diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..ad3efd213 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +build/** +.gradle/** +**/target/** +.idea/** +*.iml + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..0763946f8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing to Eclipse ORB + +Thanks for your interest in this project. + +## Project description + +Eclipse ORB is a runtime component that can be used for distributed computing +using IIOP communication. + +* https://projects.eclipse.org/projects/ee4j.orb + +## Developer resources + +Information regarding source code management, builds, coding standards, and +more. + +* https://projects.eclipse.org/projects/ee4j.orb/developer + +The project maintains the following source code repositories + +* https://github.com/eclipse-ee4j/orb +* https://github.com/eclipse-ee4j/orb-gmbal +* https://github.com/eclipse-ee4j/orb-gmbal-commons +* https://github.com/eclipse-ee4j/orb-gmbal-pfl + +## Eclipse Contributor Agreement + +Before your contribution can be accepted by the project team contributors must +electronically sign the Eclipse Contributor Agreement (ECA). + +* http://www.eclipse.org/legal/ECA.php + +Commits that are provided by non-committers must have a Signed-off-by field in +the footer indicating that the author is aware of the terms by which the +contribution has been provided to the project. The non-committer must +additionally have an Eclipse Foundation account and must have a signed Eclipse +Contributor Agreement (ECA) on file. + +For more information, please see the Eclipse Committer Handbook: +https://www.eclipse.org/projects/handbook/#resources-commit + +## Contact + +Contact the project developers via the project's "dev" list. + +* https://accounts.eclipse.org/mailing-list/orb-dev + diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..7a42c0dbf --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,29 @@ + + Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Eclipse Foundation, Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README b/README new file mode 100644 index 000000000..c284a3d85 --- /dev/null +++ b/README @@ -0,0 +1,49 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +How to build ORB .jars for delivery to GlassFish: + +--------------------------------------- +# to build and run all tests: +cd +mvn -P all-tests clean install +# +# (temporarily broken) Run dev tests with code coverage enabled. +# Cobertura code coverage report generated at: /build/cobertura/index.html +ant do-cobertura-test +# +--------------------------------------- +# to run a single test with custom arguments: +cd +mvn -Dtest.args="" install + +For example: +1. To run a specific test: +mvn -Dtest.args="-test corba.connectioncache.ConnectionCacheTest" install + +2. To debug a test, client process: +mvn -Dtest.args="-test corba.connectioncache.ConnectionCacheTest -rdebug client" install + +In the debug mode, the test waits for remote debugger to connect on the port, printed on console. The test continues once the remote debugger connects. + +3. To debug a test, server process: +mvn -Dtest.args="-test corba.cdrext.CDRExtTest -rdebug server" install + +4. Multiple remote debuggers may also be attached to client, server, and controller processes (this is not well tested): +mvn -Dtest.args=""-test corba.sometest -rdebug client:server:controller" install +--------------------------------------- + +For details, see +/make/build.xml +/make/src-build.xml + +Generated Bundles: /build/rename/ee/build/release/lib/bundles-archive.zip + + diff --git a/README.md b/README.md new file mode 100644 index 000000000..f3ddaa238 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# Glassfish CORBA ORB + +This is the [glassfish-corba project](https://javaee.github.io/glassfish-corba/). + +## Releasing + +* Make sure `gpg-agent` is running. +* Execute `mvn -B release:prepare release:perform` + +For publishing the site do the following: + +``` +cd target/checkout +mvn verify site site:stage scm-publish:publish-scm +``` diff --git a/csiv2-idl/pom.xml b/csiv2-idl/pom.xml new file mode 100644 index 000000000..360e92d2e --- /dev/null +++ b/csiv2-idl/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + glassfish-corba-csiv2-idl + Generated CSIv2 APIs + bundle + + + + + org.codehaus.mojo + idlj-maven-plugin + + + ../omgapi/src/main/idl + ../omgapi/src/main/idl-includes + + + + + CSI com.sun.corba.ee.org.omg + CSIIOP com.sun.corba.ee.org.omg + GSSUP com.sun.corba.ee.org.omg + IOP org.omg + + + + + + + org.apache.felix + maven-bundle-plugin + + + com.sun.corba.ee.org.omg.* + + + + + + diff --git a/csiv2-idl/src/main/idl/CSI.idl b/csiv2-idl/src/main/idl/CSI.idl new file mode 100644 index 000000000..1871f197a --- /dev/null +++ b/csiv2-idl/src/main/idl/CSI.idl @@ -0,0 +1,212 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _CSI_IDL_ +#define _CSI_IDL_ + +#pragma prefix "omg.org" + +module CSI { + + // The OMG VMCID; same value as CORBA::OMGVMCID. Do not change ever. + + const unsigned long OMGVMCID = 0x4F4D0; + + // An X509CertificateChain contains an ASN.1 BER encoded SEQUENCE + // [1..MAX] OF X.509 certificates encapsulated in a sequence of octets. The + // subject's certificate shall come first in the list. Each following + // certificate shall directly certify the one preceding it. The ASN.1 + // representation of Certificate is as defined in [IETF RFC 2459]. + + typedef sequence X509CertificateChain; + + // an X.501 type name or Distinguished Name encapsulated in a sequence of + // octets containing the ASN.1 encoding. + + typedef sequence X501DistinguishedName; + + // UTF-8 Encoding of String + + typedef sequence UTF8String; + + // ASN.1 Encoding of an OBJECT IDENTIFIER + + typedef sequence OID; + + typedef sequence OIDList; + + // A sequence of octets containing a GSStoken. Initial context tokens are + // ASN.1 encoded as defined in [IETF RFC 2743] Section 3.1, + // "Mechanism-Independent token Format", pp. 81-82. Initial context tokens + // contain an ASN.1 tag followed by a token length, a mechanism identifier, + // and a mechanism-specific token (i.e. a GSSUP::InitialContextToken). The + // encoding of all other GSS tokens (e.g. error tokens and final context + // tokens) is mechanism dependent. + + typedef sequence GSSToken; + + // An encoding of a GSS Mechanism-Independent Exported Name Object as + // defined in [IETF RFC 2743] Section 3.2, "GSS Mechanism-Independent + // Exported Name Object Format," p. 84. + + typedef sequence GSS_NT_ExportedName; + + typedef sequence GSS_NT_ExportedNameList; + + // The MsgType enumeration defines the complete set of service context + // message types used by the CSI context management protocols, including + // those message types pertaining only to the stateful application of the + // protocols (to insure proper alignment of the identifiers between + // stateless and stateful implementations). Specifically, the + // MTMessageInContext is not sent by stateless clients (although it may + // be received by stateless targets). + + typedef short MsgType; + + const MsgType MTEstablishContext = 0; + const MsgType MTCompleteEstablishContext = 1; + const MsgType MTContextError = 4; + const MsgType MTMessageInContext = 5; + + // The ContextId type is used carry session identifiers. A stateless + // application of the service context protocol is indicated by a session + // identifier value of 0. + + typedef unsigned long long ContextId; + + // The AuthorizationElementType defines the contents and encoding of + // the_element field of the AuthorizationElement. + + // The high order 20-bits of each AuthorizationElementType constant + // shall contain the Vendor Minor Codeset ID (VMCID) of the + // organization that defined the element type. The low order 12 bits + // shall contain the organization-scoped element type identifier. The + // high-order 20 bits of all element types defined by the OMG shall + // contain the VMCID allocated to the OMG (that is, 0x4F4D0). + + typedef unsigned long AuthorizationElementType; + + // An AuthorizationElementType of X509AttributeCertChain indicates that + // the_element field of the AuthorizationElement contains an ASN.1 BER + // SEQUENCE composed of an (X.509) AttributeCertificate followed by a + // SEQUENCE OF (X.509) Certificate. The two-part SEQUENCE is encapsulated + // in an octet stream. The chain of identity certificates is provided + // to certify the attribute certificate. Each certificate in the chain + // shall directly certify the one preceding it. The first certificate + // in the chain shall certify the attribute certificate. The ASN.1 + // representation of (X.509) Certificate is as defined in [IETF RFC 2459]. + // The ASN.1 representation of (X.509) AtributeCertificate is as defined + // in [IETF ID PKIXAC]. + + const AuthorizationElementType X509AttributeCertChain = OMGVMCID | 1; + + typedef sequence AuthorizationElementContents; + + // The AuthorizationElement contains one element of an authorization token. + // Each element of an authorization token is logically a PAC. + + struct AuthorizationElement { + AuthorizationElementType the_type; + AuthorizationElementContents the_element; + }; + + // The AuthorizationToken is made up of a sequence of + // AuthorizationElements + + typedef sequence AuthorizationToken; + + typedef unsigned long IdentityTokenType; + + // Additional standard identity token types shall only be defined by the + // OMG. All IdentityTokenType constants shall be a power of 2. + + const IdentityTokenType ITTAbsent = 0; + const IdentityTokenType ITTAnonymous = 1; + const IdentityTokenType ITTPrincipalName = 2; + const IdentityTokenType ITTX509CertChain = 4; + const IdentityTokenType ITTDistinguishedName = 8; + + typedef sequence IdentityExtension; + + union IdentityToken switch ( IdentityTokenType ) { + case ITTAbsent: boolean absent; + case ITTAnonymous: boolean anonymous; + case ITTPrincipalName: GSS_NT_ExportedName principal_name; + case ITTX509CertChain: X509CertificateChain certificate_chain; + case ITTDistinguishedName: X501DistinguishedName dn; + default: IdentityExtension id; + }; + + struct EstablishContext { + ContextId client_context_id; + AuthorizationToken authorization_token; + IdentityToken identity_token; + GSSToken client_authentication_token; + }; + + struct CompleteEstablishContext { + ContextId client_context_id; + boolean context_stateful; + GSSToken final_context_token; + }; + + struct ContextError { + ContextId client_context_id; + long major_status; + long minor_status; + GSSToken error_token; + }; + + // Not sent by stateless clients. If received by a stateless server, a + // ContextError message should be returned, indicating the session does + // not exist. + + struct MessageInContext { + ContextId client_context_id; + boolean discard_context; + }; + + union SASContextBody switch ( MsgType ) { + case MTEstablishContext: EstablishContext establish_msg; + case MTCompleteEstablishContext: CompleteEstablishContext complete_msg; + case MTContextError: ContextError error_msg; + case MTMessageInContext: MessageInContext in_context_msg; + }; + + // The following type represents the string representation of an ASN.1 + // OBJECT IDENTIFIER (OID). OIDs are represented by the string "oid:" + // followed by the integer base 10 representation of the OID separated + // by dots. For example, the OID corresponding to the OMG is represented + // as: "oid:2.23.130" + + typedef string StringOID; + + // The GSS Object Identifier for the KRB5 mechanism is: + // { iso(1) member-body(2) United States(840) mit(113554) infosys(1) + // gssapi(2) krb5(2) } + + const StringOID KRB5MechOID = "oid:1.2.840.113554.1.2.2"; + + // The GSS Object Identifier for name objects of the Mechanism-idependent + // Exported Name Object type is: + // { iso(1) org(3) dod(6) internet(1) security(5) nametypes(6) + // gss-api-exported-name(4) } + + const StringOID GSS_NT_Export_Name_OID = "oid:1.3.6.1.5.6.4"; + + // The GSS Object Identifier for the scoped-username name form is: + // { iso-itu-t (2) international-organization (23) omg (130) security (1) + // naming (2) scoped-username(1) } + + const StringOID GSS_NT_Scoped_Username_OID = "oid:2.23.130.1.2.1"; + +}; // CSI + +#endif diff --git a/csiv2-idl/src/main/idl/CSIIOP.idl b/csiv2-idl/src/main/idl/CSIIOP.idl new file mode 100644 index 000000000..11afa181d --- /dev/null +++ b/csiv2-idl/src/main/idl/CSIIOP.idl @@ -0,0 +1,145 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _CSIIOP_IDL_ +#define _CSIIOP_IDL_ +#include +#include + +#pragma prefix "omg.org" + +module CSIIOP { + + const IOP::ComponentId TAG_NULL_TAG = 34; + const IOP::ComponentId TAG_CSI_SEC_MECH_LIST = 33; + + // Association options + + typedef unsigned short AssociationOptions; + + const AssociationOptions NoProtection = 1; + const AssociationOptions Integrity = 2; + const AssociationOptions Confidentiality = 4; + const AssociationOptions DetectReplay = 8; + const AssociationOptions DetectMisordering = 16; + const AssociationOptions EstablishTrustInTarget = 32; + const AssociationOptions EstablishTrustInClient = 64; + const AssociationOptions NoDelegation = 128; + const AssociationOptions SimpleDelegation = 256; + const AssociationOptions CompositeDelegation = 512; + const AssociationOptions IdentityAssertion = 1024; + const AssociationOptions DelegationByClient = 2048; + + // The high order 20-bits of each ServiceConfigurationSyntax constant + // shall contain the Vendor Minor Codeset ID (VMCID) of the + // organization that defined the syntax. The low order 12 bits shall + // contain the organization-scoped syntax identifier. The high-order 20 + // bits of all syntaxes defined by the OMG shall contain the VMCID + // allocated to the OMG (that is, 0x4F4D0). + + typedef unsigned long ServiceConfigurationSyntax; + + const ServiceConfigurationSyntax SCS_GeneralNames = CSI::OMGVMCID | 0; + const ServiceConfigurationSyntax SCS_GSSExportedName = CSI::OMGVMCID | 1; + + typedef sequence ServiceSpecificName; + + // The name field of the ServiceConfiguration structure identifies a + // privilege authority in the format identified in the syntax field. If the + // syntax is SCS_GeneralNames, the name field contains an ASN.1 (BER) + // SEQUENCE [1..MAX] OF GeneralName, as defined by the type GeneralNames in + // [IETF RFC 2459]. If the syntax is SCS_GSSExportedName, the name field + // contains a GSS exported name encoded according to the rules in + // [IETF RFC 2743] Section 3.2, "Mechanism-Independent Exported Name + // Object Format," p. 84. + + struct ServiceConfiguration { + ServiceConfigurationSyntax syntax; + ServiceSpecificName name; + }; + + typedef sequence ServiceConfigurationList; + + // The body of the TAG_NULL_TAG component is a sequence of octets of + // length 0. + + // type used to define AS layer functionality within a compound mechanism + // definition + + struct AS_ContextSec { + AssociationOptions target_supports; + AssociationOptions target_requires; + CSI::OID client_authentication_mech; + CSI::GSS_NT_ExportedName target_name; + }; + + // type used to define SAS layer functionality within a compound mechanism + // definition + + struct SAS_ContextSec { + AssociationOptions target_supports; + AssociationOptions target_requires; + ServiceConfigurationList privilege_authorities; + CSI::OIDList supported_naming_mechanisms; + CSI::IdentityTokenType supported_identity_types; + }; + + // type used in the body of a TAG_CSI_SEC_MECH_LIST component to + // describe a compound mechanism + + struct CompoundSecMech { + AssociationOptions target_requires; + IOP::TaggedComponent transport_mech; + AS_ContextSec as_context_mech; + SAS_ContextSec sas_context_mech; + }; + + typedef sequence CompoundSecMechanisms; + + // type corresponding to the body of a TAG_CSI_SEC_MECH_LIST + // component + + struct CompoundSecMechList { + boolean stateful; + CompoundSecMechanisms mechanism_list; + }; + + struct TransportAddress { + string host_name; + unsigned short port; + }; + + typedef sequence TransportAddressList; + + // Tagged component for configuring SECIOP as a CSIv2 transport mechanism + + const IOP::ComponentId TAG_SECIOP_SEC_TRANS = 35; + + struct SECIOP_SEC_TRANS { + AssociationOptions target_supports; + AssociationOptions target_requires; + CSI::OID mech_oid; + CSI::GSS_NT_ExportedName target_name; + TransportAddressList addresses; + }; + + // tagged component for configuring TLS/SSL as a CSIv2 transport mechanism + + const IOP::ComponentId TAG_TLS_SEC_TRANS = 36; + + struct TLS_SEC_TRANS { + AssociationOptions target_supports; + AssociationOptions target_requires; + TransportAddressList addresses; + }; + +}; //CSIIOP + +#endif diff --git a/csiv2-idl/src/main/idl/GSSUP.idl b/csiv2-idl/src/main/idl/GSSUP.idl new file mode 100644 index 000000000..90de23d9e --- /dev/null +++ b/csiv2-idl/src/main/idl/GSSUP.idl @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _GSSUP_IDL_ +#define _GSSUP_IDL_ +#include + +#pragma prefix "omg.org" + +module GSSUP { + + // The GSS Object Identifier allocated for the + // username/password mechanism is defined below. + // + // { iso-itu-t (2) international-organization (23) omg (130) + // security (1) authentication (1) gssup-mechanism (1) } + + const CSI::StringOID GSSUPMechOID = "oid:2.23.130.1.1.1"; + + // The following structure defines the inner contents of the + // username password initial context token. This structure is + // CDR encapsulated and appended at the end of the + // username/password GSS (initial context) Token. + + struct InitialContextToken { + CSI::UTF8String username; + CSI::UTF8String password; + CSI::GSS_NT_ExportedName target_name; + }; + + typedef unsigned long ErrorCode; + + // GSSUP Mechanism-Specific Error Token + struct ErrorToken { + ErrorCode error_code; + }; + + // The context validator has chosen not to reveal the GSSUP + // specific cause of the failure. + const ErrorCode GSS_UP_S_G_UNSPECIFIED = 1; + + // The user identified in the username field of the + // GSSUP::InitialContextToken is unknown to the target. + const ErrorCode GSS_UP_S_G_NOUSER = 2; + + // The password supplied in the GSSUP::InitialContextToken was + // incorrect. + const ErrorCode GSS_UP_S_G_BAD_PASSWORD = 3; + + // The target_name supplied in the GSSUP::InitialContextToken does + // not match a target_name in a mechanism definition of the target. + const ErrorCode GSS_UP_S_G_BAD_TARGET = 4; + +}; // GSSUP + +#endif diff --git a/exception-annotation-processor/pom.xml b/exception-annotation-processor/pom.xml new file mode 100644 index 000000000..90dbdbd7a --- /dev/null +++ b/exception-annotation-processor/pom.xml @@ -0,0 +1,54 @@ + + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + exception-annotation-processor + Exception Annotation Processor + + + + org.glassfish.pfl + pfl-basic + ${pfl-version} + + + junit + junit + test + + + com.meterware.simplestub + simplestub + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + -proc:none + + + + + + diff --git a/exception-annotation-processor/src/main/java/org/glassfish/corba/annotation/processing/ExceptionWrapperProcessor.java b/exception-annotation-processor/src/main/java/org/glassfish/corba/annotation/processing/ExceptionWrapperProcessor.java new file mode 100644 index 000000000..99468c21a --- /dev/null +++ b/exception-annotation-processor/src/main/java/org/glassfish/corba/annotation/processing/ExceptionWrapperProcessor.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba.annotation.processing; + +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Message; + +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import java.io.IOException; +import java.util.*; + +/** + * This class creates properties files for annotated exception interfaces. Applicable interfaces are annotated with the + * {@link ExceptionWrapper} annotation. An entry will be made for each method with a {@link Message} annotation. + */ +@SupportedAnnotationTypes({"org.glassfish.pfl.basic.logex.ExceptionWrapper", "org.glassfish.pfl.basic.logex.Message"}) +@SupportedSourceVersion(SourceVersion.RELEASE_6) +public class ExceptionWrapperProcessor extends AbstractProcessor { + + Map annotatedClasses = new HashMap(); + Date creationDate = new Date(); + + @Override + public boolean process(Set typeElements, RoundEnvironment roundEnvironment) { + if (roundEnvironment.processingOver()) return false; + if (typeElements.isEmpty()) return false; + + processClassElements(roundEnvironment.getElementsAnnotatedWith(ExceptionWrapper.class)); + processMethodElements(roundEnvironment.getElementsAnnotatedWith(Message.class)); + + for (FileGenerator generator : annotatedClasses.values()) + writeFile(generator); + return true; + } + + private void writeFile(FileGenerator generator) { + try { + if (generator.shouldWriteFile()) + generator.writeFile(processingEnv.getFiler()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void processClassElements(Set classElements) { + for (Element classElement : classElements) + annotatedClasses.put(classElement,new FileGenerator(classElement, creationDate)); + } + + private void processMethodElements(Set methodElements) { + for (Element methodElement : methodElements) + if (annotatedClasses.containsKey(methodElement.getEnclosingElement())) + annotatedClasses.get(methodElement.getEnclosingElement()).addMethod(methodElement); + } + +} diff --git a/exception-annotation-processor/src/main/java/org/glassfish/corba/annotation/processing/FileGenerator.java b/exception-annotation-processor/src/main/java/org/glassfish/corba/annotation/processing/FileGenerator.java new file mode 100644 index 000000000..1015f653a --- /dev/null +++ b/exception-annotation-processor/src/main/java/org/glassfish/corba/annotation/processing/FileGenerator.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba.annotation.processing; + +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Message; + +import javax.annotation.processing.Filer; +import javax.lang.model.element.Element; +import javax.tools.FileObject; +import javax.tools.StandardLocation; +import java.io.IOException; +import java.io.Writer; +import java.util.Date; +import java.util.ArrayList; +import java.util.List; + +/** +* This class generates properties files based on annotations. +*/ +class FileGenerator { + private Element classElement; + private Date creationDate; + private List methodElements = new ArrayList(); + + FileGenerator(Element classElement, Date creationDate) { + this.classElement = classElement; + this.creationDate = creationDate; + } + + String getPrefix() { + ExceptionWrapper wrapper = classElement.getAnnotation(ExceptionWrapper.class); + return wrapper.idPrefix(); + } + + FileObject createResource(Filer filer) throws IOException { + return filer.createResource(StandardLocation.CLASS_OUTPUT, getPackage(), getName() + ".properties"); + } + + void addMethod(Element methodElement) { + methodElements.add(methodElement); + } + + String getPackage() { + return classElement.getEnclosingElement().toString(); + } + + private String getName() { + return classElement.getSimpleName().toString(); + } + + boolean shouldWriteFile() { + return !methodElements.isEmpty(); + } + + void writePropertyFileHeader(Writer writer) throws IOException { + writer.append("### Resource file generated on ").append(creationDate.toString()).append('\n'); + writer.append("#\n"); + writer.append("# Resources for class ").append(classElement.toString()).append('\n'); + writer.append("#\n"); + } + + void writePropertyLines(Writer writer) throws IOException { + for (Element methodElement : methodElements) + writePropertyLine(writer, methodElement); + } + + private void writePropertyLine(Writer writer, Element methodElement) throws IOException { + writer.append('.').append(methodElement.getSimpleName()).append("=\"").append(getPrefix()) + .append(": ").append(getMessage(methodElement)).append("\"\n"); + } + + private String getMessage(Element methodElement) { + return methodElement.getAnnotation(Message.class).value(); + } + + void writeContents(Writer writer) throws IOException { + writePropertyFileHeader(writer); + writePropertyLines(writer); + writer.close(); + } + + void writeFile(Filer filer) throws IOException { + FileObject file = createResource(filer); + writeContents(file.openWriter()); + } +} diff --git a/exception-annotation-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/exception-annotation-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor new file mode 100644 index 000000000..93b41176c --- /dev/null +++ b/exception-annotation-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor @@ -0,0 +1 @@ +org.glassfish.corba.annotation.processing.ExceptionWrapperProcessor diff --git a/exception-annotation-processor/src/test/java/org/glassfish/corba/annotation/processing/ExceptionWrapperProcessorTestCase.java b/exception-annotation-processor/src/test/java/org/glassfish/corba/annotation/processing/ExceptionWrapperProcessorTestCase.java new file mode 100644 index 000000000..47c7c830c --- /dev/null +++ b/exception-annotation-processor/src/test/java/org/glassfish/corba/annotation/processing/ExceptionWrapperProcessorTestCase.java @@ -0,0 +1,501 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba.annotation.processing; + +import com.meterware.simplestub.Stub; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Message; +import org.junit.Before; +import org.junit.Test; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.Name; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; +import javax.tools.FileObject; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import java.io.*; +import java.lang.annotation.Annotation; +import java.net.URI; +import java.util.*; + +import static com.meterware.simplestub.Stub.createStub; +import static org.junit.Assert.*; + +/** + * A test for the ExceptionWrapper annotation Processor. + * + * @author Russell Gold + */ +public class ExceptionWrapperProcessorTestCase { + + private TestRoundEnvironment roundEnvironment; + private ExceptionWrapperProcessor processor; + private List files = new ArrayList(); + private Set typeElements; + private FileGenerator fileGenerator; + private Date creationDate = new Date(); + private TestElement annotatedClassElement; + private Map,Set> annotations = new HashMap, Set>(); + + @Before + public void setUp() throws Exception { + roundEnvironment = new TestRoundEnvironment(); + processor = new ExceptionWrapperProcessor(); + processor.init(new TestProcessingEnvironment()); + typeElements = new HashSet(); + annotatedClassElement = createAnnotatedClass("org.glassfish.corba.AnException", "SF"); + fileGenerator = new FileGenerator(annotatedClassElement, creationDate); + } + + @Test + public void processor_supportsExceptionWrapperAnnotation() { + SupportedAnnotationTypes annotation = ExceptionWrapperProcessor.class.getAnnotation(SupportedAnnotationTypes.class); + assertTrue(Arrays.asList(annotation.value()).contains(ExceptionWrapper.class.getName())); + } + + @Test + public void processor_supportsMessageAnnotation() { + SupportedAnnotationTypes annotation = ExceptionWrapperProcessor.class.getAnnotation(SupportedAnnotationTypes.class); + assertTrue(Arrays.asList(annotation.value()).contains(Message.class.getName())); + } + + @Test + public void process_supportsSourceVersion6() { + SupportedSourceVersion annotation = ExceptionWrapperProcessor.class.getAnnotation(SupportedSourceVersion.class); + assertEquals(SourceVersion.RELEASE_6, annotation.value()); + } + + @Test + public void processor_extendsAbstractProcessor() { + Class superclass = ExceptionWrapperProcessor.class.getSuperclass(); + assertEquals(AbstractProcessor.class, superclass); + } + + @Test + public void processer_isRegistered() throws IOException { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream("META-INF/services/javax.annotation.processing.Processor"); + assertNotNull("Resource not found in classpath",inputStream); + InputStreamReader isr = new InputStreamReader(inputStream); + BufferedReader reader = new BufferedReader(isr); + assertEquals(ExceptionWrapperProcessor.class.getName(), reader.readLine()); + } + + @Test + public void whenNoExceptionWrapperAnnotations_doNothing() { + assertFalse(processor.process(typeElements, roundEnvironment)); + assertTrue(files.isEmpty()); + } + + @Test + public void whenProcessingIsComplete_doNothing() { + declareProcessingOver(); + assertFalse(processor.process(typeElements, roundEnvironment)); + assertTrue(files.isEmpty()); + } + + @Test + public void givenAnnotationElement_canExtractPrefix() { + assertEquals("SF", fileGenerator.getPrefix()); + } + + @Test + public void givenAnnotationElement_canExtractPackage() { + assertEquals("org.glassfish.corba", fileGenerator.getPackage()); + } + + @Test + public void givenAnnotationElement_canCreateFileObject() throws IOException { + FileObject fileObject = fileGenerator.createResource(new TestFiler()); + assertEquals(asUnixPath("file:" + System.getProperty("user.dir") + "/CLASS_OUTPUT/org/glassfish/corba/AnException.properties"), + asUnixPath(fileObject.toUri().toString())); + } + + private String asUnixPath( String path ) { + String result = path.replace('\\', '/'); + if (result.startsWith("file:/C:")) result = "file:C:" + result.substring(8); + return result; + } + + private TestElement createAnnotatedClass(String className, String prefix) { + TestElement classElement = createElement(className); + ExceptionWrapper ew = new TestExceptionWrapper(prefix); + classElement.addAnnotation(ew); + getAnnotatedElements(ExceptionWrapper.class).add(classElement); + return classElement; + } + + private Set getAnnotatedElements(Class annotationClass) { + if (annotations.containsKey(annotationClass)) + return annotations.get(annotationClass); + else + return createAnnotatedElementsSet(annotationClass); + } + + private Set createAnnotatedElementsSet(Class annotationClass) { + Set set = new HashSet(); + annotations.put(annotationClass, set); + return set; + } + + + @Test + public void withoutMethods_generatorWillNotRun() { + assertFalse( fileGenerator.shouldWriteFile()); + } + + @Test + public void withMethods_generatorWillRun() { + fileGenerator.addMethod(createAnnotatedMethod("method1", "log message 1")); + assertTrue( fileGenerator.shouldWriteFile()); + } + + @Test + public void givenAnnotatedMethod_canGenerateProperties() throws IOException { + fileGenerator.addMethod(createAnnotatedMethod("method1", "log message 1")); + fileGenerator.addMethod(createAnnotatedMethod("method2", "log message 2")); + + StringWriter writer = new StringWriter(); + fileGenerator.writePropertyLines(writer); + writer.close(); + assertEquals(".method1=\"SF: log message 1\"\n.method2=\"SF: log message 2\"\n", writer.toString()); + } + + @Test + public void generator_canCreateHeader() throws IOException { + StringWriter writer = new StringWriter(); + fileGenerator.writePropertyFileHeader( writer ); + writer.close(); + + assertEquals("### Resource file generated on " + creationDate + "\n" + + "#\n" + + "# Resources for class org.glassfish.corba.AnException\n" + + "#\n", + writer.toString() ); + } + + private TestElement createAnnotatedMethod(String methodName, String message) { + TestElement methodElement = createStub(TestElement.class, methodName, annotatedClassElement); + org.glassfish.pfl.basic.logex.Message annotation = new TestMessage(message); + methodElement.addAnnotation(annotation); + getAnnotatedElements(Message.class).add(methodElement); + return methodElement; + } + + @Test + public void whenOneClassAnnotated_createFile() { + populateTypeElements(); + fileGenerator.addMethod(createAnnotatedMethod("method1", "log message 1")); + assertTrue(processor.process(typeElements, roundEnvironment)); + assertFalse(files.isEmpty()); + } + + private void populateTypeElements() { + addToTypeElements(ExceptionWrapper.class); + addToTypeElements(Message.class); + } + + private void addToTypeElements(Class annotationClass) { + typeElements.add(createElement(annotationClass.getName())); + } + + private static TestElement createElement(String fullName) { + TestElement leaf = null; + for (String component : fullName.split("\\.")) { + leaf = Stub.createStub(TestElement.class, component, leaf); + } + return leaf; + } + + private void declareProcessingOver() { + roundEnvironment.processingOver = true; + } + + class TestRoundEnvironment implements RoundEnvironment { + boolean processingOver; + + public boolean processingOver() { + return processingOver; + } + + public boolean errorRaised() { return false; } + public Set getRootElements() { return null; } + + @Override + public Set getElementsAnnotatedWith(TypeElement typeElement) { + return null; + } + + @Override + public Set getElementsAnnotatedWith(Class aClass) { + return annotations.get(aClass); + } + } + + static class TestExceptionWrapper implements ExceptionWrapper { + private String idPrefix; + + TestExceptionWrapper(String idPrefix) { + this.idPrefix = idPrefix; + } + + public String idPrefix() { + return idPrefix; + } + + public String loggerName() { + return ""; + } + + public String resourceBundle() { + return ""; + } + + public Class annotationType() { + return ExceptionWrapper.class; + } + } + + private class TestMessage implements Message { + private String value; + + public TestMessage(String value) { + this.value = value; + } + + public String value() { + return value; + } + + @Override + public Class annotationType() { + return Message.class; + } + } + + class TestProcessingEnvironment implements ProcessingEnvironment { + + private TestFiler filer; + + @Override + public Map getOptions() { + return null; + } + + @Override + public Messager getMessager() { + return null; + } + + @Override + public Filer getFiler() { + if (filer == null) filer = new TestFiler(); + return filer; + } + + @Override + public Elements getElementUtils() { + return null; + } + + @Override + public Types getTypeUtils() { + return null; + } + + @Override + public SourceVersion getSourceVersion() { + return null; + } + + @Override + public Locale getLocale() { + return null; + } + + + } + + class TestFiler implements Filer { + + @Override + public JavaFileObject createSourceFile(CharSequence charSequence, Element... elements) throws IOException { + return null; + } + + @Override + public JavaFileObject createClassFile(CharSequence charSequence, Element... elements) throws IOException { + return null; + } + + @Override + public FileObject createResource(JavaFileManager.Location location, CharSequence pkg, CharSequence trailing, Element... elements) throws IOException { + File file = new File(location.getName()); + file = new File(file, pkg.toString().replace('.','/')); + file = new File(file, trailing.toString()); + TestFileObject testFileObject = new TestFileObject(file.toURI()); + files.add(testFileObject); + return testFileObject; + } + + @Override + public FileObject getResource(JavaFileManager.Location location, CharSequence charSequence, CharSequence charSequence1) throws IOException { + return null; + } + + + } + + class TestFileObject implements FileObject { + + private URI uri; + + + TestFileObject(URI uri) { + this.uri = uri; + } + + @Override + public URI toUri() { + return uri; + } + + @Override + public String getName() { + return null; + } + + @Override + public InputStream openInputStream() throws IOException { + return null; + } + + @Override + public OutputStream openOutputStream() throws IOException { + return null; + } + + @Override + public Reader openReader(boolean b) throws IOException { + return null; + } + + @Override + public CharSequence getCharContent(boolean b) throws IOException { + return null; + } + + @Override + public Writer openWriter() throws IOException { + return new StringWriter(); + } + + @Override + public long getLastModified() { + return 0; + } + + @Override + public boolean delete() { + return false; + } + + + } + + abstract static class TestElement implements TypeElement { + private Element enclosingElement; + private Name simpleName; + + private List annotations = new ArrayList(); + + TestElement(String component, Element enclosingElement) { + simpleName = new TestName(component); + this.enclosingElement = enclosingElement; + } + + void addAnnotation(Annotation annotation) { + annotations.add(annotation); + } + + public A getAnnotation(Class aClass) { + for (Annotation annotation : annotations) + if (aClass.isInstance(annotation)) return castTo(annotation); + return null; + } + + @SuppressWarnings("unchecked") + private A castTo(Annotation annotation) { + return (A) annotation; + } + + public Name getSimpleName() { + return simpleName; + } + + public Element getEnclosingElement() { + return enclosingElement; + } + + @Override + public String toString() { + return enclosingElement == null ? simpleName.toString() + : enclosingElement + "." + simpleName; + } + + + } + + static class TestName implements Name { + + private CharSequence value; + + TestName(CharSequence value) { + this.value = value; + } + + @Override + public boolean contentEquals(CharSequence charSequence) { + return value.equals(charSequence); + } + + @Override + public int length() { + return value.length(); + } + + @Override + public char charAt(int i) { + return value.charAt(i); + } + + @Override + public CharSequence subSequence(int start, int end) { + return value.subSequence(start, end); + } + + @Override + public String toString() { + return value.toString(); + } + + } +} diff --git a/functional-tests/README b/functional-tests/README new file mode 100644 index 000000000..221befdc3 --- /dev/null +++ b/functional-tests/README @@ -0,0 +1,2 @@ +Note: the functional tests are old, and have not been maintained in years. They use a combination of test frameworks, including some home-grown; don't pass reliably, and do not run with Java 9 and later. +They are retained here to be run as an occasional reality check, and most should pass with Java 8. \ No newline at end of file diff --git a/functional-tests/pom.xml b/functional-tests/pom.xml new file mode 100644 index 000000000..821fbd1af --- /dev/null +++ b/functional-tests/pom.xml @@ -0,0 +1,331 @@ + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + glassfish-corba-tests + Functional Tests + pom + + + + org.glassfish.gmbal + gmbal + ${gmbal-version} + + + ${project.groupId} + glassfish-corba-csiv2-idl + ${project.version} + + + ${project.groupId} + glassfish-corba-omgapi + ${project.version} + + + ${project.groupId} + glassfish-corba-orb + ${project.version} + + + org.glassfish.pfl + pfl-basic + ${pfl-version} + + + org.glassfish.pfl + pfl-basic-tools + ${pfl-version} + + + org.glassfish.pfl + pfl-dynamic + ${pfl-version} + + + org.glassfish.pfl + pfl-tf + ${pfl-version} + test + + + org.glassfish.pfl + pfl-tf-tools + ${pfl-version} + test + + + org.glassfish.pfl + pfl-test + ${pfl-version} + test + + + org.glassfish.external + management-api + 3.1.0-b001 + test + + + org.testng + testng + 6.10 + test + + + + + + + + org.codehaus.mojo + idlj-maven-plugin + + + + generate-test + + + + + + ../omgapi/src/main/idl + ../omgapi/src/main/idl-includes + + + + true + + legacy/**/*.idl + + + activationcom.sun.corba.ee.spi + + + + + IOP org.omg + Messaging org.omg + PortableServer org.omg + PortableInterceptororg.omg + + false + + + CORBA3 + + + + -corba + 3.0 + + + legacy/** + + + + + + + + + org.codehaus.mojo + rmic-maven-plugin + + ${project.build.testOutputDirectory} + + + true + true + true + + **/rmiiIServantPOA.class + **/corba/preinvokepostinvoke/MyServant.class + **/corba/rmipoacounter/counterImpl.class + + + + true + true + + **/rmiiIServant.class + + + + + + + org.glassfish.corba + rmic + ${project.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + testCompile + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + run-tests + integration-test + + + + + + + + + + + run + + + + + + + + + + + + tools.jar + + + ${java.home}/../lib/tools.jar + + + + + com.sun + tools + 1.6.0 + system + ${java.home}/../lib/tools.jar + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + com.sun + tools + 1.6.0 + system + ${java.home}/../lib/tools.jar + + + + + + + + + all-tests + + + + org.apache.maven.plugins + maven-antrun-plugin + + + run-tests + integration-test + + + + + + + + + + + + + + + + run + + + + + + + + + + + test-with-args + + + test.args + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + run-tests + integration-test + + + + + + + + + + + + run + + + + + + + + + + diff --git a/functional-tests/src/test/idl/adapteractivator.idl b/functional-tests/src/test/idl/adapteractivator.idl new file mode 100644 index 000000000..1d39e512a --- /dev/null +++ b/functional-tests/src/test/idl/adapteractivator.idl @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba { + module adapteractivator{ + interface Hello { + string sayHello(); + }; + + interface Close { + oneway void shutdown(); + }; + }; //adapteractivator +}; // corba + + diff --git a/functional-tests/src/test/idl/clientinterceptor.idl b/functional-tests/src/test/idl/clientinterceptor.idl new file mode 100644 index 000000000..b9f55a218 --- /dev/null +++ b/functional-tests/src/test/idl/clientinterceptor.idl @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module ClientRequestInterceptor +{ + interface hello + { + string sayHello(); + string saySystemException(); + oneway void sayOneway(); + void clearInvoked(); + boolean wasInvoked(); + void resetServant(); + }; +}; + diff --git a/functional-tests/src/test/idl/clientrequestinfo.idl b/functional-tests/src/test/idl/clientrequestinfo.idl new file mode 100644 index 000000000..8ec7ef56f --- /dev/null +++ b/functional-tests/src/test/idl/clientrequestinfo.idl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module ClientRequestInfo +{ + exception ExampleException { string reason; }; + + interface hello + { + string sayHello(); + string saySystemException(); + void sayUserException() raises (ExampleException); + oneway void sayOneway(); + string sayArguments( in string arg1, in long arg2, in boolean arg3 ); + void clearInvoked(); + boolean wasInvoked(); + void resetServant(); + }; +}; + diff --git a/functional-tests/src/test/idl/codec.idl b/functional-tests/src/test/idl/codec.idl new file mode 100644 index 000000000..c0e2c868b --- /dev/null +++ b/functional-tests/src/test/idl/codec.idl @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module CodecTest +{ + struct TestStruct { + short x; + short y; + }; + + union TestUnion switch (short) { + case 1: double d; + case 2: float f; + }; + +}; + diff --git a/functional-tests/src/test/idl/codeset.idl b/functional-tests/src/test/idl/codeset.idl new file mode 100644 index 000000000..8dd161d59 --- /dev/null +++ b/functional-tests/src/test/idl/codeset.idl @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module CodeSetTester +{ + custom valuetype CustomMarshaledValue { + public char ch; + public wchar wch; + public string str; + public wstring wstr; + public sequence chSeq; + public sequence wchSeq; + }; + + interface Verifier { + char verifyChar(in char ch); + wchar verifyWChar(in wchar wch); + string verifyString(in string str); + wstring verifyWString(in wstring wstr); + + typedef sequence TestCharSeq; + typedef sequence TestWCharSeq; + + void verifyCharSeq(inout TestCharSeq chSeq); + void verifyWCharSeq(inout TestWCharSeq wchSeq); + + CustomMarshaledValue verifyTransmission(in CustomMarshaledValue cv); + }; +}; diff --git a/functional-tests/src/test/idl/corba/connectintercept_1_4/Ex.idl b/functional-tests/src/test/idl/corba/connectintercept_1_4/Ex.idl new file mode 100644 index 000000000..7918cbec6 --- /dev/null +++ b/functional-tests/src/test/idl/corba/connectintercept_1_4/Ex.idl @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ + module connectintercept_1_4 + { + interface ExI + { + string sayHello(); + }; + }; +}; + diff --git a/functional-tests/src/test/idl/corba/exceptiondetailsc/idlI.idl b/functional-tests/src/test/idl/corba/exceptiondetailsc/idlI.idl new file mode 100644 index 000000000..f3068e834 --- /dev/null +++ b/functional-tests/src/test/idl/corba/exceptiondetailsc/idlI.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:25:44 by Harold Carr. +// + +module corba +{ + module exceptiondetailsc + { + exception idlException { string reason; }; + + interface idlI + { + void raise_system_exception(in string x); + void raise_user_exception(in string x) + raises (idlException); + void raise_runtime_exception(in string x); + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/corba/folb_8_1/folb.idl b/functional-tests/src/test/idl/corba/folb_8_1/folb.idl new file mode 100644 index 000000000..9eec497f8 --- /dev/null +++ b/functional-tests/src/test/idl/corba/folb_8_1/folb.idl @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** + * @author Harold Carr + */ +module corba +{ + module folb_8_1 + { + struct TaggedCustomSocketInfo { + string type; + string host; + long port; + }; + + const unsigned long TAG_TAGGED_CUSTOM_SOCKET_INFO = 4444; + + interface I + { + boolean unregister(in string socketType); + boolean register(in string socketType); + string m(in string x); + long n(in string x); + + // This has NOTHING to do with failover. + // Just here to test the server-side stack trace shown on + // The client side. + long throwRuntimeException(in long x); + }; + + interface I2 + { + long m(in string x); + Object n(in string x); + long foo(in long x); + }; + + }; +}; + +// End of file. + + diff --git a/functional-tests/src/test/idl/corba/hcks/hcks.idl b/functional-tests/src/test/idl/corba/hcks/hcks.idl new file mode 100644 index 000000000..8101c9cb0 --- /dev/null +++ b/functional-tests/src/test/idl/corba/hcks/hcks.idl @@ -0,0 +1,163 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ +module hcks +{ + typedef sequence idlJString; + + typedef sequence IntSeq10000; + typedef octet idlOctetArray10000[10000]; + + valuetype idlIntSeqValueType IntSeq10000; + valuetype idlOctetArrayValueType idlOctetArray10000; + + exception idlExampleException { string reason; }; + /* + abstract valuetype idlAbstractValueType + { + short getShortA(); + void setShortA(in short s); + }; + */ + valuetype idlValueTypeA /*: idlAbstractValueType*/ + { + private short a; + factory init (in short a); + }; + + valuetype idlValueTypeB : truncatable idlValueTypeA + { + private short b; + factory init (in short a, in short b); + }; + + custom valuetype idlValueTypeC : truncatable idlValueTypeB + { + private short c; + factory init (in short a, in short b, in short c); + }; + + custom valuetype idlValueTypeD + { + private short d; + factory init (in short d); + }; + + valuetype idlValueTypeE + { + public IntSeq10000 intSeq; + public idlOctetArray10000 octetArray; + }; + + struct recursiveType { + string a; + string b; + sequence s; + }; + + interface idlControllerI + { + string action ( in string s ); + }; + + interface idlI + { + string syncOK ( in string arg1 ); + + idlValueTypeA sendValue (in idlValueTypeA a, + in idlValueTypeB b, + in idlValueTypeC c, + in idlValueTypeD d, + in idlValueTypeE e, + in idlIntSeqValueType f, + in idlOctetArrayValueType g); + + oneway void asyncOK (in idlJString data); + + void throwUserException () + raises (idlExampleException); + + void throwSystemException (); + + void throwUnknownException (); + + void throwUNKNOWN (); + + void raiseSystemExceptionInSendReply (); + + void testEffectiveTarget1 (); + void testEffectiveTarget2 (); + + Object getAndSaveUnknownORBVersionIOR(); + boolean isIdenticalWithSavedIOR(in Object o); + }; + + interface idlSMI + { + string makeColocatedCallFromServant ( ); + string colocatedCallFromServant ( in string a ); + }; + + interface idlSAI : idlSMI + { + string raiseForwardRequestInIncarnate ( in string a ); + string raiseObjectNotExistInIncarnate ( in string a ); + string raiseSystemExceptionInIncarnate ( in string a ); + }; + + interface idlSLI : idlSMI + { + string raiseForwardRequestInPreinvoke ( in string a ); + string raiseObjectNotExistInPreinvoke ( in string a ); + string raiseSystemExceptionInPreinvoke ( in string a ); + string raiseSystemExceptionInPostinvoke ( in string a ); + string raiseSystemInServantThenPOThenSE ( ); + string raiseUserInServantThenSystemInPOThenSE ( ) + raises (idlExampleException); + + // These test ThreadDeath handling. + + string throwThreadDeathInReceiveRequestServiceContexts + ( in string a ); + string throwThreadDeathInPreinvoke ( in string a ); + string throwThreadDeathInReceiveRequest (in string a ); + string throwThreadDeathInServant ( in string a ); + string throwThreadDeathInPostinvoke ( in string a ); + string throwThreadDeathInSendReply ( in string a ); + string throwThreadDeathInServantThenSysInPostThenSysInSendException ( in string a ); + + // These are used to test server-side PICurrent. + // The names are shorthand for s(erver)Pic(urrent). + + void sPic1(); + void sPic2(); + }; + + interface idlHEADERI + { + void HEADER ( in string message ); + }; + + interface idlAttributes + { + attribute long longAttribute; + readonly attribute short readOnlyShortAttribute; + }; + + interface sendRecursiveType { + any sendAsAny(in any x); + recursiveType sendAsType(in recursiveType x); + }; + +}; // module hcks + +}; // module corba diff --git a/functional-tests/src/test/idl/corba/islocal/idlI.idl b/functional-tests/src/test/idl/corba/islocal/idlI.idl new file mode 100644 index 000000000..4dc799773 --- /dev/null +++ b/functional-tests/src/test/idl/corba/islocal/idlI.idl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2003 Apr 18 (Fri) 15:05:19 by Harold Carr. +// + +module corba +{ + module islocal + { + interface idlI + { + string o(in string x); + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/corba/poapolicies/Hello.idl b/functional-tests/src/test/idl/corba/poapolicies/Hello.idl new file mode 100644 index 000000000..09ad65a1c --- /dev/null +++ b/functional-tests/src/test/idl/corba/poapolicies/Hello.idl @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module HelloStuff { + interface Hello { + string hi(); + }; +}; + +module Util { + enum CreationMethods { + EXPLICIT_ACTIVATION_WITH_POA_ASSIGNED_OIDS, + EXPLICIT_ACTIVATION_WITH_USER_ASSIGNED_OIDS, + CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_POA_ASSIGNED_OIDS, + CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_USER_ASSIGNED_OIDS + }; + + // A generic factory that creates servants based on the + // interface name. This can be used to test different + // interfaces which contain methods that would test the + // invocation path more extensively (example, ones that + // throw exceptions etc) + + interface Factory { + Object create(in string intfName, in string implName, in CreationMethods how); + void overAndOut(); + }; +}; diff --git a/functional-tests/src/test/idl/corba/repid/BoxedValueTypes.idl b/functional-tests/src/test/idl/corba/repid/BoxedValueTypes.idl new file mode 100644 index 000000000..63fdf9e82 --- /dev/null +++ b/functional-tests/src/test/idl/corba/repid/BoxedValueTypes.idl @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Tests nested type declarations whose type definitions are in +// inherited super interfaces. +// +module test { + interface Foo {}; + valuetype FooSeq sequence; + valuetype StringSeq sequence; +}; diff --git a/functional-tests/src/test/idl/corba/requestpartitioning/Tester.idl b/functional-tests/src/test/idl/corba/requestpartitioning/Tester.idl new file mode 100644 index 000000000..4629a5945 --- /dev/null +++ b/functional-tests/src/test/idl/corba/requestpartitioning/Tester.idl @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Define an interface to return the thread pool id where the +// implemented interface is executing. + +module corba +{ + module requestpartitioning + { + interface Tester + { + long getThreadPoolIdForThisRequest(in string x); + }; + }; +}; + +// End of file. + diff --git a/functional-tests/src/test/idl/fwddecl_legal.idl b/functional-tests/src/test/idl/fwddecl_legal.idl new file mode 100644 index 000000000..0cd23ec76 --- /dev/null +++ b/functional-tests/src/test/idl/fwddecl_legal.idl @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Required tests: +// This compiles +// We can create and manipulate instances of all of these classes +// The typecodes are correct + +module corba { + module fwddecl { + // Old style recursive definition + struct Foo { + long value ; + sequence chain ; + } ; + + interface Sample ; + + // Equivalent with forward + struct NewFoo ; + typedef sequence NewFooSeq ; + struct NewFoo { + long value ; + NewFooSeq chain ; + } ; + + // multiple level + union Bar ; + typedef sequence BarSeq ; + union Bar switch(long) { + case 0: + long l_mem ; + case 1: + struct Foo { + double d_mem ; + BarSeq nested ; + } s_mem ; + } ; + + struct MoreFoo ; + + typedef sequence MoreFooSeq ; + typedef sequence MoreFooTree ; + + struct MoreFoo { + long l_mem ; + Sample interf ; + MoreFooSeq chain ; + MoreFooTree tree ; + } ; + + interface Sample { + MoreFooSeq op1() ; + void op2( + in MoreFooTree t + ) ; + } ; + } ; +} ; diff --git a/functional-tests/src/test/idl/idlj_ConstantsAndTypedefs.idl b/functional-tests/src/test/idl/idlj_ConstantsAndTypedefs.idl new file mode 100644 index 000000000..3402819fb --- /dev/null +++ b/functional-tests/src/test/idl/idlj_ConstantsAndTypedefs.idl @@ -0,0 +1,138 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +//////////////////////////////// +// IDL file. +//////////////////////////////// + +//////////////////////// +// Constant declarations +//////////////////////// + +// boolean type + +const boolean boolean_value = TRUE; + +// octet type + +const octet octet_value = 0xFF; + +// char types + +const char char_value = '\xFF'; + +const wchar wchar_value = L'\u5ae6'; + +// string types + +const string string_value = "A""B""C"; + +const wstring wstring_value = L"\u0ae6""H""E""L""L""O"; + +// integer types + +// -(2^15) +const short short_value = -32768; + +// (2^16)-1 +const unsigned short unsigned_short_value = 65535; + +// -(2^31) +const long long_value = -2147483648; + +// (2^32)-1 +const unsigned long unsigned_long_value = 4294967295; + +// -(2^63) +const long long long_long_value = -9223372036854775808; + +// Java can't handle (2^63)+1. It will be converted to -((2^63)-1) +const unsigned long long unsigned_long_long_value = 9223372036854775809; + +// enum type + +enum Color { red, green, blue }; +union ColorCount switch (Color) { + case red : + unsigned long x; + case green : + unsigned long y; + case blue : + unsigned long z; +}; + + +////////////////////////////////////////////// +// Constant declarations with type definitions +////////////////////////////////////////////// + +// boolean type + +typedef boolean boolean_type; +const boolean_type boolean_value_t = TRUE; + +// octet type + +typedef octet octet_type; +const octet_type octet_value_t = 0xFF; + +// char types + +typedef char char_type; +const char_type char_value_t = '\xFF'; + +typedef wchar wchar_type; +const wchar_type wchar_value_t = L'\u5ae6'; + +// string types + +typedef string string_type; +const string_type string_value_t = "A""B""C"; + +typedef wstring wstring_type; +const wstring_type wstring_value_t = L"\u0ae6""H""E""L""L""O"; + +// integer types + +// -(2^15) +typedef short short_type; +const short_type short_value_t = -32768; + +// (2^16)-1 +typedef unsigned short unsigned_short_type; +const unsigned_short_type unsigned_short_value_t = 65535; + +// -(2^31) +typedef long long_type; +const long_type long_value_t = -2147483648; + +// (2^32)-1 +typedef unsigned long unsigned_long_type; +const unsigned_long_type unsigned_long_value_t = 4294967295; + +// -(2^63) +typedef long long long_long_type; +const long_long_type long_long_value_t = -9223372036854775808; + +// Java can't handle (2^63)+1. It will be converted to -((2^63)-1) +typedef unsigned long long unsigned_long_long_type1; +typedef unsigned_long_long_type1 unsigned_long_long_type2; +const unsigned_long_long_type2 unsigned_long_long_value_t = 9223372036854775809; + +// enum type + +enum Height { tall, dwarf }; +typedef Height Height_type; +union HeightCount switch (Height_type) { + case tall : + unsigned long a; + default : + unsigned long b; +}; diff --git a/functional-tests/src/test/idl/idlj_NestedTypeDeclsAndInheritedTypes.idl b/functional-tests/src/test/idl/idlj_NestedTypeDeclsAndInheritedTypes.idl new file mode 100644 index 000000000..0d1dfc26d --- /dev/null +++ b/functional-tests/src/test/idl/idlj_NestedTypeDeclsAndInheritedTypes.idl @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Tests nested type declarations whose type definitions are in +// inherited super interfaces. +// +module TestIdlj { + + interface A1 { + enum A1_Enum { X1, X2, X3 }; + }; + + interface A2 : A1 {}; + + interface A3 : A2 { + struct A3_Struct { A1_Enum x; }; + }; + + interface A4: A2 { + typedef A1_Enum A4_Enum; + }; + + interface A5: A4 { + typedef A4_Enum A5_Enum; + struct A5_Struct { + A4_Enum x; + A5_Enum y; + }; + }; + + interface B1 { + typedef long B1_long; + }; + + interface B2 : B1 {}; + + interface B3 : B2 { + exception BB_Exception { B1_long x; }; + }; + + interface B4 : B2 { + typedef B1_long B4_long; + }; + + interface B5 : B4 { + typedef B4_long B5_long; + exception BB_Exception { + B4_long x; + B5_long y; + }; + }; +}; diff --git a/functional-tests/src/test/idl/iorinterceptor.idl b/functional-tests/src/test/idl/iorinterceptor.idl new file mode 100644 index 000000000..530c1e14d --- /dev/null +++ b/functional-tests/src/test/idl/iorinterceptor.idl @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module IORInterceptorTest { + + // A very simple interface so that we may extract the IOR. + interface simple { + attribute short x; + }; +}; diff --git a/functional-tests/src/test/idl/iorintsockfact.idl b/functional-tests/src/test/idl/iorintsockfact.idl new file mode 100644 index 000000000..9f7c1ec1a --- /dev/null +++ b/functional-tests/src/test/idl/iorintsockfact.idl @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** + * @author Harold Carr + */ +module corba +{ + module iorintsockfact + { + interface I + { + string m(in string x); + }; + + }; +}; + +// End of file. + + diff --git a/functional-tests/src/test/idl/legacy/activation.idl b/functional-tests/src/test/idl/legacy/activation.idl new file mode 100644 index 000000000..3ad5ed240 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/activation.idl @@ -0,0 +1,288 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module activation { + // Possible values for endpointType argument on Server.getEndpoint() + // If you change the value of this constant then update + // core.EndPoint accordingly. It has a duplicate definition + // to avoid a compilation dependency. + const string IIOP_CLEAR_TEXT = "IIOP_CLEAR_TEXT"; + + // REVISIT Use the CORBA 2.3 ORBid if we ever get the Java ORB ID + // issue resolved. + typedef string ORBid; + typedef long ServerId ; + typedef sequence POAName ; + + /** Raised if getEndpoint is called on a server callback object for + * an invalid endpoint type + */ + exception NoSuchEndPoint {} ; + + /** + * Raised if an attempt is made to retrieve ports corresponding to + * non-registered ORB + */ + + exception InvalidORBid {} ; + + /** Raised if an operation is attempted against an invalid server ID. + */ + exception ServerNotRegistered { + ServerId serverId ; + }; + + /** Raised if an operation is attempted for a server that is not running, + * and the server is required to be running for the operation. + */ + exception ServerNotActive { + ServerId serverId ; + }; + + /** Raised if an operation is attempted against a server that is in a + * hold down state. A server becomes held down if it fails to activate + * within 10 seconds. + */ + exception ServerHeldDown { + ServerId serverId ; + }; + + /** Raised if an attempt is made to activate a server that is already + * running. + */ + exception ServerAlreadyActive{ + ServerId serverId ; + }; + + /** Raised if an attempt is made to register a serverdef with the + * same applicationName as an existing serverdef. + */ + exception ServerAlreadyRegistered { + ServerId serverId; + }; + + /** Raised if an attempt is made to install a server that is currently + * installed. Note that a newly created server starts out in an uninstalled + * state. + */ + exception ServerAlreadyInstalled { + ServerId serverId; + } ; + + /** Raised if an attempt is made to uninstall a server that is currently + * uninstalled. Note that a newly created server starts out in an + * uninstalled + * state. + */ + exception ServerAlreadyUninstalled { + ServerId serverId; + } ; + + /** Raised if an attempt is made to register an invalid serverdef. + */ + exception BadServerDefinition { + string reason; + }; + + /** Raised if an attempt is made to register endpoints for the + * same ORB again + */ + exception ORBAlreadyRegistered { + ORBid orbId; + }; + + typedef long TCPPort ; + typedef sequence ServerIds; + + // passing a struct containing endpointType and port-#s + struct EndPointInfo { + string endpointType; + TCPPort port; + }; + + typedef sequence EndpointInfoList; + + // struct contain ORB and port info + struct ORBPortInfo { + ORBid orbId; + TCPPort port; + }; + + typedef sequence ORBPortInfoList; + + typedef sequence ORBidList; + + /** Server callback API, passed to Activator in active method. + */ + interface Server { + /** Shutdown this server. Returns after orb.shutdown() completes. + */ + void shutdown(); + + /** Install the server. Returns after the install hook completes + * execution in the server. + */ + void install(); + + /** Uninstall the server. Returns after the uninstall hook + * completes execution. + */ + void uninstall(); + }; + + interface Activator { + // A new ORB started server registers itself with the Activator + void active(in ServerId serverId, in Server serverObj) + raises (ServerNotRegistered); + + // Install a particular kind of endpoint + void registerEndpoints( in ServerId serverId, in ORBid orbId, + in EndpointInfoList endPointInfo) + raises (ServerNotRegistered,NoSuchEndPoint, ORBAlreadyRegistered) ; + + // list active servers + ServerIds getActiveServers(); + + // If the server is not running, start it up. + void activate(in ServerId serverId) + raises (ServerAlreadyActive, ServerNotRegistered, ServerHeldDown); + + // If the server is running, shut it down + void shutdown(in ServerId serverId) + raises (ServerNotActive, ServerNotRegistered); + + // Invoke the server install hook. If the server is not + // currently running, this method will activate it. + void install(in ServerId serverId) + raises (ServerNotRegistered, ServerHeldDown, + ServerAlreadyInstalled); + + // list all registered ORBs for a server + ORBidList getORBNames(in ServerId serverId) + raises (ServerNotRegistered); + + // Invoke the server uninstall hook. If the server is not + // currently running, this method will activate it. + // After this hook completes, the server may still be running. + void uninstall(in ServerId serverId) + raises (ServerNotRegistered, ServerHeldDown, + ServerAlreadyUninstalled); + }; + + interface Locator { + + // struct to return the list of endpoints for a server for a specific + // endpoint + struct ServerLocation { + string hostname; + ORBPortInfoList ports; + }; + + // struct to return the list of endpoints for a server for a specific + // ORB + struct ServerLocationPerORB { + string hostname; + EndpointInfoList ports; + }; + + // locate server - returns the port with a specific type for all registered + // ORBs of an active server. + // Starts the server if it is not already running. + ServerLocation locateServer( + in ServerId serverId, + in string endPoint) + raises(NoSuchEndPoint, ServerNotRegistered, ServerHeldDown); + + // locate server - returns all ports registered with a specified ORB for + // an active server + // Starts the server if it is not already running. + ServerLocationPerORB locateServerForORB( + in ServerId serverId, + in ORBid orbId) + raises(InvalidORBid, ServerNotRegistered, ServerHeldDown); + + // get the port for the endpoint of the locator + TCPPort getEndpoint(in string endPointType) + raises(NoSuchEndPoint); + + // Useful from external BadServerIdHandlers which need + // to pick a particular port type. + TCPPort getServerPortForType( + in ServerLocationPerORB location, + in string endPointType) + raises(NoSuchEndPoint); + }; + + interface ServerManager : Activator, Locator { }; + + interface InitialNameService { + exception NameAlreadyBound {}; + + // bind initial name + void bind ( + in string name, + in Object obj, + in boolean isPersistant) raises (NameAlreadyBound); + + }; + + interface Repository { + // server program definition. We should make this a ValueType. + struct ServerDef { + string applicationName; // alias used for servers with identical + // serverName values. + string serverName; // Class name of server's main class. + string serverClassPath; // class path used to run the server. + string serverArgs; + string serverVmArgs; + }; + + // register server definition + // This returns the serverId of the server. A newly created server is + // always uninstalled. + ServerId registerServer (in ServerDef serverDef) + raises (ServerAlreadyRegistered, BadServerDefinition); + + // unregister server definition + void unregisterServer (in ServerId serverId) + raises (ServerNotRegistered); + + // get server definition + ServerDef getServer(in ServerId serverId) + raises (ServerNotRegistered); + + // Return whether the server has been installed + boolean isInstalled( in ServerId serverId ) + raises (ServerNotRegistered); + + // Mark the server as being installed. Raises ServerAlreadyInstalled + // if the server is currently marked as installed. + void install( in ServerId serverId ) + raises (ServerNotRegistered, ServerAlreadyInstalled) ; + + // Mark the server as being uninstalled. Raises ServerAlreadyUninstalled + // if the server is currently marked as uninstalled. + void uninstall( in ServerId serverId ) + raises (ServerNotRegistered, ServerAlreadyUninstalled) ; + + // list registered servers + ServerIds listRegisteredServers (); + + typedef sequence StringSeq ; + + // Returns list of ALL applicationNames defined in ServerDefs of registered + // servers. + StringSeq getApplicationNames(); + + // Find the ServerID associated with the given application name. + ServerId getServerID( in string applicationName ) + raises (ServerNotRegistered) ; + }; +}; diff --git a/functional-tests/src/test/idl/legacy/clientinterceptor.idl b/functional-tests/src/test/idl/legacy/clientinterceptor.idl new file mode 100644 index 000000000..b9f55a218 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/clientinterceptor.idl @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module ClientRequestInterceptor +{ + interface hello + { + string sayHello(); + string saySystemException(); + oneway void sayOneway(); + void clearInvoked(); + boolean wasInvoked(); + void resetServant(); + }; +}; + diff --git a/functional-tests/src/test/idl/legacy/clientrequestinfo.idl b/functional-tests/src/test/idl/legacy/clientrequestinfo.idl new file mode 100644 index 000000000..8ec7ef56f --- /dev/null +++ b/functional-tests/src/test/idl/legacy/clientrequestinfo.idl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module ClientRequestInfo +{ + exception ExampleException { string reason; }; + + interface hello + { + string sayHello(); + string saySystemException(); + void sayUserException() raises (ExampleException); + oneway void sayOneway(); + string sayArguments( in string arg1, in long arg2, in boolean arg3 ); + void clearInvoked(); + boolean wasInvoked(); + void resetServant(); + }; +}; + diff --git a/functional-tests/src/test/idl/legacy/corba/invocation/hello.idl b/functional-tests/src/test/idl/legacy/corba/invocation/hello.idl new file mode 100644 index 000000000..48b175d67 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/corba/invocation/hello.idl @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba { + module invocation { + interface Hello + { + string sayHello(); + }; + }; +}; diff --git a/functional-tests/src/test/idl/legacy/corba/tcpreadtimeout/idlI.idl b/functional-tests/src/test/idl/legacy/corba/tcpreadtimeout/idlI.idl new file mode 100644 index 000000000..074c46e22 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/corba/tcpreadtimeout/idlI.idl @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ + module tcpreadtimeout + { + interface idlI + { + string o(in string x); + + string return_after_client_gives_up(in string x); + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/legacy/exceptiondetailsc.idl b/functional-tests/src/test/idl/legacy/exceptiondetailsc.idl new file mode 100644 index 000000000..34e1994d2 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/exceptiondetailsc.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:25:44 by Harold Carr. +// + +module corba +{ + module exceptiondetailsc + { + exception idlException { string reason; }; + + interface idlI + { + void raise_system_exception(in string x); + void raise_user_exception(in string x) + raises (idlException); + void raise_runtime_exception(in string x); + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/legacy/hcks.idl b/functional-tests/src/test/idl/legacy/hcks.idl new file mode 100644 index 000000000..8101c9cb0 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/hcks.idl @@ -0,0 +1,163 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ +module hcks +{ + typedef sequence idlJString; + + typedef sequence IntSeq10000; + typedef octet idlOctetArray10000[10000]; + + valuetype idlIntSeqValueType IntSeq10000; + valuetype idlOctetArrayValueType idlOctetArray10000; + + exception idlExampleException { string reason; }; + /* + abstract valuetype idlAbstractValueType + { + short getShortA(); + void setShortA(in short s); + }; + */ + valuetype idlValueTypeA /*: idlAbstractValueType*/ + { + private short a; + factory init (in short a); + }; + + valuetype idlValueTypeB : truncatable idlValueTypeA + { + private short b; + factory init (in short a, in short b); + }; + + custom valuetype idlValueTypeC : truncatable idlValueTypeB + { + private short c; + factory init (in short a, in short b, in short c); + }; + + custom valuetype idlValueTypeD + { + private short d; + factory init (in short d); + }; + + valuetype idlValueTypeE + { + public IntSeq10000 intSeq; + public idlOctetArray10000 octetArray; + }; + + struct recursiveType { + string a; + string b; + sequence s; + }; + + interface idlControllerI + { + string action ( in string s ); + }; + + interface idlI + { + string syncOK ( in string arg1 ); + + idlValueTypeA sendValue (in idlValueTypeA a, + in idlValueTypeB b, + in idlValueTypeC c, + in idlValueTypeD d, + in idlValueTypeE e, + in idlIntSeqValueType f, + in idlOctetArrayValueType g); + + oneway void asyncOK (in idlJString data); + + void throwUserException () + raises (idlExampleException); + + void throwSystemException (); + + void throwUnknownException (); + + void throwUNKNOWN (); + + void raiseSystemExceptionInSendReply (); + + void testEffectiveTarget1 (); + void testEffectiveTarget2 (); + + Object getAndSaveUnknownORBVersionIOR(); + boolean isIdenticalWithSavedIOR(in Object o); + }; + + interface idlSMI + { + string makeColocatedCallFromServant ( ); + string colocatedCallFromServant ( in string a ); + }; + + interface idlSAI : idlSMI + { + string raiseForwardRequestInIncarnate ( in string a ); + string raiseObjectNotExistInIncarnate ( in string a ); + string raiseSystemExceptionInIncarnate ( in string a ); + }; + + interface idlSLI : idlSMI + { + string raiseForwardRequestInPreinvoke ( in string a ); + string raiseObjectNotExistInPreinvoke ( in string a ); + string raiseSystemExceptionInPreinvoke ( in string a ); + string raiseSystemExceptionInPostinvoke ( in string a ); + string raiseSystemInServantThenPOThenSE ( ); + string raiseUserInServantThenSystemInPOThenSE ( ) + raises (idlExampleException); + + // These test ThreadDeath handling. + + string throwThreadDeathInReceiveRequestServiceContexts + ( in string a ); + string throwThreadDeathInPreinvoke ( in string a ); + string throwThreadDeathInReceiveRequest (in string a ); + string throwThreadDeathInServant ( in string a ); + string throwThreadDeathInPostinvoke ( in string a ); + string throwThreadDeathInSendReply ( in string a ); + string throwThreadDeathInServantThenSysInPostThenSysInSendException ( in string a ); + + // These are used to test server-side PICurrent. + // The names are shorthand for s(erver)Pic(urrent). + + void sPic1(); + void sPic2(); + }; + + interface idlHEADERI + { + void HEADER ( in string message ); + }; + + interface idlAttributes + { + attribute long longAttribute; + readonly attribute short readOnlyShortAttribute; + }; + + interface sendRecursiveType { + any sendAsAny(in any x); + recursiveType sendAsType(in recursiveType x); + }; + +}; // module hcks + +}; // module corba diff --git a/functional-tests/src/test/idl/legacy/islocal.idl b/functional-tests/src/test/idl/legacy/islocal.idl new file mode 100644 index 000000000..3b98eedc7 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/islocal.idl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2003 Apr 18 (Fri) 15:05:19 by Harold Carr. +// + +module corba +{ + module islocal + { + interface idlI + { + string o(in string x); + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/legacy/legacybootstrapserver.idl b/functional-tests/src/test/idl/legacy/legacybootstrapserver.idl new file mode 100644 index 000000000..5a3d0a4b5 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/legacybootstrapserver.idl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Dec 17 (Wed) 20:56:34 by Harold Carr. +// Last Modified : 2003 Dec 18 (Thu) 09:03:26 by Harold Carr. +// + +module corba +{ + module legacybootstrapserver + { + interface I + { + void dummy(); + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/legacy/oneway.idl b/functional-tests/src/test/idl/legacy/oneway.idl new file mode 100644 index 000000000..ad813fc19 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/oneway.idl @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module HelloApp +{ + interface hello + { + oneway void sayHello(); + oneway void shutdown(); + }; +}; + diff --git a/functional-tests/src/test/idl/legacy/orbinit.idl b/functional-tests/src/test/idl/legacy/orbinit.idl new file mode 100644 index 000000000..994d4f3f2 --- /dev/null +++ b/functional-tests/src/test/idl/legacy/orbinit.idl @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module ORBInitTest +{ + interface SampleObject { + attribute short x; + attribute short y; + }; + +}; + diff --git a/functional-tests/src/test/idl/mantis_m4764130_SendingContext.idl b/functional-tests/src/test/idl/mantis_m4764130_SendingContext.idl new file mode 100644 index 000000000..795cca755 --- /dev/null +++ b/functional-tests/src/test/idl/mantis_m4764130_SendingContext.idl @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Oct 16 (Wed) 08:32:47 by Harold Carr. +// Last Modified : 2002 Oct 17 (Thu) 11:49:59 by Harold Carr. +// + +module mantis +{ + module m4764130 + { + interface Hello + { + string hello(in string x) ; + }; + }; +}; + +// End of file. diff --git a/functional-tests/src/test/idl/multiorb_policy.idl b/functional-tests/src/test/idl/multiorb_policy.idl new file mode 100644 index 000000000..9d948f267 --- /dev/null +++ b/functional-tests/src/test/idl/multiorb_policy.idl @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module examples { + interface policy_2 + { + long increment(); + }; +}; diff --git a/functional-tests/src/test/idl/ort-iorinterceptor.idl b/functional-tests/src/test/idl/ort-iorinterceptor.idl new file mode 100644 index 000000000..b6716c184 --- /dev/null +++ b/functional-tests/src/test/idl/ort-iorinterceptor.idl @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module IORInterceptorTest { + + // This interface is designed to wait and notify ORTStateChangeEvaluator + // after the delay. This is added as a way to test the ORTStateChange + // Notification if the thread is blocking. + interface delay { + void forInMillis( in long timeInMillis, in string notificationToken ); + }; +}; diff --git a/functional-tests/src/test/idl/pi/serverinterceptor/serverinterceptor.idl b/functional-tests/src/test/idl/pi/serverinterceptor/serverinterceptor.idl new file mode 100644 index 000000000..b6b0e92b9 --- /dev/null +++ b/functional-tests/src/test/idl/pi/serverinterceptor/serverinterceptor.idl @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "Interceptors.idl" + +module ServerRequestInterceptor +{ + interface hello + { + string sayHello(); + oneway void sayOneway(); + void saySystemException(); + void sayUserException() raises (PortableInterceptor::ForwardRequest); + string syncWithServer( in boolean exceptionRaised ); + }; +}; + diff --git a/functional-tests/src/test/idl/poaandequals_wombat.idl b/functional-tests/src/test/idl/poaandequals_wombat.idl new file mode 100644 index 000000000..248573757 --- /dev/null +++ b/functional-tests/src/test/idl/poaandequals_wombat.idl @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module WombatStuff { + interface Wombat { + string squawk(); + }; +}; diff --git a/functional-tests/src/test/idl/poacallback1.idl b/functional-tests/src/test/idl/poacallback1.idl new file mode 100644 index 000000000..019f780f6 --- /dev/null +++ b/functional-tests/src/test/idl/poacallback1.idl @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ + module poacallback + { + interface idlI1 + { + string o1(in string x); + string o2(in string x); + }; + }; +}; + diff --git a/functional-tests/src/test/idl/poacallback2.idl b/functional-tests/src/test/idl/poacallback2.idl new file mode 100644 index 000000000..032b0f145 --- /dev/null +++ b/functional-tests/src/test/idl/poacallback2.idl @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ + module poacallback + { + interface idlI2 + { + string o(in string x); + }; + }; +}; + diff --git a/functional-tests/src/test/idl/poamanager.idl b/functional-tests/src/test/idl/poamanager.idl new file mode 100644 index 000000000..546bede2b --- /dev/null +++ b/functional-tests/src/test/idl/poamanager.idl @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// required because the actual poa.idl is now compiled with +// pkgPrefix, but for it to work in the framework we need to +// do this change + +#include "poa.idl" + +module HelloStuff { + interface Hello { + string hi(); + }; +}; + +module Util { + enum CreationMethods { + EXPLICIT_ACTIVATION_WITH_POA_ASSIGNED_OIDS, + EXPLICIT_ACTIVATION_WITH_USER_ASSIGNED_OIDS, + CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_POA_ASSIGNED_OIDS, + CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_USER_ASSIGNED_OIDS + }; + + // A generic factory that creates servants based on the + // interface name. This can be used to test different + // interfaces which contain methods that would test the + // invocation path more extensively (example, ones that + // throw exceptions etc) + + interface GenericFactory { + Object create(in string intfName, in string implName, in CreationMethods how); + void activate() raises ( PortableServer::POAManager::AdapterInactive ); + void holdRequests(); + void discardRequests(); + void deactivate(); + }; +}; diff --git a/functional-tests/src/test/idl/poatest.idl b/functional-tests/src/test/idl/poatest.idl new file mode 100644 index 000000000..6fed2a222 --- /dev/null +++ b/functional-tests/src/test/idl/poatest.idl @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module HelloA { + interface hello + { + oneway void sayHello(); + oneway void shutdown(); + + }; +}; diff --git a/functional-tests/src/test/idl/purgecalls.idl b/functional-tests/src/test/idl/purgecalls.idl new file mode 100644 index 000000000..8ecb20a74 --- /dev/null +++ b/functional-tests/src/test/idl/purgecalls.idl @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 14:09:12 by Harold Carr. +// Last Modified : 2002 Jan 17 (Thu) 14:09:14 by Harold Carr. +// + +module corba +{ + module purgecalls + { + interface ServerSide + { + void neverReturns ( ); + }; + }; +}; + +// End of file. + diff --git a/functional-tests/src/test/idl/serverrequestinfo.idl b/functional-tests/src/test/idl/serverrequestinfo.idl new file mode 100644 index 000000000..e64db731f --- /dev/null +++ b/functional-tests/src/test/idl/serverrequestinfo.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module ServerRequestInfo +{ + exception ExampleException { string reason; }; + + // Constants for sayInvokeAgain: + const long INVOKE_SAY_HELLO = 0; + const long INVOKE_SAY_SYSTEM_EXCEPTION = 1; + + interface hello + { + string sayHello(); + void saySystemException(); + void sayUserException() raises (ExampleException); + oneway void sayOneway(); + void sayInvokeAgain( in long n ); + + // exceptionRaised is true if the last invocation resulted in + // an exception. Returns the name of the method to invoke next. + string syncWithServer( in boolean exceptionRaised ); + }; +}; + diff --git a/functional-tests/src/test/idl/serviceexample.idl b/functional-tests/src/test/idl/serviceexample.idl new file mode 100644 index 000000000..8742260ff --- /dev/null +++ b/functional-tests/src/test/idl/serviceexample.idl @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module pi +{ +module serviceexample +{ + + // Create some arbitrary object to call. Those calls + // will be serviced by the service implemented using interceptors. + + exception ArbitraryObjectException { string reason; }; + + interface ArbitraryObject + { + string arbitraryOperation1 ( in string a1 ); + + oneway void arbitraryOperation2 ( in long a1 ); + + void arbitraryOperation3 ( in string a1 ) + raises (ArbitraryObjectException); + }; + + + // This would typically be in a file separate from the "ArbitraryObject" + // and probably unknown to it. + + interface LoggingService + { + void log ( in string a1 ); + }; + + // This would also typically be in a file of its own. + // IMPORTANT: the interface should be a local object to avoid + // unnecessary overhead. + + // REVISIT: local + /*local*/ interface AService + { + void begin(); + void end(); + void verify(); + }; + + // Tagged component for adding to an IOR to indicate that + // the AService must be in effect when invocations are made + // on the object containing this tagged component. + + // Note: we explicitly declare the tag type rather than using + // the IOP typedef (commented out) to simplify compiling this + // example (i.e., to avoid includes and make include path directives). + //const IOP::ComponentId TAG_ASERVICE_COMPONENT = 2345; + const unsigned long TAG_ASERVICE_COMPONENT = 2345; + + struct ASERVICE_COMPONENT { + boolean requiresAService; + }; + +}; // module serviceexample + +}; // module pi diff --git a/functional-tests/src/test/idl/systemexceptions.idl b/functional-tests/src/test/idl/systemexceptions.idl new file mode 100644 index 000000000..77fde707f --- /dev/null +++ b/functional-tests/src/test/idl/systemexceptions.idl @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba { + module systemexceptions { + interface idlI { + void invoke(in long excType); + }; + }; +}; diff --git a/functional-tests/src/test/idl/unarrow.idl b/functional-tests/src/test/idl/unarrow.idl new file mode 100644 index 000000000..a303dbfdb --- /dev/null +++ b/functional-tests/src/test/idl/unarrow.idl @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module corba +{ + module unarrow + { + interface Hello + { + string sayHello(); + }; + interface Bye + { + string sayBye(); + }; + abstract interface Foo + { + string doFoo(); + }; + interface Bar:Foo + { + string doBar(); + }; + }; +}; + diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/CommandHandler.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/CommandHandler.java new file mode 100644 index 000000000..513708ec5 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/CommandHandler.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +import org.omg.CORBA.ORB; + +import java.io.PrintStream; + +/** + * @version 1.19, 07/08/30 + * @author Rohit Garg + * @since JDK1.2 + */ + +public interface CommandHandler +{ + String getCommandName(); + + public final static boolean shortHelp = true; + public final static boolean longHelp = false; + + void printCommandHelp(PrintStream out, boolean helpType); + + public final static boolean parseError = true; + public final static boolean commandDone = false; + + boolean processCommand(String[] cmd, ORB orb, PrintStream out); +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/NameServiceStartThread.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/NameServiceStartThread.java new file mode 100644 index 000000000..f0a4cbd35 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/NameServiceStartThread.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + + +import java.io.File; + +import org.omg.CosNaming.NamingContext; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.impl.naming.pcosnaming.NameService; +import com.sun.corba.ee.spi.misc.ORBConstants; + +// REVISIT: After Merlin to see if we can get rid of this Thread and +// make the registration of PNameService for INS and BootStrap neat. +public class NameServiceStartThread extends java.lang.Thread +{ + private ORB orb; + private File dbDir; + + public NameServiceStartThread( ORB theOrb, File theDir ) + { + orb = theOrb; + dbDir = theDir; + } + + public void run( ) + { + try { + // start Name Service + NameService nameService = new NameService(orb, dbDir ); + NamingContext rootContext = nameService.initialNamingContext(); + orb.register_initial_reference( + ORBConstants.PERSISTENT_NAME_SERVICE_NAME, rootContext ); + } catch( Exception e ) { + System.err.println( + "NameService did not start successfully" ); + e.printStackTrace( ); + } + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ORBConfiguratorPersistentImpl.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ORBConfiguratorPersistentImpl.java new file mode 100644 index 000000000..1de86ddaf --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ORBConfiguratorPersistentImpl.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation ; + +import java.util.Collection ; +import java.util.Iterator ; + +import org.omg.CORBA.CompletionStatus ; + +import com.sun.corba.ee.spi.activation.Locator ; +import com.sun.corba.ee.spi.activation.Activator ; +import com.sun.corba.ee.spi.activation.LocatorHelper ; +import com.sun.corba.ee.spi.activation.ActivatorHelper ; +import com.sun.corba.ee.spi.activation.EndPointInfo ; + +import com.sun.corba.ee.spi.orb.ORBData ; +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.impl.orb.ORBConfiguratorImpl; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +public class ORBConfiguratorPersistentImpl extends ORBConfiguratorImpl { + private ORBUtilSystemException wrapper = ORBUtilSystemException.self ; + + @Override + protected void persistentServerInitialization( ORB orb ) + { + ORBData data = orb.getORBData() ; + + // determine the ORBD port so that persistent objrefs can be + // created. + if (data.getServerIsORBActivated()) { + try { + Locator locator = LocatorHelper.narrow( + orb.resolve_initial_references( + ORBConstants.SERVER_LOCATOR_NAME )) ; + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( + ORBConstants.SERVER_ACTIVATOR_NAME )) ; + Collection serverEndpoints = + orb.getCorbaTransportManager().getAcceptors(null, null); + EndPointInfo[] endpointList = + new EndPointInfo[serverEndpoints.size()]; + Iterator iterator = serverEndpoints.iterator(); + int i = 0 ; + while (iterator.hasNext()) { + Object n = iterator.next(); + if (! (n instanceof LegacyServerSocketEndPointInfo)) { + continue; + } + LegacyServerSocketEndPointInfo ep = + (LegacyServerSocketEndPointInfo) n; + // REVISIT - use exception instead of -1. + int port = locator.getEndpoint(ep.getType()); + if (port == -1) { + port = locator.getEndpoint(SocketInfo.IIOP_CLEAR_TEXT); + if (port == -1) { + throw new Exception( + "ORBD must support IIOP_CLEAR_TEXT"); + } + } + + ep.setLocatorPort(port); + + endpointList[i++] = + new EndPointInfo(ep.getType(), ep.getPort()); + } + + activator.registerEndpoints( + data.getPersistentServerId(), data.getORBId(), + endpointList); + } catch (Exception ex) { + throw wrapper.persistentServerInitError( ex ) ; + } + } + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ORBD.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ORBD.java new file mode 100644 index 000000000..0705c4acb --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ORBD.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +import com.sun.corba.ee.impl.legacy.connection.SocketFactoryAcceptorImpl; +import com.sun.corba.ee.impl.misc.CorbaResourceUtil; +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService; +import com.sun.corba.ee.impl.transport.AcceptorImpl; +import com.sun.corba.ee.spi.activation.Activator; +import com.sun.corba.ee.spi.activation.ActivatorHelper; +import com.sun.corba.ee.spi.activation.Locator; +import com.sun.corba.ee.spi.activation.LocatorHelper; +import com.sun.corba.ee.spi.activation.RepositoryPackage.ServerDef; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import java.io.File; +import java.util.Properties; + +/** + * + * @version 1.10, 97/12/06 + * @author Rohit Garg + * @since JDK1.2 + */ +public class ORBD +{ + + protected void initializeBootNaming(ORB orb) + { + // create a bootstrap server + int initSvcPort = orb.getORBData().getORBInitialPort(); + + Acceptor acceptor; + // REVISIT: see ORBConfigurator. use factory in TransportDefault. + if (orb.getORBData().getLegacySocketFactory() == null) { + acceptor = + new AcceptorImpl( + orb, + initSvcPort, + LegacyServerSocketEndPointInfo.BOOT_NAMING, + SocketInfo.IIOP_CLEAR_TEXT); + } else { + acceptor = + new SocketFactoryAcceptorImpl( + orb, + initSvcPort, + LegacyServerSocketEndPointInfo.BOOT_NAMING, + SocketInfo.IIOP_CLEAR_TEXT); + } + orb.getCorbaTransportManager().registerAcceptor(acceptor); + } + + protected ORB createORB(String[] args) + { + Properties props = System.getProperties(); + + // For debugging. + //props.put( ORBConstants.DEBUG_PROPERTY, "naming" ) ; + //props.put( ORBConstants.DEBUG_PROPERTY, "transport,giop,naming" ) ; + + props.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "1000" ) ; + props.put( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + props.getProperty( ORBConstants.ORBD_PORT_PROPERTY, + Integer.toString( + ORBConstants.DEFAULT_ACTIVATION_PORT ) ) ) ; + + // See Bug 4396928 for more information about why we are initializing + // the ORBClass to PIORB (now ORBImpl, but should check the bugid). + props.put("org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + return (ORB) ORB.init(args, props); + } + + private void run(String[] args) + { + try { + // parse the args and try setting the values for these + // properties + processArgs(args); + + ORB orb = createORB(args); + + if (orb.orbdDebugFlag) + System.out.println( "ORBD begins initialization." ) ; + + boolean firstRun = createSystemDirs( ORBConstants.DEFAULT_DB_DIR ); + + startActivationObjects(orb); + + if (firstRun) // orbd is being run the first time + installOrbServers(getRepository(), getActivator()); + + if (orb.orbdDebugFlag) { + System.out.println( "ORBD is ready." ) ; + System.out.println("ORBD serverid: " + + System.getProperty(ORBConstants.ORB_SERVER_ID_PROPERTY)); + System.out.println("activation dbdir: " + + System.getProperty(ORBConstants.DB_DIR_PROPERTY)); + System.out.println("activation port: " + + System.getProperty(ORBConstants.ORBD_PORT_PROPERTY)); + + String pollingTime = System.getProperty( + ORBConstants.SERVER_POLLING_TIME); + if( pollingTime == null ) { + pollingTime = Integer.toString( + ORBConstants.DEFAULT_SERVER_POLLING_TIME ); + } + System.out.println("activation Server Polling Time: " + + pollingTime + " milli-seconds "); + + String startupDelay = System.getProperty( + ORBConstants.SERVER_STARTUP_DELAY); + if( startupDelay == null ) { + startupDelay = Integer.toString( + ORBConstants.DEFAULT_SERVER_STARTUP_DELAY ); + } + System.out.println("activation Server Startup Delay: " + + startupDelay + " milli-seconds " ); + } + + // The following two lines start the Persistent NameService + NameServiceStartThread theThread = + new NameServiceStartThread( orb, dbDir ); + theThread.start( ); + + orb.run(); + } catch( org.omg.CORBA.COMM_FAILURE cex ) { + System.out.println( CorbaResourceUtil.getText("orbd.commfailure")); + System.out.println( cex ); + cex.printStackTrace(); + } catch( org.omg.CORBA.INTERNAL iex ) { + System.out.println( CorbaResourceUtil.getText( + "orbd.internalexception")); + System.out.println( iex ); + iex.printStackTrace(); + } catch (Exception ex) { + System.out.println(CorbaResourceUtil.getText( + "orbd.usage", "orbd")); + System.out.println( ex ); + ex.printStackTrace(); + } + } + + private void processArgs(String[] args) + { + Properties props = System.getProperties(); + for (int i=0; i < args.length; i++) { + if (args[i].equals("-port")) { + if ((i+1) < args.length) { + props.put(ORBConstants.ORBD_PORT_PROPERTY, args[++i]); + } else { + System.out.println(CorbaResourceUtil.getText( + "orbd.usage", "orbd")); + } + } else if (args[i].equals("-defaultdb")) { + if ((i+1) < args.length) { + props.put(ORBConstants.DB_DIR_PROPERTY, args[++i]); + } else { + System.out.println(CorbaResourceUtil.getText( + "orbd.usage", "orbd")); + } + } else if (args[i].equals("-serverid")) { + if ((i+1) < args.length) { + props.put(ORBConstants.ORB_SERVER_ID_PROPERTY, args[++i]); + } else { + System.out.println(CorbaResourceUtil.getText( + "orbd.usage", "orbd")); + } + } else if (args[i].equals("-serverPollingTime")) { + if ((i+1) < args.length) { + props.put(ORBConstants.SERVER_POLLING_TIME, args[++i]); + } else { + System.out.println(CorbaResourceUtil.getText( + "orbd.usage", "orbd")); + } + } else if (args[i].equals("-serverStartupDelay")) { + if ((i+1) < args.length) { + props.put(ORBConstants.SERVER_STARTUP_DELAY, args[++i]); + } else { + System.out.println(CorbaResourceUtil.getText( + "orbd.usage", "orbd")); + } + } + } + } + + /** + * Ensure that the Db directory exists. If not, create the Db + * and the log directory and return true. Otherwise return false. + */ + protected boolean createSystemDirs(String defaultDbDir) + { + boolean dirCreated = false; + Properties props = System.getProperties(); + String fileSep = props.getProperty("file.separator"); + + // determine the ORB db directory + dbDir = new File (props.getProperty( ORBConstants.DB_DIR_PROPERTY, + props.getProperty("user.dir") + fileSep + defaultDbDir)); + + // create the db and the logs directories + dbDirName = dbDir.getAbsolutePath(); + props.put(ORBConstants.DB_DIR_PROPERTY, dbDirName); + if (!dbDir.exists()) { + dirCreated = dbDir.mkdir(); + } + + File logDir = new File (dbDir, ORBConstants.SERVER_LOG_DIR ) ; + if (!logDir.exists()) logDir.mkdir(); + + return dirCreated; + } + + protected File dbDir; + + private String dbDirName; + protected String getDbDirName() + { + return dbDirName; + } + + protected void startActivationObjects(ORB orb) throws Exception + { + // create Initial Name Service object + initializeBootNaming(orb); + + // create Repository object + repository = new RepositoryImpl(orb, dbDir, orb.orbdDebugFlag ); + orb.register_initial_reference( ORBConstants.SERVER_REPOSITORY_NAME, repository ); + + // create Locator and Activator objects + ServerManagerImpl serverMgr = + new ServerManagerImpl( orb, + orb.getCorbaTransportManager(), + repository, + getDbDirName(), + orb.orbdDebugFlag ); + + locator = LocatorHelper.narrow(serverMgr); + orb.register_initial_reference( ORBConstants.SERVER_LOCATOR_NAME, locator ); + + activator = ActivatorHelper.narrow(serverMgr); + orb.register_initial_reference( ORBConstants.SERVER_ACTIVATOR_NAME, activator ); + + // start Name Service + new TransientNameService(orb, ORBConstants.TRANSIENT_NAME_SERVICE_NAME); + } + + protected Locator locator; + + protected Activator activator; + protected Activator getActivator() + { + return activator; + } + + protected RepositoryImpl repository; + protected RepositoryImpl getRepository() + { + return repository; + } + + /** + * Go through the list of ORB Servers and initialize and start + * them up. + */ + protected void installOrbServers(RepositoryImpl repository, + Activator activator) + { + int serverId; + String[] server; + ServerDef serverDef; + + for (String[] orbServer : orbServers) { + try { + server = orbServer; + serverDef = new ServerDef(server[1], server[2], server[3], server[4], server[5]); + + serverId = Integer.valueOf(orbServer[0]); + + repository.registerServer(serverDef, serverId); + + activator.activate(serverId); + + } catch (Exception ex) { // ignore errors + } + } + } + + public static void main(String[] args) { + ORBD orbd = new ORBD(); + orbd.run(args); + } + + /** + * List of servers to be auto registered and started by the ORBd. + * + * Each server entry is of the form {id, name, path, args, vmargs}. + */ + private static String[][] orbServers = { + {""} + }; +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ProcessMonitorThread.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ProcessMonitorThread.java new file mode 100644 index 000000000..e1dd707e4 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ProcessMonitorThread.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** ProcessMonitorThread is started when ServerManager is instantiated. The + * thread wakes up every minute (This can be changed by setting sleepTime) and + * makes sure that all the processes (Servers) registered with the ServerTool + * are healthy. If not the state in ServerTableEntry will be changed to + * De-Activated. + * Note: This thread can be killed from the main thread by calling + * interrupThread() + */ +public class ProcessMonitorThread extends java.lang.Thread { + private Map serverTable; + private int sleepTime; + private static ProcessMonitorThread instance = null; + + private ProcessMonitorThread( Map ServerTable, int SleepTime ) { + serverTable = ServerTable; + sleepTime = SleepTime; + } + + public void run( ) { + while( true ) { + try { + // Sleep's for a specified time, before checking + // the Servers health. This will repeat as long as + // the ServerManager (ORBD) is up and running. + Thread.sleep( sleepTime ); + } catch( java.lang.InterruptedException e ) { + break; + } + synchronized ( serverTable ) { + // Check each ServerTableEntry to make sure that they + // are in the right state. + Iterator serverList = serverTable.values().iterator(); + checkServerHealth( serverList ); + } + } + } + + private void checkServerHealth( Iterator serverList ) { + while (serverList.hasNext( ) ) { + ServerTableEntry entry = (ServerTableEntry) serverList.next(); + entry.checkProcessHealth( ); + } + } + + static void start( Map serverTable ) { + int sleepTime = ORBConstants.DEFAULT_SERVER_POLLING_TIME; + + String pollingTime = System.getProperties().getProperty( + ORBConstants.SERVER_POLLING_TIME ); + + if ( pollingTime != null ) { + try { + sleepTime = Integer.parseInt( pollingTime ); + } catch (Exception e ) { + // Too late to complain, Just use the default + // sleepTime + } + } + + instance = new ProcessMonitorThread( serverTable, + sleepTime ); + instance.setDaemon( true ); + instance.start(); + } + + static void interruptThread( ) { + instance.interrupt(); + } +} + diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/RepositoryImpl.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/RepositoryImpl.java new file mode 100644 index 000000000..856b93a8b --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/RepositoryImpl.java @@ -0,0 +1,424 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.Properties; +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; + +import com.sun.corba.ee.spi.activation.BadServerDefinition; +import com.sun.corba.ee.spi.activation.RepositoryPackage.ServerDef; +import com.sun.corba.ee.spi.activation._RepositoryImplBase; +import com.sun.corba.ee.spi.activation.ServerAlreadyRegistered; +import com.sun.corba.ee.spi.activation.ServerAlreadyInstalled; +import com.sun.corba.ee.spi.activation.ServerAlreadyUninstalled; +import com.sun.corba.ee.spi.activation.ServerNotRegistered; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.spi.logging.ActivationSystemException; +import com.sun.corba.ee.spi.transport.Acceptor; + +/** + * + * @version 1.1, 97/10/17 + * @author Rohit Garg + * @since JDK1.2 + */ +public class RepositoryImpl extends _RepositoryImplBase + implements Serializable +{ + + // added serialver computed by the tool + private static final long serialVersionUID = 8458417785209341858L; + + RepositoryImpl(ORB orb, File dbDir, boolean debug) + { + this.debug = debug ; + this.orb = orb; + wrapper = ActivationSystemException.self ; + + // if databse does not exist, create it otherwise read it in + File dbFile = new File(dbDir, "servers.db"); + if (!dbFile.exists()) { + db = new RepositoryDB(dbFile); + db.flush(); + } else { + try { + FileInputStream fis = new FileInputStream(dbFile); + ObjectInputStream ois = new ObjectInputStream(fis); + db = (RepositoryDB) ois.readObject(); + ois.close(); + } catch (Exception e) { + throw wrapper.cannotReadRepositoryDb( e ) ; + } + } + + // export the repository + orb.connect(this); + } + + private String printServerDef( ServerDef sd ) + { + return "ServerDef[applicationName=" + sd.applicationName + + " serverName=" + sd.serverName + + " serverClassPath=" + sd.serverClassPath + + " serverArgs=" + sd. serverArgs + + " serverVmArgs=" + sd.serverVmArgs + + "]" ; + } + + public int registerServer(ServerDef serverDef, int theServerId) + throws ServerAlreadyRegistered + { + synchronized (db) { + int serverId; + for (DBServerDef server : db.serverTable.values() ) { + if (serverDef.applicationName.equals(server.applicationName)) { + if (debug) + System.out.println( + "RepositoryImpl: registerServer called " + + "to register ServerDef " + + printServerDef( serverDef ) + + " with " + ((theServerId==illegalServerId) ? + "a new server Id" : ("server Id " + theServerId)) + + " FAILED because it is already registered." ) ; + + throw new ServerAlreadyRegistered(server.id); + } + } + + // generate a new server id + if (theServerId == illegalServerId) + serverId = db.incrementServerIdCounter(); + else + serverId = theServerId; + + // add server def to the database + DBServerDef server = new DBServerDef(serverDef, serverId); + db.serverTable.put(serverId, server); + db.flush(); + + if (debug) + if (theServerId==illegalServerId) + System.out.println( "RepositoryImpl: registerServer called " + + "to register ServerDef " + printServerDef( serverDef ) + + " with new serverId " + serverId ) ; + else + System.out.println( "RepositoryImpl: registerServer called " + + "to register ServerDef " + printServerDef( serverDef ) + + " with assigned serverId " + serverId ) ; + + return serverId; + } + } + + public int registerServer(ServerDef serverDef) + throws ServerAlreadyRegistered, BadServerDefinition + { + // verify that the entry is valid + LegacyServerSocketEndPointInfo endpoint = + orb.getLegacyServerSocketManager() + .legacyGetEndpoint(LegacyServerSocketEndPointInfo.BOOT_NAMING); + int initSvcPort = ((Acceptor)endpoint) + .getServerSocket().getLocalPort(); + ServerTableEntry entry = new ServerTableEntry( wrapper, + illegalServerId, serverDef, (int) initSvcPort, "", true, debug ); + + switch (entry.verify()) { + case ServerMain.OK: + break; + case ServerMain.MAIN_CLASS_NOT_FOUND: + throw new BadServerDefinition("main class not found."); + case ServerMain.NO_MAIN_METHOD: + throw new BadServerDefinition("no main method found."); + case ServerMain.APPLICATION_ERROR: + throw new BadServerDefinition("server application error."); + default: + throw new BadServerDefinition("unknown Exception."); + } + + return registerServer(serverDef, illegalServerId); + } + + public void unregisterServer(int serverId) throws ServerNotRegistered { + + DBServerDef server = null; + synchronized (db) { + + // check to see if the server is registered + server = db.serverTable.get(serverId); + if (server == null) { + if (debug) + System.out.println( + "RepositoryImpl: unregisterServer for serverId " + + serverId + " called: server not registered" ) ; + + throw (new ServerNotRegistered()); + } + + // remove server from the database + db.serverTable.remove(serverId); + db.flush(); + } + + if (debug) + System.out.println( + "RepositoryImpl: unregisterServer for serverId " + serverId + + " called" ) ; + } + + private DBServerDef getDBServerDef(int serverId) throws ServerNotRegistered + { + DBServerDef server = db.serverTable.get(serverId); + + if (server == null) + throw new ServerNotRegistered( serverId ); + + return server ; + } + + public ServerDef getServer(int serverId) throws ServerNotRegistered + { + DBServerDef server = getDBServerDef( serverId ) ; + + ServerDef serverDef = new ServerDef(server.applicationName, server.name, + server.classPath, server.args, server.vmArgs); + + if (debug) + System.out.println( + "RepositoryImpl: getServer for serverId " + serverId + + " returns " + printServerDef( serverDef ) ) ; + + return serverDef; + } + + public boolean isInstalled(int serverId) throws ServerNotRegistered { + DBServerDef server = getDBServerDef( serverId ) ; + return server.isInstalled ; + } + + public void install( int serverId ) + throws ServerNotRegistered, ServerAlreadyInstalled + { + DBServerDef server = getDBServerDef( serverId ) ; + + if (server.isInstalled) + throw new ServerAlreadyInstalled( serverId ) ; + else { + server.isInstalled = true ; + db.flush() ; + } + } + + public void uninstall( int serverId ) + throws ServerNotRegistered, ServerAlreadyUninstalled + { + DBServerDef server = getDBServerDef( serverId ) ; + + if (!server.isInstalled) + throw new ServerAlreadyUninstalled( serverId ) ; + else { + server.isInstalled = false ; + db.flush() ; + } + } + + public int[] listRegisteredServers() { + synchronized (db) { + int i=0; + int servers[] = new int[db.serverTable.size()]; + for (DBServerDef server : db.serverTable.values() ) { + servers[i++] = server.id ; + } + + if (debug) { + StringBuilder sb = new StringBuilder() ; + for (int ctr=0; ctr entry : db.serverTable.entrySet() ) { + if (entry.getValue().applicationName.equals(applicationName)) { + result = entry.getKey() ; + break ; + } + } + + if (debug) + System.out.println("RepositoryImpl: getServerID for " + + applicationName + " is " + result ) ; + + if (result == -1) { + throw (new ServerNotRegistered()); + } else { + return result ; + } + } + } + + public String[] getApplicationNames() { + synchronized (db) { + List result = new ArrayList() ; + for (Map.Entry entry : db.serverTable.entrySet() ) { + if (!entry.getValue().applicationName.equals("")) + result.add( entry.getValue().applicationName ) ; + } + + String[] apps = result.toArray( new String[result.size()] ) ; + + if (debug) { + StringBuilder sb = new StringBuilder() ; + for (int ctr=0; ctr serverTable; + private Integer serverIdCounter; + + RepositoryDB(File dbFile) { + + db = dbFile; + + // initialize the Server Id counter and hashtable. + // the lower id range is reserved for system servers + serverTable = new HashMap(255); + serverIdCounter = Integer.valueOf(256); + } + + int incrementServerIdCounter() + { + int value = serverIdCounter.intValue(); + serverIdCounter = Integer.valueOf(++value); + + return value; + } + + void flush() + { + try { + db.delete(); + FileOutputStream fos = new FileOutputStream(db); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(this); + oos.flush(); + oos.close(); + } catch (Exception ex) { + throw wrapper.cannotWriteRepositoryDb( ex ) ; + } + } + } + + class DBServerDef implements Serializable + { + public String toString() { + return "DBServerDef(applicationName=" + applicationName + + ", name=" + name + + ", classPath=" + classPath + + ", args=" + args + + ", vmArgs=" + vmArgs + + ", id=" + id + + ", isInstalled=" + isInstalled + ")" ; + } + + DBServerDef(ServerDef server, int server_id) { + applicationName = server.applicationName ; + name = server.serverName; + classPath = server.serverClassPath; + args = server.serverArgs; + vmArgs = server.serverVmArgs; + id = server_id; + isInstalled = false ; + } + + String applicationName; + String name; + String classPath; + String args; + String vmArgs; + boolean isInstalled ; + int id; + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerMain.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerMain.java new file mode 100644 index 000000000..3528674b9 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerMain.java @@ -0,0 +1,346 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.io.*; +import java.util.Date; +import java.util.Properties ; + +import org.omg.CORBA.ORB ; +import com.sun.corba.ee.spi.activation.Activator ; +import com.sun.corba.ee.spi.activation.ActivatorHelper ; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.spi.misc.ORBClassLoader ; + +/** + * @version 1.8, 99/11/02 + * @author Ken Cavanaugh + * @since JDK1.2 + */ +public class ServerMain +{ + public final static int OK = 0; + public final static int MAIN_CLASS_NOT_FOUND = 1; + public final static int NO_MAIN_METHOD = 2; + public final static int APPLICATION_ERROR = 3; + public final static int UNKNOWN_ERROR = 4; + public final static int NO_SERVER_ID = 5 ; + public final static int REGISTRATION_FAILED = 6; + + public static String printResult( int result ) + { + switch (result) { + case OK : return "Server terminated normally" ; + case MAIN_CLASS_NOT_FOUND : return "main class not found" ; + case NO_MAIN_METHOD : return "no main method" ; + case APPLICATION_ERROR : return "application error" ; + case NO_SERVER_ID : return "server ID not defined" ; + case REGISTRATION_FAILED: return "server registration failed" ; + default : return "unknown error" ; + } + } + + private void redirectIOStreams() + { + // redirect out and err streams + try { + String logDirName = + System.getProperty( ORBConstants.DB_DIR_PROPERTY ) + + System.getProperty("file.separator") + + ORBConstants.SERVER_LOG_DIR + + System.getProperty("file.separator"); + + // Check that the logDirName exists + new File(logDirName); + + String server = System.getProperty( + ORBConstants.ORB_SERVER_ID_PROPERTY ) ; + + FileOutputStream foutStream = + new FileOutputStream(logDirName + server+".out", true); + FileOutputStream ferrStream = + new FileOutputStream(logDirName + server+".err", true); + + PrintStream pSout = new PrintStream(foutStream, true); + PrintStream pSerr = new PrintStream(ferrStream, true); + + System.setOut(pSout); + System.setErr(pSerr); + + logInformation( "Server started" ) ; + } catch (Exception ex) { + throw new RuntimeException( "Could not redirect streams", ex ) ; + } + } + + /** Write a time-stamped message to the indicated PrintStream. + */ + private static void writeLogMessage( PrintStream pstream, String msg ) + { + Date date = new Date(); + pstream.print( "[" + date.toString() + "] " + msg + "\n"); + } + + /** Write information to standard out only. + */ + public static void logInformation( String msg ) + { + writeLogMessage( System.out, " " + msg ) ; + } + + /** Write error message to standard out and standard err. + */ + public static void logError( String msg ) + { + writeLogMessage( System.out, "ERROR: " + msg ) ; + writeLogMessage( System.err, "ERROR: " + msg ) ; + } + + /** Write final message to log(s) and then terminate by calling + * System.exit( code ). If code == OK, write a normal termination + * message to standard out, otherwise write an abnormal termination + * message to standard out and standard error. + */ + public static void logTerminal( String msg, int code ) + { + if (code == 0) { + writeLogMessage( System.out, " " + msg ) ; + } else { + writeLogMessage( System.out, "FATAL: " + + printResult( code ) + ": " + msg ) ; + + writeLogMessage( System.err, "FATAL: " + + printResult( code ) + ": " + msg ) ; + } + + System.exit( code ) ; + } + + private Method getMainMethod( Class serverClass ) + { + Method method = null ; + + try { + method = serverClass.getDeclaredMethod( "main", String[].class ) ; + } catch (Exception exc) { + logTerminal( exc.getMessage(), NO_MAIN_METHOD ) ; + } + + if (!isPublicStaticVoid( method )) + logTerminal( "", NO_MAIN_METHOD ) ; + + return method ; + } + + private boolean isPublicStaticVoid( Method method ) + { + // check modifiers: public static + int modifiers = method.getModifiers (); + if (!Modifier.isPublic (modifiers) || !Modifier.isStatic (modifiers)) { + logError( method.getName() + " is not public static" ) ; + return false ; + } + + // check return type and exceptions + if (method.getExceptionTypes ().length != 0) { + logError( method.getName() + " declares exceptions" ) ; + return false ; + } + + if (!method.getReturnType().equals (Void.TYPE)) { + logError( method.getName() + " does not have a void return type" ) ; + return false ; + } + + return true ; + } + + private Method getNamedMethod( Class serverClass, String methodName ) + { + Method method = null ; + + try { + method = serverClass.getDeclaredMethod( methodName, + org.omg.CORBA.ORB.class ) ; + } catch (Exception exc) { + return null ; + } + + if (!isPublicStaticVoid( method )) + return null ; + + return method ; + } + + private void run(String[] args) + { + try { + redirectIOStreams() ; + + String serverClassName = System.getProperty( + ORBConstants.SERVER_NAME_PROPERTY ) ; + + // determine the main class + Class serverClass = null; + + try { + // determine the main class, try loading with current class loader + serverClass = Class.forName( serverClassName ) ; + } catch (ClassNotFoundException ex) { + // eat the exception and try to load using SystemClassLoader + serverClass = Class.forName( serverClassName, true, + ORBClassLoader.getClassLoader() ); + } + + if (debug) + System.out.println("class " + serverClassName + " found"); + + // get the main method + Method mainMethod = getMainMethod( serverClass ) ; + + // This piece of code is required, to verify the server definition + // without launching it. + + // verify the server + + boolean serverVerifyFlag = Boolean.getBoolean( + ORBConstants.SERVER_DEF_VERIFY_PROPERTY) ; + if (serverVerifyFlag) { + if (mainMethod == null) + logTerminal("", NO_MAIN_METHOD); + else { + if (debug) + System.out.println("Valid Server"); + logTerminal("", OK); + } + } + + registerCallback( serverClass ) ; + mainMethod.invoke(null, new Object[] { args } ); + } catch (ClassNotFoundException e) { + logTerminal("ClassNotFound exception: " + e.getMessage(), + MAIN_CLASS_NOT_FOUND); + } catch (Exception e) { + logTerminal("Exception: " + e.getMessage(), + APPLICATION_ERROR); + } + } + + public static void main(String[] args) { + ServerMain server = new ServerMain(); + server.run(args); + } + + private static final boolean debug = false; + + private int getServerId() + { + Integer serverId = Integer.getInteger( ORBConstants.ORB_SERVER_ID_PROPERTY ) ; + + if (serverId == null) + logTerminal( "", NO_SERVER_ID ) ; + + return serverId.intValue() ; + } + + private void registerCallback( Class serverClass ) + { + Method installMethod = getNamedMethod( serverClass, "install" ) ; + Method uninstallMethod = getNamedMethod( serverClass, "uninstall" ) ; + Method shutdownMethod = getNamedMethod( serverClass, "shutdown" ) ; + + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + // NOTE: Very important to pass this property, otherwise the + // Persistent Server registration will be unsucessfull. + props.put( ORBConstants.ACTIVATED_PROPERTY, "false" ); + String args[] = null ; + ORB orb = ORB.init( args, props ) ; + + ServerCallback serverObj = new ServerCallback( orb, + installMethod, uninstallMethod, shutdownMethod ) ; + + int serverId = getServerId() ; + + try { + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + activator.active(serverId, serverObj); + } catch (Exception ex) { + logTerminal( "exception " + ex.getMessage(), + REGISTRATION_FAILED ) ; + } + } +} + +class ServerCallback extends + com.sun.corba.ee.spi.activation._ServerImplBase +{ + private ORB orb; + private transient Method installMethod ; + private transient Method uninstallMethod ; + private transient Method shutdownMethod ; + + ServerCallback(ORB orb, Method installMethod, Method uninstallMethod, + Method shutdownMethod ) + { + this.orb = orb; + this.installMethod = installMethod ; + this.uninstallMethod = uninstallMethod ; + this.shutdownMethod = shutdownMethod ; + + orb.connect( this ) ; + } + + private void invokeMethod( Method method ) + { + if (method != null) + try { + method.invoke( null, orb ) ; + } catch (Exception exc) { + ServerMain.logError( "could not invoke " + method.getName() + + " method: " + exc.getMessage() ) ; + } + } + + // shutdown the ORB and wait for completion + public void shutdown() + { + ServerMain.logInformation( "Shutdown starting" ) ; + + invokeMethod( shutdownMethod ) ; + + orb.shutdown(true); + + ServerMain.logTerminal( "Shutdown completed", ServerMain.OK ) ; + } + + public void install() + { + ServerMain.logInformation( "Install starting" ) ; + + invokeMethod( installMethod ) ; + + ServerMain.logInformation( "Install completed" ) ; + } + + public void uninstall() + { + ServerMain.logInformation( "uninstall starting" ) ; + + invokeMethod( uninstallMethod ) ; + + ServerMain.logInformation( "uninstall completed" ) ; + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerManagerImpl.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerManagerImpl.java new file mode 100644 index 000000000..848b2a730 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerManagerImpl.java @@ -0,0 +1,601 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +/** + * + * @author Rohit Garg + * @author Ken Cavanaugh + * @author Hemanth Puttaswamy + * @since JDK1.2 + */ + +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; +import java.util.NoSuchElementException; + +import com.sun.corba.ee.spi.activation.EndPointInfo; +import com.sun.corba.ee.spi.activation.ORBPortInfo; +import com.sun.corba.ee.spi.activation.Repository; +import com.sun.corba.ee.spi.activation.LocatorPackage.ServerLocation; +import com.sun.corba.ee.spi.activation.LocatorPackage.ServerLocationPerORB; +import com.sun.corba.ee.spi.activation.RepositoryPackage.ServerDef; +import com.sun.corba.ee.spi.activation._ServerManagerImplBase; +import com.sun.corba.ee.spi.activation.ServerAlreadyActive; +import com.sun.corba.ee.spi.activation.ServerAlreadyInstalled; +import com.sun.corba.ee.spi.activation.ServerAlreadyUninstalled; +import com.sun.corba.ee.spi.activation.ServerNotRegistered; +import com.sun.corba.ee.spi.activation.ORBAlreadyRegistered; +import com.sun.corba.ee.spi.activation.ServerHeldDown; +import com.sun.corba.ee.spi.activation.ServerNotActive; +import com.sun.corba.ee.spi.activation.NoSuchEndPoint; +import com.sun.corba.ee.spi.activation.InvalidORBid; +import com.sun.corba.ee.spi.activation.Server; +import com.sun.corba.ee.spi.activation.IIOP_CLEAR_TEXT; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.ForwardException; +import com.sun.corba.ee.spi.transport.TransportManager; + +import com.sun.corba.ee.spi.logging.ActivationSystemException ; + +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.transport.Acceptor; + +public class ServerManagerImpl extends _ServerManagerImplBase + implements BadServerIdHandler +{ + private static final long serialVersionUID = -8150406906204281113L; + // Using HashMap, since synchronization should be done by the calling + // routines + Map serverTable; + Repository repository; + + TransportManager transportManager; + int initialPort; + ORB orb; + ActivationSystemException wrapper; + String dbDirName; + boolean debug = false ; + + private int serverStartupDelay; + + ServerManagerImpl(ORB orb, TransportManager transportManager, + Repository repository, String dbDirName, boolean debug) + { + this.orb = orb; + wrapper = ActivationSystemException.self ; + + this.transportManager = transportManager; // REVISIT - NOT USED. + this.repository = repository; + this.dbDirName = dbDirName; + this.debug = debug ; + + LegacyServerSocketEndPointInfo endpoint = + orb.getLegacyServerSocketManager() + .legacyGetEndpoint(LegacyServerSocketEndPointInfo.BOOT_NAMING); + + initialPort = ((Acceptor)endpoint) + .getServerSocket().getLocalPort(); + serverTable = new HashMap(); + + // The ServerStartupDelay is the delay added after the Server registers + // end point information. This is to allow the server to completely + // initialize after ORB is instantiated. + serverStartupDelay = ORBConstants.DEFAULT_SERVER_STARTUP_DELAY; + String delay = System.getProperty( ORBConstants.SERVER_STARTUP_DELAY); + if( delay != null ) { + try { + serverStartupDelay = Integer.parseInt( delay ); + } catch ( Exception e ) { + // Just use the default 1000 milliseconds as the default + } + } + + Class cls = orb.getORBData( ).getBadServerIdHandler(); + if( cls == null ) { + orb.setBadServerIdHandler( this ); + } else { + orb.initBadServerIdHandler() ; + } + + orb.connect(this); + ProcessMonitorThread.start( serverTable ); + } + + public void activate(int serverId) + throws ServerAlreadyActive, ServerNotRegistered, ServerHeldDown + { + + ServerLocation location; + ServerTableEntry entry; + + synchronized(serverTable) { + entry = serverTable.get(serverId); + } + + if (entry != null && entry.isActive()) { + if (debug) + System.out.println( "ServerManagerImpl: activate for server Id " + + serverId + " failed because server is already active. " + + "entry = " + entry ) ; + + throw new ServerAlreadyActive( serverId ); + } + + // locate the server + try { + + // We call getEntry here so that state of the entry is + // checked for validity before we actually go and locate a server + + entry = getEntry(serverId); + + if (debug) + System.out.println( "ServerManagerImpl: locateServer called with " + + " serverId=" + serverId + " endpointType=" + + IIOP_CLEAR_TEXT.value + " block=false" ) ; + + location = locateServer(entry, IIOP_CLEAR_TEXT.value, false); + + if (debug) + System.out.println( "ServerManagerImpl: activate for server Id " + + serverId + " found location " + + location.hostname + " and activated it" ) ; + } catch (NoSuchEndPoint ex) { + if (debug) + System.out.println( "ServerManagerImpl: activate for server Id " + + " threw NoSuchEndpoint exception, which was ignored" ); + } + } + + public void active(int serverId, Server server) throws ServerNotRegistered + { + synchronized (serverTable) { + ServerTableEntry entry = serverTable.get(serverId); + + if (entry == null) { + if (debug) + System.out.println( "ServerManagerImpl: active for server Id " + + serverId + " called, but no such server is registered." ) ; + + throw wrapper.serverNotExpectedToRegister() ; + } else { + if (debug) + System.out.println( "ServerManagerImpl: active for server Id " + + serverId + " called. This server is now active." ) ; + + entry.register(server); + } + } + } + + public void registerEndpoints( int serverId, String orbId, + EndPointInfo [] endpointList ) throws NoSuchEndPoint, ServerNotRegistered, + ORBAlreadyRegistered + { + // orbId is ignored for now + synchronized (serverTable) { + ServerTableEntry entry = serverTable.get(serverId); + + if (entry == null) { + if (debug) + System.out.println( + "ServerManagerImpl: registerEndpoint for server Id " + + serverId + " called, but no such server is registered." ) ; + + throw wrapper.serverNotExpectedToRegister() ; + } else { + if (debug) + System.out.println( + "ServerManagerImpl: registerEndpoints for server Id " + + serverId + " called. This server is now active." ) ; + + entry.registerPorts( orbId, endpointList ); + + } + } + } + + public int[] getActiveServers() + { + int[] list = null; + + synchronized (serverTable) { + List servers = + new ArrayList() ; + + try { + for (Map.Entry entry : + serverTable.entrySet()) { + ServerTableEntry def = entry.getValue() ; + if (def.isValid() && def.isActive()) + servers.add( def ) ; + } + } catch (NoSuchElementException e) { + // all done + } + + // collect the active entries + list = new int[servers.size()]; + int i = 0 ; + for (ServerTableEntry entry : servers) + list[i++] = entry.getServerId() ; + } + + if (debug) { + StringBuffer sb = new StringBuffer() ; + for (int ctr=0; ctr> orbAndPortInfo ; + private Server serverObj; + private ServerDef serverDef; + private Process process; + private int activateRetryCount=0; + private String activationCmd; + private ActivationSystemException wrapper ; + + @Override + public String toString() + { + return "ServerTableEntry[" + "state=" + printState() + + " serverId=" + serverId + + " activateRetryCount=" + activateRetryCount + "]" ; + } + + // get the string needed to make the activation command + private static String javaHome, classPath, fileSep, pathSep; + + static { + javaHome = System.getProperty("java.home"); + classPath = System.getProperty("java.class.path"); + fileSep = System.getProperty("file.separator"); + pathSep = System.getProperty("path.separator"); + } + + ServerTableEntry( ActivationSystemException wrapper, + int serverId, ServerDef serverDef, int initialPort, + String dbDirName, boolean verify, boolean debug ) + { + this.wrapper = wrapper ; + this.serverId = serverId; + this.serverDef = serverDef; + this.debug = debug ; + + orbAndPortInfo = new HashMap>(); + + activateRetryCount = 0; + state = ACTIVATING; + + // compute the activation command + activationCmd = + + // add path to the java vm + javaHome + fileSep + "bin" + fileSep + "java " + + + // add any arguments to the server Java VM + serverDef.serverVmArgs + " " + + + // add ORB properties + "-Dioser=" + System.getProperty( "ioser" ) + " " + + "-D" + ORBConstants.INITIAL_PORT_PROPERTY + "=" + initialPort + " " + + "-D" + ORBConstants.DB_DIR_PROPERTY + "=" + dbDirName + " " + + "-D" + ORBConstants.ACTIVATED_PROPERTY + "=true " + + "-D" + ORBConstants.ORB_SERVER_ID_PROPERTY + "=" + serverId + " " + + "-D" + ORBConstants.SERVER_NAME_PROPERTY + "=" + serverDef.serverName + " " + + // we need to pass in the verify flag, so that the server is not + // launched, when we try to validate its definition during registration + // into the RepositoryImpl + + (verify ? "-D" + ORBConstants.SERVER_DEF_VERIFY_PROPERTY + "=true ": "") + + + // add classpath to the server + "-classpath " + classPath + + (serverDef.serverClassPath.equals("") == true ? "" : pathSep) + + serverDef.serverClassPath + + + // add server class name and arguments + " com.sun.corba.ee.impl.activation.ServerMain " + serverDef.serverArgs + + // Add the debug flag, if any + + (debug ? " -debug" : "") ; + + if (debug) System.out.println( + "ServerTableEntry constructed with activation command " + + activationCmd); + } + + /** + * Verify whether the server definition is valid. + */ + public int verify() + { + try { + + if (debug) + System.out.println("Server being verified w/" + activationCmd); + + process = Runtime.getRuntime().exec(activationCmd); + int result = process.waitFor(); + if (debug) + printDebug( "verify", "returns " + ServerMain.printResult( result ) ) ; + return result ; + } catch (Exception e) { + if (debug) + printDebug( "verify", "returns unknown error because of exception " + + e ) ; + return ServerMain.UNKNOWN_ERROR; + } + } + + private void printDebug(String method, String msg) + { + System.out.println("ServerTableEntry: method =" + method); + System.out.println("ServerTableEntry: server =" + serverId); + System.out.println("ServerTableEntry: state =" + printState()); + System.out.println("ServerTableEntry: message =" + msg); + System.out.println(); + } + + synchronized void activate() throws org.omg.CORBA.SystemException + { + state = ACTIVATED; + + try { + if (debug) + printDebug("activate", "activating server"); + process = Runtime.getRuntime().exec(activationCmd); + } catch (Exception e) { + deActivate(); + if (debug) + printDebug("activate", "throwing premature process exit"); + throw wrapper.unableToStartProcess() ; + } + } + + synchronized void register(Server server) + { + if (state == ACTIVATED) { + + serverObj = server; + + //state = RUNNING; + //notifyAll(); + + if (debug) + printDebug("register", "process registered back"); + + } else { + + if (debug) + printDebug("register", "throwing premature process exit"); + throw wrapper.serverNotExpectedToRegister() ; + } + } + + synchronized void registerPorts( String orbId, EndPointInfo [] endpointList) + throws ORBAlreadyRegistered + { + + // find if the ORB is already registered, then throw an exception + if (orbAndPortInfo.containsKey(orbId)) { + throw new ORBAlreadyRegistered(orbId); + } + + // store all listener ports and their types + List serverListenerPorts = new ArrayList() ; + for (int i = 0; i < endpointList.length; i++) { + serverListenerPorts.add( new EndPointInfo( + endpointList[i].endpointType, endpointList[i].port ) ) ; + + if (debug) + System.out.println("registering type: " + endpointList[i].endpointType + + " port " + endpointList[i].port); + } + + // put this set of listener ports in the HashMap associated + // with the orbId + orbAndPortInfo.put(orbId, serverListenerPorts); + if (state == ACTIVATED) { + state = RUNNING; + notifyAll(); + } + // _REVISIT_, If the state is not equal to ACTIVATED then it is a bug + // need to log that error, once the Logging framework is in place + // for rip-int. + if (debug) + printDebug("registerPorts", "process registered Ports"); + } + + synchronized void install() + { + if (state == RUNNING) + serverObj.install() ; + else + throw wrapper.serverNotRunning() ; + } + + synchronized void uninstall() + { + if (state == RUNNING) { + + deActivate(); + + try { + if (serverObj != null) { + serverObj.shutdown(); // shutdown the server + serverObj.uninstall() ; // call the uninstall + } + + if (process != null) { + process.destroy(); + } + } catch (Exception ex) { + // what kind of exception should be thrown + } + } else { + throw wrapper.serverNotRunning() ; + } + } + + synchronized void holdDown() + { + state = HELD_DOWN; + + if (debug) + printDebug( "holdDown", "server held down" ) ; + + notifyAll(); + } + + synchronized void deActivate() + { + state = DE_ACTIVATED; + + if (debug) + printDebug( "deActivate", "server deactivated" ) ; + + notifyAll(); + } + + synchronized void checkProcessHealth( ) { + // If the State in the ServerTableEntry is RUNNING and the + // Process was shut down abnormally, The method will change the + // server state as De-Activated. + if( state == RUNNING ) { + try { + int exitVal = process.exitValue(); + } catch (IllegalThreadStateException e1) { + return; + } + synchronized ( this ) { + // Clear the PortInformation as it is old + orbAndPortInfo.clear(); + // Move the state to De-Activated, So that the next + // call to this server will re-activate. + deActivate(); + } + } + } + + synchronized boolean isValid() + { + if ((state == ACTIVATING) || (state == HELD_DOWN)) { + if (debug) + printDebug( "isValid", "returns true" ) ; + + return true; + } + + try { + int exitVal = process.exitValue(); + } catch (IllegalThreadStateException e1) { + return true; + } + + if (state == ACTIVATED) { + if (activateRetryCount < ActivationRetryMax) { + if (debug) + printDebug("isValid", "reactivating server"); + activateRetryCount++; + activate(); + return true; + } + + if (debug) + printDebug("isValid", "holding server down"); + + holdDown(); + return true; + } + + deActivate(); + return false; + } + + synchronized ORBPortInfo[] lookup(String endpointType) throws ServerHeldDown + { + while ((state == ACTIVATING) || (state == ACTIVATED)) { + try { + wait(waitTime); + if (!isValid()) break; + } catch(Exception e) {} + } + + ORBPortInfo[] orbAndPortList = null; + + if (state == RUNNING) { + orbAndPortList = new ORBPortInfo[orbAndPortInfo.size()]; + + try { + int numElements = 0; + int i; + int port; + for ( String orbId : orbAndPortInfo.keySet() ) { + // get an entry corresponding to orbId + List serverListenerPorts = orbAndPortInfo.get(orbId); + port = -1; + // return the port corresponding to the endpointType + for (EndPointInfo ep : serverListenerPorts) { + if (debug) + System.out.println("lookup num-ports " + + serverListenerPorts.size() + " " + + ep.endpointType + " " + ep.port ); + if (ep.endpointType.equals(endpointType)) { + port = ep.port; + break; + } + } + orbAndPortList[numElements] = new ORBPortInfo(orbId, port); + numElements++; + } + } catch (NoSuchElementException e) { + // have everything in the table + } + return orbAndPortList; + } + + if (debug) + printDebug("lookup", "throwing server held down error"); + + throw new ServerHeldDown( serverId ) ; + } + + synchronized EndPointInfo[] lookupForORB(String orbId) + throws ServerHeldDown, InvalidORBid + { + while ((state == ACTIVATING) || (state == ACTIVATED)) { + try { + wait(waitTime); + if (!isValid()) break; + } catch(Exception e) {} + } + EndPointInfo[] portList = null; + + if (state == RUNNING) { + try { + // get an entry corresponding to orbId + List serverListenerPorts = orbAndPortInfo.get(orbId); + + portList = new EndPointInfo[serverListenerPorts.size()]; + // return the port corresponding to the endpointType + int i = 0 ; + for (EndPointInfo ep : serverListenerPorts) { + if (debug) + System.out.println("lookup num-ports " + + serverListenerPorts.size() + " " + + ep.endpointType + " " + ep.port ); + portList[i] = new EndPointInfo(ep.endpointType, ep.port); + } + } catch (NoSuchElementException e) { + // no element in HashMap corresponding to ORBid found + throw new InvalidORBid(); + } + + return portList; + } + + if (debug) + printDebug("lookup", "throwing server held down error"); + + throw new ServerHeldDown( serverId ) ; + } + + synchronized String[] getORBList() + { + String [] orbList = new String[orbAndPortInfo.size()]; + + try { + int numElements = 0; + for ( String orbId : orbAndPortInfo.keySet() ) { + orbList[numElements++] = orbId ; + } + } catch (NoSuchElementException e) { + // have everything in the table + } + return orbList; + } + + int getServerId() + { + return serverId; + } + + boolean isActive() + { + return (state == RUNNING) || (state == ACTIVATED); + } + + synchronized void destroy() + { + + deActivate(); + + try { + if (serverObj != null) + serverObj.shutdown(); + + if (debug) + printDebug( "destroy", "server shutdown successfully" ) ; + } catch (Exception ex) { + if (debug) + printDebug( "destroy", + "server shutdown threw exception" + ex ) ; + // ex.printStackTrace(); + } + + try { + if (process != null) + process.destroy(); + + if (debug) + printDebug( "destroy", "process destroyed successfully" ) ; + } catch (Exception ex) { + if (debug) + printDebug( "destroy", + "process destroy threw exception" + ex ) ; + + // ex.printStackTrace(); + } + } + + private boolean debug = false; +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerTool.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerTool.java new file mode 100644 index 000000000..5173ded24 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/activation/ServerTool.java @@ -0,0 +1,954 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.activation; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.util.List; +import java.util.ArrayList; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.CompletionStatus; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.CorbaResourceUtil; +import com.sun.corba.ee.spi.activation.*; +import com.sun.corba.ee.spi.activation.ServerHeldDown; +import com.sun.corba.ee.spi.activation.RepositoryPackage.ServerDef; +import com.sun.corba.ee.spi.activation.LocatorPackage.ServerLocation; +import com.sun.corba.ee.spi.activation.LocatorPackage.ServerLocationPerORB; + +/** + * + * @version 1.7, 97/10/19 + * @author Anita Jindal + * @since JDK1.3 + */ +public class ServerTool +{ + final static String helpCommand = "help"; + final static String toolName = "servertool"; + final static String commandArg = "-cmd"; + + static int getServerIdForAlias( ORB orb, String applicationName ) throws ServerNotRegistered + { + try { + Repository rep = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME ) ) ; + int serverid = rep.getServerID(applicationName); + + return rep.getServerID( applicationName ) ; + } catch (Exception ex) { + throw (new ServerNotRegistered()); + } + } + + void run(String[] args) + { + String[] cmd = null; + + // if command specified in the args, get it + for (int i=0; i < args.length; i++) { + + if (args[i].equals(commandArg)) { + // get the command + int cmdLen = args.length - i - 1; + cmd = new String[cmdLen]; + for (int j=0; j < cmdLen; j++) cmd[j] = args[++i]; + + break; + } + } + + try { + // create the POA ORB + Properties props = System.getProperties() ; + props.put("org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ); + orb = (ORB) ORB.init(args, props); + + // if command specified in the args, process it + if (cmd != null) executeCommand(cmd); + else { // process commands interactively + + // create a buffered reader to read commands from standard in + BufferedReader in = new + BufferedReader(new InputStreamReader(System.in)); + + // print tool banner + System.out.println(CorbaResourceUtil.getText("servertool.banner")); + + // process commands until user quits + while (true) { + cmd = readCommand(in); + if (cmd != null) executeCommand(cmd); + else printAvailableCommands(); + } + } + } catch (Exception ex) { + System.out.println(CorbaResourceUtil.getText("servertool.usage", "servertool")); + System.out.println(); + ex.printStackTrace(); + } + } + + public static void main(String[] args) + { + ServerTool tool = new ServerTool(); + tool.run(args); + } + + String[] readCommand(BufferedReader in) + { + System.out.print(toolName + " > "); + + try { + int i = 0; + String cmd[] = null; + + String cmdLine = in.readLine(); + + if (cmdLine != null) { + StringTokenizer st = new StringTokenizer(cmdLine); + if (st.countTokens() != 0) { + cmd = new String[st.countTokens()]; + while (st.hasMoreTokens()) cmd[i++] = st.nextToken(); + } + } + + return cmd; + } catch (Exception ex) { + System.out.println(CorbaResourceUtil.getText("servertool.usage", "servertool")); + System.out.println(); + ex.printStackTrace(); + } + + return null; + } + + void printAvailableCommands() + { + // print short help + System.out.println(CorbaResourceUtil.getText("servertool.shorthelp")); + + for ( CommandHandler handler : handlers ) { + System.out.print("\t" + handler.getCommandName()); + for (int j=handler.getCommandName().length(); + j < maxNameLen; j++) System.out.print(" "); + System.out.print(" - "); + handler.printCommandHelp(System.out, + CommandHandler.shortHelp); + } + + System.out.println(); + } + + void executeCommand(String[] cmd) + { + boolean result; + + // handle the help command + if (cmd[0].equals(helpCommand)) { + if (cmd.length == 1) + printAvailableCommands(); + else { + // print long help for a specific command + for ( CommandHandler handler : handlers ) { + if (handler.getCommandName().equals(cmd[1])) { + handler.printCommandHelp(System.out, + CommandHandler.longHelp); + } + } + } + + return; + } + + // determine the subcommand and execute it + for ( CommandHandler handler : handlers ) { + if (handler.getCommandName().equals(cmd[0])) { + String[] cmdArgs = new String[cmd.length - 1]; + + // construct args to the command + for (int j=0; j < cmdArgs.length; j++) + cmdArgs[j] = cmd[j+1]; + + // execute the command + try { + System.out.println(); + + result = handler.processCommand(cmdArgs, orb, System.out); + + if (result == CommandHandler.parseError) { + handler.printCommandHelp(System.out, + CommandHandler.longHelp); + } + + System.out.println(); + + } catch (Exception ex) {} + + return; + } + } + + // unknown command - print available commands + printAvailableCommands(); + } + + final private static boolean debug = false; + + ORB orb = null; + + static List handlers; + static int maxNameLen; + + static { + handlers = new ArrayList(); + handlers.add(new RegisterServer()); + handlers.add(new UnRegisterServer()); + handlers.add(new GetServerID()); + handlers.add(new ListServers()); + handlers.add(new ListAliases()); + handlers.add(new ListActiveServers()); + handlers.add(new LocateServer()); + handlers.add(new LocateServerForORB()); + handlers.add(new ListORBs()); + handlers.add(new ShutdownServer()); + handlers.add(new StartServer()); + handlers.add(new Help()); + handlers.add(new Quit()); + + // determine longest command name + maxNameLen = 0; + for ( CommandHandler handler : handlers ) { + int cmdNameLen = handler.getCommandName().length(); + if (cmdNameLen > maxNameLen) + maxNameLen = cmdNameLen; + } + } +} + +class RegisterServer implements CommandHandler +{ + public String getCommandName() {return "register";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.register")); + } else { + out.println(CorbaResourceUtil.getText("servertool.register1")); + } + } + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int i=0; + String applicationName = ""; + String name = ""; + String classpath = ""; + String args = ""; + String vmargs = ""; + int serverId = 0; + + // parse register server command + String arg; + while (i < cmdArgs.length) { + + arg = cmdArgs[i++]; + + if (arg.equals("-server")) { + if (i < cmdArgs.length) name = cmdArgs[i++]; + else return parseError; + } else if (arg.equals("-applicationName")) { + if (i < cmdArgs.length) applicationName = cmdArgs[i++]; + else return parseError; + } else if (arg.equals("-classpath")) { + if (i < cmdArgs.length) classpath = cmdArgs[i++]; + else return parseError; + } else if (arg.equals("-args")) { + while ((i < cmdArgs.length) && !cmdArgs[i].equals("-vmargs")){ + args = args.equals("") ? cmdArgs[i] : + args + " " + cmdArgs[i]; + i++; + } + if (args.equals("")) return parseError; + } else if (arg.equals("-vmargs")) { + while ((i < cmdArgs.length) && !cmdArgs[i].equals("-args")){ + vmargs = vmargs.equals("") ? cmdArgs[i] : + vmargs + " " + cmdArgs[i]; + i++; + } + if (vmargs.equals("")) return parseError; + } else return parseError; + } + + // minimally the server class name has to be specified + if (name.equals("")) return parseError; + + // register server and activate it + try { + // register the server with the repository + Repository repository = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME )); + + ServerDef server = new ServerDef(applicationName, name, classpath, args, vmargs); + serverId = repository.registerServer(server); + + // activate the server + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + activator.activate(serverId); + activator.install(serverId); + + // print success message + out.println(CorbaResourceUtil.getText("servertool.register2", serverId)); + } catch (ServerNotRegistered ex) { + } catch (ServerAlreadyActive ex) { + } catch (ServerHeldDown ex) { + out.println(CorbaResourceUtil.getText("servertool.register3", serverId)); + } catch (ServerAlreadyRegistered ex) { + out.println(CorbaResourceUtil.getText("servertool.register4", serverId)); + } catch (BadServerDefinition ex) { + out.println(CorbaResourceUtil.getText("servertool.baddef", ex.reason)); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class UnRegisterServer implements CommandHandler +{ + public String getCommandName() {return "unregister";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.unregister")); + } else { + out.println(CorbaResourceUtil.getText("servertool.unregister1")); + } +} + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int serverId = illegalServerId; + + try { + if (cmdArgs.length == 2) { + if (cmdArgs[0].equals("-serverid")) + serverId = (Integer.valueOf(cmdArgs[1])).intValue(); + else if (cmdArgs[0].equals("-applicationName")) + serverId = ServerTool.getServerIdForAlias( orb, cmdArgs[1] ) ; + } + + // the server id has to be specified + if (serverId == illegalServerId) + return parseError; + + // deactivate server, hold it down and and unregister it + // deactivate the server + try { + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + activator.uninstall(serverId); + } catch (ServerHeldDown ex) {} + + // unregister the server from the repository + Repository repository = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME )); + repository.unregisterServer(serverId); + + // print success message + out.println(CorbaResourceUtil.getText("servertool.unregister2")); + } catch (ServerNotRegistered ex) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class LocateServer implements CommandHandler +{ + public String getCommandName() {return "locate";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.locate")); + } else { + out.println(CorbaResourceUtil.getText("servertool.locate1")); + } + } + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int serverId = illegalServerId; + + String endPointType = IIOP_CLEAR_TEXT.value; + try { + + // parse command + String arg; + int i = 0; + while (i < cmdArgs.length) { + + arg = cmdArgs[i++]; + + if (arg.equals("-serverid")) { + if (i < cmdArgs.length) + serverId = (Integer.valueOf(cmdArgs[i++])).intValue(); + else + return parseError; + } else if (arg.equals("-applicationName")) { + if (i < cmdArgs.length) + serverId = ServerTool.getServerIdForAlias( orb, cmdArgs[i++] ) ; + else + return parseError; + } else if (arg.equals("-endpointType")) { + if (i < cmdArgs.length) + endPointType = cmdArgs[i++]; + } + } + + // the server id has to be specified + if (serverId == illegalServerId) + return parseError; + + // locate the server + // deactivate the server + Locator locator = LocatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_LOCATOR_NAME )); + + ServerLocation location = locator.locateServer(serverId, endPointType); + + // print success message + out.println(CorbaResourceUtil.getText("servertool.locate2", location.hostname)); + int numEntries = location.ports.length; + for (i = 0; i < numEntries; i++) { + ORBPortInfo orbPort = location.ports[i]; + out.println("\t\t"+ orbPort.port + "\t\t" + endPointType + "\t\t" + orbPort.orbId ); + } + } catch (NoSuchEndPoint ex) { + } catch (ServerHeldDown ex) { + out.println(CorbaResourceUtil.getText("servertool.helddown")); + } catch (ServerNotRegistered ex) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class LocateServerForORB implements CommandHandler +{ + public String getCommandName() {return "locateperorb";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.locateorb")); + } else { + out.println(CorbaResourceUtil.getText("servertool.locateorb1")); + } + } + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int serverId = illegalServerId; + + String orbId = ""; + try { + + // parse command + String arg; + int i = 0; + while (i < cmdArgs.length) { + + arg = cmdArgs[i++]; + + if (arg.equals("-serverid")) { + if (i < cmdArgs.length) + serverId = (Integer.valueOf(cmdArgs[i++])).intValue(); + else + return parseError; + } else if (arg.equals("-applicationName")) { + if (i < cmdArgs.length) + serverId = ServerTool.getServerIdForAlias( orb, cmdArgs[i++] ) ; + else + return parseError; + } else if (arg.equals("-orbid")) { + if (i < cmdArgs.length) + orbId = cmdArgs[i++]; + } + } + + // the server id has to be specified + if (serverId == illegalServerId) + return parseError; + + // locate the server + // deactivate the server + Locator locator = LocatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_LOCATOR_NAME )); + + ServerLocationPerORB location = locator.locateServerForORB(serverId, + orbId); + + // print success message + out.println(CorbaResourceUtil.getText("servertool.locateorb2", location.hostname)); + int numEntries = location.ports.length; + for (i = 0; i < numEntries; i++) { + EndPointInfo Port = location.ports[i]; + out.println("\t\t"+ Port.port + "\t\t" + Port.endpointType + "\t\t" + orbId ); + } + } catch (InvalidORBid ex) { + out.println(CorbaResourceUtil.getText("servertool.nosuchorb")); + } catch (ServerHeldDown ex) { + out.println(CorbaResourceUtil.getText("servertool.helddown")); + } catch (ServerNotRegistered ex) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class GetServerID implements CommandHandler +{ + public String getCommandName() {return "getserverid" ; } + + public void printCommandHelp( PrintStream out, boolean helpType ) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.getserverid")); + } else { + out.println(CorbaResourceUtil.getText("servertool.getserverid1")); + } + } + + public boolean processCommand( String[] cmdArgs, ORB orb, PrintStream out ) + { + if ((cmdArgs.length == 2) && cmdArgs[0].equals( "-applicationName" )) { + String str = (String)cmdArgs[1] ; + + try { + Repository repository = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME )); + + try { + int result = repository.getServerID( str ) ; + out.println() ; + out.println(CorbaResourceUtil.getText("servertool.getserverid2", str, Integer.toString(result))); + out.println() ; + } catch (ServerNotRegistered e) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } + } catch (Exception ex) { + ex.printStackTrace() ; + } + + return commandDone ; + } else + return parseError ; + } +} + +class ListServers implements CommandHandler +{ + public String getCommandName() {return "list";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.list")); + } else { + out.println(CorbaResourceUtil.getText("servertool.list1")); + } + } + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int serverId = illegalServerId; + boolean listOneServer = false; + ServerDef serverDef; + + // determine if list single server or all servers + listOneServer = (cmdArgs.length!=0) ; + if ((cmdArgs.length == 2) && cmdArgs[0].equals("-serverid")) + serverId = (Integer.valueOf(cmdArgs[1])).intValue(); + + if ((serverId == illegalServerId) && listOneServer) + return parseError; + + // process the list server command + try { + Repository repository = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME )); + + if (listOneServer) { + + try { + serverDef = repository.getServer(serverId); + out.println(); + printServerDef(serverDef, serverId, out); + out.println(); + } catch (ServerNotRegistered e) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } + + } else { + int[] servers = repository.listRegisteredServers(); + out.println(CorbaResourceUtil.getText("servertool.list2")); + + sortServers(servers); + for (int i=0; i < servers.length; i++) { + try { + serverDef = repository.getServer(servers[i]); + out.println("\t " + servers[i] + "\t\t" + + serverDef.serverName + "\t\t" + + serverDef.applicationName); + } catch (ServerNotRegistered e) {} + } + + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } + +static void printServerDef(ServerDef serverDef, int serverId, + PrintStream out) +{ + out.println(CorbaResourceUtil.getText("servertool.appname", serverDef.applicationName)); + out.println(CorbaResourceUtil.getText("servertool.name", serverDef.serverName)); + out.println(CorbaResourceUtil.getText("servertool.classpath", serverDef.serverClassPath)); + out.println(CorbaResourceUtil.getText("servertool.args", serverDef.serverArgs)); + out.println(CorbaResourceUtil.getText("servertool.vmargs", serverDef.serverVmArgs)); + out.println(CorbaResourceUtil.getText("servertool.serverid", serverId)); +} + +/** + * Do a simple bubble sort to sort the server ids in ascending + * order. + */ +static void sortServers(int[] serverIds) +{ + int size = serverIds.length; + int lowest; + + for (int i=0; i < size; i++) { + + lowest = i; + + for (int j=i+1; j < size; j++) { + if (serverIds[j] < serverIds[lowest]) lowest = j; + } + + if (lowest != i) { + int temp = serverIds[i]; + serverIds[i] = serverIds[lowest]; + serverIds[lowest] = temp; + } + } +} +} + +class ListActiveServers implements CommandHandler +{ + public String getCommandName() {return "listactive";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.listactive")); + } else { + out.println(CorbaResourceUtil.getText("servertool.listactive1")); + } + } + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + ServerDef serverDef; + + // process the list active servers command + try { + Repository repository = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME )); + + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + + int[] servers = activator.getActiveServers(); + + out.println(CorbaResourceUtil.getText("servertool.list2")); + + ListServers.sortServers(servers); + for (int i=0; i < servers.length; i++) { + try { + serverDef = repository.getServer(servers[i]); + out.println("\t " + servers[i] + "\t\t" + + serverDef.serverName + "\t\t" + + serverDef.applicationName); + } catch (ServerNotRegistered e) {} + } + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class ListAliases implements CommandHandler +{ + public String getCommandName() {return "listappnames";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.listappnames")); + } else { + out.println(CorbaResourceUtil.getText("servertool.listappnames1")); + } + } + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + try { + Repository repository = RepositoryHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_REPOSITORY_NAME )); + + String[] applicationNames = repository.getApplicationNames(); + + out.println(CorbaResourceUtil.getText("servertool.listappnames2")); + out.println(); + for (int i=0; i < applicationNames.length; i++) + out.println( "\t" + applicationNames[i] ) ; + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class ShutdownServer implements CommandHandler +{ + public String getCommandName() {return "shutdown";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.shutdown")); + } else { + out.println(CorbaResourceUtil.getText("servertool.shutdown1")); + } + } + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int serverId = illegalServerId; + + try { + // determine the server id + if (cmdArgs.length == 2) + if (cmdArgs[0].equals("-serverid")) + serverId = (Integer.valueOf(cmdArgs[1])).intValue(); + else if (cmdArgs[0].equals("-applicationName")) + serverId = ServerTool.getServerIdForAlias( orb, cmdArgs[1] ) ; + + if (serverId == illegalServerId) + return parseError; + + // shutdown the server + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + activator.shutdown(serverId); + + out.println(CorbaResourceUtil.getText("servertool.shutdown2")); + } catch (ServerNotActive ex) { + out.println(CorbaResourceUtil.getText("servertool.servernotrunning")); + } catch (ServerNotRegistered ex) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} + +class StartServer implements CommandHandler +{ + public String getCommandName() {return "startup";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.startserver")); + } else { + out.println(CorbaResourceUtil.getText("servertool.startserver1")); + } + } + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + int serverId = illegalServerId; + + try { + // determine the server id + if (cmdArgs.length == 2) + if (cmdArgs[0].equals("-serverid")) + serverId = (Integer.valueOf(cmdArgs[1])).intValue(); + else if (cmdArgs[0].equals("-applicationName")) + serverId = ServerTool.getServerIdForAlias( orb, cmdArgs[1] ) ; + + if (serverId == illegalServerId) + return parseError; + + // startup the server + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + activator.activate(serverId); + + out.println(CorbaResourceUtil.getText("servertool.startserver2")); + } catch (ServerNotRegistered ex) { + out.println(CorbaResourceUtil.getText("servertool.nosuchserver")); + } catch (ServerAlreadyActive ex) { + out.println(CorbaResourceUtil.getText("servertool.serverup")); + } catch (ServerHeldDown ex) { + out.println(CorbaResourceUtil.getText("servertool.helddown")); + } catch (Exception ex) { + ex.printStackTrace(); + } + return commandDone; + } +} + +class Quit implements CommandHandler +{ + public String getCommandName() {return "quit";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.quit")); + } else { + out.println(CorbaResourceUtil.getText("servertool.quit1")); + } + } + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + System.exit(0); + + return commandDone; + } +} + +class Help implements CommandHandler +{ + public String getCommandName() {return "help";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.help")); + } else { + out.println(CorbaResourceUtil.getText("servertool.help1")); + } + } + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + return commandDone; + } +} + +class ListORBs implements CommandHandler +{ + public String getCommandName() {return "orblist";} + + public void printCommandHelp(PrintStream out, boolean helpType) + { + if (helpType == longHelp) { + out.println(CorbaResourceUtil.getText("servertool.orbidmap")); + } else { + out.println(CorbaResourceUtil.getText("servertool.orbidmap1")); + } + } + + final static int illegalServerId = -1; + + public boolean processCommand(String[] cmdArgs, ORB orb, PrintStream out) + { + + int serverId = illegalServerId; + + try { + if (cmdArgs.length == 2) { + if (cmdArgs[0].equals("-serverid")) + serverId = (Integer.valueOf(cmdArgs[1])).intValue(); + else if (cmdArgs[0].equals("-applicationName")) + serverId = ServerTool.getServerIdForAlias( orb, cmdArgs[1] ) ; + } + + // the server id has to be specified + if (serverId == illegalServerId) + return parseError; + // activate the server + Activator activator = ActivatorHelper.narrow( + orb.resolve_initial_references( ORBConstants.SERVER_ACTIVATOR_NAME )); + + String[] orbList = activator.getORBNames(serverId); + + out.println(CorbaResourceUtil.getText("servertool.orbidmap2")); + + for (int i = 0; i < orbList.length ; i++) { + out.println("\t "+ orbList[i]); + } + } catch (ServerNotRegistered ex) { + out.println("\tno such server found."); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return commandDone; + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/InternalBindingKey.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/InternalBindingKey.java new file mode 100644 index 000000000..d605eea8a --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/InternalBindingKey.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + +import java.io.Serializable; +import org.omg.CosNaming.NameComponent; + + +/** + * Class InternalBindingKey implements the necessary wrapper code + * around the org.omg.CosNaming::NameComponent class to implement the proper + * equals() method and the hashCode() method for use in a hash table. + * It computes the hashCode once and stores it, and also precomputes + * the lengths of the id and kind strings for faster comparison. + */ +public class InternalBindingKey + implements Serializable +{ + + // computed by serialver tool + private static final long serialVersionUID = -5410796631793704055L; + + public String id; + public String kind; + + // Default Constructor + public InternalBindingKey() {} + + // Normal constructor + public InternalBindingKey(NameComponent n) + { + setup(n); + } + + // Setup the object + protected void setup(NameComponent n) { + this.id = n.id; + this.kind = n.kind; + } + + // Compare the keys by comparing name's id and kind + public boolean equals(java.lang.Object o) { + if (o == null) + return false; + if (o instanceof InternalBindingKey) { + InternalBindingKey that = (InternalBindingKey)o; + if( this.id != null && that.id != null ) + { + if (this.id.length() != that.id.length() ) + { + return false; + } + // If id is set is must be equal + if (this.id.length() > 0 && this.id.equals(that.id) == false) + { + return false; + } + } + else + { + // If One is Null and the other is not then it's a mismatch + // So, return false + if( ( this.id == null && that.id != null ) + || ( this.id !=null && that.id == null ) ) + { + return false; + } + } + if( this.kind != null && that.kind != null ) + { + if (this.kind.length() != that.kind.length() ) + { + return false; + } + // If kind is set it must be equal + if (this.kind.length() > 0 && this.kind.equals(that.kind) == false) + { + return false; + } + } + else + { + // If One is Null and the other is not then it's a mismatch + // So, return false + if( ( this.kind == null && that.kind != null ) + || ( this.kind !=null && that.kind == null ) ) + { + return false; + } + } + // We have checked all the possibilities, so return true + return true; + } else { + return false; + } + } + + + // Return precomputed value + public int hashCode() { + int hashVal = 0; + if (this.id.length() > 0) + { + hashVal += this.id.hashCode(); + } + if (this.kind.length() > 0) + { + hashVal += this.kind.hashCode(); + } + return hashVal; + } +} + diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/InternalBindingValue.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/InternalBindingValue.java new file mode 100644 index 000000000..b43ef0900 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/InternalBindingValue.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + +import org.omg.CosNaming.BindingType; +import java.io.Serializable; + +/** + * Class InternalBindingKey acts as a container for two objects, namely + * a org.omg.CosNaming::Binding and an CORBA object reference, which are the two + * components associated with the binding. + */ +public class InternalBindingValue + implements Serializable +{ + private static final long serialVersionUID = -2545360261776178726L; + + public BindingType theBindingType; + // The value stores both Stringified Object Reference and + // Non-Stringified Object Reference. This is done to avoid + // calling orb.string_to_object( ) everytime. Instead it + // will be set once and then the result will be used everytime. + public String strObjectRef; + transient private org.omg.CORBA.Object theObjectRef; + + // Default constructor + public InternalBindingValue() { + } + + // Normal constructor + public InternalBindingValue(BindingType b, String o) { + // Objectreference or Context + theBindingType = b; + strObjectRef = o; + } + + public org.omg.CORBA.Object getObjectRef( ) + { + return theObjectRef; + } + + public void setObjectRef( org.omg.CORBA.Object ObjectRef ) + { + theObjectRef = ObjectRef; + } + +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NameServer.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NameServer.java new file mode 100644 index 000000000..d8f341ff3 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NameServer.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + +import java.io.File; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.CorbaResourceUtil; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.activation.InitialNameService; +import com.sun.corba.ee.spi.activation.InitialNameServiceHelper; +import org.omg.CosNaming.NamingContext; +/** + * Class NameServer is a standalone application which + * implements a persistent and a transient name service. + * It uses the PersistentNameService and TransientNameService + * classes for the name service implementation. + * + * @version 1.1, 99/10/07 + * @author Hemanth Puttaswamy + * @since JDK1.2 + */ + +public class NameServer +{ + private ORB orb; + + private File dbDir; // name server database directory + + private final static String dbName = "names.db"; + + public static void main(String args[]) + { + NameServer ns = new NameServer(args); + ns.run(); + } + + protected NameServer(String args[]) + { + // create the ORB Object + java.util.Properties props = System.getProperties(); + props.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "1000" ) ; + props.put("org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + orb = (ORB) org.omg.CORBA.ORB.init(args,props); + + // set up the database directory + String dbDirName = props.getProperty( ORBConstants.DB_DIR_PROPERTY ) + + props.getProperty("file.separator") + dbName + + props.getProperty("file.separator"); + + dbDir = new File(dbDirName); + if (!dbDir.exists()) { + boolean result = dbDir.mkdir(); + if (!result) { + throw new RuntimeException( "Could not create directory " + + dbDirName ) ; + } + } + } + + protected void run() + { + try { + + // create the persistent name service + NameService ns = new NameService(orb, dbDir); + + // add root naming context to initial naming + NamingContext rootContext = ns.initialNamingContext(); + InitialNameService ins = InitialNameServiceHelper.narrow( + orb.resolve_initial_references( + ORBConstants.INITIAL_NAME_SERVICE_NAME )); + ins.bind( "NameService", rootContext, true); + System.out.println(CorbaResourceUtil.getText("pnameserv.success")); + + // wait for invocations + orb.run(); + + } catch (Exception ex) { + + ex.printStackTrace(System.err); + } + } + +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NameService.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NameService.java new file mode 100644 index 000000000..5ea2d9647 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NameService.java @@ -0,0 +1,196 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + +import java.io.File; + +import org.omg.CORBA.Policy; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.PortableServer.*; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** + * @version 1.3, 00/04/06 + * @author Hemanth Puttaswamy + * @since JDK1.2 + */ + +public class NameService +{ + private NamingContext rootContext = null; + private POA nsPOA = null; + private ServantManagerImpl contextMgr; + private ORB theorb; + + /** + * Create NameService which starts the Root Naming Context in Persistent CosNaming + * @param orb an ORB object. + * @param logDir a File + * @exception java.lang.Exception a Java exception. + */ + public NameService(ORB orb, File logDir) + throws Exception + { + theorb = orb; + + // Moved this to the creation of the ORB that is passed into this + // constructor. + // + // This is required for creating Persistent Servants under this ORB + // Right now the Persistent NameService and ORBD are launched together + // Find out a better way of doing this, Since ORBD is an important + // process which should not be killed because of some external process + // orb.setPersistentServerId( (int) 1000 ); + + // get and activate the root naming POA + POA rootPOA = (POA)orb.resolve_initial_references( + ORBConstants.ROOT_POA_NAME ) ; + rootPOA.the_POAManager().activate(); + + // create a new POA for persistent Naming Contexts + // With Non-Retain policy, So that every time Servant Manager + // will be contacted when the reference is made for the context + // The id assignment is made by the NameServer, The Naming Context + // id's will be in the format NC + int i=0; + Policy[] poaPolicy = new Policy[4]; + poaPolicy[i++] = rootPOA.create_lifespan_policy( + LifespanPolicyValue.PERSISTENT); + poaPolicy[i++] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + poaPolicy[i++] = rootPOA.create_id_assignment_policy( + IdAssignmentPolicyValue.USER_ID); + poaPolicy[i++] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN); + + + nsPOA = rootPOA.create_POA("NameService", null, poaPolicy); + nsPOA.the_POAManager().activate( ); + + // create and set the servant manager + contextMgr = new + ServantManagerImpl(orb, logDir, this ); + + // The RootObject key will be NC0 + String rootKey = contextMgr.getRootObjectKey( ); + // initialize the root Naming Context + NamingContextImpl nc = + new NamingContextImpl( orb, rootKey, this, contextMgr ); + nc = contextMgr.addContext( rootKey, nc ); + nc.setServantManagerImpl( contextMgr ); + nc.setORB( orb ); + nc.setRootNameService( this ); + + nsPOA.set_servant_manager(contextMgr); + rootContext = NamingContextHelper.narrow( + nsPOA.create_reference_with_id( rootKey.getBytes( ), + NamingContextHelper.id( ) ) ); + } + + /** + * This method returns the Root Naming Context + * @return root naming context + */ + public NamingContext initialNamingContext() + { + return rootContext; + } + + /** + * This method returns nsPOA which is the only POA that we use for + * Persistent Naming Contexts. + */ + POA getNSPOA( ) { + return nsPOA; + } + + + /** + * This method creates a NewContext, This will be internally invoked from + * NamingContextImpl. It is not a public API. NewContext is in this class + * because a persitent reference has to be created with Persistent NameService + * POA. + * @return new naming context + */ + public NamingContext newContext( ) { + try { + // Get the new Naming Context Key from + // the ServantManager + String newKey = contextMgr.getNewObjectKey( ); + // Create the new Naming context and create the Persistent + // reference + NamingContextImpl theContext = new NamingContextImpl( theorb, + newKey, this, contextMgr ); + NamingContextImpl tempContext = contextMgr.addContext( newKey, + theContext ); + if( tempContext != null ) { + theContext = tempContext; + } + // If the context is read from the File, The following three entries + // will be null. So a fresh setup may be required. + theContext.setServantManagerImpl( contextMgr ); + theContext.setORB( theorb ); + theContext.setRootNameService( this ); + NamingContext theNewContext = + NamingContextHelper.narrow( + nsPOA.create_reference_with_id( newKey.getBytes( ), + NamingContextHelper.id( )) ); + return theNewContext; + } catch( org.omg.CORBA.SystemException e ) { + throw e; + } catch( java.lang.Exception e ) { + //throw e; + } + + return null; + } + + /** getObjectReferenceFromKey returns the Object reference from the objectkey + * using POA.create_reference_with_id method. + * @param Object Key as String + * @returns reference an CORBA.Object. + */ + org.omg.CORBA.Object getObjectReferenceFromKey( String key ) { + org.omg.CORBA.Object theObject = null; + try { + theObject = nsPOA.create_reference_with_id( key.getBytes( ), NamingContextHelper.id( ) ); + } catch (Exception e ) { + theObject = null; + } + + return theObject; + } + + /** + * getObjectKey gets the Object Key from the reference using POA.reference_to_id method + * @param reference an CORBA.Object. + * @returns Object Key as String + */ + String getObjectKey( org.omg.CORBA.Object reference ) { + byte theId[]; + try { + theId = nsPOA.reference_to_id( reference ); + } catch( org.omg.PortableServer.POAPackage.WrongAdapter e ) { + return null; + } catch( org.omg.PortableServer.POAPackage.WrongPolicy e ) { + return null; + } catch( Exception e ) { + return null; + } + + String theKey = new String( theId ); + return theKey; + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NamingContextImpl.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NamingContextImpl.java new file mode 100644 index 000000000..fa5bb759d --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/NamingContextImpl.java @@ -0,0 +1,1278 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + + +import org.omg.CORBA.Object; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.PortableServer.IdAssignmentPolicyValue; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; + +import com.sun.corba.ee.impl.naming.cosnaming.NamingContextDataStore; +import com.sun.corba.ee.impl.naming.cosnaming.NamingUtils; + +import com.sun.corba.ee.impl.naming.namingutil.INSURLHandler; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.logging.NamingSystemException; +import com.sun.corba.ee.spi.trace.Naming; +import java.io.IOException; +import java.io.ObjectInputStream; + +import java.io.Serializable; +import java.util.Hashtable; + +/** + * Class NamingContextImpl implements the org.omg.CosNaming::NamingContext and + * NamingContextExt interface. + *

+ * The operations bind(), rebind(), bind_context() and rebind_context() + * are all really implemented by doBind(). resolve() is really implemented + * by doResolve(), unbind() by doUnbind(). list(), new_context() and + * destroy() uses the NamingContextDataStore interface directly. All the + * doX() methods are public static. + * They synchronize on the NamingContextDataStore object. + *

+ * None of the methods here are Synchronized because These methods will be + * invoked from Super class's doBind( ), doResolve( ) which are already + * Synchronized. + */ + + +@Naming +public class NamingContextImpl extends NamingContextExtPOA + implements NamingContextDataStore, Serializable { + + private static final long serialVersionUID = -2162298692680847808L; + + // The ORB is required to do string_to_object() operations + // All the references are stored in the files in the form of IOR strings + private transient ORB orb; + + // The ObjectKey will be in the format NC which uniquely identifies + // The NamingContext internaly + private final String objKey; + + // Hash table contains all the entries in the NamingContexts. The + // CORBA.Object references will be stored in the form of IOR strings + // and the Child Naming Contexts will have its key as the entry in the + // table. This table is written into File everytime an update is made + // on this context. + private final Hashtable theHashtable = new Hashtable( ); + + // The NameServiceHandle is required to get the ObjectId from the + // NamingContext's references. These references are created using + // POA in the NameService. + private transient NameService theNameServiceHandle; + + // ServantManager is the single point of contact to Read, Write and + // Update the NamingContextFile + private transient ServantManagerImpl theServantManagerImplHandle; + + // All the INS (Interoperable Naming Service) methods are defined in this class + // All the calls to INS will be delegated to this class. + private transient com.sun.corba.ee.impl.naming.cosnaming.InterOperableNamingImpl insImpl; + + private transient NamingSystemException wrapper = + NamingSystemException.self ; + + private static POA biPOA = null; + + // Defined so that we can get FindBugs to shut up about the transient fields. + // The various setYYY methods are called in ServantManagerImpl to correctly + // re-set the transient fields after deserialization. + private void readObject( ObjectInputStream is ) + throws IOException, ClassNotFoundException { + is.defaultReadObject() ; + + // The following fields are restored by the setYYY methods. + orb = null ; + theNameServiceHandle = null ; + theServantManagerImplHandle = null ; + + insImpl = + new com.sun.corba.ee.impl.naming.cosnaming.InterOperableNamingImpl(); + } + + /** + * Create a naming context servant. + * Runs the super constructor. + * @param orb an ORB object. + * @param objKey as String + * @param theNameService as NameService + * @param theServantManagerImpl as ServantManagerImpl + * @exception java.lang.Exception a Java exception. + */ + + public NamingContextImpl(ORB orb, String objKey, + NameService theNameService, ServantManagerImpl theServantManagerImpl ) + throws Exception + { + super(); + + setORB( orb ) ; + + this.objKey = objKey; + theNameServiceHandle = theNameService; + theServantManagerImplHandle = theServantManagerImpl; + insImpl = + new com.sun.corba.ee.impl.naming.cosnaming.InterOperableNamingImpl(); + } + + @Naming + public void setRootNameService( NameService theNameService ) { + theNameServiceHandle = theNameService; + } + + @Naming + public void setORB( ORB theOrb ) { + this.orb = theOrb ; + } + + @Naming + public void setServantManagerImpl( + ServantManagerImpl theServantManagerImpl ) + { + theServantManagerImplHandle = theServantManagerImpl; + } + + @Naming + public POA getNSPOA( ) { + return theNameServiceHandle.getNSPOA( ); + } + + /** + * Bind an object under a name in this NamingContext. If the name + * contains multiple (n) components, n-1 will be resolved in this + * NamingContext and the object bound in resulting NamingContext. + * An exception is thrown if a binding with the supplied name already + * exists. If the + * object to be bound is a NamingContext it will not participate in + * a recursive resolve. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound The supplied name + * is already bound. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see doBind + */ + @Naming + public void bind(NameComponent[] n, org.omg.CORBA.Object obj) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, + org.omg.CosNaming.NamingContextPackage.AlreadyBound + { + if( obj == null ) { + throw wrapper.objectIsNull() ; + } + + // doBind implements all four flavors of binding + NamingContextDataStore impl = (NamingContextDataStore)this; + doBind(impl,n,obj,false,BindingType.nobject); + } + + /** + * Bind a NamingContext under a name in this NamingContext. If the name + * contains multiple (n) components, n-1 will be resolved in this + * NamingContext and the object bound in resulting NamingContext. + * An exception is thrown if a binding with the supplied name already + * exists. The NamingContext will participate in recursive resolving. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param nc the NamingContect object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object is + * already bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see doBind + */ + @Naming + public void bind_context(NameComponent[] n, NamingContext nc) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, + org.omg.CosNaming.NamingContextPackage.AlreadyBound + { + if( nc == null ) { + throw wrapper.objectIsNull() ; + } + // doBind implements all four flavors of binding + NamingContextDataStore impl = (NamingContextDataStore)this; + doBind(impl,n,nc,false,BindingType.ncontext); + } + + /** + * Bind an object under a name in this NamingContext. If the name + * contains multiple (n) components, n-1 will be resolved in this + * NamingContext and the object bound in resulting NamingContext. + * If a binding under the supplied name already exists it will be + * unbound first. If the + * object to be bound is a NamingContext it will not participate in + * a recursive resolve. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see doBind + */ + @Naming + public void rebind(NameComponent[] n, org.omg.CORBA.Object obj) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + if( obj == null ) + { + throw wrapper.objectIsNull() ; + } + try { + // doBind implements all four flavors of binding + NamingContextDataStore impl = (NamingContextDataStore)this; + doBind(impl,n,obj,true,BindingType.nobject); + } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { + // This should not happen + throw wrapper.namingCtxRebindAlreadyBound( ex ) ; + } + } + + /** + * Bind a NamingContext under a name in this NamingContext. If the name + * contains multiple (n) components, the first n-1 components will be + * resolved in this + * NamingContext and the object bound in resulting NamingContext. + * If a binding under the supplied name already exists it will be + * unbound first. The NamingContext will participate in recursive resolving. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param nc the naming context to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see doBind + */ + @Naming + public void rebind_context(NameComponent[] n, NamingContext nc) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + try { + // doBind implements all four flavors of binding + NamingContextDataStore impl = (NamingContextDataStore)this; + doBind(impl,n,nc,true,BindingType.ncontext); + } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { + // This should not happen + throw wrapper.namingCtxRebindAlreadyBound( ex ) ; + } + } + + /** + * Resolve a name in this NamingContext and return the object reference + * bound to the name. If the name contains multiple (n) components, + * the first component will be resolved in this NamingContext and the + * remaining components resolved in the resulting NamingContext, provided + * that the NamingContext bound to the first component of the name was + * bound with bind_context(). + * @param n a sequence of NameComponents which is the name to be resolved. + * @return the object reference bound under the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see doResolve + */ + @Naming + public org.omg.CORBA.Object resolve(NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + // doResolve actually resolves + NamingContextDataStore impl = (NamingContextDataStore)this; + return doResolve(impl,n); + } + + /** + * Remove a binding from this NamingContext. If the name contains + * multiple (n) components, the first n-1 components will be resolved + * from this NamingContext and the final component unbound in + * the resulting NamingContext. + * @param n a sequence of NameComponents which is the name to be unbound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see doUnbind + */ + @Naming + public void unbind(NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + // doUnbind actually unbinds + NamingContextDataStore impl = (NamingContextDataStore)this; + doUnbind(impl,n); + } + + /** + * List the contents of this NamingContest. A sequence of bindings + * is returned (a BindingList) containing up to the number of requested + * bindings, and a BindingIterator object reference is returned for + * iterating over the remaining bindings. + * @param how_many The number of requested bindings in the BindingList. + * @param bl The BindingList as an out parameter. + * @param bi The BindingIterator as an out parameter. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see BindingListHolder + * @see BindingIteratorImpl + */ + @Naming + public void list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) + { + // List actually generates the list + NamingContextDataStore impl = (NamingContextDataStore)this; + synchronized (impl) { + impl.listImpl(how_many,bl,bi); + } + } + + + /** + * Create a NamingContext object and return its object reference. + * @return an object reference for a new NamingContext object implemented + * by this Name Server. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + @Naming + public synchronized NamingContext new_context() + { + // Create actually creates a new naming context + NamingContextDataStore impl = (NamingContextDataStore)this; + synchronized (impl) { + return impl.newContextImpl(); + } + } + + + /** + * Create a new NamingContext, bind it in this Naming Context and return + * its object reference. This is equivalent to using new_context() followed + * by bind_context() with the supplied name and the object reference for + * the newly created NamingContext. + * @param n a sequence of NameComponents which is the name to be unbound. + * @return an object reference for a new NamingContext object implemented + * by this Name Server, bound to the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object is + * already bound under the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see new_context + * @see bind_context + */ + @Naming + public NamingContext bind_new_context(NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.AlreadyBound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + NamingContext nc = null; + NamingContext rnc = null; + try { + // The obvious solution: + nc = this.new_context(); + this.bind_context(n,nc); + rnc = nc; + nc = null; + } finally { + try { + if(nc != null) { + nc.destroy(); + } + } catch (org.omg.CosNaming.NamingContextPackage.NotEmpty e) { + } + } + return rnc; + } + + /** + * Destroy this NamingContext object. If this NamingContext contains + * no bindings, the NamingContext is deleted. + * @exception org.omg.CosNaming.NamingContextPackage.NotEmpty This NamingContext + * is not empty (i.e., contains bindings). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + @Naming + public void destroy() + throws org.omg.CosNaming.NamingContextPackage.NotEmpty + { + NamingContextDataStore impl = (NamingContextDataStore)this; + synchronized (impl) { + if (impl.isEmptyImpl() == true) { + impl.destroyImpl(); + } + else { + throw new org.omg.CosNaming.NamingContextPackage.NotEmpty(); + } + } + } + + /** + * Implements all four flavors of binding. It uses Resolve() to + * check if a binding already exists (for bind and bind_context), and + * unbind() to ensure that a binding does not already exist. + * If the length of the name is 1, then Bind() is called with + * the name and the object to bind. Otherwise, the first component + * of the name is resolved in this NamingContext and the appropriate + * form of bind passed to the resulting NamingContext. + * This method is static for maximal reuse - even for extended naming + * context implementations where the recursive semantics still apply. + * @param impl an implementation of NamingContextDataStore + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @param rebind Replace an existing binding or not. + * @param bt Type of binding (as object or as context). + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the first component of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object is + * already bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see resolve + * @see unbind + * @see bind + * @see bind_context + * @see rebind + * @see rebind_context + */ + @Naming + private void doBind(NamingContextDataStore impl, NameComponent[] n, + org.omg.CORBA.Object obj, boolean rebind, + org.omg.CosNaming.BindingType bt) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, + org.omg.CosNaming.NamingContextPackage.AlreadyBound + { + // Valid name? + if (n.length < 1) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + // At bottom level? + if (n.length == 1) { + // The identifier must be set + if( (n[0].id.length() == 0) && (n[0].kind.length() == 0) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + // Ensure synchronization of backend + synchronized (impl) { + // Yes: bind object in this context under the name + BindingTypeHolder bth = new BindingTypeHolder(); + if (rebind) { + org.omg.CORBA.Object objRef = impl.resolveImpl( n[0], bth ); + if( objRef != null ) { + // Refer Naming Service Doc:00-11-01 section 2.2.3.4 + // If there is an object already bound with the name + // and the binding type is not ncontext a NotFound + // Exception with a reason of not a context has to be + // raised. + // Fix for bug Id: 4384628 + if ( bth.value.value() == BindingType.nobject.value() ) { + if ( bt.value() == BindingType.ncontext.value() ) { + throw new NotFound(NotFoundReason.not_context, n); + } + } else { + // Previously a Context was bound and now trying to + // bind Object. It is invalid. + if ( bt.value() == BindingType.nobject.value() ) { + throw new NotFound(NotFoundReason.not_object, n); + } + } + impl.unbindImpl(n[0]); + } + } else { + if (impl.resolveImpl(n[0],bth) != null) { + throw new org.omg.CosNaming.NamingContextPackage.AlreadyBound(); + } + } + + // Now there are no other bindings under this name + impl.bindImpl(n[0],obj,bt); + } + } else { + // No: bind in a different context + NamingContext context = resolveFirstAsContext(impl,n); + + // Compute tail + NameComponent[] tail = new NameComponent[n.length - 1]; + System.arraycopy(n,1,tail,0,n.length-1); + + // How should we propagate the bind + switch (bt.value()) { + case BindingType._nobject: + // Bind as object + if (rebind) { + context.rebind(tail, obj); + } else { + context.bind(tail, obj); + } + break; + + case BindingType._ncontext: + // Narrow to a naming context using Java casts. It must work. + NamingContext objContext = (NamingContext)obj; + // Bind as context + if (rebind) { + context.rebind_context(tail, objContext); + } else { + context.bind_context(tail, objContext); + } + break; + + default: + // This should not happen + throw wrapper.namingCtxBadBindingtype() ; + } + } + } + + + /** + * Implements resolving names in this NamingContext. The first component + * of the supplied name is resolved in this NamingContext by calling + * Resolve(). If there are no more components in the name, the + * resulting object reference is returned. Otherwise, the resulting object + * reference must have been bound as a context and be narrowable to + * a NamingContext. If this is the case, the remaining + * components of the name is resolved in the resulting NamingContext. + * This method is static for maximal reuse - even for extended naming + * context implementations where the recursive semantics still apply. + * @param impl an implementation of NamingContextDataStore + * @param n a sequence of NameComponents which is the name to be resolved. + * @return the object reference bound under the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the first component of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see resolve + */ + @Naming + public static org.omg.CORBA.Object doResolve(NamingContextDataStore impl, + NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + org.omg.CORBA.Object obj = null; + BindingTypeHolder bth = new BindingTypeHolder(); + + // Length must be greater than 0 + if (n.length < 1) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + // The identifier must be set + if (n.length == 1) { + synchronized (impl) { + // Resolve first level in this context + obj = impl.resolveImpl(n[0],bth); + } + if (obj == null) { + // Object was not found + throw new org.omg.CosNaming.NamingContextPackage.NotFound(NotFoundReason.missing_node,n); + } + return obj; + } else { + // n.length > 1 + if ( (n[1].id.length() == 0) && (n[1].kind.length() == 0 ) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + NamingContext context = resolveFirstAsContext(impl,n); + + // Compute restOfName = name[1..length] + NameComponent[] tail = new NameComponent[n.length -1]; + System.arraycopy(n,1,tail,0,n.length-1); + + // Resolve rest of name in context + return context.resolve(tail); + } + } + + /** + * Implements unbinding bound names in this NamingContext. If the + * name contains only one component, the name is unbound in this + * NamingContext using Unbind(). Otherwise, the first component + * of the name is resolved in this NamingContext and + * unbind passed to the resulting NamingContext. + * This method is static for maximal reuse - even for extended naming + * context implementations where the recursive semantics still apply. + * @param impl an implementation of NamingContextDataStore + * @param n a sequence of NameComponents which is the name to be unbound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see resolve + */ + @Naming + public static void doUnbind(NamingContextDataStore impl, + NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + // Name valid? + if (n.length < 1) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + // Unbind here? + if (n.length == 1) { + // The identifier must be set + if ( (n[0].id.length() == 0) && (n[0].kind.length() == 0 ) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + org.omg.CORBA.Object objRef = null; + synchronized (impl) { + objRef = impl.unbindImpl(n[0]); + } + + if (objRef == null) { + throw new org.omg.CosNaming.NamingContextPackage.NotFound(NotFoundReason.missing_node, n); + } + return; + } else { + // No: unbind in a different context + + // Resolve first - must be resolveable + NamingContext context = resolveFirstAsContext(impl,n); + + // Compute tail + NameComponent[] tail = new NameComponent[n.length - 1]; + System.arraycopy(n,1,tail,0,n.length-1); + + // Propagate unbind to this context + context.unbind(tail); + } + } + + /** + * Implements resolving a NameComponent in this context and + * narrowing it to CosNaming::NamingContext. It will throw appropriate + * exceptions if not found or not narrowable. + * @param impl an implementation of NamingContextDataStore + * @param n a NameComponents which is the name to be found. + * @return naming context + * @exception org.omg.CosNaming.NamingContextPackage.NotFound The + * first component could not be resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the first component of the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see resolve + */ + @Naming + protected static NamingContext resolveFirstAsContext(NamingContextDataStore impl, + NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound { + org.omg.CORBA.Object topRef = null; + BindingTypeHolder bth = new BindingTypeHolder(); + NamingContext context = null; + + synchronized (impl) { + // Resolve first - must be resolveable + topRef = impl.resolveImpl(n[0],bth); + if (topRef == null) { + // It was not bound + throw new org.omg.CosNaming.NamingContextPackage.NotFound(NotFoundReason.missing_node,n); + } + } + + // Was it bound as a context? + if (bth.value != BindingType.ncontext) { + // It was not a context + throw new org.omg.CosNaming.NamingContextPackage.NotFound(NotFoundReason.not_context,n); + } + + // Narrow to a naming context + try { + context = NamingContextHelper.narrow(topRef); + } catch (org.omg.CORBA.BAD_PARAM ex) { + // It was not a context + throw new org.omg.CosNaming.NamingContextPackage.NotFound(NotFoundReason.not_context,n); + } + + // Hmm. must be ok + return context; + } + + @Naming + public static String nameToString(NameComponent[] name) + { + StringBuilder s = new StringBuilder("{"); + if ((name != null) && (name.length > 0)) { + for (int i=0;i0) { + s.append(","); + } + s.append("[").append(name[i].id).append(",") + .append(name[i].kind).append("]"); + } + } + s.append("}"); + return s.toString(); + } + + /** + * Implements all flavors of binding( bind and bindcontext) + * This method will be called from the superclass's doBind( ) method + * which takes care of all the conditions before calling this method. + * i.e., It checks whether the Name is already Bounded, Then in the + * case of rebind it calls Unbind first. + * This method does one level binding only, To have n-level binding + * with compound names, doBind( ) calls this method recursively. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @param bt Type of binding (as object or as context). + * @exception org.omg.CosNaming.NamingContextPackage.NotFound raised + * if the NameComoponent list is invalid + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * Could not proceed in resolving the Name from the given NameComponent + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object + * is already bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions + * @see Resolve + * @see Unbind + */ + @Naming + public void bindImpl(NameComponent n, org.omg.CORBA.Object obj, BindingType bt) + { + if( obj == null ) { + // Raise a Valid Exception and Return + return; + } + + InternalBindingKey key = new InternalBindingKey(n); + InternalBindingValue value; + + try { + if( bt.value() == BindingType._nobject ) { + // If the BindingType is an ObjectRef then Stringify this ref and + // Store it in InternalBindingValue instance. This is required + // because the Object References has to be stored in file + value = new InternalBindingValue(bt, orb.object_to_string(obj) ); + value.setObjectRef( obj ); + } else { + // If the BindingType is a NamingContext then get it's object key + // from the NameService and store it in the Internal Binding Value instance + String theNCKey = theNameServiceHandle.getObjectKey( obj ); + value = new InternalBindingValue( bt, theNCKey ); + value.setObjectRef( obj ); + } + + InternalBindingValue oldValue = + (InternalBindingValue)this.theHashtable.put(key,value); + + if( oldValue != null) { + // There was an entry with this name in the Hashtable and hence throw CTX_ALREADY_BOUND + // exception + throw wrapper.namingCtxRebindAlreadyBound() ; + } else { + try { + // Everything went smooth so update the NamingContext file with the + // latest Hashtable image + theServantManagerImplHandle.updateContext( objKey, this ); + } catch( Exception e ) { + // Something went wrong while updating the context + // so speak the error + throw wrapper.bindUpdateContextFailed( e ) ; + } + } + } catch( Exception e ) { + // Something went wrong while Binding the Object Reference + // Speak the error again. + throw wrapper.bindFailure( e ) ; + } + } + + /** + * This method resolves the NamingContext or Object Reference for one level + * The doResolve( ) method calls Resolve( ) recursively to resolve n level + * Names. + * @param n a sequence of NameComponents which is the name to be resolved. + * @param bth Holder for type of binding (as object or as context). + * @return the object reference bound under the supplied name. + * @see Bind + */ + @Naming + public Object resolveImpl(NameComponent n, BindingTypeHolder bth) + { + if( ( n.id.length() == 0 ) &&( n.kind.length() == 0 ) ) { + // If the NameComponent list has no entry then it means the current + // context was requested + bth.value = BindingType.ncontext; + return theNameServiceHandle.getObjectReferenceFromKey( + this.objKey ); + } + + InternalBindingKey key = new InternalBindingKey(n); + InternalBindingValue value = + (InternalBindingValue) this.theHashtable.get(key); + + if( value == null ) { + // No entry was found for the given name and hence return NULL + // NamingContextDataStore throws appropriate exception if + // required. + return null; + } + + Object theObjectFromStringifiedReference = null; + bth.value = value.theBindingType; + + try { + // Check whether the entry found in the Hashtable starts with NC + // Which means it's a name context. So get the NamingContext reference + // from ServantManager, which would either return from the cache or + // read it from the File. + if( value.strObjectRef.startsWith( "NC" ) ) { + bth.value = BindingType.ncontext; + return theNameServiceHandle.getObjectReferenceFromKey( value.strObjectRef ); + } else { + // Else, It is a Object Reference. Check whether Object Reference + // can be obtained directly, If not then convert the stringified + // reference to object and return. + theObjectFromStringifiedReference = value.getObjectRef( ); + + if (theObjectFromStringifiedReference == null ) { + try { + theObjectFromStringifiedReference = + orb.string_to_object( value.strObjectRef ); + value.setObjectRef( theObjectFromStringifiedReference ); + } catch( Exception e ) { + throw wrapper.resolveConversionFailure( e ); + } + } + } + } catch ( Exception e ) { + throw wrapper.resolveFailure( e ); + } + + return theObjectFromStringifiedReference; + } + + /** + * This method Unbinds the NamingContext or Object Reference for one level + * The doUnbind( ) method from superclass calls Unbind() to recursively + * Unbind using compound Names. + * @param n a sequence of NameComponents which is the name to be resolved. + * @return the object reference bound under the supplied name. + * @see Bind + */ + + @Naming + public Object unbindImpl(NameComponent n) throws SystemException + { + try { + InternalBindingKey key = new InternalBindingKey(n); + InternalBindingValue value = null; + + try { + value = (InternalBindingValue) this.theHashtable.remove(key); + } catch( Exception e ) { + // Ignore the exception in Hashtable.remove + } + + theServantManagerImplHandle.updateContext( objKey, this ); + + if( value == null ) { + return null; + } + + if( value.strObjectRef.startsWith( "NC" ) ) { + theServantManagerImplHandle.readInContext( value.strObjectRef ); + Object theObjectFromStringfiedReference = + theNameServiceHandle.getObjectReferenceFromKey( value.strObjectRef ); + return theObjectFromStringfiedReference; + } else { + Object theObjectFromStringifiedReference = value.getObjectRef( ); + + if( theObjectFromStringifiedReference == null ) { + theObjectFromStringifiedReference = + orb.string_to_object( value.strObjectRef ); + } + + return theObjectFromStringifiedReference; + } + } catch( Exception e ) { + throw wrapper.unbindFailure( e ); + } + } + + /** + * List the contents of this NamingContext. It creates a new + * PersistentBindingIterator object and passes it a clone of the + * hash table and an orb object. It then uses the + * newly created object to return the required number of bindings. + * @param how_many The number of requested bindings in the BindingList. + * @param bl The BindingList as an out parameter. + * @param bi The BindingIterator as an out parameter. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + + @Naming + public void listImpl(int how_many, BindingListHolder bl, + BindingIteratorHolder bi) throws SystemException + { + if( biPOA == null ) { + createbiPOA( ); + } + try { + PersistentBindingIterator bindingIterator = + new PersistentBindingIterator(this.orb, + (Hashtable)this.theHashtable.clone(), biPOA); + // Have it set the binding list + bindingIterator.list(how_many,bl); + + byte[] objectId = biPOA.activate_object( bindingIterator ); + org.omg.CORBA.Object obj = biPOA.id_to_reference( objectId ); + + // Get the object reference for the binding iterator servant + org.omg.CosNaming.BindingIterator bindingRef = + org.omg.CosNaming.BindingIteratorHelper.narrow( obj ); + + bi.value = bindingRef; + } catch (org.omg.CORBA.SystemException e) { + throw e; + } catch( Exception e ) { + throw wrapper.transNcListGotExc( e ) ; + } + } + + @Naming + private synchronized void createbiPOA( ) { + if( biPOA != null ) { + return; + } + try { + POA rootPOA = (POA) orb.resolve_initial_references( + ORBConstants.ROOT_POA_NAME ); + rootPOA.the_POAManager().activate( ); + + int i = 0; + Policy[] poaPolicy = new Policy[3]; + poaPolicy[i++] = rootPOA.create_lifespan_policy( + LifespanPolicyValue.TRANSIENT); + poaPolicy[i++] = rootPOA.create_id_assignment_policy( + IdAssignmentPolicyValue.SYSTEM_ID); + poaPolicy[i++] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.RETAIN); + biPOA = rootPOA.create_POA("BindingIteratorPOA", null, poaPolicy ); + biPOA.the_POAManager().activate( ); + } catch( Exception e ) { + throw wrapper.namingCtxBindingIteratorCreate( e ) ; + } + } + + + /** + * Create a NamingContext object and return its object reference. + * @return an object reference for a new NamingContext object implemented + * by this Name Server. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + @Naming + public NamingContext newContextImpl() throws SystemException + { + try { + return theNameServiceHandle.newContext( ); + } catch( org.omg.CORBA.SystemException e ) { + throw e; + } catch( Exception e ) { + throw wrapper.transNcNewctxGotExc( e ) ; + } + } + + + /** + * Destroys the NamingContext. + */ + @Naming + public void destroyImpl() throws SystemException + { + // Note that orb.disconnect is illegal here, since the + // POA is used. However, there may be some associated state + // that needs to be cleaned up in ServerManagerImpl which we will + // look into further at another time. + /* + // This needs to be replaced by cleaning up the + // file that backs up the naming context. No explicit + // action is necessary at the POA level, since this is + // created with the non-retain policy. + /* + try { orb.disconnect( + theNameServiceHandle.getObjectReferenceFromKey( this.objKey ) ); + } catch( org.omg.CORBA.SystemException e ) { + throw e; + } catch( Exception e ) { + throw updateWrapper.transNcDestroyGotEx( e ) ; + } + */ + } + + /** + * This operation creates a stringified name from the array of Name + * components. + * @param n Name of the object

+ * @return the string. + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + * Indicates the name does not identify a binding. + * + */ + @Naming + public String to_string(org.omg.CosNaming.NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.InvalidName + { + // Name valid? + if ( (n == null ) || (n.length == 0) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + String theStringifiedName = insImpl.convertToString( n ); + + if( theStringifiedName == null ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + return theStringifiedName; + } + + /** + * This operation converts a Stringified Name into an equivalent array + * of Name Components. + * @param sn Stringified Name of the object

+ * @return the name components for the string. + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + * Indicates the name does not identify a binding.

+ * + */ + @Naming + public org.omg.CosNaming.NameComponent[] to_name(String sn) + throws org.omg.CosNaming.NamingContextPackage.InvalidName + { + // Name valid? + if ( (sn == null ) || (sn.length() == 0) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + org.omg.CosNaming.NameComponent[] theNameComponents = + insImpl.convertToNameComponent( sn ); + + if( ( theNameComponents == null ) || (theNameComponents.length == 0 ) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + for( int i = 0; i < theNameComponents.length; i++ ) { + // If there is a name component whose id and kind null or + // zero length string, then an invalid name exception needs to be + // raised. + if ( ( ( theNameComponents[i].id == null ) + ||( theNameComponents[i].id.length() == 0 ) ) + &&( ( theNameComponents[i].kind == null ) + ||( theNameComponents[i].kind.length() == 0 ) ) ) { + throw new InvalidName(); + } + } + + return theNameComponents; + } + + /** + * This operation creates a URL based "iiopname://" format name + * from the Stringified Name of the object. + * @param addr internet based address of the host machine where + * Name Service is running

+ * @param sn Stringified Name of the object

+ * @return the String in URL form. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * Indicates the name does not identify a binding.

+ * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidAddress + * Indicates the internet based address of the host machine is + * incorrect

+ * + */ + + @Naming + public String to_url(String addr, String sn) + throws org.omg.CosNaming.NamingContextExtPackage.InvalidAddress, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + // Name valid? + if ( (sn == null ) || (sn.length() == 0) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + if( addr == null ) { + throw new org.omg.CosNaming.NamingContextExtPackage.InvalidAddress(); + } + + String urlBasedAddress = null; + + try { + urlBasedAddress = insImpl.createURLBasedAddress( addr, sn ); + } catch (Exception e ) { + urlBasedAddress = null; + } + + // Extra check to see that corba name url created is valid as per + // INS spec grammer. + if (urlBasedAddress != null) { + try { + INSURLHandler.getINSURLHandler().parseURL(urlBasedAddress); + } catch (BAD_PARAM e) { + throw new org.omg.CosNaming.NamingContextExtPackage.InvalidAddress(); + } + } + + return urlBasedAddress; + } + + /** + * This operation resolves the Stringified name into the object + * reference. + * @param sn Stringified Name of the object

+ * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * Indicates there is no object reference for the given name.

+ * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * Indicates that the given compound name is incorrect

+ * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * Indicates the name does not identify a binding. + * + */ + @Naming + public org.omg.CORBA.Object resolve_str(String sn) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + org.omg.CORBA.Object theObject = null; + // Name valid? + if ( (sn == null ) || (sn.length() == 0) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + org.omg.CosNaming.NameComponent[] theNameComponents = + insImpl.convertToNameComponent( sn ); + + if( ( theNameComponents == null ) || (theNameComponents.length == 0 ) ) { + throw new org.omg.CosNaming.NamingContextPackage.InvalidName(); + } + + theObject = resolve( theNameComponents ); + return theObject; + } + + /** + * This is a debugging Method + */ + public boolean isEmptyImpl() + { + return this.theHashtable.isEmpty(); + } + + /** + * This is a debugging Method + */ + public void printSize( ) + { + System.out.println( "Hashtable Size = " + theHashtable.size( ) ); + java.util.Enumeration e = theHashtable.keys( ); + for( ; e.hasMoreElements(); ) + { + InternalBindingValue thevalue = + (InternalBindingValue) this.theHashtable.get(e.nextElement()); + if( thevalue != null ) + { + System.out.println( "value = " + thevalue.strObjectRef); + } + } + } + +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/PersistentBindingIterator.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/PersistentBindingIterator.java new file mode 100644 index 000000000..1c1f92aeb --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/PersistentBindingIterator.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + +// Import general CORBA classes +import org.omg.CORBA.INTERNAL; + +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.NameComponent; +import org.omg.PortableServer.POA; + +import com.sun.corba.ee.impl.naming.cosnaming.BindingIteratorImpl; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * Class TransientBindingIterator implements the abstract methods + * defined by BindingIteratorImpl, to use with the TransientNamingContext + * implementation of the NamingContextImpl. The TransientBindingIterator + * implementation receives a hash table of InternalBindingValues, and uses + * an Enumeration to iterate over the contents of the hash table. + * @see BindingIteratorImpl + * @see TransientNamingContext + */ +public class PersistentBindingIterator extends BindingIteratorImpl +{ + private POA biPOA; + /** + * Constructs a new PersistentBindingIterator object. + * @param orb a org.omg.CORBA.ORB object. + * @param aTable A hashtable containing InternalBindingValues which is + * the content of the PersistentNamingContext. + * initialize. + * @param thePOA the POA to use. + * @throws java.lang.Exception can throw many exceptions? + */ + public PersistentBindingIterator(org.omg.CORBA.ORB orb, + Map aTable, + POA thePOA ) throws java.lang.Exception + { + super(orb); + map = new HashMap( aTable ) ; + iterator = this.map.keySet().iterator() ; + currentSize = this.map.size(); + biPOA = thePOA; + } + + /** + * Returns the next binding in the NamingContext. Uses the enumeration + * object to determine if there are more bindings and if so, returns + * the next binding from the InternalBindingValue. + * @param b The Binding as an out parameter. + * @return true if there were more bindings. + */ + final public boolean nextOneImpl(org.omg.CosNaming.BindingHolder b) + { + // If there are more elements get the next element + boolean hasMore = iterator.hasNext(); + if (hasMore) { + InternalBindingKey theBindingKey = iterator.next(); + InternalBindingValue theElement = map.get( theBindingKey ); + NameComponent n = new NameComponent( theBindingKey.id, + theBindingKey.kind ); + NameComponent[] nlist = new NameComponent[1]; + nlist[0] = n; + BindingType theType = theElement.theBindingType; + + b.value = + new Binding( nlist, theType ); + } else { + // Return empty but marshalable binding + b.value = new Binding(new NameComponent[0],BindingType.nobject); + } + return hasMore; + } + + /** + * Destroys this BindingIterator by disconnecting from the ORB + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + final public void destroyImpl() + { + // Remove the object from the Active Object Map. + try { + byte[] objectId = biPOA.servant_to_id( this ); + if( objectId != null ) { + biPOA.deactivate_object( objectId ); + } + } + catch( Exception e ) { + throw new INTERNAL( "Exception in BindingIterator.Destroy " + e ); + } + } + + /** + * Returns the remaining number of elements in the iterator. + * @return the remaining number of elements in the iterator. + */ + public final int remainingElementsImpl() { + return currentSize; + } + + private int currentSize; + private HashMap map ; + private Iterator iterator; +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/ServantManagerImpl.java b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/ServantManagerImpl.java new file mode 100644 index 000000000..a5cff6c55 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/impl/naming/pcosnaming/ServantManagerImpl.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.pcosnaming; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import java.util.HashMap; + +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ForwardRequest; +import org.omg.PortableServer.ServantLocator; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; + +import com.sun.corba.ee.spi.orb.ORB; + +/** + * @version 1.6, 99/10/07 + * @author Rohit Garg + * @since JDK1.2 + */ + +public class ServantManagerImpl extends org.omg.CORBA.LocalObject implements ServantLocator +{ + private static final long serialVersionUID = 4028710359865748280L; + + private transient ORB orb; + + private transient NameService theNameService; + + private File logDir; + + private HashMap contexts; + + private transient CounterDB counterDb; + + private int counter; + + private final static String objKeyPrefix = "NC"; + + ServantManagerImpl(ORB orb, File logDir, NameService aNameService) + { + this.logDir = logDir; + this.orb = orb; + // initialize the counter database + counterDb = new CounterDB(logDir); + contexts = new HashMap(); + theNameService = aNameService; + } + + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder cookie) throws ForwardRequest + { + + String objKey = new String(oid); + + Servant servant = contexts.get(objKey); + + if (servant == null) { + servant = readInContext(objKey); + } + + return servant; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + // nada + } + + public NamingContextImpl readInContext(String objKey) + { + NamingContextImpl context = contexts.get(objKey); + if( context != null ) { + // Returning Context from Cache + return context; + } + + File contextFile = new File(logDir, objKey); + if (contextFile.exists()) { + try { + FileInputStream fis = new FileInputStream(contextFile); + ObjectInputStream ois = new ObjectInputStream(fis); + context = (NamingContextImpl) ois.readObject(); + context.setORB( orb ); + context.setServantManagerImpl( this ); + context.setRootNameService( theNameService ); + ois.close(); + } catch (Exception ex) { + throw new RuntimeException( "No file for context " + objKey ) ; + } + } + + if (context != null) { + contexts.put(objKey, context); + } + return context; + } + + public NamingContextImpl addContext(String objKey, + NamingContextImpl context) + { + File contextFile = new File(logDir, objKey); + + if (contextFile.exists()) { + context = readInContext(objKey); + } else { + try { + FileOutputStream fos = new FileOutputStream(contextFile); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(context); + oos.close(); + } catch (Exception ex) { + throw new RuntimeException( "Error in adding new context " + + objKey, ex) ; + } + } + + try { + contexts.remove( objKey ); + } catch( Exception e) { + throw new RuntimeException( "Error in removing old context " + + objKey, e) ; + } + + contexts.put(objKey, context); + + return context; + } + + public void updateContext( String objKey, + NamingContextImpl context ) + { + File contextFile = new File(logDir, objKey); + if (contextFile.exists()) { + contextFile.delete( ); + contextFile = new File(logDir, objKey); + } + + try { + FileOutputStream fos = new FileOutputStream(contextFile); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(context); + oos.close(); + } catch (Exception ex) { + throw new RuntimeException( "Could not update context " + objKey, + ex ) ; + } + } + + public static String getRootObjectKey() + { + return objKeyPrefix + CounterDB.rootCounter; + } + + public String getNewObjectKey() + { + return objKeyPrefix + counterDb.getNextCounter(); + } +} + +class CounterDB { + public static final int rootCounter = 0; + + private static final String counterFileName = "counter"; + + private Integer counter; + private transient File counterFile; + + CounterDB (File logDir) + { + counterFile = new File(logDir, counterFileName); + if (!counterFile.exists()) { + counter = Integer.valueOf(rootCounter); + writeCounter(); + } else { + readCounter(); + } + } + + private void readCounter() + { + try { + FileInputStream fis = new FileInputStream(counterFile); + ObjectInputStream ois = new ObjectInputStream(fis); + counter = (Integer) ois.readObject(); + ois.close(); + } catch (Exception ex) { + throw new RuntimeException( "Could not read counter", + ex ) ; + } + } + + private void writeCounter() + { + try { + counterFile.delete(); + FileOutputStream fos = new FileOutputStream(counterFile); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(counter); + oos.flush(); + oos.close(); + + } catch (Exception ex) { + throw new RuntimeException( "Could not write counter", + ex ) ; + } + } + + public synchronized int getNextCounter() + { + int counterVal = counter.intValue(); + counter = Integer.valueOf(++counterVal); + writeCounter(); + + return counterVal; + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/internal/CosNaming/BootstrapServer.java b/functional-tests/src/test/java/com/sun/corba/ee/internal/CosNaming/BootstrapServer.java new file mode 100644 index 000000000..655ffa271 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/internal/CosNaming/BootstrapServer.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.CosNaming; + +import java.util.Properties; + +import java.io.File; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.resolver.Resolver ; +import com.sun.corba.ee.spi.resolver.LocalResolver ; +import com.sun.corba.ee.spi.resolver.ResolverDefault ; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * Class BootstrapServer is the main entry point for the bootstrap server + * implementation. The BootstrapServer makes all object references + * defined in a configurable file available using the old + * naming bootstrap protocol. + */ +public class BootstrapServer +{ + private ORB orb; + + /** + * Main startup routine for the bootstrap server. + * It first determines the port on which to listen, checks that the + * specified file is available, and then creates the resolver + * that will be used to service the requests in the + * BootstrapServerRequestDispatcher. + * @param args the command-line arguments to the main program. + */ + public static final void main(String[] args) + { + String propertiesFilename = null; + int initialPort = ORBConstants.DEFAULT_INITIAL_PORT; + + // Process arguments + for (int i=0;i " + + "-ORBInitialPort " ) ; + return; + } + + // Create a file + File file = new File(propertiesFilename); + + // Verify that if it exists, it is readable + if (file.exists() == true && file.canRead() == false) { + System.err.println( "File " + file.getAbsolutePath() + + " is not readable" ) ; + return; + } + + // Success: start up + System.out.println( + "Bootstrapserver started on port " + Integer.toString(initialPort) + + " wirh InitialServicesFile " + file.getAbsolutePath()); + + Properties props = new Properties() ; + + // Use the SERVER_PORT to create an Acceptor using the + // old legacy code in ORBConfiguratorImpl. When (if?) + // the legacy support is removed, this code will need + // to create an Acceptor directly. + props.put( ORBConstants.SERVER_PORT_PROPERTY, + Integer.toString( initialPort ) ) ; + + ORB orb = (ORB) org.omg.CORBA.ORB.init(args,props); + + LocalResolver lres = orb.getLocalResolver() ; + Resolver fres = ResolverDefault.makeFileResolver( orb, file ) ; + Resolver cres = ResolverDefault.makeCompositeResolver( fres, lres ) ; + LocalResolver sres = ResolverDefault.makeSplitLocalResolver( cres, lres ) ; + + orb.setLocalResolver( sres ) ; + + try { + // This causes the acceptors to start listening. + orb.resolve_initial_references(ORBConstants.ROOT_POA_NAME); + } catch (org.omg.CORBA.ORBPackage.InvalidName e) { + throw new RuntimeException("This should not happen", e); + } + + orb.run() ; + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/internal/Interceptors/PIORB.java b/functional-tests/src/test/java/com/sun/corba/ee/internal/Interceptors/PIORB.java new file mode 100644 index 000000000..f030e4596 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/internal/Interceptors/PIORB.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.Interceptors; + +import com.sun.corba.ee.internal.POA.POAORB; + +/** + * Deprecated class for backward compatibility. + */ +public class PIORB + extends POAORB +{ + public PIORB() { + super(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/com/sun/corba/ee/internal/POA/POAORB.java b/functional-tests/src/test/java/com/sun/corba/ee/internal/POA/POAORB.java new file mode 100644 index 000000000..99a82c8d1 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/internal/POA/POAORB.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.POA; + +/** + * Deprecated class for backward compatibility. + */ +public class POAORB extends com.sun.corba.ee.internal.iiop.ORB +{ + public POAORB( ) + { + super(); + } +} diff --git a/functional-tests/src/test/java/com/sun/corba/ee/internal/corba/ORBSingleton.java b/functional-tests/src/test/java/com/sun/corba/ee/internal/corba/ORBSingleton.java new file mode 100644 index 000000000..fcd8079eb --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/internal/corba/ORBSingleton.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.corba; + +/** + * + * Deprecated class for backward compatibility. + */ +public class ORBSingleton extends com.sun.corba.ee.impl.orb.ORBSingleton +{ + public ORBSingleton() + { + super(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/com/sun/corba/ee/internal/iiop/ORB.java b/functional-tests/src/test/java/com/sun/corba/ee/internal/iiop/ORB.java new file mode 100644 index 000000000..de507bb70 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/internal/iiop/ORB.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.iiop; + +/** + * Deprecated class for backward compatibility. + */ +public class ORB extends /* 1.4 value: com.sun.corba.ee.internal.corba.ORB */ + com.sun.corba.ee.impl.orb.ORBImpl +{ + public ORB() + { + super(); + } +} // Class ORB diff --git a/functional-tests/src/test/java/com/sun/corba/ee/spi/JndiConstants.java b/functional-tests/src/test/java/com/sun/corba/ee/spi/JndiConstants.java new file mode 100644 index 000000000..5c6507944 --- /dev/null +++ b/functional-tests/src/test/java/com/sun/corba/ee/spi/JndiConstants.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi; + +/** + * Public constants for interaction with the Glassfish JNDI implementation. + */ +public interface JndiConstants { + + /** The name of the class used to create context factories for COSNaming. */ + String COSNAMING_CONTEXT_FACTORY = "com.sun.jndi.cosnaming.CNCtxFactory"; + + /** The JDK's registry context factory. */ + String REGISTRY_CONTEXT_FACTORY = "com.sun.jndi.rmi.registry.RegistryContextFactory"; + + /** A System Property which may be defined as equal to a trusted classpath URL. */ + String TRUST_URLCODEBASE = "com.sun.jndi.cosnaming.object.trustURLCodebase"; + + /** A system property which can be set to true to enable JNDI federation */ + String ENABLE_FEDERATION = "com.sun.jndi.cosnaming.federation"; +} diff --git a/functional-tests/src/test/java/corba/Client.java b/functional-tests/src/test/java/corba/Client.java new file mode 100644 index 000000000..f06b18bd9 --- /dev/null +++ b/functional-tests/src/test/java/corba/Client.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Dec 11 (Thu) 11:03:27 by Harold Carr. +// Last Modified : 2003 Dec 18 (Thu) 11:34:37 by Harold Carr. +// + +package corba.legacybootstrapserver; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Properties; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import corba.framework.Controller; +import corba.framework.Options; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class Client +{ + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static final String bootstrapFilename = "boostrapData"; + public static final String orbInitialPort = "4444"; + public static final String initialEntryName = "InitialEntry"; + + public static ORB orb; + + public static void main(String av[]) + { + try { + System.out.println(main + " starting"); + System.out.println(main + " " + getBootstrapFilePathAndName()); + + /* This doesn't work in test framework. Bug 4970599 + Properties props = new Properties(); + props.setProperty(ORBConstants.INITIAL_PORT_PROPERTY, orbInitialPort); + */ + + String[] args = { "-ORBInitialPort", + getORBInitialPort() }; + + orb = ORB.init(args, (Properties)null); + + lookup(false, "foo"); + org.omg.CORBA.Object o = lookup(true, initialEntryName); + update(true, "foo", o); + lookup(true, "foo"); + // NOTE: without this wait the test fails. + // Wait a second before removing it so that + // the file modified time looks diferent to the server + // from the last update. + Thread.sleep(1000); + update(false, "foo", null); + lookup(false, "foo"); + + System.out.println(main + ": Test complete."); + + } catch (Throwable t) { + System.out.println(main + ": unexpected exception: " + t); + t.printStackTrace(System.out); + System.exit(1); + } + System.out.println(main + ": PASSED"); + System.exit(Controller.SUCCESS); + } + + public static org.omg.CORBA.Object lookup(boolean shouldBeThere, + String name) + throws + Exception + { + String filename = getBootstrapFilePathAndName(); + System.out.println(filename + + " lookup(" + + (shouldBeThere ? "shouldFind" : "shouldNotFind") + ", " + + name + ")"); + + org.omg.CORBA.Object o = null; + try { + o = orb.resolve_initial_references(name); + if (! shouldBeThere) { + throw new Exception("Should not have found: " + name); + } + // Use the reference to make sure it works. + o._non_existent(); + o._is_a("foo"); + } catch (org.omg.CORBA.ORBPackage.InvalidName e) { + if (shouldBeThere) { + throw e; + } + } + return o; + } + + public static String getORBInitialPort() + { + return orbInitialPort; + } + + public static String getBootstrapFilePathAndName() + { + return + //Options.getOutputDirectory() + System.getProperty("output.dir") + + System.getProperty("file.separator") + + Client.bootstrapFilename; + } + + public static void update(boolean shouldAdd, + String name, + org.omg.CORBA.Object o) + throws + Exception + { + String filename = getBootstrapFilePathAndName(); + System.out.println(filename + + " update(" + + (shouldAdd ? "add" : "remove") + ", " + + name + ", " + + (o == null ? "null" : "IOR") + ")"); + FileInputStream is = new FileInputStream(filename); + Properties props = new Properties(); + props.load(is); + is.close(); + if (shouldAdd) { + props.put(name, orb.object_to_string(o)); + } else { + props.remove(name); + } + writeProperties(props, getBootstrapFilePathAndName()); + } + + public static void writeProperties(Properties props, String filename) + throws + Exception + { + FileOutputStream os = new FileOutputStream(filename); + props.store(os, null); + os.close(); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/LegacyBootstrapServerTest.java b/functional-tests/src/test/java/corba/LegacyBootstrapServerTest.java new file mode 100644 index 000000000..5937c1757 --- /dev/null +++ b/functional-tests/src/test/java/corba/LegacyBootstrapServerTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Dec 11 (Thu) 10:59:34 by Harold Carr. +// Last Modified : 2003 Dec 17 (Wed) 21:06:49 by Harold Carr. +// + +package corba.legacybootstrapserver; + +import corba.framework.Controller; +import corba.framework.CORBATest; +import corba.framework.Options; + +public class LegacyBootstrapServerTest extends CORBATest { + + protected void doTest() throws Throwable { + // Options.setOutputDirectory((String)getArgs().get(test.Test.OUTPUT_DIRECTORY)); + + // The ORBD is NOT used. + // However, when it wasn't here then createServer below complained + // Caught java.io.FileNotFoundException: gen/corba/legacybootstrapserver/server.out.txt (No such file or directory) + + Controller orbd = createORBD(); + + Controller server = createServer(Server.class.getName()); + Controller client = createClient(Client.class.getName()); + + orbd.start() ; + server.start(); + client.start(); + client.waitFor(60000); + client.stop(); + server.stop(); + orbd.stop(); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/Server.java b/functional-tests/src/test/java/corba/Server.java new file mode 100644 index 000000000..dc6e6b2bf --- /dev/null +++ b/functional-tests/src/test/java/corba/Server.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Dec 11 (Thu) 11:04:04 by Harold Carr. +// Last Modified : 2003 Dec 17 (Wed) 21:29:35 by Harold Carr. +// + +package corba.legacybootstrapserver; + +import java.util.Properties; +import org.omg.CORBA.ORB; +import corba.framework.Controller; +import corba.framework.Options; + +public class Server +{ + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + + public static void main(String[] av) + { + try { + System.out.println(main + " starting"); + System.out.println(main + " " + getBootstrapFilePathAndName()); + + // Initialize the file. + Properties props = new Properties(); + ORB orb = ORB.init((String[])null, (Properties) null); + org.omg.CORBA.Object o = new IServantConnect(); + orb.connect(o); + props.put(Client.initialEntryName, orb.object_to_string(o)); + Client.writeProperties(props, getBootstrapFilePathAndName()); + + // Set up args. + String[] args = { "-InitialServicesFile", + getBootstrapFilePathAndName(), + "-ORBInitialPort", + Client.getORBInitialPort() }; + + ServerThread serverThread = new ServerThread(args); + serverThread.start(); + + // Wait 5 seconds before sending handshake. + Thread.sleep(5000); + + System.out.println(Options.defServerHandshake); + + Object wait = new Object(); + synchronized (wait) { + wait.wait(); + } + } catch (Exception e) { + System.out.println(main + ": unexpected exception: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + System.exit(Controller.SUCCESS); + } + + public static String getBootstrapFilePathAndName() + { + return + //Options.getOutputDirectory() + System.getProperty("output.dir") + + System.getProperty("file.separator") + + Client.bootstrapFilename; + } +} + +class ServerThread extends Thread +{ + String[] av; + ServerThread (String[] av) + { + this.av = av; + } + + public void run () + { + try { + // Start server. + com.sun.corba.ee.internal.CosNaming.BootstrapServer.main(av); + } catch (Throwable t) { + System.out.println("BootstrapServer.main Throwable:"); + t.printStackTrace(System.out); + System.exit(1); + } + } +} + +class IServantConnect + extends + _IImplBase +{ + public void dummy(){} +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/adapteractivator/AdapterActivator.java b/functional-tests/src/test/java/corba/adapteractivator/AdapterActivator.java new file mode 100644 index 000000000..faea26dfc --- /dev/null +++ b/functional-tests/src/test/java/corba/adapteractivator/AdapterActivator.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.adapteractivator; + +import test.Test; +import corba.framework.*; +import java.util.*; +import org.omg.CORBA.*; + +public class AdapterActivator extends CORBATest +{ + protected void doTest() throws Throwable + { + Options.addServerArgs( "-ORBServerId 123 -ORBPersistentServerPort 15000" ) ; + + Controller client = createClient("corba.adapteractivator.AdapterActivatorClient"); + Controller server = createServer("corba.adapteractivator.AdapterActivatorServer"); + Controller orbd = createORBD() ; + + orbd.start() ; + server.start(); + + client.start() ; + client.waitFor( 60000 ) ; + client.stop(); + + server.stop(); + orbd.stop() ; + } +} + diff --git a/functional-tests/src/test/java/corba/adapteractivator/AdapterActivatorClient.java b/functional-tests/src/test/java/corba/adapteractivator/AdapterActivatorClient.java new file mode 100644 index 000000000..7206e3140 --- /dev/null +++ b/functional-tests/src/test/java/corba/adapteractivator/AdapterActivatorClient.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.adapteractivator ; + +import org.omg.CORBA.ORB; + +import corba.framework.statusU; +import corba.framework.RTMConstants; +import corba.framework.GetID; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +/** +* Purpose : To verify that AdapterActivator implementation registered, recreates +* the POA when ORB receives a request for an object reference that +* identifies the target POA does not exist +* +* Expected Result : Client gets a valid response +* +* Purpose : To verify that client gets a OBJECT_NOT_EXIST exception when +* ORB receives a request for an object reference that identifies +* the target POA does not exist and the AdapterActivator +* implementation registered with rootPoa does not create the POA +* +* Expected Result : Client gets OBJECT_NOT_EXIST exception +* +*/ + +public class AdapterActivatorClient { + + private Hello helloRef1,helloRef2; + private Close closeRef; + private NamingContext rootContext; + private ORB orb; + private statusU status = new statusU(); + private JUnitReportHelper helper = new JUnitReportHelper( AdapterActivatorClient.class.getName() ) ; + + final String testDesc = "To verify that the AdapterActivator registers and"+ + "\n recreates the POA when the ORB received a request"+ + "\n for an object reference which identifies the" + + "\n target POA that doesn't exist"; + + public AdapterActivatorClient(String[] args) { + + try { + orb = ORB.init(args,System.getProperties()); + + // Get root Naming Context + org.omg.CORBA.Object obj = orb.resolve_initial_references("NameService"); + rootContext = NamingContextHelper.narrow(obj); + adapterActivatorTest1(); + adapterActivatorTest2(); + System.out.println("\nAdapterActivatorClient : Calling shutdown()"); + + //Resolve Object Reference for CloseServer + NameComponent nc = new NameComponent("CloseServer",""); + NameComponent name[] = {nc}; + closeRef = CloseHelper.narrow(rootContext.resolve(name)); + closeRef.shutdown(); + } catch(Exception Ex) { + status.addStatus(GetID.generateID(this, ""), RTMConstants.FAIL, + "Got exception: "+ Ex.toString()); + } finally { + helper.done() ; + status.printSummary(GetID.generateID(this, ""), testDesc); + if (status.totalFail() > 0) + System.exit(1) ; + } + } + + void adapterActivatorTest1() { + + String subTestName = "Test01"; + helper.start( subTestName ) ; + try { + + // Resolve Object Reference + NameComponent nc = new NameComponent("HelloServer1",""); + NameComponent name[] = {nc}; + helloRef1 = HelloHelper.narrow(rootContext.resolve(name)); + + System.out.println("\nAdapterActivator-1 Started\n"); + System.out.println("Calling Operation on HelloServant of Poa1. Poa1 is "+ + "child of RootPoa, RootPoa is registered with AdapterActivator"+ + " implementation which creates Poa1 otherwise returns false"); + System.out.println(helloRef1.sayHello()); + status.addStatus(subTestName, RTMConstants.PASS, "Calling "+ + "operation on HelloServant of Poa1 ok"); + helper.pass() ; + } catch(Exception ex) { + helper.fail( ex ) ; + ex.printStackTrace(); + status.addStatus(subTestName, RTMConstants.FAIL, + "Got exception: "+ ex.toString()); + } + } + + void adapterActivatorTest2() { + + String subTestName = "Test02"; + helper.start( subTestName ) ; + try { + + //Resolve Object Reference + NameComponent nc = new NameComponent("HelloServer2",""); + NameComponent name[] = {nc}; + helloRef2 = HelloHelper.narrow(rootContext.resolve(name)); + + System.out.println("\nAdapterActivator-2 Started\n"); + System.out.println("Calling Operation on HelloServant of Poa2. Poa2 is "+ + "child of RootPoa, RootPoa is registered with AdapterActivator "+ + "implementation which creates Poa1 otherwise returns false"); + System.out.println(helloRef2.sayHello()); + helper.fail( "Unexpected success: should see OBJECT_NOT_EXIST exception" ) ; + } catch (org.omg.CORBA.OBJECT_NOT_EXIST ex) { + status.addStatus(subTestName, RTMConstants.PASS, "Operation on "+ + "HelloServant threw the expected OBJECT_NOT_EXIST"+ + " exception"); + helper.pass() ; + } catch(Exception ex) { + ex.printStackTrace(); + status.addStatus(subTestName, RTMConstants.FAIL, + "Got exception: "+ ex.toString()); + helper.fail( ex ) ; + } + } + + public static void main( String [] args ) { + AdapterActivatorClient client = new AdapterActivatorClient(args); + } +} diff --git a/functional-tests/src/test/java/corba/adapteractivator/AdapterActivatorServer.java b/functional-tests/src/test/java/corba/adapteractivator/AdapterActivatorServer.java new file mode 100644 index 000000000..59cc73fd1 --- /dev/null +++ b/functional-tests/src/test/java/corba/adapteractivator/AdapterActivatorServer.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.adapteractivator ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.AdapterActivator ; +import org.omg.PortableServer.LifespanPolicyValue ; +import org.omg.PortableServer.IdAssignmentPolicyValue ; + +import corba.framework.RTMConstants; +import org.omg.CORBA.LocalObject; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +public class AdapterActivatorServer { + + private POA rootPoa,poa1,poa2; + private HelloImpl serv1=null; + private HelloImpl serv2=null; + private byte[] oid1 = "Object1".getBytes() ; + private byte[] oid2 = "Object2".getBytes() ; + + private ORB orb=null; + + public AdapterActivatorServer(String[] args) { + + System.out.println("AdapterActivatorServer : execute"); + + try { + + orb = ORB.init(args,System.getProperties()); + rootPoa = getRootPoa(orb); + + // Registering the AdapterActivator with rootpoa that creates poa1 + System.out.println("Registering the AdapterActivator with rootpoa that creates poa1 "); + rootPoa.the_activator(new Poa1AdapterActivator()); + + // Creating HelloServant + serv1 = new HelloImpl(); + serv2 = new HelloImpl(); + System.out.println("AdapterActivatorServer: HelloImpl object created !" ); + + // Creating CloseServant + CloseImpl closeServ = new CloseImpl(orb); + System.out.println("AdapterActivatorServer: CloseImpl object created !" ); + + // Activating CloseServant with RootPOA + rootPoa.activate_object(closeServ); + + // creating poa1 and activating poa1 + createPoa1(); + + // creating poa2 and activating poa2 + createPoa2(); + + //create a object reference from the servant object + System.out.println("Creating Object reference for Helloservant object"); + org.omg.CORBA.Object helloRef1 = poa1.servant_to_reference(serv1); + org.omg.CORBA.Object helloRef2 = poa2.servant_to_reference(serv2); + + System.out.println("Creating Object reference for Closeservant object"); + org.omg.CORBA.Object closeRef = rootPoa.servant_to_reference(closeServ); + + // Get root Naming Context + org.omg.CORBA.Object obj = orb.resolve_initial_references("NameService"); + NamingContext rootContext = NamingContextHelper.narrow(obj); + + // Create a Name Components and bind to root Context + System.out.println("AdapterActivatorServer : publish Hello activated with Poa1"); + NameComponent nc = new NameComponent("HelloServer1",""); + NameComponent name[] = {nc}; + rootContext.rebind(name,helloRef1); + + System.out.println("AdapterActivatorServer : publish Hello activated with Poa2"); + NameComponent nc1 = new NameComponent("HelloServer2",""); + NameComponent name1[] = {nc1}; + rootContext.rebind(name1,helloRef2); + + System.out.println("AdapterActivatorServer : publish Close activated with RootPOA"); + NameComponent nc2 = new NameComponent("CloseServer",""); + NameComponent name2[] = {nc2}; + rootContext.rebind(name2,closeRef); + + // destroying the Poa1 + poa1.destroy(true,true); + + poa2.destroy(true,true); + + // Activating Poa + System.out.println("Activating the Root POA"); + rootPoa.the_POAManager().activate(); + + //Force the server to wait for client requests + System.out.println(RTMConstants.SERVER_READY); + orb.run(); + } + catch(org.omg.CORBA.SystemException ex) { + System.out.println(" Unexpected exception "+ex.toString()); + return; + } + catch (Exception e) { + System.out.println("Unexpected Exception" + e.toString() + "\n"); + return; + } + } + + + private void createPoa1() { + Policy[] poaPolicies = new Policy[] { + rootPoa.create_lifespan_policy( LifespanPolicyValue.PERSISTENT ), + rootPoa.create_id_assignment_policy( IdAssignmentPolicyValue.USER_ID ) + } ; + + try { + System.out.println("Creating poa1 on rootpoa"); + poa1=rootPoa.create_POA("Poa1",null,poaPolicies); + System.out.println("Created Poa1"); + poa1.activate_object_with_id(oid1, serv1); + poa1.the_POAManager().activate(); + } + catch (Exception e) { + System.out.println("Unexpected Exception" + e.toString()); + } + + } // createPoa1() + + private void createPoa2() { + Policy[] poaPolicies = new Policy[] { + rootPoa.create_lifespan_policy( LifespanPolicyValue.PERSISTENT ), + rootPoa.create_id_assignment_policy( IdAssignmentPolicyValue.USER_ID ) + } ; + + try { + System.out.println("Creating poa2 on rootpoa"); + poa2=rootPoa.create_POA("Poa2",null,poaPolicies); + System.out.println("Created Poa2"); + poa2.activate_object_with_id(oid2, serv2); + poa2.the_POAManager().activate(); + } + catch (Exception e) { + System.out.println("Unexpected Exception" + e.toString()); + } + + } // createPoa2() + + private POA getRootPoa(ORB orb) { + + POA poa=null; + try { + System.out.println("Getting Root POA from ORB"); + poa =(POA)orb.resolve_initial_references("RootPOA"); + + if (poa == null) + System.out.println("POA is null"); + } + catch(org.omg.CORBA.ORBPackage.InvalidName i) { + System.out.println("Unexpected exception in obtaining RootPoa"+i.toString()); + } + catch (Exception e) { + System.out.println("Unexpected Exception" + e.toString()); + } + return poa; + } // getRootPoa() + + + public static void main( String [] args ) { + AdapterActivatorServer server = new AdapterActivatorServer(args) ; + } // main() + + + class Poa1AdapterActivator extends LocalObject implements AdapterActivator { + + public Poa1AdapterActivator() { + + } + + // Unknown adapter creates Poa if Poa name is Poa1 otherwise it return false + + public boolean unknown_adapter(POA parent,String name){ + try { + if(name.equals("Poa1")) { + System.out.println("Creating Poa1 in unknown_adapter method"); + createPoa1(); + return true; + } + } + catch(org.omg.CORBA.SystemException ex) { + System.out.println("Unexpected System Exception " + ex.toString()); + return false; + } + catch(Exception ex){ + System.out.println("Unexpected Exception " + ex.toString()); + return false; + } + return false; + } + } +} diff --git a/functional-tests/src/test/java/corba/adapteractivator/HelloImpl.java b/functional-tests/src/test/java/corba/adapteractivator/HelloImpl.java new file mode 100644 index 000000000..a9def87dc --- /dev/null +++ b/functional-tests/src/test/java/corba/adapteractivator/HelloImpl.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.adapteractivator; + +import org.omg.CORBA.ORB; + + +public class HelloImpl extends HelloPOA { + + public String sayHello() { + System.out.println("Hello : inside sayHello()"); + return "Hello"; + } + +} + + + +class CloseImpl extends ClosePOA { + + private ORB orb=null; + + public CloseImpl(ORB orb) { + this.orb = orb; + } + + public void shutdown() { + System.out.println("PoaOperation : shutDown called"); + orb.shutdown(false); + } + +} + + + + diff --git a/functional-tests/src/test/java/corba/codeset/CharGenerator.java b/functional-tests/src/test/java/corba/codeset/CharGenerator.java new file mode 100644 index 000000000..ddc89f469 --- /dev/null +++ b/functional-tests/src/test/java/corba/codeset/CharGenerator.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codeset; + +/** + * Utility class for generating characters in Latin-1 and Unicode. + */ +public class CharGenerator +{ + public static char[] getLatin1Chars() { + return CharGenerator.getChars(new LatinSelector()); + } + + public static char[] getSomeUnicodeChars() { + return CharGenerator.getChars(new WideSelector()); + } + + public static char[] getChars(CharSelector selector) { + StringBuffer sbuf = new StringBuffer(); + for (char ch = Character.MIN_VALUE; ch < Character.MAX_VALUE; ch++) { + if (selector.testThisCharacter(ch)) + sbuf.append(ch); + } + + char[] result = new char[sbuf.length()]; + + sbuf.getChars(0, result.length, result, 0); + + return result; + } + + private static abstract class CharSelector + { + public abstract boolean testThisCharacter(char ch); + } + + private static class LatinSelector extends CharSelector + { + public boolean testThisCharacter(char ch) + { + Character.UnicodeBlock blk = Character.UnicodeBlock.of(ch); + + return (blk != null && + blk == Character.UnicodeBlock.BASIC_LATIN); + } + } + + private static class WideSelector extends LatinSelector + { + public boolean testThisCharacter(char ch) + { + Character.UnicodeBlock blk = Character.UnicodeBlock.of(ch); + return (blk != null && + (blk == Character.UnicodeBlock.KATAKANA || + blk == Character.UnicodeBlock.HIRAGANA || + blk == Character.UnicodeBlock.LATIN_1_SUPPLEMENT || + blk == Character.UnicodeBlock.LATIN_EXTENDED_A || + blk == Character.UnicodeBlock.LATIN_EXTENDED_B || + blk == Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL || + blk == Character.UnicodeBlock.NUMBER_FORMS || + blk == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS || + blk == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || + blk == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || + blk == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || + blk == Character.UnicodeBlock.ARABIC || + super.testThisCharacter(ch))); + } + } +} diff --git a/functional-tests/src/test/java/corba/codeset/Client.java b/functional-tests/src/test/java/corba/codeset/Client.java new file mode 100644 index 000000000..8406ff26f --- /dev/null +++ b/functional-tests/src/test/java/corba/codeset/Client.java @@ -0,0 +1,214 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codeset; + +import CodeSetTester.Verifier ; +import CodeSetTester.VerifierHelper ; +import CodeSetTester.VerifierPackage.TestCharSeqHolder; +import CodeSetTester.VerifierPackage.TestWCharSeqHolder; +import java.util.Properties; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.encoding.OSFCodeSetRegistry; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +public class Client +{ + private static final char TEST_CHAR = 'f'; + private static final char TEST_WCHAR = '\u3044'; + + public static void testTransmission(Verifier ver, + boolean testValueTypes) throws Exception + { + char[] latin1 = CharGenerator.getLatin1Chars(); + char[] someUnicode = CharGenerator.getSomeUnicodeChars(); + + System.out.println("Testing char..."); + char res = ver.verifyChar(Client.TEST_CHAR); + if (res != Client.TEST_CHAR) + throw new Exception("Invalid char result: " + res); + + System.out.println("Testing wchar..."); + res = ver.verifyWChar(Client.TEST_WCHAR); + if (res != Client.TEST_WCHAR) + throw new Exception("Invalid wchar result: (int)" + (int)res); + + System.out.println("Testing string..."); + String sending = new String(latin1); + String resStr = ver.verifyString(sending); + if (!sending.equals(resStr)) { + System.out.println("Got: " + resStr.length()); + System.out.println("Expected: " + sending.length()); + throw new Exception("Invalid result string: " + resStr); + } + + System.out.println("Testing wstring..."); + sending = new String(someUnicode); + resStr = ver.verifyWString(sending); + if (!sending.equals(resStr)) { + System.out.println("Got: " + resStr.length()); + System.out.println("Expected: " + sending.length()); + if (resStr.length() != sending.length()) { + throw new Exception("different lengths"); + } + for (int i = 0; i < sending.length(); i++) { + if (sending.charAt(i) != resStr.charAt(i)) { + System.out.println("chars not eq:"); + } + if (Character.UnicodeBlock.of(sending.charAt(i)) != + Character.UnicodeBlock.of(resStr.charAt(i))) { + System.out.println("chars UnicodeBlock not eq:"); + } + System.out.println( + "send: " + + sending.charAt(i) + + " " + Character.UnicodeBlock.of(sending.charAt(i)) + + "/n" + + "recv: " + + resStr.charAt(i) + + " " + Character.UnicodeBlock.of(resStr.charAt(i)) + ); + } + throw new Exception("Invalid result wstring: \n" + + " Got: " + resStr + "\n" + + " Expected: " + sending); + } + + System.out.println("Testing char sequence..."); + char[] inputCopy = new char[latin1.length]; + System.arraycopy(latin1, 0, inputCopy, 0, latin1.length); + TestCharSeqHolder chHolder = new TestCharSeqHolder(inputCopy); + ver.verifyCharSeq(chHolder); + if (chHolder.value == null) + throw new Exception("Got null char sequence"); + if (chHolder.value.length != latin1.length) + throw new Exception("Result char sequence of different length: " + + chHolder.value.length); + for (int i = 0; i < latin1.length; i++) + if (chHolder.value[i] != latin1[i]) + throw new Exception("Unequal char at idx " + i); + + System.out.println("Testing wchar sequence..."); + inputCopy = new char[someUnicode.length]; + System.arraycopy(someUnicode, 0, inputCopy, 0, someUnicode.length); + TestWCharSeqHolder wchHolder = new TestWCharSeqHolder(inputCopy); + ver.verifyWCharSeq(wchHolder); + if (wchHolder.value == null) + throw new Exception("Got null wchar sequence"); + if (wchHolder.value.length != someUnicode.length) + throw new Exception("Result wchar sequence of different length: " + + wchHolder.value.length); + for (int i = 0; i < someUnicode.length; i++) + if (wchHolder.value[i] != someUnicode[i]) + throw new Exception("Unequal wchar at idx " + i); + + if (testValueTypes) { + + System.out.println("Testing custom marshaler..."); + CodeSetTester.CustomMarshaledValueImpl cv + = new CodeSetTester.CustomMarshaledValueImpl(Client.TEST_CHAR, + Client.TEST_WCHAR, + new String(latin1), + new String(someUnicode), + latin1, + someUnicode); + + CodeSetTester.CustomMarshaledValue rescv = ver.verifyTransmission(cv); + + if (!cv.equals(rescv)) { + System.out.println("Unequal custom values:"); + System.out.println("old: " + cv); + System.out.println("new: " + rescv); + + throw new Exception("Unequal custom values"); + } + } + + System.out.println("PASSED"); + } + + /** + * Tests the ORB's ability to parse our code set + * property. + */ + public static void testORBCodeSetListParsing() throws Exception { + + System.out.println("Testing code set list parsing..."); + + StringBuffer list1 = new StringBuffer(); + list1.append(OSFCodeSetRegistry.ISO_8859_1.getNumber()); + list1.append(",0x"); + list1.append(Integer.toHexString(OSFCodeSetRegistry.UTF_8.getNumber())); + + StringBuffer list2 = new StringBuffer(); + list2.append("0x"); + list2.append(Integer.toHexString(OSFCodeSetRegistry.UTF_16.getNumber())); + list2.append(", "); + list2.append(OSFCodeSetRegistry.UTF_8.getNumber()); + list2.append(","); + list2.append(OSFCodeSetRegistry.UCS_2.getNumber()); + + Properties props = new Properties(); + props.setProperty(ORBConstants.CHAR_CODESETS, + list1.toString()); + props.setProperty(ORBConstants.WCHAR_CODESETS, + list2.toString()); + + // Should throw INITIALIZE if there are any problems + ORB testORB1 = ORB.init((String[])null, props); + + testORB1.shutdown(false); + + System.out.println("PASSED"); + } + + public static void main(String args[]) + { + try { + // First test parsing of the code set + // properties + Client.testORBCodeSetListParsing(); + + // create and initialize the ORB + ORB orb = ORB.init(args, System.getProperties()); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent("Verifier", ""); + NameComponent path[] = {nc}; + Verifier verifierRef = VerifierHelper.narrow(ncRef.resolve(path)); + + // We don't support valuetypes in GIOP 1.1, so don't bother + // testing them. + String giopVersion = System.getProperty(ORBConstants.GIOP_VERSION); + boolean testValueTypes = (giopVersion == null || + !giopVersion.equals("1.1")); + + System.out.println("GIOP version: " + giopVersion); + System.out.println("Test value types? " + testValueTypes); + + Client.testTransmission(verifierRef, testValueTypes); + + orb.shutdown(true); + + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } +} diff --git a/functional-tests/src/test/java/corba/codeset/CodeSetTest.java b/functional-tests/src/test/java/corba/codeset/CodeSetTest.java new file mode 100644 index 000000000..7a44ee1be --- /dev/null +++ b/functional-tests/src/test/java/corba/codeset/CodeSetTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codeset; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.CORBA.*; + +/** + * Simple tests in GIOP 1.1 and 1.2 of chars and wstrings. + */ +public class CodeSetTest extends CORBATest +{ + protected void doTest() throws Throwable + { + // Now GIOP 1.1. + Controller orbd = createORBD(); + + // Specify the GIOP version property + Properties clientProps = Options.getClientProperties(); + Properties serverProps = Options.getServerProperties(); + + clientProps.setProperty(ORBConstants.GIOP_VERSION, "1.1"); + serverProps.setProperty(ORBConstants.GIOP_VERSION, "1.2"); + clientProps.setProperty(ORBConstants.GIOP_FRAGMENT_SIZE, "32"); + serverProps.setProperty(ORBConstants.GIOP_FRAGMENT_SIZE, "64"); + + Controller server = createServer("corba.codeset.Server", + "server"); + Controller client = createClient("corba.codeset.Client", + "client1_1"); + + orbd.start(); + server.start(); + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + client.stop(); + + // Now try GIOP 1.2 + clientProps.setProperty(ORBConstants.GIOP_FRAGMENT_SIZE, "256"); + clientProps.setProperty(ORBConstants.GIOP_VERSION, "1.2"); + client = createClient("corba.codeset.Client", + "client1_2"); + + client.start(); + client.waitFor(120000); + client.stop(); + + server.stop(); + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/corba/codeset/CustomMarshaledValueImpl.java b/functional-tests/src/test/java/corba/codeset/CustomMarshaledValueImpl.java new file mode 100644 index 000000000..5b291e00f --- /dev/null +++ b/functional-tests/src/test/java/corba/codeset/CustomMarshaledValueImpl.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package CodeSetTester; + +import java.util.Arrays; +import org.omg.CORBA.DataOutputStream; +import org.omg.CORBA.DataInputStream; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.CharSeqHelper; +import org.omg.CORBA.WCharSeqHelper; + +// Custom marshaled valuetype with all the data types we're interested in. + +public class CustomMarshaledValueImpl extends CustomMarshaledValue +{ + public CustomMarshaledValueImpl() { + str = ""; + wstr = ""; + } + + public CustomMarshaledValueImpl(char ch, + char wch, + String str, + String wstr, + char[] chSeq, + char[] wchSeq) { + this.ch = ch; + this.wch = wch; + if (str == null) + this.str = ""; + else + this.str = new String(str); + if (wstr == null) + this.wstr = ""; + else + this.wstr = new String(wstr); + this.chSeq = chSeq; + this.wchSeq = wchSeq; + } + + public String toString() { + StringBuffer sbuf = new StringBuffer(); + + sbuf.append("ch: "); + sbuf.append((int)ch); + sbuf.append(" wch: "); + sbuf.append((int)wch); + sbuf.append(" str: "); + if (str == null) + sbuf.append("null"); + else + sbuf.append(str.length()); + sbuf.append(" wstr: "); + if (wstr == null) + sbuf.append("null"); + else + sbuf.append(wstr.length()); + + sbuf.append(" chSeq: "); + if (chSeq == null) + sbuf.append("null"); + else { + for (int i = 0; i < chSeq.length; i++) { + sbuf.append((int)chSeq[i]); + sbuf.append(' '); + } + } + + sbuf.append(" wchSeq: "); + if (wchSeq == null) + sbuf.append("null"); + else { + for (int i = 0; i < wchSeq.length; i++) { + sbuf.append((int)wchSeq[i]); + sbuf.append(' '); + } + } + + return sbuf.toString(); + } + + public boolean equals(Object obj) { + try { + CustomMarshaledValue cmv = (CustomMarshaledValue)obj; + + return (ch == cmv.ch && + wch == cmv.wch && + ((str == null && cmv.str == null) || + (str.equals(cmv.str))) && + ((wstr == null && cmv.wstr == null) || + (wstr.equals(cmv.wstr))) && + Arrays.equals(chSeq, cmv.chSeq) && + Arrays.equals(wchSeq, cmv.wchSeq)); + + } catch (ClassCastException cce) { + return false; + } + } + + public void unmarshal(DataInputStream is) { + System.out.println("Unmarshaling custom data..."); + ch = is.read_char(); + wch = is.read_wchar(); + str = is.read_string(); + wstr = is.read_wstring(); + + chSeq = CharSeqHelper.read((InputStream)is); + wchSeq = WCharSeqHelper.read((InputStream)is); + + System.out.println("Done"); + } + + public void marshal(DataOutputStream os) { + System.out.println("Marshaling custom data..."); + os.write_char(ch); + os.write_wchar(wch); + os.write_string(str); + os.write_wstring(wstr); + + if (chSeq == null) + os.write_long(0); + else + CharSeqHelper.write((OutputStream)os, chSeq); + + if (wchSeq == null) + os.write_long(0); + else + WCharSeqHelper.write((OutputStream)os, wchSeq); + + System.out.println("Done"); + } +} diff --git a/functional-tests/src/test/java/corba/codeset/Server.java b/functional-tests/src/test/java/corba/codeset/Server.java new file mode 100644 index 000000000..15c172fe3 --- /dev/null +++ b/functional-tests/src/test/java/corba/codeset/Server.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codeset; + +import CodeSetTester.VerifierPOA; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.PortableServer.POA; + +public class Server extends VerifierPOA +{ + public char verifyChar (char ch) { + System.out.println("verifyChar " + (int)ch); + return ch; + } + + public char verifyWChar (char wch) { + System.out.println("verifyWChar " + (int)wch); + return wch; + } + + public String verifyString (String str) { + System.out.println("verifyString " + str); + return str; + } + + public String verifyWString (String wstr) { + System.out.println("verifyWString " + wstr.length()); + return wstr; + } + + public void verifyCharSeq (CodeSetTester.VerifierPackage.TestCharSeqHolder chSeq) { + System.out.println("verifyCharSeq " + chSeq.value.length); + } + + public void verifyWCharSeq (CodeSetTester.VerifierPackage.TestWCharSeqHolder wchSeq) { + System.out.println("verifyWCharSeq " + wchSeq.value.length); + } + + public CodeSetTester.CustomMarshaledValue verifyTransmission (CodeSetTester.CustomMarshaledValue cv) { + return cv; + } + + public static void main(String args[]) + { + try { + + ORB orb = ORB.init(args, System.getProperties()); + System.out.println(orb); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + // create servant and register it with the ORB + Server verifierRef = new Server(); + + byte[] id = rootPOA.activate_object(verifierRef); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("Verifier", ""); + NameComponent path[] = {nc}; + + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + ncRef.rebind(path, ref); + + // Emit the handshake the test framework expects + // (can be changed in Options by the running test) + System.out.println ("Server is ready."); + + // Wait for clients + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + + // Make sure to exit with a value greater than 0 on + // error. + System.exit(1); + } + } +} diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/CRI.java b/functional-tests/src/test/java/corba/connectintercept_1_4/CRI.java new file mode 100644 index 000000000..d08453f0f --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/CRI.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 16 (Mon) 14:55:05 by Harold Carr. +// Last Modified : 2003 Feb 11 (Tue) 14:09:38 by Harold Carr. +// + + +package corba.connectintercept_1_4; + +import com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.INTERNAL; +import org.omg.IOP.TaggedComponent; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; + +public class CRI + extends + org.omg.CORBA.LocalObject + implements + ClientRequestInterceptor +{ + public static final String baseMsg = CRI.class.getName(); + + public int balance = 0; + + public String name() { return baseMsg; } + + public void destroy() + { + if (balance != 0) { + throw new RuntimeException(baseMsg + ": Interceptors not balanced."); + } + } + + public void send_request(ClientRequestInfo cri) + { + balance++; + System.out.println(baseMsg + ".send_request " + cri.operation()); + System.out.println(" request on connection: " + + ((RequestInfoExt)cri).connection()); + + try { + TaggedComponent taggedComponent = + cri.get_effective_component(Common.ListenPortsComponentID); + String componentData = + new String(taggedComponent.component_data); + System.out.println(" found ListenPortsComponentID: " + + componentData); + } catch (BAD_PARAM e) { + // This is ignored because we talk to naming which + // will not contain the listen component. + } + } + + public void send_poll(ClientRequestInfo cri) + { + balance++; + System.out.println(baseMsg + ".send_poll " + cri.operation()); + } + + public void receive_reply(ClientRequestInfo cri) + { + balance--; + System.out.println(baseMsg + ".receive_reply " + cri.operation()); + } + + public void receive_exception(ClientRequestInfo cri) + { + balance--; + System.out.println(baseMsg + ".receive_exception " + cri.operation()); + } + + public void receive_other(ClientRequestInfo cri) + { + balance--; + System.out.println(baseMsg + ".receive_other " + cri.operation()); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/CRIOrdered.java b/functional-tests/src/test/java/corba/connectintercept_1_4/CRIOrdered.java new file mode 100644 index 000000000..33c06b8c2 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/CRIOrdered.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 20 (Fri) 11:22:06 by Harold Carr. +// Last Modified : 2002 Mar 22 (Fri) 09:31:59 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.CORBA.INTERNAL; +import org.omg.PortableInterceptor.ClientRequestInfo; + +public class CRIOrdered + extends + org.omg.CORBA.LocalObject + implements + org.omg.PortableInterceptor.ClientRequestInterceptor, + Comparable +{ + public static final String baseMsg = CRIOrdered.class.getName(); + public String name; + public int order; + public CRIOrdered(String name, int order) + { + this.name = name; + this.order = order; + } + public int compareTo(Object o) + { + int otherOrder = ((CRIOrdered)o).order; + if (order < otherOrder) { + return -1; + } else if (order == otherOrder) { + return 0; + } + return 1; + } + public String name() { return name; } + + public void destroy() + { + try { + Common.up(order); + } catch (INTERNAL e) { + // INTERNAL will get swallowed by ORB. + // Convert it to something else so server will exit incorrectly + // so error can be detected. + throw new RuntimeException(baseMsg + ": Wrong order in destroy."); + } + } + + public void send_request(ClientRequestInfo cri) + { + Common.up(order); + } + public void send_poll(ClientRequestInfo cri) + { + Common.up(order); + } + public void receive_reply(ClientRequestInfo cri) + { + Common.down(order); + } + public void receive_exception(ClientRequestInfo cri) + { + Common.down(order); + } + public void receive_other(ClientRequestInfo cri) + { + Common.down(order); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/Client.java b/functional-tests/src/test/java/corba/connectintercept_1_4/Client.java new file mode 100644 index 000000000..efe3ff5dd --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/Client.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : by Everett Anderson. +// Last Modified : 2004 Apr 14 (Wed) 19:25:53 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import java.util.Properties; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class Client +{ + public static final String baseMsg = Client.class.getName(); + + public static final String defaultFactoryClassName = + //REVISIT Common.DEFAULT_FACTORY_CLASS + "com.sun.corba.ee.impl.legacy.connection.DefaultSocketFactory"; + + public static void main(String args[]) + { + try { + Properties props = new Properties(); + + props.setProperty(Common.ORBClassKey, MyPIORB.class.getName()); + + props.setProperty(ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + ClientORBInitializer.class.getName(), + "dummy"); + + // + // Case 1. + // + + System.out.println(); + System.out.println("Case 1: Default factory"); + System.out.println(); + + testFactory(args, + props, + defaultFactoryClassName + ); + + + // + // Case 2. + // + + System.out.println(); + System.out.println("Case 2: Custom factory"); + System.out.println(); + + props.put(ORBConstants.LEGACY_SOCKET_FACTORY_CLASS_PROPERTY, + Common.CUSTOM_FACTORY_CLASS); + + testFactory(args, + props, + Common.CUSTOM_FACTORY_CLASS); + + // + // Success. + // + + System.out.println(); + System.out.println(baseMsg + ".main: Test PASSED."); + + } catch (Exception e) { + System.out.println(baseMsg + ".main: Test FAILED: " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } + + public static void testFactory(String args[], + Properties props, + String factoryName) + throws Exception + { + ORB orb = ORB.init(args, props); + + Common.upDownReset(); + + resolveAndInvoke(orb, Common.serverName1); + + // Invoke on another object in same server to observe + // already connected behavior. + resolveAndInvoke(orb, Common.serverName2); + + + // Make sure that the factory that was used matches the name given. + ORBSocketFactory socketFactory = + ((com.sun.corba.ee.spi.orb.ORB)orb).getORBData().getLegacySocketFactory(); + if (socketFactory == null) { + if (factoryName.equals(defaultFactoryClassName)) { + // OK - default does not use socket factory any longer. + ; + } else { + // Not the default - so expect a socket factory. + throw new Exception(baseMsg + "unexpected null socketFactory"); + } + } else { + String orbSocketFactoryName = socketFactory.getClass().getName(); + if (! factoryName.equals(orbSocketFactoryName)) { + throw new Exception(baseMsg + ".testFactory: " + + "Wrong socket factory class: " + + orbSocketFactoryName + + " should be " + + factoryName); + } + } + orb.shutdown(false); + orb.destroy(); + } + + public static void resolveAndInvoke (ORB orb, String name) + throws + Exception + { + ExI exIRef; + + System.out.println(); + System.out.println("BEGIN: invoke on " + name); + + exIRef = ExIHelper.narrow(resolve("First", name, orb)); + + // The second resolve is to observe caching behavior. + + exIRef = ExIHelper.narrow(resolve("Second", name, orb)); + + // The multiple invokes are to observe using various + // endpoints in the component data (and to observe caching behavior). + + invoke("First", exIRef); + invoke("Second", exIRef); + invoke("Third", exIRef); + invoke("Fourth", exIRef); + invoke("Fifth", exIRef); + + System.out.println("END: invoke on " + name); + } + + public static org.omg.CORBA.Object resolve(String msg, + String name, + ORB orb) + throws Exception + { + // List initial references. + + System.out.println(); + System.out.println("BEGIN: " + msg + " list_initial_references."); + + String services[] = orb.list_initial_services(); + for (int i = 0; i < services.length; i++) { + System.out.print(" " + services[i]); + } + System.out.println(); + + System.out.println("END: " + msg + " list_initial_references."); + + + // Resolve. + + System.out.println(); + System.out.println("BEGIN: " + msg + " resolve."); + + org.omg.CORBA.Object ref + = ExIHelper.narrow(Common.getNameService(orb) + .resolve(Common.makeNameComponent(name))); + + System.out.println("END: " + msg + " resolve."); + return ref; + } + + public static void invoke(String msg, ExI exIRef) + { + System.out.println(); + System.out.println("BEGIN: " + msg + " invocation."); + + exIRef.sayHello(); + + System.out.println("END: " + msg + " invocation."); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ClientORBInitializer.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ClientORBInitializer.java new file mode 100644 index 000000000..1f37f9603 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ClientORBInitializer.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 13 (Fri) 09:55:19 by Harold Carr. +// Last Modified : 2002 Mar 24 (Sun) 09:22:30 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; + +public class ClientORBInitializer + extends + org.omg.CORBA.LocalObject + implements + ORBInitializer +{ + public static final String baseMsg = ClientORBInitializer.class.getName(); + + public void pre_init(ORBInitInfo orbInitInfo) { } + + public void post_init(ORBInitInfo orbInitInfo) + { + try { + // These are intentionally random to test ordering. + + orbInitInfo.add_client_request_interceptor( + new CRIOrdered("Three", 3)); + + orbInitInfo.add_client_request_interceptor( + new CRIOrdered("One", 1)); + + orbInitInfo.add_client_request_interceptor( + new CRI()); + + orbInitInfo.add_client_request_interceptor( + new CRIOrdered("Two", 2)); + + System.out.println(baseMsg + ".post_init: add_* completed."); + } catch (DuplicateName ex) { + System.out.println(baseMsg + ".post_init: " + ex); + System.exit(-1); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/Common.java b/functional-tests/src/test/java/corba/connectintercept_1_4/Common.java new file mode 100644 index 000000000..7a350056d --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/Common.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Sep 26 (Tue) 16:26:48 by Harold Carr. +// Last Modified : 2004 Jun 06 (Sun) 12:21:53 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; + +import com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt; +import com.sun.corba.ee.spi.legacy.interceptor.UnknownType; + +public abstract class Common +{ + public static String baseMsg = Common.class.getName(); + + public static final String ORBClassKey = "org.omg.CORBA.ORBClass"; + + public static final String DEFAULT_FACTORY_CLASS = + "com.sun.corba.ee.impl.legacy.connection.DefaultSocketFactory"; + + public static final String CUSTOM_FACTORY_CLASS = + MySocketFactory.class.getName(); + + public static final String serverName1 = "ExI1"; + public static final String serverName2 = "ExI2"; + + public static final String MyType1 = "MyType1"; + public static final String MyType2 = "MyType2"; + public static final String MyType3 = "MyType3"; + public static final int MyType1TransientPort = 2000; + public static final int MyType2TransientPort = 2001; + public static final int MyType3TransientPort = 0; + public static final int MyType1PersistentPort = 0; + public static final int MyType2PersistentPort = 0; + public static final int MyType3PersistentPort = 0; + + public static final int ListenPortsComponentID = 4545; + + public static final String DummyType = "DummyType"; + public static final String DummyHost = "DummyHost"; + public static final int DummyPort = 65000; + + public static final String Transient = "Transient"; + public static final String Persistent = "Persistent"; + + // To test proprietary interceptor ordering. + // These are used by both client and server, but in + // different VMs - so no conflict. + + public static int currentOrder = 1; + + // Need to reset before each case (since destroy leaves it + // at 3 but first invocation expects 1. + public static void upDownReset() { currentOrder = 1; } + + public static void up(int x) + { + if (x >= currentOrder) { + currentOrder = x; + } else { + throw new INTERNAL("Interceptor ordering (up): " + + x + " " + currentOrder, + -45, + CompletionStatus.COMPLETED_MAYBE); + } + } + + public static void down(int x) + { + if (x <= currentOrder) { + currentOrder = x; + } else { + throw new INTERNAL("Interceptor ordering (down): " + + x + " " + currentOrder, + -45, + CompletionStatus.COMPLETED_MAYBE); + } + } + + public static String createComponentData(String msg, Object o) + { + String ccd = baseMsg + ".createComponentData"; + int MyType1Port = -1; + int MyType2Port = -1; + int MyType3Port = -1; + if (o instanceof IORInfoExt) { + try { + MyType1Port = ((IORInfoExt)o).getServerPort(Common.MyType1); + MyType2Port = ((IORInfoExt)o).getServerPort(Common.MyType2); + MyType3Port = ((IORInfoExt)o).getServerPort(Common.MyType3); + } catch (UnknownType ex) { + System.out.println(ccd + ": " + ex); + System.exit(-1); + } + } else { + throw new RuntimeException(ccd + + ": unexpected type of object: " + o); + } + + return createComponentData(msg, MyType1Port, MyType2Port, MyType3Port); + } + + public static String createComponentData(String msg, + int MyType1Port, + int MyType2Port, + int MyType3Port) + { + String componentData = + Common.MyType1 + ":" + MyType1Port + "," + + Common.MyType2 + ":" + MyType2Port + "," + + Common.MyType3 + ":" + MyType3Port; + System.out.println(msg + " componentData: " + componentData); + + return componentData; + } + + public static NamingContext getNameService(ORB orb) + { + org.omg.CORBA.Object objRef = null; + try { + objRef = orb.resolve_initial_references("NameService"); + } catch (Exception ex) { + System.out.println("Common.getNameService: " + ex); + ex.printStackTrace(System.out); + System.exit(-1); + } + return NamingContextHelper.narrow(objRef); + } + + public static NameComponent[] makeNameComponent(String name) + { + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + return path; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ConnectIntercept_1_4Test.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ConnectIntercept_1_4Test.java new file mode 100644 index 000000000..0b7a47060 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ConnectIntercept_1_4Test.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Mar 24 (Sun) 09:04:46 by Harold Carr. +// Last Modified : 2002 Jul 24 (Wed) 11:08:55 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +public class ConnectIntercept_1_4Test + extends + CORBATest +{ + public static final String thisPackage = + ConnectIntercept_1_4Test.class.getPackage().getName(); + + protected void doTest() + throws + Throwable + { + Controller orbd = createORBD(); + orbd.start(); + + Controller server = createServer(thisPackage + "." + "ServerTransient", + "ServerTransient"); + Controller client = createClient(thisPackage + "." + "Client", + "ClientTransient"); + server.start(); + client.start(); + client.waitFor(120000); + client.stop(); + server.stop(); + orbd.stop(); + + // REVISIT: + // Need to do integrate persistent test into test framework. + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/MyPIORB.java b/functional-tests/src/test/java/corba/connectintercept_1_4/MyPIORB.java new file mode 100644 index 000000000..3556fbb76 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/MyPIORB.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Sep 27 (Wed) 17:37:35 by Harold Carr. +// Last Modified : 2002 Dec 04 (Wed) 21:00:16 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.impl.orb.ORBImpl; + +public class MyPIORB + extends + ORBImpl +{ + public static final String baseMsg = + MyPIORB.class.getName() + ".objectReferenceCreated: "; + + protected IOR objectReferenceCreated (IOR ior) + { + String componentData = Common.createComponentData(baseMsg, this); + + // This test puts the information in the IOR via + // the ServerIORInterceptor. The example here is just to + // show how to use the old hooks to get the info. + // You would put that info in the given IOR similar to + // the ServerIORInterceptor code then return the augmented + // ior. + return ior ; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/MySocketFactory.java b/functional-tests/src/test/java/corba/connectintercept_1_4/MySocketFactory.java new file mode 100644 index 000000000..fe5ff4413 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/MySocketFactory.java @@ -0,0 +1,310 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : by Everett Anderson. +// Last Modified : 2004 May 12 (Wed) 11:42:45 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.*; + +import org.omg.CORBA.ORB; +import org.omg.IOP.TaggedComponent; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.legacy.connection.GetEndPointInfoAgainException; +import com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class MySocketFactory + implements + ORBSocketFactory +{ + private Hashtable iorSocketInfo = new Hashtable(); + + public static int numCallsGetEndPointInfo = 0; + public static int numCallsCreateSocket = 0; + + // + // Constructor used during ORB initialization. + // + + public MySocketFactory() + { + System.out.println("MySocketFactory()"); + } + + // + // Server side. + // + + public ServerSocket createServerSocket(String type, int port) + throws + IOException + { + System.out.println("createServerSocket(" + type + ", " + port + ")"); + createSocketMessage("ServerSocket", type, "localhost", port); + + if (type.equals(ORBSocketFactory.IIOP_CLEAR_TEXT)) { + ServerSocketChannel serverSocketChannel = + ServerSocketChannel.open(); + ServerSocket serverSocket = serverSocketChannel.socket(); + serverSocket.bind(new InetSocketAddress(port)); + return serverSocket; + } else { + return new ServerSocket(port); + } + } + + // + // Client side. + // + + public SocketInfo getEndPointInfo(ORB orb, + IOR ior, + SocketInfo socketInfo) + { + numCallsGetEndPointInfo++; + + System.out.println("MySocketFactory.getEndPointInfo: entering."); + + if (socketInfo != null) { + if (socketInfo instanceof SocketInfoImpl) { + System.out.println( + "MySocketFactory.getEndPointInfo: found cookie: " + + ((SocketInfoImpl)socketInfo).getCookie()); + } else { + throw new RuntimeException("Wrong type of cookie"); + } + } + + // Get the clear text host/port form the profile. + + IIOPProfileTemplate temp = (IIOPProfileTemplate)ior.getProfile().getTaggedProfileTemplate() ; + IIOPAddress primary = temp.getPrimaryAddress() ; + String host = primary.getHost().toLowerCase(); + int port = primary.getPort(); + + if (/*false*/ socketInfo == null) { + // The first time it is called on each invocation + // we give bad info so we can raise an exception + // in createSocket and end up here again to test + // the get info loop. + socketInfo = + new SocketInfoImpl(Common.DummyType, + Common.DummyHost, + Common.DummyPort, + "dummy cookie"); + printSocketInfoReturn(host, port, socketInfo); + return socketInfo; + } + + // The only time we should ever get called with our cookie + // is when we "pass ourselves" the above dummy info. + // Check this is the case and ignore the dummy info. + + if (socketInfo != null) { + if (!socketInfo.getType().equals(Common.DummyType) || + !socketInfo.getHost().equals(Common.DummyHost) || + socketInfo.getPort() != Common.DummyPort) + { + throw new RuntimeException("MySocketFactory.getEndPointInfo: should never happen."); + } + } + + // Another loop for the test. + // If the component has alternate type/port info (assume same host) + // then set up a list to iterate down on each call, starting + // over when list is empty. + // The cycle is (default, 1, 2, 3)*; + Vector portList = (Vector) iorSocketInfo.get(ior); + if (portList == null) { + TaggedComponent taggedComponents[] = + ior.getProfile().getTaggedProfileTemplate().getIOPComponents( + (com.sun.corba.ee.spi.orb.ORB)orb, Common.ListenPortsComponentID); + if (taggedComponents.length > 0) { + String componentData = + new String(taggedComponents[0].component_data); + System.out.println("componentData: " + componentData); + iorSocketInfo.put(ior, parseComponentData(componentData)); + } + socketInfo = + new SocketInfoImpl(ORBSocketFactory.IIOP_CLEAR_TEXT, + host, + port, + "clear text cookie"); + } else { + TypePortPair nextPair = (TypePortPair)portList.remove(0); + if (portList.size() == 0) { + // When there is not more remembered info remove + // it from the cache so it will start over. + iorSocketInfo.remove(ior); + } + socketInfo = + new SocketInfoImpl(nextPair.getType(), + host, + nextPair.getPort(), + "component cookie"); + } + printSocketInfoReturn(host, port, socketInfo); + return socketInfo; + } + + private void printSocketInfoReturn(String host, + int port, + SocketInfo socketInfo) + { + System.out.println("getEndPointInfo(" + host + ", " + port + ")" + + " = " + socketInfo); + } + + public Socket createSocket(SocketInfo socketInfo) + throws + IOException, + GetEndPointInfoAgainException + { + numCallsCreateSocket++; + + String type = socketInfo.getType(); + String host = socketInfo.getHost(); + int port = socketInfo.getPort(); + System.out.println("createSocket(" + type + ", " + host + ", " + port +")"); + if (type.equals(Common.DummyType) && + host.equals(Common.DummyHost) && + port == Common.DummyPort) + { + // This is to test the "get info" loop. + throw new GetEndPointInfoAgainException(socketInfo); + } + + createSocketMessage("ClientSocket", type, host, port); + + if (type.equals(ORBSocketFactory.IIOP_CLEAR_TEXT)) { + InetSocketAddress address = + new InetSocketAddress(host, port); + SocketChannel socketChannel = ORBUtility.openSocketChannel(address); + Socket socket = socketChannel.socket(); + try { + socket.setTcpNoDelay(true); + } catch (Exception e) { + } + return socket; + } else { + return new Socket(host, port); + } + } + + private void createSocketMessage(String clientOrServer, + String type, + String host, + int port) + { + System.out.println(" creating " + clientOrServer + + " " + type + " " + host + " " + port); + } + + private Vector parseComponentData(String componentData) + { + // REVISIT: + // Workaround for: + // componentData: ^@^@^@^@^@^@^@*MyType1:48154,MyType2:48155,MyType3:48156^@ + // when getting forwarded IOR from orbd. + if (!componentData.startsWith(Common.MyType1)) { + componentData = new String(componentData.getBytes(), + 8, + componentData.length() - 9); + } + + + Vector typePortPairs = new Vector(); + StringTokenizer pairs = + new StringTokenizer(componentData, ","); + while (pairs.hasMoreTokens()) { + String current = pairs.nextToken(); + StringTokenizer pair = new StringTokenizer(current, ":"); + String type = null; + int port = -1; + if (pair.hasMoreTokens()) { + type = pair.nextToken(); + if (pair.hasMoreTokens()) { + try { + port = Integer.parseInt(pair.nextToken()); + } catch (NumberFormatException e) { + } + } + } + if (type == null || port == -1) { + throw new RuntimeException("Improper ORBListenSocket format: " + + componentData); + } + typePortPairs.add(new TypePortPair(type, port)); + } + return typePortPairs; + } +} + +class SocketInfoImpl + extends + com.sun.corba.ee.impl.legacy.connection.EndPointInfoImpl +{ + String cookie; + + SocketInfoImpl(String type, String host, int port, String cookie) + { + super(type, port, host); + this.cookie = cookie; + } + + String getCookie() + { + return cookie; + } + + @Override + public String toString() + { + return + "(SocketInfoImpl " + type + + " " + hostname + " " + port + + " " + cookie + + ")"; + } +} + +class TypePortPair +{ + private String type; + private int port; + TypePortPair (String type, int port) + { + this.type = type; + this.port = port; + } + public String getType () { return type; } + public int getPort () { return port; } + @Override + public String toString () { return type + ":" + port; } +} + + + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ORBDBadServerIdHandler.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ORBDBadServerIdHandler.java new file mode 100644 index 000000000..edf6b46bc --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ORBDBadServerIdHandler.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 by Harold Carr. +// Last Modified : 2004 Apr 29 (Thu) 16:28:35 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import com.sun.corba.ee.spi.activation.IIOP_CLEAR_TEXT; +import com.sun.corba.ee.spi.activation.EndPointInfo; +import com.sun.corba.ee.spi.activation.Locator; +import com.sun.corba.ee.spi.activation.LocatorHelper; +import com.sun.corba.ee.spi.activation.LocatorPackage.ServerLocationPerORB; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.ObjectKeyFactory ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.protocol.ForwardException; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +import com.sun.corba.ee.impl.ior.IORImpl; +import com.sun.corba.ee.impl.ior.POAObjectKeyTemplate ; + +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler; + +import com.sun.corba.ee.impl.util.Utility; + +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.CORBA.OBJECT_NOT_EXIST; + +public class ORBDBadServerIdHandler + implements + BadServerIdHandler +{ + public static final String baseMsg = + ORBDBadServerIdHandler.class.getName(); + + private ORB orb; + + public ORBDBadServerIdHandler(org.omg.CORBA.ORB orb) + { + this.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + } + + public void handle(ObjectKey okey) + { + Locator locator = null; + try { + locator = LocatorHelper.narrow(orb.resolve_initial_references(ORBConstants.SERVER_LOCATOR_NAME)); + } catch (InvalidName ex) { + // Should never happen. + System.out.println("ORBDBadServerIdHandler.handle: " + ex); + System.exit(-1); + } + + IOR newIOR = null; + ServerLocationPerORB location; + + POAObjectKeyTemplate poktemp = (POAObjectKeyTemplate) + (okey.getTemplate()); + int serverId = poktemp.getServerId() ; + String orbId = poktemp.getORBId() ; + + try { + location = locator.locateServerForORB(serverId, orbId); + + int clearPort = + locator.getServerPortForType(location, IIOP_CLEAR_TEXT.value); + + int myType1Port + = locator.getServerPortForType(location, Common.MyType1); + int myType2Port + = locator.getServerPortForType(location, Common.MyType2); + int myType3Port + = locator.getServerPortForType(location, Common.MyType3); + + String componentData = + Common.createComponentData(baseMsg + ".handle: ", + myType1Port, + myType2Port, + myType3Port); + + /* + 1. Use ObjectKeyFactory.create( byte[]) to convert byte[] + object key to ObjectKey (if it's not already ObjectKey). + Note that the arg type will change to a stream in my next + putback. + 2. Use host and port to construct an IIOPAddress. + 3. Use address from 2, object key template from 1, and GIOP + version info to construct IIOPProfileTemplate. + 4. Add tagged components to IIOPProfileTemplate. + 5. Use IIOPProfileTemplate from 4 and ObjectId from 1 + to construct IIOPProfile. + 6. Construct IOR from ORB and repid. + 7. Add IIOPProfile to IOR. + 8. Make IOR immutable. + */ + + IIOPProfileTemplate sipt = + IIOPFactories.makeIIOPProfileTemplate( + (com.sun.corba.ee.spi.orb.ORB)orb, + GIOPVersion.V1_2, + IIOPFactories.makeIIOPAddress( location.hostname, clearPort)); + sipt.add(new ORBDListenPortsComponent(componentData)); + IORTemplate iortemp = IORFactories.makeIORTemplate( poktemp ) ; + iortemp.add( sipt ) ; + newIOR = iortemp.makeIOR( (com.sun.corba.ee.spi.orb.ORB)orb, + "IDL:org/omg/CORBA/Object:1.0", okey.getId() ); + + /* + // REVISIT - add component data. + + newIOR = new IOR((com.sun.corba.ee.spi.orb.ORB)orb, + "IDL:org/omg/CORBA/Object:1.0", + location.hostname, + myType2Port, // REVISIT - clearPort + objectKey); + */ + } catch (Exception e) { + // For this example, all exceptions map to: + throw new OBJECT_NOT_EXIST(); + } + + throw new ForwardException( (com.sun.corba.ee.spi.orb.ORB)orb, newIOR); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ORBDListenPortsComponent.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ORBDListenPortsComponent.java new file mode 100644 index 000000000..9fe96f200 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ORBDListenPortsComponent.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 17 (Tue) 08:36:51 by Harold Carr. +// Last Modified : 2002 Dec 04 (Wed) 21:00:53 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase; + +public class ORBDListenPortsComponent + extends + TaggedComponentBase +{ + private String listenPorts; + + public ORBDListenPortsComponent(String listenPorts) + { + this.listenPorts = listenPorts; + } + + public boolean equals(Object o) + { + if (o == null) { + return false; + } + if (!(o instanceof ORBDListenPortsComponent)) { + return false; + } + return listenPorts.equals(((ORBDListenPortsComponent)o).listenPorts); + } + + public void writeContents(OutputStream os) + { + os.write_string(listenPorts); + } + + public int getId() + { + return Common.ListenPortsComponentID; + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/README.txt b/functional-tests/src/test/java/corba/connectintercept_1_4/README.txt new file mode 100644 index 000000000..c48d81b98 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/README.txt @@ -0,0 +1,87 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +This tests connection interception. + +Be sure to read the JavaDoc in: + com/sun/corba/ee/spi/legacy/connection/* + com/sun/corba/ee/spi/legacy/interceptor/* + +Also tests: + +This tests proprietary interceptor ordering. +If ordering fails it will raise INTERNAL/-45. + +This ensures that interceptor calls are balanced when the ORB is shutdown. +If it fails it raises a RuntimeException. + +============================================================================== +Transient + +ORBD: + +orbd started with no VM properties nor command line args. + +SERVER: + +ServerTransient started with no VM properties nor command line args. + +ServerTransient starts ServerCommon with Transient arg. + +ServerCommon sets the socket factory and port properties. + +During ORB.init three ports are opened for listening (besides the +default clear text port). + +During ORB.init establish_components adds one "Listen Ports" +tagged component containing the data on the 3 "extra" ports. +It gets that data from IORInfoExt (proprietary). + +CLIENT: + +Client started with no VM properties nor command line args. + +When using the default socket factory the client always makes +requests to the server by connecting to the default listen port. + +When using custom socket factory the client makes requests to the +server by connecting to ports default, 1, 2, 3 (in a cycle). +Note that once it makes a connection it uses the ephemeral port +allocated by accept (normal TCP/IP operation). + +Besides cycling through the listen ports, the client, on the first +invocation on each reference, get bad info back from the socket +factory to test the try again loop. + + +============================================================================== +Persistent + +ORBD: + +Start up with VM args: + + -Dcom.sun.corba.ee.POA.ORBBadServerIdHandlerClass=corba.connectintercept_1_4.ORBDBadServerIdHandler + -Dcom.sun.corba.ee.connection.ORBSocketFactoryClass=corba.connectintercept_1_4.MySocketFactory + -Dcom.sun.corba.ee.connection.ORBListenSocket=MyType1:2000,MyType2:2001,MyType3:0 + +SERVER: + +Use ServerTool to register ServerPersistent no VM properties nor +command line args). + +ripServerTool -cmd register -applicationName "corba.connectintercept_1_4.ServerPersistent" \ + -server corba.connectintercept_1_4.ServerPersistent -classpath ... + +CLIENT: + +Client started with no VM properties nor command line args. + +// diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/SRI.java b/functional-tests/src/test/java/corba/connectintercept_1_4/SRI.java new file mode 100644 index 000000000..9deaeb922 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/SRI.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 16 (Mon) 16:49:37 by Harold Carr. +// Last Modified : 2003 Feb 11 (Tue) 14:10:14 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt; +import org.omg.PortableInterceptor.ServerRequestInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; + +public class SRI + extends + org.omg.CORBA.LocalObject + implements + ServerRequestInterceptor +{ + + public static final String baseMsg = SRI.class.getName(); + + public int balance = 0; + + public String name() { return baseMsg; } + + public void destroy() + { + if (balance != 0) { + throw new RuntimeException(baseMsg + ": Interceptors not balanced."); + } + } + + public void receive_request_service_contexts(ServerRequestInfo sri) + { + balance++; + System.out.println(baseMsg + ".receive_request_service_contexts " + + sri.operation()); + System.out.println(" request on connection: " + + ((RequestInfoExt)sri).connection()); + } + + public void receive_request(ServerRequestInfo sri) + { + //balance++; // DO NOT DO THIS IN AN INTERMEDIATE POINT! + System.out.println(baseMsg + ".receive_request " + sri.operation()); + } + + public void send_reply(ServerRequestInfo sri) + { + balance--; + System.out.println(baseMsg + ".send_reply " + sri.operation()); + } + + public void send_exception(ServerRequestInfo sri) + { + balance--; + System.out.println(baseMsg + ".send_exception " + sri.operation()); + } + + public void send_other(ServerRequestInfo sri) + { + balance--; + System.out.println(baseMsg + ".send_other " + sri.operation()); + } +} + + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/SRIOrdered.java b/functional-tests/src/test/java/corba/connectintercept_1_4/SRIOrdered.java new file mode 100644 index 000000000..f6445f0ba --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/SRIOrdered.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 31 (Tue) 09:58:47 by Harold Carr. +// Last Modified : 2002 Mar 22 (Fri) 09:33:55 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.CORBA.INTERNAL; +import org.omg.PortableInterceptor.ServerRequestInfo; + +public class SRIOrdered + extends + org.omg.CORBA.LocalObject + implements + org.omg.PortableInterceptor.ServerRequestInterceptor, + Comparable +{ + public static final String baseMsg = SRIOrdered.class.getName(); + public String name; + public int order; + public SRIOrdered(String name, int order) + { + this.name = name; + this.order = order; + } + public int compareTo(Object o) + { + int otherOrder = ((SRIOrdered)o).order; + if (order < otherOrder) { + return -1; + } else if (order == otherOrder) { + return 0; + } + return 1; + } + public String name() { return name; } + + public void destroy() + { + try { + Common.up(order); + } catch (INTERNAL e) { + // INTERNAL will get swallowed by ORB. + // Convert it to something else so server will exit incorrectly + // so error can be detected. + throw new RuntimeException(baseMsg + ": Wrong order in destroy."); + } + } + + public void receive_request_service_contexts(ServerRequestInfo sri) + { + Common.up(order); + } + + public void receive_request(ServerRequestInfo sri) + { + // Note: Do NOT put Common.up here because all 3 ordered + // interceptors run in RRSC so when we get here current will + // be 3 but the first ordered interceptor will have value 1 + // and fail. + // Bottom line: only count up in one point. + } + + public void send_reply(ServerRequestInfo sri) + { + Common.down(order); + } + + public void send_exception(ServerRequestInfo sri) + { + Common.down(order); + } + + public void send_other(ServerRequestInfo sri) + { + Common.down(order); + } +} + +// End of file. + + + + + + + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ServerCommon.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerCommon.java new file mode 100644 index 000000000..d88e80817 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerCommon.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : by Everett Anderson. +// Last Modified : 2004 Apr 14 (Wed) 19:26:04 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import java.util.Properties ; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.PortableServer.POA; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +class ExIServant extends ExIPOA +{ + public ORB orb; + + public ExIServant(ORB orb) + { + this.orb = orb; + } + + public String sayHello() + { + return "Hello world!"; + } +} + +public class ServerCommon +{ + public static final String baseMsg = ServerCommon.class.getName(); + + public static ORB orb; + public static POA rootPoa; + public static POA childPoa; + + // The same server code is used conditionally for both + // persistent and transient servers. + public static boolean isTransient; + + + public static void main(String av[]) + { + if (av[0].equals(Common.Transient)) { + isTransient = true; + } else if (av[0].equals(Common.Persistent)) { + isTransient = false; + } else { + System.out.println(baseMsg + ".main: unknown: " + av[0]); + System.exit(-1); + } + + try { + + Properties props = System.getProperties(); + + props.setProperty(Common.ORBClassKey, MyPIORB.class.getName()); + + props.setProperty(ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + ServerORBInitializer.class.getName(), + "dummy"); + + props.setProperty(ORBConstants.LEGACY_SOCKET_FACTORY_CLASS_PROPERTY, + Common.CUSTOM_FACTORY_CLASS); + + String value; + if (isTransient) { + // It makes sense to assign specific ports for + // transient servers. + value = + Common.MyType1 + ":" + Common.MyType1TransientPort + "," + + Common.MyType2 + ":" + Common.MyType2TransientPort + "," + + Common.MyType3 + ":" + Common.MyType3TransientPort; + } else { + // It makes sense to assign emphemeral ports + // to persistent servers since the ORBD will most + // likely be assigned the fixed ports. + value = + Common.MyType1 + ":" + Common.MyType1PersistentPort + "," + + Common.MyType2 + ":" + Common.MyType2PersistentPort + "," + + Common.MyType3 + ":" + Common.MyType3PersistentPort; + } + props.setProperty(ORBConstants.LISTEN_SOCKET_PROPERTY, value); + + // REVISIT: not sure why I have to explicitly set these here + // but not in other tests. + props.setProperty(ORBConstants.INITIAL_PORT_PROPERTY, "1049"); + + orb = ORB.init(av, props); + + createAndBind(Common.serverName1); + createAndBind(Common.serverName2); + + System.out.println ("Server is ready."); + + orb.run(); + + } catch (Exception e) { + System.out.println(baseMsg + ".main: ERROR: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + } + + public static void createAndBind (String name) + throws + Exception + { + if (rootPoa == null) { + // Get rootPOA + rootPoa = + (POA)orb.resolve_initial_references(ORBConstants.ROOT_POA_NAME); + rootPoa.the_POAManager().activate(); + + // Create POAs. + + Policy[] policies = new Policy[1]; + + // Create child POA + policies[0] = + isTransient ? + rootPoa.create_lifespan_policy(LifespanPolicyValue.TRANSIENT): + rootPoa.create_lifespan_policy(LifespanPolicyValue.PERSISTENT); + childPoa =rootPoa.create_POA("childPoa", null, policies); + childPoa.the_POAManager().activate(); + } + + // REVISIT - bind a root and transient. + + // create servant and register it with the ORB + ExIServant exIServant = new ExIServant(orb); + byte[] id = childPoa.activate_object(exIServant); + org.omg.CORBA.Object ref = childPoa.id_to_reference(id); + + Common.getNameService(orb).rebind(Common.makeNameComponent(name), ref); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ServerIORInterceptor.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerIORInterceptor.java new file mode 100644 index 000000000..cd70133a2 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerIORInterceptor.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 13 (Fri) 09:48:05 by Harold Carr. +// Last Modified : 2003 Feb 11 (Tue) 14:10:21 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.IOP.TaggedComponent; +import org.omg.PortableInterceptor.IORInterceptor; +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; +import com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt; + +public class ServerIORInterceptor + extends + org.omg.CORBA.LocalObject + implements + IORInterceptor +{ + public final String baseMsg = ServerIORInterceptor.class.getName(); + public final String estMsg = baseMsg + ".establish_components"; + + public String name() { return baseMsg; } + public void destroy() { } + public void establish_components(IORInfo iorInfo) + { + IORInfoExt iorInfoExt = (IORInfoExt) iorInfo; + String componentData = Common.createComponentData(estMsg, iorInfoExt); + TaggedComponent taggedComponent = + new TaggedComponent(Common.ListenPortsComponentID, + componentData.getBytes()); + iorInfo.add_ior_component(taggedComponent); + System.out.println(estMsg + ": add_ior_component completed"); + } + + public void components_established( IORInfo iorInfo ) + { + // NO-OP + } + + public void adapter_manager_state_changed( int managerId, short state ) + { + // NO-OP + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + // NO-OP + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ServerORBInitializer.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerORBInitializer.java new file mode 100644 index 000000000..714c69b39 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerORBInitializer.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 13 (Fri) 09:55:19 by Harold Carr. +// Last Modified : 2002 Mar 24 (Sun) 09:23:14 by Harold Carr. +// + +package corba.connectintercept_1_4; + +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; + +public class ServerORBInitializer + extends + org.omg.CORBA.LocalObject + implements + ORBInitializer +{ + public static final String baseMsg = ServerORBInitializer.class.getName(); + + public void pre_init(ORBInitInfo orbInitInfo) { } + + public void post_init(ORBInitInfo orbInitInfo) + { + try { + // These are intentionally random to test ordering. + + orbInitInfo.add_client_request_interceptor( + new CRI()); + + orbInitInfo.add_server_request_interceptor( + new SRIOrdered("Three", 3)); + + orbInitInfo.add_ior_interceptor( + new ServerIORInterceptor()); + + orbInitInfo.add_server_request_interceptor( + new SRIOrdered("One", 1)); + + orbInitInfo.add_server_request_interceptor( + new SRI()); + + orbInitInfo.add_server_request_interceptor( + new SRIOrdered("Two", 2)); + + System.out.println(baseMsg + ".post_init: add_* completed."); + } catch (DuplicateName ex) { + System.out.println(baseMsg + ".post_init: " + ex); + System.exit(-1); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ServerPersistent.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerPersistent.java new file mode 100644 index 000000000..a24745efb --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerPersistent.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 14 (Sat) 08:15:25 by Harold Carr. +// Last Modified : 2002 Mar 22 (Fri) 09:34:14 by Harold Carr. +// + +package corba.connectintercept_1_4; + +public class ServerPersistent +{ + public static void main(String av[]) + { + String[] args = { Common.Persistent }; + ServerCommon.main(args); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/ServerTransient.java b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerTransient.java new file mode 100644 index 000000000..93634cc7c --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/ServerTransient.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Oct 14 (Sat) 08:15:25 by Harold Carr. +// Last Modified : 2002 Mar 22 (Fri) 09:34:17 by Harold Carr. +// + +package corba.connectintercept_1_4; + +public class ServerTransient +{ + public static void main(String av[]) + { + String[] args = { Common.Transient }; + ServerCommon.main(args); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/connectintercept_1_4/TODO.txt b/functional-tests/src/test/java/corba/connectintercept_1_4/TODO.txt new file mode 100644 index 000000000..f1d8d0175 --- /dev/null +++ b/functional-tests/src/test/java/corba/connectintercept_1_4/TODO.txt @@ -0,0 +1,11 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Add running of persistent version of test to framework. diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/Client.java b/functional-tests/src/test/java/corba/exceptiondetailsc/Client.java new file mode 100644 index 000000000..b73ce62ca --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/Client.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:54:21 by Harold Carr. +// Last Modified : 2003 Dec 17 (Wed) 10:17:24 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import java.rmi.RemoteException; +import javax.naming.InitialContext; +import org.omg.CORBA.FREE_MEM; +import org.omg.CORBA.ORB; +import org.omg.CORBA.UNKNOWN; + +import corba.framework.Controller; +import corba.hcks.C; +import corba.hcks.U; + +public class Client +{ + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static final String IDLConnect = "IDL/Connect"; + public static final String IDLPOA = "IDL/POA"; + public static final String RMIIIOPConnect = "RMI-IIOP/Connect"; + public static final String RMIIIOPPOA = "RMI-IIOP/POA"; + public static final String SYSTEM = "SYSTEM_EXCEPTION"; + public static final String USER = "USER_EXCEPTION"; + public static final String RUNTIME = "RuntimeException"; + + public static ORB orb; + public static InitialContext initialContext; + + public static idlI idlIConnect; + public static idlI idlIPOA; + public static rmiiI rmiiIConnect; + public static rmiiI rmiiIPOA; + + public static String idlIConnectArg = Server.idlIConnect; + public static String idlIPOAArg = Server.idlIPOA; + public static String rmiiIConnectArg = Server.rmiiIConnect; + public static String rmiiIPOAArg = Server.rmiiIPOA; + + public static boolean isColocated = false; + public static boolean debug = false; + + public static int numErrors = 0; + + public static void main(String[] av) + { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + U.lf(); + U.sop("+++++++++++++++++++++++++Looking up IDL references."); + U.lf(); + + idlIConnect = idlIHelper.narrow(U.resolve(Server.idlIConnect,orb)); + idlIPOA = idlIHelper.narrow(U.resolve(Server.idlIPOA, orb)); + + U.lf(); + U.sop("+++++++++++++++++++++++++Looking up RMI references."); + U.lf(); + rmiiIConnect = (rmiiI) + U.lookupAndNarrow(Server.rmiiIConnect, + rmiiI.class, initialContext); + rmiiIPOA = (rmiiI) + U.lookupAndNarrow(Server.rmiiIPOA, rmiiI.class,initialContext); + + /* REVISIT: investigate hang + rmiiIPOA = (rmiiI) + U.lookupAndNarrow(C.rmiiSL, rmiiI.class, initialContext); + */ + + U.lf(); + U.sop("+++++++++++++++++++++++++Making IDL/Connect calls."); + U.lf(); + try { + idlIConnect.raise_system_exception(idlIConnectArg); + } catch (Throwable t) { + processThrowable(IDLConnect, SYSTEM, t, + new FREE_MEM(), + "idlIServantConnect.raise_system_exception"); + } + try { + idlIConnect.raise_user_exception(idlIConnectArg); + } catch (Throwable t) { + processThrowable(IDLConnect, USER, t, + new idlException()); + } + try { + idlIConnect.raise_runtime_exception(idlIConnectArg); + } catch (Throwable t) { + processThrowable(IDLConnect, RUNTIME, t, + new UNKNOWN(), + "idlIServantConnect.raise_runtime_exception"); + } + + U.lf(); + U.sop("+++++++++++++++++++++++++Making IDL/POA calls."); + U.lf(); + try { + idlIPOA.raise_system_exception(idlIPOAArg); + } catch (Throwable t) { + processThrowable(IDLPOA, SYSTEM, t, + new FREE_MEM(), + "idlIServantPOA.raise_system_exception"); + } + try { + idlIPOA.raise_user_exception(idlIPOAArg); + } catch (Throwable t) { + processThrowable(IDLPOA, USER, t, + new idlException()); + } + + try { + idlIPOA.raise_runtime_exception(idlIPOAArg); + } catch (Throwable t) { + processThrowable(IDLPOA, RUNTIME, t, + new UNKNOWN(), + "idlIServantPOA.raise_runtime_exception"); + } + + U.lf(); + U.sop("+++++++++++++++++++++++++Making RMI-IIOP/Connect calls."); + U.lf(); + try { + rmiiIConnect.raiseSystemException(rmiiIConnectArg); + } catch (Throwable t) { + String message; + if (isColocated) { + message = "FREE_MEM"; + } else { + message = "rmiiIServantConnect.raiseSystemException"; + } + processThrowable(RMIIIOPConnect, SYSTEM, t, + new RemoteException(), // wraps FREE_MEM + message); + } + try { + rmiiIConnect.raiseUserException(rmiiIConnectArg); + } catch (Throwable t) { + processThrowable(RMIIIOPConnect, USER, t, + new rmiiException("dummy"), + rmiiIConnectArg); + } + try { + rmiiIConnect.raiseRuntimeException(rmiiIConnectArg); + } catch (Throwable t) { + processThrowable(RMIIIOPConnect, RUNTIME, t, + new RuntimeException(), + rmiiIConnectArg); + } + + U.lf(); + U.sop("+++++++++++++++++++++++++Making RMI-IIOP/POA calls."); + U.lf(); + try { + rmiiIPOA.raiseSystemException(rmiiIPOAArg); + } catch (Throwable t) { + String message; + if (isColocated) { + message = "FREE_MEM"; + } else { + message = "rmiiIServantPOA.raiseSystemException"; + } + processThrowable(RMIIIOPPOA, SYSTEM, t, + new RemoteException(), + message); + } + try { + rmiiIPOA.raiseUserException(rmiiIPOAArg); + } catch (Throwable t) { + processThrowable(RMIIIOPPOA, USER, t, + new rmiiException("dummy"), + + rmiiIPOAArg); + } + + try { + rmiiIPOA.raiseRuntimeException(rmiiIPOAArg); + } catch (Throwable t) { + processThrowable(RMIIIOPPOA, RUNTIME, t, + new RuntimeException(), + rmiiIPOAArg); + } + + if (numErrors == 0) { + U.lf(); + U.sop("+++++++++++++++++++++++++PASSED"); + U.lf(); + } else { + throw new RuntimeException("numError != 0"); + } + + orb.shutdown(true); + + } catch (Exception e) { + U.lf(); + U.sopUnexpectedException(main + " : ", e); + U.sop("+++++++++++++++++++++++++FAILED"); + U.lf(); + System.exit(1); + } + U.lf(); + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } + + public static void processThrowable(String servantType, + String exceptionCategory, + Throwable got, + Throwable expected) + { + processThrowable(servantType, exceptionCategory, got, expected, null); + } + + public static void processThrowable(String servantType, + String exceptionCategory, + Throwable got, + Throwable expected, + String messageSubstring) + { + boolean failType = false; + boolean failMessage = false; + + U.lf(); + U.sop("--------------------------------------------------"); + U.sop(servantType + " " + exceptionCategory); + if (got.getClass().isInstance(expected)) { + U.sop("Exception Type PASSED"); + } else { + U.sop("Exception Type FAIL"); + numErrors++; + failType = true; + } + if (messageSubstring != null) { + if (got.getMessage().indexOf(messageSubstring) != -1) { + U.sop("-----Exception Message PASSED-----"); + U.sop("-----BEGIN passing stack trace:"); + got.printStackTrace(System.out); + U.sop("-----END passing stack trace"); + } else { + U.sop("Exception Message FAIL"); + numErrors++; + failMessage = true; + } + } + if (failType) { + U.sop("exception type expected: " + expected); + U.sop("exception type received: " + got); + } + if (failMessage) { + U.sop("exception message (substring) expected: " + messageSubstring); + U.sop("exception message received: " + got.getMessage()); + } + + if (debug) { + if (isColocated) { + U.sop("++++++++++++++++++++++++++++++++++++++++++++++++++"); + got.printStackTrace(System.out); + U.sop("++++++++++++++++++++++++++++++++++++++++++++++++++"); + } + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/ColocatedClientServer.java b/functional-tests/src/test/java/corba/exceptiondetailsc/ColocatedClientServer.java new file mode 100644 index 000000000..999c23d96 --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/ColocatedClientServer.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 17 (Thu) 17:05:00 by Harold Carr. +// Last Modified : 2003 Jul 30 (Wed) 16:30:52 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import java.util.Properties; +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; +import corba.hcks.C; +import corba.hcks.U; + +public class ColocatedClientServer +{ + public static final String baseMsg = ColocatedClientServer.class.getName(); + public static final String main = baseMsg + ".main"; + + // REVISIT: FRAMEWORK DEVELOPMENT + // REMOVE THIS LATER. + // Necessary so calls not going through locals do not hang + // until I implement the reader thread/work split. + public static int fragmentSize = -1; + //public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String[] av) + { + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + Properties props = new Properties(); + props.setProperty("com.sun.corba.ee.ORBAllowLocalOptimization", + "true"); + orb = ORB.init(av, props); + U.sop(main + " : creating ORB."); + Server.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + Client.orb = orb; + + // Share a naming context between client and server + // so StubAdapter.isLocal is true. + + // Use the same ORB which has interceptor properties set. + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + Server.initialContext = initialContext; + Client.initialContext = initialContext; + + Client.isColocated = true; + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + Client.main(av); + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/ExceptionDetailSCTest.java b/functional-tests/src/test/java/corba/exceptiondetailsc/ExceptionDetailSCTest.java new file mode 100644 index 000000000..cd84dea39 --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/ExceptionDetailSCTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:31:43 by Harold Carr. +// Last Modified : 2003 Jul 26 (Sat) 18:28:47 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +public class ExceptionDetailSCTest + extends + CORBATest +{ + public static final String thisPackage = + ExceptionDetailSCTest.class.getPackage().getName(); + + protected void doTest() throws Throwable { + Controller orbd = createORBD(); + orbd.start(); + + doTestType("Server", "Server", + "Client", "Client"); + + Controller colocatedClientServer = + createClient(thisPackage + ".ColocatedClientServer", + "colocatedClientServer"); + colocatedClientServer.start(); + colocatedClientServer.waitFor(); + colocatedClientServer.stop(); + + orbd.stop(); + } + + protected void doTestType( + String serverMainClass, String serverTestName, + String clientMainClass, String clientTestName) throws Throwable { + + Controller server = createServer(thisPackage + "." + serverMainClass, + serverTestName); + server.start(); + + Controller client = createClient(thisPackage + "." + clientMainClass, + clientTestName); + client.start(); + client.waitFor(); + client.stop(); + + server.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/Server.java b/functional-tests/src/test/java/corba/exceptiondetailsc/Server.java new file mode 100644 index 000000000..94665df66 --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/Server.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:28:12 by Harold Carr. +// Last Modified : 2003 Jul 29 (Tue) 16:38:25 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import javax.naming.InitialContext; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; + +import corba.framework.Controller; +import corba.framework.Options; +import corba.hcks.C; +import corba.hcks.U; + +public class Server +{ + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + public static final String thisPackage = + Server.class.getPackage().getName(); + + public static final String rmiiIServantPOA_Tie = + thisPackage + "._rmiiIServantPOA_Tie"; + + public static final String idlIConnect = "idlIConnect"; + public static final String idlIPOA = "idlIPOA"; + public static final String rmiiIConnect = "rmiiIConnect"; + public static final String rmiiIPOA = "rmiiIPOA"; + + public static ORB orb; + public static InitialContext initialContext; + public static POA rootPOA; + + public static void main(String[] av) + { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = (ORB) ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + rootPOA = U.getRootPOA(orb); + rootPOA.the_POAManager().activate(); + + // + // IDL references. + // + + U.sop("Creating/binding IDL references."); + + U.createWithConnectAndBind(idlIConnect, + new idlIServantConnect(), orb); + U.createWithServantAndBind(idlIPOA, + new idlIServantPOA(), rootPOA, orb); + + // + // RMI-IIOP references. + // + + U.sop("Creating/binding RMI-IIOP references."); + + initialContext.rebind(rmiiIConnect, new rmiiIServantConnect()); + + Servant servant = (Servant) + javax.rmi.CORBA.Util.getTie(new rmiiIServantPOA()); + U.createWithServantAndBind(rmiiIPOA, servant, rootPOA, orb); + + U.sop(main + " ready"); + U.sop(Options.defServerHandshake); + System.out.flush(); + + synchronized (ColocatedClientServer.signal) { + ColocatedClientServer.signal.notifyAll(); + } + + orb.run(); + + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/idlIServantConnect.java b/functional-tests/src/test/java/corba/exceptiondetailsc/idlIServantConnect.java new file mode 100644 index 000000000..9c4c90915 --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/idlIServantConnect.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:34:33 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import org.omg.CORBA.FREE_MEM; +import corba.hcks.U; + +class idlIServantConnect + extends + _idlIImplBase +{ + public static final String baseMsg = idlIServantConnect.class.getName(); + + public idlIServantConnect() + { + } + + public void raise_system_exception(String arg1) + { + throw new FREE_MEM(arg1); + } + + public void raise_user_exception(String arg1) + throws idlException + { + throw new idlException(arg1); + } + + public void raise_runtime_exception(String arg1) + { + throw new RuntimeException(arg1); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/idlIServantPOA.java b/functional-tests/src/test/java/corba/exceptiondetailsc/idlIServantPOA.java new file mode 100644 index 000000000..a48a6911a --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/idlIServantPOA.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:34:40 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import org.omg.CORBA.FREE_MEM; +import corba.hcks.U; + +class idlIServantPOA + extends + idlIPOA +{ + public static final String baseMsg = idlIServantPOA.class.getName(); + + public idlIServantPOA() + { + } + + public void raise_system_exception(String arg1) + { + throw new FREE_MEM(arg1); + } + + public void raise_user_exception(String arg1) + throws idlException + { + throw new idlException(arg1); + } + + public void raise_runtime_exception(String arg1) + { + throw new RuntimeException(arg1); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiException.java b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiException.java new file mode 100644 index 000000000..797b6448c --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiException.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : Spring 1999 by Harold Carr. +// Last Modified : 2003 Jul 26 (Sat) 18:33:26 by Harold Carr. +// + +package corba.exceptiondetailsc; + +public class rmiiException + extends + Exception +{ + public rmiiException(String x) + { + super(x); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiI.java b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiI.java new file mode 100644 index 000000000..6c6434894 --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiI.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:26:35 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface rmiiI + extends + Remote +{ + public void raiseSystemException(String x) + throws + RemoteException; + + public void raiseUserException(String x) + throws + RemoteException, + rmiiException; + + public void raiseRuntimeException(String x) + throws + RemoteException; +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiIServantConnect.java b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiIServantConnect.java new file mode 100644 index 000000000..45d20ebdf --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiIServantConnect.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:38:12 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:27:11 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.FREE_MEM; +import corba.hcks.U; + +public class rmiiIServantConnect + extends + PortableRemoteObject + implements + rmiiI +{ + public static final String baseMsg = rmiiIServantConnect.class.getName(); + + public rmiiIServantConnect () + throws + RemoteException + { + super(); + } + + public void raiseSystemException(String x) + throws + RemoteException + { + throw new FREE_MEM(x); + } + + public void raiseUserException(String x) + throws + RemoteException, + rmiiException + { + throw new rmiiException(x); + } + + public void raiseRuntimeException(String x) + throws + RemoteException + { + throw new RuntimeException(x); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiIServantPOA.java b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiIServantPOA.java new file mode 100644 index 000000000..cca9fcefa --- /dev/null +++ b/functional-tests/src/test/java/corba/exceptiondetailsc/rmiiIServantPOA.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 11 (Sat) 10:45:48 by Harold Carr. +// Last Modified : 2003 Jul 28 (Mon) 09:27:25 by Harold Carr. +// + +package corba.exceptiondetailsc; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.FREE_MEM; +import corba.hcks.U; + +public class rmiiIServantPOA + extends + PortableRemoteObject + implements + rmiiI +{ + public static final String baseMsg = rmiiIServantPOA.class.getName(); + + public rmiiIServantPOA () + throws + RemoteException + { + // DO NOT CALL SUPER - that would connect the object. + } + + public void raiseSystemException(String x) + throws + RemoteException + { + throw new FREE_MEM(x); + } + + public void raiseUserException(String x) + throws + RemoteException, + rmiiException + { + throw new rmiiException(x); + } + + public void raiseRuntimeException(String x) + throws + RemoteException + { + throw new RuntimeException(x); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/Client.java b/functional-tests/src/test/java/corba/folb_8_1/Client.java new file mode 100644 index 000000000..251c5c7db --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/Client.java @@ -0,0 +1,398 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:50:37 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:03:42 by Harold Carr. +// + +package corba.folb_8_1; + +import java.util.Properties; + +import org.omg.CORBA.ORB; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; + +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * @author Harold Carr + */ +public class Client + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor, ORBInitializer +{ + public static final String baseMsg = Client.class.getName(); + public static final String NO_CONNECTION = "no connection"; + public static boolean withSticky = false; + public static boolean foundErrors = false; + public static Connection lastConnectionUsed; + public static String lastSocketTypeUsed; + public static I iRef; + public static I2 zero1; + public static I2 zero2; + public static ORB orb; + + public static void setProperties(Properties props) + { + props.setProperty( ORBConstants.DEBUG_PROPERTY, + "subcontract,transport" ) ; + + // + // Debugging flags. Generally commented out. + // + /* + props.setProperty(ORBConstants.DEBUG_PROPERTY, + "giop,transport,subcontract"); + */ + + // + // Register the class that knows how to find the information + // on socket types X, Y and Z installed by the server side + // IORInterceptor. + // + + props.setProperty(ORBConstants.IOR_TO_SOCKET_INFO_CLASS_PROPERTY, + IORToSocketInfoImpl.class.getName()); + + // + // Register the socket factory that knows how to create + // Sockets of type W X Y and Z. + // + + props.setProperty(ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + SocketFactoryImpl.class.getName()); + + // + // Register a client interceptor to see what connection + // is being used for test (using a proprietary extension). + // + + props.setProperty(ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + Client.class.getName(), + "dummy"); + + if (withSticky) { + System.out.println("Adding sticky manager"); + // + // Register a sticky manager and make sure it sticks. + // + props.setProperty(ORBConstants.IIOP_PRIMARY_TO_CONTACT_INFO_CLASS_PROPERTY, + IIOPPrimaryToContactInfoImpl.class.getName()); + } + } + + public static void main(String[] av) + { + try { + + if (! ColocatedCS.isColocated) { + Properties props = new Properties(); + setProperties(props); + orb = ORB.init(av, props); + } + + runTest(); + + if (foundErrors) { + throw new Exception("foundErrors"); + } + + System.out.println(); + System.out.println(baseMsg + ".main: PASSED"); + System.out.println(baseMsg + ".main: Test complete."); + + } catch (Throwable t) { + System.out.println(baseMsg + ".main: FAILED"); + System.out.println(baseMsg + ".main: Test complete."); + t.printStackTrace(System.out); + System.exit(1); + } + } + + private static void runTest() + throws Exception + { + System.out.println("================================================"); + if (withSticky) { + System.out.println("WITH STICKY"); + } else { + System.out.println("WITHOUT STICKY"); + } + + /* REVISIT - move to a separate test + ////////////////////////////////////////////////// + // ZeroPortTest + + BEGIN("ZeroPortTest"); + + zero1 = + I2Helper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.zero1))); + + zero2 = + I2Helper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.zero2))); + + zero1.m("10"); + zero2.m("11"); + zero1.m("12"); + zero2.m("13"); + + END("ZeroPortTest"); + */ + + ////////////////////////////////////////////////// + // Sticky test; + + BEGIN("Sticky Test"); + + iRef = + IHelper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.serverName1))); + + unregister(SocketInfo.IIOP_CLEAR_TEXT, iRef, false); + + for (int i = 0; i < Common.socketTypes.length - 1; i++) { + unregister(Common.socketTypes[i], iRef, true); + } + + System.out.println(); + System.out.println("DONE with unregister"); + System.out.println(); + + ////////////////////////////////////////////////// + // + // Test fallback. + // + // This should stick on Z if sticky manager registered. + // Otherwise it should go to W. + // + // Start up a W on the server. See if it goes to Z or W. + // + + System.out.println(); + printSeparator("-"); + System.out.println("TESTING FALLBACK - should stick to W without sticky, Z with sticky"); + System.out.println(); + + BEGIN("register W"); + iRef.register(Common.socketTypes[0]); // Register W + Thread.sleep(5000); + END("register W"); + + + BEGIN("unregister W if no sticky, Z if sticky present"); + + // In the following we really don't care whether we unregister + // W or Z. What we care about is which TYPE of connection the + // unregister request goes out on. With a sticky it should be Z. + // Without sticky it should be W. + // REVISIT: if we separated control (the unregister) from the check + // it would easier to understand the test. + if (withSticky) { + // unregister Z. + unregister(Common.socketTypes[Common.socketTypes.length - 1], + iRef, true); + } else { + // Unregister W. + unregister(Common.socketTypes[0], iRef, true); + } + + END("unregister W if no sticky, Z if sticky present"); + + END("Sticky Test"); + + orb.shutdown(false); + orb.destroy(); + } + + /** + * This both unregisters a specific socketType AND ensure that + * the request goes out on that same socketType. + * REVISIT: it would be better to separate the control (the unregister) + * from the test. + */ + private static void unregister(String socketType, I iRef, boolean checkP) + throws Exception + { + BEGIN("unregister: " + socketType); + iRef.unregister(socketType); + END("unregister: " + socketType); + + BEGIN("Request after " + socketType + " unregistered - still on " + socketType + " because of explicit delay at server"); + System.out.println(iRef.m("After " + socketType + " unregistered")); + if (checkP) { + checkSocketType(socketType); + } + END("Request after " + socketType + " unregistered - still on " + socketType + " because of explicit delay at server"); + Thread.sleep(5000); + } + + private static void checkSocketType(String socketType) + { + if (ColocatedCS.isColocated) { + socketType = NO_CONNECTION; + } + + if (socketType.equals(lastSocketTypeUsed)) { + System.out.println(); + System.out.println("====== Used correct socketType: " + + lastSocketTypeUsed + " ======"); + System.out.println(); + } else { + System.out.println(); + System.out.println("++++++ ERROR: INCORRECT SOCKETYPE: " + + lastSocketTypeUsed + + "; expected: " + + socketType + + " ++++++"); + System.out.println(); + foundErrors = true; + } + } + + private static void printSeparator(String s) + { + for (int i = 0; i < 70; i++) { + System.out.print(s); + } + System.out.println(); + } + + // + // Interceptor operations + // + + public String name() + { + return baseMsg; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + sopCR(baseMsg, "send_request", ri); + } + + public void send_poll(ClientRequestInfo ri) + { + sopCR(baseMsg, "send_poll", ri); + } + + public void receive_reply(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_reply", ri); + } + + public void receive_exception(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_exception", ri); + } + + public void receive_other(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_other", ri); + } + + // + // Utilities. + // + + public static void sopCR(String clazz, String point, ClientRequestInfo ri) + { + try { + if (! Common.timing) { + System.out.println(clazz + "." + point + " " + ri.operation()); + } + if (ri instanceof RequestInfoExt) { + RequestInfoExt rie = (RequestInfoExt) ri; + if (rie.connection() != null) { + if (! Common.timing) { + System.out.println(" request on connection: " + rie.connection()); + } + lastConnectionUsed = (Connection) rie.connection(); + lastSocketTypeUsed = (String) + Common.portToSocketType.get( + new Integer(rie.connection().getSocket().getPort())); + if (lastSocketTypeUsed == null) { + // NOTE: the last one is running on an emphemeral port + // so it does NOT map. Just assume it. + // Also assume we don't look at the primary which + // is also NOT mapped. + lastSocketTypeUsed = + Common.socketTypes[Common.socketTypes.length - 1]; + } + } else { + lastSocketTypeUsed = NO_CONNECTION; + } + } + } catch (Throwable e) { + System.out.println(baseMsg + "." + point + ": unexpected exception: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + } + + public void pre_init(ORBInitInfo info) + { + try { + Client interceptor = new Client(); + info.add_client_request_interceptor(interceptor); + System.out.println(baseMsg + ".pre_init"); + } catch (Throwable t) { + System.out.println(baseMsg + ": unexpected exception: " + t); + t.printStackTrace(System.out); + System.exit(1); + } + } + + public void post_init(ORBInitInfo info) + { + } + + public static void BEGIN(String msg) + { + System.out.println(); + printSeparator("-"); + System.out.println("BEGIN " + msg); + System.out.println(); + + } + + public static void END(String msg) + { + System.out.println(); + System.out.println("END " + msg); + printSeparator("-"); + + } + +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming.java b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming.java new file mode 100644 index 000000000..52c2ca4af --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming.java @@ -0,0 +1,461 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Apr 27 (Wed) 15:46:01 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:03:52 by Harold Carr. +// + +package corba.folb_8_1; + +import java.io.File; +import java.util.Properties; + + +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.impl.transport.ContactInfoListImpl; +//import com.sun.corba.ee.impl.orbutil.newtimer.generated.TimingPoints; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import org.glassfish.pfl.tf.timer.spi.LogEventHandler; +import org.glassfish.pfl.tf.timer.spi.Timer; +import org.glassfish.pfl.tf.timer.spi.TimerEventController; +import org.glassfish.pfl.tf.timer.spi.TimerFactory; +import org.glassfish.pfl.tf.timer.spi.TimerManager; + +// import corba.framework.TimerUtils ; + +/** + * @author Harold Carr + */ +public class ClientForTiming +{ + public static boolean debug = true; + + public static final int NUMBER_OF_WARMUP_LOOPS = 5;//20000; + public static final int NUMBER_OF_TIMING_LOOPS = 5;// 5003; + + public static final String baseMsg = ClientForTiming.class.getName(); + public static I iRef; + public static I2 i2Ref; + public static String[] av; + + public static ORB orb; +/* + public static TimerManager tm ; + public static TimerFactory tf ; + public static TimerEventController controller ; + public static LogEventHandler log ; + public static TimingPoints tp ; +*/ + public static Timer totalTestTime ; + public static Timer clientInvoke ; + + public static IIOPPrimaryToContactInfoImpl primaryToContactInfo; + public static ContactInfo serverPrimaryContactInfo; + public static ContactInfo serverClearTextEntry; + + // These are used as self-documenting values below. + public static final boolean FAILOVER_SUPPORT = true; + public static final boolean FAILOVER = true; + public static final boolean CACHE = true; + + public static void main(String[] argv) + { + // NOTE: must give to ORB.init - contains ORBInitialPort + av = argv; + + try { + + boolean failoverSupport = false; + boolean failover = false; + boolean cache = false; + + for (int i = 0; i < av.length; ++i) { + String x = av[i]; + System.out.print(x +" "); + if (x.equals(Common.FAILOVER_SUPPORT)) { + failoverSupport = true; + } else if (x.equals(Common.FAILOVER)) { + failover = true; + } else if (x.equals(Common.CACHE)) { + cache = true; + } + } + System.out.println(); + + runTest(failoverSupport, failover, cache); + + System.out.println(); + System.out.println(baseMsg + ".main: PASSED"); + System.out.println(baseMsg + ".main: Test complete."); + + } catch (Throwable t) { + System.out.println(baseMsg + ".main: FAILED"); + System.out.println(baseMsg + ".main: Test complete."); + t.printStackTrace(System.out); + System.exit(1); + } + } + + // USE THIS FOR VERIFY THE TEST IS ACCURATE. + // DO NOT USE THIS FOR TIMING! + // IF YOU RUN ALL IN SAME VN SESSION THEN HotSpot OPTIMIZATIONS + // GET TRIGGERED AT VARIOUS POINTS, MAKING LATER RESULTS DIFFERENT + // FROM EARLIER RESULTS BECAUSE OF HOTSPOT - NOT BECAUSE OF WHAT IS BEING + // TIMED. + public static void runAllTests() + throws Exception + { + runTest(!FAILOVER_SUPPORT, !FAILOVER, !CACHE); + runTest( FAILOVER_SUPPORT, !FAILOVER, !CACHE); + runTest( FAILOVER_SUPPORT, !FAILOVER, CACHE); + runTest( FAILOVER_SUPPORT, FAILOVER, !CACHE); + runTest( FAILOVER_SUPPORT, FAILOVER, CACHE); + } + + public static void runTest(boolean failoverSupport, + boolean failover, + boolean cache) + throws Exception + { + BEGIN(failoverSupport, failover, cache); + + // don't print to log files - including warmup runs. + if (! debug) { + Common.timing = true; + } + + setup(failoverSupport, cache); + + primaryToContactInfo = (IIOPPrimaryToContactInfoImpl) + orb.getORBData().getIIOPPrimaryToContactInfo(); + + if (! debug && cache) { + // don't print debug info. + // Note: this must be done *AFTER* setup *BEFORE* lookup. + // Setup to get the ORB. But before it is used (i.e., lookup). + primaryToContactInfo.setDebugChecked(true); + primaryToContactInfo.setDebug(false); + } + + lookup(); + + if (failover) { + setupFailover(cache); + } + + //////////////////////////////////////////////////// + // Warmup loop. + + loop(NUMBER_OF_WARMUP_LOOPS, failover, cache); + + //////////////////////////////////////////////////// + // Timing loop. + + setTimerPoints(true); + //controller.enter( totalTestTime ) ; + + loop(NUMBER_OF_TIMING_LOOPS, failover, cache); + + //controller.exit( totalTestTime ) ; + setTimerPoints(false); + + File file = new File(makeFileName(failoverSupport, failover, cache)); + file.delete(); +// TimerUtils.dumpLogToFile( tf, log, file ) ; + //log.clear() ; + + END(failoverSupport, failover, cache); + } + + public static void setupFailover(boolean cache) + throws Exception + { + dprint(); + dprint("starting setupFailover"); + dprint(); + + // Careful with the tricky bug fix about ContactInfos in the map + // pointing to a different IOR than the object on the current request. + + // Make a call on the loop object. Why? + // 1. Init the failover cache (when caching) with the entry to i2. + // 2. To cause i2Ref's contact info list to be created (it's lazy). + // Causes a conection to be established. + + dprint(); + dprint("--------- Calling i2Ref to prime pump."); + i2Ref.foo(1); + + serverPrimaryContactInfo = + ((ContactInfoListImpl) + ((ClientDelegate) + ((_I2Stub)i2Ref)._get_delegate()) + .getContactInfoList()).getPrimaryContactInfo(); + + dprint("--------- i2Ref primaryContactInfo: " + + serverPrimaryContactInfo); + dprint(); + + if (cache) { + + // REVISIT: entry not found. See README.txt + dprint(); + dprint("finding entry for key: " + serverPrimaryContactInfo); + dprint("in map: " + primaryToContactInfo.map); + + serverClearTextEntry = (ContactInfo) + primaryToContactInfo.map.get(serverClearTextEntry); + + dprint("found entry: " + serverClearTextEntry); + dprint(); + } + + // Kill a listener and its connections. + // This assumes the one we kill is the one on which we make the request + + dprint(); + dprint("kill the IIOP_CLEAR_TEXT listener and its connections:"); + iRef.unregister(SocketInfo.IIOP_CLEAR_TEXT); + dprint(" killed: " + Client.lastConnectionUsed); + dprint(); + Thread.sleep(5000); // Give the server time to kill. + + if (cache) { + + // Make the map not contain an entry for the server. + + Object o=primaryToContactInfo.map.remove(serverPrimaryContactInfo); + dprint(); + dprint("Removed from map:" + + " key: " + serverPrimaryContactInfo + + " entry: " + serverClearTextEntry); + } + dprint(); + dprint("ending setupFailover"); + dprint(); + } + + public static void revertCache() + { + dprint(); + dprint("revertCache"); + dprint(); + dprint("key: " + serverPrimaryContactInfo); + Object o = primaryToContactInfo.map.remove(serverPrimaryContactInfo); + dprint("was mapped to: " + o); + primaryToContactInfo.map.put(serverPrimaryContactInfo, + serverClearTextEntry); + dprint("now mapped to: " + + primaryToContactInfo.map.get(serverClearTextEntry)); + dprint(); + } + + public static void killFailedOverToConnection() + throws Exception + { + TransportManager transportManager = orb.getTransportManager(); + + dprint(); + dprint("killFailedOverToConnection"); + dprint("key: " + serverPrimaryContactInfo); + dprint("removing connection: " + Client.lastConnectionUsed); + dprint("from connection cache BEFORE: " + + transportManager + .getOutboundConnectionCache(serverPrimaryContactInfo)); + Client.lastConnectionUsed.close(); + Thread.sleep(1000); + dprint(); + dprint("from connection cache AFTER: " + + transportManager + .getOutboundConnectionCache(serverPrimaryContactInfo)); + dprint(); + } + + public static void loop(int times, boolean failover, boolean cache) + throws Exception + { + dprint(); + dprint("starting loop"); + dprint(); + + for (int i = 0 ; i < times; ++i) { + //controller.enter( clientInvoke ) ; + i2Ref.foo(1); + //controller.exit( clientInvoke ) ; + + if (failover) { + // We want the connection setup to show up in failover time. + killFailedOverToConnection(); + if (cache) { + // We want failover to happen on every call. + revertCache(); + } + } + } + + dprint(); + dprint("ending loop"); + dprint(); + } + + public static void setup(boolean failoverSupport, + boolean cache) + throws Exception + { + dprint(); + dprint("starting setup"); + dprint(); + + Properties props = new Properties(); + props.setProperty( ORBConstants.TIMING_POINTS_ENABLED, "true" ) ; + + if (failoverSupport) { + props.setProperty(ORBConstants.IOR_TO_SOCKET_INFO_CLASS_PROPERTY, + IORToSocketInfoImpl.class.getName()); + props.setProperty(ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + SocketFactoryImpl.class.getName()); + if (cache) { + props.setProperty(ORBConstants.IIOP_PRIMARY_TO_CONTACT_INFO_CLASS_PROPERTY, + IIOPPrimaryToContactInfoImpl.class.getName()); + } + } + + Client.setProperties(props); + orb = (ORB) ORB.init(av, props); +/* + tm = orb.makeTimerManager( TimingPoints.class ) ; + tf = tm.factory() ; + tp = tm.points() ; + + // Set up the log event handler. + controller = tm.controller() ; + log = tf.makeLogEventHandler( "TestLogger" ) ; + controller.register( log ) ; + + // Create the extra timers for this test + totalTestTime = tf.makeTimer( "totalTestTime", "Total Test Execution Time" ) ; + clientInvoke = tf.makeTimer( "clientInvoke", "Execution Time of Client Invoke" ) ; +*/ + // Not available: tp.transport().add( totalTestTime ) ; + // Not available: tp.transport().add( clientInvoke ) ; + + dprint(); + dprint("ending setup"); + dprint(); + } + + public static void lookup() + throws Exception + { + dprint(); + dprint("starting lookup"); + dprint(); + + iRef = + IHelper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.serverName1))); + + i2Ref = + I2Helper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.serverName2))); + + dprint(); + dprint("ending lookup"); + dprint(); + } + + public static void BEGIN(boolean failoverSupport, + boolean failover, + boolean cache) + { + System.out.println(); + System.out.println("------------------------------------------------"); + System.out.print("BEGIN "); + BEGINEND(failoverSupport, failover, cache); + System.out.println(); + } + + public static void END(boolean failoverSupport, + boolean failover, + boolean cache) + { + System.out.println(); + System.out.print("END "); + BEGINEND(failoverSupport, failover, cache); + System.out.println("------------------------------------------------"); + System.out.println(); + } + + public static void BEGINEND(boolean failoverSupport, + boolean failover, + boolean cache) + { + System.out.println(withOrWithout(failoverSupport, "FailoverSupport")); + System.out.println(withOrWithout(failover, "Failover")); + System.out.println(withOrWithout(cache, "Cache")); + } + + public static String withOrWithout(boolean with, String msg) + { + if (with) { + return msg; + } + return "NO" + msg; + } + + public static String makeFileName(boolean failoverSupport, + boolean failover, + boolean cache) + { + String directory = + System.getProperty("output.dir") + + System.getProperty("file.separator"); + return + //"/tmp/" + directory + + withOrWithout(failoverSupport, "FailoverSupport") + + withOrWithout(failover, "Failover") + + withOrWithout(cache, "Cache") + + ".log"; + } + + public static void setTimerPoints(boolean x) + { + /* tp.transport not available. + if (x) + tp.transport().enable() ; + else + tp.transport().disable() ; + */ + } + + public static void dprint() + { + dprint(""); + } + public static void dprint(String msg) + { + if (debug) { + System.out.println(msg); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_F_C.java b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_F_C.java new file mode 100644 index 000000000..affae10d7 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_F_C.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Apr 27 (Wed) 15:46:01 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:01:14 by Harold Carr. +// + +package corba.folb_8_1; + +/** + * @author Harold Carr + */ +public class ClientForTiming_Fs_F_C +{ + public static void main(String[] av) + { + String[] args = { Common.FAILOVER_SUPPORT, Common.FAILOVER, Common.CACHE }; + ClientForTiming.main(Common.concat(av, args)); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_F_NoC.java b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_F_NoC.java new file mode 100644 index 000000000..1d1c352a9 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_F_NoC.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Apr 27 (Wed) 15:46:01 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:04:03 by Harold Carr. +// + +package corba.folb_8_1; + +/** + * @author Harold Carr + */ +public class ClientForTiming_Fs_F_NoC +{ + public static void main(String[] av) + { + String[] args = { Common.FAILOVER_SUPPORT, Common.FAILOVER }; + ClientForTiming.main(Common.concat(av, args)); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_NoF_C.java b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_NoF_C.java new file mode 100644 index 000000000..f929a361c --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_NoF_C.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Apr 27 (Wed) 15:46:01 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:04:16 by Harold Carr. +// + +package corba.folb_8_1; + +/** + * @author Harold Carr + */ +public class ClientForTiming_Fs_NoF_C +{ + public static void main(String[] av) + { + String[] args = { Common.FAILOVER_SUPPORT, Common.CACHE }; + ClientForTiming.main(Common.concat(av, args)); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_NoF_NoC.java b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_NoF_NoC.java new file mode 100644 index 000000000..9ad72ed15 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_Fs_NoF_NoC.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Apr 27 (Wed) 15:46:01 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:04:54 by Harold Carr. +// + +package corba.folb_8_1; + +/** + * @author Harold Carr + */ +public class ClientForTiming_Fs_NoF_NoC +{ + public static void main(String[] av) + { + String[] args = { Common.FAILOVER_SUPPORT }; + ClientForTiming.main(Common.concat(av, args)); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_NoFs_NoF_NoC.java b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_NoFs_NoF_NoC.java new file mode 100644 index 000000000..667c22653 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientForTiming_NoFs_NoF_NoC.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Apr 27 (Wed) 15:46:01 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:05:04 by Harold Carr. +// + +package corba.folb_8_1; + +/** + * @author Harold Carr + */ +public class ClientForTiming_NoFs_NoF_NoC +{ + public static void main(String[] av) + { + ClientForTiming.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientTwoRefs.java b/functional-tests/src/test/java/corba/folb_8_1/ClientTwoRefs.java new file mode 100644 index 000000000..9521e515a --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientTwoRefs.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:50:37 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:05:14 by Harold Carr. +// + +package corba.folb_8_1; + +import java.util.Properties; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.UNKNOWN; + +/** + * @author Harold Carr + */ +public class ClientTwoRefs +{ + public static final String baseMsg = ClientTwoRefs.class.getName(); + + public static boolean foundErrors = false; + + public static I iRef; + public static I2 i2Ref; + + public static ORB orb; + + public static void main(String[] av) + { + try { + + if (! ColocatedCS.isColocated) { + Properties props = new Properties(); + Client.withSticky = true; + Client.setProperties(props); + orb = ORB.init(av, props); + } + + runTest(); + + if (foundErrors) { + throw new Exception("foundErrors"); + } + + System.out.println(); + System.out.println(baseMsg + ".main: PASSED"); + System.out.println(baseMsg + ".main: Test complete."); + + } catch (Throwable t) { + System.out.println(baseMsg + ".main: FAILED"); + System.out.println(baseMsg + ".main: Test complete."); + t.printStackTrace(System.out); + System.exit (1); + } + } + + private static void runTest() + throws Exception + { + System.out.println("================================================"); + System.out.println(); + + iRef = + IHelper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.serverName1))); + + i2Ref = + I2Helper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.serverName2))); + + // + // Test to ensure we are only running sticky via host/port/type + // not the entire ContactInfo. If returning an entire contactInfo + // associated with a different object, then the Tie will get an + // error - either wrong type or unknown method. + // + + System.out.println(); + System.out.println("First talk to iRef to get stuck on it."); + System.out.println(); + + String stringResult = iRef.m("Hello"); + System.out.println(stringResult); + + // The following calls will go to the wrong reference if + // using the entire ContactInfo as a key. Need to return + // a specific SocketInfo instead. + + + // This returns a String in the bad case but gets no + // error. But the return value is the length of a string + // rather than the string converted to an int. + System.out.println(); + System.out.println("Test wrong return type:"); + System.out.println(); + + int intResult = i2Ref.m("45"); + if (intResult != 45) { + foundErrors = true; + System.out.println(); + System.out.println("!!!!!!!!! WRONG RETURN TYPE"); + System.out.println(); + } else { + System.out.println(); + System.out.println("Correct return type: " + intResult); + System.out.println(); + } + + // This returns a String in the bad case. When the client-side + // tries to unmarshal an Object it breaks. + System.out.println(); + System.out.println("Test marshaling error"); + System.out.println(); + try { + org.omg.CORBA.Object o = i2Ref.n("dummy"); + System.out.println(); + System.out.println("Correct return type: " + o); + System.out.println(); + } catch (MARSHAL e) { + foundErrors = true; + System.out.println(); + System.out.println("!!!!!!!!! MARSHALING ERROR"); + System.out.println(); + } + + // In the bad case, this ends up in a Tie that does not + // have the "foo" method. + System.out.println(); + System.out.println("Test unknown method:"); + System.out.println(); + try { + intResult = i2Ref.foo(46); + System.out.println(); + System.out.println("Correct return type: " + intResult); + System.out.println(); + } catch (BAD_OPERATION e) { + foundErrors = true; + System.out.println(); + System.out.println("!!!!!!!!! UNKNOWN METHOD ERROR"); + System.out.println(); + } + + // This next call has nothing to do with failover. + // It is just to see the information logged on the server side. + + try { + iRef.throwRuntimeException(0); + } catch (UNKNOWN e) { + ;; + } + + orb.shutdown(false); + orb.destroy(); + + System.out.println("================================================"); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ClientWithSticky.java b/functional-tests/src/test/java/corba/folb_8_1/ClientWithSticky.java new file mode 100644 index 000000000..5cacb8f79 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ClientWithSticky.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2004 Jun 13 (Sun) 13:49:39 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:05:26 by Harold Carr. +// + +package corba.folb_8_1; + +public class ClientWithSticky +{ + public static void main(String[] av) + { + Client.withSticky = true; + Client.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ColocatedCS.java b/functional-tests/src/test/java/corba/folb_8_1/ColocatedCS.java new file mode 100644 index 000000000..2f7b779aa --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ColocatedCS.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 17 (Thu) 17:05:00 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:05:35 by Harold Carr. +// + +package corba.folb_8_1; + +import java.util.Properties; +import org.omg.CORBA.ORB; + +public class ColocatedCS +{ + public static final String baseMsg = ColocatedCS.class.getName(); + public static final String main = baseMsg + ".main"; + + public static ORB orb; + public static boolean isColocated = false; + public static boolean clientTwoRefs = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String[] av) + { + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + Properties props = new Properties(); + props.setProperty("com.sun.corba.ee.ORBAllowLocalOptimization", + "true"); + Client.setProperties(props); + Server.setProperties(props, Common.socketPorts); + System.out.println(main + " : creating ORB."); + orb = ORB.init(av, props); + Server.orb = orb; + if (clientTwoRefs) { + ClientTwoRefs.orb = orb; + } else { + Client.orb = orb; + } + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + if (clientTwoRefs) { + ClientTwoRefs.main(av); + } else { + Client.main(av); + } + if (Client.foundErrors) { + System.out.println("FAIL"); + System.exit(1); + } + } catch (Throwable t) { + System.out.println(main); + t.printStackTrace(System.out); + System.exit(1); + } + System.out.println(main + " done"); + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ColocatedCSWithSticky.java b/functional-tests/src/test/java/corba/folb_8_1/ColocatedCSWithSticky.java new file mode 100644 index 000000000..772f25609 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ColocatedCSWithSticky.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2004 Jun 13 (Sun) 13:49:39 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:05:45 by Harold Carr. +// + +package corba.folb_8_1; + +public class ColocatedCSWithSticky +{ + public static void main(String[] av) + { + Client.withSticky = true; + ColocatedCS.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ColocatedClientTwoRefs.java b/functional-tests/src/test/java/corba/folb_8_1/ColocatedClientTwoRefs.java new file mode 100644 index 000000000..908649817 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ColocatedClientTwoRefs.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2004 Jun 13 (Sun) 13:49:39 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:05:54 by Harold Carr. +// + +package corba.folb_8_1; + +public class ColocatedClientTwoRefs +{ + public static void main(String[] av) + { + Client.withSticky = true; + ColocatedCS.clientTwoRefs = true; + ColocatedCS.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/Common.java b/functional-tests/src/test/java/corba/folb_8_1/Common.java new file mode 100644 index 000000000..4bee25a89 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/Common.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:47:13 by Harold Carr. +// Last Modified : 2005 Sep 28 (Wed) 14:55:27 by Harold Carr. +// + +package corba.folb_8_1; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.CosNaming.*; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.Encoding; +import org.omg.IOP.ENCODING_CDR_ENCAPS; + +import com.sun.corba.ee.spi.extension.ZeroPortPolicy; + +/** + * @author Harold Carr + */ +public abstract class Common +{ + public static boolean timing = false; + public static final String FAILOVER_SUPPORT = "FAILOVER_SUPPORT"; + public static final String FAILOVER = "FAILOVER"; + public static final String CACHE = "CACHE"; + + public static final String W = "W"; + public static final String X = "X"; + public static final String Y = "Y"; + public static final String Z = "Z"; + + public static String[] socketTypes = { W, X, Y, Z }; + public static int[] socketPorts = { 3333, 4444, 5555, 0 }; + public static int[] zero2Ports = { 3334, 4445, 5556, 0 }; + public static HashMap socketTypeToPort = new HashMap(); + public static HashMap portToSocketType = new HashMap(); + static { + for (int i = 0; i < socketTypes.length; i++) { + Integer port = new Integer(socketPorts[i]); + socketTypeToPort.put(socketTypes[i], port); + portToSocketType.put(port, socketTypes[i]); + } + } + public static final String serverName1 = "I1"; + public static final String serverName2 = "I2"; + public static final String zero1 = "zero1"; + public static final String zero2 = "zero2"; + + public static POA createPOA(String name, boolean zeroPortP, ORB orb) + throws Exception + { + // Get rootPOA + + POA rootPoa = (POA) orb.resolve_initial_references("RootPOA"); + rootPoa.the_POAManager().activate(); + + // Create child + + List policies = new ArrayList(); + + // Create child POA + policies.add( + rootPoa.create_lifespan_policy(LifespanPolicyValue.TRANSIENT)); + if (zeroPortP) { + policies.add(ZeroPortPolicy.getPolicy()); + } + Policy[] policy = (Policy[]) policies.toArray(new Policy[0]); + POA childPoa = rootPoa.create_POA(name, null, policy); + childPoa.the_POAManager().activate(); + return childPoa; + } + + // create servant and register it with a POA + public static org.omg.CORBA.Object createAndBind(String name, + ORB orb, POA poa) + throws Exception + { + Servant servant; + if (name.equals(Common.serverName1)) { + servant = new IServant(orb); + } else { + servant = new I2Servant(orb); + } + byte[] id = poa.activate_object(servant); + org.omg.CORBA.Object ref = poa.id_to_reference(id); + Common.getNameService(orb).rebind(Common.makeNameComponent(name), ref); + return ref; + } + + public static NamingContext getNameService(ORB orb) + { + org.omg.CORBA.Object objRef = null; + try { + objRef = orb.resolve_initial_references("NameService"); + } catch (Exception ex) { + System.out.println("Common.getNameService: " + ex); + System.exit(1); + } + return NamingContextHelper.narrow(objRef); + } + + public static NameComponent[] makeNameComponent(String name) + { + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + return path; + } + + + public static Codec getCodec(ORB orb) + { + try { + CodecFactory codecFactory = + CodecFactoryHelper.narrow(orb.resolve_initial_references("CodecFactory")); + return codecFactory.create_codec(new Encoding((short)ENCODING_CDR_ENCAPS.value, (byte)1, (byte)2)); + } catch (Exception e) { + System.out.println("Unexpected: " + e); + System.exit(1); + } + return null; + } + + public static String[] concat(String[] a1, String[] a2) + { + String[] result = new String[a1.length + a2.length]; + + int index = 0; + + for (int i = 0; i < a1.length; ++i) { + result[index++] = a1[i]; + } + + for (int i = 0; i < a2.length; ++i) { + result[index++] = a2[i]; + } + + /* + System.out.println(formatStringArray(a1)); + System.out.println(formatStringArray(a2)); + System.out.println(formatStringArray(result)); + */ + + return result; + } + + public static String formatStringArray(String[] a) + { + String result = ""; + for (int i = 0; i < a.length; ++i) { + result += a[i] + " "; + } + return result; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/folb_8_1/FolbTest.java b/functional-tests/src/test/java/corba/folb_8_1/FolbTest.java new file mode 100644 index 000000000..3e2ca81e6 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/FolbTest.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:49:22 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:06:20 by Harold Carr. +// + +package corba.folb_8_1; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +/** + * @author Harold Carr + */ +public class FolbTest + extends + CORBATest +{ + public static final String thisPackage = + FolbTest.class.getPackage().getName(); + + protected void doTest() + throws + Throwable + { + Controller orbd; + Controller server; + Controller client; + Controller colocated ; + //////////////////////////////////////////////////// + + orbd = createORBD(); + orbd.start(); + + //////////////////////////////////////////////////// + server = createServer(thisPackage + "." + "Server", "Server"); + client = createClient(thisPackage + "." + "Client", "Client"); + server.start(); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //////////////////////////////////////////////////// + + server = createServer(thisPackage + "." + "Server", + "ServerForSticky"); + client = createClient(thisPackage + "." + "ClientWithSticky", + "ClientWithSticky"); + server.start(); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //////////////////////////////////////////////////// + + colocated = createClient(thisPackage + "." + "ColocatedCS", + "ColocatedCS"); + colocated.start(); + colocated.waitFor(); + colocated.stop(); + + //////////////////////////////////////////////////// + + colocated = createClient(thisPackage + "." + "ColocatedCSWithSticky", + "ColocatedCSWithSticky"); + colocated.start(); + colocated.waitFor(); + colocated.stop(); + + //////////////////////////////////////////////////// + + server = createServer(thisPackage + "." + "Server", + "ServerForSticky"); + client = createClient(thisPackage + "." + "ClientTwoRefs", + "ClientTwoRefs"); + server.start(); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //////////////////////////////////////////////////// + + colocated = createClient(thisPackage + "." + "ColocatedClientTwoRefs", + "ColocatedClientTwoRefs"); + colocated.start(); + colocated.waitFor(); + colocated.stop(); + + //////////////////////////////////////////////////// + /** TODO: Issue # GLASSFISH_CORBA-7. Fix and Uncomment following failing tests. + * + server = createServer(thisPackage + "." + "Server", + "ServerForTiming1"); + server.start(); + client = createClient(thisPackage + "." + "ClientForTiming_NoFs_NoF_NoC", + "ClientForTiming_NoFs_NoF_NoC"); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //------------------------- + + server = createServer(thisPackage + "." + "Server", + "ServerForTiming2"); + server.start(); + client = createClient(thisPackage + "." + "ClientForTiming_Fs_NoF_NoC", + "ClientForTiming_Fs_NoF_NoC"); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //------------------------- + + server = createServer(thisPackage + "." + "Server", + "ServerForTiming3"); + server.start(); + client = createClient(thisPackage + "." + "ClientForTiming_Fs_NoF_C", + "ClientForTiming_Fs_NoF_C"); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //------------------------- + + + server = createServer(thisPackage + "." + "Server", + "ServerForTiming4"); + server.start(); + client = createClient(thisPackage + "." + "ClientForTiming_Fs_F_NoC", + "ClientForTiming_Fs_F_NoC"); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + + //------------------------- + server = createServer(thisPackage + "." + "Server", + "ServerForTiming"); + server.start(); + client = createClient(thisPackage + "." + "ClientForTiming_Fs_F_C", + "ClientForTiming_Fs_F_C"); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + *** End Issue # GLASSFISH_CORBA-7. + ***/ + //////////////////////////////////////////////////// + + orbd.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/folb_8_1/IIOPPrimaryToContactInfoImpl.java b/functional-tests/src/test/java/corba/folb_8_1/IIOPPrimaryToContactInfoImpl.java new file mode 100644 index 000000000..86bda9083 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/IIOPPrimaryToContactInfoImpl.java @@ -0,0 +1,314 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +//package com.sun.enterprise.iiop; + +// NOTE: This is the EXACT same file as in corba/folb unit test, +// except for parts commented out. +// REVISIT: Need to use from a direct copy of AS version. +// Just update Ant to build and use it AND provide dummy logging code. + +package corba.folb_8_1; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import java.util.logging.Level; + +//import com.sun.logging.LogDomains; + +// These are "ee" in the AS version: +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; +import com.sun.corba.ee.impl.misc.ORBUtility; + +/** + * This is the "sticky manager" - based on the 7.1 EE concept. + * @author Harold Carr + */ +public class IIOPPrimaryToContactInfoImpl + implements IIOPPrimaryToContactInfo +{ + + // REVISIT - log messages must be internationalized. + /* + private static Logger _logger = null; + static { + _logger = LogDomains.getLogger(LogDomains.CORBA_LOGGER); + } + */ + + private static MyLogger _logger = new MyLogger(); + + public final String baseMsg = IIOPPrimaryToContactInfoImpl.class.getName(); + + // This is made package private for FOLB timing test. + //private Map map; + Map map; + private boolean debugChecked; + private boolean debug; + public void setDebugChecked(boolean x) { debugChecked = x; } + public void setDebug (boolean x) { debug = x; } + + public IIOPPrimaryToContactInfoImpl() + { + map = new HashMap(); + debugChecked = false; + debug = false; + } + + public synchronized void reset(ContactInfo primary) + { + try { + if (debug) { + dprint(".reset: " + getKey(primary)); + } + map.remove(getKey(primary)); + } catch (Throwable t) { + _logger.log(Level.WARNING, + "Problem in " + baseMsg + ".reset", + t); + RuntimeException rte = + new RuntimeException(baseMsg + ".reset error"); + rte.initCause(t); + throw rte; + } + } + + public synchronized boolean hasNext(ContactInfo primary, + ContactInfo previous, + List contactInfos) + { + try { + if (! debugChecked) { + debugChecked = true; + debug = ((ORB)primary.getBroker()).transportDebugFlag + || _logger.isLoggable(Level.FINE); + } + + if (debug) { + dprint(".hasNext->: " + + formatKeyPreviousList(getKey(primary), + previous, + contactInfos)); + } + boolean result; + if (previous == null) { + result = true; + } else { + int previousIndex = contactInfos.indexOf(previous); + int contactInfosSize = contactInfos.size(); + if (debug) { + dprint(".hasNext: " + + previousIndex + " " + contactInfosSize); + } + if (previousIndex < 0) { + // This SHOULD not happen. + // It would only happen if the previous is NOT + // found in the current list of contactInfos. + RuntimeException rte = new RuntimeException( + + + "Problem in " + baseMsg + ".hasNext: previousIndex: " + + previousIndex); + + _logger.log(Level.SEVERE, + "Problem in " + baseMsg + ".hasNext: previousIndex: " + + previousIndex, rte); + throw rte; + } else { + // Since this is a retry, ensure that there is a following + // ContactInfo for .next + result = (contactInfosSize - 1) > previousIndex; + } + } + if (debug) { + dprint(".hasNext<-: " + result); + } + return result; + } catch (Throwable t) { + _logger.log(Level.WARNING, + "Problem in " + baseMsg + ".hasNext", + t); + RuntimeException rte = + new RuntimeException(baseMsg + ".hasNext error"); + rte.initCause(t); + throw rte; + } + } + + public synchronized ContactInfo next(ContactInfo primary, + ContactInfo previous, + List contactInfos) + { + try { + String debugMsg = null; + + if (debug) { + debugMsg = ""; + dprint(".next->: " + + formatKeyPreviousList(getKey(primary), + previous, + contactInfos)); + dprint(".next: map: " + formatMap(map)); + } + + Object result = null; + + if (previous == null) { + // This is NOT a retry. + result = map.get(getKey(primary)); + if (result == null) { + if (debug) { + debugMsg = ".next<-: initialize map: "; + } + // NOTE: do not map primary to primary. + // In case of local transport we NEVER use primary. + result = contactInfos.get(0); + map.put(getKey(primary), result); + } else { + if (debug) { + dprint(".next: primary mapped to: " + result); + } + int position = contactInfos.indexOf(result); + if (position == -1) { + // It is possible that communication to the key + // took place on SharedCDR, then a corbaloc to + // same location uses a SocketOrChannelContactInfo + // and vice versa. + if (debug) { + dprint(".next: cannot find mapped entry in current list. Removing mapped entry and trying .next again."); + } + reset(primary); + return next(primary, previous, contactInfos); + } + // NOTE: This step is critical. You do NOT want to + // return contact info from the map. You want to find + // it, as a SocketInfo, in the current list, and then + // return that ContactInfo. Otherwise you will potentially + // return a ContactInfo pointing to an incorrect IOR. + result = contactInfos.get(position); + if (debug) { + debugMsg = ".next<-: mapped: "; + } + } + } else { + // This is a retry. + // If previous is last element then .next is not called + // because hasNext will return false. + result = contactInfos.get(contactInfos.indexOf(previous) + 1); + map.put(getKey(primary), result); + + _logger.log(Level.INFO, "IIOP failover to: " + result); + + if (debug) { + debugMsg = ".next<-: update map: " + + " " + contactInfos.indexOf(previous) + + " " + contactInfos.size() + " "; + } + } + if (debug) { + dprint(debugMsg + result); + } + return (ContactInfo) result; + } catch (Throwable t) { + _logger.log(Level.WARNING, + "Problem in " + baseMsg + ".next", + t); + RuntimeException rte = + new RuntimeException(baseMsg + ".next error"); + rte.initCause(t); + throw rte; + } + } + + private Object getKey(ContactInfo contactInfo) + { + if (((SocketInfo)contactInfo).getPort() == 0) { + // When CSIv2 is used the primary will have a zero port. + // Therefore type/host/port will NOT be unique. + // So use the entire IOR for the key in that case. + return ((ContactInfoList)contactInfo.getContactInfoList()) + .getEffectiveTargetIOR(); + } else { + return contactInfo; + } + } + + private String formatKeyPreviousList(Object key, + ContactInfo previous, List list) + { + String result = + "\n key : " + key + + "\n previous: " + previous + + "\n list:"; + Iterator i = list.iterator(); + int count = 1; + while (i.hasNext()) { + result += "\n " + count++ + " " + i.next(); + } + return result; + } + + private String formatMap(Map map) + { + String result = ""; + synchronized (map) { + Iterator i = map.entrySet().iterator(); + if (! i.hasNext()) { + return "empty"; + } + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + result += + "\n key : " + entry.getKey() + + "\n value: " + entry.getValue() + + "\n"; + } + } + return result; + } + + private void dprint(String msg) + { + _logger.log(Level.FINE, msg); + } +} + + +class MyLogger +{ + void log(Level level, String msg) + { + log(level, msg, null); + } + + void log(Level level, String msg, Throwable t) + { + ORBUtility.dprint("IIOPPrimaryToContactInfoImpl.MyLogger.log", msg); + if (t != null) { + t.printStackTrace(System.out); + } + } + + boolean isLoggable(Level level) + { + return false; + } +} + + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/IORInterceptorImpl.java b/functional-tests/src/test/java/corba/folb_8_1/IORInterceptorImpl.java new file mode 100644 index 000000000..9b418a4f2 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/IORInterceptorImpl.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 13:43:29 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:07:06 by Harold Carr. +// + +package corba.folb_8_1; + +import java.net.InetAddress; + +import org.omg.CORBA.Any; +import org.omg.IOP.TaggedComponent; + +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; + +import com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt; +import com.sun.corba.ee.spi.legacy.interceptor.ORBInitInfoExt ; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +/** + * @author Harold Carr + */ +public class IORInterceptorImpl + extends + org.omg.CORBA.LocalObject + implements + ORBInitializer, + org.omg.PortableInterceptor.IORInterceptor +{ + private ORB orb ; + + public IORInterceptorImpl() + { + } + + public IORInterceptorImpl( ORB orb ) + { + this.orb = orb ; + } + + public final String baseMsg = IORInterceptorImpl.class.getName(); + public String name() { return baseMsg; } + public void destroy() { } + + // + // ORBInitializer + // + + public void pre_init(ORBInitInfo info) { } + + public void post_init(ORBInitInfo info) + { + orb = ((ORBInitInfoExt)info).getORB() ; + try { + info.add_ior_interceptor(new IORInterceptorImpl(orb)); + } catch (DuplicateName ex) { + System.out.println(baseMsg + ex); + System.exit(1); + } + } + + // + // IORInterceptor + // + + public void establish_components(IORInfo iorInfo) + { + try { + IORInfoExt iorInfoExt = (IORInfoExt) iorInfo; + + String localAddress = InetAddress.getLocalHost().getHostAddress(); + + for (int i = 0; i < Common.socketTypes.length; i++) { + + TaggedCustomSocketInfo socketInfo = + new TaggedCustomSocketInfo( + Common.socketTypes[i], + localAddress, + iorInfoExt.getServerPort(Common.socketTypes[i])); + + if (orb.transportDebugFlag) { + dprint(".establish_components:" + + " " + Common.socketTypes[i] + + " " + localAddress + + " " + iorInfoExt.getServerPort(Common.socketTypes[i])); + } + + Any any = orb.create_any(); + TaggedCustomSocketInfoHelper.insert(any, socketInfo); + byte[] data = Common.getCodec(orb).encode(any); + TaggedComponent tc = + new TaggedComponent(TAG_TAGGED_CUSTOM_SOCKET_INFO.value, + data); + iorInfo.add_ior_component(tc); + } + } catch (Exception e) { + System.out.println(baseMsg + e); + System.exit(1); + } + } + + public void components_established( IORInfo iorInfo ) + { + } + + public void adapter_manager_state_changed( int managerId, short state ) + { + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + } + + private void dprint(String msg) + { + ORBUtility.dprint("IORInterceptor", msg); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/IORToSocketInfoImpl.java b/functional-tests/src/test/java/corba/folb_8_1/IORToSocketInfoImpl.java new file mode 100644 index 000000000..7f7700d88 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/IORToSocketInfoImpl.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2004 May 11 (Tue) 10:26:27 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:07:17 by Harold Carr. +// + +package corba.folb_8_1; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.omg.CORBA.Any; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.TaggedComponent; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class IORToSocketInfoImpl + implements IORToSocketInfo +{ + public List getSocketInfo(IOR ior, List previous) + { + boolean debug = ior.getORB().transportDebugFlag; + + if (debug) { + dprint(".getSocketInfo->: " + previous); + } + + if (! previous.isEmpty()) { + if (debug) { + dprint(".getSocketInfo<-: returning previous: " + previous); + } + return previous; + } + + SocketInfo socketInfo; + List result = new ArrayList(); + + // + // Find and add address from profile. + // + + IIOPProfileTemplate iiopProfileTemplate = (IIOPProfileTemplate) + ior.getProfile().getTaggedProfileTemplate() ; + IIOPAddress primary = iiopProfileTemplate.getPrimaryAddress() ; + String hostname = primary.getHost().toLowerCase(); + int port = primary.getPort(); + socketInfo = createSocketInfo("Primary", + SocketInfo.IIOP_CLEAR_TEXT, + hostname, port); + result.add(socketInfo); + + // + // Find and add alternate iiop addresses. + // + + Iterator iterator; + /* DO NOT DO THIS FOR THE TEST + iterator = iiopProfileTemplate.iteratorById( + TAG_ALTERNATE_IIOP_ADDRESS.value); + + while (iterator.hasNext()) { + AlternateIIOPAddressComponent alternate = + (AlternateIIOPAddressComponent) iterator.next(); + hostname = alternate.getAddress().getHost().toLowerCase(); + port = alternate.getAddress().getPort(); + socketInfo = createSocketInfo("Alternate", + SocketInfo.IIOP_CLEAR_TEXT, + hostname, port); + result.add(socketInfo); + } + */ + + // + // Find and add custom tagged addresses. + // + + iterator = iiopProfileTemplate.iteratorById( + TAG_TAGGED_CUSTOM_SOCKET_INFO.value); + + while (iterator.hasNext()) { + Object o = iterator.next(); + if (! Common.timing) { + System.out.println(o); + } + byte[] data = ((TaggedComponent)o).getIOPComponent( ior.getORB() ). + component_data ; + Any any = null; + try { + any = Common.getCodec(ior.getORB()).decode(data); + } catch (Exception e) { + System.out.println("Unexpected: " + e); + System.exit(1); + } + TaggedCustomSocketInfo taggedSocketInfo = + TaggedCustomSocketInfoHelper.extract(any); + socketInfo = createSocketInfo("custom", + taggedSocketInfo.type, + taggedSocketInfo.host, + taggedSocketInfo.port); + result.add(socketInfo); + } + + // This should be sorted in the order you want requests tried + // if failover occurs. + + if (debug) { + dprint(".getSocketInfo<-: returning: " + result); + } + return result; + } + + private SocketInfo createSocketInfo(String testMessage, + final String type, + final String hostname, final int port) + { + if (! Common.timing) { + System.out.println(testMessage + " " + type + + " " + hostname + " " + port); + } + return new SocketInfo() { + public String getType() { return type; } + public String getHost() { return hostname; } + public int getPort() { return port; } + @Override + public String toString() + { + return "SocketInfo[" + type + " " + hostname + " " + port +"]"; + } + }; + } + + private void dprint(String msg) + { + ORBUtility.dprint("IORToSocketInfoImpl", msg); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/README.txt b/functional-tests/src/test/java/corba/folb_8_1/README.txt new file mode 100644 index 000000000..ef5b60bd3 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/README.txt @@ -0,0 +1,112 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Server: + + - Opens five acceptors: + The standard IIOP_CLEAR_TEXT port. + A "W" type at port 3333. + An "X" type at port 4444. + A "Y" type at port 5555. + A "Z" type EPHEMERAL port. + + - unregister, given a port type, will find and kill the acceptor of + that type and kill all connections accepted by that acceptor. + + - register, given a port type, will start up that acceptor at the + ports show above. + +Client: Without sticky: + + - Looks up a reference to I. + - Tells the server to unregister (kill) its IIOP_CLEAR_TEST server + port followed by the W, X, and Y ports. It leaves the Z port open. + - A ClientRequestInterceptor remembers the socket type on which each + request is made (or if it is colocated). + - Checks that the connection type is the expected one. + The order expected ir IIOP_CLEAR_TEXT, W, X, Y. + - Tells the server (via connection Z) to register (start up) W. + - Tells the server to unregister W. + - Checks that the unregister request goes on W (instead of Z) since + no failover cache (sticky manager) is present. + +Client: With sticky: + + - Same as above except that the request on the last step should + go on Z even though W (earlier in the list) is present since + the sticky manager remembers Z as the last good connection. + +ColocatedCS: WithoutSticky and WithSticky: + + - Same as above but all requests do not use connetions + regardless of the state of the server ports. + + - Since we use a local subcontract none of the failover code is invoked. + +ClientTwoRefs and ColocatedClientTwoRefs: + + - Test to ensure that we go to the correct object on the server. + + - If we used the entire ContactInfo as the return from the cache + then we would use the wrong IOR. Only use the SocketInfo and + then find a match in the current ContactInfoList. + + - Colocated test for completeness. + +ZeroPort: + + - REVISIT + Need to be made into a separate test. + + When references contain a 0 port in their primary we hash + on the entire IOR. Otherwise we map IORs referring to two + different servers to only one of the servers. + +ClientForTiming: + + - When REALLY doing timing tests: + + Set NUMBER_OF_WARMUP_LOOPS and NUMBER_OF_TIMING_LOOPS appropriately. + + Set debug to false (so nothing is written to logs). + + Either set logging to FINE or set ORBUtil.mc + COMM_FAILURE/CONNECT_FAILURE to fine (to avoid writing logs). + + - This tests run and puts its results in the GEN directory + but the results are NOT examined. + + - A white box test to measure: + + NoFsNoFNoC: + Requests without failover support plugged in. + + FsNoFNoc: + Requests with failover support plugged in but no failover and no cache. + + FSNoFC: + Requests with failover support plugged in but no failover and cache. + + FsFNoC: + Requests with failover support plugged in, failover, no cache. + + FsFC: + Requests with failover support plugged in, failover, cache. + + - Relies ORB support and timing plugged into various parts of ORB. + + - REVISIT: + Note: there is a problem in FsFC mode: + In setupFailover it does NOT find the map entry for the primary + key - even though it is there. NEEDS TO BE FIXED. + + This means that, when doing revertCache after a failover request + that we put null into the map instead of the original + IIOP_CLEAR_TEXT entry. This means that on the next invocation + we initialize the map rather than find the IIOP_CLEAR_TEXT entry. + So the timing test is slightly not accurate. Regardless, the + IIOP_CLEAR_TEXT entry fails and we failover to W, which is what we + wanted to time. + +;;; End of file. + + diff --git a/functional-tests/src/test/java/corba/folb_8_1/Server.java b/functional-tests/src/test/java/corba/folb_8_1/Server.java new file mode 100644 index 000000000..f35580a75 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/Server.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:48:59 by Harold Carr. +// Last Modified : 2005 Jul 19 (Tue) 12:24:38 by Harold Carr. +// + +package corba.folb_8_1; + + +import java.util.Properties ; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import corba.hcks.U; + +/** + * @author Harold Carr + */ +public class Server +{ + public static final String baseMsg = Common.class.getName(); + + public static ORB orb; + + // So it can be accessed later. + public static org.omg.CORBA.Object ref; + + public static void setProperties(Properties props, int[] socketPorts) + { + // + // Debugging flags. Generally commented out. + // + /* + props.setProperty(ORBConstants.DEBUG_PROPERTY, + "giop,transport,subcontract"); + */ + + // + // Tell the ORB to listen on user-defined port types. + // + + String listenPorts = formatListenPorts(); + props.setProperty(ORBConstants.LISTEN_SOCKET_PROPERTY, listenPorts); + System.out.println(listenPorts); + + // + // Register the socket factory that knows how to create + // Sockets of type X Y and Z. + // + + props.setProperty(ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + SocketFactoryImpl.class.getName()); + + // + // Register and IORInterceptor that will put port + // type/address info into IORs. + // E.G.: X/:*, Y/:4444, Z/:5555 + // + + props.setProperty("org.omg.PortableInterceptor.ORBInitializerClass." + IORInterceptorImpl.class.getName(), + "dummy"); + } + + public static String formatListenPorts() + { + String result = ""; + for (int i = 0; i < Common.socketTypes.length; i++) { + result += Common.socketTypes[i] + + ":" + + Integer.toString(Common.socketPorts[i]); + if (i + 1 < Common.socketTypes.length) { + result += ","; + } + } + return result; + } + + public static void main(String av[]) + { + try { + if (! ColocatedCS.isColocated) { + Properties props = System.getProperties(); + setProperties(props, Common.socketPorts); + orb = ORB.init(av, props); + } + + POA poa = Common.createPOA("child", false, orb); + ref = Common.createAndBind(Common.serverName1, orb, poa); + Common.createAndBind(Common.serverName2, orb, poa); + + System.out.println ("Server is ready."); + + synchronized (ColocatedCS.signal) { + ColocatedCS.signal.notifyAll(); + } + + orb.run(); + + } catch (Throwable t) { + System.out.println(baseMsg + t); + t.printStackTrace(System.out); + System.exit(1); + } + } + +} + +// This class is to ensure that we do NOT store a contact info to +// a different object and try to send an invocation from a client to +// an incorrect Tie. +class I2Servant extends I2POA +{ + private com.sun.corba.ee.spi.orb.ORB orb; + + public I2Servant(ORB orb) + { + this.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + } + + public int m(String x) + { + int result = new Integer(x).intValue(); + System.out.println("I2Servant.m result: " + result); + System.out.flush(); + return result; + } + + public org.omg.CORBA.Object n(String x) + { + return Server.ref; + } + + public int foo(int x) + { + return x; + } +} + +class IServant extends IPOA +{ + private com.sun.corba.ee.spi.orb.ORB orb; + + public IServant(ORB orb) + { + this.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + } + + public String m(String x) + { + return "IServant echoes: " + x; + } + + public int n(String x) + { + return 101; + } + + public int throwRuntimeException(int x) + { + return 1/x; + } + + public boolean unregister(String socketType) + { + return U.unregisterAcceptorAndCloseConnections(socketType, orb); + } + + public boolean register(String socketType) + { + return U.registerAcceptor(socketType, + ((Integer) Common.socketTypeToPort.get(socketType)) + .intValue(), + orb); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/SocketFactoryImpl.java b/functional-tests/src/test/java/corba/folb_8_1/SocketFactoryImpl.java new file mode 100644 index 000000000..a2b98efe8 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/SocketFactoryImpl.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.folb_8_1; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.net.ServerSocket; +import java.nio.channels.SocketChannel; +import java.nio.channels.ServerSocketChannel; + +import com.sun.corba.ee.spi.transport.Acceptor; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ORBSocketFactory; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class SocketFactoryImpl + implements ORBSocketFactory +{ + private ORB orb; + + public void setORB(ORB orb) + { + this.orb = orb; + } + + public ServerSocket createServerSocket(String type, + InetSocketAddress inetSocketAddress) + throws IOException + { + ServerSocket serverSocket = null; + try { + if (! Common.timing) { + System.out.println(".createServerSocket->: " + type + " " + + inetSocketAddress); + } + + ServerSocketChannel serverSocketChannel = null; + + if (orb.getORBData().acceptorSocketType().equals(ORBConstants.SOCKETCHANNEL)) { + serverSocketChannel = ServerSocketChannel.open(); + serverSocket = serverSocketChannel.socket(); + } else { + serverSocket = new ServerSocket(); + } + serverSocket.bind(inetSocketAddress); + return serverSocket; + } finally { + if (! Common.timing) { + System.out.println(".createServerSocket<-: " + type + " " + + inetSocketAddress + " " + serverSocket); + } + } + } + + public Socket createSocket(String type, + InetSocketAddress inetSocketAddress) + throws IOException + { + Socket socket = null; + + try { + if (! Common.timing) { + System.out.println(".createSocket->: " + type + " " + + inetSocketAddress); + } + + SocketChannel socketChannel = null; + + if (orb.getORBData().connectionSocketType().equals(ORBConstants.SOCKETCHANNEL)) { + socketChannel = ORBUtility.openSocketChannel(inetSocketAddress); + socket = socketChannel.socket(); + } else { + socket = new Socket(inetSocketAddress.getHostName(), + inetSocketAddress.getPort()); + } + + // Disable Nagle's algorithm (i.e., always send immediately). + socket.setTcpNoDelay(true); + + return socket; + + } finally { + if (! Common.timing) { + System.out.println(".createSocket<-: " + type + " " + + inetSocketAddress + " " + socket); + } + } + } + + public void setAcceptedSocketOptions(Acceptor acceptor, + ServerSocket serverSocket, + Socket socket) + throws SocketException + { + // Disable Nagle's algorithm (i.e., always send immediately). + socket.setTcpNoDelay(true); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ZeroPortServer1.java b/functional-tests/src/test/java/corba/folb_8_1/ZeroPortServer1.java new file mode 100644 index 000000000..b2449fda1 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ZeroPortServer1.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2004 Aug 12 (Thu) 14:06:19 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:07:40 by Harold Carr. +// + +package corba.folb_8_1; + + +import java.util.Properties ; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; + + + +/** + * @author Harold Carr + */ +public class ZeroPortServer1 +{ + public static final String baseMsg = Common.class.getName(); + + public static ORB orb; + + public static String serverName = Common.zero1; + public static int[] socketPorts = Common.socketPorts; + + public static void main(String av[]) + { + try { + Properties props = System.getProperties(); + Server.setProperties(props, socketPorts); + orb = ORB.init(av, props); + + POA poa = Common.createPOA("zeroPortPOA", true, orb); + Common.createAndBind(serverName, orb, poa); + + System.out.println ("Server is ready."); + + orb.run(); + + } catch (Exception e) { + System.out.println(baseMsg + e); + e.printStackTrace(System.out); + System.exit(1); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/folb_8_1/ZeroPortServer2.java b/functional-tests/src/test/java/corba/folb_8_1/ZeroPortServer2.java new file mode 100644 index 000000000..3c7f7c527 --- /dev/null +++ b/functional-tests/src/test/java/corba/folb_8_1/ZeroPortServer2.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2004 Jun 13 (Sun) 13:49:39 by Harold Carr. +// Last Modified : 2005 Jun 01 (Wed) 11:07:47 by Harold Carr. +// + +package corba.folb_8_1; + +public class ZeroPortServer2 +{ + public static void main(String[] av) + { + ZeroPortServer1.serverName = Common.zero2; + ZeroPortServer1.socketPorts = Common.zero2Ports; + ZeroPortServer1.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/framework/CORBATest.java b/functional-tests/src/test/java/corba/framework/CORBATest.java new file mode 100644 index 000000000..442607388 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/CORBATest.java @@ -0,0 +1,838 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.Vector; +import org.glassfish.pfl.test.JUnitReportHelper; + +import test.RemoteTest; +import test.ServantContext; +import test.Test; + +/** + * Main CORBA Technologies test class which should be extended + * for each individual test. It provides an easy way to run + * IDL, RMI, and Java compilers; start ORBD, client(s), and server(s); + * and manage output from each. + *

+ * The default is to run all of these in separate processes, but this + * can be changed for ORBD, client, and server by specifying what execution + * strategy to use. + *

+ * It extends test.RemoteTest to gain access to some data (command + * line arguments, especially), but doesn't use RemoteTest's RMI/RMI-IIOP + * system by default. + *

+ * An individual test can configure a wide variety of things by + * setting values in the Options singleton class. + * + *@see corba.example.Example + *@see test.Test + *@see test.RemoteTest + *@see corba.framework.Options + */ +public abstract class CORBATest extends test.RemoteTest +{ + /** + * Skip any IDL compiling. This could be useful if you + * didn't wipe the output directory, and wanted to change + * stubs or skeletons by hand in debugging. + */ + public static final String SKIP_IDLJ_FLAG = "-noidlj"; + + /** + * Skip compiling generated (or user specified) .java files. + */ + public static final String SKIP_JAVAC_FLAG = "-nojavac"; + + /** + * Force use of the DebugExec execution strategy for the + * process(es) with the comma separated name(s) following + * this command line flag. It is currently set to the + * normal framework debug flag, so you see everything + * that goes on. + */ + public static final String DEBUG_STRATEGY_FLAG = "-debug"; + + /** + * Force use of the RDebugExec execution strategy for the + * process(es) with the comma separated name(s) following + * this command line flag. It does not set the framework + * debug flag. + */ + public static final String RDEBUG_STRATEGY_FLAG = "-rdebug"; + + /** + * Pass the ORBDebug settings into a controller. + * Syntax is -orbtrace name:flag1,flag2,...;name:flag1,... + * This sets the system property com.sun.corba.ee.ORBDebug to the list + * of flags for a controller named name + */ + public static final String TRACE_FLAG = "-orbtrace" ; + + /** + * Force use of the ODebugExec execution strategy for the + * process(es) with the comma separated name(s) following + * this command line flag. It does not set the framework + * debug flag. + */ + public static final String ODEBUG_STRATEGY_FLAG = "-odebug"; + + /** + * IDLCompiler instance used by compileIDLFiles() + */ + protected IDLCompiler idlCompiler = new IDLCompiler(); + + /** + * RMICCompiler instance used by compileRMIFiles() + */ + protected RMICompiler rmic = new RMICompiler(); + + /** + * JavaCompiler instance used by compileJavaFiles() + */ + protected JavaCompiler javac = new JavaCompiler(); + + /** + * Initializes this test. If you override this method, make sure to + * either call super.setup() first, or duplicate some of the code, + * especially the (re)initialization of the Options class. + * Subclasses shouldn't need to modify this since they can handle + * all their settings at the beginning of doTest with Options. + */ + @Override + public void setup() { + try { + if (usesOldFramework()) { + super.setup(); + } + + Options.init(this); + + parseDebugExecFlags(); + parseTraceFlag() ; + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + throw new Error(out.toString()); + } + } + + /** + * test.RemoteTest's way of performing an RMI or RMI-IIOP test. The given + * ServantContext allows remote control of servants by using RMI. This + * is used by the IBM tests. Any exceptions of errors thrown will result + * in the test framework reporting "FAILED," and printing the exception's + * stack trace. + *

+ * Tests which don't use RMI/RMI-IIOP can avoid this method by using + * the Options class to set files for RMIC compilation, then calling + * compileRMIFiles(). After that, they can load a servant or client + * just as they would with CORBA and IDL. + *

+ * Calls doTest() by default. To use this, override usesOldFramework + * to return true. You will also need to specify what remote + * files to use with getRemoteSevantClasses. See test.RemoteTestExample. + * + *@param context Allows the test to manage servant life-cycle + *@exception Throwable Any errors which signal that this test failed + *@see test.RemoteTest + *@see test.ServantContext + *@see test.RemoteTestExample + */ + protected void doTest(ServantContext context) throws Throwable { + doTest(); + } + + /** + * Subclasses can override this method if they need to use + * test.RemoteTest's way of managing servants (with ServantContexts). + * Returns false by default. + * + *@return True when the framework should use test.RemoteTest's + * servant management, false for the newer framework's + * system. + */ + protected boolean usesOldFramework() { + return false; + } + + /** + * Subclasses override this method to actually perform their tests. + * Any exceptions or errors thrown will result in the test framework + * reporting "FAILED," and printing the exception's stack trace. + * No-op by default. + * + *@exception Throwable Any errors which signal that this test failed + */ + protected void doTest() throws Throwable { + // Subclasses should override one of the doTest methods + } + + /** + * Calls the appropriate version of doTest, then handles exit values + * and exceptions. + * + * This is called by the test framework and shouldn't need to be changed. + */ + @Override + public void run() + { + CORBAUtil.mkdir( Options.getOutputDirectory() ) ; + CORBAUtil.mkdir( Options.getReportDirectory() ) ; + boolean errorOccured = false; + + try { + if (usesOldFramework()) { + super.run(); + } else { + doTest(null); + } + } catch (ThreadDeath death) { + errorOccured = true; + throw death; + } catch (Throwable e) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + errorOccured = true; + status = new Error("Caught " + out.toString()); + } finally { + // Make sure processes are dead and streams are closed + cleanUp(); + + // Make sure all exit values were Controller.SUCCESS + // unless there was already an error (don't want to + // overwrite the more specific error message). + if (!errorOccured) { + handleExitValues(); + } + } + } + + /** + * test.RemoteTest's way of getting the classes that need + * to go through RMIC. This newer framework does this within + * the Options singleton, just as it does with IDL and + * .java files. + * + *@return Array of class names to go through RMIC + */ + protected String[] getRemoteServantClasses() + { + return new String [0]; + } + + /** + * Compile IDL files (called by subclasses in doTest). + * To use this, simply specify file names with the Options + * singleton. They must include the .java ending, but don't have + * to be full paths, just the names. To toggle IDL + * compilation on the command line, use the -noidlj parameter. + * + *@see Options#setIDLFiles + * + *@exception Any error that occured during compilation (bad exit + * value for the process would be the most common) + */ + protected void compileIDLFiles() throws Exception + { + if (!getArgs().containsKey(SKIP_IDLJ_FLAG)) { + + String files[] = Options.getIDLFiles(); + + // Get the absolute paths of the files + if (files == null) { + return; + } + + String searchPath[] = new String[] { Options.getTestDirectory() }; + + CORBAUtil.toAbsolutePaths(files, + searchPath); + + idlCompiler.compile(files, + Options.getIDLCompilerArgs(), + Options.getOutputDirectory(), + Options.getReportDirectory()); + } + } + + /** + * Compile using RMIC (called by subclasses in doTest). + * Specify the class names with the Options singleton. To + * toggle RMIC use on the command line, use the -normic parameter. + * + *@see Options#setRMICClasses + * + *@exception Any error that occured during compilation (bad exit + * value for the process would be the most common) + */ + protected void compileRMICFiles() throws Exception + { + if (!getArgs().containsKey(RemoteTest.SKIP_RMIC_FLAG)) { + rmic.compile(Options.getRMICClasses(), + Options.getRMICArgs(), + Options.getOutputDirectory(), + Options.getReportDirectory()); + } + } + + /** + * Adds absolute paths to the given Vector of any .java files in the + * specified directory or its subdirectories. This won't add a + * file if its class file is present and the class file is newer + * than the .java file. + * + *@param files Current Vector of .java files to augment + *@param dir Directory to examine + */ + private void getGenJavaFilesHelper(Vector files, File dir) + { + // Create a filter that accepts directory names and .java files + FileFilter dotJavaFilter = new FileFilter() { + public boolean accept(File pathname) { + return ((pathname.isFile() + && pathname.toString().endsWith(".java")) + || (pathname.isDirectory())); + } + }; + + File fileArray[] = dir.listFiles(dotJavaFilter); + + if (fileArray == null) { + return; + } + + // Recurse down through any directories, gathering absolute paths + // of all .java files + for (int i = 0; i < fileArray.length; i++) { + if (fileArray[i].isDirectory()) { + getGenJavaFilesHelper(files, + new File(fileArray[i].getAbsolutePath())); + } else { + + // Add the absolute path of this .java file unless + // its .class file exists and the .java file was + // modified more recently. (Assumes they are in the + // same directory -- they should be for generated files.) + + String path = fileArray[i].getAbsolutePath(); + String dotClassName = path.substring(0, path.indexOf(".java")) + + ".class"; + + File dotClassFile = new File(dotClassName); + + if (!dotClassFile.exists() || + fileArray[i].lastModified() > dotClassFile.lastModified()) { + + files.add(fileArray[i].getAbsolutePath()); + } + } + } + } + + /** + * Return an array of absolute paths to java files which were created + * from compiling IDL. Currently, this just searches the output directory + * and its subdirectories for *.java files. Since the output directory is + * assumes to be wiped each time the test is run (unless + * debugging), this is reasonable. + * + *@return Array of absolute paths to .java files or the empty array + * if none + */ + private Vector getGeneratedJavaFiles() + { + File dir = new File (Options.getOutputDirectory()); + + Vector files = new Vector(); + + getGenJavaFilesHelper(files, dir); + + return files; + } + + /** + * Compile .java files (called by subclasses in their doTest + * method). + * Convenience method for subclasses to compile both specified + * and any generated .java files. Subclasses can specify any + * non-generated files that need compilation with the Options + * singleton. This can be skipped by specifying the -nojavac + * flag on the command line. + * + *@see Options#setJavaFiles + * + *@exception Any error that occured during compilation (bad exit + * value for the process would be the most common) + */ + @SuppressWarnings("unchecked") + protected void compileJavaFiles() throws Exception + { + if (getArgs().containsKey(SKIP_JAVAC_FLAG)) { + return; + } + + // Get any .java files that were generated + Vector fileVector = getGeneratedJavaFiles(); + + // Add any subclass-specified files + String userFiles[] = Options.getJavaFiles(); + + if (userFiles != null) { + fileVector.addAll(Arrays.asList(userFiles)); + } + + if (fileVector.isEmpty()) { + return; + } + + String[] files = CORBAUtil.toArray(fileVector); + + // Convert any non-generated file names to absolute paths + CORBAUtil.toAbsolutePaths(files, + new String[] { Options.getTestDirectory(), + Options.getOutputDirectory() }); + + javac.compile(files, + Options.getJavacArgs(), + Options.getOutputDirectory(), + Options.getReportDirectory()); + } + + private enum ControllerKind { CLIENT, SERVER, ORBD } ; + + private Controller createProcess( String className, ControllerKind kind, String name, + Properties props, Vector args, Hashtable extra ) throws Exception { + + Controller executionStrategy; + if (odebugProcessNames.contains(name)) { + executionStrategy = new ODebugExec(); + } else if (rdebugProcessNames.contains(name)) { + executionStrategy = new RDebugExec(); + } else if (debugProcessNames.contains(name)) { + executionStrategy = new DebugExec(); + } else { + switch (kind) { + case CLIENT : + executionStrategy = newClientController() ; + break ; + case SERVER : + executionStrategy = newServerController() ; + break ; + default : + executionStrategy = new ExternalExec() ; + break ; + } + } + + FileOutputDecorator exec = new FileOutputDecorator(executionStrategy); + + // The props, args, and extra values are all shared, so make copies to + // avoid unpleasant surprises! + String argArray[] = CORBAUtil.toArray(args); + + Properties copy = new Properties() ; + Enumeration en = props.propertyNames() ; + while (en.hasMoreElements()) { + String key = (String)en.nextElement() ; + copy.setProperty( key, + props.getProperty( key ) ) ; + } + + props.setProperty( "corba.test.controller.name", name ) ; + + String traceFlags = (String) traceMap.get(name) ; + if (traceFlags != null) { + copy.setProperty(ORBConstants.DEBUG_PROPERTY, traceFlags); + } + + int emmaPort = EmmaControl.setCoverageProperties( copy ) ; + + Hashtable hash = new Hashtable( extra ) ; + + exec.initialize(className, name, copy, null, argArray, + Options.getReportDirectory() + name + ".out.txt", + Options.getReportDirectory() + name + ".err.txt", hash, emmaPort); + + controllers.add(exec); + + return exec; + } + + /** + * Create and initialize the Controller for the ORBD. This initializes + * and returns a Controller wrapped in a FileOutputDecorator. Most of the + * arguments to the Controller can be set in the Options class. + * + *@return Controller object representing the ORBD process, but + * not yet started. + * + *@exception Exception Any problem generated by initializing the + * Controller + * + *@see Controller + */ + public Controller createORBD() throws Exception + { + String javaIDLHome = Options.getJavaIDLHome(); + CORBAUtil.mkdir(javaIDLHome); + + Test.dprint("ORB initial port: " + Options.getORBInitialPort()); + Test.dprint("Activation port: " + Options.getActivationPort()); + + return createProcess( "com.sun.corba.ee.impl.activation.ORBD", ControllerKind.ORBD, + "ORBD", Options.getORBDProperties(), Options.getORBDArgs(), + Options.getORBDExtra() ) ; + } + + /** + * Create and initialize the Controller for a server. This + * initializes and wraps it in a FileOutputDecorator. + * + *@param className Fully qualified class name of the server + *@param serverName Name used to identify this server for + * output file name purposes + *@return Controller Initialized (but not started) Controller + * for the server + *@exception Exception Any problem generated by initializing + * + *@see Controller + *@see #newServerController + *@see Options + */ + public Controller createServer(String className, String serverName) + throws Exception + { + Test.dprint("Creating server object..."); + return createProcess( className, ControllerKind.SERVER, serverName, + Options.getServerProperties(), Options.getServerArgs(), Options.getServerExtra() ) ; + } + + /** + * Same as createServer(String, String) but uses the default + * name "server." This is sufficient for one server tests. + */ + public Controller createServer(String className) throws Exception + { + return createServer(className, "server"); + } + + /** + * Creates a new Controller of the appropriate type for the server. + * + *@return Controller A new Controller object + *@see ExternalExec + */ + protected Controller newServerController() + { + return new ExternalExec(); + } + + private JUnitReportHelper helper = new JUnitReportHelper( "Controller_" + this.getClass().getName() ) ; + + /** + * Create and initialize the Controller for the client. This + * initializes and wraps it in a FileOutputDecorator; + * + *@param className Fully qualified class name of the client + *@param clientName Name used to identify this client for + * output file name purposes. + *@return Controller Initialized (but not started) Controller + * for the client + *@exception Exception Any problem generated by starting + *@see Controller + *@see #newClientController + *@see Options + */ + public Controller createClient(String className, String clientName) + throws Exception { + + Test.dprint("Creating client object..."); + return createProcess( className, ControllerKind.CLIENT, clientName, + Options.getClientProperties(), Options.getClientArgs(), Options.getClientExtra() ) ; + } + + /** + * Same as createClient(String, String) but uses the default name + * of "client." This is sufficient for one client tests. + */ + public Controller createClient(String className) throws Exception + { + return createClient(className, "client"); + } + + /** + * Creates a new Controller of the appropriate type for the client. + * The default implementation returns an ExternalExec object, + * so the Controller's start() method returns immediately after + * starting a separate Process. + * + *@return Controller A new Controller object + *@see ExternalExec + */ + protected Controller newClientController() + { + return new ExternalExec(); + } + + /** + * Makes sure the given process has ended, and cleans up its + * output streams. This catches all exceptions. + */ + private void cleanUpHelp(Controller process) + { + if (process == null) { + return; + } + + String name = process.getClassName() + "." + process.getProcessName(); + + Test.dprint("Cleaning up " + name + "..."); + + helper.start( name ) ; + + process.kill() ; + int exitValue = process.exitValue() ; + long duration = process.duration() ; + if (exitValue <= 0) { + helper.pass(duration / 1000); + } else { + helper.fail("Controller terminated with exit value " + exitValue, duration / 1000); + } + + try { + process.kill(); + } catch (Throwable t) { + System.err.println("Problem stopping " + name + ": " + t); + System.err.println("May need to kill this process"); + // Disregard + } + + OutputStream out = process.getOutputStream(); + OutputStream err = process.getErrorStream(); + + // For ExternalExec processes, the ProcessMonitors will + // close the output streams when the process dies and + // they finish writing all of the output. + if (process instanceof corba.framework.ExternalExec) { + return; + } + + if (out != null && out != System.out) { + try { + out.flush(); + } catch (IOException e) { + // Disregard + } + + try { + out.close(); + } catch (IOException e) { + // Disregard + } + } + + if (err != null && err != System.err) { + try { + err.flush(); + } catch (IOException e) { + // Disregard + } + + try { + err.close(); + } catch (IOException e) { + // Disregard + } + } + } + + /** + * Call cleanUpHelp for any Controllers that were created. + */ + private void cleanUp() + { + for (Controller ctrl : controllers) { + cleanUpHelp(ctrl); + } + + EmmaControl.resetPortAllocator() ; + helper.done() ; + } + + + /** + * Confirm all Controllers were either stopped or exited with + * success values. If something failed, the test's status + * member is set to a new Error documenting the problem(s). + */ + private void handleExitValues() + { + int failures = 0; + String lineSeparator = System.getProperty("line.separator"); + StringBuilder failedMsg = new StringBuilder("Bad exit value(s):" + + lineSeparator); + + for (Controller controller : controllers) { + try { + controller.kill(); + } catch (IllegalThreadStateException ex) {} + + int exitValue = 1; + + try { + exitValue = controller.exitValue(); + } catch (IllegalThreadStateException ex) { + // The process was never started, probably because of + // a prior error + continue; + } + + if (exitValue != Controller.SUCCESS && + exitValue != Controller.STOPPED) { + failedMsg.append(controller.getProcessName()).append("[") + .append(exitValue).append("]").append(lineSeparator); + failures++; + } + } + + if (failures != 0) { + status = new Error(failedMsg.toString()); + } + } + + /** + * Parse the command line list after the DEBUG_STRATEGY_FLAG. The + * list should be process names separated by colons. If clients, + * servers, or the ORBD process is created and its process name is + * found in the set, it will be executed with the DebugExec strategy. + */ + private void parseDebugExecFlags() + { + String processNames = (String)getArgs().get(DEBUG_STRATEGY_FLAG); + + if (processNames != null) { + // The process names should be separated by commas + StringTokenizer tokenizer = new StringTokenizer(processNames, ":"); + + // Add the names + while (tokenizer.hasMoreTokens()) { + debugProcessNames.add(tokenizer.nextToken()); + } + } + + processNames = (String)getArgs().get(RDEBUG_STRATEGY_FLAG) ; + + if (processNames != null) { + // The process names should be separated by commas + StringTokenizer tokenizer = new StringTokenizer(processNames, ":"); + + // Add the names + while (tokenizer.hasMoreTokens()) { + rdebugProcessNames.add(tokenizer.nextToken()); + } + } + + processNames = (String)getArgs().get(ODEBUG_STRATEGY_FLAG) ; + + if (processNames != null) { + // The process names should be separated by commas + StringTokenizer tokenizer = new StringTokenizer(processNames, ":"); + + // Add the names + while (tokenizer.hasMoreTokens()) { + odebugProcessNames.add(tokenizer.nextToken()); + } + } + } + + private void parseTraceFlag() + { + String traceData = (String)getArgs().get(TRACE_FLAG) ; + if (traceData == null) { + return; + } + + // traceData should look like + // data == group ( ";" group ) * + // group == name ":" name ( "," name ) * + // name == [a-zA-Z0-9]+ + + StringTokenizer dataST = new StringTokenizer( traceData, ";" ) ; + while (dataST.hasMoreTokens()) { + String group = dataST.nextToken() ; + StringTokenizer groupST = new StringTokenizer( group, ":" ) ; + if (groupST.countTokens() != 2) { + throw new IllegalArgumentException("Bad syntax in trace command"); + } + + String name = groupST.nextToken() ; + String debugArgs = groupST.nextToken() ; + + traceMap.put( name, debugArgs ) ; + } + } + + /** + * Set of process names which will be executed with the + * DebugExec execution strategy. These are specified in + * a colon separated list after the DEBUG_STRATEGY_FLAG + * command line flag. + */ + protected HashSet debugProcessNames = new HashSet(); + + /** + * Set of process names which will be executed with the + * RDebugExec execution strategy. These are specified in + * a colon separated list after the RDEBUG_STRATEGY_FLAG + * command line flag. + */ + protected HashSet rdebugProcessNames = new HashSet(); + + /** + * Set of process names which will be executed with the + * ODebugExec execution strategy. These are specified in + * a colon separated list after the DEBUG_STRATEGY_FLAG + * command line flag. + */ + protected HashSet odebugProcessNames = new HashSet(); + + /** + * Map from controller name to com.sun.corba.ee.ORBDebug value. + * This allows setting the ORB debug flags from the test + * arguments. + */ + protected Map traceMap = new HashMap() ; + + protected List controllers = new ArrayList(); +} diff --git a/functional-tests/src/test/java/corba/framework/CORBAUtil.java b/functional-tests/src/test/java/corba/framework/CORBAUtil.java new file mode 100644 index 000000000..dbb7f4651 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/CORBAUtil.java @@ -0,0 +1,279 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; +import test.*; + +/** + * Collection of utility methods used by CORBATest and its helpers. + */ +public class CORBAUtil +{ + /** + * Create the specified directory, including any intermediate directories + * that do not exist. + * + *@return true for success, false for failure + */ + public static boolean mkdir(String name) + { + File dir = new File(name); + return dir.mkdirs(); + } + + /** + * Open/create a file with the given name in the specified directory. + * Calls openNewFile(String) with a full path created by combining + * dir and name with the File.separator. This also ensures that + * the directory exists first. + * + *@param dir Directory of the file + *@param name Name of the file + *@return OutputStream for writing to the file + *@exception FileNotFoundException Error creating the file + */ + public static OutputStream openFile(String dir, + String name) throws FileNotFoundException + { + CORBAUtil.mkdir(dir); + + return CORBAUtil.openFile(dir + File.separator + name); + } + + /** + * Open/create a file at the given full path, appending to it if it is + * already there. + * + *@param fullpath Path and name of the file + *@return OutputStream for writing to the file + *@exception FileNotFoundException Error creating the file + */ + public static OutputStream openFile(String fullpath) + throws FileNotFoundException + { + return new BufferedOutputStream(new FileOutputStream(fullpath, true)); + } + + + /** + * Convert the given Vector to a String array. Returns null if the given + * Vector is null. + * + *@param v Vector of Strings + *@return Array of Strings copied from the Vector + */ + public static String[] toArray(Vector v) + { + if (v == null) + return null; + + String[] result = new String[v.size()]; + + v.copyInto(result); + + return result; + } + + /** + * Return the package name of the given object. Sometimes + * getPackage() returns null, but Class getName() always returns + * a fully qualified package and class name. + * + *@param obj Object to examine (can't be null) + *@return String representing the package name of the object or + * the empty string if it couldn't be determined/top level + * package + */ + public static String getPackageName(Object obj) + { + String name = obj.getClass().getName(); + + int lastPeriod = name.lastIndexOf('.'); + + // Note: returns empty string rather than null + if (lastPeriod == -1) + return ""; + + return name.substring(0, lastPeriod); + } + + /** + * Combine to string arrays. Returns null if both arguments are null + * + *@param array1 First array, can be null + *@param array2 Second array, can be null + * + *@return Array with all the elements of the previous two + */ + public static String[] combine(String[] array1, + String[] array2) + { + if (array1 == null || array1.length == 0) + return array2; + else + if (array2 == null || array2.length == 0) + return array1; + + String[] result = new String[array1.length + array2.length]; + + System.arraycopy(array1, 0, + result, 0, + array1.length); + System.arraycopy(array2, 0, + result, array1.length, + array2.length); + + return result; + } + + /** + * Determines if the given Process has stopped executing. + * + *@param p Process to examine + *@return true if it has stopped, otherwise false + */ + public static boolean processFinished(Process p) + { + try { + p.exitValue(); + return true; + } catch (IllegalThreadStateException e) { + return false; + } + } + + /** + * Find the given file name in one of the provided directories, and + * return the resulting absolute path of the result. Neither the + * filename nor the directory array can be null. + * + *@param filename Name of the file to find + *@param dirs Array of directories to examine + * + *@return An absolute path represented as a String + * + *@exception FileNotFoundException Couldn't find the file in provided + * locations + */ + public static String toAbsolutePath(String filename, + String[] dirs) throws FileNotFoundException + { + filename = filename.replace('/', File.separatorChar); + String result = null; + + for (int i = 0; i < dirs.length; i++) { + File file = new File(dirs[i] + + File.separator + + filename); + + if (file.exists()) + result = file.getAbsolutePath(); + } + + // Check the current directory + if (result == null) { + File file = new File(filename); + + if (file.exists()) + result = file.getAbsolutePath(); + } + + if (result == null) + throw new FileNotFoundException(filename); + + return result; + } + + /** + * Find the given files in the given set of directories, and convert + * them to absolute paths. Neither files nor dirs can be null. + * + *@param files Array of file names to convert to absolute paths + *@param dirs Directories to search in + * + *@exception FileNotFoundException At least one requested file + * couldn't be found in the directories + * + */ + public static void toAbsolutePaths(String[] files, + String[] dirs) + throws FileNotFoundException + { + // No null check + for (int i = 0; i < files.length; i++) + files[i] = CORBAUtil.toAbsolutePath(files[i], + dirs); + } + + /** + * Compare the two files, throwing an exception if there was an error + * or a difference between them. + * + *@param filePath1 Complete path to file number one + *@param filePath2 Complete path to file number two + * + *@exception Exception Detailed exception describing the first difference + */ + public static void fileCompare(String filePath1, + String filePath2) throws Exception + { + FileReader fr1 = null, fr2 = null; + + File f1 = new File(filePath1); + if (!f1.exists()) + throw new Exception(f1.getAbsolutePath() + " does not exist!"); + File f2 = new File(filePath2); + if (!f2.exists()) + throw new Exception(f2.getAbsolutePath() + " does not exist!"); + + try { + + fr1 = new FileReader(f1); + fr2 = new FileReader(f2); + + LineNumberReader file1 = new LineNumberReader(fr1); + LineNumberReader file2 = new LineNumberReader(fr2); + + String file1line, file2line; + + do { + + file1line = file1.readLine(); + file2line = file2.readLine(); + + if (file1line == null && file2line == null) + continue; + + if (file1line == null && file2line != null) + throw new Exception(filePath1 + + " is shorter than " + filePath2); + + if (file2line == null) + throw new Exception(filePath2 + + " is shorter than " + filePath1); + + if (!file1line.equals(file2line)) + throw new Exception(filePath1 + " and " + filePath2 + + " differ on at least line: " + + file1.getLineNumber()); + + } while (file1line != null && file2line != null); + + } finally { + if (fr1 != null) + fr1.close(); + if (fr2 != null) + fr2.close(); + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/Compiler.java b/functional-tests/src/test/java/corba/framework/Compiler.java new file mode 100644 index 000000000..034191f66 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Compiler.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Vector; +import java.util.Properties ; + +/** + * Abstraction of a compiler, used to implement IDLJ, RMIC, and Javac + * wrappers. + */ +public abstract class Compiler +{ + /** + * Compile the given files according to the other parameters. + * + *@param files Array of files to compile (assumes full paths) + *@param arguments Arguments to the compiler + *@param outputDirectory Directory in which to place generated files + *@param reportDirectory Directory in which to place dump files of + * the compiler's stdout and stderr + * + *@exception Exception Error occured + * (probably bad exit value) + */ + public abstract void compile(String files[], + Vector arguments, + String outputDirectory, + String reportDirectory) throws Exception; + + /** + * Perform the compile in a separate process. It's easier to do it + * that way since the compiler's output streams can be dumped to files. + * This waits for completion or a maximum timeout (defined in Options) + * + *@param className Name of the class of the compiler + *@param progArgs Arguments to the compiler (including file names) + *@param outputDirectory Directory in which to place generated files + *@param reportDirectory Directory in which to place IO dumps + *@param compilerName Identifying name of the compiler for the IO + * files (to create "javac.err.txt", etc) + *@exception Exception Exception Error occured (probably bad exit value) + */ + protected void compileExternally(String className, + String[] progArgs, + String outputDirectory, + String reportDirectory, + String compilerName) throws Exception + { + // Make certain the directories exist + // Note: this must be done here as well as in the test harness + // in case a test (like corba.codebase) changes the output directory + // in the test itself! + CORBAUtil.mkdir(outputDirectory); + CORBAUtil.mkdir(reportDirectory); + + FileOutputDecorator exec + = new FileOutputDecorator(new ExternalExec(false)); + + Properties props = new Properties() ; + int emmaPort = EmmaControl.setCoverageProperties( props ) ; + exec.initialize(className, + compilerName, + props, + null, + progArgs, + reportDirectory + compilerName + ".out.txt", + reportDirectory + compilerName + ".err.txt", + null, + emmaPort ) ; + + exec.start(); + int result = 1; + + try { + + result = exec.waitFor(Options.getMaximumTimeout()); + + } catch (Exception e) { + exec.stop(); + throw e; + } + + if (result != Controller.SUCCESS) + throw new Exception(compilerName + + " compile failed with result: " + + result); + + exec.stop(); + } +} diff --git a/functional-tests/src/test/java/corba/framework/Controller.java b/functional-tests/src/test/java/corba/framework/Controller.java new file mode 100644 index 000000000..ca1c63e6f --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Controller.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.OutputStream; +import java.util.Properties; +import java.util.Hashtable; + +/** + * Defines the interface for interacting with a process. This is + * the base for swapping execution strategies in the framework, + * which can ultimately be used for intricate debugging (with a + * little work). + *

+ * Exit values are assumed to be as follows: + *
+ * If the process was stopped, it probably doesn't have a real exit value, + * so return STOPPED. + *
+ * SUCCESS (0) should be returned on success. + *
+ * Any non-negative integer can be returned for failure, and this value + * will be reported in the output. + */ +public interface Controller +{ + /** + * Return value indicating the process was stopped before it + * exited normally. + */ + public static final int STOPPED = -1; + + /** + * Return value indicating the process exited normally. + */ + public static final int SUCCESS = 0; + + /** + * Setup everything necessary to execute the given class. + * + *@param className Full class name to execute + *@param processName Name which identifies this process + * ("server", "ORBD", "client5", etc) + *@param environment Environment variables to provide + *@param VMArgs Arguments to the VM(can be ignored) + *@param programArgs Arguments to the class when run + *@param out Output stream to pipe stdout to + *@param err Output stream to pipe stderr to + *@param extra Strategy specific initialization extras + * + *@exception Exception Any fatal error that occured + */ + void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + OutputStream out, + OutputStream err, + Hashtable extra) throws Exception; + + /** Time between calls to start() and either waitFor completes, or + * the controller is terminated by a call to stop or kill. + * @throws IllegalStateException if the process has not been started, + * or has not yet completed. + */ + long duration() ; + + /** + * Start the process(may block). + * + *@exception Exception Any fatal error that occured + */ + void start() throws Exception; + + /** + * Stop the process. This may request the termination of the process in some + * modes, which may fail. + * + */ + void stop(); + + /** + * Kill the process. This will attempt to forcibly terminate the process. + * + */ + void kill(); + /** + * Wait for the process to finish executing. + * + *@return 0 for success, non-zero for failure + * + *@exception Exception Any fatal error that occured + */ + int waitFor() throws Exception; + + /** + * Wait for the process to finish executing, or throw an + * exception if it doesn't finished before the given timeout. + * The timeout is relative and given in milliseconds. + * + *@param timeout Number of milliseconds to wait for the + * process to finish + *@return 0 for success, non-zero for failure + * + *@exception Exception Any fatal error that occured, including + * a timeout + */ + int waitFor(long timeout) throws Exception; + + /** + * + * Return the exit value for the process. + * + *@return Process exit value, usually non-zero for failure + * + *@exception IllegalThreadStateException Process hasn't finished yet + */ + int exitValue () throws IllegalThreadStateException; + + /** + * Determine if this process has finished executing. + * + *@return true if it has finished, otherwise false + * + *@exception IllegalThreadStateException Process was never started + */ + boolean finished() throws IllegalThreadStateException; + + /** + * Return the reference to the OutputStream to which the process's + * stdout is piped. + * + *@return OutputStream where stdout is piped + */ + OutputStream getOutputStream(); + + /** + * Return the reference to the OutputStream to which the process's + * stderr is piped. + * + *@return OutputStream where stderr is piped + */ + OutputStream getErrorStream(); + + /** + * Return the class name to be executed. + */ + String getClassName(); + + /** + * Return the name of the process ("server", "client10", etc). + */ + String getProcessName(); +} diff --git a/functional-tests/src/test/java/corba/framework/ControllerAdapter.java b/functional-tests/src/test/java/corba/framework/ControllerAdapter.java new file mode 100644 index 000000000..3b178e2d0 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ControllerAdapter.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; +import test.*; + +/** + * Adapter class providing some convenient default implementations for + * the Controller interface. + */ +public abstract class ControllerAdapter implements Controller +{ + protected String className; + protected String processName; + protected Properties environment; + protected String VMArgs[]; + protected String programArgs[]; + protected OutputStream out; + protected OutputStream err; + protected Hashtable extra; + + public void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + OutputStream out, + OutputStream err, + Hashtable extra) throws Exception + { + this.className = className; + this.processName = processName; + this.environment = environment; + this.VMArgs = VMArgs; + this.programArgs = programArgs; + this.out = out; + this.err = err; + this.extra = extra; + + // Make life a little easier + if (this.environment == null) + this.environment = new Properties(); + if (this.VMArgs == null) + this.VMArgs = new String[0]; + if (this.programArgs == null) + this.programArgs = new String[0]; + } + + public OutputStream getOutputStream() + { + return out; + } + + public OutputStream getErrorStream() + { + return err; + } + + public String getProcessName() + { + return processName; + } + + public String getClassName() + { + return className; + } +} diff --git a/functional-tests/src/test/java/corba/framework/DebugExec.java b/functional-tests/src/test/java/corba/framework/DebugExec.java new file mode 100644 index 000000000..fc6c29f54 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/DebugExec.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; +import test.*; + +/** + * Debugging execution strategy. + *

+ * Defers control to the user when methods are called. The user + * is responsible for communicating with the framework and giving + * the expected responses. This allows someone to use jdb or + * another debugger in place of running a class in a separate + * process under the framework. + */ +public class DebugExec extends ExternalExec +{ + /** + * Was this process started? + */ + private boolean started = false; + + /** + * File containing the command line for JDB (erased at the + * end of the test). + */ + protected File jdbCmd = null; + + /** + * Creates the JDB command line from the normal execution + * command line. + */ + private String buildJDBCmdString(String[] command) + { + String jdb = System.getProperty("java.home") + + File.separator + + ".." + + File.separator + + "bin" + + File.separator + + "jdb"; + + StringBuffer cmd = new StringBuffer(jdb); + + for (int i = 1; i < command.length; i++) + cmd.append(' ' + command[i]); + + return cmd.toString(); + } + + /** + * Opens and truncates the JDB command line file and writes + * the command line to it. This allows people to quickly run + * JDB for this process without copy and paste. Unfortunately, + * they will have to set the execution permission on Solaris. + */ + private void writeJDBCmdFile(String cmd) throws IOException + { + // The user directory will be test/build/[OS] + String path = System.getProperty("user.dir") + + File.separator + + "jdb" + processName + ".bat"; + + jdbCmd = new File(path); + jdbCmd.delete(); + + PrintWriter out + = new PrintWriter(new OutputStreamWriter(new FileOutputStream(jdbCmd))); + + jdbCmd.deleteOnExit(); + + out.println(cmd); + out.flush(); + out.close(); + } + + + + /** + * Ask the user to start the process, providing both the JDB command line + * and a file containing it, ready to execute. + */ + public void start() + { + String[] command = buildCommand(); + + System.out.println(); + printDebugBreak(); + System.out.println("Start the " + processName + " process"); + System.out.println(); + + System.out.println("How to run the process with jdb: "); + System.out.println(); + + String jdbStr = buildJDBCmdString(command); + System.out.println(jdbStr); + System.out.println(); + + try { + writeJDBCmdFile(jdbStr); + + System.out.println("The above command was written to: " + + jdbCmd.getName()); + System.out.println("This file will be deleted when the test finishes"); + + } catch (IOException ex) { + System.out.println("Error: Command could not be written to a file"); + System.out.println(ex); + } + + System.out.println(); + + waitForEnter("Press enter when you have started the process"); + + started = true; + } + + /** + * Ask the user to stop the process. + */ + public void stop() + { + if (jdbCmd != null) { + jdbCmd.delete(); + jdbCmd = null; + } + + if (!started || exitValue != INVALID_STATE) + return; + + printDebugBreak(); + + System.out.println("The framework wants to stop the " + + processName + " process"); + + String result = promptUser("Did this process end on its own [default: No]? "); + + if (result == null || !result.toUpperCase().startsWith("Y")) { + waitForEnter("Press enter when you have killed this process"); + exitValue = STOPPED; + } else { + exitValue(); + } + } + + /** + * Inform the user that the framework is waiting for this process, and + * ask for its exit value. + */ + public int waitFor() + { + if (started) { + printDebugBreak(); + + System.out.println("The framework is waiting for the " + + processName + " process"); + } + + return exitValue(); + } + + /** + * Inform the user that the framework is waiting for this process, and + * ask for its exit value. The timeout is meaningless in this case. + */ + public int waitFor(long timeout) + { + return waitFor(); + } + + /** + * Ask the user for the exit value for this process. + * + *@return int Exit value + *@exception IllegalThreadStateException The process hasn't started + */ + public int exitValue() throws IllegalThreadStateException + { + if (!started) + throw new IllegalThreadStateException(processName + + " was never started"); + + while (exitValue == INVALID_STATE) { + printDebugBreak(); + try { + String result = promptUser("What was the exit value of the " + + processName + " process (< 1 means SUCCESS)? "); + if (result == null) + continue; + exitValue = Integer.parseInt(result); + } catch (NumberFormatException ex) { + System.out.println("That is not a valid integer. Please try again."); + } + } + + return exitValue; + } + + /** + * Is this process still running? + * + *@exception IllegalThreadStateException The process hasn't started + */ + public boolean finished() throws IllegalThreadStateException + { + if (!started) + throw new IllegalThreadStateException(processName + + " was never started"); + + return exitValue != INVALID_STATE; + } +} diff --git a/functional-tests/src/test/java/corba/framework/EmmaControl.java b/functional-tests/src/test/java/corba/framework/EmmaControl.java new file mode 100644 index 000000000..e5d62082e --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/EmmaControl.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Properties ; + +// import com.vladium.emma.ctl.ctlCommand ; + +/** Programmatic API for use in controlling emma. This is + * specific to emma version 2.1. This is intended for use + * in a test harness that execs test programs. Note that + * the execed Java program must be started with the following + * properties: + *

    + *
  • emma.rt.control true (the default) + *
  • emma.rt.control.host localhost (the default) + *
  • emma.rt.control.port somePort (defaults to 47653) + *
+ * The port should be one obtained from allocatePort, but that is + * not too important. + * Also note that if several programs are execed, each must + * have a unique port. This is yet another CORBA test framework + * feature that prevents more than one concurrent test run per + * machine. + */ +public class EmmaControl { + private EmmaControl() {} + + private static final int FIRST_PORT = 47000 ; + + private static int nextPort = FIRST_PORT ; + private static boolean DEBUG = true ; + + /** Allocate a port to be used for emma, in the writeCoverageData + * method. + */ + private synchronized static int allocatePort() { + return nextPort++ ; + } + + public synchronized static void resetPortAllocator() { + nextPort = FIRST_PORT ; + } + + public static int setCoverageProperties( Properties props ) { + // Allow for both automatic and controlled output of coverage data. + props.setProperty( "emma.coverage.out.file", Options.getEmmaFile() ) ; + props.setProperty( "emma.coverage.out.merge", "true" ) ; + props.setProperty( "emma.rt.control", "true" ) ; + props.setProperty( "emma.rt.control.host", "localhost" ) ; + int result = allocatePort() ; + props.setProperty( "emma.rt.control.port", "" + result ) ; + return result ; + } + + /** Tell emma to dump the coverage data for the process listening + * for emma command on port to the given fileName. fileName is + * interpreted on the client side and the new coverage data is + * merged into the existing file. Emma will not dump on process + * exit after this method is used. + */ + public static void writeCoverageData( int port, String fileName ) { + String[] args = new String[] { + "-connect", + "localhost:" + port, + "-command", + "coverage.dump," + fileName + ",true,true" + } ; + + /* + if (DEBUG) { + System.out.print( "Executing emma ctl command with args:" ) ; + for (String arg : args) + System.out.print( " " + arg ) ; + System.out.println() ; + } + + ctlCommand cmd = new ctlCommand( "ctl", args ) ; + cmd.run() ; + */ + + String command = "java emma ctl" ; + for (String arg : args) + command += " " + arg ; + try { + Runtime.getRuntime().exec( command ) ; + } catch (Exception exc) { + System.out.println( "Error in executing emma ctl command" + exc ) ; + exc.printStackTrace() ; + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/ExternalExec.java b/functional-tests/src/test/java/corba/framework/ExternalExec.java new file mode 100644 index 000000000..f2efe68d0 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ExternalExec.java @@ -0,0 +1,373 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; +import java.util.Properties; + +import test.ProcessMonitor; +import test.Test; + +/** + * Runs the class in a separate process. This of course assumes the class + * has a static main method, etc. Output is redirected appropriately by + * using test.ProcessMonitor. + */ +public class ExternalExec extends ControllerAdapter +{ + private long startTime = 0 ; + private long duration = 0 ; + + public long duration() { + if (startTime == 0) { + throw new IllegalStateException("Process has not yet started"); + } + + if (duration == 0) { + throw new IllegalStateException("Process has not yet completed"); + } + + return duration ; + } + + public static final String HANDSHAKE_KEY = "handshake" ; + protected String handshake = null ; + private boolean addOrbToXbootClasspath ; + + public ExternalExec( boolean addOrbToXbootClasspath ) { + this.addOrbToXbootClasspath = addOrbToXbootClasspath ; + } + + public ExternalExec() { + this( false ) ; + } + + /** + * Flag indicating that this process hasn't started, yet. + */ + public static final int INVALID_STATE = -2; + + /** + * java.lang.Process object, null when the process hasn't started + * or was stopped. + */ + protected Process process = null; + + /** + * Monitor used to redirect the process output. + */ + protected ProcessMonitor monitor; + + /** + * Exit value of the process. Will be INVALID_STATE, + * Controller.STOPPED, Controller.SUCCESS, or a positive value + * indicating failure. + */ + protected int exitValue = INVALID_STATE; + + @Override + public void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + OutputStream out, + OutputStream err, + Hashtable extra) throws Exception + { + if (extra != null) { + handshake = (String) extra.get(HANDSHAKE_KEY); + } + + super.initialize(className, + processName, + environment, + VMArgs, + programArgs, + out, + err, + extra); + + addClasspath(); + } + + /** + * Adds the class path to the current VMArgs. + */ + protected void addClasspath() + { + String[] cp = new String[] { "-classpath", + Options.getClasspath() }; + VMArgs = CORBAUtil.combine(cp, VMArgs); + + if (addOrbToXbootClasspath) { + String[] bcp = new String[] { "-Xbootclasspath/p:" + + System.getProperty( "corba.test.orb.classpath" ) } ; + VMArgs = CORBAUtil.combine(bcp, VMArgs); + } + } + + protected String[] getDebugVMArgs() + { + return new String[0] ; + } + + protected long getMaximumTimeout() + { + return Options.getMaximumTimeout() ; + } + + /** + * Create a String array with the complete command to execute, + * including the java executable path. + * + *@return Complete command line + */ + protected String[] buildCommand() + { + List cmd = new ArrayList() ; + // Command line array: + + // [java executable] + // [arguments to the java executable] + // [-D environment variables] + // [debug arguments to the java executable] + // [class name] + // [arguments to the program] + + String[] debugArgs = getDebugVMArgs() ; + + // Java executable + cmd.add( Options.getJavaExec() ) ; + cmd.addAll(Arrays.asList(VMArgs)); + + // -D environment variables + Enumeration names = environment.propertyNames(); + while(names.hasMoreElements()) { + String name = (String) names.nextElement(); + cmd.add( "-D" + name + "=" + environment.getProperty(name) ) ; + } + + cmd.add( "-Dcorba.test.process.name=" + getProcessName() ) ; + cmd.addAll(Arrays.asList(debugArgs)); + + cmd.add( className ) ; + cmd.addAll(Arrays.asList(programArgs)); + + Test.dprint("--------"); + for(String str : cmd) { + Test.dprint(str); + } + Test.dprint("--------"); + + return cmd.toArray( new String[cmd.size()] ) ; + } + + /** + * Starts the class in a separate process, redirecting output + * appropriately. This method returns when the process starts. + */ + public void start() throws Exception { + try { + startTime = System.currentTimeMillis() ; + String[] cmd = buildCommand() ; + + if (Test.forkDebugLevel >= Test.DISPLAY) { + System.out.println( + "-----------------------------------------------------------------" ) ; + System.out.println( "Current working directory: " + + System.getProperty( "user.dir" ) ) ; + System.out.println( "ExternalExec.start: Command to be executed:" ) ; + for (String str : cmd) { + System.out.println("\t" + str); + } + System.out.println( + "-----------------------------------------------------------------" ) ; + } + + process = Runtime.getRuntime().exec(cmd) ; + + if (handshake == null) { + monitor = new ProcessMonitor(process, out, err); + } else { + monitor = new ProcessMonitor(process, out, err, handshake, null); + } + + monitor.start(); + + if (handshake != null) { + monitor.waitForHandshake(getMaximumTimeout()); + } + } catch (Exception exc) { + duration = System.currentTimeMillis() - startTime ; + throw exc ; + } + } + + /** + * Destroy the process and stop piping output. + */ + private void terminate() + { + if (process != null) { + try { + exitValue = exitValue(); + } catch (IllegalThreadStateException badState) { + // Happens when the process hasn't finished + // or was never started + process.destroy(); + exitValue = STOPPED; + } + + process = null; + + try { + monitor.finishWriting(); + } catch (InterruptedException e) { + } + + duration = System.currentTimeMillis() - startTime ; + } + } + + public void stop() + { + terminate() ; + } + + public final void kill() + { + terminate() ; + } + + public int waitFor() throws InterruptedException + { + try { + exitValue = process.waitFor() ; + return exitValue ; + } catch (InterruptedException exc) { + throw exc ; + } finally { + duration = System.currentTimeMillis() - startTime ; + } + } + + public int waitFor(long timeout) throws Exception + { + long stop = System.currentTimeMillis() + timeout; + + do { + if (finished()) { + break; + } else { + Thread.sleep(100); + } + + } while (System.currentTimeMillis() < stop); + + duration = System.currentTimeMillis() - startTime ; + + if (finished()) { + exitValue = process.exitValue() ; + return exitValue ; + } else { + throw new Exception("waitFor timed out for " + getProcessName()); + } + } + + public int exitValue() throws IllegalThreadStateException + { + // Process is running or ended on its own. In the latter + // case, it will return the exit code. In the former, it + // will throw an exception. + if (process != null) { + exitValue = process.exitValue(); + process.destroy(); + process = null; + return exitValue; + } else if (exitValue == INVALID_STATE) { + // Occurs when the process hasn't been started yet + throw new IllegalThreadStateException("process hasn't started"); + } else { + return exitValue; + } + } + + public boolean finished() throws IllegalThreadStateException + { + if (process != null) { + return CORBAUtil.processFinished(process); + } + else if (exitValue == INVALID_STATE) { + throw new IllegalThreadStateException(processName + " was never started"); + } else { + return true; + } + } + + // Provide the debug print functions here so that they + // can be shared by DebugExec and RDebugExec. + + /** + * Print a line of characters to mark the start of a debug statement. + */ + protected void printDebugBreak() + { + System.out.println("====================================================="); + } + + /** + * Print the message and wait for the user to press enter. + * + *@param message Message to give the user + */ + protected void waitForEnter(String message) + { + try { + System.out.println(message); + System.in.read(); + System.in.skip(System.in.available()); + } catch (IOException ex) { + // Just return + } + } + + /** + * Print the message and prompt the user for a string response. + * + *@param message Message to give the user + *@return String The user's response + * + */ + protected String promptUser(String message) + { + System.out.print(message); + + try { + InputStreamReader isr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(isr); + + return br.readLine(); + + } catch(IOException ex) { + return null; + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/FileOutputDecorator.java b/functional-tests/src/test/java/corba/framework/FileOutputDecorator.java new file mode 100644 index 000000000..80ebadda0 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/FileOutputDecorator.java @@ -0,0 +1,225 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; + +/** + * Decorator around a Controller, allowing the user to simply specify + * file names to initialize rather than creating the streams. + * Delegates everything else. + */ +public class FileOutputDecorator implements Controller +{ + private Controller delegate; + private boolean closed = false; + private int emmaPort ; + + public FileOutputDecorator(Controller delegate) + { + this.delegate = delegate; + } + + public long duration() { + return delegate.duration() ; + } + + /** + * Setup everything necessary to execute the given class. + * + *@param className Full class name to execute + *@param processName Name identifying this process for + * output file name purposes + *@param environment Environment variables to provide + *@param VMArgs Arguments to the VM(can be ignored) + *@param programArgs Arguments to the class when run + *@param outFileName Name of file to pipe stdout to + *@param errFileName Name of file to pipe stderr to + *@param extra Strategy specific initialization extras + * + *@exception Exception Any fatal error that occured + */ + public void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + String outFileName, + String errFileName, + Hashtable extra, + int emmaPort ) throws Exception + { + OutputStream outstr = CORBAUtil.openFile(outFileName); + OutputStream errstr = CORBAUtil.openFile(errFileName); + this.emmaPort = emmaPort ; + + delegate.initialize(className, + processName, + environment, + VMArgs, + programArgs, + outstr, + errstr, + extra); + } + + public void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + OutputStream out, + OutputStream err, + Hashtable extra) throws Exception + { + // There is no reason to call this (it defeats the + // purpose of this class), but must be present. + delegate.initialize(className, + processName, + environment, + VMArgs, + programArgs, + out, + err, + extra); + } + + public void start() throws Exception + { + delegate.start(); + } + + public void stop() + { + try { + EmmaControl.writeCoverageData( emmaPort, Options.getEmmaFile() ) ; + + try { + Thread.sleep( 500 ) ; // give emma time to write out the file + // (This may not be required) + } catch (InterruptedException exc) { + // ignore this + } + + delegate.stop(); + } finally { + try { + closeStreams(); + } catch (IOException ex) { + // Ignore + } + } + } + + public void kill() + { + try { + + delegate.kill(); + + } finally { + try { + closeStreams(); + } catch (IOException ex) { + // Ignore + } + } + } + + public int waitFor() throws Exception + { + try { + + return delegate.waitFor(); + + } finally { + closeStreams(); + } + } + + public int waitFor(long timeout) throws Exception + { + try { + + return delegate.waitFor(timeout); + + } finally { + closeStreams(); + } + } + + public int exitValue() throws IllegalThreadStateException + { + return delegate.exitValue(); + } + + public boolean finished() throws IllegalThreadStateException + { + return delegate.finished(); + } + + public OutputStream getOutputStream() + { + return delegate.getOutputStream(); + } + + public OutputStream getErrorStream() + { + return delegate.getErrorStream(); + } + + public Controller getDelegate() + { + return delegate; + } + + /** + * Flushes and closes the streams. + */ + public void closeStreams() throws IOException + { + if (!closed) { + + closed = true; + + // In a recent change, the ProcessMonitor that handles + // copying of output from a java.lang.Process now + // closes the streams on its on when the process ends. + // Closing them here could lead to problems. + if (delegate instanceof corba.framework.ExternalExec) + return; + + OutputStream out = delegate.getOutputStream(); + OutputStream err = delegate.getErrorStream(); + + try { + out.flush(); + err.flush(); + } finally { + if (out != System.out) + out.close(); + if (err != System.err) + err.close(); + } + } + } + + public String getProcessName() + { + return delegate.getProcessName(); + } + + public String getClassName() + { + return delegate.getClassName(); + } +} diff --git a/functional-tests/src/test/java/corba/framework/GetID.java b/functional-tests/src/test/java/corba/framework/GetID.java new file mode 100644 index 000000000..19c7d650f --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/GetID.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +/** + * Generates unique test-ids + * + * The GetID class generates a test-ID for identifying tests in the + * log files. The ID is generated by replacing the '.'s in the + * full-qualified package name by '_'s, and then appending a user-specified + * string Id. Since, the fully qualified package name is unique across a + * test-suite, this results in unique IDs. + * + * @author Nandkumar Kesavan (nanduk@eng.sun.com) + * @version 1.1, 04/04/01 + */ +public class GetID { + + /** + * Generates a unique ID for a test from the package name and a + * user-specified id. + * + * @param o an instance of the test class + * @param id a user-specified id to be appended + * to the id generated by this method. + * Note: Usually, one would specify a string, + * representive of the test case. + * @return a unique string ID for the test + */ + public static String generateID(Object o, String id) + { + Package p = o.getClass().getPackage(); + String packageName = p.getName(); + + //Substitute all .'s with _'s. Since . are illegal in + //class or package names, they wouldn't occur anywhere + //other than as package separators. + String ID = packageName.replace('.','_'); + + //Append the non-empty user id + if (!id.equals("")) + ID = ID + "_" + id; + return ID; + } + + /** + * Generates a unique ID for a test from the class name. + * + * @param o an instance of the test class + * @return a unique string ID for the test + */ + public static String generateID(Object o) + { + Class c = o.getClass(); + String className = c.getName(); + + //Substitute all .'s with _'s. Since . are illegal in + //class or package names, they wouldn't occur anywhere + //other than as package separators. + String ID = className.replace('.','_'); + return ID; + } +} diff --git a/functional-tests/src/test/java/corba/framework/IDLCompiler.java b/functional-tests/src/test/java/corba/framework/IDLCompiler.java new file mode 100644 index 000000000..87b5359f9 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/IDLCompiler.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Vector; +import java.io.File; + +/** + * Wrapper around calling a real IDL compiler. + */ +public class IDLCompiler extends Compiler +{ + /** + * Command line option for specifying the output directory + */ + protected String OUTPUT_DIR_OPTION = "-td"; + + /** + * Default IDL compiler class name + */ + protected static final String DEFAULT_IDL_COMPILER_CLASS + = "com.sun.tools.corba.ee.idl.toJavaPortable.Compile"; + + /** + * Returns the class name of the compiler. + */ + public String compilerClassName() + { + return DEFAULT_IDL_COMPILER_CLASS; + } + + /** + * Compile the given IDL files. Files are given as absolute paths. + * The text output messages from the compile are placed in files + * named idlcompile.out.txt and idlcompile.err.txt in the + * given report directory. + * + *@param files Absolute paths to IDL files for compilation + * (can be null) + *@param arguments Command line arguments to the compiler + *@param stubDirectory Where the resulting .java files should go + *@param reportDirectory Where the output/error stream dumps should go + * + *@exception Exception Any error generated during compile or setup, + * such as abnormal termination + */ + public void compile(String files [], + Vector arguments, + String stubDirectory, + String reportDirectory) throws Exception + { + if (files == null || files.length == 0) + return; + + // Probably the right way to do this modification (which is + // specific to our compiler) would've been to subclass IDLCompiler + // and use the subclass until our compiler is better. + + // If there's only one file, use "idlcompiler" as the base of the + // name for the stdout/stderr streams files. + if (files.length == 1) { + compileHelper(files[0], + "idlcompiler", + arguments, + stubDirectory, + reportDirectory); + } else { + // Currently, our IDL compiler can only handle one file at + // a time. This means we must make multiple executions to + // get everything compiled! + for (int i = 0; i < files.length; i++) { + String fn = null; + try { + // Try to obtain the filename (without .idl) so + // that the base of the output file names will + // be idlcompiler_{filename} + File file = new File(files[i]); + String fileName = file.getName(); + int dotIndex = fileName.indexOf(".idl"); + if (dotIndex > 0) + fileName = fileName.substring(0, dotIndex); + fn = fileName; + } catch (Throwable t) { + // If something goes wrong, just make it + // idlcompiler_{file number in the sequence} + fn = "" + i; + } + + // Do the compilation for this file + compileHelper(files[i], + "idlcompiler_" + fn, + arguments, + stubDirectory, + reportDirectory); + } + } + } + + + /** + * Helper that compiles one file externally. When our IDL compiler + * supports multiple files, this can be moved back into compile + * above. + */ + private void compileHelper(String file, + String outputFileName, + Vector arguments, + String stubDirectory, + String reportDirectory) throws Exception + { + + Vector args = new Vector(1 + arguments.size() + 2); + args.add(OUTPUT_DIR_OPTION); + args.add(stubDirectory); + + if (arguments != null) + args.addAll(arguments); + + args.add(file); + + compileExternally(compilerClassName(), + CORBAUtil.toArray(args), + stubDirectory, + reportDirectory, + outputFileName); + } +} diff --git a/functional-tests/src/test/java/corba/framework/InternalExec.java b/functional-tests/src/test/java/corba/framework/InternalExec.java new file mode 100644 index 000000000..ce31b9c10 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/InternalExec.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; + +/** + * Runs the class in the current process. This assumes the class implements + * the InternalProcess interface. Also beware the natural consequences of + * running something in the current thread and process -- it won't return + * unless it does so on its own. This assumes single threaded access. + * For multi-threaded options, see ThreadExec. + * + */ +public class InternalExec extends ControllerAdapter +{ + private long startTime ; + private long duration ; + + public void start( ) throws Exception + { + startTime = System.currentTimeMillis() ; + + try { + Loader loader = new Loader(); + loader.addPath(Options.getOutputDirectory()); + + Object obj = (loader.loadClass(className)).newInstance(); + + activateObject(obj); + } finally { + duration = System.currentTimeMillis() - startTime ; + } + } + + public long duration() { + return duration ; + } + + public void stop() + { + // Can't be stopped + } + + public void kill() + { + // Can't be killed + } + + public int waitFor() throws Exception + { + return exitValue; + } + + public int waitFor(long timeout) throws Exception + { + return exitValue; + } + + public int exitValue() throws IllegalThreadStateException + { + // Just in case a subclass wants to change finished + if (!finished()) + throw new IllegalThreadStateException("not finished"); + + return exitValue; + } + + public boolean finished() throws IllegalThreadStateException + { + return true; + } + + /** + * Activate the given Object by casting it to the + * InternalProcess interface, and calling its + * run method. + */ + protected void activateObject(Object obj) + { + InternalProcess process = (InternalProcess)obj; + + PrintStream output = new PrintStream(out, true); + PrintStream errors = new PrintStream(err, true); + + try { + process.run(environment, programArgs, output, errors, extra); + } catch (Exception ex) { + ex.printStackTrace(errors); + exitValue = 1; + } + } + + /** + * Exit value of this process. + */ + protected int exitValue = Controller.SUCCESS; +} diff --git a/functional-tests/src/test/java/corba/framework/InternalProcess.java b/functional-tests/src/test/java/corba/framework/InternalProcess.java new file mode 100644 index 000000000..dc09bbd8e --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/InternalProcess.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.PrintStream; +import java.util.Properties; +import java.util.Hashtable; + +/** + * Interface representing a process which is run in the same + * process as the test framework. A class can implement this + * and be used with the InternalExec strategy. + */ +public interface InternalProcess +{ + /** + * Start the process. + * + *@param environment Environment settings (org.omg.ORBClass, etc) + *@param args Command line arguments + *@param out Standard output stream to use + *@param err Standard error stream to use + *@param extra Extra options, often used to provide + * a Controller for another process that + * this one needs to manipulate + * + *@exception Exception Any error that occurs when running + */ + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception; +} diff --git a/functional-tests/src/test/java/corba/framework/JavaCompiler.java b/functional-tests/src/test/java/corba/framework/JavaCompiler.java new file mode 100644 index 000000000..5dbb4dcdb --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/JavaCompiler.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Vector; +import java.util.StringTokenizer; + +/** + * Wrapper around calling javac. + */ +public class JavaCompiler extends Compiler +{ + private boolean newVM() + { + String version = System.getProperty( "java.version" ) ; + StringTokenizer st = new StringTokenizer( version, "." ) ; + + // Assume that version is major.minor.patch format. + // We can ignore the patch, which need not be a string + // (e.g. 1.3.1_01 is a valid version). + int major = Integer.parseInt( st.nextToken() ) ; + int minor = Integer.parseInt( st.nextToken() ) ; + + // If we ever have a 2.x.y version, it would be new. + // For now, 1.4 and greater are new VMs. + return (major > 1) || (minor > 3) ; + } + + /** + * Returns the class name of the compiler. + */ + public String compilerClassName() + { + // Break this up to avoid rename conflicts on sun tools java. + return (newVM() ? "com.sun." : "sun.") + + "tools.javac.Main" ; + } + + /** + * Compile the given .java files. Files are given as absolute paths. + * The text output messages from the compile are placed in files + * named javac.out.txt and javac.err.txt in the + * given report directory. + * + *@param files Absolute paths to .java files for compilation + * (can be null) + *@param arguments Command line arguments to the compiler + *@param outputDirectory Where the resulting .class should go + *@param reportDirectory Where the output/error stream dumps should go + * + *@exception Exception Any error generated during compile or setup, + * such as abnormal termination + */ + public void compile(String files[], + Vector arguments, + String outputDirectory, + String reportDirectory) throws Exception + { + if (files == null || files.length == 0) + return; + + Vector args = new Vector(5 + (arguments == null ? 0 : arguments.size()) + files.length); + args.add("-g"); + args.add("-d"); + args.add(outputDirectory); + // args.add("-bootclasspath"); + // args.add(Options.getClasspath()); + args.add( "-Xbootclasspath/p:" + + System.getProperty( "corba.test.orb.classpath" ) ) ; + + if (arguments != null) + args.addAll(arguments); + + for(int i = 0; i < files.length; i++) + args.add(files[i]); + + compileExternally(compilerClassName(), + CORBAUtil.toArray(args), + outputDirectory, + reportDirectory, + "javac"); + } +} diff --git a/functional-tests/src/test/java/corba/framework/Loader.java b/functional-tests/src/test/java/corba/framework/Loader.java new file mode 100644 index 000000000..96be4f570 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Loader.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; + +/** + * Allows extra paths to be specified when searching for classes. This + * gets around the security restriction of changing the classpath within + * the program. Also, even if there isn't a security restriction, I + * think the default ClassLoader only does a getProperty once for the + * value, so changing it is useless. + *

+ * This is currently only used by Internal and ThreadExec, which execute the + * class in the current process. For the external processes, the + * classpath is augmented on the command line to include the output + * directory. + *

+ * This follows the delegation model for class loading: If the class has + * already been loaded, it returns it. Next, the system loader is tried. + * Finally, if the system loader fails, the extra paths are searched. + */ +public class Loader extends ClassLoader +{ + + /** + * Vector of extra paths to search. + */ + private Vector extraPaths = new Vector(10); + + /** + * + * Default constructor. + * + */ + public Loader() + { + } + + /** + * Constructor allowing a Vector of search paths to be specified. + * + *@param paths Extra paths to search when loading classes + * + */ + public Loader(Vector paths) + { + extraPaths = paths; + } + + /** + * Add another path to search when loading classes. + * + *@param path New path to search + */ + public void addPath(String path) + { + extraPaths.add(path); + } + + /** + * Try to load the specified class using the extra paths. This is + * called by the parent loader once it has tried all other means + * (such as checking for it being loaded, or using the system loader). + * + *@param name name of the class to load + *@exception ClassNotFoundException couldn't find the class + *@return loaded Class instance + */ + protected Class findClass(String name) throws ClassNotFoundException + { + byte[] b = loadClassData(name); + return defineClass(name, b, 0, b.length); + } + + /** + * Find the class by searching the extra paths, and read it into + * a byte array. + * + *@param className Fully qualified class name + *@return byte array containing the contents of the class file + *@exception ClassNotFoundException error loading the class + */ + private byte[] loadClassData(String className) + throws ClassNotFoundException + { + byte data[] = null; + + // Build the file name and subdirectory from the + // class name + String filename = className.replace('.', File.separatorChar) + + ".class"; + + Enumeration paths = extraPaths.elements(); + + // Search the extra paths + while (paths.hasMoreElements() && data == null) { + + File file = new File((String)paths.nextElement() + + File.separator + + filename); + + if (!file.exists()) + continue; + + try { + + // Found the file, so open it for reading + FileInputStream in = new FileInputStream(file); + + // Protect against data loss (shouldn't happen) + if (file.length() > Integer.MAX_VALUE) + throw new IOException (className + + " exceeds max length"); + + data = new byte[(int)file.length()]; + + // Read in the file contents + if (in.read(data) != data.length) + throw new IOException ("Lost data when loading " + + className); + + in.close(); + + } catch (Exception ex) { + throw new ClassNotFoundException(className, ex); + } + } + + if (data == null) + throw new ClassNotFoundException(className); + + return data; + } +} + + diff --git a/functional-tests/src/test/java/corba/framework/MethodEvent.java b/functional-tests/src/test/java/corba/framework/MethodEvent.java new file mode 100644 index 000000000..50c0c2b87 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/MethodEvent.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.lang.reflect.Method ; +import java.util.EventObject ; + +/** An event representing entering or exiting a particular method + * on a particular thread, as recorded by an interceptor with a + * particular id. + */ +public class MethodEvent +{ + private String threadId ; + private String id ; + private Method method ; + + public static MethodEvent make( String id, Method method ) + { + return new MethodEvent( id, method ) ; + } + + private MethodEvent( String id, Method method ) + { + this.threadId = Thread.currentThread().toString() ; + this.id = id ; + this.method = method ; + } + + public String getThreadId() { return threadId ; } + + public String getId() { return id ; } + + public Method getMethod() { return method ; } + + public boolean equals( Object obj ) + { + if (!(obj instanceof MethodEvent)) + return false ; + + MethodEvent other = (MethodEvent)obj ; + + return (id.equals( other.id ) && + method.equals( other.method )) ; + } + + public int hashCode() + { + return id.hashCode() ^ method.hashCode() ; + } + + public String toString() + { + return "MethodEvent[threadId=" + threadId + " id=" + id + + " method=" + method + "]" ; + } +} diff --git a/functional-tests/src/test/java/corba/framework/MethodEventListener.java b/functional-tests/src/test/java/corba/framework/MethodEventListener.java new file mode 100644 index 000000000..461eac5fb --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/MethodEventListener.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +/** A listener for MethodEvent objects. Is notified of both method entry + * and method exit. + */ +public interface MethodEventListener +{ + void methodEntered( MethodEvent event ) ; + + void methodExited( MethodEvent event ) ; +} diff --git a/functional-tests/src/test/java/corba/framework/ODebugExec.java b/functional-tests/src/test/java/corba/framework/ODebugExec.java new file mode 100644 index 000000000..97ccc4c45 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ODebugExec.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; +import test.*; + +/** + * Runs the class in a separate process using the JPDA options so that it can be + * remotely debugged. This of course assumes the class + * has a static main method, etc. Output is redirected appropriately by + * using test.ProcessMonitor. + */ +public class ODebugExec extends ExternalExec +{ + public void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + OutputStream out, + OutputStream err, + Hashtable extra) throws Exception + { + super.initialize(className, + processName, + environment, + VMArgs, + programArgs, + System.out, + err, + extra); + } + + protected String[] getDebugVMArgs() + { + String sourcepath = System.getProperty( "com.sun.corba.ee.test.sourcepath" ) ; + String[] result = { "com.lambda.Debugger.Debugger", "sourcepath", + sourcepath } ; + + return result ; + } ; + + public int waitFor(long timeout) throws Exception + { + // We don't want to set a timeout while debugging + return waitFor() ; + } + + public void start() throws Exception + { + System.out.println( "Starting process " + processName + " in remote debug mode" ) ; + super.start() ; + Object waiter = new Object() ; + synchronized (waiter) { + waiter.wait( 5000 ) ; + } + } + + public void stop() + { + // we don't want to stop; just tell the user and let them + // tell us when to stop + + printDebugBreak(); + + System.out.println("The framework wants to stop the " + + processName + " process"); + + waitForEnter("Press enter to terminate the process"); + + exitValue(); + } +} diff --git a/functional-tests/src/test/java/corba/framework/Options.java b/functional-tests/src/test/java/corba/framework/Options.java new file mode 100644 index 000000000..a1b5247f4 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Options.java @@ -0,0 +1,548 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.JndiConstants; +import test.Util; + +import java.io.File; +import java.io.IOException; +import java.util.Hashtable; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.Vector; + +/** Static library class to provide access to test configuration data. + * This thing need to be further re-written to a class that is instantiated, + * instead of the current static approach. It should set up the defaults from + * system properties and arguments to the constructor in the constructor. + * It should provide setters and getters as needed for the tests. + * Note that all setters must update all data, especially including the + * properties returned from getORBDProperties, getClientProperties, and getServerProperties. + */ +public class Options { + // Prevent normal instantiation + private Options() { } + + public static final String defORBDHandshake = "ORBD is ready."; + public static final String defServerHandshake = "Server is ready."; + + // Port related: + private static Port orbInitialPort; + private static Port activationPort; + + private static String javaIDLHome; + private static String activationDbDirName; // NO key defActivationDbDirName + private static String classpath; // key java.class.path + private static String orbClass; // key org.omg.CORBA.ORBClass + + private static Vector orbdArgs ; + private static Vector serverArgs ; + private static Vector clientArgs ; + + // Extra execution strategy arguments + private static Hashtable orbdExtra ; + private static Hashtable serverExtra ; + private static Hashtable clientExtra ; + + // Extra arguments to compilers + private static Vector rmicArgs ; + private static Vector idlCompilerArgs ; + private static Vector javacArgs ; + + // environment properties + private static Properties defaultProperties ; + private static Properties ORBDProps ; + private static Properties serverProps ; + private static Properties clientProps ; + + private static String emmaFile; + + // Note: Directories must have the file separator already appended + // to the end + private static String testDirectory; + private static String reportDirectory; + private static String outputDirectory; + + // Files for compilation + private static String[] javaFiles = null ; + private static String[] idlFiles = null ; + private static String[] rmicFiles = null ; + + private static void initializeDefaults( Properties props ) { + // Initialize default properties from the system properties. + for (String key : Util.PROCESS_PROPERTIES) { + String value = System.getProperty( key ) ; + if (value != null) + props.setProperty( key, value ) ; + } + + String prop = props.getProperty(ORBConstants.INITIAL_PORT_PROPERTY); + if (prop == null) + orbInitialPort = new Port(); + else + orbInitialPort = new Port(Integer.parseInt(prop)); + props.setProperty( ORBConstants.INITIAL_PORT_PROPERTY, orbInitialPort.toString() ) ; + + prop = props.getProperty(ORBConstants.ORBD_PORT_PROPERTY); + if (prop == null) + activationPort = new Port(); + else + activationPort = new Port(Integer.parseInt(prop)); + + emmaFile = props.getProperty("emma.coverage.out.file", "") ; + orbClass = props.getProperty("org.omg.CORBA.ORBClass", "com.sun.corba.ee.impl.orb.ORBImpl" ); + + props.setProperty( "java.naming.factory.initial", JndiConstants.COSNAMING_CONTEXT_FACTORY ) ; + } + + private static String getPackageAsDir( CORBATest parent ) { + String packageName = CORBAUtil.getPackageName(parent); + String pkg = packageName.replace('.', File.separatorChar); + return pkg ; + } + + private static String getTestDirectory( CORBATest parent ) { + String testBase = (String)(parent.getArgs().get( "-testbase" )) ; + String testRoot = "" ; + + if (testBase == null) { + testRoot = "/../src/share/classes/"; + testBase = System.getProperty( "user.dir" ) ; + } else { + testRoot = "/src/share/classes/"; + } + + String result = testBase + testRoot.replace('/', File.separatorChar) + + getPackageAsDir( parent ) + File.separator; + return result ; + } + + /** + * Initialize the options. This should be called by the + * test framework, not individual tests. It should be called + * before each new test runs to reset everything. + * + *@param parent The current test + */ + public static void init(CORBATest parent) throws IOException + { + serverArgs = new Vector(10); + clientArgs = new Vector(10); + + orbdExtra = new Hashtable(10); + serverExtra = new Hashtable(10); + clientExtra = new Hashtable(10); + + orbdExtra.put(ExternalExec.HANDSHAKE_KEY, defORBDHandshake); + serverExtra.put(ExternalExec.HANDSHAKE_KEY, defServerHandshake); + + rmicArgs = new Vector(10); + idlCompilerArgs = new Vector(10); + javacArgs = new Vector(10); + + javaFiles = null ; + idlFiles = null ; + rmicFiles = null ; + + defaultProperties = new Properties() ; + initializeDefaults( defaultProperties ) ; + + setORBDArgs( "-ORBDebug orbd" ) ; + + testDirectory = getTestDirectory( parent ) ; + + String defaultOutputDirectory = parent.getArgs().get(test.Test.OUTPUT_DIRECTORY) + + File.separator + getPackageAsDir(parent) + File.separator; + + setDirectories( defaultOutputDirectory, defaultProperties ) ; + + // Set up props based on default properties. The props may be further modified in the tests. + ORBDProps = new Properties( defaultProperties ) ; + ORBDProps.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, getActivationPort() ) ; + + String persistentServerId = defaultProperties.getProperty(ORBConstants.ORB_SERVER_ID_PROPERTY, "1"); + ORBDProps.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, persistentServerId ) ; + + serverProps = new Properties( defaultProperties ) ; + clientProps = new Properties( defaultProperties ) ; + } + + // Set directories and classpath parts that depend on outputdir. + private static void setDirectories( String outdir, Properties props ) { + outputDirectory = outdir ; + reportDirectory = outdir ; + props.setProperty( "output.dir", outdir ) ; + + javaIDLHome = outdir + "JavaIDLHome" ; + props.setProperty( "com.sun.corba.ee.JavaIDLHome", javaIDLHome ) ; + + activationDbDirName = javaIDLHome + File.separator + "db.dir" ; + props.setProperty( ORBConstants.DB_DIR_PROPERTY, activationDbDirName ) ; + + StringBuffer newPath = new StringBuffer(outputDirectory + File.pathSeparator); + newPath.append(System.getProperty("java.class.path")); + classpath = newPath.toString(); + } + + public static long getMaximumTimeout() { + return 120000 ; + } + + /** + * Returns the JavaIDLHome directory path (defaults to + * output directory/JavaIDLHome). + */ + public static String getJavaIDLHome() { + return javaIDLHome; + } + + /** + * Get the ORB initial port value (defaults to 1050 unless an + * environment variable called "org.omg.CORBA.ORBInitialPort" + * was found). + */ + public static String getORBInitialPort() { + return orbInitialPort.toString(); + } + + /** + * Get the activation port value (defaults to 1049 unless an + * environment variable called "ActivationPort" was found). + */ + public static String getActivationPort() { + return activationPort.toString(); + } + + /** + * Get argument vector passed to ORBD (initially -ORBDebug orbd). + */ + public static Vector getORBDArgs() { + return orbdArgs; + } + + /** + * Add a number of command line arguments for the + * ORBD (space separated). + */ + public static void setORBDArgs(String values) { + orbdArgs = new Vector() ; + Options.addArgsFromString(values, orbdArgs); + } + + /** + * Get argument vector passed to a server (default is + * no arguments). + */ + public static Vector getServerArgs() { + return serverArgs; + } + + /** + * Add one command line argument for the server. + */ + public static void addServerArg(String value) { + serverArgs.add(value); + } + + /** + * Add a number of command line arguments for the + * server (space separated). + */ + public static void addServerArgs(String values) { + Options.addArgsFromString(values, serverArgs); + } + + /** + * Get argument vector passed to a client (default is + * no arguments). + */ + public static Vector getClientArgs() { + return clientArgs; + } + + /** + * Add one command line argument for the client. + */ + public static void addClientArg(String value) { + clientArgs.add(value); + } + + /** + * Add a number of command line arguments for the + * client (space separated). + */ + public static void addClientArgs(String values) { + Options.addArgsFromString(values, clientArgs); + } + + /** + * Return the test's home directory (where it's source + * files are located. Defaults to + * ../src/share/classes/{package}/ since the current + * directory is assumed to be ../test/make). + */ + public static String getTestDirectory() { + return testDirectory; + } + + /** + * Return the test's report directory (defaults to + * the output directory). This is where output files such + * as javac.err.txt and javac.out.txt will go. + */ + public static String getReportDirectory() { + return reportDirectory; + } + + /** + * Return the test's output directory (defaults to + * {output dir from command line}/{package}/). + */ + public static String getOutputDirectory() { + return outputDirectory; + } + + /** + * Set the output directory -- disallowed. + */ + public static void setOutputDirectory(String value) { + setDirectories( value, defaultProperties ) ; + } + + /** + * Return the class path to pass to subprocesses + * (defaults to the system property java.class.path + * plus the output directory). + */ + public static String getClasspath() { + return classpath; + } + + /** + * Set the class path which will be given to + * subprocesses. (Note: This does not affect the + * classpath of the current process) + */ + public static void setClasspath(String value) { + classpath = value; + } + + /** + * Get the ORB class name (defaults to the IIOP ORB). + */ + public static String getORBClass() { + return orbClass; + } + + /** + * Get a hashtable of extra flags to give to the ORBD + * execution strategy. + */ + public static Hashtable getORBDExtra() { + return orbdExtra; + } + + /** + * Get a hashtable of extra flags to give to server + * execution strategies. + */ + public static Hashtable getServerExtra() { + return serverExtra; + } + + /** + * Get a hashtable of extra flags to give to client + * execution strategies. + */ + public static Hashtable getClientExtra() { + return clientExtra; + } + + /** + * The framework already provides many properties to + * ORBD, but this allows the test author to override + * or augment them. + */ + public static Properties getORBDProperties() { + return ORBDProps; + } + + /** + * The framework already provides many properties to + * a server, but this allows the test author to override + * or augment them. + */ + public static Properties getServerProperties() { + return serverProps; + } + + /** + * The framework already provides many properties to + * a client, but this allows the test author to override + * or augment them. + */ + public static Properties getClientProperties() { + return clientProps; + } + + /** + * Get the string for the java executable to use + * when creating subprocesses. Set to + * {java.home}/bin/java). + */ + public static String getJavaExec() { return System.getProperty("java.home") + + File.separator + "bin" + File.separator + "java"; + } + + /** + * Returns a vector of arguments to the Java compiler. + */ + public static Vector getJavacArgs() { + return javacArgs; + } + + /** + * Add one argument to the vector of Java compiler args. + */ + public static void addJavacArg(String value) { + javacArgs.add(value); + } + + /** + * Add a number of arguments to the vector of Java compiler + * args (space separated). + */ + public static void addJavacArgs(String values) { + Options.addArgsFromString(values, javacArgs); + } + + /** + * Returns a vector of arguments to RMIC. + */ + public static Vector getRMICArgs() { + return rmicArgs; + } + + /** + * Add one argument to the vector of RMIC args. + */ + public static void addRMICArg(String value) { + rmicArgs.add(value); + } + + /** + * Add a number of arguments to the vector of RMIC args + * (space separated). + */ + public static void addRMICArgs(String values) { + Options.addArgsFromString(values, rmicArgs); + } + + /** + * Returns a vector of arguments to the IDL compiler. + */ + public static Vector getIDLCompilerArgs() { + return idlCompilerArgs; + } + + /** + * Add one argument to the vector of IDL compiler args. + */ + public static void addIDLCompilerArg(String value) { + idlCompilerArgs.add(value); + } + + /** + * Add a number of arguments to the vector of IDL compiler + * args(space separated). + */ + public static void addIDLCompilerArgs(String values) { + Options.addArgsFromString(values, idlCompilerArgs); + } + + /** + * Utility method for adding space separated arguments to + * a given vector. + */ + private static void addArgsFromString(String args, Vector container) + { + StringTokenizer st = new StringTokenizer(args); + + while (st.hasMoreTokens()) { + String arg = st.nextToken(); + container.add(arg); + } + } + + /** + * Set the array of fully qualified class names to + * give to RMIC. + */ + public static void setRMICClasses(String[] value) { + rmicFiles = value; + } + + /** + * Get the array of fully qualified class names that + * will be given to RMIC. + */ + public static String[] getRMICClasses() { + return rmicFiles; + } + + /** + * Set the array of .java file names to give to javac + * (note: any one of these can be either a full path + * or a file name in the test directory, but must + * end in .java). + */ + public static void setJavaFiles(String[] value) { + javaFiles = value; + } + + /** + * Get the array of .java file names that will be + * given to javac. + */ + public static String[] getJavaFiles() { + return javaFiles; + } + + /** + * Set the array of .idl file names to give to idlj + * (note: any one of these can be either a full path + * or a file name in the test directory). + */ + public static void setIDLFiles(String[] value) { + idlFiles = value; + } + + /** + * Get the array of IDL file names that will be + * given to idlj. + */ + public static String[] getIDLFiles() { + return idlFiles; + } + + public static String getEmmaFile() { + return emmaFile ; + } + + /** + * Create and return an abstraction for an unused port. + */ + public static Port getUnusedPort() { + return new Port(); + } +} diff --git a/functional-tests/src/test/java/corba/framework/PRO.java b/functional-tests/src/test/java/corba/framework/PRO.java new file mode 100644 index 000000000..f83078c5f --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/PRO.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.rmi.Remote ; + +import javax.rmi.PortableRemoteObject ; + +public class PRO { + private PRO() {} + + public static T narrow( Object obj, Class cls ) { + return cls.cast( PortableRemoteObject.narrow( + obj, cls ) ) ; + } + + public static T toStub( Remote obj, Class cls ) { + try { + return cls.cast( PortableRemoteObject.toStub( + obj ) ) ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/Port.java b/functional-tests/src/test/java/corba/framework/Port.java new file mode 100644 index 000000000..d44f0ee9c --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Port.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.net.*; + +/** + * Simple port abstraction with the capability of + * late binding to an unused port. + */ +public class Port +{ + public static class PortException extends RuntimeException { + public PortException(String reason) { + super(reason); + } + } + + private static final int UNBOUND = 0; + private int port = Port.UNBOUND; + + /** + * Port will late bind to an unused port when + * getValue or toString is called. + */ + public Port() {} + + + /** + * Will use the provided port value when + * getValue or toString is called. + */ + public Port(int value) { + port = value; + } + + public int getValue() { + bind(); + + return port; + } + + public String toString() { + return String.valueOf(getValue()); + } + + /** + * Is this port available for use? + */ + public boolean isFree() { + bind(); + + return Port.isFree(port); + } + + /** + * If the port is unbound, find an unused and + * set our instance variable to it. + */ + private int bind() { + if (port == Port.UNBOUND) { + + try { + ServerSocket socket = new ServerSocket(0); + + port = socket.getLocalPort(); + + socket.close(); + } catch (IOException ex) { + throw new PortException(ex.getMessage()); + } + } + + return port; + } + + /** + * Determine if the provided port is unused. Tries to + * create a ServerSocket at the given port. + * + *@param port Port to test + *@return true if port is unused + */ + public static boolean isFree(int port) { + boolean result = false; + try { + ServerSocket ssocket = new ServerSocket(port); + + ssocket.close(); + + return true; + + } catch (IOException ex) { + return false; + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/Post.java b/functional-tests/src/test/java/corba/framework/Post.java new file mode 100644 index 000000000..19017fa1f --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Post.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.lang.annotation.Target ; +import java.lang.annotation.Documented ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** Used to mark methods that are executed after every test case + * + * @author ken + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Post { +} diff --git a/functional-tests/src/test/java/corba/framework/Pre.java b/functional-tests/src/test/java/corba/framework/Pre.java new file mode 100644 index 000000000..b746529e0 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/Pre.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.lang.annotation.Target ; +import java.lang.annotation.Documented ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** Used to mark methods executed before each test case. + * + * @author ken + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Pre { + +} diff --git a/functional-tests/src/test/java/corba/framework/ProxyInterceptor.java b/functional-tests/src/test/java/corba/framework/ProxyInterceptor.java new file mode 100644 index 000000000..464769832 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ProxyInterceptor.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.util.Iterator ; +import java.util.Set ; +import java.util.HashSet ; +import java.lang.reflect.Method ; +import java.lang.reflect.Proxy ; +import java.lang.reflect.InvocationHandler ; +import java.lang.reflect.InvocationTargetException ; + +import corba.framework.MethodEvent ; +import corba.framework.MethodEventListener ; + +/** Create an interceptor that reports method entry and exit for a + * certain set of methods. Method entry and exit is reported as + * a MethodEvent to all registered MethodEventListeners. + *

+ * For example, suppose that we want to trace all calls to + * Resolver.list and Resolver.resolve. This could be done as follows, + * inside a user defined ORB Configurator: + *

+ * // Create the proxy resolver, and plug it into the ORB.
+ * Resolver resolver = orb.getResolver() ;
+ * ProxyInterceptor proxy = ProxyInterceptor.make( "ResolverInterceptor",
+ *     new Class[] { Resolver.class }, resolver ) ;
+ * orb.setResolver( (Resolver)proxy.getActual() ) ;
+ *
+ * // Register the methods we want to monitor
+ * Class cls = Resolver.class ;
+ * Method resolveMethod = cls.getMethod( "resolve", 
+ *     new Class[] { String.class } ) ;
+ * Method listMethod = cls.getMethod( "list", null ) ;
+ * proxy.addMethod( resolveMethod ) ;
+ * proxy.addMethod( listMethod ) ;
+ *
+ * // Add the test listener
+ * proxy.addListener( traceAccumulator ) ;
+ * 
+ *

+ * Later, we just do traceAccumulator.validate( seq ), where + * seq is the expected sequence of entry/exit events. + */ +public class ProxyInterceptor { + private final String id ; // The id for this interceptor + private final Set methods ; // Set + private final Set listeners ; // Set + private final Object target ; // The actual target + private final Object actual ; // The proxy that forwards requests + // to target + + private class MyHandler implements InvocationHandler + { + private void broadcastEnter( MethodEvent mev ) + { + Iterator iter = listeners.iterator() ; + while (iter.hasNext()) { + MethodEventListener listener = + (MethodEventListener)(iter.next()) ; + listener.methodEntered( mev ) ; + } + } + + private void broadcastExit( MethodEvent mev ) + { + Iterator iter = listeners.iterator() ; + while (iter.hasNext()) { + MethodEventListener listener = + (MethodEventListener)(iter.next()) ; + listener.methodExited( mev ) ; + } + } + + private Object invokeMethod( Method method, Object target, + Object[] args ) + { + try { + return method.invoke( target, args ) ; + } catch (IllegalAccessException exc) { + throw new RuntimeException( + "Illegal access exception on method " + method, exc ) ; + } catch (IllegalArgumentException exc) { + throw new RuntimeException( + "Illegal argument exception on method " + method, exc ) ; + } catch (InvocationTargetException exc) { + throw new RuntimeException( + "Invocation target exception on method " + method, exc ) ; + } + } + + public synchronized Object invoke( Object proxy, Method method, + Object[] args ) + { + if (methods.contains( method )) { + MethodEvent mev = MethodEvent.make( id, method ) ; + try { + broadcastEnter( mev ) ; + return invokeMethod( method, target, args ) ; + } finally { + broadcastExit( mev ) ; + } + } else + return invokeMethod( method, target, args ) ; + } + } + + /** Create a ProxyInterceptor for the given classes. + * Each Class in intf must be an interface. + * The id string is used to identify which ProxyInterceptor this + * is. + */ + public static ProxyInterceptor make( String id, Class[] intf, + Object target ) + { + return new ProxyInterceptor( id, intf, target ) ; + } + + private ProxyInterceptor( String id, Class[] intf, Object target ) + { + this.id = id ; + methods = new HashSet() ; + listeners = new HashSet() ; + this.target = target ; + InvocationHandler ih = new MyHandler() ; + actual = Proxy.newProxyInstance( intf[0].getClassLoader(), + intf, ih ) ; + } + + /** Add method to the list of methods that are reported to the + * listeners. + */ + public synchronized void addMethod( Method method ) + { + methods.add( method ) ; + } + + /** Remote method from the list of methods that are reported to the + * listeners. + */ + public synchronized void removeMethod( Method method ) + { + methods.remove( method ) ; + } + + /** Return the list of methods are reported to the listeners. + */ + public synchronized Method[] getMethods() + { + return (Method[])methods.toArray( new Method[0] ) ; + } + + /** Add listener to the list of listeners for + * method entry and exit events. + */ + public synchronized void addListener( MethodEventListener listener ) + { + listeners.add( listener ) ; + } + + /** Remove listener from the list of listeners for + * method entry and exit events. + */ + public synchronized void removeListener( MethodEventListener listener ) + { + listeners.remove( listener ) ; + } + + /** Return the list of listeners for + * method entry and exit events. + */ + public synchronized MethodEventListener[] getListeners() + { + return (MethodEventListener[])listeners.toArray( + new MethodEventListener[0] ) ; + } + + /** Return the actual object to use. This object simply + * forwards all method invocations to the target, reporting + * method entry and exit for registered methods to all + * registered listeners. + */ + public synchronized Object getActual() + { + return actual ; + } +} diff --git a/functional-tests/src/test/java/corba/framework/RDebugExec.java b/functional-tests/src/test/java/corba/framework/RDebugExec.java new file mode 100644 index 000000000..ecc406c3f --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/RDebugExec.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; +import java.util.*; +import test.*; + +/** + * Runs the class in a separate process using the JPDA options so that it can be + * remotely debugged. This of course assumes the class + * has a static main method, etc. Output is redirected appropriately by + * using test.ProcessMonitor. + */ +public class RDebugExec extends ExternalExec +{ + public void initialize(String className, + String processName, + Properties environment, + String VMArgs[], + String programArgs[], + OutputStream out, + OutputStream err, + Hashtable extra) throws Exception + { + super.initialize(className, + processName, + environment, + VMArgs, + programArgs, + System.out, + err, + extra); + } + + protected String[] getDebugVMArgs() + { + String[] result = { "-Xdebug", "-Xnoagent", + "-Xrunjdwp:transport=dt_socket,server=y,suspend=y" } ; + + return result ; + } ; + + // Don't timeout while debugging + protected long getMaximumTimeout() + { + return 0 ; + } + + public int waitFor(long timeout) throws Exception + { + // We don't want to set a timeout while debugging + return waitFor() ; + } + + public void start() throws Exception + { + System.out.println( "Starting process " + processName + " in remote debug mode" ) ; + super.start() ; + Object waiter = new Object() ; + synchronized (waiter) { + waiter.wait( 5000 ) ; + } + } + + public void stop() + { + // we don't want to stop; just tell the user and let them + // tell us when to stop + + printDebugBreak(); + + System.out.println("The framework wants to stop the " + + processName + " process"); + + waitForEnter("Press enter to terminate the process"); + + kill(); + } +} diff --git a/functional-tests/src/test/java/corba/framework/RMICompiler.java b/functional-tests/src/test/java/corba/framework/RMICompiler.java new file mode 100644 index 000000000..659cf75ee --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/RMICompiler.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Vector; + +/** + * Wrapper around calling a real RMIC. + */ +public class RMICompiler extends Compiler +{ + /** + * Command line option for specifying the output directory + */ + protected String OUTPUT_DIR_OPTION = "-d"; + + /** + * Default RMIC class name + */ + protected static final String DEFAULT_RMIC_CLASS + = "sun.rmi.rmic.Main"; + + /** + * Returns the class name of the compiler. + */ + public String compilerClassName() + { + return DEFAULT_RMIC_CLASS; + } + + /** + * Compile the given class files. Files are given as absolute paths. + * The text output messages from the compile are placed in files + * named rmic.out.txt and rmic.err.txt in the + * given report directory. + * + *@param files Absolute paths to class files for compilation + * (can be null) + *@param arguments Command line arguments to the compiler + *@param outputDirectory Where the resulting files should go + *@param reportDirectory Where the output/error stream dumps should go + * + *@exception Exception Any error generated during compile or setup, + * such as abnormal termination + */ + public void compile(String files [], + Vector arguments, + String outputDirectory, + String reportDirectory) throws Exception + { + if (files == null || files.length == 0) + return; + + Vector args = new Vector(files.length + arguments.size() + 4); + args.add(OUTPUT_DIR_OPTION); + args.add(outputDirectory); + args.add("-classpath"); + args.add(Options.getClasspath()); + + if (arguments != null) + args.addAll(arguments); + + for(int i = 0; i < files.length; i++) + args.add(files[i]); + + compileExternally(compilerClassName(), + CORBAUtil.toArray(args), + outputDirectory, + reportDirectory, + "rmic"); + } +} diff --git a/functional-tests/src/test/java/corba/framework/RTMConstants.java b/functional-tests/src/test/java/corba/framework/RTMConstants.java new file mode 100644 index 000000000..43f18c012 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/RTMConstants.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +public class RTMConstants { + public static final int PASS = 1; + public static final int FAIL = 2; + + public static final String SERVER_READY = new String("Server is ready." ) ; + + public static final int AND = 3; + public static final int OR = 4; +} + + diff --git a/functional-tests/src/test/java/corba/framework/RTMUtilities.java b/functional-tests/src/test/java/corba/framework/RTMUtilities.java new file mode 100644 index 000000000..3096bfee4 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/RTMUtilities.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +// RTMUtilities class contains routines that are common to use for all RTM +// tests +public class RTMUtilities { + + private static boolean isOnTheList(String current, String list) { + if (current != null && list != null) { + if (list.indexOf(current) == -1) + return false; // Not on the list + else + return true; // on the list + } else + return false; // either property isn't provided + } + + // Return "true" if "current" argument is NOT in the "notRunOnList" argument + public static boolean isValidToRun(String current, String notRunOnList) { + String currentProperty = System.getProperty(current); + String notRunOnListProperty = System.getProperty(notRunOnList); + return (!RTMUtilities.isOnTheList(currentProperty, notRunOnListProperty)); + } + + // Return "true" if "EXEC_ENV" property is NOT in the "RELEASE_NOT_RUN_ON" + // property + public static boolean isValidToRun() { + // Get the build release that this test suite is currently running on + String currentRelease = System.getProperty("EXEC_ENV"); + // Get the list of release that certain test scenario should NOT be + // run on + String doNotRunOnReleaseList = System.getProperty("RELEASE_NOT_RUN_ON"); + return (!RTMUtilities.isOnTheList(currentRelease, doNotRunOnReleaseList)); + } + +} diff --git a/functional-tests/src/test/java/corba/framework/ReflectiveExec.java b/functional-tests/src/test/java/corba/framework/ReflectiveExec.java new file mode 100644 index 000000000..f8ae38674 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ReflectiveExec.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Enumeration; + +import test.Test; + +public class ReflectiveExec extends ExternalExec { + protected String[] buildCommand() + { + // Command line array: + + // [java executable] + // [arguments to the java executable] + // [-D environment variables] + // [debug arguments to the java executable] + // corba.framwork.ReflectiveWrapper + // [class name] + // [arguments to the program] + + String[] debugArgs = getDebugVMArgs() ; + + int size = 2 + debugArgs.length + VMArgs.length + + environment.size() + programArgs.length + 1; + + String cmd [] = new String [size]; + + int idx = 0; + // Java executable + cmd[idx++] = Options.getJavaExec(); + + // Arguments to the java executable + for(int i = 0; i < VMArgs.length; i++) + cmd[idx++] = VMArgs[i]; + + // -D environment variables + Enumeration names = environment.propertyNames(); + while(names.hasMoreElements()) { + String name =(String) names.nextElement(); + cmd[idx++] = "-D" + name + "=" + + environment.getProperty(name); + } + + // Debugging arguments, if any + for(int i = 0; i < debugArgs.length; i++ ) + cmd[idx++] = debugArgs[i]; + + + cmd[idx++] = "corba.framework.ReflectiveWrapper"; + + // Class name + cmd[idx++] = className; + + // Arguments to the program + for(int i = 0; i < programArgs.length; i++) + cmd[idx++] = programArgs[i]; + + Test.dprint("--------"); + for(int i = 0; i < cmd.length; i++) + Test.dprint("" + i + ": " + cmd[i]); + Test.dprint("--------"); + + return cmd; + } + +} diff --git a/functional-tests/src/test/java/corba/framework/ReflectiveWrapper.java b/functional-tests/src/test/java/corba/framework/ReflectiveWrapper.java new file mode 100644 index 000000000..f52c33d78 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ReflectiveWrapper.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.lang.reflect.Method; + +import test.ShutdownHook; + +public class ReflectiveWrapper { + + public static void main(String[] args) { + try { + System.out.println("** Executing ReflectiveWrapper **"); + Runtime.getRuntime().addShutdownHook(new ShutdownHook()); + String[] array = new String[args.length - 1]; + System.arraycopy(args, 1, array, 0, args.length -1); + + Class cls = Class.forName(args[0]); + Class[] params = { args.getClass() }; + Method method = cls.getDeclaredMethod("main", params); + method.invoke(null, new Object[] { array }); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/ResolveNS.java b/functional-tests/src/test/java/corba/framework/ResolveNS.java new file mode 100644 index 000000000..2d81174ce --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ResolveNS.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CORBA.ORBPackage.InvalidName; + +public class ResolveNS { + + private static boolean orbd = false; + + public static void main(String[] args) { + if (args[0].equals("orbd")) { + orbd = true; + } + + try { + org.omg.CORBA.Object nameService = null; + org.omg.CORBA.Object tnameService = null; + + ORB orb = ORB.init(args, System.getProperties()); + try { + nameService = orb.resolve_initial_references("NameService"); + } catch (InvalidName in) { } + + try { + tnameService = + orb.resolve_initial_references("TNameService"); + } catch (InvalidName in) { } + + if ((nameService == null) || (orbd && (tnameService == null)) + || (!orbd && (tnameService != null))) { + System.exit(1); + } + System.exit(0); + } catch (Throwable t) { + System.exit(2); + } + } +} diff --git a/functional-tests/src/test/java/corba/framework/TestngRunner.java b/functional-tests/src/test/java/corba/framework/TestngRunner.java new file mode 100644 index 000000000..118f33c27 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/TestngRunner.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.io.File ; + +import java.util.Set ; +import java.util.HashSet ; +import org.glassfish.pfl.test.JUnitReportHelper; + +import org.testng.TestNG ; +import org.testng.ITestResult ; +import org.testng.ITestListener ; +import org.testng.ITestContext ; + +/** Used to set up an appropriate instance of TestNG for running a test. + * Used inside the CORBA test framework in order to generate useful reports + * in JUnitReport format for integration with Hudson. + */ +public class TestngRunner { + private Set> suiteClasses ; + private TestNG testng ; + private String outdirName ; + private boolean hasFailure ; + + private class JUnitReportTestListener implements ITestListener { + private JUnitReportHelper helper ; + + JUnitReportTestListener( String name ) { + helper = new JUnitReportHelper( name ) ; + } + + private void msg( String str ) { + System.out.println( str ) ; + } + + public void onStart( ITestContext context ) { + } + + public void onFinish( ITestContext context ) { + helper.done() ; + } + + public void onTestStart( ITestResult result ) { + helper.start( result.getName() ) ; + } + + public void onTestSkipped( ITestResult result ) { + helper.fail( "Test was skipped" ) ; + } + + public void onTestFailure( ITestResult result ) { + Throwable err = result.getThrowable() ; + + helper.fail( err ) ; + } + + public void onTestSuccess( ITestResult result ) { + helper.pass() ; + } + + public void onTestFailedButWithinSuccessPercentage( ITestResult result ) { + helper.pass() ; + } + } + + /** Create a new TestngRunner. + * @param outdir The directory in which the test reports should be placed. + */ + public TestngRunner() { + final String propName = "junit.report.dir" ; + + String reportDir = System.getProperty( propName ) ; + if (reportDir == null) { + System.setProperty( propName, "." ) ; + reportDir = "." ; + } + + File outdir = new File( reportDir ) ; + if (!outdir.exists()) + throw new RuntimeException( outdir + " does not exist" ) ; + + if (!outdir.isDirectory()) + throw new RuntimeException( outdir + " is not a directory" ) ; + + outdirName = reportDir + File.separatorChar + + System.getProperty( "corba.test.controller.name", "default" ) ; + + File destDir = new File( outdirName ) ; + destDir.mkdir() ; + + suiteClasses = new HashSet>() ; + hasFailure = false ; + } + + /** Register a class container TestNG annotations on test methods. + * The test report is generated in outdir under the name .xml. + * Note that we assume that each suite is represented by a unique class. + */ + public void registerClass( Class cls ) { + suiteClasses.add( cls ) ; + } + + /** Run the tests in the registered classes and generate reports. + */ + public void run() { + for (Class cls : suiteClasses ) { + testng = new TestNG() ; + testng.setTestClasses( new Class[] { cls } ) ; + testng.setOutputDirectory( outdirName ) ; + testng.setDefaultSuiteName( cls.getName() ) ; + testng.setDefaultTestName( cls.getName() ) ; + testng.addListener( new JUnitReportTestListener( cls.getName() ) ) ; + testng.run() ; + if (testng.hasFailure()) + hasFailure = true ; + } + } + + public boolean hasFailure() { + return hasFailure ; + } + + public void systemExit() { + if (hasFailure) + System.exit( 1 ) ; + else + System.exit( 0 ) ; + } +} diff --git a/functional-tests/src/test/java/corba/framework/ThreadExec.java b/functional-tests/src/test/java/corba/framework/ThreadExec.java new file mode 100644 index 000000000..1743ef2da --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ThreadExec.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.*; + +/** + * Runs the class in a separate thread. Currently, the class must extend the + * ThreadProcess class, though it probably only needs to implement the + * InternalProcess interface (as long as it starts itself in its own + * thread). + */ +public class ThreadExec extends InternalExec +{ + public void stop() + { + if (process != null) + process.stop(); + } + + public int waitFor() throws Exception + { + if (process == null) + throw new IllegalThreadStateException(processName + + " was never started"); + + return process.waitFor(); + } + + public int waitFor(long timeout) throws Exception + { + if (process == null) + throw new IllegalThreadStateException(processName + + " was never started"); + + return process.waitFor(timeout); + } + + public int exitValue() throws IllegalThreadStateException + { + if (process == null) + throw new IllegalThreadStateException(processName + + " was never started"); + else + return process.exitValue(); + } + + public boolean finished() throws IllegalThreadStateException + { + if (process == null) + throw new IllegalThreadStateException(processName + + " was never started"); + + return process.finished(); + } + + protected void activateObject(Object obj) + { + process = (ThreadProcess)obj; + + PrintStream output = new PrintStream(out, true); + PrintStream errors = new PrintStream(err, true); + + try { + process.run(environment, programArgs, output, errors, extra); + } catch (Exception ex) { + ex.printStackTrace(errors); + exitValue = 1; + } + } + + private ThreadProcess process = null; +} diff --git a/functional-tests/src/test/java/corba/framework/ThreadProcess.java b/functional-tests/src/test/java/corba/framework/ThreadProcess.java new file mode 100644 index 000000000..c3db11e79 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/ThreadProcess.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.io.PrintStream; +import java.util.Properties; +import java.util.Hashtable; + +/** + * Class representing a process which will run a separate thread but + * the same process as the test framework. A subclass can extend this + * and be used with the ThreadExec strategy. + *

+ * Subclasses should construct their run() method such that they + * exit gracefully when stopped() returns true. + *

+ * A subclass must call setExitValue and then setFinished at the + * end of execution. + *

+ * Could probably transfer most of this to ThreadExec. + */ +public abstract class ThreadProcess implements InternalProcess, Runnable +{ + protected Properties environment; + protected String args[]; + protected PrintStream out; + protected PrintStream err; + protected Hashtable extra; + + private boolean finished = false; + protected int exitValue = ExternalExec.INVALID_STATE; + private boolean stopped = false; + + // Use a separte lock object in case the subclass wants to + // use synchronized + private Object lockObj = new Object(); + + /** + * Saves the parameters, and starts in its own thread + * (so override the Runnable run() method). + */ + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) + { + this.environment = environment; + this.args = args; + this.out = out; + this.err = out; + this.extra = extra; + + (new Thread(this)).start(); + } + + public void stop() + { + /* + If not finished: + Set the exit value to STOPPED, and set the stopped flag to true + Wait until the executing thread calls setFinished (it knows to + do so because now stopped() returns true). + */ + + synchronized(lockObj) { + + if (!finished()) { + exitValue = Controller.STOPPED; + + // The thread should eventually call setFinished and + // exit which will wake up any waiters. (It knows + // it must leave because now stopped() returns true.) + stopped = true; + + try { + lockObj.wait(); + } catch (InterruptedException ex) { + // Just return from wait -- this really shouldn't + // happen + } + } + } + } + + /** + * Used by subclasses to determine if they have been stopped, + * and should exit run(). + */ + protected boolean stopped() + { + synchronized(lockObj) { + return stopped; + } + } + + public boolean finished() + { + synchronized(lockObj) { + return finished; + } + } + + /** + * Used by subclasses to declare that they are done, and wake up + * any threads that are in waitFor. + */ + protected void setFinished() + { + synchronized(lockObj) { + finished = true; + lockObj.notifyAll(); + } + } + + public int waitFor() throws Exception + { + return waitFor(0); + } + + public int waitFor(long timeout) throws Exception + { + synchronized(lockObj) { + if (!finished()) + lockObj.wait(timeout); + return exitValue; + } + } + + public int exitValue() throws IllegalThreadStateException + { + synchronized(lockObj) { + if (exitValue == ExternalExec.INVALID_STATE) + throw new IllegalThreadStateException("exit value wasn't set"); + + return exitValue; + } + } + + /** + * Used by a subclass to set its exit value. This should be + * called before setFinished(). If another thread called + * stop(), this won't change the exit value. + */ + protected void setExitValue(int value) + { + synchronized(lockObj) { + if (!stopped()) + exitValue = value; + } + } +} + + + diff --git a/functional-tests/src/test/java/corba/framework/TimedTest.java b/functional-tests/src/test/java/corba/framework/TimedTest.java new file mode 100644 index 000000000..905bd0dc0 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/TimedTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import junit.extensions.RepeatedTest ; +import junit.framework.TestResult ; +import junit.framework.Test ; + +public class TimedTest extends RepeatedTest +{ + // Duration in nanoseconds + private long duration ; + + public TimedTest( Test test, int reps ) + { + super( test, reps ) ; + } + + public void run( TestResult result ) + { + long startTime = System.nanoTime() ; + long stopTime = 0 ; + try { + super.run( result ) ; + } finally { + stopTime = System.nanoTime() ; + } + duration = stopTime - startTime ; + } + + public long getDuration() + { + return duration ; + } +} + + diff --git a/functional-tests/src/test/java/corba/framework/TraceAccumulator.java b/functional-tests/src/test/java/corba/framework/TraceAccumulator.java new file mode 100644 index 000000000..79ff366fb --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/TraceAccumulator.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.util.Iterator ; +import java.util.List ; +import java.util.ArrayList ; + +public class TraceAccumulator implements MethodEventListener +{ + private List elements ; + + public TraceAccumulator() + { + clear() ; + } + + public void clear() + { + elements = new ArrayList() ; + } + + private void addElement( boolean isEnter, MethodEvent event ) + { + TraceElement tel = new TraceElement( isEnter, event ) ; + elements.add( tel ) ; + } + + public void methodEntered( MethodEvent event ) + { + addElement( true, event ) ; + } + + public void methodExited( MethodEvent event ) + { + addElement( false, event ) ; + } + + public List getTrace() // List + { + return elements ; + } + + public boolean validate( List expectedTrace ) // List + { + Iterator iter1 = elements.iterator() ; + Iterator iter2 = expectedTrace.iterator() ; + while (iter1.hasNext() && iter2.hasNext()) { + TraceElement tel1 = (TraceElement)(iter1.next()) ; + TraceElement tel2 = (TraceElement)(iter2.next()) ; + if (!tel1.equals( tel2 )) + return false ; + } + + return iter1.hasNext() == iter2.hasNext() ; + } +} + diff --git a/functional-tests/src/test/java/corba/framework/TraceElement.java b/functional-tests/src/test/java/corba/framework/TraceElement.java new file mode 100644 index 000000000..c73509037 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/TraceElement.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework ; + +import java.lang.reflect.Method ; + +public class TraceElement +{ + private boolean isEnter ; + private MethodEvent event ; + + public TraceElement( boolean isEnter, MethodEvent event ) + { + this.isEnter = isEnter ; + this.event = event ; + } + + public boolean isEnter() { return isEnter ; } + + public MethodEvent getEvent() { return event ; } + + public boolean equals( Object obj ) + { + if (!(obj instanceof TraceElement)) + return false ; + + TraceElement other = (TraceElement)obj ; + + return (event.equals( other.event ) && + isEnter == other.isEnter) ; + } + + public int hashCode() + { + return event.hashCode() + (isEnter ? 1711 : 0) ; + } + + public String toString() + { + return "TraceElement[isEnter=" + isEnter + " event=" + event + "]" ; + } +} diff --git a/functional-tests/src/test/java/corba/framework/package.html b/functional-tests/src/test/java/corba/framework/package.html new file mode 100644 index 000000000..c124e8b0f --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/package.html @@ -0,0 +1,713 @@ + + + + + + + + + CORBA Technologies Test Framework + + +

CORBA Technologies Test Framework

+

Contents

+

+

Overview

+
Here are some features of the new system: +
    +
  • Inherits from the IBM system, bringing ease of use to our test + efforts while not breaking old code
  • +
  • Captures stdout and stderr output of each process (compilers, + ORBD, server(s), client(s), etc)
  • +
  • Allows a high degree of control over the configuration of + subprocesses
  • +
  • Supports a wide variety of test types
  • +
  • Provides a flexible compiler abstraction with implementations for + idlj, rmic, and javac
  • +
  • Allows a user to easily debug an external process with JDB.
  • +
  • Accommodates difficult tests in which coordinating the behavior of + several processes is required
  • +
+

Good things to know

+
    +
  1. When I use the term "process" in this document, it doesn't + necessarily mean java.lang.Process.  Most of the time, ORBD, clients, + servers, and compilers are executed in separate java.lang.Process's.  + However, if the test author uses a different execution strategy (see + Writing a more sophisticated + test), something may run in the same java.lang.Process as the test + framework.
  2. +
  3. The IBM test framework depends on a command line option -output to + specify the output directory, and the framework depends on it, as well.  + This directory must be on the classpath, and our makefiles already work this + way.  The output directory is gen on Solaris, and since the + framework is always run from test/build/solaris, that's where it + is.  (On Win32, it's right off of the workspace directory.)   Each + test has its own special output directory under this one, and its name is + <command line output directory>/<test package name>.
  4. +
  5. The framework and its tests live in subdirectories of + test/src/share/classes/corba.  The package names are + corba.*.
  6. +
  7. Each test has a main Java file that is it's heart, and it extends + CORBATest.  + This is where the test author directs the flow of the test through compilation, + creation and execution of processes, and finally, how they are destroyed.
  8. +
  9. The framework makes assumptions about directory paths.  It + assumes it starts in the test/build/$OS directory and can find things + off of that.  However, I think all these assumptions are isolated in the + initialization of the Options + class.
  10. +
+

Running the tests

+
You can now execute the IBM tests followed by tests in the new + framework by using the verifyall target. +

Solaris:

The test framework and tests are compiled as a part of + the normal main build (with GNUmakefile.corba), or can be compiled + more directly by using the makefile under test/build/solaris/corba. +

To run the tests:
cd ~/ws/rip-int/build/solaris +
gnumake verifyonly_corba

+

Windows:

The test framework and tests should be compiled as a + part of the normal build, or can be compiled more directly by using the + makefile under test/build/win32/corba. +

To run the tests:
cd ws/rip-int/build/win32
nmake + verifybuild_corba

+

What you should see:

+
corba.example.Example: Run 1 : + [100484ms] PASSED
corba.oneway.OneWayTest: Run 1 : [46646ms] PASSED +
corba.cosnaming.Test: Run 1 : [28803ms] + PASSED
corba.poamanager.POAManagerTest: Run 1 : [44982ms] + PASSED
corba.poapolicies.POAPoliciesTest: Run 1 : [30906ms] + PASSED
corba.rmijtshook.RMIJTSHookTest: Run 1 : [24914ms] + PASSED
corba.jtshook.JTSHookTest: Run + 1 : [31500ms] PASSED
+

Specifying + the default ORBClass for all tests

+
Any test that uses a POA ORB should use the default ORBClass + from Options. Then, when running the makefiles, simply provided a + ORBCLASS=<orb class name> variable. The default, set in + Defs.gmk and defs-corba.nmk, is + com.sun.corba.ee.internal.POA.POAORB.
+

Examining a test's output

+ +
The framework captures stdout and stderr streams for the + compilers, ORBD, servers, and clients.  The convention is <process + name>.out.txt and <process name>.err.txt.  The test + author can decide on process names for server and client, or use the defaults + ("server" and "client").  The only time it's absolutely necessary to + assign new names is when there are multiple servers or clients. +

These files are located in the test's output directory.  This is + the directory specified on the command line (with the -output switch) + plus the test's package name.  Our makefiles currently specify + gen as the command line option.

+

Solaris:

Output directory: test/make/gen +

Windows:

Output directory: gen +

Thus, for corba.example.Example on Solaris, look in + test/build/solaris/gen/corba/example and you'll find the following: +

+

HelloApp             + client.out.txt       javac.out.txt +
JavaIDLHome          + corba                + server.err.txt +
ORBD.err.txt         + idlcompiler.err.txt  server.out.txt +
ORBD.out.txt         + idlcompiler.out.txt +
client.err.txt       javac.err.txt +

+

The further corba/example subdirectory was created by the + generation of stubs and skeletons, or any extra Java files the test required. +

+

On Win32, just look in gen/corba/example.

+

How to debug a test

+
The first thing to do if a test fails is to + examine the test's output.  If + the failure seems unusual, try running the test again.  If it looks like a + real problem, you can ask the framework to tell you exactly how it's starting + each process.  You do this by specifying the -debug command line + parameter on the failing test's line in CORBATests.txt.  +

When you still can't tell what's wrong, or if you want to dive into a + process with JDB, here's how to do it:

+

Case 1: You want to debug something run in a separate + java.lang.Process

+

This is quite easy if you want to use JDB or a similar + debugger.  The framework will take care of setting the execution strategy + to DebugExec.  + This strategy will provide you with the command to run JDB both on the screen + and in a file in your test/build/$OS directory.

+

Edit the test/src/share/classes/corba/CORBATests.txt + file.  On the line with the test you want to debug, put the + -debug flag followed by a colon separated list of the process names + you want to debug.  If the test uses the default names, you can run + ORBD, client, and server processes outside of the + framework in your debugger.  (Note: it is case sensitive)

+

Example:

+

-test corba.example.Example -debug client:server

+

When it comes time for the server or client process to start, the + framework will prompt you to do so in another window.  It will give you an + adapted command which uses JDB as the debugger.  In addition, it will + write that command to the test/build/$OS directory as a file called + jdb<process name>.bat.  Unfortunately, on Solaris, you must + still set the execution permission before you can run it.  The debug + strategy will also prompt you for other information during the test.

+

Note: the .bat files are erased after the test finishes

+

There are two other debug options: -rdebug, which uses JPDA, and + -odebug, which uses Bil Lewis's Omniscient Debugger (odb). A version of odb is + in the workspace under the Lib directory. Both options take the same arguments + as the -debug flag. The difference is in how the controller is attached to a + debugger. -rdebug launches the VM for the controller with the JPDA arguments + necessary for attaching your favorite JPDA-enabled debugger (e.g. NetBeans, + jswat, jdebugtool) to the controller. -odebug launches the main java class in + the controller under odb, which then captures all events during the execution + of the VM, and makes the entire execution history available in a viewer after + the program terminates (or it is told to terminate through a button on a window + that odb launches)

+

Case 2: You want to edit a sophisticated test that uses unusual + execution strategies

+

This is harder, but not impossible.  You must run the entire + test framework under your debugger.  This can be done quite easily under + Solaris simply by setting the environment variable DEBUGGER to 1 and running a + test suite from the Makefile. This launches the test framework using JPDA, and + any JPDA debugger can connect to the test framework. Since you probably only + want to debug one test at a time, watch how the makefile and framework load + tests from the file.  Copy and adapt how the makefile starts the framework + so it works with your debugger.  You should be able to give the line out + of CORBATests.txt for your test directly as a parameter to the framework, + rather than letting the makefile give it the -file parameter. +

+

Adding a new test

+
Assuming you follow some guidelines when writing your test, it + should be simple to insert it in the framework.  It may be easier for you + to write it outside of the framework until it's running.  The framework + does the IDL compilation for you, but that also means that any code that + depends on the stubs or skeletons must be compiled as a part of the test + (usually your client and server test code).  When you run the target, the + output directory is wiped, and the framework starts at the beginning -- + compiling IDL, compiling generated code, etc.  That takes time, and may + make it frustrating if you still have simple programming errors in your code. +

How to write your + test

Here are the basic steps to create a new test: +
    +
  1. Make your test package name corba.<test name>, and + be sure all your source files use this.
  2. +
  3. Create <test name> directories under + test/src/share/classes/corba and /test/build/$OS/corba.
  4. +
  5. Create a main test file following the model of corba.example.Example.java.  This is + the heart of your test.  Use the Options + class to set any special variables here (such as the ORB class, options to the + IDL compiler like -poa, etc).  Then use the methods such as + compileIDLFiles, compileJavaFiles, createORBD, etc, as in the + example.
  6. +
  7. Make sure that the server emits a handshake before it waits for + connections. The default is "Server is ready."
  8. +
  9. Look at the javadoc API for Options + and Controller + for more information.
  10. +
  11. Create makefiles.
  12. +
  13. Add your test to + CORBATests.txt.
  14. +
Here are some guidelines on how to write your test:
+
    +
  1. Have the client and server read org.omg.ORBClass from + System.getProperty rather than hardcoding them.  This will allow you + specify what ORB to use in one place.  You could even just give the ORB + System.getProperties() since a considerable amount of information is passed + automatically.  See the javadoc API for Options + and CORBATest#createServer + or + CORBATest#createClient for what is passed along to them already.
  2. +
  3. Be sure your client and server exit with exit + codes greater than zero when they fail.  This + is the only way the test framework will know something went wrong.  It's + usually easy to do this by catching all exceptions at the end of your program, + printing the stack trace, and calling System.exit(1);  If your + test has multiple threads, you must still find a way to report the exit code + properly.   See corba.example for a way to do + this.
  4. +
  5. Don't write your test to require human + verification of the output
  6. +
  7. Don't write your test to require human input + (though it is possible to have one of the subprocesses control the + others)
  8. +
  9. Don't write things to + user.home.  The framework gives client and server processes a + output.dir environment variable to use instead.
  10. +
  11. Consider writing your clients and servers to implement InternalProcess, + but still write a main. That way, later, people could swap execution strategies + easily (see Writing a more + sophisticated test). Perhaps something like this: +
    +public class MyClient implements InternalProcess
    +{
    +    public void run(Properties environment,
    +                    String args[],
    +                    PrintStream out,
    +                    PrintStream err,
    +                    Hashtable extra) throws Exception
    +    { 
    +       
    +        // Do what you want to here, generating
    +        // exceptions for any failure cases.  If it
    +        // is loaded internally, the framework will
    +        // report the error, yet it still works
    +        // perfectly as a default external process.
    +    }
    +
    +    public static void main (String[] args)
    +    {
    +        try {
    +            (new MyClient()).run(System.getProperties(),
    +                                 args,
    +                                 System.out,
    +                                 System.err,
    +                                 null);
    +        } catch (Exception e) {
    +            e.printStackTrace(System.err);
    +            System.exit(1);
    +        }
    +    }
    +}
    +
  12. +
+

Adding and updating + makefiles

It would be good to develop a quick script or application to + do all of this. +

Create a test/build/share/corba_<test package>.jmk file + containing ONLY those files that don't rely on stubs and skeletons.  In + the classic CORBA case, this may only be your main test file.  I advise + just copying and changing one of the others.

+

Solaris:

+

Create a test/build/solaris/corba/<test + package>/GNUmakefile for your test.  Again, start with one of the + others.  You only have to change a line or two to replace the package + names.  You may want to put TESTCORBA=1 at the top in case one of the + classes that isn't compiled within the framework uses org.omg.*.

+

Augment the test/build/solaris/corba/GNUmakefile so that it's + SUBDIRS variable declaration includes your test's subdirectory.

+

Windows:

+

Create a test/build/win32/corba/<test package>/Makefile + for your test.  Again, start with one of the others.  You only have + to change three lines to replace the names.

+

Augment the test/build/win32/corba/Makefile so that it's + SUBDIRS variable declaration includes your test's subdirectory.

+

Changing the tests file

Add your test to the + test/src/share/classes/corba/CORBATests.txt file. +

Notes:

+
+
    +
  • Give your test the -debug parameter + to see exactly what the framework is doing.
  • +
  • If you write a test using InternalExec + or ThreadExec, + please use the -separateprocess flag to make sure there are no lasting + effects.
  • +
+

Writing a more + sophisticated test

+
Not + all tests will fit into a simple model in which the processes are fairly + independent and the only things that need to be tested would generate + exceptions if they were broken.  Maybe your test requires that the ORBD + process be restarted in time with actions on the server, and then have clients + access the server after that (the PCOSNaming test does this).  Maybe you + want both client and server to use the same ORB reference, etc.  This is + possible, but still not as easy as it should be. +

Controllers + and execution strategies

Examine the Controller interface.  It's an + abstraction that allows you to create/initialize, start, wait for, and stop a + process.  The ultimate goal is to make these interchangeable whenever + possible.  All that is absolutely required is a class name to execute and + a name to call it by.  The test framework has four classes that provide + different ways of fulfilling those methods.
  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExternalExecExecutes the class in a separate process.  The start() + method returns immediately.
ExternalHandshakeExecExecutes the class in a separate process.  The start() + method returns only after receiving a handshake.  It throws an exception + if it isn't received in a certain amount of time.  The handshake string is + given as an extra value with the key + ExternalHandshakeExec.HANDSHAKE_KEY.  The timeout is defined by + Options.getMaximumTimeout().
InternalExecExecutes the class in the same process and thread as the + test.  Requires that the class implement the InternalProcess + interface.  The start() method will not return until the run + method has returned.
ThreadExecExecutes the class in the same process, but a different + thread.  Currently requires that the class extend ThreadProcess + (which implements the internal interface, but provides some other necessary + items).  This may change in the future since it should be unified with the + others.  The ThreadProcess must behave appropriately and exit + when stopped (methods are provided for all of this).
DebugExecDefers all methods of the Controller to the user, allowing him to + run the class with a debugger outside of the framework while still benefiting + from its structure.  Read more about this in the + How to debug a test section.
RDebugExecLaunches the java class with the VM arguments -Xdebug -Xnoagent + -Xrunjdwp:transport=dt_socket,server=y,suspend=y so that a JPDA debugger can be + attached to the VM. Also overrides controller.stop so that the user must + explicitly indicate when they are ready to terminate the process.
ODebugExecLaunches the java class under com.lambda.Debugger.Debugger which + causes the class to run under Bil Lewis's Omniscient debugger + (experimental).
+

If you want to switch execution strategies (except for debugging), + override one of these methods in your main test class:

+
protected Controller newClientController() +
protected Controller newORBDController()
protected + Controller newServerController()
The current implementations + return a new ExternalExec + for the client, and new ExternalHandshakeExec's + for ORBD and the Server.  (You can change the handshakes in the Options + class.)  It would be possible to use someone else's ORBD by switching + handshakes, or writing a new execution strategy that waits for or detects when + it is ready.  Similarly, you could create your own special execution + strategy for anything unusual, or for something that you couldn't change to + implement InternalProcess, but still wanted to run in the current + process.  (The above methods could be replaced by something in Options.) + +

The extra parameter to initialize is a hashtable + which allows you to pass anything special that you need to.  For example, + a handshake.  This is where the benefits of internal strategies come + in.  If your server process needs the ORBD controller for something, you + could make your server an InternalProcess or ThreadProcess, + change the execution strategy accordingly, and pass the ORBD by means of this + hashtable.

+

Using the Options + class

Options + is the place in which your main test can define lots of information.  + Unfortunately, this isn't available to your external processes, so find some + way to pass things you need (maybe through extra properties, also something you + can set with this class).  See the javadoc API for the most recent things + given to + + client, + server, + and + ORBD + processes.  You may find that what you need is already available. +

The test framework reinitializes this class before every test.  + You should only have to call its accessors (which are all + static).

+

Conversion Status

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TestConversion StatusNotes
PCOSNamingTestsConverted to corba.pcosnaming 
cosnamingConverted to corba.cosnaming 
counterNot yetCompile fails with usual Servant problem (expects interface)
javaidlhelloNot yet 
jtshooktest*Converted to corba.jtshook*Compares stdout dumps for differences
local_stub_genNot yet 
mthello*Converted to corba.example*The POA version was converted as the example, not the + orb.connect / ImplBase version
onewaytestConverted to corba.oneway 
persistenthelloNot yetCompile fails with usual Servant problem (expects interface)
poa-and-equalsConverted to corba.poaandequals 
poa-and-invalid-policiesNot yet 
poa-and-nonexistentCompile fails with usual Servant problem (expects interface)
poahelloNot yet 
poamanagerConverted to corba.poamanager 
poapolicicesConverted to corba.poapolicicesNeed to update exception catching further
rmi-jts-unexportNot yetClient exception
rmi-jtshooktest*Converted to corba.rmijtshook*Compare stdout dumps for differences
rmi-jtshooktest2Same as rmi-jtshooktest 
rmi_poa_counterConverted to corba.rmipoacounter 
rmi_poa_counter2Not yet 
rmi_poa_counter3Not yet 
rmi_poa_double_counterNot yet 
rmi_poa_double_counter2Not yet 
sc-hook-testNot yetCompile errors
simple-rmiNot yetClient side exceptions?
stub-test-compilerNot yetClient side exceptions?
sun_obv_interopNot yet 
transient_object_managerNot yet 
+

Remaining items and bugs

+
+

Goals and ideas:

+
    +
  1. All clients and servers should implement something like + corba.framework.InternalProcess to make it easier to switch execution + strategies.  They could have a static main which passes in system + properties and streams, then catches the exception, prints it, and exits with + an error code if something went wrong.
  2. +
  3. Work on all execution strategies to make them clean.  Dealing + with asynchronous processes is hard, but there must be a nice way to clean up + all those cases.
  4. +
  5. Probably, newORBDController and the others should be removed in + favor of setting this in Options
  6. + +
  7. ThreadExec + and InternalExec + need to be unified such that a client/server can be switched easily, the two + have the same semantics where possible, and there are no further requirements + other than InternalProcess (this means that ThreadProcess should go + away or just become an adapter)
  8. +
  9. Simplify makefiles or create a script/small program
  10. +
  11. Fix deprecation warnings (some tests used + DataInputStream/DataOutputStream)
  12. +
  13. Rewrite the Controller + and everything else to throw specific exceptions -- TimeoutException, + BadExitValueException, InvalidStateException, etc.  Much more tedious, but + more descriptive and precise.
  14. +
  15. A next generation project might use CORBA to talk and exchange + special references between processes.  Similar to the way the old test + framework used RMI to do this for servants, except much more broad.  You + could have the processes running ANYWHERE -- including in the same process as + the test, and not have all the special cases associated with them.  + However, that's a bit heavy weight, and it's hard to justify using what we're + testing to build a test framework to test it!
  16. +
+

Bugs

+
    +
  1. When using internal execution strategies with RMI, the system will + not be able to find the new class files since they will be under + gen/<package>/<package> but the runtime only has + gen on the classpath.  The work around is to set the output + directory in Options + (in that particular test) to just be gen and deal with the + ramifications of that.  This doesn't seem to happen in the CORBA case -- + it seems to use the framework's special class loader appropriately.
  2. +
  3. On Windows, the first time you start an ORBD process, it seems like + ORBD creates a subprocess for a few seconds. This normally isn't a problem, but + will be if you want to shut down ORBD and restart it (as in the PCOSNaming + test). If you don't give ORBD a little more time to start (the first time) with + a Thread.sleep, this mystery process will hang around. When you kill and + restart ORBD, it will prevent the restart, causing the test to time out waiting + for the ORBD handshake.
  4. +
  5. On Windows with Kestrel, the framework may hang at the end of + CORBAUtil.startProcess when it tries to pipe the error stream to a file. This + may be a java.io bug.
  6. +
  7. If your IDL doesn't have a module name, your test will fail. The + generated code will be placed in gen/<test package>, and javac will + complain of a multiple declaration.
  8. +
  9. The IDL compiler doesn't set a non-zero exit value on failure.  + Thus, make sure to check idlcompiler.err.txt if your test fails with + an unusual javac error.
  10. +

+
Everett + Anderson

+ + + diff --git a/functional-tests/src/test/java/corba/framework/statusU.java b/functional-tests/src/test/java/corba/framework/statusU.java new file mode 100644 index 000000000..834487a50 --- /dev/null +++ b/functional-tests/src/test/java/corba/framework/statusU.java @@ -0,0 +1,322 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.framework; + +import java.util.Set; +import java.util.TreeMap; +import java.util.Iterator; +import java.util.Hashtable; + +import java.util.StringTokenizer; + +public class statusU { + + class TestData { + private int status; + private String desc; + + public TestData(int status, String desc) { + this.status = status; + this.desc = desc; + } + + int getStatus() { return status; } + String getDesc() { return desc; } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + if (getStatus() == RTMConstants.PASS) + sb.append(PASS); + else + sb.append(FAIL); + + sb.append(" - "); + sb.append(getDesc()); + + return sb.toString(); + } + }; + + /* FIELDS */ + + private final String PASS = new String("PASSED"); + private final String FAIL = new String("FAILED"); + + /** + * TreeMap is used becuase it ensures that unique key-value pairs are + * stored in data structure. It stores the keys in an ascending order + * and thus using an iterator would give all the keys in a natural order + * of keys, in our case testnames. + * If the need be, we can provide a Comparator afterwards and change + * the order of the keys. + */ + TreeMap treeMap = null; + + Hashtable hash = null; + + /* CONSTRUCTORS */ + + public statusU() { + try { + treeMap = new TreeMap(); + hash = new Hashtable(); + /* + BufferedReader file = new BufferedReader(new FileReader("config.txt")); + String line; + + while ((line = file.readLine()) != null) { + StringTokenizer tokens = new StringTokenizer(line, ":"); + hash.put((String)tokens.nextElement(), (String)tokens.nextElement()); + } + */ + + hash.put("api_javaidl", "JavaIDL API Tests"); + hash.put("api_javax", "RMI-IIOP API Tests"); + hash.put("api_poa", "POA API Tests"); + hash.put("api_dynany", "DynAny API Tests"); + hash.put("api_ins", "INS API Tests"); + hash.put("api_orb", "ORB API Tests"); + hash.put("api_ior", "IOR API Tests"); + hash.put("api_giop", "GIOP API Tests"); + hash.put("api_ci", "Connection Interceptor API Tests"); + hash.put("api_InterfaceRepository", + "InterfaceRepository API Tests"); + hash.put("interoperability_evolution", + "Classes Evolution Interoperability Tests"); + hash.put("interoperability_strm2", + "Stream2 Evolution Interoperability Tests"); + hash.put("interoperability_serialization", + "Object Serialization Interoperability Tests"); + hash.put("interoperability_rmiiiop", + "RMI-IIOP Interoperability Tests"); + hash.put("performance_simpleperf", + "Local Optimization Performance Tests"); + hash.put("performance_interceptors", + "ClientInterceptor Performance Tests"); + hash.put("scalability_poa", "POA Scalability Tests"); + hash.put("scalability_activation", + "ORB Activation Deactivation Tests"); + hash.put("scalability_naming", + "NameService Scalability Tests"); + hash.put("endToend_pi", "EndToEnd PI Tests"); + hash.put("endToend_poa", "EndToEnd POA Tests"); + hash.put("Reliability", "Reliability Test"); + hash.put("product_rmijrmp", "RMI-JRMP Product Tests"); + hash.put("product_rmiiiop", "RMI-IIOP Product Tests"); + hash.put("product_pcosnaming", "PCosNaming Product Tests"); + hash.put("product_poa", "POA Product Tests"); + hash.put("product_pi", "PI Product Tests"); + hash.put("product_ots", "OTS Product Tests"); + hash.put("product_javaidl", "JavaIDL Product Tests"); + hash.put("product_valuetypes", "Valuetypes Product Tests"); + hash.put("product_saf", "Server Activation Tests"); + hash.put("product_orbspi", "PEORB SPI Tests"); + hash.put("product_ort", "ObjectReferenceTemplate Tests"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + /* METHODS */ + + synchronized public void clearStatus() { + treeMap.clear(); + } + + synchronized public void addStatus(String testName, int stat) { + TestData testData = new TestData(stat, "No Description Available"); + + treeMap.put(testName, testData); + } + + synchronized public void addStatus(String testName, int stat, String desc) { + if (desc == null) { + desc = "No Description Available"; + } + + TestData testData = new TestData(stat, desc); + + treeMap.put(testName, testData); + } + + synchronized public void addStatus(String testName, int status, String desc, int andOr) { + if ((andOr != RTMConstants.AND) && (andOr != RTMConstants.OR)) { + System.err.println("Invalid logical operator. Valid values are \"RTMConstants.AND\" or \"RTMConstants.OR\""); + return; + } + + if (desc == null) { + desc = "No Description Available"; + } + + if (treeMap.containsKey(testName)) { + TestData d = (TestData)treeMap.get(testName); + TestData d2 = new TestData(logicalOp(d.getStatus(), status, andOr) == RTMConstants.PASS ? RTMConstants.PASS : RTMConstants.FAIL, d.getDesc() + "\n" + desc); + treeMap.put(testName, d2); + } else { + addStatus(testName, status, desc); + } + } + + private int logicalOp(int status1, int status2, int op) { + if (op == RTMConstants.AND) { + if ((status1 == RTMConstants.PASS) && (status2 == RTMConstants.PASS)) + return RTMConstants.PASS; + else + return RTMConstants.FAIL; + } else { // Default is OR operation. No need of error checking + // here since input has already been validated + if ((status1 == RTMConstants.FAIL) && (status2 == RTMConstants.FAIL)) + return RTMConstants.FAIL; + else + return RTMConstants.PASS; + } + } + + private String generateStatus() { + String data = new String("\n"); + + Set s = treeMap.keySet(); + Iterator i = s.iterator(); + + while (i.hasNext()) { + data += "\n"; + + String str = (String)i.next(); + TestData d = (TestData)treeMap.get(str); + data += "" + str + "\n"; + + if (!d.getDesc().equals("")) + data += "" + d.getDesc() + "\n"; + + data += "\n\n"; + } + + return data; + } + + synchronized private String generateHeader(String testName) { + String data = new String("\n"); + + String category; + String suiteName; + + if (testName.startsWith("api")) + category = "API"; + else if (testName.startsWith("product")) + category = "PRODUCT"; + else if (testName.startsWith("endToend")) + category = "END-TO-END"; + else if (testName.startsWith("Reliability")) + category = "RELIABILITY"; + else if (testName.startsWith("interoperability")) + category = "INTEROPERABILITY"; + else if (testName.startsWith("performance")) + category = "PERFORMANCE"; + else if (testName.startsWith("scalability")) + category = "SCALABILITY"; + else + category = "No Description available"; + + int index = testName.indexOf("_"); + if (index == -1) { + index = testName.length(); + } else { + index = testName.indexOf("_", index+1); + if (index == -1) { + index = testName.length(); + } + } + suiteName = (String)hash.get(testName.substring(0, index)); + + data += "\n"; + data += "" + testName + "\n"; + + return data; + } + + synchronized private String generateFooter(String testName) { + String data = new String("\n"); + + data += "\n"; + data += "" + this.totalPass() + "\n"; + data += "" + this.totalFail() + "\n"; + data += "\n"; + data += "\n"; + + return data; + } + + synchronized public String generateSummary(String testName) { + String data = generateHeader(testName); + data += generateStatus(); + data += generateFooter(testName); + + return data; + } + + synchronized public String generateSummary(String testName, String desc) { + String data = generateHeader(testName); + data += "" + desc + "\n"; + data += generateStatus(); + data += generateFooter(testName); + + return data; + } + + synchronized public void printSummary(String testName) { + System.out.println(generateSummary(testName)); + } + + synchronized public void printSummary(String testName, String desc) { + System.out.println(generateSummary(testName, desc)); + } + + + synchronized public int totalPass() { + int pass = 0; + + Set s = treeMap.keySet(); + Iterator i = s.iterator(); + + while (i.hasNext()) { + String str = (String)i.next(); + TestData d = (TestData)treeMap.get(str); + if (d.getStatus() == RTMConstants.PASS) + pass++; + } + + return pass; + } + + + synchronized public int totalFail() { + int fail = 0; + + Set s = treeMap.keySet(); + Iterator i = s.iterator(); + + while (i.hasNext()) { + String str = (String)i.next(); + TestData d = (TestData)treeMap.get(str); + if (d.getStatus() == RTMConstants.FAIL) + fail++; + } + + return fail; + } + +} // end class statusU + + diff --git a/functional-tests/src/test/java/corba/fwddecl/Client.java b/functional-tests/src/test/java/corba/fwddecl/Client.java new file mode 100644 index 000000000..bfec6ae15 --- /dev/null +++ b/functional-tests/src/test/java/corba/fwddecl/Client.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fwddecl; + +import org.omg.CORBA.Any; +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +import java.util.Properties ; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.encoding.CDRInputObject ; +import com.sun.corba.ee.impl.encoding.CDROutputObject ; +import com.sun.corba.ee.impl.encoding.EncapsInputStream ; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; + +import org.testng.annotations.Test ; + +import corba.framework.TestngRunner ; +import org.glassfish.pfl.test.ObjectUtility; + +public class Client +{ + private ORB orb; + + private OutputStream newOutputStream() + { + return new EncapsOutputStream( orb ) ; + } + + private CDRInputObject makeInputStream( OutputStream os ) + { + byte[] bytes = getBytes( os ) ; + return makeInputStream( bytes ) ; + } + + private byte[] getBytes( OutputStream os ) + { + CDROutputObject cos = (CDROutputObject)os ; + byte[] bytes = cos.toByteArray() ; + return bytes ; + } + + private CDRInputObject makeInputStream( byte[] data ) + { + return new EncapsInputStream( orb, data, data.length ) ; + } + + @Test + public void verifyNewFoo() { + try { + + Any any = orb.create_any(); + + NewFoo n1 = new NewFoo(1, new NewFoo[0]); + NewFoo n2 = new NewFoo(2, new NewFoo[0]); + NewFoo n3 = new NewFoo(3, new NewFoo[] {n1, n2}); + + // Use insert and extract and then test equality + NewFooHelper.insert(any, n3); + NewFoo o = NewFooHelper.extract(any); + if (!ObjectUtility.equals(n3, o)) { + throw new Exception("The objects are not equal"); + } + + // Use write and read and then test equality + OutputStream os = newOutputStream(); + NewFooHelper.write(os, n3); + InputStream is = makeInputStream(os); + NewFoo o1 = NewFooHelper.read(is); + if (!ObjectUtility.equals(n3, o1)) { + throw new Exception("The objects are not equal"); + } + + System.out.println("The test for NewFoo passed !!!"); + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } + + @Test + public void verifyBar() { + try { + Any any = orb.create_any(); + + Bar b1 = new Bar(); + b1.l_mem(12); + + Bar b2 = new Bar(); + b2.l_mem(13); + + Bar b3 = new Bar(); + b3.s_mem(new corba.fwddecl.BarPackage.Foo(5.0d, new Bar[]{b1})); + + Bar b4 = new Bar(); + b4.s_mem(new corba.fwddecl.BarPackage.Foo(10.0d, new Bar[]{b3})); + + Bar b5 = new Bar(); + b5.s_mem(new corba.fwddecl.BarPackage.Foo(15.0d, new Bar[]{b2,b4})); + + // Use insert and extract and then test equality + BarHelper.insert(any, b5); + Bar o = BarHelper.extract(any); + if (!ObjectUtility.equals(b5, o)) { + throw new Exception("The objects are not equal"); + } + + // Use write and read and then test equality + OutputStream os = newOutputStream(); + BarHelper.write(os, b5); + InputStream is = makeInputStream(os); + Bar o1 = BarHelper.read(is); + if (!ObjectUtility.equals(b5, o1)) { + throw new Exception("The objects are not equal"); + } + + System.out.println("The test for Bar passed !!!"); + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + + } + + @Test + public void verifyMoreFoo() { + try { + + Any any = orb.create_any(); + + MoreFoo n1 = new MoreFoo(1, null, new MoreFoo[0], new MoreFoo[0][0]); + MoreFoo n2 = new MoreFoo(2, null, new MoreFoo[0], new MoreFoo[0][0]); + MoreFoo n3 = new MoreFoo(3, null, new MoreFoo[0], new MoreFoo[0][0]); + MoreFoo n4 = new MoreFoo(5, null, new MoreFoo[0], new MoreFoo[0][0]); + MoreFoo n5 = new MoreFoo(6, null, new MoreFoo[0], new MoreFoo[0][0]); + MoreFoo n6 = new MoreFoo(7, null, new MoreFoo[0], new MoreFoo[0][0]); + + MoreFoo n7 = new MoreFoo(8, null, new MoreFoo[]{n1, n2}, + new MoreFoo[][]{{n3, n4}, {n5, n6}}); + + // Use insert and extract and then test equality + MoreFooHelper.insert(any, n7); + MoreFoo o = MoreFooHelper.extract(any); + if (!ObjectUtility.equals(n7, o)) { + throw new Exception("The objects are not equal"); + } + + // Use write and read and then test equality + OutputStream os = newOutputStream(); + MoreFooHelper.write(os, n7); + InputStream is = makeInputStream(os); + MoreFoo o1 = MoreFooHelper.read(is); + if (!ObjectUtility.equals(n7, o1)) { + throw new Exception("The objects are not equal"); + } + + System.out.println("The test for MoreFoo passed !!!"); + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } + + private static String[] args ; + + public Client() { + Properties props = new Properties( System.getProperties() ) ; + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + this.orb = (ORB)ORB.init( args, props ) ; + } + + public static void main(String args[]) { + Client.args = args ; + TestngRunner runner = new TestngRunner() ; + runner.registerClass( Client.class ) ; + runner.run() ; + runner.systemExit() ; + } +} diff --git a/functional-tests/src/test/java/corba/fwddecl/ForwardDeclTest.java b/functional-tests/src/test/java/corba/fwddecl/ForwardDeclTest.java new file mode 100644 index 000000000..2b3661031 --- /dev/null +++ b/functional-tests/src/test/java/corba/fwddecl/ForwardDeclTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fwddecl; + +import test.Test; +import corba.framework.*; +import java.util.*; + + +/** + * This is a POA version of the mthello test. The + * client creates multiple threads that invoke a simple sayHello + * method on the remote servant. + */ +public class ForwardDeclTest extends CORBATest +{ + // This is the main method defining the test. All tests + // should have this. + protected void doTest() throws Throwable + { + // Create client controller using the given + // class. You can also specify names for these (for instance, + // you may want to distinguish between many clients) by using + // the equivalent methods that take two Strings. + Controller client = createClient("corba.fwddecl.Client"); + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(60000); + + // Make sure all the processes are shut down. + client.stop(); + } +} + diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/Client.java b/functional-tests/src/test/java/corba/giopheaderpadding/Client.java new file mode 100644 index 000000000..91d121077 --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/Client.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:54:21 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 10:06:37 by Harold Carr. +// + +package corba.giopheaderpadding; + +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; + +import corba.framework.Controller; +import corba.hcks.C; +import corba.hcks.U; + +import com.sun.corba.ee.impl.protocol.MessageMediatorImpl; + +import java.lang.reflect.*; +import org.omg.PortableInterceptor.*; + +public class Client extends org.omg.CORBA.LocalObject + implements ORBInitializer, ClientRequestInterceptor { + + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static ORB orb; + public static InitialContext initialContext; + + public static rmiiI rmiiIPOA; + + public static void main(String[] av) + { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + rmiiIPOA = (rmiiI) + U.lookupAndNarrow(C.rmiiSL, rmiiI.class, initialContext); + + U.sop("CLIENT.fooA: " + rmiiIPOA.fooA((byte)5)); + rmiiIPOA.fooB(); + U.sop("CLIENT.fooB completed"); + + orb.shutdown(true); + + } catch (Exception e) { + U.sopUnexpectedException(main + " : ", e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } + + //////////////////////////////////////////////////// + // + // ORBInitializer interface implementation. + // + + public void pre_init(ORBInitInfo info) + { + } + + public void post_init(ORBInitInfo info) + { + // register the interceptors. + try { + info.add_client_request_interceptor(this); + } catch (org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName e) { + throw new org.omg.CORBA.INTERNAL(); + } + U.sop("ORBInitializer.post_init completed"); + } + + //////////////////////////////////////////////////// + // + // implementation of the Interceptor interface. + // + + public String name() + { + return "ClientInterceptor"; + } + + public void destroy() + { + } + + //////////////////////////////////////////////////// + // + // implementation of the ClientInterceptor interface. + // + + public void send_request(ClientRequestInfo ri) throws ForwardRequest + { + U.sop("send_request called : " + ri.operation()); + } + + public void send_poll(ClientRequestInfo ri) + { + U.sop("send_poll called : " + ri.operation()); + } + + public void receive_reply(ClientRequestInfo ri) + { + String opName = ri.operation(); + U.sop("receive_reply.opName: " + opName); + + if ( ! (opName.equals("fooA") || opName.equals("fooB")) ) { + return; + } + + Class riClass = ri.getClass(); + MessageMediatorImpl cri; + try { + Field riMember = riClass.getDeclaredField("messageMediator"); + riMember.setAccessible(true); + cri = (MessageMediatorImpl) riMember.get(ri); + } catch (Throwable e) { + e.printStackTrace(System.out); + throw new RuntimeException("impl class instrospection failed", e); + } + + // fooA.buffer: [header + padding + body (1 byte)] + // fooA.buffer: [header + body (1 byte)] + + // get header size + int size = cri.getReplyHeader().getSize(); + U.sop("reply message size: " + size); + + if (opName.equals("fooA")) { + if (size != 41) { + throw new RuntimeException("header padding error"); + } + } else { // opName == fooB + if (size != 34) { + throw new RuntimeException("header padding error"); + } + } + } + + public void receive_exception(ClientRequestInfo ri) throws ForwardRequest + { + U.sop("receive_exception called : " + ri.operation()); + } + + public void receive_other(ClientRequestInfo ri) throws ForwardRequest + { + U.sop("receive_other called : " + ri.operation()); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/ColocatedClientServer.java b/functional-tests/src/test/java/corba/giopheaderpadding/ColocatedClientServer.java new file mode 100644 index 000000000..281a19468 --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/ColocatedClientServer.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 17 (Thu) 17:05:00 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 10:57:47 by Harold Carr. +// + +package corba.giopheaderpadding; + +import java.util.Properties; +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; +import corba.hcks.C; +import corba.hcks.U; + +public class ColocatedClientServer +{ + public static final String baseMsg = ColocatedClientServer.class.getName(); + public static final String main = baseMsg + ".main"; + + // REVISIT: FRAMEWORK DEVELOPMENT + // REMOVE THIS LATER. + // Necessary so calls not going through locals do not hang + // until I implement the reader thread/work split. + public static int fragmentSize = -1; + //public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String[] av) + { + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + Properties props = new Properties(); + props.setProperty("com.sun.corba.ee.ORBAllowLocalOptimization", + "true"); + orb = ORB.init(av, props); + U.sop(main + " : creating ORB."); + Server.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + Client.orb = orb; + + // Share a naming context between client and server + // so Util.isLocal is true. + + // Use the same ORB which has interceptor properties set. + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + Server.initialContext = initialContext; + Client.initialContext = initialContext; + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + Client.main(av); + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/GIOPHeaderPaddingTest.java b/functional-tests/src/test/java/corba/giopheaderpadding/GIOPHeaderPaddingTest.java new file mode 100644 index 000000000..4889df020 --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/GIOPHeaderPaddingTest.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:31:43 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:54:44 by Harold Carr. +// + +package corba.giopheaderpadding; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +import java.util.Properties; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; + +import corba.framework.*; + +public class GIOPHeaderPaddingTest extends CORBATest { + + public static final String thisPackage = + GIOPHeaderPaddingTest.class.getPackage().getName(); + + protected void doTest() throws Throwable { + if (test.Test.useJavaSerialization()) { + return; + } + + Controller orbd = createORBD(); + orbd.start(); + + Properties clientProps = Options.getClientProperties(); + clientProps.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "corba.giopheaderpadding.Client", "true"); + clientProps.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "corba.giopheaderpadding.Server", "true"); + clientProps.put(ORBConstants.GIOP_VERSION, "1.2"); + clientProps.put(ORBConstants.GIOP_12_BUFFMGR, "0"); // GROW + + Properties serverProps = Options.getServerProperties(); + serverProps.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "corba.giopheaderpadding.Server", "true"); + serverProps.put(ORBConstants.GIOP_VERSION, "1.2"); + serverProps.put(ORBConstants.GIOP_12_BUFFMGR, "0"); // GROW + + doTestType("Server", "Server", + "Client", "Client"); + + Controller colocatedClientServer = + createClient(thisPackage + ".ColocatedClientServer", + "colocatedClientServer"); + colocatedClientServer.start(); + colocatedClientServer.waitFor(); + colocatedClientServer.stop(); + + orbd.stop(); + } + + protected void doTestType(String serverMainClass, String serverTestName, + String clientMainClass, String clientTestName) + throws Throwable { + + Controller server = createServer(thisPackage + "." + serverMainClass, + serverTestName); + server.start(); + + Controller client = createClient(thisPackage + "." + clientMainClass, + clientTestName); + client.start(); + client.waitFor(); + client.stop(); + + server.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/ServantLocator.java b/functional-tests/src/test/java/corba/giopheaderpadding/ServantLocator.java new file mode 100644 index 000000000..6822651d4 --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/ServantLocator.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 07 (Tue) 16:29:22 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 11:13:27 by Harold Carr. +// + +package corba.giopheaderpadding; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.PortableServer.ForwardRequest; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; + +import corba.hcks.U; + +public class ServantLocator extends org.omg.CORBA.LocalObject + implements org.omg.PortableServer.ServantLocator { + + public static final String baseMsg = ServantLocator.class.getName(); + + public ServantLocator() {} + + public Servant preinvoke(byte[] oid, POA poa, String operation, + CookieHolder cookieHolder) + throws ForwardRequest { + + String soid = new String(oid); + U.sop(baseMsg + ".preinvoke " + soid); + + Servant servant = null; + try { + servant = + (Servant)javax.rmi.CORBA.Util.getTie(new rmiiIServantPOA()); + } catch (Exception e) { + U.sopUnexpectedException(baseMsg, e); + } + return servant; + } + + public void postinvoke(byte[] oid, POA poa, String operation, + java.lang.Object cookie, Servant servant) + { + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/Server.java b/functional-tests/src/test/java/corba/giopheaderpadding/Server.java new file mode 100644 index 000000000..0e6d8b019 --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/Server.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:28:12 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 11:12:48 by Harold Carr. +// + +package corba.giopheaderpadding; + +import javax.naming.InitialContext; + +import org.omg.CORBA.Policy; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +import corba.framework.Controller; +import corba.framework.Options; +import corba.hcks.C; +import corba.hcks.U; + +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.impl.protocol.MessageMediatorImpl; + +import java.lang.reflect.*; +import org.omg.PortableInterceptor.*; + +public class Server extends org.omg.CORBA.LocalObject + implements ORBInitializer, ServerRequestInterceptor { + + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + public static final String thisPackage = + Server.class.getPackage().getName(); + + public static final String rmiiIServantPOA_Tie = + thisPackage + "._rmiiIServantPOA_Tie"; + + public static final String SLPOA = "SLPOA"; + + public static ORB orb; + public static InitialContext initialContext; + public static TransportManager transportManager; + public static POA rootPOA; + public static POA slPOA; + + public static void main(String[] av) { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = (ORB) ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + rootPOA = U.getRootPOA(orb); + rootPOA.the_POAManager().activate(); + + Policy[] policies = U.createUseServantManagerPolicies( + rootPOA, + ServantRetentionPolicyValue.NON_RETAIN); + + slPOA = U.createPOAWithServantManager( + rootPOA, SLPOA, policies, + new ServantLocator()); + + U.createRMIPOABind(C.rmiiSL, rmiiIServantPOA_Tie, slPOA, orb, + initialContext); + + U.sop(main + " ready"); + U.sop(Options.defServerHandshake); + System.out.flush(); + + synchronized (ColocatedClientServer.signal) { + ColocatedClientServer.signal.notifyAll(); + } + + orb.run(); + + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } + + // ORBInitializer interface implementation. + + public void pre_init(ORBInitInfo info) {} + + public void post_init(ORBInitInfo info) { + // register the interceptors. + try { + info.add_server_request_interceptor(this); + } catch (org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName e) { + throw new org.omg.CORBA.INTERNAL(); + } + U.sop("ORBInitializer.post_init completed"); + } + + // implementation of the Interceptor interface. + + public String name() { return "ServerInterceptor"; } + + public void destroy() {} + + // implementation of the ServerInterceptor interface. + + public void receive_request_service_contexts(ServerRequestInfo ri) + throws ForwardRequest { + + String opName = ri.operation(); + U.sop("receive_request_service_contexts.opName: " + opName); + + if ( ! (opName.equals("fooA") || opName.equals("fooB")) ) { + return; + } + + Class riClass = ri.getClass(); + MessageMediatorImpl cri; + try { + Field riMember = riClass.getDeclaredField("request"); + riMember.setAccessible(true); + cri = (MessageMediatorImpl) riMember.get(ri); + } catch (Throwable e) { + e.printStackTrace(System.out); + throw new RuntimeException("impl class instrospection failed", e); + } + + // fooA.buffer: [header + padding + body (1 byte)] + // fooA.buffer: [header + body (1 byte)] + + // get header size + int size = cri.getRequestHeader().getSize(); + U.sop("request message size: " + size); + + if (! ColocatedClientServer.isColocated) { + if (opName.equals("fooA")) { + if (size != 153) { + throw new RuntimeException("header padding error"); + } + } else { // opName == fooB + if (size != 146) { + throw new RuntimeException("header padding error"); + } + } + } else { + if (opName.equals("fooA")) { + if (size != 129) { + throw new RuntimeException("header padding error"); + } + } else { // opName == fooB + if (size != 126) { + throw new RuntimeException("header padding error"); + } + } + } + } + + public void receive_request(ServerRequestInfo ri) throws ForwardRequest { + U.sop("receive_request called : " + ri.operation()); + } + + public void send_reply(ServerRequestInfo ri) { + U.sop("send_reply called : " + ri.operation()); + } + + public void send_exception(ServerRequestInfo ri) throws ForwardRequest { + U.sop("send_exception called : " + ri.operation()); + } + + public void send_other(ServerRequestInfo ri) throws ForwardRequest { + U.sop("send_other called : " + ri.operation()); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/rmiiI.java b/functional-tests/src/test/java/corba/giopheaderpadding/rmiiI.java new file mode 100644 index 000000000..23c4ba670 --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/rmiiI.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:55:19 by Harold Carr. +// + +package corba.giopheaderpadding; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface rmiiI extends Remote { + byte fooA(byte x) throws RemoteException; + void fooB() throws RemoteException; +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/giopheaderpadding/rmiiIServantPOA.java b/functional-tests/src/test/java/corba/giopheaderpadding/rmiiIServantPOA.java new file mode 100644 index 000000000..c681ae6cd --- /dev/null +++ b/functional-tests/src/test/java/corba/giopheaderpadding/rmiiIServantPOA.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 11 (Sat) 10:45:48 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:56:52 by Harold Carr. +// + +package corba.giopheaderpadding; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; +import corba.hcks.U; + +public class rmiiIServantPOA extends PortableRemoteObject + implements rmiiI { + + public rmiiIServantPOA() throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + } + + public byte fooA(byte x) { + U.sop(x + ""); + return x; + } + + public void fooB() { + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/C.java b/functional-tests/src/test/java/corba/hcks/C.java new file mode 100644 index 000000000..bac620c68 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/C.java @@ -0,0 +1,345 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 08 (Wed) 20:53:55 by Harold Carr. +// Last Modified : 2003 Dec 16 (Tue) 15:20:45 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.Any; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.ORB; +import org.omg.CORBA.UNKNOWN; + +import org.omg.CORBA.portable.UnknownException; + +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.CurrentHelper; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.Hashtable; +import java.util.Properties; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class C +{ + // Custom classes. + + public static String MyPOAORB = + C.class.getPackage().getName() + ".MyPOAORB"; + public static String MyORBInitializer = + C.class.getPackage().getName() + ".MyORBInitializer"; + + // Names for references in naming. + + public static final String rmiiI1 = "rmiiI1"; + public static final String rmiiI2 = "rmiiI2"; + public static final String rmiiSA = "rmiiSA"; + public static final String rmiiSL = "rmiiSL"; + + public static String idlHEADERI = "idlHEADERI"; + public static String idlStaticPOA = "idlStaticPOA"; + public static String idlDynamicPOA = "idlDynamicPOA"; + public static String idlStatic = "idlStatic"; + public static String idlStaticForDisconnect = "idlStaticForDisconnect"; + public static String idlStaticTie = "idlStaticTie"; + public static String idlDynamic = "idlDynamic"; + public static String idlSAI1 = "idlSAI1"; + public static String idlSAI2 = "idlSAI2"; + public static String idlSAIRaiseObjectNotExistInIncarnate = + "idlSAIRaiseObjectNotExistInIncarnate"; + public static String idlSAIRaiseSystemExceptionInIncarnate = + "idlSAIRaiseSystemExceptionInIncarnate"; + public static String idlSLI1 = "idlSLI1"; + public static String idlSLI2 = "idlSLI2"; + public static String idlAlwaysForward = "idlAlwaysForward"; + public static String idlAlwaysForwardedToo = "idlAlwaysForwardedToo"; + + public static String idlNonExistentDefaultServant = + "idlNonExistentDefaultServant"; + + public static String sendRecursiveType = "sendRecursiveType"; + + public static String idlControllerStatic = "idlControllerStatic"; + + // Operation/method names. + + public static String ServantActivator = "ServantActivator"; + public static String raiseForwardRequestInIncarnate = + "raiseForwardRequestInIncarnate"; + public static String raiseObjectNotExistInIncarnate = + "raiseObjectNotExistInIncarnate"; + public static String raiseSystemExceptionInIncarnate = + "raiseSystemExceptionInIncarnate"; + + public static String ServantLocator = "ServantLocator"; + public static String raiseForwardRequestInPreinvoke = + "raiseForwardRequestInPreinvoke"; + public static String raiseObjectNotExistInPreinvoke = + "raiseObjectNotExistInPreinvoke"; + public static String raiseSystemExceptionInPreinvoke = + "raiseSystemExceptionInPreinvoke"; + public static String raiseSystemExceptionInPostinvoke = + "raiseSystemExceptionInPostinvoke"; + public static String raiseUserInServantThenSystemInPOThenSE = + "raiseUserInServantThenSystemInPOThenSE"; + public static String raiseSystemInServantThenPOThenSE = + "raiseSystemInServantThenPOThenSE"; + + public static String throwThreadDeathInReceiveRequestServiceContexts = + "throwThreadDeathInReceiveRequestServiceContexts"; + public static String throwThreadDeathInPreinvoke = + "throwThreadDeathInPreinvoke"; + public static String throwThreadDeathInReceiveRequest = + "throwThreadDeathInReceiveRequest"; + public static String throwThreadDeathInServant = + "throwThreadDeathInServant"; + public static String throwThreadDeathInPostinvoke = + "throwThreadDeathInPostinvoke"; + public static String throwThreadDeathInSendReply = + "throwThreadDeathInSendReply"; + public static String throwThreadDeathInServantThenSysInPostThenSysInSendException = + "throwThreadDeathInServantThenSysInPostThenSysInSendException"; + + public static String sPic1 = "sPic1"; + public static String sPic2 = "sPic2"; + + public static String makeColocatedCallFromServant = + "makeColocatedCallFromServant"; + public static String colocatedCallFromServant = + "colocatedCallFromServant"; + + public static String sayHello = "sayHello"; + public static String sendBytes = "sendBytes"; + public static String sendOneObject = "sendOneObject"; + public static String sendTwoObjects = "sendTwoObjects"; + public static String returnObjectFromServer= + "returnObjectFromServer"; + + public static String syncOK = "syncOK"; + public static String _get_interface_def = "_get_interface_def"; + public static String _is_a = "_is_a"; + public static String _is_local = "_is_local"; + public static String _non_existent = "_non_existent"; + public static String asyncOK = "asyncOK"; + public static String throwUserException = "throwUserException"; + public static String throwSystemException = "throwSystemException"; + public static String throwUnknownException = "throwUnknownException"; + public static String throwUNKNOWN = "throwUNKNOWN"; + public static String raiseSystemExceptionInSendReply = + "raiseSystemExceptionInSendReply"; + public static String testEffectiveTarget1 = "testEffectiveTarget1"; + public static String testEffectiveTarget2 = "testEffectiveTarget2"; + public static String sendValue = "sendValue"; + public static String object_to_string = "object_to_string"; + public static String isIdenticalWithSavedIOR = + "isIdenticalWithSavedIOR"; + + + // Controller actions. + + public static String disconnectRidlStaticServant = + "disconnectRidlStaticServant"; + + // Misc. + + public static String UTF8 = "UTF8"; + public static String idlStaticStringified = "idlStaticStringified"; + public static String helloWorld = "hello world..."; + + public static int DEFAULT_FRAGMENT_SIZE = 32; + public static String GIOP_VERSION_1_1 = "1.1"; + public static String GIOP_VERSION_1_2 = "1.2"; + public static String BUFFMGR_STRATEGY_GROW = "0"; + public static String BUFFMGR_STRATEGY_STREAM = "2"; + + public static final int minorCodeForTestExceptions = -45; + + public static String rmiiColocatedCallResult = + "makeColocatedCallFromServant colocatedCallFromServant makeColocatedCallFromServant makeColocatedCallFromServant makeColocatedCallFromServant makeColocatedCallFromServant makeColocatedCallFromServant"; + + public static String idlSAI1ColocatedCallResult = + "makeColocatedCallFromServant idlSAI2 colocatedCallFromServant idlSAI2 -- makeColocatedCallFromServant idlSAI2"; + + public static String idlSLI1ColocatedResult = + "makeColocatedCallFromServant idlSLI2 colocatedCallFromServant idlSLI1 -- makeColocatedCallFromServant idlSLI2"; + + // + // Initialization. + // + + public static ORB createORB(String[] av, int fragmentSize) + { + return createORB(av, + GIOP_VERSION_1_2, + (fragmentSize > 0 ? BUFFMGR_STRATEGY_STREAM : + BUFFMGR_STRATEGY_GROW), + fragmentSize); + } + + public static ORB createORB(String [] av, + String giopVersion, + String buffMgrStrategy, + int fragmentSize) + { + Properties props = new Properties(); + props.put(U.ORBClass, MyPOAORB); + props.put(U.ORBInitializerClass + "." + MyORBInitializer, "ignored"); + + props.put(ORBConstants.GIOP_VERSION, giopVersion); + props.put(ORBConstants.GIOP_11_BUFFMGR, buffMgrStrategy); + props.put(ORBConstants.GIOP_12_BUFFMGR, buffMgrStrategy); + if (fragmentSize > 0) { + props.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize); + } + + return ORB.init(av, props); + } + + public static InitialContext createInitialContext(ORB orb) + throws + NamingException + { + Hashtable env = new Hashtable(); + env.put(U.javaNamingCorbaOrb, orb); + return new InitialContext(env); + } + + // + // Colocation factoring. + // + + public static String makeColocatedCallFromServant(String name, + ORB orb, + String delegator) + { + String result = null; + try { + result = U.getPOACurrentInfo(orb); + + idlSMI ridlSMI = null; + ridlSMI = idlSMIHelper.narrow(U.resolve(name, orb)); + result = doCall(ridlSMI, result, orb); + + } catch (Exception e) { + U.sopUnexpectedException(delegator + "." + + C.makeColocatedCallFromServant, + e); + } + return result; + } + + private static String doCall(idlSMI ridlSMI, String resultSoFar, ORB orb) + throws + Exception + { + String result = ridlSMI.colocatedCallFromServant(resultSoFar); + String info = U.getPOACurrentInfo(orb); + return info + " " + result; + } + + public static String colocatedCallFromServant(String a, + ORB orb, + String delegator) + { + String result = ""; + try { + String now = U.getPOACurrentInfo(orb); + result = now + " -- " + a; + } catch (Exception e) { + U.sopUnexpectedException(delegator + "." + + C.colocatedCallFromServant, + e); + } + return result; + } + + public static void throwUserException(String message) + throws + idlExampleException + { + throw new idlExampleException(message); + } + + public static void throwSystemException(String message) + { + throw new IMP_LIMIT(message, + minorCodeForTestExceptions, + CompletionStatus.COMPLETED_NO); + + } + + public static void throwUnknownException(String message) + { + throw new UnknownException(new idlExampleException(message)); + } + + public static void throwUNKNOWN(String message) + { + throw new UNKNOWN(message, + minorCodeForTestExceptions, + CompletionStatus.COMPLETED_NO); + } + + // + // Utility to help server-side PICurrent testing. + // + + public static boolean testAndIncrementPICSlot(boolean ensure, + String message, + int id, + int shouldBe, + ORB orb) + { + Current piCurrent = null; + try { + piCurrent = + CurrentHelper.narrow( + orb.resolve_initial_references(U.PICurrent)); + } catch (org.omg.CORBA.ORBPackage.InvalidName e) { + U.sopShouldNotSeeThis("testAndIncrementPICSlot"); + } + return testAndIncrementPICSlot(ensure, message, + id, shouldBe, piCurrent); + } + + public static boolean testAndIncrementPICSlot(boolean ensure, + String message, + int id, + int shouldBe, + Current piCurrent) + { + try { + Any any = piCurrent.get_slot(id); + if (U.isTkLong(any)) { + int currentValue = any.extract_long(); + if (currentValue == shouldBe) { + any.insert_long(++currentValue); + piCurrent.set_slot(id, any); + return true; + } + } + if (ensure) { + U.sopShouldNotSeeThis(message); + } + } catch (org.omg.PortableInterceptor.InvalidSlot e) { + U.sopShouldNotSeeThis("testAndIncrementPICSlot"); + } + return false; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/Client.java b/functional-tests/src/test/java/corba/hcks/Client.java new file mode 100644 index 000000000..e56ea27e0 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/Client.java @@ -0,0 +1,1451 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2003 Dec 16 (Tue) 15:43:37 by Harold Carr. +// + +// NOTE: all invocations occur in pairs. +// The first is direct, making it easy to step into the code using a debugger. +// The second uses the test framework for automatic testing. + +package corba.hcks; + +import java.rmi.MarshalException; + +import corba.framework.Controller; + +// +// IDL imports. +// + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.ORB; +import org.omg.CORBA.PERSIST_STORE; +import org.omg.CORBA.SystemException; +import org.omg.DynamicAny.DynAny; +import org.omg.DynamicAny.DynAnyFactory; +import org.omg.DynamicAny.DynAnyFactoryHelper; + + +// +// RMI-IIOP imports. +// + + +// JRMP +//import java.rmi.Naming; +// IIOP +import javax.naming.InitialContext; + +// +// Imports for specific tests. +// + +import org.omg.CORBA.Any; +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.OBJ_ADAPTER; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.Encoding; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ForwardRequestHelper; +import org.omg.PortableInterceptor.Current; + + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.presentation.rmi.StubWrapper; + + +// + + +public class Client +{ + static { + // System.setProperty( "corba.test.junit.helper.debug", "true" ) ; + } + + public static String testName = Client.class.getName() ; + + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static String giopVersion = C.GIOP_VERSION_1_2; + public static String buffMgrStategy = C.BUFFMGR_STRATEGY_STREAM; + public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated; + + public static idlHEADERI ridlHEADERI; + + public static rmiiI rrmiiI1; + public static rmiiI rrmiiI2; + public static rmiiI rrmiiSA; + public static rmiiI rrmiiSL; + + public static idlI ridlStaticPOA; + public static idlI ridlDynamicPOA; + public static idlI ridlStaticPOAStringified; + public static idlI ridlStatic; + public static idlI ridlStaticForDisconnect; + public static idlI ridlStaticTie; + public static idlI ridlDynamic; + public static idlI ridlStaticStringified; + public static idlSAI ridlSAI1; + public static idlSAI ridlSAI2; + public static idlSAI ridlSAIRaiseObjectNotExistInIncarnate; + public static idlSAI ridlSAIRaiseSystemExceptionInIncarnate; + public static idlSLI ridlSLI1; + public static idlSLI ridlAlwaysForward; + public static idlSAI ridlNonExistentDefaultServant; + + public static sendRecursiveType rsendRecursiveType; + + public static idlControllerI ridlControllerStatic; + + public static boolean testExpect = false; + public static boolean allowLocalOptimization ; + + // debugOn/Off were added for debugging a ServiceContext scMap aliasing bug. + private static void debugOn( String msg ) { + com.sun.corba.ee.spi.orb.ORB spiOrb = + com.sun.corba.ee.spi.orb.ORB.class.cast( orb ) ; + System.out.println( "DEBUGGING ON: " + msg ) ; + spiOrb.setDebugFlags( "serviceContext", "interceptor", "subcontract" ) ; + } + + private static void debugOff() { + com.sun.corba.ee.spi.orb.ORB spiOrb = + com.sun.corba.ee.spi.orb.ORB.class.cast( orb ) ; + spiOrb.clearDebugFlags( "serviceContext", "interceptor", "subcontract" ) ; + System.out.println( "DEBUGGING OFF" ) ; + } + + public static void main(String[] av) + { + try { + U.initialize( testName ) ; + U.setDisplayErrorsWhenTheyHappen(true); + + if (ColocatedClientServer.isColocated) { + isColocated = true; + } else { + isColocated = false; + orb = C.createORB(av, giopVersion, + buffMgrStategy, fragmentSize); + // Use the same ORB which has interceptor properties set. + // This obviates the need to set system properties. + initialContext = C.createInitialContext(orb); + } + + // orb is either initilized by the createORB call, or it was + // initialized before main was called in the ColocatedClientServer case. + // Set the flag to true, as that is the current behavior of is_local. + allowLocalOptimization = true ; + + lookupReferences(); + + runTests(); + } catch (Exception e) { + U.sopUnexpectedException(main + " : ", e); + } finally { + U.done() ; + } + + if (U.hasError()) { + System.exit(1); + } else { + System.exit(Controller.SUCCESS); + } + } + + public static void runTests() + throws + Exception + { + // Get an active ByteBuffer count (ByteBuffers actively in use by ORB) + com.sun.corba.ee.spi.orb.ORB spiOrb = (com.sun.corba.ee.spi.orb.ORB)orb; + int startCount = spiOrb.getByteBufferPool().activeCount(); + + testExpect(); // Test the test framework. + + testMisc(); + + testInterceptors(); + + testServantActivator(); + + testServantLocator(); + + testSynchronousInvocations(); + + testSpecialMethods(); + + testOneWayInvocations(); + + testUserExceptions(); + + testSystemExceptions(); + + testUnknownExceptions(); + + testDSIInvocations(); + + // These next two caused my debugger to fail at one time. + testRMIIIOP(); + testThreadDeathHandling(); + + testValueTypes(); // This does fragmentation even with grow - why? + + // report ByteBuffer active count numbers + System.out.println("Start ByteBuffer active count: " + startCount); + int currentCount = spiOrb.getByteBufferPool().activeCount(); + System.out.println("End ByteBuffer active count: " + currentCount); + System.out.println("Difference between start & end ByteBuffer count: " + + (currentCount - startCount)); + } + + public static void lookupReferences() + throws + Exception + { + // IDL refs. + + ridlHEADERI = idlHEADERIHelper.narrow(U.resolve(C.idlHEADERI, orb)); + + ridlStaticPOA = idlIHelper.narrow(U.resolve(C.idlStaticPOA, orb)); + ridlDynamicPOA = idlIHelper.narrow(U.resolve(C.idlDynamicPOA, orb)); + ridlStatic = idlIHelper.narrow(U.resolve(C.idlStatic, orb)); + ridlStaticForDisconnect = + idlIHelper.narrow(U.resolve(C.idlStaticForDisconnect, orb)); + ridlStaticTie = idlIHelper.narrow(U.resolve(C.idlStaticTie, orb)); + ridlDynamic = idlIHelper.narrow(U.resolve(C.idlDynamic, orb)); + + ridlStaticPOAStringified = + idlIHelper.narrow(orb.string_to_object(orb.object_to_string(ridlStaticPOA))); + ridlStaticStringified = + idlIHelper.narrow(orb.string_to_object(orb.object_to_string(ridlStatic))); + + ridlSAI1 = idlSAIHelper.narrow(U.resolve(C.idlSAI1, orb)); + ridlSAI2 = idlSAIHelper.narrow(U.resolve(C.idlSAI2, orb)); + + ridlSAIRaiseObjectNotExistInIncarnate = + idlSAIHelper.narrow(U.resolve(C.idlSAIRaiseObjectNotExistInIncarnate, orb)); + + ridlSAIRaiseSystemExceptionInIncarnate = + idlSAIHelper.narrow(U.resolve(C.idlSAIRaiseSystemExceptionInIncarnate, orb)); + + ridlSLI1 = idlSLIHelper.narrow(U.resolve(C.idlSLI1, orb)); + + ridlNonExistentDefaultServant = + idlSAIHelper.narrow(U.resolve(C.idlNonExistentDefaultServant, orb)); + + rsendRecursiveType = + sendRecursiveTypeHelper.narrow(U.resolve(C.sendRecursiveType, orb)); + + ridlControllerStatic = + idlControllerIHelper.narrow(U.resolve(C.idlControllerStatic, orb)); + + // RMI-IIOP refs. + + rrmiiI1 = (rmiiI) + U.lookupAndNarrow(C.rmiiI1, rmiiI.class, initialContext); + rrmiiI2 = (rmiiI) + U.lookupAndNarrow(C.rmiiI2, rmiiI.class, initialContext); + rrmiiSA = (rmiiI) + U.lookupAndNarrow(C.rmiiSA, rmiiI.class, initialContext); + rrmiiSL = (rmiiI) + U.lookupAndNarrow(C.rmiiSL, rmiiI.class, initialContext); + } + + public static void refreshIdlAlwaysForward () + throws + Exception + { + ridlAlwaysForward = + idlSLIHelper.narrow(U.resolve(C.idlAlwaysForward, orb)); + } + + // + // Misc. + // + + public static void testMisc() + throws + Exception + { + HEADER("testMisc"); + + // -------------------------------------------------- + + org.omg.CORBA.Object o =ridlStaticPOA.getAndSaveUnknownORBVersionIOR(); + boolean result = ridlStaticPOA.isIdenticalWithSavedIOR(o); + if (! result) { + throw new RuntimeException(C.isIdenticalWithSavedIOR); + } + /* + * Gets NoSuchMethodException isIdenticalWithSavedIOR + U.expect(U.result, Boolean.valueOf(true), + ridlStaticPOA, C.isIdenticalWithSavedIOR, o); + */ + + // -------------------------------------------------- + // I know I have fragments set to 32 bytes. + // So try to identify the fragments on the wire by their + // contents. + + int size = 10000; + byte[] bigBytes = new byte[size]; + byte j = 0x41; // 'A' + // 32 == fragment size + // 12 == GIOP header + for (int i = 0; i < size; i+= 32 - 15) { + bigBytes[i] = j++; + if (j == 0x5a) { // A-Z + j = 0x61; // 'a' + } else if (j == 0x7a) { // a-z + j = 0x41; // 'A' + } + } + rrmiiI1.sendBytes(bigBytes); + + // -------------------------------------------------- + + // -------------------------------------------------- + + // Direct marshaling works, but not through Any. + recursiveType rType = + new recursiveType("a","b", new recursiveType[0]); + rsendRecursiveType.sendAsType(rType); + Any rTypeAny = orb.create_any(); + recursiveTypeHelper.insert(rTypeAny, rType); + // Getting exception when marshaling Any. + //***** rsendRecursiveType.sendAsAny(rTypeAny); + + + // This used to throw a class cast exception. + DynAnyFactory dynAnyFactory = + DynAnyFactoryHelper.narrow( + orb.resolve_initial_references("DynAnyFactory")); + DynAny dynAny = dynAnyFactory.create_dyn_any(orb.create_any()); + try { + orb.object_to_string(dynAny); + U.sopShouldNotSeeThis("object_to_string did not throw exception"); + } catch (MARSHAL t) { + // Expected. + U.sop(t); + } catch (Throwable t) { + U.sopShouldNotSeeThis("object_to_string threw wrong exception: " + + t); + } + /* REVISIT + This does not find object_to_string (NoSuchMethodException). + U.expect(U.exception, new MARSHAL(), + orb, C.object_to_string, dynAny); + */ + + // -------------------------------------------------- + // disconnect then do non_existent. + // This caused null pointer at one time. + + ridlControllerStatic.action(C.disconnectRidlStaticServant); + U.sop(ridlStaticForDisconnect._non_existent()); + U.expect(U.result, Boolean.valueOf(true), + ridlStaticForDisconnect, C._non_existent); + + try { + ridlStaticForDisconnect.syncOK(C.idlStaticForDisconnect); + } catch (Throwable t) {} + U.expect(U.exception, new OBJECT_NOT_EXIST(), + ridlStaticForDisconnect, C.syncOK, C.idlStaticForDisconnect); + + // -------------------------------------------------- + // Similar to above disconnect case, but poa-based. + // This caused null pointer at one time. + // Then later it was changed to throw an adapter exception + // since the default servant is not set. + + try { + ridlNonExistentDefaultServant._non_existent(); + } catch (Throwable t) {} + U.expect(U.exception, new OBJ_ADAPTER(), + ridlNonExistentDefaultServant, C._non_existent); + + // -------------------------------------------------- + // Kill server then step through following lines + // to observe bad connection caching. + + try { ridlStaticPOA.syncOK(C.idlStaticPOA); } catch (Throwable t) {} + try { ridlStaticPOA.syncOK(C.idlStaticPOA); } catch (Throwable t) {} + try { ridlStaticPOA.syncOK(C.idlStaticPOA); } catch (Throwable t) {} + try { ridlStaticPOA.syncOK(C.idlStaticPOA); } catch (Throwable t) {} + + + // -------------------------------------------------- + // Cause a runtime exception to happen and be handled + // by PI in stub's _releaseReply + // KMC: I have removed this test since I have removed the + // old inheritance-based interceptor facility. + //MyPOAORB.throwRuntimeExceptionInSendingRequestServiceContexts = true; + //try { + //ridlStaticPOA.syncOK(C.idlStaticPOA); + //} catch (Throwable t) {} + //U.expect(U.exception, new RuntimeException(), + //ridlStaticPOA, C.syncOK, + //C.idlStaticPOA); + //MyPOAORB.throwRuntimeExceptionInSendingRequestServiceContexts = false; + + + // -------------------------------------------------- + // On server side, _is_a can be any arbitrary user code. + // Therefore, client interceptors, if present, should execute + // to make sure proper transactions and security. + + ridlDynamicPOA._is_a("foo"); + + + // -------------------------------------------------- + // Uses the ORBSingleton's internal ORB to handle + // embedded object references. + + CodecFactory codecFactory = + CodecFactoryHelper.narrow( + orb.resolve_initial_references("CodecFactory")); + Encoding encoding = new Encoding((short)0, (byte)1, (byte)2); + Codec codec = codecFactory.create_codec(encoding); + ORB orbSingleton = ORB.init(); + Any any = orbSingleton.create_any(); + ForwardRequest fr = + new ForwardRequest(orb.resolve_initial_references("NameService")); + ForwardRequestHelper.insert(any, fr); + byte[] encoded = codec.encode(any); + any = codec.decode(encoded); + fr = ForwardRequestHelper.extract(any); + NamingContext nc = NamingContextHelper.narrow(fr.forward); + U.sop(nc.resolve(U.makeNameComponent(C.idlStaticPOA))); + + // -------------------------------------------------- + + for (int i = 0; i < 3; ++i) { + // This caused a client hang at one time in the rmi-iiop/poa cases only. + try { + // debugOn( "rrmiiSA.returnObjectFromServer" ) ; + rrmiiSA.returnObjectFromServer(false); + // debugOff() ; + U.sopShouldNotSeeThis() ; + } catch (Throwable t) { + U.sop(t); + /* Get a different exception now: + checkRmiMarshalException( + new NotSerializableException(), + // This happens when server side is fragmenting. + // The server just ends the fragment so the client + // side orb raises this exception. + new MARSHAL(ORBUtilSystemException.END_OF_STREAM, + CompletionStatus.COMPLETED_NO), t); + */ + } + + /* + REVISIT - says no such method. + U.expect(U.exception, new BAD_PARAM(), + rrmiiSA, C.returnObjectFromServer, Boolean.valueOf(false)); + */ + + // This caused server threads to wait forever for input when streaming. + try { + rrmiiSA.sendOneObject(new NonSerializableObject()); + U.sopShouldNotSeeThis() ; + } catch (Throwable t) { + U.sop(t); + /* checkRmiMarshalException(new NotSerializableException(), null, t); */ + } + + try { + rrmiiSA.sendTwoObjects(new SerializableObject(), + new NonSerializableObject()); + U.sopShouldNotSeeThis() ; + } catch (Throwable t) { + U.sop(t); + /* checkRmiMarshalException(new NotSerializableException(), null, t); */ + } + } + } + + // + // ThreadDeath + // + + public static void testThreadDeathHandling() + throws + Exception + { + HEADER("testThreadDeathHandling"); + + try { + ridlSLI1. + throwThreadDeathInReceiveRequestServiceContexts(C.throwThreadDeathInReceiveRequestServiceContexts); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + try { + ridlSLI1. + throwThreadDeathInPreinvoke(C.throwThreadDeathInPreinvoke); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + try { + ridlSLI1. + throwThreadDeathInReceiveRequest(C.throwThreadDeathInReceiveRequest); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + try { + ridlSLI1. + throwThreadDeathInServant(C.throwThreadDeathInServant); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + try { + ridlSLI1. + throwThreadDeathInPostinvoke(C.throwThreadDeathInPostinvoke); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + try { + ridlSLI1. + throwThreadDeathInSendReply(C.throwThreadDeathInSendReply); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + try { + ridlSLI1. + throwThreadDeathInServantThenSysInPostThenSysInSendException( + C.throwThreadDeathInServantThenSysInPostThenSysInSendException); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t);} + + + try { + rrmiiI1.throwThreadDeathInServant(C.throwThreadDeathInServant); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t); } + try { + rrmiiSA.throwThreadDeathInServant(C.throwThreadDeathInServant); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t); } + try { + rrmiiSL.throwThreadDeathInServant(C.throwThreadDeathInServant); + U.sopShouldNotSeeThis(); + } catch (Throwable t) { U.sop(t); } + } + + // + // Interceptors + // + + public static void testInterceptors() + throws + Exception + { + HEADER("testInterceptors"); + + // + // This tests that service contexts added by a reply interceptor + // which then raises a system exception should still be seen. + // + + try { + ridlStaticPOA.raiseSystemExceptionInSendReply(); + } catch (Throwable t) {} + U.expect(U.exception, new IMP_LIMIT(), + ridlStaticPOA, C.raiseSystemExceptionInSendReply); + + // + // Tests server-side PICurrent (and some client-side too). + // + + Current piCurrent = U.getPICurrent(orb); + Any any = orb.create_any(); + any.insert_long(0); + piCurrent.set_slot(SsPicInterceptor.sPic1ASlotId, any); + // Do not depend on deep copy. + any = orb.create_any(); + any.insert_long(0); + piCurrent.set_slot(SsPicInterceptor.sPic1BSlotId, any); + // debugOn( "null,ridlSLI1" ) ; + U.expect(U.result, null, // REVISIT: really expecting Void.TYPE + ridlSLI1, C.sPic1); + // debugOff() ; + // The server's sets to these same slot ids should not + // effect the client. + C.testAndIncrementPICSlot(true, "client", + SsPicInterceptor.sPic1ASlotId, 0, piCurrent); + + // + // test effective_target (this was used when converting from + // a type-specific version to a more efficient generic version + // of the effective_target implementation. + // + + ridlStaticPOA.testEffectiveTarget1(); + } + + // + // ServantActivator + // + + public static void testServantActivator() + throws + Exception + { + HEADER(C.ServantActivator); + + + U.sop(rrmiiSA.sayHello()); + U.expect(U.result, C.helloWorld, + rrmiiSA, C.sayHello); + + + + + U.sop(ridlSAI1.raiseForwardRequestInIncarnate(C.raiseForwardRequestInIncarnate)); + U.expect(U.result, C.raiseForwardRequestInIncarnate, + ridlSAI1, C.raiseForwardRequestInIncarnate, + C.raiseForwardRequestInIncarnate); + + + + try { + ridlSAIRaiseObjectNotExistInIncarnate + .raiseObjectNotExistInIncarnate(""); + } catch (Throwable t) {} + U.expect(U.exception, new OBJECT_NOT_EXIST(), + ridlSAIRaiseObjectNotExistInIncarnate, + C.raiseObjectNotExistInIncarnate, + ""); + + + try { + ridlSAIRaiseSystemExceptionInIncarnate + .raiseSystemExceptionInIncarnate(""); + } catch (Throwable t) {} + U.expect(U.exception, new IMP_LIMIT(), + ridlSAIRaiseSystemExceptionInIncarnate, + C.raiseSystemExceptionInIncarnate, + ""); + + + U.sop(rrmiiSA.makeColocatedCallFromServant()); + // debugOn( "rmiiColocatedCallResult,makeColocatedCallFromServant" ) ; + U.expect(U.result, C.rmiiColocatedCallResult, + rrmiiSA, C.makeColocatedCallFromServant); + // debugOff() ; + + + + // Use "2" to avoid unnecessary ForwardRequest. + // debugOn( "ridlSAI2.makeColocatedCallFromServant" ) ; + U.sop(ridlSAI2.makeColocatedCallFromServant()); + // debugOff() ; + // debugOn( "idlSaIlColcatedCallResut,makeColocatedCallFromServant" ) ; + U.expect(U.result, C.idlSAI1ColocatedCallResult, + ridlSAI2, + C.makeColocatedCallFromServant); + // debugOff() ; + } + + // + // ServantLocator + // + + public static void testServantLocator() + throws + Exception + { + HEADER(C.ServantLocator); + + U.sop(rrmiiSL.sayHello()); + U.expect(U.result, C.helloWorld, + rrmiiSL, C.sayHello); + + + + U.sop(ridlSLI1.raiseForwardRequestInPreinvoke(C.raiseForwardRequestInPreinvoke)); + U.expect(U.result, C.raiseForwardRequestInPreinvoke, + ridlSLI1, C.raiseForwardRequestInPreinvoke, + C.raiseForwardRequestInPreinvoke); + + + try { + ridlSLI1.raiseObjectNotExistInPreinvoke(""); + } catch (Throwable t) {} + U.expect(U.exception, new OBJECT_NOT_EXIST(), + ridlSLI1, C.raiseObjectNotExistInPreinvoke, ""); + + + + try { + ridlSLI1.raiseSystemExceptionInPreinvoke(""); + } catch (Throwable t) {} + U.expect(U.exception, new IMP_LIMIT(), + ridlSLI1, C.raiseSystemExceptionInPreinvoke, ""); + + + try { + ridlSLI1.raiseSystemExceptionInPostinvoke( + C.raiseSystemExceptionInPostinvoke); + } catch (Throwable t) {} + U.expect(U.exception, new IMP_LIMIT(), + ridlSLI1, C.raiseSystemExceptionInPostinvoke, + C.raiseSystemExceptionInPostinvoke); + + + + try { + ridlSLI1.raiseSystemInServantThenPOThenSE(); + } catch (Throwable t) {} + U.expect(U.exception, new PERSIST_STORE(), + ridlSLI1, C.raiseSystemInServantThenPOThenSE); + + + + try { + ridlSLI1.raiseUserInServantThenSystemInPOThenSE(); + } catch (Throwable t) {} + U.expect(U.exception, new PERSIST_STORE(), + ridlSLI1, C.raiseUserInServantThenSystemInPOThenSE); + + + + + // debugOn( "rrmiiSL.makeColocatedCallFromServant" ) ; + U.sop(rrmiiSL.makeColocatedCallFromServant()); + // debugOff() ; + U.expect(U.result, C.rmiiColocatedCallResult, + rrmiiSL, C.makeColocatedCallFromServant); + + + + + U.sop(ridlSLI1.makeColocatedCallFromServant()); + U.expect(U.result, C.idlSLI1ColocatedResult, + ridlSLI1, C.makeColocatedCallFromServant); + } + + // + // RMI-IIOP + // + + public static void testRMIIIOP() + throws + Exception + { + HEADER("RMI-IIOP"); + + U.sop(rrmiiI1.sayHello()); + U.expect(U.result, C.helloWorld, + rrmiiI1, C.sayHello); + + U.sop(rrmiiI2.sayHello()); + U.expect(U.result, C.helloWorld, + rrmiiI2, C.sayHello); + + + byte[] bytes = new byte[100]; + U.sop(Integer.valueOf(rrmiiI1.sendBytes(bytes))); + U.expect(U.result, Integer.valueOf(100), + rrmiiI1, C.sendBytes, bytes); + + U.sop(rrmiiI1.sendOneObject(new java.util.Hashtable())); + /* + // REVISIT: + // Reflection code in U cannot find the method when given Hashtable. + Object object = new Object(); + U.expect(U.result, object, + rrmiiI1, C.sendOneObject, object); + */ + + /* + U.sop("equals self : " + rrmiiI1.equals(rrmiiI1)); + U.sop("equals same type : " + rrmiiI1.equals(rrmiiI2)); + U.sop("equals different type: " + rrmiiI1.equals(new Object())); + U.sop("null sendBytes : " + rrmiiI1.sendBytes(null)); + U.sop("small sendBytes : " + rrmiiI1.sendBytes(new byte[10])); + */ + } + + // + // syncOK + // + + public static void testSynchronousInvocations() + throws + Exception + { + HEADER(C.syncOK); + + U.sop(ridlStaticPOA.syncOK(C.idlStaticPOA)); + U.sop(doDynInvOfSyncOK(ridlStaticPOA, U.DII(C.idlStaticPOA))); + U.expect(U.result, idlPOAServant.baseMsg + " " + C.idlStaticPOA, + ridlStaticPOA, C.syncOK, C.idlStaticPOA); + // REVISIT - test DII + // REVISIT - add static method invocation to U.expect. + + + + U.sop(ridlDynamicPOA.syncOK(C.idlDynamicPOA)); + U.sop(doDynInvOfSyncOK(ridlDynamicPOA, U.DII(C.idlDynamicPOA))); + U.expect(U.result, U.DSI(C.idlDynamicPOA), + ridlDynamicPOA, C.syncOK, C.idlDynamicPOA); + // REVISIT - test DII + + + + U.sop(ridlStatic.syncOK(C.idlStatic)); + U.sop(doDynInvOfSyncOK(ridlStatic, U.DII(C.idlStatic))); + U.expect(U.result, idlStaticServant.baseMsg + " " + C.idlStatic, + ridlStatic, C.syncOK, C.idlStatic); + // REVISIT - test DII + + + + U.sop(ridlStaticTie.syncOK(C.idlStaticTie)); + U.expect(U.result, idlStaticServant.baseMsg + " " + C.idlStaticTie, + ridlStaticTie, C.syncOK, C.idlStaticTie); + + + + U.sop(ridlDynamic.syncOK(C.idlDynamic)); + U.sop(doDynInvOfSyncOK(ridlDynamic, U.DII(C.idlDynamic))); + U.expect(U.result, U.DSI(C.idlDynamic), + ridlDynamic, C.syncOK, C.idlDynamic); + // REVISIT - test DII + + + + U.sop(ridlStaticStringified.syncOK(C.idlStaticStringified)); + U.expect(U.result, + idlStaticServant.baseMsg + " " + C.idlStaticStringified, + ridlStaticStringified, C.syncOK, C.idlStaticStringified); + + } + + // + // Special methods. + // + + public static void testSpecialMethods() + throws + Exception + { + testIsLocal(); + testGetInterfaceDef(); + testIsA(); + testNonExistent(); + } + + public static void testIsLocal() + throws + Exception + { + // + // _is_local + // + // Note: the StubAdapter.isLocal checks are commented out because + // isLocal requires a stub as its argument, but dynamic stubs + // cannot be used with isLocal. + + HEADER(C._is_local); + + U.sop( StubAdapter.isLocal(ridlStaticPOA) ) ; + StubWrapper sw = new StubWrapper( ridlStaticPOA ) ; + U.expect(U.result, Boolean.valueOf(allowLocalOptimization && isColocated), + sw, "isLocal" ) ; + + U.sop( StubAdapter.isLocal(ridlStatic) ) ; + sw = new StubWrapper( ridlStatic ) ; + U.expect(U.result, Boolean.valueOf(allowLocalOptimization && isColocated), + sw, "isLocal" ) ; + + U.sop( StubAdapter.isLocal(rrmiiI1) ) ; + sw = new StubWrapper( (org.omg.CORBA.Object)rrmiiI1 ) ; + U.expect(U.result, Boolean.valueOf(allowLocalOptimization && isColocated), + sw, "isLocal" ) ; + //if (StubAdapter.isLocal((Stub)rrmiiI1) != false) { + //throw new Exception("should be false"); + //} + + U.sop( StubAdapter.isLocal(rrmiiSA) ) ; + sw = new StubWrapper( (org.omg.CORBA.Object)rrmiiSA ) ; + U.expect(U.result, Boolean.valueOf(allowLocalOptimization && isColocated), + sw, "isLocal" ) ; + //if (StubAdapter.isLocal((Stub)rrmiiSA) != false) { + //throw new Exception("should be false"); + //} + + U.sop( StubAdapter.isLocal(rrmiiSL) ) ; + sw = new StubWrapper( (org.omg.CORBA.Object)rrmiiSL ) ; + U.expect(U.result, Boolean.valueOf(allowLocalOptimization && isColocated), + sw, "isLocal" ) ; + //if (StubAdapter.isLocal((Stub)rrmiiSL) != false) { + //throw new Exception("should be false"); + //} + } + + public static void testGetInterfaceDef() + throws + Exception + { + // + // _get_interface_def + // + + HEADER(C._get_interface_def); + + getInterfaceDef(ridlStaticPOA, C.idlStaticPOA); + getInterfaceDef(ridlDynamicPOA, C.idlDynamicPOA); + getInterfaceDef(ridlStatic, C.idlStatic); + getInterfaceDef(ridlStaticTie, C.idlStaticTie); + getInterfaceDef(ridlDynamic, C.idlDynamic); + refreshIdlAlwaysForward(); + getInterfaceDef(ridlAlwaysForward, C.idlAlwaysForward); + } + + public static void testIsA() + throws + Exception + { + // + // _is_a + // + + HEADER(C._is_a); + + // REVISIT - make a call with a real repoID + + U.sop(ridlStaticPOA._is_a(C.idlStaticPOA)); + U.sop(ridlDynamicPOA._is_a(C.idlDynamicPOA)); + U.sop(ridlStatic._is_a(C.idlStatic)); + U.sop(ridlStaticTie._is_a(C.idlStaticTie)); + U.sop(ridlDynamic._is_a(C.idlDynamic)); + refreshIdlAlwaysForward(); + U.sop(ridlAlwaysForward._is_a(C.idlAlwaysForward)); + + U.expect(U.result, Boolean.valueOf(false), + ridlStaticPOA, C._is_a, C.idlDynamic); + U.expect(U.result, Boolean.valueOf(false), + ridlDynamicPOA, C._is_a, C.idlDynamicPOA); + U.expect(U.result, Boolean.valueOf(false), + ridlStatic, C._is_a, C.idlStatic); + U.expect(U.result, Boolean.valueOf(false), + ridlStaticTie, C._is_a, C.idlStaticTie); + U.expect(U.result, Boolean.valueOf(false), + ridlDynamic, C._is_a, C.idlDynamic); + refreshIdlAlwaysForward(); + U.expect(U.result, Boolean.valueOf(false), + ridlAlwaysForward, C._is_a, C.idlAlwaysForward); + } + + public static void testNonExistent() + throws + Exception + { + // + // _non_existent + // + + HEADER(C._non_existent); + + U.sop(ridlStaticPOA._non_existent()); + U.sop(ridlDynamicPOA._non_existent()); + U.sop(ridlStatic._non_existent()); + U.sop(ridlStaticTie._non_existent()); + U.sop(ridlDynamic._non_existent()); + refreshIdlAlwaysForward(); + U.sop(ridlAlwaysForward._non_existent()); + + U.expect(U.result, Boolean.valueOf(false), + ridlStaticPOA, C._non_existent); + U.expect(U.result, Boolean.valueOf(false), + ridlDynamicPOA, C._non_existent); + U.expect(U.result, Boolean.valueOf(false), + ridlStatic, C._non_existent); + U.expect(U.result, Boolean.valueOf(false), + ridlStaticTie, C._non_existent); + U.expect(U.result, Boolean.valueOf(false), + ridlDynamic, C._non_existent); + refreshIdlAlwaysForward(); + U.expect(U.result, Boolean.valueOf(false), + ridlAlwaysForward, C._non_existent); + } + + // + // asyncOK + // + + public static void testOneWayInvocations() + throws + Exception + { + HEADER(C.asyncOK); + + // Make this a large iteration to test for async memory leaks. + for ( int i = 0; i < 1; i++ ) { + byte[] data; + + data = new String(C.idlStaticPOA + " " + (i+1)).getBytes(C.UTF8); + ridlStaticPOA.asyncOK(data); + U.expect(U.result, null, + ridlStaticPOA, C.asyncOK, data); + + data = new String(C.idlDynamicPOA + " " + (i+1)).getBytes(C.UTF8); + ridlDynamicPOA.asyncOK(data); + U.expect(U.result, null, + ridlDynamicPOA, C.asyncOK, data); + + data = new String(C.idlStatic + " " + (i+1)).getBytes(C.UTF8); + ridlStatic.asyncOK(data); + U.expect(U.result, null, + ridlStatic, C.asyncOK, data); + + data = new String(C.idlStaticTie + " " + (i+1)).getBytes(C.UTF8); + ridlStaticTie.asyncOK(data); + U.expect(U.result, null, + ridlStaticTie, C.asyncOK, data); + + data = new String(C.idlDynamic + " " + (i+1)).getBytes(C.UTF8); + ridlDynamic.asyncOK(data); + U.expect(U.result, null, + ridlDynamic, C.asyncOK, data); + } + } + + // + // throwUserException + // + + public static void testUserExceptions() + throws + Exception + { + HEADER(C.throwUserException); + + throwUserException(ridlStaticPOA, C.idlStaticPOA); + throwUserException(ridlDynamicPOA, C.idlDynamicPOA); + throwUserException(ridlStatic, C.idlStatic); + throwUserException(ridlStaticTie, C.idlStaticTie); + throwUserException(ridlDynamic, C.idlDynamic); + } + + public static void testSystemExceptions() + throws + Exception + { + // + // throwSystemException + // + + HEADER(C.throwSystemException); + + // Revisit: if SystemException removed the Exception + // is still caught, but not in same scenario below in POA case + throwSystemException(ridlStaticPOA, C.idlStaticPOA); + throwSystemException(ridlDynamicPOA, C.idlDynamicPOA); + throwSystemException(ridlStatic, C.idlStatic); + throwSystemException(ridlStaticTie, C.idlStaticTie); + throwSystemException(ridlDynamic, C.idlDynamic); + } + + // + // Unknown + // + + public static void testUnknownExceptions() + throws + Exception + { + // + // throwUnknownException + // + + HEADER(C.throwUnknownException); + + throwUnknownException(ridlStaticPOA, C.idlStaticPOA); + throwUnknownException(ridlDynamicPOA, C.idlDynamicPOA); + throwUnknownException(ridlStatic, C.idlStatic); + throwUnknownException(ridlStaticTie, C.idlStaticTie); + throwUnknownException(ridlDynamic, C.idlDynamic); + + // + // throwUnknownException + // + + HEADER(C.throwUNKNOWN); + + throwUNKNOWN(ridlStaticPOA, C.idlStaticPOA); + throwUNKNOWN(ridlDynamicPOA, C.idlDynamicPOA); + throwUNKNOWN(ridlStatic, C.idlStatic); + throwUNKNOWN(ridlStaticTie, C.idlStaticTie); + throwUNKNOWN(ridlDynamic, C.idlDynamic); + } + + // + // Value types + // + + public static void testValueTypes() + throws + Exception + { + // + // sendValue + // + + HEADER(C.sendValue); + + // REVISIT - add U.expect + + idlValueTypeA idlValueTypeA; + idlValueTypeB idlValueTypeB = + new idlValueTypeBImpl((short)1, (short)2); + idlValueTypeC idlValueTypeC = + new idlValueTypeCImpl((short)1, (short)2, (short)3); + idlValueTypeD idlValueTypeD = + new idlValueTypeDImpl((short)1); + idlValueTypeE idlValueTypeE = + new idlValueTypeEImpl(); + int[] intSeq = new int[10000]; + byte[] octetArray = new byte[10000]; + + idlValueTypeA = ridlStaticPOA.sendValue(idlValueTypeB, + idlValueTypeB, + idlValueTypeC, + idlValueTypeD, + idlValueTypeE, + intSeq, + octetArray); + U.sop(idlValueTypeA); + U.sop(idlValueTypeA.equals((idlValueTypeA)idlValueTypeB)); + + /* + idlValueTypeA = ridlDynamicPOA.sendValue(idlValueTypeB, + idlValueTypeB, + idlValueTypeC, + idlValueTypeD, + idlValueTypeE, + intSeq, + octetArray); + U.sop(idlValueTypeA); + U.sop(idlValueTypeA.equals((idlValueTypeA)idlValueTypeB)); + */ + + idlValueTypeA = ridlStatic.sendValue(idlValueTypeB, + idlValueTypeB, + idlValueTypeC, + idlValueTypeD, + idlValueTypeE, + intSeq, + octetArray); + + U.sop(idlValueTypeA); + U.sop(idlValueTypeA.equals((idlValueTypeA)idlValueTypeB)); + + idlValueTypeA = ridlStaticTie.sendValue(idlValueTypeB, + idlValueTypeB, + idlValueTypeC, + idlValueTypeD, + idlValueTypeE, + intSeq, + octetArray); + + U.sop(idlValueTypeA); + U.sop(idlValueTypeA.equals((idlValueTypeA)idlValueTypeB)); + + /* + idlValueTypeA = ridlDynamic.sendValue(idlValueTypeB, + idlValueTypeB, + idlValueTypeC, + idlValueTypeD, + idlValueTypeE, + intSeq, + octetArray); + + U.sop(idlValueTypeA); + U.sop(idlValueTypeA.equals((idlValueTypeA)idlValueTypeB)); + */ + + } + + // + // Operations on DSI servants collected from above. + // + + public static void testDSIInvocations() + throws + Exception + { + + // + // DSI + // + + HEADER(U.DSI("")); + + U.sop(ridlDynamicPOA.syncOK(C.idlDynamicPOA)); + U.sop(ridlDynamic.syncOK(C.idlDynamic)); + getInterfaceDef(ridlDynamicPOA, C.idlDynamicPOA); + getInterfaceDef(ridlDynamic, C.idlDynamic); + U.sop(ridlDynamicPOA._is_a(C.idlDynamicPOA)); + U.sop(ridlDynamic._is_a(C.idlDynamic)); + U.sop(ridlDynamicPOA._non_existent()); + U.sop(ridlDynamic._non_existent()); + String ddata = C.idlDynamic; + ridlDynamicPOA.asyncOK(ddata.getBytes(C.UTF8)); + ridlDynamic.asyncOK(ddata.getBytes(C.UTF8)); + throwUserException(ridlDynamicPOA, C.idlDynamicPOA); + throwUserException(ridlDynamic, C.idlDynamic); + throwSystemException(ridlDynamicPOA, C.idlDynamicPOA); + throwSystemException(ridlDynamic, C.idlDynamic); + throwUnknownException(ridlDynamicPOA, C.idlDynamicPOA); + throwUnknownException(ridlDynamic, C.idlDynamic); + throwUNKNOWN(ridlDynamicPOA, C.idlDynamicPOA); + throwUNKNOWN(ridlDynamic, C.idlDynamic); + } + + // + // Utilities. + // + + public static String doDynInvOfSyncOK(idlI ref, String st) + { + org.omg.CORBA.Request r = ref._request(C.syncOK); + r.set_return_type(org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string)); + org.omg.CORBA.Any _s = r.add_in_arg(); + _s.insert_string(st); + r.invoke(); + String result = r.return_value().extract_string(); + return result; + } + + public static void getInterfaceDef(org.omg.CORBA.Object ref, String msg) + { + try { + U.sop(ref._get_interface_def()); + } catch (Exception e) { + U.sopOK(msg + " " + e); + } + U.expect(U.exception, new NO_IMPLEMENT(), + ref, C._get_interface_def); + } + + public static final int USER = 0; + public static final int SYSTEM = 1; + public static final int UnknownException = 2; + public static final int UNKNOWN = 3; + + public static void throwUserException(idlI ref, String msg) + { + throwException(USER, ref, msg); + } + + public static void throwSystemException(idlI ref, String msg) + { + throwException(SYSTEM, ref, msg); + } + + public static void throwUnknownException(idlI ref, String msg) + { + throwException(UnknownException, ref, msg); + } + + public static void throwUNKNOWN(idlI ref, String msg) + { + throwException(UNKNOWN, ref, msg); + } + + public static void throwException(int kind, idlI ref, String msg) + { + try { + switch (kind) { + case USER : + + U.expect(U.exception, new idlExampleException(), + ref, C.throwUserException); + + msg = msg + "." + C.throwUserException + " - "; + ref.throwUserException(); + break; + + case SYSTEM : + + U.expect(U.exception, new IMP_LIMIT(), + ref, C.throwSystemException); + + msg = msg + "." + C.throwSystemException + " - "; + ref.throwSystemException(); + break; + + case UnknownException : + + /* REVISIT - need to better understand how + UnknownException is used. + + U.expect(U.exception, + new UnknownException(new Throwable()), + ref, C.throwUnknownException); + */ + + msg = msg + "." + C.throwUnknownException + " - "; + ref.throwUnknownException(); + break; + + case UNKNOWN : + + /* REVISIT - need to better understand how + UNKNOWN is used. + + U.expect(U.exception, new UNKNOWN(), + ref, C.throwUnknownException); + */ + + msg = msg + "." + C.throwUNKNOWN + " - "; + ref.throwUNKNOWN(); + break; + + default : + throw new RuntimeException(baseMsg + ".throwException" + + " unknown kind: " + kind); + } + U.sopShouldNotSeeThis(msg); + } catch (SystemException e) { + switch (kind) { + case SYSTEM : + case UnknownException : + case UNKNOWN : + U.sopOK(msg + "SystemException " + e); + break; + default : + U.sopUnexpectedException(msg, e); + } + } catch (Exception e) { + switch (kind) { + case USER : + U.sopOK(msg + "Exception " + e); + break; + default : + U.sopUnexpectedException(msg, e); + } + } + } + + public static void HEADER(java.lang.Object x) + { + U.HEADER(x); + // ridlHEADERI.HEADER((String)x); + } + + public static void testExpect() + { + // REVISIT - add null return value test. + // REVISIT - add void return value test. + + if (testExpect) { + + // _result, _result + U.expect(U.result, + "bad on purpose", + rrmiiSA, C.sayHello); + + // _result _exception + U.expect(U.result, + "phony result", + ridlSAIRaiseObjectNotExistInIncarnate, + C.raiseObjectNotExistInIncarnate, + ""); + + // _exception _result + U.expect(U.exception, + new OBJECT_NOT_EXIST(), + ridlSAI1, C.raiseForwardRequestInIncarnate, + C.raiseForwardRequestInIncarnate); + + // _exception _exception + U.expect(U.exception, + new IMP_LIMIT(), + ridlSAIRaiseObjectNotExistInIncarnate, + C.raiseObjectNotExistInIncarnate, + ""); + } + } + + // REVISIT: move this into U. + // Not used. + public static void checkSystemException(SystemException expected, + int minorCode, + CompletionStatus completionStatus, + Throwable got) + { + if (! (got instanceof SystemException)) { + throw new RuntimeException("expected SystemException but got: " + + got ); + } + + SystemException gotSex = (SystemException)got; + + if (! expected.getClass().isInstance(gotSex)) { + throw new RuntimeException("SEX: wrong nested SystemException type, got: " + gotSex); + } + + if (gotSex.minor != minorCode) { + throw new RuntimeException("SEX: wrong minor code: " + gotSex.minor); + } + + if (gotSex.completed != completionStatus) { + throw new RuntimeException("SEX: wrong completion status: " + gotSex.completed); + } + } + + + public static void checkRmiMarshalException( + Throwable expected, + SystemException alternateExpected, + Throwable got) + { + if (! (got instanceof MarshalException)) { + throw new RuntimeException("RMI: excepted java.rmi.MarshalException but got: " + got); + } + + Throwable detail = ((MarshalException)got).detail; + + if (! (detail.getClass().isInstance(expected))) { + if (! (detail.getClass().isInstance(alternateExpected))) { + throw new RuntimeException("RMI: wrong nested exception: " +detail); + } + MARSHAL gotMarshal = (MARSHAL)detail; + if (gotMarshal.minor != alternateExpected.minor) { + throw new RuntimeException("RMI: wrong minor code: " + + " expected: " + alternateExpected.minor + + " got: " + gotMarshal.minor); + } + if (gotMarshal.completed != alternateExpected.completed) { + throw new RuntimeException("RMI: wrong completion status: " + + gotMarshal.completed); + } + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/ClientGrow.java b/functional-tests/src/test/java/corba/hcks/ClientGrow.java new file mode 100644 index 000000000..dc7c47468 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/ClientGrow.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 11 (Fri) 09:28:10 by Harold Carr. +// Last Modified : 2002 May 14 (Tue) 20:29:25 by Harold Carr. +// + +package corba.hcks; + +public class ClientGrow +{ + public static void main (String av[]) + { + Client.testName = ClientGrow.class.getName() ; + Client.giopVersion = C.GIOP_VERSION_1_2; + Client.buffMgrStategy = C.BUFFMGR_STRATEGY_GROW; + Client.fragmentSize = -1; + Client.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/Client_1_1.java b/functional-tests/src/test/java/corba/hcks/Client_1_1.java new file mode 100644 index 000000000..00b417bfd --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/Client_1_1.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 11 (Fri) 09:28:10 by Harold Carr. +// Last Modified : 2002 May 15 (Wed) 12:58:35 by Harold Carr. +// + +package corba.hcks; + +public class Client_1_1 +{ + public static void main (String av[]) + { + Client.testName = Client_1_1.class.getName() ; + Client.giopVersion = C.GIOP_VERSION_1_1; + Client.buffMgrStategy = C.BUFFMGR_STRATEGY_GROW; + Client.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/ColocatedClientServer.java b/functional-tests/src/test/java/corba/hcks/ColocatedClientServer.java new file mode 100644 index 000000000..b79204d83 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/ColocatedClientServer.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Jun 29 (Thu) 14:16:17 by Harold Carr. +// Last Modified : 2002 May 03 (Fri) 13:33:50 by Harold Carr. +// + +package corba.hcks; + +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; + +public class ColocatedClientServer +{ + public static final String baseMsg = ColocatedClientServer.class.getName(); + public static final String main = baseMsg + ".main"; + + // REVISIT: FRAMEWORK DEVELOPMENT + // REMOVE THIS LATER. + // Necessary so calls not going through locals do not hang + // until I implement the reader thread/work split. + public static int fragmentSize = -1; + //public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String args[]) + { + + Client.testName = ColocatedClientServer.class.getName() ; + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + orb = C.createORB(args, fragmentSize); + Server.orb = orb; + Client.orb = orb; + + // Share a naming context between client and server + // so StubAdapter.isLocal is true. + + // Use the same ORB which has interceptor properties set. + initialContext = C.createInitialContext(orb); + Server.initialContext = initialContext; + Client.initialContext = initialContext; + + ServerThread ServerThread = new ServerThread(args); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + Client.main(args); + } catch (Exception e) { + U.sopUnexpectedException(main, e); + } + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/ErrorAccumulator.java b/functional-tests/src/test/java/corba/hcks/ErrorAccumulator.java new file mode 100644 index 000000000..534016998 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/ErrorAccumulator.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 24 (Fri) 11:12:04 by Harold Carr. +// Last Modified : 2000 Nov 26 (Sun) 09:30:15 by Harold Carr. +// + +package corba.hcks; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import org.glassfish.pfl.basic.contain.Pair; + +public class ErrorAccumulator +{ + public int numberOfErrors; + public ArrayList errors; + + private int numberOfErrorsInTest ; + public ArrayList errorsInTest ; + + public void startTest() { + numberOfErrorsInTest = 0 ; + errorsInTest = new ArrayList() ; + } + + public List getTestErrors() { + return errorsInTest ; + } + + public ErrorAccumulator() + { + numberOfErrors = 0; + errors = new ArrayList(); + startTest() ; + } + + public void add(String errorMessage, Throwable t) + { + MessageAndException mae = new MessageAndException(errorMessage, t); + numberOfErrors++; + errors.add( mae ); + numberOfErrorsInTest++ ; + errorsInTest.add( mae ) ; + } + + public int getNumberOfErrors() + { + return numberOfErrors; + } + + public Collection getErrors() + { + return errors; + } + + public void reportErrors(boolean printErrors, boolean printStackTrace) + { + U.lf(); + U.sop("=================================================="); + U.sop("Number of errors: " + numberOfErrors); + U.sop("=================================================="); + U.lf(); + + if (printErrors) { + Iterator iterator = errors.iterator(); + while (iterator.hasNext()) { + MessageAndException messageAndException = + (MessageAndException) iterator.next(); + U.reportError(printStackTrace, + messageAndException.getMessage(), + messageAndException.getException()); + } + } + } + + public class MessageAndException extends Pair { + public MessageAndException(String message, Throwable exception) { + super( message, exception ) ; + } + + public String getMessage() { + return first() ; + } + + public Throwable getException() { + return second() ; + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/HcksTest.java b/functional-tests/src/test/java/corba/hcks/HcksTest.java new file mode 100644 index 000000000..38695af53 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/HcksTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 26 (Sun) 11:57:37 by Harold Carr. +// Last Modified : 2002 May 15 (Wed) 12:55:27 by Harold Carr. +// + +package corba.hcks; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +public class HcksTest + extends + CORBATest +{ + public static final String thisPackage = + HcksTest.class.getPackage().getName(); + + protected void doTest() + throws + Throwable + { + Controller orbd = createORBD(); + orbd.start(); + + doTestType("Server", "remoteServerStream", + "Client", "remoteClientStream"); + doTestType("ServerGrow", "remoteServerGrow", + "ClientGrow", "remoteClientGrow"); + doTestType("Server_1_1", "remoteServer_1_1", + "Client_1_1", "remoteClient_1_1"); + + Controller colocatedClientServer = + createClient(thisPackage + ".ColocatedClientServer", + "colocatedClientServer"); + colocatedClientServer.start(); + colocatedClientServer.waitFor(); + colocatedClientServer.stop(); + + orbd.stop(); + } + + protected void doTestType(String serverMainClass, String serverTestName, + String clientMainClass, String clientTestName) + throws + Throwable + { + Controller server = createServer(thisPackage + "." + serverMainClass, + serverTestName); + server.start(); + + Controller client = createClient(thisPackage + "." + clientMainClass, + clientTestName); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/MyInterceptor.java b/functional-tests/src/test/java/corba/hcks/MyInterceptor.java new file mode 100644 index 000000000..9a088094b --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/MyInterceptor.java @@ -0,0 +1,300 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 03 (Fri) 12:50:56 by Harold Carr. +// Last Modified : 2003 Feb 11 (Tue) 14:11:42 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.PERSIST_STORE; +import org.omg.CORBA.SystemException; +import org.omg.IOP.ServiceContext; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.RequestInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; + +import com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; + +import java.util.Hashtable; + +public class MyInterceptor + extends + org.omg.CORBA.LocalObject + implements + ClientRequestInterceptor, + ServerRequestInterceptor +{ + public static final String baseMsg = MyInterceptor.class.getName(); + + public static final boolean doShowConnection = false; + + public static final int clientSendServiceContextID = 8000; + + public static final int serverReceiveServiceContextID = 9998; + public static final int serverSendServiceContextID = 9999; + + // Meaningless but big enought to cause fragmentation.a + public static byte[] serviceContextData = + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; + + // Set this to true when fixing bug 4392779. + // Once that is fixed just leave it true. + // mroth: Fixed - setting to true. + public static boolean testingAdapterAndObjectIdWhenExceptionBeforeRR = + true; + + public static boolean testBug4383192 = true; + + public Hashtable effectiveTargetHashtable = new Hashtable(); + public int effectiveTargetSlotId; + + // + // Interceptor operations + // + + public String name() + { + return baseMsg; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + sopCR(baseMsg, "send_request", ri); + + if (ri.operation().equals(C.testEffectiveTarget1)) { + org.omg.CORBA.Object effectiveTarget1 = ri.effective_target(); + int hash = effectiveTarget1._hash(Integer.MAX_VALUE); + effectiveTargetHashtable.put(new Integer(hash), effectiveTarget1); + + // Not necessary to set recursion slot because of above if. + boolean isA = effectiveTarget1._is_a(idlIHelper.id()); + if (isA) { + idlI ridlI = idlIHelper.narrow(effectiveTarget1); + ridlI.testEffectiveTarget2(); + } else { + throw new RuntimeException(C.testEffectiveTarget1); + } + } else if (ri.operation().equals(C.testEffectiveTarget2)) { + org.omg.CORBA.Object effectiveTarget2 = ri.effective_target(); + int hash = effectiveTarget2._hash(Integer.MAX_VALUE); + org.omg.CORBA.Object effectiveTarget1 = (org.omg.CORBA.Object) + effectiveTargetHashtable.get(new Integer(hash)); + if (! effectiveTarget2._is_equivalent(effectiveTarget1)) { + throw new RuntimeException(C.testEffectiveTarget1); + } + } + + // This is sent just to cause fragmentation. + ri.add_request_service_context( + new ServiceContext(clientSendServiceContextID, + serviceContextData), + true); + } + + public void send_poll(ClientRequestInfo ri) + { + sopCR(baseMsg, "send_poll", ri); + } + + public void receive_reply(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_reply", ri); + checkServiceContexts(ri); + } + + public void receive_exception(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_exception", ri); + checkServiceContexts(ri); + } + + public void receive_other(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_other", ri); + } + + // + // ServerRequestInterceptor operations + // + + public void receive_request_service_contexts(ServerRequestInfo ri) + { + String point = "receive_request_service_contexts"; + // Check that stuff you add is available, even if exception raised. + // This is done here rather than receive_request since it is not + // called in this test when doing DSI throwSystemException. + ri.add_reply_service_context( + new ServiceContext(serverReceiveServiceContextID, + serviceContextData), + true); + try { + U.sop(baseMsg + "." + point + " " + ri.operation()); + } catch (SystemException e) { + U.sopUnexpectedException(baseMsg + "." + point, e); + } + + if (ri.operation().equals(C.throwThreadDeathInReceiveRequestServiceContexts)) { + throw new ThreadDeath(); + } + } + + public void receive_request(ServerRequestInfo ri) + { + sopSR(baseMsg, "receive_request", ri); + + if (ri.operation().equals(C.throwThreadDeathInReceiveRequest)) { + + throw new ThreadDeath(); + + } + + } + + public void send_reply(ServerRequestInfo ri) + { + sopSR(baseMsg, "send_reply", ri); + // Check that stuff you add is avaible, even if exception raised. + ri.add_reply_service_context( + new ServiceContext(serverSendServiceContextID, + serviceContextData), + true); + + if (ri.operation().equals(C.raiseSystemExceptionInSendReply)) { + + throw new IMP_LIMIT(); + + } else if (ri.operation().equals(C.throwThreadDeathInSendReply)) { + + throw new ThreadDeath(); + + } + } + + public void send_exception(ServerRequestInfo ri) + { + sopSR(baseMsg, "send_exception", ri); + ri.add_reply_service_context( + new ServiceContext(serverSendServiceContextID, + serviceContextData), + true); + String operation = ri.operation(); + if (operation.equals(C.raiseUserInServantThenSystemInPOThenSE) || + operation.equals(C.raiseSystemInServantThenPOThenSE)) + { + + throw new PERSIST_STORE(); + + } else if (operation.equals(C.throwThreadDeathInServantThenSysInPostThenSysInSendException)) + { + throw new PERSIST_STORE(); +/* KMC: Can't find any test affected by this code in HCKS, which causes problems in testMisc + } else if (operation.equals(C.sendTwoObjects)) { + SystemException sex = + ORBUtility.extractSystemException(ri.sending_exception()); + U.sop(sex); + if ((! (sex instanceof TRANSIENT)) || + (sex.minor != ORBUtilSystemException.REQUEST_CANCELED) || + (sex.completed != CompletionStatus.COMPLETED_NO)) + { + U.sopUnexpectedException( + "Not handling REQUEST_CANCELED correctly", + sex); + // Since this never makes it back to the client + // the only easy way to make the test indicate a failure + // is to kill the server. + System.exit(-1); + // REVISIT: Not complete. What if ending point never called? + // What if wrong ending point called? + } +*/ + } + + } + + public void send_other(ServerRequestInfo ri) + { + sopSR(baseMsg, "send_other", ri); + ri.add_reply_service_context( + new ServiceContext(serverSendServiceContextID, + serviceContextData), + true); + } + + // + // Utilities. + // + + public static void sopCR(String clazz, String point, ClientRequestInfo ri) + { + try { + U.sop(clazz + "." + point + " " + ri.operation()); + showConnection(ri); + } catch (SystemException e) { + U.sopUnexpectedException(baseMsg + "." + point, e); + } + } + + public static void sopSR(String clazz, String point, ServerRequestInfo ri) + { + try { + ri.adapter_id(); + U.sop(clazz + "." + point + " " + new String(ri.object_id()) + + " " + ri.operation()); + showConnection(ri); + } catch (SystemException e) { + U.sopUnexpectedException(baseMsg + "." + point, e); + if (testingAdapterAndObjectIdWhenExceptionBeforeRR) { + throw e; + } + } + } + + public static void showConnection(RequestInfo ri) + { + if (doShowConnection && (ri instanceof RequestInfoExt)) { + RequestInfoExt rie = (RequestInfoExt) ri; + if (rie.connection() != null) { + U.sop(" request on connection: " + rie.connection()); + } + } + } + + public static void checkServiceContexts(ClientRequestInfo ri) + { + if (testBug4383192) { + org.omg.CORBA.Object target = ri.effective_target(); + // Only do this on type idlI. + // Note: Do not use target._is_a to avoid interceptor recursion. + if ( StubAdapter.getTypeIds(target)[0].equals( + idlIHelper.id() )) { + ri.get_reply_service_context(serverReceiveServiceContextID); + ri.get_reply_service_context(serverSendServiceContextID); + } + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/MyORBInitializer.java b/functional-tests/src/test/java/corba/hcks/MyORBInitializer.java new file mode 100644 index 000000000..c11553e6a --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/MyORBInitializer.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Sep 22 (Fri) 11:34:53 by Harold Carr. +// Last Modified : 2001 Feb 05 (Mon) 15:01:52 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; + +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.CurrentHelper; + +public class MyORBInitializer + extends + org.omg.CORBA.LocalObject + implements + org.omg.PortableInterceptor.ORBInitializer +{ + public static final String baseMsg = MyORBInitializer.class.getName(); + + public void pre_init(ORBInitInfo info) + { + try { + MyInterceptor interceptor = new MyInterceptor(); + info.add_client_request_interceptor(interceptor); + info.add_server_request_interceptor(interceptor); + U.sop(baseMsg + ".pre_init"); + } catch (Throwable t) { + U.sopUnexpectedException(baseMsg, t); + } + } + + public void post_init(ORBInitInfo info) + { + try { + Current piCurrent = + CurrentHelper.narrow( + info.resolve_initial_references(U.PICurrent)); + NamingContext nameService = + NamingContextHelper.narrow( + info.resolve_initial_references(U.NameService));; + + SsPicInterceptor.sPic1ASlotId = info.allocate_slot_id(); + SsPicInterceptor.sPic1BSlotId = info.allocate_slot_id(); + int sPic2ASlotId = info.allocate_slot_id(); + int sPic2BSlotId = info.allocate_slot_id(); + + SsPicInterceptor sPicAInt = + new SsPicInterceptor(SsPicInterceptor.sPic1AServiceContextId, + SsPicInterceptor.sPic2AServiceContextId, + SsPicInterceptor.sPic1ASlotId, + sPic2ASlotId, + piCurrent, + nameService, + "sPicA"); + info.add_client_request_interceptor(sPicAInt); + info.add_server_request_interceptor(sPicAInt); + + + SsPicInterceptor sPicBInt = + new SsPicInterceptor(SsPicInterceptor.sPic1BServiceContextId, + SsPicInterceptor.sPic2BServiceContextId, + SsPicInterceptor.sPic1BSlotId, + sPic2BSlotId, + piCurrent, + nameService, + "sPicB"); + info.add_client_request_interceptor(sPicBInt); + info.add_server_request_interceptor(sPicBInt); + U.sop(baseMsg + ".post_init"); + } catch (Throwable t) { + U.sopUnexpectedException(baseMsg, t); + } + } + +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/MyPOAORB.java b/functional-tests/src/test/java/corba/hcks/MyPOAORB.java new file mode 100644 index 000000000..5b42c7037 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/MyPOAORB.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 by Harold Carr. +// Last Modified : 2002 Dec 04 (Wed) 21:43:39 by Harold Carr. +// + +package corba.hcks; + +import com.sun.corba.ee.impl.orb.ORBImpl; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; + +public class MyPOAORB + extends + ORBImpl +{ + public static final String baseMsg = MyPOAORB.class.getName(); + + public static boolean showProprietaryHooks = false; + + public static boolean throwRuntimeExceptionInSendingRequestServiceContexts + = false; + + protected void sendingRequestServiceContexts( ServiceContexts scs ) + { + if (showProprietaryHooks) { + U.sop(baseMsg + ".sendingRequestServiceContexts - " + scs); + } + if (throwRuntimeExceptionInSendingRequestServiceContexts) { + throw new RuntimeException(baseMsg + + ".sendingRequestServiceContexts"); + } + } + + protected void receivedReplyServiceContexts(ServiceContexts scs) + { + if (showProprietaryHooks) { + U.sop(baseMsg + ".receivedReplyServiceContexts - " + scs); + } + } + + protected void receivedRequestServiceContexts(ServiceContexts scs) + { + if (showProprietaryHooks) { + U.sop(baseMsg + ".receivedRequestServiceContexts - " + scs); + } + } + + protected void sendingReplyServiceContexts(ServiceContexts scs) + { + if (showProprietaryHooks) { + U.sop(baseMsg + ".sendingReplyServiceContexts - " + scs); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/MyServantActivator.java b/functional-tests/src/test/java/corba/hcks/MyServantActivator.java new file mode 100644 index 000000000..83cea77d7 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/MyServantActivator.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 08 (Wed) 09:18:37 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:12 by Harold Carr. + +package corba.hcks; + +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.SystemException; +import org.omg.PortableServer.ForwardRequest; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantActivator; + +public class MyServantActivator + extends + org.omg.CORBA.LocalObject + implements + ServantActivator +{ + + public static final String baseMsg = MyServantActivator.class.getName(); + + public ORB orb; + + public MyServantActivator(ORB orb) { this.orb = orb; } + + public Servant incarnate(byte[] oid, POA poa) + throws + ForwardRequest + { + String soid = new String(oid); + U.sop(baseMsg + ".incarnate " + soid); + + if (soid.startsWith("idl")) { + + // IDL. + + if (soid.equals(C.idlSAI1)) { + throw new ForwardRequest( + poa.create_reference_with_id(C.idlSAI2.getBytes(), + idlSAIHelper.id())); + } else if (soid.equals(C.idlSAIRaiseObjectNotExistInIncarnate)) { + throw new OBJECT_NOT_EXIST(); + } else if (soid.equals(C.idlSAIRaiseSystemExceptionInIncarnate)){ + throw new IMP_LIMIT(); + } + return new idlSAIServant(orb); + + } else if (soid.startsWith("rmii")) { + + // RMII + + return makermiiIServant(orb, soid); + + } else { + SystemException e = new INTERNAL(U.SHOULD_NOT_SEE_THIS); + U.sopUnexpectedException(baseMsg + ".incarnate", e); + throw e; + } + } + + public void etherealize(byte[] oid, POA poa, Servant servant, + boolean cleanupInProgress, + boolean remainingActivations) + { + String soid = new String(oid); + U.sop(baseMsg + ".etherealize " + soid); + } + + static Servant makermiiIServant(ORB orb, String name) + { + Servant servant = null; + try { + servant = + (Servant)javax.rmi.CORBA.Util.getTie(new rmiiIServantPOA(orb, name)); + } catch (Exception e) { + U.sopUnexpectedException(baseMsg + ".makermiiIServant", e); + } + return servant; + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/MyServantLocator.java b/functional-tests/src/test/java/corba/hcks/MyServantLocator.java new file mode 100644 index 000000000..a471a469b --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/MyServantLocator.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 07 (Tue) 16:29:22 by Harold Carr. +// Last Modified : 2001 Feb 07 (Wed) 16:36:40 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.PortableServer.ForwardRequest; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantLocator; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; + +public class MyServantLocator + extends + org.omg.CORBA.LocalObject + implements + ServantLocator +{ + public static final String baseMsg = MyServantLocator.class.getName(); + + public ORB orb; + + public MyServantLocator(ORB orb) { this.orb = orb; } + + public Servant preinvoke(byte[] oid, POA poa, String operation, + CookieHolder cookieHolder) + throws + ForwardRequest + { + String soid = new String(oid); + U.sop(baseMsg + ".preinvoke " + soid); + + if (soid.equals(C.idlAlwaysForward)) { + + throw new ForwardRequest( + poa.create_reference_with_id(C.idlAlwaysForwardedToo.getBytes(), + idlSLIHelper.id())); + + } else if (soid.startsWith("idl")) { + + // IDL. + + if (operation.equals(C.raiseForwardRequestInPreinvoke) && + soid.equals(C.idlSLI1)) + { + + throw new ForwardRequest( + poa.create_reference_with_id(C.idlSLI2.getBytes(), + idlSLIHelper.id())); + + } else if (operation.equals(C.raiseObjectNotExistInPreinvoke)) { + + throw new OBJECT_NOT_EXIST(); + + } else if (operation.equals(C.raiseSystemExceptionInPreinvoke)) { + + throw new IMP_LIMIT(); + + } else if (operation.equals(C.throwThreadDeathInPreinvoke)) { + + throw new ThreadDeath(); + + } + + // Test server-side PICurrent. + boolean ensure = false; + if (operation.equals(C.sPic1)) { + ensure = true; + } + C.testAndIncrementPICSlot(ensure, "preinvoke", + SsPicInterceptor.sPic1ASlotId, 1, orb); + C.testAndIncrementPICSlot(ensure, "preinvoke", + SsPicInterceptor.sPic1BSlotId, 1, orb); + + return new idlSLIServant(orb); + + } else if (soid.startsWith("rmii")) { + + // RMII. + + return MyServantActivator.makermiiIServant(orb, soid); + + } else { + + throw new INTERNAL(U.SHOULD_NOT_SEE_THIS); + + } + } + + public void postinvoke(byte[] oid, POA poa, String operation, + java.lang.Object cookie, Servant servant) + { + String soid = new String(oid); + U.sop(baseMsg + ".postinvoke " + soid); + if (operation.equals(C.raiseSystemExceptionInPostinvoke) || + operation.equals(C.raiseUserInServantThenSystemInPOThenSE) || + operation.equals(C.raiseSystemInServantThenPOThenSE)) + { + + throw new IMP_LIMIT(); + + } else if (operation.equals(C.throwThreadDeathInPostinvoke)) { + + throw new ThreadDeath(); + + } else if (operation.equals(C.throwThreadDeathInServantThenSysInPostThenSysInSendException)) + { + + throw new IMP_LIMIT(); + } + + + // Test server-side PICurrent. + boolean ensure = false; + if (operation.equals(C.sPic1)) { + ensure = true; + } + C.testAndIncrementPICSlot(ensure, "postinvoke", + SsPicInterceptor.sPic1ASlotId, 4, orb); + C.testAndIncrementPICSlot(ensure, "postinvoke", + SsPicInterceptor.sPic1BSlotId, 4, orb); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/NonSerializableObject.java b/functional-tests/src/test/java/corba/hcks/NonSerializableObject.java new file mode 100644 index 000000000..43f832932 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/NonSerializableObject.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Apr 06 (Fri) 16:45:13 by Harold Carr. +// Last Modified : 2001 May 08 (Tue) 11:16:33 by Harold Carr. +// + +package corba.hcks; + +public class NonSerializableObject +{ +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/README.txt b/functional-tests/src/test/java/corba/hcks/README.txt new file mode 100644 index 000000000..db41e5b7b --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/README.txt @@ -0,0 +1,33 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + + + hcks = Harold Carr's Kitchen Sink + + + +This test exercises many of the invoke/dispatch paths in the ORB. + + + +It is set up to easily step through everything AND to automatically +test those same paths. + + + +NOTE: Please DO NOT CHANGE ANYTHING IN THIS TEST WITHOUT FIRST + CONFERRING WITH HAROLD if possible. + + + +Thanks, +Harold Carr + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/SendRecursiveTypePOAServant.java b/functional-tests/src/test/java/corba/hcks/SendRecursiveTypePOAServant.java new file mode 100644 index 000000000..122956150 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/SendRecursiveTypePOAServant.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 12 (Fri) 09:42:02 by Harold Carr. +// Last Modified : 2002 Jul 12 (Fri) 09:54:51 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import java.util.Properties; + +class SendRecursiveTypePOAServant + extends + sendRecursiveTypePOA +{ + public static final String baseMsg = SendRecursiveTypePOAServant.class.getName(); + + public ORB orb; + + public SendRecursiveTypePOAServant(ORB orb) + { + this.orb = orb; + } + + public Any sendAsAny (Any x) + { + return x; + } + + public recursiveType sendAsType(recursiveType x) + { + return x; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/SerializableObject.java b/functional-tests/src/test/java/corba/hcks/SerializableObject.java new file mode 100644 index 000000000..bf6d0c015 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/SerializableObject.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Apr 06 (Fri) 16:45:13 by Harold Carr. +// Last Modified : 2001 Apr 06 (Fri) 16:55:53 by Harold Carr. +// + +package corba.hcks; + +import java.io.Serializable; + +public class SerializableObject + implements + Serializable +{ +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/Server.java b/functional-tests/src/test/java/corba/hcks/Server.java new file mode 100644 index 000000000..a8e6feb86 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/Server.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2003 Apr 09 (Wed) 18:21:34 by Harold Carr. +// + +package corba.hcks; + +import java.util.Properties; + +// +// IDL imports (and POA-based RMI-IIOP). +// + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.RequestProcessingPolicyValue; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +import corba.framework.Controller; +import corba.framework.Options; + +// +// RMI-IIOP imports. +// + +import java.rmi.RMISecurityManager; +import javax.rmi.PortableRemoteObject; + +//import java.rmi.Naming; // JRMP +import javax.naming.InitialContext; // IIOP + +public class Server +{ + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + + public static final String rmiiIServantPOA_Tie = + Server.class.getPackage().getName() + "._rmiiIServantPOA_Tie"; + + public static String giopVersion = C.GIOP_VERSION_1_2; + public static String buffMgrStategy = C.BUFFMGR_STRATEGY_STREAM; + public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static final String SAPOA = "SAPOA"; + public static final String SLPOA = "SLPOA"; + public static final String DSPOA = "DSPOA"; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated; + + public static POA rRootPOA; + public static POA rSAPOA; + public static POA rSLPOA; + public static POA rDSPOA; + + public static rmiiIServant rrmiiIServant; + public static idlI ridlStaticPoa; + public static idlI ridlStatic; + public static idlI ridlStaticForDisconnect; + + public static idlControllerStaticServant ridlControllerStaticServant; + + public static void main(String[] av) + { + // REVISIT - where did this come from? + if (System.getSecurityManager() == null) { + //System.setSecurityManager(new RMISecurityManager()); + } + + try { + U.sop(main + " starting"); + + if (ColocatedClientServer.isColocated) { + isColocated = true; + } else { + isColocated = false; + orb = C.createORB(av, giopVersion, + buffMgrStategy, fragmentSize); + // Use the same ORB which has interceptor properties set. + initialContext = C.createInitialContext(orb); + } + + rRootPOA = U.getRootPOA(orb); + rRootPOA.the_POAManager().activate(); + + // + // Create a POA which uses a ServantActivator. + // + + Policy[] policies; + + policies = U.createUseServantManagerPolicies( + rRootPOA, + ServantRetentionPolicyValue.RETAIN); + rSAPOA = + U.createPOAWithServantManager(rRootPOA, SAPOA, policies, + new MyServantActivator(orb)); + + // + // Create a POA which uses a ServantLocator. + // + + policies = U.createUseServantManagerPolicies( + rRootPOA, + ServantRetentionPolicyValue.NON_RETAIN); + rSLPOA = + U.createPOAWithServantManager(rRootPOA, SLPOA, policies, + new MyServantLocator(orb)); + + // + // Create a POA which retains and uses default servant. + // + + policies[0] = rRootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN); + policies[1] = rRootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_DEFAULT_SERVANT); + + + rDSPOA = rRootPOA.create_POA(DSPOA, null, policies); + rDSPOA.the_POAManager().activate(); + + // + // Standard rmi-iiop references. + // + + rrmiiIServant = new rmiiIServant(); + //Naming.rebind(rmiiI1, rrmiiIServant); // JRMP + initialContext.rebind(C.rmiiI1, rrmiiIServant); // IIOP + initialContext.rebind(C.rmiiI2, new rmiiIServant()); + + // + // poa-based rmi-iiop references. + // + + U.createRMIIPOABindAndCall(C.rmiiSA, rmiiIServantPOA_Tie, + rSAPOA, orb, initialContext); + U.createRMIIPOABindAndCall(C.rmiiSL, rmiiIServantPOA_Tie, + rSLPOA, orb, initialContext); + + // + // references managed by RootPOA + // + + U.createWithServantAndBind(C.idlHEADERI, + new idlHEADERIServant(orb), + rRootPOA, orb); + + ridlStaticPoa = + idlIHelper.narrow(U.createWithServantAndBind( + C.idlStaticPOA, new idlPOAServant(orb), rRootPOA, orb)); + + + U.createWithServantAndBind( + C.idlDynamicPOA, new idlDynamicServant(orb), rRootPOA, orb); + + U.createWithServantAndBind( + C.sendRecursiveType, new SendRecursiveTypePOAServant(orb), + rRootPOA, orb); + + // + // references managed by a POA with a ServantActivator + // + + U.createWithIdAndBind(C.idlSAI1, idlSAIHelper.id(), rSAPOA, orb); + U.createWithIdAndBind(C.idlSAI2, idlSAIHelper.id(), rSAPOA, orb); + + U.createWithIdAndBind(C.idlSAIRaiseObjectNotExistInIncarnate, + idlSAIHelper.id(), rSAPOA, orb); + + U.createWithIdAndBind(C.idlSAIRaiseSystemExceptionInIncarnate, + idlSAIHelper.id(), rSAPOA, orb); + + // + // references managed by a POA with a ServantLocator + // + + U.createWithIdAndBind(C.idlSLI1, idlSLIHelper.id(), rSLPOA, orb); + U.createWithIdAndBind(C.idlAlwaysForward, + idlSLIHelper.id(), rSLPOA, orb); + U.createWithIdAndBind(C.idlAlwaysForwardedToo, + idlSLIHelper.id(), rSLPOA, orb); + + // + // references manager by a POA with a default servant + // which is not set. + // + + // Note the type, SAI, is not important. + U.createWithIdAndBind(C.idlNonExistentDefaultServant, + idlSAIHelper.id(), rDSPOA, orb); + + // + // deprecated APIs - also used by RMI-IIOP + // + + ridlStatic = (idlI) + U.createWithConnectAndBind(C.idlStatic, + new idlStaticServant(orb), + orb); + ridlStaticForDisconnect = (idlI) + U.createWithConnectAndBind(C.idlStaticForDisconnect, + new idlStaticServant(orb), + orb); + + U.createWithConnectAndBind(C.idlStaticTie, + new idlI_Tie(ridlStatic), + orb); + + U.createWithConnectAndBind(C.idlDynamic, + new idlDeprecatedDynamicServant(orb), + orb); + + // + // The controller. + // + + + ridlControllerStaticServant = new idlControllerStaticServant(); + U.createWithConnectAndBind(C.idlControllerStatic, + ridlControllerStaticServant, + orb); + ridlControllerStaticServant.setRidlStaticORB(orb); + + + // Do an invocation on the reference to see how it works + // directly in the server. + + rrmiiIServant.sayHello(); + ridlStaticPoa.syncOK("idlStaticPoaFromInsideServer"); + ridlStatic.syncOK("idlStaticFromInsideServer"); + + U.sop(main + " ready"); + U.sop(Options.defServerHandshake); + System.out.flush(); + + synchronized (ColocatedClientServer.signal) { + ColocatedClientServer.signal.notifyAll(); + } + + orb.run(); // The ORB would not exist in standard rmi-iiop. + + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + System.exit(Controller.SUCCESS); + } + +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/ServerGrow.java b/functional-tests/src/test/java/corba/hcks/ServerGrow.java new file mode 100644 index 000000000..8c48c1a3e --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/ServerGrow.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 11 (Fri) 09:28:10 by Harold Carr. +// Last Modified : 2002 May 14 (Tue) 20:29:42 by Harold Carr. +// + +package corba.hcks; + +public class ServerGrow +{ + public static void main (String av[]) + { + Server.giopVersion = C.GIOP_VERSION_1_2; + Server.buffMgrStategy = C.BUFFMGR_STRATEGY_GROW; + Server.fragmentSize = -1; + Server.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/Server_1_1.java b/functional-tests/src/test/java/corba/hcks/Server_1_1.java new file mode 100644 index 000000000..2e2fef69c --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/Server_1_1.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 11 (Fri) 09:28:10 by Harold Carr. +// Last Modified : 2002 May 15 (Wed) 12:58:44 by Harold Carr. +// + +package corba.hcks; + +public class Server_1_1 +{ + public static void main (String av[]) + { + Server.giopVersion = C.GIOP_VERSION_1_1; + Server.buffMgrStategy = C.BUFFMGR_STRATEGY_GROW; + Server.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/SsPicInterceptor.java b/functional-tests/src/test/java/corba/hcks/SsPicInterceptor.java new file mode 100644 index 000000000..3c1f5a32f --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/SsPicInterceptor.java @@ -0,0 +1,306 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Jan 24 (Wed) 14:38:57 by Harold Carr. +// Last Modified : 2001 Feb 05 (Mon) 14:12:34 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.ORB; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; + +import org.omg.IOP.ServiceContext; + +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.PortableInterceptor.RequestInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; + +/** + * This interceptor helps test Server-Side PICurrent operation. + */ + +public class SsPicInterceptor + extends + org.omg.CORBA.LocalObject + implements + ClientRequestInterceptor, + ServerRequestInterceptor +{ + public static final String baseMsg = MyInterceptor.class.getName(); + + public ORB anyFactory = ORB.init(); + + public Current piCurrent; + public NamingContext nameService; + public String name; + + // The contents do not matter. + public static final byte[] serviceContextData = { 1 }; + + // + // From client to server and vice-versa. + // Services the client call itself. + // + + // The ids which the client side uses to communicate to the + // to the server side on a call to operation sPic1. + public static final int sPic1AServiceContextId = 0x1A; + public static final int sPic1BServiceContextId = 0x1B; + + // Value of above for this instance. + public int sPic1ServiceContextId; + + // The slots which RRSC uses communicate the above info downstream. + public static int sPic1ASlotId; // Used in other files. + public static int sPic1BSlotId; // Used in other files. + public int sPic1SlotId; // Used here in this instance. + + + // + // From server interceptor to itself. + // + + // The ids which the server side uses to communicate back to itself + // to avoid recursion. + public static final int sPic2AServiceContextId = 0x2A; + public static final int sPic2BServiceContextId = 0x2B; + + // Value of above for this instance. + public int sPic2ServiceContextId; + + // The slot which RRSC uses to communicate with client interceptor + // on a out call call to avoid recursion. + public int sPic2SlotId; + + + // + // Constructor. + // + + public SsPicInterceptor(int sPic1ServiceContextId, + int sPic2ServiceContextId, + int sPic1SlotId, + int sPic2SlotId, + Current piCurrent, + NamingContext nameService, + String name) + { + this.sPic1ServiceContextId = sPic1ServiceContextId; + this.sPic2ServiceContextId = sPic2ServiceContextId; + this.sPic1SlotId = sPic1SlotId; + this.sPic2SlotId = sPic2SlotId; + this.piCurrent = piCurrent; + this.nameService = nameService; + this.name = name; + } + + // + // Interceptor operations + // + + public String name() + { + return name; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + checkPicMemory(ri); + + // If the client gives us info then send it to the server. + // Existence counts, not contents. + Any any = null; + any = U.getSlot(ri, sPic1SlotId); + if (! U.isTkNull(any)) { + ServiceContext serviceContext = + new ServiceContext(sPic1ServiceContextId, serviceContextData); + ri.add_request_service_context(serviceContext, false); + } + + // If the server interceptor sets the recursion slot then + // put in the service context so the server doesn't make + // the call again. + + any = null; + any = U.getSlot(ri, sPic2SlotId); + if (U.isTkBoolean(any)) { + ServiceContext serviceContext = + new ServiceContext(sPic2ServiceContextId, serviceContextData); + ri.add_request_service_context(serviceContext, false); + } + + } + + public void send_poll(ClientRequestInfo ri) + { + } + + public void receive_reply(ClientRequestInfo ri) + { + checkPicMemory(ri); + + if (isSPic1(ri)) { + // This should not result in an exception. + // If it does the client test will report it. + ri.get_reply_service_context(sPic1ServiceContextId); + + // The server's sets to these same slot ids should not effect + // the client interceptors ri slots nor + // the client interceptors pic slots. + Any anyRi = null; + Any anyPic = null; + anyRi = U.getSlot(ri, sPic1SlotId); + anyPic = U.getSlot(piCurrent, sPic1SlotId); + if (U.isTkLong(anyRi)) { + int value = anyRi.extract_long(); + if (value != 0) { + throw new RuntimeException("RI CLOBBERED"); + } + } + if (! U.isTkNull(anyPic)) { + throw new RuntimeException("PIC CLOBBERED"); + } + } + } + + public void receive_exception(ClientRequestInfo ri) + { + } + + public void receive_other(ClientRequestInfo ri) + { + } + + // + // ServerRequestInterceptor operations + // + + public void receive_request_service_contexts(ServerRequestInfo ri) + { + checkPicMemory(ri); + + try { + // If the service context is sent from the client + // then send its info downstream. + // Existence counts, not contents. + ri.get_request_service_context(sPic1ServiceContextId); + Any any = anyFactory.create_any(); + any.insert_long(1); + U.setSlot(ri, sPic1SlotId, any); + } catch (BAD_PARAM e) { + // Do nothing when the context is absent. + ; + } + + // We only want to test this server side recursion when testing + // sPic1 - it works with anything but this just speeds up the test + // by narrowing its applicability. + if (ri.operation().equals(C.sPic1)) { + // Always set the recursion slot info. + Any any = anyFactory.create_any(); + any.insert_boolean(true); + U.setSlot(piCurrent, sPic2SlotId, any); + + // Now make the out call if you have not already done so. + try { + // Check the recursion indicator. + ri.get_request_service_context(sPic2ServiceContextId); + } catch (BAD_PARAM e) { + // Recusion indicator not set so make the call. + try { + idlSLI ridlSLI1 = + idlSLIHelper.narrow( + nameService.resolve(U.makeNameComponent(C.idlSLI1))); + ridlSLI1.sPic2(); + } catch (CannotProceed ex) { + U.sopUnexpectedException(baseMsg, ex); + } catch (InvalidName ex) { + U.sopUnexpectedException(baseMsg, ex); + } catch (NotFound ex) { + U.sopUnexpectedException(baseMsg, ex); + } + } + } + } + + public void receive_request(ServerRequestInfo ri) + { + checkPicMemory(ri); + + boolean ensure = isSPic1(ri); + C.testAndIncrementPICSlot(ensure, "receive_request", + sPic1SlotId, 2, piCurrent); + } + + public void send_reply(ServerRequestInfo ri) + { + checkPicMemory(ri); + + boolean ensure = isSPic1(ri); + if (C.testAndIncrementPICSlot(ensure, "send_reply", + sPic1SlotId, 5, piCurrent)) + { + // Complete the end-to-end test by sending a reply + // service context if all went well. If this is absent + // for this method then the test will complain. + ServiceContext serviceContext = + new ServiceContext(sPic1ServiceContextId, serviceContextData); + ri.add_reply_service_context(serviceContext, false); + } + } + + public void send_exception(ServerRequestInfo ri) + { + } + + public void send_other(ServerRequestInfo ri) + { + } + + // + // Utilities. + // + + // To see memory locations while stepping. + public void checkPicMemory(RequestInfo ri) + { + try { + ri.get_slot(sPic1SlotId); + piCurrent.get_slot(sPic1SlotId); + } catch (Throwable t) {} + } + + public static boolean isSPic1(RequestInfo ri) + { + return ri.operation().equals(C.sPic1); + } + +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/U.java b/functional-tests/src/test/java/corba/hcks/U.java new file mode 100644 index 000000000..55404f98b --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/U.java @@ -0,0 +1,812 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 08 (Wed) 20:53:55 by Harold Carr. +// Last Modified : 2005 Jul 12 (Tue) 12:42:31 by Harold Carr. +// + +package corba.hcks; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import java.util.List; +import java.util.Collection; +import java.util.Iterator; +import java.util.StringTokenizer; +import java.util.Vector; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.rmi.PortableRemoteObject; + +import com.sun.corba.ee.impl.oa.poa.POACurrent; + +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; + +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.PortableInterceptor.RequestInfo; +import org.omg.PortableInterceptor.ServerRequestInfo; + +import org.omg.PortableServer.POA; +import org.omg.PortableServer.RequestProcessingPolicyValue; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantManager; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.transport.AcceptorImpl; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +public class U +{ + private static JUnitReportHelper helper = null ; + private static ErrorAccumulator ea ; + private static String testName ; + private static boolean hasError = false ; + + public static boolean hasError() { + return hasError ; + } + + // KMC: initialize the helper and ErrorAccumulator + public static void initialize( String name ) { + helper = new JUnitReportHelper( name ) ; + ea = new ErrorAccumulator() ; + testName = null ; + } + + // KMC: all done + public static void done() { + if (testName != null) + testComplete() ; + + helper.done() ; + } + + // KMC: helper support + private static void testComplete() { + List errors = ea.getTestErrors() ; + if (errors.isEmpty()) { + helper.pass() ; + } else { + StringBuilder sb = new StringBuilder() ; + sb.append( "Errors in test:\n" ) ; + for (ErrorAccumulator.MessageAndException mea : errors) { + sb.append( " " ) ; + sb.append( mea.toString() ) ; + sb.append( "\n" ) ; + } + + helper.fail( sb.toString() ) ; + } + } + + // KMC: helper support + private static void testStart( Object x ) { + if (testName != null) + testComplete() ; + testName = x.toString() ; + helper.start( testName ) ; + ea.startTest() ; + } + + // + // OMG Standard Constants. + // + + public static String NameService = "NameService"; + public static String PICurrent = "PICurrent"; + public static String POACurrent = "POACurrent"; + public static String RootPOA = "RootPOA"; + public static String ORBClass = "org.omg.CORBA.ORBClass"; + public static String ORBInitializerClass = + "org.omg.PortableInterceptor.ORBInitializerClass"; + + public static int OMGVMCID = org.omg.CORBA.OMGVMCID.value; + public static int SUNVMCID = 0x53550000; + + // + // Java Standard Constants. + // + + public static String javaNamingCorbaOrb = "java.naming.corba.orb"; + + // + // Messages. + // + + public static String SHOULD_NOT_SEE_THIS = "SHOULD NOT SEE THIS"; + public static String OK = "OK"; + public static String unexpected_exception = "unexpected exception"; + public static String _DII = "DII"; + public static String _DSI = "DSI"; + public static String from_a_idlDynamic_servant = + "from a idlDynamic servant"; + public static String _servant = "servant"; + + // + // POA. + // + + + public static POA getRootPOA(ORB orb) + throws + Exception + { + return (POA)orb.resolve_initial_references(RootPOA); + } + + // + // POACurrent. + // + + public static org.omg.PortableServer.Current getPOACurrent(ORB orb) + throws + Exception + { + return (org.omg.PortableServer.Current) + // REVISIT - need PortableServer.CurrentHelper.narrow + org.omg.CORBA.CurrentHelper.narrow(orb.resolve_initial_references( + POACurrent)); + } + + public static byte[] getPOACurrentObjectId(ORB orb) + throws + Exception + { + return getPOACurrent(orb).get_object_id(); + } + + public static String getPOACurrentOperation(ORB orb) + throws + Exception + { + return ((POACurrent)getPOACurrent(orb)).getOperation(); + } + + public static String getPOACurrentInfo(ORB orb) + throws + Exception + { + String op = new String(getPOACurrentOperation(orb)); + String name = new String(getPOACurrentObjectId(orb)); + return op + " " + name; + } + + public static Policy[] createUseServantManagerPolicies( + POA poa, + ServantRetentionPolicyValue isRetain) + throws + Exception + { + Policy[] policies = new Policy[2]; + policies[0] = poa.create_servant_retention_policy(isRetain); + policies[1] = poa.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + + return policies; + } + + public static POA createPOAWithServantManager( + POA parent, + String name, + Policy[] policies, + ServantManager servantManager) + throws + Exception + { + POA child = parent.create_POA(name, null, policies); + child.the_POAManager().activate(); + child.set_servant_manager(servantManager); + return child; + } + + // This one is really not POA. It is the deprecated connect API. + public static Object createWithConnectAndBind(String name, + org.omg.CORBA.Object servant, + ORB orb) + throws + Exception + { + orb.connect(servant); + U.rebind(name, servant, orb); + return servant; + } + + public static org.omg.CORBA.Object + createWithServantAndBind (String name, + Servant servant, + POA poa, + ORB orb) + throws + Exception + { + byte[] id = name.getBytes(); + poa.activate_object_with_id(id, servant); + org.omg.CORBA.Object ref = poa.id_to_reference(id); + U.rebind(name, ref, orb); + return ref; + } + + public static org.omg.CORBA.Object createWithIdAndBind(String id, + String repoId, + POA poa, + ORB orb) + throws + Exception + { + org.omg.CORBA.Object ref = + poa.create_reference_with_id(id.getBytes(), repoId); + U.rebind(id, ref, orb); + return ref; + } + + public static rmiiI createRMIIPOABindAndCall(String name, + String tieClassName, + POA poa, + ORB orb, + InitialContext initialContext) + throws + Exception + { + org.omg.CORBA.Object ref = + createRMIPOABind(name, tieClassName, poa, orb, initialContext); + + // Do a colocated invocation. + + rmiiI rrmiiI = (rmiiI)PortableRemoteObject.narrow(ref, rmiiI.class); + U.sop(rrmiiI.sayHello()); + + return rrmiiI; + } + + public static org.omg.CORBA.Object + createRMIPOABind(String name, + String tieClassName, + POA poa, + ORB orb, + InitialContext initialContext) + throws + Exception + { + // Class.forName is used so there is no compile time reference + // to the Tie class. This makes it possible to first compile + // the *.java files with javac then run rmic on the servant classes + // to generate the Ties. + + byte[] oid = name.getBytes(); + Servant servant = + (Servant) Class.forName(tieClassName).newInstance(); + String repositoryId = servant._all_interfaces(poa, oid)[0]; + org.omg.CORBA.Object ref = + poa.create_reference_with_id(oid, repositoryId); + + initialContext.rebind(name, ref); + return ref; + } + + // + // Naming. + // + + // RMI-IIOP Naming. + + public static Object lookupAndNarrow(String name, + Class clazz, + InitialContext initialContext) + throws + NamingException + { + return PortableRemoteObject.narrow(initialContext.lookup(name), clazz); + } + + // IDL Naming. + + public static org.omg.CORBA.Object resolve(String name, ORB orb) + throws + Exception + { + return getNameService(orb).resolve(makeNameComponent(name)); + } + + + public static org.omg.CORBA.Object rebind(String name, + org.omg.CORBA.Object ref, + ORB orb) + throws + Exception + { + getNameService(orb).rebind(makeNameComponent(name), ref); + return ref; + } + + public static NameComponent[] makeNameComponent(String name) + { + Vector result = new Vector(); + StringTokenizer tokens = new StringTokenizer(name, "/"); + while (tokens.hasMoreTokens()) { + result.addElement(tokens.nextToken()); + } + NameComponent path[] = new NameComponent[result.size()]; + for (int i = 0; i < result.size(); ++i) { + path[i] = new NameComponent((String)result.elementAt(i), ""); + } + return path; + } + + public static NamingContext getNameService(ORB orb) + throws + Exception + { + return NamingContextHelper.narrow( + orb.resolve_initial_references(NameService)); + } + + + // + // Interceptors. + // + + public static org.omg.PortableInterceptor.Current getPICurrent(ORB orb) + { + org.omg.PortableInterceptor.Current current = null; + try { + current = org.omg.PortableInterceptor.CurrentHelper.narrow( + orb.resolve_initial_references(PICurrent)); + } catch (org.omg.CORBA.ORBPackage.InvalidName e) { + sopUnexpectedException("getPICurrent", e); + } + return current; + } + + public static Any getSlot(org.omg.PortableInterceptor.Current pic, + int slotId) + { + try { + return pic.get_slot(slotId); + } catch (InvalidSlot e) { + throw new RuntimeException("getSlot"); + } + } + + public static void setSlot(org.omg.PortableInterceptor.Current pic, + int slotId, Any value) + { + try { + pic.set_slot(slotId, value); + } catch (InvalidSlot e) { + throw new RuntimeException("setSlot"); + } + } + + public static Any getSlot(RequestInfo ri, int slotId) + { + try { + return ri.get_slot(slotId); + } catch (InvalidSlot e) { + throw new RuntimeException("getSlot"); + } + } + + public static void setSlot(ServerRequestInfo ri, int slotId, Any value) + { + try { + ri.set_slot(slotId, value); + } catch (InvalidSlot e) { + throw new RuntimeException("setSlot"); + } + } + + // + // Dynamic type support. + // + + public static boolean isTkBoolean(Any any) + { + return isTk(TCKind.tk_boolean, any); + } + + public static boolean isTkLong(Any any) + { + return isTk(TCKind.tk_long, any); + } + + public static boolean isTkNull(Any any) + { + return isTk(TCKind.tk_null, any); + } + + public static boolean isTk(TCKind tk, Any any) + { + TypeCode typeCode = any.type(); + TCKind tcKind = typeCode.kind(); + return tcKind.equals(tk); + } + + // + // I/O. + // + + public static void lf() + { + System.out.println(); + } + + public static void sop(java.lang.Object x) + { + System.out.println(x); + System.out.flush(); + } + + public static void sop(boolean msg) + { + System.out.println(msg); + System.out.flush(); + } + + // KMC: called before the start of a test case + public static void HEADER(java.lang.Object x) + { + lf(); + sop("--------------------------------------------------"); + testStart( x ) ; + sop(x); + lf(); + } + + public static void normalExit(String msg) + { + U.sop(msg + ": normal exit."); + } + + public static String unexpectedException(String msg, Throwable t) + { + return msg + " " + U.unexpected_exception + " " + t; + } + + public static void sopUnexpectedException(String msg, Throwable t) + { + sop(unexpectedException(msg, t)); + t.printStackTrace(System.out); + hasError = true ; + } + + public static String OK(String msg) + { + return msg + " " + U.OK; + } + + public static void sopOK(String msg) + { + sop(OK(msg)); + } + + public static void sopShouldNotSeeThis() + { + sop(SHOULD_NOT_SEE_THIS); + ea.add( SHOULD_NOT_SEE_THIS, new RuntimeException() ) ; + hasError = true ; + throw new RuntimeException(SHOULD_NOT_SEE_THIS); + } + + public static void sopShouldNotSeeThis(String msg) + { + sop(msg + " " + SHOULD_NOT_SEE_THIS); + ea.add( msg, new RuntimeException( SHOULD_NOT_SEE_THIS ) ) ; + hasError = true ; + throw new RuntimeException(msg + " " + SHOULD_NOT_SEE_THIS); + } + + public static String DII(String name) + { + return _DII + " " + name; + } + + public static String DSI(String name) + { + return _DSI + " " + name; + } + + public static String servant(String name) + { + return _servant + " " + name; + } + + public static boolean unregisterAcceptorAndCloseConnections( + String socketType, com.sun.corba.ee.spi.orb.ORB orb) + { + TransportManager transportManager =orb.getCorbaTransportManager(); + Collection acceptors = transportManager.getAcceptors(); + Iterator i = acceptors.iterator(); + while (i.hasNext()) { + Acceptor acceptor = (Acceptor) i.next(); + if (acceptor instanceof SocketInfo) { + SocketInfo socketInfo = (SocketInfo) acceptor; + if (socketInfo.getType().equals(socketType)) { + + // Close the acceptor + transportManager.unregisterAcceptor(acceptor); + sop("Closing acceptor: " + acceptor); + acceptor.close(); + + // Close the connection + Collection connections = + ((com.sun.corba.ee.impl.transport.ConnectionCacheBase)transportManager.getInboundConnectionCache(acceptor)).values(); + i = connections.iterator(); + while (i.hasNext()) { + Connection connection = (Connection) i.next(); + CloseThread closeThread = new CloseThread(connection); + closeThread.start(); + } + return true; + } + } + } + return false; + } + + public static boolean registerAcceptor(String socketType, + int port, + com.sun.corba.ee.spi.orb.ORB orb) + { + Acceptor acceptor = + new AcceptorImpl( + orb, + port, + "Test", + socketType); + orb.getCorbaTransportManager().registerAcceptor(acceptor); + // This initializes it and registers it with the transport manager. + orb.getCorbaTransportManager().getAcceptors(); + return true; + } + + + //////////////////////////////////////////////////// + // + // Test framework utilities. + // + + public static final int result = 0; + public static final int exception = 1; + public static final int exceptionEquals = 2; // Caveat: see below in switch + public static final Object[] noArgs = {}; + public static final String newlineTab = "\n\t"; + public static final String _result = "result"; + public static final String _exception = "exception"; + + public static void expect( int kind, + Object expected, + Object ref, + String methodName) + { + expect(kind, expected, ref, methodName, noArgs); + } + + public static void expect( int kind, + Object expected, + Object ref, + String methodName, + Object arg1) + { + Object[] args = { arg1 }; + expect(kind, expected, ref, methodName, args); + } + + public static void expect( int kind, + Object expected, + Object ref, + String methodName, + Object arg1, + Object arg2) + { + Object[] args = { arg1, arg2 }; + expect(kind, expected, ref, methodName, args); + } + + + public static void expect( + int kind, + Object expected, + Object ref, + String methodName, + Object[] args) + { + String baseMsg = "U.expect"; + + Class clazz = ref.getClass(); + Class[] parameterTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + parameterTypes[i] = args[i].getClass(); + } + Method method; + try { + method = clazz.getMethod(methodName, parameterTypes); + } catch (NoSuchMethodException e) { + throw new RuntimeException(baseMsg + " NoSuchMethodException " + + methodName); + } catch (SecurityException e) { + throw new RuntimeException(baseMsg + " SecurityException"); + } + + Object result = null; + boolean gotResult = false; + + try { + result = method.invoke(ref, args); + gotResult = true; + } catch (IllegalAccessException e) { + throw new RuntimeException(baseMsg + " IllegalAccessException"); + } catch (IllegalArgumentException e) { + throw new RuntimeException(baseMsg + " IllegalArgumentException"); + } catch (InvocationTargetException e) { + result = e.getTargetException(); + } + + switch (kind) { + case U.result : + if (! gotResult) { + reportError(result, + result, expected, ref, methodName, args, + _result, _exception); + } else if (result == null) { + if (expected != null) { + // This handles oneways (and voids?). + reportError(null, + result, expected, ref, methodName, args, + _result, _result); + } + } else if (! result.equals(expected)) { + reportError(null, + result, expected, ref, methodName, args, + _result, _result); + } + break; + case exceptionEquals : + case exception : + if (gotResult) { + reportError(null, + result, expected, ref, methodName, args, + _exception, _result); + } else if (! result.getClass().isInstance(expected)) { + reportError(result, + result, expected, ref, methodName,args, + _exception, _exception); + } else if (kind == exceptionEquals) { + + // Caveat: only use exceptionEquals if the exceptions + // to be compared have defined a reasonable equals. + // Otherwise it probably defaults to Object.equals + // which is just a reference compare. + + if (! result.equals(expected)) { + reportError(result, + result, expected, ref, methodName, args, + _exception, _exception); + } + } + break; + default : + throw new RuntimeException(baseMsg + " switch default"); + } + } + + public static void reportError( Object exception, // null if none. + Object result, + Object expected, + Object ref, + String methodName, + Object[] args, + String expectedType, + String resultType) + { + StringBuffer sb = formatCall(ref, methodName, args); + sb.append(newlineTab); + sb.append("expected " + expectedType + ": "); + sb.append(expected); + sb.append(newlineTab); + sb.append("but got " + resultType + ": "); + sb.append(result); + reportError(sb.toString(), (Throwable)exception); + } + + public static StringBuffer formatCall(Object ref, + String methodName, + Object[] args) + { + StringBuffer result = new StringBuffer(ref + "." + methodName + "("); + for (int i = 0; i < args.length; i++) { + result.append(args[i]); + result.append(","); + } + if (args.length > 0) { + result.deleteCharAt(result.length() - 1);// Get rid of extra comma. + } + result.append(")"); + return result; + } + + public static boolean displayErrorsWhenTheyHappen = true; + public static boolean printStackTrace = true; + + public static void setDisplayErrorsWhenTheyHappen(boolean b) + { + displayErrorsWhenTheyHappen = b; + } + + public static void setPrintStackTrace(boolean b) + { + printStackTrace = b; + } + + public static void reportError( String msg, + Throwable t) + { + ea.add(msg, t); + hasError = true ; + + if (displayErrorsWhenTheyHappen) { + reportError(printStackTrace, msg, t); + } + } + + public static void reportError(boolean printStackTrace, + String msg, + Throwable t) + { + ea.add( msg, t ) ; + hasError = true ; + + sop("--------------------------------------------------"); + sop(msg); + if (t != null && printStackTrace) { + lf(); + t.printStackTrace(System.out); + } + sop("--------------------------------------------------"); + } +} + +class CloseThread extends Thread +{ + Connection connection; + CloseThread(Connection connection) + { + this.connection = connection; + } + public void run() + { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + U.sop(e); + System.exit(1); + + } + U.sop("Closing connection: " + connection); + connection.close(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlControllerStaticServant.java b/functional-tests/src/test/java/corba/hcks/idlControllerStaticServant.java new file mode 100644 index 000000000..9036f3640 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlControllerStaticServant.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Feb 23 (Fri) 07:12:06 by Harold Carr. +// Last Modified : 2001 Feb 23 (Fri) 14:46:31 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.ORB; + +class idlControllerStaticServant + extends + _idlControllerIImplBase +{ + public static final String baseMsg = + idlControllerStaticServant.class.getName(); + + public ORB ridlStaticORB; + + public void setRidlStaticORB (ORB ridlStaticORB) + { + this.ridlStaticORB = ridlStaticORB; + } + + public String action (String action) + { + if (action.equals(C.disconnectRidlStaticServant)) { + + ridlStaticORB.disconnect(Server.ridlStaticForDisconnect); + + } else { + + U.sopShouldNotSeeThis(action); + return U.SHOULD_NOT_SEE_THIS; + + } + return action; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlDeprecatedDynamicServant.java b/functional-tests/src/test/java/corba/hcks/idlDeprecatedDynamicServant.java new file mode 100644 index 000000000..9121596a6 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlDeprecatedDynamicServant.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2000 Nov 27 (Mon) 16:57:15 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import java.util.Properties; + +class idlDeprecatedDynamicServant + extends + org.omg.CORBA.DynamicImplementation +{ + //private static String[] __ids = { "IDL:hcks/idlI:1.0" }; + private static String[] __ids = new _idlIStub()._ids(); + public String[] _ids() { return __ids; } + + private ORB orb; + + public idlDeprecatedDynamicServant(ORB orb) + { + this.orb = orb; + } + + public void invoke(ServerRequest r) + { + idlDynInvokeHelper.invoke(orb, r); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/idlDynInvokeHelper.java b/functional-tests/src/test/java/corba/hcks/idlDynInvokeHelper.java new file mode 100644 index 000000000..3cedc4b3a --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlDynInvokeHelper.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2002 Dec 04 (Wed) 21:44:06 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.*; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.*; +import java.util.Properties; +import com.sun.corba.ee.impl.misc.ORBUtility; + +class idlDynInvokeHelper +{ + + public static boolean dprint = false; + + public static boolean throwSystemException = true; + + static void invoke(ORB orb, ServerRequest r) + { + try { + if (r.op_name().equals(C.syncOK) ) { + + // syncOK + + NVList nvlist = orb.create_list(0); + + Any a1 = orb.create_any(); + a1.type(ORB.init().get_primitive_tc(TCKind.tk_string)); + nvlist.add_value("arg1", a1, ARG_IN.value); + + // get values + r.arguments(nvlist); + String arg1 = a1.extract_string(); + + U.sop(r.op_name() + "(" + arg1 + ")"); + + Any __result = orb.create_any(); + __result.insert_string(U.DSI(arg1)); + r.set_result(__result); + + } else if (r.op_name().equals(C.asyncOK) ) { + + // asyncOK + + NVList nvlist = orb.create_list(0); + + Any a1 = orb.create_any(); + a1.type(idlJStringHelper.type()); + nvlist.add_value("arg1", a1, ARG_IN.value); + + r.arguments(nvlist); + + byte[] data = idlJStringHelper.extract(a1); + U.sop(new String(data, C.UTF8)); + + Any __return = orb.create_any(); + __return.type(orb.get_primitive_tc(TCKind.tk_void)); + r.set_result(__return); + + } else if (r.op_name().equals(C.throwUserException) ) { + + // throwUserException + + idlExampleException ex = null; + try { + C.throwUserException(U.from_a_idlDynamic_servant); + throw new INTERNAL(U.SHOULD_NOT_SEE_THIS); + } catch (idlExampleException e) { + ex = e; + } + + Any any = orb.create_any(); + idlExampleExceptionHelper.insert(any, ex); + r.set_exception(any); + return; + + } else if (r.op_name().equals(C.throwSystemException) ) { + + // throwSystemException + + SystemException ex = null; + try { + C.throwSystemException(U.from_a_idlDynamic_servant); + throw new INTERNAL(U.SHOULD_NOT_SEE_THIS); + } catch (SystemException e) { + ex = e; + } + + if (throwSystemException) { + throwSystemException = false; + throw ex; + } else { + throwSystemException = true; + Any any = orb.create_any(); + ORBUtility.insertSystemException(ex, any); + r.set_exception(any); + return; + } + } else if (r.op_name().equals(C.throwUnknownException)) { + + // throwUnknownException + + UnknownException ex = null; + try { + C.throwUnknownException(U.from_a_idlDynamic_servant); + throw new INTERNAL(U.SHOULD_NOT_SEE_THIS); + } catch (UnknownException e) { + ex = e; + } + + Any any = orb.create_any(); + ORBUtility.insertSystemException(ex, any); + r.set_exception(any); + return; + + + } else if (r.op_name().equals(C.throwUNKNOWN)) { + + C.throwUNKNOWN(U.from_a_idlDynamic_servant); + + } + + } catch (SystemException ex) { + // REVISIT - probably time to remove this catch clause. + U.sop("DynamicServant.invoke SystemException: " + ex); + throw ex; + } catch (Exception ex) { + U.sop("DynamicServant.invoke Exception: " + ex); + ex.printStackTrace(System.err); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/idlDynamicServant.java b/functional-tests/src/test/java/corba/hcks/idlDynamicServant.java new file mode 100644 index 000000000..781104a95 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlDynamicServant.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2000 Nov 27 (Mon) 16:58:24 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import java.util.Properties; + +class idlDynamicServant + extends + org.omg.PortableServer.DynamicImplementation +{ + //private static String[] __ids = { "IDL:hcks/idlI:1.0" }; + private static String[] __ids = new _idlIStub()._ids(); + public String[] _all_interfaces(POA poa, byte[] oid) { return __ids; } + + private ORB orb; + + public idlDynamicServant(ORB orb) + { + this.orb = orb; + } + + public void invoke(ServerRequest r) + { + idlDynInvokeHelper.invoke(orb, r); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/idlHEADERIServant.java b/functional-tests/src/test/java/corba/hcks/idlHEADERIServant.java new file mode 100644 index 000000000..d07ac87c1 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlHEADERIServant.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 08 (Wed) 11:23:52 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:30 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.ORB; + +class idlHEADERIServant + extends + idlHEADERIPOA +{ + private ORB orb; + public idlHEADERIServant ( ORB orb ) { this.orb = orb; } + public void HEADER ( String message ) + { + U.HEADER(message); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/idlPOAServant.java b/functional-tests/src/test/java/corba/hcks/idlPOAServant.java new file mode 100644 index 000000000..6365c7b91 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlPOAServant.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2003 Dec 19 (Fri) 11:02:11 by Harold Carr. +// + +package corba.hcks; + +import org.omg.PortableServer.*; +import java.util.Iterator; +import java.util.Properties; + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.IdentifiableFactory ; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import com.sun.corba.ee.spi.ior.TaggedComponentFactoryFinder ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactory ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; +import com.sun.corba.ee.spi.ior.IdentifiableContainerBase ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.IORTemplateList ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.ior.ObjectKeyFactory ; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.transport.Acceptor; + +import com.sun.corba.ee.spi.ior.iiop.ORBTypeComponent ; + +import com.sun.corba.ee.impl.ior.GenericTaggedProfile ; +import com.sun.corba.ee.impl.ior.GenericTaggedComponent ; +import com.sun.corba.ee.impl.ior.FreezableList ; +import com.sun.corba.ee.impl.ior.OldJIDLObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.OldPOAObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.JIDLObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.POAObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.WireObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.EncapsulationUtility ; +import com.sun.corba.ee.impl.ior.TaggedComponentFactoryFinderImpl ; +import com.sun.corba.ee.impl.ior.TaggedProfileFactoryFinderImpl ; +import com.sun.corba.ee.impl.ior.ObjectAdapterIdArray ; +import com.sun.corba.ee.impl.ior.ObjectAdapterIdNumber ; +import com.sun.corba.ee.impl.ior.ObjectReferenceTemplateImpl ; +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl ; + +import com.sun.corba.ee.impl.orb.ORBVersionImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +class idlPOAServant + extends + idlIPOA +{ + public static final String baseMsg = idlPOAServant.class.getName(); + public static final String from_idlPOAServant = "from idlPOAServant"; + + public ORB orb; + + public org.omg.CORBA.Object savedObject; + + public idlPOAServant(org.omg.CORBA.ORB orb) + { + this.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + } + + public String syncOK(String arg1) + { + return baseMsg + " " + arg1; + } + + public synchronized void asyncOK(byte[] data) + { + try { + U.sop(new String(data, C.UTF8)); + } catch ( Exception e ) { + U.sopUnexpectedException(baseMsg + C.asyncOK, e); + } + } + + public void throwUserException() + throws idlExampleException + { + C.throwUserException(from_idlPOAServant); + } + + public void throwSystemException() + { + C.throwSystemException(from_idlPOAServant); + } + + public void throwUnknownException() + { + C.throwUnknownException(from_idlPOAServant); + } + + public void throwUNKNOWN() + { + C.throwUNKNOWN(from_idlPOAServant); + } + + public void raiseSystemExceptionInSendReply() + { + } + + public void testEffectiveTarget1() + { + } + + public void testEffectiveTarget2() + { + } + + public idlValueTypeA sendValue (idlValueTypeA a, + idlValueTypeB b, + idlValueTypeC c, + idlValueTypeD d, + idlValueTypeE e, + int[] f, + byte[] g) + { + U.sop(d); + return b; + } + + public org.omg.CORBA.Object getAndSaveUnknownORBVersionIOR() + { + // This is modified from corba.ior.Client test - around line 754. + + String[] ss = { "foo", "bar" } ; + ObjectAdapterId poaid = new ObjectAdapterIdArray( ss ) ; + POAObjectKeyTemplate poktemp1 = makePOAObjectKeyTemplate( poaid ) ; + + // KEY POINT: set an "unknown" ORB version. + poktemp1.setORBVersion(new ORBVersionImpl((byte)99)); + + IIOPProfileTemplate ptemp1 = makeIIOPProfileTemplate( 45671 ) ; + ORBTypeComponent comp1 = IIOPFactories.makeORBTypeComponent( 0x34567ABF ) ; + + ptemp1.add( comp1) ; + IORTemplate iortemp = IORFactories.makeIORTemplate( poktemp1 ) ; + iortemp.add( ptemp1 ) ; + + byte[] id = { 0x00, 0x00, 0x33, 0x44, 0x21, 0x23, 0x00 } ; + ObjectId oid = IORFactories.makeObjectId( id ) ; + + String typeid = "foo:bar" ; + IOR ior3 = iortemp.makeIOR( orb, typeid, oid ) ; + savedObject = ORBUtility.makeObjectReference(ior3); + return savedObject; + } + + public boolean isIdenticalWithSavedIOR(org.omg.CORBA.Object o) + { + return savedObject._is_equivalent(o); + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + public POAObjectKeyTemplate makePOAObjectKeyTemplate( ObjectAdapterId poaid ) + { + int scid = ORBConstants.FIRST_POA_SCID ; + String orbid = "AVeryLongORBIdName" ; + int serverid = -123 ; + + POAObjectKeyTemplate temp = new POAObjectKeyTemplate( orb, scid, + serverid, orbid, poaid ) ; + + return temp ; + } + + public IIOPProfileTemplate makeIIOPProfileTemplate( int port ) + { + String host = "FOO" ; + IIOPAddress primary = IIOPFactories.makeIIOPAddress( host, port ) ; + + IIOPProfileTemplate ptemp = IIOPFactories.makeIIOPProfileTemplate( orb, + GIOPVersion.V1_2, primary ) ; + + return ptemp ; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlSAIServant.java b/functional-tests/src/test/java/corba/hcks/idlSAIServant.java new file mode 100644 index 000000000..84ae47cd3 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlSAIServant.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 08 (Wed) 09:45:40 by Harold Carr. +// Last Modified : 2000 Nov 26 (Sun) 20:22:32 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.ORB; + +class idlSAIServant + extends + idlSAIPOA +{ + public ORB orb; + public static String clazz = "idlSAIServant"; + + public idlSAIServant ( ORB orb ) { this.orb = orb; } + public String raiseForwardRequestInIncarnate ( String a ) { return a; } + public String raiseObjectNotExistInIncarnate ( String a ) { return a; } + public String raiseSystemExceptionInIncarnate ( String a ) { return a; } + public String makeColocatedCallFromServant ( ) + { + return C.makeColocatedCallFromServant(C.idlSAI2, orb, clazz); + } + public String colocatedCallFromServant ( String a ) + { + return C.colocatedCallFromServant(a, orb, clazz); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/idlSLIServant.java b/functional-tests/src/test/java/corba/hcks/idlSLIServant.java new file mode 100644 index 000000000..5ebd5019b --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlSLIServant.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 07 (Tue) 12:16:39 by Harold Carr. +// Last Modified : 2001 Feb 07 (Wed) 17:19:31 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.NO_MEMORY; + +class idlSLIServant + extends + idlSLIPOA +{ + public static String baseMsg = idlSLIServant.class.getName(); + + public ORB orb; + + public idlSLIServant ( ORB orb ) { this.orb = orb; } + public String raiseForwardRequestInPreinvoke ( String a ) { return a; } + public String raiseObjectNotExistInPreinvoke ( String a ) { return a; } + public String raiseSystemExceptionInPreinvoke ( String a ) { return a; } + public String raiseSystemExceptionInPostinvoke ( String a ) { return a; } + + public String raiseSystemInServantThenPOThenSE ( ) + { + throw new NO_MEMORY(); + } + + public String raiseUserInServantThenSystemInPOThenSE ( ) + throws + idlExampleException + { + C.throwUserException(baseMsg + + C.raiseUserInServantThenSystemInPOThenSE); + // return for compiler + return U.SHOULD_NOT_SEE_THIS; + } + + public String makeColocatedCallFromServant ( ) + { + return C.makeColocatedCallFromServant(C.idlSLI1, orb, baseMsg); + } + public String colocatedCallFromServant ( String a ) + { + return C.colocatedCallFromServant(a, orb, baseMsg); + } + + public String throwThreadDeathInReceiveRequestServiceContexts( String a ) + { + U.sop(U.servant(a)); + return a; + } + public String throwThreadDeathInPreinvoke ( String a ) + { + U.sop(U.servant(a)); + return a; + } + public String throwThreadDeathInReceiveRequest ( String a ) + { + U.sop(U.servant(a)); + return a; + } + + public String throwThreadDeathInServant ( String a ) + { + U.sop(U.servant(a)); + throw new ThreadDeath(); + } + public String throwThreadDeathInPostinvoke ( String a ) + { + U.sop(U.servant(a)); + return a; + } + public String throwThreadDeathInSendReply ( String a ) + { + U.sop(U.servant(a)); + return a; + } + public String throwThreadDeathInServantThenSysInPostThenSysInSendException ( String a ) + { + U.sop(U.servant(a)); + throw new ThreadDeath(); + } + + public void sPic1() + { + C.testAndIncrementPICSlot(true, C.sPic1, + SsPicInterceptor.sPic1ASlotId, 3, orb); + C.testAndIncrementPICSlot(true, C.sPic1, + SsPicInterceptor.sPic1BSlotId, 3, orb); + } + public void sPic2() + { + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/idlStaticServant.java b/functional-tests/src/test/java/corba/hcks/idlStaticServant.java new file mode 100644 index 000000000..b6730dcc5 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlStaticServant.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 1999 Mar 01 (Mon) 16:59:34 by Harold Carr. +// Last Modified : 2003 Dec 16 (Tue) 10:01:18 by Harold Carr. +// + +package corba.hcks; + +import org.omg.CORBA.*; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.*; +import java.util.Properties; + +class idlStaticServant + extends + _idlIImplBase +{ + public static final String baseMsg = idlStaticServant.class.getName(); + public static final String from_idlStaticServant = "from idlStaticServant"; + + public ORB orb; + + public idlStaticServant(ORB orb) + { + this.orb = orb; + } + + public String syncOK(String arg1) + { + return baseMsg + " " + arg1; + } + + public synchronized void asyncOK(byte[] data) + { + try { + U.sop(new String(data, C.UTF8)); + } catch (Exception e) { + U.sopUnexpectedException(baseMsg + C.asyncOK, e); + } + } + + public void throwUserException() + throws idlExampleException + { + C.throwUserException(from_idlStaticServant); + } + + public void throwSystemException() + { + C.throwSystemException(from_idlStaticServant); + } + + public void throwUnknownException() + { + C.throwUnknownException(from_idlStaticServant); + } + + public void throwUNKNOWN() + { + C.throwUNKNOWN(from_idlStaticServant); + } + + public void raiseSystemExceptionInSendReply() + { + } + + public void testEffectiveTarget1() + { + } + + public void testEffectiveTarget2() + { + } + + public String testMonitoring () + { + return ""; + } + + public idlValueTypeA sendValue (idlValueTypeA a, + idlValueTypeB b, + idlValueTypeC c, + idlValueTypeD d, + idlValueTypeE e, + int[] f, + byte[] g) + { + U.sop(d); + return b; + } + + public org.omg.CORBA.Object getAndSaveUnknownORBVersionIOR() + { + throw new RuntimeException("Not implemented"); + } + + public boolean isIdenticalWithSavedIOR(org.omg.CORBA.Object o) + { + throw new RuntimeException("Not implemented"); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlValueTypeAImpl.java b/functional-tests/src/test/java/corba/hcks/idlValueTypeAImpl.java new file mode 100644 index 000000000..40f261925 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlValueTypeAImpl.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Mar 14 (Tue) 20:18:43 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:36 by Harold Carr. +// + +package corba.hcks; + +public class idlValueTypeAImpl + extends + idlValueTypeA +{ + public static final String baseMsg = idlValueTypeAImpl.class.getName(); + + public idlValueTypeAImpl () {} + + public idlValueTypeAImpl (short a) + { + this.a = a; + } + + public short getShortA () + { + return this.a; + } + + public void setShortA (short a) + { + this.a = a; + } + + public String toString () + { + return baseMsg + " " + a; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlValueTypeBImpl.java b/functional-tests/src/test/java/corba/hcks/idlValueTypeBImpl.java new file mode 100644 index 000000000..3bd2574e6 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlValueTypeBImpl.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Mar 14 (Tue) 20:18:43 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:37 by Harold Carr. +// + +package corba.hcks; + +public class idlValueTypeBImpl + extends + idlValueTypeB +{ + public static final String baseMsg = idlValueTypeBImpl.class.getName(); + + public idlValueTypeBImpl () {} + + public idlValueTypeBImpl (short a, short b) + { + this.a = a; + this.b = b; + } + + public String toString () + { + return baseMsg + " " + a + " " + b; + } + +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlValueTypeCImpl.java b/functional-tests/src/test/java/corba/hcks/idlValueTypeCImpl.java new file mode 100644 index 000000000..d1825ad2f --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlValueTypeCImpl.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Mar 14 (Tue) 20:18:43 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:39 by Harold Carr. +// + +package corba.hcks; + +public class idlValueTypeCImpl + extends + idlValueTypeC +{ + public static final String baseMsg = idlValueTypeCImpl.class.getName(); + + public idlValueTypeCImpl () {} + + public idlValueTypeCImpl (short a, short b, short c) + { + this.a = a; + this.b = b; + this.c = c; + } + + public String toString () + { + return baseMsg + " " + a + " " + b + " " + c; + } + + public void marshal(org.omg.CORBA.DataOutputStream out) + { + } + + public void unmarshal(org.omg.CORBA.DataInputStream in) + { + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlValueTypeDImpl.java b/functional-tests/src/test/java/corba/hcks/idlValueTypeDImpl.java new file mode 100644 index 000000000..305b839e6 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlValueTypeDImpl.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Mar 14 (Tue) 20:18:43 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:40 by Harold Carr. +// + +package corba.hcks; + +public class idlValueTypeDImpl + extends + idlValueTypeD +{ + public static final String baseMsg = idlValueTypeDImpl.class.getName(); + + public idlValueTypeDImpl () {} + + public idlValueTypeDImpl (short d) + { + this.d = d; + } + + public String toString () + { + return baseMsg + " " + d; + } + + public void marshal(org.omg.CORBA.DataOutputStream out) + { + out.write_short(d); + } + + public void unmarshal(org.omg.CORBA.DataInputStream in) + { + d = in.read_short(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/idlValueTypeEImpl.java b/functional-tests/src/test/java/corba/hcks/idlValueTypeEImpl.java new file mode 100644 index 000000000..3b28e0c42 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/idlValueTypeEImpl.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Mar 14 (Tue) 20:18:43 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:41 by Harold Carr. +// + +package corba.hcks; + +public class idlValueTypeEImpl + extends + idlValueTypeE +{ + public static final String baseMsg = idlValueTypeEImpl.class.getName(); + + public idlValueTypeEImpl () + { + intSeq = new int[10000]; + octetArray = new byte[10000]; + } + + public String toString () + { + return baseMsg + " "; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/rmiiAttributesI.java b/functional-tests/src/test/java/corba/hcks/rmiiAttributesI.java new file mode 100644 index 000000000..fd2097370 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/rmiiAttributesI.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Nov 10 (Sat) 12:47:05 by Harold Carr. +// Last Modified : 2001 Nov 10 (Sat) 12:47:46 by Harold Carr. +// + +package corba.hcks; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface rmiiAttributesI + extends + Remote +{ + // Test JavaBeans patterns -> IDL attributes. + Integer getInteger() + throws + RemoteException; + + void setInteger(Integer x) + throws + RemoteException; + + boolean isTrue() + throws + RemoteException; + + boolean getTrue() + throws + RemoteException; + + void setTrue(boolean x) + throws + RemoteException; + + // Test that this is NOT a JavaBeans pattern. + Integer get() + throws + RemoteException; + + void set(Integer x) + throws + RemoteException; +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/rmiiAttributesIServantPOA.java b/functional-tests/src/test/java/corba/hcks/rmiiAttributesIServantPOA.java new file mode 100644 index 000000000..42f9880f4 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/rmiiAttributesIServantPOA.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Nov 10 (Sat) 12:50:19 by Harold Carr. +// Last Modified : 2001 Nov 10 (Sat) 12:59:46 by Harold Carr. +// + +package corba.hcks; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +public class rmiiAttributesIServantPOA + extends + PortableRemoteObject + implements + rmiiAttributesI +{ + public rmiiAttributesIServantPOA() + throws + RemoteException {} + + public Integer getInteger() + throws + RemoteException { return null; } + + public void setInteger(Integer x) + throws + RemoteException { } + + public boolean isTrue() + throws + RemoteException { return true; } + + public boolean getTrue() + throws + RemoteException { return true; } + + public void setTrue(boolean x) + throws + RemoteException { } + + // Test that this is NOT a JavaBeans pattern. + public Integer get() + throws + RemoteException { return null; } + + public void set(Integer x) + throws + RemoteException { } + +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/rmiiI.java b/functional-tests/src/test/java/corba/hcks/rmiiI.java new file mode 100644 index 000000000..a1b445399 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/rmiiI.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : Spring 1999 by Harold Carr. +// Last Modified : 2001 May 10 (Thu) 15:44:42 by Harold Carr. +// + +package corba.hcks; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface rmiiI + extends + Remote +{ + String sayHello () + throws + RemoteException; + + int sendBytes (byte[] x) + throws + RemoteException; + + Object sendOneObject (Object x) + throws + RemoteException, + rmiiMyException; + + Object sendTwoObjects (Object x, Object y) + throws + RemoteException; + + String makeColocatedCallFromServant () + throws + RemoteException; + + String colocatedCallFromServant (String a) + throws + RemoteException, + Exception; + + String throwThreadDeathInServant (String a) + throws + RemoteException, + ThreadDeath; + + Object returnObjectFromServer (boolean isSerializable) + throws + RemoteException; +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/rmiiIServant.java b/functional-tests/src/test/java/corba/hcks/rmiiIServant.java new file mode 100644 index 000000000..8898c1b5f --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/rmiiIServant.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : Spring 1999 by Harold Carr. +// Last Modified : 2001 May 10 (Thu) 15:45:57 by Harold Carr. +// + +package corba.hcks; + +import java.rmi.RemoteException; +import org.omg.CORBA.INTERNAL; + +//import java.rmi.server.UnicastRemoteObject; // JRMP +import javax.rmi.PortableRemoteObject; // IIOP + +public class rmiiIServant + extends + //UnicastRemoteObject // JRMP + PortableRemoteObject // IIOP + implements + rmiiI +{ + public static final String baseMsg = rmiiIServant.class.getName(); + + public rmiiIServant () + throws + RemoteException + { + super(); + } + + public String sayHello () + { + return C.helloWorld; + } + + public int sendBytes (byte[] x) + { + if (x == null) + return -1; + return x.length; + } + + public Object sendOneObject (Object x) + throws + rmiiMyException + { + return x; + } + + public Object sendTwoObjects (Object x, Object y) + { + return x; + } + + // REVISIT + public String makeColocatedCallFromServant () + throws + RemoteException + { + String result; + try { + result = ((rmiiI)this.narrow(this, rmiiIServant.class)) + .colocatedCallFromServant("A"); + } catch (Exception e) { + U.sopUnexpectedException(baseMsg + C.makeColocatedCallFromServant, + e); + throw new INTERNAL(U.SHOULD_NOT_SEE_THIS); + } + return result; + } + + // REVISIT + public String colocatedCallFromServant (String a) + throws + RemoteException, + Exception + { + return "B" + a; + } + + public String throwThreadDeathInServant (String a) + throws + RemoteException, + ThreadDeath + { + U.sop(U.servant(a)); + throw new ThreadDeath(); + } + + public Object returnObjectFromServer (boolean isSerializable) + throws + RemoteException + { + if (isSerializable) { + return new SerializableObject(); + } else { + return new NonSerializableObject(); + } + } + +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/hcks/rmiiIServantPOA.java b/functional-tests/src/test/java/corba/hcks/rmiiIServantPOA.java new file mode 100644 index 000000000..beb1a4359 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/rmiiIServantPOA.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 11 (Sat) 10:45:48 by Harold Carr. +// Last Modified : 2001 May 10 (Thu) 15:45:53 by Harold Carr. +// + +package corba.hcks; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.ORB; + +public class rmiiIServantPOA + extends + PortableRemoteObject + implements + rmiiI +{ + public static final String baseMsg = rmiiIServantPOA.class.getName(); + + public ORB orb; + public String name; + + public rmiiIServantPOA (ORB orb, String name) + throws + RemoteException + { + // DO NOT CALL SUPER - that would connect the object. + this.orb = orb; + this.name = name; + } + + public String sayHello () + { + return C.helloWorld; + } + + public int sendBytes (byte[] x) + { + if (x == null) + return -1; + return x.length; + } + + public Object sendOneObject (Object x) + throws + rmiiMyException + { + return x; + } + + public Object sendTwoObjects (Object x, Object y) + { + return x; + } + + public String makeColocatedCallFromServant () + throws + RemoteException + { + rmiiI rrmiiI = null; + String result = ""; + try { + result = new String(U.getPOACurrentOperation(orb)); + + // Colocated via narrow. + + rrmiiI = null; + rrmiiI = (rmiiI) this.narrow(this, rmiiI.class); + result = doCall(rrmiiI, result); + + // Colocated via PortableRemoteObject.narrow + + rrmiiI = null; + rrmiiI = (rmiiI) PortableRemoteObject.narrow(this, rmiiI.class); + result = doCall(rrmiiI, result); + + // Colocated via common context and PRO.narrow + + rrmiiI = null; + rrmiiI = (rmiiI) + U.lookupAndNarrow(name, rmiiI.class, Server.initialContext); + result = doCall(rrmiiI, result); + + } catch (Exception e) { + U.sopUnexpectedException(baseMsg + C.makeColocatedCallFromServant, + e); + INTERNAL exc = new INTERNAL(U.SHOULD_NOT_SEE_THIS); + exc.initCause( e ) ; + throw exc ; + } + return result; + } + + private String doCall(rmiiI rrmiiI, String resultSoFar) + throws + Exception + { + String result = rrmiiI.colocatedCallFromServant(resultSoFar); + String op = new String(U.getPOACurrentOperation(orb)); + return op + " " + result; + } + + public String colocatedCallFromServant (String a) + throws + RemoteException, + Exception + { + String op = new String(U.getPOACurrentOperation(orb)); + return op + " " + a; + } + + public String throwThreadDeathInServant (String a) + throws + RemoteException, + ThreadDeath + { + U.sop(U.servant(a)); + throw new ThreadDeath(); + } + + public Object returnObjectFromServer (boolean isSerializable) + throws + RemoteException + { + if (isSerializable) { + return new SerializableObject(); + } else { + return new NonSerializableObject(); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/hcks/rmiiMyException.java b/functional-tests/src/test/java/corba/hcks/rmiiMyException.java new file mode 100644 index 000000000..27ec24383 --- /dev/null +++ b/functional-tests/src/test/java/corba/hcks/rmiiMyException.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : Spring 1999 by Harold Carr. +// Last Modified : 2000 Nov 25 (Sat) 13:11:46 by Harold Carr. +// + +package corba.hcks; + +public class rmiiMyException + extends + Exception +{ +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/invocation/Client.java b/functional-tests/src/test/java/corba/invocation/Client.java new file mode 100644 index 000000000..1eaf7522d --- /dev/null +++ b/functional-tests/src/test/java/corba/invocation/Client.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.invocation; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CORBA.SystemException; +import java.util.*; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class Client implements Runnable { + + private String[] args; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public Client(String[] args) { + this.args = args; + } + + public static void main(String args[]) { + new Client(args).run(); + } + + public void run() { + + try { + + Properties props = new Properties() ; + //props.put("com.sun.corba.ee.ORBDebug", "transport,subcontract"); + props.setProperty(ORBConstants.TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY, "250:1000:100"); + ORB orb = ORB.init(args, props); + + String corbalocURL = + System.getProperty(InvocationTest.URL_PROPERTY); + + Object obj = orb.string_to_object(corbalocURL); + + if (obj == null) { + throw new RuntimeException("string_to_object(" + + corbalocURL + ")"); + } + + try { + Hello helloRef = HelloHelper.narrow( obj ); + + String msg = "FAILURE: call incorrectly succeeded"; + System.out.println("------------------------------------"); + System.out.println(msg); + System.out.println("------------------------------------"); + throw new Exception(msg); + + } catch (org.omg.CORBA.COMM_FAILURE e) { + SystemException connectException = + wrapper.connectFailure( new RuntimeException(), + "foo", "bar", "baz"); + if (e.getClass().isInstance(connectException) + && e.minor == connectException.minor + && e.completed == connectException.completed) + { + System.out.println("------------------------------------"); + System.out.println("SUCCESS"); + System.out.println("------------------------------------"); + } else { + System.out.println("------------------------------------"); + System.out.println("FAILURE"); + System.out.println("------------------------------------"); + e.printStackTrace(System.out); + RuntimeException rte = + new RuntimeException("Incorrect exception"); + rte.initCause(e); + throw rte; + } + } + + } catch (Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + + + diff --git a/functional-tests/src/test/java/corba/invocation/InvocationTest.java b/functional-tests/src/test/java/corba/invocation/InvocationTest.java new file mode 100644 index 000000000..c7aad833d --- /dev/null +++ b/functional-tests/src/test/java/corba/invocation/InvocationTest.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.invocation; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + * This tests if invocation on non-existent targets results in COMM_FAILURE. + */ +public class InvocationTest extends CORBATest { + public static String URL_PROPERTY = "naming.instest.urlProperty"; + + protected void doTest() throws Throwable { + + Properties clientProps = Options.getClientProperties(); + clientProps.setProperty(URL_PROPERTY, + "corbaloc:iiop:1.2@localhost:" + 3050 + '/' + + "HelloService"); + Controller client = createClient("corba.invocation.Client"); + client.start(); + + client.waitFor(60000); + + // Make sure all the processes are shut down. + client.stop(); + } +} diff --git a/functional-tests/src/test/java/corba/iorintsockfact/Client.java b/functional-tests/src/test/java/corba/iorintsockfact/Client.java new file mode 100644 index 000000000..4811ce26a --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/Client.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:50:37 by Harold Carr. +// Last Modified : 2003 Jun 03 (Tue) 18:11:37 by Harold Carr. +// + +package corba.iorintsockfact; + +import java.util.Properties; + +import org.omg.CORBA.ORB; + +/** + * @author Harold Carr + */ +public class Client +{ + public static final String baseMsg = Client.class.getName(); + + public static boolean foundAlternateIIOPAddressComponent = false; + + public static void main(String args[]) + { + try { + Properties props = new Properties(); + + props.put(Common.SOCKET_FACTORY_CLASS_PROPERTY, + Common.CUSTOM_FACTORY_CLASS); + + ORB orb = ORB.init(args, props); + + I iRef = + IHelper.narrow( + Common.getNameService(orb) + .resolve(Common.makeNameComponent(Common.serverName1))); + + System.out.println(iRef.m("Hello")); + + if (! foundAlternateIIOPAddressComponent) { + System.out.println("DID NOT FIND AlternateIIOPAddressComponent"); + System.exit(1); + } + + orb.shutdown(false); + orb.destroy(); + + System.out.println(); + System.out.println(baseMsg + ".main: Test complete."); + + } catch (Exception e) { + System.out.println(baseMsg + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/iorintsockfact/Common.java b/functional-tests/src/test/java/corba/iorintsockfact/Common.java new file mode 100644 index 000000000..3c04ff7b0 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/Common.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:47:13 by Harold Carr. +// Last Modified : 2004 Jun 06 (Sun) 12:21:47 by Harold Carr. +// + +package corba.iorintsockfact; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * @author Harold Carr + */ +public abstract class Common +{ + public static final String SOCKET_FACTORY_CLASS_PROPERTY = + ORBConstants.LEGACY_SOCKET_FACTORY_CLASS_PROPERTY; + + public static final String CUSTOM_FACTORY_CLASS = + SocketFactory.class.getName(); + + public static final String serverName1 = "I1"; + + public static NamingContext getNameService(ORB orb) + { + org.omg.CORBA.Object objRef = null; + try { + objRef = orb.resolve_initial_references("NameService"); + } catch (Exception ex) { + System.out.println("Common.getNameService: " + ex); + ex.printStackTrace(System.out); + System.exit(-1); + } + return NamingContextHelper.narrow(objRef); + } + + public static NameComponent[] makeNameComponent(String name) + { + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + return path; + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/iorintsockfact/ExampleMakefile b/functional-tests/src/test/java/corba/iorintsockfact/ExampleMakefile new file mode 100644 index 000000000..b8797dae5 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/ExampleMakefile @@ -0,0 +1,52 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +## +## @author Harold Carr +## + +JAVA_HOME=$(ALT_BOOTDIR) + +CLASSPATH=./.classes + +JAVAC=$(JAVA_HOME)/bin/javac +JAVA=$(JAVA_HOME)/bin/java + +ORB_INITIAL_PORT=1050 + +PACKAGE = corba.iorintsockfact +PKGDIR = corba/iorintsockfact + +IDLJ=$(JAVA_HOME)/bin/idlj +# 1.3 +IDLJ_FLAGS=-fall -td $(CLASSPATH) -verbose +# 1.4 +#IDLJ_FLAGS=-fall -oldImplBase -td $(CLASSPATH) -verbose + +ORBD=${JAVA_HOME}/bin/orbd -ORBInitialPort ${ORB_INITIAL_PORT} + +b: + $(IDLJ) $(IDLJ_FLAGS) iorintsockfact.idl + $(JAVAC) -g $(CLASSPATH)/$(PKGDIR)/*.java + $(JAVAC) -g -classpath $(CLASSPATH) *.java -d $(CLASSPATH) + +o: + $(ORBD) + +s: + $(JAVA) -classpath $(CLASSPATH) $(PACKAGE).Server \ + -ORBInitialPort ${ORB_INITIAL_PORT} + +c: + $(JAVA) -classpath $(CLASSPATH) $(PACKAGE).Client \ + -ORBInitialPort ${ORB_INITIAL_PORT} + +clean: + rm -rf .classes/* diff --git a/functional-tests/src/test/java/corba/iorintsockfact/IORInterceptor.java b/functional-tests/src/test/java/corba/iorintsockfact/IORInterceptor.java new file mode 100644 index 000000000..647879bb5 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/IORInterceptor.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 13:43:29 by Harold Carr. +// Last Modified : 2003 Jun 03 (Tue) 18:06:35 by Harold Carr. +// + +package corba.iorintsockfact; + +import java.net.InetAddress; +import java.util.Iterator; + +import org.omg.CORBA.Any; +import org.omg.IOP.Codec; +import org.omg.IOP.Encoding; +import org.omg.PortableInterceptor.IORInfo; +// This one is only necessary when running in current development workspace. +import org.omg.PortableInterceptor.ObjectReferenceTemplate; + +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories; +import com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory; +import com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent; + +/** + * @author Harold Carr + */ +public class IORInterceptor + extends + org.omg.CORBA.LocalObject + implements + org.omg.PortableInterceptor.IORInterceptor +{ + private ORB orb ; + + public IORInterceptor( ORB orb ) + { + this.orb = orb ; + } + + public final String baseMsg = IORInterceptor.class.getName(); + public String name() { return baseMsg; } + public void destroy() { } + + public void establish_components(IORInfo iorInfo) + { + try { + IORInfoExt iorInfoExt = (IORInfoExt) iorInfo; + ObjectAdapter adapter = iorInfoExt.getObjectAdapter(); + + String localAddress = InetAddress.getLocalHost().getHostAddress(); + int port = + iorInfoExt.getServerPort(ORBSocketFactory.IIOP_CLEAR_TEXT); + + InetAddress[] allAddresses = + InetAddress.getAllByName(localAddress); + + for (int i = 0; i < allAddresses.length; i++) { + String address = allAddresses[0].getHostAddress(); + + IIOPAddress iiopAddress = + IIOPFactories.makeIIOPAddress(address, port); + AlternateIIOPAddressComponent iiopAddressComponent = + IIOPFactories.makeAlternateIIOPAddressComponent(iiopAddress); + Iterator iterator = adapter.getIORTemplate().iteratorById( + org.omg.IOP.TAG_INTERNET_IOP.value); + + while (iterator.hasNext()) { + TaggedProfileTemplate taggedProfileTemplate = + (TaggedProfileTemplate) iterator.next(); + taggedProfileTemplate.add(iiopAddressComponent); + } + } + } catch (Exception e) { + System.out.println(baseMsg + e); + System.exit(-1); + } + } + + // Thses are only necessary when running in current development workspace. + public void components_established( IORInfo iorInfo ) + { + } + + public void adapter_manager_state_changed( int managerId, short state ) + { + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/iorintsockfact/IorIntSockFactTest.java b/functional-tests/src/test/java/corba/iorintsockfact/IorIntSockFactTest.java new file mode 100644 index 000000000..f82157939 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/IorIntSockFactTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:49:22 by Harold Carr. +// Last Modified : 2002 Jul 22 (Mon) 11:09:39 by Harold Carr. +// + +package corba.iorintsockfact; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +/** + * @author Harold Carr + */ +public class IorIntSockFactTest extends CORBATest { + public static final String thisPackage = + IorIntSockFactTest.class.getPackage().getName(); + + protected void doTest() throws Throwable { + Controller orbd = createORBD(); + orbd.start(); + + Controller server = createServer(thisPackage + "." + "Server", + "Server"); + Controller client = createClient(thisPackage + "." + "Client", + "Client"); + server.start(); + client.start(); + client.waitFor(); + client.stop(); + server.stop(); + orbd.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/iorintsockfact/README.txt b/functional-tests/src/test/java/corba/iorintsockfact/README.txt new file mode 100644 index 000000000..0225f2a78 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/README.txt @@ -0,0 +1,54 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +------------------------------------------------------------------------------ +Operation: + +The server side code looks up all the host's address and puts them +into TAG_ALTERNATE_IIOP_ADDRESS components in IORs. It does that +using proprietary APIs (it is possible to use standard APIs to create +and insert the TAG_ALTERNATE_IIOP_ADDRESS component) within standard OMG +PortableInterceptor IORInteceptors. + +When the client side makes the first request on an IOR it looks for +TAG_ALTERNATE_IIOP_ADDRESS components. If any are found it uses the +address in the first one found. It does this by overriding the +getEndPointInfo method of the DefaultSocketFactory provided with the +ORB. This is a proprietary API. + +------------------------------------------------------------------------------ +Prepare: + +Note: IorIntSockFactTest.java is part of the CORBA unit test framework. +Delete that file before compile with ExampleMakefile standalone. + +rm IorIntSockFactTest.java + +------------------------------------------------------------------------------ +Compile: + +export ALT_BOOTDIR= +gnumake -f ExampleMakefile b + +------------------------------------------------------------------------------ +Run: + +# Start ORBD +gnumake -f ExampleMakefile o & + +# Start server (note it prints "Server is read.") +gnumake -f ExampleMakefile s & + +# Run client (note it prints "Server echoes: Hello" and exits). +gnumake -f ExampleMakefile c + +kill + +;;; End of file. diff --git a/functional-tests/src/test/java/corba/iorintsockfact/Server.java b/functional-tests/src/test/java/corba/iorintsockfact/Server.java new file mode 100644 index 000000000..31d53d3ea --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/Server.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:48:59 by Harold Carr. +// Last Modified : 2002 Jul 22 (Mon) 12:05:48 by Harold Carr. +// + +package corba.iorintsockfact; + +import java.util.Properties ; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.PortableServer.POA; + +class IServant extends IPOA +{ + public IServant() + { + } + + public String m(String x) + { + return "Server echoes: " + x; + } +} + +/** + * @author Harold Carr + */ +public class Server +{ + public static final String baseMsg = Common.class.getName(); + + public static ORB orb; + public static POA rootPoa; + public static POA childPoa; + + public static void main(String av[]) + { + try { + + Properties props = System.getProperties(); + + props.setProperty("org.omg.PortableInterceptor.ORBInitializerClass." + ServerORBInitializer.class.getName(), + "dummy"); + + props.put(Common.SOCKET_FACTORY_CLASS_PROPERTY, + Common.CUSTOM_FACTORY_CLASS); + + orb = ORB.init(av, props); + + createAndBind(Common.serverName1); + + System.out.println ("Server is ready."); + + orb.run(); + + } catch (Exception e) { + System.out.println(baseMsg + e); + e.printStackTrace(System.out); + System.exit(1); + } + } + + public static void createAndBind (String name) + throws + Exception + { + if (rootPoa == null) { + + // Get rootPOA + + rootPoa = (POA) + orb.resolve_initial_references("RootPOA"); + rootPoa.the_POAManager().activate(); + + // Create child POAs. + + Policy[] policies = new Policy[1]; + + // Create child POA + policies[0] = + rootPoa.create_lifespan_policy(LifespanPolicyValue.TRANSIENT); + childPoa = rootPoa.create_POA("childPoa", null, policies); + childPoa.the_POAManager().activate(); + } + + // create servant and register it with the ORB + + IServant iServant = new IServant(); + byte[] id = childPoa.activate_object(iServant); + org.omg.CORBA.Object ref = childPoa.id_to_reference(id); + + Common.getNameService(orb).rebind(Common.makeNameComponent(name), ref); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/iorintsockfact/ServerORBInitializer.java b/functional-tests/src/test/java/corba/iorintsockfact/ServerORBInitializer.java new file mode 100644 index 000000000..f57849f83 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/ServerORBInitializer.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 13:42:23 by Harold Carr. +// Last Modified : 2003 Jun 03 (Tue) 18:06:21 by Harold Carr. +// + +package corba.iorintsockfact; + +import org.omg.CosNaming.*; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.Encoding; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.legacy.interceptor.ORBInitInfoExt ; + +/** + * @author Harold Carr + */ +public class ServerORBInitializer + extends + org.omg.CORBA.LocalObject + implements + ORBInitializer +{ + public static final String baseMsg = ServerORBInitializer.class.getName(); + + public void pre_init(ORBInitInfo info) { } + + public void post_init(ORBInitInfo info) + { + ORB orb = ((ORBInitInfoExt)info).getORB() ; + try { + info.add_ior_interceptor(new IORInterceptor(orb)); + } catch (DuplicateName ex) { + System.out.println(baseMsg + ex); + System.exit(-1); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/iorintsockfact/SocketFactory.java b/functional-tests/src/test/java/corba/iorintsockfact/SocketFactory.java new file mode 100644 index 000000000..a5739c276 --- /dev/null +++ b/functional-tests/src/test/java/corba/iorintsockfact/SocketFactory.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jul 19 (Fri) 14:56:53 by Harold Carr. +// Last Modified : 2004 May 12 (Wed) 11:52:02 by Harold Carr. +// + +package corba.iorintsockfact; + +import java.util.Iterator; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.legacy.connection.DefaultSocketFactory; +import com.sun.corba.ee.impl.legacy.connection.EndPointInfoImpl; + +/** + * @author Harold Carr + */ +public class SocketFactory + extends + DefaultSocketFactory + implements + ORBSocketFactory +{ + public SocketFactory() + { + } + + // + // Client side. + // + + @Override + public SocketInfo getEndPointInfo(ORB orb, + IOR ior, + SocketInfo socketInfo) + { + // NOTE: this only uses the first IIOP profile. + // If there are multiple profiles a different API would be used + // inside a loop. + IIOPProfileTemplate iptemp = + (IIOPProfileTemplate)ior.getProfile().getTaggedProfileTemplate() ; + + Iterator iterator = + iptemp.iteratorById(org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS.value); + + // NOTE: this only uses the first address. + // If one were to try another address after failure you would + // need a loop and a hashtable, hashed by IOR to keep a loop pointer. + // Note: IOR hashing is not particularly efficient. However, the + // CorbaContactInfoList version of this solves the problem. + while (iterator.hasNext()) { + Client.foundAlternateIIOPAddressComponent = true; // For test. + + AlternateIIOPAddressComponent iiopAddressComponent = + (AlternateIIOPAddressComponent) iterator.next(); + return new EndPointInfoImpl( + ORBSocketFactory.IIOP_CLEAR_TEXT, + iiopAddressComponent.getAddress().getPort(), + iiopAddressComponent.getAddress().getHost()); + } + + // No alternate addresses. Just use profile address. + Client.foundAlternateIIOPAddressComponent = false; // For test. + + IIOPProfileTemplate temp = + (IIOPProfileTemplate)ior.getProfile().getTaggedProfileTemplate() ; + IIOPAddress primary = temp.getPrimaryAddress() ; + String host = primary.getHost().toLowerCase(); + int port = primary.getPort(); + return new EndPointInfoImpl(ORBSocketFactory.IIOP_CLEAR_TEXT, + primary.getPort(), + primary.getHost().toLowerCase()); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/islocal/Client.java b/functional-tests/src/test/java/corba/islocal/Client.java new file mode 100644 index 000000000..ca10a4a40 --- /dev/null +++ b/functional-tests/src/test/java/corba/islocal/Client.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:54:21 by Harold Carr. +// Last Modified : 2003 May 19 (Mon) 16:06:58 by Harold Carr. +// + +package corba.islocal; + +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; + +import corba.framework.Controller; +import corba.hcks.C; +import corba.hcks.U; + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; + +public class Client +{ + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static ORB orb; + public static InitialContext initialContext; + + public static idlI idlIConnect; + public static idlI idlIPOA; + public static rmiiI rmiiIConnect; + public static rmiiI rmiiIPOA; + + public static String idlIConnectArg = Server.idlIConnect; + public static String idlIPOAArg = Server.idlIPOA; + public static String rmiiIConnectArg = Server.rmiiIConnect; + public static String rmiiIPOAArg = Server.rmiiIPOA; + + public static int errors = 0; + public static Thread clientThread; + + public static void main(String[] av) + { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + idlIConnect = idlIHelper.narrow(U.resolve(Server.idlIConnect,orb)); + idlIPOA = idlIHelper.narrow(U.resolve(Server.idlIPOA, orb)); + + rmiiIConnect = (rmiiI) + U.lookupAndNarrow(Server.rmiiIConnect, + rmiiI.class, initialContext); + + /* + rmiiIPOA = (rmiiI) + U.lookupAndNarrow(C.rmiiSL, rmiiI.class, initialContext); + */ + + + U.sop("-----------isLocal-------------"); + + boolean is_local_result = StubAdapter.isLocal( rmiiIConnect ) ; + U.sop("is_local: " + is_local_result); + if (is_local_result != ColocatedClientServer.isColocated) { + errors++; + U.sop("!!! is_local value incorrect !!!"); + } + + /* REVISIT - you cannot call StubAdapter.isLocal outside of stub. + It HAS state. + boolean isLocalResult = + StubAdapter.isLocal((javax.rmi.CORBA.Stub)rmiiIConnect); + U.sop("StubAdapter.isLocal: " + isLocalResult); + if (isLocalResult != ColocatedClientServer.isColocated) { + errors++; + U.sop("!!! StubAdapter.isLocal value incorrect !!!"); + } + */ + + U.sop("-----------calls-------------"); + + if (ColocatedClientServer.isColocated) { + clientThread = Thread.currentThread(); + } + + U.sop("CLIENT: " + idlIConnect.o(idlIConnectArg)); + U.sop("CLIENT: " + idlIPOA.o(idlIPOAArg)); + U.sop("CLIENT: " + rmiiIConnect.m(rmiiIConnectArg)); + /* + U.sop("CLIENT: " + rmiiIPOA.m(rmiiIPOAArg)); + */ + + orb.shutdown(true); + + if (errors != 0) { + U.sop("!!! Errors found !!!"); + System.exit(1); + } + + } catch (Exception e) { + U.sopUnexpectedException(main + " : ", e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/islocal/ColocatedClientServer.java b/functional-tests/src/test/java/corba/islocal/ColocatedClientServer.java new file mode 100644 index 000000000..d40c57f1a --- /dev/null +++ b/functional-tests/src/test/java/corba/islocal/ColocatedClientServer.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 17 (Thu) 17:05:00 by Harold Carr. +// Last Modified : 2003 Apr 23 (Wed) 12:12:39 by Harold Carr. +// + +package corba.islocal; + +import java.util.Properties; +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; +import corba.hcks.C; +import corba.hcks.U; + +public class ColocatedClientServer +{ + public static final String baseMsg = ColocatedClientServer.class.getName(); + public static final String main = baseMsg + ".main"; + + // REVISIT: FRAMEWORK DEVELOPMENT + // REMOVE THIS LATER. + // Necessary so calls not going through locals do not hang + // until I implement the reader thread/work split. + public static int fragmentSize = -1; + //public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String[] av) + { + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + Properties props = new Properties(); + props.setProperty("com.sun.corba.ee.ORBAllowLocalOptimization", + "true"); + orb = ORB.init(av, props); + U.sop(main + " : creating ORB."); + Server.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + Client.orb = orb; + + // Share a naming context between client and server + // so StubAdapter.isLocal is true. + + // Use the same ORB which has interceptor properties set. + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + Server.initialContext = initialContext; + Client.initialContext = initialContext; + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + Client.main(av); + if (Client.errors != 0) { + System.exit(1); + } + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/islocal/CustomClassLoader.java b/functional-tests/src/test/java/corba/islocal/CustomClassLoader.java new file mode 100644 index 000000000..ea3a8fef7 --- /dev/null +++ b/functional-tests/src/test/java/corba/islocal/CustomClassLoader.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 May 18 (Sun) 15:17:31 by Harold Carr. +// Last Modified : 2003 May 19 (Mon) 13:33:33 by Harold Carr. +// + +package corba.islocal; + +import java.util.Hashtable; +import java.util.StringTokenizer; +import java.util.Vector; + +import corba.framework.Loader; + +public class CustomClassLoader + extends Loader +{ + private int indent = 0; + private Hashtable classes = new Hashtable(); + private boolean debug = false; + + public CustomClassLoader() + { + addPaths("java.class.path"); + } + + private void addPaths(String propertyName) + { + StringTokenizer tokens = + new StringTokenizer(System.getProperty(propertyName), + System.getProperty("path.separator")); + while (tokens.hasMoreTokens()) { + addPath(tokens.nextToken()); + } + } + + protected synchronized Class loadClass(String name, boolean resolve) + throws ClassNotFoundException + { + boolean errorFound = false; + Class c = null; + try { + + printIndent(indent++, ">> " + name); + + c = (Class) classes.get(name); + if (c != null) { + return c; + } + + try { + c = findClass(name); + } catch (ClassNotFoundException e) { + c = super.findSystemClass(name); + return c; + } + if (resolve) { + resolveClass(c); + } + } catch (Throwable t) { + errorFound = true; + printIndent(--indent, " 0) { + String msg = "WorkerThread(s) had " + errors + " error(s)"; + System.out.println("----------------------------------------"); + System.out.println(msg); + System.out.println("----------------------------------------"); + throw new Exception(msg); + } + + System.out.println("----------------------------------------"); + System.out.println("discarding requests"); + System.out.println("----------------------------------------"); + + f.discardRequests(); + + // Each of these should throw an exception, but that's what they're + // supposed to do + + try { + invoke(h1); + throw new Exception("Didn't throw COMM_FAILURE on invoke(h1)"); + } catch ( COMM_FAILURE ex ) { + checkTransient("h1", ex); + } + try { + invoke(h2); + throw new Exception("Didn't throw COMM_FAILURE on invoke(h2)"); + } catch ( COMM_FAILURE ex ) { + checkTransient("h2", ex); + } + try { + invoke(h3); + throw new Exception("Didn't throw COMM_FAILURE on invoke(h3)"); + } catch ( COMM_FAILURE ex ) { + checkTransient("h3", ex); + } + try { + invoke(h4); + throw new Exception("Didn't throw COMM_FAILURE on invoke(h4)"); + } catch ( COMM_FAILURE ex ) { + checkTransient("h4", ex); + } + + System.out.println("----------------------------------------"); + System.out.println("deactivating"); + System.out.println("----------------------------------------"); + + f.deactivate(); + + try { + invoke(h1); + throw new Exception("Didn't throw OBJ_ADAPTER on invoke(h1)"); + } catch ( OBJ_ADAPTER ex ) { + System.out.println("----------------------------------------"); + System.out.println("Correct behavior - OBJ_ADAPTER/h1"); + System.out.println("----------------------------------------"); + } + try { + invoke(h2); + throw new Exception("Didn't throw OBJ_ADAPTER on invoke(h2)"); + } catch ( OBJ_ADAPTER ex ) { + System.out.println("----------------------------------------"); + System.out.println("Correct behavior - OBJ_ADAPTER/h2"); + System.out.println("----------------------------------------"); + } + try { + invoke(h3); + throw new Exception("Didn't throw OBJ_ADAPTER on invoke(h3)"); + } catch ( OBJ_ADAPTER ex ) { + System.out.println("----------------------------------------"); + System.out.println("Correct behavior - OBJ_ADAPTER/h3"); + System.out.println("----------------------------------------"); + } + try { + invoke(h4); + throw new Exception("Didn't throw OBJ_ADAPTER on invoke(h4)"); + } catch ( OBJ_ADAPTER ex ) { + System.out.println("----------------------------------------"); + System.out.println("Correct behavior - OBJ_ADAPTER/h4"); + System.out.println("----------------------------------------"); + } + + try { + f.activate(); + throw new Exception("Didn't throw AdapterInactive"); + } catch (AdapterInactive ex) { + System.out.println("----------------------------------------"); + System.out.println("Correct behavior - AdapterInactive"); + System.out.println("----------------------------------------"); + } + + } catch (Exception e) { + System.out.println("----------------------------------------"); + System.out.println("Client FAILED"); + System.out.println("----------------------------------------"); + e.printStackTrace(System.out); + System.exit(1); + } + + System.out.println("----------------------------------------"); + System.out.println("Client SUCCEEDED"); + System.out.println("----------------------------------------"); + } + + public static Hello createHello(CreationMethods c, GenericFactory f) + { + return HelloHelper.narrow(f.create(HelloHelper.id(), + "corba.poamanager.HelloImpl", + c)); + } + + static final void invoke(Hello h) + { + System.out.println(h.hi()); + } + + static final WorkerThread invokeOnThread(Hello h) + { + WorkerThread th = new WorkerThread(h); + th.start(); + return th; + } + + public static void checkTransient(String msg, COMM_FAILURE e) + { + SystemException expected = + orbutilWrapper.communicationsRetryTimeout( new RuntimeException(), + -1); + SystemException expectedCause = poaWrapper.poaDiscarding(); + if (e.getClass().isInstance(expected) + && ((SystemException)e).minor == expected.minor + && ((SystemException)e).completed == expected.completed + && e.getCause() != null + && e.getCause().getClass().isInstance(expectedCause) + && ((SystemException)e.getCause()).minor == expectedCause.minor + && ((SystemException)e.getCause()).completed == expectedCause.completed) + { + System.out.println("----------------------------------------"); + System.out.println(msg + " TRANSIENT timeout SUCCESS"); + System.out.println("----------------------------------------"); + } else { + String message = msg + " TRANSIENT timeout FAILED"; + System.out.println("----------------------------------------"); + System.out.println(message); + System.out.println("----------------------------------------"); + throw new RuntimeException(message); + } + } +} + + +class WorkerThread extends Thread +{ + Hello h; + private boolean errorOccured; + + WorkerThread(Hello h) + { + this.h = h; + errorOccured = false; + } + + public void run() + { + try { + System.out.println(h.hi()); + } catch (Exception e) { + errorOccured = true; + e.printStackTrace(); + } + } + + public boolean errorOccured() + { + return errorOccured; + } +} + + diff --git a/functional-tests/src/test/java/corba/poamanager/HelloImpl.java b/functional-tests/src/test/java/corba/poamanager/HelloImpl.java new file mode 100644 index 000000000..3d665b64d --- /dev/null +++ b/functional-tests/src/test/java/corba/poamanager/HelloImpl.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poamanager; + +import HelloStuff.HelloPOA; + +public class HelloImpl extends HelloPOA +{ + public String hi() { + try { + Thread.sleep(10); // to allow interesting threading behavior + } catch ( InterruptedException ex ) {} + return "Welcome, POA"; + } +} + + diff --git a/functional-tests/src/test/java/corba/poamanager/HelloServer.java b/functional-tests/src/test/java/corba/poamanager/HelloServer.java new file mode 100644 index 000000000..c2063c1ae --- /dev/null +++ b/functional-tests/src/test/java/corba/poamanager/HelloServer.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poamanager; + +import Util.GenericFactoryHelper; +import org.omg.PortableServer.POA; + +public class HelloServer { + public static void main(String[] args) { + try { + Utility u = new Utility(args); + POA rootPoa = (POA) u.getORB().resolve_initial_references("RootPOA"); + POA poa = rootPoa.create_POA("AnotherPOA", null, null); + rootPoa.the_POAManager().activate(); + + FactoryImpl theFactory = new FactoryImpl(poa); + + byte[] id = rootPoa.activate_object(theFactory); + + u.writeFactory(GenericFactoryHelper.narrow( + rootPoa.servant_to_reference(theFactory))); + + poa.the_POAManager().activate(); + + System.out.println("Server is ready."); + u.getORB().run(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } +} diff --git a/functional-tests/src/test/java/corba/poamanager/POAManagerTest.java b/functional-tests/src/test/java/corba/poamanager/POAManagerTest.java new file mode 100644 index 000000000..9bf3c8466 --- /dev/null +++ b/functional-tests/src/test/java/corba/poamanager/POAManagerTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poamanager; + +import test.Test; +import corba.framework.*; +import java.util.*; + +public class POAManagerTest extends CORBATest +{ + protected void doTest() throws Throwable + { + Controller orbd = createORBD(); + Controller server = createServer("corba.poamanager.HelloServer"); + Controller client = createClient("corba.poamanager.HelloClient"); + + orbd.start(); + server.start(); + client.start(); + + client.waitFor(1000 * 60 * 5); + + client.stop(); + server.stop(); + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/corba/poamanager/Utility.java b/functional-tests/src/test/java/corba/poamanager/Utility.java new file mode 100644 index 000000000..0a4f7d006 --- /dev/null +++ b/functional-tests/src/test/java/corba/poamanager/Utility.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poamanager; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.util.Properties; +import org.omg.CORBA.ORB; + +public class Utility { + private ORB orb; + + public Utility(String args[]) { + orb = createORB(args); + } + + private static ORB createORB(String args[]) { + Properties props = new Properties(); + props.setProperty("org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.setProperty(ORBConstants.TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY, "250:2000:100"); + // props.setProperty("com.sun.corba.ee.ORBDebug", "transport,subcontract,poa"); + ORB o = ORB.init(args, props); + return o; + } + + public ORB getORB() { + return this.orb; + } + + public void writeObjref(org.omg.CORBA.Object ref, String file) { + String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file; + try { + DataOutputStream out = new + DataOutputStream(new FileOutputStream(fil)); + out.writeBytes(orb.object_to_string(ref)); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + } + + public org.omg.CORBA.Object readObjref(String file) { + String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file; + try { + BufferedReader in = new BufferedReader(new FileReader(fil)); + String ior = in.readLine(); + System.out.println("IOR: "+ior); + return orb.string_to_object(ior); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + return null; + } + + public void writeFactory(Util.GenericFactory ref) { + writeObjref(ref, "Factory"); + } + + public Util.GenericFactory readFactory() { + return Util.GenericFactoryHelper.narrow(readObjref("Factory")); + } +} + diff --git a/functional-tests/src/test/java/corba/poapolicies/BasicObjectFactoryImpl.java b/functional-tests/src/test/java/corba/poapolicies/BasicObjectFactoryImpl.java new file mode 100644 index 000000000..8fbe92a43 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/BasicObjectFactoryImpl.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import Util.CreationMethods; +import Util.FactoryPOA; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; + +public class BasicObjectFactoryImpl extends FactoryPOA +{ + final boolean useServantToReference = true; + + final String idString = new String("Blue Skies, Black Death"); + + POA poa; + + public java.lang.Object doneCV = new java.lang.Object(); + + void setPOA(POA p) { + poa = p; + } + + public void overAndOut() { + synchronized (doneCV) { + doneCV.notifyAll(); + } + } + + public org.omg.CORBA.Object create(String intfName, + String implName, CreationMethods how) { + try { + + System.err.println("Creating: " + implName); + + // create Servant first. + + Servant s; + try { + s = (Servant) + Class.forName(implName).newInstance(); + } catch (Exception ex) { + System.err.println("Problems finding: " + implName); + ex.printStackTrace(); + System.err.println("---"); + throw ex; + } + + org.omg.CORBA.Object ref = null; + + switch (how.value()) { + case Util.CreationMethods._EXPLICIT_ACTIVATION_WITH_POA_ASSIGNED_OIDS: + { + byte[] id = poa.activate_object(s); + if (useServantToReference) + ref = poa.servant_to_reference(s); + else + ref = poa.id_to_reference(id); + } + break; + case Util.CreationMethods._EXPLICIT_ACTIVATION_WITH_USER_ASSIGNED_OIDS: + { + byte[] id = idString.getBytes(); + poa.activate_object_with_id(id, s); + if (useServantToReference) + ref = poa.servant_to_reference(s); + else + ref = poa.id_to_reference(id); + } + break; + case Util.CreationMethods._CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_POA_ASSIGNED_OIDS: + { + ref = poa.create_reference(intfName); + byte[] id = poa.reference_to_id(ref); + poa.activate_object_with_id(id, s); + } + break; + case Util.CreationMethods._CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_USER_ASSIGNED_OIDS: + { + String newIdString = "ABCD"; + byte[] id = newIdString.getBytes(); + ref = + poa.create_reference_with_id(id, intfName); + poa.activate_object_with_id(id, s); + } + break; + } + return ref; + } catch (Exception e) { + System.err.println("BasicObjectFactoryImpl"); + e.printStackTrace(); + System.exit(1); + } + return null; + } +} + + diff --git a/functional-tests/src/test/java/corba/poapolicies/FactoryForRetainAndUseActiveMapOnly.java b/functional-tests/src/test/java/corba/poapolicies/FactoryForRetainAndUseActiveMapOnly.java new file mode 100644 index 000000000..a6b0e8493 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/FactoryForRetainAndUseActiveMapOnly.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import org.omg.CORBA.Policy; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.POAPackage.AdapterAlreadyExists; +import org.omg.PortableServer.POAPackage.InvalidPolicy; +import org.omg.PortableServer.RequestProcessingPolicyValue; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +public class FactoryForRetainAndUseActiveMapOnly implements POAFactory +{ + + public POA createPOA(POA parent) + throws AdapterAlreadyExists, InvalidPolicy + { + Policy[] policies = new Policy[2]; + + System.out.println("createPOA1"); + + policies[0] = + parent.create_servant_retention_policy( + ServantRetentionPolicyValue.RETAIN); + + System.out.println("createPOA2"); + + policies[1] = + parent.create_request_processing_policy( + RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY); + + + System.out.println("createPOA3"); + + POA x = parent.create_POA("RetainAndUseActiveMap", + null, + policies); + + System.out.println("createPOA4"); + + return x; + } + + public String getObjectFactoryName() { + return "corba.poapolicies.BasicObjectFactoryImpl"; + } +} diff --git a/functional-tests/src/test/java/corba/poapolicies/FactoryForRetainAndUseServantManager.java b/functional-tests/src/test/java/corba/poapolicies/FactoryForRetainAndUseServantManager.java new file mode 100644 index 000000000..98760c34a --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/FactoryForRetainAndUseServantManager.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; + +import java.io.*; +import java.util.*; + +import Util.*; + +public class FactoryForRetainAndUseServantManager implements POAFactory { + +// org.omg.CORBA.ORB Orb; + +// public void setORB(org.omg.CORBA.ORB orb) { +// Orb = orb; +// } + + public POA createPOA(POA parent) + throws AdapterAlreadyExists, InvalidPolicy + { + Policy[] policies = new Policy[2]; + policies[0] = + parent.create_servant_retention_policy(ServantRetentionPolicyValue.RETAIN); + policies[1] = + parent.create_request_processing_policy(RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + + POA p = parent.create_POA("RetainAndUseServantManager", + null, + policies); + try { + ServantActivatorImpl smi = new ServantActivatorImpl(); + p.activate_object(smi); + org.omg.CORBA.Object objRef = p.servant_to_reference(smi); + ServantActivator sl = ServantActivatorHelper.narrow(objRef); + p.set_servant_manager(sl); + } catch (WrongPolicy w) { + System.err.println("Wrong policy in RetainAndUseServantManager POA"); + } catch (Exception exp) { + System.err.println("Exception RetainAndUseServantManager POA"); + } + return p; + } + + public String getObjectFactoryName() { + return "corba.poapolicies.ObjectFactoryUsingServantManager"; + } +} diff --git a/functional-tests/src/test/java/corba/poapolicies/HelloClient.java b/functional-tests/src/test/java/corba/poapolicies/HelloClient.java new file mode 100644 index 000000000..b13f913c3 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/HelloClient.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import HelloStuff.Hello; +import HelloStuff.HelloHelper; +import Util.CreationMethods; +import Util.Factory; + +public class HelloClient { + public static Hello createHello(CreationMethods c, Factory f) { + System.out.println("createHello"); + String id = HelloHelper.id(); + System.out.println("id: " + id); + + System.out.println("Factory class: " + f.getClass().getName()); + + org.omg.CORBA.Object obj = f.create(id, "corba.poapolicies.HelloImpl", c); + + System.out.println("Created object"); + + Hello result = HelloHelper.narrow(obj); + + System.out.println("narrowed it"); + + return result; + + /* + return HelloHelper.narrow(f.create(HelloHelper.id(), + "HelloImpl", + c)); + */ + } + + static final void invoke(Hello h) { + System.out.println(h.hi()); + } + + public static void main(String[] args) { + + try { + + System.out.println("Client starting"); + + Utility u = new Utility(args); + Factory f = u.readFactory(); + + System.out.println("readFactory"); + + + System.out.println("invoke 1"); + + Hello h1 = + createHello(CreationMethods.EXPLICIT_ACTIVATION_WITH_POA_ASSIGNED_OIDS, + f); + + System.out.println("created 1, now invoking"); + + invoke(h1); + + System.out.println("invoke 2"); + + Hello h2 = + createHello(CreationMethods.EXPLICIT_ACTIVATION_WITH_USER_ASSIGNED_OIDS, + f); + invoke(h2); + + System.out.println("invoke 3"); + + Hello h3 = + createHello(CreationMethods.CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_POA_ASSIGNED_OIDS, + f); + invoke(h3); + + System.out.println("invoke 4"); + + Hello h4 = + createHello(CreationMethods.CREATE_REFERENCE_BEFORE_ACTIVATION_WITH_USER_ASSIGNED_OIDS, + f); + invoke(h4); + + System.out.println("Calling overAndOut"); + + f.overAndOut(); + + System.out.println("Client finished"); + + } catch (Exception e) { + System.err.println("Client level"); + e.printStackTrace(); + try { + System.err.flush(); + } catch (Exception ex) {} + System.exit(1); + } + } +} + diff --git a/functional-tests/src/test/java/corba/poapolicies/HelloImpl.java b/functional-tests/src/test/java/corba/poapolicies/HelloImpl.java new file mode 100644 index 000000000..af0b5db60 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/HelloImpl.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import HelloStuff.HelloPOA; + +public class HelloImpl extends HelloPOA +{ + public byte[] id; + public HelloImpl() { + id = null; + } + public HelloImpl(byte[] oid) { + id = oid; + } + public String hi() { + if (id == null) + return "Welcome, POA"; + else + return "Welcome, POA (oid = "+new String(id)+")"; + } +} + + diff --git a/functional-tests/src/test/java/corba/poapolicies/HelloServer.java b/functional-tests/src/test/java/corba/poapolicies/HelloServer.java new file mode 100644 index 000000000..35561d9aa --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/HelloServer.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import Util.FactoryHelper; +import org.omg.PortableServer.POA; + +class Waiter extends Thread { + BasicObjectFactoryImpl f; + POA p; + public Waiter(POA p, BasicObjectFactoryImpl f) { + this.f = f; + this.p = p; + } + public void run() { + try { + synchronized (f.doneCV) { + f.doneCV.wait(); + p.destroy(true, true); + } + } catch (InterruptedException ex) { } + } +} + +public class HelloServer +{ + public static boolean debug = false; + + public static void main(String[] args) { + try { + String debugp = System.getProperty("DebugPOA"); + if (debugp != null) + debug = true; + + POAFactory f = null; + String factory = System.getProperty("POAFactory"); + System.out.println("Server will use factory:" + factory); + + System.out.println("Class path: " + System.getProperty("java.class.path")); + + + if (factory != null && !factory.equals("")) + f = (POAFactory) Class.forName(factory).newInstance(); + + Utility u = new Utility(args); + + POA poa = (POA) u.getORB().resolve_initial_references("RootPOA"); + + if (poa == null) + System.out.println("POA is null :("); + + POA thePOA = f == null ? poa : f.createPOA(poa); + + BasicObjectFactoryImpl theFactory; + if (f == null) + theFactory = new BasicObjectFactoryImpl(); + else + theFactory = (BasicObjectFactoryImpl) + Class.forName(f.getObjectFactoryName()).newInstance(); + + System.out.println("Got the basic object factory"); + + + theFactory.setPOA(thePOA); + + byte[] id = thePOA.activate_object(theFactory); + + u.writeFactory(FactoryHelper.narrow(thePOA.servant_to_reference(theFactory))); + + thePOA.the_POAManager().activate(); + + // What does this thing do??????? + new Waiter(poa, theFactory).start(); + + System.out.println("Server is ready."); + u.getORB().run(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } +} diff --git a/functional-tests/src/test/java/corba/poapolicies/ObjectFactoryUsingServantManager.java b/functional-tests/src/test/java/corba/poapolicies/ObjectFactoryUsingServantManager.java new file mode 100644 index 000000000..c9cb63d52 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/ObjectFactoryUsingServantManager.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import Util.CreationMethods ; + +public class ObjectFactoryUsingServantManager extends BasicObjectFactoryImpl { + private static int idNum = 0; + + @Override + public org.omg.CORBA.Object create(String intfName, + String implName, + CreationMethods how) { + + String objectId = "ObjectID" + idNum++; + + try { + byte[] id = objectId.getBytes(); + + return poa.create_reference_with_id(id, intfName); + } catch (Exception e) { + System.err.println("ObjectFactoryUsingServantManager"); + e.printStackTrace(); + System.exit(1); + } + return null; + } +} diff --git a/functional-tests/src/test/java/corba/poapolicies/POAFactory.java b/functional-tests/src/test/java/corba/poapolicies/POAFactory.java new file mode 100644 index 000000000..2a797e1f4 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/POAFactory.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; + +public interface POAFactory { + public POA createPOA(POA parent) throws AdapterAlreadyExists, + InvalidPolicy; + public String getObjectFactoryName(); +} + diff --git a/functional-tests/src/test/java/corba/poapolicies/POAPoliciesTest.java b/functional-tests/src/test/java/corba/poapolicies/POAPoliciesTest.java new file mode 100644 index 000000000..756c9e49a --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/POAPoliciesTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import java.util.*; +import test.Test; +import corba.framework.*; + +public class POAPoliciesTest extends CORBATest +{ + private void testWithFactory(String poaFactory) throws Throwable + { + Test.dprint("Using POA Factory: " + + (poaFactory == null ? "(Default)" : poaFactory)); + + if (poaFactory != null) { + Properties serverProps = Options.getServerProperties(); + serverProps.setProperty("POAFactory", poaFactory); + } + + Controller server = createServer("corba.poapolicies.HelloServer"); + + Controller client = createClient("corba.poapolicies.HelloClient", poaFactory ); + + server.start(); + + client.start(); + + client.waitFor(); + + client.stop(); + + server.stop(); + } + + protected void doTest() throws Throwable + { + String prefix = "corba.poapolicies."; + testWithFactory(prefix + "FactoryForRetainAndUseActiveMapOnly"); + testWithFactory(prefix + "FactoryForRetainAndUseServantManager"); + } +} + + diff --git a/functional-tests/src/test/java/corba/poapolicies/ServantActivatorImpl.java b/functional-tests/src/test/java/corba/poapolicies/ServantActivatorImpl.java new file mode 100644 index 000000000..a3c844e96 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/ServantActivatorImpl.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +//public class ServantActivatorImpl extends org.omg.CORBA.LocalObject implements ServantActivator { + +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantActivatorPOA; + +public class ServantActivatorImpl extends ServantActivatorPOA { + public Servant incarnate(byte[] oid, POA adapter) + throws org.omg.PortableServer.ForwardRequest { + Servant servant = new HelloImpl(oid); + if (HelloServer.debug) + System.out.println("ServantActivatorImpl.incarnate (" + +" oid = "+oid + +" poa = "+adapter.the_name()); + + return servant; + } + + public void etherealize(byte[] oid, POA adapter, Servant servant, + boolean cleanup_in_progress, + boolean remaining_activations) { + if (HelloServer.debug) + System.out.println("ServantActivatorImpl.etherealize (" + +" oid = "+oid + +" cleanup = "+cleanup_in_progress + +" remaining_activations = "+remaining_activations + +")"); + } +} diff --git a/functional-tests/src/test/java/corba/poapolicies/Utility.java b/functional-tests/src/test/java/corba/poapolicies/Utility.java new file mode 100644 index 000000000..4851fffa4 --- /dev/null +++ b/functional-tests/src/test/java/corba/poapolicies/Utility.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poapolicies; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Properties; +import org.omg.CORBA.ORB; + +public class Utility { + private ORB orb; + + public Utility(String[] orbArgs) { + orb = createORB(orbArgs); + } + + private ORB createORB(String[] args) { + Properties props = System.getProperties(); + props.put("org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB o = ORB.init(args, props); + return o; + } + + public ORB getORB() { + return this.orb; + } + + public void writeObjref(org.omg.CORBA.Object ref, String file) { + String fil = System.getProperty("output.dir") + + System.getProperty("file.separator") + + file; + try { + DataOutputStream out = new + DataOutputStream(new FileOutputStream(fil)); + out.writeBytes(orb.object_to_string(ref)); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + } + + public org.omg.CORBA.Object readObjref(String file) { + String fil = System.getProperty("output.dir") + + System.getProperty("file.separator") + + file; + try { + DataInputStream in = + new DataInputStream(new FileInputStream(fil)); + String ior = in.readLine(); + System.out.println("IOR: "+ior); + return orb.string_to_object(ior); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + return null; + } + + public void writeFactory(Util.Factory ref) { + writeObjref(ref, "Factory"); + } + + public Util.Factory readFactory() { + return Util.FactoryHelper.narrow(readObjref("Factory")); + } +} + diff --git a/functional-tests/src/test/java/corba/poatest/OneWayTest.java b/functional-tests/src/test/java/corba/poatest/OneWayTest.java new file mode 100644 index 000000000..f348a50a2 --- /dev/null +++ b/functional-tests/src/test/java/corba/poatest/OneWayTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poatest; + +import corba.framework.*; +import java.util.*; + +public class OneWayTest extends CORBATest +{ + protected void doTest() throws Throwable + { + Controller orbd = createORBD(); + + orbd.start(); + + Controller server = createServer("corba.poatest.helloServer"); + + server.start(); + + Controller client = createClient("corba.poatest.helloClient"); + + client.start(); + + client.waitFor(); + + client.stop(); + + server.stop(); + + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/corba/poatest/helloClient.java b/functional-tests/src/test/java/corba/poatest/helloClient.java new file mode 100644 index 000000000..51b59edbf --- /dev/null +++ b/functional-tests/src/test/java/corba/poatest/helloClient.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poatest; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +import HelloA.hello ; +import HelloA.helloHelper; + +public class helloClient +{ + static hello helloRef; + + public static void main(String args[]) + { + try{ + // create and initialize the ORB + ORB orb = ORB.init(args, System.getProperties()); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent("Hello", ""); + NameComponent path[] = {nc}; + helloRef = helloHelper.narrow(ncRef.resolve(path)); + + System.out.println("Obtained a handle on server object: " + helloRef); + helloRef.sayHello(); + System.out.println("OK! Returned from oneway call !!"); + + // call shutdown + System.out.println("Invoking shutdown..."); + helloRef.shutdown(); + System.out.println("OK! Returned from shutdown!!"); + + + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } + +} + diff --git a/functional-tests/src/test/java/corba/poatest/helloServer.java b/functional-tests/src/test/java/corba/poatest/helloServer.java new file mode 100644 index 000000000..2b8868e19 --- /dev/null +++ b/functional-tests/src/test/java/corba/poatest/helloServer.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.poatest; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POA; +import HelloA.*; + +import java.util.Properties; + +class helloServant extends helloPOA +{ + public void shutdown() + { + System.err.println("In helloServant.shutdown, exiting.."); + System.exit(0); + } + + public void sayHello() + { + System.out.println("\nHello world !!\n"); + + } +} + +public class helloServer { + + public static void main(String args[]) + { + try{ + // create and initialize the ORB + Properties props = new Properties(); + ORB orb = ORB.init(args, System.getProperties()); + + POA rootpoa = (POA)orb.resolve_initial_references("RootPOA"); + rootpoa.the_POAManager().activate(); + + POA childpoa = rootpoa.create_POA("childPOA", null,null); + childpoa.the_POAManager().activate(); + + // create servant and register it with the ORB + helloServant helloRef = new helloServant(); + childpoa.activate_object(helloRef); + + // get the root naming context + org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + org.omg.CORBA.Object ref = childpoa.servant_to_reference(helloRef); + hello href = helloHelper.narrow(ref); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("Hello", ""); + NameComponent path[] = {nc}; + ncRef.rebind(path, href); + + System.out.println("Server is ready."); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + System.out.println("helloServant contacted"); + } + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + } +} + diff --git a/functional-tests/src/test/java/corba/preinvokepostinvoke/Interface.java b/functional-tests/src/test/java/corba/preinvokepostinvoke/Interface.java new file mode 100644 index 000000000..f2bdb7381 --- /dev/null +++ b/functional-tests/src/test/java/corba/preinvokepostinvoke/Interface.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.preinvokepostinvoke; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface Interface extends java.rmi.Remote { + public String o1(String x) throws RemoteException; + public String o2(String x) throws RemoteException; +} + diff --git a/functional-tests/src/test/java/corba/preinvokepostinvoke/MyServant.java b/functional-tests/src/test/java/corba/preinvokepostinvoke/MyServant.java new file mode 100644 index 000000000..8ea9b30fd --- /dev/null +++ b/functional-tests/src/test/java/corba/preinvokepostinvoke/MyServant.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.preinvokepostinvoke; + +import java.rmi.RemoteException ; +import javax.rmi.PortableRemoteObject ; +import org.omg.CORBA.ORB ; +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; + +class MyServant extends PortableRemoteObject implements Interface +{ + org.omg.CORBA.ORB orb; + public MyServant( org.omg.CORBA.ORB orb) throws RemoteException + { + this.orb = orb; + } + + public String o1(String arg) + { + System.out.println( "Interface.o1 called with " + arg ); + System.out.flush( ); + try { + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); + objRef = ncRef.resolve_str( "Instance2" ); + Interface i2 = + (Interface) PortableRemoteObject.narrow( objRef, Interface.class ); + i2.o2( "Invoking from Interface.o1..." ); + } catch( Throwable e ) { + System.err.println( " Exception ..." + e ); + e.printStackTrace( ); + System.exit( 1 ); + } + return "return value for interface.o1"; + } + + public String o2( String arg ) + { + System.out.println( "Interface.o2 called with " + arg ); + System.out.flush( ); + return "return value for interface.o2"; + } +} + diff --git a/functional-tests/src/test/java/corba/preinvokepostinvoke/MyServantLocator.java b/functional-tests/src/test/java/corba/preinvokepostinvoke/MyServantLocator.java new file mode 100644 index 000000000..931c99ce4 --- /dev/null +++ b/functional-tests/src/test/java/corba/preinvokepostinvoke/MyServantLocator.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.preinvokepostinvoke; + + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.ServantLocator; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; + +public class MyServantLocator + extends + org.omg.CORBA.LocalObject + implements + ServantLocator +{ + public ORB orb; + + public MyServantLocator(ORB orb) { this.orb = orb; } + + public Servant preinvoke(byte[] oid, POA poa, String operation, + CookieHolder cookieHolder) + { + System.out.println( "MyServantLocator.preinvoke called " ); + + TestAssert.preinvokeCalled( ); + + try { + return (Servant)javax.rmi.CORBA.Util.getTie(new MyServant( orb )); + } catch( Throwable e ) { + System.err.println( "Exception in MyServantLocator..." + e ); + e.printStackTrace( ); + } + return null; + } + + + public void postinvoke(byte[] oid, POA poa, String operation, + java.lang.Object cookie, Servant servant) + { + System.out.println( "MyServantLocator.postinvoke called " ); + + TestAssert.postinvokeCalled( ); + } +} + + diff --git a/functional-tests/src/test/java/corba/preinvokepostinvoke/PreInvokePostInvokeTest.java b/functional-tests/src/test/java/corba/preinvokepostinvoke/PreInvokePostInvokeTest.java new file mode 100644 index 000000000..d4e29edb5 --- /dev/null +++ b/functional-tests/src/test/java/corba/preinvokepostinvoke/PreInvokePostInvokeTest.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.preinvokepostinvoke; + +import corba.framework.Controller; +import corba.framework.CORBATest; +import corba.framework.Options; + +public class PreInvokePostInvokeTest + extends + CORBATest +{ + protected void doTest() throws Throwable + { + Controller orbd = createORBD(); + Controller server = createServer("corba.preinvokepostinvoke.Server" ); + + orbd.start(); + + server.start(); + + server.stop(); + + orbd.stop( ); + } +} diff --git a/functional-tests/src/test/java/corba/preinvokepostinvoke/TestAssert.java b/functional-tests/src/test/java/corba/preinvokepostinvoke/TestAssert.java new file mode 100644 index 000000000..0cc1e46a2 --- /dev/null +++ b/functional-tests/src/test/java/corba/preinvokepostinvoke/TestAssert.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.preinvokepostinvoke; + +public class TestAssert { + + private static int preInvokeCounter = 0; + private static int postInvokeCounter = 0; + + public static synchronized void startTest( ) { + preInvokeCounter = 0; + postInvokeCounter = 0; + } + + public static synchronized void preinvokeCalled( ) { + preInvokeCounter++; + } + + public static synchronized void postinvokeCalled( ) { + if( preInvokeCounter == 0 ) { + System.err.println( "ServantLocator.post_invoke() called before " + + " calling pre_invoke" ); + System.exit( 1 ); + } + postInvokeCounter++; + } + + public static synchronized void isTheCallBalanced( int expectedCount ) { + if ((preInvokeCounter != expectedCount ) + ||(postInvokeCounter != expectedCount ) ) + { + throw new RuntimeException( + "Test Failed because the preinvoke and " + + "postinvoke call is not balanced using " + + " FullServantCaching policy." + + "\n preInvokeCounter = " + preInvokeCounter + + "\n postInvokeCounter = " + postInvokeCounter + + "\n expectedCount = " + expectedCount ); + } + } +} diff --git a/functional-tests/src/test/java/corba/preinvokepostinvoke/readme.txt b/functional-tests/src/test/java/corba/preinvokepostinvoke/readme.txt new file mode 100644 index 000000000..bb540fe0c --- /dev/null +++ b/functional-tests/src/test/java/corba/preinvokepostinvoke/readme.txt @@ -0,0 +1,27 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Author: Hemanth Puttaswamy + +This test is to validate that the calls to ServantLocator.preinvoke() and +ServantLocator.postinvoke() is balanced if we use ServantCachingPolicy. + +The test contains 1 POA and 1 ServantLocator, 2 different Servants are bound +in NameService with the names "Instance1" and "Instance2". The Interface +for the Servant contains 2 methods o1 and o2. When client invoke Instance1.o1, +it will invoke Instance2.o2. This should result in a call trace of +------ +MyServantLocator.preinvoke called +Interface1.o1 called with Invoking from Client... +MyServantLocator.preinvoke called +Interface.o2 called with Invoking from Interface.o1... +MyServantLocator.postinvoke called +MyServantLocator.postinvoke called +----- diff --git a/functional-tests/src/test/java/corba/purgecalls/Client.java b/functional-tests/src/test/java/corba/purgecalls/Client.java new file mode 100644 index 000000000..22b2de688 --- /dev/null +++ b/functional-tests/src/test/java/corba/purgecalls/Client.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 14:19:20 by Harold Carr. +// Last Modified : 2003 Mar 12 (Wed) 09:55:39 by Harold Carr. +// + +package corba.purgecalls; + +import com.sun.corba.ee.spi.legacy.connection.Connection; +import corba.framework.Controller; +import corba.hcks.U; +import java.net.Socket; +import java.util.Properties; +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.ORB; + +public class Client +{ + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static ORB orb; + public static ServerSide rServerSide; + + // The client interceptor sets this. + public static Connection requestConnection; + + public static Throwable noExceptionExpected; + + public static void main(String av[]) + { + try { + Properties props = new Properties(); + props.put(U.ORBInitializerClass + "." + "corba.purgecalls.ClientORBInitializer", "ignored"); + orb = ORB.init(av, props); + + + rServerSide = + ServerSideHelper.narrow(U.resolve(Server.ServerSide, orb)); + + runTests(); + + // Wait for other thread to do its thing. + Thread.sleep(2000); + + U.sop("Test complete."); + + } catch (java.io.IOException e) { + + U.sop(main + " Expected: " + e); + + } catch (Throwable t) { + U.sopUnexpectedException(main + " : ", t); + System.exit(1); + } + + if (noExceptionExpected == null) { + U.normalExit(main); + // Do not explicitly exit to test that no non-daemon threads + // are hanging. + //System.exit(Controller.SUCCESS); + } else { + U.sopUnexpectedException(main + " : ", noExceptionExpected); + System.exit(1); + } + } + + public static void runTests() + throws + Exception + { + CallThread CallThread = new CallThread(); + CallThread.start(); + + Thread.sleep(5000); + + Socket socket = requestConnection.getSocket(); + socket.shutdownInput(); + socket.shutdownOutput(); + socket.getInputStream().close(); + socket.getOutputStream().close(); + socket.close(); + } +} + +class CallThread extends Thread +{ + CallThread () + { + } + public void run () + { + try { + Client.rServerSide.neverReturns(); + } catch (COMM_FAILURE e) { + U.sop("Expected: " + e); + } catch (Throwable t) { + Client.noExceptionExpected = t; + t.printStackTrace(); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/purgecalls/ClientInterceptor.java b/functional-tests/src/test/java/corba/purgecalls/ClientInterceptor.java new file mode 100644 index 000000000..f7a707bb8 --- /dev/null +++ b/functional-tests/src/test/java/corba/purgecalls/ClientInterceptor.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 14:50:11 by Harold Carr. +// Last Modified : 2003 Feb 11 (Tue) 14:12:55 by Harold Carr. +// + +package corba.purgecalls; + +import com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt; +import corba.hcks.U; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.SystemException; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; + +public class ClientInterceptor + extends + org.omg.CORBA.LocalObject + implements + ClientRequestInterceptor +{ + public static final String baseMsg = ClientInterceptor.class.getName(); + + // + // Interceptor operations + // + + public String name() + { + return baseMsg; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + sopCR(baseMsg, "send_request", ri); + Client.requestConnection = ((RequestInfoExt)ri).connection(); + } + + public void send_poll(ClientRequestInfo ri) + { + sopCR(baseMsg, "send_poll", ri); + } + + public void receive_reply(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_reply", ri); + checkServiceContexts(ri); + } + + public void receive_exception(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_exception", ri); + checkServiceContexts(ri); + } + + public void receive_other(ClientRequestInfo ri) + { + sopCR(baseMsg, "receive_other", ri); + checkServiceContexts(ri); + } + + // + // Utilities. + // + + public static void sopCR(String clazz, String point, ClientRequestInfo ri) + { + try { + U.sop(clazz + "." + point + " " + ri.operation()); + } catch (SystemException e) { + U.sopUnexpectedException(baseMsg + "." + point, e); + } + } + + public static void checkServiceContexts(ClientRequestInfo ri) + { + // The number does not matter. + // Just want to ensure no null pointer exception after purge calls. + try { + ri.get_reply_service_context(100); + } catch (BAD_PARAM e) { + U.sop(baseMsg + " Expected: " + e); + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/purgecalls/ClientORBInitializer.java b/functional-tests/src/test/java/corba/purgecalls/ClientORBInitializer.java new file mode 100644 index 000000000..451554626 --- /dev/null +++ b/functional-tests/src/test/java/corba/purgecalls/ClientORBInitializer.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 15:26:57 by Harold Carr. +// Last Modified : 2002 Jan 17 (Thu) 15:37:24 by Harold Carr. +// + +package corba.purgecalls; + +import corba.hcks.U; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; + +public class ClientORBInitializer + extends + org.omg.CORBA.LocalObject + implements + org.omg.PortableInterceptor.ORBInitializer +{ + public static final String baseMsg = ClientORBInitializer.class.getName(); + + public void pre_init(ORBInitInfo info) + { + try { + ClientInterceptor interceptor = new ClientInterceptor(); + info.add_client_request_interceptor(interceptor); + U.sop(baseMsg + ".pre_init"); + } catch (Throwable t) { + U.sopUnexpectedException(baseMsg, t); + } + } + + public void post_init(ORBInitInfo info) + { + } + +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/purgecalls/PurgecallsTest.java b/functional-tests/src/test/java/corba/purgecalls/PurgecallsTest.java new file mode 100644 index 000000000..2fce36f49 --- /dev/null +++ b/functional-tests/src/test/java/corba/purgecalls/PurgecallsTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 19:10:44 by Harold Carr. +// Last Modified : 2003 Mar 12 (Wed) 09:56:16 by Harold Carr. +// + +package corba.purgecalls; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +public class PurgecallsTest + extends + CORBATest +{ + public static final String thisPackage = + PurgecallsTest.class.getPackage().getName(); + + protected void doTest() + throws + Throwable + { + Controller orbd = createORBD(); + orbd.start(); + + Controller server = + createServer(thisPackage + "." + "Server", "Server"); + Controller client = + createClient(thisPackage + "." + "Client", "Client"); + + server.start(); + client.start(); + // When this test fails - it hangs, so do not wait forever. + client.waitFor(60000); + client.stop(); + server.stop(); + orbd.stop(); + } + +} + +// End of file. + + diff --git a/functional-tests/src/test/java/corba/purgecalls/Server.java b/functional-tests/src/test/java/corba/purgecalls/Server.java new file mode 100644 index 000000000..a615c50c0 --- /dev/null +++ b/functional-tests/src/test/java/corba/purgecalls/Server.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 14:09:43 by Harold Carr. +// Last Modified : 2002 Jan 17 (Thu) 15:42:33 by Harold Carr. +// + +package corba.purgecalls; + +import corba.framework.Controller; +import corba.hcks.C; +import corba.hcks.U; +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; + +public class Server +{ + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + + public static final String ServerSide = "ServerSide"; + + public static ORB orb; + public static POA rRootPOA; + public static ServerSide rServerSide; + + public static void main(String[] av) + { + try { + + U.sop(main + " starting"); + + orb = C.createORB(av, 1024); + rRootPOA = U.getRootPOA(orb); + rRootPOA.the_POAManager().activate(); + + U.createWithServantAndBind(ServerSide, + new ServerSideServant(), + rRootPOA, orb); + + U.sop(main + " ready"); + U.sop("Server is ready."); // CORBATest handshake. + + System.out.flush(); + + orb.run(); + + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + System.exit(Controller.SUCCESS); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/purgecalls/ServerSideServant.java b/functional-tests/src/test/java/corba/purgecalls/ServerSideServant.java new file mode 100644 index 000000000..a169c7655 --- /dev/null +++ b/functional-tests/src/test/java/corba/purgecalls/ServerSideServant.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Jan 17 (Thu) 14:14:42 by Harold Carr. +// Last Modified : 2002 Jan 17 (Thu) 15:39:39 by Harold Carr. +// + +package corba.purgecalls; + +import corba.hcks.U; + +class ServerSideServant + extends + ServerSidePOA +{ + public static final String baseMsg = ServerSideServant.class.getName(); + + public ServerSideServant ( ) { } + + public void neverReturns ( ) + { + U.sop(baseMsg + ".neverReturns"); + try { + Thread.sleep(Integer.MAX_VALUE); + } catch (InterruptedException e) { + U.sop(e); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/repid/Client.java b/functional-tests/src/test/java/corba/repid/Client.java new file mode 100644 index 000000000..46dd1ac27 --- /dev/null +++ b/functional-tests/src/test/java/corba/repid/Client.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.repid; + +import java.util.Properties; + +import org.omg.CORBA.ORB; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +public class Client { + + public static void main(String args[]) { + + try { + + Properties props = new Properties(System.getProperties()); + props.setProperty(ORBConstants.USE_REP_ID, "false"); + ORB orb = ORB.init(args, props); + + com.sun.corba.ee.spi.orb.ORB ourORB + = (com.sun.corba.ee.spi.orb.ORB) orb; + + if (ourORB.getORBData().useRepId() != false) { + throw new RuntimeException("ORB.useRepId flag is not false"); + } + + String[] inStrSeq = new String[] { "Hello", "World" }; + OutputStream ostr = (org.omg.CORBA_2_3.portable.OutputStream) + ourORB.create_output_stream(); + ostr.write_value(inStrSeq, new test.StringSeqHelper()); + InputStream istr = (org.omg.CORBA_2_3.portable.InputStream) + ostr.create_input_stream(); + String[] outStrSeq = (String[]) + istr.read_value(new test.StringSeqHelper()); + for (int i = 0; i < outStrSeq.length; i++) { + if (!(outStrSeq[i].equals(inStrSeq[i]))) { + throw new RuntimeException("Input/output value mismatch"); + } + } + + } catch (Exception e) { + System.out.println("ERROR : " + e); + e.printStackTrace(System.out); + System.exit (1); + } + } +} diff --git a/functional-tests/src/test/java/corba/repid/RepIdTest.java b/functional-tests/src/test/java/corba/repid/RepIdTest.java new file mode 100644 index 000000000..a4c4fc31c --- /dev/null +++ b/functional-tests/src/test/java/corba/repid/RepIdTest.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:31:43 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:54:44 by Harold Carr. +// + +package corba.repid; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +import corba.framework.*; + +public class RepIdTest extends CORBATest { + public static final String thisPackage = + RepIdTest.class.getPackage().getName(); + + protected void doTest() throws Throwable { + Controller client = createClient("corba.repid.Client"); + + client.start(); + + client.waitFor(60000); + + client.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/requestpartitioning/Client.java b/functional-tests/src/test/java/corba/requestpartitioning/Client.java new file mode 100644 index 000000000..ca73d0c51 --- /dev/null +++ b/functional-tests/src/test/java/corba/requestpartitioning/Client.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.requestpartitioning; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import corba.hcks.U; +import java.rmi.RemoteException; +import java.util.Properties; + +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; + +public class Client +{ + protected final static int stringSize = 10000; + protected final static String stringOf36 = + "abcdefghijklmnopqrstuvwxyz0123456789"; + protected String reallyReallyBigString = null; + protected Tester itsTester = null; + protected ORB itsOrb = null; + + public Client(String[] args) throws Exception { + + Properties props = System.getProperties(); + + itsOrb = (ORB)org.omg.CORBA.ORB.init(args, props); + + initializeReallyBigString(); + } + + protected void initializeReallyBigString() { + StringBuffer sb = new StringBuffer(stringSize); + int index = 0; + final int lengthOfStr = stringOf36.length(); + for (int i = 0; i < stringSize; i++) { + index = i % lengthOfStr; + sb.append(stringOf36.charAt(index)); + } + reallyReallyBigString = sb.toString(); + } + + protected void printError(int myPoolId, int remotePoolId) + throws Exception { + StringBuffer error = new StringBuffer(80); + error.append("FAILED: client requested thread pool id ("); + error.append(myPoolId); + error.append(") not executed on expected server thread pool id ("); + error.append(remotePoolId).append(")"); + U.sop(error.toString()); + throw new Exception(error.toString()); + } + + protected void runTest() throws RemoteException, Exception { + + U.sop("Getting name service..."); + org.omg.CORBA.Object objRef = + itsOrb.resolve_initial_references("NameService"); + NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); + U.sop("Got name service."); + + int expectedPoolId; + int returnedPoolId; + for (int i = 0; i < TestThreadPoolManager.NUMBER_OF_THREAD_POOLS_TO_CREATE; i++) + { + String name = "Tester" + i; + U.sop("Finding, looking up & narrowing " + name + " ..."); + itsTester = TesterHelper.narrow(ncRef.resolve_str(name)); + U.sop("Got " + name + " ..."); + + U.sop("Testing thread pool id (" + i + ") usage..."); + expectedPoolId = i; + returnedPoolId = + itsTester.getThreadPoolIdForThisRequest(reallyReallyBigString); + if (expectedPoolId != returnedPoolId) { + printError(expectedPoolId, returnedPoolId); + } + U.sop("Thead pool (" + i + ") test PASSED."); + } + + String defaultname = "DefaultTester"; + U.sop("Finding, looking up & narrowing " + defaultname + " ..."); + itsTester = TesterHelper.narrow(ncRef.resolve_str(defaultname)); + U.sop("Got " + defaultname + " ..."); + + U.sop("Testing DEFAULT thread pool usage..."); + expectedPoolId = 0; + returnedPoolId = + itsTester.getThreadPoolIdForThisRequest(reallyReallyBigString); + if (expectedPoolId != returnedPoolId) { + printError(expectedPoolId, returnedPoolId); + } + U.sop("Default thead pool test PASSED."); + + U.sop("All thread pool tests PASSED."); + } + + public static void main(String args[]) { + try { + + U.sop("Beginning test..."); + + Client client = new Client(args); + client.runTest(); + + U.sop("Test finished successfully..."); + + } catch (Throwable t) { + U.sop("Unexpected throwable..."); + t.printStackTrace(); + System.exit(1); + } + } +} + diff --git a/functional-tests/src/test/java/corba/requestpartitioning/RequestPartitioningTest.java b/functional-tests/src/test/java/corba/requestpartitioning/RequestPartitioningTest.java new file mode 100644 index 000000000..3590d7b01 --- /dev/null +++ b/functional-tests/src/test/java/corba/requestpartitioning/RequestPartitioningTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Test the request partitioning feature. +// +// This test creates a Server and a Client. +// The Server is configured to recieve requests for a given thread pool. +// +// Created : 2004 May 23 by Charlie Hunt. +// Last Modified : 2004 May 23 by Charlie Hunt. +// + +package corba.requestpartitioning; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.framework.Controller; +import corba.framework.CORBATest; +import corba.framework.Options; +import java.util.Properties; + +public class RequestPartitioningTest + extends + CORBATest +{ + public static final String thisPackage = + RequestPartitioningTest.class.getPackage().getName(); + + private final static int CLIENT_TIMEOUT = 90000; + + protected void doTest() + throws + Throwable + { + // Run test with DirectByteBuffers + Controller orbd = createORBD(); + orbd.start(); + + Properties serverProps = Options.getServerProperties(); + serverProps.setProperty(ORBConstants.ALWAYS_ENTER_BLOCKING_READ_PROPERTY, "true"); +// serverProps.setProperty(ORBConstants.DEBUG_PROPERTY,"transport,giop"); + Controller server = createServer(thisPackage + ".Server","Server1"); + server.start(); + + Properties clientProps = Options.getClientProperties(); + clientProps.setProperty(ORBConstants.ALWAYS_ENTER_BLOCKING_READ_PROPERTY, "true"); +// clientProps.setProperty(ORBConstants.DEBUG_PROPERTY,"transport,giop"); + Controller client = createClient(thisPackage + ".Client", "Client1"); + client.start(); + + client.waitFor(CLIENT_TIMEOUT); + + client.stop(); + server.stop(); + + serverProps.setProperty(ORBConstants.DISABLE_DIRECT_BYTE_BUFFER_USE_PROPERTY, "true"); + serverProps.setProperty(ORBConstants.ALWAYS_ENTER_BLOCKING_READ_PROPERTY, "false"); + server = createServer(thisPackage + ".Server","Server2"); + server.start(); + + clientProps.setProperty(ORBConstants.DISABLE_DIRECT_BYTE_BUFFER_USE_PROPERTY, "true"); + clientProps.setProperty(ORBConstants.ALWAYS_ENTER_BLOCKING_READ_PROPERTY, "false"); + client = createClient(thisPackage + ".Client", "Client2"); + client.start(); + + client.waitFor(CLIENT_TIMEOUT); + + client.stop(); + server.stop(); + + orbd.stop(); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/requestpartitioning/Server.java b/functional-tests/src/test/java/corba/requestpartitioning/Server.java new file mode 100644 index 000000000..232add946 --- /dev/null +++ b/functional-tests/src/test/java/corba/requestpartitioning/Server.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.requestpartitioning; + +import java.util.Properties; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.extension.RequestPartitioningPolicy; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; + +import corba.framework.Options; +import corba.hcks.U; + +import org.omg.CORBA.Policy; +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; +import org.omg.CosNaming.NameComponent; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.POAHelper; + +// +// Created : 2004 June 2, 2004 by Charlie Hunt +// Last Modified: 2004 June 2, 2004 by Charlie Hunt +// + +public class Server +{ + private static ORB orb = null; + + public static void main(String[] args) + { + Properties props = System.getProperties(); + try + { + orb = (ORB)org.omg.CORBA.ORB.init(args, props); + + // set custom thread pool manager + ThreadPoolManager threadPoolManager = + TestThreadPoolManager.getThreadPoolManager(); + orb.setThreadPoolManager(threadPoolManager); + + // Get a reference to rootpoa + POA rootPOA = POAHelper.narrow( + orb.resolve_initial_references(ORBConstants.ROOT_POA_NAME)); + + // Create servant and register it with the ORB + TesterImpl testerImpl = new TesterImpl(); + + U.sop("Creating a request partitioning policy with -1..."); + try { + Policy policy[] = new Policy[1]; + policy[0] = new RequestPartitioningPolicy(-1); + throw new Exception("new RequestPartitionPolicy(-1) was not rejected when it should have been!"); + } + catch (Exception ex) { + U.sop("Received expected exception..."); + } + U.sop("Creating a request partitioning policy with 64..."); + try { + Policy policy[] = new Policy[1]; + policy[0] = new RequestPartitioningPolicy(64); + throw new Exception("new RequestPartitionPolicy(64) was not rejected when it should have been!"); + } + catch (Exception ex) { + U.sop("Received expected exception..."); + } + + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); + NameComponent[] path = null; + + POA[] poa = new POA[TestThreadPoolManager.NUMBER_OF_THREAD_POOLS_TO_CREATE]; + Policy policy[] = new Policy[1]; + + for (int i = 0; i < poa.length; i++) { + policy[0] = new RequestPartitioningPolicy(i); + String poaName = "POA-Tester" + i; + poa[i] = rootPOA.create_POA(poaName, null, policy); + poa[i].activate_object(testerImpl); + + org.omg.CORBA.Object ref = + poa[i].servant_to_reference(testerImpl); + Tester testerRef = TesterHelper.narrow(ref); + + String name = "Tester" + i; + path = ncRef.to_name(name); + ncRef.rebind(path, testerRef); + + poa[i].the_POAManager().activate(); + } + + // create one POA for default thread pool + String specialPoaName = "POA-Default-Tester"; + POA specialPoa = rootPOA.create_POA(specialPoaName, null, null); + specialPoa.activate_object(testerImpl); + org.omg.CORBA.Object sref = + specialPoa.servant_to_reference(testerImpl); + Tester specialTesterRef = TesterHelper.narrow(sref); + String sname = "DefaultTester"; + path = ncRef.to_name(sname); + ncRef.rebind(path, specialTesterRef); + specialPoa.the_POAManager().activate(); + + U.sop(Options.defServerHandshake); + + orb.run(); + + } catch (Throwable t) { + U.sop("Unexpected throwable..."); + t.printStackTrace(); + System.exit(1); + } + U.sop("Ending successfully..."); + } +} diff --git a/functional-tests/src/test/java/corba/requestpartitioning/TestThreadPoolManager.java b/functional-tests/src/test/java/corba/requestpartitioning/TestThreadPoolManager.java new file mode 100644 index 000000000..fe0593efa --- /dev/null +++ b/functional-tests/src/test/java/corba/requestpartitioning/TestThreadPoolManager.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.requestpartitioning; + +import com.sun.corba.ee.spi.threadpool.ThreadPoolChooser; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.corba.ee.spi.threadpool.ThreadPool; +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; + +import com.sun.corba.ee.impl.threadpool.ThreadPoolImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.HashMap; +import java.util.ArrayList; + +public class TestThreadPoolManager implements ThreadPoolManager { + + public static final int NUMBER_OF_THREAD_POOLS_TO_CREATE = 64; + + private static final int DEFAULT_NUMBER_OF_QUEUES = 0; + private static final int DEFAULT_MIN_THREAD_COUNT = 10; + private static final int DEFAULT_MAX_THREAD_COUNT = 100; + + private static HashMap idToIndexTable = new HashMap(); + private static HashMap indexToIdTable = new HashMap(); + private static ArrayList threadpoolList = new ArrayList(); + private static String defaultID; + + private static ThreadPoolManager testThreadPoolMgr = new TestThreadPoolManager(); + + public static ThreadPoolManager getThreadPoolManager() { + return testThreadPoolMgr; + } + + TestThreadPoolManager() { + + for (int i = 0; i < NUMBER_OF_THREAD_POOLS_TO_CREATE; i++) { + createThreadPools(i); + } + defaultID = (String)indexToIdTable.get(new Integer(0)); + } + + private void createThreadPools(int index) { + String threadpoolId = Integer.toString(index); + + // Mutiply the idleTimeoutInSeconds by 1000 to convert to milliseconds + com.sun.corba.ee.spi.threadpool.ThreadPool threadpool = + new ThreadPoolImpl(DEFAULT_MIN_THREAD_COUNT, + DEFAULT_MAX_THREAD_COUNT, + ThreadPoolImpl.DEFAULT_INACTIVITY_TIMEOUT * 1000, + threadpoolId); + + // Add the threadpool instance to the threadpoolList + threadpoolList.add(threadpool); + + // Associate the threadpoolId to the index passed + idToIndexTable.put(threadpoolId, new Integer(index)); + + // Associate the threadpoolId to the index passed + indexToIdTable.put(new Integer(index), threadpoolId); + + } + + /** + * This method will return an instance of the threadpool given a threadpoolId, + * that can be used by any component in the app. server. + * + * @throws NoSuchThreadPoolException thrown when invalid threadpoolId is passed + * as a parameter + */ + public com.sun.corba.ee.spi.threadpool.ThreadPool + getThreadPool(String id) + throws NoSuchThreadPoolException { + + Integer i = (Integer)idToIndexTable.get(id); + if (i == null) { + throw new NoSuchThreadPoolException(); + } + try { + com.sun.corba.ee.spi.threadpool.ThreadPool threadpool = + (com.sun.corba.ee.spi.threadpool.ThreadPool) + threadpoolList.get(i.intValue()); + return threadpool; + } catch (IndexOutOfBoundsException iobe) { + throw new NoSuchThreadPoolException(); + } + } + + /** + * This method will return an instance of the threadpool given a numeric threadpoolId. + * This method will be used by the ORB to support the functionality of + * dedicated threadpool for EJB beans + * + * @throws NoSuchThreadPoolException thrown when invalidnumericIdForThreadpool is passed + * as a parameter + */ + public com.sun.corba.ee.spi.threadpool.ThreadPool + getThreadPool(int numericIdForThreadpool) + throws NoSuchThreadPoolException { + + try { + com.sun.corba.ee.spi.threadpool.ThreadPool threadpool = + (com.sun.corba.ee.spi.threadpool.ThreadPool) + threadpoolList.get(numericIdForThreadpool); + return threadpool; + } catch (IndexOutOfBoundsException iobe) { + throw new NoSuchThreadPoolException(); + } + } + + /** + * This method is used to return the numeric id of the threadpool, given a String + * threadpoolId. This is used by the POA interceptors to add the numeric threadpool + * Id, as a tagged component in the IOR. This is used to provide the functionality of + * dedicated threadpool. + */ + public int getThreadPoolNumericId(String id) { + Integer i = (Integer)idToIndexTable.get(id); + return ((i == null) ? 0 : i.intValue()); + } + + /** + * Return a String Id for a numericId of a threadpool managed by the threadpool + * manager + */ + public String getThreadPoolStringId(int numericIdForThreadpool) { + String id = (String)indexToIdTable.get(new Integer(numericIdForThreadpool)); + return ((id == null) ? defaultID : id); + } + + /** + * Returns the first instance of ThreadPool in the ThreadPoolManager + */ + public com.sun.corba.ee.spi.threadpool.ThreadPool + getDefaultThreadPool() { + try { + return getThreadPool(0); + } catch (NoSuchThreadPoolException nstpe) { + System.err.println("No default ThreadPool defined " + nstpe); + System.exit(1); + } + return null; + } + + public ThreadPoolChooser getThreadPoolChooser(String componentId) { + // not used + return null; + } + + public ThreadPoolChooser getThreadPoolChooser(int componentIndex) { + // not used + return null; + } + + public void setThreadPoolChooser(String componentId, ThreadPoolChooser aThreadPoolChooser) { + // not used + } + + public int getThreadPoolChooserNumericId(String componentId) { + // not used + return 0; + } + + public void close() throws java.io.IOException { + } +} + + diff --git a/functional-tests/src/test/java/corba/requestpartitioning/TesterImpl.java b/functional-tests/src/test/java/corba/requestpartitioning/TesterImpl.java new file mode 100644 index 000000000..3f0caea16 --- /dev/null +++ b/functional-tests/src/test/java/corba/requestpartitioning/TesterImpl.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.requestpartitioning; + +import com.sun.corba.ee.spi.orb.ORB; + +public class TesterImpl extends TesterPOA +{ + private ORB orb = null; + + public void setORB(ORB orb_val) { + orb = orb_val; + } + + // return the thread pool where request was executed + public int getThreadPoolIdForThisRequest(String theString) { + int result; + + // Get the current thread's name, parse the thread id. + // Thread's name looks like "p: xx; w: yy" + // parsing indexes --- 0123456789 + + String threadName = Thread.currentThread().getName(); + String tmpStr = null; + if (threadName.charAt(5) == ';') { + // double digit thread id + tmpStr = threadName.substring(3,5); + } + else { + // single digit thread id + tmpStr = threadName.substring(3,4); + } + + result = Integer.valueOf(tmpStr).intValue(); + + return result; + } +} diff --git a/functional-tests/src/test/java/corba/rmipoacounter/RMIPOACounterTest.java b/functional-tests/src/test/java/corba/rmipoacounter/RMIPOACounterTest.java new file mode 100644 index 000000000..df4010b51 --- /dev/null +++ b/functional-tests/src/test/java/corba/rmipoacounter/RMIPOACounterTest.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmipoacounter; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class RMIPOACounterTest extends CORBATest +{ + protected Controller newClientController() + { + return new InternalExec(); + } + + protected void doTest() throws Throwable + { + // try this one. the report dir was already set to gen/corba/rmipoacounter + Options.setOutputDirectory((String)getArgs().get(test.Test.OUTPUT_DIRECTORY)); + Options.addServerArg("-debug"); + + Controller orbd = createORBD(); + + Properties serverProps = Options.getServerProperties(); + + serverProps.setProperty(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + Options.getUnusedPort().toString()); + + Controller server = createServer("corba.rmipoacounter.counterServer"); + + orbd.start(); + server.start(); + + // In this test, the client will kill and restart the server, so it + // needs the reference. Thus, the client can only be an InternalProcess + // or a ThreadProcess. + Hashtable clientExtra = Options.getClientExtra(); + clientExtra.put("server", server); + + /* + This is basically a test of persistent servers. The server + maintains a counter in a file, and can be restarted without + losing it. Plus, the reference in ORBD stays the same. + */ + + Controller client = createClient("corba.rmipoacounter.counterClient"); + + client.start(); + + client.waitFor(); + + client.stop(); + + server.stop(); + + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/corba/rmipoacounter/counterClient.java b/functional-tests/src/test/java/corba/rmipoacounter/counterClient.java new file mode 100644 index 000000000..2e97a0a7c --- /dev/null +++ b/functional-tests/src/test/java/corba/rmipoacounter/counterClient.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmipoacounter; + +import java.util.*; +import java.io.*; +import java.io.DataInputStream ; +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import javax.rmi.PortableRemoteObject ; +import corba.framework.*; + +public class counterClient implements InternalProcess +{ + // Temporary hack to get this test to work and keep the output + // directory clean + private static final String outputDirOffset + = "/corba/rmipoacounter/".replace('/', File.separatorChar); + + /** + * These counters are used to check that the values remain + * correct even when the server is restarted. + */ + private static long counterValue = 1; + + private void performTest(PrintStream out, + PrintStream err, + counterIF counterRef1, + counterIF counterRef2) throws Exception + { + // call the counter server objects and print results + long value = counterRef1.increment(1); + out.println("Counter1 value = " + value); + if (++counterValue != value) + throw new Exception("Invalid counter1: " + + value + " but should be " + counterValue); + + for (int i = 0; i < 2; i++) { + value = counterRef2.increment(1); + out.println("Counter2 value = "+value); + if (++counterValue != value) + throw new Exception("Invalid counter2: " + + value + " but should be " + counterValue); + } + + } + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + environment.list(out); + + try { + // create and initialize the ORB + ORB orb = ORB.init(args, environment); + + // get counter objrefs from NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Counter1", ""); + NameComponent[] path = {nc}; + + counterIF counterRef1 = + (counterIF)PortableRemoteObject.narrow(ncRef.resolve(path), + counterIF.class); + + // Read IOR from file and destringify it + InputStream inf = + new FileInputStream(environment.getProperty("output.dir") + + outputDirOffset + + "counterior2"); + DataInputStream in = new DataInputStream(inf); + String ior = in.readLine() ; + org.omg.CORBA.Object obj = orb.string_to_object(ior) ; + counterIF counterRef2 + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class); + + Controller server = (Controller)extra.get("server"); + + for (int i = 0; i < 3; i++) { + out.println("Testing, pass #" + i); + performTest(out, err, counterRef1, counterRef2); + out.println("Restarting server..."); + server.stop(); + server.start(); + } + + } catch (Exception e) { + e.printStackTrace(err); + throw e; + } + } + + public static void main(String args[]) + { + try { + + (new counterClient()).run(System.getProperties(), + args, + System.out, + System.err, + null); + + } catch (Exception e) { + System.err.println("ERROR : " + e) ; + e.printStackTrace(System.err); + System.exit(1); + } + } +} diff --git a/functional-tests/src/test/java/corba/rmipoacounter/counterIF.java b/functional-tests/src/test/java/corba/rmipoacounter/counterIF.java new file mode 100644 index 000000000..42d78c135 --- /dev/null +++ b/functional-tests/src/test/java/corba/rmipoacounter/counterIF.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmipoacounter; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface counterIF extends java.rmi.Remote { + public long increment( long invalue ) throws java.rmi.RemoteException ; +} diff --git a/functional-tests/src/test/java/corba/rmipoacounter/counterImpl.java b/functional-tests/src/test/java/corba/rmipoacounter/counterImpl.java new file mode 100644 index 000000000..dd39fefe6 --- /dev/null +++ b/functional-tests/src/test/java/corba/rmipoacounter/counterImpl.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmipoacounter; + +import java.rmi.RemoteException ; +import javax.rmi.PortableRemoteObject ; +import org.omg.CORBA.ORB ; +import java.io.File ; +import java.io.RandomAccessFile ; +import org.omg.PortableServer.POA ; + +public class counterImpl extends PortableRemoteObject implements counterIF +{ + // Temporary hack to get this test to work and keep the output + // directory clean + private static final String outputDirOffset + = "/corba/rmipoacounter/".replace('/', File.separatorChar); + + String name; + private int value; + ORB orb; + private int myid; + private static int SERVANT_ID=1; + private boolean debug ; + + public counterImpl(ORB orb, boolean debug) throws RemoteException + { + this.myid = SERVANT_ID++; + this.orb = orb; + this.debug = debug ; + + name = System.getProperty("output.dir") + + outputDirOffset + + "counterValue"; + + try { + File f = new File(name); + if ( !f.exists() ) { + RandomAccessFile file = new RandomAccessFile(f, "rw"); + value = 0; + file.writeBytes(String.valueOf(value)); + file.close(); + } + } catch ( Exception ex ) { + ex.printStackTrace(); + System.exit(1); + } + } + + public synchronized long increment(long invalue) throws RemoteException + { + if ( debug ) + System.out.println( "\nIn counterServant " + myid + + " increment(), invalue = " + invalue + " Server thread is " + + Thread.currentThread()); + + try { + // Test Current operations + org.omg.PortableServer.Current current = + (org.omg.PortableServer.Current)orb.resolve_initial_references( + "POACurrent"); + POA poa = current.get_POA(); + byte[] oid = current.get_object_id(); + + if ( debug ) + System.out.println( "POA = " + poa.the_name() + " objectid = " + + oid); + + // Increment counter and save state + RandomAccessFile file = new RandomAccessFile(new File(name), "rw"); + String svalue = file.readLine(); + value = Integer.parseInt(svalue); + file.seek(0); + value += (int)invalue; + file.writeBytes(String.valueOf(value)); + file.close(); + + System.out.println("\nIn counterServant read "+svalue+" wrote "+value); + } catch ( Exception ex ) { + System.err.println("ERROR in counterServant !"); + ex.printStackTrace(); + System.exit(1); + } + + return value; + } +} + diff --git a/functional-tests/src/test/java/corba/rogueclient/Client.java b/functional-tests/src/test/java/corba/rogueclient/Client.java new file mode 100644 index 000000000..0967ae039 --- /dev/null +++ b/functional-tests/src/test/java/corba/rogueclient/Client.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rogueclient; + +import java.rmi.RemoteException; +import java.util.Properties; + +import javax.rmi.PortableRemoteObject; +import javax.naming.InitialContext; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.hcks.U; + +public class Client extends Thread +{ + private final static int NUMBER_OF_CLIENTS = 6; + private final static boolean dprint = false; + private final static int stringSize = 131072; + private final static int TEST_SIZE = 50; + private final static String stringOf36 = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static String reallyReallyBigString = null; + private static String tmpString = null; + + private static void initializeReallyBigString() { + StringBuffer sb = new StringBuffer(stringSize); + int index = 0; + final int lengthOfStr = stringOf36.length(); + for (int i = 0; i < stringSize; i++) { + index = i % lengthOfStr; + sb.append(stringOf36.charAt(index)); + } + reallyReallyBigString = sb.toString(); + } + + private void runTest(Tester tester, int iterations) + throws RemoteException { + for (int i = 0; i < iterations; i++) { + tmpString = tester.passString(reallyReallyBigString); + } + } + + public void run() { + try { + U.sop("Finding Tester ..."); + InitialContext rootContext = new InitialContext(); + U.sop("Looking up Tester..."); + java.lang.Object tst = rootContext.lookup("Tester"); + U.sop("Narrowing..."); + Tester tester + = (Tester)PortableRemoteObject.narrow(tst, + Tester.class); + runTest(tester, TEST_SIZE); + } catch (Throwable t) { + U.sop("Unexpected throwable..."); + t.printStackTrace(); + System.exit(1); + } + } + + public static void main(String args[]) { + if (dprint) { + Properties props = new Properties(); + props.put(ORBConstants.DEBUG_PROPERTY, "transport, giop"); + } + + initializeReallyBigString(); + + Client[] clients = new Client[NUMBER_OF_CLIENTS]; + for (int i = 0; i < clients.length; i++) { + clients[i] = new Client(); + } + + for (int i = 0; i < clients.length; i++) { + U.sop("Beginning client[" + i + "] test..."); + clients[i].start(); + } + + for (int i = 0; i < clients.length; i++) { + try { + clients[i].join(); + U.sop("Client[" + i + "] test finished successfully..."); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + } +} + diff --git a/functional-tests/src/test/java/corba/rogueclient/RogueClient.java b/functional-tests/src/test/java/corba/rogueclient/RogueClient.java new file mode 100644 index 000000000..61dde3c6d --- /dev/null +++ b/functional-tests/src/test/java/corba/rogueclient/RogueClient.java @@ -0,0 +1,513 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rogueclient; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; + + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.SocketChannel; +import java.rmi.RemoteException; +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; + +import java.util.concurrent.atomic.AtomicInteger ; +import org.glassfish.pfl.test.JUnitReportHelper; + +public class RogueClient implements Runnable +{ + // shared across all instances of RogueClients + private static final boolean dprint = false; + private static final boolean itsBigEndian = (ByteOrder.BIG_ENDIAN == ByteOrder.nativeOrder()); + private static final int NUM_ROGUE_CLIENTS = 10; + private static final byte HEX_G = (byte)0x47; + private static final byte HEX_I = (byte)0x49; + private static final byte HEX_O = (byte)0x4f; + private static final byte HEX_P = (byte)0x50; + private static final byte[] BOGUS_BYTES = new byte[] { + 0x00,0x00,0x00,0x06,0x03,0x00,0x00,0x00,0x00,0x00, + 0x00,0x02,0x00,0x00,0x00,0x19,-0x51,-0x55,-0x35,0x00, + 0x00,0x00,0x00,0x02,0x7a,-0x24,0x1d,-0x69,0x00,0x00, + 0x00,0x08,0x00,0x00,0x00,0x01 }; + + // unique to each instance of a RogueClient + private String itsHostname = null; + private int itsPort = 0; + private SocketChannel itsSocketChannel = null; + private JUnitReportHelper helper = new JUnitReportHelper( RogueClient.class.getName() ) ; + private int createConnectionToServerCallCounter = 0 ; + private static AtomicInteger numFailures = new AtomicInteger() ; + + private static volatile boolean useHelper = true ; + private int clientNum; + private static int numClients; + + public RogueClient() { + clientNum = numClients++; + } + + private void start( String name, int ctr ) { + if (useHelper) + helper.start( name + ctr ) ; + + print("RogueClient." + name + "()"); + } + + private void start( String name ) { + if (useHelper) + helper.start( name ) ; + + print("RogueClient." + name + "()"); + } + + private void handlePass() { + if (useHelper) + helper.pass() ; + + print("PASS"); + } + + private void handleException(Exception ex) throws Exception { + numFailures.incrementAndGet() ; + + print("Unexpected exception -> " + ex); + + StackTraceElement[] ste = ex.getStackTrace(); + for (StackTraceElement aSte : ste) { + print(aSte.toString()); + } + + helper.fail( ex ) ; + + throw ex ; + } + + private void printBuffer(ByteBuffer byteBuffer) { + print("+++++++ GIOP Buffer ++++++++\n"); + print("Current position: " + byteBuffer.position()); + print("Total length : " + byteBuffer.limit() + "\n"); + + char[] charBuf = new char[16]; + + try { + + for (int i = 0; i < byteBuffer.position(); i += 16) { + + int j = 0; + + // For every 16 bytes, there is one line + // of output. First, the hex output of + // the 16 bytes with each byte separated + // by a space. + while (j < 16 && j + i < byteBuffer.position()) { + int k = byteBuffer.get(i + j); + if (k < 0) + k = 256 + k; + String hex = Integer.toHexString(k); + if (hex.length() == 1) + hex = "0" + hex; + System.out.print(hex + " "); + j++; + } + + // Add any extra spaces to align the + // text column in case we didn't end + // at 16 + while (j < 16) { + System.out.print(" "); + j++; + } + + // Now output the ASCII equivalents. Non-ASCII + // characters are shown as periods. + int x = 0; + while (x < 16 && x + i < byteBuffer.position()) { + if (ORBUtility.isPrintable((char)byteBuffer.get(i + x))) + charBuf[x] = (char)byteBuffer.get(i + x); + else + charBuf[x] = '.'; + x++; + } + print(new String(charBuf, 0, x)); + } + } catch (Throwable t) { + t.printStackTrace(); + } + print("++++++++++++++++++++++++++++++"); + } + + private void getHostnameAndPort(Tester tester) + { + // Get the host and port number of server + print("RogueClient.getHostnameAndPort()"); + ClientDelegate delegate = + (ClientDelegate)StubAdapter.getDelegate(tester); + ContactInfoList ccil = delegate.getContactInfoList(); + IOR effectiveTargetIOR = ccil.getEffectiveTargetIOR(); + IIOPProfile iiopProfile = effectiveTargetIOR.getProfile(); + IIOPProfileTemplate iiopProfileTemplate = + (IIOPProfileTemplate)iiopProfile.getTaggedProfileTemplate() ; + IIOPAddress primary = iiopProfileTemplate.getPrimaryAddress() ; + + itsHostname = primary.getHost().toLowerCase(); + itsPort = primary.getPort(); + + String testerIOR = tester.toString(); + print("\tRemote object, Tester " + testerIOR); + print("\tCan be found at:"); + print("\tHostname -> " + itsHostname); + print("\tPort -> " + itsPort); + print("Successful"); + } + + private void createConnectionToServer() throws Exception { + start( "createConnectionToServer", + createConnectionToServerCallCounter++ ) ; + + // create SocketChannel to server + try { + InetSocketAddress isa = new InetSocketAddress(itsHostname, itsPort); + itsSocketChannel = ORBUtility.openSocketChannel(isa); + } + catch (Exception ex) { + handleException(ex); + } + + handlePass() ; + } + + private void write_octet(byte[] theBuf, int index, byte theValue) { + theBuf[index] = theValue; + } + + private void buildGIOPHeader(byte[] theBuf, int theMessageSize) + { + int index = 0; + + // write GIOP string, always written big endian + write_octet(theBuf, index++, HEX_G); + write_octet(theBuf, index++, HEX_I); + write_octet(theBuf, index++, HEX_O); + write_octet(theBuf, index++, HEX_P); + + // write GIOP version 1.2, bytes 5,6 + write_octet(theBuf, index++, GIOPVersion.DEFAULT_VERSION.getMajor()); + write_octet(theBuf, index++, GIOPVersion.DEFAULT_VERSION.getMinor()); + + // write endian-ness and no fragment bit (either 0x00 or 0x01) + // byte 6, bits 0 & 1 + if (itsBigEndian) { + write_octet(theBuf, index++, Message.FLAG_NO_FRAG_BIG_ENDIAN); + } else { + write_octet(theBuf, index++, Message.LITTLE_ENDIAN_BIT); + } + + // write GIOPRequest type, byte 8 + write_octet(theBuf, index++, Message.GIOPRequest); + + // write message size + write_message_size(theBuf, index, theMessageSize); + } + + private void write_message_size(byte[] theBuf, int index, int theMessageSize) { + // write message size, bytes 9,10,11,12 + if (itsBigEndian) { + write_octet(theBuf, index++, (byte)((theMessageSize >>> 24) & 0xFF)); + write_octet(theBuf, index++, (byte)((theMessageSize >>> 16) & 0xFF)); + write_octet(theBuf, index++, (byte)((theMessageSize >>> 8) & 0xFF)); + write_octet(theBuf, index, (byte)(theMessageSize & 0xFF)); + } else { + write_octet(theBuf, index++, (byte)(theMessageSize & 0xFF)); + write_octet(theBuf, index++, (byte)((theMessageSize >>> 8) & 0xFF)); + write_octet(theBuf, index++, (byte)((theMessageSize >>> 16) & 0xFF)); + write_octet(theBuf, index, (byte)((theMessageSize >>> 24) & 0xFF)); + } + } + + private void sendData(ByteBuffer byteBuffer, int numBytesToWrite) + throws Exception { + + int bytesWrit; + do { + bytesWrit = itsSocketChannel.write(byteBuffer); + } while (bytesWrit < numBytesToWrite); + } + + private ByteBuffer createGIOPMessage() { + + // create a GIOP header + byte[] request = new byte[Message.defaultBufferSize]; + + // build GIOP header + buildGIOPHeader(request, request.length - Message.GIOPMessageHeaderLength); + + // add some bogus junk to a rogue request + for (int i = 0; i < BOGUS_BYTES.length; i++) { + write_octet(request, + i+Message.GIOPMessageHeaderLength, + BOGUS_BYTES[i]); + } + + ByteBuffer byteBuffer = ByteBuffer.wrap(request); + byteBuffer.position(0); + byteBuffer.limit(Message.GIOPMessageHeaderLength+BOGUS_BYTES.length); + + if (dprint) { + ByteBuffer viewBuffer = byteBuffer.asReadOnlyBuffer(); + viewBuffer.position(Message.GIOPMessageHeaderLength+BOGUS_BYTES.length); + printBuffer(viewBuffer); + } + + return byteBuffer; + } + + private void runValidHeaderSlowBody() throws Exception { + start( "runValidHeaderSlowBody" ) ; + + ByteBuffer byteBuffer = createGIOPMessage(); + + // send full, valid GIOP header + ByteBuffer b = ByteBuffer.allocateDirect(Message.GIOPMessageHeaderLength); + for (int i = 0; i < Message.GIOPMessageHeaderLength; i++) { + b.put(byteBuffer.get(i)); + } + b.flip(); + + try { + sendData(b, Message.GIOPMessageHeaderLength); + + // send message body 1 byte a time with a delay between them + for (int i = Message.GIOPMessageHeaderLength; i < byteBuffer.limit(); i++) { + b = ByteBuffer.allocateDirect(1); + b.put(byteBuffer.get(i)); + b.flip(); + sendData(b, 1); + Thread.sleep(250); + } + Thread.sleep(5000); + } catch (IOException ioe) { + // We expect Server to complain with an IOException. + // So, we must close the connection and re-open it. + print("\tReceived expected IOException: " + ioe.toString()); + print("\tWill attempt to re-establish connection to server.."); + try { + itsSocketChannel.close(); + } catch (IOException ioex) { + handleException(ioex); + throw ioex ; + } + + handleException( ioe ) ; + createConnectionToServer(); + throw ioe ; + } catch (Exception ex) { + handleException(ex); + throw ex ; + } + + handlePass() ; + } + + private void runSlowGIOPHeader() throws Exception { + start( "runSlowGIOPHeader" ) ; + + ByteBuffer byteBuffer = createGIOPMessage(); + + // send GIOP header + try { + // send 1 byte a time with a delay between them + for (int i = 0; i < byteBuffer.limit(); i++) { + ByteBuffer b = ByteBuffer.allocateDirect(1); + b.put(byteBuffer.get(i)); + b.flip(); + sendData(b, 1); + Thread.sleep(500); + } + Thread.sleep(5000); + } catch (IOException ioe) { + System.out.println("received exception:"); + ioe.printStackTrace(); + // We expect Server to complain with an IOException. + // So, we must close the connection and re-open it. + print("\tReceived expected IOException: " + ioe.toString()); + print("\tWill attempt to re-establish connection to server..."); + try { + itsSocketChannel.close(); + } catch (IOException ioex) { + handleException(ioex); + throw ioex ; + } + createConnectionToServer(); + } catch (Exception ex) { + handleException(ex); + throw ex ; + } + + handlePass() ; + } + + private void runValidHeaderBogusLength() throws Exception { + start( "runValidHeaderBogusLength" ) ; + + ByteBuffer byteBuffer = createGIOPMessage(); + write_message_size(byteBuffer.array(),8,byteBuffer.limit() + 50); + + try { + // send valid header with bogus message length + sendData(byteBuffer, byteBuffer.limit()); + Thread.sleep(10000); + } catch (Exception ex) { + handleException(ex); + } + + handlePass() ; + print("PASSED"); + } + + + private void runSendMessageAndCloseConnection() throws Exception { + start( "runSendMessageAndCloseConnection" ) ; + + ByteBuffer byteBuffer = createGIOPMessage(); + byteBuffer.flip(); + try { + sendData(byteBuffer, byteBuffer.limit()); + // immediately close the channel + itsSocketChannel.close(); + } catch (Exception ex) { + handleException(ex); + } + + handlePass() ; + + createConnectionToServer(); + } + + private void runRogueConnectManyTests() throws Exception { + helper.start( "runRogueConnectManyTests" ) ; + try { + String message = "RogueClient.runRogueConnectManyTests()"; + print(message); + // create a bunch of RogueClients and let them bang away + Thread[] rogueClientThreads = new Thread[NUM_ROGUE_CLIENTS]; + + for (int i = 0; i < NUM_ROGUE_CLIENTS; i++) { + rogueClientThreads[i] = new Thread(new RogueClient()); + } + + for (Thread thread : rogueClientThreads) { + thread.start(); + } + + for (Thread thread : rogueClientThreads) { + thread.join(); + } + + print("PASSED"); + } finally { + if (numFailures.get() == 0) + helper.pass() ; + else + helper.fail( "Failed with " + numFailures.get() + " errors" ) ; + } + } + + private void print(String message) { + System.out.println("Rogue Client[" + clientNum + "]: " + message); + } + + private void runSaneTest(Tester tester) + throws RemoteException + { + // call a method on the Tester object + print("RogueClient.runSaneTest()"); + String desc = tester.getDescription(); + print("\tGot 'Tester' description: " + desc); + print("PASSED"); + } + + @Override + public void run() { + try { + print("Finding Tester ..."); + InitialContext rootContext = new InitialContext(); + print("Looking up Tester..."); + java.lang.Object tst = rootContext.lookup("Tester"); + print("Narrowing..."); + Tester tester + = (Tester)PortableRemoteObject.narrow(tst, + Tester.class); + getHostnameAndPort(tester); + createConnectionToServer(); + runSaneTest(tester); + runValidHeaderBogusLength(); + runSaneTest(tester); + runSlowGIOPHeader(); + runSaneTest(tester); + runValidHeaderSlowBody(); + runSendMessageAndCloseConnection(); + } catch (org.omg.CORBA.COMM_FAILURE c) { + StackTraceElement[] ste = c.getStackTrace(); + StringBuilder sb = new StringBuilder(256); + for (StackTraceElement aSte : ste) { + sb.append(aSte); + } + print("Received an expected org.omg.COMM_FAILURE: " + c.toString() + + " stack trace :\n" + sb.toString()); + } catch (Throwable t) { + print("Unexpected throwable!!!"); + t.printStackTrace(); + helper.done() ; + System.exit(1) ; + } finally { + helper.done() ; + } + } + + public static void main(String args[]) { + System.out.println("Beginning test..."); + + // run a single RogueClient + RogueClient rogueClient = new RogueClient(); + try { + Thread clientThread = new Thread(rogueClient); + clientThread.start(); + clientThread.join(); + + useHelper = false ; + + // run a bunch of RogueClients + rogueClient.runRogueConnectManyTests(); + + } catch (Exception ex) { + ex.printStackTrace() ; + } + + int failures = numFailures.get() ; + if (failures == 0) + System.out.println("Test finished successfully..."); + + System.exit( numFailures.get() ) ; + } +} + diff --git a/functional-tests/src/test/java/corba/rogueclient/RogueClientTest.java b/functional-tests/src/test/java/corba/rogueclient/RogueClientTest.java new file mode 100644 index 000000000..3cc6599aa --- /dev/null +++ b/functional-tests/src/test/java/corba/rogueclient/RogueClientTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Test the ability to turn away a rogue client. +// +// This test creates a Server and a well behaved Client that simply pass +// a String array between. It also creates another Rogue Client that attempts +// a variety of rogue attack by connecting to the ORBInitialPort and sending +// partial GIOP headers, GIOP messages and making a large number of connections. + +package corba.rogueclient; + +import java.util.Properties; +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.framework.Controller; +import corba.framework.CORBATest; +import corba.framework.Options; + +public class RogueClientTest extends CORBATest { + + public static final String thisPackage = + RogueClientTest.class.getPackage().getName(); + + private final static int CLIENT_TIMEOUT = 250000; + + protected void doTest() throws Throwable + { + Controller orbd = createORBD(); + orbd.start(); +// Properties serverProps = Options.getServerProperties(); +// serverProps.setProperty(ORBConstants.DEBUG_PROPERTY,"transport,giop"); + Controller server = createServer(thisPackage + ".Server","Server"); + server.start(); + +// Properties rogueClientProps = Options.getClientProperties(); +// rogueClientProps.setProperty(ORBConstants.DEBUG_PROPERTY,"transport,giop"); + Controller rogueClient = createClient(thisPackage + ".RogueClient","RogueClient"); + + // put some tougher than defaults settings on well behaved client + // so command line property for read timeouts gets executed + Properties clientProps = Options.getClientProperties(); + clientProps.setProperty(ORBConstants.TRANSPORT_TCP_TIMEOUTS_PROPERTY, + "150:2500:25"); + Controller client = createClient(thisPackage + ".Client","Client"); + + + client.start(); + + rogueClient.start(); + + client.waitFor(CLIENT_TIMEOUT); + rogueClient.waitFor(CLIENT_TIMEOUT); + + client.stop(); + rogueClient.stop(); + server.stop(); + orbd.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/rogueclient/Server.java b/functional-tests/src/test/java/corba/rogueclient/Server.java new file mode 100644 index 000000000..319cb2220 --- /dev/null +++ b/functional-tests/src/test/java/corba/rogueclient/Server.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rogueclient; + +import java.util.Properties; +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import corba.framework.Options; +import corba.hcks.C; +import corba.hcks.U; + +import org.omg.PortableServer.POA; + +// +// Created : 2004 May 3, 2004 by Charlie Hunt +// Last Modified: 2004 May 3, 2004 by Charlie Hunt +// + +public class Server +{ + private static ORB orb = null; + private static InitialContext initialContext = null; + private static boolean dprint = false; + + public static void main(String[] args) + { + Properties props = System.getProperties(); + if (dprint) + { + props.put(ORBConstants.DEBUG_PROPERTY, "transport,giop"); + } + + try + { + orb = (ORB)org.omg.CORBA.ORB.init(args, props); + + Tester testerImpl = new TesterImpl(); + + initialContext = C.createInitialContext(orb); + initialContext.rebind("Tester", testerImpl); + + U.sop(Options.defServerHandshake); + orb.run(); + + } catch (Throwable t) { + U.sop("Unexpected throwable..."); + t.printStackTrace(); + System.exit(1); + } + U.sop("Ending successfully..."); + } +} + diff --git a/functional-tests/src/test/java/corba/rogueclient/Tester.java b/functional-tests/src/test/java/corba/rogueclient/Tester.java new file mode 100644 index 000000000..f902e90fc --- /dev/null +++ b/functional-tests/src/test/java/corba/rogueclient/Tester.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rogueclient; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface Tester extends Remote { + public String getDescription() throws RemoteException; + public String passString(String theString) throws RemoteException; +} + + diff --git a/functional-tests/src/test/java/corba/rogueclient/TesterImpl.java b/functional-tests/src/test/java/corba/rogueclient/TesterImpl.java new file mode 100644 index 000000000..5c1ea865d --- /dev/null +++ b/functional-tests/src/test/java/corba/rogueclient/TesterImpl.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rogueclient; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class TesterImpl extends PortableRemoteObject implements Tester +{ + public TesterImpl() throws RemoteException { + super(); + } + + public String getDescription() throws RemoteException { + return "Tester supports a remote method, String passString(String)"; + } + + public String passString(String theString) throws RemoteException { + // reverse the string and send it back + StringBuffer sb = new StringBuffer(theString.length()); + for (int i = (theString.length() - 1); i >= 0; i--) { + sb.append(theString.charAt(i)); + } + + String result = sb.toString(); + return result; + } +} + diff --git a/functional-tests/src/test/java/corba/systemexceptions/Client.java b/functional-tests/src/test/java/corba/systemexceptions/Client.java new file mode 100644 index 000000000..bdf8065b7 --- /dev/null +++ b/functional-tests/src/test/java/corba/systemexceptions/Client.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:54:21 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 10:06:37 by Harold Carr. +// + +package corba.systemexceptions; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import corba.framework.Controller; +import corba.hcks.C; +import corba.hcks.U; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitializer; + +import javax.naming.InitialContext; + +public class Client extends org.omg.CORBA.LocalObject + implements ORBInitializer, ClientRequestInterceptor { + + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static ORB orb; + public static InitialContext initialContext; + + private static String excs[] = { + "org.omg.CORBA.ACTIVITY_COMPLETED", "org.omg.CORBA.ACTIVITY_REQUIRED", + "org.omg.CORBA.BAD_QOS", "org.omg.CORBA.CODESET_INCOMPATIBLE", + "org.omg.CORBA.INVALID_ACTIVITY", "org.omg.CORBA.REBIND", + "org.omg.CORBA.TIMEOUT", "org.omg.CORBA.TRANSACTION_MODE", + "org.omg.CORBA.TRANSACTION_UNAVAILABLE", "org.omg.CORBA.UNKNOWN" }; + + static int counter; // counter + + public static void main(String[] av) { + + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + // RMI invocations + + rmiiI rmiiIPOA = (rmiiI) U.lookupAndNarrow(Server.rmiiIPOA, + rmiiI.class, initialContext); + U.sop("\nRMI invocations:\n"); + int i = 0; + for (counter = 0, i = 0; i < 10; i++, counter++) { + try { + rmiiIPOA.invoke(i); + } catch (java.rmi.RemoteException re) { + SystemException se = (SystemException) re.getCause(); + String name = se.getClass().getName(); + U.sop("name: " + name + ", minorCode: " + se.minor + + ", completed: " + + ((se.completed.value() == + CompletionStatus._COMPLETED_YES) ? + "true" : "false") + "\n"); + if (!(name.equals(excs[i]))) { + throw new RuntimeException("Test Failed"); + } + } + } + + // IDL invocations + + idlI idlIPOA = idlIHelper.narrow(U.resolve(Server.idlIPOA, orb)); + U.sop("IDL invocations:\n"); + for (counter = 0, i = 0; i < 10; i++, counter++) { + try { + idlIPOA.invoke(i); + } catch (org.omg.CORBA.SystemException se) { + String name = se.getClass().getName(); + U.sop("name: " + name + ", minorCode: " + se.minor + + ", completed: " + + ((se.completed.value() == + CompletionStatus._COMPLETED_YES) ? + "true" : "false") + "\n"); + if (!(name.equals(excs[i]))) { + throw new RuntimeException("Test Failed"); + } + } + } + + orb.shutdown(true); + + } catch (Exception e) { + U.sopUnexpectedException(main + " : ", e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } + + //////////////////////////////////////////////////// + // + // ORBInitializer interface implementation. + // + + public void pre_init(ORBInitInfo info) + { + } + + public void post_init(ORBInitInfo info) + { + // register the interceptors. + try { + info.add_client_request_interceptor(this); + } catch (org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName e) { + throw new org.omg.CORBA.INTERNAL(); + } + U.sop("ORBInitializer.post_init completed"); + } + + //////////////////////////////////////////////////// + // + // implementation of the Interceptor interface. + // + + public String name() + { + return "ClientInterceptor"; + } + + public void destroy() + { + } + + //////////////////////////////////////////////////// + // + // implementation of the ClientInterceptor interface. + // + + public void send_request(ClientRequestInfo ri) throws ForwardRequest + { + } + + public void send_poll(ClientRequestInfo ri) + { + } + + public void receive_reply(ClientRequestInfo ri) + { + } + + public void receive_exception(ClientRequestInfo ri) throws ForwardRequest + { + String repID = ri.received_exception_id(); + String className = ORBUtility.classNameOf(repID); + U.sop("receive_exception.repID: " + repID); + U.sop("receive_exception.className: " + className); + if ( !(className.equals(excs[counter])) ) { + throw new RuntimeException("Test Failed"); + } + } + + public void receive_other(ClientRequestInfo ri) throws ForwardRequest + { + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/systemexceptions/ColocatedClientServer.java b/functional-tests/src/test/java/corba/systemexceptions/ColocatedClientServer.java new file mode 100644 index 000000000..b879d8c32 --- /dev/null +++ b/functional-tests/src/test/java/corba/systemexceptions/ColocatedClientServer.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 17 (Thu) 17:05:00 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 10:57:47 by Harold Carr. +// + +package corba.systemexceptions; + +import java.util.Properties; +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; +import corba.hcks.C; +import corba.hcks.U; + +public class ColocatedClientServer +{ + public static final String baseMsg = ColocatedClientServer.class.getName(); + public static final String main = baseMsg + ".main"; + + // REVISIT: FRAMEWORK DEVELOPMENT + // REMOVE THIS LATER. + // Necessary so calls not going through locals do not hang + // until I implement the reader thread/work split. + public static int fragmentSize = -1; + //public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String[] av) + { + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + Properties props = new Properties(); + props.setProperty("com.sun.corba.ee.ORBAllowLocalOptimization", + "true"); + orb = ORB.init(av, props); + U.sop(main + " : creating ORB."); + Server.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + Client.orb = orb; + + // Share a naming context between client and server + // so Util.isLocal is true. + + // Use the same ORB which has interceptor properties set. + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + Server.initialContext = initialContext; + Client.initialContext = initialContext; + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + Client.main(av); + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/corba/systemexceptions/Server.java b/functional-tests/src/test/java/corba/systemexceptions/Server.java new file mode 100644 index 000000000..e1d572911 --- /dev/null +++ b/functional-tests/src/test/java/corba/systemexceptions/Server.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:28:12 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 11:12:48 by Harold Carr. +// + +package corba.systemexceptions; + +import javax.naming.InitialContext; + +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; + +import corba.framework.Controller; +import corba.framework.Options; +import corba.hcks.C; +import corba.hcks.U; + +import com.sun.corba.ee.spi.orb.ORB; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +import org.omg.CORBA.*; + +interface rmiiI extends Remote { + void invoke(int excType) throws RemoteException; +} + +class rmiiIServantPOA extends PortableRemoteObject implements rmiiI { + + rmiiIServantPOA() throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + } + + public void invoke(int excType) { + Server.invoke(excType); + } +} + +class idlIServantPOA extends idlIPOA { + + public void invoke(int excType) { + Server.invoke(excType); + } +} + +public class Server extends org.omg.CORBA.LocalObject { + + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + public static final String thisPackage = + Server.class.getPackage().getName(); + + public static final String rmiiIServantPOA_Tie = + thisPackage + "._rmiiIServantPOA_Tie"; + + public static final String rmiiIPOA = "rmiiIPOA"; + public static final String idlIPOA = "idlIPOA"; + + public static ORB orb; + public static InitialContext initialContext; + + static void invoke(int excType) { + + switch (excType) { + + case 0: + U.sop("ACTIVITY_COMPLETED"); + throw new ACTIVITY_COMPLETED("ACTIVITY_COMPLETED", + 100, CompletionStatus.COMPLETED_YES); + case 1: + U.sop("ACTIVITY_REQUIRED"); + throw new ACTIVITY_REQUIRED("ACTIVITY_REQUIRED", + 101, CompletionStatus.COMPLETED_YES); + case 2: + U.sop("BAD_QOS"); + throw new BAD_QOS("BAD_QOS", 102, CompletionStatus.COMPLETED_YES); + case 3: + U.sop("CODESET_INCOMPATIBLE"); + throw new CODESET_INCOMPATIBLE("CODESET_INCOMPATIBLE", + 103, + CompletionStatus.COMPLETED_YES); + case 4: + U.sop("INVALID_ACTIVITY"); + throw new INVALID_ACTIVITY("INVALID_ACTIVITY", + 104, CompletionStatus.COMPLETED_YES); + case 5: + U.sop("REBIND"); + throw new REBIND("REBIND", 105, CompletionStatus.COMPLETED_YES); + case 6: + U.sop("TIMEOUT"); + throw new TIMEOUT("TIMEOUT", 106, CompletionStatus.COMPLETED_YES); + case 7: + U.sop("TRANSACTION_MODE"); + throw new TRANSACTION_MODE("TRANSACTION_MODE", + 107, CompletionStatus.COMPLETED_YES); + case 8: + U.sop("TRANSACTION_UNAVAILABLE"); + throw new TRANSACTION_UNAVAILABLE("TRANSACTION_UNAVAILABLE", + 108, + CompletionStatus.COMPLETED_YES); + default: + U.sop("UNKNOWN"); + throw new UNKNOWN("UNKNOWN", 109, CompletionStatus.COMPLETED_YES); + } + } + + public static void main(String[] av) { + + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = (ORB) ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + POA rootPOA = U.getRootPOA(orb); + rootPOA.the_POAManager().activate(); + + // RMI-IIOP references. + U.sop("Creating/binding RMI-IIOP references."); + Servant servant = (Servant) + javax.rmi.CORBA.Util.getTie(new rmiiIServantPOA()); + U.createWithServantAndBind(rmiiIPOA, servant, rootPOA, orb); + + // IDL references. + U.sop("Creating/binding IDL references."); + U.createWithServantAndBind(idlIPOA, + new idlIServantPOA(), rootPOA, orb); + + U.sop(main + " ready"); + U.sop(Options.defServerHandshake); + System.out.flush(); + + synchronized (ColocatedClientServer.signal) { + ColocatedClientServer.signal.notifyAll(); + } + + orb.run(); + + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } +} + +// End of file. + + diff --git a/functional-tests/src/test/java/corba/systemexceptions/SystemExceptionsTest.java b/functional-tests/src/test/java/corba/systemexceptions/SystemExceptionsTest.java new file mode 100644 index 000000000..e6de5781d --- /dev/null +++ b/functional-tests/src/test/java/corba/systemexceptions/SystemExceptionsTest.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:31:43 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:54:44 by Harold Carr. +// + +package corba.systemexceptions; + +import java.util.Properties; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +import corba.framework.*; + +public class SystemExceptionsTest extends CORBATest { + public static final String thisPackage = + SystemExceptionsTest.class.getPackage().getName(); + + protected void doTest() throws Throwable { + Controller orbd = createORBD(); + orbd.start(); + + Properties clientProps = Options.getClientProperties(); + clientProps.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "corba.systemexceptions.Client", "true"); + + doTestType("Server", "Server", + "Client", "Client"); + + Controller colocatedClientServer = + createClient(thisPackage + ".ColocatedClientServer", + "colocatedClientServer"); + colocatedClientServer.start(); + colocatedClientServer.waitFor(); + colocatedClientServer.stop(); + + orbd.stop(); + } + + protected void doTestType(String serverMainClass, String serverTestName, + String clientMainClass, String clientTestName) + throws Throwable { + + Controller server = createServer(thisPackage + "." + serverMainClass, + serverTestName); + server.start(); + + Controller client = createClient(thisPackage + "." + clientMainClass, + clientTestName); + client.start(); + client.waitFor(); + client.stop(); + + server.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/corba/unarrow/Client.java b/functional-tests/src/test/java/corba/unarrow/Client.java new file mode 100644 index 000000000..5ae2e24a5 --- /dev/null +++ b/functional-tests/src/test/java/corba/unarrow/Client.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.unarrow; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class Client +{ + static Hello helloRef; + static Bye byeRef; + + static void verifyBehavior(String args[]) { + try{ + // create and initialize the ORB + ORB orb = ORB.init(args, System.getProperties()); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent("Hello", ""); + NameComponent path[] = {nc}; + helloRef = HelloHelper.unchecked_narrow(ncRef.resolve(path)); + + System.out.println("Using unchecked_narrow obtained a handle on server object: " + helloRef); + helloRef.sayHello(); + System.out.println("Success in sayHello !!"); + + // resolve the Object Reference in Naming + nc = new NameComponent("Bye", ""); + path[0] = nc; + byeRef = ByeHelper.unchecked_narrow(ncRef.resolve(path)); + + System.out.println("Using unchecked_narrow obtained a handle on server object: " + byeRef); + byeRef.sayBye(); + System.out.println("Success in sayBye !!"); + + nc = new NameComponent("Hello", ""); + path[0] = nc; + + // Call narrow using the wrong name to make sure that we get + // an exception thrown + try { + byeRef = ByeHelper.narrow(ncRef.resolve(path)); + // If this succeeds throw exception + throw new Exception("Failure: Narrow not throwing exception, it should"); + } catch (org.omg.CORBA.BAD_PARAM bp) { + System.out.println("Success: Getting an org.omg.CORBA.BAD_PARAM exception !!"); + } + + // Now use the wrong name with unchecked narrow + // We should see no exception thrown in this call as + // per the spec + byeRef = ByeHelper.unchecked_narrow(ncRef.resolve(path)); + + System.out.println("Using wrong path in unchecked_narrow: obtained a handle on server object: " + byeRef); + + // Now do the invoke as though it is a byeRef + // We should get a BAD_OPERATION exception + try { + byeRef.sayBye(); + // If this succeeds throw exception + throw new Exception("Failure: Invocation should not succeed"); + } catch (org.omg.CORBA.BAD_OPERATION bo) { + System.out.println("Success: Getting an org.omg.CORBA.BAD_OPERATION exception !!"); + } + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } + + static void verifyMethodExists(Class helperClass, String methodName, Class[] params, Class returnType) { + try { + Method m = helperClass.getDeclaredMethod(methodName, params); + System.out.println("Success: Verified the method name and parameter types !!"); + if (m.getReturnType() != returnType) + throw new Exception("Incorrect return type"); + else + System.out.println("Success: Verified the return type " + m.getReturnType()); + int modifier = m.getModifiers(); + if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) + System.out.println("Success: Verified the method modifiers !!"); + else + throw new Exception("Method modifiers incorrect"); + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } + + static void verifyMethodCount(Class helperClass, String methodName, int numberOfMethods) { + try { + Method[] allMethods = helperClass.getDeclaredMethods(); + int total = 0; + for (int i = 0; i < allMethods.length; i++) { + if (allMethods[i].getName().equals(methodName)) { + total++; + if (total > numberOfMethods) { + throw new Exception("Too many " + methodName + " methods found !!"); + } + } + } + System.out.println("Success: Method count for " + methodName + " verified !!"); + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } + + static void verifyMethodSignatures() { + + + // In this test we will verify the method signatures of the + // Helper classes generated for the interfaces defined in hello.idl + + // + // Foo is an abtract interface so the following method should exist + // in the Helper class: + // + // public static unchecked_narrow( java.lang.Object obj) {...} + // + + verifyMethodExists(corba.unarrow.FooHelper.class, "unchecked_narrow", + new Class[]{java.lang.Object.class}, corba.unarrow.Foo.class); + + verifyMethodCount(corba.unarrow.FooHelper.class, "unchecked_narrow", 1); + + // + // Bar is a non-abstract interface with Foo as the base interface. + // The following 2 methods should exist in the Helper class for this: + // + // public static unchecked_narrow( org.omg.CORBA.Object obj) {...} + // + // public static unchecked_narrow( java.lang.Object obj) {...} + // + + + verifyMethodExists(corba.unarrow.BarHelper.class, "unchecked_narrow", + new Class[]{java.lang.Object.class}, corba.unarrow.Bar.class); + + verifyMethodExists(corba.unarrow.BarHelper.class, "unchecked_narrow", + new Class[]{org.omg.CORBA.Object.class}, corba.unarrow.Bar.class); + + verifyMethodCount(corba.unarrow.FooHelper.class, "unchecked_narrow", 2); + + // + // Hello is a non-abtract interface, so the following method should exist + // in the Helper class for it: + // + // public static unchecked_narrow( org.omg.CORBA.Object obj) {...} + // + + verifyMethodExists(corba.unarrow.HelloHelper.class, "unchecked_narrow", + new Class[]{org.omg.CORBA.Object.class}, corba.unarrow.Hello.class); + + verifyMethodCount(corba.unarrow.FooHelper.class, "unchecked_narrow", 1); + + } + + public static void main(String args[]) + { + verifyBehavior(args); + verifyMethodSignatures(); + } + +} diff --git a/functional-tests/src/test/java/corba/unarrow/Server.java b/functional-tests/src/test/java/corba/unarrow/Server.java new file mode 100644 index 000000000..38f53826f --- /dev/null +++ b/functional-tests/src/test/java/corba/unarrow/Server.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.unarrow; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; +import java.util.Properties ; +import org.omg.PortableServer.*; + +/** + * Servant implementation + */ +class HelloServant extends HelloPOA +{ + public String sayHello() + { + return "Hello world!"; + } +} + +class ByeServant extends ByePOA +{ + public String sayBye() + { + return "Bye world!"; + } +} + + +public class Server +{ + public static void main(String args[]) + { + try { + + ORB orb = ORB.init(args, System.getProperties()); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + // create servants and register it with the ORB + HelloServant helloRef = new HelloServant(); + ByeServant byeRef = new ByeServant(); + + byte[] helloId = rootPOA.activate_object(helloRef); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("Hello", ""); + NameComponent path[] = {nc}; + + org.omg.CORBA.Object ref = rootPOA.id_to_reference(helloId); + + ncRef.rebind(path, ref); + + byte[] byeId = rootPOA.activate_object(byeRef); + + // bind the Object Reference in Naming + nc = new NameComponent("Bye", ""); + path[0] = nc; + + ref = rootPOA.id_to_reference(byeId); + + ncRef.rebind(path, ref); + + // Emit the handshake the test framework expects + // (can be changed in Options by the running test) + System.out.println ("Server is ready."); + + // Wait for clients + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + + // Make sure to exit with a value greater than 0 on + // error. + System.exit(1); + } + } +} diff --git a/functional-tests/src/test/java/corba/unarrow/UncheckedNarrowTest.java b/functional-tests/src/test/java/corba/unarrow/UncheckedNarrowTest.java new file mode 100644 index 000000000..33e042603 --- /dev/null +++ b/functional-tests/src/test/java/corba/unarrow/UncheckedNarrowTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.unarrow; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + * This is a POA version of the mthello test. The + * client creates multiple threads that invoke a simple sayHello + * method on the remote servant. + */ +public class UncheckedNarrowTest extends CORBATest +{ + protected void doTest() throws Throwable + { + Controller orbd = createORBD(); + Controller server = createServer("corba.unarrow.Server"); + Controller client = createClient("corba.unarrow.Client"); + + orbd.start(); + server.start(); + client.start(); + + client.waitFor(120000); + + client.stop(); + server.stop(); + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/BitSet.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/BitSet.java new file mode 100644 index 000000000..960faa7ac --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/BitSet.java @@ -0,0 +1,495 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.io.*; + +/** + * This class implements a vector of bits that grows as needed. Each + * component of the bit set has a boolean value. The + * bits of a BitSet are indexed by nonnegative integers. + * Individual indexed bits can be examined, set, or cleared. One + * BitSet may be used to modify the contents of another + * BitSet through logical AND, logical inclusive OR, and + * logical exclusive OR operations. + *

+ * By default, all bits in the set initially have the value + * false. + *

+ * Every bit set has a current size, which is the number of bits + * of space currently in use by the bit set. Note that the size is + * related to the implementation of a bit set, so it may change with + * implementation. The length of a bit set relates to logical length + * of a bit set and is defined independently of implementation. + * + * @author Arthur van Hoff + * @author Michael McCloskey + * @version 1.34, 05/06/98 + * @since JDK1.0 + */ +public class BitSet implements java.lang.Cloneable, java.io.Serializable { + /* + * BitSets are packed into arrays of "units." Currently a unit is a long, + * which consists of 64 bits, requiring 6 address bits. The choice of unit + * is determined purely by performance concerns. + */ + private final static int ADDRESS_BITS_PER_UNIT = 6; + private final static int BITS_PER_UNIT = 1 << ADDRESS_BITS_PER_UNIT; + private final static int BIT_INDEX_MASK = BITS_PER_UNIT - 1; + + /** + * The bits in this BitSet. The ith bit is stored in bits[i/64] at + * bit position i % 64 (where bit position 0 refers to the least + * significant bit and 63 refers to the most significant bit). + * + * @serial + */ + private long bits[]; // this should be called unit[] + + private transient int unitsInUse; //# of units in logical size + + /* use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = 7997698588986878753L; + + /** + * Given a bit index return unit index containing it. + */ + private static int unitIndex(int bitIndex) { + return bitIndex >> ADDRESS_BITS_PER_UNIT; + } + + /** + * Given a bit index, return a unit that masks that bit in its unit. + */ + private static long bit(int bitIndex) { + return 1L << (bitIndex & BIT_INDEX_MASK); + } + + /** + * Set the field unitsInUse with the logical size in units of the bit + * set. WARNING:This function assumes that the number of units actually + * in use is less than or equal to the current value of unitsInUse! + */ + private void recalculateUnitsInUse() { + /* Traverse the bitset until a used unit is found */ + int i; + for (i = unitsInUse-1; i >= 0; i--) + if(bits[i] != 0) + break; //this unit is in use! + + unitsInUse = i+1; //the new logical size + } + + /** + * Creates a new bit set. All bits are initially false. + */ + public BitSet() { + this(BITS_PER_UNIT); + } + + /** + * Creates a bit set whose initial size is large enough to explicitly + * represent bits with indices in the range 0 through + * nbits-1. All bits are initially false. + * + * @param nbits the initial size of the bit set. + * @exception NegativeArraySizeException if the specified initial size + * is negative. + */ + public BitSet(int nbits) { + /* nbits can't be negative; size 0 is OK */ + if (nbits < 0) + throw new NegativeArraySizeException(Integer.toString(nbits)); + + bits = new long[(unitIndex(nbits-1) + 1)]; + } + + /** + * Ensures that the BitSet can hold enough units. + * @param unitsRequired the minimum acceptable number of units. + */ + private void ensureCapacity(int unitsRequired) { + if (bits.length < unitsRequired) { + /* Allocate larger of doubled size or required size */ + int request = Math.max(2 * bits.length, unitsRequired); + long newBits[] = new long[request]; + System.arraycopy(bits, 0, newBits, 0, unitsInUse); + bits = newBits; + } + } + + /** + * Returns the "logical size" of this BitSet: the index of + * the highest set bit in the BitSet plus one. + * + * @return the logical size of this BitSet. + * @since JDK1.2 + */ + public int length() { + if (unitsInUse == 0) + return 0; + + int highestBit = (unitsInUse - 1) * 64; + long highestUnit = bits[unitsInUse - 1]; + do { + highestUnit = highestUnit >>> 1; + highestBit++; + } while(highestUnit > 0); + return highestBit; + } + + /** + * Sets the bit specified by the index to true. + * + * @param bitIndex a bit index. + * @exception IndexOutOfBoundsException if the specified index is negative. + * @since JDK1.0 + */ + public void set(int bitIndex) { + if (bitIndex < 0) + throw new IndexOutOfBoundsException(Integer.toString(bitIndex)); + + int unitIndex = unitIndex(bitIndex); + int unitsRequired = unitIndex+1; + + if (unitsInUse < unitsRequired) { + ensureCapacity(unitsRequired); + bits[unitIndex] |= bit(bitIndex); + unitsInUse = unitsRequired; + } else { + bits[unitIndex] |= bit(bitIndex); + } + } + + /** + * Sets the bit specified by the index to false. + * + * @param bitIndex the index of the bit to be cleared. + * @exception IndexOutOfBoundsException if the specified index is negative. + * @since JDK1.0 + */ + public void clear(int bitIndex) { + if (bitIndex < 0) + throw new IndexOutOfBoundsException(Integer.toString(bitIndex)); + int unitIndex = unitIndex(bitIndex); + if (unitIndex >= unitsInUse) + return; + + bits[unitIndex] &= ~bit(bitIndex); + if (unitIndex == unitsInUse-1) + recalculateUnitsInUse(); + } + + /** + * Clears all of the bits in this BitSet whose corresponding + * bit is set in the specified BitSet. + * + * @param s the BitSet with which to mask this + * BitSet. + * @since JDK1.2 + */ + public void andNot(BitSet set) { + int unitsInCommon = Math.min(unitsInUse, set.unitsInUse); + + // perform logical (a & !b) on bits in common + for (int i=0; itrue if the bit with the index bitIndex + * is currently set in this BitSet; otherwise, the result + * is false. + * + * @param bitIndex the bit index. + * @return the value of the bit with the specified index. + * @exception IndexOutOfBoundsException if the specified index is negative. + */ + public boolean get(int bitIndex) { + if (bitIndex < 0) + throw new IndexOutOfBoundsException(Integer.toString(bitIndex)); + + boolean result = false; + int unitIndex = unitIndex(bitIndex); + if (unitIndex < unitsInUse) + result = ((bits[unitIndex] & bit(bitIndex)) != 0); + + return result; + } + + /** + * Performs a logical AND of this target bit set with the + * argument bit set. This bit set is modified so that each bit in it + * has the value true if and only if it both initially + * had the value true and the corresponding bit in the + * bit set argument also had the value true. + * + * @param set a bit set. + */ + public void and(BitSet set) { + if (this == set) + return; + + // perform logical AND on bits in common + int oldUnitsInUse = unitsInUse; + int i; + unitsInUse = Math.min(unitsInUse,set.unitsInUse); + for(i=0; iOR of this bit set with the bit set + * argument. This bit set is modified so that a bit in it has the + * value true if and only if it either already had the + * value true or the corresponding bit in the bit set + * argument has the value true. + * + * @param set a bit set. + */ + public void or(BitSet set) { + if (this == set) + return; + + ensureCapacity(set.unitsInUse); + + // perform logical OR on bits in common + int unitsInCommon = Math.min(unitsInUse, set.unitsInUse); + int i; + for(i=0; iXOR of this bit set with the bit set + * argument. This bit set is modified so that a bit in it has the + * value true if and only if one of the following + * statements holds: + *

    + *
  • The bit initially has the value true, and the + * corresponding bit in the argument has the value false. + *
  • The bit initially has the value false, and the + * corresponding bit in the argument has the value true. + *
+ * + * @param set a bit set. + */ + public void xor(BitSet set) { + int unitsInCommon; + + if (unitsInUse >= set.unitsInUse) { + unitsInCommon = set.unitsInUse; + } else { + unitsInCommon = unitsInUse; + + int newUnitsInUse = set.unitsInUse; + ensureCapacity(newUnitsInUse); + unitsInUse = newUnitsInUse; + } + + // perform logical XOR on bits in common + int i; + for (i=0; iBitSet. The algorithm used to compute it may + * be described as follows.

+ * Suppose the bits in the BitSet were to be stored + * in an array of long integers called, say, + * bits, in such a manner that bit k is + * set in the BitSet (for nonnegative values of + * k) if and only if the expression + *

((k>>6) < bits.length) && ((bits[k>>6] & (1L << (bit & 0x3F))) != 0)
+ * is true. Then the following definition of the hashCode + * method would be a correct implementation of the actual algorithm: + *
+     * public synchronized int hashCode() {
+     *      long h = 1234;
+     *      for (int i = bits.length; --i >= 0; ) {
+     *           h ^= bits[i] * (i + 1);
+     *      }
+     *      return (int)((h >> 32) ^ h);
+     * }
+ * Note that the hash code values change if the set of bits is altered. + *

Overrides the hashCode method of Object. + * + * @return a hash code value for this bit set. + */ + public int hashCode() { + long h = 1234; + for (int i = bits.length; --i >= 0; ) + h ^= bits[i] * (i + 1); + + return (int)((h >> 32) ^ h); + } + + /** + * Returns the number of bits of space actually in use by this + * BitSet to represent bit values. + * The maximum element in the set is the size - 1st element. + * + * @return the number of bits currently in this bit set. + */ + public int size() { + return bits.length << ADDRESS_BITS_PER_UNIT; + } + + /** + * Compares this object against the specified object. + * The result is true if and only if the argument is + * not null and is a Bitset object that has + * exactly the same set of bits set to true as this bit + * set. That is, for every nonnegative int index k, + *

((BitSet)obj).get(k) == this.get(k)
+ * must be true. The current sizes of the two bit sets are not compared. + *

Overrides the equals method of Object. + * + * @param obj the object to compare with. + * @return true if the objects are the same; + * false otherwise. + * @see java.util.BitSet#size() + */ + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof BitSet)) + return false; + if (this == obj) + return true; + + BitSet set = (BitSet) obj; + int minUnitsInUse = Math.min(unitsInUse, set.unitsInUse); + + // Check units in use by both BitSets + for (int i = 0; i < minUnitsInUse; i++) + if (bits[i] != set.bits[i]) + return false; + + // Check any units in use by only one BitSet (must be 0 in other) + if (unitsInUse > minUnitsInUse) { + for (int i = minUnitsInUse; iBitSet produces a new BitSet + * that is equal to it. + * The clone of the bit set is another bit set that has exactly the + * same bits set to true as this bit set and the same + * current size. + *

Overrides the clone method of Object. + * + * @return a clone of this bit set. + * @see java.util.BitSet#size() + */ + public Object clone() { + BitSet result = null; + try { + result = (BitSet) super.clone(); + } catch (CloneNotSupportedException e) { + throw new InternalError(); + } + result.bits = new long[bits.length]; + System.arraycopy(bits, 0, result.bits, 0, unitsInUse); + return result; + } + + private void writeObjectX(java.io.ObjectOutputStream out) + throws IOException { + out.defaultWriteObject(); + } + /** + * This override of readObject makes sure unitsInUse is set properly + * when deserializing a bitset + * + */ + private void readObject(java.io.ObjectInputStream in) + throws IOException, ClassNotFoundException { + + in.defaultReadObject(); + //assume maximum length then find real length + //because recalculateUnitsInUse assumes maintenance + //or reduction in logical size + unitsInUse = bits.length; + recalculateUnitsInUse(); + } + + /** + * Returns a string representation of this bit set. For every index + * for which this BitSet contains a bit in the set + * state, the decimal representation of that index is included in + * the result. Such indeces aer listed in order from lowest to + * highest, separated by ",$nbsp;" (a comma and a space) and + * surrounded by braces, resulting in the usual mathematical + * notation for a set of integers.

+ * Overrides the toString method of Object. + *

Example: + *

+     * BitSet drPepper = new BitSet();
+ * Now drPepper.toString() returns "{}".

+ *

+     * drPepper.set(2);
+ * Now drPepper.toString() returns "{2}".

+ *

+     * drPepper.set(4);
+     * drPepper.set(10);
+ * Now drPepper.toString() returns "{2, 4, 10}". + * + * @return a string representation of this bit set. + */ + public String toString() { + int numBits = unitsInUse << ADDRESS_BITS_PER_UNIT; + StringBuffer buffer = new StringBuffer(8*numBits + 2); + String separator = ""; + buffer.append('{'); + + for (int i = 0 ; i < numBits; i++) { + if (get(i)) { + buffer.append(separator); + separator = ", "; + buffer.append(i); + } + } + + buffer.append('}'); + return buffer.toString(); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/BudgetSummary.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/BudgetSummary.java new file mode 100644 index 000000000..a768b4735 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/BudgetSummary.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.lang.reflect.Array; +import java.io.Serializable; + +public class BudgetSummary implements Serializable +{ + //private String[][] test = {{"One","Two"}}; + private String[] fNames; + private double[] fPercentages; + + + public BudgetSummary (int numItems, String[] names, double[] percentages) + { + fNames = names; + fPercentages = percentages; + } + + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Cloneable.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Cloneable.java new file mode 100644 index 000000000..f24a5c2e3 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Cloneable.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* gen/java/lang/Cloneable.java +* Generated by the IBM IDL-to-Java compiler (portable), version "3.0" +* from java/util/Date.idl +* Friday, May 14, 1999 2:20:06 o'clock PM EDT +*/ + +public interface Cloneable extends org.omg.CORBA.portable.IDLEntity +{ +} // interface Cloneable diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectFour.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectFour.java new file mode 100644 index 000000000..b52b34a0c --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectFour.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectFour implements Externalizable +{ + static Random r = new Random(); + int fInt; + long fLong; + float fFloat; + double fDouble; + String fString; + + ComplexTestObjectOne fOne = null; + ComplexTestObjectTwo fTwo = null; + + public ComplexTestObjectFour() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + fOne = new ComplexTestObjectOne(); + fTwo = new ComplexTestObjectTwo(); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectFour ctbo = (ComplexTestObjectFour)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && + (ctbo.fDouble == fDouble) + && (ctbo.fOne.equals(fOne)) + && (ctbo.fTwo.equals(fTwo)) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble/*+"; fString="+fString*/); + } + + public void writeExternal(ObjectOutput out) + throws IOException { + out.writeInt(fInt); + out.writeLong(fLong); + out.writeFloat(fFloat); + out.writeDouble(fDouble); + out.writeObject(fString); + out.writeObject(fOne); + out.writeObject(fTwo); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException { + fInt = in.readInt(); + fLong = in.readLong(); + fFloat = in.readFloat(); + fDouble = in.readDouble(); + fString = (String)in.readObject(); + fOne = (ComplexTestObjectOne)in.readObject(); + fTwo = (ComplexTestObjectTwo)in.readObject(); + + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectOne.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectOne.java new file mode 100644 index 000000000..9dd909d54 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectOne.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectOne implements Serializable +{ + static Random r = new Random(); + public int fInt; + public long fLong; + public float fFloat; + public double fDouble; + public String fString; + public java.lang.Object fMarshalAsAny; + + public ComplexTestObjectOne() + { + fInt = 1;//r.nextInt(); + fLong = 2;//r.nextLong(); + fFloat = 3;//r.nextFloat(); + fDouble = 4;//r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + fMarshalAsAny = (Object)new Character('S'); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectOne ctbo = (ComplexTestObjectOne)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && + (ctbo.fDouble == fDouble) && (ctbo.fMarshalAsAny.equals(fMarshalAsAny))); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectThree.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectThree.java new file mode 100644 index 000000000..329e7b095 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectThree.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectThree implements Serializable +{ + static Random r = new Random(); + int fInt; + long fLong; + float fFloat; + double fDouble; + String fString; + + ComplexTestObjectOne fOne = null; + ComplexTestObjectTwo fTwo = null; + + public ComplexTestObjectThree() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + fOne = new ComplexTestObjectOne(); + fTwo = new ComplexTestObjectTwo(); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectThree ctbo = (ComplexTestObjectThree)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && (ctbo.fDouble == fDouble) + && (ctbo.fOne.equals(fOne)) + && (ctbo.fTwo.equals(fTwo)) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwo.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwo.java new file mode 100644 index 000000000..ac1f3a59d --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwo.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectTwo implements Serializable +{ + static Random r = new Random(); + transient public int fInt; + transient public long fLong; + transient public float fFloat; + transient public double fDouble; + transient public String fString; + transient public ComplexTestObjectOne fOne = null; + + public ComplexTestObjectTwo() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + fOne = new ComplexTestObjectOne(); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectTwo ctbo = (ComplexTestObjectTwo)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && (ctbo.fDouble == fDouble) + && (ctbo.fOne.equals(fOne)) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } + + /** + * Serialize out to output stream. + */ + private void writeObject(ObjectOutputStream s) throws IOException + { + try + { + s.writeInt(fInt); + s.writeLong(fLong); + s.writeFloat(fFloat); + s.writeDouble(fDouble); + s.writeObject(fString); + s.writeObject(fOne); + } + catch(IOException e) + { + throw e; + } + } + + /** + * Serialize in from input stream. + */ + private void readObject(ObjectInputStream s) throws IOException, + ClassNotFoundException + { + try + { + fInt = s.readInt(); + fLong = s.readLong(); + fFloat = s.readFloat(); + fDouble = s.readDouble(); + fString = (String)s.readObject(); + fOne = (ComplexTestObjectOne)s.readObject(); + } + catch(IOException e) + { + throw e; + } + + } + +} + diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoDelta.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoDelta.java new file mode 100644 index 000000000..e8e5ac992 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoDelta.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectTwoDelta implements Serializable +{ + static Random r = new Random(); + public int fInt; + public long fLong; + public float fFloat; + public double fDouble; + public String fString; + public ComplexTestObjectOne fOne = null; + + public ComplexTestObjectTwoDelta() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + fOne = new ComplexTestObjectOne(); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectTwoDelta ctbo = (ComplexTestObjectTwoDelta)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && (ctbo.fDouble == fDouble) + && (ctbo.fOne.equals(fOne)) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } + + /** + * Serialize out to output stream. + */ + private void writeObject(ObjectOutputStream s) throws IOException + { + try + { + s.defaultWriteObject(); + } + catch(IOException e) + { + throw e; + } + } + +} + diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoSubclass.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoSubclass.java new file mode 100644 index 000000000..69f9f9e87 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoSubclass.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectTwoSubclass extends ComplexTestObjectTwo +{ + + public ComplexTestObjectTwoSubclass() + { + super(); + } + + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoSubclassDefaults.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoSubclassDefaults.java new file mode 100644 index 000000000..40ea0c2b7 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectTwoSubclassDefaults.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectTwoSubclassDefaults extends ComplexTestObjectTwo +{ + public int fInt2; + public long fLong2; + + public ComplexTestObjectTwoSubclassDefaults() + { + super(); + fInt2 = r.nextInt(); + fLong2 = r.nextLong(); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectTwoSubclassDefaults ctbo = (ComplexTestObjectTwoSubclassDefaults)o; + return ((ctbo.fInt2 == fInt2) && + (ctbo.fLong2 == fLong2) + ); + } + catch(Exception e) + { + return false; + } + } + + /** + * Serialize out to output stream. + */ + private void writeObject(ObjectOutputStream s) throws IOException + { + try + { + s.defaultWriteObject(); + s.writeDouble(55.5); + } + catch(IOException e) + { + throw e; + } + } + + /** + * Serialize in from input stream. + */ + private void readObject(ObjectInputStream s) throws IOException, + ClassNotFoundException + { + try + { + s.defaultReadObject(); + double d = s.readDouble(); + if (d != 55.5) + throw new IOException("ComplexTestObjectTwoSubclassDefaults - Read after defaultReadObject Failed!"); + } + catch(IOException e) + { + throw e; + } + + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectXXX.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectXXX.java new file mode 100644 index 000000000..fa10f37f6 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/ComplexTestObjectXXX.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class ComplexTestObjectXXX implements Serializable +{ + static Random r = new Random(); + int fInt; + long fLong; + float fFloat; + double fDouble; + String fString; + + Object fHandleAsAny = null; + + ComplexTestObjectOne fOne = null; + ComplexTestObjectTwo fTwo = null; + + public ComplexTestObjectXXX() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + fHandleAsAny = new ComplexTestObjectOne(); + fOne = new ComplexTestObjectOne(); + fTwo = new ComplexTestObjectTwo(); + } + + public boolean equals(Object o) + { + try + { + ComplexTestObjectXXX ctbo = (ComplexTestObjectXXX)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && + (ctbo.fDouble == fDouble) + && (ctbo.fHandleAsAny.equals(fHandleAsAny)) + && (ctbo.fOne.equals(fOne)) + && (ctbo.fTwo.equals(fTwo)) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble/*+"; fString="+fString*/); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Date.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Date.java new file mode 100644 index 000000000..c42d466ef --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Date.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* Date.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from java/util/Date.idl +* 01 June 1999 20:22:16 o'clock GMT+00:00 +*/ + +public abstract class Date implements javax.rmi.CORBA.serialization.Cloneable, org.omg.CORBA.portable.CustomValue +{ + private static String[] _truncatable_ids = { + DateHelper.id () + }; + + public String[] _truncatable_ids() { + return _truncatable_ids; + } + + public abstract long UTC (int arg0, int arg1, int arg2, int arg3, int arg4, int arg5); + + public abstract boolean after (Date arg0); + + public abstract boolean before (Date arg0); + + public abstract boolean _equals (org.omg.CORBA.Any arg0); + + public abstract int date (); + + public abstract void date (int newDate); + + public abstract int day (); + + public abstract int hours (); + + public abstract void hours (int newHours); + + public abstract int minutes (); + + public abstract void minutes (int newMinutes); + + public abstract int month (); + + public abstract void month (int newMonth); + + public abstract int seconds (); + + public abstract void seconds (int newSeconds); + + public abstract long time (); + + public abstract void time (long newTime); + + public abstract int timezoneOffset (); + + public abstract int year (); + + public abstract void year (int newYear); + + public abstract int _hashCode (); + + public abstract long parse (String arg0); + + public abstract String toGMTString (); + + public abstract String toLocaleString (); + + public abstract String _toString (); + +} // class Date diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateDefaultFactory.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateDefaultFactory.java new file mode 100644 index 000000000..e4e87b833 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateDefaultFactory.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* DateDefaultFactory.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from java/util/Date.idl +* 01 June 1999 20:22:16 o'clock GMT+00:00 +*/ + +public class DateDefaultFactory implements DateValueFactory { + + public Date create__ () + { + return new DateImpl (); + } + + public Date create__long__long__long (int arg0, int arg1, int arg2) + { + return new DateImpl (arg0, arg1, arg2); + } + + public Date create__long__long__long__long__long (int arg0, int arg1, int arg2, int arg3, int arg4) + { + return new DateImpl (arg0, arg1, arg2, arg3, arg4); + } + + public Date create__long__long__long__long__long__long (int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) + { + return new DateImpl (arg0, arg1, arg2, arg3, arg4, arg5); + } + + public Date create__long_long (long arg0) + { + return new DateImpl (arg0); + } + + public Date create__CORBA_WStringValue (String arg0) + { + return new DateImpl (arg0); + } + + public java.io.Serializable read_value (org.omg.CORBA_2_3.portable.InputStream is) + { + return is.read_value(new DateImpl()); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateHelper.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateHelper.java new file mode 100644 index 000000000..89f59b2af --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateHelper.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* DateHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from java/util/Date.idl +* 01 June 1999 20:22:16 o'clock GMT+00:00 +*/ + +abstract public class DateHelper +{ + private static String _id = "RMI:java.util.Date:2B112DD1F3049E5C:686A81014B597419"; + + public static void insert (org.omg.CORBA.Any a, Date that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static Date extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "Date", org.omg.CORBA.VM_CUSTOM.value, null, _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static Date read (org.omg.CORBA.portable.InputStream istream) + { + return (Date)((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, Date value) + { + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ()); + } + + + public static Date create__ (org.omg.CORBA.ORB _orb) + { + try { + DateValueFactory _factory = (DateValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create__ (); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + + public static Date create__long__long__long (org.omg.CORBA.ORB _orb, int arg0, int arg1, int arg2) + { + try { + DateValueFactory _factory = (DateValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create__long__long__long (arg0, arg1, arg2); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + + public static Date create__long__long__long__long__long (org.omg.CORBA.ORB _orb, int arg0, int arg1, int arg2, int arg3, int arg4) + { + try { + DateValueFactory _factory = (DateValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create__long__long__long__long__long (arg0, arg1, arg2, arg3, arg4); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + + public static Date create__long__long__long__long__long__long (org.omg.CORBA.ORB _orb, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) + { + try { + DateValueFactory _factory = (DateValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create__long__long__long__long__long__long (arg0, arg1, arg2, arg3, arg4, arg5); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + + public static Date create__long_long (org.omg.CORBA.ORB _orb, long arg0) + { + try { + DateValueFactory _factory = (DateValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create__long_long (arg0); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + + public static Date create__CORBA_WStringValue (org.omg.CORBA.ORB _orb, String arg0) + { + try { + DateValueFactory _factory = (DateValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create__CORBA_WStringValue (arg0); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateImpl.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateImpl.java new file mode 100644 index 000000000..ef83afde3 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateImpl.java @@ -0,0 +1,268 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class DateImpl extends Date +{ + //nk + private java.util.Date delegate = null; + //nk + + public DateImpl () + { + //nk + delegate = new java.util.Date(); + //nk + } + + public DateImpl (long arg0) + { + //nk + delegate = new java.util.Date(arg0); + //nk + } + + public DateImpl (int arg0, int arg1, int arg2) + { + //nk + delegate = new java.util.Date(arg0, arg1, arg2); + //nk + } + + public DateImpl (int arg0, int arg1, int arg2, int arg3, int arg4) + { + //nk + delegate = new java.util.Date(arg0, arg1, arg2, arg3, arg4); + //nk + } + + public DateImpl (int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) + { + //nk + delegate = new java.util.Date(arg0, arg1, arg2, arg3, arg4, arg5); + //nk + + } + + public DateImpl (String arg0) + { + //nk + delegate = new java.util.Date(arg0); + //nk + } + + public long UTC (int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) + { + //nk + return delegate.UTC (arg0, arg1, arg2, arg3, arg4, arg5); + //nk + } + + public long parse (String arg0) + { + //nk + return delegate.parse(arg0); + //nk + } + + public int year () + { + //nk + return delegate.getYear(); + //nk + } + + public void year (int newYear) + { + //nk + delegate.setYear(newYear); + //nk + } + + public int month () + { + //nk + return delegate.getMonth(); + //nk + } + + public void month (int newMonth) + { + //nk + delegate.setMonth(newMonth); + //nk + } + + public int date () + { + //nk + return delegate.getDate(); + //nk + } + + public void date (int newDate) + { + //nk + delegate.setDate(newDate); + //nk + } + + public int day () + { + //nk + return delegate.getDay(); + //nk + } + + public int hours () + { + //nk + return delegate.getHours(); + //nk + + } + + public void hours (int newHours) + { + //nk + delegate.setHours(newHours); + //nk + } + + public int minutes () + { + //nk + return delegate.getMinutes(); + //nk + } + + public void minutes (int newMinutes) + { + //nk + delegate.setMinutes(newMinutes); + //nk + } + + public int seconds () + { + //nk + return delegate.getSeconds(); + //nk + } + + public void seconds (int newSeconds) + { + //nk + delegate.setSeconds(newSeconds); + //nk + } + + public long time () + { + //nk + return delegate.getTime(); + //nk + } + + public void time (long newTime) + { + //nk + delegate.setTime(newTime); + //nk + } + + public boolean before (javax.rmi.CORBA.serialization.Date arg0) + { + //nk + return delegate.before(((DateImpl)arg0).getDelegate()); + //nk + } + + public boolean after (javax.rmi.CORBA.serialization.Date arg0) + { + //nk + return delegate.after(((DateImpl)arg0).getDelegate()); + //nk + } + + public boolean _equals (org.omg.CORBA.Any arg0) + { + //nk + return false; + //nk + } + + public int _hashCode () + { + //nk + return delegate.hashCode(); + //nk + } + + public String _toString () + { + //nk + return delegate.toString(); + //nk + } + + public String toLocaleString () + { + //nk + return delegate.toLocaleString(); + //nk + } + + public String toGMTString () + { + //nk + return delegate.toGMTString(); + //nk + } + + public int timezoneOffset () + { + //nk + return delegate.getTimezoneOffset(); + //nk + + } + + //nk + public void setDelegate (java.util.Date delegate) + { + this.delegate = delegate; + } + + public java.util.Date getDelegate() + { + return delegate; + } + //nk + + //nk + //Methods to be implemented for Custom Marshalling + public void marshal(org.omg.CORBA.DataOutputStream os) + { + os.write_octet((byte)1); + os.write_boolean(false); + os.write_longlong(delegate.getTime()); + } + + public void unmarshal(org.omg.CORBA.DataInputStream is) + { + is.read_octet(); + is.read_boolean(); + delegate = new java.util.Date(is.read_longlong()); + } + //nk +} // class DateImpl diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateValueFactory.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateValueFactory.java new file mode 100644 index 000000000..d25c0bfe2 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/DateValueFactory.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* DateValueFactory.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from java/util/Date.idl +* 01 June 1999 20:22:16 o'clock GMT+00:00 +*/ + +public interface DateValueFactory extends org.omg.CORBA.portable.ValueFactory +{ + Date create__ (); + Date create__long__long__long (int arg0, int arg1, int arg2); + Date create__long__long__long__long__long (int arg0, int arg1, int arg2, int arg3, int arg4); + Date create__long__long__long__long__long__long (int arg0, int arg1, int arg2, int arg3, int arg4, int arg5); + Date create__long_long (long arg0); + Date create__CORBA_WStringValue (String arg0); +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/EmptyTestObject.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/EmptyTestObject.java new file mode 100644 index 000000000..2b794d6cf --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/EmptyTestObject.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +public class EmptyTestObject implements java.io.Serializable +{ + + public EmptyTestObject() + { + } + + public boolean equals(Object o) + { + return (o instanceof EmptyTestObject); + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Graph.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Graph.java new file mode 100644 index 000000000..fecada818 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Graph.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +// Class from Sun + + +import java.io.*; + +public class Graph implements Serializable { + + public final String CONSTANT_STRING = "This is a constant string."; + public final int CONSTANT_INT = 10; + public final BitSet CONSTANT_BITSET = new BitSet(32); + private String _list = null; + private Graph _next = null; + private BitSet _bitset = null; + transient String t_string = "This is a transient string."; + transient int t_int = 1111; + transient BitSet t_bitset = new BitSet(32); + + public Graph(String data, Graph next) { + this._list = data; + this._bitset = new BitSet(64); + this._bitset.set(10);this._bitset.set(20); + this._bitset.set(30);this._bitset.set(40); + this._bitset.set(50);this._bitset.set(60); + this._next = next; + } + + public String data() { + return this._list; + } + + public Graph next() { + return this._next; + } + + public void next(Graph next) { + this._next = next; + } + + public boolean equals(Graph o) { + try{ + Graph g = (Graph)o; + return ((_list.equals(g._list)) && + (_next.equals(g._next)) && + (_bitset.equals(g._bitset))); + } + catch(Throwable t){ + return false; + } + } + + public String toString() { + StringBuffer result = new StringBuffer("{ "); + for(Graph list = this; list != null; list = list.next()) { + result.append(list.data()).append(" "); + } + return result.append("}").toString(); + } + + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IDLValue.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IDLValue.java new file mode 100644 index 000000000..438368bfb --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IDLValue.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class IDLValue implements org.omg.CORBA.portable.IDLEntity +{ + static Random r = new Random(); + public int fInt; + public long fLong; + public float fFloat; + public double fDouble; + public String fString; + + public IDLValue() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + } + + public boolean equals(Object o) + { + try + { + IDLValue ctbo = (IDLValue)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && + (ctbo.fDouble == fDouble)); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IDLValueHelper.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IDLValueHelper.java new file mode 100644 index 000000000..1c69f089f --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IDLValueHelper.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.TypeCode; + +public abstract class IDLValueHelper +{ + public static void insert (org.omg.CORBA.Any a, IDLValue that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static IDLValue extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( id() ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [1]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[0] = new org.omg.CORBA.StructMember ( + "foo", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (id(), "IDLValue", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id() + { + return "IDL:javax/rmi/CORBA/serialization/IDLValue:1.0"; + } + + public static IDLValue read (org.omg.CORBA.portable.InputStream istream) + { + IDLValue value = new IDLValue(); + value.fInt = istream.read_long(); + value.fLong = istream.read_longlong(); + value.fFloat = istream.read_float(); + value.fDouble = istream.read_double(); + value.fString = istream.read_string(); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, IDLValue value) + { + ostream.write_long(value.fInt); + ostream.write_longlong(value.fLong); + ostream.write_float(value.fFloat); + ostream.write_double(value.fDouble); + ostream.write_string(value.fString); + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IIOPPerformance.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IIOPPerformance.java new file mode 100644 index 000000000..f0f5cf075 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IIOPPerformance.java @@ -0,0 +1,364 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @test 1.0 98/04/21 + * @summary Verify that RMI IIOP Serialization works correctly. + * + * + * @compile javax\rmi\CORBA\serialization\SerializationTest.java + * @run main SerializationTest + */ + +package javax.rmi.CORBA.serialization; + +import javax.rmi.CORBA.serialization.*; +import javax.rmi.CORBA.*; +import rmic.ObjectByValue; + +import java.io.*; +import java.util.Properties ; + +public class IIOPPerformance extends test.Test +{ + public void run() + { + try { + Properties orbProps = new Properties() ; + orbProps.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + orbProps.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton" ) ; + org.omg.CORBA.ORB orb = + org.omg.CORBA.ORB.init(getArgsAsArgs(),orbProps); + + org.omg.CORBA_2_3.portable.OutputStream sos = + (org.omg.CORBA_2_3.portable.OutputStream)orb.create_output_stream(); + + TestOBV2 tobv2 = new TestOBV2(); + sos.write_value(tobv2); + + Exception exception = new Exception("Test Exception"); + sos.write_value(exception); + + Float f = new Float(1.23); + sos.write_value(f); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne test1 = + new javax.rmi.CORBA.serialization.ComplexTestObjectOne(); + sos.write_value(test1); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwo test2 = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwo(); + sos.write_value(test2); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass test2subclass = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass(); + sos.write_value(test2subclass); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults test2subclassDefaults = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults(); + sos.write_value(test2subclassDefaults); + + javax.rmi.CORBA.serialization.EmptyTestObject testEmptyA= + new javax.rmi.CORBA.serialization.EmptyTestObject(); + sos.write_value(testEmptyA); + + javax.rmi.CORBA.serialization.EmptyTestObject testEmptyB= + new javax.rmi.CORBA.serialization.EmptyTestObject(); + sos.write_value(testEmptyB); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne test1b = + new javax.rmi.CORBA.serialization.ComplexTestObjectOne(); + sos.write_value(test1b); + + Double d = new Double(3.5); + sos.write_value(d); + + javax.rmi.CORBA.serialization.ComplexTestObjectThree test3 = + new javax.rmi.CORBA.serialization.ComplexTestObjectThree(); + sos.write_value(test3); + + javax.rmi.CORBA.serialization.ComplexTestObjectFour test4 = + new javax.rmi.CORBA.serialization.ComplexTestObjectFour(); + sos.write_value(test4); + + java.util.Properties props = new java.util.Properties(); + props.put("Key1","Value1"); + sos.write_value(props); + + // Test arrays + int anIntArray[] = {9,8,7}; + sos.write_value(anIntArray); + + Object aSharedRefsArray[] = { testEmptyA, test1b, anIntArray }; + sos.write_value( aSharedRefsArray ); + + // Check single dimensional primitive array... + + int[] array1 = {0,5,7,9,11,13}; + sos.write_value(array1); + + + // Check 2 dimensional primitive array... + + long[][] array2 = { + {9,8,7,6,1}, + {18,4,6}, + {0,5,7,9,11,13} + }; + sos.write_value(array2); + + // Recursive array references + Object recursiveArray[] = {null, "Hello", null, null}; + recursiveArray[0] = recursiveArray; + recursiveArray[2] = recursiveArray; + recursiveArray[3] = recursiveArray; + sos.write_value(recursiveArray); + + + + // Check 3 dimensional primitive array... + short[][][] dim3 = { + { + {0,8,7,6,1}, + {1,5,7,13}, + {2,4,6}, + }, + { + {3,4,10}, + {4,5,7,9,13} + }, + { + {5,4,6}, + {6,5,8,9,11,13}, + {7,8,7,6,1}, + {8,8,7,6,9}, + }, + }; + sos.write_value(dim3); + + // Check single dimensional object array... + + ObjectByValue[] array3 = { + new ObjectByValue(5,10,"a","f"), + new ObjectByValue(6,11,"b","g"), + new ObjectByValue(7,12,"c","h"), + new ObjectByValue(8,13,"d","i"), + new ObjectByValue(9,14,"e","j"), + }; + sos.write_value(array3); + + // Check multi dimensional object array... + + ObjectByValue[][] array4 = { { + new ObjectByValue(0,10,"a","g"), + new ObjectByValue(0,11,"b","h"), + new ObjectByValue(0,12,"c","i"), + }, + { + new ObjectByValue(1,13,"d","j"), + new ObjectByValue(1,14,"e","k"), + }, + { + new ObjectByValue(2,15,"f","l"), + } + }; + + sos.write_value(array4); + + /***************************************************************/ + /*********************** READ DATA BACK IN *********************/ + /***************************************************************/ + + org.omg.CORBA_2_3.portable.InputStream sis = + (org.omg.CORBA_2_3.portable.InputStream)sos.create_input_stream(); + + TestOBV2 _tobv2 = (TestOBV2)sis.read_value(); + + Exception _exception = (Exception)sis.read_value(); + if (!_exception.getMessage().equals("Test Exception")) + throw new Error("Test Exception failed!"); + + Float _f = (Float)sis.read_value(); + if (!f.equals(_f)) + throw new Error("Test Float failed!"); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne _test1 = + (javax.rmi.CORBA.serialization.ComplexTestObjectOne)sis.read_value(); + + if (test1.equals(_test1)) + ; + else + throw new Error("FAILURE! Test1 Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwo _test2 = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwo)sis.read_value(); + + if (test2.equals(_test2)) + ; + else + throw new Error("FAILURE! Test2 Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass _test2subclass = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass)sis.read_value(); + + if (test2subclass.equals(_test2subclass)) + ; + else + throw new Error("FAILURE! Test2subclass Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults _test2subclassDefaults = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults)sis.read_value(); + + if (test2subclassDefaults.equals(_test2subclassDefaults)) + ; + else + throw new Error("FAILURE! Test2subclassDefaults Failed"); + + javax.rmi.CORBA.serialization.EmptyTestObject _testEmptyA = + (javax.rmi.CORBA.serialization.EmptyTestObject)sis.read_value(); + + if (testEmptyA.equals(_testEmptyA)) + ; + else + throw new Error("FAILURE! TestEmptyA Failed"); + + javax.rmi.CORBA.serialization.EmptyTestObject _testEmptyB = + (javax.rmi.CORBA.serialization.EmptyTestObject)sis.read_value(); + + if (testEmptyB.equals(_testEmptyB)) + ; + else + throw new Error("FAILURE! TestEmptyB Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne _test1b = + (javax.rmi.CORBA.serialization.ComplexTestObjectOne)sis.read_value(); + + if (test1b.equals(_test1b)) + ; + else + throw new Error("FAILURE! Test1b Failed"); + + Double _d = (Double)sis.read_value(); + + if (d.equals(_d)) + ; + else + throw new Error("FAILURE! d Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectThree _test3 = + (javax.rmi.CORBA.serialization.ComplexTestObjectThree)sis.read_value(); + + if (test3.equals(_test3)) + ; + else + throw new Error("FAILURE! Test3 Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectFour _test4 = + (javax.rmi.CORBA.serialization.ComplexTestObjectFour)sis.read_value(); + + if (test4.equals(_test4)) + ; + else + throw new Error("FAILURE! Test4 Failed"); + + java.util.Properties _props = (java.util.Properties)sis.read_value(); + if (_props.toString().equals(props.toString())) + ; + else + throw new Error("FAILURE! props Failed"); + + + int _anIntArray[] = (int[])sis.read_value(); + + if ((_anIntArray[0] == anIntArray[0]) && + (_anIntArray[1] == anIntArray[1]) && + (_anIntArray[2] == anIntArray[2])) + ; + else + throw new Error("FAILURE! anIntArray Failed"); + + Object _aSharedRefsArray[] = (Object[])sis.read_value(); + + if ((_aSharedRefsArray[0] == _testEmptyA) && + (_aSharedRefsArray[1] == _test1b) && + (_aSharedRefsArray[2] == _anIntArray)) + ; + else + throw new Error("FAILURE! aSharedRefsArray[] == Failed"); + + int[] array1Echo = (int[])sis.read_value(); + + for (int i = 0; i < array1.length; i++) { + if (array1[i] != array1Echo[i]) { + throw new Exception("HelloTest: echoArray (int[]) failed"); + } + } + + long[][] array2Echo = (long[][])sis.read_value(); + + for (int i = 0; i < array2.length; i++) { + for (int j = 0; j < array2[i].length; j++) { + if (array2[i][j] != array2Echo[i][j]) { + throw new Exception("HelloTest: echoArray (int[][]) failed"); + } + } + } + + // Recursive array references + Object recursiveArrayEcho[] = (Object[])sis.read_value(); + if ((recursiveArrayEcho[0] != recursiveArrayEcho) || + (recursiveArrayEcho[2] != recursiveArrayEcho) || + (recursiveArrayEcho[3] != recursiveArrayEcho) || + (!((String)recursiveArrayEcho[1]).equals("Hello"))) + throw new Exception("RecursiveArray test failed!"); + + short[][][] dim3Echo = (short[][][])sis.read_value(); + + for (int i = 0; i < dim3.length; i++) { + for (int j = 0; j < dim3[i].length; j++) { + for (int k = 0; k < dim3[i][j].length; k++) { + if (dim3[i][j][k] != dim3[i][j][k]) { + throw new Exception("HelloTest: echoArray (short[][][]) failed"); + } + } + } + } + + ObjectByValue[] array3Echo = (ObjectByValue[])sis.read_value(); + for (int i = 0; i < array3.length; i++) { + if (!array3[i].equals(array3Echo[i])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[]) failed"); + } + } + + ObjectByValue[][] array4Echo = (ObjectByValue[][])sis.read_value(); + + for (int i = 0; i < array4.length; i++) { + for (int j = 0; j < array4[i].length; j++) { + if (!array4[i][j].equals(array4Echo[i][j])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[][]) failed"); + } + } + } + + + + } + catch(Throwable e) + { + status = new Error(e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IsSerializable.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IsSerializable.java new file mode 100644 index 000000000..cce3534be --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/IsSerializable.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class IsSerializable + extends NotSerializable implements java.io.Serializable { + + String helloString; + + public IsSerializable(){} + + public IsSerializable(String mssg){ + helloString = mssg; + } + + public boolean equals(Object o){ + if (!(o instanceof IsSerializable)) + return false; + return helloString.equals(((IsSerializable)o).helloString); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/JRMPPerformance.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/JRMPPerformance.java new file mode 100644 index 000000000..620f856f0 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/JRMPPerformance.java @@ -0,0 +1,358 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @test 1.0 98/04/21 + * @summary Verify that RMI IIOP Serialization works correctly. + * + * + * @compile javax\rmi\CORBA\serialization\SerializationTest.java + * @run main SerializationTest + */ + +package javax.rmi.CORBA.serialization; + +import javax.rmi.CORBA.serialization.*; +import javax.rmi.CORBA.*; +import rmic.ObjectByValue; + +import java.io.*; + +public class JRMPPerformance extends test.Test +{ + + public void run() + { + + try { + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream sos = new ObjectOutputStream(bos); + + TestOBV2 tobv2 = new TestOBV2(); + sos.writeObject(tobv2); + + Exception exception = new Exception("Test Exception"); + sos.writeObject(exception); + + Float f = new Float(1.23); + sos.writeObject(f); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne test1 = + new javax.rmi.CORBA.serialization.ComplexTestObjectOne(); + sos.writeObject(test1); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwo test2 = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwo(); + sos.writeObject(test2); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass test2subclass = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass(); + sos.writeObject(test2subclass); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults test2subclassDefaults = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults(); + sos.writeObject(test2subclassDefaults); + + javax.rmi.CORBA.serialization.EmptyTestObject testEmptyA= + new javax.rmi.CORBA.serialization.EmptyTestObject(); + sos.writeObject(testEmptyA); + + javax.rmi.CORBA.serialization.EmptyTestObject testEmptyB= + new javax.rmi.CORBA.serialization.EmptyTestObject(); + sos.writeObject(testEmptyB); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne test1b = + new javax.rmi.CORBA.serialization.ComplexTestObjectOne(); + sos.writeObject(test1b); + + Double d = new Double(3.5); + sos.writeObject(d); + + javax.rmi.CORBA.serialization.ComplexTestObjectThree test3 = + new javax.rmi.CORBA.serialization.ComplexTestObjectThree(); + sos.writeObject(test3); + + javax.rmi.CORBA.serialization.ComplexTestObjectFour test4 = + new javax.rmi.CORBA.serialization.ComplexTestObjectFour(); + sos.writeObject(test4); + + java.util.Properties props = new java.util.Properties(); + props.put("Key1","Value1"); + sos.writeObject(props); + + // Test arrays + int anIntArray[] = {9,8,7}; + sos.writeObject(anIntArray); + + Object aSharedRefsArray[] = { testEmptyA, test1b, anIntArray }; + sos.writeObject( aSharedRefsArray ); + + // Check single dimensional primitive array... + + int[] array1 = {0,5,7,9,11,13}; + sos.writeObject(array1); + + + // Check 2 dimensional primitive array... + + long[][] array2 = { + {9,8,7,6,1}, + {18,4,6}, + {0,5,7,9,11,13} + }; + sos.writeObject(array2); + + // Recursive array references + Object recursiveArray[] = {null, "Hello", null, null}; + recursiveArray[0] = recursiveArray; + recursiveArray[2] = recursiveArray; + recursiveArray[3] = recursiveArray; + sos.writeObject(recursiveArray); + + + + // Check 3 dimensional primitive array... + short[][][] dim3 = { + { + {0,8,7,6,1}, + {1,5,7,13}, + {2,4,6}, + }, + { + {3,4,10}, + {4,5,7,9,13} + }, + { + {5,4,6}, + {6,5,8,9,11,13}, + {7,8,7,6,1}, + {8,8,7,6,9}, + }, + }; + sos.writeObject(dim3); + + // Check single dimensional object array... + + ObjectByValue[] array3 = { + new ObjectByValue(5,10,"a","f"), + new ObjectByValue(6,11,"b","g"), + new ObjectByValue(7,12,"c","h"), + new ObjectByValue(8,13,"d","i"), + new ObjectByValue(9,14,"e","j"), + }; + sos.writeObject(array3); + + // Check multi dimensional object array... + + ObjectByValue[][] array4 = { { + new ObjectByValue(0,10,"a","g"), + new ObjectByValue(0,11,"b","h"), + new ObjectByValue(0,12,"c","i"), + }, + { + new ObjectByValue(1,13,"d","j"), + new ObjectByValue(1,14,"e","k"), + }, + { + new ObjectByValue(2,15,"f","l"), + } + }; + + sos.writeObject(array4); + + /***************************************************************/ + /*********************** READ DATA BACK IN *********************/ + /***************************************************************/ + + ObjectInputStream sis = + new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); + + + TestOBV2 _tobv2 = (TestOBV2)sis.readObject(); + + Exception _exception = (Exception)sis.readObject(); + if (!_exception.getMessage().equals("Test Exception")) + throw new Error("Test Exception failed!"); + + Float _f = (Float)sis.readObject(); + if (!f.equals(_f)) + throw new Error("Test Float failed!"); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne _test1 = + (javax.rmi.CORBA.serialization.ComplexTestObjectOne)sis.readObject(); + + if (test1.equals(_test1)) + ; + else + throw new Error("FAILURE! Test1 Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwo _test2 = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwo)sis.readObject(); + + if (test2.equals(_test2)) + ; + else + throw new Error("FAILURE! Test2 Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass _test2subclass = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass)sis.readObject(); + + if (test2subclass.equals(_test2subclass)) + ; + else + throw new Error("FAILURE! Test2subclass Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults _test2subclassDefaults = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults)sis.readObject(); + + if (test2subclassDefaults.equals(_test2subclassDefaults)) + ; + else + throw new Error("FAILURE! Test2subclassDefaults Failed"); + + javax.rmi.CORBA.serialization.EmptyTestObject _testEmptyA = + (javax.rmi.CORBA.serialization.EmptyTestObject)sis.readObject(); + + if (testEmptyA.equals(_testEmptyA)) + ; + else + throw new Error("FAILURE! TestEmptyA Failed"); + + javax.rmi.CORBA.serialization.EmptyTestObject _testEmptyB = + (javax.rmi.CORBA.serialization.EmptyTestObject)sis.readObject(); + + if (testEmptyB.equals(_testEmptyB)) + ; + else + throw new Error("FAILURE! TestEmptyB Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectOne _test1b = + (javax.rmi.CORBA.serialization.ComplexTestObjectOne)sis.readObject(); + + if (test1b.equals(_test1b)) + ; + else + throw new Error("FAILURE! Test1b Failed"); + + Double _d = (Double)sis.readObject(); + + if (d.equals(_d)) + ; + else + throw new Error("FAILURE! d Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectThree _test3 = + (javax.rmi.CORBA.serialization.ComplexTestObjectThree)sis.readObject(); + + if (test3.equals(_test3)) + ; + else + throw new Error("FAILURE! Test3 Failed"); + + javax.rmi.CORBA.serialization.ComplexTestObjectFour _test4 = + (javax.rmi.CORBA.serialization.ComplexTestObjectFour)sis.readObject(); + + if (test4.equals(_test4)) + ; + else + throw new Error("FAILURE! Test4 Failed"); + + java.util.Properties _props = (java.util.Properties)sis.readObject(); + if (_props.toString().equals(props.toString())) + ; + else + throw new Error("FAILURE! props Failed"); + + + int _anIntArray[] = (int[])sis.readObject(); + + if ((_anIntArray[0] == anIntArray[0]) && + (_anIntArray[1] == anIntArray[1]) && + (_anIntArray[2] == anIntArray[2])) + ; + else + throw new Error("FAILURE! anIntArray Failed"); + + Object _aSharedRefsArray[] = (Object[])sis.readObject(); + + if ((_aSharedRefsArray[0] == _testEmptyA) && + (_aSharedRefsArray[1] == _test1b) && + (_aSharedRefsArray[2] == _anIntArray)) + ; + else + throw new Error("FAILURE! aSharedRefsArray[] == Failed"); + + int[] array1Echo = (int[])sis.readObject(); + + for (int i = 0; i < array1.length; i++) { + if (array1[i] != array1Echo[i]) { + throw new Exception("HelloTest: echoArray (int[]) failed"); + } + } + + long[][] array2Echo = (long[][])sis.readObject(); + + for (int i = 0; i < array2.length; i++) { + for (int j = 0; j < array2[i].length; j++) { + if (array2[i][j] != array2Echo[i][j]) { + throw new Exception("HelloTest: echoArray (int[][]) failed"); + } + } + } + + // Recursive array references + Object recursiveArrayEcho[] = (Object[])sis.readObject(); + if ((recursiveArrayEcho[0] != recursiveArrayEcho) || + (recursiveArrayEcho[2] != recursiveArrayEcho) || + (recursiveArrayEcho[3] != recursiveArrayEcho) || + (!((String)recursiveArrayEcho[1]).equals("Hello"))) + throw new Exception("RecursiveArray test failed!"); + + short[][][] dim3Echo = (short[][][])sis.readObject(); + + for (int i = 0; i < dim3.length; i++) { + for (int j = 0; j < dim3[i].length; j++) { + for (int k = 0; k < dim3[i][j].length; k++) { + if (dim3[i][j][k] != dim3[i][j][k]) { + throw new Exception("HelloTest: echoArray (short[][][]) failed"); + } + } + } + } + + ObjectByValue[] array3Echo = (ObjectByValue[])sis.readObject(); + for (int i = 0; i < array3.length; i++) { + if (!array3[i].equals(array3Echo[i])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[]) failed"); + } + } + + ObjectByValue[][] array4Echo = (ObjectByValue[][])sis.readObject(); + + for (int i = 0; i < array4.length; i++) { + for (int j = 0; j < array4[i].length; j++) { + if (!array4[i][j].equals(array4Echo[i][j])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[][]) failed"); + } + } + } + + + } + catch(Throwable e) + { + status = new Error(e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/NotSerializable.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/NotSerializable.java new file mode 100644 index 000000000..212b41164 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/NotSerializable.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class NotSerializable { + int Int1 = 999; +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/NotSerializableChild.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/NotSerializableChild.java new file mode 100644 index 000000000..ce05f8298 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/NotSerializableChild.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class NotSerializableChild extends IsSerializable { + int Int2 = 333; + + public NotSerializableChild(){ + super("Not a serializable child"); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustom.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustom.java new file mode 100644 index 000000000..6465c608f --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustom.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public abstract class OBVTestObjectCustom implements org.omg.CORBA.portable.CustomValue +{ + private static String[] _truncatable_ids = { + OBVTestObjectCustomHelper.id () + }; + + public String[] _truncatable_ids() { + return _truncatable_ids; + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomDefaultFactory.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomDefaultFactory.java new file mode 100644 index 000000000..01097c857 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomDefaultFactory.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class OBVTestObjectCustomDefaultFactory implements org.omg.CORBA.portable.ValueFactory { + + public java.io.Serializable read_value (org.omg.CORBA_2_3.portable.InputStream is) + { + return is.read_value(new OBVTestObjectCustomImpl(is)); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomHelper.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomHelper.java new file mode 100644 index 000000000..c3f7e2026 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomHelper.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +abstract public class OBVTestObjectCustomHelper +{ + private static String _id = "IDL:javax/rmi/CORBA/serialization/OBVTestObjectCustom:1.0"; + + public static void insert (org.omg.CORBA.Any a, OBVTestObjectCustom that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static OBVTestObjectCustom extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "OBVTestObjectCustom", org.omg.CORBA.VM_CUSTOM.value, null, _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static OBVTestObjectCustom read (org.omg.CORBA.portable.InputStream istream) + { + return (OBVTestObjectCustom)((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, OBVTestObjectCustom value) + { + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ()); + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomImpl.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomImpl.java new file mode 100644 index 000000000..17a1a0e79 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectCustomImpl.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class OBVTestObjectCustomImpl extends OBVTestObjectCustom { + private static Random r = new Random(); + + // We mark these as transients just so we can make sure during the test that + // only by using the marshal and unmarshal methods could this class be serialized. + private transient int fInt; + private transient long fLong; + private transient float fFloat; + private transient double fDouble; + private transient String fString; + + OBVTestObjectCustomImpl(int aInt, long aLong, float aFloat, double aDouble, String aString) + { + fInt = aInt; + fLong = aLong; + fFloat = aFloat; + fDouble = aDouble; + fString = aString; + } + + public OBVTestObjectCustomImpl() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + } + + OBVTestObjectCustomImpl(org.omg.CORBA.portable.InputStream is) + { + // for unmarshalling only, called by the factory + } + + public boolean equals(Object o) + { + try + { + OBVTestObjectCustomImpl ctbo = (OBVTestObjectCustomImpl)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && (ctbo.fDouble == fDouble) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } + + public void marshal (org.omg.CORBA.DataOutputStream os) + { + os.write_long(fInt); + os.write_longlong(fLong); + os.write_float(fFloat); + os.write_double(fDouble); + os.write_string(fString); + } + + public void unmarshal (org.omg.CORBA.DataInputStream is) + { + fInt = is.read_long(); + fLong = is.read_longlong(); + fFloat = is.read_float(); + fDouble = is.read_double(); + fString = is.read_string(); + + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOne.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOne.java new file mode 100644 index 000000000..3a03fd97d --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOne.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public abstract class OBVTestObjectOne implements org.omg.CORBA.portable.StreamableValue +{ + // We mark these as transients just so we can make sure during the test + // that only by using the Streamable interface could this class be serialized. + protected transient int fInt = (int)0; + protected transient long fLong = (long)0; + protected transient float fFloat = (float)0; + protected transient double fDouble = (double)0; + protected transient String fString = null; + + private static String[] _truncatable_ids = { + OBVTestObjectOneHelper.id () + }; + + public String[] _truncatable_ids() { + return _truncatable_ids; + } + + public void _read (org.omg.CORBA.portable.InputStream istream) + { + this.fInt = istream.read_long (); + this.fLong = istream.read_longlong (); + this.fFloat = istream.read_float (); + this.fDouble = istream.read_double (); + this.fString = istream.read_string (); + } + + public void _write (org.omg.CORBA.portable.OutputStream ostream) + { + ostream.write_long (this.fInt); + ostream.write_longlong (this.fLong); + ostream.write_float (this.fFloat); + ostream.write_double (this.fDouble); + ostream.write_string (this.fString); + } + + public org.omg.CORBA.TypeCode _type () + { + return OBVTestObjectOneHelper.type (); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneDefaultFactory.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneDefaultFactory.java new file mode 100644 index 000000000..39c3d38aa --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneDefaultFactory.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class OBVTestObjectOneDefaultFactory implements org.omg.CORBA.portable.ValueFactory { + + public java.io.Serializable read_value(org.omg.CORBA_2_3.portable.InputStream is) + { + return is.read_value(new OBVTestObjectOneImpl(is)); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneHelper.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneHelper.java new file mode 100644 index 000000000..c8cc72b37 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneHelper.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +abstract public class OBVTestObjectOneHelper +{ + private static String _id = "IDL:javax/rmi/CORBA/serialization/OBVTestObjectOne:1.0"; + + public static void insert (org.omg.CORBA.Any a, OBVTestObjectOne that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static OBVTestObjectOne extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[5]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + // ValueMember instance for fInt + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[0] = new org.omg.CORBA.ValueMember ("fInt", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + // ValueMember instance for fLong + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_longlong); + _members0[1] = new org.omg.CORBA.ValueMember ("fLong", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + // ValueMember instance for fFloat + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_float); + _members0[2] = new org.omg.CORBA.ValueMember ("fFloat", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + // ValueMember instance for fDouble + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_double); + _members0[3] = new org.omg.CORBA.ValueMember ("fDouble", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + // ValueMember instance for fString + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _members0[4] = new org.omg.CORBA.ValueMember ("fString", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "OBVTestObjectOne", org.omg.CORBA.VM_NONE.value, null, _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static OBVTestObjectOne read (org.omg.CORBA.portable.InputStream istream) + { + return (OBVTestObjectOne)((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, OBVTestObjectOne value) + { + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ()); + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneImpl.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneImpl.java new file mode 100644 index 000000000..0edc7a8e6 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/OBVTestObjectOneImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class OBVTestObjectOneImpl extends OBVTestObjectOne +{ + static Random r = new Random(); + + OBVTestObjectOneImpl(int aInt, long aLong, float aFloat, double aDouble, String aString) + { + fInt = aInt; + fLong = aLong; + fFloat = aFloat; + fDouble = aDouble; + fString = aString; + } + + public OBVTestObjectOneImpl() + { + fInt = r.nextInt(); + fLong = r.nextLong(); + fFloat = r.nextFloat(); + fDouble = r.nextDouble(); + fString = new String(fInt +""+ fLong +""+ fFloat +""+ fDouble); + } + + OBVTestObjectOneImpl(org.omg.CORBA.portable.InputStream is) + { + // for unmarshalling only, called by the factory + } + + public boolean equals(Object o) + { + try + { + OBVTestObjectOne ctbo = (OBVTestObjectOne)o; + return ((ctbo.fString.equals(fString)) && (ctbo.fInt == fInt) && + (ctbo.fLong == fLong) && (ctbo.fFloat == fFloat) && (ctbo.fDouble == fDouble) + ); + } + catch(Exception e) + { + return false; + } + } + + public String toString() + { + return new String("fInt="+fInt+"; fLong="+fLong+"; fFloat="+fFloat+"; fDouble="+fDouble+"; fString="+fString); + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/SerializationTest.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/SerializationTest.java new file mode 100644 index 000000000..7a77c90e9 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/SerializationTest.java @@ -0,0 +1,738 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @test 1.0 98/04/21 + * @summary Verify that RMI IIOP Serialization works correctly. + * + * + * @compile javax\rmi\CORBA\serialization\SerializationTest.java + * @run main SerializationTest + */ + +package javax.rmi.CORBA.serialization; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Properties; +import java.util.Vector; +import org.glassfish.pfl.test.JUnitReportHelper; +import rmic.ObjectByValue; +import org.omg.CORBA.WStringValueHelper; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.MARSHAL; + +public class SerializationTest extends test.Test +{ + private JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + private boolean first = true ; + + private void test( String name ) { + if (first) { + first = false ; + } else { + helper.pass() ; + } + + helper.start( name ) ; + } + + public void run() + { + + try { + Properties orbProps = new Properties() ; + orbProps.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + orbProps.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton" ) ; + org.omg.CORBA.ORB orb = + org.omg.CORBA.ORB.init(getArgsAsArgs(),orbProps); + + BitSet _bitset; + + _bitset = new BitSet(64); + _bitset.set(10); + _bitset.set(20); + _bitset.set(30); + _bitset.set(40); + _bitset.set(50); + _bitset.set(60); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(_bitset); + ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream(baos.toByteArray())); + BitSet __bitset = (BitSet)ois.readObject(); + + + org.omg.CORBA_2_3.portable.OutputStream sos = + (org.omg.CORBA_2_3.portable.OutputStream)orb.create_output_stream(); + + ((org.omg.CORBA_2_3.ORB)orb).register_value_factory(DateHelper.id(), + new DateDefaultFactory()); + +// Start of writing phase: + + test( "writeDate" ) ; + javax.rmi.CORBA.serialization.Date date = DateHelper.create__(orb); + DateHelper.write(sos, date); + + test( "writeStock" ) ; + Stock stocks[] = new Stock[2]; + stocks[0] = new StockImpl("IBM"); + stocks[1] = StockHelper.create(orb, "Sun"); + seq1_StockHelper.write(sos, stocks); + + test( "writeMARSHAL" ) ; + SystemException sex = new MARSHAL("dummy exception", 37, + CompletionStatus.COMPLETED_MAYBE); + sos.write_value(sex); + + test( "writeString" ) ; + String helloString = "Hello world!"; + WStringValueHelper.write (sos, helloString); + + test( "writeIDLValue" ) ; + IDLValue idlv = new IDLValue(); + sos.write_value(idlv); + + test( "writeGraph" ) ; + Graph graph = new Graph("This", + new Graph("is", + new Graph("a", + new Graph("graph", + new Graph("object", + new Graph("test.", null)))))); + sos.write_value(graph); + + test( "writeDate2" ) ; + java.util.Date aDate = new java.util.Date(); + sos.write_value(aDate); + + test( "writeVector" ) ; + Vector vector1 = new Vector(); + sos.write_value(vector1); + + test( "writeStringValue" ) ; + sos.write_value("Hey you stream code!"); + + test( "writeVector2" ) ; + sos.write_value(vector1); + + test( "writeVector3" ) ; + Vector vector2 = new Vector(); + sos.write_value(vector2); + + test( "writeNotSerializableChild" ) ; + NotSerializableChild notser = new NotSerializableChild(); + sos.write_value(notser); + + test( "writeIsSerializable" ) ; + IsSerializable isser = new IsSerializable("Hey IBM!"); + sos.write_value(isser); + + test( "writeClass" ) ; + Class clazz = java.util.Hashtable.class; + sos.write_value(clazz); + + test( "writeString2" ) ; + sos.write_value("I5 X1"); + + test( "writeString3" ) ; + sos.write_value("I6 X2"); + + test( "writeBoolean" ) ; + sos.write_boolean(true); + + test( "writeEmptyString" ) ; + sos.write_value(""); + + test( "writeOBJV2" ) ; + TestOBV2 tobv2 = new TestOBV2(); + sos.write_value(tobv2); + + test( "writeArrayString" ) ; + String names[] = {"Alpha","Beta","Charlie"}; + double percents[] = {0.5,0.7}; + BudgetSummary summary = new BudgetSummary(2, names, percents); + sos.write_value(summary); + + test( "writeOctet" ) ; + byte b = (byte)0xBA; + sos.write_octet(b); + + test( "writeLong" ) ; + sos.write_long(45); + + test( "writeWString" ) ; + String idlString = "An idl test string"; + sos.write_wstring(idlString); + + test( "writeStringAsValue" ) ; + String str1 = new String("Hello, World!"); + sos.write_value(str1); + + test( "writeNullValue" ) ; + sos.write_value(null); + + test( "writeException" ) ; + Exception exception = new Exception("Test Exception"); + sos.write_value(exception); + + test( "writeString4" ) ; + String str2 = new String("Corvettes Rule!"); + sos.write_value(str2); + + test( "writeAliasedStringAsValue" ) ; + String str3 = str2; + sos.write_value(str3); + + test( "writeCustomObject1" ) ; + OBVTestObjectCustom obvc = new OBVTestObjectCustomImpl(); + sos.write_value(obvc); + + test( "writeCustomObject2" ) ; + OBVTestObjectCustomHelper.write(sos, obvc); + + test( "writeCustomObject3" ) ; + sos.write_value(obvc); + + test( "writeCustomObject4" ) ; + OBVTestObjectCustom obvc2 = new OBVTestObjectCustomImpl(); + OBVTestObjectCustomHelper.write(sos, obvc2); + + test( "writeObjectOne" ) ; + OBVTestObjectOne obv1 = new OBVTestObjectOneImpl(); + OBVTestObjectOneHelper.write(sos, obv1); + + test( "writeObjectShared" ) ; + OBVTestObjectOne obv1Shared = obv1; + sos.write_value(obv1Shared); + + test( "writeObjectValue2" ) ; + OBVTestObjectOne obv2 = new OBVTestObjectOneImpl(); + sos.write_value(obv2); + + // Test multiple streams open at once (tests pooling) + test( "writeMultipleStreams" ) ; + org.omg.CORBA_2_3.portable.OutputStream sos2 = + (org.omg.CORBA_2_3.portable.OutputStream)orb.create_output_stream(); + sos2.write_value(str1); + sos2.write_value(obv1); + + test( "writeFloat" ) ; + Float f = new Float(1.23); + sos.write_value(f); + + test( "writeComplexTestObjectOne" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectOne test1 = + new javax.rmi.CORBA.serialization.ComplexTestObjectOne(); + sos.write_value(test1); + + test( "writeComplexTestObjectTwo" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectTwo test2 = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwo(); + sos.write_value(test2); + + test( "writeComplexTestObjectTwoSubclass" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass test2subclass = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass(); + sos.write_value(test2subclass); + + test( "writeComplexTestObjectTwoSubclassDefaults" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults test2subclassDefaults = + new javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults(); + sos.write_value(test2subclassDefaults); + + test( "writeComplexTestObjectTwoSubclassDelta" ) ; + ComplexTestObjectTwoDelta delta2 = new ComplexTestObjectTwoDelta(); + sos.write_value(delta2); + + test( "writeEmptyTestObject" ) ; + javax.rmi.CORBA.serialization.EmptyTestObject testEmptyA= + new javax.rmi.CORBA.serialization.EmptyTestObject(); + sos.write_value(testEmptyA); + + test( "writeEmptyTestObject2" ) ; + javax.rmi.CORBA.serialization.EmptyTestObject testEmptyB= + new javax.rmi.CORBA.serialization.EmptyTestObject(); + sos.write_value(testEmptyB); + + test( "writeComplexTestObjectOne" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectOne test1b = + new javax.rmi.CORBA.serialization.ComplexTestObjectOne(); + sos.write_value(test1b); + + test( "writeDouble" ) ; + Double d = new Double(3.5); + sos.write_value(d); + + test( "writeComplexTestObjectThree" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectThree test3 = + new javax.rmi.CORBA.serialization.ComplexTestObjectThree(); + sos.write_value(test3); + + test( "writeComplexTestObjectFour" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectFour test4 = + new javax.rmi.CORBA.serialization.ComplexTestObjectFour(); + sos.write_value(test4); + + test( "writeProperties" ) ; + java.util.Properties props = new java.util.Properties(); + props.put("Key1","Value1"); + sos.write_value(props); + + test( "writeIntArray" ) ; + // Test arrays + int anIntArray[] = {9,8,7}; + sos.write_value(anIntArray); + + test( "writeSharedRefArray" ) ; + Object aSharedRefsArray[] = { testEmptyA, test1b, anIntArray }; + sos.write_value( aSharedRefsArray ); + + // Check single dimensional primitive array... + + test( "writeIntArray2" ) ; + int[] array1 = {0,5,7,9,11,13}; + sos.write_value(array1); + + + // Check 2 dimensional primitive array... + + test( "writeLongArrayArray" ) ; + long[][] array2 = { + {9,8,7,6,1}, + {18,4,6}, + {0,5,7,9,11,13} + }; + sos.write_value(array2); + + test( "writeObjectArray" ) ; + // Recursive array references + Object recursiveArray[] = {null, "Hello", null, null}; + recursiveArray[0] = recursiveArray; + recursiveArray[2] = recursiveArray; + recursiveArray[3] = recursiveArray; + sos.write_value(recursiveArray); + + test( "writeShortArrayArrayArray" ) ; + // Check 3 dimensional primitive array... + short[][][] dim3 = { + { + {0,8,7,6,1}, + {1,5,7,13}, + {2,4,6}, + }, + { + {3,4,10}, + {4,5,7,9,13} + }, + { + {5,4,6}, + {6,5,8,9,11,13}, + {7,8,7,6,1}, + {8,8,7,6,9}, + }, + }; + sos.write_value(dim3); + + test( "writeObjectArray" ) ; + // Check single dimensional object array... + + ObjectByValue[] array3 = { + new ObjectByValue(5,10,"a","f"), + new ObjectByValue(6,11,"b","g"), + new ObjectByValue(7,12,"c","h"), + new ObjectByValue(8,13,"d","i"), + new ObjectByValue(9,14,"e","j"), + }; + sos.write_value(array3); + + // Check multi dimensional object array... + + test( "writeObjectArrayArray" ) ; + ObjectByValue[][] array4 = { { + new ObjectByValue(0,10,"a","g"), + new ObjectByValue(0,11,"b","h"), + new ObjectByValue(0,12,"c","i"), + }, + { + new ObjectByValue(1,13,"d","j"), + new ObjectByValue(1,14,"e","k"), + }, + { + new ObjectByValue(2,15,"f","l"), + } + }; + + sos.write_value(array4); + + // Anys + test( "writeAny" ) ; + ComplexTestObjectXXX xxx = new ComplexTestObjectXXX(); + sos.write_value(xxx); + + //System.out.println("offset = " + ((com.sun.corba.ee.impl.encoding.CDROutputStream)sos).get_offset()); + //System.out.println("countit = " + ((com.sun.corba.ee.impl.encoding.CDROutputStream)sos).countit); + + /***************************************************************/ + /*********************** READ DATA BACK IN *********************/ + /***************************************************************/ + + test( "createInputStream" ) ; + org.omg.CORBA_2_3.portable.InputStream sis = + (org.omg.CORBA_2_3.portable.InputStream)sos.create_input_stream(); + + test( "readDate" ) ; + javax.rmi.CORBA.serialization.Date _date = (javax.rmi.CORBA.serialization.Date) + DateHelper.read(sis); + + test( "readStocks" ) ; + Stock _stocks[] = (Stock[])seq1_StockHelper.read(sis); + + test( "readSystemException" ) ; + SystemException _sex = (SystemException)sis.read_value(); + if (!(_sex.getMessage().equals(sex.getMessage())) || + _sex.minor != sex.minor || + _sex.completed != sex.completed) + throw new Error("Hello String failed!"); + + test( "readHelloString" ) ; + String _helloString = (String)WStringValueHelper.read(sis); + if (!helloString.equals(_helloString)) + throw new Error("Hello String failed!"); + + test( "readIdlValue" ) ; + IDLValue _idlv = (IDLValue)sis.read_value(); + if (!idlv.equals(_idlv)) + throw new Error("IDLValue test failed!"); + + test( "readGraph" ) ; + Graph _graph = (Graph)sis.read_value(); + if (!graph.toString().equals(_graph.toString())) { + System.out.println("graph = " + graph); + System.out.println("_graph = " + _graph); + throw new Error("Graph test failed!"); + } + + test( "readData2" ) ; + java.util.Date _aDate = + (java.util.Date)sis.read_value(); + + test( "readVector" ) ; + Vector _vector1 = (Vector)sis.read_value(); + + sis.read_value(); + + test( "readSharedVector" ) ; + Vector _sharedVector1 = (Vector)sis.read_value(); + if (_vector1 != _sharedVector1) + throw new Error("Shared vectors failed! (vectors not shared!)"); + + test( "readUnsharedVector" ) ; + Vector _vector2 = (Vector)sis.read_value(); + if (_vector1 == _vector2) + throw new Error("Unshared vectors failed! (vectors are shared!)"); + + test( "readNotSerializableChild" ) ; + NotSerializableChild _notser = (NotSerializableChild)sis.read_value(); + if (!notser.equals(_notser)) + throw new Error("NotSerializableChild test failed!"); + + test( "readIsSerializable" ) ; + IsSerializable _isser = (IsSerializable)sis.read_value(); + if (!isser.equals(_isser)) + throw new Error("IsSerializable test failed!"); + + test( "readClass" ) ; + Class _clazz = (Class)sis.read_value(); + if (!clazz.equals(_clazz)) + throw new Error("Test Clazz failed!"); + + test( "readValue1" ) ; + sis.read_value(); + + test( "readValue2" ) ; + sis.read_value(); + + test( "readBoolean" ) ; + sis.read_boolean(); + + test( "readValue3" ) ; + sis.read_value(); + + test( "readValue4" ) ; + TestOBV2 _tobv2 = (TestOBV2)sis.read_value(); + if (!tobv2.equals(_tobv2)) + throw new Error("TestOBV2 failed!"); + + test( "readBudgetSummary" ) ; + BudgetSummary _summary = (BudgetSummary)sis.read_value(); + + test( "readOctet" ) ; + byte _b = sis.read_octet(); + if (b != _b) + throw new Error("Test byte failed!"); + + test( "readLong" ) ; + long l = sis.read_long(); + if (l != 45) + throw new Error("Test 1 failed!"); + + test( "readIdlString" ) ; + String _idlString = sis.read_wstring(); + if (!idlString.equals(_idlString)) + throw new Error("Test idlString failed!"); + + test( "readStringAsValue" ) ; + String _str1 = (String)sis.read_value(); + if (!str1.equals(_str1)) + throw new Error("Test str1 failed! : " + _str1); + + test( "readNullString" ) ; + String nullString = (String)sis.read_value(); + if (nullString != null) + throw new Error("Test nullString failed! : "); + + test( "readException" ) ; + Exception _exception = (Exception)sis.read_value(); + if (!_exception.getMessage().equals("Test Exception")) + throw new Error("Test Exception failed!"); + + test( "readString5" ) ; + String _str2 = (String)sis.read_value(); + if (!str2.equals(_str2)) + throw new Error("Test str2 failed!"); + + test( "readString6" ) ; + String _str3 = (String)sis.read_value(); + if (_str3 != _str2) + throw new Error("Test str3 failed!"); + + test( "readObjectCustom" ) ; + OBVTestObjectCustom _obvc = OBVTestObjectCustomHelper.read(sis); + if (!obvc.equals(_obvc)) + throw new Error("Test Custom OBV failed!"); + + test( "readObjectCustom2" ) ; + OBVTestObjectCustom _obvcshared2 = (OBVTestObjectCustom)sis.read_value(OBVTestObjectCustom.class); + if (_obvc != _obvcshared2) + throw new Error("Test Custom OBV2 shared 2 failed!"); + + test( "readObjectCustom3" ) ; + OBVTestObjectCustom _obvcshared1 = (OBVTestObjectCustom)sis.read_value(); + if (_obvc != _obvcshared1) + throw new Error("Test Custom OBV2 shared 1 failed!"); + + test( "readObjectCustom4" ) ; + OBVTestObjectCustom _obvc2 = OBVTestObjectCustomHelper.read(sis); + if (!obvc2.equals(_obvc2)) + throw new Error("Test Custom OBV2 failed!"); + test( "readObjectOne" ) ; + OBVTestObjectOne _obv1 = (OBVTestObjectOne)sis.read_value(); + if (!obv1.equals(_obv1)) + throw new Error("Test OBV1 failed!"); + + test( "readMultipleStreams" ) ; + // Test multiple streams open at once + org.omg.CORBA_2_3.portable.InputStream sis2 = + (org.omg.CORBA_2_3.portable.InputStream)sos2.create_input_stream(); + String _str1_sis2 = (String)sis2.read_value(); + if (!str1.equals(_str1_sis2)) + throw new Error("Test _str1_sis2 idlString failed!"); + + test( "readObjectOne2" ) ; + OBVTestObjectOne _obv1_sis2 = (OBVTestObjectOne)sis2.read_value(OBVTestObjectOne.class); + if (!obv1.equals(_obv1_sis2)) + throw new Error("Test sis2 OBV1 failed!"); + + test( "readObjectOne3" ) ; + OBVTestObjectOne _obv1Shared = OBVTestObjectOneHelper.read(sis); + if (_obv1 != _obv1Shared) + throw new Error("Test Shared References OBV1 failed!"); + + test( "readObjectOne4" ) ; + OBVTestObjectOne _obv2 = (OBVTestObjectOne)sis.read_value(); + if (!obv2.equals(_obv2)) + throw new Error("Test OBV2 failed!"); + + test( "readFloat" ) ; + Float _f = (Float)sis.read_value(); + if (!f.equals(_f)) + throw new Error("Test Float failed!"); + + test( "readComplexObjectOne" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectOne _test1 = + (javax.rmi.CORBA.serialization.ComplexTestObjectOne)sis.read_value(); + if (!test1.equals(_test1)) + throw new Error("FAILURE! Test1 Failed:"+_test1); + + test( "readComplexObjectTwo" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectTwo _test2 = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwo)sis.read_value(); + if (!test2.equals(_test2)) + throw new Error("FAILURE! Test2 Failed"); + + test( "readComplexObjectTwoSubclass" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass _test2subclass = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclass)sis.read_value(); + if (!test2subclass.equals(_test2subclass)) + throw new Error("FAILURE! Test2subclass Failed"); + + test( "readComplexObjectTwoDefaults" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults _test2subclassDefaults = + (javax.rmi.CORBA.serialization.ComplexTestObjectTwoSubclassDefaults)sis.read_value(); + if (!test2subclassDefaults.equals(_test2subclassDefaults)) + throw new Error("FAILURE! Test2subclassDefaults Failed"); + + test( "readComplexObjectTwoDelta" ) ; + ComplexTestObjectTwoDelta _delta2 = (ComplexTestObjectTwoDelta)sis.read_value(); + if (!delta2.equals(_delta2)) { + System.out.println("delta2 = " + delta2); + System.out.println("_delta2 = " + _delta2); + throw new Error("FAILURE! Delta2 Failed"); + } + + test( "readEmptyObject" ) ; + javax.rmi.CORBA.serialization.EmptyTestObject _testEmptyA = + (javax.rmi.CORBA.serialization.EmptyTestObject)sis.read_value(); + if (!testEmptyA.equals(_testEmptyA)) + throw new Error("FAILURE! TestEmptyA Failed"); + + test( "readEmptyObject2" ) ; + javax.rmi.CORBA.serialization.EmptyTestObject _testEmptyB = + (javax.rmi.CORBA.serialization.EmptyTestObject)sis.read_value(); + if (!testEmptyB.equals(_testEmptyB)) + throw new Error("FAILURE! TestEmptyB Failed"); + + test( "readComplexTestObjectOneAgain" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectOne _test1b = + (javax.rmi.CORBA.serialization.ComplexTestObjectOne)sis.read_value(); + if (!test1b.equals(_test1b)) + throw new Error("FAILURE! Test1b Failed"); + + test( "readDouble" ) ; + Double _d = (Double)sis.read_value(); + if (!d.equals(_d)) + throw new Error("FAILURE! d Failed"); + + test( "readComplexObjectThree" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectThree _test3 = + (javax.rmi.CORBA.serialization.ComplexTestObjectThree)sis.read_value(); + if (!test3.equals(_test3)) + throw new Error("FAILURE! Test3 Failed"); + + test( "readComplexObjectFour" ) ; + javax.rmi.CORBA.serialization.ComplexTestObjectFour _test4 = + (javax.rmi.CORBA.serialization.ComplexTestObjectFour)sis.read_value(); + if (!test4.equals(_test4)) + throw new Error("FAILURE! Test4 Failed"); + + test( "readProperties" ) ; + java.util.Properties _props = (java.util.Properties)sis.read_value(); + if (!_props.toString().equals(props.toString())) + throw new Error("FAILURE! props Failed"); + + + test( "readIntArray" ) ; + int _anIntArray[] = (int[])sis.read_value(); + if ((_anIntArray[0] != anIntArray[0]) || + (_anIntArray[1] != anIntArray[1]) || + (_anIntArray[2] != anIntArray[2])) + throw new Error("FAILURE! anIntArray Failed"); + + test( "readObjectArray" ) ; + Object _aSharedRefsArray[] = (Object[])sis.read_value(); + if ((_aSharedRefsArray[0] != _testEmptyA) || + (_aSharedRefsArray[1] != _test1b) || + (_aSharedRefsArray[2] != _anIntArray)) + throw new Error("FAILURE! aSharedRefsArray[] == Failed"); + + test( "readIntArray2" ) ; + int[] array1Echo = (int[])sis.read_value(); + for (int i = 0; i < array1.length; i++) { + if (array1[i] != array1Echo[i]) { + throw new Exception("HelloTest: echoArray (int[]) failed"); + } + } + + test( "readLongArrayArray" ) ; + long[][] array2Echo = (long[][])sis.read_value(); + for (int i = 0; i < array2.length; i++) { + for (int j = 0; j < array2[i].length; j++) { + if (array2[i][j] != array2Echo[i][j]) { + throw new Exception("HelloTest: echoArray (int[][]) failed"); + } + } + } + + test( "readRecursizeObjectArray" ) ; + // Recursive array references + Object recursiveArrayEcho[] = (Object[])sis.read_value(); + if ((recursiveArrayEcho[0] != recursiveArrayEcho) || + (recursiveArrayEcho[2] != recursiveArrayEcho) || + (recursiveArrayEcho[3] != recursiveArrayEcho) || + (!((String)recursiveArrayEcho[1]).equals("Hello"))) + throw new Exception("RecursiveArray test failed!"); + + test( "readShortArrayArrayArray" ) ; + short[][][] dim3Echo = (short[][][])sis.read_value(); + for (int i = 0; i < dim3.length; i++) { + for (int j = 0; j < dim3[i].length; j++) { + for (int k = 0; k < dim3[i][j].length; k++) { + if (dim3[i][j][k] != dim3[i][j][k]) { + throw new Exception("HelloTest: echoArray (short[][][]) failed"); + } + } + } + } + + test( "readObjectByValueArray" ) ; + ObjectByValue[] array3Echo = (ObjectByValue[])sis.read_value(); + for (int i = 0; i < array3.length; i++) { + if (!array3[i].equals(array3Echo[i])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[]) failed"); + } + } + + test( "readObjectByValueArrayArray" ) ; + ObjectByValue[][] array4Echo = (ObjectByValue[][])sis.read_value(); + for (int i = 0; i < array4.length; i++) { + for (int j = 0; j < array4[i].length; j++) { + if (!array4[i][j].equals(array4Echo[i][j])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[][]) failed"); + } + } + } + + // Anys + test( "readAny" ) ; + ComplexTestObjectXXX _xxx = (ComplexTestObjectXXX)sis.read_value(); + if (!_xxx.equals(xxx)) + throw new Error("Any test using xxx failed!"); + } catch (Throwable e) { + helper.fail( e ) ; + status = new Error(e.getMessage()); + e.printStackTrace(); + } finally { + if (!first) + helper.pass() ; + + helper.done() ; + } + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Stock.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Stock.java new file mode 100644 index 000000000..f972fd66f --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/Stock.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* Stock.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from org/omg/boxedRMI/examples/stock/seq1_Stock.idl +* Friday, May 14, 1999 12:57:04 o'clock PM EDT +*/ + +public abstract class Stock implements org.omg.CORBA.portable.StreamableValue +{ + protected float current = (float)0; + protected String symbol = null; + + private static String[] _truncatable_ids = { + StockHelper.id () + }; + + public String[] _truncatable_ids() { + return _truncatable_ids; + } + + public abstract float update (); + + public void _read (org.omg.CORBA.portable.InputStream istream) + { + this.current = istream.read_float (); + this.symbol = org.omg.CORBA.WStringValueHelper.read (istream); + } + + public void _write (org.omg.CORBA.portable.OutputStream ostream) + { + ostream.write_float (this.current); + org.omg.CORBA.WStringValueHelper.write (ostream, this.symbol); + } + + public org.omg.CORBA.TypeCode _type () + { + return StockHelper.type (); + } + +} // class Stock diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockDefaultFactory.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockDefaultFactory.java new file mode 100644 index 000000000..f4eadf8fb --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockDefaultFactory.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class StockDefaultFactory implements StockValueFactory { + + public Stock create (String arg0) + { + return new StockImpl (arg0); + } + + public java.io.Serializable read_value (org.omg.CORBA_2_3.portable.InputStream is) + { + return is.read_value(new StockImpl ()); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockHelper.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockHelper.java new file mode 100644 index 000000000..a830de177 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockHelper.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* gen/examples/stock/StockHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from examples/stock/Stock.idl +* 02 June 1999 21:47:31 o'clock GMT+00:00 +*/ + +abstract public class StockHelper +{ + private static String _id = "RMI:javax.rmi.CORBA.serialization.Stock:B60458ECD6E4794E:CCA70DAA84257A80"; + + public static void insert (org.omg.CORBA.Any a, Stock that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static Stock extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + // ValueMember instance for current + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_float); + _members0[0] = new org.omg.CORBA.ValueMember ("current", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + // ValueMember instance for symbol + _tcOf_members0 = org.omg.CORBA.WStringValueHelper.type (); + _members0[1] = new org.omg.CORBA.ValueMember ("symbol", + org.omg.CORBA.WStringValueHelper.id (), + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PRIVATE_MEMBER.value); + __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "Stock", org.omg.CORBA.VM_NONE.value, null, _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static Stock read (org.omg.CORBA.portable.InputStream istream) + { + return (Stock)((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, Stock value) + { + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ()); + } + + + public static Stock create (org.omg.CORBA.ORB _orb, String name) + { + try { + StockValueFactory _factory = (StockValueFactory) + ((org.omg.CORBA_2_3.ORB) _orb).lookup_value_factory(id()); + return _factory.create (name); + } catch (ClassCastException _ex) { + throw new org.omg.CORBA.BAD_PARAM (); + } + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockImpl.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockImpl.java new file mode 100644 index 000000000..2354f0445 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockImpl.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +//nk +import java.util.Random; +//nk + +public class StockImpl extends Stock +{ + //nk + private static Random random = new Random(); + private final static float MAX_VALUE = 67; + //nk + + public StockImpl (String arg0) + { + //nk + symbol = arg0; + if (symbol.equals("Sun")) { + current = 30.0f; + } else { + // generate random stock price between 20 and 60 + current = (float)(random.nextInt(40) + 20); + } + //nk + } + + StockImpl() {} + + public float update() + { + //nk + float change = ((float)(random.nextGaussian() * 1.0)); + if (symbol.equals("Sun") && current < MAX_VALUE - 5) + change = Math.abs(change); // what did you expect? + + float newCurrent = current + change; + + // don't allow stock price to step outside range + if (newCurrent < 0 || newCurrent > MAX_VALUE) + change = 0; + + current += change; + + return change; + //nk + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockValueFactory.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockValueFactory.java new file mode 100644 index 000000000..fa64ca716 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/StockValueFactory.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public interface StockValueFactory extends org.omg.CORBA.portable.ValueFactory +{ + Stock create (String arg0); +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/TestOBV.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/TestOBV.java new file mode 100644 index 000000000..a8f1c9ef9 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/TestOBV.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +public class TestOBV implements java.io.Serializable { + public int foo; +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/TestOBV2.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/TestOBV2.java new file mode 100644 index 000000000..92e405394 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/TestOBV2.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +import java.util.*; +import java.io.*; + +public class TestOBV2 extends TestOBV implements java.io.Serializable { + public int bar; + public static int foo = 1; + public TestOBV2 self = null; + public static final int FOO = 3; + public TestOBV2 arrayOfThis[]; + + public TestOBV2(){ + super(); + self = this; + bar = new Random().nextInt(); + arrayOfThis = new TestOBV2[3]; + arrayOfThis[0] = null; + arrayOfThis[1] = this; + arrayOfThis[2] = null; + } + + public boolean equals (Object o){ + try + { + TestOBV2 target = (TestOBV2)o; + return ((target != null) && + (target.self == target) && + (target.arrayOfThis != null) && + (target.arrayOfThis[0] == null) && + (target.arrayOfThis[1] == target) && + (target.arrayOfThis[0] == null) && + (target.bar == bar) && + (target.foo == foo) && + (target.FOO == FOO)); + } + catch(Throwable t) + { + return false; + } + } +} diff --git a/functional-tests/src/test/java/javax/rmi/CORBA/serialization/seq1_StockHelper.java b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/seq1_StockHelper.java new file mode 100644 index 000000000..0850dab79 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/CORBA/serialization/seq1_StockHelper.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA.serialization; + +/** +* org/omg/boxedRMI/examples/stock/seq1_StockHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from org/omg/boxedRMI/examples/stock/seq1_Stock.idl +* 02 June 1999 21:40:11 o'clock GMT+00:00 +*/ + +public final class seq1_StockHelper implements org.omg.CORBA.portable.BoxedValueHelper +{ + private static String _id = "RMI:[Ljavax.rmi.CORBA.serialization.Stock;:B60458ECD6E4794E:CCA70DAA84257A80"; + + private static seq1_StockHelper _instance = new seq1_StockHelper (); + + public seq1_StockHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, Stock[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static Stock[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + __typeCode = StockHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_value_box_tc (_id, "seq1_Stock", __typeCode); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static Stock[] read (org.omg.CORBA.portable.InputStream istream) + { + if (!(istream instanceof org.omg.CORBA_2_3.portable.InputStream)) { + throw new org.omg.CORBA.BAD_PARAM(); } + return (Stock[]) ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (_instance); + } + + public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream) + { + Stock[] tmp; + int _len0 = istream.read_long (); + tmp = new Stock[_len0]; + for (int _o1 = 0;_o1 < tmp.length; ++_o1) + tmp[_o1] = StockHelper.read (istream); + return (java.io.Serializable) tmp; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, Stock[] value) + { + if (!(ostream instanceof org.omg.CORBA_2_3.portable.OutputStream)) { + throw new org.omg.CORBA.BAD_PARAM(); } + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, _instance); + } + + public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable value) + { + if (!(value instanceof Stock[])) { + throw new org.omg.CORBA.MARSHAL(); } + Stock[] valueType = (Stock[]) value; + ostream.write_long (valueType.length); + for (int _i0 = 0;_i0 < valueType.length; ++_i0) + StockHelper.write (ostream, valueType[_i0]); + } + + public String get_id () + { + return _id; + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/PortableContext.java b/functional-tests/src/test/java/javax/rmi/PortableContext.java new file mode 100644 index 000000000..9e9f440b4 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/PortableContext.java @@ -0,0 +1,939 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; +import sun.rmi.registry.RegistryImpl; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import java.io.IOException; +import java.rmi.RMISecurityManager; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.registry.Registry; +import java.rmi.server.UnicastRemoteObject; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; + +/** + * PortableContext is a convenience class for rmi-iiop programs which simplifies + * both server and client initialization. Server-side features include: + *
    + *
  • A {@link #main(java.lang.String[]) main} which provides: + *
      + *
    • Command-line initialization of servant(s). + *
    • Automatic selection of runtime (RMI or IIOP). + *
    • Automatic invocation of the appropriate name server (local host + * only). + *
    • Automatic publication of servants to the name server. + *
    + *
  • {@link #startServant(java.lang.String, boolean) startServant methods} (used by main) are + * available for direct use from within Applications. + *
  • Context information for all {@link PortableContext.Servant servant} instances. + *
+ * + * For example, to startup and publish 'HelloServant' under the name "myHello" with + * the name server running on the local host and port: + *
+ *    java javax.rmi.PortableContext myHello=HelloServant
+ * 
+ * To launch the name server if it is not running, add the -startNameServer option: + *
+ *    java javax.rmi.PortableContext myHello=HelloServant -startNameServer
+ * 
+ * Client-side features include: + *
    + *
  • {@link #lookup(java.lang.String,java.lang.Class) lookup methods} to retrieve published objects. + *
  • Context information for all {@link PortableContext.Client client} instances. + *
+ * + * Client code can get access to published servants using the {@link #lookup(java.lang.String,java.lang.Class) lookup} or + * {@link #lookupClient(java.lang.String,java.lang.Class) lookupClient} methods. For example, to lookup a servant which + * implements the 'Hello' interface, is running on IIOP, and has been published as 'myHello' with + * default host and port: + *
+ *    Hello ref = (Hello) PortableContext.lookup("iiop://myHello",Hello.class);
+ * 
+ *

+ * + *
Note + * This class does not (yet) support Applets. There are two problems: + *
    + *
  1. Resource Consumption. Currently, there is a static cache of PortableContext + * instances (to minimize resource use), which works well for applications. For applets, + * the same process is re-used for all applets, and therefore the cache does not get cleaned + * up. + *
  2. Security. Applets could get a context from a previous applet, and therefore + * have access to the ORB/InitialContext, etc. + *
+ * One solution (that doesn't throw out the entire design) is to require that the + * cache (a Hashtable) be passed in by the applet/application, rather than be a static. + * It's not as convenient, but does solve both problems. + *
+ * @version 1.0, 6/23/98 + * @author Bryan Atsatt + */ +public class PortableContext { + + public static final int RMI_RUNTIME = 0; + public static final int IIOP_RUNTIME = 1; + + + private ORB orb = null; + private InitialContext nameContext = null; + private String nameServerHost = null; + private int nameServerPort = 0; + private int runtime; + private String key = null; + private boolean startNameServer = false; + private static boolean is12VM = true; + + private static Hashtable cache = new Hashtable(); + private static final String HANDSHAKE = "Ready."; + + //____________________________________________________________________________________________ + // API Methods + //____________________________________________________________________________________________ + + /** + * Lookup a remote object. The clientURL structure is: + *

+     *   rmi|iiop://[host][:port]/publishedName
+     * 
+ * So, for example, here are various ways to specify 'bob': + *
+     *   rmi://bob             (RMIRegistry, this host, default port)
+     *   rmi://myHost/bob      (RMIRegistry, myHost, default port)
+     *   iiop://myHost:197/bob (TransientNameServer, myHost, port 197)
+     *   iiop://:1099/bob      (TransientNameServer, this host, port 1099)
+     * 
+ * Assuming a servant implements the 'Hello' interface, is running on IIOP, and has + * been published as 'bob' with default host and port: + *
+     *    Hello ref = (Hello) PortableContext.lookup("iiop://bob",Hello.class)
+     * 
+ * @param clientURL A url naming the client. + * @param narrowTo The Class of the interface to which to narrow the remote object. + * @exception NamingException Thrown if lookup fails. + * @see #lookupClient(java.lang.String, java.lang.Class) + */ + public static Object lookup (String clientURL, Class narrowTo) throws NamingException { + PortableContext.Client client = getClient(clientURL); + return PortableRemoteObject.narrow(client.client,narrowTo); + } + + /** + * Lookup a remote object. Same as {@link #lookup(java.lang.String,java.lang.Class) lookup} except that it + * returns a Client instance. + * @param clientURL A url naming the client. + * @param narrowTo The Class of the interface to which to narrow the remote object. + * @exception NamingException Thrown if lookup fails. + * @see #lookup(java.lang.String, java.lang.Class) + */ + public static Client lookupClient (String clientURL, Class narrowTo) throws NamingException { + PortableContext.Client client = getClient(clientURL); + PortableRemoteObject.narrow(client.client,narrowTo); + return client; + } + + /** + * Start up one or more servants. Supported arguments: + *
+     *     [options] servantSpec [servantSpec...]
+     * 
+ * + * The servantSpec can be either of two forms: + *
+     *   Simple form:   [publishname=]class
+     *   URL form:      servant://[host][:port]/class[?name=publishname]
+     * 
+ * So, for example, here are various servantSpecs for the acme.Dynamite servant: + *
+     *   acme.Dynamite
+     *   bob=acme.Dynamite
+     *
+     *   servant://acme.Dynamite
+     *   servant://acme.Dynamite?name=bob
+     *   servant://myHost/acme.Dynamite?name=bob
+     *   servant://myHost:45/acme.Dynamite?name=bob
+     *   servant://myHost/acme.Dynamite
+     *   servant://myHost:45/acme.Dynamite
+     *   servant://:45/acme.Dynamite
+     * 
+ * If 'publishname' is not specified, the servant is not published to the name + * server. + *

+ * + *
Note + * The JNDI Context.rebind() method is used to publish servants. If bind semantics + * are required, this main cannot be used. Instead, write a main which uses + * {@link #startServant(java.lang.String, boolean) startServant} directly, and pass servantSpecs which + * do not specify a name, and do the bind in your code: + *
+     *    Servant it = PortableContext.startServant(spec,false);
+     *    Context nameContext = it.getContext().getNameContext();
+     *    nameContext.bind(name,it.servant);
+     * 
+ *
+ * The supported options are: + *

+     *   -host nameServerHost    The host name to use if not specified in servantSpec.
+     *   -port nameServerPort    The port to use if not specified in servantSpec.
+     *   -startNameServer        Start the name server if needed. Not allowed with -host option.
+     *   -verbose                Print message describing each started servant.
+     * 
+ * @param args See description above. + * @see #startServant + */ + public static void main (String[] args) { + + String hostOption = null; + String portOption = null; + boolean startNameServer = false; + boolean verbose = false; + int argLen = args.length; + + // Scan args for options... + + int found = 0; + for (int i = 0; i < argLen; i++) { + if (args[i].equalsIgnoreCase("-host")) { + args[i] = null; + hostOption = args[++i]; + args[i] = null; + found++; + } else if (args[i].equalsIgnoreCase("-port")) { + args[i] = null; + portOption = args[++i]; + args[i] = null; + found++; + } else if (args[i].equalsIgnoreCase("-startNameServer")) { + args[i] = null; + startNameServer = true; + found++; + } else if (args[i].equalsIgnoreCase("-verbose")) { + args[i] = null; + verbose = true; + found++; + } else if (args[i].startsWith("-")) { + usage(); + } + } + + // Check incompatible arguments... + + if (hostOption != null && startNameServer) { + System.out.println("\nCannot start a name server on another host. If '" + hostOption + "'"); + System.out.println("is the local host, just remove the -host argument."); + System.exit(1); + } + + boolean haveJRMP = false; // _REVISIT_ REMOVE + + try { + if (argLen > found) { + + // Now process servants... + + for (int i = 0; i < argLen; i++) { + if (args[i] != null) { + + Servant servant = startServant(args[i],hostOption,portOption,startNameServer); + if (servant.getContext().getRuntime() == RMI_RUNTIME) haveJRMP = true; // _REVISIT_ REMOVE + + if (verbose) { + String env = servant.getContext().getRuntime() == IIOP_RUNTIME ? "IIOP" : "RMI"; + String published = servant.servantName != null ? "and published as " + servant.servantName : ""; + System.out.println(servant.servantClass + " started on " + env + " runtime " + published + "."); + } + } + } + + System.out.println(HANDSHAKE); + + // If we don't have any JRMP servants, we gotta do a wait here + // _REVISIT_ REMOVE + + if (!haveJRMP) { + + // Wait forever... + + Object sync = new Object(); + synchronized (sync) { sync.wait(); } + } + } else { + usage(); + } + } catch (Throwable e) { + System.out.println("Caught " + e); + System.exit(1); + } + } + + /** + * Startup a servant, using a name server running on the local host with + * default port. + * @param servantSpec The servant specification. + * @param startNameServer True if the name server should be started if needed. + * @exception ClassNotFoundException If servant class cannot be found. + * @exception InstantiationException If servant class cannot be instantiated. + * @exception IllegalAccessException If servant class initializer not accessible. + * @exception NamingException If an error occurs when publishing the servant. + * @see #startServant(java.lang.String, java.lang.String, java.lang.String, boolean) + */ + public static Servant startServant(String servantSpec, + boolean startNameServer) + throws ClassNotFoundException, + InstantiationException, + IllegalAccessException, + RemoteException, + NamingException { + return startServant(servantSpec,null,null,startNameServer); + } + + /** + * Startup a servant. + * @param servantSpec The servant specification. + * @param defaultHost The name server host to use if not specified in servantSpec. May be + * null (local host). + * @param defaultPort The name server port to use if not specified in servantSpec. May be + * null (use default for runtime). + * @param startNameServer True if the name server should be started if needed. + * @exception ClassNotFoundException If servant class cannot be found. + * @exception InstantiationException If servant class cannot be instantiated. + * @exception IllegalAccessException If servant class initializer not accessible. + * @exception NamingException If an error occurs when publishing the servant. + * @see #startServant(java.lang.String, boolean) + */ + public static Servant startServant( String servantSpec, + String defaultHost, + String defaultPort, + boolean startNameServer) + throws ClassNotFoundException, + InstantiationException, + IllegalAccessException, + RemoteException, + NamingException { + + + int runtime = -1; + String host = defaultHost; + String port = defaultPort; + String servantClass = null; + String servantName = null; + Remote servantInstance = null; + + // Parse the servant spec. Is it a url style spec? + + if (servantSpec.startsWith("servant://")) { + + // Yep. + + int end = servantSpec.length(); + int nameOffset = servantSpec.indexOf("?name="); + if (nameOffset >= 0) { + servantName = servantSpec.substring(nameOffset+6); + end = nameOffset; + } + + int slashOffset = servantSpec.indexOf('/',10); + if (slashOffset >= 0) { + servantClass = servantSpec.substring(slashOffset+1,end); + end = slashOffset; + + int portOffset = servantSpec.indexOf(':',10); + if (portOffset >= 0) { + host = servantSpec.substring(10,portOffset); + port = servantSpec.substring(portOffset+1,end); + } else { + host = servantSpec.substring(10,slashOffset); + } + } else { + servantClass = servantSpec.substring(10,end); + } + } else { + + // No, it's a simple spec... + + int offset = servantSpec.indexOf('='); + if (offset < 0) { + servantClass = servantSpec; + } else { + servantName = servantSpec.substring(0,offset); + servantClass = servantSpec.substring(offset+1); + } + } + + // Do some cleanup... + + if (host != null && host.length() == 0) host = null; + if (port != null && port.length() == 0) port = null; + + // Instantiate the servant... + + Class theClass = Class.forName(servantClass); + servantInstance = (Remote) theClass.newInstance(); + + // Determine runtime... + + if (findTie(servantInstance) == null) { + runtime = RMI_RUNTIME; + } else { + runtime = IIOP_RUNTIME; + } + + // Make sure we have a valid port number for the name service... + + if (port == null) { + + // Use default port... + + port = runtime == IIOP_RUNTIME ? "900" : Integer.toString(java.rmi.registry.Registry.REGISTRY_PORT); + } + + // Get a context... + + PortableContext context = getContext(runtime,host,port,startNameServer); + + // Create and start the servant... + + Servant servant = context.startServant(servantClass,servantName,servantInstance); + + return servant; + } + + + /** + * Return the runtime in use by this context. + */ + public int getRuntime() {return runtime;} + + /** + * Return the ORB in use by this context. Will be null if runtime == RMI_RUNTIME. + */ + public ORB getORB () {return orb;} + + /** + * Return the name context in use by this context. + */ + public Context getNameContext() {return nameContext;} + + /** + * Return the name server host in use by this context. Will be null if local host. + */ + public String getNameServerHost() {return nameServerHost;} + + /** + * Return the name server port in use by this context. + */ + public int getNameServerPort() {return nameServerPort;} + + //____________________________________________________________________________________________ + // Implementation Methods + //____________________________________________________________________________________________ + + // REMIND: Need support for Applet. + + protected PortableContext (int runtime, boolean startNameServer) throws NamingException { + this.runtime = runtime; + this.startNameServer = startNameServer; + init(); + } + + protected PortableContext (String nameServerHost, + String nameServerPort, + int runtime, + boolean startNameServer) throws NamingException { + + this.runtime = runtime; + this.startNameServer = startNameServer; + + if (nameServerHost != null && nameServerHost.length() > 0) { + this.nameServerHost = nameServerHost; + } + + if (nameServerPort != null && nameServerPort.length() > 0) { + this.nameServerPort = Integer.parseInt(nameServerPort); + } + + init(); + } + + + protected static Client getClient( String clientSpec) throws NamingException { + + // clientSpec: rmi|iiop://[host][:port]/publishedName; + // + // "rmi://bob" + // "rmi://myHost/bob" + // "rmi://myHost:45/bob" + // "rmi://:45/bob" + // + // "iiop://bob" + // "iiop://myHost/bob" + // "iiop://myHost:45/bob" + // "iiop://:45/bob" + + int runtime = -1; + String host = null; + String port = null; + String clientName = null; + Remote clientInstance = null; + + // Parse the client spec. Is it an rmi or iiop spec? + + int startOffset = 0; + + if (clientSpec.startsWith("rmi://")) { + runtime = RMI_RUNTIME; + startOffset = 6; + } else if (clientSpec.startsWith("iiop://")) { + runtime = IIOP_RUNTIME; + startOffset = 7; + } else { + throw new Error("Invalid url: " + clientSpec); + } + + // Yep. + + int end = clientSpec.length(); + int slashOffset = clientSpec.indexOf('/',startOffset); + if (slashOffset >= 0) { + clientName = clientSpec.substring(slashOffset+1,end); + end = slashOffset; + + int portOffset = clientSpec.indexOf(':',startOffset); + if (portOffset >= 0) { + host = clientSpec.substring(startOffset,portOffset); + port = clientSpec.substring(portOffset+1,end); + } else { + host = clientSpec.substring(startOffset,slashOffset); + } + } else { + clientName = clientSpec.substring(startOffset,end); + } + + if (clientName == null) { + throw new Error("Invalid url: " + clientSpec + ". No name specified."); + } + + // Do some cleanup... + + if (host != null && host.length() == 0) host = null; + if (port != null && port.length() == 0) port = null; + + // Make sure we have a valid port number for the name service... + + if (port == null) { + + // Use default port... + + port = runtime == IIOP_RUNTIME ? "900" : Integer.toString(java.rmi.registry.Registry.REGISTRY_PORT); + } + + // Get a context... + + PortableContext context = getContext(runtime,host,port,false); + + // Lookup the client instance... + + Object temp = context.getNameContext().lookup(clientName); + clientInstance = (Remote) PortableRemoteObject.narrow(temp,Remote.class); + + // Create the client... + + Client client = context.getClient(clientName,clientInstance); + + return client; + } + + /** Find an RMI-IIOP Tie given a server object */ + private static Tie findTie(java.rmi.Remote obj) { + Tie result = Util.getTie(obj); + if (result == null) { + result = Utility.loadTie(obj); + } + return result; + } + + // _REVISIT_ Security problem with multiple Applets?? Made private for now. + + private static PortableContext getContext( int runtime, + String host, + String port, + boolean startNameServer) throws NamingException { + String key = createContextKey(runtime,host,port); + PortableContext result = (PortableContext) cache.get(key); + + if (result == null) { + result = new PortableContext(host,port,runtime,startNameServer); + cache.put(key,result); + } + + return result; + + } + + public static Process startNameServer(String port, int runtime) throws IOException { + + String handshake = null; + Vector args = new Vector(); + + // Fill out the command... + + args.addElement("java"); + args.addElement("-classpath"); + args.addElement(System.getProperty("java.class.path")); + + if (is12VM) { + String policy = System.getProperty("java.security.policy"); + if (policy != null) { + args.addElement("-Djava.security.policy=" + policy); + } + } + + if (runtime == IIOP_RUNTIME) { + + args.addElement("com.sun.corba.ee.impl.naming.cosnaming.TransientNameServer"); + args.addElement("-ORBInitialPort"); + args.addElement(port); + handshake = "Initial Naming Context:"; + + } else if (runtime == RMI_RUNTIME) { + + + args.addElement("javax.rmi.RMIRegistry"); + args.addElement(port); + handshake = HANDSHAKE; + + } else { + throw new Error("Unknown runtime: " + runtime); + } + + // Start her up... + + return test.Util.startProcess(args,handshake); + } + + private Client getClient(String clientName, Remote client) { + return new Client(clientName,client); + } + + private Servant startServant( String servantClass, + String servantName, + Remote servant) + throws ClassNotFoundException, + InstantiationException, + IllegalAccessException, + RemoteException, + NamingException { + Servant result = new Servant(servantClass,servantName,servant); + + // Export it if we need to... + + if (!(servant instanceof PortableRemoteObject) && + !(servant instanceof UnicastRemoteObject)) { + + PortableRemoteObject.exportObject(servant); + } + + // Publish it if we need to... + + if (servantName != null) { + nameContext.rebind(servantName,servant); + } + + return result; + } + + protected void init () throws NamingException { + + Hashtable nameEnv = new Hashtable(); + + // First, make sure we have a valid port number for + // the name service... + + if (nameServerPort == 0) { + + // Use default port... + + nameServerPort = runtime == IIOP_RUNTIME ? 900 : java.rmi.registry.Registry.REGISTRY_PORT; + } + + // Are we doing IIOP? + + String[] nameServerArgs = null; + + if (runtime == IIOP_RUNTIME) { + + // Yes, so create the ORB. First, setup the + // name server arguments... + + if (nameServerHost != null) { + nameServerArgs = new String[4]; + nameServerArgs[2] = "-ORBInitialHost"; + nameServerArgs[3] = nameServerHost; + + } else { + + nameServerArgs = new String[2]; + } + + nameServerArgs[0] = "-ORBInitialPort"; + nameServerArgs[1] = Integer.toString(nameServerPort); + + // Now create the orb... + + orb = initORB(nameServerArgs); + + // Now setup the name server environment... + + nameEnv.put("java.naming.corba.orb", orb); + nameEnv.put("java.naming.factory.initial", JndiConstants.COSNAMING_CONTEXT_FACTORY); + + } else if (runtime == RMI_RUNTIME) { + + // JRMP, so just setup the name server environment... + + String serverUrl = "rmi://"; + + if (nameServerHost != null) { + serverUrl += nameServerHost; + } + + serverUrl += ":" + Integer.toString(nameServerPort); + + nameEnv.put("java.naming.factory.initial",JndiConstants.REGISTRY_CONTEXT_FACTORY); + nameEnv.put("java.naming.provider.url",serverUrl); + + } else { + throw new Error("Unknown runtime: " + runtime); + } + + // Now get our name context. + + boolean gotContext = false; + boolean retry = false; + + try { + nameContext = new InitialContext(nameEnv); + gotContext = true; + + if (runtime == RMI_RUNTIME) { + + // Under IIOP, we would have gotten an exception at this point if + // the name server was not running. We need to check with JRMP... + + try { + nameContext.lookup("atsatt"); + } catch (javax.naming.NameNotFoundException e) { + } + } + } catch (Throwable e) { + + if (e instanceof ThreadDeath) throw (ThreadDeath)e; + + String server = runtime == IIOP_RUNTIME ? "TransientNameServer" : "RMIRegistry"; + + if (startNameServer && nameServerHost == null) { + + System.out.println("Starting " + server + "..."); + + try { + startNameServer(Integer.toString(nameServerPort),runtime); + } catch (Exception e1) { + throw new NamingException("Could not start name server: " + e1.toString()); + } + + if (orb != null) { + + // We have to recreate the orb at this point, because it's + // connection to the name service is bad... + + orb.shutdown(false); + orb = initORB(nameServerArgs); + nameEnv.put("java.naming.corba.orb", orb); + } + + nameContext = new InitialContext(nameEnv); + + } else { + throw new NamingException("Could not connect to " + server + "."); + } + } + + // Finally, create our key... + + key = createContextKey(runtime,nameServerHost,Integer.toString(nameServerPort)); + } + + private ORB initORB (String[] nameServerArgs) { + + // Setup the ORB properties... + + Properties props = null; + + try { + props = System.getProperties(); + } catch (SecurityException e) { + props = new Properties(); + } + + if (props.getProperty("org.omg.CORBA.ORBClass") == null) { + props.put("org.omg.CORBA.ORBClass","com.sun.corba.ee.impl.orb.ORBImpl"); + } + + if (props.getProperty("org.omg.CORBA.ORBSingletonClass") == null) { + props.put("org.omg.CORBA.ORBSingletonClass","com.sun.corba.ee.impl.orb.ORBSingleton"); + } + + // Create and return the ORB... + + return ORB.init(nameServerArgs, props); + } + + protected static String createContextKey(int runtime, String host, String port) { + return runtime + ":" + host + ":" + port; + } + + + private static void usage () { + System.out.println("\nUsage: PortableContext [options] servantSpec [servantSpec...]\n"); + + System.out.println("Where servantSpec can be either of two forms:\n"); + System.out.println(" Simple form: [publishname=]class"); + System.out.println(" URL form: servant://[host][:port]/class[?name=publishname]"); + + System.out.println("\nIf 'publishname' is omitted, the servant is not published in the name server."); + + System.out.println("\nThe supported options are:\n"); + + System.out.println(" -host nameServerHost The host name to use if not specified in servantSpec."); + System.out.println(" -port nameServerPort The port to use if not specified in servantSpec."); + System.out.println(" -startNameServer Start the name server if needed. Not allowed with -host option."); + System.out.println(" -verbose Print message describing each started servant."); + System.exit(1); + } + + /** + * Servant is a simple wrapper for rmi-iiop implementation classes which + * provides additional context information. + */ + public class Servant { + /** + * The servant class. + */ + public String servantClass = null; + + /** + * The name servant was published as, or null. + */ + public String servantName = null; + + /** + * The servant instance. + */ + public Remote servant = null; + + /** + * Return the context. + */ + public PortableContext getContext() { + return PortableContext.this; + } + + Servant(String servantClass, + String servantName, + Remote servant) { + this.servantClass = servantClass; + this.servantName = servantName; + this.servant = servant; + } + + private Servant(){} + } + + /** + * Client is a simple wrapper for rmi-iiop stub classes which + * provides additional context information. + */ + public class Client { + /** + * The name under which this instance was found. + */ + public String clientName = null; + + /** + * The client instance. + */ + public Remote client = null; + + /** + * Return the context. + */ + public PortableContext getContext() { + return PortableContext.this; + } + + Client(String clientName, Remote client) { + this.clientName = clientName; + this.client = client; + } + private Client(){} + } +} + +class RMIRegistry { + + /** + * Main program to start a registry.
+ * The port number can be specified on the command line. + */ + public static void main(String args[]) { + // Create and install the security manager + System.setSecurityManager(new RMISecurityManager()); + + try { + int port = Registry.REGISTRY_PORT; + if (args.length >= 1) { + port = Integer.parseInt(args[0]); + } + Registry registry = new RegistryImpl(port); + System.out.println("Ready."); + + // prevent registry from exiting + while (true) { + try { + // The following timeout is used because a bug in the + // native C code for Thread.sleep() cause it to return + // immediately for any higher value. + Thread.sleep(Integer.MAX_VALUE - 1); + } catch (InterruptedException e) { + } + } + } catch (NumberFormatException e) { + System.out.println("Port is not a number."); + } catch (Exception e) { + System.out.println("RegistryImpl.main: an exception occurred: " + + e.getMessage()); + e.printStackTrace(); + } + System.exit(1); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/download/ContainerOfBadVal.java b/functional-tests/src/test/java/javax/rmi/download/ContainerOfBadVal.java new file mode 100644 index 000000000..ec98a7e6c --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/ContainerOfBadVal.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import javax.rmi.CORBA.serialization.NotSerializable; + +public class ContainerOfBadVal implements java.io.Serializable { + + public NotSerializable badDataMember = new NotSerializable(); + +} diff --git a/functional-tests/src/test/java/javax/rmi/download/IIOPTestSerializable.java b/functional-tests/src/test/java/javax/rmi/download/IIOPTestSerializable.java new file mode 100644 index 000000000..aec87af66 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/IIOPTestSerializable.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import java.io.Serializable; + +public class IIOPTestSerializable implements Serializable +{ + Servant ref; + + public void setRef(Servant t) + { + //System.out.println("setRef "+t); + ref = t; + } + + public Servant getRef() + { + //System.out.println("getRef "+ref); + return ref; + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/download/SecurityManager.java b/functional-tests/src/test/java/javax/rmi/download/SecurityManager.java new file mode 100644 index 000000000..517044675 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/SecurityManager.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import java.io.FileDescriptor; +import java.util.Hashtable; +import java.net.InetAddress; +import java.lang.reflect.Member; +//import java.security.*; + +public class SecurityManager extends java.rmi.RMISecurityManager { + + // public void checkPermission(Permission perm) { + // } + + public void checkCreateClassLoader() { } + public void checkAccess(Thread g) { } + public void checkAccess(ThreadGroup g) { } + public void checkExit(int status) { } + public void checkExec(String cmd) { } + public void checkLink(String lib) { } + public void checkRead(FileDescriptor fd) { } + public void checkRead(String file) { } + public void checkRead(String file, Object context) { } + public void checkWrite(FileDescriptor fd) { } + public void checkWrite(String file) { } + public void checkDelete(String file) { } + public void checkConnect(String host, int port) { } + public void checkConnect(String host, int port, Object context) { } + public void checkListen(int port) { } + public void checkAccept(String host, int port) { } + public void checkMulticast(InetAddress maddr) { } + public void checkMulticast(InetAddress maddr, byte ttl) { } + public void checkPropertiesAccess() { } + public void checkPropertyAccess(String key) { } + public void checkPropertyAccess(String key, String def) { } + public boolean checkTopLevelWindow(Object window) { return true; } + public void checkPrintJobAccess() { } + public void checkSystemClipboardAccess() { } + public void checkAwtEventQueueAccess() { } + public void checkPackageAccess(String pkg) { } + public void checkPackageDefinition(String pkg) { } + public void checkSetFactory() { } + public void checkMemberAccess(Class clazz, int which) { } + public void checkSecurityAccess(String provider) { } +} diff --git a/functional-tests/src/test/java/javax/rmi/download/Servant.java b/functional-tests/src/test/java/javax/rmi/download/Servant.java new file mode 100644 index 000000000..e1d6fe5f6 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/Servant.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +public interface Servant + extends java.rmi.Remote { + public String EchoSingleRemoteInterface() throws java.rmi.RemoteException; + + public TheValue getValue() throws java.rmi.RemoteException; + + public void forceNotSerializableException(java.io.Serializable val) throws java.rmi.RemoteException; + + public java.io.Serializable forceNotSerializableException() throws java.rmi.RemoteException; + + public void throwRemoteExceptionWithNonSerializableValue() throws java.rmi.RemoteException; + + public String passClass(Class clz) throws java.rmi.RemoteException; + + public java.lang.Object testWriteReadObject(java.lang.Object o) throws java.rmi.RemoteException; + +} diff --git a/functional-tests/src/test/java/javax/rmi/download/ServantImpl.java b/functional-tests/src/test/java/javax/rmi/download/ServantImpl.java new file mode 100644 index 000000000..0df842a32 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/ServantImpl.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +public class ServantImpl implements Servant { + + public String EchoSingleRemoteInterface() throws java.rmi.RemoteException{ + return "EchoSingleRemoteInterface"; + } + + public TheValue getValue() throws java.rmi.RemoteException{ + try{ + String url = System.getProperty("java.rmi.server.codebase"); + return (TheValue)java.rmi.server.RMIClassLoader.loadClass(new java.net.URL(url),"javax.rmi.download.values.TheValueImpl").newInstance(); + } + catch(Throwable t){ + java.io.CharArrayWriter cw = new java.io.CharArrayWriter(); + t.printStackTrace(new java.io.PrintWriter(cw)); + + return new TheErrorValue(cw.toString()); + } + } + + public void forceNotSerializableException(java.io.Serializable val) throws java.rmi.RemoteException { + // no op + } + + public java.io.Serializable forceNotSerializableException() throws java.rmi.RemoteException { + return new ContainerOfBadVal(); + } + + public void throwRemoteExceptionWithNonSerializableValue() throws java.rmi.RemoteException { + throw new TheBadException(); + } + + public String passClass(Class clz) throws java.rmi.RemoteException { + return "Name:"+clz.getName(); + } + + public java.lang.Object testWriteReadObject(java.lang.Object o) + throws java.rmi.RemoteException { + return o; + } + +} diff --git a/functional-tests/src/test/java/javax/rmi/download/TheBadException.java b/functional-tests/src/test/java/javax/rmi/download/TheBadException.java new file mode 100644 index 000000000..f3f23cbeb --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheBadException.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import javax.rmi.CORBA.serialization.NotSerializable; + +public class TheBadException extends java.rmi.RemoteException { + + public NotSerializable badDataMember = new NotSerializable(); + +} diff --git a/functional-tests/src/test/java/javax/rmi/download/TheClient.java b/functional-tests/src/test/java/javax/rmi/download/TheClient.java new file mode 100644 index 000000000..38e853b0c --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheClient.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Hashtable; +import java.util.Properties; + +public class TheClient { + + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + private static void passed(){ + System.out.println(test.Util.HANDSHAKE); + System.out.flush(); + } + + private static void failed(Throwable t){ + StringWriter strWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(strWriter); + t.printStackTrace(printWriter); + System.out.println("Download test FAILED:\n"+strWriter.toString()+"\n <<< END STACK TRACE >>>"); + System.out.flush(); + System.exit(1); + } + + public static void main(String[] args) { + try { + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // We are going to use JNDI/CosNaming so lets go ahead and + // create our root naming context. NOTE: We setup CosNaming + // as our naming plug-in for JNDI by setting properties above. + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + Context ic = new InitialContext(env); + + // Let the test begin... + // Resolve the Object Reference using JNDI/CosNaming + java.lang.Object objref = ic.lookup("TheDownloadTestServer"); + + // This test is designed to verify PortableRemoteObject.narrow + + try{ + Servant narrowTo = null; + if ( (narrowTo = (Servant) + PortableRemoteObject.narrow(objref,Servant.class)) != null ) { + Servant serv1 = narrowTo; + String mssg = narrowTo.getValue().sayHello(); + if (!mssg.equals("Hello, world!")) { + System.err.println(mssg); + throw new Exception("javax.rmi.download.TheTest: SingleRemoteInterface() narrow failed"); + } + + IIOPTestSerializable ones = new IIOPTestSerializable(); + ones.setRef(serv1); + IIOPTestSerializable twos = (IIOPTestSerializable)serv1.testWriteReadObject(ones); + Servant serv2 = twos.getRef(); + String mssg2 = serv2.EchoSingleRemoteInterface(); + if (!mssg2.equals("EchoSingleRemoteInterface")) { + System.err.println(mssg); + throw new Exception("javax.rmi.download.TheTest: Reverse pass failed"); + } + + passed(); + + + } + } catch (Throwable ex) { + failed(ex); + ex.printStackTrace(); + } + } catch (Exception ex) { + failed(ex); + ex.printStackTrace(System.out); + System.out.println(); + System.out.flush(); + } + } +} + diff --git a/functional-tests/src/test/java/javax/rmi/download/TheErrorValue.java b/functional-tests/src/test/java/javax/rmi/download/TheErrorValue.java new file mode 100644 index 000000000..05b515e4a --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheErrorValue.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +public class TheErrorValue extends java.rmi.RemoteException implements TheValue { + String mssg = null; + + public TheErrorValue(String mssg){ + this.mssg = mssg; + } + + public String sayHello(){ + return "Error : Could not load TheValueImpl so this was loaded instead :"+mssg; + } +} diff --git a/functional-tests/src/test/java/javax/rmi/download/TheServer.java b/functional-tests/src/test/java/javax/rmi/download/TheServer.java new file mode 100644 index 000000000..a33169817 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheServer.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import java.util.Hashtable; +import java.util.Properties; + +public class TheServer { + + // This test runs the NameServer on port 1050. + + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + public static void main(String[] args) { + try { + + // The RMIClassLoader requires a security manager to be set + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + //System.setSecurityManager(new java.rmi.RMISecurityManager()); + + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // create an RMI Servant. The Servant will actually + // handle the users request. + + ServantImpl servant = new ServantImpl(); + + // Let use PortableRemoteObject to export our servant. + // This same method works for JRMP and IIOP. + + PortableRemoteObject.exportObject(servant); + + // Once the Object is exported we are going to link it to + // our ORB. To do this we need to get the Tie associated + // with our Servant. PortableRemoteObject.export(...) + // create a Tie for us. All we have to do is to retrieve the + // Tie from javax.rmi.CORBA.Util.getTie(...); + + Tie servantsTie = javax.rmi.CORBA.Util.getTie(servant); + + // Now lets set the orb in the Tie object. The Sun/IBM + // ORB will perform a orb.connect. So at this point the + // Tie is connected to the ORB and ready for work. + servantsTie.orb(orb); + + + // We are using JNDI/CosNaming to export our object so we + // need to get the root naming context. We use the properties + // set above to initialize JNDI. + + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + + Context ic = new InitialContext(env); + + // Now lets Export our object by publishing the object + // with JNDI + ic.rebind("TheDownloadTestServer", servant); + + // Self-Test + // resolve the Object Reference using JNDI + Servant iServant = (Servant) + PortableRemoteObject.narrow(ic.lookup("TheDownloadTestServer"), + Servant.class); + + // If the self test works then we will give the "Handshake" to + // the client. This means we are open for business. + + if (iServant.EchoSingleRemoteInterface().equals("EchoSingleRemoteInterface")) { + System.out.println(test.Util.HANDSHAKE); + } else { + System.out.println("Self test FAILED."); + } + + System.out.flush(); + + // wait for object invocation + Object sync = new Object(); + synchronized (sync) { sync.wait(); } + + } catch (Exception ex) { + + ex.printStackTrace(System.out); + System.out.println(); + System.out.flush(); + } + } +} diff --git a/functional-tests/src/test/java/javax/rmi/download/TheTest.java b/functional-tests/src/test/java/javax/rmi/download/TheTest.java new file mode 100644 index 000000000..803c38bfa --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheTest.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +import com.sun.corba.ee.spi.JndiConstants; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; +import test.Util; +import test.WebServer; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; +import java.io.File; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; + +/* + * @test + */ +public class TheTest extends test.Test { + // This test runs the NameServer on port 1050. + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + public void run() { + JUnitReportHelper helper = new JUnitReportHelper( + this.getClass().getName() ) ; + + String testName = new TheTest().getClass().getName(); + Process nameServer = null; + Process server = null; + Process client = null; + boolean testPassed = true; + WebServer webServer = null; + + try { + // The RMIClassLoader requires a security manager to be set + // System.setSecurityManager(new javax.rmi.download.SecurityManager()); + //System.setSecurityManager(new java.rmi.RMISecurityManager()); + + // First Compile the classes to generate the Stub and Tie + // files that are needed. NOTE: This requires the latest + // RMIC compiler that supports IIOP. + + if (!getArgs().containsKey("-normic")) { + compileClasses(); + } + + // Now we need to start the NameServer and + // our test server. The test server will register + // with the NameServer. + + nameServer = Util.startNameServer("1050",true); + + // Start up the HTTP server + int port = Util.getHttpServerPort(); + File rootDir = new File(System.getProperty("http.server.root.directory")); + webServer = new WebServer(port,rootDir,1); + webServer.start(); + + // Create user.dir property (this is how the server knows + // where the test value is but we (this client) does not). + Vector properties = new Vector(); + properties.addElement("-Djava.rmi.server.codebase=" + (String)System.getProperty("java.rmi.server.codebase")); + String testPolicy = (String)System.getProperty("java.security.policy"); + if (testPolicy!=null) + properties.addElement("-Djava.security.policy="+testPolicy); + + + + //Class c = java.rmi.server.RMIClassLoader.loadClass(new java.net.URL(System.getProperty("java.rmi.server.codebase")), "javax.rmi.download.values.TheValueImpl"); + //System.out.println("Found : " + c.toString()); + + // Start it + server = Util.startServer("javax.rmi.download.TheServer", + properties); + + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // We are going to use JNDI/CosNaming so lets go ahead and + // create our root naming context. NOTE: We setup CosNaming + // as our naming plug-in for JNDI by setting properties above. + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + Context ic = new InitialContext(env); + + // Let the test begin... + helper.start( "test1" ) ; + // Resolve the Object Reference using JNDI/CosNaming + java.lang.Object objref = ic.lookup("TheDownloadTestServer"); + + // This test is designed to verify PortableRemoteObject.narrow + try{ + Servant narrowTo = null; + if ( (narrowTo = (Servant) + PortableRemoteObject.narrow(objref,Servant.class)) != null ) { + Servant serv1 = narrowTo; + String mssg = narrowTo.getValue().sayHello(); + if (!mssg.equals("Hello, world!")) { + System.err.println(mssg); + throw new Exception("javax.rmi.download.TheTest: SingleRemoteInterface() narrow failed"); + } + + IIOPTestSerializable ones = new IIOPTestSerializable(); + ones.setRef(serv1); + IIOPTestSerializable twos = (IIOPTestSerializable)serv1.testWriteReadObject(ones); + Servant serv2 = twos.getRef(); + String mssg2 = serv2.EchoSingleRemoteInterface(); + if (!mssg2.equals("EchoSingleRemoteInterface")) { + System.err.println(mssg); + throw new Exception("javax.rmi.download.TheTest: Reverse pass failed"); + } + } + + // Now try from separate client that has no codebase of its own + Vector properties2 = new Vector(); + properties.addElement("-Djava.security.policy="+testPolicy); + client = Util.startServer("javax.rmi.download.TheClient", + properties); + helper.pass() ; + } catch (Throwable ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + helper.fail( ex ) ; + } + } catch (Exception ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + helper.fail( ex ) ; + } finally { + helper.done() ; + + if (client != null) { + client.destroy(); + } + + if (server != null) { + server.destroy(); + } + + if (nameServer != null) { + nameServer.destroy(); + } + + if (webServer != null) + webServer.quit(); + } + + if ( testPassed == true ) { + status = null; + } else { + status = new Error("PortableRemoteObject.narrow Test Failed"); + } + + } + + // Compiling ComboInterface cause the compiler to compile + // all the other classes that need to be compiled. + + private void compileClasses () throws Exception + { + String arg = "-iiop"; + String[] additionalArgs = null; + String[] classes = {"javax.rmi.download.ServantImpl"}; + + // Create the additional args array... + + String outputDirectory = null; + int length = 3; + Hashtable flags = getArgs(); + if (flags.containsKey(test.Test.OUTPUT_DIRECTORY)) { + outputDirectory = (String)flags.get(test.Test.OUTPUT_DIRECTORY); + length += 2; + } + additionalArgs = new String[length]; + int offset = 0; + + if (outputDirectory != null) { + additionalArgs[offset++] = "-d"; + additionalArgs[offset++] = outputDirectory; + } + additionalArgs[offset++] = "-Xreverseids"; + additionalArgs[offset++] = "-alwaysgenerate"; + additionalArgs[offset++] = "-keepgenerated"; + + // Run rmic... + + Util.rmic(arg,additionalArgs,classes,false); + } +} diff --git a/functional-tests/src/test/java/javax/rmi/download/TheValue.java b/functional-tests/src/test/java/javax/rmi/download/TheValue.java new file mode 100644 index 000000000..a9be5b5cf --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheValue.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download; + +public interface TheValue extends java.io.Serializable { + public class Helper { + public static TheValue newValue() + throws ClassNotFoundException, InstantiationException, + IllegalAccessException { + return (javax.rmi.download.TheValue)Class.forName("javax.rmi.download.values.TheValueImpl").newInstance(); + } + }; + + public String sayHello(); +} diff --git a/functional-tests/src/test/java/javax/rmi/download/TheValueImpl.java b/functional-tests/src/test/java/javax/rmi/download/TheValueImpl.java new file mode 100644 index 000000000..741032d84 --- /dev/null +++ b/functional-tests/src/test/java/javax/rmi/download/TheValueImpl.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// ATTENTION! ATTENTION! This class is NOT in the wrong directory nor in the +// wrong package. It's directory should be javax.rmi.download and it's +// package should be javax.rmi.download.value. +// + + +package javax.rmi.download.values; + +import javax.rmi.download.TheValue; + +public class TheValueImpl implements TheValue { + public TheValueImpl(){} + + public String sayHello(){ + return "Hello, world!"; + } +} diff --git a/functional-tests/src/test/java/mantis/m4764130/Client.java b/functional-tests/src/test/java/mantis/m4764130/Client.java new file mode 100644 index 000000000..ef8d4a6d9 --- /dev/null +++ b/functional-tests/src/test/java/mantis/m4764130/Client.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Oct 16 (Wed) 08:32:24 by Harold Carr. +// Last Modified : 2003 Mar 17 (Mon) 20:49:36 by Harold Carr. +// + +package mantis.m4764130; + +import java.util.Properties; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class Client +{ + public static void main(String[] args) + { + try { + + Properties props = new Properties(); + props.put(ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + Interceptor.class.getName(), + "dummy"); + ORB orb = ORB.init(args, props); + + NamingContext namingContext = + NamingContextHelper.narrow(orb.resolve_initial_references( + "NameService")); + NameComponent nc = new NameComponent("Server", ""); + NameComponent path[] = { nc }; + Hello hello = HelloHelper.narrow(namingContext.resolve( path )); + + hello.hello("1234"); + + } catch (Exception ex) { + System.out.println("Client ERROR : " + ex); + ex.printStackTrace(); + System.exit(1); + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/mantis/m4764130/Interceptor.java b/functional-tests/src/test/java/mantis/m4764130/Interceptor.java new file mode 100644 index 000000000..77eb89d57 --- /dev/null +++ b/functional-tests/src/test/java/mantis/m4764130/Interceptor.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Oct 16 (Wed) 08:32:24 by Harold Carr. +// Last Modified : 2003 Mar 17 (Mon) 20:51:22 by Harold Carr. +// + +package mantis.m4764130; + +import java.util.Properties; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; +import org.omg.IOP.ServiceContext; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; +import com.sun.corba.ee.spi.servicecontext.SendingContextServiceContext; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class Interceptor + extends + org.omg.CORBA.LocalObject + implements + ClientRequestInterceptor, + ServerRequestInterceptor, + ORBInitializer +{ + public int numberOfClientHelloInvocations = 0; + // + // Interceptor operations + // + + public String name() + { + return this.getClass().getName(); + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + throws + ForwardRequest + { + System.out.println(ri.operation()); + if (ri.operation().equals("hello")) { + numberOfClientHelloInvocations++; + if (numberOfClientHelloInvocations == 1) { + throw new ForwardRequest(ri.target()); + } + } + } + + public void send_poll(ClientRequestInfo ri) + { + } + + public void receive_reply(ClientRequestInfo ri) + { + } + + public void receive_exception(ClientRequestInfo ri) + { + } + + public void receive_other(ClientRequestInfo ri) + { + } + + // + // ServerRequestInterceptor operations + // + + public void receive_request_service_contexts(ServerRequestInfo ri) + { + System.out.println(ri.operation()); + try { + ServiceContext serviceContext = + ri.get_request_service_context(SendingContextServiceContext.SERVICE_CONTEXT_ID); + } catch (BAD_PARAM e) { + // Not present. + System.out.println("SendingContextServiceContext not present"); + System.exit(1); + } + } + + public void receive_request(ServerRequestInfo ri) + { + } + + public void send_reply(ServerRequestInfo ri) + { + } + + public void send_exception(ServerRequestInfo ri) + { + } + + public void send_other(ServerRequestInfo ri) + { + } + + // + // Initializer operations. + // + + public void pre_init(ORBInitInfo info) + { + System.out.println(this.getClass().getName() + " .pre_init"); + try { + // NOTE: The client only needs the client side points. + // The server only needs the server side points. + // It just saves me time just to write one interceptor/initializer. + info.add_client_request_interceptor(new Interceptor()); + info.add_server_request_interceptor(new Interceptor()); + } catch (Throwable t) { + System.out.println("Cannot register interceptor: " + t); + } + } + + public void post_init(ORBInitInfo info) {} +} + +// End of file. diff --git a/functional-tests/src/test/java/mantis/m4764130/SendingContextTest.java b/functional-tests/src/test/java/mantis/m4764130/SendingContextTest.java new file mode 100644 index 000000000..703c615be --- /dev/null +++ b/functional-tests/src/test/java/mantis/m4764130/SendingContextTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Oct 16 (Wed) 08:35:25 by Harold Carr. +// Last Modified : 2002 Oct 17 (Thu) 09:31:31 by Harold Carr. +// + +package mantis.m4764130; + +import java.util.Properties; +import corba.framework.Controller; +import corba.framework.CORBATest; +import corba.framework.Options; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class SendingContextTest extends CORBATest { + + protected void doTest() throws Throwable { + + if (test.Test.useJavaSerialization()) { + return; + } + + Controller orbd = createORBD(); + orbd.start(); + + Controller server = createServer("mantis.m4764130.Server"); + server.start(); + + Controller client = createClient("mantis.m4764130.Client"); + client.start(); + + client.waitFor(); + + client.stop(); + server.stop(); + orbd.stop(); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/mantis/m4764130/Server.java b/functional-tests/src/test/java/mantis/m4764130/Server.java new file mode 100644 index 000000000..e6a632452 --- /dev/null +++ b/functional-tests/src/test/java/mantis/m4764130/Server.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2002 Oct 16 (Wed) 08:32:02 by Harold Carr. +// Last Modified : 2003 Mar 17 (Mon) 20:51:40 by Harold Carr. +// + +package mantis.m4764130; + +import java.util.Properties; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; +import org.omg.PortableServer.POA; +import com.sun.corba.ee.spi.misc.ORBConstants; + +class HelloImpl + extends + HelloPOA +{ + public HelloImpl() + { + } + + public String hello(String x) + { + return x; + } +} + +public class Server +{ + public static void main(String[] args) + { + try{ + Properties props = new Properties(); + props.setProperty(ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + Interceptor.class.getName(), + "dummy"); + ORB orb = ORB.init(args, props); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + HelloImpl hello = new HelloImpl(); + byte[] id = rootPOA.activate_object(hello); + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + NamingContext namingContext = + NamingContextHelper.narrow(orb.resolve_initial_references( + "NameService")); + NameComponent nc = new NameComponent("Server", ""); + NameComponent path[] = { nc }; + namingContext.rebind( path , ref ); + + System.out.println("Server is ready."); + + orb.run(); + + } catch (Exception ex) { + System.err.println("ERROR: " + ex); + ex.printStackTrace(); + System.exit(1); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/pi/clientinterceptor/ClientCommon.java b/functional-tests/src/test/java/pi/clientinterceptor/ClientCommon.java new file mode 100644 index 000000000..85ae0209c --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/ClientCommon.java @@ -0,0 +1,347 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import java.io.PrintStream; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; +import org.omg.CORBA.UNKNOWN; + +/** + * Common methods for Client implementations in this test to use + */ +abstract public class ClientCommon +{ + // Set from run() + protected com.sun.corba.ee.spi.orb.ORB orb; + + // Set from run() + protected PrintStream out; + + // Set from run() + protected PrintStream err; + + private JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + + /** + * Creates a com.sun.corba.ee.spi.orb.ORB and notifies the TestInitializer of its presence + */ + protected void createORB( String[] args ) { + // create and initialize the ORB with initializer + String testInitializer = "pi.clientinterceptor.TestInitializer"; + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + this.orb = (com.sun.corba.ee.spi.orb.ORB)ORB.init(args, props); + TestInitializer.orb = this.orb; + } + + protected void finish() { + helper.done() ; + } + + /** + * Perform common ClientRequestInterceptor tests + */ + protected void testClientInterceptor() throws Exception { + out.println(); + out.println( "Running common ClientRequestInterceptor tests" ); + out.println( "=============================================" ); + + // No exceptions thrown. Should call send_request, sayHello, and + // then receive_reply on all 3 interceptors in the correct order + out.println( "- Testing standard invocation..." ); + testInvocation( "standardInvocation", + SampleClientRequestInterceptor.MODE_NORMAL, + "sr1sr2sr3rr3rr2rr1", "sayHello", true, false, false ); + + // SYSTEM_EXCEPTION thrown by server. Should call send_request, + // saySystemException, and then receive_exception on all 3 + // interceptors in the correct order. + out.println( "- Testing invocation resulting in SYSTEM_EXCEPTION..." ); + testInvocation( "systemExceptionResult", + SampleClientRequestInterceptor.MODE_NORMAL, + "sr1sr2sr3re3re2re1", "sayException", true, true, false ); + + // This is a one-way call, so receive_other will be invoked. + // Should call send_request, sayOther, and then receive_other + // on all 3 interceptors in the correct order. + out.println( + "- Testing oneway invocation resulting in receive_other..." ); + testInvocation( "receiveOtherResult", + SampleClientRequestInterceptor.MODE_NORMAL, + "sr1sr2sr3ro3ro2ro1", "sayOneway", true, false, false ); + + // SYSTEM_EXCEPTION thrown in send_request for second interceptor. + // Should result in send_request being called for 1 and 2, but + // not 3, and receive_exception being called for 1 only. The + // method sayHello should never be invoked. + out.println( + "- Testing standard invocation where interceptor #2 " + + "throws exception." ); + testInvocation( "interceptor2SystemException", + SampleClientRequestInterceptor.MODE_SYSTEM_EXCEPTION, + "sr1sr2re1", "sayHello", false, true, false ); + + // SYSTEM_EXCEPTION thrown in receive_reply for second interceptor. + // Should result in send_request being called for all, + // receive_reply called for 3, and 2, and receive_exception for + // 1. + out.println( + "- Testing standard invocation where interceptor #2 " + + "throws system exception in receive_reply." ); + testInvocation( "interceptor2SystemExceptionReceiveReply", + SampleClientRequestInterceptor.MODE_RECEIVE_REPLY_EXCEPTION, + "sr1sr2sr3rr3rr2re1", "sayHello", true, true, false ); + + // SYSTEM_EXCEPTION thrown in receive_reply for second interceptor. + // Should result in send_request being called for all, + // receive_other called for 3, and 2, and receive_exception for + // 1. + out.println( + "- Testing oneway invocation where interceptor #2 " + + "throws SYSTEM_EXCEPTION in receive_other." ); + testInvocation( "interceptor2SystemExceptionReceiveOther", + SampleClientRequestInterceptor.MODE_RECEIVE_OTHER_EXCEPTION, + "sr1sr2sr3ro3ro2re1", "sayOneway", true, true, false ); + + // ForwardRequest thrown in send_request for second interceptor. + // Should result in send_request being called for 1 and 2, but + // not 3, and receive_other being called for 1 only. The + // method sayHello should never be invoked. + out.println( + "- Testing standard invocation where interceptor #2 " + + "throws ForwardRequest." ); + testInvocation( "interceptor2ForwardRequest", + SampleClientRequestInterceptor.MODE_FORWARD_REQUEST, + "sr1sr2ro1sr1sr2sr3rr3rr2rr1", "sayHello", true, false, true ); + + // ForwardRequest thrown in receive_exception for second interceptor. + // Should result in send_request being called for all, + // receive_exception called for 3, and 2, and receive_other for + // 1. + orb.setDebugFlag( "interceptor" ) ; + orb.setDebugFlag( "subcontract" ) ; + try { + out.println( + "- Testing standard invocation where interceptor #2 " + + "throws ForwardRequest in receive_exception." ); + testInvocation( "intercepto2ForwardRequestReceiveException", + SampleClientRequestInterceptor.MODE_RECEIVE_EXCEPTION_FORWARD, + "sr1sr2sr3re3re2ro1sr1sr2sr3re3re2re1", "sayException", + true, true, true ); + } finally { + orb.clearDebugFlag( "interceptor" ) ; + orb.clearDebugFlag( "subcontract" ) ; + } + + // Check that call counter is zero (balanced starting points with + // ending points) + out.print( + "- Checking call counter: " + + SampleClientRequestInterceptor.callCounter + " " ); + + if( SampleClientRequestInterceptor.callCounter == 0 ) { + out.println( "(ok)" ); + } + else { + out.println( "(error - should be 0)" ); + throw new RuntimeException( "Call counter should be 0!" ); + } + } + + /** + * Perform POA special operations test + * (only invoked from POA clients) + */ + protected void testSpecialOperations() + throws Exception + { + out.println(); + out.println( "Running Special Operations Tests" ); + out.println( "================================" ); + + // Note: shouldInvoke is false because we have no hook code on + // the server for these operations so we cannot tell if it was + // actually invoked. + + out.println( "+ Testing _is_a..." ); + testInvocation( "isATest", + SampleClientRequestInterceptor.MODE_NORMAL, + "sr1sr2sr3rr3rr2rr1", "_is_a", false, false, false ); + + // Expected exception return value since we do not implement this + // method. + out.println( "+ Testing _get_interface_def..." ); + testInvocation( "getInterfaceDefTest", + SampleClientRequestInterceptor.MODE_NORMAL, + "sr1sr2sr3re3re2re1", "_get_interface_def", false, false, false ); + + out.println( "+ Testing _non_existent..." ); + testInvocation( "nonExistentTest", + SampleClientRequestInterceptor.MODE_NORMAL, + "sr1sr2sr3rr3rr2rr1", "_non_existent", false, false, false ); + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + abstract protected void clearInvoked() throws Exception; + + /** + * Invoke the method with the given name on the object + */ + abstract protected void invokeMethod( String name ) throws Exception; + + /** + * Return true if the method was invoked + */ + abstract protected boolean wasInvoked() throws Exception; + + /** + * Return true if the method was forwarded + */ + abstract protected boolean didForward() throws Exception; + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation. + */ + abstract protected void resolveReferences() throws Exception; + + /** + * Tests a standard invocation by resolving a reference to helloServer + * and making an invcation, recording the interceptor invocation ordering. + * @param mode - See SampleClientRequestIntreceptor.testMode for more + * details of mode parameter. + * @param correctOrder - See SampleClientRequestInterceptor. + * invocationOrder for more details on correctOrder. + * @param methodName is either "sayHello", "sayException", or "sayOther" + * @param shouldInvokeTarget - True if the method should have been invoked, + * or false if not. + * @param exceptionExpected - True if it is expected that this call + * should return an UNKNOWN exception with the message + * "Valid Test Result" embedded within. + * @param forwardExpected - True if it is expected that this call + * should result in a forward to another object and that that object + * should be invoked. + */ + protected void testInvocation( String testName, int mode, + String correctOrder, + String methodName, + boolean shouldInvokeTarget, + boolean exceptionExpected, + boolean forwardExpected ) + throws Exception + { + helper.start( testName ) ; + + try { + // Tell interceptor to behave while clearing invocation flag: + SampleClientRequestInterceptor.testMode = + SampleClientRequestInterceptor.MODE_NORMAL; + + resolveReferences(); + + // Clear invocation flags in helloRef and helloRefForward: + clearInvoked(); + SampleClientRequestInterceptor.testMode = mode; + + // Clear invocation order. It is critical that this is done after + // clearInvoked is called so that we do not record the interceptors + // called during the clearInvoked() invocation itself. + SampleClientRequestInterceptor.invocationOrder = ""; + + try { + // Invoke the method. + invokeMethod( methodName ); + } catch( UNKNOWN e ) { + // Check to make sure we expected this exception. + if( !exceptionExpected ) { + throw e; + } + } + + // Tell interceptor to behave while analyzing results: + SampleClientRequestInterceptor.testMode = + SampleClientRequestInterceptor.MODE_NORMAL; + + // Examine invocation order to ensure everything was called in the + // right order. + // + // NOTE: This is merely a convenient way to check ordering. + // Since the specification does not require that the order in which + // interceptors are registered match the order in which they are + // invoked, the actual invocationOrder may be different but still + // valid. This test may need modification if we change the way + // we determine the initial invocation order of interceptors. + String order = SampleClientRequestInterceptor.invocationOrder; + checkOrder( correctOrder, order ); + + // Determine if the method was invoked when it was supposed to be + // or not invoked when it was not supposed to be. + + // But first, if this was a oneway call, leave sufficient time for + // the call to get there. + if( methodName.equals( "sayOneway" ) ) { + try { + // 2 seconds *should* almost always be enough. + Thread.sleep( 2000 ); + } + catch( InterruptedException e ) { + } + } + + boolean didInvoke = wasInvoked(); + boolean didForward = didForward(); + + out.println( " + Should inovke method: " + shouldInvokeTarget ); + out.println( " + Did invoke method: " + didInvoke ); + if( didInvoke != shouldInvokeTarget ) { + throw new RuntimeException( "Method should " + + (!shouldInvokeTarget ? "not" : "") + " have been invoked!" ); + } + out.println( " + Should forward and invoke: " + forwardExpected ); + out.println( " + Did forward and invoke: " + didForward ); + if( didForward != forwardExpected ) { + throw new RuntimeException( "Method should " + + (!forwardExpected ? "not" : "") + " have forwarded!" ); + } + + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Checks the invocation order against the correct invocation order, + * displays some debug output and throws an Exception if they do not + * match. + */ + private void checkOrder( String correctOrder, String order ) + throws Exception + { + out.println( " + Expected invocation order: " + correctOrder ); + out.println( " + Actual invocation order: " + order ); + if( !order.equals( correctOrder ) ) { + out.println( " + MISMATCH. Exiting." ); + throw new Exception( "Invocation order mismatch." ); + } + } + +} + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/ClientInterceptorTest.java b/functional-tests/src/test/java/pi/clientinterceptor/ClientInterceptorTest.java new file mode 100644 index 000000000..3bd682741 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/ClientInterceptorTest.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import corba.framework.*; +import java.util.*; + +/** + * Tests ClientInterceptor as per Portable Interceptors spec + * orbos/99-12-02, section 5.2. See pi/assertions.html for Assertions + * covered in this test. + *

+ * The test works as follows: + *

    + *
  • First, a test ORB initializer registers three client request + * interceptors with the ORB.
  • + *
+ */ +public class ClientInterceptorTest + extends CORBATest +{ + // Set to true if at least one test fails. + private boolean failed = false; + + Controller orbd; + + protected void doTest() + throws Throwable + { + System.out.println(); + System.out.println( " \t\t\t\tLocal\t\tRemote" ); + + startORBD( ); + + beginTest( "[POA]\t\t\t" ); + testPOALocal(); + endTest( "\t\t" ); + testPOARemote(); + endTest( "\n" ); + + beginTest( "[POA DII]\t\t\t" ); + testPOADIILocal(); + endTest( "\t\t" ); + testPOADIIRemote(); + endTest( "\n" ); + + beginTest( "[RMI]\t\t\t" ); + testRMILocal(); + endTest( "\t\t" ); + testRMIRemote(); + endTest( "\n" ); + + beginTest( "[ClientDelegate DII]\t" ); + testClientDelegateDIILocal(); + endTest( "\t\t" ); + testClientDelegateDIIRemote(); + endTest( "\n" ); + stopORBD( ); + + System.out.println(); + System.out.print( " Final Result: " ); + if( failed ) { + throw new RuntimeException( "Errors detected" ); + } + } + + private void testPOALocal() + throws Throwable + { + Controller client; + + try { + // Start only a client - the client will create the server. + client = createClient( "pi.clientinterceptor.POALocalClient", + "poalocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testPOARemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientinterceptor.POAServer", + "poa-server" ); + server.start(); + client = createClient( "pi.clientinterceptor.POAClient", + "poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testPOADIILocal() + throws Throwable + { + Controller client, server; + + try { + // Start only a client - the client will create the server. + client = createClient( + "pi.clientinterceptor.DIIPOALocalClient", "diipoalocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testPOADIIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientinterceptor.POAServer", + "dii-poa-server" ); + server.start(); + client = createClient( "pi.clientinterceptor.DIIPOAClient", + "dii-poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testRMILocal() + throws Throwable + { + try { + Controller client; + + // Start only a client - the client will create the server. + client = createClient( "pi.clientinterceptor.RMILocalClient", + "rmilocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testRMIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientinterceptor.RMIServer", + "rmi-server" ); + server.start(); + client = createClient( "pi.clientinterceptor.RMIClient", + "rmi-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testClientDelegateDIILocal() + throws Throwable + { + Controller client; + + try { + // Start only a client - the client will create the server. + client = createClient( "pi.clientinterceptor.DIIRMILocalClient", + "diirmilocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testClientDelegateDIIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientinterceptor.OldRMIServer", + "dii-oldrmi-server" ); + server.start(); + client = createClient( "pi.clientinterceptor.DIIPOAClient", + "dii-oldrmi-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void beginTest( String name ) + throws Exception + { + System.out.print( " " + name ); + } + + private void endTest( String terminator ) + throws Exception + { + System.out.print( terminator ); + } + + private void startORBD() + throws Exception + { + orbd = createORBD(); + orbd.start(); + } + + private void stopORBD() + throws Exception + { + orbd.stop(); + pause(); + } + + private void printEndTest( Controller client, Controller server ) + throws Throwable + { + if( (server != null) && server.finished() ) { + System.out.print( "FAILED, Server crashed" ); + failed = true; + } + else if( client.exitValue() != Controller.SUCCESS ) { + System.out.print( "FAILED, Client exit value = " + + client.exitValue() ); + failed = true; + } + else { + System.out.print( "PASSED" ); + } + } + + // Pause a little to allow all processes to fully terminate. + private void pause() { + try { + Thread.sleep( 2000 ); + } + catch( InterruptedException e ) { + // ignore. + } + } +} + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/DIIPOAClient.java b/functional-tests/src/test/java/pi/clientinterceptor/DIIPOAClient.java new file mode 100644 index 000000000..d7f736f5e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/DIIPOAClient.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; + +/** + * Tests DII POA Remote invocation + */ +public class DIIPOAClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloDIIClientStub helloRef; + + // Reference to hello object to be forwarded to: + private helloDIIClientStub helloRefForward; + + public static void main(String args[]) { + try { + (new DIIPOAClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "====================================" ); + out.println( "Invoking ORB for DII POA Remote test" ); + out.println( "====================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + try { + // Test ClientInterceptor + testClientInterceptor(); + + // Test POA Special operations + testSpecialOperations(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "_is_a" ) ) { + helloRef._is_a( "IDL:ServerRequestInterceptor/goodbye:1.0" ); + } + else if( methodName.equals( "_get_interface_def" ) ) { + try { + helloRef._get_interface_def(); + } + catch( NO_IMPLEMENT e ) { + // This is expected in our ORB. + } + } + else if( methodName.equals( "_non_existent" ) ) { + helloRef._non_existent(); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward.getObject(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloDIIClientStub resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + org.omg.CORBA.Object helloRef = ncRef.resolve(path); + + return new helloDIIClientStub( orb, helloRef ); + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/DIIPOALocalClient.java b/functional-tests/src/test/java/pi/clientinterceptor/DIIPOALocalClient.java new file mode 100644 index 000000000..983cb489e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/DIIPOALocalClient.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; + +/** + * Tests DII POA Local invocation (with a co-located orb) + */ +public class DIIPOALocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloDIIClientStub helloRef; + + // Reference to hello object to be forwarded to: + private helloDIIClientStub helloRefForward; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===================================" ); + System.out.println( "Creating ORB for DII POA Local test" ); + System.out.println( "===================================" ); + + final DIIPOALocalClient client = new DIIPOALocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new POALocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientInterceptor(); + + // Test POA Special operations + testSpecialOperations(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "_is_a" ) ) { + helloRef._is_a( "IDL:ServerRequestInterceptor/goodbye:1.0" ); + } + else if( methodName.equals( "_get_interface_def" ) ) { + try { + helloRef._get_interface_def(); + } + catch( NO_IMPLEMENT e ) { + // This is expected in our ORB. + } + } + else if( methodName.equals( "_non_existent" ) ) { + helloRef._non_existent(); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward.getObject(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloDIIClientStub resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + org.omg.CORBA.Object helloRef = ncRef.resolve(path); + + return new helloDIIClientStub( orb, helloRef ); + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/DIIRMILocalClient.java b/functional-tests/src/test/java/pi/clientinterceptor/DIIRMILocalClient.java new file mode 100644 index 000000000..5b43052e9 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/DIIRMILocalClient.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; + +/** + * Tests DII RMI Local invocation + */ +public class DIIRMILocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloDIIClientStub helloRef; + + // Reference to hello object to be forwarded to: + private helloDIIClientStub helloRefForward; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + + try { + System.out.println( "====================================" ); + System.out.println( "Creating ORB for DII RMI Local test" ); + System.out.println( "====================================" ); + + final DIIRMILocalClient client = new DIIRMILocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server + // using the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new OldRMILocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientInterceptor(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward.getObject(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloDIIClientStub resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + org.omg.CORBA.Object helloRef = ncRef.resolve(path); + + return new helloDIIClientStub( orb, helloRef ); + } + + /** + * Overridden from ClientCommon. Resets the servant after each + * invocation. + */ + protected void testInvocation( String name, + int mode, + String correctOrder, + String methodName, + boolean shouldInvokeTarget, + boolean exceptionExpected, + boolean forwardExpected ) + throws Exception + { + super.testInvocation( name, mode, correctOrder, methodName, + shouldInvokeTarget, + exceptionExpected, + forwardExpected ); + + // Reset the servant: + helloRef.resetServant(); + } +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/OldRMILocalServer.java b/functional-tests/src/test/java/pi/clientinterceptor/OldRMILocalServer.java new file mode 100644 index 000000000..ed2a90e7d --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/OldRMILocalServer.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test. Uses old _*ImplBase skeletons. + */ +public class OldRMILocalServer + implements Observer +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public void run( com.sun.corba.ee.spi.orb.ORB orb, java.lang.Object syncObject, + Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + out.println( "+ Creating and binding hello objects..." ); + rebindObjects(); + + // no handshake required here: + //out.println("Server is ready."); + //out.flush(); + + // Notify client to wake up: + synchronized( syncObject ) { + syncObject.notifyAll(); + } + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloOldRMIIIOP obj = new helloOldRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + + // Add this server as an observer so that when resetServant is called + // we can rebind. + helloDelegate delegate = obj.getDelegate(); + delegate.addObserver( this ); + } + + private void rebindObjects() + throws Exception + { + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + } + + public void update( Observable o, java.lang.Object arg ) { + try { + rebindObjects(); + } + catch( Exception e ) { + System.err.println( "rebindObjects() failed! " + e ); + throw new RuntimeException( "rebindObjects failed!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/OldRMIServer.java b/functional-tests/src/test/java/pi/clientinterceptor/OldRMIServer.java new file mode 100644 index 000000000..f79b57b29 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/OldRMIServer.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test. Uses old _*ImplBase skeletons. + */ +public class OldRMIServer + implements InternalProcess +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public static void main(String args[]) { + try { + (new OldRMIServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + out.println( "+ Creating and binding hello objects..." ); + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloOldRMIIIOP obj = new helloOldRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/POAClient.java b/functional-tests/src/test/java/pi/clientinterceptor/POAClient.java new file mode 100644 index 000000000..7d3733cc3 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/POAClient.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; + +/** + * Tests POA Remote invocation + */ +public class POAClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private hello helloRef; + + // Reference to hello object to be forwarded to: + private hello helloRefForward; + + public static void main(String args[]) { + try { + (new POAClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "================================" ); + out.println( "Invoking ORB for POA Remote test" ); + out.println( "================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + try { + // Test ClientInterceptor + testClientInterceptor(); + + // Test POA Special operations + testSpecialOperations(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "_is_a" ) ) { + helloRef._is_a( "IDL:ServerRequestInterceptor/goodbye:1.0" ); + } + else if( methodName.equals( "_get_interface_def" ) ) { + try { + helloRef._get_interface_def(); + } + catch( NO_IMPLEMENT e ) { + // This is expected in our ORB. + } + } + else if( methodName.equals( "_non_existent" ) ) { + helloRef._non_existent(); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private hello resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path)); + + return helloRef; + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/POALocalClient.java b/functional-tests/src/test/java/pi/clientinterceptor/POALocalClient.java new file mode 100644 index 000000000..117addd9f --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/POALocalClient.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; + +/** + * Tests POA Local invocation (with a co-located orb) + */ +public class POALocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private hello helloRef; + + // Reference to hello object to be forwarded to: + private hello helloRefForward; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===============================" ); + System.out.println( "Creating ORB for POA Local test" ); + System.out.println( "===============================" ); + + final POALocalClient client = new POALocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new POALocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientInterceptor(); + + // Test POA Special operations + testSpecialOperations(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "_is_a" ) ) { + helloRef._is_a( "IDL:ServerRequestInterceptor/goodbye:1.0" ); + } + else if( methodName.equals( "_get_interface_def" ) ) { + try { + helloRef._get_interface_def(); + } + catch( NO_IMPLEMENT e ) { + // This is expected in our ORB. + } + } + else if( methodName.equals( "_non_existent" ) ) { + helloRef._non_existent(); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private hello resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path)); + + return helloRef; + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/POALocalServer.java b/functional-tests/src/test/java/pi/clientinterceptor/POALocalServer.java new file mode 100644 index 000000000..fbd120c12 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/POALocalServer.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; // hello interface + +public class POALocalServer { + // Set from run() + private PrintStream out; + + private static final String ROOT_POA = "RootPOA"; + + private POA rootPOA; + + private com.sun.corba.ee.spi.orb.ORB orb; + + public void run( com.sun.corba.ee.spi.orb.ORB orb, java.lang.Object syncObject, + Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.orb = orb; + + // Get the root POA: + rootPOA = null; + out.println( "Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object and helloForward object for POA remote case: + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + + // no handshake required here. + //out.println("Server is ready."); + //out.flush(); + + // notify client to wake up: + synchronized( syncObject ) { + syncObject.notifyAll(); + } + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public void createAndBind (String name) + throws Exception + { + // create servant and register it with the ORB + helloServant helloRef = new helloServant( out ); + + byte[] id = rootPOA.activate_object(helloRef); + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/POAServer.java b/functional-tests/src/test/java/pi/clientinterceptor/POAServer.java new file mode 100644 index 000000000..73dc30478 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/POAServer.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; // hello interface + +public class POAServer + implements InternalProcess +{ + // Set from run() + private PrintStream out; + + private static final String ROOT_POA = "RootPOA"; + + private POA rootPOA; + + private com.sun.corba.ee.spi.orb.ORB orb; + + public static void main(String args[]) { + try { + (new POAServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "Invoking ORB" ); + out.println( "============" ); + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + // Get the root POA: + rootPOA = null; + out.println( "Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object and helloForward object for POA remote case: + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public void createAndBind (String name) + throws Exception + { + // create servant and register it with the ORB + helloServant helloRef = new helloServant( out ); + + byte[] id = rootPOA.activate_object(helloRef); + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/RMIClient.java b/functional-tests/src/test/java/pi/clientinterceptor/RMIClient.java new file mode 100644 index 000000000..5204e7593 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/RMIClient.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.rmi.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; +import javax.rmi.*; + +public class RMIClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloIF helloRef; + + // Reference to hello object to be forwarded to: + private helloIF helloRefForward; + + // Initial naming context + InitialContext initialNamingContext; + + // Names for JNDI lookup: + public static final String NAME1 = "hello2"; + public static final String NAME2 = "hello2Forward"; + + public static void main(String args[]) { + try { + (new RMIClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "===================================" ); + out.println( "Instantiating ORB for RMI/IIOP test" ); + out.println( "===================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + try { + // Test ClientInterceptor + testClientInterceptor(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + try { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + } + catch( RemoteException e ) { + throw (Exception)e.detail; + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - " + NAME1 ); + helloRef = resolve( NAME1 ); + out.println( " - " + NAME2 ); + helloRefForward = resolve( NAME2 ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = + (org.omg.CORBA.Object)helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloIF resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } + + /** + * Overridden from ClientCommon. Oneway calls are not supported. + */ + protected void testInvocation( String name, int mode, + String correctOrder, + String methodName, + boolean shouldInvokeTarget, + boolean exceptionExpected, + boolean forwardExpected ) + throws Exception + { + if( !methodName.equals( "sayOneway" ) ) { + super.testInvocation( name, mode, correctOrder, methodName, + shouldInvokeTarget, + exceptionExpected, + forwardExpected ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/RMILocalClient.java b/functional-tests/src/test/java/pi/clientinterceptor/RMILocalClient.java new file mode 100644 index 000000000..a9ee3d1cc --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/RMILocalClient.java @@ -0,0 +1,248 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ClientRequestInterceptor.*; + +/** + * Tests RMI Local invocation (with a co-located orb) + */ +public class RMILocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloIF helloRef; + + // Reference to hello object to be forwarded to: + private helloIF helloRefForward; + + // Initial naming context + InitialContext initialNamingContext; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===============================" ); + System.out.println( "Creating ORB for RMI Local test" ); + System.out.println( "===============================" ); + + final RMILocalClient client = new RMILocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + // Inform JNDI provider of the ORB to use and create initial + // naming context: + System.out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", client.orb ); + client.initialNamingContext = new InitialContext( env ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new RMILocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientInterceptor(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + try { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + } + catch( RemoteException e ) { + throw (Exception)e.detail; + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInterceptor tests + */ + protected void testClientInterceptor() + throws Exception + { + super.testClientInterceptor(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( "Hello1" ); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = + (org.omg.CORBA.Object)helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloIF resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } + + /** + * Overridden from ClientCommon. Oneway calls are not supported. + */ + protected void testInvocation( String name, int mode, + String correctOrder, + String methodName, + boolean shouldInvokeTarget, + boolean exceptionExpected, + boolean forwardExpected ) + throws Exception + { + if( !methodName.equals( "sayOneway" ) ) { + super.testInvocation( name, mode, correctOrder, methodName, + shouldInvokeTarget, + exceptionExpected, + forwardExpected ); + + // Reset the servant: + helloRef.resetServant(); + } + } + + +} + + + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/RMILocalServer.java b/functional-tests/src/test/java/pi/clientinterceptor/RMILocalServer.java new file mode 100644 index 000000000..769569b15 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/RMILocalServer.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test + */ +public class RMILocalServer + implements Observer +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public void run( com.sun.corba.ee.spi.orb.ORB orb, java.lang.Object syncObject, + Properties environment, String args[], + PrintStream out, PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + rebindObjects(); + + // no handshake required here: + //out.println("Server is ready."); + //out.flush(); + + // Notify client to wake up: + synchronized( syncObject ) { + syncObject.notifyAll(); + } + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + private void rebindObjects() + throws Exception + { + out.println( "+ Creating and binding hello objects..." ); + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloRMIIIOP obj = new helloRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + + // Add this server as an observer so that when resetServant is called + // we can rebind. + helloDelegate delegate = obj.getDelegate(); + delegate.addObserver( this ); + } + + public void update( Observable o, java.lang.Object arg ) { + try { + rebindObjects(); + } + catch( Exception e ) { + System.err.println( "rebindObjects() failed! " + e ); + throw new RuntimeException( "rebindObjects failed!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/RMIServer.java b/functional-tests/src/test/java/pi/clientinterceptor/RMIServer.java new file mode 100644 index 000000000..e5fcb844e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/RMIServer.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test + */ +public class RMIServer + implements InternalProcess +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public static void main(String args[]) { + try { + (new RMIServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + out.println( "+ Creating and binding hello objects..." ); + createAndBind( RMIClient.NAME1 ); + createAndBind( RMIClient.NAME2 ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloRMIIIOP obj = new helloRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/SampleClientRequestInterceptor.java b/functional-tests/src/test/java/pi/clientinterceptor/SampleClientRequestInterceptor.java new file mode 100644 index 000000000..74386c32b --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/SampleClientRequestInterceptor.java @@ -0,0 +1,230 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.RequestInfo; + +//import ORBInitTest.*; + +/** + * Sample ClientRequestInterceptor for use in testing + */ +public class SampleClientRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor +{ + // This string is modified from within this class and from Client.java. + // It keeps track of which method was invoked when by appending + // two-letter codes in succession. The following codes are used + // represents the name of the interceptor invoked. This is + // used to check order of interceptor invocation. + // + // sr = send_request + // sp = send_poll + // rr = receive_reply + // re = receive_exception + // ro = receive_other + // For example, sr1sr2rr2rr1 would indicate a normal invocation. + public static String invocationOrder = ""; + + // This attribute is set by Client.java to indicate how this interceptor + // should behave. There are a predetermined set of behavior values: + // MODE_NORMAL - All interceptors exit without throwing an Exception + // MODE_SYSTEM_EXCEPTION - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a SYSTEM_EXCEPTION during send_request. + // MODE_FORWARD_REQUEST - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a ForwardRequest during send_request. + // MODE_RECEIVE_REPLY_EXCEPTION - Interceptors 3 and 1 return normally, + // while interceptor 2 throws a SystemException during receive_reply. + // MODE_RECEIVE_EXCEPTION_FORWARD - Interceptors 3 and 1 return + // normally, while interceptor 2 throws a ForwardRequest during + // receive_exception. + // MODE_RECEIVE_OTHER_EXCEPTION - Interceptors 3 and 1 return + // normally, while interceptor 2 throws a SystemException during + // receive_other. + public static int testMode; + + public static final int MODE_NORMAL = 0; + public static final int MODE_SYSTEM_EXCEPTION = 1; + public static final int MODE_FORWARD_REQUEST = 2; + public static final int MODE_RECEIVE_REPLY_EXCEPTION = 3; + public static final int MODE_RECEIVE_EXCEPTION_FORWARD = 4; + public static final int MODE_RECEIVE_OTHER_EXCEPTION = 5; + + private String name; + + // Counter to make sure each start is matched by an end + public static int callCounter = 0; + + public static boolean enabled = false; + + public static boolean printPointEntryFlag = false; + + private void printPointEntry( String message, RequestInfo ri ) + { + if (printPointEntryFlag) { + System.out.println(message + + " " + ri.request_id() + + " " + ri.operation() + + " " + callCounter); + } + } + + public SampleClientRequestInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void send_request (ClientRequestInfo ri) + throws ForwardRequest + { + // Count all calls (and print entry), not just test ones, + // to make sure all ORB internal calls are balanced. + callCounter++; // Starting point - add + printPointEntry("send_request", ri); + + if( !enabled ) return; + + // Log that we did a send_request on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "sr" + name; + + // Only exhibit behavior if we are the initial object, not the + // forwarded object. + if( name.equals( "2" ) && + !TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) + { + if( testMode == MODE_SYSTEM_EXCEPTION ) { + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + + // Since this starting point is throwing an exception + // an ending point will not be called. Therefore, + // explicitly decrement the call counter. + callCounter--; + throw new UNKNOWN( "Valid Test Result" ); + } + else if( testMode == MODE_FORWARD_REQUEST ) { + // If we are the second interceptor, it is our turn to + // throw a ForwardRequest here. + + // Since this starting point is throwing an exception + // an ending point will not be called. Therefore, + // explicitly decrement the call counter. + callCounter--; + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + } + } + + public void send_poll (ClientRequestInfo ri) + { + callCounter++; // Starting point - add + printPointEntry("send_poll", ri); + + if( !enabled ) return; + + // Log that we did a send_poll on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "sp" + name; + } + + public void receive_reply (ClientRequestInfo ri) + { + // Ending points have the print/call statements reverse intentionally. + printPointEntry("receive_reply", ri); + callCounter--; // Ending point - subtracm + + if( !enabled ) return; + + // Log that we did a receive_reply on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "rr" + name; + + // Only exhibit behavior if we are the initial object, not the + // forwarded object. + if( name.equals( "2" ) && + !TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) + { + if( testMode == MODE_RECEIVE_REPLY_EXCEPTION ) { + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + throw new UNKNOWN( "Valid Test Result" ); + } + } + } + + public void receive_exception (ClientRequestInfo ri) + throws ForwardRequest + { + printPointEntry("receive_exception", ri); + callCounter--; // Ending point - subtract + + if( !enabled ) return; + + // Log that we did a receive_exception on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "re" + name; + + // Only exhibit behavior if we are the initial object, not the + // forwarded object. + if( name.equals( "2" ) && + !TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) + { + if( testMode == MODE_RECEIVE_EXCEPTION_FORWARD ) { + // If we are the second interceptor, it is our turn to + // throw a ForwardRequest here. + + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + } + } + + public void receive_other (ClientRequestInfo ri) + throws ForwardRequest + { + printPointEntry("receive_other", ri); + callCounter--; // Ending point - subtract + + if( !enabled ) return; + + // Log that we did a receive_other on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "ro" + name; + + // Only exhibit behavior if we are the initial object, not the + // forwarded object. + if( name.equals( "2" ) && + !TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) + { + if( testMode == MODE_RECEIVE_OTHER_EXCEPTION ) { + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + throw new UNKNOWN( "Valid Test Result" ); + } + } + } +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/TestInitializer.java b/functional-tests/src/test/java/pi/clientinterceptor/TestInitializer.java new file mode 100644 index 000000000..891ef3fc2 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/TestInitializer.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +import ClientRequestInterceptor.*; // hello interface + +/** + * Registers the necessary Client Interceptors to test + * ClientRequestInterceptor. + */ +public class TestInitializer + extends org.omg.CORBA.LocalObject + implements ORBInitializer +{ + + // The PrintStream to pass to the ClientRequestInterceptor for output. + // This is set from Client.java statically. + static PrintStream out; + + /** The ORB to pass to the ClientRequestInterceptor */ + static ORB orb; + + // Where to forward the caller on a ForwardRequest + static org.omg.CORBA.Object helloRefForward; + + /** + * Creates a TestInitializer + */ + public TestInitializer() { + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + ClientRequestInterceptor interceptor1; + ClientRequestInterceptor interceptor2; + ClientRequestInterceptor interceptor3; + + interceptor1 = new SampleClientRequestInterceptor( "1" ); + interceptor2 = new SampleClientRequestInterceptor( "2" ); + interceptor3 = new SampleClientRequestInterceptor( "3" ); + + try { + out.println( " - post_init: adding 3 client interceptors..." ); + info.add_client_request_interceptor( interceptor1 ); + info.add_client_request_interceptor( interceptor2 ); + info.add_client_request_interceptor( interceptor3 ); + } + catch( DuplicateName e ) { + out.println( " - post_init: received DuplicateName!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/helloDIIClientStub.java b/functional-tests/src/test/java/pi/clientinterceptor/helloDIIClientStub.java new file mode 100644 index 000000000..9f6d060fe --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/helloDIIClientStub.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * Utility class to encapsulate the logic to make DII calls on the + * hello interface. + */ +public class helloDIIClientStub { + + /** The CORBA object to make DII calls on */ + private org.omg.CORBA.Object object; + + /** The ORB to use to create objects */ + private ORB orb; + + /** + * Creates a new helloDIIClientStub which will make DII calls on the given + * corba object, and will create objects using the given ORB. + */ + public helloDIIClientStub( ORB orb, org.omg.CORBA.Object object ) { + this.object = object; + this.orb = orb; + } + + public org.omg.CORBA.Object getObject() { + return object; + } + + String sayHello() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_string( "dummy" ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "sayHello", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_string(); + } + + String saySystemException() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_string( "dummy" ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "saySystemException", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_string(); + } + + void sayOneway() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // No result parameter: + + // Invoke method as a oneway: + Request thisReq = object._create_request( null, "sayOneway", + argList, null ); + thisReq.send_oneway(); + } + + boolean _is_a( String repository_id ) { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + Any a1 = orb.create_any(); + a1.insert_string( repository_id ); + argList.add_value( "repository_id", a1, ARG_IN.value ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_boolean( true ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "_is_a", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_boolean(); + } + + boolean _non_existent() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_boolean( false ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "_non_existent", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_boolean(); + } + + org.omg.CORBA.Object _get_interface_def() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_Object( (org.omg.CORBA.Object)null ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "_get_interface_def", + argList, resultVal ); + + try { + thisReq.invoke(); + } + catch( BAD_OPERATION e ) { + // expected, since we do not implement _get_interface_def in our ORB. + } + + // Return result: + result = thisReq.result().value(); + return result.extract_Object(); + } + + void clearInvoked() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // No result parameter: + + // Invoke method: + Request thisReq = object._create_request( null, "clearInvoked", + argList, null ); + thisReq.invoke(); + } + + boolean wasInvoked() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_boolean( false ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "wasInvoked", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_boolean(); + } + + void resetServant() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // No result parameter: + + // Invoke method: + Request thisReq = object._create_request( null, "resetServant", + argList, null ); + thisReq.invoke(); + } + +} + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/helloDelegate.java b/functional-tests/src/test/java/pi/clientinterceptor/helloDelegate.java new file mode 100644 index 000000000..bc2230cbb --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/helloDelegate.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; + +import java.io.*; +import javax.rmi.*; +import javax.naming.*; +import java.util.*; + +import ClientRequestInterceptor.*; // hello interface + +/** + * Contains the actual implementations of hello operations. + */ +public class helloDelegate extends Observable implements helloIF { + private boolean invoked = false; + private PrintStream out = null; + + public helloDelegate( PrintStream out ) { + super(); + this.out = out; + } + + public String sayHello() { + out.println( "helloServant: sayHello() invoked" ); + invoked = true; + return "Hello, world!"; + } + + public String saySystemException() { + out.println( "helloServant: saySystemException() invoked" ); + invoked = true; + throw new UNKNOWN( "Valid Test Result" ); + } + + // This will cause a receive_reply to be invoked since this + // is a one-way method. + public void sayOneway() { + out.println( "helloServant: sayOneway() invoked" ); + invoked = true; + } + + public void clearInvoked() { + invoked = false; + } + + public boolean wasInvoked() { + return invoked; + } + + public void resetServant() { + setChanged(); + notifyObservers(); + } +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/helloIF.java b/functional-tests/src/test/java/pi/clientinterceptor/helloIF.java new file mode 100644 index 000000000..e4a6d004d --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/helloIF.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * Hello interface for RMI-IIOP version of test + */ +public interface helloIF + extends Remote +{ + String sayHello () throws RemoteException; + String saySystemException () throws RemoteException; + void sayOneway () throws RemoteException; + void clearInvoked () throws RemoteException; + boolean wasInvoked () throws RemoteException; + void resetServant () throws RemoteException; +} + diff --git a/functional-tests/src/test/java/pi/clientinterceptor/helloOldRMIIIOP.java b/functional-tests/src/test/java/pi/clientinterceptor/helloOldRMIIIOP.java new file mode 100644 index 000000000..595e95e45 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/helloOldRMIIIOP.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; + +import java.io.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +import ClientRequestInterceptor.*; // hello interface + +/** + * ClientDelegate implementation with old stubs. + */ +public class helloOldRMIIIOP + extends _helloImplBase +{ + // Contains the actual implementation of the hello interface. + private helloDelegate delegate = null; + + public helloOldRMIIIOP( PrintStream out ) + throws RemoteException + { + super(); + this.delegate = new helloDelegate( out ); + } + + public helloDelegate getDelegate() { + return delegate; + } + + public String sayHello() { + return delegate.sayHello(); + } + + public String saySystemException() { + return delegate.saySystemException(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void clearInvoked() { + delegate.clearInvoked(); + } + + public boolean wasInvoked() { + return delegate.wasInvoked(); + } + + public void resetServant() { + delegate.resetServant(); + } + +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/helloRMIIIOP.java b/functional-tests/src/test/java/pi/clientinterceptor/helloRMIIIOP.java new file mode 100644 index 000000000..841475c10 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/helloRMIIIOP.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; + +import java.io.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +import ClientRequestInterceptor.*; // hello interface + +/** + * RMI/IIOP implementation. + */ +public class helloRMIIIOP + extends PortableRemoteObject + implements helloIF +{ + // Contains the actual implementation of the hello interface. + private helloDelegate delegate = null; + + public helloRMIIIOP( PrintStream out ) + throws RemoteException + { + super(); + this.delegate = new helloDelegate( out ); + } + + public helloDelegate getDelegate() { + return this.delegate; + } + + public String sayHello() { + return delegate.sayHello(); + } + + public String saySystemException() { + return delegate.saySystemException(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void clearInvoked() { + delegate.clearInvoked(); + } + + public boolean wasInvoked() { + return delegate.wasInvoked(); + } + + public void resetServant() { + delegate.resetServant(); + } +} diff --git a/functional-tests/src/test/java/pi/clientinterceptor/helloServant.java b/functional-tests/src/test/java/pi/clientinterceptor/helloServant.java new file mode 100644 index 000000000..869b90a03 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientinterceptor/helloServant.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientinterceptor; + +import org.omg.CORBA.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInterceptor.*; // hello interface + +/** + * Servant implementation. + */ +public class helloServant + extends helloPOA +{ + // contains implementations of methods. + private helloDelegate delegate; + + public helloServant( PrintStream out ) { + super(); + delegate = new helloDelegate( out ); + } + + public String sayHello() { + return delegate.sayHello(); + } + + public String saySystemException() { + return delegate.saySystemException(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void clearInvoked() { + delegate.clearInvoked(); + } + + public boolean wasInvoked() { + return delegate.wasInvoked(); + } + + public void resetServant() { + delegate.resetServant(); + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/AttributesValidStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/AttributesValidStrategy.java new file mode 100644 index 000000000..65862d33a --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/AttributesValidStrategy.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.Messaging.*; + +/** + * Strategy to test operations() + */ +public class AttributesValidStrategy + extends InterceptorStrategy +{ + + // The request count. We should be calling: + // 0 - sayHello + // 1 - saySystemException + // 2 - saySystemException. + private int count = 0; + + // The most recent operation name received. + private String operationName; + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + try { + super.send_request( interceptor, ri ); + + String validName = (count == 0) ? + "sayHello" : "saySystemException"; + this.operationName = ri.operation(); + log( "send_request(): Expected operation name = " + validName ); + log( "send_request(): Actual operation name = " + + this.operationName ); + + if( !this.operationName.equals( validName ) ) { + fail( "Operation name not equal to expected name." ); + } + + checkSyncScope( "send_request", ri ); + + // Check that within send_request, reply_status + // throws BAD_INV_ORDER: + try { + short replyStatus = ri.reply_status(); + fail( "send_request(): Should not be able to execute " + + "reply_status() here" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_request(): Tried reply_status() and received " + + "BAD_INV_ORDER (ok)" ); + } + + count++; + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // never executed in our orb. + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + try { + super.receive_reply( interceptor, ri ); + checkOperation( "receive_reply", ri.operation() ); + checkSyncScope( "receive_reply", ri ); + + // Check that within receive_reply, reply_status is SUCCESSFUL. + boolean[] validValues = { true, false, false, false, false }; + checkReplyStatus( "receive_reply", ri, validValues ); + } + catch( Exception ex ) { + failException( "receive_reply", ex ); + } + } + + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + try { + super.receive_exception( interceptor, ri ); + checkOperation( "receive_exception", ri.operation() ); + checkSyncScope( "receive_exception", ri ); + + // Check that within receive_exception, reply_status is + // SYSTEM_EXCEPTION or USER_EXCEPTION: + boolean[] validValues = { false, true, true, false, false }; + checkReplyStatus( "receive_exception", ri, validValues ); + } + catch( Exception ex ) { + failException( "receive_exception", ex ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + try { + super.receive_other( interceptor, ri ); + checkOperation( "receive_other", ri.operation() ); + checkSyncScope( "receive_other", ri ); + + // Check that within receive_other, reply_status is + // SUCCESSFUL, LOCATION_FORWARD, or TRANSPORT_RETRY. + boolean[] validValues = { true, false, false, true, true }; + checkReplyStatus( "receive_other", ri, validValues ); + } + catch( Exception ex ) { + failException( "receive_other", ex ); + } + } + + private void checkOperation( String method, String opName ) { + log( method + "(): Actual operation name = " + opName ); + if( !opName.equals( this.operationName ) ) { + fail( "Operation name in " + method + " not equal to " + + "operation name in send_request()" ); + } + } + + private void checkSyncScope( String method, ClientRequestInfo ri ) { + short syncScope = ri.sync_scope(); + log( method + "(): sync_scope() returns " + syncScope ); + if( syncScope != SYNC_WITH_TRANSPORT.value ) { + fail( "sync_scope() is not SYNC_WITH_TRANSPORT" ); + } + } + + private void checkReplyStatus( String method, ClientRequestInfo ri, + boolean[] validValues ) + { + int i; + + // Describe to user which values are valid: + String validDesc = "{ "; + for( i = 0; i < validValues.length; i++ ) { + validDesc += "" + validValues[i] + " "; + } + validDesc += "}"; + log( method + "(): Valid values: " + validDesc ); + + short replyStatus = ri.reply_status(); + log( method + "(): Actual value: " + replyStatus ); + + if( !validValues[replyStatus] ) { + fail( method + "(): Not a valid reply status." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/ClientCommon.java b/functional-tests/src/test/java/pi/clientrequestinfo/ClientCommon.java new file mode 100644 index 000000000..1699ac797 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/ClientCommon.java @@ -0,0 +1,270 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import java.io.PrintStream; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; + +/** + * Common methods for Client implementations in this test to use + */ +abstract public class ClientCommon +{ + // Set from run() + protected com.sun.corba.ee.spi.orb.ORB orb; + + // Set from run() + public PrintStream out; + + // Set from run() + public PrintStream err; + + // Strategy for current run + protected InterceptorStrategy interceptorStrategy; + + // Strategy for current run + protected InvokeStrategy invokeStrategy; + + // The current Client being executed + public static ClientCommon client; + + JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + + protected void finish() { + helper.done() ; + } + + /** + * Creates a com.sun.corba.ee.spi.orb.ORB and notifies the TestInitializer of its presence + */ + protected void createORB( String[] args ) { + // create and initialize the ORB with initializer + String testInitializer = "pi.clientrequestinfo.TestInitializer"; + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + this.orb = (com.sun.corba.ee.spi.orb.ORB)ORB.init(args, props); + TestInitializer.orb = this.orb; + } + + /** + * Perform common ClientRequestInfo tests + */ + protected void testClientRequestInfo() throws Exception { + out.println(); + out.println( "Running common ClientRequestInfo tests" ); + out.println( "======================================" ); + + client = this; + + testRequestId(); + testAttributesValid(); + testOneWay(); + testServiceContext(); + + testForwardReference(); + + // _REVISIT_ Waiting on new IOR code to be checked in. + //testEffectiveProfile(); + + testException(); + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + abstract protected void clearInvoked() throws Exception; + + /** + * Invoke the method with the given name on the object + */ + abstract protected void invokeMethod( String name ) throws Exception; + + /** + * Return true if the method was invoked + */ + abstract protected boolean wasInvoked() throws Exception; + + /** + * Return true if the method was forwarded + */ + abstract protected boolean didForward() throws Exception; + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation. + */ + abstract protected void resolveReferences() throws Exception; + + /** + * Prepars for a test invocation by setting the interceptor strategy + * and the invocation and forward objects. + */ + protected void setParameters( InterceptorStrategy interceptorStrategy, + InvokeStrategy invokeStrategy ) + { + out.println( " - Using interceptor strategy " + + interceptorStrategy.getClass().getName() ); + out.println( " - Using invocation strategy " + + invokeStrategy.getClass().getName() ); + this.interceptorStrategy = interceptorStrategy; + this.invokeStrategy = invokeStrategy; + } + + /** + * Executes the test case set up with the parameters in setParameters + */ + protected void runTestCase( String testName ) + throws Exception + { + helper.start( testName ) ; + + try { + out.println( " - Resolving references." ); + resolveReferences(); + out.println( " - Executing test " + testName + "." ); + SampleClientRequestInterceptor.strategy = interceptorStrategy; + invokeStrategy.invoke(); + if( interceptorStrategy.failed ) { + throw new RuntimeException( interceptorStrategy.failReason ); + } + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /* + ********************************************************************* + * Test assertions + *********************************************************************/ + + /** + * Tests request_id(). + */ + protected void testRequestId() + throws Exception + { + out.println( "+ Testing request_id()..." ); + + // Test request_id is same for request as for reply: + InterceptorStrategy interceptorStrategy = new RequestId1Strategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "request_id.1" ); + + // Test request_id is unique for each currently active + // request/reply sequence: + interceptorStrategy = new RequestId2Strategy(); + invokeStrategy = new InvokeRecursive(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "request_id.2" ); + } + + /** + * Tests various attributes are valid. Attributes tested: + * operation(), sync_scope(), reply_status() + */ + protected void testAttributesValid() + throws Exception + { + out.println( "+ Testing for valid attributes..." ); + + InterceptorStrategy interceptorStrategy = + new AttributesValidStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "attributes_valid" ); + } + + /** + * Tests response_expected() by invoking a oneWay method + */ + protected void testOneWay() + throws Exception + { + out.println( "+ Testing response_expected() with one way..." ); + + InterceptorStrategy interceptorStrategy = new OneWayStrategy(); + InvokeStrategy invokeStrategy = new InvokeOneWay(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "response_expected" ); + } + + /** + * Tests forward_reference() + */ + protected void testForwardReference() + throws Exception + { + out.println( "+ Testing forward_reference()..." ); + + InterceptorStrategy interceptorStrategy = + new ForwardReferenceStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAllForward(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "forward_reference" ); + } + + /** + * Tests get_request_service_context(), get_reply_service_context(). + * and add_request_service_context(). + */ + protected void testServiceContext() + throws Exception + { + out.println( "+ Testing {get|add}_*_service_context()..." ); + + InterceptorStrategy interceptorStrategy = + new ServiceContextStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "{get|add}_*_service_context" ); + } + + /** + * Tests effective_profile() + */ + protected void testEffectiveProfile() + throws Exception + { + out.println( "+ Testing effective_profile()..." ); + + InterceptorStrategy interceptorStrategy = + new EffectiveProfileStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "effective_profile" ); + } + + /** + * Tests received_exception() and received_exception_id() + */ + protected void testException() + throws Exception + { + out.println( "+ Testing received_exception[_id]()..." ); + + InterceptorStrategy interceptorStrategy = + new ExceptionStrategy(); + InvokeStrategy invokeStrategy = new InvokeExceptions(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "received_exception[_id]" ); + } + +} + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/ClientRequestInfoTest.java b/functional-tests/src/test/java/pi/clientrequestinfo/ClientRequestInfoTest.java new file mode 100644 index 000000000..138ffe65b --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/ClientRequestInfoTest.java @@ -0,0 +1,282 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import corba.framework.*; +import java.util.*; + +/** + * Tests ClientRequestInfo as per Portable Interceptors spec + * orbos/99-12-02, section 5.4. See pi/assertions.html for Assertions + * covered in this test. + */ +public class ClientRequestInfoTest + extends CORBATest +{ + // Set to true if at least one test fails. + private boolean failed = false; + + Controller orbd; + + public static String[] rmicClasses = { + "pi.clientrequestinfo.helloRMIIIOP" + }; + + protected void doTest() + throws Throwable + { + startORBD(); + System.out.println(); + System.out.println( " \t\t\t\tLocal\t\tRemote" ); + + beginTest( "[POA]\t\t\t" ); + testPOALocal(); + endTest( "\t\t" ); + testPOARemote(); + endTest( "\n" ); + + beginTest( "[POA DII]\t\t\t" ); + testPOADIILocal(); + endTest( "\t\t" ); + testPOADIIRemote(); + endTest( "\n" ); + + beginTest( "[RMI]\t\t\t" ); + testRMILocal(); + endTest( "\t\t" ); + testRMIRemote(); + endTest( "\n" ); + + beginTest( "[ClientDelegate DII]\t" ); + testClientDelegateDIILocal(); + endTest( "\t\t" ); + testClientDelegateDIIRemote(); + endTest( "\n" ); + + stopORBD(); + System.out.println(); + System.out.print( " Final Result: " ); + if( failed ) { + throw new RuntimeException( "Errors detected" ); + } + } + + private void testPOALocal() + throws Throwable + { + Controller client; + + try { + // Start only a client - the client will create the server. + client = createClient( + "pi.clientrequestinfo.POALocalClient", + "poalocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testPOARemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientrequestinfo.POAServer", + "poa-server" ); + server.start(); + client = createClient( "pi.clientrequestinfo.POAClient", + "poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testPOADIILocal() + throws Throwable + { + Controller client; + + try { + // Start only a client - the client will create the server. + client = createClient( "pi.clientrequestinfo.DIIPOALocalClient", + "diipoalocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testPOADIIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientrequestinfo.POAServer", + "dii-poa-server" ); + server.start(); + client = createClient( "pi.clientrequestinfo.DIIPOAClient", + "dii-poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testRMILocal() + throws Throwable + { + Controller client; + + try { + // Start only a client - the client will create the server. + client = createClient( "pi.clientrequestinfo.RMILocalClient", + "rmilocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testRMIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientrequestinfo.RMIServer", + "rmi-server" ); + server.start(); + client = createClient( "pi.clientrequestinfo.RMIClient", + "rmi-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testClientDelegateDIILocal() + throws Throwable + { + Controller client; + + try { + // Start only a client - the client will create the server. + client = createClient( "pi.clientrequestinfo.DIIRMILocalClient", + "diirmilocal" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + } + finally { + } + } + + private void testClientDelegateDIIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.clientrequestinfo.OldRMIServer", + "dii-rmi-server" ); + server.start(); + client = createClient( "pi.clientrequestinfo.DIIPOAClient", + "dii-rmi-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void beginTest( String name ) + throws Exception + { + System.out.print( " " + name ); + } + + private void endTest( String terminator ) + throws Exception + { + System.out.print( terminator ); + } + + private void startORBD() + throws Exception + { + orbd = createORBD(); + orbd.start(); + } + + private void stopORBD() + throws Exception + { + orbd.stop(); + pause(); + } + + + private void printEndTest( Controller client, Controller server ) + throws Throwable + { + if( (server != null) && server.finished() ) { + System.out.print( "FAILED, Server crashed" ); + failed = true; + } + else if( client.exitValue() != Controller.SUCCESS ) { + System.out.print( "FAILED, Client exit value = " + + client.exitValue() ); + failed = true; + } + else { + System.out.print( "PASSED" ); + } + } + + // Pause a little to allow all processes to fully terminate. + private void pause() { + try { + Thread.sleep( 2000 ); + } + catch( InterruptedException e ) { + // ignore. + } + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/DIIPOAClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/DIIPOAClient.java new file mode 100644 index 000000000..d846b150e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/DIIPOAClient.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; + +/** + * Tests DII POA Remote invocation + */ +public class DIIPOAClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloDIIClientStub helloRef; + + // Reference to hello object to be forwarded to: + private helloDIIClientStub helloRefForward; + + public static void main(String args[]) { + try { + (new DIIPOAClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "====================================" ); + out.println( "Creating ORB for DII POA Remote test" ); + out.println( "====================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestRequestInfo tests + */ + protected void testClientRequestInfo() + throws Exception + { + super.testClientRequestInfo(); + + // Perform DII-specific tests: + testDynamic(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = helloRef.getObject(); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward.getObject(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloDIIClientStub resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + org.omg.CORBA.Object helloRef = ncRef.resolve( path ); + + return new helloDIIClientStub( orb, helloRef ); + } + + /** + * Test DII-specific features + */ + protected void testDynamic() + throws Exception + { + out.println( "+ Testing DII ClientRequestInfo methods..." ); + + InterceptorStrategy interceptorStrategy = + new DynamicStrategy(); + InvokeStrategy invokeStrategy = new InvokeDynamic(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "dii_dynamic" ); + } + + /** + * When asked to run exception tests, run in DII mode. + * This will skip any UserException-related tests. + */ + protected void testException() + throws Exception + { + out.println( "+ Testing received_exception[_id]() in DII mode..." ); + + InterceptorStrategy interceptorStrategy = + new ExceptionStrategy( true ); + InvokeStrategy invokeStrategy = new InvokeExceptions(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "received_exception[_id]" ); + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/DIIPOALocalClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/DIIPOALocalClient.java new file mode 100644 index 000000000..78a20d042 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/DIIPOALocalClient.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; + +/** + * Tests DII POA Local invocation (with a co-located orb) + */ +public class DIIPOALocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloDIIClientStub helloRef; + + // Reference to hello object to be forwarded to: + private helloDIIClientStub helloRefForward; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===================================" ); + System.out.println( "Creating ORB for DII POA Local test" ); + System.out.println( "===================================" ); + + final DIIPOALocalClient client = new DIIPOALocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new POALocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInfo tests + */ + protected void testClientRequestInfo () + throws Exception + { + super.testClientRequestInfo(); + + // Test DII dynamic calls: + testDynamic(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = helloRef.getObject(); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward.getObject(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloDIIClientStub resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + org.omg.CORBA.Object helloRef = ncRef.resolve( path ); + + return new helloDIIClientStub( orb, helloRef ); + } + + /** + * Test DII-specific features + */ + protected void testDynamic() + throws Exception + { + out.println( "+ Testing DII ClientRequestInfo methods..." ); + + InterceptorStrategy interceptorStrategy = + new DynamicStrategy(); + InvokeStrategy invokeStrategy = new InvokeDynamic(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "dii_dynamic" ); + } + + /** + * When asked to run exception tests, run in DII mode. + * This will skip any UserException-related tests. + */ + protected void testException() + throws Exception + { + out.println( "+ Testing received_exception[_id]() in DII mode..." ); + + InterceptorStrategy interceptorStrategy = + new ExceptionStrategy( true ); + InvokeStrategy invokeStrategy = new InvokeExceptions(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "received_exception[_id]" ); + } +} + + + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/DIIRMILocalClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/DIIRMILocalClient.java new file mode 100644 index 000000000..a531c5241 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/DIIRMILocalClient.java @@ -0,0 +1,278 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; + +/** + * Tests DII RMI Local invocation (with a co-located orb) + */ +public class DIIRMILocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloDIIClientStub helloRef; + + // Reference to hello object to be forwarded to: + private helloDIIClientStub helloRefForward; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===================================" ); + System.out.println( "Creating ORB for DII RMI Local test" ); + System.out.println( "===================================" ); + + final DIIRMILocalClient client = new DIIRMILocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new OldRMILocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInfo tests + */ + protected void testClientRequestInfo () + throws Exception + { + super.testClientRequestInfo(); + + // Test DII dynamic calls: + testDynamic(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = helloRef.getObject(); + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward.getObject(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloDIIClientStub resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + org.omg.CORBA.Object helloRef = ncRef.resolve( path ); + + return new helloDIIClientStub( orb, helloRef ); + } + + /** + * One-way test not applicable for RMI case. Override it. + */ + protected void testOneWay() throws Exception { + out.println( "+ OneWay test not applicable for RMI. Skipping..." ); + } + + /** + * Test DII-specific features + */ + protected void testDynamic() + throws Exception + { + out.println( "+ Testing DII ClientRequestInfo methods..." ); + + InterceptorStrategy interceptorStrategy = + new DynamicStrategy(); + InvokeStrategy invokeStrategy = new InvokeDynamic(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "dii_dynamic" ); + } + + /** + * When asked to run exception tests, run in DII mode. + * This will skip any UserException-related tests. + */ + protected void testException() + throws Exception + { + out.println( "+ Testing received_exception[_id]() in DII mode..." ); + + InterceptorStrategy interceptorStrategy = + new ExceptionStrategy( true ); + InvokeStrategy invokeStrategy = new InvokeExceptions(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "received_exception[_id]" ); + } + + /** + * Executes the test case set up with the parameters in setParameters + */ + protected void runTestCase( String testName ) + throws Exception + { + super.runTestCase( testName ); + + out.println( " + Resetting servants on server side" ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + helloRef.resetServant(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/DynamicStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/DynamicStrategy.java new file mode 100644 index 000000000..6faba8913 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/DynamicStrategy.java @@ -0,0 +1,348 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.Messaging.*; +import org.omg.Dynamic.*; + +import ClientRequestInfo.*; + +/** + * Strategy to test DII dynamic operations. This was originally its own + * test, but has been moved to this test to simulate a more realistic + * environment. + *

+ * This strategy will only work with DII calls. The following methods are + * tested: + *

    + *
  • arguments
  • + *
  • exceptions
  • + *
  • contexts
  • + *
  • operation_context
  • + *
  • result
  • + *
+ */ +public class DynamicStrategy + extends InterceptorStrategy +{ + // The request count. We should be calling: + // 0 - sayArguments + // 1 - sayUserException + // 2 - saySystemException. + private int count = 0; + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + try { + super.send_request( interceptor, ri ); + + if( count == 0 ) { + // sayArguments was just called. + testArguments( "send_request", "sayArguments", ri ); + testContexts( "send_request", "sayArguments", ri ); + + // Ensure result() is inaccessible. + try { + ri.result(); + fail( "send_request: Should not have been " + + "able to access result()" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_request: Could not access " + + "result() (ok)" ); + } + } + else if( count == 1 ) { + // sayUserException was just called. + testExceptions( "send_request", "sayUserException", ri ); + } + + count++; + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // never executed in our orb. + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + try { + super.receive_reply( interceptor, ri ); + + if( count == 1 ) { + // sayArguments was just called. + testArguments( "receive_reply", "sayArguments", ri ); + testContexts( "receive_reply", "sayArguments", ri ); + testResult( "receive_reply", "sayArguments", ri ); + } + else if( count == 2 ) { + // sayUserException was just called. + testExceptions( "receive_reply", "sayUserException", ri ); + } + } + catch( Exception ex ) { + failException( "receive_reply", ex ); + } + } + + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + try { + super.receive_exception( interceptor, ri ); + + if( count == 1 ) { + // Ensure arguments() is inaccessible. + try { + ri.arguments(); + fail( "receive_exception: Should not have been " + + "able to access arguments()" ); + } + catch( BAD_INV_ORDER e ) { + log( "receive_exception: Could not access " + + "arguments() (ok)" ); + } + + testContexts( "receive_exception", "sayArguments", ri ); + + // Ensure result() is inaccessible. + try { + ri.result(); + fail( "send_request: Should not have been " + + "able to access result()" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_request: Could not access " + + "result() (ok)" ); + } + } + else if( count == 2 ) { + // sayUserException was just called. + testExceptions( "receive_exception", "sayUserException", ri ); + } + } + catch( Exception ex ) { + failException( "receive_exception", ex ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + try { + super.receive_other( interceptor, ri ); + + if( count == 1 ) { + // Ensure arguments() is inaccessible. + try { + ri.arguments(); + fail( "receive_exception: Should not have been " + + "able to access arguments()" ); + } + catch( BAD_INV_ORDER e ) { + log( "receive_exception: Could not access " + + "arguments() (ok)" ); + } + + testContexts( "receive_other", "sayArguments", ri ); + + // Ensure result() is inaccessible. + try { + ri.result(); + fail( "send_request: Should not have been " + + "able to access result()" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_request: Could not access " + + "result() (ok)" ); + } + } + else if( count == 2 ) { + // sayUserException was just called. + testExceptions( "receive_other", "sayUserException", ri ); + } + } + catch( Exception ex ) { + failException( "receive_other", ex ); + } + } + + // Test that arguments() returns valid values. + private void testArguments( String interceptionPoint, String methodName, + ClientRequestInfo ri ) + throws Exception + { + String header = interceptionPoint + "(): "; + if( methodName.equals( "sayArguments" ) ) { + log( header + "Analyzing arguments for " + methodName ); + Parameter[] params = ri.arguments(); + if( params.length != 3 ) { + fail( header + "sayArguments should have 3 parameters." ); + } + else { + Any arg = params[0].argument; + if( arg == null ) { + fail( header + "first argument is null" ); + } + else { + String par = arg.extract_string(); + if( !par.equals( "one" ) ) { + fail( header + "first argument was not \"one\"" ); + } + else { + log( header + "first argument is valid." ); + } + } + + arg = params[1].argument; + if( arg == null ) { + fail( header + "second argument is null" ); + } + else { + int par = arg.extract_long(); + if( par != 2 ) { + fail( header + "second argument was not \"2\"" ); + } + else { + log( header + "second argument is valid." ); + } + } + + arg = params[2].argument; + if( arg == null ) { + fail( header + "third argument is null" ); + } + else { + boolean par = arg.extract_boolean(); + if( !par ) { + fail( header + "third argument was not \"true\"" ); + } + else { + log( header + "third argument is valid." ); + } + } + } + } + } + + // Test that exceptions() returns valid values. + private void testExceptions( String interceptionPoint, String methodName, + ClientRequestInfo ri ) + throws Exception + { + String header = interceptionPoint + "(): "; + if( methodName.equals( "sayUserException" ) ) { + log( header + "Analyzing exceptions for " + methodName ); + TypeCode[] excList = ri.exceptions(); + + if( excList.length != 1 ) { + fail( header + methodName + " should throw one exception." ); + } + else { + if( excList[0].kind().value() != TCKind._tk_except ) { + fail( header + "the TypeCode is not _tk_except." ); + } + else { + String id = excList[0].id(); + String correctId = ExampleExceptionHelper.id(); + if( !correctId.equals( id ) ) { + fail( header + "the exception id is " + id + + " instead of " + correctId ); + } + else { + log( header + "exception id is " + id + " (ok)" ); + } + } + } + } + } + + // Tests that contexts() returns valid values. + private void testContexts( String interceptionPoint, String methodName, + ClientRequestInfo ri ) + throws Exception + { + String header = interceptionPoint + "(): "; + if( methodName.equals( "sayArguments" ) ) { + log( header + "Analyzing contexts for " + methodName ); + + String[] contexts = ri.contexts(); + if( contexts.length != 2 ) { + fail( header + "sayArguments should have 2 contexts." ); + } + else { + if( !contexts[0].equals( "context1" ) ) { + fail( header + "expected context1. got " + contexts[0] ); + } + else if( !contexts[1].equals( "context2" ) ) { + fail( header + "expected context2. got " + contexts[1] ); + } + else { + log( header + "both contexts are valid." ); + } + } + } + + } + + // Tests that result() returns a valid value. + private void testResult( String interceptionPoint, String methodName, + ClientRequestInfo ri ) + throws Exception + { + String header = interceptionPoint + "(): "; + if( methodName.equals( "sayArguments" ) ) { + Any result = ri.result(); + + // Ensure result is "return value" + if( result == null ) { + fail( header + "result was null!" ); + } + else { + String stringResult = result.extract_string(); + if( !stringResult.equals( "return value" ) ) { + fail( header + "result was " + stringResult + " (error)" ); + } + else { + log( header + "result was correct." ); + } + } + } + else if( methodName.equals( "sayUserException" ) ) { + Any result = ri.result(); + + // Ensure result is void: + if( result.type().kind().value() != TCKind._tk_void ) { + fail( header + "result was not void (error)" ); + } + else { + log( header + "result was void (ok)" ); + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/EffectiveProfileStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/EffectiveProfileStrategy.java new file mode 100644 index 000000000..6a18d7774 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/EffectiveProfileStrategy.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; + +/** + * Strategy to test effective_profile + */ +public class EffectiveProfileStrategy + extends InterceptorStrategy +{ + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + testEffectiveProfile( "send_request", ri ); + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // never executed in our orb. + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + + try { + testEffectiveProfile( "receive_reply", ri ); + } + catch( Exception ex ) { + failException( "receive_reply", ex ); + } + } + + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_exception( interceptor, ri ); + + try { + testEffectiveProfile( "receive_exception", ri ); + } + catch( Exception ex ) { + failException( "receive_exception", ex ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_other( interceptor, ri ); + + try { + testEffectiveProfile( "receive_other", ri ); + } + catch( Exception ex ) { + failException( "receive_other", ex ); + } + } + + private void testEffectiveProfile( String methodName, + ClientRequestInfo ri ) + { + String header = methodName + "(): "; + TaggedProfile profile = ri.effective_profile(); + log( header + "effective_profile().tag = " + profile.tag ); + if( profile.tag != TAG_INTERNET_IOP.value ) { + fail( header + "tag is not TAG_INTERNET_IOP." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/ExceptionStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/ExceptionStrategy.java new file mode 100644 index 000000000..55b7662ab --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/ExceptionStrategy.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.misc.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import ClientRequestInfo.*; +import org.omg.CORBA.*; + +/** + * Strategy to test received_exception() and received_exception_id(). + * Expected invocation order: + * count = 1, send_request, receive_reply + * count = 2, send_request, receive_exception (SystemException) + * count = 3, send_request, receive_exception (UserException) + * count = 4, send_request, receive_other + * All points are checked in order to assure received_exception() + * can only be called in the receive_exception interception point. + */ +public class ExceptionStrategy + extends InterceptorStrategy +{ + + private int count = 0; + + + // True if this test is being run in DII mode. In DII mode, all + // UserException tests are skipped. + // + // _REVISIT_ Remove this special mode once UserExceptions work properly + // with DII. + boolean diiMode; + + public ExceptionStrategy() { + this( false ); + } + + public ExceptionStrategy( boolean diiMode ) { + this.diiMode = diiMode; + } + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + count++; + + testException( "send_request", ri ); + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // never executed in our orb. + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + + try { + testException( "receive_reply", ri ); + } + catch( Exception ex ) { + failException( "receive_reply", ex ); + } + } + + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_exception( interceptor, ri ); + + try { + testException( "receive_exception", ri ); + } + catch( Exception ex ) { + failException( "receive_exception", ex ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_other( interceptor, ri ); + + try { + testException( "receive_other", ri ); + } + catch( Exception ex ) { + failException( "receive_other", ex ); + } + } + + private void testException( String methodName, + ClientRequestInfo ri ) + { + String header = methodName + "(): "; + if( methodName.equals( "receive_exception" ) ) { + if( count == 2 ) { + // Called for System Exception: + // Test received_exception: + Any receivedException = ri.received_exception(); + SystemException sysex = ORBUtility.extractSystemException( + receivedException ); + if( !(sysex instanceof UNKNOWN) ) { + fail( header + "received_exception() did not return " + + "correct SystemException" ); + } + else { + log( header + "received_exception() returned " + + "correct SystemException." ); + } + + // Test received_exception_id: + String exceptionId = ri.received_exception_id(); + + log( header + "exceptionId for SystemException is: " + + exceptionId ); + + if( exceptionId.indexOf( "UNKNOWN" ) == -1 ) { + fail( header + "exceptionId incorrect!" ); + } + } + else if( count == 3 ) { + // Skip this test in DII mode: + if( diiMode ) { + log( header + "skipping UserException test for DII" ); + } + else { + // Called for User Exception: + // Test received_exception: + Any receivedException = ri.received_exception(); + + ExampleException exception = + ExampleExceptionHelper.extract( receivedException ); + if( !exception.reason.equals( "valid" ) ) { + fail( header + + "received_exception() did not return valid " + + "ExampleException" ); + } + else { + log( header + "received_exception() is valid." ); + } + + // Test received_exception_id: + String exceptionId = ri.received_exception_id(); + + log( header + "exceptionId for UserException is: " + + exceptionId ); + + if( exceptionId.indexOf( "ExampleException" ) == -1 ) { + fail( header + "exceptionId incorrect!" ); + } + } + } + else { + fail( header + "receive_exception should not be " + + "called when count = " + count ); + } + } + else { + // We should not be able to access received_exception! + try { + ri.received_exception(); + fail( header + + "received_exception() did not raise BAD_INV_ORDER!" ); + } + catch( BAD_INV_ORDER e ) { + log( header + "received_exception() raised BAD_INV_ORDER (ok)"); + } + + // We should not be able to access received_exception_id! + try { + ri.received_exception_id(); + fail( header + + "received_exception_id() did not raise BAD_INV_ORDER!" ); + } + catch( BAD_INV_ORDER e ) { + log( header + + "received_exception_id() raised BAD_INV_ORDER (ok)"); + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/ForwardReferenceStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/ForwardReferenceStrategy.java new file mode 100644 index 000000000..711ff380e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/ForwardReferenceStrategy.java @@ -0,0 +1,240 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Strategy to test forward_reference + *

+ * A call will be made, and the interceptor will forward the request to + * another object to handle it. forward_reference will be checked when + * reply status is LOCATION_FORWARD and when it is not LOCATION_FORWARD. + *

+ * Should be called as follows: + * count = 1 + * send_request + * receive_reply + * count = 2 + * send_request + * receive_exception + * count = 3 + * send_request + * receive_other + * count = 4, effective_target is now helloRefForward + * send_request + * receive_exception + */ +public class ForwardReferenceStrategy + extends InterceptorStrategy +{ + + private int count = 0; + + public ForwardReferenceStrategy() { + } + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + count++; + log( "send_request(): count is " + count ); + + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "send_request(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_request(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + + // Try target() + org.omg.CORBA.Object obj = ri.target(); + org.omg.CORBA.Object correctObject; + correctObject = TestInitializer.helloRef; + + if( correctObject._is_equivalent( obj ) ) { + log( "send_request(): target() is valid." ); + } + else { + fail( "send_request(): target() is invalid." ); + } + + // Try effective_target() + obj = ri.effective_target(); + if( count < 4 ) { + // This is before we are invoking on helloRefForward. + correctObject = TestInitializer.helloRef; + } + else { + // This is after we are invoking on helloRefForward. + correctObject = TestInitializer.helloRefForward; + } + if( correctObject._is_equivalent( obj ) ) { + log( "send_request(): effective_target() is valid." ); + } + else { + fail( "send_request(): effective_target() is invalid." ); + } + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void receive_reply( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + + try { + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "receive_reply(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "receive_reply(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + + // Try target() + org.omg.CORBA.Object obj = ri.target(); + if( TestInitializer.helloRef._is_equivalent( obj ) ) { + log( "send_request(): target() is valid." ); + } + else { + fail( "send_request(): target() is invalid." ); + } + + // Try effective_target() + obj = ri.effective_target(); + if( TestInitializer.helloRef._is_equivalent( obj ) ) { + log( "send_request(): effective_target() is valid." ); + } + else { + fail( "send_request(): effective_target() is invalid." ); + } + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_exception( interceptor, ri ); + + try { + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "receive_exception(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "receive_exception(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + + // Try target() + org.omg.CORBA.Object obj = ri.target(); + org.omg.CORBA.Object correctObject; + correctObject = TestInitializer.helloRef; + + if( correctObject._is_equivalent( obj ) ) { + log( "receive_exception(): target() is valid." ); + } + else { + fail( "receive_exception(): target() is invalid." ); + } + + // Try effective_target() + obj = ri.effective_target(); + if( count < 4 ) { + // This is before we are invoking on helloRefForward. + correctObject = TestInitializer.helloRef; + } + else { + // This is after we are invoking on helloRefForward. + correctObject = TestInitializer.helloRefForward; + } + if( correctObject._is_equivalent( obj ) ) { + log( "receive_exception(): effective_target() is valid." ); + } + else { + fail( "receive_exception(): effective_target() is invalid." ); + } + } + catch( Exception ex ) { + failException( "receive_exception", ex ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_other( interceptor, ri ); + + try { + try { + // Try calling forward_reference(). Should not fail. + org.omg.CORBA.Object obj = ri.forward_reference(); + if( TestInitializer.helloRefForward._is_equivalent( obj ) ) { + log( "receive_other(): forward_reference() is valid." ); + } + else { + fail( "receive_other(): forward_reference() is " + + "invalid." ); + } + } + catch( BAD_INV_ORDER e ) { + fail( "receive_other(): forward_reference() raised " + + "BAD_INV_ORDER"); + } + + // Try target() + org.omg.CORBA.Object obj = ri.target(); + if( TestInitializer.helloRef._is_equivalent( obj ) ) { + log( "receive_other(): target() is valid." ); + } + else { + fail( "receive_other(): target() is invalid." ); + } + + // Try effective_target() + obj = ri.effective_target(); + if( TestInitializer.helloRef._is_equivalent( obj ) ) { + log( "receive_other(): effective_target() is valid." ); + } + else { + fail( "receive_other(): effective_target() is invalid." ); + } + } + catch( Exception ex ) { + failException( "receive_other", ex ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InterceptorStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/InterceptorStrategy.java new file mode 100644 index 000000000..e3454496d --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InterceptorStrategy.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Base class for all client request interceptor strategies used in this + * test. This allows for dyanmic behavior modifications between test cases. + * Default method implementations do nothing. + */ +abstract public class InterceptorStrategy { + + /** True if test failed, false if not */ + public boolean failed = false; + + /** The reason for failure */ + public String failReason = null; + + /** + * Logs the given message as test output. + */ + protected void log( String message ) { + ClientCommon.client.out.println( " + " + message ); + } + + /** + * Reports the given message as a test failure for the given reason. + */ + protected void fail( String reason ) { + ClientCommon.client.out.println( " + ERROR: " + reason ); + failReason = reason; + failed = true; + } + + /** + * Reports a test failure, using the exception object as a reason. + * The origin of failure is given in the origin string. + */ + protected void failException( String origin, Exception ex ) { + String failReason = "Exception " + + ex.getClass().getName() + "( " + ex.getMessage() + " )" + + " in " + this.getClass().getName() + "." + origin + "."; + ClientCommon.client.out.println( " + ERROR: " + failReason ); + ex.printStackTrace(); + failed = true; + } + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + } + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeDynamic.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeDynamic.java new file mode 100644 index 000000000..58919ad9c --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeDynamic.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +import ClientRequestInfo.*; + +/** + * Invocation strategy in which each interception point is visited, similar + * to InvokeVisitAll, but sayArguments is called instead of sayHello. + * + * The following order is used: + * send_request, receive_reply + * send_request, receive_exception + * send_request, receive_other + */ +public class InvokeDynamic + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke send_request then receive_reply + invokeMethod( "sayArguments" ); + + // Invoke send_request then receive_exception: + try { + invokeMethod( "sayUserException" ); + } + catch( ExampleException e ) { + // We expect this, but no other exception. + } + catch( UnknownUserException e ) { + // We expect this, but no other exception. + } + + // Invoke send_request then receive_other: + SampleClientRequestInterceptor.exceptionRedirectToOther = true; + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeExceptions.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeExceptions.java new file mode 100644 index 000000000..9d9efab84 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeExceptions.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; +import ClientRequestInfo.*; + +/** + * Invocation strategy in which three calls are made. + * 1. No exception raised + * 2. SystemException raised + * 3. UserException raised + * 4. No exception raised, receive_other is called. + */ +public class InvokeExceptions + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke send_request then receive_reply + invokeMethod( "sayHello" ); + + // Invoke send_request then receive_exception: + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + + // Invoke send_request then receive_exception (user exception): + try { + invokeMethod( "sayUserException" ); + } + catch( ExampleException e ) { + // We expect these, but no other exceptions. + } + catch( UnknownUserException e ) { + // We expect these, but no other exceptions. + // This occurs in the DII case. + } + + // Invoke send_request then receive_other: + SampleClientRequestInterceptor.exceptionRedirectToOther = true; + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeOneWay.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeOneWay.java new file mode 100644 index 000000000..9d0b41064 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeOneWay.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which two requests are sent, one that is not oneway + * and one that is oneway, in that order. + */ +public class InvokeOneWay + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke normal call + invokeMethod( "sayHello" ); + + // Invoke oneway call + invokeMethod( "sayOneway" ); + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeRecursive.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeRecursive.java new file mode 100644 index 000000000..2e2c4b85d --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeRecursive.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which a recursive call is made, causing + * send_request and receive_reply to be invoked twice, as follows: + * send_request + * send_request + * receive_reply + * receive_reply + */ +public class InvokeRecursive + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke send_request, cause send_request to make a request causing + // send_request then receive_reply, and then finally receive_reply. + SampleClientRequestInterceptor.recursiveInvoke = true; + invokeMethod( "sayHello" ); + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeStrategy.java new file mode 100644 index 000000000..f3244091e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeStrategy.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Base class for all invocation strategies used in this test. This allows + * for dynamic behavior modifications between test cases of which objects + * are invoked. Default method implementations do nothing. + */ +abstract public class InvokeStrategy { + /** + * Invokes the method with the given name + */ + protected void invokeMethod( String name ) throws Exception { + ClientCommon.client.invokeMethod( name ); + } + + public void invoke() throws Exception { + // Reset the request interceptor to prepare for test: + SampleClientRequestInterceptor.enabled = true; + SampleClientRequestInterceptor.sendRequestEnabled = true; + SampleClientRequestInterceptor.sendPollEnabled = true; + SampleClientRequestInterceptor.receiveReplyEnabled = true; + SampleClientRequestInterceptor.receiveExceptionEnabled = true; + SampleClientRequestInterceptor.receiveOtherEnabled = true; + + // Disable special flags: + SampleClientRequestInterceptor.exceptionRedirectToOther = false; + SampleClientRequestInterceptor.recursiveInvoke = false; + SampleClientRequestInterceptor.invokeOnForwardedObject = false; + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeVisitAll.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeVisitAll.java new file mode 100644 index 000000000..058451022 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeVisitAll.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which each interception point is visited. + * The following order is used: + * send_request, receive_reply + * send_request, receive_exception + * send_request, receive_other + */ +public class InvokeVisitAll + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke send_request then receive_reply + invokeMethod( "sayHello" ); + + // Invoke send_request then receive_exception: + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + + // Invoke send_request then receive_other: + SampleClientRequestInterceptor.exceptionRedirectToOther = true; + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/InvokeVisitAllForward.java b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeVisitAllForward.java new file mode 100644 index 000000000..e1255e18e --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/InvokeVisitAllForward.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which each interception point is visited. + * Interceptors are also called for the forwarded object. + * The following order is used: + * send_request, receive_reply + * send_request, receive_exception + * send_request, receive_other + * send_request, receive_reply + */ +public class InvokeVisitAllForward + extends InvokeStrategy +{ + public InvokeVisitAllForward() { + } + + public void invoke() throws Exception { + super.invoke(); + + SampleClientRequestInterceptor.invokeOnForwardedObject = true; + + // Invoke send_request then receive_reply + invokeMethod( "sayHello" ); + + // Invoke send_request then receive_exception: + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + + // Invoke send_request then receive_other: + SampleClientRequestInterceptor.exceptionRedirectToOther = true; + try { + invokeMethod( "saySystemException" ); + } + catch( UNKNOWN e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/OldRMILocalServer.java b/functional-tests/src/test/java/pi/clientrequestinfo/OldRMILocalServer.java new file mode 100644 index 000000000..cdf8c7f5a --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/OldRMILocalServer.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test. Uses old _*ImplBase skeletons. + */ +public class OldRMILocalServer + implements Observer +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public void run( com.sun.corba.ee.spi.orb.ORB orb, java.lang.Object syncObject, + Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + rebindObjects(); + + // no handshake required here: + //out.println("Server is ready."); + //out.flush(); + + // Notify client to wake up: + synchronized( syncObject ) { + syncObject.notifyAll(); + } + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + private void rebindObjects() + throws Exception + { + out.println( "+ Creating and binding hello objects..." ); + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloOldRMIIIOP obj = new helloOldRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + + // Add this server as an observer so that when resetServant is called + // we can rebind. + helloDelegate delegate = obj.getDelegate(); + delegate.addObserver( this ); + } + + public void update( Observable o, java.lang.Object arg ) { + try { + rebindObjects(); + } + catch( Exception e ) { + System.err.println( "rebindObjects() failed! " + e ); + throw new RuntimeException( "rebindObjects failed!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/OldRMIServer.java b/functional-tests/src/test/java/pi/clientrequestinfo/OldRMIServer.java new file mode 100644 index 000000000..dba6c5092 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/OldRMIServer.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test. Uses old _*ImplBase skeletons. + */ +public class OldRMIServer + implements InternalProcess +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public static void main(String args[]) { + try { + (new OldRMIServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + out.println( "+ Creating and binding hello objects..." ); + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloOldRMIIIOP obj = new helloOldRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/OneWayStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/OneWayStrategy.java new file mode 100644 index 000000000..642f70e8f --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/OneWayStrategy.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Strategy to test response_expected() + */ +public class OneWayStrategy + extends InterceptorStrategy +{ + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + checkResponseExpected( "send_request", ri ); + } + catch( Exception e ) { + failException( "send_request", e ); + } + } + + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // never executed in our orb. + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + + try { + checkResponseExpected( "receive_reply", ri ); + } + catch( Exception e ) { + failException( "receive_reply", e ); + } + } + + + private void checkResponseExpected( String method, ClientRequestInfo ri ) { + String operationName = ri.operation(); + boolean responseExpected = ri.response_expected(); + boolean validExpected = !operationName.equals( "sayOneway" ); + + log( method + "(): Operation " + operationName + + ", response expected = " + responseExpected ); + + if( responseExpected != validExpected ) { + fail( "response_expected() invalid for this operation." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/POAClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/POAClient.java new file mode 100644 index 000000000..ddc678d94 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/POAClient.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; + +/** + * Tests POA Remote invocation + */ +public class POAClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private hello helloRef; + + // Reference to hello object to be forwarded to: + private hello helloRefForward; + + public static void main(String args[]) { + try { + (new POAClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "================================" ); + out.println( "Creating ORB for POA Remote test" ); + out.println( "================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestRequestInfo tests + */ + protected void testClientRequestInfo() + throws Exception + { + super.testClientRequestInfo(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = helloRef; + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private hello resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path)); + + return helloRef; + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/POALocalClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/POALocalClient.java new file mode 100644 index 000000000..64fa444bb --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/POALocalClient.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; + +/** + * Tests POA Local invocation (with a co-located orb) + */ +public class POALocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private hello helloRef; + + // Reference to hello object to be forwarded to: + private hello helloRefForward; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===============================" ); + System.out.println( "Creating ORB for POA Local test" ); + System.out.println( "===============================" ); + + final POALocalClient client = new POALocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new POALocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInfo tests + */ + protected void testClientRequestInfo () + throws Exception + { + super.testClientRequestInfo(); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( orb, "Hello1" ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = helloRef; + out.println( " - Hello1Forward" ); + helloRefForward = resolve( orb, "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private hello resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path)); + + return helloRef; + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/POALocalServer.java b/functional-tests/src/test/java/pi/clientrequestinfo/POALocalServer.java new file mode 100644 index 000000000..440a82bb3 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/POALocalServer.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; // hello interface + +public class POALocalServer { + // Set from run() + private PrintStream out; + + private static final String ROOT_POA = "RootPOA"; + + private POA rootPOA; + + private com.sun.corba.ee.spi.orb.ORB orb; + + public void run( com.sun.corba.ee.spi.orb.ORB orb, java.lang.Object syncObject, + Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.orb = orb; + + // Get the root POA: + rootPOA = null; + out.println( "Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object and helloForward object for POA remote case: + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + + // no handshake required here. + //out.println("Server is ready."); + //out.flush(); + + // notify client to wake up: + synchronized( syncObject ) { + syncObject.notifyAll(); + } + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public void createAndBind (String name) + throws Exception + { + // create servant and register it with the ORB + helloServant helloRef = new helloServant( out ); + + byte[] id = rootPOA.activate_object(helloRef); + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/POAServer.java b/functional-tests/src/test/java/pi/clientrequestinfo/POAServer.java new file mode 100644 index 000000000..6d1485670 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/POAServer.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; + +import ClientRequestInfo.*; // hello interface + +public class POAServer + implements InternalProcess +{ + // Set from run() + private PrintStream out; + + private static final String ROOT_POA = "RootPOA"; + + private POA rootPOA; + + private com.sun.corba.ee.spi.orb.ORB orb; + + public static void main(String args[]) { + try { + (new POAServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "Invoking ORB" ); + out.println( "============" ); + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + // Get the root POA: + rootPOA = null; + out.println( "Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object and helloForward object for POA remote case: + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public void createAndBind (String name) + throws Exception + { + // create servant and register it with the ORB + helloServant helloRef = new helloServant( out ); + + byte[] id = rootPOA.activate_object(helloRef); + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/RMIClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/RMIClient.java new file mode 100644 index 000000000..52af18c80 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/RMIClient.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.rmi.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; +import javax.rmi.*; + +public class RMIClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloIF helloRef; + + // Reference to hello object to be forwarded to: + private helloIF helloRefForward; + + // Initial naming context + InitialContext initialNamingContext; + + // Names for JNDI lookup: + public static final String NAME1 = "hello2"; + public static final String NAME2 = "hello2Forward"; + + public static void main(String args[]) { + try { + (new RMIClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "===================================" ); + out.println( "Instantiating ORB for RMI/IIOP test" ); + out.println( "===================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + try { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + catch( RemoteException e ) { + throw (Exception)e.detail; + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInfo tests + */ + protected void testClientRequestInfo() + throws Exception + { + super.testClientRequestInfo(); + } + + /** + * One-way test not applicable for RMI case. Override it. + */ + protected void testOneWay() throws Exception { + out.println( "+ OneWay test not applicable for RMI. Skipping..." ); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - " + NAME1 ); + helloRef = resolve( NAME1 ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = (org.omg.CORBA.Object)helloRef; + out.println( " - " + NAME2 ); + helloRefForward = resolve( NAME2 ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = + (org.omg.CORBA.Object)helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + private helloIF resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } + +} + + + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/RMILocalClient.java b/functional-tests/src/test/java/pi/clientrequestinfo/RMILocalClient.java new file mode 100644 index 000000000..c90e1c5b0 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/RMILocalClient.java @@ -0,0 +1,256 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ClientRequestInfo.*; + +/** + * Tests RMI Local invocation (with a co-located orb) + */ +public class RMILocalClient + extends ClientCommon + implements InternalProcess +{ + // Reference to hello object + private helloIF helloRef; + + // Reference to hello object to be forwarded to: + private helloIF helloRefForward; + + // Initial naming context + InitialContext initialNamingContext; + + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + System.out.println( "===============================" ); + System.out.println( "Creating ORB for RMI Local test" ); + System.out.println( "===============================" ); + + final RMILocalClient client = new RMILocalClient(); + + TestInitializer.out = System.out; + client.out = System.out; + client.err = System.err; + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + client.createORB( args ); + + // Inform JNDI provider of the ORB to use and create initial + // naming context: + System.out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", client.orb ); + client.initialNamingContext = new InitialContext( env ); + + System.out.println( "+ Starting Server..." ); + client.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + (new RMILocalServer()).run( + client.orb, client.syncObject, + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( client.syncObject ) { + try { + client.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Test ClientInterceptor + testClientRequestInfo(); + } finally { + finish() ; + } + } + + /** + * Clear invocation flags of helloRef and helloRefForward + */ + protected void clearInvoked() + throws Exception + { + helloRef.clearInvoked(); + helloRefForward.clearInvoked(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + try { + // Make an invocation: + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + helloRef.sayUserException(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "sayArguments" ) ) { + helloRef.sayArguments( "one", 2, true ); + } + } + catch( RemoteException e ) { + throw (Exception)e.detail; + } + } + + /** + * Return true if the method was invoked + */ + protected boolean wasInvoked() + throws Exception + { + return helloRef.wasInvoked(); + } + + /** + * Return true if the method was forwarded + */ + protected boolean didForward() + throws Exception + { + return helloRefForward.wasInvoked(); + } + + /** + * Perform ClientRequestInfo tests + */ + protected void testClientRequestInfo () + throws Exception + { + super.testClientRequestInfo(); + } + + /** + * One-way test not applicable for RMI case. Override it. + */ + protected void testOneWay() throws Exception { + out.println( "+ OneWay test not applicable for RMI. Skipping..." ); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation + */ + protected void resolveReferences() + throws Exception + { + out.println( " + resolving references..." ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + // Resolve the hello object. + out.println( " - Hello1" ); + helloRef = resolve( "Hello1" ); + // The initializer will store the location the interceptors should + // use during a normal request: + TestInitializer.helloRef = (org.omg.CORBA.Object)helloRef; + out.println( " - Hello1Forward" ); + helloRefForward = resolve( "Hello1Forward" ); + // The initializer will store the location the interceptors should + // use during a forward request: + TestInitializer.helloRefForward = + (org.omg.CORBA.Object)helloRefForward; + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + + /** + * Implementation borrowed from corba.socket.HelloClient.java test + */ + private helloIF resolve(String name) + throws Exception + { + // Get the root naming context + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } + + /** + * Executes the test case set up with the parameters in setParameters + */ + protected void runTestCase( String testName ) + throws Exception + { + super.runTestCase( testName ); + + out.println( " + Resetting servants on server side" ); + out.println( " - disabling interceptors..." ); + SampleClientRequestInterceptor.enabled = false; + helloRef.resetServant(); + out.println( " - enabling interceptors..." ); + SampleClientRequestInterceptor.enabled = true; + } + +} + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/RMILocalServer.java b/functional-tests/src/test/java/pi/clientrequestinfo/RMILocalServer.java new file mode 100644 index 000000000..f4747ec2b --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/RMILocalServer.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test + */ +public class RMILocalServer + implements Observer +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public void run( com.sun.corba.ee.spi.orb.ORB orb, java.lang.Object syncObject, + Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + rebindObjects(); + + // no handshake required here: + //out.println("Server is ready."); + //out.flush(); + + // Notify client to wake up: + synchronized( syncObject ) { + syncObject.notifyAll(); + } + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + private void rebindObjects() + throws Exception + { + out.println( "+ Creating and binding hello objects..." ); + createAndBind( "Hello1" ); + createAndBind( "Hello1Forward" ); + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloRMIIIOP obj = new helloRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + + // Add this server as an observer so that when resetServant is called + // we can rebind. + helloDelegate delegate = obj.getDelegate(); + delegate.addObserver( this ); + } + + public void update( Observable o, java.lang.Object arg ) { + try { + rebindObjects(); + } + catch( Exception e ) { + System.err.println( "rebindObjects() failed! " + e ); + throw new RuntimeException( "rebindObjects failed!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/RMIServer.java b/functional-tests/src/test/java/pi/clientrequestinfo/RMIServer.java new file mode 100644 index 000000000..22ddf2c2a --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/RMIServer.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; + +import java.util.*; +import java.io.*; +import javax.naming.*; + +/** + * Server for RMI/IIOP version of test + */ +public class RMIServer + implements InternalProcess +{ + // Set from run() + private PrintStream out; + + private com.sun.corba.ee.spi.orb.ORB orb; + + InitialContext initialNamingContext; + + public static void main(String args[]) { + try { + (new RMIServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + this.orb = (com.sun.corba.ee.spi.orb.ORB)orb; + + + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create intial + // naming context: + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + out.println( "+ Creating and binding hello objects..." ); + createAndBind( RMIClient.NAME1 ); + createAndBind( RMIClient.NAME2 ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + + } + + /** + * Creates and binds a hello object using RMI + */ + public void createAndBind (String name) + throws Exception + { + helloRMIIIOP obj = new helloRMIIIOP( out ); + initialNamingContext.rebind( name, obj ); + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/RequestId1Strategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/RequestId1Strategy.java new file mode 100644 index 000000000..eb22675f2 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/RequestId1Strategy.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Strategy to test request_id.1 + */ +public class RequestId1Strategy + extends InterceptorStrategy +{ + + // The id received in send_request: + private int requestId; + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + this.requestId = ri.request_id(); + log( "send_request(): request_id = " + requestId ); + } + catch( Exception ex ) { + failException( "send_request", ex ); + } + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // never executed in our orb. + } + + public void receive_reply ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + try { + testId( "receive_reply", ri.request_id() ); + } + catch( Exception e ) { + failException( "receive_reply", e ); + } + } + + + public void receive_exception ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_exception( interceptor, ri ); + try { + testId( "receive_exception", ri.request_id() ); + } + catch( Exception e ) { + failException( "receive_exception", e ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_other( interceptor, ri ); + + try { + testId( "receive_other", ri.request_id() ); + } + catch( Exception e ) { + failException( "receive_other", e ); + } + } + + /** + * Tests the given id after send_request + */ + private void testId( String method, int id ) { + log( method + "(): request_id = " + id ); + if( id != this.requestId ) { + fail( "Request ID in " + method + " did not match request " + + "id in send_request." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/RequestId2Strategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/RequestId2Strategy.java new file mode 100644 index 000000000..61694fe56 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/RequestId2Strategy.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Strategy to test request_id.2 + *

+ * A recursive call will be made. We will ensure the inner-most call has a + * different requestId than the outer-most call. + */ +public class RequestId2Strategy + extends InterceptorStrategy +{ + + // The request id for the outer-most call: + private int outerId = -1; + + // The request id for the inner-most call: + private int innerId = -1; + + // The request id count: + private int count = 0; + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + if( count == 0 ) { + outerId = ri.request_id(); + log( "send_request(): outer-most id is " + outerId ); + count++; + } + else if( count == 1 ) { + innerId = ri.request_id(); + log( "send_request(): inner-most id is " + innerId ); + count++; + + if( innerId == outerId ) { + fail( "outer and inner requests ids are the same." ); + } + } + } + catch( Exception e ) { + failException( "send_request", e ); + } + } + + public void receive_reply( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + + try { + // check to make sure inner ids match. + count--; + + if( count == 1 ) { + int id = ri.request_id(); + log( "receive_reply(): inner-most id is " + id ); + if( id != innerId ) { + fail( "inner id is not the same in receive_reply() as " + + "it was in send_request()" ); + } + } + else if( count == 0 ) { + int id = ri.request_id(); + log( "receive_reply(): outer-most id is " + id ); + if( id != outerId ) { + fail( "outer id is not the same in receive_reply() as " + + "it was in send_request()" ); + } + } + } + catch( Exception e ) { + failException( "receive_reply", e ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/SampleClientRequestInterceptor.java b/functional-tests/src/test/java/pi/clientrequestinfo/SampleClientRequestInterceptor.java new file mode 100644 index 000000000..da1513eb7 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/SampleClientRequestInterceptor.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; + +/** + * Sample ClientRequestInterceptor for use in testing. This interceptor + * is dynamically configurable via an InterceptorStrategy. It assumes + * three interceptors have been registered, and most operations will be + * performed on interceptor number 2 and only if the target() is not + * helloRefForward. + */ +public class SampleClientRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor +{ + // The dyanmic strategy that will be used for this round. + public static InterceptorStrategy strategy = null; + + // The name of this interceptor + private String name; + + // True if enabled, false if all interception points must + // return immediately. + public static boolean enabled = false; + + // Selective enabling and disabling of interception points. These + // are only applicable if enabled is true: + public static boolean sendRequestEnabled = true; + public static boolean sendPollEnabled = true; + public static boolean receiveReplyEnabled = true; + public static boolean receiveExceptionEnabled = true; + public static boolean receiveOtherEnabled = true; + + // Special flags to override the strategy behavior of this interceptor. + + // Throw ForwardRequest during receive_exception so that receive_other + // is called. + public static boolean exceptionRedirectToOther = false; + + // Cause send_request to recursively invoke another method. + public static boolean recursiveInvoke = false; + + // Allow interceptors to be invoked for forwarded object as well. + public static boolean invokeOnForwardedObject = false; + + private static int invokeCount = 0; + + public SampleClientRequestInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void send_request (ClientRequestInfo ri) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( !enabled ) return; + if( !sendRequestEnabled ) return; + if( !name.equals( "2" ) ) return; + if( !invokeOnForwardedObject && + TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) return; + + strategy.send_request( this, ri ); + + if( recursiveInvoke ) { + if( invokeCount == 0 ) { + invokeCount++; + try { + ClientCommon.client.invokeMethod( "sayHello" ); + } + catch( Exception e ) { + // If this throws an exception, convert it into a + // SystemException. + throw new BAD_OPERATION( e.getMessage() ); + } + invokeCount--; + } + } + } + + public void send_poll (ClientRequestInfo ri) { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( !enabled ) return; + if( !sendPollEnabled ) return; + if( !name.equals( "2" ) ) return; + if( !invokeOnForwardedObject && + TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) return; + + strategy.send_poll( this, ri ); + } + + public void receive_reply (ClientRequestInfo ri) { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( !enabled ) return; + if( !receiveReplyEnabled ) return; + if( !name.equals( "2" ) ) return; + if( !invokeOnForwardedObject && + TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) return; + + strategy.receive_reply( this, ri ); + } + + public void receive_exception (ClientRequestInfo ri) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( !enabled ) return; + if( !receiveExceptionEnabled ) return; + if( !name.equals( "2" ) ) return; + if( !invokeOnForwardedObject && + TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) return; + + if( exceptionRedirectToOther && + !TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) + { + // Override strategy, and cause this exception to redirect to + // a receive_other on interceptor number 1. + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + else { + strategy.receive_exception( this, ri ); + } + } + + public void receive_other (ClientRequestInfo ri) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( !enabled ) return; + if( !receiveOtherEnabled ) return; + if( !name.equals( "1" ) ) return; + if( !invokeOnForwardedObject && + TestInitializer.helloRefForward._is_equivalent( + ri.effective_target() ) ) return; + + strategy.receive_other( this, ri ); + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/ServiceContextStrategy.java b/functional-tests/src/test/java/pi/clientrequestinfo/ServiceContextStrategy.java new file mode 100644 index 000000000..f2601d75c --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/ServiceContextStrategy.java @@ -0,0 +1,295 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import com.sun.corba.ee.spi.servicecontext.ORBVersionServiceContext; +import org.omg.CORBA.*; +import java.util.*; + +/** + * Strategy to test get_request_service_context and get_reply_service_context. + *

+ * Both get_request_service_context and get_reply_service_context will be + * tried for each interception point. + */ +public class ServiceContextStrategy + extends InterceptorStrategy +{ + // Service context ID that is known to be invalid. + private final static int INVALID_ID = 1234; + + // Fake ids and data: + private final static int FAKEID1 = 2123; + private final static int FAKEID2 = 2124; + private final static int FAKEID3 = 2125; + + private final static byte[] FAKEDATA1 = { + (byte)1, (byte)2, (byte)3, (byte)4 }; + private final static byte[] FAKEDATA2 = { + (byte)5, (byte)6, (byte)7 }; + private final static byte[] FAKEDATA3 = { + (byte)8 }; + + + public void send_request ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.send_request( interceptor, ri ); + + try { + testGetRequestSC( "send_request", ri ); + //testGetReplySC( "send_request", ri ); + testAddRequestSC( "send_request", ri ); + } + catch( Exception e ) { + failException( "send_request", e ); + } + } + + public void send_poll ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.send_poll( interceptor, ri ); + // Never called in our ORB. + } + + public void receive_reply( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + { + super.receive_reply( interceptor, ri ); + + try { + testGetRequestSC( "receive_reply", ri ); + //testGetReplySC( "receive_reply", ri ); + testAddRequestSC( "receive_reply", ri ); + } + catch( Exception e ) { + failException( "receive_reply", e ); + } + } + + public void receive_exception( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_exception( interceptor, ri ); + + try { + testGetRequestSC( "receive_exception", ri ); + //testGetReplySC( "receive_exception", ri ); + testAddRequestSC( "receive_exception", ri ); + } + catch( Exception e ) { + failException( "receive_exception", e ); + } + } + + public void receive_other ( + SampleClientRequestInterceptor interceptor, ClientRequestInfo ri) + throws ForwardRequest + { + super.receive_other( interceptor, ri ); + + try { + testGetRequestSC( "receive_other", ri ); + //testGetReplySC( "receive_other", ri ); + testAddRequestSC( "receive_other", ri ); + } + catch( Exception e ) { + failException( "receive_other", e ); + } + } + + private void testGetRequestSC( String methodName, ClientRequestInfo ri ) { + // Test to ensure valid and invalid IDs work properly: + testSC( "request", methodName, ri ); + } + + private void testGetReplySC( String methodName, ClientRequestInfo ri ) { + if( methodName.equals( "send_request" ) ) { + // get_reply_service_context is invalid here. + try { + ri.get_reply_service_context( 0 ); + fail( methodName + "(): get_reply_service_context() " + + "did not raise BAD_INV_ORDER." ); + } + catch( BAD_INV_ORDER e ) { + log( methodName + "(): get_reply_service_context() " + + "raised BAD_INV_ORDER (ok)" ); + } + } + else { + // Test to ensure valid and invalid IDs work properly: + testSC( "reply", methodName, ri ); + } + } + + private void testSC( String reqOrRep, String methodName, + ClientRequestInfo ri ) + { + String header = methodName + "(): get_" + reqOrRep + + "_service_context"; + + // Test to ensure an invalid ID raises a BAD_PARAM: + try { + if( reqOrRep.equals( "request" ) ) { + ri.get_request_service_context( INVALID_ID ); + } + else { + ri.get_reply_service_context( INVALID_ID ); + } + fail( header + "( INVALID_ID ) did not raise BAD_PARAM." ); + } + catch( BAD_PARAM e ) { + log( header + "( INVALID_ID ) raised BAD_PARAM (ok)" ); + } + + // Test to ensure valid ID works properly: + int id; + if( reqOrRep.equals( "request" ) ) { + id = ORBVersionServiceContext.SERVICE_CONTEXT_ID; + } + else { + // _REVISIT_ What do we do here? + id = 6; + } + + try { + ServiceContext sc; + if( reqOrRep.equals( "request" ) ) { + sc = ri.get_request_service_context( id ); + } + else { + sc = ri.get_reply_service_context( id ); + } + + log( header + "( " + id + " ) exists (ok)." ); + + // Commenting out copy test due to "good citizen" assumption. + /* + // Ensure this is a copy and not the real thing: + byte altered = ++sc.context_data[0]; + + if( reqOrRep.equals( "request" ) ) { + sc = ri.get_request_service_context( id ); + } + else { + sc = ri.get_reply_service_context( id ); + } + + if( sc.context_data[0] == altered ) { + fail( header + "( " + id + " ) is not a copy. " + + "It is the original!" ); + } + else { + log( header + "( " + id + " ) is a copy, " + + "not the original (ok)" ); + } + */ + } + catch( BAD_PARAM e ) { + fail( header + "( " + id + " ) raised BAD_PARAM" ); + } + } + + private void testAddRequestSC( String methodName, ClientRequestInfo ri ) { + String header = methodName + "(): "; + + if( methodName.equals( "send_request" ) ) { + try { + // Add a service context + ServiceContext sc = new ServiceContext( FAKEID2, FAKEDATA2 ); + ri.add_request_service_context( sc, true ); + log( header + "added service context 1." ); + + // Check to make sure it's there. + sc = ri.get_request_service_context( FAKEID2 ); + if( Arrays.equals( sc.context_data, FAKEDATA2 ) ) { + log( header + "service context data is valid." ); + } + else { + fail( header + "service context data is invalid." ); + } + + // Try to replace it with replace = true: + try { + sc = new ServiceContext( FAKEID2, FAKEDATA3 ); + ri.add_request_service_context( sc, true ); + log( header + "was able to replace context with " + + "replace=true." ); + + // Check to make sure it was changed: + sc = ri.get_request_service_context( FAKEID2 ); + if( Arrays.equals( sc.context_data, FAKEDATA3 ) ) { + log( header + "service context data is valid." ); + } + else { + fail( header + "service context data is invalid." ); + } + } + catch( BAD_INV_ORDER e ) { + fail( header + "was not able to replace context with " + + "replace=true." ); + } + + // Try to replace it with replace = false. + try { + sc = new ServiceContext( FAKEID2, FAKEDATA1 ); + ri.add_request_service_context( sc, false ); + fail( header + "was able to replace context with " + + "replace=false." ); + } + catch( BAD_INV_ORDER e ) { + log( header + "was not able to replace context with " + + "replace=false." ); + + // Check to make sure it was not changed: + sc = ri.get_request_service_context( FAKEID2 ); + if( Arrays.equals( sc.context_data, FAKEDATA3 ) ) { + log( header + "service context data is valid." ); + } + else { + fail( header + "service context data is invalid." ); + } + } + } + catch( BAD_INV_ORDER e ) { + fail( header + + "denied access to add_request_service_context." ); + } + } + else { + // Ensure we are not able to call add_request_service_context + // anywhere but in send_request: + try { + ServiceContext sc = new ServiceContext( FAKEID1, FAKEDATA1 ); + ri.add_request_service_context( sc, true ); + fail( header + + "invalid access to add_request_service_context." ); + } + catch( BAD_INV_ORDER e ) { + log( header + + "denied access to add_request_service_context (ok)." ); + } + } + + // Test to ensure valid and invalid IDs work properly: + testSC( "request", methodName, ri ); + + + // Check that we are being returned a *copy* of the service context. + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/TestInitializer.java b/functional-tests/src/test/java/pi/clientrequestinfo/TestInitializer.java new file mode 100644 index 000000000..f980094a9 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/TestInitializer.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +import ClientRequestInfo.*; // hello interface + +/** + * Registers the necessary Client Interceptors to test + * ClientRequestInterceptor. + */ +public class TestInitializer + extends org.omg.CORBA.LocalObject + implements ORBInitializer +{ + + // The PrintStream to pass to the ClientRequestInterceptor for output. + // This is set from Client.java statically. + static PrintStream out; + + /** The ORB to pass to the ClientRequestInterceptor */ + static ORB orb; + + // Where to send normal requests + static org.omg.CORBA.Object helloRef; + + // Where to forward the caller on a ForwardRequest + static org.omg.CORBA.Object helloRefForward; + + /** + * Creates a TestInitializer + */ + public TestInitializer() { + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + ClientRequestInterceptor interceptor1; + ClientRequestInterceptor interceptor2; + ClientRequestInterceptor interceptor3; + + interceptor1 = new SampleClientRequestInterceptor( "1" ); + interceptor2 = new SampleClientRequestInterceptor( "2" ); + interceptor3 = new SampleClientRequestInterceptor( "3" ); + + try { + out.println( " - post_init: adding 3 client interceptors..." ); + info.add_client_request_interceptor( interceptor1 ); + info.add_client_request_interceptor( interceptor2 ); + info.add_client_request_interceptor( interceptor3 ); + } + catch( DuplicateName e ) { + out.println( " - post_init: received DuplicateName!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/helloDIIClientStub.java b/functional-tests/src/test/java/pi/clientrequestinfo/helloDIIClientStub.java new file mode 100644 index 000000000..b3b3253d6 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/helloDIIClientStub.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; +import java.rmi.Remote; +import java.rmi.RemoteException; + +import ClientRequestInfo.*; + +/** + * Utility class to encapsulate the logic to make DII calls on the + * hello interface. + */ +public class helloDIIClientStub +{ + + /** The CORBA object to make DII calls on */ + private org.omg.CORBA.Object object; + + /** The ORB to use to create objects */ + private ORB orb; + + /** + * Creates a new helloDIIClientStub which will make DII calls on the given + * corba object, and will create objects using the given ORB. + */ + public helloDIIClientStub( ORB orb, org.omg.CORBA.Object object ) { + this.object = object; + this.orb = orb; + } + + public org.omg.CORBA.Object getObject() { + return object; + } + + String sayHello() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_string( "dummy" ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "sayHello", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_string(); + } + + String saySystemException() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_string( "dummy" ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "saySystemException", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_string(); + } + + String sayUserException() + throws UnknownUserException, ExampleException + { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_string( "dummy" ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Exception list: + ExceptionList excList = orb.create_exception_list(); + excList.add( ExampleExceptionHelper.type() ); + + // Invoke method: + Request thisReq = object._create_request( null, "sayUserException", + argList, resultVal, excList, null ); + thisReq.invoke(); + + // Analyze environment to see if UserException was thrown. + Environment env = thisReq.env(); + Exception exc = env.exception(); + + // _REVISIT_ For now, we will accept either UnknownUserException or + // ExampleException since the DII code in our ORB does not provide us + // access to the actual exception that was thrown (see + // RequestImpl.doInvocation) + + if( exc instanceof UnknownUserException ) { + throw (UnknownUserException)exc; + } + else if( exc instanceof ExampleException ) { + throw (ExampleException)exc; + } + else { + throw new RuntimeException( + "sayUserException: Unexpected exception: " + exc ); + } + } + + void sayOneway() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // No result parameter: + + // Invoke method as a oneway: + Request thisReq = object._create_request( null, "sayOneway", + argList, null ); + thisReq.send_oneway(); + } + + String sayArguments( String arg1, int arg2, boolean arg3 ) { + // Create parameter list: + NVList argList = orb.create_list( 3 ); + Any par1Value = orb.create_any(); + par1Value.insert_string( arg1 ); + Any par2Value = orb.create_any(); + par2Value.insert_long( arg2 ); + Any par3Value = orb.create_any(); + par3Value.insert_boolean( arg3 ); + argList.add_value( "arg1", par1Value, ARG_IN.value ); + argList.add_value( "arg2", par2Value, ARG_IN.value ); + argList.add_value( "arg3", par3Value, ARG_IN.value ); + + // Add two contexts so we can test contexts(): + ContextList ctxList = orb.create_context_list(); + ctxList.add( "context1" ); + ctxList.add( "context2" ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_string( "dummy" ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "sayArguments", + argList, resultVal, null, ctxList ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_string(); + } + + void clearInvoked() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // No result parameter: + + // Invoke method: + Request thisReq = object._create_request( null, "clearInvoked", + argList, null ); + thisReq.invoke(); + } + + boolean wasInvoked() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // Create result parameter: + Any result = orb.create_any(); + result.insert_boolean( false ); + NamedValue resultVal = orb.create_named_value( "result", result, + org.omg.CORBA.ARG_OUT.value ); + + // Invoke method: + Request thisReq = object._create_request( null, "wasInvoked", + argList, resultVal ); + thisReq.invoke(); + + // Return result: + result = thisReq.result().value(); + return result.extract_boolean(); + } + + void resetServant() { + // Create parameter list: + NVList argList = orb.create_list( 0 ); + + // No result parameter: + + // Invoke method: + Request thisReq = object._create_request( null, "resetServant", + argList, null ); + thisReq.invoke(); + } + +} + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/helloDelegate.java b/functional-tests/src/test/java/pi/clientrequestinfo/helloDelegate.java new file mode 100644 index 000000000..da6f6626b --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/helloDelegate.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; + +import java.io.*; +import javax.rmi.*; +import javax.naming.*; +import java.util.*; + +import ClientRequestInfo.*; // hello interface + +/** + * Contains the actual implementations of hello operations. + */ +public class helloDelegate + extends Observable + implements helloIF +{ + private boolean invoked = false; + private PrintStream out = null; + + public helloDelegate( PrintStream out ) { + super(); + this.out = out; + } + + public String sayHello() { + out.println( "helloServant: sayHello() invoked" ); + invoked = true; + return "Hello, world!"; + } + + public String saySystemException() { + out.println( "helloServant: saySystemException() invoked" ); + invoked = true; + throw new UNKNOWN( "Valid Test Result" ); + } + + public void sayUserException() + throws ExampleException + { + out.println( "helloServant: sayUserException() invoked" ); + invoked = true; + throw new ExampleException( "valid" ); + } + + // This will cause a receive_reply to be invoked since this + // is a one-way method. + public void sayOneway() { + out.println( "helloServant: sayOneway() invoked" ); + invoked = true; + } + + public String sayArguments( String arg1, int arg2, boolean arg3 ) { + out.println( "helloServant: sayArguments() invoked" ); + invoked = true; + + return "return value"; + } + + public void clearInvoked() { + invoked = false; + } + + public boolean wasInvoked() { + return invoked; + } + + public void resetServant() { + setChanged(); + notifyObservers(); + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/helloIF.java b/functional-tests/src/test/java/pi/clientrequestinfo/helloIF.java new file mode 100644 index 000000000..5d9164210 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/helloIF.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import org.omg.CORBA.*; +import ClientRequestInfo.*; + +/** + * Hello interface for RMI-IIOP version of test + */ +public interface helloIF + extends Remote +{ + String sayHello () throws RemoteException; + String saySystemException () throws RemoteException; + void sayUserException () throws ExampleException, RemoteException; + void sayOneway () throws RemoteException; + String sayArguments( String arg1, int arg2, boolean arg3 ) + throws RemoteException; + void clearInvoked () throws RemoteException; + boolean wasInvoked () throws RemoteException; + void resetServant () throws RemoteException; +} + diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/helloOldRMIIIOP.java b/functional-tests/src/test/java/pi/clientrequestinfo/helloOldRMIIIOP.java new file mode 100644 index 000000000..452f8a39c --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/helloOldRMIIIOP.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; + +import java.io.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; +import org.omg.CORBA.*; + +import ClientRequestInfo.*; // hello interface + +/** + * ClientDelegate implementation with old stubs. + */ +public class helloOldRMIIIOP + extends _helloImplBase +{ + // Contains the actual implementation of the hello interface. + private helloDelegate delegate = null; + + public helloOldRMIIIOP( PrintStream out ) + throws RemoteException + { + super(); + this.delegate = new helloDelegate( out ); + } + + public helloDelegate getDelegate() { + return this.delegate; + } + + public String sayHello() { + return delegate.sayHello(); + } + + public String saySystemException() { + return delegate.saySystemException(); + } + + public void sayUserException() + throws ExampleException + { + delegate.sayUserException(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public String sayArguments( String arg1, int arg2, boolean arg3 ) { + return delegate.sayArguments( arg1, arg2, arg3 ); + } + + public void clearInvoked() { + delegate.clearInvoked(); + } + + public boolean wasInvoked() { + return delegate.wasInvoked(); + } + + public void resetServant() { + delegate.resetServant(); + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/helloRMIIIOP.java b/functional-tests/src/test/java/pi/clientrequestinfo/helloRMIIIOP.java new file mode 100644 index 000000000..90a732a00 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/helloRMIIIOP.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; + +import java.io.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; +import org.omg.CORBA.*; + +import ClientRequestInfo.*; // hello interface + +/** + * RMI/IIOP implementation. + */ +public class helloRMIIIOP + extends PortableRemoteObject + implements helloIF +{ + // Contains the actual implementation of the hello interface. + private helloDelegate delegate = null; + + public helloRMIIIOP( PrintStream out ) + throws RemoteException + { + super(); + this.delegate = new helloDelegate( out ); + } + + public helloDelegate getDelegate() { + return delegate; + } + + public String sayHello() { + return delegate.sayHello(); + } + + public String saySystemException() { + return delegate.saySystemException(); + } + + public void sayUserException() + throws ExampleException + { + delegate.sayUserException(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public String sayArguments( String arg1, int arg2, boolean arg3 ) { + return delegate.sayArguments( arg1, arg2, arg3 ); + } + + public void clearInvoked() { + delegate.clearInvoked(); + } + + public boolean wasInvoked() { + return delegate.wasInvoked(); + } + + public void resetServant() { + delegate.resetServant(); + } +} diff --git a/functional-tests/src/test/java/pi/clientrequestinfo/helloServant.java b/functional-tests/src/test/java/pi/clientrequestinfo/helloServant.java new file mode 100644 index 000000000..8217f66a7 --- /dev/null +++ b/functional-tests/src/test/java/pi/clientrequestinfo/helloServant.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.clientrequestinfo; + +import org.omg.CORBA.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +import ClientRequestInfo.*; // hello interface + +/** + * Servant implementation. + */ +public class helloServant + extends helloPOA +{ + // contains implementations of methods. + private helloDelegate delegate; + + public helloServant( PrintStream out ) { + super(); + delegate = new helloDelegate( out ); + } + + public String sayHello() { + return delegate.sayHello(); + } + + public String saySystemException() { + return delegate.saySystemException(); + } + + public void sayUserException() + throws ExampleException + { + delegate.sayUserException(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public String sayArguments( String arg1, int arg2, boolean arg3 ) { + return delegate.sayArguments( arg1, arg2, arg3 ); + } + + public void clearInvoked() { + delegate.clearInvoked(); + } + + public boolean wasInvoked() { + return delegate.wasInvoked(); + } + + public void resetServant() { + delegate.resetServant(); + } +} diff --git a/functional-tests/src/test/java/pi/codec/Client.java b/functional-tests/src/test/java/pi/codec/Client.java new file mode 100644 index 000000000..41589d3cc --- /dev/null +++ b/functional-tests/src/test/java/pi/codec/Client.java @@ -0,0 +1,469 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.codec; + +import CodecTest.TestStruct; +import CodecTest.TestStructHelper; +import CodecTest.TestUnion; +import CodecTest.TestUnionHelper; +import corba.framework.InternalProcess; +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TypeCode; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.CodecFactoryPackage.UnknownEncoding; +import org.omg.IOP.CodecPackage.FormatMismatch; +import org.omg.IOP.ENCODING_CDR_ENCAPS; +import org.omg.IOP.Encoding; + +public class Client + implements InternalProcess +{ + private JUnitReportHelper helper = new JUnitReportHelper( Client.class.getName() ) ; + + private ORB orb; + private PrintStream out; + private PrintStream err; + private CodecFactory codecFactory; + + public static void main(String args[]) { + try { + (new Client()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + + this.out = out; + this.err = err; + this.orb = orb; + + try { + // Test the codec factory: + testCodecFactory(); + + // Test the codec: + testCodec(); + } finally { + helper.done() ; + } + } + + private void testCodecFactory() throws Exception + { + out.println( "Testing CodecFactory" ); + out.println( "====================" ); + + // Test that the CodecFactory is obtained through a call to + // ORB::resolve_initial_references( "CodecFactory" ) + testReference(); + + // Test that a codec is obtained from the Codec Factory, and + // that ENCODING_CDR_ENCAPS 1.0, 1.1, 1.2 are supported. + testValidCodecs(); + + // Test that UnknownEncoding is raised if this factory cannot + // create a Codec of the given encoding. + testInvalidCodecs(); + } + + private void testReference() throws Exception + { + helper.start( "testReference" ) ; + + try { + out.println( "resolve_initial_references( \"CodecFactory\" ): " ); + + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("CodecFactory"); + + if( objRef != null ) { + out.println( " - Retrieved reference." ); + } else { + throw new RuntimeException( "null Reference from ORB." ); + } + + codecFactory = CodecFactoryHelper.narrow(objRef); + + if( objRef != null ) { + out.println( " - Narrowed reference." ); + } else { + throw new RuntimeException( + "CodecFactory Reference narrowed to null" ); + } + + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + } + } + + private void testValidCodecs() throws Exception + { + for( int minor = 0; minor <=2; minor++ ) { + helper.start( "testValidCodecs_" + minor ) ; + + try { + try { + out.print( "create_codec( ENCODING_CDR_ENCAPS, 1, " + + minor + " ):" ); + Encoding encoding = new Encoding( + (short)ENCODING_CDR_ENCAPS.value, (byte)1, (byte)minor ); + Codec codec = codecFactory.create_codec( encoding ); + + if( codec != null ) { + out.println( "valid (ok)" ); + } else { + out.println( "null (error)" ); + throw new RuntimeException( "Null Codec returned for 1." + + minor ); + } + } catch( UnknownEncoding e ) { + out.println( "unknown (error)" ); + throw new RuntimeException( + "Could not get Codec for 1." + minor ); + } + + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + throw exc ; + } + } + } + + private void testInvalidCodecs() throws Exception + { + for( int format = ENCODING_CDR_ENCAPS.value; + format <= ENCODING_CDR_ENCAPS.value + 1; format ++ ) { + // (try 0 and 1) + for( int major = 2; major <= 3; major+=1 ) { + for( int minor = 3 - (major-2) * 2; + minor <= 5 - (major-2) * 2; minor+=1 ) { + + helper.start( "testInvalidCodecs_" + format + "_" + major + "_" + minor ) ; + + // (try 2.3, 2.4, 2.5, 3.1, 3.2, 3.3) + try { + out.print( "create_codec( " + format + ", " + + major + ", " + minor + " ):" ); + Encoding encoding = new Encoding( + (short)format, (byte)major, (byte)minor ); + Codec codec = codecFactory.create_codec( encoding ); + + String msg = (codec == null) ? + "null (error)" : + "valid (error)" ; + out.println( msg ); + helper.fail( msg ) ; + + throw new RuntimeException( + "No exception thrown for " + major + "." + minor ); + } catch( UnknownEncoding e ) { + // We expect these versions to fail. + helper.pass() ; + out.println( "unknown (ok)" ); + } + } // minor loop + } // major loop + } // format loop + + } + + private void testCodec() + throws Exception + { + out.println( "" ); + out.println( "Testing Codec" ); + out.println( "=============" ); + + // Test that encode and decode work + testEncodeDecode( false ); + + // Test that encode_value and decode_value work + testEncodeDecode( true ); + + // Test that FormatMismatch is raised if decode or decode_value + // is called when data in the provided octet sequence cannot be + // decoded into an any. + testFormatMismatch(); + } + + private void testEncodeDecode( boolean valueOnly ) throws Exception { + if( valueOnly ) { + out.println( "testing encode_value and decode_value:" ); + } + else { + out.println( "testing encode and decode:" ); + } + + // Get a codec to test with + Codec codec = codecFactory.create_codec( + new Encoding( (short)ENCODING_CDR_ENCAPS.value, (byte)1, + (byte)2 ) ); + + // Try to encode a representative set from the available types in + // CORBA IDL. Then, decode them to ensure they are equal to + // their original values. Note that this is not an all-inclusive + // set. + + Any sourceAny; // Holds the source any + + // null + sourceAny = orb.create_any() ; + check( codec, valueOnly, "null", sourceAny, 8, 1 ); + + + // short + sourceAny = orb.create_any() ; + sourceAny.insert_short( (short)345 ); + check( codec, valueOnly, "short", sourceAny, 10, 4 ); + + // float + sourceAny = orb.create_any() ; + sourceAny.insert_float( (float)3.45 ); + check( codec, valueOnly, "float", sourceAny, 12, 8 ); + + // boolean + sourceAny = orb.create_any() ; + sourceAny.insert_boolean( true ); + check( codec, valueOnly, "boolean", sourceAny, 9, 2 ); + + // char + sourceAny = orb.create_any() ; + sourceAny.insert_char( 'w' ); + check( codec, valueOnly, "char", sourceAny, 9, 2 ); + + // octet + sourceAny = orb.create_any() ; + sourceAny.insert_octet( (byte)127 ); + check( codec, valueOnly, "octet", sourceAny, 9, 2 ); + + // string + sourceAny = orb.create_any() ; + sourceAny.insert_string( "hello, world" ); + check( codec, valueOnly, "string", sourceAny, 29, 21 ); + + // struct + TestStruct testStruct = new TestStruct( (short)10, (short)20 ); + sourceAny = orb.create_any() ; + TestStructHelper.insert( sourceAny, testStruct ); + check( codec, valueOnly, "struct", sourceAny, 108, 6 ); + + // union + TestUnion testUnion = new TestUnion(); + testUnion.f( (float)3.45 ); + sourceAny = orb.create_any() ; + TestUnionHelper.insert( sourceAny, testUnion ); + check( codec, valueOnly, "union", sourceAny, 128, 8 ); + + // longlong + sourceAny = orb.create_any() ; + sourceAny.insert_longlong( 1234567L ); + check( codec, valueOnly, "longlong", sourceAny, 16, 16 ); + + // wstring + sourceAny = orb.create_any() ; + sourceAny.insert_wstring( "hello, world" ); + check( codec, valueOnly, "wstring", sourceAny, 40, 32 ); + + // fixed + sourceAny = orb.create_any() ; + sourceAny.insert_fixed( new java.math.BigDecimal( "1234.5678" ) ); + check( codec, valueOnly, "fixed", sourceAny, 17, 6 ); + } + + // Does a loopback test on the given source Any by encoding with the + // given codec, and then decoding it. Throws a RuntimeException if + // the decoded value does not match the encoded one or if the + // actual length does not match the expected length. Does not + // trap any exceptions - just passes them through. + private void check( Codec codec, boolean valueOnly, String type, + Any source, int lenWithType, int lenWOType ) + throws Exception + { + helper.start( "encodeDecode_" + type + "_valueOnly_" + valueOnly ) ; + + try { + byte[] octets; // Holds the intermediate octet stream + Any destAny; // Holds the target any + TypeCode tc = source.type(); + int expectedLength; // Expected length of octet stream + + out.print( " - " + type + ": " ); + if (valueOnly) { + octets = codec.encode_value( source ); + expectedLength = lenWOType; + } else { + octets = codec.encode( source ); + expectedLength = lenWithType; + } + out.print( "size: " + octets.length ); + if (valueOnly) { + destAny = codec.decode_value( octets, tc ); + } else { + destAny = codec.decode( octets ); + } + boolean compare = source.equal( destAny ); + out.println( " compare: " + compare ); + out.println( " " + dumpHex( octets ) ); + + if (!compare) { + throw new RuntimeException( + "" + type + " fails loopback test content comparison" ); + } + + if (octets.length != expectedLength) { + throw new RuntimeException( + "" + type + " fails loopback test length comparison: expected " + + expectedLength + " got " + octets.length ); + } + + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + // Dumps the hex values in the given byte array + private String dumpHex( byte[] octets ) { + StringBuffer result = new StringBuffer( "" ); + for( int i = 0; i < octets.length; i++ ) { + if( (i != 0) && ((i % 16) == 0) ) result.append( "\n " ); + int b = octets[i]; + if( b < 0 ) b = 256 + b; + String hex = Integer.toHexString( b ); + if( hex.length() == 1 ) { + hex = "0" + hex; + } + result.append( hex + " " ); + } + + return result.toString(); + } + + private void testFormatMismatch() + throws Exception + { + // Some invalid sequences. Each of these sequences is invalid for + // a different reason. On an attempt to call decode or decode_value, + // a FormatMismatch exception is expected. If it is not received, + // the test fails. + + // These are invalid for decode() + byte[][] invalidForDecode = { + // This is invalid because it specifies an invalid type code. + { 0x00, 0x00, 0x00, 0x00, // big-endian + 0x00, 0x00, 0x00, 0x7f, // invalid type + 0x00, 0x00, 0x00, 0x00, // extra data + 0x00, 0x00, 0x00, 0x00 + }, + + // This is invalid because it has too few octets. + { 0x00, 0x00, 0x00, 0x00, // big-endian + 0x00, 0x00, 0x00, 0x17, // long long + 0x12, 0x34 // not enough data + } + }; + + // These are invalid for decode_value() + byte[][] invalidForDecodeValue = { + // This is an invalid null because it has no endian type. + {}, // missing endian + + // This is an invalid long long because it has too few octets. + { 0x00, 0x00, 0x00, 0x00, // big-endian + 0x00, 0x00, 0x00, 0x00, // padding + 0x12, 0x34 } // not enough data + }; + + // Type codes for the decode_value cases + Any longAny = orb.create_any() ; + longAny.insert_longlong( 1L ); + TypeCode[] typeCodes = { + orb.create_any().type(), // null TypeCode + longAny.type() // long TypeCode + }; + + // Get a codec to use for these tests: + Codec codec = codecFactory.create_codec( + new Encoding( (short)ENCODING_CDR_ENCAPS.value, (byte)1, + (byte)2 ) ); + + // Test decode() + checkInvalid( codec, false, "decode", invalidForDecode, typeCodes ); + checkInvalid( codec, true, "decode_value", invalidForDecodeValue, + typeCodes ); + + } + + private void checkInvalid( Codec codec, boolean valueOnly, String type, + byte[][] cases, TypeCode[] typeCodes ) + throws Exception + { + out.println( "Testing FormatMismatch for " + type ); + + for( int i = 0; i < cases.length; i++ ) { + helper.start( "formatMismatch_" + type + "_" + i ) ; + + out.print( " - Case #" + i + ": " ); + byte[] data = cases[i]; + boolean pass = false; + + try { + if (valueOnly) { + codec.decode_value( data, typeCodes[i] ); + } else { + codec.decode( data ); + } + } + catch( FormatMismatch e ) { + // We got the expected exception: + pass = true; + } + + if( pass ) { + out.println( "FormatMismatch thrown (ok)" ); + helper.pass() ; + } else { + out.println( "FormatMismatch not thrown (error)" ); + helper.fail( "FormatMismatch not thrown" ) ; + } + + // Let us see what the data was: + out.println( " " + dumpHex( data ) ); + + if( !pass ) { + throw new RuntimeException( "FormatMismatch not thrown" ); + } + } + } +} diff --git a/functional-tests/src/test/java/pi/codec/CodecTest.java b/functional-tests/src/test/java/pi/codec/CodecTest.java new file mode 100644 index 000000000..01af54451 --- /dev/null +++ b/functional-tests/src/test/java/pi/codec/CodecTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.codec; + +import corba.framework.*; +import java.util.*; + +/** + * Tests Codec and CodecFactory as per Portable Interceptors spec + * orbos/99-12-02, Chapter 10. See pi/assertions.html for Assertions + * covered in this test. + */ +public class CodecTest extends CORBATest +{ + protected void doTest() + throws Throwable + { + Controller orbd = createORBD(); + + orbd.start(); + + Controller client = createClient( "pi.codec.Client" ); + + client.start(); + + client.waitFor(); + + client.stop(); + + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/pi/iorinterceptor/Client.java b/functional-tests/src/test/java/pi/iorinterceptor/Client.java new file mode 100644 index 000000000..7f9e60d7a --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/Client.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +public class Client + implements InternalProcess +{ + + // Set from run() + private ORB orb; + + // Set from run() + private PrintStream out; + + // Set from run() + private PrintStream err; + + private CodecFactory codecFactory; + + public static void main(String args[]) { + try { + (new Client()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // Initializer classes + String testInitializer = "pi.orbinit.ClientTestInitializer"; + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + ORB orb = ORB.init(args, props); + + this.out = out; + this.err = err; + this.orb = orb; + + if( ServerTestInitializer.postInitFailed ) { + throw new RuntimeException( "post_init failed" ); + } + + // Test IORInterceptor + testIORInterceptor(); + + // Test IORInfo + testIORInfo(); + } + + /** + * Perform IORInterceptor tests + */ + private void testIORInterceptor() { + out.println(); + out.println( "Testing IORInterceptor" ); + out.println( "======================" ); + out.println( "+ Nothing to test on client side, yet." ); + } + + /** + * Perform IORInfo-related tests + */ + private void testIORInfo() { + out.println(); + out.println( "Testing IORInfo" ); + out.println( "===============" ); + out.println( "+ Nothing to test on client side, yet." ); + } +} diff --git a/functional-tests/src/test/java/pi/iorinterceptor/IORInterceptorTest.java b/functional-tests/src/test/java/pi/iorinterceptor/IORInterceptorTest.java new file mode 100644 index 000000000..e522fe096 --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/IORInterceptorTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import org.omg.CORBA.*; +import corba.framework.*; +import java.util.*; + +/** + * Tests IORInterceptor and IORInfo as per Portable Interceptors spec + * orbos/99-12-02, Chapter 7. See pi/assertions.html for Assertions + * covered in this test. + */ +public class IORInterceptorTest + extends CORBATest +{ + protected void doTest() + throws Throwable + { + Controller orbd = createORBD(); + + orbd.start(); + + Controller server = createServer( "pi.iorinterceptor.Server" ); + + server.start(); + + Controller client = createClient( "pi.iorinterceptor.Client" ); + + client.start(); + + client.waitFor(); + + client.stop(); + + server.stop(); + + orbd.stop(); + } +} + diff --git a/functional-tests/src/test/java/pi/iorinterceptor/NPEIORInterceptor.java b/functional-tests/src/test/java/pi/iorinterceptor/NPEIORInterceptor.java new file mode 100644 index 000000000..6c35511a9 --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/NPEIORInterceptor.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import java.io.*; + +import org.omg.CORBA.LocalObject; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.IORInterceptor; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; + +/** + * An IORInterceptor that throws a NullPointerException during its + * establish_components. + */ +public class NPEIORInterceptor + extends LocalObject + implements IORInterceptor +{ + + // The name for this interceptor + private String name; + + // Destination for all output, set from constructor upon construction + // by ServerTestInitializer: + private PrintStream out; + + // True if any instances of NPEIORInterceptor were ever registered, or + // false if not. + public static boolean registered = false; + + // True if establish_components was ever called on this interceptor, + // or false if not + public static boolean establishComponentsCalled = false; + + public NPEIORInterceptor( String name, PrintStream out ) { + this.name = name; + this.out = out; + out.println( " - NPEIORInterceptor " + name + " created." ); + registered = true; + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void establish_components (IORInfo info) { + out.println( " - NPEIORInterceptor: establish_components called." ); + establishComponentsCalled = true; + throw new NullPointerException(); + } + + public void components_established( IORInfo info ) + { + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + } + + public void adapter_manager_state_changed( int managerId, short state ) + { + } +} + + diff --git a/functional-tests/src/test/java/pi/iorinterceptor/PolicyFactoryHundred.java b/functional-tests/src/test/java/pi/iorinterceptor/PolicyFactoryHundred.java new file mode 100644 index 000000000..9328017b9 --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/PolicyFactoryHundred.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * This is the Policy Factory to create PolicyHundred object. + */ +public class PolicyFactoryHundred extends LocalObject + implements org.omg.PortableInterceptor.PolicyFactory +{ + public Policy create_policy( int type, Any val ) { + System.out.println( "PolicyFactoryHundred.create_policy called..." ); + System.out.flush(); + return new PolicyHundred( val.extract_long() ); + } +} + diff --git a/functional-tests/src/test/java/pi/iorinterceptor/PolicyHundred.java b/functional-tests/src/test/java/pi/iorinterceptor/PolicyHundred.java new file mode 100644 index 000000000..fc427e98b --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/PolicyHundred.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * This Policy object's type is 100. + */ +public class PolicyHundred extends LocalObject + implements Policy +{ + private int value; + + public PolicyHundred( int value ) { + this.value = value; + } + + public int policy_type( ) { + return 100; + } + + + public org.omg.CORBA.Policy copy( ) { + return this; + } + + public void destroy ( ) { + // Do Nothing + } + + public int getValue() { + return value; + } +} + diff --git a/functional-tests/src/test/java/pi/iorinterceptor/SampleIORInterceptor.java b/functional-tests/src/test/java/pi/iorinterceptor/SampleIORInterceptor.java new file mode 100644 index 000000000..afe1fac46 --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/SampleIORInterceptor.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import java.io.*; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; + +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import org.omg.IOP.TaggedComponent; +import org.omg.IOP.TAG_INTERNET_IOP; +import com.sun.corba.ee.spi.logging.OMGSystemException; + +/** + * Thoroughly tests IORInterceptor support. + */ +public class SampleIORInterceptor + extends LocalObject + implements IORInterceptor +{ + private static final OMGSystemException wrapper = + OMGSystemException.self ; + + // The name for this interceptor + private String name; + + // Destination for all output. This is set in the constructor, which + // is called by ServerTestInitializer. + private PrintStream out; + + // True if any instances of this IORInterceptor were registered, or + // false if not; + public static boolean registered = false; + + // True if establish_components was ever called on this interceptor, + // or false if not + public static boolean establishComponentsCalled = false; + + // True if establish_components completed successfully, or false if + // not. + public static boolean establishComponentsPassed = false; + + // Constant for fake tag values: + public static final int FAKE_TAG_1 = 8954; + public static final int FAKE_TAG_2 = 8955; + + // Constants for fake data to put in the tagged components: + public static byte[] FAKE_DATA_1 = null; + public static byte[] FAKE_DATA_2 = null; + + // constant for a profile ID that does not exist: + public static final int INVALID_PROFILE_ID = 1234; + + public SampleIORInterceptor( String name, PrintStream out ) { + this.name = name; + this.out = out; + out.println( " - IORInterceptor " + name + " created." ); + registered = true; + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void establish_components (IORInfo info) { + out.println( " - establish_components called." ); + establishComponentsCalled = true; + establishComponentsPassed = true; + + try { + out.println( " - generating fake data using CodecFactory..." ); + // Get a Singleton ORB and create sample data to insert into + // profiles: + ORB initORB = ServerTestInitializer.orb; + org.omg.CORBA.Object objRef = + initORB.resolve_initial_references( "CodecFactory" ); + CodecFactory codecFactory = CodecFactoryHelper.narrow( objRef ); + Codec codec = codecFactory.create_codec( new Encoding( + (short)ENCODING_CDR_ENCAPS.value, (byte)1, (byte)2 ) ); + Any any = initORB.create_any(); + any.insert_float( (float)3.45 ); + + // Create octet stream of CDR encapsulation of value. + FAKE_DATA_1 = codec.encode_value( any ); + + any.insert_string( "Hi there" ); + FAKE_DATA_2 = codec.encode_value( any ); + + // Add a component to all profiles: + out.println( " - adding component to all profiles..." ); + TaggedComponent tcAllProfiles = new TaggedComponent( FAKE_TAG_1, + FAKE_DATA_1 ); + info.add_ior_component( tcAllProfiles ); + + // Add a component to only the TAG_INTERNET_IOP profile: + out.println( " - adding component to specific profile..." ); + TaggedComponent tcSpecificProfile = + new TaggedComponent( FAKE_TAG_2, FAKE_DATA_2 ); + int profileId = TAG_INTERNET_IOP.value; + info.add_ior_component_to_profile( tcSpecificProfile, profileId ); + + // Add a component with the same component ID as an existing + // component: + out.println( " - adding duplicate components..." ); + info.add_ior_component_to_profile( tcSpecificProfile, profileId ); + + // Add a component to a profile that does not exist: + out.println( " - adding component to non-existent profile..." ); + try { + info.add_ior_component_to_profile( tcSpecificProfile, + INVALID_PROFILE_ID ); + out.println( " + No exception thrown" ); + establishComponentsPassed = false; + } + catch( BAD_PARAM e ) { + out.println( " + Correct exception thrown" ); + if( e.minor != wrapper.INVALID_PROFILE_ID ) { + out.println( " + Incorrect minor code ( " + e.minor + + ") detected." ); + establishComponentsPassed = false; + } + else { + out.println( " + Correct minor code." ); + } + } + catch( Exception e ) { + out.println( " + Incorrect exception thrown." ); + establishComponentsPassed = false; + } + + // Test get_effective_policy + out.println( " - testing get_effective_policy..." ); + Policy policy; + + try { + out.print( " + ID Uniqueness policy: " ); + policy = info.get_effective_policy( + ID_UNIQUENESS_POLICY_ID.value ); + if( policy == null ) { + out.println( "policy was null!" ); + establishComponentsPassed = false; + } + else if( !(policy instanceof IdUniquenessPolicy ) ) { + out.println( "not an id uniqueness policy!" ); + establishComponentsPassed = false; + } + else { + IdUniquenessPolicy idUniquenessPolicy = + (IdUniquenessPolicy)policy; + if( idUniquenessPolicy.value().value() == + IdUniquenessPolicyValue._MULTIPLE_ID ) + { + out.println( "ok" ); + } + else { + out.println( "wrong policy value!" ); + establishComponentsPassed = false; + } + } + + out.print( " + Hundred policy: " ); + policy = info.get_effective_policy( 100 ); + if( policy == null ) { + out.println( "policy is null!" ); + establishComponentsPassed = false; + } + else if( !(policy instanceof PolicyHundred ) ) { + out.println( "not a 'hundred' policy!" ); + establishComponentsPassed = false; + } + else { + PolicyHundred hundredPolicy = (PolicyHundred)policy; + if( hundredPolicy.getValue() == 99 ) { + out.println( "ok" ); + } + else { + out.println( "wrong policy value!" ); + establishComponentsPassed = false; + } + } + } + catch( INV_POLICY e ) { + out.println( " + INV_POLICY thrown." ); + establishComponentsPassed = false; + } + + // Try invalid ID: + try { + out.print( " + Invalid policy: " ); + policy = info.get_effective_policy( 101 ); + if( policy == null ) { + out.println( "policy was null (ok)" ); + establishComponentsPassed = true; + } + else { + out.println( "policy was not null!" ); + establishComponentsPassed = false; + } + } + catch( INV_POLICY e ) { + out.println( + "INV_POLICY thrown. (error - should return null)" ); + establishComponentsPassed = false; + } + } + catch( Exception f ) { + // Something unexpected happened - treat it as a test failure. + out.println( " - Invalid exception " + f + " detected." ); + f.printStackTrace(); + establishComponentsPassed = false; + } + } + + public void components_established( IORInfo info ) + { + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + } + + public void adapter_manager_state_changed( int managedId, short state ) + { + } +} + + diff --git a/functional-tests/src/test/java/pi/iorinterceptor/Server.java b/functional-tests/src/test/java/pi/iorinterceptor/Server.java new file mode 100644 index 000000000..d8f0d91a4 --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/Server.java @@ -0,0 +1,373 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.encoding.EncapsInputStream; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream; +import com.sun.corba.ee.impl.ior.GenericIdentifiable ; +import corba.framework.InternalProcess; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.PortableServer.IdUniquenessPolicyValue; +import org.omg.PortableServer.POA; + +public class Server + implements InternalProcess +{ + JUnitReportHelper helper = new JUnitReportHelper( Server.class.getName() ) ; + + private static final String ROOT_POA = "RootPOA"; + + private POA rootPOA; + private POA policyPOA; + + // Set from run() + private PrintStream out; + private PrintStream err; + private ORB orb; + + public static void main(String args[]) { + try { + (new Server()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + this.out = out; + this.err = err; + + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // Initializer class + String testInitializer = "pi.iorinterceptor.ServerTestInitializer"; + ServerTestInitializer.out = out; + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + orb = ORB.init(args, props); + ServerTestInitializer.orb = orb; + + // Get root POA: + out.println( "Server retrieving root POA:" ); + rootPOA = (POA)orb.resolve_initial_references( "RootPOA" ); + rootPOA.the_POAManager().activate(); + + // Create another child POA, with a set of policies. + out.println( "Server creating child POA with some policies..." ); + Policy[] policies = new Policy[2]; + + // _REVISIT_ Once our orb is CORBA 2.4 compliant, this test can + // make use of orb.create_policy for the POA policies as well. + + // Insert two standard policies and one custom policy: + policies[0] = rootPOA.create_id_uniqueness_policy( + IdUniquenessPolicyValue.MULTIPLE_ID ); + Any value = orb.create_any(); + value.insert_long( 99 ); + policies[1] = orb.create_policy( 100, value ); + + policyPOA = rootPOA.create_POA( "PolicyPOA", null, policies ); + policyPOA.the_POAManager().activate(); + + // Note at this point, if establish_components does not properly + // handle exceptions, the exception will be passed here and thrown + // before the server gets its handshake in, which will cause the + // test to fail. This tests whether the implementation properly + // handles exceptions in establish_components. If we got this + // far, exceptions are handled properly considering the + // NPEIORInterceptor is registered. + out.println( "NullPointerException handled gracefully (ok)" ); + + // Check to make sure all interceptors are registered: + checkRegistered(); + + // Check to make sure all establish_components calls were made: + checkEstablishComponentsCalled(); + + // Check to make sure all establish_components calls all passed: + checkEstablishComponentsPassed(); + + // Check to make sure tagged components are inserted into IORs. + checkTaggedComponentsPresent(); + } finally { + helper.done() ; + + //handshake: + out.println("Server is ready."); + out.flush(); + + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + sync.wait(); + } + } + } + + // Check to make sure all interceptors were registered + private void checkRegistered() { + helper.start( "checkRegistered" ) ; + + try { + out.println( "Checking if interceptors were registered..." ); + if( !NPEIORInterceptor.registered ) { + throw new RuntimeException( + "NPEIORInterceptor never registered!"); + } + out.println( " - NPEIORInterceptor was registered." ); + if( !SampleIORInterceptor.registered ) { + throw new RuntimeException( + "SampleIORInterceptor never registered!"); + } + out.println( " - SampleIORInterceptor was registered." ); + + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + // Checks to make sure establish_components was called on all + // IORInterceptors. + private void checkEstablishComponentsCalled() { + helper.start( "checkEstablishComponentsCalled" ) ; + + try { + out.println( "Checking if establish_components called..." ); + if( !NPEIORInterceptor.establishComponentsCalled ) { + throw new RuntimeException( + "NPEIORInterceptor.establish_components never called!"); + } + out.println( " - NPEIORInterceptor.establish_components() called."); + if( !SampleIORInterceptor.establishComponentsCalled ) { + throw new RuntimeException( + "SampleIORInterceptor.establish_components never called!"); + } + out.println( " - SampleIORInterceptor.establish_components() " + + "called."); + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + // Checks to make sure establish_components passed on all + // IORInterceptors. + private void checkEstablishComponentsPassed() { + helper.start( "checkEstablishComponentsPassed" ) ; + + try { + out.println( "Checking if establish_components passed..." ); + if( !SampleIORInterceptor.establishComponentsPassed ) { + throw new RuntimeException( + "SampleIORInterceptor.establish_components did not pass!"); + } + out.println( " - SampleIORInterceptor.establish_components() " + + "passed."); + + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + // Creates an object and checks its IOR to make sure the tagged + // components added by the IOR Interceptors are actually present. + private void checkTaggedComponentsPresent() throws Exception { + helper.start( "checkTaggedComponentsPresent" ) ; + + try { + out.println( "Checking if tagged components are present..." ); + + // Create an object: + out.println( " + Creating sample object and getting IOR..." ); + org.omg.CORBA.Object obj = createSampleObject(); + + // Obtain the IOR for this object by writing it to an OutputStream + // and reading it back from an input stream. + EncapsOutputStream encapsOutputStream = new EncapsOutputStream( + (com.sun.corba.ee.spi.orb.ORB)orb, GIOPVersion.V1_2 ); + encapsOutputStream.write_Object( obj ); + EncapsInputStream encapsInputStream = + (EncapsInputStream)encapsOutputStream.create_input_stream(); + IOR ior = IORFactories.makeIOR( + (com.sun.corba.ee.spi.orb.ORB)orb, encapsInputStream ); + + // Check if the appropriate tagged components are present in the IOR. + out.println( " + Searching for tagged components..." ); + IIOPProfile profile = ior.getProfile(); + IIOPProfileTemplate template = + (IIOPProfileTemplate)profile.getTaggedProfileTemplate(); + + // The template is a List of TaggedComponent objects. We are + // interested in the tagged components with the IDs + // SampleIORInterceptor.FAKE_TAG_1 and FAKE_TAG_2. + // FAKE_TAG_2 should appear twice, since it is being used to test + // that multiple tagged components with the same ID can co-exist in + // the same profile. + Iterator fake1 = template.iteratorById( + SampleIORInterceptor.FAKE_TAG_1 ); + verifyComponent( fake1, SampleIORInterceptor.FAKE_TAG_1, + SampleIORInterceptor.FAKE_DATA_1, 1 ); + + Iterator fake2 = template.iteratorById( + SampleIORInterceptor.FAKE_TAG_2 ); + verifyComponent( fake2, SampleIORInterceptor.FAKE_TAG_2, + SampleIORInterceptor.FAKE_DATA_2, 2 ); + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Ensures that the given tagged component is valid. Throws a + * RuntimeException if not. + * + * @param components An iterator, where each element is a + * GenericIdentifiable representing a tagged component with a + * known id. + * @param expectedId The expected ID of the component (used primarily + * for debug output) + * @param expectedData The data to verify against to make sure the + * tagged component was inserted properly. + * @param numOccurrences The number of times this tagged component is + * expected to appear in the profile. + */ + private void verifyComponent( Iterator components, int expectedId, + byte[] expectedData, int numOccurrences ) + { + ArrayList componentList = new ArrayList(); + + while( components.hasNext() ) { + componentList.add( components.next() ); + } + + // Check to make sure numOccurrences objects found: + if( componentList.size() != numOccurrences ) { + String failReason = "Component ID " + expectedId + + ": Incorrect number of occurrences found. " + + "Expected: " + numOccurrences + + ". Found: " + componentList.size() + ". FAIL."; + out.println( " - " + failReason ); + throw new RuntimeException( failReason ); + // *** FAIL *** + } + + // Check each found occurrence to make sure it contains the correct + // data. + for( int i = 0; i < componentList.size(); i++ ) { + GenericIdentifiable encaps = null; + try { + encaps = (GenericIdentifiable)componentList.get( i ); + } + catch( ClassCastException e ) { + String failReason = "Component ID " + expectedId + + ": One or more occurrences is not a " + + "GenericIdentifiable. FAIL."; + out.println( " - " + failReason ); + throw new RuntimeException( failReason ); + // *** FAIL *** + } + + byte[] data = encaps.getData(); + // Compare actual data to inserted data: + if( Arrays.equals( data, expectedData ) ) { + out.println( " - Component ID " + expectedId + + ": PRESENT AND VALID" ); + // *** PASS *** + } + else { + String failReason = "Component ID " + expectedId + + ": Present correct number of times, but one or more " + + "instances contain invalid data. FAIL."; + out.println( " - " + failReason ); + throw new RuntimeException( failReason ); + // *** FAIL *** + } + } + } + + // Creates an instance of the simple interface and binds it. + private org.omg.CORBA.Object createSampleObject() + throws Exception + { + // Create from the child POA, not the root POA. The IORInterceptor + // does not get activated for the root POA. + + // Set up hello object: + return createAndBind( policyPOA, "Simple1" ); + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public org.omg.CORBA.Object createAndBind (POA poa, String name) + throws Exception + { + org.omg.CORBA.Object result; + // create servant and register it with the ORB + SimpleServant simpleRef = new SimpleServant(); + + byte[] id = poa.activate_object(simpleRef); + result = poa.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind( path, result ); + + return result; + } + +} diff --git a/functional-tests/src/test/java/pi/iorinterceptor/ServerTestInitializer.java b/functional-tests/src/test/java/pi/iorinterceptor/ServerTestInitializer.java new file mode 100644 index 000000000..c4cec5c2a --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/ServerTestInitializer.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * Registers the necessary IORInterceptor interceptors to test IORInterceptor. + */ +public class ServerTestInitializer + extends org.omg.CORBA.LocalObject + implements ORBInitializer +{ + + // The PrintStream to pass to the IORInterceptor for output + // This is set from Server.java, statically. + static PrintStream out; + + /** The ORB to pass to the IORInterceptor */ + static ORB orb; + + /** True if post_init failed */ + public static boolean postInitFailed = false; + + /** + * Creates a ServerTestInitializer + */ + public ServerTestInitializer() { + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + IORInterceptor iorInterceptor = new SampleIORInterceptor( "test", out); + IORInterceptor npeIORInterceptor = new NPEIORInterceptor( "npe", out); + try { + out.println( " - post_init: adding Sample IOR Interceptor..." ); + info.add_ior_interceptor( iorInterceptor ); + out.println( " - post_init: adding NPE IOR Interceptor..." ); + info.add_ior_interceptor( npeIORInterceptor ); + } + catch( DuplicateName e ) { + out.println( " - post_init: received DuplicateName!" ); + postInitFailed = true; + } + + out.println( " - post_init: registering PolicyFactory for 100..." ); + PolicyFactory policyFactory100 = new PolicyFactoryHundred(); + info.register_policy_factory( 100, policyFactory100 ); + } + +} diff --git a/functional-tests/src/test/java/pi/iorinterceptor/SimpleServant.java b/functional-tests/src/test/java/pi/iorinterceptor/SimpleServant.java new file mode 100644 index 000000000..906d7d212 --- /dev/null +++ b/functional-tests/src/test/java/pi/iorinterceptor/SimpleServant.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.iorinterceptor; + +import IORInterceptorTest.*; // for IDL + +/** + * Servant implementation for simplePOA + */ +public class SimpleServant extends simplePOA { + private short x; + + public short x() { + return x; + } + + public void x( short newX ) { + this.x = newX; + } +} diff --git a/functional-tests/src/test/java/pi/orbinit/ClientCommon.java b/functional-tests/src/test/java/pi/orbinit/ClientCommon.java new file mode 100644 index 000000000..1e5ccfaa4 --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/ClientCommon.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import corba.framework.InternalProcess; +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; +import org.omg.IOP.CodecFactory; + +public abstract class ClientCommon + implements InternalProcess +{ + JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + + // Set from run() + private ORB orb; + + // Set from run() + private PrintStream out; + + // Set from run() + private PrintStream err; + + private CodecFactory codecFactory; + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "Client" ); + out.println( "======" ); + + this.out = out; + this.err = err; + ClientTestInitializer.out = this.out; + + this.orb = createORB( args ); + ClientTestInitializer.orb = this.orb; + + try { + // Test ORBInitializer + testORBInitializer(); + + // Test ORBInitInfo + testORBInitInfo(); + + // Test destroy + testDestroy(); + } finally { + helper.done() ; + } + } + + /** + * Perform ORBInitializer-related tests + */ + private void testORBInitializer() { + helper.start( "testORBInitializer" ) ; + + try { + out.println(); + out.println( "Testing ORBInitializer" ); + out.println( "======================" ); + + // Ensure the test initializer was initialized appropriately. + out.println( "Verifying testInitializer: " ); + if( !ClientTestInitializer.initializedAppropriately() ) { + throw new RuntimeException( + "ClientTestInitializer not initialized appropriately." ); + } + out.println( " - initialized appropriately. (ok)" ); + + if( !ClientTestInitializer.post_post_init() ) { + throw new RuntimeException( + "ORBInitInfo allowed access after post_init." ); + } + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Perform ORBInitInfo-related tests + */ + private void testORBInitInfo() { + helper.start( "testORBInitInfo" ) ; + + try { + // Any tests on ORBInitInfo are actually done inside the + // ORBInitializer. At this point, we just analyze the results of + // tests that have already run. + + out.println(); + out.println( "Testing ORBInitInfo" ); + out.println( "===================" ); + + // Analyze resolve_initial_references results + out.println( ClientTestInitializer.resolveInitialReferencesResults ); + if( !ClientTestInitializer.passResolveInitialReferences ) { + throw new RuntimeException( + "resolve_initial_references not functioning properly." ); + } + else if( !ClientTestInitializer.passResolveInitialReferencesInvalid ) { + throw new RuntimeException( + "resolve_initial_references not raising InvalidName." ); + } + + // Analyze add_*_interceptor + out.println( "Testing pre_init add interceptor..." ); + out.println( ClientTestInitializer.preAddInterceptorResult ); + if( !ClientTestInitializer.preAddInterceptorPass ) { + throw new RuntimeException( + "pre_init add interceptor test failed." ); + } + + out.println( "Testing post_init add interceptor..." ); + out.println( ClientTestInitializer.postAddInterceptorResult ); + if( !ClientTestInitializer.postAddInterceptorPass ) { + throw new RuntimeException( + "post_init add interceptor test failed." ); + } + + // Analyze get/set_slot test results + out.println( "Testing get/set slot from within ORBInitializer..." ); + out.println( ClientTestInitializer.getSetSlotResult ); + if( !ClientTestInitializer.getSetSlotPass ) { + throw new RuntimeException( "get/set slot test failed." ); + } + + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Test that destroy is called on all interceptors. + */ + private void testDestroy() + throws Exception + { + helper.start( "testDestroy" ) ; + + try { + out.println(); + out.println( "Testing destroy functionality" ); + out.println( "=============================" ); + + out.println( "Checking destroy counts before calling destroy..." ); + int clientCount = SampleClientRequestInterceptor.destroyCount; + int serverCount = SampleServerRequestInterceptor.destroyCount; + int iorCount = SampleIORInterceptor.destroyCount; + checkDestroyCount( "Client", 0, clientCount ); + checkDestroyCount( "Server", 0, serverCount ); + checkDestroyCount( "IOR", 0, iorCount ); + + out.println( "Calling ORB.destroy..." ); + orb.destroy(); + + out.println( + "Checking that interceptors' destroy methods were called." ); + clientCount = SampleClientRequestInterceptor.destroyCount; + serverCount = SampleServerRequestInterceptor.destroyCount; + iorCount = SampleIORInterceptor.destroyCount; + + checkDestroyCount( "Client", 6, clientCount ); + checkDestroyCount( "Server", 2, serverCount ); + checkDestroyCount( "IOR", 2, iorCount ); + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Checks that a single interceptor passed the destroy test + */ + private void checkDestroyCount( String name, int expected, int actual ) + throws Exception + { + out.println( "* " + name + " interceptor: Expected " + expected + + " destroys. Received " + actual + "." ); + if( expected != actual ) { + throw new RuntimeException( + "Incorrect number of destroys called." ); + } + } + + abstract protected ORB createORB( String[] args ); +} diff --git a/functional-tests/src/test/java/pi/orbinit/ClientTestInitializer.java b/functional-tests/src/test/java/pi/orbinit/ClientTestInitializer.java new file mode 100644 index 000000000..810dc2719 --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/ClientTestInitializer.java @@ -0,0 +1,580 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +import ORBInitTest.*; + +/** + * Test initializer on the client side. Most of the testing is done in this + * class, and the results are stored in static publicly accessible variables + * that are analyzed in Client.java. + */ +public class ClientTestInitializer + extends LocalObject + implements ORBInitializer +{ + // Output stream to send information to + public static PrintStream out = null; + public static ORB orb = null; + + // Were we initialized the right way? + private static boolean initializedPre = false; + private static boolean initializedPost = false; + private static boolean globalValid = false; + private static boolean firstInit = true; + + // Recorded Results from the resolve_initial_references test + public static boolean passResolveInitialReferences = false; + public static boolean passResolveInitialReferencesInvalid = false; + public static String resolveInitialReferencesResults = ""; + + // Recorded results from the add_*_interceptor test + public static String preAddInterceptorResult = ""; + public static boolean preAddInterceptorPass = false; + public static String postAddInterceptorResult = ""; + public static boolean postAddInterceptorPass = false; + + // Recorded results from the get/set_slot test + public static String getSetSlotResult = ""; + public static boolean getSetSlotPass = false; + + // "Illegal" private copy of ORBInitInfo - should not be able to access + // after postInit, but we'll try anyway. + private static ORBInitInfo cachedInfo = null; + + // Test reference name to use for initial references + private static String REFERENCE_NAME = "ClientTestInitializerReference"; + + /** + * Creates a ClientTestInitializer + */ + public ClientTestInitializer() { + out.println( " - ClientTestInitializer constructed." ); + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + if( firstInit ) { + firstInit = false; + globalValid = true; + } + + out.println( " - ClientTestInitializer.pre_init called" ); + + if( initializedPre ) { + // pre was already called! + out.println( "ERROR: pre_init() was already called!" ); + globalValid = false; + } + + if( initializedPost ) { + // post was already called! + out.println( "ERROR: post_init() was already called!" ); + globalValid = false; + } + + // Check to make sure info object is valid + if( info == null ) { + out.println( + "ERROR: supplied ORBInitInfo object to pre_init() is null" ); + globalValid = false; + } + else { + if( !testInfo( info, true ) ) { + out.println( + "ERROR: Supplied ORBInitInfo object to " + + "pre_init() is invalid" ); + globalValid = false; + } + } + + // Test interceptor registration + testInterceptorRegistration( info, "preinit" ); + + initializedPre = true; + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + out.println( " - ClientTestInitializer.post_init called" ); + + // Hold on to ORBInitInfo for a later stage of the test. + cachedInfo = info; + + if( !initializedPre ) { + // pre was never called! + out.println( "ERROR: pre_init() was never called!" ); + globalValid = false; + } + + if( initializedPost ) { + // post was already called! + out.println( "ERROR: post_init() was already called!" ); + globalValid = false; + } + + // Check to make sure info object is valid + if( info == null ) { + out.println( + "ERROR: supplied ORBInitInfo object to post_init() is null" ); + } + else { + if( !testInfo( info, false ) ) { + out.println( + "ERROR: Supplied ORBInitInfo object to " + + "pre_init() is invalid" ); + globalValid = false; + } + } + + // We can do this only in post_init() + testResolveInitialReferences( info ); + + // Test interceptor registration + testInterceptorRegistration( info, "postinit" ); + + // Test that get_slot and set_slot cannot be called in PICurrent. + testGetSetSlot( info ); + + initializedPost = true; + } + + /** + * Returns true to the Client.java test if we were initialized + * appropriately. + */ + public static boolean initializedAppropriately() { + return globalValid; + } + + /** + * Run some sanity checks on the given ORBInitInfo object + * + * @param preInit true if this was a preInit call, false if post. + */ + private boolean testInfo( ORBInitInfo info, boolean preInit ) { + // Innocent until proven guilty: + boolean infoValid = true; + + out.println( " - Testing provided initInfo..." ); + + // Check method validity at different stages of init + // (an x indicates valid to call, a dash indicates invalid): + // + // ORBInitInfo Method pre_init post_init + // ------------------ -------- --------- + // arguments x x + // orb_id x x + // codec_factory x x + // + + // Check that all attributes return valid values. + try { + String[] args = info.arguments(); + String id = info.orb_id(); + CodecFactory codecFactory = info.codec_factory(); + + if( args == null ) { + out.println( + " - arguments is null (error)" ); + infoValid = false; + } + else { + // We know the arguments "abcd" and "efgh" must be present. + boolean abcdPresent = false; + boolean efghPresent = false; + for( int i = 0; i < args.length; i++ ) { + if( args[i].equals( "abcd" ) ) { + abcdPresent = true; + } + if( args[i].equals( "efgh" ) ) { + efghPresent = true; + } + } + if( abcdPresent && efghPresent ) { + out.println( + " - arguments contains 'abcd' and 'efgh'(ok)"); + } + else { + out.println( + " - arguments 'abcd' and 'efgh' not found (error)"); + infoValid = false; + } + } + + // We do not care if orb_id is null - just that we can call it + + // CodecFactory must be valid: + if( id == null ) { + out.println( " - orb id is null (error)" ); + infoValid = false; + } + else { + out.println( " - orb id: " + id + " [non-null] (ok)" ); + } + if( codecFactory == null ) { + out.println( " - codecFactory is null (error)" ); + infoValid = false; + } + else { + out.println( " - codecFactory: valid" ); + } + } + catch( Exception e ) { + infoValid = false; + out.println( + " - Exception accessing attributes (error)" ); + } + + + // ORBInitInfo Method pre_init post_init + // ------------------ -------- --------- + // register_initial_reference x - + // resolve_initial_reference - x + + if( preInit ) { + out.print( " - Checking preInit validity: " ); + boolean preInitFailed = false; + + // Ensure register_initial_reference can be called + try { + info.register_initial_reference( + REFERENCE_NAME, this ); + } + catch( Exception e ) { + infoValid = false; + e.printStackTrace(); + out.println( + "Could not call register_initial_references (error)" + + " Reason: " + e ); + preInitFailed = true; + } + + // Ensure resolve_initial_references cannot be called + try { + info.resolve_initial_references( REFERENCE_NAME ); + infoValid = false; + out.println( + "Able to call resolve_initial_references (error)" ); + preInitFailed = true; + } + catch( Exception e ) { + // expected (ok). + } + + if( !preInitFailed ) out.println( "ok" ); + } + else { + out.print( " - Checking postInit validity: " ); + boolean postInitFailed = false; + + // Ensure register_initial_reference can be called + try { + info.register_initial_reference( + REFERENCE_NAME + "2", this ); + } + catch( Exception e ) { + infoValid = false; + out.println( + "Could not call register_initial_references (error)" + + " Reason: " + e ); + postInitFailed = true; + } + + // Ensure resolve_initial_references can be called + try { + info.resolve_initial_references( "CodecFactory" ); + } + catch( Exception e ) { + infoValid = false; + out.println( + "Unable to call resolve_initial_references (error)" ); + postInitFailed = true; + } + + if( !postInitFailed ) out.println( "ok" ); + } + + // These are trickier to test and require actually doing something + // useful. They will be hit later in the test. + // + // ORBInitInfo Method pre_init post_init + // ------------------ -------- --------- + // add_client_request_interceptor x x + // add_server_request_interceptor x x + // add_ior_interceptor x x + // allocate_slot_id x x + // register_policy_factory x x + + + return infoValid; + } + + /** + * Called after post_init to make sure we cannot still access + * ORBInitInfo. Returns false if we were able to access the + * ORBInitInfo object here, or true if not or if we did not get + * an OBJECT_NOT_EXIST exception. (true is pass, false is fail) + */ + public static boolean post_post_init () { + boolean result = true; + + out.println( " - Testing post_post_init access to initInfo..." ); + + try { + CodecFactory codecFactory = cachedInfo.codec_factory(); + + // We should not get to this point. + result = false; + out.println( " - able to access (error)" ); + } + catch( OBJECT_NOT_EXIST e ) { + // Correct exception was thrown + result = true; + out.println( " - OBJECT_NOT_EXIST thrown (ok)" ); + } + catch( Exception e ) { + // We should not get to this point. + result = false; + out.println( " - " + e + " thrown (error)" ); + } + + return result; + } + + /** + * Test the resolve_initial_references call, and record results for + * future retrieval from the test harness + */ + private void testResolveInitialReferences( ORBInitInfo info ) { + resolveInitialReferencesResults = + "Testing resolve_initial_references:\n"; + + try { + resolveInitialReferencesResults += + " - Testing info.resolve_initial_references( " + + "\"CodecFactory\" )... "; + org.omg.CORBA.Object objRef = + info.resolve_initial_references( "CodecFactory" ); + CodecFactory codecFactory = CodecFactoryHelper.narrow( objRef ); + if( objRef != null ) { + // If we go this far, we know we can look up existing + // references. + passResolveInitialReferences = true; + resolveInitialReferencesResults += "passed.\n"; + } + else { + passResolveInitialReferences = false; + resolveInitialReferencesResults += "failed. null received.\n"; + } + } + catch( Exception e ) { + passResolveInitialReferences = false; + resolveInitialReferencesResults += "failed: " + e + "\n"; + } + + // Ensure resolve_initial_references throws InvalidName at the + // appropiate times (the name to be resolved is invalid). + try { + resolveInitialReferencesResults += + " - Testing info.resolve_initial_references( " + + "\"CodecFactory2\" )... "; + org.omg.CORBA.Object objRef = + info.resolve_initial_references( "CodecFactory2" ); + // If we got this far, the resolve did not throw an InvalidName + // Exception as expected. + passResolveInitialReferencesInvalid = false; + resolveInitialReferencesResults += + "failed. InvalidName not raised.\n"; + } + catch( + org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName e ) + { + // This is the correct IDL version of InvalidName. + passResolveInitialReferencesInvalid = true; + resolveInitialReferencesResults += + "InvalidName raised. (passed)\n"; + } + catch( Exception e ) { + // This is the incorrect PIDL version of InvalidName. + passResolveInitialReferencesInvalid = false; + resolveInitialReferencesResults += + "Incorrect Exception raised: " + e + " (failed).\n"; + } + + } + + private void testInterceptorRegistration( ORBInitInfo info, String name ) { + SampleClientRequestInterceptor cReqInt = + new SampleClientRequestInterceptor( name ); + SampleServerRequestInterceptor sReqInt = + new SampleServerRequestInterceptor( name ); + SampleIORInterceptor iInt = + new SampleIORInterceptor( name ); + String results = ""; + boolean resultOk = true; + + // Try adding a client request interceptor + results += " - Adding Client Request Interceptor... "; + try { + info.add_client_request_interceptor( cReqInt ); + results += "(ok)\n"; + } + catch( Exception e ) { + results += e + " (error)\n"; + resultOk = false; + } + + // Try adding a server request interceptor + results += " - Adding Server Request Interceptor... "; + try { + info.add_server_request_interceptor( sReqInt ); + results += "(ok)\n"; + } + catch( Exception e ) { + results += e + " (error)\n"; + resultOk = false; + } + + // Try adding an IOR interceptor + results += " - Adding IOR Interceptor... "; + try { + info.add_ior_interceptor( iInt ); + results += "(ok)\n"; + } + catch( Exception e ) { + results += e + " (error)\n"; + resultOk = false; + } + + // Try adding a client request interceptor with a duplicate name: + results += " - Testing Duplicate Interceptor... "; + try { + info.add_client_request_interceptor( cReqInt ); + + // If we get to here, it allowed us to add a duplicate name. + resultOk = false; + results += "No DuplicateName thrown (error)\n"; + } + catch( DuplicateName e ) { + // Expected. + results += "DuplicateName raised. (ok)\n"; + + } + catch( Exception e ) { + // Some other exception. Not expected. + results += e + " (error)\n"; + resultOk = false; + } + + // Try adding two anonymous interceptors in a row. + SampleClientRequestInterceptor cAnonymous1 = + new SampleClientRequestInterceptor( "" ); + SampleClientRequestInterceptor cAnonymous2 = + new SampleClientRequestInterceptor( "" ); + + // Try adding first anonymous interceptor + results += " - Testing First Anonymous Interceptor... "; + try { + info.add_client_request_interceptor( cAnonymous1 ); + + results += "allowed (ok)\n"; + } + catch( Exception e ) { + // Not expected. + results += e + " (error)\n"; + resultOk = false; + } + + // Try adding second anonymous interceptor + results += " - Testing Second Anonymous Interceptor... "; + try { + info.add_client_request_interceptor( cAnonymous2 ); + + results += "allowed (ok)\n"; + } + catch( Exception e ) { + // Not expected. + results += e + " (error)\n"; + resultOk = false; + } + + // This should be the end of this test. If we get to this point, + // we know all other calls were successful. + if( name.equals( "preinit" ) ) { + preAddInterceptorPass = resultOk; + preAddInterceptorResult = results; + } + else if( name.equals( "postinit" ) ) { + postAddInterceptorPass = resultOk; + postAddInterceptorResult = results; + } + + } + + private void testGetSetSlot(org.omg.PortableInterceptor.ORBInitInfo info) { + String results = ""; + boolean resultOk = true; + + results += " - Testing PICurrent::get_slot access... "; + try { + org.omg.PortableInterceptor.Current pic = + (org.omg.PortableInterceptor.Current) + info.resolve_initial_references( "PICurrent" ); + pic.get_slot( 0 ); + + results += "accessible. (error)\n"; + resultOk = false; + } + catch( BAD_INV_ORDER e ) { + results += "inaccessible. (ok)\n"; + } + catch( Exception e ) { + results += "inaccessible, but wrong Exception (" + e + + " instead of BAD_INV_ORDER). (error)\n"; + resultOk = false; + } + + results += " - Testing PICurrent::set_slot access... "; + try { + org.omg.PortableInterceptor.Current pic = + (org.omg.PortableInterceptor.Current) + info.resolve_initial_references( "PICurrent" ); + pic.set_slot( 0, null ); + + results += "accessible. (error)\n"; + resultOk = false; + } + catch( BAD_INV_ORDER e ) { + results += "inaccessible. (ok)\n"; + } + catch( Exception e ) { + results += "inaccessible, but wrong Exception (" + e + + " instead of BAD_INV_ORDER). (error)\n"; + resultOk = false; + } + + getSetSlotPass = resultOk; + getSetSlotResult = results; + } +} diff --git a/functional-tests/src/test/java/pi/orbinit/ORBInitTest.java b/functional-tests/src/test/java/pi/orbinit/ORBInitTest.java new file mode 100644 index 000000000..a65979d4d --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/ORBInitTest.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import corba.framework.*; +import java.util.*; + +/** + * Tests ORBInitializer and ORBInitInfo as per Portable Interceptors spec + * orbos/99-12-02, Chapter 9. See pi/assertions.html for Assertions + * covered in this test. + */ +public class ORBInitTest extends CORBATest { + // Set to true if at least one test fails. + private boolean failed = false; + + protected void doTest() throws Throwable { + System.out.println(); + + printBeginTest( "[Properties Object] " ); + Controller orbd = createORBD(); + orbd.start(); + Controller client = createClient( "pi.orbinit.PropsClient" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + orbd.stop(); + pause(); + + /* Second time around is invalid unless flags in ClientTestInitializer + * are cleared; so how did this ever work correctly? + * Also note that system vs. props test is not needed here, + * as the ORB initialization test already covers that. + + printBeginTest( "[System Properties] " ); + orbd = createORBD(); + orbd.start(); + client = createClient( "pi.orbinit.SystemClient" ); + client.start(); + client.waitFor(); + printEndTest( client, null ); + client.stop(); + orbd.stop(); + */ + + System.out.print( " Final Result: " ); + if( failed ) { + throw new RuntimeException( "Errors detected" ); + } + } + + private void printBeginTest( String name ) { + System.out.print( " " + name ); + } + + private void printEndTest( Controller client, Controller server ) + throws Throwable + { + if( (server != null) && server.finished() ) { + System.out.println( "FAILED, Server crashed" ); + failed = true; + } + else if( client.exitValue() != Controller.SUCCESS ) { + System.out.println( "FAILED, Client exit value = " + + client.exitValue() ); + failed = true; + } + else { + System.out.println( "PASSED" ); + } + } + + // Pause a little to allow all processes to fully terminate. + private void pause() { + try { + Thread.sleep( 2000 ); + } + catch( InterruptedException e ) { + // ignore. + } + } + +} + diff --git a/functional-tests/src/test/java/pi/orbinit/PropsClient.java b/functional-tests/src/test/java/pi/orbinit/PropsClient.java new file mode 100644 index 000000000..52daaa07c --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/PropsClient.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +/** + * Client that passes in orb initializers as a properties object + */ +public class PropsClient + extends ClientCommon +{ + public static void main(String args[]) { + try { + (new PropsClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + protected ORB createORB( String[] args ) { + // Initializer classes + String invalidInitializer = "com.sun.nonexistent.intializer.Foo"; + String testInitializer = "pi.orbinit.ClientTestInitializer"; + + // add an additional argument to args[]. + String[] newArgs = new String[ args.length + 2 ]; + int i = 0; + for( i = 0; i < args.length; i++ ) { + newArgs[i] = args[i]; + } + + // We will check for the presence of these arguments later: + newArgs[i++] = "abcd"; + newArgs[i++] = "efgh"; + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + invalidInitializer, "" ); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + + return ORB.init(newArgs, props); + } + +} diff --git a/functional-tests/src/test/java/pi/orbinit/SampleClientRequestInterceptor.java b/functional-tests/src/test/java/pi/orbinit/SampleClientRequestInterceptor.java new file mode 100644 index 000000000..3e450ab08 --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/SampleClientRequestInterceptor.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import org.omg.CORBA.LocalObject; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; + +import ORBInitTest.*; + +/** + * Sample ClientRequestInterceptor for use in testing + */ +public class SampleClientRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor +{ + + private String name; + + // Number of times destroy was called for interceptors of this type. + static int destroyCount = 0; + + public SampleClientRequestInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + destroyCount++; + } + + public void send_request (ClientRequestInfo ri) + throws ForwardRequest + { + } + + public void send_poll (ClientRequestInfo ri) { + } + + public void receive_reply (ClientRequestInfo ri) { + } + + public void receive_exception (ClientRequestInfo ri) + throws ForwardRequest + { + } + + public void receive_other (ClientRequestInfo ri) + throws ForwardRequest + { + } + +} + + diff --git a/functional-tests/src/test/java/pi/orbinit/SampleIORInterceptor.java b/functional-tests/src/test/java/pi/orbinit/SampleIORInterceptor.java new file mode 100644 index 000000000..577ca093d --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/SampleIORInterceptor.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import org.omg.CORBA.LocalObject; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.IORInterceptor; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; + +import ORBInitTest.*; + +/** + * Sample IORInterceptor for use in testing + */ +public class SampleIORInterceptor + extends org.omg.CORBA.LocalObject + implements IORInterceptor +{ + + private String name; + + // Number of times destroy was called on this type of interceptor. + static int destroyCount = 0; + + public SampleIORInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + destroyCount++; + } + + public void establish_components (IORInfo info) { + } + + public void components_established( IORInfo info ) + { + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + } + + public void adapter_manager_state_changed( int managedId, short state ) + { + } +} + + diff --git a/functional-tests/src/test/java/pi/orbinit/SampleObjectImpl.java b/functional-tests/src/test/java/pi/orbinit/SampleObjectImpl.java new file mode 100644 index 000000000..17971ce1c --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/SampleObjectImpl.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import ORBInitTest.*; + +public class SampleObjectImpl + extends _SampleObjectImplBase +{ + private short _x; + private short _y; + + public short x () { + return _x; + } + + public void x (short newX) { + this._x = newX; + } + + public short y () { + return _y; + } + + public void y (short newY) { + this._y = newY; + } + +} + + diff --git a/functional-tests/src/test/java/pi/orbinit/SampleServerRequestInterceptor.java b/functional-tests/src/test/java/pi/orbinit/SampleServerRequestInterceptor.java new file mode 100644 index 000000000..f341f6009 --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/SampleServerRequestInterceptor.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import org.omg.CORBA.LocalObject; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ServerRequestInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; + +import ORBInitTest.*; + +/** + * Sample ServerRequestInterceptor for use in testing + */ +public class SampleServerRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ServerRequestInterceptor +{ + + private String name; + + static int destroyCount = 0; + + public SampleServerRequestInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + destroyCount++; + } + + public void receive_request_service_contexts (ServerRequestInfo ri) + throws ForwardRequest + { + } + + public void receive_request (ServerRequestInfo ri) + throws ForwardRequest + { + } + + public void send_reply (ServerRequestInfo ri) { + } + + public void send_exception (ServerRequestInfo ri) + throws ForwardRequest + { + } + + public void send_other (ServerRequestInfo ri) + throws ForwardRequest + { + } + +} + + diff --git a/functional-tests/src/test/java/pi/orbinit/SystemClient.java b/functional-tests/src/test/java/pi/orbinit/SystemClient.java new file mode 100644 index 000000000..98cfd562d --- /dev/null +++ b/functional-tests/src/test/java/pi/orbinit/SystemClient.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.orbinit; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +/** + * Client that passes in orb initializers as system properties. + */ +public class SystemClient + extends ClientCommon +{ + public static void main(String args[]) { + try { + (new SystemClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + protected ORB createORB( String[] args ) { + // Initializer classes + String invalidInitializer = "com.sun.nonexistent.intializer.Foo"; + String testInitializer = "pi.orbinit.ClientTestInitializer"; + + // add an additional argument to args[]. + String[] newArgs = new String[ args.length + 2 ]; + int i = 0; + for( i = 0; i < args.length; i++ ) { + newArgs[i] = args[i]; + } + + // We will check for the presence of these arguments later: + newArgs[i++] = "abcd"; + newArgs[i++] = "efgh"; + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + System.setProperty( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + invalidInitializer, "" ); + System.setProperty( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + + return ORB.init(newArgs, props); + } + +} diff --git a/functional-tests/src/test/java/pi/ort/Constants.java b/functional-tests/src/test/java/pi/ort/Constants.java new file mode 100644 index 000000000..bb84b3c75 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/Constants.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +public class Constants { + public static final String ORB_ID = "11111"; + + public static final String ORB_SERVER_ID = "2222"; +} diff --git a/functional-tests/src/test/java/pi/ort/DelayServant.java b/functional-tests/src/test/java/pi/ort/DelayServant.java new file mode 100644 index 000000000..aa0175492 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/DelayServant.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +import IORInterceptorTest.*; // for IDL + +/** + * Servant implementation for delayPOA. This is a special servant created for + * ORT testing, it has one method that sleeps for the given time and notifies + * ORTStateChangeEvaluator after completion with the notificationToken. + */ +public class DelayServant extends delayPOA { + public void forInMillis( int timeInMillis, String notificationToken ) { + try { + System.out.println( "DelayServant.forInMillis() called with " + + timeInMillis ); + System.out.flush( ); + Thread.sleep( timeInMillis ); + ORTStateChangeEvaluator.getInstance( ).notificationTokenFromDelayServant( notificationToken ); + } catch( Exception e ) { + System.err.println( "The Thread.sleep() in DelayServant crashed " + + e ); + e.printStackTrace( ); + System.exit( 1 ); + } + } +} diff --git a/functional-tests/src/test/java/pi/ort/ORTStateChangeEvaluator.java b/functional-tests/src/test/java/pi/ort/ORTStateChangeEvaluator.java new file mode 100644 index 000000000..a06d58587 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/ORTStateChangeEvaluator.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +import org.omg.PortableInterceptor.*; + +/** + * ORTStateChangeEvaluator is a Singleton used for + * 1. registering Adapter and AdapterState Changes from the IORInterceptor + * 2. evaluating that the statechanges happed as expected + * 3. notifying DelayServant.method() completion + */ +public class ORTStateChangeEvaluator { + private static ORTStateChangeEvaluator ortStateChangeEvaluatorInstance = + new ORTStateChangeEvaluator ( ); + + String[] poasWhoseStateChangesAreReported; + short currentAdapterState; + int managerId; + short currentAdapterManagerState; + String notificationToken = null; + + + boolean registerAdapterStateChangeCalled; + + private ORTStateChangeEvaluator( ) { + resetAllStates( ); + } + + public static ORTStateChangeEvaluator getInstance( ) { + return ortStateChangeEvaluatorInstance; + } + + /** + * The AdapterStateChange from the IORInterceptor is notified here. + */ + public void registerAdapterStateChange(ObjectReferenceTemplate[] templates, + short state ) + { + System.out.println( "registerAdapterState Change called...." ); + System.out.flush( ); + if( ( templates == null ) + ||( templates.length == 0 ) ) + { + System.err.println( + "Adapter State Change called with no templates"); + System.exit( -1 ); + } + this.poasWhoseStateChangesAreReported = new String[templates.length]; + for( int i = 0; i < templates.length; i++ ) { + String[] adapterNames = templates[i].adapter_name( ); + poasWhoseStateChangesAreReported[i] = + adapterNames[ adapterNames.length - 1 ]; + System.out.println("\t- POAs Whose State Change Is Reported : " + + poasWhoseStateChangesAreReported[i] ); + System.out.println("\t - POA Parent to Child list.." ); + for( int j = 0; j < adapterNames.length; j++ ) { + System.out.println( "\t\t + " + adapterNames[j] ); + System.out.flush( ); + } + System.out.flush( ); + } + this.currentAdapterState = state; + System.out.println( "\t - State Changed to " + state ); + System.out.flush( ); + registerAdapterStateChangeCalled = true; + } + + + + /** + * The AdapterManagerStateChange from the IORInterceptor is notified here. + */ + public void registerAdapterManagerStateChange( int managerId, short state ) + { + this.managerId = managerId; + this.currentAdapterManagerState = state; + System.out.println( + "\t- AdapterManagerStateChange Manager Id = " + managerId + + " state = " + state ); + System.out.flush( ); + } + + /** + * Compares the list of POAs whose destroyed notifications are expected Vs. + * the list of POAs whose destroyed notifications are actually recieved. + * If it doesn't match it returns false, else the evaluation passed. + */ + public boolean evaluateAdapterStateChange( String[] poas ) { + if( currentAdapterState != NON_EXISTENT.value ) + { + System.err.println( "AdapterStateChange reported = " + + currentAdapterState ); + System.err.println( "AdapterStateChange Expected = " + + NON_EXISTENT.value ); + return false; + } + boolean check = checkAllPOAStateChangesReported( poas ); + return check; + + } + + /** + * Very similar to the previous method with an extra check to see if the + * token passed matches the notificationToken recieved from DelayServant. + */ + public boolean evaluateAdapterStateChange( String[] poas, String token ) { + if( ( notificationToken == null ) + ||( !notificationToken.equals( token ) ) ) { + System.err.println( "POA Destroy is notified before completing " + + " invocations...." ); + System.err.flush( ); + return false; + } + return evaluateAdapterStateChange( poas ); + } + + + /** + * A simple utility to compare two arrays. + * _REVISIT_: Ken might have an utility to compare two arrays, just use + * that. + */ + private boolean checkAllPOAStateChangesReported( String[] poas ) { + if( poas.length != poasWhoseStateChangesAreReported.length ) { + return false; + } + int i = 0, j = 0; + boolean matchFound; + for( i = 0; i < poas.length; i++ ) { + matchFound = false; + for( j = 0; j < poas.length; j++ ) { + if( poasWhoseStateChangesAreReported[j].equals( poas[i] ) ) { + matchFound = true; + break; + } + } + if( !matchFound ) { + return false; + } + } + return true; + } + + /** + * Compares the AdapterManagerState notified from IOR interceptor with + * passed in state. If it doesn't match then, it returns false. + */ + public boolean evaluateAdapterManagerState( short state ) { + if( currentAdapterManagerState == state ) { + return true; + } + System.err.println( "In evaluateAdapterManagerState " ); + System.err.print( "currentAdapterManagerState = " + + currentAdapterManagerState ); + System.err.print( " is Not Equal To " + state ); + return false; + } + + /** + * resets all the variable states to allow for a new test to start. + */ + void resetAllStates( ) { + currentAdapterState = 0; + currentAdapterManagerState = 0; + notificationToken = null; + poasWhoseStateChangesAreReported = null; + managerId = 0; + registerAdapterStateChangeCalled = false; + } + + /** + * DelayServant will invoke this method with a notificationToken passed to + * it to signal the method completion. + */ + public void notificationTokenFromDelayServant( String token ) { + System.out.println( "notificationTokenFromDelayServant called with " + + " the token = " + token ); + System.out.flush( ); + notificationToken = token; + } +} + + + diff --git a/functional-tests/src/test/java/pi/ort/ORTTest.java b/functional-tests/src/test/java/pi/ort/ORTTest.java new file mode 100644 index 000000000..36293a0f2 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/ORTTest.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +import org.omg.CORBA.*; +import corba.framework.*; +import java.util.*; + +/** + * Tests IORInterceptor and IORInfo as per Portable Interceptors spec + * orbos/99-12-02, Chapter 7. See pi/assertions.html for Assertions + * covered in this test. + */ +public class ORTTest extends CORBATest +{ + protected void doTest() + throws Throwable + { + Controller server = createServer( "pi.ort.Server" ); + + server.start(); + + // NOTE: This sleep is required, there are some more tests that is + // still running even after recievig "Server is Ready" handshake. + Thread.sleep( 80000 ); + + server.stop(); + + } +} + diff --git a/functional-tests/src/test/java/pi/ort/Readme.txt b/functional-tests/src/test/java/pi/ort/Readme.txt new file mode 100644 index 000000000..6c9e1a2e1 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/Readme.txt @@ -0,0 +1,25 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +To test ORT related interceptor notifications, the following infrastructure +is used. + +1. ORTStateChangeEvaluator (A Singleton) recieves AdapterStateChange and + AdapterManagerStateChange Notifications from SampleIORInterceptor + and provides utility methods to evaluate (compare) the expected state + Vs. the actual state. Server.java uses ORTStateChangeEvaluator to check + that the test is working by passing expected states. +2. SampleIORInterceptor simply reports the state changes to + ORTStateChangeEvaluator +3. Server.java drives the test + +This test also verifies that ORBId and ORBServerId values are propogated +correctly to IORInterceptor. + diff --git a/functional-tests/src/test/java/pi/ort/SampleIORInterceptor.java b/functional-tests/src/test/java/pi/ort/SampleIORInterceptor.java new file mode 100644 index 000000000..5e4256987 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/SampleIORInterceptor.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +import java.io.*; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; + +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import org.omg.IOP.TaggedComponent; +import org.omg.IOP.TAG_INTERNET_IOP; + +/** + * Thoroughly tests IORInterceptor support. + */ +public class SampleIORInterceptor + extends LocalObject + implements IORInterceptor_3_0 +{ + + // The name for this interceptor + private String name; + + // Destination for all output. This is set in the constructor, which + // is called by ServerTestInitializer. + private PrintStream out; + + public SampleIORInterceptor( String name, PrintStream out ) { + this.name = name; + this.out = out; + out.println( " - IORInterceptor " + name + " created." ); + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void establish_components (IORInfo info) { + } + + /** + * Check ORBId and ORBServerId are propogated correctly. + */ + public void components_established( IORInfo info ) + { + com.sun.corba.ee.impl.interceptors.IORInfoImpl iorInfoImpl = + (com.sun.corba.ee.impl.interceptors.IORInfoImpl) info; + ObjectReferenceTemplate ort = iorInfoImpl.adapter_template(); + if( !ort.orb_id().equals( Constants.ORB_ID ) && + !ort.orb_id().equals(com.sun.corba.ee.impl.ior.ObjectKeyTemplateBase.JIDL_ORB_ID)) { + System.err.println( + "ORBId is not passed to components_established correctly.."); + System.exit( -1 ); + } + + if( !ort.server_id().equals( Constants.ORB_SERVER_ID ) ) { + System.err.println( + "ORBServerId is not passed to components_established correctly.."); + System.exit( -1 ); + } + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) + { + ORTStateChangeEvaluator.getInstance( ).registerAdapterStateChange( + templates, state ); + } + + public void adapter_manager_state_changed( int managedId, short state ) + { + ORTStateChangeEvaluator.getInstance().registerAdapterManagerStateChange( + managedId, state ); + } +} + + diff --git a/functional-tests/src/test/java/pi/ort/Server.java b/functional-tests/src/test/java/pi/ort/Server.java new file mode 100644 index 000000000..450cbe9dd --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/Server.java @@ -0,0 +1,441 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import IORInterceptorTest.*; // for IDL +import corba.framework.InternalProcess; +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableInterceptor.NON_EXISTENT; +import org.omg.PortableServer.IdUniquenessPolicyValue; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.POAManager; + +public class Server + implements InternalProcess +{ + + private static final String ROOT_POA = "RootPOA"; + + private POA rootPOA; + + // Set from run() + private PrintStream out; + private PrintStream err; + private ORB orb; + + private JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + + public static void main(String args[]) { + try { + (new Server()).run( System.getProperties(), + args, System.out, System.err, null ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + this.out = out; + this.err = err; + + out.println( "Instantiating ORB" ); + out.println( "=================" ); + + // Initializer class + String testInitializer = "pi.ort.ServerTestInitializer"; + ServerTestInitializer.out = out; + + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + props.put( ORBConstants.ORB_ID_PROPERTY, Constants.ORB_ID ); + props.put( ORBConstants.ORB_SERVER_ID_PROPERTY, + Constants.ORB_SERVER_ID ); + orb = ORB.init(args, props); + ServerTestInitializer.orb = orb; + + // Get root POA: + out.println( "Server retrieving root POA:" ); + rootPOA = (POA)orb.resolve_initial_references( "RootPOA" ); + rootPOA.the_POAManager().activate(); + + // Check to make sure that POA state changes are notified + // in the IOR Interceptor. + checkAdapterStateChangesTest1(); + + //handshake: + out.println("Server is ready."); + out.flush(); + + checkAdapterStateChangesTest2(); + + checkAdapterStateChangesTest3(); + + // NOTE: THIS TEST SHOULD ALWAYS BE THE LAST ONE. IT DESTROYS + // THE POAMANAGER + // Check to make sure that POAManager state changes are notified + // in the IOR Interceptor. + checkAdapterManagerStateChanges(); + } finally { + helper.done() ; + } + } + + /** + * checkAdapterManagerStateChanges tests that the ORT notifications of + * POAManager works right. These are the states it checks + * ACTIVE -> HOLD -> DISCARD -> DEACTIVATE + */ + private void checkAdapterManagerStateChanges() { + helper.start( "checkAdapterManagerStateChanges" ) ; + out.println( + "Checking if AdapterManagerStateChanges are registered..." ); + try { + try { + ORTStateChangeEvaluator stateChangeEvaluator = + ORTStateChangeEvaluator.getInstance( ); + stateChangeEvaluator.resetAllStates( ); + POAManager manager = rootPOA.the_POAManager( ); + manager.hold_requests( true ); + evaluateAdapterManagerStateChange( ); + manager.discard_requests( true ); + evaluateAdapterManagerStateChange( ); + manager.deactivate( false, true ); + evaluateAdapterManagerStateChange( ); + } catch( org.omg.PortableServer.POAManagerPackage.AdapterInactive e ) { + err.println( "Unexpected AdapterInactive Exception in " + + " checkAdapterManagerStateChanges " ); + throw new RuntimeException( + "checkAdapterManagerStateChanges FAILED!"); + } + out.println( "checkAdapterManagerStateChanges PASSED.." ); + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + + /** + * This is a utility method to check that the POAManager state and + * the state in ORTStateChangeEvaluator is same. If not, it raises + * a RuntimeException. + */ + private void evaluateAdapterManagerStateChange( ) { + ORTStateChangeEvaluator stateChangeEvaluator = + ORTStateChangeEvaluator.getInstance( ); + POAManager manager = rootPOA.the_POAManager( ); + if( !stateChangeEvaluator.evaluateAdapterManagerState( (short) + manager.get_state( ).value( ) ) ) + { + err.println( "ERROR: Current POAManager state change:" + + manager.get_state( ).value( ) + + " is not notified to IORInterceptor.." ); + throw new RuntimeException( + "checkAdapterManagerStateChanges FAILED!"); + } + } + + + /** + * These are the ORT Adapter State Change tests. + * Test 1: Create 2 group of POAs and destroy one group at a time and + * make sure that the destroyed notifications for all the POAs + * are obtained as a group. + */ + private void checkAdapterStateChangesTest1( ) { + helper.start( "checkAdapterStateChangesTest1" ) ; + + System.out.println( "checkAdapterStateChangesTest1 BEGIN.." ); + try { + try { + ORTStateChangeEvaluator stateChangeEvaluator = + ORTStateChangeEvaluator.getInstance( ); + stateChangeEvaluator.resetAllStates( ); + + String[] poaGroup1 = { "POA1", "POA11", "POA12" }; + + String[] poaGroup2 = { "POA2", "POA21", "POA22" }; + + POA[] poaList1 = createPOAs( poaGroup1 ); + + POA[] poaList2 = createPOAs( poaGroup2 ); + + poaList1[0].destroy( false, true ); + evaluateAdapterStateChange( poaGroup1, null ); + + stateChangeEvaluator.resetAllStates( ); + + poaList2[0].destroy( false, true ); + evaluateAdapterStateChange( poaGroup2, null); + + System.out.println( "checkAdapterStateChanges Test1 PASSED.." ); + + } catch( Exception e ) { + err.println( "EXCEPTION : In checkAdapterStateChangeTest1 " + e ); + e.printStackTrace( ); + throw new RuntimeException( + "checkAdapterStateChanges Test1 FAILED!"); + } + + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Test 2: This test is very similar to Test 1, but little more complex. + * It creates a group of POAs and a Servant (DelayServant) using + * one of the child POAs. A method is invoked on the Servant in a + * separate thread, this method will sleep for a minute or so. + * Parallely destroy the parent POA and check to see that detroyed + * notifications do happen after the completion of the method on + * DelayServant. + */ + private void checkAdapterStateChangesTest2( ) { + helper.start( "checkAdapterStateChangesTest2" ) ; + + try { + System.out.println( "checkAdapterStateChangesTest2 BEGIN.." ); + try { + ORTStateChangeEvaluator stateChangeEvaluator = + ORTStateChangeEvaluator.getInstance( ); + stateChangeEvaluator.resetAllStates( ); + + final String NOTIFICATION_TOKEN = "POA12INVOCATION_COMPLETE"; + String[] poasUnderTest = {"POA1", "POA11", "POA12" }; + POA[] poaList = createPOAs( poasUnderTest ); + + org.omg.CORBA.Object object = createDelayServant( poaList[2] ); + final delay aDelay = delayHelper.narrow( object ); + new Thread( ) { + public void run() { + try { + aDelay.forInMillis(30000, NOTIFICATION_TOKEN ); + } catch( Exception e ) { + System.err.println( "Failed to invoke on aDelay " + + " servant..." + e ); + e.printStackTrace( ); + System.exit( 1 ); + } + } + }.start( ); + + // This sleep is to make sure that the Thread in the previous + // statement is started for sure before calling POA.destroy + Thread.sleep( 5000 ); + poaList[0].destroy( false, true ); + evaluateAdapterStateChange( poasUnderTest, NOTIFICATION_TOKEN ); + System.out.println( "checkAdapterStateChangesTest2 PASSED.." ); + } catch( Exception e ) { + err.println( "EXCEPTION : In checkAdapterStateChangeTest2 " + e ); + e.printStackTrace( ); + throw new RuntimeException( + "checkAdapterStateChanges Test2 FAILED!"); + } + + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + /** + * Test 3: This test is very similar to Test 2, but with + * wait_for_completion for POA.destroy is set to false. + * It creates a group of POAs and a Servant (DelayServant) using + * one of the child POAs. A method is invoked on the Servant in a + * separate thread, this method will sleep for a minute or so. + * Parallely destroy the parent POA and check to see that destroyed + * notifications do happen after the completion of the method on + * DelayServant. + * + * NOTE: The sleep times are added to make sure that the destroyed + * notification happens only after the invoke on DelayServant is complete. + */ + private void checkAdapterStateChangesTest3( ) { + helper.start( "checkAdapterStateChangesTest2" ) ; + + System.out.println( "checkAdapterStateChangesTest3 BEGIN.." ); + + try { + try { + ORTStateChangeEvaluator stateChangeEvaluator = + ORTStateChangeEvaluator.getInstance( ); + stateChangeEvaluator.resetAllStates( ); + + final String NOTIFICATION_TOKEN = "POA11INVOCATION_COMPLETE"; + String[] poasUnderTest = {"POA1", "POA11", "POA12" }; + POA[] poaList = createPOAs( poasUnderTest ); + + org.omg.CORBA.Object object = createDelayServant( poaList[1] ); + final delay aDelay = delayHelper.narrow( object ); + new Thread( ) { + public void run() { + try { + aDelay.forInMillis(30000,NOTIFICATION_TOKEN ); + } catch( Exception e ) { + System.err.println( "Failed to invoke on aDelay " + + " servant..." + e ); + e.printStackTrace( ); + System.exit( 1 ); + } + } + }.start( ); + // This sleep is to make sure that the Thread in the previous + // statement is started for sure before calling POA.destroy + Thread.sleep( 5000 ); + + poaList[0].destroy( false, false ); + + Thread.sleep( 5000 ); + + boolean testStatus = true; + + // Negative test to make sure that the destroy notification has + // not happened before completing DelayServant method. + try { + evaluateAdapterStateChange( poasUnderTest, NOTIFICATION_TOKEN ); + // If evaluation passed, then this test failed. + testStatus = false; + } catch( RuntimeException re ) { + // This is the expected result + } + + // Positive test to make sure that the destroy notification + // happened after completing DelaySerant method + if (testStatus) { + // Wait for a while to finish the invocation on the DelayServant + int i = 0; + while(!stateChangeEvaluator.registerAdapterStateChangeCalled){ + System.out.println( "..Wait Loop.." + i++ ); + Thread.sleep( 5000 ); + } + // Now check to see if the notifications have happened + // correctly + evaluateAdapterStateChange( poasUnderTest, NOTIFICATION_TOKEN ); + System.out.println( "checkAdapterStateChangesTest3 PASSED.." ); + } else { + // If we are here then the test failed + throw new RuntimeException( "TEST FAILED..." ); + } + } catch( Exception e ) { + err.println( "EXCEPTION : In checkAdapterStateChangeTest3 " + e ); + e.printStackTrace( ); + throw new RuntimeException( + "checkAdapterStateChanges Test3 FAILED!"); + } + + helper.pass() ; + } catch (RuntimeException exc) { + helper.fail( exc ) ; + throw exc ; + } + } + + + /** + * A Utility method to create POAs. This creates + * 1. POA<1> under rootPOA using poaIds[0] + * 2. Child POAs using poaIds[1....n] under POA<1> + * + * NOTE: The return values is the ordered list of POAs created with + * one to one mapping of poaIds passed. The first element is the parent and + * others are children of the first POA. + */ + private POA[] createPOAs( String[] poaIds ) { + try { + POAManager poaManager = rootPOA.the_POAManager( ); + Policy[] policies = new Policy[1]; + + policies[0] = rootPOA.create_id_uniqueness_policy( + IdUniquenessPolicyValue.MULTIPLE_ID ); + + POA[] poas = new POA[poaIds.length]; + + poas[0] = rootPOA.create_POA( poaIds[0], poaManager, policies ); + for( int i = 1; i < poaIds.length; i++ ) { + poas[i] = poas[0].create_POA( poaIds[i], poaManager, policies ); + } + return poas; + } catch( Exception e ) { + err.println( "EXCEPTION : In checkAdapterStateChangeTest2 " + e ); + e.printStackTrace( ); + throw new RuntimeException( + "checkAdapterStateChanges Test2 FAILED!"); + } + + } + + /** + * This checks to make sure that all POA destroyed notifications are + * registered in ORTStateChangeEvaluator. If a token is not null, it will + * also check to make sure that token is sent from the delay servant. + * It throws RuntimeException if the evaluation fails. + */ + private void evaluateAdapterStateChange( + String[] poasWhoseStateChangesShouldbeReported, String token ) + { + ORTStateChangeEvaluator stateChangeEvaluator = + ORTStateChangeEvaluator.getInstance( ); + boolean testStatus = false; + if( token == null ) { + testStatus = stateChangeEvaluator.evaluateAdapterStateChange( + poasWhoseStateChangesShouldbeReported ); + } else { + testStatus = stateChangeEvaluator.evaluateAdapterStateChange( + poasWhoseStateChangesShouldbeReported, token ); + } + + if( !testStatus ) { + err.println( "ERROR: Adapter state change:" + + NON_EXISTENT.value + + " is not correctly notified to IORInterceptor.." ); + throw new RuntimeException( + "checkAdapterStateChanges FAILED!"); + } + } + + /** + * Create and Bind the DelayServant + */ + public org.omg.CORBA.Object createDelayServant ( POA poa ) + throws Exception + { + org.omg.CORBA.Object result; + // create servant and register it with the ORB + DelayServant delayServantRef = new DelayServant(); + + byte[] id = poa.activate_object(delayServantRef); + result = poa.id_to_reference(id); + + return result; + } + +} diff --git a/functional-tests/src/test/java/pi/ort/ServerTestInitializer.java b/functional-tests/src/test/java/pi/ort/ServerTestInitializer.java new file mode 100644 index 000000000..35f167564 --- /dev/null +++ b/functional-tests/src/test/java/pi/ort/ServerTestInitializer.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.ort; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * Registers the necessary IORInterceptor interceptors to test IORInterceptor. + */ +public class ServerTestInitializer + extends org.omg.CORBA.LocalObject + implements ORBInitializer +{ + + // The PrintStream to pass to the IORInterceptor for output + // This is set from Server.java, statically. + static PrintStream out; + + /** The ORB to pass to the IORInterceptor */ + static ORB orb; + + /** + * Creates a ServerTestInitializer + */ + public ServerTestInitializer() { + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + IORInterceptor iorInterceptor = new SampleIORInterceptor( "test", out); + try { + out.println( " - post_init: adding Sample IOR Interceptor..." ); + info.add_ior_interceptor( iorInterceptor ); + } + catch( DuplicateName e ) { + out.println( " - post_init: received DuplicateName!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/ClientCommon.java b/functional-tests/src/test/java/pi/serverinterceptor/ClientCommon.java new file mode 100644 index 000000000..ee65d89a0 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/ClientCommon.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +public abstract class ClientCommon + implements InternalProcess +{ + + // Set in run() + com.sun.corba.ee.spi.orb.ORB orb; + + // Set in run() + PrintStream out; + + // Set in run() + PrintStream err; + + // Set to true if the last invocation resulted in an exception. + boolean exceptionRaised; + + /** + * Creates a com.sun.corba.ee.spi.orb.ORB and notifies the TestInitializer of its presence + */ + void createORB( String[] args ) { + // create the ORB without an initializer + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + this.orb = (com.sun.corba.ee.spi.orb.ORB)ORB.init(args, props); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation. + */ + abstract void resolveReferences() throws Exception; + + /** + * Call syncWithServer on the server object + */ + abstract String syncWithServer() throws Exception; + + /** + * Invoke the method with the given name on the object + */ + abstract protected void invokeMethod( String methodName ) throws Exception; + + /** + * Wait for server to give us the name of a method to execute, and then + * execute that method. Repeat the process until the server tells us + * to execute a method called "exit." + */ + void obeyServer() throws Exception { + out.println( "+ Obeying commands from server." ); + + String methodName; + do { + // Re-resolve all references to eliminate any cached + // LOCATION_FORWARDs + resolveReferences(); + + // Synchronize with the server and get the name of the + // method to invoke.: + out.println( " - Syncing with server..." + + new Date().toString() ); + methodName = syncWithServer(); + out.println( " - Synced with server at " + + new Date().toString() ); + + // Execute the appropriate method on the hello object: + out.println( " - Executing method " + methodName + "..." ); + exceptionRaised = false; + try { + invokeMethod( methodName ); + } + catch( IMP_LIMIT e ) { + exceptionRaised = true; + out.println( " + Received IMP_LIMIT exception" ); + } + + } while( !methodName.equals( ServerCommon.EXIT_METHOD ) ); + + out.println( " - Exit detected. No longer obeying server." ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIImpl.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIImpl.java new file mode 100644 index 000000000..92d3a7b88 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIImpl.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.PortableInterceptor.*; +import org.omg.PortableServer.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Servant implementation, shared by ServerRequestDispatcher and POA versions of + * the servant. + */ +class DSIImpl { + // The object to delegate all calls to: + helloDelegate delegate; + + // The orb to use to make DSI-related calls on + private ORB orb; + + public DSIImpl( ORB orb, PrintStream out, String symbol ) { + super(); + this.orb = orb; + this.delegate = new helloDelegate( out, symbol ); + } + + public void invoke( ServerRequest r ) { + String opName = r.op_name(); + java.lang.Object result = null; + + if( opName.equals( "sayHello" ) ) { + sayHello( r ); + } + else if( opName.equals( "sayOneway" ) ) { + sayOneway( r ); + } + else if( opName.equals( "saySystemException" ) ) { + saySystemException( r ); + } + else if( opName.equals( "sayUserException" ) ) { + sayUserException( r ); + } + else if( opName.equals( "syncWithServer" ) ) { + syncWithServer( r ); + } + } + + private void sayHello( ServerRequest r ) { + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + String answer = delegate.sayHello(); + + // Return result: + Any result = orb.create_any(); + result.insert_string( answer ); + r.result( result ); + } + + private void sayOneway( ServerRequest r ) { + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + delegate.sayOneway(); + + // Return void result: + Any ret = orb.create_any(); + ret.type( orb.get_primitive_tc( TCKind.tk_void ) ); + r.set_result( ret ); + } + + private void saySystemException( ServerRequest r ) { + // Must call arguments first. Bug? + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + delegate.saySystemException(); + } + + private void sayUserException( ServerRequest r ) { + // Must call arguments first. Bug? + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + try { + delegate.sayUserException(); + } + catch( org.omg.PortableInterceptor.ForwardRequest e ) { + Any any = orb.create_any(); + org.omg.PortableInterceptor.ForwardRequestHelper.insert( any, e ); + r.except( any ); + } + } + + private void syncWithServer( ServerRequest r ) { + // Decode exceptionRaised parameter + NVList nvlist = orb.create_list( 0 ); + + Any a1 = orb.create_any(); + a1.type( orb.get_primitive_tc( TCKind.tk_boolean ) ); + nvlist.add_value( "exceptionRaised", a1, ARG_IN.value ); + r.arguments( nvlist ); + + boolean exceptionRaised = a1.extract_boolean(); + + // Make call to delegate: + String answer = delegate.syncWithServer( exceptionRaised ); + + // Return result: + Any result = orb.create_any(); + result.insert_string( answer ); + r.result( result ); + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIPOALocalServer.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIPOALocalServer.java new file mode 100644 index 000000000..fbac09e28 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIPOALocalServer.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Tests POA Local invocations (with a co-located orb) + */ +public class DSIPOALocalServer + extends DSIPOAServer +{ + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final DSIPOALocalServer server = new DSIPOALocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + server.out.println( "===================================" ); + server.out.println( "Creating ORB for DSI POA Local test" ); + server.out.println( "===================================" ); + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + Properties props = new Properties(); + server.createORB( args, props ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + POALocalClient client = new POALocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + // notify main that client can launch now: + synchronized( syncObject ) { + syncObject.notify(); + } + } + + void waitForClients() { + // NOP for this test. + } + + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIPOARemoteServer.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIPOARemoteServer.java new file mode 100644 index 000000000..dd2a7ed70 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIPOARemoteServer.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +public class DSIPOARemoteServer + extends DSIPOAServer +{ + public static void main(String args[]) { + try { + (new DSIPOARemoteServer()).run( System.getProperties(), + args, System.out, System.err, + null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=========================================" ); + out.println( "Instantiating ORB for DSI POA Remote test" ); + out.println( "=========================================" ); + + out.println( "+ Creating ORB..." ); + Properties props = new Properties(); + createORB( args, props ); + + super.run( environment, args, out, err, extra ); + + + } + + void handshake() { + out.println("Server is ready."); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIPOAServer.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIPOAServer.java new file mode 100644 index 000000000..61303fbcb --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIPOAServer.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Common base class for DSI POA Server test files. + */ +public abstract class DSIPOAServer + extends ServerCommon +{ + static final String ROOT_POA = "RootPOA"; + + POA rootPOA; + + // To be invoked by subclass after orb is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Get the root POA: + rootPOA = null; + out.println( "+ Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( rootPOA, "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( rootPOA, + "Hello1Forward", + "[Hello1Forward]" ); + + handshake(); + + // Test ServerInterceptor + testServerInterceptor(); + + // Test POA special operations + testSpecialOps(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + + // wait for invocations from clients + waitForClients(); + } + } + + // Output handshake or wake up main. + abstract void handshake(); + + // Wait for invocations from clients. + abstract void waitForClients(); + + /** + * Tests the special operations _is_a, _get_interface_def, and + * _non_existent. + */ + void testSpecialOps() + throws Exception + { + out.println(); + out.println( "Running Special Operations Tests" ); + out.println( "================================" ); + + out.println( "+ Testing _is_a..." ); + SampleServerRequestInterceptor.dontIgnoreIsA = true; + testInvocation( "testInvocationIsA", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "_is_a", "", false ); + + // We do not implement this interface in our ORB. + // Thus, the send_exception. We pass in false for exception + // expected because this is not the exception we normally look for. + out.println( "+ Testing _get_interface_def..." ); + testInvocation( "testInvocationGetInterfaceDef", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3se3se2se1", + "_get_interface_def", "", false ); + + out.println( "+ Testing _non_existent..." ); + testInvocation( "testInvocationNonExistent", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "_non_existent", "", false ); + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public org.omg.CORBA.Object createAndBind ( POA poa, String name, + String symbol ) + throws Exception + { + // create servant and register it with the ORB + helloDSIServant helloRef = new helloDSIServant( orb, out, symbol ); + + byte[] id = poa.activate_object(helloRef); + org.omg.CORBA.Object ref = poa.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + + return ref; + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIClient.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIClient.java new file mode 100644 index 000000000..4e7a5f832 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIClient.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInterceptor.*; + +/** + * Common base class for RMI client test code + */ +public abstract class DSIRMIClient + extends ClientCommon +{ + // The hello object to make invocations on. + hello helloRef; + + // Reference to hello object to be forwarded to. + hello helloRefForward; + + // RMI initial naming context + InitialContext initialNamingContext; + + // to be invoked from subclasses after the ORB is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.err = err; + + out.println( "+ Creating initial naming context..." + orb ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Obey the server's commands: + obeyServer(); + } + + void resolveReferences() throws Exception { + out.println( " - Resolving Hello1..." ); + // Look up reference to hello object on server: + helloRef = resolve( "Hello1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving Hello1Forward..." ); + helloRefForward = resolve( "Hello1Forward" ); + out.println( " - Resolved." ); + } + + String syncWithServer() throws Exception { + return helloRef.syncWithServer( exceptionRaised ); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + try { + helloRef.sayUserException(); + out.println( " - Did not catch ForwardRequest user " + + "exception (error)" ); + throw new RuntimeException( + "Did not catch ForwardRequest user exception " + + "on sayUserException" ); + } + catch( ForwardRequest e ) { + out.println( " - Caught ForwardRequest user " + + "exception (ok)" ); + } + } + } + + /** + * Resolves name using RMI + */ + hello resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + hello helloRef = (hello)helloHelper.narrow( (org.omg.CORBA.Object)obj); + + return helloRef; + } + + +} + + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIRMILocalClient.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMILocalClient.java new file mode 100644 index 000000000..badaaac91 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMILocalClient.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInterceptor.*; + +public class DSIRMILocalClient + extends DSIRMIClient +{ + public DSIRMILocalClient( com.sun.corba.ee.spi.orb.ORB orb ) { + this.orb = orb; + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "===============================================" ); + out.println( "Instantiating Client ORB for DSI RMI Local test" ); + out.println( "===============================================" ); + + super.run( environment, args, out, err, extra ); + } + +} + + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIRMILocalServer.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMILocalServer.java new file mode 100644 index 000000000..fa2cb3881 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMILocalServer.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class DSIRMILocalServer + extends DSIRMIServer +{ + // Object to syncrhornize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final DSIRMILocalServer server = new DSIRMILocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + System.out.println( "===================================" ); + System.out.println( "Creating ORB for DSI RMI Local test" ); + System.out.println( "===================================" ); + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + server.createORB( args, new Properties() ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting client..." ); + DSIRMILocalClient client = new DSIRMILocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + synchronized( syncObject ) { + syncObject.notifyAll(); + } + } + + void waitForClients() { + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIRemoteClient.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIRemoteClient.java new file mode 100644 index 000000000..f61da1798 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIRemoteClient.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInterceptor.*; + +public class DSIRMIRemoteClient + extends DSIRMIClient +{ + public static void main(String args[]) { + try { + (new DSIRMIRemoteClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "================================================" ); + out.println( "Instantiating Client ORB for DSI RMI Remote test" ); + out.println( "================================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + super.run( environment, args, out, err, extra ); + } +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIRemoteServer.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIRemoteServer.java new file mode 100644 index 000000000..8a4ae7df7 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIRemoteServer.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class DSIRMIRemoteServer + extends DSIRMIServer +{ + public static void main(String args[]) { + try { + (new DSIRMIRemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=========================================" ); + out.println( "Instantiating ORB for DSI RMI Remote test" ); + out.println( "=========================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args, new Properties() ); + + super.run( environment, args, out, err, extra ); + } + + void handshake() { + out.println( "Server is ready." ); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized( sync ) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIServer.java b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIServer.java new file mode 100644 index 000000000..c92575e61 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/DSIRMIServer.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public abstract class DSIRMIServer + extends ServerCommon +{ + InitialContext initialNamingContext; + + private static final String hello2Id = "qwerty"; + private String hello2IOR; + + private TestServantLocator servantLocator; + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create + // initial naming context: + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( "Hello1Forward", + "[Hello1Forward]" ); + + handshake(); + + // Test ServerInterceptor + testServerInterceptor(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + waitForClients(); + } + } + + abstract void handshake(); + + abstract void waitForClients(); + + /** + * Creates and binds a hello object using RMI + */ + public org.omg.CORBA.Object createAndBind ( String name, + String symbol ) + throws Exception + { + // create and register it with RMI + helloDSIDeprecatedServant obj = new helloDSIDeprecatedServant( + orb, out, symbol ); + orb.connect( obj ); + initialNamingContext.rebind( name, obj ); + + java.lang.Object o = initialNamingContext.lookup( name ); + return (org.omg.CORBA.Object)PortableRemoteObject.narrow( o, + org.omg.CORBA.Object.class ); + } + + /** + * Overridden from ServerCommon. Oneway calls are not supported in RMI. + */ + void testInvocation( String name, + int mode, + String correctOrder, + String methodName, + String correctMethodOrder, + boolean exceptionExpected ) + throws Exception + { + // Rebind each time so that location forward information is + // wiped out. See CDRInputStream1_0 readObject. This is necessary + // because the local case will always return the exact same object + // on the client side otherwise. + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( "Hello1Forward", + "[Hello1Forward]" ); + + + if( !methodName.equals( "sayOneway" ) ) { + super.testInvocation( name, mode, correctOrder, methodName, + correctMethodOrder, exceptionExpected ); + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/POAClient.java b/functional-tests/src/test/java/pi/serverinterceptor/POAClient.java new file mode 100644 index 000000000..4426723a5 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/POAClient.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +public abstract class POAClient + extends ClientCommon +{ + // The hello object to make invocations on. + hello helloRef; + + // Reference to hello object to be forwarded to. + hello helloRefForward; + + // To be invoked after the orb is created by subclasses. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.err = err; + + // Obey the server's commands: + obeyServer(); + } + + void resolveReferences() throws Exception { + out.println( " - Resolving Hello1..." ); + // Look up reference to hello object on server: + helloRef = resolve( orb, "Hello1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving Hello1Forward..." ); + helloRefForward = resolve( orb, "Hello1Forward" ); + out.println( " - Resolved." ); + } + + String syncWithServer() throws Exception { + return helloRef.syncWithServer( exceptionRaised ); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + try { + helloRef.sayUserException(); + out.println( " - Did not catch ForwardRequest user " + + "exception (error)" ); + throw new RuntimeException( + "Did not catch ForwardRequest user exception " + + "on sayUserException" ); + } + catch( ForwardRequest e ) { + out.println( " - Caught ForwardRequest user " + + "exception (ok)" ); + } + } + else if( methodName.startsWith( "sayHello2" ) ) { + // special method. Resolve helloRef2 and call sayHello. + String ior = methodName.substring( "sayHello2".length() + 1 ); + out.println( " - Resolving IOR " + ior ); + org.omg.CORBA.Object obj = orb.string_to_object( ior ); + out.println( " - Narrowing..." ); + hello helloRef2 = helloHelper.narrow( obj ); + out.println( " - Invoking sayHello..." ); + helloRef2.sayHello(); + out.println( " - Invoked." ); + } + else if( methodName.equals( "_is_a" ) ) { + out.println( " - Invoking _is_a..." ); + out.println( " - Result: " + + helloRef._is_a( "IDL:ServerRequestInterceptor/goodbye:1.0" ) ); + out.println( " - Invoked." ); + } + else if( methodName.equals( "_get_interface_def" ) ) { + out.println( " - Invoking _get_interface_def..." ); + try { + helloRef._get_interface_def(); + out.println( " - Invoked." ); + } + catch( NO_IMPLEMENT e ) { + out.println( " - Invoked. Received NO_IMPLEMENT (ok)." ); + } + } + else if( methodName.equals( "_non_existent" ) ) { + out.println( " - Invoking _non_existent..." ); + helloRef._non_existent(); + out.println( " - Invoked." ); + } + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + hello resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path)); + + return helloRef; + } + + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/POALocalClient.java b/functional-tests/src/test/java/pi/serverinterceptor/POALocalClient.java new file mode 100644 index 000000000..39c22a3d2 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/POALocalClient.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * This client is launched from POALocalServer so they can share + * a single orb. + */ +public class POALocalClient + extends POAClient +{ + public POALocalClient( com.sun.corba.ee.spi.orb.ORB orb ) { + this.orb = orb; + } + + public void run( Properties environment, String args[], + PrintStream out, PrintStream err, Hashtable extra) + throws Exception + { + out.println( "===============" ); + out.println( "Starting Client" ); + out.println( "===============" ); + + super.run( environment, args, out, err, extra ); + } + + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/POALocalServer.java b/functional-tests/src/test/java/pi/serverinterceptor/POALocalServer.java new file mode 100644 index 000000000..0d69846d3 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/POALocalServer.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Tests POA Local invocations (with a co-located orb) + */ +public class POALocalServer + extends POAServer +{ + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final POALocalServer server = new POALocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + server.out.println( "===============================" ); + server.out.println( "Creating ORB for POA Local test" ); + server.out.println( "===============================" ); + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + Properties props = new Properties(); + props.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "9999" ); + server.createORB( args, props ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + POALocalClient client = new POALocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + // notify main that client can launch now: + synchronized( syncObject ) { + syncObject.notify(); + } + } + + void waitForClients() { + // NOP for this test. + } + + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/POARemoteClient.java b/functional-tests/src/test/java/pi/serverinterceptor/POARemoteClient.java new file mode 100644 index 000000000..fd66009bc --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/POARemoteClient.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +public class POARemoteClient + extends POAClient +{ + public static void main(String args[]) { + try { + (new POARemoteClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "============================================" ); + out.println( "Instantiating Client ORB for POA Remote test" ); + out.println( "============================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + super.run( environment, args, out, err, extra ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/POARemoteServer.java b/functional-tests/src/test/java/pi/serverinterceptor/POARemoteServer.java new file mode 100644 index 000000000..ef3bb0f31 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/POARemoteServer.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +public class POARemoteServer + extends POAServer +{ + public static void main(String args[]) { + try { + (new POARemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=====================================" ); + out.println( "Instantiating ORB for POA Remote test" ); + out.println( "=====================================" ); + + out.println( "+ Creating ORB..." ); + Properties props = new Properties(); + props.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "9999" ); + createORB( args, props ); + + super.run( environment, args, out, err, extra ); + + + } + + void handshake() { + out.println("Server is ready."); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/POAServer.java b/functional-tests/src/test/java/pi/serverinterceptor/POAServer.java new file mode 100644 index 000000000..e1edabc15 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/POAServer.java @@ -0,0 +1,245 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Common base class for POA Server test files. + */ +public abstract class POAServer + extends ServerCommon +{ + static final String ROOT_POA = "RootPOA"; + + POA rootPOA; + POA persistentPOA; + + static final String hello2Id = "qwerty"; + String hello2IOR; + + TestServantLocator servantLocator; + + // To be invoked by subclass after orb is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + // Get the root POA: + rootPOA = null; + out.println( "+ Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( rootPOA, "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( rootPOA, + "Hello1Forward", + "[Hello1Forward]" ); + + // Create a persistent, non-retaining POA with a ServantLocator: + out.println( "+ Creating persistent POA with ServantLocator..." ); + persistentPOA = createPersistentPOA(); + + out.println( "+ Creating and binding Hello2 reference..." ); + hello2IOR = createReference( persistentPOA, "Hello2", + hello2Id.getBytes() ); + + handshake(); + + // Test ServerInterceptor + testServerInterceptor(); + + // Test ServantManager throwing a ForwardRequest. + testServantManager(); + + // Test POA special operations + testSpecialOps(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + + // wait for invocations from clients + waitForClients(); + } + } + + // Output handshake or wake up main. + abstract void handshake(); + + // Wait for invocations from clients. + abstract void waitForClients(); + + /** + * Tests that if a ServantManager throws a ForwardRequest, everything + * works as expected. + */ + void testServantManager() + throws Exception + { + out.println(); + out.println( "Running ServantManager test" ); + out.println( "===========================" ); + + out.println( "+ Testing standard invocation where ServantLocator " + + "redirects..." ); + testInvocation( "testInvocationServantLocatorRedirect", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3so3so2so1rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "sayHello2@" + hello2IOR, "[Hello1]", false ); + + // ServantLocator forwards to Hello1 and send_other throws + // SystemException. + out.println( "+ Testing invocation where ServantLocator redirects " + + "and send_other throws SystemException..." ); + servantLocator.resetFirstTime(); + testInvocation( "testInvocationServantLocatorRedirectSendOtherSystemException", + SampleServerRequestInterceptor.MODE_SO_SYSTEM_EXCEPTION, + "rs1rs2rs3so3so2se1", + "sayHello2@" + hello2IOR, "", true ); + + // ServantLocator forwards to Hello1 and send_other redirects to + // helloRefForward. + out.println( "+ Testing invocation where ServantLocator redirects " + + "and send_other further redirects..." ); + servantLocator.resetFirstTime(); + testInvocation( "testInvocationServantLocatorRedirectSendOtherRedirect", + SampleServerRequestInterceptor.MODE_SO_FORWARD_REQUEST, + "rs1rs2rs3so3so2so1rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "sayHello2@" + hello2IOR, "[Hello1Forward]", false ); + } + + /** + * Tests the special operations _is_a, _get_interface_def, and + * _non_existent. + */ + void testSpecialOps() + throws Exception + { + out.println(); + out.println( "Running Special Operations Tests" ); + out.println( "================================" ); + + out.println( "+ Testing _is_a..." ); + SampleServerRequestInterceptor.dontIgnoreIsA = true; + testInvocation( "testInvocationIsA", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "_is_a", "", false ); + + // We do not implement this interface in our ORB. + // Thus, the send_exception. We pass in false for exception + // expected because this is not the exception we normally look for. + out.println( "+ Testing _get_interface_def..." ); + testInvocation( "testInvocationGetInterfaceDef", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3se3se2se1", + "_get_interface_def", "", false ); + + out.println( "+ Testing _non_existent..." ); + testInvocation( "testInvocationNonExistent", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "_non_existent", "", false ); + } + + /** + * Borrowed from rmipoacounter test and modified: + */ + POA createPersistentPOA() + throws Exception + { + // create a persistent, non-retaining POA + Policy[] tpolicy = new Policy[3]; + tpolicy[0] = rootPOA.create_lifespan_policy( + LifespanPolicyValue.PERSISTENT ); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER ); + tpolicy[2] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN ); + + POA tpoa = rootPOA.create_POA("PersistentPOA", null, tpolicy); + + // register the ServantLocator with the POA, then activate POA + servantLocator = new TestServantLocator( out, orb, + TestInitializer.helloRef ); + tpoa.set_servant_manager( servantLocator ); + tpoa.the_POAManager().activate(); + return tpoa; + } + + /** + * Creates an object with an id, but does not bind it to the naming + * service. Returns the ior for that object. + */ + String createReference( POA poa, String name, byte[] id ) + throws Exception + { + org.omg.CORBA.Object obj = poa.create_reference_with_id( id, + "IDL:ServerRequestInterceptor/hello:1.0" ); + return orb.object_to_string( obj ); + } + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public org.omg.CORBA.Object createAndBind ( POA poa, String name, + String symbol ) + throws Exception + { + // create servant and register it with the ORB + helloServant helloRef = new helloServant( out, symbol ); + + byte[] id = poa.activate_object(helloRef); + org.omg.CORBA.Object ref = poa.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + + return ref; + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/RMIClient.java b/functional-tests/src/test/java/pi/serverinterceptor/RMIClient.java new file mode 100644 index 000000000..8286ed975 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/RMIClient.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInterceptor.*; + +/** + * Common base class for RMI client test code + */ +public abstract class RMIClient + extends ClientCommon +{ + // The hello object to make invocations on. + helloIF helloRef; + + // Reference to hello object to be forwarded to. + helloIF helloRefForward; + + // RMI initial naming context + InitialContext initialNamingContext; + + // to be invoked from subclasses after the ORB is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.err = err; + + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Obey the server's commands: + obeyServer(); + } + + void resolveReferences() throws Exception { + out.println( " - Resolving Hello1..." ); + // Look up reference to hello object on server: + helloRef = resolve( "Hello1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving Hello1Forward..." ); + helloRefForward = resolve( "Hello1Forward" ); + out.println( " - Resolved." ); + } + + String syncWithServer() throws Exception { + return helloRef.syncWithServer( exceptionRaised ); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + try { + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + try { + helloRef.sayUserException(); + out.println( " - Did not catch ForwardRequest user " + + "exception (error)" ); + throw new RuntimeException( + "Did not catch ForwardRequest user exception " + + "on sayUserException" ); + } + catch( ForwardRequest e ) { + out.println( " - Caught ForwardRequest user " + + "exception (ok)" ); + } + } + } + catch( RemoteException e ) { + throw (Exception)e.detail; + } + } + + /** + * Resolves name using RMI + */ + helloIF resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } + + +} + + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/RMILocalClient.java b/functional-tests/src/test/java/pi/serverinterceptor/RMILocalClient.java new file mode 100644 index 000000000..b5daa9fd2 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/RMILocalClient.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInterceptor.*; + +public class RMILocalClient + extends RMIClient +{ + public RMILocalClient( com.sun.corba.ee.spi.orb.ORB orb ) { + this.orb = orb; + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "===========================================" ); + out.println( "Instantiating Client ORB for RMI Local test" ); + out.println( "===========================================" ); + + super.run( environment, args, out, err, extra ); + } + +} + + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/RMILocalServer.java b/functional-tests/src/test/java/pi/serverinterceptor/RMILocalServer.java new file mode 100644 index 000000000..a846d5599 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/RMILocalServer.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class RMILocalServer + extends RMIServer +{ + // Object to syncrhornize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final RMILocalServer server = new RMILocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + System.out.println( "===============================" ); + System.out.println( "Creating ORB for RMI Local test" ); + System.out.println( "===============================" ); + + // For this test, start botht he client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + server.createORB( args, new Properties() ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting client..." ); + RMILocalClient client = new RMILocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + synchronized( syncObject ) { + syncObject.notifyAll(); + } + } + + void waitForClients() { + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/RMIRemoteClient.java b/functional-tests/src/test/java/pi/serverinterceptor/RMIRemoteClient.java new file mode 100644 index 000000000..7478dae03 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/RMIRemoteClient.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInterceptor.*; + +public class RMIRemoteClient + extends RMIClient +{ + public static void main(String args[]) { + try { + (new RMIRemoteClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "============================================" ); + out.println( "Instantiating Client ORB for RMI Remote test" ); + out.println( "============================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + super.run( environment, args, out, err, extra ); + } +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/RMIRemoteServer.java b/functional-tests/src/test/java/pi/serverinterceptor/RMIRemoteServer.java new file mode 100644 index 000000000..fcf200598 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/RMIRemoteServer.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class RMIRemoteServer + extends RMIServer +{ + public static void main(String args[]) { + try { + (new RMIRemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=====================================" ); + out.println( "Instantiating ORB for RMI Remote test" ); + out.println( "=====================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args, new Properties() ); + + super.run( environment, args, out, err, extra ); + } + + void handshake() { + out.println( "Server is ready." ); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized( sync ) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/RMIServer.java b/functional-tests/src/test/java/pi/serverinterceptor/RMIServer.java new file mode 100644 index 000000000..c14e357bb --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/RMIServer.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public abstract class RMIServer + extends ServerCommon +{ + InitialContext initialNamingContext; + + private static final String hello2Id = "qwerty"; + private String hello2IOR; + + private TestServantLocator servantLocator; + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create + // initial naming context: + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( "Hello1Forward", + "[Hello1Forward]" ); + + handshake(); + + // Test ServerInterceptor + testServerInterceptor(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + + waitForClients(); + } + } + + abstract void handshake(); + + abstract void waitForClients(); + + /** + * Creates and binds a hello object using RMI + */ + public org.omg.CORBA.Object createAndBind ( String name, + String symbol ) + throws Exception + { + // create and register it with RMI + helloRMIIIOP obj = new helloRMIIIOP( out, symbol ); + initialNamingContext.rebind( name, obj ); + + java.lang.Object o = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( o, + helloIF.class ); + return (org.omg.CORBA.Object)helloRef; + } + + /** + * Overridden from ServerCommon. Oneway calls are not supported in RMI. + */ + void testInvocation( String name, + int mode, + String correctOrder, + String methodName, + String correctMethodOrder, + boolean exceptionExpected ) + throws Exception + { + // Rebind each time so that location forward information is + // wiped out. See CDRInputStream1_0 readObject. This is necessary + // because the local case will always return the exact same object + // on the client side otherwise. + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( "Hello1Forward", + "[Hello1Forward]" ); + + + if( !methodName.equals( "sayOneway" ) ) { + super.testInvocation( name, mode, correctOrder, methodName, + correctMethodOrder, exceptionExpected ); + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/SampleServerRequestInterceptor.java b/functional-tests/src/test/java/pi/serverinterceptor/SampleServerRequestInterceptor.java new file mode 100644 index 000000000..1d1ad78e6 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/SampleServerRequestInterceptor.java @@ -0,0 +1,319 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.RequestInfo; +import org.omg.PortableInterceptor.ServerRequestInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; + +//import ORBInitTest.*; + +/** + * Sample ServerRequestInterceptor for use in testing + */ +public class SampleServerRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ServerRequestInterceptor +{ + // This string is modified from within this class and from Server.java. + // It keeps track of which method was invoked when by appending + // two-letter codes in succession. The following codes are used + // represents the name of the interceptor invoked. This is + // used to check order of interceptor invocation. + // + // rs = receive_request_service_contexts + // rr = receive_request + // sr = send_reply + // se = send_exception + // so = send_other + // For example, rs1rs2rr1rr2sr2sr1 would indicate a normal invocation. + public static String invocationOrder = ""; + + // This string is modified from within helloDelegate. It is appended to + // every time a relevant method is invoked so that we make check to make + // sure the methods are invoked on the correct objects for each test. + public static String methodOrder = ""; + + // The message to embed in exceptions so they can be checked for validity. + public static final String VALID_MESSAGE = "Valid Test Result."; + + // This attribute is set by Server.java to indicate how this interceptor + // should behave. There are a predetermined set of behavior values: + // MODE_NORMAL - All interceptors exit without throwing an Exception + // MODE_RRSC_SYSTEM_EXCEPTION - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a SYSTEM_EXCEPTION from rrsc. + // MODE_RRSC_FORWARD_REQUEST - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a ForwardRequest from rrsc. + // MODE_RR_SYSTEM_EXCEPTION - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a SYSTEM_EXCEPTION from rr. + // MODE_RR_FORWARD_REQUEST - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a ForwardRequest from rr. + // MODE_SR_SYSTEM_EXCEPTION - Interceptors 1 and 3 return normally, + // while interceptor 2 throws a SYSTEM_EXCEPTION from sr. + + private static int testMode; + + public static final int MODE_NORMAL = 0; + public static final int MODE_RRSC_SYSTEM_EXCEPTION = 1; + public static final int MODE_RRSC_FORWARD_REQUEST = 2; + public static final int MODE_RR_SYSTEM_EXCEPTION = 3; + public static final int MODE_RR_FORWARD_REQUEST = 4; + public static final int MODE_SR_SYSTEM_EXCEPTION = 5; + public static final int MODE_SE_SYSTEM_EXCEPTION = 6; + public static final int MODE_SE_FORWARD_REQUEST = 7; + public static final int MODE_SO_SYSTEM_EXCEPTION = 8; + public static final int MODE_SO_FORWARD_REQUEST = 9; + + // This is necessary because we invoke ending points once before the + // actual invocation sequence we are recording (see the sequence + // diagram in ServerCommon.checkOrder) and because the mode is reset + // after the first time the mode flag becomes relevant. + private static int endpointSkip; + + private String name; + + // Counter to make sure each start is mated by an end + public static int callCounter = 0; + + // Normally, _is_a invocations are not recorded. This is because _is_a + // is invoked often by RMI lookup code. If this flag is set, + // _is_a invocations are recorded at most once. This is useful for + // when we actually want to record interception on the _is_a "special op". + static boolean dontIgnoreIsA = false; + + public static boolean printPointEntryFlag = false; + + private void printPointEntry( String message, RequestInfo ri ) + { + if (printPointEntryFlag) { + System.out.println(message + + " " + ri.request_id() + + " " + ri.operation() + + " " + callCounter); + } + } + + public SampleServerRequestInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void receive_request_service_contexts (ServerRequestInfo ri) + throws ForwardRequest + { + callCounter++; // Starting point - add + printPointEntry("receive_request_service_contexts", ri); + + // Ignore any calls to _is_a since this happens quite often for + // the RMI case and we are not interested in recording those. + if( !dontIgnoreIsA && ri.operation().equals( "_is_a" ) ) { + if( name.equals( "1" ) ) { + System.out.println( + " - Interceptor: Ignoring _is_a call..." ); + } + } + else { + // Log that we did a receive_request_service_contexts + // on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "rs" + name; + + if( name.equals( "2" ) ) { + if( testMode == MODE_RRSC_SYSTEM_EXCEPTION ) { + // Reset to original test mode: + testMode = MODE_NORMAL; + + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + + // Since this starting point is throwing an exception + // an ending point will not be called. Therefore, + // explicitly decrement the call counter. + callCounter--; + + throw new IMP_LIMIT( VALID_MESSAGE ); + } + else if( testMode == MODE_RRSC_FORWARD_REQUEST ) { + testMode = MODE_NORMAL; + + // Since this starting point is throwing an exception + // an ending point will not be called. Therefore, + // explicitly decrement the call counter. + callCounter--; + + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + } + } + } + + public void receive_request (ServerRequestInfo ri) + throws ForwardRequest + { + printPointEntry("receive_request", ri); + + // Ignore any calls to _is_a since this happens quite often for + // the RMI case and we are not interested in recording those. + if( dontIgnoreIsA || !ri.operation().equals( "_is_a" ) ) { + // Log that we did a receive_request on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "rr" + name; + + if( name.equals( "2" ) ) { + if( testMode == MODE_RR_SYSTEM_EXCEPTION ) { + // Reset to original test mode: + testMode = MODE_NORMAL; + + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + throw new IMP_LIMIT( VALID_MESSAGE ); + } + else if( testMode == MODE_RR_FORWARD_REQUEST ) { + testMode = MODE_NORMAL; + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + } + } + } + + public void send_reply (ServerRequestInfo ri) + { + printPointEntry("send_reply", ri); + callCounter--; // Ending point - subtract + + // Ignore any calls to _is_a since this happens quite often for + // the RMI case and we are not interested in recording those. + if( dontIgnoreIsA || !ri.operation().equals( "_is_a" ) ) { + // Log that we did a send_reply on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "sr" + name; + + if( name.equals( "2" ) ) { + if( endpointSkip > 0 ) { + endpointSkip--; + } + else if( testMode == MODE_SR_SYSTEM_EXCEPTION ) { + // Reset to original test mode: + testMode = MODE_NORMAL; + + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + throw new IMP_LIMIT( VALID_MESSAGE ); + } + } + } + + // Reset dontIgnoreIsA so that the most number of times _is_a is + // ever processed in a single call is once. + if( name.equals( "1" ) && ri.operation().equals( "_is_a" ) ) { + dontIgnoreIsA = false; + } + } + + public void send_exception (ServerRequestInfo ri) + throws ForwardRequest + { + printPointEntry("send_exception", ri); + callCounter--; // Ending point - subtract + + try { + System.out.println( "re: " + ri.exceptions()[0].id() ); + } + catch( Exception e ) { + } + + // Ignore any calls to _is_a since this happens quite often for + // the RMI case and we are not interested in recording those. + if( dontIgnoreIsA || !ri.operation().equals( "_is_a" ) ) { + // Log that we did a send_exception on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "se" + name; + + if( name.equals( "2" ) ) { + if( endpointSkip > 0 ) { + endpointSkip--; + } + else if( testMode == MODE_SE_SYSTEM_EXCEPTION ) { + // Reset to original test mode: + testMode = MODE_NORMAL; + + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + throw new IMP_LIMIT( VALID_MESSAGE ); + } + else if( testMode == MODE_SE_FORWARD_REQUEST ) { + testMode = MODE_NORMAL; + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + } + } + + // Reset dontIgnoreIsA so that the most number of times _is_a is + // ever processed in a single call is once. + if( name.equals( "1" ) && ri.operation().equals( "_is_a" ) ) { + dontIgnoreIsA = false; + } + } + + public void send_other (ServerRequestInfo ri) + throws ForwardRequest + { + printPointEntry("send_other", ri); + callCounter--; // Ending point - subtract + + // Ignore any calls to _is_a since this happens quite often for + // the RMI case and we are not interested in recording those. + if( dontIgnoreIsA || !ri.operation().equals( "_is_a" ) ) { + // Log that we did a send_other on this interceptor so we can + // verify invocation order was correct in test. + invocationOrder += "so" + name; + + if( name.equals( "2" ) ) { + if( endpointSkip > 0 ) { + endpointSkip--; + } + else if( testMode == MODE_SO_SYSTEM_EXCEPTION ) { + // Reset to original test mode: + testMode = MODE_NORMAL; + + // If we are the second interceptor, it is our turn to + // throw a SystemException here. + throw new IMP_LIMIT( VALID_MESSAGE ); + } + else if( testMode == MODE_SO_FORWARD_REQUEST ) { + testMode = MODE_NORMAL; + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + } + } + + // Reset dontIgnoreIsA so that the most number of times _is_a is + // ever processed in a single call is once. + if( name.equals( "1" ) && ri.operation().equals( "_is_a" ) ) { + dontIgnoreIsA = false; + } + } + + public static void setTestMode( int testMode ) { + SampleServerRequestInterceptor.testMode = testMode; + SampleServerRequestInterceptor.endpointSkip = 1; + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/ServerCommon.java b/functional-tests/src/test/java/pi/serverinterceptor/ServerCommon.java new file mode 100644 index 000000000..7a58f06bd --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/ServerCommon.java @@ -0,0 +1,444 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.framework.InternalProcess; +import java.io.PrintStream; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; + +/** + * Common methods for Server implementations in this test to use + */ +public abstract class ServerCommon + implements InternalProcess +{ + // Set from run() + com.sun.corba.ee.spi.orb.ORB orb; + + // Set from run() + PrintStream out; + + // Set from run() + PrintStream err; + + // True if one of the methods on the Servant was invoked, false if not. + // This is reset and set, and tested for each invocation tested. + static boolean servantInvoked = false; + + // True if the client is currently waiting for syncWithServer to return + // or false otherwise. + static boolean syncing = false; + + // The name of the next method to invoke: + static String nextMethodToInvoke; + + // An object for syncWithServer to wait on before returning to the client. + static final Integer syncObject = new Integer( 0 ); + + // Constant string to indicate to the client that we are done. + static final String EXIT_METHOD = "exit"; + + // Set to true by syncWithServer if the last invocation resulted in + // an exception on the client side. + static boolean exceptionRaised; + + JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + + protected void finish() { + helper.done() ; + } + + /** + * Creates a com.sun.corba.ee.spi.orb.ORB and notifies the TestInitializer of its presence + */ + void createORB( String[] args, Properties props ) { + // create and initialize the ORB with initializer + String testInitializer = "pi.serverinterceptor.TestInitializer"; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + // props.put( ORBConstants.DEBUG_PROPERTY, "subcontract" ) ; + this.orb = (com.sun.corba.ee.spi.orb.ORB)ORB.init(args, props); + TestInitializer.orb = this.orb; + } + + /** + * Perform ServerRequestInterceptor tests for server side + */ + void testServerInterceptor() throws Exception { + out.println(); + out.println( "Running common ServerRequestInterceptor tests" ); + out.println( "=============================================" ); + + // Wait for client to synchronize with server for the first time. + // We do this because we want testInvocation to wait for the client + // at the end of an invocation so we know the method finished + // executing. However, we do not want to incur the 0.5 second + // overhead of waiting for the client both at the begininng and the + // end of the testInvocation method. + waitForClient(); + + // No exceptions thrown. Should call receive_request_service_contexts, + // receive_request, process sayHello, and then send_reply on all + // 3 interceptors in the correct order + out.println( "+ Testing standard invocation..." ); + testInvocation( "testStandardInvocation", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3sr3sr2sr1", "sayHello", "[Hello1]", false ); + + // No exceptions thrown. Should call receive_request_service_contexts, + // receive_request, process sayOneWay, and then send_reply on all + // 3 interceptors in the correct order + out.println( "+ Testing oneway invocation..." ); + testInvocation( "testOnewayInvocation", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3sr3sr2sr1", "sayOneway", "[Hello1]", false ); + + // SYSTEM_EXCEPTION thrown by method. Should call + // receive_request_service_contexts, receive_request, + // process saySystemException, and then send_exception on all 3 + // interceptors in the correct order. + out.println( "+ Testing invocation resulting in SYSTEM_EXCEPTION..." ); + testInvocation( "testInvocationResultSystemException", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3se3se2se1", "saySystemException", + "[Hello1]", true ); + + // USER_EXCEPTION thrown by method. Should call + // receive_request_service_contexts, receive_request, + // process sayUserException, and then send_exception on all 3 + // interceptors in the correct order. + // We pass in false for exception expected because it is not + // the exception we are checking for (which is a SystemException). + // The check is instead done in the client code during invocation. + out.println( "+ Testing invocation resulting in USER_EXCEPTION..." ); + testInvocation( "testInvocationResultUserException", + SampleServerRequestInterceptor.MODE_NORMAL, + "rs1rs2rs3rr1rr2rr3se3se2se1", "sayUserException", + "[Hello1]", false ); + + // SYSTEM_EXCEPTION thrown in rrsc for second interceptor. + // Should result in rrsc being called for 1 and 2, but not + // 3, no intermediate points invoked, and send_exception + // called for 1 only. The method sayHello should never be + // invoked. + out.println( "+ Testing invocation where interceptor #2 " + + "throws exception in rrsc." ); + testInvocation( "testInvocationInterceptorExceptionRRSC", + SampleServerRequestInterceptor.MODE_RRSC_SYSTEM_EXCEPTION, + "rs1rs2se1", "sayHello", "", true ); + + // ForwardRequest raised in rrsc for second interceptor. + // Should result in rrsc being called for 1 and 2, but not + // 3, no intermediate points invoked, and send_exception + // called for 1 only. The method sayHello should be called + // on the second object. + out.println( "+ Testing invocation where interceptor #2 " + + "raises ForwardRequest in rrsc." ); + testInvocation( "testInvocationInterceptorForwardRequestRRSC", + SampleServerRequestInterceptor.MODE_RRSC_FORWARD_REQUEST, + "rs1rs2so1rs1rs2rs3rr1rr2rr3sr3sr2sr1", "sayHello", + "[Hello1Forward]", false ); + + // SYSTEM_EXCEPTION thrown in rr for second interceptor. + // Should result in rrsc being called for all interceptors, + // intermediate points rr1 and rr2 but not rr3, and send_exception + // called for all points. The method sayHello should never be + // invoked. + out.println( "+ Testing invocation where interceptor #2 " + + "throws exception in rr." ); + testInvocation( "testInvocationInteceptorExceptionRR", + SampleServerRequestInterceptor.MODE_RR_SYSTEM_EXCEPTION, + "rs1rs2rs3rr1rr2se3se2se1", "sayHello", "", true ); + + // ForwardRequest raised in rr for second interceptor. + // Should result in rrsc being called for all interceptors, + // intermediate points rr1 and rr2 but not rr3, and + // send_other for all interceptors. The method sayHello should + // be called on the second object. + out.println( "+ Testing invocation where interceptor #2 " + + "raises ForwardRequest in rr." ); + testInvocation( "testInvocationInterceptorForwardRequestRR", + SampleServerRequestInterceptor.MODE_RR_FORWARD_REQUEST, + "rs1rs2rs3rr1rr2so3so2so1rs1rs2rs3rr1rr2rr3sr3sr2sr1", + "sayHello", "[Hello1Forward]", false ); + + // SYSTEM_EXCEPTION thrown in sr for second interceptor. + // Should result in rrsc being called for all interceptors, + // intermediate points for all, and send_reply for 1 and 2, + // then send_exception for 3. The method sayHello should have been + // invoked. + out.println( "+ Testing invocation where interceptor #2 " + + "throws exception in sr." ); + testInvocation( "testInvocationInterceptorExceptionSR", + SampleServerRequestInterceptor.MODE_SR_SYSTEM_EXCEPTION, + "rs1rs2rs3rr1rr2rr3sr3sr2se1", "sayHello", "[Hello1]", true ); + + // SYSTEM_EXCEPTION thrown in se for second interceptor. + // Should result in rrsc being called for all interceptors, + // intermediate points for all, and send_exception for 1 and 2, + // then send_exception for 3. The method sayException should have been + // invoked. + out.println( "+ Testing invocation where interceptor #2 " + + "throws exception in se." ); + testInvocation( "testInvocationInterceptorExceptionSE", + SampleServerRequestInterceptor.MODE_SE_SYSTEM_EXCEPTION, + "rs1rs2rs3rr1rr2rr3se3se2se1", "saySystemException", + "[Hello1]", true ); + + // ForwardRequest thrown in se for second interceptor. + // Should result in rrsc being called for all interceptors, + // intermediate points for all, and send_reply for 1 and 2, + // then send_other for 3. The method sayException should have been + // invoked. Then, sayHello is invoked again, on the forwarded + // object. + out.println( "+ Testing invocation where interceptor #2 " + + "throws forward request in se." ); + testInvocation( "testInvocationInterceptorForwardRequestSE", + SampleServerRequestInterceptor.MODE_SE_FORWARD_REQUEST, + "rs1rs2rs3rr1rr2rr3se3se2so1rs1rs2rs3rr1rr2rr3se3se2se1", + "saySystemException", "[Hello1][Hello1Forward]", true ); + + // _REVISIT_ The callCounter should be zero here. However, + // when we check the count we have not executed the + // server interceptor reply points for the final message yet. + // Since there are 3 interceptors registered the call count + // is 3. Any number other than three indicates an unbalanced + // PICurrent stack. + + // Test call counter (all starting points should be matched by an + // ending point): + out.print( + "- Checking call counter: " + + SampleServerRequestInterceptor.callCounter + " " ); + if( SampleServerRequestInterceptor.callCounter == 3 ) { + out.println( "(ok)" ); + } + else { + out.println( "(error - should be 3)" ); + throw new RuntimeException( "Call counter was not 3" ); + } + } + + /** + * Tests a standard invocation by instructing the client to + * resolve a reference to helloServer and make an invocation, + * recording the interceptor invocation ordering. Assumes we are + * already synchronized with the client. + * + * @param mode - See SampleServerRequestIntreceptor.testMode for more + * details of mode parameter. + * @param correctOrder - See SampleServerRequestInterceptor. + * invocationOrder for more details on correctOrder. + * @param methodName is either "sayHello" or "sayException" + * @param correctMethodOrder - See SampleServerRequestInterceptor. + * methodOrder for more details on correctMethodOrder. + * @param exceptionExpected - True if an exception should make its way + * to the client or false if not. + */ + void testInvocation( String name, + int mode, + String correctOrder, + String methodName, + String correctMethodOrder, + boolean exceptionExpected ) + throws Exception + { + helper.start( name ) ; + + try { + // We are already synchronized with the client. + + // Prepare for the call: + nextMethodToInvoke = methodName; + servantInvoked = false; + SampleServerRequestInterceptor.invocationOrder = ""; + SampleServerRequestInterceptor.methodOrder = ""; + SampleServerRequestInterceptor.setTestMode( mode ); + + // Return from syncWithServer() and let the client make the call: + synchronized( syncObject ) { + syncObject.notify(); + } + + // If this is a oneway call, wait an extra second to make sure + // everything went through okay. + if( methodName.equals( "sayOneway" ) ) { + out.println( " - Delaying for oneway..." ); + try { + Thread.sleep( 1000 ); + } + catch( InterruptedException e ) { + } + out.println( " - This should be long enough." ); + } + + // Wait for client to synchronize with server again. Now we know + // for sure that the method invocation is complete. Even if the + // call was a oneway, we can be fairly certain the call has completed + // since we delay for 0.5 seconds before exiting waitForClient() + // which should be enough time in most cases. + waitForClient(); + + // Examine invocation order to ensure everything was called in the + // right order. + // + // NOTE: This is merely a convenient way to check ordering. + // Since the specification does not require that the order in which + // interceptors are registered match the order in which they are + // invoked, the actual invocationOrder may be different but still + // valid. This test may need modification if we change the way + // we determine the initial invocation order of interceptors. + String order = SampleServerRequestInterceptor.invocationOrder; + checkOrder( correctOrder, order ); + + // Examine method invocation order to ensure all appropriate methods + // were called, and in the right order. + String methodOrder = SampleServerRequestInterceptor.methodOrder; + checkMethodOrder( correctMethodOrder, methodOrder ); + + // Determine if an exception was raised: + out.println( " - Client-side exception expected: " + + exceptionExpected ); + out.println( " - Client-side exception raised: " + + exceptionRaised ); + if( exceptionExpected != exceptionRaised ) { + throw new RuntimeException( "Method should " + + (!exceptionExpected ? "not" : "") + + " have raised an exception!" ); + } + + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + } + } + + /** + * Waits for the client to sync with the server + */ + private void waitForClient() { + out.println( " - Waiting for client..." ); + while( !syncing ) { + try { + Thread.sleep( 100 ); + } + catch( InterruptedException e ) { + } + } + + // Leave enough time for the method and interceptors to finish + // invoking so we can clear the invocation history: + try { + Thread.sleep( 500 ); + } + catch( InterruptedException e ) { + } + out.println( " - Synchronized with client." ); + } + + /** + * Notifies the client it is time to exit + */ + void exitClient() { + out.println( "+ Notifying client it's time to exit..." ); + nextMethodToInvoke = EXIT_METHOD; + synchronized( syncObject ) { + syncObject.notify(); + } + } + + /** + * Checks the invocation order against the correct invocation order, + * displays some debug output and throws an Exception if they do not + * match. + */ + private void checkOrder( String correctOrder, String order ) + throws Exception + { + // Because we synchronize with the client before we check the + // invocation order, all invocations for syncWithServer are + // present at the end of the actual invocation order. Additionally, + // the end of the previous syncWithServer should appear. We will + // check for the presence of these as well. + // + // Client Server + // | | + // [ ] syncWithServer() | + // [ ]------------------------>[ ] rs1 rs2 rs3 rr1 rr2 rr3 + // [ ] [ ] + // [ ] "sayHello" [ ] // order cleared here + // [ ]<------------------------[ ] sr3 sr2 sr1 + // [ ] | + // [ ] sayHello() | // + // [ ]------------------------>[ ] rs1 rs2 rs3 rr1 rr2 rr3 + // [ ] [ ] + // [ ] "hello there" [ ] + // [ ]<------------------------[ ] sr3 sr2 sr1 + // [ ] | // + // [ ] syncWithServer() | + // [ ]------------------------>[ ] rs1 rs2 rs3 rr1 rr2 rr3 + // [ ] [ ] + // [ ] [ ] // check order here + // [ ] [ ] // next test begins soon after. + // ... ... + // + // Notice that at "check order here" our string is as follows: + // sr3sr2sr1rs1rs2rs3rr1rr2rr3sr3sr2sr1rs1rs2rs3rr1rr2rr3 + // ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^~~~~~~~~~~~~~~~~~~ + // [ junk ][ important info ][ junk ] + + String prependOrder = "sr3sr2sr1"; + String appendedOrder = "rs1rs2rs3rr1rr2rr3"; + correctOrder = prependOrder + correctOrder + appendedOrder; + + out.println( " - Expected invocation order: " + + correctOrder.substring( prependOrder.length(), + correctOrder.length() - + appendedOrder.length() ) ); + + out.println( " - Actual invocation order: " + + order.substring( prependOrder.length(), + order.length() - + appendedOrder.length() ) ); + + if( !order.equals( correctOrder ) ) { + out.println( " - MISMATCH. Exiting." ); + throw new Exception( "Invocation order mismatch." ); + } + } + + /** + * Checks the method invocation order against the correct method + * invocation order, displays some debug output and throws an Exception + * if they do not match. + */ + private void checkMethodOrder( String correctMethodOrder, + String methodOrder ) + throws Exception + { + out.println( " - Expected method invocation order: " + + correctMethodOrder ); + + out.println( " - Actual method invocation order: " + + methodOrder ); + + if( !methodOrder.equals( correctMethodOrder ) ) { + out.println( " - MISMATCH. Exiting." ); + throw new Exception( "Method Invocation order mismatch." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/ServerInterceptorTest.java b/functional-tests/src/test/java/pi/serverinterceptor/ServerInterceptorTest.java new file mode 100644 index 000000000..dfae72e3e --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/ServerInterceptorTest.java @@ -0,0 +1,313 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.framework.*; +import java.util.*; + +/** + * Tests ServerInterceptor as per Portable Interceptors spec + * orbos/99-12-02, section 5.3. See pi/assertions.html for Assertions + * covered in this test. + *

+ * This test essentially is designed to determine which interception points + * are invoked on various types of method invocations and varying interceptor + * behaviors, and in what order those interception points are invoked. + */ +public class ServerInterceptorTest + extends CORBATest +{ + // Set to true if at least one test failes + private boolean failed = false; + + Controller orbd; + + protected void doTest() + throws Throwable + { + startORBD(); + System.out.println(); + System.out.println( " \t\t\t\tLocal\t\tRemote" ); + + beginTest( "[POA]\t\t\t" ); + testPOALocal(); + endTest( "\t\t" ); + testPOARemote(); + endTest( "\n" ); + + beginTest( "[POA DSI]\t\t\t" ); + testPOADSILocal(); + endTest( "\t\t" ); + testPOADSIRemote(); + endTest( "\n" ); + + beginTest( "[RMI]\t\t\t" ); + testRMILocal(); + endTest( "\t\t" ); + testRMIRemote(); + endTest( "\n" ); + + beginTest( "[ServerRequestDispatcher DSI]\t" ); + testServerRequestDispatcherDSILocal(); + endTest( "\t\t" ); + testServerRequestDispatcherDSIRemote(); + endTest( "\n" ); + stopORBD(); + + System.out.println(); + System.out.print( " Final Result: " ); + if( failed ) { + throw new RuntimeException( "Errors detected" ); + } + } + + private void testPOALocal() + throws Throwable + { + Controller server; + + try { + + Properties clientProps = Options.getClientProperties(); + + clientProps.setProperty(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + Options.getUnusedPort().toString()); + + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverinterceptor.POALocalServer", + "poalocal" ); + + server.start(); + + clientProps.remove(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY); + + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testPOARemote() + throws Throwable + { + Controller client, server; + + try { + + Properties serverProps = Options.getServerProperties(); + + serverProps.setProperty(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + Options.getUnusedPort().toString()); + + server = createServer( "pi.serverinterceptor.POARemoteServer", + "poa-server" ); + server.start(); + + serverProps.remove(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY); + + client = createClient( "pi.serverinterceptor.POARemoteClient", + "poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testPOADSILocal() + throws Throwable + { + Controller server; + + try { + + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverinterceptor.DSIPOALocalServer", + "dsipoalocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testPOADSIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.serverinterceptor.DSIPOARemoteServer", + "dsi-poa-server" ); + server.start(); + client = createClient( "pi.serverinterceptor.POARemoteClient", + "dsi-poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testRMILocal() + throws Throwable + { + Controller server; + + try { + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverinterceptor.RMILocalServer", + "rmilocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testRMIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.serverinterceptor.RMIRemoteServer", + "rmi-server" ); + server.start(); + client = createClient( "pi.serverinterceptor.RMIRemoteClient", + "rmi-client" ); + + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testServerRequestDispatcherDSILocal() + throws Throwable + { + Controller server; + + try { + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverinterceptor.DSIRMILocalServer", + "dsirmilocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testServerRequestDispatcherDSIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.serverinterceptor.DSIRMIRemoteServer", + "dsi-rmi-server" ); + server.start(); + client = createClient( "pi.serverinterceptor.DSIRMIRemoteClient", + "dsi-rmi-client" ); + + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void beginTest( String name ) + throws Exception + { + System.out.print( " " + name ); + } + + private void endTest( String terminator ) + throws Exception + { + System.out.print( terminator ); + } + + private void printBeginTest( String name ) { + System.out.print( " " + name ); + } + + private void printEndTest( Controller client, Controller server ) { + if( (server != null) && server.finished() ) { + System.out.print( "FAILED, Server crashed" ); + failed = true; + } + else if( (client != null) && + (client.exitValue() != Controller.SUCCESS) ) + { + System.out.print( "FAILED, Client exit value = " + + client.exitValue() ); + failed = true; + } + else { + System.out.print( "PASSED" ); + } + } + + private void startORBD() + throws Exception + { + orbd = createORBD(); + orbd.start(); + } + + private void stopORBD() + throws Exception + { + orbd.stop(); + pause(); + } + + // Pause a little to allow all processes to fully terminate. + private void pause() { + try { + Thread.sleep( 2000 ); + } + catch( InterruptedException e ) { + // ignore. + } + } + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/TestInitializer.java b/functional-tests/src/test/java/pi/serverinterceptor/TestInitializer.java new file mode 100644 index 000000000..e6fd3dabc --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/TestInitializer.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * Registers the necessary Server Interceptors to test + * ServerRequestInterceptor. + */ +public class TestInitializer + extends org.omg.CORBA.LocalObject + implements ORBInitializer +{ + + // The PrintStream to pass to the ServerRequestInterceptor for output + // This is set from Server.java, statically. + static PrintStream out; + + /** The ORB to pass to the ServerRequestInterceptor */ + static ORB orb; + + // The location of the original hello object. + static org.omg.CORBA.Object helloRef; + + // Where to forward the caller on a ForwardRequest + static org.omg.CORBA.Object helloRefForward; + + /** + * Creates a TestInitializer + */ + public TestInitializer() { + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + ServerRequestInterceptor interceptor1; + ServerRequestInterceptor interceptor2; + ServerRequestInterceptor interceptor3; + + interceptor1 = new SampleServerRequestInterceptor( "1" ); + interceptor2 = new SampleServerRequestInterceptor( "2" ); + interceptor3 = new SampleServerRequestInterceptor( "3" ); + + try { + out.println( " - post_init: adding 3 server interceptors..." ); + info.add_server_request_interceptor( interceptor1 ); + info.add_server_request_interceptor( interceptor2 ); + info.add_server_request_interceptor( interceptor3 ); + } + catch( DuplicateName e ) { + out.println( " - post_init: received DuplicateName!" ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/TestServantLocator.java b/functional-tests/src/test/java/pi/serverinterceptor/TestServantLocator.java new file mode 100644 index 000000000..53bbe0f30 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/TestServantLocator.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import java.io.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.CORBA.*; + +/** + * Test Servant locator that throws a ForwardRequest. + */ +public class TestServantLocator + extends org.omg.CORBA.LocalObject + implements ServantLocator +{ + // The PrintStream to pass to the ServerRequestInterceptor for output + // This is set from Server.java, statically. + PrintStream out; + + /** The ORB to pass to the ServerRequestInterceptor */ + ORB orb; + + // Where to forward the caller on a ForwardRequest + org.omg.CORBA.Object helloRefForward; + + // We will only throw a ForwardRequest the first time. + boolean firstTime = true; + + /** + * Creates the servant locator. + */ + public TestServantLocator( PrintStream out, ORB orb, + org.omg.CORBA.Object helloRefForward ) + { + this.out = out; + this.orb = orb; + this.helloRefForward = helloRefForward; + this.firstTime = true; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + out.println( " - TestServantLocator.preinvoke called." ); + if( firstTime ) { + firstTime = false; + out.println( " - First time - raising ForwardRequest." ); + throw new org.omg.PortableServer.ForwardRequest( helloRefForward ); + } + + return new helloServant( out, "[Hello2]" ); + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + out.println( " - TestServantLocator.postinvoke called." ); + } + + void resetFirstTime() { + this.firstTime = true; + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/helloDSIDeprecatedServant.java b/functional-tests/src/test/java/pi/serverinterceptor/helloDSIDeprecatedServant.java new file mode 100644 index 000000000..4fd8a742d --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/helloDSIDeprecatedServant.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.PortableInterceptor.*; +import org.omg.PortableServer.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Servant implementation. + */ +class helloDSIDeprecatedServant + extends org.omg.CORBA.DynamicImplementation +{ + // The object to delegate to + DSIImpl impl; + + public static String[] __ids = { "IDL:ServerRequestInterceptor/hello:1.0" }; + + public String[] _ids() { + return __ids; + } + + public helloDSIDeprecatedServant( + ORB orb, PrintStream out, String symbol ) + { + impl = new DSIImpl( orb, out, symbol ); + } + + public void invoke( ServerRequest r ) { + impl.invoke( r ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/helloDSIServant.java b/functional-tests/src/test/java/pi/serverinterceptor/helloDSIServant.java new file mode 100644 index 000000000..dd91a842d --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/helloDSIServant.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; +import org.omg.PortableInterceptor.*; +import org.omg.PortableServer.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInterceptor.*; + +/** + * Servant implementation. + */ +class helloDSIServant extends org.omg.PortableServer.DynamicImplementation { + // The object to delegate to + DSIImpl impl; + + public static String[] __ids = { "IDL:ServerRequestInterceptor/hello:1.0" }; + + public String[] _all_interfaces( POA poa, byte[] oid ) { + return __ids; + } + + public helloDSIServant( ORB orb, PrintStream out, String symbol ) { + impl = new DSIImpl( orb, out, symbol ); + } + + public void invoke( ServerRequest r ) { + impl.invoke( r ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/helloDelegate.java b/functional-tests/src/test/java/pi/serverinterceptor/helloDelegate.java new file mode 100644 index 000000000..bbf84c625 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/helloDelegate.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; + +import java.util.*; +import java.io.*; +import org.omg.PortableInterceptor.*; + +import ServerRequestInterceptor.*; + +/** + * Servant implementation. + */ +class helloDelegate implements helloIF { + private PrintStream out = null; + + // The symbol to append to SampleServerRequestInterceptor.methodOrder + // every time a relevant method is called on this object. + String symbol; + + public helloDelegate( PrintStream out, String symbol ) { + super(); + this.out = out; + this.symbol = symbol; + } + + public String sayHello() { + ServerCommon.servantInvoked = true; + out.println( " - helloDelegate: sayHello() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + return "Hello, world!"; + } + + public void sayOneway() { + ServerCommon.servantInvoked = true; + out.println( " - helloDelegate: sayOneway() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + } + + public void saySystemException() { + ServerCommon.servantInvoked = true; + out.println( " - helloDelegate: saySystemException() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + throw new IMP_LIMIT( SampleServerRequestInterceptor.VALID_MESSAGE ); + } + + public void sayUserException() + throws ForwardRequest + { + ServerCommon.servantInvoked = true; + out.println( " - helloDelegate: sayUserException() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + throw new ForwardRequest( TestInitializer.helloRef ); + } + + // Client code calls this to synchronize with server. This call + // blocks until the server is ready for the next invocation. + // It then returns a String containing the name of the method to + // invoke on (either "sayHello" or "saySystemException"). + // If the string "exit" is returned, the Client's + // work is done and it may exit. + // + // @param exceptionRaised true if the last invocation resulted in + // an exception on the client side. + public String syncWithServer( boolean exceptionRaised ) { + out.println( " - helloDelegate: syncWithServer() invoked" ); + // Notify the test case that the client is waiting for + // syncWithServer to return: + ServerCommon.syncing = true; + ServerCommon.exceptionRaised = exceptionRaised; + + // Wait for the next test case to start: + synchronized( ServerCommon.syncObject ) { + try { + ServerCommon.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore, assume we are good to go. + } + } + + ServerCommon.syncing = false; + + return ServerCommon.nextMethodToInvoke; + } + +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/helloIF.java b/functional-tests/src/test/java/pi/serverinterceptor/helloIF.java new file mode 100644 index 000000000..e12c3f82a --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/helloIF.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import org.omg.PortableInterceptor.*; +import ServerRequestInterceptor.*; + +/** + * Hello interface for RMI-IIOP version of test + */ +public interface helloIF + extends Remote +{ + String sayHello () throws RemoteException; + void sayOneway () throws RemoteException; + void saySystemException () throws RemoteException; + void sayUserException () throws ForwardRequest, RemoteException; + String syncWithServer ( boolean exceptionRaised ) throws RemoteException; +} + diff --git a/functional-tests/src/test/java/pi/serverinterceptor/helloRMIIIOP.java b/functional-tests/src/test/java/pi/serverinterceptor/helloRMIIIOP.java new file mode 100644 index 000000000..4bbeb73de --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/helloRMIIIOP.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; + +import java.io.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; +import org.omg.PortableInterceptor.*; + +import ServerRequestInterceptor.*; // hello interface + +/** + * RMI/IIOP implementation. + */ +public class helloRMIIIOP + extends PortableRemoteObject + implements helloIF +{ + // Contains the actual implementation of the hello interface. + private helloDelegate delegate = null; + + public helloRMIIIOP( PrintStream out, String symbol ) + throws RemoteException + { + super(); + this.delegate = new helloDelegate( out, symbol ); + } + + public String sayHello() { + return delegate.sayHello(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void saySystemException() { + delegate.saySystemException(); + } + + public void sayUserException() + throws ForwardRequest + { + delegate.sayUserException(); + } + + public String syncWithServer( boolean exceptionRaised ) { + return delegate.syncWithServer( exceptionRaised ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverinterceptor/helloServant.java b/functional-tests/src/test/java/pi/serverinterceptor/helloServant.java new file mode 100644 index 000000000..d29f1fb22 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverinterceptor/helloServant.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverinterceptor; + +import org.omg.CORBA.*; + +import java.util.*; +import java.io.*; +import org.omg.PortableInterceptor.*; + +import ServerRequestInterceptor.*; + +/** + * Servant implementation. + */ +class helloServant extends helloPOA { + // The object to delegate all calls to: + helloDelegate delegate; + + public helloServant( PrintStream out, String symbol ) { + super(); + this.delegate = new helloDelegate( out, symbol ); + } + + public String sayHello() { + return delegate.sayHello(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void saySystemException() { + delegate.saySystemException(); + } + + public void sayUserException() + throws ForwardRequest + { + delegate.sayUserException(); + } + + public String syncWithServer( boolean exceptionRaised ) { + return delegate.syncWithServer( exceptionRaised ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/AdapterIdStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/AdapterIdStrategy.java new file mode 100644 index 000000000..89c007b04 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/AdapterIdStrategy.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.Messaging.*; +import com.sun.corba.ee.impl.misc.HexOutputStream; + +import java.util.*; +import java.io.*; + +/** + * Strategy to further test adapter_id() (only executed for POA) + */ +public class AdapterIdStrategy + extends InterceptorStrategy +{ + + // The request count. We should be calling: + // 0 - sayHello + // 1 - saySystemException + // 2 - saySystemException. + private int count = 0; + + // Set from POAServer. This is the adapter ID to test against. + private byte[] expectedAdapterId; + + public AdapterIdStrategy( byte[] expectedAdapterId ) { + this.expectedAdapterId = expectedAdapterId; + } + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + // We already checked that adapter_id is invalid in rrsc. + try { + super.receive_request_service_contexts( interceptor, ri ); + count++; + } + catch( Exception ex ) { + failException( "rrsc", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.receive_request( interceptor, ri ); + checkAdapterId( "receive_request", ri.adapter_id() ); + } + catch( Exception ex ) { + failException( "receive_request", ex ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.send_reply( interceptor, ri ); + checkAdapterId( "send_reply", ri.adapter_id() ); + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.send_exception( interceptor, ri ); + checkAdapterId( "send_exception", ri.adapter_id() ); + } + catch( Exception ex ) { + failException( "send_exception", ex ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.send_other( interceptor, ri ); + checkAdapterId( "send_other", ri.adapter_id() ); + } + catch( Exception ex ) { + failException( "send_other", ex ); + } + } + + private void checkAdapterId( String method, byte[] adapterId ) { + log( method + "(): Actual adapter id = " + dumpHex( adapterId ) ); + if( Arrays.equals( adapterId, expectedAdapterId ) ) { + log( method + "(): Adapter id compares." ); + } + else { + fail( method + "(): Adapter id does not compare. " + + "(expected id: " + dumpHex( expectedAdapterId ) + ")" ); + } + } + + private String dumpHex( byte[] bytes ) { + StringWriter sw = new StringWriter(); + HexOutputStream out = new HexOutputStream( sw ); + try { + out.write( bytes ); + } + catch( IOException e ) {} + return sw.toString(); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/AttributesValidStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/AttributesValidStrategy.java new file mode 100644 index 000000000..b02c0bad1 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/AttributesValidStrategy.java @@ -0,0 +1,377 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.Messaging.*; + +import java.util.*; + +/** + * Strategy to test operations() + */ +public class AttributesValidStrategy + extends InterceptorStrategy +{ + + // The request count. We should be calling: + // 0 - sayHello + // 1 - saySystemException + // 2 - saySystemException. + private int count = 0; + + // The most recent operation name received. + private String operationName; + + // The most receive object id received + private byte[] objectId; + + // The most receive adapter id received + private byte[] adapterId; + + // The Hello interface repository id to check against. + private String validRepId; + + // Fake Hello interface repository id to check against. + private String invalidRepId; + + public AttributesValidStrategy( String validRepId, String invalidRepId ) { + this.validRepId = validRepId; + this.invalidRepId = invalidRepId; + } + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.receive_request_service_contexts( interceptor, ri ); + + String validName = (count == 0) ? + "sayHello" : "saySystemException"; + this.operationName = ri.operation(); + log( "rrsc(): Expected operation name = " + validName ); + log( "rrsc(): Actual operation name = " + + this.operationName ); + + if( !this.operationName.equals( validName ) ) { + fail( "Operation name not equal to expected name." ); + } + + checkSyncScope( "rrsc", ri ); + + // Check that within rrsc, reply_status + // throws BAD_INV_ORDER: + try { + short replyStatus = ri.reply_status(); + fail( "rrsc(): Should not be able to execute " + + "reply_status() here" ); + } + catch( BAD_INV_ORDER e ) { + log( "rrsc(): Tried reply_status() and received " + + "BAD_INV_ORDER (ok)" ); + } + + // Check than within rrsc, object_id throws BAD_INV_ORDER: + try { + byte[] objectId = ri.object_id(); + fail( "rrsc(): Should not be able to execute " + + "object_id() here" ); + } + catch( BAD_INV_ORDER e ) { + log( "rrsc(): Tried object_id() and received " + + "BAD_INV_ORDER (ok)" ); + } + + // Check than within rrsc, adapter_id throws BAD_INV_ORDER: + try { + byte[] adapterId = ri.adapter_id(); + fail( "rrsc(): Should not be able to execute " + + "adapter_id() here" ); + } + catch( BAD_INV_ORDER e ) { + log( "rrsc(): Tried adapter_id() and received " + + "BAD_INV_ORDER (ok)" ); + } + + checkTMDI( "rrsc", ri ); + checkTargetIsA( "rrsc", ri ); + + count++; + } + catch( Exception ex ) { + failException( "rrsc", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.receive_request( interceptor, ri ); + checkOperation( "receive_request", ri.operation() ); + checkSyncScope( "receive_request", ri ); + + // Check that within receive_request, reply_status + // throws BAD_INV_ORDER: + try { + short replyStatus = ri.reply_status(); + fail( "rr(): Should not be able to execute " + + "reply_status() here" ); + } + catch( BAD_INV_ORDER e ) { + log( "receive_request(): Tried reply_status() and received " + + "BAD_INV_ORDER (ok)" ); + } + + // Check that, object_id is valid in receive_request: + this.objectId = ri.object_id(); + if( this.objectId == null ) { + fail( "receive_request(): Object id is null" ); + } + else if( Arrays.equals( this.objectId, "".getBytes() ) ) { + fail( "receive_request(): Object id is empty string" ); + } + else { + log( "receive_request(): Object id is " + this.objectId ); + } + + // Check that, adapter_id is valid in receive_request: + this.adapterId = ri.adapter_id(); + if( this.adapterId == null ) { + fail( "receive_request(): Adapter id is null" ); + } + else if( Arrays.equals( this.adapterId, "".getBytes() ) ) { + fail( "receive_request(): Adapter id is empty string" ); + } + else { + log( "receive_request(): Adapter id is " + this.adapterId ); + } + + checkTMDI( "receive_request", ri ); + checkTargetIsA( "receive_request", ri ); + } + catch( Exception ex ) { + failException( "receive_request", ex ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.send_reply( interceptor, ri ); + checkOperation( "send_reply", ri.operation() ); + checkSyncScope( "send_reply", ri ); + + // Check that within send_reply, reply_status is SUCCESSFUL. + boolean[] validValues = { true, false, false, false, false }; + checkReplyStatus( "send_reply", ri, validValues ); + + checkObjectId( "send_reply", ri ); + checkAdapterId( "send_reply", ri ); + checkTMDI( "send_reply", ri ); + checkTargetIsA( "send_reply", ri ); + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.send_exception( interceptor, ri ); + checkOperation( "send_exception", ri.operation() ); + checkSyncScope( "send_exception", ri ); + + // Check that within send_exception, reply_status is + // SYSTEM_EXCEPTION or USER_EXCEPTION: + boolean[] validValues = { false, true, true, false, false }; + checkReplyStatus( "send_exception", ri, validValues ); + + checkObjectId( "send_exception", ri ); + checkAdapterId( "send_exception", ri ); + checkTMDI( "send_exception", ri ); + checkTargetIsA( "send_exception", ri ); + } + catch( Exception ex ) { + failException( "send_exception", ex ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.send_other( interceptor, ri ); + checkOperation( "send_other", ri.operation() ); + checkSyncScope( "send_other", ri ); + + // Check that within send_other, reply_status is + // SUCCESSFUL, LOCATION_FORWARD, or TRANSPORT_RETRY. + boolean[] validValues = { true, false, false, true, true }; + checkReplyStatus( "send_other", ri, validValues ); + + checkObjectId( "send_other", ri ); + checkAdapterId( "send_other", ri ); + checkTMDI( "send_other", ri ); + checkTargetIsA( "send_other", ri ); + } + catch( Exception ex ) { + failException( "send_other", ex ); + } + } + + private void checkOperation( String method, String opName ) { + log( method + "(): Actual operation name = " + opName ); + if( !opName.equals( this.operationName ) ) { + fail( "Operation name in " + method + " not equal to " + + "operation name in send_request()" ); + } + } + + private void checkSyncScope( String method, ServerRequestInfo ri ) { + short syncScope = ri.sync_scope(); + log( method + "(): sync_scope() returns " + syncScope ); + if( syncScope != SYNC_WITH_TRANSPORT.value ) { + fail( "sync_scope() is not SYNC_WITH_TRANSPORT" ); + } + } + + private void checkReplyStatus( String method, ServerRequestInfo ri, + boolean[] validValues ) + { + int i; + + // Describe to user which values are valid: + String validDesc = "{ "; + for( i = 0; i < validValues.length; i++ ) { + validDesc += "" + validValues[i] + " "; + } + validDesc += "}"; + log( method + "(): Valid values: " + validDesc ); + + short replyStatus = ri.reply_status(); + log( method + "(): Actual value: " + replyStatus ); + + if( !validValues[replyStatus] ) { + fail( method + "(): Not a valid reply status." ); + } + } + + private void checkObjectId( String method, ServerRequestInfo ri ) { + // Check that object_id is valid + byte[] objectId = ri.object_id(); + if( Arrays.equals( this.objectId, objectId ) ) { + log( method + "(): Object id is valid" ); + } + else { + fail( method + "(): Object id is invalid (" + + objectId + ")" ); + } + } + + private void checkAdapterId( String method, ServerRequestInfo ri ) { + // Check that adapter_id is valid + byte[] adatperId = ri.adapter_id(); + if( Arrays.equals( this.adapterId, adapterId ) ) { + log( method + "(): Adapter id is valid" ); + } + else { + fail( method + "(): Adapter id is invalid (" + + adapterId + ")" ); + } + } + + // TMDI = Target Most Dervied Interface + private void checkTMDI( String method, ServerRequestInfo ri ) { + if( !method.equals( "receive_request" ) ) { + // everything but receive_request should disallow access to + // target_most_derived_interface + try { + ri.target_most_derived_interface(); + fail( method + "(): Should not be able to execute " + + "target_most_derived_interface() here" ); + } + catch( BAD_INV_ORDER e ) { + log( method + "(): Tried target_most_derived_interface() and "+ + "received BAD_INV_ORDER (ok)" ); + } + + } + else { + // Check that target_most_dervied_interface is valid + String targetMostDerivedInterface = + ri.target_most_derived_interface(); + if( targetMostDerivedInterface == null ) { + fail( method + "(): Target most derived interface " + + "is null" ); + } + else if( targetMostDerivedInterface.equals( "" ) ) { + fail( method + "(): Target most derived interface " + + "is empty string" ); + } + else if( targetMostDerivedInterface.equals( validRepId ) ) { + log( method + "(): Target most derived interface " + + "is " + targetMostDerivedInterface ); + } + else { + fail( method + "(): Target most derived interface " + + "is " + targetMostDerivedInterface + ". Expecting " + + validRepId + " instead." ); + } + } + } + + private void checkTargetIsA( String method, ServerRequestInfo ri ) { + if( !method.equals( "receive_request" ) ) { + // everything but receive_request should disallow access to + // target_is_a. + try { + ri.target_is_a( validRepId ); + fail( method + "(): Should not be able to execute " + + "target_is_a() here" ); + } + catch( BAD_INV_ORDER e ) { + log( method + "(): Tried target_is_a() and " + + "received BAD_INV_ORDER (ok)" ); + } + + } + else { + // Check that target_is_a is valid + if( ri.target_is_a( validRepId ) ) { + log( method + "(): target_is_a(" + + validRepId + ") is true (ok)" ); + } + else { + fail( method + "(): target_is_a(" + validRepId + + ") is false." ); + } + + if( ri.target_is_a( invalidRepId ) ) { + fail( method + "(): target_is_a(" + + invalidRepId + ") is true" ); + } + else { + log( method + "(): target_is_a(" + + invalidRepId + ") is false (ok)." ); + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/ClientCommon.java b/functional-tests/src/test/java/pi/serverrequestinfo/ClientCommon.java new file mode 100644 index 000000000..7ef076ab8 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/ClientCommon.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +public abstract class ClientCommon + implements InternalProcess +{ + + // Set in run() + com.sun.corba.ee.spi.orb.ORB orb; + + // Set in run() + PrintStream out; + + // Set in run() + PrintStream err; + + // Set to true if the last invocation resulted in an exception. + boolean exceptionRaised; + + /** + * Creates a com.sun.corba.ee.spi.orb.ORB and notifies the TestInitializer of its presence + */ + void createORB( String[] args ) { + // create the ORB without an initializer + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + this.orb = (com.sun.corba.ee.spi.orb.ORB)ORB.init(args, props); + } + + /** + * Re-resolves all references to eliminate any cached ForwardRequests + * from the last invocation. + */ + abstract void resolveReferences() throws Exception; + + /** + * Call syncWithServer on the server object + */ + abstract String syncWithServer() throws Exception; + + /** + * Invoke the method with the given name on the object + */ + abstract protected void invokeMethod( String methodName ) throws Exception; + + /** + * Wait for server to give us the name of a method to execute, and then + * execute that method. Repeat the process until the server tells us + * to execute a method called "exit." + */ + void obeyServer() throws Exception { + out.println( "+ Obeying commands from server." ); + + String methodName; + do { + // Re-resolve all references to eliminate any cached + // LOCATION_FORWARDs + resolveReferences(); + + // Synchronize with the server and get the name of the + // method to invoke.: + out.println( " - Syncing with server..." + + new Date().toString() ); + methodName = syncWithServer(); + out.println( " - Synced with server at " + + new Date().toString() ); + + // Execute the appropriate method on the hello object: + out.println( " - Executing method " + methodName + "..." ); + exceptionRaised = false; + if( !methodName.equals( ServerCommon.EXIT_METHOD ) ) { + try { + invokeMethod( methodName ); + } + catch( IMP_LIMIT e ) { + exceptionRaised = true; + out.println( " + Received IMP_LIMIT exception" ); + } + } + + } while( !methodName.equals( ServerCommon.EXIT_METHOD ) ); + + out.println( " - Exit detected. No longer obeying server." ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIImpl.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIImpl.java new file mode 100644 index 000000000..b93e4080e --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIImpl.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.PortableInterceptor.*; +import org.omg.PortableServer.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * Servant implementation, shared by ServerRequestDispatcher and POA versions of + * the servant. + */ +class DSIImpl { + // The object to delegate all calls to: + helloDelegate delegate; + + // The orb to use to make DSI-related calls on + private ORB orb; + + public DSIImpl( ORB orb, PrintStream out, String symbol, + helloDelegate.ClientCallback clientCallback ) + { + super(); + this.orb = orb; + this.delegate = new helloDelegate( out, symbol, clientCallback ); + } + + public void invoke( ServerRequest r ) { + String opName = r.op_name(); + java.lang.Object result = null; + + if( opName.equals( "sayHello" ) ) { + sayHello( r ); + } + else if( opName.equals( "sayOneway" ) ) { + sayOneway( r ); + } + else if( opName.equals( "saySystemException" ) ) { + saySystemException( r ); + } + else if( opName.equals( "sayUserException" ) ) { + sayUserException( r ); + } + else if( opName.equals( "syncWithServer" ) ) { + syncWithServer( r ); + } + else if( opName.equals( "sayInvokeAgain" ) ) { + sayInvokeAgain( r ); + } + } + + private void sayHello( ServerRequest r ) { + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + String answer = delegate.sayHello(); + + // Return result: + Any result = orb.create_any(); + result.insert_string( answer ); + r.result( result ); + } + + private void sayOneway( ServerRequest r ) { + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + delegate.sayOneway(); + + // Return void result: + Any ret = orb.create_any(); + ret.type( orb.get_primitive_tc( TCKind.tk_void ) ); + r.set_result( ret ); + } + + private void saySystemException( ServerRequest r ) { + // Must call arguments first. Bug? + NVList list = orb.create_list( 0 ); + r.arguments( list ); + + delegate.saySystemException(); + } + + private void sayUserException( ServerRequest r ) { + try { + delegate.sayUserException(); + } + catch( ExampleException e ) { + Any any = orb.create_any(); + ExampleExceptionHelper.insert( any, e ); + r.set_exception( any ); + } + } + + private void syncWithServer( ServerRequest r ) { + // Decode exceptionRaised parameter + NVList nvlist = orb.create_list( 0 ); + + Any a1 = orb.create_any(); + a1.type( orb.get_primitive_tc( TCKind.tk_boolean ) ); + nvlist.add_value( "exceptionRaised", a1, ARG_IN.value ); + r.arguments( nvlist ); + + boolean exceptionRaised = a1.extract_boolean(); + + // Make call to delegate: + String answer = delegate.syncWithServer( exceptionRaised ); + + // Return result: + Any result = orb.create_any(); + result.insert_string( answer ); + r.result( result ); + } + + private void sayInvokeAgain( ServerRequest r ) { + NVList list = orb.create_list( 0 ); + Any a1 = orb.create_any(); + a1.type( orb.get_primitive_tc( TCKind.tk_long ) ); + list.add_value( "n", a1, ARG_IN.value ); + + r.arguments( list ); + + int n = a1.extract_long(); + delegate.sayInvokeAgain( n ); + + // Return void result: + Any ret = orb.create_any(); + ret.type( orb.get_primitive_tc( TCKind.tk_void ) ); + r.set_result( ret ); + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIPOALocalServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIPOALocalServer.java new file mode 100644 index 000000000..3eb76f70d --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIPOALocalServer.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * Tests DSI POA Local invocations (with a co-located orb) + */ +public class DSIPOALocalServer + extends POAServer +{ + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public DSIPOALocalServer() { + // True means this is a DSI server. + super( true ); + } + + public static void main(String args[]) { + final String[] arguments = args; + try { + final DSIPOALocalServer server = new DSIPOALocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + server.out.println( "===================================" ); + server.out.println( "Creating ORB for DSI POA Local test" ); + server.out.println( "===================================" ); + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + Properties props = new Properties(); + server.createORB( args, props ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + POALocalClient client = new POALocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + // notify main that client can launch now: + synchronized( syncObject ) { + syncObject.notify(); + } + } + + void waitForClients() { + // NOP for this test. + } + + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIPOARemoteServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIPOARemoteServer.java new file mode 100644 index 000000000..b99765e15 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIPOARemoteServer.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +public class DSIPOARemoteServer + extends POAServer +{ + public DSIPOARemoteServer() { + // True means this is a DSI server. + super( true ); + } + + public static void main(String args[]) { + try { + (new DSIPOARemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=========================================" ); + out.println( "Instantiating ORB for DSI POA Remote test" ); + out.println( "=========================================" ); + + out.println( "+ Creating ORB..." ); + Properties props = new Properties(); + createORB( args, props ); + + super.run( environment, args, out, err, extra ); + + + } + + void handshake() { + out.println("Server is ready."); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIClient.java new file mode 100644 index 000000000..5967f631b --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIClient.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInfo.*; + +/** + * Common base class for DSI RMI client test code + */ +public abstract class DSIRMIClient + extends ClientCommon +{ + // The hello object to make invocations on. + hello helloRef; + + // Reference to hello object to be forwarded to. + hello helloRefForward; + + // RMI initial naming context + InitialContext initialNamingContext; + + // to be invoked from subclasses after the ORB is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.err = err; + + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Obey the server's commands: + obeyServer(); + } + + void resolveReferences() throws Exception { + out.println( " - Resolving Hello1..." ); + // Look up reference to hello object on server: + helloRef = resolve( "Hello1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving Hello1Forward..." ); + helloRefForward = resolve( "Hello1Forward" ); + out.println( " - Resolved." ); + } + + String syncWithServer() throws Exception { + return helloRef.syncWithServer( exceptionRaised ); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + try { + helloRef.sayUserException(); + out.println( " - Did not catch ForwardRequest user " + + "exception (error)" ); + throw new RuntimeException( + "Did not catch ForwardRequest user exception " + + "on sayUserException" ); + } + catch( ExampleException e ) { + out.println( " - Caught ExampleException user " + + "exception (ok)" ); + } + } + else if( methodName.equals( "sayInvokeAgain.sayHello" ) ) { + helloRef.sayInvokeAgain( INVOKE_SAY_HELLO.value ); + } + else if( methodName.equals( "sayInvokeAgain.saySystemException" ) ) { + helloRef.sayInvokeAgain( INVOKE_SAY_SYSTEM_EXCEPTION.value ); + } + } + + /** + * Resolves name using RMI + */ + hello resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + hello helloRef = (hello)helloHelper.narrow( (org.omg.CORBA.Object)obj); + + return helloRef; + } + + +} + + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMILocalClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMILocalClient.java new file mode 100644 index 000000000..9721f3a62 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMILocalClient.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInfo.*; + +public class DSIRMILocalClient + extends DSIRMIClient +{ + public DSIRMILocalClient( com.sun.corba.ee.spi.orb.ORB orb ) { + this.orb = orb; + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "===============================================" ); + out.println( "Instantiating Client ORB for DSI RMI Local test" ); + out.println( "===============================================" ); + + super.run( environment, args, out, err, extra ); + } + +} + + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMILocalServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMILocalServer.java new file mode 100644 index 000000000..87f99a5c4 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMILocalServer.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class DSIRMILocalServer + extends DSIRMIServer +{ + + // Object to syncrhornize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final DSIRMILocalServer server = new DSIRMILocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + System.out.println( "===================================" ); + System.out.println( "Creating ORB for DSI RMI Local test" ); + System.out.println( "===================================" ); + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + server.createORB( args, new Properties() ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting client..." ); + DSIRMILocalClient client = new DSIRMILocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + synchronized( syncObject ) { + syncObject.notifyAll(); + } + } + + void waitForClients() { + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIRemoteClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIRemoteClient.java new file mode 100644 index 000000000..09256001d --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIRemoteClient.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInfo.*; + +public class DSIRMIRemoteClient + extends DSIRMIClient +{ + public static void main(String args[]) { + try { + (new DSIRMIRemoteClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "================================================" ); + out.println( "Instantiating Client ORB for DSI RMI Remote test" ); + out.println( "================================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + super.run( environment, args, out, err, extra ); + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIRemoteServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIRemoteServer.java new file mode 100644 index 000000000..e1c303943 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIRemoteServer.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class DSIRMIRemoteServer + extends DSIRMIServer +{ + public static void main(String args[]) { + try { + (new DSIRMIRemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=========================================" ); + out.println( "Instantiating ORB for DSI RMI Remote test" ); + out.println( "=========================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args, new Properties() ); + + super.run( environment, args, out, err, extra ); + } + + void handshake() { + out.println( "Server is ready." ); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized( sync ) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIServer.java new file mode 100644 index 000000000..19adcee8a --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/DSIRMIServer.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public abstract class DSIRMIServer + extends ServerCommon + implements helloDelegate.ClientCallback +{ + InitialContext initialNamingContext; + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create + // initial naming context: + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( "Hello1Forward", + "[Hello1Forward]" ); + + handshake(); + + // Test ServerInterceptor + testServerRequestInfo(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + + waitForClients(); + } + } + + abstract void handshake(); + + abstract void waitForClients(); + + /** + * Creates and binds a hello object using RMI + */ + public org.omg.CORBA.Object createAndBind ( String name, + String symbol ) + throws Exception + { + // create and register it with RMI + helloDSIDeprecatedServant obj = new helloDSIDeprecatedServant( + orb, out, symbol, this ); + orb.connect( obj ); + initialNamingContext.rebind( name, obj ); + + java.lang.Object o = initialNamingContext.lookup( name ); + return (org.omg.CORBA.Object)PortableRemoteObject.narrow( o, + org.omg.CORBA.Object.class ); + } + + /** + * One-way test not applicable for RMI case. Override it. + */ + protected void testOneWay() throws Exception { + out.println( "+ OneWay test not applicable for RMI. Skipping..." ); + } + + /** + * Passes in the appropriate valid and invalid repository ids for RMI + */ + protected void testAttributesValid() + throws Exception + { + testAttributesValid( + "IDL:ServerRequestInfo/hello:1.0", + "IDL:ServerRequestInfo/goodbye:1.0" ); + } + + + // ClientCallback interface + + public String sayHello() { + String result = ""; + + out.println( + " + ClientCallback: resolving and invoking sayHello()..." ); + try { + hello helloRef = resolve( "Hello1" ); + result = helloRef.sayHello(); + } + catch( Exception e ) { + e.printStackTrace(); + throw new RuntimeException( "ClientCallback: Exception thrown." ); + } + + return result; + } + + public void saySystemException() { + out.println( + " + ClientCallback: resolving and invoking " + + "saySystemException()..." ); + try { + hello helloRef = resolve( "Hello1" ); + helloRef.saySystemException(); + } + catch( SystemException e ) { + // expected. + throw e; + } + catch( Exception e ) { + e.printStackTrace(); + throw new RuntimeException( "ClientCallback: Exception thrown." ); + } + } + + /** + * Resolves name using RMI + */ + hello resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + hello helloRef = (hello)helloHelper.narrow( (org.omg.CORBA.Object)obj); + + return helloRef; + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/ExceptionStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/ExceptionStrategy.java new file mode 100644 index 000000000..425164ad8 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/ExceptionStrategy.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.misc.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import ServerRequestInfo.*; +import org.omg.CORBA.*; + +/** + * Strategy to test received_exception() and received_exception_id(). + * Expected invocation order: + * count = 1, send_request, receive_reply + * count = 2, send_request, receive_exception (SystemException) + * count = 3, send_request, receive_exception (UserException) + * count = 4, send_request, receive_other + * All points are checked in order to assure received_exception() + * can only be called in the receive_exception interception point. + */ +public class ExceptionStrategy + extends InterceptorStrategy +{ + + private int count = 0; + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.receive_request_service_contexts( interceptor, ri ); + + try { + count++; + + testException( "rrsc", ri ); + } + catch( Exception ex ) { + failException( "rrsc", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.receive_request( interceptor, ri ); + + try { + testException( "receive_request", ri ); + } + catch( Exception ex ) { + failException( "receive_request", ex ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.send_reply( interceptor, ri ); + + try { + testException( "send_reply", ri ); + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_exception( interceptor, ri ); + + try { + testException( "send_exception", ri ); + } + catch( Exception ex ) { + failException( "send_exception", ex ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_other( interceptor, ri ); + + try { + testException( "send_other", ri ); + } + catch( Exception ex ) { + failException( "send_other", ex ); + } + } + + private void testException( String methodName, + ServerRequestInfo ri ) + { + String header = methodName + "(): "; + if( methodName.equals( "send_exception" ) ) { + if( count == 2 ) { + // Called for System Exception: + // Test send_exception: + Any sendingException = ri.sending_exception(); + SystemException sysex = ORBUtility.extractSystemException( + sendingException ); + if( !(sysex instanceof IMP_LIMIT) ) { + fail( header + "sending_exception() did not return " + + "correct SystemException" ); + } + else { + log( header + "sending_exception() returned " + + "correct SystemException." ); + } + } + else if( count == 3 ) { + // Called for User Exception: + // Test send_exception: + // _REVISIT_ Currently, we do not have access to the + // user exception in the Java Language mappings. When this + // is fixed, uncomment this test. + /* + Any sendingException = ri.sending_exception(); + + try { + log( header + "Got any with type = " + + sendingException.type().name() ); + } + catch( org.omg.CORBA.TypeCodePackage.BadKind e ) { + log( "" + e ); + } + + SystemException sex = + ORBUtility.extractSystemException( sendingException ); + log( "SystemException: " + sex ); + log( "SystemException: " + sex.getMessage() ); + + ExampleException exception = ExampleExceptionHelper.extract( + sendingException ); + if( !exception.reason.equals( "valid" ) ) { + fail( header + + "sending_exception() did not return valid " + + "ExampleException. Reason = " + exception.reason ); + } + else { + log( header + "sending_exception() is valid." ); + } + */ + } + else { + fail( header + "sending_exception should not be " + + "called when count = " + count ); + } + } + else { + // We should not be able to access received_exception! + try { + ri.sending_exception(); + fail( header + + "sending_exception() did not raise BAD_INV_ORDER!" ); + } + catch( BAD_INV_ORDER e ) { + log( header + "sending_exception() raised BAD_INV_ORDER (ok)"); + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/ForwardReferenceStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/ForwardReferenceStrategy.java new file mode 100644 index 000000000..6347f681c --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/ForwardReferenceStrategy.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Strategy to test forward_reference + *

+ * A call will be made, and the interceptor will forward the request to + * another object to handle it. forward_reference will be checked when + * reply status is LOCATION_FORWARD and when it is not LOCATION_FORWARD. + *

+ * Should be called as follows: + * count = 1 + * receive_request_service_contexts + * receive_request + * send_reply + * count = 2 + * receive_request_service_contexts + * receive_request + * send_exception + * count = 3 + * receive_request_service_contexts + * receive_request + * send_other + * count = 4, effective_target is now helloRefForward + * receive_request_service_contexts + * receive_request + * send_reply + */ +public class ForwardReferenceStrategy + extends InterceptorStrategy +{ + + private int count = 0; + + public ForwardReferenceStrategy() { + } + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.receive_request_service_contexts( interceptor, ri ); + + try { + count++; + log( "rrsc(): count is " + count ); + + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "rrsc(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "rrsc(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + } + catch( Exception ex ) { + failException( "rrsc", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.receive_request( interceptor, ri ); + + try { + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "send_reply(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_reply(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.send_reply( interceptor, ri ); + + try { + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "send_reply(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_reply(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_exception( interceptor, ri ); + + try { + // Try calling forward_reference(). Should fail. + try { + ri.forward_reference(); + fail( "send_exception(): forward_reference() did not " + + "raise BAD_INV_ORDER" ); + } + catch( BAD_INV_ORDER e ) { + log( "send_exception(): forward_reference() " + + "raised BAD_INV_ORDER (ok)" ); + } + } + catch( Exception ex ) { + failException( "send_exception", ex ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_other( interceptor, ri ); + + try { + try { + // Try calling forward_reference(). Should not fail. + org.omg.CORBA.Object obj = ri.forward_reference(); + if( TestInitializer.helloRefForward._is_equivalent( obj ) ) { + log( "send_other(): forward_reference() is valid." ); + } + else { + fail( "send_other(): forward_reference() is " + + "invalid." ); + } + } + catch( BAD_INV_ORDER e ) { + fail( "send_other(): forward_reference() raised " + + "BAD_INV_ORDER"); + } + } + catch( Exception ex ) { + failException( "send_other", ex ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/GetServerPolicyStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/GetServerPolicyStrategy.java new file mode 100644 index 000000000..823defb66 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/GetServerPolicyStrategy.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.Messaging.*; + +import java.util.*; + +/** + * Strategy to test get_server_policy. + */ +public class GetServerPolicyStrategy + extends InterceptorStrategy +{ + + // The request count. We should be calling: + // 0 - sayHello + // 1 - saySystemException + // 2 - saySystemException. + private int count = 0; + + private static final int INVALID_POLICY_TYPE = 101; + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws org.omg.PortableInterceptor.ForwardRequest + { + try { + super.receive_request_service_contexts( interceptor, ri ); + count++; + checkGetServerPolicy( "rrsc", ri ); + } + catch( Exception ex ) { + failException( "rrsc", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.receive_request( interceptor, ri ); + checkGetServerPolicy( "rr", ri ); + } + catch( Exception ex ) { + failException( "receive_request", ex ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.send_reply( interceptor, ri ); + checkGetServerPolicy( "sr", ri ); + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws org.omg.PortableInterceptor.ForwardRequest + { + try { + super.send_exception( interceptor, ri ); + checkGetServerPolicy( "se", ri ); + } + catch( Exception ex ) { + failException( "send_exception", ex ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws org.omg.PortableInterceptor.ForwardRequest + { + try { + super.send_other( interceptor, ri ); + checkGetServerPolicy( "so", ri ); + } + catch( Exception ex ) { + failException( "send_other", ex ); + } + } + + private void checkGetServerPolicy( String method, ServerRequestInfo ri ) + throws Exception + { + // Try an invalid policy: + try { + Policy policy = ri.get_server_policy( INVALID_POLICY_TYPE ); + if( policy != null ) { + fail( method + "(): get_server_policy( INVALID ) " + + "is not null!" ); + } + else { + log( method + "(): get_server_policy( INVALID ) " + + "is null (ok)" ); + } + } + catch( INV_POLICY e ) { + fail( method + "(): get_server_policy( INVALID ) " + + "throws INV_POLICY (error - should return null)" ); + } + catch( Exception e ) { + e.printStackTrace(); + fail( method + "(): get_server_policy( INVALID ) " + + "throws incorrect exception: " + e ); + } + + // Try a standard policy: + try { + Policy policy = ri.get_server_policy( + ID_UNIQUENESS_POLICY_ID.value ); + if( policy instanceof IdUniquenessPolicy ) { + log( method + "(): get_server_policy( STANDARD ) " + + "returns correct policy." ); + } + else { + fail( method + "(): get_server_policy( STANDARD ) " + + "returns incorrect policy: " + + policy.getClass().getName() ); + } + } + catch( INV_POLICY e ) { + fail( method + "(): get_server_policy( STANDARD ) " + + "throws INV_POLICY" ); + } + catch( Exception e ) { + e.printStackTrace(); + fail( method + "(): get_server_policy( STANDARD ) " + + "throws incorrect exception: " + e ); + } + + // Try a custom policy: + try { + Policy policy = ri.get_server_policy( 100 ); + if( policy instanceof PolicyHundred ) { + log( method + "(): get_server_policy( CUSTOM ) " + + "returns correct policy." ); + } + else { + fail( method + "(): get_server_policy( CUSTOM ) " + + "returns incorrect policy: " + + policy.getClass().getName() ); + } + } + catch( INV_POLICY e ) { + fail( method + "(): get_server_policy( CUSTOM ) " + + "throws INV_POLICY" ); + } + catch( Exception e ) { + e.printStackTrace(); + fail( method + "(): get_server_policy( CUSTOM ) " + + "throws incorrect exception: " + e ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/InterceptorStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/InterceptorStrategy.java new file mode 100644 index 000000000..e9d5d7afe --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/InterceptorStrategy.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Base class for all server request interceptor strategies used in this + * test. This allows for dyanmic behavior modifications between test cases. + * Default method implementations do nothing. + */ +abstract public class InterceptorStrategy { + + /** True if test failed, false if not */ + public boolean failed = false; + + /** The reason for failure */ + public String failReason = null; + + /** + * Logs the given message as test output. + */ + protected void log( String message ) { + ServerCommon.server.out.println( " + " + message ); + } + + /** + * Reports the given message as a test failure for the given reason. + */ + protected void fail( String reason ) { + ServerCommon.server.out.println( " + ERROR: " + reason ); + failReason = reason; + failed = true; + } + + /** + * Reports a test failure, using the exception object as a reason. + * The origin of failure is given in the origin string. + */ + protected void failException( String origin, Exception ex ) { + String failReason = "Exception " + + ex.getClass().getName() + "( " + ex.getMessage() + " )" + + " in " + this.getClass().getName() + "." + origin + "."; + ServerCommon.server.out.println( " + ERROR: " + failReason ); + ex.printStackTrace(); + failed = true; + } + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + } + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/InvokeExceptions.java b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeExceptions.java new file mode 100644 index 000000000..8fd7da150 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeExceptions.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; +import ServerRequestInfo.*; + +/** + * Invocation strategy in which four calls are made. + * 1. No exception raised + * 2. SystemException raised + * 3. UserException raised + * 4. No exception raised, receive_other is called. + */ +public class InvokeExceptions + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke rrsc, rr, then sr + invokeMethod( "sayHello" ); + + // Invoke rrsc, rr, then se + try { + invokeMethod( "saySystemException" ); + } + catch( IMP_LIMIT e ) { + // We expect this, but no other exception. + } + + // Invoke rrsc, rr, then se (user exception) + try { + invokeMethod( "sayUserException" ); + } + catch( ExampleException e ) { + // We expect this, but no other exception. + } + + // Invoke rrsc, rr, then so + SampleServerRequestInterceptor.exceptionRedirectToOther = true; + SampleServerRequestInterceptor.invokeOnForwardedObject = false; + try { + invokeMethod( "saySystemException" ); + } + catch( IMP_LIMIT e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/InvokeOneWay.java b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeOneWay.java new file mode 100644 index 000000000..f428b920d --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeOneWay.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which two requests are sent, one that is not oneway + * and one that is oneway, in that order. + */ +public class InvokeOneWay + extends InvokeStrategy +{ + public void invoke() throws Exception { + super.invoke(); + + // Invoke normal call + invokeMethod( "sayHello" ); + + // Invoke oneway call + invokeMethod( "sayOneway" ); + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/InvokeStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeStrategy.java new file mode 100644 index 000000000..241aa32da --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeStrategy.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Base class for all invocation strategies used in this test. This allows + * for dynamic behavior modifications between test cases of which objects + * are invoked. Default method implementations do nothing. + */ +abstract public class InvokeStrategy { + /** + * Invokes the method with the given name + */ + protected void invokeMethod( String name ) throws Exception { + ServerCommon.server.invokeMethod( name ); + } + + public void invoke() throws Exception { + // Reset the request interceptor to prepare for test: + SampleServerRequestInterceptor.enabled = true; + SampleServerRequestInterceptor.receiveRequestServiceContextsEnabled = + true; + SampleServerRequestInterceptor.receiveRequestEnabled = true; + SampleServerRequestInterceptor.sendReplyEnabled = true; + SampleServerRequestInterceptor.sendExceptionEnabled = true; + SampleServerRequestInterceptor.sendOtherEnabled = true; + + // Reset flags + SampleServerRequestInterceptor.exceptionRedirectToOther = false; + SampleServerRequestInterceptor.invokeOnForwardedObject = false; + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/InvokeVisitAll.java b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeVisitAll.java new file mode 100644 index 000000000..f9ba153e3 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeVisitAll.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which each interception point is visited. + * The following order is used: + * rrsc, rr, sr + * rrsc, rr, se + * rrsc, rr, so + */ +public class InvokeVisitAll + extends InvokeStrategy +{ + // String to prepend to any outgoing call for this invocation strategy. + private String methodPrefix = ""; + + public InvokeVisitAll( String methodPrefix ) { + this.methodPrefix = methodPrefix; + } + + public InvokeVisitAll() { + this( "" ); + } + + public void invoke() throws Exception { + super.invoke(); + + // Invoke rrsc, rr, sr + invokeMethod( methodPrefix + "sayHello" ); + + // Invoke rrsc, rr, se + try { + invokeMethod( methodPrefix + "saySystemException" ); + } + catch( IMP_LIMIT e ) { + // We expect this, but no other exception. + } + + // Invoke rrsc, rr, so + try { + SampleServerRequestInterceptor.exceptionRedirectToOther = true; + SampleServerRequestInterceptor.invokeOnForwardedObject = false; + invokeMethod( methodPrefix + "saySystemException" ); + } + catch( IMP_LIMIT e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/InvokeVisitAllForward.java b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeVisitAllForward.java new file mode 100644 index 000000000..4c31026c8 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/InvokeVisitAllForward.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.CORBA.*; + +/** + * Invocation strategy in which each interception point is visited. + * Interceptors are also called for the forwarded object. + * The following order is used: + * rrsc, rr, sr + * rrsc, rr, se + * rrsc, rr, so + * rrsc, rr, sr + */ +public class InvokeVisitAllForward + extends InvokeStrategy +{ + public InvokeVisitAllForward() { + } + + public void invoke() throws Exception { + super.invoke(); + + SampleServerRequestInterceptor.invokeOnForwardedObject = true; + + // Invoke send_request then receive_reply + invokeMethod( "sayHello" ); + + // Invoke send_request then receive_exception: + try { + invokeMethod( "saySystemException" ); + } + catch( IMP_LIMIT e ) { + // We expect this, but no other exception. + } + + // Invoke send_request then receive_other: + SampleServerRequestInterceptor.exceptionRedirectToOther = true; + try { + invokeMethod( "saySystemException" ); + } + catch( IMP_LIMIT e ) { + // We expect this, but no other exception. + } + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/OneWayStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/OneWayStrategy.java new file mode 100644 index 000000000..a08168f40 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/OneWayStrategy.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Strategy to test response_expected() + */ +public class OneWayStrategy + extends InterceptorStrategy +{ + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.receive_request_service_contexts( interceptor, ri ); + + try { + checkResponseExpected( "rrsc", ri ); + } + catch( Exception e ) { + failException( "rrsc", e ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.receive_request( interceptor, ri ); + + try { + checkResponseExpected( "receive_request", ri ); + } + catch( Exception e ) { + failException( "receive_request", e ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.send_reply( interceptor, ri ); + + try { + checkResponseExpected( "send_reply", ri ); + } + catch( Exception e ) { + failException( "send_reply", e ); + } + } + + + private void checkResponseExpected( String method, ServerRequestInfo ri ) { + String operationName = ri.operation(); + boolean responseExpected = ri.response_expected(); + boolean validExpected = !operationName.equals( "sayOneway" ); + + log( method + "(): Operation " + operationName + + ", response expected = " + responseExpected ); + + if( responseExpected != validExpected ) { + fail( "response_expected() invalid for this operation." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/POAClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/POAClient.java new file mode 100644 index 000000000..bd2a022ad --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/POAClient.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +public abstract class POAClient + extends ClientCommon +{ + // The hello object to make invocations on. + hello helloRef; + + // Reference to hello object to be forwarded to. + hello helloRefForward; + + // Reference to hello child 1 + hello helloChild1; + + // Reference to hello child 2 + hello helloChild2; + + // To be invoked after the orb is created by subclasses. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.err = err; + + // Obey the server's commands: + obeyServer(); + } + + void resolveReferences() throws Exception { + out.println( " - Resolving Hello1..." ); + // Look up reference to hello object on server: + helloRef = resolve( orb, "Hello1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving Hello1Forward..." ); + helloRefForward = resolve( orb, "Hello1Forward" ); + out.println( " - Resolved." ); + + out.println( " - Resolving HelloChild1..." ); + helloChild1 = resolve( orb, "HelloChild1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving HelloChild2..." ); + helloChild2 = resolve( orb, "HelloChild2" ); + out.println( " - Resolved." ); + } + + String syncWithServer() throws Exception { + return helloRef.syncWithServer( exceptionRaised ); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "child1.sayHello" ) ) { + helloChild1.sayHello(); + } + else if( methodName.equals( "child2.sayHello" ) ) { + helloChild2.sayHello(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "child1.saySystemException" ) ) { + helloChild1.saySystemException(); + } + else if( methodName.equals( "child2.saySystemException" ) ) { + helloChild2.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + try { + helloRef.sayUserException(); + out.println( " - Did not catch ForwardRequest user " + + "exception (error)" ); + throw new RuntimeException( + "Did not catch ForwardRequest user exception " + + "on sayUserException" ); + } + catch( ExampleException e ) { + out.println( " - Caught ExampleException user " + + "exception (ok)" ); + } + } + else if( methodName.equals( "sayInvokeAgain.sayHello" ) ) { + helloRef.sayInvokeAgain( INVOKE_SAY_HELLO.value ); + } + else if( methodName.equals( "sayInvokeAgain.saySystemException" ) ) { + helloRef.sayInvokeAgain( INVOKE_SAY_SYSTEM_EXCEPTION.value ); + } + else { + throw new RuntimeException( "Unknown method: '" + + methodName + "'" ); + } + } + + /** + * Implementation borrwed from corba.socket.HelloClient.java test + */ + static hello resolve(ORB orb, String name) + throws Exception + { + // Get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path)); + + return helloRef; + } + + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/POALocalClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/POALocalClient.java new file mode 100644 index 000000000..4b270af2d --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/POALocalClient.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * This client is launched from POALocalServer so they can share + * a single orb. + */ +public class POALocalClient + extends POAClient +{ + public POALocalClient( com.sun.corba.ee.spi.orb.ORB orb ) { + this.orb = orb; + } + + public void run( Properties environment, String args[], + PrintStream out, PrintStream err, Hashtable extra) + throws Exception + { + out.println( "===============" ); + out.println( "Starting Client" ); + out.println( "===============" ); + + super.run( environment, args, out, err, extra ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/POALocalServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/POALocalServer.java new file mode 100644 index 000000000..b5bdaa68f --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/POALocalServer.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * Tests POA Local invocations (with a co-located orb) + */ +public class POALocalServer + extends POAServer +{ + // Object to synchronize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final POALocalServer server = new POALocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + server.out.println( "===============================" ); + server.out.println( "Creating ORB for POA Local test" ); + server.out.println( "===============================" ); + + // For this test, start both the client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + Properties props = new Properties(); + server.createORB( args, props ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting Client..." ); + POALocalClient client = new POALocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + // notify main that client can launch now: + synchronized( syncObject ) { + syncObject.notify(); + } + } + + void waitForClients() { + // NOP for this test. + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/POARemoteClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/POARemoteClient.java new file mode 100644 index 000000000..d7f0a9c9c --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/POARemoteClient.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +public class POARemoteClient + extends POAClient +{ + public static void main(String args[]) { + try { + (new POARemoteClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "============================================" ); + out.println( "Instantiating Client ORB for POA Remote test" ); + out.println( "============================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + super.run( environment, args, out, err, extra ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/POARemoteServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/POARemoteServer.java new file mode 100644 index 000000000..a3a3ea1dc --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/POARemoteServer.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +public class POARemoteServer + extends POAServer +{ + public static void main(String args[]) { + try { + (new POARemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=====================================" ); + out.println( "Instantiating ORB for POA Remote test" ); + out.println( "=====================================" ); + + out.println( "+ Creating ORB..." ); + Properties props = new Properties(); + createORB( args, props ); + + super.run( environment, args, out, err, extra ); + + + } + + void handshake() { + out.println("Server is ready."); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/POAServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/POAServer.java new file mode 100644 index 000000000..11646853e --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/POAServer.java @@ -0,0 +1,277 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * Common base class for POA Server test files. + */ +public abstract class POAServer + extends ServerCommon + implements helloDelegate.ClientCallback +{ + static final String ROOT_POA = "RootPOA"; + + POA rootPOA; + + POA childPOA1; + POA childPOA2; + org.omg.CORBA.Object childPOA1Object; + org.omg.CORBA.Object childPOA2Object; + byte[] childPOA1Id; + byte[] childPOA2Id; + + // true if this is a dynamic implementation, or false if not + boolean dsi; + + public POAServer() { + this( false ); + } + + public POAServer( boolean dsi ) { + this.dsi = dsi; + } + + // To be invoked by subclass after orb is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + this.out = out; + + // Get the root POA: + rootPOA = null; + out.println( "+ Obtaining handle to root POA and activating..." ); + try { + rootPOA = (POA)orb.resolve_initial_references( ROOT_POA ); + } + catch( InvalidName e ) { + err.println( ROOT_POA + " is an invalid name." ); + throw e; + } + rootPOA.the_POAManager().activate(); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( rootPOA, "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( rootPOA, + "Hello1Forward", + "[Hello1Forward]" ); + + // Create 2 additional POAs, each with different IDs, so we can test + // adapter_id: + out.println( "+ Creating 2 additional POAs with different IDs..." ); + createChildPOA( 1 ); + createChildPOA( 2 ); + + handshake(); + + // Test ServerRequestInfo + testServerRequestInfo(); + + // Test adapter_id + testAdapterId(); + + // Test get_server_policy + testGetServerPolicy(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + + // wait for invocations from clients + waitForClients(); + } + } + + // Output handshake or wake up main. + abstract void handshake(); + + // Wait for invocations from clients. + abstract void waitForClients(); + + /** + * Implementation borrowed from corba.socket.HelloServer test + */ + public org.omg.CORBA.Object createAndBind ( POA poa, String name, + String symbol ) + throws Exception + { + // create servant and register it with the ORB + Servant helloRef; + + if( dsi ) { + helloRef = new helloDSIServant( orb, out, symbol, this ); + } + else { + helloRef = new helloServant( out, symbol, this ); + } + + byte[] id = poa.activate_object(helloRef); + org.omg.CORBA.Object ref = poa.id_to_reference(id); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, ref); + + return ref; + } + + /** + * Passes in the appropriate valid and invalid repository ids for POA + */ + protected void testAttributesValid() + throws Exception + { + testAttributesValid( + "IDL:ServerRequestInfo/hello:1.0", + "IDL:ServerRequestInfo/goodbye:1.0" ); + } + + + /** + * Special test case for adapter_id that makes an invocation on + * two separate objects, using two separate POAs each with a different + * adapter ID. Checks to make sure adapter_id returns the correct + * value for each. + */ + protected void testAdapterId() + throws Exception + { + out.println( "+ Testing adapter_id with child POA 1..." ); + InterceptorStrategy interceptorStrategy = + new AdapterIdStrategy( childPOA1Id ); + InvokeStrategy invokeStrategy = new InvokeVisitAll( "child1." ); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "adapter_id_1" ); + + out.println( "+ Testing adapter_id with child POA 2..." ); + interceptorStrategy = new AdapterIdStrategy( childPOA2Id ); + invokeStrategy = new InvokeVisitAll( "child2." ); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "adapter_id_2" ); + } + + /** + * Special test case for get_server_policy that verifies we can retrieve + * policies from ServerRequestInfo + */ + protected void testGetServerPolicy() + throws Exception + { + out.println( "+ Testing get_server_policy..." ); + InterceptorStrategy interceptorStrategy = + new GetServerPolicyStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll( "child1." ); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "get_server_policy" ); + } + + /** + * Creates a child POA and remember its adapter id. Attach some policies + * to the POA so we can test get_server_policy later on. + */ + private void createChildPOA( int n ) + throws Exception + { + Policy[] policies = new Policy[2]; + + policies[0] = rootPOA.create_id_uniqueness_policy( + IdUniquenessPolicyValue.MULTIPLE_ID ); + Any value = orb.create_any(); + value.insert_long( 99 ); + policies[1] = orb.create_policy( 100, value ); + + POA tpoa = rootPOA.create_POA( "childPOA" + n, null, policies ); + tpoa.the_POAManager().activate(); + org.omg.CORBA.Object obj = + createAndBind( tpoa, "HelloChild" + n, "[HelloChild" + n + "]" ); + byte[] id = tpoa.id(); + + out.println( " - Adpater id is " + id ); + + if( n == 1 ) { + childPOA1 = tpoa; + childPOA1Object = obj; + childPOA1Id = id; + } + else { + childPOA2 = tpoa; + childPOA2Object = obj; + childPOA2Id = id; + } + } + + // ClientCallback interface for request info stack test: + public String sayHello() { + String result = ""; + + out.println( + " + ClientCallback: resolving and invoking sayHello()..." ); + try { + hello helloRef = POAClient.resolve( orb, "Hello1" ); + result = helloRef.sayHello(); + } + catch( Exception e ) { + e.printStackTrace(); + throw new RuntimeException( "ClientCallback: exception thrown." ); + } + + return result; + + } + + public void saySystemException() { + out.println( + " + ClientCallback: resolving and invoking " + + "saySystemException()..." ); + try { + hello helloRef = POAClient.resolve( orb, "Hello1" ); + helloRef.saySystemException(); + } + catch( SystemException e ) { + // expected. + throw e; + } + catch( Exception e ) { + e.printStackTrace(); + throw new RuntimeException( "ClientCallback: exception thrown." ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/PolicyFactoryHundred.java b/functional-tests/src/test/java/pi/serverrequestinfo/PolicyFactoryHundred.java new file mode 100644 index 000000000..62e2835c6 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/PolicyFactoryHundred.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * This is the Policy Factory to create PolicyHundred object. + * + * COPIED FROM iorinterceptor test. + */ +public class PolicyFactoryHundred extends LocalObject + implements org.omg.PortableInterceptor.PolicyFactory +{ + public Policy create_policy( int type, Any val ) { + System.out.println( "PolicyFactoryHundred.create_policy called..." ); + System.out.flush(); + return new PolicyHundred( val.extract_long() ); + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/PolicyHundred.java b/functional-tests/src/test/java/pi/serverrequestinfo/PolicyHundred.java new file mode 100644 index 000000000..87d967a89 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/PolicyHundred.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** + * This Policy object's type is 100. + * + * COPIED FROM iorinterceptor test. + */ +public class PolicyHundred extends LocalObject + implements Policy +{ + private int value; + + public PolicyHundred( int value ) { + this.value = value; + } + + public int policy_type( ) { + return 100; + } + + + public org.omg.CORBA.Policy copy( ) { + return this; + } + + public void destroy ( ) { + // Do Nothing + } + + public int getValue() { + return value; + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RMIClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/RMIClient.java new file mode 100644 index 000000000..925ca487a --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RMIClient.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInfo.*; + +/** + * Common base class for RMI client test code + */ +public abstract class RMIClient + extends ClientCommon +{ + // The hello object to make invocations on. + helloIF helloRef; + + // Reference to hello object to be forwarded to. + helloIF helloRefForward; + + // RMI initial naming context + InitialContext initialNamingContext; + + // to be invoked from subclasses after the ORB is created. + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + this.out = out; + this.err = err; + + out.println( "+ Creating initial naming context..." ); + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Obey the server's commands: + obeyServer(); + } + + void resolveReferences() throws Exception { + out.println( " - Resolving Hello1..." ); + // Look up reference to hello object on server: + helloRef = resolve( "Hello1" ); + out.println( " - Resolved." ); + + out.println( " - Resolving Hello1Forward..." ); + helloRefForward = resolve( "Hello1Forward" ); + out.println( " - Resolved." ); + } + + String syncWithServer() throws Exception { + return helloRef.syncWithServer( exceptionRaised ); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + try { + if( methodName.equals( "sayHello" ) ) { + helloRef.sayHello(); + } + else if( methodName.equals( "sayOneway" ) ) { + helloRef.sayOneway(); + } + else if( methodName.equals( "saySystemException" ) ) { + helloRef.saySystemException(); + } + else if( methodName.equals( "sayUserException" ) ) { + try { + helloRef.sayUserException(); + out.println( " - Did not catch ForwardRequest user " + + "exception (error)" ); + throw new RuntimeException( + "Did not catch ForwardRequest user exception " + + "on sayUserException" ); + } + catch( ExampleException e ) { + out.println( " - Caught ExampleException user " + + "exception (ok)" ); + } + } + else if( methodName.equals( "sayInvokeAgain.sayHello" ) ) { + helloRef.sayInvokeAgain( INVOKE_SAY_HELLO.value ); + } + else if( methodName.equals( "sayInvokeAgain.saySystemException" ) ) + { + helloRef.sayInvokeAgain( INVOKE_SAY_SYSTEM_EXCEPTION.value ); + } + } + catch( RemoteException e ) { + throw (Exception)e.detail; + } + } + + /** + * Resolves name using RMI + */ + helloIF resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } + + +} + + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RMILocalClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/RMILocalClient.java new file mode 100644 index 000000000..e966b6906 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RMILocalClient.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInfo.*; + +public class RMILocalClient + extends RMIClient +{ + public RMILocalClient( com.sun.corba.ee.spi.orb.ORB orb ) { + this.orb = orb; + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "===========================================" ); + out.println( "Instantiating Client ORB for RMI Local test" ); + out.println( "===========================================" ); + + super.run( environment, args, out, err, extra ); + } + +} + + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RMILocalServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/RMILocalServer.java new file mode 100644 index 000000000..2a8565c7c --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RMILocalServer.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class RMILocalServer + extends RMIServer +{ + // Object to syncrhornize on to wait for server to start: + private java.lang.Object syncObject; + + public static void main(String args[]) { + final String[] arguments = args; + try { + final RMILocalServer server = new RMILocalServer(); + + TestInitializer.out = System.out; + server.out = System.out; + server.err = System.err; + + System.out.println( "===============================" ); + System.out.println( "Creating ORB for RMI Local test" ); + System.out.println( "===============================" ); + + // For this test, start botht he client and the server using + // the same ORB. + System.out.println( "+ Creating ORB for client and server..." ); + server.createORB( args, new Properties() ); + + System.out.println( "+ Starting Server..." ); + server.syncObject = new java.lang.Object(); + + new Thread() { + public void run() { + try { + server.run( + System.getProperties(), + arguments, System.out, + System.err, null ); + } + catch( Exception e ) { + System.err.println( "SERVER CRASHED:" ); + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + }.start(); + + // Wait for server to start... + synchronized( server.syncObject ) { + try { + server.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore. + } + } + + // Start client: + System.out.println( "+ Starting client..." ); + RMILocalClient client = new RMILocalClient( server.orb ); + client.run( System.getProperties(), + args, System.out, System.err, null ); + System.exit( 0 ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + super.run( environment, args, out, err, extra ); + } + + void handshake() { + synchronized( syncObject ) { + syncObject.notifyAll(); + } + } + + void waitForClients() { + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RMIRemoteClient.java b/functional-tests/src/test/java/pi/serverrequestinfo/RMIRemoteClient.java new file mode 100644 index 000000000..e81ada531 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RMIRemoteClient.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import corba.framework.*; + +import java.util.*; +import java.io.*; +import java.rmi.*; +import javax.naming.*; +import javax.rmi.*; + +import ServerRequestInfo.*; + +public class RMIRemoteClient + extends RMIClient +{ + public static void main(String args[]) { + try { + (new RMIRemoteClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + out.println( "============================================" ); + out.println( "Instantiating Client ORB for RMI Remote test" ); + out.println( "============================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args ); + + super.run( environment, args, out, err, extra ); + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RMIRemoteServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/RMIRemoteServer.java new file mode 100644 index 000000000..e8ce09a94 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RMIRemoteServer.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public class RMIRemoteServer + extends RMIServer +{ + public static void main(String args[]) { + try { + (new RMIRemoteServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } + catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + TestInitializer.out = out; + this.out = out; + this.err = err; + + out.println( "=====================================" ); + out.println( "Instantiating ORB for RMI Remote test" ); + out.println( "=====================================" ); + + out.println( "+ Creating ORB..." ); + createORB( args, new Properties() ); + + super.run( environment, args, out, err, extra ); + } + + void handshake() { + out.println( "Server is ready." ); + out.flush(); + } + + void waitForClients() { + // wait for invocations from clients + java.lang.Object sync = new java.lang.Object(); + synchronized( sync ) { + try { + sync.wait(); + } + catch( InterruptedException e ) { + } + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RMIServer.java b/functional-tests/src/test/java/pi/serverrequestinfo/RMIServer.java new file mode 100644 index 000000000..d4771d360 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RMIServer.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.CORBA.ORBPackage.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.POAPackage.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import org.omg.PortableInterceptor.*; +import com.sun.corba.ee.impl.interceptors.*; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; + +public abstract class RMIServer + extends ServerCommon + implements helloDelegate.ClientCallback +{ + InitialContext initialNamingContext; + + public void run( Properties environment, String args[], PrintStream out, + PrintStream err, Hashtable extra) + throws Exception + { + try { + out.println( "+ Creating Initial naming context..." ); + // Inform the JNDI provider of the ORB to use and create + // initial naming context: + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb ); + initialNamingContext = new InitialContext( env ); + + // Set up hello object: + out.println( "+ Creating and binding Hello1 object..." ); + TestInitializer.helloRef = createAndBind( "Hello1", + "[Hello1]" ); + + out.println( "+ Creating and binding Hello1Forward object..." ); + TestInitializer.helloRefForward = createAndBind( "Hello1Forward", + "[Hello1Forward]" ); + + handshake(); + + // Test ServerInterceptor + testServerRequestInfo(); + } finally { + finish() ; + + // Notify client it's time to exit. + exitClient(); + + waitForClients(); + } + } + + abstract void handshake(); + + abstract void waitForClients(); + + /** + * Creates and binds a hello object using RMI + */ + public org.omg.CORBA.Object createAndBind ( String name, + String symbol ) + throws Exception + { + // create and register it with RMI + helloRMIIIOP obj = new helloRMIIIOP( out, symbol, this ); + initialNamingContext.rebind( name, obj ); + + java.lang.Object o = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( o, + helloIF.class ); + return (org.omg.CORBA.Object)helloRef; + } + + /** + * One-way test not applicable for RMI case. Override it. + */ + protected void testOneWay() throws Exception { + out.println( "+ OneWay test not applicable for RMI. Skipping..." ); + } + + /** + * Passes in the appropriate valid and invalid repository ids for RMI + */ + protected void testAttributesValid() + throws Exception + { + testAttributesValid( + "RMI:pi.serverrequestinfo.helloIF:0000000000000000", + "RMI:pi.serverrequestinfo.goodbyeIF:0000000000000000" ); + } + + + // ClientCallback interface for request info stack test: + public String sayHello() { + String result = ""; + + out.println( + " + ClientCallback: resolving and invoking sayHello()..." ); + try { + helloIF helloRef = resolve( "Hello1" ); + result = helloRef.sayHello(); + } + catch( Exception e ) { + e.printStackTrace(); + throw new RuntimeException( "ClientCallback: Exception thrown." ); + } + + return result; + } + + public void saySystemException() { + out.println( + " + ClientCallback: resolving and invoking " + + "saySystemException()..." ); + try { + helloIF helloRef = resolve( "Hello1" ); + try { + helloRef.saySystemException(); + } + catch( RemoteException e ) { + throw e.detail; + } + } + catch( SystemException e ) { + // expected. + throw e; + } + catch( Throwable e ) { + System.err.println( "ClientCallback: Exception " + + e.getClass().getName() + " thrown." ); + e.printStackTrace(); + throw new RuntimeException( "ClientCallback: Exception thrown." ); + } + } + + /** + * Resolves name using RMI + */ + helloIF resolve(String name) + throws Exception + { + java.lang.Object obj = initialNamingContext.lookup( name ); + helloIF helloRef = (helloIF)PortableRemoteObject.narrow( + obj, helloIF.class ); + + return helloRef; + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RequestId1Strategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/RequestId1Strategy.java new file mode 100644 index 000000000..f79cae6d1 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RequestId1Strategy.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; + +/** + * Strategy to test request_id.1 + */ +public class RequestId1Strategy + extends InterceptorStrategy +{ + + // The id received in receive_request_service_contexts: + private int requestId; + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.receive_request_service_contexts( interceptor, ri ); + + try { + this.requestId = ri.request_id(); + log( "receive_request_service_contexts(): request_id = " + + requestId ); + } + catch( Exception ex ) { + failException( "receive_request_service_contexts", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.receive_request( interceptor, ri ); + try { + testId( "receive_request", ri.request_id() ); + } + catch( Exception e ) { + failException( "send_reply", e ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.send_reply( interceptor, ri ); + try { + testId( "send_reply", ri.request_id() ); + } + catch( Exception e ) { + failException( "send_reply", e ); + } + } + + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_exception( interceptor, ri ); + try { + testId( "send_exception", ri.request_id() ); + } + catch( Exception e ) { + failException( "send_exception", e ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_other( interceptor, ri ); + + try { + testId( "send_other", ri.request_id() ); + } + catch( Exception e ) { + failException( "send_other", e ); + } + } + + /** + * Tests the given id after send_request + */ + private void testId( String method, int id ) { + log( method + "(): request_id = " + id ); + if( id != this.requestId ) { + fail( "Request ID in " + method + " did not match request " + + "id in " + method ); + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/RequestInfoStackStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/RequestInfoStackStrategy.java new file mode 100644 index 000000000..63b971151 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/RequestInfoStackStrategy.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.Messaging.*; + +import java.util.*; + +/** + * Strategy to test that the server-sides request info stack is functioning. + */ +public class RequestInfoStackStrategy + extends InterceptorStrategy +{ + + // The request count. We should be calling: + // 0 - idle + // 1 - sayInvokeAgain + // 2 - sayHello + private int count = 0; + + // The test number. We should be recursively calling: + // 1 - sayHello + // 2 - saySystemException + // 3 - saySystemException + private int testNum = 0; + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.receive_request_service_contexts( interceptor, ri ); + log( "rrsc(): count = " + count ); + log( "rrsc(): count = " + count + " to " + (count+1) ); + count++; + if( count == 1 ) testNum++; + checkOperationName( "rrsc", ri.operation() ); + } + catch( Exception ex ) { + failException( "rrsc", ex ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.receive_request( interceptor, ri ); + log( "rr(): count = " + count ); + checkOperationName( "rr", ri.operation() ); + } + catch( Exception ex ) { + failException( "receive_request", ex ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + try { + super.send_reply( interceptor, ri ); + log( "sr(): count = " + count ); + checkOperationName( "sr", ri.operation() ); + log( "sr(): count = " + count + " to " + (count-1) ); + count--; + } + catch( Exception ex ) { + failException( "send_reply", ex ); + } + } + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.send_exception( interceptor, ri ); + log( "se(): count = " + count ); + checkOperationName( "se", ri.operation() ); + log( "se(): count = " + count + " to " + (count-1) ); + count--; + } + catch( Exception ex ) { + failException( "send_exception", ex ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + try { + super.send_other( interceptor, ri ); + log( "so(): count = " + count ); + checkOperationName( "so", ri.operation() ); + log( "so(): count = " + count + " to " + (count-1) ); + count--; + } + catch( Exception ex ) { + failException( "send_other", ex ); + } + } + + private void checkOperationName( String method, String operationName ) + throws Exception + { + switch( count ) { + case 1: + if( !operationName.equals( "sayInvokeAgain" ) ) { + fail( method + "(): Incorrect operation name: " + + operationName + " Count = 1" ); + } + log( method + "(): sayInvokeAgain() invoked" ); + break; + case 2: + String expected = (testNum == 1) ? + "sayHello" : "saySystemException"; + if( !operationName.equals( expected ) ) { + fail( method + "(): Incorrect operation name: " + + operationName + " Count = 2" ); + } + log( method + "(): " + expected + "() invoked" ); + break; + default: + // This will happen if our recursive depth is too high + // from PI's standpoint. + log( method + "(): count too high! count = " + count ); + break; + } + } +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/SampleServerRequestInterceptor.java b/functional-tests/src/test/java/pi/serverrequestinfo/SampleServerRequestInterceptor.java new file mode 100644 index 000000000..95ebac99a --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/SampleServerRequestInterceptor.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; + +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ServerRequestInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; + +/** + * Sample ServerRequestInterceptor for use in testing. This interceptor + * is dynamically configurable via an InterceptorStrategy. It assumes + * three interceptors have been registered, and most operations will be + * performed on interceptor number 2 and only if the target() is not + * helloRefForward. + */ +public class SampleServerRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ServerRequestInterceptor +{ + // Valid message for exceptions + public static final String VALID_MESSAGE = "Valid test result."; + + // The dyanmic strategy that will be used for this round. + public static InterceptorStrategy strategy = null; + + // The name of this interceptor + private String name; + + // Ensure this call was intercepted. This is set to true when at + // least one interceptor was called, and is reset before the server + // requests an invocation from the client. This helps detect a faulty + // test run. + public static boolean intercepted = false; + + // True if enabled, false if all interception points must + // return immediately. + public static boolean enabled = false; + + // Selective enabling and disabling of interception points. These + // are only applicable if enabled is true: + public static boolean receiveRequestServiceContextsEnabled = true; + public static boolean receiveRequestEnabled = true; + public static boolean sendReplyEnabled = true; + public static boolean sendExceptionEnabled = true; + public static boolean sendOtherEnabled = true; + + // Special flags to override the strategy behavior of this interceptor. + + // Throw ForwardRequest during receive_exception so that receive_other + // is called. + public static boolean exceptionRedirectToOther = false; + + // Allow interceptors to be invoked for forwarded object as well. + public static boolean invokeOnForwardedObject = false; + + // Normally, _is_a invocations are not recorded. This is because _is_a + // is invoked often by RMI lookup code. If this flag is set, + // _is_a invocations are recorded at most once. This is useful for + // when we actually want to record interception on the _is_a "special op". + static boolean dontIgnoreIsA = false; + + + // Records the method invocation order + public static String methodOrder = ""; + + private static int invokeCount = 0; + + public SampleServerRequestInterceptor( String name ) { + this.name = name; + } + + public String name() { + return name; + } + + public void destroy() { + } + + public void receive_request_service_contexts( ServerRequestInfo ri ) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( ri.operation().equals( "syncWithServer" ) ) return; + if( !dontIgnoreIsA && ri.operation().equals( "_is_a" ) ) { + if( name.equals( "1" ) ) { + System.out.println( + " - Interceptor: Ingoring _is_a call..." ); + } + return; + } + if( !enabled ) return; + if( !receiveRequestServiceContextsEnabled ) return; + if( !name.equals( "2" ) ) return; + + intercepted = true; + strategy.receive_request_service_contexts( this, ri ); + } + + public void receive_request (ServerRequestInfo ri) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( ri.operation().equals( "syncWithServer" ) ) return; + if( !dontIgnoreIsA && ri.operation().equals( "_is_a" ) ) return; + if( !enabled ) return; + if( !receiveRequestEnabled ) return; + if( !name.equals( "2" ) ) return; + + strategy.receive_request( this, ri ); + } + + public void send_reply (ServerRequestInfo ri) { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( ri.operation().equals( "syncWithServer" ) ) return; + if( !dontIgnoreIsA && ri.operation().equals( "_is_a" ) ) return; + if( !enabled ) return; + if( !sendReplyEnabled ) return; + if( !name.equals( "2" ) ) return; + + strategy.send_reply( this, ri ); + } + + public void send_exception (ServerRequestInfo ri) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( ri.operation().equals( "syncWithServer" ) ) return; + if( !dontIgnoreIsA && ri.operation().equals( "_is_a" ) ) return; + if( !enabled ) return; + if( !sendExceptionEnabled ) return; + if( exceptionRedirectToOther && name.equals( "3" ) ) { + exceptionRedirectToOther = false; + throw new ForwardRequest( TestInitializer.helloRefForward ); + } + if( !name.equals( "2" ) ) return; + + strategy.send_exception( this, ri ); + } + + public void send_other (ServerRequestInfo ri) + throws ForwardRequest + { + // Only execute if the interceptor is enabled, this interception + // point is enabled, we are the second interceptor, and we are + // executing on hello, not helloForward. + if( ri.operation().equals( "syncWithServer" ) ) return; + if( !dontIgnoreIsA && ri.operation().equals( "_is_a" ) ) return; + if( !enabled ) return; + if( !sendOtherEnabled ) return; + if( !name.equals( "2" ) ) return; + + strategy.send_other( this, ri ); + + // Make sure we do not invoke any more strategy methods. + // This will effectively ignore invoking interceptors on forwards. + if( !invokeOnForwardedObject ) { + enabled = false; + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/ServerCommon.java b/functional-tests/src/test/java/pi/serverrequestinfo/ServerCommon.java new file mode 100644 index 000000000..920d26c7c --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/ServerCommon.java @@ -0,0 +1,358 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.framework.InternalProcess; +import java.io.PrintStream; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; + +/** + * This test works similar to the way the serverinterceptor test works. + * The server controls the client by waitinf for a syncWithServer call + * and then returns the name of the method to invoke. The method is invoked + * and on the next syncWithServer() call, the results are checked. + * + * Client Server + * | | + * [ ] syncWithServer() | + * [ ]------------------------>[ ] rs1 rs2 rs3 rr1 rr2 rr3 + * [ ] [ ] + * [ ] "sayHello" [ ] // order cleared here + * [ ]<------------------------[ ] sr3 sr2 sr1 + * [ ] | + * [ ] sayHello() | // + * [ ]------------------------>[ ] rs1 rs2 rs3 rr1 rr2 rr3 + * [ ] [ ] + * [ ] "hello there" [ ] + * [ ]<------------------------[ ] sr3 sr2 sr1 + * [ ] | // + * [ ] syncWithServer() | + * [ ]------------------------>[ ] rs1 rs2 rs3 rr1 rr2 rr3 + * [ ] [ ] + * [ ] [ ] // check order here + * [ ] [ ] // next test begins soon after. + * ... ... + */ +public abstract class ServerCommon + implements InternalProcess +{ + // Set from run() + com.sun.corba.ee.spi.orb.ORB orb; + + // Set from run() + PrintStream out; + + // Set from run() + PrintStream err; + + // Strategy for current run + InterceptorStrategy interceptorStrategy; + + // Strategy for current run + InvokeStrategy invokeStrategy; + + // True if the client is currently waiting for syncWithServer to return + // or false otherwise. + static boolean syncing = false; + + // The name of the next method to invoke: + static String nextMethodToInvoke; + + // An object for syncWithServer to wait on before returning to the client. + static final Integer syncObject = new Integer( 0 ); + + // Constant string to indicate to the client that we are done. + static final String EXIT_METHOD = "exit"; + + // Set to true by syncWithServer if the last invocation resulted in + // an exception on the client side. + static boolean exceptionRaised; + + // The currently executing server. + static ServerCommon server; + + private JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + + protected void finish() { + helper.done() ; + } + + /** + * Creates a com.sun.corba.ee.spi.orb.ORB and notifies the TestInitializer of its presence + */ + void createORB( String[] args, Properties props ) { + // create and initialize the ORB with initializer + String testInitializer = "pi.serverrequestinfo.TestInitializer"; + props.put( "org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + testInitializer, "" ); + this.orb = (com.sun.corba.ee.spi.orb.ORB)ORB.init(args, props); + TestInitializer.orb = this.orb; + } + + /** + * Perform common ServerRequestInfo tests + */ + void testServerRequestInfo() throws Exception { + out.println(); + out.println( "Running common ServerRequestInfo tests" ); + out.println( "======================================" ); + + ServerCommon.server = this; + waitForClient(); + + // Run tests: + testRequestId(); + testAttributesValid(); + testOneWay(); + testForwardReference(); + testServiceContext(); + testException(); + testRequestInfoStack(); + } + + /** + * Invoke the method with the given name on the object + */ + protected void invokeMethod( String methodName ) + throws Exception + { + // We are already synchronized with the client. + + // Prepare for the call: + nextMethodToInvoke = methodName; + SampleServerRequestInterceptor.methodOrder = ""; + + // Return from syncWithServer() and let the client make the call: + synchronized( syncObject ) { + syncObject.notify(); + } + + // If this is a oneway call, wait an extra second to make sure + // everything went through okay. + if( methodName.equals( "sayOneway" ) ) { + out.println( " - Delaying for oneway..." ); + try { + Thread.sleep( 1000 ); + } + catch( InterruptedException e ) { + } + out.println( " - This should be long enough." ); + } + + // Wait for client to synchronize with server again. Now we know + // for sure that the method invocation is complete. Even if the + // call was a oneway, we can be fairly certain the call has completed + // since we delay for 0.5 seconds before exiting waitForClient() + // which should be enough time in most cases. + waitForClient(); + } + + /** + * Waits for the client to sync with the server + */ + void waitForClient() { + out.println( " - Waiting for client..." ); + while( !syncing ) { + try { + Thread.sleep( 100 ); + } + catch( InterruptedException e ) { + } + } + + // Leave enough time for the method and interceptors to finish + // invoking so we can clear the invocation history: + try { + Thread.sleep( 500 ); + } + catch( InterruptedException e ) { + } + out.println( " - Synchronized with client." ); + } + + /** + * Notifies the client it is time to exit + */ + void exitClient() { + out.println( "+ Notifying client it's time to exit..." ); + nextMethodToInvoke = EXIT_METHOD; + synchronized( syncObject ) { + syncObject.notify(); + } + } + + /** + * Prepares for a test invocation by setting the interceptor strategy + * and the invocation and forward objects. + */ + protected void setParameters( InterceptorStrategy interceptorStrategy, + InvokeStrategy invokeStrategy ) + { + out.println( " - Using interceptor strategy " + + interceptorStrategy.getClass().getName() ); + out.println( " - Using invocation strategy " + + invokeStrategy.getClass().getName() ); + this.interceptorStrategy = interceptorStrategy; + this.invokeStrategy = invokeStrategy; + } + + /** + * Executes the test case set up with the parameters in setParameters + */ + protected void runTestCase( String testName ) + throws Exception + { + helper.start( testName ) ; + + try { + out.println( " - Executing test " + testName + "." ); + SampleServerRequestInterceptor.strategy = interceptorStrategy; + SampleServerRequestInterceptor.intercepted = false; + invokeStrategy.invoke(); + if( interceptorStrategy.failed ) { + throw new RuntimeException( interceptorStrategy.failReason ); + } + if( !SampleServerRequestInterceptor.intercepted ) { + throw new RuntimeException( "No interceptors were invoked!" ); + } + + helper.pass() ; + } catch (Exception exc) { + helper.fail( exc ) ; + } + } + + /* + ********************************************************************* + * Test assertions + *********************************************************************/ + + /** + * Tests request_id(). + */ + protected void testRequestId() + throws Exception + { + out.println( "+ Testing request_id()..." ); + + // Test request_id is same for request as for reply: + InterceptorStrategy interceptorStrategy = new RequestId1Strategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "request_id" ); + } + + /** + * Overridden by subclasses. Calls testAttributesValid( String, String ) + * passing in a valid and invalid repository id for the technology type + * being used. + */ + protected abstract void testAttributesValid() + throws Exception; + + /** + * Tests various attributes are valid. Attributes tested: + * operation(), sync_scope(), reply_status() + */ + protected void testAttributesValid( String validRepId, String invalidRepId) + throws Exception + { + out.println( "+ Testing for valid attributes..." ); + + InterceptorStrategy interceptorStrategy = + new AttributesValidStrategy( validRepId, invalidRepId ); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "attributes_valid" ); + } + + /** + * Tests response_expected() by invoking a oneWay method + */ + protected void testOneWay() + throws Exception + { + out.println( "+ Testing response_expected() with one way..." ); + + InterceptorStrategy interceptorStrategy = new OneWayStrategy(); + InvokeStrategy invokeStrategy = new InvokeOneWay(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "response_expected" ); + } + + /** + * Tests forward_reference() + */ + protected void testForwardReference() + throws Exception + { + out.println( "+ Testing forward_reference()..." ); + + InterceptorStrategy interceptorStrategy = + new ForwardReferenceStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAllForward(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "forward_reference" ); + } + + /** + * Tests get_request_service_context(), get_reply_service_context(). + * and add_reply_service_context(). + */ + protected void testServiceContext() + throws Exception + { + out.println( "+ Testing {get|add}_*_service_context()..." ); + + InterceptorStrategy interceptorStrategy = + new ServiceContextStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "{get|add}_*_service_context" ); + } + + /** + * Tests sending_exception() + */ + protected void testException() + throws Exception + { + out.println( "+ Testing sending_exception()..." ); + + InterceptorStrategy interceptorStrategy = + new ExceptionStrategy(); + InvokeStrategy invokeStrategy = new InvokeExceptions(); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "sending_exception" ); + } + + /** + * Tests that, if we make a co-located orb-mediated call from within a + * servant, the info stack is exercised. + */ + protected void testRequestInfoStack() + throws Exception + { + out.println( "+ Testing request info stack..." ); + + InterceptorStrategy interceptorStrategy = + new RequestInfoStackStrategy(); + InvokeStrategy invokeStrategy = new InvokeVisitAll( "sayInvokeAgain."); + setParameters( interceptorStrategy, invokeStrategy ); + runTestCase( "request_info_stack" ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/ServerRequestInfoTest.java b/functional-tests/src/test/java/pi/serverrequestinfo/ServerRequestInfoTest.java new file mode 100644 index 000000000..44e7b8b83 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/ServerRequestInfoTest.java @@ -0,0 +1,363 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import corba.framework.*; +import java.util.*; + +/** + * Tests ServerRequestInfo as per Portable Interceptors spec + * orbos/99-12-02, section 5.4. See pi/assertions.html for Assertions + * covered in this test. + */ +public class ServerRequestInfoTest + extends CORBATest +{ + public static String[] idlFiles = { "serverrequestinfo.idl" }; + + // Set to true if at least one test fails. + private boolean failed = false; + + Controller orbd; + + /* + public static String[] javaFiles = { + "ClientCommon.java", + "ServerCommon.java", + "POAClient.java", + "POAServer.java", + "POALocalClient.java", + "POALocalServer.java", + "DSIPOALocalServer.java", + "POARemoteClient.java", + "POARemoteServer.java", + "DSIPOARemoteServer.java", + "RMIClient.java", + "RMIServer.java", + "DSIRMIClient.java", + "DSIRMIServer.java", + "RMILocalClient.java", + "DSIRMILocalClient.java", + "RMILocalServer.java", + "DSIRMILocalServer.java", + "RMIRemoteClient.java", + "DSIRMIRemoteClient.java", + "RMIRemoteServer.java", + "DSIRMIRemoteServer.java", + "TestInitializer.java", + "SampleServerRequestInterceptor.java", + "DSIImpl.java", + "helloDelegate.java", + "helloIF.java", + "helloServant.java", + "helloDSIServant.java", + "helloDSIDeprecatedServant.java", + "helloRMIIIOP.java", + "PolicyFactoryHundred.java", + "PolicyHundred.java", + + // Interception strategies: + "InterceptorStrategy.java", + "RequestId1Strategy.java", + "AttributesValidStrategy.java", + "AdapterIdStrategy.java", + "OneWayStrategy.java", + "ForwardReferenceStrategy.java", + "ServiceContextStrategy.java", + "ExceptionStrategy.java", + "RequestInfoStackStrategy.java", + "GetServerPolicyStrategy.java", + + // Invocation strategies: + "InvokeStrategy.java", + "InvokeVisitAll.java", + "InvokeExceptions.java", + "InvokeOneWay.java", + "InvokeVisitAllForward.java" + }; + + public static String[] rmicClasses = { + "pi.serverrequestinfo.helloRMIIIOP" + }; + */ + + protected void doTest() + throws Throwable + { + /* + Options.addIDLCompilerArgs( "-fall" ); + Options.setJavaFiles(javaFiles); + Options.setIDLFiles(idlFiles); + Options.addRMICArgs( "-nolocalstubs -iiop -keep -g" ); + Options.setRMICClasses( rmicClasses ); + + compileIDLFiles(); + compileRMICFiles(); + compileJavaFiles(); + */ + + startORBD(); + System.out.println(); + System.out.println( " \t\t\t\tLocal\t\tRemote" ); + + beginTest( "[POA]\t\t\t" ); + testPOALocal(); + endTest( "\t\t" ); + testPOARemote(); + endTest( "\n" ); + + beginTest( "[POA DSI]\t\t\t" ); + testPOADSILocal(); + endTest( "\t\t" ); + testPOADSIRemote(); + endTest( "\n" ); + + beginTest( "[RMI]\t\t\t" ); + testRMILocal(); + endTest( "\t\t" ); + testRMIRemote(); + endTest( "\n" ); + + beginTest( "[ServerRequestDispatcher DSI]\t" ); + testServerRequestDispatcherDSILocal(); + endTest( "\t\t" ); + testServerRequestDispatcherDSIRemote(); + endTest( "\n" ); + stopORBD(); + + System.out.println(); + System.out.print( " Final Result: " ); + if( failed ) { + throw new RuntimeException( "Errors detected" ); + } + } + + private void testPOALocal() + throws Throwable + { + Controller server; + + try { + + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverrequestinfo.POALocalServer", + "poalocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testPOARemote() + throws Throwable + { + Controller client, server; + + try { + + server = createServer( "pi.serverrequestinfo.POARemoteServer", + "poa-server" ); + server.start(); + client = createClient( "pi.serverrequestinfo.POARemoteClient", + "poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testPOADSILocal() + throws Throwable + { + Controller server; + + try { + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverrequestinfo.DSIPOALocalServer", + "dsipoalocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testPOADSIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.serverrequestinfo.DSIPOARemoteServer", + "dsi-poa-server" ); + server.start(); + client = createClient( "pi.serverrequestinfo.POARemoteClient", + "dsi-poa-client" ); + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testRMILocal() + throws Throwable + { + Controller server; + + try { + + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverrequestinfo.RMILocalServer", + "rmilocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + private void testRMIRemote() + throws Throwable + { + Controller client, server; + + try { + server = createServer( "pi.serverrequestinfo.RMIRemoteServer", + "rmi-server" ); + server.start(); + client = createClient( "pi.serverrequestinfo.RMIRemoteClient", + "rmi-client" ); + + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void testServerRequestDispatcherDSILocal() + throws Throwable + { + Controller server; + + try { + + // Start only a server - the server will create the client in this + // test. Create it as a client so no handshake is tested for. + server = createClient( "pi.serverrequestinfo.DSIRMILocalServer", + "dsirmilocal" ); + server.start(); + server.waitFor(); + printEndTest( server, null ); + server.stop(); + } + finally { + } + } + + + private void testServerRequestDispatcherDSIRemote() + throws Throwable + { + Controller client, server; + + try { + + server = createServer( "pi.serverrequestinfo.DSIRMIRemoteServer", + "dsi-rmi-server" ); + server.start(); + client = createClient( "pi.serverrequestinfo.DSIRMIRemoteClient", + "dsi-rmi-client" ); + + client.start(); + client.waitFor(); + printEndTest( client, server ); + client.stop(); + server.stop(); + } + finally { + } + } + + private void beginTest( String name ) + throws Exception + { + System.out.print( " " + name ); + } + + private void endTest( String terminator ) + throws Exception + { + System.out.print( terminator ); + } + + private void printEndTest( Controller client, Controller server ) + throws Throwable + { + if( (server != null) && server.finished() ) { + System.out.print( "FAILED, Server crashed" ); + failed = true; + } + else if( client.exitValue() != Controller.SUCCESS ) { + System.out.print( "FAILED, Client exit value = " + + client.exitValue() ); + failed = true; + } + else { + System.out.print( "PASSED" ); + } + } + private void startORBD() + throws Exception + { + orbd = createORBD(); + orbd.start(); + } + + private void stopORBD() + throws Exception + { + orbd.stop(); + pause(); + } + + // Pause a little to allow all processes to fully terminate. + private void pause() { + try { + Thread.sleep( 2000 ); + } + catch( InterruptedException e ) { + // ignore. + } + } +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/ServiceContextStrategy.java b/functional-tests/src/test/java/pi/serverrequestinfo/ServiceContextStrategy.java new file mode 100644 index 000000000..bc24ec35c --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/ServiceContextStrategy.java @@ -0,0 +1,360 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import com.sun.corba.ee.impl.interceptors.*; +import org.omg.PortableInterceptor.*; +import org.omg.IOP.*; +import com.sun.corba.ee.spi.servicecontext.ORBVersionServiceContext; +import org.omg.CORBA.*; +import java.util.*; + +/** + * Strategy to test get_request_service_context and get_reply_service_context. + *

+ * Both get_request_service_context and get_reply_service_context will be + * tried for each interception point. + */ +public class ServiceContextStrategy + extends InterceptorStrategy +{ + // Service context ID that is known to be invalid. + private final static int INVALID_ID = 1234; + + // Fake ids and data: + private final static int FAKEID1 = 2123; + private final static int FAKEID_RRSC = 2126; + private final static int FAKEID_RR = 2127; + + private final static byte[] FAKEDATA1 = { + (byte)1, (byte)2, (byte)3, (byte)4 }; + private final static byte[] FAKEDATA2 = { + (byte)5, (byte)6, (byte)7 }; + private final static byte[] FAKEDATA3 = { + (byte)8 }; + private final static byte[] FAKEDATA4 = { + (byte)2 }; + private final static byte[] FAKEDATA_RRSC = { + (byte)1, (byte)8, (byte)2 }; + private final static byte[] FAKEDATA_RR = { + (byte)9, (byte)8, (byte)9 }; + + + public void receive_request_service_contexts ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.receive_request_service_contexts( interceptor, ri ); + + try { + testGetRequestSC( "rrsc", ri ); + //testGetReplySC( "rrsc", ri ); + testAddReplySC( "rrsc", ri ); + } + catch( Exception e ) { + failException( "rrsc", e ); + } + } + + public void receive_request ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.receive_request( interceptor, ri ); + + try { + testGetRequestSC( "receive_request", ri ); + //testGetReplySC( "receive_request", ri ); + testAddReplySC( "receive_request", ri ); + } + catch( Exception e ) { + failException( "receive_request", e ); + } + } + + public void send_reply ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + { + super.send_reply( interceptor, ri ); + + try { + testGetRequestSC( "send_reply", ri ); + //testGetReplySC( "send_reply", ri ); + testAddReplySC( "send_reply", ri ); + } + catch( Exception e ) { + failException( "send_reply", e ); + } + } + + public void send_exception ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_exception( interceptor, ri ); + + try { + testGetRequestSC( "send_exception", ri ); + //testGetReplySC( "send_exception", ri ); + testAddReplySC( "send_exception", ri ); + } + catch( Exception e ) { + failException( "send_exception", e ); + } + } + + public void send_other ( + SampleServerRequestInterceptor interceptor, ServerRequestInfo ri) + throws ForwardRequest + { + super.send_other( interceptor, ri ); + + try { + testGetRequestSC( "send_other", ri ); + //testGetReplySC( "send_other", ri ); + testAddReplySC( "send_other", ri ); + } + catch( Exception e ) { + failException( "send_other", e ); + } + } + + private void testGetRequestSC( String methodName, ServerRequestInfo ri ) { + // Test to ensure valid and invalid IDs work properly: + testSC( "request", methodName, ri ); + } + + private void testGetReplySC( String methodName, ServerRequestInfo ri ) { + if( methodName.equals( "rrsc" ) || + methodName.equals( "receive_request" ) ) + { + // get_reply_service_context is invalid here. + try { + ri.get_reply_service_context( 0 ); + fail( methodName + "(): get_reply_service_context() " + + "did not raise BAD_INV_ORDER." ); + } + catch( BAD_INV_ORDER e ) { + log( methodName + "(): get_reply_service_context() " + + "raised BAD_INV_ORDER (ok)" ); + } + } + else { + // Test to ensure valid and invalid IDs work properly: + testSC( "reply", methodName, ri ); + } + } + + private void testSC( String reqOrRep, String methodName, + ServerRequestInfo ri ) + { + String header = methodName + "(): get_" + reqOrRep + + "_service_context"; + + // Test to ensure an invalid ID raises a BAD_PARAM: + try { + if( reqOrRep.equals( "request" ) ) { + ri.get_request_service_context( INVALID_ID ); + } + else { + ri.get_reply_service_context( INVALID_ID ); + } + fail( header + "( INVALID_ID ) did not raise BAD_PARAM." ); + } + catch( BAD_PARAM e ) { + log( header + "( INVALID_ID ) raised BAD_PARAM (ok)" ); + } + + // Test to ensure valid ID works properly: + int id; + if( reqOrRep.equals( "request" ) ) { + id = ORBVersionServiceContext.SERVICE_CONTEXT_ID; + } + else { + // _REVISIT_ What do we do here? + id = 6; + } + + try { + ServiceContext sc; + if( reqOrRep.equals( "request" ) ) { + sc = ri.get_request_service_context( id ); + } + else { + sc = ri.get_reply_service_context( id ); + } + + log( header + "( " + id + " ) exists (ok)." ); + + // Commenting out "copy" test due to "good citizen" assumption. + /* + // Ensure this is a copy and not the real thing: + byte altered = ++sc.context_data[0]; + + if( reqOrRep.equals( "request" ) ) { + sc = ri.get_request_service_context( id ); + } + else { + sc = ri.get_reply_service_context( id ); + } + + if( sc.context_data[0] == altered ) { + fail( header + "( " + id + " ) is not a copy. " + + "It is the original!" ); + } + else { + log( header + "( " + id + " ) is a copy, " + + "not the original (ok)" ); + } + */ + } + catch( BAD_PARAM e ) { + fail( header + "( " + id + " ) raised BAD_PARAM" ); + } + } + + private void testAddReplySC( String methodName, ServerRequestInfo ri ) { + String header = methodName + "(): "; + + // For RRSC: Add FAKEID_RRSC, FAKE_DATA_RRSC + // For RR: Add FAKEID_RR, FAKE_DATA1 + // Replace FAKEID_RR, FAKE_DATA_RR, true + // Replace FAKEID_RR, FAKE_DATA2, false + // else: Check FAKEID_RRSC, FAKE_DATA_RRSC + // Check FAKEID_RR, FAKE_DATA_RR + // Add FAKEID1, FAKE_DATA3 + // Replace FAKEID1, FAKE_DATA4, true + // Check FAKEID1, FAKE_DATA4 + // Replace FAKEID1, FAKE_DATA3, false + // Check FAKEID1, FAKE_DATA4 + + if( methodName.equals( "rrsc" ) ) { + try { + // Add FAKEID_RRSC, FAKE_DATA_RRSC + ServiceContext sc = new ServiceContext( FAKEID_RRSC, + FAKEDATA_RRSC ); + ri.add_reply_service_context( sc, true ); + log( header + "added service context RRSC." ); + } + catch( BAD_INV_ORDER e ) { + fail( header + + "denied access to add_reply_service_context." ); + } + } + else if( methodName.equals( "receive_request" ) ) { + try { + // Add FAKEID_RR, FAKE_DATA1 + ServiceContext sc = new ServiceContext( FAKEID_RR, + FAKEDATA1 ); + ri.add_reply_service_context( sc, true ); + log( header + "added service context RR." ); + + // Replace FAKEID_RR, FAKE_DATA_RR, true + try { + sc = new ServiceContext( FAKEID_RR, FAKEDATA_RR ); + ri.add_reply_service_context( sc, true ); + log( header + "was able to replace context with " + + "replace=true." ); + } + catch( BAD_INV_ORDER e ) { + fail( header + "was not able to replace context with " + + "replace=true." ); + } + + // Replace FAKEID_RR, FAKE_DATA2, false + try { + sc = new ServiceContext( FAKEID_RR, FAKEDATA2 ); + ri.add_reply_service_context( sc, false ); + fail( header + "was able to replace context with " + + "replace=false." ); + } + catch( BAD_INV_ORDER e ) { + log( header + "was not able to replace context with " + + "replace=false." ); + + } + } + catch( BAD_INV_ORDER e ) { + fail( header + + "denied access to add_reply_service_context." ); + } + } + else { + + // Check FAKEID_RRSC, FAKE_DATA_RRSC + ServiceContext sc = ri.get_reply_service_context( FAKEID_RRSC ); + if( Arrays.equals( sc.context_data, FAKEDATA_RRSC ) ) { + log( header + "service context data for rrsc is valid." ); + } + else { + fail( header + "service context data for rrsc is invalid." ); + } + + // Check FAKEID_RR, FAKE_DATA_RR + sc = ri.get_reply_service_context( FAKEID_RR ); + if( Arrays.equals( sc.context_data, FAKEDATA_RR ) ) { + log( header + "service context data for rr is valid." ); + } + else { + fail( header + "service context data for rr is invalid." ); + } + + // Add FAKEID1, FAKE_DATA3 + sc = new ServiceContext( FAKEID1, + FAKEDATA3 ); + ri.add_reply_service_context( sc, true ); + log( header + "added service context 1." ); + + // Replace FAKEID1, FAKE_DATA4, true + try { + sc = new ServiceContext( FAKEID1, FAKEDATA4 ); + ri.add_reply_service_context( sc, true ); + log( header + "was able to replace context with " + + "replace=true." ); + } + catch( BAD_INV_ORDER e ) { + fail( header + "was not able to replace context with " + + "replace=true." ); + } + + // Check FAKEID1, FAKE_DATA4 + sc = ri.get_reply_service_context( FAKEID1 ); + if( Arrays.equals( sc.context_data, FAKEDATA4 ) ) { + log( header + "service context data for 1 is valid." ); + } + else { + fail( header + "service context data for 1 is invalid." ); + } + + // Replace FAKEID1, FAKE_DATA3, false + try { + sc = new ServiceContext( FAKEID1, FAKEDATA3 ); + ri.add_reply_service_context( sc, false ); + fail( header + "was able to replace context with " + + "replace=false." ); + } + catch( BAD_INV_ORDER e ) { + log( header + "was not able to replace context with " + + "replace=false (ok)." ); + } + + // Check FAKEID1, FAKE_DATA4 + sc = ri.get_reply_service_context( FAKEID1 ); + if( Arrays.equals( sc.context_data, FAKEDATA4 ) ) { + log( header + "service context data for 1 is valid." ); + } + else { + fail( header + "service context data for 1 is invalid." ); + } + + } + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/TestInitializer.java b/functional-tests/src/test/java/pi/serverrequestinfo/TestInitializer.java new file mode 100644 index 000000000..db60c24d6 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/TestInitializer.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +import ServerRequestInfo.*; // hello interface + +/** + * Registers the necessary Server Interceptors to test + * ServerRequestInfo. + */ +public class TestInitializer + extends org.omg.CORBA.LocalObject + implements ORBInitializer +{ + + // The PrintStream to pass to the ServerRequestInfo for output. + // This is set from the server statically. + static PrintStream out; + + /** The ORB to pass to the ServerRequestInfo */ + static ORB orb; + + // Where to send normal requests + static org.omg.CORBA.Object helloRef; + + // Where to forward the caller on a ForwardRequest + static org.omg.CORBA.Object helloRefForward; + + /** + * Creates a TestInitializer + */ + public TestInitializer() { + } + + /** + * Called before all references are registered + */ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + } + + /** + * Called after all references are registered + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + ServerRequestInterceptor interceptor1; + ServerRequestInterceptor interceptor2; + ServerRequestInterceptor interceptor3; + + interceptor1 = new SampleServerRequestInterceptor( "1" ); + interceptor2 = new SampleServerRequestInterceptor( "2" ); + interceptor3 = new SampleServerRequestInterceptor( "3" ); + + try { + out.println( " - post_init: adding 3 server interceptors..." ); + info.add_server_request_interceptor( interceptor1 ); + info.add_server_request_interceptor( interceptor2 ); + info.add_server_request_interceptor( interceptor3 ); + } + catch( DuplicateName e ) { + out.println( " - post_init: received DuplicateName!" ); + } + + out.println( " - post_init: registering PolicyFactory for 100..." ); + PolicyFactory policyFactory100 = new PolicyFactoryHundred(); + info.register_policy_factory( 100, policyFactory100 ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/helloDSIDeprecatedServant.java b/functional-tests/src/test/java/pi/serverrequestinfo/helloDSIDeprecatedServant.java new file mode 100644 index 000000000..435dfe781 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/helloDSIDeprecatedServant.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.PortableInterceptor.*; +import org.omg.PortableServer.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * Servant implementation. + */ +class helloDSIDeprecatedServant + extends org.omg.CORBA.DynamicImplementation +{ + // The object to delegate to + DSIImpl impl; + + public static String[] __ids = { "IDL:ServerRequestInfo/hello:1.0" }; + + public String[] _ids() { + return __ids; + } + + public helloDSIDeprecatedServant( ORB orb, PrintStream out, String symbol, + helloDelegate.ClientCallback clientCallback ) + { + impl = new DSIImpl( orb, out, symbol, clientCallback ); + } + + public void invoke( ServerRequest r ) { + impl.invoke( r ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/helloDSIServant.java b/functional-tests/src/test/java/pi/serverrequestinfo/helloDSIServant.java new file mode 100644 index 000000000..ddc714f18 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/helloDSIServant.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; +import org.omg.PortableInterceptor.*; +import org.omg.PortableServer.*; + +import java.util.*; +import java.io.*; + +import ServerRequestInfo.*; + +/** + * Servant implementation. + */ +class helloDSIServant extends org.omg.PortableServer.DynamicImplementation { + // The object to delegate to + DSIImpl impl; + + public static String[] __ids = { "IDL:ServerRequestInfo/hello:1.0" }; + + public String[] _all_interfaces( POA poa, byte[] oid ) { + return __ids; + } + + public helloDSIServant( ORB orb, PrintStream out, String symbol, + helloDelegate.ClientCallback clientCallback ) + { + impl = new DSIImpl( orb, out, symbol, clientCallback ); + } + + public void invoke( ServerRequest r ) { + impl.invoke( r ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/helloDelegate.java b/functional-tests/src/test/java/pi/serverrequestinfo/helloDelegate.java new file mode 100644 index 000000000..91b684f63 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/helloDelegate.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; + +import java.util.*; +import java.io.*; +import org.omg.PortableInterceptor.*; + +import ServerRequestInfo.*; + +/** + * Servant implementation. + */ +class helloDelegate implements helloIF { + private PrintStream out = null; + + // The symbol to append to SampleServerRequestInterceptor.methodOrder + // every time a relevant method is called on this object. + String symbol; + + // A callback back to the server so that we can cause this Servant to + // become a client. This is used to test the request info stack. When + // the Server creates this delegate, it passes a reference to an + // object implementing ClientCallback. This object will look up a + // reference to this same servant and make the appropriate invocation. + ClientCallback clientCallback; + + // See above comment for clientCallback. + public static interface ClientCallback { + public String sayHello(); + public void saySystemException(); + } + + public helloDelegate( PrintStream out, String symbol, + ClientCallback callback ) + { + super(); + this.out = out; + this.symbol = symbol; + this.clientCallback = callback; + } + + public String sayHello() { + out.println( " - helloDelegate: sayHello() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + return "Hello, world!"; + } + + public void sayOneway() { + out.println( " - helloDelegate: sayOneway() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + } + + public void saySystemException() { + out.println( " - helloDelegate: saySystemException() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + throw new IMP_LIMIT( SampleServerRequestInterceptor.VALID_MESSAGE ); + } + + public void sayUserException() + throws ExampleException + { + out.println( " - helloDelegate: sayUserException() invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + throw new ExampleException( "valid" ); + } + + // Client code calls this to synchronize with server. This call + // blocks until the server is ready for the next invocation. + // It then returns a String containing the name of the method to + // invoke on (either "sayHello" or "saySystemException"). + // If the string "exit" is returned, the Client's + // work is done and it may exit. + // + // @param exceptionRaised true if the last invocation resulted in + // an exception on the client side. + public String syncWithServer( boolean exceptionRaised ) { + out.println( " - helloDelegate: syncWithServer() invoked" ); + // Notify the test case that the client is waiting for + // syncWithServer to return: + ServerCommon.syncing = true; + ServerCommon.exceptionRaised = exceptionRaised; + + // Wait for the next test case to start: + synchronized( ServerCommon.syncObject ) { + try { + ServerCommon.syncObject.wait(); + } + catch( InterruptedException e ) { + // ignore, assume we are good to go. + } + } + + ServerCommon.syncing = false; + + return ServerCommon.nextMethodToInvoke; + } + + /** + * If n is 0, sayHello is invoked. + * If n is 1, saySystemException is invoked. + */ + public void sayInvokeAgain( int n ) { + out.println( " - helloDelegate: sayInvokeAgain( " + n + + " ) invoked" ); + SampleServerRequestInterceptor.methodOrder += symbol; + + switch( n ) { + case INVOKE_SAY_HELLO.value: + out.println( " - helloDelegate: invoking sayHello..." ); + clientCallback.sayHello(); + break; + case INVOKE_SAY_SYSTEM_EXCEPTION.value: + out.println( + " - helloDelegate: invoking saySystemException..." ); + clientCallback.saySystemException(); + break; + } + + out.println( " - helloDelegate: sayInvokeAgain( " + n + + " ) returning..." ); + } + +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/helloIF.java b/functional-tests/src/test/java/pi/serverrequestinfo/helloIF.java new file mode 100644 index 000000000..8f66308b2 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/helloIF.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import org.omg.PortableInterceptor.*; +import ServerRequestInfo.*; + +/** + * Hello interface for RMI-IIOP version of test + */ +public interface helloIF + extends Remote +{ + String sayHello () throws RemoteException; + void sayOneway () throws RemoteException; + void saySystemException () throws RemoteException; + void sayUserException () throws ExampleException, RemoteException; + String syncWithServer ( boolean exceptionRaised ) throws RemoteException; + void sayInvokeAgain ( int n ) throws RemoteException; +} + diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/helloRMIIIOP.java b/functional-tests/src/test/java/pi/serverrequestinfo/helloRMIIIOP.java new file mode 100644 index 000000000..06aef7def --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/helloRMIIIOP.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; + +import java.io.*; +import java.rmi.*; +import javax.rmi.*; +import javax.naming.*; +import org.omg.PortableInterceptor.*; + +import ServerRequestInfo.*; // hello interface + +/** + * RMI/IIOP implementation. + */ +public class helloRMIIIOP + extends PortableRemoteObject + implements helloIF +{ + // Contains the actual implementation of the hello interface. + private helloDelegate delegate = null; + + public helloRMIIIOP( PrintStream out, String symbol, + helloDelegate.ClientCallback clientCallback ) + throws RemoteException + { + super(); + this.delegate = new helloDelegate( out, symbol, clientCallback ); + } + + public String sayHello() { + return delegate.sayHello(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void saySystemException() { + delegate.saySystemException(); + } + + public void sayUserException() + throws ExampleException + { + delegate.sayUserException(); + } + + public String syncWithServer( boolean exceptionRaised ) { + return delegate.syncWithServer( exceptionRaised ); + } + + public void sayInvokeAgain( int n ) { + delegate.sayInvokeAgain( n ); + } + +} diff --git a/functional-tests/src/test/java/pi/serverrequestinfo/helloServant.java b/functional-tests/src/test/java/pi/serverrequestinfo/helloServant.java new file mode 100644 index 000000000..52fc07d44 --- /dev/null +++ b/functional-tests/src/test/java/pi/serverrequestinfo/helloServant.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serverrequestinfo; + +import org.omg.CORBA.*; + +import java.util.*; +import java.io.*; +import org.omg.PortableInterceptor.*; + +import ServerRequestInfo.*; + +/** + * Servant implementation. + */ +class helloServant extends helloPOA { + // The object to delegate all calls to: + helloDelegate delegate; + + public helloServant( PrintStream out, String symbol, + helloDelegate.ClientCallback clientCallback ) + { + super(); + this.delegate = new helloDelegate( out, symbol, clientCallback ); + } + + public String sayHello() { + return delegate.sayHello(); + } + + public void sayOneway() { + delegate.sayOneway(); + } + + public void saySystemException() { + delegate.saySystemException(); + } + + public void sayUserException() + throws ExampleException + { + delegate.sayUserException(); + } + + public String syncWithServer( boolean exceptionRaised ) { + return delegate.syncWithServer( exceptionRaised ); + } + + public void sayInvokeAgain( int n ) { + delegate.sayInvokeAgain( n ); + } + +} diff --git a/functional-tests/src/test/java/pi/serviceexample/AServiceIORInterceptor.java b/functional-tests/src/test/java/pi/serviceexample/AServiceIORInterceptor.java new file mode 100644 index 000000000..db473c348 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/AServiceIORInterceptor.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Sep 24 (Mon) 20:51:03 by Harold Carr. +// Last Modified : 2001 Oct 02 (Tue) 20:49:16 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.Any; +import org.omg.CORBA.LocalObject; +import org.omg.CORBA.ORB; +import org.omg.IOP.TaggedComponent; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.IORInterceptor; + +public class AServiceIORInterceptor + extends org.omg.CORBA.LocalObject + implements IORInterceptor +{ + private Codec codec; + + public AServiceIORInterceptor(Codec codec) + { + this.codec = codec; + } + + // + // Interceptor operations + // + + public String name() + { + return "AServiceInterceptor"; + } + + public void destroy() + { + } + + // + // IOR Interceptor operations + // + + public void establish_components(IORInfo info) + { + // + // Note: typically, rather than just inserting a tagged component + // this interceptor would check info.get_effective_policy(int) + // to determine if a tagged component reflecting that policy + // should be added to the IOR. That is not shown in this example. + // + + ASERVICE_COMPONENT aServiceComponent = new ASERVICE_COMPONENT(true); + Any any = ORB.init().create_any(); + ASERVICE_COMPONENTHelper.insert(any, aServiceComponent); + byte[] value = null; + try { + value = codec.encode_value(any); + } catch (InvalidTypeForEncoding e) { + System.out.println("Exception handling not shown."); + } + TaggedComponent taggedComponent = + new TaggedComponent(TAG_ASERVICE_COMPONENT.value, value); + info.add_ior_component(taggedComponent); + } + +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/AServiceImpl.java b/functional-tests/src/test/java/pi/serviceexample/AServiceImpl.java new file mode 100644 index 000000000..581280cfe --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/AServiceImpl.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 11:57:05 by Harold Carr. +// Last Modified : 2001 Sep 20 (Thu) 21:39:43 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.Any; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.LocalObject; +import org.omg.CORBA.ORB; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.InvalidSlot; + +class AServiceImpl + extends LocalObject + implements AService +{ + private int slotId; + + private int currentServiceId = 0; + + private Current piCurrent; + + private Any NOT_IN_EFFECT; + + public AServiceImpl(int slotId) + { + this.slotId = slotId; + NOT_IN_EFFECT = ORB.init().create_any(); + } + + // Package protected so the AService ORBInitializer can access this + // non-IDL defined method. + void setPICurrent(Current piCurrent) + { + this.piCurrent = piCurrent; + } + + public void begin() + { + Any any = ORB.init().create_any(); + any.insert_long(++currentServiceId); + setSlot(any); + } + + public void end() + { + setSlot(NOT_IN_EFFECT); + } + + public void verify() + { + try { + Any any = piCurrent.get_slot(slotId); + if (any.type().kind().equals(TCKind.tk_long)) { + System.out.println("Service present: " + any.extract_long()); + } else { + System.out.println("Service not present"); + } + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + } + + // Synchronized because two threads in the same ORB could be + // sharing this object. + synchronized private void setSlot(Any any) + { + try { + piCurrent.set_slot(slotId, any); + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/AServiceInterceptor.java b/functional-tests/src/test/java/pi/serviceexample/AServiceInterceptor.java new file mode 100644 index 000000000..3d7ad4572 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/AServiceInterceptor.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 19:46:30 by Harold Carr. +// Last Modified : 2001 Oct 02 (Tue) 20:41:23 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TCKind; +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.IOP.TaggedComponent; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; + +public class AServiceInterceptor + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor, ServerRequestInterceptor +{ + private int slotId; + private Codec codec; + + private static final int serviceContextId = 1234; + + public AServiceInterceptor(int slotId) + { + this.slotId = slotId; + } + + void setCodec(Codec codec) + { + this.codec = codec; + } + + // + // Interceptor operations + // + + public String name() + { + return "AServiceInterceptor"; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + // + // See if the target object contains an ASERVICE_COMPONENT. + // + + try { + TaggedComponent taggedComponent = + ri.get_effective_component(TAG_ASERVICE_COMPONENT.value); + + Any sAny = null; + try { + sAny = codec.decode_value(taggedComponent.component_data, + ASERVICE_COMPONENTHelper.type()); + } catch (TypeMismatch e) { + System.out.println("Exception handling not shown."); + } catch (FormatMismatch e) { + System.out.println("Exception handling not shown."); + } + + ASERVICE_COMPONENT aServiceComponent = + ASERVICE_COMPONENTHelper.extract(sAny); + + // + // Only send the service context if the target object requires it. + // + + if (aServiceComponent.requiresAService) { + try { + Any any = ri.get_slot(slotId); + if (any.type().kind().equals(TCKind.tk_long)) { + int serviceId = any.extract_long(); + byte[] serviceContextData = { + // Little endian to make it + // easier to see in debugger. + (byte)((serviceId >>> 0) & 0xFF), + (byte)((serviceId >>> 8) & 0xFF), + (byte)((serviceId >>> 16) & 0xFF), + (byte)((serviceId >>> 24) & 0xFF) + }; + ri.add_request_service_context( + new ServiceContext(serviceContextId, + serviceContextData), + false); + } + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + } + } catch (BAD_PARAM e) { + // If it is not present, do nothing. + ; + } + } + + public void send_poll(ClientRequestInfo ri) + { + } + + public void receive_reply(ClientRequestInfo ri) + { + } + + public void receive_exception(ClientRequestInfo ri) + { + } + + public void receive_other(ClientRequestInfo ri) + { + } + + // + // ServerRequestInterceptor operations + // + + public void receive_request_service_contexts(ServerRequestInfo ri) + { + try { + ServiceContext serviceContext = + ri.get_request_service_context(serviceContextId); + byte[] data = serviceContext.context_data; + int b1, b2, b3, b4; + b4 = (data[0] << 0) & 0x000000FF; + b3 = (data[1] << 8) & 0x0000FF00; + b2 = (data[2] << 16) & 0x00FF0000; + b1 = (data[3] << 24) & 0xFF000000; + int serviceId = (b1 | b2 | b3 | b4); + Any any = ORB.init().create_any(); + any.insert_long(serviceId); + ri.set_slot(slotId, any); + } catch (BAD_PARAM e) { + // Not present means service is not in effect. + // Do nothing. + ; + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + } + + public void receive_request(ServerRequestInfo ri) + { + } + + public void send_reply(ServerRequestInfo ri) + { + } + + public void send_exception(ServerRequestInfo ri) + { + } + + public void send_other(ServerRequestInfo ri) + { + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/AServiceORBInitializer.java b/functional-tests/src/test/java/pi/serviceexample/AServiceORBInitializer.java new file mode 100644 index 000000000..a814fd023 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/AServiceORBInitializer.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 20:32:27 by Harold Carr. +// Last Modified : 2001 Oct 02 (Tue) 20:33:57 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.Encoding; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.CurrentHelper; +import org.omg.PortableInterceptor.ORBInitInfo; + + +public class AServiceORBInitializer + extends org.omg.CORBA.LocalObject + implements org.omg.PortableInterceptor.ORBInitializer +{ + private AServiceImpl aServiceImpl; + private AServiceInterceptor aServiceInterceptor; + + public void pre_init(ORBInitInfo info) + { + try { + int id = info.allocate_slot_id(); + + aServiceInterceptor = new AServiceInterceptor(id); + + info.add_client_request_interceptor(aServiceInterceptor); + info.add_server_request_interceptor(aServiceInterceptor); + + // Create and register a reference to the service to be + // used by client code. + + aServiceImpl = new AServiceImpl(id); + + info.register_initial_reference("AService", aServiceImpl); + + } catch (Throwable t) { + System.out.println("Exception handling not shown."); + } + } + + public void post_init(ORBInitInfo info) + { + try { + + Current piCurrent = + CurrentHelper.narrow( + info.resolve_initial_references("PICurrent")); + aServiceImpl.setPICurrent(piCurrent); + + CodecFactory codecFactory = + CodecFactoryHelper.narrow( + info.resolve_initial_references("CodecFactory")); + Encoding encoding = new Encoding((short)0, (byte)1, (byte)2); + Codec codec = codecFactory.create_codec(encoding); + aServiceInterceptor.setCodec(codec); + + AServiceIORInterceptor aServiceIORInterceptor = + new AServiceIORInterceptor(codec); + info.add_ior_interceptor(aServiceIORInterceptor); + + } catch (Throwable t) { + System.out.println("Exception handling not shown."); + } + } + +} + +// End of file. diff --git a/functional-tests/src/test/java/pi/serviceexample/ArbitraryObjectImpl.java b/functional-tests/src/test/java/pi/serviceexample/ArbitraryObjectImpl.java new file mode 100644 index 000000000..ecc47f9ff --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/ArbitraryObjectImpl.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.serviceexample; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.PortableServer.POA; + +import java.util.Properties; + +class ArbitraryObjectImpl + extends ArbitraryObjectPOA +{ + public static ORB orb; + + private AService aService; + + // + // The IDL operations. + // + + public String arbitraryOperation1(String a1) + { + verifyService(); + return "I got this from the client: " + a1; + } + + public void arbitraryOperation2 (int a1) + { + verifyService(); + } + + public void arbitraryOperation3(String a1) + throws ArbitraryObjectException + { + verifyService(); + if (a1.equals("throw exception")) { + throw new ArbitraryObjectException("because you told me to"); + } + } + + private void verifyService() + { + getAService().verify(); + } + + private AService getAService() + { + // Only look up the service once, then cache it. + + if (aService == null) { + try { + aService = + AServiceHelper.narrow( + orb.resolve_initial_references("AService")); + } catch (InvalidName e) { + System.out.println("Exception handling not shown."); + } + } + return aService; + } + + // + // The server. + // + + public static void main(String[] av) + { + try { + if (orb == null) { + Properties props = new Properties(); + props.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "pi.serviceexample.AServiceORBInitializer", + ""); + props.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "pi.serviceexample.LoggingServiceServerORBInitializer", + ""); + orb = ORB.init(av, props); + } + + POA rootPOA = (POA) orb.resolve_initial_references("RootPOA"); + // Create a POA so the IOR interceptor executes. + POA childPOA = rootPOA.create_POA("childPOA", null, null); + childPOA.the_POAManager().activate(); + + byte[] objectId = + childPOA.activate_object(new ArbitraryObjectImpl()); + org.omg.CORBA.Object ref = childPOA.id_to_reference(objectId); + + NamingContext nameService = + NamingContextHelper.narrow( + orb.resolve_initial_references("NameService")); + NameComponent path[] = + { new NameComponent("ArbitraryObject", "") }; + nameService.rebind(path, ref); + + System.out.println("ArbitaryObject ready."); + + orb.run(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + System.exit(0); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/Client.java b/functional-tests/src/test/java/pi/serviceexample/Client.java new file mode 100644 index 000000000..20c1246f4 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/Client.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 15:24:44 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 19:50:01 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; + +import java.util.Properties; + +public class Client +{ + public static void main(String av[]) + { + try { + Properties props = new Properties(); + props.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "pi.serviceexample.AServiceORBInitializer", + ""); + props.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "pi.serviceexample.LoggingServiceClientORBInitializer", + ""); + ORB orb = ORB.init(av, props); + + // + // The client obtains a reference to a service. + // The client does not know the service is implemented + // using interceptors. + // + + AService aService = + AServiceHelper.narrow( + orb.resolve_initial_references("AService")); + + // + // The client obtains a reference to some object that + // it will invoke. + // + + NamingContext nameService = + NamingContextHelper.narrow( + orb.resolve_initial_references("NameService")); + NameComponent arbitraryObjectPath[] = + { new NameComponent("ArbitraryObject", "") }; + ArbitraryObject arbitraryObject = + ArbitraryObjectHelper.narrow(nameService.resolve(arbitraryObjectPath)); + + // + // The client begins the service so that invocations of + // any object will be done with that service in effect. + // + + aService.begin(); + + arbitraryObject.arbitraryOperation1("one"); + arbitraryObject.arbitraryOperation2(2); + + // + // The client ends the service so that further invocations + // of any object will not be done with that service in effect. + // + + aService.end(); + + // This invocation is not serviced by aService since + // it is outside the begin/end. + arbitraryObject.arbitraryOperation3("just return"); + + + aService.begin(); + try { + arbitraryObject.arbitraryOperation3("throw exception"); + throw new RuntimeException("should not see this"); + } catch (ArbitraryObjectException e) { + // Expected in this example, so do nothing. + } + aService.end(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + System.out.println("Client done."); + System.exit(0); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/ColocatedServers.java b/functional-tests/src/test/java/pi/serviceexample/ColocatedServers.java new file mode 100644 index 000000000..c8be640f3 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/ColocatedServers.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Jun 29 (Thu) 14:16:17 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 21:41:02 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.ORB; +import java.util.Properties; + +public class ColocatedServers +{ + public static ORB orb; + + public static boolean colocatedBootstrapDone = false; + + public static void main (String[] av) + { + try { + + // + // Share an ORB between objects servers. + // + + Properties props = new Properties(); + props.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "pi.serviceexample.AServiceORBInitializer", + ""); + props.put("org.omg.PortableInterceptor.ORBInitializerClass." + + "pi.serviceexample.LoggingServiceServerORBInitializer", + ""); + ORB orb = ORB.init(av, props); + ArbitraryObjectImpl.orb = orb; + LoggingServiceImpl.orb = orb; + + // + // Start both object servers. + // + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + ArbitraryObjectImpl.main(av); + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } +} + +class ServerThread extends Thread +{ + String[] av; + ServerThread (String[] av) + { + this.av = av; + } + public void run () + { + LoggingServiceImpl.main(av); + } +} + +// End of file. diff --git a/functional-tests/src/test/java/pi/serviceexample/LoggingServiceClientInterceptor.java b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceClientInterceptor.java new file mode 100644 index 000000000..7330062b6 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceClientInterceptor.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 19:46:30 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 21:42:34 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TCKind; +import org.omg.IOP.ServiceContext; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.InvalidSlot; + +public class LoggingServiceClientInterceptor + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor +{ + private LoggingService loggingService; + private Current piCurrent; + private int outCallIndicatorSlotId; + + public LoggingServiceClientInterceptor(LoggingService loggingService, + Current piCurrent, + int outCallIndicatorSlotId) + { + this.loggingService = loggingService; + this.piCurrent = piCurrent; + this.outCallIndicatorSlotId = outCallIndicatorSlotId; + } + + // + // Interceptor operations + // + + public String name() + { + return "LoggingServiceClientInterceptor"; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + log(ri, "send_request"); + } + + public void send_poll(ClientRequestInfo ri) + { + log(ri, "send_poll"); + } + + public void receive_reply(ClientRequestInfo ri) + { + log(ri, "receive_reply"); + } + + public void receive_exception(ClientRequestInfo ri) + { + log(ri, "receive_exception"); + } + + public void receive_other(ClientRequestInfo ri) + { + log(ri, "receive_other"); + } + + // + // Utilities. + // + + public void log(ClientRequestInfo ri, String point) + { + // IMPORTANT: Always set the TSC out call indicator in case + // other interceptors make outcalls for this request. + // Otherwise the outcall will not be set for the other interceptor's + // outcall resulting in infinite recursion. + + Any indicator = ORB.init().create_any(); + indicator.insert_boolean(true); + try { + piCurrent.set_slot(outCallIndicatorSlotId, indicator); + } catch (InvalidSlot e) { } + + try { + indicator = ri.get_slot(outCallIndicatorSlotId); + + // If the RSC out call slot is not set then log this invocation. + // If it is set that indicates the interceptor is servicing the + // invocation of loggingService itself. In that case do + // nothing (to avoid infinite recursion). + + if (indicator.type().kind().equals(TCKind.tk_null)) { + loggingService.log(ri.operation() + " " + point); + } + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/LoggingServiceClientORBInitializer.java b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceClientORBInitializer.java new file mode 100644 index 000000000..fcc812fc7 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceClientORBInitializer.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 20:32:27 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 19:16:26 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.CurrentHelper; +import org.omg.PortableInterceptor.ORBInitInfo; + +public class LoggingServiceClientORBInitializer + extends org.omg.CORBA.LocalObject + implements org.omg.PortableInterceptor.ORBInitializer +{ + public void pre_init(ORBInitInfo info) + { + } + + public void post_init(ORBInitInfo info) + { + try { + + // Get a reference to the LoggingService object. + + NamingContext nameService = + NamingContextHelper.narrow( + info.resolve_initial_references("NameService")); + + NameComponent path[] = + { new NameComponent("LoggingService", "") }; + LoggingService loggingService = + LoggingServiceHelper.narrow(nameService.resolve(path)); + + // Get a reference to TSC PICurrent. + + Current piCurrent = + CurrentHelper.narrow( + info.resolve_initial_references("PICurrent")); + + // Allocate a slot id to use for the interceptor to indicate + // that it is making an outcall. This is used to avoid + // infinite recursion. + + int outCallIndicatorSlotId = info.allocate_slot_id(); + + // Create (with the above data) and register the client + // side interceptor. + + LoggingServiceClientInterceptor interceptor = + new LoggingServiceClientInterceptor(loggingService, + piCurrent, + outCallIndicatorSlotId); + + info.add_client_request_interceptor(interceptor); + } catch (Throwable t) { + System.out.println("Exception handling not shown."); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/pi/serviceexample/LoggingServiceImpl.java b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceImpl.java new file mode 100644 index 000000000..9109ecc06 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceImpl.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 11:57:05 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 21:26:29 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.PortableServer.POA; + +import java.util.Properties; + +class LoggingServiceImpl + extends LoggingServicePOA +{ + public static ORB orb; + + // + // The IDL operations. + // + + public void log(String a1) + { + System.out.println(a1); + } + + // + // The server. + // + + public static void main(String[] av) + { + try { + if (orb == null) { + orb = ORB.init(av, null); + } + + POA rootPOA = (POA) orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + byte[] objectId = + rootPOA.activate_object(new LoggingServiceImpl()); + org.omg.CORBA.Object ref = rootPOA.id_to_reference(objectId); + + NamingContext nameService = + NamingContextHelper.narrow( + orb.resolve_initial_references("NameService")); + NameComponent path[] = + { new NameComponent("LoggingService", "") }; + nameService.rebind(path, ref); + + // Only relevant for colocated example. + ColocatedServers.colocatedBootstrapDone = true; + + System.out.println("Server is ready."); + + orb.run(); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + System.exit(0); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/LoggingServiceServerInterceptor.java b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceServerInterceptor.java new file mode 100644 index 000000000..c5f20c540 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceServerInterceptor.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Jun 05 (Tue) 19:22:46 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 21:34:05 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TCKind; +import org.omg.IOP.ServiceContext; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; + +public class LoggingServiceServerInterceptor + extends org.omg.CORBA.LocalObject + implements ClientRequestInterceptor, + ServerRequestInterceptor +{ + private NamingContext nameService; + private LoggingService loggingService; + private Current piCurrent; + private int outCallIndicatorSlotId; + private static final int serviceContextId = 100001; + private static final byte[] serviceContextData = {1}; + + // Returns a reference to the logging process. + + private LoggingService loggingService() + { + if (loggingService == null) { + NameComponent path[] = + { new NameComponent("LoggingService", "") }; + try { + loggingService = + LoggingServiceHelper.narrow(nameService.resolve(path)); + } catch (Throwable t) { + System.out.println("Exception handling not shown."); + } + } + return loggingService; + } + + public LoggingServiceServerInterceptor(NamingContext nameService, + Current piCurrent, + int outCallIndicatorSlotId) + { + this.nameService = nameService; + this.piCurrent = piCurrent; + this.outCallIndicatorSlotId = outCallIndicatorSlotId; + } + + // + // Interceptor operations + // + + public String name() + { + return "LoggingServiceServerInterceptor"; + } + + public void destroy() + { + } + + // + // ClientRequestInterceptor operations + // + + public void send_request(ClientRequestInfo ri) + { + + // If the server interceptor sets the recursion slot then + // put in the service context so the server doesn't make + // the call again in the case where the server side interceptor + // is colocated in the same ORB as the object being invoked. + + try { + Any indicator = ri.get_slot(outCallIndicatorSlotId); + if (indicator.type().kind().equals(TCKind.tk_boolean)) { + ServiceContext serviceContext = + new ServiceContext(serviceContextId, serviceContextData); + ri.add_request_service_context(serviceContext, false); + } + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + } + + public void send_poll(ClientRequestInfo ri) + { + } + + public void receive_reply(ClientRequestInfo ri) + { + } + + public void receive_exception(ClientRequestInfo ri) + { + } + + public void receive_other(ClientRequestInfo ri) + { + } + + // + // ServerRequestInterceptor operations + // + + public void receive_request_service_contexts(ServerRequestInfo ri) + { + log(ri, "receive_request_service_contexts"); + } + + public void receive_request(ServerRequestInfo ri) + { + log(ri, "receive_request"); + } + + public void send_reply(ServerRequestInfo ri) + { + log(ri, "send_reply"); + } + + public void send_exception(ServerRequestInfo ri) + { + log(ri, "send_exception"); + } + + public void send_other(ServerRequestInfo ri) + { + log(ri, "send_other"); + } + + // + // Utilities. + // + + public void log(ServerRequestInfo ri, String point) + { + // This is only relevant for the colocated example. + // Do not attempt to log until the logging service object + // has been bound in naming. Otherwise the attempt to call + // rebind on naming will call log which will fail. + if (! ColocatedServers.colocatedBootstrapDone) { + return; + } + + // IMPORTANT: + // The conditional logging of the invocation is only necessary + // if there is a chance that the object being invoked is colocated + // in the same ORB as this interceptor. Otherwise the outcall to + // the logging service can be made unconditionally. + + // Always set the recursion slot. + + Any indicator = ORB.init().create_any(); + indicator.insert_boolean(true); + try { + piCurrent.set_slot(outCallIndicatorSlotId, indicator); + } catch (InvalidSlot e) { + System.out.println("Exception handling not shown."); + } + + // Make the out call if you have not already done so. + + try { + + // Only the presence of the service context counts. + // The data is ignored. + + ri.get_request_service_context(serviceContextId); + } catch (BAD_PARAM e) { + // Recursion indicator not set so make the call. + loggingService().log(ri.operation() + " " + point); + } + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/LoggingServiceServerORBInitializer.java b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceServerORBInitializer.java new file mode 100644 index 000000000..668b07f38 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/LoggingServiceServerORBInitializer.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 May 23 (Wed) 20:32:27 by Harold Carr. +// Last Modified : 2001 Sep 20 (Thu) 21:02:59 by Harold Carr. +// + +package pi.serviceexample; + +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.CurrentHelper; +import org.omg.PortableInterceptor.ORBInitInfo; + +public class LoggingServiceServerORBInitializer + extends org.omg.CORBA.LocalObject + implements org.omg.PortableInterceptor.ORBInitializer +{ + public void pre_init(ORBInitInfo info) + { + } + + public void post_init(ORBInitInfo info) + { + try { + + // Create and register the logging service interceptor. + // Give that interceptor references to the NameService and + // PICurrent to avoid further lookups (i.e., optimization). + // More importantly, allocate and give the interceptor + // a slot id which is will use to tell itself not to + // log calls that the interceptor makes to the logging process. + + NamingContext nameService = + NamingContextHelper.narrow( + info.resolve_initial_references("NameService")); + + Current piCurrent = + CurrentHelper.narrow( + info.resolve_initial_references("PICurrent")); + + int outCallIndicatorSlotId = info.allocate_slot_id(); + + LoggingServiceServerInterceptor interceptor = + new LoggingServiceServerInterceptor(nameService, + piCurrent, + outCallIndicatorSlotId); + + info.add_client_request_interceptor(interceptor); + info.add_server_request_interceptor(interceptor); + } catch (Throwable t) { + System.out.println("Exception handling not shown."); + } + } +} + +// End of file. diff --git a/functional-tests/src/test/java/pi/serviceexample/Makefile.example b/functional-tests/src/test/java/pi/serviceexample/Makefile.example new file mode 100644 index 000000000..cbe6cd04d --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/Makefile.example @@ -0,0 +1,56 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +JAVA_HOME=/java/re/j2se/1.4/promoted/beta3/b81/binaries/solsparc + +CLASSPATH=. + +JAVAC=$(JAVA_HOME)/bin/javac +JAVA=$(JAVA_HOME)/bin/java + +ORB_INITIAL_PORT=1050 + +IDLJ=$(JAVA_HOME)/bin/idlj +IDLJ_FLAGS=-fall -td $(CLASSPATH) -verbose + +ORBD=${JAVA_HOME}/bin/orbd -ORBInitialPort ${ORB_INITIAL_PORT} + +build: + $(IDLJ) $(IDLJ_FLAGS) serviceexample.idl + $(JAVAC) -d $(CLASSPATH) *.java + $(JAVAC) pi/serviceexample/*.java + +runorbd: + $(ORBD) + +runloggingservice: + $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.LoggingServiceImpl \ + -ORBInitialPort ${ORB_INITIAL_PORT} + +runarbitraryobject: + $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.ArbitraryObjectImpl \ + -ORBInitialPort ${ORB_INITIAL_PORT} + +runcolocatedservers: + $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.ColocatedServers \ + -ORBInitialPort ${ORB_INITIAL_PORT} + +runclient: + $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.Client \ + -ORBInitialPort ${ORB_INITIAL_PORT} + +clean: + rm -rf pi + rm -rf orb.db + +# Order of steps: +# Build: clean build +# Remote: runorbd runloggingservice runarbitraryobjectimpl runclient +# Colocated: runorbd runcolocatedservers runclient diff --git a/functional-tests/src/test/java/pi/serviceexample/README.txt b/functional-tests/src/test/java/pi/serviceexample/README.txt new file mode 100644 index 000000000..b5204e9e7 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/README.txt @@ -0,0 +1,162 @@ +# +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +This is an example of how to use interceptors. + +It contains two scenarios: + +1. A logging service which logs invocations. The client nor server + does not explicitly use the logging service. + +2. An "empty" service which passes information from the client to the + server. The client and server explicitly use this service but are + not aware that it is implemented using interceptors. + +The purpose of the logging service example is to show how to avoid +infinite recursion when making outcalls (i.e., invocations on CORBA +references) from within interception points. This turns out to be quite +involved when all corner cases are covered. + +The purpose of the "empty" service example is to show how to implement +services which flow context information from client to server and back. + +Note: these examples explicitly register ORBInitializers to make the +code easier to experiment with and setup. Typically this would not be +done. Instead, this information would be passed as -D properties to +java when the applications are started. That way the applications are +not coupled to the fact that either the service exists (e.g., the +logging service) or that a service that they explicitly use (e.g., the +"AService" interface) is implemented as an interceptor. + +Files: + +serviceexample.idl + + Contains definitions of an arbitrary object on which to make + invocations and two services which will service calls to the + arbitrary object. + +LoggingServiceClientORBInitializer.java + + Creates and registers the logging service interceptor used by + object clients. + +LoggingServiceClientInterceptor.java + + This interceptor logs client side interception points. It + illustrates how to make invocations on other objects from + within an interceptor and how to avoid infinite recursion + during those "outcall" invocations. + +LoggingServiceServerORBInitializer.java + + Creates and registers the logging service interceptor used by + object servers. Even though this interceptor is meant to only + log server side interception points it is both a client and + server interceptor. This is to illustrate how to avoid + infinite recursion in the case where the object being called + is colocated in the same ORB as which the interceptors are + registered. + +LoggingServiceServerInterceptor.java + + This interceptor logs server side interception points. + + This interceptor is implemented as both a + ClientRequestInterceptor and a ServerRequestInterceptor to + illustrate the need to set some "out call" service context + data (in addition to setting an out call slot) to avoid + infinite recursion for the case noted in the description of + LoggingServiceServerORBInitializer.java. + +LoggingServiceImpl.java + + The logging object to which the logging service interceptors + send their data. + +AServiceORBInitializer.java + + Creates and registers the AServiceInterceptor as both a client + and server interceptor. It also creates a local object to be + used by applications to explicitly control the services + offered by AService. This local object is registered as an + initial service with the ORB such that it can be obtained by + clients via org.omg.CORBA.ORB.resolve_initial_references. + + Creates and registers teh AServiceIORInterceptor which + puts a TaggedComponent into IORs. + +AServiceImpl.java + + This object is explicitly used by client and servant code to + communicate with the service. When the client "begin"s the + service that causes an "service id" specific to the service to + be put in the TSC PICurrent slot reserved by this service. + When the client call "end" on the service it sets the TSC slot + to a non-valid value to indicate that the service is not in + effect. Servant's use the "verify" method which simply + indicates whether the service id was passed from the + client side to the server side. + +AServiceInterceptor.java + + This interceptor is responsible for arranging to pass the + client side AService information to the service side. + + On the client side, if AService.begin() has been called then + the send_request point will see the service id in the RSC + slot. In this case it then inserts the value of that service + id into a org.omg.CORBA.ServiceContext and adds that service + context to the data to be passed along with the invocation. + + On the server side, receive_request_service_context looks for + the presence of that service context. When present, it + extracts the service id value from the service context and + sets the RSC slot to that value. When the servant is + executing the value of that RSC slot is available in the TSC + slot. + +AServiceIORInterceptor.java + + Adds a TaggedComponent to IORs. + +ArbitaryObjectImpl.java + + An implementation and server for the ArbitraryObject IDL interface. + The implementations of the IDL interface operations explicitly + call the AServiceImpl.verify method to illustrate the + end-to-end passing of data from the client (via + AService.begin) to the servant. + +Client.java + + A client which calls methods on ArbitraryObject. It makes + some of those calls within the context of AService and some + outside of its context. It is unaware of the existence of the + logging interceptor (except that it explicitly registers the + LoggingServerClientORBInitializer as noted above). + +ColocatedServers.java + + This is a server which runs both ArbitraryObject and + LoggingService in the same ORB. This means that these objects + are "colocated". + + This is done to exercise the code in + LoggingServiceServerInterceptor that illustrates when + interceptors make out calls to objects which are colocated in + the same ORB extra steps must be taken to avoid infinite + recursion. + +ServerExampleTest.java + + This class exists to run the code in the rip unit test + framework. It is NOT part of the example. + +// End of file. diff --git a/functional-tests/src/test/java/pi/serviceexample/ServiceExampleTest.java b/functional-tests/src/test/java/pi/serviceexample/ServiceExampleTest.java new file mode 100644 index 000000000..8dd4c7d14 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/ServiceExampleTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2001 Sep 24 (Mon) 20:20:45 by Harold Carr. +// Last Modified : 2001 Sep 24 (Mon) 20:21:06 by Harold Carr. +// + +package pi.serviceexample; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +public class ServiceExampleTest + extends + CORBATest +{ + public static final String thisPackage = + ServiceExampleTest.class.getPackage().getName(); + + protected void doTest() + throws + Throwable + { + Controller orbd = createORBD(); + orbd.start(); + + // Remote. + + Controller loggingServer = + createServer(thisPackage + ".LoggingServiceImpl", + "loggingServer") ; + loggingServer.start(); + + Controller arbitraryObjectServer = + createServer(thisPackage + ".ArbitraryObjectServiceImpl", + "arbitraryObjectServer") ; + arbitraryObjectServer.start(); + + Controller client = createClient(thisPackage + ".Client", + "client"); + + client.start(); + client.waitFor(); + client.stop(); + arbitraryObjectServer.stop(); + loggingServer.stop(); + + // Colocated. + + Controller colocatedServers = + createServer(thisPackage + ".ColocatedServers", + "colocatedClientServer"); + colocatedServers.start(); + client.start(); + client.waitFor(); + client.stop(); + colocatedServers.stop(); + + orbd.stop(); + } +} + +// End of file. + diff --git a/functional-tests/src/test/java/pi/serviceexample/doc/AService.vthought b/functional-tests/src/test/java/pi/serviceexample/doc/AService.vthought new file mode 100644 index 000000000..629a4b475 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/doc/AService.vthought @@ -0,0 +1,1036 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause +; + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.4") + (buildDate "$Date: 2006/05/11 16:29:44 $") + (writeDate "Fri Mar 1, 2002 10:57:19 AM PST") + (documentPath "/space/home/carr/ws/rip-int/test/src/share/classes/pi/serviceexample/doc/AService.vthought") +) + +(document + (palette F) + (layout + (page "Letter") + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 316 20) + (size 632 594) + (zoom 1) + (documentLocation 0 248) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 364.5 369) + (size 117 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 12 aService.verify()}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 319.5 423) + (size 63 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc PICurrent}) + ) + (shape + (id 7) + (layer 6) + (type "Rectangle") + (location 364.5 522) + (size 81 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc SRInfo}) + ) + (shape + (id 11) + (layer 10) + (type "Rectangle") + (location 67.5 567) + (size 117 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1 aService.begin()}) + ) + (shape + (id 12) + (layer 11) + (type "Rectangle") + (location 576 324) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard SERVER}) + ) + (shape + (id 13) + (layer 12) + (type "Rectangle") + (location 90 324) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard CLIENT}) + ) + (shape + (id 22) + (layer 21) + (type "Rectangle") + (location 166.5 351) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 15 receive_*}) + ) + (shape + (id 23) + (layer 22) + (type "Rectangle") + (location 337.5 333) + (size 63 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 14 send_*}) + ) + (shape + (id 24) + (layer 23) + (type "Rectangle") + (location 567 378) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 11 Servant}) + ) + (shape + (id 25) + (layer 24) + (type "Rectangle") + (location 450 441) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 10 receive_request}) + ) + (shape + (id 26) + (layer 25) + (type "Rectangle") + (location 396 594) + (size 216 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 7 receive_request_service_contexts}) + ) + (shape + (id 29) + (layer 28) + (type "Rectangle") + (location 220.5 513) + (size 81 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc CRInfo}) + ) + (shape + (id 30) + (layer 29) + (type "Rectangle") + (location 130.5 486) + (size 63 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc PICurrent}) + ) + (shape + (id 31) + (layer 30) + (type "Rectangle") + (location 184.5 594) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 3 send_request}) + ) + (shape + (id 32) + (layer 31) + (type "Rectangle") + (location 54 531) + (size 90 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 2 ref.method()}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (end 4) + (points + (360 378) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.25) + (textWidth 126) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 13 get_slot, set_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (points + (486 369) + (432 369) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (points + (396 540) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.55) + (textWidth 72) + (textOffset -10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 9 set_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 6) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (points + (333 540) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.632) + (textWidth 102) + (textOffset 22) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 8 get_req_s_c}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 8) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 31) + (points + (258 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 1) + (textWidth 90) + (textOffset -23) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 6 add_req_s_c}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 9) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 31) + (points + (181 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.59) + (textWidth 97) + (textOffset 24) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 4 get_eff_comp}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 10) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (points + (36 540) + (9 549) + (9 585) + (126 594) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 14) + (layer 13) + (rotation 0) + (textRotation 0) + (locked F) + (points + (279 639) + (567 639) + (567 315) + (279 315) + (279 639) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 1 1) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 15) + (layer 14) + (rotation 0) + (textRotation 0) + (locked F) + (points + (9 639) + (261 639) + (261 315) + (9 315) + (9 639) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 1 1) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 16) + (layer 15) + (rotation 0) + (textRotation 0) + (locked F) + (points + (126 351) + (108 351) + (99 369) + (90 396) + (90 432) + (90 495) + (72 513) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 17) + (layer 16) + (rotation 0) + (textRotation 0) + (locked F) + (points + (297 333) + (216 351) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 18) + (layer 17) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (points + (450 360) + (378 333) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 19) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (start 25) + (end 24) + (points + (450 387) + (477 378) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 20) + (layer 19) + (rotation 0) + (textRotation 0) + (locked F) + (points + (513 594) + (531 594) + (549 585) + (558 576) + (558 567) + (558 549) + (531 531) + (432 450) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 21) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (points + (243 594) + (279 594) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 27) + (layer 26) + (rotation 0) + (textRotation 0) + (locked F) + (start 31) + (points + (216 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.404) + (textWidth 72) + (textOffset -18) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 5 get_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 28) + (layer 27) + (rotation 0) + (textRotation 0) + (locked F) + (start 11) + (points + (144 504) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.629) + (textWidth 74) + (textOffset -13) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 1a set_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) +) + +(groups +) diff --git a/functional-tests/src/test/java/pi/serviceexample/doc/LoggingService.vthought b/functional-tests/src/test/java/pi/serviceexample/doc/LoggingService.vthought new file mode 100644 index 000000000..7dc412dde --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/doc/LoggingService.vthought @@ -0,0 +1,863 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause +; + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.4") + (buildDate "$Date: 2006/05/11 16:29:50 $") + (writeDate "Fri Mar 1, 2002 10:57:02 AM PST") + (documentPath "/space/home/carr/ws/rip-int/test/src/share/classes/pi/serviceexample/doc/LoggingService.vthought") +) + +(document + (palette F) + (layout + (page "Letter") + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 227 41) + (size 632 594) + (zoom 1) + (documentLocation 0 248) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 2) + (layer 1) + (type "Rectangle") + (location 576 324) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard SERVER}) + ) + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 90 324) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard CLIENT}) + ) + (shape + (id 13) + (layer 12) + (type "Rectangle") + (location 166.5 351) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 14 receive_*}) + ) + (shape + (id 14) + (layer 13) + (type "Rectangle") + (location 337.5 351) + (size 63 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 13 send_*}) + ) + (shape + (id 15) + (layer 14) + (type "Rectangle") + (location 567 378) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 12 Servant}) + ) + (shape + (id 16) + (layer 15) + (type "Rectangle") + (location 450 441) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 11 receive_request}) + ) + (shape + (id 18) + (layer 17) + (type "Rectangle") + (location 396 594) + (size 216 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 9 receive_request_service_contexts}) + ) + (shape + (id 22) + (layer 21) + (type "Rectangle") + (location 202.5 513) + (size 45 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc CRInfo}) + ) + (shape + (id 23) + (layer 22) + (type "Rectangle") + (location 139.5 513) + (size 63 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc PICurrent}) + ) + (shape + (id 24) + (layer 23) + (type "Rectangle") + (location 189 594) + (size 108 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 2, 5 send_request}) + ) + (shape + (id 25) + (layer 24) + (type "Rectangle") + (location 54 531) + (size 90 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1 ref.method()}) + ) + (shape + (id 26) + (layer 25) + (type "Rectangle") + (location 274.5 702) + (size 99 54) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc LoggingService}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (points + (243 603) + (252 612) + (252 621) + (243 630) + (153 630) + (117 621) + (117 603) + (135 592) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 4) + (layer 3) + (rotation 0) + (textRotation 0) + (locked F) + (points + (279 639) + (567 639) + (567 315) + (279 315) + (279 639) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 1 1) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (points + (9 639) + (261 639) + (261 315) + (9 315) + (9 639) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 1 1) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 6) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (points + (72 549) + (90 576) + (126 585) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 7) + (layer 6) + (rotation 0) + (textRotation 0) + (locked F) + (points + (126 351) + (108 351) + (99 369) + (90 396) + (90 432) + (90 495) + (72 513) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 8) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (points + (306 351) + (216 351) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 9) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 15) + (points + (450 360) + (378 351) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 10) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 15) + (points + (450 387) + (477 378) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 11) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (points + (513 594) + (531 594) + (549 585) + (558 576) + (558 567) + (558 549) + (531 531) + (432 450) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 12) + (layer 11) + (rotation 0) + (textRotation 0) + (locked F) + (points + (243 594) + (279 594) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 17) + (layer 16) + (rotation 0) + (textRotation 0) + (locked F) + (start 18) + (end 26) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.67) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 10 log}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 19) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (end 26) + (points + (189 603) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.66) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 8 log}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 20) + (layer 19) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (points + (207 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.68) + (textWidth 90) + (textOffset -37) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 4, 7 get_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 21) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (points + (153 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.64) + (textWidth 74) + (textOffset 20) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 3, 6 set_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) +) + +(groups +) diff --git a/functional-tests/src/test/java/pi/serviceexample/doc/LoggingServiceColocated.vthought b/functional-tests/src/test/java/pi/serviceexample/doc/LoggingServiceColocated.vthought new file mode 100644 index 000000000..5e998816b --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/doc/LoggingServiceColocated.vthought @@ -0,0 +1,799 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.4") + (buildDate "$Date: 2006/05/11 16:29:55 $") + (writeDate "Fri Mar 1, 2002 10:57:33 AM PST") + (documentPath "/space/home/carr/ws/rip-int/test/src/share/classes/pi/serviceexample/doc/LoggingServiceColocated.vthought") +) + +(document + (palette F) + (layout + (page "Letter") + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 227 11) + (size 632 594) + (zoom 1) + (documentLocation 0 248) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 7) + (layer 6) + (type "Rectangle") + (location 463.5 351) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 13 receive_*}) + ) + (shape + (id 10) + (layer 9) + (type "Rectangle") + (location 382.5 513) + (size 81 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc CRInfo}) + ) + (shape + (id 11) + (layer 10) + (type "Rectangle") + (location 382.5 594) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 4 send_request}) + ) + (shape + (id 12) + (layer 11) + (type "Rectangle") + (location 306 297) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard SERVER}) + ) + (shape + (id 16) + (layer 15) + (type "Rectangle") + (location 67.5 351) + (size 63 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 12 send_*}) + ) + (shape + (id 17) + (layer 16) + (type "Rectangle") + (location 297 378) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 11 Servant}) + ) + (shape + (id 18) + (layer 17) + (type "Rectangle") + (location 180 441) + (size 144 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 10 receive_request}) + ) + (shape + (id 21) + (layer 20) + (type "Rectangle") + (location 130.5 513) + (size 45 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc SRInfo}) + ) + (shape + (id 22) + (layer 21) + (type "Rectangle") + (location 67.5 513) + (size 63 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc PICurrent}) + ) + (shape + (id 23) + (layer 22) + (type "Rectangle") + (location 153 594) + (size 234 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1, 7 receive_request_service_contexts}) + ) + (shape + (id 24) + (layer 23) + (type "Rectangle") + (location 274.5 396) + (size 99 54) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc LoggingService}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (points + (504 351) + (522 351) + (531 342) + (531 324) + (522 315) + (153 306) + (9 306) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (points + (27 351) + (18 342) + (18 333) + (27 324) + (153 333) + (261 342) + (378 351) + (414 351) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 23) + (points + (171 450) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 4) + (layer 3) + (rotation 0) + (textRotation 0) + (locked F) + (points + (270 594) + (315 594) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (points + (432 594) + (468 594) + (486 603) + (486 621) + (468 639) + (423 639) + (54 639) + (27 630) + (27 621) + (36 603) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 6) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (end 23) + (points + (0 594) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 8) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 11) + (points + (405 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 1) + (textWidth 185) + (textOffset -73) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 6 add_request_service_context}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 9) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 11) + (points + (351 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.64) + (textWidth 74) + (textOffset 14) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 5 get_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 13) + (layer 12) + (rotation 0) + (textRotation 0) + (locked F) + (points + (9 747) + (567 747) + (567 288) + (9 288) + (9 747) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 1 1) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 14) + (layer 13) + (rotation 0) + (textRotation 0) + (locked F) + (start 17) + (points + (180 360) + (108 351) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 15) + (layer 14) + (rotation 0) + (textRotation 0) + (locked F) + (start 18) + (end 17) + (points + (180 387) + (207 378) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 19) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (points + (112 585) + (135 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.87) + (textWidth 208) + (textOffset -84) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 3, 9 get_request_service_context}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 20) + (layer 19) + (rotation 0) + (textRotation 0) + (locked F) + (points + (104 585) + (81 531) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.7) + (textWidth 72) + (textOffset 14) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 2, 8 set_slot}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) +) + +(groups +) diff --git a/functional-tests/src/test/java/pi/serviceexample/doc/README.txt b/functional-tests/src/test/java/pi/serviceexample/doc/README.txt new file mode 100644 index 000000000..826ec2da2 --- /dev/null +++ b/functional-tests/src/test/java/pi/serviceexample/doc/README.txt @@ -0,0 +1,192 @@ +# +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +

Flowing Context Information between Clients and Servers

+ +A typical interceptor-based service will flow context information +between clients and servers. The AService example shows how this +information is flowed from the client thread into the client +interceptors, across the wire into the server interceptors, to the +servant thread and back. + +It is important to note that the client and servant is not aware that +the service is implemented using interceptors. Instead, they interact +with the service through local object references (the aService +reference in this example). + + + +1. The client invokes aService.begin(). +1a. aService.begin() sets the service context information in a slot + it has reserved in PICurrent. +2. The client invokes a method on some reference (i.e., ref.method()). + This invocation is taking place inside the context of the service since + aService.begin() has been invoked. +3. send_request is entered for the ref.method call. +4. get_effective_component(s) may be called to determine if the + reference being invoked needs to interact with the service. +5. get_slot is called to retrieve the context set in step 1a. +6. The service interceptor adds a service context containing the + appropriate context (most likely depending on the context set in + step 1a and any components retrieved in step 4). It uses + add_request_service_context to add this context information to + the request which is sent over the wire. +7. The ref.method request arrives at the server, activating the + receive_request_service_contexts interception point. +8. get_request_service_context is used to retrieve the service context + added at step 6. +9. ServerRequestInfo.set_slot is used to transfer the context information + from the service context retrieved in step 8 to the logical thread + local data. +10. receive_request is entered. +11. The "ref" Servant's "method" is entered. +12. The servant method invokes aService.verify() to interact with the + service. +13. The service uses get_slot on PICurrent to retrieve the context + information sent from the client side. The service may also + use set_slot on PICurrent to set any return context information. +14. After the Servant completes, the send_* interception point is + entered. If the service set any return context information then + it would add a service context to the return. This is not shown + in this example. + +

Avoiding Infinite Recursion During Interceptor Outcalls

+ +Some services may need to make invocations on other CORBA object +references from within interception points. When making outcalls from +within interception points steps must be taken to avoid infinite +recursion since those outcalls will flow through the inteception +points. The LoggingService example illustrates this case. + +The LoggingService example is comprised of ClientRequestInterceptors +registered in a client program, and ServerRequestInterceptors +registered in a server program. These interceptors send information +from the client and server to a LoggingService implemenation which +logs this information. + +However, since the LoggingService implementation is itself a CORBA +server, we must ensure that we do not log calls to the logger. The +following diagrams illustrate the steps taken to avoid infinite +recursion. + +The following diagram shows the simplest case of avoiding recursion +when calling an external logger from within interceptors. These steps +are useful for the case where the client ORB only contains +ClientRequestInterceptors, the server ORB only contains +ServerRequestInterceptors, and the LoggingService is external to both +the client and server ORBs. + + + +1. The client invokes a method on some reference. +2. The client interceptor's send_request method is entered for the method + invoked in step 1. +3. A slot reserved for indicating an outcall is set to true on PICurrent. +4. The same slot is checked on ClientRequestInfo via get_slot. + This value will not be set since it represents the client's thread + state at step #1. Therefore a call to the logger will be made. +5. send_request is entered for the logger invocation made in step 4. +6. A slot reserved for indicating an outcall is set to true on PICurrent. + Note, this slot is always unconditionally set. This is necessary + when there are 2 or more interceptors doing outcalls. Since interceptors + do not know about the existence of other interceptors we + always set the PICurrent slot. +7. The slot is checked on ClientRequestInfo via get_slot. + This time the value is set (from step 3). Therefore we do not log + this call (which is the call to the logger itself). The send_request + point entered at step 5 finishes. +8. The ORB sends the log invocation made at step 4 to the logging service. +9. The send_request point for step 2 finishes. The ORB sends the + initial client invocation made in step 1 to the server for the + appropriate reference. +10. The server's receive_request_service_contexts point is entered. + It logs the incoming request. A server which does not contain + client interceptors which make outcalls and which does not contain the + implementation of the logger itself does not need to set recursion + avoidance slots. That is what this diagram represents. + Therefore all the server side interception points are entered + with no further checking and the response from the method initially + invoked by the client is returned to the client ORB. +14. The client's receive_* point is entered. Steps similar to + 2-9 will occur if this point needs to make an outcall. + +

Avoiding recursion for colocated outcall references

+ +The following diagram illustrates the case where the LoggingService +may be colocated in the same ORB as the reference being invoked by the +client. In general, it is not possible to know that a particular +object reference is NOT colocated with any other objects hosted by +that ORB. Therefore, to cover all corner cases, more steps must be +taken. + +This diagram only shows the server side. The client side steps are +identical to those in the preceeding diagram. + + + +1. The request from the client ORB arrives, activating the + receive_request_service_contexts interception point. +2. A slot reserved for indicating an outcall is set to true on PICurrent. +3. ServerRequestInfo.get_request_service_context is used to check for + the presence of a service context indicating an outcall. + The service context is not present so the logger is invoked from + within the interception point. +4. The send_request interception point is entered for the logger request. +5. get_slot check for the outcall indicator. +6. The outcall indicator slot is set (from step #2). + Therefore add_request_service_context is used to a service context + indicating an outcall. This is necessary since there is no logical + relationship between client and server threads. +7. The logger invocation arrives at receive_request_service_contexts. +8. A slot reserved for indicating an outcall is set to true on PICurrent. +9. ServerRequestInfo.get_request_service_context is used to check for + the presence of a service context indicating an outcall. + The service context is present so no further action is taken. + receive_request_service_contexts exits. +10. The logger request proceeds to receive_request. Steps similar + to those taken inside receive_request_service_context are necessary + if the logger is called at the receive_request point. That is + not shown in the diagram (although the example code logs all points). +11. The logger request arrives at the LoggingService Servant, which + logs the initial client request (not invocation of the logger). +12. The logger request proceeds to ServerRequestInterceptor.send_* + (most likely send_reply). +13. The logger request proceeds to ClientRequestInterceptor.receive_* + (most likely receive_reply). + +The main point illustrated in this example is the necessity of using both +client and server interceptors in conjunction with PICurrent slots and +service contexts to indicate an outcall. + +

Avoid recursion by using multiple ORBs

+ +A simpler way to avoid recursion is to ensure that the outcall references +are associated with a different ORB that does not have the logging +interceptors registered. That way the outcall invocations never go through +interceptors. + +This seems like a simple solution, but, in general, interceptors are +registered via properties passed to the VM during startup. This means that +all ORBs created in that VM will contain all interceptors so this solution +will not work. + +This solution will only work where interceptors are explicitly registered +in client code during ORB.init. However, that is not a typical nor +a recommended way to register interceptor-based services. + +

Example code

+ +The following files contain the code which the above diagrams illustrate. +Instructions for compiling and executing these examples follow the code. + + + +

Compiling and running the application

+ +// End of file. diff --git a/functional-tests/src/test/java/rmic/AbstractObject.java b/functional-tests/src/test/java/rmic/AbstractObject.java new file mode 100644 index 000000000..50cd016ff --- /dev/null +++ b/functional-tests/src/test/java/rmic/AbstractObject.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public interface AbstractObject { + public boolean isValue () throws java.rmi.RemoteException; + public int getValue () throws java.rmi.RemoteException; + public String getCodeBase() throws java.rmi.RemoteException; +} + diff --git a/functional-tests/src/test/java/rmic/AppletServer.java b/functional-tests/src/test/java/rmic/AppletServer.java new file mode 100644 index 000000000..9a51eef4d --- /dev/null +++ b/functional-tests/src/test/java/rmic/AppletServer.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class AppletServer extends java.applet.Applet + implements Base { + public void method() throws java.rmi.RemoteException, TestException {} +} diff --git a/functional-tests/src/test/java/rmic/Base.java b/functional-tests/src/test/java/rmic/Base.java new file mode 100644 index 000000000..335806058 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Base.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface Base extends java.rmi.Remote { + void method() throws java.rmi.RemoteException, TestException; +} diff --git a/functional-tests/src/test/java/rmic/BaseImpl.java b/functional-tests/src/test/java/rmic/BaseImpl.java new file mode 100644 index 000000000..65a1e0a99 --- /dev/null +++ b/functional-tests/src/test/java/rmic/BaseImpl.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class BaseImpl extends javax.rmi.PortableRemoteObject implements Base { + public BaseImpl() throws java.rmi.RemoteException { + super(); + } + + public void method() throws java.rmi.RemoteException, TestException { + } +} diff --git a/functional-tests/src/test/java/rmic/CORBAUserException.java b/functional-tests/src/test/java/rmic/CORBAUserException.java new file mode 100644 index 000000000..f15a62d2e --- /dev/null +++ b/functional-tests/src/test/java/rmic/CORBAUserException.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + + +/** +* rmic/CORBAUserException.java +* Generated by the IBM IDL-to-Java compiler (portable), version "3.0" +* from cue.idl +* 09 May 1999 11:07:10 o'clock GMT+00:00 +*/ + +public final class CORBAUserException extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity +{ + + public CORBAUserException () + { + } // ctor + +} // class CORBAUserException diff --git a/functional-tests/src/test/java/rmic/CORBAUserException2.java b/functional-tests/src/test/java/rmic/CORBAUserException2.java new file mode 100644 index 000000000..affce58f3 --- /dev/null +++ b/functional-tests/src/test/java/rmic/CORBAUserException2.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + + +/** +* rmic/CORBAUserException2.java +* Generated by the IBM IDL-to-Java compiler (portable), version "3.0" +* from cue.idl +* Monday, May 10, 1999 12:31:06 o'clock PM PDT +*/ + +public final class CORBAUserException2 extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity +{ + + public CORBAUserException2 () + { + } // ctor + +} // class CORBAUserException2 diff --git a/functional-tests/src/test/java/rmic/CORBAUserException2Helper.java b/functional-tests/src/test/java/rmic/CORBAUserException2Helper.java new file mode 100644 index 000000000..56c8e6be1 --- /dev/null +++ b/functional-tests/src/test/java/rmic/CORBAUserException2Helper.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + + +/** +* rmic/CORBAUserException2Helper.java +* Generated by the IBM IDL-to-Java compiler (portable), version "3.0" +* from cue.idl +* Monday, May 10, 1999 12:31:05 o'clock PM PDT +*/ + +public final class CORBAUserException2Helper +{ + private static String _id = "IDL:rmic/CORBAUserException2:1.0"; + + public CORBAUserException2Helper() + { + } + + public static void insert (org.omg.CORBA.Any a, rmic.CORBAUserException2 that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static rmic.CORBAUserException2 extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (rmic.CORBAUserException2Helper.id (), "CORBAUserException2", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static rmic.CORBAUserException2 read (org.omg.CORBA.portable.InputStream istream) + { + rmic.CORBAUserException2 value = new rmic.CORBAUserException2 (); + // read and discard the repository ID + istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, rmic.CORBAUserException2 value) + { + // write the repository ID + ostream.write_string (id ()); + } + +} diff --git a/functional-tests/src/test/java/rmic/CORBAUserExceptionHelper.java b/functional-tests/src/test/java/rmic/CORBAUserExceptionHelper.java new file mode 100644 index 000000000..20f4571be --- /dev/null +++ b/functional-tests/src/test/java/rmic/CORBAUserExceptionHelper.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + + +/** +* rmic/CORBAUserExceptionHelper.java +* Generated by the IBM IDL-to-Java compiler (portable), version "3.0" +* from cue.idl +* 09 May 1999 11:07:10 o'clock GMT+00:00 +*/ + +public final class CORBAUserExceptionHelper +{ + private static String _id = "IDL:rmic/CORBAUserException:1.0"; + + public CORBAUserExceptionHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, rmic.CORBAUserException that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static rmic.CORBAUserException extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (rmic.CORBAUserExceptionHelper.id (), "CORBAUserException", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static rmic.CORBAUserException read (org.omg.CORBA.portable.InputStream istream) + { + rmic.CORBAUserException value = new rmic.CORBAUserException (); + // read and discard the repository ID + istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, rmic.CORBAUserException value) + { + // write the repository ID + ostream.write_string (id ()); + } + +} diff --git a/functional-tests/src/test/java/rmic/Cat.java b/functional-tests/src/test/java/rmic/Cat.java new file mode 100644 index 000000000..d4acac0ff --- /dev/null +++ b/functional-tests/src/test/java/rmic/Cat.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.io.IOException; + +public interface Cat extends Remote { + String cat(String one, String two, String three, Object it) throws RemoteException; + + public class Servant implements Cat { + public String cat(String one, String two, String three, Object it) { + return one + two + three + it.toString(); + } + } +} diff --git a/functional-tests/src/test/java/rmic/CharValue.java b/functional-tests/src/test/java/rmic/CharValue.java new file mode 100644 index 000000000..4f5158269 --- /dev/null +++ b/functional-tests/src/test/java/rmic/CharValue.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class CharValue implements java.io.Serializable { + + char value; + + public CharValue (char value) { + this.value = value; + } + + public char getValue () throws java.rmi.RemoteException { + return value; + } + + public int hashCode () { + return value; + } + + public boolean equals (Object it) { + boolean result = false; + if (this == it) { + result = true; + } else if (it != null && it instanceof CharValue) { + CharValue other = (CharValue) it; + if (other.value == value) { + result = true; + } + } + return result; + } +} + diff --git a/functional-tests/src/test/java/rmic/ClassEnumerator.java b/functional-tests/src/test/java/rmic/ClassEnumerator.java new file mode 100644 index 000000000..0ba24cc25 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ClassEnumerator.java @@ -0,0 +1,256 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.util.Enumeration; +import java.util.Vector; +import java.util.Hashtable; +import java.io.File; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipException; +import java.util.Comparator; +import java.util.Arrays; + +/** + * This class provides static methods to enumerate all classes in + * a specified class path. + */ +public class ClassEnumerator { + + /** + * Get classes using the specified path string. + */ + public static Vector getClasses (String pathstr, boolean sort) { + Vector list = new Vector(4096); + Hashtable roots = new Hashtable(20); + Object nullValue = new Object(); + ClassPathEntry[] path = null; + + try { + path = parsePath(pathstr); + for (int i = path.length; --i >= 0; ) { + if (path[i].zip != null) { + Enumeration e = path[i].zip.entries(); + while (e.hasMoreElements()) { + ZipEntry entry = (ZipEntry)e.nextElement(); + String name = entry.getName(); + int index = name.indexOf(".class"); + if (index >=0) { + name = name.replace('/','.').substring(0,index); + list.addElement(name); + } + } + } else { + + // Just gather the unique root directories... + + File rootDir = path[i].dir; + if (rootDir.getPath().equals(".")) { + rootDir = new File(System.getProperty("user.dir")); + } + + // _REVISIT_ Forcing lower case here could cause us to skip a + // real root (if actually different case); however, + // if we don't do this, the "user.dir" property can + // screw us up by being in different case! + + String pathName = rootDir.getPath().toLowerCase(); + + if (!roots.containsKey(pathName)) { + roots.put(pathName,rootDir); + } + } + } + + // Process the root directories... + + for (Enumeration e = roots.keys(); e.hasMoreElements() ;) { + File rootDir = (File) roots.get(e.nextElement()); + int rootLen = rootDir.getPath().length() + 1; + addClasses(rootLen,rootDir,list,roots); + } + + // Release resources... + + } finally { + + if (path != null) { + for (int i = path.length; --i >= 0; ) { + if (path[i].zip != null) { + try { + path[i].zip.close(); + } catch (IOException e) {} + } + } + } + } + + // Sort it if we're supposed to... + + if (sort) { + int size = list.size(); + String[] temp = new String[size]; + list.copyInto(temp); + Arrays.sort(temp,new StringComparator()); + list = new Vector(size); + for (int i = 0; i < size; i++) { + list.addElement(temp[i]); + } + } + + return list; + } + + /** + * Get classes using the class path returned by getFullClassPath(). + */ + public static Vector getClasses (boolean sort) { + String cp = getFullClassPath(); + return getClasses(cp,sort); + } + + /** + * Return a class path constructed by concatenating the System + * Property values for: + *
+     *    java.sys.class.path
+     *    java.class.path
+     *    env.class.path
+     * 
+ * in that order. + */ + public static String getFullClassPath () { + String syscp = System.getProperty("java.sys.class.path"); + String appcp = System.getProperty("java.class.path"); + String envcp = System.getProperty("env.class.path"); + String cp = null; + + if (syscp != null) { + cp = syscp; + } + + if (appcp != null) { + if (cp == null) { + cp = appcp; + } else { + cp = cp + File.pathSeparator + appcp; + } + } + + if (envcp != null) { + if (cp == null) { + cp = envcp; + } else { + cp = cp + File.pathSeparator + envcp; + } + } + + if (cp == null) { + cp = "."; + } + + return cp; + } + + private static ClassPathEntry[] parsePath (String pathstr) { + + char dirSeparator = File.pathSeparatorChar; + int i, j, n; + ClassPathEntry[] path; + + if (pathstr.length() == 0) { + path = new ClassPathEntry[0]; + } + + // Count the number of path separators + i = n = 0; + while ((i = pathstr.indexOf(dirSeparator, i)) != -1) { + n++; i++; + } + // Build the class path + path = new ClassPathEntry[n+1]; + int len = pathstr.length(); + for (i = n = 0; i < len; i = j + 1) { + if ((j = pathstr.indexOf(dirSeparator, i)) == -1) { + j = len; + } + if (i == j) { + path[n] = new ClassPathEntry(); + path[n++].dir = new File("."); + } else { + File file = new File(pathstr.substring(i, j)); + if (file.exists()) { + if (file.isFile()) { + try { + ZipFile zip = new ZipFile(file); + path[n] = new ClassPathEntry(); + path[n++].zip = zip; + } catch (ZipException e) { + } catch (IOException e) { + // Ignore exceptions, at least for now... + } + } else { + path[n] = new ClassPathEntry(); + path[n++].dir = file; + } + } + } + } + // Trim class path to exact size + ClassPathEntry[] result = new ClassPathEntry[n]; + System.arraycopy((Object)path, 0, (Object)result, 0, n); + return result; + } + + private static void addClasses(int rootLen, File dir, Vector list, Hashtable roots) { + String[] files = dir.list(); + for (int i = 0; i < files.length; i++) { + File file = new File(dir,files[i]); + if (file.isDirectory()) { + + // Does our list of roots contain this directory? Must + // use a case-insensitive compare... + + String path = file.getPath().toLowerCase(); + if (roots.get(path) == null) { + + // No, so add it... + + addClasses(rootLen,file,list,roots); + } + } else { + String name = file.getPath(); + int index = name.lastIndexOf(".class"); + if (index >= 0) { + name = name.replace(File.separatorChar,'.').substring(rootLen,index); + list.addElement(name); + } + } + } + } +} + +class ClassPathEntry { + File dir; + ZipFile zip; +} + +class StringComparator implements Comparator { + + public int compare(Object o1, Object o2) { + String s1 = (String) o1; + String s2 = (String) o2; + return s1.compareTo(s2); + } +} diff --git a/functional-tests/src/test/java/rmic/DefaultPackage.java b/functional-tests/src/test/java/rmic/DefaultPackage.java new file mode 100644 index 000000000..28f4dac73 --- /dev/null +++ b/functional-tests/src/test/java/rmic/DefaultPackage.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public interface DefaultPackage extends java.rmi.Remote { + public void doSomething () throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/DefaultPackageImpl.java b/functional-tests/src/test/java/rmic/DefaultPackageImpl.java new file mode 100644 index 000000000..dd447185d --- /dev/null +++ b/functional-tests/src/test/java/rmic/DefaultPackageImpl.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class DefaultPackageImpl implements DefaultPackage { + public DefaultPackageImpl () throws java.rmi.RemoteException {} + public void doSomething () throws java.rmi.RemoteException {} +} diff --git a/functional-tests/src/test/java/rmic/DerivedImpl.java b/functional-tests/src/test/java/rmic/DerivedImpl.java new file mode 100644 index 000000000..6f90effee --- /dev/null +++ b/functional-tests/src/test/java/rmic/DerivedImpl.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class DerivedImpl extends BaseImpl implements Base { + public DerivedImpl() throws java.rmi.RemoteException { + super(); + } +} + diff --git a/functional-tests/src/test/java/rmic/Diamond.java b/functional-tests/src/test/java/rmic/Diamond.java new file mode 100644 index 000000000..4a9b9c829 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Diamond.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface Diamond extends Left, Right { + void method() throws java.rmi.RemoteException, TestException; + void left() throws java.rmi.RemoteException; + void right() throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/DiamondServer.java b/functional-tests/src/test/java/rmic/DiamondServer.java new file mode 100644 index 000000000..78117ff80 --- /dev/null +++ b/functional-tests/src/test/java/rmic/DiamondServer.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class DiamondServer implements Diamond { + public void method() throws java.rmi.RemoteException, TestException {} + public void left() throws java.rmi.RemoteException {} + public void right() throws java.rmi.RemoteException {} +} diff --git a/functional-tests/src/test/java/rmic/EmptyInterface.java b/functional-tests/src/test/java/rmic/EmptyInterface.java new file mode 100644 index 000000000..513b91ef6 --- /dev/null +++ b/functional-tests/src/test/java/rmic/EmptyInterface.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface EmptyInterface { +} diff --git a/functional-tests/src/test/java/rmic/Hello.java b/functional-tests/src/test/java/rmic/Hello.java new file mode 100644 index 000000000..187b2a8b7 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Hello.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.io.Serializable; + +public interface Hello extends java.rmi.Remote +{ + String CONSTANT1 = "constant1"; + int CONSTANT2 = 3+3; + + public String getCodeBase() throws java.rmi.RemoteException; + public void publishRemoteObject(String name) throws java.rmi.RemoteException; + public String sayHello() throws java.rmi.RemoteException; + public int sum(int value1, int value2) throws java.rmi.RemoteException; + public String concatenate(String str1, String str2) throws java.rmi.RemoteException; + public String checkOBV(ObjectByValue obv) throws java.rmi.RemoteException; + public ObjectByValue getOBV() throws java.rmi.RemoteException; + public Hello getHello () throws java.rmi.RemoteException; + + public int[] echoArray (int[] array) throws java.rmi.RemoteException; + public long[][] echoArray (long[][] array) throws java.rmi.RemoteException; + public short[][][] echoArray (short[][][] array) throws java.rmi.RemoteException; + public ObjectByValue[] echoArray (ObjectByValue[] array) throws java.rmi.RemoteException; + public ObjectByValue[][] echoArray (ObjectByValue[][] array) throws java.rmi.RemoteException; + + public AbstractObject echoAbstract (AbstractObject absObj) throws java.rmi.RemoteException; + public AbstractObject[] getRemoteAbstract() throws java.rmi.RemoteException; + public void shutDown () throws java.rmi.RemoteException; + public void throwHello (int count, String message) throws java.rmi.RemoteException, HelloException; + public void throw_NO_PERMISSION (String s, int minor) throws java.rmi.RemoteException; + public CharValue echoCharValue (CharValue value) throws java.rmi.RemoteException; + public Object echoObject (Object it) throws java.rmi.RemoteException; + public Serializable echoSerializable (Serializable it) throws java.rmi.RemoteException; + + public void throwError(Error it) throws java.rmi.RemoteException; + public void throwRemoteException(java.rmi.RemoteException it) throws java.rmi.RemoteException; + public void throwRuntimeException(RuntimeException it) throws java.rmi.RemoteException; + + public Hello echoRemote (Hello stub) throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/HelloException.java b/functional-tests/src/test/java/rmic/HelloException.java new file mode 100644 index 000000000..c0240f8ec --- /dev/null +++ b/functional-tests/src/test/java/rmic/HelloException.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class HelloException extends java.lang.Exception { + + private int count; + + public HelloException (int count, String message) { + super(message); + this.count = count; + } + + public int getCount () {return count;} +} diff --git a/functional-tests/src/test/java/rmic/HelloImpl.java b/functional-tests/src/test/java/rmic/HelloImpl.java new file mode 100644 index 000000000..d7b31110e --- /dev/null +++ b/functional-tests/src/test/java/rmic/HelloImpl.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import org.omg.CORBA.ORB; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.NO_PERMISSION; +import org.omg.CORBA.CompletionStatus; +import java.io.Serializable; +import java.rmi.server.RMIClassLoader; + +public class HelloImpl //extends javax.rmi.PortableRemoteObject + implements Hello { + + ObjectByValue obv = null; + AbstractObject[] remotes = null; + + public HelloImpl() throws java.rmi.RemoteException { + } + + public void initRemotes() throws java.rmi.RemoteException { + if (remotes == null) { + remotes = new AbstractObject[3]; + remotes[0] = new RemoteObjectServer(0); + remotes[1] = new RemoteObjectServer(1); + remotes[2] = new RemoteObjectServer(2); + } + } + + public String getCodeBase() throws java.rmi.RemoteException { + return RMIClassLoader.getClassAnnotation(getClass()); + } + + public void publishRemoteObject(String name) throws java.rmi.RemoteException { + try { + test.Util.singleServantContext.rebind(name,new RemoteObjectServer(192)); + } catch (javax.naming.NamingException e) { + throw new java.rmi.RemoteException("publishRemoteException caught: "+e); + } + } + + public String sayHello() throws java.rmi.RemoteException { + return "hello"; + } + + public int sum(int value1, int value2) throws java.rmi.RemoteException { + return value1 + value2; + } + + public String concatenate(String str1, String str2) throws java.rmi.RemoteException { + return str1+str2; + } + + public String checkOBV(ObjectByValue obv) throws java.rmi.RemoteException { + this.obv = obv; + + return "The Results are: " + + (obv.getValue1() + obv.getValue2()) + + obv.getString1() + + obv.getString2(); + } + + public ObjectByValue getOBV() throws java.rmi.RemoteException { + return obv; + } + + public Hello getHello () throws java.rmi.RemoteException { + return (Hello) PortableRemoteObject.toStub(this); + } + + public int[] echoArray (int[] array) throws java.rmi.RemoteException { + return array; + } + + public long[][] echoArray (long[][] array) throws java.rmi.RemoteException { + return array; + } + + public short[][][] echoArray (short[][][] array) throws java.rmi.RemoteException { + return array; + } + + public ObjectByValue[] echoArray (ObjectByValue[] array) throws java.rmi.RemoteException { + return array; + } + + public ObjectByValue[][] echoArray (ObjectByValue[][] array) throws java.rmi.RemoteException { + return array; + } + + public AbstractObject echoAbstract (AbstractObject absObj) throws java.rmi.RemoteException { + return absObj; + } + + public AbstractObject[] getRemoteAbstract() throws java.rmi.RemoteException { + initRemotes(); + return remotes; + } + + + public void shutDown () throws java.rmi.RemoteException { + System.exit(0); + } + + public void throwHello (int count, String message) throws java.rmi.RemoteException, HelloException { + throw new HelloException(count,message); + } + + public void throw_NO_PERMISSION (String s, int minor) throws java.rmi.RemoteException { + throw new NO_PERMISSION(s,minor,CompletionStatus.COMPLETED_YES); + } + + public CharValue echoCharValue (CharValue value) throws java.rmi.RemoteException { + return value; + } + + public Object echoObject (Object it) throws java.rmi.RemoteException { + return it; + } + + public Serializable echoSerializable (Serializable it) throws java.rmi.RemoteException { + return it; + } + + public void throwError(Error it) throws java.rmi.RemoteException { + throw it; + } + + public void throwRemoteException(java.rmi.RemoteException it) throws java.rmi.RemoteException { + throw it; + } + + public void throwRuntimeException(RuntimeException it) throws java.rmi.RemoteException { + throw it; + } + + public Hello echoRemote (Hello stub) throws java.rmi.RemoteException { + return stub; + } +} diff --git a/functional-tests/src/test/java/rmic/HelloTest.java b/functional-tests/src/test/java/rmic/HelloTest.java new file mode 100644 index 000000000..2099d1e75 --- /dev/null +++ b/functional-tests/src/test/java/rmic/HelloTest.java @@ -0,0 +1,601 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import test.ServantContext; +import test.RemoteTest; +import java.rmi.AccessException; +import java.util.Properties; +import java.util.Enumeration; +import java.io.Serializable; +import java.rmi.RemoteException; +import java.io.File; +import test.WebServer; +import test.Util; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.portable.ServantObject; +import org.omg.CORBA.portable.Delegate; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBData ; +import org.glassfish.pfl.test.JUnitReportHelper; + +/* + * @test + */ +public class HelloTest extends RemoteTest { + + private static final String servantName = "HelloServer"; + private static final String servantClass = "rmic.HelloImpl"; + private static final String[] compileEm = { + "rmic.HelloImpl", + "rmic.RemoteObjectServer", + }; + + private JUnitReportHelper helper = null ; + private boolean firstTest = true ; + + private void nextTest( String name ) { + if (firstTest) + firstTest = false ; + else + helper.pass() ; + + helper.start( name ) ; + } + + /** + * Return an array of fully qualified remote servant class + * names for which ties/skels need to be generated. Return + * empty array if none. + */ + protected String[] getRemoteServantClasses () { + return compileEm; + } + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + @Override + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + if (iiop) { + String[] ourArgs = {"-alwaysGenerate", "-keepgenerated"}; + return super.getAdditionalRMICArgs(ourArgs); + } else { + return super.getAdditionalRMICArgs(currentArgs); + } + } + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. + */ + @Override + protected boolean generateStubsOnlyOnce () { + return false; + } + + /** + * Return true if stubs should be generated in an external process. + */ + @Override + protected boolean generateStubsExternally () { + return false; + } + + /** + * Perform the test. + * @param context The context returned by getServantContext(). + */ + public void doTest (ServantContext context) throws Throwable { + WebServer webServer = null; + + final boolean useLocalServants ; + useLocalServants = getArgs().get(LOCAL_SERVANTS_FLAG) != null ; + helper = new JUnitReportHelper( this.getClass().getName() + + ( useLocalServants ? "_local" : "" ) ) ; + + try { + ORB orb = (ORB)(context.getORB()) ; + ORBData odata = orb.getORBData() ; + boolean usesDynamicStubs = ((ORB)context.getORB()).getPresentationManager().useDynamicStubs() ; + + String outputDirPath = (String) getArgs().get(test.Test.OUTPUT_DIRECTORY); + if (outputDirPath == null) { + throw new Exception ("Must have valid output directory set with -output option."); + } + + File rootDir = new File(outputDirPath); + File rmicDir = new File(rootDir,"rmic"); + + if (!usesDynamicStubs) { + nextTest( "setup" ) ; + // Rename _RemoteObject_Stub.class so can only be loaded by + // WebServer... + + String origName = "_RemoteObject_Stub.class"; + String newName = "_RemoteObject_Stub.clz"; + + File origFile = new File (rmicDir,origName); + File newFile = new File (rmicDir,newName); + if (origFile.exists() && newFile.exists()) { + newFile.delete(); + } + + origFile.renameTo(newFile); + if (newFile.exists() && !origFile.exists()) { + // System.out.println("Found newFile: " + newFile.getPath()); + } else { + throw new Exception ("_RemoteObject_Stub rename failed."); + } + + // Create our aliases and start up the WebServer... + Properties aliases = new Properties(); + aliases.put("/rmic/" + origName,"/rmic/" + newName); + int port = Util.getHttpServerPort(); + webServer = new WebServer(port,rootDir,1,aliases,null); + webServer.start(); + } + + nextTest( "getStubs" ) ; + + int stubKind; // 0 = remote, 1 = localremote (i.e. non-optimized), 2 = local + + boolean mustBeRemote; + + if (useLocalServants) { + if (getArgs().get(NO_LOCAL_STUBS_FLAG) != null) { + stubKind = 1; // localremote (i.e. non-optimized) + mustBeRemote = true; + Util.setDefaultCodeBase(true); + if (verbose) System.out.println("(No local stubs) "); + } else { + stubKind = 2; // local + mustBeRemote = false; + Util.setDefaultCodeBase(true); + } + } else { + stubKind = 0; // remote + mustBeRemote = true; + } + + // Start up our servant... + + Object initialRef = context.startServant(servantClass,servantName,true,iiop); + Hello objref = (Hello) PortableRemoteObject.narrow(initialRef,Hello.class); + + // Make sure we have the correct stub kind... + + Delegate del = StubAdapter.getDelegate( objref ) ; + ServantObject so = del.servant_preinvoke( + (org.omg.CORBA.Object)objref,"method", + Hello.class); + boolean isLocal = (so != null); + + if (mustBeRemote && isLocal) { + throw new Exception("Supposed to be remote stub, but is local: " + + objref.getClass().getName()); + } + if (!mustBeRemote && !isLocal) { + throw new Exception("Supposed to be local stub, but is remote:" + + objref.getClass().getName()); + } + + // Make sure stub downloading works (if not local)... + + if (stubKind != 2) { + nextTest( "testStubDownloading" ) ; + // Ask objref to publish an instance of RemoteObject... + + objref.publishRemoteObject("stubDownloadTest"); + + // Look it up in the name server... + + Object lookupResult = context.getNameContext().lookup("stubDownloadTest"); + + // Narrow to expected type... + + RemoteObject ro = (RemoteObject) PortableRemoteObject.narrow(lookupResult, + RemoteObject.class); + + // Check the codebase... + + IOR ior = orb.getIOR( (org.omg.CORBA.Object)ro, false ) ; + String localCodeBase = ior.getProfile().getCodebase(); + + if (localCodeBase == null) { + throw new Exception("localCodeBase == null"); + } + + String remoteCodeBase = ro.getCodeBase(); + + if (remoteCodeBase == null) { + throw new Exception("localCodeBase == null"); + } + + if (!remoteCodeBase.equals(localCodeBase)) { + throw new Exception("localCodeBase (" + localCodeBase + + ") != remoteCodeBase (" + remoteCodeBase +")"); + } + + // Check the class loader, unless we are using dynamic stubs: dynamic stus + // are never downloaded. + if (!usesDynamicStubs) { + ClassLoader loader = ro.getClass().getClassLoader(); + + if (loader != null) { + String loaderName = loader.getClass().getName(); + + if (!loaderName.startsWith("sun.rmi.server.LoaderHandler")) { + throw new Exception ( + "Stub downloaded with wrong loader on 1.2: " + + loaderName); + } + } else { + throw new Exception("Got null loader for "+ro.getClass().getName()); + } + } + } + + nextTest( "testHelloString" ) ; + if (!objref.sayHello().equals("hello")) { + throw new Exception("HelloTest: sayHello() failed"); + } + + nextTest( "testIntSum" ) ; + if (objref.sum(10,10) != 20) { + throw new Exception("HelloTest: sum(10,10) failed"); + } + + nextTest( "testStringConcat" ) ; + if (!objref.concatenate("Here"," This").equals("Here This")) { + throw new Exception("HelloTest: concatenate(\"Here\",\" This\") failed"); + } + + nextTest( "testObjectByValue" ) ; + ObjectByValue value = new ObjectByValue(5,7," It's ","Me!"); + + if (!objref.checkOBV(value).equals("The Results are: 12 It's Me!")) { + throw new Exception("HelloTest: checkOBV(value) failed"); + } + + nextTest( "testObjectByValue2" ) ; + ObjectByValue result = objref.getOBV(); + + if (!result.equals(value)) { + throw new Exception("HelloTest: getOBV() failed"); + } + + nextTest( "testRemoteObject" ) ; + Hello remoteObject = objref.getHello (); + + if (!remoteObject.sayHello().equals("hello")) { + throw new Exception("HelloTest: remoteObject.sayHello() failed"); + } + + nextTest( "testRemoteClassName" ) ; + String remoteClassName = remoteObject.getClass().getName(); + String matchName = "rmic._Hello_Stub"; + if (stubKind == 2) matchName = "rmic._Hello_Stub"; + + // We cannot assume that we know the stub class name if we are using dynamic stubs. + if (!usesDynamicStubs && !remoteClassName.equals(matchName)) { + throw new Exception("HelloTest: remoteObject.getClass() failed: " + remoteClassName); + } + + nextTest( "testNullObjref" ) ; + if (objref.echoRemote(null) != null) { + throw new Exception("HelloTest: null object reference failed."); + } + + nextTest( "testNullAbstract" ) ; + if (objref.echoAbstract(null) != null) { + throw new Exception("HelloTest: null abstract object failed."); + } + + nextTest( "testSingleArray" ) ; + int[] array1 = {0,5,7,9,11,13}; + int[] array1Echo = remoteObject.echoArray(array1); + + for (int i = 0; i < array1.length; i++) { + if (array1[i] != array1Echo[i]) { + throw new Exception("HelloTest: echoArray (int[]) failed"); + } + } + + nextTest( "test2DArray" ) ; + long[][] array2 = { + {9,8,7,6,1}, + {18,4,6}, + {0,5,7,9,11,13} + }; + + long[][] array2Echo = remoteObject.echoArray(array2); + + for (int i = 0; i < array2.length; i++) { + for (int j = 0; j < array2[i].length; j++) { + if (array2[i][j] != array2Echo[i][j]) { + throw new Exception("HelloTest: echoArray (int[][]) failed"); + } + } + } + + nextTest( "test3DArray" ) ; + short[][][] dim3 = { + { + {0,8,7,6,1}, + {1,5,7,13}, + {2,4,6}, + }, + { + {3,4,10}, + {4,5,7,9,13} + }, + { + {5,4,6}, + {6,5,8,9,11,13}, + {7,8,7,6,1}, + {8,8,7,6,9}, + }, + }; + + short[][][] dim3Echo = remoteObject.echoArray(dim3); + + for (int i = 0; i < dim3.length; i++) { + for (int j = 0; j < dim3[i].length; j++) { + for (int k = 0; k < dim3[i][j].length; k++) { + if (dim3[i][j][k] != dim3[i][j][k]) { + throw new Exception("HelloTest: echoArray (short[][][]) failed"); + } + } + } + } + + nextTest( "testSingleObjectArray" ) ; + ObjectByValue[] array3 = { + new ObjectByValue(5,10,"a","f"), + new ObjectByValue(6,11,"b","g"), + new ObjectByValue(7,12,"c","h"), + new ObjectByValue(8,13,"d","i"), + new ObjectByValue(9,14,"e","j"), + }; + + ObjectByValue[] array3Echo = remoteObject.echoArray(array3); + for (int i = 0; i < array3.length; i++) { + if (!array3[i].equals(array3Echo[i])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[]) failed"); + } + } + + nextTest( "test2DObjectArray" ) ; + ObjectByValue[][] array4 = { { + new ObjectByValue(0,10,"a","g"), + new ObjectByValue(0,11,"b","h"), + new ObjectByValue(0,12,"c","i"), + }, + { + new ObjectByValue(1,13,"d","j"), + new ObjectByValue(1,14,"e","k"), + }, + { + new ObjectByValue(2,15,"f","l"), + } + }; + + ObjectByValue[][] array4Echo = remoteObject.echoArray(array4); + + for (int i = 0; i < array4.length; i++) { + for (int j = 0; j < array4[i].length; j++) { + if (!array4[i][j].equals(array4Echo[i][j])) { + throw new Exception("HelloTest: echoArray (ObjectByValue[][]) failed"); + } + } + } + + nextTest( "testReadWriteAbstract" ) ; + AbstractObject[] remotes = remoteObject.getRemoteAbstract(); + AbstractObject[] array5 = { + new ValueObject(111), + remotes[0], + new ValueObject(222), + remotes[1], + new ValueObject(333), + new ValueObject(444), + remotes[2], + }; + + for (int i = 0; i < array5.length; i++) { + AbstractObject abs = remoteObject.echoAbstract(array5[i]); + + if (array5[i].getValue() != abs.getValue()) { + throw new Exception("HelloTest: echoAbstract (AbstractObject) failed (getValue)"); + } + + if (array5[i].isValue() != abs.isValue()) { + throw new Exception("HelloTest: echoAbstract (AbstractObject) failed (isValue)"); + } + } + + nextTest( "testApplicationException" ) ; + boolean caughtExpected = false; + + try { + remoteObject.throwHello(17,"Seventeen"); + } catch (HelloException e) { + if (e.getCount() == 17 && e.getMessage().startsWith("Seventeen")) { + caughtExpected = true; + } else { + throw new Exception("HelloTest: throwHello got count = " + + e.getCount() + ", message = " + e.getMessage()); + } + } + if (!caughtExpected) { + throw new Exception("HelloTest: throwHello failed"); + } + + nextTest( "testSystemException" ) ; + caughtExpected = false; + + try { + remoteObject.throw_NO_PERMISSION("ACK!",99); + } catch (AccessException e) { + if (e.getMessage().startsWith("CORBA NO_PERMISSION 99")) { + caughtExpected = true; + } else { + throw new Exception("HelloTest: throwSystem got " + e.toString()); + } + } + if (!caughtExpected) { + throw new Exception("HelloTest: throwSystem failed"); + } + + nextTest( "testError" ) ; + caughtExpected = false; + + try { + remoteObject.throwError(new Error("Error test")); + } catch (java.rmi.ServerError e) { + if (e.detail.getMessage().startsWith("Error test")) { + caughtExpected = true; + } else { + throw new Exception("HelloTest: throwError got " + e.detail.toString()); + } + } + if (!caughtExpected) { + throw new Exception("HelloTest: throwError failed"); + } + + nextTest( "testRemoteException" ) ; + caughtExpected = false; + + try { + remoteObject.throwRemoteException(new RemoteException("RemoteException test")); + } catch (java.rmi.ServerException e) { + if (e.detail.getMessage().startsWith("RemoteException test")) { + caughtExpected = true; + } else { + throw new Exception("HelloTest: throwRemoteException got " + e.detail.toString()); + } + } + if (!caughtExpected) { + throw new Exception("HelloTest: throwRemoteException failed"); + } + + nextTest( "testRuntimeException" ) ; + caughtExpected = false; + + try { + remoteObject.throwRuntimeException(new RuntimeException("RuntimeException test")); + } catch (java.rmi.ServerRuntimeException e) { + if (e.detail.getMessage().startsWith("RuntimeException test")) { + caughtExpected = true; + throw new Exception( + "HelloTest: throwRuntimeException got ServerRuntimeException on 1.2 vm"); + } else { + throw new Exception("HelloTest: throwRuntimeException got " + e.detail.toString()); + } + } catch (RuntimeException e) { + if (e.getMessage().startsWith("RuntimeException test")) { + caughtExpected = true; + } else { + throw new Exception("HelloTest: throwRuntimeException got " + e.toString()); + } + } + if (!caughtExpected) { + throw new Exception("HelloTest: throwRuntimeException failed"); + } + + nextTest( "testCharValue" ) ; + CharValue v1 = remoteObject.echoCharValue(new CharValue('%')); + if (v1.getValue() != '%') { + throw new Exception("HelloTest: echoCharValue failed."); + } + + CharValue v2 = remoteObject.echoCharValue(new CharValue('\u05d0')); + if (v2.getValue() != '\u05d0') { + throw new Exception("HelloTest: echoCharValue failed."); + } + + nextTest( "testObject" ) ; + String o1 = new String("An Object"); + Object o2 = remoteObject.echoObject(o1); + if (!o1.equals(o2)) { + throw new Exception("HelloTest: echoObject failed."); + } + + nextTest( "testProperties" ) ; + Properties props1 = new Properties(); + props1.put("one", v1); + props1.put("two", v2); + + Properties props2 = (Properties) remoteObject.echoObject(props1); + if (!equals(props1,props2)) { + throw new Exception("HelloTest: echoObject failed."); + } + + nextTest( "testSerializable" ) ; + Serializable s1 = remoteObject.echoSerializable(o1); + if (!s1.equals(o1)) { + throw new Exception("HelloTest: echoSerializable failed."); + } + + nextTest( "testPropsSerializable" ) ; + Properties props3 = (Properties) remoteObject.echoSerializable(props1); + if (!equals(props1,props3)) { + throw new Exception("HelloTest: echoSerializable failed."); + } + + if (!firstTest) + helper.pass() ; + } catch (Exception exc) { + System.out.println( "Test failed with exception " + exc ) ; + exc.printStackTrace() ; + helper.fail( exc ) ; + throw exc ; + } finally { + helper.done() ; + if (context != null) { + context.destroy(); + } + java.util.Hashtable myArgs = getArgs(); + myArgs.remove(LOCAL_SERVANTS_FLAG); + myArgs.remove(NO_LOCAL_STUBS_FLAG); + myArgs.remove(SKIP_RMIC_FLAG); + if (webServer != null) { + webServer.quit(); + } + Thread.sleep(500); // Wait for name server to go down. + } + } + + boolean equals (Properties one, Properties two) { + boolean result = false; + if (one.size() == two.size()) { + Enumeration e = one.keys(); + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + Object vOne = one.get(key); + Object vTwo = two.get(key); + + if (vOne != null && vTwo != null && !vOne.equals(vTwo)) { + break; + } + } + result = true; + } + return result; + } +} diff --git a/functional-tests/src/test/java/rmic/Hi.java b/functional-tests/src/test/java/rmic/Hi.java new file mode 100644 index 000000000..71750ade2 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Hi.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.io.IOException; + +public interface Hi extends Remote { + public String hi_0 () throws RemoteException, ClassNotFoundException; + public String hi_1 () throws RemoteException, ClassNotFoundException; + public String hi_2 () throws Exception; + public String hi_3 () throws IOException,ClassNotFoundException; + public String hi_4 (String input) throws IOException,ClassNotFoundException,HelloException; +} diff --git a/functional-tests/src/test/java/rmic/HiServant.java b/functional-tests/src/test/java/rmic/HiServant.java new file mode 100644 index 000000000..9a4d1c9d9 --- /dev/null +++ b/functional-tests/src/test/java/rmic/HiServant.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.io.IOException; + +public class HiServant implements Hi { + public String hi_0 () { + return "Hi!"; + } + + public String hi_1 () throws ClassNotFoundException { + throw new ClassNotFoundException(); + } + + public String hi_2 () throws Exception { + return "hi"; + } + + public String hi_3 () throws IOException,ClassNotFoundException { + return "hi"; + } + + public String hi_4 (String in) throws IOException,ClassNotFoundException,HelloException { + return "hi"; + } +} diff --git a/functional-tests/src/test/java/rmic/IDLEntityException.java b/functional-tests/src/test/java/rmic/IDLEntityException.java new file mode 100644 index 000000000..f3329e72b --- /dev/null +++ b/functional-tests/src/test/java/rmic/IDLEntityException.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class IDLEntityException extends java.rmi.RemoteException + implements org.omg.CORBA.portable.IDLEntity { +} diff --git a/functional-tests/src/test/java/rmic/IDLEntityValue.java b/functional-tests/src/test/java/rmic/IDLEntityValue.java new file mode 100644 index 000000000..a03cfea40 --- /dev/null +++ b/functional-tests/src/test/java/rmic/IDLEntityValue.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class IDLEntityValue implements org.omg.CORBA.portable.IDLEntity { + public int getFoo() {return 0;} + private IDLEntityValue(){} +} + diff --git a/functional-tests/src/test/java/rmic/IDLReferenceTest.java b/functional-tests/src/test/java/rmic/IDLReferenceTest.java new file mode 100644 index 000000000..26c88cae1 --- /dev/null +++ b/functional-tests/src/test/java/rmic/IDLReferenceTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +/* + * @test + */ +public class IDLReferenceTest extends IDLTest { + + public static final String[] ADDITIONAL_ARGS = {"-alwaysGenerate", + "-noValueMethods"}; + + public static final String CLASS_LIST_FILE = ".classlist"; + public static final String IDL_FILE = ".idl"; + public static final String IDL_REF_FILE = ".idlref"; + public static final String[] IGNORE_PREFIX = {"/*", " *", "*",}; + + private String[] classes = null; + + /** + * Return an array of fully qualified class names for which generation + * should occur. Return empty array if none. + */ + protected String[] getGenerationClasses () throws Throwable { + return getClasses(); + } + + /** + * Perform the test. + */ + protected void doTest () throws Throwable { + getClasses(); + for (int i = 0; i < classes.length; i++) { + compareUnorderedResources(classes[i],IDL_FILE,IDL_REF_FILE,IGNORE_PREFIX); + } + } + + /** + * Append additional (i.e. after -idl and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + return super.getAdditionalRMICArgs(ADDITIONAL_ARGS); + } + + private synchronized String[] getClasses () throws Throwable { + if (classes == null) { + classes = getResourceAsArray(getClass().getName(),CLASS_LIST_FILE,"#"); + } + return classes; + } + +} diff --git a/functional-tests/src/test/java/rmic/IDLTest.java b/functional-tests/src/test/java/rmic/IDLTest.java new file mode 100644 index 000000000..e05c4e20e --- /dev/null +++ b/functional-tests/src/test/java/rmic/IDLTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +/* + * @test + */ +public abstract class IDLTest extends RMICTest { + + /** + * Return an array of fully qualified class names for which generation + * should occur. Return empty array if none. + */ + protected abstract String[] getGenerationClasses () throws Throwable; + + /** + * Return the primary generator argument (e.g. "-iiop" or "-idl"). + */ + protected String getGeneratorArg () { + return "-idl"; + } + + /** + * Perform the test. + */ + protected abstract void doTest () throws Throwable; +} diff --git a/functional-tests/src/test/java/rmic/InnerTest.java b/functional-tests/src/test/java/rmic/InnerTest.java new file mode 100644 index 000000000..e26dcf3e7 --- /dev/null +++ b/functional-tests/src/test/java/rmic/InnerTest.java @@ -0,0 +1,412 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import test.Test; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.io.Serializable; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.glassfish.pfl.test.JUnitReportHelper; +import sun.rmi.rmic.iiop.Constants; +import sun.rmi.rmic.iiop.CompoundType; +import sun.rmi.rmic.iiop.ContextStack; +import sun.tools.java.ClassPath; + +public class InnerTest extends Test implements Constants { + + private ByteArrayOutputStream out = null; + private TestEnv env = null; + private ContextStack stack = null; + + /* + Outer Inner Name + --------------------- --------------------- ---- + Remote interface Remote interface RR + Remote interface interface RI + Remote interface Value RV + Remote interface Servant RS + Remote interface Abstract interface RA + + interface Remote interface IR + interface interface II + interface Value IV + interface Servant IS + interface Abstract interface IA + + Value Remote interface VR + Value interface VI + Value Value VV + Value Servant VS + Value Abstract interface VA + + Servant Remote interface SR + Servant interface SI + Servant Value SV + Servant Servant SS + Servant Abstract interface SA + + Abstract interface Remote interface AR + Abstract interface interface AI + Abstract interface Value AV + Abstract interface Servant AS + Abstract interface Abstract interface AA + */ + private static final String[] CASES = { + "RR","RI","RV","RS","RA", + "IR","II","IV","IS","IA", + "VR","VI","VV","VS","VA",//"SR", + "SI","SV","SS","SA", + "AR","AI","AV","AS","AA", + }; + private int typeCode(char c) { + switch (c) { + case 'R': return TYPE_REMOTE; + case 'I': return TYPE_NC_INTERFACE; + case 'V': return TYPE_VALUE; + case 'S': return TYPE_IMPLEMENTATION; + case 'A': return TYPE_ABSTRACT; + default: throw new Error("Unkown type."); + } + } + + private void checkType(String className, char typeInitial) { + env.reset(); + int typeCode = typeCode(typeInitial); + CompoundType type = (CompoundType) MapType.getType(className,stack); + + if (type == null) { + throw new Error(type + " is null"); + } + + if (!type.isType(typeCode)) { + throw new Error(type + " is not expected type. Found " + type.getTypeDescription()); + } + } + + + /** + * Run the test. + */ + public void run () { + JUnitReportHelper helper = new JUnitReportHelper( + this.getClass().getName() ) ; + + try { + + out = new ByteArrayOutputStream(); + env = new TestEnv(rmic.ParseTest.createClassPath(),out); + stack = new ContextStack(env); + + // Do the tests... + for (int i = 0; i < CASES.length; i++) { + helper.start( "test_" + CASES[i] ) ; + String outerClass = "rmic." + CASES[i]; + checkType(outerClass,CASES[i].charAt(0)); + checkType(outerClass + ".Inner",CASES[i].charAt(1)); + checkType(outerClass + ".Inner",CASES[i].charAt(1)); + helper.pass() ; + } + + env.shutdown(); + + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + helper.fail( e ) ; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + status = new Error("Caught " + out.toString()); + } finally { + helper.done() ; + } + } +} + +// Remote Outer... + +interface RR extends Remote { + public String hello () throws RemoteException; + public interface Inner extends Remote { + public String hello () throws RemoteException; + } + public static interface Nested extends Remote { + public String hello () throws RemoteException; + } +} + +interface RI extends Remote { + public String hello () throws RemoteException; + public interface Inner { + public String hello (); + } + public static interface Nested { + public String hello (); + } +} + +interface RV extends Remote { + public String hello () throws RemoteException; + public class Inner implements Serializable { + public String hello; + } + public static class Nested implements Serializable { + public String hello; + } +} + +interface RS extends Remote { + public String hello () throws RemoteException; + public class Inner implements RS { + public Inner () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} +} +public static class Nested implements RS { + public Nested () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} +} +} + +interface RA extends Remote { + public String hello () throws RemoteException; + public interface Inner { + public String hello () throws RemoteException; + } + public static interface Nested { + public String hello () throws RemoteException; + } +} + +// Interface Outer... + +interface IR { + public String hello (); + public interface Inner extends Remote { + public String hello () throws RemoteException; + } + public static interface Nested extends Remote { + public String hello () throws RemoteException; + } +} + +interface II { + public String hello (); + public interface Inner { + public String hello (); + } + public static interface Nested { + public String hello (); + } +} + +interface IV { + public String hello (); + public class Inner implements Serializable { + public String hello; + } + public static class Nested implements Serializable { + public String hello; + } +} + +interface IS { + public String hello (); + public class Inner implements RS { + public Inner () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} +} +public static class Nested implements RS { + public Nested () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} +} +} + +interface IA { + public String hello (); + public interface Inner { + public String hello () throws RemoteException; + } + public static interface Nested { + public String hello () throws RemoteException; + } +} + + +// Value Outer... + +class VR implements Serializable { + public String hello; + public interface Inner extends Remote { + public String hello () throws RemoteException; + } + public static interface Nested extends Remote { + public String hello () throws RemoteException; + } +} + +class VI implements Serializable { + public String hello; + public interface Inner { + public String hello (); + } + public static interface Nested { + public String hello (); + } +} + +class VV implements Serializable { + public String hello; + public class Inner implements Serializable { + public String hello; + } + public static class Nested implements Serializable { + public String hello; + } +} + +class VS implements Serializable { + public String hello; + public class Inner implements RR { + public Inner () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + } + public static class Nested implements RR { + public Nested () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + } +} + +class VA implements Serializable { + public String hello; + public interface Inner { + public String hello () throws RemoteException; + } + public static interface Nested { + public String hello () throws RemoteException; + } +} + +// Servant Outer... + +class SR implements SRInner { + public SR () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + public static interface Nested extends Remote { + public String hello () throws RemoteException; + } +} + +class SI implements RR { + public SI () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + public interface Inner { + public String hello (); + } + public static interface Nested { + public String hello (); + } +} + +class SV implements RR { + public SV () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + + // Note: Changed to static to avoid error caused by + // rmic.SV data member and constructor... + + static public class Inner implements Serializable { + public String hello; + } + public static class Nested implements Serializable { + public String hello; + } +} + +class SS implements RR { + public SS () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + public class Inner implements RR { + public Inner () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + } + public static class Nested implements RR { + public Nested () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + } +} + +class SA implements RR { + public SA () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + public interface Inner { + public String hello () throws RemoteException; + } + public static interface Nested { + public String hello () throws RemoteException; + } +} + + +// Abstract Outer... + +interface AR { + public String hello () throws RemoteException; + public interface Inner extends Remote { + public String hello () throws RemoteException; + } + public static interface Nested extends Remote { + public String hello () throws RemoteException; + } +} + +interface AI { + public String hello () throws RemoteException; + public interface Inner { + public String hello (); + } + public static interface Nested { + public String hello (); + } +} + +interface AV { + public String hello () throws RemoteException; + public class Inner implements Serializable { + public String hello; + } + public static class Nested implements Serializable { + public String hello; + } +} + +interface AS { + public String hello () throws RemoteException; + public class Inner implements RS { + public Inner () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + } + public static class Nested implements RS { + public Nested () throws RemoteException {} + public String hello () throws RemoteException {return "Hello";} + } +} + +interface AA { + public String hello () throws RemoteException; + public interface Inner { + public String hello () throws RemoteException; + } + public static interface Nested { + public String hello () throws RemoteException; + } +} diff --git a/functional-tests/src/test/java/rmic/InvalidNC.java b/functional-tests/src/test/java/rmic/InvalidNC.java new file mode 100644 index 000000000..1a1de6c97 --- /dev/null +++ b/functional-tests/src/test/java/rmic/InvalidNC.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class InvalidNC { + public static final char J_bar = 1; + public static final char _bar = 2; +} diff --git a/functional-tests/src/test/java/rmic/Left.java b/functional-tests/src/test/java/rmic/Left.java new file mode 100644 index 000000000..43b36c1b2 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Left.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface Left extends Base { + void left() throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/LocalHello.java b/functional-tests/src/test/java/rmic/LocalHello.java new file mode 100644 index 000000000..2976f9996 --- /dev/null +++ b/functional-tests/src/test/java/rmic/LocalHello.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import javax.rmi.CORBA.Stub; + +public interface LocalHello extends java.rmi.Remote { + public String sayHello(String to) throws java.rmi.RemoteException; + public String echoString(String it) throws java.rmi.RemoteException; + public Object echoObject(Object it) throws java.rmi.RemoteException; + public int identityHash(Object it) throws java.rmi.RemoteException; + public int[] identityHash(Object a, Object b, Object c) throws java.rmi.RemoteException; + + public test.Hello echoHello (test.Hello in) throws java.rmi.RemoteException; + public rmic.Hello echoHello (rmic.Hello in) throws java.rmi.RemoteException; + public void argNamesClash(int in, + int _in, + int out, + int _out, + int so, + int exCopy, + int copies, + int method, + int reply, + int ex) throws java.rmi.RemoteException; + + public Base newServant() throws java.rmi.RemoteException; + + public String testPrimTypes(String arg0, + double arg1, + float arg2, + String arg3, + boolean arg4, + Object arg5, + String arg6) throws java.rmi.RemoteException; + + public Object echoString(Object value1, String str, Object value2) throws java.rmi.RemoteException; + + public Object echoArg1(int arg0, Object arg1) throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/LocalHelloServant.java b/functional-tests/src/test/java/rmic/LocalHelloServant.java new file mode 100644 index 000000000..cc090b99d --- /dev/null +++ b/functional-tests/src/test/java/rmic/LocalHelloServant.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import com.sun.corba.ee.impl.util.JDKBridge; +import javax.rmi.CORBA.Stub; +import org.omg.CORBA.BAD_OPERATION; +import java.rmi.RemoteException; +import java.rmi.MarshalException; + +public class LocalHelloServant extends javax.rmi.PortableRemoteObject implements LocalHello { + + public LocalHelloServant() throws java.rmi.RemoteException { + JDKBridge.setLocalCodebase(null); + } + + public String sayHello (String to) throws java.rmi.RemoteException { + return "Hello " + to; + } + + public String echoString(String it) throws java.rmi.RemoteException { + return it; + } + + public Object echoObject(Object it) throws java.rmi.RemoteException { + return it; + } + + public int identityHash(Object it) throws java.rmi.RemoteException { + return System.identityHashCode(it); + } + + public int[] identityHash(Object a, Object b, Object c) throws java.rmi.RemoteException { + int[] result = new int[3]; + result[0] = System.identityHashCode(a); + result[1] = System.identityHashCode(b); + result[2] = System.identityHashCode(c); + return result; + } + + public test.Hello echoHello (test.Hello in) throws java.rmi.RemoteException { + return in; + } + + public rmic.Hello echoHello (rmic.Hello in) throws java.rmi.RemoteException { + return in; + } + + public void argNamesClash(int in, + int _in, + int out, + int _out, + int so, + int exCopy, + int copies, + int method, + int reply, + int ex) throws java.rmi.RemoteException { + + } + + public Base newServant() throws java.rmi.RemoteException { + String codebase = JDKBridge.getLocalCodebase(); + if (codebase != null) { + throw new java.rmi.RemoteException("localCodebase = "+codebase); + } + + return new BaseImpl(); + } + + public String testPrimTypes(String arg0, + double arg1, + float arg2, + String arg3, + boolean arg4, + Object arg5, + String arg6) throws java.rmi.RemoteException { + return "help"; + } + + public Object echoString(Object value1, String str, Object value2) throws java.rmi.RemoteException { + if (!(value1 instanceof RemoteException)) { + throw new RemoteException("value1 not RemoteException. Is "+value1.getClass()); + } + if (!(value2 instanceof MarshalException)) { + throw new RemoteException("value2 not MarshalException. Is "+value2.getClass()); + } + + return str; + } + + public Object echoArg1(int arg0, Object arg1) throws java.rmi.RemoteException { + return arg1; + } + +} diff --git a/functional-tests/src/test/java/rmic/LocalStubTest.java b/functional-tests/src/test/java/rmic/LocalStubTest.java new file mode 100644 index 000000000..e1d971a34 --- /dev/null +++ b/functional-tests/src/test/java/rmic/LocalStubTest.java @@ -0,0 +1,314 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import test.ServantContext; +import test.RemoteTest; +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Util; +import javax.naming.Context; +import org.omg.CORBA.ORB; +import org.omg.CORBA.portable.ServantObject; +import org.omg.CORBA.portable.Delegate; +import org.omg.CORBA.BAD_OPERATION; +import java.io.File; +import com.sun.corba.ee.impl.util.JDKBridge; +import java.rmi.MarshalException; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import org.glassfish.pfl.test.JUnitReportHelper; + +/* + * @test + */ +public class LocalStubTest extends RemoteTest { + + private static final String publishName = "HelloServer"; + private static final String servantInterface = "rmic.LocalHello"; + private static final String servantClass = "rmic.LocalHelloServant"; + private static final String[] compileEm = { servantClass, + servantInterface, + "rmic.BaseImpl"}; + private File[] classFiles = {null,null}; + /** + * Return an array of fully qualified remote servant class + * names for which ties/skels need to be generated. Return + * empty array if none. + */ + protected String[] getRemoteServantClasses () { + /* + + // If we can, delete the rmic.LocalHello and + // rmic.LocalHelloServant class files so that + // rmic will compile them. This will ensure that + // real argument names will be used and tests + // that the generated variable names will not + // clash... + + ClassPath path = null; + try { + path = ParseTest.createClassPath(); + for (int i = 0; i < 2; i++) { + ClassFile cls = path.getFile(compileEm[i].replace('.',File.separatorChar) + ".class"); + if (cls != null && !cls.isZipped()) { + File file = new File(cls.getPath()); + File newName = new File(cls.getPath()+"X"); + if (file.renameTo(newName)) { + classFiles[i] = newName; + } + } + } + + path.close(); + } catch (Exception e) {} + + */ + + return compileEm; + } + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + if (iiop) { + String[] ourArgs = {"-always", "-keep"}; + return super.getAdditionalRMICArgs(ourArgs); + } else { + return super.getAdditionalRMICArgs(currentArgs); + } + } + + private final JUnitReportHelper helper ; + private boolean first = true ; + + public LocalStubTest() { + helper = new JUnitReportHelper( this.getClass().getName() ) ; + } + + private void newTest( String name ) { + if (first) + first = false ; + else + helper.pass() ; + + helper.start( name ) ; + } + + /** + * Perform the test. + * @param context The context returned by getServantContext(). + */ + public void doTest (ServantContext context) throws Throwable { + String currentCodebase = JDKBridge.getLocalCodebase(); + + try { + newTest( "startServant" ) ; + // Start up our servant. (The 'iiop' flag is set to true by RemoteTest + // unless the -jrmp flag was used). + Remote remote = context.startServant(servantClass,publishName,true,iiop); + + if (remote == null) { + throw new Exception ("Could not start servant: " + servantClass); + } + + newTest( "remoteRefCorrectResponse" ) ; + LocalHello remoteRef = (LocalHello) PortableRemoteObject.narrow(remote,LocalHello.class); + + if (!remoteRef.sayHello("LocalStubTest").equals("Hello LocalStubTest")) { + throw new Exception("Could not communicate with servant."); + } + + newTest( "remoteRefIsRemoteStub" ) ; + // Make sure that remoteRef is really a remote stub... + Delegate del = StubAdapter.getDelegate( remoteRef ) ; + ORB orb = del.orb((org.omg.CORBA.Object)remoteRef); + ServantObject so = del.servant_preinvoke( + (org.omg.CORBA.Object)remoteRef,"method",LocalHello.class); + if (so != null) { + throw new Exception("Got local stub for remoteRef."); + } + + newTest( "makeLocalServant" ) ; + // Make a local servant, connect it and convert it to a stub... + LocalHelloServant localImpl = new LocalHelloServant(); + PortableRemoteObject.connect(localImpl,remoteRef); + Remote localRef1 = PortableRemoteObject.toStub(localImpl); + if (localRef1 == null) { + throw new Exception ("toStub() failed"); + } + + // Now make sure it is really a local stub by calling + // servant_preinvoke and comparing the result to our + // local servant... + + newTest( "localRefIsLocal" ) ; + del = StubAdapter.getDelegate( localRef1 ) ; + so = del.servant_preinvoke((org.omg.CORBA.Object)localRef1, + "method",LocalHello.class); + if (so == null) { + throw new Exception("servant_preinvoke() returned null"); + } + if (so.servant != localImpl) { + throw new Exception("servant_preinvoke() returned wrong servant"); + } + + // Publish and retrieve localImpl to/from name service... + newTest( "unmarshaledLocalRefStillLocal" ) ; + Context nameContext = context.getNameContext(); + nameContext.rebind("localRef2",localImpl); + Object temp = nameContext.lookup("localRef2"); + + LocalHello localRef2 = (LocalHello) PortableRemoteObject.narrow(temp,LocalHello.class); + + // Now make sure it is local... + + del = StubAdapter.getDelegate( localRef2 ) ; + so = del.servant_preinvoke( (org.omg.CORBA.Object)localRef2, + "method",LocalHello.class); + if (so == null) { + throw new Exception("servant_preinvoke() returned null"); + } + if (so.servant != localImpl) { + throw new Exception("servant_preinvoke() returned wrong servant"); + } + + // Now make sure local copying gets done correctly... + newTest( "localCopyobjectOK" ) ; + String localString1 = "one"; + RemoteException localValue1 = new RemoteException(); + BAD_OPERATION localValue2 = new BAD_OPERATION(); + MarshalException localValue3 = new MarshalException("test"); + int localString1Hash = System.identityHashCode(localString1); + int localValue1Hash = System.identityHashCode(localValue1); + int localValue2Hash = System.identityHashCode(localValue2); + int[] primitiveArray1 = {3,7,9}; + char[][] primitiveArray2 = {{'a'},{'b'},{'c','d'}}; + + if (localRef2.echoArg1(3,localValue3) == localValue3) { + throw new Exception("localValue3 not copied!"); + } + + if (localRef2.echoString(localValue1,localString1,localValue3) == localString1) { + throw new Exception("localString1 not copied!"); + } + + if (localRef2.echoObject(localValue1) == localValue1) { + throw new Exception("localValue1 not copied!"); + } + + int[] pArray1Copy = (int[])localRef2.echoObject(primitiveArray1); + if (pArray1Copy == primitiveArray1) { + throw new Exception("primitiveArray1 not copied!"); + } + if (primitiveArray1[0] != pArray1Copy[0] || + primitiveArray1[1] != pArray1Copy[1] || + primitiveArray1[2] != pArray1Copy[2]) { + throw new Exception("primitiveArray1 not copied *correctly*!"); + } + + char[][] pArray2Copy = (char[][])localRef2.echoObject(primitiveArray2); + if (pArray2Copy == primitiveArray2) { + throw new Exception("primitiveArray2 not copied!"); + } + if (primitiveArray2[0][0] != pArray2Copy[0][0] || + primitiveArray2[1][0] != pArray2Copy[1][0] || + primitiveArray2[2][0] != pArray2Copy[2][0] || + primitiveArray2[2][1] != pArray2Copy[2][1]) { + throw new Exception("primitiveArray2 not copied *correctly*!"); + } + + if (localRef2.identityHash(localValue1) == localValue1Hash) { + throw new Exception("localValue1Hash hash == localValue1Hash!"); + } + + int[] hash = localRef2.identityHash(localString1,localString1,localString1); + + hash = localRef2.identityHash(localString1,localString1,localValue1); + if (hash[0] == localString1Hash || + hash[1] == localString1Hash || + hash[2] == localValue1Hash) { + throw new Exception("string,string,value did not get copies!"); + } + + hash = localRef2.identityHash(localValue1,localValue1,localValue2); + if (hash[0] == localValue1Hash || + hash[1] == localValue1Hash || + hash[2] == localValue2Hash) { + throw new Exception("string,string,value did not get copies!"); + } + + if (!StubAdapter.isStub(localRef2.echoObject(new LocalHelloServant()))) { + throw new Exception("localRef2.echoObject(impl) did not return a stub!"); + } + + if (!StubAdapter.isStub(remoteRef.echoObject(new LocalHelloServant()))) { + throw new Exception("remoteRef.echoObject(impl) did not return a stub!"); + } + + RemoteException[] array2 = {localValue1,localValue1}; + if (Util.copyObjects(array2,orb) == array2) { + throw new Exception ("Util.copyObjects(array2) == array2"); + } + + // Unexport our localImpl and make sure that stub is invalid... + newTest( "unexportLocalObject" ) ; + PortableRemoteObject.unexportObject(localImpl); + boolean failed = false; + try { + localRef2.echoString("hi"); + } catch (Exception e) { + failed = true; + } + if (!failed) { + throw new Exception("localRef2.echoString() succeeded on unexported impl."); + } + + del = StubAdapter.getDelegate( localRef2 ) ; + so = del.servant_preinvoke( (org.omg.CORBA.Object)localRef2, + "method",LocalHello.class); + if (so != null) { + throw new Exception("servant_preinvoke() did not return null"); + } + + if (!first) + helper.pass() ; + } catch (Throwable thr) { + helper.fail( thr ) ; + } finally { + helper.done() ; + // Put the codebase back... + JDKBridge.setLocalCodebase(currentCodebase); + + // Rename our class files back to the correct names... + for (int i = 0; i < 2; i++) { + File current = classFiles[i]; + boolean error = false; + if (current != null) { + String path = current.getPath(); + String origPath = path.substring(0,path.length()-1); + File orig = new File(origPath); + if (!current.renameTo(orig)) { + System.out.println("Failed to rename "+path+" to "+origPath); + error = true; + } + } + if (error) { + throw new Error("Rename failed."); + } + } + } + } +} diff --git a/functional-tests/src/test/java/rmic/MangleMethods.java b/functional-tests/src/test/java/rmic/MangleMethods.java new file mode 100644 index 000000000..c03d305ab --- /dev/null +++ b/functional-tests/src/test/java/rmic/MangleMethods.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.MarshalException; +import java.util.Hashtable; +import java.io.IOException; + +public interface MangleMethods extends Remote { + + // Methods that should be attributes... + + int getFoo () throws RemoteException; + int getAB () throws RemoteException; + boolean isX () throws RemoteException; + char getChar() throws RemoteException; + void setChar(char c) throws RemoteException, RuntimeException; + long getLong() throws RemoteException, ClassCastException; // RuntimeException subclass. + int getSomething() throws RemoteException, MarshalException; // RemoteException subclass. + + // Methods that look like they should be attributes + // but aren't... + + byte getByte () throws Exception; // Invalid exception. + + boolean is () throws RemoteException; // No property name + + void setZ(int z) throws RemoteException; // No getter + + boolean isLong() throws RemoteException; // Same name as getLong, different type. + + boolean isShort() throws RemoteException; // getter... + void setShort(short s) throws RemoteException; // ... setter different types... + + int getOther(char i) throws RemoteException; // Argument. + + void getIt() throws RemoteException; // void return. + + int getY() throws RemoteException; // getter... + void setY() throws RemoteException; // ... setter with void arg + + // Miscellaneous... + + boolean isFloat() throws RemoteException; // getter... + void setFloat(float f) throws RemoteException; // ... setter different types ... + float getFloat() throws RemoteException; // ... set/get are attrs, 'is' isn't. + + boolean isEmpty() throws RemoteException; // Looks like a case-collision... + boolean IsEmpty() throws RemoteException; // ... but isn't. + + int doAJob() throws RemoteException; // Case collision... + int doAjob() throws RemoteException; // ... but not attributes. + + boolean isAJob() throws RemoteException; // Case collision... + boolean getAjob() throws RemoteException; // ... and are (different) attributes. + + byte getfred() throws RemoteException; // Not case collision (5.4.3.4 mangling)... + void setFred(byte b) throws RemoteException; // ... and are attribute pair. + + int _do\u01c3It$() throws RemoteException; // Methods with illegal chars... + int _do\u01c3It$(int i) throws RemoteException; // ... and overloaded versions... + int _do\u01c3It$(char c) throws RemoteException; // ... + + int getFooBar() throws RemoteException; // Attribute... + int fooBar() throws RemoteException; // ... and colliding method. + + // IDL Keyword collisions... + + int typeDef () throws RemoteException; // Method name is keyword + int getDefault () throws RemoteException; // Attribute name is keyword. + int getObject () throws RemoteException; // Attribute name is keyword. + int getException () throws RemoteException; // Attribute name is keyword. + + + // Assertion mechanism... + + class Asserts { + + private static Hashtable map = null; + + public static String[] getAsserts (String methodSig) { + + if (map == null) { + map = new Hashtable(); + for (int i = 0; i < ASSERTS.length; i++) { + map.put(ASSERTS[i][0],new Integer(i)); + } + } + + Integer theIndex = (Integer)map.get(methodSig); + + if (theIndex == null) { + throw new Error("Assert not found for " + methodSig); + } + + return ASSERTS[theIndex.intValue()]; + } + + private static String[][] ASSERTS = { + + // Method Signature Kind Attribute Name Wire Name + // ---------------------- ----------- ------------------- ------------------------- + {"int getFoo()", "GET", "foo", "_get_foo"}, + {"int getAB()", "GET", "AB", "_get_AB"}, + {"boolean isX()", "IS", "x", "_get_x"}, + {"char getChar()", "GET_RW", "_char", "_get_char"}, + {"void setChar(char)", "SET", "_char", "_set_char"}, + {"byte getByte()", "NONE", null, "getByte"}, + {"boolean is()", "NONE", null, "is"}, + {"void setZ(int)", "NONE", null, "setZ"}, + {"boolean isLong()", "NONE", null, "isLong"}, + {"long getLong()", "GET", "_long", "_get_long"}, + {"boolean isShort()", "NONE", null, "isShort"}, + {"void setShort(short)", "NONE", null, "setShort"}, + {"int getSomething()", "GET", "something", "_get_something"}, + {"int getOther(char)", "NONE", null, "getOther"}, + {"void getIt()", "NONE", null, "getIt"}, + {"int getY()", "GET", "y", "_get_y"}, + {"void setY()", "NONE", null, "setY"}, + {"boolean isFloat()", "NONE", null, "isFloat"}, + {"float getFloat()", "GET_RW", "_float", "_get_float"}, + {"void setFloat(float)", "SET", "_float", "_set_float"}, + {"boolean isEmpty()", "IS", "empty", "_get_empty"}, + {"boolean IsEmpty()", "NONE", null, "IsEmpty"}, + {"int doAJob()", "NONE", null, "doAJob_2_3"}, + {"int doAjob()", "NONE", null, "doAjob_2"}, + {"boolean isAJob()", "IS", "AJob_0_1", "_get_AJob_0_1"}, + {"boolean getAjob()", "GET", "ajob_", "_get_ajob_"}, + {"byte getfred()", "GET", "fred", "_get_fred"}, + {"void setFred(byte)", "NONE", null, "setFred"}, + {"int _do\u01c3It$()", "NONE", null, "J_doU01C3ItU0024__"}, + {"int _do\u01c3It$(int)", "NONE", null, "J_doU01C3ItU0024__long"}, + {"int _do\u01c3It$(char)", "NONE", null, "J_doU01C3ItU0024__wchar"}, + {"int getFooBar()", "GET", "fooBar__", "_get_fooBar__"}, + {"int fooBar()", "NONE", null, "fooBar"}, + {"int typeDef()", "NONE", null, "_typeDef"}, + {"int getDefault()", "GET", "_default", "_get_default"}, + {"int getObject()", "GET", "_object", "_get_object"}, + {"int getException()", "GET", "_exception", "_get_exception"}, + }; + } +} diff --git a/functional-tests/src/test/java/rmic/MangleMethodsFail1.java b/functional-tests/src/test/java/rmic/MangleMethodsFail1.java new file mode 100644 index 000000000..8133b8dde --- /dev/null +++ b/functional-tests/src/test/java/rmic/MangleMethodsFail1.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MangleMethodsFail1 extends Remote { + int getFoo() throws RemoteException; + int foo() throws RemoteException; + int foo__() throws RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/MangleMethodsFail2.java b/functional-tests/src/test/java/rmic/MangleMethodsFail2.java new file mode 100644 index 000000000..17555403a --- /dev/null +++ b/functional-tests/src/test/java/rmic/MangleMethodsFail2.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MangleMethodsFail2 extends Remote { + boolean getBar() throws RemoteException; + boolean isBar() throws RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/MangleMethodsFail3.java b/functional-tests/src/test/java/rmic/MangleMethodsFail3.java new file mode 100644 index 000000000..28caad9e8 --- /dev/null +++ b/functional-tests/src/test/java/rmic/MangleMethodsFail3.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MangleMethodsFail3 extends Remote { + void foo() throws RemoteException; + void foo(int a) throws RemoteException; + void foo__long() throws RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/MapType.java b/functional-tests/src/test/java/rmic/MapType.java new file mode 100644 index 000000000..5a21702c7 --- /dev/null +++ b/functional-tests/src/test/java/rmic/MapType.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import sun.rmi.rmic.Names; +import sun.rmi.rmic.iiop.Type; +import sun.rmi.rmic.iiop.CompoundType; +import sun.rmi.rmic.iiop.ContextStack; +import sun.tools.java.ClassPath; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.Identifier; + +public class MapType extends CompoundType { + + public static boolean resetTypesForEach = false; + + private MapType() { + super(null,0,null); + } + + public String getTypeDescription () { + return null; + } + + + public int getCount () { + return countTypes(); + } + + public static Type getType (String className, + ContextStack stack) { + + if (MapType.resetTypesForEach) { + stack.getEnv().reset(); + } + + Identifier classID = Identifier.lookup(className); + classID = stack.getEnv().resolvePackageQualifiedName(classID); + classID = Names.mangleClass(classID); + ClassDeclaration decl = stack.getEnv().getClassDeclaration(classID); + return makeType(decl.getType(), null, stack); + } + + public static void main (String[] args) { + + int status = 0; + try { + resetTypesForEach = Boolean.valueOf(args[0]).booleanValue(); + int offset = Integer.parseInt(args[1]); + TestEnv env = new TestEnv(new ClassPath(args[2])); + ContextStack stack = new ContextStack(env); + + for (int i = 3; i < args.length; i++) { + String className = args[i]; + try { + env.reset(); + int line = offset + i - 2; + String num = Integer.toString(line); + if (line < 10) num = " " + num; + else if (line < 100) num = " " + num; + else if (line < 1000) num = " " + num; + else if (line < 10000) num = " " + num; + System.out.print(num + " - " + className); + + Type result = getType(className,stack); + + if (result != null) { + if (env.nerrors > 0) { + status = 1; + System.out.println("!!!Failure: result = " + result.getTypeDescription()); + } else { + System.out.println(" = " + result.getTypeDescription()); + } + } + } catch (Throwable e) { + if (e instanceof ThreadDeath) throw (ThreadDeath) e; + status = 1; + System.out.println("!!!Exception: " + className + " caught " + e); + } + } + } catch (Throwable e) { + System.out.println("!!!Exception: caught " + e); + status = 1; + } + + System.exit(status); + } +} diff --git a/functional-tests/src/test/java/rmic/MethodOverload1.java b/functional-tests/src/test/java/rmic/MethodOverload1.java new file mode 100644 index 000000000..bb4c8c58b --- /dev/null +++ b/functional-tests/src/test/java/rmic/MethodOverload1.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class MethodOverload1 { + public void foo(){} + public void foo(int i){} + public void foo(java.rmi.RemoteException e){} + + public static final String[] IDL_NAMES = { + "create", + "foo__", + "foo__long", + "foo__java_rmi_RemoteException", + }; + + public static final boolean[] CONSTRUCTOR = { + true, + false, + false, + false, + }; +} + +class MethodOverload2 { + public void create(){} + + public static final String[] IDL_NAMES = { + "create__", + "create", + }; + public static final boolean[] CONSTRUCTOR = { + true, + false, + }; +} + +class MethodOverload3 { + public void create(){} + public void create(boolean e){} + + public static final String[] IDL_NAMES = { + "create", + "create__", + "create__boolean", + }; + public static final boolean[] CONSTRUCTOR = { + true, + false, + false, + }; +} + +class MethodOverload4 { + + public MethodOverload4() {} + public MethodOverload4(char i) {} + + public static final String[] IDL_NAMES = { + "create__", + "create__wchar", + }; + + public static final boolean[] CONSTRUCTOR = { + true, + true, + }; +} + +class MethodOverload5 { + + public MethodOverload5() {} + public MethodOverload5(char i) {} + public void create(){} + + public static final String[] IDL_NAMES = { + "create__", + "create__wchar", + "create", + }; + + public static final boolean[] CONSTRUCTOR = { + true, + true, + false, + }; +} + +class MethodOverload6 { + + public MethodOverload6() {} + public MethodOverload6(char i) {} + public void create(){} + public void create(char i){} + + public static final String[] IDL_NAMES = { + "create____", + "create__wchar__", + "create__", + "create__wchar", + }; + + public static final boolean[] CONSTRUCTOR = { + true, + true, + false, + false, + }; +} diff --git a/functional-tests/src/test/java/rmic/NCIOException.java b/functional-tests/src/test/java/rmic/NCIOException.java new file mode 100644 index 000000000..785ffbd50 --- /dev/null +++ b/functional-tests/src/test/java/rmic/NCIOException.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class NCIOException extends java.io.IOException { + char J_foo; + char _foo; +} diff --git a/functional-tests/src/test/java/rmic/NCRemoteException.java b/functional-tests/src/test/java/rmic/NCRemoteException.java new file mode 100644 index 000000000..db47f4ff2 --- /dev/null +++ b/functional-tests/src/test/java/rmic/NCRemoteException.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class NCRemoteException extends java.rmi.RemoteException { + public static final char J_bar = 1; + + public String getHelp() {return "HELP!";} + + char J_foo; + char _foo; +} diff --git a/functional-tests/src/test/java/rmic/NCRuntimeException.java b/functional-tests/src/test/java/rmic/NCRuntimeException.java new file mode 100644 index 000000000..2bd39afbd --- /dev/null +++ b/functional-tests/src/test/java/rmic/NCRuntimeException.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class NCRuntimeException extends java.lang.RuntimeException { + char J_foo; + char _foo; +} diff --git a/functional-tests/src/test/java/rmic/NoMethods.java b/functional-tests/src/test/java/rmic/NoMethods.java new file mode 100644 index 000000000..261a4ce62 --- /dev/null +++ b/functional-tests/src/test/java/rmic/NoMethods.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface NoMethods extends java.rmi.Remote { +} diff --git a/functional-tests/src/test/java/rmic/NoMethodsImpl.java b/functional-tests/src/test/java/rmic/NoMethodsImpl.java new file mode 100644 index 000000000..2b4965090 --- /dev/null +++ b/functional-tests/src/test/java/rmic/NoMethodsImpl.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class NoMethodsImpl implements NoMethods { + public NoMethodsImpl () throws java.rmi.RemoteException {} +} diff --git a/functional-tests/src/test/java/rmic/NonRemoteOuterRemoteInner.java b/functional-tests/src/test/java/rmic/NonRemoteOuterRemoteInner.java new file mode 100644 index 000000000..c70aca7de --- /dev/null +++ b/functional-tests/src/test/java/rmic/NonRemoteOuterRemoteInner.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public interface NonRemoteOuterRemoteInner { + + public String hello(); + + public interface Inner extends java.rmi.Remote { + public String innerRemoteHello () throws java.rmi.RemoteException; + } +} diff --git a/functional-tests/src/test/java/rmic/ObjectByValue.java b/functional-tests/src/test/java/rmic/ObjectByValue.java new file mode 100644 index 000000000..4738e0c85 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ObjectByValue.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.lang.String; + +public class ObjectByValue implements java.io.Serializable { + + public static int foo = 1; + public static final int FOO = 3; + + int value1; + int value2; + private String str1; + String str2; + private transient PrivateValue1 transientPrivate = null; + private static PrivateValue2 staticPrivate = new PrivateValue2(); + private static final PrivateValue3 constantPrivate = new PrivateValue3(); + + //private PrivateValue4 memberPrivate; // Should not be allowed by rmic. + + + public ObjectByValue(int val1, int val2, String str1, String str2 ) + { + this.value1 = val1; + this.value2 = val2; + this.str1 = str1; + this.str2 = str2; + } + + public String toString () { + return "{" + value1 + ", " + value2 + ", " + str1 + ", " + str2 + "}"; + } + + public boolean equals (Object right) { + if (right instanceof ObjectByValue) { + ObjectByValue other = (ObjectByValue)right; + return value1 == other.value1 && + value2 == other.value2 && + str1.equals(other.str1) && + str2.equals(other.str2); + } else { + return false; + } + } + + public int getValue1() { return value1; } + public int getValue2() { return value2; } + + public String getString1() { return str1; } + public String getString2() { return str2; } + + public synchronized void checkPrivate(PrivateValue1 it) { + } +} + +class PrivateValue1 implements java.io.Serializable { + private int value = 1; +} + +class PrivateValue2 implements java.io.Serializable { + private int value = 2; +} + +class PrivateValue3 implements java.io.Serializable { + private int value = 3; +} + +class PrivateValue4 implements java.io.Serializable { + private int value = 4; +} diff --git a/functional-tests/src/test/java/rmic/OnlyRemoteServant.java b/functional-tests/src/test/java/rmic/OnlyRemoteServant.java new file mode 100644 index 000000000..b9f5e7044 --- /dev/null +++ b/functional-tests/src/test/java/rmic/OnlyRemoteServant.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +public class OnlyRemoteServant extends PortableRemoteObject + implements Remote { + public OnlyRemoteServant () throws RemoteException { + } + + public String message (){ + return "Hello World!"; + } +} diff --git a/functional-tests/src/test/java/rmic/ParseTest.java b/functional-tests/src/test/java/rmic/ParseTest.java new file mode 100644 index 000000000..2745f4972 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ParseTest.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import sun.rmi.rmic.iiop.Constants; +import sun.tools.java.ClassPath; +import java.lang.reflect.Method; + +import corba.framework.TestngRunner ; + +public class ParseTest extends test.Test implements Constants { + public static ClassPath createClassPath() { + + String path = System.getProperty("java.class.path"); + + // Use reflection to call sun.rmi.rmic.BatchEnvironment.createClassPath(path) + // so that we can leave classes.zip at the front of the classpath for + // the build environment. Don't ask. + + try { + Class env = sun.rmi.rmic.BatchEnvironment.class; + Method method = env.getMethod("createClassPath",new Class[]{java.lang.String.class}); + return (ClassPath) method.invoke(null,new Object[]{path}); + } catch (Throwable e) { + if (e instanceof ThreadDeath) + throw (ThreadDeath)e; + throw new Error("ParseTest.createClassPath() caught "+e); + } + } + + public void run( ) { + TestngRunner runner = new TestngRunner() ; + runner.registerClass( TestExecutor.class ) ; + runner.run() ; + if (runner.hasFailure()) + status = new Error( "test failed" ) ; + } +} diff --git a/functional-tests/src/test/java/rmic/PassIDLEntityException.java b/functional-tests/src/test/java/rmic/PassIDLEntityException.java new file mode 100644 index 000000000..df2ede739 --- /dev/null +++ b/functional-tests/src/test/java/rmic/PassIDLEntityException.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface PassIDLEntityException extends java.rmi.Remote { + void method(IDLEntityException arg) throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/PassImplInterface.java b/functional-tests/src/test/java/rmic/PassImplInterface.java new file mode 100644 index 000000000..56c49a7d2 --- /dev/null +++ b/functional-tests/src/test/java/rmic/PassImplInterface.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface PassImplInterface extends java.rmi.Remote { + void method(BaseImpl arg) throws java.rmi.RemoteException; +} + diff --git a/functional-tests/src/test/java/rmic/PassImplValue.java b/functional-tests/src/test/java/rmic/PassImplValue.java new file mode 100644 index 000000000..4e1514e9c --- /dev/null +++ b/functional-tests/src/test/java/rmic/PassImplValue.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class PassImplValue implements java.io.Serializable { + private HelloImpl impl; +} diff --git a/functional-tests/src/test/java/rmic/PrivateMethodCollision.java b/functional-tests/src/test/java/rmic/PrivateMethodCollision.java new file mode 100644 index 000000000..ccbd6fdd8 --- /dev/null +++ b/functional-tests/src/test/java/rmic/PrivateMethodCollision.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class PrivateMethodCollision implements java.io.Serializable { + public PrivateMethodCollision () {} + private PrivateMethodCollision (int i) {} + public void foo () {} + private void foo (int i) {} + private boolean foo; +} + diff --git a/functional-tests/src/test/java/rmic/RMICTest.java b/functional-tests/src/test/java/rmic/RMICTest.java new file mode 100644 index 000000000..bdae95441 --- /dev/null +++ b/functional-tests/src/test/java/rmic/RMICTest.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.util.Vector; +import java.io.OutputStream; +import java.io.IOException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashSet; +import test.Util; +import test.Test; + +/* + * @test + */ +public abstract class RMICTest extends Test { + + public static final String SKIP_RMIC_FLAG = "-normic"; + private static HashSet files = new HashSet(); + + /** + * Return an array of fully qualified class names for which generation + * should occur. Return empty array if none. + */ + protected abstract String[] getGenerationClasses () throws Throwable; + + /** + * Perform the test. + */ + protected abstract void doTest () throws Throwable; + + /** + * Return the primary generator argument (e.g. "-iiop" or "-idl"). + */ + protected abstract String getGeneratorArg (); + + /** + * Append additional (i.e. after -idl and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + + String[] result = currentArgs; + String dir = (String)getArgs().get(OUTPUT_DIRECTORY); + + if (dir != null) { + + result = new String[currentArgs.length + 2]; + System.arraycopy(currentArgs,0,result,0,currentArgs.length); + result[currentArgs.length] = "-d"; + result[currentArgs.length + 1] = dir; + } + + return result; + } + + /** + * Return true if generation shuold occur once per process, false + * if they should be generated prior to each call to doTest(). Default + * is true. + */ + protected boolean generateOnlyOnce () { + return true; + } + + /** + * Return the output stream to which rmic should write output. + */ + protected OutputStream getOutputStream () { + return System.out; + } + + /** + * Generate rmic output for the supplied class. + */ + protected void generate (String theClass, OutputStream out) throws Exception { + String[] list = new String[1]; + list[0] = theClass; + generate(list,out); + } + + /** + * Generate rmic output for the supplied classes. + */ + protected void generate (String[] classes,OutputStream out) throws Exception { + String[] additionalArgs = new String[0]; + String generatorArg = getGeneratorArg(); + additionalArgs = getAdditionalRMICArgs(additionalArgs); + boolean onlyOnce = generateOnlyOnce(); + generate(classes,generatorArg,additionalArgs,onlyOnce,out); + } + + /** + * Run the test. + */ + public void run () { + try { + + if (!getArgs().containsKey(SKIP_RMIC_FLAG)) { + + // Do generation... + + generate(getGenerationClasses(),getOutputStream()); + } + + // Do the test... + + doTest(); + + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + status = new Error("Caught " + out.toString()); + } + } + + /** + * Generate. + * @param classes An array of fully qualified class names. + * @param generatorArg The primary generator argument. + * @param additionalRMICArgs An array of additional arguments (e.g. after -idl and + * before classes) to rmic. + * @param onlyOnce Return true if stubs should only be generated once per process. + * @param out Where to write output. + */ + public static synchronized void generate ( String[] classes, + String generatorArg, + String[] additionalRMICArgs, + boolean onlyOnce, + OutputStream out) throws Exception { + + // Create a list of classes to compile... + + Vector list = new Vector(classes.length); + for (int i = 0; i < classes.length; i++) { + + String theClass = classes[i]; + + // Do we need to compile this class? + + if (!files.contains(theClass)) { + + // Yes. + + list.addElement(theClass); + } + } + + // Anything to do? + + int count = list.size(); + + if (count > 0) { + + // Yep. Convert vector to array... + + String[] compileEm = new String[count]; + list.copyInto(compileEm); + + // Do the compile... + + Util.rmic(generatorArg,additionalRMICArgs,compileEm,false,out); + + // Are we supposed to compile these guys only once? + + if (onlyOnce) { + + // Yes, so add them to the static table... + + for (int i = 0; i < count; i++) { + files.add(compileEm[i]); + } + } + } + } +} diff --git a/functional-tests/src/test/java/rmic/RemoteObject.java b/functional-tests/src/test/java/rmic/RemoteObject.java new file mode 100644 index 000000000..cfec219d1 --- /dev/null +++ b/functional-tests/src/test/java/rmic/RemoteObject.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public interface RemoteObject extends java.rmi.Remote, AbstractObject { + public boolean isValue () throws java.rmi.RemoteException; + public int getValue () throws java.rmi.RemoteException; + public String getCodeBase() throws java.rmi.RemoteException; +} + diff --git a/functional-tests/src/test/java/rmic/RemoteObjectServer.java b/functional-tests/src/test/java/rmic/RemoteObjectServer.java new file mode 100644 index 000000000..dcb0ccf33 --- /dev/null +++ b/functional-tests/src/test/java/rmic/RemoteObjectServer.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import javax.rmi.PortableRemoteObject; +import java.rmi.server.RMIClassLoader; + +public class RemoteObjectServer extends PortableRemoteObject implements RemoteObject { + + int value; + + public RemoteObjectServer (int value) throws java.rmi.RemoteException { + this.value = value; + } + + public boolean isValue () throws java.rmi.RemoteException { + return false; + } + + public int getValue () throws java.rmi.RemoteException { + return value; + } + + public String getCodeBase() throws java.rmi.RemoteException { + return RMIClassLoader.getClassAnnotation(getClass()); + } +} + diff --git a/functional-tests/src/test/java/rmic/RemoteOuterNonRemoteInner.java b/functional-tests/src/test/java/rmic/RemoteOuterNonRemoteInner.java new file mode 100644 index 000000000..744dd0f74 --- /dev/null +++ b/functional-tests/src/test/java/rmic/RemoteOuterNonRemoteInner.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public interface RemoteOuterNonRemoteInner extends java.rmi.Remote { + + public String remoteHello () throws java.rmi.RemoteException; + + public interface Inner { + public String hello(); + } +} diff --git a/functional-tests/src/test/java/rmic/RemoteOuterRemoteInner.java b/functional-tests/src/test/java/rmic/RemoteOuterRemoteInner.java new file mode 100644 index 000000000..68e516933 --- /dev/null +++ b/functional-tests/src/test/java/rmic/RemoteOuterRemoteInner.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public interface RemoteOuterRemoteInner extends java.rmi.Remote { + + public String remoteHello () throws java.rmi.RemoteException; + + public interface Inner extends java.rmi.Remote { + public String innerRemoteHello () throws java.rmi.RemoteException; + } +} diff --git a/functional-tests/src/test/java/rmic/ReservedMethod.java b/functional-tests/src/test/java/rmic/ReservedMethod.java new file mode 100644 index 000000000..398503644 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ReservedMethod.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface ReservedMethod extends java.rmi.Remote { + Object object (Object it) throws java.rmi.RemoteException; + Exception exception (Exception it) throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/ReturnImplInterface.java b/functional-tests/src/test/java/rmic/ReturnImplInterface.java new file mode 100644 index 000000000..129e81275 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ReturnImplInterface.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface ReturnImplInterface extends java.rmi.Remote { + HiServant method() throws java.rmi.RemoteException; +} + diff --git a/functional-tests/src/test/java/rmic/ReturnVector.java b/functional-tests/src/test/java/rmic/ReturnVector.java new file mode 100644 index 000000000..662ef271c --- /dev/null +++ b/functional-tests/src/test/java/rmic/ReturnVector.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface ReturnVector extends java.rmi.Remote { + java.util.Vector getVector () throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/Right.java b/functional-tests/src/test/java/rmic/Right.java new file mode 100644 index 000000000..bca44bc84 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Right.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface Right extends java.rmi.Remote { + void right() throws java.rmi.RemoteException; + void method() throws java.rmi.RemoteException, TestException; +} diff --git a/functional-tests/src/test/java/rmic/SRInner.java b/functional-tests/src/test/java/rmic/SRInner.java new file mode 100644 index 000000000..d8c929348 --- /dev/null +++ b/functional-tests/src/test/java/rmic/SRInner.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +interface SRInner extends Remote { + public String hello () throws RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/Simple.java b/functional-tests/src/test/java/rmic/Simple.java new file mode 100644 index 000000000..453cdb503 --- /dev/null +++ b/functional-tests/src/test/java/rmic/Simple.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface Simple extends Remote { + void method1 () throws RemoteException; + void method2 () throws RemoteException, TestException; +} diff --git a/functional-tests/src/test/java/rmic/SimpleServant.java b/functional-tests/src/test/java/rmic/SimpleServant.java new file mode 100644 index 000000000..4efd412b5 --- /dev/null +++ b/functional-tests/src/test/java/rmic/SimpleServant.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +public class SimpleServant extends PortableRemoteObject implements Simple { + public SimpleServant () throws RemoteException {} + public void method1 () {} + public void method2 () {} +} diff --git a/functional-tests/src/test/java/rmic/StaticStringsHashTest.java b/functional-tests/src/test/java/rmic/StaticStringsHashTest.java new file mode 100644 index 000000000..3e8389108 --- /dev/null +++ b/functional-tests/src/test/java/rmic/StaticStringsHashTest.java @@ -0,0 +1,305 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import test.Test; +import sun.rmi.rmic.iiop.StaticStringsHash; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.glassfish.pfl.test.JUnitReportHelper; + +/* + * @test + */ +public class StaticStringsHashTest extends Test { + + static final String[][] TEST_CASES = { + { + "a", "b", "c" + }, + { + "one", "two", "three" + }, + { + "a", "bb", "ccc" + }, + { + "method_1", "method_3", "method_2" + }, + { + "asd;lfjafd;ljadsfkja;dslfjadsiewqrpouew0-adsflkjfdsa[09qrewlkjafdm/asdfa.madsfpoiuawer;lkjadfa;lkjadsf;lkjqewrpoiqu", + "a;lkqreoiufds;lkafdsoiuqerw;nafdpoiuafd;ln;aqreopiuadslkfjafdpoiuqrew;lkjasdfpoiuawer;lnvc/nm/", + "dfas;lkjrewqpoiuafd.,mn40987145lkhjafavpoiuqre,mnzv.,mvczxoiusatrnafd;lhjafo", + "daf;lkjasdfp0uqrnmae0uafd;lkjaffjkl;asdpoiuqweru8a8fdsj;lfa/.m vc;'afd[poier", + "affj;lkasfdpoiuqreq0-87450987afjafpoiuasdf87qwerjadfsakj;adsfuvc;lkvczjafdoupafup", + "sadf;lkjasdf;ljafds;lkjdsaf;lkjasdf;lkjfdsapoiuewqrpoiuwqerojadsf;lkj", + "adsf;lkjafds[uqewr;ljaf[iuqwer;lkjasadf;lkjasdfopiuqwer;lkjafpoiuqewr;lkjqerui", + "afd;lkjasdfpoiuqrewpoiuqewr098745-08752430-9862-098450987tr5jartp0u", + }, + { + "IOR:0000000000000023524d493a6578616d706c652e48617368633a303030303030303030303030303030300000000000010000000000000054000101000000000b392e362e32322e32303200000479000000000018afabcafe0000000283d0ea290000000800000003000000000000000100000001000000140000000000010020000000000001010000000000", + "IOR:0000000000000024524d493a6578616d706c652e53616d706c653a3030303030303030303030303030303000000000010000000000000054000101000000000b392e362e32322e32303200000479000000000018afabcafe0000000283d0ea290000000800000002000000000000000100000001000000140000000000010020000000000001010000000000", + }, + { + "imageUpdate", + "_get_font", + "remove", + "postEvent", + "_get_name", + "_set_name", + "_get_parent", + "_get_peer", + "_get_treeLock", + "_get_toolkit", + "_get_valid", + "_get_visible", + "_get_showing", + "_get_enabled", + "_set_enabled", + "enable__", + "enable__boolean", + "disable", + "_set_visible", + "show__", + "show__boolean", + "hide", + "_get_foreground", + "_set_foreground", + "_get_background", + "_set_background", + "_set_font", + "_get_locale", + "_set_locale", + "_get_colorModel", + "_get_location__", + "_get_locationOnScreen", + "location", + "setLocation", + "move", + "_set_location__", + "_get_size__", + "size", + "setSize", + "resize__long__long", + "_set_size__", + "resize__java_awt_Dimension", + "_get_bounds__", + "bounds", + "setBounds", + "reshape", + "_set_bounds__", + "_get_preferredSize__", + "preferredSize", + "_get_minimumSize__", + "minimumSize", + "_get_maximumSize", + "_get_alignmentX", + "_get_alignmentY", + "doLayout", + "layout", + "validate", + "invalidate", + "_get_graphics", + "getFontMetrics", + "_set_cursor", + "_get_cursor", + "paint", + "update", + "paintAll", + "repaint__", + "repaint__long_long", + "repaint__long__long__long__long", + "repaint__long_long__long__long__long__long", + "print", + "printAll", + "createImage__java_awt_image_ImageProducer", + "createImage__long__long", + "prepareImage__java_awt_Image__java_awt_image_ImageObserver", + "prepareImage__java_awt_Image__long__long__java_awt_image_ImageObserver", + "checkImage__java_awt_Image__java_awt_image_ImageObserver", + "checkImage__java_awt_Image__long__long__java_awt_image_ImageObserver", + "contains__long__long", + "inside", + "contains__java_awt_Point", + "getComponentAt__long__long", + "locate", + "getComponentAt__java_awt_Point", + "deliverEvent", + "dispatchEvent", + "dispatchEventImpl", + "areInputMethodsEnabled", + "eventEnabled", + "addComponentListener", + "removeComponentListener", + "addFocusListener", + "removeFocusListener", + "addKeyListener", + "removeKeyListener", + "addMouseListener", + "removeMouseListener", + "addMouseMotionListener", + "removeMouseMotionListener", + "_get_inputContext", + "enableEvents", + "disableEvents", + "processEvent", + "processComponentEvent", + "processFocusEvent", + "processKeyEvent", + "processMouseEvent", + "processMouseMotionEvent", + "postsOldMouseEvents", + "handleEvent", + "mouseDown", + "mouseDrag", + "mouseUp", + "mouseMove", + "mouseEnter", + "mouseExit", + "keyDown", + "keyUp", + "action", + "addNotify", + "removeNotify", + "gotFocus", + "lostFocus", + "_get_focusTraversable", + "requestFocus", + "transferFocus", + "nextFocus", + "add", + "paramString", + "toString", + "list__", + "list__java_io_PrintStream", + "list__java_io_PrintStream__long", + "list__java_io_PrintWriter", + "list__java_io_PrintWriter__long", + "_get_nativeContainer", + }, + { + "* This interface imposes a total ordering on the objects of each class that", + "* implements it. This ordering is referred to as the class's natural", + "* ordering, and the class's compareTo method is referred to as", + "* its natural comparison method.

", + "* Lists (and arrays) of objects that implement this interface can be sorted", + "* automatically by Collections.sort (and Arrays.sort).", + "* Objects that implement this interface can be used as keys in a sorted map", + "* or elements in a sorted set, without the need to specify a comparator.

", + "* A class's natural ordering is said to be consistent with equals if", + "* and only if (e1.compareTo((Object)e2)==0) has the same boolean", + "* value as e1.equals((Object)e2) for every e1 and", + "* e2 of class C.

", + "* It is strongly recommended (though not required) that natural orderings be", + "* consistent with equals. This is so because sorted sets (and sorted maps)", + "* without explicit comparators behave \"strangely\" when they are used with", + "* elements (or keys) whose natural ordering is inconsistent with equals. In", + "* particular, such a sorted set (or sorted map) violates the general contract", + "* for set (or map), which is defined in terms of the equals", + "* operation.

", + "* For example, if one adds two keys a and b such that", + "* (a.equals((Object)b) && a.compareTo((Object)b) != 0) to a sorted", + "* set that does not use an explicit comparator, the second add", + "* operation returns false (and the size of the sorted set does not increase)", + "* because a and b are equivalent from the sorted set's", + "* perspective.

", + "* Virtually all Java core classes that implement ComparableX have natural", + "* orderings that are consistent with equals. One exception is", + "* java.math.BigDecimal, whose natural ordering equates", + "* BigDecimals with equal values and different precisions (such as", + "* 4.0 and 4.00).

", + "* For the mathematically inclined, the relation that defines", + "* the natural ordering on a given class C is:

",
+            "*   {(x, y) such that x.compareTo((Object)y) <= 0}.",
+            "* 
The quotient for this total order is:
",
+            "*   {(x, y) such that x.compareTo((Object)y) == 0}.",
+            "* It follows immediately from the contract for compareTo that the",
+            "* quotient is an equivalence relation on C, and that the",
+            "* natural ordering is a total order on C.  When we say that a",
+            "* class's natural ordering is consistent with equals, we mean that the",
+            "* quotient for the natural ordering is the equivalence relation defined by",
+            "* the class's equals(Object) method:
",
+            "* {(x, y) such that x.equals((Object)y)}.",
+            "* 
", + }, + }; + + /** + * Perform the test. + */ + protected void check (String[] list) throws Throwable { + + StaticStringsHash hash = new StaticStringsHash(list); + int length = list.length; + + // Make sure lengths are the same... + + if (hash.keys.length != hash.buckets.length) { + throw new Error("lengths not equal"); + } + + // Mark all the indices we find. Ensure that for each + // bucket, each string in the bucket has the key + // listed in the keys array... + + int[] found = new int[length]; + for (int i = 0; i < hash.buckets.length; i++) { + int currentHash = hash.keys[i]; + for (int j = 0; j < hash.buckets[i].length; j++) { + int index = hash.buckets[i][j]; + + // Make sure it is not already used... + + if (found[index] == 1) { + throw new Error("index found more than once"); + } else { + found[index] = 1; + } + + int h = hash.getKey(list[index]); + if (h != currentHash) { + throw new Error("hash does not match"); + } + } + } + + // Make sure all indices are represented... + + for (int i = 0; i < length; i++) { + if (found[i] != 1) { + throw new Error("index "+i+" not found"); + } + } + } + + public void run () { + JUnitReportHelper helper = new JUnitReportHelper( + this.getClass().getName() ) ; + + try { + for (int i = 0; i < TEST_CASES.length; i++) { + helper.start( "test_" + i ) ; + check(TEST_CASES[i]); + helper.pass() ; + } + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + status = new Error("Caught " + out.toString()); + helper.fail( e ) ; + } finally { + helper.done() ; + } + } +} diff --git a/functional-tests/src/test/java/rmic/StressParseIIOP.java b/functional-tests/src/test/java/rmic/StressParseIIOP.java new file mode 100644 index 000000000..c3032c11e --- /dev/null +++ b/functional-tests/src/test/java/rmic/StressParseIIOP.java @@ -0,0 +1,360 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.io.File; +import java.io.PrintStream; +import java.util.Vector; +import java.io.InputStreamReader; +import java.io.BufferedReader; +import java.io.PrintWriter; +import java.io.OutputStream; +import java.io.IOException; + +/** + * StressParseIIOP walks all classes in a classpath and has CompoundType.makeType() + * parse them. The output is sent to standard out. + * + * @author Bryan Atsatt + */ +public class StressParseIIOP { + + private static final int MAX_FILES = 400; + private static final String kPathArg = "-classpath"; + private static final String kBatchSizeArg = "-batchsize"; + private static final String kSoloArg = "-solo"; + private String classPath; + private int batchSize; + private boolean solo; + private int totalCount; + + + /** + * Constructor + */ + public StressParseIIOP (String classPath, int batchSize, boolean solo) { + + this.classPath = classPath; + this.batchSize = batchSize; + this.solo = solo; + totalCount = 0; + } + + public int parse () { + + int result = 0; + + // Collect all classes... + + Vector allClasses = ClassEnumerator.getClasses(classPath,true); + System.out.println("Processing " + allClasses.size() + " classes:\n"); + + // Split the list if needed... + + Vector[] classes = split(allClasses,batchSize); + + // Parse them... + + for (int i = 0; i < classes.length; i++) { + int exitValue = parse(classes[i]); + if (exitValue != 0) { + result = exitValue; + } + } + + return result; + } + + protected static Vector[] split (Vector all, int maxSize) { + int chunks = 1; + int count = all.size(); + if (count > maxSize) { + float temp = ((float)count)/((float)maxSize); + chunks = (int) temp; + if (temp > chunks) chunks++; + } + + Vector[] result = new Vector[chunks]; + + // Do we need to split them? + + if (chunks == 1) { + + // Nope... + + result[0] = all; + + } else { + + // Yes... + + int copyIndex = 0; + int copyCount = maxSize; + + for (int i = 0; i < chunks; i++) { + result[i] = new Vector(copyCount); + int thisCount = copyCount; + while (thisCount-- > 0) { + result[i].addElement(all.elementAt(copyIndex++)); + } + + count -= copyCount; + if (count < maxSize) { + copyCount = count; + } + } + } + + return result; + } + + protected int parse (Vector list) { + + // Create args array... + + int listSize = list.size(); + int count = listSize + 5; + String[] args = new String[count]; + int offset = 0; + args[offset++] = "java"; + args[offset++] = "rmic.MapType"; + args[offset++] = new Boolean(solo).toString(); + args[offset++] = Integer.toString(totalCount); + args[offset++] = classPath; + + for (int i = 0; i < listSize; i++) { + args[offset++] = (String) list.elementAt(i); + } + totalCount += listSize; + + // Run the command and exit... + + return execAndWaitFor(args); + } + + + /** + * Process the arguments, construct an instance and tell it to process the files... + */ + public static void main(String args[]) { + + // Init arguments... + + String classPath = null; + int batchSize = MAX_FILES; + boolean solo = false; + + // Get arguments... + + if (args == null) { + usage(); + } else { + for (int i = 0; i < args.length; i++) { + + String arg = args[i].toLowerCase(); + + if (arg.equals(kPathArg)) classPath = args[++i]; + else if (arg.equals(kBatchSizeArg)) batchSize = Integer.parseInt(args[++i]); + else if (arg.equals(kSoloArg)) solo = true; + else usage(); + } + } + + // Init classPath if needed... + + if (classPath == null) { + classPath = ClassEnumerator.getFullClassPath(); + } + // Construct our object... + + StressParseIIOP parser = new StressParseIIOP(classPath,batchSize,solo); + + // Tell it to do it's thing... + + int result = 0; + + try { + long startTime = System.currentTimeMillis(); + result = parser.parse(); + long duration = System.currentTimeMillis() - startTime; + + if (result == 0) { + System.out.println("PASS. Completed in " + duration + " ms."); + } else { + System.out.println("FAIL. Completed in " + duration + " ms."); + } + } catch (InternalError e) { + result = 1; + System.err.println("Error! " + e.getMessage()); + } catch (Exception e) { + result = 1; + System.err.println("Error! Caught " + e.getMessage()); + e.printStackTrace(System.err); + } + + System.exit(result); + } + + /** + * Print usage. + */ + public static void usage () { + PrintStream out = System.out; + + out.println(); + out.println("Usage: java rmic.StressParseIIOP [-classpath ]"); + out.println(); + } + + /** + * execAndWaitFor will create a new Process and wait for the + * process to complete before returning + * @param command command line arguments to pass to exec. + * @return int the result of Process.exitValue() or -1; + * @throws Error if an unexpected exception occurs an Error is + * thrown with the message string from the original exception. + */ + public static int execAndWaitFor(String[] command) { + + try { + + Runtime runtime = Runtime.getRuntime(); + Process theProcess = runtime.exec(command); + ProcessMonitor monitor = new ProcessMonitor(theProcess,System.out,System.err,0); + monitor.start(); + int result = waitForCompletion(theProcess,2000); + monitor.stop(); + return result; + } catch (Throwable error) { + error.printStackTrace(System.out); + throw new Error(error.getMessage()); + } + } + + + private static int waitForCompletion( Process theProcess, int sleepTime) + throws java.lang.InterruptedException + { + int result = -1; + + try { + theProcess.waitFor(); + result = theProcess.exitValue(); + } + catch (java.lang.IllegalThreadStateException notDone) { + // We assume that waitFor() does not work and exitValue() + // failed because the Process is not done. Lets Sleep + // for a while then check for completion again. + Thread.sleep(sleepTime,0); + result = waitForCompletion(theProcess,sleepTime+1500); + } + + return result; + } +} + + + +/** + * ProcessMonitor provides a thread which will consume output from a + * java.lang.Process and write it to the specified local streams. + * + * @version 1.0, 6/11/98 + * @author Bryan Atsatt + */ +class ProcessMonitor extends Thread { + Process process; + long delay; + PrintWriter localOut; + PrintWriter localErr; + String prefix = null; + + /** + * Constructor. + * @param theProcess The process to monitor. + * @param out The stream to which to copy Process.getInputStream() data. + * @param err The stream to which to copy Process.getErrorStream() data. + * @param delay How long to wait between checking the streams for data. + * May be zero. + */ + ProcessMonitor ( Process theProcess, + OutputStream out, + OutputStream err, + long delay) { + process = theProcess; + this.delay = delay; + localOut = new PrintWriter(out,true); + localErr = new PrintWriter(err,true); + setDaemon(true); + } + + /** + * Constructor. + * @param theProcess The process to monitor. + * @param out The stream to which to copy Process.getInputStream() data. + * @param err The stream to which to copy Process.getErrorStream() data. + * @param delay How long to wait between checking the streams for data. + * May be zero. + * @param prefix String to prepend to all copied output lines. + */ + ProcessMonitor ( Process theProcess, + OutputStream out, + OutputStream err, + long delay, + String prefix) { + process = theProcess; + this.delay = delay; + localOut = new PrintWriter(out,true); + localErr = new PrintWriter(err,true); + setDaemon(true); + this.prefix = prefix; + } + + public void run () { + + BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); + BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); + + String eolTest = ""; + + try { + while ((eolTest = in.readLine()) != null) { + if (prefix != null) { + localOut.println(prefix + eolTest); + } else { + localOut.println(eolTest); + } + + } + } catch (IOException e) {} + + try { + while ((eolTest = err.readLine()) != null) { + if (prefix != null) { + localErr.println(prefix + eolTest); + } else { + localErr.println(eolTest); + } + } + + } catch (IOException e) {} + + if (delay > 0) { + synchronized (this) { + + try { + wait(delay); + } catch (InterruptedException e){} + } + } + } +} diff --git a/functional-tests/src/test/java/rmic/StubReferenceTest.java b/functional-tests/src/test/java/rmic/StubReferenceTest.java new file mode 100644 index 000000000..b1dc92a55 --- /dev/null +++ b/functional-tests/src/test/java/rmic/StubReferenceTest.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import java.io.ByteArrayOutputStream; +import java.util.StringTokenizer; +import org.glassfish.pfl.test.JUnitReportHelper; + + +/* + * @test + */ +public class StubReferenceTest extends StubTest { + + public static final String[] ADDITIONAL_ARGS = {"-alwaysGenerate","-keep"}; + + public static final String CLASS_LIST_FILE = ".classlist"; + public static final String FILE_EXT = ".java"; + public static final String FILE_REF_EXT = ".javaref"; + + private String[] shouldCompileClasses = null; + private Target[] targets = null; + + /** + * Return an array of fully qualified class names for which generation + * should occur. Return empty array if none. + */ + protected String[] getGenerationClasses () throws Throwable { + initClasses(); + return shouldCompileClasses; + } + + /** + * Perform the test. + */ + protected void doTest () throws Throwable { + JUnitReportHelper helper = new JUnitReportHelper( + this.getClass().getName() ) ; + + try { + // Those classes that should compile have been compiled. Check to + // ensure that they match there reference files... + + for (int i = 0; i < targets.length; i++) { + if (targets[i].shouldCompile) { + helper.start( "test_" + i ) ; + String[] output = targets[i].output; + + try { + for (int j = 0; j < output.length; j++) { + compareResources(output[j],FILE_EXT,FILE_REF_EXT); + } + + helper.pass() ; + } catch (Throwable thr) { + helper.fail( thr ) ; + throw thr ; + } + } + } + + // Now ensure that those classes which should NOT compile, do in + // fact fail as expected... + + for (int i = 0; i < targets.length; i++) { + if (!targets[i].shouldCompile) { + helper.start( "test_" + i ) ; + Target target = targets[i]; + boolean failed = false; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + generate(target.inputClass,out); + } catch (Exception e) { + failed = true; + } + + if (failed) { + // Make sure that the error output contains all the errorStrings in the + // output array... + + String[] errors = target.output; + String errorText = out.toString(); + + for (int j = 1; j < errors.length; j++) { + if (errorText.indexOf(errors[j]) < 0) { + String msg = target.inputClass + + " error message did not contain '" + + errors[j] + "'. Got " + errorText ; + + helper.fail( msg ) ; + throw new Error( msg ) ; + } + } + helper.pass() ; + } else { + String msg = target.inputClass + " should FAIL to compile but did not." ; + helper.fail( msg ) ; + throw new Error( msg ) ; + } + } + } + } finally { + helper.done() ; + } + } + + /** + * Append additional (i.e. after -idl and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + return super.getAdditionalRMICArgs(ADDITIONAL_ARGS); + } + + private synchronized void initClasses () throws Throwable { + + if (shouldCompileClasses == null) { + String[] array = getResourceAsArray(getClass().getName(),CLASS_LIST_FILE,"#"); + int totalCount = array.length; + targets = new Target[totalCount]; + int shouldCompileCount = 0; + + // Parse input into our Target array, keeping count of those that should + // compile... + + for (int i = 0; i < totalCount; i++) { + targets[i] = new Target(array[i]); + + if (targets[i].shouldCompile) { + shouldCompileCount++; + } + } + + int shouldNotCompileCount = totalCount - shouldCompileCount; + + // Allocate our array... + + shouldCompileClasses = new String[shouldCompileCount]; + + // Fill them up... + + int shouldOffset = 0; + for (int i = 0; i < totalCount; i++) { + if (targets[i].shouldCompile) { + shouldCompileClasses[shouldOffset++] = targets[i].inputClass; + } + } + } + } +} + +class Target { + public String inputClass = null; + public String[] output = null; + public boolean shouldCompile = true; + + public Target (String entry) { + + // Parse the =[,] format... + + StringTokenizer s = new StringTokenizer(entry,"=,"); + int count = s.countTokens() - 1; + output = new String[count]; + inputClass = s.nextToken().trim(); + int offset = 0; + while (s.hasMoreTokens()) { + output[offset++] = s.nextToken().trim(); + } + + // Set the shouldCompile flag if needed... + + if (output[0].equalsIgnoreCase("ERROR")) { + shouldCompile = false; + } + } +} diff --git a/functional-tests/src/test/java/rmic/StubTest.java b/functional-tests/src/test/java/rmic/StubTest.java new file mode 100644 index 000000000..5487e5d75 --- /dev/null +++ b/functional-tests/src/test/java/rmic/StubTest.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +/* + * @test + */ +public abstract class StubTest extends RMICTest { + + /** + * Return an array of fully qualified class names for which generation + * should occur. Return empty array if none. + */ + protected abstract String[] getGenerationClasses () throws Throwable; + + /** + * Return the primary generator argument (e.g. "-iiop" or "-idl"). + */ + protected String getGeneratorArg () { + return "-iiop"; + } + + /** + * Perform the test. + */ + protected abstract void doTest () throws Throwable; +} diff --git a/functional-tests/src/test/java/rmic/SwapMember.java b/functional-tests/src/test/java/rmic/SwapMember.java new file mode 100644 index 000000000..098d6948e --- /dev/null +++ b/functional-tests/src/test/java/rmic/SwapMember.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class SwapMember implements java.io.Serializable { + private NotAbstract na; + private ShouldSwap ss; +} + +interface NotAbstract { + public void method1 (ShouldSwap foo); +} + +class ShouldSwap implements java.io.Serializable { + private NotAbstract notAbstract; +} diff --git a/functional-tests/src/test/java/rmic/TestEnv.java b/functional-tests/src/test/java/rmic/TestEnv.java new file mode 100644 index 000000000..9c68c4f72 --- /dev/null +++ b/functional-tests/src/test/java/rmic/TestEnv.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import sun.rmi.rmic.Main; +import sun.tools.java.ClassPath; +import java.io.OutputStream; + +public class TestEnv extends sun.rmi.rmic.iiop.BatchEnvironment { + + private boolean firstLine = true; + + public TestEnv(ClassPath path, OutputStream out) { + super(out,path,new Main(System.out, "rmic")); + } + + public TestEnv(ClassPath path) { + super(System.out,path,new Main(System.out, "rmic")); + } + + public void reset() { + firstLine = true; + nerrors = 0; + nwarnings = 0; + ndeprecations = 0; + super.reset(); + } + + public void output(String msg) { + if (firstLine) { + System.out.println(); + firstLine = false; + } + System.out.println(" " + msg); + } +} + diff --git a/functional-tests/src/test/java/rmic/TestException.java b/functional-tests/src/test/java/rmic/TestException.java new file mode 100644 index 000000000..7a6c0c74d --- /dev/null +++ b/functional-tests/src/test/java/rmic/TestException.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class TestException extends java.lang.Exception { +} diff --git a/functional-tests/src/test/java/rmic/TestExecutor.java b/functional-tests/src/test/java/rmic/TestExecutor.java new file mode 100644 index 000000000..dd2e3b711 --- /dev/null +++ b/functional-tests/src/test/java/rmic/TestExecutor.java @@ -0,0 +1,479 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +import test.Util; +import java.io.ByteArrayOutputStream; +import java.util.Hashtable; +import sun.tools.java.MemberDefinition; +import sun.rmi.rmic.iiop.Type; +import sun.rmi.rmic.iiop.ValueType; +import sun.rmi.rmic.iiop.Constants; +import sun.rmi.rmic.iiop.CompoundType; +import sun.rmi.rmic.iiop.RemoteType; +import sun.rmi.rmic.iiop.AbstractType; +import sun.rmi.rmic.iiop.ContextStack; + +import org.testng.Assert ; + +import org.testng.annotations.Test ; +import org.testng.annotations.AfterGroups ; +import org.testng.annotations.BeforeGroups ; +import org.testng.annotations.AfterSuite ; +import org.testng.annotations.BeforeSuite ; + +public class TestExecutor { + private ByteArrayOutputStream out = null; + private TestEnv env = null; + private ContextStack stack = null; + + private void myAssert (boolean test, String message) { + Assert.assertTrue( test, message ) ; + } + + @Test + public void testImplArgOrDataMember() throws Throwable { + testFailure("rmic.PassImplInterface", "is a remote implementation class ", "PassImplInterface"); + testFailure("rmic.ReturnImplInterface", "is a remote implementation class ", "ReturnImplInterface"); + testFailure("rmic.PassImplValue", "is a remote implementation class ", "PassImplValue"); + } + + @Test + public void testReservedMethod() throws Throwable { + RemoteType type = (RemoteType) MapType.getType("rmic.ReservedMethod",stack); + myAssert(type != null,"rmic.ReservedMethod failed"); + } + + @Test + public void testIDLEntityValue() throws Throwable { + ValueType type = (ValueType) MapType.getType("rmic.IDLEntityValue",stack); + myAssert(type != null,"rmic.IDLEntityValue failed"); + CompoundType.Method[] methods = type.getMethods(); + myAssert(methods.length == 1,"rmic.IDLEntityValue does not have 1 method"); + myAssert(methods[0].getIDLName().equals("_get_foo"),"rmic.IDLEntityValue method != _get_foo"); + } + + @Test + public void testPrivateMethodCollision() throws Throwable { + CompoundType type = (CompoundType) MapType.getType("rmic.PrivateMethodCollision",stack); + CompoundType.Method[] methods = type.getMethods(); + for (int i = 0;i < methods.length; i++) { + if (!methods[i].isConstructor()) { + myAssert(methods[i].getIDLName().equals("foo"),"rmic.PrivateMethodCollision method name != foo."); + break; + } + } + CompoundType.Member[] members = type.getMembers(); + myAssert(members.length == 1,"rmic.PrivateMethodCollision does not have 1 member"); + myAssert(members[0].getIDLName().equals("foo_"),"rmic.PrivateMethodCollision member != foo_"); + } + + @Test + public void testEmptyInterface() throws Throwable { + AbstractType type = (AbstractType) MapType.getType("rmic.EmptyInterface",stack); + myAssert(type != null,"rmic.EmptyInterface failed"); + } + + @BeforeGroups( { "nonconforming" } ) + public void ncOn() { + env.setParseNonConforming(true); + } + + @AfterGroups( { "nonconforming" } ) + public void ncOff() { + env.setParseNonConforming(false); + } + + @Test( groups = { "nonconforming" } ) + public void testInvalidNC() throws Throwable { + testFailure("rmic.InvalidNC", "rmic.InvalidNC is not a valid class", "J_bar conflicts"); + } + + @Test( groups = { "nonconforming" } ) + public void testValueWithInvalidNC() throws Throwable { + testFailure("rmic.ValueWithInvalidNC", "rmic.ValueWithInvalidNC contains an invalid argument", "in method foo"); + } + + @Test + public void testReturnVector() throws Throwable { + RemoteType type = (RemoteType) MapType.getType("rmic.ReturnVector",stack); + myAssert(type != null,"rmic.ReturnVector failed"); + } + + @Test + public void testThrowNCIOException() throws Throwable { + testFailure("rmic.ThrowNCIOException", "not a valid class", "rmic.NCIOException"); + } + + @Test + public void testThrowNCException() throws Throwable { + testFailure("rmic.ThrowNCException", "not a valid class", "rmic.NCRemoteException"); + } + + @Test + public void testPassIDLEntityException() throws Throwable { + testFailure("rmic.PassIDLEntityException", "may not pass an exception", "org.omg.CORBA.portable.IDLEntity"); + } + + @Test + public void testOnlyRemote() throws Throwable { + CompoundType type = (CompoundType) MapType.getType("rmic.OnlyRemoteServant",stack); + myAssert(type != null,"rmic.OnlyRemoteServant failed"); + } + + @Test + public void testSerialPersistent() throws Throwable { + CompoundType type = (CompoundType) MapType.getType("test12.SerialPersistent",stack); + CompoundType.Member[] members = type.getMembers(); + for (int i = 0;i < members.length; i++) { + if (members[i].getName().equals("member8")) { + myAssert(members[i].isTransient(),"test12.SerialPersistent member8 not marked transient."); + break; + } + } + } + + @Test + public void testSequence() throws Throwable { + + // Check alpha.bravo.Charlie.. + + CompoundType type = (CompoundType) MapType.getType("alpha.bravo.Charlie",stack); + CompoundType.Member[] members = type.getMembers(); + Hashtable table = new Hashtable(); + + for (int i = 0; i < members.length; i++) { + Type t = members[i].getType(); + String name = t.getQualifiedIDLName(false); + table.put(name,""); + } + + String[] names = { + "org::omg::boxedRMI::omega::seq2_A", + "org::omg::boxedRMI::seq2_boolean", + "org::omg::boxedRMI::javax::rmi::CORBA::seq1_ClassDesc", + "org::omg::boxedRMI::seq1_Object", + "org::omg::boxedRMI::java::lang::seq1_Exception", + "org::omg::boxedRMI::java::io::seq1_Externalizable", + "org::omg::boxedRMI::omega::seq1_Dolphin", + "org::omg::boxedRMI::omega::seq2_Dolphin", + "org::omg::boxedRMI::omega::seq3_Dolphin", + "org::omg::boxedRMI::org::omg::boxedIDL::omega::seq1_Foxtrot", + "org::omg::boxedRMI::org::omg::boxedIDL::omega::seq2_Foxtrot", + "org::omg::boxedRMI::omega::seq1_Golf", + "org::omg::boxedRMI::omega::seq2_Golf", + "org::omg::boxedRMI::omega::seq1_Hotel", + "org::omg::boxedRMI::omega::seq2_Hotel", + "org::omg::boxedRMI::org::omg::CORBA::portable::seq1_IDLEntity", + "org::omg::boxedRMI::omega::seq1_India", + "org::omg::boxedRMI::omega::seq2_India", + "org::omg::boxedRMI::java::lang::seq1_Object", + "org::omg::boxedRMI::seq1_long_long", + "org::omg::boxedRMI::seq2_long_long", + "org::omg::boxedRMI::java::rmi::seq1_Remote", + "org::omg::boxedRMI::java::io::seq1_Serializable", + "org::omg::boxedRMI::java::io::seq2_Serializable", + "org::omg::boxedRMI::CORBA::seq1_WStringValue", + "org::omg::boxedRMI::CORBA::seq2_WStringValue", + }; + + for (int i = 0; i < names.length; i++) { + myAssert(table.containsKey(names[i]),"Did not find " + names[i]); + } + } + + public void testMethodOverload(String typeName, String[] names, boolean[] constructor) throws Throwable { + + CompoundType type = (CompoundType) MapType.getType(typeName,stack); + CompoundType.Method[] methods = type.getMethods(); + Hashtable table = new Hashtable(); + for (int i = 0; i < methods.length; i++) { + String name = methods[i].getIDLName(); + table.put(name,new Boolean(methods[i].isConstructor())); + } + + for (int i = 0; i < names.length; i++) { + Boolean value = (Boolean) table.get(names[i]); + myAssert(value != null,"Did not find " + names[i] + " in "+typeName); + myAssert(value.booleanValue() == constructor[i],"Constructor mismatch for " + names[i] + " in "+typeName); + } + } + + @Test( groups = { "nonconforming" } ) + private void testMethodOverload() throws Throwable { + testMethodOverload("rmic.MethodOverload1",rmic.MethodOverload1.IDL_NAMES,rmic.MethodOverload1.CONSTRUCTOR); + testMethodOverload("rmic.MethodOverload2",rmic.MethodOverload2.IDL_NAMES,rmic.MethodOverload2.CONSTRUCTOR); + testMethodOverload("rmic.MethodOverload3",rmic.MethodOverload3.IDL_NAMES,rmic.MethodOverload3.CONSTRUCTOR); + testMethodOverload("rmic.MethodOverload4",rmic.MethodOverload4.IDL_NAMES,rmic.MethodOverload4.CONSTRUCTOR); + testMethodOverload("rmic.MethodOverload5",rmic.MethodOverload5.IDL_NAMES,rmic.MethodOverload5.CONSTRUCTOR); + testMethodOverload("rmic.MethodOverload6",rmic.MethodOverload6.IDL_NAMES,rmic.MethodOverload6.CONSTRUCTOR); + } + + @Test + public void testSwap() throws Throwable { + + // Make sure that we get the correct type for + // SwapMember.notAbstract... + + CompoundType swapMember = (CompoundType) MapType.getType("rmic.SwapMember",stack); + CompoundType.Member[] members = swapMember.getMembers(); + myAssert(members.length==2,"SwapMember found " + members.length + " members"); + CompoundType shouldSwap = null; + int index = 0; + if (members[1].getName().equals("ss")) index = 1; + else myAssert(members[0].getName().equals("ss"),"SwapMember 'ss' not found"); + shouldSwap = (CompoundType)members[index].getType(); + members = shouldSwap.getMembers(); + myAssert(members.length==1,"ShouldSwap found " + members.length + " members"); + CompoundType na = (CompoundType)members[0].getType(); + String naName = members[0].getName(); + myAssert(naName.equals("notAbstract"),"Found wrong method: " + naName); + myAssert(na instanceof sun.rmi.rmic.iiop.NCInterfaceType,"Found wrong type: " + na.getClass()); + } + + @Test + public void testTypedef() throws Throwable { + + // Check rmic.Typedef... + + CompoundType type = (CompoundType) MapType.getType("rmic.Typedef",stack); + CompoundType.Method[] methods = type.getMethods(); + int found = 0; + for (int i = 0; i < methods.length; i++) { + String name = methods[i].getIDLName(); + if (name.equals("union__wchar")) { + found++; + } else if (name.equals("union__long_long__java_lang_Object")) { + found++; + } + } + + myAssert(found == 2,"Did not find expected IDL method names in rmic.Typedef"); + } + + @Test + public void testClass() throws Throwable { + + // Check java.lang.Class... + + CompoundType type = (CompoundType) MapType.getType("java.lang.Class",stack); + + String name = type.getQualifiedName(); + myAssert(name.equals("java.lang.Class"),"java.lang.Class got name: " + name); + + String idlName = type.getQualifiedIDLName(false); + myAssert(idlName.equals("javax::rmi::CORBA::ClassDesc"),"java.lang.Class got IDL name: " + idlName); + } + + @Test + public void testHiServant() throws Throwable { + + // Check rmic.HiServant. + + CompoundType type = (CompoundType) MapType.getType("rmic.HiServant",stack); + myAssert(type != null,"rmic.HiServant got null type"); + myAssert(type.isType(Constants.TYPE_IMPLEMENTATION),"rmic.HiServant got wrong type"); + } + + + @Test + public void testCorbaObject() throws Throwable { + + // Check java.lang.Object... + + CompoundType type = (CompoundType) MapType.getType("org.omg.CORBA.Object",stack); + + String name = type.getQualifiedName(); + myAssert(name.equals("org.omg.CORBA.Object"),"org.omg.CORBA.Object got name: " + name); + + String idlName = type.getQualifiedIDLName(false); + myAssert(idlName.equals("Object"),"org.omg.CORBA.Object got IDL name: " + idlName); + } + + @Test + public void testJavaLangObject() throws Throwable { + + // Check java.lang.Object... + + CompoundType type = (CompoundType) MapType.getType("java.lang.Object",stack); + + String name = type.getQualifiedName(); + myAssert(name.equals("java.lang.Object"),"java.lang.Object got name: " + name); + + String idlName = type.getQualifiedIDLName(false); + myAssert(idlName.equals("java::lang::_Object"),"java.lang.Object got IDL name: " + idlName); + } + + @Test + public void testAbstract() throws Throwable { + + // Check alpha.bravo.Bear... + + CompoundType type = (CompoundType) MapType.getType("alpha.bravo.Bear",stack); + CompoundType.Method[] methods = type.getMethods(); + int count = methods.length; + + for (int i = 0; i < count; i++) { + String name = methods[i].getName(); + boolean isAttribute = methods[i].isAttribute(); + if (name.equals("getSize")) { + if (!isAttribute) { + throw new Error("alpha.bravo.Bear method " + methods[i] + " is not an attribute " + + methods[i].getAttributeName()); + } + } else { + if (isAttribute) { + throw new Error("alpha.bravo.Bear method " + methods[i] + " is an attribute " + + methods[i].getAttributeName()); + } + } + } + + // Check rmic.AbstractObject... + + type = (CompoundType) MapType.getType("rmic.AbstractObject",stack); + methods = type.getMethods(); + count = methods.length; + + for (int i = 0; i < count; i++) { + String name = methods[i].getName(); + boolean isAttribute = methods[i].isAttribute(); + if (name.equals("getCodeBase") || name.equals("getValue")) { + if (!isAttribute) { + throw new Error("rmic.AbstractObject method " + methods[i] + " is not an attribute " + + methods[i].getAttributeName()); + } + } else { + if (isAttribute) { + throw new Error("rmic.AbstractObject method " + methods[i] + " is an attribute " + + methods[i].getAttributeName()); + } + } + } + } + + @Test + public void testMangleMethodsFail() throws Throwable { + + testFailure("rmic.MangleMethodsFail1", "idl name for", "conflicts with"); + testFailure("rmic.MangleMethodsFail2", "idl name for", "conflicts with"); + testFailure("rmic.MangleMethodsFail3", "idl name for", "conflicts with"); + } + + private void testFailure(String clz, String errString1, String errString2) { + testFailure(new String[]{clz},errString1,errString2); + } + + private void testFailure(String[] classes, String errString1, String errString2) { + out.reset(); + boolean failed = false; + String[] additionalRMICArgs = {"-nowrite"}; + try { + Util.rmic("-idl",additionalRMICArgs,classes,false,out); + } catch (Exception e) { + failed = true; + } + + String error = out.toString(); + if (!failed || error.indexOf(errString1) <= 0 || error.indexOf(errString2) <= 0) { + String names = ""; + for (int i = 0; i < classes.length; i++) { + names += (classes[i]+ " "); + } + + String msg = names + "did not fail as expected. Got: "+error; + Assert.fail( msg ) ; + } + } + + + @Test + public void testMangleMethods() throws Throwable { + + // Get methods... + + CompoundType type = (CompoundType) MapType.getType("rmic.MangleMethods",stack); + CompoundType.Method[] methods = type.getMethods(); + int count = methods.length; + + // Check asserts... + + for (int i = 0; i < count; i++) { + + CompoundType.Method method = methods[i]; + MemberDefinition def = method.getMemberDefinition(); + + if (method.isConstructor()) continue; + + String[] asserts = MangleMethods.Asserts.getAsserts(def.toString()); + + // Check attribute kind... + + int assertKind = getAttributeKind(asserts[1]); + if (method.getAttributeKind() != assertKind) { + throw new Error("Kinds do not match for " + def + ". Found " + method.getAttributeKind()); + } + + // Check attribute name... + + String assertAttrName = asserts[2]; + String attrName = method.getAttributeName(); + + if ((assertAttrName == null || attrName == null) && + (assertAttrName != null || attrName != null)) { + throw new Error("Attribute names do not match (null) for " + def + ". Found " + attrName); + } else { + + if (assertAttrName == null || attrName == null) { + //System.out.println("Both null so match"); + } else { + if (!assertAttrName.equals(attrName)) { + throw new Error("Attribute names do not match for " + def + ". Found " + attrName); + } + } + } + + // Check IDL name... + + String assertIDLName = asserts[3]; + String idlName = method.getIDLName(); + + if (!assertIDLName.equals(idlName)) { + throw new Error("IDL names do not match for " + def + ". Found " + idlName); + } + } + + } + + private int getAttributeKind(String assertKind) { + + if (assertKind.equalsIgnoreCase("NONE")) return Constants.ATTRIBUTE_NONE; + if (assertKind.equalsIgnoreCase("IS")) return Constants.ATTRIBUTE_IS; + if (assertKind.equalsIgnoreCase("GET")) return Constants.ATTRIBUTE_GET; + if (assertKind.equalsIgnoreCase("IS_RW")) return Constants.ATTRIBUTE_IS_RW; + if (assertKind.equalsIgnoreCase("GET_RW")) return Constants.ATTRIBUTE_GET_RW; + if (assertKind.equalsIgnoreCase("SET")) return Constants.ATTRIBUTE_SET; + throw new Error("Invalid assertKind: " + assertKind); + } + + @BeforeSuite() + public void setup() { + out = new ByteArrayOutputStream(); + env = new TestEnv(ParseTest.createClassPath(),out); + stack = new ContextStack(env); + } + + @AfterSuite() + void cleanUp() { + env.shutdown() ; + } +} diff --git a/functional-tests/src/test/java/rmic/ThrowCORBAUserExServant.java b/functional-tests/src/test/java/rmic/ThrowCORBAUserExServant.java new file mode 100644 index 000000000..a3c2aeab1 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ThrowCORBAUserExServant.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import org.omg.CORBA.UserException; +import java.rmi.Remote; +import java.rmi.RemoteException; + +public class ThrowCORBAUserExServant implements ThrowCORBAUserException { + public ThrowCORBAUserExServant() throws RemoteException {} + public void a () throws RemoteException {} + public void b () throws RemoteException, CORBAUserException {} + public void c () throws RemoteException, CORBAUserException, TestException {} + public void d () throws RemoteException, CORBAUserException, UserException, TestException {} + public void e () throws RemoteException, CORBAUserException, CORBAUserException2, UserException, TestException {} + public void f () throws RemoteException, TestException, CORBAUserException, CORBAUserException2, UserException {} + public void g () throws RemoteException, UserException, CORBAUserException, TestException, CORBAUserException2 {} + public void h () throws RemoteException, TestException, CORBAUserException, CORBAUserException2 {} + public void i () throws RemoteException, CORBAUserException, TestException, CORBAUserException2 {} + public void j () throws RemoteException, CORBAUserException, CORBAUserException2,TestException {} +} diff --git a/functional-tests/src/test/java/rmic/ThrowCORBAUserException.java b/functional-tests/src/test/java/rmic/ThrowCORBAUserException.java new file mode 100644 index 000000000..b3f436259 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ThrowCORBAUserException.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import org.omg.CORBA.UserException; +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface ThrowCORBAUserException extends Remote { + void a () throws RemoteException; + void b () throws RemoteException, CORBAUserException; + void c () throws RemoteException, CORBAUserException, TestException; + void d () throws RemoteException, CORBAUserException, UserException, TestException; + void e () throws RemoteException, CORBAUserException, CORBAUserException2, UserException, TestException; + void f () throws RemoteException, TestException, CORBAUserException, CORBAUserException2, UserException; + void g () throws RemoteException, UserException, CORBAUserException, TestException, CORBAUserException2; + void h () throws RemoteException, TestException, CORBAUserException, CORBAUserException2; + void i () throws RemoteException, CORBAUserException, TestException, CORBAUserException2; + void j () throws RemoteException, CORBAUserException, CORBAUserException2,TestException; +} diff --git a/functional-tests/src/test/java/rmic/ThrowNCException.java b/functional-tests/src/test/java/rmic/ThrowNCException.java new file mode 100644 index 000000000..b9966a6fe --- /dev/null +++ b/functional-tests/src/test/java/rmic/ThrowNCException.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface ThrowNCException extends java.rmi.Remote { + void a () throws java.rmi.RemoteException, rmic.NCRemoteException; + void b () throws java.rmi.RemoteException, rmic.NCRuntimeException; +} diff --git a/functional-tests/src/test/java/rmic/ThrowNCIOException.java b/functional-tests/src/test/java/rmic/ThrowNCIOException.java new file mode 100644 index 000000000..41151150a --- /dev/null +++ b/functional-tests/src/test/java/rmic/ThrowNCIOException.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public interface ThrowNCIOException extends java.rmi.Remote { + void a () throws java.rmi.RemoteException, rmic.NCIOException; +} diff --git a/functional-tests/src/test/java/rmic/Typedef.java b/functional-tests/src/test/java/rmic/Typedef.java new file mode 100644 index 000000000..cd3d3817e --- /dev/null +++ b/functional-tests/src/test/java/rmic/Typedef.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface Typedef extends Remote { + char union (char a) throws RemoteException; + char union (long a, Object b) throws RemoteException; +} diff --git a/functional-tests/src/test/java/rmic/UID.java b/functional-tests/src/test/java/rmic/UID.java new file mode 100644 index 000000000..add721541 --- /dev/null +++ b/functional-tests/src/test/java/rmic/UID.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; + +public class UID implements java.io.Serializable { + private static final long serialVersionUID = 123456789L; +} diff --git a/functional-tests/src/test/java/rmic/ValueObject.java b/functional-tests/src/test/java/rmic/ValueObject.java new file mode 100644 index 000000000..acfdabd33 --- /dev/null +++ b/functional-tests/src/test/java/rmic/ValueObject.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +import java.rmi.server.RMIClassLoader; + +public class ValueObject implements java.io.Serializable, AbstractObject { + + int value; + + public ValueObject (int value) { + this.value = value; + } + + public boolean isValue () throws java.rmi.RemoteException { + return true; + } + + public int getValue () throws java.rmi.RemoteException { + return value; + } + + public String getCodeBase() throws java.rmi.RemoteException { + return RMIClassLoader.getClassAnnotation(getClass()); + } +} + diff --git a/functional-tests/src/test/java/rmic/ValueWithInvalidNC.java b/functional-tests/src/test/java/rmic/ValueWithInvalidNC.java new file mode 100644 index 000000000..cf456bdcf --- /dev/null +++ b/functional-tests/src/test/java/rmic/ValueWithInvalidNC.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package rmic; +public class ValueWithInvalidNC implements java.io.Serializable { + void foo(InvalidNC it) {}; +} diff --git a/functional-tests/src/test/java/test/Alarm.java b/functional-tests/src/test/java/test/Alarm.java new file mode 100644 index 000000000..c9110892e --- /dev/null +++ b/functional-tests/src/test/java/test/Alarm.java @@ -0,0 +1,314 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.util.*; + +/** + * Alarm provides a one-shot mechanism to schedule asynchronous calls + * to an AlarmHandler. + * Typical usage: + *
+ *   Alarm.scheduleWakeupFromNow(myAlarmHandler,1000); // Wait 1 second.
+ * 
+ * @author Bryan Atsatt + */ +public class Alarm implements Runnable +{ + private static Vector fgAlarms; + private static Thread fgThread; + private static boolean fgStarted; + + private AlarmHandler fHandler; + private long fWakeupTime; + + /** + * Constructor. + * @param handler the alarm handler to invoke at wake up. + * @param wakeupTime the time to wake up. + */ + public Alarm (AlarmHandler handler, long wakeupTime) + { + fHandler = handler; + fWakeupTime = wakeupTime; + } + + /** + * Check if this alarm's wakeup time is before a given alarm. + */ + public boolean isBefore (Alarm alarm) + { + return fWakeupTime < alarm.fWakeupTime; + } + + /** + * Get handler. + */ + public AlarmHandler getHandler () + { + return fHandler; + } + + /** + * Set handler. + */ + public void setHandler (AlarmHandler handler) + { + fHandler = handler; + } + + /** + * Get wakeup time. + */ + public long getWakeupTime () + { + return fWakeupTime; + } + + /** + * Set wakeup time. This does not schedule a wake up call. + */ + public void setWakeupTime (long wakeupTime) + { + fWakeupTime = wakeupTime; + } + + /** + * Schedule a wake up call relative to now. Alarms are one-shot and + * therefore must be rescheduled after wakeup if another wakeup is desired. + * @param handler the alarm handler to invoke at wake up. + * @param wakeupDeltaMillis the number of milliseconds from now at which to wake up. + * @return the scheduled alarm. + */ + public static Alarm scheduleWakeupFromNow (AlarmHandler handler, long wakeupDeltaMillis) + { + return scheduleWakeup(new Alarm(handler,System.currentTimeMillis() + wakeupDeltaMillis)); + } + + /** + * Schedule a wake up call relative to now. Alarms are one-shot and + * therefore must be rescheduled after wakeup if another wakeup is desired. + * @param theAlarm the alarm to schedule. + * @param wakeupDeltaMillis the number of milliseconds from now at which to wake up. + * @return the scheduled alarm. + */ + public static Alarm scheduleWakeupFromNow (Alarm theAlarm, long wakeupDeltaMillis) + { + theAlarm.setWakeupTime(System.currentTimeMillis() + wakeupDeltaMillis); + return scheduleWakeup(theAlarm); + } + + /** + * Schedule an alarm. Alarms are one-shot and therefore must be rescheduled after + * wakeup if another wakeup is desired. + * @param handler the alarm handler to invoke at wake up. + * @param wakeupDelta the number of milliseconds from now at which to wake up. + * @return the scheduled alarm. + */ + public static Alarm scheduleWakeup (Alarm theAlarm) + { + synchronized (fgAlarms) + { + // Start our thread if needed... + + if (fgStarted == false) + { + fgStarted = true; + fgThread.start(); + } + + // Insert alarm such that the next alarm is at the lowest index. + // Do binary search till gap is 2 or less... + + int low = 0; + int high = fgAlarms.size(); + + while (high - low > 2) + { + int middle = (low + high) / 2; + + if (theAlarm.isBefore( (Alarm)fgAlarms.elementAt(middle)) ) + { + // Shift to low half of array... + + high = middle; + } + else + { + // Shift to high half of array... + + low = middle + 1; + } + } + + // Do linear search on remaining... + + while (low < high) + { + if (((Alarm)fgAlarms.elementAt(low)).isBefore(theAlarm)) + { + low++; + } + else + { + break; + } + } + + // Ok, do insert... + + fgAlarms.insertElementAt(theAlarm,low); + + // Notify the alarm thread... + + fgAlarms.notify(); + } + + return theAlarm; + } + + /** + * Cancel a scheduled an alarm. Cancellation may fail if + * the alarm has already been fired. + * @param theAlarm the alarm to cancel. + * @return true if canceled, false otherwise. + */ + public static boolean cancelWakeup (Alarm theAlarm) + { + boolean result = false; + + synchronized (fgAlarms) + { + // Is the alarm in the queue? + + int count = fgAlarms.size(); + + for (int index = 0; index < count; index++) + { + if (fgAlarms.elementAt(index) == theAlarm) + { + // Found it. Do remove... + + fgAlarms.removeElementAt(index); + + // Set result and notify the alarm thread. + + result = true; + fgAlarms.notify(); + } + } + } + + return result; + } + + /** + * Wakeup and call handler. + */ + private void wakeup (long nextWakeupTime) + { + fHandler.wakeup(this, nextWakeupTime); + } + + /** + * The method that is executed when a Runnable object is activated. The run() method + * is the "soul" of a Thread. It is in this method that all of the action of a + * Thread takes place. + * @see Thread#run + */ + public void run() + { + while (true) + { + synchronized (fgAlarms) + { + // Wait till we have something to schedule... + + while (fgAlarms.isEmpty()) + { + try + { + fgAlarms.wait(); + } + catch (Throwable e){} + } + } + + // Wait till wakeup time of first element. Note that the lock is deliberately + // released inside the loop in order to provide access to scheduleWakeup()... + + while (true) + { + synchronized (fgAlarms) + { + if (fgAlarms.isEmpty()) break; // Can happen if canceled. + + Alarm theAlarm = (Alarm) fgAlarms.firstElement(); + + long delta = theAlarm.getWakeupTime() - System.currentTimeMillis(); + + if (delta > 0) + { + try + { + fgAlarms.wait(delta); + } + catch (Throwable e){} + } + else + { + // Time to wakeup... + + try + { + // Remove the current alarm... + + fgAlarms.removeElementAt(0); + + // Get the next wakeup time, if any... + + long nextWakeup = 0; + + if (fgAlarms.isEmpty() == false) + { + nextWakeup = ((Alarm) fgAlarms.firstElement()).getWakeupTime(); + } + + // Wake 'em up... + + theAlarm.wakeup(nextWakeup); + } + catch (Throwable e){} + + break; // Break out of loop. + } + } + } + } + } + + // Only for fgThread... + + private Alarm() + { + } + + // Init our static data... + + static + { + fgAlarms = new Vector(); + fgThread = new Thread(new Alarm(),"AlarmThread"); + fgThread.setDaemon(true); + fgStarted = false; + } +} diff --git a/functional-tests/src/test/java/test/AlarmHandler.java b/functional-tests/src/test/java/test/AlarmHandler.java new file mode 100644 index 000000000..f9153badb --- /dev/null +++ b/functional-tests/src/test/java/test/AlarmHandler.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.util.*; + +/** + * AlarmHandler provides an interface which is called asynchronously by Alarm + * at the scheduled wakeup time. + * @see Alarm + * @author Bryan Atsatt + */ +public interface AlarmHandler +{ + /** + * This method is called asynchronously at the scheduled wakeup time. May be later + * than the current time, depending on system activity and/or on the amount of time + * used by previous alarm handlers. + *

+ * The calling thread is owned by the Alarm class and is responsible for all + * alarms; therefore, it is recommended that implementations perform + * only small amounts of processing in order to ensure timely delivery of + * alarms. If, in a given process, all usage of alarms is known, implementations + * may safely use more time. The nextAlarmWakeupTime argument passed to this + * method can be used to determine how much time can be used; however, it is + * expected that few clients can effectively use this information. + * @param theAlarm The alarm. + * @param nextAlarmWakeupTime The next (currently) scheduled wakeup time for any + * alarm. May be zero, in which case there are no currently scheduled alarms. (This + * is not the next scheduled wakeup for this alarm -- alarms are one-shot and + * must be rescheduled once wakeup is called.) + */ + public abstract void wakeup (Alarm theAlarm, long nextAlarmWakeupTime); +} diff --git a/functional-tests/src/test/java/test/ClassUtils.java b/functional-tests/src/test/java/test/ClassUtils.java new file mode 100644 index 000000000..95709f630 --- /dev/null +++ b/functional-tests/src/test/java/test/ClassUtils.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.io.File; +import sun.tools.java.ClassPath; +import sun.tools.java.ClassFile; +import java.io.IOException; +import java.util.StringTokenizer; + +/** + * ClassUtils provides miscellaneous static utility methods related to + * classes and their packages. + * @author Bryan Atsatt + */ + +public class ClassUtils { + + /** + * Return the directory which contains a given class (either .java or .class). + * Uses the current system classpath. + * @param className Fully qualified class name. + * @param requireFile True if .class or .java file must be found. False if + * ok to return a directory which does not contain file. + * @return the directory or null if none found (or zipped). + */ + public static File packageDirectory (String className, boolean requireFile) { + ClassPath path = new ClassPath(System.getProperty("java.class.path")); + File result = packageDirectory(className,path,requireFile); + try { + path.close(); + } catch (IOException e) {} + + return result; + } + + /** + * Return the directory which contains a given class (either .java or .class). + * @param className Fully qualified class name. + * @param path the class path. + * @param requireFile True if .class or .java file must be found. False if + * ok to return a directory which does not contain file. + * @return the directory or null if none found (or zipped). + */ + public static File packageDirectory (String className, ClassPath path, boolean requireFile) { + + // Try binary first, then source, then directory... + + File result = packageDirectory(className,path,".class"); + if (result == null) { + result = packageDirectory(className,path,".java"); + if (result == null && !requireFile) { + int i = className.lastIndexOf('.'); + if (i >= 0) { + String packageName = className.substring(0,i); + ClassFile cls = path.getDirectory(packageName.replace('.',File.separatorChar)); + if (cls != null && ! cls.isZipped()) { + result = new File(cls.getPath()); + } + } + } + } + return result; + } + + private static boolean directoryInPath(String dirPath, String path) { + if (!dirPath.endsWith(File.separator)) { + dirPath = dirPath + File.separator; + } + StringTokenizer st = new StringTokenizer(path,"\t\n\r"+File.pathSeparator); + while (st.hasMoreTokens()) { + String entry = st.nextToken(); + if (!entry.endsWith(".zip") && + !entry.endsWith(".jar")) { + + if (entry.equals(".")) { + return true; + } else { + if (!entry.endsWith(File.separator)) { + entry = entry + File.separator; + } + if (entry.equalsIgnoreCase(dirPath)) { + return true; + } + } + } + } + + return false; + } + + private static File packageDirectory (String className, ClassPath path, String fileExt) { + + ClassFile cls = path.getFile(className.replace('.',File.separatorChar) + fileExt); + + if (cls != null && ! cls.isZipped()) { + File file = new File(cls.getPath()); + File dir = new File(file.getParent()); + return dir; + } + + return null; + } +} + diff --git a/functional-tests/src/test/java/test/Debug.java b/functional-tests/src/test/java/test/Debug.java new file mode 100644 index 000000000..498c0bbe3 --- /dev/null +++ b/functional-tests/src/test/java/test/Debug.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; +import java.util.Properties; +import java.util.Enumeration; + +public class Debug { + + private String name = null; + + public Debug (String name) { + if (name == null) { + name = ""; + } else { + this.name = name + ": "; + } + setTop(); + } + + public final void log (String msg) { + doLog(name,msg); + } + + public final void log (byte[] data) { + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < data.length; i++) { + if (i > 0) { + buf.append(' '); + } + buf.append((char)ASCII_HEX[(data[i] & 0xF0) >>> 4]); + buf.append((char)ASCII_HEX[(data[i] & 0x0F)]); + } + + doLog(name,buf.toString()); + } + + public final void logStack () { + doLogStack(name); + } + + public final void logSystemProperties () { + doLogSystemProperties(name); + } + + public final void logException (Throwable e) { + doLogException(name,e); + } + + + private static synchronized void setTop() { + lastName = "atsatt :-)"; + } + + private static synchronized void doLog (String name, String msg) { + if (log == null) { + initLog(name); + } else { + if (name != null && !name.equals(lastName)) { + log.println(" ---"); + } + } + lastName = name; + log.println(name + msg); + } + + private static String getStack(int trimSize) { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintWriter pw = new PrintWriter(os); + new Exception().printStackTrace(pw); + pw.flush(); + String result = os.toString(); + if (trimSize > 0) { + return result.substring(trimSize); + } + return result; + } + + private static void doLogStack (String name) { + doLog(name, getStack(0)); + } + + private static void doLogSystemProperties (String name) { + StringBuffer buf = new StringBuffer(); + Properties props = System.getProperties(); + buf.append("System Properties:"); + buf.append(eol); + for (Enumeration e = props.propertyNames() ; e.hasMoreElements() ;) { + String key = (String) e.nextElement(); + String value = (String) props.get(key); + buf.append(" "); + buf.append(key); + buf.append(" = "); + buf.append(value); + buf.append(eol); + } + doLog(name, buf.toString()); + } + + private static void doLogException (String name, Throwable e) { + doLog(name,"Caught " + e + eol + getStack(0)); + } + + public static void main (String[] args) { + Debug d = new Debug("main"); + d.log("Testing..."); + d.logStack(); + d.logSystemProperties(); + } + + private static PrintWriter log = null; + private static final String LOG_NAME = "DebugLog"; + private static final String LOG_EXT = ".txt"; + private static File rootDir = null; + private static String lastName = null; + private static String eol = (String)System.getProperty("line.separator"); + public static final byte ASCII_HEX[] = { + (byte)'0', + (byte)'1', + (byte)'2', + (byte)'3', + (byte)'4', + (byte)'5', + (byte)'6', + (byte)'7', + (byte)'8', + (byte)'9', + (byte)'A', + (byte)'B', + (byte)'C', + (byte)'D', + (byte)'E', + (byte)'F', + }; + + private static synchronized void initLog(String name) { + if (log == null) { + rootDir = new File(System.getProperty("user.dir")); + log = createLog(0); + log.println("Log created by " +name+" at " + new java.util.Date().toString()); + log.println(); + } + } + + private static PrintWriter createLog (int number) { + String fileName = LOG_NAME + Integer.toString(number) + LOG_EXT; + File file = new File(rootDir,fileName); + + // If file exists, assume another vm process owns it, and + // bump the number... + + if (file.exists()) { + return createLog(++number); + } + try { + FileOutputStream os = new FileOutputStream(file); + return new PrintWriter(os,true); + } catch (IOException e) { + System.err.println("Failed to create vmlog. Caught: "+e); + return null; + } + } +} diff --git a/functional-tests/src/test/java/test/DistributedSet.java b/functional-tests/src/test/java/test/DistributedSet.java new file mode 100644 index 000000000..529b4d92a --- /dev/null +++ b/functional-tests/src/test/java/test/DistributedSet.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * DistributedSet is a remote interface which supports a distributed + * collection of sets, all of which coordinate with each other to maintain, + * in each instance, a list of all the currently active sets. + * + * @version 1.0, 5/13/98 + * @author Bryan Atsatt + */ +public interface DistributedSet extends Remote { + + public static final String PING_RESPONSE = "Pong"; + + /* + * See if this set is still active. Returns PING_RESPONSE. + */ + public String ping (String fromSetName) throws RemoteException; + + /* + * Get this set's name. + */ + public String getName () throws RemoteException; + + /* + * Notify this set that the specified set is joining. If the set + * already is 'known' by this instance, this call performs no + * action. + */ + public void join (String setName, DistributedSet set) throws RemoteException; + + /* + * Notify this set that the specified set is leaving. + */ + public void leave (String setName) throws RemoteException; + + /* + * Broadcast a message to all sets. + */ + public void broadcastMessage (String message) throws RemoteException; + + /* + * Send a message to specified set. + */ + public void sendMessage (DistributedSet toSet, String message) throws RemoteException; + + /* + * Receive a message from another set. + */ + public void receiveMessage (String message, String fromSetName) throws RemoteException; + + /* + * Return the number of currently active sets, _excluding_ + * this instance. + */ + public int countSets () throws RemoteException; + + /* + * List the names of all the active sets, _excluding_ this + * instance. + */ + public String[] listSetNames () throws RemoteException; + + /* + * Get a set instance by name. Returns null if not found. + */ + public DistributedSet getSet (String setName) throws RemoteException; +} + diff --git a/functional-tests/src/test/java/test/DistributedSetMonitor.java b/functional-tests/src/test/java/test/DistributedSetMonitor.java new file mode 100644 index 000000000..e7c4612f4 --- /dev/null +++ b/functional-tests/src/test/java/test/DistributedSetMonitor.java @@ -0,0 +1,747 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.Hashtable; +import java.util.Vector; +import java.util.Enumeration; +import java.net.InetAddress; +import java.net.UnknownHostException; +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.NameClassPair; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.ORB; +import java.io.DataInputStream; +import javax.rmi.PortableRemoteObject; + +/** + * DistributedSetMonitor implements the DistributedSet interface and + * supports the addition of notifiers which enable monitoring events + * in the set. + * + * @version 1.0, 5/13/98 + * @author Bryan Atsatt + */ +public class DistributedSetMonitor extends PortableRemoteObject + implements DistributedSet, AlarmHandler { + + private Hashtable sets = new Hashtable(); + private Vector notifiers = new Vector(); + private String name = null; + private String type = null; + private String publishName = null; + private Context context = null; + private long autoRefreshDelay = 0; + + //_____________________________________________________________________ + // DistributedSet Methods + //_____________________________________________________________________ + + /* + * See if this set is still active. Returns PING_RESPONSE. + */ + public synchronized String ping (String fromSetName) throws RemoteException { + int count = notifiers.size(); + for (int i = 0; i < count; i++) { + DistributedSetNotifier notifier = + (DistributedSetNotifier) notifiers.elementAt(i); + notifier.pinged(fromSetName); + } + return PING_RESPONSE; + } + + /* + * Get this set's name. + */ + public String getName () throws RemoteException { + return name; + } + + /* + * Notify this set that the specified set is joining. If the set + * already is 'known' by this instance, this call performs no + * action. + */ + public synchronized void join (String setName, DistributedSet set) throws RemoteException { + + // Do an add, and do _not_ call set.join()... + + add(setName,set,false); + } + + + /* + * Notify this set that the specified set is leaving. + */ + public synchronized void leave (String setName) throws RemoteException { + doLeave(setName,false); + } + + /* + * Broadcast a message to all sets. + */ + public synchronized void broadcastMessage (String message) throws RemoteException { + + // Send the message to all sets... + + Enumeration e = sets.elements(); + while (e.hasMoreElements()) { + DistributedSet set = (DistributedSet) e.nextElement(); + set.receiveMessage(message,name); + } + + // Now send it to ourself... + + //receiveMessage(message,name); + } + + /* + * Send a message to specified set. + */ + public synchronized void sendMessage (DistributedSet toSet, String message) throws RemoteException { + toSet.receiveMessage(message,name); + } + + /* + * Receive a message from another set. Messages are forwarded to all + * registered notifiers. + */ + public synchronized void receiveMessage (String message, String fromSetName) throws RemoteException { + doReceiveMessage(message,fromSetName); + } + + /* + * Return the number of currently active sets, _excluding_ + * this instance. + */ + public synchronized int countSets () throws RemoteException { + return sets.size(); + } + + /* + * List the names of all the active sets, _excluding_ this + * instance. + */ + public String[] listSetNames () throws RemoteException { + return doListSetNames(); + } + + /* + * Get a set instance by name. Returns null if not found. + */ + public synchronized DistributedSet getSet (String setName) throws RemoteException { + return doGetSet(setName); + } + + //_____________________________________________________________________ + // AlarmHandler Methods + //_____________________________________________________________________ + + public void wakeup (Alarm theAlarm, long nextAlarmWakeupTime) { + + // Do the refresh... + + try { + refresh(); + } catch (ThreadDeath death) { + System.out.println("wakeup caught ThreadDeath!"); + throw death; + } catch (Error e) {} + + // Reschedule alarm if we need to... + + if (autoRefreshDelay > 0) { + Alarm.scheduleWakeupFromNow(theAlarm,autoRefreshDelay); + } + } + + //_____________________________________________________________________ + // Local Methods + //_____________________________________________________________________ + + + /* + * Constructor. + * @param orb The ORB to connect to. + * @param context The naming context to use. + * @param name The name for this instance. + * @param type The type for all instances that should be part of this + * set. May not contain '$' character. + * @param autoRefreshDelay The number of seconds between refresh calls. + * If zero, no auto-refresh will be performed. + */ + public DistributedSetMonitor ( ORB orb, + Context context, + String name, + String type, + int autoRefreshDelay) + throws RemoteException, NamingException { + this.context = context; + this.name = name; + this.type = type; + + if (autoRefreshDelay > 0) { + this.autoRefreshDelay = autoRefreshDelay * 1000; + } else { + this.autoRefreshDelay = 0; + } + + // Set publishName... + + if (type.indexOf('$') >= 0) { + throw new NamingException("type may not contain '$': " + type); + } + + publishName = type + "$" + name; + + // Connect to the ORB... + + Tie tie = javax.rmi.CORBA.Util.getTie(this); + tie.orb(orb); + + // Publish self... + + try { + context.bind(publishName, tie); + } catch (Exception e) { + + // There is already such a name registered. + // Can we reuse it? + + boolean okToReuse = false; + + try { + DistributedSet other = lookup(publishName); + if (other != null) { + try { + other.ping(this.name); + } catch (RemoteException ex) { + + // Nope, so we can reuse the name... + + okToReuse = true; + } + } else { + okToReuse = true; + } + } catch (Exception ne) { + okToReuse = true; + } + + if (okToReuse) { + + // We can reuse the name... + + context.rebind(publishName, tie); + } else { + + // We cannot reuse the name... + + PortableRemoteObject.unexportObject(this); + throw new NamingException("Name is already in use: " + name); + } + } + + // Initialize our list... + + checkNameServer(); + + // Are we supposed to auto-refresh? + + if (autoRefreshDelay > 0) { + + // Yep, so set an alarm... + + Alarm.scheduleWakeupFromNow(this,autoRefreshDelay); + } + } + + /* + * List the names of all the active sets, _excluding_ this + * instance. + */ + public synchronized String[] doListSetNames () { + int count = sets.size(); + String[] result = new String[count]; + int index = 0; + Enumeration e = sets.keys(); + while (e.hasMoreElements()) { + result[index++] = (String) e.nextElement(); + } + return result; + } + + /* + * Get a set instance by name. Returns null if not found. + */ + public synchronized DistributedSet doGetSet (String setName) { + + // Do we have it? + + DistributedSet result = (DistributedSet) sets.get(setName); + + if (result == null) { + + // No, so see if it exists in the name server... + + result = lookup(type + '$' + setName); + + if (result != null) { + + // It does, so add it... + + try { + add(setName,result,true); + } catch (RemoteException re) {} + } + } + + return result; + } + + + /* + * Destroy this instance. Must be called! + */ + public void destroy () { + + // Turn off alarms... + + autoRefreshDelay = 0; + + // Unpublish... + + try { + context.unbind(publishName); + } catch (Exception e) {} + + // Tell all sets that we are leaving... + + Enumeration e = sets.elements(); + while (e.hasMoreElements()) { + DistributedSet set = (DistributedSet) e.nextElement(); + + try { + set.leave(name); + } catch (RemoteException e1){} + } + } + + /* + * Refresh the list of active sets. Just checks to ensure that + * each registered set is still alive, and removes any that are + * not. Unfortunately, this method must perform some copying + * and therefore creates garbage. + */ + public void refresh () { + + String setName = null; + + // Are all the sets we currently know about alive? + // Since we have to call isAlive with the lock _released_, we + // need to copy all the keys and values first(!)... + + String[] allNames = null; + DistributedSet[] allSets = null; + int count; + + synchronized (this) { + count = sets.size(); + if (count > 0) { + allNames = new String[count]; + allSets = new DistributedSet[count]; + count = 0; + Enumeration e = sets.keys(); + while (e.hasMoreElements()) { + allNames[count] = (String) e.nextElement(); + allSets[count] = (DistributedSet) sets.get(allNames[count]); + count++; + } + } + } + + // Now, with the lock released, iterate and call isAlive for + // each... + + for (int i = 0; i < count; i++) { + isAlive(allNames[i],null,allSets[i]); + } + } + + public void checkNameServer () { + + String setName = null; + + try { + // Get the currently registered sets from the name server... + + // REMIND: Is there a way to limit this to names of the correct + // type, so we don't have to see if the name starts with + // a known string?? Surely there must be! Looks like + // using InitialDirContext instead of InitialContext allows + // for associating attributes with objects and doing searches + // with them, but I don't think the CosNaming provider supports + // this. + + NamingEnumeration names = context.list(""); + + // Are there any we don't know about? + + while(names.hasMore()) { + + NameClassPair pair = (NameClassPair) names.next(); + String publishName = pair.getName(); + + // Is this our type? + + int index = publishName.indexOf('$'); + if (index >= 0 && publishName.startsWith(type)) { + + // Yes, extract the name... + + setName = publishName.substring(index+1); + + // Is this one that we don't know about? + + if (!setName.equals(this.name) && + !sets.containsKey(setName)) { + + // Yes, so we must do a join... + + DistributedSet set = lookup(publishName); + + if (set == null) { + try { + context.unbind(publishName); + } catch (Exception ex3) {} + } + + if (set != null && isAlive(setName,publishName,set)) { + + try { + add(setName,set,true); + } catch (RemoteException re) {} + } + } + } + } + } catch (NamingException e) { + doReceiveMessage("checkNameServer caught " + e.toString(),setName); + } + } + + /* + * Add a notifier. + */ + public synchronized void addNotifier (DistributedSetNotifier notifier) { + notifiers.addElement(notifier); + } + + //_____________________________________________________________________ + // This main is intended only as an test/example of using a this class. + //_____________________________________________________________________ + + /* + * Start up a set. arg[0] == nameServerHost, arg[1] == nameServerPort + */ + public static void main(String[] args) { + + boolean iiop = true; + + try { + + // Get the args... + + String name = null; + String host = null; + int port = 0; + + if (args.length == 3) { + name = args[0]; + port = Integer.parseInt(args[1]); + host = args[2]; + if (host.equals("null")) { + host = null; + } + } else if (args.length == 2) { + name = args[0]; + port = Integer.parseInt(args[1]); + } else { + System.out.println("Usage: DistributedSetMonitor []"); + System.exit(1); + } + + // Create the orb and initial context... + + ORB orb = Util.createORB(host,port,null); + Context context = null; + + try { + context = Util.getInitialContext(iiop,host,port,orb); + } catch (Exception e) { + + if (host == null) { + System.out.println("Starting name server. Don't forget to kill it later!"); + + try { + Util.startNameServer(port,iiop); + } catch (Exception e1) { + System.out.println("Failed. Caught " + e1.toString()); + System.exit(1); + } + + // REMIND: We have to recreate the orb at this point! Why? + + orb = Util.createORB(host,port,null); + context = Util.getInitialContext(iiop,host,port,orb); + + } else { + + System.out.println("Could not connect to the name server. Did you forget to start it?"); + System.exit(1); + } + } + + // Create a monitor... + + DistributedSetMonitor monitor = new DistributedSetMonitor(orb,context,name,"main",5); + + // Add our notifier... + + Notifier notifier = new Notifier(monitor); + monitor.addNotifier(notifier); + + // Print out the 'commands'... + + System.out.println("\n" + name + " Ready"); + System.out.println("Type 'quit' to exit or 'message' to broadcast a message.\n"); + + // Dump the current sets... + + notifier.dumpCurrent(null); + + // Now loop till we're done... + + boolean run = true; + DataInputStream inStream = new DataInputStream(System.in); + + while (run) { + + String input = inStream.readLine(); + + if (input.indexOf("quit") >= 0) { + run = false; + monitor.destroy(); + } else { + if (input.length() > 0) { + monitor.broadcastMessage(input); + } + } + } + + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + if (e instanceof NamingException) { + String message = e.getMessage(); + if (message.indexOf("already in use") >= 0) { + System.out.println(message); + } + } else { + e.printStackTrace(System.out); + System.out.println(); + } + System.out.flush(); + } + + System.exit(0); + } + + //_____________________________________________________________________ + // Internal Methods + //_____________________________________________________________________ + + private DistributedSet lookup (String publishName) { + + DistributedSet result = null; + + try { + Object it = context.lookup(publishName); + + if (it != null) { + result = (DistributedSet) PortableRemoteObject.narrow(it,DistributedSet.class); + } + } catch (Exception e) {} + + return result; + } + + + /* + * Must be called with lock RELEASED! + */ + private boolean isAlive (String name, String publishName, DistributedSet set) { + + boolean result = true; + + try { + set.ping(this.name); + } catch (RemoteException ex) { + + result = false; + + synchronized (this) { + + // Dead set. First remove it from our list. + + doLeave(name,true); + } + + // Now make sure it is removed from the name server... + + if (publishName == null) { + publishName = type + '$' + name; + } + + try { + context.unbind(publishName); + } catch (NamingException ex3) {} + } + + return result; + } + + + private void add ( String setName, + DistributedSet set, + boolean doJoin) throws RemoteException { + + boolean added = false; + + synchronized (this) { + + // Do we already know about this set? + + if (!sets.containsKey(setName)) { + + // No, so add it... + + sets.put(setName,set); + + // Notify about the change... + + notifyChanged(true,setName,false); + + added = true; + } + } + + // Do a join, with the lock released, if + // we need to... + + if (added && doJoin) { + set.join(name,this); + } + } + + private void doLeave (String setName, boolean died) { + sets.remove(setName); + notifyChanged(false,setName,died); + } + + private void doReceiveMessage (String message, String fromSetName) { + int count = notifiers.size(); + for (int i = 0; i < count; i++) { + DistributedSetNotifier notifier = + (DistributedSetNotifier) notifiers.elementAt(i); + notifier.messageReceived(message,fromSetName); + } + } + + private void notifyChanged (boolean added, String setName, boolean died) { + int count = notifiers.size(); + for (int i = 0; i < count; i++) { + DistributedSetNotifier notifier = + (DistributedSetNotifier) notifiers.elementAt(i); + + if (added) { + notifier.setAdded(setName); + } else { + notifier.setRemoved(setName,died); + } + } + } +} + +//_____________________________________________________________________ +// Simple notifier for use by main. +//_____________________________________________________________________ + +class Notifier implements DistributedSetNotifier { + + DistributedSetMonitor set; + + Notifier(DistributedSetMonitor set) { + this.set = set; + } + + public void pinged (String fromSetName) { + // System.out.println("\nPinged by " + fromSetName); + } + + public void setAdded (String setName) { + dumpCurrent(setName + " joined. "); + } + + public void setRemoved (String setName,boolean died) { + String reason = died ? " died! " : " left. "; + dumpCurrent(setName + reason); + } + + public void messageReceived (String message, String fromSetName) { + System.out.println("<" + fromSetName + " said> " + message); + System.out.flush(); + } + + public void dumpCurrent(String prefix) { + + String[] current = set.doListSetNames(); + int count = current.length; + + if (prefix != null) { + System.out.print(prefix); + } + + if (count == 0) { + System.out.print("No current members."); + } else { + if (count == 1) { + System.out.print("1 current member: "); + } else { + System.out.print(count + " current members: "); + } + for (int i = 0; i < count; i++) { + if (i > 0) { + System.out.print(", "); + } + System.out.print(current[i]); + } + } + System.out.println(); + System.out.flush(); + } +} diff --git a/functional-tests/src/test/java/test/DistributedSetNotifier.java b/functional-tests/src/test/java/test/DistributedSetNotifier.java new file mode 100644 index 000000000..9df8411a8 --- /dev/null +++ b/functional-tests/src/test/java/test/DistributedSetNotifier.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +/** + * DistributedSetNotifier provides a simple interface for DistributedSetMonitor + * instances to provide event notification. + * + * @version 1.0, 5/13/98 + * @author Bryan Atsatt + */ +public interface DistributedSetNotifier { + public void pinged (String fromSetName); + public void setAdded (String setName); + public void setRemoved (String setName, boolean died); + public void messageReceived (String message, String fromSetName); +} + diff --git a/functional-tests/src/test/java/test/Hello.java b/functional-tests/src/test/java/test/Hello.java new file mode 100644 index 000000000..d6b83d37d --- /dev/null +++ b/functional-tests/src/test/java/test/Hello.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; +public interface Hello extends java.rmi.Remote { + public String sayHello(String to) throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/test/HelloClient.java b/functional-tests/src/test/java/test/HelloClient.java new file mode 100644 index 000000000..708cd7937 --- /dev/null +++ b/functional-tests/src/test/java/test/HelloClient.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import javax.rmi.PortableContext; +import javax.rmi.PortableRemoteObject; + +public class HelloClient { + + public static void main (String[] args) { + + try { + if (args.length > 0) { + for (int i = 0; i < args.length; i++) { + + // Get the client and narrow to our type... + + Hello ref = (Hello) PortableContext.lookup(args[i],Hello.class); + + // Call it... + + System.out.println(ref.sayHello(args[i])); + } + } else { + System.out.println("usage: HelloClient rmi|iiop://[host][:port]/publishedName..."); + } + } catch (Exception e) { + e.printStackTrace(System.out); + } + } +} diff --git a/functional-tests/src/test/java/test/HelloServant.java b/functional-tests/src/test/java/test/HelloServant.java new file mode 100644 index 000000000..5539f79ab --- /dev/null +++ b/functional-tests/src/test/java/test/HelloServant.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +public class HelloServant extends javax.rmi.PortableRemoteObject implements Hello { + + public HelloServant() throws java.rmi.RemoteException {} + public String sayHello (String to) throws java.rmi.RemoteException { + return "Hello " + to; + } +} diff --git a/functional-tests/src/test/java/test/InstallTest.java b/functional-tests/src/test/java/test/InstallTest.java new file mode 100644 index 000000000..aab28e432 --- /dev/null +++ b/functional-tests/src/test/java/test/InstallTest.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import rmic.HelloTest; +import com.sun.corba.ee.impl.util.Version; + +/* + * @test + */ +public class InstallTest extends HelloTest { + + private static boolean TIME_IT = true; + long startTime; + + public String getName () { + if (TIME_IT) startTime = System.currentTimeMillis(); + return Version.asString() + + "\n Running on JDK " + System.getProperty("java.version") + "\n" + + "\n Verifying installation (requires < 2 minutes to complete)"; + } + + public String getPassed () { + if (TIME_IT) { + long duration = System.currentTimeMillis() - startTime; + return "completed successfully in " + duration/1000 + " seconds."; + } else { + return "successful."; + } + } + + public String getFailed(Error e) { + return "failed, caught " + e; + } +} diff --git a/functional-tests/src/test/java/test/ProcessMonitor.java b/functional-tests/src/test/java/test/ProcessMonitor.java new file mode 100644 index 000000000..83433b95a --- /dev/null +++ b/functional-tests/src/test/java/test/ProcessMonitor.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.io.*; + +/** + * ProcessMonitor provides a thread which will consume output from a + * java.lang.Process and write it to the specified local streams. + * + * @version 1.0, 6/11/98 + * @author Bryan Atsatt + * + * Split into StreamReaders by Everett Anderson 8/1/2000. Note that + * the output streams will be closed at the end of the + * process's inputs. + */ +public class ProcessMonitor { + Process process; + boolean run = true; + StreamReader outReader; + StreamReader errReader; + + /** + * Constructor. + * @param theProcess The process to monitor. + * @param out The stream to which to copy Process.getInputStream() data. + * @param err The stream to which to copy Process.getErrorStream() data. + */ + public ProcessMonitor (Process theProcess, + OutputStream out, + OutputStream err) { + + process = theProcess; + + outReader = new StreamReader(out, theProcess.getInputStream()); + errReader = new StreamReader(err, theProcess.getErrorStream()); + } + + /** + * Constructor. + * @param theProcess The process to monitor. + * @param out The stream to which to copy Process.getInputStream() data. + * @param err The stream to which to copy Process.getErrorStream() data. + * @param prefix String to prepend to all copied output lines. + */ + public ProcessMonitor (Process theProcess, + OutputStream out, + OutputStream err, + String handshake) { + process = theProcess; + + outReader = new StreamReader(out, + process.getInputStream(), + handshake, + null); + errReader = new StreamReader(err, + process.getErrorStream(), + null, + null); + } + + public ProcessMonitor (Process theProcess, + OutputStream out, + OutputStream err, + String handshake, + String prefix) { + + process = theProcess; + + // Always assume the handshake is on stdout + outReader = new StreamReader(out, + process.getInputStream(), + handshake, + prefix); + errReader = new StreamReader(err, + process.getErrorStream(), + null, + prefix); + } + + + public void start() { + outReader.start(); + errReader.start(); + } + + public void waitForHandshake(long timeout) throws Exception { + outReader.waitForHandshake(timeout); + } + + // The process should have been killed/finished before + // calling this. + public void finishWriting() throws InterruptedException + { + outReader.join(); + errReader.join(); + } +} diff --git a/functional-tests/src/test/java/test/RemoteTest.java b/functional-tests/src/test/java/test/RemoteTest.java new file mode 100644 index 000000000..4b53ad529 --- /dev/null +++ b/functional-tests/src/test/java/test/RemoteTest.java @@ -0,0 +1,304 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; +import java.io.IOException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import javax.naming.NamingException; +import java.util.HashSet; +import com.sun.corba.ee.impl.util.Utility; +import java.io.File; + +/* + * @test + */ +public abstract class RemoteTest extends Test { + + public static final String NAME_SERVER_HOST_FLAG = "-nameserverhost"; + public static final String NAME_SERVER_PORT_FLAG = "-nameserverport"; + public static final String SKIP_RMIC_FLAG = "-normic"; + public static final String JRMP_FLAG = "-jrmp"; + public static final String LOCAL_SERVANTS_FLAG = "-localservants"; + public static final String NO_LOCAL_STUBS_FLAG = "-nolocalstubs"; + + // NOTE: To debug the server-side, invoke the test with -localservants + // flag which will cause any servant to be started in the same + // process as the test. You may also want to pass the -normic + // flag if you know that the stubs/ties are already present. + + protected boolean iiop = true; + + private static HashSet stubs = new HashSet(); + + /** + * Return an array of fully qualified remote interface class + * names for which stubs need to be generated. Return empty + * array if none. + */ + protected String[] getRemoteInterfaceClasses () { + return new String[0]; + } + + /** + * Return an array of fully qualified remote servant class + * names for which ties/skels need to be generated. Return + * empty array if none. + */ + protected abstract String[] getRemoteServantClasses (); + + /** + * Perform the test. + * @param context The context returned by getServantContext(). + */ + protected abstract void doTest (ServantContext context) throws Throwable; + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + + String[] result = currentArgs; + String dir = (String)getArgs().get(OUTPUT_DIRECTORY); + + if (dir != null) { + String[] extra = {"-d",dir}; + result = append(result,extra); + } + + if (getArgs().get(NO_LOCAL_STUBS_FLAG) != null) { + String[] extra = {NO_LOCAL_STUBS_FLAG}; + result = append(result,extra); + } + + return result; + } + + protected String[] append (String[] source, String[] append) { + + String result[] = source; + int appendLen = append.length; + + if (appendLen > 0) { + int sourceLen = source.length; + result = new String[appendLen + sourceLen]; + System.arraycopy(source,0,result,0,sourceLen); + System.arraycopy(append,0,result,sourceLen,appendLen); + } + + return result; + } + + /** + * Return true if stubs should only be generated once per process, false + * if they should be generated prior to each call to doTest(). Default + * is true. + */ + protected boolean generateStubsOnlyOnce () { + return iiop ? true : false; + } + + /** + * Return true if stubs should be generated in an external process. + * Default is false. + */ + protected boolean generateStubsExternally () { + return false; + } + + /** + * Generate stubs/ties. + * @param classes An array of fully qualified class names for which stubs/ties need + * to be generated. + * @param additionalRMICArgs An array of additional arguments (i.e. after -iiop and + * before classes)to rmic. + * @param onlyOnce True if stubs should only be generated once per process. + * @param iiop True if iiop stubs should be generated. + * @param external True if compile should be done in external process. + */ + protected void generateStubs ( String[] classes, + String[] additionalRMICArgs, + boolean onlyOnce, + boolean iiop, + boolean external) throws Exception + { + try { + dprint( "RemoteTest.generateStubs called" ) ; + dprint( "\tclasses = " + Test.display(classes)) ; + dprint( "\tadditionalRMICArgs = " + Test.display(additionalRMICArgs)) ; + dprint( "\tonlyOnce = " + onlyOnce ) ; + dprint( "\tiiop = " + iiop ) ; + dprint( "\texternal = " + external ) ; + + Vector list = new Vector(classes.length); + for (int i = 0; i < classes.length; i++) { + String theClass = classes[i]; + // Do we need to compile this class? + if (!stubs.contains(theClass) || !onlyOnce) { + dprint( "RemoteTest.generateStubs: adding to list " + theClass ) ; + list.addElement(theClass); + } + } + + int classCount = list.size(); + if (classCount > 0) { + String[] compileEm = new String[classCount]; + list.copyInto(compileEm); + + String genArg = null; + if (iiop) { + genArg = "-iiop"; + } else { + genArg = "-vcompat"; + } + + // Util.rmic(null,null,null,external); // _REVSISIT_ Remove! Bug in 1.2b4.1 + Util.rmic(genArg,additionalRMICArgs,compileEm,external); + + if (onlyOnce) { + for (int i = 0; i < classCount; i++) { + stubs.add(compileEm[i]); + } + } + } + } finally { + dprint( "RemoteTest.generateStubs exiting" ) ; + } + } + + + /** + * Return the servant context. This implementation uses the + * -nameserverhost and -nameserverport arguments if present, or + * gets the default context if not. + */ + protected ServantContext getServantContext () throws Exception { + + ServantContext result = null; + + Hashtable flags = getArgs(); + String host = (String)flags.get(NAME_SERVER_HOST_FLAG); + String portString = (String)flags.get(NAME_SERVER_PORT_FLAG); + + Properties sysProps = System.getProperties(); + if (flags.get(LOCAL_SERVANTS_FLAG) != null) { + if (verbose) System.out.print("(Local Servants)"); + sysProps.put(ServantContext.LOCAL_SERVANTS_FLAG,"true"); + } else { + if (verbose) System.out.print("(Remote Servants)"); + sysProps.remove(ServantContext.LOCAL_SERVANTS_FLAG); + } + + if (host == null && portString == null) { + result = ServantContext.getDefaultContext(iiop); + } else { + int port = Util.getNameServerPort(); + + if (portString != null) { + port = Integer.parseInt(portString); + } + String orbDebugFlags = (String)flags.get( ORB_DEBUG ) ; + result = ServantContext.getContext(host,port,true,iiop,orbDebugFlags); + } + + dprint( "getServantContext returns " + result ) ; + return result; + } + + public void setup () { + try { + dprint( "RemoteTest.setup called" ) ; + iiop = !getArgs().containsKey(JRMP_FLAG); + + if (!getArgs().containsKey(SKIP_RMIC_FLAG)) { + if (verbose) { + if (iiop) { + System.out.print("(IIOP) "); + } else { + System.out.print("(JRMP) "); + } + } + + // Get all the servant classes... + String[] tieClasses = getRemoteServantClasses(); + String[] servantManager = {ServantContext.SERVANT_MANAGER_CLASS}; + tieClasses = append(tieClasses,servantManager); + + // Delete ties if we are doing jrmp... + if (!iiop) { + String dir = (String)getArgs().get(OUTPUT_DIRECTORY); + if (dir != null) { + File root = new File(dir); + for (int i = 0; i < tieClasses.length; i++) { + dprint( "RemoteTest.setup: tieClass = " + tieClasses[i] ) ; + String tieClass = Utility.tieName(tieClasses[i]); + tieClass = tieClass.replace('.',File.separatorChar); + tieClass += ".class"; + File file = new File(root,tieClass); + dprint( "RemoteTest.setup: file = " + file ) ; + if (file.exists()) { + dprint( "RemoteTest.setup: deleting file" ) ; + file.delete(); + } + } + } + } + + // Generate needed stubs/ties/skels... + String[] rmicClasses = append(tieClasses,getRemoteInterfaceClasses()); + String[] additionalArgs = new String[0]; + additionalArgs = getAdditionalRMICArgs(additionalArgs); + boolean onlyOnce = generateStubsOnlyOnce(); + boolean external = generateStubsExternally(); + generateStubs(rmicClasses,additionalArgs,onlyOnce,iiop,external); + } + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + throw new Error(out.toString()); + } finally { + dprint( "RemoteTest.setup exiting" ) ; + } + } + + public void run () { + dprint( "run called" ) ; + ServantContext theContext = null; + + try { + // Do the test... + theContext = getServantContext(); + + dprint( "doTest called" ) ; + doTest(theContext); + } catch (ThreadDeath death) { + throw death; + } catch (Throwable e) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + status = new Error("Caught " + out.toString()); + } + + // Make sure we destroy the context... + + if (theContext != null) { + theContext.destroy(); + } + } +} diff --git a/functional-tests/src/test/java/test/RemoteTestExample.java b/functional-tests/src/test/java/test/RemoteTestExample.java new file mode 100644 index 000000000..81d68afcc --- /dev/null +++ b/functional-tests/src/test/java/test/RemoteTestExample.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import test.ServantContext; +import test.RemoteTest; +import javax.rmi.PortableRemoteObject; + +// NOTE: This is a template for subclasses of RemoteTest. Copy it, then: +// +// 1. Change the class name/package. +// 2. Change the static Strings as needed for your class. +// 3. Replace 'test.Hello' in the 2nd to last line with the name of your remote interface. +// 4. Replace last line with your test code. + +/* + * @test + */ +public class RemoteTestExample extends RemoteTest { + + private static final String publishName = "HelloServer"; + private static final String servantClass = "test.HelloServant"; + private static final String[] compileEm = {servantClass}; + + /** + * Return an array of fully qualified remote servant class + * names for which ties/skels need to be generated. Return + * empty array if none. + */ + protected String[] getRemoteServantClasses () { + return compileEm; + } + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + if (iiop) { + String[] ourArgs = {"-alwaysGenerate"}; + return super.getAdditionalRMICArgs(ourArgs); + } else { + return super.getAdditionalRMICArgs(currentArgs); + } + } + + /** + * Perform the test. + * @param context The context returned by getServantContext(). + */ + public void doTest (ServantContext context) throws Throwable { + + // Start up our servant. (The 'iiop' flag is set to true by RemoteTest + // unless the -jrmp flag was used). + + Remote remote = context.startServant(servantClass,publishName,true,iiop); + + if (remote == null) { + throw new Exception ("Could not start servant: " + servantClass); + } + + // Narrow to our expected interface... + + test.Hello objref = (test.Hello) PortableRemoteObject.narrow(remote,test.Hello.class); + + // TEST CODE HERE... + + System.out.println(objref.sayHello("RemoteTestExample")); + } +} diff --git a/functional-tests/src/test/java/test/ServantContext.java b/functional-tests/src/test/java/test/ServantContext.java new file mode 100644 index 000000000..722e26f6a --- /dev/null +++ b/functional-tests/src/test/java/test/ServantContext.java @@ -0,0 +1,339 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.rmi.Remote; +import java.util.Vector; +import java.util.Hashtable; +import java.util.Enumeration; +import org.omg.CORBA.ORB; +import javax.naming.Context; +import javax.naming.NamingException; +import java.io.IOException; +import javax.rmi.PortableRemoteObject; +import java.net.InetAddress; +import java.net.UnknownHostException; + +public class ServantContext implements ServantManager { + + // If a System property exists called "LOCAL_SERVANTS", the servant + // manager will be started in the current process. + + public static final String LOCAL_SERVANTS_FLAG = "LOCAL_SERVANTS"; + public static boolean LOCAL_SERVANTS = false; + + static final String SERVANT_MANAGER_CLASS = "test.ServantManagerImpl"; + static final String SERVANT_MANAGER_NAME = "ServantManager"; + + private static Hashtable contexts = new Hashtable(); + + private ORB orb = null; + private String nameServerHost = null; + private int nameServerPort = 0; + private Process nameServerProcess = null; + private Process servantManagerProcess = null; + private Context nameContext = null; + private ServantManager servantManager = null; + private String name = null; + private boolean iiop; + private String orbDebugFlags ; + private String key = null; + + public Context getNameContext () { + return nameContext; + } + + public ORB getORB () { + return orb; + } + + private ServantContext ( String nameServerHost, int nameServerPort, + boolean iiop, String key, String orbDebugFlags ) throws Exception { + Test.dprint( "ServantContext constructor called: nameServerHost = " + + nameServerHost + " nameServerPort = " + nameServerPort + + " iiop = " + iiop + " key = " + key ) ; + this.nameServerHost = nameServerHost; + this.nameServerPort = nameServerPort; + this.iiop = iiop; + this.orbDebugFlags = orbDebugFlags ; + boolean failed = true; + this.key = key; + + try { + if (nameServerHost == null) { + try { + nameServerProcess = Util.startNameServer(nameServerPort,iiop); + if (nameServerProcess == null) { + throw new IOException( + "ServantContext: could not start name server"); + } + } catch (Error e) { + if (Test.debug) + e.printStackTrace() ; + + if (e.getMessage().indexOf( "bootstrap service on port " + + nameServerPort) < 0) { + throw e; + } else { + System.out.println("Name server already started."); + } + } + + // Are we supposed to start the servant manager in this process? + if (!LOCAL_SERVANTS) { + servantManagerProcess = Util.startServer( + SERVANT_MANAGER_CLASS, getName(), nameServerHost, + nameServerPort, iiop ); + + if (servantManagerProcess == null) { + throw new IOException( + "ServantContext: could not start servant manager"); + } + } + } + + if (iiop) { + Test.dprint( "starting an ORB" ) ; + // Start up the orb... + orb = Util.createORB( nameServerHost,nameServerPort, + orbDebugFlags ); + } + + nameContext = Util.getInitialContext(iiop, + nameServerHost, nameServerPort, orb ) ; + + // Are we supposed to start the servant manager in this process? + if (!LOCAL_SERVANTS) { + Test.dprint( "LOCAL_SERVANTS is false: looking for servant manager" ) ; + Object stub = nameContext.lookup(getName()); + servantManager = (ServantManager) PortableRemoteObject.narrow( + stub, test.ServantManager.class); + } else { + Test.dprint( "LOCAL_SERVANTS is true: starting servant manager" ) ; + ServantManagerImpl impl = new ServantManagerImpl(orb,nameContext); + PortableRemoteObject.exportObject(impl); + + // Before calling toStub(), we need to make sure that the impl has + // been connected to the orb we created above. To do so, just + // look up the tie, and set the orb... + javax.rmi.CORBA.Tie tie = javax.rmi.CORBA.Util.getTie(impl); + tie.orb(orb); + + // Now get the stub... + servantManager = (ServantManager) PortableRemoteObject.toStub( + impl); + } + + // Did we succeed? + if (servantManager.ping().equalsIgnoreCase("Pong")) { + // Yep. + failed = false; + } + } finally { + Test.dprint( "ServantContext constructor is exiting" ) ; + if (failed) { + // Make sure we clean up... + destroy(); + } + } + } + + + /** + * Return this context's name. + */ + public synchronized String getName () { + if (name == null) { + + if (!LOCAL_SERVANTS) { + String host = null; + String date = Long.toString(System.currentTimeMillis()); + try { + host = InetAddress.getLocalHost().toString().replace('/',';'); + } catch (UnknownHostException e) {} + name = SERVANT_MANAGER_NAME + "[" + host + ";" + date + "]"; + } else { + + // We're debugging the server, so use a canonical name... + + name = SERVANT_MANAGER_NAME; + } + } + + return name; + } + + /** + * Start a servant in the remote process. + * @param servantClass The class of the servant object. Must have a default constructor. + * @param servantName The name by which this servant should be known. + * @param publishName True if the name should be published in the name server. + * @param iiop True if iiop. + */ + public Remote startServant( String servantClass, + String servantName, + boolean publishName, + boolean iiop) throws java.rmi.RemoteException { + + return servantManager.startServant( servantClass, + servantName, + publishName, + nameServerHost == null ? "" : nameServerHost, + nameServerPort, + iiop); + } + + /** + * Start a servant in the remote process. + * @param servantClass The class of the servant object. Must have a default constructor. + * @param servantName The name by which this servant should be known. + * @param publishName True if the name should be published in the name server. + * @param nameServerHost The name server host. May be null if local host. + * @param nameServerPort The name server port. + * @param iiop True if iiop. + */ + public Remote startServant( String servantClass, + String servantName, + boolean publishName, + String nameServerHost, + int nameServerPort, + boolean iiop) throws java.rmi.RemoteException { + + return servantManager.startServant( servantClass, + servantName, + publishName, + nameServerHost, + nameServerPort, + iiop); + } + + /** + * Unexport the specified servant. If the servant was published, will be unpublised. + */ + public void stopServant(String servantName) throws java.rmi.RemoteException { + servantManager.stopServant(servantName); + } + + /** + * Stop all servants in this context. + */ + public void stopAllServants() throws java.rmi.RemoteException { + servantManager.stopAllServants(); + } + + /** + * @Return String the String "Pong" + */ + public String ping() throws java.rmi.RemoteException { + return servantManager.ping(); + } + + /** + * Destroy this context. + */ + public void destroy () { + Test.dprint( "ServantContext.destroy called on " + name ) ; + + // Remove self from table... + synchronized (this) { + contexts.remove(key); + } + + // Destroy the name server process if needed... + + try { + if (nameServerProcess != null) { + Test.dprint( "destroying nameServerProcess" ) ; + nameServerProcess.destroy(); + nameServerProcess = null; + } + } catch (Exception e1) {} + + // Destroy the servant manager process if needed... + + try { + if (servantManagerProcess != null) { + Test.dprint( "destroying servantManagerProcess" ) ; + servantManagerProcess.destroy(); + nameServerProcess = null; + } + } catch (Exception e2) {} + } + + /** + * Destroy all contexts. MUST BE CALLED PRIOR TO PROCESS EXIT!! + */ + public static synchronized void destroyAll () { + for (Enumeration e = contexts.elements() ; e.hasMoreElements() ;) { + try { + ((ServantContext)e.nextElement()).destroy(); + } catch (Exception e1) {} + } + } + + /** + * Get the default ServantContext. + */ + public static ServantContext getDefaultContext(boolean iiop) + throws Exception { + return getContext( null, 1070, true, iiop, null ); + } + + /** + * Get or create a ServantContext. + * @param nameServerHost The host on which the name server should run. If not + * null, the name server will be started if needed. + * @param nameServerPort The port on which the name server should run. + * @param createIfNeeded If true and a context does not already exist, one will + * be created. + * @param iiop True if iiop. + */ + public static synchronized ServantContext getContext(String nameServerHost, + int nameServerPort, boolean createIfNeeded, boolean iiop, + String orbDebugFlags ) throws Exception { + + Test.dprint( "Entering ServantContext.getContext" ) ; + Test.dprint( "/tnameServerHost = " + nameServerHost ) ; + Test.dprint( "/tnameServerPort = " + nameServerPort ) ; + Test.dprint( "/tcreateIfNeeded = " + createIfNeeded ) ; + Test.dprint( "/tiiop = " + iiop ) ; + Test.dprint( "/torbDebugFlags = " + orbDebugFlags ) ; + + ServantContext result = null; + + try { + if (System.getProperty(LOCAL_SERVANTS_FLAG) != null) { + LOCAL_SERVANTS = true; + } else { + LOCAL_SERVANTS = false; + } + + String key = nameServerHost + ":" + Integer.toString(nameServerPort); + + Object it = contexts.get(key); + + if (it != null) { + result = (ServantContext) it; + } else { + if (createIfNeeded) { + result = new ServantContext( nameServerHost, nameServerPort, + iiop, key, orbDebugFlags ); + contexts.put(key,result); + } + } + } finally { + Test.dprint( "Exiting ServantContext.getContext" ) ; + } + + return result; + } +} diff --git a/functional-tests/src/test/java/test/ServantManager.java b/functional-tests/src/test/java/test/ServantManager.java new file mode 100644 index 000000000..3d8f23bd2 --- /dev/null +++ b/functional-tests/src/test/java/test/ServantManager.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.rmi.Remote; + +public interface ServantManager extends Remote { + + /** + * Start a servant in the remote process. + * @param servantClass The class of the servant object. Must have a default constructor. + * @param servantName The name by which this servant should be known. + * @param publishName True if the name should be published in the name server. + * @param nameServerHost The name server host. May be null if local host. + * @param nameServerPort The name server port. + * @param iiop True if iiop. + */ + public Remote startServant( String servantClass, + String servantName, + boolean publishName, + String nameServerHost, + int nameServerPort, + boolean iiop) throws java.rmi.RemoteException; + + /** + * Unexport the specified servant. If the servant was published, will be unpublised. + */ + public void stopServant(String servantName) throws java.rmi.RemoteException; + + /** + * Stop all servants in this context. + */ + public void stopAllServants() throws java.rmi.RemoteException; + + /** + * @Return String the String "Pong" + */ + public String ping() throws java.rmi.RemoteException; +} diff --git a/functional-tests/src/test/java/test/ServantManagerImpl.java b/functional-tests/src/test/java/test/ServantManagerImpl.java new file mode 100644 index 000000000..b41ccd9d0 --- /dev/null +++ b/functional-tests/src/test/java/test/ServantManagerImpl.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.rmi.Remote; +import java.util.Hashtable; +import java.rmi.RemoteException; +import org.omg.CORBA.ORB; +import javax.naming.Context; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import java.util.Enumeration; + +public class ServantManagerImpl implements ServantManager { + + private Hashtable table = new Hashtable(); + private ORB orb = null; + private Context context = null; + + public ServantManagerImpl() { + } + + public ServantManagerImpl(ORB orb, Context context) { + this.orb = orb; + this.context = context; + } + + /** + * Start a servant in the remote process. + * @param servantClass The class of the servant object. Must have a default constructor. + * @param servantName The name by which this servant should be known. + * @param publishName True if the name should be published in the name server. + * @param nameServerHost The name server host. May be null if local host. + * @param nameServerPort The name server port. + * @param iiop True if iiop. + */ + public synchronized Remote startServant( + String servantClass, String servantName, boolean publishName, + String nameServerHost, int nameServerPort, + boolean iiop ) throws java.rmi.RemoteException { + try { + if (nameServerHost != null && nameServerHost.equals("")) { + nameServerHost = null; + } + + // Do we already have this guy? + + Remote result = null; + State state = (State) table.get(servantName); + + if (state == null) { + + // No, make sure we have an orb if we need it... + + if (iiop) { + if (orb == null) { + Tie tie = javax.rmi.CORBA.Util.getTie(this); + + if (tie != null) { + orb = tie.orb(); + } else { + orb = Util.createORB(nameServerHost,nameServerPort, + null ); + } + } + } + + // Make sure we have our name context... + + if (context == null) { + context = Util.getInitialContext(iiop,nameServerHost,nameServerPort,orb); + } + + // Ok, create an instance and export it (if we need to)... + + Class theClass = Class.forName(servantClass); + Remote servant = (Remote) theClass.newInstance(); + + if (!(servant instanceof PortableRemoteObject)) { + PortableRemoteObject.exportObject(servant); + } + + // Are we supposed to publish it? + + if (publishName) { + + // Yes, so do it... + + context.rebind(servantName, servant); + + // Set the result with the stub + // returned by the lookup. This is needed + // to workaround a bug in the CNCtx class + // which causes it to ALWAYS connect the tie + // even if it has already been connected. By + // doing this lookup, we ensure that the IOR + // we know this guy by is correct. + + result = (Remote)context.lookup(servantName); + + } else { + + // No, so get it's tie and connect it to the orb... + + if (iiop) { + Tie tie = javax.rmi.CORBA.Util.getTie(servant); + tie.orb(orb); + result = PortableRemoteObject.toStub(servant); + } else { + result = servant; + } + } + + // Stash it away in our table... + + state = new State(); + state.remote = result; + state.published = publishName; + table.put(servantName,state); + + } else { + + // Just return the original one... + + result = state.remote; + } + + return result; + + } catch (Exception e) { + RemoteException rexc = new RemoteException (e.toString(), e ); + throw rexc ; + } + } + + /** + * Unexport the specified servant. If the servant was published, will be unpublised. + */ + public synchronized void stopServant(String servantName) throws java.rmi.RemoteException { + + try { + State state = (State) table.get(servantName); + + if (state != null) { + + // Unexport it... + + PortableRemoteObject.unexportObject(state.remote); + + // Was it published? + + if (state.published) { + + // Yes, so unpublish it... + + context.unbind(servantName); + } + } + } catch (Exception e) { + RemoteException rexc = new RemoteException (e.toString()); + rexc.initCause(e) ; + throw rexc ; + } + } + + /** + * Stop all servants in this context. + */ + public synchronized void stopAllServants() throws java.rmi.RemoteException { + for (Enumeration e = table.keys() ; e.hasMoreElements() ;) { + try { + stopServant((String) e.nextElement()); + } catch (Exception e1) {} + } + } + + /** + * @Return String the String "Pong" + */ + public String ping() throws java.rmi.RemoteException { + return "Pong"; + } + + public static void main(String[] args) { + + String host = null; + int port = Util.getNameServerPort(); + + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + if (arg.equals("-ORBInitialHost")) { + host = args[++i]; + } else if (arg.equals("-ORBInitialPort")) { + String portString = args[++i]; + port = Integer.parseInt(portString); + } + } + + if (Util.startSingleServant(ServantContext.SERVANT_MANAGER_CLASS, + ServantContext.SERVANT_MANAGER_NAME, + host, + port, + true, null ) == false) { + System.exit(1); + } + } +} + +class State { + public Remote remote; + public boolean published; +} diff --git a/functional-tests/src/test/java/test/ShutdownHook.java b/functional-tests/src/test/java/test/ShutdownHook.java new file mode 100644 index 000000000..7cbc083d4 --- /dev/null +++ b/functional-tests/src/test/java/test/ShutdownHook.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +public class ShutdownHook extends Thread { + public void run() { + System.out.println("** ShutdownHook called **"); + } +} diff --git a/functional-tests/src/test/java/test/StartRMIRegistry.java b/functional-tests/src/test/java/test/StartRMIRegistry.java new file mode 100644 index 000000000..9a381a39e --- /dev/null +++ b/functional-tests/src/test/java/test/StartRMIRegistry.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import sun.rmi.registry.RegistryImpl; +import java.rmi.registry.Registry; +import java.rmi.RMISecurityManager; + +public class StartRMIRegistry { + + private static Registry registry = null; + + /** + * Main program to start a registry.
+ * The port number can be specified on the command line. + */ + public static void main(String args[]) { + // Create and install the security manager + System.setSecurityManager(new RMISecurityManager()); + + try { + int port = Registry.REGISTRY_PORT; + if (args.length >= 1) { + port = Integer.parseInt(args[0]); + } + registry = new RegistryImpl(port); + System.out.println(Util.HANDSHAKE); + + + // prevent registry from exiting + while (true) { + try { + // The following timeout is used because a bug in the + // native C code for Thread.sleep() cause it to return + // immediately for any higher value. + Thread.sleep(Integer.MAX_VALUE - 1); + } catch (InterruptedException e) { + } + } + } catch (NumberFormatException e) { + System.out.println("Port is not a number."); + } catch (Exception e) { + System.out.println("RegistryImpl.main: an exception occurred: " + + e.getMessage()); + e.printStackTrace(); + } + System.exit(1); + } +} diff --git a/functional-tests/src/test/java/test/StreamReader.java b/functional-tests/src/test/java/test/StreamReader.java new file mode 100644 index 000000000..fb8c79f73 --- /dev/null +++ b/functional-tests/src/test/java/test/StreamReader.java @@ -0,0 +1,219 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.io.*; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * A thread which pipes everything from an input stream + * to an output stream. Note that this closes the + * output stream and dies when the reader encounters an end of + * stream! Thus just end the stream it's reading from to make + * it quit. For instance, this should occur when a process + * ends. + */ +public class StreamReader extends Thread +{ + /** + * The NULL_OUTPUT_STREAM can be used to create a StreamReader + * which reads everything from the input stream and can even + * wait for a handshake, but doesn't write to anything. + */ + public static final OutputStream NULL_OUTPUT_STREAM + = new NullOutputStream(); + + private OutputStream originalStream; + private PrintWriter out; + private BufferedReader in; + private String prefix = null; + private String handshake = null; + private int handshakeStatus = WAITING; + private List inputReceived = new LinkedList(); + + // Handshake status + private static final int WAITING = 0; + private static final int RECEIVED = 1; + private static final int ERROR = 2; + + // Prevent garbage collection so someone can run Processes + // without keeping references to their StreamReaders or + // ProcessMonitors, and still not have the program hang. + private static Map selfReferences = new IdentityHashMap(11); + + public StreamReader(OutputStream output, + InputStream input) { + originalStream = output; + out = new PrintWriter(output, true); + in = new BufferedReader(new InputStreamReader(input)); + setDaemon(true); + } + + + public StreamReader(OutputStream output, + InputStream input, + String handshake) { + this(output, input); + this.handshake = handshake; + } + + public StreamReader(OutputStream output, + InputStream input, + String handshake, + String prefix) { + this(output, input, handshake); + this.prefix = prefix; + } + + private final void output(String msg) { + if (prefix == null) + out.println(msg); + else + out.println(prefix + msg); + } + + public void run() { + + try { + + // Keep a reference to ourselves around to try to avoid garbage + // collection or stopping of this thread when it's out of scope. + // The thread should die either when the VM exits or the end of + // the stream is reached. + synchronized(selfReferences) { + selfReferences.put(this, this); + } + + setName("StreamReader"); + + int inputReceivedThreshold = 0; + while (true) { + String input = null ; + + try { + input = in.readLine(); + if (Test.debug) + System.out.println( "Streamreader.read: " + input ) ; + + // readLine should return null at the end of the + // stream + if (input == null) + break; + if (++inputReceivedThreshold > 10000) { + inputReceived.clear(); + } + + } catch (java.io.IOException exc) { + // We also can get errors due to the InputStream being + // closed. Simply treat these as termination. This + // seems to happen on JDK 1.4.1 only? + break ; + } + + // For seeing what when wrong if no handshake. + inputReceived.add(input); + + output(input); + + if (handshake != null && + handshakeStatus == WAITING && + handshake.equals(input)) { + + signalHandshakeReceived(); + } + + } + + // Process/input stream ended before the handshake + if (handshake != null && handshakeStatus == WAITING) + signalBadHandshake(); + + } finally { + synchronized(selfReferences) { + selfReferences.remove(this); + } + out.flush(); + if (originalStream != System.out && + originalStream != System.err) + out.close(); + } + } + + private synchronized void signalBadHandshake() { + if (Test.debug) + System.out.println( "Streamreader.signalBadHandshake called" ) ; + handshakeStatus = ERROR; + this.notifyAll(); + } + + private synchronized void signalHandshakeReceived() { + if (Test.debug) + System.out.println( "Streamreader.signalHandshakeReceived called" ) ; + handshakeStatus = RECEIVED; + this.notifyAll(); + } + + public synchronized void waitForHandshake() + throws InterruptedException, Exception { + + waitForHandshake(0); + } + + public synchronized void waitForHandshake(long timeout) + throws InterruptedException, Exception { + + if (handshake != null) { + if (handshakeStatus == WAITING) + this.wait(timeout); + + if (handshakeStatus == ERROR) + throw new Exception("Terminated before reading handshake (" + + handshake + ')' + '\n' + + formatInputReceived()); + + if (handshakeStatus != RECEIVED) + throw new Exception("Timed out waiting for handshake (" + + handshake + ")" + "\n" + + formatInputReceived()); + } + } + + private String formatInputReceived() + { + boolean headerWritten = false; + StringBuffer sb = new StringBuffer(); + Iterator i = inputReceived.iterator(); + while (i.hasNext()) { + if (! headerWritten) { + sb.append("Tail of input received so far:\n"); + headerWritten = true; + } + String line = (String) i.next(); + sb.append(line + '\n'); + } + return sb.toString(); + } + + private static final class NullOutputStream extends java.io.OutputStream + { + public final void close() {} + public final void flush() {} + public final void write(byte[] b) {} + public final void write(byte[] b, int offset, int len) {} + public final void write(int b) {} + } +} + + diff --git a/functional-tests/src/test/java/test/Test.java b/functional-tests/src/test/java/test/Test.java new file mode 100644 index 000000000..422df4217 --- /dev/null +++ b/functional-tests/src/test/java/test/Test.java @@ -0,0 +1,1275 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import java.lang.management.RuntimeMXBean ; +import java.lang.management.ManagementFactory ; + +import java.util.List ; +import java.util.Hashtable; +import java.util.Vector; +import java.util.Date; +import java.util.StringTokenizer; +import java.io.IOException; +import java.io.FileInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StreamTokenizer; +import java.io.BufferedReader; +import sun.tools.java.ClassPath; +import sun.tools.java.ClassFile; +import java.net.ServerSocket; +import java.util.Properties; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB ; + +/** + * The abstract Test class. The simplest way to use this class is to inherit from it + * and implement the run method. Set the status to an Error exception if the test + * did not pass. + * + * A typical invocation : + * java test.Test -test javax.rmi.CORBA.io.BaseIOTest -wait -verbose -iterate 5 + * + * @see #UsageAndExit + **/ +public abstract class Test implements java.lang.Runnable +{ + private static final boolean DEBUG_CLASS_LOADER = false ; + + static { + displayRuntimeInformation() ; + } + + public static String display( String[] args ) { + String result = null ; + for (String str : args) { + if (result == null) + result = "[" + str ; + else + result += ", " + str ; + } + result += "]" ; + return result ; + } + + public static void displayRuntimeInformation() { + if (DEBUG_CLASS_LOADER) { + RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean() ; + + System.out.println( "Boot classpath = " ) ; + for (String str : bean.getBootClassPath().split(":")) + System.out.println( "\t" + str ) ; + + System.out.println( "System classpath = " ) ; + for (String str : bean.getClassPath().split(":")) + System.out.println( "\t" + str ) ; + + List args = bean.getInputArguments() ; + System.out.println( "VM arguments:" ) ; + for (String str : args ) + System.out.println( "\t" + str ) ; + } + } + + // Set this to true to turn on the use of a security manager + // that actually enforces security (and watch all of the tests + // fail due to access exceptions). + private static final boolean USE_REAL_SECURITY_MANAGER = false ; + + // Strings MUST be lower case. The hash table is initialized + // with the command line arguments converted to lower case. + public static String OUTPUT_DIRECTORY = "-output"; + public static String TEST_CLASS_NAME_FLAG = "-test"; + public static String TEST_FILE_NAME_FLAG = "-file"; + public static String NUMBER_OF_ITERATIONS_FLAG = "-iterate"; + public static String NO_ITERATE_FLAG = "-noiterate"; + public static String VERBOSE_FLAG = "-verbose"; + public static String DEMURE_FLAG = "-demure"; + public static String SEPARATE_PROCESS_FLAG = "-separateprocess"; + public static String WAIT_FLAG = "-wait"; + public static String ORB_DEBUG = "-orbdebug"; + public static String DURATION = "duration"; + public static String STATUS = "status"; + public static String FVD_FLAG = "-fvd"; + public static String DEBUG_FLAG = "-debug"; + public static String FORK_DEBUG_LEVEL = "-forkdebuglevel"; + public static String IF_PRESENT_FLAG = "-ifpresent"; + + public static final String ORB_CLASS_KEY = "org.omg.CORBA.ORBClass"; + public static final String ORB_CLASS = "com.sun.corba.ee.impl.orb.ORBImpl"; + + protected Hashtable args; + protected Error status = null; + protected String sArgs[] = null; + protected boolean verbose = false; + protected boolean demure = false; + + private Hashtable results[]; + private static File testPackageDir = null; + private static File outputDir = null; + private static int mainResult = 0; + + public static boolean debug = false; + public static int forkDebugLevel = 0 ; + + // forkDebugLevel values + public static int DISPLAY = 1 ; + public static int ATTACH = 2 ; + + public static void dprint( String msg ) + { + if (debug) + System.out.println( "TEST: " + msg ) ; + } + + public static void UsageAndExit() + { + System.out.println(); + System.out.println("Usage: java test.Test | \n"); + System.out.println(" : -test [-iterate <#>] [-verbose] []"); + System.out.println(" : -file [-iterate <#>] [-verbose]\n"); + System.out.println(" : fully qualified test class name\n"); + System.out.println(" : @ | "); + System.out.println(" : [ | \\n]...[ | \\n]"); + System.exit(1); + } + + /** + * Takes an array of strings and produces a Hashtable wherein the keys + * are strings prefixed with a hyphen and the values are the strings which + * immediately follow such hyphen prefixed strings. However, if strings + * '-one' and '-two' are found in sequence, the key '-one' has an empty + * string for a value. + *

+ * Example : + *

+ * If an array of {'-one','-two','Value2','-three','Value3'} is the input, + * the Hashtable { key = '-one' value = ''; key = '-two' value = 'Value2'; + * key = '-three' value = 'Value3'} is the output. + * + * @param args An array of strings. + * @return The hashtable created from the array + **/ + public static Hashtable createFromConsolePairs(String args[]) + { + int i = 0; + Hashtable table = new Hashtable(); + String key, value; + + while(i < args.length){ + key = args[i].toLowerCase(); + + if (key.charAt(0) != '-') + throw new Error(key + " is not a key"); + + i++; + if (i == args.length) + value = ""; + else { + value = args[i]; + + if (value.charAt(0) == '-') { + value = ""; + } else + i++; + } + + table.put(key, value); + + } + + if (table.containsKey( DEBUG_FLAG )) + dprint( "Contents of argument table: " + table ) ; + + return table; + } + + /** + * Return a list of free ports. + **/ + public static int[] getFreePorts(int count) throws IOException { + int[] result = new int[count]; + ServerSocket[] sockets = new ServerSocket[count]; + for (int i = 0; i < count; i++) { + sockets[i] = new ServerSocket(0); + result[i] = sockets[i].getLocalPort(); + } + for (int i = 0; i < count; i++) { + sockets[i].close(); + } + return result; + } + + /** + * Gets the main argument list as a Hashtable. + **/ + public Hashtable getArgs() + { + return args; + } + + /** + * Sets the Hashtable argument list. + **/ + public void setArgs(Hashtable args) + { + try { + this.args = args; + verbose = args.containsKey(VERBOSE_FLAG); + demure = args.containsKey(DEMURE_FLAG); + + // If FVD_FLAG exists, set test boolean on IIOPInputStream. + // This forces the runtime to always use FullValueDescription + // instead of ObjectStreamClass + } catch (java.lang.Throwable thr) { + System.out.println( "Caught exception " + thr ) ; + thr.printStackTrace() ; + } + } + + /** + * Gets the main argument list as the original String array. + * @return String args[] + **/ + public String[] getArgsAsArgs() + { + return sArgs; + } + + public void createResultsTable( int num ) + { + results = new Hashtable[num] ; + } + + public static void main(String args[]) + { + // checkSunTools() ; + + if (System.getProperty( "jcov" ) != null) + Runtime.getRuntime().addShutdownHook( + new ShutdownHook() ) ; + + try { + if (USE_REAL_SECURITY_MANAGER) + System.setSecurityManager( new SecurityManager() ) ; + else + // This disables all security checks. + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + + // Initialize the port based properties with free ports... + + Properties sysProps = System.getProperties(); + int[] ports = getFreePorts(2); + + if (sysProps.get("http.server.port") == null) { + // System.out.println("Setting http.server.port = "+ports[0]); + sysProps.put("http.server.port",Integer.toString(ports[0])); + } + + if (sysProps.get("name.server.port") == null) { + // System.out.println("Setting name.server.port = "+ports[1]); + sysProps.put("name.server.port",Integer.toString(ports[1])); + } + + if (sysProps.get("java.rmi.server.codebase") == null) { + String codebase = "http://localhost:"+Integer.toString(ports[0])+"/"; + // System.out.println("Setting java.rmi.server.codebase = "+codebase); + sysProps.put("java.rmi.server.codebase",codebase); + } + + // Initialize the ORB class property... + if (sysProps.get(ORB_CLASS_KEY) == null) { + sysProps.put(ORB_CLASS_KEY, ORB_CLASS); + } + + // Run the test... + + if (run(args)) { + System.out.println("\nTests Completed\n ---- Press CTRL-C to Finish ----"); + while(true); + } + } catch (Throwable thr) { + System.out.println("Unexpected throwable: " + thr ) ; + thr.printStackTrace() ; + mainResult = 1; + } finally { + // Make sure we clean up... + ServantContext.destroyAll(); + + // And ensure we exit... + System.exit(mainResult); + } + } + + + /** + * Get a resource as stream given a fully qualified class name. + * @param className The fully qualified class name. + * @param extensionName The resource extension name (e.g. ".class", ".properties", etc). + **/ + public static InputStreamReader getResource ( String className, + String extensionName) + throws ClassNotFoundException { + + // Get the class instance... + + Class theClass = Class.forName(className); + + // Create the resource name... + + String resourceName = className; + int index = resourceName.lastIndexOf('.'); + + if (index >= 0) { + resourceName = resourceName.substring(index+1); + } + + resourceName += extensionName; + + // Get the resource stream... + + InputStream resource = theClass.getResourceAsStream(resourceName); + + // Wrap it up and return it as a InputStreamReader... + + if (resource != null) { + return new InputStreamReader(resource); + } else { + return null; + } + } + + /** + * Return the specified resource as an array of strings. Whitespace is trimmed + * from both ends of all strings. Blank lines are ignored. + * @param className The fully qualified class name. + * @param extensionName The resource extension name (e.g. ".classlist", ".array", etc). + * @param ignoreLinesStartingWith Any lines which begin with this string (after + * whitespace has been trimmed) will be ignored. May be null. + */ + protected String[] getResourceAsArray ( String className, + String extensionName, + String ignoreLinesStartingWith) + throws ClassNotFoundException, IOException { + + String[] result = null; + InputStreamReader inStream = getResource(className,extensionName); + + if (inStream == null) { + throw new Error("Could not load resource: " + className + extensionName); + } + + try { + Vector list = new Vector(); + BufferedReader in = new BufferedReader(inStream); + + while (true) { + String line = in.readLine(); + if (line != null) { + line = line.trim(); + if (line.length() > 0) { + if (ignoreLinesStartingWith == null || !line.startsWith(ignoreLinesStartingWith)) { + list.addElement(line); + } + } + } else { + break; + } + } + + result = new String[list.size()]; + list.copyInto(result); + + } finally { + inStream.close(); + } + + return result; + } + + /** + * Compare two resources for the given class, ignoring whitespace. + * @param className The fully qualified class name. + * @param sourceExtension The 'file' extension for the source (e.g. ".properties"). + * @param targetExtension The 'file' extension for the target (e.g. ".reference"). + * @param ignorePrefix Ignore all lines beginning with these strings. May be null. + */ + public void compareUnorderedResources ( String className, + String sourceExtension, + String targetExtension, + String[] ignorePrefix) + throws ClassNotFoundException, + IOException { + + // Get resources as string arrays and check them... + + String[] source = getResourceAsArray(className,sourceExtension,null); + String[] target = getResourceAsArray(className,targetExtension,null); + + if (source == null) { + throw new Error("Could not load " + className + sourceExtension + " resource."); + } + + if (target == null) { + throw new Error("Could not load " + className + targetExtension + " resource."); + } + + if (source.length != target.length) { + throw new Error("Resource comparison failed for " + className + ": resource lengths different"); + } + + // Sort them... + + sort(source); + sort(target); + + // Compare them... + + for (int i = 0; i < source.length; i++) { + + boolean match = true; + + if (!source[i].equals(target[i])) { + + // Doesn't match. Should we ignore both lines? + + boolean doTokenMatch = true; + boolean ignoreSource = false; + boolean ignoreTarget = false; + + if (ignorePrefix != null) { + for (String anIgnorePrefix : ignorePrefix) { + if (source[i].startsWith(anIgnorePrefix)) { + ignoreSource = true; + } + if (target[i].startsWith(anIgnorePrefix)) { + ignoreTarget = true; + } + } + } + + // Are we supposed to ignore BOTH lines? + + if (ignoreSource && ignoreTarget) { + + // Yes, so skip token match and leave match = true... + + doTokenMatch = false; + + } else { + + // No, are we supposed to ignore ONE line? + + if (ignoreSource || ignoreTarget) { + + // Yes, so skip token match and set match = false... + + doTokenMatch = false; + match = false; + } + } + + if (doTokenMatch) { + + // Nope, so tokenize, sort and re-compare... + + StringTokenizer s = new StringTokenizer(source[i],", \n\t\r"); + StringTokenizer t = new StringTokenizer(target[i],", \n\t\r"); + + int sLen = s.countTokens(); + int tLen = t.countTokens(); + + if (sLen == tLen) { + String[] sTokens = new String[sLen]; + String[] tTokens = new String[sLen]; + int j = 0; + while (s.hasMoreTokens()) { + sTokens[j++] = s.nextToken(); + } + j = 0; + while (t.hasMoreTokens()) { + tTokens[j++] = t.nextToken(); + } + sort(sTokens); + sort(tTokens); + for (j = 0; j < sLen; j++) { + if (!sTokens[j].equals(tTokens[j])) { + match = false; + break; + } + } + } else { + match = false; + } + } + } + + if (!match) { + String error = "found '" + source[i] + "', expected '" + target[i] + "'."; + throw new Error("Resource comparison failed for " + className + ": " + error); + } + } + } + + + /** + * Compare two resources for the given class, ignoring whitespace. + * @param className The fully qualified class name. + * @param sourceExtension The 'file' extension for the source (e.g. ".properties"). + * @param targetExtension The 'file' extension for the target (e.g. ".reference"). + */ + public void compareResources ( String className, + String sourceExtension, + String targetExtension) + throws ClassNotFoundException, + IOException { + boolean done = false; + InputStreamReader inStream = null; + InputStreamReader refStream = null; + + try { + // First, get our resource streams and make sure they are valid... + inStream = getResource(className,sourceExtension); + refStream = getResource(className,targetExtension); + + if (inStream == null) { + throw new Error("Could not load " + className + sourceExtension + " resource."); + } + + if (refStream == null) { + throw new Error("Could not load " + className + targetExtension + " resource."); + } + + StreamTokenizer in = new StreamTokenizer(inStream); + StreamTokenizer ref = new StreamTokenizer(refStream); + + // Turn off 'number' parsing... + in.ordinaryChars('0','9'); + in.wordChars('0','9'); + in.ordinaryChars('-','-'); + in.wordChars('-','-'); + in.ordinaryChars('.','.'); + in.wordChars('.','.'); + + ref.ordinaryChars('0','9'); + ref.wordChars('0','9'); + ref.ordinaryChars('-','-'); + ref.wordChars('-','-'); + ref.ordinaryChars('.','.'); + ref.wordChars('.','.'); + + while (!done) { + String expected = null; + String found = null; + + if (in.nextToken() == ref.nextToken()) { + if (in.ttype == StreamTokenizer.TT_EOF) { + done = true; + } else { + if (in.sval == null && ref.sval == null) { + } else { + if (in.sval == null || ref.sval == null || !in.sval.equals(ref.sval)) { + found = in.sval; + expected = ref.sval; + } + } + } + } else { + found = String.valueOf((char)in.ttype); + expected = String.valueOf((char)ref.ttype); + } + + if (expected != null) { + String error = "found '" + found+ "', expected '" + expected + "' (line " + in.lineno() + ")."; + throw new Error("Resource comparison failed for " + className + ": " + error); + } + } + } finally { + if (inStream != null) + inStream.close(); + if (refStream != null) + refStream.close(); + } + } + + + // Returns a platform specific build classes directory (either windows or unix ONLY). + // Returns null if tests are in test jar or build directory does not exist. + // + // NOTE : This is meant strictly for the original RMI-IIOP workspace structure. + public static String getClassesDirectory(String childWorkspace) { + + String className = "com.sun.corba.ee.impl.orb.ORBImpl"; + ClassPath classPath = new ClassPath(System.getProperty("java.class.path")); + ClassFile cls = classPath.getFile(className.replace('.',File.separatorChar) + ".class"); + try { + classPath.close(); + } catch (IOException e) { + // ignore + } + + if (cls != null) { + + File pathDir; + + // Ok, we have a ClassFile for com.sun.corba.ee.impl.orb.ORBImpl.class. Is it in + // a zip file? + + if (cls.isZipped()) { + + return null; + + } else { + String platform = "win32"; + + // No, so walk back to root... + + String path = cls.getPath(); + if (File.separatorChar == '\\') { + path = path.replace('/',File.separatorChar); + } else { + platform = "solaris"; + path = path.replace('\\',File.separatorChar); + } + File dir = new File(path); + + + // the hardcoded number 10 has to be changed depending on + // the hierarchy presented by the className, if the hierarchy + // changes then this number needs to be changed + + for (int i = 0; i < 10; i++) { + dir = new File(dir.getParent()); + + } + + pathDir = new File(dir, + childWorkspace+File.separatorChar+ + "build"+File.separatorChar+ + platform+File.separatorChar+ + "classes"); + } + + // If we have a directory, update the Hashtable... + + if (pathDir.exists() && pathDir.isDirectory()) { + return pathDir.getPath(); + } + else return null; + } + else return null; + } + + private static void setDefaultOutputDir(Hashtable flags) { + String outputDir = flags.get(OUTPUT_DIRECTORY); + if (outputDir == null) { + + // No output dir, so set to gen if present... + + String className = "com.sun.corba.ee.spi.orb.ORB"; + ClassPath classPath = new ClassPath(System.getProperty("java.class.path")); + ClassFile cls = classPath.getFile(className.replace('.',File.separatorChar) + ".class"); + try { + classPath.close(); + } catch (IOException e) { + // discard any exception + } + + if (cls != null) { + + File genDir = null; + + // Ok, we have a ClassFile for com.sun.corba.ee.spi.orb.ORB.class. Is it in + // a zip file? + + if (cls.isZipped()) { + + // Yes. _REVISIT_ + + System.out.println("test.Test found com.sun.corba.ee.spi.orb.ORB.class in: " + cls.getPath()); + System.out.println("The output directory did not default to 'gen'."); + + } else { + + // No, so walk back to root... + + String path = cls.getPath(); + if (File.separatorChar == '\\') { + path = path.replace('/',File.separatorChar); + } else { + path = path.replace('\\',File.separatorChar); + } + File dir = new File(path); + + for (int i = 0; i < 7; i++) { + dir = new File(dir.getParent()); + + } + + genDir = new File(dir,"gen"); + } + + // If we have a directory, update the Hashtable... + + if (genDir != null && genDir.exists() && genDir.isDirectory()) { + flags.put(OUTPUT_DIRECTORY,genDir.getPath()); + } + } + } + } + + private static boolean expandMagicDirectoryFor(String key, Hashtable flags) { + + boolean result = false; + String value = flags.get(key); + + // Do we need to expand our magic directory? + + if (value != null && (value.startsWith("%") || value.startsWith("@"))) { + + // Yes, do we already have our test directory? + + if (testPackageDir == null) { + + // Nope, so look it up... + + testPackageDir = ClassUtils.packageDirectory("test.Test",true); + + if (testPackageDir == null || !testPackageDir.isDirectory()) { + System.out.println("Cannot find directory for 'test'."); + System.exit(1); + } + + // Make an output dir also... + + outputDir = new File(testPackageDir.getParent()); + } + + // Make a new value... + + String magicValue; + + if (key.equals(OUTPUT_DIRECTORY)) { + magicValue = outputDir.getPath(); + } else { + + if (value.length() > 1) { + File theFile = new File(testPackageDir,value.substring(1)); + magicValue = theFile.getPath(); + } else { + magicValue = testPackageDir.getPath(); + } + } + + // Change the value in the hashtable... + + flags.put(key,magicValue); + result = true; + } + + return result; + } + + public String getPassed() { + return "Passed"; + } + + public String getFailed(Error e) { + return "Failed, caught " + e; + } + + public String getName () { + String className = getClass().getName(); + int index = className.lastIndexOf('.'); + if (index >= 0) { + return className.substring(index+1); + } else { + return className; + } + } + + public static boolean run( String args[]) + { + Hashtable flags = createFromConsolePairs(args); + + // Expand our 'magic' directories, if need be... + expandMagicDirectoryFor(TEST_FILE_NAME_FLAG,flags); + expandMagicDirectoryFor(OUTPUT_DIRECTORY,flags); + setDefaultOutputDir(flags); + + String testClassName = flags.get(TEST_CLASS_NAME_FLAG); + + // Are we running a single test class? + + + if (testClassName != null) { + runTestClass(testClassName,flags,args); + } else { + // No, are we running a test file? + String testFileName = flags.get(TEST_FILE_NAME_FLAG); + + if (testFileName != null) { + // Yes, so do it... + runTestFile(testFileName,args); + } else { + // Nope, so error... + UsageAndExit(); + } + } + + return (flags.containsKey(WAIT_FLAG)) ; + } + + private static boolean useDynamicStubs() + { + // return Boolean.getBoolean( + // ORBConstants.USE_DYNAMIC_STUB_PROPERTY ) ; + return ORB.getPresentationManager().useDynamicStubs() ; + } + + private static boolean useCodegenReflectiveCopyobject() + { + return Boolean.getBoolean( + ORBConstants.USE_CODEGEN_REFLECTIVE_COPYOBJECT ) ; + } + + // This is needed in several tests. + public static boolean useJavaSerialization() + { + return Boolean.getBoolean( + ORBConstants.ENABLE_JAVA_SERIALIZATION_PROPERTY ) ; + } + + public static boolean debugORBInit() + { + return Boolean.getBoolean( + ORBConstants.INIT_DEBUG_PROPERTY ) ; + } + + public static void identifyEnvironment() + { + System.out.println( "Running on " + new Date() ) ; + System.out.println( "Running with " + (useCodegenReflectiveCopyobject() ? + "codegen" : "standard") + " reflective object copier" ) ; + System.out.println( "Running with " + (useDynamicStubs() ? + "dynamic" : "static") + " stubs" ) ; + System.out.println("Running with serialization encoding: " + + (useJavaSerialization() ? "JSG" : "CDR")); + System.out.println( "Dynamic StubFactoryFactory: " + + ORB.getPresentationManager().getDynamicStubFactoryFactory() ) ; + System.out.println("Encoding is " + + (useJavaSerialization() ? "JSG" : "CDR")); + System.out.println("ORB initialization debugging is " + + (debugORBInit() ? "on" : "off")); + System.out.println( "Environment:" ) ; + System.out.println( " java.version = " + + System.getProperty( "java.version" ) ) ; + System.out.println( " java.vm.name = " + + System.getProperty( "java.vm.name" ) ) ; + System.out.println( " os.name = " + + System.getProperty( "os.name" ) ) ; + System.out.println( " os.arch = " + + System.getProperty( "os.arch" ) ) ; + System.out.println( " os.version = " + + System.getProperty( "os.version" ) ) ; + } + + public static void runTestFile(String testFile, String[] args) { + if (testFile == null) + UsageAndExit(); + + // Open up the file... + Vector lines = new Vector(); + DataInputStream stream = null; + + try { + // Make sure the file exists... + + File theFile = new File(testFile); + + if (!theFile.exists()) { + System.out.println("Test file does not exist: " + + theFile.getPath()); + System.exit(1); + } + + // Read all the lines into the 'lines' vector... + stream = new DataInputStream(new FileInputStream(theFile)); + + String line = stream.readLine(); + + while (line != null) { + line = line.trim(); + + if (!line.startsWith("//") && !line.equals("")) { + lines.addElement(line); + } + + line = stream.readLine(); + } + + stream.close(); + + System.out.println( "======================================================================" ) ; + System.out.println( "CORBA test suite " + testFile ) ; + identifyEnvironment() ; + System.out.println( "======================================================================" ) ; + + // Run all tests... + int testCount = lines.size(); + for (int i = 0; i < testCount; i++) { + line = lines.elementAt(i); + + // Parse the line -- format is same as for main... + StringTokenizer parser = new StringTokenizer(line, + ", \t\n\r", false); + + int count = parser.countTokens(); + String[] testArgs = new String[count]; + for (int j = 0; j < count; j++) { + testArgs[j] = parser.nextToken(); + } + + // Concatenate the two sets of args... + String[] theArgs = new String[args.length + testArgs.length]; + System.arraycopy(args,0,theArgs,0,args.length); + System.arraycopy(testArgs,0,theArgs,args.length,testArgs.length); + + // See if we have -separateprocess flag... + boolean ownProcess = false; + for (String testArg : testArgs) { + if (testArg.equalsIgnoreCase(SEPARATE_PROCESS_FLAG)) { + ownProcess = true; + break; + } + } + + // Now run it... + if (ownProcess) { + Vector command = new Vector(); + command.addElement(System.getProperty("java.home") + "/bin/java"); + command.addElement("-classpath"); + command.addElement(System.getProperty("java.class.path")); + + command.addElement( + "-Djavax.rmi.CORBA.UtilClass=" + + "com.sun.corba.ee.impl.javax.rmi.CORBA.Util"); + command.addElement( + "-Djavax.rmi.CORBA.StubClass=" + + "com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl"); + command.addElement( + "-Djavax.rmi.CORBA.PortableRemoteObjectClass=" + + "com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject"); + + Util.inheritProperties( command ) ; + + command.addElement("test.Test"); + + for (String testArg : testArgs) { + command.addElement(testArg); + } + + for (int j = 0; j < args.length; j++) { + if (args[j].equals(TEST_FILE_NAME_FLAG)) { + j++; + } else { + command.addElement(args[j]); + } + } + + String[] theCommand = new String[command.size()]; + command.copyInto(theCommand); + + if (forkDebugLevel >= DISPLAY) { + System.out.println( "Forking Test:" ) ; + for (String str : theCommand) + System.out.println( "\t" + str ) ; + } + + int result = Util.execAndWaitFor(theCommand,System.out, + System.err); + + if (result != 0) { + mainResult = result; + } + } else { + run(theArgs); + } + } + } catch (IOException e1) { + try { + if (stream != null) stream.close(); + } catch (IOException e2) { + // ignore exception + } + } + } + + private static int getInt( String str ) { + dprint( "getInt called with " + str ) ; + if (str == null) + return 0 ; + + try { + return Integer.parseInt( str ) ; + } catch (NumberFormatException exc) { + return 0 ; + } + } + + public static void runTestClass(String testClassName, Hashtable flags, String args[]) { + dprint( "Running test " + testClassName ) ; + + if (testClassName == null) + UsageAndExit(); + + Test testObj = null; + + try{ + testObj = (Test)Class.forName(testClassName).newInstance(); + } catch(ClassNotFoundException cnfe) { + System.out.print( " " + testClassName + ": not found - " ) ; + if (flags.containsKey( IF_PRESENT_FLAG ) ) { + System.out.println( "skipping execution" ) ; + return ; + } else { + System.out.println( cnfe ) ; + cnfe.printStackTrace() ; + UsageAndExit() ; + } + } catch(Throwable e) { + e.printStackTrace(); + UsageAndExit(); + } + + testObj.sArgs = args; + testObj.setArgs(flags); + + debug = flags.containsKey (DEBUG_FLAG); + forkDebugLevel = getInt( (String)flags.get( FORK_DEBUG_LEVEL ) ) ; + dprint( "forkDebugLevel = " + forkDebugLevel ) ; + + int iterations = 1; + long sum = 0; + boolean noIterate = flags.containsKey(NO_ITERATE_FLAG); + if (!noIterate && flags.containsKey(NUMBER_OF_ITERATIONS_FLAG)) + iterations = Integer.parseInt(flags.get( NUMBER_OF_ITERATIONS_FLAG)); + testObj.createResultsTable( iterations ) ; + + try { + boolean verbose = flags.containsKey(VERBOSE_FLAG); + boolean demure = flags.containsKey(DEMURE_FLAG); + String info = ""; + if (flags.containsKey(FVD_FLAG)) + info = " (Using FVD) "; + + if (verbose) { + System.out.print(" " + testClassName + info + ": "); + } else if (demure) { + System.out.print(" " + testObj.getName() + " ... "); + } + + dprint( "setup called on test" ) ; + testObj.setup(); + + for (int i = 0; i < iterations; i++) { + dprint( "Iteration " + i + " begins" ) ; + if (verbose) { + System.out.print("Run " + (i+1) + " : "); + System.out.flush(); + } + + dprint( "beginAnIteration called" ) ; + testObj.beginAnIteration(); + + long start = System.currentTimeMillis(); + + dprint( "run called" ) ; + try { + testObj.run(); + } catch (Error e) { + dprint( "run returned error " + e ) ; + testObj.status = e; + } + + long duration = System.currentTimeMillis() - start; + sum = sum + duration; + dprint( "finishAnIteration called" ) ; + Error status = testObj.finishAnIteration(); + testObj.results[i] = new Hashtable(); + testObj.results[i].put(DURATION, duration); + if (status != null) { + testObj.results[i].put(STATUS, status); + mainResult = 1; + } + + if (verbose) { + System.out.print("[" + duration + "ms] "); + if (status == null) System.out.println("PASSED"); + else { + System.out.println("FAILED"); + System.out.println(status.getMessage()); + } + System.out.flush(); + } else if (demure) { + if (status == null) { + System.out.println(testObj.getPassed()); + } else { + System.out.println(testObj.getFailed(status)); + } + System.out.flush(); + } + } + + if (verbose && iterations > 1) { + System.out.println(" AVERAGE TIME (MS) = " + (sum/iterations)); + } + + testObj.finish(); + + } catch (Throwable e) { + if (e instanceof ThreadDeath) { + throw (ThreadDeath) e; + } else { + mainResult = 1; + System.out.print( " " + testClassName + + " failed, caught: " + e); + e.printStackTrace(); + } + } + } + + /** + * Called before the iteration testing for the test class begins. General setup + * can be done here. + **/ + public void setup() + { + // no op + } + + /** + * Prepare for a single interation just before run() is called. + **/ + public void beginAnIteration() + { + status = null; + } + + /** + * Your test method. Set the Test.status Error code to a java.lang.Error instance + * if the test did not pass. Otherwise, leave the status field as null. + **/ + public abstract void run(); + + /** + * This is called after the run() method finishes to collect status. + * + * @return The status(An Error upon failure or null if success) + **/ + public Error finishAnIteration() + { + return status; + } + + /** + * Called when all iterations over a test class are completed. General cleanup + * can be done here. + **/ + public void finish() + { + // no op + } + + + public static void sort(String a[]) + { + quickSort(a, 0, a.length - 1); + } + + + /** This is a generic version of C.A.R Hoare's Quick Sort + * algorithm. This will handle arrays that are already + * sorted, and arrays with duplicate keys.
+ * + * If you think of a one dimensional array as going from + * the lowest index on the left to the highest index on the right + * then the parameters to this function are lowest index or + * left and highest index or right. The first time you call + * this function it will be with the parameters 0, a.length - 1. + * + * @param a a String array + * @param lo0 left boundary of array partition + * @param hi0 right boundary of array partition + */ + private static void quickSort(String a[], int lo0, int hi0) { + int lo = lo0; + int hi = hi0; + String mid; + + if ( hi0 > lo0) { + + /* Arbitrarily establishing partition element as the midpoint of + * the array. + */ + mid = a[ ( lo0 + hi0 ) / 2 ]; + + // loop through the array until indices cross + while( lo <= hi ) { + /* find the first element that is greater than or equal to + * the partition element starting from the left Index. + */ + while( ( lo < hi0 ) && ( a[lo].compareTo(mid) < 0 )) + ++lo; + + /* find an element that is smaller than or equal to + * the partition element starting from the right Index. + */ + while( ( hi > lo0 ) && ( a[hi].compareTo(mid) > 0 )) + --hi; + + // if the indexes have not crossed, swap + if( lo <= hi ) + { + swap(a, lo, hi); + ++lo; + --hi; + } + } + + /* If the right index has not reached the left side of array + * must now sort the left partition. + */ + if( lo0 < hi ) + quickSort( a, lo0, hi ); + + /* If the left index has not reached the right side of array + * must now sort the right partition. + */ + if( lo < hi0 ) + quickSort( a, lo, hi0 ); + } + } + + private static void swap(String a[], int i, int j) + { + String T; + T = a[i]; + a[i] = a[j]; + a[j] = T; + + } +} + diff --git a/functional-tests/src/test/java/test/Util.java b/functional-tests/src/test/java/test/Util.java new file mode 100644 index 000000000..fee9842aa --- /dev/null +++ b/functional-tests/src/test/java/test/Util.java @@ -0,0 +1,907 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test; + +import com.sun.corba.ee.impl.util.JDKBridge; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; +import sun.rmi.rmic.Main; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.rmi.Remote; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; + +public class Util { + + static private boolean debug = false ; + + static public void trace( String msg ) + { + if (debug) + System.out.println( msg ) ; + } + + public static final String HANDSHAKE = "Ready."; + + /* + * Create an ORB. + */ + public static ORB createORB ( String nameServerHost, + int nameServerPort, String orbDebugFlags ) { + // Setup the name server arguments... + String[] nameServerArgs; + + if (nameServerHost != null) { + nameServerArgs = new String[4]; + nameServerArgs[2] = "-ORBInitialHost"; + nameServerArgs[3] = nameServerHost; + } else { + nameServerArgs = new String[2]; + } + + nameServerArgs[0] = "-ORBInitialPort"; + nameServerArgs[1] = Integer.toString(nameServerPort); + + // Setup the ORB properties... + + Properties props = System.getProperties(); + + props.put("org.omg.CORBA.ORBClass", "com.sun.corba.ee.impl.orb.ORBImpl"); + props.put("org.omg.CORBA.ORBSingletonClass", "com.sun.corba.ee.impl.orb.ORBSingleton"); + + if (orbDebugFlags != null) + props.put( ORBConstants.DEBUG_PROPERTY, orbDebugFlags ) ; + + // Create and return the ORB... + return ORB.init(nameServerArgs, props); + } + + /* + * Start up the ORB and return the name context. + * Name server must be started prior to this call. + */ + public static Context startORBAndGetNameContext (String nameServerHost, + int nameServerPort, String orbDebugFlags ) throws Exception { + // Create the ORB... + ORB orb = createORB( nameServerHost, nameServerPort, orbDebugFlags ); + + // Return the initial context... + return getInitialContext(true,nameServerHost,nameServerPort,orb); + } + + /* + * Get the initial context. + * Name server must be started prior to this call. + */ + public static Context getInitialContext ( boolean iiop, + String nameServerHost, + int nameServerPort, + ORB orb) + throws Exception { + Context result = null; + + // Create a hashtable with the correct properties... + + Hashtable env = new Hashtable(); + + if (iiop) { + + env.put("java.naming.corba.orb", orb); + env.put("java.naming.factory.initial", JndiConstants.COSNAMING_CONTEXT_FACTORY); + + } else { + + String serverUrl = "rmi://"; + + if (nameServerHost != null && !nameServerHost.equals("")) { + serverUrl += nameServerHost; + } + + serverUrl += ":" + Integer.toString(nameServerPort); + + env.put("java.naming.factory.initial", JndiConstants.REGISTRY_CONTEXT_FACTORY); + env.put("java.naming.provider.url",serverUrl); + } + + // Now get and return our context... + + return new InitialContext(env); + } + + + /* + * Start up the ORB and lookup object reference. + * Name server must be started prior to this call. + */ + public static Object startORBAndLookup ( + String servantName, String nameServerHost, int nameServerPort, + String orbDebugFlags ) throws Exception { + // Start the ORB and get a name context... + Context context = startORBAndGetNameContext( nameServerHost, + nameServerPort, orbDebugFlags ); + + // Now do the lookup and return it... + + return context.lookup(servantName); + } + + public static int getHttpServerPort() { + String prop = System.getProperty("http.server.port"); + if (prop != null) { + return Integer.parseInt(prop); + } else { + throw new Error("Must set http.server.port property"); + } + } + + public static int getNameServerPort() { + String prop = System.getProperty("name.server.port"); + if (prop != null) { + return Integer.parseInt(prop); + } else { + throw new Error("Must set name.server.port property"); + } + } + + public static void setDefaultCodeBase(boolean iiop) { + + // If we don't have a codebase set, set it to a + // reasonable default (iiop only)... + + if (iiop) { + String codebaseKey = "java.rmi.server.codebase"; + if (System.getProperty(codebaseKey) == null) { + String codebase = "http://localhost:" + getHttpServerPort() + "/"; + System.getProperties().put(codebaseKey,codebase); + JDKBridge.setCodebaseProperties(); + } + } else { + JDKBridge.setLocalCodebase(null); + } + } + + /* + * Start up the ORB, export and publish servant in the + * name server. Expects: + * + * args[0] == Implementation class name + * args[1] == Name to publish in the name server + * args[2] == Name server host (may be null for local) + * args[3] == Name server port + * args[4] == "-iiop" or "-jrmp" + * args[5] == ORB debug flags + * + * Name server must be started prior to this call. + */ + public static void main(String[] args) { + + boolean error = false; + + if (args.length != 5) { + error = true; + } else { + boolean iiop = true; + if (args[4].equalsIgnoreCase("-iiop")) { + } else if (args[4].equalsIgnoreCase("-jrmp")) { + iiop = false; + // Dynamic RMI-IIOP prevents the use of JRMP, so + // make sure it is disabled. + System.setProperty( "com.sun.corba.ee.ORBUseDynamicStub", "false" ) ; + } else { + error = true; + } + + if (!error) { + + if (System.getSecurityManager() == null) { + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + } + + setDefaultCodeBase(iiop); + + String host = args[2]; + if (host.equals("-nullHost")) host = null; + + if (!startSingleServant( args[0], args[1], host, Integer.parseInt(args[3]), iiop, null )) { + System.exit(1); + } + } + } + + System.out.println("Usage: test.Util <-iiop | -jrmp>"); + } + + /* + * Start up the ORB, export and publish servant in the + * name server. Meant to be used as + * a convenient way to write a main which wants to run + * a single servant: + * + * public static void main(String[] args) { + * Util.startSingleServant("MyImpl","MyServer",1050,true); + * } + * + * Name server must be started prior to this call. + */ + public static boolean startSingleServant( + String servantClassName, String servantName, String nameServerHost, + int nameServerPort, boolean iiop, String orbDebugFlags ) { + boolean result = true; + trace( "Util.startSingleServant called." ) ; + + try { + + Class servantClass = Class.forName(servantClassName); + Remote servant = (Remote) servantClass.newInstance(); + result = startSingleServant( servant, servantName, nameServerHost, + nameServerPort, iiop, orbDebugFlags ); + + } catch (Throwable e) { + + e.printStackTrace(System.out); + System.out.println(); + System.out.flush(); + result = false; + + if (e instanceof ThreadDeath) { + throw new ThreadDeath(); + } + } finally { + trace( "Util.startSingleServant exiting." ) ; + } + + return result; + } + + public static Context singleServantContext = null; + + /* + * Start up the ORB, export and publish servant in the + * name server. Meant to be used as + * a convenient way to write a main which wants to run + * a single servant. + * + * Name server must be started prior to this call. + */ + public static boolean startSingleServant( Remote servant, String servantName, + String nameServerHost, int nameServerPort, boolean iiop, String orbDebugFlags ) { + + boolean result = true; + + trace( "Util.startSingleServant called" ) ; + + try { + ORB orb = null; + + if (iiop) { + orb = createORB( null, nameServerPort, orbDebugFlags ); + } + + if (!(servant instanceof PortableRemoteObject)) { + PortableRemoteObject.exportObject(servant); + } + + singleServantContext = getInitialContext(iiop,nameServerHost,nameServerPort,orb); + + singleServantContext.rebind(servantName, servant); + + Object stub = singleServantContext.lookup(servantName); + + if (stub != null) { + System.out.println(HANDSHAKE); + } else { + System.out.println("Self test FAILED."); + } + + System.out.flush(); + } catch (Throwable e) { + e.printStackTrace(System.out); + System.out.println(); + System.out.flush(); + result = false; + + trace( "Util.startSingleServant exiting" ) ; + if (e instanceof ThreadDeath) { + throw new ThreadDeath(); + } + } + + return result; + } + + // List of properties that must be inherited by any process + // the test framework starts by Runtime.exec. Used both in + // the IBM tests (based on test.Test) and the CORBA test framework + // tests (based on corba.framework.CORBATest). + public static String[] PROCESS_PROPERTIES = { + // RMI delegates + "javax.rmi.CORBA.UtilClass", + "javax.rmi.CORBA.StubClass", + "javax.rmi.CORBA.PortableRemoteObjectClass", + + // Standard ORB impl classes + "org.omg.CORBA.ORBClass", + "org.omg.CORBA.ORBSingletonClass", + + // Security related + "com.sun.corba.ee.ORBBase", + "java.security.policy", + "java.security.debug", + "java.security.manager", + + // Test setup + "corba.test.orb.classpath", + "corba.test.controller.name", + "http.server.port", + "name.server.port", + "java.rmi.server.codebase", + "java.compiler", + "java.rmi.server.codebase", + "http.server.root.directory", + "com.sun.corba.ee.JavaIDLHome", + + // For testing tools + "emma.coverage.out.file", + "emma.coverage.out.merge", + "emma.rt.control", + "junit.report.dir", + "net.sourceforge.cobertura.datafile", + + // Test configuration properties + ORBConstants.ORB_SERVER_ID_PROPERTY, + ORBConstants.GIOP_VERSION, + ORBConstants.GIOP_FRAGMENT_SIZE, + ORBConstants.GIOP_BUFFER_SIZE, + ORBConstants.GIOP_11_BUFFMGR, + ORBConstants.GIOP_12_BUFFMGR, + ORBConstants.USE_DYNAMIC_STUB_PROPERTY, + ORBConstants.ENABLE_JAVA_SERIALIZATION_PROPERTY, + ORBConstants.USE_CODEGEN_REFLECTIVE_COPYOBJECT, + ORBConstants.INIT_DEBUG_PROPERTY, + ORBConstants.DEBUG_DYNAMIC_STUB, + ORBConstants.INITIAL_PORT_PROPERTY, + ORBConstants.ORBD_PORT_PROPERTY + }; + + public static void inheritProperties( Vector command ) + { + for (int j = 0; j < PROCESS_PROPERTIES.length; j++) { + String key = PROCESS_PROPERTIES[j]; + String value = System.getProperty(key); + if (value != null) { + command.insertElementAt("-D" + key + "=" + value, 1 ); + } + } + } + + public static Process startProcess( Vector command, + String handShake ) throws IOException { + return startProcess( command, handShake, Test.forkDebugLevel ) ; + } + + public static Process startProcess( Vector command, + String handShake, int debugLevel ) throws IOException + { + inheritProperties( command ) ; + + if (debugLevel >= Test.ATTACH) { + command.insertElementAt( "-Xrunjdwp:transport=dt_socket,server=y,suspend=y", 1 ) ; + command.insertElementAt( "-Xnoagent", 1 ) ; + command.insertElementAt( "-Xdebug", 1 ) ; + } + + String[] arg = new String[command.size()]; + command.copyInto(arg); + + if (debugLevel >= Test.DISPLAY) { + StringBuffer buff = new StringBuffer() ; + buff.append( "startProcess: about to exec:" ) ; + for (int ctr=0; ctr= Test.DISPLAY) + displayCommand( command ) ; + + theProcess = Runtime.getRuntime().exec(command); + + ProcessMonitor monitor ; + + if (debugLevel >= Test.DISPLAY) + monitor = new ProcessMonitor( theProcess, + System.out, System.err, handShake); + else + monitor = new ProcessMonitor(theProcess, + StreamReader.NULL_OUTPUT_STREAM, StreamReader.NULL_OUTPUT_STREAM, handShake); + + monitor.start(); + + try { + monitor.waitForHandshake(120000); + } catch (Exception e) { + theProcess.destroy(); + theProcess = null; + try { + monitor.finishWriting(); + } catch (InterruptedException iex) { + System.err.println( iex ); + iex.printStackTrace( ); + } + + Error err = new Error(e.getMessage()); + err.initCause( e ) ; + throw err ; + } + + return theProcess; + } + + /** + * Run the rmic compiler. + * @param generatorArg The generator argument (e.g. "-iiop" or "-idl"). + * May be null. + * @param additionalArgs Additional arguments. May be null. + * @param classes Classes to compile. If null or empty, this method + * does nothing. + * @param externalProcess If true, rmic will be run in an external process; + * if false, rmic will be run in the current process. + * @throws Exception if compile fails. + */ + public static void rmic ( String generatorArg, + String[] additionalArgs, + String[] classes, + boolean externalProcess) throws Exception { + rmic(generatorArg,additionalArgs,classes,externalProcess,System.out); + } + + /** + * Run the rmic compiler. + * @param generatorArg The generator argument (e.g. "-iiop" or "-idl"). + * May be null. + * @param additionalArgs Additional arguments. May be null. + * @param classes Classes to compile. If null or empty, this method + * does nothing. + * @param externalProcess If true, rmic will be run in an external process; + * if false, rmic will be run in the current process. + * @param out Where to write output. + * @throws Exception if compile fails. + */ + public static void rmic ( String generatorArg, + String[] additionalArgs, + String[] classes, + boolean externalProcess, + OutputStream out) throws Exception { + + if (externalProcess) { + rmicExternal(generatorArg,additionalArgs,classes,out); + } else { + rmicInternal(generatorArg,additionalArgs,classes,out); + } + } + + /** + * Runs the rmic compiler in the current process. + * @param generatorArg The generator argument (e.g. "-iiop" or "-idl"). + * May be null. + * @param additionalArgs Additional arguments. May be null. + * @param classes Classes to compile. If null or empty, this method + * does nothing. + * @param out Where to write output. + * @throws Exception if compile fails. + */ + private static void rmicInternal (String generatorArg, + String[] additionalArgs, + String[] classes, + OutputStream out) + throws Exception { + + try { + trace( "Util.rmicInternal called" ) ; + trace( "\tgeneratorArg = " + generatorArg ) ; + trace( "\tadditionalArgs = " + Test.display(additionalArgs)) ; + trace( "\tclasses = " + Test.display(classes)) ; + + if (classes != null && classes.length > 0) { + int commandCount = classes.length+2; + if (debug) + commandCount++; + if (generatorArg != null) + commandCount++; + if (additionalArgs != null) + commandCount+=additionalArgs.length; + String[] args = new String[commandCount]; + int index = 0; + if (generatorArg != null) + args[index++] = generatorArg; + if (additionalArgs != null) { + int count = additionalArgs.length; + System.arraycopy(additionalArgs,0,args,index,count); + index += count; + } + + args[index++] = "-classpath"; + args[index++] = System.getProperty("java.class.path"); + if (debug) + args[index++] = "-verbose" ; + + int count = classes.length; + System.arraycopy(classes,0,args,index,count); + + // Test.checkSunTools() ; + Main compiler = new Main(out, "rmic"); + if (!compiler.compile(args)) { + throw new Exception ("compile failed"); + } + } + + } catch (Throwable e) { + if (e instanceof ThreadDeath) { + throw (ThreadDeath) e; + } + Exception exc = new Exception(e.toString()); + exc.initCause( e ) ; + throw exc ; + } finally { + trace( "Util.rmicInternal exiting" ) ; + } + } + + /** + * Runs the rmic compiler in a separate process. + * @param generatorArg The generator argument (e.g. "-iiop" or "-idl"). + * May be null. + * @param additionalArgs Additional arguments. May be null. + * @throws Exception if compile fails. + */ + private static void rmicExternal (String generatorArg, + String[] additionalArgs, + String[] classes, + OutputStream out) + throws Exception { + + trace( "Util.rmicExternal called" ) ; + trace( "\tgeneratorArg = " + generatorArg ) ; + trace( "\tadditionalArgs = " + Test.display(additionalArgs)) ; + trace( "\tclasses = " + Test.display(classes)) ; + + if (classes != null && classes.length > 0) { + Vector temp = new Vector(10); + temp.addElement(System.getProperty("java.home") + "/bin/java"); // _REVISIT_ Should be rmic! + String classPath = System.getProperty( "java.class.path" ) ; + temp.addElement("-classpath"); + temp.addElement(classPath); + temp.addElement("sun.rmi.rmic.Main"); + temp.addElement("-classpath"); + temp.addElement(classPath); + if (debug) + temp.addElement( "-verbose" ) ; + if (generatorArg != null) { + temp.addElement(generatorArg); + } + + int commandCount = temp.size(); + int additionalCount = additionalArgs != null ? additionalArgs.length : 0; + int classCount = classes.length; + String command[] = new String[commandCount + additionalCount + classCount]; + temp.copyInto(command); + if (additionalCount > 0) { + System.arraycopy(additionalArgs,0,command,commandCount,additionalCount); + } + System.arraycopy(classes,0,command,commandCount + additionalCount,classCount); + + // Do the compile... + + try { + int result = execAndWaitFor(command,out,System.err); + if (result != 0) { + throw new Exception("compile failed: " + result); + } + } catch (Throwable e) { + if (e instanceof ThreadDeath) { + throw (ThreadDeath) e; + } + Exception exc = new Exception(e.toString()); + exc.initCause( e ) ; + throw exc ; + } finally { + trace( "Util.rmicExternal exiting" ) ; + } + } + } + + public static Process startServer ( String serverClass, + String serverName, + String nameServerHost, + int nameServerPort, + boolean iiop) throws IOException { + // Fill out the command... + + Vector temp = new Vector(15); + + temp.addElement(System.getProperty("java.home") + "/bin/java" ); + temp.addElement("-Dorg.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl"); + temp.addElement("-Dorg.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton"); + + // add the Util delegates property; this is required so that + // appropriate delegates are picked up when running with the + // serialization code that has 5 bug fixes to handle + // interoperability and the correct RepID generation + + temp.addElement("-Djavax.rmi.CORBA.UtilClass=com.sun.corba.ee.impl.javax.rmi.CORBA.Util"); + temp.addElement("-Djavax.rmi.CORBA.StubClass=com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl"); + temp.addElement("-Djavax.rmi.CORBA.PortableRemoteObjectClass=com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject"); + String codebase = System.getProperty("java.rmi.server.codebase"); + if (codebase != null) { + temp.addElement("-Djava.rmi.server.codebase=" + codebase); + } + + boolean is12VM = true; + if (is12VM) { + String policy = System.getProperty("java.security.policy"); + if (policy != null) { + temp.addElement("-Djava.security.policy=" + policy); + } + } + + temp.addElement("-classpath"); + temp.addElement(System.getProperty("java.class.path")); + temp.addElement("test.Util"); + temp.addElement(serverClass); + temp.addElement(serverName); + temp.addElement(nameServerHost != null ? nameServerHost : "-nullHost"); + temp.addElement(Integer.toString(nameServerPort)); + + if (iiop) { + temp.addElement("-iiop"); + } else { + temp.addElement("-jrmp"); + } + + // Start her up... + + return startProcess(temp,Util.HANDSHAKE,Test.forkDebugLevel); + } + + public static Process startServer (String serverClass) throws IOException { + + // Fill out the command... + Vector cmd = new Vector(); + + cmd.add(System.getProperty("java.home") + "/bin/java"); + + String policy = System.getProperty("java.security.policy"); + if (policy != null) + cmd.addElement("-Djava.security.policy=" + policy); + + cmd.add("-Dorg.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl"); + cmd.add("-Dorg.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton"); + cmd.add("-Djavax.rmi.CORBA.UtilClass=com.sun.corba.ee.impl.javax.rmi.CORBA.Util"); + cmd.add("-Djavax.rmi.CORBA.StubClass=com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl"); + cmd.add("-Djavax.rmi.CORBA.PortableRemoteObjectClass=com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject"); + + cmd.add("-classpath"); + cmd.add(System.getProperty("java.class.path")); + cmd.add(serverClass); + + // Start her up... + return startProcess(cmd,Util.HANDSHAKE,Test.forkDebugLevel); + } + + public static Process startServer (String serverClass, Vector properties) throws IOException { + + // Fill out the command... + + Vector cmd = new Vector() ; + cmd.add( System.getProperty("java.home") + "/bin/java" ); + + cmd.add( "-Dorg.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl" ); + cmd.add( "-Dorg.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton" ); + cmd.add( "-Djavax.rmi.CORBA.UtilClass=com.sun.corba.ee.impl.javax.rmi.CORBA.Util" ); + cmd.add( "-Djavax.rmi.CORBA.StubClass=com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl" ); + cmd.add( "-Djavax.rmi.CORBA.PortableRemoteObjectClass=com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject" ); + + // Add properties + int index; + for (index = 0; index < properties.size(); index++) + cmd.add( (String)properties.elementAt(index) ); + + // Add classpath and server class + cmd.add( "-classpath" ); + cmd.add( System.getProperty("java.class.path") ); + cmd.add( serverClass ); + + // Start her up... + + return startProcess(cmd,Util.HANDSHAKE,Test.forkDebugLevel); + } + + // This version of startServer allows added paths to be appended to the classpath + public static Process startServer (String serverClass, Vector properties, + String classpath) + throws IOException { + + // Fill out the command... + + Vector cmd = new Vector() ; + cmd.add( System.getProperty("java.home") + "/bin/java" ); + cmd.add( "-Dorg.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl" ); + cmd.add( "-Dorg.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton" ); + cmd.add( "-Djavax.rmi.CORBA.UtilClass=com.sun.corba.ee.impl.javax.rmi.CORBA.Util" ); + cmd.add( "-Djavax.rmi.CORBA.StubClass=com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl" ); + cmd.add( "-Djavax.rmi.CORBA.PortableRemoteObjectClass=com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject" ); + + // Add properties + int index; + for (index = 0; index < properties.size(); index++) + cmd.add( (String)properties.elementAt(index) ); + + // Add classpath and server class + cmd.add( "-classpath" ); + cmd.add( System.getProperty("java.class.path")+File.pathSeparator+classpath ); + cmd.add( serverClass ); + + // Start her up... + return startProcess(cmd,Util.HANDSHAKE,Test.forkDebugLevel); + } + + public static Process startNameServer(int port, boolean iiop) throws IOException { + return startNameServer(Integer.toString(port),iiop); + } + + public static Process startNameServer(String port, boolean iiop) throws IOException { + + try { + Thread.sleep( 3*1000 ) ; // sleep for 3 seconds + } catch (InterruptedException exc) { + // ignore this: very rare case + } + + String handshake = null; + Vector args = new Vector(); + + // Fill out the command... + + args.addElement(System.getProperty("java.home") + "/bin/java" ); + args.addElement("-Dorg.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl"); + args.addElement("-Dorg.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton"); + args.addElement("-Djavax.rmi.CORBA.UtilClass=com.sun.corba.ee.impl.javax.rmi.CORBA.Util"); + args.addElement("-Djavax.rmi.CORBA.StubClass=com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl"); + args.addElement("-Djavax.rmi.CORBA.PortableRemoteObjectClass=com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject"); + args.addElement("-classpath"); + args.addElement(System.getProperty("java.class.path")); + + boolean is12VM = true; + if (is12VM) { + String policy = System.getProperty("java.security.policy"); + args.addElement("-Djava.security.policy=" + policy); + } + + if (iiop) { + + args.addElement("com.sun.corba.ee.impl.naming.cosnaming.TransientNameServer"); + args.addElement("-ORBInitialPort"); + args.addElement(port); + handshake = "Initial Naming Context:"; + + } else { + + args.addElement("test.StartRMIRegistry"); + args.addElement(port); + handshake = HANDSHAKE; + } + + // Start her up... + Test.dprint( "name server being started with command " + args ) ; + Test.dprint( "Expecting handshake: " + handshake ) ; + + return startProcess(args,handshake,Test.forkDebugLevel); + } + + /** + * execAndWaitFor will create a new Process and wait for the + * process to complete before returning + * @param command command line arguments to pass to exec. + * @return int the result of Process.exitValue() or -1; + * @throws Error if an unexpected exception occurs an Error is + * thrown with the message string from the original exception. + */ + public static int execAndWaitFor(String[] command) { + return execAndWaitFor(command,System.out,System.err); + } + + /** + * execAndWaitFor will create a new Process and wait for the + * process to complete before returning + * @param command command line arguments to pass to exec. + * @param out Where to copy output. + * @param err Where to copy error output. + * @return int the result of Process.exitValue() or -1; + * @throws Error if an unexpected exception occurs an Error is + * thrown with the message string from the original exception. + */ + public static int execAndWaitFor(String[] command, + OutputStream out, + OutputStream err) { + + try { + if (Test.forkDebugLevel >= Test.DISPLAY) + displayCommand( command ) ; + + Process theProcess = Runtime.getRuntime().exec(command); + + ProcessMonitor monitor = new ProcessMonitor(theProcess,out,err); + monitor.start(); + int result = waitForCompletion(theProcess,2000); + monitor.finishWriting(); + return result; + + } catch (Throwable error) { + Error exc = new Error(error.getMessage()); + exc.initCause( error ) ; + throw exc ; + } + } + + + public static int waitForCompletion( Process theProcess ,int sleepTime) + throws java.lang.InterruptedException + { + int result = -1; + + try { + theProcess.waitFor(); + result = theProcess.exitValue(); + } + catch (java.lang.IllegalThreadStateException notDone) { + // We assume that waitFor() does not work and exitValue() + // failed because the Process is not done. Lets Sleep + // for a while then check for completion again. + Thread.sleep(sleepTime,0); + waitForCompletion(theProcess,sleepTime+1500); + } + + return result; + } +} + diff --git a/functional-tests/src/test/java/test/WebServer.java b/functional-tests/src/test/java/test/WebServer.java new file mode 100644 index 000000000..077adcc27 --- /dev/null +++ b/functional-tests/src/test/java/test/WebServer.java @@ -0,0 +1,540 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * This class is based on example code by David Brown. + */ + +package test; + +import java.io.*; +import java.net.*; +import java.util.*; + +public class WebServer extends Thread implements HttpConstants { + + PrintStream log = null; + Vector threads = new Vector(); + File root = null; + int timeout = 5000; + int workers = 5; + int port = 8080; + boolean run; + Properties aliases = null; + boolean started = false; + ServerSocket ss = null; + + public static void main(String[] a) throws Exception { + int port = 8080; + String rootPath = System.getProperty("user.dir"); + int threads = 5; + boolean error = false; + Properties aliases = new Properties(); + + for (int i = 0; i < a.length; i++) { + String arg = a[i]; + if (arg.equals("-port")) { + port = Integer.parseInt(a[i+1]); + i++; + } else if (arg.equals("-docroot")) { + rootPath = a[i+1]; + i++; + } else if (arg.equals("-threads")) { + threads = Integer.parseInt(a[i+1]); + i++; + } else if (arg.equals("-alias")) { + String alias = a[i+1]; + int index = alias.indexOf('='); + if (index >=0) { + String key = alias.substring(0,index); + String value = alias.substring(index+1); + aliases.put(key,value); + } else { + System.out.println(alias + " is an invalid alias. Use x=y form."); + error = true; + } + i++; + } else { + error = true; + } + } + + File root = new File(rootPath); + if (!root.exists()) { + System.out.println("docroot '" + rootPath + "' does not exist."); + error = true; + } + + if (!error) { + WebServer server = new WebServer(port,root,threads,aliases,null); + server.start(); + System.out.println("Ready."); + } else { + System.out.println("Usage: test.WebServer [-port n][-docroot docRootPath][-threads n][-alias x=y]"); + } + } + + public WebServer (int port, File root, int threads) throws Exception { + this(port,root,threads,null,null); + } + + public WebServer (int port, File root, int threads, + Properties aliases, PrintStream log) throws Exception { + this.root = root; + this.port = port; + this.workers = threads; + this.log = log; + run = true; + this.aliases = aliases; + if (this.log == null) { + this.log = new PrintStream(new FileOutputStream(new File(root,"WebServer.log"))); + } + if (aliases != null) { + if (aliases.size() > 0) { + this.log.println("aliases: " + aliases); + } else { + this.log.println("aliases: "); + } + } + } + + /* print to the log file */ + protected void log(String s) { + if (log != null) { + synchronized (log) { + log.println(s); + log.flush(); + } + } + } + + public boolean waitTillReady() { + if (!Thread.currentThread().isAlive()) { + return false; // Died. + } + synchronized(this) { + while (!started) { + try { + wait(); + } catch (InterruptedException e) {} + } + } + return true; + } + + public void quit() { + try { + ss.close(); + } catch (Exception e){} + + run = false; + } + + public void run () { + + try { + /* start worker threads */ + for (int i = 0; i < workers; ++i) { + Worker w = new Worker(this); + (new Thread(w, "worker #"+i)).start(); + threads.addElement(w); + } + + ss = new ServerSocket(port); + + synchronized(this) { + started = true; + notifyAll(); + } + + while (run) { + try { + Socket s = ss.accept(); + Worker w = null; + synchronized (threads) { + if (threads.isEmpty()) { + Worker ws = new Worker(this); + ws.setSocket(s); + (new Thread(ws, "additional worker")).start(); + } else { + w = (Worker) threads.elementAt(0); + threads.removeElementAt(0); + w.setSocket(s); + } + } + } catch (IOException e) {} + } + + + + } catch (Exception e) { + log.println("WebServer died. Caught " + e); + } + } +} + + +class Worker implements HttpConstants, Runnable { + final static int BUF_SIZE = 2048; + + static final byte[] EOL = {(byte)'\r', (byte)'\n' }; + + /* buffer to use for requests */ + byte[] buf; + /* Socket to client we're handling */ + private Socket s; + private WebServer server; + + Worker(WebServer server) { + this.server = server; + buf = new byte[BUF_SIZE]; + s = null; + } + + synchronized void setSocket(Socket s) { + this.s = s; + notify(); + } + + public synchronized void run() { + while(server.run) { + if (s == null) { + /* nothing to do */ + try { + wait(); + } catch (InterruptedException e) { + /* should not happen */ + continue; + } + } + try { + handleClient(); + } catch (Exception e) { + e.printStackTrace(); + } + /* go back in wait queue if there's fewer + * than numHandler connections. + */ + s = null; + Vector pool = server.threads; + synchronized (pool) { + if (pool.size() >= server.workers) { + /* too many threads, exit this one */ + return; + } else { + pool.addElement(this); + } + } + } + } + + void handleClient() throws IOException { + InputStream is = new BufferedInputStream(s.getInputStream()); + PrintStream ps = new PrintStream(s.getOutputStream()); + /* we will only block in read for this many milliseconds + * before we fail with java.io.InterruptedIOException, + * at which point we will abandon the connection. + */ + s.setSoTimeout(server.timeout); + s.setTcpNoDelay(true); + /* zero out the buffer from last time */ + for (int i = 0; i < BUF_SIZE; i++) { + buf[i] = 0; + } + try { + /* We only support HTTP GET/HEAD, and don't + * support any fancy HTTP options, + * so we're only interested really in + * the first line. + */ + int nread = 0, r = 0; + + outerloop: + while (nread < BUF_SIZE) { + r = is.read(buf, nread, BUF_SIZE - nread); + if (r == -1) { + /* EOF */ + return; + } + int i = nread; + nread += r; + for (; i < nread; i++) { + if (buf[i] == (byte)'\n' || buf[i] == (byte)'\r') { + /* read one line */ + break outerloop; + } + } + } + + /* are we doing a GET or just a HEAD */ + boolean doingGet; + /* beginning of file name */ + int index; + if (buf[0] == (byte)'G' && + buf[1] == (byte)'E' && + buf[2] == (byte)'T' && + buf[3] == (byte)' ') { + doingGet = true; + index = 4; + } else if (buf[0] == (byte)'H' && + buf[1] == (byte)'E' && + buf[2] == (byte)'A' && + buf[3] == (byte)'D' && + buf[4] == (byte)' ') { + doingGet = false; + index = 5; + } else { + /* we don't support this method */ + ps.print("HTTP/1.0 " + HTTP_BAD_METHOD + + " unsupported method type: "); + ps.write(buf, 0, 5); + ps.write(EOL); + ps.flush(); + s.close(); + return; + } + + int i = 0; + /* find the file name, from: + * GET /foo/bar.html HTTP/1.0 + * extract "/foo/bar.html" + */ + for (i = index; i < nread; i++) { + if (buf[i] == (byte)' ') { + break; + } + } + String fname = new String(buf, 0, index,i-index); + fname = checkAliases(fname).replace('/', File.separatorChar); + if (fname.startsWith(File.separator)) { + fname = fname.substring(1); + } + + File targ = new File(server.root, fname); + if (targ.isDirectory()) { + File ind = new File(targ, "index.html"); + if (ind.exists()) { + targ = ind; + } + } + + boolean OK = printHeaders(targ, ps); + if (doingGet) { + if (OK) { + server.log("GET "+targ+". OK"); + sendFile(targ, ps); + } else { + server.log("GET "+targ+". NOT FOUND"); + send404(targ, ps); + } + } else { + server.log("HEAD "+targ+" OK"); + } + } finally { + ps.flush(); + ps.close(); + s.close(); + } + } + + String checkAliases (String name) { + String result = name; + if (server.aliases != null) { + String temp = (String) server.aliases.get(name); + if (temp != null) { + result = temp; + } + } + server.log.println("checkAliases: " + name + " --> " + result); + return result; + } + + boolean printHeaders(File targ, PrintStream ps) throws IOException { + boolean ret = false; + int rCode = 0; + if (!targ.exists()) { + rCode = HTTP_NOT_FOUND; + ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found"); + ps.write(EOL); + ret = false; + } else { + rCode = HTTP_OK; + ps.print("HTTP/1.0 " + HTTP_OK+" OK"); + ps.write(EOL); + ret = true; + } + server.log("From " +s.getInetAddress().getHostAddress()+": GET " + + targ.getAbsolutePath()+"-->"+rCode); + ps.print("Server: Simple java"); + ps.write(EOL); + ps.print("Date: " + (new Date())); + ps.write(EOL); + if (ret) { + if (!targ.isDirectory()) { + ps.print("Content-length: "+targ.length()); + ps.write(EOL); + ps.print("Last Modified: " + (new + Date(targ.lastModified()))); + ps.write(EOL); + String name = targ.getName(); + int ind = name.lastIndexOf('.'); + String ct = null; + if (ind > 0) { + ct = (String) map.get(name.substring(ind)); + } + if (ct == null) { + ct = "unknown/unknown"; + } + ps.print("Content-type: " + ct); + ps.write(EOL); + } else { + ps.print("Content-type: text/html"); + ps.write(EOL); + } + ps.write(EOL); // Bryan + } + return ret; + } + +void send404(File targ, PrintStream ps) throws IOException { + ps.write(EOL); + ps.write(EOL); + ps.println("Not Found\n\n"+ + "The requested resource was not found.\n"); +} + +void sendFile(File targ, PrintStream ps) throws IOException { + InputStream is = null; + if (targ.isDirectory()) { + listDirectory(targ, ps); + return; + } else { + server.log.print("sendFile: " + targ.getAbsolutePath() + ", length = " + targ.length()); + is = new FileInputStream(targ.getAbsolutePath()); + } + int sent = 0; + try { + int n; + while ((n = is.read(buf)) > 0) { + ps.write(buf, 0, n); + sent += n; + } + server.log.println(", sent = " + sent); + } catch (Exception e) { + server.log.println(", CAUGHT = " + e); + } finally { + // ps.flush(); + is.close(); + } +} + +/* mapping of file extensions to content-types */ +static java.util.Hashtable map = new java.util.Hashtable(); + +static { + fillMap(); +} +static void setSuffix(String k, String v) { + map.put(k, v); +} + +static void fillMap() { + setSuffix("", "content/unknown"); + setSuffix(".uu", "application/octet-stream"); + setSuffix(".exe", "application/octet-stream"); + setSuffix(".ps", "application/postscript"); + setSuffix(".zip", "application/zip"); + setSuffix(".sh", "application/x-shar"); + setSuffix(".tar", "application/x-tar"); + setSuffix(".snd", "audio/basic"); + setSuffix(".au", "audio/basic"); + setSuffix(".wav", "audio/x-wav"); + setSuffix(".gif", "image/gif"); + setSuffix(".jpg", "image/jpeg"); + setSuffix(".jpeg", "image/jpeg"); + setSuffix(".htm", "text/html"); + setSuffix(".html", "text/html"); + setSuffix(".text", "text/plain"); + setSuffix(".c", "text/plain"); + setSuffix(".cc", "text/plain"); + setSuffix(".c++", "text/plain"); + setSuffix(".h", "text/plain"); + setSuffix(".pl", "text/plain"); + setSuffix(".txt", "text/plain"); + setSuffix(".java", "text/plain"); + setSuffix(".class", "application/java"); + setSuffix(".clz", "application/java"); +} + + void listDirectory(File dir, PrintStream ps) throws IOException { + ps.println("Directory listing

\n"); + ps.println("Parent Directory
\n"); + String[] list = dir.list(); + for (int i = 0; list != null && i < list.length; i++) { + File f = new File(dir, list[i]); + if (f.isDirectory()) { + ps.println(""+list[i]+"/
"); + } else { + ps.println(""+list[i]+"



" + (new Date()) + ""); + } + +} + +interface HttpConstants { + /** 2XX: generally "OK" */ + public static final int HTTP_OK = 200; + public static final int HTTP_CREATED = 201; + public static final int HTTP_ACCEPTED = 202; + public static final int HTTP_NOT_AUTHORITATIVE = 203; + public static final int HTTP_NO_CONTENT = 204; + public static final int HTTP_RESET = 205; + public static final int HTTP_PARTIAL = 206; + + /** 3XX: relocation/redirect */ + public static final int HTTP_MULT_CHOICE = 300; + public static final int HTTP_MOVED_PERM = 301; + public static final int HTTP_MOVED_TEMP = 302; + public static final int HTTP_SEE_OTHER = 303; + public static final int HTTP_NOT_MODIFIED = 304; + public static final int HTTP_USE_PROXY = 305; + + /** 4XX: client error */ + public static final int HTTP_BAD_REQUEST = 400; + public static final int HTTP_UNAUTHORIZED = 401; + public static final int HTTP_PAYMENT_REQUIRED = 402; + public static final int HTTP_FORBIDDEN = 403; + public static final int HTTP_NOT_FOUND = 404; + public static final int HTTP_BAD_METHOD = 405; + public static final int HTTP_NOT_ACCEPTABLE = 406; + public static final int HTTP_PROXY_AUTH = 407; + public static final int HTTP_CLIENT_TIMEOUT = 408; + public static final int HTTP_CONFLICT = 409; + public static final int HTTP_GONE = 410; + public static final int HTTP_LENGTH_REQUIRED = 411; + public static final int HTTP_PRECON_FAILED = 412; + public static final int HTTP_ENTITY_TOO_LARGE = 413; + public static final int HTTP_REQ_TOO_LONG = 414; + public static final int HTTP_UNSUPPORTED_TYPE = 415; + + /** 5XX: server error */ + public static final int HTTP_SERVER_ERROR = 500; + public static final int HTTP_INTERNAL_ERROR = 501; + public static final int HTTP_BAD_GATEWAY = 502; + public static final int HTTP_UNAVAILABLE = 503; + public static final int HTTP_GATEWAY_TIMEOUT = 504; + public static final int HTTP_VERSION = 505; +} + + + diff --git a/idl/ir.idl b/idl/ir.idl new file mode 100644 index 000000000..a9a8b2fe0 --- /dev/null +++ b/idl/ir.idl @@ -0,0 +1,778 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * This file contains OMG IDL from CORBA V2.0, July 1995. + * It also contains the TypeCode creation APIs in CORBA::ORB + **/ + +#pragma prefix "omg.org" +//#pragma javaPackage org.omg + +module CORBA { + typedef string Identifier; + typedef string ScopedName; + typedef string RepositoryId; + + enum DefinitionKind { + dk_none, dk_all, + dk_Attribute, dk_Constant, dk_Exception, dk_Interface, + dk_Module, dk_Operation, dk_Typedef, + dk_Alias, dk_Struct, dk_Union, dk_Enum, + dk_Primitive, dk_String, dk_Sequence, dk_Array, + dk_Repository, + dk_Wstring, dk_Fixed, + dk_Value, dk_ValueBox, dk_ValueMember, // orbos 98-01-18: Objects By Value + dk_Native + }; + + + interface IRObject + /** + An IRObject IDL interface represents the most generic interface + from which all other Interface Repository interfaces are derived, + even the Repository itself. + */ + { + // read interface + readonly attribute DefinitionKind def_kind; + + // write interface + void destroy (); + }; + + + + typedef string VersionSpec; + + interface Contained; + interface Repository; + interface Container; + + interface Contained : IRObject + /** + The Contained Interface is inherited by all Interface Repository + interfaces that are contained by other objects. + */ + { + // read/write interface + + attribute RepositoryId id; + attribute Identifier name; + attribute VersionSpec version; + + // read interface + + readonly attribute Container defined_in; + readonly attribute ScopedName absolute_name; + readonly attribute Repository containing_repository; + + struct Description { + DefinitionKind kind; + any value; + }; + + Description describe (); + + // write interface + + void move ( + in Container new_container, + in Identifier new_name, + in VersionSpec new_version + ); + }; + + + interface ModuleDef; + interface ConstantDef; + interface IDLType; + interface StructDef; + interface UnionDef; + interface EnumDef; + interface AliasDef; + interface InterfaceDef; + interface ExceptionDef; + interface ValueDef; // orbos 98-01-18: Objects By Value + interface ValueMemberDef; // orbos 98-01-18: Objects By Value + interface ValueBoxDef; // orbos 98-01-18: Objects By Value + interface NativeDef; + + + typedef sequence InterfaceDefSeq; + + + typedef sequence ContainedSeq; + + struct StructMember { + Identifier name; + TypeCode type; + IDLType type_def; + }; + typedef sequence StructMemberSeq; + + struct UnionMember { + Identifier name; + any label; + TypeCode type; + IDLType type_def; + }; + typedef sequence UnionMemberSeq; + + + typedef sequence EnumMemberSeq; + + // orbos 98-01-18: Objects By Value -- begin + typedef short Visibility; + const Visibility PRIVATE_MEMBER = 0; + const Visibility PUBLIC_MEMBER = 1; + + struct ValueMember { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + IDLType type_def; + Visibility access; + }; + typedef sequence ValueMemberSeq; + + struct Initializer { + StructMemberSeq members; + }; + typedef sequence InitializerSeq; + + typedef sequence ValueDefSeq; + + // orbos 98-01-18: Objects By Value -- end + + + interface Container : IRObject + /** + The Container interface is used to form a containment hierarchy + in the Interface Repository. A Container can contain any number + of objects derived from the Contained interface. + */ + { + // read interface + + Contained lookup ( in ScopedName search_name); + + ContainedSeq contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + ContainedSeq lookup_name ( + in Identifier search_name, + in long levels_to_search, + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + struct Description { + Contained contained_object; + DefinitionKind kind; + any value; + }; + + typedef sequence DescriptionSeq; + + DescriptionSeq describe_contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited, + in long max_returned_objs + ); + + // write interface + + ModuleDef create_module ( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + ConstantDef create_constant ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in any value + ); + + StructDef create_struct ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + UnionDef create_union ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType discriminator_type, + in UnionMemberSeq members + ); + + EnumDef create_enum ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in EnumMemberSeq members + ); + + AliasDef create_alias ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type + ); + + ExceptionDef create_exception ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + + InterfaceDef create_interface ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_abstract, + in InterfaceDefSeq base_interfaces + ); + + // orbos 98-01-18: Objects By Value + ValueDef create_value( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_custom, + in boolean is_abstract, + in octet flags, // must be 0 + in ValueDef base_value, + in boolean has_safe_base, + in ValueDefSeq abstract_base_values, + in InterfaceDefSeq supported_interfaces, + in InitializerSeq initializers + ); + + // orbos 98-01-18: Objects By Value + ValueBoxDef create_value_box( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type_def + ); + + NativeDef create_native( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + }; + + + + interface IDLType : IRObject + /** + The IDLType interface is an abstract interface inherited by all + IR objects that represent the OMG IDL types. It provides access + to the TypeCode describing the type, and is used in defining the + other interfaces wherever definitions of IDLType must be referenced. + */ + { + readonly attribute TypeCode type; + }; + + + + interface PrimitiveDef; + interface StringDef; + interface SequenceDef; + interface ArrayDef; + + enum PrimitiveKind { + pk_null, pk_void, pk_short, pk_long, pk_ushort, pk_ulong, + pk_float, pk_double, pk_boolean, pk_char, pk_octet, + pk_any, pk_TypeCode, pk_Principal, pk_string, pk_objref + }; + + interface Repository : Container + /** + Repository is an interface that provides global access to the + Interface Repository. Repository objects can contain constants, + typedefs, exceptions, interfaces, and modules. + */ + { + // read interface + + Contained lookup_id (in RepositoryId search_id); + + PrimitiveDef get_primitive (in PrimitiveKind kind); + + // write interface + + StringDef create_string (in unsigned long bound); + + SequenceDef create_sequence ( + in unsigned long bound, + in IDLType element_type + ); + + ArrayDef create_array ( + in unsigned long length, + in IDLType element_type + ); + }; + + + interface ModuleDef : Container, Contained + /** + A ModuleDef can contain constants, typedefs, exceptions, interfaces, + and other module objects. + */ + { + }; + + struct ModuleDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + }; + + + interface ConstantDef : Contained + /** + A ConstantDef object defines a named constant. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute any value; + }; + + struct ConstantDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + any value; + }; + + + interface TypedefDef : Contained, IDLType + /** + TypedefDef is an abstract interface used as a base interface for + all named non-object types(structures, unions, enumerations, + aliases). The TypedefDef interface is not inherited by the definition + objects for the primitive or anonymous types. + */ + { + }; + + struct TypeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + interface StructDef : TypedefDef, Container + /** + A StructDef represents an OMG IDL structure definition. + */ + { + attribute StructMemberSeq members; + }; + + + interface UnionDef : TypedefDef, Container + /** + A UnionDef represents an OMG IDL union definition. + */ + { + readonly attribute TypeCode discriminator_type; + attribute IDLType discriminator_type_def; + attribute UnionMemberSeq members; + }; + + + interface EnumDef : TypedefDef + /** + A EnumDef represents an OMG IDL enum definition. + */ + { + attribute EnumMemberSeq members; + }; + + + interface AliasDef : TypedefDef + /** + An AliasDef represents an OMG IDL typedef that aliases other + definition. + */ + { + attribute IDLType original_type_def; + }; + + + interface PrimitiveDef: IDLType + /** + A PrimitiveDef represents one of the IDL primitive types. As + primitive types are unnamed, this interface is not derived from + TypedefDef or Contained. + */ + { + readonly attribute PrimitiveKind kind; + }; + + + interface StringDef : IDLType + /** + A StringDef represents an OMG IDL string type. As string + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + }; + + + interface SequenceDef : IDLType + /** + A SequenceDef represents an OMG IDL sequence type. As sequence + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + interface ArrayDef : IDLType + /** + An ArrayDef represents an OMG IDL array type. As array + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long length; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + + interface ExceptionDef : Contained, Container + /** + An ExceptionDef represents an exception definition. + */ + { + readonly attribute TypeCode type; + attribute StructMemberSeq members; + }; + struct ExceptionDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + + enum AttributeMode {ATTR_NORMAL, ATTR_READONLY}; + + interface AttributeDef : Contained + /** + An AttributeDef represents the information that defines an + attribute of an interface. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute AttributeMode mode; + }; + + struct AttributeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + AttributeMode mode; + }; + + + + enum OperationMode {OP_NORMAL, OP_ONEWAY}; + + enum ParameterMode {PARAM_IN, PARAM_OUT, PARAM_INOUT}; + struct ParameterDescription { + Identifier name; + TypeCode type; + IDLType type_def; + ParameterMode mode; + }; + typedef sequence ParDescriptionSeq; + + typedef Identifier ContextIdentifier; + typedef sequence ContextIdSeq; + + typedef sequence ExceptionDefSeq; + typedef sequence ExcDescriptionSeq; + + interface OperationDef : Contained + /** + An OperationDef represents the information that defines an + operation of an interface. + */ + { + readonly attribute TypeCode result; + attribute IDLType result_def; + attribute ParDescriptionSeq params; + attribute OperationMode mode; + attribute ContextIdSeq contexts; + attribute ExceptionDefSeq exceptions; + }; + + struct OperationDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode result; + OperationMode mode; + ContextIdSeq contexts; + ParDescriptionSeq parameters; + ExcDescriptionSeq exceptions; + }; + + + + typedef sequence RepositoryIdSeq; + typedef sequence OpDescriptionSeq; + typedef sequence AttrDescriptionSeq; + + interface InterfaceDef : Container, Contained, IDLType + /** + An InterfaceDef object represents an interface definition. It can + contains constants, typedefs, exceptions, operations, and + attributes. + */ + { + // read/write interface + + attribute InterfaceDefSeq base_interfaces; + attribute boolean is_abstract; + + // read interface + + boolean is_a (in RepositoryId interface_id); + + struct FullInterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + boolean is_abstract; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + RepositoryIdSeq base_interfaces; + TypeCode type; + }; + + FullInterfaceDescription describe_interface(); + + // write interface + + AttributeDef create_attribute ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + + struct InterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq base_interfaces; + }; + + + // orbos 98-01-18: Objects By Value -- begin + + interface ValueMemberDef : Contained + + /** A ValueMemberDef object represents the public + and private data member definition of a Value type + */ + + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute Visibility access; + }; + + interface ValueDef : Container, Contained, IDLType + /** + A ValueDef object represents the definition of the + Value object used to pass the object state + between hosts + */ + + { + // read/write interface + attribute InterfaceDefSeq supported_interfaces; + attribute InitializerSeq initializers; + attribute ValueDef base_value; + attribute ValueDefSeq abstract_base_values; + attribute boolean is_abstract; + attribute boolean is_custom; + attribute octet flags; // always 0 + attribute boolean has_safe_base; + + // read interface + boolean is_a(in RepositoryId value_id); + + struct FullValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + ValueMemberSeq members; + InitializerSeq initializers; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + TypeCode type; + }; + + FullValueDescription describe_value(); + + // write interface + + ValueMemberDef create_value_member( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type_def, + in Visibility access + ); + + AttributeDef create_attribute( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + struct ValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + }; + + interface ValueBoxDef : IDLType + + /** ValueBoxDef is an interface that reresents a value type with + a single data member inside its state section and no + inheritance or methods. For example, when transmitting a + string or sequence as an actual parameter on an interface + operation or as a data member of a value type that is an + actual parameter, it may be important to preserve any sharing + of the string or sequence within the object graph being + transmitted. Because current IDL data types do not preserve + referential integrity in this way, this requirement is + conveniently handled by using a value type. Value types also + support the transmission of nulls (as a distinguished value), + whereas IDL data types such as string and sequence (which are + mapped to empty strings and sequences) do not. The Java to IDL + mapping requires both preservation of referential integrity + and transmission of nulls. Because it would be cumbersome to + require the full IDL syntax for a value type for this specific + usage, this shorthand notation is introduced to cover this use + of value types for simple containment of a single data member. + */ + + { + attribute IDLType original_type_def; + }; + + // orbos 98-01-18: Objects By Value -- end + + enum TCKind { + tk_null, tk_void, + tk_short, tk_long, tk_ushort, tk_ulong, + tk_float, tk_double, tk_boolean, tk_char, + tk_octet, tk_any, tk_TypeCode, tk_Principal, tk_objref, + tk_struct, tk_union, tk_enum, tk_string, + tk_sequence, tk_array, tk_alias, tk_except, + tk_longlong, tk_ulonglong, tk_longdouble, + tk_wchar, tk_wstring, tk_fixed, + tk_value, tk_value_box, + tk_native, + tk_abstract_interface + }; + + interface NativeDef : TypedefDef { + }; +}; diff --git a/idl/orb.idl b/idl/orb.idl new file mode 100644 index 000000000..5fde42430 --- /dev/null +++ b/idl/orb.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// IDL not generated by rmic, do not edit +// These are all in IDL module CORBA +// The Java classes are in the package org.omg.CORBA +// See ValueType Semantics:Standard Value Box Definitions (5.3) in CORBA 2.3 spec + +#ifndef __org_omg_CORBA__ +#define __org_omg_CORBA__ + +#pragma prefix "omg.org" + +module CORBA{ + + valuetype StringValue string; + valuetype WStringValue wstring; + +}; + +#include "ir.idl" + +#pragma prefix "" + +#endif diff --git a/idl/rt.idl b/idl/rt.idl new file mode 100644 index 000000000..c073d0807 --- /dev/null +++ b/idl/rt.idl @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "ir.idl" + +#pragma prefix "omg.org" +module SendingContext { + interface RunTime {}; + + interface CodeBase: RunTime { + typedef string URL; + typedef sequence URLSeq; + typedef sequence ValueDescSeq; + + // Operation to obtain the IR from the sending context + CORBA::Repository get_ir(); + + // Operations to obtain a URL to the implementation code + URL implementation(in CORBA::RepositoryId x); + URLSeq implementations(in CORBA::RepositoryIdSeq x); + + // Operations to obtain complete meta information about a Value + // This is just a performance optimization the IR can provide + // the same information + CORBA::ValueDef::FullValueDescription meta(in CORBA::RepositoryId x); + ValueDescSeq metas(in CORBA::RepositoryIdSeq x); + + // To obtain a type graph for a value type + // same comment as before the IR can provide similar + // information + CORBA::RepositoryIdSeq bases(in CORBA::RepositoryId x); + }; +}; +#include "ir.idl" + +#pragma prefix "omg.org" +module SendingContext { + interface RunTime {}; + + interface CodeBase: RunTime { + typedef string URL; + typedef sequence URLSeq; + typedef sequence ValueDescSeq; + + // Operation to obtain the IR from the sending context + CORBA::Repository get_ir(); + + // Operations to obtain a URL to the implementation code + URL implementation(in CORBA::RepositoryId x); + URLSeq implementations(in CORBA::RepositoryIdSeq x); + + // Operations to obtain complete meta information about a Value + // This is just a performance optimization the IR can provide + // the same information + CORBA::ValueDef::FullValueDescription meta(in CORBA::RepositoryId x); + ValueDescSeq metas(in CORBA::RepositoryIdSeq x); + + // To obtain a type graph for a value type + // same comment as before the IR can provide similar + // information + CORBA::RepositoryIdSeq bases(in CORBA::RepositoryId x); + }; +}; diff --git a/idlj/README b/idlj/README new file mode 100644 index 000000000..0a2fc87e0 --- /dev/null +++ b/idlj/README @@ -0,0 +1,3 @@ +With the ORB removed from the JDK, the include files orb.idl and ir.idl, which were located at $JAVA_HOME/lib are +no longer available. They are now being packaged in the idlj.jar file, under the top-level "includes" directory. +Users will need to extract them to a local directory in order to use them. \ No newline at end of file diff --git a/idlj/pom.xml b/idlj/pom.xml new file mode 100644 index 000000000..4d7107766 --- /dev/null +++ b/idlj/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + idlj + IDL compiler + + + + org.hamcrest + hamcrest-all + + + junit + junit + + + com.meterware.simplestub + simplestub + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + + com.sun.tools.corba.ee.idl.toJavaPortable.Compile + + + ${project.version} + + + + + + + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Arguments.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Arguments.java new file mode 100644 index 000000000..c2277bc6d --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Arguments.java @@ -0,0 +1,298 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -F46082.51 Remove -stateful option. "Stateful interfaces" obsolete. +// -D58319 Add -version option. Note that this may occur as the last +// argument on the command-line. +// -F60858.1 Add -corba [level] option. Accept IDL upto this level, and +// behave in a "proprietary manner" otherwise. +// -D62023 Add -noWarn option to supress warnings. + +import com.sun.tools.corba.ee.idl.som.cff.FileLocator; + +import java.io.DataInputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Hashtable; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + * This class is responsible for parsing the command line arguments to the + * compiler. To add new arguments to the compiler, this class must be extended + * and the parseOtherArgs method overridden. + **/ +public class Arguments +{ + /** + * Method parseOtherArgs() is called when the framework detects arguments + * which are unknown to it. The default implementation of this method simply + * throws an InvalidArgument exception. Any overriding implementation + * must check the arguments passed to it for validity and process the + * arguments appropriately. If it detects an invalid argument, it should + * throw an InvalidArgument exception. Arguments MUST be of the form + * `/<arg> [<qualifiers>]' or `-<arg> [<qualifiers>]' where <qualifiers> + * is optional (for example, -iC:\includes, `C:\includes' is the qualifier + * for the argument `i'). + * @param args The arguments which are unknown by the framework. + * @param properties Environment-style properties collected from the + * file idl.config. + * @exception InvalidArgument if the argument is unknown. + **/ + protected void parseOtherArgs (String[] args, Properties properties) throws InvalidArgument + { + if (args.length > 0) + throw new InvalidArgument(args[0]); + } // parseOtherArgs + + + protected void setDebugFlags( String args ) + { + StringTokenizer st = new StringTokenizer( args, "," ) ; + while (st.hasMoreTokens()) { + String token = st.nextToken() ; + + // If there is a public boolean data member in this class + // named token + "DebugFlag", set it to true. + try { + Field fld = this.getClass().getField( token + "DebugFlag" ) ; + int mod = fld.getModifiers() ; + if (Modifier.isPublic( mod ) && !Modifier.isStatic( mod )) + if (fld.getType() == boolean.class) + fld.setBoolean( this, true ) ; + } catch (Exception exc) { + // ignore it + } + } + } + + /** + * Collect the command-line parameters. + **/ + void parseArgs (String[] args) throws InvalidArgument { + Vector unknownArgs = new Vector (); + int i = 0; + + try { + // Process command line parameters + for (i = 0; i < args.length - 1; ++i) { + if (args[i].charAt (0) != '-' && args[i].charAt (0) != '/') + throw new InvalidArgument(args[i]); + String lcArg = args[i].substring (1).toLowerCase (); + + // Include path + if (lcArg.equals ("i")) { + includePaths.addElement (args[++i]); + } else if (lcArg.startsWith ("i")) { + includePaths.addElement (args[i].substring (2)); + } else if (lcArg.equals ("v") || lcArg.equals ("verbose")) { + // Verbose mode + verbose = true; + } else if (lcArg.equals ("d")) { + // Define symbol + definedSymbols.put (args[++i], ""); + } else if (lcArg.equals( "debug" )) { + // Turn on debug flags + setDebugFlags( args[++i] ) ; + } else if (lcArg.startsWith ("d")) { + definedSymbols.put (args[i].substring (2), ""); + } else if (lcArg.equals ("emitall")) { + // Emit bindings for included sources + emitAll = true; + } else if (lcArg.equals ("keep")) { + // Keep old files + keepOldFiles = true; + } else if (lcArg.equals ("nowarn")) { + // Suppress warnings + noWarn = true; + } else if (lcArg.equals ("trace")) { + // Allow tracing. + Runtime.getRuntime ().traceMethodCalls (true); + } + // Remove -stateful feature. + //else if (lcArg.equals ("stateful")) + //{ + // Emit stateful bindings. + // parseStateful = true; + //} + // CPPModule + else if ( lcArg.equals ("cppmodule")) { + cppModule = true; + } else if (lcArg.equals ("version")) { + // Version + versionRequest = true; + } else if (lcArg.equals ("corba")) { + // CORBA level + if (i + 1 >= args.length) + throw new InvalidArgument(args[i]); + String level = args[++i]; + if (level.charAt (0) == '-') + throw new InvalidArgument(args[i - 1]); + try { + corbaLevel = new Float (level).floatValue (); + } catch (NumberFormatException e) { + throw new InvalidArgument(args[i]); + } + } else { + unknownArgs.addElement (args[i]); + ++i; + while (i < (args.length - 1) && + args[i].charAt (0) != '-' && + args[i].charAt (0) != '/') { + unknownArgs.addElement (args[i++]); + } + --i; + } + } + } catch (ArrayIndexOutOfBoundsException e) { + // If there is any array indexing problem, it is probably + // because the qualifier on the last argument is missing. + // Report that this last argument is invalid. + throw new InvalidArgument(args[args.length - 1]); + } + + // + // The last argument is the file argument or "-version", which may + // be specified without a file argument. + if (i == args.length - 1) { + if (args[i].toLowerCase ().equals ("-version")) + versionRequest = true; + else + file = args[i]; + } else + throw new InvalidArgument(); + + // Get and process the idl.config file. + Properties props = new Properties (); + try { + DataInputStream stream = FileLocator.locateFileInClassPath ("idl.config"); + props.load (stream); + addIncludePaths (props); + } catch (IOException e) { + } + + // Call parseOtherArgs. By default, if there are unknown args, + // InvalidArgument is called. A call to parseOtherArgs is useful + // only when this framework has been extended. + String[] otherArgs; + if (unknownArgs.size () > 0) { + otherArgs = new String[unknownArgs.size ()]; + unknownArgs.copyInto (otherArgs); + } else + otherArgs = new String[0]; + + parseOtherArgs (otherArgs, props); + } // parseArgs + + /** + * + **/ + private void addIncludePaths (Properties props) + { + String paths = props.getProperty ("includes"); + if (paths != null) + { + String separator = System.getProperty ("path.separator"); + int end = -separator.length (); // so the first pass paths == original paths + do + { + paths = paths.substring (end + separator.length ()); + end = paths.indexOf (separator); + if (end < 0) + end = paths.length (); + includePaths.addElement (paths.substring (0, end)); + } + while (end != paths.length ()); + } + } // addIncludePaths + + /** + * The name of the IDL file. + **/ + public String file = null; + + /** + * True if the user wishes to see processing remarks. + **/ + public boolean verbose = false; + + /** + * If this is true, then existing files should not be overwritten + * by the compiler. + **/ + public boolean keepOldFiles = false; + + /** + * If this is true, then the types in all included files are also emitted. + **/ + public boolean emitAll = false; + + // Remove -stateful feature. + ///** + // * If this is true, then stateful interfaces (for the Objects-by-Value + // * proposal) are allowed. This is not yet a standard, so it must + // * explicitly be called for by setting the -stateful argument to the + // * compiler. If -stateful does not appear on the command line, then + // * the IDL will be parsed according to the standards. + // **/ + //public boolean parseStateful = false; + /** + * A list of strings, each of which is a path from which included files + * are found. + **/ + public Vector includePaths = new Vector (); + + /** + * A table of defined symbols. The key is the symbol name; the value + * (if any) is the replacement value for the symbol. + **/ + public Hashtable definedSymbols = new Hashtable (); + + /** + * <f46082.46.01> True if new module entries are created for each + * re-opened module. + **/ + public boolean cppModule = false; + + /** + * -version option. + **/ + public boolean versionRequest = false; // + + // Specify the maximal level of the CORBA spec. the parser + // will support. + // + // NOTE: For BOSS 3.0, specify at 2.2. Raise to greater value in future + // releases. + /** + * -corba [level] option, where [level] is a floating-point number indicating + * the maximal level of CORBA IDL the parser framework can accept. + **/ + public float corbaLevel = 2.2f; + // + /** + * -noWarn option. Suppress warnings when true. + **/ + public boolean noWarn = false; // Issue warnings by default. + + // Currently defined debug flags. Any additions must be called xxxDebugFlag. + // All debug flags must be public boolean types. + // These are set by passing the flag -ORBDebug x,y,z in the ORB init args. + // Note that x,y,z must not contain spaces. + public boolean scannerDebugFlag = false ; + public boolean tokenDebugFlag = false ; + +} // class Arguments diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/AttributeEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/AttributeEntry.java new file mode 100644 index 000000000..747f0217b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/AttributeEntry.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for attributes. An attribute is simply + * two methods with no exceptions or contexts: a get method and, if not + * readOnly, a set method. + **/ +public class AttributeEntry extends MethodEntry +{ + protected AttributeEntry () + { + super (); + } // ctor + + protected AttributeEntry (AttributeEntry that) + { + super (that); + _readOnly = that._readOnly; + } // ctor + + protected AttributeEntry (com.sun.tools.corba.ee.idl.InterfaceEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + } // ctor + + public Object clone () + { + return new AttributeEntry (this); + } // clone + + /** Invoke the attribute generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + attributeGen.generate (symbolTable, this, stream); + } // generate + + /** Access the attribute generator. + @return an object which implements the AttributeGen interface. + @see com.sun.tools.corba.ee.idl.AttributeGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return attributeGen; + } // generator + + /** if true, only a get method will be generated. */ + public boolean readOnly () + { + return _readOnly; + } // readOnly + + /** if true, only a get method will be generated. */ + public void readOnly (boolean readOnly) + { + _readOnly = readOnly; + } // readOnly + + static com.sun.tools.corba.ee.idl.AttributeGen attributeGen; + + public boolean _readOnly = false; +} // class AttributeEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/AttributeGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/AttributeGen.java new file mode 100644 index 000000000..d1c45046e --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/AttributeGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface AttributeGen extends Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.AttributeEntry entry, PrintWriter stream); +} // interface AttributeGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Comment.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Comment.java new file mode 100644 index 000000000..8b8cf371b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Comment.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.io.IOException; +import java.util.StringTokenizer; + +public class Comment +{ + // Styles + static final int UNKNOWN = -1; + static final int JAVA_DOC = 0; + static final int C_BLOCK = 1; + static final int CPP_LINE = 2; + + // System-dependent line separator + private static String _eol = System.getProperty ("line.separator"); + + private String _text = new String (""); + private int _style = UNKNOWN; + + Comment () {_text = new String (""); _style = UNKNOWN;} // ctor + + Comment (String text) {_text = text; _style = style (_text);} // ctor + + /** Sets comment text */ + public void text (String string) {_text = string; _style = style (_text);} + + /** Returns comment text */ + public String text () {return _text;} + + /** Returns the comment style of a string. */ + private int style (String text) + { + if (text == null) + return UNKNOWN; + else if (text.startsWith ("/**") && text.endsWith ("*/")) + return JAVA_DOC; + else if (text.startsWith ("/*") && text.endsWith ("*/")) + return C_BLOCK; + else if (text.startsWith ("//")) + return CPP_LINE; + else + return UNKNOWN; + } // style + + /** Writes comment text to standard output (debug). */ + public void write () {System.out.println (_text);} + + /** Writes comment text to the specified print stream in the appropriate format. */ + public void generate (String indent, PrintWriter printStream) + { + if (_text == null || printStream == null) + return; + if (indent == null) + indent = new String (""); + switch (_style) + { + case JAVA_DOC: + //printJavaDoc (indent, printStream); + print (indent, printStream); + break; + case C_BLOCK: + //printCBlock (indent, printStream); + print (indent, printStream); + break; + case CPP_LINE: + //printCppLine (indent, printStream); + print (indent, printStream); + break; + default: + break; + } + } // generate + + /** Writes comment to the specified print stream without altering its format. + This routine does not alter vertical or horizontal spacing of comment text, + thus, it only works well for comments with a non-indented first line. */ + private void print (String indent, PrintWriter stream) + { + String text = _text.trim () + _eol; + String line = null; + + int iLineStart = 0; + int iLineEnd = text.indexOf (_eol); + int iTextEnd = text.length () - 1; + + stream.println (); + while (iLineStart < iTextEnd) + { + line = text.substring (iLineStart, iLineEnd); + stream.println (indent + line); + iLineStart = iLineEnd + _eol.length (); + iLineEnd = iLineStart + text.substring (iLineStart).indexOf (_eol); + } + } // print + + /* + * The following routines print formatted comments of differing styles. + * Each routine will alter the horizontal spacing of the comment text, + * but not the vertical spacing. + */ + + /** Writes comment in JavaDoc-style to the specified print stream. */ + private void printJavaDoc (String indent, PrintWriter stream) + { + // Strip surrounding "/**", "*/", and whitespace; append sentinel + String text = _text.substring (3, (_text.length () - 2)).trim () + _eol; + String line = null; + + int iLineStart = 0; + int iLineEnd = text.indexOf (_eol); + int iTextEnd = text.length () - 1; // index of last text character + + stream.println (_eol + indent + "/**"); + while (iLineStart < iTextEnd) + { + line = text.substring (iLineStart, iLineEnd).trim (); + if (line.startsWith ("*")) + // Strip existing "*" prefix + stream.println (indent + " * " + line.substring (1, line.length ()).trim ()); + else + stream.println (indent + " * " + line); + iLineStart = iLineEnd + _eol.length (); + iLineEnd = iLineStart + text.substring (iLineStart).indexOf (_eol); + } + stream.println (indent + " */"); + } // printJavaDoc + + /** Writes comment in c-block-style to the specified print stream. */ + private void printCBlock (String indent, PrintWriter stream) + { + // Strip surrounding "/*", "*/", and whitespace; append sentinel + String text = _text.substring (2, (_text.length () - 2)).trim () + _eol; + String line = null; + + int iLineStart = 0; + int iLineEnd = text.indexOf (_eol); + int iTextEnd = text.length () - 1; // index of last text character + + stream.println (indent + "/*"); + while (iLineStart < iTextEnd) + { + line = text.substring (iLineStart, iLineEnd).trim (); + if (line.startsWith ("*")) + // Strip existing "*[ws]" prefix + stream.println (indent + " * " + line.substring (1, line.length ()).trim ()); + else + stream.println (indent + " * " + line); + iLineStart = iLineEnd + _eol.length (); + iLineEnd = iLineStart + text.substring (iLineStart).indexOf (_eol); + } + stream.println (indent + " */"); + } // printCBlock + + /** Writes a line comment to the specified print stream. */ + private void printCppLine (String indent, PrintWriter stream) + { + stream.println (indent + "//"); + // Strip "//[ws]" prefix + stream.println (indent + "// " + _text.substring (2).trim ()); + stream.println (indent + "//"); + } // printCppLine +} // class Comment + + +/*================================================================================== + DATE ACTION + ---------------------------------------------------------------------------------- + 11aug1997 Initial version completed. + 18aug1997 Modified generate to write comment unformatted. + ==================================================================================*/ + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Compile.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Compile.java new file mode 100644 index 000000000..3c6bd963c --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Compile.java @@ -0,0 +1,490 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -D56351 Update computation of RepositoryIDs to CORBA 2.3 (see spec.). +// -D58319 Display version info. for -version option. + +import com.sun.tools.corba.ee.idl.constExpr.DefaultExprFactory; +import com.sun.tools.corba.ee.idl.constExpr.ExprFactory; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Stack; +import java.util.Vector; + +/** + * Compiler usage: + *

+ * + * java com.sun.tools.corba.ee.idl.toJava.compile [options] <idl file> + *

+ * + * where <idl file> is the name of a file containing IDL definitions, + * and [options] is any combination of the options listed below. The options + * and the idl file name can appear in any order. + *

+ * + * Options: + *
+ *
-i <include path> + *
By default, the current directory is scanned for included files. + * This option adds another directory. See also Note 1 below. + * + *
-d <symbol> + *
This is equivalent to the following line in an IDL file: #define <symbol> + * + *
-emitAll + *
Emit all types, including those found in #included files. + * + *
-v + *
Verbose mode. + *
+ * + * Note 1: If you have an include path or paths that you will always be using, + * it can get tedious putting these on the command with the -i option all the + * time. Instead, these can be placed into a config file called idl.config. + * This file must be in the CLASSPATH. The format of the includes line is: + * + *
+ * includes=<path1><path2>;...;<pathN>
+ * 
+ * + * Note that the path separator character, here shown as a semicolon, is + * machine dependent. For instance, on Windows 95 this character is a + * semicolon, on UNIX it is a colon. + * + *

+ * Note 2: If you are directly invoking the main method on this class (not + * a subclass), then it will only check that the IDL file is syntactically + * correct. It does not generate any files. Only extensions to this + * framework generate files, therefore an extension must be invoked if you + * want files to be generated. + *

+ * + * To Extend the compiler: + *

+ * + * You only need to extend the compiler if you want it to generate something + * other than what it currently generates. + *

+ * + * Step 1 - Implement the generator interfaces: + *

+ * + * Each generator interface defines one method: generate (Hashtable, XXXEntry, PrintWriter); + *
+ * - The Hashtable is the symbol table; each element is a SymtabEntry (or a + * subclass of SymtabEntry) and is keyed by its fully qualified name; + *
+ * - XXXEntry is the appropriate entry for the type to be generated. For + * example: AttributeGen defines generate (Hashtable, AttributeEntry, PrintWriter); + * ConstGen defines generate (Hashtable, ConstEntry, PrintWriter); etc. + *
+ * - The PrintWriter is a stream to the file being generated. For the + * generators called by the compiler framework, this will be null. The + * generator is responsible for creating and opening files. But for + * generators that are called by other generators - for instance, + * MethodGen.generate will most likely be called by InterfaceGen.generate - + * this parameter is provided so that the proper file can be written to. + *

+ * + * Step 2 - Implement the GenFactory interface: + *

+ * + * All of the generators implemented in Step 1 must be created somehow. There + * is an interface for a factory, GenFactory, which must be implemented. The + * name of this factory must be set in the extension to the Compile class (see + * Step 3, below). + *

+ * + * Step 3 - Extend Factories: + *

+ * + * Extend Factories and override the method genFactory. This + * method must return an instance of the factory which you implemented in + * step 2. Your extension of this class may also do more, this is only the + * minimum. See Factories for more information. + *

+ * + * Step 4 - Extend Compile: + *

+ * + * Your extension of Compile should contain a minimum of + * two methods: + *

+ *
protected Factories () + *
This method overrides Compile.factories and returns your + * extension from Step 3. + * + *
public static void main (String[] args) + *
This main method must instantiate this class and call its start method. + *
+ * + * Given that the extension of Factories is MyFactories, the extension of + * Compile could be: + * + *
+ * public class MyCompile extends Compile
+ * {
+ *   protected Factories factories ()
+ *   {
+ *     return new MyFactories ();
+ *   }
+ *   public static void main (String[] args)
+ *   {
+ *     MyCompile compile = new MyCompile ();
+ *     compile.start (args);
+ *   }
+ * }
+ * 
+ * + * If you would like a bit more control over the processing of the framework, + * you can replace compile.start with what it calls. But then you also have + * to handle the exceptions which start handles for you: + *
+ * public class MyCompile extends Compile
+ * {
+ *   ...
+ *
+ *   public static void main (String[] args)
+ *   {
+ *     MyCompile compile = new MyCompile ();
+ *     try
+ *     {
+ *       compile.init (args);
+ *       java.util.Enumeration emitList = compile.parse ();
+ *       compile.generate ();
+ *     }
+ *     catch (InvalidArgument e)
+ *     {
+ *       System.err.println (e);
+ *     }
+ *     catch (java.io.IOException e)
+ *     {
+ *       System.err.println (e);
+ *     }
+ *   }
+ * }
+ * 
+ * + * Note that compile.parse returns an enumeration. This enumerates the + * SymtabEntry's which should be generated. If the parse method detects + * errors, it returns null. Note that you do not have to check that + * `emitList' is valid before calling generate (that's done internally), but + * if you do any processing between parse and generate, emitList should be + * checked before executing that code. + *

+ **/ +@SuppressWarnings("unchecked") +public class Compile +{ + public Compile () + { + NoPragma noPragma = new NoPragma(); + noPragma.init (preprocessor); + preprocessor.registerPragma (noPragma); + + // Reset static variables to allow parsing multiple sources. + // DO NOT reset SymtabEntry.maxKey because it crashes IDLC. + com.sun.tools.corba.ee.idl.ParseException.detected = false; + com.sun.tools.corba.ee.idl.SymtabEntry.includeStack = (Stack) new java.util.Stack (); + com.sun.tools.corba.ee.idl.SymtabEntry.setEmit = true; + //SymtabEntry.maxKey = -1; + com.sun.tools.corba.ee.idl.Parser.repIDStack = new java.util.Stack (); // + } // ctor + + public static void main (String[] args) + { + (new Compile ()).start (args); + } // main + + protected com.sun.tools.corba.ee.idl.Factories factories () + { + return new com.sun.tools.corba.ee.idl.Factories(); + } // genFactoryName + + /** + * Initialize the framework. + **/ + protected void init (String[] args) throws com.sun.tools.corba.ee.idl.InvalidArgument + { + initFactories (); + arguments.parseArgs (args); + initGenerators (); + parser = new com.sun.tools.corba.ee.idl.Parser(preprocessor, arguments, overrideNames, symbolTable, symtabFactory, exprFactory, keywords); + preprocessor.init (parser); + parser.includes = includes; + parser.includeEntries = includeEntries; + } // init + + /** + * Parse the IDL file and return an enumeration of the symbols to be + * generated. All elements of the Enumeration will be extensions of + * SymtabEntry. If any errors were encountered during parsing, null + * will be returned. + **/ + protected Enumeration parse () throws IOException + { + if (arguments.verbose) + System.out.println (com.sun.tools.corba.ee.idl.Util.getMessage("Compile.parsing", arguments.file)); + parser.parse (arguments.file); + if ( !com.sun.tools.corba.ee.idl.ParseException.detected ) + { + parser.forwardEntryCheck(); + + // <46082.03> Revert to "IDL:"-style (i.e., regular) repository ID. + //parser.updateRepositoryIds(); + } + if (arguments.verbose) + System.out.println (com.sun.tools.corba.ee.idl.Util.getMessage("Compile.parseDone", arguments.file)); + if (com.sun.tools.corba.ee.idl.ParseException.detected) + { + symbolTable = null; + emitList = null; + } + else + { + symbolTable = Parser.symbolTable; + emitList = parser.emitList.elements (); + } + return emitList; + } // parse + + /** + * Invoke the generators. + **/ + @SuppressWarnings("StatementWithEmptyBody") + protected void generate () throws IOException + { + /* + // print the symbol table + Enumeration v = parser.symbolTable.elements (); + Enumeration k = parser.symbolTable.keys (); + while (k.hasMoreElements ()) + System.out.println (k.nextElement () + ": " + v.nextElement ()); + */ + if (com.sun.tools.corba.ee.idl.ParseException.detected) + emitList = null; + else + emitList = parser.emitList.elements (); + if (emitList != null) + { + // Emit the output files for all of the types in the IDL file + if (arguments.verbose) + System.out.println (); + while (emitList.hasMoreElements ()) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)emitList.nextElement (); + if (arguments.verbose) + if (entry.generator () instanceof com.sun.tools.corba.ee.idl.Noop) + ; // Nothing will be generated, so don't say so. + else if (entry.module () . equals ("")) + System.out.println (com.sun.tools.corba.ee.idl.Util.getMessage("Compile.generating", entry.name())); + else + System.out.println (com.sun.tools.corba.ee.idl.Util.getMessage("Compile.generating", entry.module() + '/' + entry.name())); + entry.generate (symbolTable, null); + if (arguments.verbose) + if (entry.generator () instanceof com.sun.tools.corba.ee.idl.Noop) + ; // Nothing will be generated, so don't say so. + else if (entry.module () . equals ("")) + System.out.println (com.sun.tools.corba.ee.idl.Util.getMessage("Compile.genDone", entry.name())); + else + System.out.println (com.sun.tools.corba.ee.idl.Util.getMessage("Compile.genDone", entry.module() + '/' + entry.name())); + } + } + } // generate + + /** + * Start the parse/code generation process. This method calls init, + * parse, generate. If more control is desired, rather than call start, + * those three methods could be called explicitly. + **/ + public void start (String[] args) + { + try + { + init (args); + if (arguments.versionRequest) // + displayVersion (); + else + { + parse (); + generate (); + } + } + catch (InvalidArgument | IOException e) + { + System.err.println (e); + } + } // start + + private void initFactories () + { + // Get the factories. + com.sun.tools.corba.ee.idl.Factories factories = factories (); + if (factories == null) factories = new com.sun.tools.corba.ee.idl.Factories(); + + // Get the argument processor from the factories. + com.sun.tools.corba.ee.idl.Arguments tmpArgs = factories.arguments (); + if (tmpArgs == null) + arguments = new com.sun.tools.corba.ee.idl.Arguments(); + else + arguments = tmpArgs; + + // Get the symbol table entry factory from the factories. + com.sun.tools.corba.ee.idl.SymtabFactory tmpSTF = factories.symtabFactory (); + if (tmpSTF == null) + symtabFactory = new com.sun.tools.corba.ee.idl.DefaultSymtabFactory(); + else + symtabFactory = tmpSTF; + + // Get the expression factory from the factories. + ExprFactory tmpExpF = factories.exprFactory (); + if (tmpExpF == null) + exprFactory = new DefaultExprFactory (); + else + exprFactory = tmpExpF; + + // Get the generator factory from the factories. + com.sun.tools.corba.ee.idl.GenFactory tmpGenF = factories.genFactory (); + if (tmpGenF == null) + genFactory = noop; + else + genFactory = tmpGenF; + + // Get the language keywords. + keywords = factories.languageKeywords (); + if (keywords == null) + keywords = new String[0]; + } // initFactories + + private void initGenerators () + { + com.sun.tools.corba.ee.idl.AttributeGen agen = genFactory.createAttributeGen (); + com.sun.tools.corba.ee.idl.AttributeEntry.attributeGen = agen == null ? noop : agen; + + com.sun.tools.corba.ee.idl.ConstGen cgen = genFactory.createConstGen (); + com.sun.tools.corba.ee.idl.ConstEntry.constGen = cgen == null ? noop : cgen; + + com.sun.tools.corba.ee.idl.EnumGen egen = genFactory.createEnumGen (); + com.sun.tools.corba.ee.idl.EnumEntry.enumGen = egen == null ? noop : egen; + + com.sun.tools.corba.ee.idl.ExceptionGen exgen = genFactory.createExceptionGen (); + com.sun.tools.corba.ee.idl.ExceptionEntry.exceptionGen = exgen == null ? noop : exgen; + + com.sun.tools.corba.ee.idl.ForwardGen fgen = genFactory.createForwardGen (); + com.sun.tools.corba.ee.idl.ForwardEntry.forwardGen = fgen == null ? noop : fgen; + + com.sun.tools.corba.ee.idl.ForwardValueGen fvgen = genFactory.createForwardValueGen (); + com.sun.tools.corba.ee.idl.ForwardValueEntry.forwardValueGen = fvgen == null ? noop : fvgen; + + com.sun.tools.corba.ee.idl.IncludeGen ingen = genFactory.createIncludeGen (); + com.sun.tools.corba.ee.idl.IncludeEntry.includeGen = ingen == null ? noop : ingen; + + com.sun.tools.corba.ee.idl.InterfaceGen igen = genFactory.createInterfaceGen (); + com.sun.tools.corba.ee.idl.InterfaceEntry.interfaceGen = igen == null ? noop : igen; + + com.sun.tools.corba.ee.idl.ValueGen vgen = genFactory.createValueGen (); + com.sun.tools.corba.ee.idl.ValueEntry.valueGen = vgen == null ? noop : vgen; + + com.sun.tools.corba.ee.idl.ValueBoxGen vbgen = genFactory.createValueBoxGen (); + com.sun.tools.corba.ee.idl.ValueBoxEntry.valueBoxGen = vbgen == null ? noop : vbgen; + + com.sun.tools.corba.ee.idl.MethodGen mgen = genFactory.createMethodGen (); + com.sun.tools.corba.ee.idl.MethodEntry.methodGen = mgen == null ? noop : mgen; + + com.sun.tools.corba.ee.idl.ModuleGen modgen = genFactory.createModuleGen (); + com.sun.tools.corba.ee.idl.ModuleEntry.moduleGen = modgen == null ? noop : modgen; + + com.sun.tools.corba.ee.idl.NativeGen ngen = genFactory.createNativeGen (); + com.sun.tools.corba.ee.idl.NativeEntry.nativeGen = ngen == null ? noop : ngen; + + com.sun.tools.corba.ee.idl.ParameterGen pgen = genFactory.createParameterGen (); + com.sun.tools.corba.ee.idl.ParameterEntry.parameterGen = pgen == null ? noop : pgen; + + com.sun.tools.corba.ee.idl.PragmaGen prgen = genFactory.createPragmaGen (); + com.sun.tools.corba.ee.idl.PragmaEntry.pragmaGen = prgen == null ? noop : prgen; + + com.sun.tools.corba.ee.idl.PrimitiveGen primgen = genFactory.createPrimitiveGen (); + com.sun.tools.corba.ee.idl.PrimitiveEntry.primitiveGen = primgen == null ? noop : primgen; + + com.sun.tools.corba.ee.idl.SequenceGen seqgen = genFactory.createSequenceGen (); + com.sun.tools.corba.ee.idl.SequenceEntry.sequenceGen = seqgen == null ? noop : seqgen; + + com.sun.tools.corba.ee.idl.StringGen strgen = genFactory.createStringGen (); + com.sun.tools.corba.ee.idl.StringEntry.stringGen = strgen == null ? noop : strgen; + + com.sun.tools.corba.ee.idl.StructGen sgen = genFactory.createStructGen (); + com.sun.tools.corba.ee.idl.StructEntry.structGen = sgen == null ? noop : sgen; + + com.sun.tools.corba.ee.idl.TypedefGen tgen = genFactory.createTypedefGen (); + com.sun.tools.corba.ee.idl.TypedefEntry.typedefGen = tgen == null ? noop : tgen; + + com.sun.tools.corba.ee.idl.UnionGen ugen = genFactory.createUnionGen (); + com.sun.tools.corba.ee.idl.UnionEntry.unionGen = ugen == null ? noop : ugen; + } // initGenerators + + /** + * Write the version number of this compiler to standard out. + **/ + protected void displayVersion () + { + String message = com.sun.tools.corba.ee.idl.Util.getMessage ("Version.product", com.sun.tools.corba.ee.idl.Util.getMessage("Version.number")); + System.out.println (message); + } + + /** + * This is the repository of emitter arguments. + **/ + public com.sun.tools.corba.ee.idl.Arguments arguments = null; + /** + * This hashtable contains <real name, alias> pairs. It is filled in by + * extenders in cases where they wish to override an IDL type name with + * some other name. For instance, when mapping to Java, there could be + * an overrideNames entry of <"TRUE", "true">. NOTE: Do NOT change this + * variable to a new Hash table. Just add elements to it. + **/ + protected Hashtable overrideNames = new Hashtable (); + /** + * This is the symbol table. It will be empty until the parse method + * executes. If errors are encountered, the state of the symbol table + * is undefined. + **/ + protected Hashtable symbolTable = new Hashtable<>(); + /** + * This is a vector of strings of the form "IDLfile" or <IDLfile>. It is + * a list of the files included in the given IDL file. It will be empty + * until the parse method executes. If errors are encountered, the state + * of this vector is undefined. + **/ + protected Vector includes = new Vector (); + /** + * This is a vector of IncludeEntry's. It is a list of the files included + * in the given IDL file. It mirrors the includes vector. It will be empty + * until the parse method executes. If errors are encountered, the state of + * this vector is undefined. + **/ + private Vector includeEntries = new Vector (); + private static com.sun.tools.corba.ee.idl.Noop noop = new com.sun.tools.corba.ee.idl.Noop(); + private com.sun.tools.corba.ee.idl.GenFactory genFactory = null; + private com.sun.tools.corba.ee.idl.SymtabFactory symtabFactory = null; + private ExprFactory exprFactory = null; + private com.sun.tools.corba.ee.idl.Parser parser = null; + private com.sun.tools.corba.ee.idl.Preprocessor preprocessor = new com.sun.tools.corba.ee.idl.Preprocessor(); + private Enumeration emitList = null; + private String[] keywords = null; +} // class Compile + + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ConstEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ConstEntry.java new file mode 100644 index 000000000..1ae727edd --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ConstEntry.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for constants. + **/ +public class ConstEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected ConstEntry () + { + super (); + } // ctor + + protected ConstEntry (ConstEntry that) + { + super (that); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + _value = that._value; + } // ctor + + /** This is a shallow copy constructor. */ + protected ConstEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + /** This is a shallow copy clone. */ + public Object clone () + { + return new ConstEntry (this); + } // clone + + /** Invoke the constant generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + constGen.generate (symbolTable, this, stream); + } // generate + + /** Access the constant generator. + @return an object which implements the ConstGen interface. + @see com.sun.tools.corba.ee.idl.ConstGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return constGen; + } // generator + + public Expression value () + { + return _value; + } // value + + public void value (Expression newValue) + { + _value = newValue; + } // value + + static com.sun.tools.corba.ee.idl.ConstGen constGen; + private Expression _value = null; +} // class ConstEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ConstGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ConstGen.java new file mode 100644 index 000000000..0d0a68af5 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ConstGen.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ConstGen extends Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ConstEntry entry, PrintWriter stream); +} // interface ConstGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/DefaultSymtabFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/DefaultSymtabFactory.java new file mode 100644 index 000000000..e920a207a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/DefaultSymtabFactory.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +/** + * This factory constructs the default symbol table entries, namely, + * those declared within the package com.sun.tools.corba.ee.idl. + **/ +public class DefaultSymtabFactory implements SymtabFactory +{ + public com.sun.tools.corba.ee.idl.AttributeEntry attributeEntry () + { + return new com.sun.tools.corba.ee.idl.AttributeEntry(); + } // attributeEntry + + public com.sun.tools.corba.ee.idl.AttributeEntry attributeEntry (com.sun.tools.corba.ee.idl.InterfaceEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.AttributeEntry(container, id); + } // attributeEntry + + public com.sun.tools.corba.ee.idl.ConstEntry constEntry () + { + return new com.sun.tools.corba.ee.idl.ConstEntry(); + } // constEntry + + public com.sun.tools.corba.ee.idl.ConstEntry constEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ConstEntry(container, id); + } // constEntry + + public com.sun.tools.corba.ee.idl.NativeEntry nativeEntry () + { + return new com.sun.tools.corba.ee.idl.NativeEntry(); + } // interfaceEntry + + public com.sun.tools.corba.ee.idl.NativeEntry nativeEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.NativeEntry(container, id); + } // interfaceEntry + + public com.sun.tools.corba.ee.idl.EnumEntry enumEntry () + { + return new com.sun.tools.corba.ee.idl.EnumEntry(); + } // enumEntry + + public com.sun.tools.corba.ee.idl.EnumEntry enumEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.EnumEntry(container, id); + } // enumEntry + + public com.sun.tools.corba.ee.idl.ExceptionEntry exceptionEntry () + { + return new com.sun.tools.corba.ee.idl.ExceptionEntry(); + } // exceptionEntry + + public com.sun.tools.corba.ee.idl.ExceptionEntry exceptionEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ExceptionEntry(container, id); + } // exceptionEntry + + public com.sun.tools.corba.ee.idl.ForwardEntry forwardEntry () + { + return new com.sun.tools.corba.ee.idl.ForwardEntry(); + } // forwardEntry + + public com.sun.tools.corba.ee.idl.ForwardEntry forwardEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ForwardEntry(container, id); + } // forwardEntry + + public com.sun.tools.corba.ee.idl.ForwardValueEntry forwardValueEntry () + { + return new com.sun.tools.corba.ee.idl.ForwardValueEntry(); + } // forwardValueEntry + + public com.sun.tools.corba.ee.idl.ForwardValueEntry forwardValueEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ForwardValueEntry(container, id); + } // forwardValueEntry + + public com.sun.tools.corba.ee.idl.IncludeEntry includeEntry () + { + return new com.sun.tools.corba.ee.idl.IncludeEntry(); + } // includeEntry + + public com.sun.tools.corba.ee.idl.IncludeEntry includeEntry (com.sun.tools.corba.ee.idl.SymtabEntry container) + { + return new com.sun.tools.corba.ee.idl.IncludeEntry(container); + } // includeEntry + + public com.sun.tools.corba.ee.idl.InterfaceEntry interfaceEntry () + { + return new com.sun.tools.corba.ee.idl.InterfaceEntry(); + } // interfaceEntry + + public com.sun.tools.corba.ee.idl.InterfaceEntry interfaceEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.InterfaceEntry(container, id); + } // interfaceEntry + + public com.sun.tools.corba.ee.idl.ValueEntry valueEntry () + { + return new com.sun.tools.corba.ee.idl.ValueEntry(); + } // valueEntry + + public com.sun.tools.corba.ee.idl.ValueEntry valueEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ValueEntry(container, id); + } // valueEntry + + public com.sun.tools.corba.ee.idl.ValueBoxEntry valueBoxEntry () + { + return new com.sun.tools.corba.ee.idl.ValueBoxEntry(); + } // valueBoxEntry + + public com.sun.tools.corba.ee.idl.ValueBoxEntry valueBoxEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ValueBoxEntry(container, id); + } // valueBoxEntry + + public com.sun.tools.corba.ee.idl.MethodEntry methodEntry () + { + return new com.sun.tools.corba.ee.idl.MethodEntry(); + } // methodEntry + + public com.sun.tools.corba.ee.idl.MethodEntry methodEntry (com.sun.tools.corba.ee.idl.InterfaceEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.MethodEntry(container, id); + } // methodEntry + + public com.sun.tools.corba.ee.idl.ModuleEntry moduleEntry () + { + return new com.sun.tools.corba.ee.idl.ModuleEntry(); + } // moduleEntry + + public com.sun.tools.corba.ee.idl.ModuleEntry moduleEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ModuleEntry(container, id); + } // moduleEntry + + public com.sun.tools.corba.ee.idl.ParameterEntry parameterEntry () + { + return new com.sun.tools.corba.ee.idl.ParameterEntry(); + } // parameterEntry + + public com.sun.tools.corba.ee.idl.ParameterEntry parameterEntry (com.sun.tools.corba.ee.idl.MethodEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.ParameterEntry(container, id); + } // parameterEntry + + public com.sun.tools.corba.ee.idl.PragmaEntry pragmaEntry () + { + return new com.sun.tools.corba.ee.idl.PragmaEntry(); + } // pragmaEntry + + public com.sun.tools.corba.ee.idl.PragmaEntry pragmaEntry (com.sun.tools.corba.ee.idl.SymtabEntry container) + { + return new com.sun.tools.corba.ee.idl.PragmaEntry(container); + } // pragmaEntry + + public com.sun.tools.corba.ee.idl.PrimitiveEntry primitiveEntry () + { + return new com.sun.tools.corba.ee.idl.PrimitiveEntry(); + } // primitiveEntry + + /** "name" can be, but is not limited to, the primitive idl type names: + 'char', 'octet', 'short', 'long', etc. The reason it is not limited + to these is that, as an extender, you may wish to override these names. + For instance, when generating Java code, octet translates to byte, so + there is an entry in Compile.overrideNames: <"octet", "byte"> and a + PrimitiveEntry in the symbol table for "byte". */ + public com.sun.tools.corba.ee.idl.PrimitiveEntry primitiveEntry (String name) + { + return new com.sun.tools.corba.ee.idl.PrimitiveEntry(name); + } // primitiveEntry + + public com.sun.tools.corba.ee.idl.SequenceEntry sequenceEntry () + { + return new com.sun.tools.corba.ee.idl.SequenceEntry(); + } // sequenceEntry + + public com.sun.tools.corba.ee.idl.SequenceEntry sequenceEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.SequenceEntry(container, id); + } // sequenceEntry + + public com.sun.tools.corba.ee.idl.StringEntry stringEntry () + { + return new com.sun.tools.corba.ee.idl.StringEntry(); + } // stringEntry + + public com.sun.tools.corba.ee.idl.StructEntry structEntry () + { + return new com.sun.tools.corba.ee.idl.StructEntry(); + } // structEntry + + public com.sun.tools.corba.ee.idl.StructEntry structEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.StructEntry(container, id); + } // structEntry + + public com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry () + { + return new com.sun.tools.corba.ee.idl.TypedefEntry(); + } // typedefEntry + + public com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.TypedefEntry(container, id); + } // typedefEntry + + public com.sun.tools.corba.ee.idl.UnionEntry unionEntry () + { + return new com.sun.tools.corba.ee.idl.UnionEntry(); + } // unionEntry + + public com.sun.tools.corba.ee.idl.UnionEntry unionEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id) + { + return new com.sun.tools.corba.ee.idl.UnionEntry(container, id); + } // unionEntry + +} // interface DefaultSymtabFactory diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/EnumEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/EnumEntry.java new file mode 100644 index 000000000..e000f5709 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/EnumEntry.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for enumerated types. + **/ +public class EnumEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected EnumEntry () + { + super (); + } // ctor + + protected EnumEntry (EnumEntry that) + { + super (that); + _elements = (Vector)that._elements.clone (); + } // ctor + + protected EnumEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new EnumEntry (this); + } // clone + + /** Invoke the enumerator generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + enumGen.generate (symbolTable, this, stream); + } // generate + + /** Access the enumerator generator. + @return an object which implements the EnumGen interface. + @see com.sun.tools.corba.ee.idl.EnumGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return enumGen; + } // generator + + /** Add an element to the list of elements. */ + public void addElement (String element) + { + _elements.addElement (element); + } // addElement + + /** Each element of the vector is a String. */ + public Vector elements () + { + return _elements; + } // elements + + static com.sun.tools.corba.ee.idl.EnumGen enumGen; + private Vector _elements = new Vector (); +} // class EnumEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/EnumGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/EnumGen.java new file mode 100644 index 000000000..87a0b3cac --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/EnumGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface EnumGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.EnumEntry entry, PrintWriter stream); +} // interface EnumGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ExceptionEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ExceptionEntry.java new file mode 100644 index 000000000..58bde2233 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ExceptionEntry.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for exceptions. An exception is simply + * a struct by a different name. + **/ +public class ExceptionEntry extends StructEntry +{ + protected ExceptionEntry () + { + super (); + } // ctor + + protected ExceptionEntry (ExceptionEntry that) + { + super (that); + } // ctor + + protected ExceptionEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + } // ctor + + public Object clone () + { + return new ExceptionEntry (this); + } // clone + + /** Invoke the exception generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + exceptionGen.generate (symbolTable, this, stream); + } // generate + + /** Access the exception generator. + @return an object which implements the ExceptionGen interface. + @see com.sun.tools.corba.ee.idl.ExceptionGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return exceptionGen; + } // generator + + static com.sun.tools.corba.ee.idl.ExceptionGen exceptionGen; +} // class ExceptionEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ExceptionGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ExceptionGen.java new file mode 100644 index 000000000..622a35c75 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ExceptionGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ExceptionGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ExceptionEntry entry, PrintWriter stream); +} // interface ExceptionGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Factories.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Factories.java new file mode 100644 index 000000000..a16f81aa2 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Factories.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import com.sun.tools.corba.ee.idl.constExpr.DefaultExprFactory; +import com.sun.tools.corba.ee.idl.constExpr.ExprFactory; + +/** + * If the framework is being extended, this class must be extended. + * At very least, the genFactory method must be overridden to return + * the code generator extensions. The remaining methods may be overridden + * if necessary: + *
+ *
symtabFactory + *
If you wish to extend the symbol table entries, this method must return the factory which constructs those extensions. If you only want to extend a few of the symbol table entries, it may be useful to extend DefaultSymtabFactory and only override the pertinent methods. + *
exprFactory + *
If you wish to extend the expression classes, this method must return the factory which constructs those extensions. If you only want to extend a few of the expression classes, it may be useful to extend com.sun.tools.corba.ee.idl.constExpr.DefaultSymtabFactory and only override the pertinent methods. + *
arguments + *
If you wish to add additional arguments to the base set of arguments, extend Arguments and override this method to return that class. + *
languageKeywords + *
If the language you are generating code in has keywords other than IDL keywords, these keywords should be returned by this method. The framework will prepend any IDL identifiers it encounters which are in this list with an underscore (`_') to avoid compilation errors. For instance, `catch' is a Java keyword. If the generators are emitting Java code for the following IDL, emitting `catch' as is will cause compile errors, so it is changed to `_catch': + *
+ * IDL: + *
+ * const long catch = 22; + *
+ * Possible generated code: + *
+ * public static final int _catch = 22; + *
+ **/ +public class Factories +{ + /** Return the implementation of the GenFactory interface. If this + returns null, then the compiler cannot generate anything. */ + public GenFactory genFactory () + { + return null; + } // genFactory + + /** Return the implementation of the SymtabFactory interface. If this + returns null, the default symbol table entries will be used. */ + public com.sun.tools.corba.ee.idl.SymtabFactory symtabFactory () + { + return new com.sun.tools.corba.ee.idl.DefaultSymtabFactory(); + } // symtabFactory + + /** Return the implementation of the ExprFactory interface. If this + returns null, the default expressions will be used. */ + public ExprFactory exprFactory () + { + return new DefaultExprFactory(); + } // exprFactory + + /** Return a subclass of the Arguments class. If this returns null, + the default will be used. */ + public com.sun.tools.corba.ee.idl.Arguments arguments () + { + return new com.sun.tools.corba.ee.idl.Arguments(); + } // arguments + + /** Return the list of keywords in the generated language. + Note that these keywords may contain the following wildcards: +
+
`*' +
matches zero or more characters +
`+' +
matches one or more characters +
`.' +
matches any single character +
*/ + public String[] languageKeywords () + { + return null; + } // languageKeywords +} // interface Factories diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardEntry.java new file mode 100644 index 000000000..a972880cf --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardEntry.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for forward declarations of interfaces. + **/ +public class ForwardEntry extends com.sun.tools.corba.ee.idl.SymtabEntry implements com.sun.tools.corba.ee.idl.InterfaceType +{ + protected ForwardEntry () + { + super (); + } // ctor + + protected ForwardEntry (ForwardEntry that) + { + super (that); + } // ctor + + protected ForwardEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new ForwardEntry (this); + } // clone + + /** Invoke the forward declaration generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + forwardGen.generate (symbolTable, this, stream); + } // generate + + /** Access the interface generator. + @return an object which implements the InterfaceGen interface. + @see com.sun.tools.corba.ee.idl.InterfaceGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return forwardGen; + } // generator + + static boolean replaceForwardDecl (com.sun.tools.corba.ee.idl.InterfaceEntry interfaceEntry) + { + boolean result = true; + try + { + ForwardEntry forwardEntry = + (ForwardEntry) com.sun.tools.corba.ee.idl.Parser.symbolTable.get (interfaceEntry.fullName ()); + if ( forwardEntry != null ) + { + result = (interfaceEntry.getInterfaceType () == + forwardEntry.getInterfaceType ()); + forwardEntry.type (interfaceEntry); + + // If this interface has been forward declared, there are probably + // other interfaces which derive from a ForwardEntry. Replace + // those ForwardEntry's with this InterfaceEntry: + interfaceEntry.forwardedDerivers = forwardEntry.derivers; + for ( Enumeration derivers = forwardEntry.derivers.elements(); + derivers.hasMoreElements(); ) + ((com.sun.tools.corba.ee.idl.InterfaceEntry)derivers.nextElement ()).replaceForwardDecl (forwardEntry, interfaceEntry); + + // Replace the entry's whose types are forward declarations: + for ( Enumeration types = forwardEntry.types.elements (); + types.hasMoreElements (); ) + ((com.sun.tools.corba.ee.idl.SymtabEntry)types.nextElement ()).type (interfaceEntry); + } + } + catch (Exception exception) + {} + return result; + } // replaceForwardDecl + + /////////////// + // Implement interface InterfaceType + + public int getInterfaceType () + { + return _type; + } + + public void setInterfaceType (int type) + { + _type = type; + } + + static com.sun.tools.corba.ee.idl.ForwardGen forwardGen; + Vector derivers = new Vector (); // Vector of InterfaceEntry's. + Vector types = new Vector (); // Vector of the entry's whose type is a forward declaration. + private int _type = com.sun.tools.corba.ee.idl.InterfaceType.NORMAL; // interface type +} // class ForwardEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardGen.java new file mode 100644 index 000000000..d910e6210 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ForwardGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ForwardEntry entry, PrintWriter stream); +} // interface ForwardGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardValueEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardValueEntry.java new file mode 100644 index 000000000..999bc446f --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardValueEntry.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for forward declarations of values. + **/ +public class ForwardValueEntry extends ForwardEntry +{ + protected ForwardValueEntry () + { + super (); + } // ctor + + protected ForwardValueEntry (ForwardValueEntry that) + { + super (that); + } // ctor + + protected ForwardValueEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + } // ctor + + public Object clone () + { + return new ForwardValueEntry (this); + } // clone + + /** Invoke the forward value declaration generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + forwardValueGen.generate (symbolTable, this, stream); + } // generate + + /** Access the interface generator. + @return an object which implements the ForwardValueGen interface. + @see com.sun.tools.corba.ee.idl.ValueGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return forwardValueGen; + } // generator + + static com.sun.tools.corba.ee.idl.ForwardValueGen forwardValueGen; +} // class ForwardValueEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardValueGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardValueGen.java new file mode 100644 index 000000000..ae43bfbc5 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ForwardValueGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ForwardValueGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ForwardValueEntry entry, PrintWriter stream); +} // interface ForwardValueGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/GenFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/GenFactory.java new file mode 100644 index 000000000..86198f84c --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/GenFactory.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +/** + * To extend this compiler framework to generate something other than + * the default, this factory interface must be implemented and the name + * of it must be set in the main method (see idl.Compile). + *

+ * The implementation of each method should be quite simple. Take + * createAttributeGen, for instance. If the interface AttributeGen is + * implemented by a class called MyAttributeGen, then createAttributeGen + * will be the following: + *

+ * public AttributeGen createAttributeGen ()
+ * {
+ *   return new MyAttributeGen ();
+ * }
+ * 
+ *

+ * If it is desired that a generator do nothing, it is not necessary to + * implement one which does nothing; you may simply write that particular + * create method so that it returns null. + *

+ * Note that this class MUST have a public default constructor (one which + * takes no parameters). + **/ +public interface GenFactory +{ + public AttributeGen createAttributeGen (); + public com.sun.tools.corba.ee.idl.ConstGen createConstGen (); + public com.sun.tools.corba.ee.idl.EnumGen createEnumGen (); + public com.sun.tools.corba.ee.idl.ExceptionGen createExceptionGen (); + public com.sun.tools.corba.ee.idl.ForwardGen createForwardGen (); + public com.sun.tools.corba.ee.idl.ForwardValueGen createForwardValueGen (); + public com.sun.tools.corba.ee.idl.IncludeGen createIncludeGen (); + public com.sun.tools.corba.ee.idl.InterfaceGen createInterfaceGen (); + public com.sun.tools.corba.ee.idl.ValueGen createValueGen (); + public com.sun.tools.corba.ee.idl.ValueBoxGen createValueBoxGen (); + public com.sun.tools.corba.ee.idl.MethodGen createMethodGen (); + public com.sun.tools.corba.ee.idl.ModuleGen createModuleGen (); + public com.sun.tools.corba.ee.idl.NativeGen createNativeGen (); + public com.sun.tools.corba.ee.idl.ParameterGen createParameterGen (); + public com.sun.tools.corba.ee.idl.PragmaGen createPragmaGen (); + public com.sun.tools.corba.ee.idl.PrimitiveGen createPrimitiveGen (); + public com.sun.tools.corba.ee.idl.SequenceGen createSequenceGen (); + public com.sun.tools.corba.ee.idl.StringGen createStringGen (); + public com.sun.tools.corba.ee.idl.StructGen createStructGen (); + public com.sun.tools.corba.ee.idl.TypedefGen createTypedefGen (); + public com.sun.tools.corba.ee.idl.UnionGen createUnionGen (); +} // interface GenFactory diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/GenFileStream.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/GenFileStream.java new file mode 100644 index 000000000..8a4d07b8c --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/GenFileStream.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.CharArrayWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; + +public class GenFileStream extends PrintWriter +{ + public GenFileStream (String filename) + { + // What I really want to do here is: + // super (byteStream = new ByteArrayOutputStream ()); + // but that isn't legal. The super constructor MUST + // be called before any instance variables are used. + // This implementation gets around that problem. + // + //super (tmpByteStream = new ByteArrayOutputStream ()); + //byteStream = tmpByteStream; + super (tmpCharArrayWriter = new CharArrayWriter()); + charArrayWriter = tmpCharArrayWriter; + name = filename; + } // ctor + + public void close () + { + File file = new File (name); + try + { + if (checkError ()) + throw new IOException (); + // + //FileOutputStream fileStream = new FileOutputStream (file); + //fileStream.write (byteStream.toByteArray ()); + //fileStream.close (); + FileWriter fileWriter = new FileWriter (file); + fileWriter.write (charArrayWriter.toCharArray ()); + fileWriter.close (); + } + catch (IOException e) + { + String[] parameters = {name, e.toString ()}; + System.err.println (Util.getMessage("GenFileStream.1", parameters)); + } + super.close (); + } // close + + public String name () + { + return name; + } // name + + // + //private ByteArrayOutputStream byteStream; + //private static ByteArrayOutputStream tmpByteStream; + private CharArrayWriter charArrayWriter; + private static CharArrayWriter tmpCharArrayWriter; + private String name; +} // GenFileStream diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Generator.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Generator.java new file mode 100644 index 000000000..f8e4deb95 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Generator.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +public interface Generator +{ +} // interface Generator + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/IDLID.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/IDLID.java new file mode 100644 index 000000000..7acaa8129 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/IDLID.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +public class IDLID extends RepositoryID +{ + public IDLID () + { + _prefix = ""; + _name = ""; + _version = "1.0"; + } // ctor + + public IDLID (String prefix, String name, String version) + { + _prefix = prefix; + _name = name; + _version = version; + } // ctor + + public String ID () + { + if (_prefix.equals ("")) + return "IDL:" + _name + ':' + _version; + else + return "IDL:" + _prefix + '/' + _name + ':' + _version; + } // ID + + public String prefix () + { + return _prefix; + } // prefix + + void prefix (String prefix) + { + if (prefix == null) + _prefix = ""; + else + _prefix = prefix; + } // prefix + + public String name () + { + return _name; + } // name + + void name (String name) + { + if (name == null) + _name = ""; + else + _name = name; + } // name + + public String version () + { + return _version; + } // version + + void version (String version) + { + if (version == null) + _version = ""; + else + _version = version; + } // version + + void appendToName (String name) + { + if (name != null) + if (_name.equals ("")) + _name = name; + else + _name = _name + '/' + name; + } // appendToName + + void replaceName (String name) + { + if (name == null) + _name = ""; + else + { + int index = _name.lastIndexOf ('/'); + if (index < 0) + _name = name; + else + _name = _name.substring (0, index + 1) + name; + } + } // replaceName + + public Object clone () + { + return new IDLID (_prefix, _name, _version); + } // clone + + private String _prefix; + private String _name; + private String _version; +} // class IDLID diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/IncludeEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/IncludeEntry.java new file mode 100644 index 000000000..e27f69fcc --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/IncludeEntry.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for the #include statement. + **/ +public class IncludeEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected IncludeEntry () + { + super (); + repositoryID (Util.emptyID); + } // ctor + + protected IncludeEntry (com.sun.tools.corba.ee.idl.SymtabEntry that) + { + super (that, new com.sun.tools.corba.ee.idl.IDLID()); + module (that.name ()); + name (""); + } // ctor + + protected IncludeEntry (IncludeEntry that) + { + super (that); + } // ctor + + public Object clone () + { + return new IncludeEntry (this); + } // clone + + /** Invoke the Include type generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + includeGen.generate (symbolTable, this, stream); + } // generate + + /** Access the Include type generator. + @return an object which implements the IncludeGen interface. + @see com.sun.tools.corba.ee.idl.IncludeGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return includeGen; + } // generator + + //d44810 + /** Set the fully-qualified file specification of this include file. */ + public void absFilename (String afn) + { + _absFilename = afn; + } + + //d44810 + /** Access the fully-qualified file specification of this include. + @return a string containing the path of the include file. */ + public String absFilename () + { + return _absFilename; + } + + /** Add an IncludeEntry to the list of files which this included + file includes. */ + public void addInclude (IncludeEntry entry) + { + includeList.addElement (entry); + } // addInclude + + /** Get the list of files which this file includes. */ + public Vector includes () + { + return includeList; + } // includes + + static com.sun.tools.corba.ee.idl.IncludeGen includeGen; + /** List of files this file includes */ + private Vector includeList = new Vector (); + //d44810 + /** Absolute file name for .u file generation. */ + private String _absFilename = null; +} // class IncludeEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/IncludeGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/IncludeGen.java new file mode 100644 index 000000000..2c548dec3 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/IncludeGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface IncludeGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.IncludeEntry entry, PrintWriter stream); +} // interface IncludeGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceEntry.java new file mode 100644 index 000000000..0aba14bac --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceEntry.java @@ -0,0 +1,331 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for interfaces. + **/ +public class InterfaceEntry extends com.sun.tools.corba.ee.idl.SymtabEntry implements InterfaceType +{ + + protected InterfaceEntry () + { + super (); + } // ctor + + protected InterfaceEntry (InterfaceEntry that) + { + super (that); + _derivedFromNames = (Vector)that._derivedFromNames.clone (); + _derivedFrom = (Vector)that._derivedFrom.clone (); + _methods = (Vector)that._methods.clone (); + _allMethods = (Vector)that._allMethods.clone (); + forwardedDerivers = (Vector)that.forwardedDerivers.clone (); + _contained = (Vector)that._contained.clone (); + _interfaceType = that._interfaceType; + } // ctor + + protected InterfaceEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public boolean isAbstract() + { + return _interfaceType == ABSTRACT ; + } + + public boolean isLocal() + { + return _interfaceType == LOCAL ; + } + + public boolean isLocalServant() + { + return _interfaceType == LOCALSERVANT ; + } + + public boolean isLocalSignature() + { + return _interfaceType == LOCAL_SIGNATURE_ONLY ; + } + + public Object clone () + { + return new InterfaceEntry (this); + } // clone + + /** Invoke the interface generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + interfaceGen.generate (symbolTable, this, stream); + } // generate + + /** Access the interface generator. + @return an object which implements the InterfaceGen interface. + @see com.sun.tools.corba.ee.idl.InterfaceGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return interfaceGen; + } // generator + + /** Add an InterfaceEntry to the list of interfaces which this interface + is derivedFrom. During parsing, the parameter to this method COULD + be a ForwardEntry, but when parsing is complete, calling derivedFrom + will return a vector which only contains InterfaceEntry's. */ + public void addDerivedFrom (com.sun.tools.corba.ee.idl.SymtabEntry derivedFrom) + { + _derivedFrom.addElement (derivedFrom); + } // addDerivedFrom + + /** This method returns a vector of InterfaceEntry's. */ + public Vector derivedFrom () + { + return _derivedFrom; + } // derivedFrom + + /** Add to the list of derivedFrom names. */ + public void addDerivedFromName (String name) + { + _derivedFromNames.addElement (name); + } // addDerivedFromName + + /** This method returns a vector of Strings, each of which is a fully + qualified name of an interface. This vector corresponds to the + derivedFrom vector. The first element of this vector is the name + of the first element of the derivedFrom vector, etc. */ + public Vector derivedFromNames () + { + return _derivedFromNames; + } // derivedFromNames + + /** Add a method/attribute to the list of methods. */ + public void addMethod (com.sun.tools.corba.ee.idl.MethodEntry method) + { + _methods.addElement (method); + } // addMethod + + /** This is a vector of MethodEntry's. These are the methods and + attributes contained within this Interface. */ + public Vector methods () + { + return _methods; + } // methods + + /** Add a symbol table entry to this interface's contained vector. */ + public void addContained (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + _contained.addElement (entry); + } // addContained + + /** This is a vector of SymtabEntry's. Valid entries in this vector are: + AttributeEntry, ConstEntry, EnumEntry, ExceptionEntry, MethodEntry, + StructEntry, NativeEntry, TypedefEntry, UnionEntry. + Note that the methods vector is a subset of this vector. */ + public Vector contained () + { + return _contained; + } // contained + + void methodsAddElement (com.sun.tools.corba.ee.idl.MethodEntry method, com.sun.tools.corba.ee.idl.Scanner scanner) + { + if (verifyMethod (method, scanner, false)) + { + addMethod (method); + _allMethods.addElement (method); + + // Add this method to the 'allMethods' list of any interfaces + // which may have inherited this one when it was a forward + // reference. + addToForwardedAllMethods (method, scanner); + } + } // methodsAddElement + + void addToForwardedAllMethods (com.sun.tools.corba.ee.idl.MethodEntry method, com.sun.tools.corba.ee.idl.Scanner scanner) + { + Enumeration e = forwardedDerivers.elements (); + while (e.hasMoreElements ()) + { + InterfaceEntry derived = (InterfaceEntry)e.nextElement (); + if (derived.verifyMethod (method, scanner, true)) + derived._allMethods.addElement (method); + } + } // addToForwardedAllMethods + + // Make sure a method by this name doesn't exist in this class or + // in this class's parents + private boolean verifyMethod (com.sun.tools.corba.ee.idl.MethodEntry method, com.sun.tools.corba.ee.idl.Scanner scanner, boolean clash) + { + boolean unique = true; + String lcName = method.name ().toLowerCase (); + Enumeration e = _allMethods.elements (); + while (e.hasMoreElements ()) + { + com.sun.tools.corba.ee.idl.MethodEntry emethod = (com.sun.tools.corba.ee.idl.MethodEntry)e.nextElement (); + + // Make sure the method doesn't exist either in its + // original name or in all lower case. In IDL, identifiers + // which differ only in case are collisions. + String lceName = emethod.name ().toLowerCase (); + if (method != emethod && lcName.equals (lceName)) + { + if (clash) + com.sun.tools.corba.ee.idl.ParseException.methodClash(scanner, fullName(), method.name()); + else + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, method.name()); + unique = false; + break; + } + } + return unique; + } // verifyMethod + + void derivedFromAddElement (com.sun.tools.corba.ee.idl.SymtabEntry e, com.sun.tools.corba.ee.idl.Scanner scanner) + { + addDerivedFrom (e); + addDerivedFromName (e.fullName ()); + addParentType( e, scanner ); + } // derivedFromAddElement + + void addParentType (com.sun.tools.corba.ee.idl.SymtabEntry e, com.sun.tools.corba.ee.idl.Scanner scanner) + { + if (e instanceof com.sun.tools.corba.ee.idl.ForwardEntry) + addToDerivers ((com.sun.tools.corba.ee.idl.ForwardEntry)e); + else + { // e instanceof InterfaceEntry + InterfaceEntry derivedFrom = (InterfaceEntry)e; + + // Compare all of the parent's methods to the methods on this + // interface, looking for name clashes: + for ( Enumeration enumeration = derivedFrom._allMethods.elements (); + enumeration.hasMoreElements (); ) + { + com.sun.tools.corba.ee.idl.MethodEntry method = (com.sun.tools.corba.ee.idl.MethodEntry)enumeration.nextElement (); + if ( verifyMethod (method, scanner, true)) + _allMethods.addElement (method); + + // Add this method to the 'allMethods' list of any interfaces + // which may have inherited this one when it was a forward + // reference: + addToForwardedAllMethods (method, scanner); + } + + // If any of the parent's parents are forward entries, make + // sure this interface gets added to their derivers list so + // that when the forward entry is defined, the 'allMethods' + // list of this interface can be updated. + lookForForwardEntrys (scanner, derivedFrom); + } + } // addParentType + + private void lookForForwardEntrys (com.sun.tools.corba.ee.idl.Scanner scanner, InterfaceEntry entry) + { + Enumeration parents = entry.derivedFrom ().elements (); + while (parents.hasMoreElements ()) + { + com.sun.tools.corba.ee.idl.SymtabEntry parent = (com.sun.tools.corba.ee.idl.SymtabEntry)parents.nextElement (); + if (parent instanceof com.sun.tools.corba.ee.idl.ForwardEntry) + addToDerivers ((com.sun.tools.corba.ee.idl.ForwardEntry)parent); + else if (parent == entry) + com.sun.tools.corba.ee.idl.ParseException.selfInherit(scanner, entry.fullName()); + else // it must be an InterfaceEntry + lookForForwardEntrys (scanner, (InterfaceEntry)parent); + } + } // lookForForwardEntrys + + public boolean replaceForwardDecl (com.sun.tools.corba.ee.idl.ForwardEntry oldEntry, InterfaceEntry newEntry) + { + int index = _derivedFrom.indexOf( oldEntry ); + if ( index >= 0 ) + _derivedFrom.setElementAt( newEntry, index ); + return (index >= 0); + } // replaceForwardDecl + + private void addToDerivers (com.sun.tools.corba.ee.idl.ForwardEntry forward) + { + // Add this interface to the derivers list on the forward entry + // so that when the forward entry is defined, the 'allMethods' + // list of this interface can be updated. + forward.derivers.addElement (this); + Enumeration e = forwardedDerivers.elements (); + while (e.hasMoreElements ()) + forward.derivers.addElement ((InterfaceEntry)e.nextElement ()); + } // addToDerivers + + /** This method returns a vector of the elements in the state block. + If it is null, this is not a stateful interface. If it is non-null, + but of zero length, then it is still stateful; it has no state + entries itself, but it has an ancestor which does. */ + public Vector state () + { + return _state; + } // state + + public void initState () + { + _state = new Vector (); + } // initState + + public void addStateElement (com.sun.tools.corba.ee.idl.InterfaceState state, com.sun.tools.corba.ee.idl.Scanner scanner) + { + if (_state == null) + _state = new Vector (); + String name = state.entry.name (); + for (Enumeration e = _state.elements (); e.hasMoreElements ();) + if (name.equals (((com.sun.tools.corba.ee.idl.InterfaceState) e.nextElement ()).entry.name ())) + com.sun.tools.corba.ee.idl.ParseException.duplicateState(scanner, name); + _state.addElement (state); + } // state + + public int getInterfaceType () + { + return _interfaceType; + } + + public void setInterfaceType (int type) + { + _interfaceType = type; + } + + /** Get the allMethods vector. */ + public Vector allMethods () + { + return _allMethods; + } + + private Vector _derivedFromNames = new Vector(); + private Vector _derivedFrom = new Vector(); + private Vector _methods = new Vector(); + Vector _allMethods = new Vector(); + Vector forwardedDerivers = new Vector(); + private Vector _contained = new Vector(); + private Vector _state = null; + private int _interfaceType = NORMAL; + + static com.sun.tools.corba.ee.idl.InterfaceGen interfaceGen; +} // class InterfaceEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceGen.java new file mode 100644 index 000000000..a104acb72 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceGen.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface InterfaceGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.InterfaceEntry entry, PrintWriter stream); +} // interface InterfaceGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceState.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceState.java new file mode 100644 index 000000000..94c6c8a7a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceState.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +/** + * This class is only used within an InterfaceEntry. If the interface + * is stateful, then its state vector will contain one or more of these + * InterfaceStates. + **/ +public class InterfaceState +{ + public static final int Private = 0, + Protected = 1, + Public = 2; + + public InterfaceState (int m, TypedefEntry e) + { + modifier = m; + entry = e; + if (modifier < Private || modifier > Public) + modifier = Public; + } // ctor + + public int modifier = Public; + public TypedefEntry entry = null; +} // class InterfaceState diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceType.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceType.java new file mode 100644 index 000000000..1337522a0 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InterfaceType.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +public interface InterfaceType +{ + public static final int NORMAL = 0 ; + public static final int ABSTRACT = 1 ; + + // LOCAL generates code according to the Local interfaces + // Here helper and holder classes are the only ones generated + public static final int LOCAL = 2 ; + + // intermediate solution to enable people to extend ServantLocatorPOA + // and ServantActivatorPOA for interoperability. This is until the + // POA is declared Local officially by OMG + public static final int LOCALSERVANT = 3 ; + + // generate only signature interfaces, no helper/holders are generated + public static final int LOCAL_SIGNATURE_ONLY = 4 ; + + public int getInterfaceType (); + + public void setInterfaceType( int type ) ; +} // interface InterfaceType diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/InvalidArgument.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InvalidArgument.java new file mode 100644 index 000000000..e9246ebb7 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InvalidArgument.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +/** + * An invalid argument for the compiler has been encountered. + **/ +public class InvalidArgument extends Exception +{ + /** @param arg the invalid argument. */ + public InvalidArgument (String arg) + { + message = Util.getMessage("InvalidArgument.1", arg) + "\n\n" + Util.getMessage("usage"); + } // ctor + + public InvalidArgument () + { + message = Util.getMessage("InvalidArgument.2") + "\n\n" + Util.getMessage("usage"); + } // ctor + + public String getMessage () + { + return message; + } // getMessage + + private String message = null; +} // class InvalidArgument diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/InvalidCharacter.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InvalidCharacter.java new file mode 100644 index 000000000..1a5ee0187 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/InvalidCharacter.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -D62023 Cast char to byte for JDK 1.2 compatability. + +import java.io.IOException; + +public class InvalidCharacter extends IOException +{ + public InvalidCharacter (String filename, String line, int lineNumber, int pos, char ch) + { + String pointer = "^"; + if (pos > 1) + { + byte[] bytes = new byte [pos - 1]; + for (int i = 0; i < pos - 1; ++i) + bytes[i] = (byte)' '; // + pointer = new String (bytes) + pointer; + } + String[] parameters = {filename, Integer.toString (lineNumber), "" + ch, Integer.toString ((int)ch), line, pointer}; + message = Util.getMessage("InvalidCharacter.1", parameters); + } + + public String getMessage () + { + return message; + } // getMessage + + private String message = null; +} // class InvalidCharacter + + + + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/MethodEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/MethodEntry.java new file mode 100644 index 000000000..0c1ab5e5e --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/MethodEntry.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// - What does oneway mean? + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for methods. + **/ +public class MethodEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected MethodEntry () + { + super (); + } // ctor + + protected MethodEntry (MethodEntry that) + { + super (that); + _exceptionNames = (Vector)that._exceptionNames.clone (); + _exceptions = (Vector)that._exceptions.clone (); + _contexts = (Vector)that._contexts.clone (); + _parameters = (Vector)that._parameters.clone (); + _oneway = that._oneway; + } // ctor + + protected MethodEntry (InterfaceEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new MethodEntry (this); + } // clone + + /** Invoke the method generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + methodGen.generate (symbolTable, this, stream); + } // generate + + /** Access the method generator. + @return an object which implements the MethodGen interface. + @see com.sun.tools.corba.ee.idl.MethodGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return methodGen; + } // generator + + public void type (com.sun.tools.corba.ee.idl.SymtabEntry newType) + { + super.type (newType); + if (newType == null) + typeName ("void"); + } // type + + /** Add an exception to the exception list. */ + public void addException (com.sun.tools.corba.ee.idl.ExceptionEntry exception) + { + _exceptions.addElement (exception); + } // addException + + /** This a a vector of the exceptions which this method raises. */ + public Vector exceptions () + { + return _exceptions; + } // exceptions + + /** Add an exception name to the list of exception names. */ + public void addExceptionName (String name) + { + _exceptionNames.addElement (name); + } // addExceptionName + + /** This is a vector of strings, each of which is the full name of an + exception which this method throws. This vector corresponds to the + exceptions vector. The first element of this vector is the name + of the first element of the exceptions vector, etc. */ + public Vector exceptionNames () + { + return _exceptionNames; + } // exceptionNames + + /* Add a context to the context list. */ + public void addContext (String context) + { + _contexts.addElement (context); + } // addContext + + /** This is a vector of strings, each of which is the name of a context. */ + public Vector contexts () + { + return _contexts; + } // contexts + + /** Add a parameter to the parameter list. */ + public void addParameter (com.sun.tools.corba.ee.idl.ParameterEntry parameter) + { + _parameters.addElement (parameter); + } // addParameter + + /** This is a vector of ParameterEntry's. They are the parameters on + this method and their order in the vector is the order they appear + on the method. */ + public Vector parameters () + { + return _parameters; + } // parameters + + /** Is this a oneway method? */ + public void oneway (boolean yes) + { + _oneway = yes; + } // oneway + + /** Is this a oneway method? */ + public boolean oneway () + { + return _oneway; + } // oneway + + /** Is this a value method? */ + public void valueMethod (boolean yes) + { + _valueMethod = yes; + } // valueMethod + + /** Is this a value method? */ + public boolean valueMethod () + { + return _valueMethod; + } // valueMethod + + void exceptionsAddElement (com.sun.tools.corba.ee.idl.ExceptionEntry e) + { + addException (e); + addExceptionName (e.fullName ()); + } // exceptionsAddElement + + private Vector _exceptionNames = new Vector (); + private Vector _exceptions = new Vector (); + private Vector _contexts = new Vector (); + private Vector _parameters = new Vector (); + private boolean _oneway = false; + private boolean _valueMethod = false; + + static com.sun.tools.corba.ee.idl.MethodGen methodGen; +} // class MethodEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/MethodGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/MethodGen.java new file mode 100644 index 000000000..713df336d --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/MethodGen.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface MethodGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.MethodEntry entry, PrintWriter stream); +} // interface MethodGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ModuleEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ModuleEntry.java new file mode 100644 index 000000000..207d616dd --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ModuleEntry.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for modules. + **/ +public class ModuleEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected ModuleEntry () + { + super (); + } // ctor + + protected ModuleEntry (ModuleEntry that) + { + super (that); + _contained = (Vector)that._contained.clone (); + } // ctor + + protected ModuleEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new ModuleEntry (this); + } // clone + + /** Invoke the module generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + moduleGen.generate (symbolTable, this, stream); + } // generate + + /** Access the module generator. + @return an object which implements the ModuleGen interface. + @see com.sun.tools.corba.ee.idl.ModuleGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return moduleGen; + } // generator + + /** alid entries in this vector are: TypedefEntry, ExceptionEntry, + StructEntry, UnionEntry, EnumEntry, ConstEntry, InterfaceEntry, + ModuleEntry. */ + public void addContained (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + _contained.addElement (entry); + } // addContained + + /** This is a vector of SymtabEntry's. Valid entries in this vector are: + TypedefEntry, ExceptionEntry, StructEntry, UnionEntry, EnumEntry, + ConstEntry, InterfaceEntry, ModuleEntry. */ + public Vector contained () + { + return _contained; + } // contained + + private Vector _contained = new Vector (); + + static com.sun.tools.corba.ee.idl.ModuleGen moduleGen; +} // class ModuleEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ModuleGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ModuleGen.java new file mode 100644 index 000000000..8875beb7a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ModuleGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ModuleGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ModuleEntry entry, PrintWriter stream); +} // interface ModuleGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/NativeEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/NativeEntry.java new file mode 100644 index 000000000..09c4e04b7 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/NativeEntry.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for constants. + **/ +public class NativeEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected NativeEntry () + { + super (); + repositoryID (Util.emptyID); + } // ctor + + protected NativeEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + protected NativeEntry (NativeEntry that) + { + super (that); + } // ctor + + /** This is a shallow copy clone. */ + public Object clone () + { + return new NativeEntry (this); + } // clone + + /** Invoke the constant generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + nativeGen.generate(symbolTable, this, stream); + } // generate + + /** Access the constant generator. + @return an object which implements the ConstGen interface. + @see com.sun.tools.corba.ee.idl.ConstGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return nativeGen; + } // generator + + static com.sun.tools.corba.ee.idl.NativeGen nativeGen; +} // class NativeEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/NativeGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/NativeGen.java new file mode 100644 index 000000000..39bc79f71 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/NativeGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface NativeGen extends Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.NativeEntry entry, PrintWriter stream); +} // interface NativeGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/NoPragma.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/NoPragma.java new file mode 100644 index 000000000..f0af0c055 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/NoPragma.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.IOException; + +class NoPragma extends PragmaHandler +{ + public boolean process (String pragma, String currentToken) throws IOException + { + parseException (com.sun.tools.corba.ee.idl.Util.getMessage("Preprocessor.unknownPragma", pragma)); + skipToEOL (); + return true; + } // process +} // class NoPragma diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Noop.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Noop.java new file mode 100644 index 000000000..51958e830 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Noop.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public class Noop implements + com.sun.tools.corba.ee.idl.AttributeGen, com.sun.tools.corba.ee.idl.ConstGen, com.sun.tools.corba.ee.idl.EnumGen, com.sun.tools.corba.ee.idl.ExceptionGen, com.sun.tools.corba.ee.idl.ForwardGen, + com.sun.tools.corba.ee.idl.ForwardValueGen, com.sun.tools.corba.ee.idl.IncludeGen, com.sun.tools.corba.ee.idl.InterfaceGen, com.sun.tools.corba.ee.idl.ValueGen, com.sun.tools.corba.ee.idl.ValueBoxGen, + com.sun.tools.corba.ee.idl.MethodGen, com.sun.tools.corba.ee.idl.ModuleGen, com.sun.tools.corba.ee.idl.NativeGen, com.sun.tools.corba.ee.idl.ParameterGen, com.sun.tools.corba.ee.idl.PragmaGen, + com.sun.tools.corba.ee.idl.PrimitiveGen, com.sun.tools.corba.ee.idl.SequenceGen, com.sun.tools.corba.ee.idl.StringGen, com.sun.tools.corba.ee.idl.StructGen, com.sun.tools.corba.ee.idl.TypedefGen, + com.sun.tools.corba.ee.idl.UnionGen, GenFactory +{ + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.AttributeEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ConstEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.EnumEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ExceptionEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ForwardEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ForwardValueEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.IncludeEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.InterfaceEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ValueEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ValueBoxEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.MethodEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ModuleEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ParameterEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.PragmaEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.PrimitiveEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.SequenceEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.StringEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.StructEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.TypedefEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.UnionEntry entry, PrintWriter stream) + { + } // generate + + public void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.NativeEntry entry, PrintWriter stream) + { + } // generate + + // For GenFactory + public com.sun.tools.corba.ee.idl.AttributeGen createAttributeGen () + { + return null; + } // createAttributeGen + + public com.sun.tools.corba.ee.idl.ConstGen createConstGen () + { + return null; + } // createConstGen + + public com.sun.tools.corba.ee.idl.EnumGen createEnumGen () + { + return null; + } // createEnumGen + + public com.sun.tools.corba.ee.idl.ExceptionGen createExceptionGen () + { + return null; + } // createExceptionGen + + public com.sun.tools.corba.ee.idl.ForwardGen createForwardGen () + { + return null; + } // createForwardGen + + public com.sun.tools.corba.ee.idl.ForwardValueGen createForwardValueGen () + { + return null; + } // createForwardValueGen + + public com.sun.tools.corba.ee.idl.IncludeGen createIncludeGen () + { + return null; + } // createIncludeGen + + public com.sun.tools.corba.ee.idl.InterfaceGen createInterfaceGen () + { + return null; + } // createInterfaceGen + + public com.sun.tools.corba.ee.idl.ValueGen createValueGen () + { + return null; + } // createValueGen + + public com.sun.tools.corba.ee.idl.ValueBoxGen createValueBoxGen () + { + return null; + } // createValueBoxGen + + public com.sun.tools.corba.ee.idl.MethodGen createMethodGen () + { + return null; + } // createMethodGen + + public com.sun.tools.corba.ee.idl.ModuleGen createModuleGen () + { + return null; + } // createModuleGen + + public com.sun.tools.corba.ee.idl.NativeGen createNativeGen () + { + return null; + } // createNativeGen + + public com.sun.tools.corba.ee.idl.ParameterGen createParameterGen () + { + return null; + } // createParameterGen + + public com.sun.tools.corba.ee.idl.PragmaGen createPragmaGen () + { + return null; + } // createPragmaGen + + public com.sun.tools.corba.ee.idl.PrimitiveGen createPrimitiveGen () + { + return null; + } // createPrimitiveGen + + public com.sun.tools.corba.ee.idl.SequenceGen createSequenceGen () + { + return null; + } // createSequenceGen + + public com.sun.tools.corba.ee.idl.StringGen createStringGen () + { + return null; + } // createStringGen + + public com.sun.tools.corba.ee.idl.StructGen createStructGen () + { + return null; + } // createStructGen + + public com.sun.tools.corba.ee.idl.TypedefGen createTypedefGen () + { + return null; + } // createTypedefGen + + public com.sun.tools.corba.ee.idl.UnionGen createUnionGen () + { + return null; + } // createUnionGen +} // class Noop diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParameterEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParameterEntry.java new file mode 100644 index 000000000..8c96196d0 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParameterEntry.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for parameters. + **/ +public class ParameterEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + /** This is a set of class constants. A parameter can be passed + as one of In, Out, or Inout. */ + public static final int In = 0, + Inout = 1, + Out = 2; + + protected ParameterEntry () + { + super (); + } // ctor + + protected ParameterEntry (ParameterEntry that) + { + super (that); + _passType = that._passType; + } // ctor + + protected ParameterEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new ParameterEntry (this); + } // clone + + /** Invoke the paramter generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + parameterGen.generate (symbolTable, this, stream); + } // generate + + /** Access the parameter generator. + @return an object which implements the ParameterGen interface. + @see com.sun.tools.corba.ee.idl.ParameterGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return parameterGen; + } // generator + + /** This indicates the pass type of this parameter. */ + public void passType (int passType) + { + if (passType >= In && passType <= Out) + _passType = passType; + } // passType + + /** This indicates the pass type of this parameter. */ + public int passType () + { + return _passType; + } // passType + + private int _passType = In; + + static com.sun.tools.corba.ee.idl.ParameterGen parameterGen; +} // class ParameterEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParameterGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParameterGen.java new file mode 100644 index 000000000..50ff21205 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParameterGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ParameterGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ParameterEntry entry, PrintWriter stream); +} // interface ParameterGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParseException.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParseException.java new file mode 100644 index 000000000..d6ad10b9b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ParseException.java @@ -0,0 +1,419 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +/** + * + **/ +class ParseException extends Exception +{ + /** + * Constructor: print the supplied message to Standard.err + * and create a new ParseException + * @return a new ParseException. + **/ + ParseException (String message) + { + super (message); + System.err.println (message); + detected = true; + } // ctor + + /** + * Constructor: print the supplied message to Standard.err, if it + * is not a warning, and create a new ParseException. + * @return a new ParseException. + **/ + ParseException (String message, boolean onlyAWarning) + { + super (message); + System.err.println (message); + if (!onlyAWarning) + detected = true; + } + + static ParseException abstractValueBox (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("abstractValueBox", scanner); + } + + static ParseException alreadyDeclared (com.sun.tools.corba.ee.idl.Scanner scanner, String type) + { + return arg1 ("alreadyDeclared", scanner, type); + } + + static ParseException declNotInSameFile( com.sun.tools.corba.ee.idl.Scanner scanner, String type, + String firstFile ) + { + return arg2 ("declNotInSameFile", scanner, type, firstFile) ; + } + + static ParseException alreadyDefaulted (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("alreadydefaulted", scanner); + } + + static ParseException alreadyDerived (com.sun.tools.corba.ee.idl.Scanner scanner, String derived, String iface) + { + return arg2 ("alreadyDerived", scanner, derived, iface); + } + + static ParseException alreadyRaised (com.sun.tools.corba.ee.idl.Scanner scanner, String exception) + { + return arg1 ("alreadyRaised", scanner, exception); + } + + // + static ParseException attributeNotType (com.sun.tools.corba.ee.idl.Scanner scanner, String attr) + { + return arg1 ("attributeNotType", scanner, attr); + } + + static ParseException badAbstract (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("badAbstract", scanner, name); + } + + static ParseException badCustom (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("badCustom", scanner); + } + + // + static ParseException badRepIDAlreadyAssigned (com.sun.tools.corba.ee.idl.Scanner scanner, String entry) + { + return arg1 ("badRepIDAlreadyAssigned", scanner, entry); + } + + // + static ParseException badRepIDForm (com.sun.tools.corba.ee.idl.Scanner scanner, String entry) + { + return arg1 ("badRepIDForm", scanner, entry); + } + + // + static ParseException badRepIDPrefix (com.sun.tools.corba.ee.idl.Scanner scanner, String entry, String expected, String got) + { + return arg3 ("badRepIDPrefix", scanner, entry, expected, got); + } + + static ParseException badState (com.sun.tools.corba.ee.idl.Scanner scanner, String entry) + { + return arg1 ("badState", scanner, entry); + } + + static ParseException branchLabel (com.sun.tools.corba.ee.idl.Scanner scanner, String label) + { + return arg1 ("branchLabel", scanner, label); + } + + static ParseException branchName (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("branchName", scanner, name); + } + + static ParseException duplicateInit (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("duplicateInit", scanner); + } + + static ParseException duplicateState (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("duplicateState", scanner, name); + } + + static ParseException elseNoIf (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("elseNoIf", scanner); + } + + static ParseException endNoIf (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("endNoIf", scanner); + } + + static ParseException evaluationError (com.sun.tools.corba.ee.idl.Scanner scanner, String problem) + { + return arg1 ("evaluation", scanner, problem); + } + + static ParseException forwardEntry (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("forwardEntry", scanner, name); + } + + // Cannot forward value boxes. + static ParseException forwardedValueBox (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("forwardedValueBox", scanner, name); + } + + static ParseException generic (com.sun.tools.corba.ee.idl.Scanner scanner, String message) + { + return arg1 ("generic", scanner, message); + } + + static ParseException illegalArray (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("illegalArray", scanner, name); + } + + static ParseException illegalException (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("illegalException", scanner, name); + } + + static ParseException invalidConst (com.sun.tools.corba.ee.idl.Scanner scanner, String mustBe, String is) + { + return arg2 ("invalidConst1", scanner, mustBe, is); + } + + static ParseException invalidConst (com.sun.tools.corba.ee.idl.Scanner scanner, String type) + { + return arg1 ("invalidConst2", scanner, type); + } + + // Non-escaped identifiers that collide with keywords are illegal. + static ParseException keywordCollision (com.sun.tools.corba.ee.idl.Scanner scanner, String id) + { + return arg1 ("keywordCollision", scanner, id); + } + + // Warning for keywords that will be removed in a future version of IDL. + static ParseException deprecatedKeywordWarning (com.sun.tools.corba.ee.idl.Scanner scanner, String id) + { + return arg1Warning ("deprecatedKeywordWarning", scanner, id); + } + + // Warning for above error. + static ParseException keywordCollisionWarning (com.sun.tools.corba.ee.idl.Scanner scanner, String id) + { + return arg1Warning ("keywordCollisionWarning", scanner, id); + } + + static ParseException methodClash (com.sun.tools.corba.ee.idl.Scanner scanner, String interf, String method) + { + return arg2 ("methodClash", scanner, interf, method); + } + + static ParseException moduleNotType (com.sun.tools.corba.ee.idl.Scanner scanner, String module) + { + return arg1 ("moduleNotType", scanner, module); + } + + // + static ParseException nestedValueBox (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("nestedValueBox", scanner); + } + + static ParseException noDefault (com.sun.tools.corba.ee.idl.Scanner scanner) + { + return arg0 ("noDefault", scanner); + } + + static ParseException nonAbstractParent (com.sun.tools.corba.ee.idl.Scanner scanner, String baseClass, String parentClass) + { + return arg2 ("nonAbstractParent", scanner, baseClass, parentClass); + } + + static ParseException nonAbstractParent2 (com.sun.tools.corba.ee.idl.Scanner scanner, String baseClass, String parentClass) + { + return arg2 ("nonAbstractParent2", scanner, baseClass, parentClass); + } + + static ParseException nonAbstractParent3 (com.sun.tools.corba.ee.idl.Scanner scanner, String baseClass, String parentClass) + { + return arg2 ("nonAbstractParent3", scanner, baseClass, parentClass); + } + + static ParseException notANumber (com.sun.tools.corba.ee.idl.Scanner scanner, String notNumber) + { + return arg1 ("notANumber", scanner, notNumber); + } + + static ParseException nothing (String filename) + { + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException.nothing", filename)); + } + + static ParseException notPositiveInt (com.sun.tools.corba.ee.idl.Scanner scanner, String notPosInt) + { + return arg1 ("notPosInt", scanner, notPosInt); + } + + static ParseException oneway (com.sun.tools.corba.ee.idl.Scanner scanner, String method) + { + return arg1 ("oneway", scanner, method); + } + + // + static ParseException operationNotType (com.sun.tools.corba.ee.idl.Scanner scanner, String op) + { + return arg1 ("operationNotType", scanner, op); + } + + static ParseException outOfRange (com.sun.tools.corba.ee.idl.Scanner scanner, String value, String type) + { + return arg2 ("outOfRange", scanner, value, type); + } + + static ParseException recursive (com.sun.tools.corba.ee.idl.Scanner scanner, String type, String name) + { + return arg2 ("recursive", scanner, type, name); + } + + static ParseException selfInherit (com.sun.tools.corba.ee.idl.Scanner scanner, String name) + { + return arg1 ("selfInherit", scanner, name); + } + + static ParseException stringTooLong (com.sun.tools.corba.ee.idl.Scanner scanner, String str, String max) + { + return arg2 ("stringTooLong", scanner, str, max); + } + + static ParseException syntaxError (com.sun.tools.corba.ee.idl.Scanner scanner, int expected, int got) + { + return arg2 ("syntax1", scanner, Token.toString(expected), Token.toString(got)); + } + + static ParseException syntaxError (com.sun.tools.corba.ee.idl.Scanner scanner, String expected, String got) + { + return arg2 ("syntax1", scanner, expected, got); + } + + static ParseException syntaxError (com.sun.tools.corba.ee.idl.Scanner scanner, int[] expected, int got) + { + return syntaxError (scanner, expected, Token.toString(got)); + } + + static ParseException syntaxError (com.sun.tools.corba.ee.idl.Scanner scanner, int[] expected, String got) + { + String tokenList = ""; + for (int i = 0; i < expected.length; ++i) + tokenList += " `" + Token.toString(expected[i]) + "'"; + return arg2 ("syntax2", scanner, tokenList, got); + } + + static ParseException unclosedComment (String filename) + { + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException.unclosed", filename)); + } + + static ParseException undeclaredType (com.sun.tools.corba.ee.idl.Scanner scanner, String undeclaredType) + { + return arg1 ("undeclaredType", scanner, undeclaredType); + } + + static ParseException warning (com.sun.tools.corba.ee.idl.Scanner scanner, String message) + { + scannerInfo (scanner); + String[] parameters = { filename, Integer.toString (lineNumber), message, line, pointer }; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException.warning", parameters), true); + } + + static ParseException wrongType (com.sun.tools.corba.ee.idl.Scanner scanner, String name, String mustBe, String is) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), name, is, mustBe, line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException.wrongType", parameters)); + } + + static ParseException wrongExprType (com.sun.tools.corba.ee.idl.Scanner scanner, String mustBe, String is) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), + is, mustBe, line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException.constExprType", + parameters)); + } + + static ParseException illegalForwardInheritance( com.sun.tools.corba.ee.idl.Scanner scanner, String declName, + String baseName ) + { + scannerInfo( scanner ) ; + String[] parameters = { filename, Integer.toString(lineNumber), + declName, baseName, line, pointer } ; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage( + "ParseException.forwardInheritance", parameters) ) ; + } + + static ParseException illegalIncompleteTypeReference( com.sun.tools.corba.ee.idl.Scanner scanner, + String declName ) + { + scannerInfo( scanner ) ; + String[] parameters = { filename, Integer.toString(lineNumber), + declName, line, pointer } ; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage( + "ParseException.illegalIncompleteTypeReference", parameters) ) ; + } + + private static void scannerInfo (com.sun.tools.corba.ee.idl.Scanner scanner) + { + filename = scanner.filename (); + line = scanner.lastTokenLine (); + lineNumber = scanner.lastTokenLineNumber (); + int pos = scanner.lastTokenLinePosition (); + pointer = "^"; + if (pos > 1) + { + byte[] bytes = new byte[ pos - 1 ]; + for (int i = 0; i < pos - 1; ++i) + bytes[i] = (byte)' '; // + pointer = new String (bytes) + pointer; + } + } + + private static ParseException arg0 (String msgId, com.sun.tools.corba.ee.idl.Scanner scanner) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException." + msgId, parameters)); + } + + private static ParseException arg1 (String msgId, com.sun.tools.corba.ee.idl.Scanner scanner, String arg1) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), arg1, line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException." + msgId, parameters)); + } + + // + private static ParseException arg1Warning (String msgId, com.sun.tools.corba.ee.idl.Scanner scanner, String arg1) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), arg1, line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException." + msgId, parameters), true); + } + + private static ParseException arg2 (String msgId, com.sun.tools.corba.ee.idl.Scanner scanner, String arg1, String arg2) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), arg1, arg2, line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException." + msgId, parameters)); + } + + private static ParseException arg3 (String msgId, com.sun.tools.corba.ee.idl.Scanner scanner, String arg1, String arg2, String arg3) + { + scannerInfo (scanner); + String[] parameters = {filename, Integer.toString (lineNumber), arg1, arg2, arg3, line, pointer}; + return new ParseException (com.sun.tools.corba.ee.idl.Util.getMessage("ParseException." + msgId, parameters)); + } + + private static String filename = ""; + private static String line = ""; + private static int lineNumber = 0; + private static String pointer = "^"; + + static boolean detected = false; +} // class ParseException diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Parser.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Parser.java new file mode 100644 index 000000000..9d92f602a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Parser.java @@ -0,0 +1,3881 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -F46082.51 Remove -stateful feature. +// -D52042 Allow floating-point constants to be initialized with +// integral as well as floating-point literals. No other variations allowed. +// -D58058 Set index array type to long rather than array element type. +// -D56351 Update computation of RepositoryIDs to CORBA 2.3 (see spec.). +// -D57110 Provide method() to set/clear ability for scoped names to +// resolve to modules. Allows rep. ids to be assigned to modules. +// -D46094 Prohibit exceptions from appearing wihtin structs, unions, exceptions. +// -D46094 Prohibit attributes from appearing as operation parameter types, +// operation return types, attribute types. +// -D59067 Prohibit nested value boxes. +// -D59166 Prohibit collisions between keywords and non-escaped identifiers. +// -D59809 At Pigeonhole(), add map short name of CORBA types to long name +// (e.g., CORBA/StringValue --> org/omg/CORBA/StringValue), which allows fully- +// qualified CORBA type names to resolve successfully. +// -F60858.1 Support "-corba" option, level <= 2.2: issue warning for +// keyowrd collisions; +// -D60942 Prohibit operations from appearing within parameter types. +// -D61643 Repair pigeonhole() to correctly filter bad RepIDs. +// -D62023 Support -noWarn option; Issue warnings when tokens are +// deprecated keywords or keywords in greater release version. +// -D61919 Emit entries for modules originally opened in #include files +// appearing at global scope and then reopened in the main IDL file. Only +// types appearing in the main IDL source will be emitted. + +import java.io.EOFException; +import java.io.IOException; + +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Stack; +import java.util.Vector; +import java.util.List ; +import java.util.ArrayList ; +import java.util.Iterator ; + +import java.math.BigInteger; + +/** + * + **/ +class Parser +{ + /** + * + **/ + Parser (com.sun.tools.corba.ee.idl.Preprocessor preprocessor, com.sun.tools.corba.ee.idl.Arguments arguments, Hashtable overrides, + Hashtable symtab, com.sun.tools.corba.ee.idl.SymtabFactory stFac, com.sun.tools.corba.ee.idl.constExpr.ExprFactory exprFac, String [] genKeywords) + { + this.arguments = arguments; + noWarn = arguments.noWarn; // + corbaLevel = arguments.corbaLevel; // + paths = arguments.includePaths; + symbols = arguments.definedSymbols; + verbose = arguments.verbose; + emitAll = arguments.emitAll; + // + cppModule = arguments.cppModule; + // Remove -stateful feature. + //parseStateful = arguments.parseStateful; + overrideNames = (overrides == null) ? new Hashtable () : overrides; + symbolTable = (symtab == null) ? new Hashtable () : symtab; + keywords = (genKeywords == null) ? new String [0] : genKeywords; + stFactory = stFac; + exprFactory = exprFac; + currentModule = topLevelModule = new com.sun.tools.corba.ee.idl.ModuleEntry(); + prep = preprocessor; + repIDStack.push (new com.sun.tools.corba.ee.idl.IDLID()); + addPrimEntries (); + } // ctor + + /** + * + **/ + void parse (String file) throws IOException + { + IncludeEntry fileEntry = stFactory.includeEntry (); + fileEntry.name ('"' + file + '"'); + try + { + // Set absolute file path + fileEntry.absFilename (com.sun.tools.corba.ee.idl.Util.getAbsolutePath(file, paths)); + } + catch (IOException ioe) + {} + + // Remove -stateful feature. + //scanner = new Scanner (fileEntry, keywords, verbose, parseStateful, emitAll); + // Support "-corba [level]" option. + //scanner = new Scanner (fileEntry, keywords, verbose, emitAll); + scanner = new com.sun.tools.corba.ee.idl.Scanner(fileEntry, keywords, verbose, emitAll, corbaLevel, + arguments.scannerDebugFlag ); + topLevelModule.sourceFile (fileEntry); + + // Prime the pump... + // Match handles preprocessor directives, so use match to + // call scanner.getToken just in case the first token is + // such a directive. But match depends on the token + // already having a value, so fudge something. + token = new com.sun.tools.corba.ee.idl.Token(0); + tokenHistory.insert (token); // Initialize look back buffer <26jul1997daz>. + try + { + match (0); + if (token.equals (com.sun.tools.corba.ee.idl.Token.EOF)) + com.sun.tools.corba.ee.idl.ParseException.nothing(file); + else + specification (topLevelModule); + } + catch (com.sun.tools.corba.ee.idl.ParseException exception) // Match MIGHT throw this + { + // It has already been reported, just end. + } + catch (EOFException exception) // skipToSemicolon MIGHT throw this + { + // It has already been reported, just end. + } + } // parse + + /** + * + **/ + private void addPrimEntries () + { + symbolTable.put ("short", stFactory.primitiveEntry ("short")); + symbolTable.put ("long", stFactory.primitiveEntry ("long")); + symbolTable.put ("long long", stFactory.primitiveEntry ("long long")); + symbolTable.put ("unsigned short", stFactory.primitiveEntry ("unsigned short")); + symbolTable.put ("unsigned long", stFactory.primitiveEntry ("unsigned long")); + symbolTable.put ("unsigned long long", stFactory.primitiveEntry ("unsigned long long")); + symbolTable.put ("char", stFactory.primitiveEntry ("char")); + symbolTable.put ("wchar", stFactory.primitiveEntry ("wchar")); + symbolTable.put ("float", stFactory.primitiveEntry ("float")); + //Support fixed type: symbolTable.put ("fixed", stFactory.primitiveEntry ("fixed")); + symbolTable.put ("double", stFactory.primitiveEntry ("double")); + symbolTable.put ("boolean", stFactory.primitiveEntry ("boolean")); + symbolTable.put ("octet", stFactory.primitiveEntry ("octet")); + symbolTable.put ("any", stFactory.primitiveEntry ("any")); + + com.sun.tools.corba.ee.idl.InterfaceEntry object = stFactory.interfaceEntry(); + object.name ("Object"); + symbolTable.put ("Object", object); + + com.sun.tools.corba.ee.idl.ValueEntry valueBase = stFactory.valueEntry(); + valueBase.name ("ValueBase"); + symbolTable.put ("ValueBase", valueBase); + + // put these same entries in the lowercase symbol table + lcSymbolTable.put ("short", stFactory.primitiveEntry ("short")); + lcSymbolTable.put ("long", stFactory.primitiveEntry ("long")); + lcSymbolTable.put ("long long", stFactory.primitiveEntry ("long long")); + lcSymbolTable.put ("unsigned short", stFactory.primitiveEntry ("unsigned short")); + lcSymbolTable.put ("unsigned long", stFactory.primitiveEntry ("unsigned long")); + lcSymbolTable.put ("unsigned long long", stFactory.primitiveEntry ("unsigned long long")); + lcSymbolTable.put ("char", stFactory.primitiveEntry ("char")); + lcSymbolTable.put ("wchar", stFactory.primitiveEntry ("wchar")); + lcSymbolTable.put ("float", stFactory.primitiveEntry ("float")); + // Support fixed type: lcSymbolTable.put ("fixed", stFactory.primitiveEntry ("fixed")); + lcSymbolTable.put ("double", stFactory.primitiveEntry ("double")); + lcSymbolTable.put ("boolean", stFactory.primitiveEntry ("boolean")); + lcSymbolTable.put ("octet", stFactory.primitiveEntry ("octet")); + lcSymbolTable.put ("any", stFactory.primitiveEntry ("any")); + lcSymbolTable.put ("object", object); + lcSymbolTable.put ("valuebase", valueBase); + } // addPrimEntries + + /** + * + **/ + private void specification (com.sun.tools.corba.ee.idl.ModuleEntry entry) throws IOException + { + while (!token.equals (com.sun.tools.corba.ee.idl.Token.EOF)) + { + definition (entry); + addToEmitList (entry); + } + } // specification + + // ModuleEntry is the topLevelModule; add its contained types to the emit list. + /** + * + **/ + private void addToEmitList (com.sun.tools.corba.ee.idl.ModuleEntry entry) + { + for (Enumeration e = entry.contained ().elements (); e.hasMoreElements();) + { + com.sun.tools.corba.ee.idl.SymtabEntry emitEntry = (com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement (); + if (emitEntry.emit ()) + { + emitList.addElement (emitEntry); + + // I think the absence of the following statement was an + // oversight. If module X.Y.Z first appears in an include file, then is + // reopened in the main IDL source, this statement guarantees that X.Y.Z + // definitions within the main IDL source are emitted. + ///--------------------------------------------------------------------- + // If any of this module's elements should be emitted, add + // this module to the emit list. + if (emitEntry instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + checkContained ((com.sun.tools.corba.ee.idl.ModuleEntry)emitEntry); + if (emitEntry instanceof IncludeEntry) + { + includes.addElement (emitEntry.name ()); + includeEntries.addElement (emitEntry); + } + } + else + // If any of this module's elements should be emitted, add + // this module to the emit list. + if (emitEntry instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + checkContained ((com.sun.tools.corba.ee.idl.ModuleEntry)emitEntry); + } + entry.contained ().removeAllElements (); + } // addToEmitList + + /** + * + **/ + private void checkContained (com.sun.tools.corba.ee.idl.ModuleEntry entry) + { + // If any of this module's elements is to be emitted, + // then add the module to the emit list. + for (Enumeration e = entry.contained ().elements (); e.hasMoreElements ();) + { + com.sun.tools.corba.ee.idl.SymtabEntry contained = (com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement (); + if (contained instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + checkContained ((com.sun.tools.corba.ee.idl.ModuleEntry)contained); + if (contained.emit ()) + { + if (!emitList.contains (entry)) + emitList.addElement (entry); + entry.emit (true); + break; + } + } + } // checkContained + + /** + * + **/ + private void definition (com.sun.tools.corba.ee.idl.ModuleEntry entry) throws IOException + { + try + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Typedef: + case com.sun.tools.corba.ee.idl.Token.Struct: + case com.sun.tools.corba.ee.idl.Token.Union: + case com.sun.tools.corba.ee.idl.Token.Enum: + typeDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Const: + constDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Native: + nativeDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Exception: + exceptDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Interface: + interfaceProd (entry, com.sun.tools.corba.ee.idl.InterfaceEntry.NORMAL); + break; + case com.sun.tools.corba.ee.idl.Token.Local: + match( com.sun.tools.corba.ee.idl.Token.Local ) ; + if (token.type == com.sun.tools.corba.ee.idl.Token.Interface) + interfaceProd( entry, com.sun.tools.corba.ee.idl.InterfaceEntry.LOCAL ) ; + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Interface}, token.type) ; + break ; + case com.sun.tools.corba.ee.idl.Token.Module: + module (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Abstract: + match (com.sun.tools.corba.ee.idl.Token.Abstract); + if (token.type == com.sun.tools.corba.ee.idl.Token.Interface) + interfaceProd (entry, com.sun.tools.corba.ee.idl.InterfaceEntry.ABSTRACT); + else if (token.type == com.sun.tools.corba.ee.idl.Token.Valuetype) + valueProd (entry, true); + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Interface, com.sun.tools.corba.ee.idl.Token.Valuetype}, token.type); + break; + case com.sun.tools.corba.ee.idl.Token.Custom: + case com.sun.tools.corba.ee.idl.Token.Valuetype: + valueProd (entry, false); + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Typedef, com.sun.tools.corba.ee.idl.Token.Struct, com.sun.tools.corba.ee.idl.Token.Union, com.sun.tools.corba.ee.idl.Token.Enum, + com.sun.tools.corba.ee.idl.Token.Const, com.sun.tools.corba.ee.idl.Token.Exception, com.sun.tools.corba.ee.idl.Token.Interface, com.sun.tools.corba.ee.idl.Token.Valuetype, + com.sun.tools.corba.ee.idl.Token.Module}, token.type); + } + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + } + catch (com.sun.tools.corba.ee.idl.ParseException e) + { + skipToSemicolon (); + } + } // definition + + /** + * + **/ + private void module (com.sun.tools.corba.ee.idl.ModuleEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Module); + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + com.sun.tools.corba.ee.idl.ModuleEntry newEntry = newModule (entry); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (newEntry.name ()); + // comment must immediately precede "module" keyword + newEntry.comment (tokenHistory.lookBack (1).comment); + currentModule = newEntry; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + prep.openScope (newEntry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace); + definition (newEntry); + while (!token.equals (com.sun.tools.corba.ee.idl.Token.EOF) && !token.equals (com.sun.tools.corba.ee.idl.Token.RightBrace)) + definition (newEntry); + prep.closeScope (newEntry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace); + currentModule = entry; + repIDStack.pop (); + } // module + + /** + * + **/ + private void interfaceProd (com.sun.tools.corba.ee.idl.ModuleEntry entry, int interfaceType) + throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Interface); + String name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + interface2 (entry, name, interfaceType); + } // interfaceProd + + /** + * + **/ + private void interface2 (com.sun.tools.corba.ee.idl.ModuleEntry module, String name, int interfaceType) + throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type == com.sun.tools.corba.ee.idl.Token.Colon || token.type == com.sun.tools.corba.ee.idl.Token.LeftBrace) { + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + com.sun.tools.corba.ee.idl.InterfaceEntry entry = stFactory.interfaceEntry (module, + (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (name); + entry.setInterfaceType(interfaceType); + // Comment must immediately precede "[local | abstract] interface" keyword + entry.comment (tokenHistory.lookBack ( + entry.getInterfaceType() == com.sun.tools.corba.ee.idl.InterfaceEntry.NORMAL ? 2 : 3).comment); + + if (!com.sun.tools.corba.ee.idl.ForwardEntry.replaceForwardDecl(entry)) + com.sun.tools.corba.ee.idl.ParseException.badAbstract(scanner, entry.fullName()); + pigeonhole (module, entry); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (name); + currentModule = entry; + interfaceDcl (entry); + currentModule = module; + repIDStack.pop (); + } else { // This is a forward declaration + com.sun.tools.corba.ee.idl.ForwardEntry entry = stFactory.forwardEntry (module, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (name); + entry.setInterfaceType(interfaceType); + // comment must immediately precede "interface" keyword. + entry.comment (tokenHistory.lookBack ( + entry.getInterfaceType() == com.sun.tools.corba.ee.idl.InterfaceEntry.NORMAL ? 2 : 3).comment); + pigeonhole (module, entry); + } + } // interface2 + + /** + * + **/ + private void interfaceDcl (com.sun.tools.corba.ee.idl.InterfaceEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type != com.sun.tools.corba.ee.idl.Token.LeftBrace) + inheritanceSpec (entry); + else if (!entry.isAbstract ()) { + com.sun.tools.corba.ee.idl.SymtabEntry objectEntry = qualifiedEntry ("Object"); + com.sun.tools.corba.ee.idl.SymtabEntry realOEntry = typeOf (objectEntry); + if (objectEntry == null) + ; // qualifiedEntry already generated an error message + else if (!isInterface(realOEntry)) + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, overrideName("Object"), + "interface", objectEntry.typeName()); + else + entry.derivedFromAddElement (realOEntry, scanner); + } + + prep.openScope (entry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace); + while (token.type != com.sun.tools.corba.ee.idl.Token.RightBrace) + export (entry); + prep.closeScope (entry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace); + } // interfaceDcl + + /** + * + **/ + private void export (com.sun.tools.corba.ee.idl.InterfaceEntry entry) throws IOException + { + try + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Typedef: + case com.sun.tools.corba.ee.idl.Token.Struct: + case com.sun.tools.corba.ee.idl.Token.Union: + case com.sun.tools.corba.ee.idl.Token.Enum: + typeDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Const: + constDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Native: + nativeDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Exception: + exceptDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Readonly: + case com.sun.tools.corba.ee.idl.Token.Attribute: + attrDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Oneway: + case com.sun.tools.corba.ee.idl.Token.Float: + case com.sun.tools.corba.ee.idl.Token.Double: + case com.sun.tools.corba.ee.idl.Token.Long: + case com.sun.tools.corba.ee.idl.Token.Short: + case com.sun.tools.corba.ee.idl.Token.Unsigned: + case com.sun.tools.corba.ee.idl.Token.Char: + case com.sun.tools.corba.ee.idl.Token.Wchar: + case com.sun.tools.corba.ee.idl.Token.Boolean: + case com.sun.tools.corba.ee.idl.Token.Octet: + case com.sun.tools.corba.ee.idl.Token.Any: + case com.sun.tools.corba.ee.idl.Token.String: + case com.sun.tools.corba.ee.idl.Token.Wstring: + case com.sun.tools.corba.ee.idl.Token.Identifier: + case com.sun.tools.corba.ee.idl.Token.Object: + // Value base type. + case com.sun.tools.corba.ee.idl.Token.ValueBase: + case com.sun.tools.corba.ee.idl.Token.DoubleColon: + case com.sun.tools.corba.ee.idl.Token.Void: + opDcl (entry); + break; + // Remove -stateful feature. + //case Token.State: if (parseStateful) { + // stateDef (entry); + // break; } + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Typedef, com.sun.tools.corba.ee.idl.Token.Struct, com.sun.tools.corba.ee.idl.Token.Union, com.sun.tools.corba.ee.idl.Token.Enum, + com.sun.tools.corba.ee.idl.Token.Const, com.sun.tools.corba.ee.idl.Token.Exception, com.sun.tools.corba.ee.idl.Token.Readonly, com.sun.tools.corba.ee.idl.Token.Attribute, + com.sun.tools.corba.ee.idl.Token.Oneway, com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double, com.sun.tools.corba.ee.idl.Token.Long, + com.sun.tools.corba.ee.idl.Token.Short, com.sun.tools.corba.ee.idl.Token.Unsigned, com.sun.tools.corba.ee.idl.Token.Char, com.sun.tools.corba.ee.idl.Token.Wchar, + com.sun.tools.corba.ee.idl.Token.Boolean, com.sun.tools.corba.ee.idl.Token.Octet, com.sun.tools.corba.ee.idl.Token.Any, com.sun.tools.corba.ee.idl.Token.String, + com.sun.tools.corba.ee.idl.Token.Wstring, com.sun.tools.corba.ee.idl.Token.Identifier, com.sun.tools.corba.ee.idl.Token.DoubleColon, com.sun.tools.corba.ee.idl.Token.Void, + com.sun.tools.corba.ee.idl.Token.ValueBase}, token.type); + } + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + } + catch (com.sun.tools.corba.ee.idl.ParseException exception) + { + skipToSemicolon (); + } + } // export + + private void inheritanceSpec (com.sun.tools.corba.ee.idl.InterfaceEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + for (match (com.sun.tools.corba.ee.idl.Token.Colon); ; match (com.sun.tools.corba.ee.idl.Token.Comma)) { + com.sun.tools.corba.ee.idl.SymtabEntry parent = scopedName (entry.container (), + stFactory.interfaceEntry ()); + com.sun.tools.corba.ee.idl.SymtabEntry realParent = typeOf (parent); + + if (isInterfaceOnly (realParent)) { + boolean isInterface = (realParent instanceof com.sun.tools.corba.ee.idl.InterfaceEntry); + if (entry.derivedFrom ().contains (realParent)) + com.sun.tools.corba.ee.idl.ParseException.alreadyDerived(scanner, realParent.fullName(), entry.fullName()); + else if (!entry.isAbstract () || + (((com.sun.tools.corba.ee.idl.InterfaceType)realParent).getInterfaceType() == com.sun.tools.corba.ee.idl.InterfaceType.ABSTRACT)) + entry.derivedFromAddElement (realParent, scanner); + else + com.sun.tools.corba.ee.idl.ParseException.nonAbstractParent(scanner, entry.fullName(), parent.fullName()); + } else if (isForward( realParent )) { + com.sun.tools.corba.ee.idl.ParseException.illegalForwardInheritance(scanner, + entry.fullName(), parent.fullName()) ; + } else + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, parent.fullName(), "interface", entryName(parent)); + + if ((parent instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) && (((com.sun.tools.corba.ee.idl.InterfaceEntry)parent).state () != null)) + if (entry.state () == null) + entry.initState (); + else + throw com.sun.tools.corba.ee.idl.ParseException.badState(scanner, entry.fullName()); + + if (token.type != com.sun.tools.corba.ee.idl.Token.Comma) + break; + } + } // inheritanceSpec + + // <57110> Member _moduleIsLegalType may be set by any feature to allow + // method scopedName() and any of its helper methods -- qualifiedName(), + // partlyQualifiedName(), and unqualifiedName() -- to return a ModuleEntry + // rather than a parse error in the event a name resolves to a module. The + // flag must be cleared (set to false) to resume normal parsing behavior. + // + // Currently, this is used only when preprocessing the ID pragma directive. + + private boolean _isModuleLegalType = false; + + /** + * + **/ + public boolean isModuleLegalType () + { + return _isModuleLegalType; + }; // moduleIsLegaType + + /** + * + **/ + public void isModuleLegalType (boolean b) + { + _isModuleLegalType = b; + }; // moduleIsLegalType + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry scopedName (com.sun.tools.corba.ee.idl.SymtabEntry container, + com.sun.tools.corba.ee.idl.SymtabEntry expected) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + return scopedName( container, expected, true ) ; + } + + com.sun.tools.corba.ee.idl.SymtabEntry scopedName (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.SymtabEntry expected, + boolean mustBeReferencable ) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + boolean globalScope = false; + boolean partialScope = false; + String name = null; + if (token.type == com.sun.tools.corba.ee.idl.Token.DoubleColon) + globalScope = true; + else + { + if (token.type == com.sun.tools.corba.ee.idl.Token.Object) + { + name = "Object"; + match (com.sun.tools.corba.ee.idl.Token.Object); + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.ValueBase) // + { + name = "ValueBase"; + match (com.sun.tools.corba.ee.idl.Token.ValueBase); + } + else + { + name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + } + while (token.type == com.sun.tools.corba.ee.idl.Token.DoubleColon) + { + match (com.sun.tools.corba.ee.idl.Token.DoubleColon); + partialScope = true; + if (name != null) + name += '/' + token.name; + else name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + com.sun.tools.corba.ee.idl.SymtabEntry entry = null; + if (globalScope) + entry = qualifiedEntry (name); + else if (partialScope) + entry = partlyQualifiedEntry (name, container); + else + entry = unqualifiedEntry (name, container); + + if (entry == null) + // Make the entry the expected entry. The generators will + // not be called now, since a semantic exception ocurred, but + // the parse has to finish and something valid has to be + // returned. + (entry = expected).name (name); + else if (!entry.isReferencable() && mustBeReferencable) + throw com.sun.tools.corba.ee.idl.ParseException.illegalIncompleteTypeReference(scanner, name) ; + + return entry; + } // scopedName + + private void valueProd (com.sun.tools.corba.ee.idl.ModuleEntry entry, boolean isAbstract) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + boolean isCustom = (token.type == com.sun.tools.corba.ee.idl.Token.Custom); + if (isCustom) + match (com.sun.tools.corba.ee.idl.Token.Custom); + match (com.sun.tools.corba.ee.idl.Token.Valuetype); + String name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.LeftBrace: + case com.sun.tools.corba.ee.idl.Token.Colon: + case com.sun.tools.corba.ee.idl.Token.Supports: + value2 (entry, name, isAbstract, isCustom); + return; + case com.sun.tools.corba.ee.idl.Token.Semicolon: + if (isCustom) + break; + valueForwardDcl (entry, name, isAbstract); + return; + } + if (isCustom) + throw com.sun.tools.corba.ee.idl.ParseException.badCustom(scanner); + if (isAbstract) + throw com.sun.tools.corba.ee.idl.ParseException.abstractValueBox(scanner); + valueBox (entry, name); + } // valueProd + + /** + * + **/ + private void value2 (com.sun.tools.corba.ee.idl.ModuleEntry module, String name, boolean isAbstract, + boolean isCustom) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + // The 'actual' repository ID will be calculated at the end of the + // parsing phase, since it is based on the entire contents of the + // declaration, and needs to have all forward references resolved: + com.sun.tools.corba.ee.idl.ValueEntry entry = stFactory.valueEntry (module, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (name); + entry.setInterfaceType (isAbstract ? com.sun.tools.corba.ee.idl.InterfaceType.ABSTRACT : com.sun.tools.corba.ee.idl.InterfaceType.NORMAL); + entry.setCustom (isCustom); + // Comment must immediately precede "[abstract | custom] value" keyword + entry.comment (tokenHistory.lookBack ((isAbstract || isCustom) ? 3 : 2).comment); + // If this value has been forward declared, there are probably + // other values which derive from a ForwardValueEntry. Replace + // those ForwardValueEntry's with this ValueEntry: + if (!com.sun.tools.corba.ee.idl.ForwardEntry.replaceForwardDecl(entry)) + com.sun.tools.corba.ee.idl.ParseException.badAbstract(scanner, entry.fullName()); + pigeonhole (module, entry); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (name); + currentModule = entry; + valueDcl (entry); + entry.tagMethods (); + currentModule = module; + repIDStack.pop (); + } // value2 + + /** + * + **/ + private void valueDcl (com.sun.tools.corba.ee.idl.ValueEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type == com.sun.tools.corba.ee.idl.Token.Colon) + valueInheritanceSpec (entry); + else if (!entry.isAbstract ()) + { + com.sun.tools.corba.ee.idl.SymtabEntry objectEntry = qualifiedEntry ("ValueBase"); + com.sun.tools.corba.ee.idl.SymtabEntry realOEntry = typeOf (objectEntry); + if (objectEntry == null) + ; // qualifiedEntry already generated an error message + else if (!isValue (realOEntry)) + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, overrideName("ValueBase"), "value", objectEntry.typeName()); + else + entry.derivedFromAddElement (realOEntry, false, scanner); + } + if (token.type == com.sun.tools.corba.ee.idl.Token.Supports) + valueSupportsSpec (entry); + prep.openScope (entry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace); + while (token.type != com.sun.tools.corba.ee.idl.Token.RightBrace) + { + valueElement (entry); + } + prep.closeScope (entry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace); + } // valueDcl + + /** + * + **/ + private void valueInheritanceSpec (com.sun.tools.corba.ee.idl.ValueEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Colon); + boolean isTruncatable = (token.type == com.sun.tools.corba.ee.idl.Token.Truncatable); + if (isTruncatable) + match (com.sun.tools.corba.ee.idl.Token.Truncatable); + for (; ; match (com.sun.tools.corba.ee.idl.Token.Comma), isTruncatable = false) { + com.sun.tools.corba.ee.idl.SymtabEntry parent = scopedName (entry.container (), + stFactory.valueEntry ()); + com.sun.tools.corba.ee.idl.SymtabEntry realParent = typeOf (parent); + if (isValue (realParent) && !(realParent instanceof com.sun.tools.corba.ee.idl.ValueBoxEntry)) + entry.derivedFromAddElement (realParent, isTruncatable, + scanner); + else if (isForward(realParent)) + com.sun.tools.corba.ee.idl.ParseException.illegalForwardInheritance(scanner, + entry.fullName(), parent.fullName()) ; + else + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, + parent.fullName(), "value", entryName(parent)); + if (token.type != com.sun.tools.corba.ee.idl.Token.Comma) + break; + } + } // valueInheritanceSpec + + /** + * + **/ + private void valueSupportsSpec (com.sun.tools.corba.ee.idl.ValueEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Supports) ; + for (; ; match( com.sun.tools.corba.ee.idl.Token.Comma ) ) { + com.sun.tools.corba.ee.idl.SymtabEntry parent = scopedName (entry.container (), stFactory.interfaceEntry ()); + com.sun.tools.corba.ee.idl.SymtabEntry realParent = typeOf (parent); + if (isInterface(realParent)) + entry.derivedFromAddElement (realParent, scanner); + else + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, parent.fullName(), "interface", + entryName(parent)); + + if (token.type != com.sun.tools.corba.ee.idl.Token.Comma) + break; + } + } // valueSupportsSpec + + private void valueElement (com.sun.tools.corba.ee.idl.ValueEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (entry.isAbstract ()) + export (entry); + else + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Private: + case com.sun.tools.corba.ee.idl.Token.Public: + valueStateMember (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Init: + case com.sun.tools.corba.ee.idl.Token.Factory: // "factory" supplants "init" in 2.4RTF + initDcl (entry); + break; + case com.sun.tools.corba.ee.idl.Token.Typedef: + case com.sun.tools.corba.ee.idl.Token.Struct: + case com.sun.tools.corba.ee.idl.Token.Union: + case com.sun.tools.corba.ee.idl.Token.Enum: + case com.sun.tools.corba.ee.idl.Token.Const: + case com.sun.tools.corba.ee.idl.Token.Native: + case com.sun.tools.corba.ee.idl.Token.Exception: + case com.sun.tools.corba.ee.idl.Token.Readonly: + case com.sun.tools.corba.ee.idl.Token.Attribute: + case com.sun.tools.corba.ee.idl.Token.Oneway: + case com.sun.tools.corba.ee.idl.Token.Float: + case com.sun.tools.corba.ee.idl.Token.Double: + case com.sun.tools.corba.ee.idl.Token.Long: + case com.sun.tools.corba.ee.idl.Token.Short: + case com.sun.tools.corba.ee.idl.Token.Unsigned: + case com.sun.tools.corba.ee.idl.Token.Char: + case com.sun.tools.corba.ee.idl.Token.Wchar: + case com.sun.tools.corba.ee.idl.Token.Boolean: + case com.sun.tools.corba.ee.idl.Token.Octet: + case com.sun.tools.corba.ee.idl.Token.Any: + case com.sun.tools.corba.ee.idl.Token.String: + case com.sun.tools.corba.ee.idl.Token.Wstring: + case com.sun.tools.corba.ee.idl.Token.Identifier: + case com.sun.tools.corba.ee.idl.Token.Object: + case com.sun.tools.corba.ee.idl.Token.ValueBase: + case com.sun.tools.corba.ee.idl.Token.DoubleColon: + case com.sun.tools.corba.ee.idl.Token.Void: + export (entry); + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Private, com.sun.tools.corba.ee.idl.Token.Public, com.sun.tools.corba.ee.idl.Token.Init, com.sun.tools.corba.ee.idl.Token.ValueBase, + com.sun.tools.corba.ee.idl.Token.Typedef, com.sun.tools.corba.ee.idl.Token.Struct, com.sun.tools.corba.ee.idl.Token.Union, com.sun.tools.corba.ee.idl.Token.Enum, + com.sun.tools.corba.ee.idl.Token.Const, com.sun.tools.corba.ee.idl.Token.Exception, com.sun.tools.corba.ee.idl.Token.Readonly, com.sun.tools.corba.ee.idl.Token.Attribute, + com.sun.tools.corba.ee.idl.Token.Oneway, com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double, com.sun.tools.corba.ee.idl.Token.Long, + com.sun.tools.corba.ee.idl.Token.Short, com.sun.tools.corba.ee.idl.Token.Unsigned, com.sun.tools.corba.ee.idl.Token.Char, com.sun.tools.corba.ee.idl.Token.Wchar, + com.sun.tools.corba.ee.idl.Token.Boolean, com.sun.tools.corba.ee.idl.Token.Octet, com.sun.tools.corba.ee.idl.Token.Any, com.sun.tools.corba.ee.idl.Token.String, + com.sun.tools.corba.ee.idl.Token.Wstring, com.sun.tools.corba.ee.idl.Token.Identifier, com.sun.tools.corba.ee.idl.Token.DoubleColon, com.sun.tools.corba.ee.idl.Token.Void}, + token.type); + } // switch + } // valueElement + + // + /** + * + **/ + private void valueStateMember (com.sun.tools.corba.ee.idl.ValueEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry = + stFactory.typedefEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + typedefEntry.sourceFile (scanner.fileEntry ()); + // comment must immediately precede "public", "private" keywords + typedefEntry.comment (token.comment); + boolean isPublic = (token.type == com.sun.tools.corba.ee.idl.Token.Public); + if (isPublic) + match (com.sun.tools.corba.ee.idl.Token.Public); + else + match (com.sun.tools.corba.ee.idl.Token.Private); + // Add constructed types declared "inline" to the contained + // vector of this value entry. + boolean isConstTypeSpec = + (token.type == com.sun.tools.corba.ee.idl.Token.Struct || token.type == com.sun.tools.corba.ee.idl.Token.Union || token.type == com.sun.tools.corba.ee.idl.Token.Enum); + // Make typedefEntry anonymous. If this line is removed, + // the entry will be named incorrectly. See . + typedefEntry.name (""); + typedefEntry.type (typeSpec (typedefEntry)); + addDeclarators (entry, typedefEntry, isPublic); + // + if (isConstTypeSpec) + entry.addContained (typedefEntry); + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + } // valueStateMember + + + private void addDeclarators (com.sun.tools.corba.ee.idl.ValueEntry entry, com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry, + boolean isPublic) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + int modifier = isPublic ? com.sun.tools.corba.ee.idl.InterfaceState.Public : com.sun.tools.corba.ee.idl.InterfaceState.Private; + try + { + Vector typedefList = new Vector (); + declarators (typedefEntry, typedefList); + for (Enumeration e = typedefList.elements (); e.hasMoreElements ();) + entry.addStateElement ( + new com.sun.tools.corba.ee.idl.InterfaceState(modifier, (com.sun.tools.corba.ee.idl.TypedefEntry)e.nextElement ()), scanner); + } + catch (com.sun.tools.corba.ee.idl.ParseException exception) + { + skipToSemicolon (); + } + } // addDeclarators + + /** + * + **/ + private void initDcl (com.sun.tools.corba.ee.idl.ValueEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.MethodEntry method = stFactory.methodEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + method.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede "init" keyword: + method.comment (token.comment); + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (token.name); + + // In 2.3 prelim, ::= "init" "(" ... + if (token.type == com.sun.tools.corba.ee.idl.Token.Init) + { + method.name ("init"); + match (com.sun.tools.corba.ee.idl.Token.Init); + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + } + else // In 2.4rtf, ::= "factory" "(" ... + { + match (com.sun.tools.corba.ee.idl.Token.Factory); + method.name (token.name); + if (token.type == com.sun.tools.corba.ee.idl.Token.MacroIdentifier) + match (com.sun.tools.corba.ee.idl.Token.MacroIdentifier); // "(" already consumed. + else + { + match (com.sun.tools.corba.ee.idl.Token.Identifier); + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + } + } + + if (token.type != com.sun.tools.corba.ee.idl.Token.RightParen) + for (;;) + { + initParamDcl (method); + if (token.type == com.sun.tools.corba.ee.idl.Token.RightParen) + break; + match (com.sun.tools.corba.ee.idl.Token.Comma); + } + entry.initializersAddElement (method, scanner); + match (com.sun.tools.corba.ee.idl.Token.RightParen); + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + repIDStack.pop (); + } // initDcl + + /** + * + **/ + private void initParamDcl (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.ParameterEntry parmEntry = stFactory.parameterEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + parmEntry.sourceFile (scanner.fileEntry()); + // Comment must immediately precede parameter attribute + parmEntry.comment (token.comment); + match (com.sun.tools.corba.ee.idl.Token.In); + parmEntry.passType (com.sun.tools.corba.ee.idl.ParameterEntry.In); + parmEntry.type (paramTypeSpec (entry)); + parmEntry.name (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + if (isntInList (entry.parameters (), parmEntry.name ())) + entry.addParameter (parmEntry); + } // initParamDcl + + /** + * + **/ + private void valueBox (com.sun.tools.corba.ee.idl.ModuleEntry module, String name) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + // Note: The 'actual' repository ID will be calculated at the end of + // the parsing phase, since it is based on the entire contents of the + // declaration, and needs to have all forward references resolved: + com.sun.tools.corba.ee.idl.ValueEntry entry = stFactory.valueBoxEntry (module, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (name); + // comment must immediately precede "value" keyword + entry.comment (tokenHistory.lookBack (2).comment); + // Value boxes may not be forwarded. + // If this value has been forward declared, there are probably + // other values which derive from a ForwardValueEntry. + // Replace those ForwardValueEntry's with this ValueEntry: + //if (!ForwardValueEntry.replaceForwardDecl (entry)) + // ParseException.badAbstract (scanner, entry.fullName()); + com.sun.tools.corba.ee.idl.SymtabEntry valueForward = (com.sun.tools.corba.ee.idl.SymtabEntry)Parser.symbolTable.get (entry.fullName ()); + if (valueForward != null && valueForward instanceof com.sun.tools.corba.ee.idl.ForwardEntry) + com.sun.tools.corba.ee.idl.ParseException.forwardedValueBox(scanner, entry.fullName()); + pigeonhole (module, entry); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (name); + currentModule = entry; + com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry = stFactory.typedefEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + typedefEntry.sourceFile (scanner.fileEntry ()); + typedefEntry.comment (token.comment); + // Workaround to place typedefEntry in the _contained vector of + // this value box entry ONLY when is a constructed type declared + // at this point (i.e., not an identifier that resolves to a constructed + // type), so that emitters may generate bindings for it. + boolean isConstTypeSpec = + token.type == com.sun.tools.corba.ee.idl.Token.Struct || token.type == com.sun.tools.corba.ee.idl.Token.Union || token.type == com.sun.tools.corba.ee.idl.Token.Enum; + // Make typedefEntry anonymous. If this line is removed, the + // entry will be named incorrectly. + typedefEntry.name (""); + typedefEntry.type (typeSpec (typedefEntry)); + // Value boxes cannot be nested. + if (typedefEntry.type () instanceof com.sun.tools.corba.ee.idl.ValueBoxEntry) + com.sun.tools.corba.ee.idl.ParseException.nestedValueBox(scanner); + //typedefEntry.name (""); + entry.addStateElement (new com.sun.tools.corba.ee.idl.InterfaceState(com.sun.tools.corba.ee.idl.InterfaceState.Public, typedefEntry), scanner); + if (isConstTypeSpec) + entry.addContained (typedefEntry); + currentModule = module; + repIDStack.pop (); + } // valueBox + + /** + * + **/ + private void valueForwardDcl (com.sun.tools.corba.ee.idl.ModuleEntry module, String name, boolean isAbstract) + throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.ForwardValueEntry entry = stFactory.forwardValueEntry (module, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (name); + entry.setInterfaceType(isAbstract ? com.sun.tools.corba.ee.idl.InterfaceType.ABSTRACT : com.sun.tools.corba.ee.idl.InterfaceType.NORMAL ); + // Comment must immediately precede "[abstract] value" keyword[s] + entry.comment (tokenHistory.lookBack (isAbstract? 3 : 2).comment); + pigeonhole (module, entry); + } // valueForwardDcl + + private void nativeDcl (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Native); + com.sun.tools.corba.ee.idl.NativeEntry nativeEntry = stFactory.nativeEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + nativeEntry.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede "native" keyword + nativeEntry.comment (tokenHistory.lookBack (1).comment); + nativeEntry.name (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + pigeonhole (entry, nativeEntry); + } // nativeDcl + /** + * + **/ + private void constDcl (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Const); + com.sun.tools.corba.ee.idl.ConstEntry constEntry = stFactory.constEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + constEntry.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede "const" keyword + constEntry.comment (tokenHistory.lookBack (1).comment); + constType (constEntry); + constEntry.name (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + match (com.sun.tools.corba.ee.idl.Token.Equal); + constEntry.value (constExp (constEntry)); + verifyConstType (constEntry.value (), typeOf (constEntry.type ())); + pigeonhole (entry, constEntry); + } // constDcl + + /** + * + **/ + private void constType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Octet: + entry.type( octetType()) ; + break ; + case com.sun.tools.corba.ee.idl.Token.Long: + case com.sun.tools.corba.ee.idl.Token.Short: + case com.sun.tools.corba.ee.idl.Token.Unsigned: + entry.type (integerType (entry)); + break; + case com.sun.tools.corba.ee.idl.Token.Char: + case com.sun.tools.corba.ee.idl.Token.Wchar: + entry.type (charType ()); + break; + case com.sun.tools.corba.ee.idl.Token.Boolean: + entry.type (booleanType ()); + break; + case com.sun.tools.corba.ee.idl.Token.Float: + case com.sun.tools.corba.ee.idl.Token.Double: + entry.type (floatingPtType ()); + break; + case com.sun.tools.corba.ee.idl.Token.String: + case com.sun.tools.corba.ee.idl.Token.Wstring: + entry.type (stringType (entry)); + break; + case com.sun.tools.corba.ee.idl.Token.Identifier: + case com.sun.tools.corba.ee.idl.Token.DoubleColon: + entry.type (scopedName (entry.container (), stFactory.primitiveEntry ())); + if (hasArrayInfo (entry.type ())) + com.sun.tools.corba.ee.idl.ParseException.illegalArray(scanner, "const"); + com.sun.tools.corba.ee.idl.SymtabEntry entryType = typeOf (entry.type ()); + if (!((entryType instanceof com.sun.tools.corba.ee.idl.PrimitiveEntry) || (entryType instanceof com.sun.tools.corba.ee.idl.StringEntry))) + { + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, entry.fullName(), "primitive or string", entryName(entry.type())); + entry.type (qualifiedEntry ("long")); + } + else if (entryType instanceof com.sun.tools.corba.ee.idl.PrimitiveEntry) + { + String any = overrideName ("any"); + if (entryType.name().equals (any)) + { + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, entry.fullName(), "primitive or string (except " + any + ')', any); + entry.type (qualifiedEntry ("long")); + } + } + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Long, com.sun.tools.corba.ee.idl.Token.Short, com.sun.tools.corba.ee.idl.Token.Unsigned, com.sun.tools.corba.ee.idl.Token.Char, + com.sun.tools.corba.ee.idl.Token.Wchar, com.sun.tools.corba.ee.idl.Token.Boolean, com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double, + com.sun.tools.corba.ee.idl.Token.String, com.sun.tools.corba.ee.idl.Token.Wstring, com.sun.tools.corba.ee.idl.Token.Identifier, + com.sun.tools.corba.ee.idl.Token.DoubleColon}, token.type); + } + } // constType + + /** + * + **/ + private boolean hasArrayInfo (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + while (entry instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + { + if (((com.sun.tools.corba.ee.idl.TypedefEntry)entry).arrayInfo ().size () != 0) + return true; + entry = entry.type (); + } + return false; + } // hasArrayInfo + + /** + * + **/ + public static String overrideName (String string) + { + String name = (String)overrideNames.get (string); + return (name == null) ? string : name; + } // overrideName + + // If entry is boolean, expression value must be boolean + // If entry is float/double, expression value must be float/double + // If entry is integral, expression value must be integral + // If entry is string, expression value must be string + + /** + * + **/ + private void verifyConstType (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry t) + { + Object value = e.value (); + if (value instanceof BigInteger) + verifyIntegral ((Number)value, t); + else if (value instanceof String) + verifyString (e, t); + else if (value instanceof Boolean) + verifyBoolean (t); + else if (value instanceof Character) + verifyCharacter (e, t); + else if (value instanceof Float || value instanceof Double) + verifyFloat((Number)value, t); + else if (value instanceof com.sun.tools.corba.ee.idl.ConstEntry) + verifyConstType (((com.sun.tools.corba.ee.idl.ConstEntry)value).value (), t); + else + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.fullName(), + (value == null) ? "" : value.toString()); + } // verifyConstType + + private static final int MAX_SHORT = 32767; + private static final int MIN_SHORT = -32768; + private static final int MAX_USHORT = 65535; + + /** + * + **/ + private void verifyIntegral (Number n, com.sun.tools.corba.ee.idl.SymtabEntry t) + { + boolean outOfRange = false; + //KEEP: Useful for debugging com.sun.tools.corba.ee.idl.constExpr package + //System.out.println ("verifyIntegral, n = " + n.toString ()); + + if (t == qualifiedEntry( "octet" )) { + if ((n.longValue() > 255) || (n.longValue() < 0)) + outOfRange = true ; + } else if (t == qualifiedEntry ("long")) { + if (n.longValue () > Integer.MAX_VALUE || n.longValue() < Integer.MIN_VALUE) + outOfRange = true; + } else if (t == qualifiedEntry ("short")) { + if (n.intValue () > Short.MAX_VALUE || n.intValue () < Short.MIN_VALUE) + outOfRange = true; + } else if (t == qualifiedEntry ("unsigned long")) { + if (n.longValue () > (long)Integer.MAX_VALUE*2+1 || n.longValue() < 0) + outOfRange = true; + } else if (t == qualifiedEntry ("unsigned short")) { + if (n.intValue () > (int) Short.MAX_VALUE*2+1 || n.intValue () < 0) + outOfRange = true; + } else if (t == qualifiedEntry ("long long")) { + // BigInteger required because value being compared may exceed + // java.lang.Long.MAX_VALUE/MIN_VALUE: + BigInteger llMax = BigInteger.valueOf (Long.MAX_VALUE); + BigInteger llMin = BigInteger.valueOf (Long.MIN_VALUE); + if (((BigInteger)n).compareTo (llMax) > 0 || + ((BigInteger)n).compareTo (llMin) < 0) + outOfRange = true; + } else if (t == qualifiedEntry ("unsigned long long")) { + BigInteger ullMax = BigInteger.valueOf (Long.MAX_VALUE). + multiply (BigInteger.valueOf (2)). + add (BigInteger.valueOf (1)); + BigInteger ullMin = BigInteger.valueOf (0); + if (((BigInteger)n).compareTo (ullMax) > 0 || + ((BigInteger)n).compareTo (ullMin) < 0) + outOfRange = true; + } else { + String got = null; + // THIS MUST BE CHANGED; BIGINTEGER IS ALWAYS THE CONTAINER + /* + if (n instanceof Short) + got = "short"; + else if (n instanceof Integer) + got = "long"; + else + got = "long long"; + */ + got = "long"; + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.fullName(), got); + } + + if (outOfRange) + com.sun.tools.corba.ee.idl.ParseException.outOfRange(scanner, n.toString(), t.fullName()); + } // verifyIntegral + + /** + * + **/ + private void verifyString (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry t) + { + String string = (String)(e.value()) ; + if (!(t instanceof com.sun.tools.corba.ee.idl.StringEntry)) { + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.fullName(), e.type()); + } else if (((com.sun.tools.corba.ee.idl.StringEntry)t).maxSize () != null) { + com.sun.tools.corba.ee.idl.constExpr.Expression maxExp = ((com.sun.tools.corba.ee.idl.StringEntry)t).maxSize (); + try { + Number max = (Number)maxExp.value (); + if (string.length () > max.intValue ()) + com.sun.tools.corba.ee.idl.ParseException.stringTooLong(scanner, string, max.toString()); + } catch (Exception exception) { + // If the above statement is not valid and throws an + // exception, then an error occurred and was reported + // earlier. Move on. + } + } + + if (!e.type().equals( t.name())) { + // cannot mix strings and wide strings + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.name(), e.type()) ; + } + } // verifyString + + /** + * + **/ + private void verifyBoolean (com.sun.tools.corba.ee.idl.SymtabEntry t) + { + if (!t.name ().equals (overrideName ("boolean"))) + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.name(), "boolean"); + } // verifyBoolean + + /** + * + **/ + private void verifyCharacter (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry t) + { + // Bug fix 4382578: Can't compile a wchar literal. + // Allow a Character to be either a char or a wchar. + if (!t.name ().equals (overrideName ("char")) && + !t.name ().equals (overrideName ("wchar")) || + !t.name().equals(e.type()) ) + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.fullName(), e.type()) ; + } // verifyCharacter + + /** + * + **/ + private void verifyFloat (Number f, com.sun.tools.corba.ee.idl.SymtabEntry t) + { + // Added range checking for floats. + //if (!(t.name ().equals (overrideName ("float")) || + // t.name ().equals (overrideName ("double")))) + // ParseException.wrongExprType (scanner, + // t.fullName (), (f instanceof Float) ? "float" : "double"); + //KEEP: Useful for debugging com.sun.tools.corba.ee.idl.constExpr package + //System.out.println ("verifyFloat, f = " + f.toString ()); + boolean outOfRange = false; + if (t.name ().equals (overrideName ("float"))) + { + double absVal = (f.doubleValue () < 0.0) ? + f.doubleValue () * -1.0 : f.doubleValue (); + if ((absVal != 0.0) && + (absVal > Float.MAX_VALUE || absVal < Float.MIN_VALUE)) + outOfRange = true; + } + else if (t.name ().equals (overrideName ("double"))) + { + // Cannot check range of double until BigDecimal is the basis + // of all floating-point types. Currently, it is Double. The + // parser will fail when instantiating a Double with an exception. + } + else + { + com.sun.tools.corba.ee.idl.ParseException.wrongExprType(scanner, t.fullName(), + (f instanceof Float) ? "float" : "double"); + } + if (outOfRange) + com.sun.tools.corba.ee.idl.ParseException.outOfRange(scanner, f.toString(), t.fullName()); + } // verifyFloat + + /** + * + **/ + com.sun.tools.corba.ee.idl.constExpr.Expression constExp (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // Parse the expression. + com.sun.tools.corba.ee.idl.constExpr.Expression expr = orExpr (null, entry); + + // Set its target type. + if (expr.type() == null) + expr.type (entry.typeName ()); + // Compute its value and coerce it to the target type. + try + { + expr.evaluate (); + + // Coerces integral value to Double if an integer literal + // was used to initialize a floating-point constant expression. + if (expr instanceof com.sun.tools.corba.ee.idl.constExpr.Terminal && + expr.value () instanceof BigInteger && + (overrideName (expr.type ()).equals ("float") || + overrideName (expr.type ()).indexOf ("double") >= 0)) + { + expr.value (new Double (((BigInteger)expr.value ()).doubleValue ())); + } + } + catch (com.sun.tools.corba.ee.idl.constExpr.EvaluationException exception) + { + com.sun.tools.corba.ee.idl.ParseException.evaluationError(scanner, exception.toString()); + } + return expr; + } // constExp + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression orExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = xorExpr (null, entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (xorExpr (null, entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Bar)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Or or = exprFactory.or (e, null); + or.type (entry.typeName ()); + or.rep (e.rep () + " | "); + return orExpr (or, entry); + } + return e; + } // orExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression xorExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = andExpr (null, entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (andExpr (null, entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Carat)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Xor xor = exprFactory.xor (e, null); + xor.rep (e.rep () + " ^ "); + xor.type (entry.typeName ()); + return xorExpr (xor, entry); + } + return e; + } // xorExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression andExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = shiftExpr (null, entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (shiftExpr (null, entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Ampersand)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.And and = exprFactory.and (e, null); + and.rep(e.rep () + " & "); + and.type (entry.typeName ()); + return andExpr (and, entry); + } + return e; + } // andExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression shiftExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = addExpr (null, entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (addExpr (null, entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.ShiftLeft)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.ShiftLeft sl = exprFactory.shiftLeft (e, null); + sl.type (entry.typeName ()); + sl.rep (e.rep () + " << "); + return shiftExpr (sl, entry); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.ShiftRight)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.ShiftRight sr = exprFactory.shiftRight (e, null); + sr.type (entry.typeName ()); + sr.rep (e.rep () + " >> "); + return shiftExpr (sr, entry); + } + return e; + } // shiftExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression addExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = multExpr (null, entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (multExpr (null, entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Plus)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Plus p = exprFactory.plus (e, null); + p.type (entry.typeName ()); + p.rep (e.rep () + " + "); + return addExpr (p, entry); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Minus)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Minus m = exprFactory.minus (e, null); + m.type (entry.typeName ()); + m.rep (e.rep () + " - "); + return addExpr (m, entry); + } + return e; + } // addExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression multExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = unaryExpr (entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (unaryExpr (entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Star)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Times t = exprFactory.times (e, null); + t.type (entry.typeName ()); + t.rep (e.rep () + " * "); + return multExpr (t, entry); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Slash)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Divide d = exprFactory.divide (e, null); + d.type (entry.typeName ()); + d.rep (e.rep () + " / "); + return multExpr (d, entry); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Percent)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Modulo m = exprFactory.modulo (e, null); + m.type (entry.typeName ()); + m.rep (e.rep () + " % "); + return multExpr (m, entry); + } + return e; + } // multExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression unaryExpr (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.Plus)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Expression e = primaryExpr (entry); + com.sun.tools.corba.ee.idl.constExpr.Positive pos = exprFactory.positive (e); + pos.type (entry.typeName()); + pos.rep ('+' + e.rep()); + return pos; + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Minus)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Expression e = primaryExpr (entry); + com.sun.tools.corba.ee.idl.constExpr.Negative neg = exprFactory.negative (e); + neg.type (entry.typeName()); + neg.rep ('-' + e.rep()); + return neg; + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.Tilde)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Expression e = primaryExpr (entry); + com.sun.tools.corba.ee.idl.constExpr.Not not = exprFactory.not (e); + not.type (entry.typeName()); + not.rep ('~' + e.rep()); + return not; + } + return primaryExpr (entry); + } // unaryExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression primaryExpr (com.sun.tools.corba.ee.idl.SymtabEntry entry) + throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.constExpr.Expression primary = null; + if (parsingConditionalExpr) + { + prep.token = token; // Give current token to preprocessor + primary = prep.primaryExpr (entry); + token = prep.token; // Get the current token from preprocessor + } + else + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Identifier: + case com.sun.tools.corba.ee.idl.Token.DoubleColon: + com.sun.tools.corba.ee.idl.ConstEntry expectedC = stFactory.constEntry (); + expectedC.value (exprFactory.terminal ("1", BigInteger.valueOf (1))); + com.sun.tools.corba.ee.idl.SymtabEntry ref = scopedName (entry.container (), expectedC); + if (!(ref instanceof com.sun.tools.corba.ee.idl.ConstEntry)) + { + com.sun.tools.corba.ee.idl.ParseException.invalidConst(scanner, ref.fullName()); + // An error occurred. Just give it some bogus value. + //primary = exprFactory.terminal ("1", new Long (1)); + primary = exprFactory.terminal ("1", BigInteger.valueOf (1)); + } + else + primary = exprFactory.terminal ((com.sun.tools.corba.ee.idl.ConstEntry)ref); + break; + case com.sun.tools.corba.ee.idl.Token.BooleanLiteral: + case com.sun.tools.corba.ee.idl.Token.CharacterLiteral: + case com.sun.tools.corba.ee.idl.Token.IntegerLiteral: + case com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral: + case com.sun.tools.corba.ee.idl.Token.StringLiteral: + primary = literal (entry); + break; + case com.sun.tools.corba.ee.idl.Token.LeftParen: + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + primary = constExp (entry); + match (com.sun.tools.corba.ee.idl.Token.RightParen); + primary.rep ('(' + primary.rep () + ')'); + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Identifier, com.sun.tools.corba.ee.idl.Token.DoubleColon, com.sun.tools.corba.ee.idl.Token.Literal, com.sun.tools.corba.ee.idl.Token.LeftParen}, + token.type); + } + return primary; + } // primaryExpr + + /** + * + **/ + @SuppressWarnings("ThrowableResultOfMethodCallIgnored") + com.sun.tools.corba.ee.idl.constExpr.Expression literal (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + String string = token.name; + com.sun.tools.corba.ee.idl.constExpr.Expression literal = null; + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.IntegerLiteral: + match (com.sun.tools.corba.ee.idl.Token.IntegerLiteral); + try + { + literal = exprFactory.terminal (string, parseString (string)); + literal.type (entry.typeName ()); + } + catch (NumberFormatException exception) + { + com.sun.tools.corba.ee.idl.ParseException.notANumber(scanner, string); + literal = exprFactory.terminal ("0", BigInteger.valueOf (0)); + } + break; + case com.sun.tools.corba.ee.idl.Token.CharacterLiteral: + boolean isWide = token.isWide(); + match (com.sun.tools.corba.ee.idl.Token.CharacterLiteral); + literal = exprFactory.terminal ("'" + string.substring (1) + "'", string.charAt( 0 ), isWide ); + break; + case com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral: + match (com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral); + try + { + literal = exprFactory.terminal (string, new Double (string)); + literal.type (entry.typeName ()); + } + catch (NumberFormatException e) + { + com.sun.tools.corba.ee.idl.ParseException.notANumber(scanner, string); + } + break; + case com.sun.tools.corba.ee.idl.Token.BooleanLiteral: + literal = booleanLiteral (); + break; + case com.sun.tools.corba.ee.idl.Token.StringLiteral: + literal = stringLiteral (); + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Literal, token.type); + } + return literal; + } // literal + + /** + * + **/ + private BigInteger parseString (String string) throws NumberFormatException + { + int radix = 10; + if (string.length() > 1) + if (string.charAt (0) == '0') + if (string.charAt (1) == 'x' || string.charAt (1) == 'X') + { + string = string.substring (2); + radix = 16; + } + else + radix = 8; + return new BigInteger (string, radix); + } // parseString + + @SuppressWarnings("ThrowableResultOfMethodCallIgnored") + private com.sun.tools.corba.ee.idl.constExpr.Terminal booleanLiteral() throws IOException, com.sun.tools.corba.ee.idl.ParseException { + Boolean bool; + switch ( token.name ) { + case "TRUE": + bool = true; + break; + case "FALSE": + bool = false; + break; + default: + ParseException.invalidConst( scanner, token.name ); + bool = false; + break; + } + String name = token.name; + match (com.sun.tools.corba.ee.idl.Token.BooleanLiteral); + return exprFactory.terminal (name, bool); + } + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression stringLiteral () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // If string literals appear together, concatenate them. Ie: + // "Twas " "brillig " "and " "the " "slithy " "toves" + // becomes + // "Twas brillig and the slithy toves" + boolean isWide = token.isWide() ; + String literal = ""; + do + { + literal += token.name; + match (com.sun.tools.corba.ee.idl.Token.StringLiteral); + } while (token.equals (com.sun.tools.corba.ee.idl.Token.StringLiteral)); + com.sun.tools.corba.ee.idl.constExpr.Expression stringExpr = exprFactory.terminal (literal, isWide ); + stringExpr.rep ('"' + literal + '"'); + return stringExpr; + } // stringLiteral + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression positiveIntConst (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.constExpr.Expression e = constExp (entry); + Object value = e.value (); + while (value instanceof com.sun.tools.corba.ee.idl.ConstEntry) + value = ((com.sun.tools.corba.ee.idl.ConstEntry)value).value ().value (); + if (!(value instanceof Number) || value instanceof Float || value instanceof Double) + { + com.sun.tools.corba.ee.idl.ParseException.notPositiveInt(scanner, e.rep()); + //e = exprFactory.terminal ("1", new Long (1)); + e = exprFactory.terminal ("1", BigInteger.valueOf (1)); + } + //else if (((Number)value).longValue () <= 0) { + // ParseException.notPositiveInt (scanner, value.toString ()); + // e = exprFactory.terminal ("1", new Long (1)); } + else if (((BigInteger)value).compareTo (BigInteger.valueOf (0)) <= 0) + { + com.sun.tools.corba.ee.idl.ParseException.notPositiveInt(scanner, value.toString()); + //e = exprFactory.terminal ("1", new Long (1)); + e = exprFactory.terminal ("1", BigInteger.valueOf (1)); + } + return e; + } // positiveIntConst + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry typeDcl (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Typedef: + match (com.sun.tools.corba.ee.idl.Token.Typedef); + return typeDeclarator (entry); + case com.sun.tools.corba.ee.idl.Token.Struct: + return structType (entry); + case com.sun.tools.corba.ee.idl.Token.Union: + return unionType (entry); + case com.sun.tools.corba.ee.idl.Token.Enum: + return enumType (entry); + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Typedef, com.sun.tools.corba.ee.idl.Token.Struct, com.sun.tools.corba.ee.idl.Token.Union, com.sun.tools.corba.ee.idl.Token.Enum}, token.type); + } + } // typeDcl + + /** + * + **/ + private com.sun.tools.corba.ee.idl.TypedefEntry typeDeclarator (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry = stFactory.typedefEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + typedefEntry.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede "typedef" keyword + typedefEntry.comment (tokenHistory.lookBack (1).comment); + typedefEntry.type (typeSpec (entry)); + Vector typedefList = new Vector (); + declarators (typedefEntry, typedefList); + for (Enumeration e = typedefList.elements(); e.hasMoreElements();) + pigeonhole (entry, (com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement ()); + return typedefEntry; + } // typeDeclarator + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry typeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + return ((token.type == com.sun.tools.corba.ee.idl.Token.Struct) || + (token.type == com.sun.tools.corba.ee.idl.Token.Union) || + (token.type == com.sun.tools.corba.ee.idl.Token.Enum)) + ? constrTypeSpec (entry) + : simpleTypeSpec (entry, true); + } // typeSpec + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry simpleTypeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry, + boolean mustBeReferencable ) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // + //if ((token.type == Token.Identifier) || + // (token.type == Token.DoubleColon) || + // (token.type == Token.Object)) { + if ((token.type == com.sun.tools.corba.ee.idl.Token.Identifier) || + (token.type == com.sun.tools.corba.ee.idl.Token.DoubleColon) || + (token.type == com.sun.tools.corba.ee.idl.Token.Object) || + (token.type == com.sun.tools.corba.ee.idl.Token.ValueBase)) + { + com.sun.tools.corba.ee.idl.SymtabEntry container = ((entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) || + (entry instanceof com.sun.tools.corba.ee.idl.ModuleEntry) || + (entry instanceof com.sun.tools.corba.ee.idl.StructEntry) || + (entry instanceof com.sun.tools.corba.ee.idl.UnionEntry)) + ? entry + : entry.container (); + return scopedName (container, stFactory.primitiveEntry (), + mustBeReferencable); + } + return ((token.type == com.sun.tools.corba.ee.idl.Token.Sequence) || + (token.type == com.sun.tools.corba.ee.idl.Token.String) || + (token.type == com.sun.tools.corba.ee.idl.Token.Wstring)) + ? templateTypeSpec (entry) + : baseTypeSpec (entry); + } // simpleTypeSpec + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry baseTypeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Float: + case com.sun.tools.corba.ee.idl.Token.Double: + return floatingPtType (); + case com.sun.tools.corba.ee.idl.Token.Long: + case com.sun.tools.corba.ee.idl.Token.Short: + case com.sun.tools.corba.ee.idl.Token.Unsigned: + return integerType (entry); + case com.sun.tools.corba.ee.idl.Token.Char: + case com.sun.tools.corba.ee.idl.Token.Wchar: + return charType (); + case com.sun.tools.corba.ee.idl.Token.Boolean: + return booleanType (); + case com.sun.tools.corba.ee.idl.Token.Octet: + return octetType (); + case com.sun.tools.corba.ee.idl.Token.Any: + return anyType (); + // NOTE: Object and ValueBase are s, but both + // are processed at simpleTypeSpec(), not here. parmTypeSpec() + // directly checks for these types. Could make baseTypeSpec() do + // the same + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double, com.sun.tools.corba.ee.idl.Token.Long, com.sun.tools.corba.ee.idl.Token.Short, + com.sun.tools.corba.ee.idl.Token.Unsigned, com.sun.tools.corba.ee.idl.Token.Char, com.sun.tools.corba.ee.idl.Token.Wchar, com.sun.tools.corba.ee.idl.Token.Boolean, + com.sun.tools.corba.ee.idl.Token.Octet, com.sun.tools.corba.ee.idl.Token.Any}, token.type); + } + } // baseTypeSpec + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry templateTypeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Sequence: + return sequenceType (entry); + case com.sun.tools.corba.ee.idl.Token.String: + case com.sun.tools.corba.ee.idl.Token.Wstring: + return stringType (entry); + } + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{com.sun.tools.corba.ee.idl.Token.Sequence, com.sun.tools.corba.ee.idl.Token.String, com.sun.tools.corba.ee.idl.Token.Wstring}, token.type); + } // templateTypeSpec + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry constrTypeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Struct: + return structType (entry); + case com.sun.tools.corba.ee.idl.Token.Union: + return unionType (entry); + case com.sun.tools.corba.ee.idl.Token.Enum: + return enumType (entry); + } + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{com.sun.tools.corba.ee.idl.Token.Struct, com.sun.tools.corba.ee.idl.Token.Union, com.sun.tools.corba.ee.idl.Token.Enum}, token.type); + } // constrTypeSpec + + /** + * + **/ + private void declarators (com.sun.tools.corba.ee.idl.TypedefEntry entry, Vector list) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + for (; ; match (com.sun.tools.corba.ee.idl.Token.Comma)) + { + com.sun.tools.corba.ee.idl.TypedefEntry newEntry = (com.sun.tools.corba.ee.idl.TypedefEntry)entry.clone (); + declarator (newEntry); + if (isntInList (list, newEntry.name ())) + list.addElement (newEntry); + if (token.type != com.sun.tools.corba.ee.idl.Token.Comma) + break; + } + } // declarators + + /** + * + **/ + private void declarator (com.sun.tools.corba.ee.idl.TypedefEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + entry.name (token.name); + // If the declarator is commented then override the comment cloned from the parent + // entry. <08aug1997daz> + if (!token.comment.text ().equals ("")) + entry.comment (token.comment); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + while (token.type == com.sun.tools.corba.ee.idl.Token.LeftBracket) + fixedArraySize (entry); + } // declarator + + /** + * + **/ + private com.sun.tools.corba.ee.idl.PrimitiveEntry floatingPtType () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + String name = "double"; + if (token.type == com.sun.tools.corba.ee.idl.Token.Float) + { + match (com.sun.tools.corba.ee.idl.Token.Float); + name = "float"; + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.Double) + match (com.sun.tools.corba.ee.idl.Token.Double); + else + { + int [] expected = {com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double}; + com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double}, token.type); + } + com.sun.tools.corba.ee.idl.PrimitiveEntry ret = null; + try + { + ret = (com.sun.tools.corba.ee.idl.PrimitiveEntry)qualifiedEntry (name); + } + catch (ClassCastException exception) + { + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, name); + } + return ret; + } // floatingPtType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.PrimitiveEntry integerType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + String name = ""; + if (token.type == com.sun.tools.corba.ee.idl.Token.Unsigned) + { + match (com.sun.tools.corba.ee.idl.Token.Unsigned); + name = "unsigned "; + } + name += signedInt(); + com.sun.tools.corba.ee.idl.PrimitiveEntry ret = null; + try + { + ret = (com.sun.tools.corba.ee.idl.PrimitiveEntry) qualifiedEntry (name); + } + catch (ClassCastException exception) + { + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, name); + } + return ret; + } // integerType + + /** + * + **/ + private String signedInt () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + String ret = "long"; + if (token.type == com.sun.tools.corba.ee.idl.Token.Long) + { + match (com.sun.tools.corba.ee.idl.Token.Long); + // ::= "long" | e + if (token.type == com.sun.tools.corba.ee.idl.Token.Long) + { + ret = "long long"; + match (com.sun.tools.corba.ee.idl.Token.Long); + } + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.Short) + { + ret = "short"; + match (com.sun.tools.corba.ee.idl.Token.Short); + } + else + com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{com.sun.tools.corba.ee.idl.Token.Long, com.sun.tools.corba.ee.idl.Token.Short}, token.type); + return ret; + } // signedInt + + /** + * + **/ + private com.sun.tools.corba.ee.idl.PrimitiveEntry charType () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + String tokenName; + if (token.type == com.sun.tools.corba.ee.idl.Token.Char) + { + match (com.sun.tools.corba.ee.idl.Token.Char); + tokenName = "char"; + } + else + { + match (com.sun.tools.corba.ee.idl.Token.Wchar); + tokenName = "wchar"; + } + com.sun.tools.corba.ee.idl.PrimitiveEntry ret = null; + try + { + ret = (com.sun.tools.corba.ee.idl.PrimitiveEntry) qualifiedEntry (tokenName); + } + catch (ClassCastException exception) + { + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, overrideName(tokenName)); + } + return ret; + } // charType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.PrimitiveEntry booleanType () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.PrimitiveEntry ret = null; + match (com.sun.tools.corba.ee.idl.Token.Boolean); + try + { + ret = (com.sun.tools.corba.ee.idl.PrimitiveEntry) qualifiedEntry ("boolean"); + } + catch (ClassCastException exception) + { + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, overrideName("boolean")); + } + return ret; + } // booleanType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.PrimitiveEntry octetType () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.PrimitiveEntry ret = null; + match (com.sun.tools.corba.ee.idl.Token.Octet); + try + { + ret = (com.sun.tools.corba.ee.idl.PrimitiveEntry) qualifiedEntry ("octet"); + } + catch (ClassCastException exception) + { + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, overrideName("octet")); + } + return ret; + } // octetType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry anyType () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Any); + try + { + return qualifiedEntry ("any"); + } + catch (ClassCastException exception) + { + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, overrideName("any")); + return null; + } + } // anyType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.StructEntry structType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, + com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Struct); + String name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + com.sun.tools.corba.ee.idl.StructEntry structEntry = null ; + + if (token.type == com.sun.tools.corba.ee.idl.Token.LeftBrace) { + repIDStack.push(((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()) ; +//!!! ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (name); + structEntry = makeStructEntry( name, entry, false ) ; + prep.openScope (structEntry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace) ; + member (structEntry) ; + memberList2 (structEntry) ; + prep.closeScope (structEntry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace) ; + repIDStack.pop() ; + } else if (token.equals( com.sun.tools.corba.ee.idl.Token.Semicolon )) { + structEntry = makeStructEntry( name, entry, true ) ; + } else { + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, + new int[]{com.sun.tools.corba.ee.idl.Token.Semicolon, com.sun.tools.corba.ee.idl.Token.LeftBrace}, token.type); + } + return structEntry; + } // structType + + private com.sun.tools.corba.ee.idl.StructEntry makeStructEntry( String name, com.sun.tools.corba.ee.idl.SymtabEntry entry, + boolean isForward ) + { + com.sun.tools.corba.ee.idl.StructEntry structEntry = stFactory.structEntry (entry, + (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek () ); + structEntry.isReferencable( !isForward ) ; + structEntry.sourceFile (scanner.fileEntry ()); + structEntry.name (name); + // Comment must immediately preceed "struct" keyword + structEntry.comment (tokenHistory.lookBack (1).comment); + pigeonhole( entry, structEntry ) ; + return structEntry ; + } + + /** + * + **/ + private void memberList2 (com.sun.tools.corba.ee.idl.StructEntry entry) throws IOException + { + while (token.type != com.sun.tools.corba.ee.idl.Token.RightBrace) + member (entry); + } // memberList2 + + /** + * + **/ + private void member (com.sun.tools.corba.ee.idl.StructEntry entry) throws IOException + { + com.sun.tools.corba.ee.idl.TypedefEntry newEntry = stFactory.typedefEntry(entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek()); + newEntry.sourceFile (scanner.fileEntry ()); + // comment must immediately precede lexeme + newEntry.comment (token.comment); + try + { + newEntry.type (typeSpec (entry)); + if (newEntry.type () == entry) + throw com.sun.tools.corba.ee.idl.ParseException.recursive(scanner, entry.fullName(), + (token.name == null) ? "" : token.name); + // Exception cannot appear within a struct, union, or exception + if (typeOf (newEntry) instanceof com.sun.tools.corba.ee.idl.ExceptionEntry) + throw com.sun.tools.corba.ee.idl.ParseException.illegalException(scanner, entryName(entry)); + declarators (newEntry, entry.members ()); + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + } + catch (com.sun.tools.corba.ee.idl.ParseException exception) + { + skipToSemicolon (); + } + } // member + + /** + * + **/ + private final boolean isConstTypeSpec (com.sun.tools.corba.ee.idl.Token t) + { + return (t.type == com.sun.tools.corba.ee.idl.Token.Struct || t.type == com.sun.tools.corba.ee.idl.Token.Union || t.type == com.sun.tools.corba.ee.idl.Token.Enum); + } // isConstTypeSpec + + /** + * + **/ + private com.sun.tools.corba.ee.idl.UnionEntry unionType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Union) ; + String name = token.name ; + match (com.sun.tools.corba.ee.idl.Token.Identifier) ; + com.sun.tools.corba.ee.idl.UnionEntry unionEntry = null ; + + if (token.type == com.sun.tools.corba.ee.idl.Token.Switch) { + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); +//!!! ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (name); + unionEntry = makeUnionEntry( name, entry, false ) ; + match (com.sun.tools.corba.ee.idl.Token.Switch); + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + unionEntry.type (switchTypeSpec (unionEntry)); + match (com.sun.tools.corba.ee.idl.Token.RightParen); + prep.openScope (unionEntry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace); + switchBody (unionEntry); + verifyUnion (unionEntry); + prep.closeScope (unionEntry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace); + repIDStack.pop (); + } else if (token.equals( com.sun.tools.corba.ee.idl.Token.Semicolon )) { + unionEntry = makeUnionEntry( name, entry, true ) ; + } else { + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, + new int[]{com.sun.tools.corba.ee.idl.Token.Semicolon, com.sun.tools.corba.ee.idl.Token.Switch}, token.type); + } + + return unionEntry ; + } // unionType + + private com.sun.tools.corba.ee.idl.UnionEntry makeUnionEntry( String name, com.sun.tools.corba.ee.idl.SymtabEntry entry, + boolean isForward ) + { + com.sun.tools.corba.ee.idl.UnionEntry unionEntry = stFactory.unionEntry (entry, + (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek () ); + unionEntry.isReferencable( !isForward ) ; + unionEntry.sourceFile (scanner.fileEntry ()); + unionEntry.name (name); + // Comment must immediately preceed "union" keyword + unionEntry.comment (tokenHistory.lookBack (1).comment); + pigeonhole( entry, unionEntry ) ; + return unionEntry ; + } + + /** + * + **/ + private void verifyUnion (com.sun.tools.corba.ee.idl.UnionEntry u) + { + if (u.typeName ().equals (overrideName ("boolean"))) + { + if (caseCount (u) > 2) + com.sun.tools.corba.ee.idl.ParseException.noDefault(scanner); + } + else if (u.type () instanceof com.sun.tools.corba.ee.idl.EnumEntry) + { + if (caseCount (u) > ((com.sun.tools.corba.ee.idl.EnumEntry)u.type ()).elements ().size ()) + com.sun.tools.corba.ee.idl.ParseException.noDefault(scanner); + } + } // verifyUnion + + /** + * + **/ + private long caseCount (com.sun.tools.corba.ee.idl.UnionEntry u) + { + long cases = 0; + Enumeration branches = u.branches ().elements (); + while (branches.hasMoreElements ()) + { + com.sun.tools.corba.ee.idl.UnionBranch branch = (com.sun.tools.corba.ee.idl.UnionBranch)branches.nextElement (); + cases += branch.labels.size (); + if (branch.isDefault) + ++cases; + } + return cases; + } // caseCount + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry switchTypeSpec (com.sun.tools.corba.ee.idl.UnionEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.SymtabEntry ret = null; + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Long: + case com.sun.tools.corba.ee.idl.Token.Short: + case com.sun.tools.corba.ee.idl.Token.Unsigned: + return integerType (entry); + case com.sun.tools.corba.ee.idl.Token.Char: + case com.sun.tools.corba.ee.idl.Token.Wchar: + return charType(); + case com.sun.tools.corba.ee.idl.Token.Boolean: + return booleanType(); + case com.sun.tools.corba.ee.idl.Token.Enum: + return enumType (entry); + case com.sun.tools.corba.ee.idl.Token.Identifier: + case com.sun.tools.corba.ee.idl.Token.DoubleColon: + ret = scopedName (entry, stFactory.primitiveEntry ()); + if (hasArrayInfo (entry.type ())) + com.sun.tools.corba.ee.idl.ParseException.illegalArray(scanner, "switch"); + com.sun.tools.corba.ee.idl.SymtabEntry retType = typeOf (ret); + if (!(retType instanceof com.sun.tools.corba.ee.idl.EnumEntry || retType instanceof com.sun.tools.corba.ee.idl.PrimitiveEntry)) + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, ret.fullName(), + "long, unsigned long, short, unsigned short, char, boolean, enum", + entryName(ret.type())); + else if (ret instanceof com.sun.tools.corba.ee.idl.PrimitiveEntry) + { + com.sun.tools.corba.ee.idl.SymtabEntry octet = qualifiedEntry ("octet"); + com.sun.tools.corba.ee.idl.SymtabEntry flt = qualifiedEntry ("float"); + com.sun.tools.corba.ee.idl.SymtabEntry dbl = qualifiedEntry ("double"); + if (retType == octet || retType == flt || retType == dbl) + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, ret.fullName(), + "long, unsigned long, short, unsigned short, char, boolean, enum", + entryName(ret.type())); + } + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Long, com.sun.tools.corba.ee.idl.Token.Short, com.sun.tools.corba.ee.idl.Token.Unsigned, com.sun.tools.corba.ee.idl.Token.Char, + com.sun.tools.corba.ee.idl.Token.Boolean, com.sun.tools.corba.ee.idl.Token.Enum, com.sun.tools.corba.ee.idl.Token.Identifier, + com.sun.tools.corba.ee.idl.Token.DoubleColon}, token.type); + } + return ret; + } // switchTypeSpec + + // This is only used by the union methods + com.sun.tools.corba.ee.idl.UnionBranch defaultBranch = null; + + /** + * + **/ + private void switchBody (com.sun.tools.corba.ee.idl.UnionEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + caseProd (entry); + while (!token.equals (com.sun.tools.corba.ee.idl.Token.RightBrace)) + caseProd (entry); + entry.defaultBranch ((defaultBranch == null) ? null : defaultBranch.typedef); + defaultBranch = null; + } // switchBody + + /** + * + **/ + private void caseProd (com.sun.tools.corba.ee.idl.UnionEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.UnionBranch branch = new com.sun.tools.corba.ee.idl.UnionBranch(); + entry.addBranch (branch); + caseLabel (entry, branch); + while (token.equals (com.sun.tools.corba.ee.idl.Token.Case) || token.equals (com.sun.tools.corba.ee.idl.Token.Default)) + caseLabel (entry, branch); + elementSpec (entry, branch); + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + } // caseProd + + /** + * + **/ + private void caseLabel (com.sun.tools.corba.ee.idl.UnionEntry entry, com.sun.tools.corba.ee.idl.UnionBranch branch) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type == com.sun.tools.corba.ee.idl.Token.Case) + { + match (com.sun.tools.corba.ee.idl.Token.Case); + com.sun.tools.corba.ee.idl.ConstEntry tmpEntry = stFactory.constEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + tmpEntry.sourceFile (scanner.fileEntry ()); + tmpEntry.type (entry); + + com.sun.tools.corba.ee.idl.constExpr.Expression label; + com.sun.tools.corba.ee.idl.SymtabEntry type = typeOf (entry.type ()); + if (type instanceof com.sun.tools.corba.ee.idl.EnumEntry) + label = matchEnum ((com.sun.tools.corba.ee.idl.EnumEntry)type); + else + { + label = constExp (tmpEntry); + verifyConstType (label, type); + } + if (entry.has (label)) + com.sun.tools.corba.ee.idl.ParseException.branchLabel(scanner, label.rep()); + branch.labels.addElement (label); + match (com.sun.tools.corba.ee.idl.Token.Colon); + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.Default) + { + match (com.sun.tools.corba.ee.idl.Token.Default); + match (com.sun.tools.corba.ee.idl.Token.Colon); + if (entry.defaultBranch () != null) + com.sun.tools.corba.ee.idl.ParseException.alreadyDefaulted(scanner); + branch.isDefault = true; + defaultBranch = branch; + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{com.sun.tools.corba.ee.idl.Token.Case, com.sun.tools.corba.ee.idl.Token.Default}, token.type); + } // caselabel + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression matchEnum (com.sun.tools.corba.ee.idl.EnumEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // Get the symbol table entry for the case label based on the + // scope of the EnumEntry, NOT the UnionEntry (the union could be + // in a different scope than the enum). Given + // module M { enum E {A, B, C, D}; }; + // a case label for A could be one of the following: + // case A: + // case M::A: + // case ::M::A: + com.sun.tools.corba.ee.idl.SymtabEntry label = scopedName (entry.container(), new com.sun.tools.corba.ee.idl.SymtabEntry()); + return exprFactory.terminal (label.name (), false); + } // matchEnum + + /** + * + **/ + private void elementSpec (com.sun.tools.corba.ee.idl.UnionEntry entry, com.sun.tools.corba.ee.idl.UnionBranch branch) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.TypedefEntry typedef = stFactory.typedefEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + typedef.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede lexeme + typedef.comment (token.comment); + typedef.type (typeSpec (entry)); + if (typedef.type () == entry) + throw com.sun.tools.corba.ee.idl.ParseException.recursive(scanner, entry.fullName(), (token.name == null) ? "" : token.name); + // Exception cannot appear within a struct, union, or exception + if (typeOf (typedef) instanceof com.sun.tools.corba.ee.idl.ExceptionEntry) + throw com.sun.tools.corba.ee.idl.ParseException.illegalException(scanner, entryName(entry)); + declarator (typedef); + branch.typedef = typedef; + // Ensure a branch with the same name doesn't already exist. + if (entry.has (typedef)) + com.sun.tools.corba.ee.idl.ParseException.branchName(scanner, typedef.name()); + } // elementSpec + + /** + * + **/ + private com.sun.tools.corba.ee.idl.EnumEntry enumType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Enum); + com.sun.tools.corba.ee.idl.EnumEntry enumEntry = newEnumEntry (entry); + // comment must immediately precede "enum" keyword + enumEntry.comment (tokenHistory.lookBack (1).comment); + enumEntry.name (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + prep.openScope (enumEntry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace); + if (isntInStringList (enumEntry.elements (), token.name)) + { + enumEntry.addElement (token.name); + com.sun.tools.corba.ee.idl.SymtabEntry element = new com.sun.tools.corba.ee.idl.SymtabEntry(entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + // if block taken from EnumEntry ctor + if (element.module ().equals ("")) + element.module (element.name ()); + else if (!element.name ().equals ("")) + element.module (element.module () + "/" + element.name ()); + element.name (token.name); + // Place the SymtabEntry representing this enumeration + // contant into the SymtabEntry defining its scope (e.g., InterfaceEntry, + // ValueEntry, etc.) rather than the SymtabEntry passed in, which + // may not define the contant's scope (e.g., TypedefEntry). + //pigeonhole (entry, element); } + pigeonhole (enumEntry.container (), element); + } + match (com.sun.tools.corba.ee.idl.Token.Identifier); + enumType2 (enumEntry); + prep.closeScope (enumEntry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace); + return enumEntry; + } // enumType + + /** + * + **/ + private void enumType2 (com.sun.tools.corba.ee.idl.EnumEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (token.type == com.sun.tools.corba.ee.idl.Token.Comma) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + String name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + if (isntInStringList (entry.elements (), name)) + { + entry.addElement (name); + com.sun.tools.corba.ee.idl.SymtabEntry element = new com.sun.tools.corba.ee.idl.SymtabEntry(entry.container (), (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + // if block taken from EnumEntry ctor: + if (element.module ().equals ("")) + element.module (element.name ()); + else if (!element.name().equals ("")) + element.module (element.module () + "/" + element.name ()); + element.name (name); + pigeonhole (entry.container (), element); + } + } + } // enumType2 + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SequenceEntry sequenceType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Sequence); + match (com.sun.tools.corba.ee.idl.Token.LessThan); + + com.sun.tools.corba.ee.idl.SequenceEntry newEntry = newSequenceEntry (entry); + com.sun.tools.corba.ee.idl.SymtabEntry tsentry = simpleTypeSpec (newEntry, false ); + newEntry.type (tsentry); + if (!tsentry.isReferencable()) { + // This is a sequence type that is referencing an + // incomplete forward declaration of a struct or + // union. Save the sequence in a list for later + // backpatching. + try { + List fwdTypes = (List)tsentry.dynamicVariable( ftlKey ) ; + if (fwdTypes == null) { + fwdTypes = new ArrayList() ; + tsentry.dynamicVariable( ftlKey, fwdTypes ) ; + } + fwdTypes.add( newEntry ) ; + } catch (NoSuchFieldException exc) { + throw new IllegalStateException() ; + } + } + + if (token.type == com.sun.tools.corba.ee.idl.Token.Comma) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + com.sun.tools.corba.ee.idl.ConstEntry tmpEntry = stFactory.constEntry (newEntry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + tmpEntry.sourceFile (scanner.fileEntry ()); + tmpEntry.type (qualifiedEntry ("long")); + newEntry.maxSize (positiveIntConst (tmpEntry)); + verifyConstType (newEntry.maxSize(), qualifiedEntry ("long")); + } + match (com.sun.tools.corba.ee.idl.Token.GreaterThan); + return newEntry; + } // sequenceType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.StringEntry stringType (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.StringEntry string = stFactory.stringEntry (); + if (token.type == com.sun.tools.corba.ee.idl.Token.String) + { + string.name (overrideName ("string")); + match (com.sun.tools.corba.ee.idl.Token.String); + } + else + { + string.name (overrideName ("wstring")); + match (com.sun.tools.corba.ee.idl.Token.Wstring); + } + string.maxSize (stringType2 (entry)); + return string; + } // stringType + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression stringType2 (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type == com.sun.tools.corba.ee.idl.Token.LessThan) + { + match (com.sun.tools.corba.ee.idl.Token.LessThan); + + // START IBM.11417 failure in the IDL compiler + //Expression maxSize = positiveIntConst (entry); IBM.11417 + + com.sun.tools.corba.ee.idl.ConstEntry tmpEntry = stFactory.constEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek +()); + tmpEntry.sourceFile (scanner.fileEntry ()); + tmpEntry.type (qualifiedEntry ("long")); + com.sun.tools.corba.ee.idl.constExpr.Expression maxSize = positiveIntConst (tmpEntry); + + // END IBM.11417 + + verifyConstType (maxSize, qualifiedEntry ("long")); + match (com.sun.tools.corba.ee.idl.Token.GreaterThan); + return maxSize; + } + return null; + } // stringType2 + + /** + * + **/ + private void fixedArraySize (com.sun.tools.corba.ee.idl.TypedefEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.LeftBracket); + com.sun.tools.corba.ee.idl.ConstEntry tmpEntry = stFactory.constEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + tmpEntry.sourceFile (scanner.fileEntry ()); + // Set type of tmpExpr to "long", which is the array index type. + // Previously, this type was erroneously set to the array element type. + //tmpEntry.type (entry.type ()); + tmpEntry.type (qualifiedEntry ("long")); + com.sun.tools.corba.ee.idl.constExpr.Expression expr = positiveIntConst (tmpEntry); + entry.addArrayInfo (expr); + verifyConstType (expr, qualifiedEntry ("long")); + match (com.sun.tools.corba.ee.idl.Token.RightBracket); + } // fixedArraySize + + /** + * + **/ + private void attrDcl (com.sun.tools.corba.ee.idl.InterfaceEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.AttributeEntry attribute = stFactory.attributeEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + attribute.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede the "attribute" keyword. Save the + // comment preceding the declaration for use below. + attribute.comment (token.comment); + com.sun.tools.corba.ee.idl.Comment dclComment = attribute.comment (); + + if (token.type == com.sun.tools.corba.ee.idl.Token.Readonly) + { + match (com.sun.tools.corba.ee.idl.Token.Readonly); + attribute.readOnly (true); + } + match (com.sun.tools.corba.ee.idl.Token.Attribute); + attribute.type (paramTypeSpec (attribute)); + attribute.name (token.name); + // Override declaration comment if attribute identifier is commented + if (!token.comment.text ().equals ("")) + attribute.comment (token.comment); + entry.methodsAddElement (attribute, scanner); + pigeonholeMethod (entry, attribute); + // Declaration comment was overriden: + if (!token.comment.text ().equals ("")) + { + // Create a temporary attribute with declaration comment so cloning in + // attrdcl2() can use declaration comment as default. + com.sun.tools.corba.ee.idl.AttributeEntry attributeClone = (com.sun.tools.corba.ee.idl.AttributeEntry) attribute.clone (); + attributeClone.comment (dclComment); + + match (com.sun.tools.corba.ee.idl.Token.Identifier); + attrDcl2 (entry, attributeClone); + } + else + { + match (com.sun.tools.corba.ee.idl.Token.Identifier); + attrDcl2 (entry, attribute); + } + //match (Token.Identifier); + //attrDcl2 (entry, attribute); + } // attrDcl + + /** + * + **/ + private void attrDcl2 (com.sun.tools.corba.ee.idl.InterfaceEntry entry, com.sun.tools.corba.ee.idl.AttributeEntry clone) + throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (token.type == com.sun.tools.corba.ee.idl.Token.Comma) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + com.sun.tools.corba.ee.idl.AttributeEntry attribute = (com.sun.tools.corba.ee.idl.AttributeEntry)clone.clone (); + attribute.name (token.name); + // Override the declaration comment (i.e., that preceding the + // "attribute" keyword) if the attribute identifier is commented. + if (!token.comment.text ().equals ("")) + attribute.comment (token.comment); + entry.methodsAddElement (attribute, scanner); + pigeonholeMethod (entry, attribute); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + } // attrDcl2 + + /** + * + **/ + private void exceptDcl (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Exception); + com.sun.tools.corba.ee.idl.ExceptionEntry exceptEntry = stFactory.exceptionEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (token.name); + exceptEntry.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede "exception" keyword + exceptEntry.comment (tokenHistory.lookBack (1).comment); + exceptEntry.name (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + pigeonhole (entry, exceptEntry); + if (token.equals (com.sun.tools.corba.ee.idl.Token.LeftBrace)) + { + prep.openScope (exceptEntry); + match (com.sun.tools.corba.ee.idl.Token.LeftBrace); + memberList2 (exceptEntry); + prep.closeScope (exceptEntry); + match (com.sun.tools.corba.ee.idl.Token.RightBrace); + repIDStack.pop (); + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.LeftBrace, token.type); + } // exceptDcl + + /** + * + **/ + private void opDcl (com.sun.tools.corba.ee.idl.InterfaceEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.MethodEntry method = stFactory.methodEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + method.sourceFile (scanner.fileEntry ()); + // Comment must immediately precede "oneway" keyword or + method.comment (token.comment); + if (token.type == com.sun.tools.corba.ee.idl.Token.Oneway) + { + match (com.sun.tools.corba.ee.idl.Token.Oneway); + method.oneway (true); + } + method.type (opTypeSpec (method)); + repIDStack.push (((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).clone ()); + ((com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()).appendToName (token.name); + method.name (token.name); + entry.methodsAddElement (method, scanner); + pigeonholeMethod (entry, method); + opDcl2 (method); + if (method.oneway ()) + checkIfOpLegalForOneway (method); + repIDStack.pop (); + } // opDcl + + /** + * + **/ + private void checkIfOpLegalForOneway (com.sun.tools.corba.ee.idl.MethodEntry method) + { + boolean notLegal = false; + if ((method.type() != null) || + (method.exceptions().size() != 0)) notLegal = true; + else + { + for (Enumeration e = method.parameters().elements(); e.hasMoreElements();) + { + if (((com.sun.tools.corba.ee.idl.ParameterEntry)e.nextElement ()).passType () != com.sun.tools.corba.ee.idl.ParameterEntry.In) + { + notLegal = true; + break; + } + } + } + if (notLegal) + com.sun.tools.corba.ee.idl.ParseException.oneway(scanner, method.name()); + } // checkifOpLegalForOneway + + /** + * + **/ + private void opDcl2 (com.sun.tools.corba.ee.idl.MethodEntry method) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + { + match (com.sun.tools.corba.ee.idl.Token.MacroIdentifier); + parameterDcls2 (method); + } + else + { + match (com.sun.tools.corba.ee.idl.Token.Identifier); + parameterDcls (method); + } + opDcl3 (method); + } // opDcl2 + + /** + * + **/ + private void opDcl3 (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type != com.sun.tools.corba.ee.idl.Token.Semicolon) + { + if (!token.equals (com.sun.tools.corba.ee.idl.Token.Raises) && !token.equals (com.sun.tools.corba.ee.idl.Token.Context)) + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Raises, com.sun.tools.corba.ee.idl.Token.Context, com.sun.tools.corba.ee.idl.Token.Semicolon}, token.type); + if (token.type == com.sun.tools.corba.ee.idl.Token.Raises) + raisesExpr (entry); + if (token.type == com.sun.tools.corba.ee.idl.Token.Context) + contextExpr (entry); + } + } // opDcl3 + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry opTypeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.SymtabEntry ret = null; + if (token.type == com.sun.tools.corba.ee.idl.Token.Void) + match (com.sun.tools.corba.ee.idl.Token.Void); + else + ret = paramTypeSpec (entry); + return ret; + } // opTypeSpec + + /** + * + **/ + private void parameterDcls (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + parameterDcls2 (entry); + } // parameterDcls + + /** + * + **/ + private void parameterDcls2 (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type == com.sun.tools.corba.ee.idl.Token.RightParen) + match (com.sun.tools.corba.ee.idl.Token.RightParen); + else + { + paramDcl (entry); + while (token.type == com.sun.tools.corba.ee.idl.Token.Comma) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + paramDcl (entry); + } + match (com.sun.tools.corba.ee.idl.Token.RightParen); + } + } // paraneterDcls2 + + /** + * + **/ + private void paramDcl (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.ParameterEntry parmEntry = stFactory.parameterEntry (entry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + parmEntry.sourceFile (scanner.fileEntry ()); + // Comment must immeiately precede the parameter attribute + parmEntry.comment (token.comment); + paramAttribute (parmEntry); + parmEntry.type (paramTypeSpec (entry)); + parmEntry.name (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + if (isntInList (entry.parameters (), parmEntry.name ())) + entry.addParameter (parmEntry); + } // paramDcl + + /** + * + **/ + private void paramAttribute (com.sun.tools.corba.ee.idl.ParameterEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type == com.sun.tools.corba.ee.idl.Token.In) + { + entry.passType (com.sun.tools.corba.ee.idl.ParameterEntry.In); + match (com.sun.tools.corba.ee.idl.Token.In); + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.Out) + { + entry.passType (com.sun.tools.corba.ee.idl.ParameterEntry.Out); + match (com.sun.tools.corba.ee.idl.Token.Out); + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.Inout) + { + entry.passType (com.sun.tools.corba.ee.idl.ParameterEntry.Inout); + match (com.sun.tools.corba.ee.idl.Token.Inout); + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.In, com.sun.tools.corba.ee.idl.Token.Out, com.sun.tools.corba.ee.idl.Token.Inout}, token.type); + } // paramAttribute + + /** + * + **/ + private void raisesExpr (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Raises); + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + // Comment must immediately precede for exception + com.sun.tools.corba.ee.idl.Comment tempComment = token.comment; + com.sun.tools.corba.ee.idl.SymtabEntry exception = scopedName(entry.container (), stFactory.exceptionEntry ()); + if (typeOf (exception) instanceof com.sun.tools.corba.ee.idl.ExceptionEntry) + { + // Comment must immediately precede for exception + exception.comment (tempComment); + if (isntInList (entry.exceptions (), exception)) + entry.exceptionsAddElement ((com.sun.tools.corba.ee.idl.ExceptionEntry) exception); + } + else + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, exception.fullName(), + "exception", entryName(exception.type())); + raisesExpr2 (entry); + match (com.sun.tools.corba.ee.idl.Token.RightParen); + } // raisesExpr + + /** + * + **/ + private void raisesExpr2 (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (token.type == com.sun.tools.corba.ee.idl.Token.Comma) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + // Comment must immediately precede of exception + com.sun.tools.corba.ee.idl.Comment tempComment = token.comment; + com.sun.tools.corba.ee.idl.SymtabEntry exception = scopedName (entry.container (), stFactory.exceptionEntry ()); + if (typeOf (exception) instanceof com.sun.tools.corba.ee.idl.ExceptionEntry) + { + // Comment must immediately precede of exception + exception.comment (tempComment); + if (isntInList (entry.exceptions (), exception)) + entry.addException ((com.sun.tools.corba.ee.idl.ExceptionEntry)exception); + } + else + com.sun.tools.corba.ee.idl.ParseException.wrongType(scanner, exception.fullName(), + "exception", entryName(exception.type())); + } + } // raisesExpr2 + + /** + * + **/ + private void contextExpr (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Context); + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + String stringLit = (String)stringLiteral ().value (); + if (isntInStringList (entry.contexts (), stringLit)) + entry.addContext (stringLit); + contextExpr2 (entry); + match (com.sun.tools.corba.ee.idl.Token.RightParen); + } // contextExpr + + + private void contextExpr2 (com.sun.tools.corba.ee.idl.MethodEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (token.type == com.sun.tools.corba.ee.idl.Token.Comma) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + String stringLit = (String)stringLiteral ().value (); + if (isntInStringList (entry.contexts (), stringLit)) + entry.addContext (stringLit); + } + } // contextExpr2 + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SymtabEntry paramTypeSpec (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.SymtabEntry ret = null; + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Float: + case com.sun.tools.corba.ee.idl.Token.Double: + case com.sun.tools.corba.ee.idl.Token.Long: + case com.sun.tools.corba.ee.idl.Token.Short: + case com.sun.tools.corba.ee.idl.Token.Unsigned: + case com.sun.tools.corba.ee.idl.Token.Char: + case com.sun.tools.corba.ee.idl.Token.Wchar: + case com.sun.tools.corba.ee.idl.Token.Boolean: + case com.sun.tools.corba.ee.idl.Token.Octet: + case com.sun.tools.corba.ee.idl.Token.Any: + return baseTypeSpec (entry); + case com.sun.tools.corba.ee.idl.Token.String: + case com.sun.tools.corba.ee.idl.Token.Wstring: + return stringType (entry); + case com.sun.tools.corba.ee.idl.Token.Identifier: + case com.sun.tools.corba.ee.idl.Token.Object: + // + case com.sun.tools.corba.ee.idl.Token.ValueBase: + case com.sun.tools.corba.ee.idl.Token.DoubleColon: + ret = scopedName (entry.container (), stFactory.primitiveEntry ()); + if (typeOf (ret) instanceof com.sun.tools.corba.ee.idl.AttributeEntry) + //ParseException.attributeParamType (scanner); + com.sun.tools.corba.ee.idl.ParseException.attributeNotType(scanner, ret.name()); + else // + if (typeOf (ret) instanceof com.sun.tools.corba.ee.idl.MethodEntry) + com.sun.tools.corba.ee.idl.ParseException.operationNotType(scanner, ret.name()); + + //if (!(returnType instanceof PrimitiveEntry || + // returnType instanceof StringEntry)) + //ParseException.wrongType (scanner, ret.fullName(), + // "primitive or string", entryName (ret.type())); + break; + default: + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, new int[]{ + com.sun.tools.corba.ee.idl.Token.Float, com.sun.tools.corba.ee.idl.Token.Double, com.sun.tools.corba.ee.idl.Token.Long, com.sun.tools.corba.ee.idl.Token.Short, + com.sun.tools.corba.ee.idl.Token.Unsigned, com.sun.tools.corba.ee.idl.Token.Char, com.sun.tools.corba.ee.idl.Token.Wchar, com.sun.tools.corba.ee.idl.Token.Boolean, + com.sun.tools.corba.ee.idl.Token.Octet, com.sun.tools.corba.ee.idl.Token.Any, com.sun.tools.corba.ee.idl.Token.String, com.sun.tools.corba.ee.idl.Token.Wstring, + com.sun.tools.corba.ee.idl.Token.Identifier, com.sun.tools.corba.ee.idl.Token.DoubleColon, com.sun.tools.corba.ee.idl.Token.ValueBase}, token.type); + } + return ret; + } // paramTypeSpec + + /** + * + **/ + private void match (int type) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.ParseException exception = null; + if (!token.equals (type)) + { + exception = com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, type, token.type); + // Missing a semicolon is a common error. If a semicolon was expected, + // assume it exists and keep the current token (don't get the next one). + // BEWARE!!! THIS HAS THE POTENTIAL FOR AN INFINITE LOOP! + if (type == com.sun.tools.corba.ee.idl.Token.Semicolon) + return; + } + // Unecessary due to new valueElement() algorithm. + //if (!tokenStack.empty()) + //{ + // token = (Token)tokenStack.pop (); + // return; + //} + + // Fetch the next token. + token = scanner.getToken (); + + // Issue warnings about tokens. + issueTokenWarnings (); + + // Maintain history of most recent tokens. + tokenHistory.insert (token); + + // Identifiers that collide with keywords are illegal. Note + // that escaped identifers never collide! + /* + if (token.collidesWithKeyword ()) + { + // Issue a warning only + if (corbaLevel <= 2.2f) + ParseException.keywordCollisionWarning (scanner, token.name); + else + exception = ParseException.keywordCollision (scanner, token.name); + } + */ + + while (token.isDirective ()) + token = prep.process (token); + + // If the token is a defined thingy, scan the defined string + // instead of the input stream for a while. + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier) || token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + { + String string = (String)symbols.get (token.name); + if (string != null && !string.equals ("")) + { + // If this is a macro, parse the macro + if (macros.contains (token.name)) + { + scanner.scanString (prep.expandMacro (string, token)); + match (token.type); + } + else // This is just a normal define. + { + scanner.scanString (string); + match (token.type); + } + } + } + if (exception != null) + throw exception; + } // match + + // + /** + * Issue warnings according to attributes of current Token. + **/ + private void issueTokenWarnings () + { + if (noWarn) + return; + + if ((token.equals (com.sun.tools.corba.ee.idl.Token.Identifier) || token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + && !token.isEscaped ()) + { + // Identifier collision with keyword in another release. + // Identifier collision with keyword in letter, but not in case. + if (token.collidesWithKeyword ()) + com.sun.tools.corba.ee.idl.ParseException.warning (scanner, com.sun.tools.corba.ee.idl.Util.getMessage("Migration.keywordCollision", token.name)); + } + // Deprecated keyword. + if (token.isKeyword () && token.isDeprecated ()) + com.sun.tools.corba.ee.idl.ParseException.warning (scanner, com.sun.tools.corba.ee.idl.Util.getMessage("Deprecated.keyword", token.toString())); + } // issueTokenWarnings + + /** + * + **/ + private com.sun.tools.corba.ee.idl.ModuleEntry newModule (com.sun.tools.corba.ee.idl.ModuleEntry oldEntry) + { + com.sun.tools.corba.ee.idl.ModuleEntry entry = stFactory.moduleEntry (oldEntry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (token.name); + // If this named module already exists, just reopen it. + /* <46082.46.01> if cppModule, always create new module entry */ + com.sun.tools.corba.ee.idl.SymtabEntry prevEntry = (com.sun.tools.corba.ee.idl.SymtabEntry) symbolTable.get (entry.fullName ()); + if (!cppModule && prevEntry != null && prevEntry instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + { + // A module has been reopened, return that ModuleEntry. + entry = (com.sun.tools.corba.ee.idl.ModuleEntry) prevEntry; + if (oldEntry == topLevelModule) + { + // Do a little checking: + if (!entry.emit ()) + // The entry module is being reopened to put new stuff into it. + // The module itself is not marked as "emit", but the new stuff + // may be, so put the module on the emitList (add it to topLevelModule). + addToContainer (oldEntry, entry); + else if (!oldEntry.contained().contains (entry)) + // The entry module being reopened is to be emitted, but + // will not be placed on the emitList! I.E., it was not added to + // topLevelModule. Occurs when a generator manually inserts + // ModuleEntrys into the symbol table (e.g., org; see preParse() + // in ...idl.toJava.Compile). + addToContainer (oldEntry, entry); + } + } + else + pigeonhole (oldEntry, entry); + return entry; + } // newModule + + /** + * + **/ + private com.sun.tools.corba.ee.idl.EnumEntry newEnumEntry (com.sun.tools.corba.ee.idl.SymtabEntry oldEntry) + { + com.sun.tools.corba.ee.idl.EnumEntry entry = stFactory.enumEntry (oldEntry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (token.name); + pigeonhole (oldEntry, entry); + return entry; + } // newEnumEntry + + /** + * + **/ + private com.sun.tools.corba.ee.idl.SequenceEntry newSequenceEntry (com.sun.tools.corba.ee.idl.SymtabEntry oldEntry) + { + com.sun.tools.corba.ee.idl.SequenceEntry entry = stFactory.sequenceEntry (oldEntry, (com.sun.tools.corba.ee.idl.IDLID)repIDStack.peek ()); + entry.sourceFile (scanner.fileEntry ()); + entry.name (""); + pigeonhole (oldEntry, entry); + return entry; + } // newSequenceEntry + + private void updateSymbolTable( String fullName, com.sun.tools.corba.ee.idl.SymtabEntry entry, boolean lcCheck ) + { + // Check for case-insensitive collision (IDL error). + String lcFullName = fullName.toLowerCase(); + if (lcCheck) + if (lcSymbolTable.get (lcFullName) != null) { + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, fullName); + } + symbolTable.put (fullName, entry); + lcSymbolTable.put (lcFullName, entry); + // Allow fully-qualified CORBA types to be resolved by mapping + // short name (e.g., CORBA/StringValue) to long name, actual name. + String omgPrefix = "org/omg/CORBA" ; + if (fullName.startsWith (omgPrefix)) { + overrideNames.put ( + "CORBA" + fullName.substring (omgPrefix.length()), fullName); + } + } + + private void pigeonhole (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + if (entry.name().equals ("")) + entry.name (unknownNamePrefix + ++sequence); + + // If this object is not in the overrides list, then it is + // ok to put it in the table (if it IS in the overrides list, + // it is already in the table under a different name). + String fullName = entry.fullName(); + if (overrideNames.get (fullName) == null) { + addToContainer (container, entry); + + // It is an error is this name already exists in the symbol + // table, unless this is a redefinition of a forward decl. + // Re-opening a module is also legal, but not handled here. + com.sun.tools.corba.ee.idl.SymtabEntry oldEntry = (com.sun.tools.corba.ee.idl.SymtabEntry) symbolTable.get (fullName); + + if (oldEntry == null) { + updateSymbolTable( fullName, entry, true ) ; + } else if (oldEntry instanceof com.sun.tools.corba.ee.idl.ForwardEntry && + entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) { + + String repIDPrefix = ((com.sun.tools.corba.ee.idl.IDLID)entry.repositoryID ()).prefix (); + String oldRepIDPrefix = ((com.sun.tools.corba.ee.idl.IDLID)oldEntry.repositoryID ()).prefix (); + if (repIDPrefix.equals (oldRepIDPrefix)) { + updateSymbolTable( fullName, entry, false ) ; + } else { + com.sun.tools.corba.ee.idl.ParseException.badRepIDPrefix(scanner, fullName, + oldRepIDPrefix, repIDPrefix); + } + } else if (entry instanceof com.sun.tools.corba.ee.idl.ForwardEntry && + (oldEntry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry || + oldEntry instanceof com.sun.tools.corba.ee.idl.ForwardEntry)) { + if (oldEntry instanceof com.sun.tools.corba.ee.idl.ForwardEntry && + entry.repositoryID () instanceof com.sun.tools.corba.ee.idl.IDLID && + oldEntry.repositoryID () instanceof com.sun.tools.corba.ee.idl.IDLID) { + + String repIDPrefix = + ((com.sun.tools.corba.ee.idl.IDLID)entry.repositoryID ()).prefix (); + String oldRepIDPrefix = + ((com.sun.tools.corba.ee.idl.IDLID)oldEntry.repositoryID ()).prefix (); + + if (!(repIDPrefix.equals (oldRepIDPrefix))) { + // Disallow multiple ForwardEntry's having same Repository + // ID prefixes (CORBA 2.3). + com.sun.tools.corba.ee.idl.ParseException.badRepIDPrefix(scanner, fullName, + oldRepIDPrefix, repIDPrefix); + } + } + } else if (cppModule && entry instanceof com.sun.tools.corba.ee.idl.ModuleEntry && + oldEntry instanceof com.sun.tools.corba.ee.idl.ModuleEntry) { + // Allow multiple ModuleEntrys when user submits + // the -cppModule flag. + } else if (fullName.startsWith ("org/omg/CORBA") || + fullName.startsWith ("CORBA")) { + // Ignore CORBA PIDL types entered at preParse() by generator. + } else if (isForwardable( oldEntry, entry )) { + // Both oldEntry and entry are structs or unions. + // Legality depends on isReferencable on the two entries: + // oldEntry Entry + // T T ERROR alreadyDeclared + // T F legal fwd decl + // F T if defined in same file legal, + // otherwise ERROR + // F F legal fwd decl + if (oldEntry.isReferencable() && entry.isReferencable()) + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, fullName); + + if (entry.isReferencable()) { + String firstFile = + oldEntry.sourceFile().absFilename() ; + String defFile = + entry.sourceFile().absFilename() ; + if (!firstFile.equals( defFile )) + com.sun.tools.corba.ee.idl.ParseException.declNotInSameFile(scanner, + fullName, firstFile) ; + else { + updateSymbolTable( fullName, entry, false ) ; + + List oldRefList ; + + try { + oldRefList = (List)oldEntry.dynamicVariable( + ftlKey ) ; + } catch (NoSuchFieldException exc) { + throw new IllegalStateException() ; + } + + if (oldRefList != null) { + // Update entries in backpatch list + Iterator iter = oldRefList.iterator() ; + while (iter.hasNext()) { + com.sun.tools.corba.ee.idl.SymtabEntry elem = (com.sun.tools.corba.ee.idl.SymtabEntry)iter.next() ; + elem.type( entry ) ; + } + } + } + } + } else { + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, fullName); + } + } + } // pigeonhole + + private boolean isForwardable( com.sun.tools.corba.ee.idl.SymtabEntry oldEntry, + com.sun.tools.corba.ee.idl.SymtabEntry entry ) + { + return ((oldEntry instanceof com.sun.tools.corba.ee.idl.StructEntry) && + (entry instanceof com.sun.tools.corba.ee.idl.StructEntry)) || + ((oldEntry instanceof com.sun.tools.corba.ee.idl.UnionEntry) && + (entry instanceof com.sun.tools.corba.ee.idl.UnionEntry)) ; + } + + // pigeonhole checks to see if this entry is already in the symbol + // table and generates an error if it is. Methods must be checked + // not only against the symbol table but also against their + // interface's parent's methods. This is done in InterfaceEntry. + // verifyMethod, so no checking need be done here. + + /** + * + **/ + private void pigeonholeMethod (com.sun.tools.corba.ee.idl.InterfaceEntry container, com.sun.tools.corba.ee.idl.MethodEntry entry) + { + if (entry.name ().equals ("")) + entry.name (unknownNamePrefix + ++sequence); + + // If this object is not in the overrides list, then it is + // ok to put it in the table (if it IS in the overrides list, + // it is already in the table under a different name). + String fullName = entry.fullName (); + if (overrideNames.get (fullName) == null) + { + addToContainer (container, entry); + String lcFullName = fullName.toLowerCase (); + symbolTable.put (fullName, entry); + lcSymbolTable.put (lcFullName, entry); + // Allow fully-qualified CORBA types to be resolved by mapping + // short name (e.g., CORBA/StringValue) to long name, actual name. + if (fullName.startsWith ("org/omg/CORBA")) + overrideNames.put ("CORBA" + fullName.substring (13), fullName); + } + } // pigeonholeMethod + + /** + * + **/ + private void addToContainer (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.SymtabEntry contained) + { + if (container instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + ((com.sun.tools.corba.ee.idl.ModuleEntry)container).addContained (contained); + else if (container instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + ((com.sun.tools.corba.ee.idl.InterfaceEntry)container).addContained (contained); + else if (container instanceof com.sun.tools.corba.ee.idl.StructEntry) + ((com.sun.tools.corba.ee.idl.StructEntry)container).addContained (contained); + else if (container instanceof com.sun.tools.corba.ee.idl.UnionEntry) + ((com.sun.tools.corba.ee.idl.UnionEntry)container).addContained (contained); + else if (container instanceof com.sun.tools.corba.ee.idl.SequenceEntry) + ((com.sun.tools.corba.ee.idl.SequenceEntry)container).addContained (contained); + } // addToContainer + + // NOTE: qualifiedEntry/partlyQualifiedEntry/unqualifiedEntry and + // their court could probably use some performance improvements, + // but I'm scared to touch anything. It's the most complex bit of + // code in this parser. + + // The qualified named type is searched for in the following order: + // 1. OverrideNames + // 2. Global scope + // 3. Inheritance scope (if container is an interface) + // A qualified name is one which begins with :: or is assumed to be + // in the global scope (like long, short, etc). + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry qualifiedEntry (String typeName) + { + com.sun.tools.corba.ee.idl.SymtabEntry type = recursiveQualifiedEntry (typeName); + if (type == null) + // Then it's not anywhere, report the error. + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, typeName); + + // Relax this retriction when parsing ID pragma directive, e.g.. + //else if (type instanceof ModuleEntry) { + else if (type instanceof com.sun.tools.corba.ee.idl.ModuleEntry && !_isModuleLegalType) + { + // Module's are not valid types. + com.sun.tools.corba.ee.idl.ParseException.moduleNotType(scanner, typeName); + type = null; + } + return type; + } // qualifiedEntry + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry recursiveQualifiedEntry (String typeName) + { + com.sun.tools.corba.ee.idl.SymtabEntry type = null; + if (typeName != null && !typeName.equals ("void")) + { + int index = typeName.lastIndexOf ('/'); + if (index >= 0) + { + // Figure out if the container of this thing exists, converting any typedefs to interfaces if necessary. + type = recursiveQualifiedEntry (typeName.substring (0, index)); + if (type == null) + return null; + else if (type instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + typeName = typeOf (type).fullName () + typeName.substring (index); + } + + // If we got this far, a container exists, start over looking + // for the thing itself (this is the meat of the method): + type = searchOverrideNames (typeName); + if (type == null) + type = (com.sun.tools.corba.ee.idl.SymtabEntry) symbolTable.get (typeName); // search global scope: + if (type == null) + type = searchGlobalInheritanceScope (typeName); + } + return type; + } // recursiveQualifiedEntry + + // A partially qualified name is of the form ::. + // First the scope is defined (meaning it is fully qualified); + // Then the name is searched for in the scope. + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry partlyQualifiedEntry (String typeName, com.sun.tools.corba.ee.idl.SymtabEntry container) + { + // This is the simple logic of this method: + // type = searchModuleScope (typeName.substring (0, typeName.lastIndexOf ('/')), container); + // type = qualifiedEntry (type.fullName () + typeName.substring (typeName.lastIndexOf ('/'))); + // But searchModuleScope only finds the first module that fits. + // The name might not be in that module but in one further out + // in the module scope. Should others be searched? + com.sun.tools.corba.ee.idl.SymtabEntry type = null; + if (typeName != null) + { + int index = typeName.lastIndexOf ('/'); + + // Figure out if the container of this thing exists, converting any + // typedefs to interfaces if necessary: + type = recursivePQEntry (typeName.substring (0, index), container); + if (type instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + typeName = typeOf (type).fullName () + typeName.substring (index); + + // If we got this far, a container exists, start over looking + // for the thing itself. + + if (container != null) + type = searchModuleScope (typeName.substring (0, typeName.lastIndexOf ('/')), container); + if (type == null) + type = qualifiedEntry (typeName); + else + type = qualifiedEntry (type.fullName () + typeName.substring (typeName.lastIndexOf ('/'))); + } + return type; + } // partlyQualifiedEntry + + // partlyQualifiedEntry and recursivePQEntry are almost identical. + // They are different because when the recursive one is looking for + // the existence of containers, the error check for a module type + // must not occur (this check is done in qualifiedEntry). Only + // when the full partly qualified name is being processed must this + // check be performed. + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry recursivePQEntry (String typeName, com.sun.tools.corba.ee.idl.SymtabEntry container) + { + com.sun.tools.corba.ee.idl.SymtabEntry type = null; + if (typeName != null) + { + int index = typeName.lastIndexOf ('/'); + if (index < 0) + type = searchModuleScope (typeName, container); + else + { + // Figure out if the container of this thing exists, converting any + // typedefs to interfaces if necessary: + type = recursivePQEntry (typeName.substring (0, index), container); + if (type == null) + return null; + else if (type instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + typeName = typeOf (type).fullName () + typeName.substring (index); + + // If we got this far, a container exists, start over, looking + // for the thing itself (This is the meat of the method): + if (container != null) + type = searchModuleScope (typeName.substring (0, typeName.lastIndexOf ('/')), container); + if (type == null) + recursiveQualifiedEntry (typeName); + else + type = recursiveQualifiedEntry (type.fullName () + typeName.substring (typeName.lastIndexOf ('/'))); + } + } + return type; + } // recursivePQEntry + + // The named type is searched for in the following order: + // 1. Local scope + // 2. Inheritance scope + // 3. OverrideNames + // 4. Module scope + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry unqualifiedEntry (String typeName, com.sun.tools.corba.ee.idl.SymtabEntry container) + { + com.sun.tools.corba.ee.idl.SymtabEntry type = unqualifiedEntryWMod (typeName, container); + + // Relax this retriction in special cases, e.g., when + // parsing a ID pragma directive. + //if (type instanceof ModuleEntry) { + if (type instanceof com.sun.tools.corba.ee.idl.ModuleEntry && !_isModuleLegalType) + { + // Module's are not valid types: + com.sun.tools.corba.ee.idl.ParseException.moduleNotType(scanner, typeName); + type = null; + } + return type; + } // unqualifiedEntry + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry unqualifiedEntryWMod (String typeName, com.sun.tools.corba.ee.idl.SymtabEntry container) + { + com.sun.tools.corba.ee.idl.SymtabEntry type = null; + if ((typeName != null) && !typeName.equals ("void")) + { + // Search local scope: + type = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (container.fullName () + '/' + typeName); + if (type == null) + type = searchLocalInheritanceScope (typeName, container); + if (type == null) + type = searchOverrideNames (typeName); + if ((type == null) && (container != null)) + type = searchModuleScope (typeName, container); + if (type == null) + type = searchParentInheritanceScope (typeName, container); + } + if (type == null) + // Then it's not anywhere, report the error: + com.sun.tools.corba.ee.idl.ParseException.undeclaredType(scanner, typeName); + return type; + } // unqualifiedEntryWMod + + /** + * Walks up the enclosing scopes until it finds an interface type. Then, + * searches up that interface inheritance tree for the type definition. + * + * @param name type name to be searched for. + * @param ptype parent type entry. + **/ + com.sun.tools.corba.ee.idl.SymtabEntry searchParentInheritanceScope(String name, com.sun.tools.corba.ee.idl.SymtabEntry ptype) { + + String cname = ptype.fullName(); + + while ((ptype != null) && !(cname.equals ("")) && + !(ptype instanceof com.sun.tools.corba.ee.idl.InterfaceEntry)) { + int index = cname.lastIndexOf ('/'); + if (index < 0) { + cname = ""; + } else { + cname = cname.substring (0, index); + ptype = (com.sun.tools.corba.ee.idl.SymtabEntry) symbolTable.get(cname); + } + } + + if ((ptype == null) || !(ptype instanceof com.sun.tools.corba.ee.idl.InterfaceEntry)) { + return null; // could not find an enclosing interface type - give up. + } + + // check if the enclosing interface supports the type definition. + String fullName = ptype.fullName () + '/' + name; + com.sun.tools.corba.ee.idl.SymtabEntry type = (com.sun.tools.corba.ee.idl.SymtabEntry) symbolTable.get (fullName); + if (type != null) { + return type; // found type definition. + } + + // search up the interface inheritance tree. + return searchLocalInheritanceScope(name, ptype); + } + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry searchGlobalInheritanceScope (String name) + { + // See if the container of this named object is an interface: + int index = name.lastIndexOf ('/'); + com.sun.tools.corba.ee.idl.SymtabEntry entry = null; + if (index >= 0) + { + String containerName = name.substring (0, index); + entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (containerName); + entry = (entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + // It's an interface, now look in its inheritance scope: + ? searchLocalInheritanceScope (name.substring (index + 1), entry) + : null; + } + return entry; + } // searchGlobalInheritanceScope + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry searchLocalInheritanceScope (String name, com.sun.tools.corba.ee.idl.SymtabEntry container) + { + return (container instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + ? searchDerivedFrom (name, (com.sun.tools.corba.ee.idl.InterfaceEntry) container) + : null; + } // searchLocalInheritanceScope + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry searchOverrideNames (String name) + { + String overrideName = (String)overrideNames.get (name); + return (overrideName != null) + ? (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (overrideName) + : null; + } // searchOverrideNames + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry searchModuleScope (String name, com.sun.tools.corba.ee.idl.SymtabEntry container) + { + String module = container.fullName (); + String fullName = module + '/' + name; + com.sun.tools.corba.ee.idl.SymtabEntry type = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (fullName); + while ((type == null) && !module.equals ("")) + { + int index = module.lastIndexOf ('/'); + if (index < 0) + module = ""; + else + { + module = module.substring (0, index); + fullName = module + '/' + name; + type = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (fullName); + } + } + return (type == null) ? (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name) : type; + } // searchModuleScope + + /** + * + **/ + com.sun.tools.corba.ee.idl.SymtabEntry searchDerivedFrom (String name, com.sun.tools.corba.ee.idl.InterfaceEntry i) + { + for (Enumeration e = i.derivedFrom ().elements (); e.hasMoreElements ();) + { + com.sun.tools.corba.ee.idl.SymtabEntry tmp = (com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement (); + if (tmp instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + { + com.sun.tools.corba.ee.idl.InterfaceEntry parent = (com.sun.tools.corba.ee.idl.InterfaceEntry)tmp; + String fullName = parent.fullName () + '/' + name; + com.sun.tools.corba.ee.idl.SymtabEntry type = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (fullName); + if (type != null) + return type; + type = searchDerivedFrom (name, parent); + if (type != null) + return type; + } + // else it is a ForwardEntry and nothing can be done at this point. + } + return null; + } // searchDerivedFrom + + /** + * + **/ + String entryName (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + if (entry instanceof com.sun.tools.corba.ee.idl.AttributeEntry) + return "attribute"; + if (entry instanceof com.sun.tools.corba.ee.idl.ConstEntry) + return "constant"; + if (entry instanceof com.sun.tools.corba.ee.idl.EnumEntry) + return "enumeration"; + if (entry instanceof com.sun.tools.corba.ee.idl.ExceptionEntry) + return "exception"; + if (entry instanceof com.sun.tools.corba.ee.idl.ValueBoxEntry) + return "value box"; + if (entry instanceof com.sun.tools.corba.ee.idl.ForwardValueEntry || entry instanceof com.sun.tools.corba.ee.idl.ValueEntry) + return "value"; + if (entry instanceof com.sun.tools.corba.ee.idl.ForwardEntry || entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + return "interface"; + if (entry instanceof com.sun.tools.corba.ee.idl.MethodEntry) + return "method"; + if (entry instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + return "module"; + if (entry instanceof com.sun.tools.corba.ee.idl.ParameterEntry) + return "parameter"; + if (entry instanceof com.sun.tools.corba.ee.idl.PrimitiveEntry) + return "primitive"; + if (entry instanceof com.sun.tools.corba.ee.idl.SequenceEntry) + return "sequence"; + if (entry instanceof com.sun.tools.corba.ee.idl.StringEntry) + return "string"; + if (entry instanceof com.sun.tools.corba.ee.idl.StructEntry) + return "struct"; + if (entry instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + return "typedef"; + if (entry instanceof com.sun.tools.corba.ee.idl.UnionEntry) + return "union"; + return "void"; + } // entryName + + /** + * + **/ + private boolean isInterface (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + return entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry || (entry instanceof com.sun.tools.corba.ee.idl.ForwardEntry + && !(entry instanceof com.sun.tools.corba.ee.idl.ForwardValueEntry)) ; + } + + private boolean isValue (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + return entry instanceof com.sun.tools.corba.ee.idl.ValueEntry; // || entry instanceof ForwardValueEntry; + } + + private boolean isInterfaceOnly (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + return entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry; + } + + private boolean isForward(com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + return entry instanceof com.sun.tools.corba.ee.idl.ForwardEntry; + } + + // list must be a vector of Strings. + /** + * + **/ + private boolean isntInStringList (Vector list, String name) + { + boolean isnt = true; + Enumeration e = list.elements (); + while (e.hasMoreElements ()) + if (name.equals ((String)e.nextElement ())) + { + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, name); + isnt = false; + break; + } + return isnt; + } // isntInStringList + + // list must be a vector of SymtabEntry's. + /** + * + **/ + private boolean isntInList (Vector list, String name) + { + boolean isnt = true; + for (Enumeration e = list.elements (); e.hasMoreElements ();) + if (name.equals (((com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement ()).name ())) + { + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, name); + isnt = false; + break; + } + return isnt; + } // isntInList + + // list must be a vector of SymtabEntry's. + /** + * + **/ + private boolean isntInList (Vector list, com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + boolean isnt = true; + for (Enumeration e = list.elements (); e.hasMoreElements ();) + { + com.sun.tools.corba.ee.idl.SymtabEntry eEntry = (com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement (); + if (entry == eEntry) // && entry.fullName().equals (eEntry.fullName())) + { + com.sun.tools.corba.ee.idl.ParseException.alreadyDeclared(scanner, entry.fullName()); + isnt = false; + break; + } + } + return isnt; + } // isntInList + + /** + * + **/ + public static com.sun.tools.corba.ee.idl.SymtabEntry typeOf (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + while (entry instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + entry = entry.type (); + return entry; + } // typeOf + + /** + * + **/ + void forwardEntryCheck () + { + for (Enumeration e = symbolTable.elements (); e.hasMoreElements ();) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)e.nextElement (); + if (entry instanceof com.sun.tools.corba.ee.idl.ForwardEntry) + com.sun.tools.corba.ee.idl.ParseException.forwardEntry(scanner, entry.fullName()); + } + } // forwardEntryCheck + + // <46082.03> Revert to "IDL:"-style (i.e., regular) repository ID. + /* + void updateRepositoryIds () { + for (Enumeration e = symbolTable.elements(); e.hasMoreElements();) { + SymtabEntry entry = (SymtabEntry) e.nextElement(); + if (entry instanceof ValueEntry) + ((ValueEntry) entry).calcRepId(); + } + } // updateRepositoryIds + */ + + //////////////////// + // Error Handling Methods + + // A syntax error occurred. Skip until a semicolon is encountered. + // Ignore semicolons within {...} blocks + /** + * + **/ + private void skipToSemicolon () throws IOException + { + while (!token.equals (com.sun.tools.corba.ee.idl.Token.EOF) && !token.equals (com.sun.tools.corba.ee.idl.Token.Semicolon)) + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.LeftBrace)) + skipToRightBrace(); + try + { + match (token.type); + } + catch (com.sun.tools.corba.ee.idl.ParseException exception) + { + // The error has already been reported... + } + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.EOF)) + throw new EOFException (); + try + { + match (com.sun.tools.corba.ee.idl.Token.Semicolon); + } + catch (Exception exception) + { + } + } // skipToSemicolon + + /** + * + **/ + private void skipToRightBrace () throws IOException + { + boolean firstTime = true; + while (!token.equals (com.sun.tools.corba.ee.idl.Token.EOF) && !token.equals (com.sun.tools.corba.ee.idl.Token.RightBrace)) + { + if (firstTime) + firstTime = false; + else if (token.equals (com.sun.tools.corba.ee.idl.Token.LeftBrace)) + skipToRightBrace (); + try + { + match (token.type); + } + catch (com.sun.tools.corba.ee.idl.ParseException exception) + { + // The error has already been reported... + } + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.EOF)) + throw new EOFException(); + } // skipToRightBrace + + // Error Handling Methods + //////////////////// + + // In CORBA 2.3, an IDL file provides a new scope for Repository IDs. + // The following methods provide a means for other classes in the framework + // to manage this scoping (see Preprocessor and Scanner). + + // public static int nPush = 0; + // public static int nPop = 0; + + /** + * + **/ + public static void enteringInclude () + { + repIDStack.push (new com.sun.tools.corba.ee.idl.IDLID()); + } // enteringInclude + + /** + * + **/ + public static void exitingInclude () + { + repIDStack.pop (); + } // exitingInclude + + + public static final String unknownNamePrefix = "uN__"; + + static Hashtable symbolTable; + Hashtable lcSymbolTable = new Hashtable (); + static Hashtable overrideNames; + Vector emitList = new Vector (); + boolean emitAll; + // + boolean cppModule; + // + boolean noWarn; + com.sun.tools.corba.ee.idl.Scanner scanner; + // No longer necessary due to new valueElement() algorithm. + // Stack tokenStack = new Stack(); + Hashtable symbols; + Vector macros = new Vector (); + Vector paths; + + // Only needed for the pragma directive + com.sun.tools.corba.ee.idl.SymtabEntry currentModule = null; + + // Static field necessary to allow Scanner access to enterind/exiting + // Include() methods. Must reset in Compile class, too! + // Stack repIDStack = new Stack (); + static Stack repIDStack = new Stack (); + + // Dynamic variable key used for forward type lists. + // A struct or union X entry may have this attached, + // which always contains a List. + // The elements are entries E such that E.type() == X. + // This list must be resolved in pigeonhole when the + // type is finally defined. This is similar to + // ForwardEntry.replaceForwardDecl. + private static int ftlKey = com.sun.tools.corba.ee.idl.SymtabEntry.getVariableKey() ; + + int sequence = 0; + Vector includes; + Vector includeEntries; + + // Only needed in primaryExpr. Set in Preprocessor.booleanConstExpr. + boolean parsingConditionalExpr = false; + + com.sun.tools.corba.ee.idl.Token token; + com.sun.tools.corba.ee.idl.ModuleEntry topLevelModule; + private com.sun.tools.corba.ee.idl.Preprocessor prep; + private boolean verbose; + com.sun.tools.corba.ee.idl.SymtabFactory stFactory; + com.sun.tools.corba.ee.idl.constExpr.ExprFactory exprFactory; + private String[] keywords; + // Remove -stateful feature. + //private boolean parseStateful = false; + + // Circular buffer containing most recent tokens, including the current token. + private com.sun.tools.corba.ee.idl.TokenBuffer tokenHistory = new com.sun.tools.corba.ee.idl.TokenBuffer(); + protected float corbaLevel; // + private com.sun.tools.corba.ee.idl.Arguments arguments; + +} // class Parser + + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaEntry.java new file mode 100644 index 000000000..15b34b0cf --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaEntry.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for the #pragma statement. + **/ +public class PragmaEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected PragmaEntry () + { + super (); + repositoryID (Util.emptyID); + } // ctor + + protected PragmaEntry (com.sun.tools.corba.ee.idl.SymtabEntry that) + { + super (that, new com.sun.tools.corba.ee.idl.IDLID()); + module (that.name ()); + name (""); + } // ctor + + protected PragmaEntry (PragmaEntry that) + { + super (that); + } // ctor + + public Object clone () + { + return new PragmaEntry (this); + } // clone + + /** Invoke the Include type generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + pragmaGen.generate (symbolTable, this, stream); + } // generate + + /** Access the Include type generator. + @return an object which implements the IncludeGen interface. + @see com.sun.tools.corba.ee.idl.IncludeGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return pragmaGen; + } // generator + + public String data () + { + return _data; + } // data + + public void data (String newData) + { + _data = newData; + } // data + + static com.sun.tools.corba.ee.idl.PragmaGen pragmaGen; + + private String _data = null; +} // class PragmaEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaGen.java new file mode 100644 index 000000000..bb7c87ab1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface PragmaGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.PragmaEntry entry, PrintWriter stream); +} // interface PragmaGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaHandler.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaHandler.java new file mode 100644 index 000000000..d7bad883f --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PragmaHandler.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// - Add openScope and closeScope. + +import java.io.IOException; + +public abstract class PragmaHandler +{ + public abstract boolean process (String pragma, String currentToken) throws IOException; + + void init (com.sun.tools.corba.ee.idl.Preprocessor p) + { + preprocessor = p; + } // init + + // Utility methods. + + /** Get the current token. */ + protected String currentToken () + { + return preprocessor.currentToken (); + } // currentToken + + /** This method, given an entry name, returns the entry with that name. + It can take fully or partially qualified names and returns the + appropriate entry defined within the current scope. If no entry + exists, null is returned. */ + protected SymtabEntry getEntryForName (String string) + { + return preprocessor.getEntryForName (string); + } // getEntryForName + + /** This method returns a string of all of the characters from the input + file from the current position up to, but not including, the end-of-line + character(s). */ + protected String getStringToEOL () throws IOException + { + return preprocessor.getStringToEOL (); + } // getStringToEOL + + /** This method returns a string of all of the characters from the input + file from the current position up to, but not including, the given + character. It encapsulates parenthesis and quoted strings, meaning + it does not stop if the given character is found within parentheses + or quotes. For instance, given the input of `start(inside)end', + getUntil ('n') will return "start(inside)e" */ + protected String getUntil (char c) throws IOException + { + return preprocessor.getUntil (c); + } // getUntil + + /** This method returns the next token String from the input file. */ + protected String nextToken () throws IOException + { + return preprocessor.nextToken (); + } // nextToken + + /** This method assumes that the current token marks the beginning + of a scoped name. It then parses the subsequent identifier and + double colon tokens, builds the scoped name, and finds the symbol + table entry with that name. */ + protected SymtabEntry scopedName () throws IOException + { + return preprocessor.scopedName (); + } // scopedName + + /** Skip to the end of the line. */ + protected void skipToEOL () throws IOException + { + preprocessor.skipToEOL (); + } // skipToEOL + + /** This method skips the data in the input file until the specified + character is encountered, then it returns the next token. */ + protected String skipUntil (char c) throws IOException + { + return preprocessor.skipUntil (c); + } // skipUntil + + /** This method displays a Parser Exception complete with line number + and position information with the given message string. */ + protected void parseException (String message) + { + preprocessor.parseException (message); + } // parseException + + /** This method is called when the parser encounters a left curly brace. + An extender of PragmaHandler may find scope information useful. + For example, the prefix pragma takes effect as soon as it is + encountered and stays in effect until the current scope is closed. + If a similar pragma extension is desired, then the openScope and + closeScope methods are available for overriding. + @param entry the symbol table entry whose scope has just been opened. + Be aware that, since the scope has just been entered, this entry is + incomplete at this point. */ + protected void openScope (SymtabEntry entry) + { + } // openScope + + /** This method is called when the parser encounters a right curly brace. + An extender of PragmaHandler may find scope information useful. + For example, the prefix pragma takes effect as soon as it is + encountered and stays in effect until the current scope is closed. + If a similar pragma extension is desired, then the openScope and + closeScope methods are available for overriding. + @param entry the symbol table entry whose scope has just been closed. */ + protected void closeScope (SymtabEntry entry) + { + } // closeScope + + private com.sun.tools.corba.ee.idl.Preprocessor preprocessor = null; +} // class PragmaHandler diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Preprocessor.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Preprocessor.java new file mode 100644 index 000000000..039e4387a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Preprocessor.java @@ -0,0 +1,1403 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -D57110 Allow ID pragma directive to be applied to modules and update +// feature in accordance to CORBA 2.3. +// -D59165 Enable escaped identifiers when processing pragmas. +// -f60858.1 Support -corba option, level = 2.2: Accept identifiers that +// collide with keywords, in letter but not case, and issue a warning. +// -d62023 support -noWarn option; suppress inappropriate warnings when +// parsing IBM-specific pragmas (#meta abstract). + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Stack; +import java.util.Vector; + +/** + * This class should be extended if new pragmas are desired. If the + * preprocessor encounters a pragma name which it doesn't recognize + * (anything other than ID, prefix, or version), it calls the method + * otherPragmas. This is the only method which need be overridden. + * The Preprocessor base class has a number of utility-like methods + * which can be used by the overridden otherPragmas method. + **/ +public class Preprocessor +{ + /** + * Public zero-argument constructor. + **/ + Preprocessor () + { + } // ctor + + /** + * + **/ + void init (com.sun.tools.corba.ee.idl.Parser p) + { + parser = p; + symbols = p.symbols; + macros = p.macros; + } // init + + /** + * + **/ + protected Object clone () + { + return new Preprocessor (); + } // clone + + /** + * + **/ + com.sun.tools.corba.ee.idl.Token process (com.sun.tools.corba.ee.idl.Token t) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + token = t; + scanner = parser.scanner; + // Deactivate escaped identifier processing in Scanner while + // preprocessing. + //scanner.underscoreOK = true; + scanner.escapedOK = false; + try + { + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Include: + include (); + break; + case com.sun.tools.corba.ee.idl.Token.If: + ifClause (); + break; + case com.sun.tools.corba.ee.idl.Token.Ifdef: + ifdef (false); + break; + case com.sun.tools.corba.ee.idl.Token.Ifndef: + ifdef (true); + break; + case com.sun.tools.corba.ee.idl.Token.Else: + if (alreadyProcessedABranch.empty ()) + throw com.sun.tools.corba.ee.idl.ParseException.elseNoIf(scanner); + else if (((Boolean)alreadyProcessedABranch.peek ()).booleanValue ()) + skipToEndif (); + else + { + alreadyProcessedABranch.pop (); + alreadyProcessedABranch.push (true); + token = scanner.getToken (); + } + break; + case com.sun.tools.corba.ee.idl.Token.Elif: + elif (); + break; + case com.sun.tools.corba.ee.idl.Token.Endif: + if (alreadyProcessedABranch.empty ()) + throw com.sun.tools.corba.ee.idl.ParseException.endNoIf(scanner); + else + { + alreadyProcessedABranch.pop (); + token = scanner.getToken (); + break; + } + case com.sun.tools.corba.ee.idl.Token.Define: + define (); + break; + case com.sun.tools.corba.ee.idl.Token.Undef: + undefine (); + break; + case com.sun.tools.corba.ee.idl.Token.Pragma: + pragma (); + break; + case com.sun.tools.corba.ee.idl.Token.Unknown: + if (!parser.noWarn) + com.sun.tools.corba.ee.idl.ParseException.warning (scanner, com.sun.tools.corba.ee.idl.Util.getMessage("Preprocessor.unknown", token.name)); + case com.sun.tools.corba.ee.idl.Token.Error: + case com.sun.tools.corba.ee.idl.Token.Line: + case com.sun.tools.corba.ee.idl.Token.Null: + // ignore + default: + scanner.skipLineComment (); + token = scanner.getToken (); + } + } + catch (IOException e) + { + // Underscore may now precede any identifier, so underscoreOK + // is vestigal. The Preprocessor must reset escapedOK so that Scanner + // will process escaped identifiers according to specification. + //scanner.underscoreOK = false; + scanner.escapedOK = true; + throw e; + } + catch (com.sun.tools.corba.ee.idl.ParseException e) + { + // See above. + //scanner.underscoreOK = false; + scanner.escapedOK = true; + throw e; + } + // See above. + //scanner.underscoreOK = false; + scanner.escapedOK = true; + return token; + } // process + + /** + * + **/ + private void include () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Include); + IncludeEntry include = parser.stFactory.includeEntry (parser.currentModule); + include.sourceFile (scanner.fileEntry ()); + scanner.fileEntry ().addInclude (include); + if (token.type == com.sun.tools.corba.ee.idl.Token.StringLiteral) + include2 (include); + else if (token.type == com.sun.tools.corba.ee.idl.Token.LessThan) + include3 (include); + else + { + int[] expected = {com.sun.tools.corba.ee.idl.Token.StringLiteral, com.sun.tools.corba.ee.idl.Token.LessThan}; + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, expected, token.type); + } + if (parser.currentModule instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + ((com.sun.tools.corba.ee.idl.ModuleEntry)parser.currentModule).addContained (include); + else if (parser.currentModule instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + ((com.sun.tools.corba.ee.idl.InterfaceEntry)parser.currentModule).addContained (include); + } // include + + /** + * + **/ + private void include2 (IncludeEntry include) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + include.name ('"' + token.name + '"'); + include4 (include, token.name); + match (com.sun.tools.corba.ee.idl.Token.StringLiteral); + } // include2 + + /** + * + **/ + private void include3 (IncludeEntry include) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.type != com.sun.tools.corba.ee.idl.Token.LessThan) + // match will throw an exception + match (com.sun.tools.corba.ee.idl.Token.LessThan); + else + { + try + { + String includeFile = getUntil ('>'); + token = scanner.getToken (); + include.name ('<' + includeFile + '>'); + include4 (include, includeFile); + match (com.sun.tools.corba.ee.idl.Token.GreaterThan); + } + catch (IOException e) + { + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, ">", "EOF"); + } + } + } // include3 + + /** + * + **/ + private void include4 (IncludeEntry include, String filename) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + try + { + // If the #include is at the global scope, it is treated as + // an import statement. If it is within some other scope, it + // is treated as a normal #include. + boolean includeIsImport = parser.currentModule == parser.topLevelModule; + //daz + include.absFilename (com.sun.tools.corba.ee.idl.Util.getAbsolutePath(filename, parser.paths)); + scanner.scanIncludedFile (include, getFilename (filename), includeIsImport); + } + catch (IOException e) + { + com.sun.tools.corba.ee.idl.ParseException.generic(scanner, e.toString()); + } + } // include4 + + /** + * + **/ + private void define () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Define); + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier)) + { + String symbol = scanner.getStringToEOL (); + symbols.put (token.name, symbol.trim ()); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + { + symbols.put (token.name, '(' + scanner.getStringToEOL () . trim ()); + macros.addElement (token.name); + match (com.sun.tools.corba.ee.idl.Token.MacroIdentifier); + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Identifier, token.type); + } // define + + /** + * + **/ + private void undefine () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Undef); + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier)) + { + symbols.remove (token.name); + macros.removeElement (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Identifier, token.type); + } // undefine + + /** + * + **/ + private void ifClause () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.If); + constExpr (); + } // ifClause + + /** + * + **/ + private void constExpr () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.SymtabEntry dummyEntry = new com.sun.tools.corba.ee.idl.SymtabEntry(parser.currentModule); + dummyEntry.container (parser.currentModule); + parser.parsingConditionalExpr = true; + com.sun.tools.corba.ee.idl.constExpr.Expression boolExpr = booleanConstExpr (dummyEntry); + parser.parsingConditionalExpr = false; + boolean expr; + if (boolExpr.value () instanceof Boolean) + expr = ((Boolean)boolExpr.value ()).booleanValue (); + else + expr = ((Number)boolExpr.value ()).longValue () != 0; + alreadyProcessedABranch.push (expr); + if (!expr) + skipToEndiforElse (); + } // constExpr + + /** + * + **/ + com.sun.tools.corba.ee.idl.constExpr.Expression booleanConstExpr (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.constExpr.Expression expr = orExpr (null, entry); + try + { + expr.evaluate (); + } + catch (com.sun.tools.corba.ee.idl.constExpr.EvaluationException e) + { + com.sun.tools.corba.ee.idl.ParseException.evaluationError(scanner, e.toString()); + } + return expr; + } // booleanConstExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression orExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = andExpr (null, entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (andExpr (null, entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.DoubleBar)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.BooleanOr or = parser.exprFactory.booleanOr (e, null); + or.rep (e.rep () + " || "); + return orExpr (or, entry); + } + else + return e; + } // orExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression andExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + e = notExpr (entry); + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + b.right (notExpr (entry)); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.DoubleAmpersand)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.BooleanAnd and = parser.exprFactory.booleanAnd (e, null); + and.rep (e.rep () + " && "); + return andExpr (and, entry); + } + else + return e; + } // andExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression notExpr (/*boolean alreadySawExclamation, */com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.constExpr.Expression e; + if (token.equals (com.sun.tools.corba.ee.idl.Token.Exclamation)) + { + match (com.sun.tools.corba.ee.idl.Token.Exclamation); + e = parser.exprFactory.booleanNot (definedExpr (entry)); + e.rep ("!" + ((com.sun.tools.corba.ee.idl.constExpr.BooleanNot)e).operand ().rep ()); + } + else + e = definedExpr (entry); + return e; + } // notExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression definedExpr (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier) && token.name.equals ("defined")) + match (com.sun.tools.corba.ee.idl.Token.Identifier); + return equalityExpr (null, entry); + } // definedExpr + + /** + * + **/ + private com.sun.tools.corba.ee.idl.constExpr.Expression equalityExpr (com.sun.tools.corba.ee.idl.constExpr.Expression e, com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (e == null) + { + parser.token = token; // Since parser to parse, give it this token + e = parser.constExp (entry); + token = parser.token; // Since parser last parsed, get its token + } + else + { + com.sun.tools.corba.ee.idl.constExpr.BinaryExpr b = (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e; + parser.token = token; // Since parser to parse, give it this token + com.sun.tools.corba.ee.idl.constExpr.Expression constExpr = parser.constExp (entry); + token = parser.token; // Since parser last parsed, get its token + b.right (constExpr); + e.rep (e.rep () + b.right ().rep ()); + } + if (token.equals (com.sun.tools.corba.ee.idl.Token.DoubleEqual)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.Equal eq = parser.exprFactory.equal (e, null); + eq.rep (e.rep () + " == "); + return equalityExpr (eq, entry); + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.NotEqual)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.NotEqual n = parser.exprFactory.notEqual (e, null); + n.rep (e.rep () + " != "); + return equalityExpr (n, entry); + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.GreaterThan)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.GreaterThan g = parser.exprFactory.greaterThan (e, null); + g.rep (e.rep () + " > "); + return equalityExpr (g, entry); + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.GreaterEqual)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.GreaterEqual g = parser.exprFactory.greaterEqual (e, null); + g.rep (e.rep () + " >= "); + return equalityExpr (g, entry); + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.LessThan)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.LessThan l = parser.exprFactory.lessThan (e, null); + l.rep (e.rep () + " < "); + return equalityExpr (l, entry); + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.LessEqual)) + { + match (token.type); + com.sun.tools.corba.ee.idl.constExpr.LessEqual l = parser.exprFactory.lessEqual (e, null); + l.rep (e.rep () + " <= "); + return equalityExpr (l, entry); + } + else + return e; + } // equalityExpr + + /** + * + **/ + com.sun.tools.corba.ee.idl.constExpr.Expression primaryExpr (com.sun.tools.corba.ee.idl.SymtabEntry entry) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + com.sun.tools.corba.ee.idl.constExpr.Expression primary = null; + switch (token.type) + { + case com.sun.tools.corba.ee.idl.Token.Identifier: + // If an identifier gets this far, it means that no + // preprocessor variable was defined with that name. + // Generate a FALSE boolean expr. + //daz primary = parser.exprFactory.terminal ("0", new Long (0)); + primary = parser.exprFactory.terminal ("0", BigInteger.valueOf (0)); + token = scanner.getToken (); + break; + case com.sun.tools.corba.ee.idl.Token.BooleanLiteral: + case com.sun.tools.corba.ee.idl.Token.CharacterLiteral: + case com.sun.tools.corba.ee.idl.Token.IntegerLiteral: + case com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral: + case com.sun.tools.corba.ee.idl.Token.StringLiteral: + //daz primary = parser.literal (); + primary = parser.literal (entry); + token = parser.token; + break; + case com.sun.tools.corba.ee.idl.Token.LeftParen: + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + primary = booleanConstExpr (entry); + match (com.sun.tools.corba.ee.idl.Token.RightParen); + primary.rep ('(' + primary.rep () + ')'); + break; + default: + int[] expected = {com.sun.tools.corba.ee.idl.Token.Literal, com.sun.tools.corba.ee.idl.Token.LeftParen}; + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, expected, token.type); + } + return primary; + } // primaryExpr + + /** + * + **/ + private void ifDefine (boolean inParens, boolean not) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier)) + if ((not && symbols.containsKey (token.name)) || (!not && !symbols.containsKey (token.name))) + { + alreadyProcessedABranch.push (false); + skipToEndiforElse (); + } + else + { + alreadyProcessedABranch.push (true); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + if (inParens) + match (com.sun.tools.corba.ee.idl.Token.RightParen); + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Identifier, token.type); + } // ifDefine + + /** + * + **/ + private void ifdef (boolean not) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (not) + match (com.sun.tools.corba.ee.idl.Token.Ifndef); + else + match (com.sun.tools.corba.ee.idl.Token.Ifdef); + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier)) + if ((not && symbols.containsKey (token.name)) || (!not && !symbols.containsKey (token.name))) + { + alreadyProcessedABranch.push (false); + skipToEndiforElse (); + } + else + { + alreadyProcessedABranch.push (true); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + else + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Identifier, token.type); + } // ifdef + + /** + * + **/ + private void elif () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (alreadyProcessedABranch.empty ()) + throw com.sun.tools.corba.ee.idl.ParseException.elseNoIf(scanner); + else if (((Boolean)alreadyProcessedABranch.peek ()).booleanValue ()) + skipToEndif (); + else + { + match (com.sun.tools.corba.ee.idl.Token.Elif); + constExpr (); + } + } // elif + + /** + * + **/ + private void skipToEndiforElse () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (!token.equals (com.sun.tools.corba.ee.idl.Token.Endif) && !token.equals (com.sun.tools.corba.ee.idl.Token.Else) && !token.equals (com.sun.tools.corba.ee.idl.Token.Elif)) + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.Ifdef) || token.equals (com.sun.tools.corba.ee.idl.Token.Ifndef)) + { + alreadyProcessedABranch.push (true); + skipToEndif (); + } + else + token = scanner.skipUntil ('#'); + } + process (token); + } // skipToEndiforElse + + /** + * + **/ + private void skipToEndif () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (!token.equals (com.sun.tools.corba.ee.idl.Token.Endif)) + { + token = scanner.skipUntil ('#'); + if (token.equals (com.sun.tools.corba.ee.idl.Token.Ifdef) || token.equals (com.sun.tools.corba.ee.idl.Token.Ifndef)) + { + alreadyProcessedABranch.push (true); + skipToEndif (); + } + } + alreadyProcessedABranch.pop (); + match (com.sun.tools.corba.ee.idl.Token.Endif); + } // skipToEndif + + /////////////// + // For Pragma + + /** + * + **/ + private void pragma () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (com.sun.tools.corba.ee.idl.Token.Pragma); + String pragmaType = token.name; + + // Enable escaped identifiers while processing pragma internals. + // Don't enable until scanning pragma name! + scanner.escapedOK = true; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + + // Add pragma entry to container + com.sun.tools.corba.ee.idl.PragmaEntry pragmaEntry = parser.stFactory.pragmaEntry (parser.currentModule); + pragmaEntry.name (pragmaType); + pragmaEntry.sourceFile (scanner.fileEntry ()); + pragmaEntry.data (scanner.currentLine ()); + if (parser.currentModule instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + ((com.sun.tools.corba.ee.idl.ModuleEntry)parser.currentModule).addContained (pragmaEntry); + else if (parser.currentModule instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + ((com.sun.tools.corba.ee.idl.InterfaceEntry)parser.currentModule).addContained (pragmaEntry); + + // If the token was an identifier, then pragmaType WILL be non-null. + if (pragmaType.equals ("ID")) + idPragma (); + else if (pragmaType.equals ("prefix")) + prefixPragma (); + else if (pragmaType.equals ("version")) + versionPragma (); + + // we are adding extensions to the Sun's idlj compiler to + // handle correct code generation for local Objects, where + // the OMG is taking a long time to formalize stuff. Good + // example of this is poa.idl. Two proprietory pragmas + // sun_local and sun_localservant are defined. sun_local + // generates only Holder and Helper classes, where read + // and write methods throw marshal exceptions. sun_localservant + // is to generate Helper, Holder, and only Skel with _invoke + // throwing an exception, since it does not make sense for + // local objects. + + else if (pragmaType.equals ("sun_local")) + localPragma(); + else if (pragmaType.equals ("sun_localservant")) + localServantPragma(); + else + { + otherPragmas (pragmaType, tokenToString ()); + token = scanner.getToken (); + } + + scanner.escapedOK = false; // Disable escaped identifiers. + } // pragma + + // Pragma ID can be appiled to modules and it is an error to + // name a type in more than one ID pragma directive. + + private Vector PragmaIDs = new Vector (); + + private void localPragma () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // Before I can use a parser method, I must make sure it has the current token. + parser.token = token; + // this makes sense only for interfaces, if specified for modules, + // parser should throw an error + com.sun.tools.corba.ee.idl.SymtabEntry anErrorOccurred = new com.sun.tools.corba.ee.idl.SymtabEntry(); + com.sun.tools.corba.ee.idl.SymtabEntry entry = parser.scopedName (parser.currentModule, anErrorOccurred); + // Was the indicated type found in the symbol table? + if (entry == anErrorOccurred) + { + System.out.println("Error occured "); + // Don't have to generate an error, scopedName already has. + scanner.skipLineComment (); + token = scanner.getToken (); + } + else + { + // by this time we have already parsed the ModuleName and the + // pragma type, therefore setInterfaceType + if (entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) { + com.sun.tools.corba.ee.idl.InterfaceEntry ent = (com.sun.tools.corba.ee.idl.InterfaceEntry) entry; + ent.setInterfaceType (com.sun.tools.corba.ee.idl.InterfaceEntry.LOCAL_SIGNATURE_ONLY); + } + token = parser.token; + String string = token.name; + match (com.sun.tools.corba.ee.idl.Token.StringLiteral); + // for non-interfaces it doesn't make sense, so just ignore it + } + } // localPragma + + private void localServantPragma () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // Before I can use a parser method, I must make sure it has the current token. + parser.token = token; + // this makes sense only for interfaces, if specified for modules, + // parser should throw an error + com.sun.tools.corba.ee.idl.SymtabEntry anErrorOccurred = new com.sun.tools.corba.ee.idl.SymtabEntry(); + com.sun.tools.corba.ee.idl.SymtabEntry entry = parser.scopedName (parser.currentModule, anErrorOccurred); + + // Was the indicated type found in the symbol table? + if (entry == anErrorOccurred) + { + // Don't have to generate an error, scopedName already has. + scanner.skipLineComment (); + token = scanner.getToken (); + System.out.println("Error occured "); + } + else + { + // by this time we have already parsed the ModuleName and the + // pragma type, therefore setInterfaceType + if (entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) { + com.sun.tools.corba.ee.idl.InterfaceEntry ent = (com.sun.tools.corba.ee.idl.InterfaceEntry) entry; + ent.setInterfaceType (com.sun.tools.corba.ee.idl.InterfaceEntry.LOCALSERVANT); + } + token = parser.token; + String string = token.name; + match (com.sun.tools.corba.ee.idl.Token.StringLiteral); + // for non-interfaces it doesn't make sense, so just ignore it + } + } // localServantPragma + + + /** + * + **/ + private void idPragma () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // Before I can use a parser method, I must make sure it has the current token. + parser.token = token; + + // This flag will relax the restriction that the scopedNamed + // in this ID pragma directive cannot resolve to a module. + parser.isModuleLegalType (true); + com.sun.tools.corba.ee.idl.SymtabEntry anErrorOccurred = new com.sun.tools.corba.ee.idl.SymtabEntry(); + com.sun.tools.corba.ee.idl.SymtabEntry entry = parser.scopedName (parser.currentModule, anErrorOccurred); + parser.isModuleLegalType (false); // <57110> + + // Was the indicated type found in the symbol table? + if (entry == anErrorOccurred) + { + // Don't have to generate an error, scopedName already has. + scanner.skipLineComment (); + token = scanner.getToken (); + } + // + //else if (PragmaIDs.contains (entry)) + //{ + // ParseException.badRepIDAlreadyAssigned (scanner, entry.name ()); + // scanner.skipLineComment (); + // token = scanner.getToken (); + //} + else + { + token = parser.token; + String string = token.name; + // Do not match token until after raise exceptions, otherwise + // incorrect messages will be emitted! + if (PragmaIDs.contains (entry)) // + { + com.sun.tools.corba.ee.idl.ParseException.badRepIDAlreadyAssigned(scanner, entry.name()); + } + else if (!com.sun.tools.corba.ee.idl.RepositoryID.hasValidForm(string)) // + { + com.sun.tools.corba.ee.idl.ParseException.badRepIDForm(scanner, string); + } + else + { + entry.repositoryID (new com.sun.tools.corba.ee.idl.RepositoryID(string)); + PragmaIDs.addElement (entry); // + } + match (com.sun.tools.corba.ee.idl.Token.StringLiteral); + } + } // idPragma + + /** + * + **/ + private void prefixPragma () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + String string = token.name; + match (com.sun.tools.corba.ee.idl.Token.StringLiteral); + ((com.sun.tools.corba.ee.idl.IDLID)parser.repIDStack.peek ()).prefix (string); + ((com.sun.tools.corba.ee.idl.IDLID)parser.repIDStack.peek ()).name (""); + } // prefixPragma + + /** + * + **/ + private void versionPragma () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + // Before I can use a parser method, I must make sure it has the current token. + parser.token = token; + // This flag will relax the restriction that the scopedNamed + // in this Version pragma directive cannot resolve to a module. + parser.isModuleLegalType (true); + com.sun.tools.corba.ee.idl.SymtabEntry anErrorOccurred = new com.sun.tools.corba.ee.idl.SymtabEntry(); + com.sun.tools.corba.ee.idl.SymtabEntry entry = parser.scopedName (parser.currentModule, anErrorOccurred); + // reset the flag to original value + parser.isModuleLegalType (false); + if (entry == anErrorOccurred) + { + // Don't have to generate an error, scopedName already has. + scanner.skipLineComment (); + token = scanner.getToken (); + } + else + { + token = parser.token; + String string = token.name; + match (com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral); + if (entry.repositoryID () instanceof com.sun.tools.corba.ee.idl.IDLID) + ((com.sun.tools.corba.ee.idl.IDLID)entry.repositoryID ()).version (string); + } + } // versionPragma + + private Vector pragmaHandlers = new Vector (); + + /** + * + **/ + void registerPragma (com.sun.tools.corba.ee.idl.PragmaHandler handler) + { + pragmaHandlers.addElement (handler); + } // registerPragma + + /** + * + **/ + private void otherPragmas (String pragmaType, String currentToken) throws IOException + { + for (int i = pragmaHandlers.size () - 1; i >= 0; --i) + { + com.sun.tools.corba.ee.idl.PragmaHandler handler = (com.sun.tools.corba.ee.idl.PragmaHandler)pragmaHandlers.elementAt (i); + if (handler.process (pragmaType, currentToken)) + break; + } + } // otherPragmas + + /* + * These protected methods are used by extenders, by the code + * which implements otherPragma. + */ + + /** + * Get the current token. + **/ + String currentToken () + { + return tokenToString (); + } // currentToken + + /** + * This method, given an entry name, returns the entry with that name. + * It can take fully or partially qualified names and returns the + * appropriate entry defined within the current scope. If no entry + * exists, null is returned. + **/ + com.sun.tools.corba.ee.idl.SymtabEntry getEntryForName (String string) + { + boolean partialScope = false; + boolean globalScope = false; + + // Change all ::'s to /'s + if (string.startsWith ("::")) + { + globalScope = true; + string = string.substring (2); + } + int index = string.indexOf ("::"); + while (index >= 0) + { + partialScope = true; + string = string.substring (0, index) + '/' + string.substring (index + 2); + index = string.indexOf ("::"); + } + + // Get the entry for that string + com.sun.tools.corba.ee.idl.SymtabEntry entry = null; + if (globalScope) + entry = parser.recursiveQualifiedEntry (string); + else if (partialScope) + entry = parser.recursivePQEntry (string, parser.currentModule); + else + entry = parser.unqualifiedEntryWMod (string, parser.currentModule); + return entry; + } // getEntryForName + + /** + * This method returns a string of all of the characters from the + * input file from the current position up to, but not including, + * the end-of-line character(s). + **/ + String getStringToEOL () throws IOException + { + return scanner.getStringToEOL (); + } // getStringToEOL + + /** + * This method returns a string of all of the characters from the + * input file from the current position up to, but not including, + * the given character. It encapsulates parenthesis and quoted strings, + * meaning it does not stop if the given character is found within + * parentheses or quotes. For instance, given the input of + * `start(inside)end', getUntil ('n') will return "start(inside)e" + **/ + String getUntil (char c) throws IOException + { + return scanner.getUntil (c); + } // getUntil + + private boolean lastWasMacroID = false; + + /** + * + **/ + private String tokenToString () + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + { + lastWasMacroID = true; + return token.name; + } + else if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier)) + return token.name; + else + return token.toString (); + } // tokenToString + + /** + * This method returns the next token String from the input file. + **/ + String nextToken () throws IOException + { + if (lastWasMacroID) + { + lastWasMacroID = false; + return "("; + } + else + { + token = scanner.getToken (); + return tokenToString (); + } + } // nextToken + + /** + * This method assumes that the current token marks the beginning + * of a scoped name. It then parses the subsequent identifier and + * double colon tokens, builds the scoped name, and finds the symbol + * table entry with that name. + **/ + com.sun.tools.corba.ee.idl.SymtabEntry scopedName () throws IOException + { + boolean globalScope = false; + boolean partialScope = false; + String name = null; + com.sun.tools.corba.ee.idl.SymtabEntry entry = null; + try + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.DoubleColon)) + globalScope = true; + else + { + if (token.equals (com.sun.tools.corba.ee.idl.Token.Object)) + { + name = "Object"; + match (com.sun.tools.corba.ee.idl.Token.Object); + } + else if (token.type == com.sun.tools.corba.ee.idl.Token.ValueBase) + { + name = "ValueBase"; + match (com.sun.tools.corba.ee.idl.Token.ValueBase); + } + else + { + name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + } + while (token.equals (com.sun.tools.corba.ee.idl.Token.DoubleColon)) + { + match (com.sun.tools.corba.ee.idl.Token.DoubleColon); + partialScope = true; + if (name != null) + name = name + '/' + token.name; + else + name = token.name; + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + if (globalScope) + entry = parser.recursiveQualifiedEntry (name); + else if (partialScope) + entry = parser.recursivePQEntry (name, parser.currentModule); + else + entry = parser.unqualifiedEntryWMod (name, parser.currentModule); + } + catch (com.sun.tools.corba.ee.idl.ParseException e) + { + entry = null; + } + return entry; + } // scopedName + + /** + * Skip to the end of the line. + **/ + void skipToEOL () throws IOException + { + scanner.skipLineComment (); + } // skipToEOL + + /** + * This method skips the data in the input file until the specified + * character is encountered, then it returns the next token. + **/ + String skipUntil (char c) throws IOException + { + if (!(lastWasMacroID && c == '(')) + token = scanner.skipUntil (c); + return tokenToString (); + } // skipUntil + + /** + * This method displays a Parser Exception complete with line number + * and position information with the given message string. + **/ + void parseException (String message) + { + // Suppress warnings + if (!parser.noWarn) + com.sun.tools.corba.ee.idl.ParseException.warning(scanner, message); + } // parseException + + // For Pragma + /////////////// + // For macro expansion + + /** + * + **/ + String expandMacro (String macroDef, com.sun.tools.corba.ee.idl.Token t) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + token = t; + // Get the parameter values from the macro 'call' + Vector parmValues = getParmValues (); + + // Get the parameter names from the macro definition + // NOTE: a newline character is appended here so that when + // getStringToEOL is called, it stops scanning at the end + // of this string. + scanner.scanString (macroDef + '\n'); + Vector parmNames = new Vector (); + macro (parmNames); + + if (parmValues.size () < parmNames.size ()) + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Comma, com.sun.tools.corba.ee.idl.Token.RightParen); + else if (parmValues.size () > parmNames.size ()) + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.RightParen, com.sun.tools.corba.ee.idl.Token.Comma); + + macroDef = scanner.getStringToEOL (); + for (int i = 0; i < parmNames.size (); ++i) + macroDef = replaceAll (macroDef, (String)parmNames.elementAt (i), (String)parmValues.elementAt (i)); + return removeDoublePound (macroDef); + } // expandMacro + + // This method is only used by the macro expansion methods. + /** + * + **/ + private void miniMatch (int type) throws com.sun.tools.corba.ee.idl.ParseException + { + // A normal production would now execute: + // match (type); + // But match reads the next token. I don't want to do that now. + // Just make sure the current token is a 'type'. + if (!token.equals (type)) + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, type, token.type); + } // miniMatch + + /** + * + **/ + private Vector getParmValues () throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + Vector values = new Vector (); + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier)) + { + match (com.sun.tools.corba.ee.idl.Token.Identifier); + miniMatch (com.sun.tools.corba.ee.idl.Token.LeftParen); + } + else if (!token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError (scanner, com.sun.tools.corba.ee.idl.Token.Identifier, token.type); + + if (!token.equals (com.sun.tools.corba.ee.idl.Token.RightParen)) + { + values.addElement (scanner.getUntil (',', ')').trim ()); + token = scanner.getToken (); + macroParmValues (values); + } + return values; + } // getParmValues + + /** + * + **/ + private void macroParmValues (Vector values) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (!token.equals (com.sun.tools.corba.ee.idl.Token.RightParen)) + { + miniMatch (com.sun.tools.corba.ee.idl.Token.Comma); + values.addElement (scanner.getUntil (',', ')').trim ()); + token = scanner.getToken (); + } + } // macroParmValues + + /** + * + **/ + private void macro (Vector parmNames) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + match (token.type); + match (com.sun.tools.corba.ee.idl.Token.LeftParen); + macroParms (parmNames); + miniMatch (com.sun.tools.corba.ee.idl.Token.RightParen); + } // macro + + /** + * + **/ + private void macroParms (Vector parmNames) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (!token.equals (com.sun.tools.corba.ee.idl.Token.RightParen)) + { + parmNames.addElement (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + macroParms2 (parmNames); + } + } // macroParms + + /** + * + **/ + private void macroParms2 (Vector parmNames) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + while (!token.equals (com.sun.tools.corba.ee.idl.Token.RightParen)) + { + match (com.sun.tools.corba.ee.idl.Token.Comma); + parmNames.addElement (token.name); + match (com.sun.tools.corba.ee.idl.Token.Identifier); + } + } // macroParms2 + + /** + * + **/ + private String replaceAll (String string, String from, String to) + { + int index = 0; + while (index != -1) + { + index = string.indexOf (from, index); + if (index != -1) + { + if (!embedded (string, index, index + from.length ())) + if (index > 0 && string.charAt(index) == '#') + string = string.substring (0, index) + '"' + to + '"' + string.substring (index + from.length ()); + else + string = string.substring (0, index) + to + string.substring (index + from.length ()); + index += to.length (); + } + } + return string; + } // replaceAll + + /** + * + **/ + private boolean embedded (String string, int index, int endIndex) + { + // Don't replace if found substring is not an independent id. + // For example, don't replace "thither".indexOf ("it", 0) + boolean ret = false; + char preCh = index == 0 ? ' ' : string.charAt (index - 1); + char postCh = endIndex >= string.length () - 1 ? ' ' : string.charAt (endIndex); + if ((preCh >= 'a' && preCh <= 'z') || (preCh >= 'A' && preCh <= 'Z')) + ret = true; + else if ((postCh >= 'a' && postCh <= 'z') || (postCh >= 'A' && postCh <= 'Z') || (postCh >= '0' && postCh <= '9') || postCh == '_') + ret = true; + else + ret = inQuotes (string, index); + return ret; + } // embedded + + /** + * + **/ + private boolean inQuotes (String string, int index) + { + int quoteCount = 0; + for (int i = 0; i < index; ++i) + if (string.charAt (i) == '"') ++quoteCount; + // If there are an odd number of quotes before this region, + // then this region is within quotes + return quoteCount % 2 != 0; + } // inQuotes + + /** + * Remove any occurrences of ##. + **/ + private String removeDoublePound (String string) + { + int index = 0; + while (index != -1) + { + index = string.indexOf ("##", index); + if (index != -1) + { + int startSkip = index - 1; + int stopSkip = index + 2; + if (startSkip < 0) + startSkip = 0; + if (stopSkip >= string.length ()) + stopSkip = string.length () - 1; + while (startSkip > 0 && + (string.charAt (startSkip) == ' ' || + string.charAt (startSkip) == '\t')) + --startSkip; + while (stopSkip < string.length () - 1 && + (string.charAt (stopSkip) == ' ' || + string.charAt (stopSkip) == '\t')) + ++stopSkip; + string = string.substring (0, startSkip + 1) + string.substring (stopSkip); + } + } + return string; + } // removeDoublePound + + // For macro expansion + /////////////// + + /** + * + **/ + private String getFilename (String name) throws FileNotFoundException + { + String fullName = null; + File file = new File (name); + if (file.canRead ()) + fullName = name; + else + { + Enumeration pathList = parser.paths.elements (); + while (!file.canRead () && pathList.hasMoreElements ()) + { + fullName = (String)pathList.nextElement () + File.separatorChar + name; + file = new File (fullName); + } + if (!file.canRead ()) + throw new FileNotFoundException (name); + } + return fullName; + } // getFilename + + /** + * + **/ + private void match (int type) throws IOException, com.sun.tools.corba.ee.idl.ParseException + { + if (!token.equals (type)) + throw com.sun.tools.corba.ee.idl.ParseException.syntaxError(scanner, type, token.type); + token = scanner.getToken (); + + // Added for convenience, but commented-out because there is + // no reason to issue warnings for tokens scanned during preprocessing. + // See issueTokenWarnings(). + //issueTokenWarnings (); + + //System.out.println ("Preprocessor.match token = " + token.type); + //if (token.equals (Token.Identifier) || token.equals (Token.MacroIdentifier)) + // System.out.println ("Preprocessor.match token name = " + token.name); + + // If the token is a defined thingy, scan the defined string + // instead of the input stream for a while. + if (token.equals (com.sun.tools.corba.ee.idl.Token.Identifier) || token.equals (com.sun.tools.corba.ee.idl.Token.MacroIdentifier)) + { + String string = (String)symbols.get (token.name); + if (string != null && !string.equals ("")) + // If this is a macro, parse the macro + if (macros.contains (token.name)) + { + scanner.scanString (expandMacro (string, token)); + token = scanner.getToken (); + } + // else this is just a normal define + else + { + scanner.scanString (string); + token = scanner.getToken (); + } + } + } // match + + // + /** + * Issue warnings about tokens scanned during preprocessing. + **/ + private void issueTokenWarnings () + { + if (parser.noWarn) + return; + + // There are no keywords defined for preprocessing (only directives), so: + // + // 1.) Do not issue warnings for identifiers known to be keywords in + // another level of IDL. + // 2.) Do not issue warnings for identifiers that collide with keywords + // in letter, but not case. + // 3.) Do not issue warnings for deprecated keywords. + // + // Should we warn when a macro identifier replaces a keyword? Hmmm. + + // Deprecated directives? None to date. + //if (token.isDirective () && token.isDeprecated ()) + // ParseException.warning (scanner, Util.getMesage ("Deprecated.directive", token.name)); + } // issueTokenWarnings + + /** + * This method is called when the parser encounters a left curly brace. + * An extender of PragmaHandler may find scope information useful. + * For example, the prefix pragma takes effect as soon as it is + * encountered and stays in effect until the current scope is closed. + * If a similar pragma extension is desired, then the openScope and + * closeScope methods are available for overriding. + * @param entry the symbol table entry whose scope has just been opened. + * Be aware that, since the scope has just been entered, this entry is + * incomplete at this point. + **/ + void openScope (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + for (int i = pragmaHandlers.size () - 1; i >= 0; --i) + { + com.sun.tools.corba.ee.idl.PragmaHandler handler = (com.sun.tools.corba.ee.idl.PragmaHandler)pragmaHandlers.elementAt (i); + handler.openScope (entry); + } + } // openScope + + /** + * This method is called when the parser encounters a right curly brace. + * An extender of PragmaHandler may find scope information useful. + * For example, the prefix pragma takes effect as soon as it is + * encountered and stays in effect until the current scope is closed. + * If a similar pragma extension is desired, then the openScope and + * closeScope methods are available for overriding. + * @param entry the symbol table entry whose scope has just been closed. + **/ + void closeScope (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + for (int i = pragmaHandlers.size () - 1; i >= 0; --i) + { + com.sun.tools.corba.ee.idl.PragmaHandler handler = (com.sun.tools.corba.ee.idl.PragmaHandler)pragmaHandlers.elementAt (i); + handler.closeScope (entry); + } + } // closeScope + + private com.sun.tools.corba.ee.idl.Parser parser; + private com.sun.tools.corba.ee.idl.Scanner scanner; + private Hashtable symbols; + private Vector macros; + + // The logic associated with this stack is scattered above. + // A concise map of the logic is: + // case #if false, #ifdef false, #ifndef true + // push (false); + // skipToEndifOrElse (); + // case #if true, #ifdef true, #ifndef false + // push (true); + // case #elif + // if (top == true) + // skipToEndif (); + // else if (conditional == true) + // pop (); + // push (true); + // else if (conditional == false) + // skipToEndifOrElse (); + // case #else + // if (top == true) + // skipToEndif (); + // else + // pop (); + // push (true); + // case #endif + // pop (); + private Stack alreadyProcessedABranch = new Stack (); + com.sun.tools.corba.ee.idl.Token token; + + private static String indent = ""; +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/PrimitiveEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PrimitiveEntry.java new file mode 100644 index 000000000..dc16bf53b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PrimitiveEntry.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for primitive types: octet, char, + * short, long, long long (and unsigned versions), float, double, string. + **/ +public class PrimitiveEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected PrimitiveEntry () + { + super (); + repositoryID (Util.emptyID); + } // ctor + + protected PrimitiveEntry (String name) + { + name (name); + module (""); + repositoryID (Util.emptyID); + } // ctor + + protected PrimitiveEntry (PrimitiveEntry that) + { + super (that); + } // ctor + + public Object clone () + { + return new PrimitiveEntry (this); + } // clone + + /** Invoke the primitive type generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + primitiveGen.generate (symbolTable, this, stream); + } // generate + + /** Access the primitive type generator. + @return an object which implements the PrimitiveGen interface. + @see com.sun.tools.corba.ee.idl.PrimitiveGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return primitiveGen; + } // generator + + static com.sun.tools.corba.ee.idl.PrimitiveGen primitiveGen; +} // class PrimitiveEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/PrimitiveGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PrimitiveGen.java new file mode 100644 index 000000000..ae93a9ddd --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/PrimitiveGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface PrimitiveGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.PrimitiveEntry entry, PrintWriter stream); +} // interface PrimitiveGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/RepositoryID.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/RepositoryID.java new file mode 100644 index 000000000..4a84e96e2 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/RepositoryID.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -D57110 Add method to verify format (CORBA 2.3). + +public class RepositoryID +{ + public RepositoryID () + { + _id = ""; + } // ctor + + public RepositoryID (String id) + { + _id = id; + } // ctor + + public String ID () + { + return _id; + } // ID + + public Object clone () + { + return new RepositoryID (_id); + } // clone + + public String toString () + { + return ID (); + } // toString + + /** + * Determine is a supplied string meets the minimal format requirement + * for a Repository ID. + * @return true iff supplied string has form '<format>:<string>', where + * <format> is any non-empty string not containing ':'. + **/ + public static boolean hasValidForm (String string) + { + return string != null && string.indexOf (':') > 0; + } // hasValidForm + + private String _id; +} // class RepositoryID diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ResourceBundleUtil.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ResourceBundleUtil.java new file mode 100644 index 000000000..118a80a9f --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ResourceBundleUtil.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -capitalize and parseTypeModifier should probably be in the +// generators package. +// -D58319 Add version() method. + +import java.text.MessageFormat; +import java.util.ResourceBundle; + +public class ResourceBundleUtil +{ + // + /** + * Fetch the version number of this build of the IDL Parser Framework. + * This method may be called before or after the framework has been + * initialized. If the framework is inititialized, the version information + * is extracted from the message properties object; otherwise, it is extracted + * from the indicated resouce bundle. + * @return the version number. + **/ + public static String getVersion () + { + String version = getMessage ("Version.product", getMessage ("Version.number")); + return version; + } // getVersion + + + ////////////// + // Message-related methods + + public static String getMessage (String key, String... fill) + { + String pattern = getResourceBundle().getString(key) ; + MessageFormat mf = new MessageFormat( pattern ) ; + return mf.format( fill, new StringBuffer(), null ).toString() ; + } // getMessage + + + /** Register a ResourceBundle. This file will be searched for + in the CLASSPATH. */ + public static void registerResourceBundle (ResourceBundle bundle) + { + if (bundle != null) + fBundle = bundle; + } // registerResourceBundle + + + /** Gets the current ResourceBundle. */ + public static ResourceBundle getResourceBundle () + { + if (fBundle == null) { + fBundle = ResourceBundle.getBundle("com.sun.tools.corba.ee.idl.idl"); + } + return fBundle; + } // getResourceBundle + + private static ResourceBundle fBundle = null ; +} // class ResourceBundleUtil diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Scanner.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Scanner.java new file mode 100644 index 000000000..40ee641c1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Scanner.java @@ -0,0 +1,1590 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -F46082.51 Remove -stateful feature. +// -D56351 Update computation of RepositoryIDs to CORBA 2.3 (see spec.). +// -D59166 Add escaped-id. info. to identifiers. +// -F60858.1 Add support for -corba option, levels 2.2 and 2.3: accept 2.3 +// keywords as ids.; accept ids. that match keywords in letter, but not in case. +// -D62023 Add support for -corba option, level 2.4: see keyword checking. + +import java.io.EOFException; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import java.util.Enumeration; +import java.util.Stack; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + * + **/ +class Scanner +{ + // -Remove stateful feature. + //Scanner (IncludeEntry file, String[] keywords, boolean vbose, boolean scanStateful, boolean emitAllIncludes) throws IOException + // + //Scanner (IncludeEntry file, String[] keywords, boolean vbose, boolean emitAllIncludes) throws IOException + /** + * + **/ + Scanner (com.sun.tools.corba.ee.idl.IncludeEntry file, String[] keywords, boolean vbose, + boolean emitAllIncludes, float cLevel, boolean debug) throws IOException + { + readFile (file); + verbose = vbose; + // + //stateful = scanStateful; + emitAll = emitAllIncludes; + sortKeywords (keywords); + corbaLevel = cLevel; + this.debug = debug ; + } // ctor + + /** + * + **/ + void sortKeywords (String[] keywords) + { + for (int i = 0; i < keywords.length; ++i) + if (wildcardAtEitherEnd (keywords[i])) + this.openEndedKeywords.addElement (keywords[i]); + else if (wildcardsInside (keywords[i])) + this.wildcardKeywords.addElement (keywords[i]); + else + this.keywords.addElement (keywords[i]); + } // sortKeywords + + /** + * + **/ + private boolean wildcardAtEitherEnd (String string) + { + return string.startsWith ("*") || + string.startsWith ("+") || + string.startsWith (".") || + string.endsWith ("*") || + string.endsWith ("+") || + string.endsWith ("."); + } // wildcardAtEitherEnd + + /** + * + **/ + private boolean wildcardsInside (String string) + { + return string.indexOf ("*") > 0 || + string.indexOf ("+") > 0 || + string.indexOf (".") > 0; + } // wildcardsInside + + /** + * + **/ + void readFile (com.sun.tools.corba.ee.idl.IncludeEntry file) throws IOException + { + String filename = file.name (); + filename = filename.substring (1, filename.length () - 1); + readFile (file, filename); + } // readFile + + /** + * + **/ + void readFile (com.sun.tools.corba.ee.idl.IncludeEntry file, String filename) throws IOException + { + data.fileEntry = file; + data.filename = filename; + // + //FileInputStream stream = new FileInputStream (data.filename); + //data.fileBytes = new byte [stream.available ()]; + //stream.read (data.fileBytes); + //stream.close (); + File idlFile = new File (data.filename); + int len = (int)idlFile.length (); + FileReader fileReader = new FileReader (idlFile); + // data.fileBytes = new char [len]; + final String EOL = System.getProperty ("line.separator"); + data.fileBytes = new char [len + EOL.length ()]; + + fileReader.read (data.fileBytes, 0, len); + fileReader.close (); + + // + for (int i = 0; i < EOL.length (); i++) + data.fileBytes[len + i] = EOL.charAt (i); + + readChar (); + } // readFile + + /** + * + **/ + com.sun.tools.corba.ee.idl.Token getToken () throws IOException + { + //System.out.println ("Scanner.getToken char = |" + data.ch + "| (ASCII " + (int)data.ch + ")."); + + // The token could be null if the next set of characters + // is not a token: white space, comments, ignored preprocessor + // commands. + com.sun.tools.corba.ee.idl.Token token = null; + String commentText = new String (""); + + while (token == null) + try + { + data.oldIndex = data.fileIndex; + data.oldLine = data.line; + if (data.ch <= ' ') { + skipWhiteSpace (); + continue; + } + + // Special case for wchar and wstring literals. + // The values are preceded by an L. + // + // Bug fix 4382578: Can't compile a wchar literal. + // + // REVISIT. This maps wchar/wstring literals to + // our char/string literal types. Eventually, we + // need to write stronger checking to be spec + // compliant in negative cases such as leaving the + // L off of a wide string or putting it on a string. + if (data.ch == 'L') { + // Check to see if the next character is an + // apostrophe. + readChar(); + // Note: This doesn't allow for space between + // the L and the apostrophe or quote. + if (data.ch == '\'') { + // It was a wchar literal. Get the value + // and return the token. + token = getCharacterToken(true); + readChar(); + continue; + } else + if (data.ch == '"') { + // It was a wstring literal. + // + // getUntil assumes we've already passed the + // first quote. + readChar (); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.StringLiteral, getUntil ('"'), true); + readChar (); + continue; + } else { + // It must not have been a wchar literal. + // Push the input back into the buffer, and + // fall to the next if case. + unread(data.ch); + unread('L'); + readChar(); + } + } + + if ((data.ch >= 'a' && data.ch <= 'z') || + (data.ch >= 'A' && data.ch <= 'Z') || + // Escaped identifier; see data member comments. + //(data.ch == '_' && underscoreOK) || + (data.ch == '_') || + Character.isLetter (data.ch)) { + token = getString (); + } else + if ((data.ch >= '0' && data.ch <= '9') || data.ch == '.') { + token = getNumber (); + } else { + switch (data.ch) + { + case ';': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Semicolon); + break; + case '{': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.LeftBrace); + break; + case '}': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.RightBrace); + break; + case ':': + readChar (); + if (data.ch == ':') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.DoubleColon); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Colon); + } + break; + case ',': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Comma); + break; + case '=': + readChar (); + if (data.ch == '=') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.DoubleEqual); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Equal); + } + break; + case '+': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Plus); + break; + case '-': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Minus); + break; + case '(': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.LeftParen); + break; + case ')': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.RightParen); + break; + case '<': + readChar (); + if (data.ch == '<') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.ShiftLeft); + else if (data.ch == '=') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.LessEqual); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.LessThan); + } + break; + case '>': + readChar (); + if (data.ch == '>') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.ShiftRight); + else if (data.ch == '=') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.GreaterEqual); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.GreaterThan); + } + break; + case '[': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.LeftBracket); + break; + case ']': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.RightBracket); + break; + case '\'': + token = getCharacterToken(false); + break; + case '"': + readChar (); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.StringLiteral, getUntil ('"', false, false, false)); + break; + case '\\': + readChar (); + // If this is at the end of a line, then it is the + // line continuation character - treat it as white space + if (data.ch == '\n' || data.ch == '\r') + token = null; + else + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Backslash); + break; + case '|': + readChar (); + if (data.ch == '|') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.DoubleBar); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Bar); + } + break; + case '^': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Carat); + break; + case '&': + readChar (); + if (data.ch == '&') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.DoubleAmpersand); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Ampersand); + } + break; + case '*': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Star); + break; + case '/': + readChar (); + // <21jul1997daz> Extract comments rather than skipping them. + // Preserve only the comment immediately preceding the next token. + if (data.ch == '/') + //skipLineComment (); + commentText = getLineComment(); + else if (data.ch == '*') + //skipBlockComment (); + commentText = getBlockComment(); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Slash); + } + break; + case '%': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Percent); + break; + case '~': + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Tilde); + break; + + // The period token is recognized in getNumber. + // The period is only valid in a floating ponit number. + //case '.': + // token = new Token (Token.Period); + // break; + + case '#': + token = getDirective (); + break; + case '!': + readChar (); + if (data.ch == '=') + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.NotEqual); + else + { + unread (data.ch); + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Exclamation); + } + break; + case '?': + try + { + token = replaceTrigraph (); + break; + } + catch (com.sun.tools.corba.ee.idl.InvalidCharacter e) {} + default: + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + } + readChar (); + } + } + catch (EOFException e) + { + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.EOF); + } + + // Transfer comment to parser via token. 21jul1997 + token.comment = new Comment( commentText ); + + //System.out.println ("Scanner.getToken returning token.type = " + token.type); + //if (token.type == Token.Identifier || token.type == Token.MacroIdentifier || (token.type >= Token.BooleanLiteral && token.type <= Token.StringLiteral)) + // System.out.println ("Scanner.getToken returns token.name = " + token.name); + + if (debug) + System.out.println( "Token: " + token ) ; + + return token; + } // getToken + + /** + * + **/ + void scanString (String string) + { + dataStack.push (data); + + data = new ScannerData (data); + + data.fileIndex = 0; + data.oldIndex = 0; + // data.fileBytes = string.getBytes (); + int strLen = string.length(); + data.fileBytes = new char[strLen]; + string.getChars (0, strLen, data.fileBytes, 0); + + data.macrodata = true; + + try {readChar ();} catch (IOException e) {} + } // scanString + + /** + * + **/ + void scanIncludedFile (com.sun.tools.corba.ee.idl.IncludeEntry file, String filename, boolean includeIsImport) throws IOException + { + dataStack.push (data); + data = new ScannerData (); + data.indent = ((ScannerData)dataStack.peek ()).indent + ' '; + data.includeIsImport = includeIsImport; + try + { + readFile (file, filename); + if (!emitAll && includeIsImport) + com.sun.tools.corba.ee.idl.SymtabEntry.enteringInclude(); + // As of CORBA 2.3, include files define new scope for Repository + // ID prefixes. The previous Rep. ID is just below the top of the stack and + // must be restored when the contents of this include file are parsed (see readCh()). + com.sun.tools.corba.ee.idl.Parser.enteringInclude(); + + if (verbose) + System.out.println (data.indent + com.sun.tools.corba.ee.idl.Util.getMessage("Compile.parsing", filename)); + } + catch (IOException e) + { + data = (ScannerData)dataStack.pop (); + throw e; + } + } // scanIncludedFile + + /** + * + **/ + private void unread (char ch) + { + if (ch == '\n' && !data.macrodata) --data.line; + --data.fileIndex; + } // unread + + /** + * + **/ + void readChar () throws IOException + { + if (data.fileIndex >= data.fileBytes.length) + if (dataStack.empty ()) + throw new EOFException (); + else + { + // Indicate end-of-scope for include file to parser. + //Parser.exitingInclude (); + + // IBM.11666 - begin + //if (!emitAll && data.includeIsImport && !data.macrodata) + //{ + //SymtabEntry.exitingInclude (); + //Parser.exitingInclude (); // + //} + if (!data.macrodata) + { + if (!emitAll && data.includeIsImport) + com.sun.tools.corba.ee.idl.SymtabEntry.exitingInclude(); + com.sun.tools.corba.ee.idl.Parser.exitingInclude(); + } // IBM.11666 - end + + if (verbose && !data.macrodata) + System.out.println (data.indent + com.sun.tools.corba.ee.idl.Util.getMessage("Compile.parseDone", data.filename)); + data = (ScannerData)dataStack.pop (); + } + else + { + data.ch = (char)(data.fileBytes[data.fileIndex++] & 0x00ff); + if (data.ch == '\n' && !data.macrodata) ++data.line; + } + } // readChar + + /** + * Starting at a quote, reads a string with possible + * unicode or octal values until an end quote. Doesn't + * handle line feeds or comments. + */ + private String getWString() throws IOException + { + readChar(); + StringBuffer result = new StringBuffer(); + + while (data.ch != '"') { + if (data.ch == '\\') { + // Could be a \ooo octal or + // unicode hex + readChar(); + if (data.ch == 'u') { + // Unicode hex + int num = getNDigitHexNumber(4); + System.out.println("Got num: " + num); + System.out.println("Which is: " + (int)(char)num); + result.append((char)num); + // result.append((char)getNDigitHexNumber(4)); + // getNDigitHexNumber reads the next + // character, so loop without reading another + continue; + } else + if (data.ch >= '0' && data.ch <= '7') { + // Octal + result.append((char)get3DigitOctalNumber()); + // get3DigitOctalNumber reads the next + // character, so loop without reading another + continue; + } else { + // Wasn't either, so just append the + // slash and current character. + result.append('\\'); + result.append(data.ch); + } + } else { + // Just append the character + result.append(data.ch); + } + + // Advance to the next character + readChar(); + } + + return result.toString(); + } + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getCharacterToken(boolean isWide) throws IOException + { + // The token name returned contains a string with two elements: + // first the character appears, then the representation of the + // character. These are typically the same, but they CAN be + // different, for example "O\117" + com.sun.tools.corba.ee.idl.Token token = null; + readChar (); + if ( data.ch == '\\' ) + { + readChar (); + if ((data.ch == 'x') || (data.ch == 'u')) + { + char charType = data.ch; + int hexNum = getNDigitHexNumber ((charType == 'x') ? 2 : 4); + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, + ((char)hexNum) + "\\" + charType + Integer.toString (hexNum, 16), isWide ); + } + if ((data.ch >= '0') && (data.ch <= '7')) + { + int octNum = get3DigitOctalNumber (); + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, + ((char)octNum) + "\\" + Integer.toString (octNum, 8), isWide ); + } + return singleCharEscapeSequence (isWide); + } + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "" + data.ch + data.ch, isWide ); + readChar (); + return token; + } // getCharacterToken + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token singleCharEscapeSequence (boolean isWide) throws IOException + { + com.sun.tools.corba.ee.idl.Token token; + if (data.ch == 'n') + // newline + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\n\\n", isWide); + else if (data.ch == 't') + // horizontal tab + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\t\\t", isWide); + else if (data.ch == 'v') + // vertical tab + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\013\\v", isWide); + else if (data.ch == 'b') + // backspace + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\b\\b", isWide); + else if (data.ch == 'r') + // carriage return + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\r\\r", isWide); + else if (data.ch == 'f') + // form feed + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\f\\f", isWide); + else if (data.ch == 'a') + // alert + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\007\\a", isWide); + else if (data.ch == '\\') + // backslash + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\\\\\\", isWide); + else if (data.ch == '?') + // question mark + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "?\\?", isWide); + else if (data.ch == '\'') + // single quote + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "'\\'", isWide); + else if (data.ch == '"') + // double quote + token = new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.CharacterLiteral, "\"\\\"", isWide); + else + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + readChar (); + return token; + } // singleCharEscapeSequence + + private com.sun.tools.corba.ee.idl.Token getString () throws IOException + { + StringBuffer sbuf = new StringBuffer() ; + boolean escaped = false; // + boolean[] collidesWithKeyword = { false } ; // + + // An escaped id. begins with '_', which is followed by a normal + // identifier. Disallow prefixes of '_' having length > 1. + if (data.ch == '_') { + sbuf.append( data.ch ) ; + readChar (); + if (escaped = escapedOK) + if (data.ch == '_') + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), + currentLineNumber (), currentLinePosition (), data.ch); + } + + // Build up the string of valid characters until a non-string + // character is encountered. + while (Character.isLetterOrDigit( data.ch ) || (data.ch == '_')) { + sbuf.append( data.ch ) ; + readChar() ; + } + + String string = sbuf.toString() ; + + // Escaped identifiers - If identifier has '_' prefix, ignore + // keyword check and strip '_'; otherwise, perform keyword check. + + if (!escaped) { // Escaped id ==> ignore keyword check + com.sun.tools.corba.ee.idl.Token result = com.sun.tools.corba.ee.idl.Token.makeKeywordToken(string, corbaLevel, escapedOK, + collidesWithKeyword) ; + if (result != null) + return result ; + } + + // At this point the string is an identifier. If it is a + // string which is also a Java keyword, prepend an underscore + // so that it doesn't generate a compiler error. + string = getIdentifier (string); + + // If a left paren immediately follows, this could be a + // macro definition, return a MacroIdentifier + if (data.ch == '(') { + readChar (); + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.MacroIdentifier, string, escaped, + collidesWithKeyword[0], false); + } else + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Identifier, string, escaped, + collidesWithKeyword[0], false); + } + + // Wildcard values + static final int Star = 0, Plus = 1, Dot = 2, None = 3; + + /** + * + **/ + private boolean matchesClosedWildKeyword (String string) + { + boolean found = true; + String tmpString = string; + Enumeration e = wildcardKeywords.elements (); + while (e.hasMoreElements ()) + { + int wildcard = None; + StringTokenizer tokens = new StringTokenizer ((String)e.nextElement (), "*+.", true); + if (tokens.hasMoreTokens ()) + { + String token = tokens.nextToken (); + if (tmpString.startsWith (token)) + { + tmpString = tmpString.substring (token.length ()); + while (tokens.hasMoreTokens () && found) + { + token = tokens.nextToken (); + if (token.equals ("*")) + wildcard = Star; + else if (token.equals ("+")) + wildcard = Plus; + else if (token.equals (".")) + wildcard = Dot; + else if (wildcard == Star) + { + int index = tmpString.indexOf (token); + if (index >= 0) + tmpString = tmpString.substring (index + token.length ()); + else + found = false; + } + else if (wildcard == Plus) + { + int index = tmpString.indexOf (token); + if (index > 0) + tmpString = tmpString.substring (index + token.length ()); + else + found = false; + } + else if (wildcard == Dot) + { + int index = tmpString.indexOf (token); + if (index == 1) + tmpString = tmpString.substring (1 + token.length ()); + else + found = false; + } + } + if (found && tmpString.equals ("")) + break; + } + } + } + return found && tmpString.equals (""); + } // matchesClosedWildKeyword + + /** + * + **/ + private String matchesOpenWildcard (String string) + { + Enumeration e = openEndedKeywords.elements (); + String prepend = ""; + while (e.hasMoreElements ()) + { + int wildcard = None; + boolean found = true; + String tmpString = string; + StringTokenizer tokens = new StringTokenizer ((String)e.nextElement (), "*+.", true); + while (tokens.hasMoreTokens () && found) + { + String token = tokens.nextToken (); + if (token.equals ("*")) + wildcard = Star; + else if (token.equals ("+")) + wildcard = Plus; + else if (token.equals (".")) + wildcard = Dot; + else if (wildcard == Star) + { + wildcard = None; + int index = tmpString.lastIndexOf (token); + if (index >= 0) + tmpString = blankOutMatch (tmpString, index, token.length ()); + else + found = false; + } + else if (wildcard == Plus) + { + wildcard = None; + int index = tmpString.lastIndexOf (token); + if (index > 0) + tmpString = blankOutMatch (tmpString, index, token.length ()); + else + found = false; + } + else if (wildcard == Dot) + { + wildcard = None; + int index = tmpString.lastIndexOf (token); + if (index == 1) + tmpString = blankOutMatch (tmpString, 1, token.length ()); + else + found = false; + } + else if (wildcard == None) + if (tmpString.startsWith (token)) + tmpString = blankOutMatch (tmpString, 0, token.length ()); + else + found = false; + } + + // Make sure that, if the last character of the keyword is a + // wildcard, that the string matches what the wildcard + // requires. + if (found) + { + if (wildcard == Star) + ; + else if (wildcard == Plus && tmpString.lastIndexOf (' ') != tmpString.length () - 1) + ; + else if (wildcard == Dot && tmpString.lastIndexOf (' ') == tmpString.length () - 2) + ; + else if (wildcard == None && tmpString.lastIndexOf (' ') == tmpString.length () - 1) + ; + else + found = false; + } + // If found, then prepend an underscore. But also try matching + // again after leading and trailing blanks are removed from + // tmpString. This isn't quite right, but it solves a problem + // which surfaced in the Java mapping. For example: + // openEndedKeywords = {"+Helper", "+Holder", "+Package"}; + // string = fooHelperPackage. + // Given the mechanics of the Java mapping, _fooHelperPackage + // COULD have a conflict, so for each occurance of a keyword, + // an underscore is added, so this would cause two underscores: + // __fooHelperPackage. To accomplish this, the first time thru + // tmpString is "fooHelper " at this point, strip off the + // trailing blanks and try matching "fooHelper". This also + // matches, so two underscores are prepended. + if (found) + { + prepend = prepend + "_" + matchesOpenWildcard (tmpString.trim ()); + break; + } + } + return prepend; + } // matchesOpenWildcard + + /** + * + **/ + private String blankOutMatch (String string, int start, int length) + { + char[] blanks = new char [length]; + for (int i = 0; i < length; ++i) + blanks[i] = ' '; + return string.substring (0, start) + new String (blanks) + string.substring (start + length); + } // blankOutMatch + + /** + * + **/ + private String getIdentifier (String string) + { + if (keywords.contains (string)) + // string matches a non-wildcard keyword + string = '_' + string; + else + { + // Check to see if string matches any wildcard keywords that + // aren't open ended (don't have a wildcard as the first or + // last character. + String prepend = ""; + if (matchesClosedWildKeyword (string)) + prepend = "_"; + else + // string did not match any closed wildcard keywords (that + // is, keywords with wildcards anywhere but at the beginning + // or end of the word). + // Now check for * + or . at the beginning or end. + // These require special handling because they could match + // more than one keyword. prepend an underscore for each + // matched keyword. + prepend = matchesOpenWildcard (string); + string = prepend + string; + } + return string; + } // getIdentifier + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getDirective () throws IOException + { + readChar (); + String string = new String (); + while ((data.ch >= 'a' && data.ch <= 'z') || (data.ch >= 'A' && data.ch <= 'Z')) + { + string = string + data.ch; + readChar (); + } + unread (data.ch); + for (int i = 0; i < com.sun.tools.corba.ee.idl.Token.Directives.length; ++i) + if (string.equals (com.sun.tools.corba.ee.idl.Token.Directives[i])) + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.FirstDirective + i); + // If it got this far, it is an unknown preprocessor directive. + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Unknown, string); + } // getDirective + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getNumber () throws IOException + { + if (data.ch == '.') + return getFractionNoInteger (); + else if (data.ch == '0') + return isItHex (); + else // the only other possibliities are 1..9 + return getInteger (); + } // getNumber + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getFractionNoInteger () throws IOException + { + readChar (); + if (data.ch >= '0' && data.ch <= '9') + return getFraction ("."); + else + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.Period); + } // getFractionNoInteger + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getFraction (String string) throws IOException + { + while (data.ch >= '0' && data.ch <= '9') + { + string = string + data.ch; + readChar (); + } + if (data.ch == 'e' || data.ch == 'E') + return getExponent (string + 'E'); + else + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral, string); + } // getFraction + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getExponent (String string) throws IOException + { + readChar (); + if (data.ch == '+' || data.ch == '-') + { + string = string + data.ch; + readChar (); + } + else if (data.ch < '0' || data.ch > '9') + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + while (data.ch >= '0' && data.ch <= '9') + { + string = string + data.ch; + readChar (); + } + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.FloatingPointLiteral, string); + } // getExponent + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token isItHex () throws IOException + { + readChar (); + if (data.ch == '.') + { + readChar (); + return getFraction ("0."); + } + else if (data.ch == 'x' || data.ch == 'X') + return getHexNumber ("0x"); + else if (data.ch == '8' || data.ch == '9') + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + else if (data.ch >= '0' && data.ch <= '7') + return getOctalNumber (); + else if (data.ch == 'e' || data.ch == 'E') + return getExponent ("0E"); + else + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.IntegerLiteral, "0"); + } // isItHex + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getOctalNumber () throws IOException + { + String string = "0" + data.ch; + readChar (); + while ((data.ch >= '0' && data.ch <= '9')) + { + if (data.ch == '8' || data.ch == '9') + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + string = string + data.ch; + readChar (); + } + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.IntegerLiteral, string); + } // getOctalNumber + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getHexNumber (String string) throws IOException + { + readChar (); + if ((data.ch < '0' || data.ch > '9') && (data.ch < 'a' || data.ch > 'f') && (data.ch < 'A' || data.ch > 'F')) + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + else + while ((data.ch >= '0' && data.ch <= '9') || (data.ch >= 'a' && data.ch <= 'f') || (data.ch >= 'A' && data.ch <= 'F')) + { + string = string + data.ch; + readChar (); + } + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.IntegerLiteral, string); + } // getHexNumber + + /** + * + **/ + private int getNDigitHexNumber (int n) throws IOException + { + readChar (); + if (!isHexChar (data.ch)) + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), + currentLineNumber (), currentLinePosition (), data.ch); + String string = "" + data.ch; + readChar (); + for (int i = 2; i <= n; i++) + { + if (!isHexChar( data.ch)) + break; + string += data.ch; + readChar (); + } + try + { + return Integer.parseInt (string, 16); + } + catch (NumberFormatException e) + { + } + return 0; + } // getNDigitHexNumber + + /** + * + **/ + private boolean isHexChar ( char hex ) + { + return ((data.ch >= '0') && (data.ch <= '9')) || + ((data.ch >= 'a') && (data.ch <= 'f')) || + ((data.ch >= 'A') && (data.ch <= 'F')); + } + + /** + * + **/ + private int get3DigitOctalNumber () throws IOException + { + char firstDigit = data.ch; + String string = "" + data.ch; + readChar (); + if (data.ch >= '0' && data.ch <= '7') + { + string = string + data.ch; + readChar (); + if (data.ch >= '0' && data.ch <= '7') + { + string = string + data.ch; + if (firstDigit > '3') + // This is a 3-digit number bigger than 377 + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), firstDigit); + readChar (); + } + } + int ret = 0; + try + { + ret = Integer.parseInt (string, 8); + } + catch (NumberFormatException e) + { + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), string.charAt (0)); + } + return ret; + } // get3DigitOctalNumber + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token getInteger () throws IOException + { + String string = "" + data.ch; + readChar (); + if (data.ch == '.') + { + readChar (); + return getFraction (string + '.'); + } + else if (data.ch == 'e' || data.ch == 'E') + return getExponent (string + 'E'); + else if (data.ch >= '0' && data.ch <= '9') + while (data.ch >= '0' && data.ch <= '9') + { + string = string + data.ch; + readChar (); + if (data.ch == '.') + { + readChar (); + return getFraction (string + '.'); + } + } + return new com.sun.tools.corba.ee.idl.Token(com.sun.tools.corba.ee.idl.Token.IntegerLiteral, string); + } // getInteger + + /** + * + **/ + private com.sun.tools.corba.ee.idl.Token replaceTrigraph () throws IOException + { + readChar (); + if (data.ch == '?') + { + readChar (); + if (data.ch == '=') + data.ch = '#'; + else if (data.ch == '/') + data.ch = '\\'; + else if (data.ch == '\'') + data.ch = '^'; + else if (data.ch == '(') + data.ch = '['; + else if (data.ch == ')') + data.ch = ']'; + else if (data.ch == '!') + data.ch = '|'; + else if (data.ch == '<') + data.ch = '{'; + else if (data.ch == '>') + data.ch = '}'; + else if (data.ch == '-') + data.ch = '~'; + else + { + unread (data.ch); + unread ('?'); + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + } + return getToken (); + } + else + { + unread ('?'); + throw new com.sun.tools.corba.ee.idl.InvalidCharacter(data.filename, currentLine (), currentLineNumber (), currentLinePosition (), data.ch); + } + } // replaceTrigraph + + /** + * + **/ + void skipWhiteSpace () throws IOException + { + while (data.ch <= ' ') + readChar (); + } // skipWhiteSpace + + /** + * + **/ + private void skipBlockComment () throws IOException + { + try + { + boolean done = false; + readChar (); + while (!done) + { + while (data.ch != '*') + readChar (); + readChar (); + if (data.ch == '/') + done = true; + } + } + catch (EOFException e) + { + com.sun.tools.corba.ee.idl.ParseException.unclosedComment(data.filename); + throw e; + } + } // skipBlockComment + + /** + * + **/ + void skipLineComment () throws IOException + { + while (data.ch != '\n') + readChar (); + } // skipLineComment + + // The following two routines added to extract comments rather + // than ignore them. + + /** + * Extract a line comment from the input buffer. + **/ + private String getLineComment () throws IOException + { + StringBuffer sb = new StringBuffer( "/" ); + while (data.ch != '\n') + { + if (data.ch != '\r') + sb.append (data.ch); + readChar (); + } + return sb.toString(); + } // getLineComment + + /** + * Extract a block comment from the input buffer. + **/ + private String getBlockComment () throws IOException + { + StringBuffer sb = new StringBuffer ("/*"); + try + { + boolean done = false; + readChar (); + sb.append (data.ch); + while (!done) + { + while (data.ch != '*') + { + readChar (); + sb.append (data.ch); + } + readChar (); + sb.append (data.ch); + if (data.ch == '/') + done = true; + } + } + catch (EOFException e) + { + com.sun.tools.corba.ee.idl.ParseException.unclosedComment(data.filename); + throw e; + } + return sb.toString (); + } // getBlockComment + + /** + * + **/ + com.sun.tools.corba.ee.idl.Token skipUntil (char c) throws IOException + { + while (data.ch != c) + { + if (data.ch == '/') + { + readChar (); + if (data.ch == '/') + { + skipLineComment (); + // If this is skipping until the newline, skipLineComment + // reads past the newline, so it won't be seen by the + // while loop conditional check. + if (c == '\n') break; + } + else if (data.ch == '*') + skipBlockComment (); + } + else + readChar (); + } + return getToken (); + } // skipUntil + + // getUntil is used for macro definitions and to get quoted + // strings, so characters within "("...")" and '"'...'"' are + // ignored. Ie getUntil ',' on (,,,,),X will return (,,,,) + + String getUntil (char c) throws IOException + { + return getUntil (c, true, true, true); + } + + String getUntil (char c, boolean allowQuote, boolean allowCharLit, boolean allowComment) throws IOException + { + String string = ""; + while (data.ch != c) + string = appendToString (string, allowQuote, allowCharLit, allowComment); + return string; + } // getUntil + + /** + * + **/ + String getUntil (char c1, char c2) throws IOException + { + String string = ""; + while (data.ch != c1 && data.ch != c2) + string = appendToString (string, false, false, false); + return string; + } // getUntil + + /** + * + **/ + private String appendToString (String string, boolean allowQuote, boolean allowCharLit, boolean allowComment) throws IOException + { + // Ignore any comments if they are allowed + if (allowComment && data.ch == '/') + { + readChar (); + if (data.ch == '/') + skipLineComment (); + else if (data.ch == '*') + skipBlockComment (); + else + string = string + '/'; + } + // Handle line continuation character + else if (data.ch == '\\') + { + readChar (); + if (data.ch == '\n') + readChar (); + else if (data.ch == '\r') + { + readChar (); + if (data.ch == '\n') + readChar (); + } + else + { + string = string + '\\' + data.ch; + readChar (); + } + } + // characters within "("...")" and '"'...'"' are ignored. + // Ie getUntil ',' on (,,,,),X will return (,,,) + else + { + if (allowCharLit && data.ch == '"') + { + readChar (); + string = string + '"'; + while (data.ch != '"') + string = appendToString (string, true, false, allowComment); + } + else if (allowQuote && allowCharLit && data.ch == '(') + { + readChar (); + string = string + '('; + while (data.ch != ')') + string = appendToString (string, false, false, allowComment); + } + else if (allowQuote && data.ch == '\'') + { + readChar (); + string = string + "'"; + while (data.ch != '\'') + string = appendToString (string, false, true, allowComment); + } + string = string + data.ch; + readChar (); + } + return string; + } // appendToString + + /** + * + **/ + String getStringToEOL () throws IOException + { + String string = new String (); + while (data.ch != '\n') + { + if (data.ch == '\\') + { + readChar (); + if (data.ch == '\n') + readChar (); + else if (data.ch == '\r') + { + readChar (); + if (data.ch == '\n') + readChar (); + } + else + { + string = string + data.ch; + readChar (); + } + } + else + { + string = string + data.ch; + readChar (); + } + } + return string; + } // getStringToEOL + + /** + * + **/ + String filename () + { + return data.filename; + } // filename + + /** + * + **/ + com.sun.tools.corba.ee.idl.IncludeEntry fileEntry () + { + return data.fileEntry; + } // fileEntry + + /** + * + **/ + int currentLineNumber () + { + return data.line; + } // currentLineNumber + + /** + * + **/ + int lastTokenLineNumber () + { + return data.oldLine; + } // lastTokenLineNumber + + private int BOL; // Beginning Of Line + + /** + * + **/ + String currentLine () + { + BOL = data.fileIndex - 1; + try + { + // If the current position is at the end of the line, + // set BOL to before the end of the line so the whole + // line is returned. + if (data.fileBytes[BOL - 1] == '\r' && data.fileBytes[BOL] == '\n') + BOL -= 2; + else if (data.fileBytes[BOL] == '\n') + --BOL; + while (data.fileBytes[BOL] != '\n') + --BOL; + } + catch (ArrayIndexOutOfBoundsException e) + { + BOL = -1; + } + ++BOL; // Go to the first character AFTER the newline + int EOL = data.fileIndex - 1; + try + { + while (data.fileBytes[EOL] != '\n' && data.fileBytes[EOL] != '\r') + ++EOL; + } + catch (ArrayIndexOutOfBoundsException e) + { + EOL = data.fileBytes.length; + } + if (BOL < EOL) + return new String (data.fileBytes, BOL, EOL - BOL); + else + return ""; + } // currentLine + + /** + * + **/ + String lastTokenLine () + { + int saveFileIndex = data.fileIndex; + data.fileIndex = data.oldIndex; + String ret = currentLine (); + data.fileIndex = saveFileIndex; + return ret; + } // lastTokenLine + + /** + * + **/ + int currentLinePosition () + { + return data.fileIndex - BOL; + } // currentLinePosition + + /** + * + **/ + int lastTokenLinePosition () + { + return data.oldIndex - BOL; + } // lastTokenLinePosition + + // The scanner data is moved to a separate class so that all of the + // data can easily be pushed and popped to a stack. + + // The data must be stackable for macros and #included files. When + // a macro is encountered: the current stack data is reserved on + // the stack; the stack is loaded with the macro info; processing + // proceeds with this data. The same is true for #included files. + + // It may seem that the entire Scanner should be put on a stack in + // the Parser since all the scanner data is stackable. But that + // would mean instantiating a new scanner. The scanner must + // continue from where it left off; when certain things cross file + // boundaries, they must be handled by the scanner, not the parser, + // things like: block comments, quoted strings, tokens. + private ScannerData data = new ScannerData (); + private Stack dataStack = new Stack (); + private Vector keywords = new Vector (); + private Vector openEndedKeywords = new Vector (); + private Vector wildcardKeywords = new Vector (); + private boolean verbose; + // Identifiers starting with '_' are considered "Escaped", + // except when scanned during preprocessing. Class Preprocessor is + // responsible to modify the escapedOK flag accordingly. Since preceding + // underscores are now legal when scanning identifiers as well as + // macro identifier, underscoreOK is obsolete. + // + // boolean underscoreOK = false; + boolean escapedOK = true; + // Remove -stateful feature. + // boolean stateful; + private boolean emitAll; + private float corbaLevel; + private boolean debug ; +} // class Scanner + +// This is a dumb class, really just a struct. It contains all of the +// scanner class's data in one place so that that data can be easily +// pushed and popped to a stack. + +/** + * + **/ +class ScannerData +{ + /** + * + **/ + public ScannerData () + { + } // ctor + + /** + * + **/ + public ScannerData (ScannerData that) + { + indent = that.indent; + fileEntry = that.fileEntry; + filename = that.filename; + fileBytes = that.fileBytes; + fileIndex = that.fileIndex; + oldIndex = that.oldIndex; + ch = that.ch; + line = that.line; + oldLine = that.oldLine; + macrodata = that.macrodata; + includeIsImport = that.includeIsImport; + } // copy ctor + + String indent = ""; + com.sun.tools.corba.ee.idl.IncludeEntry fileEntry = null; + String filename = ""; + + // fileBytes is a byte array rather than a char array. This is + // safe because OMG IDL is specified to be ISO Latin-1 whose high- + // order byte is always 0x0. Converted from byte[] to char[] + // to employ Reader classes, which have Character encoding features. + //byte[] fileBytes = null; + char[] fileBytes = null; + int fileIndex = 0; + int oldIndex = 0; + char ch; + int line = 1; + int oldLine = 1; + boolean macrodata = false; + boolean includeIsImport = false; +} // class ScannerData + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/SequenceEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SequenceEntry.java new file mode 100644 index 000000000..0346c99f1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SequenceEntry.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for sequences. + **/ +public class SequenceEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected SequenceEntry () + { + super (); + repositoryID (com.sun.tools.corba.ee.idl.Util.emptyID); + } // ctor + + protected SequenceEntry (SequenceEntry that) + { + super (that); + _maxSize = that._maxSize; + } // ctor + + protected SequenceEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (!(that instanceof SequenceEntry)) + // If that is a SequenceEntry, then it is a container of this sequence, but it is not a module of this sequence. It's name doesn't belong in the module name. + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + repositoryID (com.sun.tools.corba.ee.idl.Util.emptyID); + } // ctor + + public Object clone () + { + return new SequenceEntry (this); + } // clone + + public boolean isReferencable() + { + // A sequence is referencable if its component + // type is. + return type().isReferencable() ; + } + + public void isReferencable( boolean value ) + { + // NO-OP: this cannot be set for a sequence. + } + + /** Invoke the sequence generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + sequenceGen.generate (symbolTable, this, stream); + } // generate + + /** Access the sequence generator. + @return an object which implements the SequenceGen interface. + @see com.sun.tools.corba.ee.idl.SequenceGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return sequenceGen; + } // generator + + /** the constant expression defining the maximum size of the sequence. + If it is null, then the sequence is unbounded. */ + public void maxSize (Expression expr) + { + _maxSize = expr; + } // maxSize + + /** the constant expression defining the maximum size of the sequence. + If it is null, then the sequence is unbounded. */ + public Expression maxSize () + { + return _maxSize; + } // maxSize + + /** Only sequences can be contained within sequences. */ + public void addContained (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + _contained.addElement (entry); + } // addContained + + /** Only sequences can be contained within sequences. */ + public Vector contained () + { + return _contained; + } // contained + + static com.sun.tools.corba.ee.idl.SequenceGen sequenceGen; + + private Expression _maxSize = null; + private Vector _contained = new Vector (); +} // class SequenceEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/SequenceGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SequenceGen.java new file mode 100644 index 000000000..40d390e05 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SequenceGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface SequenceGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.SequenceEntry entry, PrintWriter stream); +} // interface SequenceGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/StringEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StringEntry.java new file mode 100644 index 000000000..e2d05b470 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StringEntry.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +import java.io.PrintWriter; +import java.util.Hashtable; + +public class StringEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected StringEntry () + { + super (); + String override = (String) com.sun.tools.corba.ee.idl.Parser.overrideNames.get ("string"); + if (override == null) + name ("string"); + else + name (override); + repositoryID (com.sun.tools.corba.ee.idl.Util.emptyID); + } // ctor + + protected StringEntry (StringEntry that) + { + super (that); + _maxSize = that._maxSize; + } // ctor + + protected StringEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + module (""); + + String override = (String) com.sun.tools.corba.ee.idl.Parser.overrideNames.get ("string"); + if (override == null) + name ("string"); + else + name (override); + repositoryID (com.sun.tools.corba.ee.idl.Util.emptyID); + } // ctor + + public Object clone () + { + return new StringEntry (this); + } // clone + + /** Invoke the string type generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + stringGen.generate (symbolTable, this, stream); + } // generate + + /** Access the primitive type generator. + @return an object which implements the PrimitiveGen interface. + @see com.sun.tools.corba.ee.idl.PrimitiveGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return stringGen; + } // generator + + /** The constant expression defining the maximum size of the string. + If it is null, then the string is unbounded. */ + public void maxSize (Expression expr) + { + _maxSize = expr; + } // maxSize + + /** The constant expression defining the maximum size of the string. + If it is null, then the string is unbounded. */ + public Expression maxSize () + { + return _maxSize; + } // maxSize + + static com.sun.tools.corba.ee.idl.StringGen stringGen; + + private Expression _maxSize = null; +} // class StringEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/StringGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StringGen.java new file mode 100644 index 000000000..7409febd9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StringGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface StringGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.StringEntry entry, PrintWriter stream); +} // interface StringGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/StructEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StructEntry.java new file mode 100644 index 000000000..2ee3f235e --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StructEntry.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for structs. + **/ +public class StructEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected StructEntry () + { + super (); + } // ctor + + protected StructEntry (StructEntry that) + { + super (that); + if (!name ().equals ("")) + { + module (module () + name ()); + name (""); + } + _members = (Vector)that._members.clone (); + _contained = (Vector)that._contained.clone (); + } // ctor + + protected StructEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new StructEntry (this); + } // clone + + /** Invoke the struct generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + structGen.generate (symbolTable, this, stream); + } // generate + + /** Access the struct generator. + @returns an object which implements the StructGen interface. + @see com.sun.tools.corba.ee.idl.StructGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return structGen; + } // generator + + /** Add a member to the member list. */ + public void addMember (com.sun.tools.corba.ee.idl.TypedefEntry member) + { + _members.addElement (member); + } // addMember + + /** This is a vector of TypedefEntry's. In this context, only the name, + type, and arrayInfo fields hold any meaning. */ + public Vector members () + { + return _members; + } // members + + public void addContained (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + _contained.addElement (entry); + } // addContained + + /** This is a vector of SymtabEntry's. It itemizes any types which + this struct contains. It is different than the member list. + For example: +

+      struct A
+      {
+        long x;
+        Struct B
+        {
+          long a;
+          long b;
+        } y;
+      }
+      
+ Struct B is contained within struct A. + The members vector will contain entries for x and y. */ + public Vector contained () + { + return _contained; + } // contained + + private Vector _members = new Vector (); + private Vector _contained = new Vector (); + + static com.sun.tools.corba.ee.idl.StructGen structGen; +} // class StructEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/StructGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StructGen.java new file mode 100644 index 000000000..d20229226 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/StructGen.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface StructGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.StructEntry entry, PrintWriter stream); +} // interface StructGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/SymtabEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SymtabEntry.java new file mode 100644 index 000000000..7b25b298d --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SymtabEntry.java @@ -0,0 +1,351 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; + +import java.util.Hashtable; +import java.util.Stack; +import java.util.Vector; + +/** + * This is the base class for all symbol table entries. + * @see AttributeEntry + * @see com.sun.tools.corba.ee.idl.ConstEntry + * @see com.sun.tools.corba.ee.idl.EnumEntry + * @see com.sun.tools.corba.ee.idl.ExceptionEntry + * @see com.sun.tools.corba.ee.idl.IncludeEntry + * @see com.sun.tools.corba.ee.idl.InterfaceEntry + * @see com.sun.tools.corba.ee.idl.MethodEntry + * @see com.sun.tools.corba.ee.idl.ModuleEntry + * @see com.sun.tools.corba.ee.idl.ParameterEntry + * @see com.sun.tools.corba.ee.idl.PragmaEntry + * @see com.sun.tools.corba.ee.idl.PrimitiveEntry + * @see com.sun.tools.corba.ee.idl.SequenceEntry + * @see com.sun.tools.corba.ee.idl.StructEntry + * @see com.sun.tools.corba.ee.idl.TypedefEntry + * @see com.sun.tools.corba.ee.idl.UnionEntry + **/ +public class SymtabEntry +{ + public SymtabEntry () + { + initDynamicVars (); + } // ctor + + SymtabEntry (SymtabEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + _module = that._module; + _name = that._name; + _type = that._type; + _typeName = that._typeName; + _sourceFile = that._sourceFile; + _info = that._info; + _repID = (com.sun.tools.corba.ee.idl.RepositoryID)clone.clone (); + ((com.sun.tools.corba.ee.idl.IDLID)_repID).appendToName (_name); + if (that instanceof com.sun.tools.corba.ee.idl.InterfaceEntry || that instanceof com.sun.tools.corba.ee.idl.ModuleEntry || that instanceof com.sun.tools.corba.ee.idl.StructEntry || that instanceof com.sun.tools.corba.ee.idl.UnionEntry || (that instanceof com.sun.tools.corba.ee.idl.SequenceEntry && this instanceof com.sun.tools.corba.ee.idl.SequenceEntry)) + _container = that; + else + _container = that._container; + initDynamicVars (); + _comment = that._comment; // <21jul1997daz> + } // ctor + + /** This is a shallow copy constructor */ + SymtabEntry (SymtabEntry that) + { + _module = that._module; + _name = that._name; + _type = that._type; + _typeName = that._typeName; + _sourceFile = that._sourceFile; + _info = that._info; + _repID = (com.sun.tools.corba.ee.idl.RepositoryID)that._repID.clone (); + _container = that._container; + + if (_type instanceof com.sun.tools.corba.ee.idl.ForwardEntry) + ((com.sun.tools.corba.ee.idl.ForwardEntry)_type).types.addElement (this); + + initDynamicVars (); + // <21JUL1997> + _comment = that._comment; + } // ctor + + void initDynamicVars () + { + _dynamicVars = new Vector (maxKey + 1); + for (int i = 0; i <= maxKey; ++i) + _dynamicVars.addElement (null); + } // initDynamicVars + + /** This is a shallow copy clone */ + public Object clone () + { + return new SymtabEntry (this); + } // clone + + /** @return the concatenation of the module and the name, delimited by '/'. */ + public final String fullName () + { + return _module.equals ("") ? _name : _module + '/' + _name; + } // fullName + + /** Get the name of this entry's module. If there are modules within + modules, each module name is separated by '/'. + @return this entry's module name. */ + public String module () + { + return _module; + } // module + + /** Set the module for this entry. + @param newName the new name of the module. */ + public void module (String newName) + { + if (newName == null) + _module = ""; + else + _module = newName; + } // module + + /** @return the name of this entry. */ + public String name () + { + return _name; + } // name + + /** Set the name. + @param newName the new name. */ + public void name (String newName) + { + if (newName == null) + _name = ""; + else + _name = newName; + + // Update the RepositoryID + if (_repID instanceof com.sun.tools.corba.ee.idl.IDLID) + ((com.sun.tools.corba.ee.idl.IDLID)_repID).replaceName (newName); + } // name + + /** @return the type name of this entry. */ + public String typeName () + { + return _typeName; + } // typeName + + protected void typeName (String typeName) + { + _typeName = typeName; + } // typeName + + /** @return the type entry of this entry */ + public SymtabEntry type () + { + return _type; + } // type + + public void type (SymtabEntry newType) + { + if (newType == null) + typeName (""); + else + typeName (newType.fullName ()); + _type = newType; + + if (_type instanceof com.sun.tools.corba.ee.idl.ForwardEntry) + ((com.sun.tools.corba.ee.idl.ForwardEntry)_type).types.addElement (this); + } // type + + /** The file name in which this entry was defined. */ + public com.sun.tools.corba.ee.idl.IncludeEntry sourceFile () + { + return _sourceFile; + } // sourceFile + + /** The file name in which this entry was defined. */ + public void sourceFile (com.sun.tools.corba.ee.idl.IncludeEntry file) + { + _sourceFile = file; + } // sourceFile + + /** This must be either an InterfaceEntry or a ModuleEntry. + It can be nothing else. */ + public SymtabEntry container () + { + return _container; + } // container + + /** This must be either an InterfaceEntry or a ModuleEntry. + It can be nothing else. */ + public void container (SymtabEntry newContainer) + { + if (newContainer instanceof com.sun.tools.corba.ee.idl.InterfaceEntry || newContainer instanceof com.sun.tools.corba.ee.idl.ModuleEntry) + _container = newContainer; + } // container + + /** @return the repository ID for this entry. */ + public com.sun.tools.corba.ee.idl.RepositoryID repositoryID () + { + return _repID; + } // repositoryID + + /** Set the repository ID for this entry. + @param id the new repository ID. */ + public void repositoryID (com.sun.tools.corba.ee.idl.RepositoryID id) + { + _repID = id; + } // repositoryID + + /** Should this type be emitted? */ + public boolean emit () + { + return _emit && _isReferencable ; + } // emit + + public void emit (boolean emit) + { + _emit = emit; + } // emit + + /* <21jul1997daz> Accessors for comment */ + + public com.sun.tools.corba.ee.idl.Comment comment() + { + return _comment; + } + + public void comment( com.sun.tools.corba.ee.idl.Comment comment ) + { + _comment = comment; + } + + public boolean isReferencable() + { + return _isReferencable ; + } + + public void isReferencable( boolean value ) + { + _isReferencable = value ; + } + + static Stack includeStack = new Stack<>(); + + static void enteringInclude () + { + includeStack.push (setEmit); + setEmit = false; + } // enteringInclude + + static void exitingInclude () + { + setEmit = includeStack.pop(); + } // exitingInclude + + /** Other variables besides the default ones can be dynamically placed + into SymTabEntry (and therefore on all symbol table entries) by + extenders. Before such a variable can exist, its key must be + obtained by calling getVariableKey. */ + public static int getVariableKey () + { + return ++maxKey; + } // dynamicVariable + + /** Other variables besides the default ones can be dynamically placed + into SymTabEntry (and therefore on all symbol table entries) by + extenders. This method assigns the value to the variable of the + given key. A valid key must be obtained by calling the method + getVariableKey. If the key is invalid, NoSuchFieldException is + thrown. */ + public void dynamicVariable (int key, Object value) throws NoSuchFieldException + { + if (key > maxKey) + throw new NoSuchFieldException (Integer.toString (key)); + else + { + if (key >= _dynamicVars.size ()) + growVars (); + _dynamicVars.setElementAt (value, key); + } + } // dynamicVariable + + /** Other variables besides the default ones can be dynamically placed + into SymTabEntry (and therefore on all symbol table entries) by + extenders. This method gets the value of the variable of the + given key. A valid key must be obtained by calling the method + getVariableKey. If the key is invalid, NoSuchFieldException is + thrown. */ + public Object dynamicVariable (int key) throws NoSuchFieldException + { + if (key > maxKey) + throw new NoSuchFieldException (Integer.toString (key)); + else + { + if (key >= _dynamicVars.size ()) + growVars (); + return _dynamicVars.elementAt (key); + } + } // dynamicVariable + + void growVars () + { + int diff = maxKey - _dynamicVars.size () + 1; + for (int i = 0; i < diff; ++i) + _dynamicVars.addElement (null); + } // growVars + + /** Invoke a generator. A call to this method is only meaningful + for subclasses of SymtabEntry. If called on this class, it + is a no-op. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + } // generate + + /** Access a generator. A call to this method is only meaningful + for subclasses of SymtabEntry. If called on this class, it + is a no-op. + @return an object which implements the Generator interface. */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return null; + } // generator + + static boolean setEmit = true; + static int maxKey = -1; + + private SymtabEntry _container = null; + private String _module = ""; + private String _name = ""; + private String _typeName = ""; + private SymtabEntry _type = null; + private com.sun.tools.corba.ee.idl.IncludeEntry _sourceFile = null; + private Object _info = null; + private com.sun.tools.corba.ee.idl.RepositoryID _repID = new com.sun.tools.corba.ee.idl.IDLID("", "", "1.0"); + private boolean _emit = setEmit; + private com.sun.tools.corba.ee.idl.Comment _comment = null; + private Vector _dynamicVars; + private boolean _isReferencable = true ; +} // class SymtabEntry + +/*======================================================================================= + DATE ACTION + --------------------------------------------------------------------------------------- + 21jul1997 Added _comment data member to afford transferring comments from source + file to target; added acessor methods for comment. + =======================================================================================*/ diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/SymtabFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SymtabFactory.java new file mode 100644 index 000000000..4aee898c9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/SymtabFactory.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +/** + * Each entry must have three ways in which it can be instantiated: + *
    + *
  • with no parameters; + *
  • cloned from a copy of itself; + *
  • the normal-use instantiation (usually with 2 parameters: the container and the id of the container). + *
+ **/ +public interface SymtabFactory +{ + AttributeEntry attributeEntry (); + AttributeEntry attributeEntry (com.sun.tools.corba.ee.idl.InterfaceEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ConstEntry constEntry (); + com.sun.tools.corba.ee.idl.ConstEntry constEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.NativeEntry nativeEntry (); + com.sun.tools.corba.ee.idl.NativeEntry nativeEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.EnumEntry enumEntry (); + com.sun.tools.corba.ee.idl.EnumEntry enumEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ExceptionEntry exceptionEntry (); + com.sun.tools.corba.ee.idl.ExceptionEntry exceptionEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ForwardEntry forwardEntry (); + com.sun.tools.corba.ee.idl.ForwardEntry forwardEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ForwardValueEntry forwardValueEntry (); + com.sun.tools.corba.ee.idl.ForwardValueEntry forwardValueEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.IncludeEntry includeEntry (); + com.sun.tools.corba.ee.idl.IncludeEntry includeEntry (com.sun.tools.corba.ee.idl.SymtabEntry container); + + com.sun.tools.corba.ee.idl.InterfaceEntry interfaceEntry (); + com.sun.tools.corba.ee.idl.InterfaceEntry interfaceEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ValueEntry valueEntry (); + com.sun.tools.corba.ee.idl.ValueEntry valueEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ValueBoxEntry valueBoxEntry (); + com.sun.tools.corba.ee.idl.ValueBoxEntry valueBoxEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.MethodEntry methodEntry (); + com.sun.tools.corba.ee.idl.MethodEntry methodEntry (com.sun.tools.corba.ee.idl.InterfaceEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ModuleEntry moduleEntry (); + com.sun.tools.corba.ee.idl.ModuleEntry moduleEntry (com.sun.tools.corba.ee.idl.ModuleEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.ParameterEntry parameterEntry (); + com.sun.tools.corba.ee.idl.ParameterEntry parameterEntry (com.sun.tools.corba.ee.idl.MethodEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.PragmaEntry pragmaEntry (); + com.sun.tools.corba.ee.idl.PragmaEntry pragmaEntry (com.sun.tools.corba.ee.idl.SymtabEntry container); + + com.sun.tools.corba.ee.idl.PrimitiveEntry primitiveEntry (); + /** name can be, but is not limited to, the primitive idl type names: + char, octet, short, long, etc. The reason it is not limited to + these is that, as an extender, you may wish to override these names. + For instance, when generating Java code, octet translates to byte, + so there is an entry in Compile.overrideNames: <"octet", "byte"> + and a PrimitiveEntry in the symbol table for "byte". */ + com.sun.tools.corba.ee.idl.PrimitiveEntry primitiveEntry (String name); + + com.sun.tools.corba.ee.idl.SequenceEntry sequenceEntry (); + com.sun.tools.corba.ee.idl.SequenceEntry sequenceEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.StringEntry stringEntry (); + + com.sun.tools.corba.ee.idl.StructEntry structEntry (); + com.sun.tools.corba.ee.idl.StructEntry structEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry (); + com.sun.tools.corba.ee.idl.TypedefEntry typedefEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); + + com.sun.tools.corba.ee.idl.UnionEntry unionEntry (); + com.sun.tools.corba.ee.idl.UnionEntry unionEntry (com.sun.tools.corba.ee.idl.SymtabEntry container, com.sun.tools.corba.ee.idl.IDLID id); +} // interface SymtabFactory diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Token.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Token.java new file mode 100644 index 000000000..8aece31c1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Token.java @@ -0,0 +1,671 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -F46082.51 Remove -stateful feature. +// -D59166 Add support for keyword/identifier collision detection. This +// feature is implemented here, rather than class Scanner, to allow the Parser +// to handle the problem. +// -F60858.1 Support -corba option, level <= 2.2: identify 2.3 keywords. +// -D62023 Support -corba option, level <= 2.3, identify 2.4 keywords. +// KMC Support -corba, level <= 3.0. Added 3.0 keywords. +// +// Should escaped Identifier should be a type rather than an attribute? +// + +/** + * Class Token represents a lexeme appearing within an IDL source. Every + * Token has a type. Depending on its type and on the supported version + * of IDL, a Token will have other associated attributes, such as a name + * (identifier, e.g.), and whether it is escaped, deprecated, or is a type + * that is known to be in a future version of IDL. + **/ +class Token +{ + /////////////// + // Available types + + static final int // Keywords + Any = 0, // 2.2 + Attribute = 1, // | + Boolean = 2, // . + Case = 3, // . + Char = 4, // . + Const = 5, + Context = 6, + Default = 7, + Double = 8, + Enum = 9, + Exception = 10, + FALSE = 11, + Fixed = 12, // New addition + Float = 13, + In = 14, + Inout = 15, + Interface = 16, + Long = 17, + Module = 18, + Native = 19, // New addition + Object = 20, + Octet = 21, + Oneway = 22, + Out = 23, + Raises = 24, + Readonly = 25, + Sequence = 26, + Short = 27, + String = 28, + Struct = 29, + Switch = 30, + TRUE = 31, + Typedef = 32, + Unsigned = 33, // . + Union = 34, // . + Void = 35, // . + Wchar = 36, // | + Wstring = 37, // 2.2 + // New OBV keywords... + // In 2.4rtf, "factory" is synonymous to "init" in 2.3 + Init = 38, // 2.3 only + Abstract = 39, // 2.3 2.4rtf + Custom = 40, // | | + Private = 41, // | | + Public = 42, // | | + Supports = 43, // | | + Truncatable = 44, // | | + ValueBase = 45, // | | + Valuetype = 46, // 2.3 2.4rtf + Factory = 47, // 2.4rtf only + + // Keywords in CORBA 3.0 + Component = 48, + Consumes = 49, + Emits = 50, + Finder = 51, + GetRaises = 52, + Home = 53, + Import = 54, + Local = 55, + Manages = 56, + Multiple = 57, + PrimaryKey = 58, + Provides = 59, + Publishes = 60, + SetRaises = 61, + TypeId = 62, + TypePrefix = 63, + Uses = 64, + + Identifier = 80, // Identifier + MacroIdentifier = 81, // Macro Identifier + + Semicolon = 100, // Symbols + LeftBrace = 101, + RightBrace = 102, + Colon = 103, + Comma = 104, + Equal = 105, + Plus = 106, + Minus = 107, + LeftParen = 108, + RightParen = 109, + LessThan = 110, + GreaterThan = 111, + LeftBracket = 112, + RightBracket = 113, + Apostrophe = 114, + Quote = 115, + Backslash = 116, + Bar = 117, + Carat = 118, + Ampersand = 119, + Star = 120, + Slash = 121, + Percent = 122, + Tilde = 123, + DoubleColon = 124, + ShiftLeft = 125, + ShiftRight = 126, + Period = 127, + Hash = 128, + Exclamation = 129, + DoubleEqual = 130, + NotEqual = 131, + GreaterEqual = 132, + LessEqual = 133, + DoubleBar = 134, + DoubleAmpersand = 135, + + BooleanLiteral = 200, // Literals + CharacterLiteral = 201, + IntegerLiteral = 202, + FloatingPointLiteral = 203, + StringLiteral = 204, + Literal = 205, + + Define = 300, // Directives + Undef = 301, + If = 302, + Ifdef = 303, + Ifndef = 304, + Else = 305, + Elif = 306, + Include = 307, + Endif = 308, + Line = 309, + Error = 310, + Pragma = 311, + Null = 312, + Unknown = 313, + + Defined = 400, + + // Keyword identifiers. + //Abstract = 500, + //Custom = 501, + //Init = 502, + //Private2 = 503, + //Public2 = 504, + //Supports = 505, + //Truncatable = 506, + //ValueBase = 507, + //Valuetype = 508, + + EOF = 999; // End of Input + + // Available types + /////////////// + // Keywords + + static final String [] Keywords = { + "any", "attribute", "boolean", + "case", "char", "const", + "context", "default", "double", + "enum", "exception", "FALSE", "fixed", + "float", "in", "inout", + "interface", "long", "module", "native", + "Object", "octet", "oneway", + "out", "raises", "readonly", + "sequence", "short", "string", + "struct", "switch", "TRUE", + "typedef", "unsigned", "union", + "void", "wchar", "wstring", + "init", // In 2.3 only + "abstract", "custom", "private", // 2.3 and 2.4rtf + "public", "supports", "truncatable", + "ValueBase", "valuetype", + "factory", // In 2.4rtf only + // CORBA 3.0 keywords + "component", "consumes", "emits", + "finder", "getRaises", "home", + "import", "local", "manages", + "multiple", "primaryKey", "provides", + "publishes", "setRaises", "supports", + "typeId", "typePrefix", "uses" } ; + + // Remove keyword identifiers. + //static final int + // FirstKeywordIdentifier = 500, + // LastKeywordIdentifier = Valuetype; + // + //static final String[] KeywordIdentifiers = { + // "abstract", "custom", "init", + // "private", "public", "supports", + // "truncatable", "valueBase", "valuetype"}; + + /** + * Determine whether this token is a keyword. + * @return true iff this token is a keyword. + **/ + boolean isKeyword () + { + return type >= FirstKeyword && type <= LastKeyword; + } // isKeyword + + private static final int + FirstKeyword = Any, // 0 + LastKeyword = Uses; + + // Keywords in CORBA 2.2 that we support. + private static final int + First22Keyword = Any, // 0 + Last22Keyword = Wstring; + + // New keywords in CORBA 2.3 (preliminary) that we support. + private static final int + First23Keyword = Init, + Last23Keyword = Valuetype; + + // New keywords in CORBA 2.4rtf (accepted 2.3) that we support. + // Note that "factory" replaces "init". Scanner must account for this in + // keyword scan. + private static final int + First24rtfKeyword = Abstract, + Last24rtfKeyword = Factory; + + // New keywords in CORBA 3.0 (from CORBA components v. 1) + private static final int + First30Keyword = Component, + Last30Keyword = Uses; + + // Current valid CORBA levels: + // 2.2 (or <2.3): the default: no OBV support + // 2.3: add OBV with init + // >2.3: OBV with init replcaed by factory + // 3.0: adds components, attr exceptions, local interfaces, type repository + // decls. + + private static final int CORBA_LEVEL_22 = 0 ; + private static final int CORBA_LEVEL_23 = 1 ; + private static final int CORBA_LEVEL_24RTF = 2 ; + private static final int CORBA_LEVEL_30 = 3 ; + + // Do the conversion from a floating point CORBA level to an int + private static int getLevel( float cLevel ) + { + if (cLevel < 2.3f) + return CORBA_LEVEL_22 ; + if (Util.absDelta(cLevel, 2.3f) < 0.001f) + return CORBA_LEVEL_23 ; + if (cLevel < 3.0f) + return CORBA_LEVEL_24RTF ; + return CORBA_LEVEL_30 ; + } + + // Return the last keyword corresponding to a particular CORBA level + private static int getLastKeyword( int level ) + { + if (level == CORBA_LEVEL_22) + return Last22Keyword ; + if (level == CORBA_LEVEL_23) + return Last23Keyword ; + if (level == CORBA_LEVEL_24RTF) + return Last24rtfKeyword ; + return Last30Keyword ; + } + + /** Create a keyword token from a string. + * Determines whether the string is an IDL keyword based on the corbaLevel. + * Strings that are keywords at higher CORBA levels than the corbaLevel + * argument create identifier tokens that are marked as "collidesWithKeyword", unless + * escapedOK is FALSE, which is the case only when preprocessing is taking place. + * In the case of the "init" keyword, which was only defined in CORBA 2.3, init is + * marked deprecated in CORBA 2.3 since it is not supported in higher levels. + * @param String string The string we are converting to a token. + * @param float corbaLevel The CORBA level, currently in the interval [2.2, 3.0]. + * @param boolean escapedOK Flag set true if _ is used to escape an IDL keyword for use + * as an identifier. + * @param boolean[] collidesWithKeyword is an array containing one value: a flag + * representing whether this string is an identifier that collides with a keyword. + * This is set by this method. + * @returns Token The resulting Token corresponding to string. + */ + public static Token makeKeywordToken( + String string, float corbaLevel, boolean escapedOK, boolean[] collision ) + { + int level = getLevel( corbaLevel ) ; + int lastKeyword = getLastKeyword( level ) ; + boolean deprecated = false ; + collision[0] = false ; + + // If the string is a keyword token, return that token + for (int i = Token.FirstKeyword; i <= Token.LastKeyword; ++i) { + if (string.equals (Token.Keywords[i])) { + // Return identifier if lexeme is a keyword in a + // greater CORBA level; collect attributes indicating future keyword/ + // identifier collision and deprecations. + + // Init is really a funny case. I don't want to mark it as + // a keyword collision in the 2.2 case, since it was only + // defined to be a keyword briefly in 2.3. + if (i == Token.Init) { + if (level == CORBA_LEVEL_23) + deprecated = true ; + else + break ; + } + + if (i > lastKeyword) { + collision[0] |= escapedOK; // escapedOK true iff not preprocessing + break ; + } + + if (string.equals ("TRUE") || string.equals ("FALSE")) + return new Token (Token.BooleanLiteral, string) ; + else + return new Token (i, deprecated); + } else if (string.equalsIgnoreCase (Token.Keywords[i])) { + // PU! This will go away in a future release, because + // case-insensitive keyword checking will be standard. For now, + // indicate that a keyword collision has occurred. + collision[0] |= true; + break; + } + } // for i <= lastKeyword + + return null ; + } // makeKeywordToken + + // Keywords + /////////////// + // Symbols + + static final int + FirstSymbol = 100, + LastSymbol = 199; + + static final String [] Symbols = { + ";", "{", "}", ":", ",", "=", "+", "-", + "(", ")", "<", ">", "[", "]", "'", "\"", + "\\", "|", "^", "&", "*", "/", "%", "~", + "::", "<<", ">>", ".", "#", "!", "==", "!=", + ">=", "<=", "||", "&&"}; + + // Symbols + /////////////// + // Literals + + static final int + FirstLiteral = 200, + LastLiteral = 299; + + static final String [] Literals = { + Util.getMessage("Token.boolLit"), + Util.getMessage("Token.charLit"), + Util.getMessage("Token.intLit"), + Util.getMessage("Token.floatLit"), + Util.getMessage("Token.stringLit"), + Util.getMessage("Token.literal")}; + + // Literals + /////////////// + // Directives + + /** + * Determine whether this token is a preprocessor directive. + * @return true iff this token is a preprocessor directive. + **/ + boolean isDirective () + { + return type >= FirstDirective && type <= LastDirective; + } // isDirective + + static final int + FirstDirective = 300, + LastDirective = 399; + + static final String [] Directives = { + "define", "undef", "if", + "ifdef", "ifndef", "else", + "elif", "include","endif", + "line", "error", "pragma", + ""}; + + // Directives + /////////////// + // Specials + + static final int + FirstSpecial = 400, + LastSpecial = 499; + + static final String [] Special = { + "defined"}; + + // Specials + /////////////// + + /** + * Constructor. + * @return a Token of the supplied type. + **/ + Token (int tokenType) + { + type = tokenType; + } // ctor + + // + /** + * Constructor. + * @return a Token having the supplied attributes. + **/ + Token (int tokenType, boolean deprecated) + { + this.type = tokenType; + this.isDeprecated = deprecated; + } // ctor + + /** + * Constructor. + * @return a Token having the supplied attributes. + **/ + Token (int tokenType, String tokenName) + { + type = tokenType; + name = tokenName; + } // ctor + + /** + * Constructor. + * @return a Token having the supplied attribtues. + * having + **/ + Token (int tokenType, String tokenName, boolean isWide) + { + this (tokenType, tokenName); + this.isWide = isWide; + } // ctor + + + // + /** + * Constructor. + * @return a Token having the supplied attributes. + **/ + Token (int tokenType, String tokenName, boolean escaped, + boolean collision, boolean deprecated) + { + this (tokenType, tokenName); + this.isEscaped = escaped; + this.collidesWithKeyword = collision; + this.isDeprecated = deprecated; + } // ctor + + // Remove keyword identifiers. + ///** + // * Constructor. + // * @return a Token having the supplied attributes. + // **/ + //Token (int tokenType, int tokenSubType, String tokenName) + //{ + // type = tokenType; + // subType = tokenSubType; + // name = tokenName; + //} // ctor + + /** + * Get the String representation of this Token. + * @return a String containing representation of this Token. + **/ + public String toString () + { + if (type == Identifier) + return name; + if (type == MacroIdentifier) + return name + '('; + return Token.toString (type); + } // toString + + /** + * Get the String representation of a supplied Token type. + * @return A String containing the name of the supplied Token type. + **/ + static String toString (int type) + { + if (type <= LastKeyword) + return Keywords[type]; + // Remove keyword identifiers. + //if ( (type >= FirstKeywordIdentifier) && (type <= LastKeywordIdentifier) ) + // return KeywordIdentifiers[ type - FirstKeywordIdentifier ]; + if (type == Identifier || type == MacroIdentifier) + return Util.getMessage("Token.identifier"); + if (type <= LastSymbol) + return Symbols[type - FirstSymbol]; + if (type <= LastLiteral) + return Literals[type - FirstLiteral]; + if (type <= LastDirective) + return Directives[type - FirstDirective]; + if (type <= LastSpecial) + return Special[type - FirstSpecial]; + if (type == EOF) + return Util.getMessage("Token.endOfFile"); + return Util.getMessage("Token.unknown"); + } // toString + + /////////////// + // Accessors and Predicates + + /** + * Determine whether this token equals a supplied token. + * @return true iff the types and names of this and the supplied + * Token are equal. + **/ + boolean equals (Token that) + { + if (this.type == that.type) + if (this.name == null) + return that.name == null; + else + return this.name.equals (that.name); + return false; + } // equals + + /** + * Determine whether the this token is of a supplied type. + * @return true iff the type of this Token equals that supplied. + **/ + boolean equals (int type) + { + return this.type == type; + } // equals + + /** + * Determine whether this identifier has the supplied name. + * @return true iff this Token is an identifier having the supplied name. + **/ + boolean equals (String name) + { + if (this.type == Identifier) { + if ((this.name == null && name == null) || this.name.equals(name)) { + return true ; + } + } + return false ; + } // equals + + // Although isEscaped is an independent attribute, it may be true only + // when type is Identifer. + /** + * Accessor. + * @return true iff this token is an escaped identifier. + **/ + public boolean isEscaped () + { + return type == Identifier && isEscaped; + } // isEscaped + + // + /** + * Accessor. + * @return true iff this token is an identifier having a name matching + * a keyword in a version of CORBA greater than the specified CORBA level, + * or iff it matches a keyword in letter, but note case. + **/ + public boolean collidesWithKeyword () + { + return collidesWithKeyword; + } // collidesWithKeyword + + // Storing deprecation information in a token seems a natural + // means to notify the parser about deprecated types. + /** + * Accessor. + * @return true iff this token is a deprecated lexeme or lexical type with + * respect to the specified CORBA level. + **/ + public boolean isDeprecated () + { + return isDeprecated; + } + // isDeprecated + + public boolean isWide() + { + return isWide ; + } + + // It's more efficient if Scanner determines this attribute. + /** + * Determine whether this token collides with an IDL keyword. + **/ + //public boolean collidesWithKeyword () + //{ + // if (name != null && type == Identifier && !isEscaped) + // { + // String lcName = name.toLowerCase (); + // for (int i = FirstKeyword; i <= LastKeyword; ++i) + // if (lcName.equals (Token.Keywords [i].toLowerCase ())) + // return true; + // } + // return false; + //} // collidesWithKeyword + + // Accessors and Predicates + /////////////// + + /** + * Code identifying the lexical class to which this token belongs, e.g., + * Keyword, Identifier, ... + **/ + int type; + /** + * Lexeme extracted from the source for this token. + **/ + String name = null; + /** + * Source comment associated with this token. + **/ + com.sun.tools.corba.ee.idl.Comment comment = null; + /** + * True iff this token is an escaped identifier. + **/ + boolean isEscaped = false; // + /** + * True iff this token is an identifier that is known to be a keyword + * in another version of CORBA or matches a keyword in letter, but not case. + **/ + boolean collidesWithKeyword = false; // + /** + * True iff this token is deprecated. + **/ + boolean isDeprecated = false; // + // Remove keyword identifier implementation. + ///** + // * Non-zero only when type = [Macro]Identifier + // **/ + //int subType = 0; + + boolean isWide = false ; // Only for string and char literals: indicates that this is + // a wide string or char. +} // class Token + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/TokenBuffer.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/TokenBuffer.java new file mode 100644 index 000000000..d209a6141 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/TokenBuffer.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +class TokenBuffer +{ + private final int DEFAULT_SIZE = 10; + + private int _size = 0; + private Token _buffer [] = null; + private int _currPos = -1; + + TokenBuffer () + { + _size = DEFAULT_SIZE; + _buffer = new Token[_size]; + _currPos = -1; + } // ctor + + TokenBuffer (int size) throws Exception + { + _size = size; // _size == 0 is legal, but useless and problematic + _buffer = new Token[_size]; + _currPos = -1; + } // ctor + + /** Inserts a token at the head of the buffer. */ + void insert (Token token) + { + // _size == 0 ==> ArithmeticException: divide by zero + _currPos = ++_currPos % _size; + _buffer [_currPos] = token; + } + + /** Returns the token residing "i" elements from the head of the buffer. */ + Token lookBack (int i) + { + // Beware: i > _size ==> idx < 0 ==> ArrayOutOfBoundsException + return _buffer [(_currPos - i) >= 0 ? _currPos - i : _currPos - i + _size]; + } + + /** Return the token most recently inserted into the buffer (i.e., the head of the buffer.) */ + Token current () + { + // Beware: _buffer empty || _size == 0 ==> ArrayOutOfBoundsException + return _buffer [_currPos]; + } +} // class TokenBuffer + + +/*================================================================================== + DATE ACTION + ---------------------------------------------------------------------------------- + 11aug1997 Initial version completed. Buffer used to maintain history of + comments extracted from source file during parse. + ==================================================================================*/ + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/TypedefEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/TypedefEntry.java new file mode 100644 index 000000000..df90fab4b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/TypedefEntry.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for typedefs. + **/ +public class TypedefEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected TypedefEntry () + { + super (); + } // ctor + + protected TypedefEntry (TypedefEntry that) + { + super (that); + _arrayInfo = (Vector)that._arrayInfo.clone (); + } // ctor + + protected TypedefEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + /** This method returns a vector of Expressions, each expression + represents a dimension in an array. A zero-length vector indicates + no array information.*/ + public Vector arrayInfo () + { + return _arrayInfo; + } // arrayInfo + + public void addArrayInfo (Expression e) + { + _arrayInfo.addElement (e); + } // addArrayInfo + + public Object clone () + { + return new TypedefEntry (this); + } // clone + + /** Invoke the typedef generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + typedefGen.generate (symbolTable, this, stream); + } // generate + + public boolean isReferencable() + { + // A typedef is referencable if its component + // type is. + return type().isReferencable() ; + } + + public void isReferencable( boolean value ) + { + // NO-OP: this cannot be set for a typedef. + } + + /** Access the typedef generator. + @return an object which implements the TypedefGen interface. + @see com.sun.tools.corba.ee.idl.TypedefGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return typedefGen; + } // generator + + private Vector _arrayInfo = new Vector (); + + static com.sun.tools.corba.ee.idl.TypedefGen typedefGen; +} // class TypedefEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/TypedefGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/TypedefGen.java new file mode 100644 index 000000000..54fef3fdc --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/TypedefGen.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface TypedefGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.TypedefEntry entry, PrintWriter stream); +} // interface TypedefGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionBranch.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionBranch.java new file mode 100644 index 000000000..91706e733 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionBranch.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.util.Vector; + +/** + * This class encapsulates one branch of a union. Here are some examples + * of what it may contain: + *
+ *
+ * case 1: short x; + *
<short x, <1>, false> + *
+ * case 0: + * case 8: + * case 2: long x; + *
<long x, <0, 8, 2>, false> + *
+ * default: long x; + *
<long x, <>, true> + *
+ * case 0: + * case 2: + * default: char c; + *
<char c, <0, 2>, true> + *
+ **/ +public class UnionBranch +{ + /** The type definition for the branch. */ + public TypedefEntry typedef; + /** A vector of Expression's, one for each label in the order in which + they appear in the IDL file. The default branch has no label. */ + public Vector labels = new Vector (); + /** true if this is the default branch. */ + public boolean isDefault = false; +} // class UnionBranch diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionEntry.java new file mode 100644 index 000000000..f98fc9a40 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionEntry.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * This is the symbol table entry for unions. + **/ +public class UnionEntry extends com.sun.tools.corba.ee.idl.SymtabEntry +{ + protected UnionEntry () + { + super (); + } // ctor + + protected UnionEntry (UnionEntry that) + { + super (that); + if (!name ().equals ("")) + { + module (module () + name ()); + name (""); + } + _branches = (Vector)that._branches.clone (); + _defaultBranch = that._defaultBranch; + _contained = that._contained; + } // ctor + + protected UnionEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + if (module ().equals ("")) + module (name ()); + else if (!name ().equals ("")) + module (module () + "/" + name ()); + } // ctor + + public Object clone () + { + return new UnionEntry (this); + } // clone + + /** Invoke the union generator. + @param symbolTable the symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + unionGen.generate (symbolTable, this, stream); + } // generate + + /** Access the union generator. + @return an object which implements the UnionGen interface. + @see com.sun.tools.corba.ee.idl.UnionGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return unionGen; + } // generator + + void addBranch(com.sun.tools.corba.ee.idl.UnionBranch branch) + { + _branches.addElement (branch); + } // addBranch + + /** This is a vector of UnionBranch's. */ + public Vector branches () + { + return _branches; + } // branches + + /** This TypedefEntry describes the type and name for the default branch. + Like the entries in the branches vector, only the type and name fields + are pertinent. */ + public void defaultBranch (com.sun.tools.corba.ee.idl.TypedefEntry branch) + { + _defaultBranch = branch; + } // defaultBranch + + /** This TypedefEntry describes the type and name for the default branch. + Like the entries in the branches vector, only the type and name fields + are pertinent. */ + public com.sun.tools.corba.ee.idl.TypedefEntry defaultBranch () + { + return _defaultBranch; + } // defaultBranch + + public void addContained (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + _contained.addElement (entry); + } // addContained + + /** This is a vector of SymtabEntry's. It itemizes any types which + this union contains. For example: + +
+      union A
+      switch (long)
+      {
+        case 0: long x;
+        case 1:
+          Struct B
+          {
+            long a;
+            long b;
+          } y;
+      }
+      
+ Struct B is contained within union A. */ + public Vector contained () + { + return _contained; + } // contained + + boolean has (Expression label) + { + Enumeration eBranches = _branches.elements (); + while (eBranches.hasMoreElements ()) + { + Enumeration eLabels = ((com.sun.tools.corba.ee.idl.UnionBranch)eBranches.nextElement ()).labels.elements (); + while (eLabels.hasMoreElements ()) + { + Expression exp = (Expression)eLabels.nextElement (); + if (exp.equals (label) || exp.value ().equals (label.value ())) + return true; + } + } + return false; + } // has + + boolean has (com.sun.tools.corba.ee.idl.TypedefEntry typedef) + { + Enumeration e = _branches.elements (); + while (e.hasMoreElements ()) + { + com.sun.tools.corba.ee.idl.UnionBranch branch = (com.sun.tools.corba.ee.idl.UnionBranch)e.nextElement (); + if (!branch.typedef.equals (typedef) && branch.typedef.name ().equals (typedef.name ())) + return true; + } + return false; + } // has + + /** A vector of UnionBranch's. */ + private Vector _branches = new Vector (); + private com.sun.tools.corba.ee.idl.TypedefEntry _defaultBranch = null; + private Vector _contained = new Vector (); + + static com.sun.tools.corba.ee.idl.UnionGen unionGen; +} // class UnionEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionGen.java new file mode 100644 index 000000000..72de1a1e1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/UnionGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface UnionGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symtab, com.sun.tools.corba.ee.idl.UnionEntry entry, PrintWriter stream); +} // interface UnionGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/Util.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Util.java new file mode 100644 index 000000000..f9c5cadd9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/Util.java @@ -0,0 +1,322 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: +// -capitalize and parseTypeModifier should probably be in the +// generators package. +// -D58319 Add version() method. +// -D62023 Add absDelta() method to support float computations. + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.MissingResourceException; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.Vector; + +public class Util +{ + private static final String DEFAULT_MESSAGE_RESOURCE = "com/sun/tools/corba/ee/idl/idl"; + // + /** + * Fetch the version number of this build of the IDL Parser Framework + * from the appropriate properties file. + * @return the version number contained within the appropriate properties + * file, which indicates the build of this IDL Parser Framework. + **/ + public static String getVersion () + { + return getVersion (DEFAULT_MESSAGE_RESOURCE); + } + + /** + * Fetch the version number of this build of the IDL Parser Framework. + * This method may be called before or after the framework has been + * initialized. If the framework is initialized, the version information + * is extracted from the message properties object; otherwise, it is extracted + * from the indicated messages file. + * @return the version number. + **/ + protected static String getVersion(String filename) + { + String version = ""; + if (messages == null) // Use supplied file + { + Vector oldMsgFiles = msgResources; + if (filename == null || filename.equals ("")) + filename = DEFAULT_MESSAGE_RESOURCE; + filename = filename.replace ('/', File.separatorChar); + registerMessageResource(filename); + version = getMessage ("Version.product", getMessage ("Version.number")); + msgResources = oldMsgFiles; + messages = null; + } + else + { + version = getMessage ("Version.product", getMessage ("Version.number")); + } + return version; + } // getVersion + + public static boolean isAttribute (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof AttributeEntry; + } // isAttribute + + public static boolean isConst (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.ConstEntry; + } // isConst + + public static boolean isEnum (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.EnumEntry; + } // isEnum + + public static boolean isException (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.ExceptionEntry; + } // isException + + public static boolean isInterface (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry; + } // isInterface + + public static boolean isMethod (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.MethodEntry; + } // isMethod + + public static boolean isModule (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.ModuleEntry; + } // isModule + + public static boolean isParameter (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.ParameterEntry; + } // isParameter + + public static boolean isPrimitive (String name, Hashtable symbolTable) + { + // Distinguish "string" because the name could be something like: + // string(25 + 1) + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + if (entry == null) + { + // If it is null then it may be of the form string(). + // Don't just check for string because the name "string" may + // have been overridden. + int parenIndex = name.indexOf ('('); + if (parenIndex >= 0) + entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name.substring (0, parenIndex)); + } + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.PrimitiveEntry; + } // isPrimitive + + public static boolean isSequence (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.SequenceEntry; + } // isSequence + + public static boolean isStruct (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.StructEntry; + } // isStruct + + public static boolean isString (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.StringEntry; + } // isString + + public static boolean isTypedef (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.TypedefEntry; + } // isTypedef + + public static boolean isUnion (String name, Hashtable symbolTable) + { + com.sun.tools.corba.ee.idl.SymtabEntry entry = (com.sun.tools.corba.ee.idl.SymtabEntry)symbolTable.get (name); + return entry == null ? false : entry instanceof com.sun.tools.corba.ee.idl.UnionEntry; + } // isUnion + + ////////////// + // Message-related methods + + public static String getMessage (String key) + { + if (messages == null) + readMessages (); + String message = messages.getProperty (key); + if (message == null) + message = getDefaultMessage (key); + return message; + } // getMessage + + public static String getMessage (String key, String fill) + { + if (messages == null) + readMessages (); + String message = messages.getProperty (key); + if (message == null) + message = getDefaultMessage (key); + else + { + int index = message.indexOf ("%0"); + if (index >= 0) + message = message.substring (0, index) + fill + message.substring (index + 2); + } + return message; + } // getMessage + + public static String getMessage (String key, String[] fill) + { + if (messages == null) + readMessages (); + String message = messages.getProperty (key); + if (message == null) + message = getDefaultMessage (key); + else + for (int i = 0; i < fill.length; ++i) + { + int index = message.indexOf ("%" + i); + if (index >= 0) + message = message.substring (0, index) + fill[i] + message.substring (index + 2); + } + return message; + } // getMessage + + private static String getDefaultMessage (String keyNotFound) + { + String message = messages.getProperty (defaultKey); + int index = message.indexOf ("%0"); + if (index > 0) + message = message.substring (0, index) + keyNotFound; + return message; + } // getDefaultMessage + + + private static void readMessages() { + messages = new Properties(); + for (String msgResource : msgResources) + loadMessages(msgResource); + + if (messages.size() == 0) + messages.put(defaultKey, "Error reading Messages File."); + } + + private static void loadMessages(String msgResource) { + try { + ResourceBundle newMessages = ResourceBundle.getBundle(msgResource); + for (String key : newMessages.keySet()) + messages.setProperty(key, newMessages.getString(key)); + } catch (MissingResourceException ignore) { + } + } + + /** Register a message resource. This resource will be searched for in the CLASSPATH. */ + public static void registerMessageResource(String resourceName) { + if (resourceName != null) + if (messages == null) + msgResources.addElement(resourceName); + else + loadMessages(resourceName); + } + + private static Properties messages = null; + private static String defaultKey = "default"; + private static Vector msgResources = new Vector<>(); + static + { + msgResources.addElement (DEFAULT_MESSAGE_RESOURCE); + } + + // Message-related methods + /////////////// + + public static String capitalize (String lc) { + String first = lc.substring(0, 1); + first = first.toUpperCase(); + return first + lc.substring (1); + } + + /////////////// + // General file methods + + /** Searches the current user directory and a list of directories for + a given short file name and returns its absolute file specification. + @return Absolute file name of a given short filename + @throws FileNotFoundException The file does not exist in the + current user or specified directories. + @see java.io.File#getAbsolutePath */ + public static String getAbsolutePath (String filename, Vector includePaths) throws FileNotFoundException + { + String filepath = null; + File file = new File (filename); + if (file.canRead ()) + filepath = file.getAbsolutePath (); + else + { + String fullname = null; + Enumeration pathList = includePaths.elements (); + while (!file.canRead () && pathList.hasMoreElements ()) + { + fullname = (String)pathList.nextElement () + File.separatorChar + filename; + file = new File (fullname); + } + if (file.canRead ()) + filepath = file.getPath (); + else + throw new FileNotFoundException (filename); + } + return filepath; + } // getAbsolutePath + + // General file methods + /////////////// + + /////////////// + // Numeric computations + + // + /** + * Compute the absolute value of the difference between two floating-point + * numbers having single precision. + * @return the absolute value of the difference between two floats. + **/ + public static float absDelta (float f1, float f2) + { + double delta = f1 - f2; + return (float)((delta < 0) ? delta * -1.0 : delta); + } // absDelta + + // Numeric computations + /////////////// + + static com.sun.tools.corba.ee.idl.RepositoryID emptyID = new com.sun.tools.corba.ee.idl.RepositoryID(); +} // class Util diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueBoxEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueBoxEntry.java new file mode 100644 index 000000000..6e120cfcd --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueBoxEntry.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * This is the symbol table entry for valuesBoxes. + **/ +public class ValueBoxEntry extends ValueEntry +{ + protected ValueBoxEntry () + { + super (); + } // ctor + + protected ValueBoxEntry (ValueBoxEntry that) + { + super (that); + } // ctor + + protected ValueBoxEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, com.sun.tools.corba.ee.idl.IDLID clone) + { + super (that, clone); + } // ctor + + public Object clone () + { + return new ValueBoxEntry (this); + } // clone + + /** Invoke the interface generator. + @param symbolTable the symbol table is a hash table whose key is a fully + qualified type name and whose value is a SymtabEntry or a subclass of + SymtabEntry. + @param stream the stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + valueBoxGen.generate (symbolTable, this, stream); + } // generate + + /** Access the value generator. + @return an object which implements the ValueGen interface. + @see com.sun.tools.corba.ee.idl.ValueGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return valueBoxGen; + } // generator + + static com.sun.tools.corba.ee.idl.ValueBoxGen valueBoxGen; +} // class ValueEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueBoxGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueBoxGen.java new file mode 100644 index 000000000..2bbc0cc60 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueBoxGen.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ValueBoxGen extends com.sun.tools.corba.ee.idl.Generator +{ + void generate (Hashtable symbolTable, com.sun.tools.corba.ee.idl.ValueBoxEntry entry, PrintWriter stream); +} // interface ValueBoxGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueEntry.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueEntry.java new file mode 100644 index 000000000..69128cc28 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueEntry.java @@ -0,0 +1,389 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; +// import com.sun.tools.corba.ee.idl.som.idlemit.TypeCode; + +/** +* This is the symbol table entry for values. +**/ +public class ValueEntry extends com.sun.tools.corba.ee.idl.InterfaceEntry +{ + protected ValueEntry () + { + super (); + } // ctor + + protected ValueEntry (ValueEntry that) + { + super (that); + _supportsNames = (Vector)that._supportsNames.clone (); + _supports = (Vector)that._supports.clone (); + _initializers = (Vector)that._initializers.clone (); + _custom = that._custom; + _isSafe = that._isSafe; + } // ctor + + protected ValueEntry (com.sun.tools.corba.ee.idl.SymtabEntry that, IDLID clone) + { + super (that, clone); + } // ctor + + public Object clone () + { + return new ValueEntry (this); + } // clone + + /** Invoke the interface generator. + @param symbolTable The symbol table is a hash table whose key is + a fully qualified type name and whose value is a SymtabEntry or + a subclass of SymtabEntry. + @param stream The stream to which the generator should sent its output. + @see com.sun.tools.corba.ee.idl.SymtabEntry */ + public void generate (Hashtable symbolTable, PrintWriter stream) + { + valueGen.generate (symbolTable, this, stream); + } // generate + + /** Access the value generator. + @return an object which implements the ValueGen interface. + @see com.sun.tools.corba.ee.idl.ValueGen */ + public com.sun.tools.corba.ee.idl.Generator generator () + { + return valueGen; + } // generator + + /** Add an InterfaceEntry to the list of interfaces which this value + supports. During parsing, the parameter to this method COULD be a + ForwardEntry, but when parsing is complete, calling supports will + return a vector which only contains InterfaceEntry's. */ + public void addSupport (com.sun.tools.corba.ee.idl.SymtabEntry supports) + { + _supports.addElement (supports); + } // addSupport + + /** This method returns a vector of InterfaceEntry's. */ + public Vector supports () + { + return _supports; + } // supports + + /** Add to the list of support names. */ + public void addSupportName (String name) + { + _supportsNames.addElement (name); + } // addSupportName + + /** This method returns a vector of Strings, each of which is a fully + qualified name of an interface. This vector corresponds to the + supports vector. The first element of this vector is the name of + the first element of the supports vector, etc. */ + public Vector supportsNames () + { + return _supportsNames; + } // supportsNames + + /** Add a parent value type to the list of parent types for the value. + This method: +
    +
  • Allows only the first added class to be concrete if the receiver is + concrete. +
  • Does not allow any added classes to be concrete if the receiver is + abstract. +
  • Does not allow duplicate classes to be added. +
*/ + void derivedFromAddElement (com.sun.tools.corba.ee.idl.SymtabEntry e, boolean isSafe, com.sun.tools.corba.ee.idl.Scanner scanner) + { + if (((com.sun.tools.corba.ee.idl.InterfaceType)e).getInterfaceType() != com.sun.tools.corba.ee.idl.InterfaceType.ABSTRACT) { + if (isAbstract ()) + com.sun.tools.corba.ee.idl.ParseException.nonAbstractParent2(scanner, fullName(), e.fullName()); + else if (derivedFrom ().size () > 0) + com.sun.tools.corba.ee.idl.ParseException.nonAbstractParent3(scanner, fullName(), e.fullName()); + } + + if (derivedFrom ().contains (e)) + com.sun.tools.corba.ee.idl.ParseException.alreadyDerived(scanner, e.fullName(), fullName()); + + if (isSafe) + _isSafe = true; + + addDerivedFrom (e); + addDerivedFromName (e.fullName ()); + addParentType (e, scanner); + } // derivedFromAddElement + + void derivedFromAddElement (com.sun.tools.corba.ee.idl.SymtabEntry e, com.sun.tools.corba.ee.idl.Scanner scanner) + { + // This code must check for duplicate interfaces being supported... + addSupport (e); + addSupportName (e.fullName ()); + addParentType (e, scanner); + } // derivedFromAddElement + + public boolean replaceForwardDecl (com.sun.tools.corba.ee.idl.ForwardEntry oldEntry, com.sun.tools.corba.ee.idl.InterfaceEntry newEntry) + { + if (super.replaceForwardDecl (oldEntry, newEntry)) + return true; + int index = _supports.indexOf (oldEntry); + if ( index >= 0) + _supports.setElementAt (newEntry, index); + return (index >= 0); + } + + void initializersAddElement (com.sun.tools.corba.ee.idl.MethodEntry method, com.sun.tools.corba.ee.idl.Scanner scanner) + { + // Check to see if the parameter signature is a duplicate: + Vector params = method.parameters (); + int args = params.size (); + for (Enumeration e = _initializers.elements (); e.hasMoreElements ();) + { + Vector params2 = ( (com.sun.tools.corba.ee.idl.MethodEntry) e.nextElement ()).parameters (); + if (args == params2.size ()) + { + int i = 0; + for (; i < args; i++) + if (!((com.sun.tools.corba.ee.idl.ParameterEntry)params.elementAt (i)).type ().equals ( + ((com.sun.tools.corba.ee.idl.ParameterEntry)params2.elementAt (i)).type ())) + break; + if (i >= args) + com.sun.tools.corba.ee.idl.ParseException.duplicateInit(scanner); + } + } + _initializers.addElement (method); + } // initializersAddElement + + public Vector initializers () + { + return _initializers; + } + + /** Tag all methods introduced by the value type as 'value methods' so + they can be differentiated in the emitters from any interface methods + that the value type supports. */ + public void tagMethods () + { + for (Enumeration e = methods ().elements (); e.hasMoreElements ();) + ((com.sun.tools.corba.ee.idl.MethodEntry)e.nextElement ()).valueMethod (true); + } + + // <46082.03> Revert to "IDL:"-style (i.e., regular) repository ID. + + /** Calculate the 'repository ID' for the value. This method should not be + called before the complete value type has been parsed, since it computes + the repository ID by computing hashcodes using all information contained + in the value type definition, not just the value type's fully qualified + name.*/ + /* + public void calcRepId () + { + ValueRepositoryId repId = new ValueRepositoryId (); + repId.addType (this); + calcRepId (repId); + String scopedName = fullName (); + // KLR - following switched to new format 8/26/98 per Simon's request + repositoryID (new RepositoryID ( "H:" + repId.getHashcode() + ":" + scopedName)); + } // calcRepId + */ + + /* + public void calcRepId (ValueRepositoryId repId) + { + Vector baseClasses = derivedFrom (); + if (baseClasses.size () >= 1) + ((ValueEntry)baseClasses.elementAt (0)).calcRepId (repId); + Vector state = state (); + if (state != null) + for (Enumeration e = state.elements (); e.hasMoreElements ();) + calcTypedefType (((InterfaceState)e.nextElement ()).entry, repId); + } // calcRepId + + private void calcValueType (ValueEntry entry, ValueRepositoryId repId) + { + if (repId.isNewType (entry)) + { + // repId.addValue (TypeCode.tk_value); + repId.addValue (org.omg.CORBA.TCKind._tk_value); + entry.calcRepId (repId); + } + } // calcValueType + + private void calcValueBoxType (ValueBoxEntry entry, ValueRepositoryId repId) + { + if (repId.isNewType (entry)) + { + // repId.addValue (TypeCode.tk_value_box); + repId.addValue (org.omg.CORBA.TCKind._tk_value_box); + entry.calcRepId (repId); + } + } // calcValueBoxType + + private void calcTypedefType (TypedefEntry entry, ValueRepositoryId repId) + { + if (repId.isNewType (entry)) + { + Vector arrayInfo = entry.arrayInfo (); + if (arrayInfo.size () > 0) + { + // repId.addValue (TypeCode.tk_array); + repId.addValue (org.omg.CORBA.TCKind._tk_array); + for (Enumeration e = arrayInfo.elements (); e.hasMoreElements ();) + repId.addValue (((Number)((Expression)e.nextElement ()).value ()).intValue ()); + } + calcType (entry.type (), repId); + } + } // calcTypedefType + + private void calcType (SymtabEntry entry, ValueRepositoryId repId) + { + if (entry instanceof TypedefEntry) + calcTypedefType ((TypedefEntry)entry, repId); + else if (entry instanceof PrimitiveEntry) + calcPrimitiveType (entry, repId); + else if (entry instanceof InterfaceEntry) + // repId.addValue (TypeCode._tk_objref); + repId.addValue (org.omg.CORBA.TCKind._tk_objref); + else if (entry instanceof EnumEntry) + // repId.addValue (TypeCode._tk_enum); + repId.addValue (org.omg.CORBA.TCKind._tk_enum); + else if (entry instanceof StringEntry) + calcStringType ( (StringEntry) entry, repId); + else if (entry instanceof SequenceEntry) + calcSequenceType ( (SequenceEntry) entry, repId); + else if (entry instanceof StructEntry) + calcStructType ( (StructEntry) entry, repId); + else if (entry instanceof UnionEntry) + calcUnionType ( (UnionEntry) entry, repId); + else if (entry instanceof ValueBoxEntry) + calcValueBoxType ( (ValueBoxEntry) entry, repId); + else if (entry instanceof ValueEntry) + calcValueType ( (ValueEntry) entry, repId); + } // calcType + + private static Hashtable primTypes; + + private void calcPrimitiveType (SymtabEntry entry, ValueRepositoryId repId) + { + if (primTypes == null) + { + primTypes = new Hashtable (); + // primTypes.put ("short", new Integer (TypeCode.tk_short )); + primTypes.put ("short", new Integer (org.omg.CORBA.TCKind._tk_short )); + // primTypes.put ("long", new Integer (TypeCode.tk_long )); + primTypes.put ("long", new Integer (org.omg.CORBA.TCKind._tk_long )); + // primTypes.put ("unsigned short", new Integer (TypeCode.tk_ushort )); + primTypes.put ("unsigned short", new Integer (org.omg.CORBA.TCKind._tk_ushort )); + // primTypes.put ("unsigned long", new Integer (TypeCode.tk_ulong )); + primTypes.put ("unsigned long", new Integer (org.omg.CORBA.TCKind._tk_ulong )); + // primTypes.put ("char", new Integer (TypeCode.tk_char )); + primTypes.put ("char", new Integer (org.omg.CORBA.TCKind._tk_char )); + // primTypes.put ("wchar", new Integer (TypeCode.tk_wchar )); + primTypes.put ("wchar", new Integer (org.omg.CORBA.TCKind._tk_wchar )); + // primTypes.put ("float", new Integer (TypeCode.tk_float )); + primTypes.put ("float", new Integer (org.omg.CORBA.TCKind._tk_float )); + // primTypes.put ("double", new Integer (TypeCode.tk_double )); + primTypes.put ("double", new Integer (org.omg.CORBA.TCKind._tk_double )); + // primTypes.put ("boolean", new Integer (TypeCode.tk_boolean)); + primTypes.put ("boolean", new Integer (org.omg.CORBA.TCKind._tk_boolean)); + // primTypes.put ("octet", new Integer (TypeCode.tk_octet )); + primTypes.put ("octet", new Integer (org.omg.CORBA.TCKind._tk_octet )); + // primTypes.put ("any", new Integer (TypeCode.tk_any )); } + primTypes.put ("any", new Integer (org.omg.CORBA.TCKind._tk_any )); + } + repId.addValue (((Integer)primTypes.get (entry.name ())).intValue ()); + } // calcPrimitiveType + + private void calcStringType (StringEntry entry, ValueRepositoryId repId) + { + repId.addValue (entry.name ().equals (Parser.overrideName ("string")) ? + // TypeCode.tk_string: + org.omg.CORBA.TCKind._tk_string : + // TypeCode.tk_wstring); + org.omg.CORBA.TCKind._tk_wstring); + if (entry.maxSize () != null) + try + { + repId.addValue ( ( (Number) (entry.maxSize ()).value ()). intValue ()); + } + catch (Exception exception) + {} + } // calcStringType + + private void calcSequenceType (SequenceEntry entry, ValueRepositoryId repId) + { + // repId.addValue (TypeCode.tk_sequence); + repId.addValue (org.omg.CORBA.TCKind._tk_sequence); + if (entry.maxSize () != null) + try + { + repId.addValue (((Number)(entry.maxSize ()).value ()).intValue ()); + } + catch (Exception exception) + {} + } // calcSequenceType + + private void calcStructType (StructEntry entry, ValueRepositoryId repId) + { + if (repId.isNewType (entry)) + { + // repId.addValue (TypeCode.tk_struct); + repId.addValue (org.omg.CORBA.TCKind._tk_struct); + for (Enumeration e = entry.members ().elements (); e.hasMoreElements ();) + calcTypedefType ( (TypedefEntry) e.nextElement (), repId); + } + } // calcStructType + + private void calcUnionType (UnionEntry entry, ValueRepositoryId repId) + { + if (repId.isNewType (entry)) + { + // repId.addValue (TypeCode.tk_union); + repId.addValue (org.omg.CORBA.TCKind._tk_union); + calcType (entry.type (), repId); + for (Enumeration e = entry.branches ().elements (); e.hasMoreElements ();) + calcTypedefType ( ( (UnionBranch) e.nextElement ()).typedef, repId); + } + } // calcUnionType +*/ + + /** Get the 'custom' marshaling property. */ + public boolean isCustom () + { + return _custom; + } + + /** Set the 'custom' marshaling property. */ + public void setCustom (boolean isCustom) + { + _custom = isCustom; + } + + /** Return whether or not the value type can be "safely" truncated to + its concrete parent type. */ + public boolean isSafe () + { + return _isSafe; + } + + private Vector _supportsNames = new Vector (); + private Vector _supports = new Vector (); + private Vector _initializers = new Vector (); + private boolean _custom = false; + private boolean _isSafe = false; + + static com.sun.tools.corba.ee.idl.ValueGen valueGen; +} // class ValueEntry diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueGen.java new file mode 100644 index 000000000..d2b2d474a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueGen.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +public interface ValueGen extends com.sun.tools.corba.ee.idl.Generator { + void generate ( Hashtable symbolTable, com.sun.tools.corba.ee.idl.ValueEntry entry, PrintWriter stream); +} // interface ValueGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueRepositoryId.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueRepositoryId.java new file mode 100644 index 000000000..d5c0abc71 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ValueRepositoryId.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +// NOTES: + +import java.security.MessageDigest; +import java.util.Hashtable; + +/** + * + **/ +public class ValueRepositoryId +{ + private MessageDigest sha; // Message digest used to compute SHA-1 + private int index; // Current index in the 'logical' sequence + private Hashtable types; // Already processed types + private String hashcode; // The computed hashcode + + public ValueRepositoryId () + { + try + { + sha = MessageDigest.getInstance ("SHA-1"); + } + catch (Exception exception) + {} + index = 0; + types = new Hashtable (); + hashcode = null; + } // ctor + + /**Add a value to the hashcode being computed. + @param value the value to be added to the value RepositoryID. */ + public void addValue (int value) + { + sha.update ((byte)((value >> 24) & 0x0F)); + sha.update ((byte)((value >> 16) & 0x0F)); + sha.update ((byte)((value >> 8) & 0x0F)); + sha.update ((byte)(value & 0x0F)); + index++; + } // addValue + + /** Add a type to the list of types which have already been included. + Note that the type should be added prior to its value. + @param entry the type to be added to the value RepositoryID. */ + public void addType (SymtabEntry entry) + { + types.put (entry, new Integer (index)); + } + + /** Check to see if a specified type has already been processed. If so, + add the appropriate 'previously processed' code (0xFFFFFFFF) and + sequence offset, and return false; otherwise add the symbol table entry + and current offset to the hashtable and return false. + @param entry the type to be checked + @return true if the symbol table entry has not been previously added; + and false otherwise. */ + public boolean isNewType (SymtabEntry entry) + { + Object index = types.get (entry); + if (index == null) + { + addType (entry); + return true; + } + addValue (0xFFFFFFFF); + addValue (((Integer)index).intValue ()); + return false; + } // isNewType + + /** Get the hashcode computed for the value type. This method MUST not be + called until all fields have been added, since it computes the hash + code from the values entered for each field. + @return the 64 bit hashcode for the value type represented as a + 16 character hexadecimal string. */ + public String getHashcode () + { + if (hashcode == null) + { + byte [] digest = sha.digest (); + hashcode = hexOf (digest[0]) + hexOf (digest[1]) + + hexOf (digest[2]) + hexOf (digest[3]) + + hexOf (digest[4]) + hexOf (digest[5]) + + hexOf (digest[6]) + hexOf (digest[7]); + } + return hashcode; + } // getHashCode + + // Convert a byte to a two character hex string: + private static String hexOf (byte value) + { + int d1 = (value >> 4) & 0x0F; + int d2 = value & 0x0F; + return "0123456789ABCDEF".substring (d1, d1 + 1) + + "0123456789ABCDEF".substring (d2, d2 + 1); + } // hexOf +} // class ValueRepositoryId diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/And.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/And.java new file mode 100644 index 000000000..5ac9d806a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/And.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class And extends BinaryExpr +{ + protected And (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("&", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.and"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Arithmetic and (&) + //daz value (new Long (l.longValue () & r.longValue ())); + BigInteger uL = (BigInteger)coerceToTarget ((BigInteger)l); + BigInteger uR = (BigInteger)coerceToTarget ((BigInteger)r); + value (uL.and (uR)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.and"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class And diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BinaryExpr.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BinaryExpr.java new file mode 100644 index 000000000..777f3aef7 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BinaryExpr.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +public abstract class BinaryExpr extends Expression +{ + public BinaryExpr (String operation, Expression leftOperand, Expression rightOperand) + { + _op = operation; + _left = leftOperand; + _right = rightOperand; + } // ctor + + public void op (String op) {_op = (op == null)? "": op;} + public String op () {return _op;} + + public void left (Expression left) {_left = left;} + public Expression left () {return _left;} + + public void right (Expression right) {_right = right;} + public Expression right () {return _right;} + + private String _op = ""; + private Expression _left = null; + private Expression _right = null; +} // class BinaryExpr diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanAnd.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanAnd.java new file mode 100644 index 000000000..8bd93da39 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanAnd.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class BooleanAnd extends BinaryExpr +{ + protected BooleanAnd (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("&&", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object tmpL = left ().evaluate (); + Object tmpR = right ().evaluate (); + Boolean l; + Boolean r; + + //daz if (tmpL instanceof Number) + // l = new Boolean (((Number)tmpL).longValue () != 0); + // else + // l = (Boolean)tmpL; + if (tmpL instanceof Number) + { + if (tmpL instanceof BigInteger) + l = Boolean.valueOf (((BigInteger)tmpL).compareTo (BigInteger.valueOf (0)) != 0); + else + l = Boolean.valueOf (((Number)tmpL).longValue () != 0); + } + else + l = (Boolean)tmpL; + //daz if (tmpR instanceof Number) + // r = new Boolean (((Number)tmpR).longValue () != 0); + // else + // r = (Boolean)tmpR; + if (tmpR instanceof Number) + { + if (tmpR instanceof BigInteger) + r = Boolean.valueOf (((BigInteger)tmpR).compareTo (zero) != 0); + else + r = Boolean.valueOf (((Number)tmpR).longValue () != 0); + } + else + r = (Boolean)tmpR; + + value (new Boolean (l.booleanValue () && r.booleanValue ())); + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.booleanAnd"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class BooleanAnd diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanNot.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanNot.java new file mode 100644 index 000000000..3b31d6deb --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanNot.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class BooleanNot extends UnaryExpr +{ + protected BooleanNot (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + super ("!", operand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object tmp = operand ().evaluate (); + Boolean op; + //daz if (tmp instanceof Number) + // op = new Boolean (((Number)tmp).longValue () != 0); + // else + // op = (Boolean)tmp; + if (tmp instanceof Number) + { + if (tmp instanceof BigInteger) + op = Boolean.valueOf (((BigInteger)tmp).compareTo (zero) != 0); + else + op = Boolean.valueOf (((Number)tmp).longValue () != 0); + } + else + op = (Boolean)tmp; + + value (Boolean.valueOf (!op.booleanValue ())); + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.booleanNot"), operand ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.2", parameters)); + } + return value (); + } // evaluate +} // class BooleanNot diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanOr.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanOr.java new file mode 100644 index 000000000..8b06e9cdc --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/BooleanOr.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class BooleanOr extends BinaryExpr +{ + protected BooleanOr (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("||", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object tmpL = left ().evaluate (); + Object tmpR = right ().evaluate (); + Boolean l; + Boolean r; + + //daz if (tmpL instanceof Number) + // l = new Boolean (((Number)tmpL).longValue () != 0); + // else + // l = (Boolean)tmpL; + if (tmpL instanceof Number) + { + if (tmpL instanceof BigInteger) + l = Boolean.valueOf (((BigInteger)tmpL).compareTo (zero) != 0); + else + l = Boolean.valueOf (((Number)tmpL).longValue () != 0); + } + else + l = (Boolean)tmpL; + //daz if (tmpR instanceof Number) + // r = new Boolean (((Number)tmpR).longValue () != 0); + // else + // r = (Boolean)tmpR; + if (tmpR instanceof Number) + { + if (tmpR instanceof BigInteger) + r = Boolean.valueOf (((BigInteger)tmpR).compareTo (BigInteger.valueOf (0)) != 0); + else + r = Boolean.valueOf (((Number)tmpR).longValue () != 0); + } + else + r = (Boolean)tmpR; + value (Boolean.valueOf (l.booleanValue () || r.booleanValue ())); + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.booleanOr"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class BooleanOr diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/DefaultExprFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/DefaultExprFactory.java new file mode 100644 index 000000000..f0048ddc6 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/DefaultExprFactory.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.ConstEntry; + +import java.math.BigInteger; + +public class DefaultExprFactory implements ExprFactory +{ + public com.sun.tools.corba.ee.idl.constExpr.And and (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.And(left, right); + } // and + + public com.sun.tools.corba.ee.idl.constExpr.BooleanAnd booleanAnd (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.BooleanAnd(left, right); + } // booleanAnd + + public com.sun.tools.corba.ee.idl.constExpr.BooleanNot booleanNot (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + return new com.sun.tools.corba.ee.idl.constExpr.BooleanNot(operand); + } // booleanNot + + public com.sun.tools.corba.ee.idl.constExpr.BooleanOr booleanOr (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.BooleanOr(left, right); + } // booleanOr + + public com.sun.tools.corba.ee.idl.constExpr.Divide divide (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Divide(left, right); + } // divide + + public com.sun.tools.corba.ee.idl.constExpr.Equal equal (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Equal(left, right); + } // equal + + public com.sun.tools.corba.ee.idl.constExpr.GreaterEqual greaterEqual (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.GreaterEqual(left, right); + } // greaterEqual + + public com.sun.tools.corba.ee.idl.constExpr.GreaterThan greaterThan (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.GreaterThan(left, right); + } // greaterThan + + public com.sun.tools.corba.ee.idl.constExpr.LessEqual lessEqual (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.LessEqual(left, right); + } // lessEqual + + public com.sun.tools.corba.ee.idl.constExpr.LessThan lessThan (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.LessThan(left, right); + } // lessThan + + public com.sun.tools.corba.ee.idl.constExpr.Minus minus (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Minus(left, right); + } // minus + + public com.sun.tools.corba.ee.idl.constExpr.Modulo modulo (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Modulo(left, right); + } // modulo + + public com.sun.tools.corba.ee.idl.constExpr.Negative negative (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + return new com.sun.tools.corba.ee.idl.constExpr.Negative(operand); + } // negative + + public com.sun.tools.corba.ee.idl.constExpr.Not not (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + return new com.sun.tools.corba.ee.idl.constExpr.Not(operand); + } // not + + public com.sun.tools.corba.ee.idl.constExpr.NotEqual notEqual (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.NotEqual(left, right); + } // notEqual + + public com.sun.tools.corba.ee.idl.constExpr.Or or (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Or(left, right); + } // or + + public com.sun.tools.corba.ee.idl.constExpr.Plus plus (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Plus(left, right); + } // plus + + public com.sun.tools.corba.ee.idl.constExpr.Positive positive (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + return new com.sun.tools.corba.ee.idl.constExpr.Positive(operand); + } // positive + + public com.sun.tools.corba.ee.idl.constExpr.ShiftLeft shiftLeft (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.ShiftLeft(left, right); + } // shiftLeft + + public com.sun.tools.corba.ee.idl.constExpr.ShiftRight shiftRight (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.ShiftRight(left, right); + } // shiftRight + + public com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, Character charValue, + boolean isWide ) + { + return new com.sun.tools.corba.ee.idl.constExpr.Terminal(representation, charValue, isWide ); + } // ctor + + public com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, Boolean booleanValue) + { + return new com.sun.tools.corba.ee.idl.constExpr.Terminal(representation, booleanValue); + } // ctor + + // Support long long + public com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, BigInteger bigIntegerValue) + { + return new com.sun.tools.corba.ee.idl.constExpr.Terminal(representation, bigIntegerValue); + } // ctor + + //daz public Terminal terminal (String representation, Long longValue) + // { + // return new Terminal (representation, longValue); + // } // ctor + + public com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, Double doubleValue) + { + return new com.sun.tools.corba.ee.idl.constExpr.Terminal(representation, doubleValue); + } // ctor + + public com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String stringValue, boolean isWide ) + { + return new com.sun.tools.corba.ee.idl.constExpr.Terminal(stringValue, isWide); + } // ctor + + public com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (ConstEntry constReference) + { + return new com.sun.tools.corba.ee.idl.constExpr.Terminal(constReference); + } // ctor + + public com.sun.tools.corba.ee.idl.constExpr.Times times (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Times(left, right); + } // times + + public com.sun.tools.corba.ee.idl.constExpr.Xor xor (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right) + { + return new com.sun.tools.corba.ee.idl.constExpr.Xor(left, right); + } // xor +} // class DefaultExprFactory diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Divide.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Divide.java new file mode 100644 index 000000000..8713aa1b1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Divide.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: +// -D52042 Added protypical code for computing mixed-operand binary +// expressions, which promotes result to Double only when the target type +// is floating-point. Code violates spec, but may be usable at some future +// time. + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +/** + * + **/ +public class Divide extends BinaryExpr +{ + /** + * Constructor: set operation and operands. + **/ + protected Divide (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("/", leftOperand, rightOperand); + } // ctor + + /** + * + **/ + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + boolean lIsNonInteger = l instanceof Float || l instanceof Double; + boolean rIsNonInteger = r instanceof Float || r instanceof Double; + + if (lIsNonInteger && rIsNonInteger) + value (new Double (l.doubleValue () / r.doubleValue ())); + else if (lIsNonInteger || rIsNonInteger) + { + String[] parameters = {Util.getMessage ("EvaluationException.divide"), + left ().value ().getClass ().getName (), + right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + BigInteger tmpL = (BigInteger)l, tmpR = (BigInteger)r; + value (tmpL.divide (tmpR)); + } + // Allow evaluation over mixed operands. Supplant code above. + /* + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + boolean lIsNonInteger = l instanceof Float || l instanceof Double; + boolean rIsNonInteger = r instanceof Float || r instanceof Double; + + // Floating-point operands. + if (lIsNonInteger && rIsNonInteger) + { + value (new Double (l.doubleValue () / r.doubleValue ())); + } + // Integral operands. + else if (!(lIsNonInteger || rIsNonInteger)) + { + BigInteger tmpL = (BigInteger)l, tmpR = (BigInteger)r; + value (tmpL.divide (tmpR)); + } + // Mixed operands: one operand is floating-point, the other is integral. + else + { + // Legal over floating-point types only. + if (type ().equals ("float") || + type ().equals ("double")) + { + value (new Double (l.doubleValue () / r.doubleValue ())); + } + else + { + String[] parameters = {Util.getMessage ("EvaluationException.divide"), + left ().value ().getClass ().getName (), + right ().value ().getClass ().getName ()}; + throw new EvaluationException (Util.getMessage ("EvaluationException.1", parameters)); + } + } + */ + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.divide"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Divide diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Equal.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Equal.java new file mode 100644 index 000000000..e83c4525b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Equal.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Equal extends BinaryExpr +{ + protected Equal (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("==", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object left = left ().evaluate (); + if (left instanceof Boolean) + { + Boolean l = (Boolean)left; + Boolean r = (Boolean)right ().evaluate (); + value (Boolean.valueOf (l.booleanValue () == r.booleanValue())); + } + else + { + Number l = (Number)left; + Number r = (Number)right ().evaluate (); + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + value (new Boolean (l.doubleValue () == r.doubleValue ())); + else + //daz value (Boolean.valueOf (l.longValue () == r.longValue ())); + value (Boolean.valueOf (((BigInteger)l).equals ((BigInteger)r))); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.equal"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Equal diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/EvaluationException.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/EvaluationException.java new file mode 100644 index 000000000..12451ffeb --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/EvaluationException.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +public class EvaluationException extends Exception +{ + public EvaluationException (String message) + { + super (message); + } // ctor +} // class EvaluationException diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ExprFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ExprFactory.java new file mode 100644 index 000000000..e3a3adabe --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ExprFactory.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.ConstEntry; + +import java.math.BigInteger; + +public interface ExprFactory +{ + And and (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.BooleanAnd booleanAnd (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.BooleanNot booleanNot (com.sun.tools.corba.ee.idl.constExpr.Expression operand); + com.sun.tools.corba.ee.idl.constExpr.BooleanOr booleanOr (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Divide divide (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Equal equal (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.GreaterEqual greaterEqual (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.GreaterThan greaterThan (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.LessEqual lessEqual (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.LessThan lessThan (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Minus minus (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Modulo modulo (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Negative negative (com.sun.tools.corba.ee.idl.constExpr.Expression operand); + com.sun.tools.corba.ee.idl.constExpr.Not not (com.sun.tools.corba.ee.idl.constExpr.Expression operand); + com.sun.tools.corba.ee.idl.constExpr.NotEqual notEqual (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Or or (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Plus plus (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Positive positive (com.sun.tools.corba.ee.idl.constExpr.Expression operand); + com.sun.tools.corba.ee.idl.constExpr.ShiftLeft shiftLeft (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.ShiftRight shiftRight (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, Character charValue, + boolean isWide ); + com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, Boolean booleanValue); + //daz Terminal terminal (String representation, Long longValue); + com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, Double doubleValue); + com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String representation, BigInteger bigIntegerValue); + com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (String stringValue, boolean isWide ); + com.sun.tools.corba.ee.idl.constExpr.Terminal terminal (ConstEntry constReference); + com.sun.tools.corba.ee.idl.constExpr.Times times (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); + com.sun.tools.corba.ee.idl.constExpr.Xor xor (com.sun.tools.corba.ee.idl.constExpr.Expression left, com.sun.tools.corba.ee.idl.constExpr.Expression right); +} // interface ExprFactory diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Expression.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Expression.java new file mode 100644 index 000000000..ac3c2b783 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Expression.java @@ -0,0 +1,234 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import java.math.BigInteger; + +public abstract class Expression +{ + /** + * Compute the value of this expression. + **/ + public abstract Object evaluate () throws EvaluationException; + + /** + * Set the value of this expression. + **/ + public void value (Object value) + { + _value = value; + } + /** + * Get the value of this expression. + **/ + public Object value () + { + return _value; + } + + /** + * Set the representation of this expression. + **/ + public void rep (String rep) + { + _rep = rep; + } + /** + * Get the representation of this expression. + **/ + public String rep () + { + return _rep; + } + + /** + * Set the target type of this expression. + **/ + public void type (String type) + { + _type = type; + } + /** + * Get the target type of this expression. + **/ + public String type () + { + return _type; + } + + /** + * Return the default computation type for the given target type. + **/ + protected static String defaultType (String targetType) + { + return (targetType == null) ? new String ("") : targetType; + } // defaultType + + // BigInteger is a multi-precision number whose representation contains + // a signum (sign-number = 1, -1) and a magnitude. To support "long long", + // all integer expressions are now performed over BigInteger and stored as + // such. During the evaluation of an integer expression, the signum of its + // value may toggle, which may cause the value of an expression to conflict + // with its target type: [Case 1] If the resulting value is negative + // (signum=-1) and the target type is unsigned; or [Case 2] if the resulting + // value is positive (signum=1) and greater than 2**(target-type-length - 1), + // and the target type is signed, then the resulting value will be out of + // range. However, this value is correct and must be coerced to the target + // type. E.G., After appying "not" to a BigInteger, the result is + // a BigInteger that represents its 2's-complement (~5 => -6 in a byte-space). + // In this example, the signum toggles and the magnatude is 6. If the target + // type of this value were unsigned short, it must be coerced to a positive + // number whose bits truly represent -6 in 2's-complement (250 in a byte-space). + // + // Also, floating types may now be intialized with any integer expression. + // The result must be coerced to Double. + // + // Use the following routines to coerce this expression's value to its + // "target" type. + + /** + * Coerces a number to the target type of this expression. + * @param obj The number to coerce. + * @return the value of number coerced to the (target) type of + * this expression. + **/ + public Object coerceToTarget (Object obj) + { + if (obj instanceof BigInteger) + { + if (type().contains("unsigned")) + return toUnsignedTarget ((BigInteger)obj); + else + return toSignedTarget ((BigInteger)obj); + } + return obj; + } // coerceToTarget + + /** + * Coerces an integral value (BigInteger) to its corresponding unsigned + * representation, if the target type of this expression is unsigned. + * @param b The BigInteger to be coerced. + * @return the value of an integral type coerced to its corresponding + * unsigned integral type, if the target type of this expression is + * unsigned. + **/ + protected BigInteger toUnsignedTarget (BigInteger b) + { + if (type ().equals ("unsigned short")) // target type of this expression + { + if (b != null && b.compareTo (zero) < 0) // error if value < min = -(2**(l-1)). + return b.add (twoPow16); + } + else if (type ().equals ("unsigned long")) + { + if (b != null && b.compareTo (zero) < 0) + return b.add (twoPow32); + } + else if (type ().equals ("unsigned long long")) + { + if (b != null && b.compareTo (zero) < 0) + return b.add (twoPow64); + } + return b; + } // toUnsignedTarget + + /** + * Coerces an integral value (BigInteger) to its corresponding signed + * representation, if the target type of this expression is signed. + * @param b The BigInteger to be coerced. + * @return the value of an integral type coerced to its corresponding + * signed integral type, if the target type of this expression is + * signed. + **/ + protected BigInteger toSignedTarget (BigInteger b) + { + if (type ().equals ("short")) + { + if (b != null && b.compareTo (sMax) > 0) + return b.subtract (twoPow16); + } + else if (type ().equals ("long")) + { + if (b != null && b.compareTo (lMax) > 0) + return b.subtract (twoPow32); + } + else if (type ().equals ("long long")) + { + if (b != null && b.compareTo (llMax) > 0) + return b.subtract (twoPow64); + } + return b; + } // toSignedTarget + + /** + * Return the unsigned value of a BigInteger. + **/ + protected BigInteger toUnsigned (BigInteger b) + { + if (b != null && b.signum () == -1) + if (type ().equals ("short")) + return b.add (twoPow16); + else if (type ().equals ("long")) + return b.add (twoPow32); + else if (type ().equals ("long long")) + return b.add (twoPow64); + return b; + } + + // Integral-type boundaries. + + public static final BigInteger negOne = BigInteger.valueOf (-1); + public static final BigInteger zero = BigInteger.valueOf (0); + public static final BigInteger one = BigInteger.valueOf (1); + public static final BigInteger two = BigInteger.valueOf (2); + + public static final BigInteger twoPow15 = two.pow (15); + public static final BigInteger twoPow16 = two.pow (16); + public static final BigInteger twoPow31 = two.pow (31); + public static final BigInteger twoPow32 = two.pow (32); + public static final BigInteger twoPow63 = two.pow (63); + public static final BigInteger twoPow64 = two.pow (64); + + public static final BigInteger sMax = BigInteger.valueOf (Short.MAX_VALUE); + public static final BigInteger sMin = BigInteger.valueOf (Short.MAX_VALUE); + + public static final BigInteger usMax = sMax.multiply (two).add (one); + public static final BigInteger usMin = zero; + + public static final BigInteger lMax = BigInteger.valueOf (Integer.MAX_VALUE); + public static final BigInteger lMin = BigInteger.valueOf (Integer.MAX_VALUE); + + public static final BigInteger ulMax = lMax.multiply (two).add (one); + public static final BigInteger ulMin = zero; + + public static final BigInteger llMax = BigInteger.valueOf (Long.MAX_VALUE); + public static final BigInteger llMin = BigInteger.valueOf (Long.MIN_VALUE); + + public static final BigInteger ullMax = llMax.multiply (two).add (one); + public static final BigInteger ullMin = zero; + + /** + * Value of this expression: Boolean, Char, Byte, BigInteger, Double, + * String, Expression, ConstEntry. + **/ + private Object _value = null; + /** + * String representation of this expression. + **/ + private String _rep = null; + /** + * Computation type of this (sub)expression = Target type for now. + **/ + private String _type = null; +} // abstract class Expression diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/GreaterEqual.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/GreaterEqual.java new file mode 100644 index 000000000..72265fef8 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/GreaterEqual.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class GreaterEqual extends BinaryExpr +{ + protected GreaterEqual (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super (">=", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object left = left ().evaluate (); + if (left instanceof Boolean) + { + String[] parameters = {Util.getMessage ("EvaluationException.greaterEqual"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + Number l = (Number)left; + Number r = (Number)right ().evaluate (); + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + value (Boolean.valueOf (l.doubleValue () >= r.doubleValue ())); + else + //daz value (Boolean.valueOf (l.longValue () >= r.longValue ())); + value (Boolean.valueOf ( ((BigInteger)l).compareTo ((BigInteger)r) >= 0)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.greaterEqual"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class GreaterEqual diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/GreaterThan.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/GreaterThan.java new file mode 100644 index 000000000..53c409ffa --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/GreaterThan.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class GreaterThan extends BinaryExpr +{ + protected GreaterThan (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super (">", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object left = left ().evaluate (); + if (left instanceof Boolean) + { + String[] parameters = {Util.getMessage ("EvaluationException.greaterThan"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + Number l = (Number)left; + Number r = (Number)right ().evaluate (); + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + value (Boolean.valueOf (l.doubleValue () > r.doubleValue ())); + else + //daz value (Boolean.valueOf (l.longValue () > r.longValue ())); + value (Boolean.valueOf ( ((BigInteger)l).compareTo ((BigInteger)r) > 0)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.greaterThan"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class GreaterThan diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/LessEqual.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/LessEqual.java new file mode 100644 index 000000000..e6cce56f7 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/LessEqual.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class LessEqual extends BinaryExpr +{ + protected LessEqual (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("<=", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object left = left ().evaluate (); + if (left instanceof Boolean) + { + String[] parameters = {Util.getMessage ("EvaluationException.lessEqual"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + Number l = (Number)left; + Number r = (Number)right ().evaluate (); + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + value (Boolean.valueOf (l.doubleValue () <= r.doubleValue ())); + else + //daz value (Boolean.valueOf (l.longValue () <= r.longValue ())); + value (Boolean.valueOf ( ((BigInteger)l).compareTo ((BigInteger)r) <= 0)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.lessEqual"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class LessEqual diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/LessThan.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/LessThan.java new file mode 100644 index 000000000..d1cef5b8b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/LessThan.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class LessThan extends BinaryExpr +{ + protected LessThan (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("<", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object left = left ().evaluate (); + if (left instanceof Boolean) + { + String[] parameters = {Util.getMessage ("EvaluationException.lessThan"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + Number l = (Number)left; + Number r = (Number)right ().evaluate (); + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + value (Boolean.valueOf (l.doubleValue () < r.doubleValue ())); + else + //daz value (Boolean.valueOf (l.longValue () < r.longValue ())); + value (Boolean.valueOf (((BigInteger)l).compareTo ((BigInteger)r) < 0)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.lessThan"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class LessThan diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Minus.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Minus.java new file mode 100644 index 000000000..273f83286 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Minus.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Minus extends BinaryExpr +{ + protected Minus (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("-", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + boolean lIsNonInteger = l instanceof Float || l instanceof Double; + boolean rIsNonInteger = r instanceof Float || r instanceof Double; + + if (lIsNonInteger && rIsNonInteger) + value (new Double (l.doubleValue () - r.doubleValue ())); + else if (lIsNonInteger || rIsNonInteger) + { + String[] parameters = {Util.getMessage ("EvaluationException.minus"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Subtraction (-) + BigInteger tmpL = (BigInteger)l, tmpR = (BigInteger)r; + value (tmpL.subtract (tmpR)); + //daz value (new Long (l.longValue () - r.longValue ())); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.minus"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Minus diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Modulo.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Modulo.java new file mode 100644 index 000000000..eca91e5ba --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Modulo.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Modulo extends BinaryExpr +{ + protected Modulo (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("%", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.mod"), left().value ().getClass ().getName (), right().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Modulo (%) + BigInteger tmpL = (BigInteger)l, tmpR = (BigInteger)r; + value (tmpL.remainder (tmpR)); + //daz value (tmpL.mod (tmpR)); Requires positive modulus; not required by IDL. + //daz value (new Long (l.longValue () % r.longValue ())); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.mod"), left().value ().getClass ().getName (), right().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Modulo diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Negative.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Negative.java new file mode 100644 index 000000000..174bbd294 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Negative.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Negative extends UnaryExpr +{ + protected Negative (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + super ("-", operand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number op = (Number)operand ().evaluate (); + + if (op instanceof Float || op instanceof Double) + value (new Double (-op.doubleValue ())); + else + { + // Multiply by -1 + //daz value (new Long (-op.longValue ())); + BigInteger tmpOp = (BigInteger)op; + value (tmpOp.multiply (BigInteger.valueOf (-1))); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.neg"), operand ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.2", parameters)); + } + return value (); + } // evaluate +} // class Negative diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Not.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Not.java new file mode 100644 index 000000000..d3a3dc0ed --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Not.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Not extends UnaryExpr +{ + protected Not (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + super ("~", operand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number op = (Number)operand ().evaluate (); + + if (op instanceof Float || op instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.not"), operand ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.2", parameters)); + } + else + { + // Complement (~) + //daz value (new Long (~op.longValue ())); + BigInteger b = (BigInteger)coerceToTarget((BigInteger)op); + + // Compute according to CORBA 2.1 specifications for specified type. + if (type ().equals ("short") || type ().equals ("long") || type ().equals ("long long")) + value (b.add (one).multiply (negOne)); + else if (type ().equals("unsigned short")) + // "short" not CORBA compliant, but necessary for logical operations--size matters! + value (twoPow16.subtract (one).subtract (b)); + else if (type ().equals ("unsigned long")) + value (twoPow32.subtract (one).subtract (b)); + else if (type ().equals ("unsigned long long")) + value (twoPow64.subtract (one).subtract (b)); + else + value (b.not ()); // Should never execute... + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.not"), operand ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.2", parameters)); + } + return value (); + } // evaluate +} // class Not diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/NotEqual.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/NotEqual.java new file mode 100644 index 000000000..4c0bbb15a --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/NotEqual.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class NotEqual extends BinaryExpr +{ + protected NotEqual (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("!=", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Object left = left ().evaluate (); + if (left instanceof Boolean) + { + Boolean l = (Boolean)left; + Boolean r = (Boolean)right ().evaluate (); + value (Boolean.valueOf (l.booleanValue () != r.booleanValue())); + } + else + { + Number l = (Number)left; + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + value (Boolean.valueOf (l.doubleValue () != r.doubleValue ())); + else + //daz value (Boolean.valueOf (l.longValue () != r.longValue ())); + value (Boolean.valueOf (!((BigInteger)l).equals ((BigInteger)r))); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.notEqual"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class NotEqual diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Or.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Or.java new file mode 100644 index 000000000..56f2f3bcd --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Or.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Or extends BinaryExpr +{ + protected Or (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("|", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.or"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // or + //daz value (new Long (l.longValue () | r.longValue ())); + BigInteger uL = (BigInteger)toUnsigned((BigInteger)l); + BigInteger uR = (BigInteger)toUnsigned((BigInteger)r); + value((BigInteger)coerceToTarget(uL.or (uR))); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.or"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Or diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Plus.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Plus.java new file mode 100644 index 000000000..c6ebad289 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Plus.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Plus extends BinaryExpr +{ + protected Plus (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("+", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + boolean lIsNonInteger = l instanceof Float || l instanceof Double; + boolean rIsNonInteger = r instanceof Float || r instanceof Double; + + if (lIsNonInteger && rIsNonInteger) + value (new Double (l.doubleValue () + r.doubleValue ())); + else if (lIsNonInteger || rIsNonInteger) + { + String[] parameters = {Util.getMessage ("EvaluationException.plus"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Addition (+) + BigInteger tmpL = (BigInteger)l, tmpR = (BigInteger)r; + value (tmpL.add (tmpR)); + //daz value (new Long (l.longValue () + r.longValue ())); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.plus"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Plus diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Positive.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Positive.java new file mode 100644 index 000000000..dc854748d --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Positive.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Positive extends UnaryExpr +{ + protected Positive (com.sun.tools.corba.ee.idl.constExpr.Expression operand) + { + super ("+", operand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number op = (Number)operand ().evaluate (); + + if (op instanceof Float || op instanceof Double) + value (new Double (+op.doubleValue ())); + else + { + // Multiply by sign + //daz value (new Long (+op.longValue ())); + value (((BigInteger)op).multiply (BigInteger.valueOf (((BigInteger)op).signum ()))); + //promote (); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.pos"), operand ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.2", parameters)); + } + return value (); + } // evaluate +} // class Positive diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ShiftLeft.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ShiftLeft.java new file mode 100644 index 000000000..cc1748655 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ShiftLeft.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class ShiftLeft extends BinaryExpr +{ + protected ShiftLeft (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("<<", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.left"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Shift left (<<) + //daz value (new Long (l.longValue () << r.longValue ())); + BigInteger bL = (BigInteger)coerceToTarget (l); + BigInteger bR = (BigInteger)r; + + BigInteger ls = bL.shiftLeft (bR.intValue ()); + + if (type ().indexOf ("short") >= 0) + ls = ls.mod (twoPow16); + else if (type ().indexOf ("long") >= 0) + ls = ls.mod (twoPow32); + else if (type ().indexOf ("long long") >= 0) + ls = ls.mod (twoPow64); + + value (coerceToTarget (ls)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.left"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class ShiftLeft diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ShiftRight.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ShiftRight.java new file mode 100644 index 000000000..3a43002e9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/ShiftRight.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class ShiftRight extends BinaryExpr +{ + protected ShiftRight (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super (">>", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.right"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Shift right (>>) + //daz value (new Long (l.longValue () >> r.longValue ())); + BigInteger bL = (BigInteger)coerceToTarget ((BigInteger)l); + BigInteger bR = (BigInteger)r; + + // Change signed to unsigned (Clear sign bit--can be done when setting bL!) + if (bL.signum () == -1) + if (type ().equals ("short")) + bL = bL.add (twoPow16); + else if (type ().equals ("long")) + bL = bL.add (twoPow32); + else if (type ().equals ("long long")) + bL = bL.add (twoPow64); + + value (bL.shiftRight (bR.intValue ())); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.right"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class ShiftRight diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Terminal.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Terminal.java new file mode 100644 index 000000000..ad700fc30 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Terminal.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.ConstEntry; + +import java.math.BigInteger; + +/** + * This class contains values. Objects of this class are the terminal + * nodes of an expression tree. + * + * Note that there is a constructor for Double values, but not Float. + * CORBA defines that all floating point expressions are evaluated as + * double, and that the result is coerced back to float if necessary. + * + * Note also that there is a constructor for long values, but not for + * int or short. CORBA defines that all integral expressions are evaluated + * as unsigned long. A CORBA long is a Java int. There is no unsigned int + * in Java, so the next larger type, long, is used. + **/ +public class Terminal extends Expression +{ + protected Terminal (String representation, Character charValue, + boolean isWide) + { + rep (representation); + value (charValue); + if (isWide) + type( "wchar" ) ; + else + type( "char" ) ; + } // ctor + + protected Terminal (String representation, Boolean booleanValue) + { + rep (representation); + value (booleanValue); + } // ctor + + // Support long long + protected Terminal (String representation, BigInteger bigIntegerValue) + { + rep (representation); + value (bigIntegerValue); + } // ctor + + protected Terminal (String representation, Long longValue) + { + long lv = longValue.longValue (); + rep (representation); + if (lv > Integer.MAX_VALUE || lv < Integer.MIN_VALUE) + value (longValue); + else + value (Integer.valueOf (longValue.intValue ())); + } // ctor + + protected Terminal (String representation, Double doubleValue) + { + rep (representation); + value (doubleValue); + } // ctor + + protected Terminal (String stringValue, boolean isWide ) + { + rep (stringValue); + value (stringValue); + if (isWide) + type( "wstring" ) ; + else + type( "string" ) ; + } // ctor + + protected Terminal (ConstEntry constReference) + { + rep (constReference.fullName ()); + value (constReference); + } // ctor + + ///// INSTANCE METHODS + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + if (value () instanceof ConstEntry) + return ((ConstEntry)value ()).value ().evaluate (); + else + return value (); + } // evaluate +} // class Terminal diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Times.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Times.java new file mode 100644 index 000000000..88e84027b --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Times.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Times extends BinaryExpr +{ + protected Times (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("*", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + boolean lIsNonInteger = l instanceof Float || l instanceof Double; + boolean rIsNonInteger = r instanceof Float || r instanceof Double; + + if (lIsNonInteger && rIsNonInteger) + value (new Double (l.doubleValue () * r.doubleValue ())); + else if (lIsNonInteger || rIsNonInteger) + { + String[] parameters = {Util.getMessage ("EvaluationException.times"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Multiplication (*) + BigInteger tmpL = (BigInteger)l, tmpR = (BigInteger)r; + value (tmpL.multiply (tmpR)); + //daz value (new Long (l.longValue () * r.longValue ())); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.times"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Times diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/UnaryExpr.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/UnaryExpr.java new file mode 100644 index 000000000..90be98286 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/UnaryExpr.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +public abstract class UnaryExpr extends Expression +{ + public UnaryExpr (String operation, Expression unaryOperand) + { + _op = operation; + _operand = unaryOperand; + } // ctor + + public void op (String op) {_op = (op == null)? "": op;} + public String op () {return _op;} + + public void operand (Expression operand) {_operand = operand;} + public Expression operand () {return _operand;} + + private String _op = ""; + private Expression _operand = null; +} // class UnaryExpr diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Xor.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Xor.java new file mode 100644 index 000000000..4e431d906 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/constExpr/Xor.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.constExpr; + +// NOTES: + +import com.sun.tools.corba.ee.idl.Util; + +import java.math.BigInteger; + +public class Xor extends BinaryExpr +{ + protected Xor (com.sun.tools.corba.ee.idl.constExpr.Expression leftOperand, com.sun.tools.corba.ee.idl.constExpr.Expression rightOperand) + { + super ("^", leftOperand, rightOperand); + } // ctor + + public Object evaluate () throws com.sun.tools.corba.ee.idl.constExpr.EvaluationException + { + try + { + Number l = (Number)left ().evaluate (); + Number r = (Number)right ().evaluate (); + + if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) + { + String[] parameters = {Util.getMessage ("EvaluationException.xor"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + else + { + // Xor (^) + //daz value (new Long (l.longValue () ^ r.longValue ())); + //BigInteger uL = (BigInteger)toUnsigned((BigInteger)l); + //BigInteger uR = (BigInteger)toUnsigned((BigInteger)r); + //value (coerceToTarget(uL.xor (uR))); + BigInteger uL = (BigInteger)coerceToTarget((BigInteger)l); + BigInteger uR = (BigInteger)coerceToTarget((BigInteger)r); + value (uL.xor (uR)); + } + } + catch (ClassCastException e) + { + String[] parameters = {Util.getMessage ("EvaluationException.xor"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()}; + throw new com.sun.tools.corba.ee.idl.constExpr.EvaluationException(Util.getMessage ("EvaluationException.1", parameters)); + } + return value (); + } // evaluate +} // class Xor diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/first.set b/idlj/src/main/java/com/sun/tools/corba/ee/idl/first.set new file mode 100644 index 000000000..ea7c45394 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/first.set @@ -0,0 +1,210 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +CORBA IDL +--------------- + + typedef, struct, union, enum, const, exception, interface, module + + , typedef, struct, union, enum, const, exception, interface, module + + typedef, struct, union, enum, const, exception, interface, module + + module + + typedef, struct, union, enum, const, exception, interface, module + + typedef, struct, union, enum, const, exception, interface, module, + + interface + + , :, { + + :, { + + typedef, struct, union, enum, const, exception, readonly, attribute, oneway, float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void, state + + , typedef, struct, union, enum, const, exception, readonly, attribute, oneway, float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void, state + + typedef, struct, union, enum, const, exception, readonly, attribute, oneway, float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void, state + + state + + private, protected, public, float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum, + + private, protected, public, float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + private, protected, public + + : + + , "," + + id, :: + + , :: + + const + + long, short, unsigned, char, boolean, float, double, string, id, :: + + -, +, ~, id, ::, literal, ( + + -, +, ~, id, ::, literal, ( + + , | + + -, +, ~, id, ::, literal, ( + + , ^ + + -, +, ~, id, ::, literal, ( + + , & + + -, +, ~, id, ::, literal, ( + + , >>, << + + -, +, ~, id, ::, literal, ( + + , +, - + + -, +, ~, id, ::, literal, ( + + , *, /, % + + -, +, ~, id, ::, literal, ( + + -, +, ~ + + id, ::, literal, ( + + literals + + -, +, ~, id, ::, literal, ( + + typedef, struct, union, enum + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, :: + + float, double, long, short, unsigned, char, boolean, octet, any + + sequence, string + + struct, union, enum + + id + + , "," + + id + + , [ + + float, double + + long, short, unsigned + + long, short + + unsigned + + char + + boolean + + octet + + any + + struct + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + , float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + union + + long, short, unsigned, char, boolean, enum, id, :: + + case, default + + , case, default + + case, default + + , case, default + + case, default + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + enum + + , "," + + sequence + + ",", > + + string + + , < + + [ + + readonly, attribute + + , "," + + exception + + , float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + oneway, float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void + + id, macroID + + , raises, context, ; + + , context + + oneway + + float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void + + ( + + in, out, inout, ) + + , "," + + in, out, inout + + in, out, inout + + raises + + , "," + + context + + , "," + + float, double, long, short, unsigned, char, boolean, octet, any, string, id, :: + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/follow.set b/idlj/src/main/java/com/sun/tools/corba/ee/idl/follow.set new file mode 100644 index 000000000..5d09a5374 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/follow.set @@ -0,0 +1,210 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +CORBA IDL +----------------- + + EOF + + EOF + + EOF, typedef, struct, union, enum, const, exception, interface, module, } + + ; + + } + + } + + ; + + ; + + ; + + } + + } + + typedef, struct, union, enum, const, exception, readonly, attribute, oneway, float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void, state, } + + typedef, struct, union, enum, const, exception, readonly, attribute, oneway, float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void, state, } + + } + + private, protected, public, float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum, } + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + { + + { + + ",", {, id, ::, literal, (, >, ), macroID + + ",", {, id, ::, literal, (, >, ), macroID + + ; + + id + + ;, ), >, ], : + + ;, ), >, ], : + + ;, ), >, ], : + + |, ;, ), >, ], : + + | ;, ), >, ], : + + ^, |, ;, ), >, ], : + + ^, |, ;, ), >, ], : + + &, ^, |, ;, ), >, ], : + + &, ^, |, ;, ), >, ], : + + >>, <<, &, ^, |, ;, ), >, ], : + + >>, <<, &, ^, |, ;, ), >, ], : + + >>, <<, &, ^, |, ;, ), >, ], : + + +, -, >>, <<, &, ^, |, ;, ), >, ], : + + *, /, %, +, -, >>, <<, &, ^, |, ;, ), >, ], : + + id, ::, literal, ( + + *, /, %, +, -, >>, <<, &, ^, |, ;, ), >, ], : + + *, /, %, +, -, >>, <<, &, ^, |, ;, ), >, ], : (and , for string literal in ) + + >, ] + + ; + + ; + + id + + id, ",", > + + id, ",", >, macroID + + id, ",", > + + id + + ; + + ; + + ",", ; + + ",", ; + + id, ",", >, macroID + + id, ",", >, macroID, ) + + id, ",", >, macroID, ) + + id, ",", >, macroID, ) + + id, ",", >, macroID, ) + + id, ",", >, macroID, ) + + id, ",", >, macroID + + id, ",", >, macroID + + ;, id + + } + + } + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum, } + + ;, id + + ) + + } + + } + + case, default, } + + float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + case, default, float, double, long, short, unsigned, char, boolean, octet, any, sequence, string, id, ::, struct, union, enum + + ; + + ;, id, ) + + } + + id, ",", > + + id, ",", > + + id, ",", >, macroID + + id, ",", >, macroID + + [, ",", ; + + ; + + ; + + ; + + } + + ; + + ; + + ; + + ; + + float, double, long, short, unsigned, char, boolean, octet, any, string, id, ::, void + + id, macroID + + raises, context, ; + + raises, context, ; + + ) + + , ) + + float, double, long, short, unsigned, char, boolean, octet, any, string, id, :: + + context, ; + + ) + + ; + + ) + + id, macroID + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/grammar.idl b/idlj/src/main/java/com/sun/tools/corba/ee/idl/grammar.idl new file mode 100644 index 000000000..ec1c49ef9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/grammar.idl @@ -0,0 +1,399 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +CORBA 2.3 IDL +--------------- + +(1) + +(1) e + + +(2) ";" + ";" + ";" + ";" + ";" + ";" + +(3) "module" "{" "}" + +(3) + +(3) + e + +(4) + + +(5) "{" "}" + +(6) "abstract" "interface" + "interface" + +(7) "abstract" "interface" + "interface" + +(7) e + + +(8) + +(8) e + + +(9) ";" + ";" + ";" + ";" + ";" + + + +(10) ":" + +(10) e + "," + +(12) + "::" + +(12) e + "::" + +(13) + + + + +(14) "abstract" "valuetype" + "valuetype" + +(15) "valuetype" + +(16) "abstract" "valuetype" "{" "}" + "abstract" "valuetype" "{" "}" + +(16) e + + +(17) "{" "}" + +(17) e + + +(18) "custom" "valuetype" + "valuetype" + "custom" "valuetype" + "valuetype" + +(19) + +(19) e + ":" "truncatable" + ":" + +(19) e + "," + +(19) e + "supports" + +(19) e + "," + +(20) + +(21) + + + +(22) "public" ";" + "private" ";" + +(23) "factory" "(" ")" + "factory" "(" ")" + +(24) + "," + +(25) + +(26) "in" + +(27) "const" "=" + +(28) + + + + + + + + + +(29) + +(30) + +(30) e + "|" + +(31) + +(31) e + "^" + +(32) + +(32) e + "&" + +(33) + +(33) e + ">>" + "<<" + +(34) + +(34) e + "+" + "-" + +(35) + +(35) e + "*" + "/" + "%" + +(36) + + +(37) "-" + "+" + "~" + +(38) + + "(" ")" + +(39) <> + <>> + <>> + <> + <> + <> + <> + <> + +(40) "TRUE" + "FALSE" + +(41) + +(42) "typedef" + + + + "native" + +(43) + +(44) + + +(45) + + + +(46) + + + + + + + + + +(47) + + + + +(48) + + + +(49) + +(49) e + "," + +(50) + + +(51) + +(52) + +(53) "float" + "double" + "long" "double" + +(54) + + +(55) "long" + "short" + "long" "long" + +// 56-58 omitted + +(59) "unsigned" + +// 60-62 omitted + +(63) "char" + +(64) "wchar" + +(65) "boolean" + +(66) "octet" + +(67) "any" + +(68) "Object" + +(69) "struct" "{" "}" + +(70) + +(70) e + + +(71) ";" + +(72) "union" "switch" "(" ")" "{" "}" + +(73) + + + + + +(74) + +(74) e + + +(75) ";" + +(75) e + + +(76) "case" ":" + "default" ":" + +(77) + +(78) "enum" "{" "}" + +(78) e + "," + +// 79 omitted + +(80) "sequence" "<" + +(80) "," ">" + ">" + +(81) "string" + "string" "<" ">" + +(82) "wstring" + "wstring" "<" ">" + +(83) + +(84) "[" "]" + +(85) "readonly" "attribute" + "attribute" + +(85) e + "," + +(86) "exception" "{" "}" + +(86) e + + +(87) + + +(87) + + +(87) e + + + + +(88) "oneway" + +(89) + "void" + +(90) "(" + +(90) ")" + ")" + +(90) e + "," + +(91) + +(92) "in" + "out" + "inout" + +(93) "raises" "(" ")" + +(93) e + "," + +(94) "context" "(" ")" + +(94) e + "," + +(95) + + + + +(96) "fixed" "<" "," ">" + +(97) "fixed" + +(98) "ValueBase" + +NOTES: + +- #define id(id, id, ...) token-string is a macro definition. There can be no space between the first id and the left paren. Since id( must be treated as a token and id( can also appear in op_dcl, see that production for the effect of this token. + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/grammar3.idl b/idlj/src/main/java/com/sun/tools/corba/ee/idl/grammar3.idl new file mode 100644 index 000000000..2f393aa08 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/grammar3.idl @@ -0,0 +1,516 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +(1) // CORBA3 + +(1) e // CORBA3 + // CORBA3 + +(1) "import" ";" // CORBA3 + +(1) // CORBA3 + // CORBA3 + +(1) e + + +(2) ";" + ";" + ";" + ";" + ";" + ";" + ";" // CORBA3 + ";" // CORBA3 + ";" // CORBA3 + ";" // CORBA3 + +(2) "typeId" // CORBA3 + +(2) "typePrefix" // CORBA3 + +(3) "module" "{" "}" + +(3) + +(3) + e + +(4) + + +(5) "{" "}" + +(6) "abstract" "interface" + "local" "interface" // CORBA3 + "interface" + +(7) "abstract" "interface" + "local" "interface" // CORBA3 + "interface" + +(7) e + + +(8) + +(8) e + + +(9) ";" + ";" + ";" + ";" + ";" + ";" // CORBA3 + ";" // CORBA3 + +(10) ":" + +(10) e + "," + +(12) + "::" + +(12) e + "::" + +(13) + + + + +(14) "abstract" "valuetype" + "valuetype" + +(15) "valuetype" + +(16) "abstract" "valuetype" "{" "}" + "abstract" "valuetype" "{" "}" + +(16) e + + +(17) "{" "}" + +(17) e + + +(18) "custom" "valuetype" + "valuetype" + "custom" "valuetype" + "valuetype" + +(19) + +(19) e + ":" "truncatable" + ":" + +(19) e + "," + +(19) e + "supports" + +(19) e + "," + +(20) + +(21) + + + +(22) "public" ";" + "private" ";" + +(23) "factory" "(" ")" + "factory" "(" ")" + +(24) + "," + +(25) + +(26) "in" + +(27) "const" "=" + +(28) + + + + + + + + + +(29) + +(30) + +(30) e + "|" + +(31) + +(31) e + "^" + +(32) + +(32) e + "&" + +(33) + +(33) e + ">>" + "<<" + +(34) + +(34) e + "+" + "-" + +(35) + +(35) e + "*" + "/" + "%" + +(36) + + +(37) "-" + "+" + "~" + +(38) + + "(" ")" + +(39) <> + <>> + <>> + <> + <> + <> + <> + <> + +(40) "TRUE" + "FALSE" + +(41) + +(42) "typedef" + + + + "native" + +(43) + +(44) + + +(45) + + + +(46) + + + + + + + + + +(47) + + + + +(48) + + + +(49) + +(49) e + "," + +(50) + + +(51) + +(52) + +(53) "float" + "double" + "long" "double" + +(54) + + +(55) "long" + "short" + "long" "long" + +// 56-58 omitted + +(59) "unsigned" + +// 60-62 omitted + +(63) "char" + +(64) "wchar" + +(65) "boolean" + +(66) "octet" + +(67) "any" + +(68) "Object" + +(69) "struct" "{" "}" + +(70) + +(70) e + + +(71) ";" + +(72) "union" "switch" "(" ")" "{" "}" + +(73) + + + + + +(74) + +(74) e + + +(75) ";" + +(75) e + + +(76) "case" ":" + "default" ":" + +(77) + +(78) "enum" "{" "}" + +(78) e + "," + +// 79 omitted + +(80) "sequence" "<" + +(80) "," ">" + ">" + +(81) "string" + "string" "<" ">" + +(82) "wstring" + "wstring" "<" ">" + +(83) + +(84) "[" "]" + +(85) // CORBA3 + // CORBA3 + +(85) // CORBA3 + +(85) "readonly" "attribute" // CORBA3 + +(85) // CORBA3 + // CORBA3 + +(85) e // CORBA3 + // CORBA3 + +(85) "attribute" // CORBA3 + +(85) // CORBA3 + // CORBA3 + +(85) // CORBA3 + // CORBA3 + // CORBA3 + +(85) "getRaises" // CORBA3 + +(85) "setRaises" // CORBA3 + +(85) "(" ")" // CORBA3 + +(85) e // CORBA3 + "," // CORBA3 + +(86) "exception" "{" "}" + +(86) e + + +(87) + + +(87) + + +(87) e + + + + +(88) "oneway" + +(89) + "void" + +(90) "(" + +(90) ")" + ")" + +(90) e + "," + +(91) + +(92) "in" + "out" + "inout" + +(93) "raises" "(" ")" + +(93) e + "," + +(94) "context" "(" ")" + +(94) e + "," + +(95) + + + + +(96) "fixed" "<" "," ">" + +(97) "fixed" + +(98) "ValueBase" + +// CORBA3 Component and Home IDL + +(200) + + +(201) "component" + +(202) "{" "}" + +(203) "component" + "component" + "component" + "component" + +(204) "supports" + +(204) e + "," + +(205) ":" + +(206) + +(206) e + + +(207) ";" + ";" + ";" + ";" + ";" + ";" + +(208) "provides" + +(209) + "Object" + +(210) "uses" + "uses" "multiple" + +(211) "emits" + +(212) "publishes" + +(213) "consumes" + +(214) + +(215) "home" "manages" + "home" "manages" + "home" "manages" + "home" "manages" + +(216) ":" + +(217) "primaryKey" + +(218) "{" "}" + +(218) e + + +(219) + ";" + ";" + +(220) "factory" "(" ")" + "factory" "(" ")" + "factory" "(" ")" + "factory" "(" ")" + +(221) "finder" "(" ")" + "finder" "(" ")" + "finder" "(" ")" + "finder" "(" ")" + +NOTES: + +- #define id(id, id, ...) token-string is a macro definition. There can be no space between the first id and the left paren. Since id( must be treated as a token and id( can also appear in op_dcl, see that production for the effect of this token. + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl new file mode 100644 index 000000000..9579a78c6 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl @@ -0,0 +1,763 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * This file contains OMG IDL from CORBA V2.0, July 1995. + * It also contains the TypeCode creation APIs in CORBA::ORB + **/ + +#pragma prefix "omg.org" + +module CORBA { + typedef string Identifier; + typedef string ScopedName; + typedef string RepositoryId; + + enum DefinitionKind { + dk_none, dk_all, + dk_Attribute, dk_Constant, dk_Exception, dk_Interface, + dk_Module, dk_Operation, dk_Typedef, + dk_Alias, dk_Struct, dk_Union, dk_Enum, + dk_Primitive, dk_String, dk_Sequence, dk_Array, + dk_Repository, + dk_Wstring, dk_Fixed, + dk_Value, dk_ValueBox, dk_ValueMember, // orbos 98-01-18: Objects By Value + dk_Native + }; + + + interface IRObject + /** + An IRObject IDL interface represents the most generic interface + from which all other Interface Repository interfaces are derived, + even the Repository itself. + */ + { + // read interface + readonly attribute DefinitionKind def_kind; + + // write interface + void destroy (); + }; + + + + typedef string VersionSpec; + + interface Contained; + interface Repository; + interface Container; + + interface Contained : IRObject + /** + The Contained Interface is inherited by all Interface Repository + interfaces that are contained by other objects. + */ + { + // read/write interface + + attribute RepositoryId id; + attribute Identifier name; + attribute VersionSpec version; + + // read interface + + readonly attribute Container defined_in; + readonly attribute ScopedName absolute_name; + readonly attribute Repository containing_repository; + + struct Description { + DefinitionKind kind; + any value; + }; + + Description describe (); + + // write interface + + void move ( + in Container new_container, + in Identifier new_name, + in VersionSpec new_version + ); + }; + + + interface ModuleDef; + interface ConstantDef; + interface IDLType; + interface StructDef; + interface UnionDef; + interface EnumDef; + interface AliasDef; + interface InterfaceDef; + interface ExceptionDef; + interface ValueDef; // orbos 98-01-18: Objects By Value + interface ValueMemberDef; // orbos 98-01-18: Objects By Value + interface ValueBoxDef; // orbos 98-01-18: Objects By Value + interface NativeDef; + + + typedef sequence InterfaceDefSeq; + + + typedef sequence ContainedSeq; + + struct StructMember { + Identifier name; + TypeCode type; + IDLType type_def; + }; + typedef sequence StructMemberSeq; + + struct UnionMember { + Identifier name; + any label; + TypeCode type; + IDLType type_def; + }; + typedef sequence UnionMemberSeq; + + + typedef sequence EnumMemberSeq; + + // orbos 98-01-18: Objects By Value -- begin + typedef short Visibility; + const Visibility PRIVATE_MEMBER = 0; + const Visibility PUBLIC_MEMBER = 1; + + struct ValueMember { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + IDLType type_def; + Visibility access; + }; + typedef sequence ValueMemberSeq; + + struct Initializer { + StructMemberSeq members; + }; + typedef sequence InitializerSeq; + + typedef sequence ValueDefSeq; + + // orbos 98-01-18: Objects By Value -- end + + + interface Container : IRObject + /** + The Container interface is used to form a containment hierarchy + in the Interface Repository. A Container can contain any number + of objects derived from the Contained interface. + */ + { + // read interface + + Contained lookup ( in ScopedName search_name); + + ContainedSeq contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + ContainedSeq lookup_name ( + in Identifier search_name, + in long levels_to_search, + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + struct Description { + Contained contained_object; + DefinitionKind kind; + any value; + }; + + typedef sequence DescriptionSeq; + + DescriptionSeq describe_contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited, + in long max_returned_objs + ); + + // write interface + + ModuleDef create_module ( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + ConstantDef create_constant ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in any value + ); + + StructDef create_struct ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + UnionDef create_union ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType discriminator_type, + in UnionMemberSeq members + ); + + EnumDef create_enum ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in EnumMemberSeq members + ); + + AliasDef create_alias ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type + ); + + ExceptionDef create_exception ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + + InterfaceDef create_interface ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_abstract, + in InterfaceDefSeq base_interfaces + ); + + // orbos 98-01-18: Objects By Value + ValueDef create_value( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_custom, + in boolean is_abstract, + in octet flags, // must be 0 + in ValueDef base_value, + in boolean has_safe_base, + in ValueDefSeq abstract_base_values, + in InterfaceDefSeq supported_interfaces, + in InitializerSeq initializers + ); + + // orbos 98-01-18: Objects By Value + ValueBoxDef create_value_box( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type_def + ); + + NativeDef create_native( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + }; + + + + interface IDLType : IRObject + /** + The IDLType interface is an abstract interface inherited by all + IR objects that represent the OMG IDL types. It provides access + to the TypeCode describing the type, and is used in defining the + other interfaces wherever definitions of IDLType must be referenced. + */ + { + readonly attribute TypeCode type; + }; + + + + interface PrimitiveDef; + interface StringDef; + interface SequenceDef; + interface ArrayDef; + + enum PrimitiveKind { + pk_null, pk_void, pk_short, pk_long, pk_ushort, pk_ulong, + pk_float, pk_double, pk_boolean, pk_char, pk_octet, + pk_any, pk_TypeCode, pk_Principal, pk_string, pk_objref + }; + + interface Repository : Container + /** + Repository is an interface that provides global access to the + Interface Repository. Repository objects can contain constants, + typedefs, exceptions, interfaces, and modules. + */ + { + // read interface + + Contained lookup_id (in RepositoryId search_id); + + PrimitiveDef get_primitive (in PrimitiveKind kind); + + // write interface + + StringDef create_string (in unsigned long bound); + + SequenceDef create_sequence ( + in unsigned long bound, + in IDLType element_type + ); + + ArrayDef create_array ( + in unsigned long length, + in IDLType element_type + ); + }; + + + interface ModuleDef : Container, Contained + /** + A ModuleDef can contain constants, typedefs, exceptions, interfaces, + and other module objects. + */ + { + }; + + struct ModuleDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + }; + + + interface ConstantDef : Contained + /** + A ConstantDef object defines a named constant. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute any value; + }; + + struct ConstantDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + any value; + }; + + + interface TypedefDef : Contained, IDLType + /** + TypedefDef is an abstract interface used as a base interface for + all named non-object types(structures, unions, enumerations, + aliases). The TypedefDef interface is not inherited by the definition + objects for the primitive or anonymous types. + */ + { + }; + + struct TypeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + interface StructDef : TypedefDef, Container + /** + A StructDef represents an OMG IDL structure definition. + */ + { + attribute StructMemberSeq members; + }; + + + interface UnionDef : TypedefDef, Container + /** + A UnionDef represents an OMG IDL union definition. + */ + { + readonly attribute TypeCode discriminator_type; + attribute IDLType discriminator_type_def; + attribute UnionMemberSeq members; + }; + + + interface EnumDef : TypedefDef + /** + A EnumDef represents an OMG IDL enum definition. + */ + { + attribute EnumMemberSeq members; + }; + + + interface AliasDef : TypedefDef + /** + An AliasDef represents an OMG IDL typedef that aliases other + definition. + */ + { + attribute IDLType original_type_def; + }; + + + interface PrimitiveDef: IDLType + /** + A PrimitiveDef represents one of the IDL primitive types. As + primitive types are unnamed, this interface is not derived from + TypedefDef or Contained. + */ + { + readonly attribute PrimitiveKind kind; + }; + + + interface StringDef : IDLType + /** + A StringDef represents an OMG IDL string type. As string + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + }; + + + interface SequenceDef : IDLType + /** + A SequenceDef represents an OMG IDL sequence type. As sequence + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + interface ArrayDef : IDLType + /** + An ArrayDef represents an OMG IDL array type. As array + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long length; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + + interface ExceptionDef : Contained, Container + /** + An ExceptionDef represents an exception definition. + */ + { + readonly attribute TypeCode type; + attribute StructMemberSeq members; + }; + struct ExceptionDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + + enum AttributeMode {ATTR_NORMAL, ATTR_READONLY}; + + interface AttributeDef : Contained + /** + An AttributeDef represents the information that defines an + attribute of an interface. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute AttributeMode mode; + }; + + struct AttributeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + AttributeMode mode; + }; + + + + enum OperationMode {OP_NORMAL, OP_ONEWAY}; + + enum ParameterMode {PARAM_IN, PARAM_OUT, PARAM_INOUT}; + struct ParameterDescription { + Identifier name; + TypeCode type; + IDLType type_def; + ParameterMode mode; + }; + typedef sequence ParDescriptionSeq; + + typedef Identifier ContextIdentifier; + typedef sequence ContextIdSeq; + + typedef sequence ExceptionDefSeq; + typedef sequence ExcDescriptionSeq; + + interface OperationDef : Contained + /** + An OperationDef represents the information that defines an + operation of an interface. + */ + { + readonly attribute TypeCode result; + attribute IDLType result_def; + attribute ParDescriptionSeq params; + attribute OperationMode mode; + attribute ContextIdSeq contexts; + attribute ExceptionDefSeq exceptions; + }; + + struct OperationDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode result; + OperationMode mode; + ContextIdSeq contexts; + ParDescriptionSeq parameters; + ExcDescriptionSeq exceptions; + }; + + + + typedef sequence RepositoryIdSeq; + typedef sequence OpDescriptionSeq; + typedef sequence AttrDescriptionSeq; + + interface InterfaceDef : Container, Contained, IDLType + /** + An InterfaceDef object represents an interface definition. It can + contains constants, typedefs, exceptions, operations, and + attributes. + */ + { + // read/write interface + + attribute InterfaceDefSeq base_interfaces; + attribute boolean is_abstract; + + // read interface + + boolean is_a (in RepositoryId interface_id); + + struct FullInterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + boolean is_abstract; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + RepositoryIdSeq base_interfaces; + TypeCode type; + }; + + FullInterfaceDescription describe_interface(); + + // write interface + + AttributeDef create_attribute ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + + struct InterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq base_interfaces; + }; + + + // orbos 98-01-18: Objects By Value -- begin + + interface ValueMemberDef : Contained + + /** A ValueMemberDef object represents the public + and private data member definition of a Value type + */ + + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute Visibility access; + }; + + interface ValueDef : Container, Contained, IDLType + /** + A ValueDef object represents the definition of the + Value object used to pass the object state + between hosts + */ + + { + // read/write interface + attribute InterfaceDefSeq supported_interfaces; + attribute InitializerSeq initializers; + attribute ValueDef base_value; + attribute ValueDefSeq abstract_base_values; + attribute boolean is_abstract; + attribute boolean is_custom; + attribute octet flags; // always 0 + attribute boolean has_safe_base; + + // read interface + boolean is_a(in RepositoryId value_id); + + struct FullValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + ValueMemberSeq members; + InitializerSeq initializers; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + TypeCode type; + }; + + FullValueDescription describe_value(); + + // write interface + + ValueMemberDef create_value_member( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type_def, + in Visibility access + ); + + AttributeDef create_attribute( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + struct ValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + }; + + interface ValueBoxDef : IDLType + + /** ValueBoxDef is an interface that reresents a value type with + a single data member inside its state section and no + inheritance or methods. For example, when transmitting a + string or sequence as an actual parameter on an interface + operation or as a data member of a value type that is an + actual parameter, it may be important to preserve any sharing + of the string or sequence within the object graph being + transmitted. Because current IDL data types do not preserve + referential integrity in this way, this requirement is + conveniently handled by using a value type. Value types also + support the transmission of nulls (as a distinguished value), + whereas IDL data types such as string and sequence (which are + mapped to empty strings and sequences) do not. The Java to IDL + mapping requires both preservation of referential integrity + and transmission of nulls. Because it would be cumbersome to + require the full IDL syntax for a value type for this specific + usage, this shorthand notation is introduced to cover this use + of value types for simple containment of a single data member. + */ + +{ + attribute IDLType original_type_def; + }; + + // orbos 98-01-18: Objects By Value -- end + + interface NativeDef : TypedefDef { + }; +}; diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/keywords.txt b/idlj/src/main/java/com/sun/tools/corba/ee/idl/keywords.txt new file mode 100644 index 000000000..113cae91e --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/keywords.txt @@ -0,0 +1,91 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +IDL Tokens: + +Grouping: ( ) [ ] { } +Separators: : :: ; +Operators: % & * + , - / < << = > >> ^ | ~ + +Keywords: + CORBA 2.2 or earlier: + any + attribute + boolean + case + char + const + context + default + double + enum + exception + FALSE + float + in + inout + interface + long + module + Object + octet + oneway + out + raises + readonly + sequence + short + string + struct + switch + TRUE + typedef + unsigned + union + void + wchar + wstring + + CORBA 2.3 only: + init (replaced by factory) + + CORBA 2.3 and 2.4rtf: + abstract + custom + private + public + truncatable + ValueBase + valuetype + factory + + CORBA 2.3, not supported by IBM compiler + native + fixed + + CORBA 3.0: + component + consumes + emits + finder + getRaises + home + import + local + manages + multiple + primaryKey + provides + publishes + setRaises + supports + typeId + typePrefix + uses diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/orb.idl b/idlj/src/main/java/com/sun/tools/corba/ee/idl/orb.idl new file mode 100644 index 000000000..5fde42430 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/orb.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// IDL not generated by rmic, do not edit +// These are all in IDL module CORBA +// The Java classes are in the package org.omg.CORBA +// See ValueType Semantics:Standard Value Box Definitions (5.3) in CORBA 2.3 spec + +#ifndef __org_omg_CORBA__ +#define __org_omg_CORBA__ + +#pragma prefix "omg.org" + +module CORBA{ + + valuetype StringValue string; + valuetype WStringValue wstring; + +}; + +#include "ir.idl" + +#pragma prefix "" + +#endif diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/cff/FileLocator.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/cff/FileLocator.java new file mode 100644 index 000000000..2b20a82ff --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/cff/FileLocator.java @@ -0,0 +1,392 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.som.cff; + +import java.lang.Exception; +import java.lang.String; +import java.lang.System; +import java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.IOException; +import java.util.Locale; +import java.util.NoSuchElementException; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.zip.*; + +/** + * FileLocator is an abstract class (one that cannot be instantiated) that + * provides class methods for finding files in the directories or zip + * archives that make up the CLASSPATH. + * + * @author Larry K. Raper + */ +public abstract class FileLocator extends Object { + + /* Class variables */ + + + static final Properties pp = System.getProperties (); + static final String classPath = pp.getProperty ("java.class.path", "."); + static final String pathSeparator = pp.getProperty ("path.separator", ";"); + + /* Instance variables */ + + /* [None, no instances of this class are ever instantiated.] */ + + /** + * locateClassFile returns a DataInputStream with mark/reset + * capability that can be used to read the requested class file. The + * CLASSPATH is used to locate the class. + * + * @param classFileName The name of the class to locate. The class name + * should be given in fully-qualified form, for example: + *
+     *     java.lang.Object
+     *     java.io.DataInputStream
+     * 
+ * + * @exception java.io.FileNotFoundException The requested class file + * could not be found. + * @exception java.io.IOException The requested class file + * could not be opened. + */ + public static DataInputStream locateClassFile (String classFileName) + throws FileNotFoundException, IOException { + + boolean notFound = true; + StringTokenizer st; + String path = ""; + String pathNameForm; + File cf = null; + NamedDataInputStream result; + + st = new StringTokenizer (classPath, pathSeparator, false); + pathNameForm = classFileName.replace ('.', File.separatorChar) + + ".class"; + + while (st.hasMoreTokens () && notFound) { + + try {path = st.nextToken ();} + catch (NoSuchElementException nse) {break;} + int pLen = path.length (); + String pathLast4 = pLen > 3 ? path.substring (pLen - 4) : ""; + if (pathLast4.equalsIgnoreCase (".zip") || + pathLast4.equalsIgnoreCase (".jar")) { + + try { + + result = locateInZipFile (path, classFileName, true, true); + if (result == null) + continue; + return (DataInputStream) result; + + } catch (ZipException zfe) { + continue; + } catch (IOException ioe) { + continue; + } + + } else { + try {cf = new File (path + File.separator + pathNameForm); + } catch (NullPointerException npe) { continue; } + if ((cf != null) && cf.exists ()) + notFound = false; + } + } + + if (notFound) { + + /* Make one last attempt to find the file in the current + * directory + */ + + int lastdot = classFileName.lastIndexOf ('.'); + String simpleName = + (lastdot >= 0) ? classFileName.substring (lastdot+1) : + classFileName; + + result = new NamedDataInputStream (new BufferedInputStream ( + new FileInputStream (simpleName + ".class")), + simpleName + ".class", false); + return (DataInputStream) result; + } + + result = new NamedDataInputStream (new BufferedInputStream ( + new FileInputStream (cf)), path + File.separator + pathNameForm, + false); + return (DataInputStream) result; + + } + + /** + * locateLocaleSpecificFileInClassPath returns a DataInputStream that + * can be used to read the requested file, but the name of the file is + * determined using information from the current locale and the supplied + * file name (which is treated as a "base" name, and is supplemented with + * country and language related suffixes, obtained from the current + * locale). The CLASSPATH is used to locate the file. + * + * @param fileName The name of the file to locate. The file name + * may be qualified with a partial path name, using '/' as the separator + * character or using separator characters appropriate for the host file + * system, in which case each directory or zip file in the CLASSPATH will + * be used as a base for finding the fully-qualified file. + * Here is an example of how the supplied fileName is used as a base + * for locating a locale-specific file: + * + *
+     *     Supplied fileName: a/b/c/x.y,  current locale: US English
+     *
+     *                     Look first for: a/b/c/x_en_US.y
+     *     (if that fails) Look next for:  a/b/c/x_en.y
+     *     (if that fails) Look last for:  a/b/c/x.y
+     *
+     *     All elements of the class path are searched for each name,
+     *     before the next possible name is tried.
+     * 
+ * + * @exception java.io.FileNotFoundException The requested class file + * could not be found. + * @exception java.io.IOException The requested class file + * could not be opened. + */ + public static DataInputStream locateLocaleSpecificFileInClassPath ( + String fileName) throws FileNotFoundException, IOException { + + String localeSuffix = "_" + Locale.getDefault ().toString (); + int lastSlash = fileName.lastIndexOf ('/'); + int lastDot = fileName.lastIndexOf ('.'); + String fnFront, fnEnd; + DataInputStream result = null; + boolean lastAttempt = false; + + if ((lastDot > 0) && (lastDot > lastSlash)) { + fnFront = fileName.substring (0, lastDot); + fnEnd = fileName.substring (lastDot); + } else { + fnFront = fileName; + fnEnd = ""; + } + + while (true) { + if (lastAttempt) + result = locateFileInClassPath (fileName); + else try { + result = locateFileInClassPath (fnFront + localeSuffix + fnEnd); + } catch (Exception e) { /* ignore */ } + if ((result != null) || lastAttempt) + break; + int lastUnderbar = localeSuffix.lastIndexOf ('_'); + if (lastUnderbar > 0) + localeSuffix = localeSuffix.substring (0, lastUnderbar); + else + lastAttempt = true; + } + return result; + + } + + /** + * locateFileInClassPath returns a DataInputStream that can be used + * to read the requested file. The CLASSPATH is used to locate the file. + * + * @param fileName The name of the file to locate. The file name + * may be qualified with a partial path name, using '/' as the separator + * character or using separator characters appropriate for the host file + * system, in which case each directory or zip file in the CLASSPATH will + * be used as a base for finding the fully-qualified file. + * + * @exception java.io.FileNotFoundException The requested class file + * could not be found. + * @exception java.io.IOException The requested class file + * could not be opened. + */ + public static DataInputStream locateFileInClassPath (String fileName) + throws FileNotFoundException, IOException { + + boolean notFound = true; + StringTokenizer st; + String path = ""; + File cf = null; + NamedDataInputStream result; + + String zipEntryName = File.separatorChar == '/' ? fileName : + fileName.replace (File.separatorChar, '/'); + + String localFileName = File.separatorChar == '/' ? fileName : + fileName.replace ('/', File.separatorChar); + + st = new StringTokenizer (classPath, pathSeparator, false); + + while (st.hasMoreTokens () && notFound) { + + try {path = st.nextToken ();} + catch (NoSuchElementException nse) {break;} + int pLen = path.length (); + String pathLast4 = pLen > 3 ? path.substring (pLen - 4) : ""; + if (pathLast4.equalsIgnoreCase (".zip") || + pathLast4.equalsIgnoreCase (".jar")) { + + try { + + result = locateInZipFile (path, zipEntryName, false, false); + if (result == null) + continue; + return (DataInputStream) result; + + } catch (ZipException zfe) { + continue; + } catch (IOException ioe) { + continue; + } + + } else { + try {cf = new File (path + File.separator + localFileName); + } catch (NullPointerException npe) { continue; } + if ((cf != null) && cf.exists ()) + notFound = false; + } + } + + if (notFound) { + + /* Make one last attempt to find the file in the current + * directory + */ + + int lastpart = localFileName.lastIndexOf (File.separator); + String simpleName = + (lastpart >= 0) ? localFileName.substring (lastpart+1) : + localFileName; + + result = new NamedDataInputStream (new BufferedInputStream ( + new FileInputStream (simpleName)), simpleName, false); + return (DataInputStream) result; + } + + result = new NamedDataInputStream (new BufferedInputStream ( + new FileInputStream (cf)), path + File.separator + localFileName, + false); + return (DataInputStream) result; + + } + + /** + * Returns the fully qualified file name associated with the passed + * DataInputStream if the DataInputStream was created using one + * of the static locate methods supplied with this class, otherwise + * returns a zero length string. + */ + public static String getFileNameFromStream (DataInputStream ds) { + + if (ds instanceof NamedDataInputStream) + return ((NamedDataInputStream) ds).fullyQualifiedFileName; + return ""; + + } + + /** + * Returns an indication of whether the passed DataInputStream is + * associated with a member of a zip file if the DataInputStream was + * created using one of the static locate methods supplied with this + * class, otherwise returns false. + */ + public static boolean isZipFileAssociatedWithStream (DataInputStream ds) { + + if (ds instanceof NamedDataInputStream) + return ((NamedDataInputStream) ds).inZipFile; + return false; + + } + + private static NamedDataInputStream locateInZipFile (String zipFileName, + String fileName, boolean wantClass, boolean buffered) + throws ZipException, IOException { + + ZipFile zf; + ZipEntry ze; + zf = new ZipFile (zipFileName); + + if (zf == null) + return null; + String zeName = wantClass ? + fileName.replace ('.', '/') + ".class" : + fileName; + + // This code works with JDK 1.0 level SUN zip classes + // + + // ze = zf.get (zeName); + // if (ze == null) + // return null; + // return new NamedDataInputStream ( + // new BufferedInputStream (new ZipInputStream (ze)), + // zipFileName + '(' +zeName + ')', true); + + // This code works with JDK 1.0.2 and JDK 1.1 level SUN zip classes + // + + ze = zf.getEntry (zeName); + if (ze == null) { + zf.close(); // D55355, D56419 + zf = null; + return null; + } + InputStream istream = zf.getInputStream(ze); + if (buffered) + istream = new BufferedInputStream(istream); + return new NamedDataInputStream (istream, + zipFileName + '(' + zeName + ')', true); + + } + +} + +/** + * This class is used to associate a filename with a DataInputStream + * The host platform's file naming conventions are assumed for the filename. + * + * @version 1.16, 07/27/07 + * @author Larry K. Raper + * + */ +/* default access */ class NamedDataInputStream extends DataInputStream { + + /* Instance variables */ + + /** + * The name of the file associated with the DataInputStream. + */ + public String fullyQualifiedFileName; + + /** + * Indicates whether or not the file is contained in a .zip file. + */ + public boolean inZipFile; + + /* Constructors */ + + protected NamedDataInputStream (InputStream in, String fullyQualifiedName, + boolean inZipFile) { + + super (in); + this.fullyQualifiedFileName = fullyQualifiedName; + this.inZipFile = inZipFile; + + } + +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/cff/Messages.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/cff/Messages.java new file mode 100644 index 000000000..586719161 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/cff/Messages.java @@ -0,0 +1,331 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.som.cff; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; +import java.lang.String; +import java.lang.System; + +/** + * This class provides messaging services for accessing, and merging + * parameters into, translatable message text. The text is presumed + * to reside in a .properties file. A "cff.properties" file that + * contains all of the message text needed for the CFF framework itself + * is loaded during class initialization. All of the messages in the + * cff.properties file that are needed by the CFF framework contain keys + * that begin with the string "cff.". + *

+ * The static method Messages.msgLoad may be used to merge additional + * message text .properties files needed by other frameworks or user + * programs. + * + * @see Messages#msgLoad + * + * @author Larry K. Raper + */ + +public abstract class Messages { + + /* Class variables */ + + + /* Metasymbol for leading or trailing blank */ + private static final String LTB = "%B"; + /* Metasymbol for line separator */ + private static final char NL = '\n'; + + private static final String lineSeparator = + System.getProperty ("line.separator"); + + private static final Properties m = new Properties (); + private static boolean loadNeeded = true; + + /* Class methods for message loading and formatting */ + + private static final synchronized void loadDefaultProperties () { + + if (!loadNeeded) + return; + try { + m.load (FileLocator.locateLocaleSpecificFileInClassPath( + "com/sun/tools/corba/se/idl/som/cff/cff.properties")); + } catch (IOException ioe) { } + fixMessages (m); /* #26964 Replace any metasymbols */ + loadNeeded = false; + + } + + /** + * This method was introduced to fix defect #26964. For Java 1.0.2 + * on Win NT, the escape sequence \u0020 was not being handled + * correctly by the Java Properties class when it was the final + * character of a line. Instead the trailing blank was dropped + * and the next line was swallowed as a continuation. To work + * around the problem, we introduced our own metasymbol to represent + * a trailing blank. Hence: + * + * Performs substitution for any metasymbols in the message + * templates. So far only %B is needed. This was introduced + * to make it more convenient for .properties files to + * contain message templates with leading or trailing blanks + * (although %B may actually occur anywhere in a template). + * Subsequently, checking for '\n' has also been added. Now, + * wherever '\n' occurs in a message template, it is replaced + * with the value of System.getProperty ("line.separator"). + */ + private static final void fixMessages (Properties p) { + + Enumeration keys = p.keys (); + Enumeration elems = p.elements (); + while (keys.hasMoreElements ()) { + String key = (String) keys.nextElement (); + String elem = (String) elems.nextElement (); + int i = elem.indexOf (LTB); + boolean changed = false; + while (i != -1) { + if (i == 0) + elem = " " + elem.substring (2); + else + elem = elem.substring (0, i) + " " + elem.substring (i+2); + changed = true; + i = elem.indexOf (LTB); + } + int lsIncr = lineSeparator.length () - 1; + for (i=0; i + * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, String parm) { + + if (loadNeeded) + loadDefaultProperties (); + String msgtext = m.getProperty (msgkey, msgkey); + int i = msgtext.indexOf ("%1"); + if (i >= 0) { + String ending = ""; + if ((i+2) < msgtext.length ()) + ending = msgtext.substring (i+2); + return msgtext.substring (0, i) + parm + ending; + } else + msgtext += " " + parm; + return msgtext; + + } + + /** + * Returns the message text corresponding to the passed msgkey + * string. The message text is assumed to require the insertion + * of a single argument, supplied by the "parm" parameter. + * If the message text does not contain the meta characters "%1" + * that indicate where to place the argument, the passed argument + * is appended at the end of the message text. + *

+ * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, int parm) { + + return msg (msgkey, String.valueOf (parm)); + + } + + /** + * Returns the message text corresponding to the passed msgkey + * string. The message text is assumed to require the insertion + * of two arguments, supplied by the "parm1" and "parm2" parameters. + * If the message text does not contain the meta characters "%1" and + * "%2" that indicate where to place the arguments, the passed arguments + * are appended at the end of the message text. + *

+ * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, String parm1, String parm2) { + + if (loadNeeded) + loadDefaultProperties (); + String result = m.getProperty (msgkey, msgkey); + String ending = ""; + int i = result.indexOf ("%1"); + if (i >= 0) { + if ((i+2) < result.length ()) + ending = result.substring (i+2); + result = result.substring (0, i) + parm1 + ending; + } else + result += " " + parm1; + i = result.indexOf ("%2"); + if (i >= 0) { + ending = ""; + if ((i+2) < result.length ()) + ending = result.substring (i+2); + result = result.substring (0, i) + parm2 + ending; + } else + result += " " + parm2; + return result; + + } + + /** + * Returns the message text corresponding to the passed msgkey + * string. The message text is assumed to require the insertion + * of two arguments, supplied by the "parm1" and "parm2" parameters. + * If the message text does not contain the meta characters "%1" and + * "%2" that indicate where to place the arguments, the passed arguments + * are appended at the end of the message text. + *

+ * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, int parm1, String parm2) { + + return msg (msgkey, String.valueOf (parm1), parm2); + + } + + /** + * Returns the message text corresponding to the passed msgkey + * string. The message text is assumed to require the insertion + * of two arguments, supplied by the "parm1" and "parm2" parameters. + * If the message text does not contain the meta characters "%1" and + * "%2" that indicate where to place the arguments, the passed arguments + * are appended at the end of the message text. + *

+ * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, String parm1, int parm2) { + + return msg (msgkey, parm1, String.valueOf (parm2)); + + } + + /** + * Returns the message text corresponding to the passed msgkey + * string. The message text is assumed to require the insertion + * of two arguments, supplied by the "parm1" and "parm2" parameters. + * If the message text does not contain the meta characters "%1" and + * "%2" that indicate where to place the arguments, the passed arguments + * are appended at the end of the message text. + *

+ * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, int parm1, int parm2) { + + return msg (msgkey, String.valueOf (parm1), String.valueOf (parm2)); + + } + + + /** + * Returns the message text corresponding to the passed msgkey + * string. The message text is assumed to require the insertion + * of three arguments, supplied by the "parm1", "parm2" and "parm3" + * parameters. + * If the message text does not contain the meta characters "%1" and + * "%2" that indicate where to place the arguments, the passed arguments + * are appended at the end of the message text. + *

+ * If the msgkey cannot be found, its value is used as the + * message text. + */ + public static final String msg (String msgkey, String parm1, + String parm2, String parm3) { + if (loadNeeded) + loadDefaultProperties (); + String result = m.getProperty (msgkey, msgkey); + result = substituteString(result, 1, parm1); + result = substituteString(result, 2, parm2); + result = substituteString(result, 3, parm3); + + return result; + } + + /* helper function for string substition. + @return the substituted string, it substitution is possible. + Otherwise, return a new string with subst at the end. + @orig: original string + @paramNum the parameter number to search. For example, + paramNam == 1 means search for "%1". + @subst: string for the substitution. + */ + private static String substituteString(String orig, int paramNum, + String subst){ + String result = orig; + String paramSubst = "%"+ paramNum; + int len = paramSubst.length(); + int index = result.indexOf (paramSubst); + String ending = ""; + if (index >= 0) { + if ((index+len) < result.length ()) + ending = result.substring (index+len); + result = result.substring (0, index) + subst + ending; + } + else result += " " + subst; + + return result; + } + + +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/idlemit/MetaPragma.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/idlemit/MetaPragma.java new file mode 100644 index 000000000..2a436626d --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/som/idlemit/MetaPragma.java @@ -0,0 +1,239 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.som.idlemit; +import com.sun.tools.corba.ee.idl.ForwardEntry; +import com.sun.tools.corba.ee.idl.PragmaHandler; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.som.cff.Messages; + +import java.util.Vector; +/** + * This is an implementation that handles + * #pragma meta scoped_name string + * where + *

    + *
  • scoped_name == "::" separated scoped name + *
  • string == separated identifiers, such as "localonly", + * "abstract", or "init". + * D59407: NOTE: any non-white-space is grouped + * as part of the identifier. + *
+ * + * This pragma handler places a vector of Strings into the dynamicVariable() + * part of the SymtabEntry. The key to access the dynamicVariable() + * is MetaPragma.metaKey + * + * It is possible to associate a meta pragma with a forward entry. + * At some point after the parser has completed, + * the method processForward(ForwardEntry entry) should be called + * for each ForwardEntry so that the meta information can be folded from + * the ForwardEntry into the corresponding InterfaceEntry. + */ +public class MetaPragma extends PragmaHandler { + /* Class variables */ + + /* key to access the Cached meta info in SymtabEntry */ + public static int metaKey = SymtabEntry.getVariableKey(); + + + /** + * Main entry point for the MetaPragma handler + * @param pragma string for pragma name + * @param currentToken next token in the input stream. + * @return true if this is a meta pragma. + */ + public boolean process(String pragma, String currentToken) { + if ( !pragma.equals("meta")) + return false; + + SymtabEntry entry ; + String msg; + try { + entry = scopedName(); + if ( entry == null){ + /* scoped name not found */ + parseException(Messages.msg("idlemit.MetaPragma.scopedNameNotFound")); + skipToEOL(); + } + else { + msg = (currentToken()+ getStringToEOL()); +// System.out.println(entry + ": " + msg); + Vector v; + v = (Vector) entry.dynamicVariable(metaKey); + if ( v== null){ + v = new Vector(); + entry.dynamicVariable(metaKey, v); + } + parseMsg(v, msg); + } + } catch(Exception e){ +// System.out.println("exception in MetaPragma"); + } + return true; + } + + + /** + * Fold the meta info from the forward entry into its corresponding + * interface entry. + * @param forwardEntry the forward entry to process + */ + static public void processForward(ForwardEntry forwardEntry){ + + Vector forwardMeta; + try { + forwardMeta = (Vector)forwardEntry.dynamicVariable(metaKey); + } catch (Exception e){ + forwardMeta = null; + } + SymtabEntry forwardInterface = forwardEntry.type(); + if (forwardMeta != null && forwardInterface!= null) { + Vector interfaceMeta; + try { + interfaceMeta= (Vector)forwardInterface.dynamicVariable(metaKey); + } catch ( Exception e){ + interfaceMeta = null; + } + + if ( interfaceMeta == null) { + /* set */ + try { + forwardInterface.dynamicVariable(MetaPragma.metaKey, forwardMeta); + } catch(Exception e){}; + } + else if (interfaceMeta != forwardMeta) { + /* The above check is needed because sometimes + a forward entry is processed more the once. + Not sure why */ + /* merge */ + for (int i=0; i < forwardMeta.size(); i++){ + try { + Object obj = forwardMeta.elementAt(i); + interfaceMeta.addElement(obj); + } catch (Exception e){}; + } + } + } + } + + /** + * parse pragma message and place into vector v. + * @param v: vector to add message + * @param msg: string of comma separated message, perhaps with comment. + * This is implemented as a state machine as follows: + * + * State token next action + * ----------------------------------------------------- + * initial whitespace initial + * initial SlashStar comment + * initial SlashSlash final + * initial no more final + * initial text text add to text buffer + * initial StarSlash initial + * comment StarSlash initial + * comment SlashStar comment + * comment whitespace comment + * comment SlashSlash comment + * comment text comment + * comment no more final + * text text text add to buffer + * text SlashStar comment put in vector + * text whitespace initial put in vector + * text SlashSlash final put in vector + * text StarSlash initial put in vector + * text no more final put in vector + * + */ + private static int initialState = 0; + private static int commentState = 1; + private static int textState = 2; + private static int finalState =3; + + private void parseMsg(Vector v, String msg){ + int state = initialState; + String text = ""; + int index = 0; + while ( state != finalState ){ + boolean isNoMore = index >= msg.length(); + char ch = ' '; + boolean isSlashStar = false; + boolean isSlashSlash = false; + boolean isWhiteSpace = false; + boolean isStarSlash = false; + boolean isText = false; + if (!isNoMore ){ + ch = msg.charAt(index); + if (ch == '/' && index+1 < msg.length()){ + if (msg.charAt(index+1) == '/'){ + isSlashSlash = true; + index++; + } + else if (msg.charAt(index+1) == '*'){ + isSlashStar= true; + index++; + } else isText = true; + } + else if (ch == '*' && index+1 < msg.length() ){ + if (msg.charAt(index+1) == '/'){ + isStarSlash = true; + index++; + } else isText = true; + } + else if ( Character.isSpaceChar(ch) || (ch == ',') // 59601 + || (ch == ';') ) // 59683 + isWhiteSpace = true; + else isText = true; + } + + if (state == initialState){ + if (isSlashStar){ + state = commentState; + } + else if (isSlashSlash || isNoMore){ + state = finalState; + } + else if (isText){ + state = textState; + text = text+ ch; + } + } + else if (state == commentState){ + if (isNoMore){ + state = finalState; + } + else if ( isStarSlash){ + state = initialState; + } + } + else if (state == textState){ + if (isNoMore || isStarSlash || isSlashSlash || + isSlashStar || isWhiteSpace ){ + if (!text.equals("")) { + v.addElement(text); +// System.err.println("adding " + text); + text = ""; + } + if (isNoMore) + state = finalState; + else if (isSlashStar) + state = commentState; + else state = initialState; + } + else if (isText){ + text = text+ch; + } + } + index++; + } + } + +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Arguments.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Arguments.java new file mode 100644 index 000000000..b726cc914 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Arguments.java @@ -0,0 +1,315 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -09/23/98 Ported -td option to change output directory +// -09/23/98 Ported -m option to generate make dependencies +// -F46082.51 Transferred -m, -mmin, mall, -mdepend options to com.sun.tools.corba.ee.idl.toJava +// since these are IBM-specific (see f46838); cleaned-out dead code. +// -D57482 Added method setDefaultEmitter so could be overridden. +// -F60858.1 Set corba level to 2.3. + +import com.sun.tools.corba.ee.idl.InvalidArgument; + +import java.io.File; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; + +/** + * + **/ +public class Arguments extends com.sun.tools.corba.ee.idl.Arguments +{ + /** + * Public, zero-argument constructor. + **/ + public Arguments () + { + super (); + corbaLevel = 2.4f; + } // ctor + + /** + * + **/ + protected void parseOtherArgs (String[] args, + Properties properties) throws InvalidArgument + { + String skeletonPattern = null ; + String tiePattern = null ; + + // Get package prefixes from user's properties file. + packages.put ("CORBA", "org.omg"); // klr - always needed + packageFromProps (properties); + + // Now get package prefixes from command line (along with other args). + // This order has the effect of making command line packages + // supercede any idl.config file packages. + try + { + Vector unknownArgs = new Vector (); + + // Process command line parameters + for (int i = 0; i < args.length; ++i) + { + String lcArg = args[i].toLowerCase (); + + if (lcArg.charAt (0) != '-' && lcArg.charAt (0) != '/') + throw new InvalidArgument (args[i]); + lcArg = lcArg.substring (1); + + // Proxy options; default is -fclient. + if (lcArg.startsWith ("f")) + { + // If the command line had '-f client', make it '-fclient' + if (lcArg.equals ("f")) + lcArg = 'f' + args[++i].toLowerCase (); + + // Determine whether to emit bindings for client, server or both; and + // whether to emit delegate-style (TIE) rather than derived-style + // skeletons, which are the default. + + if (lcArg.equals ("fclient")) + { + emit = ((emit == Server || emit == All) ? All : Client); + } + else if (lcArg.equals ("fserver")) + { + emit = ((emit == Client || emit == All) ? All : Server); + TIEServer = false; + } + else if (lcArg.equals ("fall")) + { + emit = All; + TIEServer = false; + //Should be removed and incorporated in the clause below + // POAServer = true; + } + else if (lcArg.equals ("fservertie")) + { + emit = ((emit == Client || emit == All) ? All : Server); + TIEServer = true; + } + else if (lcArg.equals ("falltie")) + { + emit = All; + TIEServer = true; + } + else + i = collectUnknownArg (args, i, unknownArgs); + } + else if (lcArg.equals ("pkgtranslate")) + { + if (i + 2 >= args.length) + throw new InvalidArgument( args[i] ) ; + + String orig = args[++i] ; + String trans = args[++i] ; + checkPackageNameValid( orig ) ; + checkPackageNameValid( trans ) ; + if (orig.equals( "org" ) || orig.startsWith( "org.omg" )) + throw new InvalidArgument( args[i] ) ; + orig = orig.replace( '.', '/' ) ; + trans = trans.replace( '.', '/' ) ; + packageTranslation.put( orig, trans ) ; + } + // Package prefix + else if (lcArg.equals ("pkgprefix")) + { + if (i + 2 >= args.length) + throw new InvalidArgument (args[i]); + + String type = args[++i]; + String pkg = args[++i]; + checkPackageNameValid( type ) ; + checkPackageNameValid( pkg ) ; + packages.put (type, pkg); + } + // Target directory + else if (lcArg.equals ("td")) // + { + if (i + 1 >= args.length) + throw new InvalidArgument (args[i]); + String trgtDir = args[++i]; + if (trgtDir.charAt (0) == '-') + throw new InvalidArgument (args[i - 1]); + else + { + targetDir = trgtDir.replace ('/', File.separatorChar); + if (targetDir.charAt (targetDir.length () - 1) != File.separatorChar) + targetDir = targetDir + File.separatorChar; + } + } + // Separator + else if (lcArg.equals ("sep")) + { + if (i + 1 >= args.length) + throw new InvalidArgument (args[i]); + separator = args[++i]; + } + // POA flag ? + else if (lcArg.equals ("oldimplbase")){ + POAServer = false; + } + else if (lcArg.equals("skeletonname")){ + if (i + 1 >= args.length) + throw new InvalidArgument (args[i]); + skeletonPattern = args[++i]; + } + else if (lcArg.equals("tiename")){ + if (i + 1 >= args.length) + throw new InvalidArgument (args[i]); + tiePattern = args[++i]; + } + else if (lcArg.equals("localoptimization")) { + LocalOptimization = true; + } + else i = collectUnknownArg (args, i, unknownArgs); + } + + // Encountered unknown arguments? + if (unknownArgs.size () > 0) + { + String [] otherArgs = new String [unknownArgs.size ()]; + unknownArgs.copyInto (otherArgs); + // Throws InvalidArgument by default + super.parseOtherArgs (otherArgs, properties); + } + + setDefaultEmitter(); // d57482 + setNameModifiers( skeletonPattern, tiePattern ) ; + } + catch (ArrayIndexOutOfBoundsException e) + { + // If there is any array indexing problem, it is probably + // because the qualifier on the last argument is missing. + // Report that this last argument is invalid. + throw new InvalidArgument (args[args.length - 1]); + } + } // parseOtherArgs + + /** + * + **/ + protected int collectUnknownArg (String[] args, int i, Vector unknownArgs) + { + unknownArgs.addElement (args [i]); + ++i; + while (i < args.length && args[i].charAt (0) != '-' && args[i].charAt (0) != '/') + unknownArgs.addElement (args[i++]); + return --i; + } // collectUnknownArg + + /** + * + **/ + protected void packageFromProps (Properties props) throws InvalidArgument + { + Enumeration propsEnum = props.propertyNames (); + while (propsEnum.hasMoreElements ()) + { + String prop = (String)propsEnum.nextElement (); + if (prop.startsWith ("PkgPrefix.")) + { + String type = prop.substring (10); + String pkg = props.getProperty (prop); + checkPackageNameValid( pkg ) ; + checkPackageNameValid( type ) ; + packages.put (type, pkg); + } + } + } // packageFromProps + + /** + * d57482 (klr) method added so default emitter check could be overriden. + **/ + private void setDefaultEmitter() { + // If the flag -fclient was not found, assume it. + if (emit == None) emit = Client; + } + + private void setNameModifiers(String skeletonPattern, + String tiePattern) { + if (emit>Client) { + String tp ; + String sp ; + + if (skeletonPattern != null) + sp = skeletonPattern ; + else if (POAServer) + sp = "%POA" ; + else + sp = "_%ImplBase" ; + + if (tiePattern != null) + tp = tiePattern ; + else if (POAServer) + tp = "%POATie" ; + else + tp = "%_Tie" ; + + skeletonNameModifier = new NameModifierImpl( sp ) ; + tieNameModifier = new NameModifierImpl( tp ) ; + } + } + + /** + * + **/ + private void checkPackageNameValid (String name) throws InvalidArgument + { + if (name.charAt (0) == '.') + throw new InvalidArgument (name); + for (int i = 0; i < name.length ();++i) + if (name.charAt (i) == '.') + { + if (i == name.length () - 1 || !Character.isJavaIdentifierStart (name.charAt (++i))) + throw new InvalidArgument (name); + } + else if (!Character.isJavaIdentifierPart (name.charAt (i))) + throw new InvalidArgument (name); + } // validatePackageName + + // <46082.03><46838> Modified access restrictions from protected to public. + + // This is a hash table whose keys are top-level typenames and + // whose values are the package prefixes to those types. + // For instance, <"CORBA", "org.omg"> is a possible entry. + public Hashtable packages = new Hashtable (); + + public String separator = null; + + public static final int + None = 0, + Client = 1, + Server = 2, + All = 3; + public int emit = None; + public boolean TIEServer = false; + public boolean POAServer = true; + // By default we do not generate Locally Optimized stub because of an + // unresolved PI problem. We will generate only if -localOptimization flag + // is passed + public boolean LocalOptimization = false; + public com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier skeletonNameModifier = null ; + public com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier tieNameModifier = null ; + + // Key is original package name; value is translated package name. + // Note that this translation happens AFTER prefixes are added in the + // packages table. + public Hashtable packageTranslation = new Hashtable() ; + + public String targetDir = ""; // +} // class Arguments diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AttributeGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AttributeGen.java new file mode 100644 index 000000000..93e0cc513 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AttributeGen.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.AttributeEntry; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.ParameterEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +/** + * + **/ +public class AttributeGen extends MethodGen implements com.sun.tools.corba.ee.idl.AttributeGen +{ + /** + * Public zero-argument constructor. + **/ + public AttributeGen () + { + } // ctor + + /** + * + **/ + private boolean unique (InterfaceEntry entry, String name) + { + // Compare the name to the methods of this interface + Enumeration methods = entry.methods ().elements (); + while (methods.hasMoreElements ()) + { + SymtabEntry method = (SymtabEntry)methods.nextElement (); + if (name.equals (method.name ())) + return false; + } + + // Recursively call unique on each derivedFrom interface + Enumeration derivedFrom = entry.derivedFrom ().elements (); + while (derivedFrom.hasMoreElements ()) + if (!unique ((InterfaceEntry)derivedFrom.nextElement (), name)) + return false; + + // If the name isn't in any method, nor in any method of the + // derivedFrom interfaces, then the name is unique. + return true; + } // unique + + /** + * Method generate() is not used in MethodGen. They are replaced by the + * more granular interfaceMethod, stub, skeleton, dispatchSkeleton. + **/ + public void generate (Hashtable symbolTable, AttributeEntry m, PrintWriter stream) + { + } // generate + + /** + * + **/ + protected void interfaceMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + AttributeEntry a = (AttributeEntry)m; + + // Generate for the get method + super.interfaceMethod (symbolTable, a, stream); + + // Generate for the set method if the attribute is not readonly + if (!a.readOnly ()) + { + setupForSetMethod (); + super.interfaceMethod (symbolTable, a, stream); + clear (); + } + } // interfaceMethod + + /** + * + **/ + protected void stub (String className, boolean isAbstract, Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index) + { + AttributeEntry a = (AttributeEntry)m; + + // Generate for the get method + super.stub (className, isAbstract, symbolTable, a, stream, index); + + // Generate for the set method if the attribute is not readonly + if (!a.readOnly ()) + { + setupForSetMethod (); + super.stub (className, isAbstract, symbolTable, a, stream, index + 1); + clear (); + } + } // stub + + /** + * + **/ + protected void skeleton (Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index) + { + AttributeEntry a = (AttributeEntry)m; + + // Generate for the get method + super.skeleton (symbolTable, a, stream, index); + + // Generate for the set method if the attribute is not readonly + if (!a.readOnly ()) + { + setupForSetMethod (); + super.skeleton (symbolTable, a, stream, index + 1); + clear (); + } + } // skeleton + + /** + * + **/ + protected void dispatchSkeleton (Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index) + { + AttributeEntry a = (AttributeEntry)m; + + // Generate for the get method + super.dispatchSkeleton (symbolTable, a, stream, index); + + // Generate for the set method if the attribute is not readonly + if (!a.readOnly ()) + { + setupForSetMethod (); + super.dispatchSkeleton (symbolTable, m, stream, index + 1); + clear (); + } + } // dispatchSkeleton + + private SymtabEntry realType = null; + + /** + * + **/ + protected void setupForSetMethod () + { + ParameterEntry parm = com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factory.parameterEntry (); + parm.type (m.type ()); + parm.name ("new" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.capitalize(m.name())); + m.parameters ().addElement (parm); + realType = m.type (); + m.type (null); + } // setupForSetMethod + + /** + * + **/ + protected void clear () + { + // Set back to normal + m.parameters ().removeAllElements (); + m.type (realType); + } // clear +} // class AttributeGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AttributeGen24.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AttributeGen24.java new file mode 100644 index 000000000..3af399efb --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AttributeGen24.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 New file to implement CORBA 2.4 RTF +// REVISIT: These changes should be folded into AttributeGen. + +import com.sun.tools.corba.ee.idl.AttributeEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * + **/ +public class AttributeGen24 extends MethodGenClone24 +{ + /** + * Public zero-argument constructor. + **/ + public AttributeGen24 () + { + } // ctor + + /** + * (d62023-klr) Added for 2.4 RTF + **/ + protected void abstractMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + AttributeEntry a = (AttributeEntry)m; + + // Generate for the get method + super.abstractMethod (symbolTable, a, stream); + + // Generate for the set method if the attribute is not readonly + if (!a.readOnly ()) + { + setupForSetMethod (); + super.abstractMethod (symbolTable, a, stream); + clear (); + } + } // abstractMethod + + /** + * (d62023-klr) Added for 2.4 RTF + **/ + protected void interfaceMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + AttributeEntry a = (AttributeEntry)m; + + // Generate for the get method + super.interfaceMethod (symbolTable, a, stream); + + // Generate for the set method if the attribute is not readonly + if (!a.readOnly ()) + { + setupForSetMethod (); + super.interfaceMethod (symbolTable, a, stream); + clear (); + } + } // interfaceMethod + +} // class AttributeGen24 diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AuxGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AuxGen.java new file mode 100644 index 000000000..e5e7f0ead --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/AuxGen.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import com.sun.tools.corba.ee.idl.SymtabEntry; + +/** + * + **/ +public interface AuxGen +{ + void generate (java.util.Hashtable symbolTable, SymtabEntry entry); +} // interface AuxGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Compile.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Compile.java new file mode 100644 index 000000000..2514a89a9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Compile.java @@ -0,0 +1,382 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -09/23/98 KLR Ported -m updates (F46838.1-3) +// -f46082.51 Transferred makefile list generation (for ODE delta-builds, +// see f46838) to toJava; cleaned-out dead code. +// -D58319 Display version info. for -version option. +// -D58951 Modify to allow QuickTest to build. +// -D49526 Remove "TypeCode" symbol from preParse(). +// -D58591 Publicise _factories and compile for QuickTest. Need to revert +// t0 private and add accessor methods. +// -D59437 Fill typename information for value boxes. + +import com.sun.tools.corba.ee.idl.*; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * Compiler usage: + *

+ * + * java Compile [options] <idl file> + *

+ * + * where <idl file> is the name of a file containing IDL definitions, + * and [options] is any combination of the options listed below. The options + * may appear in any order. + *

+ * + * Options: + *
+ *
-i <include path> + *
By default, the current directory is scanned for included files. + * This option adds another directory. See also the note below. + * + *
-d <symbol> + *
This is equivalent to the following line in an IDL file: + * #define <symbol> + * + *
-f<side> + *
Defines what bindings to emit. <side> is one of client, server, all, + * serverTIE, allTIE. serverTIE and allTIE cause delegate model skeletons + * to be emitted. If this flag is not used, -fclient is assumed. + * allPOA has the same effect as all, except for generation POA type skeletons. + * + *
-keep + *
If a file to be generated already exists, do not overwrite it. By + * default it is overwritten. + * + *
-sep <string> + *
Only valid with -m. Replace the file separator character with + * <string> in the file names listed in the .u file. + * + *
-emitAll + *
Emit all types, including those found in #included files. + * + *
-v + *
Verbose mode. + * + *
-pkgPrefix <type> <package> + *
Whereever <type> is encountered, make sure it resides within + * <package> in all generated files. <type> is a fully + * qualified, java-style name. + *
+ * + * Note: If you have an include path or paths that you will always + * be using, it can get tedious putting these on the command with the -i + * option all the time. Instead, these can be placed into a config file + * called idl.config. This file must be in the CLASSPATH. The format of + * the includes line is: + * + *
+ * includes=<path1>;<path2>;...;<pathN>
+ * 
+ * + * Note that the path separator character, here shown as a semicolon, + * is machine dependent. For instance, on Windows 95 this character + * is a semicolon, on UNIX it is a colon. + **/ +public class Compile extends com.sun.tools.corba.ee.idl.Compile +{ + /** + * + **/ + public static void main (String[] args) + { + compiler = new Compile (); + compiler.start (args); + } // main + + /** + * + **/ + public void start (String[] args) + { + try + { + // Use generator-specific messages file. + //Util.registerMessageFile ("com/sun/corba/ee/idl/toJavaPortable/toJava.prp"); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.registerMessageResource("com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable"); + init (args); + if (arguments.versionRequest) + displayVersion (); + else + { + preParse (); + Enumeration e = parse (); + if (e != null) + { + preEmit (e); + generate (); + // Move ODE delta-build support to toJava + //if (((Arguments)arguments).genMakefileLists) + // generateMakefileLists (); + } + } + } + catch (InvalidArgument | IOException e) + { + System.err.println (e); + } + } // start + + /** + * + **/ + protected Compile () + { + factory = factories ().symtabFactory (); + } // ctor + + // _factories was made public for QuickTest to operate correctly, + // but the code needs to be changed to this: + //private Factories _factories = null; + //protected Factories factories () + //{ + // if (_factories == null) + // _factories = new Factories (); + // return _factories; + //} // factories + + private Factories _factories = new Factories(); // 58974 - changed for quicktest + protected com.sun.tools.corba.ee.idl.Factories factories () + { + return _factories; + } // factories + + + ModuleEntry org; + ModuleEntry omg; + ModuleEntry corba; + InterfaceEntry object; + + /** + * + **/ + private void preParse() + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.setSymbolTable(symbolTable); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.setPackageTranslation(((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) arguments).packageTranslation) ; + + // Need modules for the predefined objects + org = factory.moduleEntry (); + // Suppress generation of this module. If the parser reopens it + // while parsing the main IDL source, any definitions appearing in the module + // -- and not appearing in a global-scope include file -- will be added to + // the emit list with emit=true for eventual generation. + org.emit (false); + org.name ("org"); + org.container (null); + omg = factory.moduleEntry (); + omg.emit (false); // + omg.name ("omg"); + omg.module ("org"); + omg.container (org); + org.addContained (omg); + corba = factory.moduleEntry (); + corba.emit (false); // + corba.name ("CORBA"); + corba.module ("org/omg"); + corba.container (omg); + omg.addContained (corba); + symbolTable.put ("org", org); + symbolTable.put ("org/omg", omg); + symbolTable.put ("org/omg/CORBA", corba); + + // Add CORBA::Object to symbol table. + object = (InterfaceEntry)symbolTable.get ("Object"); + object.module ("org/omg/CORBA"); + object.container (corba); + symbolTable.put ("org/omg/CORBA/Object", object); + + // Add PIDL type (primitive) CORBA::TypeCode to symbol table. + PrimitiveEntry pEntry = factory.primitiveEntry (); + pEntry.name ("TypeCode"); + pEntry.module ("org/omg/CORBA"); + pEntry.container (corba); + symbolTable.put ("org/omg/CORBA/TypeCode", pEntry); + symbolTable.put ("CORBA/TypeCode", pEntry); // + overrideNames.put ("CORBA/TypeCode", "org/omg/CORBA/TypeCode"); // + overrideNames.put ("org/omg/CORBA/TypeCode", "CORBA/TypeCode"); // + // Allow user to specify types named "TypeCode" + //symbolTable.put ("TypeCode", pEntry); + //overrideNames.put ("TypeCode", "org/omg/CORBA/TypeCode"); + + // CORBA::Principal is deprecated! + // Add PIDL type (primitive) CORBA::Principal to symbol table. + pEntry = factory.primitiveEntry (); + pEntry.name ("Principal"); + pEntry.module ("org/omg/CORBA"); + pEntry.container (corba); + symbolTable.put ("org/omg/CORBA/Principle", pEntry); + symbolTable.put ("CORBA/Principal", pEntry); + overrideNames.put ("CORBA/Principal", "org/omg/CORBA/Principal"); + overrideNames.put ("org/omg/CORBA/Principal", "CORBA/Principal"); + + // Add PIDL type (interface) CORBA::Current to symbol table. + //InterfaceEntry iEntry = factory.interfaceEntry (); + //iEntry.name ("Current"); + //iEntry.module ("org/omg/CORBA"); + //iEntry.container (corba); + //symbolTable.put ("org/omg/CORBA/Current", iEntry); + //symbolTable.put ("CORBA/Current", iEntry); + //overrideNames.put ("CORBA/Current", "org/omg/CORBA/Current"); + //overrideNames.put ("org/omg/CORBA/Current", "CORBA/Current"); + + overrideNames.put ("TRUE", "true"); + overrideNames.put ("FALSE", "false"); + //overrideNames.put ("any", "org/omg/CORBA/Any"); + + // Add CORBA module to symbol table + symbolTable.put ("CORBA", corba); // 55699 + overrideNames.put ("CORBA", "org/omg/CORBA"); // + overrideNames.put ("org/omg/CORBA", "CORBA"); // + } // preParse + + + protected void preEmit (Enumeration emitList) + { + typedefInfo = SymtabEntry.getVariableKey (); + Hashtable tempST = (Hashtable)symbolTable.clone (); + + for (Enumeration e = tempST.elements (); e.hasMoreElements ();) + { + SymtabEntry element = (SymtabEntry)e.nextElement (); + + // Any other symbolTable processing? + preEmitSTElement (element); + } + + // Do this processing AFTER any other processing to get the + // correct names. + Enumeration elements = symbolTable.elements (); + while (elements.hasMoreElements ()) + { + // Find all TypedefEntry's and fill in the SymtabEntry.info + // field with it's real type , including [][]... with const + // exprs. + SymtabEntry element = (SymtabEntry)elements.nextElement (); + if (element instanceof TypedefEntry || element instanceof SequenceEntry) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(element); + + // Members of constructed types may now be value boxes, and value + // boxes may contain types that are directly defined rather than typedef-ed + // (e.g., "valuetype vb sequence ;"). If member resolves to a value + // box, then check and fillInfo() for value box and its content type BEFORE + // doing fillInfo() on member; otherwise, could get an exception. There's + // code in fillInfo() that performs this check, so it does not appear here. + + else if (element instanceof StructEntry) + { + Enumeration members = ((StructEntry)element).members ().elements (); + while (members.hasMoreElements ()) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo((SymtabEntry) members.nextElement()); + } + else if (element instanceof InterfaceEntry && ((InterfaceEntry)element).state () != null) + { + Enumeration members = ((InterfaceEntry)element).state ().elements (); + while (members.hasMoreElements ()) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(((InterfaceState) members.nextElement()).entry); + } + else if (element instanceof UnionEntry) + { + Enumeration branches = ((UnionEntry)element).branches ().elements (); + while (branches.hasMoreElements ()) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(((UnionBranch) branches.nextElement()).typedef); + } + + // For each type that is at the top level that is NOT a module + // or IncludeEntry, add it to the imports list. If there are + // types within modules which refer to these, their types must + // be explicitly stated in an import statement. + if (element.module ().equals ("") && !(element instanceof ModuleEntry || element instanceof IncludeEntry || element instanceof PrimitiveEntry)) + importTypes.addElement (element); + } + + while (emitList.hasMoreElements ()) + { + SymtabEntry entry = (SymtabEntry)emitList.nextElement (); + + // Any other emitList processing: + preEmitELElement (entry); + } + } // preEmit + + /** + * This method is called by preEmit once for each symbol table entry. + * It can be called by extenders. + **/ + protected void preEmitSTElement (SymtabEntry entry) + { + // If the -package argument was used, search the packages list + // for the given type name and prepend the package to it. + Hashtable packages = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments)arguments).packages; + if (packages.size () > 0) + { + String substr = (String)packages.get (entry.fullName ()); + if (substr != null) + { + String pkg = null; + ModuleEntry mod = null; + ModuleEntry prev = null; + while (substr != null) + { + int dot = substr.indexOf ('.'); + if (dot < 0) + { + pkg = substr; + substr = null; + } + else + { + pkg = substr.substring (0, dot); + substr = substr.substring (dot + 1); + } + + String fullName = prev == null ? pkg : prev.fullName () + '/' + pkg; + mod = (ModuleEntry)symbolTable.get (fullName); + if (mod == null) + { + mod = factory.moduleEntry (); + mod.name (pkg); + mod.container (prev); + if (prev != null) mod.module (prev.fullName ()); + symbolTable.put (pkg, mod); + } + prev = mod; + } + entry.module (mod.fullName ()); + entry.container (mod); + } + } + } // preEmitSTElement + + /** + * This method is called by preEmit once for each emitList entry. + * It can be called by extenders. + **/ + protected void preEmitELElement (SymtabEntry entry) + { + } // preEmitELElement + + public Vector importTypes = new Vector (); + public SymtabFactory factory; + public static int typedefInfo; + public Hashtable list = new Hashtable (); + public static Compile compiler = null; // +} // class Compile diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ConstGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ConstGen.java new file mode 100644 index 000000000..595603ea2 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ConstGen.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.ConstEntry; +import com.sun.tools.corba.ee.idl.ModuleEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; + +/** + * + **/ +public class ConstGen implements com.sun.tools.corba.ee.idl.ConstGen +{ + /** + * Public zero-argument constructor. + **/ + public ConstGen () + { + } // ctor + + /** + * Generate Java code for an IDL constant. A constant is written to + * a new class only when it is not a member of an interface; otherwise + * it written to the interface class in which it resides. + **/ + public void generate (Hashtable symbolTable, ConstEntry c, PrintWriter s) + { + this.symbolTable = symbolTable; + this.c = c; + this.stream = s; + init (); + + if (c.container () instanceof ModuleEntry) + generateConst (); + else if (stream != null) + writeConstExpr (); + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + } // init + + /** + * Generate the class defining the constant. + **/ + protected void generateConst () + { + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generateConst + + /** + * Open a new print stream only if the constant is not a member + * of an interface. + **/ + protected void openStream () + { + stream = Util.stream(c, ".java"); + } // openStream + + /** + * Write the heading for the class defining the constant. + **/ + protected void writeHeading () + { + Util.writePackage(stream, c); + Util.writeProlog(stream, ((GenFileStream) stream).name()); + stream.println ("public interface " + c.name ()); + // should not be done according to the mapping + // + " extends org.omg.CORBA.portable.IDLEntity"); + stream.println ("{"); + } // writeHeading + + /** + * Write the constant expression and any comment, if present. + **/ + protected void writeBody () + { + writeConstExpr (); + } // writeBody + + /** + * Write the entire constant expression and any comment, if present. + **/ + protected void writeConstExpr () + { + if (c.comment () != null) + c.comment ().generate (" ", stream); + if (c.container () instanceof ModuleEntry) { + + stream.print (" public static final " + Util.javaName(c.type()) + " value = "); + } else { + stream.print (" public static final " + Util.javaName(c.type()) + ' ' + c.name () + " = "); + } + writeConstValue (c.type ()); + } // writeConstExpr + + /** + * Write the constant's value according to its type. + **/ + private void writeConstValue (SymtabEntry type) + { + if (type instanceof PrimitiveEntry) + stream.println ('(' + Util.javaName(type) + ")(" + Util.parseExpression(c.value()) + ");"); + else if (type instanceof StringEntry) + stream.println (Util.parseExpression(c.value()) + ';'); + else if (type instanceof TypedefEntry) + { + while (type instanceof TypedefEntry) + type = type.type (); + writeConstValue (type); + } + else + stream.println (Util.parseExpression(c.value()) + ';'); + } // writeValue + + /** + * Generate any last words and close the class. + **/ + protected void writeClosing () + { + stream.println ("}"); + } // writeClosing + + /** + * Close the print stream, causing the file to be written. + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + protected java.util.Hashtable symbolTable = null; + protected ConstEntry c = null; + protected PrintWriter stream = null; +} // class ConstGen + + +/*======================================================================================= + DATE-AUTHOR ACTION + --------------------------------------------------------------------------------------- + 11sep1997daz Return when print stream is null and container is NOT a module. Fixes + -keep option, which causes null print stream to be sent to ConstGen. + 31jul1997daz Write source comment immediately preceding constant declaration. + =======================================================================================*/ + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/DefaultFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/DefaultFactory.java new file mode 100644 index 000000000..3a3e3ee73 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/DefaultFactory.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 klr new class + +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +/** + * + **/ +public class DefaultFactory implements AuxGen +{ + /** + * Public zero-argument constructor. + **/ + public DefaultFactory () + { + } // ctor + + /** + * Generate the default value factory class. Provides general algorithm for + * auxiliary binding generation: + * 1.) Initialize symbol table and symbol table entry members, + * common to all generators. + * 2.) Initialize members unique to this generator. + * 3.) Open print stream + * 4.) Write class heading (package, prologue, source comment, class + * statement, open curly + * 5.) Write class body (member data and methods) + * 6.) Write class closing (close curly) + * 7.) Close the print stream + **/ + public void generate (java.util.Hashtable symbolTable, SymtabEntry entry) + { + this.symbolTable = symbolTable; + this.entry = entry; + init (); + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize variables unique to this generator. + **/ + protected void init () + { + factoryClass = entry.name () + "DefaultFactory"; + factoryInterface = entry.name () + "ValueFactory"; + factoryType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + implType = entry.name () + "Impl"; // default implementation class + } // init + + /** + * @return true if entry has any factory methods declared + **/ + protected boolean hasFactoryMethods () + { + Vector init = ((ValueEntry)entry).initializers (); + if (init != null && init.size () > 0) + return true; + else + return false; + } // hasFactoryMethods + + /** + * Open the print stream for subsequent output. + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(entry, "DefaultFactory.java"); + } // openStream + + /** + * Generate the heading, including the package, imports, + * source comment, class statement, and left curly. + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, entry, com.sun.tools.corba.ee.idl.toJavaPortable.Util.TypeFile); // REVISIT - same as interface? + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, stream.name()); + if (entry.comment () != null) + entry.comment ().generate ("", stream); + stream.print ("public class " + factoryClass + " implements "); + if (hasFactoryMethods ()) + stream.print (factoryInterface); + else + stream.print ("org.omg.CORBA.portable.ValueFactory"); + stream.println (" {"); + } // writeHeading + + /** + * Generate the contents of this class + **/ + protected void writeBody () + { + writeFactoryMethods (); + stream.println (); + writeReadValue (); + } // writeBody + + /** + * Generate members of this class. + **/ + protected void writeFactoryMethods () + { + Vector init = ((ValueEntry)entry).initializers (); + if (init != null) + { + for (int i = 0; i < init.size (); i++) + { + MethodEntry element = (MethodEntry) init.elementAt (i); + element.valueMethod (true); //tag value method if not tagged previously + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen24) element.generator ()).defaultFactoryMethod (symbolTable, element, stream); + } + } + } // writeFactoryMethods + + /** + * Generate default read_value + **/ + protected void writeReadValue () + { + stream.println (" public java.io.Serializable read_value (org.omg.CORBA_2_3.portable.InputStream is)"); + stream.println (" {"); + stream.println (" return is.read_value(new " + implType + " ());"); + stream.println (" }"); + } // writeReadValue + + /** + * Generate the closing statements. + **/ + protected void writeClosing () + { + stream.println ('}'); + } // writeClosing + + /** + * Write the stream to file by closing the print stream. + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + protected java.util.Hashtable symbolTable; + protected SymtabEntry entry; + protected GenFileStream stream; + + // Unique to this generator + protected String factoryClass; + protected String factoryInterface; + protected String factoryType; + protected String implType; +} // class Holder diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/EnumGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/EnumGen.java new file mode 100644 index 000000000..e88ebc500 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/EnumGen.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D61056 Use Util.helperName + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.EnumEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +/** + * + **/ +public class EnumGen implements com.sun.tools.corba.ee.idl.EnumGen, JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public EnumGen () + { + } // ctor + + /** + * Generate the Java code for an IDL enumeration. + **/ + public void generate (Hashtable symbolTable, EnumEntry e, PrintWriter s) + { + this.symbolTable = symbolTable; + this.e = e; + init (); + + openStream (); + if (stream == null) return; + generateHolder (); + generateHelper (); + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + className = e.name (); + fullClassName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(e); + } + + /** + * Open the print stream to which to write the enumeration class. + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(e, ".java"); + } + + /** + * Generate the holder class for this enumeration. + **/ + protected void generateHolder () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, e); + } + + /** + * Generate the helper class for this enumeration. + **/ + protected void generateHelper () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, e); + } + + /** + * Write the heading of the enumeration class, including the package, + * imports, class statement, and open curly. + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, e); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + if (e.comment () != null) + e.comment ().generate ("", stream); + stream.println ("public class " + className + " implements org.omg.CORBA.portable.IDLEntity"); + stream.println ("{"); + } + + /** + * Write the members of enumeration class. + **/ + protected void writeBody () + { + stream.println (" private int __value;"); + stream.println (" private static int __size = " + (e.elements ().size ()) + ';'); + stream.println (" private static " + fullClassName + "[] __array = new " + fullClassName + " [__size];"); + stream.println (); + for (int i = 0; i < e.elements ().size (); ++i) + { + String label = (String)e.elements ().elementAt (i); + stream.println (" public static final int _" + label + " = " + i + ';'); + stream.println (" public static final " + fullClassName + ' ' + label + " = new " + fullClassName + "(_" + label + ");"); + } + stream.println (); + writeValue (); + writeFromInt (); + writeCtors (); + } + + /** + * Write the value method for the enumeration class. + **/ + protected void writeValue () + { + stream.println (" public int value ()"); + stream.println (" {"); + stream.println (" return __value;"); + stream.println (" }"); + stream.println (); + } // writeValue + + /** + * Write the from_int method for the enumeration class. + **/ + protected void writeFromInt () + { + stream.println (" public static " + fullClassName + " from_int (int value)"); + stream.println (" {"); + stream.println (" if (value >= 0 && value < __size)"); + stream.println (" return __array[value];"); + stream.println (" else"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" }"); + stream.println (); + } + + /** + * Write the protected constructor for the enumeration class. + **/ + protected void writeCtors () + { + stream.println (" protected " + className + " (int value)"); + stream.println (" {"); + stream.println (" __value = value;"); + stream.println (" __array[__value] = this;"); + stream.println (" }"); + } + + /** + * Close the enumeration class. + **/ + protected void writeClosing () + { + stream.println ("} // class " + className); + } + + /** + * Close the print stream, which writes the stream to file. + **/ + protected void closeStream () + { + stream.close (); + } + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + tcoffsets.set (entry); + EnumEntry enumEntry = (EnumEntry)entry; + StringBuffer emit = new StringBuffer ("new String[] { "); + Enumeration e = enumEntry.elements ().elements (); + boolean firstTime = true; + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + emit.append (", "); + emit.append ('"' + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores((String) e.nextElement()) + '"'); + } + emit.append ("} "); + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_enum_tc (" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(enumEntry, true) + ".id (), \"" // <54697> // +// + "_id, \"" <54697> + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(entry.name()) + "\", " + + new String (emit) + ");"); + return index + 1; + + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); // + return index; + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + stream.println (" return " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(entry) + ".from_int (istream.read_long ());"); + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + stream.println (" ostream.write_long (value.value ());"); + } // helperWrite + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(entry) + ".from_int (istream.read_long ());"); + return index; + } // read + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + stream.println (indent + "ostream.write_long (" + name + ".value ());"); + return index; + } // write + + // From JavaGenerator + /////////////// + + protected Hashtable symbolTable = null; + protected EnumEntry e = null; + protected PrintWriter stream = null; + + // Member data unique to this generator + String className = null; + String fullClassName = null; +} // class EnumGen + + +/*============================================================================ + DATE ACTION + ---------------------------------------------------------------------------- + 31jul1997 Modified to write comment immediately preceding class defining + enumeration declaration. + 12dec1998 D55971 - omg 98-11-03 Java 2.4 RTF - make subclassable + ===========================================================================*/ + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ExceptionGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ExceptionGen.java new file mode 100644 index 000000000..9a496dbb1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ExceptionGen.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.ExceptionEntry; + +/** + * + **/ +public class ExceptionGen extends StructGen implements com.sun.tools.corba.ee.idl.ExceptionGen +{ + /** + * Public zero-argument constructor. + **/ + public ExceptionGen () + { + super (true); + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, ExceptionEntry entry, PrintWriter stream) + { + super.generate (symbolTable, entry, stream); + } // generate +} // class ExceptionGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Factories.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Factories.java new file mode 100644 index 000000000..e20f148ef --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Factories.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 Add corbaLevel=2.4 + +/** + * + **/ +public class Factories extends com.sun.tools.corba.ee.idl.Factories +{ + public com.sun.tools.corba.ee.idl.GenFactory genFactory () + { + return new GenFactory(); + } // genFactory + + public com.sun.tools.corba.ee.idl.Arguments arguments () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.Arguments(); + } // arguments + + public String[] languageKeywords () + { + // These are Java keywords that are not also IDL keywords. + return keywords; + } // languageKeywords + + static String[] keywords = + {"abstract", "break", "byte", + "catch", "class", "continue", + "do", "else", "extends", + "false", "final", "finally", + "for", "goto", "if", + "implements", "import", "instanceof", + "int", "interface", "native", + "new", "null", "operator", + "outer", "package", "private", + "protected", "public", "return", + "static", "super", "synchronized", + "this", "throw", "throws", + "transient", "true", "try", + "volatile", "while", +// Special reserved suffixes: + "+Helper", "+Holder", "+Package", +// These following are not strictly keywords. They +// are methods on java.lang.Object and, as such, must +// not have conflicts with methods defined on IDL +// interfaces. Treat them the same as keywords. + "clone", "equals", "finalize", + "getClass", "hashCode", "notify", + "notifyAll", "toString", "wait"}; + + /////////////// + // toJava-specific factory methods + + private com.sun.tools.corba.ee.idl.toJavaPortable.Helper _helper = null; // <62023> + public com.sun.tools.corba.ee.idl.toJavaPortable.Helper helper () + { + if (_helper == null) + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + _helper = new com.sun.tools.corba.ee.idl.toJavaPortable.Helper24(); // + else + _helper = new com.sun.tools.corba.ee.idl.toJavaPortable.Helper(); + return _helper; + } // helper + + private com.sun.tools.corba.ee.idl.toJavaPortable.ValueFactory _valueFactory = null; // <62023> + public com.sun.tools.corba.ee.idl.toJavaPortable.ValueFactory valueFactory () + { + if (_valueFactory == null) + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + _valueFactory = new com.sun.tools.corba.ee.idl.toJavaPortable.ValueFactory(); // + // else return null since shouldn't be used + return _valueFactory; + } // valueFactory + + private com.sun.tools.corba.ee.idl.toJavaPortable.DefaultFactory _defaultFactory = null; // <62023> + public com.sun.tools.corba.ee.idl.toJavaPortable.DefaultFactory defaultFactory () + { + if (_defaultFactory == null) + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + _defaultFactory = new com.sun.tools.corba.ee.idl.toJavaPortable.DefaultFactory(); // + // else return null since shouldn't be used + return _defaultFactory; + } // defaultFactory + + private com.sun.tools.corba.ee.idl.toJavaPortable.Holder _holder = new com.sun.tools.corba.ee.idl.toJavaPortable.Holder(); + public com.sun.tools.corba.ee.idl.toJavaPortable.Holder holder () + { + return _holder; + } // holder + + private com.sun.tools.corba.ee.idl.toJavaPortable.Skeleton _skeleton = new com.sun.tools.corba.ee.idl.toJavaPortable.Skeleton(); + public com.sun.tools.corba.ee.idl.toJavaPortable.Skeleton skeleton () + { + return _skeleton; + } // skeleton + + private com.sun.tools.corba.ee.idl.toJavaPortable.Stub _stub = new com.sun.tools.corba.ee.idl.toJavaPortable.Stub(); + public com.sun.tools.corba.ee.idl.toJavaPortable.Stub stub () + { + return _stub; + } // stub + + // toJava-specific factory methods + /////////////// +} // class Factories diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ForwardValueGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ForwardValueGen.java new file mode 100644 index 000000000..c30e85193 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ForwardValueGen.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D61056 Use Util.helperName + +import java.io.PrintWriter; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.ForwardValueEntry; + +/** + * + **/ +public class ForwardValueGen implements com.sun.tools.corba.ee.idl.ForwardValueGen, JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public ForwardValueGen () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, ForwardValueEntry v, PrintWriter str) + { + this.symbolTable = symbolTable; + this.v = v; + + openStream (); + if (stream == null) + return; + generateHelper (); + generateHolder (); + generateStub (); + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(v, ".java"); + } // openStream + + /** + * + **/ + protected void generateHelper () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, v); + } // generateHelper + + /** + * + **/ + protected void generateHolder () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, v); + } // generateHolder + + /** + * + **/ + protected void generateStub () + { + } // generateStub + + /** + * + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, v); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + if (v.comment () != null) + v.comment ().generate ("", stream); + + stream.print ("public class " + v.name () + " implements org.omg.CORBA.portable.IDLEntity"); + // There should ALWAYS be at least one: ValueBase + + stream.println ("{"); + } // writeHeading + + /** + * + **/ + protected void writeBody () + { + } // writeBody + + /** + * + **/ + protected void writeClosing () + { + stream.println ("} // class " + v.name ()); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); // + return index; + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + stream.println (" " + entryName + " value = new " + entryName + " ();"); + read (0, " ", "value", entry, stream); + stream.println (" return value;"); + } // helperRead + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + return index; + } // read + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + write (0, " ", "value", entry, stream); + } // helperWrite + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + return index; + } // write + + // From JavaGenerator + /////////////// + + /** + * + **/ + protected void writeAbstract () + { + } // writeAbstract + + protected Hashtable symbolTable = null; + protected ForwardValueEntry v = null; + protected PrintWriter stream = null; +} // class ForwardValueGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/GenFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/GenFactory.java new file mode 100644 index 000000000..d5091b515 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/GenFactory.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import com.sun.tools.corba.ee.idl.*; + +/** + * + **/ +public class GenFactory implements com.sun.tools.corba.ee.idl.GenFactory +{ + + public com.sun.tools.corba.ee.idl.AttributeGen createAttributeGen () + { + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + return new AttributeGen24(); + else + return new com.sun.tools.corba.ee.idl.toJavaPortable.AttributeGen(); + } // createAttributeGen + + public com.sun.tools.corba.ee.idl.ConstGen createConstGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.ConstGen(); + } // createConstGen + + public com.sun.tools.corba.ee.idl.NativeGen createNativeGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.NativeGen(); + } // createNativeGen + + public com.sun.tools.corba.ee.idl.EnumGen createEnumGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.EnumGen(); + } // createEnumGen + + public com.sun.tools.corba.ee.idl.ExceptionGen createExceptionGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.ExceptionGen(); + } // createExceptionGen + + public ForwardGen createForwardGen () + { + return null; + } // createForwardGen + + public com.sun.tools.corba.ee.idl.ForwardValueGen createForwardValueGen () + { + return null; + } // createForwardValueGen + + public IncludeGen createIncludeGen () + { + return null; + } // createIncludeGen + + public com.sun.tools.corba.ee.idl.InterfaceGen createInterfaceGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.InterfaceGen(); + } // createInterfaceGen + + public com.sun.tools.corba.ee.idl.ValueGen createValueGen () + { + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + return new com.sun.tools.corba.ee.idl.toJavaPortable.ValueGen24(); + else + return new com.sun.tools.corba.ee.idl.toJavaPortable.ValueGen(); + } // createValueGen + + public com.sun.tools.corba.ee.idl.ValueBoxGen createValueBoxGen () + { + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + return new com.sun.tools.corba.ee.idl.toJavaPortable.ValueBoxGen24(); + else + return new com.sun.tools.corba.ee.idl.toJavaPortable.ValueBoxGen(); + } // createValueBoxGen + + public com.sun.tools.corba.ee.idl.MethodGen createMethodGen () + { + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + return new com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen24(); + else + return new com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen(); + } // createMethodGen + + public com.sun.tools.corba.ee.idl.ModuleGen createModuleGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.ModuleGen(); + } // createModuleGen + + public ParameterGen createParameterGen () + { + return null; + } // createParameterGen + + public PragmaGen createPragmaGen () + { + return null; + } // createPragmaGen + + public com.sun.tools.corba.ee.idl.PrimitiveGen createPrimitiveGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.PrimitiveGen(); + } // createPrimitiveGen + + public com.sun.tools.corba.ee.idl.SequenceGen createSequenceGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.SequenceGen(); + } // createSequenceGen + + public com.sun.tools.corba.ee.idl.StringGen createStringGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.StringGen(); + } // createSequenceGen + + public com.sun.tools.corba.ee.idl.StructGen createStructGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.StructGen(); + } // createStructGen + + public com.sun.tools.corba.ee.idl.TypedefGen createTypedefGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.TypedefGen(); + } // createTypedefGen + + public com.sun.tools.corba.ee.idl.UnionGen createUnionGen () + { + return new com.sun.tools.corba.ee.idl.toJavaPortable.UnionGen(); + } // createUnionGen +} // class GenFactory diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Helper.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Helper.java new file mode 100644 index 000000000..cc4159635 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Helper.java @@ -0,0 +1,668 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -F46082.51 Remove -stateful feature. +// -D57118 Fix "narrow" in helper for abstract interface +// -D58889 re-Fix "narrow" in helper for abstract interface +// -D59383 'get_class' in value helper returns value class, not helper. +// -D59413 Remove Helper interface references for non-value types. +// -D59435 Remove read_Object, write_Object completely. +// -D59418 Move read_Value, write_Value to generator's helperRead. + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.StructEntry; + +/** + * + **/ +public class Helper implements AuxGen +{ + /** + * Public zero-argument constructor. + **/ + public Helper () + { + } // ctor + + /** + * Generate the helper class. Provides general algorithm + * for auxiliary binding generation: + * + * 1.) Initialize symbol table and symbol table entry members, + * common to all generators. + * 2.) Initialize members unique to this generator. + * 3.) Open print stream + * 4.) Write class heading: package, prologue, class statement, open curly + * 5.) Write class body: member data and methods + * 6.) Write class closing: close curly + * 7.) Close the print stream + **/ + public void generate (java.util.Hashtable symbolTable, SymtabEntry entry) + { + this.symbolTable = symbolTable; + this.entry = entry; + init (); + + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize variables unique to this generator. + **/ + protected void init () + { + helperClass = entry.name () + "Helper"; + if (entry instanceof ValueBoxEntry) + { + ValueBoxEntry v = (ValueBoxEntry) entry; + TypedefEntry member = ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry) + helperType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + else + helperType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType); + } + else + helperType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + } // init + + /** + * Open the print stream for subsequent output. + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(entry, "Helper.java"); + } // openStream + + /** + * Generate the heading, including package, imports, class statements, + * and open curly. + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, entry, com.sun.tools.corba.ee.idl.toJavaPortable.Util.HelperFile); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, stream.name()); + + // Transfer comment to target <30jul1997daz>. + if (entry.comment () != null) + entry.comment ().generate ("", stream); + + stream.print ("public final class " + helperClass); + if (entry instanceof ValueEntry) + stream.println (" implements org.omg.CORBA.portable.ValueHelper"); + else + stream.println (); + stream.println ('{'); + } + + /** + * Generate members of this class. + **/ + protected void writeBody () + { + writeInstVars (); + writeCtors (); + writeInsert (); + writeExtract (); + writeType (); + writeID (); + writeRead (); + writeWrite (); + if (entry instanceof InterfaceEntry && !(entry instanceof ValueEntry)) { + writeNarrow (); + writeUncheckedNarrow (); + } + writeHelperInterface (); + if (entry instanceof ValueEntry) + writeValueHelperInterface (); + } // writeBody + + /** + * Generate members of the Helper interface. + **/ + protected void writeHelperInterface () + { + } // writeHelperInterface + + /** + * Generate members of the ValueHelper interface. + **/ + protected void writeValueHelperInterface () + { + writeGetID (); // moved for + writeGetType (); // moved for + writeGetInstance (); // not in ValueHelper interface + writeGetClass (); + writeGetSafeBaseIds (); + } // writeHelperInterface + + /** + * Generate the closing statements. + **/ + protected void writeClosing () + { + stream.println ('}'); + } + + /** + * Write the stream to file by closing the print stream. + **/ + protected void closeStream () + { + stream.close (); + } + + /** + * Generate the instance variables. + **/ + protected void writeInstVars () + { + stream.println (" private static String _id = \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscoresFromID(entry.repositoryID().ID()) + "\";"); + if (entry instanceof ValueEntry) + { + stream.println (); + stream.println (" private static " + helperClass + " helper = new " + helperClass + " ();"); + stream.println (); + stream.println (" private static String[] _truncatable_ids = {"); + stream.print (" _id"); + + // Any safe ValueEntry must have a concete value parent. + // The topmost parent cannot be safe since it doesn't have + // a concrete parent. + ValueEntry child = (ValueEntry) entry; + while (child.isSafe ()) + { + stream.println(","); + ValueEntry parent = (ValueEntry)child.derivedFrom ().elementAt (0); + stream.print(" \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscoresFromID(parent.repositoryID().ID()) + "\""); + child = parent; + } + stream.println(" };"); + } + stream.println (); + } // writeInstVars + + /** + * Generate the constructors. + **/ + protected void writeCtors () + { + stream.println (" public " + helperClass + "()"); + stream.println (" {"); + stream.println (" }"); + stream.println (); + } // writeCtors + + /** + * Generate the insert method. + **/ + protected void writeInsert () + { + stream.println (" public static void insert (org.omg.CORBA.Any a, " + helperType + " that)"); + stream.println (" {"); + stream.println (" org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();"); + stream.println (" a.type (type ());"); + stream.println (" write (out, that);"); + stream.println (" a.read_value (out.create_input_stream (), type ());"); + stream.println (" }"); + stream.println (); + } // writeInsert + + /** + * Generate the extract method. + **/ + protected void writeExtract () + { + stream.println (" public static " + helperType + " extract (org.omg.CORBA.Any a)"); + stream.println (" {"); + stream.println (" return read (a.create_input_stream ());"); + stream.println (" }"); + stream.println (); + } // writeExtract + + /** + * Generate the typecode variable and type method. + **/ + protected void writeType () + { + boolean canRecurse = entry instanceof ValueEntry + || entry instanceof ValueBoxEntry + || entry instanceof StructEntry; + stream.println (" private static org.omg.CORBA.TypeCode __typeCode = null;"); + if (canRecurse) + stream.println (" private static boolean __active = false;"); + stream.println (" synchronized public static org.omg.CORBA.TypeCode type ()"); + stream.println (" {"); + stream.println (" if (__typeCode == null)"); + stream.println (" {"); + if (canRecurse) { + stream.println (" synchronized (org.omg.CORBA.TypeCode.class)"); + stream.println (" {"); + stream.println (" if (__typeCode == null)"); + stream.println (" {"); + stream.println (" if (__active)"); + stream.println (" {"); + stream.println (" return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );"); + stream.println (" }"); + stream.println (" __active = true;"); + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.generator ()).helperType (0, " ", new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(), "__typeCode", entry, stream); + } + else + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.generator ()).helperType (0, " ", new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(), "__typeCode", entry, stream); + + // Generate body of type() method + + if (canRecurse) { + stream.println (" __active = false;"); + stream.println (" }"); + stream.println (" }"); + } + stream.println (" }"); + stream.println (" return __typeCode;"); + stream.println (" }"); + stream.println (); + } // writeType + + /** + * Generate the ID method. + **/ + protected void writeID () + { + stream.println (" public static String id ()"); + stream.println (" {"); + stream.println (" return _id;"); + stream.println (" }"); + stream.println (); + } // writeID + + /** + * Generate the read method. + **/ + protected void writeRead () + { + + boolean isLocalInterface = false; + + if (entry instanceof InterfaceEntry) { + InterfaceEntry ie = (InterfaceEntry) entry; + + // for #pragma sun_local or sun_localservant, or actual local + // local interface, set the flag by checking on both + isLocalInterface = ie.isLocal() | ie.isLocalServant(); + } + + stream.println (" public static " + helperType + " read (org.omg.CORBA.portable.InputStream istream)"); + stream.println (" {"); + if ( !isLocalInterface ) { // nonLocal Interface and other types + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.generator ()).helperRead (helperType, entry, stream); + } else { //Local interface should throw exception + stream.println (" throw new org.omg.CORBA.MARSHAL ();"); + } + stream.println (" }"); + stream.println (); + } // writeRead + + /** + * Generate the write method. + **/ + protected void writeWrite () + { + + boolean isLocalInterface = false; + + if (entry instanceof InterfaceEntry) { + InterfaceEntry ie = (InterfaceEntry) entry; + + // for #pragma sun_local or sun_localservant, or actual local + // local interface, set the flag by checking on both + isLocalInterface = ie.isLocal() | ie.isLocalServant(); + } + + stream.println (" public static void write (org.omg.CORBA.portable.OutputStream ostream, " + helperType + " value)"); + stream.println (" {"); + if ( !isLocalInterface ) { // nonLocal Interface and other types + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.generator ()).helperWrite (entry, stream); + } else { //Local interface should throw exception + stream.println (" throw new org.omg.CORBA.MARSHAL ();"); + } + stream.println (" }"); + stream.println (); + } // writeWrite + + + /** + * Generate the narrow method. + **/ + protected void writeNarrow () + { + writeRemoteNarrow (); + stream.println (); + } + + /** + * Write the narrow() method for a remotable object. + **/ + protected void writeRemoteNarrow () + { + InterfaceEntry ie = (InterfaceEntry) entry; + + // narrow for LocalObject interface + if (ie.isLocal ()) { + writeRemoteNarrowForLocal (false); + return; + } + + // narrow for Abstract interface + if (ie.isAbstract ()) { + writeRemoteNarrowForAbstract (false); + return; + } else { + // Determine if the non-abstract interface has any abstract parents + for (int i = 0; i < ie.derivedFrom ().size (); i++) { + SymtabEntry parent = (SymtabEntry) ie.derivedFrom ().elementAt (i); + if (((InterfaceEntry) parent).isAbstract ()) { + writeRemoteNarrowForAbstract (true); + break; + } + } + } + + stream.println (" public static " + helperType + " narrow (org.omg.CORBA.Object obj)"); + stream.println (" {"); + stream.println (" if (obj == null)"); + stream.println (" return null;"); + stream.println (" else if (obj instanceof " + helperType + ')'); + stream.println (" return (" + helperType + ")obj;"); + stream.println (" else if (!obj._is_a (id ()))"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" else"); + stream.println (" {"); + stream.println (" org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();"); + String stubNameofEntry = stubName ((InterfaceEntry)entry); + stream.println (" " + stubNameofEntry + " stub = new " + stubNameofEntry + " ();"); + stream.println (" stub._set_delegate(delegate);"); + stream.println (" return stub;"); + stream.println (" }"); + stream.println (" }"); + } // writeRemoteNarrow + + /** + * Write the narrow() method for local interface. + **/ + private void writeRemoteNarrowForLocal (boolean hasAbstractParent) + { + stream.println (" public static " + helperType + " narrow (org.omg.CORBA.Object obj)"); + stream.println (" {"); + stream.println (" if (obj == null)"); + stream.println (" return null;"); + stream.println (" else if (obj instanceof " + helperType + ')'); + stream.println (" return (" + helperType + ")obj;"); + stream.println (" else"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" }"); + } // writeRemoteNarrowForLocal + + /** + * Write the narrow() method for abstract interface. + **/ + private void writeRemoteNarrowForAbstract (boolean hasAbstractParent) + { + stream.print (" public static " + helperType + " narrow (java.lang.Object obj)"); + stream.println (" {"); + stream.println (" if (obj == null)"); + stream.println (" return null;"); + if (hasAbstractParent) + { + stream.println (" else if (obj instanceof org.omg.CORBA.Object)"); + stream.println (" return narrow ((org.omg.CORBA.Object) obj);"); + } + else + { + stream.println (" else if (obj instanceof " + helperType + ')'); + stream.println (" return (" + helperType + ")obj;"); + } + + // If hasAbstractParent is false, then THIS entry must be abstract. + // This method is also called in case THIS entry is not abstract, but + // there is an abstract parent. If this entry is not abstract, + // it can never narrow to a CORBA object reference. + if (!hasAbstractParent) { // + String stubNameofEntry = stubName ((InterfaceEntry)entry); + + stream.println (" else if ((obj instanceof org.omg.CORBA.portable.ObjectImpl) &&"); + stream.println (" (((org.omg.CORBA.Object)obj)._is_a (id ()))) {"); + stream.println (" org.omg.CORBA.portable.ObjectImpl impl = (org.omg.CORBA.portable.ObjectImpl)obj ;" ) ; + stream.println (" org.omg.CORBA.portable.Delegate delegate = impl._get_delegate() ;" ) ; + stream.println (" " + stubNameofEntry + " stub = new " + stubNameofEntry + " ();"); + stream.println (" stub._set_delegate(delegate);"); + stream.println (" return stub;" ) ; + stream.println (" }" ) ; + }; + // end + + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" }"); + stream.println (); + } // writeRemoteNarrowForAbstract + + + /** + * Generate the unchecked narrow method. + **/ + protected void writeUncheckedNarrow () + { + writeUncheckedRemoteNarrow (); + stream.println (); + } + + /** + * Write the unchecked narrow() method for a remotable object. + **/ + protected void writeUncheckedRemoteNarrow () + { + InterfaceEntry ie = (InterfaceEntry) entry; + + // unchecked narrow for LocalObject interface + if (ie.isLocal ()) { + writeRemoteUncheckedNarrowForLocal (false); + return; + } + + // unchecked narrow for Abstract interface + if (ie.isAbstract ()) { + writeRemoteUncheckedNarrowForAbstract (false); + return; + } else { + // Determine if the non-abstract interface has any abstract parents + for (int i = 0; i < ie.derivedFrom ().size (); i++) { + SymtabEntry parent = (SymtabEntry) ie.derivedFrom ().elementAt (i); + if (((InterfaceEntry) parent).isAbstract ()) { + writeRemoteUncheckedNarrowForAbstract (true); + break; + } + } + } + + stream.println (" public static " + helperType + " unchecked_narrow (org.omg.CORBA.Object obj)"); + stream.println (" {"); + stream.println (" if (obj == null)"); + stream.println (" return null;"); + stream.println (" else if (obj instanceof " + helperType + ')'); + stream.println (" return (" + helperType + ")obj;"); + stream.println (" else"); + stream.println (" {"); + stream.println (" org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();"); + String stubNameofEntry = stubName ((InterfaceEntry)entry); + stream.println (" " + stubNameofEntry + " stub = new " + stubNameofEntry + " ();"); + stream.println (" stub._set_delegate(delegate);"); + stream.println (" return stub;"); + stream.println (" }"); + stream.println (" }"); + } // writeUncheckedRemoteNarrow + + /** + * Write the unchecked narrow() method for local interface. + **/ + private void writeRemoteUncheckedNarrowForLocal (boolean hasAbstractParent) + { + stream.println (" public static " + helperType + " unchecked_narrow (org.omg.CORBA.Object obj)"); + stream.println (" {"); + stream.println (" if (obj == null)"); + stream.println (" return null;"); + stream.println (" else if (obj instanceof " + helperType + ')'); + stream.println (" return (" + helperType + ")obj;"); + stream.println (" else"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" }"); + } // writeRemoteUncheckedNarrowForLocal + + /** + * Write the unchecked narrow() method for abstract interface. + **/ + private void writeRemoteUncheckedNarrowForAbstract (boolean hasAbstractParent) + { + stream.print (" public static " + helperType + " unchecked_narrow (java.lang.Object obj)"); + stream.println (" {"); + stream.println (" if (obj == null)"); + stream.println (" return null;"); + if (hasAbstractParent) + { + stream.println (" else if (obj instanceof org.omg.CORBA.Object)"); + stream.println (" return unchecked_narrow ((org.omg.CORBA.Object) obj);"); + } + else + { + stream.println (" else if (obj instanceof " + helperType + ')'); + stream.println (" return (" + helperType + ")obj;"); + } + + if (!hasAbstractParent) { + String stubNameofEntry = stubName ((InterfaceEntry)entry); + + stream.println (" else if (obj instanceof org.omg.CORBA.portable.ObjectImpl) {"); + stream.println (" org.omg.CORBA.portable.ObjectImpl impl = (org.omg.CORBA.portable.ObjectImpl)obj ;" ) ; + stream.println (" org.omg.CORBA.portable.Delegate delegate = impl._get_delegate() ;" ) ; + stream.println (" " + stubNameofEntry + " stub = new " + stubNameofEntry + " ();"); + stream.println (" stub._set_delegate(delegate);"); + stream.println (" return stub;" ) ; + stream.println (" }" ) ; + }; + + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" }"); + stream.println (); + } // writeRemoteUncheckedNarrowForAbstract + + + /** + * Generate the GetID method. + **/ + protected void writeGetID () + { + if ( !com.sun.tools.corba.ee.idl.toJavaPortable.Util.IDLEntity(entry)) + return; + stream.println (" public String get_id ()"); + stream.println (" {"); + stream.println (" return _id;"); + stream.println (" }"); + stream.println (); + } // writeGetID + + /** + * Generate the GetType method. + **/ + protected void writeGetType () + { + if ( !com.sun.tools.corba.ee.idl.toJavaPortable.Util.IDLEntity(entry)) + return; + stream.println (" public org.omg.CORBA.TypeCode get_type ()"); + stream.println (" {"); + stream.println (" return type ();"); + stream.println (" }"); + stream.println (); + } // writeGetID + + /** + * Generate the get_class method. + **/ + protected void writeGetClass () + { + stream.println (" public Class get_class ()"); + stream.println (" {"); + stream.println (" return " + helperType + ".class;"); // + stream.println (" }"); + stream.println (); + } // writeGetClass + + /** + * Generate the get_instance method. + **/ + protected void writeGetInstance () + { + stream.println (" public static org.omg.CORBA.portable.ValueHelper get_instance ()"); + stream.println (" {"); + stream.println (" return helper;"); + stream.println (" }"); + stream.println (); + } // writeGetInstance + + /** + * Generate the GetSafeBaseIds method. + **/ + protected void writeGetSafeBaseIds () + { + stream.println (" public String[] get_truncatable_base_ids ()"); + stream.println (" {"); + stream.println (" return _truncatable_ids;"); + stream.println (" }"); + stream.println (); + } // writeGetSafeBaseIds + + /** + * Return the stub name for the interface entry. + **/ + protected String stubName (InterfaceEntry entry) + { + String name; + if (entry.container ().name ().equals ("")) + name = '_' + entry.name () + "Stub"; + else + { + name = com.sun.tools.corba.ee.idl.toJavaPortable.Util.containerFullName(entry.container()) + "._" + entry.name () + "Stub"; + } + return name.replace ('/', '.'); + } // stubName + + protected java.util.Hashtable symbolTable; + protected SymtabEntry entry; + protected GenFileStream stream; + + // Unique to this generator + protected String helperClass; + protected String helperType; +} // class Helper diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Helper24.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Helper24.java new file mode 100644 index 000000000..893a60769 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Helper24.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 New file to implement CORBA 2.4 RTF + +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +import java.util.Vector; + +/** + * + **/ +public class Helper24 extends Helper +{ + /** + * Public zero-argument constructor. + **/ + public Helper24 () + { + } // ctor + + /** + * Generate the heading, including package, imports, class statements, + * and open curly. + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, entry, com.sun.tools.corba.ee.idl.toJavaPortable.Util.HelperFile); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, stream.name()); + + // Transfer comment to target <30jul1997daz>. + if (entry.comment () != null) + entry.comment ().generate ("", stream); + + if (entry instanceof ValueBoxEntry) { + stream.print ("public final class " + helperClass); + stream.println (" implements org.omg.CORBA.portable.BoxedValueHelper"); + } + else + stream.println ("abstract public class " + helperClass); + stream.println ('{'); + } + + /** + * Generate the instance variables. + **/ + protected void writeInstVars () + { + stream.println (" private static String _id = \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscoresFromID(entry.repositoryID().ID()) + "\";"); + if (entry instanceof ValueEntry) + { + stream.println (); + if (entry instanceof ValueBoxEntry) { + stream.println (" private static " + helperClass + " _instance = new " + helperClass + " ();"); + stream.println (); + } + } + stream.println (); + } // writeInstVars + + protected void writeValueHelperInterface () + { + if (entry instanceof ValueBoxEntry) { + writeGetID (); + } else if (entry instanceof ValueEntry) { + writeHelperFactories (); + } + } // writeValueHelperInterface + + /** + * + **/ + protected void writeHelperFactories () + { + Vector init = ((ValueEntry)entry).initializers (); + if (init != null) + { + stream.println (); + for (int i = 0; i < init.size (); i++) + { + MethodEntry element = (MethodEntry) init.elementAt (i); + element.valueMethod (true); //tag value method if not tagged previously + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen24) element.generator ()). helperFactoryMethod (symbolTable, element, entry, stream); + } + } + } // writeHelperFactories + + protected void writeCtors () + { + if (entry instanceof ValueBoxEntry) { + stream.println (" public " + helperClass + "()"); + stream.println (" {"); + stream.println (" }"); + stream.println (); + } + } // writeCtors +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Holder.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Holder.java new file mode 100644 index 000000000..28a95a0c5 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Holder.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D61056 Use Util.helperName + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; + +/** + * + **/ +public class Holder implements AuxGen +{ + /** + * Public zero-argument constructor. + **/ + public Holder () + { + } // ctor + + /** + * Generate the holder class. Provides general algorithm for + * auxiliary binding generation: + * 1.) Initialize symbol table and symbol table entry members, + * common to all generators. + * 2.) Initialize members unique to this generator. + * 3.) Open print stream + * 4.) Write class heading (package, prologue, source comment, class + * statement, open curly + * 5.) Write class body (member data and methods) + * 6.) Write class closing (close curly) + * 7.) Close the print stream + **/ + public void generate (java.util.Hashtable symbolTable, SymtabEntry entry) + { + this.symbolTable = symbolTable; + this.entry = entry; + init (); + + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize variables unique to this generator. + **/ + protected void init () + { + holderClass = entry.name () + "Holder"; + helperClass = com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true); // + if (entry instanceof ValueBoxEntry) + { + ValueBoxEntry v = (ValueBoxEntry) entry; + TypedefEntry member = ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + holderType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType); + } + else + holderType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + } // init + + /** + * Open the print stream for subsequent output. + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(entry, "Holder.java"); + } // openStream + + /** + * Generate the heading, including the package, imports, + * source comment, class statement, and left curly. + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, entry, com.sun.tools.corba.ee.idl.toJavaPortable.Util.HolderFile); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, stream.name()); + if (entry.comment () != null) + entry.comment ().generate ("", stream); + stream.println ("public final class " + holderClass + " implements org.omg.CORBA.portable.Streamable"); + stream.println ('{'); + } // writeHeading + + /** + * Generate members of this class. + **/ + protected void writeBody () + { + if (entry instanceof ValueBoxEntry) + stream.println (" public " + holderType + " value;"); + else + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(" public ", "value", "", entry, stream); + stream.println (); + writeCtors (); + writeRead (); + writeWrite (); + writeType (); + } // writeBody + + /** + * Generate the closing statements. + **/ + protected void writeClosing () + { + stream.println ('}'); + } // writeClosing + + /** + * Write the stream to file by closing the print stream. + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /** + * Generate the constructors. + **/ + protected void writeCtors () + { + stream.println (" public " + holderClass + " ()"); + stream.println (" {"); + stream.println (" }"); + stream.println (); + stream.println (" public " + holderClass + " (" + holderType + " initialValue)"); + stream.println (" {"); + stream.println (" value = initialValue;"); + stream.println (" }"); + stream.println (); + } // writeCtors + + /** + * Generate the _read method. + **/ + protected void writeRead () + { + stream.println (" public void _read (org.omg.CORBA.portable.InputStream i)"); + stream.println (" {"); + if (entry instanceof ValueBoxEntry) + { + TypedefEntry member = ((InterfaceState) ((ValueBoxEntry) entry).state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof StringEntry) + stream.println (" value = i.read_string ();"); + + else if (mType instanceof PrimitiveEntry) + stream.println (" value = " + helperClass + ".read (i).value;"); + + else + stream.println (" value = " + helperClass + ".read (i);"); + } + else + stream.println (" value = " + helperClass + ".read (i);"); + stream.println (" }"); + stream.println (); + } // writeRead + + /** + * Generate the _write method. + **/ + protected void writeWrite () + { + stream.println (" public void _write (org.omg.CORBA.portable.OutputStream o)"); + stream.println (" {"); + if (entry instanceof ValueBoxEntry) + { + TypedefEntry member = ((InterfaceState) ((ValueBoxEntry) entry).state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof StringEntry) + stream.println (" o.write_string (value);"); + + else if (mType instanceof PrimitiveEntry) + { + String name = entry.name (); + stream.println (" " + name + " vb = new " + name + " (value);"); + stream.println (" " + helperClass + ".write (o, vb);"); + } + + else + stream.println (" " + helperClass + ".write (o, value);"); + } + else + stream.println (" " + helperClass + ".write (o, value);"); + stream.println (" }"); + stream.println (); + } // writeWrite + + /** + * Generate the _type method. + **/ + protected void writeType () + { + stream.println (" public org.omg.CORBA.TypeCode _type ()"); + stream.println (" {"); + stream.println (" return " + helperClass + ".type ();"); + stream.println (" }"); + stream.println (); + } // writeType + + protected java.util.Hashtable symbolTable; + protected SymtabEntry entry; + protected GenFileStream stream; + + // Unique to this generator + protected String holderClass; + protected String helperClass; + protected String holderType; +} // class Holder diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/InterfaceGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/InterfaceGen.java new file mode 100644 index 000000000..192b238ba --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/InterfaceGen.java @@ -0,0 +1,832 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -The ctor should really throw an exception, but then it must have a +// throws clause. How much of a ripple effect is this? +// -F46082.51 Remove -stateful feature. +// -D60929 Update for RTF2.4 changes +// -D61056 Use Util.helperName +// -D62014 Move const definitions from signature to operations interf. +// -D62310 Fix declaration of interfaces extending abstract intf. +// -D62023 Move const definitions back from operations to signature. + +import com.sun.tools.corba.ee.idl.ConstEntry; +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +/** + * + **/ +public class InterfaceGen implements com.sun.tools.corba.ee.idl.InterfaceGen, JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public InterfaceGen () + { + //emit = ((Arguments)Compile.compiler.arguments).emit; + //factories = (Factories)Compile.compiler.factories (); + } // ctor + + /** + * Generate the interface and all the files associated with it. + * Provides general algorithm for binding generation: + * 1.) Initialize symbol table and symbol table entry members, common to all generators. + * 2.) Generate the skeleton if required by calling generateSkeletn () + * 3.) Generate the holder by calling generateHolder () + * 4.) Generate the helper by calling generateHelper () + * 5.) Generate the stub if required by calling generateStub () + * 6.) Generate the interface by calling generateInterface () + **/ + public void generate (Hashtable symbolTable, InterfaceEntry i, PrintWriter stream) + { + if (!isPseudo(i)) + { + this.symbolTable = symbolTable; + this.i = i; + init (); + + // for sun_local pragma, just generate the signature and operations interfaces + // for sun_localservant pragma, generate the Local Stubs, and Skel, should not + // have _invoke defined. + // for local (is_local()) case, generate only Helpers and Holder, where they + // have been modified to throw appropriate exceptions for read and write, and + // narrow is modified to not invoke _is_a + + if (! (i.isLocalSignature())) { + // generate the stubs and skeletons for non-local interfaces + if (! (i.isLocal())) { + // for local servant case just generate the skeleton, but + // for others generate the stubs also + generateSkeleton (); + + // _REVISIT_, Whenever there is time restructure the code to + // encapsulate stub and skeleton generation. + + // If the option is -fallTie then generate the Tie class first + // and then generate the ImplBase class to make the generation + // complete for the Hierarchy. + com.sun.tools.corba.ee.idl.toJavaPortable.Arguments theArguments = (com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments; + if( (theArguments.TIEServer == true ) + &&(theArguments.emit == theArguments.All ) ) + { + theArguments.TIEServer = false; + // Generate the ImplBase class + generateSkeleton (); + // Revert in case file contains multiple interfaces + theArguments.TIEServer = true; + } + generateStub (); + } + generateHolder (); + generateHelper (); + } + intfType = SIGNATURE; + generateInterface (); + intfType = OPERATIONS; + generateInterface (); + intfType = 0; + } + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + emit = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).emit; + factories = (com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories (); + } // init + + /** + * Generate a Skeleton when the user does not want just the client-side code. + **/ + protected void generateSkeleton () + { + // Remove -stateful feature. + // The Skeleton is generated only when the user doesn't want + // JUST the client code OR when the interface is stateful + //if (emit != Arguments.Client || i.state () != null) + // factories.skeleton ().generate (symbolTable, i); + if (emit != com.sun.tools.corba.ee.idl.toJavaPortable.Arguments.Client) + factories.skeleton ().generate (symbolTable, i); + } // generateSkeleton + + /** + * Generate a Stub when the user does not want just the server-side code. + **/ + protected void generateStub () + { + // According to Simon on 10/28/98, we should generate stubs for + // abstract interfaces too. + if (emit != com.sun.tools.corba.ee.idl.toJavaPortable.Arguments.Server /* && !i.isAbstract () */) + factories.stub ().generate (symbolTable, i); + } // generateStub + + /** + * Generate a Helper when the user does not want just the server-side code. + **/ + protected void generateHelper () + { + if (emit != com.sun.tools.corba.ee.idl.toJavaPortable.Arguments.Server) + factories.helper ().generate (symbolTable, i); + } // generateHelper + + /** + * Generate a Holder when the user does not want just the server-side code. + **/ + protected void generateHolder () + { + if (emit != com.sun.tools.corba.ee.idl.toJavaPortable.Arguments.Server) + factories.holder ().generate (symbolTable, i); + } // generateHolder + + /** + * Generate the interface. Provides general algorithm for binding generation: + * 1.) Initialize members unique to this generator. - init () + * 2.) Open print stream - openStream () + * 3.) Write class heading (package, prologue, class statement, open curly - writeHeading () + * 4.) Write class body (member data and methods) - write*Body () + * 5.) Write class closing (close curly) - writeClosing () + * 6.) Close the print stream - closeStream () + * + * For CORBA 2.3, interfaces are mapped to Operations and Signature + * interfaces. The Operations interface contains the method definitions. + * The Signature interface extends the Operations interface and adds + * CORBA::Object. + **/ + private void generateInterface() + { + init (); + openStream (); + if (stream == null) + return; + writeHeading (); + if (intfType == OPERATIONS) + writeOperationsBody (); + if (intfType == SIGNATURE) + writeSignatureBody (); + writeClosing (); + closeStream (); + } // generateInterface + + /** + * + **/ + protected void openStream () + { + if (i.isAbstract () || intfType == SIGNATURE) + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(i, ".java"); + else if (intfType == OPERATIONS) + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(i, "Operations.java"); + } // openStream + + /** + * + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, i, com.sun.tools.corba.ee.idl.toJavaPortable.Util.TypeFile); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + // Transfer interface comment to target <31jul1997>. + if (i.comment () != null) + i.comment ().generate ("", stream); + + String className = i.name (); +// if (((Arguments)Compile.compiler.arguments).TIEServer) +// { +// // For the delegate model, don't make interface a subclass of CORBA.Object +// stream.print ("public interface " + className); +// boolean firstTime = true; +// for (int ii = 0; ii < i.derivedFrom ().size (); ++ii) +// { +// SymtabEntry parent = (SymtabEntry)i.derivedFrom ().elementAt (ii); +// if (!parent.fullName ().equals ("org/omg/CORBA/Object")) +// { +// if (firstTime) +// { +// firstTime = false; +// stream.print (" extends "); +// } +// else +// stream.print (", "); +// stream.print (Util.javaName (parent)); +// } +// } +// if (i.derivedFrom ().size () > 0) +// stream.print (", "); +// stream.print ("org.omg.CORBA.portable.IDLEntity "); +// } +// +// else +// { + if (intfType == SIGNATURE) + writeSignatureHeading (); + else if (intfType == OPERATIONS) + writeOperationsHeading (); +// } + + stream.println (); + stream.println ('{'); + } // writeHeading + + /** + * + **/ + protected void writeSignatureHeading () + { + String className = i.name (); + stream.print ("public interface " + className + " extends " + className + "Operations, "); + boolean firstTime = true; + boolean hasNonAbstractParent = false; // + for (int k = 0; k < i.derivedFrom ().size (); ++k) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + InterfaceEntry parent = (InterfaceEntry)i.derivedFrom ().elementAt (k); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent)); + if (! parent.isAbstract ()) // + hasNonAbstractParent = true; // + } + // - begin + // If this interface extends only abstract interfaces, + // it should extend both org.omg.CORBA.Object and IDLEntity. + if (!hasNonAbstractParent) { + stream.print (", org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity "); + } + else { + // - end + // extends IDLEntity if there's only one default parent - CORBA.Object + if (i.derivedFrom ().size () == 1) + stream.print (", org.omg.CORBA.portable.IDLEntity "); + } + } // writeSignatureHeading + + /** + * + **/ + protected void writeOperationsHeading () + { + stream.print ("public interface " + i.name ()); + if ( !i.isAbstract ()) + stream.print ("Operations "); + else { + // - base abstract interfaces extend AbstractBase + // changed to IDLEntity by SCN per latest spec... + if (i.derivedFrom ().size () == 0) + stream.print (" extends org.omg.CORBA.portable.IDLEntity"); + } + + boolean firstTime = true; + for (int k = 0; k < i.derivedFrom ().size (); ++k) + { + InterfaceEntry parent = (InterfaceEntry) i.derivedFrom ().elementAt (k); + String parentName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent); + + // ignore the default parent - CORBA.Object + if (parentName.equals ("org.omg.CORBA.Object")) + continue; + + if (firstTime) + { + firstTime = false; + stream.print (" extends "); + } + else + stream.print (", "); + + // Don't append suffix Operations to the parents of abstract interface + // or to the abstract parents of regular interface + if (parent.isAbstract () || i.isAbstract ()) + stream.print (parentName); + else + stream.print (parentName + "Operations"); + } + } // writeOperationsHeading + + + /** + * + **/ + protected void writeOperationsBody () + { + // Generate everything but constants + Enumeration e = i.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry contained = (SymtabEntry)e.nextElement (); + if (contained instanceof MethodEntry) + { + MethodEntry element = (MethodEntry)contained; + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)element.generator ()).interfaceMethod (symbolTable, element, stream); + } + else + if ( !(contained instanceof ConstEntry)) + contained.generate (symbolTable, stream); + } + } // writeOperationsBody + + /** + * + **/ + protected void writeSignatureBody () + { + // Generate only constants + Enumeration e = i.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry contained = (SymtabEntry)e.nextElement (); + if (contained instanceof ConstEntry) + contained.generate (symbolTable, stream); + } + } // writeSignatureBody + + /** + * + **/ + protected void writeClosing () + { + String intfName = i.name (); + if ( !i.isAbstract () && intfType == OPERATIONS) + intfName = intfName + "Operations"; + stream.println ("} // interface " + intfName); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /////////////// + // From JavaGenerator + + // Remove -stateful feature. + /* + public int helperType (int index, String indent, TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.state () != null && i.state ().size () > 0) + index = structHelperType (index, indent, tcoffsets, name, entry, stream); + else + { + tcoffsets.set (entry); + if (entry.fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + name + + " = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_objref);"); + else + stream.println (indent + name + // <54697> + //+ " = org.omg.CORBA.ORB.init ().create_interface_tc (_id, " + + " = org.omg.CORBA.ORB.init ().create_interface_tc (" + Util.helperName (i, true) + ".id (), " // + + '\"' + Util.stripLeadingUnderscores (entry.name ()) + "\");"); + } + return index; + } // helperType + */ + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + tcoffsets.set (entry); + if (entry.fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + name + + " = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_objref);"); + else + stream.println (indent + name + // <54697> + //+ " = org.omg.CORBA.ORB.init ().create_interface_tc (_id, " + + " = org.omg.CORBA.ORB.init ().create_interface_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(i, true) + ".id (), " // + + '\"' + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(entry.name()) + "\");"); + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); // + return index; + } // type + + // Remove -stateful feature. + /* + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.state () != null) + structHelperRead (entryName, i, stream); + else + { + if (i.isAbstract ()) + stream.println (" return narrow (((org.omg.CORBA_2_3.portable.InputStream)istream).read_abstract_interface (_" + i.name () + "Stub.class));"); // + else + stream.println (" return narrow (istream.read_Object (_" + i.name () + "Stub.class));"); + } + } // helperRead + + */ + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.isAbstract ()) + stream.println (" return narrow (((org.omg.CORBA_2_3.portable.InputStream)istream).read_abstract_interface (_" + i.name () + "Stub.class));"); // + else + stream.println (" return narrow (istream.read_Object (_" + i.name () + "Stub.class));"); + } // helperRead + + // Remove -stateful feature. + /* + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.state () != null) + structHelperWrite (entry, stream); + else + write (0, " ", "value", entry, stream); + } // helperWrite + */ + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + write (0, " ", "value", entry, stream); + } // helperWrite + + // Remove -stateful feature. + /* + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.state () != null) + index = structRead (index, indent, name, i, stream); + else + { + if (entry.fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + name + " = istream.read_Object (_" + i.name () + "Stub.class);"); + else + stream.println (indent + name + " = " + Util.helperName (entry, false) + ".narrow (istream.read_Object (_" + i.name () + "Stub.class));"); // + } + return index; + } // read + */ + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (entry.fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + name + " = istream.read_Object (_" + i.name () + "Stub.class);"); + else + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, false) + ".narrow (istream.read_Object (_" + i.name () + "Stub.class));"); // + return index; + } // read + + // Remove -stateful feature. + /* + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.state () != null) + index = structWrite (index, indent, name, entry, stream); + else + { + if (i.isAbstract ()) + stream.println (indent + "((org.omg.CORBA_2_3.portable.OutputStream)ostream).write_abstract_interface ((java.lang.Object) " + name + ");"); // + else + stream.println (indent + "ostream.write_Object ((org.omg.CORBA.Object) " + name + ");"); + } + return index; + } // write + */ + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + InterfaceEntry i = (InterfaceEntry)entry; + if (i.isAbstract ()) + stream.println (indent + "((org.omg.CORBA_2_3.portable.OutputStream)ostream).write_abstract_interface ((java.lang.Object) " + name + ");"); // + else + stream.println (indent + "ostream.write_Object ((org.omg.CORBA.Object) " + name + ");"); + return index; + } // write + + // Remove -stateful feature. + /* + // These methods are cobbled from StructGen. Stateful interfaces + // are sent across the wire as if they were structs, with the first + // element being a string - the Java name of the class. + + public int structHelperType (int index, String indent, TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + TCOffsets innerOffsets = new TCOffsets (); + innerOffsets.set (entry); + int offsetForStruct = innerOffsets.currentOffset (); + InterfaceEntry i = (InterfaceEntry)entry; + String membersName = "_members" + index++; + Vector state = i.state (); + stream.println (indent + "org.omg.CORBA.StructMember[] " + membersName + " = new org.omg.CORBA.StructMember [" + (state.size () + 1) + "];"); + String tcOfMembers = "_tcOf" + membersName; + stream.println (indent + "org.omg.CORBA.TypeCode " + tcOfMembers + ';'); + + // The name string is the first element of the struct + String memberName = "_name"; + StringEntry stringEntry = Compile.compiler.factory.stringEntry (); + index = ((JavaGenerator)stringEntry.generator ()).helperType (index, indent, innerOffsets, tcOfMembers, stringEntry, stream); + stream.println (indent + membersName + "[0] = new org.omg.CORBA.StructMember ("); + stream.println (indent + " \"" + memberName + "\","); + stream.println (indent + " " + tcOfMembers + ','); + stream.println (indent + " null);"); + int offsetSoFar = innerOffsets.currentOffset (); + innerOffsets = new TCOffsets (); + innerOffsets.set (entry); + innerOffsets.bumpCurrentOffset (offsetSoFar - offsetForStruct); + + for (int idx = 0; idx < state.size (); ++idx) + { + TypedefEntry member = ((InterfaceState)state.elementAt (idx)).entry; + memberName = member.name (); + index = ((JavaGenerator)member.generator ()).helperType (index, indent, innerOffsets, tcOfMembers, member, stream); + stream.println (indent + membersName + '[' + (idx + 1) + "] = new org.omg.CORBA.StructMember ("); + stream.println (indent + " \"" + memberName + "\","); + stream.println (indent + " " + tcOfMembers + ','); + stream.println (indent + " null);"); + offsetSoFar = innerOffsets.currentOffset (); + innerOffsets = new TCOffsets (); + innerOffsets.set (entry); + innerOffsets.bumpCurrentOffset (offsetSoFar - offsetForStruct); + } + tcoffsets.bumpCurrentOffset (innerOffsets.currentOffset ()); + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_struct_tc (id (), \"" + entry.name () + "\", " + membersName + ");"); + return index; + } // structHelperType + + public void structHelperRead (String entryName, InterfaceEntry entry, PrintWriter stream) + { + String impl = implName ((InterfaceEntry)entry); + stream.println (" " + Util.javaStatefulName (entry) + " value = null;"); + structRead (0, " ", "value", entry, stream); + stream.println (" return value;"); + } // structHelperRead + + private String implName (InterfaceEntry entry) + { + String name; + if (entry.container ().name ().equals ("")) + name = '_' + entry.name () + "Impl"; + else + name = Util.containerFullName (entry.container ()) + "._" + entry.name () + "Impl"; + return name.replace ('/', '.'); + } // implName + + public int structRead (int index, String indent, String name, InterfaceEntry entry, PrintWriter stream) + { + // The first element will be the name of the Java implementation class. + String stringName = "_name" + index++; + stream.println (indent + "String " + stringName + " = istream.read_string ();"); + stream.println (indent + "try"); + stream.println (indent + "{"); + stream.println (indent + " " + name + " = (" + Util.javaStatefulName (entry) + ")com.sun.corba.ee.iiop.ORB.getImpl (" + stringName + ".replace ('/', '.'));"); + stream.println (indent + "}"); + stream.println (indent + "catch (Exception e)"); + stream.println (indent + "{"); + stream.println (indent + " " + name + " = null;"); + stream.println (indent + "}"); + stream.println (indent + "if (" + name + " == null)"); + stream.println (indent + " throw new org.omg.CORBA.NO_IMPLEMENT (0, org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + stream.println (); + + stream.println (indent + "if (!" + stringName + ".equals (\"" + entry.fullName () + "\"))"); + stream.println (indent + '{'); + stream.println (indent + " Class _cls = " + name + ".getClass ();"); + stream.println (indent + " boolean _found = false;"); + stream.println (indent + " while (!_found && _cls != null)"); + stream.println (indent + " {"); + stream.println (indent + " Class[] interfaces = _cls.getInterfaces ();"); + stream.println (indent + " for (int i = 0; i < interfaces.length; ++i)"); + stream.println (indent + " if (interfaces[i].getName ().indexOf (\"State\") > 0)"); + stream.println (indent + " {"); + stream.println (indent + " _cls = interfaces[i];"); + stream.println (indent + " _found = true;"); + stream.println (indent + " break;"); + stream.println (indent + " }"); + stream.println (indent + " if (!_found)"); + stream.println (indent + " _cls = _cls.getSuperclass ();"); + stream.println (indent + " }"); + stream.println (indent + " if (_cls == null)"); + stream.println (indent + " throw new org.omg.CORBA.NO_IMPLEMENT (0, org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + stream.println (); + stream.println (indent + " String _className = _cls.getName ();"); + stream.println (indent + " int _index = _className.lastIndexOf ('.');"); + stream.println (indent + " String _helperName = _className.substring (0, _index + 1) + _className.substring (_index + 2, _className.length () - 5) + \"Helper\"; // 5 == \"State\".length"); + stream.println (indent + " try"); + stream.println (indent + " {"); + stream.println (indent + " Class _helperClass = Class.forName (_helperName);"); + stream.println (indent + " Class[] _formalParms = new Class [1];"); + stream.println (indent + " _formalParms[0] = Class.forName (\"org.omg.CORBA.portable.InputStream\");"); + stream.println (indent + " java.lang.reflect.Method _read = _helperClass.getMethod (\"read\", _formalParms);"); + stream.println (indent + " Object[] _actualParms = new Object [1];"); + stream.println (indent + " _actualParms[0] = istream;"); + stream.println (indent + " " + name + " = (" + Util.javaStatefulName (entry) + ")_read.invoke (null, _actualParms);"); + stream.println (indent + " }"); + stream.println (indent + " catch (Exception e)"); + stream.println (indent + " {"); + stream.println (indent + " throw new org.omg.CORBA.NO_IMPLEMENT (0, org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + stream.println (indent + " }"); + stream.println (indent + '}'); + + // instantiate an implementation + stream.println (indent + "else"); + stream.println (indent + '{'); + + // Load the state + readState (index, indent, name, (InterfaceEntry)entry, stream); + + stream.println (indent + '}'); + return index; + } // structRead + + private void readState (int index, String indent, String name, InterfaceEntry entry, PrintWriter stream) + { + // First write the state from all parents + Enumeration e = entry.derivedFrom ().elements (); + while (e.hasMoreElements ()) + { + InterfaceEntry parent = (InterfaceEntry)e.nextElement (); + if (parent.state () != null) + { + if (parent.state ().size () > 0) + readState (index, indent, name, parent, stream); + break; + } + } + + // Now write the state for the local entry + e = entry.state ().elements (); + while (e.hasMoreElements ()) + { + TypedefEntry member = ((InterfaceState)e.nextElement ()).entry; + String tmpName = '_' + member.name () + "Tmp"; + Util.writeInitializer (indent + " ", tmpName, "", member, stream); + if (!member.arrayInfo ().isEmpty () || member.type () instanceof SequenceEntry || member.type () instanceof PrimitiveEntry || member.type () instanceof StringEntry) + index = ((JavaGenerator)member.generator ()).read (index, indent + " ", tmpName, member, stream); + else + stream.println (indent + " " + tmpName + " = " + Util.helperName (member.type (), true) + ".read (istream);"); // + stream.println (indent + " " + name + '.' + member.name () + " (" + tmpName + ");"); + } + } // readState + + public void structHelperWrite (SymtabEntry entry, PrintWriter stream) + { + structWrite (0, " ", "value", entry, stream); + } // structHelperWrite + + public int structWrite (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + // The first element of the struct must be the name of the real interface. + stream.println (indent + "Class _cls = " + name + ".getClass ();"); + stream.println (indent + "boolean _found = false;"); + stream.println (indent + "while (!_found && _cls != null)"); + stream.println (indent + "{"); + stream.println (indent + " Class[] interfaces = _cls.getInterfaces ();"); + stream.println (indent + " for (int i = 0; i < interfaces.length; ++i)"); + stream.println (indent + " if (interfaces[i].getName ().indexOf (\"State\") > 0)"); + stream.println (indent + " {"); + stream.println (indent + " _cls = interfaces[i];"); + stream.println (indent + " _found = true;"); + stream.println (indent + " break;"); + stream.println (indent + " }"); + stream.println (indent + " if (!_found)"); + stream.println (indent + " _cls = _cls.getSuperclass ();"); + stream.println (indent + '}'); + stream.println (); + stream.println (indent + "if (_cls == null)"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + stream.println (); + stream.println (indent + "String _className = _cls.getName ();"); + stream.println (indent + "int _index = _className.lastIndexOf ('.');"); + stream.println (indent + "String _interfaceName = _className.substring (0, _index + 1) + _className.substring (_index + 2, _className.length () - 5); // 5 == \"State\".length"); + stream.println (indent + "ostream.write_string (_interfaceName.replace ('.', '/'));"); + + // If _className != Util.javaName (entry), then call that class's helper class. + stream.println (); + stream.println (indent + "if (!_interfaceName.equals (\"" + Util.javaName (entry) + "\"))"); + stream.println (indent + '{'); + stream.println (indent + " try"); + stream.println (indent + " {"); + stream.println (indent + " Class _helperClass = Class.forName (_interfaceName + \"Helper\");"); + stream.println (indent + " Class[] _formalParms = new Class [2];"); + stream.println (indent + " _formalParms[0] = Class.forName (\"org.omg.CORBA.portable.OutputStream\");"); + stream.println (indent + " _formalParms[1] = _cls;"); + stream.println (indent + " java.lang.reflect.Method _write = _helperClass.getMethod (\"write\", _formalParms);"); + stream.println (indent + " Object[] _actualParms = new Object [2];"); + stream.println (indent + " _actualParms[0] = ostream;"); + stream.println (indent + " _actualParms[1] = " + name + ';'); + stream.println (indent + " _write.invoke (null, _actualParms);"); + stream.println (indent + " }"); + stream.println (indent + " catch (Exception e)"); + stream.println (indent + " {"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + stream.println (indent + " }"); + stream.println (indent + '}'); + + stream.println (indent + "else"); + stream.println (indent + '{'); + + writeState (index, indent, name, (InterfaceEntry)entry, stream); + + stream.println (indent + '}'); + return index; + } // structWrite + + private void writeState (int index, String indent, String name, InterfaceEntry entry, PrintWriter stream) + { + // First write the state from all parents + Enumeration e = entry.derivedFrom ().elements (); + while (e.hasMoreElements ()) + { + InterfaceEntry parent = (InterfaceEntry)e.nextElement (); + if (parent.state () != null) + { + if (parent.state ().size () > 0) + writeState (index, indent, name, parent, stream); + break; + } + } + + // Now write the state for the local entry + Vector members = entry.state (); + for (int i = 0; i < members.size (); ++i) + { + TypedefEntry member = ((InterfaceState)members.elementAt (i)).entry; + if (!member.arrayInfo ().isEmpty () || member.type () instanceof SequenceEntry || member.type () instanceof PrimitiveEntry || member.type () instanceof StringEntry) + index = ((JavaGenerator)member.generator ()).write (index, indent + " ", name + '.' + member.name () + "()", member, stream); + else + stream.println (indent + " " + Util.helperName (member.type (), true) + ".write (ostream, " + name + '.' + member.name () + " ());"); // + } + } // writeState + */ + + /** + * @return true if the entry is for a CORBA pseudo-object. + **/ + private boolean isPseudo(InterfaceEntry i) { + java.lang.String fullname = i.fullName(); + if (fullname.equalsIgnoreCase("CORBA/TypeCode")) + return true; + if (fullname.equalsIgnoreCase("CORBA/Principal")) + return true; + if (fullname.equalsIgnoreCase("CORBA/ORB")) + return true; + if (fullname.equalsIgnoreCase("CORBA/Any")) + return true; + if (fullname.equalsIgnoreCase("CORBA/Context")) + return true; + if (fullname.equalsIgnoreCase("CORBA/ContextList")) + return true; + if (fullname.equalsIgnoreCase("CORBA/DynamicImplementation")) + return true; + if (fullname.equalsIgnoreCase("CORBA/Environment")) + return true; + if (fullname.equalsIgnoreCase("CORBA/ExceptionList")) + return true; + if (fullname.equalsIgnoreCase("CORBA/NVList")) + return true; + if (fullname.equalsIgnoreCase("CORBA/NamedValue")) + return true; + if (fullname.equalsIgnoreCase("CORBA/Request")) + return true; + if (fullname.equalsIgnoreCase("CORBA/ServerRequest")) + return true; + if (fullname.equalsIgnoreCase("CORBA/UserException")) + return true; + return false; + } + + // From JavaGenerator + /////////////// + + protected int emit = 0; + protected com.sun.tools.corba.ee.idl.toJavaPortable.Factories factories = null; + + protected Hashtable symbolTable = null; + protected InterfaceEntry i = null; + protected PrintWriter stream = null; + + // Modify access to protected. + protected static final int SIGNATURE = 1; + protected static final int OPERATIONS = 2; + protected int intfType = 0; +} // class InterfaceGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/JavaGenerator.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/JavaGenerator.java new file mode 100644 index 000000000..7d8a9acf1 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/JavaGenerator.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import java.io.PrintWriter; + +import com.sun.tools.corba.ee.idl.SymtabEntry; + +/** + * + **/ +public interface JavaGenerator +{ + // The helper methods print the specific helper method. + // The helper read/write methods call the read/write methods. + + int helperType (int index, String indent, TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream); + + void helperRead (String entryName, SymtabEntry entry, PrintWriter stream); + + void helperWrite (SymtabEntry entry, PrintWriter stream); + + // The read/write methods print the streaming of the type. + // This printed code is found in the helper method but it is only + // that code that is concerned with streaming itself. + + int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream); + + int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream); + + int type (int index, String indent, TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream); + +} // interface JavaGenerator diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGen.java new file mode 100644 index 000000000..afd1c2ba4 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGen.java @@ -0,0 +1,1067 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -After demarshalling an IOR, think about how to deal with the exceptions. +// -catching Exception throws a string which should be in a properties file. +// -30jul1997 Modified to write comment immediately preceding method signature. +// -07May1998 Modified to support RMI Portable Stub +// -26Aug1998 Modified to pass helper instance to read_Value. +// -F46082.51 Remove -stateful feature; javaStatefulName() obsolete. +// -D56554 Port bounded string checks from toJava to toJavaPortable +// -D58549 bounded string checks on in/inout parms throw BAD_PARAM +// -D57112 Valuetype initializers map to ctor, regardless of name, and +// "void _init(...)" methods now mapped correctly. +// -D59297 pass context parm when Remarshalling +// -D59560 call read/write_Context +// -D60929 Update for RTF2.4 changes +// -D61056 Use Util.helperName +// -D61650 Remove '\n' from generated strings; use println()'s. + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.ExceptionEntry; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.ParameterEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.AttributeEntry; + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +/** + * + **/ +public class MethodGen implements com.sun.tools.corba.ee.idl.MethodGen +{ + private static final String ONE_INDENT = " "; + private static final String TWO_INDENT = " "; + private static final String THREE_INDENT = " "; + private static final String FOUR_INDENT = " "; + private static final String FIVE_INDENT = " "; + // This is the length of _get_ and _set_ + private static final int ATTRIBUTE_METHOD_PREFIX_LENGTH = 5; + /** + * Public zero-argument constructor. + **/ + public MethodGen () + { + } // ctor + + /** + * Method generate() is not used in MethodGen. They are replaced by the + * more granular interfaceMethod, stub, skeleton, dispatchSkeleton. + **/ + public void generate (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + } // generate + + /** + * + **/ + protected void interfaceMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + if (m.comment () != null) + m.comment ().generate ("", stream); + stream.print (" "); + SymtabEntry container = (SymtabEntry)m.container (); + boolean isAbstract = false; + boolean valueContainer = false; + if (container instanceof ValueEntry) + { + isAbstract = ((ValueEntry)container).isAbstract (); + valueContainer = true; + } + if (valueContainer && !isAbstract) + stream.print ("public "); + writeMethodSignature (); + if (valueContainer && !isAbstract) + { + stream.println (); + stream.println (" {"); + stream.println (" }"); + stream.println (); + } + else + stream.println (";"); + } // interfaceMethod + + /** + * + **/ + protected void stub (String className, boolean isAbstract, + Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index) + { + localOptimization = + ((Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).LocalOptimization; + this.isAbstract = isAbstract; + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + this.methodIndex = index; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" public "); + writeMethodSignature (); + stream.println (); + stream.println (" {"); + writeStubBody ( className ); + stream.println (" } // " + m.name ()); + stream.println (); + } // stub + + /** + * + **/ + protected void localstub (Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index, InterfaceEntry i) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + this.methodIndex = index; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" public "); + writeMethodSignature (); + stream.println (); + stream.println (" {"); + writeLocalStubBody (i); + stream.println (" } // " + m.name ()); + stream.println (); + } // stub + /** + * + **/ + protected void skeleton (Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + this.methodIndex = index; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" public "); + writeMethodSignature (); + stream.println (); + stream.println (" {"); + writeSkeletonBody (); + stream.println (" } // " + m.name ()); + } // skeleton + + /** + * + **/ + protected void dispatchSkeleton (Hashtable symbolTable, MethodEntry m, PrintWriter stream, int index) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + this.methodIndex = index; + if (m.comment () != null) + m.comment ().generate (" ", stream); + writeDispatchCall (); + } // dispatchSkeleton + + // + /** + * Determine whether method entry m is a valuetype initializer. + * @return true if is m is valuetype initializer, false otherwise. + **/ + protected boolean isValueInitializer () + { + MethodEntry currentInit = null; + if ((m.container () instanceof ValueEntry)) + { + Enumeration e = ((ValueEntry)m.container ()).initializers ().elements (); + while (currentInit != m && e.hasMoreElements ()) + currentInit = (MethodEntry)e.nextElement (); + } + return (currentInit == m) && (null != m); // True ==> yes, false ==> no. + } // isValueInitializer + + /** + * + **/ + protected void writeMethodSignature () + { + boolean isValueInitializer = isValueInitializer (); // + + // Step 0. Print the return type and name. + // A return type of null indicates the "void" return type. If m is a + // Valuetype intitializer, it has name "init" and a null return type, + // but it maps to a ctor. + // + //if (m.type () == null) + //{ + // if (m.name ().compareTo ("init") != 0) + // stream.print ("void"); + //} + if (m.type () == null) + { + if (!isValueInitializer) + stream.print ("void"); + } + else + { + // Remove -stateful feature; javaStatefulName() obsolete. + //stream.print (Util.javaStatefulName (m.type ())); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(m.type())); + } + // Value initializers map to constructors. + // If the value has an 'init' method with a return type, handle + // the method like other regular methods + //if (m.valueMethod () && m.name ().compareTo ("init") == 0 && + // m.type () == null) + if (isValueInitializer) + stream.print (' ' + m.container ().name () + " ("); + else + stream.print (' ' + m.name () + " ("); + + // Step 1. Print the parameter list. + boolean firstTime = true; + Enumeration e = m.parameters ().elements (); + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + ParameterEntry parm = (ParameterEntry)e.nextElement (); + + writeParmType (parm.type (), parm.passType ()); + + // Print parm name + stream.print (' ' + parm.name ()); + } + + // Step 2. Add the context parameter if necessary. + if (m.contexts ().size () > 0) + { + if (!firstTime) + stream.print (", "); + stream.print ("org.omg.CORBA.Context $context"); + } + + // Step 3. Print the throws clause (if necessary). + if (m.exceptions ().size () > 0) + { + stream.print (") throws "); + e = m.exceptions ().elements (); + firstTime = true; + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName((SymtabEntry) e.nextElement())); + } + } + else + stream.print (')'); + } // writeMethodSignature + + /** + * + **/ + protected void writeParmType (SymtabEntry parm, int passType) + { + if (passType != ParameterEntry.In) + { + parm = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(parm); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.holderName(parm)); + } + else // passType is `in' + // Remove -stateful feature; javaStatefulName() obsolete. + //stream.print (Util.javaStatefulName (parm)); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parm)); + } // writeParmType + + /** + * + **/ + protected void writeDispatchCall () + { + String indent = " "; + String fullMethodName = m.fullName (); + if (m instanceof AttributeEntry) + { + // determine the index at which the attribute name starts in the full name + int index = fullMethodName.lastIndexOf ('/') + 1; + if (m.type () == null) // if it's a modifier + fullMethodName = fullMethodName.substring (0, index) + "_set_" + m.name (); + else + fullMethodName = fullMethodName.substring (0, index) + "_get_" + m.name (); + } + stream.println (indent + "case " + methodIndex + ": // " + fullMethodName); + stream.println (indent + "{"); + indent = indent + " "; + if (m.exceptions ().size () > 0) + { + stream.println (indent + "try {"); + indent = indent + " "; + } + + // Step 1 Read arguments from the input stream + SymtabEntry mtype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(m.type()); + Enumeration parms = m.parameters ().elements (); + parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry) parms.nextElement (); + String name = parm.name (); + String anyName = '_' + name; + SymtabEntry type = parm.type (); + int passType = parm.passType (); + + if (passType == ParameterEntry.In) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(indent, name, "", type, writeInputStreamRead("in", type), stream); + + else // the parm is a holder + { + String holderName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.holderName(type); + stream.println (indent + holderName + ' ' + name + " = new " + holderName + " ();"); + if (passType == ParameterEntry.Inout) + { + if (type instanceof ValueBoxEntry) + { + ValueBoxEntry v = (ValueBoxEntry) type; + TypedefEntry member = ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof PrimitiveEntry) + stream.println (indent + name + ".value = (" + writeInputStreamRead ("in", parm.type ()) + ").value;"); + else + stream.println (indent + name + ".value = " + writeInputStreamRead ("in", parm.type ()) + ";"); + } + else + stream.println (indent + name + ".value = " + writeInputStreamRead ("in", parm.type ()) + ";"); + } + } + } + + // Step 1a. Read the context parameter if necessary. + if (m.contexts ().size () > 0) + { + stream.println (indent + "org.omg.CORBA.Context $context = in.read_Context ();"); + } + + // Step 2 Load return if necessary + if (mtype != null) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(indent, "$result", "", mtype, stream); + + // Step 3 Call the method with the list of parameters + writeMethodCall (indent); + + parms = m.parameters ().elements (); + boolean firstTime = true; + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + if (firstTime) + firstTime = false; + else + stream.print (", "); + stream.print (parm.name ()); + } + + // Step 3a. Add the context parameter if necessary. + if (m.contexts ().size () > 0) + { + if (!firstTime) + stream.print (", "); + stream.print ("$context"); + } + + stream.println (");"); + + //Step 3b. Create reply; + writeCreateReply (indent); + + // Step 4 Write method's result to the output stream + if (mtype != null) + { + writeOutputStreamWrite (indent, "out", "$result", mtype, stream); + } + + // Step 5 Write inout/out value to the output stream + parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + int passType = parm.passType (); + if (passType != ParameterEntry.In) + { + writeOutputStreamWrite (indent, "out", parm.name () + ".value", parm.type (), stream); + } + } + + // Step 6 Handle exception + if (m.exceptions ().size () > 0) + { + Enumeration exceptions = m.exceptions ().elements (); + while (exceptions.hasMoreElements ()) + { + indent = " "; + ExceptionEntry exc = (ExceptionEntry) exceptions.nextElement (); + String fullName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(exc); + stream.println (indent + "} catch (" + fullName + " $ex) {"); + indent = indent + " "; + stream.println (indent + "out = $rh.createExceptionReply ();"); + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(exc, true) + ".write (out, $ex);"); // + } + + indent = " "; + stream.println (indent + "}"); + } + + stream.println (" break;"); + stream.println (" }"); + stream.println (); + } // writeDispatchCall + + /** + * + **/ + protected void writeStubBody ( String className ) + { + // Step 1 Create a request + String methodName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(m.name()); + if (m instanceof AttributeEntry) + { + if (m.type () == null) // if it's a modifier + methodName = "_set_" + methodName; + else + methodName = "_get_" + methodName; + } + if( localOptimization && !isAbstract ) { + stream.println (ONE_INDENT + "while(true) {" ); + stream.println(TWO_INDENT + "if(!this._is_local()) {" ); + } + stream.println(THREE_INDENT + + "org.omg.CORBA.portable.InputStream $in = null;"); + stream.println(THREE_INDENT + "try {"); + stream.println(FOUR_INDENT + "org.omg.CORBA.portable.OutputStream $out =" + + " _request (\"" + methodName + "\", " + !m.oneway() + ");"); + + // Step 1.b. Check string bounds + // begin in/inout string bounds check + Enumeration parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + SymtabEntry parmType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(parm.type()); + if (parmType instanceof StringEntry) + if ((parm.passType () == ParameterEntry.In) || + (parm.passType () == ParameterEntry.Inout)) + { + StringEntry string = (StringEntry)parmType; + if (string.maxSize () != null) + { + stream.print (THREE_INDENT + "if (" + parm.name ()); + if (parm.passType () == ParameterEntry.Inout) + stream.print (".value"); // get from holder + stream.print (" == null || " + parm.name ()); + if (parm.passType () == ParameterEntry.Inout) + stream.print (".value"); // get from holder + stream.println (".length () > (" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(string.maxSize()) + "))"); + stream.println (THREE_INDENT + + "throw new org.omg.CORBA.BAD_PARAM (0," + + " org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + } + } + } + // end in/inout string bounds check + + // Step 2 Load the parameters into the outputStream + parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + if (parm.passType () == ParameterEntry.In) + writeOutputStreamWrite(FOUR_INDENT, "$out", parm.name (), parm.type (), + stream); + else if (parm.passType () == ParameterEntry.Inout) + writeOutputStreamWrite(FOUR_INDENT, "$out", parm.name () + ".value", + parm.type (), stream); + } + + // Step 2a. Write the context parameter if necessary. + if (m.contexts ().size () > 0) + { + stream.println(FOUR_INDENT + "org.omg.CORBA.ContextList $contextList =" + + "_orb ().create_context_list ();"); + + for (int cnt = 0; cnt < m.contexts ().size (); cnt++) + { + stream.println(FOUR_INDENT + + "$contextList.add (\"" + m.contexts (). elementAt (cnt) + "\");"); + } + stream.println(FOUR_INDENT + + "$out.write_Context ($context, $contextList);"); + } + + // Step 3 Invoke the method with the output stream + stream.println (FOUR_INDENT + "$in = _invoke ($out);"); + + SymtabEntry mtype = m.type (); + if (mtype != null) + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(FOUR_INDENT, "$result", "", mtype, + writeInputStreamRead("$in", mtype), stream); + + // Step 4 Read the inout/out values + parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + if (parm.passType () != ParameterEntry.In) + { + if (parm.type () instanceof ValueBoxEntry) + { + ValueBoxEntry v = (ValueBoxEntry) parm.type (); + TypedefEntry member = + ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof PrimitiveEntry) + stream.println(FOUR_INDENT + parm.name () + + ".value = (" + writeInputStreamRead ("$in", parm.type ()) + + ").value;"); + else + stream.println(FOUR_INDENT + parm.name () + + ".value = " + writeInputStreamRead ("$in", parm.type ()) +";"); + } + else + stream.println (FOUR_INDENT + parm.name () + ".value = " + + writeInputStreamRead ("$in", parm.type ()) + ";"); + } + } + // Step 4.b. Check string bounds + // begin out/inout/return string bounds check + parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + SymtabEntry parmType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(parm.type()); + if (parmType instanceof StringEntry) + if ((parm.passType () == ParameterEntry.Out) || + (parm.passType () == ParameterEntry.Inout)) + { + StringEntry string = (StringEntry)parmType; + if (string.maxSize () != null) + { + stream.print (FOUR_INDENT + "if (" + parm.name () + + ".value.length ()"); + stream.println (" > (" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(string.maxSize()) + "))"); + stream.println (FIVE_INDENT + "throw new org.omg.CORBA.MARSHAL(0,"+ + "org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + } + } + } + if (mtype instanceof StringEntry) + { + StringEntry string = (StringEntry)mtype; + if (string.maxSize () != null) + { + stream.println(FOUR_INDENT + "if ($result.length () > (" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(string.maxSize()) + "))"); + stream.println (FIVE_INDENT + "throw new org.omg.CORBA.MARSHAL (0," + + " org.omg.CORBA.CompletionStatus.COMPLETED_NO);"); + } + } + // end out/inout/return string bounds check + + // Step 5 Handle return if necessary + if (mtype != null) { + stream.println(FOUR_INDENT + "return $result;"); + } else { + stream.println(FOUR_INDENT + "return;"); + } + + // Step 6 Handle exceptions + stream.println(THREE_INDENT + + "} catch (org.omg.CORBA.portable.ApplicationException " + "$ex) {"); + stream.println(FOUR_INDENT + "$in = $ex.getInputStream ();"); + stream.println(FOUR_INDENT + "String _id = $ex.getId ();"); + + if (m.exceptions ().size () > 0) + { + Enumeration exceptions = m.exceptions ().elements (); + boolean firstExc = true; + while (exceptions.hasMoreElements ()) + { + ExceptionEntry exc = (ExceptionEntry)exceptions.nextElement (); + if (firstExc) + { + stream.print(FOUR_INDENT + "if "); + firstExc = false; + } + else + stream.print(FOUR_INDENT + "else if "); + + stream.println( "(_id.equals (\"" + exc.repositoryID ().ID () + "\"))"); + stream.println (FIVE_INDENT + "throw " + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName((SymtabEntry) exc, false) + ".read ($in);"); + } + stream.println(FOUR_INDENT + "else"); + stream.println(FIVE_INDENT + "throw new org.omg.CORBA.MARSHAL (_id);"); + } + else + stream.println(FOUR_INDENT + "throw new org.omg.CORBA.MARSHAL (_id);"); + + stream.println(THREE_INDENT + + "} catch (org.omg.CORBA.portable.RemarshalException $rm) {"); + stream.print( FOUR_INDENT ); + if (m.type () != null) // not a void method + stream.print ("return "); + stream.print (m.name () + " ("); + { + // write parm names + boolean firstTime = true; + Enumeration e = m.parameters ().elements (); + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + ParameterEntry parm = (ParameterEntry)e.nextElement (); + stream.print (parm.name ()); + } + // Step 2. Add the context parameter if necessary. + if (m.contexts ().size () > 0) + { + if (!firstTime) + stream.print (", "); + stream.print ("$context"); + } + } + stream.println (TWO_INDENT + ");"); + stream.println (THREE_INDENT + "} finally {"); + stream.println (FOUR_INDENT + "_releaseReply ($in);"); + stream.println (THREE_INDENT + "}"); + if( localOptimization && !isAbstract ) { + stream.println (TWO_INDENT + "}"); + writeStubBodyForLocalInvocation( className, methodName ); + } + + } // writeStubBody + + + /** + * This method writes the else part of the stub method invocation to + * enable local invocation in case of collocation. + * NOTE: This will only be invoked from writeStubBody. + */ + private void writeStubBodyForLocalInvocation( String className, + String methodName ) + { + stream.println (TWO_INDENT + "else {" ); + stream.println (THREE_INDENT + + "org.omg.CORBA.portable.ServantObject _so ="); + stream.println (FOUR_INDENT + "_servant_preinvoke(\"" + methodName + + "\", _opsClass);" ); + stream.println(THREE_INDENT + "if (_so == null ) {"); + stream.println(FOUR_INDENT + "continue;" ); + stream.println(THREE_INDENT + "}"); + stream.println(THREE_INDENT + className + "Operations _self =" ); + stream.println(FOUR_INDENT + "(" + className + "Operations) _so.servant;"); + stream.println(THREE_INDENT + "try {" ); + Enumeration parms = m.parameters ().elements (); + if (m instanceof AttributeEntry) + { + // Local Method Name should drop _get_ or _set_ prefix for attribute + // entry + methodName = methodName.substring( ATTRIBUTE_METHOD_PREFIX_LENGTH ); + } + boolean voidReturnType = (this.m.type() == null); + if ( !voidReturnType ) { + stream.println (FOUR_INDENT + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(this.m.type()) + + " $result;"); + } + if( !isValueInitializer() ) { + if ( voidReturnType ) { + stream.print(FOUR_INDENT + "_self." + methodName + "( " ); + } else { + stream.print(FOUR_INDENT + "$result = _self." + + methodName + "( " ); + } + while (parms.hasMoreElements ()) { + ParameterEntry param = (ParameterEntry)parms.nextElement (); + if( parms.hasMoreElements( ) ) { + stream.print( " " + param.name() + "," ); + } else { + stream.print( " " + param.name() ); + } + } + stream.print( ");" ); + stream.println( " " ); + if( voidReturnType ) { + stream.println(FOUR_INDENT + "return;" ); + } else { + stream.println(FOUR_INDENT + "return $result;" ); + } + } + stream.println(" "); + stream.println (THREE_INDENT + "}" ); + stream.println (THREE_INDENT + "finally {" ); + stream.println (FOUR_INDENT + "_servant_postinvoke(_so);" ); + stream.println (THREE_INDENT + "}" ); + stream.println (TWO_INDENT + "}" ); + stream.println (ONE_INDENT + "}" ); + } + + + protected void writeLocalStubBody (InterfaceEntry i) + { + // Step 1 Create a request + String methodName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(m.name()); + if (m instanceof AttributeEntry) + { + if (m.type () == null) // if it's a modifier + methodName = "_set_" + methodName; + else + methodName = "_get_" + methodName; + } + //stream.println (" while(true) {"); + stream.println (" org.omg.CORBA.portable.ServantObject $so = " + + "_servant_preinvoke (\"" + methodName + "\", " + "_opsClass);"); + //stream.println (" if ($so == null) {"); + //stream.println (" continue;"); + //stream.println (" }"); + String opsName = i.name() + "Operations"; + stream.println (" " + opsName + " $self = " + "(" + opsName + ") " + "$so.servant;"); + stream.println (); + stream.println (" try {"); + stream.print (" "); + if (m.type () != null) // not a void method + stream.print ("return "); + stream.print ("$self." + m.name () + " ("); + { + // write parm names + boolean firstTime = true; + Enumeration e = m.parameters ().elements (); + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + ParameterEntry parm = (ParameterEntry)e.nextElement (); + stream.print (parm.name ()); + } + // Step 2. Add the context parameter if necessary. + if (m.contexts ().size () > 0) + { + if (!firstTime) + stream.print (", "); + stream.print ("$context"); + } + } + stream.println (");"); + //stream.println (" } catch (org.omg.CORBA.portable.RemarshalException $rm) {"); + //stream.println (" continue; "); + stream.println (" } finally {"); + stream.println (" _servant_postinvoke ($so);"); + stream.println (" }"); + //stream.println (" }"); + + } // writeLocalStubBody + + + + /** + * + **/ + private void writeInsert (String indent, String target, String source, SymtabEntry type, PrintWriter stream) + { + String typeName = type.name (); + if (type instanceof PrimitiveEntry) + { + // RJB does something have to be done with TC offsets? + if (typeName.equals ("long long")) + stream.println (indent + source + ".insert_longlong (" + target + ");"); + else if (typeName.equals ("unsigned short")) + stream.println (indent + source + ".insert_ushort (" + target + ");"); + else if (typeName.equals ("unsigned long")) + stream.println (indent + source + ".insert_ulong (" + target + ");"); + else if (typeName.equals ("unsigned long long")) + stream.println (indent + source + ".insert_ulonglong (" + target + ");"); + else + stream.println (indent + source + ".insert_" + typeName + " (" + target + ");"); + } + else if (type instanceof StringEntry) + stream.println (indent + source + ".insert_" + typeName + " (" + target + ");"); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".insert (" + source + ", " + target + ");"); // + } // writeInsert + + /** + * + **/ + private void writeType (String indent, String name, SymtabEntry type, PrintWriter stream) + { + if (type instanceof PrimitiveEntry) + { + // RJB does something have to be done with TC offsets? + if (type.name ().equals ("long long")) + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_longlong));"); + else if (type.name ().equals ("unsigned short")) + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ushort));"); + else if (type.name ().equals ("unsigned long")) + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ulong));"); + else if (type.name ().equals ("unsigned long long")) + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ulonglong));"); + else + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_" + type.name () + "));"); + } + else if (type instanceof StringEntry) + { + StringEntry s = (StringEntry)type; + Expression e = s.maxSize (); + if (e == null) + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().create_" + type.name () + "_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(e) + "));"); + else + stream.println (indent + name + " (org.omg.CORBA.ORB.init ().create_" + type.name () + "_tc (0));"); + } + else + stream.println (indent + name + '(' + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".type ());"); // + } // writeType + + /** + * + **/ + private void writeExtract (String indent, String target, String source, SymtabEntry type, PrintWriter stream) + { + if (type instanceof PrimitiveEntry) + { + if (type.name ().equals ("long long")) + stream.println (indent + target + " = " + source + ".extract_longlong ();"); + else if (type.name ().equals ("unsigned short")) + stream.println (indent + target + " = " + source + ".extract_ushort ();"); + else if (type.name ().equals ("unsigned long")) + stream.println (indent + target + " = " + source + ".extract_ulong ();"); + else if (type.name ().equals ("unsigned long long")) + stream.println (indent + target + " = " + source + ".extract_ulonglong ();"); + else + stream.println (indent + target + " = " + source + ".extract_" + type.name () + " ();"); + } + else if (type instanceof StringEntry) + stream.println (indent + target + " = " + source + ".extract_" + type.name () + " ();"); + else + stream.println (indent + target + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".extract (" + source + ");"); // + } // writeExtract + + /** + * + **/ + private String writeExtract (String source, SymtabEntry type) + { + String extract; + if (type instanceof PrimitiveEntry) + { + if (type.name ().equals ("long long")) + extract = source + ".extract_longlong ()"; + else if (type.name ().equals ("unsigned short")) + extract = source + ".extract_ushort ()"; + else if (type.name ().equals ("unsigned long")) + extract = source + ".extract_ulong ()"; + else if (type.name ().equals ("unsigned long long")) + extract = source + ".extract_ulonglong ()"; + else + extract = source + ".extract_" + type.name () + " ()"; + } + else if (type instanceof StringEntry) + extract = source + ".extract_" + type.name () + " ()"; + else + extract = com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".extract (" + source + ')'; // + return extract; + } // writeExtract + + /** + * + **/ + private void writeSkeletonBody () + { + SymtabEntry mtype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(m.type()); + + // If there is a return value, increment the appropriate counter + stream.print (" "); + if (mtype != null) + stream.print ("return "); + stream.print ("_impl." + m.name () + '('); + + // Load the parameters + Enumeration parms = m.parameters ().elements (); + boolean first = true; + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + if (first) + first = false; + else + stream.print (", "); + stream.print (parm.name ()); + } + if (m.contexts ().size () != 0) + { + if (!first) + stream.print (", "); + stream.print ("$context"); + } + + stream.println (");"); + } // writeSkeletonBody + + /** + * + **/ + protected String passType (int passType) + { + String type; + switch (passType) + { + case ParameterEntry.Inout: + type = "org.omg.CORBA.ARG_INOUT.value"; + break; + case ParameterEntry.Out: + type = "org.omg.CORBA.ARG_OUT.value"; + break; + case ParameterEntry.In: + default: + type = "org.omg.CORBA.ARG_IN.value"; + break; + } + return type; + } // passType + + /** + * This is only used by AttributeGen. The java mapping says + * the names should be getXXX and setXXX, but CORBA says they + * should be _get_XXX and _set_XXX. this.name () will be + * getXXX. realName is set by AttributeGen to _get_XXX. + **/ + protected void serverMethodName (String name) + { + realName = (name == null) ? "" : name; + } // serverMethodName + + /** + * + **/ + private void writeOutputStreamWrite (String indent, String oStream, String name, SymtabEntry type, PrintWriter stream) + { + String typeName = type.name (); + stream.print (indent); + if (type instanceof PrimitiveEntry) + { + if (typeName.equals ("long long")) + stream.println (oStream + ".write_longlong (" + name +");"); + else if (typeName.equals ("unsigned short")) + stream.println (oStream + ".write_ushort (" + name + ");"); + else if (typeName.equals ("unsigned long")) + stream.println (oStream + ".write_ulong (" + name + ");"); + else if (typeName.equals ("unsigned long long")) + stream.println (oStream + ".write_ulonglong (" + name + ");"); + else + stream.println (oStream + ".write_" + typeName + " (" + name + ");"); + } + else if (type instanceof StringEntry) + stream.println (oStream + ".write_" + typeName + " (" + name + ");"); + else if (type instanceof SequenceEntry) + stream.println (oStream + ".write_" + type.type().name() + " (" + name + ");"); + else if (type instanceof ValueBoxEntry) + { + ValueBoxEntry v = (ValueBoxEntry) type; + TypedefEntry member = ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + + // if write value to the boxed holder indicated by the name ending with ".value" + if (mType instanceof PrimitiveEntry && name.endsWith (".value")) + stream.println (com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".write (" + oStream + ", " // + + " new " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(type) + " (" + name + "));"); // + else + stream.println (com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".write (" + oStream + ", " + name + ");"); // // + } + else if (type instanceof ValueEntry) + stream.println (com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".write (" + oStream + ", " + name + ");"); // // + else + stream.println (com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".write (" + oStream + ", " + name + ");"); // + } // writeOutputStreamWrite + + /** + * + **/ + private String writeInputStreamRead (String source, SymtabEntry type) + { + String read = ""; + if (type instanceof PrimitiveEntry) + { + if (type.name ().equals ("long long")) + read = source + ".read_longlong ()"; + else if (type.name ().equals ("unsigned short")) + read = source + ".read_ushort ()"; + else if (type.name ().equals ("unsigned long")) + read = source + ".read_ulong ()"; + else if (type.name ().equals ("unsigned long long")) + read = source + ".read_ulonglong ()"; + else + read = source + ".read_" + type.name () + " ()"; + } + else if (type instanceof StringEntry) + read = source + ".read_" + type.name () + " ()"; + else + read = com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".read (" + source + ')'; // + return read; + } // writeInputStreamRead + + /** + * + **/ + protected void writeMethodCall (String indent) + { + SymtabEntry mtype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(m.type()); + if (mtype == null) + stream.print (indent + "this." + m.name () + " ("); + else + stream.print (indent + "$result = this." + m.name () + " ("); + } // writeMethodCall + + /** + * + **/ + protected void writeCreateReply(String indent){ + stream.println(indent + "out = $rh.createReply();"); + } + + protected int methodIndex = 0; + protected String realName = ""; + protected Hashtable symbolTable = null; + protected MethodEntry m = null; + protected PrintWriter stream = null; + protected boolean localOptimization = false; + protected boolean isAbstract = false; +} // class MethodGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGen24.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGen24.java new file mode 100644 index 000000000..db90a8343 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGen24.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 New file to implement CORBA 2.4 RTF +// -D62794 Fix problem with no-arg create functions + +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.ParameterEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +/** + * + **/ +public class MethodGen24 extends MethodGen +{ + /** + * Public zero-argument constructor. + **/ + public MethodGen24 () + { + } // ctor + + /** + * Print the parameter list for the factory method. + * @param m The method to list parameters for + * @param listTypes If try, declare the parms, otherwise just list them + * @param stream The PrintWriter to print on + */ + protected void writeParmList (MethodEntry m, boolean listTypes, PrintWriter stream) { + boolean firstTime = true; + Enumeration e = m.parameters ().elements (); + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + ParameterEntry parm = (ParameterEntry)e.nextElement (); + if (listTypes) { + writeParmType (parm.type (), parm.passType ()); + stream.print (' '); + } + // Print parm name + stream.print (parm.name ()); + // end of parameter list + } + } + + void helperFactoryMethod(Hashtable symbolTable, MethodEntry m, SymtabEntry t, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + String initializerName = m.name (); + String typeName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(t); + String factoryName = typeName + "ValueFactory"; + + // Step 1. Print factory method decl up to parms. + stream.print (" public static " + typeName + " " + initializerName + + " (org.omg.CORBA.ORB $orb"); + if (!m.parameters ().isEmpty ()) + stream.print (", "); // + + // Step 2. Print the declaration parameter list. + writeParmList (m, true, stream); + + // Step 3. Print the body of the factory method + stream.println (")"); + stream.println (" {"); + stream.println (" try {"); + stream.println (" " + factoryName + " $factory = (" + factoryName + ")"); + stream.println (" ((org.omg.CORBA_2_3.ORB) $orb).lookup_value_factory(id());"); + stream.print (" return $factory." + initializerName + " ("); + writeParmList (m, false, stream); + stream.println (");"); + stream.println (" } catch (ClassCastException $ex) {"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM ();"); + stream.println (" }"); + stream.println (" }"); + stream.println (); + } // helperFactoryMethod + + void abstractMethod(Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" "); + stream.print ("public abstract "); + writeMethodSignature (); + stream.println (";"); + stream.println (); + } // abstractMethod + + void defaultFactoryMethod(Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + String typeName = m.container (). name (); + stream.println (); + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" public " + typeName + " " + m.name () + " ("); + writeParmList (m, true, stream); + stream.println (")"); + stream.println (" {"); + stream.print (" return new " + typeName + "Impl ("); + writeParmList (m, false, stream); + stream.println (");"); + stream.println (" }"); + } // defaultFactoryMethod + + protected void writeMethodSignature () + { + // Step 0. Print the return type and name. + // A return type of null indicates the "void" return type. If m is a + // Valuetype factory method, it has a null return type, + if (m.type () == null) + { + // if factory method, result type is container + if (isValueInitializer ()) + stream.print (m.container ().name ()); + else + stream.print ("void"); + } + else + { + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(m.type())); + } + stream.print (' ' + m.name () + " ("); + + // Step 1. Print the parameter list. + boolean firstTime = true; + Enumeration e = m.parameters ().elements (); + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + ParameterEntry parm = (ParameterEntry)e.nextElement (); + + writeParmType (parm.type (), parm.passType ()); + + // Print parm name + stream.print (' ' + parm.name ()); + } + + // Step 2. Add the context parameter if necessary. + if (m.contexts ().size () > 0) + { + if (!firstTime) + stream.print (", "); + stream.print ("org.omg.CORBA.Context $context"); + } + + // Step 3. Print the throws clause (if necessary). + if (m.exceptions ().size () > 0) + { + stream.print (") throws "); + e = m.exceptions ().elements (); + firstTime = true; + while (e.hasMoreElements ()) + { + if (firstTime) + firstTime = false; + else + stream.print (", "); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName((SymtabEntry) e.nextElement())); + } + } + else + stream.print (')'); + } // writeMethodSignature + + protected void interfaceMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" "); + writeMethodSignature (); + stream.println (";"); + } // interfaceMethod +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGenClone24.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGenClone24.java new file mode 100644 index 000000000..88903b8f5 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/MethodGenClone24.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 New file to implement CORBA 2.4 RTF +// NOTE: The methods in this class should be exact copies of the +// correspoind methods in MethodGen24. The purpose of this class is +// to inject the changes made in MethodGen24 between AttributeGen +// and AttributeGen24. When the AttributeGen24 changes are merged, this +// class should be deleted. + +import com.sun.tools.corba.ee.idl.MethodEntry; + +import java.io.PrintWriter; +import java.util.Hashtable; + +/** + * + **/ +public class MethodGenClone24 extends AttributeGen +{ + /** + * Public zero-argument constructor. + **/ + public MethodGenClone24 () + { + } // ctor + + /** + * write an abstract method definition + **/ + protected void abstractMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" "); + stream.print ("public abstract "); + writeMethodSignature (); + stream.println (";"); + stream.println (); + } // abstractMethod + + /** + * delete method templates for valuetypes + **/ + protected void interfaceMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.m = m; + this.stream = stream; + if (m.comment () != null) + m.comment ().generate (" ", stream); + stream.print (" "); + writeMethodSignature (); + stream.println (";"); + } // interfaceMethod +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ModuleGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ModuleGen.java new file mode 100644 index 000000000..ced9aab9f --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ModuleGen.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.ModuleEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +/** + * + **/ +public class ModuleGen implements com.sun.tools.corba.ee.idl.ModuleGen +{ + /** + * Public zero-argument constructor. + **/ + public ModuleGen () + { + } // ctor + + /** + * Generate Java code for all members of an IDL module. + **/ + public void generate (Hashtable symbolTable, ModuleEntry entry, PrintWriter stream) + { + // Generate the package directory + String name = Util.containerFullName(entry) ; + Util.mkdir(name); + + // Generate all of the contained types + Enumeration e = entry.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry element = (SymtabEntry)e.nextElement (); + if (element.emit ()) + element.generate (symbolTable, stream); + } + } // generate +} // class ModuleGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/NameModifier.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/NameModifier.java new file mode 100644 index 000000000..9c4552567 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/NameModifier.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +public interface NameModifier { + /** Create a modified name from the base name. + */ + String makeName( String base ) ; +} ; + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/NameModifierImpl.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/NameModifierImpl.java new file mode 100644 index 000000000..2304a73ae --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/NameModifierImpl.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +public class NameModifierImpl implements com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier { + private String prefix ; + private String suffix ; + + public NameModifierImpl( ) + { + this.prefix = null ; + this.suffix = null ; + } + + public NameModifierImpl( String prefix, String suffix ) + { + this.prefix = prefix ; + this.suffix = suffix ; + } + + /** Construct a NameModifier from a pattern of the form xxx%xxx. + * The pattern must consist of characters chosen from the + * set [A-Za-z0-9%$_]. In addition, the pattern must contain + * exactly one % character. Finally, if % is not the first char in + * the pattern, the pattern must not start with a number. + *

+ * The semantics of makeName are very simply: just replace the + * % character with the base in the pattern and return the result. + */ + public NameModifierImpl( String pattern ) + { + int first = pattern.indexOf( '%' ) ; + int last = pattern.lastIndexOf( '%' ) ; + + if (first != last) + throw new IllegalArgumentException( + Util.getMessage("NameModifier.TooManyPercent") ) ; + + if (first == -1) + throw new IllegalArgumentException( + Util.getMessage("NameModifier.NoPercent") ) ; + + for (int ctr = 0; ctr + emit = "tk_Principal"; + else if (entry.name ().equals ("wchar")) + emit = "tk_wchar"; + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind." + emit + ");"); + return index; + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + } // helperWrite + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + stream.println (indent + name + " = " + "istream.read_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.collapseName(entry.name()) + " ();"); + return index; + } // read + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + stream.println (indent + "ostream.write_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.collapseName(entry.name()) + " (" + name + ");"); + return index; + } // write + + // From JavaGenerator + /////////////// +} // class PrimitiveGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/SequenceGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/SequenceGen.java new file mode 100644 index 000000000..60c091009 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/SequenceGen.java @@ -0,0 +1,247 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -F46082.51 Remove -stateful feature; javaStatefulName() obsolete. +// -D61056 Use Util.helperName + +import java.io.PrintWriter; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +/** + * + **/ +public class SequenceGen implements com.sun.tools.corba.ee.idl.SequenceGen, com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public SequenceGen () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, SequenceEntry s, PrintWriter stream) + { + } // generator + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + int offsetOfType = tcoffsets.offset (entry.type ().fullName ()); + if (offsetOfType >= 0) + { + // This code uses the deprecated create_recursive_sequence_tc() + // It should be eliminated when the API is removed from the ORB class + // Regardles, this code will not be emitted since updated emitters invoke + // method type() below instead of helperType() when handling sequences + + // This is a recursive sequence + tcoffsets.set (null); + Expression maxSize = ((SequenceEntry)entry).maxSize (); + if (maxSize == null) + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_recursive_sequence_tc (0, " + (offsetOfType - tcoffsets.currentOffset ()) + ");"); + else + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_recursive_sequence_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(maxSize) + ", " + (offsetOfType - tcoffsets.currentOffset ()) + ");"); + tcoffsets.bumpCurrentOffset (4); // add indirection field + } + else + { + // This is a normal sequence + tcoffsets.set (entry); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.type ().generator ()).helperType (index + 1, indent, tcoffsets, name, entry.type (), stream); + Expression maxSize = ((SequenceEntry)entry).maxSize (); + if (maxSize == null) + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_sequence_tc (0, " + name + ");"); + else + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_sequence_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(maxSize) + ", " + name + ");"); + } + tcoffsets.bumpCurrentOffset (4); // add on the seq max size + return index; + } // helperType + + public int type (int index, String indent, TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + int offsetOfType = tcoffsets.offset (entry.type ().fullName ()); + if (offsetOfType >= 0) + { + // This is a recursive sequence + tcoffsets.set (null); + + // Need to fix later: how to get repositoryId of IDL type containing this sequence? + // entry.repositoryID().ID() returns empty string and + // Util.javaQualifiedName(entry) returns internal name which is not valid repId + + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_recursive_tc (" + "\"\"" + ");"); + tcoffsets.bumpCurrentOffset (4); // add indirection field + } + else + { + // This is a normal sequence + tcoffsets.set (entry); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.type ().generator ()).type (index + 1, indent, tcoffsets, name, entry.type (), stream); + Expression maxSize = ((SequenceEntry)entry).maxSize (); + if (maxSize == null) + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_sequence_tc (0, " + name + ");"); + else + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_sequence_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(maxSize) + ", " + name + ");"); + } + //stream.println (indent + name + " = " + Util.helperName (entry, true) + ".type ();"); // + return index; + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + } // helperWrite + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + SequenceEntry seq = (SequenceEntry)entry; + String length = "_len" + index++; + stream.println (indent + "int " + length + " = istream.read_long ();"); + if (seq.maxSize () != null) + { + stream.println (indent + "if (" + length + " > (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(seq.maxSize()) + "))"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + } + String seqOfName; + try + { + seqOfName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.sansArrayInfo ((String) seq.dynamicVariable(com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo)); + } + catch (NoSuchFieldException e) + { + seqOfName = seq.name (); + } + int startArray = seqOfName.indexOf ('['); + String arrayDcl = seqOfName.substring (startArray); + seqOfName = seqOfName.substring (0, startArray); + + // For interfaces having state, e.g., valuetypes. + SymtabEntry seqOfEntry = (SymtabEntry) com.sun.tools.corba.ee.idl.toJavaPortable.Util.symbolTable.get (seqOfName.replace ('.', '/')); + if (seqOfEntry != null && seqOfEntry instanceof InterfaceEntry && ((InterfaceEntry)seqOfEntry).state () != null) + // Remove -stateful feature; javaStatefulName() obsolete. + //seqOfName = Util.javaStatefulName ((InterfaceEntry)seqOfEntry); + seqOfName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName((InterfaceEntry) seqOfEntry); + + arrayDcl = arrayDcl.substring (2); + stream.println (indent + name + " = new " + seqOfName + '[' + length + ']' + arrayDcl + ';'); + if (seq.type () instanceof PrimitiveEntry) + // Check for CORBA::Principal, too + //if (seq.type ().name ().equals ("any") || seq.type ().name ().equals ("TypeCode")) + if (seq.type ().name ().equals ("any") || + seq.type ().name ().equals ("TypeCode") || + seq.type ().name ().equals ("Principal")) + { + String loopIndex = "_o" + index; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + " " + name + '[' + loopIndex + "] = istream.read_" + seq.type ().name () + " ();"); + } + else + { // special case for ValueBox: if name is "xxx tmp", drop xxx + String varName = name; + int nameIndex = varName.indexOf (' '); + if ( nameIndex != -1 ) + varName = varName.substring( nameIndex + 1 ); + stream.println (indent + "istream.read_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.collapseName(entry.type().name()) + "_array (" + varName + ", 0, " + length + ");"); + } + else if (entry.type () instanceof StringEntry) + { + String loopIndex = "_o" + index; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + " " + name + '[' + loopIndex + "] = istream.read_" + seq.type ().name () + " ();"); + } + else if (entry.type () instanceof SequenceEntry) + { + String loopIndex = "_o" + index; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + '{'); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)seq.type ().generator ()).read (index, indent + " ", name + '[' + loopIndex + ']', seq.type (), stream); + stream.println (indent + '}'); + } + else + { // special case for ValueBox: if name is "xxx tmp", drop xxx + String varName = name; + int nameIndex = varName.indexOf (' '); + if ( nameIndex != -1 ) + varName = varName.substring( nameIndex + 1 ); + String loopIndex = "_o" + index; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + varName + ".length; ++" + loopIndex + ')'); + stream.println (indent + " " + varName + '[' + loopIndex + "] = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(seq.type(), true) + ".read (istream);"); // + } + return index; + } // read + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + SequenceEntry seq = (SequenceEntry)entry; + if (seq.maxSize () != null) + { + stream.println (indent + "if (" + name + ".length > (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(seq.maxSize()) + "))"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + } + stream.println (indent + "ostream.write_long (" + name + ".length);"); + if (entry.type () instanceof PrimitiveEntry) + // Check for CORBA::Principal, too. + //if (entry.type ().name ().equals ("any") || entry.type ().name ().equals ("TypeCode")) + if (entry.type ().name ().equals ("any") || + entry.type ().name ().equals ("TypeCode") || + entry.type ().name ().equals ("Principal")) + { + String loopIndex = "_i" + index++; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + " ostream.write_" + seq.type ().name () + " (" + name + '[' + loopIndex + "]);"); + } + else + stream.println (indent + "ostream.write_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.collapseName(entry.type().name()) + "_array (" + name + ", 0, " + name + ".length);"); + else if (entry.type () instanceof StringEntry) + { + String loopIndex = "_i" + index++; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + " ostream.write_" + seq.type ().name () + " (" + name + '[' + loopIndex + "]);"); + } + else if (entry.type () instanceof SequenceEntry) + { + String loopIndex = "_i" + index++; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + '{'); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)seq.type ().generator ()).write (index, indent + " ", name + '[' + loopIndex + ']', seq.type (), stream); + stream.println (indent + '}'); + } + else + { + String loopIndex = "_i" + index++; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < " + name + ".length; ++" + loopIndex + ')'); + stream.println (indent + " " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(seq.type(), true) + ".write (ostream, " + name + '[' + loopIndex + "]);"); // + } + return index; + } // write + + // From JavaGenerator + /////////////// +} // class SequenceGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Skeleton.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Skeleton.java new file mode 100644 index 000000000..5af283b80 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Skeleton.java @@ -0,0 +1,542 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -F46082.51 Remove -stateful feature; javaStatefulName() obsolete. +// -D57147 Make _Tie implement org.omg.CORBA.portable.InvokeHandler +// -D58037 Make _Tie delegate to Operations interface +// -D62739 no TIE for values that support abstract interfaces, etc. + +import java.io.PrintWriter; + +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.AttributeEntry; +import com.sun.tools.corba.ee.idl.GenFileStream; + +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +/** + * + **/ +public class Skeleton implements AuxGen +{ + private com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier skeletonNameModifier ; + private com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier tieNameModifier ; + + public Skeleton () + { + } + + public void generate (Hashtable symbolTable, SymtabEntry entry) + { + // + // Per Simon, 5-12-99, don't generate TIE or Skeleton for + // + // 1) valuetypes supporting abstract interfaces + // 2) valuetypes with no supports. + // 3) abstract interfaces + // + if (entry instanceof ValueEntry) + { + ValueEntry v = (ValueEntry) entry; + if ((v.supports ().size () == 0) || + ((InterfaceEntry) v.supports ().elementAt (0)).isAbstract ()) { + return; + } + } + if (((InterfaceEntry) entry).isAbstract ()) { + return; + } + // + + this.symbolTable = symbolTable; + + this.i = (InterfaceEntry)entry; + init (); + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + tie = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).TIEServer ; + poa = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).POAServer ; + + skeletonNameModifier = + ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).skeletonNameModifier ; + tieNameModifier = + ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).tieNameModifier ; + + tieClassName = tieNameModifier.makeName( i.name() ) ; + skeletonClassName = skeletonNameModifier.makeName( i.name() ) ; + + intfName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(i); + // for valuetype, get the name of the interface the valuetype supports + if (i instanceof ValueEntry) + { + ValueEntry v = (ValueEntry) i; + InterfaceEntry intf = (InterfaceEntry) v.supports ().elementAt (0); + intfName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(intf); + } + } // init + + protected void openStream () + { + if (tie) + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(i, tieNameModifier, ".java") ; + else + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(i, skeletonNameModifier, ".java") ; + } // openStream + + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, i, com.sun.tools.corba.ee.idl.toJavaPortable.Util.StubFile); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + if (i.comment () != null) + i.comment ().generate ("", stream); + writeClassDeclaration (); + stream.println ('{'); + stream.println (); + } // writeHeading + + protected void writeClassDeclaration () + { + if (tie){ + stream.println ("public class " + tieClassName + + " extends " + skeletonClassName ) ; + } else { + if (poa) { + stream.println ("public abstract class " + skeletonClassName + + " extends org.omg.PortableServer.Servant"); + stream.print (" implements " + intfName + "Operations, "); + stream.println ("org.omg.CORBA.portable.InvokeHandler"); + } else { + stream.println ("public abstract class " + skeletonClassName + + " extends org.omg.CORBA.portable.ObjectImpl"); + stream.print (" implements " + intfName + ", "); + stream.println ("org.omg.CORBA.portable.InvokeHandler"); + } + } + } // writeClassDeclaration + + /** + * + **/ + protected void writeBody () + { + // Remove -stateful feature. ????? + //if (i.state () != null) + // writeState (); + writeCtors (); + if (i instanceof ValueEntry) + { + // use the interface the valuetype supports to generate the + // tie class instead of using the valuetype itself + ValueEntry v = (ValueEntry) i; + this.i = (InterfaceEntry) v.supports ().elementAt (0); + } + buildMethodList (); + //DispatchMethod and MethodTable + if (tie){ //Concrete class implementing the remote interface + //The logic is here for future use + if (poa) { + writeMethods (); + stream.println (" private " + intfName + "Operations _impl;"); + stream.println (" private org.omg.PortableServer.POA _poa;"); + } else { + writeMethods (); + stream.println (" private " + intfName + "Operations _impl;"); + } + } else { //Both POA and ImplBase are abstract InvokeHandler + //The logic is here for future use + if (poa) { + writeMethodTable (); + writeDispatchMethod (); + writeCORBAOperations (); + } else { + writeMethodTable (); + writeDispatchMethod (); + writeCORBAOperations (); + } + } + //legacy !! + writeOperations (); + } // writeBody + + /** + * Close the skeleton class. The singleton ORB member is + * necessary only for portable skeletons. + **/ + protected void writeClosing () + { + stream.println (); + if (tie){ + stream.println ("} // class " + tieClassName); + } else { + stream.println ("} // class " + skeletonClassName); + } + } // writeClosing + + /** + * Close the print stream, which flushes the stream to file. + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + protected void writeCtors () + { + stream.println (" // Constructors"); + // Empty argument constructors + if (!poa) { + if (tie){ + stream.println (" public " + tieClassName + " ()"); + stream.println (" {"); + stream.println (" }"); + } else { + stream.println (" public " + skeletonClassName + " ()"); + stream.println (" {"); + stream.println (" }"); + } + } + stream.println (); + // Argumented constructors + if (tie){ + if (poa) { + //Write constructors + writePOATieCtors(); + //Write state setters and getters + writePOATieFieldAccessMethods(); + } else { + stream.println (" public " + tieClassName + + " (" + intfName + "Operations impl)"); + stream.println (" {"); + // Does it derive from a interface having state, e.g., valuetype? + if (((InterfaceEntry)i.derivedFrom ().firstElement ()).state () != null) + stream.println (" super (impl);"); + else + stream.println (" super ();"); + stream.println (" _impl = impl;"); + stream.println (" }"); + stream.println (); + } + } else { //Skeleton is not Tie so it has no constructors. + if (poa) { + } else { + } + } + + } // writeCtors + + + private void writePOATieCtors(){ + //First constructor + stream.println (" public " + tieClassName + " ( " + intfName + "Operations delegate ) {"); + stream.println (" this._impl = delegate;"); + stream.println (" }"); + //Second constructor specifying default poa. + stream.println (" public " + tieClassName + " ( " + intfName + + "Operations delegate , org.omg.PortableServer.POA poa ) {"); + stream.println (" this._impl = delegate;"); + stream.println (" this._poa = poa;"); + stream.println (" }"); + } + + private void writePOATieFieldAccessMethods(){ + //Getting delegate + stream.println (" public " + intfName+ "Operations _delegate() {"); + stream.println (" return this._impl;"); + stream.println (" }"); + //Setting delegate + stream.println (" public void _delegate (" + intfName + "Operations delegate ) {"); + stream.println (" this._impl = delegate;"); + stream.println (" }"); + //Overriding default poa + stream.println (" public org.omg.PortableServer.POA _default_POA() {"); + stream.println (" if(_poa != null) {"); + stream.println (" return _poa;"); + stream.println (" }"); + stream.println (" else {"); + stream.println (" return super._default_POA();"); + stream.println (" }"); + stream.println (" }"); + } + + /** + * Build a list of all of the methods, keeping out duplicates. + **/ + protected void buildMethodList () + { + // Start from scratch + methodList = new Vector (); + + buildMethodList (i); + } // buildMethodList + + /** + * + **/ + private void buildMethodList (InterfaceEntry entry) + { + // Add the local methods + Enumeration locals = entry.methods ().elements (); + while (locals.hasMoreElements ()) + addMethod ((MethodEntry)locals.nextElement ()); + + // Add the inherited methods + Enumeration parents = entry.derivedFrom ().elements (); + while (parents.hasMoreElements ()) + { + InterfaceEntry parent = (InterfaceEntry)parents.nextElement (); + if (!parent.name ().equals ("Object")) + buildMethodList (parent); + } + } // buildMethodList + + /** + * + **/ + private void addMethod (MethodEntry method) + { + if (!methodList.contains (method)) + methodList.addElement (method); + } // addMethod + + /** + * + **/ + protected void writeDispatchMethod () + { + String indent = " "; + stream.println (" public org.omg.CORBA.portable.OutputStream _invoke (String $method,"); + stream.println (indent + "org.omg.CORBA.portable.InputStream in,"); + stream.println (indent + "org.omg.CORBA.portable.ResponseHandler $rh)"); + stream.println (" {"); + + // this is a special case code generation for cases servantLocator and + // servantActivator, where OMG is taking too long to define them + // as local objects + + boolean isLocalInterface = false; + if (i instanceof InterfaceEntry) { + isLocalInterface = i.isLocalServant(); + } + + if (!isLocalInterface) { + // Per Simon 8/26/98, create and return reply stream for all methods - KLR + stream.println (" org.omg.CORBA.portable.OutputStream out = null;"); + stream.println (" java.lang.Integer __method = _methods.get($method);"); + stream.println (" if (__method == null)"); + stream.println (" throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + stream.println (); + if (methodList.size () > 0) + { + stream.println (" switch (__method.intValue ())"); + stream.println (" {"); + + // Write the method case statements + int realI = 0; + for (int i = 0; i < methodList.size (); ++i) + { + MethodEntry method = (MethodEntry)methodList.elementAt (i); + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)method.generator ()).dispatchSkeleton (symbolTable, method, stream, realI); + if (method instanceof AttributeEntry && !((AttributeEntry)method).readOnly ()) + realI += 2; + else + ++realI; + } + + indent = " "; + stream.println (indent + "default:"); + stream.println (indent + " throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + stream.println (" }"); + stream.println (); + } + stream.println (" return out;"); + } else { + stream.println(" throw new org.omg.CORBA.BAD_OPERATION();"); + } + stream.println (" } // _invoke"); + stream.println (); + } // writeDispatchMethod + + /** + * + **/ + protected void writeMethodTable () + { + // Write the methods hashtable + stream.println (" private static java.util.Map _methods = new java.util.HashMap ();"); + stream.println (" static"); + stream.println (" {"); + + int count = -1; + Enumeration e = methodList.elements (); + while (e.hasMoreElements ()) + { + MethodEntry method = (MethodEntry)e.nextElement (); + if (method instanceof AttributeEntry) + { + stream.println (" _methods.put (\"_get_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(method.name()) + "\", " + (++count) + ");"); + if (!((AttributeEntry)method).readOnly ()) + stream.println (" _methods.put (\"_set_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(method.name()) + "\", " + (++count) + ");"); + } + else + stream.println (" _methods.put (\"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(method.name()) + "\", " + (++count) + ");"); + } + stream.println (" }"); + stream.println (); + } // writeMethodTable + + /** + * + **/ + protected void writeMethods () + { + int realI = 0; + for (int i = 0; i < methodList.size (); ++i) + { + MethodEntry method = (MethodEntry)methodList.elementAt (i); + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)method.generator ()).skeleton + (symbolTable, method, stream, realI); + if (method instanceof AttributeEntry && + !((AttributeEntry)method).readOnly ()) + realI += 2; + else + ++realI; + stream.println (); + } + } // writeMethods + + /** + * + **/ + private void writeIDs () + { + Vector list = new Vector (); + buildIDList (i, list); + Enumeration e = list.elements (); + boolean first = true; + while (e.hasMoreElements ()) + { + if (first) + first = false; + else + stream.println (", "); + stream.print (" \"" + (String)e.nextElement () + '"'); + } + } // writeIDs + + /** + * + **/ + private void buildIDList (InterfaceEntry entry, Vector list) + { + if (!entry.fullName ().equals ("org/omg/CORBA/Object")) + { + String id = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscoresFromID(entry.repositoryID().ID()); + if (!list.contains (id)) + list.addElement (id); + Enumeration e = entry.derivedFrom ().elements (); + while (e.hasMoreElements ()) + buildIDList ((InterfaceEntry)e.nextElement (), list); + } + } // buildIDList + + /** + * + **/ + protected void writeCORBAOperations () + { + stream.println (" // Type-specific CORBA::Object operations"); + + stream.println (" private static String[] __ids = {"); + writeIDs (); + stream.println ("};"); + stream.println (); + if (poa) + writePOACORBAOperations(); + else + writeNonPOACORBAOperations(); + + } // writeCORBAOperations + + protected void writePOACORBAOperations(){ + stream.println (" public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)"); + //Right now, with our POA implementation, the same + //implementation of _ids() type methods seem to work for both non-POA + //as well as POA servers. We need to REVISIT since the equivalent + //POA interface, i.e. _all_interfaces, has parameters which are not being + //used in the _ids() implementation. + stream.println (" {"); + stream.println (" return (String[])__ids.clone ();"); + stream.println (" }"); + stream.println (); + //_this() + stream.println (" public "+ i.name() +" _this() "); + stream.println (" {"); + stream.println (" return "+ i.name() +"Helper.narrow(" ); + stream.println (" super._this_object());"); + stream.println (" }"); + stream.println (); + //_this(org.omg.CORBA.ORB orb) + stream.println (" public "+ i.name() +" _this(org.omg.CORBA.ORB orb) "); + stream.println (" {"); + stream.println (" return "+ i.name() +"Helper.narrow(" ); + stream.println (" super._this_object(orb));"); + stream.println (" }"); + stream.println (); + } + protected void writeNonPOACORBAOperations(){ + stream.println (" public String[] _ids ()"); + stream.println (" {"); + stream.println (" return (String[])__ids.clone ();"); + stream.println (" }"); + stream.println (); + } + /** + * + **/ + protected void writeOperations () + { + // _get_ids removed at Simon's request 8/26/98 - KLR + } // writeOperations + + protected Hashtable symbolTable = null; + protected InterfaceEntry i = null; + protected PrintWriter stream = null; + + // Unique to this generator + protected String tieClassName = null; + protected String skeletonClassName = null; + protected boolean tie = false; + protected boolean poa = false; + protected Vector methodList = null; + protected String intfName = ""; +} // class Skeleton + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/StringGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/StringGen.java new file mode 100644 index 000000000..f766ad23c --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/StringGen.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D61056 Use Util.helperName + +import java.io.PrintWriter; +import java.util.Hashtable; + +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +/** + * Handles generation of CORBA strings as well as wstrings. Be careful + * not to forget the wstrings. + **/ +public class StringGen implements com.sun.tools.corba.ee.idl.StringGen, JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public StringGen () + { + } // ctor + + /** + * This should never be called. This class exists for the + * JavaGenerator interface. + **/ + public void generate (Hashtable symbolTable, StringEntry e, PrintWriter stream) + { + } // generate + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + return type(index, indent, tcoffsets, name, entry, stream); + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + tcoffsets.set (entry); + StringEntry stringEntry = (StringEntry)entry; + String bound; + if (stringEntry.maxSize () == null) + bound = "0"; + else + bound = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(stringEntry.maxSize()); + + // entry.name() is necessary to determine whether it is a + // string or wstring + + stream.println (indent + + name + + " = org.omg.CORBA.ORB.init ().create_" + + entry.name() + + "_tc (" + + bound + ");"); + return index; + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + } // helperWrite + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + StringEntry string = (StringEntry)entry; + String entryName = entry.name (); + if (entryName.equals ("string")) + stream.println (indent + name + " = istream.read_string ();"); + else if (entryName.equals ("wstring")) + stream.println (indent + name + " = istream.read_wstring ();"); + if (string.maxSize () != null) + { + stream.println (indent + "if (" + name + ".length () > (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(string.maxSize()) + "))"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + } + return index; + } // read + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + StringEntry string = (StringEntry)entry; + if (string.maxSize () != null) + { + stream.print (indent + "if (" + name + ".length () > (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(string.maxSize()) + "))"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + } + String entryName = entry.name (); + if (entryName.equals ("string")) + stream.println (indent + "ostream.write_string (" + name + ");"); + else if (entryName.equals ("wstring")) + stream.println (indent + "ostream.write_wstring (" + name + ");"); + return index; + } // write + + // From JavaGenerator + /////////////// +} // class StringGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/StructGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/StructGen.java new file mode 100644 index 000000000..c4aaa15c8 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/StructGen.java @@ -0,0 +1,429 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// - Think about arrays (and sequences?) as members +// - A sequence must be converted to an array, but a memory of the +// max size must be retained. +// - After demarshalling an IOR, think about how to deal with the exceptions. +// - The demarshall method should be throwing a ClientException, +// but should it, really? +// -D60929 Update for RTF2.4 changes +// -D61056 Use Util.helperName +// -D62023 Use corbaLevel in read/write generation +// -D59437 Modify read() to enit qualified name of value box helper. + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.StructEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; + +/** + * + **/ +public class StructGen implements com.sun.tools.corba.ee.idl.StructGen, com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public StructGen () + { + } // ctor + + /** + * Constructor for ExceptionGen. + **/ + protected StructGen (boolean exception) + { + thisIsReallyAnException = exception; + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, StructEntry s, PrintWriter str) + { + this.symbolTable = symbolTable; + this.s = s; + //init (); + + openStream (); + if (stream == null) + return; + generateHelper (); + generateHolder (); + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + generateContainedTypes (); + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + } // init + + /** + * + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(s, ".java"); + } // openStream + + /** + * + **/ + protected void generateHelper () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, s); + } // generateHelper + + /** + * + **/ + protected void generateHolder () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, s); + } // generateHolder + + /** + * + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, s); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + if (s.comment () != null) + s.comment ().generate ("", stream); + + stream.print ("public final class " + s.name ()); + if (thisIsReallyAnException) + stream.print (" extends org.omg.CORBA.UserException"); + else + stream.print(" implements org.omg.CORBA.portable.IDLEntity"); + stream.println (); + stream.println ("{"); + } // writeHeading + + /** + * + **/ + protected void writeBody () + { + writeMembers (); + writeCtors (); + } // writeBody + + /** + * + **/ + protected void writeClosing () + { + stream.println ("} // class " + s.name ()); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /** + * + **/ + protected void generateContainedTypes () + { + // Generate all of the contained types + Enumeration e = s.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry entry = (SymtabEntry)e.nextElement (); + + // Don't generate contained entries if they are sequences. + // Sequences are unnamed and since they translate to arrays, + // no classes are generated for them, not even holders in this + // case since they cannot be accessed outside of this struct. + + if (!(entry instanceof SequenceEntry)) + entry.generate (symbolTable, stream); + } + } // generateContainedTypes + + /** + * + **/ + protected void writeMembers () + { + // Write members and populate quality arrays + int size = s.members ().size (); + memberIsPrimitive = new boolean [size]; + memberIsInterface = new boolean [size]; + memberIsTypedef = new boolean [size]; + for (int i = 0; i < s.members ().size (); ++i) + { + SymtabEntry member = (SymtabEntry)s.members ().elementAt (i); + memberIsPrimitive[i] = member.type () instanceof PrimitiveEntry; + memberIsInterface[i] = member.type () instanceof InterfaceEntry; + memberIsTypedef[i] = member.type () instanceof TypedefEntry; + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(member); + // Transfer member comment to target <31jul1997>. + if (member.comment () != null) + member.comment ().generate (" ", stream); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(" public ", member.name(), "", member, stream); + } + } // writeMembers + + /** + * + **/ + protected void writeCtors () + { + // Write default ctor + stream.println (); + stream.println (" public " + s.name () + " ()"); + stream.println (" {"); + // fixed mapping for exceptions + if (thisIsReallyAnException) + stream.println (" super(" + s.name() + "Helper.id());"); + stream.println (" } // ctor"); + writeInitializationCtor(true); + if (thisIsReallyAnException) { + // for exception according to mapping we should always + // have a full constructor + writeInitializationCtor(false); + } + } + + private void writeInitializationCtor(boolean init) + { + // Write initialization ctor + if (!init || (s.members ().size () > 0)) + { + stream.println (); + stream.print (" public " + s.name () + " ("); + boolean firstTime = true; + if (!init) { + stream.print ("String $reason"); + firstTime = false; + } + + for (int i = 0; i < s.members ().size (); ++i) + { + SymtabEntry member = (SymtabEntry)s.members ().elementAt (i); + if (firstTime) + firstTime = false; + else + stream.print (", "); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(member) + " _" + member.name ()); + } + stream.println (")"); + stream.println (" {"); + // fixed mapping for exceptions + if (thisIsReallyAnException) { + if (init) + stream.println (" super(" + s.name() + "Helper.id());"); + else + stream.println (" super(" + s.name() + "Helper.id() + \" \" + $reason);"); + } + for (int i = 0; i < s.members ().size (); ++i) + { + SymtabEntry member = (SymtabEntry)s.members ().elementAt (i); + stream.println (" " + member.name () + " = _" + member.name () + ";"); + } + stream.println (" } // ctor"); + } + stream.println (); + } // writeInitializationCtor + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets innerOffsets = new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(); + innerOffsets.set (entry); + int offsetForStruct = innerOffsets.currentOffset (); + StructEntry s = (StructEntry)entry; + String membersName = "_members" + index++; + stream.println (indent + "org.omg.CORBA.StructMember[] " + membersName + " = new org.omg.CORBA.StructMember [" + s.members ().size () + "];"); + String tcOfMembers = "_tcOf" + membersName; + stream.println (indent + "org.omg.CORBA.TypeCode " + tcOfMembers + " = null;"); + for (int i = 0; i < s.members ().size (); ++i) + { + TypedefEntry member = (TypedefEntry)s.members ().elementAt (i); + String memberName = member.name (); + // Generate and assign member TypeCode to tcofMembers + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).type (index, indent, innerOffsets, tcOfMembers, member, stream); + stream.println (indent + membersName + '[' + i + "] = new org.omg.CORBA.StructMember ("); + stream.println (indent + " \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(memberName) + "\","); + stream.println (indent + " " + tcOfMembers + ','); + stream.println (indent + " null);"); + int offsetSoFar = innerOffsets.currentOffset (); + innerOffsets = new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(); + innerOffsets.set (entry); + innerOffsets.bumpCurrentOffset (offsetSoFar - offsetForStruct); + + } + tcoffsets.bumpCurrentOffset (innerOffsets.currentOffset ()); + // <54697> + //stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_struct_tc (id (), \"" + Util.stripLeadingUnderscores (entry.name ()) + "\", " + membersName + ");"); + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_" + (thisIsReallyAnException ? "exception" : "struct") + "_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(s, true) + ".id (), \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(entry.name()) + "\", " + membersName + ");"); // + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); // + return index; + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + stream.println (" " + entryName + " value = new " + entryName + " ();"); + read (0, " ", "value", entry, stream); + stream.println (" return value;"); + } // helperRead + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + if (thisIsReallyAnException) + { + stream.println (indent + "// read and discard the repository ID"); + stream.println (indent + "istream.read_string ();"); + } + + Enumeration e = ((StructEntry)entry).members ().elements (); + while (e.hasMoreElements ()) + { + TypedefEntry member = (TypedefEntry)e.nextElement (); + SymtabEntry mType = member.type (); + + if (!member.arrayInfo ().isEmpty () || mType instanceof SequenceEntry || + mType instanceof PrimitiveEntry || mType instanceof StringEntry || + mType instanceof TypedefEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).read (index, indent, name + '.' + member.name (), member, stream); + else if (mType instanceof ValueBoxEntry) + { + // call read_value instead of Helper.read for the value + Vector st = ((ValueBoxEntry) mType).state (); + TypedefEntry vbMember = ((InterfaceState) st.elementAt (0)).entry; + SymtabEntry vbType = vbMember.type (); + + String jName = null; + String jHelper = null; + + if (vbType instanceof SequenceEntry || vbType instanceof StringEntry || + !vbMember.arrayInfo ().isEmpty ()) + { + jName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(vbType); // name of mapped Java type + // REVISIT. Typename info. now correct for value boxes, so + // these two cases may be obsolete. See UnionGen.read(). + //jHelper = Util.helperName (vbType, false); // + jHelper = com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true); + } + else + { + jName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType); // name of mapped Java class + // + //jHelper = Util.helperName (mType, false); // + jHelper = com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true); + } + // Call xHelper.read() for valueboxes for RTF2.4 + if (com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) + stream.println (indent + name + '.' + member.name () + " = (" + jName + ") " + jHelper + ".read (istream);"); + else + stream.println (indent + name + '.' + member.name () + " = (" + jName + ") ((org.omg.CORBA_2_3.portable.InputStream)istream).read_value (" + jHelper + ".get_instance ());"); // + } + // for corbaLevel 2.4 and up, use Helper.read like + // everything else + else if ((mType instanceof ValueEntry) && + !com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) // + { + // call read_value instead of Helper.read for the value + stream.println (indent + name + '.' + member.name () + " = (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType) + ") ((org.omg.CORBA_2_3.portable.InputStream)istream).read_value (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, false) + ".get_instance ());"); // // + } + else + stream.println (indent + name + '.' + member.name () + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(member.type(), true) + ".read (istream);"); // + } + return index; + } // read + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + write (0, " ", "value", entry, stream); + } // helperWrite + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + if (thisIsReallyAnException) + { + stream.println (indent + "// write the repository ID"); + stream.println (indent + "ostream.write_string (id ());"); + } + + Vector members = ((StructEntry)entry).members (); + for (int i = 0; i < members.size (); ++i) + { + TypedefEntry member = (TypedefEntry)members.elementAt (i); + SymtabEntry mType = member.type (); + + if (!member.arrayInfo ().isEmpty () || mType instanceof SequenceEntry || + mType instanceof TypedefEntry || mType instanceof PrimitiveEntry || + mType instanceof StringEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, " ", name + '.' + member.name (), member, stream); + + // for corbaLevel 2.4 and up, use Helper.write like + // everything else + else if ((mType instanceof ValueEntry || mType instanceof ValueBoxEntry) + && !com.sun.tools.corba.ee.idl.toJavaPortable.Util.corbaLevel(2.4f, 99.0f)) { // + stream.println (indent + "((org.omg.CORBA_2_3.portable.OutputStream)ostream).write_value ((java.io.Serializable) " // + + name + '.' + member.name () + ", " + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(member.type(), true) // + + ".get_instance ());"); // + } + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(member.type(), true) + ".write (ostream, " + name + '.' + member.name () + ");"); // + } + return index; + } // write + + // From JavaGenerator + /////////////// + + protected Hashtable symbolTable = null; + protected StructEntry s = null; + protected PrintWriter stream = null; + + protected boolean thisIsReallyAnException = false; + private boolean[] memberIsPrimitive; + private boolean[] memberIsInterface; + private boolean[] memberIsTypedef; +} // class StructGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Stub.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Stub.java new file mode 100644 index 000000000..32a746ea7 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Stub.java @@ -0,0 +1,356 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import com.sun.tools.corba.ee.idl.AttributeEntry; +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; + +import java.io.File; +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * + **/ +public class Stub implements AuxGen +{ + /** + * Public zero-argument constructor. + **/ + public Stub () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, SymtabEntry entry) + { + this.symbolTable = symbolTable; + this.i = (InterfaceEntry)entry; + this.localStub = i.isLocalServant(); + this.isAbstract = i.isAbstract( ); + init (); + + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize unique members of this generator. + **/ + protected void init () + { + classSuffix = "Stub"; + } // init + + /** + * + **/ + protected void openStream () + { + String name = '_' + i.name () + classSuffix; + String pkg = com.sun.tools.corba.ee.idl.toJavaPortable.Util.containerFullName(i.container()); + if (pkg != null && !pkg.equals ("")) + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.mkdir(pkg); + name = pkg + '/' + name; + } + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.getStream(name.replace('/', File.separatorChar) + ".java", i); + } // openStream + + /** + * + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, i, com.sun.tools.corba.ee.idl.toJavaPortable.Util.StubFile); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + // Transfer interface comment to target <31jul1997>. + if (i.comment () != null) + i.comment ().generate ("", stream); + + writeClassDeclaration (); + stream.println ('{'); + } // writeHeading + + /** + * + **/ + protected void writeClassDeclaration () + { + stream.print ("public class _" + i.name () + classSuffix + " extends org.omg.CORBA.portable.ObjectImpl"); + stream.println (" implements " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(i)); + } // writeClassDeclaration + + /** + * Steps done within writeBody include: + * 1.) makeCtors (); + * 2.) buildMethodList (); + * 3.) makeMethods (); + * 4.) makeCORBAObjectMethods () + **/ + protected void writeBody () + { + writeCtors (); + buildMethodList (); + writeMethods (); + writeCORBAObjectMethods (); + writeSerializationMethods (); + } // writeBody + + /** + * + **/ + protected void writeClosing () + { + stream.println ("} // class _" + i.name () + classSuffix); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /** + * + **/ + protected void writeCtors () + { + String name = i.name (); + + /*** the constructors are not generated as per ptc/00-01-08.pdf + * since these are non-standard APIs, and same can be accomplished + * programatically, we need to comment this out, in order to + * be able to generate standard stubs + */ + + /************* + stream.println (" // Constructors"); + stream.println (" // NOTE: If the default constructor is used, the"); + stream.println (" // object is useless until _set_delegate (...)"); + stream.println (" // is called."); + stream.println (" public _" + name + classSuffix + " ()"); + stream.println (" {"); + stream.println (" super ();"); + stream.println (" }"); + stream.println (); + stream.println (" public _" + name + classSuffix + " (org.omg.CORBA.portable.Delegate delegate)"); + stream.println (" {"); + stream.println (" super ();"); + stream.println (" _set_delegate (delegate);"); + stream.println (" }"); + ***************/ + // This is confusing since we have localOptimization flag as well. + // We have left this code because JCK team filed a P1 bug for changing + // _opsClass to $opsClass. Will clean it up in Tiger + // _REVISIT_ (Hemanth 03/05/2002) + if (localStub) { + stream.println (" final public static java.lang.Class _opsClass = " + + name + "Operations.class;"); + stream.println (); + } + stream.println (); + } // writeCtors + + /** + * Build a list of all of the methods, keeping out duplicates. + **/ + protected void buildMethodList () + { + // Start from scratch + methodList = new Vector (); + + buildMethodList (i); + } // buildMethodList + + /** + * + **/ + private void buildMethodList (InterfaceEntry entry) + { + // Add the local methods + Enumeration locals = entry.methods ().elements (); + while (locals.hasMoreElements ()) + addMethod ((MethodEntry)locals.nextElement ()); + + // Add the inherited methods + Enumeration parents = entry.derivedFrom ().elements (); + while (parents.hasMoreElements ()) + { + InterfaceEntry parent = (InterfaceEntry)parents.nextElement (); + if (!parent.name ().equals ("Object")) + buildMethodList (parent); + } + } // buildMethodList + + /** + * + **/ + private void addMethod (MethodEntry method) + { + if (!methodList.contains (method)) + methodList.addElement (method); + } // addMethod + + /** + * + **/ + protected void writeMethods () + { + // Count the methods, attributes which are not readonly are + // counted as 2 methods. + int count = methodList.size (); + Enumeration e = methodList.elements (); + while (e.hasMoreElements ()) + { + Object method = e.nextElement (); + if (method instanceof AttributeEntry && !((AttributeEntry)method).readOnly ()) + ++count; + } + + if( (((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).LocalOptimization ) + && !isAbstract ) + { + stream.println( " final public static java.lang.Class _opsClass =" ); + stream.println( " " + this.i.name() + "Operations.class;" ); + } + + // Write the methods + int realI = 0; + for (int i = 0; i < methodList.size (); ++i) + { + MethodEntry method = (MethodEntry)methodList.elementAt (i); + if (!localStub) { + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)method.generator ()).stub (this.i.name(), isAbstract, symbolTable, method, stream, realI); + } else { + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)method.generator ()).localstub (symbolTable, method, stream, realI, this.i); + } + if (method instanceof AttributeEntry && !((AttributeEntry)method).readOnly ()) + realI += 2; + else + ++realI; + } + } // writeMethods + + /** + * + **/ + private void buildIDList (InterfaceEntry entry, Vector list) + { + if (!entry.fullName ().equals ("org/omg/CORBA/Object")) + { + String id = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscoresFromID(entry.repositoryID().ID()); + if (!list.contains (id)) + list.addElement (id); + Enumeration e = entry.derivedFrom ().elements (); + while (e.hasMoreElements ()) + buildIDList ((InterfaceEntry)e.nextElement (), list); + } + } // buildIDList + + /** + * + **/ + private void writeIDs () + { + Vector list = new Vector (); + buildIDList (i, list); + Enumeration e = list.elements (); + boolean first = true; + while (e.hasMoreElements ()) + { + if (first) + first = false; + else + stream.println (", "); + stream.print (" \"" + (String)e.nextElement () + '"'); + } + } // writeIDs + + /** + * + **/ + protected void writeCORBAObjectMethods () + { + stream.println (" // Type-specific CORBA::Object operations"); + stream.println (" private static String[] __ids = {"); + writeIDs (); + stream.println ("};"); + stream.println (); + stream.println (" public String[] _ids ()"); + stream.println (" {"); + stream.println (" return (String[])__ids.clone ();"); + stream.println (" }"); + stream.println (); + } // writeCORBAObjectMethods + + /** + * + **/ + protected void writeSerializationMethods () + { + stream.println (" private void readObject (java.io.ObjectInputStream s) throws java.io.IOException"); + stream.println (" {"); + stream.println (" String str = s.readUTF ();"); + stream.println (" String[] args = null;"); + stream.println (" java.util.Properties props = null;"); + stream.println (" org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);"); + stream.println (" try {"); + stream.println (" org.omg.CORBA.Object obj = orb.string_to_object (str);"); + stream.println (" org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate ();"); + stream.println (" _set_delegate (delegate);"); + stream.println (" } finally {"); + stream.println (" orb.destroy() ;"); + stream.println (" }"); + stream.println (" }"); + stream.println (); + stream.println (" private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException"); + stream.println (" {"); + stream.println (" String[] args = null;"); + stream.println (" java.util.Properties props = null;"); + stream.println (" org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);"); + stream.println (" try {"); + stream.println (" String str = orb.object_to_string (this);"); + stream.println (" s.writeUTF (str);"); + stream.println (" } finally {"); + stream.println (" orb.destroy() ;"); + stream.println (" }"); + stream.println (" }"); + } + + protected Hashtable symbolTable = null; + protected InterfaceEntry i = null; + protected PrintWriter stream = null; + + // Unique to this generator + protected Vector methodList = null; + protected String classSuffix = ""; + protected boolean localStub = false; + private boolean isAbstract = false; +} // class Stub diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/TCOffsets.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/TCOffsets.java new file mode 100644 index 000000000..f07aeeeea --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/TCOffsets.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: + +import java.util.Enumeration; +import java.util.Hashtable; + +// This class is passed through the JavaGenerator.HelperType methods. +// It is ONLY used when a recursive sequence is detected. ie. +// +// struct S1 +// { +// sequence others; +// }; + +/** + * + **/ +public class TCOffsets +{ + /** + * Return -1 if the given name is not in the list of types. + **/ + public int offset (String name) + { + Integer value = (Integer)tcs.get (name); + return value == null ? -1 : value.intValue (); + } // offset + + /** + * + **/ + public void set (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + if (entry == null) + offset += 8; + else + { + tcs.put (entry.fullName (), Integer.valueOf (offset)); + offset += 4; + String repID = Util.stripLeadingUnderscoresFromID(entry.repositoryID().ID()); + if (entry instanceof com.sun.tools.corba.ee.idl.InterfaceEntry) + offset += alignStrLen (repID) + alignStrLen (entry.name ()); + else if (entry instanceof com.sun.tools.corba.ee.idl.StructEntry) + offset += alignStrLen (repID) + alignStrLen (entry.name ()) + 4; + else if (entry instanceof com.sun.tools.corba.ee.idl.UnionEntry) + offset += alignStrLen (repID) + alignStrLen (entry.name ()) + 12; + else if (entry instanceof com.sun.tools.corba.ee.idl.EnumEntry) + { + offset += alignStrLen (repID) + alignStrLen (entry.name ()) + 4; + Enumeration e = ((com.sun.tools.corba.ee.idl.EnumEntry)entry).elements ().elements (); + while (e.hasMoreElements ()) + offset += alignStrLen ((String)e.nextElement ()); + } + else if (entry instanceof com.sun.tools.corba.ee.idl.StringEntry) + offset += 4; + else if (entry instanceof com.sun.tools.corba.ee.idl.TypedefEntry) + { + offset += alignStrLen (repID) + alignStrLen (entry.name ()); + if (((com.sun.tools.corba.ee.idl.TypedefEntry)entry).arrayInfo ().size () != 0) + offset += 8; + } + } + } // set + + /** + * Return the full length of the string type: 4 byte length, x bytes for + * string + 1 for the null terminator, align it so it ends on a 4-byte + * boundary. This method assumes the string starts at a 4-byte boundary + * since it doesn't do any leading alignment. + **/ + public int alignStrLen (String string) + { + int len = string.length () + 1; + int align = 4 - (len % 4); + if (align == 4) align = 0; + return len + align + 4; + } // alignStrLen + + /** + * + **/ + public void setMember (com.sun.tools.corba.ee.idl.SymtabEntry entry) + { + offset += alignStrLen (entry.name ()); + if (((com.sun.tools.corba.ee.idl.TypedefEntry)entry).arrayInfo ().size () != 0) + offset += 4; + } // setMember + + /** + * + **/ + public int currentOffset () + { + return offset; + } // currentOffset + + /** + * + **/ + public void bumpCurrentOffset (int value) + { + offset += value; + } // bumpCurrentOffset + + private Hashtable tcs = new Hashtable (); + private int offset = 0; +} // class TCOffsets diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/TypedefGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/TypedefGen.java new file mode 100644 index 000000000..03d3643d8 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/TypedefGen.java @@ -0,0 +1,301 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -11aug1997 No modification: comments for type_defs will appear in +// helper, holder classes as a result of modifications to routines +// makeHelper(), makeHolder() in class com.sun.tools.corba.ee.idl.toJava.Util. +// -F46082.51 Remove -stateful feature; javaStatefulName() obsolete. +// -D61056 Use Util.helperName + +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.StructEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.UnionEntry; +import com.sun.tools.corba.ee.idl.constExpr.Expression; + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +// Notes: + +/** + * + **/ +public class TypedefGen implements com.sun.tools.corba.ee.idl.TypedefGen, com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public TypedefGen () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, TypedefEntry t, PrintWriter stream) + { + this.symbolTable = symbolTable; + this.t = t; + + if (t.arrayInfo ().size () > 0 || t.type () instanceof SequenceEntry) + generateHolder (); + generateHelper (); + } // generator + + /** + * + **/ + protected void generateHolder () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, t); + } + + /** + * + **/ + protected void generateHelper () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, t); + } + + /////////////// + // From JavaGenerator + + private boolean inStruct (TypedefEntry entry) + { + boolean inStruct = false; + if (entry.container () instanceof StructEntry || entry.container () instanceof UnionEntry) + inStruct = true; + else if (entry.container () instanceof InterfaceEntry) + { + InterfaceEntry i = (InterfaceEntry)entry.container (); + if (i.state () != null) + { + Enumeration e = i.state ().elements (); + while (e.hasMoreElements ()) + if (((InterfaceState)e.nextElement ()).entry == entry) + { + inStruct = true; + break; + } + } + } + return inStruct; + } // inStruct + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + TypedefEntry td = (TypedefEntry)entry; + boolean inStruct = inStruct (td); + if (inStruct) + tcoffsets.setMember (entry); + else + tcoffsets.set (entry); + + // Print the base types typecode + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)td.type ().generator ()).type (index, indent, tcoffsets, name, td.type (), stream); + + if (inStruct && td.arrayInfo ().size () != 0) + tcoffsets.bumpCurrentOffset (4); // for array length field + + // Print the array typecodes (if there are any) + int dimensions = td.arrayInfo ().size (); + for (int i = 0; i < dimensions; ++i) + { + String size = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression((Expression) td.arrayInfo().elementAt(i)); + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_array_tc (" + size + ", " + name + " );"); + } + + // If this typedef describes a struct/union member, don't put it + // in an alias typedef; otherwise that's where it belongs. + if (!inStruct) + // <54697> + //stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_alias_tc (id (), \"" + Util.stripLeadingUnderscores (td.name ()) + "\", " + name + ");"); + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_alias_tc (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(td, true) + ".id (), \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(td.name()) + "\", " + name + ");"); // + + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + // The type() method is invoked from other emitters instead of when an IDL + // typedef statement is being processed. Code generated is identical minus the + // generation of a create_alias_tc() which is required for IDL typedef's but not + // needed when typedef is being processed as a member of struct/union/valuetype. + + return helperType( index, indent, tcoffsets, name, entry, stream); + } // type + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(" ", "value", "", entry, stream); + read (0, " ", "value", entry, stream); + stream.println (" return value;"); + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + write (0, " ", "value", entry, stream); + } // helperWrite + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + TypedefEntry td = (TypedefEntry)entry; + String modifier = com.sun.tools.corba.ee.idl.toJavaPortable.Util.arrayInfo(td.arrayInfo()); + if (!modifier.equals ("")) + { + // arrayInfo is a vector of Expressions which indicate the + // number of array dimensions for this typedef. But what if + // this is a typedef of a sequence? + // The `new' statement being generated must know the full + // number of brackets. That can be found in td.info. + // For instance: + // typedef sequence A[10][10]; + // void proc (out A a); + // typeModifier = "[10][10]" + // td.info = "short[][][]"; + // The first new statement generated is: + // a.value = new short[10][][]; + // Note that the 3 sets of brackets come from td.info, not + // arrayInfo; + // The second new statement generated is: + // a.value[_i1] = new short[10][]; + // ------------ ---- ------ + // \ \ \ + // name baseName arrayDcl + int closingBrackets = 0; + String loopIndex = ""; + String baseName; + try + { + baseName = (String)td.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo); + } + catch (NoSuchFieldException e) + { + baseName = td.name (); + } + int startArray = baseName.indexOf ('['); + String arrayDcl = com.sun.tools.corba.ee.idl.toJavaPortable.Util.sansArrayInfo(baseName.substring(startArray)) + "[]"; // Add an extra set because the first gets stripped off in the loop. + baseName = baseName.substring (0, startArray); + + // For interfaces having state, e.g., valuetypes. + SymtabEntry baseEntry = (SymtabEntry) com.sun.tools.corba.ee.idl.toJavaPortable.Util.symbolTable.get (baseName.replace ('.', '/')); + if (baseEntry instanceof InterfaceEntry && ((InterfaceEntry)baseEntry).state () != null) + // Remove -stateful feature; javaStatefulName() obsolete. + //baseName = Util.javaStatefulName ((InterfaceEntry)baseEntry); + baseName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName((InterfaceEntry) baseEntry); + + int end1stArray; + while (!modifier.equals ("")) + { + int rbracket = modifier.indexOf (']'); + String size = modifier.substring (1, rbracket); + end1stArray = arrayDcl.indexOf (']'); + arrayDcl = '[' + size + arrayDcl.substring (end1stArray + 2); + stream.println (indent + name + " = new " + baseName + arrayDcl + ';'); + loopIndex = "_o" + index++; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < (" + size + "); ++" + loopIndex + ')'); + stream.println (indent + '{'); + ++closingBrackets; + modifier = modifier.substring (rbracket + 1); + indent = indent + " "; + name = name + '[' + loopIndex + ']'; + } + end1stArray = arrayDcl.indexOf (']'); + if (td.type () instanceof SequenceEntry || td.type () instanceof PrimitiveEntry || td.type () instanceof StringEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)td.type ().generator ()).read (index, indent, name, td.type (), stream); + else if (td.type () instanceof InterfaceEntry && td.type ().fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + name + " = istream.read_Object ();"); + else + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(td.type(), true) + ".read (istream);"); // + for (int i = 0; i < closingBrackets; ++i) + { + indent = indent.substring (2); + stream.println (indent + '}'); + } + } + else + { + SymtabEntry tdtype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(td.type()); + if (tdtype instanceof SequenceEntry || tdtype instanceof PrimitiveEntry || tdtype instanceof StringEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)tdtype.generator ()).read (index, indent, name, tdtype, stream); + else if (tdtype instanceof InterfaceEntry && tdtype.fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + name + " = istream.read_Object ();"); + else + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(tdtype, true) + ".read (istream);"); // + } + return index; + } // read + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + TypedefEntry td = (TypedefEntry)entry; + String modifier = com.sun.tools.corba.ee.idl.toJavaPortable.Util.arrayInfo(td.arrayInfo()); + if (!modifier.equals ("")) + { + int closingBrackets = 0; + String loopIndex = ""; + while (!modifier.equals ("")) + { + int rbracket = modifier.indexOf (']'); + String size = modifier.substring (1, rbracket); + stream.println (indent + "if (" + name + ".length != (" + size + "))"); + stream.println (indent + " throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);"); + loopIndex = "_i" + index++; + stream.println (indent + "for (int " + loopIndex + " = 0;" + loopIndex + " < (" + size + "); ++" + loopIndex + ')'); + stream.println (indent + '{'); + ++closingBrackets; + modifier = modifier.substring (rbracket + 1); + indent = indent + " "; + name = name + '[' + loopIndex + ']'; + } + if (td.type () instanceof SequenceEntry || td.type () instanceof PrimitiveEntry || td.type () instanceof StringEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)td.type ().generator ()).write (index, indent, name, td.type (), stream); + else if (td.type () instanceof InterfaceEntry && td.type ().fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + "ostream.write_Object (" + name + ");"); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(td.type(), true) + ".write (ostream, " + name + ");"); // + for (int i = 0; i < closingBrackets; ++i) + { + indent = indent.substring (2); + stream.println (indent + '}'); + } + } + else + { + SymtabEntry tdtype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(td.type()); + if (tdtype instanceof SequenceEntry || tdtype instanceof PrimitiveEntry || tdtype instanceof StringEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)tdtype.generator ()).write (index, indent, name, tdtype, stream); + else if (tdtype instanceof InterfaceEntry && tdtype.fullName ().equals ("org/omg/CORBA/Object")) + stream.println (indent + "ostream.write_Object (" + name + ");"); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(tdtype, true) + ".write (ostream, " + name + ");"); // + } + return index; + } // write + + // From JavaGenerator + //////////////// + + protected Hashtable symbolTable = null; + protected TypedefEntry t = null; +} // class TypedefGen + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/UnionGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/UnionGen.java new file mode 100644 index 000000000..a82d14919 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/UnionGen.java @@ -0,0 +1,1031 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -cast() does not support longlong types yet. +// -Deal with typedef changes. +// -Scoped names for the discriminator are ignored at the moment. +// -F46082.51 Remove -stateful feature; javaStatefulName() obsolete. +// -D61056 Use Util.helperName + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.EnumEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.UnionBranch; +import com.sun.tools.corba.ee.idl.UnionEntry; + +import com.sun.tools.corba.ee.idl.constExpr.Expression; +import com.sun.tools.corba.ee.idl.constExpr.EvaluationException; + +/** + * + **/ +public class UnionGen implements com.sun.tools.corba.ee.idl.UnionGen, com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public UnionGen () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, UnionEntry u, PrintWriter s) + { + this.symbolTable = symbolTable; + this.u = u; + init (); + + openStream (); + if (stream == null) + return; + generateHelper (); + generateHolder (); + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + generateContainedTypes (); + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + unionIsEnum = utype instanceof EnumEntry; + } // init + + /** + * + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(u, ".java"); + } // openStream + + /** + * + **/ + protected void generateHelper () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, u); + } // generateHelper + + /** + * + **/ + protected void generateHolder () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, u); + } // generateHolder + + /** + * + **/ + protected void writeHeading () + { + // If the discriminator is an enum, assign the typePackage string. + if (unionIsEnum) + typePackage = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(utype) + '.'; + else + typePackage = ""; + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, u); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + String className = u.name (); + stream.println ("public final class " + u.name () + " implements org.omg.CORBA.portable.IDLEntity"); + stream.println ("{"); + } // writeHeading + + /** + * + **/ + protected void writeBody () + { + // Write branches and populate quality arrays + int size = u.branches ().size () + 1; + Enumeration e = u.branches ().elements (); + int i = 0; + while (e.hasMoreElements ()) + { + UnionBranch branch = (UnionBranch)e.nextElement (); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(branch.typedef); + // Remove -stateful feature; javaStatefulName() obsolete. + //stream.println (" private " + Util.javaStatefulName (branch.typedef) + " ___" + branch.typedef.name () + ";"); + stream.println (" private " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(branch.typedef) + " ___" + branch.typedef.name () + ";"); + ++i; + } + stream.println (" private " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + " __discriminator;"); + stream.println (" private boolean __uninitialized = true;"); + + // Write ctor + stream.println (); + stream.println (" public " + u.name () + " ()"); + stream.println (" {"); + stream.println (" }"); + + // Write discriminator + stream.println (); + stream.println (" public " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + " " + safeName (u, "discriminator") + " ()"); + stream.println (" {"); + stream.println (" if (__uninitialized)"); + stream.println (" throw new org.omg.CORBA.BAD_OPERATION ();"); + stream.println (" return __discriminator;"); + stream.println (" }"); + + // Write for each branch: + // - setter + // - getter + // - private verifyXXX + e = u.branches ().elements (); + i = 0; + while (e.hasMoreElements ()) + { + UnionBranch branch = (UnionBranch)e.nextElement (); + writeBranchMethods (stream, u, branch, i++); + } + if (u.defaultBranch () == null && !coversAll (u)) + { + stream.println (); + stream.println (" public void _default ()"); + stream.println (" {"); + stream.println (" __discriminator = " + defaultDiscriminator (u) + ';'); + stream.println (" __uninitialized = false;"); + stream.println (" }"); + + stream.println (); + stream.println (" public void _default (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + + " discriminator)"); + stream.println (" {"); + stream.println (" verifyDefault( discriminator ) ;" ); + stream.println (" __discriminator = discriminator ;"); + stream.println (" __uninitialized = false;"); + stream.println (" }"); + + writeVerifyDefault() ; + } + stream.println (); + } // writeBody + + /** + * + **/ + protected void writeClosing () + { + stream.println ("} // class " + u.name ()); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /** + * + **/ + protected void generateContainedTypes () + { + Enumeration e = u.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry entry = (SymtabEntry)e.nextElement (); + + // Don't generate contained entries if they are sequences. + // Sequences are unnamed and since they translate to arrays, + // no classes are generated for them, not even holders in this + // case since they cannot be accessed outside of this union. + if (!(entry instanceof SequenceEntry)) + entry.generate (symbolTable, stream); + } + } // generateContainedTypes + + private void writeVerifyDefault() + { + Vector labels = vectorizeLabels (u.branches (), true); + + stream.println( "" ) ; + stream.println( " private void verifyDefault( " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + + " value )" ) ; + stream.println( " {" ) ; + + if (unionIsEnum) + stream.println( " switch (value.value()) {" ) ; + else + stream.println( " switch (value) {" ) ; + + Enumeration e = labels.elements() ; + while (e.hasMoreElements()) { + String str = (String)(e.nextElement()) ; + stream.println( " case " + str + ":" ) ; + } + + stream.println( " throw new org.omg.CORBA.BAD_OPERATION() ;" ) ; + stream.println( "" ) ; + stream.println( " default:" ) ; + stream.println( " return;" ) ; + stream.println( " }" ) ; + stream.println( " }" ) ; + } + + private String defaultDiscriminator (UnionEntry u) + { + Vector labels = vectorizeLabels (u.branches (), false ); + String ret = null; + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + if (utype instanceof PrimitiveEntry && utype.name ().equals ("boolean")) { + // If it got this far, then: + // - there is only one branch; + // - that branch has only one label. + if (labels.contains ("true")) + ret = "false"; + else + ret = "true"; + } else if (utype.name ().equals ("char")) { + // This doesn't handle '\u0030' == '0'. Unions are so + // seldom used. I don't have time to make this perfect. + int def = 0; + String string = "'\\u0000'"; + while (def != 0xFFFF && labels.contains (string)) + if (++def / 0x10 == 0) + string = "'\\u000" + def + "'"; + else if (def / 0x100 == 0) + string = "\\u00" + def + "'"; + else if (def / 0x1000 == 0) + string = "\\u0" + def + "'"; + else + string = "\\u" + def + "'"; + ret = string; + } else if (utype instanceof EnumEntry) { + Enumeration e = labels.elements (); + EnumEntry enumEntry = (EnumEntry)utype; + Vector enumList = (Vector)enumEntry.elements ().clone (); + // cull out those elements in the enumeration list that are + // in the cases of this union + while (e.hasMoreElements ()) + enumList.removeElement (e.nextElement ()); + // If all of the enum elements are covered in this union and + // there is a default statement, just pick one of the + // elements for the default. If there are enum elements + // which are NOT covered by the cases, pick one as the + // default. + if (enumList.size () == 0) + ret = typePackage + (String)enumEntry.elements ().lastElement (); + else + ret = typePackage + (String)enumList.firstElement (); + } else if (utype.name ().equals ("octet")) { + short def = Byte.MIN_VALUE; + while (def != Byte.MAX_VALUE && labels.contains (Integer.toString (def))) + ++def; + ret = Integer.toString (def); + } else if (utype.name ().equals ("short")) { + short def = Short.MIN_VALUE; + while (def != Short.MAX_VALUE && labels.contains (Integer.toString (def))) + ++def; + ret = Integer.toString (def); + } else if (utype.name ().equals ("long")) { + int def = Integer.MIN_VALUE; + while (def != Integer.MAX_VALUE && labels.contains (Integer.toString (def))) + ++def; + ret = Integer.toString (def); + } else if (utype.name ().equals ("long long")) { + long def = Long.MIN_VALUE; + while (def != Long.MAX_VALUE && labels.contains (Long.toString (def))) + ++def; + ret = Long.toString (def); + } else if (utype.name ().equals ("unsigned short")) { + short def = 0; + while (def != Short.MAX_VALUE && labels.contains (Integer.toString (def))) + ++def; + ret = Integer.toString (def); + } else if (utype.name ().equals ("unsigned long")) { + int def = 0; + while (def != Integer.MAX_VALUE && labels.contains (Integer.toString (def))) + ++def; + ret = Integer.toString (def); + } else if (utype.name ().equals ("unsigned long long")) { + long def = 0; + while (def != Long.MAX_VALUE && labels.contains (Long.toString (def))) + ++def; + ret = Long.toString (def); + } + + return ret; + } // defaultDiscriminator + + /** + * + **/ + private Vector vectorizeLabels (Vector branchVector, boolean useIntsForEnums ) + { + Vector mergedLabels = new Vector (); + Enumeration branches = branchVector.elements (); + while (branches.hasMoreElements ()) + { + UnionBranch branch = (UnionBranch)branches.nextElement (); + Enumeration labels = branch.labels.elements (); + while (labels.hasMoreElements ()) + { + Expression expr = (Expression)labels.nextElement (); + String str ; + + if (unionIsEnum) + if (useIntsForEnums) + str = typePackage + "_" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(expr) ; + else + str = typePackage + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(expr) ; + else + str = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(expr) ; + + mergedLabels.addElement (str); + } + } + return mergedLabels; + } // vectorizeLabels + + /** + * + **/ + private String safeName (UnionEntry u, String name) + { + Enumeration e = u.branches ().elements (); + while (e.hasMoreElements ()) + if (((UnionBranch)e.nextElement ()).typedef.name ().equals (name)) + { + name = '_' + name; + break; + } + return name; + } // safeName + + /** + * + **/ + private boolean coversAll (UnionEntry u) + { + // This assumes that it is not possible to cover types other than + // boolean and enums. This is not quite correct, but since octet + // is not a valid discriminator type, it's not too bad in practice. + // It may also be possible to cover a char type, but we won't worry + // about that either. + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + + boolean coversAll = false; + if (utype.name ().equals ("boolean")) { + if (u.branches ().size () == 2) + coversAll = true; + } else if (utype instanceof EnumEntry) { + Vector labels = vectorizeLabels (u.branches (), true); + if (labels.size () == ((EnumEntry)utype).elements ().size ()) + coversAll = true; + } + + return coversAll; + } // coversAll + + /** + * + **/ + private void writeBranchMethods (PrintWriter stream, UnionEntry u, UnionBranch branch, int i) + { + // Write getter + stream.println (); + // Remove -stateful feature; javaStatefulName() obsolete. + //stream.println (" public " + Util.javaStatefulName (branch.typedef) + " " + branch.typedef.name () + " ()"); + stream.println (" public " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(branch.typedef) + " " + branch.typedef.name () + " ()"); + stream.println (" {"); + stream.println (" if (__uninitialized)"); + stream.println (" throw new org.omg.CORBA.BAD_OPERATION ();"); + stream.println (" verify" + branch.typedef.name () + " (__discriminator);"); + stream.println (" return ___" + branch.typedef.name () + ";"); + stream.println (" }"); + + // Write setter(s) + stream.println (); + // Remove -stateful feature; javaStatefulName() obsolete. + //stream.println (" public void " + branch.typedef.name () + " (" + Util.javaStatefulName (branch.typedef) + " value)"); + stream.println (" public void " + branch.typedef.name () + " (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(branch.typedef) + " value)"); + stream.println (" {"); + if (branch.labels.size () == 0) + { + // This is a default branch + stream.println (" __discriminator = " + defaultDiscriminator (u) + ";"); + } + else + { + // This is a non-default branch + if (unionIsEnum) + stream.println (" __discriminator = " + typePackage + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression((Expression) branch.labels.firstElement()) + ";"); + else + stream.println (" __discriminator = " + cast ((Expression)branch.labels.firstElement (), u.type ()) + ";"); + } + stream.println (" ___" + branch.typedef.name () + " = value;"); + stream.println (" __uninitialized = false;"); + stream.println (" }"); + + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + + // If there are multiple labels for one branch, write the + // setter that takes a discriminator. + if (branch.labels.size () > 0 || branch.isDefault) + { + stream.println (); + // Remove -stateful feature; javaStatefulName() obsolete. + //stream.println (" public void " + branch.typedef.name () + " (" + Util.javaName (utype) + " discriminator, " + Util.javaStatefulName (branch.typedef) + " value)"); + stream.println (" public void " + branch.typedef.name () + " (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + " discriminator, " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(branch.typedef) + " value)"); + stream.println (" {"); + stream.println (" verify" + branch.typedef.name () + " (discriminator);"); + stream.println (" __discriminator = discriminator;"); + stream.println (" ___" + branch.typedef.name () + " = value;"); + stream.println (" __uninitialized = false;"); + stream.println (" }"); + } + + // Write verifyXXX + stream.println (); + stream.println (" private void verify" + branch.typedef.name () + " (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + " discriminator)"); + stream.println (" {"); + + boolean onlyOne = true; + + if (branch.isDefault && u.branches ().size () == 1) + ;// If all that is in this union is a default branch, + // all discriminators are legal. Don't print any + // body to this method in that case. + else + { + // Otherwise this code is executed and a body is printed. + stream.print (" if ("); + if (branch.isDefault) + { + Enumeration eBranches = u.branches ().elements (); + while (eBranches.hasMoreElements ()) + { + UnionBranch b = (UnionBranch)eBranches.nextElement (); + if (b != branch) + { + Enumeration eLabels = b.labels.elements (); + while (eLabels.hasMoreElements ()) + { + Expression label = (Expression)eLabels.nextElement (); + if (!onlyOne) + stream.print (" || "); + if (unionIsEnum) + stream.print ("discriminator == " + typePackage + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(label)); + else + stream.print ("discriminator == " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(label)); + onlyOne = false; + } + } + } + } + else + { + Enumeration e = branch.labels.elements (); + while (e.hasMoreElements ()) + { + Expression label = (Expression)e.nextElement (); + if (!onlyOne) + stream.print (" && "); + if (unionIsEnum) + stream.print ("discriminator != " + typePackage + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(label)); + else + stream.print ("discriminator != " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(label)); + onlyOne = false; + } + } + stream.println (")"); + stream.println (" throw new org.omg.CORBA.BAD_OPERATION ();"); + } + stream.println (" }"); + } // writeBranchMethods + + /////////////// + // From JavaGenerator + + /** + * + **/ + + // Computes the total number of labels in the union, which is the sum + // of the number of labels in each branch of the union. Note that the + // label for the default branch has size 0, but still counts in the total + // size. + private int unionLabelSize( UnionEntry un ) + { + int size = 0 ; + Vector branches = un.branches() ; + for (int i = 0; i < branches.size (); ++i) { + UnionBranch branch = (UnionBranch)(branches.get(i)) ; + int branchSize = branch.labels.size() ; + size += ((branchSize == 0) ? 1 : branchSize) ; + } + return size ; + } + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, + String name, SymtabEntry entry, PrintWriter stream) + { + com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets innerOffsets = new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(); + UnionEntry u = (UnionEntry)entry; + String discTypeCode = "_disTypeCode" + index; + String membersName = "_members" + index; + + // Build discriminator tc + stream.println (indent + "org.omg.CORBA.TypeCode " + discTypeCode + ';'); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)u.type ().generator ()).type (index + 1, indent, + innerOffsets, discTypeCode, u.type (), stream); + tcoffsets.bumpCurrentOffset (innerOffsets.currentOffset ()); + + stream.println (indent + "org.omg.CORBA.UnionMember[] " + membersName + + " = new org.omg.CORBA.UnionMember [" + unionLabelSize(u) + "];"); + String tcOfMembers = "_tcOf" + membersName; + String anyOfMembers = "_anyOf" + membersName; + stream.println (indent + "org.omg.CORBA.TypeCode " + tcOfMembers + ';'); + stream.println (indent + "org.omg.CORBA.Any " + anyOfMembers + ';'); + + innerOffsets = new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(); + innerOffsets.set (entry); + int offsetForUnion = innerOffsets.currentOffset (); + for (int i = 0; i < u.branches ().size (); ++i) { + UnionBranch branch = (UnionBranch)u.branches ().elementAt (i); + TypedefEntry member = branch.typedef; + Vector labels = branch.labels; + String memberName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscores(member.name()); + + if (labels.size() == 0) { + stream.println (); + stream.println (indent + "// Branch for " + memberName + + " (Default case)" ); + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + stream.println (indent + anyOfMembers + " = org.omg.CORBA.ORB.init ().create_any ();"); + // For default member, label is the zero octet (per CORBA spec.) + stream.println (indent + anyOfMembers + ".insert_octet ((byte)0); // default member label"); + + // Build typecode + innerOffsets.bumpCurrentOffset (4); // label value + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).type (index, indent, innerOffsets, tcOfMembers, member, stream); + int offsetSoFar = innerOffsets.currentOffset (); + innerOffsets = new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(); + innerOffsets.set (entry); + innerOffsets.bumpCurrentOffset (offsetSoFar - offsetForUnion); + + // Build union member + stream.println (indent + membersName + '[' + i + "] = new org.omg.CORBA.UnionMember ("); + stream.println (indent + " \"" + memberName + "\","); + stream.println (indent + " " + anyOfMembers + ','); + stream.println (indent + " " + tcOfMembers + ','); + stream.println (indent + " null);"); + } else { + Enumeration enumeration = labels.elements() ; + while (enumeration.hasMoreElements()) { + Expression expr = (Expression)(enumeration.nextElement()) ; + String elem = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(expr) ; + + stream.println (); + stream.println (indent + "// Branch for " + memberName + + " (case label " + elem + ")" ); + + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + + // Build any + stream.println (indent + anyOfMembers + " = org.omg.CORBA.ORB.init ().create_any ();"); + + if (utype instanceof PrimitiveEntry) + stream.println (indent + anyOfMembers + ".insert_" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.collapseName(utype.name()) + " ((" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype) + + ')' + elem + ");"); + else { // it must be enum + String enumClass = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(utype); + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(utype, false) + ".insert (" + + anyOfMembers + ", " + enumClass + '.' + elem + ");"); // + } + + // Build typecode + innerOffsets.bumpCurrentOffset (4); // label value + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).type (index, indent, innerOffsets, tcOfMembers, member, stream); + int offsetSoFar = innerOffsets.currentOffset (); + innerOffsets = new com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets(); + innerOffsets.set (entry); + innerOffsets.bumpCurrentOffset (offsetSoFar - offsetForUnion); + + // Build union member + stream.println (indent + membersName + '[' + i + "] = new org.omg.CORBA.UnionMember ("); + stream.println (indent + " \"" + memberName + "\","); + stream.println (indent + " " + anyOfMembers + ','); + stream.println (indent + " " + tcOfMembers + ','); + stream.println (indent + " null);"); + } + } + } + + tcoffsets.bumpCurrentOffset (innerOffsets.currentOffset ()); + + // Build create_union_tc + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_union_tc (" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(u, true) + ".id (), \"" + entry.name () + "\", " + + discTypeCode + ", " + membersName + ");"); + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, + SymtabEntry entry, PrintWriter stream) + { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); + return index; + } + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + stream.println (" " + entryName + " value = new " + entryName + " ();"); + read (0, " ", "value", entry, stream); + stream.println (" return value;"); + } + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + write (0, " ", "value", entry, stream); + } + + public int read (int index, String indent, String name, + SymtabEntry entry, PrintWriter stream) + { + UnionEntry u = (UnionEntry)entry; + String disName = "_dis" + index++; + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(indent, disName, "", utype, stream); + + if (utype instanceof PrimitiveEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)utype.generator ()).read (index, indent, disName, utype, stream); + else + stream.println (indent + disName + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(utype, true) + ".read (istream);"); + + if (utype.name ().equals ("boolean")) + index = readBoolean (disName, index, indent, name, u, stream); + else + index = readNonBoolean (disName, index, indent, name, u, stream); + + return index; + } + + private int readBoolean (String disName, int index, String indent, + String name, UnionEntry u, PrintWriter stream) + { + UnionBranch firstBranch = (UnionBranch)u.branches ().firstElement (); + UnionBranch secondBranch; + + if (u.branches ().size () == 2) + secondBranch = (UnionBranch)u.branches ().lastElement (); + else + secondBranch = null; + + boolean firstBranchIsTrue = false; + boolean noCases = false; + try { + if (u.branches ().size () == 1 && + (u.defaultBranch () != null || firstBranch.labels.size () == 2)) { + noCases = true; + } else { + Expression expr = (Expression)(firstBranch.labels.firstElement()) ; + Boolean bool = (Boolean)(expr.evaluate()) ; + firstBranchIsTrue = bool.booleanValue (); + } + } catch (EvaluationException ex) { + // no action + } + + if (noCases) { + // There is only a default label. Since there are no cases, + // there is no need for if...else branches. + index = readBranch (index, indent, firstBranch.typedef.name (), "", firstBranch.typedef, stream); + } else { + // If first branch is false, swap branches + if (!firstBranchIsTrue) { + UnionBranch tmp = firstBranch; + firstBranch = secondBranch; + secondBranch = tmp; + } + + stream.println (indent + "if (" + disName + ')'); + + if (firstBranch == null) + stream.println (indent + " throw new org.omg.CORBA.BAD_OPERATION ();"); + else { + stream.println (indent + '{'); + index = readBranch (index, indent + " ", firstBranch.typedef.name (), + disName, firstBranch.typedef, stream); + stream.println (indent + '}'); + } + + stream.println (indent + "else"); + + if (secondBranch == null) + stream.println (indent + " throw new org.omg.CORBA.BAD_OPERATION ();"); + else { + stream.println (indent + '{'); + index = readBranch (index, indent + " ", secondBranch.typedef.name (), + disName, secondBranch.typedef, stream); + stream.println (indent + '}'); + } + } + + return index; + } + + private int readNonBoolean (String disName, int index, String indent, + String name, UnionEntry u, PrintWriter stream) + { + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + + if (utype instanceof EnumEntry) + stream.println (indent + "switch (" + disName + ".value ())"); + else + stream.println (indent + "switch (" + disName + ')'); + + stream.println (indent + '{'); + String typePackage = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(utype) + '.'; + + Enumeration e = u.branches ().elements (); + while (e.hasMoreElements ()) { + UnionBranch branch = (UnionBranch)e.nextElement (); + Enumeration labels = branch.labels.elements (); + + while (labels.hasMoreElements ()) { + Expression label = (Expression)labels.nextElement (); + + if (utype instanceof EnumEntry) { + String key = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(label); + stream.println (indent + " case " + typePackage + '_' + key + ':'); + } else + stream.println (indent + " case " + cast (label, utype) + ':'); + } + + if (!branch.typedef.equals (u.defaultBranch ())) { + index = readBranch (index, indent + " ", branch.typedef.name (), + branch.labels.size() > 1 ? disName : "" , + branch.typedef, stream); + stream.println (indent + " break;"); + } + } + + // We need a default branch unless all of the case of the discriminator type + // are listed in the case branches. + if (!coversAll(u)) { + stream.println( indent + " default:") ; + + if (u.defaultBranch () == null) { + // If the union does not have a default branch, we still need to initialize + // the discriminator. + stream.println( indent + " value._default( " + disName + " ) ;" ) ; + } else { + index = readBranch (index, indent + " ", u.defaultBranch ().name (), disName, + u.defaultBranch (), stream); + } + + stream.println (indent + " break;"); + } + + stream.println (indent + '}'); + + return index; + } + + private int readBranch (int index, String indent, String name, String disName, TypedefEntry entry, PrintWriter stream) + { + SymtabEntry type = entry.type (); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(indent, '_' + name, "", entry, stream); + + if (!entry.arrayInfo ().isEmpty () || + type instanceof SequenceEntry || + type instanceof PrimitiveEntry || + type instanceof StringEntry) { + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.generator ()).read (index, indent, '_' + name, entry, stream); + } else { + stream.println (indent + '_' + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".read (istream);"); + } + + stream.print (indent + "value." + name + " ("); + if( disName == "" ) + stream.println("_" + name + ");"); + else + stream.println(disName + ", " + "_" + name + ");"); + + return index; + } + + /** + * + **/ + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + UnionEntry u = (UnionEntry)entry; + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + if (utype instanceof PrimitiveEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)utype.generator ()).write (index, indent, name + ".discriminator ()", utype, stream); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(utype, true) + ".write (ostream, " + name + ".discriminator ());"); // + if (utype.name ().equals ("boolean")) + index = writeBoolean (name + ".discriminator ()", index, indent, name, u, stream); + else + index = writeNonBoolean (name + ".discriminator ()", index, indent, name, u, stream); + return index; + } // write + + /** + * + **/ + private int writeBoolean (String disName, int index, String indent, String name, UnionEntry u, PrintWriter stream) + { + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + UnionBranch firstBranch = (UnionBranch)u.branches ().firstElement (); + UnionBranch secondBranch; + if (u.branches ().size () == 2) + secondBranch = (UnionBranch)u.branches ().lastElement (); + else + secondBranch = null; + boolean firstBranchIsTrue = false; + boolean noCases = false; + try + { + if (u.branches ().size () == 1 && (u.defaultBranch () != null || firstBranch.labels.size () == 2)) + noCases = true; + else + firstBranchIsTrue = ((Boolean)((Expression)firstBranch.labels.firstElement ()).evaluate ()).booleanValue (); + } + catch (EvaluationException ex) + {} + + if (noCases) + { + // There is only a default label. Since there are no cases, + // there is no need for if...else branches. + index = writeBranch (index, indent, name, firstBranch.typedef, stream); + } + else + { + // If first branch is false, swap branches + if (!firstBranchIsTrue) + { + UnionBranch tmp = firstBranch; + firstBranch = secondBranch; + secondBranch = tmp; + } + stream.println (indent + "if (" + disName + ')'); + if (firstBranch == null) + stream.println (indent + " throw new org.omg.CORBA.BAD_OPERATION ();"); + else + { + stream.println (indent + '{'); + index = writeBranch (index, indent + " ", name, firstBranch.typedef, stream); + stream.println (indent + '}'); + } + stream.println (indent + "else"); + if (secondBranch == null) + stream.println (indent + " throw new org.omg.CORBA.BAD_OPERATION ();"); + else + { + stream.println (indent + '{'); + index = writeBranch (index, indent + " ", name, secondBranch.typedef, stream); + stream.println (indent + '}'); + } + } + return index; + } // writeBoolean + + /** + * + **/ + private int writeNonBoolean (String disName, int index, String indent, String name, UnionEntry u, PrintWriter stream) + { + SymtabEntry utype = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(u.type()); + if (utype instanceof EnumEntry) + stream.println (indent + "switch (" + name + ".discriminator ().value ())"); + else + stream.println (indent + "switch (" + name + ".discriminator ())"); + stream.println (indent + "{"); + String typePackage = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(utype) + '.'; + Enumeration e = u.branches ().elements (); + while (e.hasMoreElements ()) + { + UnionBranch branch = (UnionBranch)e.nextElement (); + Enumeration labels = branch.labels.elements (); + while (labels.hasMoreElements ()) + { + Expression label = (Expression)labels.nextElement (); + if (utype instanceof EnumEntry) + { + String key = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(label); + stream.println (indent + " case " + typePackage + '_' + key + ":"); + } + else + stream.println (indent + " case " + cast (label, utype) + ':'); + } + if (!branch.typedef.equals (u.defaultBranch ())) + { + index = writeBranch (index, indent + " ", name, branch.typedef, stream); + stream.println (indent + " break;"); + } + } + if (u.defaultBranch () != null) { + stream.println (indent + " default:"); + index = writeBranch (index, indent + " ", name, u.defaultBranch (), stream); + stream.println (indent + " break;"); + } + stream.println (indent + "}"); + return index; + } // writeNonBoolean + + /** + * + **/ + private int writeBranch (int index, String indent, String name, TypedefEntry entry, PrintWriter stream) + { + SymtabEntry type = entry.type (); + if (!entry.arrayInfo ().isEmpty () || type instanceof SequenceEntry || type instanceof PrimitiveEntry || type instanceof StringEntry) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)entry.generator ()).write (index, indent, name + '.' + entry.name () + " ()", entry, stream); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(type, true) + ".write (ostream, " + name + '.' + entry.name () + " ());"); // + return index; + } // writeBranch + + // From JavaGenerator + /////////////// + + /** + * + **/ + private String cast (Expression expr, SymtabEntry type) + { + String ret = com.sun.tools.corba.ee.idl.toJavaPortable.Util.parseExpression(expr); + if (type.name ().indexOf ("short") >= 0) + { + if (expr.value () instanceof Long) + { + long value = ((Long)expr.value ()).longValue (); + if (value > Short.MAX_VALUE) + ret = "(short)(" + ret + ')'; + } + else if (expr.value () instanceof Integer) + { + int value = ((Integer)expr.value ()).intValue (); + if (value > Short.MAX_VALUE) + ret = "(short)(" + ret + ')'; + } + } + else if (type.name ().indexOf ("long") >= 0) + { + if (expr.value () instanceof Long) + { + long value = ((Long)expr.value ()).longValue (); + // value == Integer.MIN_VALUE because if the number is + // Integer.MIN_VALUE, then it will have the 'L' suffix and + // the cast will be necessary. + if (value > Integer.MAX_VALUE || value == Integer.MIN_VALUE) + ret = "(int)(" + ret + ')'; + } + else if (expr.value () instanceof Integer) + { + int value = ((Integer)expr.value ()).intValue (); + // value == Integer.MIN_VALUE because if the number is + // Integer.MIN_VALUE, then it will have the 'L' suffix and + // the cast will be necessary. + if (value > Integer.MAX_VALUE || value == Integer.MIN_VALUE) + ret = "(int)(" + ret + ')'; + } + } + return ret; + } // cast + + protected Hashtable symbolTable = null; + protected UnionEntry u = null; + protected PrintWriter stream = null; + protected SymtabEntry utype = null; + protected boolean unionIsEnum; + protected String typePackage = ""; +} // class UnionGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Util.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Util.java new file mode 100644 index 000000000..eb5493cf4 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/Util.java @@ -0,0 +1,1401 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// Notes: +// -F46838.4 Ported -td option from toJava. +// -10/17/98 KLR Ported fix for d48911 from toJava +// -10/18/98 KLR Ported fix from toJava for "unsigned long" constants +// -F46082.51 Removed code to collect makefile list generation inforamtion +// from getStream(); see f46830. +// -F46082.51 Removed -stateful feature: methods javaStatefulName(String) +// and javaStatefulName(SymtabEntry) are obsolete, supplanted by javaName(). +// -D54640 Represent unsigned long long expressions with their computed +// value rather than their actual representation (see notes in method +// parseTerminal(), parseBinary(), and parseUnary().) +// -D58319 Add getVersion() method. +// -D48034 Import Helper classes for typedef struct members when generating +// helper. See method addImportLines(). +// -D59851 Modify to enable QuickTest build. (pending) +// -D42256 Determine import lines for template types, which may specify any +// positive int., constant expression for a boundary. Such expression containing +// non-literal contansts previously caused problems when appearing in constructs +// structs, unions, exceptions, typedefs, operation types and parameters, +// attributes; and of course, sequences, strings. +// -D59063 Add helper for global exception to stub import list. +// -D58951 Publicise members for QuickTest. +// -D59421 Change ValueBaseHolder to SerializableHolder +// -D59596 Prevent accesses to elements of empty Vectors. +// -D59771 Add import stmt for Helper of global type in stubs. +// -D59355 Remove target dir. from filename when writing to prolog. +// -D59437 Fill typename information for value boxes. +// -D62023 Don't import ValueBase* +// -D62023 Add corbaLevel + +import com.sun.tools.corba.ee.idl.ConstEntry; +import com.sun.tools.corba.ee.idl.EnumEntry; +import com.sun.tools.corba.ee.idl.ExceptionEntry; +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.NativeEntry; +import com.sun.tools.corba.ee.idl.ParameterEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.StructEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.UnionBranch; +import com.sun.tools.corba.ee.idl.UnionEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +import java.io.File; +import java.io.PrintWriter; +import java.math.BigInteger; +import java.text.DateFormat; +import java.util.Date; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Locale; +import java.util.Vector; + +/** + * Class Util is a repository of static members available for general + * use by the IDL parser framework and any generator extensions. + **/ +public class Util extends com.sun.tools.corba.ee.idl.Util +{ + // + /** + * Fetch the version number of this build of the IDL-to-Java (portable) + * compiler from the appropriate properties file. + * @return the version number of this compiler build. + **/ + public static String getVersion () + { + return com.sun.tools.corba.ee.idl.Util.getVersion("com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable"); + } // getVersion + + /** + * This method is called by Setup.preEmit, so + * symbolTable is available for all Util methods. + **/ + static void setSymbolTable (Hashtable symtab) + { + symbolTable = symtab; + } // setSymbolTable + + public static void setPackageTranslation( Hashtable pkgtrans ) + { + packageTranslation = pkgtrans ; + } + + public static boolean isInterface (String name) + { + return isInterface (name, symbolTable); + } // isInterface + + static String arrayInfo (Vector arrayInfo) + { + int arrays = arrayInfo.size (); + String info = ""; + Enumeration e = arrayInfo.elements (); + while (e.hasMoreElements ()) + info = info + '[' + parseExpression ((com.sun.tools.corba.ee.idl.constExpr.Expression)e.nextElement ()) + ']'; + return info; + } // arrayInfo + + // static String sansArrayInfo (Vector arrayInfo) + public static String sansArrayInfo (Vector arrayInfo) + { + int arrays = arrayInfo.size (); + String brackets = ""; + for (int i = 0; i < arrays; ++i) + brackets = brackets + "[]"; + return brackets; + } // sansArrayInfo + + // static String sansArrayInfo (String name) + static public String sansArrayInfo (String name) + { + int index = name.indexOf ('['); + if (index >= 0) + { + String array = name.substring (index); + name = name.substring (0, index); + while (!array.equals ("")) + { + name = name + "[]"; + array = array.substring (array.indexOf (']') + 1); + } + } + return name; + } // sansArrayInfo + + /** + * Given a symbol table entry, return the name of + * the file which should be created. + **/ + public static String fileName (SymtabEntry entry, String extension ) + { + com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier nm = new NameModifierImpl() ; + return fileName( entry, nm, extension ) ; + } // fileName + + public static String fileName (SymtabEntry entry, com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier modifier, String extension ) + { + // This may not be the most appropriate place for + // the mkdir calls, but it's common to everything: + String pkg = containerFullName (entry.container ()); + if (pkg != null && !pkg.equals ("")) + mkdir (pkg); + + String name = entry.name (); + name = modifier.makeName( name ) + extension ; + if (pkg != null && !pkg.equals ("")) + name = pkg + '/' + name; + + return name.replace ('/', File.separatorChar); + } // fileName + + public static GenFileStream stream (SymtabEntry entry, String extension) + { + com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier nm = new NameModifierImpl() ; + return stream(entry, nm, extension); + } // stream + + public static GenFileStream stream (SymtabEntry entry, com.sun.tools.corba.ee.idl.toJavaPortable.NameModifier modifier, String extension ) + { + return getStream ( fileName (entry,modifier,extension), entry ) ; + } + + public static GenFileStream getStream (String name, SymtabEntry entry) + { + // + String absPathName = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).targetDir + name; + if (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments.keepOldFiles && new File (absPathName).exists ()) + return null; + else + // Write the data to the file stream + return new GenFileStream (absPathName); + } // getStream + + public static String containerFullName( SymtabEntry container) + { + String name = doContainerFullName( container ) ; + if (packageTranslation.size() > 0) + name = translate( name ) ; + return name ; + } + + public static String translate( String name ) + { + String head = name ; + String tail = "" ; + int index ; + String trname ; + + // Check for package name translations, starting with the + // most specific match. + do { + trname = (String)(packageTranslation.get( head )) ; + if (trname != null) + return trname + tail ; + + index = head.lastIndexOf( '/' ) ; + if (index >= 0) { + tail = head.substring( index ) + tail ; + head = head.substring( 0, index ) ; + } + } while (index >= 0) ; + + return name ; + } + + private static String doContainerFullName (SymtabEntry container) + { + String name = ""; + + if (container == null) + name = ""; + else + { + if (container instanceof InterfaceEntry || + container instanceof StructEntry || + container instanceof UnionEntry) + name = container.name () + "Package"; + else + name = container.name (); + + if (container.container () != null && + !container.container ().name ().equals ("")) + name = doContainerFullName (container.container ()) + '/' + name; + } + + return name; + } // doContainerFullName + + /** + * Given a SymtabEntry, return the string which should be used + * for this entry. Enums are converted to ints, typedefs and + * sequences are converted to their info types. javaQualifiedName + * does not do any of these conversions. + **/ + public static String javaName (SymtabEntry entry) + { + // First get the real name of this type + String name = ""; + if (entry instanceof TypedefEntry || entry instanceof SequenceEntry) + try + { + name = sansArrayInfo ((String)entry.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo)); + } + catch (NoSuchFieldException e) + { + name = entry.name (); + } + else if (entry instanceof PrimitiveEntry) + name = javaPrimName (entry.name ()); + else if (entry instanceof StringEntry) + name = "String"; + else if (entry instanceof NativeEntry) + name = javaNativeName (entry.name()); + else if (entry instanceof ValueEntry && entry.name ().equals ("ValueBase")) + name = "java.io.Serializable"; + else if (entry instanceof ValueBoxEntry) + { + ValueBoxEntry v = (ValueBoxEntry) entry; + TypedefEntry member = ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof PrimitiveEntry) + { + name = containerFullName (entry.container ()); + if (!name.equals ("")) + name = name + '.'; + name = name + entry.name (); + } + else + name = javaName (mType); + } + else + { + name = containerFullName (entry.container ()); + if (name.equals ("")) + name = entry.name (); + else + name = name + '.' + entry.name (); + } + + // Make it a fully package-qualified name + return name.replace ('/', '.'); + } // javaName + + public static String javaPrimName (String name) + { + if (name.equals ("long") || name.equals ("unsigned long")) + name = "int"; + else if (name.equals ("octet")) + name = "byte"; + // "unisigned long long" exceeds Java long. + else if (name.equals ("long long") || name.equals ("unsigned long long")) + name = "long"; + else if (name.equals ("wchar")) + name = "char"; + else if (name.equals ("unsigned short")) + name = "short"; + else if (name.equals ("any")) + name = "org.omg.CORBA.Any"; + else if (name.equals ("TypeCode")) + name = "org.omg.CORBA.TypeCode"; + else if (name.equals ("Principal")) // + name = "org.omg.CORBA.Principal"; + return name; + } // javaPrimName + + public static String javaNativeName (String name) + { + + // translations for Native declarations according to CORBA 2.3 spec + + if (name.equals ("AbstractBase") || name.equals ("Cookie")) + name = "java.lang.Object"; + else if (name.equals ("Servant")) + name = "org.omg.PortableServer.Servant"; + else if (name.equals ("ValueFactory")) + name = "org.omg.CORBA.portable.ValueFactory"; + return name; + } + + + /** + * Given a symtabEntry, return the name of this entry. This + * method does not do any conversions like javaName does. + **/ + public static String javaQualifiedName (SymtabEntry entry) + { + String name = ""; + if (entry instanceof PrimitiveEntry) + name = javaPrimName (entry.name ()); + else if (entry instanceof StringEntry) + name = "String"; + else if (entry instanceof ValueEntry && entry.name ().equals ("ValueBase")) + name = "java.io.Serializable"; + else + { + SymtabEntry container = entry.container (); + if (container != null) + name = container.name (); + if (name.equals ("")) + name = entry.name (); + else + name = containerFullName (entry.container ()) + '.' + entry.name (); + } + return name.replace ('/', '.'); + } // javaQualifiedName + + // Publicize for extensions. + //static String collapseName (String name) + + /** + * Collapse primitive type names. + **/ + public static String collapseName (String name) + { + if (name.equals ("unsigned short")) + name = "ushort"; + else if (name.equals ("unsigned long")) + name = "ulong"; + else if (name.equals ("unsigned long long")) + name = "ulonglong"; + else if (name.equals ("long long")) + name = "longlong"; + return name; + } // collapseName + + /** + * + **/ + public static SymtabEntry typeOf (SymtabEntry entry) + { + while (entry instanceof TypedefEntry && ((TypedefEntry)entry).arrayInfo ().isEmpty () && !(entry.type () instanceof SequenceEntry)) + entry = entry.type (); + return entry; + } // typeOf + + /** + * Fill the info field with the full name (with array info) of the type. + **/ + static void fillInfo (SymtabEntry infoEntry) + { + String arrayInfo = ""; + SymtabEntry entry = infoEntry; + boolean alreadyHave = false; + + do + { + try + { + alreadyHave = entry.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo) != null; + } + catch (NoSuchFieldException e) + {} + // If this entry's info has already been processed + // don't bother processing it again, just take it. + if (!alreadyHave) + { + if (entry instanceof TypedefEntry) + arrayInfo = arrayInfo + arrayInfo (((TypedefEntry)entry).arrayInfo ()); + else if (entry instanceof SequenceEntry) + { + com.sun.tools.corba.ee.idl.constExpr.Expression maxSize = ((SequenceEntry)entry).maxSize (); + if (maxSize == null) + arrayInfo = arrayInfo + "[]"; + else + arrayInfo = arrayInfo + '[' + parseExpression (maxSize) + ']'; + } + if (entry.type () == null) + { + // Suppress this message. It tells the developer nothing, and + // this path does not cause the algorithm to fail. Value boxes may + // contain anonymous types, like a struct or enum. + //System.err.println (getMessage ("PreEmit.indeterminateTypeInfo", entry.typeName ())); + } + else + entry = entry.type (); + } + } while (!alreadyHave && entry != null && + (entry instanceof TypedefEntry || entry instanceof SequenceEntry)); + // Value boxes may contain types lacking typename info., which + // causes the 2nd case, below, to fail with exception when retrieving the + // javaName(). + if (entry instanceof ValueBoxEntry) + fillValueBoxInfo ((ValueBoxEntry)entry); + try + { + if (alreadyHave) + infoEntry.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo, (String)entry.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo) + arrayInfo); + else + infoEntry.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo, javaName (entry) + arrayInfo); + } + catch (NoSuchFieldException e) + {} + } // fillInfo + + // + /** + * + **/ + static void fillValueBoxInfo (ValueBoxEntry vb) + { + SymtabEntry stateMember = (((InterfaceState) vb.state ().elementAt (0)).entry); + if (stateMember.type() != null) + Util.fillInfo (stateMember.type ()); + Util.fillInfo (stateMember); + } // fillValueBoxInfo + + /** + * + **/ + public static String holderName (SymtabEntry entry) + { + String name; + if (entry instanceof PrimitiveEntry) + if (entry.name ().equals ("any")) + name = "org.omg.CORBA.AnyHolder"; + else if (entry.name ().equals ("TypeCode")) + name = "org.omg.CORBA.TypeCodeHolder"; + else if (entry.name ().equals ("Principal")) // + name = "org.omg.CORBA.PrincipalHolder"; + else + name = "org.omg.CORBA." + capitalize (javaQualifiedName (entry)) + "Holder"; + else if (entry instanceof TypedefEntry) + { + TypedefEntry td = (TypedefEntry)entry; + if (!td.arrayInfo ().isEmpty () || td.type () instanceof SequenceEntry) + name = javaQualifiedName (entry) + "Holder"; + else + name = holderName (entry.type ()); + } + else if (entry instanceof StringEntry) + name = "org.omg.CORBA.StringHolder"; + else if (entry instanceof ValueEntry) + { + if (entry.name ().equals ("ValueBase")) + name = "org.omg.CORBA.ValueBaseHolder"; // , + else + name = javaName (entry) + "Holder"; + } else if (entry instanceof NativeEntry) { + // do not attach holder to the translation for Native Entries, e.g. + // for Cookie it should be CookieHolder instead of java.lang.ObjectHolder + // returns the complete name for the package, etc. + name = javaQualifiedName(entry) + "Holder"; + } + else + name = javaName (entry) + "Holder"; + return name; + } // holderName + + public static String helperName (SymtabEntry entry, boolean qualifiedName) + { + if (entry instanceof ValueEntry) + if (entry.name ().equals ("ValueBase")) + return "org.omg.CORBA.ValueBaseHelper"; + + if (qualifiedName) + return javaQualifiedName (entry) + "Helper"; + else + return javaName (entry) + "Helper"; + } // helperName + + static final short + TypeFile = 0, + StubFile = 1, + HelperFile = 2, + HolderFile = 3, + StateFile = 4; + + /** + * + **/ + public static void writePackage (PrintWriter stream, SymtabEntry entry) + { + writePackage (stream, entry, TypeFile); + } // writePackage + + /** + * + **/ + public static void writePackage (PrintWriter stream, SymtabEntry entry, String name, short type) + { + if (name != null && !name.equals ("")) + { + stream.println ("package " + name.replace ('/', '.') + ';'); + + // This type is in a module. Just in case it refers to types + // in the unnamed module, add an import statement for each of + // those types. + if (!com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.importTypes.isEmpty ()) + { + stream.println (); + Vector v = addImportLines (entry, com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.importTypes, type); + printImports (v, stream); + } + } + } // writePackage + + /** + * + **/ + public static void writePackage (PrintWriter stream, SymtabEntry entry, short type) + { + String fullName = containerFullName (entry.container ()); + if (fullName != null && !fullName.equals ("")) + { + stream.println ("package " + fullName.replace ('/', '.') + ';'); + // This type is in a module. Just in case it refers to types + // in the unnamed module, add an import statement for each of + // those types. + if ((type != HolderFile || entry instanceof TypedefEntry) && !com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.importTypes.isEmpty ()) + { + stream.println (); + Vector v = addImportLines (entry, com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.importTypes, type); + printImports (v, stream); + } + /* + Enumeration e = Compile.compiler.importTypes.elements (); + while (e.hasMoreElements ()) + { + SymtabEntry i = (SymtabEntry)e.nextElement (); + // Write import for type + if (!(i instanceof TypedefEntry)) + stream.println ("import " + i.name () + ';'); + + // Write import for Helper + if (!(i instanceof ConstEntry)) + stream.println ("import " + i.name () + "Helper;"); + + // Write import for Holder + if (!(i instanceof ConstEntry)) + if (!(i instanceof TypedefEntry) || (i.type () instanceof SequenceEntry || !((TypedefEntry)i).arrayInfo ().isEmpty ())) + stream.println ("import " + i.name () + "Holder;"); + } + */ + } + } // writePackage + + /** + * + **/ + static private void printImports (Vector importList, PrintWriter stream) + { + Enumeration e = importList.elements (); + while (e.hasMoreElements ()) + stream.println ("import " + (String)e.nextElement () + ';'); + } // printImport + + /** + * + **/ + static private void addTo (Vector importList, String name) + { + // REVISIT - was also importing ValueBaseHolder and Helper + if (name.startsWith ("ValueBase")) // don't import ValueBase* + if ((name.compareTo ("ValueBase") == 0) || + (name.compareTo ("ValueBaseHolder") == 0) || + (name.compareTo ("ValueBaseHelper") == 0)) + return; + if (!importList.contains (name)) + importList.addElement (name); + } // addTo + + /** + * + **/ + static private Vector addImportLines (SymtabEntry entry, Vector importTypes, short type) + { + Vector importList = new Vector (); + if (entry instanceof ConstEntry) + { + ConstEntry c = (ConstEntry)entry; + Object cvalue = c.value ().value (); + if (cvalue instanceof ConstEntry && importTypes.contains (cvalue)) + addTo (importList, ((ConstEntry)cvalue).name ()); + } + else if (entry instanceof ValueEntry && type == HelperFile) // + { + // This code inspired by ValueGen.getConcreteBaseTypeCode(). Helper method + // type() could be invoked against a global valuetype. + if (((ValueEntry)entry).derivedFrom ().size () > 0) // <59596> KLR HACK + { + ValueEntry base = (ValueEntry)((ValueEntry)entry).derivedFrom ().elementAt (0); + String baseName = base.name (); + if (!"ValueBase".equals (baseName)) + if (importTypes.contains (base)) + addTo (importList, baseName + "Helper"); + } + } + else if (entry instanceof InterfaceEntry && (type == TypeFile || type == StubFile)) + { + InterfaceEntry i = (InterfaceEntry)entry; + + if (i instanceof ValueEntry) // + { + // Examine interface parents in supports vector. + Enumeration e = ((ValueEntry)i).supports ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry parent = (SymtabEntry)e.nextElement (); + if (importTypes.contains (parent)) + { + addTo (importList, parent.name () + "Operations"); + } + // If this is a stub, then recurse to the parents + if (type == StubFile) + { + if (importTypes.contains (parent)) + addTo (importList, parent.name ()); + Vector subImportList = addImportLines (parent, importTypes, StubFile); + Enumeration en = subImportList.elements (); + while (en.hasMoreElements ()) + { + addTo (importList, (String)en.nextElement ()); + } + } + } + } + // Interface or valuetype -- Examine interface and valuetype parents, + // Look through derivedFrom vector + Enumeration e = i.derivedFrom ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry parent = (SymtabEntry)e.nextElement (); + if (importTypes.contains (parent)) + { + addTo (importList, parent.name ()); + // Always add both imports, even though superfluous. Cannot + // tell when writing Operations or Signature interface! + if (!(parent instanceof ValueEntry)) // && parent.name ().equals ("ValueBase"))) + addTo (importList, parent.name () + "Operations"); + } + // If this is a stub, then recurse to the parents + if (type == StubFile) + { + Vector subImportList = addImportLines (parent, importTypes, StubFile); + Enumeration en = subImportList.elements (); + while (en.hasMoreElements ()) + { + addTo (importList, (String)en.nextElement ()); + } + } + } + // Look through methods vector + e = i.methods ().elements (); + while (e.hasMoreElements ()) + { + MethodEntry m = (MethodEntry)e.nextElement (); + + // Look at method type + SymtabEntry mtype = typeOf (m.type ()); + if (mtype != null && importTypes.contains (mtype)) + if (type == TypeFile || type == StubFile) + { + addTo (importList, mtype.name ()); + addTo (importList, mtype.name () + "Holder"); + if (type == StubFile) + addTo (importList, mtype.name () + "Helper"); + } + checkForArrays (mtype, importTypes, importList); + // Print import lines for globals constants and constants + // within global interfaces. + if (type == StubFile) + checkForBounds (mtype, importTypes, importList); + + // Look through exceptions + Enumeration exEnum = m.exceptions ().elements (); + while (exEnum.hasMoreElements ()) + { + ExceptionEntry ex = (ExceptionEntry)exEnum.nextElement (); + if (importTypes.contains (ex)) + { + addTo (importList, ex.name ()); + addTo (importList, ex.name () + "Helper"); // + } + } + + // Look through parameters + Enumeration parms = m.parameters ().elements (); + while (parms.hasMoreElements ()) + { + ParameterEntry parm = (ParameterEntry)parms.nextElement (); + SymtabEntry parmType = typeOf (parm.type ()); + if (importTypes.contains (parmType)) + { + // Helper needed in stubs. + if (type == StubFile) + addTo (importList, parmType.name () + "Helper"); + if (parm.passType () == ParameterEntry.In) + addTo (importList, parmType.name ()); + else + addTo (importList, parmType.name () + "Holder"); + } + checkForArrays (parmType, importTypes, importList); + // + if (type == StubFile) + checkForBounds (parmType, importTypes, importList); + } + } + } + else if (entry instanceof StructEntry) + { + StructEntry s = (StructEntry)entry; + + // Look through the members + Enumeration members = s.members ().elements (); + while (members.hasMoreElements ()) + { + SymtabEntry member = (TypedefEntry)members.nextElement (); + // Need to add helper name for typedef members. This name + // is referenced at typecode generation in Helper class. + SymtabEntry memberType = member.type (); + member = typeOf (member); + if (importTypes.contains (member)) + { + // If this IS a typedef, then there are only Helper/Holder classes. + //if (!(member instanceof TypedefEntry)) + // Valueboxes + if (!(member instanceof TypedefEntry) && !(member instanceof ValueBoxEntry)) + addTo (importList, member.name ()); + // Add helper name of alias, too, if member is a typedef. + //if (type == HelperFile) + // addTo (importList, member.name () + "Helper"); + if (type == HelperFile) + { + addTo (importList, member.name () + "Helper"); + if (memberType instanceof TypedefEntry) + addTo (importList, memberType.name () + "Helper"); + } + } + checkForArrays (member, importTypes, importList); + checkForBounds (member, importTypes, importList); + } + } + else if (entry instanceof TypedefEntry) + { + TypedefEntry t = (TypedefEntry)entry; + String arrays = checkForArrayBase (t, importTypes, importList); + if (type == HelperFile) + { + checkForArrayDimensions (arrays, importTypes, importList); + try + { + String name = (String)t.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo); + int index = name.indexOf ('['); + if (index >= 0) + name = name.substring (0, index); + // See if the base type should be added to the list. + SymtabEntry typeEntry = (SymtabEntry)symbolTable.get (name); + if (typeEntry != null && importTypes.contains (typeEntry)) + addTo (importList, typeEntry.name () + "Helper"); + } + catch (NoSuchFieldException e) + {} + + // Typedefs for global bounded strings need import + // statement when bound expression contains non-literal constants. + checkForBounds (typeOf (t), importTypes, importList); + } + Vector subImportList = addImportLines (t.type (), importTypes, type); + Enumeration e = subImportList.elements (); + while (e.hasMoreElements ()) + addTo (importList, (String)e.nextElement ()); + } + else if (entry instanceof UnionEntry) + { + UnionEntry u = (UnionEntry)entry; + + // Look at the discriminant type + SymtabEntry utype = typeOf (u.type ()); + if (utype instanceof EnumEntry && importTypes.contains (utype)) + addTo (importList, utype.name ()); + + // Look through the branches + Enumeration branches = u.branches ().elements (); + while (branches.hasMoreElements ()) + { + UnionBranch branch = (UnionBranch)branches.nextElement (); + SymtabEntry branchEntry = typeOf (branch.typedef); + if (importTypes.contains (branchEntry)) + { + addTo (importList, branchEntry.name ()); + if (type == HelperFile) + addTo (importList, branchEntry.name () + "Helper"); + } + checkForArrays (branchEntry, importTypes, importList); + // + checkForBounds (branchEntry, importTypes, importList); + } + } + + // If a typedef is not a sequence or an array, only holders and + // helpers are generated for it. Remove references to such + // class names. + Enumeration en = importList.elements (); + while (en.hasMoreElements ()) + { + String name = (String)en.nextElement (); + SymtabEntry e = (SymtabEntry)symbolTable.get (name); + if (e != null && e instanceof TypedefEntry) + { + TypedefEntry t = (TypedefEntry)e; + if (t.arrayInfo ().size () == 0 || !(t.type () instanceof SequenceEntry)) + importList.removeElement (name); + } + } + return importList; + } // addImportLines + + /** + * + **/ + static private void checkForArrays (SymtabEntry entry, Vector importTypes, Vector importList) + { + if (entry instanceof TypedefEntry) + { + TypedefEntry t = (TypedefEntry)entry; + String arrays = checkForArrayBase (t, importTypes, importList); + checkForArrayDimensions (arrays, importTypes, importList); + } + } // checkForArrays + + /** + * + **/ + static private String checkForArrayBase (TypedefEntry t, Vector importTypes, Vector importList) + { + String arrays = ""; + try + { + String name = (String)t.dynamicVariable (com.sun.tools.corba.ee.idl.toJavaPortable.Compile.typedefInfo); + int index = name.indexOf ('['); + if (index >= 0) + { + arrays = name.substring (index); + name = name.substring (0, index); + } + + // See if the base type should be added to the list. + SymtabEntry typeEntry = (SymtabEntry)symbolTable.get (name); + if (typeEntry != null && importTypes.contains (typeEntry)) + addTo (importList, typeEntry.name ()); + } + catch (NoSuchFieldException e) + {} + return arrays; + } // checkForArrayBase + + /** + * + **/ + static private void checkForArrayDimensions (String arrays, Vector importTypes, Vector importList) + { + // See if any of the arrays contain a constentry. + // If so, see if it should be added to the list. + while (!arrays.equals ("")) + { + int index = arrays.indexOf (']'); + String dim = arrays.substring (1, index); + arrays = arrays.substring (index + 1); + SymtabEntry constant = (SymtabEntry)symbolTable.get (dim); + if (constant == null) + { + // A constant expr could be of the form OR + // .. This if branch checks for that case. + int i = dim.lastIndexOf ('.'); + if (i >= 0) + constant = (SymtabEntry)symbolTable.get (dim.substring (0, i)); + } + if (constant != null && importTypes.contains (constant)) + addTo (importList, constant.name ()); + } + } // checkForArrayDimensions + + // Call the following method when its necessary to determine the + // the import types for IDL constructs containing arbitrary positive int. + // expressions, which may specify non-literal constants. + + /** + * Determine the import lines for template types. + **/ + static private void checkForBounds (SymtabEntry entry, Vector importTypes, Vector importList) + { + // Obtain actual type, just to be complete. + SymtabEntry entryType = entry; + while (entryType instanceof TypedefEntry) + entryType = entryType.type (); + + if (entryType instanceof StringEntry && ((StringEntry)entryType).maxSize () != null) + checkForGlobalConstants (((StringEntry)entryType).maxSize ().rep (), importTypes, importList); + else + if (entryType instanceof SequenceEntry && ((SequenceEntry)entryType).maxSize () != null) + checkForGlobalConstants (((SequenceEntry)entryType).maxSize ().rep (), importTypes, importList); + } // checkForBounds + + /** + * Extract the global constants from the supplied integer expression + * representation (string) and add them to the supplied import list. + **/ + static private void checkForGlobalConstants (String exprRep, Vector importTypes, Vector importList) + { + // NOTE: Do not use '/' as a delimiter. Symbol table names use '/' as a + // delimiter and would not be otherwise properly collected. Blanks and + // arithmetic symbols do not appear in tokens, except for '/'. + java.util.StringTokenizer st = new java.util.StringTokenizer (exprRep, " +-*()~&|^%<>"); + while (st.hasMoreTokens ()) + { + String token = st.nextToken (); + // When token contains '/', it represents the division symbol or + // a nested type (e.g., I/x). Ignore the division symbol, and don't + // forget constants declared within global interfaces! + if (!token.equals ("/")) + { + SymtabEntry typeEntry = (SymtabEntry)symbolTable.get (token); + if (typeEntry instanceof ConstEntry) + { + int slashIdx = token.indexOf ('/'); + if (slashIdx < 0) // Possible global constant + { + if (importTypes.contains (typeEntry)) + addTo (importList, typeEntry.name ()); + } + else // Possible constant in global interface + { + SymtabEntry constContainer = (SymtabEntry)symbolTable.get (token.substring (0, slashIdx)); + if (constContainer instanceof InterfaceEntry && importTypes.contains (constContainer)) + addTo (importList, constContainer.name ()); + } + } + } + } + } // checkForGlobalConstants + + /** + * + **/ + public static void writeInitializer (String indent, String name, String arrayDcl, SymtabEntry entry, PrintWriter stream) + { + if (entry instanceof TypedefEntry) + { + TypedefEntry td = (TypedefEntry)entry; + writeInitializer (indent, name, arrayDcl + sansArrayInfo (td.arrayInfo ()), td.type (), stream); + } + else if (entry instanceof SequenceEntry) + writeInitializer (indent, name, arrayDcl + "[]", entry.type (), stream); + else if (entry instanceof EnumEntry) + if (arrayDcl.length () > 0) + stream.println (indent + javaName (entry) + ' ' + name + arrayDcl + " = null;"); + else + stream.println (indent + javaName (entry) + ' ' + name + " = null;"); + else if (entry instanceof PrimitiveEntry) + { + boolean array = arrayDcl.length () > 0; + String tname = javaPrimName (entry.name ()); + if (tname.equals ("boolean")) + stream.println (indent + "boolean " + name + arrayDcl + " = " + (array ? "null;" : "false;")); + else if (tname.equals ("org.omg.CORBA.TypeCode")) + stream.println (indent + "org.omg.CORBA.TypeCode " + name + arrayDcl + " = null;"); + else if (tname.equals ("org.omg.CORBA.Any")) + stream.println (indent + "org.omg.CORBA.Any " + name + arrayDcl + " = null;"); + else if (tname.equals ("org.omg.CORBA.Principal")) // + stream.println (indent + "org.omg.CORBA.Principal " + name + arrayDcl + " = null;"); + else + stream.println (indent + tname + ' ' + name + arrayDcl + " = " + (array ? "null;" : '(' + tname + ")0;")); + } + // Remove -stateful feature. This case is identical to next one + // because javaName() supplants javaStatefulName(). + //else if (entry instanceof InterfaceEntry && ((InterfaceEntry)entry).state () != null) + // stream.println (indent + javaStatefulName ((InterfaceEntry)entry) + ' ' + name + arrayDcl + " = null;"); + else + stream.println (indent + javaName (entry) + ' ' + name + arrayDcl + " = null;"); + } // writeInitializer + + /** + * + **/ + public static void writeInitializer (String indent, String name, String arrayDcl, SymtabEntry entry, String initializer, PrintWriter stream) + { + if (entry instanceof TypedefEntry) + { + TypedefEntry td = (TypedefEntry)entry; + writeInitializer (indent, name, arrayDcl + sansArrayInfo (td.arrayInfo ()), td.type (), initializer, stream); + } + else if (entry instanceof SequenceEntry) + writeInitializer (indent, name, arrayDcl + "[]", entry.type (), initializer, stream); + else if (entry instanceof EnumEntry) + if (arrayDcl.length () > 0) + stream.println (indent + javaName (entry) + ' ' + name + arrayDcl + " = " + initializer + ';'); + else + stream.println (indent + javaName (entry) + ' ' + name + " = " + initializer + ';'); + else if (entry instanceof PrimitiveEntry) + { + boolean array = arrayDcl.length () > 0; + String tname = javaPrimName (entry.name ()); + if (tname.equals ("boolean")) + stream.println (indent + "boolean " + name + arrayDcl + " = " + initializer + ';'); + else if (tname.equals ("org.omg.CORBA.TypeCode")) + stream.println (indent + "org.omg.CORBA.TypeCode " + name + arrayDcl + " = " + initializer + ';'); + else if (tname.equals ("org.omg.CORBA.Any")) + stream.println (indent + "org.omg.CORBA.Any " + name + arrayDcl + " = " + initializer + ';'); + else if (tname.equals ("org.omg.CORBA.Principal")) // + stream.println (indent + "org.omg.CORBA.Principal " + name + arrayDcl + " = " + initializer + ';'); + else + stream.println (indent + tname + ' ' + name + arrayDcl + " = " + initializer + ';'); + } + // Remove -stateful feature. This case is identical to next one + // because javaName() supplants javaStatefulName(). + //else if (entry instanceof InterfaceEntry && ((InterfaceEntry)entry).state () != null) + // stream.println (indent + javaStatefulName ((InterfaceEntry)entry) + ' ' + name + arrayDcl + " = " + initializer + ';'); + else + stream.println (indent + javaName (entry) + ' ' + name + arrayDcl + " = " + initializer + ';'); + } // writeInitializer + + /** + * + **/ + public static void mkdir (String name) + { + String targetDir = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).targetDir; // F46838.4 + name = (targetDir + name).replace ('/', File.separatorChar); // F46838.4 + File pkg = new File (name); + if (!pkg.exists ()) + if (!pkg.mkdirs ()) + System.err.println (getMessage ("Util.cantCreatePkg", name)); + } // mkdir + + /** + * + **/ + public static void writeProlog (PrintWriter stream, String filename) + { + // Remove target directory + String targetDir = ((com.sun.tools.corba.ee.idl.toJavaPortable.Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).targetDir; + if (targetDir != null) + filename = filename.substring (targetDir.length ()); + stream.println (); + stream.println ("/**"); + stream.println ("* " + filename.replace (File.separatorChar, '/') + + " ."); + stream.println ("* " + Util.getMessage ("toJavaProlog1", + Util.getMessage ("Version.product", Util.getMessage ("Version.number")))); + // Do not introduce invalid escape characters into comment! + //stream.println ("* " + Util.getMessage ("toJavaProlog2", Compile.compiler.arguments.file)); + stream.println ("* " + Util.getMessage ("toJavaProlog2", com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments.file.replace (File.separatorChar, '/'))); + + /////////////// + // This SHOULD work, but there's a bug in the JDK. + // stream.println ("* " + DateFormat.getDateTimeInstance (DateFormat.FULL, DateFormat.FULL, Locale.getDefault ()).format (new Date ())); + // This gets around the bug: + + DateFormat formatter = DateFormat.getDateTimeInstance (DateFormat.FULL, DateFormat.FULL, Locale.getDefault ()); + + // Japanese-specific workaround. JDK bug 4069784 being repaired by JavaSoft. + // Keep this transient solution until bug fix is reported.cd . + + if (Locale.getDefault () == Locale.JAPAN) + formatter.setTimeZone (java.util.TimeZone.getTimeZone ("JST")); + else + formatter.setTimeZone (java.util.TimeZone.getDefault ()); + + stream.println ("* " + formatter.format (new Date ())); + + // + /////////////// + + stream.println ("*/"); + stream.println (); + } // writeProlog + + // keywords ending in Holder or Helper or Package have '_' prepended. + // These prepended underscores must not be part of anything sent + // across the wire, so these two methods are provided to strip them + // off. + + /** + * + **/ + public static String stripLeadingUnderscores (String string) + { + while (string.startsWith ("_")) + string = string.substring (1); + return string; + } // stripLeadingUnderscores + + /** + * + **/ + public static String stripLeadingUnderscoresFromID (String string) + { + String stringPrefix = ""; + int slashIndex = string.indexOf (':'); + if (slashIndex >= 0) + do + { + stringPrefix = stringPrefix + string.substring (0, slashIndex + 1); + string = string.substring (slashIndex + 1); + while (string.startsWith ("_")) + string = string.substring (1); + slashIndex = string.indexOf ('/'); + } while (slashIndex >= 0); + return stringPrefix + string; + } // stripLeadingUnderscoresFromID + + /** + * + **/ + public static String parseExpression (com.sun.tools.corba.ee.idl.constExpr.Expression e) + { + if (e instanceof com.sun.tools.corba.ee.idl.constExpr.Terminal) + return parseTerminal ((com.sun.tools.corba.ee.idl.constExpr.Terminal)e); + else if (e instanceof com.sun.tools.corba.ee.idl.constExpr.BinaryExpr) + return parseBinary ((com.sun.tools.corba.ee.idl.constExpr.BinaryExpr)e); + else if (e instanceof com.sun.tools.corba.ee.idl.constExpr.UnaryExpr) + return parseUnary ((com.sun.tools.corba.ee.idl.constExpr.UnaryExpr)e); + else + return "(UNKNOWN_VALUE)"; // This shouldn't happen unless someone slips + // in another type of expression. + } // parseExpression + + /** + * + **/ + static String parseTerminal (com.sun.tools.corba.ee.idl.constExpr.Terminal e) + { + if (e.value () instanceof ConstEntry) + { + ConstEntry c = (ConstEntry)e.value (); + if (c.container () instanceof InterfaceEntry) + return javaQualifiedName (c.container ()) + '.' + c.name (); + else + return javaQualifiedName (c) + ".value"; + } + else if (e.value () instanceof com.sun.tools.corba.ee.idl.constExpr.Expression) + return '(' + parseExpression ((com.sun.tools.corba.ee.idl.constExpr.Expression)e.value ()) + ')'; + else if (e.value () instanceof Character) + { + if (((Character)e.value ()).charValue () == '\013') + // e.rep is \v. \v for vertical tab is meaningless in Java. + return "'\\013'"; + else if (((Character)e.value ()).charValue () == '\007') + // e.rep is \a. \a for alert is meaningless in Java. + return "'\\007'"; + else if (e.rep ().startsWith ("'\\x")) + return hexToOctal (e.rep ()); + else if (e.rep ().equals ("'\\?'")) + return "'?'"; + else + return e.rep (); + } + else if (e.value () instanceof Boolean) + return e.value ().toString (); + + // If value is type "unsigned long long" (ull) and its magnitude + // is greater than the maximal Java long (i.e., IDL long long) value, then + // return its signed representation rather than its actual representation. + /* + // Support long long + //else if (e.value () instanceof Long) + else if (e.value () instanceof BigInteger && + (e.type ().indexOf ("long long") >= 0 || e.type ().equals ("unsigned long"))) // + { + String rep = e.rep (); + int index = rep.indexOf (')'); + if (index < 0) + return rep + 'L'; + else + return rep.substring (0, index) + 'L' + rep.substring (index); + } + */ + else if (e.value () instanceof BigInteger) + { + // Get the correct primitive type. Since integer types (octet, short, + // long, long long, unsigned short, unsigned long, unsigned long long) + // could be aliased (typedef'ed) to any arbitrary levels, the code + // below walks up the alias chain to get to the primitive type. + + // Get the symbol table entry corresponding to the 'type'. + SymtabEntry typeEntry = (SymtabEntry) symbolTable.get(e.type()); + + // Get to the primitive type. + while (typeEntry.type() != null) { + typeEntry = typeEntry.type(); + } + String type = typeEntry.name(); + + if (type.equals("unsigned long long") && + ((BigInteger)e.value ()).compareTo (com.sun.tools.corba.ee.idl.constExpr.Expression.llMax) > 0) // value > long long Max? + { + // Convert to signed value, which will always be negative. + BigInteger v = (BigInteger)e.value (); + v = v.subtract (com.sun.tools.corba.ee.idl.constExpr.Expression.twoPow64); + int index = e.rep ().indexOf (')'); + if (index < 0) + return v.toString () + 'L'; + else + return '(' + v.toString () + 'L' + ')'; + } + else if ( type.indexOf("long long") >= 0 || type.equals("unsigned long") ) + { + String rep = e.rep (); + int index = rep.indexOf (')'); + if (index < 0) + return rep + 'L'; + else + return rep.substring (0, index) + 'L' + rep.substring (index); + } + else + return e.rep (); + } // end + else + return e.rep (); + } // parseTerminal + + /** + * + **/ + static String hexToOctal (String hex) + { + // The format of hex is '/xXX' where XX is one or two hex digits. + // This statement pulls off XX. + hex = hex.substring (3, hex.length () - 1); + return "'\\" + Integer.toString (Integer.parseInt (hex, 16), 8) + "'"; + } // hexToOctal + + /** + * + **/ + static String parseBinary (com.sun.tools.corba.ee.idl.constExpr.BinaryExpr e) + { + String castString = ""; + if (e.value () instanceof Float || e.value () instanceof Double) + { + castString = "(double)"; + if (!(e instanceof com.sun.tools.corba.ee.idl.constExpr.Plus || e instanceof com.sun.tools.corba.ee.idl.constExpr.Minus || + e instanceof com.sun.tools.corba.ee.idl.constExpr.Times || e instanceof com.sun.tools.corba.ee.idl.constExpr.Divide)) + System.err.println ("Operator " + e.op () + " is invalid on floating point numbers"); + } + else if (e.value () instanceof Number) + { + if (e.type (). indexOf ("long long") >= 0) + castString = "(long)"; + else + castString = "(int)"; + } + else + { + castString = ""; + System.err.println ("Unknown type in constant expression"); + } + + // Must emit value rather than representation when type "unsigned + // long long" (ull) because emitted binary arithmetic expressions containing + // ull's converted to long (i.e., IDL long long) do not always compute to + // the correct result. + + //return castString + '(' + parseExpression (e.left ()) + ' ' + e.op () + ' ' + parseExpression (e.right ()) + ')'; + if (e.type ().equals ("unsigned long long")) + { + BigInteger value = (BigInteger)e.value (); + if (value.compareTo (com.sun.tools.corba.ee.idl.constExpr.Expression.llMax) > 0) // value > long long max? + value = value.subtract (com.sun.tools.corba.ee.idl.constExpr.Expression.twoPow64); // Convert to Java long (signed) + return castString + '(' + value.toString () + 'L' + ')'; + } + else + return castString + '(' + parseExpression (e.left ()) + ' ' + e.op () + ' ' + parseExpression (e.right ()) + ')'; + // end + } // parseBinary + + /** + * + **/ + static String parseUnary (com.sun.tools.corba.ee.idl.constExpr.UnaryExpr e) + { + if (!(e.value () instanceof Number)) + return "(UNKNOWN_VALUE)"; // This shouldn't happen if the parser checked the expression types correctly. + else if ((e.value () instanceof Float || e.value () instanceof Double) && e instanceof com.sun.tools.corba.ee.idl.constExpr.Not) + return "(UNKNOWN_VALUE)"; // This shouldn't happen if the parser checked the expression types correctly. + else + { + String castString = ""; + if (e.operand ().value () instanceof Float || + e.operand ().value () instanceof Double) + castString = "(double)"; + // Support long long. + //else + // castString = "(long)"; + else if (e.type (). indexOf ("long long") >= 0) + castString = "(long)"; + else + castString = "(int)"; + + // Must emit value rather than representation when type is + // "unsigned long long" (ull) because emitted unary arithmetic expressions + // containing a ull converted to long (i.e., IDL long long) do not always + // compute to the correct result. + + //return castString + e.op () + parseExpression (e.operand ()); + if (e.type ().equals ("unsigned long long")) + { + BigInteger value = (BigInteger)e.value (); + if (value.compareTo (com.sun.tools.corba.ee.idl.constExpr.Expression.llMax) > 0) // value > long long max? + value = value.subtract (com.sun.tools.corba.ee.idl.constExpr.Expression.twoPow64); // Convert to Java long (signed) + return castString + '(' + value.toString () + 'L' + ')'; + } + else + return castString + e.op () + parseExpression (e.operand ()); + // end + } + } // parseUnary + + /** + * + **/ + public static boolean IDLEntity (SymtabEntry entry) + { + boolean rc = true; + if (entry instanceof PrimitiveEntry || entry instanceof StringEntry) + rc = false; + else if (entry instanceof TypedefEntry) + rc = IDLEntity (entry.type ()); + return rc; + } // IDLEntity + + // + /** + * @return true if the current setting of corbaLevel is within delta of + * the range min <= corbaLevel <= max + **/ + public static boolean corbaLevel (float min, float max) + { + float level = com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments.corbaLevel; + float delta = 0.001f; + if ((level - min + delta >= 0.0f) && (max - level + delta >= 0.0f)) + return true; + else + return false; + } // corbaLevel + + static Hashtable symbolTable = new Hashtable (); + private static Hashtable packageTranslation = new Hashtable() ; +} // class Util + diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueBoxGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueBoxGen.java new file mode 100644 index 000000000..507f20cce --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueBoxGen.java @@ -0,0 +1,322 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D60929 Update for RTF2.4 changes +// -D61056 Use Util.helperName +// -D62023 Fix generation botch in helper.read for boxed bounded strings + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Enumeration; +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; + +/** + * + **/ +public class ValueBoxGen implements com.sun.tools.corba.ee.idl.ValueBoxGen, com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public ValueBoxGen () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, ValueBoxEntry v, PrintWriter str) + { + this.symbolTable = symbolTable; + this.v = v; + + TypedefEntry member = ((InterfaceState) v.state ().elementAt (0)).entry; + SymtabEntry mType = member.type (); + // if it's primitive type, generate a java class + if (mType instanceof PrimitiveEntry) + { + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } + else + { + // If a constructed type is nested in the value box, + // value v struct s {...}; + // the bindings for the nested type must be handled here + Enumeration e = v.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry contained = (SymtabEntry) e.nextElement (); + + // in case of value box w/ nested enum, ex: value v enum e {e0, e1,...}; + // the SymtabEntry for the enum and labels are contained in the vector. + // Must check the type to ignore the SymtabEntry for labels. + if (contained.type () != null) + contained.type ().generate (symbolTable, stream); + } + } + generateHelper (); + generateHolder (); + } // generate + + /** + * + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(v, ".java"); + } // openStream + + /** + * + **/ + protected void generateHelper () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, v); + } // generateHelper + + /** + * + **/ + protected void generateHolder () + { + ((Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, v); + } // generateHolder + + /** + * + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, v); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + if (v.comment () != null) + v.comment ().generate ("", stream); +// stream.println ("public class " + v.name () + " implements org.omg.CORBA.portable.ValueBase, org.omg.CORBA.portable.Streamable"); + stream.println ("public class " + v.name () + " implements org.omg.CORBA.portable.ValueBase"); // + stream.println ("{"); + } // writeHeading + + /** + * + **/ + protected void writeBody () + { + InterfaceState member = (InterfaceState) v.state ().elementAt (0); + SymtabEntry entry = (SymtabEntry) member.entry; + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(entry); + if (entry.comment () != null) + entry.comment ().generate (" ", stream); + stream.println (" public " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry) + " value;"); + stream.println (" public " + v.name () + " (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry) + " initial)"); + stream.println (" {"); + stream.println (" value = initial;"); + stream.println (" }"); + stream.println (); + writeTruncatable (); // +// writeStreamableMethods (); + } // writeBody + + /** + * + **/ + protected void writeTruncatable () // + { + // Per Simon, 4/6/98, emit _truncatable_ids() + stream.println (" public String[] _truncatable_ids() {"); + stream.println (" return " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(v, true) + ".get_instance().get_truncatable_base_ids();"); // + stream.println (" }"); + stream.println (); + } // writeTruncatable + + /** + * + **/ + protected void writeClosing () + { + stream.println ("} // class " + v.name ()); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /** + * + **/ + protected void writeStreamableMethods () + { + stream.println (" public void _read (org.omg.CORBA.portable.InputStream istream)"); + stream.println (" {"); + streamableRead ("this", v, stream); + stream.println (" }"); + stream.println (); + stream.println (" public void _write (org.omg.CORBA.portable.OutputStream ostream)"); + stream.println (" {"); + write (0, " ", "this", v, stream); + stream.println (" }"); + stream.println (); + stream.println (" public org.omg.CORBA.TypeCode _type ()"); + stream.println (" {"); + stream.println (" return " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(v, false) + ".type ();"); // + stream.println (" }"); + } // writeStreamableMethods + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + ValueEntry vt = (ValueEntry) entry; + TypedefEntry member = (TypedefEntry) ((InterfaceState) (vt.state ()).elementAt (0)).entry; + SymtabEntry mType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(member); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)mType.generator ()).type (index, indent, tcoffsets, name, mType, stream); + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_value_box_tc (" + + "_id, " + + '"' + entry.name () + "\", " + + name + + ");"); + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); // + return index; + } // type + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + return index; + } // read + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + // per Simon, make "static" read call istream.read_value. + // put real marshalling code in read_value. + stream.println (" return (" + entryName +") ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (get_instance());"); // + stream.println (" }"); + stream.println (); + + // done with "read", now do "read_value with real marshalling code. + + stream.println (" public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream)"); // + stream.println (" {"); + // end of changes + + String indent = " "; + Vector vMembers = ((ValueBoxEntry) entry).state (); + TypedefEntry member = ((InterfaceState) vMembers.elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof PrimitiveEntry || + mType instanceof SequenceEntry || + mType instanceof TypedefEntry || + mType instanceof StringEntry || + !member.arrayInfo ().isEmpty ()) { + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType) + " tmp;"); // + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).read (0, indent, "tmp", member, stream); + } + else if (mType instanceof ValueEntry || mType instanceof ValueBoxEntry) + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(mType) + " tmp = (" + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(mType) + ") ((org.omg.CORBA_2_3.portable.InputStream)istream).read_value (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".get_instance ());"); // // + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType) + " tmp = " + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".read (istream);"); // + if (mType instanceof PrimitiveEntry) + stream.println (indent + "return new " + entryName + " (tmp);"); + else + stream.println (indent + "return tmp;"); + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + // per Simon, make "static" write call istream.write_value. + // put real marshalling code in write_value. + stream.println (" ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, get_instance());"); // + stream.println (" }"); + stream.println (); + + // done with "write", now do "write_value with real marshalling code. + + stream.println (" public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable obj)"); // + stream.println (" {"); + + String entryName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + stream.println (" " + entryName + " value = (" + entryName + ") obj;"); + write (0, " ", "value", entry, stream); + } // helperWrite + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + Vector vMembers = ( (ValueEntry) entry ).state (); + TypedefEntry member = ((InterfaceState) vMembers.elementAt (0)).entry; + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry || !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, indent, name + ".value", member, stream); + else if (mType instanceof SequenceEntry || mType instanceof StringEntry || mType instanceof TypedefEntry || !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, indent, name, member, stream); + else if (mType instanceof ValueEntry || mType instanceof ValueBoxEntry) + stream.println (indent + + "((org.omg.CORBA_2_3.portable.OutputStream)ostream).write_value ((java.io.Serializable) value, " // + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) // + + ".get_instance ());"); // + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".write (ostream, " + name + ");"); // + return index; + } // write + + protected void writeAbstract () + { + } // writeAbstract + + protected void streamableRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + Vector vMembers = ( (ValueBoxEntry) entry ).state (); + TypedefEntry member = ((InterfaceState) vMembers.elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof PrimitiveEntry || mType instanceof SequenceEntry || mType instanceof TypedefEntry || + mType instanceof StringEntry || !member.arrayInfo ().isEmpty ()) + { + SymtabEntry mEntry = (SymtabEntry) ((InterfaceState) vMembers.elementAt (0)).entry; + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).read (0, " ", entryName + ".value", member, stream); + } + else if (mType instanceof ValueEntry || mType instanceof ValueBoxEntry) + stream.println (" " + entryName + ".value = (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(mType) + ") ((org.omg.CORBA_2_3.portable.InputStream)istream).read_value (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".get_instance ());"); // // + else + stream.println (" " + entryName + ".value = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".read (istream);"); // + } // streamableRead + + protected Hashtable symbolTable = null; + protected ValueBoxEntry v = null; + protected PrintWriter stream = null; +} // class ValueBoxGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueBoxGen24.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueBoxGen24.java new file mode 100644 index 000000000..f931b5a87 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueBoxGen24.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 Update for Java 2.4 RTF + +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +import java.io.PrintWriter; +import java.util.Vector; + +/** + * + **/ +public class ValueBoxGen24 extends ValueBoxGen +{ + /** + * Public zero-argument constructor. + **/ + public ValueBoxGen24 () + { + } // ctor + + protected void writeTruncatable () // + { + stream.print (" private static String[] _truncatable_ids = {"); + stream.println (com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(v, true) + ".id ()};"); + stream.println (); + stream.println (" public String[] _truncatable_ids() {"); + stream.println (" return _truncatable_ids;"); + stream.println (" }"); + stream.println (); + } // writeTruncatable + + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + stream.println (" if (!(istream instanceof org.omg.CORBA_2_3.portable.InputStream)) {"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM(); }"); + stream.println (" return (" + entryName +") ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (_instance);"); + stream.println (" }"); + stream.println (); + + // done with "read", now do "read_value with real marshalling code. + + stream.println (" public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream)"); // + stream.println (" {"); + + String indent = " "; + Vector vMembers = ((ValueBoxEntry) entry).state (); + TypedefEntry member = ((InterfaceState) vMembers.elementAt (0)).entry; + SymtabEntry mType = member.type (); + if (mType instanceof PrimitiveEntry || + mType instanceof SequenceEntry || + mType instanceof TypedefEntry || + mType instanceof StringEntry || + !member.arrayInfo ().isEmpty ()) { + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType) + " tmp;"); + ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).read (0, indent, "tmp", member, stream); + } + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType) + " tmp = " + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".read (istream);"); + if (mType instanceof PrimitiveEntry) + stream.println (indent + "return new " + entryName + " (tmp);"); + else + stream.println (indent + "return (java.io.Serializable) tmp;"); + } // helperRead + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + stream.println (" if (!(ostream instanceof org.omg.CORBA_2_3.portable.OutputStream)) {"); + stream.println (" throw new org.omg.CORBA.BAD_PARAM(); }"); + stream.println (" ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, _instance);"); + stream.println (" }"); + stream.println (); + + // done with "write", now do "write_value with real marshalling code. + + stream.println (" public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable value)"); + stream.println (" {"); + + String entryName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + stream.println (" if (!(value instanceof " + entryName + ")) {"); + stream.println (" throw new org.omg.CORBA.MARSHAL(); }"); + stream.println (" " + entryName + " valueType = (" + entryName + ") value;"); + write (0, " ", "valueType", entry, stream); + } // helperWrite + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + Vector vMembers = ( (ValueEntry) entry ).state (); + TypedefEntry member = ((InterfaceState) vMembers.elementAt (0)).entry; + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry || !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, indent, name + ".value", member, stream); + else if (mType instanceof SequenceEntry || mType instanceof StringEntry || mType instanceof TypedefEntry || !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, indent, name, member, stream); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".write (ostream, " + name + ");"); // + return index; + } // write +} diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueFactory.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueFactory.java new file mode 100644 index 000000000..ee31663b9 --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueFactory.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 klr new class + +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +/** + * + **/ +public class ValueFactory implements AuxGen +{ + /** + * Public zero-argument constructor. + **/ + public ValueFactory () + { + } // ctor + + /** + * Generate the default value factory class. Provides general algorithm for + * auxiliary binding generation: + * 1.) Initialize symbol table and symbol table entry members, + * common to all generators. + * 2.) Initialize members unique to this generator. + * 3.) Open print stream + * 4.) Write class heading (package, prologue, source comment, class + * statement, open curly + * 5.) Write class body (member data and methods) + * 6.) Write class closing (close curly) + * 7.) Close the print stream + **/ + public void generate (java.util.Hashtable symbolTable, SymtabEntry entry) + { + this.symbolTable = symbolTable; + this.entry = entry; + init (); + if (hasFactoryMethods ()) { + openStream (); + if (stream == null) + return; + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } + } // generate + + /** + * Initialize variables unique to this generator. + **/ + protected void init () + { + factoryClass = entry.name () + "ValueFactory"; + factoryType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + } // init + + /** + * @return true if entry has any factory methods declared + **/ + protected boolean hasFactoryMethods () + { + Vector init = ((ValueEntry)entry).initializers (); + if (init != null && init.size () > 0) + return true; + else + return false; + } // hasFactoryMethods + + /** + * Open the print stream for subsequent output. + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(entry, "ValueFactory.java"); + } // openStream + + /** + * Generate the heading, including the package, imports, + * source comment, class statement, and left curly. + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage (stream, entry, com.sun.tools.corba.ee.idl.toJavaPortable.Util.TypeFile); // REVISIT - same as interface? + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, stream.name()); + if (entry.comment () != null) + entry.comment ().generate ("", stream); + stream.println ("public interface " + factoryClass + " extends org.omg.CORBA.portable.ValueFactory"); + stream.println ('{'); + } // writeHeading + + /** + * Generate members of this class. + **/ + protected void writeBody () + { + Vector init = ((ValueEntry)entry).initializers (); + if (init != null) + { + for (int i = 0; i < init.size (); i++) + { + MethodEntry element = (MethodEntry) init.elementAt (i); + element.valueMethod (true); //tag value method if not tagged previously + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen) element.generator ()). interfaceMethod (symbolTable, element, stream); + } + } + } // writeBody + + /** + * Generate the closing statements. + **/ + protected void writeClosing () + { + stream.println ('}'); + } // writeClosing + + /** + * Write the stream to file by closing the print stream. + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + protected java.util.Hashtable symbolTable; + protected SymtabEntry entry; + protected GenFileStream stream; + + // Unique to this generator + protected String factoryClass; + protected String factoryType; +} // class Holder diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueGen.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueGen.java new file mode 100644 index 000000000..a7d924dde --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueGen.java @@ -0,0 +1,741 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -F46082.51 Remove -stateful feature; javaStatefulName() obsolete. +// -D57067 suppress default init if an emit init explicitly specified. +// -D59071 Clone method entries when their content needs modification. +// -D59092 Valuetype supporting interfaces should implement interface. +// -D59418 Custom values implement org.omg.CORBA.CustomMarshal +// -D59418 Invert read/read_Value, write/write_Value for Simon +// -D60929 Update for RTF2.4 changes +// -D62018 write_value for value with value field x calls xHelper.write. +// -D62062 Add _write to value Helper to marshal state. +// write_value for value subclass calls parent._write +// -D61650 Remove '\n' from generated strings; use println()'s. + +import java.io.PrintWriter; +import java.util.Hashtable; +import java.util.Enumeration; +import java.util.Vector; + +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; +import com.sun.tools.corba.ee.idl.ValueBoxEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; + +/** + * + **/ +public class ValueGen implements com.sun.tools.corba.ee.idl.ValueGen, com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator +{ + /** + * Public zero-argument constructor. + **/ + public ValueGen () + { + } // ctor + + /** + * + **/ + public void generate (Hashtable symbolTable, ValueEntry v, PrintWriter str) + { + this.symbolTable = symbolTable; + this.v = v; + init (); + + openStream (); + if (stream == null) + return; + generateTie (); + generateHelper (); + generateHolder (); + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * Initialize members unique to this generator. + **/ + protected void init () + { + emit = ((Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).emit; + factories = (com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories (); + } // init + + /** + * + **/ + protected void openStream () + { + stream = com.sun.tools.corba.ee.idl.toJavaPortable.Util.stream(v, ".java"); + } // openStream + + /** + * Generate a Tie class only when the user specifies the TIE option + * and the valuetype does support an interface. + **/ + protected void generateTie () + { + boolean tie = ((Arguments) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.arguments).TIEServer; + if (v.supports ().size () > 0 && tie) + { + com.sun.tools.corba.ee.idl.toJavaPortable.Factories factories = (com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories (); + factories.skeleton ().generate (symbolTable, v); + } + } // generateTie + + /** + * + **/ + protected void generateHelper () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).helper ().generate (symbolTable, v); + } // generateHelper + + /** + * + **/ + protected void generateHolder () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).holder ().generate (symbolTable, v); + } // generateHolder + + /** + * + **/ + protected void writeHeading () + { + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, v); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + if (v.comment () != null) + v.comment ().generate ("", stream); + + if (v.isAbstract ()) + { + writeAbstract (); + return; + } + else + stream.print ("public class " + v.name ()); + + // There should always be at least one parent: ValueBase + SymtabEntry parent = (SymtabEntry) v.derivedFrom ().elementAt (0); + + // If parent is ValueBase, it's mapped to java.io.Serializable + String parentName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent); + boolean impl = false; + + if (parentName.equals ("java.io.Serializable")) + { +// stream.print (" implements org.omg.CORBA.portable.ValueBase, org.omg.CORBA.portable.Streamable"); + stream.print (" implements org.omg.CORBA.portable.ValueBase"); // + impl = true; + } + else if ( !((ValueEntry)parent).isAbstract ()) + stream.print (" extends " + parentName); + + // if inheriting from abstract values + for (int i = 0; i < v.derivedFrom ().size (); i++) { + parent = (SymtabEntry) v.derivedFrom ().elementAt (i); + if ( ((ValueEntry)parent).isAbstract ()) + { + if (!impl) + { + stream.print (" implements "); + impl = true; + } + else + stream.print (", "); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent)); + } + } +// Valuetype supporting interface implement Operations interface +// for supported IDL interface + if (((ValueEntry)v).supports ().size () > 0) { + if (!impl) + { + stream.print (" implements "); + impl = true; + } + else + stream.print (", "); + + InterfaceEntry s =(InterfaceEntry)((ValueEntry)v).supports().elementAt(0); + // abstract supported classes don't have "Operations" + if (s.isAbstract ()) + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(s)); + else + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(s) + "Operations"); + } + +// Custom valuetypes implement org.omg.CORBA.CustomMarshal. + if ( ((ValueEntry)v).isCustom ()) { + if (!impl) + { + stream.print (" implements "); + impl = true; + } + else + stream.print (", "); + + stream.print ("org.omg.CORBA.CustomMarshal "); + } + + stream.println (); + stream.println ("{"); + } // writeHeading + + /** + * + **/ + protected void writeBody () + { + writeMembers (); + writeInitializers (); + writeConstructor (); // + writeTruncatable (); // + writeMethods (); + } // writeBody + + /** + * + **/ + protected void writeClosing () + { + if (v.isAbstract ()) + stream.println ("} // interface " + v.name ()); + else + stream.println ("} // class " + v.name ()); + } // writeClosing + + /** + * + **/ + protected void closeStream () + { + stream.close (); + } // closeStream + + /** + * + **/ + protected void writeConstructor () + { + // Per Simon, 9/3/98, emit a protected default constructor + if (!v.isAbstract () && !explicitDefaultInit) { // + stream.println (" protected " + v.name () + " () {}"); + stream.println (); + } + } // writeConstructor + + /** + * + **/ + protected void writeTruncatable () // + { + // Per Simon, 4/6/98, emit _truncatable_ids() + if (!v.isAbstract ()) { + stream.println (" public String[] _truncatable_ids() {"); + stream.println (" return " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(v, true) + ".get_instance().get_truncatable_base_ids();"); // + stream.println (" }"); + stream.println (); + } + } // writeTruncatable + + /** + * + **/ + protected void writeMembers () + { + // if the value type contains no data members, a null return is expected + if (v.state () == null) + return; + + for (int i = 0; i < v.state ().size (); i ++) + { + InterfaceState member = (InterfaceState) v.state ().elementAt (i); + SymtabEntry entry = (SymtabEntry) member.entry; + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(entry); + + if (entry.comment () != null) + entry.comment ().generate (" ", stream); + + String modifier = " "; + if (member.modifier == InterfaceState.Public) + modifier = " public "; + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(modifier, entry.name(), "", entry, stream); + } + } // writeMembers + + /** + * + **/ + protected void writeInitializers () + { + Vector init = v.initializers (); + if (init != null) + { + stream.println (); + for (int i = 0; i < init.size (); i++) + { + MethodEntry element = (MethodEntry) init.elementAt (i); + element.valueMethod (true); + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen) element.generator ()). interfaceMethod (symbolTable, element, stream); + if (element.parameters ().isEmpty ()) // + explicitDefaultInit = true; + } + } + } // writeInitializers + + /** + * + **/ + protected void writeMethods () + { + // contained vector contains methods, attributes, const, enums, exceptions, + // structs, unions, or typedefs that are declared inside the value object. + // State members of the nested types are also included in this vector. + // Thus, if the declaration of a constructed type is nested in the decl. + // of a state member, e.g struct x {boolean b;} memberx; + // the generation of the nested type must be handled here. + Enumeration e = v.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry contained = (SymtabEntry)e.nextElement (); + if (contained instanceof MethodEntry) + { + MethodEntry element = (MethodEntry)contained; + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)element.generator ()).interfaceMethod (symbolTable, element, stream); + } + else + { + // Generate the type referenced by the typedef. + if (contained instanceof TypedefEntry) + contained.type ().generate (symbolTable, stream); + + // Note that we also need to generate the typedef itself if + // contained is a typedef. + contained.generate (symbolTable, stream); + } + } + + // Abstract values are mapped to interfaces. There is no need to generate + // the bindings for inheriting methods in case of inheritance from other + // abstract values or supporting interface + if (v.isAbstract ()) + return; + + // workaround: if the value type doesnot support any interfaces, a null + // return is expected instead of an empty vector + + // if supporting an interfaces, generate bindings for inheriting methods + if (v.supports ().size () > 0) + { + InterfaceEntry intf = (InterfaceEntry) v.supports ().elementAt (0); + Enumeration el = intf.allMethods ().elements (); + while (el.hasMoreElements ()) + { + MethodEntry m = (MethodEntry) el.nextElement (); + // Don't alter the symbol table/emit list elements! + //m.container (v); + //((MethodGen)m.generator ()).interfaceMethod (symbolTable, m, stream); + MethodEntry mClone = (MethodEntry)m.clone (); + mClone.container (v); + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)mClone.generator ()).interfaceMethod (symbolTable, mClone, stream); + } + } + + // if inheriting from abstract values, generating bindings for all + // inheriting methods + for (int i = 0; i < v.derivedFrom ().size (); i++) { + ValueEntry parentValue = (ValueEntry) v.derivedFrom ().elementAt (i); + if (parentValue.isAbstract ()) + { + Enumeration el = parentValue.allMethods ().elements (); + while (el.hasMoreElements ()) + { + MethodEntry m = (MethodEntry) el.nextElement (); + // Don't alter the symbol table/emit list elements! + //m.container (v); + //((MethodGen)m.generator ()).interfaceMethod (symbolTable, m, stream); + MethodEntry mClone = (MethodEntry)m.clone (); + mClone.container (v); + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen)mClone.generator ()).interfaceMethod (symbolTable, mClone, stream); + } + } + } + + //writeStreamableMethods (); + } // writeMethods + + /** + * + **/ + protected void writeStreamableMethods () + { + stream.println (" public void _read (org.omg.CORBA.portable.InputStream istream)"); + stream.println (" {"); + read (0, " ", "this", v, stream); + stream.println (" }"); + stream.println (); + stream.println (" public void _write (org.omg.CORBA.portable.OutputStream ostream)"); + stream.println (" {"); + write (0, " ", "this", v, stream); + stream.println (" }"); + stream.println (); + stream.println (" public org.omg.CORBA.TypeCode _type ()"); + stream.println (" {"); + stream.println (" return " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(v, false) + ".type ();"); // + stream.println (" }"); + } // writeStreamableMethods + + /////////////// + // From JavaGenerator + + public int helperType (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) + { + ValueEntry vt = (ValueEntry) entry; + Vector state = vt.state (); + int noOfMembers = state == null ? 0 : state.size (); + String members = "_members" + index++; + String tcOfMembers = "_tcOf" + members; + + stream.println (indent + "org.omg.CORBA.ValueMember[] " + + members + " = new org.omg.CORBA.ValueMember[" + + noOfMembers + + "];"); + stream.println (indent + "org.omg.CORBA.TypeCode " + tcOfMembers + " = null;"); + //stream.println (""); // + + String definedInrepId = "_id"; + String repId, version; + + for (int k=0; k + if (mType instanceof ValueEntry || mType instanceof ValueBoxEntry) + // OBV spec is silent on defining VersionSpec for valuetype RepIds + version = "\"\""; + else + { + String id = mType.repositoryID ().ID (); + version = '"' + id.substring (id.lastIndexOf (':')+1) + '"'; + } + } + else + { + repId = "\"\""; + version = "\"\""; + } + + // Get TypeCode for valuetype member and store it var. name given by tcOfMembers + stream.println (indent + "// ValueMember instance for " + member.name ()); + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).type (index, indent, tcoffsets, tcOfMembers, member, stream); + stream.println (indent + members + "[" + k + "] = new org.omg.CORBA.ValueMember (" // + + '"' + member.name () + "\", "); // name + stream.println (indent + " " + repId + ", "); // id + stream.println (indent + " " + definedInrepId + ", "); // defined_in + stream.println (indent + " " + version + ", "); // version + stream.println (indent + " " + tcOfMembers + ", "); // type + stream.println (indent + " " + "null, "); // type_def + stream.println (indent + " " + "org.omg.CORBA." + + (valueMember.modifier == InterfaceState.Public ? + "PUBLIC_MEMBER" : "PRIVATE_MEMBER") + ".value" + ");"); // access + } // end for + + stream.println (indent + name + " = org.omg.CORBA.ORB.init ().create_value_tc (" + + "_id, " + + '"' + entry.name () + "\", " + + getValueModifier (vt) + ", " + + getConcreteBaseTypeCode (vt) + ", " + + members + + ");"); + + return index; + } // helperType + + public int type (int index, String indent, com.sun.tools.corba.ee.idl.toJavaPortable.TCOffsets tcoffsets, String name, SymtabEntry entry, PrintWriter stream) { + stream.println (indent + name + " = " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(entry, true) + ".type ();"); // + return index; + } // type + + // Check for types which don't have a Repository ID: primitive, + // string, arrays and sequences. + + private static boolean hasRepId (SymtabEntry member) + { + SymtabEntry mType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.typeOf(member); + return !( mType instanceof PrimitiveEntry || + mType instanceof StringEntry || + ( mType instanceof TypedefEntry && + !(((TypedefEntry)mType).arrayInfo ().isEmpty ()) ) || + ( mType instanceof TypedefEntry && member.type () instanceof SequenceEntry) ); + } // hasRepId + + private static String getValueModifier (ValueEntry vt) + { + String mod = "NONE"; + if (vt.isCustom ()) + mod = "CUSTOM"; + else if (vt.isAbstract ()) + mod = "ABSTRACT"; + else if (vt.isSafe ()) + mod = "TRUNCATABLE"; + return "org.omg.CORBA.VM_" + mod + ".value"; + } // getValueModifier + + private static String getConcreteBaseTypeCode (ValueEntry vt) + { + Vector v = vt.derivedFrom (); + if (!vt.isAbstract ()) + { + SymtabEntry base = (SymtabEntry)vt.derivedFrom ().elementAt (0); + if (!"ValueBase".equals (base.name ())) + return com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(base, true) + ".type ()"; // + } + return "null"; + } // getConcreteBaseTypeCode + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + // per Simon, make "static" read call istream.read_value. + // put real marshalling code in read_value. + + if (((ValueEntry)entry).isAbstract ()) + { + stream.println (" throw new org.omg.CORBA.BAD_OPERATION (\"abstract value cannot be instantiated\");"); + } + else + { + stream.println (" return (" + entryName +") ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (get_instance());"); // + } + stream.println (" }"); + stream.println (); + + // done with "read", now do "read_value with real marshalling code. + + stream.println (" public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream)"); // + stream.println (" {"); + + // per Simon, 3/3/99, read_value for custom values throws an exception + if (((ValueEntry)entry).isAbstract ()) + { + stream.println (" throw new org.omg.CORBA.BAD_OPERATION (\"abstract value cannot be instantiated\");"); + } + else + if (((ValueEntry)entry).isCustom ()) + { + stream.println (" throw new org.omg.CORBA.BAD_OPERATION (\"custom values should use unmarshal()\");"); + } + else + { + stream.println (" " + entryName + " value = new " + entryName + " ();"); + read (0, " ", "value", entry, stream); + stream.println (" return value;"); + } + stream.println (" }"); + stream.println (); + // End of normal read method + + // Per Simon, 8/26/98 - Value helpers get an additional overloaded + // read method where the value is passed in instead of "new'd" up. This is + // used for reading parent value state. + + // Per Simon, 3/3/99 - Don't change this "read" for custom marshalling + stream.println (" public static void read (org.omg.CORBA.portable.InputStream istream, " + entryName + " value)"); + stream.println (" {"); + read (0, " ", "value", entry, stream); + } // helperRead + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + // First do the state members from concrete parent hierarchy + Vector vParents = ((ValueEntry) entry).derivedFrom (); + if (vParents != null && vParents.size() != 0) + { + ValueEntry parent = (ValueEntry) vParents.elementAt (0); + if (parent == null) + return index; + // Per Simon, 4/6/99 - call parent read. + if (! com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(parent).equals ("java.io.Serializable")) // + stream.println(indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(parent, true) + ".read (istream, value);"); // // + } + + Vector vMembers = ((ValueEntry) entry).state (); + int noOfMembers = vMembers == null ? 0 : vMembers.size (); + + for (int k = 0; k < noOfMembers; k++) + { + TypedefEntry member = (TypedefEntry)((InterfaceState)vMembers.elementAt (k)).entry; + String memberName = member.name (); + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry || + mType instanceof TypedefEntry || + mType instanceof SequenceEntry || + mType instanceof StringEntry || + !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).read (index, indent, name + '.' + memberName, member, stream); + else if (mType instanceof ValueEntry) + { + String returnType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(mType); + if (mType instanceof ValueBoxEntry) + // Remove -stateful. + //returnType = Util.javaStatefulName (mType); + returnType = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(mType); + stream.println (" " + name + '.' + memberName + " = (" + returnType + + ") ((org.omg.CORBA_2_3.portable.InputStream)istream).read_value (" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + // + ".get_instance ());"); // + } + else + stream.println (indent + name + '.' + memberName + " = " + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".read (istream);"); // + } + + return index; + } // read + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + // per Simon, make "static" write call istream.write_value. + // put real marshalling code in write_value. + stream.println (" ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, get_instance());"); // + stream.println (" }"); + stream.println (); + + // + // per Simon, 4/27/99, add static _write that marshals the state of this + // value for non-custom valuetypes + if (!((ValueEntry)entry).isCustom ()) + { + stream.println (" public static void _write (org.omg.CORBA.portable.OutputStream ostream, " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry) + " value)"); + stream.println (" {"); + write (0, " ", "value", entry, stream); + stream.println (" }"); + stream.println (); + } + + // done with "_write", now do "write_value + stream.println (" public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable obj)"); // + stream.println (" {"); + + // per Simon, 3/3/99, write_value for custom values throws an exception + if (((ValueEntry)entry).isCustom ()) + { + stream.println (" throw new org.omg.CORBA.BAD_OPERATION (\"custom values should use marshal()\");"); + } + else { + String entryName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(entry); + stream.println (" _write (ostream, (" + entryName + ") obj);"); // +// write (0, " ", "value", entry, stream); + } + } // helperWrite + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + // First do the state members from concrete parent hierarchy + Vector vParents = ((ValueEntry)entry).derivedFrom (); + if (vParents != null && vParents.size () != 0) + { + ValueEntry parent = (ValueEntry)vParents.elementAt (0); + if (parent == null) + return index; + // Per Simon, 4/06/99 - call parent write. + // Per Simon, 4/27/99 - call parent _write. + if (! com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(parent).equals ("java.io.Serializable")) // + stream.println(indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(parent, true) + "._write (ostream, value);"); // + } + + Vector vMembers = ((ValueEntry) entry ).state (); + int noOfMembers = vMembers == null ? 0 : vMembers.size (); + for (int k = 0; k < noOfMembers; k++) + { + TypedefEntry member = (TypedefEntry)((InterfaceState)vMembers.elementAt (k)).entry; + String memberName = member.name (); + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry || + mType instanceof TypedefEntry || + mType instanceof SequenceEntry || + mType instanceof StringEntry || + !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, indent, name + '.' + memberName, member, stream); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + // + ".write (ostream, " + name + '.' + memberName + ");"); + } + + return index; + } // write + + /** + * + **/ + protected void writeAbstract () + { + stream.print ("public interface " + v.name ()); + + // workaround: if the abstract value type does not have any parent, a vector + // containing ValueBase should be returned instead of an empty vector + if (v.derivedFrom ().size () == 0) + stream.print (" extends org.omg.CORBA.portable.ValueBase"); // + else + { + SymtabEntry parent; + // list the values the abstract value type inherits + for (int i = 0; i < v.derivedFrom ().size (); i++) + { + if (i == 0) + stream.print (" extends "); + else + stream.print (", "); + parent = (SymtabEntry) v.derivedFrom ().elementAt (i); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent)); + } + } + + // list the interface the abstract value type supports + if (v.supports ().size () > 0) + { + stream.print (", "); + SymtabEntry intf = (SymtabEntry) v.supports ().elementAt (0); + stream.print (com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(intf)); + } + stream.println (); + stream.println ("{"); + } + + protected int emit = 0; + protected com.sun.tools.corba.ee.idl.toJavaPortable.Factories factories = null; + protected Hashtable symbolTable = null; + protected ValueEntry v = null; + protected PrintWriter stream = null; + protected boolean explicitDefaultInit = false; // +} // class ValueGen diff --git a/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueGen24.java b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueGen24.java new file mode 100644 index 000000000..27ab42c7c --- /dev/null +++ b/idlj/src/main/java/com/sun/tools/corba/ee/idl/toJavaPortable/ValueGen24.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +// NOTES: +// -D62023 Update for Java 2.4 RTF +// -D62794.1 Don't include operations inherited from abstract valuetypes +// -D62794.1 Don't include operations inherited from supported interfaces + +import com.sun.tools.corba.ee.idl.AttributeEntry; +import com.sun.tools.corba.ee.idl.GenFileStream; +import com.sun.tools.corba.ee.idl.InterfaceEntry; +import com.sun.tools.corba.ee.idl.InterfaceState; +import com.sun.tools.corba.ee.idl.MethodEntry; +import com.sun.tools.corba.ee.idl.PrimitiveEntry; +import com.sun.tools.corba.ee.idl.SequenceEntry; +import com.sun.tools.corba.ee.idl.StringEntry; +import com.sun.tools.corba.ee.idl.SymtabEntry; +import com.sun.tools.corba.ee.idl.TypedefEntry; +import com.sun.tools.corba.ee.idl.ValueEntry; + +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * + **/ +public class ValueGen24 extends ValueGen +{ + /** + * Public zero-argument constructor. + **/ + public ValueGen24 () + { + } // ctor + + protected void writeConstructor () + { + } // writeConstructor + + public void helperWrite (SymtabEntry entry, PrintWriter stream) + { + // REVISIT: Abstract/Custom?? + // per Simon mail 5/17/99 + stream.println (" ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ());"); + } // helperWrite + + public void helperRead (String entryName, SymtabEntry entry, PrintWriter stream) + { + // REVISIT: Abstract/Custom?? + // per Simon mail 5/17/99 + stream.println (" return (" + entryName + ")((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ());"); + } // helperRead + + protected void writeInitializers () + { + // override to do nothing + } // writeInitializers + + protected void writeTruncatable () // + { + if (!v.isAbstract ()) { + stream.println (" private static String[] _truncatable_ids = {"); + stream.print (" " + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(v, true) + ".id ()"); + + // Any safe ValueEntry must have a concete value parent. + // The topmost parent cannot be safe since it doesn't have + // a concrete parent. + ValueEntry child = v; + while (child.isSafe ()) + { + stream.println(","); + ValueEntry parent = (ValueEntry)child.derivedFrom ().elementAt (0); + stream.print(" \"" + com.sun.tools.corba.ee.idl.toJavaPortable.Util.stripLeadingUnderscoresFromID(parent.repositoryID().ID()) + "\""); + child = parent; + } + stream.println(); + stream.println(" };"); + stream.println(); + stream.println (" public String[] _truncatable_ids() {"); + stream.println (" return _truncatable_ids;"); + stream.println (" }"); + stream.println (); + } + } // writeTruncatable + + class ImplStreamWriter { + private boolean isImplementsWritten = false ; + + public void writeClassName( String name ) + { + if (!isImplementsWritten) { + stream.print( " implements " ) ; + isImplementsWritten = true ; + } else + stream.print( ", " ) ; + + stream.print( name ) ; + } + } + + protected void writeHeading () + { + ImplStreamWriter isw = new ImplStreamWriter() ; + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writePackage(stream, v); + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeProlog(stream, ((GenFileStream) stream).name()); + + if (v.comment () != null) + v.comment ().generate ("", stream); + + if (v.isAbstract ()) { + writeAbstract (); + return; + } else + stream.print ("public abstract class " + v.name ()); + + // There should always be at least one parent: ValueBase + SymtabEntry parent = (SymtabEntry) v.derivedFrom ().elementAt (0); + + // If parent is ValueBase, it's mapped to java.io.Serializable + String parentName = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent); + boolean cv = false; // true if we've already implemented CustomValue + + if (parentName.equals ("java.io.Serializable")) { + if (((ValueEntry)v).isCustom ()) { + isw.writeClassName( "org.omg.CORBA.portable.CustomValue" ) ; + cv = true; + } else + isw.writeClassName( "org.omg.CORBA.portable.StreamableValue" ) ; + } else if ( !((ValueEntry)parent).isAbstract ()) + stream.print (" extends " + parentName); + + // if inheriting from abstract values + for (int i = 0; i < v.derivedFrom ().size (); i++) { + parent = (SymtabEntry) v.derivedFrom ().elementAt (i); + if ( ((ValueEntry)parent).isAbstract ()) { + isw.writeClassName( com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(parent) ) ; + } + } + + // Write out the supported interfaces + Enumeration enumeration = v.supports().elements(); + while (enumeration.hasMoreElements()) { + InterfaceEntry ie = (InterfaceEntry)(enumeration.nextElement()) ; + String cname = com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaName(ie) ; + if (!ie.isAbstract()) + cname += "Operations" ; + isw.writeClassName( cname ) ; + } + + // for when a custom valuetype inherits from a non-custom valuetype + if ( v.isCustom () && !cv) + isw.writeClassName( "org.omg.CORBA.portable.CustomValue" ) ; + + stream.println (); + stream.println ("{"); + } // writeHeading + + protected void writeMembers () + { + // if the value type contains no data members, a null return is expected + if (v.state () == null) + return; + + for (int i = 0; i < v.state ().size (); i ++) + { + InterfaceState member = (InterfaceState) v.state ().elementAt (i); + SymtabEntry entry = (SymtabEntry) member.entry; + com.sun.tools.corba.ee.idl.toJavaPortable.Util.fillInfo(entry); + + if (entry.comment () != null) + entry.comment ().generate (" ", stream); + + String modifier = " "; + if (member.modifier == InterfaceState.Public) + modifier = " public "; + else + modifier = " protected "; + com.sun.tools.corba.ee.idl.toJavaPortable.Util.writeInitializer(modifier, entry.name(), "", entry, stream); + } + stream.println(); + } // writeMembers + + protected void writeMethods () + { + // contained vector contains methods, attributes, const, enums, exceptions, + // structs, unions, or typedefs that are declared inside the value object. + // State members of the nested types are also included in this vector. + // Thus, if the declaration of a constructed type is nested in the decl. + // of a state member, e.g struct x {boolean b;} memberx; + // the generation of the nested type must be handled here. + Enumeration e = v.contained ().elements (); + while (e.hasMoreElements ()) + { + SymtabEntry contained = (SymtabEntry)e.nextElement (); + if (contained instanceof AttributeEntry) + { + AttributeEntry element = (AttributeEntry)contained; + ((com.sun.tools.corba.ee.idl.toJavaPortable.AttributeGen24)element.generator ()).abstractMethod (symbolTable, element, stream); + } + else if (contained instanceof MethodEntry) + { + MethodEntry element = (MethodEntry)contained; + ((com.sun.tools.corba.ee.idl.toJavaPortable.MethodGen24)element.generator ()).abstractMethod (symbolTable, element, stream); + } + else + { + // Generate the type referenced by the typedef. + if (contained instanceof TypedefEntry) + contained.type ().generate (symbolTable, stream); + + // Note that we also need to generate the typedef itself if + // contained is a typedef. + contained.generate (symbolTable, stream); + } + } + + // Abstract values are mapped to interfaces. There is no need to generate + // the bindings for inheriting methods in case of inheritance from other + // abstract values or supporting interface + if (v.isAbstract ()) + return; + + // Non-abstract, Non-Custom valuetypes support the Streamable interface + if (!(v.isCustom () || v.isAbstract ())) + writeStreamableMethods (); + } // writeMethods + + public int read (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + // First do the state members from concrete parent hierarchy + Vector vParents = ((ValueEntry) entry).derivedFrom (); + if (vParents != null && vParents.size() != 0) + { + ValueEntry parent = (ValueEntry) vParents.elementAt (0); + if (parent == null) + return index; + + // call super._read if non-abstract value parent + if ((!parent.isAbstract ()) && (! com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(parent).equals ("java.io.Serializable"))) // + stream.println(indent + "super._read (istream);"); + } + + Vector vMembers = ((ValueEntry) entry).state (); + int noOfMembers = vMembers == null ? 0 : vMembers.size (); + + for (int k = 0; k < noOfMembers; k++) + { + TypedefEntry member = (TypedefEntry)((InterfaceState)vMembers.elementAt (k)).entry; + String memberName = member.name (); + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry || + mType instanceof TypedefEntry || + mType instanceof SequenceEntry || + mType instanceof StringEntry || + !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).read (index, indent, name + '.' + memberName, member, stream); + else + stream.println (indent + name + '.' + memberName + " = " + + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + ".read (istream);"); // + } + + return index; + } // read + + public int write (int index, String indent, String name, SymtabEntry entry, PrintWriter stream) + { + // First do the state members from concrete parent hierarchy + Vector vParents = ((ValueEntry)entry).derivedFrom (); + if (vParents != null && vParents.size () != 0) + { + ValueEntry parent = (ValueEntry)vParents.elementAt (0); + if (parent == null) + return index; + // call super._read if non-abstract value parent + if ((!parent.isAbstract ()) && (! com.sun.tools.corba.ee.idl.toJavaPortable.Util.javaQualifiedName(parent).equals ("java.io.Serializable"))) // + stream.println(indent + "super._write (ostream);"); + } + + Vector vMembers = ((ValueEntry) entry ).state (); + int noOfMembers = vMembers == null ? 0 : vMembers.size (); + for (int k = 0; k < noOfMembers; k++) + { + TypedefEntry member = (TypedefEntry)((InterfaceState)vMembers.elementAt (k)).entry; + String memberName = member.name (); + SymtabEntry mType = member.type (); + + if (mType instanceof PrimitiveEntry || + mType instanceof TypedefEntry || + mType instanceof SequenceEntry || + mType instanceof StringEntry || + !member.arrayInfo ().isEmpty ()) + index = ((com.sun.tools.corba.ee.idl.toJavaPortable.JavaGenerator)member.generator ()).write (index, indent, name + '.' + memberName, member, stream); + else + stream.println (indent + com.sun.tools.corba.ee.idl.toJavaPortable.Util.helperName(mType, true) + // + ".write (ostream, " + name + '.' + memberName + ");"); + } + + return index; + } // write + + public void generate (Hashtable symbolTable, ValueEntry v, PrintWriter str) + { + this.symbolTable = symbolTable; + this.v = v; + init (); + + openStream (); + if (stream == null) + return; + generateTie (); + generateHelper (); + generateHolder (); + if (!v.isAbstract ()) { + generateValueFactory (); + generateDefaultFactory (); + } + writeHeading (); + writeBody (); + writeClosing (); + closeStream (); + } // generate + + /** + * + **/ + protected void generateValueFactory () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).valueFactory ().generate (symbolTable, v); + } // generateValueFactory + + /** + * + **/ + protected void generateDefaultFactory () + { + ((com.sun.tools.corba.ee.idl.toJavaPortable.Factories) com.sun.tools.corba.ee.idl.toJavaPortable.Compile.compiler.factories ()).defaultFactory ().generate (symbolTable, v); + } // generateDefaultFactory +} diff --git a/idlj/src/main/resources/com/sun/tools/corba/ee/idl/idl.properties b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/idl.properties new file mode 100644 index 000000000..da32edd5b --- /dev/null +++ b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/idl.properties @@ -0,0 +1,148 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997-1999 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Translator: Each line below is of the form "=". +# The keys are NOT to be translated. +# The messages ARE to be translated. +# +# DO NOT translate the following: +# ASCII +# #else +# #endif +# IDL +# +# %0, %1, etc. are postional parameters to the message. Do not +# translate these. The number order is the order they are given to +# the message writer. It is OK to change their order in the message +# if the language grammar so dictates. +# +# Lines of the form "%0 (line %1): \n%x\n%y" are error +# messages: %0 is a filename; %1 is a line number; %x is line %1 from +# %0; %y is the error marker. So the message comes out looking like: +# (line xxx): +# Line xxx from where the carat points to the error +# ^ +# So the first two and the last two parameters of these messages must +# remain in their positions. +# +# A backslash (\) at the end of a line is a line continuation +# character. A backslash at the beginning of a line means don't +# ignore leading blanks (they normally are). These backslashes +# should remain in the message. +# +# Translator: Start Translating + +Compile.parsing=Parsing %0 +Compile.parseDone=done - %0 +Compile.generating=Generating %0 +Compile.genDone=done - %0 +Deprecated.keyword=WARNING: Keyword `%0' is deprecated. +EvaluationException.1=Operands of %0 operator are inconsistent: %1 and %2. +EvaluationException.2=Operand of %0 operator must be a number, not a %1. +EvaluationException.or=bitwise or +EvaluationException.xor=bitwise xor +EvaluationException.and=bitwise and +EvaluationException.plus=addition +EvaluationException.minus=subtraction +EvaluationException.left=left shift +EvaluationException.right=right shift +EvaluationException.times=multiplication +EvaluationException.divide=division +EvaluationException.mod=modulo +EvaluationException.pos=unary positive +EvaluationException.neg=unary negation +EvaluationException.not=bitwise not +EvaluationException.booleanNot=boolean not +EvaluationException.booleanAnd=boolean and +EvaluationException.booleanOr=boolean or +EvaluationException.equal=equal +EvaluationException.notEqual=not equal +EvaluationException.greaterThan=greater than +EvaluationException.lessThan=less than +EvaluationException.greaterEqual=greater than or equal +EvaluationException.lessEqual=less than or equal +GenFileStream.1=%0 could not be generated: %1 +InvalidArgument.1=Invalid argument: %0. +InvalidArgument.2=No IDL file was specified. +InvalidCharacter.1=%0 (line %1): invalid character: %2 (ASCII %3).\n%4\n%5 +Migration.futureKeyword=WARNING: Identifier `%0' collides with a keyword; use an escaped identifier to ensure future compatibility. +Migration.keywordCollision=WARNING: Identifier `%0' collides with a keyword; use an escaped identifier to ensure future compatibility. +ParseException.abstractValueBox=%0 (line %1): A value box cannot be declared abstract.\n%2\n%3 +ParseException.alreadyDeclared=%0 (line %1): %2 has already been declared.\n%3\n%4 +ParseException.declNotInSameFile=%0 (line %1): %2 was declared previously in a forward declaration in file %3.\n%4\n%5 +ParseException.alreadyDerived=%0 (line %1): %2 has already been declared as a parent of %3.\n%4\n%5 +ParseException.alreadyDefaulted=%0 (line %1): The default branch has already been encountered.\n%2\n%3 +ParseException.alreadyRaised=%0 (line %1): %2 already specified in raises clause.\n%3\n%4 +ParseException.attributeNotType=%0 (line %1): %2 is an attribute. It cannot be used as a type.\n%3\n%4 +ParseException.badAbstract=%0 (line %1): The forward and actual declaration of %2 is inconsistent. One is abstract and the other is not.\n%3\n%4 +ParseException.badCustom=%0 (line %1): A forward value declaration cannot be declared custom.\n%2\n%3 +ParseException.badRepIDAlreadyAssigned=%0 (line %1): Type %2 has already been assigned a Repository ID in a previous ID pragma directive.\n%3\n%4 +ParseException.badRepIDForm=%0 (line %1): Repository ID '%2' should have form ':'.\n%3\n%4 +ParseException.badRepIDPrefix=%0 (line %1): Interface %2 should have Repository ID prefix `%3', not '%4'.\n%5\n%6 +ParseException.badState=%0 (line %1): %2 cannot be a stateful interface; it has more than one stateful parent.\n%3\n%4 +ParseException.branchLabel=%0 (line %1): case %2 has already been declared.\n%3\n%4 +ParseException.branchName=%0 (line %1): A branch named %2 has already been declared.\n%3\n%4 +ParseException.duplicateInit=%0 (line %1): An initializer has the same signature as a previous initializer.\n%2\n%3 +ParseException.duplicateState=%0 (line %1): The data member %2 has the same name as a previous data member.\n%3\n%4 +ParseException.elseNoIf=%0 (line %1): #else encountered without a matching #if.\n%2\n%3 +ParseException.endNoIf=%0 (line %1): #endif encountered without a matching #if.\n%2\n%3 +ParseException.evaluation=%0 (line %1): %2\n%3\n%4 +ParseException.forwardEntry=%0 (line %1): There is a forward reference to %2, but it is not defined.\n%3\n%4 +ParseException.forwardedValueBox=%0 (line %1): %2 has a forward declaration. A value box cannot be forward declared.\n%3\n%4 +ParseException.forwardInheritance=%0 (line %1): It is illegal for %2 to inherit from the incomplete forward declaration of %3.\n%4\n%5 +ParseException.generic=%0 (line %1): %2\n%3\n%4 +ParseException.illegalArray=%0 (line %1): An array is not a legal type in a %2.\n%3\n%4 +ParseException.illegalException=%0 (line %1): Exceptions cannot appear within %2s.\n%3\n%4 +ParseException.invalidConst1=%0 (line %1): Constant expression must be of type %2, not %3.\n%4\n%5 +ParseException.invalidConst2=%0 (line %1): Identifiers in constant expressions must be constants, not %2.\n%3\n%4 +ParseException.keywordCollision=%0 (line %1): Identifier `%2' collides with keyword; use escaped identifier if necessary.\n%3\n%4 +ParseException.methodClash=%0 (line %1): Method name clash in interface %2: %3.\n%4\n%5 +ParseException.moduleNotType=%0 (line %1): %2 is a module. It cannot be used as a type.\n%3\n%4 +ParseException.nestedValueBox=%0 (line %1): Value boxes cannot be nested.\n%2\n%3 +ParseException.noDefault=%0 (line %1): A default branch is not allowed when all possible cases are fully covered.\n%2\n%3 +ParseException.nonAbstractParent=%0 (line %1): The abstract interface %2 cannot inherit from the non-abstract interface %3.\n%4\n%5 +ParseException.nonAbstractParent2=%0 (line %1): The abstract value %2 cannot inherit from the non-abstract value %3.\n%4\n%5 +ParseException.nonAbstractParent3=%0 (line %1): The value %2 cannot inherit from the non-abstract value %3 as specified.\n%4\n%5 +ParseException.notANumber=%0 (line %1): A number was expected. %2 is not a valid number.\n%3\n%4 +ParseException.nothing=%0 is empty. There is nothing to compile. +ParseException.notPosInt=%0 (line %1): Expected a positive integer constant, not %2.\n%3\n%4 +ParseException.oneway=%0 (line %1): %2 is declared to be oneway. Oneway methods must: return void; have only in parameters; raise no exceptions.\n%3\n%4 +ParseException.operationNotType=%0 (line %1): %2 is an operation. It cannot be used as a type.\n%3\n%4 +ParseException.outOfRange=%0 (line %1): The value of the constant expression, %2, is out of range for type %3.\n%4\n%5 +ParseException.recursive=%0 (line %1): The only legal recursive definition is: sequence<%2> %3.\n%4\n%5 +ParseException.selfInherit=%0 (line %1): %2 cannot inherit from itself.\n%3\n%4 +ParseException.stringTooLong=%0 (line %1): "%2" cannot be more than %3 characters long.\n%4\n%5 +ParseException.syntax1=%0 (line %1): Expected `%2'; encountered `%3'.\n%4\n%5 +ParseException.syntax2=%0 (line %1): Expected one of%2; encountered `%3'.\n%4\n%5 +ParseException.unclosed=%0: Unexpected end of file encountered in comment. +ParseException.undeclaredType=%0 (line %1): %2 is an undeclared type.\n%3\n%4 +ParseException.warning=%0 (line %1): %2\n%3\n%4 +ParseException.constExprType=%0 (line %1): The type of the constant expression is %2, but it should be %3.\n%4\n%5 +ParseException.wrongType=%0 (line %1): The type of %2 is %3, but it should be %4.\n%5\n%6 +ParseException.illegalIncompleteTypeReference=%0 (line %1): Illegal reference to incomplete forward declaration of type %2.\n%3\n%4 +Preprocessor.unknown=Unknown preprocessor directive, `%0'. Line ignored. +Preprocessor.unknownPragma=Unknown pragma `%0'. Line ignored. +Preprocessor.undefinedName=Undefined type name for pragma %0: %1. Line ignored. +Token.boolLit= +Token.charLit= +Token.intLit= +Token.floatLit= +Token.stringLit= +Token.literal= +Token.identifier= +Token.endOfFile=EOF +Token.unknown=? +Util.cantCreatePkg=Cannot create the package %0. +Version.product=IDL Parser Framework, version "%0" +Version.number=4.02 +default=Error! A message was requested which does not exist. The messages file does not contain the key: %0. + + diff --git a/idlj/src/main/resources/com/sun/tools/corba/ee/idl/idl_ja.properties b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/idl_ja.properties new file mode 100644 index 000000000..e7a4543dc --- /dev/null +++ b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/idl_ja.properties @@ -0,0 +1,290 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997-1999 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Translator: Each line below is of the form "=". +# The keys are NOT to be translated. +# The messages ARE to be translated. +# +# DO NOT translate the following: +# ASCII +# #else +# #endif +# IDL +# +# %0, %1, etc. are postional parameters to the message. Do not +# translate these. The number order is the order they are given to +# the message writer. It is OK to change their order in the message +# if the language grammar so dictates. +# +# Lines of the form "%0 (line %1): \n%x\n%y" are error +# messages: %0 is a filename; %1 is a line number; %x is line %1 from +# %0; %y is the error marker. So the message comes out looking like: +# (line xxx): +# Line xxx from where the carat points to the error +# ^ +# So the first two and the last two parameters of these messages must +# remain in their positions. +# +# A backslash (\) at the end of a line is a line continuation +# character. A backslash at the beginning of a line means don't +# ignore leading blanks (they normally are). These backslashes +# should remain in the message. +# +# Translator: Start Translating + +Compile.parsing=%0 \u3092\u69cb\u6587\u89e3\u6790\u4e2d +#Compile.parsing=Parsing %0 +Compile.parseDone=\u5b8c\u4e86 - %0 +#Compile.parseDone=done - %0 +Compile.generating=%0 \u3092\u751f\u6210\u4e2d +#Compile.generating=Generating %0 +Compile.genDone=\u5b8c\u4e86 - %0 +#Compile.genDone=done - %0 +Deprecated.keyword=\u8b66\u544a: \u30ad\u30fc\u30ef\u30fc\u30c9 `%0' \u306f\u63a8\u5968\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002 +#Deprecated.keyword=WARNING: Keyword `%0' is deprecated. +EvaluationException.1=%0 \u6f14\u7b97\u5b50\u306e\u30aa\u30da\u30e9\u30f3\u30c9 %1 \u3068 %2 \u304c\u4e00\u81f4\u3057\u3066\u3044\u307e\u305b\u3093\u3002 +#EvaluationException.1=Operands of %0 operator are inconsistent: %1 and %2. +EvaluationException.2=%0 \u6f14\u7b97\u5b50\u306e\u30aa\u30da\u30e9\u30f3\u30c9\u306f %1 \u3067\u306f\u306a\u304f\u6570\u5024\u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 +#EvaluationException.2=Operand of %0 operator must be a number, not a %1. +EvaluationException.or=\u30d3\u30c3\u30c8\u5358\u4f4d\u306e\u8ad6\u7406\u548c +#EvaluationException.or=bitwise or +EvaluationException.xor=\u30d3\u30c3\u30c8\u5358\u4f4d\u306e\u6392\u4ed6\u7684\u8ad6\u7406\u548c +#EvaluationException.xor=bitwise xor +EvaluationException.and=\u30d3\u30c3\u30c8\u5358\u4f4d\u306e\u8ad6\u7406\u7a4d +#EvaluationException.and=bitwise and +EvaluationException.plus=\u52a0\u7b97 +#EvaluationException.plus=addition +EvaluationException.minus=\u6e1b\u7b97 +#EvaluationException.minus=subtraction +EvaluationException.left=\u5de6\u30b7\u30d5\u30c8 +#EvaluationException.left=left shift +EvaluationException.right=\u53f3\u30b7\u30d5\u30c8 +#EvaluationException.right=right shift +EvaluationException.times=\u4e57\u7b97 +#EvaluationException.times=multiplication +EvaluationException.divide=\u9664\u7b97 +#EvaluationException.divide=division +EvaluationException.mod=\u30e2\u30b8\u30e5\u30ed +#EvaluationException.mod=modulo +EvaluationException.pos=\u5358\u9805\u6b63\u6570 +#EvaluationException.pos=unary positive +EvaluationException.neg=\u5358\u9805\u8ca0\u6570 +#EvaluationException.neg=unary negation +EvaluationException.not=\u30d3\u30c3\u30c8\u5358\u4f4d\u306e\u5426\u5b9a +#EvaluationException.not=bitwise not +EvaluationException.booleanNot=\u30d6\u30fc\u30eb\u306e\u5426\u5b9a +#EvaluationException.booleanNot=boolean not +EvaluationException.booleanAnd=\u30d6\u30fc\u30eb\u306e\u8ad6\u7406\u7a4d +#EvaluationException.booleanAnd=boolean and +EvaluationException.booleanOr=\u30d6\u30fc\u30eb\u306e\u8ad6\u7406\u548c +#EvaluationException.booleanOr=boolean or +EvaluationException.equal=\u7b49\u4fa1 +#EvaluationException.equal=equal +EvaluationException.notEqual=\u4e0d\u7b49\u4fa1 +#EvaluationException.notEqual=not equal +EvaluationException.greaterThan=\u5927\u304d\u3044 +#EvaluationException.greaterThan=greater than +EvaluationException.lessThan=\u5c0f\u3055\u3044 +#EvaluationException.lessThan=less than +EvaluationException.greaterEqual=\u5927\u304d\u3044\u304b\u7b49\u3057\u3044 +#EvaluationException.greaterEqual=greater than or equal +EvaluationException.lessEqual=\u5c0f\u3055\u3044\u304b\u7b49\u3057\u3044 +#EvaluationException.lessEqual=less than or equal +GenFileStream.1=%0 \u3092\u751f\u6210\u3067\u304d\u307e\u305b\u3093: %1 +#GenFileStream.1=%0 could not be generated: %1 +InvalidArgument.1=\u4e0d\u6b63\u306a\u5f15\u6570: %0 +#InvalidArgument.1=Invalid argument: %0. +InvalidArgument.2=IDL \u30d5\u30a1\u30a4\u30eb\u304c\u6307\u5b9a\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002 +#InvalidArgument.2=No IDL file was specified. +InvalidCharacter.1=%0 (%1 \u884c\u76ee): \u4e0d\u6b63\u306a\u6587\u5b57: %2 (ASCII %3).\n%4\n%5 +#InvalidCharacter.1=%0 (line %1): invalid character: %2 (ASCII %3).\n%4\n%5 +Migration.futureKeyword=\u8b66\u544a: \u8b58\u5225\u5b50 `%0' \u304c\u30ad\u30fc\u30ef\u30fc\u30c9\u3068\u885d\u7a81\u3057\u3066\u3044\u307e\u3059\u3002\u4eca\u5f8c\u3082\u4e92\u63db\u6027\u3092\u4fdd\u3064\u305f\u3081\u306b\u306f\u62e1\u5f35\u8b58\u5225\u5b50\u3092\u4f7f\u7528\u3057\u3066\u304f\u3060\u3055\u3044\u3002 +#Migration.futureKeyword=WARNING: Identifier `%0' collides with a keyword; use an escaped identifier to ensure future compatibility. +Migration.keywordCollision=\u8b66\u544a: \u8b58\u5225\u5b50 `%0' \u304c\u30ad\u30fc\u30ef\u30fc\u30c9\u3068\u885d\u7a81\u3057\u3066\u3044\u307e\u3059\u3002\u4eca\u5f8c\u3082\u4e92\u63db\u6027\u3092\u4fdd\u3064\u305f\u3081\u306b\u306f\u62e1\u5f35\u8b58\u5225\u5b50\u3092\u4f7f\u7528\u3057\u3066\u304f\u3060\u3055\u3044\u3002 +#Migration.keywordCollision=WARNING: Identifier `%0' collides with a keyword; use an escaped identifier to ensure future compatibility. +ParseException.abstractValueBox=%0 (%1 \u884c\u76ee): \u5024\u30dc\u30c3\u30af\u30b9\u3092 abstract \u3067\u5ba3\u8a00\u3067\u304d\u307e\u305b\u3093\u3002\n%2\n%3 +#ParseException.abstractValueBox=%0 (line %1): A value box cannot be declared abstract.\n%2\n%3 +ParseException.alreadyDeclared=%0 (%1 \u884c\u76ee): %2 \u306f\u65e2\u306b\u5ba3\u8a00\u3055\u308c\u3066\u3044\u307e\u3059\u3002\n%3\n%4 +#ParseException.alreadyDeclared=%0 (line %1): %2 has already been declared.\n%3\n%4 +ParseException.alreadyDerived=%0 (%1 \u884c\u76ee): %2 \u306f %3 \u306e\u89aa\u3068\u3057\u3066\u65e2\u306b\u5ba3\u8a00\u3055\u308c\u3066\u3044\u307e\u3059\u3002\n%4\n%5 +#ParseException.alreadyDerived=%0 (line %1): %2 has already been declared as a parent of %3.\n%4\n%5 +ParseException.alreadyDefaulted=%0 (%1 \u884c\u76ee): \u30c7\u30d5\u30a9\u30eb\u30c8\u306e\u5206\u5c90\u306f\u65e2\u306b\u691c\u51fa\u3055\u308c\u3066\u3044\u307e\u3059\u3002\n%2\n%3 +#ParseException.alreadyDefaulted=%0 (line %1): The default branch has already been encountered.\n%2\n%3 +ParseException.alreadyRaised=%0 (%1 \u884c\u76ee): %2 \u306f raises \u7bc0\u3067\u65e2\u306b\u6307\u5b9a\u3055\u308c\u3066\u3044\u307e\u3059\u3002\n%3\n%4 +#ParseException.alreadyRaised=%0 (line %1): %2 already specified in raises clause.\n%3\n%4 +ParseException.attributeNotType=%0 (%1 \u884c\u76ee): %2 \u306f\u5c5e\u6027\u3067\u3059\u3002\u578b\u3068\u3057\u3066\u4f7f\u7528\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.attributeNotType=%0 (line %1): %2 is an attribute. It cannot be used as a type.\n%3\n%4 +ParseException.badAbstract=%0 (%1 \u884c\u76ee): %2 \u306e\u524d\u65b9\u306e\u5ba3\u8a00\u3068\u5b9f\u969b\u306e\u5ba3\u8a00\u304c\u4e00\u81f4\u3057\u307e\u305b\u3093\u3002\u4e00\u65b9\u306f abstract \u3067\u4ed6\u65b9\u306f\u305d\u308c\u3068\u7570\u306a\u308a\u307e\u3059\u3002\n%3\n%4 +#ParseException.badAbstract=%0 (line %1): The forward and actual declaration of %2 is inconsistent. One is abstract and the other is not.\n%3\n%4 +ParseException.badCustom=%0 (%1 \u884c\u76ee): \u524d\u65b9\u5024\u5ba3\u8a00\u3092 custom \u3067\u5ba3\u8a00\u3067\u304d\u307e\u305b\u3093\u3002\n%2\n%3 +#ParseException.badCustom=%0 (line %1): A forward value declaration cannot be declared custom.\n%2\n%3 +ParseException.badRepIDAlreadyAssigned=%0 (%1 \u884c\u76ee): \u578b %2 \u306f\u524d\u306e ID \u30d7\u30e9\u30b0\u30de\u6307\u793a\u306e\u30ea\u30dd\u30b8\u30c8\u30ea ID \u306b\u5272\u308a\u5f53\u3066\u3089\u308c\u3066\u3044\u307e\u3059\u3002\n%3\n%4 +#ParseException.badRepIDAlreadyAssigned=%0 (line %1): Type %2 has already been assigned a Repository ID in a previous ID pragma directive.\n%3\n%4 +ParseException.badRepIDForm=%0 (%1 \u884c\u76ee): \u30ea\u30dd\u30b8\u30c8\u30ea ID '%2' \u306f ':' \u306e\u5f62\u5f0f\u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.badRepIDForm=%0 (line %1): Repository ID '%2' should have form ':'.\n%3\n%4 +ParseException.badRepIDPrefix=%0 (%1 \u884c\u76ee): \u30a4\u30f3\u30bf\u30d5\u30a7\u30fc\u30b9 %2 \u306e\u30ea\u30dd\u30b8\u30c8\u30ea ID \u306e\u63a5\u982d\u8f9e\u306f '%4' \u3067\u306a\u304f `%3' \u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002\n%5\n%6 +#ParseException.badRepIDPrefix=%0 (line %1): Interface %2 should have Repository ID prefix `%3', not '%4'.\n%5\n%6 +ParseException.badState=%0 (%1 \u884c\u76ee): %2 \u3092\u72b6\u614b\u3092\u6301\u3063\u305f\u30a4\u30f3\u30bf\u30d5\u30a7\u30fc\u30b9\u306b\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u30022 \u3064\u4ee5\u4e0a\u306e\u72b6\u614b\u3092\u6301\u3063\u305f\u89aa\u304c\u3042\u308a\u307e\u3059\u3002\n%3\n%4 +#ParseException.badState=%0 (line %1): %2 cannot be a stateful interface; it has more than one stateful parent.\n%3\n%4 +ParseException.branchLabel=%0 (%1 \u884c\u76ee): case %2 \u306f\u65e2\u306b\u5ba3\u8a00\u3055\u308c\u3066\u3044\u307e\u3059\u3002\n%3\n%4 +#ParseException.branchLabel=%0 (line %1): case %2 has already been declared.\n%3\n%4 +ParseException.branchName=%0 (%1 \u884c\u76ee): %2 \u3068\u3044\u3046\u5206\u5c90\u306f\u65e2\u306b\u5ba3\u8a00\u3055\u308c\u3066\u3044\u307e\u3059\u3002\n%3\n%4 +#ParseException.branchName=%0 (line %1): A branch named %2 has already been declared.\n%3\n%4 +ParseException.duplicateInit=%0 (%1 \u884c\u76ee): \u521d\u671f\u5316\u5b50\u306e\u30b7\u30b0\u30cb\u30c1\u30e3\u30fc\u304c\u524d\u306e\u521d\u671f\u5316\u5b50\u3068\u540c\u3058\u3067\u3059\u3002\n%2\n%3 +#ParseException.duplicateInit=%0 (line %1): An initializer has the same signature as a previous initializer.\n%2\n%3 +ParseException.duplicateState=%0 (%1 \u884c\u76ee): \u30c7\u30fc\u30bf\u30e1\u30f3\u30d0 %2 \u306e\u540d\u524d\u304c\u524d\u306e\u30c7\u30fc\u30bf\u30e1\u30f3\u30d0\u3068\u540c\u3058\u3067\u3059\u3002\n%3\n%4 +#ParseException.duplicateState=%0 (line %1): The data member %2 has the same name as a previous data member.\n%3\n%4 +ParseException.elseNoIf=%0 (%1 \u884c\u76ee): #if \u3068\u30de\u30c3\u30c1\u30f3\u30b0\u3057\u306a\u3044 #else \u304c\u691c\u51fa\u3055\u308c\u307e\u3057\u305f\u3002\n%2\n%3 +#ParseException.elseNoIf=%0 (line %1): #else encountered without a matching #if.\n%2\n%3 +ParseException.endNoIf=%0 (%1 \u884c\u76ee): #if \u3068\u30de\u30c3\u30c1\u30f3\u30b0\u3057\u306a\u3044 #endif \u304c\u691c\u51fa\u3055\u308c\u307e\u3057\u305f\u3002\n%2\n%3 +#ParseException.endNoIf=%0 (line %1): #endif encountered without a matching #if.\n%2\n%3 +ParseException.evaluation=%0 (%1 \u884c\u76ee): %2\n%3\n%4 +#ParseException.evaluation=%0 (line %1): %2\n%3\n%4 +ParseException.forwardEntry=%0 (%1 \u884c\u76ee): %2 \u3078\u306e\u524d\u65b9\u53c2\u7167\u304c\u3042\u308a\u307e\u3057\u305f\u304c\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.forwardEntry=%0 (line %1): There is a forward reference to %2, but it is not defined.\n%3\n%4 +ParseException.forwardedValueBox=%0 (%1 \u884c\u76ee): %2 \u306b\u524d\u65b9\u5ba3\u8a00\u304c\u3042\u308a\u307e\u3059\u3002\u5024\u30dc\u30c3\u30af\u30b9\u3092\u524d\u65b9\u5ba3\u8a00\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.forwardedValueBox=%0 (line %1): %2 has a forward declaration. A value box cannot be forward declared.\n%3\n%4 +ParseException.forwardInheritance=%0 (%1 \u884c\u76ee): %3 \u306e\u4e0d\u5b8c\u5168\u306a\u524d\u65b9\u5ba3\u8a00\u3092 %2 \u304c\u7d99\u627f\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.forwardInheritance=%0 (line %1): It is illegal for %2 to inherit from the incomplete forward declaration of %3.\n%4\n%5 +ParseException.generic=%0 (%1 \u884c\u76ee): %2\n%3\n%4 +#ParseException.generic=%0 (line %1): %2\n%3\n%4 +ParseException.illegalArray=%0 (%1 \u884c\u76ee): %2 \u306e\u914d\u5217\u306e\u578b\u304c\u4e0d\u6b63\u3067\u3059\u3002\n%3\n%4 +#ParseException.illegalArray=%0 (line %1): An array is not a legal type in a %2.\n%3\n%4 +ParseException.illegalException=%0 (%1 \u884c\u76ee): %2 \u5185\u3067\u4f8b\u5916\u3092\u751f\u6210\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.illegalException=%0 (line %1): Exceptions cannot appear within %2s.\n%3\n%4 +ParseException.invalidConst1=%0 (%1 \u884c\u76ee): \u5b9a\u6570\u5f0f\u306e\u578b\u306f %3 \u3067\u306f\u306a\u304f %2 \u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.invalidConst1=%0 (line %1): Constant expression must be of type %2, not %3.\n%4\n%5 +ParseException.invalidConst2=%0 (%1 \u884c\u76ee): \u5b9a\u6570\u5f0f\u5185\u306e\u8b58\u5225\u5b50\u306f %2 \u3067\u306f\u306a\u304f\u5b9a\u6570\u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.invalidConst2=%0 (line %1): Identifiers in constant expressions must be constants, not %2.\n%3\n%4 +ParseException.keywordCollision=%0 (%1 \u884c\u76ee): \u8b58\u5225\u5b50 `%2' \u304c\u30ad\u30fc\u30ef\u30fc\u30c9\u3068\u885d\u7a81\u3057\u3066\u3044\u307e\u3059\u3002\u62e1\u5f35\u8b58\u5225\u5b50\u3092\u5fc5\u8981\u306b\u5fdc\u3058\u3066\u4f7f\u7528\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n%3\n%4 +#ParseException.keywordCollision=%0 (line %1): Identifier `%2' collides with keyword; use escaped identifier if necessary.\n%3\n%4 +ParseException.methodClash=%0 (%1 \u884c\u76ee): \u30e1\u30bd\u30c3\u30c9\u540d\u304c\u30a4\u30f3\u30bf\u30d5\u30a7\u30fc\u30b9 %2 \u3067\u885d\u7a81\u3057\u3066\u3044\u307e\u3059: %3.\n%4\n%5 +#ParseException.methodClash=%0 (line %1): Method name clash in interface %2: %3.\n%4\n%5 +ParseException.moduleNotType=%0 (%1 \u884c\u76ee): %2 \u306f\u30e2\u30b8\u30e5\u30fc\u30eb\u3067\u3059\u3002\u578b\u3068\u3057\u3066\u4f7f\u7528\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.moduleNotType=%0 (line %1): %2 is a module. It cannot be used as a type.\n%3\n%4 +ParseException.nestedValueBox=%0 (%1 \u884c\u76ee): \u5024\u30dc\u30c3\u30af\u30b9\u3092\u5165\u308c\u5b50\u306b\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%2\n%3 +#ParseException.nestedValueBox=%0 (line %1): Value boxes cannot be nested.\n%2\n%3 +ParseException.noDefault=%0 (%1 \u884c\u76ee): \u8d77\u3053\u308a\u3046\u308b\u5168 case \u304c\u5b8c\u5168\u306b\u30ab\u30d0\u30fc\u3055\u308c\u3066\u3044\u306a\u3044\u9650\u308a\u3001\u30c7\u30d5\u30a9\u30eb\u30c8\u306e\u5206\u5c90\u3092\u4f7f\u7528\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%2\n%3 +#ParseException.noDefault=%0 (line %1): A default branch is not allowed when all possible cases are fully covered.\n%2\n%3 +ParseException.nonAbstractParent=%0 (%1 \u884c\u76ee): abstract \u30a4\u30f3\u30bf\u30d5\u30a7\u30fc\u30b9 %2 \u306f\u975e abstract \u30a4\u30f3\u30bf\u30d5\u30a7\u30fc\u30b9 %3 \u3092\u7d99\u627f\u3067\u304d\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.nonAbstractParent=%0 (line %1): The abstract interface %2 cannot inherit from the non-abstract interface %3.\n%4\n%5 +ParseException.nonAbstractParent2=%0 (%1 \u884c\u76ee): abstract \u5024 %2 \u306f\u975e abstract \u5024 %3 \u3092\u7d99\u627f\u3067\u304d\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.nonAbstractParent2=%0 (line %1): The abstract value %2 cannot inherit from the non-abstract value %3.\n%4\n%5 +ParseException.nonAbstractParent3=%0 (%1 \u884c\u76ee): \u5024 %2 \u306f\u6307\u5b9a\u3055\u308c\u305f\u975e abstract \u5024 %3 \u3092\u7d99\u627f\u3067\u304d\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.nonAbstractParent3=%0 (line %1): The value %2 cannot inherit from the non-abstract value %3 as specified.\n%4\n%5 +ParseException.notANumber=%0 (%1 \u884c\u76ee): \u6570\u5024\u304c\u4e88\u671f\u3055\u308c\u3066\u3044\u307e\u3057\u305f\u3002%2 \u306f\u4e0d\u6b63\u306a\u6570\u5024\u3067\u3059\u3002\n%3\n%4 +#ParseException.notANumber=%0 (line %1): A number was expected. %2 is not a valid number.\n%3\n%4 +ParseException.nothing=%0 \u306f\u7a7a\u3067\u3059\u3002\u30b3\u30f3\u30d1\u30a4\u30eb\u5bfe\u8c61\u304c\u5b58\u5728\u3057\u307e\u305b\u3093\u3002 +#ParseException.nothing=%0 is empty. There is nothing to compile. +ParseException.notPosInt=%0 (%1 \u884c\u76ee): %2 \u3067\u306f\u306a\u304f\u6b63\u306e\u6574\u6570\u5b9a\u6570\u304c\u4e88\u671f\u3055\u308c\u3066\u3044\u307e\u3057\u305f\u3002\n%3\n%4 +#ParseException.notPosInt=%0 (line %1): Expected a positive integer constant, not %2.\n%3\n%4 +ParseException.oneway=%0 (%1 \u884c\u76ee): %2 \u306f\u7247\u65b9\u5411\u306b\u5ba3\u8a00\u3055\u308c\u3066\u3044\u307e\u3059\u3002\u7247\u65b9\u5411\u30e1\u30bd\u30c3\u30c9\u306f\u3001void \u3092\u8fd4\u3059\u3053\u3068\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u5185\u3067 1 \u3064\u3060\u3051\u3067\u3042\u308b\u3053\u3068\u3001\u4f8b\u5916\u3092\u751f\u6210\u3057\u306a\u3044\u3053\u3068\u304c\u8981\u6c42\u3055\u308c\u307e\u3059\u3002\n%3\n%4 +#ParseException.oneway=%0 (line %1): %2 is declared to be oneway. Oneway methods must: return void; have only in parameters; raise no exceptions.\n%3\n%4 +ParseException.operationNotType=%0 (%1 \u884c\u76ee): %2 \u306f\u6f14\u7b97\u5b50\u3067\u3059\u3002\u578b\u3068\u3057\u3066\u4f7f\u7528\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.operationNotType=%0 (line %1): %2 is an operation. It cannot be used as a type.\n%3\n%4 +ParseException.outOfRange=%0 (%1 \u884c\u76ee): \u5b9a\u6570\u5f0f\u306e\u5024 %2 \u306f\u578b %3 \u306e\u7bc4\u56f2\u5916\u3067\u3059\u3002\n%4\n%5 +#ParseException.outOfRange=%0 (line %1): The value of the constant expression, %2, is out of range for type %3.\n%4\n%5 +ParseException.recursive=%0 (%1 \u884c\u76ee): \u6b63\u5f53\u306a\u518d\u5e30\u5b9a\u7fa9\u306f\u6b21\u306e\u3082\u306e\u3060\u3051\u3067\u3059: sequence<%2> %3.\n%4\n%5 +#ParseException.recursive=%0 (line %1): The only legal recursive definition is: sequence<%2> %3.\n%4\n%5 +ParseException.selfInherit=%0 (%1 \u884c\u76ee): %2 \u306f\u81ea\u8eab\u3092\u7d99\u627f\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%3\n%4 +#ParseException.selfInherit=%0 (line %1): %2 cannot inherit from itself.\n%3\n%4 +ParseException.stringTooLong=%0 (%1 \u884c\u76ee): "%2" \u306f %3 \u6587\u5b57\u4ee5\u4e0a\u306e\u9577\u3055\u306b\u3059\u308b\u3053\u3068\u306f\u3067\u304d\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.stringTooLong=%0 (line %1): "%2" cannot be more than %3 characters long.\n%4\n%5 +ParseException.syntax1=%0 (%1 \u884c\u76ee): `%2' \u304c\u4e88\u671f\u3055\u308c `%3' \u304c\u691c\u51fa\u3055\u308c\u307e\u3057\u305f\u3002\n%4\n%5 +#ParseException.syntax1=%0 (line %1): Expected `%2'; encountered `%3'.\n%4\n%5 +ParseException.syntax2=%0 (%1 \u884c\u76ee): %2 \u306e 1 \u3064\u304c\u4e88\u671f\u3055\u308c `%3'\u304c\u691c\u51fa\u3055\u308c\u307e\u3057\u305f\u3002\n%4\n%5 +#ParseException.syntax2=%0 (line %1): Expected one of%2; encountered `%3'.\n%4\n%5 +ParseException.unclosed=%0: \u30b3\u30e1\u30f3\u30c8\u5185\u306b\u4e88\u60f3\u5916\u306e EOF \u304c\u691c\u51fa\u3055\u308c\u307e\u3057\u305f\u3002 +#ParseException.unclosed=%0: Unexpected end of file encountered in comment. +ParseException.undeclaredType=%0 (%1 \u884c\u76ee): %2 \u306f\u5ba3\u8a00\u3055\u308c\u3066\u3044\u306a\u3044\u578b\u3067\u3059\u3002\n%3\n%4 +#ParseException.undeclaredType=%0 (line %1): %2 is an undeclared type.\n%3\n%4 +ParseException.warning=%0 (%1 \u884c\u76ee): %2\n%3\n%4 +#ParseException.warning=%0 (line %1): %2\n%3\n%4 +ParseException.wrongType=%0 (%1 \u884c\u76ee): %2 \u306e\u578b\u306f %3 \u3067\u3059\u304c %4 \u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002\n%5\n%6 +#ParseException.wrongType=%0 (line %1): The type of %2 is %3, but it should be %4.\n%5\n%6 +ParseException.constExprType=%0 (%1 \u884c\u76ee): \u5b9a\u6570\u5f0f\u306e\u578b\u306f %2 \u3067\u3059\u304c\u3001%3 \u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002\n%4\n%5 +#ParseException.constExprType=%0 (line %1): The type of the constant expression is %2, but it should be %3.\n%4\n%5 +Preprocessor.unknown=`%0'\u306f\u672a\u77e5\u306e\u30d7\u30ea\u30d7\u30ed\u30bb\u30c3\u30b5\u6307\u793a\u3067\u3059\u3002\u884c\u306f\u7121\u8996\u3055\u308c\u307e\u3059\u3002 +#Preprocessor.unknown=Unknown preprocessor directive, `%0'. Line ignored. +Preprocessor.unknownPragma=`%0'\u306f\u672a\u77e5\u306e\u30d7\u30e9\u30b0\u30de\u3067\u3059\u3002\u884c\u306f\u7121\u8996\u3055\u308c\u307e\u3059\u3002 +#Preprocessor.unknownPragma=Unknown pragma `%0'. Line ignored. +Preprocessor.undefinedName=%1 \u306f\u30d7\u30e9\u30b0\u30de %0 \u306e\u672a\u5b9a\u7fa9\u306e\u578b\u540d\u3067\u3059\u3002\u884c\u306f\u7121\u8996\u3055\u308c\u307e\u3059\u3002 +#Preprocessor.undefinedName=Undefined type name for pragma %0: %1. Line ignored. +Token.boolLit= +#Token.boolLit= +Token.charLit= +#Token.charLit= +Token.intLit= +#Token.intLit= +Token.floatLit= +#Token.floatLit= +Token.stringLit= +#Token.stringLit= +Token.literal= +#Token.literal= +Token.identifier= +#Token.identifier= +Token.endOfFile=EOF +#Token.endOfFile=EOF +Token.unknown=? +#Token.unknown=? +Util.cantCreatePkg=\u30d1\u30c3\u30b1\u30fc\u30b8 %0 \u3092\u4f5c\u6210\u3067\u304d\u307e\u305b\u3093\u3002 +#Util.cantCreatePkg=Cannot create the package %0. +Version.product=IDL Parser Framework, \u30d0\u30fc\u30b8\u30e7\u30f3 "%0" +#Version.product=IDL Parser Framework, version "%0" +Version.number=3.0 +#Version.number=3.0 +default=\u30a8\u30e9\u30fc! \u5b58\u5728\u3057\u306a\u3044\u30e1\u30c3\u30bb\u30fc\u30b8\u304c\u8981\u6c42\u3055\u308c\u307e\u3057\u305f\u3002\u30e1\u30c3\u30bb\u30fc\u30b8\u30d5\u30a1\u30a4\u30eb\u306b\u30ad\u30fc\u304c\u3042\u308a\u307e\u305b\u3093: %0. +#default=Error! A message was requested which does not exist. The messages file does not contain the key: %0. + +# Translator: In the list of options below, do not translate: +# -i, -d, -keep, -emitAll, -noWarn, -v, -verbose, -version, #define +# Do not translate the string "java Compile" + +usage=\u30b3\u30f3\u30d1\u30a4\u30e9\u306e\u4f7f\u3044\u65b9:\n\ +\ java Compile [options] \n\ + \u306f IDL \u5b9a\u7fa9\u304c\u683c\u7d0d\u3055\u308c\u305f\u30d5\u30a1\u30a4\u30eb\u306e\u540d\u524d\u3067\u3059\u3002\n\ +[options] \u306f\u4ee5\u4e0b\u306b\u793a\u3059\u30aa\u30d7\u30b7\u30e7\u30f3\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u3059\u3002\n\ +\u3053\u308c\u3089\u306e\u30aa\u30d7\u30b7\u30e7\u30f3\u306f\u7701\u7565\u53ef\u80fd\u3067\u3001\u4efb\u610f\u306e\u9806\u5e8f\u3067\u4f7f\u7528\u3067\u304d\u307e\u3059\u3002\n\ +\u305f\u3060\u3057 \u306f\u5fc5\u9808\u3067\u3001\u6700\u5f8c\u306b\u6307\u5b9a\u3059\u308b\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059\u3002\n\ +\ \n\ +\u30aa\u30d7\u30b7\u30e7\u30f3:\n\ + -d IDL \u30d5\u30a1\u30a4\u30eb\u5185\u306e\u6b21\u306e\u884c\u3068\u7b49\u4fa1:\n\ +\ #define \n\ + -emitAll #include \u30d5\u30a1\u30a4\u30eb\u306b\u6307\u5b9a\u3055\u308c\u3066\u3044\u308b\u3082\u306e\u3082\u542b\u3081\u5168\u578b\u3092\u751f\u6210\u3059\u308b\n\ + -i \u30c7\u30d5\u30a9\u30eb\u30c8\u3067\u306f\u73fe\u5728\u306e\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u3067\u30a4\u30f3\u30af\u30eb\u30fc\u30c9\u30d5\u30a1\u30a4\u30eb\u3092\n\ +\ \u691c\u7d22\u3059\u308b\u3002\u305d\u308c\u4ee5\u5916\u306e\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u306f\u3053\u306e\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u8ffd\u52a0\u3059\u308b\n\ + -keep \u751f\u6210\u3059\u308b\u30d5\u30a1\u30a4\u30eb\u304c\u65e2\u306b\u5b58\u5728\u3059\u308b\u5834\u5408\u3001\u65e2\u5b58\u306e\u30d5\u30a1\u30a4\u30eb\u3092\n\ +\ \u4e0a\u66f8\u304d\u3057\u306a\u3044\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u3067\u306f\u4e0a\u66f8\u304d\u3059\u308b\n\ + -noWarn \u8b66\u544a\u3092\u751f\u6210\u3057\u306a\u3044\n\ + -v, -verbose \u5197\u9577\u30e2\u30fc\u30c9\n\ + -version \u30d0\u30fc\u30b8\u30e7\u30f3\u756a\u53f7\u3092\u8868\u793a\u3057\u3066\u7d42\u4e86\n +#usage=Compiler Usage:\n\ +#\ java Compile [options] \n\ +#where is the name of a file containing IDL definitions, and\n\ +#[options] is any combination of the options listed below. The options\n\ +#are optional and may appear in any order; is required and\n\ +#must appear last.\n\ +#\ \n\ +#Options:\n\ +# -d This is equivalent to the following line in an\n\ +#\ IDL file: #define \n\ +# -emitAll Emit all types, including those found in #included\n\ +#\ files.\n\ +# -i By default, the current directory is scanned for\n\ +#\ included files. This option adds another directory.\n\ +# -keep If a file to be generated already exists, do not\n\ +#\ overwrite it. By default it is overwritten.\n\ +# -noWarn Suppress warnings.\n\ +# -v, -verbose Verbose mode.\n\ +# -version Display the version number.\n + + diff --git a/idlj/src/main/resources/com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable.properties b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable.properties new file mode 100644 index 000000000..2f8250b29 --- /dev/null +++ b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable.properties @@ -0,0 +1,88 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997-1999 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# +# Translator: Each line below is of the form "=". +# The keys are NOT to be translated. +# The messages ARE to be translated. +# +# DO NOT translate the following: +# IBM +# IDL +# Java +# +# %0 is a parameter to the message. Do not translate it. +# +# A backslash (\) at the end of a line is a line continuation +# character. A backslash at the beginning of a line means don't +# ignore leading blanks (they normally are). These backslashes +# should remain in the message. +# +# Translator: Start Translating +# +toJavaProlog1=Generated by the %0 +toJavaProlog2=from %0 +PreEmit.indeterminateTypeInfo=Cannot determine type infomation for %0. +InterfaceGen.noImpl=No local implementation found for %0. +Version.product=IDL-to-Java compiler (portable), version "%0" +Version.number=4.1 +NameModifier.TooManyPercent=Pattern contains more than one percent characters +NameModifier.NoPercent=Pattern does not contain a percent character +NameModifier.InvalidChar=Pattern contains an invalid character %0 +# +# Translator: In the list of options below, do not translate: +# -d, -emitAll, -f, -i, -keep, -m, -sep, -pkgPrefix, -td, -v, -verbose, -version, -implbase +# Do not translate the string "java Compile" +# +usage=Compiler Usage:\n\ +\n\ +\ java Compile [options] \n\ +\n\ +where is the name of a file containing IDL definitions, and\n\ +[options] is any combination of the options listed below. The options\n\ +are optional and may appear in any order; is required and\n\ +must appear last.\n\ +\ \n\ +Options:\n\ + -d This is equivalent to the following line in an\n\ +\ IDL file: #define \n\ + -emitAll Emit all types, including those found in #included files.\n\ + -f Define what bindings to emit. is one of client,\n\ +\ server, all, serverTIE, allTIE. serverTIE and allTIE\n\ +\ cause delegate model skeletons to be emitted. If this\n\ +\ flag is not used, -fclient is assumed.\n\ + -i By default, the current directory is scanned for\n\ +\ included files. This option adds another directory.\n\ + -keep If a file to be generated already exists, do not\n\ +\ overwrite it. By default it is overwritten.\n\ + -noWarn Suppress warnings.\n\ + -oldImplBase Generate skeletons compatible with old (pre-1.4) JDK ORBs.\n\ + -pkgPrefix When the type or module name is encountered at\n\ +\ file scope, begin the Java package name for all files\n\ +\ generated for with .\n\ + -pkgTranslate When the type or module name in encountered, replace\n\ +\ it with in the generated java package. Note that\n\ +\ pkgPrefix changes are made first. must match the\n\ +\ full package name exactly. Also, must not be\n\ +\ org, org.omg, or any subpackage of org.omg.\n\ + -skeletonName Name the skeleton according to the pattern.\n\ +\ The defaults are:\n\ +\ %POA for the POA base class (-fserver or -fall) \n\ +\ _%ImplBase for the oldImplBase base class\n\ +\ (-oldImplBase and (-fserver or -fall)).\n\ + -td

use for the output directory instead of\n\ +\ the current directory.\n\ + -tieName Name the tie according to the pattern. The defaults are:\n\ +\ %POATie for the POA tie (-fserverTie or -fallTie) \n\ +\ %_Tie for the oldImplBase tie\n\ +\ (-oldImplBase and (-fserverTie or -fallTie)).\n\ + -v, -verbose Verbose mode.\n\ + -version Display the version number and quit.\n diff --git a/idlj/src/main/resources/com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable_ja.properties b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable_ja.properties new file mode 100644 index 000000000..8eed15041 --- /dev/null +++ b/idlj/src/main/resources/com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable_ja.properties @@ -0,0 +1,139 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997-1999 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# +# Translator: Each line below is of the form "=". +# The keys are NOT to be translated. +# The messages ARE to be translated. +# +# DO NOT translate the following: +# IBM +# IDL +# Java +# +# %0 is a parameter to the message. Do not translate it. +# +# A backslash (\) at the end of a line is a line continuation +# character. A backslash at the beginning of a line means don't +# ignore leading blanks (they normally are). These backslashes +# should remain in the message. +# +# Translator: Start Translating +# +toJavaProlog1=%0 \u3067\u751f\u6210 +#toJavaProlog1=Generated by the %0 +toJavaProlog2=\u751f\u6210\u5143: %0 +#toJavaProlog2=from %0 +PreEmit.indeterminateTypeInfo=%0 \u306e\u578b\u60c5\u5831\u3092\u5224\u5b9a\u3067\u304d\u307e\u305b\u3093\u3002 +#PreEmit.indeterminateTypeInfo=Cannot determine type infomation for %0. +InterfaceGen.noImpl=%0 \u306e\u30ed\u30fc\u30ab\u30eb\u5b9f\u88c5\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3002 +#InterfaceGen.noImpl=No local implementation found for %0. +Version.product=IDL-to-Java \u30b3\u30f3\u30d1\u30a4\u30e9 (\u30dd\u30fc\u30bf\u30d6\u30eb), \u30d0\u30fc\u30b8\u30e7\u30f3 "%0" +#Version.product=IDL-to-Java compiler (portable), version "%0" +Version.number=3.1 +#Version.number=3.1 +NameModifier.TooManyPercent=\u30d1\u30bf\u30fc\u30f3\u306b\u30011 \u3064\u4ee5\u4e0a\u306e % \u6587\u5b57\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059 +#NameModifier.TooManyPercent=Pattern contains more than one percent characters +NameModifier.NoPercent=\u30d1\u30bf\u30fc\u30f3\u306b % \u6587\u5b57\u304c 1 \u3064\u3082\u542b\u307e\u308c\u3066\u3044\u307e\u305b\u3093 +#NameModifier.NoPercent=Pattern does not contain a percent character +NameModifier.InvalidChar=\u30d1\u30bf\u30fc\u30f3\u306b\u7121\u52b9\u306a\u6587\u5b57 %0 \u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059 +#NameModifier.InvalidChar=Pattern contains an invalid character %0 +# +# Translator: In the list of options below, do not translate: +# -d, -emitAll, -f, -i, -keep, -m, -sep, -pkgPrefix, -td, -v, -verbose, -version, -implbase +# Do not translate the string "java Compile" +# +usage=\u30b3\u30f3\u30d1\u30a4\u30e9\u306e\u4f7f\u3044\u65b9:\n\ +\n\ +\ java Compile [options] \n\ +\n\ + \u306f IDL \u5b9a\u7fa9\u304c\u683c\u7d0d\u3055\u308c\u305f\u30d5\u30a1\u30a4\u30eb\u306e\u540d\u524d\u3067\u3059\u3002\n\ +[options] \u306f\u4ee5\u4e0b\u306b\u793a\u3059\u30aa\u30d7\u30b7\u30e7\u30f3\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u3059\u3002\n\ +\u3053\u308c\u3089\u306e\u30aa\u30d7\u30b7\u30e7\u30f3\u306f\u7701\u7565\u53ef\u80fd\u3067\u3001\u4efb\u610f\u306e\u9806\u5e8f\u3067\u4f7f\u7528\u3067\u304d\u307e\u3059\u3002\n\ +\u305f\u3060\u3057 \u306f\u5fc5\u9808\u3067\u3001\u6700\u5f8c\u306b\u6307\u5b9a\u3059\u308b\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059\u3002\n\ +\ \n\ +\u30aa\u30d7\u30b7\u30e7\u30f3:\n\ + -d IDL \u30d5\u30a1\u30a4\u30eb\u5185\u306e\u6b21\u306e\u884c\u3068\u7b49\u4fa1:\n\ +\ #define \n\ + -emitAll #included \u30d5\u30a1\u30a4\u30eb\u5185\u306e\u3082\u306e\u3092\u542b\u3080\u5168\u578b\u3092\u751f\u6210\u3059\u308b\n\ + -f \u751f\u6210\u3059\u308b\u30d3\u30eb\u30c9\u3092\u5b9a\u7fa9\u3059\u308b\u3002 \u306b\u306f\u3001client\u3001server\u3001\n\ +\ all\u3001serverTIE\u3001allTIE \u306e\u3046\u3061\u306e 1 \u3064\u3092\u6307\u5b9a\u3059\u308b\u3002serverTIE \u3068\n\ +\ allTIE \u3067\u306f\u59d4\u8b72\u30e2\u30c7\u30eb\u30b9\u30b1\u30eb\u30c8\u30f3\u304c\u751f\u6210\u3055\u308c\u308b\u3002\u3053\u306e\u30d5\u30e9\u30b0\u3092\n\ +\ \u6307\u5b9a\u3057\u306a\u3044\u5834\u5408\u3001-fclient \u304c\u6307\u5b9a\u3055\u308c\u305f\u3082\u306e\u3068\u3057\u3066\u52d5\u4f5c\u3059\u308b\n\ + -i \u30c7\u30d5\u30a9\u30eb\u30c8\u3067\u306f\u73fe\u5728\u306e\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u3067\u30a4\u30f3\u30af\u30eb\u30fc\u30c9\u30d5\u30a1\u30a4\u30eb\u3092\u691c\u7d22\n\ +\ \u3059\u308b\u3002\u305d\u308c\u4ee5\u5916\u306e\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u306f\u3053\u306e\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u8ffd\u52a0\u3059\u308b\n\ + -keep \u751f\u6210\u3059\u308b\u30d5\u30a1\u30a4\u30eb\u304c\u65e2\u306b\u5b58\u5728\u3059\u308b\u5834\u5408\u3001\u65e2\u5b58\u306e\u30d5\u30a1\u30a4\u30eb\u3092\n\ +\ \u4e0a\u66f8\u304d\u3057\u306a\u3044\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u3067\u306f\u4e0a\u66f8\u304d\u3059\u308b\n\ + -noWarn \u8b66\u544a\u3092\u751f\u6210\u3057\u306a\u3044\n\ + -oldImplBase \u65e7 JDK (1.4 \u4ee5\u524d) \u306e ORB \u3068\u4e92\u63db\u6027\u306e\u3042\u308b\u30b9\u30b1\u30eb\u30c8\u30f3\u3092\u751f\u6210\u3059\u308b\n\ + -pkgPrefix \u30d5\u30a1\u30a4\u30eb\u30b9\u30b3\u30fc\u30d7\u3067\u578b\u540d\u307e\u305f\u306f\u30e2\u30b8\u30e5\u30fc\u30eb\u540d \u304c\u691c\u51fa\u3055\u308c\u305f\n\ +\ \u5834\u5408\u3001 \u306b\u5bfe\u3057\u3066\u751f\u6210\u3059\u308b\u5168\u30d5\u30a1\u30a4\u30eb\u306e Java \u30d1\u30c3\u30b1\u30fc\u30b8\u540d\u306e\n\ +\ \u5148\u982d\u306b \u3092\u8ffd\u52a0\u3059\u308b\n\ + -pkgTranslate \u578b\u307e\u305f\u306f\u30e2\u30b8\u30e5\u30fc\u30eb\u540d \u3092\u691c\u51fa\u3059\u308b\u3068\u3001\u751f\u6210\u3057\u305f java\n\ +\ \u30d1\u30c3\u30b1\u30fc\u30b8\u5185\u306e \u306b\u7f6e\u304d\u63db\u3048\u3089\u308c\u308b\u3002pkgPrefix \u304c\u6700\u521d\u306b\n\ +\ \u5909\u66f4\u3055\u308c\u308b\u3053\u3068\u306b\u6ce8\u610f\u3059\u308b\u3053\u3068\u3002 \u306f\u30d1\u30c3\u30b1\u30fc\u30b8\u540d\u3068\u6b63\u78ba\u306b\n\ +\ \u4e00\u81f4\u3057\u3066\u3044\u308b\u5fc5\u8981\u304c\u3042\u308b\u3002\u307e\u305f\u3001 \u306f\u3001org\u3001org.omg\u3001\u307e\u305f\u306f\n\ +\ org.omg \u306e\u30b5\u30d6\u30d1\u30c3\u30b1\u30fc\u30b8\u3067\u3042\u3063\u3066\u306f\u306a\u3089\u306a\u3044\u3002\n\ + -skeletonName \u30d1\u30bf\u30fc\u30f3\u306b\u5f93\u3063\u3066\u30b9\u30b1\u30eb\u30c8\u30f3\u306b\u540d\u524d\u3092\u4ed8\u3051\u308b\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u306f\n\ +\ \u4ee5\u4e0b\u306e\u901a\u308a:\n\ +\ POA \u57fa\u5e95\u30af\u30e9\u30b9 (-fserver \u307e\u305f\u306f -fall) \u306b\u306f %POA\u3001\n\ +\ oldImplBase \u57fa\u5e95\u30af\u30e9\u30b9 (-oldImplBase \u304a\u3088\u3073 (-fserver \n\ +\ \u307e\u305f\u306f -fall)) \u306b\u306f _%Impl\u3002\n\ + -td \u51fa\u529b\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u3068\u3057\u3066\u73fe\u5728\u306e\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u306e\u4ee3\u308f\u308a\u306b \u3092\n\ +\ \u4f7f\u7528\u3059\u308b\n\ + -tieName \u30d1\u30bf\u30fc\u30f3\u306b\u5f93\u3063\u3066 Tie \u306b\u540d\u524d\u3092\u4ed8\u3051\u308b\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u306f\u4ee5\u4e0b\u306e\u901a\u308a:\n\ +\ POA Tie (-fserverTie \u307e\u305f\u306f -fallTie) \u306b\u306f %POATie\u3001\n\ +\ oldImplBase Tie (-oldImplBase \u304a\u3088\u3073 (-fserverTie \u307e\u305f\u306f\n\ +\ -fallTie)) \u306b\u306f _%Tie\u3002\n\ + -v, -verbose \u8a73\u7d30\u30e2\u30fc\u30c9\n\ + -version \u30d0\u30fc\u30b8\u30e7\u30f3\u756a\u53f7\u3092\u8868\u793a\u3057\u3066\u7d42\u4e86\u3059\u308b\n +#usage=Compiler Usage:\n\ +#\ java Compile [options] \n\ +#where is the name of a file containing IDL definitions, and\n\ +#[options] is any combination of the options listed below. The options\n\ +#are optional and may appear in any order; is required and\n\ +#must appear last.\n\ +#\ \n\ +#Options:\n\ +# -d This is equivalent to the following line in an\n\ +#\ IDL file: #define \n\ +# -emitAll Emit all types, including those found in #included files.\n\ +# -f Define what bindings to emit. is one of client,\n\ +#\ server, all, serverTIE, allTIE. serverTIE and allTIE\n\ +#\ cause delegate model skeletons to be emitted. If this\n\ +#\ flag is not used, -fclient is assumed.\n\ +# -i By default, the current directory is scanned for\n\ +#\ included files. This option adds another directory.\n\ +# -keep If a file to be generated already exists, do not\n\ +#\ overwrite it. By default it is overwritten.\n\ +# -noWarn Suppress warnings.\n\ +# -oldImplBase Generate skeletons compatible with old (pre-1.4) JDK ORBs.\n\ +# -pkgPrefix When the type or module name is encountered at\n\ +#\ file scope, begin the Java package name for all files\n\ +#\ generated for with .\n\ +# -pkgTranslate When the type or module name in encountered, replace\n\ +#\ it with in the generated java package. Note that\n\ +#\ pkgPrefix changes are made first. must match the\n\ +#\ full package name exactly. Also, must not be\n\ +#\ org, org.omg, or any subpackage of org.omg.\n\ +# -skeletonName Name the skeleton according to the pattern.\n\ +#\ The defaults are:\n\ +#\ %POA for the POA base class (-fserver or -fall) \n\ +#\ _%ImplBase for the oldImplBase base class\n\ +#\ (-oldImplBase and (-fserver or -fall)).\n\ +# -td use for the output directory instead of\n\ +#\ the current directory.\n\ +# -tieName Name the tie according to the pattern. The defaults are:\n\ +#\ %POATie for the POA tie (-fserverTie or -fallTie) \n\ +#\ %_Tie for the oldImplBase tie\n\ +#\ (-oldImplBase and (-fserverTie or -fallTie)).\n\ +# -v, -verbose Verbose mode.\n\ +# -version Display the version number and quit.\n\ diff --git a/idlj/src/main/resources/includes/ir.idl b/idlj/src/main/resources/includes/ir.idl new file mode 100644 index 000000000..fa3b3ade0 --- /dev/null +++ b/idlj/src/main/resources/includes/ir.idl @@ -0,0 +1,763 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * This file contains OMG IDL from CORBA V2.0, July 1995. + * It also contains the TypeCode creation APIs in CORBA::ORB + **/ + +#pragma prefix "omg.org" + +module CORBA { + typedef string Identifier; + typedef string ScopedName; + typedef string RepositoryId; + + enum DefinitionKind { + dk_none, dk_all, + dk_Attribute, dk_Constant, dk_Exception, dk_Interface, + dk_Module, dk_Operation, dk_Typedef, + dk_Alias, dk_Struct, dk_Union, dk_Enum, + dk_Primitive, dk_String, dk_Sequence, dk_Array, + dk_Repository, + dk_Wstring, dk_Fixed, + dk_Value, dk_ValueBox, dk_ValueMember, // orbos 98-01-18: Objects By Value + dk_Native + }; + + + interface IRObject + /** + An IRObject IDL interface represents the most generic interface + from which all other Interface Repository interfaces are derived, + even the Repository itself. + */ + { + // read interface + readonly attribute DefinitionKind def_kind; + + // write interface + void destroy (); + }; + + + + typedef string VersionSpec; + + interface Contained; + interface Repository; + interface Container; + + interface Contained : IRObject + /** + The Contained Interface is inherited by all Interface Repository + interfaces that are contained by other objects. + */ + { + // read/write interface + + attribute RepositoryId id; + attribute Identifier name; + attribute VersionSpec version; + + // read interface + + readonly attribute Container defined_in; + readonly attribute ScopedName absolute_name; + readonly attribute Repository containing_repository; + + struct Description { + DefinitionKind kind; + any value; + }; + + Description describe (); + + // write interface + + void move ( + in Container new_container, + in Identifier new_name, + in VersionSpec new_version + ); + }; + + + interface ModuleDef; + interface ConstantDef; + interface IDLType; + interface StructDef; + interface UnionDef; + interface EnumDef; + interface AliasDef; + interface InterfaceDef; + interface ExceptionDef; + interface ValueDef; // orbos 98-01-18: Objects By Value + interface ValueMemberDef; // orbos 98-01-18: Objects By Value + interface ValueBoxDef; // orbos 98-01-18: Objects By Value + interface NativeDef; + + + typedef sequence InterfaceDefSeq; + + + typedef sequence ContainedSeq; + + struct StructMember { + Identifier name; + TypeCode type; + IDLType type_def; + }; + typedef sequence StructMemberSeq; + + struct UnionMember { + Identifier name; + any label; + TypeCode type; + IDLType type_def; + }; + typedef sequence UnionMemberSeq; + + + typedef sequence EnumMemberSeq; + + // orbos 98-01-18: Objects By Value -- begin + typedef short Visibility; + const Visibility PRIVATE_MEMBER = 0; + const Visibility PUBLIC_MEMBER = 1; + + struct ValueMember { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + IDLType type_def; + Visibility access; + }; + typedef sequence ValueMemberSeq; + + struct Initializer { + StructMemberSeq members; + }; + typedef sequence InitializerSeq; + + typedef sequence ValueDefSeq; + + // orbos 98-01-18: Objects By Value -- end + + + interface Container : IRObject + /** + The Container interface is used to form a containment hierarchy + in the Interface Repository. A Container can contain any number + of objects derived from the Contained interface. + */ + { + // read interface + + Contained lookup ( in ScopedName search_name); + + ContainedSeq contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + ContainedSeq lookup_name ( + in Identifier search_name, + in long levels_to_search, + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + struct Description { + Contained contained_object; + DefinitionKind kind; + any value; + }; + + typedef sequence DescriptionSeq; + + DescriptionSeq describe_contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited, + in long max_returned_objs + ); + + // write interface + + ModuleDef create_module ( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + ConstantDef create_constant ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in any value + ); + + StructDef create_struct ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + UnionDef create_union ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType discriminator_type, + in UnionMemberSeq members + ); + + EnumDef create_enum ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in EnumMemberSeq members + ); + + AliasDef create_alias ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type + ); + + ExceptionDef create_exception ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + + InterfaceDef create_interface ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_abstract, + in InterfaceDefSeq base_interfaces + ); + + // orbos 98-01-18: Objects By Value + ValueDef create_value( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_custom, + in boolean is_abstract, + in octet flags, // must be 0 + in ValueDef base_value, + in boolean has_safe_base, + in ValueDefSeq abstract_base_values, + in InterfaceDefSeq supported_interfaces, + in InitializerSeq initializers + ); + + // orbos 98-01-18: Objects By Value + ValueBoxDef create_value_box( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type_def + ); + + NativeDef create_native( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + }; + + + + interface IDLType : IRObject + /** + The IDLType interface is an abstract interface inherited by all + IR objects that represent the OMG IDL types. It provides access + to the TypeCode describing the type, and is used in defining the + other interfaces wherever definitions of IDLType must be referenced. + */ + { + readonly attribute TypeCode type; + }; + + + + interface PrimitiveDef; + interface StringDef; + interface SequenceDef; + interface ArrayDef; + + enum PrimitiveKind { + pk_null, pk_void, pk_short, pk_long, pk_ushort, pk_ulong, + pk_float, pk_double, pk_boolean, pk_char, pk_octet, + pk_any, pk_TypeCode, pk_Principal, pk_string, pk_objref + }; + + interface Repository : Container + /** + Repository is an interface that provides global access to the + Interface Repository. Repository objects can contain constants, + typedefs, exceptions, interfaces, and modules. + */ + { + // read interface + + Contained lookup_id (in RepositoryId search_id); + + PrimitiveDef get_primitive (in PrimitiveKind kind); + + // write interface + + StringDef create_string (in unsigned long bound); + + SequenceDef create_sequence ( + in unsigned long bound, + in IDLType element_type + ); + + ArrayDef create_array ( + in unsigned long length, + in IDLType element_type + ); + }; + + + interface ModuleDef : Container, Contained + /** + A ModuleDef can contain constants, typedefs, exceptions, interfaces, + and other module objects. + */ + { + }; + + struct ModuleDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + }; + + + interface ConstantDef : Contained + /** + A ConstantDef object defines a named constant. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute any value; + }; + + struct ConstantDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + any value; + }; + + + interface TypedefDef : Contained, IDLType + /** + TypedefDef is an abstract interface used as a base interface for + all named non-object types(structures, unions, enumerations, + aliases). The TypedefDef interface is not inherited by the definition + objects for the primitive or anonymous types. + */ + { + }; + + struct TypeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + interface StructDef : TypedefDef, Container + /** + A StructDef represents an OMG IDL structure definition. + */ + { + attribute StructMemberSeq members; + }; + + + interface UnionDef : TypedefDef, Container + /** + A UnionDef represents an OMG IDL union definition. + */ + { + readonly attribute TypeCode discriminator_type; + attribute IDLType discriminator_type_def; + attribute UnionMemberSeq members; + }; + + + interface EnumDef : TypedefDef + /** + A EnumDef represents an OMG IDL enum definition. + */ + { + attribute EnumMemberSeq members; + }; + + + interface AliasDef : TypedefDef + /** + An AliasDef represents an OMG IDL typedef that aliases other + definition. + */ + { + attribute IDLType original_type_def; + }; + + + interface PrimitiveDef: IDLType + /** + A PrimitiveDef represents one of the IDL primitive types. As + primitive types are unnamed, this interface is not derived from + TypedefDef or Contained. + */ + { + readonly attribute PrimitiveKind kind; + }; + + + interface StringDef : IDLType + /** + A StringDef represents an OMG IDL string type. As string + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + }; + + + interface SequenceDef : IDLType + /** + A SequenceDef represents an OMG IDL sequence type. As sequence + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + interface ArrayDef : IDLType + /** + An ArrayDef represents an OMG IDL array type. As array + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long length; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + + interface ExceptionDef : Contained, Container + /** + An ExceptionDef represents an exception definition. + */ + { + readonly attribute TypeCode type; + attribute StructMemberSeq members; + }; + struct ExceptionDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + + enum AttributeMode {ATTR_NORMAL, ATTR_READONLY}; + + interface AttributeDef : Contained + /** + An AttributeDef represents the information that defines an + attribute of an interface. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute AttributeMode mode; + }; + + struct AttributeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + AttributeMode mode; + }; + + + + enum OperationMode {OP_NORMAL, OP_ONEWAY}; + + enum ParameterMode {PARAM_IN, PARAM_OUT, PARAM_INOUT}; + struct ParameterDescription { + Identifier name; + TypeCode type; + IDLType type_def; + ParameterMode mode; + }; + typedef sequence ParDescriptionSeq; + + typedef Identifier ContextIdentifier; + typedef sequence ContextIdSeq; + + typedef sequence ExceptionDefSeq; + typedef sequence ExcDescriptionSeq; + + interface OperationDef : Contained + /** + An OperationDef represents the information that defines an + operation of an interface. + */ + { + readonly attribute TypeCode result; + attribute IDLType result_def; + attribute ParDescriptionSeq params; + attribute OperationMode mode; + attribute ContextIdSeq contexts; + attribute ExceptionDefSeq exceptions; + }; + + struct OperationDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode result; + OperationMode mode; + ContextIdSeq contexts; + ParDescriptionSeq parameters; + ExcDescriptionSeq exceptions; + }; + + + + typedef sequence RepositoryIdSeq; + typedef sequence OpDescriptionSeq; + typedef sequence AttrDescriptionSeq; + + interface InterfaceDef : Container, Contained, IDLType + /** + An InterfaceDef object represents an interface definition. It can + contains constants, typedefs, exceptions, operations, and + attributes. + */ + { + // read/write interface + + attribute InterfaceDefSeq base_interfaces; + attribute boolean is_abstract; + + // read interface + + boolean is_a (in RepositoryId interface_id); + + struct FullInterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + boolean is_abstract; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + RepositoryIdSeq base_interfaces; + TypeCode type; + }; + + FullInterfaceDescription describe_interface(); + + // write interface + + AttributeDef create_attribute ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + + struct InterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq base_interfaces; + }; + + + // orbos 98-01-18: Objects By Value -- begin + + interface ValueMemberDef : Contained + + /** A ValueMemberDef object represents the public + and private data member definition of a Value type + */ + + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute Visibility access; + }; + + interface ValueDef : Container, Contained, IDLType + /** + A ValueDef object represents the definition of the + Value object used to pass the object state + between hosts + */ + + { + // read/write interface + attribute InterfaceDefSeq supported_interfaces; + attribute InitializerSeq initializers; + attribute ValueDef base_value; + attribute ValueDefSeq abstract_base_values; + attribute boolean is_abstract; + attribute boolean is_custom; + attribute octet flags; // always 0 + attribute boolean has_safe_base; + + // read interface + boolean is_a(in RepositoryId value_id); + + struct FullValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + ValueMemberSeq members; + InitializerSeq initializers; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + TypeCode type; + }; + + FullValueDescription describe_value(); + + // write interface + + ValueMemberDef create_value_member( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type_def, + in Visibility access + ); + + AttributeDef create_attribute( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + struct ValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + }; + + interface ValueBoxDef : IDLType + + /** ValueBoxDef is an interface that reresents a value type with + a single data member inside its state section and no + inheritance or methods. For example, when transmitting a + string or sequence as an actual parameter on an interface + operation or as a data member of a value type that is an + actual parameter, it may be important to preserve any sharing + of the string or sequence within the object graph being + transmitted. Because current IDL data types do not preserve + referential integrity in this way, this requirement is + conveniently handled by using a value type. Value types also + support the transmission of nulls (as a distinguished value), + whereas IDL data types such as string and sequence (which are + mapped to empty strings and sequences) do not. The Java to IDL + mapping requires both preservation of referential integrity + and transmission of nulls. Because it would be cumbersome to + require the full IDL syntax for a value type for this specific + usage, this shorthand notation is introduced to cover this use + of value types for simple containment of a single data member. + */ + +{ + attribute IDLType original_type_def; + }; + + // orbos 98-01-18: Objects By Value -- end + + interface NativeDef : TypedefDef { + }; +}; diff --git a/idlj/src/main/resources/includes/orb.idl b/idlj/src/main/resources/includes/orb.idl new file mode 100644 index 000000000..adf49c32e --- /dev/null +++ b/idlj/src/main/resources/includes/orb.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// IDL not generated by rmic, do not edit +// These are all in IDL module CORBA +// The Java classes are in the package org.omg.CORBA +// See ValueType Semantics:Standard Value Box Definitions (5.3) in CORBA 2.3 spec + +#ifndef __org_omg_CORBA__ +#define __org_omg_CORBA__ + +#pragma prefix "omg.org" + +module CORBA{ + + valuetype StringValue string; + valuetype WStringValue wstring; + +}; + +#include "ir.idl" + +#pragma prefix "" + +#endif diff --git a/idlj/src/test/idl/CorbaServerTest.idl b/idlj/src/test/idl/CorbaServerTest.idl new file mode 100644 index 000000000..03f547e8c --- /dev/null +++ b/idlj/src/test/idl/CorbaServerTest.idl @@ -0,0 +1,96 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +#include "orb.idl" + +module org { +module glassfish { +module idlj { + + struct CORBAStruct { + long l; + long long lll; // The name is 3 chars long to avoid a JDK alignment bug. + string s; + any a; + }; + + struct AnyStruct { + any a; + CORBAStruct s; + }; + + union CORBAUnion switch ( long ) { + case 0: boolean b; + case 1: wstring w; + case 2: string s; + case 3: any a; + case 4: CORBAStruct cs; + default: long long lll; + }; + + enum CORBAEnum { + ONE, + TWO, + THREE + }; + + typedef sequence CORBASeq; + typedef sequence LongSeq; + + interface CORBAServerTest { + exception AnException {}; + exception MungedException { + #pragma ID MungedException "IDL:org/glassfish/idlj/MungedExRepid:1.0" + }; + + string test_primitive(in string s, in long l); + + oneway void test_oneway(in string s, in long l); + + any test_any(in any a); + + void test_out(out string s); + + void test_inout(inout any a); + + void test_transaction(); + + void test_subject(); + + void test_exception() raises (AnException); + + void test_exception2() raises (MungedException); + + wstring test_widestring(in wstring w); + + string test_timeout(in long timeout); + + CORBA::WStringValue test_value(in CORBA::WStringValue w); + + org::glassfish::idlj::CORBAUnion test_union(inout org::glassfish::idlj::CORBAUnion u); + + org::glassfish::idlj::CORBAStruct test_struct(in org::glassfish::idlj::CORBAStruct s, out org::glassfish::idlj::CORBAStruct os); + + org::glassfish::idlj::CORBASeq test_seq(inout org::glassfish::idlj::CORBASeq seq); + + org::glassfish::idlj::LongSeq test_long_seq(inout org::glassfish::idlj::LongSeq seq); + + Object test_POA(in string name); + void cleanup_POA(in string name); + }; + + interface DummyCORBAServer { + #pragma ID DummyCORBAServer "IDL:org/glassfish/idlj/MungedRepid:1.0" + }; + + +}; +}; +}; diff --git a/idlj/src/test/java/com/sun/tools/corba/ee/idl/UtilTest.java b/idlj/src/test/java/com/sun/tools/corba/ee/idl/UtilTest.java new file mode 100644 index 000000000..9776ac01a --- /dev/null +++ b/idlj/src/test/java/com/sun/tools/corba/ee/idl/UtilTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl; + +import com.meterware.simplestub.Memento; +import com.meterware.simplestub.StaticStubSupport; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashSet; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +public class UtilTest { + private HashSet mementos = new HashSet<>(); + + @Before + public void setUp() throws Exception { + mementos.add(StaticStubSupport.install(Util.class, "messages", null)); + mementos.add(StaticStubSupport.preserve(Util.class, "msgResources")); + } + + @After + public void tearDown() throws Exception { + for (Memento memento : mementos) memento.revert(); + } + + @Test + public void readVersionFromDefaultPropertyFile() throws Exception { + assertThat(Util.getVersion(), containsString("4.02")); + } + + @Test + public void readVersionFromUnnamedPropertyFile() throws Exception { + assertThat(Util.getVersion(""), containsString("4.02")); + } + + @Test + public void retrieveMessage() throws Exception { + assertThat(Util.getMessage("EvaluationException.not"), equalTo("bitwise not")); + } + + @Test + public void substituteSingleParamMessage() throws Exception { + assertThat(Util.getMessage("InvalidArgument.1", "zork"), equalTo("Invalid argument: zork.")); + } + + @Test + public void substituteMultiParamMessage() throws Exception { + assertThat(Util.getMessage("GenFileStream.1", new String[] {"zork", "foo"}), equalTo("zork could not be generated: foo")); + } + + @Test + public void retrieveMessagesFromMultipleFiles() throws Exception { + Util.registerMessageResource("com/sun/tools/corba/ee/idl/idl"); + Util.registerMessageResource("com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable"); + + assertThat(Util.getMessage("EvaluationException.not"), equalTo("bitwise not")); + assertThat(Util.getMessage("NameModifier.TooManyPercent"), equalTo("Pattern contains more than one percent characters")); + } + + @Test + public void afterRetrievingMessagesFromOneFile_canRegisterAndRetrieveFromAnother() throws Exception { + Util.registerMessageResource("com/sun/tools/corba/ee/idl/idl"); + Util.getMessage("EvaluationException.not"); + Util.registerMessageResource("com/sun/tools/corba/ee/idl/toJavaPortable/toJavaPortable"); + + assertThat(Util.getMessage("NameModifier.TooManyPercent"), equalTo("Pattern contains more than one percent characters")); + } +} diff --git a/idlj/src/test/java/com/sun/tools/corba/ee/idl/toJavaPortable/IdljGenerationTest.java b/idlj/src/test/java/com/sun/tools/corba/ee/idl/toJavaPortable/IdljGenerationTest.java new file mode 100644 index 000000000..1690d8597 --- /dev/null +++ b/idlj/src/test/java/com/sun/tools/corba/ee/idl/toJavaPortable/IdljGenerationTest.java @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.fail; + +/** + * Tests IDLJ by comparing the generated source files against the expected files. + */ +public class IdljGenerationTest { + + private static int testNum = 0; + private static File rootDir; + private static final boolean COMPILE_GENERATED = true; // set false to check generated files without compiling + + @SuppressWarnings("ResultOfMethodCallIgnored") + @BeforeClass + public static void clearRootDir() throws IOException { + rootDir = Files.createTempDirectory("idlj").toFile(); + } + + @Test + public void generateClassesWithoutOptions() throws Exception { + GenerationControl generator = new GenerationControl("src/main/java/com/sun/tools/corba/ee/idl/ir.idl"); + + generator.generate(); + + checkGeneratedFiles(generator, "ir"); + } + + @Test + public void generateStructureClasses() throws Exception { + GenerationControl generator = new GenerationControl("src/test/idl/CorbaServerTest.idl"); + generator.addArgs("-oldImplBase", "-fall"); + generator.addIncludePath("src/main/java/com/sun/tools/corba/ee/idl"); + + generator.generate(); + + checkGeneratedFiles(generator, "structures"); + } + + // Confirms that the generated files match those in the specified directory of master files + private void checkGeneratedFiles(GenerationControl generator, String mastersSubDir) throws IOException { + File masterDir = new File(getModuleRoot(), "src/test/masters/" + mastersSubDir); + + String[] generatedFilePaths = getFilePaths(generator.getDestDir()); + String[] expectedFilePaths = getFilePaths(masterDir); + + assertThat("In " + generator.getDestDir(), generatedFilePaths, arrayContaining(expectedFilePaths)); + compareGeneratedFiles(masterDir, generator.getDestDir(), expectedFilePaths); + } + + private static File getModuleRoot() { + String classPathString = TestUtils.getClassPathString(); + return new File(classPathString.substring(0, classPathString.lastIndexOf("/target/"))); + } + + // Returns a sorted array of paths to files with the specified suffix under the specified directory, relative to that directory + private String[] getFilePaths(File rootDir) { + ArrayList files = new ArrayList<>(); + appendFiles(files, rootDir, rootDir.getAbsolutePath().length() + 1, ".java"); + Collections.sort(files); + return files.toArray(new String[files.size()]); + } + + @SuppressWarnings("ConstantConditions") + private void appendFiles(ArrayList files, File currentDir, int rootDirLength, String suffix) { + for (File file : currentDir.listFiles()) + if (file.isDirectory()) + appendFiles(files, file, rootDirLength, suffix); + else if (file.getName().endsWith(suffix)) + files.add(getRelativePath(file, rootDirLength)); + } + + private String getRelativePath(File file, int rootDirLength) { + return file.getAbsolutePath().substring(rootDirLength); + } + + private void compareGeneratedFiles(File expectedDir, File actualDir, String... generatedFileNames) throws IOException { + for (String filePath : generatedFileNames) + compareFiles(filePath, expectedDir, actualDir); + } + + private void compareFiles(String filePath, File masterDirectory, File generationDirectory) throws IOException { + File expectedFile = new File(masterDirectory, filePath); + File actualFile = new File(generationDirectory, filePath); + + compareFiles(expectedFile, actualFile); + } + + private void compareFiles(File expectedFile, File actualFile) throws IOException { + LineNumberReader expected = new LineNumberReader(new FileReader(expectedFile)); + LineNumberReader actual = new LineNumberReader(new FileReader(actualFile)); + + String expectedLine = ""; + String actualLine = ""; + while (expectedLine != null && actualLine != null && linesMatch(expectedLine, actualLine)) { + expectedLine = expected.readLine(); + actualLine = actual.readLine(); + } + + if (expectedLine == null && actualLine == null) return; + + if (expectedLine == null) + fail("Unexpected line in generated file at " + actual.getLineNumber() + ": " + actualLine); + else if (actualLine == null) + fail("Actual file ends unexpectedly at line " + expected.getLineNumber()); + else + fail("Generated file mismatch in " + actualFile + " at line " + actual.getLineNumber() + + "\nshould be <" + expectedLine + "> " + + "\nbut found <" + actualLine + ">"); + + } + + private boolean linesMatch(String expectedLine, String actualLine) { + return expectedLine.equals(actualLine) || expectedLine.trim().startsWith("* "); + } + + + private class GenerationControl { + private ArrayList argList = new ArrayList<>(); + private String[] idlFiles; + private File destDir; + private String warning; + + @SuppressWarnings("ResultOfMethodCallIgnored") + GenerationControl(String... idlFiles) { + this.idlFiles = idlFiles; + + destDir = new File(rootDir + "/" + (++testNum)); + destDir.mkdirs(); + addArgs("-td", destDir.getAbsolutePath()); + } + + private void addIncludePath(String includePath) { + addArgs("-i", new File(getModuleRoot(), includePath).getAbsolutePath()); + } + + private void addArgs(String... args) { + argList.addAll(Arrays.asList(args)); + } + + File getDestDir() { + return destDir; + } + + String getWarning() { + return warning; + } + + private void generate() throws IOException { + if (argList.contains("-iiop") && !COMPILE_GENERATED) addArgs("-Xnocompile"); + for (String name : idlFiles) + addArgs(new File(getModuleRoot(), name).getAbsolutePath()); + Compile.compiler = new Compile(); + String[] argv = argList.toArray(new String[argList.size()]); + Compile.compiler.start(argv); + } + + } + + private static String[] toNameList(Class[] classes) { + String[] nameList = new String[classes.length]; + for (int i = 0; i < classes.length; i++) + nameList[i] = classes[i].getName(); + return nameList; + } +} diff --git a/idlj/src/test/java/com/sun/tools/corba/ee/idl/toJavaPortable/TestUtils.java b/idlj/src/test/java/com/sun/tools/corba/ee/idl/toJavaPortable/TestUtils.java new file mode 100644 index 000000000..e8ba846b2 --- /dev/null +++ b/idlj/src/test/java/com/sun/tools/corba/ee/idl/toJavaPortable/TestUtils.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.tools.corba.ee.idl.toJavaPortable; + +import java.io.File; + +public class TestUtils { + @SuppressWarnings("ConstantConditions") + public static String getClassPathString() { + String classFileName = toPath(TestUtils.class.getName()); + String filePath = TestUtils.class.getClassLoader().getResource(classFileName).getPath(); + return filePath.substring(0, filePath.indexOf(classFileName)); + } + + private static String toPath(String className) { + return className.replace('.', File.separatorChar) + ".class"; + } +} diff --git a/idlj/src/test/masters/README b/idlj/src/test/masters/README new file mode 100644 index 000000000..363ddb025 --- /dev/null +++ b/idlj/src/test/masters/README @@ -0,0 +1,5 @@ +The files in this directory were generated by running the Java built-in idlj against: + + idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl + +and are used as 'golden masters' in order to ensure that the Glassfish version is compatible. \ No newline at end of file diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AliasDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDef.java new file mode 100644 index 000000000..ff1b0aa4c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AliasDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface AliasDef extends AliasDefOperations, org.omg.CORBA.TypedefDef, org.omg.CORBA.portable.IDLEntity +{ +} // interface AliasDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefHelper.java new file mode 100644 index 000000000..ab14f295f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AliasDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class AliasDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/AliasDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.AliasDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.AliasDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.AliasDefHelper.id (), "AliasDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.AliasDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_AliasDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.AliasDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.AliasDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.AliasDef) + return (org.omg.CORBA.AliasDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._AliasDefStub stub = new org.omg.CORBA._AliasDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.AliasDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.AliasDef) + return (org.omg.CORBA.AliasDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._AliasDefStub stub = new org.omg.CORBA._AliasDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefHolder.java new file mode 100644 index 000000000..a26298ead --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/AliasDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class AliasDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.AliasDef value = null; + + public AliasDefHolder () + { + } + + public AliasDefHolder (org.omg.CORBA.AliasDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.AliasDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.AliasDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.AliasDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefOperations.java new file mode 100644 index 000000000..949093068 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AliasDefOperations.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AliasDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface AliasDefOperations extends org.omg.CORBA.TypedefDefOperations +{ + org.omg.CORBA.IDLType original_type_def (); + void original_type_def (org.omg.CORBA.IDLType newOriginal_type_def); +} // interface AliasDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDef.java new file mode 100644 index 000000000..cfd8488dd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ArrayDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ArrayDef extends ArrayDefOperations, org.omg.CORBA.IDLType, org.omg.CORBA.portable.IDLEntity +{ +} // interface ArrayDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefHelper.java new file mode 100644 index 000000000..5498b9688 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ArrayDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ArrayDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ArrayDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ArrayDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ArrayDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ArrayDefHelper.id (), "ArrayDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ArrayDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ArrayDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ArrayDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ArrayDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ArrayDef) + return (org.omg.CORBA.ArrayDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ArrayDefStub stub = new org.omg.CORBA._ArrayDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ArrayDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ArrayDef) + return (org.omg.CORBA.ArrayDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ArrayDefStub stub = new org.omg.CORBA._ArrayDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefHolder.java new file mode 100644 index 000000000..03c25f28e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ArrayDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ArrayDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ArrayDef value = null; + + public ArrayDefHolder () + { + } + + public ArrayDefHolder (org.omg.CORBA.ArrayDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ArrayDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ArrayDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ArrayDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefOperations.java new file mode 100644 index 000000000..ff28ac21f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ArrayDefOperations.java @@ -0,0 +1,18 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ArrayDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ArrayDefOperations extends org.omg.CORBA.IDLTypeOperations +{ + int length (); + void length (int newLength); + org.omg.CORBA.TypeCode element_type (); + org.omg.CORBA.IDLType element_type_def (); + void element_type_def (org.omg.CORBA.IDLType newElement_type_def); +} // interface ArrayDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttrDescriptionSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttrDescriptionSeqHelper.java new file mode 100644 index 000000000..f917e0cce --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttrDescriptionSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttrDescriptionSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class AttrDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttrDescriptionSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.AttributeDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.AttributeDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.AttributeDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.AttrDescriptionSeqHelper.id (), "AttrDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.AttributeDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.AttributeDescription value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.AttributeDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.AttributeDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.AttributeDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.AttributeDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttrDescriptionSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttrDescriptionSeqHolder.java new file mode 100644 index 000000000..3e66fbd2e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttrDescriptionSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttrDescriptionSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class AttrDescriptionSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.AttributeDescription value[] = null; + + public AttrDescriptionSeqHolder () + { + } + + public AttrDescriptionSeqHolder (org.omg.CORBA.AttributeDescription[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.AttrDescriptionSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.AttrDescriptionSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.AttrDescriptionSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDef.java new file mode 100644 index 000000000..3b8afbd32 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface AttributeDef extends AttributeDefOperations, org.omg.CORBA.Contained, org.omg.CORBA.portable.IDLEntity +{ +} // interface AttributeDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefHelper.java new file mode 100644 index 000000000..ecd4ac491 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class AttributeDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttributeDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.AttributeDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.AttributeDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.AttributeDefHelper.id (), "AttributeDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.AttributeDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_AttributeDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.AttributeDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.AttributeDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.AttributeDef) + return (org.omg.CORBA.AttributeDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._AttributeDefStub stub = new org.omg.CORBA._AttributeDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.AttributeDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.AttributeDef) + return (org.omg.CORBA.AttributeDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._AttributeDefStub stub = new org.omg.CORBA._AttributeDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefHolder.java new file mode 100644 index 000000000..dac88c846 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/AttributeDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class AttributeDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.AttributeDef value = null; + + public AttributeDefHolder () + { + } + + public AttributeDefHolder (org.omg.CORBA.AttributeDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.AttributeDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.AttributeDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.AttributeDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefOperations.java new file mode 100644 index 000000000..f095497aa --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDefOperations.java @@ -0,0 +1,18 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface AttributeDefOperations extends org.omg.CORBA.ContainedOperations +{ + org.omg.CORBA.TypeCode type (); + org.omg.CORBA.IDLType type_def (); + void type_def (org.omg.CORBA.IDLType newType_def); + org.omg.CORBA.AttributeMode mode (); + void mode (org.omg.CORBA.AttributeMode newMode); +} // interface AttributeDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescription.java new file mode 100644 index 000000000..aea725195 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescription.java @@ -0,0 +1,34 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class AttributeDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + public org.omg.CORBA.AttributeMode mode = null; + + public AttributeDescription () + { + } // ctor + + public AttributeDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type, org.omg.CORBA.AttributeMode _mode) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + mode = _mode; + } // ctor + +} // class AttributeDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescriptionHelper.java new file mode 100644 index 000000000..d562c75ab --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescriptionHelper.java @@ -0,0 +1,114 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class AttributeDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttributeDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.AttributeDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.AttributeDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [6]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.AttributeModeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "mode", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.AttributeDescriptionHelper.id (), "AttributeDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.AttributeDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.AttributeDescription value = new org.omg.CORBA.AttributeDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + value.mode = org.omg.CORBA.AttributeModeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.AttributeDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + org.omg.CORBA.AttributeModeHelper.write (ostream, value.mode); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescriptionHolder.java new file mode 100644 index 000000000..90405a652 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/AttributeDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class AttributeDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.AttributeDescription value = null; + + public AttributeDescriptionHolder () + { + } + + public AttributeDescriptionHolder (org.omg.CORBA.AttributeDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.AttributeDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.AttributeDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.AttributeDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeMode.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeMode.java new file mode 100644 index 000000000..12c1e598e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeMode.java @@ -0,0 +1,40 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeMode.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class AttributeMode implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 2; + private static org.omg.CORBA.AttributeMode[] __array = new org.omg.CORBA.AttributeMode [__size]; + + public static final int _ATTR_NORMAL = 0; + public static final org.omg.CORBA.AttributeMode ATTR_NORMAL = new org.omg.CORBA.AttributeMode(_ATTR_NORMAL); + public static final int _ATTR_READONLY = 1; + public static final org.omg.CORBA.AttributeMode ATTR_READONLY = new org.omg.CORBA.AttributeMode(_ATTR_READONLY); + + public int value () + { + return __value; + } + + public static org.omg.CORBA.AttributeMode from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected AttributeMode (int value) + { + __value = value; + __array[__value] = this; + } +} // class AttributeMode diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeModeHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeModeHelper.java new file mode 100644 index 000000000..ca3a6d547 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeModeHelper.java @@ -0,0 +1,53 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/AttributeModeHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class AttributeModeHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttributeMode:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.AttributeMode that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.AttributeMode extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.AttributeModeHelper.id (), "AttributeMode", new String[] { "ATTR_NORMAL", "ATTR_READONLY"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.AttributeMode read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.AttributeMode.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.AttributeMode value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/AttributeModeHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeModeHolder.java new file mode 100644 index 000000000..772a2123e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/AttributeModeHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/AttributeModeHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class AttributeModeHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.AttributeMode value = null; + + public AttributeModeHolder () + { + } + + public AttributeModeHolder (org.omg.CORBA.AttributeMode initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.AttributeModeHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.AttributeModeHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.AttributeModeHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDef.java new file mode 100644 index 000000000..4f1fa1700 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ConstantDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ConstantDef extends ConstantDefOperations, org.omg.CORBA.Contained, org.omg.CORBA.portable.IDLEntity +{ +} // interface ConstantDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefHelper.java new file mode 100644 index 000000000..0eac6ac78 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ConstantDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ConstantDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ConstantDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ConstantDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ConstantDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ConstantDefHelper.id (), "ConstantDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ConstantDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ConstantDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ConstantDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ConstantDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ConstantDef) + return (org.omg.CORBA.ConstantDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ConstantDefStub stub = new org.omg.CORBA._ConstantDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ConstantDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ConstantDef) + return (org.omg.CORBA.ConstantDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ConstantDefStub stub = new org.omg.CORBA._ConstantDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefHolder.java new file mode 100644 index 000000000..0b6f62a46 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ConstantDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ConstantDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ConstantDef value = null; + + public ConstantDefHolder () + { + } + + public ConstantDefHolder (org.omg.CORBA.ConstantDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ConstantDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ConstantDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ConstantDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefOperations.java new file mode 100644 index 000000000..f6dd43aad --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDefOperations.java @@ -0,0 +1,18 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ConstantDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ConstantDefOperations extends org.omg.CORBA.ContainedOperations +{ + org.omg.CORBA.TypeCode type (); + org.omg.CORBA.IDLType type_def (); + void type_def (org.omg.CORBA.IDLType newType_def); + org.omg.CORBA.Any value (); + void value (org.omg.CORBA.Any newValue); +} // interface ConstantDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescription.java new file mode 100644 index 000000000..7d37f8d80 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescription.java @@ -0,0 +1,34 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ConstantDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ConstantDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + public org.omg.CORBA.Any value = null; + + public ConstantDescription () + { + } // ctor + + public ConstantDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type, org.omg.CORBA.Any _value) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + value = _value; + } // ctor + +} // class ConstantDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescriptionHelper.java new file mode 100644 index 000000000..c77059366 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescriptionHelper.java @@ -0,0 +1,114 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ConstantDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ConstantDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ConstantDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ConstantDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ConstantDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [6]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[5] = new org.omg.CORBA.StructMember ( + "value", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ConstantDescriptionHelper.id (), "ConstantDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ConstantDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ConstantDescription value = new org.omg.CORBA.ConstantDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + value.value = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ConstantDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + ostream.write_any (value.value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescriptionHolder.java new file mode 100644 index 000000000..474a12016 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ConstantDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ConstantDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ConstantDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ConstantDescription value = null; + + public ConstantDescriptionHolder () + { + } + + public ConstantDescriptionHolder (org.omg.CORBA.ConstantDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ConstantDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ConstantDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ConstantDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/Contained.java b/idlj/src/test/masters/ir/org/omg/CORBA/Contained.java new file mode 100644 index 000000000..85fd9ad93 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/Contained.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/Contained.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface Contained extends ContainedOperations, org.omg.CORBA.IRObject, org.omg.CORBA.portable.IDLEntity +{ +} // interface Contained diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedHelper.java new file mode 100644 index 000000000..27b185ace --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContainedHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class ContainedHelper +{ + private static String _id = "IDL:omg.org/CORBA/Contained:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Contained that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Contained extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ContainedHelper.id (), "Contained"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Contained read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ContainedStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Contained value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.Contained narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Contained) + return (org.omg.CORBA.Contained)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ContainedStub stub = new org.omg.CORBA._ContainedStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.Contained unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Contained) + return (org.omg.CORBA.Contained)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ContainedStub stub = new org.omg.CORBA._ContainedStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedHolder.java new file mode 100644 index 000000000..9eea8622a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ContainedHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class ContainedHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Contained value = null; + + public ContainedHolder () + { + } + + public ContainedHolder (org.omg.CORBA.Contained initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContainedHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContainedHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContainedHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedOperations.java new file mode 100644 index 000000000..acbd55e07 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedOperations.java @@ -0,0 +1,32 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContainedOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface ContainedOperations extends org.omg.CORBA.IRObjectOperations +{ + + // read/write interface + String id (); + + // read/write interface + void id (String newId); + String name (); + void name (String newName); + String version (); + void version (String newVersion); + + // read interface + org.omg.CORBA.Container defined_in (); + String absolute_name (); + org.omg.CORBA.Repository containing_repository (); + org.omg.CORBA.ContainedPackage.Description describe (); + + // write interface + void move (org.omg.CORBA.Container new_container, String new_name, String new_version); +} // interface ContainedOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/Description.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/Description.java new file mode 100644 index 000000000..bcdb4593a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/Description.java @@ -0,0 +1,26 @@ +package org.omg.CORBA.ContainedPackage; + + +/** +* org/omg/CORBA/ContainedPackage/Description.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class Description implements org.omg.CORBA.portable.IDLEntity +{ + public org.omg.CORBA.DefinitionKind kind = null; + public org.omg.CORBA.Any value = null; + + public Description () + { + } // ctor + + public Description (org.omg.CORBA.DefinitionKind _kind, org.omg.CORBA.Any _value) + { + kind = _kind; + value = _value; + } // ctor + +} // class Description diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/DescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/DescriptionHelper.java new file mode 100644 index 000000000..ebdce84bd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/DescriptionHelper.java @@ -0,0 +1,82 @@ +package org.omg.CORBA.ContainedPackage; + + +/** +* org/omg/CORBA/ContainedPackage/DescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class DescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/Contained/Description:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ContainedPackage.Description that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ContainedPackage.Description extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.DefinitionKindHelper.type (); + _members0[0] = new org.omg.CORBA.StructMember ( + "kind", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[1] = new org.omg.CORBA.StructMember ( + "value", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ContainedPackage.DescriptionHelper.id (), "Description", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ContainedPackage.Description read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ContainedPackage.Description value = new org.omg.CORBA.ContainedPackage.Description (); + value.kind = org.omg.CORBA.DefinitionKindHelper.read (istream); + value.value = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ContainedPackage.Description value) + { + org.omg.CORBA.DefinitionKindHelper.write (ostream, value.kind); + ostream.write_any (value.value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/DescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/DescriptionHolder.java new file mode 100644 index 000000000..444907088 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedPackage/DescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA.ContainedPackage; + +/** +* org/omg/CORBA/ContainedPackage/DescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class DescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ContainedPackage.Description value = null; + + public DescriptionHolder () + { + } + + public DescriptionHolder (org.omg.CORBA.ContainedPackage.Description initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContainedPackage.DescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContainedPackage.DescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContainedPackage.DescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedSeqHelper.java new file mode 100644 index 000000000..78aeb48cb --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContainedSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class ContainedSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ContainedSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Contained[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Contained[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ContainedHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContainedSeqHelper.id (), "ContainedSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Contained[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.Contained value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.Contained[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ContainedHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Contained[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ContainedHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainedSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedSeqHolder.java new file mode 100644 index 000000000..93685fa68 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainedSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContainedSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class ContainedSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Contained value[] = null; + + public ContainedSeqHolder () + { + } + + public ContainedSeqHolder (org.omg.CORBA.Contained[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContainedSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContainedSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContainedSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/Container.java b/idlj/src/test/masters/ir/org/omg/CORBA/Container.java new file mode 100644 index 000000000..9ee42fdcc --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/Container.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/Container.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public interface Container extends ContainerOperations, org.omg.CORBA.IRObject, org.omg.CORBA.portable.IDLEntity +{ +} // interface Container diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerHelper.java new file mode 100644 index 000000000..90089258c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerHelper.java @@ -0,0 +1,87 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContainerHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +abstract public class ContainerHelper +{ + private static String _id = "IDL:omg.org/CORBA/Container:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Container that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Container extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ContainerHelper.id (), "Container"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Container read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ContainerStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Container value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.Container narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Container) + return (org.omg.CORBA.Container)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ContainerStub stub = new org.omg.CORBA._ContainerStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.Container unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Container) + return (org.omg.CORBA.Container)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ContainerStub stub = new org.omg.CORBA._ContainerStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerHolder.java new file mode 100644 index 000000000..ac82c5e7f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerHolder.java @@ -0,0 +1,40 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ContainerHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public final class ContainerHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Container value = null; + + public ContainerHolder () + { + } + + public ContainerHolder (org.omg.CORBA.Container initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContainerHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContainerHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContainerHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerOperations.java new file mode 100644 index 000000000..28567da8b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerOperations.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContainerOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public interface ContainerOperations extends org.omg.CORBA.IRObjectOperations +{ + + // read interface + org.omg.CORBA.Contained lookup (String search_name); + org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited); + org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited); + org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs); + + // write interface + org.omg.CORBA.ModuleDef create_module (String id, String name, String version); + org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value); + org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members); + org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members); + org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members); + org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type); + org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members); + org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces); + + // orbos 98-01-18: Objects By Value + org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers); + + // orbos 98-01-18: Objects By Value + org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def); + org.omg.CORBA.NativeDef create_native (String id, String name, String version); +} // interface ContainerOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/Description.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/Description.java new file mode 100644 index 000000000..d2727799d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/Description.java @@ -0,0 +1,28 @@ +package org.omg.CORBA.ContainerPackage; + + +/** +* org/omg/CORBA/ContainerPackage/Description.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class Description implements org.omg.CORBA.portable.IDLEntity +{ + public org.omg.CORBA.Contained contained_object = null; + public org.omg.CORBA.DefinitionKind kind = null; + public org.omg.CORBA.Any value = null; + + public Description () + { + } // ctor + + public Description (org.omg.CORBA.Contained _contained_object, org.omg.CORBA.DefinitionKind _kind, org.omg.CORBA.Any _value) + { + contained_object = _contained_object; + kind = _kind; + value = _value; + } // ctor + +} // class Description diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionHelper.java new file mode 100644 index 000000000..af1615bd8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionHelper.java @@ -0,0 +1,89 @@ +package org.omg.CORBA.ContainerPackage; + + +/** +* org/omg/CORBA/ContainerPackage/DescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class DescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/Container/Description:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ContainerPackage.Description that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ContainerPackage.Description extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [3]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ContainedHelper.type (); + _members0[0] = new org.omg.CORBA.StructMember ( + "contained_object", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.DefinitionKindHelper.type (); + _members0[1] = new org.omg.CORBA.StructMember ( + "kind", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[2] = new org.omg.CORBA.StructMember ( + "value", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ContainerPackage.DescriptionHelper.id (), "Description", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ContainerPackage.Description read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ContainerPackage.Description value = new org.omg.CORBA.ContainerPackage.Description (); + value.contained_object = org.omg.CORBA.ContainedHelper.read (istream); + value.kind = org.omg.CORBA.DefinitionKindHelper.read (istream); + value.value = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ContainerPackage.Description value) + { + org.omg.CORBA.ContainedHelper.write (ostream, value.contained_object); + org.omg.CORBA.DefinitionKindHelper.write (ostream, value.kind); + ostream.write_any (value.value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionHolder.java new file mode 100644 index 000000000..8d89eb16b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA.ContainerPackage; + +/** +* org/omg/CORBA/ContainerPackage/DescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class DescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ContainerPackage.Description value = null; + + public DescriptionHolder () + { + } + + public DescriptionHolder (org.omg.CORBA.ContainerPackage.Description initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContainerPackage.DescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContainerPackage.DescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContainerPackage.DescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionSeqHelper.java new file mode 100644 index 000000000..84ff175c6 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA.ContainerPackage; + + +/** +* org/omg/CORBA/ContainerPackage/DescriptionSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class DescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/Container/DescriptionSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ContainerPackage.Description[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ContainerPackage.Description[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ContainerPackage.DescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.id (), "DescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ContainerPackage.Description[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ContainerPackage.Description value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.ContainerPackage.Description[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ContainerPackage.DescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ContainerPackage.Description[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ContainerPackage.DescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionSeqHolder.java new file mode 100644 index 000000000..7b988718a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContainerPackage/DescriptionSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA.ContainerPackage; + + +/** +* org/omg/CORBA/ContainerPackage/DescriptionSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class DescriptionSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ContainerPackage.Description value[] = null; + + public DescriptionSeqHolder () + { + } + + public DescriptionSeqHolder (org.omg.CORBA.ContainerPackage.Description[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdSeqHelper.java new file mode 100644 index 000000000..cb505f97b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdSeqHelper.java @@ -0,0 +1,64 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContextIdSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ContextIdSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ContextIdSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, String[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContextIdentifierHelper.id (), "ContextIdentifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContextIdSeqHelper.id (), "ContextIdSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[] read (org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long (); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ContextIdentifierHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ContextIdentifierHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdSeqHolder.java new file mode 100644 index 000000000..9a0c18349 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContextIdSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ContextIdSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public String value[] = null; + + public ContextIdSeqHolder () + { + } + + public ContextIdSeqHolder (String[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ContextIdSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ContextIdSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ContextIdSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdentifierHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdentifierHelper.java new file mode 100644 index 000000000..b56939ead --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ContextIdentifierHelper.java @@ -0,0 +1,57 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ContextIdentifierHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ContextIdentifierHelper +{ + private static String _id = "IDL:omg.org/CORBA/ContextIdentifier:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContextIdentifierHelper.id (), "ContextIdentifier", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKind.java b/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKind.java new file mode 100644 index 000000000..101e41986 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKind.java @@ -0,0 +1,84 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/DefinitionKind.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public class DefinitionKind implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 24; + private static org.omg.CORBA.DefinitionKind[] __array = new org.omg.CORBA.DefinitionKind [__size]; + + public static final int _dk_none = 0; + public static final org.omg.CORBA.DefinitionKind dk_none = new org.omg.CORBA.DefinitionKind(_dk_none); + public static final int _dk_all = 1; + public static final org.omg.CORBA.DefinitionKind dk_all = new org.omg.CORBA.DefinitionKind(_dk_all); + public static final int _dk_Attribute = 2; + public static final org.omg.CORBA.DefinitionKind dk_Attribute = new org.omg.CORBA.DefinitionKind(_dk_Attribute); + public static final int _dk_Constant = 3; + public static final org.omg.CORBA.DefinitionKind dk_Constant = new org.omg.CORBA.DefinitionKind(_dk_Constant); + public static final int _dk_Exception = 4; + public static final org.omg.CORBA.DefinitionKind dk_Exception = new org.omg.CORBA.DefinitionKind(_dk_Exception); + public static final int _dk_Interface = 5; + public static final org.omg.CORBA.DefinitionKind dk_Interface = new org.omg.CORBA.DefinitionKind(_dk_Interface); + public static final int _dk_Module = 6; + public static final org.omg.CORBA.DefinitionKind dk_Module = new org.omg.CORBA.DefinitionKind(_dk_Module); + public static final int _dk_Operation = 7; + public static final org.omg.CORBA.DefinitionKind dk_Operation = new org.omg.CORBA.DefinitionKind(_dk_Operation); + public static final int _dk_Typedef = 8; + public static final org.omg.CORBA.DefinitionKind dk_Typedef = new org.omg.CORBA.DefinitionKind(_dk_Typedef); + public static final int _dk_Alias = 9; + public static final org.omg.CORBA.DefinitionKind dk_Alias = new org.omg.CORBA.DefinitionKind(_dk_Alias); + public static final int _dk_Struct = 10; + public static final org.omg.CORBA.DefinitionKind dk_Struct = new org.omg.CORBA.DefinitionKind(_dk_Struct); + public static final int _dk_Union = 11; + public static final org.omg.CORBA.DefinitionKind dk_Union = new org.omg.CORBA.DefinitionKind(_dk_Union); + public static final int _dk_Enum = 12; + public static final org.omg.CORBA.DefinitionKind dk_Enum = new org.omg.CORBA.DefinitionKind(_dk_Enum); + public static final int _dk_Primitive = 13; + public static final org.omg.CORBA.DefinitionKind dk_Primitive = new org.omg.CORBA.DefinitionKind(_dk_Primitive); + public static final int _dk_String = 14; + public static final org.omg.CORBA.DefinitionKind dk_String = new org.omg.CORBA.DefinitionKind(_dk_String); + public static final int _dk_Sequence = 15; + public static final org.omg.CORBA.DefinitionKind dk_Sequence = new org.omg.CORBA.DefinitionKind(_dk_Sequence); + public static final int _dk_Array = 16; + public static final org.omg.CORBA.DefinitionKind dk_Array = new org.omg.CORBA.DefinitionKind(_dk_Array); + public static final int _dk_Repository = 17; + public static final org.omg.CORBA.DefinitionKind dk_Repository = new org.omg.CORBA.DefinitionKind(_dk_Repository); + public static final int _dk_Wstring = 18; + public static final org.omg.CORBA.DefinitionKind dk_Wstring = new org.omg.CORBA.DefinitionKind(_dk_Wstring); + public static final int _dk_Fixed = 19; + public static final org.omg.CORBA.DefinitionKind dk_Fixed = new org.omg.CORBA.DefinitionKind(_dk_Fixed); + public static final int _dk_Value = 20; + public static final org.omg.CORBA.DefinitionKind dk_Value = new org.omg.CORBA.DefinitionKind(_dk_Value); + public static final int _dk_ValueBox = 21; + public static final org.omg.CORBA.DefinitionKind dk_ValueBox = new org.omg.CORBA.DefinitionKind(_dk_ValueBox); + public static final int _dk_ValueMember = 22; + public static final org.omg.CORBA.DefinitionKind dk_ValueMember = new org.omg.CORBA.DefinitionKind(_dk_ValueMember); + public static final int _dk_Native = 23; + public static final org.omg.CORBA.DefinitionKind dk_Native = new org.omg.CORBA.DefinitionKind(_dk_Native); + + public int value () + { + return __value; + } + + public static org.omg.CORBA.DefinitionKind from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected DefinitionKind (int value) + { + __value = value; + __array[__value] = this; + } +} // class DefinitionKind diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKindHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKindHelper.java new file mode 100644 index 000000000..1b86e1e4b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKindHelper.java @@ -0,0 +1,53 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/DefinitionKindHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class DefinitionKindHelper +{ + private static String _id = "IDL:omg.org/CORBA/DefinitionKind:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.DefinitionKind that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.DefinitionKind extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.DefinitionKindHelper.id (), "DefinitionKind", new String[] { "dk_none", "dk_all", "dk_Attribute", "dk_Constant", "dk_Exception", "dk_Interface", "dk_Module", "dk_Operation", "dk_Typedef", "dk_Alias", "dk_Struct", "dk_Union", "dk_Enum", "dk_Primitive", "dk_String", "dk_Sequence", "dk_Array", "dk_Repository", "dk_Wstring", "dk_Fixed", "dk_Value", "dk_ValueBox", "dk_ValueMember", "dk_Native"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.DefinitionKind read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.DefinitionKind.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.DefinitionKind value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKindHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKindHolder.java new file mode 100644 index 000000000..8b90df524 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/DefinitionKindHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/DefinitionKindHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class DefinitionKindHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.DefinitionKind value = null; + + public DefinitionKindHolder () + { + } + + public DefinitionKindHolder (org.omg.CORBA.DefinitionKind initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.DefinitionKindHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.DefinitionKindHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.DefinitionKindHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/EnumDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDef.java new file mode 100644 index 000000000..02cf7c920 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/EnumDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface EnumDef extends EnumDefOperations, org.omg.CORBA.TypedefDef, org.omg.CORBA.portable.IDLEntity +{ +} // interface EnumDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefHelper.java new file mode 100644 index 000000000..4c9b71ee3 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/EnumDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class EnumDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/EnumDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.EnumDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.EnumDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.EnumDefHelper.id (), "EnumDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.EnumDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_EnumDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.EnumDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.EnumDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.EnumDef) + return (org.omg.CORBA.EnumDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._EnumDefStub stub = new org.omg.CORBA._EnumDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.EnumDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.EnumDef) + return (org.omg.CORBA.EnumDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._EnumDefStub stub = new org.omg.CORBA._EnumDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefHolder.java new file mode 100644 index 000000000..53e387977 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/EnumDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class EnumDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.EnumDef value = null; + + public EnumDefHolder () + { + } + + public EnumDefHolder (org.omg.CORBA.EnumDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.EnumDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.EnumDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.EnumDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefOperations.java new file mode 100644 index 000000000..06efe14a9 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/EnumDefOperations.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/EnumDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface EnumDefOperations extends org.omg.CORBA.TypedefDefOperations +{ + String[] members (); + void members (String[] newMembers); +} // interface EnumDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/EnumMemberSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/EnumMemberSeqHelper.java new file mode 100644 index 000000000..396560144 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/EnumMemberSeqHelper.java @@ -0,0 +1,63 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/EnumMemberSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class EnumMemberSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/EnumMemberSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, String[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.EnumMemberSeqHelper.id (), "EnumMemberSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[] read (org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long (); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.IdentifierHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.IdentifierHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/EnumMemberSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/EnumMemberSeqHolder.java new file mode 100644 index 000000000..1a50c69d6 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/EnumMemberSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/EnumMemberSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class EnumMemberSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public String value[] = null; + + public EnumMemberSeqHolder () + { + } + + public EnumMemberSeqHolder (String[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.EnumMemberSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.EnumMemberSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.EnumMemberSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExcDescriptionSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExcDescriptionSeqHelper.java new file mode 100644 index 000000000..306cbd011 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExcDescriptionSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExcDescriptionSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ExcDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ExcDescriptionSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ExceptionDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ExceptionDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ExceptionDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ExcDescriptionSeqHelper.id (), "ExcDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ExceptionDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ExceptionDescription value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.ExceptionDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ExceptionDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ExceptionDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ExceptionDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExcDescriptionSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExcDescriptionSeqHolder.java new file mode 100644 index 000000000..6a384db5d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExcDescriptionSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExcDescriptionSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ExcDescriptionSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ExceptionDescription value[] = null; + + public ExcDescriptionSeqHolder () + { + } + + public ExcDescriptionSeqHolder (org.omg.CORBA.ExceptionDescription[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ExcDescriptionSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ExcDescriptionSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ExcDescriptionSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDef.java new file mode 100644 index 000000000..f2e1d748d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ExceptionDef extends ExceptionDefOperations, org.omg.CORBA.Contained, org.omg.CORBA.Container +{ +} // interface ExceptionDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefHelper.java new file mode 100644 index 000000000..de8129b6a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ExceptionDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ExceptionDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ExceptionDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ExceptionDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ExceptionDefHelper.id (), "ExceptionDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ExceptionDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ExceptionDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ExceptionDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ExceptionDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ExceptionDef) + return (org.omg.CORBA.ExceptionDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ExceptionDefStub stub = new org.omg.CORBA._ExceptionDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ExceptionDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ExceptionDef) + return (org.omg.CORBA.ExceptionDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ExceptionDefStub stub = new org.omg.CORBA._ExceptionDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefHolder.java new file mode 100644 index 000000000..11e25410c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ExceptionDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ExceptionDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ExceptionDef value = null; + + public ExceptionDefHolder () + { + } + + public ExceptionDefHolder (org.omg.CORBA.ExceptionDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ExceptionDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ExceptionDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ExceptionDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefOperations.java new file mode 100644 index 000000000..51c73a309 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefOperations.java @@ -0,0 +1,16 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ExceptionDefOperations extends org.omg.CORBA.ContainedOperations, org.omg.CORBA.ContainerOperations +{ + org.omg.CORBA.TypeCode type (); + org.omg.CORBA.StructMember[] members (); + void members (org.omg.CORBA.StructMember[] newMembers); +} // interface ExceptionDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefSeqHelper.java new file mode 100644 index 000000000..fd7196053 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDefSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ExceptionDefSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ExceptionDefSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ExceptionDef[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ExceptionDef[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ExceptionDefHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ExceptionDefSeqHelper.id (), "ExceptionDefSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ExceptionDef[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ExceptionDef value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.ExceptionDef[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ExceptionDefHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ExceptionDef[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ExceptionDefHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefSeqHolder.java new file mode 100644 index 000000000..9fb154ed2 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDefSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDefSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ExceptionDefSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ExceptionDef value[] = null; + + public ExceptionDefSeqHolder () + { + } + + public ExceptionDefSeqHolder (org.omg.CORBA.ExceptionDef[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ExceptionDefSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ExceptionDefSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ExceptionDefSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescription.java new file mode 100644 index 000000000..f0986d50e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescription.java @@ -0,0 +1,32 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ExceptionDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + + public ExceptionDescription () + { + } // ctor + + public ExceptionDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + } // ctor + +} // class ExceptionDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescriptionHelper.java new file mode 100644 index 000000000..fb6a7921c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescriptionHelper.java @@ -0,0 +1,107 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ExceptionDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ExceptionDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ExceptionDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ExceptionDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ExceptionDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [5]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ExceptionDescriptionHelper.id (), "ExceptionDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ExceptionDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ExceptionDescription value = new org.omg.CORBA.ExceptionDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ExceptionDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescriptionHolder.java new file mode 100644 index 000000000..795e84f2a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ExceptionDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ExceptionDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ExceptionDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ExceptionDescription value = null; + + public ExceptionDescriptionHolder () + { + } + + public ExceptionDescriptionHolder (org.omg.CORBA.ExceptionDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ExceptionDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ExceptionDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ExceptionDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IDLType.java b/idlj/src/test/masters/ir/org/omg/CORBA/IDLType.java new file mode 100644 index 000000000..33fb3704e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IDLType.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IDLType.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface IDLType extends IDLTypeOperations, org.omg.CORBA.IRObject, org.omg.CORBA.portable.IDLEntity +{ +} // interface IDLType diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeHelper.java new file mode 100644 index 000000000..acba14fbc --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IDLTypeHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class IDLTypeHelper +{ + private static String _id = "IDL:omg.org/CORBA/IDLType:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.IDLType that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.IDLType extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.IDLTypeHelper.id (), "IDLType"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.IDLType read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_IDLTypeStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.IDLType value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.IDLType narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.IDLType) + return (org.omg.CORBA.IDLType)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._IDLTypeStub stub = new org.omg.CORBA._IDLTypeStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.IDLType unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.IDLType) + return (org.omg.CORBA.IDLType)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._IDLTypeStub stub = new org.omg.CORBA._IDLTypeStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeHolder.java new file mode 100644 index 000000000..653afc4a5 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/IDLTypeHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class IDLTypeHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.IDLType value = null; + + public IDLTypeHolder () + { + } + + public IDLTypeHolder (org.omg.CORBA.IDLType initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.IDLTypeHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.IDLTypeHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.IDLTypeHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeOperations.java new file mode 100644 index 000000000..c0328672e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IDLTypeOperations.java @@ -0,0 +1,14 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IDLTypeOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface IDLTypeOperations extends org.omg.CORBA.IRObjectOperations +{ + org.omg.CORBA.TypeCode type (); +} // interface IDLTypeOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IRObject.java b/idlj/src/test/masters/ir/org/omg/CORBA/IRObject.java new file mode 100644 index 000000000..948a5b984 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IRObject.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IRObject.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface IRObject extends IRObjectOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} // interface IRObject diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectHelper.java new file mode 100644 index 000000000..e1368a591 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IRObjectHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class IRObjectHelper +{ + private static String _id = "IDL:omg.org/CORBA/IRObject:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.IRObject that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.IRObject extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.IRObjectHelper.id (), "IRObject"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.IRObject read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_IRObjectStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.IRObject value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.IRObject narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.IRObject) + return (org.omg.CORBA.IRObject)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._IRObjectStub stub = new org.omg.CORBA._IRObjectStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.IRObject unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.IRObject) + return (org.omg.CORBA.IRObject)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._IRObjectStub stub = new org.omg.CORBA._IRObjectStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectHolder.java new file mode 100644 index 000000000..6bd4e7659 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/IRObjectHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class IRObjectHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.IRObject value = null; + + public IRObjectHolder () + { + } + + public IRObjectHolder (org.omg.CORBA.IRObject initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.IRObjectHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.IRObjectHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.IRObjectHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectOperations.java new file mode 100644 index 000000000..59023bd1a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IRObjectOperations.java @@ -0,0 +1,19 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IRObjectOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface IRObjectOperations +{ + + // read interface + org.omg.CORBA.DefinitionKind def_kind (); + + // write interface + void destroy (); +} // interface IRObjectOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/IdentifierHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/IdentifierHelper.java new file mode 100644 index 000000000..aac819365 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/IdentifierHelper.java @@ -0,0 +1,56 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/IdentifierHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class IdentifierHelper +{ + private static String _id = "IDL:omg.org/CORBA/Identifier:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/Initializer.java b/idlj/src/test/masters/ir/org/omg/CORBA/Initializer.java new file mode 100644 index 000000000..5b959f453 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/Initializer.java @@ -0,0 +1,24 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/Initializer.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class Initializer implements org.omg.CORBA.portable.IDLEntity +{ + public org.omg.CORBA.StructMember members[] = null; + + public Initializer () + { + } // ctor + + public Initializer (org.omg.CORBA.StructMember[] _members) + { + members = _members; + } // ctor + +} // class Initializer diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InitializerHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerHelper.java new file mode 100644 index 000000000..542dfedc4 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerHelper.java @@ -0,0 +1,77 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InitializerHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class InitializerHelper +{ + private static String _id = "IDL:omg.org/CORBA/Initializer:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Initializer that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Initializer extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [1]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.StructMemberHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.StructMemberSeqHelper.id (), "StructMemberSeq", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "members", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.InitializerHelper.id (), "Initializer", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Initializer read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.Initializer value = new org.omg.CORBA.Initializer (); + value.members = org.omg.CORBA.StructMemberSeqHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Initializer value) + { + org.omg.CORBA.StructMemberSeqHelper.write (ostream, value.members); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InitializerHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerHolder.java new file mode 100644 index 000000000..bc9bbfc8e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/InitializerHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class InitializerHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Initializer value = null; + + public InitializerHolder () + { + } + + public InitializerHolder (org.omg.CORBA.Initializer initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.InitializerHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.InitializerHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.InitializerHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InitializerSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerSeqHelper.java new file mode 100644 index 000000000..4b7986377 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InitializerSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class InitializerSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/InitializerSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Initializer[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Initializer[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.InitializerHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.InitializerSeqHelper.id (), "InitializerSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Initializer[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.Initializer value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.Initializer[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.InitializerHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Initializer[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.InitializerHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InitializerSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerSeqHolder.java new file mode 100644 index 000000000..59f4e5b61 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InitializerSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InitializerSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class InitializerSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Initializer value[] = null; + + public InitializerSeqHolder () + { + } + + public InitializerSeqHolder (org.omg.CORBA.Initializer[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.InitializerSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.InitializerSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.InitializerSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDef.java new file mode 100644 index 000000000..78ea7fe2a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface InterfaceDef extends InterfaceDefOperations, org.omg.CORBA.Container, org.omg.CORBA.Contained, org.omg.CORBA.IDLType +{ +} // interface InterfaceDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefHelper.java new file mode 100644 index 000000000..53b8e925d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class InterfaceDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/InterfaceDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.InterfaceDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.InterfaceDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.InterfaceDefHelper.id (), "InterfaceDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.InterfaceDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_InterfaceDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.InterfaceDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.InterfaceDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.InterfaceDef) + return (org.omg.CORBA.InterfaceDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._InterfaceDefStub stub = new org.omg.CORBA._InterfaceDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.InterfaceDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.InterfaceDef) + return (org.omg.CORBA.InterfaceDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._InterfaceDefStub stub = new org.omg.CORBA._InterfaceDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefHolder.java new file mode 100644 index 000000000..bb9346de1 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/InterfaceDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class InterfaceDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.InterfaceDef value = null; + + public InterfaceDefHolder () + { + } + + public InterfaceDefHolder (org.omg.CORBA.InterfaceDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.InterfaceDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.InterfaceDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.InterfaceDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefOperations.java new file mode 100644 index 000000000..2eb046759 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefOperations.java @@ -0,0 +1,29 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface InterfaceDefOperations extends org.omg.CORBA.ContainerOperations, org.omg.CORBA.ContainedOperations, org.omg.CORBA.IDLTypeOperations +{ + + // read/write interface + org.omg.CORBA.InterfaceDef[] base_interfaces (); + + // read/write interface + void base_interfaces (org.omg.CORBA.InterfaceDef[] newBase_interfaces); + boolean is_abstract (); + void is_abstract (boolean newIs_abstract); + + // read interface + boolean is_a (String interface_id); + org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription describe_interface (); + + // write interface + org.omg.CORBA.AttributeDef create_attribute (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.AttributeMode mode); + org.omg.CORBA.OperationDef create_operation (String id, String name, String version, org.omg.CORBA.IDLType result, org.omg.CORBA.OperationMode mode, org.omg.CORBA.ParameterDescription[] params, org.omg.CORBA.ExceptionDef[] exceptions, String[] contexts); +} // interface InterfaceDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescription.java new file mode 100644 index 000000000..78dd44a55 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescription.java @@ -0,0 +1,40 @@ +package org.omg.CORBA.InterfaceDefPackage; + + +/** +* org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class FullInterfaceDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public boolean is_abstract = false; + public org.omg.CORBA.OperationDescription operations[] = null; + public org.omg.CORBA.AttributeDescription attributes[] = null; + public String base_interfaces[] = null; + public org.omg.CORBA.TypeCode type = null; + + public FullInterfaceDescription () + { + } // ctor + + public FullInterfaceDescription (String _name, String _id, String _defined_in, String _version, boolean _is_abstract, org.omg.CORBA.OperationDescription[] _operations, org.omg.CORBA.AttributeDescription[] _attributes, String[] _base_interfaces, org.omg.CORBA.TypeCode _type) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + is_abstract = _is_abstract; + operations = _operations; + attributes = _attributes; + base_interfaces = _base_interfaces; + type = _type; + } // ctor + +} // class FullInterfaceDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHelper.java new file mode 100644 index 000000000..7e6b94f33 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHelper.java @@ -0,0 +1,142 @@ +package org.omg.CORBA.InterfaceDefPackage; + + +/** +* org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class FullInterfaceDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/InterfaceDef/FullInterfaceDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [9]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[4] = new org.omg.CORBA.StructMember ( + "is_abstract", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.OperationDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.OpDescriptionSeqHelper.id (), "OpDescriptionSeq", _tcOf_members0); + _members0[5] = new org.omg.CORBA.StructMember ( + "operations", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.AttributeDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.AttrDescriptionSeqHelper.id (), "AttrDescriptionSeq", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "attributes", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[7] = new org.omg.CORBA.StructMember ( + "base_interfaces", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[8] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescriptionHelper.id (), "FullInterfaceDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription value = new org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.is_abstract = istream.read_boolean (); + value.operations = org.omg.CORBA.OpDescriptionSeqHelper.read (istream); + value.attributes = org.omg.CORBA.AttrDescriptionSeqHelper.read (istream); + value.base_interfaces = org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.type = istream.read_TypeCode (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_boolean (value.is_abstract); + org.omg.CORBA.OpDescriptionSeqHelper.write (ostream, value.operations); + org.omg.CORBA.AttrDescriptionSeqHelper.write (ostream, value.attributes); + org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.base_interfaces); + ostream.write_TypeCode (value.type); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHolder.java new file mode 100644 index 000000000..4522b7dbc --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA.InterfaceDefPackage; + +/** +* org/omg/CORBA/InterfaceDefPackage/FullInterfaceDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class FullInterfaceDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription value = null; + + public FullInterfaceDescriptionHolder () + { + } + + public FullInterfaceDescriptionHolder (org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefSeqHelper.java new file mode 100644 index 000000000..a1f5f8af9 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDefSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class InterfaceDefSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/InterfaceDefSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.InterfaceDef[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.InterfaceDef[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.InterfaceDefHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.InterfaceDefSeqHelper.id (), "InterfaceDefSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.InterfaceDef[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.InterfaceDef value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.InterfaceDef[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.InterfaceDefHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.InterfaceDef[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.InterfaceDefHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefSeqHolder.java new file mode 100644 index 000000000..fdc89eaf9 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDefSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDefSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class InterfaceDefSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.InterfaceDef value[] = null; + + public InterfaceDefSeqHolder () + { + } + + public InterfaceDefSeqHolder (org.omg.CORBA.InterfaceDef[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.InterfaceDefSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.InterfaceDefSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.InterfaceDefSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescription.java new file mode 100644 index 000000000..58ee6d67a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescription.java @@ -0,0 +1,32 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class InterfaceDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public String base_interfaces[] = null; + + public InterfaceDescription () + { + } // ctor + + public InterfaceDescription (String _name, String _id, String _defined_in, String _version, String[] _base_interfaces) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + base_interfaces = _base_interfaces; + } // ctor + +} // class InterfaceDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescriptionHelper.java new file mode 100644 index 000000000..2fec13d02 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescriptionHelper.java @@ -0,0 +1,110 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/InterfaceDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class InterfaceDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/InterfaceDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.InterfaceDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.InterfaceDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [5]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[4] = new org.omg.CORBA.StructMember ( + "base_interfaces", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.InterfaceDescriptionHelper.id (), "InterfaceDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.InterfaceDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.InterfaceDescription value = new org.omg.CORBA.InterfaceDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.base_interfaces = org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.InterfaceDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.base_interfaces); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescriptionHolder.java new file mode 100644 index 000000000..915fd80d9 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/InterfaceDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/InterfaceDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class InterfaceDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.InterfaceDescription value = null; + + public InterfaceDescriptionHolder () + { + } + + public InterfaceDescriptionHolder (org.omg.CORBA.InterfaceDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.InterfaceDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.InterfaceDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.InterfaceDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDef.java new file mode 100644 index 000000000..e025dc0ae --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ModuleDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ModuleDef extends ModuleDefOperations, org.omg.CORBA.Container, org.omg.CORBA.Contained +{ +} // interface ModuleDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefHelper.java new file mode 100644 index 000000000..c4febbd7a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ModuleDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ModuleDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ModuleDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ModuleDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ModuleDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ModuleDefHelper.id (), "ModuleDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ModuleDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ModuleDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ModuleDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ModuleDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ModuleDef) + return (org.omg.CORBA.ModuleDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ModuleDefStub stub = new org.omg.CORBA._ModuleDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ModuleDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ModuleDef) + return (org.omg.CORBA.ModuleDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ModuleDefStub stub = new org.omg.CORBA._ModuleDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefHolder.java new file mode 100644 index 000000000..26714fbbd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ModuleDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ModuleDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ModuleDef value = null; + + public ModuleDefHolder () + { + } + + public ModuleDefHolder (org.omg.CORBA.ModuleDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ModuleDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ModuleDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ModuleDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefOperations.java new file mode 100644 index 000000000..8f4ae0884 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDefOperations.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ModuleDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface ModuleDefOperations extends org.omg.CORBA.ContainerOperations, org.omg.CORBA.ContainedOperations +{ +} // interface ModuleDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescription.java new file mode 100644 index 000000000..a7f271a21 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescription.java @@ -0,0 +1,30 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ModuleDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ModuleDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + + public ModuleDescription () + { + } // ctor + + public ModuleDescription (String _name, String _id, String _defined_in, String _version) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + } // ctor + +} // class ModuleDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescriptionHelper.java new file mode 100644 index 000000000..4eef7a942 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescriptionHelper.java @@ -0,0 +1,100 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ModuleDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ModuleDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ModuleDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ModuleDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ModuleDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ModuleDescriptionHelper.id (), "ModuleDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ModuleDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ModuleDescription value = new org.omg.CORBA.ModuleDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ModuleDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescriptionHolder.java new file mode 100644 index 000000000..e10b78e17 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ModuleDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ModuleDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ModuleDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ModuleDescription value = null; + + public ModuleDescriptionHolder () + { + } + + public ModuleDescriptionHolder (org.omg.CORBA.ModuleDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ModuleDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ModuleDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ModuleDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/NativeDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDef.java new file mode 100644 index 000000000..51ca9800e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDef.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/NativeDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public interface NativeDef extends NativeDefOperations, org.omg.CORBA.TypedefDef, org.omg.CORBA.portable.IDLEntity +{ +} // interface NativeDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefHelper.java new file mode 100644 index 000000000..3ba415552 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefHelper.java @@ -0,0 +1,87 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/NativeDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +abstract public class NativeDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/NativeDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.NativeDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.NativeDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.NativeDefHelper.id (), "NativeDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.NativeDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_NativeDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.NativeDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.NativeDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.NativeDef) + return (org.omg.CORBA.NativeDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._NativeDefStub stub = new org.omg.CORBA._NativeDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.NativeDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.NativeDef) + return (org.omg.CORBA.NativeDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._NativeDefStub stub = new org.omg.CORBA._NativeDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefHolder.java new file mode 100644 index 000000000..d7d429519 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefHolder.java @@ -0,0 +1,40 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/NativeDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public final class NativeDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.NativeDef value = null; + + public NativeDefHolder () + { + } + + public NativeDefHolder (org.omg.CORBA.NativeDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.NativeDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.NativeDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.NativeDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefOperations.java new file mode 100644 index 000000000..b80906afd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/NativeDefOperations.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/NativeDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public interface NativeDefOperations extends org.omg.CORBA.TypedefDefOperations +{ +} // interface NativeDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OpDescriptionSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/OpDescriptionSeqHelper.java new file mode 100644 index 000000000..bdcdef8f6 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OpDescriptionSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OpDescriptionSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class OpDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/OpDescriptionSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.OperationDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.OperationDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.OperationDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.OpDescriptionSeqHelper.id (), "OpDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.OperationDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.OperationDescription value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.OperationDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.OperationDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.OperationDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.OperationDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OpDescriptionSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/OpDescriptionSeqHolder.java new file mode 100644 index 000000000..7b1ca351f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OpDescriptionSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OpDescriptionSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class OpDescriptionSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.OperationDescription value[] = null; + + public OpDescriptionSeqHolder () + { + } + + public OpDescriptionSeqHolder (org.omg.CORBA.OperationDescription[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.OpDescriptionSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.OpDescriptionSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.OpDescriptionSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDef.java new file mode 100644 index 000000000..f14533a4c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface OperationDef extends OperationDefOperations, org.omg.CORBA.Contained, org.omg.CORBA.portable.IDLEntity +{ +} // interface OperationDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefHelper.java new file mode 100644 index 000000000..8e36a0fc2 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class OperationDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/OperationDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.OperationDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.OperationDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.OperationDefHelper.id (), "OperationDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.OperationDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_OperationDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.OperationDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.OperationDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.OperationDef) + return (org.omg.CORBA.OperationDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._OperationDefStub stub = new org.omg.CORBA._OperationDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.OperationDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.OperationDef) + return (org.omg.CORBA.OperationDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._OperationDefStub stub = new org.omg.CORBA._OperationDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefHolder.java new file mode 100644 index 000000000..e460f048b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/OperationDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class OperationDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.OperationDef value = null; + + public OperationDefHolder () + { + } + + public OperationDefHolder (org.omg.CORBA.OperationDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.OperationDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.OperationDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.OperationDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefOperations.java new file mode 100644 index 000000000..1e7c972da --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDefOperations.java @@ -0,0 +1,24 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface OperationDefOperations extends org.omg.CORBA.ContainedOperations +{ + org.omg.CORBA.TypeCode result (); + org.omg.CORBA.IDLType result_def (); + void result_def (org.omg.CORBA.IDLType newResult_def); + org.omg.CORBA.ParameterDescription[] params (); + void params (org.omg.CORBA.ParameterDescription[] newParams); + org.omg.CORBA.OperationMode mode (); + void mode (org.omg.CORBA.OperationMode newMode); + String[] contexts (); + void contexts (String[] newContexts); + org.omg.CORBA.ExceptionDef[] exceptions (); + void exceptions (org.omg.CORBA.ExceptionDef[] newExceptions); +} // interface OperationDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescription.java new file mode 100644 index 000000000..578753754 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescription.java @@ -0,0 +1,40 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class OperationDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode result = null; + public org.omg.CORBA.OperationMode mode = null; + public String contexts[] = null; + public org.omg.CORBA.ParameterDescription parameters[] = null; + public org.omg.CORBA.ExceptionDescription exceptions[] = null; + + public OperationDescription () + { + } // ctor + + public OperationDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _result, org.omg.CORBA.OperationMode _mode, String[] _contexts, org.omg.CORBA.ParameterDescription[] _parameters, org.omg.CORBA.ExceptionDescription[] _exceptions) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + result = _result; + mode = _mode; + contexts = _contexts; + parameters = _parameters; + exceptions = _exceptions; + } // ctor + +} // class OperationDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescriptionHelper.java new file mode 100644 index 000000000..5fc3d1ec6 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescriptionHelper.java @@ -0,0 +1,143 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class OperationDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/OperationDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.OperationDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.OperationDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [9]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "result", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.OperationModeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "mode", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContextIdentifierHelper.id (), "ContextIdentifier", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ContextIdSeqHelper.id (), "ContextIdSeq", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "contexts", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ParameterDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ParDescriptionSeqHelper.id (), "ParDescriptionSeq", _tcOf_members0); + _members0[7] = new org.omg.CORBA.StructMember ( + "parameters", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ExceptionDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ExcDescriptionSeqHelper.id (), "ExcDescriptionSeq", _tcOf_members0); + _members0[8] = new org.omg.CORBA.StructMember ( + "exceptions", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.OperationDescriptionHelper.id (), "OperationDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.OperationDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.OperationDescription value = new org.omg.CORBA.OperationDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.result = istream.read_TypeCode (); + value.mode = org.omg.CORBA.OperationModeHelper.read (istream); + value.contexts = org.omg.CORBA.ContextIdSeqHelper.read (istream); + value.parameters = org.omg.CORBA.ParDescriptionSeqHelper.read (istream); + value.exceptions = org.omg.CORBA.ExcDescriptionSeqHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.OperationDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.result); + org.omg.CORBA.OperationModeHelper.write (ostream, value.mode); + org.omg.CORBA.ContextIdSeqHelper.write (ostream, value.contexts); + org.omg.CORBA.ParDescriptionSeqHelper.write (ostream, value.parameters); + org.omg.CORBA.ExcDescriptionSeqHelper.write (ostream, value.exceptions); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescriptionHolder.java new file mode 100644 index 000000000..fc6a9e5b4 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/OperationDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class OperationDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.OperationDescription value = null; + + public OperationDescriptionHolder () + { + } + + public OperationDescriptionHolder (org.omg.CORBA.OperationDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.OperationDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.OperationDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.OperationDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationMode.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationMode.java new file mode 100644 index 000000000..16168e723 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationMode.java @@ -0,0 +1,40 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationMode.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class OperationMode implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 2; + private static org.omg.CORBA.OperationMode[] __array = new org.omg.CORBA.OperationMode [__size]; + + public static final int _OP_NORMAL = 0; + public static final org.omg.CORBA.OperationMode OP_NORMAL = new org.omg.CORBA.OperationMode(_OP_NORMAL); + public static final int _OP_ONEWAY = 1; + public static final org.omg.CORBA.OperationMode OP_ONEWAY = new org.omg.CORBA.OperationMode(_OP_ONEWAY); + + public int value () + { + return __value; + } + + public static org.omg.CORBA.OperationMode from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected OperationMode (int value) + { + __value = value; + __array[__value] = this; + } +} // class OperationMode diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationModeHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationModeHelper.java new file mode 100644 index 000000000..95172981c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationModeHelper.java @@ -0,0 +1,53 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/OperationModeHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class OperationModeHelper +{ + private static String _id = "IDL:omg.org/CORBA/OperationMode:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.OperationMode that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.OperationMode extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.OperationModeHelper.id (), "OperationMode", new String[] { "OP_NORMAL", "OP_ONEWAY"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.OperationMode read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.OperationMode.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.OperationMode value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/OperationModeHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/OperationModeHolder.java new file mode 100644 index 000000000..0de59b380 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/OperationModeHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/OperationModeHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class OperationModeHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.OperationMode value = null; + + public OperationModeHolder () + { + } + + public OperationModeHolder (org.omg.CORBA.OperationMode initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.OperationModeHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.OperationModeHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.OperationModeHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PRIVATE_MEMBER.java b/idlj/src/test/masters/ir/org/omg/CORBA/PRIVATE_MEMBER.java new file mode 100644 index 000000000..db1fa08eb --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PRIVATE_MEMBER.java @@ -0,0 +1,14 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PRIVATE_MEMBER.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface PRIVATE_MEMBER +{ + public static final short value = (short)(0); +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PUBLIC_MEMBER.java b/idlj/src/test/masters/ir/org/omg/CORBA/PUBLIC_MEMBER.java new file mode 100644 index 000000000..9efe6eeab --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PUBLIC_MEMBER.java @@ -0,0 +1,14 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PUBLIC_MEMBER.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public interface PUBLIC_MEMBER +{ + public static final short value = (short)(1); +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParDescriptionSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParDescriptionSeqHelper.java new file mode 100644 index 000000000..855497d48 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParDescriptionSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ParDescriptionSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ParDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ParDescriptionSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ParameterDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ParameterDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ParameterDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ParDescriptionSeqHelper.id (), "ParDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ParameterDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ParameterDescription value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.ParameterDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ParameterDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ParameterDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ParameterDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParDescriptionSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParDescriptionSeqHolder.java new file mode 100644 index 000000000..2530b9b7e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParDescriptionSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ParDescriptionSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ParDescriptionSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ParameterDescription value[] = null; + + public ParDescriptionSeqHolder () + { + } + + public ParDescriptionSeqHolder (org.omg.CORBA.ParameterDescription[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ParDescriptionSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ParDescriptionSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ParDescriptionSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescription.java new file mode 100644 index 000000000..bb40b4784 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescription.java @@ -0,0 +1,30 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ParameterDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ParameterDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public org.omg.CORBA.TypeCode type = null; + public org.omg.CORBA.IDLType type_def = null; + public org.omg.CORBA.ParameterMode mode = null; + + public ParameterDescription () + { + } // ctor + + public ParameterDescription (String _name, org.omg.CORBA.TypeCode _type, org.omg.CORBA.IDLType _type_def, org.omg.CORBA.ParameterMode _mode) + { + name = _name; + type = _type; + type_def = _type_def; + mode = _mode; + } // ctor + +} // class ParameterDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescriptionHelper.java new file mode 100644 index 000000000..37b4d3316 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescriptionHelper.java @@ -0,0 +1,97 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ParameterDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ParameterDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ParameterDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ParameterDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ParameterDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[1] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[2] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ParameterModeHelper.type (); + _members0[3] = new org.omg.CORBA.StructMember ( + "mode", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ParameterDescriptionHelper.id (), "ParameterDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ParameterDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ParameterDescription value = new org.omg.CORBA.ParameterDescription (); + value.name = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + value.mode = org.omg.CORBA.ParameterModeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ParameterDescription value) + { + ostream.write_string (value.name); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + org.omg.CORBA.ParameterModeHelper.write (ostream, value.mode); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescriptionHolder.java new file mode 100644 index 000000000..b80103f79 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ParameterDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ParameterDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ParameterDescription value = null; + + public ParameterDescriptionHolder () + { + } + + public ParameterDescriptionHolder (org.omg.CORBA.ParameterDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ParameterDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ParameterDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ParameterDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParameterMode.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterMode.java new file mode 100644 index 000000000..24135eed6 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterMode.java @@ -0,0 +1,42 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ParameterMode.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class ParameterMode implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 3; + private static org.omg.CORBA.ParameterMode[] __array = new org.omg.CORBA.ParameterMode [__size]; + + public static final int _PARAM_IN = 0; + public static final org.omg.CORBA.ParameterMode PARAM_IN = new org.omg.CORBA.ParameterMode(_PARAM_IN); + public static final int _PARAM_OUT = 1; + public static final org.omg.CORBA.ParameterMode PARAM_OUT = new org.omg.CORBA.ParameterMode(_PARAM_OUT); + public static final int _PARAM_INOUT = 2; + public static final org.omg.CORBA.ParameterMode PARAM_INOUT = new org.omg.CORBA.ParameterMode(_PARAM_INOUT); + + public int value () + { + return __value; + } + + public static org.omg.CORBA.ParameterMode from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected ParameterMode (int value) + { + __value = value; + __array[__value] = this; + } +} // class ParameterMode diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParameterModeHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterModeHelper.java new file mode 100644 index 000000000..af1b27dc5 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterModeHelper.java @@ -0,0 +1,53 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ParameterModeHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ParameterModeHelper +{ + private static String _id = "IDL:omg.org/CORBA/ParameterMode:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ParameterMode that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ParameterMode extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.ParameterModeHelper.id (), "ParameterMode", new String[] { "PARAM_IN", "PARAM_OUT", "PARAM_INOUT"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ParameterMode read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.ParameterMode.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ParameterMode value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ParameterModeHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterModeHolder.java new file mode 100644 index 000000000..1e42f74ce --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ParameterModeHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ParameterModeHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ParameterModeHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ParameterMode value = null; + + public ParameterModeHolder () + { + } + + public ParameterModeHolder (org.omg.CORBA.ParameterMode initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ParameterModeHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ParameterModeHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ParameterModeHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDef.java new file mode 100644 index 000000000..cedc3e376 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PrimitiveDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface PrimitiveDef extends PrimitiveDefOperations, org.omg.CORBA.IDLType, org.omg.CORBA.portable.IDLEntity +{ +} // interface PrimitiveDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefHelper.java new file mode 100644 index 000000000..c55441482 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PrimitiveDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class PrimitiveDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/PrimitiveDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.PrimitiveDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.PrimitiveDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.PrimitiveDefHelper.id (), "PrimitiveDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.PrimitiveDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_PrimitiveDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.PrimitiveDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.PrimitiveDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.PrimitiveDef) + return (org.omg.CORBA.PrimitiveDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._PrimitiveDefStub stub = new org.omg.CORBA._PrimitiveDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.PrimitiveDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.PrimitiveDef) + return (org.omg.CORBA.PrimitiveDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._PrimitiveDefStub stub = new org.omg.CORBA._PrimitiveDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefHolder.java new file mode 100644 index 000000000..63ba45f95 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/PrimitiveDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class PrimitiveDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.PrimitiveDef value = null; + + public PrimitiveDefHolder () + { + } + + public PrimitiveDefHolder (org.omg.CORBA.PrimitiveDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.PrimitiveDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.PrimitiveDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.PrimitiveDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefOperations.java new file mode 100644 index 000000000..be8e44caf --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveDefOperations.java @@ -0,0 +1,14 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PrimitiveDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface PrimitiveDefOperations extends org.omg.CORBA.IDLTypeOperations +{ + org.omg.CORBA.PrimitiveKind kind (); +} // interface PrimitiveDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKind.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKind.java new file mode 100644 index 000000000..2bb9eecc8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKind.java @@ -0,0 +1,68 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PrimitiveKind.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public class PrimitiveKind implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 16; + private static org.omg.CORBA.PrimitiveKind[] __array = new org.omg.CORBA.PrimitiveKind [__size]; + + public static final int _pk_null = 0; + public static final org.omg.CORBA.PrimitiveKind pk_null = new org.omg.CORBA.PrimitiveKind(_pk_null); + public static final int _pk_void = 1; + public static final org.omg.CORBA.PrimitiveKind pk_void = new org.omg.CORBA.PrimitiveKind(_pk_void); + public static final int _pk_short = 2; + public static final org.omg.CORBA.PrimitiveKind pk_short = new org.omg.CORBA.PrimitiveKind(_pk_short); + public static final int _pk_long = 3; + public static final org.omg.CORBA.PrimitiveKind pk_long = new org.omg.CORBA.PrimitiveKind(_pk_long); + public static final int _pk_ushort = 4; + public static final org.omg.CORBA.PrimitiveKind pk_ushort = new org.omg.CORBA.PrimitiveKind(_pk_ushort); + public static final int _pk_ulong = 5; + public static final org.omg.CORBA.PrimitiveKind pk_ulong = new org.omg.CORBA.PrimitiveKind(_pk_ulong); + public static final int _pk_float = 6; + public static final org.omg.CORBA.PrimitiveKind pk_float = new org.omg.CORBA.PrimitiveKind(_pk_float); + public static final int _pk_double = 7; + public static final org.omg.CORBA.PrimitiveKind pk_double = new org.omg.CORBA.PrimitiveKind(_pk_double); + public static final int _pk_boolean = 8; + public static final org.omg.CORBA.PrimitiveKind pk_boolean = new org.omg.CORBA.PrimitiveKind(_pk_boolean); + public static final int _pk_char = 9; + public static final org.omg.CORBA.PrimitiveKind pk_char = new org.omg.CORBA.PrimitiveKind(_pk_char); + public static final int _pk_octet = 10; + public static final org.omg.CORBA.PrimitiveKind pk_octet = new org.omg.CORBA.PrimitiveKind(_pk_octet); + public static final int _pk_any = 11; + public static final org.omg.CORBA.PrimitiveKind pk_any = new org.omg.CORBA.PrimitiveKind(_pk_any); + public static final int _pk_TypeCode = 12; + public static final org.omg.CORBA.PrimitiveKind pk_TypeCode = new org.omg.CORBA.PrimitiveKind(_pk_TypeCode); + public static final int _pk_Principal = 13; + public static final org.omg.CORBA.PrimitiveKind pk_Principal = new org.omg.CORBA.PrimitiveKind(_pk_Principal); + public static final int _pk_string = 14; + public static final org.omg.CORBA.PrimitiveKind pk_string = new org.omg.CORBA.PrimitiveKind(_pk_string); + public static final int _pk_objref = 15; + public static final org.omg.CORBA.PrimitiveKind pk_objref = new org.omg.CORBA.PrimitiveKind(_pk_objref); + + public int value () + { + return __value; + } + + public static org.omg.CORBA.PrimitiveKind from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected PrimitiveKind (int value) + { + __value = value; + __array[__value] = this; + } +} // class PrimitiveKind diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKindHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKindHelper.java new file mode 100644 index 000000000..a348b9829 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKindHelper.java @@ -0,0 +1,53 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/PrimitiveKindHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class PrimitiveKindHelper +{ + private static String _id = "IDL:omg.org/CORBA/PrimitiveKind:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.PrimitiveKind that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.PrimitiveKind extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.PrimitiveKindHelper.id (), "PrimitiveKind", new String[] { "pk_null", "pk_void", "pk_short", "pk_long", "pk_ushort", "pk_ulong", "pk_float", "pk_double", "pk_boolean", "pk_char", "pk_octet", "pk_any", "pk_TypeCode", "pk_Principal", "pk_string", "pk_objref"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.PrimitiveKind read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.PrimitiveKind.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.PrimitiveKind value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKindHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKindHolder.java new file mode 100644 index 000000000..8915eee3a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/PrimitiveKindHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/PrimitiveKindHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class PrimitiveKindHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.PrimitiveKind value = null; + + public PrimitiveKindHolder () + { + } + + public PrimitiveKindHolder (org.omg.CORBA.PrimitiveKind initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.PrimitiveKindHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.PrimitiveKindHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.PrimitiveKindHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/Repository.java b/idlj/src/test/masters/ir/org/omg/CORBA/Repository.java new file mode 100644 index 000000000..b0699cdda --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/Repository.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/Repository.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface Repository extends RepositoryOperations, org.omg.CORBA.Container, org.omg.CORBA.portable.IDLEntity +{ +} // interface Repository diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryHelper.java new file mode 100644 index 000000000..34c02b03e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/RepositoryHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class RepositoryHelper +{ + private static String _id = "IDL:omg.org/CORBA/Repository:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Repository that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Repository extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.RepositoryHelper.id (), "Repository"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Repository read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_RepositoryStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Repository value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.Repository narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Repository) + return (org.omg.CORBA.Repository)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._RepositoryStub stub = new org.omg.CORBA._RepositoryStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.Repository unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Repository) + return (org.omg.CORBA.Repository)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._RepositoryStub stub = new org.omg.CORBA._RepositoryStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryHolder.java new file mode 100644 index 000000000..1259a0661 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/RepositoryHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class RepositoryHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Repository value = null; + + public RepositoryHolder () + { + } + + public RepositoryHolder (org.omg.CORBA.Repository initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.RepositoryHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.RepositoryHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.RepositoryHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdHelper.java new file mode 100644 index 000000000..5e6cd7e0e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdHelper.java @@ -0,0 +1,56 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/RepositoryIdHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class RepositoryIdHelper +{ + private static String _id = "IDL:omg.org/CORBA/RepositoryId:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdSeqHelper.java new file mode 100644 index 000000000..6636eff12 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdSeqHelper.java @@ -0,0 +1,63 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/RepositoryIdSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class RepositoryIdSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/RepositoryIdSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, String[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[] read (org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long (); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.RepositoryIdHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.RepositoryIdHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdSeqHolder.java new file mode 100644 index 000000000..abcefa2c9 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryIdSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/RepositoryIdSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class RepositoryIdSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public String value[] = null; + + public RepositoryIdSeqHolder () + { + } + + public RepositoryIdSeqHolder (String[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.RepositoryIdSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.RepositoryIdSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.RepositoryIdSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryOperations.java new file mode 100644 index 000000000..925f5a55d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/RepositoryOperations.java @@ -0,0 +1,22 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/RepositoryOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface RepositoryOperations extends org.omg.CORBA.ContainerOperations +{ + + // read interface + org.omg.CORBA.Contained lookup_id (String search_id); + org.omg.CORBA.PrimitiveDef get_primitive (org.omg.CORBA.PrimitiveKind kind); + + // write interface + org.omg.CORBA.StringDef create_string (int bound); + org.omg.CORBA.SequenceDef create_sequence (int bound, org.omg.CORBA.IDLType element_type); + org.omg.CORBA.ArrayDef create_array (int length, org.omg.CORBA.IDLType element_type); +} // interface RepositoryOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ScopedNameHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ScopedNameHelper.java new file mode 100644 index 000000000..8f4bfc297 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ScopedNameHelper.java @@ -0,0 +1,56 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ScopedNameHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class ScopedNameHelper +{ + private static String _id = "IDL:omg.org/CORBA/ScopedName:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ScopedNameHelper.id (), "ScopedName", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDef.java new file mode 100644 index 000000000..aed5a6e2b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/SequenceDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface SequenceDef extends SequenceDefOperations, org.omg.CORBA.IDLType, org.omg.CORBA.portable.IDLEntity +{ +} // interface SequenceDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefHelper.java new file mode 100644 index 000000000..d9b08e27e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/SequenceDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class SequenceDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/SequenceDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.SequenceDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.SequenceDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.SequenceDefHelper.id (), "SequenceDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.SequenceDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_SequenceDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.SequenceDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.SequenceDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.SequenceDef) + return (org.omg.CORBA.SequenceDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._SequenceDefStub stub = new org.omg.CORBA._SequenceDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.SequenceDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.SequenceDef) + return (org.omg.CORBA.SequenceDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._SequenceDefStub stub = new org.omg.CORBA._SequenceDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefHolder.java new file mode 100644 index 000000000..aa9938292 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/SequenceDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class SequenceDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.SequenceDef value = null; + + public SequenceDefHolder () + { + } + + public SequenceDefHolder (org.omg.CORBA.SequenceDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.SequenceDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.SequenceDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.SequenceDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefOperations.java new file mode 100644 index 000000000..aa7aef5dd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/SequenceDefOperations.java @@ -0,0 +1,18 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/SequenceDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface SequenceDefOperations extends org.omg.CORBA.IDLTypeOperations +{ + int bound (); + void bound (int newBound); + org.omg.CORBA.TypeCode element_type (); + org.omg.CORBA.IDLType element_type_def (); + void element_type_def (org.omg.CORBA.IDLType newElement_type_def); +} // interface SequenceDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StringDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/StringDef.java new file mode 100644 index 000000000..162139e49 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StringDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StringDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface StringDef extends StringDefOperations, org.omg.CORBA.IDLType, org.omg.CORBA.portable.IDLEntity +{ +} // interface StringDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StringDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/StringDefHelper.java new file mode 100644 index 000000000..98956bc6e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StringDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StringDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class StringDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/StringDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StringDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.StringDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.StringDefHelper.id (), "StringDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.StringDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_StringDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StringDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.StringDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.StringDef) + return (org.omg.CORBA.StringDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._StringDefStub stub = new org.omg.CORBA._StringDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.StringDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.StringDef) + return (org.omg.CORBA.StringDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._StringDefStub stub = new org.omg.CORBA._StringDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StringDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/StringDefHolder.java new file mode 100644 index 000000000..f82650cad --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StringDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/StringDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class StringDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.StringDef value = null; + + public StringDefHolder () + { + } + + public StringDefHolder (org.omg.CORBA.StringDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.StringDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.StringDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.StringDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StringDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/StringDefOperations.java new file mode 100644 index 000000000..15166637b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StringDefOperations.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StringDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface StringDefOperations extends org.omg.CORBA.IDLTypeOperations +{ + int bound (); + void bound (int newBound); +} // interface StringDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructDef.java new file mode 100644 index 000000000..7831ac278 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface StructDef extends StructDefOperations, org.omg.CORBA.TypedefDef, org.omg.CORBA.Container +{ +} // interface StructDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructDefHelper.java new file mode 100644 index 000000000..b6a077ee7 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class StructDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/StructDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StructDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.StructDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.StructDefHelper.id (), "StructDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.StructDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_StructDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StructDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.StructDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.StructDef) + return (org.omg.CORBA.StructDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._StructDefStub stub = new org.omg.CORBA._StructDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.StructDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.StructDef) + return (org.omg.CORBA.StructDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._StructDefStub stub = new org.omg.CORBA._StructDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructDefHolder.java new file mode 100644 index 000000000..6619f7641 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/StructDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class StructDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.StructDef value = null; + + public StructDefHolder () + { + } + + public StructDefHolder (org.omg.CORBA.StructDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.StructDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.StructDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.StructDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructDefOperations.java new file mode 100644 index 000000000..bfd21bdf9 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructDefOperations.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface StructDefOperations extends org.omg.CORBA.TypedefDefOperations, org.omg.CORBA.ContainerOperations +{ + org.omg.CORBA.StructMember[] members (); + void members (org.omg.CORBA.StructMember[] newMembers); +} // interface StructDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructMember.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructMember.java new file mode 100644 index 000000000..d398ab8db --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructMember.java @@ -0,0 +1,28 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructMember.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class StructMember implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public org.omg.CORBA.TypeCode type = null; + public org.omg.CORBA.IDLType type_def = null; + + public StructMember () + { + } // ctor + + public StructMember (String _name, org.omg.CORBA.TypeCode _type, org.omg.CORBA.IDLType _type_def) + { + name = _name; + type = _type; + type_def = _type_def; + } // ctor + +} // class StructMember diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberHelper.java new file mode 100644 index 000000000..5b8484eb0 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberHelper.java @@ -0,0 +1,90 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructMemberHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class StructMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/StructMember:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StructMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.StructMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [3]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[1] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[2] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.StructMemberHelper.id (), "StructMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.StructMember read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.StructMember value = new org.omg.CORBA.StructMember (); + value.name = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StructMember value) + { + ostream.write_string (value.name); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberHolder.java new file mode 100644 index 000000000..d8e795c73 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/StructMemberHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class StructMemberHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.StructMember value = null; + + public StructMemberHolder () + { + } + + public StructMemberHolder (org.omg.CORBA.StructMember initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.StructMemberHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.StructMemberHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.StructMemberHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberSeqHelper.java new file mode 100644 index 000000000..e99e2ceeb --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructMemberSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class StructMemberSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/StructMemberSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StructMember[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.StructMember[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.StructMemberHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.StructMemberSeqHelper.id (), "StructMemberSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.StructMember[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.StructMember value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.StructMember[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.StructMemberHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StructMember[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.StructMemberHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberSeqHolder.java new file mode 100644 index 000000000..0535b1713 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/StructMemberSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/StructMemberSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class StructMemberSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.StructMember value[] = null; + + public StructMemberSeqHolder () + { + } + + public StructMemberSeqHolder (org.omg.CORBA.StructMember[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.StructMemberSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.StructMemberSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.StructMemberSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescription.java new file mode 100644 index 000000000..9d56602e8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescription.java @@ -0,0 +1,32 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/TypeDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class TypeDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + + public TypeDescription () + { + } // ctor + + public TypeDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + } // ctor + +} // class TypeDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescriptionHelper.java new file mode 100644 index 000000000..cc2f28704 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescriptionHelper.java @@ -0,0 +1,107 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/TypeDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class TypeDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/TypeDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.TypeDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.TypeDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [5]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.TypeDescriptionHelper.id (), "TypeDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.TypeDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.TypeDescription value = new org.omg.CORBA.TypeDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.TypeDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescriptionHolder.java new file mode 100644 index 000000000..2582db625 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypeDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/TypeDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class TypeDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.TypeDescription value = null; + + public TypeDescriptionHolder () + { + } + + public TypeDescriptionHolder (org.omg.CORBA.TypeDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.TypeDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.TypeDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.TypeDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDef.java new file mode 100644 index 000000000..1b7d6932a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/TypedefDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface TypedefDef extends TypedefDefOperations, org.omg.CORBA.Contained, org.omg.CORBA.IDLType +{ +} // interface TypedefDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefHelper.java new file mode 100644 index 000000000..43758244f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/TypedefDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class TypedefDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/TypedefDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.TypedefDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.TypedefDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.TypedefDefHelper.id (), "TypedefDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.TypedefDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_TypedefDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.TypedefDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.TypedefDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.TypedefDef) + return (org.omg.CORBA.TypedefDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._TypedefDefStub stub = new org.omg.CORBA._TypedefDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.TypedefDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.TypedefDef) + return (org.omg.CORBA.TypedefDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._TypedefDefStub stub = new org.omg.CORBA._TypedefDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefHolder.java new file mode 100644 index 000000000..844d30356 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/TypedefDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class TypedefDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.TypedefDef value = null; + + public TypedefDefHolder () + { + } + + public TypedefDefHolder (org.omg.CORBA.TypedefDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.TypedefDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.TypedefDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.TypedefDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefOperations.java new file mode 100644 index 000000000..48eaf9c1e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/TypedefDefOperations.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/TypedefDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface TypedefDefOperations extends org.omg.CORBA.ContainedOperations, org.omg.CORBA.IDLTypeOperations +{ +} // interface TypedefDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDef.java new file mode 100644 index 000000000..c71f77722 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface UnionDef extends UnionDefOperations, org.omg.CORBA.TypedefDef, org.omg.CORBA.Container +{ +} // interface UnionDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefHelper.java new file mode 100644 index 000000000..803efa9c8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class UnionDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/UnionDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.UnionDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.UnionDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.UnionDefHelper.id (), "UnionDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.UnionDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_UnionDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.UnionDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.UnionDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.UnionDef) + return (org.omg.CORBA.UnionDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._UnionDefStub stub = new org.omg.CORBA._UnionDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.UnionDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.UnionDef) + return (org.omg.CORBA.UnionDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._UnionDefStub stub = new org.omg.CORBA._UnionDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefHolder.java new file mode 100644 index 000000000..25d40b9a8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/UnionDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class UnionDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.UnionDef value = null; + + public UnionDefHolder () + { + } + + public UnionDefHolder (org.omg.CORBA.UnionDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.UnionDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.UnionDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.UnionDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefOperations.java new file mode 100644 index 000000000..943dc39ee --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionDefOperations.java @@ -0,0 +1,18 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public interface UnionDefOperations extends org.omg.CORBA.TypedefDefOperations, org.omg.CORBA.ContainerOperations +{ + org.omg.CORBA.TypeCode discriminator_type (); + org.omg.CORBA.IDLType discriminator_type_def (); + void discriminator_type_def (org.omg.CORBA.IDLType newDiscriminator_type_def); + org.omg.CORBA.UnionMember[] members (); + void members (org.omg.CORBA.UnionMember[] newMembers); +} // interface UnionDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionMember.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMember.java new file mode 100644 index 000000000..2cdc8d238 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMember.java @@ -0,0 +1,30 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionMember.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class UnionMember implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public org.omg.CORBA.Any label = null; + public org.omg.CORBA.TypeCode type = null; + public org.omg.CORBA.IDLType type_def = null; + + public UnionMember () + { + } // ctor + + public UnionMember (String _name, org.omg.CORBA.Any _label, org.omg.CORBA.TypeCode _type, org.omg.CORBA.IDLType _type_def) + { + name = _name; + label = _label; + type = _type; + type_def = _type_def; + } // ctor + +} // class UnionMember diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberHelper.java new file mode 100644 index 000000000..99f0f3d0c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberHelper.java @@ -0,0 +1,97 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionMemberHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class UnionMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/UnionMember:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.UnionMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.UnionMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[1] = new org.omg.CORBA.StructMember ( + "label", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[2] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[3] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.UnionMemberHelper.id (), "UnionMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.UnionMember read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.UnionMember value = new org.omg.CORBA.UnionMember (); + value.name = istream.read_string (); + value.label = istream.read_any (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.UnionMember value) + { + ostream.write_string (value.name); + ostream.write_any (value.label); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberHolder.java new file mode 100644 index 000000000..1ff3c6b6b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/UnionMemberHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class UnionMemberHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.UnionMember value = null; + + public UnionMemberHolder () + { + } + + public UnionMemberHolder (org.omg.CORBA.UnionMember initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.UnionMemberHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.UnionMemberHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.UnionMemberHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberSeqHelper.java new file mode 100644 index 000000000..455e4a854 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionMemberSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class UnionMemberSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/UnionMemberSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.UnionMember[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.UnionMember[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.UnionMemberHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.UnionMemberSeqHelper.id (), "UnionMemberSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.UnionMember[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.UnionMember value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.UnionMember[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.UnionMemberHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.UnionMember[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.UnionMemberHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberSeqHolder.java new file mode 100644 index 000000000..e3daf2757 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/UnionMemberSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/UnionMemberSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class UnionMemberSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.UnionMember value[] = null; + + public UnionMemberSeqHolder () + { + } + + public UnionMemberSeqHolder (org.omg.CORBA.UnionMember[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.UnionMemberSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.UnionMemberSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.UnionMemberSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDef.java new file mode 100644 index 000000000..bdaf62ce8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueBoxDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public interface ValueBoxDef extends ValueBoxDefOperations, org.omg.CORBA.IDLType, org.omg.CORBA.portable.IDLEntity +{ +} // interface ValueBoxDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefHelper.java new file mode 100644 index 000000000..929b6dcc8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueBoxDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +abstract public class ValueBoxDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueBoxDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueBoxDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueBoxDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ValueBoxDefHelper.id (), "ValueBoxDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueBoxDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ValueBoxDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueBoxDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ValueBoxDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ValueBoxDef) + return (org.omg.CORBA.ValueBoxDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ValueBoxDefStub stub = new org.omg.CORBA._ValueBoxDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ValueBoxDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ValueBoxDef) + return (org.omg.CORBA.ValueBoxDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ValueBoxDefStub stub = new org.omg.CORBA._ValueBoxDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefHolder.java new file mode 100644 index 000000000..f8aca8d3c --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ValueBoxDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public final class ValueBoxDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueBoxDef value = null; + + public ValueBoxDefHolder () + { + } + + public ValueBoxDefHolder (org.omg.CORBA.ValueBoxDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueBoxDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueBoxDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueBoxDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefOperations.java new file mode 100644 index 000000000..54c83ec9d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueBoxDefOperations.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueBoxDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public interface ValueBoxDefOperations extends org.omg.CORBA.IDLTypeOperations +{ + org.omg.CORBA.IDLType original_type_def (); + void original_type_def (org.omg.CORBA.IDLType newOriginal_type_def); +} // interface ValueBoxDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDef.java new file mode 100644 index 000000000..426709e93 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDef.java @@ -0,0 +1,13 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public interface ValueDef extends ValueDefOperations, org.omg.CORBA.Container, org.omg.CORBA.Contained, org.omg.CORBA.IDLType +{ +} // interface ValueDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefHelper.java new file mode 100644 index 000000000..5737aa24d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefHelper.java @@ -0,0 +1,85 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +abstract public class ValueDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ValueDefHelper.id (), "ValueDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ValueDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ValueDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ValueDef) + return (org.omg.CORBA.ValueDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ValueDefStub stub = new org.omg.CORBA._ValueDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ValueDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ValueDef) + return (org.omg.CORBA.ValueDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ValueDefStub stub = new org.omg.CORBA._ValueDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefHolder.java new file mode 100644 index 000000000..bced92816 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ValueDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public final class ValueDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueDef value = null; + + public ValueDefHolder () + { + } + + public ValueDefHolder (org.omg.CORBA.ValueDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefOperations.java new file mode 100644 index 000000000..336208308 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefOperations.java @@ -0,0 +1,46 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public interface ValueDefOperations extends org.omg.CORBA.ContainerOperations, org.omg.CORBA.ContainedOperations, org.omg.CORBA.IDLTypeOperations +{ + + // read/write interface + org.omg.CORBA.InterfaceDef[] supported_interfaces (); + + // read/write interface + void supported_interfaces (org.omg.CORBA.InterfaceDef[] newSupported_interfaces); + org.omg.CORBA.Initializer[] initializers (); + void initializers (org.omg.CORBA.Initializer[] newInitializers); + org.omg.CORBA.ValueDef base_value (); + void base_value (org.omg.CORBA.ValueDef newBase_value); + org.omg.CORBA.ValueDef[] abstract_base_values (); + void abstract_base_values (org.omg.CORBA.ValueDef[] newAbstract_base_values); + boolean is_abstract (); + void is_abstract (boolean newIs_abstract); + boolean is_custom (); + void is_custom (boolean newIs_custom); + byte flags (); + void flags (byte newFlags); + + // always 0 + boolean has_safe_base (); + + // always 0 + void has_safe_base (boolean newHas_safe_base); + + // read interface + boolean is_a (String value_id); + org.omg.CORBA.ValueDefPackage.FullValueDescription describe_value (); + + // write interface + org.omg.CORBA.ValueMemberDef create_value_member (String id, String name, String version, org.omg.CORBA.IDLType type_def, short access); + org.omg.CORBA.AttributeDef create_attribute (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.AttributeMode mode); + org.omg.CORBA.OperationDef create_operation (String id, String name, String version, org.omg.CORBA.IDLType result, org.omg.CORBA.OperationMode mode, org.omg.CORBA.ParameterDescription[] params, org.omg.CORBA.ExceptionDef[] exceptions, String[] contexts); +} // interface ValueDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescription.java new file mode 100644 index 000000000..b4178eecb --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescription.java @@ -0,0 +1,56 @@ +package org.omg.CORBA.ValueDefPackage; + + +/** +* org/omg/CORBA/ValueDefPackage/FullValueDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public final class FullValueDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public boolean is_abstract = false; + public boolean is_custom = false; + public byte flags = (byte)0; + + // always 0 + public String defined_in = null; + public String version = null; + public org.omg.CORBA.OperationDescription operations[] = null; + public org.omg.CORBA.AttributeDescription attributes[] = null; + public org.omg.CORBA.ValueMember members[] = null; + public org.omg.CORBA.Initializer initializers[] = null; + public String supported_interfaces[] = null; + public String abstract_base_values[] = null; + public boolean has_safe_base = false; + public String base_value = null; + public org.omg.CORBA.TypeCode type = null; + + public FullValueDescription () + { + } // ctor + + public FullValueDescription (String _name, String _id, boolean _is_abstract, boolean _is_custom, byte _flags, String _defined_in, String _version, org.omg.CORBA.OperationDescription[] _operations, org.omg.CORBA.AttributeDescription[] _attributes, org.omg.CORBA.ValueMember[] _members, org.omg.CORBA.Initializer[] _initializers, String[] _supported_interfaces, String[] _abstract_base_values, boolean _has_safe_base, String _base_value, org.omg.CORBA.TypeCode _type) + { + name = _name; + id = _id; + is_abstract = _is_abstract; + is_custom = _is_custom; + flags = _flags; + defined_in = _defined_in; + version = _version; + operations = _operations; + attributes = _attributes; + members = _members; + initializers = _initializers; + supported_interfaces = _supported_interfaces; + abstract_base_values = _abstract_base_values; + has_safe_base = _has_safe_base; + base_value = _base_value; + type = _type; + } // ctor + +} // class FullValueDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java new file mode 100644 index 000000000..1317ce6a3 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java @@ -0,0 +1,199 @@ +package org.omg.CORBA.ValueDefPackage; + + +/** +* org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +abstract public class FullValueDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueDef/FullValueDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueDefPackage.FullValueDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueDefPackage.FullValueDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [16]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[2] = new org.omg.CORBA.StructMember ( + "is_abstract", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[3] = new org.omg.CORBA.StructMember ( + "is_custom", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_octet); + _members0[4] = new org.omg.CORBA.StructMember ( + "flags", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[5] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.OperationDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.OpDescriptionSeqHelper.id (), "OpDescriptionSeq", _tcOf_members0); + _members0[7] = new org.omg.CORBA.StructMember ( + "operations", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.AttributeDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.AttrDescriptionSeqHelper.id (), "AttrDescriptionSeq", _tcOf_members0); + _members0[8] = new org.omg.CORBA.StructMember ( + "attributes", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ValueMemberHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ValueMemberSeqHelper.id (), "ValueMemberSeq", _tcOf_members0); + _members0[9] = new org.omg.CORBA.StructMember ( + "members", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.InitializerHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.InitializerSeqHelper.id (), "InitializerSeq", _tcOf_members0); + _members0[10] = new org.omg.CORBA.StructMember ( + "initializers", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[11] = new org.omg.CORBA.StructMember ( + "supported_interfaces", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[12] = new org.omg.CORBA.StructMember ( + "abstract_base_values", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[13] = new org.omg.CORBA.StructMember ( + "has_safe_base", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[14] = new org.omg.CORBA.StructMember ( + "base_value", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[15] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.id (), "FullValueDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueDefPackage.FullValueDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ValueDefPackage.FullValueDescription value = new org.omg.CORBA.ValueDefPackage.FullValueDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.is_abstract = istream.read_boolean (); + value.is_custom = istream.read_boolean (); + value.flags = istream.read_octet (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.operations = org.omg.CORBA.OpDescriptionSeqHelper.read (istream); + value.attributes = org.omg.CORBA.AttrDescriptionSeqHelper.read (istream); + value.members = org.omg.CORBA.ValueMemberSeqHelper.read (istream); + value.initializers = org.omg.CORBA.InitializerSeqHelper.read (istream); + value.supported_interfaces = org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.abstract_base_values = org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.has_safe_base = istream.read_boolean (); + value.base_value = istream.read_string (); + value.type = istream.read_TypeCode (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueDefPackage.FullValueDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_boolean (value.is_abstract); + ostream.write_boolean (value.is_custom); + ostream.write_octet (value.flags); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + org.omg.CORBA.OpDescriptionSeqHelper.write (ostream, value.operations); + org.omg.CORBA.AttrDescriptionSeqHelper.write (ostream, value.attributes); + org.omg.CORBA.ValueMemberSeqHelper.write (ostream, value.members); + org.omg.CORBA.InitializerSeqHelper.write (ostream, value.initializers); + org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.supported_interfaces); + org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.abstract_base_values); + ostream.write_boolean (value.has_safe_base); + ostream.write_string (value.base_value); + ostream.write_TypeCode (value.type); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHolder.java new file mode 100644 index 000000000..2e940b9c4 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA.ValueDefPackage; + +/** +* org/omg/CORBA/ValueDefPackage/FullValueDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public final class FullValueDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueDefPackage.FullValueDescription value = null; + + public FullValueDescriptionHolder () + { + } + + public FullValueDescriptionHolder (org.omg.CORBA.ValueDefPackage.FullValueDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefSeqHelper.java new file mode 100644 index 000000000..75ec2b66f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDefSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class ValueDefSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueDefSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueDef[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueDef[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ValueDefHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ValueDefSeqHelper.id (), "ValueDefSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueDef[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ValueDef value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.ValueDef[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ValueDefHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueDef[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ValueDefHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefSeqHolder.java new file mode 100644 index 000000000..3dc26522e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDefSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDefSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class ValueDefSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueDef value[] = null; + + public ValueDefSeqHolder () + { + } + + public ValueDefSeqHolder (org.omg.CORBA.ValueDef[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueDefSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueDefSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueDefSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescription.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescription.java new file mode 100644 index 000000000..4579e079f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescription.java @@ -0,0 +1,46 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDescription.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public final class ValueDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public boolean is_abstract = false; + public boolean is_custom = false; + public byte flags = (byte)0; + + // always 0 + public String defined_in = null; + public String version = null; + public String supported_interfaces[] = null; + public String abstract_base_values[] = null; + public boolean has_safe_base = false; + public String base_value = null; + + public ValueDescription () + { + } // ctor + + public ValueDescription (String _name, String _id, boolean _is_abstract, boolean _is_custom, byte _flags, String _defined_in, String _version, String[] _supported_interfaces, String[] _abstract_base_values, boolean _has_safe_base, String _base_value) + { + name = _name; + id = _id; + is_abstract = _is_abstract; + is_custom = _is_custom; + flags = _flags; + defined_in = _defined_in; + version = _version; + supported_interfaces = _supported_interfaces; + abstract_base_values = _abstract_base_values; + has_safe_base = _has_safe_base; + base_value = _base_value; + } // ctor + +} // class ValueDescription diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescriptionHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescriptionHelper.java new file mode 100644 index 000000000..a339dacfa --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescriptionHelper.java @@ -0,0 +1,156 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueDescriptionHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +abstract public class ValueDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueDescription:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [11]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[2] = new org.omg.CORBA.StructMember ( + "is_abstract", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[3] = new org.omg.CORBA.StructMember ( + "is_custom", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_octet); + _members0[4] = new org.omg.CORBA.StructMember ( + "flags", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[5] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[7] = new org.omg.CORBA.StructMember ( + "supported_interfaces", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[8] = new org.omg.CORBA.StructMember ( + "abstract_base_values", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[9] = new org.omg.CORBA.StructMember ( + "has_safe_base", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[10] = new org.omg.CORBA.StructMember ( + "base_value", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ValueDescriptionHelper.id (), "ValueDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueDescription read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ValueDescription value = new org.omg.CORBA.ValueDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.is_abstract = istream.read_boolean (); + value.is_custom = istream.read_boolean (); + value.flags = istream.read_octet (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.supported_interfaces = org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.abstract_base_values = org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.has_safe_base = istream.read_boolean (); + value.base_value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_boolean (value.is_abstract); + ostream.write_boolean (value.is_custom); + ostream.write_octet (value.flags); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.supported_interfaces); + org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.abstract_base_values); + ostream.write_boolean (value.has_safe_base); + ostream.write_string (value.base_value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescriptionHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescriptionHolder.java new file mode 100644 index 000000000..62ea179fb --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueDescriptionHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ValueDescriptionHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public final class ValueDescriptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueDescription value = null; + + public ValueDescriptionHolder () + { + } + + public ValueDescriptionHolder (org.omg.CORBA.ValueDescription initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueDescriptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueDescriptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueDescriptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMember.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMember.java new file mode 100644 index 000000000..f9bd134af --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMember.java @@ -0,0 +1,36 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMember.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class ValueMember implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + public org.omg.CORBA.IDLType type_def = null; + public short access = (short)0; + + public ValueMember () + { + } // ctor + + public ValueMember (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type, org.omg.CORBA.IDLType _type_def, short _access) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + type_def = _type_def; + access = _access; + } // ctor + +} // class ValueMember diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDef.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDef.java new file mode 100644 index 000000000..dc73fa3a5 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDef.java @@ -0,0 +1,15 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMemberDef.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- begin +public interface ValueMemberDef extends ValueMemberDefOperations, org.omg.CORBA.Contained, org.omg.CORBA.portable.IDLEntity +{ +} // interface ValueMemberDef diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefHelper.java new file mode 100644 index 000000000..970aa2ffd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefHelper.java @@ -0,0 +1,87 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMemberDefHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- begin +abstract public class ValueMemberDefHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueMemberDef:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueMemberDef that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueMemberDef extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.ValueMemberDefHelper.id (), "ValueMemberDef"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueMemberDef read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ValueMemberDefStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueMemberDef value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.ValueMemberDef narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ValueMemberDef) + return (org.omg.CORBA.ValueMemberDef)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ValueMemberDefStub stub = new org.omg.CORBA._ValueMemberDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.omg.CORBA.ValueMemberDef unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.ValueMemberDef) + return (org.omg.CORBA.ValueMemberDef)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.omg.CORBA._ValueMemberDefStub stub = new org.omg.CORBA._ValueMemberDefStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefHolder.java new file mode 100644 index 000000000..72f610769 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefHolder.java @@ -0,0 +1,40 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ValueMemberDefHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- begin +public final class ValueMemberDefHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueMemberDef value = null; + + public ValueMemberDefHolder () + { + } + + public ValueMemberDefHolder (org.omg.CORBA.ValueMemberDef initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueMemberDefHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueMemberDefHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueMemberDefHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefOperations.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefOperations.java new file mode 100644 index 000000000..c71da41dc --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberDefOperations.java @@ -0,0 +1,20 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMemberDefOperations.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- begin +public interface ValueMemberDefOperations extends org.omg.CORBA.ContainedOperations +{ + org.omg.CORBA.TypeCode type (); + org.omg.CORBA.IDLType type_def (); + void type_def (org.omg.CORBA.IDLType newType_def); + short access (); + void access (short newAccess); +} // interface ValueMemberDefOperations diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberHelper.java new file mode 100644 index 000000000..daf422157 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberHelper.java @@ -0,0 +1,122 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMemberHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class ValueMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueMember:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [7]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VisibilityHelper.id (), "Visibility", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "access", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ValueMemberHelper.id (), "ValueMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueMember read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ValueMember value = new org.omg.CORBA.ValueMember (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + value.access = istream.read_short (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueMember value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + ostream.write_short (value.access); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberHolder.java new file mode 100644 index 000000000..0b0ef8dff --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberHolder.java @@ -0,0 +1,38 @@ +package org.omg.CORBA; + +/** +* org/omg/CORBA/ValueMemberHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class ValueMemberHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueMember value = null; + + public ValueMemberHolder () + { + } + + public ValueMemberHolder (org.omg.CORBA.ValueMember initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueMemberHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueMemberHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueMemberHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberSeqHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberSeqHelper.java new file mode 100644 index 000000000..68b6497d6 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberSeqHelper.java @@ -0,0 +1,62 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMemberSeqHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class ValueMemberSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueMemberSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueMember[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueMember[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ValueMemberHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ValueMemberSeqHelper.id (), "ValueMemberSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueMember[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ValueMember value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.ValueMember[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.ValueMemberHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueMember[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.ValueMemberHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberSeqHolder.java b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberSeqHolder.java new file mode 100644 index 000000000..71cfd2399 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/ValueMemberSeqHolder.java @@ -0,0 +1,39 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/ValueMemberSeqHolder.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public final class ValueMemberSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.ValueMember value[] = null; + + public ValueMemberSeqHolder () + { + } + + public ValueMemberSeqHolder (org.omg.CORBA.ValueMember[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ValueMemberSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ValueMemberSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ValueMemberSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/VersionSpecHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/VersionSpecHelper.java new file mode 100644 index 000000000..d93312f03 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/VersionSpecHelper.java @@ -0,0 +1,56 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/VersionSpecHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +abstract public class VersionSpecHelper +{ + private static String _id = "IDL:omg.org/CORBA/VersionSpec:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/VisibilityHelper.java b/idlj/src/test/masters/ir/org/omg/CORBA/VisibilityHelper.java new file mode 100644 index 000000000..b3a2ae5f8 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/VisibilityHelper.java @@ -0,0 +1,58 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/VisibilityHelper.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- begin +abstract public class VisibilityHelper +{ + private static String _id = "IDL:omg.org/CORBA/Visibility:1.0"; + + public static void insert (org.omg.CORBA.Any a, short that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static short extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VisibilityHelper.id (), "Visibility", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static short read (org.omg.CORBA.portable.InputStream istream) + { + short value = (short)0; + value = istream.read_short (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, short value) + { + ostream.write_short (value); + } + +} diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_AliasDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_AliasDefStub.java new file mode 100644 index 000000000..499667314 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_AliasDefStub.java @@ -0,0 +1,371 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_AliasDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _AliasDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.AliasDef +{ + + public org.omg.CORBA.IDLType original_type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_original_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return original_type_def ( ); + } finally { + _releaseReply ($in); + } + } // original_type_def + + public void original_type_def (org.omg.CORBA.IDLType newOriginal_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_original_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newOriginal_type_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + original_type_def (newOriginal_type_def ); + } finally { + _releaseReply ($in); + } + } // original_type_def + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/AliasDef:1.0", + "IDL:omg.org/CORBA/TypedefDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/IDLType:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _AliasDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ArrayDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ArrayDefStub.java new file mode 100644 index 000000000..26a6a1ccd --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ArrayDefStub.java @@ -0,0 +1,207 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ArrayDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _ArrayDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ArrayDef +{ + + public int length () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_length", true); + $in = _invoke ($out); + int $result = $in.read_ulong (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return length ( ); + } finally { + _releaseReply ($in); + } + } // length + + public void length (int newLength) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_length", true); + $out.write_ulong (newLength); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + length (newLength ); + } finally { + _releaseReply ($in); + } + } // length + + public org.omg.CORBA.TypeCode element_type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_element_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return element_type ( ); + } finally { + _releaseReply ($in); + } + } // element_type + + public org.omg.CORBA.IDLType element_type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_element_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return element_type_def ( ); + } finally { + _releaseReply ($in); + } + } // element_type_def + + public void element_type_def (org.omg.CORBA.IDLType newElement_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_element_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newElement_type_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + element_type_def (newElement_type_def ); + } finally { + _releaseReply ($in); + } + } // element_type_def + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ArrayDef:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ArrayDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_AttributeDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_AttributeDefStub.java new file mode 100644 index 000000000..9586c2cc3 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_AttributeDefStub.java @@ -0,0 +1,407 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_AttributeDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _AttributeDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.AttributeDef +{ + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + public org.omg.CORBA.IDLType type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type_def ( ); + } finally { + _releaseReply ($in); + } + } // type_def + + public void type_def (org.omg.CORBA.IDLType newType_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newType_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + type_def (newType_def ); + } finally { + _releaseReply ($in); + } + } // type_def + + public org.omg.CORBA.AttributeMode mode () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_mode", true); + $in = _invoke ($out); + org.omg.CORBA.AttributeMode $result = org.omg.CORBA.AttributeModeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return mode ( ); + } finally { + _releaseReply ($in); + } + } // mode + + public void mode (org.omg.CORBA.AttributeMode newMode) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_mode", true); + org.omg.CORBA.AttributeModeHelper.write ($out, newMode); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + mode (newMode ); + } finally { + _releaseReply ($in); + } + } // mode + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/AttributeDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _AttributeDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ConstantDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ConstantDefStub.java new file mode 100644 index 000000000..7ed2b863b --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ConstantDefStub.java @@ -0,0 +1,407 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ConstantDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _ConstantDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ConstantDef +{ + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + public org.omg.CORBA.IDLType type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type_def ( ); + } finally { + _releaseReply ($in); + } + } // type_def + + public void type_def (org.omg.CORBA.IDLType newType_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newType_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + type_def (newType_def ); + } finally { + _releaseReply ($in); + } + } // type_def + + public org.omg.CORBA.Any value () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_value", true); + $in = _invoke ($out); + org.omg.CORBA.Any $result = $in.read_any (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return value ( ); + } finally { + _releaseReply ($in); + } + } // value + + public void value (org.omg.CORBA.Any newValue) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_value", true); + $out.write_any (newValue); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + value (newValue ); + } finally { + _releaseReply ($in); + } + } // value + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ConstantDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ConstantDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ContainedStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ContainedStub.java new file mode 100644 index 000000000..eda0b1b1e --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ContainedStub.java @@ -0,0 +1,311 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ContainedStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public class _ContainedStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.Contained +{ + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ContainedStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ContainerStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ContainerStub.java new file mode 100644 index 000000000..29a8c8f66 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ContainerStub.java @@ -0,0 +1,449 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ContainerStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public class _ContainerStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.Container +{ + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/Container:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ContainerStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_EnumDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_EnumDefStub.java new file mode 100644 index 000000000..ebe676ad0 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_EnumDefStub.java @@ -0,0 +1,371 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_EnumDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _EnumDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.EnumDef +{ + + public String[] members () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_members", true); + $in = _invoke ($out); + String $result[] = org.omg.CORBA.EnumMemberSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return members ( ); + } finally { + _releaseReply ($in); + } + } // members + + public void members (String[] newMembers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_members", true); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, newMembers); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + members (newMembers ); + } finally { + _releaseReply ($in); + } + } // members + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/EnumDef:1.0", + "IDL:omg.org/CORBA/TypedefDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/IDLType:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _EnumDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ExceptionDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ExceptionDefStub.java new file mode 100644 index 000000000..ee99c00bf --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ExceptionDefStub.java @@ -0,0 +1,725 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ExceptionDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _ExceptionDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ExceptionDef +{ + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + public org.omg.CORBA.StructMember[] members () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_members", true); + $in = _invoke ($out); + org.omg.CORBA.StructMember $result[] = org.omg.CORBA.StructMemberSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return members ( ); + } finally { + _releaseReply ($in); + } + } // members + + public void members (org.omg.CORBA.StructMember[] newMembers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_members", true); + org.omg.CORBA.StructMemberSeqHelper.write ($out, newMembers); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + members (newMembers ); + } finally { + _releaseReply ($in); + } + } // members + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ExceptionDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/Container:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ExceptionDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_IDLTypeStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_IDLTypeStub.java new file mode 100644 index 000000000..ad7ca095f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_IDLTypeStub.java @@ -0,0 +1,111 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_IDLTypeStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public class _IDLTypeStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.IDLType +{ + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _IDLTypeStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_IRObjectStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_IRObjectStub.java new file mode 100644 index 000000000..1cb5b7841 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_IRObjectStub.java @@ -0,0 +1,91 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_IRObjectStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public class _IRObjectStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.IRObject +{ + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _IRObjectStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_InterfaceDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_InterfaceDefStub.java new file mode 100644 index 000000000..76a00633f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_InterfaceDefStub.java @@ -0,0 +1,862 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_InterfaceDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _InterfaceDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.InterfaceDef +{ + + + // read/write interface + public org.omg.CORBA.InterfaceDef[] base_interfaces () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_base_interfaces", true); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result[] = org.omg.CORBA.InterfaceDefSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return base_interfaces ( ); + } finally { + _releaseReply ($in); + } + } // base_interfaces + + + // read/write interface + public void base_interfaces (org.omg.CORBA.InterfaceDef[] newBase_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_base_interfaces", true); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, newBase_interfaces); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + base_interfaces (newBase_interfaces ); + } finally { + _releaseReply ($in); + } + } // base_interfaces + + public boolean is_abstract () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_is_abstract", true); + $in = _invoke ($out); + boolean $result = $in.read_boolean (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return is_abstract ( ); + } finally { + _releaseReply ($in); + } + } // is_abstract + + public void is_abstract (boolean newIs_abstract) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_is_abstract", true); + $out.write_boolean (newIs_abstract); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + is_abstract (newIs_abstract ); + } finally { + _releaseReply ($in); + } + } // is_abstract + + + // read interface + public boolean is_a (String interface_id) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("is_a", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, interface_id); + $in = _invoke ($out); + boolean $result = $in.read_boolean (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return is_a (interface_id ); + } finally { + _releaseReply ($in); + } + } // is_a + + public org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription describe_interface () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_interface", true); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription $result = org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_interface ( ); + } finally { + _releaseReply ($in); + } + } // describe_interface + + + // write interface + public org.omg.CORBA.AttributeDef create_attribute (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.AttributeMode mode) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_attribute", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + org.omg.CORBA.AttributeModeHelper.write ($out, mode); + $in = _invoke ($out); + org.omg.CORBA.AttributeDef $result = org.omg.CORBA.AttributeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_attribute (id, name, version, type, mode ); + } finally { + _releaseReply ($in); + } + } // create_attribute + + public org.omg.CORBA.OperationDef create_operation (String id, String name, String version, org.omg.CORBA.IDLType result, org.omg.CORBA.OperationMode mode, org.omg.CORBA.ParameterDescription[] params, org.omg.CORBA.ExceptionDef[] exceptions, String[] contexts) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_operation", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, result); + org.omg.CORBA.OperationModeHelper.write ($out, mode); + org.omg.CORBA.ParDescriptionSeqHelper.write ($out, params); + org.omg.CORBA.ExceptionDefSeqHelper.write ($out, exceptions); + org.omg.CORBA.ContextIdSeqHelper.write ($out, contexts); + $in = _invoke ($out); + org.omg.CORBA.OperationDef $result = org.omg.CORBA.OperationDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_operation (id, name, version, result, mode, params, exceptions, contexts ); + } finally { + _releaseReply ($in); + } + } // create_operation + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/InterfaceDef:1.0", + "IDL:omg.org/CORBA/Container:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IDLType:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _InterfaceDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ModuleDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ModuleDefStub.java new file mode 100644 index 000000000..8949a60a7 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ModuleDefStub.java @@ -0,0 +1,668 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ModuleDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _ModuleDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ModuleDef +{ + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ModuleDef:1.0", + "IDL:omg.org/CORBA/Container:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/Contained:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ModuleDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_NativeDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_NativeDefStub.java new file mode 100644 index 000000000..d8f148220 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_NativeDefStub.java @@ -0,0 +1,335 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_NativeDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- end +public class _NativeDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.NativeDef +{ + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/NativeDef:1.0", + "IDL:omg.org/CORBA/TypedefDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/IDLType:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _NativeDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_OperationDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_OperationDefStub.java new file mode 100644 index 000000000..8a2f5017d --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_OperationDefStub.java @@ -0,0 +1,521 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_OperationDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _OperationDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.OperationDef +{ + + public org.omg.CORBA.TypeCode result () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_result", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return result ( ); + } finally { + _releaseReply ($in); + } + } // result + + public org.omg.CORBA.IDLType result_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_result_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return result_def ( ); + } finally { + _releaseReply ($in); + } + } // result_def + + public void result_def (org.omg.CORBA.IDLType newResult_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_result_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newResult_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + result_def (newResult_def ); + } finally { + _releaseReply ($in); + } + } // result_def + + public org.omg.CORBA.ParameterDescription[] params () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_params", true); + $in = _invoke ($out); + org.omg.CORBA.ParameterDescription $result[] = org.omg.CORBA.ParDescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return params ( ); + } finally { + _releaseReply ($in); + } + } // params + + public void params (org.omg.CORBA.ParameterDescription[] newParams) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_params", true); + org.omg.CORBA.ParDescriptionSeqHelper.write ($out, newParams); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + params (newParams ); + } finally { + _releaseReply ($in); + } + } // params + + public org.omg.CORBA.OperationMode mode () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_mode", true); + $in = _invoke ($out); + org.omg.CORBA.OperationMode $result = org.omg.CORBA.OperationModeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return mode ( ); + } finally { + _releaseReply ($in); + } + } // mode + + public void mode (org.omg.CORBA.OperationMode newMode) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_mode", true); + org.omg.CORBA.OperationModeHelper.write ($out, newMode); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + mode (newMode ); + } finally { + _releaseReply ($in); + } + } // mode + + public String[] contexts () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_contexts", true); + $in = _invoke ($out); + String $result[] = org.omg.CORBA.ContextIdSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contexts ( ); + } finally { + _releaseReply ($in); + } + } // contexts + + public void contexts (String[] newContexts) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_contexts", true); + org.omg.CORBA.ContextIdSeqHelper.write ($out, newContexts); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + contexts (newContexts ); + } finally { + _releaseReply ($in); + } + } // contexts + + public org.omg.CORBA.ExceptionDef[] exceptions () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_exceptions", true); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result[] = org.omg.CORBA.ExceptionDefSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return exceptions ( ); + } finally { + _releaseReply ($in); + } + } // exceptions + + public void exceptions (org.omg.CORBA.ExceptionDef[] newExceptions) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_exceptions", true); + org.omg.CORBA.ExceptionDefSeqHelper.write ($out, newExceptions); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + exceptions (newExceptions ); + } finally { + _releaseReply ($in); + } + } // exceptions + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/OperationDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _OperationDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_PrimitiveDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_PrimitiveDefStub.java new file mode 100644 index 000000000..e91f441c1 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_PrimitiveDefStub.java @@ -0,0 +1,131 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_PrimitiveDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _PrimitiveDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.PrimitiveDef +{ + + public org.omg.CORBA.PrimitiveKind kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_kind", true); + $in = _invoke ($out); + org.omg.CORBA.PrimitiveKind $result = org.omg.CORBA.PrimitiveKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return kind ( ); + } finally { + _releaseReply ($in); + } + } // kind + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/PrimitiveDef:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _PrimitiveDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_RepositoryStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_RepositoryStub.java new file mode 100644 index 000000000..7b24b3771 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_RepositoryStub.java @@ -0,0 +1,554 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_RepositoryStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:22 PM EST +*/ + +public class _RepositoryStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.Repository +{ + + + // read interface + public org.omg.CORBA.Contained lookup_id (String search_id) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, search_id); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_id (search_id ); + } finally { + _releaseReply ($in); + } + } // lookup_id + + public org.omg.CORBA.PrimitiveDef get_primitive (org.omg.CORBA.PrimitiveKind kind) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("get_primitive", true); + org.omg.CORBA.PrimitiveKindHelper.write ($out, kind); + $in = _invoke ($out); + org.omg.CORBA.PrimitiveDef $result = org.omg.CORBA.PrimitiveDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return get_primitive (kind ); + } finally { + _releaseReply ($in); + } + } // get_primitive + + + // write interface + public org.omg.CORBA.StringDef create_string (int bound) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_string", true); + $out.write_ulong (bound); + $in = _invoke ($out); + org.omg.CORBA.StringDef $result = org.omg.CORBA.StringDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_string (bound ); + } finally { + _releaseReply ($in); + } + } // create_string + + public org.omg.CORBA.SequenceDef create_sequence (int bound, org.omg.CORBA.IDLType element_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_sequence", true); + $out.write_ulong (bound); + org.omg.CORBA.IDLTypeHelper.write ($out, element_type); + $in = _invoke ($out); + org.omg.CORBA.SequenceDef $result = org.omg.CORBA.SequenceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_sequence (bound, element_type ); + } finally { + _releaseReply ($in); + } + } // create_sequence + + public org.omg.CORBA.ArrayDef create_array (int length, org.omg.CORBA.IDLType element_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_array", true); + $out.write_ulong (length); + org.omg.CORBA.IDLTypeHelper.write ($out, element_type); + $in = _invoke ($out); + org.omg.CORBA.ArrayDef $result = org.omg.CORBA.ArrayDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_array (length, element_type ); + } finally { + _releaseReply ($in); + } + } // create_array + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/Repository:1.0", + "IDL:omg.org/CORBA/Container:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _RepositoryStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_SequenceDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_SequenceDefStub.java new file mode 100644 index 000000000..eac0a0a0a --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_SequenceDefStub.java @@ -0,0 +1,207 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_SequenceDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _SequenceDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.SequenceDef +{ + + public int bound () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_bound", true); + $in = _invoke ($out); + int $result = $in.read_ulong (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return bound ( ); + } finally { + _releaseReply ($in); + } + } // bound + + public void bound (int newBound) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_bound", true); + $out.write_ulong (newBound); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + bound (newBound ); + } finally { + _releaseReply ($in); + } + } // bound + + public org.omg.CORBA.TypeCode element_type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_element_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return element_type ( ); + } finally { + _releaseReply ($in); + } + } // element_type + + public org.omg.CORBA.IDLType element_type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_element_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return element_type_def ( ); + } finally { + _releaseReply ($in); + } + } // element_type_def + + public void element_type_def (org.omg.CORBA.IDLType newElement_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_element_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newElement_type_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + element_type_def (newElement_type_def ); + } finally { + _releaseReply ($in); + } + } // element_type_def + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/SequenceDef:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _SequenceDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_StringDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_StringDefStub.java new file mode 100644 index 000000000..164185496 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_StringDefStub.java @@ -0,0 +1,150 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_StringDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _StringDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.StringDef +{ + + public int bound () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_bound", true); + $in = _invoke ($out); + int $result = $in.read_ulong (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return bound ( ); + } finally { + _releaseReply ($in); + } + } // bound + + public void bound (int newBound) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_bound", true); + $out.write_ulong (newBound); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + bound (newBound ); + } finally { + _releaseReply ($in); + } + } // bound + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/StringDef:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _StringDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_StructDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_StructDefStub.java new file mode 100644 index 000000000..eeb02d718 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_StructDefStub.java @@ -0,0 +1,727 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_StructDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _StructDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.StructDef +{ + + public org.omg.CORBA.StructMember[] members () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_members", true); + $in = _invoke ($out); + org.omg.CORBA.StructMember $result[] = org.omg.CORBA.StructMemberSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return members ( ); + } finally { + _releaseReply ($in); + } + } // members + + public void members (org.omg.CORBA.StructMember[] newMembers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_members", true); + org.omg.CORBA.StructMemberSeqHelper.write ($out, newMembers); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + members (newMembers ); + } finally { + _releaseReply ($in); + } + } // members + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/StructDef:1.0", + "IDL:omg.org/CORBA/TypedefDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/Container:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _StructDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_TypedefDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_TypedefDefStub.java new file mode 100644 index 000000000..83c4f6a5f --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_TypedefDefStub.java @@ -0,0 +1,332 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_TypedefDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _TypedefDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.TypedefDef +{ + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/TypedefDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/IDLType:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _TypedefDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_UnionDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_UnionDefStub.java new file mode 100644 index 000000000..b57fd2fcc --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_UnionDefStub.java @@ -0,0 +1,784 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_UnionDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _UnionDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.UnionDef +{ + + public org.omg.CORBA.TypeCode discriminator_type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_discriminator_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return discriminator_type ( ); + } finally { + _releaseReply ($in); + } + } // discriminator_type + + public org.omg.CORBA.IDLType discriminator_type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_discriminator_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return discriminator_type_def ( ); + } finally { + _releaseReply ($in); + } + } // discriminator_type_def + + public void discriminator_type_def (org.omg.CORBA.IDLType newDiscriminator_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_discriminator_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newDiscriminator_type_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + discriminator_type_def (newDiscriminator_type_def ); + } finally { + _releaseReply ($in); + } + } // discriminator_type_def + + public org.omg.CORBA.UnionMember[] members () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_members", true); + $in = _invoke ($out); + org.omg.CORBA.UnionMember $result[] = org.omg.CORBA.UnionMemberSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return members ( ); + } finally { + _releaseReply ($in); + } + } // members + + public void members (org.omg.CORBA.UnionMember[] newMembers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_members", true); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, newMembers); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + members (newMembers ); + } finally { + _releaseReply ($in); + } + } // members + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/UnionDef:1.0", + "IDL:omg.org/CORBA/TypedefDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/Container:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _UnionDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ValueBoxDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ValueBoxDefStub.java new file mode 100644 index 000000000..e95b7a182 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ValueBoxDefStub.java @@ -0,0 +1,150 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ValueBoxDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:24 PM EST +*/ + +public class _ValueBoxDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ValueBoxDef +{ + + public org.omg.CORBA.IDLType original_type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_original_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return original_type_def ( ); + } finally { + _releaseReply ($in); + } + } // original_type_def + + public void original_type_def (org.omg.CORBA.IDLType newOriginal_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_original_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newOriginal_type_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + original_type_def (newOriginal_type_def ); + } finally { + _releaseReply ($in); + } + } // original_type_def + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ValueBoxDef:1.0", + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ValueBoxDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ValueDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ValueDefStub.java new file mode 100644 index 000000000..101a38cb1 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ValueDefStub.java @@ -0,0 +1,1118 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ValueDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + +public class _ValueDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ValueDef +{ + + + // read/write interface + public org.omg.CORBA.InterfaceDef[] supported_interfaces () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_supported_interfaces", true); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result[] = org.omg.CORBA.InterfaceDefSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return supported_interfaces ( ); + } finally { + _releaseReply ($in); + } + } // supported_interfaces + + + // read/write interface + public void supported_interfaces (org.omg.CORBA.InterfaceDef[] newSupported_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_supported_interfaces", true); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, newSupported_interfaces); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + supported_interfaces (newSupported_interfaces ); + } finally { + _releaseReply ($in); + } + } // supported_interfaces + + public org.omg.CORBA.Initializer[] initializers () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_initializers", true); + $in = _invoke ($out); + org.omg.CORBA.Initializer $result[] = org.omg.CORBA.InitializerSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return initializers ( ); + } finally { + _releaseReply ($in); + } + } // initializers + + public void initializers (org.omg.CORBA.Initializer[] newInitializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_initializers", true); + org.omg.CORBA.InitializerSeqHelper.write ($out, newInitializers); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + initializers (newInitializers ); + } finally { + _releaseReply ($in); + } + } // initializers + + public org.omg.CORBA.ValueDef base_value () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_base_value", true); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return base_value ( ); + } finally { + _releaseReply ($in); + } + } // base_value + + public void base_value (org.omg.CORBA.ValueDef newBase_value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_base_value", true); + org.omg.CORBA.ValueDefHelper.write ($out, newBase_value); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + base_value (newBase_value ); + } finally { + _releaseReply ($in); + } + } // base_value + + public org.omg.CORBA.ValueDef[] abstract_base_values () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_abstract_base_values", true); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result[] = org.omg.CORBA.ValueDefSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return abstract_base_values ( ); + } finally { + _releaseReply ($in); + } + } // abstract_base_values + + public void abstract_base_values (org.omg.CORBA.ValueDef[] newAbstract_base_values) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_abstract_base_values", true); + org.omg.CORBA.ValueDefSeqHelper.write ($out, newAbstract_base_values); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + abstract_base_values (newAbstract_base_values ); + } finally { + _releaseReply ($in); + } + } // abstract_base_values + + public boolean is_abstract () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_is_abstract", true); + $in = _invoke ($out); + boolean $result = $in.read_boolean (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return is_abstract ( ); + } finally { + _releaseReply ($in); + } + } // is_abstract + + public void is_abstract (boolean newIs_abstract) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_is_abstract", true); + $out.write_boolean (newIs_abstract); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + is_abstract (newIs_abstract ); + } finally { + _releaseReply ($in); + } + } // is_abstract + + public boolean is_custom () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_is_custom", true); + $in = _invoke ($out); + boolean $result = $in.read_boolean (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return is_custom ( ); + } finally { + _releaseReply ($in); + } + } // is_custom + + public void is_custom (boolean newIs_custom) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_is_custom", true); + $out.write_boolean (newIs_custom); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + is_custom (newIs_custom ); + } finally { + _releaseReply ($in); + } + } // is_custom + + public byte flags () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_flags", true); + $in = _invoke ($out); + byte $result = $in.read_octet (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return flags ( ); + } finally { + _releaseReply ($in); + } + } // flags + + public void flags (byte newFlags) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_flags", true); + $out.write_octet (newFlags); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + flags (newFlags ); + } finally { + _releaseReply ($in); + } + } // flags + + + // always 0 + public boolean has_safe_base () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_has_safe_base", true); + $in = _invoke ($out); + boolean $result = $in.read_boolean (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return has_safe_base ( ); + } finally { + _releaseReply ($in); + } + } // has_safe_base + + + // always 0 + public void has_safe_base (boolean newHas_safe_base) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_has_safe_base", true); + $out.write_boolean (newHas_safe_base); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + has_safe_base (newHas_safe_base ); + } finally { + _releaseReply ($in); + } + } // has_safe_base + + + // read interface + public boolean is_a (String value_id) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("is_a", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, value_id); + $in = _invoke ($out); + boolean $result = $in.read_boolean (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return is_a (value_id ); + } finally { + _releaseReply ($in); + } + } // is_a + + public org.omg.CORBA.ValueDefPackage.FullValueDescription describe_value () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_value", true); + $in = _invoke ($out); + org.omg.CORBA.ValueDefPackage.FullValueDescription $result = org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_value ( ); + } finally { + _releaseReply ($in); + } + } // describe_value + + + // write interface + public org.omg.CORBA.ValueMemberDef create_value_member (String id, String name, String version, org.omg.CORBA.IDLType type_def, short access) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_member", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type_def); + org.omg.CORBA.VisibilityHelper.write ($out, access); + $in = _invoke ($out); + org.omg.CORBA.ValueMemberDef $result = org.omg.CORBA.ValueMemberDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_member (id, name, version, type_def, access ); + } finally { + _releaseReply ($in); + } + } // create_value_member + + public org.omg.CORBA.AttributeDef create_attribute (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.AttributeMode mode) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_attribute", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + org.omg.CORBA.AttributeModeHelper.write ($out, mode); + $in = _invoke ($out); + org.omg.CORBA.AttributeDef $result = org.omg.CORBA.AttributeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_attribute (id, name, version, type, mode ); + } finally { + _releaseReply ($in); + } + } // create_attribute + + public org.omg.CORBA.OperationDef create_operation (String id, String name, String version, org.omg.CORBA.IDLType result, org.omg.CORBA.OperationMode mode, org.omg.CORBA.ParameterDescription[] params, org.omg.CORBA.ExceptionDef[] exceptions, String[] contexts) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_operation", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, result); + org.omg.CORBA.OperationModeHelper.write ($out, mode); + org.omg.CORBA.ParDescriptionSeqHelper.write ($out, params); + org.omg.CORBA.ExceptionDefSeqHelper.write ($out, exceptions); + org.omg.CORBA.ContextIdSeqHelper.write ($out, contexts); + $in = _invoke ($out); + org.omg.CORBA.OperationDef $result = org.omg.CORBA.OperationDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_operation (id, name, version, result, mode, params, exceptions, contexts ); + } finally { + _releaseReply ($in); + } + } // create_operation + + + // read interface + public org.omg.CORBA.Contained lookup (String search_name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup", true); + org.omg.CORBA.ScopedNameHelper.write ($out, search_name); + $in = _invoke ($out); + org.omg.CORBA.Contained $result = org.omg.CORBA.ContainedHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup (search_name ); + } finally { + _releaseReply ($in); + } + } // lookup + + public org.omg.CORBA.Contained[] contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return contents (limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // contents + + public org.omg.CORBA.Contained[] lookup_name (String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("lookup_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, search_name); + $out.write_long (levels_to_search); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $in = _invoke ($out); + org.omg.CORBA.Contained $result[] = org.omg.CORBA.ContainedSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return lookup_name (search_name, levels_to_search, limit_type, exclude_inherited ); + } finally { + _releaseReply ($in); + } + } // lookup_name + + public org.omg.CORBA.ContainerPackage.Description[] describe_contents (org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe_contents", true); + org.omg.CORBA.DefinitionKindHelper.write ($out, limit_type); + $out.write_boolean (exclude_inherited); + $out.write_long (max_returned_objs); + $in = _invoke ($out); + org.omg.CORBA.ContainerPackage.Description $result[] = org.omg.CORBA.ContainerPackage.DescriptionSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe_contents (limit_type, exclude_inherited, max_returned_objs ); + } finally { + _releaseReply ($in); + } + } // describe_contents + + + // write interface + public org.omg.CORBA.ModuleDef create_module (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_module", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.ModuleDef $result = org.omg.CORBA.ModuleDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_module (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_module + + public org.omg.CORBA.ConstantDef create_constant (String id, String name, String version, org.omg.CORBA.IDLType type, org.omg.CORBA.Any value) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_constant", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, type); + $out.write_any (value); + $in = _invoke ($out); + org.omg.CORBA.ConstantDef $result = org.omg.CORBA.ConstantDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_constant (id, name, version, type, value ); + } finally { + _releaseReply ($in); + } + } // create_constant + + public org.omg.CORBA.StructDef create_struct (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_struct", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.StructDef $result = org.omg.CORBA.StructDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_struct (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_struct + + public org.omg.CORBA.UnionDef create_union (String id, String name, String version, org.omg.CORBA.IDLType discriminator_type, org.omg.CORBA.UnionMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_union", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, discriminator_type); + org.omg.CORBA.UnionMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.UnionDef $result = org.omg.CORBA.UnionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_union (id, name, version, discriminator_type, members ); + } finally { + _releaseReply ($in); + } + } // create_union + + public org.omg.CORBA.EnumDef create_enum (String id, String name, String version, String[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_enum", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.EnumMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.EnumDef $result = org.omg.CORBA.EnumDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_enum (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_enum + + public org.omg.CORBA.AliasDef create_alias (String id, String name, String version, org.omg.CORBA.IDLType original_type) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_alias", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type); + $in = _invoke ($out); + org.omg.CORBA.AliasDef $result = org.omg.CORBA.AliasDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_alias (id, name, version, original_type ); + } finally { + _releaseReply ($in); + } + } // create_alias + + public org.omg.CORBA.ExceptionDef create_exception (String id, String name, String version, org.omg.CORBA.StructMember[] members) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_exception", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.StructMemberSeqHelper.write ($out, members); + $in = _invoke ($out); + org.omg.CORBA.ExceptionDef $result = org.omg.CORBA.ExceptionDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_exception (id, name, version, members ); + } finally { + _releaseReply ($in); + } + } // create_exception + + public org.omg.CORBA.InterfaceDef create_interface (String id, String name, String version, boolean is_abstract, org.omg.CORBA.InterfaceDef[] base_interfaces) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_interface", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_abstract); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, base_interfaces); + $in = _invoke ($out); + org.omg.CORBA.InterfaceDef $result = org.omg.CORBA.InterfaceDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_interface (id, name, version, is_abstract, base_interfaces ); + } finally { + _releaseReply ($in); + } + } // create_interface + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueDef create_value (String id, String name, String version, boolean is_custom, boolean is_abstract, byte flags, org.omg.CORBA.ValueDef base_value, boolean has_safe_base, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $out.write_boolean (is_custom); + $out.write_boolean (is_abstract); + $out.write_octet (flags); + org.omg.CORBA.ValueDefHelper.write ($out, base_value); + $out.write_boolean (has_safe_base); + org.omg.CORBA.ValueDefSeqHelper.write ($out, abstract_base_values); + org.omg.CORBA.InterfaceDefSeqHelper.write ($out, supported_interfaces); + org.omg.CORBA.InitializerSeqHelper.write ($out, initializers); + $in = _invoke ($out); + org.omg.CORBA.ValueDef $result = org.omg.CORBA.ValueDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value (id, name, version, is_custom, is_abstract, flags, base_value, has_safe_base, abstract_base_values, supported_interfaces, initializers ); + } finally { + _releaseReply ($in); + } + } // create_value + + + // orbos 98-01-18: Objects By Value + public org.omg.CORBA.ValueBoxDef create_value_box (String id, String name, String version, org.omg.CORBA.IDLType original_type_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_value_box", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + org.omg.CORBA.IDLTypeHelper.write ($out, original_type_def); + $in = _invoke ($out); + org.omg.CORBA.ValueBoxDef $result = org.omg.CORBA.ValueBoxDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_value_box (id, name, version, original_type_def ); + } finally { + _releaseReply ($in); + } + } // create_value_box + + public org.omg.CORBA.NativeDef create_native (String id, String name, String version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("create_native", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, id); + org.omg.CORBA.IdentifierHelper.write ($out, name); + org.omg.CORBA.VersionSpecHelper.write ($out, version); + $in = _invoke ($out); + org.omg.CORBA.NativeDef $result = org.omg.CORBA.NativeDefHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return create_native (id, name, version ); + } finally { + _releaseReply ($in); + } + } // create_native + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ValueDef:1.0", + "IDL:omg.org/CORBA/Container:1.0", + "IDL:omg.org/CORBA/IRObject:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IDLType:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ValueDefStub diff --git a/idlj/src/test/masters/ir/org/omg/CORBA/_ValueMemberDefStub.java b/idlj/src/test/masters/ir/org/omg/CORBA/_ValueMemberDefStub.java new file mode 100644 index 000000000..79a612120 --- /dev/null +++ b/idlj/src/test/masters/ir/org/omg/CORBA/_ValueMemberDefStub.java @@ -0,0 +1,409 @@ +package org.omg.CORBA; + + +/** +* org/omg/CORBA/_ValueMemberDefStub.java . +* IGNORE Generated by the IDL-to-Java compiler (portable), version "3.2" +* from idlj/src/main/java/com/sun/tools/corba/ee/idl/ir.idl +* IGNORE Sunday, January 21, 2018 1:54:23 PM EST +*/ + + +// orbos 98-01-18: Objects By Value -- begin +public class _ValueMemberDefStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.ValueMemberDef +{ + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type", true); + $in = _invoke ($out); + org.omg.CORBA.TypeCode $result = $in.read_TypeCode (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type ( ); + } finally { + _releaseReply ($in); + } + } // type + + public org.omg.CORBA.IDLType type_def () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_type_def", true); + $in = _invoke ($out); + org.omg.CORBA.IDLType $result = org.omg.CORBA.IDLTypeHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return type_def ( ); + } finally { + _releaseReply ($in); + } + } // type_def + + public void type_def (org.omg.CORBA.IDLType newType_def) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_type_def", true); + org.omg.CORBA.IDLTypeHelper.write ($out, newType_def); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + type_def (newType_def ); + } finally { + _releaseReply ($in); + } + } // type_def + + public short access () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_access", true); + $in = _invoke ($out); + short $result = org.omg.CORBA.VisibilityHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return access ( ); + } finally { + _releaseReply ($in); + } + } // access + + public void access (short newAccess) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_access", true); + org.omg.CORBA.VisibilityHelper.write ($out, newAccess); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + access (newAccess ); + } finally { + _releaseReply ($in); + } + } // access + + + // read/write interface + public String id () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_id", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.RepositoryIdHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return id ( ); + } finally { + _releaseReply ($in); + } + } // id + + + // read/write interface + public void id (String newId) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_id", true); + org.omg.CORBA.RepositoryIdHelper.write ($out, newId); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + id (newId ); + } finally { + _releaseReply ($in); + } + } // id + + public String name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.IdentifierHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return name ( ); + } finally { + _releaseReply ($in); + } + } // name + + public void name (String newName) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_name", true); + org.omg.CORBA.IdentifierHelper.write ($out, newName); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + name (newName ); + } finally { + _releaseReply ($in); + } + } // name + + public String version () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_version", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.VersionSpecHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return version ( ); + } finally { + _releaseReply ($in); + } + } // version + + public void version (String newVersion) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_set_version", true); + org.omg.CORBA.VersionSpecHelper.write ($out, newVersion); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + version (newVersion ); + } finally { + _releaseReply ($in); + } + } // version + + + // read interface + public org.omg.CORBA.Container defined_in () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_defined_in", true); + $in = _invoke ($out); + org.omg.CORBA.Container $result = org.omg.CORBA.ContainerHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return defined_in ( ); + } finally { + _releaseReply ($in); + } + } // defined_in + + public String absolute_name () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_absolute_name", true); + $in = _invoke ($out); + String $result = org.omg.CORBA.ScopedNameHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return absolute_name ( ); + } finally { + _releaseReply ($in); + } + } // absolute_name + + public org.omg.CORBA.Repository containing_repository () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_containing_repository", true); + $in = _invoke ($out); + org.omg.CORBA.Repository $result = org.omg.CORBA.RepositoryHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return containing_repository ( ); + } finally { + _releaseReply ($in); + } + } // containing_repository + + public org.omg.CORBA.ContainedPackage.Description describe () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("describe", true); + $in = _invoke ($out); + org.omg.CORBA.ContainedPackage.Description $result = org.omg.CORBA.ContainedPackage.DescriptionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return describe ( ); + } finally { + _releaseReply ($in); + } + } // describe + + + // write interface + public void move (org.omg.CORBA.Container new_container, String new_name, String new_version) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("move", true); + org.omg.CORBA.ContainerHelper.write ($out, new_container); + org.omg.CORBA.IdentifierHelper.write ($out, new_name); + org.omg.CORBA.VersionSpecHelper.write ($out, new_version); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + move (new_container, new_name, new_version ); + } finally { + _releaseReply ($in); + } + } // move + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("_get_def_kind", true); + $in = _invoke ($out); + org.omg.CORBA.DefinitionKind $result = org.omg.CORBA.DefinitionKindHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return def_kind ( ); + } finally { + _releaseReply ($in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("destroy", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + destroy ( ); + } finally { + _releaseReply ($in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/ValueMemberDef:1.0", + "IDL:omg.org/CORBA/Contained:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _ValueMemberDefStub diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStruct.java b/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStruct.java new file mode 100644 index 000000000..bbf292e58 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStruct.java @@ -0,0 +1,26 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/AnyStruct.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class AnyStruct implements org.omg.CORBA.portable.IDLEntity +{ + public org.omg.CORBA.Any a = null; + public org.glassfish.idlj.CORBAStruct s = null; + + public AnyStruct () + { + } // ctor + + public AnyStruct (org.omg.CORBA.Any _a, org.glassfish.idlj.CORBAStruct _s) + { + a = _a; + s = _s; + } // ctor + +} // class AnyStruct diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStructHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStructHelper.java new file mode 100644 index 000000000..2be198485 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStructHelper.java @@ -0,0 +1,82 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/AnyStructHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class AnyStructHelper +{ + private static String _id = "IDL:org/glassfish/idlj/AnyStruct:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.AnyStruct that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.AnyStruct extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[0] = new org.omg.CORBA.StructMember ( + "a", + _tcOf_members0, + null); + _tcOf_members0 = org.glassfish.idlj.CORBAStructHelper.type (); + _members0[1] = new org.omg.CORBA.StructMember ( + "s", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.glassfish.idlj.AnyStructHelper.id (), "AnyStruct", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.AnyStruct read (org.omg.CORBA.portable.InputStream istream) + { + org.glassfish.idlj.AnyStruct value = new org.glassfish.idlj.AnyStruct (); + value.a = istream.read_any (); + value.s = org.glassfish.idlj.CORBAStructHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.AnyStruct value) + { + ostream.write_any (value.a); + org.glassfish.idlj.CORBAStructHelper.write (ostream, value.s); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStructHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStructHolder.java new file mode 100644 index 000000000..ceb9ccc4d --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/AnyStructHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj; + +/** +* org/glassfish/idlj/AnyStructHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class AnyStructHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.AnyStruct value = null; + + public AnyStructHolder () + { + } + + public AnyStructHolder (org.glassfish.idlj.AnyStruct initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.AnyStructHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.AnyStructHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.AnyStructHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnum.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnum.java new file mode 100644 index 000000000..7f1c926a5 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnum.java @@ -0,0 +1,42 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAEnum.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public class CORBAEnum implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 3; + private static org.glassfish.idlj.CORBAEnum[] __array = new org.glassfish.idlj.CORBAEnum [__size]; + + public static final int _ONE = 0; + public static final org.glassfish.idlj.CORBAEnum ONE = new org.glassfish.idlj.CORBAEnum(_ONE); + public static final int _TWO = 1; + public static final org.glassfish.idlj.CORBAEnum TWO = new org.glassfish.idlj.CORBAEnum(_TWO); + public static final int _THREE = 2; + public static final org.glassfish.idlj.CORBAEnum THREE = new org.glassfish.idlj.CORBAEnum(_THREE); + + public int value () + { + return __value; + } + + public static org.glassfish.idlj.CORBAEnum from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected CORBAEnum (int value) + { + __value = value; + __array[__value] = this; + } +} // class CORBAEnum diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnumHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnumHelper.java new file mode 100644 index 000000000..55a972e04 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnumHelper.java @@ -0,0 +1,53 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAEnumHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class CORBAEnumHelper +{ + private static String _id = "IDL:org/glassfish/idlj/CORBAEnum:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAEnum that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAEnum extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.glassfish.idlj.CORBAEnumHelper.id (), "CORBAEnum", new String[] { "ONE", "TWO", "THREE"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAEnum read (org.omg.CORBA.portable.InputStream istream) + { + return org.glassfish.idlj.CORBAEnum.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAEnum value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnumHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnumHolder.java new file mode 100644 index 000000000..807e8b1cf --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAEnumHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj; + +/** +* org/glassfish/idlj/CORBAEnumHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBAEnumHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAEnum value = null; + + public CORBAEnumHolder () + { + } + + public CORBAEnumHolder (org.glassfish.idlj.CORBAEnum initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBAEnumHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBAEnumHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBAEnumHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBASeqHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBASeqHelper.java new file mode 100644 index 000000000..42bcfe75b --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBASeqHelper.java @@ -0,0 +1,62 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBASeqHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class CORBASeqHelper +{ + private static String _id = "IDL:org/glassfish/idlj/CORBASeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAStruct[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAStruct[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.glassfish.idlj.CORBAStructHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.glassfish.idlj.CORBASeqHelper.id (), "CORBASeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAStruct[] read (org.omg.CORBA.portable.InputStream istream) + { + org.glassfish.idlj.CORBAStruct value[] = null; + int _len0 = istream.read_long (); + value = new org.glassfish.idlj.CORBAStruct[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.glassfish.idlj.CORBAStructHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAStruct[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.glassfish.idlj.CORBAStructHelper.write (ostream, value[_i0]); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBASeqHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBASeqHolder.java new file mode 100644 index 000000000..37a593a78 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBASeqHolder.java @@ -0,0 +1,39 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBASeqHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBASeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAStruct value[] = null; + + public CORBASeqHolder () + { + } + + public CORBASeqHolder (org.glassfish.idlj.CORBAStruct[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBASeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBASeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBASeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTest.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTest.java new file mode 100644 index 000000000..b6ebd02d9 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTest.java @@ -0,0 +1,13 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAServerTest.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public interface CORBAServerTest extends CORBAServerTestOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} // interface CORBAServerTest diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestHelper.java new file mode 100644 index 000000000..2473cf869 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestHelper.java @@ -0,0 +1,85 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAServerTestHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class CORBAServerTestHelper +{ + private static String _id = "IDL:org/glassfish/idlj/CORBAServerTest:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAServerTest that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAServerTest extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.glassfish.idlj.CORBAServerTestHelper.id (), "CORBAServerTest"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAServerTest read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_CORBAServerTestStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAServerTest value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.glassfish.idlj.CORBAServerTest narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.glassfish.idlj.CORBAServerTest) + return (org.glassfish.idlj.CORBAServerTest)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.glassfish.idlj._CORBAServerTestStub stub = new org.glassfish.idlj._CORBAServerTestStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.glassfish.idlj.CORBAServerTest unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.glassfish.idlj.CORBAServerTest) + return (org.glassfish.idlj.CORBAServerTest)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.glassfish.idlj._CORBAServerTestStub stub = new org.glassfish.idlj._CORBAServerTestStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestHolder.java new file mode 100644 index 000000000..b2ade7ca4 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj; + +/** +* org/glassfish/idlj/CORBAServerTestHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBAServerTestHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAServerTest value = null; + + public CORBAServerTestHolder () + { + } + + public CORBAServerTestHolder (org.glassfish.idlj.CORBAServerTest initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBAServerTestHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBAServerTestHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBAServerTestHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestOperations.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestOperations.java new file mode 100644 index 000000000..74f95de77 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestOperations.java @@ -0,0 +1,31 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAServerTestOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public interface CORBAServerTestOperations +{ + String test_primitive (String s, int l); + void test_oneway (String s, int l); + org.omg.CORBA.Any test_any (org.omg.CORBA.Any a); + void test_out (org.omg.CORBA.StringHolder s); + void test_inout (org.omg.CORBA.AnyHolder a); + void test_transaction (); + void test_subject (); + void test_exception () throws org.glassfish.idlj.CORBAServerTestPackage.AnException; + void test_exception2 () throws org.glassfish.idlj.CORBAServerTestPackage.MungedException; + String test_widestring (String w); + String test_timeout (int timeout); + String test_value (String w); + org.glassfish.idlj.CORBAUnion test_union (org.glassfish.idlj.CORBAUnionHolder u); + org.glassfish.idlj.CORBAStruct test_struct (org.glassfish.idlj.CORBAStruct s, org.glassfish.idlj.CORBAStructHolder os); + org.glassfish.idlj.CORBAStruct[] test_seq (org.glassfish.idlj.CORBASeqHolder seq); + int[] test_long_seq (org.glassfish.idlj.LongSeqHolder seq); + org.omg.CORBA.Object test_POA (String name); + void cleanup_POA (String name); +} // interface CORBAServerTestOperations diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnException.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnException.java new file mode 100644 index 000000000..782a7f9a5 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnException.java @@ -0,0 +1,25 @@ +package org.glassfish.idlj.CORBAServerTestPackage; + + +/** +* org/glassfish/idlj/CORBAServerTestPackage/AnException.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class AnException extends org.omg.CORBA.UserException +{ + + public AnException () + { + super(AnExceptionHelper.id()); + } // ctor + + + public AnException (String $reason) + { + super(AnExceptionHelper.id() + " " + $reason); + } // ctor + +} // class AnException diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHelper.java new file mode 100644 index 000000000..ebd75351e --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHelper.java @@ -0,0 +1,72 @@ +package org.glassfish.idlj.CORBAServerTestPackage; + + +/** +* org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class AnExceptionHelper +{ + private static String _id = "IDL:org/glassfish/idlj/CORBAServerTest/AnException:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAServerTestPackage.AnException that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAServerTestPackage.AnException extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.glassfish.idlj.CORBAServerTestPackage.AnExceptionHelper.id (), "AnException", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAServerTestPackage.AnException read (org.omg.CORBA.portable.InputStream istream) + { + org.glassfish.idlj.CORBAServerTestPackage.AnException value = new org.glassfish.idlj.CORBAServerTestPackage.AnException (); + // read and discard the repository ID + istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAServerTestPackage.AnException value) + { + // write the repository ID + ostream.write_string (id ()); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHolder.java new file mode 100644 index 000000000..9373391f0 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj.CORBAServerTestPackage; + +/** +* org/glassfish/idlj/CORBAServerTestPackage/AnExceptionHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class AnExceptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAServerTestPackage.AnException value = null; + + public AnExceptionHolder () + { + } + + public AnExceptionHolder (org.glassfish.idlj.CORBAServerTestPackage.AnException initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBAServerTestPackage.AnExceptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBAServerTestPackage.AnExceptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBAServerTestPackage.AnExceptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedException.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedException.java new file mode 100644 index 000000000..506b63278 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedException.java @@ -0,0 +1,25 @@ +package org.glassfish.idlj.CORBAServerTestPackage; + + +/** +* org/glassfish/idlj/CORBAServerTestPackage/MungedException.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class MungedException extends org.omg.CORBA.UserException +{ + + public MungedException () + { + super(MungedExceptionHelper.id()); + } // ctor + + + public MungedException (String $reason) + { + super(MungedExceptionHelper.id() + " " + $reason); + } // ctor + +} // class MungedException diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHelper.java new file mode 100644 index 000000000..b0a529822 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHelper.java @@ -0,0 +1,72 @@ +package org.glassfish.idlj.CORBAServerTestPackage; + + +/** +* org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class MungedExceptionHelper +{ + private static String _id = "IDL:org/glassfish/idlj/MungedExRepid:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAServerTestPackage.MungedException that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAServerTestPackage.MungedException extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.glassfish.idlj.CORBAServerTestPackage.MungedExceptionHelper.id (), "MungedException", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAServerTestPackage.MungedException read (org.omg.CORBA.portable.InputStream istream) + { + org.glassfish.idlj.CORBAServerTestPackage.MungedException value = new org.glassfish.idlj.CORBAServerTestPackage.MungedException (); + // read and discard the repository ID + istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAServerTestPackage.MungedException value) + { + // write the repository ID + ostream.write_string (id ()); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHolder.java new file mode 100644 index 000000000..ce2929f88 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj.CORBAServerTestPackage; + +/** +* org/glassfish/idlj/CORBAServerTestPackage/MungedExceptionHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class MungedExceptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAServerTestPackage.MungedException value = null; + + public MungedExceptionHolder () + { + } + + public MungedExceptionHolder (org.glassfish.idlj.CORBAServerTestPackage.MungedException initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBAServerTestPackage.MungedExceptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBAServerTestPackage.MungedExceptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBAServerTestPackage.MungedExceptionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStruct.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStruct.java new file mode 100644 index 000000000..de4072dd2 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStruct.java @@ -0,0 +1,32 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAStruct.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBAStruct implements org.omg.CORBA.portable.IDLEntity +{ + public int l = (int)0; + public long lll = (long)0; + + // The name is 3 chars long to avoid a JDK alignment bug. + public String s = null; + public org.omg.CORBA.Any a = null; + + public CORBAStruct () + { + } // ctor + + public CORBAStruct (int _l, long _lll, String _s, org.omg.CORBA.Any _a) + { + l = _l; + lll = _lll; + s = _s; + a = _a; + } // ctor + +} // class CORBAStruct diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStructHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStructHelper.java new file mode 100644 index 000000000..9f91c1bef --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStructHelper.java @@ -0,0 +1,96 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAStructHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class CORBAStructHelper +{ + private static String _id = "IDL:org/glassfish/idlj/CORBAStruct:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAStruct that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAStruct extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[0] = new org.omg.CORBA.StructMember ( + "l", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_longlong); + _members0[1] = new org.omg.CORBA.StructMember ( + "lll", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _members0[2] = new org.omg.CORBA.StructMember ( + "s", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[3] = new org.omg.CORBA.StructMember ( + "a", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.glassfish.idlj.CORBAStructHelper.id (), "CORBAStruct", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAStruct read (org.omg.CORBA.portable.InputStream istream) + { + org.glassfish.idlj.CORBAStruct value = new org.glassfish.idlj.CORBAStruct (); + value.l = istream.read_long (); + value.lll = istream.read_longlong (); + value.s = istream.read_string (); + value.a = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAStruct value) + { + ostream.write_long (value.l); + ostream.write_longlong (value.lll); + ostream.write_string (value.s); + ostream.write_any (value.a); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStructHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStructHolder.java new file mode 100644 index 000000000..78e98806d --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAStructHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj; + +/** +* org/glassfish/idlj/CORBAStructHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBAStructHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAStruct value = null; + + public CORBAStructHolder () + { + } + + public CORBAStructHolder (org.glassfish.idlj.CORBAStruct initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBAStructHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBAStructHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBAStructHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnion.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnion.java new file mode 100644 index 000000000..a3ebc88ef --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnion.java @@ -0,0 +1,207 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAUnion.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBAUnion implements org.omg.CORBA.portable.IDLEntity +{ + private boolean ___b; + private String ___w; + private String ___s; + private org.omg.CORBA.Any ___a; + private org.glassfish.idlj.CORBAStruct ___cs; + private long ___lll; + private int __discriminator; + private boolean __uninitialized = true; + + public CORBAUnion () + { + } + + public int discriminator () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + return __discriminator; + } + + public boolean b () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyb (__discriminator); + return ___b; + } + + public void b (boolean value) + { + __discriminator = 0; + ___b = value; + __uninitialized = false; + } + + public void b (int discriminator, boolean value) + { + verifyb (discriminator); + __discriminator = discriminator; + ___b = value; + __uninitialized = false; + } + + private void verifyb (int discriminator) + { + if (discriminator != 0) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public String w () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyw (__discriminator); + return ___w; + } + + public void w (String value) + { + __discriminator = 1; + ___w = value; + __uninitialized = false; + } + + public void w (int discriminator, String value) + { + verifyw (discriminator); + __discriminator = discriminator; + ___w = value; + __uninitialized = false; + } + + private void verifyw (int discriminator) + { + if (discriminator != 1) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public String s () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifys (__discriminator); + return ___s; + } + + public void s (String value) + { + __discriminator = 2; + ___s = value; + __uninitialized = false; + } + + public void s (int discriminator, String value) + { + verifys (discriminator); + __discriminator = discriminator; + ___s = value; + __uninitialized = false; + } + + private void verifys (int discriminator) + { + if (discriminator != 2) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public org.omg.CORBA.Any a () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifya (__discriminator); + return ___a; + } + + public void a (org.omg.CORBA.Any value) + { + __discriminator = 3; + ___a = value; + __uninitialized = false; + } + + public void a (int discriminator, org.omg.CORBA.Any value) + { + verifya (discriminator); + __discriminator = discriminator; + ___a = value; + __uninitialized = false; + } + + private void verifya (int discriminator) + { + if (discriminator != 3) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public org.glassfish.idlj.CORBAStruct cs () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifycs (__discriminator); + return ___cs; + } + + public void cs (org.glassfish.idlj.CORBAStruct value) + { + __discriminator = 4; + ___cs = value; + __uninitialized = false; + } + + public void cs (int discriminator, org.glassfish.idlj.CORBAStruct value) + { + verifycs (discriminator); + __discriminator = discriminator; + ___cs = value; + __uninitialized = false; + } + + private void verifycs (int discriminator) + { + if (discriminator != 4) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public long lll () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifylll (__discriminator); + return ___lll; + } + + public void lll (long value) + { + __discriminator = -2147483648; + ___lll = value; + __uninitialized = false; + } + + public void lll (int discriminator, long value) + { + verifylll (discriminator); + __discriminator = discriminator; + ___lll = value; + __uninitialized = false; + } + + private void verifylll (int discriminator) + { + if (discriminator == 0 || discriminator == 1 || discriminator == 2 || discriminator == 3 || discriminator == 4) + throw new org.omg.CORBA.BAD_OPERATION (); + } + +} // class CORBAUnion diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnionHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnionHelper.java new file mode 100644 index 000000000..138f72dc2 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnionHelper.java @@ -0,0 +1,175 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/CORBAUnionHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class CORBAUnionHelper +{ + private static String _id = "IDL:org/glassfish/idlj/CORBAUnion:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.CORBAUnion that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.CORBAUnion extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + org.omg.CORBA.TypeCode _disTypeCode0; + _disTypeCode0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + org.omg.CORBA.UnionMember[] _members0 = new org.omg.CORBA.UnionMember [6]; + org.omg.CORBA.TypeCode _tcOf_members0; + org.omg.CORBA.Any _anyOf_members0; + + // Branch for b (case label 0) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[0] = new org.omg.CORBA.UnionMember ( + "b", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for w (case label 1) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)1); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_wstring_tc (0); + _members0[1] = new org.omg.CORBA.UnionMember ( + "w", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for s (case label 2) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)2); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _members0[2] = new org.omg.CORBA.UnionMember ( + "s", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for a (case label 3) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)3); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[3] = new org.omg.CORBA.UnionMember ( + "a", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for cs (case label 4) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)4); + _tcOf_members0 = org.glassfish.idlj.CORBAStructHelper.type (); + _members0[4] = new org.omg.CORBA.UnionMember ( + "cs", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for lll (Default case) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_octet ((byte)0); // default member label + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_longlong); + _members0[5] = new org.omg.CORBA.UnionMember ( + "lll", + _anyOf_members0, + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_union_tc (org.glassfish.idlj.CORBAUnionHelper.id (), "CORBAUnion", _disTypeCode0, _members0); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.CORBAUnion read (org.omg.CORBA.portable.InputStream istream) + { + org.glassfish.idlj.CORBAUnion value = new org.glassfish.idlj.CORBAUnion (); + int _dis0 = (int)0; + _dis0 = istream.read_long (); + switch (_dis0) + { + case 0: + boolean _b = false; + _b = istream.read_boolean (); + value.b (_b); + break; + case 1: + String _w = null; + _w = istream.read_wstring (); + value.w (_w); + break; + case 2: + String _s = null; + _s = istream.read_string (); + value.s (_s); + break; + case 3: + org.omg.CORBA.Any _a = null; + _a = istream.read_any (); + value.a (_a); + break; + case 4: + org.glassfish.idlj.CORBAStruct _cs = null; + _cs = org.glassfish.idlj.CORBAStructHelper.read (istream); + value.cs (_cs); + break; + default: + long _lll = (long)0; + _lll = istream.read_longlong (); + value.lll (_dis0, _lll); + break; + } + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.CORBAUnion value) + { + ostream.write_long (value.discriminator ()); + switch (value.discriminator ()) + { + case 0: + ostream.write_boolean (value.b ()); + break; + case 1: + ostream.write_wstring (value.w ()); + break; + case 2: + ostream.write_string (value.s ()); + break; + case 3: + ostream.write_any (value.a ()); + break; + case 4: + org.glassfish.idlj.CORBAStructHelper.write (ostream, value.cs ()); + break; + default: + ostream.write_longlong (value.lll ()); + break; + } + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnionHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnionHolder.java new file mode 100644 index 000000000..a284b7be8 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/CORBAUnionHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj; + +/** +* org/glassfish/idlj/CORBAUnionHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class CORBAUnionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.CORBAUnion value = null; + + public CORBAUnionHolder () + { + } + + public CORBAUnionHolder (org.glassfish.idlj.CORBAUnion initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.CORBAUnionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.CORBAUnionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.CORBAUnionHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServer.java b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServer.java new file mode 100644 index 000000000..77e509d10 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServer.java @@ -0,0 +1,13 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/DummyCORBAServer.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public interface DummyCORBAServer extends DummyCORBAServerOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} // interface DummyCORBAServer diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerHelper.java new file mode 100644 index 000000000..56e2311d2 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerHelper.java @@ -0,0 +1,85 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/DummyCORBAServerHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class DummyCORBAServerHelper +{ + private static String _id = "IDL:org/glassfish/idlj/MungedRepid:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.glassfish.idlj.DummyCORBAServer that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.glassfish.idlj.DummyCORBAServer extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.glassfish.idlj.DummyCORBAServerHelper.id (), "DummyCORBAServer"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.glassfish.idlj.DummyCORBAServer read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_DummyCORBAServerStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.glassfish.idlj.DummyCORBAServer value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.glassfish.idlj.DummyCORBAServer narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.glassfish.idlj.DummyCORBAServer) + return (org.glassfish.idlj.DummyCORBAServer)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.glassfish.idlj._DummyCORBAServerStub stub = new org.glassfish.idlj._DummyCORBAServerStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.glassfish.idlj.DummyCORBAServer unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.glassfish.idlj.DummyCORBAServer) + return (org.glassfish.idlj.DummyCORBAServer)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.glassfish.idlj._DummyCORBAServerStub stub = new org.glassfish.idlj._DummyCORBAServerStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerHolder.java new file mode 100644 index 000000000..195620991 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerHolder.java @@ -0,0 +1,38 @@ +package org.glassfish.idlj; + +/** +* org/glassfish/idlj/DummyCORBAServerHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class DummyCORBAServerHolder implements org.omg.CORBA.portable.Streamable +{ + public org.glassfish.idlj.DummyCORBAServer value = null; + + public DummyCORBAServerHolder () + { + } + + public DummyCORBAServerHolder (org.glassfish.idlj.DummyCORBAServer initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.DummyCORBAServerHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.DummyCORBAServerHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.DummyCORBAServerHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerOperations.java b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerOperations.java new file mode 100644 index 000000000..7502a7dae --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/DummyCORBAServerOperations.java @@ -0,0 +1,13 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/DummyCORBAServerOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public interface DummyCORBAServerOperations +{ +} // interface DummyCORBAServerOperations diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/LongSeqHelper.java b/idlj/src/test/masters/structures/org/glassfish/idlj/LongSeqHelper.java new file mode 100644 index 000000000..5dd0e74cd --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/LongSeqHelper.java @@ -0,0 +1,60 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/LongSeqHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +abstract public class LongSeqHelper +{ + private static String _id = "IDL:org/glassfish/idlj/LongSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, int[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static int[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.glassfish.idlj.LongSeqHelper.id (), "LongSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static int[] read (org.omg.CORBA.portable.InputStream istream) + { + int value[] = null; + int _len0 = istream.read_long (); + value = new int[_len0]; + istream.read_long_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, int[] value) + { + ostream.write_long (value.length); + ostream.write_long_array (value, 0, value.length); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/LongSeqHolder.java b/idlj/src/test/masters/structures/org/glassfish/idlj/LongSeqHolder.java new file mode 100644 index 000000000..4f12db316 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/LongSeqHolder.java @@ -0,0 +1,39 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/LongSeqHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public final class LongSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public int value[] = null; + + public LongSeqHolder () + { + } + + public LongSeqHolder (int[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.glassfish.idlj.LongSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.glassfish.idlj.LongSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.glassfish.idlj.LongSeqHelper.type (); + } + +} diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/_CORBAServerTestImplBase.java b/idlj/src/test/masters/structures/org/glassfish/idlj/_CORBAServerTestImplBase.java new file mode 100644 index 000000000..24964d5bb --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/_CORBAServerTestImplBase.java @@ -0,0 +1,254 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/_CORBAServerTestImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public abstract class _CORBAServerTestImplBase extends org.omg.CORBA.portable.ObjectImpl + implements org.glassfish.idlj.CORBAServerTest, org.omg.CORBA.portable.InvokeHandler +{ + + // Constructors + public _CORBAServerTestImplBase () + { + } + + private static java.util.Map _methods = new java.util.HashMap (); + static + { + _methods.put ("test_primitive", 0); + _methods.put ("test_oneway", 1); + _methods.put ("test_any", 2); + _methods.put ("test_out", 3); + _methods.put ("test_inout", 4); + _methods.put ("test_transaction", 5); + _methods.put ("test_subject", 6); + _methods.put ("test_exception", 7); + _methods.put ("test_exception2", 8); + _methods.put ("test_widestring", 9); + _methods.put ("test_timeout", 10); + _methods.put ("test_value", 11); + _methods.put ("test_union", 12); + _methods.put ("test_struct", 13); + _methods.put ("test_seq", 14); + _methods.put ("test_long_seq", 15); + _methods.put ("test_POA", 16); + _methods.put ("cleanup_POA", 17); + } + + public org.omg.CORBA.portable.OutputStream _invoke (String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) + { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = _methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue ()) + { + case 0: // org/glassfish/idlj/CORBAServerTest/test_primitive + { + String s = in.read_string (); + int l = in.read_long (); + String $result = null; + $result = this.test_primitive (s, l); + out = $rh.createReply(); + out.write_string ($result); + break; + } + + case 1: // org/glassfish/idlj/CORBAServerTest/test_oneway + { + String s = in.read_string (); + int l = in.read_long (); + this.test_oneway (s, l); + out = $rh.createReply(); + break; + } + + case 2: // org/glassfish/idlj/CORBAServerTest/test_any + { + org.omg.CORBA.Any a = in.read_any (); + org.omg.CORBA.Any $result = null; + $result = this.test_any (a); + out = $rh.createReply(); + out.write_any ($result); + break; + } + + case 3: // org/glassfish/idlj/CORBAServerTest/test_out + { + org.omg.CORBA.StringHolder s = new org.omg.CORBA.StringHolder (); + this.test_out (s); + out = $rh.createReply(); + out.write_string (s.value); + break; + } + + case 4: // org/glassfish/idlj/CORBAServerTest/test_inout + { + org.omg.CORBA.AnyHolder a = new org.omg.CORBA.AnyHolder (); + a.value = in.read_any (); + this.test_inout (a); + out = $rh.createReply(); + out.write_any (a.value); + break; + } + + case 5: // org/glassfish/idlj/CORBAServerTest/test_transaction + { + this.test_transaction (); + out = $rh.createReply(); + break; + } + + case 6: // org/glassfish/idlj/CORBAServerTest/test_subject + { + this.test_subject (); + out = $rh.createReply(); + break; + } + + case 7: // org/glassfish/idlj/CORBAServerTest/test_exception + { + try { + this.test_exception (); + out = $rh.createReply(); + } catch (org.glassfish.idlj.CORBAServerTestPackage.AnException $ex) { + out = $rh.createExceptionReply (); + org.glassfish.idlj.CORBAServerTestPackage.AnExceptionHelper.write (out, $ex); + } + break; + } + + case 8: // org/glassfish/idlj/CORBAServerTest/test_exception2 + { + try { + this.test_exception2 (); + out = $rh.createReply(); + } catch (org.glassfish.idlj.CORBAServerTestPackage.MungedException $ex) { + out = $rh.createExceptionReply (); + org.glassfish.idlj.CORBAServerTestPackage.MungedExceptionHelper.write (out, $ex); + } + break; + } + + case 9: // org/glassfish/idlj/CORBAServerTest/test_widestring + { + String w = in.read_wstring (); + String $result = null; + $result = this.test_widestring (w); + out = $rh.createReply(); + out.write_wstring ($result); + break; + } + + case 10: // org/glassfish/idlj/CORBAServerTest/test_timeout + { + int timeout = in.read_long (); + String $result = null; + $result = this.test_timeout (timeout); + out = $rh.createReply(); + out.write_string ($result); + break; + } + + case 11: // org/glassfish/idlj/CORBAServerTest/test_value + { + String w = org.omg.CORBA.WStringValueHelper.read (in); + String $result = null; + $result = this.test_value (w); + out = $rh.createReply(); + org.omg.CORBA.WStringValueHelper.write (out, $result); + break; + } + + case 12: // org/glassfish/idlj/CORBAServerTest/test_union + { + org.glassfish.idlj.CORBAUnionHolder u = new org.glassfish.idlj.CORBAUnionHolder (); + u.value = org.glassfish.idlj.CORBAUnionHelper.read (in); + org.glassfish.idlj.CORBAUnion $result = null; + $result = this.test_union (u); + out = $rh.createReply(); + org.glassfish.idlj.CORBAUnionHelper.write (out, $result); + org.glassfish.idlj.CORBAUnionHelper.write (out, u.value); + break; + } + + case 13: // org/glassfish/idlj/CORBAServerTest/test_struct + { + org.glassfish.idlj.CORBAStruct s = org.glassfish.idlj.CORBAStructHelper.read (in); + org.glassfish.idlj.CORBAStructHolder os = new org.glassfish.idlj.CORBAStructHolder (); + org.glassfish.idlj.CORBAStruct $result = null; + $result = this.test_struct (s, os); + out = $rh.createReply(); + org.glassfish.idlj.CORBAStructHelper.write (out, $result); + org.glassfish.idlj.CORBAStructHelper.write (out, os.value); + break; + } + + case 14: // org/glassfish/idlj/CORBAServerTest/test_seq + { + org.glassfish.idlj.CORBASeqHolder seq = new org.glassfish.idlj.CORBASeqHolder (); + seq.value = org.glassfish.idlj.CORBASeqHelper.read (in); + org.glassfish.idlj.CORBAStruct $result[] = null; + $result = this.test_seq (seq); + out = $rh.createReply(); + org.glassfish.idlj.CORBASeqHelper.write (out, $result); + org.glassfish.idlj.CORBASeqHelper.write (out, seq.value); + break; + } + + case 15: // org/glassfish/idlj/CORBAServerTest/test_long_seq + { + org.glassfish.idlj.LongSeqHolder seq = new org.glassfish.idlj.LongSeqHolder (); + seq.value = org.glassfish.idlj.LongSeqHelper.read (in); + int $result[] = null; + $result = this.test_long_seq (seq); + out = $rh.createReply(); + org.glassfish.idlj.LongSeqHelper.write (out, $result); + org.glassfish.idlj.LongSeqHelper.write (out, seq.value); + break; + } + + case 16: // org/glassfish/idlj/CORBAServerTest/test_POA + { + String name = in.read_string (); + org.omg.CORBA.Object $result = null; + $result = this.test_POA (name); + out = $rh.createReply(); + org.omg.CORBA.ObjectHelper.write (out, $result); + break; + } + + case 17: // org/glassfish/idlj/CORBAServerTest/cleanup_POA + { + String name = in.read_string (); + this.cleanup_POA (name); + out = $rh.createReply(); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:org/glassfish/idlj/CORBAServerTest:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + +} // class _CORBAServerTestImplBase diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/_CORBAServerTestStub.java b/idlj/src/test/masters/structures/org/glassfish/idlj/_CORBAServerTestStub.java new file mode 100644 index 000000000..ae56fe8e0 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/_CORBAServerTestStub.java @@ -0,0 +1,411 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/_CORBAServerTestStub.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public class _CORBAServerTestStub extends org.omg.CORBA.portable.ObjectImpl implements org.glassfish.idlj.CORBAServerTest +{ + + public String test_primitive (String s, int l) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_primitive", true); + $out.write_string (s); + $out.write_long (l); + $in = _invoke ($out); + String $result = $in.read_string (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_primitive (s, l ); + } finally { + _releaseReply ($in); + } + } // test_primitive + + public void test_oneway (String s, int l) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_oneway", false); + $out.write_string (s); + $out.write_long (l); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_oneway (s, l ); + } finally { + _releaseReply ($in); + } + } // test_oneway + + public org.omg.CORBA.Any test_any (org.omg.CORBA.Any a) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_any", true); + $out.write_any (a); + $in = _invoke ($out); + org.omg.CORBA.Any $result = $in.read_any (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_any (a ); + } finally { + _releaseReply ($in); + } + } // test_any + + public void test_out (org.omg.CORBA.StringHolder s) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_out", true); + $in = _invoke ($out); + s.value = $in.read_string (); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_out (s ); + } finally { + _releaseReply ($in); + } + } // test_out + + public void test_inout (org.omg.CORBA.AnyHolder a) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_inout", true); + $out.write_any (a.value); + $in = _invoke ($out); + a.value = $in.read_any (); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_inout (a ); + } finally { + _releaseReply ($in); + } + } // test_inout + + public void test_transaction () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_transaction", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_transaction ( ); + } finally { + _releaseReply ($in); + } + } // test_transaction + + public void test_subject () + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_subject", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_subject ( ); + } finally { + _releaseReply ($in); + } + } // test_subject + + public void test_exception () throws org.glassfish.idlj.CORBAServerTestPackage.AnException + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_exception", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + if (_id.equals ("IDL:org/glassfish/idlj/CORBAServerTest/AnException:1.0")) + throw org.glassfish.idlj.CORBAServerTestPackage.AnExceptionHelper.read ($in); + else + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_exception ( ); + } finally { + _releaseReply ($in); + } + } // test_exception + + public void test_exception2 () throws org.glassfish.idlj.CORBAServerTestPackage.MungedException + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_exception2", true); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + if (_id.equals ("IDL:org/glassfish/idlj/MungedExRepid:1.0")) + throw org.glassfish.idlj.CORBAServerTestPackage.MungedExceptionHelper.read ($in); + else + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + test_exception2 ( ); + } finally { + _releaseReply ($in); + } + } // test_exception2 + + public String test_widestring (String w) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_widestring", true); + $out.write_wstring (w); + $in = _invoke ($out); + String $result = $in.read_wstring (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_widestring (w ); + } finally { + _releaseReply ($in); + } + } // test_widestring + + public String test_timeout (int timeout) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_timeout", true); + $out.write_long (timeout); + $in = _invoke ($out); + String $result = $in.read_string (); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_timeout (timeout ); + } finally { + _releaseReply ($in); + } + } // test_timeout + + public String test_value (String w) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_value", true); + org.omg.CORBA.WStringValueHelper.write ($out, w); + $in = _invoke ($out); + String $result = org.omg.CORBA.WStringValueHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_value (w ); + } finally { + _releaseReply ($in); + } + } // test_value + + public org.glassfish.idlj.CORBAUnion test_union (org.glassfish.idlj.CORBAUnionHolder u) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_union", true); + org.glassfish.idlj.CORBAUnionHelper.write ($out, u.value); + $in = _invoke ($out); + org.glassfish.idlj.CORBAUnion $result = org.glassfish.idlj.CORBAUnionHelper.read ($in); + u.value = org.glassfish.idlj.CORBAUnionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_union (u ); + } finally { + _releaseReply ($in); + } + } // test_union + + public org.glassfish.idlj.CORBAStruct test_struct (org.glassfish.idlj.CORBAStruct s, org.glassfish.idlj.CORBAStructHolder os) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_struct", true); + org.glassfish.idlj.CORBAStructHelper.write ($out, s); + $in = _invoke ($out); + org.glassfish.idlj.CORBAStruct $result = org.glassfish.idlj.CORBAStructHelper.read ($in); + os.value = org.glassfish.idlj.CORBAStructHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_struct (s, os ); + } finally { + _releaseReply ($in); + } + } // test_struct + + public org.glassfish.idlj.CORBAStruct[] test_seq (org.glassfish.idlj.CORBASeqHolder seq) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_seq", true); + org.glassfish.idlj.CORBASeqHelper.write ($out, seq.value); + $in = _invoke ($out); + org.glassfish.idlj.CORBAStruct $result[] = org.glassfish.idlj.CORBASeqHelper.read ($in); + seq.value = org.glassfish.idlj.CORBASeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_seq (seq ); + } finally { + _releaseReply ($in); + } + } // test_seq + + public int[] test_long_seq (org.glassfish.idlj.LongSeqHolder seq) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_long_seq", true); + org.glassfish.idlj.LongSeqHelper.write ($out, seq.value); + $in = _invoke ($out); + int $result[] = org.glassfish.idlj.LongSeqHelper.read ($in); + seq.value = org.glassfish.idlj.LongSeqHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_long_seq (seq ); + } finally { + _releaseReply ($in); + } + } // test_long_seq + + public org.omg.CORBA.Object test_POA (String name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("test_POA", true); + $out.write_string (name); + $in = _invoke ($out); + org.omg.CORBA.Object $result = org.omg.CORBA.ObjectHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return test_POA (name ); + } finally { + _releaseReply ($in); + } + } // test_POA + + public void cleanup_POA (String name) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("cleanup_POA", true); + $out.write_string (name); + $in = _invoke ($out); + return; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + cleanup_POA (name ); + } finally { + _releaseReply ($in); + } + } // cleanup_POA + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:org/glassfish/idlj/CORBAServerTest:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _CORBAServerTestStub diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/_DummyCORBAServerImplBase.java b/idlj/src/test/masters/structures/org/glassfish/idlj/_DummyCORBAServerImplBase.java new file mode 100644 index 000000000..7760f290f --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/_DummyCORBAServerImplBase.java @@ -0,0 +1,47 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/_DummyCORBAServerImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public abstract class _DummyCORBAServerImplBase extends org.omg.CORBA.portable.ObjectImpl + implements org.glassfish.idlj.DummyCORBAServer, org.omg.CORBA.portable.InvokeHandler +{ + + // Constructors + public _DummyCORBAServerImplBase () + { + } + + private static java.util.Map _methods = new java.util.HashMap (); + static + { + } + + public org.omg.CORBA.portable.OutputStream _invoke (String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) + { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = _methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:org/glassfish/idlj/MungedRepid:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + +} // class _DummyCORBAServerImplBase diff --git a/idlj/src/test/masters/structures/org/glassfish/idlj/_DummyCORBAServerStub.java b/idlj/src/test/masters/structures/org/glassfish/idlj/_DummyCORBAServerStub.java new file mode 100644 index 000000000..6d0b829f5 --- /dev/null +++ b/idlj/src/test/masters/structures/org/glassfish/idlj/_DummyCORBAServerStub.java @@ -0,0 +1,50 @@ +package org.glassfish.idlj; + + +/** +* org/glassfish/idlj/_DummyCORBAServerStub.java . +* Generated by the IDL-to-Java compiler (portable), version "4.1" +* from /Users/rgold/projects/glassfish/glassfish-corba/idlj/src/main/idl/org/glassfish/idlj/CORBAServerTest.idl +* Monday, January 29, 2018 11:19:41 AM EST +*/ + +public class _DummyCORBAServerStub extends org.omg.CORBA.portable.ObjectImpl implements org.glassfish.idlj.DummyCORBAServer +{ + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:org/glassfish/idlj/MungedRepid:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + org.omg.CORBA.Object obj = orb.string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } finally { + orb.destroy() ; + } + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props); + try { + String str = orb.object_to_string (this); + s.writeUTF (str); + } finally { + orb.destroy() ; + } + } +} // class _DummyCORBAServerStub diff --git a/iiop-folb-dev-test/OLD/createLog.1 b/iiop-folb-dev-test/OLD/createLog.1 new file mode 100644 index 000000000..ea7a7a018 --- /dev/null +++ b/iiop-folb-dev-test/OLD/createLog.1 @@ -0,0 +1,70 @@ ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin start-domain +Waiting for domain1 to start ... +Successfully started the domain : domain1 +domain Location: /space/work/GlassFish/v3/glassfish3/glassfish/domains/domain1 +Log File: /space/work/GlassFish/v3/glassfish3/glassfish/domains/domain1/logs/server.log +Admin Port: 4848 +Command start-domain executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin enable-secure-admin +Command enable-secure-admin executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin --user admin create-node-ssh --nodehost minas --installdir /volumes/work/GlassFish/v3/glassfish3 agent1 +Command create-node-ssh executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin create-cluster c1 +Command create-cluster executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin --host minas --port 4848 create-instance --cluster c1 --systemproperties instance_name=in1 --node agent1 in1 +Command _create-instance-filesystem executed successfully. +Port Assignments for server instance in1: +JMX_SYSTEM_CONNECTOR_PORT=28686 +JMS_PROVIDER_PORT=27676 +HTTP_LISTENER_PORT=28080 +ASADMIN_LISTENER_PORT=24848 +JAVA_DEBUGGER_PORT=29009 +IIOP_SSL_LISTENER_PORT=23820 +IIOP_LISTENER_PORT=23700 +OSGI_SHELL_TELNET_PORT=26666 +HTTP_SSL_LISTENER_PORT=28181 +IIOP_SSL_MUTUALAUTH_PORT=23920 +The instance, in1, was created on host minas +Command create-instance executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin --host minas --port 4848 create-instance --cluster c1 --systemproperties instance_name=in2 --node agent1 in2 +Using DAS host localhost and port 4848 from existing das.properties for node +agent1. To use a different DAS, create a new node using create-node-ssh or +create-node-config. Create the instance with the new node and correct +host and port: +asadmin --host das_host --port das_port create-local-instance --node node_name instance_name. +Command _create-instance-filesystem executed successfully. +Port Assignments for server instance in2: +JMX_SYSTEM_CONNECTOR_PORT=28687 +JMS_PROVIDER_PORT=27677 +HTTP_LISTENER_PORT=28081 +ASADMIN_LISTENER_PORT=24849 +JAVA_DEBUGGER_PORT=29010 +IIOP_SSL_LISTENER_PORT=23821 +IIOP_LISTENER_PORT=23701 +OSGI_SHELL_TELNET_PORT=26667 +HTTP_SSL_LISTENER_PORT=28182 +IIOP_SSL_MUTUALAUTH_PORT=23921 +The instance, in2, was created on host minas +Command create-instance executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin --host minas --port 4848 create-instance --cluster c1 --systemproperties instance_name=in3 --node agent1 in3 +Using DAS host localhost and port 4848 from existing das.properties for node +agent1. To use a different DAS, create a new node using create-node-ssh or +create-node-config. Create the instance with the new node and correct +host and port: +asadmin --host das_host --port das_port create-local-instance --node node_name instance_name. +Command _create-instance-filesystem executed successfully. +Port Assignments for server instance in3: +JMX_SYSTEM_CONNECTOR_PORT=28688 +JMS_PROVIDER_PORT=27678 +HTTP_LISTENER_PORT=28082 +ASADMIN_LISTENER_PORT=24850 +JAVA_DEBUGGER_PORT=29011 +IIOP_SSL_LISTENER_PORT=23822 +IIOP_LISTENER_PORT=23702 +OSGI_SHELL_TELNET_PORT=26668 +HTTP_SSL_LISTENER_PORT=28183 +IIOP_SSL_MUTUALAUTH_PORT=23922 +The instance, in3, was created on host minas +Command create-instance executed successfully. ++ /volumes/work/GlassFish/v3/glassfish3/glassfish/bin/asadmin --host minas --port 4848 start-cluster c1 +Command start-cluster executed successfully. diff --git a/iiop-folb-dev-test/OLD/createconfig.sh b/iiop-folb-dev-test/OLD/createconfig.sh new file mode 100644 index 000000000..ce566fab7 --- /dev/null +++ b/iiop-folb-dev-test/OLD/createconfig.sh @@ -0,0 +1,25 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +. ../cluster.props.ssh +S1AS_HOME="${instance1_s1as_home}/glassfish" +ASADMIN="${S1AS_HOME}/bin/asadmin" +set -x +${ASADMIN} start-domain +${ASADMIN} enable-secure-admin +${ASADMIN} --user admin create-node-ssh --nodehost ${das_node} --installdir ${instance1_s1as_home} agent1 +${ASADMIN} create-cluster ${cluster_name} +${ASADMIN} --host ${das_node} --port ${das_port} create-instance --cluster ${cluster_name} --systemproperties instance_name=in1 --node agent1 in1 + +${ASADMIN} --host ${das_node} --port ${das_port} create-instance --cluster ${cluster_name} --systemproperties instance_name=in2 --node agent1 in2 + +${ASADMIN} --host ${das_node} --port ${das_port} create-instance --cluster ${cluster_name} --systemproperties instance_name=in3 --node agent1 in3 + +${ASADMIN} --host ${das_node} --port ${das_port} start-cluster ${cluster_name} diff --git a/iiop-folb-dev-test/OLD/setup.sh b/iiop-folb-dev-test/OLD/setup.sh new file mode 100644 index 000000000..747e2e7ce --- /dev/null +++ b/iiop-folb-dev-test/OLD/setup.sh @@ -0,0 +1,18 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +. ../cluster.props +S1AS_HOME="${instance1_s1as_home}/glassfish" +ASADMIN="${S1AS_HOME}/bin/asadmin" +set -x +PROPS_FILE=${PWD}/logging.properties +${ASADMIN} create-system-properties --target ${cluster_name} "java.util.logging.config.file=${PROPS_FILE}" +${ASADMIN} create-system-properties java.util.logging.config.file=${PROPS_FILE} + diff --git a/iiop-folb-dev-test/OLD/test-debug.sh b/iiop-folb-dev-test/OLD/test-debug.sh new file mode 100755 index 000000000..f9254b4b7 --- /dev/null +++ b/iiop-folb-dev-test/OLD/test-debug.sh @@ -0,0 +1,36 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +set -x +. ../cluster.props +APS_HOME="test/OrbFailOver/build" +S1AS_HOME="${instance1_s1as_home}/glassfish" +ASADMIN="${S1AS_HOME}/bin/asadmin" +APPCLIENT="${S1AS_HOME}/bin/appclient" + +# HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT},${instance3_node}:${instance3_IIOP_LISTENER_PORT} +HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT} + +######### customized cluster creation +# ${ASADMIN} start-domain --debug +# ${ASADMIN} create-cluster ${cluster_name} +# ${ASADMIN} create-local-instance --cluster ${cluster_name} ${instance1_name} +# ${ASADMIN} create-local-instance --cluster ${cluster_name} ${instance2_name} +######### end customized cluster creation + +# ${ASADMIN} start-local-instance ${instance1_name} ; ${ASADMIN} start-local-instance ${instance2_name} + +${ASADMIN} deploy --target ${cluster_name} --force ${APS_HOME}/OrbFailOver-ejb.jar + +${APPCLIENT} -agentlib:jdwp=transport=dt_socket,address=8118,server=y,suspend=y -Djavax.enterprise.resource.corba.level=WARN -Djava.util.logging.level=WARN -Dcom.sun.appserv.iiop.endpoints=${HOST_PORTS} -client ${APS_HOME}/OrbFailOver-app-client.jar -targetserver ${HOST_PORTS} -name OrbFailOver-app-client $@ + +# sleep 30 +# ${ASADMIN} stop-instance ${instance1_name} + diff --git a/iiop-folb-dev-test/OLD/test-fo.sh b/iiop-folb-dev-test/OLD/test-fo.sh new file mode 100755 index 000000000..c903589e7 --- /dev/null +++ b/iiop-folb-dev-test/OLD/test-fo.sh @@ -0,0 +1,37 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +. ../cluster.props +APS_HOME="test/OrbFailOver/build" +S1AS_HOME="${instance1_s1as_home}/glassfish" +ASADMIN="${S1AS_HOME}/bin/asadmin" +APPCLIENT="${S1AS_HOME}/bin/appclient" +PROPS_FILE=${PWD}/logging.properties + +# HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT},${instance3_node}:${instance3_IIOP_LISTENER_PORT} +HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT} +INSTANCES=${instance1_name},${instance2_name},${instance3_name} + +set -x +${ASADMIN} deploy --target ${cluster_name} --force ${APS_HOME}/OrbFailOver-ejb.jar + +# ${APPCLIENT} -Djava.util.logging.config.file=${PROPS_FILE} -Dcom.sun.appserv.iiop.endpoints=${HOST_PORTS} -Dtest.folb.asadmin.command=${ASADMIN} -Dtest.folb.instances=${INSTANCES} -client ${APS_HOME}/OrbFailOver-app-client.jar -targetserver ${HOST_PORTS} -name OrbFailOver-app-client -failover + +${APPCLIENT} -agentlib:jdwp=transport=dt_socket,address=8118,server=y,suspend=y -Djava.util.logging.config.file=${PROPS_FILE} -Dcom.sun.appserv.iiop.endpoints=${HOST_PORTS} -Dtest.folb.asadmin.command=${ASADMIN} -Dtest.folb.instances=${INSTANCES} -client ${APS_HOME}/OrbFailOver-app-client.jar -targetserver ${HOST_PORTS} -name OrbFailOver-app-client -failover + +# sleep 25 +# ${ASADMIN} stop-instance ${instance3_name} + +# give some time for failover completion +# sleep 30 + +# Return, let the plugin (stop cluster) take control. + + diff --git a/iiop-folb-dev-test/OLD/test-lb.sh b/iiop-folb-dev-test/OLD/test-lb.sh new file mode 100755 index 000000000..b850619fc --- /dev/null +++ b/iiop-folb-dev-test/OLD/test-lb.sh @@ -0,0 +1,26 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +. ../cluster.props +APS_HOME="test/OrbFailOver/build" +S1AS_HOME="${instance1_s1as_home}/glassfish" +ASADMIN="${S1AS_HOME}/bin/asadmin" +APPCLIENT="${S1AS_HOME}/bin/appclient" +PROPS_FILE=${PWD}/logging.properties + +# HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT},${instance3_node}:${instance3_IIOP_LISTENER_PORT} +HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT} + +set -x +${ASADMIN} deploy --target ${cluster_name} --force ${APS_HOME}/OrbFailOver-ejb.jar + +#${APPCLIENT} -Djavax.enterprise.resource.corba.level=FINE -Djava.util.loggin.level=FINE -client ${APS_HOME}/OrbFailOver-app-client.jar -targetserver ${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT} -name OrbFailOver-app-client & + +${APPCLIENT} -Djava.util.logging.config.file=${PROPS_FILE} -client ${APS_HOME}/OrbFailOver-app-client.jar -targetserver ${HOST_PORTS} -name OrbFailOver-app-client -loadbalance diff --git a/iiop-folb-dev-test/OLD/testsac.sh b/iiop-folb-dev-test/OLD/testsac.sh new file mode 100755 index 000000000..600c07f8b --- /dev/null +++ b/iiop-folb-dev-test/OLD/testsac.sh @@ -0,0 +1,33 @@ +#! /bin/sh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +. ../cluster.props +APS_HOME="test/OrbFailOver/build" +S1AS_HOME="${instance1_s1as_home}/glassfish" +ASADMIN="${S1AS_HOME}/bin/asadmin" +SACLIENT="java -Drmiregistry.host=minas -classpath ${S1AS_HOME}/modules/gf-client.jar:${APS_HOME}/OrbFailOver-app-client.jar:${APS_HOME}/OrbFailOver-ejb.jar" + +PROPS_FILE=${PWD}/logging.properties +DEBUG_ARGS="-agentlib:jdwp=transport=dt_socket,address=8118,server=y,suspend=y" + +# HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT},${instance3_node}:${instance3_IIOP_LISTENER_PORT} +HOST_PORTS=${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT} + +set -x +${ASADMIN} deploy --target ${cluster_name} --force ${APS_HOME}/OrbFailOver-ejb.jar + +#${SACLIENT} -Djavax.enterprise.resource.corba.level=FINE -Djava.util.loggin.level=FINE -client ${APS_HOME}/OrbFailOver-app-client.jar -targetserver ${instance1_node}:${instance1_IIOP_LISTENER_PORT},${instance2_node}:${instance2_IIOP_LISTENER_PORT} -name OrbFailOver-app-client & + +if [ "${DEBUGGER}" = "1" ]; +then ${SACLIENT} ${DEBUG_ARGS} -Djava.util.logging.config.file=${PROPS_FILE} -Dcom.sun.appserv.iiop.endpoints=${HOST_PORTS} -Dtest.folb.asadmin.command=${ASADMIN} orbfailover.Main $@ ; +else +${SACLIENT} -Djava.util.logging.config.file=${PROPS_FILE} -Dcom.sun.appserv.iiop.endpoints=${HOST_PORTS} -Dtest.folb.asadmin.command=${ASADMIN} orbfailover.Main $@ ; +fi diff --git a/iiop-folb-dev-test/README b/iiop-folb-dev-test/README new file mode 100644 index 000000000..72c6a13a6 --- /dev/null +++ b/iiop-folb-dev-test/README @@ -0,0 +1,14 @@ +This directory contains GlassFish IIOP / Fail Over Load Balance Test. + +To Run the Test: mvn integration-test + +Test Execution Details: + +- Copy the glassfish build to the current directory: ./glassfish.zip +- Run the tests: "source setup.sh ; run.sh" +- samplerun.sh shows how to run a subset of tests of interest. + +README.html has more details about the test suite. + +Dependencies: mvn 3+, ant 1.8.2 +, gawk 3.1.8 + + diff --git a/iiop-folb-dev-test/README.html b/iiop-folb-dev-test/README.html new file mode 100644 index 000000000..6b178a54b --- /dev/null +++ b/iiop-folb-dev-test/README.html @@ -0,0 +1,331 @@ + + + + + The IIOP FOLB dev tests + + + + + + + +

Notes on the IIOP FOLB dev tests

+

for GlassFish Version 3.1.x

+

The project contains a very standard EJB, and a somewhat strange +app client. The EJB is just deployed to a cluster as usual, but the +app client is really a standalone program that starts the cluster and +configures and controls it as needed. The project is itself a Java EE +project, containing sub projects for the EJB and the app client.

The +EJB essentially has one method:

+

public String +getLocation() ;

+


This method just returns the instance on which the EJB runs.  +The EJB itself gets the instance from a system property, which is set +up as part of the cluster configuration.

+

Configuring and running the test

+

The first step is to setup the nodes that you will use so that (at +least) the DAS node can ssh to the other nodes (including itself) +without userid/password. To do this, you basically need to create a +public/private key pair, and publish the public key to each machine +(see google for details). The most important (and most easily +overlooked) requirement is to set the permissions correctly:

+
    +
  • ~/.ssh MUST have permission 700 +

    +
  • The private key (e.g. id_rsa) MUST + have permission 600 +

    +
  • The public key (e.g. id_rsa.pub) + MUST have permission 644 +

    +
  • The authorized_keys files MUST + have permission 600 +

    +
  • The known_hosts files MUST have permission 644

    +
+

The next step requires setting up some environment variables and +configuring the run.sh script.
First, let's assume that you have +unzipped glassfish.zip to the directory <WORK>.
The required +environment variables are:

+
    +
  • S1AS_HOME: must be set to + <WORK>/glassfish4/glassfish +

    +
  • JAVA_HOME: must be set such that $JAVA_HOME/bin/java and +$JAVA_HOME/bin/jps is accessible. +

    +
  • GFV3_WORK: must be set to <WORK> +

    +
  • CORBA_WS: must be set to the base + of the current CORBA workspace +

    +
      +
    • Use mercurial to get this from + https://kenai.com/hg/gf-corba-v3-mirror~staging +

      +
    +
  • GFV3_WS: must be set to the base + of the current GlasFish workspace +

    +
      +
    • Use subversion to get this from + https://svn.java.net/svn/glassfish~svn/trunk/v3 +

      +
    +
+

Note that that installgfv3 script will install the currently build +GF from ${GFV3_WS} to WORK. +

+

The current run.sh also assumes that you have some scripts +available:

+
    +
  • killgf: kill all GF processes on a + machine +

    +
  • installorb: install the GF 3.1 ORB + into <WORK>/glassfish4/glassfish/modules +

    +
  • installgfv3: installs GF 3.1 into + <WORK> +

    +
  • installgforb: installs GF 3.1 + orb/* modules into <WORK>/glassfish4/glassfish/modules +

    +
  • installgfnaming: installs GF 3.1 common/glassfish-naming + module into <WORK>/glassfish4/glassfish/modules +

    +
+

These scripts are in the scripts directory. +

+

A couple of things need to be set according to your environment in +run.sh:

+
    +
  • DAS_HOST: the host on which you + run the DAS. +

    +
  • AVAILABLE_NODES: set to comma + separated list <host:num instances> +

    +
      +
    • GF instances will be distributed + across the available instances +

      +
    • The number of instances must be at least 5 (in order to run + 14867).  Most test cases work well with 3 instances. +

      +
    +
+

To run the tests, just call
   
    +./run.sh <options>

Options will be discussed later.

+

A tour through the project

+
    +
  • run.sh: the script used to run + everything

    +
  • README.html: (this file obviously) +

    +
  • OLD: directory containing obsolete + version of test scripts +

    +
  • testcommands.txt: gives a typical + example of the asadmin commands used to create a cluster +

    +
  • test +

    +
      +
    • OrbFailover +

      +
        +
      • nbproject (this is the level at + which NetBeans starts) +

        +
      • OrbFailover-app-client +

        +
          +
        • src +

          +
            +
          • java +

            +
              +
            • argparser: an extended + ORB-style ArgParser that supports extensions +

              +
            • glassfish +

              +
                +
              • AdminCommand: allows issuing + asadmin commands by execing asadmin +

                +
              • GlassFishCluster: manages a + cluster using AdminCommand +

                +
              • GlassFishInstallation: keeps + track of the basic GF installation +

                +
              • StandardPorts: an enum for + the various port types +

                +
              • WeightedCircularIterator: + used to iterate over the AVAILABLE_NODES information +

                +
              +
            • orb/folb: a copy of + LocationBeanRemote +

              +
            • orbfailover +

              +
                +
              • Main.java: the actual test + program +

                +
              +
            • testtools +

              +
                +
              • Base.java: a quick-and-dirty + annotation driven test framework similar to JUnit, TestNg +

                +
              • Post: annotation used on + methods that are executed after each test method +

                +
              • Pre: annotation used on + methods that are executed before each test method +

                +
              • Test: annotates the method + with an optional testID +

                +
                  +
                • default testID is method + name +

                  +
                +
              +
            +
          +
        +
      • OrbFailover-ejb +

        +
          +
        • src +

          +
            +
          • java +

            +
              +
            • orb +

              +
                +
              • folb +

                +
                  +
                • LocationBean.java: the bean + implementation

                  +
                • LocationBeanRemove.java: + the remote interface +

                  +
                    +
                  • This is duplicated in the + app client, because that's the only way I could get it to + work!

                    +
                  +
                +
              +
            +
          +
        +
      • build.xml +

        +
      • src (ignore: NB/JavaEE stuff)

        +
      • Build the project using NetBeans IDE, or use the CLI + command:

        +
          +
        • ant -Dj2ee.server.home=$S1AS_HOME + -Dlibs.CopyLibs.classpath=$NETBEANS_HOME/java/ant/extra/o/org-netbeans-modules-java-j2seproject-copylibstask.jar

          +
        +
      +
    +
+

Command Options

+

Command options in Base: (see Base.Arguments for details):

+
    +
  • debug (true/false): controls + debugging mode for test framework +

    +
  • cases (true/false) +

    +
  • include (list of String): testIDs + to include in this run +

    +
  • exclude (list of String): testIDs to exclude in this run

    +
+


Specific command options for Main: (see Main.Installation for +details):

+
    +
  • installDir (String): directory + where GF is installed +

    +
  • dasNode (String): name of the + machine running the DAS +

    +
  • availableNodes (list of String): + see AVAILABLE_NODES above +

    +
  • testEJB (String): path of the EJB + to deploy +

    +
  • doCleanup (boolean): whether or + not to shutdown and destroy the cluster at the end +

    +
  • skipSetup (boolean): whether or + not to skip the setup of the cluster +

    +
      +
    • setting this to false is useful + if you are repeatedly running the same test for debugging +

      +
    +
  • numInstances (int): number of + instances to use in the cluster (default 5) +

    +
      +
    • most tests will run fine with 3 instances, 14867 needs 5

      +
    +
+

Description of Test Cases

+

Here are the test cases (ID after name):

+
    +
  • test14732 (14732) +

    +
  • test14755 (14755) +

    +
  • test14762 (14762) +

    +
  • test14766 (14766) +

    +
  • test14867 (14867)

    +
  • test15100 (15100) +

    +
  • testLBFail (lbfail): loadbalance + after failure

    +
  • testLoadBalance (loadbalance): + basic loadbalance

    +
  • failOverTest (failover): basic + failover +

    +
  • listContextTest (listcontext): + lists a naming context +

    +
      +
    • This doesn't work, because naming is a bit messed up in GF.  + Should file an issue and fix in 3.2.

      +
    +
+



+

+ + diff --git a/iiop-folb-dev-test/hudsonsetup.sh b/iiop-folb-dev-test/hudsonsetup.sh new file mode 100755 index 000000000..d5208fba4 --- /dev/null +++ b/iiop-folb-dev-test/hudsonsetup.sh @@ -0,0 +1,33 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +echo "Start Date: `date`" +GFV3_WS=${HOME}/data/workspace/corba-build-glassfish-trunk/main/appserver +CORBA_WS=${HOME}/data/workspace/corba-staging-build-test-orb +GFV3_WORK=${WORKSPACE} +S1AS_HOME=${GFV3_WORK}/glassfish4/glassfish +export GFV3_WS +export CORBA_WS +export GFV3_WORK +export S1AS_HOME +########## +CORBA_DEVTEST_WS=$WORKSPACE +$CORBA_DEVTEST_WS/scripts/installgfv3 +$CORBA_DEVTEST_WS/scripts/installorb +cd $CORBA_DEVTEST_WS/test/OrbFailOver +OPT1="-Dlibs.CopyLibs.classpath=$HOME/bin/org-netbeans-modules-java-j2seproject-copylibstask.jar" +OPT2="-Dj2ee.server.home=${WORKSPACE}/glassfish4" +JAVA_HOME=/usr/jdk/latest +export JAVA_HOME +ant $OPT1 $OPT2 clean +ant $OPT1 $OPT2 +cd $CORBA_DEVTEST_WS +export DEBUGGER=0 + diff --git a/iiop-folb-dev-test/logging.properties b/iiop-folb-dev-test/logging.properties new file mode 100644 index 000000000..7bfd22a99 --- /dev/null +++ b/iiop-folb-dev-test/logging.properties @@ -0,0 +1,20 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +handlers= java.util.logging.ConsoleHandler +.level= INFO +java.util.logging.FileHandler.pattern = %h/java%u.log +java.util.logging.FileHandler.limit = 50000 +java.util.logging.FileHandler.count = 1 +java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter +java.util.logging.ConsoleHandler.level = FINE +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + +javax.enterprise.system.core.naming.level = FINE diff --git a/iiop-folb-dev-test/pom.xml b/iiop-folb-dev-test/pom.xml new file mode 100644 index 000000000..6917bbdac --- /dev/null +++ b/iiop-folb-dev-test/pom.xml @@ -0,0 +1,46 @@ + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.0.0-b008-SNAPSHOT + + + glassfish-corba-integration-tests + Integration Tests + pom + + + + + exec-maven-plugin + org.codehaus.mojo + 1.2.1 + + + integration-test + + exec + + + samplerun.sh + + + + + + + + diff --git a/iiop-folb-dev-test/run.sh b/iiop-folb-dev-test/run.sh new file mode 100755 index 000000000..31867c3a7 --- /dev/null +++ b/iiop-folb-dev-test/run.sh @@ -0,0 +1,106 @@ +#! /bin/sh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Note that S1AS_HOME and GFV3_WORK must be defined before this script is called. +# GFV3_WS must be set in order to use scripts/installgfv3. +# CORBA_WS must be set in order to use scripts/installorb. +# The script installgfv3 must be available, and must install your GF 3.1 +# into ${GFV3_WORK}. +# The current directory must be the directory containing this run.sh script. + +################################################################ +# The following setup is environment specific: +################################################################ +# Use 'localhost' for single node setup. See issue GLASSFISH-15863 +DAS_HOST="localhost" +# Must allow at least 5 instances for the test +# Must be able to access the available nodes from the DAS using +# SSH without password. + +AVAILABLE_NODES="localhost:5" + +################################################################ +# Do the following to create a new cluster and new GF installation, +# or just set SKIP_SETUP=true. Different installXXX commands +# can be used to copy updated modules into the GF image, avoiding a +# rebuild of GF (which can take 30+ minutes) +# +# Install scripts: +# installgfv3 install GF 3.1 image from a local build +# installgforb install GF 3.1 orb glue bundles (orb/orb-iiop, etc.) +# installgfnaming install GF 3.1 naming code (common/glassfish-naming) +# installorb install 3.1 version of ORB from a local build +################################################################ + +# Clean up old instances +# ${S1AS_HOME}/bin/asadmin stop-cluster c1 +# ${S1AS_HOME}/bin/asadmin stop-domain + +# Do any needed installs. installgfv3 MUST be first. +# Only installgfv3 is needed for a fresh install; the others +# are for use if some of the GF or ORB code has been modified +# without rebuilding all of GF. +# scripts/installgfv3 +# scripts/installgforb +# scripts/installgfnaming +# scripts/installgfejbsec +# scripts/installorb +SKIP_SETUP="false" + +# Only use this if no installations (see above) is needed. +# SKIP_SETUP="true" + +################################################################ +# The rest of the script is fixed +################################################################ + +date + +APS_HOME="`pwd`/test/OrbFailOver" +APPCLIENT="${S1AS_HOME}/bin/appclient" +PROPS_FILE=${PWD}/logging.properties +echo ${PROPS_FILE} + +EJB_NAME="${APS_HOME}/OrbFailOver-ejb/dist/OrbFailOver-ejb.jar" +CLIENT_NAME="${APS_HOME}/OrbFailOver-app-client/dist/OrbFailOver-app-client.jar" + +ENDPOINTS="localhost:9037,localhost:10037,localhost:11037" +TARGET_ARGS="-targetserver ${ENDPOINTS}" +TARGET_DEF="-Dcom.sun.appserv.iiop.endpoints=${ENDPOINTS}" +DEBUG_ARGS="-agentlib:jdwp=transport=dt_socket,address=8228,server=y,suspend=y" +SETUP_ARGS="-Djava.util.logging.config.file=${PROPS_FILE}" +TEST_ARGS="-installDir ${GFV3_WORK}/glassfish4 -dasNode ${DAS_HOST} -availableNodes ${AVAILABLE_NODES} -testEjb ${EJB_NAME} -doCleanup false -skipSetup ${SKIP_SETUP}" +CLIENT_ARGS="-client ${CLIENT_NAME} -name OrbFailOver-app-client -serverORBDebug folb" + +set -x + +# echo ${APPCLIENT} ${SETUP_ARGS} ${CLIENT_ARGS} ${TEST_ARGS} $@ ; + +if [ "${DEBUGGER}" = "1" ]; +then + CMD="${APPCLIENT} ${DEBUG_ARGS} ${SETUP_ARGS} ${CLIENT_ARGS} ${TEST_ARGS} $@ " +else +# CMD="${APPCLIENT} ${SETUP_ARGS} ${CLIENT_ARGS} ${TEST_ARGS} $@ " + CMD="${APPCLIENT} ${SETUP_ARGS} -Djava.rmi.server.useCodebaseOnly=true ${CLIENT_ARGS} ${TEST_ARGS} $@ " +fi +echo $CMD +$CMD +exitStatus=$? + +# For testing with externally supplied endpoints +# if [ "${DEBUGGER}" = "1" ]; +# then ${APPCLIENT} ${DEBUG_ARGS} ${SETUP_ARGS} ${TARGET_DEF} ${CLIENT_ARGS} ${TEST_ARGS} -useExternalEndpoints true $@ +# else ${APPCLIENT} ${SETUP_ARGS} ${CLIENT_ARGS} ${TEST_ARGS} -useExternalEndpoints true $@ +# fi + +date +exit $exitStatus + diff --git a/iiop-folb-dev-test/samplerun.sh b/iiop-folb-dev-test/samplerun.sh new file mode 100755 index 000000000..af22e740b --- /dev/null +++ b/iiop-folb-dev-test/samplerun.sh @@ -0,0 +1,23 @@ +#!/bin/bash -x +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# sample local test execution script +source ./setup.sh +############################ +glassfish4/glassfish/bin/asadmin start-domain +glassfish4/glassfish/bin/asadmin create-jvm-options -Djava.rmi.server.useCodebaseOnly=true +glassfish4/glassfish/bin/asadmin stop-domain +pause +############################ +#./run.sh +#./run.sh -include "lbfail" +./run.sh -exclude "15804sfsb,15804sfsb_kill,15804sfsb_kill_delete" + diff --git a/iiop-folb-dev-test/scripts/installgfejbsec b/iiop-folb-dev-test/scripts/installgfejbsec new file mode 100755 index 000000000..6e01daaea --- /dev/null +++ b/iiop-folb-dev-test/scripts/installgfejbsec @@ -0,0 +1,23 @@ +#! /bin/csh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +setenv BUILD ${GFV3_WS} +setenv RUN ${GFV3_WORK} +setenv MAVEN ~/.m2/repository +setenv GROUPID org/glassfish/security +setenv DEST ${RUN}/glassfish4/glassfish/modules +setenv VERSION 3.1-SNAPSHOT + +cd ${MAVEN}/${GROUPID} + +pushd ejb.security/${VERSION} +cp ejb.security-${VERSION}.jar ${DEST}/ejb.security.jar + diff --git a/iiop-folb-dev-test/scripts/installgfnaming b/iiop-folb-dev-test/scripts/installgfnaming new file mode 100755 index 000000000..c40dfce81 --- /dev/null +++ b/iiop-folb-dev-test/scripts/installgfnaming @@ -0,0 +1,23 @@ +#! /bin/csh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +setenv BUILD ${GFV3_WS} +setenv RUN ${GFV3_WORK} +setenv MAVEN ~/.m2/repository +setenv GROUPID org/glassfish/common +setenv DEST ${RUN}/glassfish4/glassfish/modules +setenv VERSION 3.1-SNAPSHOT + +cd ${MAVEN}/${GROUPID} + +pushd glassfish-naming/${VERSION} +cp glassfish-naming-${VERSION}.jar ${DEST}/glassfish-naming.jar +popd diff --git a/iiop-folb-dev-test/scripts/installgforb b/iiop-folb-dev-test/scripts/installgforb new file mode 100755 index 000000000..b85a9b133 --- /dev/null +++ b/iiop-folb-dev-test/scripts/installgforb @@ -0,0 +1,33 @@ +#! /bin/csh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +setenv BUILD ${GFV3_WS} +setenv RUN ${GFV3_WORK} +setenv MAVEN ~/.m2/repository +setenv GROUPID org/glassfish/orb +setenv DEST ${RUN}/glassfish4/glassfish/modules +setenv VERSION 3.1-SNAPSHOT + +cd ${MAVEN}/${GROUPID} + +pushd orb-iiop/${VERSION} +cp orb-iiop-${VERSION}.jar ${DEST}/orb-iiop.jar +popd + +pushd orb-connector/${VERSION} +cp orb-connector-${VERSION}.jar ${DEST}/orb-connector.jar +popd + +pushd orb-enabler/${VERSION} +cp orb-enabler-${VERSION}.jar ${DEST}/orb-enabler.jar +popd + + diff --git a/iiop-folb-dev-test/scripts/installgfv3 b/iiop-folb-dev-test/scripts/installgfv3 new file mode 100755 index 000000000..3cc328631 --- /dev/null +++ b/iiop-folb-dev-test/scripts/installgfv3 @@ -0,0 +1,23 @@ +#! /bin/csh -x +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +setenv BUILD ${GFV3_WS} +if ("$1" == "") then + setenv RUN ${GFV3_WORK} +else + setenv RUN ${GFV3_WORK}/$1 +endif + +rm ${RUN}/glassfish.zip +rm -rf ${RUN}/glassfish4 +cp ${BUILD}/distributions/glassfish/target/glassfish.zip ${RUN} +cd ${RUN} +unzip -q glassfish.zip diff --git a/iiop-folb-dev-test/scripts/installorb b/iiop-folb-dev-test/scripts/installorb new file mode 100755 index 000000000..dcf10702e --- /dev/null +++ b/iiop-folb-dev-test/scripts/installorb @@ -0,0 +1,17 @@ +#! /bin/csh -x +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +setenv ORB ${CORBA_WS}/build/rename/ee/build/release/lib/bundles-archive.zip +setenv DEST ${GFV3_WORK}/glassfish4 + +cd ${DEST} +unzip -o ${ORB} + diff --git a/iiop-folb-dev-test/scripts/kill b/iiop-folb-dev-test/scripts/kill new file mode 100755 index 000000000..f418ad56a --- /dev/null +++ b/iiop-folb-dev-test/scripts/kill @@ -0,0 +1,35 @@ +#!/bin/sh -x +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +#JAVA_HOME=$1 +JPS=$JAVA_HOME/bin/jps +PROC_NAME=$1 +OSNAME=`uname -a | awk '{ print $1 }'` +echo "$OSNAME" + +kill_processes() { + PROCESS_NAME=$1 + case $OSNAME in + AIX*) PIDS=`ps -ef | grep $PROCESS_NAME |grep glassfish.jar| awk '{ print $2 }' | xargs`;; + *) PIDS=`$JAVA_HOME/bin/jps -mlVv | grep $PROCESS_NAME | awk '{ print $1 }' | xargs`;; + esac + + for PID in $PIDS ; + do + case $OSNAME in + CYGWIN*) taskkill /F /T /PID $PID;; + *) kill -9 $PID;; + esac + done +} + +kill_processes $PROC_NAME + diff --git a/iiop-folb-dev-test/scripts/killgf b/iiop-folb-dev-test/scripts/killgf new file mode 100755 index 000000000..e54a17df3 --- /dev/null +++ b/iiop-folb-dev-test/scripts/killgf @@ -0,0 +1,23 @@ +#! /bin/csh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +foreach f (`jps | grep ASMain | gawk '{print $1}'`) + # echo $f + kill -9 $f +end +foreach f (`jps | grep Broker | gawk '{print $1}'`) + # echo $f + kill -9 $f +end +foreach f (`jps | grep DerbyControl | gawk '{print $1}'`) + # echo $f + kill -9 $f +end diff --git a/iiop-folb-dev-test/setup.sh b/iiop-folb-dev-test/setup.sh new file mode 100755 index 000000000..d74d6437b --- /dev/null +++ b/iiop-folb-dev-test/setup.sh @@ -0,0 +1,34 @@ +#!/bin/bash -x +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# sample local test setup script for U*x +./scripts/killgf +sleep 5 +if [ -d glassfish4 ] +then + \rm -rf glassfish4.old + mv glassfish4 glassfish4.old +fi +#point to appripriate glassfish.zip bundle +#wget http://hudson.glassfish.org/job/gf-trunk-build-continuous/lastSuccessfulBuild/artifact/bundles/glassfish.zip +unzip -qo ./glassfish.zip +#cp /tmp/orb-iiop.jar glassfish4/glassfish/modules/orb-iiop.jar +export GFV3_WORK=`pwd` +export S1AS_HOME=${GFV3_WORK}/glassfish4/glassfish +cd test/OrbFailOver +ant -Dj2ee.server.home=${S1AS_HOME} clean +#ant -Dj2ee.server.home=${S1AS_HOME} +cd OrbFailOver-app-client +ant -Dj2ee.server.home=${S1AS_HOME} +cd ../OrbFailOver-ejb/ +ant -Dj2ee.server.home=${S1AS_HOME} +cd ../../.. + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/build.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/build.xml new file mode 100644 index 000000000..4258a56ff --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/build.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + Builds, tests, and runs the project OrbFailOver-app-client. + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/ant-deploy.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/ant-deploy.xml new file mode 100644 index 000000000..681f9abd0 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/ant-deploy.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/build-impl.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/build-impl.xml new file mode 100644 index 000000000..1bba6c931 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/build-impl.xml @@ -0,0 +1,1003 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set build.generated.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + +The Java EE server classpath is not correctly set up - server home directory is missing. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Dj2ee.server.home=<app_server_installation_directory> + + +The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Duser.properties.file=<path_to_property_file> (where you put the property "j2ee.platform.classpath" in a .properties file) +or ant -Dj2ee.platform.classpath=<server_classpath> (where no properties file is used) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Main class must be set. Go to OrbFailOver-app-client project properties -> Run and set the main class there. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Browser not found, cannot launch the deployed application. Try to set the BROWSER environment variable. + + + Launching ${browse.url} + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/genfiles.properties b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/genfiles.properties new file mode 100644 index 000000000..f41362d80 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/genfiles.properties @@ -0,0 +1,18 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +build.xml.data.CRC32=efe41177 +build.xml.script.CRC32=a1d9cf79 +build.xml.stylesheet.CRC32=2c379194@1.22.1.1 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=efe41177 +nbproject/build-impl.xml.script.CRC32=6473bf66 +nbproject/build-impl.xml.stylesheet.CRC32=868bea5c@1.22.1.1 diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/project.properties b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/project.properties new file mode 100644 index 000000000..b8df7ea4d --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/project.properties @@ -0,0 +1,114 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=true +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.dir}/jar +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.ear.classes.dir=${build.dir}/jar +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.ear.jar=${dist.dir}/${jar.name} +dist.jar=${dist.dir}/${jar.name} +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath=\ + ${libs.javaee-endorsed-api-6.0.classpath} +excludes= +file.reference.glassfish-corba-asm.jar=../../../glassfish4/glassfish/modules/glassfish-corba-asm.jar +file.reference.glassfish-corba-codegen.jar=../../../glassfish4/glassfish/modules/glassfish-corba-codegen.jar +file.reference.glassfish-corba-csiv2-idl.jar=../../../glassfish4/glassfish/modules/glassfish-corba-csiv2-idl.jar +file.reference.glassfish-corba-internal-api.jar=../../../glassfish4/glassfish/modules/glassfish-corba-internal-api.jar +file.reference.glassfish-corba-newtimer.jar=../../../glassfish4/glassfish/modules/glassfish-corba-newtimer.jar +file.reference.glassfish-corba-omgapi.jar=../../../glassfish4/glassfish/modules/glassfish-corba-omgapi.jar +file.reference.glassfish-corba-orb.jar=../../../glassfish4/glassfish/modules/glassfish-corba-orb.jar +file.reference.glassfish-corba-orbgeneric.jar=../../../glassfish4/glassfish/modules/glassfish-corba-orbgeneric.jar +file.reference.gmbal.jar=../../../glassfish4/glassfish/modules/gmbal.jar +file.reference.javaee.jar=../../../glassfish4/glassfish/lib/javaee.jar +includes=** +j2ee.appclient.mainclass.args=${j2ee.appclient.tool.args} +j2ee.platform=1.6 +j2ee.platform.classpath=${j2ee.server.home}/modules/jaxrpc-api-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/javax.enterprise.deploy.jar:${j2ee.server.home}/modules/jaxr-api-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.el.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jar:${j2ee.server.home}/modules/javax.management.j2ee.jar:${j2ee.server.home}/modules/endorsed/javax.annotation.jar:${j2ee.server.home}/modules/javax.el-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp-api.jar:${j2ee.server.home}/modules/javax.security.jacc.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl-api.jar:${j2ee.server.home}/modules/jersey-core.jar:${j2ee.server.home}/modules/javax.transaction.jar:${j2ee.server.home}/modules/javax.resource.jar:${j2ee.server.home}/modules/javax.persistence.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar:${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/javax.security.auth.message.jar:${j2ee.server.home}/modules/javax.servlet-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl.jar:${j2ee.server.home}/modules/javax.jms.jar:${j2ee.server.home}/modules/javax.mail.jar +j2ee.platform.embeddableejb.classpath=${j2ee.server.home}/lib/embedded/glassfish-embedded-static-shell.jar +j2ee.platform.wscompile.classpath=${j2ee.server.home}/modules/webservices-osgi.jar +j2ee.platform.wsgen.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar +j2ee.platform.wsimport.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar +j2ee.platform.wsit.classpath= +j2ee.server.type=gfv3ee6 +jar.compress=false +jar.name=OrbFailOver-app-client.jar +javac.classpath=\ + ${file.reference.gmbal.jar}:\ + ${file.reference.javaee.jar}:\ + ${file.reference.glassfish-corba-asm.jar}:\ + ${file.reference.glassfish-corba-codegen.jar}:\ + ${file.reference.glassfish-corba-csiv2-idl.jar}:\ + ${file.reference.glassfish-corba-internal-api.jar}:\ + ${file.reference.glassfish-corba-newtimer.jar}:\ + ${file.reference.glassfish-corba-omgapi.jar}:\ + ${file.reference.glassfish-corba-orb.jar}:\ + ${file.reference.glassfish-corba-orbgeneric.jar} +# Space-separated list of extra javac options +javac.compilerargs=-target 6 +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javac.test.processorpath=${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class=orbfailover.Main +manifest.file=${meta.inf}/MANIFEST.MF +meta.inf=${source.root}/conf +no.dependencies=true +platform.active=default_platform +resource.dir=setup +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.root=src +src.dir=${source.root}/java +test.src.dir=test diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/project.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/project.xml new file mode 100644 index 000000000..b8d834a2e --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/nbproject/project.xml @@ -0,0 +1,39 @@ + + + + + org.netbeans.modules.j2ee.clientproject + + + OrbFailOver-app-client + 1.6.5 + + + + + + + file.reference.gmbal.jar + file.reference.javaee.jar + file.reference.glassfish-corba-asm.jar + file.reference.glassfish-corba-codegen.jar + file.reference.glassfish-corba-csiv2-idl.jar + file.reference.glassfish-corba-internal-api.jar + file.reference.glassfish-corba-newtimer.jar + file.reference.glassfish-corba-omgapi.jar + file.reference.glassfish-corba-orb.jar + file.reference.glassfish-corba-orbgeneric.jar + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/conf/MANIFEST.MF b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/conf/MANIFEST.MF new file mode 100644 index 000000000..328e8e5bc --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/conf/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/conf/application-client.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/conf/application-client.xml new file mode 100644 index 000000000..1b5b8421a --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/conf/application-client.xml @@ -0,0 +1,16 @@ + + + + + OrbFailOver-app-client + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ArgParser.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ArgParser.java new file mode 100644 index 000000000..35b7d570b --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ArgParser.java @@ -0,0 +1,489 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.util.Collection ; +import java.util.Collections ; +import java.util.ArrayList ; +import java.util.List ; +import java.util.Map ; +import java.util.Set ; +import java.util.HashMap ; + +import java.lang.reflect.Array ; +import java.lang.reflect.Method ; +import java.lang.reflect.Proxy ; +import java.lang.reflect.InvocationHandler ; + +import java.net.URL ; +import java.util.Arrays; + +/** A general purpose argument parser that uses annotations, reflection, + * and generics. + *

+ * This class solves a simple problem: How do I write an argument parser + * that parses arguments of the form + *

+ * -xxx value + *

+ * There are many ways of doing this: the ORB has probably at least 6 + * different ways of attacking this problem (and I wrote half of them). + * The approach taken here is to start with an interface, annotate it + * to indicate some information (like default values) for parsing, and then + * use reflection to produce an implementation of the interface that uses a + * dynamic proxy. + *

+ * The argument parsing is entirely specified in terms of an interface with + * annotated methods. The name of the method is the name used as a -xxx + * argument when parsing the data. The type of data determines the valid + * inputs for the argument. All arguments must be in the -xxx yyy form, + * where yyy is a valid input for the type of method xxx() in the interface. + *

+ * The interface is very simply: just create an ArgParser of the appropriate type, + * and then call parse( String[] ) to get an instance of the interface. There + * is also a getHelpText() method that returns a String with formatted information + * about all the valid arguments for this parser. + *

+ * Not all required information can be derived from the method type and name. + * Some annotations are defined for additional information: + *

    + *
  1. @DefaultValue. This gives a String that is used to construct a default value + * for the given method. + *
  2. @Separator. This is used to override the default "," separator used for + * lists of values for fields of type List<Type> or Type[]. + *
  3. @Help. This is used to give any help text for the field that is displayed + * by the getHelpText method. + *
+ * + * TODO: + * + *
    + *
  1. Support I18N for this (required before it could be used for public + * parts of the ORB). + *
  2. Support Set<Type> Similar to list, but all elements must be unique. + *
  3. Support Map<Type,Type> + *
  4. Do we want to support really complex types, like Map<String,List<Map<String,Foo>>> + * How would we specify needed separators? + *
  5. Should we extend along the lines of the ORB arg parser, with an embedded + * language to describe how to parse a String? + *
  6. Extend this to support property parsing as well (required for ORB.init parsing). + * Probably just want to parse Properties as well as String[]. This requires some + * way to handle the property prefix (as in -ORBInitHost and org.omg.CORBA.ORBInitHost). + *
  7. Extend to support abstract classes. Only non-private abstract methods + * that are read-only + * beans and are annotated with @DefaultValue can be set by the parser. Other + * methods are allowed, but not used by the parser. + *
  8. Support an @Complete annotation. All such methods must be void(), and are + * executed in some order after the parsing is complete. + *
  9. Add an @Keyword notation to override the default name of the argument (the + * method name). This allows having different names for the methods and the arguments. + * Note that this can be used for fully-qualified property names. This supports the + * ORB dual use of properties and arguments (with perhaps a little fudging for + * things like ORBInitRef: if there are multiple args, concat them together and use + * a list separator?) + *
  10. Add an @ClassName annotation that takes no arguments. This means that the + * string passed must be the name of a class that has a no-args constructor. + * The class must be assignment compatible with the return type of the annotated + * method. At parse time, we just load the class named by the string and create + * a new instance of it. + *
  11. Consider using apt for this. This solves two problems: + *
      + *
    1. We can generate a more efficient class than the current version that + * uses a dynamic proxy and a table lookup. This becomes important when + * we consider that ORBData may be referenced many times during an invocation. + *
    2. We can generate much of the required ORBConstants (say as ORBPropertyNames) + * directly from the annotated interface. + *
    3. + *
    + *
  12. Most of the extensions here are aimed at reducing the code size of the + * ORB data stuff. + *
  13. If we don't want to use apt: + *
      + *
    1. Use codegen to generate a class that implements the argument interface. + *
    2. Instead of generating ORBConstants, look things up from it using static + * reflection on the name of the constant. This would require some other annotations: + *
        + *
      1. @IndirectKeyword gives the name of the constant in the @ConstantClass to look for. + * Do we need multiple constant classes? + *
      2. @ConstantClass would give the class to use for looking up public static final + * constants for @IndirectKeyword, which is like @Keyword. + *
      + *
    + *
+ * + * Summary of current and proposed annotations: + *
    + *
  1. @DefaultValue: current method-level takes string + *
  2. @Separator: current method-level takes string + *
  3. @Help: current method-level takes string + *
  4. @ConstantClass: proposed class-level takes class constant + *
  5. @Complete: proposed method-level marker + *
  6. @Keyword: proposed method-level takes string + *
  7. @IndirectKeyword: proposed method-level takes string + *
  8. @ClassName: proposed method-level marker + *
  9. + *
+ * + * @author Ken Cavanaugh + */ +public class ArgParser { + private final List> interfaceClasses = + new ArrayList>() ; + private final Map helpText = + new HashMap() ; + private final Map defaultValues = + new HashMap() ; + private final Map parserData = + new HashMap() ; + + /** Construct an ArgParser that parses an argument string into an instance of the + * Class argument. + * cls must be an interface. Each method in this interface must take no arguments. + * Each method must be annotated with a DefaultValue annotation. + * Each method must return one of the following types: + *
    + *
  • A primitive type + *
  • A String type + *
  • A type that has a public constructor that takes a single String argument + *
  • An Enum + *
  • A List parameterized by one of the above types + *
  • An array of one of the first four types + *
+ * The name of the method is the name of the keyword. + */ + public ArgParser( Class cls ) { + init( cls ) ; + } + + public ArgParser( List> classes ) { + init(classes ) ; + } + + private void init( Class cls ) { + List> classes = new ArrayList>() ; + classes.add( cls ) ; + init( classes ) ; + } + + private void init( List> classes) { + final Map defaultValueData = new HashMap() ; + for (Class cls : classes) { + if (!cls.isInterface()) { + error(cls.getName() + " is not an interface"); + } + interfaceClasses.add( cls ) ; + + // Construct the list of ParserData entries for the methods in cls, and + // also a map from keyword to default value data for the @DefaultValue + // annotations. + for (Method m : cls.getMethods()) { + final String keyword = checkMethod( m ) ; + final ElementParser ep = ElementParser.factory.evaluate( m ) ; + parserData.put( keyword, ep ) ; + + final DefaultValue dv = m.getAnnotation( DefaultValue.class ) ; + if (dv == null) { + error( "Method " + m.getName() + + " does not have a DefaultValue annotation" ) ; + } else { + defaultValueData.put( keyword, dv.value() ) ; + } + + final Help help = m.getAnnotation( Help.class ) ; + if (help != null) { + helpText.put(keyword, help.value()); + } + } + } + + internalParse( defaultValueData, defaultValues ) ; + } + + private String display( Object obj ) { + if (obj.getClass().isArray()) { + StringBuilder sb = new StringBuilder() ; + sb.append( "[" ) ; + for (int ctr=0; ctr 0) { + sb.append( "," ) ; + } + sb.append( element.toString() ) ; + } + sb.append( "]" ) ; + return sb.toString() ; + } else if (obj instanceof Collection) { + StringBuilder sb = new StringBuilder() ; + sb.append( "[" ) ; + boolean first = true ; + for (Object element : (Collection)obj) { + if (first) { + first = false ; + } else { + sb.append( "," ) ; + } + sb.append( element.toString() ) ; + } + sb.append( "]" ) ; + return sb.toString() ; + } else { + return obj.toString() ; + } + } + + /** Returns a formatted text string that describes the expected + * arguments for this parser. + */ + public String getHelpText() { + StringBuilder sb = new StringBuilder() ; + sb.append( " Legal arguments are:\n" ) ; + Set keys = parserData.keySet() ; + List keyList = new ArrayList( keys ) ; + Collections.sort( keyList ) ; + for (String keyword : keyList) { + ElementParser ep = parserData.get( keyword ) ; + sb.append("\t-").append(keyword).append( " <") ; + boolean first = true ; + for (String str : ep.describe() ) { + if (first) { + first = false; + } + else { + sb.append("\n\t "); + } + + sb.append( str ) ; + } + sb.append( ">\n" ) ; + + String defaultValue = display(defaultValues.get(keyword)) ; + sb.append("\t " + "(default ").append(defaultValue) + .append( ")\n") ; + + String help = helpText.get( keyword ) ; + if (help != null) { + sb.append("\t ").append(help).append( "\n") ; + } + + sb.append( "\n" ) ; + } + + return sb.toString() ; + } + + /** Parse the argument string into an instance of type T. + */ + public Object parse( String[] args ) { + Map data = makeMap( args ) ; + Map pdata = new HashMap() ; + internalParse( data, pdata ) ; + Object result = makeProxy( pdata ) ; + return result ; + } + + private void error( String msg ) { + System.out.println( "Error in argument parser: " + msg ) ; + System.out.println( getHelpText() ) ; + throw new RuntimeException ( msg ) ; + } + + // Check that method has no arguments + private String checkMethod( Method m ) { + if (m.getParameterTypes().length == 0) { + String result = m.getName() ; + if (parserData.containsKey(result )) { + error( "Keyword " + result + " is already defined.") ; + } else { + return m.getName(); + } + } else { + error("Method " + m.getName() + " must not have any parameters"); + } + + return null ; + } + + private void internalParse( Map data, + Map result ) { + for (Map.Entry entry : data.entrySet()) { + String keyword = entry.getKey() ; + ElementParser ep = parserData.get( keyword ) ; + if (ep == null) { + error(keyword + " is not a valid keyword"); + } + Object val = ep.evaluate( entry.getValue() ) ; + result.put( keyword, val ) ; + } + } + + private String getKeyword( String arg ) { + if (arg.charAt(0) == '-') { + return arg.substring(1); + } else { + error(arg + " is not a valid keyword"); + } + return null ; // not reachable + } + + // Data must all be of the form (-keyword value)* + private Map makeMap( String[] args ) { + Map result = new HashMap() ; + String keyword = null ; + for (String arg : args) { + if (keyword == null) { + keyword = getKeyword(arg); + } else { + result.put( keyword, arg ) ; + keyword = null ; + } + } + if (keyword != null) { + error("No argument supplied for keyword " + keyword); + } + return result ; + } + + // Make a dynamic proxy of type T for the given data. + // The keys in the data must be the same as the method names in + // the type T. + private Object makeProxy( final Map data ) { + final InvocationHandler ih = new InvocationHandler() { + private Object getValue( final String keyword ) { + Object result = data.get( keyword ) ; + if (result == null) { + result = defaultValues.get(keyword); + } + return result ; + } + + private String getString( final Object obj ) { + final Class cls = obj.getClass() ; + if (cls.isArray()) { + final StringBuilder sb = new StringBuilder() ; + sb.append( "[" ) ; + for (int ctr=0; ctr0) { + sb.append( "," ) ; + } + + Object element = Array.get( obj, ctr ) ; + sb.append( element.toString() ) ; + } + + sb.append( "]" ) ; + return sb.toString() ; + } else { + return obj.toString() ; + } + } + + @Override + public Object invoke( final Object proxy, final Method method, + final Object[] args ) { + + final String name = method.getName() ; + if (name.equals("toString")) { + final StringBuilder sb = new StringBuilder() ; + for (String keyword : parserData.keySet()) { + sb.append( keyword ) ; + sb.append( "=" ) ; + sb.append( getString( getValue( keyword ) ) ) ; + sb.append( "\n" ) ; + } + return sb.toString() ; + } else { + return getValue( name ) ; + } + } + } ; + + final Class[] interfaces = interfaceClasses.toArray( + new Class[interfaceClasses.size()] ) ; + + ClassLoader cl = this.getClass().getClassLoader() ; + if (cl == null) { + cl = interfaces[0].getClass().getClassLoader() ; + } + if (cl == null) { + ClassLoader.getSystemClassLoader() ; + } + + return Proxy.newProxyInstance( cl, interfaces, ih ) ; + } + +//////////////////////////////////////////////////////////////////////////////////// +// +// Data for built-in test +// +//////////////////////////////////////////////////////////////////////////////////// + + private enum PrimaryColor { RED, GREEN, BLUE } ; + + public static class StringPair extends Pair { + public StringPair( String data ) { + super( null, null ) ; + int index = data.indexOf( ':' ) ; + if (index < 0) { + throw new IllegalArgumentException(data + + " does not contain a :"); + } + _first = data.substring( 0, index ) ; + _second = data.substring( index + 1 ) ; + } + } + + private interface TestInterface1 { + @DefaultValue( "27" ) + @Help( "An integer value" ) + int value() ; + + @DefaultValue( "Michigan" ) + @Help( "The name of a lake" ) + String lake() ; + + @DefaultValue( "RED" ) + @Help( "Pick a color" ) + PrimaryColor color() ; + } + + private interface TestInterface2 { + @DefaultValue( "http://www.sun.com" ) + @Help( "your favorite URL" ) + URL url() ; + + @DefaultValue( "funny:thing,another:thing,something:else" ) + @Help( "A list of pairs of the form xxx:yyy" ) + @Separator( "," ) + StringPair[] arrayData() ; + + @DefaultValue( "funny:thing,another:thing,something:else" ) + @Help( "A list of pairs of the form xxx:yyy" ) + @Separator( "," ) + List listData() ; + + @DefaultValue( "" ) + @Help( "A list of strings") + List str() ; + } + + public static void main( String[] args ) { + Class[] interfaces = { TestInterface1.class, TestInterface2.class } ; + ArgParser ap = new ArgParser( Arrays.asList( interfaces) ) ; + System.out.println( "Help text for this parser:\n" + ap.getHelpText() ) ; + Object result = ap.parse( args ) ; + if (!(result instanceof TestInterface1) + && !(result instanceof TestInterface2)) { + System.out.println( "Error: result not an instance of both test interfaces" ) ; + } + + System.out.println( "Result is:\n" + result ) ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/CompositeInvocationHandler.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/CompositeInvocationHandler.java new file mode 100644 index 000000000..a7298ff8e --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/CompositeInvocationHandler.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.io.Serializable ; +import java.lang.reflect.InvocationHandler ; + +public interface CompositeInvocationHandler extends InvocationHandler, + Serializable +{ + /** Add an invocation handler for all methods on interface interf. + */ + void addInvocationHandler( Class interf, InvocationHandler handler ) ; + + /** Set the default invocation handler to use if none of the + * invocation handlers added by calls to addInvocationHandler apply. + */ + void setDefaultHandler( InvocationHandler handler ) ; +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/CompositeInvocationHandlerImpl.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/CompositeInvocationHandlerImpl.java new file mode 100644 index 000000000..db6139375 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/CompositeInvocationHandlerImpl.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + + +import java.util.Map ; +import java.util.LinkedHashMap ; + +import java.lang.reflect.Method ; +import java.lang.reflect.InvocationHandler ; + +public class CompositeInvocationHandlerImpl implements + CompositeInvocationHandler +{ + private Map,InvocationHandler> classToInvocationHandler = + new LinkedHashMap,InvocationHandler>() ; + private InvocationHandler defaultHandler = null ; + + public void addInvocationHandler( Class interf, + InvocationHandler handler ) + { + classToInvocationHandler.put( interf, handler ) ; + } + + public void setDefaultHandler( InvocationHandler handler ) + { + defaultHandler = handler ; + } + + public Object invoke( Object proxy, Method method, Object[] args ) + throws Throwable + { + // Note that the declaring class in method is the interface + // in which the method was defined, not the proxy class. + Class cls = method.getDeclaringClass() ; + + // Handle Object methods here. This allows overridding of + // toString, equals, and hashCode in a class that extends + // CompositeInvocationHandlerImpl. + if (cls.equals( Object.class )) { + try { + return method.invoke( this, args ) ; + } catch (Exception exc) { + throw new RuntimeException( "Invocation error on Object method", + exc ) ; + } + } + + InvocationHandler handler = classToInvocationHandler.get(cls) ; + + if (handler == null) { + if (defaultHandler != null) { + handler = defaultHandler; + } else { + throw new RuntimeException( "No invocation handler for method " + + "\"" + method.toString() + "\"" ) ; + } + } + + // handler should never be null here. + + return handler.invoke( proxy, method, args ) ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/DefaultValue.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/DefaultValue.java new file mode 100644 index 000000000..efdbfd418 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/DefaultValue.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.lang.annotation.Documented ; +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface DefaultValue { + String value() default "" ; +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ElementParser.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ElementParser.java new file mode 100644 index 000000000..fca4becad --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ElementParser.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.lang.reflect.Method ; + +public interface ElementParser extends UnaryFunction { + String[] describe() ; + + UnaryFunction factory = + new UnaryFunction() { + @Override + public ElementParser evaluate( Method m ) { + return new ElementParserImpl( m ) ; + } + } ; +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ElementParserImpl.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ElementParserImpl.java new file mode 100644 index 000000000..102a97253 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/ElementParserImpl.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.util.List ; +import java.util.ArrayList ; + +import java.lang.reflect.Array ; +import java.lang.reflect.Method ; +import java.lang.reflect.Constructor ; +import java.lang.reflect.Type ; +import java.lang.reflect.ParameterizedType ; +import java.lang.reflect.InvocationTargetException ; + +public class ElementParserImpl implements ElementParser { + private UnaryFunction func ; + private String[] description ; + + @Override + public Object evaluate( String str ) { + return func.evaluate( str ) ; + } + + @Override + public String[] describe() { + return description ; + } + + private static class ResultData extends Pair,String[]> { + public ResultData( UnaryFunction func, String[] desc ) { + super( func, desc ) ; + } + } + + public ElementParserImpl( Method m ) { + ResultData result = getData( m ) ; + + func = result.first() ; + description = result.second() ; + } + + String[] append( String str, String[] strs ) { + String[] result = new String[ strs.length + 1 ] ; + int rctr = 0 ; + result[rctr++] = str ; + for (String s : strs) { + result[rctr++] = s ; + } + return result ; + } + + // Used for complex data types like List and arrays. + private ResultData getData( Method meth ) { + UnaryFunction myFunc = null ; + String[] myDescription = null ; + Class type = meth.getReturnType() ; + + if (type.isArray()) { + final String sep = getSeparator( meth ) ; + final Class elementClass = type.getComponentType() ; + final ResultData elementResultData = getSimpleData( elementClass ) ; + myDescription = append( "A " + sep + "-separated list of ", + elementResultData.second() ) ; + + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String value ) { + String[] elements = value.isEmpty() ? + new String[0] : value.split( sep ) ; + Object result = Array.newInstance( elementClass, + elements.length ) ; + int ctr = 0 ; + for (String str : elements) { + Object val = elementResultData.first().evaluate( str ) ; + Array.set( result, ctr++, val ) ; + } + + return result ; + } + } ; + } else if (type.equals( List.class )) { + final String sep = getSeparator( meth ) ; + Class elementClass = getListElementClass( meth ) ; + final ResultData elementResultData = getSimpleData( elementClass ) ; + myDescription = append( "A " + sep + "-separated list of ", + elementResultData.second() ) ; + + myFunc = new UnaryFunction() { + @Override + @SuppressWarnings("unchecked") + public Object evaluate( String value ) { + String[] elements = value.isEmpty() ? + new String[0] : value.split( sep ) ; + List result = new ArrayList( elements.length ) ; + for (String str : elements) { + Object val = elementResultData.first().evaluate( str ) ; + result.add( val ) ; + } + + return result ; + } + } ; + } else { + return getSimpleData( type ) ; + } + + return new ResultData( myFunc, + myDescription ) ; + } + + // Used for all types that take a single element. This does + // not include List or Type[]. + private ResultData getSimpleData( final Class type ) { + UnaryFunction myFunc = null ; + String[] myDescription = null ; + + if (type.isPrimitive()) { + myDescription = new String[] { "A valid " + type.getName() } ; + + myFunc = getPrimitiveParser( type ) ; + } else if (type == String.class){ + myDescription = new String[] { "A String" } ; + + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return str ; + } + } ; + } else if (type.isEnum()) { + myDescription = new String[] { + "One of: " + getEnumElements( type ) } ; + + myFunc = new UnaryFunction() { + @Override + @SuppressWarnings("unchecked") + public Object evaluate( String str ) { + try { + return Enum.valueOf( type, str ) ; + } catch (IllegalArgumentException exc) { + throw new RuntimeException( str + + " is not in enum " + type.getName() ) ; + } + } + }; + } else { // Anything else: must be a class that supports (String) + myDescription = new String[] { + "A string that can create a " + type.getName() } ; + + myFunc = makeClassConverter( type ) ; + } + + return new ResultData( myFunc, + myDescription ) ; + } + + private String getEnumElements( Class cls ) { + boolean isFirst = true ; + StringBuilder sb = new StringBuilder() ; + for (Object obj : cls.getEnumConstants()) { + if (isFirst) { + isFirst = false ; + } else { + sb.append( ' ' ) ; + } + sb.append( obj.toString() ) ; + } + return sb.toString() ; + } + + private UnaryFunction getPrimitiveParser( Class type ) { + UnaryFunction myFunc = null ; + + if (type == boolean.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Boolean.valueOf( str ) ; + } + } ; + } else if (type == byte.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Byte.valueOf( str ) ; + } + } ; + } else if (type == char.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + if (str.length() != 1) { + throw new RuntimeException("String \"" + str + + "\" cannot be converted to a Character"); + } + return Character.valueOf( str.charAt(0) ) ; + } + } ; + } else if (type == short.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Short.valueOf( str ) ; + } + } ; + } else if (type == int.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Integer.valueOf( str ) ; + } + } ; + } else if (type == long.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Long.valueOf( str ) ; + } + } ; + } else if (type == float.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Float.valueOf( str ) ; + } + } ; + } else if (type == double.class) { + myFunc = new UnaryFunction() { + @Override + public Object evaluate( String str ) { + return Double.valueOf( str ) ; + } + } ; + } + + return myFunc ; + } + + private UnaryFunction makeClassConverter( + final Class type ) { + + Constructor cons = null ; + + try { + cons = type.getConstructor( String.class ) ; + } catch (NoSuchMethodException e1) { + throw new RuntimeException( type.getName() + + " does not have a constructor (String)" ) ; + } catch (SecurityException e2) { + throw new RuntimeException( type.getName() + + " constructor (String) is not accessible" ) ; + } + + final Constructor fcons = cons ; + + return new UnaryFunction() { + @Override + public Object evaluate( String str ) { + try { + return fcons.newInstance( str ) ; + } catch (InvocationTargetException e1) { + throw new RuntimeException( type.getName() + + "(String) constructor threw exception: " + + e1.getTargetException() ) ; + } catch (Exception e2) { + throw new RuntimeException( "Exception " + e2 + + " occured in calling constructor " + + type.getName() + "(String)" ) ; + } + } + } ; + } + + private Class getListElementClass( Method meth ) { + Type rtype = meth.getGenericReturnType() ; + if (rtype instanceof ParameterizedType) { + ParameterizedType ptype = (ParameterizedType)rtype ; + Type[] typeArgs = ptype.getActualTypeArguments() ; + assert typeArgs.length == 1 ; + Type etype = typeArgs[0] ; + if (etype instanceof Class) { + return (Class)etype ; + } else { + throw new RuntimeException( "Method " + meth + + " has a List<> return type " + + " that is not parameterized by a class" ) ; + } + } else { + throw new RuntimeException( "Method " + meth + + " does not have a parameterized List return type" ) ; + } + } + + private String getSeparator( Method meth ) { + Separator sep = meth.getAnnotation( Separator.class ) ; + String result = "," ; + if (sep != null) { + result = sep.value(); + } + + return result ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Help.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Help.java new file mode 100644 index 000000000..cc50c499b --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Help.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.lang.annotation.Documented ; +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Help { + String value() default "" ; +} + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Pair.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Pair.java new file mode 100644 index 000000000..112cd37b2 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Pair.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2003, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +/** A utilitiy class representing a generic types Pair of elements. + * Useful for simple data structures, returning multiple values, etc. + * Pair is similar to a cons cell. + */ +public class Pair { + protected S _first ; + protected T _second ; + + public Pair( final S first, final T second ) { + _first = first ; + _second = second ; + } + + public Pair( final S first ) { + this( first, null ) ; + } + + public Pair() { + this( null ) ; + } + + public S first() { + return _first ; + } + + public T second() { + return _second ; + } + + @Override + public boolean equals( Object obj ) { + if (obj == this) { + return true ; + } + + if (!(obj instanceof Pair)) { + return false ; + } + + Pair pair = Pair.class.cast( obj ) ; + + if (first() == null ? + pair.first() == null : first().equals( pair.first())) { + return (second() == null ? + pair.second() == null : second().equals( pair.second())) ; + } else { + return false ; + } + } + + @Override + public int hashCode() { + int result = 0 ; + if (_first != null) { + result ^= _first.hashCode(); + } + if (_second != null) { + result ^= _second.hashCode(); + } + + return result ; + } + + @Override + public String toString() { + return "Pair[" + _first + "," + _second + "]" ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Separator.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Separator.java new file mode 100644 index 000000000..531eae81a --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/Separator.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +import java.lang.annotation.Documented ; +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Separator { + String value() default "" ; +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/UnaryFunction.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/UnaryFunction.java new file mode 100644 index 000000000..781e67a91 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/argparser/UnaryFunction.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2003, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package argparser ; + +public interface UnaryFunction { + R evaluate( T arg ) ; +} + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/AdminCommand.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/AdminCommand.java new file mode 100644 index 000000000..f8d235f12 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/AdminCommand.java @@ -0,0 +1,317 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package glassfish; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import testtools.Base; + +/** + * + * @author ken + */ +public class AdminCommand { + // Note that only one thread at a time may use an instance of AdminCommand. + private static final String ASADMIN_CMD_PROP = "test.folb.asadmin.command" ; + private static final String DEFAULT_ASADMIN = System.getProperty( + ASADMIN_CMD_PROP ) ; + + private final Base base ; + private final String asadmin ; + private final boolean echoOnly ; // echo command only if true: do not exec + private final List commandOutput = new ArrayList() ; + private final IntervalTimer timer = new IntervalTimer() ; + + public AdminCommand( Base base ) { + this( base, DEFAULT_ASADMIN ) ; + } + + public AdminCommand( Base base, String asadmin ) { + this( base, asadmin, false ) ; + } + public AdminCommand( Base base, String asadmin, boolean echoOnly ) { + this.base = base ; + this.asadmin = asadmin ; + this.echoOnly = echoOnly ; + } + + public static class IntervalTimer { + long lastTime ; + + public void start() { + lastTime = System.nanoTime() ; + } + + /** Returns interval since last start() or interval() call in + * microseconds. + * @return Elapsed time in microseconds + */ + public long interval() { + final long current = System.nanoTime() ; + final long diff = current - lastTime ; + start() ; + return diff/1000 ; + } + } + private boolean adminCommand( String command ) { + return Command(asadmin + " " + command); + } + + private boolean Command( String cmd ) { + commandOutput.clear() ; + base.note( "Command " + cmd ) ; + + if (!echoOnly) { + try { + timer.start() ; + final Process proc = Runtime.getRuntime().exec( cmd ) ; + final InputStream is = proc.getInputStream() ; + final BufferedReader reader = new BufferedReader( + new InputStreamReader( is ) ); + String line = reader.readLine() ; + while (line != null) { + base.note( line ) ; + commandOutput.add( line ) ; + line = reader.readLine() ; + } + + final int result = proc.waitFor(); + if (result != 0) { + throw new RuntimeException( "Command " + cmd + + " failed with result " + result ) ; + } + } catch (Exception ex) { + base.note( "Exception " + ex + " in " + cmd ) ; + // ex.printStackTrace(); + return false ; + } finally { + base.note( "Command " + cmd + " executed in " + + timer.interval() + " microseconds\n" ) ; + } + } + + return true ; + } + + public List commandOutput() { + return commandOutput ; + } + + public boolean startDomain() { + return adminCommand( "start-domain" ) ; + } + + public boolean stopDomain() { + return adminCommand( "stop-domain" ) ; + } + + public boolean enableSecureAdmin() { + return adminCommand( "enable-secure-admin" ) ; + } + + public boolean createCluster( String clusterName ) { + return adminCommand( "create-cluster " + clusterName ) ; + } + + public boolean deleteCluster( String clusterName ) { + return adminCommand( "delete-cluster " + clusterName ) ; + } + + public boolean startCluster( String clusterName ) { + return adminCommand( "start-cluster " + clusterName ) ; + } + + public boolean stopCluster( String clusterName ) { + return adminCommand( "stop-cluster " + clusterName ) ; + } + + public boolean createNodeSsh( String nodeHost, String installDir, + String agentName ) { + String str = String.format( + "--user admin create-node-ssh --nodehost %s --installdir %s %s", + nodeHost, installDir, agentName ); + return adminCommand( str ) ; + } + + public boolean destroyNodeSsh( String agentName ) { + return adminCommand( "delete-node-ssh " + agentName ) ; + } + + private String getPropertiesString( Properties props ) { + final StringBuilder sb = new StringBuilder() ; + final Set propNames = props.stringPropertyNames() ; + + boolean first = true ; + + for (String pname : propNames) { + if (first) { + first = false ; + } else { + sb.append( ':' ) ; + } + + sb.append( pname ) ; + sb.append( '=' ) ; + sb.append( props.getProperty(pname) ) ; + } + + return sb.toString() ; + } + + public boolean createSystemProperties( String instanceName, Properties props ) { + if (props == null) { + return false ; + } + + String command = String.format( + "create-system-properties --target %s %s", instanceName, + getPropertiesString(props)) ; + + boolean result = adminCommand( command ) ; + return result ; + } + + public boolean createInstance( String agentName, String clusterName, + int portBase, String instanceName ) { + String command = String.format( "create-instance --node %s " + + "--cluster %s --portbase %d --checkports=true %s", + agentName, clusterName, portBase, instanceName ) ; + + boolean result = adminCommand( command ) ; + + if (echoOnly) { + // for testing only + int current = portBase ; + for (StandardPorts sport : StandardPorts.values()) { + String msg = sport + "=" + current++ ; + base.note( msg ); + commandOutput.add( msg ) ; + } + } + + return result ; + } + + public boolean destroyInstance( String instanceName ) { + return adminCommand( "delete-instance " + instanceName ) ; + } + + + public void sleep( int seconds ) { + try { + // delay to make sure change has actually propagated + Thread.sleep(seconds * 1000); + } catch (InterruptedException ex) { + // ignore this + } + } + + public boolean startInstance( String name ) { + boolean result = adminCommand( "start-instance " + name) ; + // sleep(10) ; + return result ; + } + + public boolean stopInstance( String name ) { + boolean result = adminCommand( "stop-instance --force true " + name) ; + // sleep(10) ; + return result ; + } + + public boolean killInstance( String name ) { + // uniquely identify the process id + String processCommandContains = name + "/config" ; + if (!Command("scripts/kill " + processCommandContains)) { + System.out.println("SEVERE ERROR: Failed to kill instance " + name + ", trying stop instance!"); + return stopInstance(name); + } + return true ; + } + + public boolean destroyCluster(String clusterName) { + return adminCommand( "delete-cluster " + clusterName ) ; + } + + public boolean deploy( String clusterName, String componentName, + String jarFile ) { + + String cmd = String.format( "deploy --target %s --name %s --force %s", + clusterName, componentName, jarFile ) ; + + return adminCommand( cmd ) ; + } + + public boolean deploy( String clusterName, String componentName, + String jarFile, boolean availabilityEnabled ) { + + String cmd = String.format( "deploy --target %s --name %s --availabilityenabled=%b --force %s", + clusterName, componentName, availabilityEnabled, jarFile) ; + + return adminCommand( cmd ) ; + } + + public boolean undeploy( String clusterName, String componentName ) { + + String cmd = String.format( "undeploy --target %s --name %s --force", + clusterName, componentName ) ; + + return adminCommand( cmd ) ; + } + + public boolean set( String dottedName, String value ) { + String cmd = String.format( "set %s=%s", dottedName, value ) ; + return adminCommand( cmd ) ; + } + + public boolean get( String dottedName ) { + return adminCommand( "get " + dottedName ) ; + } + + public Map getOutputProperties() { + Map result = new HashMap() ; + for (String str : commandOutput() ) { + int index = str.indexOf( '=' ) ; + if (index > 0) { + final String key = str.substring( 0, index ) ; + final String value = str.substring( index + 1 ) ; + result.put( key, value ) ; + } + } + return result ; + } + + public boolean listClusters() { + return adminCommand( "list-clusters" ) ; + } + + public boolean listInstances( String clusterName ) { + return adminCommand( "list-instances " + clusterName ) ; + } + + public Map getOutputTable() { + Map result = new HashMap() ; + for (String str : commandOutput() ) { + String[] token = str.split( "\\s+" ) ; + if (token.length == 2) { + result.put( token[0], token[1] ) ; + } + } + return result ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/GlassFishCluster.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/GlassFishCluster.java new file mode 100644 index 000000000..b828368a1 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/GlassFishCluster.java @@ -0,0 +1,399 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package glassfish; + +import argparser.Pair; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import testtools.Base; + +/** Class used to create and manage a GlassFish cluster across multiple nodes. + * + * @author ken + */ +public class GlassFishCluster { + // This is also the definition used in the implementation of the + // EJB, but I don't want to import that here. Actually, this doesn't + // really belong here either, but it's too important to the IIOP FOLB + // tests to not include, and putting it into Main doesn't work either + // when createInstances is used. + public static final String INSTANCE_NAME_PROPERTY = "instance_name" ; + + private final GlassFishInstallation gfInst ; + private final String clusterName ; + private final Map instanceInfoMap ; + private final Set runningInstances ; + + public GlassFishCluster( GlassFishInstallation gfInst, String clusterName, + boolean skipSetup ) { + this.clusterName = clusterName ; + this.gfInst = gfInst ; + this.instanceInfoMap = new HashMap() ; + this.runningInstances = new HashSet() ; + + if (skipSetup) { + final AdminCommand ac = gfInst.ac() ; + ac.listInstances( clusterName ) ; + final Map instances = ac.getOutputTable() ; + for (Map.Entry entry : instances.entrySet()) { + final String inst = entry.getKey() ; + final String state = entry.getValue() ; + if (state.equals( "running" )) { + runningInstances.add( inst ) ; + } + final String instDNPrefix = "servers.server." + inst ; + final String naDN = instDNPrefix + ".node-ref" ; + ac.get( naDN ) ; + final Map naRef = ac.getOutputProperties() ; + final String na = naRef.get( naDN ) ; + + final String nodeDN = "nodes.node." + na + ".node-host" ; + ac.get(nodeDN) ; + final Map nodeRef = ac.getOutputProperties() ; + final String node = nodeRef.get( nodeDN ) ; + + final InstanceInfo ii = new InstanceInfo( inst, node ) ; + final String propsDN = instDNPrefix + ".system-property.*.value" ; + ac.get( propsDN ) ; + final Map ports = ac.getOutputProperties() ; + for (Map.Entry entry2 : ports.entrySet()) { + final String prop = entry2.getKey() ; + final String[] tokens = prop.split( "\\." ) ; + if (tokens.length == 6) { + final String key = tokens[4] ; + if (key.contains( "PORT" )) { + final String value = entry2.getValue() ; + final StandardPorts port = StandardPorts.valueOf( key ) ; + final int pnum = Integer.parseInt(value) ; + ii.addPort(port, pnum); + } + } + } + instanceInfoMap.put( inst, ii ) ; + } + } else { + gfInst.ac().createCluster( clusterName ) ; + for (Pair pair : gfInst.availableNodes()) { + String node = pair.first() ; + gfInst.ac().createNodeSsh( node, gfInst.installDir(), + gfInst.getNAName(node) ); + } + } + } + + public InstanceInfo createInstance( String instanceName, String nodeName, + int portBase ) { + return createInstance( instanceName, nodeName, portBase, "" ) ; + } + + public InstanceInfo createInstance( String instanceName, String nodeName, + int portBase, String orbDebug ) { + + gfInst.ac().createInstance( gfInst.getNAName( nodeName ), clusterName, + portBase, instanceName ) ; + InstanceInfo info = new InstanceInfo(instanceName, nodeName) ; + for (String str : gfInst.ac().commandOutput() ) { + int index = str.indexOf( '=' ) ; + if (index > 0) { + final String pnameString = str.substring( 0, index ) ; + final String pnumString = str.substring( index + 1 ) ; + StandardPorts pname = StandardPorts.valueOf(pnameString) ; + int pnum = Integer.parseInt(pnumString) ; + info.addPort( pname, pnum) ; + } + } + + instanceInfoMap.put( instanceName, info) ; + + String debugDottedName = + "configs.config." + clusterName + "-config.java-config.debug-enabled" ; + gfInst.ac().set( debugDottedName, "true" ) ; + + // Note: setting properties on GF 3.1 does not work properly on + // a create-instance commands: see issue 15683. + // So we use a separate command for this. + Properties props = new Properties() ; + if ((orbDebug != null) && !orbDebug.isEmpty()) { + props.setProperty( "com.sun.corba.ee.ORBDebug", orbDebug ) ; + gfInst.ac().createSystemProperties(instanceName, props); + } + + + return info ; + } + + private static final int CREATE_INSTANCES_PORT_BASE = 9000 ; + private static final int CREATE_INSTANCES_PORT_INCREMENT = 1000 ; + + // Worst case: run out of ports because of how this is constructed + // and how ports are allocated on a single node. This is 56, which + // should be more instances than I ever node for a unit test. + private static final int MAX_INSTANCES = + (Short.MAX_VALUE - CREATE_INSTANCES_PORT_BASE) / + CREATE_INSTANCES_PORT_INCREMENT ; + + /** Create a number of instances spread across the available nodes in the + * cluster. The name of each instance is instanceBaseName + number, for + * a number from 0 to numInstances - 1. numInstances must not exceed + * the total available capacity in the GF installation as indicated by + * the elements of gfInst.availableNodes. + * + * @param instanceBaseName The base name to use for all instance names. + * @param numInstances The number of instances to create. + * @param orbDebug comma separated list of ORBDebug flags to turn on in + * the created instances. + */ + public Map createInstances( String instanceBaseName, + int numInstances, String orbDebug ) { + return createInstances( instanceBaseName, numInstances, orbDebug, + CREATE_INSTANCES_PORT_BASE ) ; + } + + /** Create a number of instances spread across the available nodes in the + * cluster. The name of each instance is instanceBaseName + number, for + * a number from 0 to numInstances - 1. numInstances must not exceed + * the total available capacity in the GF installation as indicated by + * the elements of gfInst.availableNodes. + * + * @param instanceBaseName The base name to use for all instance names. + * @param numInstances The number of instances to create. + * @param orbDebug comma separated list of ORBDebug flags to turn on in + * the created instances. + */ + public Map createInstances( String instanceBaseName, + int numInstances, String orbDebug, int portBase ) { + + int numAvailable = 0 ; + for (Pair pair : gfInst.availableNodes() ) { + numAvailable += pair.second() ; + } + + if (numInstances > MAX_INSTANCES) { + throw new RuntimeException( "Request number of instances " + + numInstances + " is greater than maximum instances supported" + + MAX_INSTANCES ) ; + } + + if (numInstances > numAvailable) { + throw new RuntimeException( "Request number of instances " + + numInstances + " is greater than available instances " + + numAvailable ) ; + } + + WeightedCircularIterator iter = + new WeightedCircularIterator() ; + for (Pair pair : gfInst.availableNodes() ) { + iter.add( pair.first(), pair.second() ) ; + } + + final Map result = + new HashMap() ; + for (int index=0; index runningInstances() { + return new HashSet( runningInstances ) ; + } + + public void startCluster() { + if (gfInst.ac().startCluster(clusterName)) { + runningInstances.clear() ; + runningInstances.addAll( instanceInfoMap.keySet() ) ; + } + } + + public void stopCluster() { + if (gfInst.ac().stopCluster(clusterName)) { + runningInstances.clear() ; + } + } + + public void destroyCluster() { + stopCluster() ; + + Set instances = new HashSet( instanceInfoMap.keySet() ) ; + for (String instName : instances) { + destroyInstance(instName) ; + } + + for (Pair pair : gfInst.availableNodes()) { + String node = pair.first() ; + gfInst.ac().destroyNodeSsh( gfInst.getNAName(node) ); + } + + gfInst.ac().destroyCluster( clusterName ) ; + } + + public void sleep(int seconds ) { + gfInst.ac().sleep( seconds ) ; + } + + public static class InstanceInfo { + private final String name ; + private final String node ; + private final Map portMap ; + + public InstanceInfo( String name, String node ) { + this.name = name ; + this.node = node ; + this.portMap = new EnumMap( + StandardPorts.class) ; + } + + public String name() { + return name ; + } + + public String node() { + return node ; + } + + public Map ports() { + return portMap ; + } + + void addPort( StandardPorts pname, int pnum ) { + portMap.put( pname, pnum ) ; + } + + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "InstanceInfo[" ) ; + sb.append( name ).append( ',' ) ; + sb.append( node ).append( ',' ) ; + sb.append( portMap.toString() ) ; + sb.append( ']' ) ; + return sb.toString() ; + } + } + + public Map instanceInfo() { + return instanceInfoMap ; + } + + public static class Test extends Base { + private static final String installDir = + "/volumes/work/GlassFish/v3/glassfishv3/glassfish" ; + private static final String dasNodeName = "minas" ; + private static final List> availableNodes = + new ArrayList>() ; + + static { + availableNodes.add( new Pair( "minas", 3 ) ) ; + availableNodes.add( new Pair( "hermes", 2 ) ) ; + availableNodes.add( new Pair( "apollo", 4 ) ) ; + } + + private GlassFishInstallation gfInst = + new GlassFishInstallation( this, installDir, dasNodeName, + availableNodes, true, false ) ; + + private static final String clusterName = "c1" ; + + private GlassFishCluster gfCluster = + new GlassFishCluster( gfInst, clusterName, false ) ; + + @testtools.Test + public void testCreateInstance() { + InstanceInfo info = gfCluster.createInstance( "in1", "minas", 2000 ) ; + note( "createInstance returned " + info ) ; + gfCluster.destroyInstance( "in1" ) ; + } + + @testtools.Test + public void testCreateInstances() { + Map infos = gfCluster.createInstances( + "in", 7, "" ) ; + note( "createInstances returned " + infos ) ; + gfCluster.destroyCluster(); + } + + @testtools.Test + public void testStartStop() { + Map infos = gfCluster.createInstances( + "in", 7, "" ) ; + Set instances = new HashSet( + infos.keySet() ) ; + gfCluster.startCluster() ; + check( instances.equals( gfCluster.runningInstances() ), + "Expected running instances does not match instances") ; + + gfCluster.stopInstance( "in1" ) ; + instances.remove( "in1" ) ; + check( instances.equals( gfCluster.runningInstances() ), + "Expected running instances does not match instances") ; + + gfCluster.startInstance( "in1" ) ; + instances.add( "in1" ) ; + check( instances.equals( gfCluster.runningInstances() ), + "Expected running instances does not match instances") ; + + gfCluster.stopCluster() ; + instances.clear() ; + check( instances.equals( gfCluster.runningInstances() ), + "Expected running instances does not match instances") ; + } + + public Test( String[] args ) { + super( args ) ; + } + } + + public static void main( String[] args ) { + Test test = new Test( args ) ; + test.run() ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/GlassFishInstallation.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/GlassFishInstallation.java new file mode 100644 index 000000000..1972c1ad4 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/GlassFishInstallation.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package glassfish; + +import java.util.List; +import argparser.Pair ; +import java.io.File; +import java.util.ArrayList; +import testtools.Base; + +/** + * + * @author ken + */ +public class GlassFishInstallation { + private final Base base ; + private final String installDir ; + private final String dasNodeName ; + private final List> availableNodes ; + private final AdminCommand ac ; + private boolean isDestroyed = false ; + private boolean skipSetup ; + + public String installDir() { + return installDir ; + } + + public String dasNodeName() { + return dasNodeName ; + } + + public List> availableNodes() { + return availableNodes ; + } + + public String getNAName( String name ) { + return name + "NA" ; + } + + public AdminCommand ac() { + return ac ; + } + + /** Create a GlassFish installation and all of the node agents needed. + * After the construction completes, the DAS and node agents are running, + * but no instances have been created. + * + * @param installDir Installation directory for GF (contains bin). + * @param dasNodeName Name of node used for DAS. + * @param availableNodes List of node name, max supported instances for each + * available node (may include DAS node). + */ + public GlassFishInstallation( Base base, String installDir, + String dasNodeName, List> availableNodes, + boolean echoOnly, boolean skipSetup ) { + this.base = base ; + this.installDir = installDir ; + if (!installDir.endsWith( File.separator )) { + installDir += File.separator ; + } + this.dasNodeName = dasNodeName ; + this.availableNodes = availableNodes ; + this.ac = new AdminCommand( base, installDir + "glassfish/bin/asadmin", + echoOnly ) ; + this.skipSetup = skipSetup ; + start() ; + } + + public GlassFishInstallation( Base base, String installDir, + String dasNodeName, List> availableNodes ) { + this( base, installDir, dasNodeName, availableNodes, false, false ) ; + } + + private void checkDestroyed() { + if (isDestroyed) { + throw new RuntimeException( + "GlassFish installation has been destroyed") ; + } + } + + private void checkAdminCommand( boolean result ) { + if (!result) { + throw new RuntimeException( "Admin command failed" ) ; + } + } + + /** Start the domain and enable secure mode + * + */ + public final void start() { + if (!skipSetup) { + checkDestroyed() ; + checkAdminCommand( ac.startDomain() ) ; + } + } + + /** Stop the domain + * + */ + public final void stop() { + if (!skipSetup) { + checkDestroyed() ; + checkAdminCommand( ac.stopDomain() ) ; + } + } + + public final void destroy() { + stop() ; + isDestroyed = true ; + } + + public static class Test extends Base { + private static final String installDir = + "/volumes/work/GlassFish/v3/glassfishv3/glassfish" ; + private static final String dasNodeName = "minas" ; + private static final List> availableNodes = + new ArrayList>() ; + + static { + availableNodes.add( new Pair( "minas", 3 ) ) ; + availableNodes.add( new Pair( "hermes", 2 ) ) ; + availableNodes.add( new Pair( "apollo", 4 ) ) ; + } + + private GlassFishInstallation gfInst = + new GlassFishInstallation( this, installDir, dasNodeName, + availableNodes, true, false ) ; + + @testtools.Test + public void test() { + gfInst.stop() ; + gfInst.start() ; + gfInst.destroy() ; + } + + public Test( String[] args ) { + super( args ) ; + } + } + + public static void main( String[] args ) { + Test test = new Test( args ) ; + test.run() ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/StandardPorts.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/StandardPorts.java new file mode 100644 index 000000000..118911d8b --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/StandardPorts.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package glassfish; + +/** The standard ports GlassFish uses. The create-instance command returns + * these in the form (NAME)=nnnn. + * + * @author ken_admin + */ +public enum StandardPorts { + HTTP_LISTENER_PORT, + HTTP_SSL_LISTENER_PORT, + IIOP_LISTENER_PORT, + IIOP_SSL_LISTENER_PORT, + IIOP_SSL_MUTUALAUTH_PORT, + JAVA_DEBUGGER_PORT, + JMX_SYSTEM_CONNECTOR_PORT, + JMS_PROVIDER_PORT, + ASADMIN_LISTENER_PORT, + GMS_LISTENER_PORT, + OSGI_SHELL_TELNET_PORT ; +} ; + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/WeightedCircularIterator.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/WeightedCircularIterator.java new file mode 100644 index 000000000..efddc98ec --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/glassfish/WeightedCircularIterator.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package glassfish; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +/** An iterator that iterates over the elements of a list. + * Each element will be returned the number of times of its weight. + * hasNext() is true until each element has been returned at many + * times as its weight. + * + * @author ken_admin + */ +public class WeightedCircularIterator implements Iterator { + private final List elements = new ArrayList() ; + private final Map weights = new HashMap() ; + private final Map counts = new HashMap() ; + private int current = 0 ; + + public void add( T elem, int weight ) { + elements.add( elem ) ; + weights.put( elem, weight ) ; + counts.put( elem, 0 ) ; + } + + @Override + public boolean hasNext() { + return !elements.isEmpty() ; + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException( + "Collection is empty, so no next element") ; + } + + if (current > (elements.size()-1)) { + current = 0 ; + } + + T result = elements.get( current ) ; + + int count = counts.get( result ) ; + count++ ; + counts.put( result, count ) ; + if (count == weights.get( result )) { + elements.remove( current ) ; + } else { + current++ ; + } + + return result ; + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Not supported yet."); + } + + public static void main( String[] args ) { + WeightedCircularIterator iter = + new WeightedCircularIterator() ; + + iter.add( "A", 5 ) ; + iter.add( "B", 3 ) ; + iter.add( "C", 1 ) ; + iter.add( "D", 4 ) ; + + String[] strs = { "A", "B", "C", "D", "A", "B", "D", "A", "B", "D", + "A", "D", "A" } ; + + for (String str : strs) { + if (!iter.hasNext()) { + throw new RuntimeException( "Unexpected failure of hasNext") ; + } + + String next = iter.next() ; + System.out.println( next ) ; + if (!str.equals( next )) { + throw new RuntimeException( + "Expected " + str + ", got " + next ) ; + } + } + + if (iter.hasNext()) { + throw new RuntimeException( + "hasNext true after all elements exhausted" ) ; + } + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/Location.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/Location.java new file mode 100644 index 000000000..9e63f3dcc --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/Location.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +/** + * + * @author ken + */ +public interface Location { + public String getLocation(); +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/LocationBean.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/LocationBean.java new file mode 100644 index 000000000..5e7cf9219 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/LocationBean.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package orb.folb; + +import javax.ejb.Stateless; +import java.net.InetAddress; +import java.util.Properties; +import java.util.Enumeration; + +/** + * + * @author hv51393 + */ +@Stateless +public class LocationBean implements LocationBeanRemote { + + public String getLocation() { + + try { + String instanceName = System.getProperty("com.sun.aas.instanceName"); + return instanceName; + } catch (Exception e) { + return null; + } + } + + public String getHostName() { + + try { + String hostName = InetAddress.getLocalHost().getCanonicalHostName(); + return hostName ; + } catch (Exception e) { + return null; + } + } + + public void printSystemProperties() { + Properties p = System.getProperties(); + Enumeration keys = p.keys(); + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + String value = (String) p.get(key); + System.out.println(key + ": " + value); + } + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/LocationBeanRemote.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/LocationBeanRemote.java new file mode 100644 index 000000000..af3aaa42e --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/LocationBeanRemote.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +import javax.ejb.Remote; + +/** + * + * @author hv51393 + */ +@Remote +public interface LocationBeanRemote extends Location { + public String getHostName(); + public void printSystemProperties(); + +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/StatefullLocationBean.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/StatefullLocationBean.java new file mode 100644 index 000000000..c085a8e66 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/StatefullLocationBean.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +import javax.ejb.Stateful; + +/** + * + * @author ken + */ +@Stateful +public class StatefullLocationBean implements StatefullLocationBeanRemote { + @Override + public String getLocation() { + try { + String instanceName = System.getProperty("com.sun.aas.instanceName"); + return instanceName; + } catch (Exception e) { + return null; + } + } + +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/StatefullLocationBeanRemote.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/StatefullLocationBeanRemote.java new file mode 100644 index 000000000..9c772651e --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orb/folb/StatefullLocationBeanRemote.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +import javax.ejb.Remote; + +/** + * + * @author ken + */ +@Remote +public interface StatefullLocationBeanRemote extends Location { +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orbfailover/Main.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orbfailover/Main.java new file mode 100644 index 000000000..552d7b4c7 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/orbfailover/Main.java @@ -0,0 +1,1232 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package orbfailover; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import argparser.DefaultValue; +import argparser.Help; +import argparser.Pair; + +import glassfish.AdminCommand; +import glassfish.GlassFishCluster; +import glassfish.GlassFishInstallation; +import glassfish.StandardPorts; +import java.util.HashSet; +import java.util.Hashtable; +import javax.naming.Context; +import javax.naming.NameClassPair; +import javax.naming.NamingEnumeration; + +import orb.folb.LocationBeanRemote; + +import testtools.Test ; +import testtools.Base ; +import testtools.Post; +import testtools.Pre; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import java.lang.reflect.Field; +import javax.rmi.CORBA.Stub; +import orb.folb.Location; + + + +/** + * @author hv51393 + * @author kcavanaugh + */ +public class Main extends Base { + // @EJB + // private static LocationBeanRemote locationBean; + private static final String CLUSTER_NAME = "c1" ; + private static final String EJB_NAME = "TestEJB" ; + private static final String INSTANCE_BASE_NAME = "in" ; + + private ORB orb = null ; + private String[] orbDebugFlags = null ; + + private GlassFishInstallation gfInstallation ; + private AdminCommand ac ; + private GlassFishCluster gfCluster ; + private Map clusterInfo ; + + private static final String beanJndiName = + "orb.folb.LocationBeanRemote"; + private static final String statefullBeanJndiName = + "orb.folb.StatefullLocationBeanRemote"; + + private static Pair split(String str) { + int index = str.indexOf( ':' ) ; + final String first = str.substring( 0, index ) ; + final String second = str.substring( index + 1 ) ; + final int value = Integer.valueOf( second ) ; + return new Pair( first, value ) ; + } + + private static List> parseStringIntPair( + List args ) { + + List> result = + new ArrayList>() ; + for (String str : args) { + result.add( split( str ) ) ; + } + return result ; + } + + // Get an IIOP endpoint list from a set of instance names. + private String getIIOPEndpointList( Set instances ) { + final StringBuilder sb = new StringBuilder() ; + boolean first = true ; + for (String str : instances) { + if (first) { + first = false ; + } else { + sb.append( ',' ) ; + } + + final GlassFishCluster.InstanceInfo info = + gfCluster.instanceInfo().get( str ) ; + final String host = info.node() ; + final int port = info.ports().get( StandardPorts.IIOP_LISTENER_PORT ) ; + sb.append( host ).append( ':' ).append( port ) ; + } + + return sb.toString() ; + } + + // Returns string of : separated by commas + // for all running instances. + private String getIIOPEndpointList() { + return getIIOPEndpointList( gfCluster.runningInstances()) ; + } + + private InitialContext makeIC() throws NamingException { + return makeIC( getIIOPEndpointList() ) ; + } + + private InitialContext makeIC( String eplist ) throws NamingException { + InitialContext result ; + if (eplist != null && !inst.useExternalEndpoints()) { + final Hashtable table = new Hashtable() ; + table.put( "com.sun.appserv.iiop.endpoints", eplist ) ; + result = new InitialContext( table ) ; + } else { + result = new InitialContext() ; + } + + note( "Created new InitialContext with endpoints " + eplist ) ; + + return result ; + } + + private String invokeMethod( Location locBean ) { + String result = locBean.getLocation() ; + note( "Invocation returned " + result ) ; + return result ; + } + + private enum BeanType { SFSB, SLSB } + + private Location lookup( InitialContext ic ) + throws NamingException { + + return lookup( ic, BeanType.SLSB ) ; + } + + private Location lookup( InitialContext ic, BeanType bt ) + throws NamingException { + + Location lb = (Location)ic.lookup( + (bt == BeanType.SLSB) ? beanJndiName : statefullBeanJndiName ) ; + + getORB( lb ) ; + note( "Looked up bean in context") ; + return lb ; + } + + private Location lookupUsingJavaCmp( InitialContext ic, BeanType bt ) + throws NamingException { + + Context ctx = (Context)ic.lookup( "java:comp/env/ejb" ) ; + Location lb = (Location)ctx.lookup( + (bt == BeanType.SLSB) ? beanJndiName : statefullBeanJndiName ) ; + + getORB( lb ) ; + note( "Looked up bean in context") ; + return lb ; + } + + private Field getField( Class cls, String name ) { + Field result = null ; + try { + result = cls.getDeclaredField(name); + result.setAccessible(true); + } catch (Exception ex) { + Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); + } + + return result; + } + + private void getORB(Location lb) { + if (orb == null) { + try { + final Class lbClass = lb.getClass() ; + final Field delegateField = getField( lbClass, "delegate_") ; + final Stub stub = (Stub)delegateField.get( lb ) ; + + // final Class delegateClass = delegate.getClass() ; + // delegateSuperClass should be a CodegenStubBase + // final Class delegateSuperClass = delegateClass.getSuperclass() ; + // final Field fld = getField( delegateSuperClass, "__delegate"); + final ClientDelegate cdel = + (ClientDelegate)stub._get_delegate() ; + + orb = cdel.getBroker(); + if (orbDebugFlags != null) { + setORBDebug( orbDebugFlags ) ; + } + } catch (Exception ex) { + Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + + private void setORBDebug( String... args ) { + if (orb != null) { + if (args != null) { + orb.setDebugFlags( args ) ; + } + } else { + orbDebugFlags = args ; + } + } + + private void clearORBDebug( String... args ) { + if (orb != null) { + if (args != null) { + orb.clearDebugFlags( args ) ; + } + } else { + orbDebugFlags = null ; + } + } + + public interface Installation { + @DefaultValue("") + @Help("Name of directory where GlassFish is installed") + String installDir() ; + + @DefaultValue("") + @Help("Name of node for GlassFish DAS") + String dasNode() ; + + @DefaultValue("") + @Help("A list of available nodes for cluster setup: comma separed list of name:number") + List availableNodes() ; + + @DefaultValue("") + @Help("The test EJB needed for this test") + String testEjb() ; + + @DefaultValue( "false" ) + @Help("Set if we want to shutdown and destroy the cluster after the test") + boolean doCleanup() ; + + @DefaultValue( "false" ) + @Help( "Set if the cluster is already setup and running in order to avoid" + + "extra processing") + boolean skipSetup() ; + + @DefaultValue( "5" ) + @Help( "Set the number of instances to create in the cluster. " + + "There must be sufficient availability declared in availableNodes " + + "for this many instances") + int numInstances() ; + + @DefaultValue( "false" ) + @Help( "Set this to true if you only want to set up a cluster, and do NOT" + + "want to run any tests") + boolean skipTests() ; + + @DefaultValue( "" ) + @Help( "Set this to the comma separated list of ORB debug flags to use" + + " on the app server instances") + String serverORBDebug() ; + + @DefaultValue( "false" ) + @Help( "Set this to true if the test uses only externally supplied IIOP" + + "endpoints") + boolean useExternalEndpoints() ; + } + + private final Installation inst ; + + public Main( String[] args ) { + super( args, Installation.class ) ; + inst = getArguments( Installation.class ) ; + try { + List> avnodes = parseStringIntPair( + inst.availableNodes() ) ; + gfInstallation = new GlassFishInstallation( this, + inst.installDir(), inst.dasNode(), avnodes, false, + inst.skipSetup() ) ; + ac = gfInstallation.ac() ; + + gfCluster = new GlassFishCluster( gfInstallation, CLUSTER_NAME, + inst.skipSetup()) ; + if (!inst.skipSetup()) { + clusterInfo = gfCluster.createInstances( INSTANCE_BASE_NAME, + inst.numInstances(), inst.serverORBDebug() ) ; + gfCluster.startCluster() ; + if (!inst.testEjb().isEmpty()) { + boolean availabilityEnabled = true ; + ac.deploy( CLUSTER_NAME, EJB_NAME, inst.testEjb(), + availabilityEnabled ) ; + } + } else { + gfCluster.startCluster() ; + clusterInfo = gfCluster.instanceInfo() ; + } + + } catch (Exception exc) { + System.out.println( "Exception in constructor: " + exc ) ; + exc.printStackTrace() ; + cleanup() ; + } + } + + private void cleanup() { + if (inst.doCleanup()) { + if (ac != null) { + ac.undeploy( CLUSTER_NAME, EJB_NAME ) ; + ac = null ; + } + + if (gfCluster != null) { + gfCluster.destroyCluster() ; + gfCluster = null ; + } + + if (gfInstallation != null) { + gfInstallation.destroy() ; + gfInstallation = null ; + } + } + } + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + Main m = new Main( args ); + int result = 0 ; + if (!m.inst.skipTests()) { + result = 1 ; + if (m.gfCluster != null) { + try { + result = m.run() ; + } finally { + m.cleanup() ; + } + } + } + System.exit( result ) ; + } + + // Not a useful test: listing of context is broken in GF 3.1. + // @Test( "listContextTest" ) + public void listContextTest() throws NamingException { + InitialContext ic = makeIC() ; + listContext( ic, 0 ) ; + } + + private String indent( String str, int size ) { + String fmt = String.format( "%%%d%%s", size ) ; + return String.format( fmt, str ) ; + } + + private void listContext( Context ctx, int level ) throws NamingException { + final NamingEnumeration ne = ctx.list( "" ) ; + final int size = 4*level ; + while (ne.hasMore()) { + final NameClassPair pair = ne.next() ; + final String name = pair.getName() ; + + Object val = null ; + try { + val = ctx.lookup( name ) ; + } catch (Exception exc) { + val = "*UNAVAILABLE* (" + pair.getClassName() + ")" ; + } + + final StringBuilder sb = new StringBuilder() ; + if (val instanceof Context) { + final Context ctx2 = (Context)val ; + sb.append( name ).append( ':' ) ; + note( indent( sb.toString(), size ) ) ; + listContext( ctx2, level+1 ) ; + } else { + sb.append( name ).append( "=>" ).append( val.toString() ) ; + note( indent( sb.toString(), size ) ) ; + } + } + } + + @Test( "failover" ) + public void failOverTest() { + final int numCalls = 150 ; + final int stopAt = numCalls/3 ; + final int startAt = 2*numCalls/3 ; + String stoppedInstance = null ; + + boolean failOverDetected = false; + try { + InitialContext ctx = makeIC(); + Location locBean = lookup( ctx ) ; + String origLocation = invokeMethod( locBean ); + if (origLocation == null) { + fail( "couldn't get the instance name!"); + } + for (int i = 1; i <= numCalls; i++) { + String newLocation = null ; + try { + newLocation = invokeMethod( locBean ); + } catch (Exception e) { + fail( "caught invocation exception " + e ); + } + + note( "result[" + i + "]= " + newLocation); + if (!origLocation.equals(newLocation)) { + failOverDetected = true; + } + + if (i == stopAt) { + stoppedInstance = newLocation ; + ac.stopInstance( stoppedInstance ); + } + + if (i == startAt) { + ac.startInstance( stoppedInstance ) ; + stoppedInstance = null ; + } + } + } catch (Exception exc) { + fail( "caught naming exception " + exc ) ; + } finally { + if (stoppedInstance != null) { + ac.startInstance( stoppedInstance ) ; + } + } + } + + private void increment( Map map, String name ) { + Integer val = map.get( name ) ; + if (val == null) { + val = Integer.valueOf(1) ; + } else { + val = Integer.valueOf( val.intValue() + 1 ) ; + } + + map.put( name, val ) ; + } + + @Test( "loadbalance" ) + public void testLoadBalance( ) throws NamingException { + doLoadBalance( gfCluster.runningInstances(), 1000 ) ; + } + + @Test( "15768" ) + public void test15768( ) throws NamingException { + doLoadBalanceUsingJavaCmp( gfCluster.runningInstances(), 100, + getIIOPEndpointList() ) ; + } + + private T pick( Set set ) { + return pick( set, false ) ; + } + + private T pick( Set set, boolean remove ) { + T result = null ; + for (T elem : set) { + result = elem ; + break ; + } + + if (remove) { + set.remove( result ) ; + } + + return result ; + } + + // Test scenario for issue 14762: + // 1. Deploy the app + // 2. Bring down the cluster + // 3. Start one instance (firstinstance) + // 4. Create 10 new IC, and do ejb lookups (appclient is run with + // endpoints having all instances host:port info) + // 5. Bring up all remaining instances + // 6. Kill Instance where we created ic and did lookups + // 7. Access business methods for the ejb's (created in step 4) + @Test( "14762" ) + public void test14762() throws NamingException { + gfCluster.stopCluster(); + + Set strs = new HashSet( clusterInfo.keySet() ) ; + final String first = pick( strs, true ) ; + final String second = pick( strs, true ) ; + ac.startInstance(first) ; + + Set initialInstances = new HashSet() ; + initialInstances.add( first ) ; + initialInstances.add( second ) ; + String initial = getIIOPEndpointList( initialInstances ) ; + + final List ics = new ArrayList() ; + final List lbs = new ArrayList() ; + for (int ctr=0; ctr<10; ctr++) { + final String str = (ctr==0) ? initial : null ; + final InitialContext ic = makeIC(str) ; + ics.add( ic ) ; + final Location lb = lookup( ic ) ; + lbs.add( lb ) ; + } + ensure() ; + ac.stopInstance(first); + for (Location lb : lbs ) { + String loc = invokeMethod( lb ) ; + check( !loc.equals( first), + "Location returned was stopped instance " + first) ; + } + } + + // Test scenario for issue 14755: + // 1. New Initial Context + // 2. Lookup EJB + // 3. Call a Business method + // 4. Find the instance that served the business method - firstinstance + // 5. Kill that instance + // 6. Call business method + // 7. Now the request will be served by another instance - secondinstance + // 8. Bring back the first instance (which we killed before) + // Call business method + // 9. The request goes to firstinstance (it should go to secondinstance - since it + // should be sticky) + @Test( "14755" ) + public void test14755() throws NamingException { + InitialContext ic = makeIC() ; + Location lb = lookup( ic ) ; + String first = invokeMethod( lb ) ; + ac.stopInstance(first); + String second = invokeMethod( lb ) ; + check( !first.equals( second ), + "Method executed on instance that was supposed to be down " + second ) ; + ac.startInstance( first ) ; + String result = invokeMethod( lb ) ; + check( result.equals( second ), + "Request did not stick to instance " + second + + " after original instance " + first + " restarted" ) ; + } + + // Test scenario for issue 14766: + // 1. start up all instances + // 2. start up client with target-server+ A:B:C + // 3. do new IntialContext/lookup + // 4. do one request - ensure it works + // 5. shutdown A + // 6. do one request - ensure it works + // 7. shutdown B + // 8. do one request - ensure it works + // 9. restart A + // 10 do one request - ensure it works + // 11 shutdown C + // 12 do one request - ensure it works + @Test( "14766") + public void test14766() throws NamingException { + InitialContext ctx = makeIC() ; + Location locBean = lookup( ctx ) ; + + String loc1 = invokeMethod( locBean ); + ac.stopInstance(loc1); + + String loc2 = invokeMethod( locBean ) ; + check( !loc1.equals(loc2), "Failover did not happen") ; + ac.stopInstance(loc2); + + String loc3 = invokeMethod( locBean ) ; + check( !loc3.equals(loc2), "Failover did not happen") ; + ac.startInstance(loc1); + + String loc4 = invokeMethod( locBean ) ; + check( loc4.equals(loc3), "No failover expected" ) ; + ac.stopInstance(loc3); + + String loc5 = invokeMethod( locBean ) ; + check( !loc5.equals(loc4), "Failover did not happen") ; + } + + @Test( "lbfail" ) + public void testLBFail() throws NamingException { + final int numCalls = 200 ; + doLoadBalance( gfCluster.runningInstances(), numCalls ) ; + + final String inst1 = pick( gfCluster.runningInstances() ) ; + gfCluster.stopInstance(inst1) ; + doLoadBalance( gfCluster.runningInstances(), numCalls ) ; + + final String inst2 = pick( gfCluster.runningInstances() ) ; + gfCluster.stopInstance(inst2) ; + + final String inst3 = pick( gfCluster.runningInstances() ) ; + + gfCluster.startInstance(inst1); + gfCluster.sleep( 5 ) ; // Seems to take a while to wake up? + doLoadBalance( gfCluster.runningInstances(), numCalls ) ; + + gfCluster.stopInstance(inst3); + doLoadBalance( gfCluster.runningInstances(), numCalls ) ; + } + + public void doLoadBalance( Set expected, + int numCalls ) throws NamingException { + doLoadBalance( expected, numCalls, getIIOPEndpointList() ) ; + } + + public Location doLoadBalance( Set expected, int numCalls, + String endpoints ) throws NamingException { + Location current = null ; + // XXX add checking for approximate distribution + // according to weights + Map counts = + new HashMap() ; + + String newLocation = "" ; + for (int i = 1; i <= numCalls ; i++) { + InitialContext ctx = makeIC( endpoints ) ; + current = lookup( ctx ) ; + newLocation = invokeMethod( current ); + note( "result[" + i + "]= " + newLocation); + increment( counts, newLocation ) ; + } + + note( "Call distribution: (expected on instances " + expected + ")" ) ; + for (Map.Entry entry : counts.entrySet()) { + int count = entry.getValue().intValue() ; + note( String.format( "\tName = %20s Count = %10d", + entry.getKey(), count ) ) ; + } + + check( expected.equals(counts.keySet()), + "Requests not loadbalanced across expected instances: " + + " expected " + expected + ", actual " + counts.keySet() ) ; + + return current ; + } + + public Location doLoadBalanceUsingJavaCmp( Set expected, + int numCalls, String endpoints ) throws NamingException { + Location current = null ; + // XXX add checking for approximate distribution + // according to weights + Map counts = + new HashMap() ; + + String newLocation = "" ; + for (int i = 1; i <= numCalls ; i++) { + InitialContext ctx = makeIC( endpoints ) ; + current = lookupUsingJavaCmp( ctx, BeanType.SLSB ) ; + newLocation = invokeMethod( current ); + note( "result[" + i + "]= " + newLocation); + increment( counts, newLocation ) ; + } + + note( "Call distribution: (expected on instances " + expected + ")" ) ; + for (Map.Entry entry : counts.entrySet()) { + int count = entry.getValue().intValue() ; + note( String.format( "\tName = %20s Count = %10d", + entry.getKey(), count ) ) ; + } + + check( expected.equals(counts.keySet()), + "Requests not loadbalanced across expected instances: " + + " expected " + expected + ", actual " + counts.keySet() ) ; + + return current ; + } + + public void doLoadBalance( Set expected, Set ics + ) throws NamingException { + // XXX add checking for approximate distribution + // according to weights + Map counts = + new HashMap() ; + + String newLocation = "" ; + int i = 0 ; + for (InitialContext ctx : ics ) { + Location locBean = lookup( ctx ) ; + newLocation = invokeMethod( locBean ); + note( "result[" + (i++) + "]= " + newLocation); + increment( counts, newLocation ) ; + } + + note( "Call distribution:" ) ; + for (Map.Entry entry : counts.entrySet()) { + int count = entry.getValue().intValue() ; + note( String.format( "\tName = %20s Count = %10d", + entry.getKey(), count ) ) ; + } + + check( (counts.keySet().size() == 1) + && expected.containsAll( counts.keySet() ), + "Request did not failover to a single instance in expected instance " + + expected ) ; + } + + // Test scenario for issue 14732: + // 1. One instance of cluster is running (all remaining are stopped) + // 2. Create Initial Context (with endpoints having all instance host and ports) + // 3. Do EJB Lookup + // 4. Call Business method + // 5. Create InitialContext + // 6. Stop Instance (the only instance) + // 7. Start remaining instances + // 8. Do lookup (the expectation is it will failover to other instance) + // 9. Call Business Method + @Test( "14732" ) + public void test14732() throws NamingException { + // Capture full endpoint list for later use in makeIC. + String endpoints = getIIOPEndpointList() ; + + // Make sure only inst is running + boolean first = true ; + String running = "" ; + for (String inst : gfCluster.runningInstances()) { + if (first) { + running = inst ; + note( "Running instance is " + inst ) ; + first = false ; + } else { + ac.stopInstance(inst); + } + } + + InitialContext ctx = makeIC( endpoints ) ; + note( "got new initial context") ; + + Location locBean = lookup( ctx ) ; + note( "located EJB" ) ; + + String current = invokeMethod( locBean ); + note( "EJB invocation returned " + current ) ; + check( current.equals( running ), + "Current location " + current + " is not the same as the" + + " running location " + running ) ; + + ac.stopInstance( running ) ; + for (String inst : clusterInfo.keySet()) { + if (!inst.equals(running)) { + ac.startInstance( inst ) ; + } + } + + locBean = lookup( ctx ) ; + note( "Locating EJB second time") ; + + current = invokeMethod( locBean ); + note( "EJB invocation returned " + current ) ; + check( !current.equals( running ), + "Apparent location " + current + + " is the same as a stoppped instance " + running ) ; +} + + // Test scenario for issue 14867: + // 1. Deploy an application to a cluster with three instances + // 2. Start up one client with target-server+ specifying the three instances. + // 3. In a loop (100 iterations): + // 1. Create a new InitialContext + // 2. Do a lookup + // 3. Remember which instance the lookup went to + // 4. Create and start two new instances + // 5. Then do 100 new IntialContext/lookup. + // 6. Destroy new instances. + // New instances should process some of new requests + @Test( "14867c" ) + public void test14867createInstances() throws NamingException { + Set instances = gfCluster.runningInstances() ; + note( "Running instances = " + instances ) ; + check( instances.size() >= 3, "Cluster must contain at least 5 instances") ; + + final String gfInstance1 = pick( instances, true ) ; + final String gfInstance2 = pick( instances, true ) ; + final String gfInstance3 = pick( instances, true ) ; + gfCluster.stopCluster() ; + + gfCluster.startInstance( gfInstance1 ); + gfCluster.startInstance( gfInstance2 ); + gfCluster.startInstance( gfInstance3 ); + final String endpoints = getIIOPEndpointList() ; + + final int COUNT = 100 ; + instances = gfCluster.runningInstances() ; + note( "Running instances = " + instances ) ; + final String[] flags = { /* "subcontract", "transport", "folb" */ } ; + Location last = null ; + try { + setORBDebug( flags ) ; + /* last = */ doLoadBalance( instances, COUNT, endpoints ) ; + } finally { + clearORBDebug( flags ) ; + } + + final String testBase = "testInstance" ; + final int portBase = 20000 ; + gfCluster.createInstances( testBase, 2, "", portBase ) ; + gfCluster.startInstance( testBase + "0" ); + if (last != null) { + invokeMethod(last) ; + } + gfCluster.startInstance( testBase + "1" ); + if (last != null) { + invokeMethod(last) ; + } + + gfCluster.sleep(10); + + try { + setORBDebug( flags ) ; + instances = gfCluster.runningInstances() ; + note( "Running instances = " + instances ) ; + doLoadBalance( instances, 10*COUNT, endpoints ) ; + } finally { + clearORBDebug( flags ) ; + gfCluster.stopInstance( testBase + "0" ) ; + gfCluster.destroyInstance( testBase + "0" ) ; + gfCluster.stopInstance( testBase + "1" ) ; + gfCluster.destroyInstance( testBase + "1" ) ; + } + } + + // Test scenario for issue 14867: + // 1. Make sure cluster has at least 5 instances. Stop 2 instances. + // 2. Deploy an application to a cluster with three instances + // 3. Start up one client with target-server+ specifying the three instances. + // 4. In a loop (100 iterations): + // 1. Create a new InitialContext + // 2. Do a lookup + // 3. Remember which instance the lookup went to + // 5. Start two more instances + // 6. Then do 100 new IntialContext/lookup. + // New instances should process some of new requests + @Test( "14867" ) + public void test14867() throws NamingException { + Set instances = gfCluster.runningInstances() ; + note( "Running instances = " + instances ) ; + check( instances.size() >= 5, "Cluster must contain at least 5 instances") ; + + final String gfInstance1 = pick( instances, true ) ; + final String gfInstance2 = pick( instances, true ) ; + final String gfInstance3 = pick( instances, true ) ; + final String gfInstance4 = pick( instances, true ) ; + final String gfInstance5 = pick( instances, true ) ; + gfCluster.stopCluster() ; + + gfCluster.startInstance( gfInstance1 ); + gfCluster.startInstance( gfInstance2 ); + gfCluster.startInstance( gfInstance3 ); + final String endpoints = getIIOPEndpointList() ; + + final int COUNT = 1000 ; + instances = gfCluster.runningInstances() ; + note( "Running instances = " + instances ) ; + final String[] flags = { /* "subcontract", "transport", "folb" */ } ; + Location last = null ; + try { + setORBDebug( flags ) ; + /* last = */ doLoadBalance( instances, COUNT, endpoints ) ; + } finally { + clearORBDebug( flags ) ; + } + + gfCluster.startInstance( gfInstance4 ); + if (last != null) { + invokeMethod(last) ; + } + gfCluster.startInstance( gfInstance5 ); + if (last != null) { + invokeMethod(last) ; + } + + gfCluster.sleep(10); + + try { + setORBDebug( flags ) ; + instances = gfCluster.runningInstances() ; + note( "Running instances = " + instances ) ; + doLoadBalance( instances, COUNT, endpoints ) ; + } finally { + clearORBDebug( flags ) ; + } + } + + // Test scenario: + // 1. App is deployed on a 3 instance cluster + // 2. loop for 100 times: + // - ic = new InitialContext + // - ejb = ic.lookup + // - loc = ejb.getLocation + // - if first time, kill instance loc + // 3. see that LB happens on remaining cluster + @Test( "lbstopinstance" ) + public void testLBStopInstance() throws Exception { + final int CLUSTER_SIZE = 3 ; + final int NUM_IC = 100 ; + Set clusterInstances = new HashSet() ; + Set instances = gfCluster.runningInstances() ; + for (int ctr=0; ctr instances = gfCluster.runningInstances() ; + final String selected = pick( instances, true ) ; + final String second = pick( instances, true ) ; + final Set initialInstances = new HashSet() ; + initialInstances.add( selected ) ; + initialInstances.add( second ) ; + final String initalEndpoints = getIIOPEndpointList(initialInstances) ; + gfCluster.stopCluster(); + gfCluster.startInstance(selected) ; + doLoadBalance(gfCluster.runningInstances(), 10, initalEndpoints ); + gfCluster.startCluster(); + gfCluster.stopInstance(selected); + doLoadBalance(gfCluster.runningInstances(), 100, initalEndpoints ); + } + + // Test scenario: + // 1. Run a 3 instance cluster + // 2. Create initialContext with running instances. + // 3. Lookup stateful (b1) and stateless (b2) session beans. + // 4. inst = access b1 + // 5. shutdown inst + // 6. Create and start 2 new instances in cluster + // 7. inst2 = access b1 (should fail over to new instance) + // 8. shutdown inst2 + // 9. inst3 = access b2 + @Test( "15746" ) + public void test15746() throws NamingException { + Set running = gfCluster.runningInstances() ; + if (running.size() < 3) { + fail( "Must have cluster with at least three instances") ; + return ; + } + + final int numToStop = running.size() - 3 ; + + for (int ctr=0; ctr < numToStop; ctr++) { + final String inst = pick( gfCluster.runningInstances() ) ; + gfCluster.stopInstance(inst ); + } + + InitialContext ic = makeIC() ; + Location slsb = lookup( ic, BeanType.SLSB ) ; + Location sfsb = lookup( ic, BeanType.SFSB ) ; + + String inst = invokeMethod(slsb) ; + gfCluster.stopInstance(inst); + + final String testBase = "testInstance" ; + final int portBase = 20000 ; + gfCluster.createInstances( testBase, 2, "", portBase ) ; + gfCluster.startInstance( testBase + "0" ); + gfCluster.startInstance( testBase + "1" ); + + final String[] flags = { /* "subcontract", "transport", */ "folb" } ; + try { + setORBDebug(flags); + String inst2 = invokeMethod(slsb) ; + gfCluster.stopInstance(inst2); + + // String inst2_1 = invokeMethod(sfsb) ; + // gfCluster.stopInstance(inst2_1); + + String inst3 = invokeMethod(sfsb) ; + } finally { + clearORBDebug(flags); + } + } + + // Test scenario: + // 1. Run a 3 instance cluster + // 2. Create initialContext with running instances. + // 3. Lookup stateless (b1) Session bean. + // 4. inst1 = access b1 + // 5. shutdown inst1 + // 6. Lookup stateful (b2) Session bean. + // 7. inst2 = access b2 + // 8. shutdown inst2 + // 9. inst3 = access b2 + @Test( "15804sfsb" ) + public void test15804sfsb() throws NamingException { + Set running = gfCluster.runningInstances() ; + if (running.size() < 3) { + fail( "Must have cluster with at least three instances") ; + return ; + } else { + note("test15804sfsb: Cluster Size= " + running.size()); + } + + InitialContext ic = makeIC() ; + Location slsb = lookup( ic, BeanType.SLSB ) ; + + String inst1 = invokeMethod(slsb) ; + gfCluster.stopInstance(inst1); + + gfCluster.sleep(2); + Location sfsb = lookup( ic, BeanType.SFSB ) ; + String inst2 = invokeMethod(sfsb) ; + gfCluster.stopInstance(inst2); + gfCluster.sleep(2); + String inst3 = invokeMethod(sfsb) ; + } + + // same as 15804sfsb, except that we use manual kill instance + @Test( "15804sfsb_kill" ) + public void test15804sfsb_kill() throws NamingException { + Set running = gfCluster.runningInstances() ; + if (running.size() < 3) { + fail( "Must have cluster with at least three instances") ; + return ; + } else { + note("test15804sfsb: Cluster Size= " + running.size()); + } + + InitialContext ic = makeIC() ; + Location slsb = lookup( ic, BeanType.SLSB ) ; + + String inst1 = invokeMethod(slsb) ; + + gfCluster.killInstance(inst1); + try { + Thread.sleep(2000); + } catch (Exception e) { + //ignore + } + Location sfsb = lookup( ic, BeanType.SFSB ) ; + String inst2 = invokeMethod(sfsb) ; + + gfCluster.killInstance(inst2); + try { + Thread.sleep(2000); + } catch (Exception e) { + //ignore + } + String inst3 = invokeMethod(sfsb) ; + } + + // same as 15804sfsb_kill, except that we delete an instance midway + // 1. Run a 3 instance cluster + // 2. Create initialContext with running instances. + // 3. Lookup stateless (b1) Session bean. + // 4. inst1 = access b1 + // 5.1 kill inst1 + // 5.2 delete inst1 + // 6. Lookup stateful (b2) Session bean. + // 7. inst2 = access b2 + // 8. kill inst2 + // 9. inst3 = access b2 + //Deploy MultiEJBApp.ear +//stop-cluster st-cluster +//start-instance instance110; start-instance instance109 +//Kill the instance with message [SFSB1Bean.getName] +//Delete the instance with message [SFSB1Bean.getName] +//start-cluster st-cluster +//Kill the instance with message [SFSB1Bean.getName] +//Run test with appclient: appclient ... com.sun.appserver.ee.tests.client.ClientDynamicClusterRemoveInstance MultipleFO +//Exception was throw on client side. + + @Test( "15804sfsb_kill_delete" ) + public void test15804sfsb_kill_delete() throws NamingException { + Set running = gfCluster.runningInstances() ; + if (running.size() < 3) { + fail( "Must have cluster with at least three instances") ; + return ; + } else { + note("test15804sfsb: Cluster Size= " + running.size()); + } + + InitialContext ic = makeIC() ; + Location slsb = lookup( ic, BeanType.SLSB ) ; + + String inst1 = invokeMethod(slsb) ; + + gfCluster.killInstance(inst1); + try { + Thread.sleep(2000); + } catch (Exception e) { + //ignore + } + gfCluster.destroyInstance(inst1); + try { + Thread.sleep(2000); + } catch (Exception e) { + //ignore + } + Location sfsb = lookup( ic, BeanType.SFSB ) ; + String inst2 = invokeMethod(sfsb) ; + + gfCluster.killInstance(inst2); + try { + Thread.sleep(2000); + } catch (Exception e) { + //ignore + } + String inst3 = invokeMethod(sfsb) ; + } + // Test scenario: + // 1. Run a 3 instance cluster + // 2. Create initialContext with running instances. + // 3. Lookup stateful (b1) Session bean. + // 4. inst1 = access b1 + // 5. shutdown inst1 + // 6. Lookup stateless (b2) Session bean. + // 7. inst2 = access b2 + // 8. shutdown inst2 + // 9. inst3 = access b2 + @Test( "15804slsb" ) + public void test15804slsb() throws NamingException { + Set running = gfCluster.runningInstances() ; + if (running.size() < 3) { + fail( "Must have cluster with at least three instances") ; + return ; + } else { + note("test15804slsb: Cluster Size= " + running.size()); + } + + InitialContext ic = makeIC() ; + Location sfsb = lookup( ic, BeanType.SFSB ) ; + + String inst1 = invokeMethod(sfsb) ; + gfCluster.stopInstance(inst1); + + Location slsb = lookup( ic, BeanType.SLSB ) ; + String inst2 = invokeMethod(slsb) ; + gfCluster.stopInstance(inst2); + String inst3 = invokeMethod(slsb) ; + } + + // Test scenario: + // 1. App is deployed on a 3 instance cluster + // 2. Send 100 New initial Contexts, approx 30 are created on instance 1 + // 3. Bring down instance 1 + // 4. Call business methods using the IC , the 30 requests are failed + // over to only one instance + // 5. The expectation is, the failoved requests should be distributed + // among healthy instances (15 each approx) + @Test( "lbfail2") + public void testLBFail2() throws NamingException { + final int CLUSTER_SIZE = 3 ; + final int NUM_IC = 100 ; + Set clusterInstances = new HashSet() ; + Set instances = gfCluster.runningInstances() ; + for (int ctr=0; ctr chosen = new HashSet() ; + + for (int ctr=0; ctr testMethods ; + private final List currentResults ; + // private final List currentNotes ; + private final Arguments argvals ; + private final Set includes ; + private final Set excludes ; + private final List preMethods ; + private final List postMethods ; + + private String current ; + private Set pass = new HashSet() ; + private Set fail = new HashSet() ; + private Set skip = new HashSet() ; + + private interface Arguments { + @DefaultValue( "false" ) + @Help( "Control debugging mode") + boolean debug() ; + + @DefaultValue( "false" ) + @Help( "Displays the valid test case identifiers" ) + boolean cases() ; + + @DefaultValue( "" ) + @Help( "A list of test cases to include: includes everything if empty" ) + @Separator( "," ) + List include() ; + + @DefaultValue( "" ) + @Help( "A list of test cases to excelude: include everything if empty" ) + @Separator( "," ) + List exclude() ; + } + + private void execute( Collection methods ) + throws IllegalAccessException, IllegalArgumentException, + InvocationTargetException { + + for (Method m : methods) { + m.invoke( this ) ; + } + } + + public Base( String[] args ) { + this( args, null ) ; + } + + public Base(String[] args, Class parserInterface) { + this( args, parserInterface, null ) ; + } + + public Base(String[] args, Class parserInterface, Class testClass ) { + testMethods = new ArrayList() ; + preMethods = new ArrayList() ; + postMethods = new ArrayList() ; + + final Class cls = (testClass == null) ? this.getClass() : testClass ; + for (Method m : cls.getMethods()) { + if (m.getDeclaringClass().equals( Base.class ) + && !this.getClass().equals( Base.class )) { + // Skip test methods defined on this class for self test + // unless we are actually running the self test. + continue ; + } + + Test anno = m.getAnnotation( Test.class ) ; + if (anno != null) { + if (m.getParameterTypes().length == 0) { + if (m.getReturnType().equals( void.class )) { + testMethods.add( m ) ; + } else { + msg( "Method " + m + " is annotated @Test, " + + "but has a non-void return type").nl() ; + } + } else { + msg( "Method " + m + " is annotated @Test, " + + "but has parameters").nl() ; + } + } + + Pre pre = m.getAnnotation( Pre.class ) ; + if (pre != null) { + preMethods.add( m ) ; + } + + Post post = m.getAnnotation( Post.class ) ; + if (post != null) { + postMethods.add( m ) ; + } + } + + + Class[] interfaces = (parserInterface == null) + ? new Class[]{ Arguments.class } + : new Class[]{ Arguments.class, parserInterface } ; + + ArgParser parser = new ArgParser( Arrays.asList(interfaces)) ; + argvals = (Arguments)parser.parse( args ) ; + if (argvals.debug()) { + msg( "Arguments are:\n" + argvals ).nl() ; + } + + if (argvals.include().isEmpty()) { + includes = new HashSet() ; + for (Method m : testMethods) { + includes.add( getTestId( m ) ) ; + } + } else { + List incs = argvals.include() ; + includes = new HashSet( incs ) ; + } + + excludes = new HashSet( argvals.exclude() ) ; + + if (argvals.cases()) { + msg( "Valid test case identifiers are:" ).nl() ; + for (Method m : testMethods) { + msg( " " + getTestId( m ) ).nl() ; + } + } + + currentResults = new ArrayList() ; + // currentNotes = new ArrayList() ; + } + + public T getArguments( Class cls ) { + return cls.cast( argvals ) ; + } + + private Base msg( String str ) { + System.out.print( str ) ; + return this ; + } + + private Base nl() { + System.out.println() ; + return this ; + } + + private String getTestId( Method m ) { + Test anno = m.getAnnotation( Test.class ) ; + if (!anno.value().equals("")) { + return anno.value() ; + } + + String mname = m.getName() ; + if (mname.startsWith( "test" )) { + return mname.substring( 4 ) ; + } else { + return mname ; + } + } + + private void display( String title, List strs ) { + if (!strs.isEmpty()) { + msg( title + ":" ).nl() ; + for (String str : strs ) { + msg( "\t" + str ).nl() ; + } + } + } + + public int run() { + for (Method m : testMethods) { + currentResults.clear() ; + // currentNotes.clear() ; + + current = getTestId( m ) ; + if (includes.contains(current) && !excludes.contains(current)) { + msg( "Test " + current + ": " ).nl() ; + msg( " Notes:" ).nl() ; + try { + execute( preMethods ) ; + m.invoke( this ) ; + } catch (Exception exc) { + fail( "Caught exception : " + exc ) ; + exc.printStackTrace(); + } finally { + try { + execute(postMethods); + } catch (Exception exc) { + fail( "Exception in post methods : " + exc ) ; + exc.printStackTrace(); + } + } + + if (currentResults.isEmpty()) { + pass.add( current ) ; + msg( "Test " + current + " PASSED." ).nl() ; + } else { + fail.add( current ) ; + msg( "Test " + current + " FAILED." ).nl() ; + } + + // display( " Notes", currentNotes ) ; + display( " Results", currentResults ) ; + } else { + msg( "Test " + current + " SKIPPED" ).nl() ; + skip.add( current ) ; + } + } + + msg( "-------------------------------------------------").nl() ; + msg( "Results:" ).nl() ; + msg( "-------------------------------------------------").nl() ; + + msg( "\tFAILED:").nl() ; displaySet( fail ) ; + msg( "\tSKIPPED:").nl() ; displaySet( skip ) ; + msg( "\tPASSED:").nl() ; displaySet( pass ) ; + + nl() ; + msg( pass.size() + " test(s) passed; " + + fail.size() + " test(s) failed; " + + skip.size() + " test(s) skipped." ).nl() ; + msg( "-------------------------------------------------").nl() ; + + return fail.size() ; + } + + private void displaySet( Set set ) { + for (String str : set ) { + msg( "\t\t" ).msg( str ).nl() ; + } + } + + public void fail( String failMessage ) { + check( false, failMessage ) ; + } + + public void check( boolean result, String failMessage ) { + if (!result) { + currentResults.add( failMessage ) ; + } + } + + public void note( String msg ) { + // currentNotes.add( msg ) ; + msg( "\t" + msg ).nl() ; + } + + @Test + public void testSimple() {} + + @Test + public void testGood( ) { + note( "this is a good test" ) ; + note( "A second note") ; + } + + @Test( "Bad" ) + public void badTest() { + note( "this is a bad test" ) ; + fail( "this test failed once" ) ; + fail( "this test failed twice" ) ; + } + + @Test + public void exception() { + throw new RuntimeException( "This test throws an exception") ; + } + + @Test + public boolean badReturnType() { + return true ; + } + + @Test + public void hasParameters( String name ) { + } + + public static void main( String[] args ) { + Base base = new Base( args ) ; + base.run() ; + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Post.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Post.java new file mode 100644 index 000000000..9f79246cf --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Post.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package testtools ; + +import java.lang.annotation.Target ; +import java.lang.annotation.Documented ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** Used to mark methods that are executed after every test case + * + * @author ken + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Post { +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Pre.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Pre.java new file mode 100644 index 000000000..70fc29e6a --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Pre.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package testtools ; + +import java.lang.annotation.Target ; +import java.lang.annotation.Documented ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** Used to mark methods executed before each test case. + * + * @author ken + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Pre { + +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Test.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Test.java new file mode 100644 index 000000000..ea65f3a43 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/src/java/testtools/Test.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package testtools ; + +import java.lang.annotation.Target ; +import java.lang.annotation.Documented ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** + * + * @author ken + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Test { + String value() default "" ; +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/testtest b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/testtest new file mode 100755 index 000000000..c0b889216 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-app-client/testtest @@ -0,0 +1,13 @@ +#! /bin/sh +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# java -classpath dist/*jar -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=3232 testtools.Base $@ +java -classpath dist/*jar testtools.Base $@ diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/build.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/build.xml new file mode 100644 index 000000000..b251d9439 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/build.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + Builds, tests, and runs the project OrbFailOver-ejb. + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/ant-deploy.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/ant-deploy.xml new file mode 100644 index 000000000..681f9abd0 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/ant-deploy.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/build-impl.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/build-impl.xml new file mode 100644 index 000000000..e8700966f --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/build-impl.xml @@ -0,0 +1,853 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set build.generated.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + +The Java EE server classpath is not correctly set up - server home directory is missing. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Dj2ee.server.home=<app_server_installation_directory> + + +The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Duser.properties.file=<path_to_property_file> (where you put the property "j2ee.platform.classpath" in a .properties file) +or ant -Dj2ee.platform.classpath=<server_classpath> (where no properties file is used) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set main.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/genfiles.properties b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/genfiles.properties new file mode 100644 index 000000000..89ca111b4 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/genfiles.properties @@ -0,0 +1,18 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +build.xml.data.CRC32=c09f6e85 +build.xml.script.CRC32=270c5a94 +build.xml.stylesheet.CRC32=5910fda3@1.30.1 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=c09f6e85 +nbproject/build-impl.xml.script.CRC32=6db65b2f +nbproject/build-impl.xml.stylesheet.CRC32=2bce7fe8@1.30.1 diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/project.properties b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/project.properties new file mode 100644 index 000000000..2b689436b --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/project.properties @@ -0,0 +1,90 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=true +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form,**/.nbattrs +build.dir=build +build.ear.classes.dir=${build.dir}/classes +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +debug.classpath=${javac.classpath}:${build.classes.dir} +debug.test.classpath=\ + ${run.test.classpath} +dist.dir=dist +dist.ear.jar=${dist.dir}/${jar.name} +dist.jar=${dist.dir}/${jar.name} +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath=\ + ${libs.javaee-endorsed-api-6.0.classpath} +excludes= +file.reference.gmbal.jar=../../../glassfish4/glassfish/modules/gmbal.jar +file.reference.javaee.jar=../../../glassfish4/glassfish/lib/javaee.jar +includes=** +j2ee.compile.on.save=true +j2ee.deploy.on.save=true +j2ee.platform=1.6 +j2ee.platform.classpath=${j2ee.server.home}/modules/jaxrpc-api-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/javax.enterprise.deploy.jar:${j2ee.server.home}/modules/jaxr-api-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.el.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jar:${j2ee.server.home}/modules/javax.management.j2ee.jar:${j2ee.server.home}/modules/endorsed/javax.annotation.jar:${j2ee.server.home}/modules/javax.el-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp-api.jar:${j2ee.server.home}/modules/javax.security.jacc.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl-api.jar:${j2ee.server.home}/modules/jersey-core.jar:${j2ee.server.home}/modules/javax.transaction.jar:${j2ee.server.home}/modules/javax.resource.jar:${j2ee.server.home}/modules/javax.persistence.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar:${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/javax.security.auth.message.jar:${j2ee.server.home}/modules/javax.servlet-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl.jar:${j2ee.server.home}/modules/javax.jms.jar:${j2ee.server.home}/modules/javax.mail.jar +j2ee.platform.embeddableejb.classpath=${j2ee.server.home}/lib/embedded/glassfish-embedded-static-shell.jar +j2ee.platform.wscompile.classpath=${j2ee.server.home}/modules/webservices-osgi.jar +j2ee.platform.wsgen.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar +j2ee.platform.wsimport.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar +j2ee.platform.wsit.classpath= +j2ee.server.type=gfv3ee6 +jar.compress=false +jar.name=OrbFailOver-ejb.jar +javac.classpath=\ + ${file.reference.javaee.jar}:\ + ${file.reference.gmbal.jar} +javac.compilerargs=-target 6 +javac.debug=true +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javac.test.processorpath=${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.preview=true +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +meta.inf=${source.root}/conf +meta.inf.excludes=sun-cmp-mappings.xml +platform.active=default_platform +resource.dir=setup +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +# Space-separated list of JVM arguments used when running a class with a main method or a unit test +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value): +runmain.jvmargs= +source.encoding=UTF-8 +source.root=src +src.dir=${source.root}/java +test.src.dir=test diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/project.xml b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/project.xml new file mode 100644 index 000000000..7f198de93 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/nbproject/project.xml @@ -0,0 +1,30 @@ + + + + + org.netbeans.modules.j2ee.ejbjarproject + + + OrbFailOver-ejb + 1.6.5 + file.reference.javaee.jar + file.reference.gmbal.jar + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/conf/MANIFEST.MF b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/conf/MANIFEST.MF new file mode 100644 index 000000000..59499bce4 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/conf/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/Location.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/Location.java new file mode 100644 index 000000000..9e63f3dcc --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/Location.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +/** + * + * @author ken + */ +public interface Location { + public String getLocation(); +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/LocationBean.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/LocationBean.java new file mode 100644 index 000000000..5e7cf9219 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/LocationBean.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package orb.folb; + +import javax.ejb.Stateless; +import java.net.InetAddress; +import java.util.Properties; +import java.util.Enumeration; + +/** + * + * @author hv51393 + */ +@Stateless +public class LocationBean implements LocationBeanRemote { + + public String getLocation() { + + try { + String instanceName = System.getProperty("com.sun.aas.instanceName"); + return instanceName; + } catch (Exception e) { + return null; + } + } + + public String getHostName() { + + try { + String hostName = InetAddress.getLocalHost().getCanonicalHostName(); + return hostName ; + } catch (Exception e) { + return null; + } + } + + public void printSystemProperties() { + Properties p = System.getProperties(); + Enumeration keys = p.keys(); + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + String value = (String) p.get(key); + System.out.println(key + ": " + value); + } + } +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/LocationBeanRemote.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/LocationBeanRemote.java new file mode 100644 index 000000000..af3aaa42e --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/LocationBeanRemote.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +import javax.ejb.Remote; + +/** + * + * @author hv51393 + */ +@Remote +public interface LocationBeanRemote extends Location { + public String getHostName(); + public void printSystemProperties(); + +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/StatefullLocationBean.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/StatefullLocationBean.java new file mode 100644 index 000000000..c085a8e66 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/StatefullLocationBean.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +import javax.ejb.Stateful; + +/** + * + * @author ken + */ +@Stateful +public class StatefullLocationBean implements StatefullLocationBeanRemote { + @Override + public String getLocation() { + try { + String instanceName = System.getProperty("com.sun.aas.instanceName"); + return instanceName; + } catch (Exception e) { + return null; + } + } + +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/StatefullLocationBeanRemote.java b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/StatefullLocationBeanRemote.java new file mode 100644 index 000000000..9c772651e --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/OrbFailOver-ejb/src/java/orb/folb/StatefullLocationBeanRemote.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package orb.folb; + +import javax.ejb.Remote; + +/** + * + * @author ken + */ +@Remote +public interface StatefullLocationBeanRemote extends Location { +} diff --git a/iiop-folb-dev-test/test/OrbFailOver/build.xml b/iiop-folb-dev-test/test/OrbFailOver/build.xml new file mode 100644 index 000000000..579bf78bf --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + Builds, tests, and runs the project OrbFailOver. + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/nbproject/ant-deploy.xml b/iiop-folb-dev-test/test/OrbFailOver/nbproject/ant-deploy.xml new file mode 100644 index 000000000..681f9abd0 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/nbproject/ant-deploy.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/nbproject/build-impl.xml b/iiop-folb-dev-test/test/OrbFailOver/nbproject/build-impl.xml new file mode 100644 index 000000000..b5a51ea82 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/nbproject/build-impl.xml @@ -0,0 +1,588 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set build.dir + Must set build.generated.dir + Must set dist.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Browser not found, cannot launch the deployed application. Try to set the BROWSER environment variable. + + + Launching ${browse.url} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/nbproject/genfiles.properties b/iiop-folb-dev-test/test/OrbFailOver/nbproject/genfiles.properties new file mode 100644 index 000000000..dc4d8e756 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/nbproject/genfiles.properties @@ -0,0 +1,18 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +build.xml.data.CRC32=5584e19a +build.xml.script.CRC32=9dc7008d +build.xml.stylesheet.CRC32=a5d15b16@1.26.1 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=5584e19a +nbproject/build-impl.xml.script.CRC32=2ac2a138 +nbproject/build-impl.xml.stylesheet.CRC32=c6867ec8@1.26.1 diff --git a/iiop-folb-dev-test/test/OrbFailOver/nbproject/project.properties b/iiop-folb-dev-test/test/OrbFailOver/nbproject/project.properties new file mode 100644 index 000000000..44e44a057 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/nbproject/project.properties @@ -0,0 +1,56 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +app.client=OrbFailOver-app-client +build.classes.excludes=**/*.java,**/*.form,**/.nbattrs +build.dir=build +build.generated.dir=${build.dir}/generated +client.module.uri=OrbFailOver/${app.client} +client.urlPart= +debug.classpath=${javac.classpath}::${jar.content.additional}:${run.classpath} +display.browser=true +dist.dir=dist +dist.jar=${dist.dir}/${jar.name} +endorsed.classpath=\ + ${libs.javaee-endorsed-api-6.0.classpath} +file.reference.gmbal.jar=../../glassfish4/glassfish/modules/gmbal.jar +file.reference.javaee.jar=../../glassfish4/glassfish/lib/javaee.jar +j2ee.appclient.mainclass.args=${j2ee.appclient.tool.args} +j2ee.compile.on.save=false +j2ee.deploy.on.save=false +j2ee.platform=1.6 +j2ee.platform.classpath=${j2ee.server.home}/modules/jaxrpc-api-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/javax.enterprise.deploy.jar:${j2ee.server.home}/modules/jaxr-api-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.el.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jar:${j2ee.server.home}/modules/javax.management.j2ee.jar:${j2ee.server.home}/modules/endorsed/javax.annotation.jar:${j2ee.server.home}/modules/javax.el-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp-api.jar:${j2ee.server.home}/modules/javax.security.jacc.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl-api.jar:${j2ee.server.home}/modules/jersey-core.jar:${j2ee.server.home}/modules/javax.transaction.jar:${j2ee.server.home}/modules/javax.resource.jar:${j2ee.server.home}/modules/javax.persistence.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar:${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/javax.security.auth.message.jar:${j2ee.server.home}/modules/javax.servlet-api.jar:${j2ee.server.home}/modules/javax.servlet.jsp.jstl.jar:${j2ee.server.home}/modules/javax.jms.jar:${j2ee.server.home}/modules/javax.mail.jar +j2ee.platform.embeddableejb.classpath=${j2ee.server.home}/lib/embedded/glassfish-embedded-static-shell.jar +j2ee.platform.wscompile.classpath=${j2ee.server.home}/modules/webservices-osgi.jar +j2ee.platform.wsgen.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar +j2ee.platform.wsimport.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/endorsed/jaxb-api-osgi.jar:${j2ee.server.home}/modules/javax.ejb.jar:${j2ee.server.home}/modules/javax.ejb-api.jar +j2ee.platform.wsit.classpath= +j2ee.server.type=gfv3ee6 +jar.compress=false +jar.content.additional=\ + ${reference.OrbFailOver-app-client.j2ee-module-car}:\ + ${reference.OrbFailOver-ejb.dist-ear} +jar.name=OrbFailOver.ear +javac.debug=true +javac.deprecation=false +javac.source=1.6 +javac.target=1.6 +meta.inf=src/conf +no.dependencies=false +platform.active=default_platform +project.OrbFailOver-app-client=OrbFailOver-app-client +project.OrbFailOver-ejb=OrbFailOver-ejb +reference.OrbFailOver-app-client.j2ee-module-car=${project.OrbFailOver-app-client}/dist/OrbFailOver-app-client.jar +reference.OrbFailOver-ejb.dist-ear=${project.OrbFailOver-ejb}/dist/OrbFailOver-ejb.jar +resource.dir=setup +run.classpath=\ + ${file.reference.javaee.jar}:\ + ${file.reference.gmbal.jar} +source.root=. diff --git a/iiop-folb-dev-test/test/OrbFailOver/nbproject/project.xml b/iiop-folb-dev-test/test/OrbFailOver/nbproject/project.xml new file mode 100644 index 000000000..cf8723631 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/nbproject/project.xml @@ -0,0 +1,51 @@ + + + + + org.netbeans.modules.j2ee.earproject + + + OrbFailOver + 1.6.5 + + + + ${reference.OrbFailOver-app-client.j2ee-module-car} + / + + + ${reference.OrbFailOver-ejb.dist-ear} + / + + + + + + OrbFailOver-app-client + j2ee_ear_archive + + dist-ear + clean-ear + j2ee-module-car + + + OrbFailOver-ejb + j2ee_ear_archive + + dist-ear + clean-ear + dist-ear + + + + diff --git a/iiop-folb-dev-test/test/OrbFailOver/src/conf/MANIFEST.MF b/iiop-folb-dev-test/test/OrbFailOver/src/conf/MANIFEST.MF new file mode 100644 index 000000000..59499bce4 --- /dev/null +++ b/iiop-folb-dev-test/test/OrbFailOver/src/conf/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/iiop-folb-dev-test/testcommands.txt b/iiop-folb-dev-test/testcommands.txt new file mode 100644 index 000000000..17dba96d0 --- /dev/null +++ b/iiop-folb-dev-test/testcommands.txt @@ -0,0 +1,11 @@ +This is the basic set of commands needed to set up a cluster for testing: + +start-domain +create-cluster c1 +--user admin create-node-ssh --nodehost minas --installdir /volumes/work/GlassFish/v3/glassfish4 minasNA +--user admin create-node-ssh --nodehost apollo --installdir /volumes/work/GlassFish/v3/glassfish4 apolloNA +create-instance --node minasNA --cluster c1 --portbase 9000 --checkports=true in0 +create-instance --node apolloNA --cluster c1 --portbase 10000 --checkports=true in1 +create-instance --node minasNA --cluster c1 --portbase 11000 --checkports=true in2 +start-cluster c1 +deploy --target c1 --name TestEJB --force /space/ws/mercurial/CORBA/iiop-folb-test/test/OrbFailOver/OrbFailOver-ejb/dist/OrbFailOver-ejb.jar diff --git a/internal-api/pom.xml b/internal-api/pom.xml new file mode 100644 index 000000000..5a79cc61e --- /dev/null +++ b/internal-api/pom.xml @@ -0,0 +1,54 @@ + + + + + + glassfish-corba + org.glassfish.corba + 4.2.0-b005-SNAPSHOT + + 4.0.0 + + glassfish-corba-internal-api + Exposed Internal APIs + Exposed Internal APIs + bundle + + + + org.glassfish.gmbal + gmbal + ${gmbal-version} + + + org.glassfish.pfl + pfl-basic + ${pfl-version} + + + + + + + + org.apache.felix + maven-bundle-plugin + + + com.sun.corba.ee.spi.threadpool;version=1, com.sun.corba.ee.impl.threadpool;version=1, com.sun.corba.ee.spi.logex.stdcorba;version=1 + + + + + + diff --git a/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/Exceptions.java b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/Exceptions.java new file mode 100644 index 000000000..69f25cc48 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/Exceptions.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.threadpool; + +import com.sun.corba.ee.spi.logex.stdcorba.StandardLogger; +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +/** Exception wrapper class. The logex WrapperGenerator uses this interface + * to generate an implementation which returns the appropriate exception, and + * generates a log report when the method is called. This is used for all + * implementation classes in this package. + * + * The exception IDs are allocated in blocks of EXCEPTIONS_PER_CLASS, which is + * a lot more than is needed, but we have 32 bits for IDs, and multiples of + * a suitably chosen EXCEPTIONS_PER_CLASS (like 100 here) are easy to read in + * error messages. + * + * @author ken + */ +@ExceptionWrapper( idPrefix="ORBTPOOL" ) +public interface Exceptions { + static final Exceptions self = WrapperGenerator.makeWrapper( + Exceptions.class, StandardLogger.self ) ; + + // Allow 100 exceptions per class + static final int EXCEPTIONS_PER_CLASS = 100 ; + +// ThreadPoolImpl + static final int TP_START = 1 ; + + @Message( "Join was interrrupted on thread {0} while closing ThreadPool {1}" ) + @Log( id = TP_START + 0 ) + void interruptedJoinCallWhileClosingThreadPool( + @Chain InterruptedException exc, Thread wt, ThreadPoolImpl aThis); + + @Message( "Worker Thread {0} has been created with ClassLoader {1}" ) + @Log( id = TP_START + 0, level=LogLevel.FINE ) + void workerThreadCreated(Thread thread, + ClassLoader contextClassLoader); + + @Message( "Worker thread creation failure" ) + @Log( id = TP_START + 1, level=LogLevel.SEVERE ) + void workerThreadCreationFailure( @Chain Throwable t); + + @Message( "Unable to get worker thread {0}; check securiy policy file:" + + " must grant 'getContextClassLoader' runtime permission") + @Log( id = TP_START + 2 ) + RuntimeException workerThreadGetContextClassloaderFailed( + @Chain SecurityException se, Thread aThis); + + @Message( "Worker thread {0} context ClassLoader was changed to {1};" + + " will attempt a reset to its initial ClassLoader {2} " ) + @Log( id = TP_START + 3, level=LogLevel.FINE ) + void workerThreadForgotClassloaderReset( Thread aThis, + ClassLoader currentClassLoader, ClassLoader workerThreadClassLoader); + + @Message( "Unable to set worker thread {0}; check securiy policy file:" + + " must grant 'setContextClassLoader' runtime permission") + @Log( id = TP_START + 5 ) + void workerThreadResetContextClassloaderFailed( + @Chain SecurityException se, Thread aThis); + + @Message( "Worker thread {0} caught throwable while executing work." ) + @Log( id = TP_START + 6 ) + void workerThreadDoWorkThrowable( @Chain Throwable t, Thread aThis); + + @Message( "Worker thread {0} will exit; current thread count {1} is" + + " greater than minimum worker threads needed {2}" ) + @Log( id = TP_START + 7, level=LogLevel.FINE ) + void workerThreadNotNeeded( Thread aThis, + int currentNumberOfThreads, int minimumNumberOfThreads); + + @Message( "Worker thread from thread pool {0} was interrupted:" + + " closeCalled is {1}" ) + @Log( id = TP_START + 8, level=LogLevel.FINE ) + void workQueueThreadInterrupted( + InterruptedException exc, String name, Boolean valueOf); + + @Message( "Worker thread {0} caught throwable when" + + " requesting work from work queue {1}" ) + @Log( id = TP_START + 9, level=LogLevel.FINE ) + void workerThreadThrowableFromRequestWork( + @Chain Throwable t, Thread aThis, String name); + + @Message( "Worker thread {0} caught unexpected throwable" ) + @Log( id = TP_START + 10 ) + void workerThreadCaughtUnexpectedThrowable( + @Chain Throwable e, Thread aThis); + +// ThreadPoolManagerImpl + static final int TPM_START = TP_START + EXCEPTIONS_PER_CLASS ; + + @Message( "Error in closing ThreadPool" ) + @Log( id = TPM_START + 0 ) + void threadPoolCloseError() ; + + @Message( "ThreadGroup {0} is already destroyed; cannot destroy it again" ) + @Log( id = TPM_START + 1 ) + void threadGroupIsDestroyed( ThreadGroup thgrp ) ; + + @Message( "ThreadGroup {0} has {1} active threads: destroy may cause exceptions" ) + @Log( id = TPM_START + 2 ) + void threadGroupHasActiveThreadsInClose( ThreadGroup thgrp, + int numThreads) ; + + @Message( "ThreadGroup {0} has {1} sub-ThreadGroups: destroy may cause exceptions" ) + @Log( id = TPM_START + 3 ) + void threadGroupHasSubGroupsInClose(ThreadGroup threadGroup, + int numGroups); + + @Message( "ThreadGroup {0} could not be destroyed" ) + @Log( id = TPM_START + 4 ) + void threadGroupDestroyFailed( @Chain IllegalThreadStateException exc, + ThreadGroup threadGroup); + +// ThreadStateValidator + static final int TSV_START = TPM_START + EXCEPTIONS_PER_CLASS ; + + @Message( "Thread state validator threw an exception on validator {0}" ) + @Log( id = TSV_START + 0 ) + RuntimeException threadStateValidatorException( Runnable run, @Chain Throwable exc ) ; +} diff --git a/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/ThreadPoolImpl.java b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/ThreadPoolImpl.java new file mode 100644 index 000000000..2ac423471 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/ThreadPoolImpl.java @@ -0,0 +1,530 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.threadpool; + +import java.io.IOException ; +import java.io.Closeable ; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import java.util.List ; +import java.util.ArrayList ; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import com.sun.corba.ee.spi.threadpool.NoSuchWorkQueueException; +import com.sun.corba.ee.spi.threadpool.ThreadPool; +import com.sun.corba.ee.spi.threadpool.ThreadStateValidator; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.threadpool.WorkQueue; + +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.NameValue ; + +@ManagedObject +@Description( "A ThreadPool used by the ORB" ) +public class ThreadPoolImpl implements ThreadPool +{ + public static final int DEFAULT_INACTIVITY_TIMEOUT = 120000; + + // serial counter useful for debugging + private static final AtomicInteger threadCounter = new AtomicInteger(0); + + // Any time currentThreadCount and/or availableWorkerThreads is updated + // or accessed this ThreadPool's WorkQueue must be locked. And, it is + // expected that this ThreadPool's WorkQueue is the only object that + // updates and accesses these values directly and indirectly though a + // call to a method in this ThreadPool. If any call to update or access + // those values must synchronized on this ThreadPool's WorkQueue. + final private WorkQueue workQueue; + + // Stores the number of available worker threads + private int availableWorkerThreads = 0; + + // Stores the number of threads in the threadpool currently + private int currentThreadCount = 0; + + // Minimum number of worker threads created at instantiation of the threadpool + final private int minWorkerThreads; + + // Maximum number of worker threads in the threadpool + final private int maxWorkerThreads; + + // Inactivity timeout value for worker threads to exit and stop running + final private long inactivityTimeout; + + // Running count of the work items processed + // Set the value to 1 so that divide by zero is avoided in + // averageWorkCompletionTime() + private AtomicLong processedCount = new AtomicLong(1); + + // Running aggregate of the time taken in millis to execute work items + // processed by the threads in the threadpool + private AtomicLong totalTimeTaken = new AtomicLong(0); + + // Name of the ThreadPool + final private String name; + + // ThreadGroup in which threads should be created + private ThreadGroup threadGroup ; + + final private ClassLoader workerThreadClassLoader ; + + final Object workersLock = new Object() ; + + List workers = new ArrayList() ; + + /** Create an unbounded thread pool in the current thread group + * with the current context ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPoolImpl(String threadpoolName) { + this( Thread.currentThread().getThreadGroup(), threadpoolName ) ; + } + + /** Create an unbounded thread pool in the given thread group + * with the current context ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPoolImpl(ThreadGroup tg, String threadpoolName ) { + this( tg, threadpoolName, getDefaultClassLoader() ) ; + } + + /** Create an unbounded thread pool in the given thread group + * with the given ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPoolImpl(ThreadGroup tg, String threadpoolName, + ClassLoader defaultClassLoader) { + + inactivityTimeout = DEFAULT_INACTIVITY_TIMEOUT; + minWorkerThreads = 0; + maxWorkerThreads = Integer.MAX_VALUE; + workQueue = new WorkQueueImpl(this); + // XXX register this with gmbal. + threadGroup = tg ; + name = threadpoolName; + workerThreadClassLoader = defaultClassLoader ; + } + + /** Create a bounded thread pool in the current thread group + * with the current context ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPoolImpl( int minSize, int maxSize, long timeout, + String threadpoolName) { + + this( minSize, maxSize, timeout, threadpoolName, getDefaultClassLoader() ) ; + } + + /** Create a bounded thread pool in the current thread group + * with the given ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPoolImpl( int minSize, int maxSize, long timeout, + String threadpoolName, ClassLoader defaultClassLoader ) + { + inactivityTimeout = timeout; + minWorkerThreads = minSize; + maxWorkerThreads = maxSize; + workQueue = new WorkQueueImpl(this); + threadGroup = Thread.currentThread().getThreadGroup() ; + name = threadpoolName; + workerThreadClassLoader = defaultClassLoader ; + synchronized (workQueue) { + for (int i = 0; i < minWorkerThreads; i++) { + createWorkerThread(); + } + } + } + + + // Note that this method should not return until AFTER all threads have died. + public void close() throws IOException { + // Copy to avoid concurrent modification problems. + List copy = null ; + synchronized (workersLock) { + copy = new ArrayList( workers ) ; + } + + for (WorkerThread wt : copy) { + wt.close() ; + + while (wt.getState() != Thread.State.TERMINATED) { + try { + wt.join() ; + } catch (InterruptedException exc) { + Exceptions.self.interruptedJoinCallWhileClosingThreadPool( exc, + wt, this ) ; + } + } + } + + threadGroup = null ; + } + + private static ClassLoader getDefaultClassLoader() { + if (System.getSecurityManager() == null) + return Thread.currentThread().getContextClassLoader() ; + else { + final ClassLoader cl = AccessController.doPrivileged( + new PrivilegedAction() { + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader() ; + } + } + ) ; + + return cl ; + } + } + + public WorkQueue getAnyWorkQueue() + { + return workQueue; + } + + public WorkQueue getWorkQueue(int queueId) + throws NoSuchWorkQueueException + { + if (queueId != 0) + throw new NoSuchWorkQueueException(); + return workQueue; + } + + private Thread createWorkerThreadHelper( String name ) { + // Thread creation needs to be in a doPrivileged block + // if there is a non-null security manager for two reasons: + // 1. The creation of a thread in a specific ThreadGroup + // is a privileged operation. Lack of a doPrivileged + // block here causes an AccessControlException + // (see bug 6268145). + // 2. We want to make sure that the permissions associated + // with this thread do NOT include the permissions of + // the current thread that is calling this method. + // This leads to problems in the app server where + // some threads in the ThreadPool randomly get + // bad permissions, leading to unpredictable + // permission errors (see bug 6021011). + // + // A Java thread contains a stack of call frames, + // one for each method called that has not yet returned. + // Each method comes from a particular class. The class + // was loaded by a ClassLoader which has an associated + // CodeSource, and this determines the Permissions + // for all methods in that class. The current + // Permissions for the thread are the intersection of + // all Permissions for the methods on the stack. + // This is part of the Security Context of the thread. + // + // When a thread creates a new thread, the new thread + // inherits the security context of the old thread. + // This is bad in a ThreadPool, because different + // creators of threads may have different security contexts. + // This leads to occasional unpredictable errors when + // a thread is re-used in a different security context. + // + // Avoiding this problem is simple: just do the thread + // creation in a doPrivileged block. This sets the + // inherited security context to that of the code source + // for the ORB code itself, which contains all permissions + // in either Java SE or Java EE. + WorkerThread thread = new WorkerThread(threadGroup, name); + synchronized (workersLock) { + workers.add( thread ) ; + } + + // The thread must be set to a daemon thread so the + // VM can exit if the only threads left are PooledThreads + // or other daemons. We don't want to rely on the + // calling thread always being a daemon. + // Note that no exception is possible here since we + // are inside the doPrivileged block. + thread.setDaemon(true); + + Exceptions.self.workerThreadCreated( thread, thread.getContextClassLoader() ) ; + + thread.start(); + return null ; + } + + /** + * To be called from the WorkQueue to create worker threads when none + * available. + */ + void createWorkerThread() { + final String lname = getName(); + synchronized (workQueue) { + try { + if (System.getSecurityManager() == null) { + createWorkerThreadHelper(lname) ; + } else { + // If we get here, we need to create a thread. + AccessController.doPrivileged( + new PrivilegedAction() { + public Object run() { + return createWorkerThreadHelper(lname) ; + } + } + ) ; + } + } catch (Throwable t) { + // Decrementing the count of current worker threads. + // But, it will be increased in the finally block. + decrementCurrentNumberOfThreads(); + Exceptions.self.workerThreadCreationFailure(t); + } finally { + incrementCurrentNumberOfThreads(); + } + } + } + + public int minimumNumberOfThreads() { + return minWorkerThreads; + } + + public int maximumNumberOfThreads() { + return maxWorkerThreads; + } + + public long idleTimeoutForThreads() { + return inactivityTimeout; + } + + @ManagedAttribute + @Description( "The current number of threads" ) + public int currentNumberOfThreads() { + synchronized (workQueue) { + return currentThreadCount; + } + } + + void decrementCurrentNumberOfThreads() { + synchronized (workQueue) { + currentThreadCount--; + } + } + + void incrementCurrentNumberOfThreads() { + synchronized (workQueue) { + currentThreadCount++; + } + } + + @ManagedAttribute + @Description( "The number of available threads in this ThreadPool" ) + public int numberOfAvailableThreads() { + synchronized (workQueue) { + return availableWorkerThreads; + } + } + + @ManagedAttribute + @Description( "The number of threads busy processing work in this ThreadPool" ) + public int numberOfBusyThreads() { + synchronized (workQueue) { + return (currentNumberOfThreads() - numberOfAvailableThreads()); + } + } + + @ManagedAttribute + @Description( "The average time needed to complete a work item" ) + public long averageWorkCompletionTime() { + return (totalTimeTaken.get() / processedCount.get()); + } + + @ManagedAttribute + @Description( "The number of work items processed" ) + public long currentProcessedCount() { + return processedCount.get(); + } + + @NameValue + public String getName() { + return name; + } + + /** + * This method will return the number of WorkQueues serviced by the threadpool. + */ + public int numberOfWorkQueues() { + return 1; + } + + + private static int getUniqueThreadId() { + return ThreadPoolImpl.threadCounter.incrementAndGet(); + } + + /** + * This method will decrement the number of available threads + * in the threadpool which are waiting for work. Called from + * WorkQueueImpl.requestWork() + */ + void decrementNumberOfAvailableThreads() { + synchronized (workQueue) { + availableWorkerThreads--; + } + } + + /** + * This method will increment the number of available threads + * in the threadpool which are waiting for work. Called from + * WorkQueueImpl.requestWork() + */ + void incrementNumberOfAvailableThreads() { + synchronized (workQueue) { + availableWorkerThreads++; + } + } + + private class WorkerThread extends Thread implements Closeable + { + final private static String THREAD_POOLNAME_PREFIX_STR = "p: "; + final private static String WORKER_THREAD_NAME_PREFIX_STR = "; w: "; + final private static String IDLE_STR = "Idle"; + + private Work currentWork ; + private volatile boolean closeCalled = false ; + + WorkerThread(ThreadGroup tg, String threadPoolName) { + super(tg, THREAD_POOLNAME_PREFIX_STR + threadPoolName + + WORKER_THREAD_NAME_PREFIX_STR + ThreadPoolImpl.getUniqueThreadId()); + this.currentWork = null; + } + + private void setClassLoader() { + if (System.getSecurityManager() == null) + setClassLoaderHelper() ; + else { + AccessController.doPrivileged( + new PrivilegedAction() { + public ClassLoader run() { + return WorkerThread.this.setClassLoaderHelper() ; + } + } + ) ; + } + } + + private ClassLoader setClassLoaderHelper() { + Thread thr = Thread.currentThread() ; + ClassLoader result = thr.getContextClassLoader() ; + thr.setContextClassLoader( workerThreadClassLoader ) ; + return result ; + } + + public synchronized void close() { + closeCalled = true ; + interrupt() ; + } + + private void resetClassLoader() { + ClassLoader currentClassLoader = null; + try { + if (System.getSecurityManager() == null) { + currentClassLoader = getContextClassLoader() ; + } else { + currentClassLoader = AccessController.doPrivileged( + new PrivilegedAction() { + public ClassLoader run() { + return getContextClassLoader(); + } + } + ); + } + } catch (SecurityException se) { + throw Exceptions.self.workerThreadGetContextClassloaderFailed(se, this); + } + + if (workerThreadClassLoader != currentClassLoader) { + Exceptions.self.workerThreadForgotClassloaderReset(this, + currentClassLoader, workerThreadClassLoader); + + try { + setClassLoader() ; + } catch (SecurityException se) { + Exceptions.self.workerThreadResetContextClassloaderFailed(se, this); + } + } + } + + private void performWork() { + long start = System.currentTimeMillis(); + try { + currentWork.doWork(); + } catch (Throwable t) { + Exceptions.self.workerThreadDoWorkThrowable(t, this); + } finally { + ThreadStateValidator.checkValidators(); + } + long elapsedTime = System.currentTimeMillis() - start; + totalTimeTaken.addAndGet(elapsedTime); + processedCount.incrementAndGet(); + } + + @Override + public void run() { + try { + // Issue 13266: Make sure that the ClassLoader is set the FIRST time + // the worker thread runs. resetClassLoader below takes care of the + // other cases. + setClassLoader() ; + + while (!closeCalled) { + try { + currentWork = ((WorkQueueImpl)workQueue).requestWork( + inactivityTimeout); + if (currentWork == null) + continue; + } catch (WorkerThreadNotNeededException toe) { + Exceptions.self.workerThreadNotNeeded(this, + currentNumberOfThreads(), minimumNumberOfThreads()); + closeCalled = true ; + continue ; + } catch (InterruptedException exc) { + Thread.interrupted() ; + Exceptions.self.workQueueThreadInterrupted( exc, super.getName(), + Boolean.valueOf( closeCalled ) ) ; + + continue ; + } catch (Throwable t) { + Exceptions.self.workerThreadThrowableFromRequestWork(t, this, + workQueue.getName()); + + continue; + } + + performWork() ; + + // set currentWork to null so that the work item can be + // garbage collected without waiting for the next work item. + currentWork = null; + + resetClassLoader() ; + } + } catch (Throwable e) { + // This should not be possible + Exceptions.self.workerThreadCaughtUnexpectedThrowable(e, this); + } finally { + synchronized (workersLock) { + workers.remove( this ) ; + } + } + } + } // End of WorkerThread class +} + +// End of file. diff --git a/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/ThreadPoolManagerImpl.java b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/ThreadPoolManagerImpl.java new file mode 100644 index 000000000..dd6db908e --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/ThreadPoolManagerImpl.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.threadpool; + +import java.io.IOException ; + +import java.security.PrivilegedAction; +import java.security.AccessController ; + +import java.util.concurrent.atomic.AtomicInteger ; + +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; +import com.sun.corba.ee.spi.threadpool.ThreadPool; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.corba.ee.spi.threadpool.ThreadPoolChooser; + +public class ThreadPoolManagerImpl implements ThreadPoolManager +{ + public static final String THREADPOOL_DEFAULT_NAME = "default-threadpool"; + + private ThreadPool threadPool ; + private ThreadGroup threadGroup ; + + public ThreadPoolManagerImpl() { + threadGroup = getThreadGroup() ; + threadPool = new ThreadPoolImpl( threadGroup, + THREADPOOL_DEFAULT_NAME ) ; + } + + private static AtomicInteger tgCount = new AtomicInteger() ; + + private ThreadGroup getThreadGroup() { + ThreadGroup tg ; + + // See bugs 4916766 and 4936203 + // We intend to create new threads in a reliable thread group. + // This avoids problems if the application/applet + // creates a thread group, makes JavaIDL calls which create a new + // connection and ReaderThread, and then destroys the thread + // group. If our ReaderThreads were to be part of such destroyed thread + // group then it might get killed and cause other invoking threads + // sharing the same connection to get a non-restartable + // CommunicationFailure. We'd like to avoid that. + // + // Our solution is to create all of our threads in the highest thread + // group that we have access to, given our own security clearance. + // + try { + // try to get a thread group that's as high in the threadgroup + // parent-child hierarchy, as we can get to. + // this will prevent an ORB thread created during applet-init from + // being killed when an applet dies. + tg = AccessController.doPrivileged( + new PrivilegedAction() { + public ThreadGroup run() { + ThreadGroup tg = Thread.currentThread().getThreadGroup() ; + ThreadGroup ptg = tg ; + try { + while (ptg != null) { + tg = ptg; + ptg = tg.getParent(); + } + } catch (SecurityException se) { + // Discontinue going higher on a security exception. + } + return new ThreadGroup(tg, "ORB ThreadGroup " + tgCount.getAndIncrement() ); + } + } + ); + } catch (SecurityException e) { + // something wrong, we go back to the original code + tg = Thread.currentThread().getThreadGroup(); + } + + return tg ; + } + + public void close() { + try { + threadPool.close() ; + } catch (IOException exc) { + Exceptions.self.threadPoolCloseError() ; + } + + try { + boolean isDestroyed = threadGroup.isDestroyed() ; + int numThreads = threadGroup.activeCount() ; + int numGroups = threadGroup.activeGroupCount() ; + + if (isDestroyed) { + Exceptions.self.threadGroupIsDestroyed( threadGroup ) ; + } else { + if (numThreads > 0) + Exceptions.self.threadGroupHasActiveThreadsInClose( threadGroup, numThreads ) ; + + if (numGroups > 0) + Exceptions.self.threadGroupHasSubGroupsInClose( threadGroup, numGroups ) ; + + threadGroup.destroy() ; + } + } catch (IllegalThreadStateException exc ) { + Exceptions.self.threadGroupDestroyFailed( exc, threadGroup ) ; + } + + threadGroup = null ; + } + + /** + * This method will return an instance of the threadpool given a threadpoolId, + * that can be used by any component in the app. server. + * + * @throws NoSuchThreadPoolException thrown when invalid threadpoolId is passed + * as a parameter + */ + public ThreadPool getThreadPool(String threadpoolId) + throws NoSuchThreadPoolException { + + return threadPool; + } + + /** + * This method will return an instance of the threadpool given a numeric threadpoolId. + * This method will be used by the ORB to support the functionality of + * dedicated threadpool for EJB beans + * + * @throws NoSuchThreadPoolException thrown when invalidnumericIdForThreadpool is passed + * as a parameter + */ + public ThreadPool getThreadPool(int numericIdForThreadpool) + throws NoSuchThreadPoolException { + + return threadPool; + } + + /** + * This method is used to return the numeric id of the threadpool, given a String + * threadpoolId. This is used by the POA interceptors to add the numeric threadpool + * Id, as a tagged component in the IOR. This is used to provide the functionality of + * dedicated threadpool for EJB beans + */ + public int getThreadPoolNumericId(String threadpoolId) { + return 0; + } + + /** + * Return a String Id for a numericId of a threadpool managed by the threadpool + * manager + */ + public String getThreadPoolStringId(int numericIdForThreadpool) { + return ""; + } + + /** + * Returns the first instance of ThreadPool in the ThreadPoolManager + */ + public ThreadPool getDefaultThreadPool() { + return threadPool; + } + + /** + * Return an instance of ThreadPoolChooser based on the componentId that was + * passed as argument + */ + public ThreadPoolChooser getThreadPoolChooser(String componentId) { + //FIXME: This method is not used, but should be fixed once + //nio select starts working and we start using ThreadPoolChooser + return null; + } + /** + * Return an instance of ThreadPoolChooser based on the componentIndex that was + * passed as argument. This is added for improved performance so that the caller + * does not have to pay the cost of computing hashcode for the componentId + */ + public ThreadPoolChooser getThreadPoolChooser(int componentIndex) { + //FIXME: This method is not used, but should be fixed once + //nio select starts working and we start using ThreadPoolChooser + return null; + } + + /** + * Sets a ThreadPoolChooser for a particular componentId in the ThreadPoolManager. This + * would enable any component to add a ThreadPoolChooser for their specific use + */ + public void setThreadPoolChooser(String componentId, ThreadPoolChooser aThreadPoolChooser) { + //FIXME: This method is not used, but should be fixed once + //nio select starts working and we start using ThreadPoolChooser + } + + /** + * Gets the numeric index associated with the componentId specified for a + * ThreadPoolChooser. This method would help the component call the more + * efficient implementation i.e. getThreadPoolChooser(int componentIndex) + */ + public int getThreadPoolChooserNumericId(String componentId) { + //FIXME: This method is not used, but should be fixed once + //nio select starts working and we start using ThreadPoolChooser + return 0; + } + +} + +// End of file. diff --git a/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/WorkQueueImpl.java b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/WorkQueueImpl.java new file mode 100644 index 000000000..f1da914ad --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/WorkQueueImpl.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.threadpool; + +import java.util.LinkedList; +import java.util.Queue; + +import com.sun.corba.ee.spi.threadpool.ThreadPool; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.threadpool.WorkQueue; + +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.NameValue ; + +public class WorkQueueImpl implements WorkQueue +{ + public static final String WORKQUEUE_DEFAULT_NAME = "default-workqueue"; + + final private Queue queue; + private ThreadPool workerThreadPool; + + private long workItemsAdded = 0; + private long workItemsDequeued = 0; + private long totalTimeInQueue = 0; + + // Name of the work queue + final private String name; + + public WorkQueueImpl() { + this.name = WORKQUEUE_DEFAULT_NAME; + this.queue = new LinkedList(); + } + + public WorkQueueImpl(ThreadPool workerThreadPool) { + this(workerThreadPool, WORKQUEUE_DEFAULT_NAME); + } + + public WorkQueueImpl(ThreadPool workerThreadPool, String name) { + this.workerThreadPool = workerThreadPool; + this.name = name; + this.queue = new LinkedList(); + } + + private synchronized int getWorkQueueSize() { + return queue.size(); + } + + public synchronized void addWork(Work work) { + workItemsAdded++; + work.setEnqueueTime(System.currentTimeMillis()); + + queue.offer(work); + notify(); + + int waitingThreads = workerThreadPool.numberOfAvailableThreads(); + int threadCount = workerThreadPool.currentNumberOfThreads(); + int maxThreads = workerThreadPool.maximumNumberOfThreads(); + if (threadCount < maxThreads && waitingThreads < getWorkQueueSize()) { + // NOTE: It is possible that the Work that was just added may unblock + // Worker Threads waiting on the Work just added and all Worker + // Threads are busy, (blocked & waiting for a response). This + // situation can lead to a deadlock. The solution to such a + // a problem should it occur is to increase the maximum number + // of threads. + // REVISIT - A possible solution to the above issue is check the + // enqueued Work timestamp periodically by another thread + // and create a Worker Thread if a piece of Work sits on + // Work Queue for longer than some threshold. + // add a WorkerThread + ((ThreadPoolImpl)workerThreadPool).createWorkerThread(); + } + } + + // XXX Re-write this to use a simple poll( waitTime, TimeUnit.MILLISECONDS ) + // and avoid the race conditions. The change is a little too large to make + // right now (a few days before GFv3 HCF). See issue 7722. + synchronized Work requestWork(long waitTime) throws WorkerThreadNotNeededException, + InterruptedException { + + if (this.isQueueEmpty()) { + try { + ((ThreadPoolImpl)workerThreadPool).incrementNumberOfAvailableThreads(); + long timeOutTime = System.currentTimeMillis() + waitTime; + + wait(waitTime); + + if (this.isQueueEmpty() && System.currentTimeMillis() >= timeOutTime) { + int availableThreads = + workerThreadPool.numberOfAvailableThreads(); + int minThreads = workerThreadPool.minimumNumberOfThreads(); + if (availableThreads > minThreads) { + // This thread has timed out and can die because + // we have enough available idle threads. + // NOTE: It is expected the WorkerThread calling this + // method will gracefully exit as a result of + // catching the WorkerThreadNotNeededException. + ((ThreadPoolImpl)workerThreadPool). + decrementCurrentNumberOfThreads(); + throw new WorkerThreadNotNeededException(); + } + } + + // We still want to keep this thread, but let it do a + // poll in case we waited at least as long + // as timeOutTime, and then we were awakened by addWork. + // In that case, we still want to do the queue.poll(). + } finally { + ((ThreadPoolImpl)workerThreadPool).decrementNumberOfAvailableThreads(); + } + } + + Work work = queue.poll(); + if (work != null) { + workItemsDequeued++ ; + totalTimeInQueue += System.currentTimeMillis() - work.getEnqueueTime() ; + } + + return work ; + } + + private synchronized boolean isQueueEmpty() { + int waitingThreads = workerThreadPool.numberOfAvailableThreads(); + return (queue.size() - waitingThreads <= 0); + } + + public synchronized void setThreadPool(ThreadPool workerThreadPool) { + this.workerThreadPool = workerThreadPool; + } + + public synchronized ThreadPool getThreadPool() { + return workerThreadPool; + } + + /** + * Returns the total number of Work items added to the Queue. + */ + @ManagedAttribute + @Description( "Total number of items added to the queue" ) + public synchronized long totalWorkItemsAdded() { + return workItemsAdded; + } + + /** + * Returns the total number of Work items in the Queue to be processed. + */ + @ManagedAttribute + @Description( "Total number of items in the queue to be processed" ) + public synchronized int workItemsInQueue() { + return queue.size(); + } + + /** + * Returns the average amount Work items have spent in the Queue waiting + * to be processed. + */ + @ManagedAttribute + @Description( "Average time work items spend waiting in the queue in milliseconds" ) + public synchronized long averageTimeInQueue() { + if (workItemsDequeued == 0) { + return 0 ; + } else { + return (totalTimeInQueue/workItemsDequeued); + } + } + + @NameValue + public String getName() { + return name; + } +} + +// End of file. diff --git a/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/WorkerThreadNotNeededException.java b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/WorkerThreadNotNeededException.java new file mode 100644 index 000000000..285ad3353 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/impl/threadpool/WorkerThreadNotNeededException.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.threadpool; + +public class WorkerThreadNotNeededException extends Exception { + + public WorkerThreadNotNeededException() { + super(); + } + + public WorkerThreadNotNeededException(String message) { + super(message); + } + + public WorkerThreadNotNeededException(String message, Throwable cause) { + super(message, cause); + } + + public WorkerThreadNotNeededException(Throwable cause) { + super(cause); + } +} + +// End of file. + diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/logex/stdcorba/StandardLogger.java b/internal-api/src/main/java/com/sun/corba/ee/spi/logex/stdcorba/StandardLogger.java new file mode 100644 index 000000000..f6e637eb7 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/logex/stdcorba/StandardLogger.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logex.stdcorba; + +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +/** + * + * @author ken_admin + */ +public class StandardLogger extends WrapperGenerator.ExtensionBase { + public static final StandardLogger self = new StandardLogger() ; + + private static final String SPI_PREFIX = "com.sun.corba.ee.spi." ; + private static final String IMPL_PREFIX = "com.sun.corba.ee.impl." ; + public static final String CORBA_LOGGER_PREFIX = + "javax.enterprise.resource.corba" ; + + @Override + public String getLoggerName( Class cls ) { + final ExceptionWrapper ew = cls.getAnnotation( ExceptionWrapper.class ) ; + if (!ew.loggerName().equals( "" )) { + return ew.loggerName() ; + } + + final String name = cls.getPackage().getName() ; + String shortName ; + if (name.startsWith( SPI_PREFIX )) { + shortName = name.substring( SPI_PREFIX.length() ) ; + } else if (name.startsWith( IMPL_PREFIX )) { + shortName = name.substring( IMPL_PREFIX.length() ) ; + } else { + shortName = name ; + } + + return CORBA_LOGGER_PREFIX + "." + shortName ; + } +} diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/NoSuchThreadPoolException.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/NoSuchThreadPoolException.java new file mode 100644 index 000000000..b906c519e --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/NoSuchThreadPoolException.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +public class NoSuchThreadPoolException extends Exception +{ +} + +// End of file. + diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/NoSuchWorkQueueException.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/NoSuchWorkQueueException.java new file mode 100644 index 000000000..d8285611d --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/NoSuchWorkQueueException.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +public class NoSuchWorkQueueException extends Exception +{ +} + +// End of file. + diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPool.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPool.java new file mode 100644 index 000000000..6481cedbe --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPool.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +import java.io.Closeable ; + +/** This interface defines a thread pool execution service. The ORB uses this + * interface, which preceeds the JDK 5 ExecutorService. Note that the close + * method must be called in order to reclaim thread resources. + */ +public interface ThreadPool extends Closeable +{ + /** + * This method will return any instance of the WorkQueue. If the ThreadPool + * instance only services one WorkQueue then that WorkQueue instance will + * be returned. If there are more than one WorkQueues serviced by this + * ThreadPool, then this method would return a WorkQueue based on the + * implementation of the class that implements this interface. For PE 8.0 we + * would return a WorkQueue in a roundrobin fashion everytime this method + * is called. In the future we could allow pluggability of Policy objects for this. + */ + public WorkQueue getAnyWorkQueue(); + + /** + * This method will return an instance of the of the WorkQueue given a queueId. + * This will be useful in situations where there are more than one WorkQueues + * managed by the ThreadPool and the user of the ThreadPool wants to always use + * the same WorkQueue for doing the Work. + * If the number of WorkQueues in the ThreadPool are 10, then queueIds will go + * from 0-9 + * + * @throws NoSuchWorkQueueException thrown when queueId passed is invalid + */ + public WorkQueue getWorkQueue(int queueId) throws NoSuchWorkQueueException; + + /** + * This method will return the number of WorkQueues serviced by the threadpool. + */ + public int numberOfWorkQueues(); + + /** + * This method will return the minimum number of threads maintained by the threadpool. + */ + public int minimumNumberOfThreads(); + + /** + * This method will return the maximum number of threads in the threadpool at any + * point in time, for the life of the threadpool + */ + public int maximumNumberOfThreads(); + + /** + * This method will return the time in milliseconds when idle threads in the threadpool are + * removed. + */ + public long idleTimeoutForThreads(); + + /** + * This method will return the current number of threads in the threadpool. This method + * returns a value which is not synchronized. + */ + public int currentNumberOfThreads(); + + /** + * This method will return the number of available threads in the threadpool which are + * waiting for work. This method returns a value which is not synchronized. + */ + public int numberOfAvailableThreads(); + + /** + * This method will return the number of busy threads in the threadpool + * This method returns a value which is not synchronized. + */ + public int numberOfBusyThreads(); + + /** + * This method returns the number of Work items processed by the threadpool + */ + public long currentProcessedCount(); + + /** + * This method returns the average elapsed time taken to complete a Work + * item. + */ + public long averageWorkCompletionTime(); + + /** + * This method will return the name of the threadpool. + */ + public String getName(); + +} + +// End of file. diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolChooser.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolChooser.java new file mode 100644 index 000000000..8e2aa3507 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolChooser.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + + +public interface ThreadPoolChooser +{ + /** + * This method is used to return an instance of ThreadPool based on the + * strategy/policy implemented in the ThreadPoolChooser from the set of + * ThreadPools allowed to be used by the ORB. Typically, the set of + * ThreadPools would be specified by passing the threadpool-ids + * configured in the ORB element of the domain.xml of the appserver. + */ + public ThreadPool getThreadPool(); + + /** + * This method is used to return an instance of ThreadPool that is obtained + * by using the id argument passed to it. This method will be used in + * situations where the threadpool id is known to the caller e.g. by the + * connection object or looking at the high order bits of the request id + */ + public ThreadPool getThreadPool(int id); + + /** + * This method is a convenience method to see what threadpool-ids are being + * used by the ThreadPoolChooser + */ + public String[] getThreadPoolIds(); +} diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolFactory.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolFactory.java new file mode 100644 index 000000000..e66fa95a1 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolFactory.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +import com.sun.corba.ee.impl.threadpool.ThreadPoolImpl ; + +public class ThreadPoolFactory { + /** Create an unbounded thread pool in the current thread group + * with the current context ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPool create( String threadpoolName) { + return new ThreadPoolImpl( threadpoolName ) ; + } + + /** Create an unbounded thread pool in the given thread group + * with the current context ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPool create( ThreadGroup tg, String threadpoolName ) { + return new ThreadPoolImpl( tg, threadpoolName ) ; + } + + /** Create an unbounded thread pool in the given thread group + * with the given ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPool create(ThreadGroup tg, String threadpoolName, + ClassLoader defaultClassLoader) { + return new ThreadPoolImpl( tg, threadpoolName, defaultClassLoader ) ; + } + + /** Create a bounded thread pool in the current thread group + * with the current context ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPool create( int minSize, int maxSize, long timeout, + String threadpoolName) { + + return new ThreadPoolImpl( minSize, maxSize, timeout, threadpoolName ) ; + } + + /** Create a bounded thread pool in the current thread group + * with the given ClassLoader as the worker thread default + * ClassLoader. + */ + public ThreadPool create( int minSize, int maxSize, long timeout, + String threadpoolName, ClassLoader defaultClassLoader ) + { + return new ThreadPoolImpl( minSize, maxSize, timeout, + threadpoolName, defaultClassLoader ) ; + } +} diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolManager.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolManager.java new file mode 100644 index 000000000..839412c5a --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadPoolManager.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +import java.io.Closeable ; + +public interface ThreadPoolManager extends Closeable +{ + /** + * This method will return an instance of the threadpool given a threadpoolId, + * that can be used by any component in the app. server. + * + * @throws NoSuchThreadPoolException thrown when invalid threadpoolId is passed + * as a parameter + */ + public ThreadPool getThreadPool(String threadpoolId) throws NoSuchThreadPoolException; + + /** + * This method will return an instance of the threadpool given a numeric threadpoolId. + * This method will be used by the ORB to support the functionality of + * dedicated threadpool for EJB beans + * + * @throws NoSuchThreadPoolException thrown when invalidnumericIdForThreadpool is passed + * as a parameter + */ + public ThreadPool getThreadPool(int numericIdForThreadpool) throws NoSuchThreadPoolException; + + /** + * This method is used to return the numeric id of the threadpool, given a String + * threadpoolId. This is used by the POA interceptors to add the numeric threadpool + * Id, as a tagged component in the IOR. This is used to provide the functionality of + * dedicated threadpool for EJB beans + */ + public int getThreadPoolNumericId(String threadpoolId); + + /** + * Return a String Id for a numericId of a threadpool managed by the threadpool + * manager + */ + public String getThreadPoolStringId(int numericIdForThreadpool); + + /** + * Returns the first instance of ThreadPool in the ThreadPoolManager + */ + public ThreadPool getDefaultThreadPool(); + + /** + * Return an instance of ThreadPoolChooser based on the componentId that was + * passed as argument + */ + public ThreadPoolChooser getThreadPoolChooser(String componentId); + + /** + * Return an instance of ThreadPoolChooser based on the componentIndex that was + * passed as argument. This is added for improved performance so that the caller + * does not have to pay the cost of computing hashcode for the componentId + */ + public ThreadPoolChooser getThreadPoolChooser(int componentIndex); + + /** + * Sets a ThreadPoolChooser for a particular componentId in the ThreadPoolManager. This + * would enable any component to add a ThreadPoolChooser for their specific use + */ + public void setThreadPoolChooser(String componentId, ThreadPoolChooser aThreadPoolChooser); + + /** + * Gets the numeric index associated with the componentId specified for a + * ThreadPoolChooser. This method would help the component call the more + * efficient implementation i.e. getThreadPoolChooser(int componentIndex) + */ + public int getThreadPoolChooserNumericId(String componentId); +} + +// End of file. diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadStateValidator.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadStateValidator.java new file mode 100644 index 000000000..e6a44faf0 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/ThreadStateValidator.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +import com.sun.corba.ee.impl.threadpool.Exceptions ; +import java.util.ArrayList; +import java.util.List; + +/** Interface to support thread state validation. The basic idea is that + * one or more validators can be registered with an implementation of the + * TSV. The validators are executed whenever a thread is returned to the + * threadpool, For example, a validator may check for unreleased locks or uncleared + * threadlocals. This is intended as a last-ditch backstop for leaking resource + * problems. + * + * @author ken + */ +public class ThreadStateValidator { + private static final Exceptions wrapper = Exceptions.self ; + + private static final List validators = new ArrayList() ; + + private ThreadStateValidator() {} + + /** Register a thread validator (represented as a Runnable). + * A validator may check for locks that should not be held, check + * for threadlocals that should be cleared, or take any other action + * to check for resources that should not be held once the thread is no + * longer needed, as signaled by the thread being returned to the threadpool. + *

+ * A validator typically may take the following actions: + *

    + *
  1. Check whether or not a resource has been released. + *
  2. Log any detected problems. + *
  3. Reclaim the resource. + *
+ * A validator should NOT throw an exception, as all exceptions thrown + * from a validator will be ignored. + * + * @param validator + */ + public static void registerValidator( Runnable validator ) { + validators.add( validator ) ; + } + + /** Execute all of the validators. Should only be called from the + * threadpool implementation. + */ + public static void checkValidators() { + for (Runnable run : validators) { + try { + run.run() ; + } catch (Throwable thr) { + wrapper.threadStateValidatorException( run, thr ) ; + } + } + } +} diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/Work.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/Work.java new file mode 100644 index 000000000..8806f8858 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/Work.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +public interface Work +{ + + /** + * This method denotes the actual work that is done by the work item. + */ + public void doWork(); + + /** + * This methods sets the time in millis in the work item, when this + * work item was enqueued in the work queue. + */ + public void setEnqueueTime(long timeInMillis); + + /** + * This methods gets the time in millis in the work item, when this + * work item was enqueued in the work queue. + */ + public long getEnqueueTime(); + + /** + * This method will return the name of the work item. + */ + public String getName(); + +} + +// End of file. + diff --git a/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/WorkQueue.java b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/WorkQueue.java new file mode 100644 index 000000000..41dfedeb6 --- /dev/null +++ b/internal-api/src/main/java/com/sun/corba/ee/spi/threadpool/WorkQueue.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.threadpool; + +public interface WorkQueue +{ + + /** + * This method is used to add work to the WorkQueue + */ + public void addWork(Work aWorkItem); + + /** + * This method will return the name of the WorkQueue. + */ + public String getName(); + + /** + * Returns the total number of Work items added to the Queue. + */ + public long totalWorkItemsAdded(); + + /** + * Returns the total number of Work items in the Queue to be processed. + */ + public int workItemsInQueue(); + + /** + * Returns the average time a work item is waiting in the queue before + * getting processed. + */ + public long averageTimeInQueue(); + + /** + * Set the ThreadPool instance servicing this WorkQueue + */ + public void setThreadPool(ThreadPool aThreadPool); + + /** + * Get the ThreadPool instance servicing this WorkQueue + */ + public ThreadPool getThreadPool(); +} + +// End of file. diff --git a/make/BundleNotes.txt b/make/BundleNotes.txt new file mode 100644 index 000000000..e2bb2e3b4 --- /dev/null +++ b/make/BundleNotes.txt @@ -0,0 +1,24 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Some packages are exported in the glassfish-corba-orb bundle because they are +needed at runtime for various reflective operations. This includes: + +com.sun.corba.ee.impl.orb: so that ORBSingleton is available +com.sun.corba.ee.impl.presentation.rmi: so that CodegenStubBase is available +com.sun.corba.ee.spi.trace: while these are internal only, they are + needed in order for the trace facility code in glassfish-corba-orbgeneric + to be able to load these classes reflectively from + glassfish-corba-orb +com.sun.corba.ee.impl.javax.*: + It seems that we need to make sure that the implementations of the standard + RMI-IIOP PortableRemoteObject, Stub, and Util classes need to be visible in users + of glassfish-corba-orb, or the standard javax.rmi.* classes won't be able + to load the implementations. diff --git a/make/build.properties b/make/build.properties new file mode 100644 index 000000000..cd0df228b --- /dev/null +++ b/make/build.properties @@ -0,0 +1,18 @@ +# +# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +#Wed, 20 Jul 2011 14:06:24 -0700 +#Wed Feb 09 10:55:14 PST 2011 +corba.update.version=0 +build.int=005 +build.version=b${build.int} +corba.major.version=3 +corba.minor.version=2 +release.version=${corba.major.version}.${corba.minor.version}.${corba.update.version} diff --git a/make/build.xml b/make/build.xml new file mode 100644 index 000000000..85b9324fd --- /dev/null +++ b/make/build.xml @@ -0,0 +1,499 @@ + + + + + + This is the Ant file that builds the GlassFish ORB. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/make/copyright-information/copyright.txt b/make/copyright-information/copyright.txt new file mode 100644 index 000000000..8069d4971 --- /dev/null +++ b/make/copyright-information/copyright.txt @@ -0,0 +1,8 @@ + + Copyright (c) @StartYear@-@LastYear@ Oracle and/or its affiliates. All rights reserved. + + This program and the accompanying materials are made available under the + terms of the Eclipse Distribution License v. 1.0, which is available at + http://www.eclipse.org/org/documents/edl-v10.php. + + SPDX-License-Identifier: BSD-3-Clause diff --git a/make/copyright-information/file_suffix_classification.txt b/make/copyright-information/file_suffix_classification.txt new file mode 100644 index 000000000..d770a163d --- /dev/null +++ b/make/copyright-information/file_suffix_classification.txt @@ -0,0 +1,65 @@ +Changes in /volumes/ws/headers: + +Block comments: + Java comment conventions (Use /* ... */ block comments): + C source: + *.c *.h + + Java source: + *.java *.javaref *.sjava + (also policy files: *.policy *.secure) + + IDL + *.idl *.idlref + + XML/HTML related: + (All use for block comments) + HTML + *.htm *.html: + + XML + *.xml *.pom + + XML DTD + *.dtd + +Line comments: + Scheme comment conventions: (comment lines start with ;) + Scheme source: + *.mc *.mcd *.scm *.vthought + + Unix shell comment: (Comment lines start with #): + *.classlist *.config *.jmk *.ksh *.properties *.prp *.xjmk *.set *.sh *.data + + Makefiles: + Makefile.corba *.gmk Makefile.example ExampleMakefile Makefile + + Text files: + *.text *.txt + + Also, anything with contents that starts with #! is a shell script + +Things that do NOT get comments: + Binary files: + StarOffice files: + *.sxc *.sxi *.sxw *.odp + + Binary files: + *.gif *.png *.jar *.zip *.jpg *.pdf + + Framemaker + *.doc *.mif *.fm *.book + + UML tools: + *.zargo *.zuml + + text files, no comments allowed: + .cvsignore .hgignore *.list + + ASM java file: + *.old + + BCEL java file: + *.orig *.rej + +ignore *.swp (from vim) diff --git a/make/findbugs-filter.xml b/make/findbugs-filter.xml new file mode 100644 index 000000000..76bd0b220 --- /dev/null +++ b/make/findbugs-filter.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/make/runtest b/make/runtest new file mode 100755 index 000000000..4acacbd33 --- /dev/null +++ b/make/runtest @@ -0,0 +1,14 @@ +#! /bin/sh +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +export TEST_ARGS +TEST_ARGS=$* +ant run-test-target diff --git a/make/src-build-notes.txt b/make/src-build-notes.txt new file mode 100644 index 000000000..44dcaa443 --- /dev/null +++ b/make/src-build-notes.txt @@ -0,0 +1,63 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Current path for the build target + +rename (mkdir java(WorkspaceRename) + init + +build + init (property, echo, path, pathconvert) + prepare-dirs (mkdir) + init + compile (echo, javac) + init + prepare-dirs + build-jscheme (javac, run-jscheme) + init + jscheme-not-available + MACRO run-jscheme + java + orb-library + init + compile-orb-library + init + prepare-dirs + compile-logutils (echo, javac) + init + compile-idl-compiler (echo, copy, javac) + init + run-all-idl (ant-call(call-idl) + compile-idl-compiler + run-all-jscheme (mkdir, property, java(REPL), antcall(call-jscheme), concat) + call-jscheme (java(REPL) + check-minorcode-file-changed + minorcode-file-changed + generate-timing-points + delete-java-sources (delete) + init + copy-resources (copy, echo) + init + make-bundles (was create-jars) + init + generate-bnd-properties (propertyfile) + init + make-src-bundle + init + MACRO make-bundle + +new-source-build.xml + +new-build.xml + IMPORTs new-source-build.xml + + overrides (and extends) targets: + init + prepare-dirs diff --git a/make/src-build.xml b/make/src-build.xml new file mode 100644 index 000000000..45cf5f5e4 --- /dev/null +++ b/make/src-build.xml @@ -0,0 +1,86 @@ + + + + + + This is the Ant file that builds the GlassFish ORB. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/omgapi/pom.xml b/omgapi/pom.xml new file mode 100644 index 000000000..c39a3b6e7 --- /dev/null +++ b/omgapi/pom.xml @@ -0,0 +1,69 @@ + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + glassfish-corba-omgapi + bundle + Generated OMG APIs + + + + + org.codehaus.mojo + idlj-maven-plugin + + + src/main/idl-includes + + + + + CORBA org.omg + CosNaming org.omg + CosTransactions org.omg + CosTSInteroperationorg.omg + CosTSPortability org.omg + Dynamic org.omg + DynamicAny org.omg + IOP org.omg + Messaging org.omg + PortableInterceptororg.omg + PortableServer org.omg + SendingContext org.omg + TimeBase org.omg + + + + + + + + org.apache.felix + maven-bundle-plugin + + + org.omg.*; version=1, com.sun.*;version=1, javax.rmi.CORBA;version=1 + !org.omg.PortableServer.ServantLocatorPackage + system.bundle; extension:=framework + + + + + + diff --git a/omgapi/src/main/idl-includes/corba.idl b/omgapi/src/main/idl-includes/corba.idl new file mode 100644 index 000000000..a4abc139c --- /dev/null +++ b/omgapi/src/main/idl-includes/corba.idl @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// minimal definitions to keep idltojava happy while compiling poa.idl +#pragma prefix "omg.org" + +module CORBA { + + typedef string Identifier; + typedef string RepositoryId; + + // basic Policy definition + typedef unsigned long PolicyType ; + + /** The Policy interface provides a mechanism for ORBs and Object + * Services to allow access to certain choices that affect their + * operation. This information is accessed in a structured manner + * using interfaces derived from the org.omg.CORBA.Policy interface. + */ + interface Policy { + /** Return the constant value that corresponds to the + * type of the policy object. The values of + * the polivy objectys are allocated by the OMG. + * New values for PolicyType should be obtained from the OMG by + * sending mail to request@omg.org. In general the constant + * values that are allocated are defined in conjunction with + * the definition of the corresponding policy object. + * @return the constant value that corresponds to the type of + * the policy object. + */ + readonly attribute PolicyType policy_type; + + /** Copies the policy object. The copy does not retain any + * relationships that the policy had with any domain or object. + * @return the copy of the policy object. + */ + Policy copy( ); + + /** Destroys the policy object. It is the responsibility of + * the policy object to determine whether it can be destroyed. + */ + void destroy( ); + }; + + typedef sequence PolicyList; + + /** + * An interface that makes it possible to access information + * associated with a particular thread of execution, such as + * security information or a transaction identifier. + *

+ * An ORB or CORBA service that needs its own thread-specific + * state extends the CORBA package's Current. + * Users of the service can obtain an instance of the appropriate + * Current interface by invoking + * ORB.resolve_initial_references. + * For example, the Security service obtains the Current + * relevant to it by invoking + *

+         *    ORB.resolve_initial_references("SecurityCurrent");
+         * 
+ *

+ * A CORBA service does not have to use this method of keeping context + * but may choose to do so. + *

+ * Methods on classes that implement from Current access state + * associated with the thread in which they are invoked, not state associated + * with the thread from which the Current was obtained. + * Current objects must not be exported to other processes, or externalized + * with ORB.object_to_string. If any attempt is made to do so, the offending + * operation will raise a MARSHAL system exception. + * @see portable + * package comments for unimplemented features + */ + interface Current { }; +}; + + diff --git a/omgapi/src/main/idl-includes/manual-ir.idl b/omgapi/src/main/idl-includes/manual-ir.idl new file mode 100644 index 000000000..4f00082f3 --- /dev/null +++ b/omgapi/src/main/idl-includes/manual-ir.idl @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * definitions from ir.idl that have been created manually and must not be generated. + */ + + +module CORBA { + + typedef string RepositoryId; + typedef string Identifier; + typedef string VersionSpec; + + // orbos 98-01-18: Objects By Value -- begin + typedef short Visibility; + const Visibility PRIVATE_MEMBER = 0; + const Visibility PUBLIC_MEMBER = 1; + + interface IDLType; + + enum DefinitionKind { + dk_none, dk_all, + dk_Attribute, dk_Constant, dk_Exception, dk_Interface, + dk_Module, dk_Operation, dk_Typedef, + dk_Alias, dk_Struct, dk_Union, dk_Enum, + dk_Primitive, dk_String, dk_Sequence, dk_Array, + dk_Repository, + dk_Wstring, dk_Fixed, + dk_Value, dk_ValueBox, dk_ValueMember, // orbos 98-01-18: Objects By Value + dk_Native + }; + + interface IRObject + /** + An IRObject IDL interface represents the most generic interface + from which all other Interface Repository interfaces are derived, + even the Repository itself. + */ + { + // read interface + readonly attribute DefinitionKind def_kind; + + // write interface + void destroy (); + }; + + + struct StructMember { + Identifier name; + TypeCode type; + IDLType type_def; + }; + + struct UnionMember { + Identifier name; + any label; + TypeCode type; + IDLType type_def; + }; + + struct ValueMember { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + IDLType type_def; + Visibility access; + }; + + + interface IDLType : IRObject + /** + The IDLType interface is an abstract interface inherited by all + IR objects that represent the OMG IDL types. It provides access + to the TypeCode describing the type, and is used in defining the + other interfaces wherever definitions of IDLType must be referenced. + */ + { + readonly attribute TypeCode type; + }; + + + enum TCKind { + tk_null, tk_void, + tk_short, tk_long, tk_ushort, tk_ulong, + tk_float, tk_double, tk_boolean, tk_char, + tk_octet, tk_any, tk_TypeCode, tk_Principal, tk_objref, + tk_struct, tk_union, tk_enum, tk_string, + tk_sequence, tk_array, tk_alias, tk_except, + tk_longlong, tk_ulonglong, tk_longdouble, + tk_wchar, tk_wstring, tk_fixed, + tk_value, tk_value_box, + tk_native, + tk_abstract_interface + }; +}; diff --git a/omgapi/src/main/idl-includes/orb.idl b/omgapi/src/main/idl-includes/orb.idl new file mode 100644 index 000000000..5fde42430 --- /dev/null +++ b/omgapi/src/main/idl-includes/orb.idl @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// IDL not generated by rmic, do not edit +// These are all in IDL module CORBA +// The Java classes are in the package org.omg.CORBA +// See ValueType Semantics:Standard Value Box Definitions (5.3) in CORBA 2.3 spec + +#ifndef __org_omg_CORBA__ +#define __org_omg_CORBA__ + +#pragma prefix "omg.org" + +module CORBA{ + + valuetype StringValue string; + valuetype WStringValue wstring; + +}; + +#include "ir.idl" + +#pragma prefix "" + +#endif diff --git a/omgapi/src/main/idl/CORBAX.idl b/omgapi/src/main/idl/CORBAX.idl new file mode 100644 index 000000000..bd8aa588a --- /dev/null +++ b/omgapi/src/main/idl/CORBAX.idl @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _CORBAX_IDL_ +#define _CORBAX_IDL_ + +#pragma prefix "omg.org" + +module CORBA { + /** + * Enumeration of parameter modes for Parameter. Possible vaues: + *

    + *
  • PARAM_IN - Represents an "in" parameter.
  • + *
  • PARAM_OUT - Represents an "out" parameter.
  • + *
  • PARAM_INOUT - Represents an "inout" parameter.
  • + *
+ */ + enum ParameterMode {PARAM_IN, PARAM_OUT, PARAM_INOUT}; + + /** An array of Strings */ + typedef sequence StringSeq; + + /** An array of WStrings */ + typedef sequence WStringSeq; + + /** A byte array */ + typedef sequence OctetSeq; + + /** Repository ID, represented as a String */ + typedef string RepositoryId; + + /** + * Encapsulates a reason a Policy may be invalid. + * + * @see PolicyError + */ + typedef short PolicyErrorCode; + + /** + * Thrown to indicate problems with parameter values passed to the + * ORB.create_policy operation. + */ + exception PolicyError { PolicyErrorCode reason; }; +}; + + +#endif // _CORBAX_IDL_ diff --git a/omgapi/src/main/idl/CosTSInteroperation.idl b/omgapi/src/main/idl/CosTSInteroperation.idl new file mode 100644 index 000000000..af2288262 --- /dev/null +++ b/omgapi/src/main/idl/CosTSInteroperation.idl @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// CosTSInteroperation module, as on 11/04/2000 +// CORBAservices, Transaction Service V1.2 (RTF Working Draft) +// http://www.omg.org/cgi-bin/doc?ptc/00-09-04.pdf + +#pragma prefix "omg.org" + +#include +#include "IOP.idl" + +module CosTSInteroperation { + + // Commented out since J2EE does not need them. + //const IOP::ComponentId TAG_TRANSACTION_POLICY = 26; + //struct TransactionPolicyComponent { + // TransactionPolicyValue value; + //}; + + const IOP::ComponentId TAG_OTS_POLICY = 31; + const IOP::ComponentId TAG_INV_POLICY = 32; +}; + diff --git a/omgapi/src/main/idl/CosTransactions.idl b/omgapi/src/main/idl/CosTransactions.idl new file mode 100644 index 000000000..61496dce9 --- /dev/null +++ b/omgapi/src/main/idl/CosTransactions.idl @@ -0,0 +1,267 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// CosTransactions module as on 11/04/2000 +// CORBAservices, Transaction Service V1.2 (RTF Working Draft) +// http://www.omg.org/cgi-bin/doc?ptc/00-09-04.pdf + +#pragma prefix "omg.org" + +#include + +module CosTransactions { + + // DATATYPES + + enum Status { + StatusActive, + StatusMarkedRollback, + StatusPrepared, + StatusCommitted, + StatusRolledBack, + StatusUnknown, + StatusNoTransaction, + StatusPreparing, + StatusCommitting, + StatusRollingBack + }; + + enum Vote { + VoteCommit, + VoteRollback, + VoteReadOnly + }; + + // TransactionPolicyValue definitions are deprecated and replaced // + // with new InvocationPolicy and OTSPolicy definitions. They are // + // retained for backward compatibility.// + // Commented out since J2EE does not need them. + //typedef unsigned short TransactionPolicyValue; + //const TransactionPolicyValue Allows_shared = 0; + //const TransactionPolicyValue Allows_none = 1; + //const TransactionPolicyValue Requires_shared = 2; + //const TransactionPolicyValue Allows_unshared = 3; + //const TransactionPolicyValue Allows_either = 4; + //const TransactionPolicyValue Requires_unshared = 5; + //const TransactionPolicyValue Requires_either = 6; + + // Forward references for interfaces defined later in module + + interface Current; + interface TransactionFactory; + interface Control; + interface Terminator; + interface Coordinator; + interface RecoveryCoordinator; + interface Resource; + interface Synchronization; + interface SubtransactionAwareResource; + // TransactionalObject has been deprecated. See 10.3.10. + interface TransactionalObject; + + // Structure definitions + + struct otid_t { + long formatID; /*format identifier. 0 is OSI TP */ + long bqual_length; + sequence tid; + }; + + struct TransIdentity { + Coordinator coord; + Terminator term; + otid_t otid; + }; + + struct PropagationContext { + unsigned long timeout; + TransIdentity current; + sequence parents; + any implementation_specific_data; + }; + + // Heuristic exceptions + + exception HeuristicRollback {}; + exception HeuristicCommit {}; + exception HeuristicMixed {}; + exception HeuristicHazard {}; + + // Other transaction-specific exceptions + + exception SubtransactionsUnavailable {}; + exception NotSubtransaction {}; + exception Inactive {}; + exception NotPrepared {}; + exception NoTransaction {}; + exception InvalidControl {}; + exception Unavailable {}; + exception SynchronizationUnavailable {}; + + // Current transaction + interface Current : CORBA::Current { + void begin() + raises(SubtransactionsUnavailable); + void commit(in boolean report_heuristics) + raises( + NoTransaction, + HeuristicMixed, + HeuristicHazard + ); + void rollback() + raises(NoTransaction); + void rollback_only() + raises(NoTransaction); + Status get_status(); + string get_transaction_name(); + void set_timeout(in unsigned long seconds); + unsigned long get_timeout(); + Control get_control(); + Control suspend(); + void resume(in Control which) + raises(InvalidControl); + }; + + interface TransactionFactory { + Control create(in unsigned long time_out); + Control recreate(in PropagationContext ctx); + }; + + interface Control { + Terminator get_terminator() + raises(Unavailable); + Coordinator get_coordinator() + raises(Unavailable); + }; + + interface Terminator { + void commit(in boolean report_heuristics) + raises( + HeuristicMixed, + HeuristicHazard + ); + void rollback(); + }; + + interface Coordinator { + Status get_status(); + Status get_parent_status(); + Status get_top_level_status(); + boolean is_same_transaction(in Coordinator tc); + boolean is_related_transaction(in Coordinator tc); + boolean is_ancestor_transaction(in Coordinator tc); + boolean is_descendant_transaction(in Coordinator tc); + boolean is_top_level_transaction(); + unsigned long hash_transaction(); + unsigned long hash_top_level_tran(); + RecoveryCoordinator register_resource(in Resource r) + raises(Inactive); + void register_synchronization (in Synchronization sync) + raises(Inactive, SynchronizationUnavailable); + void register_subtran_aware(in SubtransactionAwareResource r) + raises(Inactive, NotSubtransaction); + void rollback_only() + raises(Inactive); + string get_transaction_name(); + Control create_subtransaction() + raises(SubtransactionsUnavailable, Inactive); + PropagationContext get_txcontext () + raises(Unavailable); + }; + + interface RecoveryCoordinator { + Status replay_completion(in Resource r) + raises(NotPrepared); + }; + + interface Resource { + Vote prepare() + raises( + HeuristicMixed, + HeuristicHazard + ); + void rollback() + raises( + HeuristicCommit, + HeuristicMixed, + HeuristicHazard + ); + void commit() + raises( + NotPrepared, + HeuristicRollback, + HeuristicMixed, + HeuristicHazard + ); + void commit_one_phase() + raises( + HeuristicHazard + ); + void forget(); + }; + + // TransactionalObject has been deprecated // + // and replaced by the OTSPolicy component // + // Synchronization will use the OTSPolicy of ADAPTS // + // Inheritance from TransactionalObject is for backward compatability // + interface Synchronization { + void before_completion(); + void after_completion(in Status s); + }; + + interface SubtransactionAwareResource : Resource { + void commit_subtransaction(in Coordinator parent); + void rollback_subtransaction(); + }; + + // TransactionalObject has been deprecated. See 10.3.10. + interface TransactionalObject { + }; + + // TransactionPolicyType is deprecated and replaced // + // by InvocationPolicyType and OTSPolicyType // + // It is retained for backward compatibility. // + // Commented out since J2EE does not need them. + //typedef unsigned short TransactionPolicyValue; + //const CORBA::PolicyType TransactionPolicyType = 46; + //interface TransactionPolicy : CORBA::Policy { + // readonly attribute TransactionPolicyValue value; + //}; + + typedef unsigned short InvocationPolicyValue; + const InvocationPolicyValue EITHER = 0; + const InvocationPolicyValue SHARED = 1; + const InvocationPolicyValue UNSHARED =2; + + typedef unsigned short OTSPolicyValue; + const OTSPolicyValue REQUIRES = 1; + const OTSPolicyValue FORBIDS =2; + const OTSPolicyValue ADAPTS =3; + + typedef unsigned short NonTxTargetPolicyValue; + const NonTxTargetPolicyValue PREVENT = 0; + const NonTxTargetPolicyValue PERMIT = 1; + const CORBA::PolicyType INVOCATION_POLICY_TYPE = 55; + + interface InvocationPolicy : CORBA::Policy { + readonly attribute InvocationPolicyValue value; + }; + + const CORBA::PolicyType OTS_POLICY_TYPE = 56; + interface OTSPolicy : CORBA::Policy { + readonly attribute OTSPolicyValue value; + }; + + const CORBA::PolicyType NON_TX_TARGET_POLICY_TYPE = 57; + interface NonTxTargetPolicy : CORBA::Policy { + readonly attribute NonTxTargetPolicyValue value; + }; + +}; // End of CosTransactions Module diff --git a/omgapi/src/main/idl/Dynamic.idl b/omgapi/src/main/idl/Dynamic.idl new file mode 100644 index 000000000..ed1e74f50 --- /dev/null +++ b/omgapi/src/main/idl/Dynamic.idl @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// File: Dynamic.idl +// CORBA 3.0, Chapter 21 + +#ifndef _DYNAMIC_IDL_ +#define _DYNAMIC_IDL_ + +#pragma prefix "omg.org" +#include +#include + +module Dynamic { + + struct Parameter { + any argument; + CORBA::ParameterMode mode; + }; + + typedef sequence ParameterList; + typedef CORBA::StringSeq ContextList; + typedef sequence ExceptionList; + typedef CORBA::StringSeq RequestContext; + +}; // module Dynamic +#endif // _DYNAMIC_IDL_ diff --git a/omgapi/src/main/idl/DynamicAny.idl b/omgapi/src/main/idl/DynamicAny.idl new file mode 100644 index 000000000..835e98ef1 --- /dev/null +++ b/omgapi/src/main/idl/DynamicAny.idl @@ -0,0 +1,1265 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// IDL +// File: DynamicAny.idl + +#ifndef _DYNAMIC_ANY_IDL_ +#define _DYNAMIC_ANY_IDL_ + +#pragma prefix "omg.org" +#include + +/** +* An any can be passed to a program that doesn't have any static information for the +type of the any (code generated for the type by an IDL compiler has not been +compiled with the object implementation). As a result, the object receiving the any +does not have a portable method of using it. +

DynAnys enable traversal of the data value associated with an any at +runtime and extraction of the primitive constituents of the data value. This is especially +helpful for writing powerful generic servers (bridges, event channels supporting +filtering). +

Similarly, this facility enables the construction of an any at runtime, without having +static knowledge of its type. This is especially helpful for writing generic clients +(bridges, browsers, debuggers, user interface tools). +*/ +module DynamicAny { + /** + * Any values can be dynamically interpreted (traversed) and constructed through DynAny objects. + * A DynAny object is associated with a data value which corresponds to a copy of the value + * inserted into an any. + *

A DynAny object may be viewed as an ordered collection of component DynAnys. + * For DynAnys representing a basic type, such as long, or a type without components, + * such as an empty exception, the ordered collection of components is empty. + * Each DynAny object maintains the notion of a current position into its collection + * of component DynAnys. The current position is identified by an index value that runs + * from 0 to n-1, where n is the number of components. + * The special index value -1 indicates a current position that points nowhere. + * For values that cannot have a current position (such as an empty exception), + * the index value is fixed at -1. + * If a DynAny is initialized with a value that has components, the index is initialized to 0. + * After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode + * that permits components), the current position depends on the type of value represented by + * the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny + * gets default values for its components.) + *

The iteration operations rewind, seek, and next can be used to change the current position + * and the current_component operation returns the component at the current position. + * The component_count operation returns the number of components of a DynAny. + * Collectively, these operations enable iteration over the components of a DynAny, for example, + * to (recursively) examine its contents. + *

A constructed DynAny object is a DynAny object associated with a constructed type. + * There is a different interface, inheriting from the DynAny interface, associated with + * each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, + * exception, and value type). + *

A constructed DynAny object exports operations that enable the creation of new DynAny objects, + * each of them associated with a component of the constructed data value. + * As an example, a DynStruct is associated with a struct value. This means that the DynStruct + * may be seen as owning an ordered collection of components, one for each structure member. + * The DynStruct object exports operations that enable the creation of new DynAny objects, + * each of them associated with a member of the struct. + *

If a DynAny object has been obtained from another (constructed) DynAny object, + * such as a DynAny representing a structure member that was created from a DynStruct, + * the member DynAny is logically contained in the DynStruct. + * Calling an insert or get operation leaves the current position unchanged. + * Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny) + * also destroys any component DynAny objects obtained from it. + * Destroying a non-top level DynAny object does nothing. + * Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST. + * If the programmer wants to destroy a DynAny object but still wants to manipulate some component + * of the data value associated with it, then he or she should first create a DynAny for the component + * and, after that, make a copy of the created DynAny object. + *

The behavior of DynAny objects has been defined in order to enable efficient implementations + * in terms of allocated memory space and speed of access. DynAny objects are intended to be used + * for traversing values extracted from anys or constructing values of anys at runtime. + * Their use for other purposes is not recommended. + *

Insert and get operations are necessary to handle basic DynAny objects + * but are also helpful to handle constructed DynAny objects. + * Inserting a basic data type value into a constructed DynAny object + * implies initializing the current component of the constructed data value + * associated with the DynAny object. For example, invoking insert_boolean on a + * DynStruct implies inserting a boolean data value at the current position + * of the associated struct data value. + * A type is consistent for inserting or extracting a value if its TypeCode is equivalent to + * the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode + * of the DynAny at the current position. + *

DynAny and DynAnyFactory objects are intended to be local to the process in which they are + * created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported + * to other processes, or externalized with ORB.object_to_string(). + * If any attempt is made to do so, the offending operation will raise a MARSHAL system exception. + * Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard + * org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object + * interface may raise the standard NO_IMPLEMENT exception. + * An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception. + */ + interface DynAny { + #pragma sun_localservant DynAny "" + exception InvalidValue {}; + exception TypeMismatch {}; + + /** + * Returns the TypeCode associated with this DynAny object. + * A DynAny object is created with a TypeCode value assigned to it. + * This TypeCode value determines the type of the value handled through the DynAny object. + * Note that the TypeCode associated with a DynAny object is initialized at the time the + * DynAny is created and cannot be changed during lifetime of the DynAny object. + * + * @return The TypeCode associated with this DynAny object + */ + CORBA::TypeCode type(); + + /** + * Initializes the value associated with a DynAny object with the value + * associated with another DynAny object. + * The current position of the target DynAny is set to zero for values that have components + * and to -1 for values that do not have components. + * + * @param dyn_any + * @exception TypeMismatch if the type of the passed DynAny is not equivalent to the type of target DynAny + */ + void assign(in DynAny dyn_any) + raises(TypeMismatch); + + /** + * Initializes the value associated with a DynAny object with the value contained in an any. + * The current position of the target DynAny is set to zero for values that have components + * and to -1 for values that do not have components. + * + * @exception TypeMismatch if the type of the passed Any is not equivalent to the type of target DynAny + * @exception InvalidValue if the passed Any does not contain a legal value (such as a null string) + */ + void from_any(in any value) + raises(TypeMismatch, InvalidValue); + + /** + * Creates an any value from a DynAny object. + * A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. + * The value associated with the DynAny object is copied into the any. + * + * @return a new Any object with the same value and TypeCode + */ + any to_any(); + + /** + * Compares two DynAny values for equality. + * Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys + * have equal values. + * The current position of the two DynAnys being compared has no effect on the result of equal. + * + * @return true of the DynAnys are equal, false otherwise + */ + boolean equal(in DynAny dyn_any); + + /** + * Destroys a DynAny object. + * This operation frees any resources used to represent the data value associated with a DynAny object. + * It must be invoked on references obtained from one of the creation operations on the ORB interface + * or on a reference returned by DynAny.copy() to avoid resource leaks. + * Invoking destroy on component DynAny objects (for example, on objects returned by the + * current_component operation) does nothing. + * Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. + * That is, references to components of a destroyed DynAny become invalid. + * Invocations on such references raise OBJECT_NOT_EXIST. + * It is possible to manipulate a component of a DynAny beyond the life time of the DynAny + * from which the component was obtained by making a copy of the component with the copy operation + * before destroying the DynAny from which the component was obtained. + */ + void destroy(); + + /** + * Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. + * The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, + * such as DynStruct, creates the derived type but returns its reference as the DynAny base type. + * + * @return a deep copy of the DynAny object + */ + DynAny copy(); + + /** + * Inserts a boolean value into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_boolean(in boolean value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_octet(in octet value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a char value into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_char(in char value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a short value into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_short(in short value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_ushort(in unsigned short value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_long(in long value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_ulong(in unsigned long value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a float value into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_float(in float value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a double value into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_double(in double value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a string value into the DynAny. + * Both bounded and unbounded strings are inserted using this method. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception InvalidValue if the string inserted is longer than the bound of a bounded string + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_string(in string value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a reference to a CORBA object into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_reference(in Object value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a TypeCode object into the DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_typecode(in CORBA::TypeCode value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_longlong(in long long value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a long value into the DynAny. + * The IDL unsigned long long data type is mapped to the Java long data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_ulonglong(in unsigned long long value) + raises(TypeMismatch, InvalidValue); + +// void insert_longdouble(in long double value) +// raises(TypeMismatch, InvalidValue); + + /** + * Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_wchar(in wchar value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a string value into the DynAny. + * Both bounded and unbounded strings are inserted using this method. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception InvalidValue if the string inserted is longer than the bound of a bounded string + */ + void insert_wstring(in wstring value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts an Any value into the Any represented by this DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_any(in any value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_dyn_any(in DynAny value) + raises(TypeMismatch, InvalidValue); + + /** + * Inserts a reference to a Serializable object into this DynAny. + * The IDL ValueBase type is mapped to the Java Serializable type. + * + * @exception InvalidValue if this DynAny has components but has a current position of -1 + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + void insert_val(in ValueBase value) + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the boolean value from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + boolean get_boolean() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + octet get_octet() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the char value from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + char get_char() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the short value from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + short get_short() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + unsigned short get_ushort() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + long get_long() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + unsigned long get_ulong() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the float value from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + float get_float() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the double value from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + double get_double() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the string value from this DynAny. + * Both bounded and unbounded strings are extracted using this method. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + string get_string() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the reference to a CORBA Object from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + Object get_reference() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the TypeCode object from this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + CORBA::TypeCode get_typecode() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + long long get_longlong() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the long value from this DynAny. + * The IDL unsigned long long data type is mapped to the Java long data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + unsigned long long get_ulonglong() + raises(TypeMismatch, InvalidValue); +// long double get_longdouble() +// raises(TypeMismatch, InvalidValue); + + /** + * Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + wchar get_wchar() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the string value from this DynAny. + * Both bounded and unbounded strings are extracted using this method. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + */ + wstring get_wstring() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts an Any value contained in the Any represented by this DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + any get_any() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped + * into a new DynAny. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + DynAny get_dyn_any() + raises(TypeMismatch, InvalidValue); + + /** + * Extracts a Serializable object from this DynAny. + * The IDL ValueBase type is mapped to the Java Serializable type. + * + * @exception TypeMismatch if the accessed component in the DynAny is of a type + * that is not equivalent to the requested type. + * @exception TypeMismatch if called on a DynAny whose current component itself has components + * @exception InvalidValue if this DynAny has components but has a current position of -1 + */ + ValueBase get_val() + raises(TypeMismatch, InvalidValue); + + /** + * Sets the current position to index. The current position is indexed 0 to n-1, that is, + * index zero corresponds to the first component. The operation returns true if the resulting + * current position indicates a component of the DynAny and false if index indicates + * a position that does not correspond to a component. + * Calling seek with a negative index is legal. It sets the current position to -1 to indicate + * no component and returns false. Passing a non-negative index value for a DynAny that does not + * have a component at the corresponding position sets the current position to -1 and returns false. + */ + boolean seek(in long index); + + /** + * Is equivalent to seek(0). + */ + void rewind(); + + /** + * Advances the current position to the next component. + * The operation returns true while the resulting current position indicates a component, false otherwise. + * A false return value leaves the current position at -1. + * Invoking next on a DynAny without components leaves the current position at -1 and returns false. + */ + boolean next(); + + /** + * Returns the number of components of a DynAny. + * For a DynAny without components, it returns zero. + * The operation only counts the components at the top level. + * For example, if component_count is invoked on a DynStruct with a single member, + * the return value is 1, irrespective of the type of the member. + *

    + *
  • For sequences, the operation returns the current number of elements. + *
  • For structures, exceptions, and value types, the operation returns the number of members. + *
  • For arrays, the operation returns the number of elements. + *
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, + * otherwise, it returns 1. + *
  • For DynFixed and DynEnum, the operation returns zero. + *
+ */ + unsigned long component_count(); + + /** + * Returns the DynAny for the component at the current position. + * It does not advance the current position, so repeated calls to current_component + * without an intervening call to rewind, next, or seek return the same component. + * The returned DynAny object reference can be used to get/set the value of the current component. + * If the current component represents a complex type, the returned reference can be narrowed + * based on the TypeCode to get the interface corresponding to the to the complex type. + * Calling current_component on a DynAny that cannot have components, + * such as a DynEnum or an empty exception, raises TypeMismatch. + * Calling current_component on a DynAny whose current position is -1 returns a nil reference. + * The iteration operations, together with current_component, can be used + * to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, + * current_component and next can be used to initialize all the components of the value. + * Once the dynamic value is completely initialized, to_any creates the corresponding any value. + * + * @exception TypeMismatch If called on a DynAny that cannot have components, + * such as a DynEnum or an empty exception + */ + DynAny current_component() + raises(TypeMismatch); + }; + + /** + * DynFixed objects support the manipulation of IDL fixed values. + * Because IDL does not have a generic type that can represent fixed types with arbitrary + * number of digits and arbitrary scale, the operations use the IDL string type. + */ + interface DynFixed : DynAny { + #pragma sun_localservant DynFixed "" + + /** + * Returns the value of a DynFixed. + */ + string get_value(); + + /** + * Sets the value of the DynFixed. + * The val string must contain a fixed string constant in the same format as used for IDL fixed-point literals. + * However, the trailing d or D is optional. The return value is true if val can be represented as the DynFixed + * without loss of precision. If val has more fractional digits than can be represented in the DynFixed, + * fractional digits are truncated and the return value is false. + * + * @exception TypeMismatch If val does not contain a valid fixed-point literal or contains extraneous + * characters other than leading or trailing white space + * @exception InvalidValue If val contains a value whose scale exceeds that of the DynFixed + * or is not initialized + */ + boolean set_value(in string val) + raises(TypeMismatch, InvalidValue); + }; + + /** + * DynEnum objects support the manipulation of IDL enumerated values. + * The current position of a DynEnum is always -1. + */ + interface DynEnum : DynAny { + #pragma sun_localservant DynEnum "" + + /** + * Returns the value of the DynEnum as an IDL identifier. + */ + string get_as_string(); + + /** + * Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter. + * + * @exception InvalidValue If value contains a string that is not a valid IDL identifier + * for the corresponding enumerated type + */ + void set_as_string(in string value) + raises(InvalidValue); + + /** + * Returns the value of the DynEnum as the enumerated value's ordinal value. + * Enumerators have ordinal values 0 to n-1, as they appear from left to right + * in the corresponding IDL definition. + */ + unsigned long get_as_ulong(); + + /** + * Sets the value of the DynEnum as the enumerated value's ordinal value. + * + * @exception InvalidValue If value contains a value that is outside the range of ordinal values + * for the corresponding enumerated type + */ + void set_as_ulong(in unsigned long value) + raises(InvalidValue); + }; + + typedef string FieldName; + + /** + * NameValuePairs associate a name with an Any object. + */ + struct NameValuePair { + /** + * The name associated with the Any. + */ + FieldName id; + /** + * The Any value associated with the name. + */ + any value; + }; + typedef sequence NameValuePairSeq; + + /** + * NameDynAnyPairs associate a name with an DynAny object. + */ + struct NameDynAnyPair { + /** + * The name associated with the DynAny. + */ + FieldName id; + /** + * The DynAny value associated with the name. + */ + DynAny value; + }; + typedef sequence NameDynAnyPairSeq; + + /** + * DynStruct objects support the manipulation of IDL struct and exception values. + * Members of the exceptions are handled in the same way as members of a struct. + */ + interface DynStruct : DynAny { + #pragma sun_localservant DynStruct "" + + /** + * Returns the name of the member at the current position. + * This operation may return an empty string since the TypeCode of the value being + * manipulated may not contain the names of members. + * + * @exception TypeMismatch if the DynStruct represents an empty exception. + * @exception InvalidValue if the current position does not indicate a member + */ + FieldName current_member_name() + raises(TypeMismatch, InvalidValue); + + /** + * Returns the TCKind associated with the member at the current position. + * + * @exception TypeMismatch if the DynStruct represents an empty exception. + * @exception InvalidValue if the current position does not indicate a member + */ + CORBA::TCKind current_member_kind() + raises(TypeMismatch, InvalidValue); + + /** + * Returns a sequence of NameValuePairs describing the name and the value of each member + * in the struct associated with a DynStruct object. + * The sequence contains members in the same order as the declaration order of members + * as indicated by the DynStruct's TypeCode. The current position is not affected. + * The member names in the returned sequence will be empty strings if the DynStruct's TypeCode + * does not contain member names. + */ + NameValuePairSeq get_members(); + + /** + * Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs. + * The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, + * if an empty sequence is passed, the current position is set to -1. + *

Members must appear in the NameValuePairs in the order in which they appear in the IDL specification + * of the struct as indicated by the DynStruct's TypeCode or they must be empty strings. + * The operation makes no attempt to assign member values based on member names. + * + * @exception TypeMismatch if the member names supplied in the passed sequence do not match the + * corresponding member name in the DynStruct's TypeCode and they are not empty strings + * @exception InvalidValue if the passed sequence has a number of elements that disagrees + * with the number of members as indicated by the DynStruct's TypeCode + */ + void set_members(in NameValuePairSeq value) + raises(TypeMismatch, InvalidValue); + + /** + * Returns a sequence of NameDynAnyPairs describing the name and the value of each member + * in the struct associated with a DynStruct object. + * The sequence contains members in the same order as the declaration order of members + * as indicated by the DynStruct's TypeCode. The current position is not affected. + * The member names in the returned sequence will be empty strings if the DynStruct's TypeCode + * does not contain member names. + */ + NameDynAnyPairSeq get_members_as_dyn_any(); + + /** + * Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs. + * The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, + * if an empty sequence is passed, the current position is set to -1. + *

Members must appear in the NameDynAnyPairs in the order in which they appear in the IDL specification + * of the struct as indicated by the DynStruct's TypeCode or they must be empty strings. + * The operation makes no attempt to assign member values based on member names. + * + * @exception TypeMismatch if the member names supplied in the passed sequence do not match the + * corresponding member name in the DynStruct's TypeCode and they are not empty strings + * @exception InvalidValue if the passed sequence has a number of elements that disagrees + * with the number of members as indicated by the DynStruct's TypeCode + */ + void set_members_as_dyn_any(in NameDynAnyPairSeq value) + raises(TypeMismatch, InvalidValue); + }; + + /** + * DynUnion objects support the manipulation of IDL unions. + * A union can have only two valid current positions: + *

    + *
  • zero, which denotes the discriminator + *
  • one, which denotes the active member + *
+ * The component_count value for a union depends on the current discriminator: + * it is 2 for a union whose discriminator indicates a named member, and 1 otherwise. + */ + interface DynUnion : DynAny { + #pragma sun_localservant DynUnion "" + + /** + * Returns the current discriminator value. + */ + DynAny get_discriminator(); + + /** + * Sets the discriminator of the DynUnion to the specified value. + * Setting the discriminator to a value that is consistent with the currently active union member + * does not affect the currently active member. Setting the discriminator to a value that is inconsistent + * with the currently active member deactivates the member and activates the member that is consistent + * with the new discriminator value (if there is a member for that value) by initializing the member + * to its default value. + * Setting the discriminator of a union sets the current position to 0 if the discriminator value + * indicates a non-existent union member (has_no_active_member returns true in this case). + * Otherwise, if the discriminator value indicates a named union member, the current position is set to 1 + * (has_no_active_member returns false and component_count returns 2 in this case). + * + * @exception TypeMismatch if the TypeCode of the parameter is not equivalent to the TypeCode + * of the union???s discriminator + */ + void set_discriminator(in DynAny d) + raises(TypeMismatch); + + /** + * Sets the discriminator to a value that is consistent with the value of the default case of a union. + * It sets the current position to zero and causes component_count to return 2. + * + * @exception TypeMismatch if the union does not have an explicit default case + */ + void set_to_default_member() + raises(TypeMismatch); + + /** + * Sets the discriminator to a value that does not correspond to any of the unions case labels. + * It sets the current position to zero and causes component_count to return 1. + * + * @exception TypeMismatch if the union has an explicit default case or if it uses the entire range + * of discriminator values for explicit case labels + */ + void set_to_no_active_member() + raises(TypeMismatch); + + /** + * Returns true if the union has no active member, that is, the unions value consists solely + * of its discriminator because the discriminator has a value that is not listed as an explicit case label. + * Calling this operation on a union that has a default case returns false. + * Calling this operation on a union that uses the entire range of discriminator values + * for explicit case labels returns false. + */ + boolean has_no_active_member(); + + /** + * Returns the TCKind value of the discriminators TypeCode. + */ + CORBA::TCKind discriminator_kind(); + + /** + * Returns the TCKind value of the currently active members TypeCode. + * + * @exception InvalidValue if the union does not have a currently active member + */ + CORBA::TCKind member_kind() + raises(InvalidValue); + + /** + * Returns the currently active member. Note that the returned reference remains valid only + * for as long as the currently active member does not change. Using the returned reference + * beyond the life time of the currently active member raises OBJECT_NOT_EXIST. + * + * @exception InvalidValue if the union has no active member + */ + DynAny member() + raises(InvalidValue); + + /** + * Returns the name of the currently active member. If the unions TypeCode does not contain + * a member name for the currently active member, the operation returns an empty string. + * + * @exception InvalidValue if the union has no active member + */ + FieldName member_name() + raises(InvalidValue); + }; + + typedef sequence AnySeq; + typedef sequence DynAnySeq; + + /** + * DynSequence objects support the manipulation of IDL sequences. + */ + interface DynSequence : DynAny { + #pragma sun_localservant DynSequence "" + + /** + * Returns the current length of the sequence. + */ + unsigned long get_length(); + + /** + * Sets the length of the sequence. + * Increasing the length of a sequence adds new elements at the tail without affecting the values + * of already existing elements. Newly added elements are default-initialized. + * Increasing the length of a sequence sets the current position to the first newly-added element + * if the previous current position was -1. Otherwise, if the previous current position was not -1, + * the current position is not affected. + * Decreasing the length of a sequence removes elements from the tail without affecting the value + * of those elements that remain. The new current position after decreasing the length of a sequence + * is determined as follows: + *
    + *
  • If the length of the sequence is set to zero, the current position is set to -1. + *
  • If the current position is -1 before decreasing the length, it remains at -1. + *
  • If the current position indicates a valid element and that element is not removed when the length + * is decreased, the current position remains unaffected. + *
  • If the current position indicates a valid element and that element is removed, + * the current position is set to -1. + *
+ * + * @exception InvalidValue if this is a bounded sequence and len is larger than the bound + */ + void set_length(in unsigned long len) + raises(InvalidValue); + + /** + * Returns the elements of the sequence. + */ + AnySeq get_elements(); + + /** + * Sets the elements of a sequence. + * The length of the DynSequence is set to the length of value. The current position is set to zero + * if value has non-zero length and to -1 if value is a zero-length sequence. + * + * @exception TypeMismatch if value contains one or more elements whose TypeCode is not equivalent + * to the element TypeCode of the DynSequence + * @exception InvalidValue if the length of value exceeds the bound of a bounded sequence + */ + void set_elements(in AnySeq value) + raises(TypeMismatch, InvalidValue); + + /** + * Returns the DynAnys representing the elements of the sequence. + */ + DynAnySeq get_elements_as_dyn_any(); + + /** + * Sets the elements of a sequence using DynAnys. + * The length of the DynSequence is set to the length of value. The current position is set to zero + * if value has non-zero length and to -1 if value is a zero-length sequence. + * + * @exception TypeMismatch if value contains one or more elements whose TypeCode is not equivalent + * to the element TypeCode of the DynSequence + * @exception InvalidValue if the length of value exceeds the bound of a bounded sequence + */ + void set_elements_as_dyn_any(in DynAnySeq value) + raises(TypeMismatch, InvalidValue); + }; + + /** + * DynArray objects support the manipulation of IDL arrays. + * Note that the dimension of the array is contained in the TypeCode which is accessible + * through the type attribute. It can also be obtained by calling the component_count operation. + */ + interface DynArray : DynAny { + #pragma sun_localservant DynArray "" + + /** + * Returns the elements of the DynArray. + */ + AnySeq get_elements(); + + /** + * Sets the DynArray to contain the passed elements. + * + * @exception TypeMismatch if one or more elements have a type that is inconsistent with the DynArrays TypeCode + * @exception InvalidValue if the sequence does not contain the same number of elements as the array dimension + */ + void set_elements(in AnySeq value) + raises(TypeMismatch, InvalidValue); + + /** + * Returns the elements of the DynArray as DynAnys. + */ + DynAnySeq get_elements_as_dyn_any(); + + /** + * Sets the DynArray to contain the passed elements. + * + * @exception TypeMismatch if one or more elements have a type that is inconsistent with the DynArrays TypeCode + * @exception InvalidValue if the sequence does not contain the same number of elements as the array dimension + */ + void set_elements_as_dyn_any(in DynAnySeq value) + raises(TypeMismatch, InvalidValue); + }; + + /** + * DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces. + */ + interface DynValueCommon : DynAny { + /** + * Returns true if the DynValueCommon represents a null value type. + */ + boolean is_null(); + + /** + * Changes the representation of a DynValueCommon to a null value type. + */ + void set_to_null(); + + /** + * Replaces a null value type with a newly constructed value. Its components are initialized + * to default values as in DynAnyFactory.create_dyn_any_from_type_code. + * If the DynValueCommon represents a non-null value type, then this operation has no effect. + */ + void set_to_value(); + }; + + /** + * DynValue objects support the manipulation of IDL non-boxed value types. + * The DynValue interface can represent both null and non-null value types. + * For a DynValue representing a non-null value type, the DynValue's components comprise + * the public and private members of the value type, including those inherited from concrete base value types, + * in the order of definition. A DynValue representing a null value type has no components + * and a current position of -1. + *

Warning: Indiscriminantly changing the contents of private value type members can cause the value type + * implementation to break by violating internal constraints. Access to private members is provided to support + * such activities as ORB bridging and debugging and should not be used to arbitrarily violate + * the encapsulation of the value type. + */ + interface DynValue : DynValueCommon { + #pragma sun_localservant DynValue "" + + /** + * Returns the name of the member at the current position. + * This operation may return an empty string since the TypeCode of the value being + * manipulated may not contain the names of members. + * + * @exception TypeMismatch if the DynValue represents a null value type. + * @exception InvalidValue if the current position does not indicate a member + */ + FieldName current_member_name() + raises(TypeMismatch, InvalidValue); + + /** + * Returns the TCKind associated with the member at the current position. + * + * @exception TypeMismatch if the DynValue represents a null value type. + * @exception InvalidValue if the current position does not indicate a member + */ + CORBA::TCKind current_member_kind() + raises(TypeMismatch, InvalidValue); + + /** + * Returns a sequence of NameValuePairs describing the name and the value of each member + * in the value type. + * The sequence contains members in the same order as the declaration order of members + * as indicated by the DynValue's TypeCode. The current position is not affected. + * The member names in the returned sequence will be empty strings if the DynValue's TypeCode + * does not contain member names. + * + * @exception InvalidValue if this object represents a null value type + */ + NameValuePairSeq get_members() + raises(InvalidValue); + + /** + * Initializes the value type's members from a sequence of NameValuePairs. + * The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, + * if an empty sequence is passed, the current position is set to -1. + * A null value type can be initialized to a non-null value type using this method. + *

Members must appear in the NameValuePairs in the order in which they appear in the IDL specification + * of the value type as indicated by the DynValue's TypeCode or they must be empty strings. + * The operation makes no attempt to assign member values based on member names. + * + * @exception TypeMismatch if the member names supplied in the passed sequence do not match the + * corresponding member name in the DynValue's TypeCode and they are not empty strings + * @exception InvalidValue if the passed sequence has a number of elements that disagrees + * with the number of members as indicated by the DynValue's TypeCode + */ + void set_members(in NameValuePairSeq value) + raises(TypeMismatch, InvalidValue); + + /** + * Returns a sequence of NameDynAnyPairs describing the name and the value of each member + * in the value type. + * The sequence contains members in the same order as the declaration order of members + * as indicated by the DynValue's TypeCode. The current position is not affected. + * The member names in the returned sequence will be empty strings if the DynValue's TypeCode + * does not contain member names. + * + * @exception InvalidValue if this object represents a null value type + */ + NameDynAnyPairSeq get_members_as_dyn_any() + raises(InvalidValue); + + /** + * Initializes the value type's members from a sequence of NameDynAnyPairs. + * The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, + * if an empty sequence is passed, the current position is set to -1. + * A null value type can be initialized to a non-null value type using this method. + *

Members must appear in the NameDynAnyPairs in the order in which they appear in the IDL specification + * of the value type as indicated by the DynValue's TypeCode or they must be empty strings. + * The operation makes no attempt to assign member values based on member names. + * + * @exception TypeMismatch if the member names supplied in the passed sequence do not match the + * corresponding member name in the DynValue's TypeCode and they are not empty strings + * @exception InvalidValue if the passed sequence has a number of elements that disagrees + * with the number of members as indicated by the DynValue's TypeCode + */ + void set_members_as_dyn_any(in NameDynAnyPairSeq value) + raises(TypeMismatch, InvalidValue); + }; + + /** + * DynValueBox objects support the manipulation of IDL boxed value types. + * The DynValueBox interface can represent both null and non-null value types. + * For a DynValueBox representing a non-null value type, the DynValueBox has a single component + * of the boxed type. A DynValueBox representing a null value type has no components + * and a current position of -1. + */ + interface DynValueBox : DynValueCommon { + + /** + * Returns the boxed value as an Any. + * + * @exception InvalidValue if this object represents a null value box type + */ + any get_boxed_value() + raises(InvalidValue); + + /** + * Replaces the boxed value with the specified value. + * If the DynBoxedValue represents a null valuetype, it is converted to a non-null value. + * + * @exception TypeMismatch if this object represents a non-null value box type and the type + * of the parameter is not matching the current boxed value type. + */ + void set_boxed_value(in any boxed) + raises(TypeMismatch); + + /** + * Returns the boxed value as a DynAny. + * + * @exception InvalidValue if this object represents a null value box type + */ + DynAny get_boxed_value_as_dyn_any() + raises(InvalidValue); + + /** + * Replaces the boxed value with the value contained in the parameter. + * If the DynBoxedValue represents a null valuetype, it is converted to a non-null value. + * + * @exception TypeMismatch if this object represents a non-null value box type and the type + * of the parameter is not matching the current boxed value type. + */ + void set_boxed_value_as_dyn_any(in DynAny boxed) + raises(TypeMismatch); + }; + + /** + * DynAny objects can be created by invoking operations on the DynAnyFactory object. + * Generally there are only two ways to create a DynAny object: + *

    + *
  • invoking an operation on an existing DynAny object + *
  • invoking an operation on a DynAnyFactory object + *
+ * A constructed DynAny object supports operations that enable the creation of new DynAny + * objects encapsulating access to the value of some constituent. + * DynAny objects also support the copy operation for creating new DynAny objects. + * A reference to the DynAnyFactory object is obtained by calling ORB.resolve_initial_references() + * with the identifier parameter set to the string constant "DynAnyFactory". + *

Dynamic interpretation of an any usually involves creating a DynAny object using create_dyn_any() + * as the first step. Depending on the type of the any, the resulting DynAny object reference can be narrowed + * to a DynFixed, DynStruct, DynSequence, DynArray, DynUnion, DynEnum, or DynValue object reference. + *

Dynamic creation of an any involves creating a DynAny object using create_dyn_any_from_type_code(), + * passing the TypeCode associated with the value to be created. The returned reference is narrowed to one of + * the complex types, such as DynStruct, if appropriate. Then, the value can be initialized by means of + * invoking operations on the resulting object. Finally, the to_any operation can be invoked + * to create an any value from the constructed DynAny. + */ + interface DynAnyFactory { + #pragma sun_localservant DynAnyFactory "" + exception InconsistentTypeCode {}; + + /** + * Creates a new DynAny object from an any value. + * A copy of the TypeCode associated with the any value is assigned to the resulting DynAny object. + * The value associated with the DynAny object is a copy of the value in the original any. + * The current position of the created DynAny is set to zero if the passed value has components, + * to -1 otherwise + * + * @exception InconsistentTypeCode if value has a TypeCode with a TCKind of tk_Principal, + * tk_native, or tk_abstract_interface + */ + DynAny create_dyn_any(in any value) + raises(InconsistentTypeCode); + + /** + * Creates a DynAny from a TypeCode. Depending on the TypeCode, the created object may be of type DynAny, + * or one of its derived types, such as DynStruct. The returned reference can be narrowed to the derived type. + * In all cases, a DynAny constructed from a TypeCode has an initial default value. + * The default values of basic types are: + *

    + *
  • false for boolean + *
  • zero for numeric types + *
  • zero for types octet, char, and wchar + *
  • the empty string for string and wstring + *
  • null for object references + *
  • a type code with a TCKind value of tk_null for type codes + *
  • for any values, an any containing a type code with a TCKind value of tk_null type and no value + *
+ * For complex types, creation of the corresponding DynAny assigns a default value as follows: + *
    + *
  • For DynSequence it sets the current position to -1 and creates an empty sequence. + *
  • For DynEnum it sets the current position to -1 and sets the value of the enumerator + * to the first enumerator value indicated by the TypeCode. + *
  • For DynFixed it sets the current position to -1 and sets the value zero. + *
  • For DynStruct it sets the current position to -1 for empty exceptions + * and to zero for all other TypeCodes. The members (if any) are (recursively) initialized + * to their default values. + *
  • For DynArray sets the current position to zero and (recursively) initializes elements + * to their default value. + *
  • For DynUnion sets the current position to zero. The discriminator value is set + * to a value consistent with the first named member of the union. That member is activated and (recursively) + * initialized to its default value. + *
  • For DynValue and DynValueBox it initializes to a null value. + *
+ */ + DynAny create_dyn_any_from_type_code(in CORBA::TypeCode type) + raises(InconsistentTypeCode); + }; +}; // module DynamicAny + +#endif // _DYNAMIC_ANY_IDL_ diff --git a/omgapi/src/main/idl/IOP.idl b/omgapi/src/main/idl/IOP.idl new file mode 100644 index 000000000..634b2b511 --- /dev/null +++ b/omgapi/src/main/idl/IOP.idl @@ -0,0 +1,602 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _IOP_IDL_ +#define _IOP_IDL_ + +#include "CORBAX.idl" + +#pragma prefix "omg.org" + +#ifndef CORBA3 +#define local +#endif + +module IOP { + // + // Standard Protocol Profile tag values + // + /** Profile ID */ + typedef unsigned long ProfileId; + + /** + * Identifies profiles that + * support the Internet Inter-ORB Protocol. The ProfileBody + * of this profile contains a CDR encapsulation of a structure + * containing addressing and object identification information used by + * IIOP. Version 1.1 of the TAG_INTERNET_IOP profile + * also includes an array of TaggedComponent objects that can + * contain additional information supporting optional IIOP features, + * ORB services such as security, and future protocol extensions. + *

+ * Protocols other than IIOP (such as ESIOPs and other GIOPs) can share + * profile information (such as object identity or security + * information) with IIOP by encoding their additional profile information + * as components in the TAG_INTERNET_IOP profile. All + * TAG_INTERNET_IOP profiles support IIOP, regardless of + * whether they also support additional protocols. Interoperable + * ORBs are not required to create or understand any other profile, + * nor are they required to create or understand any of the components + * defined for other protocols that might share the + * TAG_INTERNET_IOP profile with IIOP. + *

+ * The profile_data for the TAG_INTERNET_IOP + * profile is a CDR encapsulation of the IIOP.ProfileBody_1_1 + * type. + */ + const ProfileId TAG_INTERNET_IOP = 0; + + /** + * Indicates that the value encapsulated is of type + * MultipleComponentProfile. In this case, the profile + * consists of a list of protocol components, the use of which must + * be specified by the protocol using this profile. This profile may + * be used to carry IOR components. + *

+ * The profile_data for the + * TAG_MULTIPLE_COMPONENTS profile is a CDR encapsulation + * of the MultipleComponentProfile type shown above. + */ + const ProfileId TAG_MULTIPLE_COMPONENTS = 1; + + /** + * Object references have at least one tagged profile. Each profile + * supports one or more protocols and encapsulates all the basic + * information the protocols it supports need to identify an object. + * Any single profile holds enough information to drive a complete + * invocation using any of the protocols it supports; the content + * and structure of those profile entries are wholly specified by + * these protocols. + */ + struct TaggedProfile { + /** The tag, represented as a profile id. */ + ProfileId tag; + + /** The associated profile data. */ + sequence profile_data; + }; + + /** + * Captures information about a object references, such as whether the + * object is null, what type it is, what protocols are supported, and what + * ORB services are available. + *

+ * This data structure need not be used internally to any given ORB, + * and is not intended to be visible to application-level ORB programmers. + * It should be used only when crossing object reference domain + * boundaries, within bridges. + *

+ * This data structure is designed to be efficient in typical + * single-protocol configurations, while not penalizing multiprotocol ones. + *

+ * Object references have at least one tagged profile. Each profile + * supports one or more protocols and encapsulates all the basic + * information the protocols it supports need to identify an object. + * Any single profile holds enough information to drive a complete + * invocation using any of the protocols it supports; the content + * and structure of those profile entries are wholly specified by + * these protocols. A bridge between two domains may need to know the + * detailed content of the profile for those domains' profiles, + * depending on the technique it uses to bridge the domains. + *

+ * Each profile has a unique numeric tag, assigned by the OMG. + * Profile tags in the range 0x80000000 through 0xffffffff are reserved + * for future use, and are not currently available for assignment. + *

+ * Null object references are indicated by an empty set of profiles, + * and by a "Null" type ID (a string which contains only a single + * terminating character). A Null TypeID is the only + * mechanism that can be used to represent the type + * CORBA.Object. Type IDs may only be "Null" in any message, + * requiring the client to use existing knowledge or to consult the + * object, to determine interface types supported. The type ID + * is a Repository ID identifying the interface type, and is provided + * to allow ORBs to preserve strong typing. This identifier is agreed + * on within the bridge and, for reasons outside the scope of the + * interoperability specification, needs to have a much broader scope to + * address various problems in system evolution and maintenance. + * Type IDs support detection of type equivalence, and in conjunction + * with an Interface Repository, allow processes to reason about the + * relationship of the type of the object referred to and any other type. + *

+ * The type ID, if provided by the server, indicates the most derived + * type that the server wishes to publish, at the time the reference + * is generated. The object's actual most derived type may later change + * to a more derived type. Therefore, the type ID in the IOR can only + * be interpreted by the client as a hint that the object supports at + * least the indicated interface. The client can succeed in narrowing + * the reference to the indicated interface, or to one of its base + * interfaces, based solely on the type ID in the IOR, but must not fail + * to narrow the reference without consulting the object via the + * "_is_a" or "_get_interface" pseudo-operations. + */ + struct IOR { + /** The type id, represented as a String. */ + string type_id; + + /** + * An array of tagged profiles associated with this + * object reference. + */ + sequence profiles; + }; + + /** + * Standard way of representing multicomponent profiles. + * This would be encapsulated in a TaggedProfile. + */ + typedef unsigned long ComponentId; + + /** + * TaggedComponents contained in + * TAG_INTERNET_IOP and + * TAG_MULTIPLE_COMPONENTS profiles are identified by + * unique numeric tags using a namespace distinct form that is used for + * profile tags. Component tags are assigned by the OMG. + *

+ * Specifications of components must include the following information: + *

    + *
  • Component ID: The compound tag that is obtained + * from OMG.
  • + *
  • Structure and encoding: The syntax of the component + * data and the encoding rules. If the component value is + * encoded as a CDR encapsulation, the IDL type that is + * encapsulated and the GIOP version which is used for encoding + * the value, if different than GIOP 1.0, must be specified as + * part of the component definition.
  • + *
  • Semantics: How the component data is intended to be + * used.
  • + *
  • Protocols: The protocol for which the component is + * defined, and whether it is intended that the component be + * usable by other protocols.
  • + *
  • At most once: whether more than one instance of this + * component can be included in a profile.
  • + *
+ * Specification of protocols must describe how the components affect + * the protocol. The following should be specified in any protocol + * definition for each TaggedComponent that the protocol uses: + *
    + *
  • Mandatory presence: Whether inclusion of the component + * in profiles supporting the protocol is required (MANDATORY + * PRESENCE) or not required (OPTIONAL PRESENCE).
  • + *
  • Droppable: For optional presence component, whether + * component, if present, must be retained or may be dropped.
  • + *
+ */ + struct TaggedComponent { + /** The tag, represented as a component id. */ + ComponentId tag; + + /** The component data associated with the component id. */ + sequence component_data; + }; + + /** + * It is often useful in the real world to be able to identify the + * particular kind of ORB an object reference is coming from, to work + * around problems with that particular ORB, or exploit shared + * efficiencies. + *

+ * The TAG_ORB_TYPE component has an associated value of + * type unsigned long (Java long), encoded as a CDR encapsulation, + * designating an ORB type ID allocated by the OMG for the ORB type of the + * originating ORB. Anyone may register any ORB types by submitting + * a short (one-paragraph) description of the ORB type to the OMG, + * and will receive a new ORB type ID in return. A list of ORB type + * descriptions and values will be made available on the OMG web server. + *

+ * The TAG_ORB_TYPE component can appear at most once in + * any IOR profile. For profiles supporting IIOP 1.1 or greater, it + * is optionally present. + */ + const ComponentId TAG_ORB_TYPE = 0 ; + + /** + * The code set component of the IOR multi-component profile structure + * contains: + *

    + *
  • server's native char code set and conversion code sets, and
  • + *
  • server's native wchar code set and conversion code sets.
  • + *
+ * Both char and wchar conversion code sets are listed in order of + * preference. + */ + const ComponentId TAG_CODE_SETS = 1 ; + + /** + * A profile component containing the sequence of QoS policies exported + * with the object reference by an object adapter. + */ + const ComponentId TAG_POLICIES = 2 ; + + /** + * In cases where the same object key is used for more than one + * internet location, the following standard IOR Component is defined + * for support in IIOP version 1.2. + *

+ * The TAG_ALTERNATE_IIOP_ADDRESS component has an + * associated value of type: + * + *

+     *     struct { 
+     *         string HostID, 
+     *         short Port 
+     *     }; 
+     *   
+ * + * encoded as a CDR encapsulation. + *

+ * Zero or more instances of the TAG_ALTERNATE_IIOP_ADDRESS + * component type may be included in a version 1.2 + * TAG_INTERNET_IOP Profile. Each of these alternative + * addresses may be used by the client orb, in addition to the host + * and port address expressed in the body of the Profile. In cases + * where one or more TAG_ALTERNATE_IIOP_ADDRESS components + * are present in a TAG_INTERNET_IOP Profile, no order of + * use is prescribed by Version 1.2 of IIOP. + */ + const ComponentId TAG_ALTERNATE_IIOP_ADDRESS = 3 ; + + /** + * Class downloading is supported for stubs, ties, values, and + * value helpers. The specification allows transmission of codebase + * information on the wire for stubs and ties, and enables usage of + * pre-existing ClassLoaders when relevant. + *

+ * For values and value helpers, the codebase is transmitted after the + * value tag. For stubs and ties, the codebase is transmitted as + * the TaggedComponent TAG_JAVA_CODEBASE in the IOR + * profile, where the component_data is a CDR encapsulation + * of the codebase written as an IDL string. The codebase is a + * space-separated list of one or more URLs. + */ + const ComponentId TAG_JAVA_CODEBASE = 25 ; + + /** + * RMI-IIOP has multiple stream format versions. A server + * can specify its maximum version by including the + * TAG_RMI_CUSTOM_MAX_STREAM_FORMAT tagged component or + * rely on the default of version 1 for GIOP 1.2 and less + * and version 2 for GIOP 1.3 and higher. + * + * See Java to IDL ptc/02-01-12 1.4.11. + */ + const ComponentId TAG_RMI_CUSTOM_MAX_STREAM_FORMAT = 38 ; + + /** An array of tagged components, forming a multiple component profile. */ + typedef sequence MultipleComponentProfile; + + /** A service id, represented as an int */ + typedef unsigned long ServiceId; + + /** + * Service-specific information to be passed implicitly with requests + * and replies. Service contexts are composed of service ids and + * associated data. + */ + struct ServiceContext { + /** The service context id */ + ServiceId context_id; + + /** The data associated with this service context */ + sequence context_data; + }; + + /** An array of service contexts, forming a service context list. */ + typedef sequence ServiceContextList; + + /** + * Identifies a CDR encapsulation of the + * CosTSInteroperation.PropogationContext defined in + * CORBAservices: Common Object Services Specifications. + */ + const ServiceId TransactionService = 0; + + /** + * Identifies a CDR encapsulation of the + * CONV_FRAME.CodeSetContext defined in + * Section 13.10.2.5, "GIOP Code Set Service Context," on page 13-43. + */ + const ServiceId CodeSets = 1; + + /** + * Identifies a CDR encapsulation of the RMICustomMaxStreamFormat + * service context which contains a single byte specifying + * the client's maximum RMI-IIOP stream format version. + * + * See Java to IDL ptc/02-01-12 1.4.12. + */ + const ServiceId RMICustomMaxStreamFormat = 17 ; + + /** + * DCOM-CORBA Interworking uses three service contexts as defined in + * "DCOM-CORBA Interworking" in the "Interoperability with non-CORBA + * Systems" chapter. + *

+ * ChainBypassCheck carries a CDR encapsulation of the + * struct CosBridging.ChainBypassCheck. This is carried + * only in a Request message as described in Section 20.9.1, "CORBA + * Chain Bypass," on page 20-19. + */ + const ServiceId ChainBypassCheck = 2; + + /** + * DCOM-CORBA Interworking uses three service contexts as defined in + * "DCOM-CORBA Interworking" in the "Interoperability with non-CORBA + * Systems" chapter. + *

+ * ChainBypassInfo carries a CDR encapsulation of the + * struct CosBridging.ChainBypassInfo. This is carried + * only in a Reply message as described in Section 20.9.1, "CORBA Chain + * Bypass," on page 20-19. + */ + const ServiceId ChainBypassInfo = 3; + + /** + * DCOM-CORBA Interworking uses three service contexts as defined in + * "DCOM-CORBA Interworking" in the "Interoperability with non-CORBA + * Systems" chapter. + *

+ * LogicalThreadId, carries a CDR encapsulation of + * the struct CosBridging.LogicalThreadId as described + * in Section 20.10, "Thread Identification," on page 20-21. + */ + const ServiceId LogicalThreadId = 4; + + /** + * Identifies a CDR encapsulation of the + * IIOP.BiDirIIOPServiceContext defined in Section 15.8, + * "Bi-Directional GIOP," on page 15-55. + */ + const ServiceId BI_DIR_IIOP = 5; + + /** + * Identifies a CDR encapsulation of the IOR of the + * SendingContext.RunTime object (see Section 5.6, "Access + * to the Sending Context Run Time," on page 5-15). + */ + const ServiceId SendingContextRunTime = 6; + + /** + * For information on INVOCATION_POLICIES refer to the + * Asynchronous Messaging specification - orbos/98-05-05. + */ + const ServiceId INVOCATION_POLICIES = 7; + + /** + * For information on FORWARDED_IDENTITY refer to the + * Firewall specification - orbos/98-05-04. + */ + const ServiceId FORWARDED_IDENTITY = 8; + + /** + * Identifies a CDR encapsulation of a marshaled instance of a + * java.lang.Throwable or one of its subclasses as described in Java + * to IDL Language Mapping, Section 1.4.8.1, "Mapping of + * UnknownExceptionInfo Service Context," on page 1-32. + */ + const ServiceId UnknownExceptionInfo = 9; + + /** + * CORBA formal/02-06-01: 13.7.1: + * ExceptionDetailMessage identifies a CDR encapsulation of a wstring, + * encoded using GIOP 1.2 with a TCS-W of UTF-16. This service context + * may be sent on Reply messages with a reply_status of SYSTEM_EXCEPTION + * or USER_EXCEPTION. The usage of this service context is defined + * by language mappings.

+ * + * IDL/Java: ptc/02-01-22: 1.15.2: + * When a System Exception is marshaled, its GIOP Reply message shall + * include an associated ExceptionDetailMessage service context. The + * callee's stack trace is often very valuable debugging information but + * may contain sensitive or unwanted information. The wstring within the + * service context will therefore contain additional information relating + * to the exception, for example the result of calling either + * printStackTrace(PrintWriter) or getMessage() on the exception. When + * unmarshaling a System Exception on the client side, the wstring from + * any ExceptionDetailMessage service context shall become the Java error + * message in the unmarshaled exception object. + */ + const ServiceId ExceptionDetailMessage = 14; + + + // BEGIN part which lived in Interceptors.idl. + + /** + * An array of TaggedComponent objects. + */ + typedef sequence TaggedComponentSeq; + + /** + * The formats of IOR components and service context data used by ORB + * services are often defined as CDR encapsulations encoding instances + * of IDL defined data types. The Codec provides a mechanism + * to transfer these components between their IDL data types and their CDR + * encapsulation representations. + *

+ * A Codec is obtained from the CodecFactory. + * The CodecFactory is obtained through a call to + * ORB.resolve_initial_references( "CodecFactory" ). + */ + local interface Codec { + + /** + * This exception is thrown by Codec.encode or + * Codec.encode_value when the type is invalid for the + * encoding. For example, this exception is thrown if the encoding is + * ENCODING_CDR_ENCAPS version 1.0 and a type + * that does not exist in that version, such as wstring, + * is passed to the operation. + */ + exception InvalidTypeForEncoding {}; + + /** + * This exception is thrown by Codec.decode or + * Codec.decode_value when the data in the byte array + * cannot be decoded into an Any. + */ + exception FormatMismatch {}; + + /** + * This exception is thrown by decode_value when the given + * TypeCode does not match the given byte array. + */ + exception TypeMismatch {}; + + /** + * Converts the given any into a byte array based on the encoding + * format effective for this Codec. + * + * @param data The data, in the form of an any, to be encoded into + * a byte array. + * @return A byte array containing the encoded Any. This byte array + * contains both the TypeCode and the data of the type. + * @exception InvalidTypeForEncoding thrown if the type is not valid for + * the encoding format effective for this Codec. + */ + CORBA::OctetSeq encode (in any data) + raises (InvalidTypeForEncoding); + + /** + * Decodes the given byte array into an Any based on the encoding + * format effective for this Codec. + * + * @param data The data, in the form of a byte array, to be decoded into + * an Any. + * @return An Any containing the data from the decoded byte array. + * @exception FormatMismatch is thrown if the byte array cannot be + * decoded into an Any. + */ + any decode (in CORBA::OctetSeq data) raises (FormatMismatch); + + /** + * Converts the given any into a byte array based on the encoding + * format effective for this Codec. Only the data from the Any is + * encoded, not the TypeCode. + * + * @param data The data, in the form of an Any, to be encoded into + * a byte array. + * @return A byte array containing the data from the encoded any. + * @exception InvalidTypeForEncoding thrown if the type is not valid for + * the encoding format effective for this Codec. + */ + CORBA::OctetSeq encode_value (in any data) + raises (InvalidTypeForEncoding); + + /** + * Decodes the given byte array into an Any based on the given + * TypeCode and the encoding format effective for + * this Codec. + * + * @param data The data, in the form of a byte array, to be decoded + * into an Any. + * @param tc The TypeCode to be used to decode the data. + * @return An Any containing the data from the decoded byte array. + * @exception FormatMismatch thrown if the byte array cannot be + * decoded into an Any. + */ + any decode_value (in CORBA::OctetSeq data, in CORBA::TypeCode tc) + raises (FormatMismatch, TypeMismatch); + }; + + /** + * Defines an encoding format of a Codec, such as + * CDR Encapsulation (ENCODING_CDR_ENCAPS). + */ + typedef short EncodingFormat; + + /** + * The CDR Encapsulation encoding. + * @see CodecFactory + */ + const EncodingFormat ENCODING_CDR_ENCAPS = 0; + + /** + * Defines the encoding format of a Codec. This class + * details the encoding format, such as CDR Encapsulation encoding, and + * the major and minor versions of that format. + *

+ * The encodings currently supported are: + *

    + *
  • ENCODING_CDR_ENCAPS, version 1.0;
  • + *
  • ENCODING_CDR_ENCAPS, version 1.1;
  • + *
  • ENCODING_CDR_ENCAPS, version 1.2;
  • + *
  • ENCODING_CDR_ENCAPS for all future versions of GIOP as + * they arise.
  • + *
+ * Vendors are free to support additional encodings. + * + * @see ENCODING_CDR_ENCAPS + */ + struct Encoding { + /** + * The encoding format. + */ + EncodingFormat format; + + /** + * The major version of this Encoding format. + */ + octet major_version; + + /** + * The minor version of this Encoding format. + */ + octet minor_version; + }; + + /** + * Codecs are obtained from the CodecFactory. + * The CodecFactory is obtained through a call to + * ORB.resolve_initial_references( "CodecFactory" ). + */ + local interface CodecFactory { + /** + * This exception is thrown by CodecFactory.create_codec when + * the factory cannot create a Codec for a given encoding. + */ + exception UnknownEncoding {}; + + /** + * Create a Codec of the given encoding. + *

+ * @param enc The encoding for which to create a Codec. + * @return A Codec obtained with the given encoding. + * @exception UnknownEncoding thrown if this factory cannot create a + * Codec of the given encoding. + */ + Codec create_codec (in Encoding enc) raises (UnknownEncoding); + }; + + // END part which lived in Interceptors.idl. + +}; + +#endif // _IOP_IDL_ diff --git a/omgapi/src/main/idl/Interceptors.idl b/omgapi/src/main/idl/Interceptors.idl new file mode 100644 index 000000000..351c8580f --- /dev/null +++ b/omgapi/src/main/idl/Interceptors.idl @@ -0,0 +1,1981 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Differences from original: + * + * - do not include orb.idl + * - include IOP.idl, Messaging.idl and CORBAX.idl + * - renamed component parameter names to tagged_component (so that they + * do not conflict with the CORBA 3.0 "component" keyword). + * - javadocs added (synchronized with orbos/00-08-06) + * + * NOTE: After compilation of this IDL file, all Helper and Holder classes + * that are not needed are removed. + */ +#include "IOP.idl" +#include "Messaging.idl" +#include "CORBAX.idl" +#include "corba.idl" + +#pragma prefix "omg.org" + +#ifndef CORBA3 +#define local +#endif + + +module PortableInterceptor { + /** + * All Portable Interceptors implement Interceptor. + */ + local interface Interceptor { + /** + * Returns the name of the interceptor. + *

+ * Each Interceptor may have a name that may be used administratively + * to order the lists of Interceptors. Only one Interceptor of a given + * name can be registered with the ORB for each Interceptor type. An + * Interceptor may be anonymous, i.e., have an empty string as the name + * attribute. Any number of anonymous Interceptors may be registered with + * the ORB. + * + * @return the name of the interceptor. + */ + readonly attribute string name; + + // Added in ptc/00-08-06 + /** + * Provides an opportunity to destroy this interceptor. + * The destroy method is called during ORB.destroy. When an + * application calls ORB.destroy, the ORB: + *

    + *
  1. waits for all requests in progress to complete
  2. + *
  3. calls the Interceptor.destroy operation for each + * interceptor
  4. + *
  5. completes destruction of the ORB
  6. + *
+ * Method invocations from within Interceptor.destroy on + * object references for objects implemented on the ORB being destroyed + * result in undefined behavior. However, method invocations on objects + * implemented on an ORB other than the one being destroyed are + * permitted. (This means that the ORB being destroyed is still capable + * of acting as a client, but not as a server.) + */ + void destroy(); + }; + + + /** + * The ForwardRequest exception is the means by which an + * Interceptor can indicate to the ORB that a retry of the request should + * occur with the new object given in the exception. This behavior of + * causing a retry only occurs if the ORB receives a ForwardRequest from + * an interceptor. If ForwardRequest is thrown anywhere else + * it is passed through the ORB as is normal for a user exception. + *

+ * If an Interceptor throws a ForwardRequest exception in + * response to a call of an interceptor, no other Interceptors are called + * for that interception point. The remaining Interceptors in the Flow Stack + * shall have their appropriate ending interception point called: + * receive_other on the client, or send_other on + * the server. The reply_status in the + * receive_other or send_other would be + * LOCATION_FORWARD. + */ + exception ForwardRequest { + /** + * The new object to forward the request to. + */ + Object forward; +// Change in ptc/00-08-06 +// boolean permanent; + }; + + /** Reply status, represented as an int */ + typedef short ReplyStatus; + + // Valid reply_status values: + + /** + * Indicates a successful Reply Status. One possible value for + * RequestInfo.reply_status. + * @see RequestInfo#reply_status + * @see SYSTEM_EXCEPTION + * @see USER_EXCEPTION + * @see LOCATION_FORWARD + * @see TRANSPORT_RETRY + */ + const ReplyStatus SUCCESSFUL = 0; + + /** + * Indicates a SystemException reply status. One possible value for + * RequestInfo.reply_status. + * @see RequestInfo#reply_status + * @see SUCCESSFUL + * @see USER_EXCEPTION + * @see LOCATION_FORWARD + * @see TRANSPORT_RETRY + */ + const ReplyStatus SYSTEM_EXCEPTION = 1; + + /** + * Indicates a UserException reply status. One possible value for + * RequestInfo.reply_status. + * @see RequestInfo#reply_status + * @see SUCCESSFUL + * @see SYSTEM_EXCEPTION + * @see LOCATION_FORWARD + * @see TRANSPORT_RETRY + */ + const ReplyStatus USER_EXCEPTION = 2; + + /** + * Indicates a LocationForward reply status. One possible value for + * RequestInfo.reply_status. + * @see RequestInfo#reply_status + * @see SUCCESSFUL + * @see SYSTEM_EXCEPTION + * @see USER_EXCEPTION + * @see TRANSPORT_RETRY + */ + const ReplyStatus LOCATION_FORWARD = 3; + +// Changes in ptc/00-08-06 +// const ReplyStatus LOCATION_FORWARD_PERMANENT = 4; + + /** + * Indicates a Transport Retry reply status. One possible value for + * RequestInfo.reply_status. + * @see RequestInfo#reply_status + * @see SUCCESSFUL + * @see SYSTEM_EXCEPTION + * @see USER_EXCEPTION + * @see LOCATION_FORWARD + */ + const ReplyStatus TRANSPORT_RETRY = 4; + + /** Slot id, represented as an int */ + typedef unsigned long SlotId; + + /** + * This exception is thrown when get_slot or + * set_slot is called on a slot that has not been allocated. + */ + exception InvalidSlot {}; + + /** + * Portable Interceptors Current (also known as PICurrent) + * is merely a slot table, the slots of which are used by each service to + * transfer their context data between their context and the request's or + * reply's service context. Each service which wishes to use PICurrent + * reserves a slot or slots at initialization time and uses those slots + * during the processing of requests and replies. + *

+ * Before an invocation is made, PICurrent is obtained via a call to + * ORB.resolve_initial_references( "PICurrent" ). From within + * the interception points, the data on PICurrent that has moved from the + * thread scope to the request scope is available via the + * get_slot operation on the RequestInfo object. + * A PICurrent can still be obtained via + * resolve_initial_references, but that is the Interceptor's + * thread scope PICurrent. + */ + local interface Current : CORBA::Current { + + /** + * Retrieves the slot data the application set in PICurrent via + * get_slot. The data is in the form of an Any. + *

+ * If the given slot has not been set, an Any containing a type code + * with a TCKind value of tk_null and no value + * is returned. + * + * @param id The SlotId of the slot from which the data will + * be returned. + * @return The data, in the form of an Any, of the given slot identifier. + * @exception InvalidSlot thrown if get_slot is called on a slot that + * has not been allocated. + * @exception BAD_INV_ORDER thrown if get_slot is called + * from within an ORB initializer + */ + any get_slot (in SlotId id) raises (InvalidSlot); + + /** + * Sets data in a slot. The data is in the form of an Any. If data + * already exists in that slot, it is overridden. + * + * @param id The SlotId of the slot to which the data will + * be set. + * @param data The data, in the form of an Any, which will be set + * to the identified slot. + * @exception InvalidSlot thrown if set_slot is called on + * a slot that has not been allocated. + * @exception BAD_INV_ORDER thrown if set_slot is called + * from within an ORB initializer. + */ + void set_slot (in SlotId id, in any data) raises (InvalidSlot); + }; + + /** + * Request Information, accessible to Interceptors. + *

+ * Each interception point is given an object through which the + * Interceptor can access request information. Client-side and server-side + * interception points are concerned with different information, so there + * are two information objects: ClientRequestInfo is passed + * to the client-side interception points and ServerRequestInfo + * is passed to the server-side interception points. But there is + * information that is common to both, so they both inherit from a common + * interface: RequestInfo. + * + * @see ClientRequestInfo + * @see ServerRequestInfo + */ + local interface RequestInfo { + /** + * Returns an id that uniquely identifies an active request/reply + * sequence. Once a request/reply sequence is concluded this ID may be + * reused. Note that this id is not the same as the GIOP + * request_id. If GIOP is the transport mechanism used, + * then these IDs may very well be the same, but this is not guaranteed + * nor required. + */ + readonly attribute unsigned long request_id; + + /** + * Returns the name of the operation being invoked. + */ + readonly attribute string operation; + + /** + * Returns an array of Parameter objects, containing the + * arguments on the operation being invoked. If there are no arguments, + * this attribute will be a zero length array. + *

+ * Not all environments provide access to the arguments. With the Java + * portable bindings, for example, the arguments are not available. + * In these environments, when this attribute is accessed, + * NO_RESOURCES will be thrown with a standard minor code + * of 1. + *

+ * Note: Arguments are available for DSI/DII calls. + * + * @exception NO_RESOURCES thrown if arguments are not available. + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute Dynamic::ParameterList arguments; + + /** + * Returns an array of TypeCode objects describing the + * TypeCodes of the user exceptions that this operation + * invocation may throw. If there are no user exceptions, this + * will return a zero length array. + *

+ * Not all environments provide access to the exception list. With + * the Java portable bindings, for example, the exception list is + * not available. In these environments, when this attribute is + * accessed, NO_RESOURCES will be thrown with a + * standard minor code of 1. + *

+ * Note: Exceptions are available for DSI/DII calls. + * + * @exception NO_RESOURCES thrown if exceptions are not available. + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute Dynamic::ExceptionList exceptions; + + /** + * Returns an array of String objects describing the + * contexts that may be passed on this operation invocation. If there + * are no contexts, this will return a zero length array. + *

+ * Not all environments provide access to the context list. With the + * Java portable bindings, for example, the context list is not + * available. In these environments, when this attribute is accessed, + * NO_RESOURCES will be thrown with a standard minor code + * of 1. + *

+ * Note: Contexts are available for DSI/DII calls. + * + * @exception NO_RESOURCES thrown if contexts are not available. + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute Dynamic::ContextList contexts; + + /** + * Returns an array of String objects containing the + * contexts being sent on the request. + *

+ * Not all environments provide access to the context. With the Java + * portable bindings, for example, the context is not available. In + * these environments, when this attribute is accessed, NO_RESOURCES will + * be thrown with standard minor code of 1. + *

+ * Note: operation_context is available for + * DSI/DII calls. + * + * @exception NO_RESOURCES thrown if operation context is not available. + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute Dynamic::RequestContext operation_context; + + /** + * Returns an any containing the result of the operation invocation. + * If the operation return type is void, this attribute will be an any + * containing a type code with a TCKind value of + * tk_void and no value. + *

+ * Not all environments provide access to the result. With the Java + * portable bindings, for example, the result is not available. In + * these environments, when this attribute is accessed, + * NO_RESOURCES will be thrown with a standard minor code of + * 1. + *

+ * Note: Result is available for DSI/DII calls. + * + * @exception NO_RESOURCES thrown if result is not available. + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute any result; + + /** + * Indicates whether a response is expected. + *

+ * On the client, a reply is not returned when + * response_expected is false, so receive_reply + * cannot be called. receive_other is called unless an + * exception occurs, in which case receive_exception is + * called. + *

+ * On the client, within send_poll, this attribute is true. + */ + readonly attribute boolean response_expected; + + /** + * Defines how far the request shall progress before control is returned + * to the client. This is defined in the Messaging specification, and + * is pertinent only when response_expected is false. If + * response_expected is true, the value of + * sync_scope is undefined. This attribute may have one of + * the following values: + *

    + *
  • Messaging.SYNC_NONE
  • + *
  • Messaging.SYNC_WITH_TRANSPORT
  • + *
  • Messaging.SYNC_WITH_SERVER
  • + *
  • Messaging.SYNC_WITH_TARGET
  • + *
+ * On the server, for all scopes, a reply will be created from the + * return of the target operation call, but the reply will not return + * to the client. Although it does not return to the client, it does + * occur, so the normal server-side interception points are + * followed (i.e., receive_request_service_contexts, + * receive_request, send_reply or + * send_exception). + *

+ * For SYNC_WITH_SERVER and SYNC_WITH_TARGET, + * the server does send an empty reply back to the client before the + * target is invoked. This reply is not intercepted by server-side + * Interceptors. + * + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute Messaging::SyncScope sync_scope; + + /** + * Describes the state of the result of the operation invocation. The + * return value can be one of the following: + *

    + *
  • PortableInterceptor.SUCCESSFUL
  • + *
  • PortableInterceptor.SYSTEM_EXCEPTION
  • + *
  • PortableInterceptor.USER_EXCEPTION
  • + *
  • PortableInterceptor.LOCATION_FORWARD
  • + *
  • PortableInterceptor.TRANSPORT_RETRY
  • + *
+ * On the client: + *
    + *
  • Within the receive_reply interception point, this + * will only return SUCCESSFUL
  • . + *
  • Within the receive_exception interception point, + * this will be either SYSTEM_EXCEPTION or + * USER_EXCEPTION.
  • + *
  • Within the receive_other interception point, this + * will be any of: SUCCESSFUL, + * LOCATION_FORWARD, or TRANSPORT_RETRY. + * SUCCESSFUL means an asynchronous request returned + * successfully. LOCATION_FORWARD means that a reply + * came back with LOCATION_FORWARD as its status. + * TRANSPORT_RETRY means that the transport + * mechanism indicated a retry - a GIOP reply with a status of + * NEEDS_ADDRESSING_MODE, for instance.
  • + *
+ * On the server: + *
    + *
  • Within the send_reply interception point, this + * will only be SUCCESSFUL.
  • + *
  • Within the send_exception interception point, + * this will be either SYSTEM_EXCEPTION or + * USER_EXCEPTION.
  • + *
  • Within the send_other interception point, this + * attribute will be any of: SUCCESSFUL, or + * LOCATION_FORWARD. SUCCESSFUL means + * an asynchronous request returned successfully. + * LOCATION_FORWARD means that a reply came back + * with LOCATION_FORWARD as its status.
  • + *
+ * + * @see SUCCESSFUL + * @see SYSTEM_EXCEPTION + * @see USER_EXCEPTION + * @see LOCATION_FORWARD + * @see TRANSPORT_RETRY + */ + readonly attribute ReplyStatus reply_status; + + /** + * Contains the object to which the request will be forwarded, if the + * reply_status attribute is LOCATION_FORWARD. + * It is indeterminate whether a forwarded request will actually occur. + */ + readonly attribute Object forward_reference; + + /** + * Returns the data from the given slot of the + * PortableInterceptor.Current that is in the scope of + * the request. + *

+ * If the given slot has not been set, then an any containing a + * type code with a TCKind value of tk_null is + * returned. + * + * @param id The SlotId of the slot which is to be + * returned. + * @return The slot data, in the form of an any, obtained with the + * given identifier. + * @exception InvalidSlot thrown if the ID does not define an + * allocated slot. + * @see Current + */ + any get_slot (in SlotId id) raises (InvalidSlot); + + /** + * Returns a copy of the service context with the given ID that + * is associated with the request. + *

+ * @param id The IOP.ServiceId of the service context + * which is to be returned. + * @return The IOP.ServiceContext obtained with the + * given identifier. + * @exception BAD_PARAM thrown with a standard minor code of 26, if the + * request's service context does not contain an entry for that ID. + */ + IOP::ServiceContext get_request_service_context + (in IOP::ServiceId id); + + /** + * Returns a copy of the service context with the given ID that + * is associated with the reply. + * + * @param id The IOP.ServiceId of the service context + * which is to be returned. + * @return The IOP.ServiceContext obtained with the given + * identifier. + * @exception BAD_PARAM thrown with a standard minor code of 26 if the + * request's service context does not contain an entry for that ID. + */ + IOP::ServiceContext get_reply_service_context + (in IOP::ServiceId id); + }; + + /** + * Request Information, accessible to client-side request interceptors. + *

+ * Some attributes and operations on ClientRequestInfo are + * not valid at all interception points. The following table shows the + * validity of each attribute or operation. If it is not valid, attempting + * to access it will result in a BAD_INV_ORDER being thrown + * with a standard minor code of 14. + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
 send_requestsend_pollreceive_replyreceive_exceptionreceive_other
Inherited from RequestInfo:
request_idyes yes yes yes yes
operationyes yes yes yes yes
argumentsyes1no yes no no
exceptionsyes no yes yes yes
contextsyes no yes yes yes
operation_contextyes no yes yes yes
resultno no yes no no
response_expectedyes yes yes yes yes
sync_scopeyes no yes yes yes
reply_statusno no yes yes yes
forward_referenceno no no no yes2 + *
get_slotyes yes yes yes yes
get_request_service_contextyes no yes yes yes
get_reply_service_contextno no yes yes yes
ClientRequestInfo-specific:
targetyes yes yes yes yes
effective_targetyes yes yes yes yes
effective_profileyes yes yes yes yes
received_exceptionno no no yes no
received_exception_idno no no yes no
get_effective_componentyes no yes yes yes
get_effective_componentsyes no yes yes yes
get_request_policyyes no yes yes yes
add_request_service_contextyes no no no no
+ *

    + *
  1. When ClientRequestInfo is passed to + * send_request, there is an entry in the list for every + * argument, whether in, inout, or out. But only the in and inout + * arguments will be available.
  2. + *
  3. If the reply_status atribute is not + * LOCATION_FORWARD, accessing this attribute will + * throw BAD_INV_ORDER with a standard minor code of + * 14.
  4. + *
+ * + * @see ClientRequestInterceptor + */ + local interface ClientRequestInfo : RequestInfo { + + /** + * Returns the object which the client called to perform the + * operation. + * + * @see #effective_target + */ + readonly attribute Object target; + + /** + * Returns the actual object on which the operation will be invoked. + * If the reply_status is LOCATION_FORWARD, + * then on subsequent requests, effective_target will + * contain the forwarded IOR while target will remain unchanged. + * + * @see #target + */ + readonly attribute Object effective_target; + + /** + * Returns the profile that will be used to send the request. If a + * location forward has occurred for this operation's object and + * that object's profile changed accordingly, then this profile will + * be that located profile. + */ + readonly attribute IOP::TaggedProfile effective_profile; + + /** + * Returns an any which contains the exception to be returned to + * the client. + *

+ * If the exception is a user exception which cannot be inserted + * into an any (e.g., it is unknown or the bindings don t provide + * the TypeCode), then this attribute will be an any + * containing the system exception UNKNOWN with a + * standard minor code of 1. However, the repository id of + * the exception is available in the received_exception_id + * attribute. + * + * @see #received_exception_id + */ + readonly attribute any received_exception; + + /** + * Returns the repository id of the exception to be returned to + * the client. + * + * @see #received_exception + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute CORBA::RepositoryId received_exception_id; + + /** + * Returns the IOP.TaggedComponent with the given ID from + * the profile selected for this request. + *

+ * If there is more than one component for a given component ID, it + * is undefined which component this operation returns. If there is + * more than one component for a given component ID, + * get_effective_components should be called instead. + * + * @param id The component id of the component which + * is to be returned. + * @return The IOP.TaggedComponent obtained with the + * given identifier. + * @exception BAD_PARAM thrown, with a standard minor code of 28, if + * no component exists for the given component ID. + * @see #get_effective_components + */ + IOP::TaggedComponent get_effective_component + (in IOP::ComponentId id); + + /** + * Returns an array of all tagged components with the given ID from the + * profile selected for this request. + * + * @param id The component id of the components which are to be returned. + * @return An array of TaggedComponent objects, each of + * which contains the given identifier. + * @exception BAD_PARAM thrown, with a standard minor code of 28, if + * no component exists for the given component ID. + * @see #get_effective_component + */ + IOP::TaggedComponentSeq get_effective_components + (in IOP::ComponentId id); + + /** + * Returns the given policy in effect for this operation. + * + * @exception INV_POLICY thrown, with a standard minor code of 1, if the + * policy type is not valid either because the specified type is + * not supported by this ORB or because a policy object of that type + * is not associated with this Object + * @param type The policy type which specifies the policy to be + * returned. + * @return The CORBA.Policy obtained with the given type. + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + CORBA::Policy get_request_policy + (in CORBA::PolicyType type); + + /** + * Allows Interceptors to add service contexts to the request. + *

+ * There is no declaration of the order of the service contexts. + * They may or may not appear in the order that they are added. + * + * @param service_context The IOP.ServiceContext to be + * added to the request. + * @param replace Indicates the behavior of this operation when a + * service context already exists with the given ID. If false, + * then BAD_INV_ORDER with a standard minor code of 15 + * is thrown. If true, then the existing service context is + * replaced by the new one. + */ + void add_request_service_context ( + in IOP::ServiceContext service_context, + in boolean replace); + }; + + // Should be type string + typedef string ServerId ; + + // This should actually be the CORBA::ORBid type once that is available + typedef string ORBId ; + + /** The name of an object adapter. This is unique only within + * the scope of the ORB that created the object adapter. + */ + typedef org::omg::CORBA::StringSeq AdapterName ; + + /** Type of an object id. This provides the identity of a particular + * object that was created by an object adapter. + */ + typedef org::omg::CORBA::OctetSeq ObjectId ; + + /** + * Request Information, accessible to server-side request interceptors. + *

+ * Some attributes and operations on ServerRequestInfo are not + * valid at all interception points. The following table shows the validity + * of each attribute or operation. If it is not valid, attempting to access + * it will result in a BAD_INV_ORDER being thrown with a + * standard minor code of 14. + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
 receive_request_
service_contexts
receive_requestsend_replysend_exceptionsend_other
Inherited from RequestInfo:
request_idyes yes yes yes yes
operationyes yes yes yes yes
argumentsno yes1 + * yes no2no2 + *
exceptionsno yes yes yes yes
contextsno yes yes yes yes
operation_contextno yes yes no no
resultno no yes no no
response_expectedyes yes yes yes yes
sync_scopeyes yes yes yes yes
reply_statusno no yes yes yes
forward_referenceno no no no yes2 + *
get_slotyes yes yes yes yes
get_request_service_contextyes no yes yes yes
get_reply_service_contextno no yes yes yes
ServerRequestInfo-specific:
sending_exceptionno no no yes no
object_idno yes yes yes3yes3 + *
adapter_idno yes yes yes3yes3 + *
server_idno yes yes yes yes
orb_idno yes yes yes yes
adapter_nameno yes yes yes yes
target_most_derived_interfaceno yes no4no4no4 + *
get_server_policyyes yes yes yes yes
set_slotyes yes yes yes yes
target_is_ano yes no4no4no4 + *
add_reply_service_contextyes yes yes yes yes
+ *

    + *
  1. When ServerRequestInfo is passed to + * receive_request, there is an entry in the list for + * every argument, whether in, inout, or out. But only the in and + * inout arguments will be available.
  2. + *
  3. If the reply_status attribute is not + * LOCATION_FORWARD, accessing this attribute will throw + * BAD_INV_ORDER with a standard minor code of 14.
  4. + *
  5. If the servant locator caused a location forward, or thrown an + * exception, this attribute/operation may not be available in this + * interception point. NO_RESOURCES with a standard minor + * code of 1 will be thrown if it is not available.
  6. + *
  7. The operation is not available in this interception point because + * the necessary information requires access to the target object's + * servant, which may no longer be available to the ORB. For example, + * if the object's adapter is a POA that uses a + * ServantLocator, then the ORB invokes the interception + * point after it calls ServantLocator.postinvoke()
  8. . + *
+ * + * @see ServerRequestInterceptor + */ + local interface ServerRequestInfo : RequestInfo { + + /** + * Returns an any which contains the exception to be returned to + * the client. + *

+ * If the exception is a user exception which cannot be inserted into + * an any (e.g., it is unknown or the bindings don't provide the + * TypeCode), then this attribute will be an any + * containing the system exception UNKNOWN with a + * standard minor code of 1. + * + * @see + * PortableInterceptor package comments for + * limitations / unimplemented features + */ + readonly attribute any sending_exception; + + /** + * Returns the opaque object_id describing the target of + * the operation invocation. + */ + readonly attribute ObjectId object_id; + + /** + * Returns the opaque identifier for the object adapter. + */ + readonly attribute CORBA::OctetSeq adapter_id; + + /** + * Returns the server ID that was specified on ORB::init using the -ORBServerId + * argument. + */ + readonly attribute ServerId server_id ; + + /** + * Returns the ID that was used to create the ORB. + */ + readonly attribute ORBId orb_id ; + + /** + * Returns the sequence of strings that identifies the object + * adapter instance that is handling this request. + */ + readonly attribute AdapterName adapter_name ; + + /** + * Returns the repository id for the most derived interface of the + * servant. + */ + readonly attribute CORBA::RepositoryId + target_most_derived_interface; + + /** + * Returns the policy in effect for this operation for the given + * policy type. The returned CORBA.Policy object shall + * only be a policy whose type was registered via + * register_policy_factory. + * + * @param type The CORBA.PolicyType which specifies the + * policy to be returned. + * @return The CORBA.Policy obtained with the given + * policy type. + * @exception INV_POLICY thrown, with a standard minor code of 2, if + * a policy for the given type was not registered via + * register_policy_factory. + * @see ORBInitInfo#register_policy_factory + */ + CORBA::Policy get_server_policy + (in CORBA::PolicyType type); + + /** + * Allows an Interceptor to set a slot in the + * PortableInterceptor.Current that is in the scope of + * the request. If data already exists in that slot, it will be + * overwritten. + * + * @param id The id of the slot. + * @param data The data, in the form of an any, to store in that slot. + * @exception InvalidSlot thrown if the ID does not define an allocated + * slot. + * @see Current + */ + void set_slot (in SlotId id, in any data) raises (InvalidSlot); + + /** + * Returns true if the servant is the given repository id, + * false if it is not. + * + * @param id The caller wants to know if the servant is this + * repository id. + * @return Is the servant the given RepositoryId? + */ + boolean target_is_a (in CORBA::RepositoryId id); + + /** + * Allows Interceptors to add service contexts to the request. + *

+ * There is no declaration of the order of the service contexts. + * They may or may not appear in the order that they are added. + * + * @param service_context The IOP.ServiceContext to add to + * the reply. + * @param replace Indicates the behavior of this operation when a + * service context already exists with the given ID. If false, + * then BAD_INV_ORDER with a standard minor code of 15 + * is thrown. If true, then the existing service context is + * replaced by the new one. + * @exception BAD_INV_ORDER thrown, with a standard minor code of 15, if + * replace is false and a service context already exists with the + * given ID. + */ + void add_reply_service_context ( + in IOP::ServiceContext service_context, + in boolean replace); + }; + + /** + * Client-side request interceptor. + *

+ * A request Interceptor is designed to intercept the flow of a + * request/reply sequence through the ORB at specific points so that + * services can query the request information and manipulate the service + * contexts which are propagated between clients and servers. The primary + * use of request Interceptors is to enable ORB services to transfer + * context information between clients and servers. There are two types + * of request Interceptors: client-side and server-side. + *

+ * To write a client-side Interceptor, implement the + * ClientRequestInterceptor interface. + * + * @see ClientRequestInfo + */ + local interface ClientRequestInterceptor : Interceptor { + /** + * Allows an Interceptor to query request information and modify the + * service context before the request is sent to the server. + *

+ * This interception point may throw a system exception. If it does, + * no other Interceptors' send_request operations are called. + * Those Interceptors on the Flow Stack are popped and their + * receive_exception interception points are called. This + * interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, no other + * Interceptors' send_request operations are + * called. Those Interceptors on the Flow Stack are popped and their + * receive_other interception points are called. + *

+ * Compliant Interceptors shall properly follow completion_status + * semantics if they throw a system exception from this interception + * point. The completion_status shall be + * COMPLETED_NO. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void send_request (in ClientRequestInfo ri) raises (ForwardRequest); + + /** + * Allows an Interceptor to query information during a Time-Independent + * Invocation (TII) polling get reply sequence. + *

+ * With TII, an application may poll for a response to a request sent + * previously by the polling client or some other client. This poll is + * reported to Interceptors through the send_poll + * interception point and the response is returned through the + * receive_reply or receive_exception + * interception points. If the response is not available before the + * poll time-out expires, the system exception TIMEOUT is + * thrown and receive_exception is called with this + * exception. + *

+ * This interception point may throw a system exception. If it does, + * no other Interceptors' send_poll operations are + * called. Those Interceptors on the Flow Stack are popped and their + * receive_exception interception points are called. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. The completion_status shall be + * COMPLETED_NO. + * + * @param ri Information about the current request being intercepted. + * @exception TIMEOUT thrown if the response is not available before + * the poll time-out expires + */ + void send_poll (in ClientRequestInfo ri); + + /** + * Allows an Interceptor to query the information on a reply after it + * is returned from the server and before control is returned to the + * client. + *

+ * This interception point may throw a system exception. If it does, + * no other Interceptors' receive_reply operations are + * called. The remaining Interceptors in the Flow Stack shall have + * their receive_exception interception point called. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. The + * completion_status shall be COMPLETED_YES. + * + * @param ri Information about the current request being intercepted. + */ + void receive_reply (in ClientRequestInfo ri); + + /** + * Indicates to the interceptor that an exception occurred. Allows + * an Interceptor to query the exception's information before it is + * thrown to the client. + *

+ * This interception point may throw a system exception. This has the + * effect of changing the exception which successive Interceptors + * popped from the Flow Stack receive on their calls to + * receive_exception. The exception thrown to the client + * will be the last exception thrown by an Interceptor, or the original + * exception if no Interceptor changes the exception. + *

+ * This interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, no other + * Interceptors' receive_exception operations are called. + * The remaining Interceptors in the Flow Stack are popped and have their + * receive_other interception point called. + *

+ * If the completion_status of the exception is not + * COMPLETED_NO, then it is inappropriate for this + * interception point to throw a ForwardRequest exception. + * The request s at-most-once semantics would be lost. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. If the original exception is + * a system exception, the completion_status of the new + * exception shall be the same as on the original. If the original + * exception is a user exception, then the completion_status + * of the new exception shall be COMPLETED_YES. + *

+ * Under some conditions, depending on what policies are in effect, an + * exception (such as COMM_FAILURE) may result in a retry + * of the request. While this retry is a new request with respect to + * Interceptors, there is one point of correlation between the original + * request and the retry: because control has not returned to the + * client, the PortableInterceptor.Current for both the + * original request and the retrying request is the same. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void receive_exception (in ClientRequestInfo ri) raises (ForwardRequest); + + /** + * Allows an Interceptor to query the information available when a + * request results in something other than a normal reply or an + * exception. For example, a request could result in a retry + * (e.g., a GIOP Reply with a LOCATION_FORWARD status was + * received); or on asynchronous calls, the reply does not immediately + * follow the request, but control shall return to the client and an + * ending interception point shall be called. + *

+ * For retries, depending on the policies in effect, a new request may or + * may not follow when a retry has been indicated. If a new request does + * follow, while this request is a new request, with respect to + * Interceptors, there is one point of correlation between the original + * request and the retry: because control has not returned to the client, + * the request scoped PortableInterceptor.Current for both + * the original request and the retrying request is the same. + *

+ * This interception point may throw a system exception. If it does, no + * other Interceptors' receive_other operations are called. + * The remaining Interceptors in the Flow Stack are popped and have + * their receive_exception interception point called. + *

+ * This interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, successive + * Interceptors' receive_other operations are called with + * the new information provided by the ForwardRequest + * exception. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. The + * completion_status shall be COMPLETED_NO. + * If the target invocation had completed, this interception point + * would not be called. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void receive_other (in ClientRequestInfo ri) raises (ForwardRequest); + }; + + /** + * Server-side request interceptor. + *

+ * A request Interceptor is designed to intercept the flow of a + * request/reply sequence through the ORB at specific points so that + * services can query the request information and manipulate the service + * contexts which are propagated between clients and servers. The primary + * use of request Interceptors is to enable ORB services to transfer + * context information between clients and servers. There are two types + * of request Interceptors: client-side and server-side. + *

+ * To write a server-side Interceptor, implement the + * ServerRequestInterceptor interface. + * + * @see ServerRequestInfo + */ + local interface ServerRequestInterceptor : Interceptor { + /** + * Allows the interceptor to process service context information. + *

+ * At this interception point, Interceptors must get their service + * context information from the incoming request transfer it to + * PortableInterceptor.Current's slots. + *

+ * This interception point is called before the servant manager is called. + * Operation parameters are not yet available at this point. This + * interception point may or may not execute in the same thread as + * the target invocation. + *

+ * This interception point may throw a system exception. If it does, + * no other Interceptors' receive_request_service_contexts + * operations are called. Those Interceptors on the Flow Stack are + * popped and their send_exception interception points are + * called. + *

+ * This interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, no other + * Interceptors' receive_request_service_contexts operations + * are called. Those Interceptors on the Flow Stack are popped and + * their send_other interception points are called. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. The + * completion_status shall be COMPLETED_NO. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void receive_request_service_contexts (in ServerRequestInfo ri) + raises (ForwardRequest); + + /** + * Allows an Interceptor to query request information after all the + * information, including operation parameters, are available. This + * interception point shall execute in the same thread as the target + * invocation. + *

+ * In the DSI model, since the parameters are first available when + * the user code calls arguments, receive_request + * is called from within arguments. It is possible that + * arguments is not called in the DSI model. The target + * may call set_exception before calling + * arguments. The ORB shall guarantee that + * receive_request is called once, either through + * arguments or through set_exception. If it + * is called through set_exception, requesting the + * arguments will result in NO_RESOURCES being thrown with + * a standard minor code of 1. + *

+ * This interception point may throw a system exception. If it does, no + * other Interceptors' receive_request operations are + * called. Those Interceptors on the Flow Stack are popped and their + * send_exception interception points are called. + *

+ * This interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, no other + * Interceptors' receive_request operations are called. + * Those Interceptors on the Flow Stack are popped and their + * send_other interception points are called. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. The + * completion_status shall be COMPLETED_NO. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void receive_request (in ServerRequestInfo ri) raises (ForwardRequest); + + /** + * Allows an Interceptor to query reply information and modify the + * reply service context after the target operation has been invoked + * and before the reply is returned to the client. This interception + * point shall execute in the same thread as the target invocation. + *

+ * This interception point may throw a system exception. If it does, + * no other Interceptors' send_reply operations are called. + * The remaining Interceptors in the Flow Stack shall have their + * send_exception interception point called. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a + * system exception from this interception point. The + * completion_status shall be COMPLETED_YES. + * + * @param ri Information about the current request being intercepted. + */ + void send_reply (in ServerRequestInfo ri); + + /** + * Allows an Interceptor to query the exception information and modify + * the reply service context before the exception is thrown to the client. + * When an exception occurs, this interception point is called. This + * interception point shall execute in the same thread as the target + * invocation. + *

+ * This interception point may throw a system exception. This has the + * effect of changing the exception which successive Interceptors + * popped from the Flow Stack receive on their calls to + * send_exception. The exception thrown to the client will + * be the last exception thrown by an Interceptor, or the original + * exception if no Interceptor changes the exception. + *

+ * This interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, no other + * Interceptors' send_exception operations are called. The + * remaining Interceptors in the Flow Stack shall have their + * send_other interception points called. + *

+ * If the completion_status of the exception is not + * COMPLETED_NO, then it is inappropriate for this + * interception point to throw a ForwardRequest exception. + * The request's at-most-once semantics would be lost. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. If the original exception + * is a system exception, the completion_status of the new + * exception shall be the same as on the original. If the original + * exception is a user exception, then the completion_status + * of the new exception shall be COMPLETED_YES. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void send_exception (in ServerRequestInfo ri) raises (ForwardRequest); + + /** + * Allows an Interceptor to query the information available when a + * request results in something other than a normal reply or an + * exception. For example, a request could result in a retry + * (e.g., a GIOP Reply with a LOCATION_FORWARD status was + * received). This interception point shall execute in the same thread + * as the target invocation. + *

+ * This interception point may throw a system exception. If it does, + * no other Interceptors' send_other operations are called. + * The remaining Interceptors in the Flow Stack shall have their + * send_exception interception points called. + *

+ * This interception point may also throw a ForwardRequest + * exception. If an Interceptor throws this exception, successive + * Interceptors' send_other operations are called with + * the new information provided by the ForwardRequest + * exception. + *

+ * Compliant Interceptors shall properly follow + * completion_status semantics if they throw a system + * exception from this interception point. The + * completion_status shall be COMPLETED_NO. + * + * @param ri Information about the current request being intercepted. + * @exception ForwardRequest If thrown, indicates to the ORB that a + * retry of the request should occur with the new object given in + * the exception. + */ + void send_other (in ServerRequestInfo ri) raises (ForwardRequest); + }; + + /** The object reference factory. This provides the capability of + * creating an object reference. + */ + abstract valuetype ObjectReferenceFactory { + /** make_object creates a CORBA object reference according + * to the data in this template, with the given repository ID and + * object ID. + */ + Object make_object( in string repositoryId, in ObjectId object_id ) ; + } ; + + /** The object reference template. An instance of this must + * exist for each object adapter created in an ORB. The server_id, + * orb_id, and adapter_name attributes uniquely identify this template + * within the scope of an IMR. Note that adapter_id is similarly unique + * within the same scope, but it is opaque, and less useful in many + * cases. + */ + abstract valuetype ObjectReferenceTemplate : ObjectReferenceFactory { + + readonly attribute ServerId server_id ; + + readonly attribute ORBId orb_id ; + + readonly attribute AdapterName adapter_name ; + } ; + + /** Sequence of object reference templates is used for reporting state + * changes that do not occur on the adapter manager. + */ + typedef sequence ObjectReferenceTemplateSeq ; + + /** Adapter manager identifier. Every object adapter has an adapter manager, + * indicated in this API only through the ID. A group of object adapter + * instances may share the same adapter manager, in which case state transitions + * reported for the adapter manager are observed by all object adapters with the + * same adapter manager ID. + */ + typedef long AdapterManagerId ; + + /** Type of object adapter state. State changes are reported either to + * the object adapter or to the adapter manager. + */ + typedef short AdapterState ; + + /** Object adapter state that holds requests temporarily until the + * state is changed. + */ + const AdapterState HOLDING = 0 ; + + /** Object adapter state that indicates normal request processing. + */ + const AdapterState ACTIVE = 1 ; + + /** Object adapter state that causes all requests to be discarded. + */ + const AdapterState DISCARDING = 2 ; + + /** Object adapter state that causes all requests to be discarded. + * This state indicates that the adapter is shutting down. + */ + const AdapterState INACTIVE = 3 ; + + /** Object adapter state indicating that the adapter has been destroyed. + */ + const AdapterState NON_EXISTENT = 4 ; + + /** + * Provides the server-side ORB service with access to the applicable + * policies during IOR construction and the ability to add components. + * The ORB passes an instance of its implementation of this interface as + * a parameter to IORInterceptor.establish_components. + * + * @see IORInterceptor + */ + local interface IORInfo { + + /** + * Allows an ORB service implementation to determine what server side + * policy of a particular type is in effect for an IOR being + * constructed. When the IOR being constructed is for an object + * implemented using a POA, all Policy objects passed to the + * PortableServer.POA.create_POA call that created that + * POA are accessable via get_effective_policy. + *

+ * If a policy for the given type is not known to the ORB, then this + * operation will throw INV_POLICY with a standard minor + * code of 2. + * + * @param type an int specifying the type of policy to return. + * @return The effective CORBA.Policy object of the + * requested type. If the given policy type is known, but no policy + * of that type is in effect, then this operation will return a + * nil object reference. + */ + CORBA::Policy get_effective_policy + (in CORBA::PolicyType type); + + /** + * A portable ORB service implementation calls + * add_ior_component from its implementation of + * establish_components to add a tagged component to the + * set which will be included when constructing IORs. The components in + * this set will be included in all profiles. + *

+ * Any number of components may exist with the same component ID. + * + * @param tagged_component The IOP.TaggedComponent to add. + */ + void add_ior_component + (in IOP::TaggedComponent tagged_component); + + /** + * A portable ORB service implementation calls + * add_ior_component_to_profile from its implementation of + * establish_components to add a tagged component to the + * set which will be included when constructing IORs. The components in + * this set will be included in the specified profile. + *

+ * Any number of components may exist with the same component ID. + * + * @param tagged_component The IOP.TaggedComponent to add. + * @param profile_id The profile id of the profile to + * which this component will be added. + * @exception BAD_PARAM thrown, with a standard minor code of 29, if the + * given profile ID does not define a known profile or it is + * impossible to add components to that profile. + */ + void add_ior_component_to_profile ( + in IOP::TaggedComponent tagged_component, + in IOP::ProfileId profile_id); + + /** Return the adapter manager id of the object adapter + * that was just created and is running IOR interceptors. + */ + readonly attribute AdapterManagerId manager_id ; + + /** Return the adapter state of the object adapter + * that was just created and is running IOR interceptors. + */ + readonly attribute AdapterState state ; + + /** Return the object reference template of the object adapter + * that was just created and is running IOR interceptors. + */ + readonly attribute ObjectReferenceTemplate adapter_template ; + + /** On read, returns the current factory that will be used to create + * object references for the object adapter that was just created + * and is running IOR interceptors. By default, this factory is the same + * as the value of the adapter_template attribute. The current_factory + * may also be set to another object reference template inside an + * IORInterceptor_3_0. + */ + attribute ObjectReferenceFactory current_factory ; + }; + + /** + * Interceptor used to establish tagged components in the profiles within + * an IOR. + *

+ * In some cases, a portable ORB service implementation may need to add + * information describing the server's or object's ORB service related + * capabilities to object references in order to enable the ORB service + * implementation in the client to function properly. + *

+ * This is supported through the IORInterceptor and + * IORInfo interfaces. + * + * @see IORInfo + */ + local interface IORInterceptor : Interceptor { + /** + * A server side ORB calls the establish_components + * operation on all registered IORInterceptor instances + * when it is assembling the list of components that will be included + * in the profile or profiles of an object reference. This operation + * is not necessarily called for each individual object reference. + * In the case of the POA, this operation is called each time POA::create_POA + * is called. In any case, establish_components is + * guaranteed to be called at least once for each distinct set of + * server policies. + *

+ * An implementation of establish_components must not + * throw exceptions. If it does, the ORB shall ignore the exception + * and proceed to call the next IOR Interceptor's + * establish_components operation. + * + * @param info The IORInfo instance used by the ORB + * service to query applicable policies and add components to be + * included in the generated IORs. + */ + void establish_components (in IORInfo info); + }; + + local interface IORInterceptor_3_0 : IORInterceptor { + /** The components_established method is invoked on all registered + * IORInterceptor_3_0 instances after establish_components + * has been invoked on all registered IORInterceptor instances. + * The adapter_template is available in info during this call. + * The current_factory may be get or set in info during this call. + *

+ * Any exception thrown from this method is handled by the Object + * Adapter that called this interceptor. In the case of the POA, + * an exception results in a OBJ_ADAPTER exception with an OMG + * standard minor code of 6. + * @param info The IORInfo for the object adapter being created. + */ + void components_established( in IORInfo info ) ; + + /** Called whenever the state of an adapter manager changes. + * For the POA, that is the POAManager. If the state change + * is reported through adapter_manager_state_changed, + * it is not reported through adapter_state_changed. + * @param id the adapter manager id of the adapter manager that + * changed state + * @param state the new state of the adapter manager + */ + void adapter_manager_state_changed( in AdapterManagerId id, + in AdapterState state ) ; + + /** Called whenever the state of an object adapter changes, and + * the state change is not caused by an adapter manager. Such + * changes are reported to all registered IORInterceptor_3_0 + * instances. + * @param templates the sequence of ObjectReferenceTemplate instances + * on which this state change occurred. + * @param state the new AdapterState shared by all of the templates. + */ + void adapter_state_changed( in ObjectReferenceTemplateSeq templates, + in AdapterState state ) ; + }; + + /** + * Enables policy types to be constructed using + * CORBA.ORB.create_policy. + *

+ * A portable ORB service implementation registers an instance of the + * PolicyFactory interface during ORB initialization in order + * to enable its policy types to be constructed using + * CORBA.ORB.create_policy. The POA is required to preserve + * any policy which is registered with ORBInitInfo in this + * manner. + * + * @see ORBInitInfo#register_policy_factory + */ + local interface PolicyFactory + { + /** + * Returns an instance of the appropriate interface derived from + * CORBA.Policy whose value corresponds to the + * specified any. + *

+ * The ORB calls create_policy on a registered + * PolicyFactory instance when + * CORBA.ORB.create_policy is called for the + * PolicyType under which the PolicyFactory has + * been registered. The create_policy operation then + * returns an instance of the appropriate interface derived from + * CORBA.Policy whose value corresponds to the specified + * any. If it cannot, it shall throw an exception as described for + * CORBA.ORB.create_policy. + * + * @param type An int specifying the type of policy being created. + * @param value An any containing data with which to construct the + * CORBA.Policy. + * @return A CORBA.Policy object of the specified type and + * value. + */ + CORBA::Policy create_policy + (in CORBA::PolicyType type, in any value) + raises (CORBA::PolicyError); + }; + + /** + * Passed to each ORBInitializer, allowing it to + * to register interceptors and perform other duties while the ORB is + * initializing. + *

+ * The ORBInitInfo object is only valid during + * ORB.init. If a service keeps a reference to its + * ORBInitInfo object and tries to use it after + * ORB.init returns, the object no longer exists and an + * OBJECT_NOT_EXIST exception shall be thrown. + * + * @see ORBInitializer + */ + local interface ORBInitInfo { + + /** Object id, represented as a String */ + typedef string ObjectId; + + /** + * Only one Interceptor of a given name can be registered with the + * ORB for each Interceptor type. If an attempt is made to register a + * second Interceptor with the same name, DuplicateName is thrown. + *

+ * An Interceptor may be anonymous, i.e., have an empty string as the + * name attribute. Any number of anonymous Interceptors may be + * registered with the ORB so, if the Interceptor being registered + * is anonymous, the registration operation will not throw + * DuplicateName. + */ + exception DuplicateName { + /** + * The name for which there was already an interceptor registered. + */ + string name; + }; + + /** + * This exception is thrown by + * register_initial_reference and + * resolve_initial_references. + * register_initial_reference throws InvalidName + * if: + *

    + *
  • this operation is called with an empty string id; or
  • + *
  • this operation is called with an id that is already registered, + * including the default names defined by OMG.
  • + *
+ * resolve_initial_references throws + * InvalidName if the name to be resolved is invalid. + */ + exception InvalidName {}; + + /** + * Returns the arguments passed to ORB.init. They may or + * may not contain the ORB's arguments. + */ + readonly attribute CORBA::StringSeq arguments; + + /** + * Returns the ID of the ORB being initialized. + */ + readonly attribute string orb_id; + + /** + * Returns the IOP.CodecFactory. The + * CodecFactory is normally obtained via a call to + * ORB.resolve_initial_references( "CodecFactory" ), but + * since the ORB is not yet available and Interceptors, particularly when + * processing service contexts, will require a Codec, a + * means of obtaining a Codec is necessary during ORB + * initialization. + */ + readonly attribute IOP::CodecFactory codec_factory; + + /** + * Identical to ORB.register_initial_reference. This same + * functionality exists here because the ORB, not yet fully initialized, + * is not yet available but initial references may need to be + * registered as part of Interceptor registration. The only difference + * is that the version of this operation on the ORB uses PIDL + * (CORBA.ORB.ObjectId) and + * (CORBA.ORB.InvalidName) whereas the version in this + * interface uses IDL defined in this interface; the semantics are + * identical. + */ + void register_initial_reference (in ObjectId id, in Object obj) + raises (InvalidName); + + // This was incorrectly returning void in orbos/99-12-02, correction + // from errata in orbos/00-01-01 + /** + * Identical to ORB.resolve_initial_references. This same + * functionality exists here because the ORB, not yet fully initialized, + * is not yet available but initial references may be required from the + * ORB as part of Interceptor registration. The only difference is that + * the version of this operation on the ORB uses PIDL + * (CORBA::ORB::ObjectId and + * CORBA::ORB::InvalidName) whereas the version in this + * interface uses IDL defined in this interface; the semantics + * are identical. + *

+ * This operation is only valid during post_init. + */ + Object resolve_initial_references (in ObjectId id) raises (InvalidName); + + /** + * Used to add a client-side request Interceptor to the list of + * client-side request Interceptors. + * + * @param interceptor The ClientRequestInterceptor to be + * added. + * @exception DuplicateName thrown if a client-side request Interceptor + * has already been registered with this Interceptor's name. + */ + void add_client_request_interceptor + (in ClientRequestInterceptor interceptor) + raises (DuplicateName); + + /** + * Used to add a server-side request Interceptor to the list of + * server-side request Interceptors. + * + * @param interceptor The ServerRequestInterceptor to be added. + * @exception DuplicateName thrown if a server-side request Interceptor + * has already been registered with this Interceptor's name + */ + void add_server_request_interceptor ( + in ServerRequestInterceptor interceptor) + raises (DuplicateName); + + /** + * Used to add an IOR Interceptor to the list of IOR Interceptors. + * + * @param interceptor The IORInterceptor to be added. + * @exception DuplicateName thrown if an IOR Interceptor has already + * been registered with this Interceptor's name. + */ + void add_ior_interceptor (in IORInterceptor interceptor) + raises (DuplicateName); + + /** + * Called to allocate a slot on PortableInterceptor.Current. + *

+ * Note that while slot id's can be allocated within an ORB initializer, + * the slots themselves cannot be initialized. + * + * @return The index to the slot which has been allocated. + * @exception BAD_INV_ORDER thrown, with a standard minor code of 14, if + * set_slot or get_slot is called on the + * PICurrent within an ORB initializer. + * @see Current + */ + SlotId allocate_slot_id (); + + /** + * Registers a PolicyFactory for the given + * PolicyType. + * + * @param type The policy type that the given PolicyFactory + * serves. + * @param policy_factory The factory for the given policy type. + * @exception BAD_INV_ORDER thrown, with a standard minor code of 16, if + * a PolicyFactory already exists for the given + * PolicyType. + */ + void register_policy_factory ( + in CORBA::PolicyType type, + in PolicyFactory policy_factory); + }; + + /** + * Facilitates interceptor registration and ORB initialization. + *

+ * Interceptors are intended to be a means by which ORB services gain + * access to ORB processing, effectively becoming part of the ORB. + * Since Interceptors are part of the ORB, when ORB.init + * returns an ORB, the Interceptors shall have been registered. + * Interceptors cannot be registered on an ORB after it has been + * returned by a call to ORB.init. + *

+ * An Interceptor is registered by registering an associated + * ORBInitializer object which implements the + * ORBInitializer interface. When an ORB is initializing, + * it shall call each registered ORBInitializer, passing it + * an ORBInitInfo object which is used to register its + * Interceptor. + *

+ * Registering ORB Initializers in Java + *

+ * ORBInitializers are registered via Java ORB properties. + *

+ * The property names are of the form: + *

+ * org.omg.PortableInterceptor.ORBInitializerClass.<Service> + *
+ * where <Service> is the string name of a class + * which implements + *
+ * org.omg.PortableInterceptor.ORBInitializer + *
+ * To avoid name collisions, the reverse DNS name convention should be + * used. For example, if company X has three initializers, it could define + * the following properties: + *
    + *
  • + * org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init1 + *
  • + *
  • + * org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init2 + *
  • + *
  • + * org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init3 + *
  • + *
+ * During ORB.init, these ORB properties which begin with + * org.omg.PortableInterceptor.ORBInitializerClass shall be + * collected, the <Service> portion of each property + * shall be extracted, an object shall be instantiated with the + * <Service> string as its class name, and the + * pre_init and post_init methods shall be + * called on that object. If there are any exceptions, the ORB shall + * ignore them and proceed. + *

+ * Example + *

+ * A client-side logging service written by company X, for example, may + * have the following ORBInitializer implementation: + *

+   * package com.x.logging;
+   * 
+   * import org.omg.PortableInterceptor.Interceptor; 
+   * import org.omg.PortableInterceptor.ORBInitializer; 
+   * import org.omg.PortableInterceptor.ORBInitInfo; 
+   * 
+   * public class LoggingService implements ORBInitializer { 
+   *     void pre_init( ORBInitInfo info ) { 
+   *         // Instantiate the Logging Service s Interceptor. 
+   *         Interceptor interceptor = new LoggingInterceptor(); 
+   *
+   *         // Register the Logging Service s Interceptor. 
+   *         info.add_client_request_interceptor( interceptor ); 
+   *     } 
+   * 
+   *     void post_init( ORBInitInfo info ) { 
+   *         // This service does not need two init points. 
+   *     } 
+   * } 
+   * 
+ * To run a program called MyApp using this logging + * service, the user could type: + *
+ * java + *-Dorg.omg.PortableInterceptor.ORBInitializerClass.com.x.Logging.LoggingService + * MyApp + *
+ *

+ * Notes about Registering Interceptors + *

+ * Request Interceptors are registered on a per-ORB basis. + *

+ * To achieve virtual per-object Interceptors, query the policies on the + * target from within the interception points to determine whether they + * should do any work. + *

+ * To achieve virtual per-POA Interceptors, instantiate each POA with a + * different ORB. While Interceptors may be ordered administratively, + * there is no concept of order with respect to the registration of + * Interceptors. Request Interceptors are concerned with service contexts. + * Service contexts have no order, so there is no purpose for request + * Interceptors to have an order. IOR Interceptors are concerned with + * tagged components. Tagged components also have no order, so there + * is no purpose for IOR Interceptors to have an order. + *

+ * Registration code should avoid using the ORB (i.e., calling + * ORB.init with the provided orb_id). Since + * registration occurs during ORB initialization, results of invocations + * on this ORB while it is in this state are undefined. + * + * @see ORBInitInfo + */ + local interface ORBInitializer { + + /** + * Called during ORB initialization. If it is expected that initial + * services registered by an interceptor will be used by other + * interceptors, then those initial services shall be registered at + * this point via calls to + * ORBInitInfo.register_initial_reference. + * + * @param info provides initialization attributes and operations by + * which Interceptors can be registered. + */ + void pre_init (in ORBInitInfo info); + + /** + * Called during ORB initialization. If a service must resolve initial + * references as part of its initialization, it can assume that all + * initial references will be available at this point. + *

+ * Calling the post_init operations is not the final + * task of ORB initialization. The final task, following the + * post_init calls, is attaching the lists of registered + * interceptors to the ORB. Therefore, the ORB does not contain the + * interceptors during calls to post_init. If an + * ORB-mediated call is made from within post_init, no + * request interceptors will be invoked on that call. + * Likewise, if an operation is performed which causes an IOR to be + * created, no IOR interceptors will be invoked. + * + * @param info provides initialization attributes and + * operations by which Interceptors can be registered. + */ + void post_init (in ORBInitInfo info); + }; +}; diff --git a/omgapi/src/main/idl/Messaging.idl b/omgapi/src/main/idl/Messaging.idl new file mode 100644 index 000000000..5411852ca --- /dev/null +++ b/omgapi/src/main/idl/Messaging.idl @@ -0,0 +1,210 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// File: Messaging.idl +// CORBA 3.0, Chapter 22 + +#ifndef _MESSAGING_IDL_ +#define _MESSAGING_IDL_ + +#define _PRE_3_0_COMPILER_ + +#ifdef _PRE_3_0_COMPILER_ +#pragma prefix "omg.org" +#include +#include +#include +#include +#else +import ::CORBA; +import ::Dynamic; +import ::IOP; +import ::TimeBase; +#endif // _PRE_3_0_COMPILER_ + +// App developers should never have to use this IDL file. The ORB vendor +// should supply an implementation language version of this file, and +// that should be used by app developers if necessary. + +// Most IDL compilers don't accept the "native" keyword in application IDL +// files. In order to compile an IDL (really PIDL) file that has it, the +// following trick can be used: change what the compiler sees. Instead +// of letting the compiler see the keyword "native", use a preprocessor +// definition that results in valid IDL, even if it doesn't yield +// useful stubs and skeletons. Of course, PIDL never results in +// the standard stubs so that's not a problem. +// +// Set the variable _MASK_NATIVE_ in the IDL compiler to enable it to +// parse this file. + +#ifdef _MASK_NATIVE_ +#define native typedef long +#endif // _MASK_NATIVE_ + +module Messaging { + +#ifndef _PRE_3_0_COMPILER_ + typeprefix Messaging "omg.org"; +#endif // _PRE_3_0_COMPILER_ + + typedef short RebindMode; + const RebindMode TRANSPARENT = 0; + const RebindMode NO_REBIND = 1; + const RebindMode NO_RECONNECT = 2; + + typedef short SyncScope; + const SyncScope SYNC_NONE = 0; + const SyncScope SYNC_WITH_TRANSPORT = 1; + const SyncScope SYNC_WITH_SERVER = 2; + const SyncScope SYNC_WITH_TARGET = 3; + + typedef short RoutingType; + const RoutingType ROUTE_NONE = 0; + const RoutingType ROUTE_FORWARD = 1; + const RoutingType ROUTE_STORE_AND_FORWARD =2; + + typedef short Priority; + + typedef unsigned short Ordering; + const Ordering ORDER_ANY = 0x01; + const Ordering ORDER_TEMPORAL = 0x02; + const Ordering ORDER_PRIORITY = 0x04; + const Ordering ORDER_DEADLINE = 0x08; + + // Rebind Policy (default = TRANSPARENT) + const CORBA::PolicyType REBIND_POLICY_TYPE = 23; + + interface RebindPolicy : CORBA::Policy { + readonly attribute RebindMode rebind_mode; + }; + + // Synchronization Policy (default = SYNC_WITH_TRANSPORT) + const CORBA::PolicyType SYNC_SCOPE_POLICY_TYPE = 24; + + interface SyncScopePolicy : CORBA::Policy { + readonly attribute SyncScope synchronization; + }; + + // Priority Policies + const CORBA::PolicyType REQUEST_PRIORITY_POLICY_TYPE = 25; + + struct PriorityRange { + Priority min; + Priority max; + }; + + interface RequestPriorityPolicy : CORBA::Policy { + readonly attribute PriorityRange priority_range; + }; + + const CORBA::PolicyType REPLY_PRIORITY_POLICY_TYPE = 26; + + interface ReplyPriorityPolicy : CORBA::Policy { + readonly attribute PriorityRange priority_range; + }; + + // Timeout Policies + const CORBA::PolicyType REQUEST_START_TIME_POLICY_TYPE = 27; + + interface RequestStartTimePolicy : CORBA::Policy { + readonly attribute TimeBase::UtcT start_time; + }; + + const CORBA::PolicyType REQUEST_END_TIME_POLICY_TYPE = 28; + + interface RequestEndTimePolicy : CORBA::Policy { + readonly attribute TimeBase::UtcT end_time; + }; + + const CORBA::PolicyType REPLY_START_TIME_POLICY_TYPE = 29; + + interface ReplyStartTimePolicy : CORBA::Policy { + readonly attribute TimeBase::UtcT start_time; + }; + + const CORBA::PolicyType REPLY_END_TIME_POLICY_TYPE = 30; + + interface ReplyEndTimePolicy : CORBA::Policy { + readonly attribute TimeBase::UtcT end_time; + }; + + const CORBA::PolicyType RELATIVE_REQ_TIMEOUT_POLICY_TYPE = 31; + + interface RelativeRequestTimeoutPolicy : CORBA::Policy { + readonly attribute TimeBase::TimeT relative_expiry; + }; + + const CORBA::PolicyType RELATIVE_RT_TIMEOUT_POLICY_TYPE = 32; + + interface RelativeRoundtripTimeoutPolicy : CORBA::Policy { + readonly attribute TimeBase::TimeT relative_expiry; + }; + + const CORBA::PolicyType ROUTING_POLICY_TYPE = 33; + + struct RoutingTypeRange { + RoutingType min; + RoutingType max; + }; + + interface RoutingPolicy : CORBA::Policy { + readonly attribute RoutingTypeRange routing_range; + }; + + const CORBA::PolicyType MAX_HOPS_POLICY_TYPE = 34; + + interface MaxHopsPolicy : CORBA::Policy { + readonly attribute unsigned short max_hops; + }; + + // Router Delivery-ordering Policy (default = ORDER_TEMPORAL) + const CORBA::PolicyType QUEUE_ORDER_POLICY_TYPE = 35; + + interface QueueOrderPolicy : CORBA::Policy { + readonly attribute Ordering allowed_orders; + }; + + // Profile components through which policy values are expressed in IORs + + struct PolicyValue { + CORBA::PolicyType ptype; + sequence pvalue; + }; + + typedef sequence PolicyValueSeq; + +#ifdef _SUPPORTS_NATIVE_ + native UserExceptionBase; + valuetype ExceptionHolder { + void raise_exception() raises (UserExceptionBase); + void raise_exception_with_list( + in Dynamic::ExceptionList exc_list) + raises (UserExceptionBase); + private boolean is_system_exception; + private boolean byte_order; + private sequence marshaled_exception; + }; + + // For handling Routing + interface ReplyHandler { }; + + // Generic Poller Valuetype + + valuetype Poller : CORBA::Pollable { + readonly attribute Object operation_target; + readonly attribute string operation_name; + attribute ReplyHandler associated_handler; + readonly attribute boolean is_from_poller; + private Object target; + private string op_name; + }; +#endif +}; // module Messaging +#endif // _MESSAGING_IDL_ diff --git a/omgapi/src/main/idl/SendingContext.idl b/omgapi/src/main/idl/SendingContext.idl new file mode 100644 index 000000000..d94bc7dc4 --- /dev/null +++ b/omgapi/src/main/idl/SendingContext.idl @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// File: SendingContext.idl +// CORBA 2.5.1, Chapter 5 + +#ifndef _SENDING_CONTEXT_IDL_ +#define _SENDING_CONTEXT_IDL_ + +#define _PRE_3_0_COMPILER_ + +#ifdef _PRE_3_0_COMPILER_ +#include +#pragma prefix "omg.org" +#else +import ::CORBA; +#endif // _PRE_3_0_COMPILER_ + +module SendingContext { + +#ifndef _PRE_3_0_COMPILER_ + typeprefix SendingContext "omg.org"; +#endif // _PRE_3_0_COMPILER_ + + interface RunTime {}; // so that we can provide more + // sending context run time + // services in the future + + interface CodeBase: RunTime { + typedef string URL; // blank-separated list of one or more URLs + typedef sequence URLSeq; + typedef sequence ValueDescSeq; + + // Operation to obtain the IR from the sending context + CORBA::Repository get_ir(); + + // Operations to obtain a location of the implementation code + URL implementation( in CORBA::RepositoryId x); + URL implementationx( in CORBA::RepositoryId x); + URLSeq implementations( in CORBA::RepositoryIdSeq x); + + // Operations to obtain complete meta information about a Value + // This is just a performance optimization the IR can provide + // the same information + CORBA::ValueDef::FullValueDescription meta( in CORBA::RepositoryId x); + ValueDescSeq metas(in CORBA::RepositoryIdSeq x); + + // To obtain a type graph for a value type + // same comment as before the IR can provide similar + // information + CORBA::RepositoryIdSeq bases( in CORBA::RepositoryId x); + }; +}; +#endif // _SENDING_CONTEXT_IDL_ diff --git a/omgapi/src/main/idl/TimeBase.idl b/omgapi/src/main/idl/TimeBase.idl new file mode 100644 index 000000000..0938be627 --- /dev/null +++ b/omgapi/src/main/idl/TimeBase.idl @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +//File: TimeBase.idl +//Part of the Time Service +// Note: if your IDL compiler does not yet support the +// "long long" data type, compile this module with the +// preprocessor definition "NOLONGLONG". With many +// compilers this would be done with a qualifier on +// the command line, something like -DNOLONGLONG + +#ifndef _TIME_BASE_IDL_ +#define _TIME_BASE_IDL_ +#pragma prefix "omg.org" + +module TimeBase { + +#ifdef NOLONGLONG + struct ulonglong{ + unsigned long low; + unsigned long high; + }; + typedef ulonglong TimeT; +#else + typedef unsigned long long TimeT; +#endif + + typedef TimeT InaccuracyT; + typedef short TdfT; + struct UtcT { + TimeT time; // 8 octets + unsigned long inacclo; // 4 octets + unsigned short inacchi; // 2 octets + TdfT tdf; // 2 octets + // total 16 octets. + }; + + struct IntervalT { + TimeT lower_bound; + TimeT upper_bound; + }; +}; +#endif /* ifndef _TIME_BASE_IDL_ */ diff --git a/omgapi/src/main/idl/ir.idl b/omgapi/src/main/idl/ir.idl new file mode 100644 index 000000000..58d4fb4fc --- /dev/null +++ b/omgapi/src/main/idl/ir.idl @@ -0,0 +1,691 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * This file contains OMG IDL from CORBA V2.0, July 1995. + * It also contains the TypeCode creation APIs in CORBA::ORB + **/ + +#pragma prefix "omg.org" +//#pragma javaPackage org.omg + +#include + +module CORBA { + typedef string ScopedName; + + interface Contained; + interface Repository; + interface Container; + + interface Contained : IRObject + /** + The Contained Interface is inherited by all Interface Repository + interfaces that are contained by other objects. + */ + { + // read/write interface + + attribute RepositoryId id; + attribute Identifier name; + attribute VersionSpec version; + + // read interface + + readonly attribute Container defined_in; + readonly attribute ScopedName absolute_name; + readonly attribute Repository containing_repository; + + struct Description { + DefinitionKind kind; + any value; + }; + + Description describe (); + + // write interface + + void move ( + in Container new_container, + in Identifier new_name, + in VersionSpec new_version + ); + }; + + + interface ModuleDef; + interface ConstantDef; + interface StructDef; + interface UnionDef; + interface EnumDef; + interface AliasDef; + interface InterfaceDef; + interface ExceptionDef; + interface ValueDef; // orbos 98-01-18: Objects By Value + interface ValueMemberDef; // orbos 98-01-18: Objects By Value + interface ValueBoxDef; // orbos 98-01-18: Objects By Value + interface NativeDef; + + + typedef sequence InterfaceDefSeq; + + + typedef sequence ContainedSeq; + typedef sequence StructMemberSeq; + typedef sequence UnionMemberSeq; + + + typedef sequence EnumMemberSeq; + typedef sequence ValueMemberSeq; + + struct Initializer { + StructMemberSeq members; + }; + typedef sequence InitializerSeq; + + typedef sequence ValueDefSeq; + + // orbos 98-01-18: Objects By Value -- end + + + interface Container : IRObject + /** + The Container interface is used to form a containment hierarchy + in the Interface Repository. A Container can contain any number + of objects derived from the Contained interface. + */ + { + // read interface + + Contained lookup ( in ScopedName search_name); + + ContainedSeq contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + ContainedSeq lookup_name ( + in Identifier search_name, + in long levels_to_search, + in DefinitionKind limit_type, + in boolean exclude_inherited + ); + + struct Description { + Contained contained_object; + DefinitionKind kind; + any value; + }; + + typedef sequence DescriptionSeq; + + DescriptionSeq describe_contents ( + in DefinitionKind limit_type, + in boolean exclude_inherited, + in long max_returned_objs + ); + + // write interface + + ModuleDef create_module ( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + ConstantDef create_constant ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in any value + ); + + StructDef create_struct ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + UnionDef create_union ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType discriminator_type, + in UnionMemberSeq members + ); + + EnumDef create_enum ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in EnumMemberSeq members + ); + + AliasDef create_alias ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type + ); + + ExceptionDef create_exception ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in StructMemberSeq members + ); + + + InterfaceDef create_interface ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_abstract, + in InterfaceDefSeq base_interfaces + ); + + // orbos 98-01-18: Objects By Value + ValueDef create_value( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in boolean is_custom, + in boolean is_abstract, + in octet flags, // must be 0 + in ValueDef base_value, + in boolean has_safe_base, + in ValueDefSeq abstract_base_values, + in InterfaceDefSeq supported_interfaces, + in InitializerSeq initializers + ); + + // orbos 98-01-18: Objects By Value + ValueBoxDef create_value_box( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType original_type_def + ); + + NativeDef create_native( + in RepositoryId id, + in Identifier name, + in VersionSpec version + ); + + }; + + + + + interface PrimitiveDef; + interface StringDef; + interface SequenceDef; + interface ArrayDef; + + enum PrimitiveKind { + pk_null, pk_void, pk_short, pk_long, pk_ushort, pk_ulong, + pk_float, pk_double, pk_boolean, pk_char, pk_octet, + pk_any, pk_TypeCode, pk_Principal, pk_string, pk_objref + }; + + interface Repository : Container + /** + Repository is an interface that provides global access to the + Interface Repository. Repository objects can contain constants, + typedefs, exceptions, interfaces, and modules. + */ + { + // read interface + + Contained lookup_id (in RepositoryId search_id); + + PrimitiveDef get_primitive (in PrimitiveKind kind); + + // write interface + + StringDef create_string (in unsigned long bound); + + SequenceDef create_sequence ( + in unsigned long bound, + in IDLType element_type + ); + + ArrayDef create_array ( + in unsigned long length, + in IDLType element_type + ); + }; + + + interface ModuleDef : Container, Contained + /** + A ModuleDef can contain constants, typedefs, exceptions, interfaces, + and other module objects. + */ + { + }; + + struct ModuleDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + }; + + + interface ConstantDef : Contained + /** + A ConstantDef object defines a named constant. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute any value; + }; + + struct ConstantDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + any value; + }; + + + interface TypedefDef : Contained, IDLType + /** + TypedefDef is an abstract interface used as a base interface for + all named non-object types(structures, unions, enumerations, + aliases). The TypedefDef interface is not inherited by the definition + objects for the primitive or anonymous types. + */ + { + }; + + struct TypeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + interface StructDef : TypedefDef, Container + /** + A StructDef represents an OMG IDL structure definition. + */ + { + attribute StructMemberSeq members; + }; + + + interface UnionDef : TypedefDef, Container + /** + A UnionDef represents an OMG IDL union definition. + */ + { + readonly attribute TypeCode discriminator_type; + attribute IDLType discriminator_type_def; + attribute UnionMemberSeq members; + }; + + + interface EnumDef : TypedefDef + /** + A EnumDef represents an OMG IDL enum definition. + */ + { + attribute EnumMemberSeq members; + }; + + + interface AliasDef : TypedefDef + /** + An AliasDef represents an OMG IDL typedef that aliases other + definition. + */ + { + attribute IDLType original_type_def; + }; + + + interface PrimitiveDef: IDLType + /** + A PrimitiveDef represents one of the IDL primitive types. As + primitive types are unnamed, this interface is not derived from + TypedefDef or Contained. + */ + { + readonly attribute PrimitiveKind kind; + }; + + + interface StringDef : IDLType + /** + A StringDef represents an OMG IDL string type. As string + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + }; + + + interface SequenceDef : IDLType + /** + A SequenceDef represents an OMG IDL sequence type. As sequence + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long bound; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + interface ArrayDef : IDLType + /** + An ArrayDef represents an OMG IDL array type. As array + types are anonymous, this interface is not derived from TypedefDef + or Contained. + */ + { + attribute unsigned long length; + readonly attribute TypeCode element_type; + attribute IDLType element_type_def; + }; + + + interface ExceptionDef : Contained, Container + /** + An ExceptionDef represents an exception definition. + */ + { + readonly attribute TypeCode type; + attribute StructMemberSeq members; + }; + struct ExceptionDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + }; + + + + enum AttributeMode {ATTR_NORMAL, ATTR_READONLY}; + + interface AttributeDef : Contained + /** + An AttributeDef represents the information that defines an + attribute of an interface. + */ + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute AttributeMode mode; + }; + + struct AttributeDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode type; + AttributeMode mode; + }; + + + + enum OperationMode {OP_NORMAL, OP_ONEWAY}; + + enum ParameterMode {PARAM_IN, PARAM_OUT, PARAM_INOUT}; + struct ParameterDescription { + Identifier name; + TypeCode type; + IDLType type_def; + ParameterMode mode; + }; + typedef sequence ParDescriptionSeq; + + typedef Identifier ContextIdentifier; + typedef sequence ContextIdSeq; + + typedef sequence ExceptionDefSeq; + typedef sequence ExcDescriptionSeq; + + interface OperationDef : Contained + /** + An OperationDef represents the information that defines an + operation of an interface. + */ + { + readonly attribute TypeCode result; + attribute IDLType result_def; + attribute ParDescriptionSeq params; + attribute OperationMode mode; + attribute ContextIdSeq contexts; + attribute ExceptionDefSeq exceptions; + }; + + struct OperationDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + TypeCode result; + OperationMode mode; + ContextIdSeq contexts; + ParDescriptionSeq parameters; + ExcDescriptionSeq exceptions; + }; + + + + typedef sequence RepositoryIdSeq; + typedef sequence OpDescriptionSeq; + typedef sequence AttrDescriptionSeq; + + interface InterfaceDef : Container, Contained, IDLType + /** + An InterfaceDef object represents an interface definition. It can + contains constants, typedefs, exceptions, operations, and + attributes. + */ + { + // read/write interface + + attribute InterfaceDefSeq base_interfaces; + attribute boolean is_abstract; + + // read interface + + boolean is_a (in RepositoryId interface_id); + + struct FullInterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + boolean is_abstract; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + RepositoryIdSeq base_interfaces; + TypeCode type; + }; + + FullInterfaceDescription describe_interface(); + + // write interface + + AttributeDef create_attribute ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation ( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + + struct InterfaceDescription { + Identifier name; + RepositoryId id; + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq base_interfaces; + }; + + + // orbos 98-01-18: Objects By Value -- begin + + interface ValueMemberDef : Contained + + /** A ValueMemberDef object represents the public + and private data member definition of a Value type + */ + + { + readonly attribute TypeCode type; + attribute IDLType type_def; + attribute Visibility access; + }; + + interface ValueDef : Container, Contained, IDLType + /** + A ValueDef object represents the definition of the + Value object used to pass the object state + between hosts + */ + + { + // read/write interface + attribute InterfaceDefSeq supported_interfaces; + attribute InitializerSeq initializers; + attribute ValueDef base_value; + attribute ValueDefSeq abstract_base_values; + attribute boolean is_abstract; + attribute boolean is_custom; + attribute octet flags; // always 0 + attribute boolean has_safe_base; + + // read interface + boolean is_a(in RepositoryId value_id); + + struct FullValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + RepositoryId defined_in; + VersionSpec version; + OpDescriptionSeq operations; + AttrDescriptionSeq attributes; + ValueMemberSeq members; + InitializerSeq initializers; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean is_truncatable; + RepositoryId base_value; + TypeCode type; + }; + + FullValueDescription describe_value(); + + // write interface + + ValueMemberDef create_value_member( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type_def, + in Visibility access + ); + + AttributeDef create_attribute( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType type, + in AttributeMode mode + ); + + OperationDef create_operation( + in RepositoryId id, + in Identifier name, + in VersionSpec version, + in IDLType result, + in OperationMode mode, + in ParDescriptionSeq params, + in ExceptionDefSeq exceptions, + in ContextIdSeq contexts + ); + }; + struct ValueDescription { + Identifier name; + RepositoryId id; + boolean is_abstract; + boolean is_custom; + octet flags; // always 0 + RepositoryId defined_in; + VersionSpec version; + RepositoryIdSeq supported_interfaces; + RepositoryIdSeq abstract_base_values; + boolean has_safe_base; + RepositoryId base_value; + }; + + interface ValueBoxDef : IDLType + + /** ValueBoxDef is an interface that reresents a value type with + a single data member inside its state section and no + inheritance or methods. For example, when transmitting a + string or sequence as an actual parameter on an interface + operation or as a data member of a value type that is an + actual parameter, it may be important to preserve any sharing + of the string or sequence within the object graph being + transmitted. Because current IDL data types do not preserve + referential integrity in this way, this requirement is + conveniently handled by using a value type. Value types also + support the transmission of nulls (as a distinguished value), + whereas IDL data types such as string and sequence (which are + mapped to empty strings and sequences) do not. The Java to IDL + mapping requires both preservation of referential integrity + and transmission of nulls. Because it would be cumbersome to + require the full IDL syntax for a value type for this specific + usage, this shorthand notation is introduced to cover this use + of value types for simple containment of a single data member. + */ + + { + attribute IDLType original_type_def; + }; + + // orbos 98-01-18: Objects By Value -- end + + interface NativeDef : TypedefDef { + }; +}; diff --git a/omgapi/src/main/idl/nameservice.idl b/omgapi/src/main/idl/nameservice.idl new file mode 100644 index 000000000..39c912a4d --- /dev/null +++ b/omgapi/src/main/idl/nameservice.idl @@ -0,0 +1,496 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// name.idl - Naming service interface +#pragma prefix "omg.org" + + +/** + * The CORBA COS Naming Service provides the ability to bind a name + * to an object relative to a naming context. A naming context is an + * object that contains a set of name bindings in which each name is unique. + * To resolve a name is to determine the object associated with the name in + * a given context.

+ * + * See http://www.omg.org/technology/documents/formal/naming_service.htm + * for the complete CORBA + * COS Naming Specification.

+ */ +module CosNaming +{ + typedef string Istring; + + /** + * Many of the operations defined on a naming context take names as + * parameters. Names have structure. A name is an ordered sequence of + * components.

+ * + * A name with a single component is called a simple name; a name with + * multiple components is called a compound name. Each component except + * the last is used to name a context; the last component denotes the + * bound object.

+ * + * A name component consists of two attributes: the identifier + * attribute and the kind attribute. Both the identifier attribute and the + * kind attribute are represented as IDL strings. The kind attribute adds + * descriptive power to names in a syntax-independent way. Examples of the + * value of the kind attribute include c_source, object_code, executable, + * postscript, or " ". + */ + struct NameComponent + { + Istring id; + Istring kind; + }; + + /** + * A name is a sequence of name components. + */ + typedef sequence Name; + + /** + * Specifies whether the given binding is for a object (that is not a + * naming context) or for a naming context. + */ + enum BindingType + { + nobject, // name is bound to an object + ncontext // name is bound to a naming context + }; + + /** + * A name-to-object association is called a Binding. + */ + struct Binding + { + Name binding_name; // name + BindingType binding_type; // whether name is bound to an object + // or a naming context + }; + + /** + * List of Bindings. + */ + typedef sequence BindingList; + + /** + * The BindingIterator interface allows a client to iterate through + * the bindings using the next_one or next_n operations. + * + * The bindings iterator is obtained by using the list + * method on the NamingContext. + * @see org.omg.CosNaming.NamingContext#list + */ + interface BindingIterator + { + /** + * This operation returns the next binding. If there are no more + * bindings, false is returned. + * + * @param b the returned binding + */ + boolean next_one(out Binding b); + + /** + * This operation returns at most the requested number of bindings. + * + * @param how_many the maximum number of bindings tro return

+ * + * @param bl the returned bindings + */ + boolean next_n(in unsigned long how_many, + out BindingList bl); + + // Destroy binding iterator + /** + * This operation destroys the iterator. + */ + void destroy(); + }; + +/** + * A naming context is an object that contains a set of name bindings in + * which each name is unique. Different names can be bound to an object + * in the same or different contexts at the same time.

+ * + * See + * CORBA COS + * Naming Specification. + */ + interface NamingContext + { + // Declare exceptions + /** + * Indicates the reason for not able to resolve. + */ + enum NotFoundReason + { + missing_node, + not_context, + not_object + }; + +/** + * Indicates the name does not identify a binding. + */ + exception NotFound + { + NotFoundReason why; + Name rest_of_name; + }; + +/** + * Indicates that the implementation has given up for some reason. + * The client, however, may be able to continue the operation at the + * returned naming context. + */ + exception CannotProceed + { + NamingContext cxt; + Name rest_of_name; + }; + +/** + * Indicates the name is invalid. + */ + exception InvalidName + {}; + +/** + * Indicates an object is already bound to the specified name. Only + * one object can be bound to a particular name in a context. + */ + exception AlreadyBound + {}; + +/** + * Indicates that the Naming Context contains bindings. + */ + exception NotEmpty + {}; + +/** + * Creates a binding of a name and an object in the naming context. + * Naming contexts that are bound using bind do not participate in name + * resolution when compound names are passed to be resolved. + * + * @param n Name of the object

+ * + * @param obj The Object to bind with the given name

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates + * the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * Indicates that the implementation has given up for some reason. + * The client, however, may be able to continue the operation + * at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * Indicates that the name is invalid.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + * Indicates an object is already bound to the specified name.

+ */ + void bind(in Name n, + in Object obj) + raises(NotFound, + CannotProceed, + InvalidName, + AlreadyBound); + +/** + * Names an object that is a naming context. Naming contexts that + * are bound using bind_context() participate in name resolution + * when compound names are passed to be resolved. + * + * @param n Name of the object

+ * + * @param nc NamingContect object to bind with the given name

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has + * given up for some reason. The client, however, may be able to + * continue the operation at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound Indicates an object is already + * bound to the specified name.

+ */ + void bind_context(in Name n, + in NamingContext nc) + raises(NotFound, + CannotProceed, + InvalidName, + AlreadyBound); + +/** + * Creates a binding of a name and an object in the naming context + * even if the name is already bound in the context. Naming contexts + * that are bound using rebind do not participate in name resolution + * when compound names are passed to be resolved. + * + * @param n Name of the object

+ * + * @param obj The Object to rebind with the given name

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has + * given up for some reason. The client, however, may be able to + * continue the operation at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid.

+ */ + void rebind(in Name n, + in Object obj) + raises(NotFound, + CannotProceed, + InvalidName); + +/** + * Creates a binding of a name and a naming context in the naming + * context even if the name is already bound in the context. Naming + * contexts that are bound using rebind_context() participate in name + * resolution when compound names are passed to be resolved. + * + * @param n Name of the object

+ * + * @param nc NamingContect object to rebind with the given name

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has + * given up for some reason. The client, however, may be able to + * continue the operation at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid.

+ */ + void rebind_context(in Name n, + in NamingContext nc) + raises(NotFound, + CannotProceed, + InvalidName); + +/** + * The resolve operation is the process of retrieving an object + * bound to a name in a given context. The given name must exactly + * match the bound name. The naming service does not return the type + * of the object. Clients are responsible for "narrowing" the object + * to the appropriate type. That is, clients typically cast the returned + * object from Object to a more specialized interface. + * + * @param n Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has + * given up for some reason. The client, however, may be able to + * continue the operation at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid.

+ */ + Object resolve(in Name n) + raises(NotFound, + CannotProceed, + InvalidName); + +/** + * The unbind operation removes a name binding from a context. + * + * @param n Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has + * given up for some reason. The client, however, may be able to + * continue the operation at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid.

+ */ + void unbind(in Name n) + raises(NotFound, + CannotProceed, + InvalidName); + +/** + * The list operation allows a client to iterate through a set of + * bindings in a naming context.

+ * + * The list operation returns at most the requested number of + * bindings in BindingList bl. + *

    + *
  • If the naming context contains additional + * bindings, the list operation returns a BindingIterator with the + * additional bindings. + *
  • If the naming context does not contain additional + * bindings, the binding iterator is a nil object reference. + *
+ * + * @param how_many the maximum number of bindings to return

+ * + * @param bl the returned list of bindings

+ * + * @param bi the returned binding iterator

+ */ + void list(in unsigned long how_many, + out BindingList bl, + out BindingIterator bi); + +/** + * This operation returns a naming context implemented by the same + * naming server as the context on which the operation was invoked. + * The new context is not bound to any name. + */ + NamingContext new_context(); + +/** + * This operation creates a new context and binds it to the name + * supplied as an argument. The newly-created context is implemented + * by the same naming server as the context in which it was bound (that + * is, the naming server that implements the context denoted by the + * name argument excluding the last component). + * + * @param n Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound Indicates an object is already + * bound to the specified name.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has + * given up for some reason. The client, however, may be able to + * continue the operation at the returned naming context.

+ * + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid.

+ */ + NamingContext bind_new_context(in Name n) + raises(NotFound, + AlreadyBound, + CannotProceed, + InvalidName); + +/** + * The destroy operation deletes a naming context. If the naming + * context contains bindings, the NotEmpty exception is raised. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotEmpty Indicates that the Naming Context contains bindings. + */ + void destroy() + raises(NotEmpty); + + }; + + +/** + * NamingContextExt is the extension of NamingContext + * which + * contains a set of name bindings in which each name is unique and is + * part of Interoperable Naming Service. + * Different names can be bound to an object in the same or different + * contexts at the same time. Using NamingContextExt, you can use + * URL-based names to bind and resolve.

+ * + * See + * CORBA COS + * Naming Specification. + */ + interface NamingContextExt: NamingContext + { +/** + * StringName is the Stringified Name, Array of Name Components + * represented as a String. + */ + typedef string StringName; + +/** + * Address is the Host and Port information represented as a String. + */ + typedef string Address; + +/** + * URLString is the URL address (corbaloc: or corbaname:) represented as + * a String. + */ + typedef string URLString; + +/** + * This operation creates a stringified name from the array of Name + * components. + * + * @param n Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName + * Indicates the name does not identify a binding.

+ * + */ + StringName to_string( in Name n ) raises (InvalidName); + +/** + * This operation converts a Stringified Name into an equivalent array + * of Name Components. + * + * @param sn Stringified Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName + * Indicates the name does not identify a binding.

+ * + */ + Name to_name( in StringName sn ) raises (InvalidName); + + +/** + * Indicates the invalid Stringified name for the object, The + * reason could be invalid syntax. + */ + exception InvalidAddress + { }; + +/** + * This operation creates a URL based "iiopname://" format name + * from the Stringified Name of the object. + * + * @param addr internet based address of the host machine where Name Service is running

+ * @param sn Stringified Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName + * Indicates the name does not identify a binding.

+ * @exception org.omg.CosNaming.NamingContextPackage.InvalidAddress + * Indicates the internet based address of the host machine is + * incorrect

+ * + */ + URLString to_url( in Address addr, in StringName sn ) + raises( InvalidAddress, InvalidName ); + + +/** + * This operation resolves the Stringified name into the object + * reference. + * + * @param sn Stringified Name of the object

+ * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * Indicates there is no object reference for the given name.

+ * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * Indicates that the given compound name is incorrect

+ * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName + * Indicates the name does not identify a binding.

+ * + */ + Object resolve_str( in StringName sn) + raises( NotFound, CannotProceed, + InvalidName); + + }; + +}; diff --git a/omgapi/src/main/idl/poa.idl b/omgapi/src/main/idl/poa.idl new file mode 100644 index 000000000..926952b92 --- /dev/null +++ b/omgapi/src/main/idl/poa.idl @@ -0,0 +1,1176 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "corba.idl" +#include "CORBAX.idl" + +#pragma prefix "omg.org" +/** + * All Mapping corresponds to the Chapter 11 of + * CORBA V2.3.1 specified by OMG document formal/99-10-07.pdf. + * The exception to this is the id attribute, which is added in ptc/00-08-06, + * section 11.3.8.26. + */ +module PortableServer { + + #pragma version PortableServer 2.3 + + // forward reference + interface POA; + + /** + * List of POAs + */ + typedef sequence POAList; + + /** + * Values of type Servant support a language specific + * programming interface that can be used by the ORB to + * obtain a default POA for that servant. + * Some language mappings may allow Servant values to + * be implicitly converted to object references under + * appropriate conditions. + */ + native Servant; + + /** + * ObjectId value associated with the object reference. + */ + typedef sequence ObjectId; + + /** + * ForwardRequest to indicate to the ORB + * that it is responsible for delivering + * the current request and subsequent + * requests to the object denoted in the + * forward_reference member of the exception. + */ + exception ForwardRequest { Object forward_reference; }; + + // ********************************************** + // + // Policy interfaces + // + // ********************************************** + + /** + * The value representing THREAD_POLICY_ID. + */ + const CORBA::PolicyType THREAD_POLICY_ID = 16; + /** + * The value representing LIFESPAN_POLICY_ID. + */ + const CORBA::PolicyType LIFESPAN_POLICY_ID = 17; + /** + * The value representing ID_UNIQUENESS_POLICY_ID. + */ + const CORBA::PolicyType ID_UNIQUENESS_POLICY_ID = 18; + /** + * The value representing ID_ASSIGNMENT_POLICY_ID. + */ + const CORBA::PolicyType ID_ASSIGNMENT_POLICY_ID = 19; + /** + * The value representing IMPLICIT_ACTIVATION_POLICY_ID. + */ + const CORBA::PolicyType IMPLICIT_ACTIVATION_POLICY_ID = 20; + /** + * The value representing SERVANT_RETENTION_POLICY_ID. + */ + const CORBA::PolicyType SERVANT_RETENTION_POLICY_ID = 21; + /** + * The value representing REQUEST_PROCESSING_POLICY_ID. + */ + const CORBA::PolicyType REQUEST_PROCESSING_POLICY_ID = 22; + + /** + * The ThreadPolicyValue can have the following values. + * ORB_CTRL_MODEL - The ORB is responsible for assigning + * requests for an ORB- controlled POA to threads. + * SINGLE_THREAD_MODEL - Requests for a single-threaded + * POA are processed sequentially. + */ + enum ThreadPolicyValue { ORB_CTRL_MODEL, SINGLE_THREAD_MODEL }; + + /** + * The ThreadPolicy specifies the threading model + * used with the created POA. The default is + * ORB_CTRL_MODEL. + */ + interface ThreadPolicy : CORBA::Policy { + #pragma sun_local ThreadPolicy "" + /** + * specifies the policy value + */ + readonly attribute ThreadPolicyValue value; + }; + + /** + * The LifespanPolicyValue can have the following values. + * TRANSIENT - The objects implemented in the POA + * cannot outlive the POA instance in which they are + * first created. + * PERSISTENT - The objects implemented in the POA can + * outlive the process in which they are first created. + */ + enum LifespanPolicyValue { TRANSIENT, PERSISTENT }; + + /** + * The LifespanPolicy specifies the lifespan of the + * objects implemented in the created POA. The default + * is TRANSIENT. + */ + interface LifespanPolicy : CORBA::Policy { + #pragma sun_local LifespanPolicy "" + /** + * specifies the policy value + */ + readonly attribute LifespanPolicyValue value; + }; + + /** + * IdUniquenessPolicyValue can have the following values. + * UNIQUE_ID - Servants activated with that POA support + * exactly one Object Id. MULTIPLE_ID - a servant + * activated with that POA may support one or more + * Object Ids. + */ + enum IdUniquenessPolicyValue { UNIQUE_ID, MULTIPLE_ID }; + + /** + * The IdUniquenessPolicy specifies whether the servants + * activated in the created POA must have unique object i + * identities. The default is UNIQUE_ID. + */ + interface IdUniquenessPolicy : CORBA::Policy { + #pragma sun_local IdUniquenessPolicy "" + /** + * specifies the policy value + */ + readonly attribute IdUniquenessPolicyValue value; + }; + + /** + * The IdAssignmentPolicyValue can have the following + * values. USER_ID - Objects created with that POA are + * assigned Object Ids only by the application. + * SYSTEM_ID - Objects created with that POA are + * assigned Object Ids only by the POA. If the POA also + * has the PERSISTENT policy, assigned Object Ids must + * be unique across all instantiations of the same POA. + */ + enum IdAssignmentPolicyValue { USER_ID, SYSTEM_ID }; + + /** + * IdAssignmentPolicy specifies whether Object Ids in + * the created POA are generated by the application or + * by the ORB. The default is SYSTEM_ID. + */ + interface IdAssignmentPolicy : CORBA::Policy { + #pragma sun_local IdAssignmentPolicy "" + /** + * specifies the policy value + */ + readonly attribute IdAssignmentPolicyValue value; + }; + + /** + * ImplicitActivationPolicyValue has the following + * semantics. + * IMPLICIT_ACTIVATION to indicate implicit activation + * of servants. This requires SYSTEM_ID and RETAIN + * policies to be set. + * NO_IMPLICIT_ACTIVATION to indicate no implicit + * servant activation. + */ + enum ImplicitActivationPolicyValue { + IMPLICIT_ACTIVATION, NO_IMPLICIT_ACTIVATION + }; + + /** + * This policy specifies whether implicit activation + * of servants is supported in the created POA. + */ + interface ImplicitActivationPolicy : CORBA::Policy { + #pragma sun_local ImplicitActivationPolicy "" + /** + * specifies the policy value + */ + readonly attribute ImplicitActivationPolicyValue value; + }; + + /** + * ServantRetentionPolicyValue can have the following + * values. RETAIN - to indicate that the POA will retain + * active servants in its Active Object Map. + * NON_RETAIN - to indicate Servants are not retained by + * the POA. If no ServantRetentionPolicy is specified at + * POA creation, the default is RETAIN. + */ + enum ServantRetentionPolicyValue { RETAIN, NON_RETAIN }; + + /** + * This policy specifies whether the created POA retains + * active servants in an Active Object Map. + */ + interface ServantRetentionPolicy : CORBA::Policy { + #pragma sun_local ServantRetentionPolicy "" + /** + * specifies the policy value + */ + readonly attribute ServantRetentionPolicyValue value; + }; + + /** + * The RequestProcessingPolicyValue can have the following + * values. USE_ACTIVE_OBJECT_MAP_ONLY - If the Object Id + * is not found in the Active Object Map, + * an OBJECT_NOT_EXIST exception is returned to the + * client. The RETAIN policy is also required. + * USE_DEFAULT_SERVANT - If the Object Id is not found in + * the Active Object Map or the NON_RETAIN policy is + * present, and a default servant has been registered + * with the POA using the set_servant operation, + * the request is dispatched to the default servant. + * USE_SERVANT_MANAGER - If the Object Id is not found + * in the Active Object Map or the NON_RETAIN policy + * is present, and a servant manager has been registered + * with the POA using the set_servant_manager operation, + * the servant manager is given the opportunity to + * locate a servant or raise an exception. + */ + enum RequestProcessingPolicyValue { + USE_ACTIVE_OBJECT_MAP_ONLY, USE_DEFAULT_SERVANT, USE_SERVANT_MANAGER + }; + + /** + * This policy specifies how requests are processed by + * the created POA. The default is + * USE_ACTIVE_OBJECT_MAP_ONLY. + */ + interface RequestProcessingPolicy : CORBA::Policy { + #pragma sun_local RequestProcessingPolicy "" + /** + * specifies the policy value + */ + readonly attribute RequestProcessingPolicyValue value; + }; + + + // ************************************************** + // + // POAManager interface + // + // ********************************** + /** + * Each POA object has an associated POAManager object. + * A POA manager may be associated with one or more + * POA objects. A POA manager encapsulates the processing + * state of the POAs it is associated with. + */ + interface POAManager { + #pragma sun_local POAManager "" + exception AdapterInactive{ }; + /** + * Specifies the states for the POAManager + */ + enum State {HOLDING, ACTIVE, DISCARDING, INACTIVE}; + + /** + * This operation changes the state of the POA manager + * to active, causing associated POAs to start processing + * requests. + * @exception AdapterInactive is raised if the operation is + * invoked on the POAManager in inactive state. + */ + void activate() + raises(AdapterInactive); + /** + * This operation changes the state of the POA manager + * to holding, causing associated POAs to queue incoming + * requests. + * @param wait_for_completion if FALSE, the operation + * returns immediately after changing state. + * If TRUE, it waits for all active requests + * to complete. + * @exception AdapterInactive is raised if the operation is + * invoked on the POAManager in inactive state. + */ + void hold_requests(in boolean wait_for_completion) + raises(AdapterInactive); + /** + * This operation changes the state of the POA manager + * to discarding. This causes associated POAs to discard + * incoming requests. + * @param wait_for_completion if FALSE, the operation + * returns immediately after changing state. + * If TRUE, it waits for all active requests + * to complete. + * @exception AdapterInactive is raised if the operation is + * invoked on the POAManager in inactive state. + */ + void discard_requests(in boolean wait_for_completion) + raises(AdapterInactive); + + /** + * This operation changes the state of the POA manager + * to inactive, causing associated POAs to reject the + * requests that have not begun executing as well as + * as any new requests. + * @param etherealize_objects a flag to indicate whether + * to invoke the etherealize operation of the + * associated servant manager for all active + * objects. + * @param wait_for_completion if FALSE, the operation + * returns immediately after changing state. + * If TRUE, it waits for all active requests + * to complete. + * @exception AdapterInactive is raised if the operation is + * invoked on the POAManager in inactive state. + */ + void deactivate(in boolean etherealize_objects, + in boolean wait_for_completion) + raises(AdapterInactive); + /** + * This operation returns the state of the POA manager. + */ + State get_state(); + }; + + + // ************************************************** + // + // AdapterActivator interface + // + // **************************** + + /** + * An adapter activator supplies a POA with the ability + * to create child POAs on demand, as a side-effect of + * receiving a request that names the child POA + * (or one of its children), or when find_POA is called + * with an activate parameter value of TRUE. + */ + + interface AdapterActivator { + #pragma sun_local AdapterActivator "" + #pragma version AdapterActivator 2.3 + /** + * This operation is invoked when the ORB receives + * a request for an object reference that identifies + * a target POA that does not exist. The ORB invokes + * this operation once for each POA that must be + * created in order for the target POA to exist. + * @param parent indicates the parent POA for the POA + * that needs to be created. + * @param name identifies the name of the POA relative to + * the parent. + * @return returns TRUE if the POA was created or FALSE + * otherwise. + */ + boolean unknown_adapter(in POA parent, in string name); + }; + + + // ************************************************** + // + // ServantManager interface + // + // ****************************** + + /** + * A servant manager supplies a POA with the ability + * to activate objects on demand when the POA receives + * a request targeted at an inactive object. A servant + * manager is registered with a POA as a callback object, + * to be invoked by the POA when necessary. + * ServantManagers can either be ServantActivators or + * ServantLocators. A ServantManager object must be + * local to the process containing the POA objects + * it is registered with. + */ + + interface ServantManager + { #pragma sun_local ServantManager "" }; + + + /** + * When the POA has the RETAIN policy it uses servant + * managers that are ServantActivators. + */ + interface ServantActivator : ServantManager { + #pragma version ServantActivator 2.3 + #pragma sun_localservant ServantActivator "" + /** + * This operation is invoked by the POA whenever the + * POA receives a request for an object that is not + * currently active, assuming the POA has the + * USE_SERVANT_MANAGER and RETAIN policies. + * @param oid object Id associated with the object on + * the request was made. + * @param adapter object reference for the POA in which + * the object is being activated. + * @return Servant corresponding to oid is created or + * located by the user supplied servant manager. + * @exception ForwardRequest to indicate to the ORB + * that it is responsible for delivering + * the current request and subsequent + * requests to the object denoted in the + * forward_reference member of the exception. + */ + Servant incarnate ( in ObjectId oid, in POA adapter ) + raises (ForwardRequest); + /** + * This operation is invoked whenever a servant for + * an object is deactivated, assuming the POA has + * the USE_SERVANT_MANAGER and RETAIN policies. + * @param oid object Id associated with the object + * being deactivated. + * @param adapter object reference for the POA in which + * the object was active. + * @param serv contains reference to the servant + * associated with the object being deactivated. + * @param cleanup_in_progress if TRUE indicates that + * destroy or deactivate is called with + * etherealize_objects param of TRUE. FALSE + * indicates that etherealize was called due to + * other reasons. + * @param remaining_activations indicates whether the + * Servant Manager can destroy a servant. If + * set to TRUE, the Servant Manager should wait + * until all invocations in progress have + * completed. + */ + void etherealize ( in ObjectId oid, + in POA adapter, + in Servant serv, + in boolean cleanup_in_progress, + in boolean remaining_activations); + }; + + + /** + * When the POA has the NON_RETAIN policy it uses servant + * managers that are ServantLocators. Because the POA + * knows that the servant returned by this servant + * manager will be used only for a single request, + * it can supply extra information to the servant + * manager's operations and the servant manager's pair + * of operations may be able to cooperate to do + * something different than a ServantActivator. + * When the POA uses the ServantLocator interface, + * immediately after performing the operation invocation + * on the servant returned by preinvoke, the POA will + * invoke postinvoke on the servant manager, passing the + * ObjectId value and the Servant value as parameters + * (among others). This feature may be used to force + * every request for objects associated with a POA to + * be mediated by the servant manager. + */ + interface ServantLocator : ServantManager { + #pragma sun_localservant ServantLocator "" + /** + * Opaque data used to pass the information from + * preinvoke to postinvoke hooks. This specific + * by the language mapping, that is why it is + * specified as native. + */ + native Cookie; + /** + * This operations is used to get a servant that will be + * used to process the request that caused preinvoke to + * be called. + * @param oid the object id associated with object on + * which the request was made. + * @param adapter the reference for POA in which the + * object is being activated. + * @param operation the operation name. + * @param the_cookie an opaque value that can be set + * by the servant manager to be used + * during postinvoke. + * @return Servant used to process incoming request. + * @exception ForwardRequest to indicate to the ORB + * that it is responsible for delivering + * the current request and subsequent + * requests to the object denoted in the + * forward_reference member of the exception. + */ + Servant preinvoke( in ObjectId oid, in POA adapter, + in CORBA::Identifier operation, + out Cookie the_cookie ) + raises (ForwardRequest); + /** + * This operation is invoked whenener a servant completes + * a request. + * @param oid the object id ssociated with object on which + * the request was made. + * @param adapter the reference for POA in which the + * object was active. + * @param the_cookie an opaque value that contains + * the data set by preinvoke. + * @param the_servant reference to the servant that is + * associated with the object. + */ + void postinvoke( in ObjectId oid, in POA adapter, + in CORBA::Identifier operation, + in Cookie the_cookie, + in Servant the_servant); + }; + + + // ************************************************** + // + // POA interface + // + // ***************************************** + + /** + * A POA object manages the implementation of a + * collection of objects. The POA supports a name space + * for the objects, which are identified by Object Ids. + * A POA also provides a name space for POAs. A POA is + * created as a child of an existing POA, which forms a + * hierarchy starting with the root POA. A POA object + * must not be exported to other processes, or + * externalized with ORB::object_to_string. + */ + interface POA { + #pragma sun_local POA "" + #pragma version POA 2.3 + /** + * specifies that an child POA with the specified + * name already exists. + */ + exception AdapterAlreadyExists { }; + + /** + * This is raised if the POA with a specified Name cannot + * be found. + */ + exception AdapterNonExistent { }; + + /** + * This is raised if any of the policy objects are + * not valid for the ORB + */ + exception InvalidPolicy { + unsigned short index; + }; + + /** + * This is raised if no default servant is associated + * with the POA. + */ + exception NoServant { }; + + /** + * specifies that an object is already active or + * exists in the Active Object Map. + */ + exception ObjectAlreadyActive { }; + /** + * specifies that the object is not active or its + * mapping does not exist in the Active Object Map. + */ + + exception ObjectNotActive { }; + + /** + * This is raised when an attempt is made to activate + * a servant that is already active or has a mapping in + * the Active Object Map. + */ + exception ServantAlreadyActive { }; + + /** + * This is raised when an attempt is made to access a + * servant that is not active or is not registered in + * the Active Object Map. + */ + exception ServantNotActive { }; + + /** + * This is raised if the reference was not created by + * the POA + * specified in the reference. + */ + exception WrongAdapter { }; + + /** + * WrongPolicy is specified when the POA does not + * specify the policy appropriate for its operations. + */ + exception WrongPolicy { }; + + + //---------------------------------------- + // + // POA creation and destruction + // + //------------------------------- + + /** + * This operation creates a new POA as a child of the + * target POA. + * @param adapter_name identifies the new POA with + * respect to other POAs with the same parent POA. + * @param a_POAManager specifies the POA Manager to be + * associated with the new POA. + * @param policies specifies policy objects to be + * associated with the POA to control its behavior. + * @exception AdapterAlreadyExists specifies that the + * target POA already has a child POA with + * the specified name. + * @exception InvalidPolicy is raised if any of the + * policy objects are not valid for the ORB, + * or are in conflict, or require an + * administrative action that has not been + * performed. + */ + POA create_POA(in string adapter_name, + in POAManager a_POAManager, + in CORBA::PolicyList policies) + raises (AdapterAlreadyExists, InvalidPolicy); + + /** + * If the target POA is the parent of a child POA with + * the specified name (relative to the target POA), that + * child POA is returned. + * @param adapter_name POA name to be found. + * @param activate_it if a POA with the specified + * name does not exist and the value of + * the activate_it parameter is TRUE, the target + * POA's AdapterActivator, if one exists, + * is invoked. + * @return POA if one exists or is activated by the + * AdapterActivator. + * @return AdapterNonExistent is raised if POA with + * a specified name cannot be found or + * activated using AdapaterActivator. + */ + POA find_POA(in string adapter_name, + in boolean activate_it) + raises (AdapterNonExistent); + + /** + * This operation destroys the POA and all descendant + * POAs. All descendant POAs are destroyed (recursively) + * before the destruction of the containing POA. The POA + * so destroyed (that is, the POA with its name) may be + * re-created later in the same process. + * @param etherealize_objects flag to indicate whether + * etherealize operation on servant manager needs + * to be called. + * @param wait_for_completion flag to indicate whether + * POA and its children need to wait for active + * requests and the etherealization to complete. + * + */ + void destroy( in boolean etherealize_objects, + in boolean wait_for_completion); + + // ************************************************** + // + // Factories for Policy objects + // + // ************ + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return ThreadPolcy Object + */ + ThreadPolicy create_thread_policy( + in ThreadPolicyValue value); + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return LifespanPolicy Object. + */ + LifespanPolicy create_lifespan_policy( + in LifespanPolicyValue value); + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return IdUniquenessPolicy Object. + */ + IdUniquenessPolicy create_id_uniqueness_policy( + in IdUniquenessPolicyValue value); + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return IdAssignmentPolicy Object. + */ + IdAssignmentPolicy create_id_assignment_policy( + in IdAssignmentPolicyValue value); + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return ImplicitActivationPolicy Object. + */ + ImplicitActivationPolicy create_implicit_activation_policy( + in ImplicitActivationPolicyValue value); + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return ServantRetentionPolicy Object. + */ + ServantRetentionPolicy create_servant_retention_policy( + in ServantRetentionPolicyValue value); + /** + * These operations each return a reference to a policy + * object with the specified value. + * @param value policy type + * @return RequestProcessingPolicy Object. + */ + + RequestProcessingPolicy create_request_processing_policy( + in RequestProcessingPolicyValue value); + + //-------------------------------------------------- + // + // POA attributes + // + //----------------------------------- + /** + * This attribute identifies the POA relative to its + * parent. This name is assigned when the POA is created. + */ + readonly attribute string the_name; + /** + * This attribute identifies the parent of the POA. + * The parent of the root POA is null. + */ + readonly attribute POA the_parent; + /** + * This attribute identifies the current set of all + * child POAs of the POA. The set of child POAs + * includes only the POA's immediate children, and + * not their descendants. + */ + readonly attribute POAList the_children; + /** + * This attribute identifies the POA manager + * associated with the POA. + */ + readonly attribute POAManager the_POAManager; + + /** + * This attribute identifies the adapter activator + * associated with the POA. + */ + attribute AdapterActivator the_activator; + + //-------------------------------------------------- + // + // Servant Manager registration: + // + //-------------------------------------------------- + /** + * + * If the ServantRetentionPolicy of the POA is RETAIN, + * then the ServantManager argument (imgr) shall support + * the ServantActivator interface. For a NON_RETAIN policy, + * the ServantManager shall support the ServantLocator + * interface. If the argument is nil, or does not support + * the required interface, then the OBJ_ADAPTER + * exception is raised. + * @return ServantManager associated with a POA or null if + * none exists. + * @exception WrongPolicy raised if the + * USE_SERVANT_MANAGER policy is not specified. + */ + ServantManager get_servant_manager() + raises (WrongPolicy); + /** + * + * This operation sets the default servant manager + * associated with the POA. This operation may only be + * invoked once after a POA has been created. Attempting + * to set the servant manager after one has already + * been set will result in the BAD_INV_ORDER exception + * being raised. + * @param imgr servant manager to be used as a default. + * @exception WrongPolicy raised if the + * USE_SERVANT_MANAGER policy is not specified. + */ + void set_servant_manager( in ServantManager imgr) + raises (WrongPolicy); + + //-------------------------------------------------- + // + // operations for the USE_DEFAULT_SERVANT policy + // + //---------- + /** + * This operation returns the default servant associated + * with the POA. + * @return p_servant default servant associated with a POA. + * @exception NoServant raised if no default servant is + * associated with the POA. + * @exception WrongPolicy raised if the + * USE_DEFAULT_SERVANT policy is not specified. + */ + Servant get_servant() + raises (NoServant, WrongPolicy); + + /** + * + * This operation registers the specified servant with + * the POA as the default servant. This servant will + * be used for all requests for which no servant is + * found in the Active Object Map. + * @param p_servant servant to be used as a default. + * @exception WrongPolicy raised if the + * USE_DEFAULT_SERVANT policy is not specified. + */ + void set_servant(in Servant p_servant) + raises (WrongPolicy); + + // ************************************************** + // + // object activation and deactivation + // + // ************ + + /** + * + * This operation generates an Object Id and enters + * the Object Id and the specified servant in the + * Active Object Map. + * @param p_servant servant to be associated with an + * object to be activated. + * @return POA generated object id. + * @exception ServantAlreadyActive is raised if the + * POA has UNIQUE_ID policy and servant is + * is already in the Active Object Map. + * @exception WrongPolicy raised if the SYSTEM_ID and + * RETAIN policies are not specified. + */ + ObjectId activate_object( in Servant p_servant ) + raises (ServantAlreadyActive, WrongPolicy); + /** + * This operation enters an association between the + * specified Object Id and the specified servant in the + * Active Object Map. + * @param id object id for the object to be activated. + * @param p_servant servant to be associated with the + * object. + * @exception ServantAlreadyActive raised if the POA + * has the UNIQUE_ID policy and the servant + * is already in the Active Object Map. + * @exception ObjectAlreadyActive raised if the object is + * already active in the POA. + * @exception WrongPolicy raised if the RETAIN policy is + * is not specified. + */ + + void activate_object_with_id( in ObjectId id, + in Servant p_servant) + raises ( ServantAlreadyActive, ObjectAlreadyActive, + WrongPolicy); + /** + * + * This operation causes the ObjectId specified in the + * oid parameter to be deactivated. An ObjectId which + * has been deactivated continues to process requests + * until there are no active requests for that ObjectId. + * A deactivated ObjectId is removed from the Active + * Object Map when all requests executing for that + * ObjectId have completed. + * @param oid Object Id for the object to be deactivated. + * @exception ObjectNotActive if the object with the + * specified oid is not in the Active Object + * Map. + * @exception WrongPolicy raised if the RETAIN policy is + * is not specified. + */ + void deactivate_object(in ObjectId oid) + raises (ObjectNotActive, WrongPolicy); + + // ************************************************** + // + // reference creation operations + // + // ***************** + /** + * This operation creates an object reference that + * encapsulates a POA-generated Object Id value and + * the specified interface repository id. + * + * @param intf rep id for creating an object reference. + * @return object reference created using intf. + * @exception WrongPolicy if SYSTEM_ID policy is not + * specified. + */ + Object create_reference ( in CORBA::RepositoryId intf ) + raises (WrongPolicy); + + /** + * This operation creates an object reference that + * encapsulates the specified Object Id and interface + * repository Id values. It does not cause an activation + * to take place. The resulting reference may be passed + * to clients, so that subsequent requests on those + * references will cause the object to be activated + * if necessary, or the default servant used, depending + * on the applicable policies. + * @param oid object id for creating an objref + * @param intf rep id for creating an objref + * @return object reference created using oid and intf + * @exception BAD_PARAM is raised if the POA has the + * SYSTEM_ID policy and it detects that the + * Object Id value was not generated by the + * system or for this POA. + */ + Object create_reference_with_id ( in ObjectId oid, + in CORBA::RepositoryId intf ); + // not specified in 11.3.8.19 raises (WrongPolicy); + + //-------------------------------------------------- + // + // Identity mapping operations: + // + //-------------------------------------------------- + /** + * This operation has four possible behaviors. + * 1. If the POA has the UNIQUE_ID policy and the + * specified servant is active, the Object Id associated + * with that servant is returned. + * 2. If the POA has the IMPLICIT_ACTIVATION policy and + * either the POA has the MULTIPLE_ID policy or the + * specified servant is not active, the servant is + * activated using a POA-generated Object Id and the + * Interface Id associated with the servant, and that + * Object Id is returned. + * 3. If the POA has the USE_DEFAULT_SERVANT policy, + * the servant specified is the default servant, and the + * operation is being invoked in the context of executing + * a request on the default servant, then the ObjectId + * associated with the current invocation is returned. + * 4. Otherwise, the ServantNotActive exception is raised. + * + * @param p_servant servant for which the object disi returned. + * @return object id associated with the servant. + * @exception ServantNotActive if the above rules and + * policy combination is not met. + * @exception WrongPolicy if the USE_DEFAULT_SERVANT policy + * or a combination of the RETAIN policy and + * either the UNIQUE_ID or IMPLICIT_ACTIVATION + * policies are not present. + */ + ObjectId servant_to_id(in Servant p_servant) + raises (ServantNotActive, WrongPolicy); + + /** + * This operation requires the RETAIN policy and either + * the UNIQUE_ID or IMPLICIT_ACTIVATION policies if + * invoked outside the context of an operation dispatched + * by this POA. It has four possible behaviors. + * 1. If the POA has both the RETAIN and the + * UNIQUE_ID policy and the specified servant is active, + * an object reference encapsulating the information used + * to activate the servant is returned. + * 2. If the POA has both the RETAIN and the + * IMPLICIT_ACTIVATION policy and either the POA has the + * MULTIPLE_ID policy or the specified servant is not + * active, the servant is activated using a POA-generated + * Object Id and the Interface Id associated with the + * servant, and a corresponding object reference is + * returned. + * 3. If the operation was invoked in the context of + * executing a request on the specified servant, the + * reference associated with the current invocation + * is returned. + * 4. Otherwise, the ServantNotActive exception is raised. + * + * @param p_servant servant for which the object reference + * needs to be obtained. + * @return object reference associated with the servant. + * @exception WrongPolicy if the operation is not invoked + * in the context of executing a request on + * the specified servant and the required + * policies are not present. + * @exception ServantNotActive if the above specified + * policies and rules are not met. + */ + Object servant_to_reference(in Servant p_servant) + raises (ServantNotActive, WrongPolicy); + + /** + * If the POA has the RETAIN policy and the specified + * object is present in the Active Object Map, this + * operation returns the servant associated with that + * object in the Active Object Map. Otherwise, if the + * POA has the USE_DEFAULT_SERVANT policy and a default + * servant has been registered with the POA, this + * operation returns the default servant. If the object + * reference was not created by this POA, + * the WrongAdapter exception is raised. (OMG Issue + * on inconsistency with the POA.IDL. + * + * @param reference object reference for which the + * servant is returned. + * @return servant associated with the reference. + * @exception WrongPolicy if neither the RETAIN policy or + * the USE_DEFAULT_SERVANT policy is present. + * @exception ObjectNotActive if the servant is not + * present in the Active Object Map (for RETAIN) + * or no default servant is registered (for + * USE_DEFAULT_POLICY). + * @exception WrongAdapter if reference was not created by + * this POA instance. + */ + Servant reference_to_servant(in Object reference) + raises (ObjectNotActive, WrongPolicy, WrongAdapter); + + /** + * This operation returns the Object Id value + * encapsulated by the specified reference. This + * operation is valid only if the reference was created + * by the POA on which the operation is being performed. + * The object denoted by the reference does not have + * to be active for this operation to succeed. + * + * @param reference the object reference from which the + * object id needs to be returned. + * @return object id encapsulated in the reference. + * @exception WrongAdapter if the reference was not + * created by the POA specified in the + * reference. + * @exception WrongPolicy declared to allow future + * extensions. + * + */ + ObjectId reference_to_id(in Object reference) + raises (WrongAdapter, WrongPolicy); + + /** + * If the POA has the RETAIN policy and the specified + * ObjectId is in the Active Object Map, this operation + * returns the servant associated with that object in + * the Active Object Map. Otherwise, if the POA has + * the USE_DEFAULT_SERVANT policy and a default servant + * has been registered with the POA, this operation + * returns the default servant. + * + * @param oid object id for the which the servant is + * returned. + * @return servant associated with oid. + * @exception ObjectNotActive is raised if ObjectId is + * is not in the Active Object Map (for RETAIN + * policy), or no default servant is registered + * (for USE_DEFAULT_SERVANT policy). + * + * @exception WrongPolicy is raised if the RETAIN policy + * or the USE_DEFAULT_SERVANT + * policy is not present. + */ + Servant id_to_servant(in ObjectId oid) + raises (ObjectNotActive, WrongPolicy); + + /** + * If an object with the specified Object Id value is + * currently active, a reference encapsulating the + * information used to activate the object is returned. + * + * @param oid id of the object for which the + * reference is returned. + * @return the object reference + * + * @exception ObjectNotActive if the Object Id value + * is not active in the POA. + * @exception WrongPolicy if the RETAIN policy is not + * present. + */ + Object id_to_reference(in ObjectId oid) + raises (ObjectNotActive, WrongPolicy); + + /** + * This returns the unique id of the POA in the process in which it + * is created. It is for use by portable interceptors. + *

+ * This id is guaranteed unique for the life span of the POA in the + * process. For persistent POAs, this means that if a POA is created + * in the same path with the same name as another POA, these POAs + * are identical and, therefore, have the same id. For transient + * POAs, each POA is unique. + */ + readonly attribute ::org::omg::CORBA::OctetSeq id; + + }; + + // ***************************************************** + // + // Current interface: + // + // ***************************************************** + + /** + * The PortableServer::Current interface, derived from + * CORBA::Current, provides method implementations with + * access to the identity of the object on which the + * method was invoked. The Current interface is provided + * to support servants that implement multiple objects, + * but can be used within the context of POA-dispatched + * method invocations on any servant. To provide location + * transparency, ORBs are required to support use of + * Current in the context of both locally and remotely + * invoked operations. An instance of Current can be + * obtained by the application by issuing the + * CORBA::ORB::resolve_initial_references("POACurrent") + * operation. Thereafter, it can be used within the + * context of a method dispatched by the POA to obtain + * the POA and ObjectId that identify the object on + * which that operation was invoked. + */ + interface Current : CORBA::Current { + #pragma sun_local Current "" + #pragma version Current 2.3 + /** + * The exception that is used to indicate that the + * operation is invoked outside the context of the + * POA-dispatched operation. + */ + + exception NoContext { }; + + /** + * Returns reference to the POA implementing the + * object in whose context it is called. + * + * @return The poa implementing the object + * + * @exception NoContext is raised when the operation is + * outside the context of a POA-dispatched + * operation + */ + POA get_POA() + raises (NoContext); + + /** + * Returns the ObjectId identifying the object in + * whose context it is called. + * + * @return the ObjectId of the object + * + * @exception NoContext is raised when the operation + * is called outside the context of a POA-dispatched + * operation. + */ + + ObjectId get_object_id() + raises (NoContext); + }; +}; diff --git a/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/GetPropertyAction.java b/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/GetPropertyAction.java new file mode 100644 index 000000000..66ba4b2cb --- /dev/null +++ b/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/GetPropertyAction.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.org.omg.CORBA ; + +/** + * A convenience class for retrieving the string value of a system + * property as a privileged action. This class is directly copied + * from sun.security.action.GetPropertyAction in order to avoid + * depending on the sun.security.action package. + * + *

An instance of this class can be used as the argument of + * AccessController.doPrivileged. + * + *

The following code retrieves the value of the system + * property named "prop" as a privileged action:

+ * + *

+ * String s = (String) java.security.AccessController.doPrivileged(
+ *                         new GetPropertyAction("prop"));
+ * 
+ * + * DO NOT GENERIFY THIS UNTIL WE HAVE A NEW RMIC -IIOP!! + * (javax.rmi.CORBA.Stub depends on this, and may be visible to rmic) + * + * @author Roland Schemers + * @author Ken Cavanaugh + * @see java.security.PrivilegedAction + * @see java.security.AccessController + */ + +public class GetPropertyAction implements java.security.PrivilegedAction { + private String theProp; + private String defaultVal; + + /** + * Constructor that takes the name of the system property whose + * string value needs to be determined. + * + * @param theProp the name of the system property. + */ + public GetPropertyAction(String theProp) { + this.theProp = theProp; + } + + /** + * Constructor that takes the name of the system property and the default + * value of that property. + * + * @param theProp the name of the system property. + * @param defaulVal the default value. + */ + public GetPropertyAction(String theProp, String defaultVal) { + this.theProp = theProp; + this.defaultVal = defaultVal; + } + + /** + * Determines the string value of the system property whose + * name was specified in the constructor. + * + * @return the string value of the system property, + * or the default value if there is no property with that key. + */ + public Object run() { + String value = System.getProperty(theProp); + return (value == null) ? defaultVal : value; + } +} diff --git a/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/ORB.java b/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/ORB.java new file mode 100644 index 000000000..8fd5f0e49 --- /dev/null +++ b/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/ORB.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.org.omg.CORBA ; + +import org.omg.CORBA.ORBPackage.InvalidName ; + +/** This ORB class is defined to provide a home for the +* register_initial_reference operation, which is added by +* portable interceptors and CORBA 2.4. It is added here +* until there is an official Java language mapping for the +* method. +*/ +abstract public class ORB extends org.omg.CORBA_2_3.ORB +{ + /** + * If this operation is called with an id, "Y", and an + * object, YY, then a subsequent call to + * ORB.resolve_initial_references( "Y" ) will + * return object YY. + * + * @param id The ID by which the initial reference will be known. + * @param obj The initial reference itself. + * @throws InvalidName if this operation is called with an empty string id + * or this operation is called with an id that is already registered, + * including the default names defined by OMG. + * @throws BAD_PARAM if the obj parameter is null. + */ + public void register_initial_reference( String id, + org.omg.CORBA.Object obj ) + throws InvalidName + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/SUNVMCID.java b/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/SUNVMCID.java new file mode 100644 index 000000000..51a7819b1 --- /dev/null +++ b/omgapi/src/main/java/com/sun/corba/ee/org/omg/CORBA/SUNVMCID.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.org.omg.CORBA ; + +/** + * The vendor minor code ID reserved for Sun by the OMG. + * All VMCIDs occupy the high order 20 bits. + */ + +public interface SUNVMCID { + + /** + * The vendor minor code ID reserved for Sun. This value is or'd with + * the high order 20 bits of the minor code to produce the minor value + * in a system exception. + */ + static final int value = 0x53550000; +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/ClassDesc.java b/omgapi/src/main/java/javax/rmi/CORBA/ClassDesc.java new file mode 100644 index 000000000..ac2e65d48 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/ClassDesc.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +/** + * This class is used to marshal java.lang.Class objects over IIOP. + */ +public class ClassDesc implements java.io.Serializable { + + /** + * @serial The class's RepositoryId. + */ + private String repid; + + /** + * @serial A space-separated list of codebase URLs. + */ + private String codebase; +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/EnumDesc.java b/omgapi/src/main/java/javax/rmi/CORBA/EnumDesc.java new file mode 100644 index 000000000..4ccf65a3d --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/EnumDesc.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA ; + +/** Class used to describe how a Java Enum is marshaled over + * RMI-IIOP. This is one of the proposals for OMG issue 10336, but + * not the final approved version. + */ +public class EnumDesc implements java.io.Serializable { + static final long serialVersionUID = -155483178780200630L ; + + /** Name of the enum constant. + */ + public String value ; + + /** Name of the enum class. + */ + public String className ; +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/GetORBPropertiesFileAction.java b/omgapi/src/main/java/javax/rmi/CORBA/GetORBPropertiesFileAction.java new file mode 100644 index 000000000..5284f8cc8 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/GetORBPropertiesFileAction.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1993-1997 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import java.io.File; +import java.io.FileInputStream; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Properties; + +class GetORBPropertiesFileAction implements PrivilegedAction { + private boolean debug = false ; + + public GetORBPropertiesFileAction () { + } + + private String getSystemProperty(final String name) { + // This will not throw a SecurityException because this + // class was loaded from rt.jar using the bootstrap classloader. + String propValue = (String) AccessController.doPrivileged( + new PrivilegedAction() { + public java.lang.Object run() { + return System.getProperty(name); + } + } + ); + + return propValue; + } + + private void getPropertiesFromFile( Properties props, String fileName ) + { + try { + File file = new File( fileName ) ; + if (!file.exists()) + return ; + + FileInputStream in = new FileInputStream( file ) ; + + try { + props.load( in ) ; + } finally { + in.close() ; + } + } catch (Exception exc) { + if (debug) + System.out.println( "ORB properties file " + fileName + + " not found: " + exc) ; + } + } + + public Object run() + { + Properties defaults = new Properties() ; + + String javaHome = getSystemProperty( "java.home" ) ; + String fileName = javaHome + File.separator + "lib" + File.separator + + "orb.properties" ; + + getPropertiesFromFile( defaults, fileName ) ; + + Properties results = new Properties( defaults ) ; + + String userHome = getSystemProperty( "user.home" ) ; + fileName = userHome + File.separator + "orb.properties" ; + + getPropertiesFromFile( results, fileName ) ; + return results ; + } +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/PortableRemoteObjectDelegate.java b/omgapi/src/main/java/javax/rmi/CORBA/PortableRemoteObjectDelegate.java new file mode 100644 index 000000000..0d9716bc2 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/PortableRemoteObjectDelegate.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import java.rmi.RemoteException; +import java.rmi.NoSuchObjectException; +import java.rmi.Remote; + +/** + * Supports delegation for method implementations in {@link javax.rmi.PortableRemoteObject}. + * The delegate is a singleton instance of a class that implements this + * interface and provides a replacement implementation for all the + * methods of javax.rmi.PortableRemoteObject. + * + * Delegates are enabled by providing the delegate's class name as the + * value of the + * javax.rmi.CORBA.PortableRemoteObjectClass + * system property. + * + * @see javax.rmi.PortableRemoteObject + */ +public interface PortableRemoteObjectDelegate { + + /** + * Delegation call for {@link javax.rmi.PortableRemoteObject#exportObject}. + */ + void exportObject(Remote obj) + throws RemoteException; + + /** + * Delegation call for {@link javax.rmi.PortableRemoteObject#toStub}. + */ + Remote toStub (Remote obj) + throws NoSuchObjectException; + + /** + * Delegation call for {@link javax.rmi.PortableRemoteObject#unexportObject}. + */ + void unexportObject(Remote obj) + throws NoSuchObjectException; + + /** + * Delegation call for {@link javax.rmi.PortableRemoteObject#narrow}. + */ + java.lang.Object narrow (java.lang.Object narrowFrom, + java.lang.Class narrowTo) + throws ClassCastException; + + /** + * Delegation call for {@link javax.rmi.PortableRemoteObject#connect}. + */ + void connect (Remote target, Remote source) + throws RemoteException; + +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/ProxyDesc.java b/omgapi/src/main/java/javax/rmi/CORBA/ProxyDesc.java new file mode 100644 index 000000000..804a1b7e4 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/ProxyDesc.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +/** + * This class is used to marshal java.lang.Proxy objects over IIOP. + */ +public class ProxyDesc implements java.io.Serializable { + /** + * @serial The class names of the interfaces that the Proxy object + * implements. + */ + public String[] interfaces; + + /** + * @serial A space-separated list of codebase URLs. + */ + public String codebase; + + /** + * @serial The Proxy's InvocationHandler instance. + */ + public java.lang.reflect.InvocationHandler handler; + + static final long serialVersionUID = 1234286961190911798L; +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/Stub.java b/omgapi/src/main/java/javax/rmi/CORBA/Stub.java new file mode 100644 index 000000000..68f152ace --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/Stub.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA_2_3.portable.ObjectImpl; + +import java.io.IOException; +import java.rmi.RemoteException; +import java.io.File; +import java.io.FileInputStream; +import java.net.MalformedURLException ; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Properties; +import java.rmi.server.RMIClassLoader; + +import com.sun.corba.ee.org.omg.CORBA.GetPropertyAction; + + +/** + * Base class from which all RMI-IIOP stubs must inherit. + */ +public abstract class Stub extends ObjectImpl + implements java.io.Serializable { + + private static final long serialVersionUID = 1087775603798577179L; + + // This can only be set at object construction time (no sync necessary). + private transient StubDelegate stubDelegate = null; + private static Class stubDelegateClass = null; + private static final String StubClassKey = "javax.rmi.CORBA.StubClass"; + private static final String defaultStubImplName = "com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl"; + + static { + Object stubDelegateInstance = (Object) createDelegateIfSpecified(StubClassKey, defaultStubImplName); + if (stubDelegateInstance != null) + stubDelegateClass = stubDelegateInstance.getClass(); + + } + + + /** + * Returns a hash code value for the object which is the same for all stubs + * that represent the same remote object. + * @return the hash code value. + */ + public int hashCode() { + + if (stubDelegate == null) { + setDefaultDelegate(); + } + + if (stubDelegate != null) { + return stubDelegate.hashCode(this); + } + + return 0; + } + + /** + * Compares two stubs for equality. Returns true when used to compare stubs + * that represent the same remote object, and false otherwise. + * @param obj the reference object with which to compare. + * @return true if this object is the same as the obj + * argument; false otherwise. + */ + public boolean equals(java.lang.Object obj) { + + if (stubDelegate == null) { + setDefaultDelegate(); + } + + if (stubDelegate != null) { + return stubDelegate.equals(this, obj); + } + + return false; + } + + /** + * Returns a string representation of this stub. Returns the same string + * for all stubs that represent the same remote object. + * @return a string representation of this stub. + */ + public String toString() { + + + if (stubDelegate == null) { + setDefaultDelegate(); + } + + String ior; + if (stubDelegate != null) { + ior = stubDelegate.toString(this); + if (ior == null) { + return super.toString(); + } else { + return ior; + } + } + return super.toString(); + } + + /** + * Connects this stub to an ORB. Required after the stub is deserialized + * but not after it is demarshalled by an ORB stream. If an unconnected + * stub is passed to an ORB stream for marshalling, it is implicitly + * connected to that ORB. Application code should not call this method + * directly, but should call the portable wrapper method + * {@link javax.rmi.PortableRemoteObject#connect}. + * @param orb the ORB to connect to. + * @exception RemoteException if the stub is already connected to a different + * ORB, or if the stub does not represent an exported remote or local object. + */ + public void connect(ORB orb) throws RemoteException { + + if (stubDelegate == null) { + setDefaultDelegate(); + } + + if (stubDelegate != null) { + stubDelegate.connect(this, orb); + } + + } + + /** + * Serialization method to restore the IOR state. + */ + private void readObject(java.io.ObjectInputStream stream) + throws IOException, ClassNotFoundException { + + if (stubDelegate == null) { + setDefaultDelegate(); + } + + if (stubDelegate != null) { + stubDelegate.readObject(this, stream); + } + + } + + /** + * Serialization method to save the IOR state. + * @serialData The length of the IOR type ID (int), followed by the IOR type ID + * (byte array encoded using ISO8859-1), followed by the number of IOR profiles + * (int), followed by the IOR profiles. Each IOR profile is written as a + * profile tag (int), followed by the length of the profile data (int), followed + * by the profile data (byte array). + */ + private void writeObject(java.io.ObjectOutputStream stream) throws IOException { + + if (stubDelegate == null) { + setDefaultDelegate(); + } + + if (stubDelegate != null) { + stubDelegate.writeObject(this, stream); + } + } + + private void setDefaultDelegate() { + if (stubDelegateClass != null) { + try { + stubDelegate = (javax.rmi.CORBA.StubDelegate) stubDelegateClass.newInstance(); + } catch (Exception ex) { + // what kind of exception to throw + // delegate not set therefore it is null and will return default + // values + } + } + } + + // Same code as in PortableRemoteObject. Can not be shared because they + // are in different packages and the visibility needs to be package for + // security reasons. If you know a better solution how to share this code + // then remove it from PortableRemoteObject. Also in Util.java + private static Object createDelegateIfSpecified(String classKey, + String defaultClassName) { + + String className = + (String)AccessController.doPrivileged(new GetPropertyAction(classKey)); + if (className == null) { + Properties props = getORBPropertiesFile(); + if (props != null) { + className = props.getProperty(classKey); + } + } + + if (className == null) { + className = defaultClassName; + } + + try { + return loadDelegateClass(className).newInstance(); + } catch (ClassNotFoundException ex) { + INITIALIZE exc = new INITIALIZE( "Cannot instantiate " + className); + exc.initCause( ex ) ; + throw exc ; + } catch (Exception ex) { + INITIALIZE exc = new INITIALIZE( "Error while instantiating" + className); + exc.initCause( ex ) ; + throw exc ; + } + + } + + private static Class loadDelegateClass( String className ) throws ClassNotFoundException + { + try { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + return Class.forName(className, false, loader); + } catch (ClassNotFoundException e) { + // ignore, then try RMIClassLoader + } + + try { + return RMIClassLoader.loadClass(className); + } catch (MalformedURLException e) { + String msg = "Could not load " + className + ": " + e.toString(); + ClassNotFoundException exc = new ClassNotFoundException( msg ) ; + throw exc ; + } + } + + /** + * Load the orb.properties file. + */ + private static Properties getORBPropertiesFile () { + return (Properties) AccessController.doPrivileged(new GetORBPropertiesFileAction()); + } + +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/StubDelegate.java b/omgapi/src/main/java/javax/rmi/CORBA/StubDelegate.java new file mode 100644 index 000000000..81efa99ed --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/StubDelegate.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.rmi.RemoteException; +import org.omg.CORBA.ORB; + +/** + * Supports delegation for method implementations in {@link Stub}. + * A delegate is an instance of a class that implements this + * interface and provides a replacement implementation for all the + * methods of javax.rmi.CORBA.Stub. If delegation is + * enabled, each stub has an associated delegate. + * + * Delegates are enabled by providing the delegate's class name as the + * value of the + * javax.rmi.CORBA.StubClass + * system property. + * + * @see Stub + */ +public interface StubDelegate { + + /** + * Delegation call for {@link Stub#hashCode}. + */ + int hashCode(Stub self); + + /** + * Delegation call for {@link Stub#equals}. + */ + boolean equals(Stub self, java.lang.Object obj); + + /** + * Delegation call for {@link Stub#toString}. + */ + String toString(Stub self); + + /** + * Delegation call for {@link Stub#connect}. + */ + void connect(Stub self, ORB orb) + throws RemoteException; + + // _REVISIT_ cannot link to Stub.readObject directly... why not? + /** + * Delegation call for + * Stub.readObject(java.io.ObjectInputStream). + */ + void readObject(Stub self, ObjectInputStream s) + throws IOException, ClassNotFoundException; + + // _REVISIT_ cannot link to Stub.writeObject directly... why not? + /** + * Delegation call for + * Stub.writeObject(java.io.ObjectOutputStream). + */ + void writeObject(Stub self, ObjectOutputStream s) + throws IOException; + +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/Tie.java b/omgapi/src/main/java/javax/rmi/CORBA/Tie.java new file mode 100644 index 000000000..29e47c453 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/Tie.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import java.rmi.Remote; +import java.util.Hashtable; + +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.Delegate; +import org.omg.CORBA.ORB; + +/** + * Defines methods which all RMI-IIOP server side ties must implement. + */ +public interface Tie extends org.omg.CORBA.portable.InvokeHandler { + /** + * Returns an object reference for the target object represented by + * this tie. + * @return an object reference for the target object. + */ + org.omg.CORBA.Object thisObject(); + + /** + * Deactivates the target object represented by this tie. + */ + void deactivate() throws java.rmi.NoSuchObjectException; + + /** + * Returns the ORB for this tie. + * @return the ORB. + */ + ORB orb(); + + /** + * Sets the ORB for this tie. + * @param orb the ORB. + */ + void orb(ORB orb); + + /** + * Called by {@link Util#registerTarget} to set the target + * for this tie. + * @param target the object to use as the target for this tie. + */ + void setTarget(java.rmi.Remote target); + + /** + * Returns the target for this tie. + * @return the target. + */ + java.rmi.Remote getTarget(); +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/Util.java b/omgapi/src/main/java/javax/rmi/CORBA/Util.java new file mode 100644 index 000000000..e7aacb91d --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/Util.java @@ -0,0 +1,389 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import java.rmi.RemoteException; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.Any; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ObjectImpl; + +import javax.rmi.CORBA.Tie; +import java.rmi.Remote; +import java.io.File; +import java.io.FileInputStream; +import java.io.SerializablePermission; +import java.net.MalformedURLException ; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Properties; +import java.rmi.server.RMIClassLoader; + +import com.sun.corba.ee.org.omg.CORBA.GetPropertyAction; + +/** + * Provides utility methods that can be used by stubs and ties to + * perform common operations. + */ +public class Util { + + // This can only be set at static initialization time (no sync necessary). + private static javax.rmi.CORBA.UtilDelegate utilDelegate = null; + private static final String UtilClassKey = "javax.rmi.CORBA.UtilClass"; + private static final String defaultUtilImplName = + "com.sun.corba.ee.impl.javax.rmi.CORBA.Util"; + + static { + utilDelegate = (javax.rmi.CORBA.UtilDelegate) + createDelegateIfSpecified(UtilClassKey, defaultUtilImplName); + } + + private Util(){} + + /** + * Maps a SystemException to a RemoteException. + * @param ex the SystemException to map. + * @return the mapped exception. + */ + public static RemoteException mapSystemException(SystemException ex) { + + if (utilDelegate != null) { + return utilDelegate.mapSystemException(ex); + } + return null; + } + + /** + * Writes any java.lang.Object as a CORBA any. + * @param out the stream in which to write the any. + * @param obj the object to write as an any. + */ + public static void writeAny(OutputStream out, Object obj) { + + if (utilDelegate != null) { + utilDelegate.writeAny(out, obj); + } + } + + /** + * Reads a java.lang.Object as a CORBA any. + * @param in the stream from which to read the any. + * @return the object read from the stream. + */ + public static Object readAny(InputStream in) { + + if (utilDelegate != null) { + return utilDelegate.readAny(in); + } + return null; + } + + /** + * Writes a java.lang.Object as a CORBA Object. If obj is + * an exported RMI-IIOP server object, the tie is found + * and wired to obj, then written to +out.write_Object(org.omg.CORBA.Object). + * If obj is a CORBA Object, it is written to + * out.write_Object(org.omg.CORBA.Object). + * @param out the stream in which to write the object. + * @param obj the object to write. + */ + public static void writeRemoteObject(OutputStream out, + java.lang.Object obj) { + + if (utilDelegate != null) { + utilDelegate.writeRemoteObject(out, obj); + } + + } + + /** + * Writes a java.lang.Object as either a value or a CORBA Object. + * If obj is a value object or a stub object, it is written to + * out.write_abstract_interface(java.lang.Object). If obj +is +an exported + * RMI-IIOP server object, the tie is found and wired to obj, + * then written to out.write_abstract_interface(java.lang.Object). + * @param out the stream in which to write the object. + * @param obj the object to write. + */ + public static void writeAbstractObject(OutputStream out, + java.lang.Object obj) { + + if (utilDelegate != null) { + utilDelegate.writeAbstractObject(out, obj); + } + } + + /** + * Registers a target for a tie. Adds the tie to an internal table and calls + * {@link Tie#setTarget} on the tie object. + * @param tie the tie to register. + * @param target the target for the tie. + */ + public static void registerTarget(javax.rmi.CORBA.Tie tie, + java.rmi.Remote target) { + + if (utilDelegate != null) { + utilDelegate.registerTarget(tie, target); + } + + } + + /** + * Removes the associated tie from an internal table and calls {@link +Tie#deactivate} + * to deactivate the object. + * @param target the object to unexport. + */ + public static void unexportObject(java.rmi.Remote target) + throws java.rmi.NoSuchObjectException + { + + if (utilDelegate != null) { + utilDelegate.unexportObject(target); + } + + } + + /** + * Returns the tie (if any) for a given target object. + * @return the tie or null if no tie is registered for the given target. + */ + public static Tie getTie (Remote target) { + + if (utilDelegate != null) { + return utilDelegate.getTie(target); + } + return null; + } + + + /** + * Returns a singleton instance of a class that implements the + * {@link ValueHandler} interface. + * @return a class which implements the ValueHandler interface. + */ + public static ValueHandler createValueHandler() { + isCustomSerializationPermitted(); + + if (utilDelegate != null) { + return utilDelegate.createValueHandler(); + } + return null; + } + + /** + * Returns the codebase, if any, for the given class. + * @param clz the class to get a codebase for. + * @return a space-separated list of URLs, or null. + */ + public static String getCodebase(java.lang.Class clz) { + if (utilDelegate != null) { + return utilDelegate.getCodebase(clz); + } + return null; + } + + /** + * Returns a class instance for the specified class. + *

The spec for this method is the "Java to IDL language + * mapping", ptc/00-01-06. + *

In Java SE Platform, this method works as follows: + *

  • Find the first non-null ClassLoader on the + * call stack and attempt to load the class using this + * ClassLoader. + *
  • If the first step fails, and if remoteCodebase + * is non-null and + * useCodebaseOnly is false, then call + * java.rmi.server.RMIClassLoader.loadClass(remoteCodebase, className). + *
  • If remoteCodebase is null or useCodebaseOnly + * is true, then call java.rmi.server.RMIClassLoader.loadClass(className). + *
  • If a class was not successfully loaded by step 1, 2, or 3, + * and loader is non-null, then call loader.loadClass(className). + *
  • If a class was successfully loaded by step 1, 2, 3, or 4, then + * return the loaded class, else throw ClassNotFoundException. + * @param className the name of the class. + * @param remoteCodebase a space-separated list of URLs at which + * the class might be found. May be null. + * @param loader a ClassLoader that may be used to + * load the class if all other methods fail. + * @return the Class object representing the loaded class. + * @exception ClassNotFoundException if class cannot be loaded. + */ + public static Class loadClass(String className, + String remoteCodebase, + ClassLoader loader) + throws ClassNotFoundException { + if (utilDelegate != null) { + return utilDelegate.loadClass(className,remoteCodebase,loader); + } + return null ; + } + + + /** + * The isLocal method has the same semantics as the + * ObjectImpl._is_local + * method, except that it can throw a RemoteException. + * + * The _is_local() method is provided so that stubs may determine if a + * particular object is implemented by a local servant and hence local + * invocation APIs may be used. + * + * @param stub the stub to test. + * + * @return The _is_local() method returns true if + * the servant incarnating the object is located in the same process as + * the stub and they both share the same ORB instance. The _is_local() + * method returns false otherwise. The default behavior of _is_local() is + * to return false. + * + * @throws RemoteException The Java to IDL specification does not + * specify the conditions that cause a RemoteException to be thrown. + */ + public static boolean isLocal(Stub stub) throws RemoteException { + + if (utilDelegate != null) { + return utilDelegate.isLocal(stub); + } + + return false; + } + + /** + * Wraps an exception thrown by an implementation + * method. It returns the corresponding client-side exception. + * @param orig the exception to wrap. + * @return the wrapped exception. + */ + public static RemoteException wrapException(Throwable orig) { + + if (utilDelegate != null) { + return utilDelegate.wrapException(orig); + } + + return null; + } + + /** + * Copies or connects an array of objects. Used by local stubs + * to copy any number of actual parameters, preserving sharing + * across parameters as necessary to support RMI semantics. + * @param obj the objects to copy or connect. + * @param orb the ORB. + * @return the copied or connected objects. + * @exception RemoteException if any object could not be copied or connected. + */ + public static Object[] copyObjects (Object[] obj, ORB orb) + throws RemoteException { + + if (utilDelegate != null) { + return utilDelegate.copyObjects(obj, orb); + } + + return null; + } + + /** + * Copies or connects an object. Used by local stubs to copy + * an actual parameter, result object, or exception. + * @param obj the object to copy. + * @param orb the ORB. + * @return the copy or connected object. + * @exception RemoteException if the object could not be copied or connected. + */ + public static Object copyObject (Object obj, ORB orb) + throws RemoteException { + + if (utilDelegate != null) { + return utilDelegate.copyObject(obj, orb); + } + return null; + } + + // Same code as in PortableRemoteObject. Can not be shared because they + // are in different packages and the visibility needs to be package for + // security reasons. If you know a better solution how to share this code + // then remove it from PortableRemoteObject. Also in Stub.java + private static Object createDelegateIfSpecified(String classKey, + String defaultClassName) + { + String className = (String) + AccessController.doPrivileged(new GetPropertyAction(classKey)); + if (className == null) { + Properties props = getORBPropertiesFile(); + if (props != null) { + className = props.getProperty(classKey); + } + } + + if (className == null) { + className = defaultClassName; + } + + try { + return loadDelegateClass(className).newInstance(); + } catch (ClassNotFoundException ex) { + INITIALIZE exc = new INITIALIZE( "Cannot instantiate " + className); + exc.initCause( ex ) ; + throw exc ; + } catch (Exception ex) { + INITIALIZE exc = new INITIALIZE( "Error while instantiating" + className); + exc.initCause( ex ) ; + throw exc ; + } + } + + private static Class loadDelegateClass( String className ) throws ClassNotFoundException + { + try { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + return Class.forName(className, false, loader); + } catch (ClassNotFoundException e) { + // ignore, then try RMIClassLoader + } + + try { + return RMIClassLoader.loadClass(className); + } catch (MalformedURLException e) { + String msg = "Could not load " + className + ": " + e.toString(); + ClassNotFoundException exc = new ClassNotFoundException( msg ) ; + throw exc ; + } + } + /** + * Load the orb.properties file. + */ + private static Properties getORBPropertiesFile () + { + return (Properties) AccessController.doPrivileged( + new GetORBPropertiesFileAction()); + } + + private static void isCustomSerializationPermitted() { + SecurityManager sm = System.getSecurityManager(); + if ( sm != null) { + // check that a serialization permission has been + // set to allow the loading of the Util delegate + // which provides access to custom ValueHandler + sm.checkPermission(new SerializablePermission( + "enableCustomValueHandler")); + } + } + +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/UtilDelegate.java b/omgapi/src/main/java/javax/rmi/CORBA/UtilDelegate.java new file mode 100644 index 000000000..d85372305 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/UtilDelegate.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.ValueHandler; +import org.omg.CORBA.ORB; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.SystemException; + +/** + * Supports delegation for method implementations in {@link Util}. The + * delegate is a singleton instance of a class that implements this + * interface and provides a replacement implementation for all the + * methods of javax.rmi.CORBA.Util. + * + * Delegation is enabled by providing the delegate's class name as the + * value of the + * javax.rmi.CORBA.UtilClass + * system property. + * + * @see Util + */ +public interface UtilDelegate { + + /** + * Delegation call for {@link Util#mapSystemException}. + */ + RemoteException mapSystemException(SystemException ex); + + /** + * Delegation call for {@link Util#writeAny}. + */ + void writeAny(OutputStream out, Object obj); + + /** + * Delegation call for {@link Util#readAny}. + */ + java.lang.Object readAny(InputStream in); + + /** + * Delegation call for {@link Util#writeRemoteObject}. + */ + void writeRemoteObject(OutputStream out, Object obj); + + /** + * Delegation call for {@link Util#writeAbstractObject}. + */ + void writeAbstractObject(OutputStream out, Object obj); + + /** + * Delegation call for {@link Util#registerTarget}. + */ + void registerTarget(Tie tie, Remote target); + + /** + * Delegation call for {@link Util#unexportObject}. + */ + void unexportObject(Remote target) throws java.rmi.NoSuchObjectException; + + /** + * Delegation call for {@link Util#getTie}. + */ + Tie getTie(Remote target); + + /** + * Delegation call for {@link Util#createValueHandler}. + */ + ValueHandler createValueHandler(); + + /** + * Delegation call for {@link Util#getCodebase}. + */ + String getCodebase(Class clz); + + /** + * Delegation call for {@link Util#loadClass}. + */ + Class loadClass(String className, String remoteCodebase, ClassLoader loader) + throws ClassNotFoundException; + + /** + * Delegation call for {@link Util#isLocal}. + */ + boolean isLocal(Stub stub) throws RemoteException; + + /** + * Delegation call for {@link Util#wrapException}. + */ + RemoteException wrapException(Throwable obj); + + /** + * Delegation call for {@link Util#copyObject}. + */ + Object copyObject(Object obj, ORB orb) throws RemoteException; + + /** + * Delegation call for {@link Util#copyObjects}. + */ + Object[] copyObjects(Object[] obj, ORB orb) throws RemoteException; + +} + diff --git a/omgapi/src/main/java/javax/rmi/CORBA/ValueHandler.java b/omgapi/src/main/java/javax/rmi/CORBA/ValueHandler.java new file mode 100644 index 000000000..1fd53a479 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/ValueHandler.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +/** + * Defines methods which allow serialization of Java objects + * to and from GIOP streams. + **/ +public interface ValueHandler { + + /** + * Writes a value to the stream using Java semantics. + * @param out the stream to write the value to. + * @param value the value to be written to the stream. + **/ + void writeValue(org.omg.CORBA.portable.OutputStream out, + java.io.Serializable value); + + /** + * Reads a value from the stream using Java semantics. + * @param in the stream to read the value from. + * @param offset the current position in the input stream. + * @param clz the type of the value to be read in. + * @param repositoryID the RepositoryId of the value to be read in. + * @param sender the sending context runtime codebase. + * @return the value read from the stream. + **/ + java.io.Serializable readValue(org.omg.CORBA.portable.InputStream in, + int offset, + java.lang.Class clz, + String repositoryID, + org.omg.SendingContext.RunTime sender); + + /** + * Returns the CORBA RepositoryId for the given Java class. + * @param clz a Java class. + * @return the CORBA RepositoryId for the class. + **/ + java.lang.String getRMIRepositoryID(java.lang.Class clz); + + /** + * Indicates whether the given class performs custom or + * default marshaling. + * @param clz the class to test for custom marshaling. + * @return true if the class performs custom marshaling, false + * if it does not. + **/ + boolean isCustomMarshaled(java.lang.Class clz); + + /** + * Returns the CodeBase for this ValueHandler. This is used by + * the ORB runtime. The server sends the service context containing + * the IOR for this CodeBase on the first GIOP reply. The client + * does the same on the first GIOP request. + * @return the SendingContext.CodeBase of this ValueHandler. + **/ + org.omg.SendingContext.RunTime getRunTimeCodeBase(); + + /** + * If the value contains a writeReplace method then the result + * is returned. Otherwise, the value itself is returned. + * @param value the value to be marshaled. + * @return the true value to marshal on the wire. + **/ + java.io.Serializable writeReplace(java.io.Serializable value); + +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/ValueHandlerMultiFormat.java b/omgapi/src/main/java/javax/rmi/CORBA/ValueHandlerMultiFormat.java new file mode 100644 index 000000000..e8c2d46d2 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/ValueHandlerMultiFormat.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.CORBA; + +/** + * Java to IDL ptc 02-01-12 1.5.1.5 + */ +public interface ValueHandlerMultiFormat extends ValueHandler { + + /** + * Returns the maximum stream format version for + * RMI/IDL custom value types that is supported + * by this ValueHandler object. The ValueHandler + * object must support the returned stream format version and + * all lower versions. + * + * An ORB may use this value to include in a standard + * IOR tagged component or service context to indicate to other + * ORBs the maximum RMI-IIOP stream format that it + * supports. If not included, the default for GIOP 1.2 + * is stream format version 1, and stream format version + * 2 for GIOP 1.3 and higher. + */ + byte getMaximumStreamFormatVersion(); + + /** + * Allows the ORB to pass the stream format + * version for RMI/IDL custom value types. If the ORB + * calls this method, it must pass a stream format version + * between 1 and the value returned by the + * getMaximumStreamFormatVersion method inclusive, + * or else a BAD_PARAM exception with standard minor code + * will be thrown. + * + * If the ORB calls the older ValueHandler.writeValue(OutputStream, + * Serializable) method, stream format version 1 is implied. + * + * The ORB output stream passed to the ValueHandlerMultiFormat.writeValue + * method must implement the ValueOutputStream interface, and the + * ORB input stream passed to the ValueHandler.readValue method must + * implement the ValueInputStream interface. + */ + void writeValue(org.omg.CORBA.portable.OutputStream out, + java.io.Serializable value, + byte streamFormatVersion); +} diff --git a/omgapi/src/main/java/javax/rmi/CORBA/package.html b/omgapi/src/main/java/javax/rmi/CORBA/package.html new file mode 100644 index 000000000..33ccd8cfb --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/CORBA/package.html @@ -0,0 +1,19 @@ + + + +Contains portability APIs for RMI-IIOP. These APIs +provide a standard interface between the generated stubs and ties and the +RMI-IIOP runtime. They also allow third party ORBs to be used for RMI over IIOP +as an alternative to the ORB supplied by Sun. They are not intended to be called +directly from RMI-IIOP applications. See also the {@link javax.rmi} package. + diff --git a/omgapi/src/main/java/javax/rmi/PortableRemoteObject.java b/omgapi/src/main/java/javax/rmi/PortableRemoteObject.java new file mode 100644 index 000000000..8553bd8d5 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/PortableRemoteObject.java @@ -0,0 +1,274 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import com.sun.corba.ee.org.omg.CORBA.GetPropertyAction; +import org.omg.CORBA.INITIALIZE; + +import java.io.File; +import java.io.FileInputStream; +import java.net.MalformedURLException; +import java.rmi.NoSuchObjectException; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.server.RMIClassLoader; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Properties; + +/** + * Server implementation objects may either inherit from + * javax.rmi.PortableRemoteObject or they may implement a remote interface + * and then use the exportObject method to register themselves as a server object. + * The toStub method takes a server implementation and returns a stub that + * can be used to access that server object. + * The connect method makes a Remote object ready for remote communication. + * The unexportObject method is used to deregister a server object, allowing it to become + * available for garbage collection. + * The narrow method takes an object reference or abstract interface type and + * attempts to narrow it to conform to + * the given interface. If the operation is successful the result will be an + * object of the specified type, otherwise an exception will be thrown. + */ +public class PortableRemoteObject { + + private static javax.rmi.CORBA.PortableRemoteObjectDelegate proDelegate = null; + + private static final String PortableRemoteObjectClassKey = + "javax.rmi.CORBA.PortableRemoteObjectClass"; + + private static final String defaultPortableRemoteObjectImplName = + "com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject"; + + static { + proDelegate = (javax.rmi.CORBA.PortableRemoteObjectDelegate) + createDelegateIfSpecified(PortableRemoteObjectClassKey); + } + + /** + * Initializes the object by calling exportObject(this). + * @exception RemoteException if export fails. + */ + protected PortableRemoteObject() throws RemoteException { + if (proDelegate != null) { + PortableRemoteObject.exportObject((Remote)this); + } + } + + /** + * Makes a server object ready to receive remote calls. Note + * that subclasses of PortableRemoteObject do not need to call this + * method, as it is called by the constructor. + * @param obj the server object to export. + * @exception RemoteException if export fails. + */ + public static void exportObject(Remote obj) + throws RemoteException { + + // Let the delegate do everything, including error handling. + if (proDelegate != null) { + proDelegate.exportObject(obj); + } + } + + /** + * Returns a stub for the given server object. + * @param obj the server object for which a stub is required. Must either be a subclass + * of PortableRemoteObject or have been previously the target of a call to + * {@link #exportObject}. + * @return the most derived stub for the object. + * @exception NoSuchObjectException if a stub cannot be located for the given server object. + */ + public static Remote toStub (Remote obj) + throws NoSuchObjectException { + + if (proDelegate != null) { + return proDelegate.toStub(obj); + } + return null; + } + + /** + * Deregisters a server object from the runtime, allowing the object to become + * available for garbage collection. + * @param obj the object to unexport. + * @exception NoSuchObjectException if the remote object is not + * currently exported. + */ + public static void unexportObject(Remote obj) + throws NoSuchObjectException { + + if (proDelegate != null) { + proDelegate.unexportObject(obj); + } + + } + + /** + * Checks to ensure that an object of a remote or abstract interface type + * can be cast to a desired type. + * @param narrowFrom the object to check. + * @param narrowTo the desired type. + * @return an object which can be cast to the desired type. + * @throws ClassCastException if narrowFrom cannot be cast to narrowTo. + */ + public static java.lang.Object narrow ( java.lang.Object narrowFrom, + java.lang.Class narrowTo) + throws ClassCastException { + + if (proDelegate != null) { + return proDelegate.narrow(narrowFrom, narrowTo); + } + return null; + + } + + /** + * Makes a Remote object ready for remote communication. This normally + * happens implicitly when the object is sent or received as an argument + * on a remote method call, but in some circumstances it is useful to + * perform this action by making an explicit call. See the + * {@link javax.rmi.CORBA.Stub#connect} method for more information. + * @param target the object to connect. + * @param source a previously connected object. + * @throws RemoteException if source is not connected + * or if target is already connected to a different ORB than + * source. + */ + public static void connect (Remote target, Remote source) + throws RemoteException { + + if (proDelegate != null) { + proDelegate.connect(target, source); + } + + } + + // Same code as in javax.rmi.CORBA.Util. Can not be shared because they + // are in different packages and the visibility needs to be package for + // security reasons. If you know a better solution how to share this code + // then remove it from here. + private static Object createDelegateIfSpecified(String classKey) { + String className = (String) + AccessController.doPrivileged(new GetPropertyAction(classKey)); + if (className == null) { + Properties props = getORBPropertiesFile(); + if (props != null) { + className = props.getProperty(classKey); + } + } + if (className == null) { + className = defaultPortableRemoteObjectImplName; + } + + try { + return (Object) loadDelegateClass(className).newInstance(); + } catch (ClassNotFoundException ex) { + INITIALIZE exc = new INITIALIZE( "Cannot instantiate " + className); + exc.initCause( ex ) ; + throw exc ; + } catch (Exception ex) { + INITIALIZE exc = new INITIALIZE( "Error while instantiating" + className); + exc.initCause( ex ) ; + throw exc ; + } + + } + + private static Class loadDelegateClass( String className ) throws ClassNotFoundException + { + try { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + return Class.forName(className, false, loader); + } catch (ClassNotFoundException e) { + // ignore, then try RMIClassLoader + } + + try { + return RMIClassLoader.loadClass(className); + } catch (MalformedURLException e) { + String msg = "Could not load " + className + ": " + e.toString(); + ClassNotFoundException exc = new ClassNotFoundException( msg ) ; + throw exc ; + } + } + + /** + * Load the orb.properties file. + */ + private static Properties getORBPropertiesFile () { + return (Properties) AccessController.doPrivileged(new GetORBPropertiesFileAction()); + } +} + +class GetORBPropertiesFileAction implements PrivilegedAction { + private boolean debug = false ; + + public GetORBPropertiesFileAction () { + } + + private String getSystemProperty(final String name) { + // This will not throw a SecurityException because this + // class was loaded from rt.jar using the bootstrap classloader. + String propValue = (String) AccessController.doPrivileged( + new PrivilegedAction() { + public java.lang.Object run() { + return System.getProperty(name); + } + } + ); + + return propValue; + } + + private void getPropertiesFromFile( Properties props, String fileName ) + { + try { + File file = new File( fileName ) ; + if (!file.exists()) + return ; + + FileInputStream in = new FileInputStream( file ) ; + + try { + props.load( in ) ; + } finally { + in.close() ; + } + } catch (Exception exc) { + if (debug) + System.out.println( "ORB properties file " + fileName + + " not found: " + exc) ; + } + } + + public Object run() + { + Properties defaults = new Properties() ; + + String javaHome = getSystemProperty( "java.home" ) ; + String fileName = javaHome + File.separator + "lib" + File.separator + + "orb.properties" ; + + getPropertiesFromFile( defaults, fileName ) ; + + Properties results = new Properties( defaults ) ; + + String userHome = getSystemProperty( "user.home" ) ; + fileName = userHome + File.separator + "orb.properties" ; + + getPropertiesFromFile( results, fileName ) ; + return results ; + } +} + + diff --git a/omgapi/src/main/java/javax/rmi/package.html b/omgapi/src/main/java/javax/rmi/package.html new file mode 100644 index 000000000..4b7f13b91 --- /dev/null +++ b/omgapi/src/main/java/javax/rmi/package.html @@ -0,0 +1,18 @@ + + + +Contains user APIs for RMI-IIOP. These APIs are +provided for use by RMI-IIOP applications, and provide equivalent +semantics when running over either IIOP or JRMP. See also the +{@link javax.rmi.CORBA} package. + diff --git a/omgapi/src/main/java/org/omg/CORBA/ACTIVITY_COMPLETED.java b/omgapi/src/main/java/org/omg/CORBA/ACTIVITY_COMPLETED.java new file mode 100644 index 000000000..a1222f3e8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ACTIVITY_COMPLETED.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The ACTIVITY_COMPLETED system exception may be raised on any + * method for which Activity context is accessed. It indicates that the + * Activity context in which the method call was made has been completed due + * to a timeout of either the Activity itself or a transaction that encompasses + * the Activity, or that the Activity completed in a manner other than that + * originally requested. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class ACTIVITY_COMPLETED extends SystemException { + + /** + * Constructs an ACTIVITY_COMPLETED exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public ACTIVITY_COMPLETED() { + this(""); + } + + /** + * Constructs an ACTIVITY_COMPLETED exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public ACTIVITY_COMPLETED(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an ACTIVITY_COMPLETED exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public ACTIVITY_COMPLETED(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an ACTIVITY_COMPLETED exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public ACTIVITY_COMPLETED(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ACTIVITY_REQUIRED.java b/omgapi/src/main/java/org/omg/CORBA/ACTIVITY_REQUIRED.java new file mode 100644 index 000000000..9a4e93d33 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ACTIVITY_REQUIRED.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The ACTIVITY_REQUIRED system exception may be raised on any + * method for which an Activity context is required. It indicates that an + * Activity context was necessary to perform the invoked operation, but one + * was not found associated with the calling thread. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class ACTIVITY_REQUIRED extends SystemException { + + /** + * Constructs an ACTIVITY_REQUIRED exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public ACTIVITY_REQUIRED() { + this(""); + } + + /** + * Constructs an ACTIVITY_REQUIRED exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public ACTIVITY_REQUIRED(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an ACTIVITY_REQUIRED exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public ACTIVITY_REQUIRED(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an ACTIVITY_REQUIRED exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public ACTIVITY_REQUIRED(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ARG_IN.java b/omgapi/src/main/java/org/omg/CORBA/ARG_IN.java new file mode 100644 index 000000000..de27852ee --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ARG_IN.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Signifies an "input" argument to an invocation, + * meaning that the argument is being passed from the client to + * the server. + * ARG_IN.value is one of the possible values used to + * indicate the direction in + * which a parameter is being passed during an invocation performed + * using the Dynamic Invocation Interface (DII). + *

    + * The code fragment below shows a typical usage: + *

    + *    ORB orb = ORB.init(args, null);
    + *    org.omg.CORBA.NamedValue nv = orb.create_named_value(
    + *         "IDLArgumentIdentifier", myAny, org.omg.CORBA.ARG_IN.value);
    + * 
    + * + * @version 1.5, 09/09/97 + * @see org.omg.CORBA.NamedValue + * @since JDK1.2 + */ +public interface ARG_IN { + + /** + * The value indicating an input argument. + */ + int value = 1; +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/ARG_INOUT.java b/omgapi/src/main/java/org/omg/CORBA/ARG_INOUT.java new file mode 100644 index 000000000..2a5d000ee --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ARG_INOUT.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Signifies an argument used for both input and output in an invocation, + * meaning that the argument is being passed from the client to + * the server and then back from the server to the client. + * ARG_INOUT.value is one of the possible values used to + * indicate the direction in + * which a parameter is being passed during a dynamic invocation + * using the Dynamic Invocation Interface (DII). + *

    + * The code fragment below shows a typical usage: + *

    + *  ORB orb = ORB.init(args, null);
    + *  org.omg.CORBA.NamedValue nv = orb.create_named_value(
    + *        "argumentIdentifier", myAny, org.omg.CORBA.ARG_INOUT.value);
    + * 
    + * + * @version 1.5, 09/09/97 + * @see org.omg.CORBA.NamedValue + * @since JDK1.2 + */ +public interface ARG_INOUT { + +/** + * The constant value indicating an argument used for both + * input and output. + */ + int value = 3; +} + + + + diff --git a/omgapi/src/main/java/org/omg/CORBA/ARG_OUT.java b/omgapi/src/main/java/org/omg/CORBA/ARG_OUT.java new file mode 100644 index 000000000..40f8c0741 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ARG_OUT.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A constant that signifies an "output" argument to an invocation, + * meaning that the argument is being passed from the server to + * the client. + * ARG_OUT.value is one of the possible values used + * to indicate the direction in + * which a parameter is being passed during a dynamic invocation + * using the Dynamic Invocation Interface (DII). + *

    + * The code fragment below shows a typical usage: + *

    + *  ORB orb = ORB.init(args, null);
    + *  org.omg.CORBA.NamedValue nv = orb.create_named_value(
    + *        "argumentIdentifier", myAny, org.omg.CORBA.ARG_OUT.value);
    + * 
    + * + * @version 1.5, 09/09/97 + * @see org.omg.CORBA.NamedValue + * @since JDK1.2 + */ +public interface ARG_OUT { + +/** + * The constant value indicating an output argument. + */ + int value = 2; +} + + + diff --git a/omgapi/src/main/java/org/omg/CORBA/Any.java b/omgapi/src/main/java/org/omg/CORBA/Any.java new file mode 100644 index 000000000..696370951 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Any.java @@ -0,0 +1,707 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.IDLEntity; + +/** + * Serves as a container for any data that can be + * described in IDL or for any IDL primitive type. + * An Any object is used as a component of a + * NamedValue object, which provides information about + * arguments or return values in requests, and which is used to define + * name/value pairs in Context objects. +

    + * + * An Any object consists of two parts: + *

      + *
    1. a data value + *
    2. a TypeCode object describing the type of the data + * value contained in the Any object. For example, + * a TypeCode object for an array contains + * a field for the length of the array and a field for + * the type of elements in the array. (Note that in this case, the + * second field of the TypeCode object is itself a + * TypeCode object.) + *
    + * + *

    + * + * A large part of the Any class consists of pairs of methods + * for inserting values into and extracting values from an + * Any object. + *

    + * For a given primitive type X, these methods are: + *

    + *
    void insert_X(X x) + *
    This method allows the insertion of + * an instance x of primitive type X + * into the value field of the Any object. + * Note that the method + * insert_X also resets the Any object's + * type field if necessary. + *
    X extract_X() + *
    This method allows the extraction of an instance of + * type X from the Any object. + *
    + *

    + * This method throws the exception BAD_OPERATION under two conditions: + *

      + *
    1. the type of the element contained in the Any object is not + * X + *
    2. the method extract_X is called before + * the value field of the Any object + * has been set + *
    + *
    + *

    + * There are distinct method pairs for each + * primitive IDL data type (insert_long and extract_long, + * insert_string and extract_string, and so on).
    + *

    + * The class Any also has methods for + * getting and setting the type code, + * for testing two Any objects for equality, + * and for reading an Any object from a stream or + * writing it to a stream. + *
    + * @version 1.12, 09/09/97 + * @since JDK1.2 + */ +abstract public class Any implements IDLEntity { + + /** + * Checks for equality between this Any object and the + * given Any object. Two Any objects are + * equal if both their values and type codes are equal. + * + * @param a the Any object to test for equality + * @return true if the Any objects are equal; + * false otherwise + * @see
    CORBA package + * comments for unimplemented features + */ + abstract public boolean equal(Any a); + + /** + * Returns type information for the element contained in this + * Any object. + * + * @return the TypeCode object containing type information + * about the value contained in this Any object + */ + abstract public TypeCode type(); + + /** + * Sets this Any object's type field + * to the given TypeCode object and clears its value. + *

    + * Note that using this method to set the type code wipes out the + * value if there is one. The method + * is provided primarily so that the type may be set properly for + * IDL out parameters. Generally, setting the type + * is done by the insert_X methods, which will set the type + * to X if it is not already set to X. + * + * @param t the TypeCode object giving + * information for the value in + * this Any object + */ + abstract public void type(TypeCode t); + + /////////////////////////////////////////////////////////////////////////// + // marshalling/unmarshalling routines + + /** + * Reads off (unmarshals) the value of an Any object from + * the given input stream using the given typecode. + * + * @param is the org.omg.CORBA.portable.InputStream + * object from which to read + * the value contained in this Any object + * + * @param t a TypeCode object containing type information + * about the value to be read + * + * @exception MARSHAL when the given TypeCode object is + * not consistent with the value that was contained + * in the input stream + */ + abstract public void read_value(InputStream is, TypeCode t) + throws MARSHAL; + + /** + * Writes out the value of this Any object + * to the given output stream. If both typecode + * and value need to be written, use + * create_output_stream() to create an OutputStream, + * then use write_any on the OutputStream. + *

    + * If this method is called on an Any object that has not + * had a value inserted into its value field, it will throw + * the exception java.lang.NullPointerException. + * + * @param os the org.omg.CORBA.portable.OutputStream + * object into which to marshal the value + * of this Any object + * + */ + abstract public void write_value(OutputStream os); + + /** + * Creates an output stream into which this Any object's + * value can be marshalled. + * + * @return the newly-created OutputStream + */ + abstract public OutputStream create_output_stream(); + + /** + * Creates an input stream from which this Any object's value + * can be unmarshalled. + * + * @return the newly-created InputStream + */ + abstract public InputStream create_input_stream(); + + /////////////////////////////////////////////////////////////////////////// + // basic insertion/extraction methods + + /** + * Extracts the short in this + * Any object's value field. + * + * @return the short stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a short or the + * value field has not yet been set + */ + abstract public short extract_short() throws BAD_OPERATION; + + /** + * Inserts the given short + * into this Any object's value field. + * + * @param s the short to insert into this + * Any object + */ + abstract public void insert_short(short s); + + /** + * Extracts the int in this + * Any object's value field. + * + * @return the int stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than an int or the + * value field has not yet been set + */ + abstract public int extract_long() throws BAD_OPERATION; + + /** + * Inserts the given int + * into this Any object's value field. + * + * @param l the int to insert into this + * Any object + */ + abstract public void insert_long(int l); + + + /** + * Extracts the long in this + * Any object's value field. + * + * @return the long stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a long or the + * value field has not yet been set + */ + abstract public long extract_longlong() throws BAD_OPERATION; + + /** + * Inserts the given long + * into this Any object's value field. + * + * @param l the long to insert into this + * Any object + */ + abstract public void insert_longlong(long l); + + /** + * Extracts the short in this + * Any object's value field. + * + * @return the short stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a short or the + * value field has not yet been set + */ + abstract public short extract_ushort() throws BAD_OPERATION; + + /** + * Inserts the given short + * into this Any object's value field. + * + * @param s the short to insert into this + * Any object + */ + abstract public void insert_ushort(short s); + + /** + * Extracts the int in this + * Any object's value field. + * + * @return the int stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than an int or the + * value field has not yet been set + */ + abstract public int extract_ulong() throws BAD_OPERATION; + + /** + * Inserts the given int + * into this Any object's value field. + * + * @param l the int to insert into this + * Any object + */ + abstract public void insert_ulong(int l); + + /** + * Extracts the long in this + * Any object's value field. + * + * @return the long stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a long or the + * value field has not yet been set + */ + abstract public long extract_ulonglong() throws BAD_OPERATION; + + /** + * Inserts the given long + * into this Any object's value field. + * + * @param l the long to insert into this + * Any object + */ + abstract public void insert_ulonglong(long l); + + /** + * Extracts the float in this + * Any object's value field. + * + * @return the float stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a float or the + * value field has not yet been set + */ + abstract public float extract_float() throws BAD_OPERATION; + + /** + * Inserts the given float + * into this Any object's value field. + * + * @param f the float to insert into this + * Any object + */ + abstract public void insert_float(float f); + + /** + * Extracts the double in this + * Any object's value field. + * + * @return the double stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a double or the + * value field has not yet been set + */ + abstract public double extract_double() throws BAD_OPERATION; + + /** + * Inserts the given double + * into this Any object's value field. + * + * @param d the double to insert into this + * Any object + */ + abstract public void insert_double(double d); + + /** + * Extracts the boolean in this + * Any object's value field. + * + * @return the boolean stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a boolean or the + * value field has not yet been set + */ + abstract public boolean extract_boolean() throws BAD_OPERATION; + + /** + * Inserts the given boolean + * into this Any object's value field. + * + * @param b the boolean to insert into this + * Any object + */ + abstract public void insert_boolean(boolean b); + + /** + * Extracts the char in this + * Any object's value field. + * + * @return the char stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a char or the + * value field has not yet been set + */ + abstract public char extract_char() throws BAD_OPERATION; + + /** + * Inserts the given char + * into this Any object's value field. + * + * @param c the char to insert into this + * Any object + * @exception DATA_CONVERSION if there is a data conversion + * error + */ + abstract public void insert_char(char c) throws DATA_CONVERSION; + + /** + * Extracts the char in this + * Any object's value field. + * + * @return the char stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a char or the + * value field has not yet been set + */ + abstract public char extract_wchar() throws BAD_OPERATION; + + /** + * Inserts the given char + * into this Any object's value field. + * + * @param c the char to insert into this + * Any object + */ + abstract public void insert_wchar(char c); + + /** + * Extracts the byte in this + * Any object's value field. + * + * @return the byte stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a byte or the + * value field has not yet been set + */ + abstract public byte extract_octet() throws BAD_OPERATION; + + /** + * Inserts the given byte + * into this Any object's value field. + * + * @param b the byte to insert into this + * Any object + */ + abstract public void insert_octet(byte b); + + /** + * Extracts the Any object in this + * Any object's value field. + * + * @return the Any object stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than an Any object or the + * value field has not yet been set + */ + abstract public Any extract_any() throws BAD_OPERATION; + + /** + * Inserts the given Any object + * into this Any object's value field. + * + * @param a the Any object to insert into this + * Any object + */ + abstract public void insert_any(Any a); + + /** + * Extracts the org.omg.CORBA.Object in this + * Any object's value field. + * + * @return the org.omg.CORBA.Object stored in + * this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than an + * org.omg.CORBA.Object or the + * value field has not yet been set + */ + abstract public org.omg.CORBA.Object extract_Object() throws BAD_OPERATION; + + /** + * Inserts the given org.omg.CORBA.Object object + * into this Any object's value field. + * + * @param o the org.omg.CORBA.Object object to insert into this + * Any object + */ + abstract public void insert_Object(org.omg.CORBA.Object o); + + /** + * Extracts the java.io.Serializable object in this + * Any object's value field. + * + * @return the java.io.Serializable object stored in + * this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a java.io.Serializable + * object or the + * value field has not yet been set + */ + abstract public java.io.Serializable extract_Value() throws BAD_OPERATION ; + + /** + * Inserts the given java.io.Serializable object + * into this Any object's value field. + * + * @param v the java.io.Serializable object to insert into this + * Any object + */ + abstract public void insert_Value(java.io.Serializable v) ; + + /** + * Inserts the given java.io.Serializable object + * into this Any object's value field. + * + * @param v the java.io.Serializable object to insert into this + * Any object + * @param t the TypeCode object that is to be inserted into + * this Any object's type field + * and that describes the java.io.Serializable + * object being inserted + * @throws MARSHAL if the ORB has a problem marshalling or + * unmarshalling parameters + */ + abstract public void insert_Value(java.io.Serializable v, TypeCode t) + throws MARSHAL ; +/** + * Inserts the given org.omg.CORBA.Object object + * into this Any object's value field. + * + * @param o the org.omg.CORBA.Object instance to insert into this + * Any object + * @param t the TypeCode object that is to be inserted into + * this Any object and that describes + * the Object being inserted + * @exception BAD_OPERATION if this method is invalid for this + * Any object + * + */ + abstract public void insert_Object(org.omg.CORBA.Object o, TypeCode t) + throws BAD_PARAM; + + /** + * Extracts the String object in this + * Any object's value field. + * + * @return the String object stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a String object or the + * value field has not yet been set + */ + abstract public String extract_string() throws BAD_OPERATION; + + /** + * Inserts the given String object + * into this Any object's value field. + * + * @param s the String object to insert into this + * Any object + * @exception DATA_CONVERSION if there is a data conversion error + * @exception MARSHAL if the ORB has a problem marshalling or + * unmarshalling parameters + */ + abstract public void insert_string(String s) throws DATA_CONVERSION, MARSHAL; + + /** + * Extracts the String object in this + * Any object's value field. + * + * @return the String object stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a String object or the + * value field has not yet been set + */ + abstract public String extract_wstring() throws BAD_OPERATION; + + /** + * Inserts the given String object + * into this Any object's value field. + * + * @param s the String object to insert into this + * Any object + * @exception MARSHAL if the ORB has a problem marshalling or + * unmarshalling parameters + */ + abstract public void insert_wstring(String s) throws MARSHAL; + + /** + * Extracts the TypeCode object in this + * Any object's value field. + * + * @return the TypeCode object stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a TypeCode object or the + * value field has not yet been set + */ + abstract public TypeCode extract_TypeCode() throws BAD_OPERATION; + + /** + * Inserts the given TypeCode object + * into this Any object's value field. + * + * @param t the TypeCode object to insert into this + * Any object + */ + abstract public void insert_TypeCode(TypeCode t); + + /** + * Extracts the Principal object in this + * Any object's value field. + * Note that the class Principal has been deprecated. + * + * @return the Principal object stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a + * Principal object or the + * value field has not yet been set + * @see CORBA package + * comments for unimplemented features + * @deprecated Deprecated by CORBA 2.2. + */ + // @Deprecated + public Principal extract_Principal() throws BAD_OPERATION { + throw new org.omg.CORBA.NO_IMPLEMENT() ; + } + + /** + * Inserts the given Principal object + * into this Any object's value field. + * Note that the class Principal has been deprecated. + * + * @param p the Principal object to insert into this + * Any object + * @see CORBA package + * comments for unimplemented features + * @deprecated Deprecated by CORBA 2.2. + */ + // @Deprecated + public void insert_Principal(Principal p) { + throw new org.omg.CORBA.NO_IMPLEMENT() ; + } + + /////////////////////////////////////////////////////////////////////////// + // insertion/extraction of streamables + + /** + * Extracts a Streamable from this Any object's + * value field. This method allows the extraction of + * non-primitive IDL types. + * + * @return the Streamable stored in the Any object. + * @throws BAD_INV_ORDER if the caller has invoked operations in the wrong order + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.portable.Streamable extract_Streamable() + throws org.omg.CORBA.BAD_INV_ORDER { + throw new org.omg.CORBA.NO_IMPLEMENT() ; + } + + /** + * Inserts the given Streamable object + * into this Any object's value field. + * This method allows the insertion of non-primitive IDL types. + * + * @param s the Streamable object to insert into this + * Any object; may be a non-primitive + * IDL type + * @see CORBA package + * comments for unimplemented features + */ + public void insert_Streamable(Streamable s) { + throw new org.omg.CORBA.NO_IMPLEMENT() ; + } + + /** + * Extracts the java.math.BigDecimal object in this + * Any object's value field. + * + * @return the java.math.BigDecimal object + * stored in this Any object + * @exception BAD_OPERATION if this Any object + * contains something other than a + * java.math.BigDecimal object or the + * value field has not yet been set + * @see CORBA package + * comments for unimplemented features + */ + public java.math.BigDecimal extract_fixed() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Throws an + * org.omg.CORBA.NO_IMPLEMENT exception. + *

    + * Inserts the given java.math.BigDecimal object + * into this Any object's value field. + * + * @param value the java.math.BigDecimal object + * to insert into this Any object + * @see CORBA package + * comments for unimplemented features + */ + public void insert_fixed(java.math.BigDecimal value) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Throws an + * org.omg.CORBA.NO_IMPLEMENT exception. + *

    + * Inserts the given java.math.BigDecimal object + * into this Any object's value field. + * + * @param value the java.math.BigDecimal object + * to insert into this Any object + * @param type the TypeCode object that is to be inserted into + * this Any object's type field + * and that describes the java.math.BigDecimal + * object being inserted + * @throws org.omg.CORBA.BAD_INV_ORDER if this method is invoked improperly + * @see CORBA package + * comments for unimplemented features + */ + public void insert_fixed(java.math.BigDecimal value, org.omg.CORBA.TypeCode type) + throws org.omg.CORBA.BAD_INV_ORDER + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/AnyHolder.java b/omgapi/src/main/java/org/omg/CORBA/AnyHolder.java new file mode 100644 index 000000000..553632a3a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/AnyHolder.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Any. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for Any objects + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL any as an "out" + * or "inout" parameter, the programmer must pass an instance of + * AnyHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myAnyHolder is an instance of AnyHolder, + * the value stored in its value field can be accessed with + * myAnyHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class AnyHolder implements Streamable { + /** + * The Any value held by this AnyHolder object. + */ + + public Any value; + + /** + * Constructs a new AnyHolder object with its + * value field initialized to null. + */ + public AnyHolder() { + } + + /** + * Constructs a new AnyHolder object for the given + * Any object. + * @param initial the Any object with which to initialize + * the value field of the new + * AnyHolder object + */ + public AnyHolder(Any initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in the Holder + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire. + */ + public void _read(InputStream input) { + value = input.read_any(); + } + + /** + * Marshals to output the value in + * this AnyHolder object. + * + * @param output the OutputStream which will contain the CDR formatted data. + */ + public void _write(OutputStream output) { + output.write_any(value); + } + + /** + * Returns the TypeCode object corresponding to the value + * held in this AnyHolder object. + * + * @return the TypeCode of the value held in + * this AnyHolder object + */ + public TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_any); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/AnySeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/AnySeqHelper.java new file mode 100644 index 000000000..a782eb016 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/AnySeqHelper.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for AnySeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/AnySeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class AnySeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/AnySeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Any[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Any[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.AnySeqHelper.id (), "AnySeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Any[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.Any value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.Any[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Any[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + ostream.write_any (value[_i0]); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/AnySeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/AnySeqHolder.java new file mode 100644 index 000000000..1c4598744 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/AnySeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for AnySeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/AnySeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class AnySeqHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Any value[] = null; + + public AnySeqHolder () + { + } + + public AnySeqHolder (org.omg.CORBA.Any[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.AnySeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.AnySeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.AnySeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_CONTEXT.java b/omgapi/src/main/java/org/omg/CORBA/BAD_CONTEXT.java new file mode 100644 index 000000000..5532ac70b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_CONTEXT.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when an operation is invoked by a client but the passed + * context does not contain the context values required by the operation.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class BAD_CONTEXT extends SystemException { + + /** + * Constructs a BAD_CONTEXT exception + * with a default minor code + * of 0 and a completion state of COMPLETED_NO. + */ + public BAD_CONTEXT() { + this(""); + } + + /** + * Constructs a BAD_CONTEXT exception + * with the specified detail message, a minor code + * of 0 and a completion state of COMPLETED_NO. + * @param s a String object containing a detail message + */ + public BAD_CONTEXT(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a BAD_CONTEXT exception + * with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_CONTEXT(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a BAD_CONTEXT exception + * with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_CONTEXT(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_INV_ORDER.java b/omgapi/src/main/java/org/omg/CORBA/BAD_INV_ORDER.java new file mode 100644 index 000000000..2ec0ab0a6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_INV_ORDER.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates that the caller has invoked operations in + * the wrong order. For example, it can be raised by an ORB if an + * application makes an ORB-related call without having correctly + * initialized the ORB first.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.18, 09/09/97 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class BAD_INV_ORDER extends SystemException { + + /** + * Constructs a BAD_INV_ORDER exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public BAD_INV_ORDER() { + this(""); + } + + /** + * Constructs a BAD_INV_ORDER exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * + * @param s the String containing a detail message + */ + public BAD_INV_ORDER(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a BAD_INV_ORDER exceptionBAD_INV_ORDER with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_INV_ORDER(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a BAD_INV_ORDER exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public BAD_INV_ORDER(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_OPERATION.java b/omgapi/src/main/java/org/omg/CORBA/BAD_OPERATION.java new file mode 100644 index 000000000..3b21537a4 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_OPERATION.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when an object reference denotes an existing object, + * but that the object does not support the operation that was invoked.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class BAD_OPERATION extends SystemException { + + /** + * Constructs a BAD_OPERATION exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public BAD_OPERATION() { + this(""); + } + + /** + * Constructs a BAD_OPERATION exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public BAD_OPERATION(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a BAD_OPERATION exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_OPERATION(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a BAD_OPERATION exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_OPERATION(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_PARAM.java b/omgapi/src/main/java/org/omg/CORBA/BAD_PARAM.java new file mode 100644 index 000000000..90b61821e --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_PARAM.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown + * when a parameter passed to a call is out of range or + * otherwise considered illegal. An ORB may raise this exception + * if null values or null pointers are passed to an operation (for + * language mappings where the concept of a null pointers or null + * values applies). BAD_PARAM can also be raised as a result of a + * client generating requests with incorrect parameters using the DII.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @see meaning of + * minor codes + * @version 1.18, 09/09/97 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class BAD_PARAM extends SystemException { + + /** + * Constructs a BAD_PARAM exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public BAD_PARAM() { + this(""); + } + + /** + * Constructs a BAD_PARAM exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * + * @param s the String containing a detail message describing this + * exception + */ + public BAD_PARAM(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a BAD_PARAM exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public BAD_PARAM(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a BAD_PARAM exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes + * this particular exception. + * + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public BAD_PARAM(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY.java b/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY.java new file mode 100644 index 000000000..f38db145c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; +/** + * A PolicyErrorCode which would be filled in + * the PolicyError exception. + * + * @author rip-dev + * @version 1.16 07/27/07 + */ + +public interface BAD_POLICY { + /** + * The Error code in PolicyError exception. + */ + final short value = (short) (0L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY_TYPE.java b/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY_TYPE.java new file mode 100644 index 000000000..f8d37eeeb --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY_TYPE.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A PolicyErrorCode which would be filled in + * the PolicyError exception. + * + * @author rip-dev + * @version 1.16 07/27/07 + */ +public interface BAD_POLICY_TYPE { + /** + * The Error code in PolicyError exception. + */ + final short value = (short) (2L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY_VALUE.java b/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY_VALUE.java new file mode 100644 index 000000000..726b9c65b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_POLICY_VALUE.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* Contains the value used to indicate a policy value that is +* incorrect for a valid policy type in a call to the +* create_policy method defined in the ORB class. +* +* @version 1.15 07/27/07 +*/ +public interface BAD_POLICY_VALUE { + /** + * The value used to represent a bad policy value error + * in a PolicyError exception. + * @see org.omg.CORBA.PolicyError + */ + final short value = (short) (3L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_QOS.java b/omgapi/src/main/java/org/omg/CORBA/BAD_QOS.java new file mode 100644 index 000000000..8de77b94e --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_QOS.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The BAD_QOS exception is raised whenever an object cannot + * support the quality of service required by an invocation parameter that + * has a quality of service semantics associated with it. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class BAD_QOS extends SystemException { + + /** + * Constructs an BAD_QOS exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public BAD_QOS() { + this(""); + } + + /** + * Constructs an BAD_QOS exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public BAD_QOS(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an BAD_QOS exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public BAD_QOS(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an BAD_QOS exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public BAD_QOS(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BAD_TYPECODE.java b/omgapi/src/main/java/org/omg/CORBA/BAD_TYPECODE.java new file mode 100644 index 000000000..d23f04c81 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BAD_TYPECODE.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when the ORB has encountered a malformed type code + * (for example, a type code with an invalid TCKind value).

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class BAD_TYPECODE extends SystemException { + + /** + * Constructs a BAD_TYPECODE exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public BAD_TYPECODE() { + this(""); + } + + /** + * Constructs a BAD_TYPECODE exception with the specified detail, + * a minor code of 0, and a completion state of COMPLETED_NO. + * + * @param s the String containing a detail message + */ + public BAD_TYPECODE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a BAD_TYPECODE exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_TYPECODE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a BAD_TYPECODE exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed an instance of CompletionStatus indicating + * the completion status + */ + public BAD_TYPECODE(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BooleanHolder.java b/omgapi/src/main/java/org/omg/CORBA/BooleanHolder.java new file mode 100644 index 000000000..114bf4f2b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BooleanHolder.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + + +/** + * The Holder for Boolean. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a boolean + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL boolean as an "out" + * or "inout" parameter, the programmer must pass an instance of + * BooleanHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myBooleanHolder is an instance of BooleanHolder, + * the value stored in its value field can be accessed with + * myBooleanHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class BooleanHolder implements Streamable { + + /** + * The boolean value held by this BooleanHolder + * object. + */ + public boolean value; + + /** + * Constructs a new BooleanHolder object with its + * value field initialized to false. + */ + public BooleanHolder() { + } + + /** + * Constructs a new BooleanHolder object with its + * value field initialized with the given boolean. + * @param initial the boolean with which to initialize + * the value field of the newly-created + * BooleanHolder object + */ + public BooleanHolder(boolean initial) { + value = initial; + } + + /** + * Reads unmarshalled data from input and assigns it to this + * BooleanHolder object's value field. + * + * @param input the InputStream object containing + * CDR formatted data from the wire + */ + public void _read(InputStream input) { + value = input.read_boolean(); + } + + /** + * Marshals the value in this BooleanHolder object's + * value field to the output stream output. + * + * @param output the OutputStream which will contain the CDR formatted data + */ + public void _write(OutputStream output) { + output.write_boolean(value); + } + + /** + * Retrieves the TypeCode object that corresponds to the + * value held in this BooleanHolder object. + * + * @return the TypeCode for the value held + * in this BooleanHolder object + */ + public TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_boolean); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BooleanSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/BooleanSeqHelper.java new file mode 100644 index 000000000..dc151b7cb --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BooleanSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for BooleanSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/BooleanSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class BooleanSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/BooleanSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, boolean[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static boolean[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.BooleanSeqHelper.id (), "BooleanSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static boolean[] read (org.omg.CORBA.portable.InputStream istream) + { + boolean value[] = null; + int _len0 = istream.read_long (); + value = new boolean[_len0]; + istream.read_boolean_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, boolean[] value) + { + ostream.write_long (value.length); + ostream.write_boolean_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/BooleanSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/BooleanSeqHolder.java new file mode 100644 index 000000000..f436300a1 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/BooleanSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for BooleanSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/BooleanSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class BooleanSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public boolean value[] = null; + + public BooleanSeqHolder () + { + } + + public BooleanSeqHolder (boolean[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.BooleanSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.BooleanSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.BooleanSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/Bounds.java b/omgapi/src/main/java/org/omg/CORBA/Bounds.java new file mode 100644 index 000000000..8f9f9e7d3 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Bounds.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A user exception thrown when a parameter is not within + * the legal bounds for the object that a method is trying + * to access. + * + * @see documentation on + * Java IDL exceptions + */ + +// @SuppressWarnings({"serial"}) +public final class Bounds extends org.omg.CORBA.UserException { + + /** + * Constructs an Bounds with no specified detail message. + */ + public Bounds() { + super(); + } + + /** + * Constructs an Bounds with the specified detail message. + * + * @param reason the detail message. + */ + public Bounds(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ByteHolder.java b/omgapi/src/main/java/org/omg/CORBA/ByteHolder.java new file mode 100644 index 000000000..9db0b3080 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ByteHolder.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Byte. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a byte + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL octet as an "out" + * or "inout" parameter, the programmer must pass an instance of + * ByteHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myByteHolder is an instance of ByteHolder, + * the value stored in its value field can be accessed with + * myByteHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class ByteHolder implements Streamable { + /** + * The byte value held by this ByteHolder + * object. + */ + + public byte value; + + /** + * Constructs a new ByteHolder object with its + * value field initialized to 0. + */ + public ByteHolder() { + } + + /** + * Constructs a new ByteHolder object for the given + * byte. + * @param initial the byte with which to initialize + * the value field of the new + * ByteHolder object + */ + public ByteHolder(byte initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in + * this ByteHolder object + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire. + */ + public void _read(InputStream input) { + value = input.read_octet(); + } + + /** + * Marshals to output the value in + * this ByteHolder object. + * + * @param output the OutputStream which will contain the CDR formatted data. + */ + public void _write(OutputStream output) { + output.write_octet(value); + } + + /** + * Returns the TypeCode corresponding to the value held in + * this ByteHolder object. + * + * @return the TypeCode of the value held in + * this ByteHolder object + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_octet); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CODESET_INCOMPATIBLE.java b/omgapi/src/main/java/org/omg/CORBA/CODESET_INCOMPATIBLE.java new file mode 100644 index 000000000..fb3388a39 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CODESET_INCOMPATIBLE.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception is raised whenever meaningful communication is not possible + * between client and server native code sets. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class CODESET_INCOMPATIBLE extends SystemException { + + /** + * Constructs an CODESET_INCOMPATIBLE exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public CODESET_INCOMPATIBLE() { + this(""); + } + + /** + * Constructs an CODESET_INCOMPATIBLE exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public CODESET_INCOMPATIBLE(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an CODESET_INCOMPATIBLE exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public CODESET_INCOMPATIBLE(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an CODESET_INCOMPATIBLE exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public CODESET_INCOMPATIBLE(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/COMM_FAILURE.java b/omgapi/src/main/java/org/omg/CORBA/COMM_FAILURE.java new file mode 100644 index 000000000..6b2d813cc --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/COMM_FAILURE.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception is raised if communication is lost while an operation + * is in progress, after the request was sent by the client, but before + * the reply from the server has been returned to the client.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section meaning + * of minor codes to see the minor codes for this exception. + * + * @see meaning of + * minor codes + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class COMM_FAILURE extends SystemException { + + /** + * Constructs a COMM_FAILURE exception with + * a default minor code of 0 and a completion state of COMPLETED_NO. + */ + public COMM_FAILURE() { + this(""); + } + + /** + * Constructs a COMM_FAILURE exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * + * @param s the String containing a detail message describing + * this exception + */ + public COMM_FAILURE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a COMM_FAILURE exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status, which must be one of + * COMPLETED_YES, COMPLETED_NO, or + * COMPLETED_MAYBE. + */ + public COMM_FAILURE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a COMM_FAILURE exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status, which must be one of + * COMPLETED_YES, COMPLETED_NO, or + * COMPLETED_MAYBE. + */ + public COMM_FAILURE(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CTX_RESTRICT_SCOPE.java b/omgapi/src/main/java/org/omg/CORBA/CTX_RESTRICT_SCOPE.java new file mode 100644 index 000000000..4c35d2073 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CTX_RESTRICT_SCOPE.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A flag that can be used as the second parameter to the method + * Context.get_values to restrict the search scope. + * When this flag is used, it restricts the search for + * context values to this particular Context object + * or to the scope specified in the first parameter to + * Context.get_values. + *

    + * Usage: + *

    + *     NVList props = myContext.get_values("_USER",
    + *                     CTX_RESTRICT_SCOPE.value, "id*");
    + * 
    + * + * @see org.omg.CORBA.Context#get_values(String, int, String) + * @version 1.3, 09/09/97 + * @since JDK1.2 + */ +public interface CTX_RESTRICT_SCOPE { + +/** + * The field containing the int value of a + * CTX_RESTRICT_SCOPE flag. + */ + int value = 15; +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/CharHolder.java b/omgapi/src/main/java/org/omg/CORBA/CharHolder.java new file mode 100644 index 000000000..fd48ac700 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CharHolder.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Char. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a char + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL char as an "out" + * or "inout" parameter, the programmer must pass an instance of + * CharHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myCharHolder is an instance of CharHolder, + * the value stored in its value field can be accessed with + * myCharHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class CharHolder implements Streamable { + + /** + * The char value held by this CharHolder + * object. + */ + public char value; + + /** + * Constructs a new CharHolder object with its + * value field initialized to 0. + */ + public CharHolder() { + } + + /** + * Constructs a new CharHolder object for the given + * char. + * @param initial the char with which to initialize + * the value field of the new + * CharHolder object + */ + public CharHolder(char initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in + * this CharHolder object + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire + */ + public void _read(InputStream input) { + value = input.read_char(); + } + + /** + * Marshals to output the value in + * this CharHolder object. + * + * @param output the OutputStream which will contain the CDR formatted data + */ + public void _write(OutputStream output) { + output.write_char(value); + } + + /** + * Returns the TypeCode object corresponding + * to the value held in + * this CharHolder object. + * + * @return the TypeCode of the value held in + * this CharHolder object + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_char); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CharSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/CharSeqHelper.java new file mode 100644 index 000000000..ea9020fa8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CharSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for CharSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/CharSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class CharSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/CharSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, char[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static char[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_char); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.CharSeqHelper.id (), "CharSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static char[] read (org.omg.CORBA.portable.InputStream istream) + { + char value[] = null; + int _len0 = istream.read_long (); + value = new char[_len0]; + istream.read_char_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, char[] value) + { + ostream.write_long (value.length); + ostream.write_char_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CharSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/CharSeqHolder.java new file mode 100644 index 000000000..79b5fef83 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CharSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for CharSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/CharSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class CharSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public char value[] = null; + + public CharSeqHolder () + { + } + + public CharSeqHolder (char[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.CharSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.CharSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.CharSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CompletionStatus.java b/omgapi/src/main/java/org/omg/CORBA/CompletionStatus.java new file mode 100644 index 000000000..2e258589f --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CompletionStatus.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object that indicates whether a method had completed running + * when a SystemException was thrown. + *

    + * The class CompletionStatus + * contains three CompletionStatus instances, which are constants + * representing each + * possible completion status: COMPLETED_MAYBE, + * COMPLETED_NO, and COMPLETED_YES. + * It also contains + * three int members, each a constant corresponding to one of + * the CompletionStatus instances. These int + * members make it possible to use a switch statement. + *

    + * The class also contains two methods: + *

      + *
    • public int value() -- which accesses the + * value field of a CompletionStatus object + *
    • public static CompletionStatus + * from_int(int i) -- + * for creating an instance from one of the int members + *
    + * @version %I, %G + * @see org.omg.CORBA.SystemException + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class CompletionStatus implements org.omg.CORBA.portable.IDLEntity +{ +/** + * The constant indicating that a method completed running + * before a SystemException was thrown. + */ + public static final int _COMPLETED_YES = 0, + +/** + * The constant indicating that a method had not completed running + * when a SystemException was thrown. + */ + _COMPLETED_NO = 1, + +/** + * The constant indicating that it is unknown whether a method had + * completed running when a SystemException was thrown. + */ + _COMPLETED_MAYBE = 2; + + +/** + * An instance of CompletionStatus initialized with + * the constant _COMPLETED_YES. + */ + public static final CompletionStatus COMPLETED_YES = new CompletionStatus(_COMPLETED_YES); + +/** + * An instance of CompletionStatus initialized with + * the constant _COMPLETED_NO. + */ + public static final CompletionStatus COMPLETED_NO = new CompletionStatus(_COMPLETED_NO); + + /** + * An instance of CompletionStatus initialized with + * the constant _COMPLETED_MAYBE. + */ + public static final CompletionStatus COMPLETED_MAYBE = new CompletionStatus(_COMPLETED_MAYBE); + + /** + * Retrieves the value of this CompletionStatus object. + * + * @return one of the possible CompletionStatus values: + * _COMPLETED_YES, _COMPLETED_NO, or + * _COMPLETED_MAYBE + * + */ + public int value() { return _value; } + +/** + * Creates a CompletionStatus object from the given int. + * + * @param i one of _COMPLETED_YES, _COMPLETED_NO, or + * _COMPLETED_MAYBE + * + * @return one of the possible CompletionStatus objects + * with values: + * _COMPLETED_YES, _COMPLETED_NO, or + * _COMPLETED_MAYBE + * + * @exception org.omg.CORBA.BAD_PARAM if the argument given is not one of the + * int constants defined in CompletionStatus + */ + public static CompletionStatus from_int(int i) { + switch (i) { + case _COMPLETED_YES: + return COMPLETED_YES; + case _COMPLETED_NO: + return COMPLETED_NO; + case _COMPLETED_MAYBE: + return COMPLETED_MAYBE; + default: + throw new org.omg.CORBA.BAD_PARAM(); + } + } + + +/** + * Creates a CompletionStatus object from the given int. + * + * @param _value one of _COMPLETED_YES, _COMPLETED_NO, or + * _COMPLETED_MAYBE + * + */ + private CompletionStatus(int _value) { + this._value = _value; + } + + private int _value; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CompletionStatusHelper.java b/omgapi/src/main/java/org/omg/CORBA/CompletionStatusHelper.java new file mode 100644 index 000000000..504d861eb --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CompletionStatusHelper.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for CompletionStatus. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/CompletionStatusHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* 03 June 1999 11:52:03 o'clock GMT+00:00 +*/ + +abstract public class CompletionStatusHelper +{ + private static String _id = "IDL:omg.org/CORBA/CompletionStatus:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.CompletionStatus that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.CompletionStatus extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.CompletionStatusHelper.id (), "CompletionStatus", new String[] { "COMPLETED_YES", "COMPLETED_NO", "COMPLETED_MAYBE"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.CompletionStatus read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.CompletionStatus.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.CompletionStatus value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/Context.java b/omgapi/src/main/java/org/omg/CORBA/Context.java new file mode 100644 index 000000000..a685b0a80 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Context.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object used in Request operations + * to specify the context object in which context strings + * must be resolved before being sent along with the request invocation. + * A Context object + * contains a list of properties in the form of NamedValue + * objects. These properties represent information + * about the client, the environment, or the circumstances of a request + * and generally are properties that might be inconvenient + * to pass as parameters. + *

    + * A Context object is created by first calling the + * ORB method get_default_context + * and then calling the method create_child on the + * default context. + *

    + * Each property in a Context object is represented by + * a NamedValue object. The property name is contained + * in the NamedValue object's name field, and + * the value associated with the name is contained in the Any + * object that was assigned to the NamedValue object's + * value field. + *

    + * Context properties can represent a portion of a client's + * or application's environment that is meant to be propagated to + * (and made implicitly part of) a server's environment. + * (Examples might be a window identifier or user preference information). + * Once a server has been invoked (that is, after the properties are + * propagated), the server may query its Context object + * for these properties using the method get_values. + * + *

    + * When an operation declaration includes a context clause, + * the stubs and skeletons will have an additional argument + * added for the context. When an operation invocation occurs, + * the ORB causes the properties that were named in the operation + * definition in IDL and + * that are present in the client's Context object + * to be provided in the Context object parameter to + * the invoked method. + *

    + * Context property names (which are strings) + * typically have the form of an OMG IDL identifier or + * a series of OMG IDL identifiers separated by periods. + * A context property name pattern is either a property name + * or a property name followed by a single "*". A property + * name pattern without a trailing "*" is said to match only + * itself. A property name pattern of the form "<name>*" matches any + * property name that starts with <name> and continues with zero + * or more additional characters. + *

    + * Property name patterns are used in the context clause of + * an operation definition and as a parameter for the + * method Context.get_values. + *

    + * Context objects may be "chained" together to achieve a + * particular defaulting behavior. A Context + * object created with the method create_child will + * be chained to its parent (the Context object + * that created it), and that means that the parent will be searched + * after the child in a search for property names. + *

    + * Properties defined in a particular Context object + * effectively override those properties in the next higher level. + * The scope used in a search for properties may be restricted by specifying a + * starting scope and by using the flag CTX_RESTRICT_SCOPE + * when invoking the method get_values. + *

    + * A Context object may be named for purposes of specifying + * a starting search scope. + * + * @version 1.11, 09/09/97 + * @since JDK1.2 + */ + +public abstract class Context { + + /** + * Retrieves the name of this Context object. + * + * @return the name of this Context object + */ + + public abstract String context_name(); + + + /** + * Retrieves the parent of this Context object. + * + * @return the Context object that is the + * parent of this Context object + */ + + public abstract Context parent(); + + /** + * Creates a Context object with the given string as its + * name and with this Context object set as its parent. + *

    + * The new Context object is chained into its parent + * Context object. This means that in a search for + * matching property names, if a match is not found in this context, + * the search will continue in the parent. If that is not successful, + * the search will continue in the grandparent, if there is one, and + * so on. + * + * + * @param child_ctx_name the String object to be set as + * the name of the new Context object + * @return the newly-created child Context object + * initialized with the specified name + */ + + public abstract Context create_child(String child_ctx_name); + + /** + * Creates a NamedValue object and adds it to this + * Context object. The name field of the + * new NamedValue object is set to the given string, + * the value field is set to the given Any + * object, and the flags field is set to zero. + * + * @param propname the name of the property to be set + * @param propvalue the Any object to which the + * value of the property will be set. The + * Any object's value + * field contains the value to be associated + * with the given propname; the + * kind field must be set to + * TCKind.tk_string. + */ + + public abstract void set_one_value(String propname, Any propvalue); + + /** + I Sets one or more property values in this Context + * object. The NVList supplied to this method + * contains one or more NamedValue objects. + * In each NamedValue object, + * the name field holds the name of the property, and + * the flags field must be set to zero. + * The NamedValue object's value field + * contains an Any object, which, in turn, contains the value + * for the property. Since the value is always a string, + * the Any object must have the kind + * field of its TypeCode set to TCKind.tk_string. + * + * @param values an NVList containing the property + * names and associated values to be set + * + * @see #get_values + * @see org.omg.CORBA.NamedValue + * @see org.omg.CORBA.Any + */ + + public abstract void set_values(NVList values); + + /** + * Deletes from this Context object the + * NamedValue object(s) whose + * name field matches the given property name. + * If the String object supplied for + * propname has a + * trailing wildcard character ("*"), then + * all NamedValue objects whose name + * fields match will be deleted. The search scope is always + * limited to this Context object. + *

    + * If no matching property is found, an exception is returned. + * + * @param propname name of the property to be deleted + */ + + public abstract void delete_values(String propname); + + /** + * Retrieves the NamedValue objects whose + * name field matches the given name or name + * pattern. This method allows for wildcard searches, + * which means that there can be multiple matches and + * therefore multiple values returned. If the + * property is not found at the indicated level, the search + * continues up the context object tree until a match is found or + * all Context objects in the chain have been exhausted. + *

    + * If no match is found, an error is returned and no property list + * is returned. + * + * @param start_scope a String object indicating the + * context object level at which to initiate the + * search for the specified properties + * (for example, "_USER", "_GROUP", "_SYSTEM"). Valid scope + * names are implementation-specific. If a + * scope name is omitted, the search + * begins with the specified context + * object. If the specified scope name is + * not found, an exception is returned. + * @param op_flags an operation flag. The one flag + * that may be specified is CTX_RESTRICT_SCOPE. + * If this flag is specified, searching is limited to the + * specified start_scope or this + * Context object. + * @param pattern the property name whose values are to + * be retrieved. pattern may be a + * name or a name with a + * trailing wildcard character ("*"). + * + * @return an NVList containing all the property values + * (in the form of NamedValue objects) + * whose associated property name matches the given name or + * name pattern + * @see #set_values + * @see org.omg.CORBA.NamedValue + */ + + abstract public NVList get_values(String start_scope, int op_flags, + String pattern); +}; + diff --git a/omgapi/src/main/java/org/omg/CORBA/ContextList.java b/omgapi/src/main/java/org/omg/CORBA/ContextList.java new file mode 100644 index 000000000..9d65236c6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ContextList.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object containing a modifiable list of String objects + * that represent property names. + * This class is used in Request operations to + * describe the contexts that need to be resolved and sent with the + * invocation. (A context is resolved by giving a property name + * and getting back the value associated with it.) This is done + * by calling the Context method + * get_values and supplying a string from a + * ContextList object as the third parameter. + * The method get_values returns an NVList + * object containing the NamedValue objects that hold + * the value(s) identified by the given string. + *

    + * A ContextList object is created by the ORB, as + * illustrated here: + *

    + *   ORB orb = ORB.init(args, null);
    + *   org.omg.CORBA.ContextList ctxList = orb.create_context_list();
    + * 
    + * The variable ctxList represents an empty + * ContextList object. Strings are added to + * the list with the method add, accessed + * with the method item, and removed with the + * method remove. + * + * @see Context + * @version 1.2, 09/09/97 + * @since JDK1.2 + */ + +public abstract class ContextList { + + /** + * Returns the number of String objects in this + * ContextList object. + * + * @return an int representing the number of + * Strings in this ContextList object + */ + + public abstract int count(); + + /** + * Adds a String object to this ContextList + * object. + * + * @param ctx the String object to be added + */ + + public abstract void add(String ctx); + + /** + * Returns the String object at the given index. + * + * @param index the index of the string desired, with 0 being the + index of the first string + * @return the string at the given index + * @exception org.omg.CORBA.Bounds if the index is greater than + * or equal to the number of strings in this + * ContextList object + */ + + public abstract String item(int index) throws org.omg.CORBA.Bounds; + + /** + * Removes the String object at the given index. Note that + * the indices of all strings following the one removed are + * shifted down by one. + * + * @param index the index of the String object to be removed, + * with 0 designating the first string + * @exception org.omg.CORBA.Bounds if the index is greater than + * or equal to the number of String objects in + * this ContextList object + */ + + public abstract void remove(int index) throws org.omg.CORBA.Bounds; + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/Current.java b/omgapi/src/main/java/org/omg/CORBA/Current.java new file mode 100644 index 000000000..d04508ba6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Current.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* Interfaces derived from the Current interface enable ORB and CORBA +* services to provide access to information (context) associated with +* the thread of execution in which they are running. This information +* is accessed in a structured manner using interfaces derived from the +* Current interface defined in the CORBA module. +* +*

    Each ORB or CORBA service that needs its own context derives an +* interface from the CORBA module's Current. Users of the +* service can obtain an instance of the appropriate Current +* interface by invoking ORB::resolve_initial_references.

    +* +* org/omg/CORBA/Current.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:21 AM PDT. +*/ + +public interface Current extends CurrentOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} // interface Current diff --git a/omgapi/src/main/java/org/omg/CORBA/CurrentHelper.java b/omgapi/src/main/java/org/omg/CORBA/CurrentHelper.java new file mode 100644 index 000000000..5befc818f --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CurrentHelper.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for Current. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/CurrentHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:21 AM PDT +*/ + +abstract public class CurrentHelper +{ + private static String _id = "IDL:omg.org/CORBA/Current:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Current that) + { + throw new org.omg.CORBA.MARSHAL() ; + } + + public static org.omg.CORBA.Current extract (org.omg.CORBA.Any a) + { + throw new org.omg.CORBA.MARSHAL() ; + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.CurrentHelper.id (), "Current"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Current read (org.omg.CORBA.portable.InputStream istream) + { + throw new org.omg.CORBA.MARSHAL() ; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Current value) + { + throw new org.omg.CORBA.MARSHAL() ; + } + + public static org.omg.CORBA.Current narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Current) + return (org.omg.CORBA.Current)obj; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CurrentHolder.java b/omgapi/src/main/java/org/omg/CORBA/CurrentHolder.java new file mode 100644 index 000000000..4648be847 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CurrentHolder.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The Holder for Current. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/CurrentHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:21 AM PDT +*/ + +public final class CurrentHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Current value = null; + + public CurrentHolder () + { + } + + public CurrentHolder (org.omg.CORBA.Current initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.CurrentHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.CurrentHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.CurrentHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/CurrentOperations.java b/omgapi/src/main/java/org/omg/CORBA/CurrentOperations.java new file mode 100644 index 000000000..105143d11 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CurrentOperations.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The interface for Current. For more information on +* Operations interfaces, see +* "Generated Files". +* +* org/omg/CORBA/CurrentOperations.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:21 AM PDT. +*/ + +public interface CurrentOperations +{ +} // interface CurrentOperations diff --git a/omgapi/src/main/java/org/omg/CORBA/CustomMarshal.java b/omgapi/src/main/java/org/omg/CORBA/CustomMarshal.java new file mode 100644 index 000000000..f3203392a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/CustomMarshal.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.DataOutputStream; +import org.omg.CORBA.DataInputStream; + +/** + * An abstract value type that is meant to + * be used by the ORB, not the user. Semantically it is treated + * as a custom valuetype's implicit base class, although the custom + * valutype does not actually inherit it in IDL. The implementer + * of a custom value type shall provide an implementation of the + * CustomMarshal operations. The manner in which this is done is + * specified in the IDL to Java langague mapping. Each custom + * marshaled value type shall have its own implementation. + * @see DataOuputStream + * @see DataInputStream + */ +public interface CustomMarshal { + /** + * Marshal method has to be implemented by the Customized Marshal class + * This is the method invoked for Marshalling. + * + * @param os a DataOutputStream + */ + void marshal(DataOutputStream os); + /** + * Unmarshal method has to be implemented by the Customized Marshal class + * This is the method invoked for Unmarshalling. + * + * @param is a DataInputStream + */ + void unmarshal(DataInputStream is); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DATA_CONVERSION.java b/omgapi/src/main/java/org/omg/CORBA/DATA_CONVERSION.java new file mode 100644 index 000000000..23e4fbea8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DATA_CONVERSION.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception is raised if an ORB cannot convert the representation + * of data as marshaled into its native representation or vice-versa. + * For example, DATA_CONVERSION can be raised if wide character codeset + * conversion fails, or if an ORB cannot convert floating point values + * between different representations.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section meaning + * of minor codes to see the minor codes for this exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16, 09/09/97 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class DATA_CONVERSION extends SystemException { + + /** + * Constructs a DATA_CONVERSION exception with a default minor code + * of 0 and a completion state of COMPLETED_NO. + */ + public DATA_CONVERSION() { + this(""); + } + + /** + * Constructs a DATA_CONVERSION exception with the specified detail. + * @param s the String containing a detail message + */ + public DATA_CONVERSION(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a DATA_CONVERSION exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public DATA_CONVERSION(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a DATA_CONVERSION exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public DATA_CONVERSION(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DataInputStream.java b/omgapi/src/main/java/org/omg/CORBA/DataInputStream.java new file mode 100644 index 000000000..51b854cfa --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DataInputStream.java @@ -0,0 +1,331 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Defines the methods used to read primitive data types from input streams +* for unmarshaling custom value types. This interface is used by user +* written custom unmarshaling code for custom value types. +* @see org.omg.CORBA.DataOutputStream +* @see org.omg.CORBA.CustomMarshal +* @version 1.13 07/27/07 +*/ +public interface DataInputStream extends org.omg.CORBA.portable.ValueBase +{ + /** Reads an IDL Any value from the input stream. + * @return the Any read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + org.omg.CORBA.Any read_any (); + + /** Reads an IDL boolean value from the input stream. + * @return the boolean read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + boolean read_boolean (); + + /** Reads an IDL character value from the input stream. + * @return the character read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + char read_char (); + + /** Reads an IDL wide character value from the input stream. + * @return the wide character read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + char read_wchar (); + + /** Reads an IDL octet value from the input stream. + * @return the octet value read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + byte read_octet (); + + /** Reads an IDL short from the input stream. + * @return the short read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + short read_short (); + + /** Reads an IDL unsigned short from the input stream. + * @return the unsigned short read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + short read_ushort (); + + /** Reads an IDL long from the input stream. + * @return the long read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + int read_long (); + + /** Reads an IDL unsigned long from the input stream. + * @return the unsigned long read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + int read_ulong (); + + /** Reads an IDL long long from the input stream. + * @return the long long read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + long read_longlong (); + + /** Reads an unsigned IDL long long from the input stream. + * @return the unsigned long long read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + long read_ulonglong (); + + /** Reads an IDL float from the input stream. + * @return the float read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + float read_float (); + + /** Reads an IDL double from the input stream. + * @return the double read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + double read_double (); + // read_longdouble not supported by IDL/Java mapping + + /** Reads an IDL string from the input stream. + * @return the string read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + String read_string (); + + /** Reads an IDL wide string from the input stream. + * @return the wide string read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + String read_wstring (); + + /** Reads an IDL CORBA::Object from the input stream. + * @return the CORBA::Object read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + org.omg.CORBA.Object read_Object (); + + /** Reads an IDL Abstract interface from the input stream. + * @return the Abstract interface read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + java.lang.Object read_Abstract (); + + /** Reads an IDL value type from the input stream. + * @return the value type read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + java.io.Serializable read_Value (); + + /** Reads an IDL typecode from the input stream. + * @return the typecode read. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + org.omg.CORBA.TypeCode read_TypeCode (); + + /** Reads array of IDL Anys from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_any_array (org.omg.CORBA.AnySeqHolder seq, int offset, int length); + + /** Reads array of IDL booleans from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_boolean_array (org.omg.CORBA.BooleanSeqHolder seq, int offset, int length); + + /** Reads array of IDL characters from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_char_array (org.omg.CORBA.CharSeqHolder seq, int offset, int length); + + /** Reads array of IDL wide characters from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_wchar_array (org.omg.CORBA.WCharSeqHolder seq, int offset, int length); + + /** Reads array of IDL octets from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_octet_array (org.omg.CORBA.OctetSeqHolder seq, int offset, int length); + + /** Reads array of IDL shorts from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_short_array (org.omg.CORBA.ShortSeqHolder seq, int offset, int length); + + /** Reads array of IDL unsigned shorts from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_ushort_array (org.omg.CORBA.UShortSeqHolder seq, int offset, int length); + + /** Reads array of IDL longs from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_long_array (org.omg.CORBA.LongSeqHolder seq, int offset, int length); + + /** Reads array of IDL unsigned longs from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_ulong_array (org.omg.CORBA.ULongSeqHolder seq, int offset, int length); + + /** Reads array of IDL unsigned long longs from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_ulonglong_array (org.omg.CORBA.ULongLongSeqHolder seq, int offset, int length); + + /** Reads array of IDL long longs from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_longlong_array (org.omg.CORBA.LongLongSeqHolder seq, int offset, int length); + + /** Reads array of IDL floats from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_float_array (org.omg.CORBA.FloatSeqHolder seq, int offset, int length); + + /** Reads array of IDL doubles from offset for length elements from the + * input stream. + * @param seq The out parameter holder for the array to be read. + * @param offset The index into seq of the first element to read from the + * input stream. + * @param length The number of elements to read from the input stream. + * @throws org.omg.CORBA.MARSHAL + * If an inconsistency is detected, including not having registered + * a streaming policy, then the standard system exception MARSHAL is raised. + */ + void read_double_array (org.omg.CORBA.DoubleSeqHolder seq, int offset, int length); +} // interface DataInputStream + diff --git a/omgapi/src/main/java/org/omg/CORBA/DataOutputStream.java b/omgapi/src/main/java/org/omg/CORBA/DataOutputStream.java new file mode 100644 index 000000000..7b46f59ec --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DataOutputStream.java @@ -0,0 +1,269 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Defines the methods used to write primitive data types to output streams +* for marshalling custom value types. This interface is used by user +* written custom marshalling code for custom value types. +* @see org.omg.CORBA.DataInputStream +* @see org.omg.CORBA.CustomMarshal +* @version 1.15 07/27/07 +*/ +public interface DataOutputStream extends org.omg.CORBA.portable.ValueBase +{ + /** + * Writes the Any value to the output stream. + * @param value The value to be written. + */ + void write_any (org.omg.CORBA.Any value); + + /** + * Writes the boolean value to the output stream. + * @param value The value to be written. + */ + void write_boolean (boolean value); + + /** + * Writes the IDL character value to the output stream. + * @param value The value to be written. + */ + void write_char (char value); + + /** + * Writes the IDL wide character value to the output stream. + * @param value The value to be written. + */ + void write_wchar (char value); + + /** + * Writes the IDL octet value (represented as a Java byte) to the output stream. + * @param value The value to be written. + */ + void write_octet (byte value); + + /** + * Writes the IDL short value to the output stream. + * @param value The value to be written. + */ + void write_short (short value); + + /** + * Writes the IDL unsigned short value (represented as a Java short + * value) to the output stream. + * @param value The value to be written. + */ + void write_ushort (short value); + + /** + * Writes the IDL long value (represented as a Java int) to the output stream. + * @param value The value to be written. + */ + void write_long (int value); + + /** + * Writes the IDL unsigned long value (represented as a Java int) to the output stream. + * @param value The value to be written. + */ + void write_ulong (int value); + + /** + * Writes the IDL long long value (represented as a Java long) to the output stream. + * @param value The value to be written. + */ + void write_longlong (long value); + + /** + * Writes the IDL unsigned long long value (represented as a Java long) + * to the output stream. + * @param value The value to be written. + */ + void write_ulonglong (long value); + + /** + * Writes the IDL float value to the output stream. + * @param value The value to be written. + */ + void write_float (float value); + + /** + * Writes the IDL double value to the output stream. + * @param value The value to be written. + */ + void write_double (double value); + + // write_longdouble not supported by IDL/Java mapping + + /** + * Writes the IDL string value to the output stream. + * @param value The value to be written. + */ + void write_string (String value); + + /** + * Writes the IDL wide string value (represented as a Java String) to the output stream. + * @param value The value to be written. + */ + void write_wstring (String value); + + /** + * Writes the IDL CORBA::Object value to the output stream. + * @param value The value to be written. + */ + void write_Object (org.omg.CORBA.Object value); + + /** + * Writes the IDL Abstract interface type to the output stream. + * @param value The value to be written. + */ + void write_Abstract (java.lang.Object value); + + /** + * Writes the IDL value type value to the output stream. + * @param value The value to be written. + */ + void write_Value (java.io.Serializable value); + + /** + * Writes the typecode to the output stream. + * @param value The value to be written. + */ + void write_TypeCode (org.omg.CORBA.TypeCode value); + + /** + * Writes the array of IDL Anys from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_any_array (org.omg.CORBA.Any[] seq, int offset, int length); + + /** + * Writes the array of IDL booleans from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_boolean_array (boolean[] seq, int offset, int length); + + /** + * Writes the array of IDL characters from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_char_array (char[] seq, int offset, int length); + + /** + * Writes the array of IDL wide characters from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_wchar_array (char[] seq, int offset, int length); + + /** + * Writes the array of IDL octets from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_octet_array (byte[] seq, int offset, int length); + + /** + * Writes the array of IDL shorts from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_short_array (short[] seq, int offset, int length); + + /** + * Writes the array of IDL unsigned shorts (represented as Java shorts) + * from offset for length elements to the output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_ushort_array (short[] seq, int offset, int length); + + /** + * Writes the array of IDL longs from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_long_array (int[] seq, int offset, int length); + + /** + * Writes the array of IDL unsigned longs (represented as Java ints) + * from offset for length elements to the output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_ulong_array (int[] seq, int offset, int length); + + /** + * Writes the array of IDL unsigned long longs (represented as Java longs) + * from offset for length elements to the output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_ulonglong_array (long[] seq, int offset, int length); + + /** + * Writes the array of IDL long longs from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_longlong_array (long[] seq, int offset, int length); + + /** + * Writes the array of IDL floats from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_float_array (float[] seq, int offset, int length); + + /** + * Writes the array of IDL doubles from offset for length elements to the + * output stream. + * @param seq The array to be written. + * @param offset The index into seq of the first element to write to the + * output stream. + * @param length The number of elements to write to the output stream. + */ + void write_double_array (double[] seq, int offset, int length); +} // interface DataOutputStream diff --git a/omgapi/src/main/java/org/omg/CORBA/DefinitionKind.java b/omgapi/src/main/java/org/omg/CORBA/DefinitionKind.java new file mode 100644 index 000000000..22c7ad2b7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DefinitionKind.java @@ -0,0 +1,487 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/DefinitionKind.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; + +/** +* The class that provides the constants used to identify the type of an +* Interface Repository object. This class contains two kinds of constants, +* those that are an int and those that are an instance of the class +* DefinitionKind. This class provides the method +* from_int, which given one +* of the int constants, creates the corresponding +* DefinitionKind instance. It also provides the method +* value, which returns the int constant that +* is the value for a DefinitionKind instance. +* +* @see IRObject +*/ + +// @SuppressWarnings({"serial"}) +public class DefinitionKind implements org.omg.CORBA.portable.IDLEntity { + +/** + * The constant that indicates that an Interface Repository object + * does not have a definition kind. + */ + public static final int _dk_none = 0, + +/** + * The constant that indicates that the type of an Interface Repository object + * may be any type. + */ + _dk_all = 1, + +/** + * The constant that indicates that an Interface Repository object is an + * attribute. + */ + _dk_Attribute = 2, + +/** + * The constant that indicates that an Interface Repository object is a + * constant. + */ + _dk_Constant = 3, + +/** + * The constant that indicates that an Interface Repository object is an + * exception. + */ + + _dk_Exception = 4, + +/** + * The constant that indicates that an Interface Repository object is an + * interface. + */ + + _dk_Interface = 5, + +/** + * The constant that indicates that an Interface Repository object is a + * module. + */ + + _dk_Module = 6, + +/** + * The constant that indicates that an Interface Repository object is an + * operation. + */ + + _dk_Operation = 7, + +/** + * The constant that indicates that an Interface Repository object is a + * Typedef. + */ + + _dk_Typedef = 8, + +/** + * The constant that indicates that an Interface Repository object is an + * Alias. + */ + + _dk_Alias = 9, + +/** + * The constant that indicates that an Interface Repository object is a + * Struct. + */ + + _dk_Struct = 10, + +/** + * The constant that indicates that an Interface Repository object is a + * Union. + */ + + _dk_Union = 11, + +/** + * The constant that indicates that an Interface Repository object is an + * Enum. + */ + + _dk_Enum = 12, + +/** + * The constant that indicates that an Interface Repository object is a + * Primitive. + */ + + _dk_Primitive = 13, + +/** + * The constant that indicates that an Interface Repository object is a + * String. + */ + + _dk_String = 14, + +/** + * The constant that indicates that an Interface Repository object is a + * Sequence. + */ + + _dk_Sequence = 15, + +/** + * The constant that indicates that an Interface Repository object is an + * Array. + */ + + _dk_Array = 16, + +/** + * The constant that indicates that an Interface Repository object is a + * Repository. + */ + + _dk_Repository = 17, + +/** + * The constant that indicates that an Interface Repository object is a + * Wstring. + */ + + _dk_Wstring = 18, + +/** + * The constant that indicates that an Interface Repository object is of type + * Fixed. + */ + + _dk_Fixed = 19, + +/** + * The constant that indicates that an Interface Repository object is a + * Value. + */ + + _dk_Value = 20, + +/** + * The constant that indicates that an Interface Repository object is a + * ValueBox. + */ + + _dk_ValueBox = 21, + +/** + * The constant that indicates that an Interface Repository object is a + * ValueMember. + */ + + _dk_ValueMember = 22, + +/** + * The constant that indicates that an Interface Repository object is of type + * Native. + */ + + _dk_Native = 23, + +/** + * The constant that indicates that an Interface Repository object + * is representing an abstract interface. + */ + _dk_AbstractInterface = 24; + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object has no definition kind. + */ + + public static final DefinitionKind dk_none = new DefinitionKind(_dk_none); + + /** + * The wildcard DefinitionKind constant, useful + * in all occasions where any + * DefinitionKind is appropriate. The Container's + * contents method + * makes use of this constant to return all contained definitions of any kind. + */ + + public static final DefinitionKind dk_all = new DefinitionKind(_dk_all); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Attribute. + */ + + public static final DefinitionKind dk_Attribute = new DefinitionKind(_dk_Attribute); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a constant. + */ + + public static final DefinitionKind dk_Constant = new DefinitionKind(_dk_Constant); + + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Exception. + */ + + public static final DefinitionKind dk_Exception = new DefinitionKind(_dk_Exception); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Interface. + */ + + public static final DefinitionKind dk_Interface = new DefinitionKind(_dk_Interface); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Module. + */ + + public static final DefinitionKind dk_Module = new DefinitionKind(_dk_Module); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Operation. + */ + + public static final DefinitionKind dk_Operation = new DefinitionKind(_dk_Operation); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Typedef. + */ + + public static final DefinitionKind dk_Typedef = new DefinitionKind(_dk_Typedef); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Alias. + */ + + public static final DefinitionKind dk_Alias = new DefinitionKind(_dk_Alias); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Struct. + */ + + public static final DefinitionKind dk_Struct = new DefinitionKind(_dk_Struct); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Union. + */ + + public static final DefinitionKind dk_Union = new DefinitionKind(_dk_Union); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Enum. + */ + + public static final DefinitionKind dk_Enum = new DefinitionKind(_dk_Enum); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Primitive. + */ + + public static final DefinitionKind dk_Primitive = new DefinitionKind(_dk_Primitive); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a String. + */ + + public static final DefinitionKind dk_String = new DefinitionKind(_dk_String); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Sequence. + */ + + public static final DefinitionKind dk_Sequence = new DefinitionKind(_dk_Sequence); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is an Array. + */ + + public static final DefinitionKind dk_Array = new DefinitionKind(_dk_Array); + + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Repository. + */ + + public static final DefinitionKind dk_Repository = new DefinitionKind(_dk_Repository); + + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Wstring. + */ + + public static final DefinitionKind dk_Wstring = new DefinitionKind(_dk_Wstring); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Fixed value. + */ + + public static final DefinitionKind dk_Fixed = new DefinitionKind(_dk_Fixed); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Value. + */ + + public static final DefinitionKind dk_Value = new DefinitionKind(_dk_Value); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a ValueBox. + */ + + public static final DefinitionKind dk_ValueBox = new DefinitionKind(_dk_ValueBox); + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a ValueMember. + */ + + public static final DefinitionKind dk_ValueMember = new DefinitionKind(_dk_ValueMember); + + +/** + * The static instance of DefinitionKind indicating that an + * Interface Repository object is a Native value. + */ + + public static final DefinitionKind dk_Native = new DefinitionKind(_dk_Native); + + +/** +* The static instance of DefinitionKind indicating that an +* Interface Repository object represents an abstract interface. +*/ + public static final DefinitionKind dk_AbstractInterface = new DefinitionKind(_dk_AbstractInterface); + + + /** + * Returns the int constant identifying the type of an IR object. + * @return the int constant from the class + * DefinitionKind that is the value of this + * DefinitionKind instance + */ + + public int value() { + return _value; + } + + + /** + * Creates a DefinitionKind instance corresponding to the given code +. + * @param i one of the int constants from the class + * DefinitionKind + * @return the DefinitionKind instance corresponding + * to the given code + * @throws org.omg.CORBA.BAD_PARAM if the given parameter is not + one + * of the int constants from the class + * DefinitionKind + */ + + public static DefinitionKind from_int(int i) { + switch (i) { + case _dk_none: + return dk_none; + case _dk_all: + return dk_all; + case _dk_Attribute: + return dk_Attribute; + case _dk_Constant: + return dk_Constant; + case _dk_Exception: + return dk_Exception; + case _dk_Interface: + return dk_Interface; + case _dk_Module: + return dk_Module; + case _dk_Operation: + return dk_Operation; + case _dk_Typedef: + return dk_Typedef; + case _dk_Alias: + return dk_Alias; + case _dk_Struct: + return dk_Struct; + case _dk_Union: + return dk_Union; + case _dk_Enum: + return dk_Enum; + case _dk_Primitive: + return dk_Primitive; + case _dk_String: + return dk_String; + case _dk_Sequence: + return dk_Sequence; + case _dk_Array: + return dk_Array; + case _dk_Repository: + return dk_Repository; + case _dk_Wstring: + return dk_Wstring; + case _dk_Fixed: + return dk_Fixed; + case _dk_Value: + return dk_Value; + case _dk_ValueBox: + return dk_ValueBox; + case _dk_ValueMember: + return dk_ValueMember; + case _dk_Native: + return dk_Native; + default: + throw new org.omg.CORBA.BAD_PARAM(); + } + } + + /** + * Constructs a DefinitionKind object with its _value + * field initialized with the given value. + * @param _value one of the int constants defined in the + * class DefinitionKind + */ + + protected DefinitionKind(int _value){ + this._value = _value; + } + + /** + * The field that holds a value for a DefinitionKind object. + * @serial + */ + + private int _value; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DefinitionKindHelper.java b/omgapi/src/main/java/org/omg/CORBA/DefinitionKindHelper.java new file mode 100644 index 000000000..e19832748 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DefinitionKindHelper.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for DefinitionKind. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/DefinitionKindHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:43 o'clock GMT+00:00 +*/ + +abstract public class DefinitionKindHelper +{ + private static String _id = "IDL:omg.org/CORBA/DefinitionKind:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.DefinitionKind that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.DefinitionKind extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.DefinitionKindHelper.id (), "DefinitionKind", new String[] { "dk_none", "dk_all", "dk_Attribute", "dk_Constant", "dk_Exception", "dk_Interface", "dk_Module", "dk_Operation", "dk_Typedef", "dk_Alias", "dk_Struct", "dk_Union", "dk_Enum", "dk_Primitive", "dk_String", "dk_Sequence", "dk_Array", "dk_Repository", "dk_Wstring", "dk_Fixed", "dk_Value", "dk_ValueBox", "dk_ValueMember", "dk_Native"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.DefinitionKind read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.DefinitionKind.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.DefinitionKind value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DomainManager.java b/omgapi/src/main/java/org/omg/CORBA/DomainManager.java new file mode 100644 index 000000000..af04e0b5a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DomainManager.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Provides mechanisms for establishing and navigating relationships to + * superior and subordinate domains, as well as for creating and accessing + * policies. The DomainManager has associated with it the policy + * objects for a + * particular domain. The domain manager also records the membership of + * the domain and provides the means to add and remove members. The domain + * manager is itself a member of a domain, possibly the domain it manages. + * The domain manager provides mechanisms for establishing and navigating + * relationships to superior and subordinate domains and + * creating and accessing policies. + */ + +public interface DomainManager extends DomainManagerOperations, + org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/DomainManagerOperations.java b/omgapi/src/main/java/org/omg/CORBA/DomainManagerOperations.java new file mode 100644 index 000000000..3acd23f3b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DomainManagerOperations.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Provides the DomainManager with the means to access policies. + *

    + * The DomainManager has associated with it the policy objects for a + * particular domain. The domain manager also records the membership of + * the domain and provides the means to add and remove members. The domain + * manager is itself a member of a domain, possibly the domain it manages. + * The domain manager provides mechanisms for establishing and navigating + * relationships to superior and subordinate domains and + * creating and accessing policies. + */ + +public interface DomainManagerOperations +{ + /** This returns the policy of the specified type for objects in + * this domain. The types of policies available are domain specific. + * See the CORBA specification for a list of standard ORB policies. + * + *@param policy_type Type of policy to request + */ + public org.omg.CORBA.Policy get_domain_policy(int policy_type); +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/DoubleHolder.java b/omgapi/src/main/java/org/omg/CORBA/DoubleHolder.java new file mode 100644 index 000000000..349ae0375 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DoubleHolder.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Double. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a double + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL double as an "out" + * or "inout" parameter, the programmer must pass an instance of + * DoubleHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myDoubleHolder is an instance of DoubleHolder, + * the value stored in its value field can be accessed with + * myDoubleHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class DoubleHolder implements Streamable { + + /** + * The double value held by this DoubleHolder + * object. + */ + + public double value; + + /** + * Constructs a new DoubleHolder object with its + * value field initialized to 0.0. + */ + public DoubleHolder() { + } + + /** + * Constructs a new DoubleHolder object for the given + * double. + * @param initial the double with which to initialize + * the value field of the new + * DoubleHolder object + */ + public DoubleHolder(double initial) { + value = initial; + } + + /** + * Read a double value from the input stream and store it in the + * value member. + * + * @param input the InputStream to read from. + */ + public void _read(InputStream input) { + value = input.read_double(); + } + + /** + * Write the double value stored in this holder to an + * OutputStream. + * + * @param output the OutputStream to write into. + */ + public void _write(OutputStream output) { + output.write_double(value); + } + + /** + * Return the TypeCode of this holder object. + * + * @return the TypeCode object. + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_double); + } + + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DoubleSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/DoubleSeqHelper.java new file mode 100644 index 000000000..cd5e049fd --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DoubleSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for DoubleSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/DoubleSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class DoubleSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/DoubleSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, double[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static double[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_double); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.DoubleSeqHelper.id (), "DoubleSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static double[] read (org.omg.CORBA.portable.InputStream istream) + { + double value[] = null; + int _len0 = istream.read_long (); + value = new double[_len0]; + istream.read_double_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, double[] value) + { + ostream.write_long (value.length); + ostream.write_double_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DoubleSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/DoubleSeqHolder.java new file mode 100644 index 000000000..f5fdd363c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DoubleSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for DoubleSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/DoubleSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +*/ + +public final class DoubleSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public double value[] = null; + + public DoubleSeqHolder () + { + } + + public DoubleSeqHolder (double[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.DoubleSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.DoubleSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.DoubleSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynAny.java b/omgapi/src/main/java/org/omg/CORBA/DynAny.java new file mode 100644 index 000000000..892e1d215 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynAny.java @@ -0,0 +1,717 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** Enables org.omg.CORBA.Any values to be dynamically + * interpreted (traversed) and + * constructed. A DynAny object is associated with a data value + * which may correspond to a copy of the value inserted into an Any. + * The DynAny APIs enable traversal of the data value associated with an + * Any at runtime and extraction of the primitive constituents of the + * data value. + * @deprecated Use the new DynAny instead + */ + + +// @Deprecated +public interface DynAny extends org.omg.CORBA.Object +{ + /** + * Returns the TypeCode of the object inserted into + * this DynAny. + * + * @return the TypeCode object. + */ + public org.omg.CORBA.TypeCode type() ; + + /** + * Copy the contents from one Dynamic Any into another. + * + * @param dyn_any the DynAny object whose contents + * are assigned to this DynAny. + * @throws Invalid if the source DynAny is + * invalid + */ + public void assign(org.omg.CORBA.DynAny dyn_any) + throws org.omg.CORBA.DynAnyPackage.Invalid; + + /** + * Make a DynAny object from an Any + * object. + * + * @param value the Any object. + * @throws Invalid if the source Any object is + * empty or bad + */ + public void from_any(org.omg.CORBA.Any value) + throws org.omg.CORBA.DynAnyPackage.Invalid; + + /** + * Convert a DynAny object to an Any + * object. + * + * @return the Any object. + * @throws Invalid if this DynAny is empty or + * bad. + * created or does not contain a meaningful value + */ + public org.omg.CORBA.Any to_any() + throws org.omg.CORBA.DynAnyPackage.Invalid; + + /** + * Destroys this DynAny object and frees any resources + * used to represent the data value associated with it. This method + * also destroys all DynAny objects obtained from it. + *

    + * Destruction of DynAny objects should be handled with + * care, taking into account issues dealing with the representation of + * data values associated with DynAny objects. A programmer + * who wants to destroy a DynAny object but still be able + * to manipulate some component of the data value associated with it, + * should first create a DynAny object for the component + * and then make a copy of the created DynAny object. + */ + public void destroy() ; + + /** + * Clones this DynAny object. + * + * @return a copy of this DynAny object + */ + public org.omg.CORBA.DynAny copy() ; + + /** + * Inserts the given boolean as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the boolean to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_boolean(boolean value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given byte as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the byte to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_octet(byte value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given char as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the char to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_char(char value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given short as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the short to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_short(short value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given short as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the short to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_ushort(short value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given int as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the int to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_long(int value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given int as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the int to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_ulong(int value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given float as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the float to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_float(float value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given double as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the double to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_double(double value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given String object as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the String to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_string(String value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given org.omg.CORBA.Object as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the org.omg.CORBA.Object to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_reference(org.omg.CORBA.Object value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given org.omg.CORBA.TypeCode as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the org.omg.CORBA.TypeCode to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_typecode(org.omg.CORBA.TypeCode value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given long as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the long to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_longlong(long value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given long as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the long to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_ulonglong(long value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given char as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the char to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_wchar(char value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given String as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the String to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_wstring(String value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Inserts the given org.omg.CORBA.Any object as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the org.omg.CORBA.Any object to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_any(org.omg.CORBA.Any value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + // orbos 98-01-18: Objects By Value -- begin + + /** + * Inserts the given java.io.Serializable object as the value for this + * DynAny object. + * + *

    If this method is called on a constructed DynAny + * object, it initializes the next component of the constructed data + * value associated with this DynAny object. + * + * @param value the java.io.Serializable object to insert into this + * DynAny object + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue + * if the value inserted is not consistent with the type + * of the accessed component in this DynAny object + */ + public void insert_val(java.io.Serializable value) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; + + /** + * Retrieves the java.io.Serializable object contained + * in this DynAny object. + * + * @return the java.io.Serializable object that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a java.io.Serializable object + */ + public java.io.Serializable get_val() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + // orbos 98-01-18: Objects By Value -- end + + /** + * Retrieves the boolean contained + * in this DynAny object. + * + * @return the boolean that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a boolean + */ + public boolean get_boolean() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the byte contained + * in this DynAny object. + * + * @return the byte that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a byte + */ + public byte get_octet() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + /** + * Retrieves the char contained + * in this DynAny object. + * + * @return the char that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a char + */ + public char get_char() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the short contained + * in this DynAny object. + * + * @return the short that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a short + */ + public short get_short() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the short contained + * in this DynAny object. + * + * @return the short that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a short + */ + public short get_ushort() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the int contained + * in this DynAny object. + * + * @return the int that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a int + */ + public int get_long() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the int contained + * in this DynAny object. + * + * @return the int that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a int + */ + public int get_ulong() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the float contained + * in this DynAny object. + * + * @return the float that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a float + */ + public float get_float() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the double contained + * in this DynAny object. + * + * @return the double that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a double + */ + public double get_double() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the String contained + * in this DynAny object. + * + * @return the String that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a String + */ + public String get_string() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the org.omg.CORBA.Other contained + * in this DynAny object. + * + * @return the org.omg.CORBA.Other that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for an org.omg.CORBA.Other + */ + public org.omg.CORBA.Object get_reference() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the org.omg.CORBA.TypeCode contained + * in this DynAny object. + * + * @return the org.omg.CORBA.TypeCode that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a org.omg.CORBA.TypeCode + */ + public org.omg.CORBA.TypeCode get_typecode() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the long contained + * in this DynAny object. + * + * @return the long that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a long + */ + public long get_longlong() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the long contained + * in this DynAny object. + * + * @return the long that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a long + */ + public long get_ulonglong() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the char contained + * in this DynAny object. + * + * @return the char that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a char + */ + public char get_wchar() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the String contained + * in this DynAny object. + * + * @return the String that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for a String + */ + public String get_wstring() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + + /** + * Retrieves the org.omg.CORBA.Any contained + * in this DynAny object. + * + * @return the org.omg.CORBA.Any that is the + * value for this DynAny object + * @throws org.omg.CORBA.DynAnyPackage.TypeMismatch + * if the type code of the accessed component in this + * DynAny object is not equivalent to + * the type code for an org.omg.CORBA.Any + */ + public org.omg.CORBA.Any get_any() + throws org.omg.CORBA.DynAnyPackage.TypeMismatch; + + /** + * Returns a DynAny object reference that can + * be used to get/set the value of the component currently accessed. + * The appropriate insert method + * can be called on the resulting DynAny object + * to initialize the component. + * The appropriate get method + * can be called on the resulting DynAny object + * to extract the value of the component. + * + * @return a DynAny object reference that can be + * used to retrieve or set the value of the component currently + * accessed + */ + public org.omg.CORBA.DynAny current_component() ; + + /** + * Moves to the next component of this DynAny object. + * This method is used for iterating through the components of + * a constructed type, effectively moving a pointer from one + * component to the next. The pointer starts out on the first + * component when a DynAny object is created. + * + * @return true if the pointer points to a component; + * false if there are no more components or this + * DynAny is associated with a basic type rather than + * a constructed type + */ + public boolean next() ; + + /** + * Moves the internal pointer to the given index. Logically, this method + * sets a new offset for this pointer. + * + * @param index an int indicating the position to which + * the pointer should move. The first position is 0. + * @return true if the pointer points to a component; + * false if there is no component at the designated + * index. If this DynAny object is associated with a + * basic type, this method returns false for any index + * other than 0. + */ + public boolean seek(int index) ; + + /** + * Moves the internal pointer to the first component. + */ + public void rewind() ; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/Invalid.java b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/Invalid.java new file mode 100644 index 000000000..21708d329 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/Invalid.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.DynAnyPackage; + +/** + * Invalid is thrown by dynamic any operations when a bad + * DynAny or Any is passed as a parameter. + */ +// @SuppressWarnings({"serial"}) +public final class Invalid + extends org.omg.CORBA.UserException { + + /** + * Constructs an Invalid object. + */ + public Invalid() { + super(); + } + + /** + * Constructs an Invalid object. + * @param reason a String giving more information + * regarding the bad parameter passed to a dynamic any operation. + */ + public Invalid(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/InvalidSeq.java b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/InvalidSeq.java new file mode 100644 index 000000000..8d3b7ee95 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/InvalidSeq.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.DynAnyPackage; + +/** + * The InvalidSeq exception is thrown by all operations on dynamic + * anys that take a sequence (Java array) as an argument, when that + * sequence is invalid. + */ +// @SuppressWarnings({"serial"}) +public final class InvalidSeq + extends org.omg.CORBA.UserException { + + /** + * Constructs an InvalidSeq object. + */ + public InvalidSeq() { + super(); + } + + /** + * Constructs an InvalidSeq object. + * @param reason a String giving more information + * regarding the exception. + */ + public InvalidSeq(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/InvalidValue.java b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/InvalidValue.java new file mode 100644 index 000000000..6c55eb81f --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/InvalidValue.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.DynAnyPackage; + +/** + * @author unattributed + * @version 1.18 07/27/07 + * + * Dynamic Any insert operations raise the InvalidValue + * exception if the value inserted is not consistent with the type + * of the accessed component in the DynAny object. + */ +// @SuppressWarnings({"serial"}) +public final class InvalidValue + extends org.omg.CORBA.UserException { + + /** + * Constructs an InvalidValue object. + */ + public InvalidValue() { + super(); + } + + /** + * Constructs an InvalidValue object. + * @param reason a String giving more information + * regarding the exception. + */ + public InvalidValue(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/TypeMismatch.java b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/TypeMismatch.java new file mode 100644 index 000000000..5e5656424 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/TypeMismatch.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.DynAnyPackage; + +/** + * TypeMismatch is thrown by dynamic any accessor methods when + * type of the actual contents do not match what is trying to be + * accessed. + */ +// @SuppressWarnings({"serial"}) +public final class TypeMismatch + extends org.omg.CORBA.UserException { + + /** + * Constructs a TypeMismatch object. + */ + public TypeMismatch() { + super(); + } + + /** + * Constructs a TypeMismatch object. + * @param reason a String giving more information + * regarding the exception. + */ + public TypeMismatch(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/package.html b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/package.html new file mode 100644 index 000000000..109eadb35 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynAnyPackage/package.html @@ -0,0 +1,29 @@ + + + + + + + + +Provides the exceptions used with the DynAny interface +(InvalidValue, +Invalid, InvalidSeq, and +TypeMismatch). + + + +@since JDK1.2 +@serial exclude + + diff --git a/omgapi/src/main/java/org/omg/CORBA/DynArray.java b/omgapi/src/main/java/org/omg/CORBA/DynArray.java new file mode 100644 index 000000000..cbf1b7d03 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynArray.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** Represents a DynAny object associated + * with an array. + * @deprecated Use the new DynArray instead + */ + +// @Deprecated +public interface DynArray extends org.omg.CORBA.Object, org.omg.CORBA.DynAny +{ + /** + * Returns the value of all the elements of this array. + * + * @return the array of Any objects that is the value + * for this DynArray object + * @see #set_elements + */ + public org.omg.CORBA.Any[] get_elements(); + + /** + * Sets the value of this + * DynArray object to the given array. + * + * @param value the array of Any objects + * @exception InvalidSeq if the sequence is bad + * @see #get_elements + */ + public void set_elements(org.omg.CORBA.Any[] value) + throws org.omg.CORBA.DynAnyPackage.InvalidSeq; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynEnum.java b/omgapi/src/main/java/org/omg/CORBA/DynEnum.java new file mode 100644 index 000000000..09407af90 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynEnum.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Represents a DynAny object associated + * with an IDL enum. + * @deprecated Use the new DynEnum instead + */ + +// @Deprecated +public interface DynEnum extends org.omg.CORBA.Object, org.omg.CORBA.DynAny +{ + /** + * Return the value of the IDL enum stored in this + * DynEnum as a string. + * + * @return the stringified value. + */ + public String value_as_string(); + + /** + * Set a particular enum in this DynEnum. + * + * @param arg the string corresponding to the value. + */ + public void value_as_string(String arg); + + /** + * Return the value of the IDL enum as a Java int. + * + * @return the integer value. + */ + public int value_as_ulong(); + + /** + * Set the value of the IDL enum. + * + * @param arg the int value of the enum. + */ + public void value_as_ulong(int arg); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynFixed.java b/omgapi/src/main/java/org/omg/CORBA/DynFixed.java new file mode 100644 index 000000000..d32b28b32 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynFixed.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Represents a DynAny object that is associated + * with an IDL fixed type. + * @deprecated Use the new DynFixed instead + */ + +public interface DynFixed extends org.omg.CORBA.Object, org.omg.CORBA.DynAny +{ + /** + * Returns the value of the fixed type represented in this + * DynFixed object. + * + * @return the value as a byte array + * @see #set_value + */ + public byte[] get_value(); + + /** + * Sets the given fixed type instance as the value for this + * DynFixed object. + * + * @param val the value of the fixed type as a byte array + * @throws org.omg.CORBA.DynAnyPackage.InvalidValue if the given + * argument is bad + * @see #get_value + */ + public void set_value(byte[] val) + throws org.omg.CORBA.DynAnyPackage.InvalidValue; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynSequence.java b/omgapi/src/main/java/org/omg/CORBA/DynSequence.java new file mode 100644 index 000000000..99539be62 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynSequence.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The representation of a DynAny object that is associated + * with an IDL sequence. + * @deprecated Use the new DynSequence instead + */ +// @Deprecated +public interface DynSequence extends org.omg.CORBA.Object, org.omg.CORBA.DynAny +{ + + /** + * Returns the length of the sequence represented by this + * DynFixed object. + * + * @return the length of the sequence + */ + public int length(); + + /** + * Sets the length of the sequence represented by this + * DynFixed object to the given argument. + * + * @param arg the length of the sequence + */ + public void length(int arg); + + /** + * Returns the value of every element in this sequence. + * + * @return an array of Any objects containing the values in + * the sequence + * @see #set_elements + */ + public org.omg.CORBA.Any[] get_elements(); + + /** + * Sets the values of all elements in this sequence with the given + * array. + * + * @param value the array of Any objects to be set + * @exception InvalidSeq if the array of values is bad + * @see #get_elements + */ + public void set_elements(org.omg.CORBA.Any[] value) + throws org.omg.CORBA.DynAnyPackage.InvalidSeq; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynStruct.java b/omgapi/src/main/java/org/omg/CORBA/DynStruct.java new file mode 100644 index 000000000..89debb01a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynStruct.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The representation of a DynAny object that is associated + * with an IDL struct. + * @deprecated Use the new DynStruct instead + */ + +// @Deprecated +public interface DynStruct extends org.omg.CORBA.Object, org.omg.CORBA.DynAny +{ + /** + * During a traversal, returns the name of the current member. + * + * @return the string name of the current member + */ + public String current_member_name(); + + /** + * Returns the TCKind object that describes the kind of + * the current member. + * + * @return the TCKind object that describes the current member + */ + public org.omg.CORBA.TCKind current_member_kind(); + + /** + * Returns an array containing all the members of the stored struct. + * + * @return the array of name-value pairs + * @see #set_members + */ + public org.omg.CORBA.NameValuePair[] get_members(); + + /** + * Set the members of the struct. + * + * @param value the array of name-value pairs. + * @throws org.omg.CORBA.DynAnyPackage.InvalidSeq if the given argument + * is invalid + * @see #get_members + */ + public void set_members(org.omg.CORBA.NameValuePair[] value) + throws org.omg.CORBA.DynAnyPackage.InvalidSeq; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynUnion.java b/omgapi/src/main/java/org/omg/CORBA/DynUnion.java new file mode 100644 index 000000000..838106ea1 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynUnion.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The DynUnion interface represents a DynAny object + * that is associated with an IDL union. + * Union values can be traversed using the operations defined in DynAny. + * The first component in the union corresponds to the discriminator; + * the second corresponds to the actual value of the union. + * Calling the method next() twice allows you to access both components. + * @deprecated Use the new DynUnion instead + */ + +// @Deprecated +public interface DynUnion extends org.omg.CORBA.Object, org.omg.CORBA.DynAny +{ + /** + * Determines whether the discriminator associated with this union has been assigned + * a valid default value. + * @return true if the discriminator has a default value; + * false otherwise + */ + public boolean set_as_default(); + + /** + * Determines whether the discriminator associated with this union gets assigned + * a valid default value. + * @param arg true if the discriminator gets assigned a default value + */ + public void set_as_default(boolean arg); + + /** + * Returns a DynAny object reference that must be narrowed to the type + * of the discriminator in order to insert/get the discriminator value. + * @return a DynAny object reference representing the discriminator value + */ + // @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.DynAny discriminator(); + + /** + * Returns the TCKind object associated with the discriminator of this union. + * @return the TCKind object associated with the discriminator of this union + */ + public org.omg.CORBA.TCKind discriminator_kind(); + + /** + * Returns a DynAny object reference that is used in order to insert/get + * a member of this union. + * @return the DynAny object representing a member of this union + */ + // @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.DynAny member(); + + /** + * Allows for the inspection of the name of this union member + * without checking the value of the discriminator. + * @return the name of this union member + */ + public String member_name(); + + /** + * Allows for the assignment of the name of this union member. + * @param arg the new name of this union member + */ + public void member_name(String arg); + + /** + * Returns the TCKind associated with the member of this union. + * @return the TCKind object associated with the member of this union + */ + public org.omg.CORBA.TCKind member_kind(); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynValue.java b/omgapi/src/main/java/org/omg/CORBA/DynValue.java new file mode 100644 index 000000000..78bb71d5b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynValue.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The representation of a DynAny object that is associated + * with an IDL value type. + * @deprecated Use the new DynValue instead + */ +public interface DynValue extends org.omg.CORBA.Object, org.omg.CORBA.DynAny { + + /** + * Returns the name of the current member while traversing a + * DynAny object that represents a Value object. + * + * @return the name of the current member + */ + String current_member_name(); + + /** + * Returns the TCKind object that describes the current member. + * + * @return the TCKind object corresponding to the current + * member + */ + TCKind current_member_kind(); + + /** + * Returns an array containing all the members of the value object + * stored in this DynValue. + * + * @return an array of name-value pairs. + * @see #set_members + */ + org.omg.CORBA.NameValuePair[] get_members(); + + /** + * Sets the members of the value object this DynValue + * object represents to the given array of NameValuePair + * objects. + * + * @param value the array of name-value pairs to be set + * @throws org.omg.CORBA.DynAnyPackage.InvalidSeq + * if an inconsistent value is part of the given array + * @see #get_members + */ + void set_members(NameValuePair[] value) + throws org.omg.CORBA.DynAnyPackage.InvalidSeq; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/DynamicImplementation.java b/omgapi/src/main/java/org/omg/CORBA/DynamicImplementation.java new file mode 100644 index 000000000..503404cc8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/DynamicImplementation.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.ObjectImpl; + +/** + * @deprecated org.omg.CORBA.DynamicImplementation + */ + +public class DynamicImplementation extends org.omg.CORBA.portable.ObjectImpl { + + /** + * @deprecated Deprecated by Portable Object Adapter + */ + + public void invoke(ServerRequest request) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + public String[] _ids() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/Environment.java b/omgapi/src/main/java/org/omg/CORBA/Environment.java new file mode 100644 index 000000000..909804a38 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Environment.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A container (holder) for an exception that is used in Request + * operations to make exceptions available to the client. An + * Environment object is created with the ORB + * method create_environment. + * + * @version 1.11, 09/09/97 + * @since JDK1.2 + */ + +public abstract class Environment { + + /** + * Retrieves the exception in this Environment object. + * + * @return the exception in this Environment object + */ + + public abstract java.lang.Exception exception(); + + /** + * Inserts the given exception into this Environment object. + * + * @param except the exception to be set + */ + + public abstract void exception(java.lang.Exception except); + + /** + * Clears this Environment object of its exception. + */ + + public abstract void clear(); + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ExceptionList.java b/omgapi/src/main/java/org/omg/CORBA/ExceptionList.java new file mode 100644 index 000000000..881404e63 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ExceptionList.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object used in Request operations to + * describe the exceptions that can be thrown by a method. It maintains a + * modifiable list of TypeCodes of the exceptions. + *

    + * The following code fragment demonstrates creating + * an ExceptionList object: + *

    + *    ORB orb = ORB.init(args, null);
    + *    org.omg.CORBA.ExceptionList excList = orb.create_exception_list();
    + * 
    + * The variable excList represents an ExceptionList + * object with no TypeCode objects in it. + *

    + * To add items to the list, you first create a TypeCode object + * for the exception you want to include, using the ORB method + * create_exception_tc. Then you use the ExceptionList + * method add to add it to the list. + * The class ExceptionList has a method for getting + * the number of TypeCode objects in the list, and after + * items have been added, it is possible to call methods for accessing + * or deleting an item at a designated index. + * + * @version 1.13, 09/09/97 + * @since JDK1.2 + */ + +public abstract class ExceptionList { + + /** + * Retrieves the number of TypeCode objects in this + * ExceptionList object. + * + * @return the number of TypeCode objects in this + * ExceptionList object + */ + + public abstract int count(); + + /** + * Adds a TypeCode object describing an exception + * to this ExceptionList object. + * + * @param exc the TypeCode object to be added + */ + + public abstract void add(TypeCode exc); + + /** + * Returns the TypeCode object at the given index. The first + * item is at index 0. + * + * @param index the index of the TypeCode object desired. + * This must be an int between 0 and the + * number of TypeCode objects + * minus one, inclusive. + * @return the TypeCode object at the given index + * @exception org.omg.CORBA.Bounds if the index given is greater than + * or equal to the number of TypeCode objects + * in this ExceptionList object + */ + + public abstract TypeCode item(int index) + throws org.omg.CORBA.Bounds; + + /** + * Removes the TypeCode object at the given index. + * Note that the indices of all the TypeCoded objects + * following the one deleted are shifted down by one. + * + * @param index the index of the TypeCode object to be + * removed. + * This must be an int between 0 and the + * number of TypeCode objects + * minus one, inclusive. + * + * @exception org.omg.CORBA.Bounds if the index is greater than + * or equal to the number of TypeCode objects + * in this ExceptionList object + */ + + public abstract void remove(int index) + throws org.omg.CORBA.Bounds; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/FREE_MEM.java b/omgapi/src/main/java/org/omg/CORBA/FREE_MEM.java new file mode 100644 index 000000000..132a4b47c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/FREE_MEM.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown + * when the ORB failed in an attempt to free dynamic memory, for example + * because of heap corruption or memory segments being locked.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16, 09/09/97 + * @since JDK1.2 + */ + +public final class FREE_MEM extends SystemException { + /** + * Constructs a FREE_MEM exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public FREE_MEM() { + this(""); + } + + /** + * Constructs a FREE_MEM exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * + * @param s the String containing a detail message + */ + public FREE_MEM(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a FREE_MEM exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public FREE_MEM(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a FREE_MEM exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public FREE_MEM(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/FieldNameHelper.java b/omgapi/src/main/java/org/omg/CORBA/FieldNameHelper.java new file mode 100644 index 000000000..ebfaf2370 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/FieldNameHelper.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for FieldName. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/FieldNameHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* 03 June 1999 11:52:03 o'clock GMT+00:00 +*/ + +abstract public class FieldNameHelper +{ + private static String _id = "IDL:omg.org/CORBA/FieldName:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.FieldNameHelper.id (), "FieldName", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/FixedHolder.java b/omgapi/src/main/java/org/omg/CORBA/FixedHolder.java new file mode 100644 index 000000000..4bec41450 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/FixedHolder.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + + +/** + * The Holder for Fixed. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * FixedHolder is a container class for values of IDL type "fixed", + * which is mapped to the Java class java.math.BigDecimal. + * It is usually used to store "out" and "inout" IDL method parameters. + * If an IDL method signature has a fixed as an "out" or "inout" parameter, + * the programmer must pass an instance of FixedHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the contained + * value corresponding to the "out" value returned from the server. + * + * @version 1.14 09/09/97 + */ +public final class FixedHolder implements Streamable { + /** + * The value held by the FixedHolder + */ + public java.math.BigDecimal value; + + /** + * Construct the FixedHolder without initializing the contained value. + */ + public FixedHolder() { + } + + /** + * Construct the FixedHolder and initialize it with the given value. + * @param initial the value used to initialize the FixedHolder + */ + public FixedHolder(java.math.BigDecimal initial) { + value = initial; + } + + /** + * Read a fixed point value from the input stream and store it in + * the value member. + * + * @param input the InputStream to read from. + */ + public void _read(InputStream input) { + value = input.read_fixed(); + } + + /** + * Write the fixed point value stored in this holder to an + * OutputStream. + * + * @param output the OutputStream to write into. + */ + public void _write(OutputStream output) { + output.write_fixed(value); + } + + + /** + * Return the TypeCode of this holder object. + * + * @return the TypeCode object. + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_fixed); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/FloatHolder.java b/omgapi/src/main/java/org/omg/CORBA/FloatHolder.java new file mode 100644 index 000000000..56ace0c7a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/FloatHolder.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + + +/** + * The Holder for Float. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a float + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL float as an "out" + * or "inout" parameter, the programmer must pass an instance of + * FloatHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myFloatHolder is an instance of FloatHolder, + * the value stored in its value field can be accessed with + * myFloatHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class FloatHolder implements Streamable { + /** + * The float value held by this FloatHolder + * object. + */ + public float value; + + /** + * Constructs a new FloatHolder object with its + * value field initialized to 0.0. + */ + public FloatHolder() { + } + + /** + * Constructs a new FloatHolder object for the given + * float. + * @param initial the float with which to initialize + * the value field of the new + * FloatHolder object + */ + public FloatHolder(float initial) { + value = initial; + } + + /** + * Read a float from an input stream and initialize the value + * member with the float value. + * + * @param input the InputStream to read from. + */ + public void _read(InputStream input) { + value = input.read_float(); + } + + /** + * Write the float value into an output stream. + * + * @param output the OutputStream to write into. + */ + public void _write(OutputStream output) { + output.write_float(value); + } + + /** + * Return the TypeCode of this Streamable. + * + * @return the TypeCode object. + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_float); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/FloatSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/FloatSeqHelper.java new file mode 100644 index 000000000..2ce3ba67c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/FloatSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for FloatSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/FloatSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class FloatSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/FloatSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, float[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static float[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_float); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.FloatSeqHelper.id (), "FloatSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static float[] read (org.omg.CORBA.portable.InputStream istream) + { + float value[] = null; + int _len0 = istream.read_long (); + value = new float[_len0]; + istream.read_float_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, float[] value) + { + ostream.write_long (value.length); + ostream.write_float_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/FloatSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/FloatSeqHolder.java new file mode 100644 index 000000000..2f472d1b7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/FloatSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for FloatSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/FloatSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +*/ + +public final class FloatSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public float value[] = null; + + public FloatSeqHolder () + { + } + + public FloatSeqHolder (float[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.FloatSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.FloatSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.FloatSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/IDLType.java b/omgapi/src/main/java/org/omg/CORBA/IDLType.java new file mode 100644 index 000000000..8e40d81f8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IDLType.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/IDLType.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; +/** +* tempout/org/omg/CORBA/IDLType.java +* Generated by the IBM IDL-to-Java compiler, version 1.0 +* from ../../Lib/ir.idl +* Thursday, February 25, 1999 2:11:23 o'clock PM PST +*/ + +/** + * An abstract interface inherited by all Interface Repository + * (IR) objects that represent OMG IDL types. It provides access + * to the TypeCode object describing the type and is used in defining the + * other interfaces wherever definitions of IDLType must be referenced. + */ + +public interface IDLType extends IDLTypeOperations, org.omg.CORBA.IRObject, org.omg.CORBA.portable.IDLEntity +{ +} // interface IDLType + + + diff --git a/omgapi/src/main/java/org/omg/CORBA/IDLTypeHelper.java b/omgapi/src/main/java/org/omg/CORBA/IDLTypeHelper.java new file mode 100644 index 000000000..18b84ddc2 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IDLTypeHelper.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for IDLType. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/IDLTypeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:44 o'clock GMT+00:00 +*/ + +abstract public class IDLTypeHelper +{ + private static String _id = "IDL:omg.org/CORBA/IDLType:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.IDLType that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.IDLType extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.IDLTypeHelper.id (), "IDLType"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.IDLType read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_IDLTypeStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.IDLType value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.IDLType narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.IDLType) + return (org.omg.CORBA.IDLType)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + return new org.omg.CORBA._IDLTypeStub (delegate); + } + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/IDLTypeOperations.java b/omgapi/src/main/java/org/omg/CORBA/IDLTypeOperations.java new file mode 100644 index 000000000..f3f095bbe --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IDLTypeOperations.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The interface for IDLType. For more information on +* Operations interfaces, see +* "Generated Files: Operations files". +*/ + +/* + tempout/org/omg/CORBA/IDLTypeOperations.java + Generated by the IBM IDL-to-Java compiler, version 1.0 + from ../../Lib/ir.idl + Thursday, February 25, 1999 2:11:23 o'clock PM PST +*/ + +/** + * This interface must be implemented by all IDLType objects. + * The IDLType is inherited by all IR objects that + * represent IDL types, including interfaces, typedefs, and + * anonymous types. + * @see IDLType + * @see IRObject + * @see IRObjectOperations + */ + +public interface IDLTypeOperations extends org.omg.CORBA.IRObjectOperations +{ + /** + * The type attribute describes the type defined by an object + * derived from IDLType. + * @return the TypeCode defined by this object. + */ + org.omg.CORBA.TypeCode type (); +} // interface IDLTypeOperations diff --git a/omgapi/src/main/java/org/omg/CORBA/IMP_LIMIT.java b/omgapi/src/main/java/org/omg/CORBA/IMP_LIMIT.java new file mode 100644 index 000000000..a5a0670bf --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IMP_LIMIT.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates that an implementation limit was + * exceeded in the ORB run time. For example, an ORB may reach + * the maximum number of references it can hold simultaneously + * in an address space, the size of a parameter may have + * exceeded the allowed maximum, or an ORB may impose a maximum + * on the number of clients or servers that can run simultaneously.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16, 09/09/97 + * @since JDK1.2 + */ + + +public final class IMP_LIMIT extends SystemException { + /** + * Constructs an IMP_LIMIT exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public IMP_LIMIT() { + this(""); + } + + /** + * Constructs an IMP_LIMIT exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * + * @param s the String containing a detail message + */ + public IMP_LIMIT(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an IMP_LIMIT exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public IMP_LIMIT(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an IMP_LIMIT exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public IMP_LIMIT(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INITIALIZE.java b/omgapi/src/main/java/org/omg/CORBA/INITIALIZE.java new file mode 100644 index 000000000..fd6aa1cd2 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INITIALIZE.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown + * when an ORB has encountered a failure during its initialization, + * such as failure to acquire networking resources or detecting a + * configuration error.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.19, 09/09/97 + * @since JDK1.2 + */ + +public final class INITIALIZE extends SystemException { + /** + * Constructs an INITIALIZE exception with a default + * minor code of 0 and a completion state of + * CompletionStatus.COMPLETED_NO. + */ + public INITIALIZE() { + this(""); + } + + /** + * Constructs an INITIALIZE exception with the specified detail + * message, a minor code of 0, and a completion state of + * CompletionStatus.COMPLETED_NO. + * @param s the String containing a detail message + */ + public INITIALIZE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INITIALIZE exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus + * indicating the completion status of the method + * that threw this exception + */ + public INITIALIZE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INITIALIZE exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed an instance of CompletionStatus + * indicating the completion status of the method + * that threw this exception + */ + public INITIALIZE(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INTERNAL.java b/omgapi/src/main/java/org/omg/CORBA/INTERNAL.java new file mode 100644 index 000000000..7684bce79 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INTERNAL.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates an internal failure in an ORB, for + * example, if an ORB has detected corruption of its internal + * data structures.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section meaning + * of minor codes to see the minor codes for this exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16, 09/09/97 + * @since JDK1.2 + */ + +public final class INTERNAL extends SystemException { + /** + * Constructs an INTERNAL exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public INTERNAL() { + this(""); + } + + /** + * Constructs an INTERNAL exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public INTERNAL(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INTERNAL exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus + * that indicates the completion status of the method + * that threw this exception + */ + public INTERNAL(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INTERNAL exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed an instance of CompletionStatus + * that indicates the completion status of the method + * that threw this exception + */ + public INTERNAL(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INTF_REPOS.java b/omgapi/src/main/java/org/omg/CORBA/INTF_REPOS.java new file mode 100644 index 000000000..3ae5df5e6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INTF_REPOS.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception raised + * when an ORB cannot reach the interface + * repository, or some other failure relating to the interface repository + * is detected.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16, 09/09/97 + * @since JDK1.2 + */ + +public final class INTF_REPOS extends SystemException { + /** + * Constructs an INTF_REPOS exception with a default minor code + * of 0 and a completion state of COMPLETED_NO. + */ + public INTF_REPOS() { + this(""); + } + + /** + * Constructs an INTF_REPOS exception with the specified detail. + * @param s the String containing a detail message + */ + public INTF_REPOS(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INTF_REPOS exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public INTF_REPOS(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INTF_REPOS exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public INTF_REPOS(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INVALID_ACTIVITY.java b/omgapi/src/main/java/org/omg/CORBA/INVALID_ACTIVITY.java new file mode 100644 index 000000000..df59364fe --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INVALID_ACTIVITY.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The INVALID_ACTIVITY system exception may be raised on the + * Activity or Transaction services' resume methods if a transaction or + * Activity is resumed in a context different to that from which it was + * suspended. It is also raised when an attempted invocation is made that + * is incompatible with the Activity's current state. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class INVALID_ACTIVITY extends SystemException { + + /** + * Constructs an INVALID_ACTIVITY exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public INVALID_ACTIVITY() { + this(""); + } + + /** + * Constructs an INVALID_ACTIVITY exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public INVALID_ACTIVITY(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INVALID_ACTIVITY exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public INVALID_ACTIVITY(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an INVALID_ACTIVITY exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public INVALID_ACTIVITY(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INVALID_TRANSACTION.java b/omgapi/src/main/java/org/omg/CORBA/INVALID_TRANSACTION.java new file mode 100644 index 000000000..1176704ce --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INVALID_TRANSACTION.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown + * when the request carried an invalid transaction context. + * For example, this exception could be raised if an error + * occurred when trying to register a resource.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.5, 09/09/97 + * @since JDK1.2 + * + */ + +public final class INVALID_TRANSACTION extends SystemException { + /** + * Constructs an INVALID_TRANSACTION exception with a default minor code + * of 0 and a completion state of COMPLETED_NO. + */ + public INVALID_TRANSACTION() { + this(""); + } + + /** + * Constructs an INVALID_TRANSACTION exception + * with the specified detail message. + * @param s the String containing a detail message + */ + public INVALID_TRANSACTION(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INVALID_TRANSACTION exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public INVALID_TRANSACTION(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INVALID_TRANSACTION exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + public INVALID_TRANSACTION(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INV_FLAG.java b/omgapi/src/main/java/org/omg/CORBA/INV_FLAG.java new file mode 100644 index 000000000..0bddb03ab --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INV_FLAG.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown + * when an invalid flag was passed to an operation (for example, when + * creating a DII request).

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16, 09/09/97 + * @since JDK1.2 + */ + +public final class INV_FLAG extends SystemException { + /** + * Constructs an INV_FLAG exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public INV_FLAG() { + this(""); + } + + /** + * Constructs an INV_FLAG exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public INV_FLAG(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INV_FLAG exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed an instance of CompletionStatus + * indicating the completion status + */ + public INV_FLAG(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INV_FLAG exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed an instance of CompletionStatus + * indicating the completion status + */ + public INV_FLAG(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INV_IDENT.java b/omgapi/src/main/java/org/omg/CORBA/INV_IDENT.java new file mode 100644 index 000000000..7d643741b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INV_IDENT.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates that an IDL identifier is syntactically + * invalid. It may be raised if, for example, an identifier passed + * to the interface repository does not conform to IDL identifier + * syntax, or if an illegal operation name is used with the DII.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16 09/09/97 + * @since JDK1.2 + */ + +public final class INV_IDENT extends SystemException { + /** + * Constructs an INV_IDENT exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public INV_IDENT() { + this(""); + } + + /** + * Constructs an INV_IDENT exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public INV_IDENT(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INV_IDENT exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed a CompletionStatus object indicating + * the completion status + */ + public INV_IDENT(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INV_IDENT exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed a CompletionStatus object indicating + * the completion status + */ + public INV_IDENT(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INV_OBJREF.java b/omgapi/src/main/java/org/omg/CORBA/INV_OBJREF.java new file mode 100644 index 000000000..d76d3fc97 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INV_OBJREF.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates that an object reference is internally + * malformed. For example, the repository ID may have incorrect + * syntax or the addressing information may be invalid. This + * exception is raised by ORB::string_to_object if the passed + * string does not decode correctly. An ORB may choose to detect + * calls via nil references (but is not obliged to do detect them). + * INV_OBJREF is used to indicate this.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section Minor + * Code Meanings to see the minor codes for this exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17 09/09/97 + * @since JDK1.2 + */ + +public final class INV_OBJREF extends SystemException { + /** + * Constructs an INV_OBJREF exception with a default + * minor code of 0 and a completion state of COMPLETED_NO. + */ + public INV_OBJREF() { + this(""); + } + + /** + * Constructs an INV_OBJREF exception with the specified detail + * message, a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public INV_OBJREF(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an INV_OBJREF exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed a CompletionStatus instance indicating + * the completion status + */ + public INV_OBJREF(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an INV_OBJREF exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param s the String containing a detail message + * @param minor the minor code + * @param completed a CompletionStatus instance indicating + * the completion status + */ + public INV_OBJREF(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/INV_POLICY.java b/omgapi/src/main/java/org/omg/CORBA/INV_POLICY.java new file mode 100644 index 000000000..ea950a35f --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/INV_POLICY.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Standard exception thrown + * when an invocation cannot be made because of an incompatibility between + * Policy overrides that apply to the particular invocation. + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.5 09/09/97 + */ + +public final class INV_POLICY extends SystemException { + /** + * Constructs a INV_POLICY exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public INV_POLICY() { + this(""); + } + + /** + * Constructs a INV_POLICY exception with the + * specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public INV_POLICY(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a INV_POLICY exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public INV_POLICY(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a INV_POLICY exception with the + * specified description message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public INV_POLICY(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/IRObject.java b/omgapi/src/main/java/org/omg/CORBA/IRObject.java new file mode 100644 index 000000000..af42a036c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IRObject.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/IRObject.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; +/** +An IRObject IDL interface represents the most generic interface +from which all other Interface Repository interfaces are derived, +even the Repository itself. +*/ + +public interface IRObject extends IRObjectOperations, org.omg.CORBA.Object, + org.omg.CORBA.portable.IDLEntity +{ +} diff --git a/omgapi/src/main/java/org/omg/CORBA/IRObjectOperations.java b/omgapi/src/main/java/org/omg/CORBA/IRObjectOperations.java new file mode 100644 index 000000000..b29467358 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IRObjectOperations.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The interface for IRObject. For more information on +* Operations interfaces, see +* "Generated Files: Operations files". +*/ + +/* + tempout/org/omg/CORBA/IRObjectOperations.java + Generated by the IBM IDL-to-Java compiler, version 1.0 + from ../../Lib/ir.idl + Thursday, February 25, 1999 2:11:21 o'clock PM PST +*/ + +/** + * This is the Operations interface for the mapping from IRObject. + * Several interfaces are used as base interfaces for objects in + * the Interface Repository (IR). These base interfaces are not instantiable. + * A common set of operations is used to locate objects within the + * Interface Repository. Some of these operations are defined in + * the IRObject. All IR objects inherit from the IRObject interface, + * which provides an operation for identifying the actual type of + * the object. (The IDL base interface IRObject represents the most + * generic interface from which all other Interface Repository interfaces + * are derived, even the Repository itself.) All java implementations of + * IR objects must implement the IRObjectOperations interface. + * @see IDLTypeOperations + * @see IDLType + * @see IRObject + */ +public interface IRObjectOperations +{ + + // read interface + /** + * Returns the DefinitionKind corresponding to this Interface Repository object. + * @return the DefinitionKind corresponding to this Interface Repository object. + */ + org.omg.CORBA.DefinitionKind def_kind (); + + // write interface + /** + * Destroys this object. If the object is a Container, + * this method is applied to all its contents. If the object contains an IDLType + * attribute for an anonymous type, that IDLType is destroyed. + * If the object is currently contained in some other object, it is removed. + * If the method is invoked on a Repository or on a PrimitiveDef + * then the BAD_INV_ORDER exception is raised with minor value 2. + * An attempt to destroy an object that would leave the repository in an + * incoherent state causes BAD_INV_ORDER exception to be raised + * with the minor code 1. + * @exception BAD_INV_ORDER if this method is invoked on a repository or + * PrimitiveDef, or if an attempt to destroy an + * object would leave the repository in an incoherent state + */ + void destroy (); +} // interface IRObjectOperations diff --git a/omgapi/src/main/java/org/omg/CORBA/IdentifierHelper.java b/omgapi/src/main/java/org/omg/CORBA/IdentifierHelper.java new file mode 100644 index 000000000..8987e2fd7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IdentifierHelper.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for Identifier. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/IdentifierHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:42 o'clock GMT+00:00 +*/ + +abstract public class IdentifierHelper +{ + private static String _id = "IDL:omg.org/CORBA/Identifier:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/IntHolder.java b/omgapi/src/main/java/org/omg/CORBA/IntHolder.java new file mode 100644 index 000000000..5a9768bf3 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/IntHolder.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Int. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for an int + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL long as an "out" + * or "inout" parameter, the programmer must pass an instance of + * IntHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myIntHolder is an instance of IntHolder, + * the value stored in its value field can be accessed with + * myIntHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class IntHolder implements Streamable { + + /** + * The int value held by this IntHolder + * object in its value field. + */ + public int value; + + /** + * Constructs a new IntHolder object with its + * value field initialized to 0. + */ + public IntHolder() { + } + + /** + * Constructs a new IntHolder object with its + * value field initialized to the given + * int. + * @param initial the int with which to initialize + * the value field of the newly-created + * IntHolder object + */ + public IntHolder(int initial) { + value = initial; + } + + /** + * Reads unmarshalled data from input and assigns it to + * the value field in this IntHolder object. + * + * @param input the InputStream object containing CDR + * formatted data from the wire + */ + public void _read(InputStream input) { + value = input.read_long(); + } + + /** + * Marshals the value in this IntHolder object's + * value field to the output stream output. + * + * @param output the OutputStream object that will contain + * the CDR formatted data + */ + public void _write(OutputStream output) { + output.write_long(value); + } + + /** + * Retrieves the TypeCode object that corresponds + * to the value held in this IntHolder object's + * value field. + * + * @return the type code for the value held in this IntHolder + * object + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_long); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/LocalObject.java b/omgapi/src/main/java/org/omg/CORBA/LocalObject.java new file mode 100644 index 000000000..d22e3e69d --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/LocalObject.java @@ -0,0 +1,492 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; +import org.omg.CORBA.portable.*; + + +/** + *

    Used as a base class for implementation of a local IDL interface in the + * Java language mapping. It is a class which implements all the operations + * in the org.omg.CORBA.Object interface. + *

    Local interfaces are implemented by using CORBA::LocalObject + * to provide implementations of Object pseudo + * operations and any other ORB-specific support mechanisms that are + * appropriate for such objects. Object implementation techniques are + * inherently language-mapping specific. Therefore, the + * LocalObject type is not defined in IDL, but is specified + * in each language mapping. + *

    Methods that do not apply to local objects throw + * an org.omg.CORBA.NO_IMPLEMENT exception with the message, + * "This is a locally contrained object." Attempting to use a + * LocalObject to create a DII request results in NO_IMPLEMENT + * system exception. Attempting to marshal or stringify a + * LocalObject results in a MARSHAL system exception. Narrowing + * and widening references to LocalObjects must work as for regular + * object references. + *

    LocalObject is to be used as the base class of locally + * constrained objects, such as those in the PortableServer module. + * The specification here is based on the CORBA Components + * Volume I - orbos/99-07-01

    + * @see CORBA package + * comments for unimplemented features + */ + +public class LocalObject implements org.omg.CORBA.Object +{ + private static String reason = "This is a locally constrained object."; + + /** + * Constructs a default LocalObject instance. + */ + public LocalObject() {} + + /** + *

    Determines whether the two object references are equivalent, + * so far as the ORB can easily determine. Two object references are equivalent + * if they are identical. Two distinct object references which in fact refer to + * the same object are also equivalent. However, ORBs are not required + * to attempt determination of whether two distinct object references + * refer to the same object, since such determination could be impractically + * expensive. + *

    Default implementation of the org.omg.CORBA.Object method.

    + * + * @param that the object reference with which to check for equivalence + * @return true if this object reference is known to be + * equivalent to the given object reference. + * Note that false indicates only that the two + * object references are distinct, not necessarily that + * they reference distinct objects. + */ + public boolean _is_equivalent(org.omg.CORBA.Object that) { + return equals(that) ; + } + + /** + * Always returns false. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * + * @return false + */ + public boolean _non_existent() { + return false; + } + + /** + * Returns a hash value that is consistent for the + * lifetime of the object, using the given number as the maximum. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @param maximum an int identifying maximum value of + * the hashcode + * @return this instance's hashcode + */ + public int _hash(int maximum) { + return hashCode() ; + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." This method + * does not apply to local objects and is therefore not implemented. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * + * @param repository_id a String + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + public boolean _is_a(String repository_id) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @return a duplicate of this LocalObject instance. + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.Object _duplicate() { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public void _release() { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * + * @param operation a String giving the name of an operation + * to be performed by the request that is returned + * @return a Request object with the given operation + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public Request _request(String operation) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * + * @param ctx a Context object containing + * a list of properties + * @param operation the String representing the name of the + * method to be invoked + * @param arg_list an NVList containing the actual arguments + * to the method being invoked + * @param result a NamedValue object to serve as a + * container for the method's return value + * @return a new Request object initialized with the given + * arguments + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public Request _create_request(Context ctx, + String operation, + NVList arg_list, + NamedValue result) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * + * @param ctx a Context object containing + * a list of properties + * @param operation the name of the method to be invoked + * @param arg_list an NVList containing the actual arguments + * to the method being invoked + * @param result a NamedValue object to serve as a + * container for the method's return value + * @param exceptions an ExceptionList object containing a + * list of possible exceptions the method can throw + * @param contexts a ContextList object containing a list of + * context strings that need to be resolved and sent + * with the + * Request instance + * @return the new Request object initialized with the given + * arguments + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public Request _create_request(Context ctx, + String operation, + NVList arg_list, + NamedValue result, + ExceptionList exceptions, + ContextList contexts) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." This method + * does not apply to local objects and is therefore not implemented. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.Object _get_interface() + { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.Object _get_interface_def() + { + // First try to call the delegate implementation class's + // "Object get_interface_def(..)" method (will work for JDK1.2 + // ORBs). + // Else call the delegate implementation class's + // "InterfaceDef get_interface(..)" method using reflection + // (will work for pre-JDK1.2 ORBs). + + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @return the ORB instance that created the Delegate contained in this + * ObjectImpl + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.ORB _orb() { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." This method + * does not apply to local objects and is therefore not implemented. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @param policy_type an int + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.Policy _get_policy(int policy_type) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." This method + * does not apply to local objects and is therefore not implemented. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.DomainManager[] _get_domain_managers() { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." This method + * does not apply to local objects and is therefore not implemented. + * This method is the default implementation of the + * org.omg.CORBA.Object method. + * + * @param policies an array + * @param set_add a flag + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + public org.omg.CORBA.Object + _set_policy_override(org.omg.CORBA.Policy[] policies, + org.omg.CORBA.SetOverrideType set_add) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * Returns true for this LocalObject instance.

    + * @return true always + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public boolean _is_local() { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @param operation a String indicating which operation + * to preinvoke + * @param expectedType the class of the type of operation mentioned above + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local object + * @see CORBA package + * comments for unimplemented features + */ + public ServantObject _servant_preinvoke(String operation, + Class expectedType) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @param servant the servant object on which to post-invoke + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public void _servant_postinvoke(ServantObject servant) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /* + * The following methods were added by orbos/98-04-03: Java to IDL + * Mapping. These are used by RMI over IIOP. + */ + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method. + *

    Called by a stub to obtain an OutputStream for + * marshaling arguments. The stub must supply the operation name, + * and indicate if a response is expected (i.e is this a oneway + * call).

    + * @param operation the name of the operation being requested + * @param responseExpected true if a response is expected, + * false if it is a one-way call + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + public OutputStream _request(String operation, + boolean responseExpected) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method. + *

    Called to invoke an operation. The stub provides an + * OutputStream that was previously returned by a + * _request() + * call. _invoke returns an InputStream which + * contains the + * marshaled reply. If an exception occurs, _invoke may throw an + * ApplicationException object which contains an + * InputStream from + * which the user exception state may be unmarshaled.

    + * @param output the OutputStream to invoke + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @throws ApplicationException If an exception occurs, + * _invoke may throw an + * ApplicationException object which contains + * an InputStream from + * which the user exception state may be unmarshaled. + * @throws RemarshalException If an exception occurs, + * _invoke may throw an + * ApplicationException object which contains + * an InputStream from + * which the user exception state may be unmarshaled. + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + public InputStream _invoke(OutputStream output) + throws ApplicationException, RemarshalException + { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." + * This method is the default implementation of the + * org.omg.CORBA.Object method. + *

    May optionally be called by a stub to release a + * reply stream back to the ORB when the unmarshaling has + * completed. The stub passes the InputStream returned by + * _invoke() or + * ApplicationException.getInputStream(). + * A null + * value may also be passed to _releaseReply, in which case the + * method is a no-op.

    + * @param input the reply stream back to the ORB or null + * @exception NO_IMPLEMENT + * @see CORBA package + * comments for unimplemented features + */ + public void _releaseReply(InputStream input) { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception with + * the message "This is a locally constrained object." This method + * does not apply to local objects and is therefore not implemented. + * This method is the default implementation of the + * org.omg.CORBA.Object method.

    + * @return NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @exception NO_IMPLEMENT because this is a locally constrained object + * and this method does not apply to local objects + * @see CORBA package + * comments for unimplemented features + */ + + public boolean validate_connection() { + throw new org.omg.CORBA.NO_IMPLEMENT(reason); + } +} + + + + + + + diff --git a/omgapi/src/main/java/org/omg/CORBA/LongHolder.java b/omgapi/src/main/java/org/omg/CORBA/LongHolder.java new file mode 100644 index 000000000..65c967ed7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/LongHolder.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Long. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a long + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL long long as an "out" + * or "inout" parameter, the programmer must pass an instance of + * LongHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myLongHolder is an instance of LongHolder, + * the value stored in its value field can be accessed with + * myLongHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class LongHolder implements Streamable { + + /** + * The long value held by this LongHolder + * object. + */ + public long value; + + /** + * Constructs a new LongHolder object with its + * value field initialized to 0. + */ + public LongHolder() { + } + + /** + * Constructs a new LongHolder object with its + * value field initialized to the given + * long. + * @param initial the long with which to initialize + * the value field of the newly-created + * LongHolder object + */ + public LongHolder(long initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in the Holder + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire + */ + public void _read(InputStream input) { + value = input.read_longlong(); + } + + /** + * Marshals to output the value in the Holder. + * + * @param output the OutputStream which will contain the CDR formatted data + */ + public void _write(OutputStream output) { + output.write_longlong(value); + } + + /** + * Returns the TypeCode object + * corresponding to the value held in the Holder. + * + * @return the TypeCode of the value held in the holder + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_longlong); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/LongLongSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/LongLongSeqHelper.java new file mode 100644 index 000000000..9cab4dbf1 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/LongLongSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for LongLongSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/LongLongSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class LongLongSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/LongLongSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, long[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static long[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_longlong); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.LongLongSeqHelper.id (), "LongLongSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static long[] read (org.omg.CORBA.portable.InputStream istream) + { + long value[] = null; + int _len0 = istream.read_long (); + value = new long[_len0]; + istream.read_longlong_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, long[] value) + { + ostream.write_long (value.length); + ostream.write_longlong_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/LongLongSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/LongLongSeqHolder.java new file mode 100644 index 000000000..eeb61d716 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/LongLongSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for LongLongSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/LongLongSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class LongLongSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public long value[] = null; + + public LongLongSeqHolder () + { + } + + public LongLongSeqHolder (long[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.LongLongSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.LongLongSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.LongLongSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/LongSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/LongSeqHelper.java new file mode 100644 index 000000000..94a560ae2 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/LongSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for LongSeqHelper. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/LongSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class LongSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/LongSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, int[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static int[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.LongSeqHelper.id (), "LongSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static int[] read (org.omg.CORBA.portable.InputStream istream) + { + int value[] = null; + int _len0 = istream.read_long (); + value = new int[_len0]; + istream.read_long_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, int[] value) + { + ostream.write_long (value.length); + ostream.write_long_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/LongSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/LongSeqHolder.java new file mode 100644 index 000000000..d8df1778d --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/LongSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for LongSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/LongSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class LongSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public int value[] = null; + + public LongSeqHolder () + { + } + + public LongSeqHolder (int[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.LongSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.LongSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.LongSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/MARSHAL.java b/omgapi/src/main/java/org/omg/CORBA/MARSHAL.java new file mode 100644 index 000000000..4bcb472b6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/MARSHAL.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A request or reply from the network is structurally invalid. + * This error typically indicates a bug in either the client-side + * or server-side run time. For example, if a reply from the server + * indicates that the message contains 1000 bytes, but the actual + * message is shorter or longer than 1000 bytes, the ORB raises + * this exception. MARSHAL can also be caused by using + * the DII or DSI incorrectly, for example, if the type of the + * actual parameters sent does not agree with IDL signature of an + * operation.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section Minor + * Code Meanings to see the minor codes for this exception. + * + * @version 1.18, 09/09/97 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class MARSHAL extends SystemException { + /** + * Constructs a MARSHAL exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public MARSHAL() { + this(""); + } + + /** + * Constructs a MARSHAL exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description of the exception + */ + public MARSHAL(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a MARSHAL exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public MARSHAL(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a MARSHAL exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public MARSHAL(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NO_IMPLEMENT.java b/omgapi/src/main/java/org/omg/CORBA/NO_IMPLEMENT.java new file mode 100644 index 000000000..8f47d391a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NO_IMPLEMENT.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates that even though the operation that + * was invoked exists (it has an IDL definition), no implementation + * for that operation exists. NO_IMPLEMENT can, for + * example, be raised by an ORB if a client asks for an object's + * type definition from the interface repository, but no interface + * repository is provided by the ORB.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section Minor + * Code Meanings to see the minor codes for this exception. + * + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class NO_IMPLEMENT extends SystemException { + /** + * Constructs a NO_IMPLEMENT exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public NO_IMPLEMENT() { + this(""); + } + + /** + * Constructs a NO_IMPLEMENT exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description of the exception + */ + public NO_IMPLEMENT(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a NO_IMPLEMENT exception with the specified + * minor code and completion status. + * @param minor an int specifying the minor code + * @param completed a CompletionStatus instance indicating + * the completion status + */ + public NO_IMPLEMENT(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a NO_IMPLEMENT exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor an int specifying the minor code + * @param completed a CompletionStatus instance indicating + * the completion status + */ + public NO_IMPLEMENT(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NO_MEMORY.java b/omgapi/src/main/java/org/omg/CORBA/NO_MEMORY.java new file mode 100644 index 000000000..04881451d --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NO_MEMORY.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when the ORB run time has run out of memory. + *

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.18, 09/09/97 + * @since JDK1.2 + */ + +public final class NO_MEMORY extends SystemException { + /** + * Constructs a NO_MEMORY exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public NO_MEMORY() { + this(""); + } + + /** + * Constructs a NO_MEMORY exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description message + */ + public NO_MEMORY(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a NO_MEMORY exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public NO_MEMORY(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a NO_MEMORY exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public NO_MEMORY(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/NO_PERMISSION.java b/omgapi/src/main/java/org/omg/CORBA/NO_PERMISSION.java new file mode 100644 index 000000000..4a695bd38 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NO_PERMISSION.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when an invocation failed because the caller + * has insufficient privileges.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class NO_PERMISSION extends SystemException { + /** + * Constructs a NO_PERMISSION exception with a default minor code + * of 0 and a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public NO_PERMISSION() { + this(""); + } + + /** + * Constructs a NO_PERMISSION exception with the specified description, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description message + */ + public NO_PERMISSION(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a NO_PERMISSION exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public NO_PERMISSION(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a NO_PERMISSION exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public NO_PERMISSION(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NO_RESOURCES.java b/omgapi/src/main/java/org/omg/CORBA/NO_RESOURCES.java new file mode 100644 index 000000000..9d386c9c8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NO_RESOURCES.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when the ORB has encountered some general resource + * limitation. For example, the run time may have reached the maximum + * permissible number of open connections.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class NO_RESOURCES extends SystemException { + /** + * Constructs a NO_RESOURCES exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public NO_RESOURCES() { + this(""); + } + + /** + * Constructs a NO_RESOURCES exception with the specified description, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description message + */ + public NO_RESOURCES(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a NO_RESOURCES exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public NO_RESOURCES(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a NO_RESOURCES exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public NO_RESOURCES(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NO_RESPONSE.java b/omgapi/src/main/java/org/omg/CORBA/NO_RESPONSE.java new file mode 100644 index 000000000..e4c115734 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NO_RESPONSE.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception is raised if a client attempts to retrieve the result + * of a deferred synchronous call, but the response for the request is + * not yet available.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class NO_RESPONSE extends SystemException { + /** + * Constructs a NO_RESPONSE exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public NO_RESPONSE() { + this(""); + } + + /** + * Constructs a NO_RESPONSE exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description message + */ + public NO_RESPONSE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a NO_RESPONSE exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public NO_RESPONSE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a NO_RESPONSE exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public NO_RESPONSE(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NVList.java b/omgapi/src/main/java/org/omg/CORBA/NVList.java new file mode 100644 index 000000000..98d1c5013 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NVList.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A modifiable list containing NamedValue objects. + *

    + * The class NVList is used as follows: + *

      + *
    • to describe arguments for a Request object + * in the Dynamic Invocation Interface and + * the Dynamic Skeleton Interface + *
    • to describe context values in a Context object + *
    + *

    + * Each NamedValue object consists of the following: + *

      + *
    • a name, which is a String object + *
    • a value, as an Any object + *
    • an argument mode flag + *
    + *

    + * An NVList object + * may be created using one of the following + * ORB methods: + *

      + *
    1. org.omg.CORBA.ORB.create_list + *
      + *    org.omg.CORBA.NVList nv = orb.create_list(3);
      + * 
      + * The variable nv represents a newly-created + * NVList object. The argument is a memory-management + * hint to the orb and does not imply the actual length of the list. + * If, for example, you want to use an NVList object + * in a request, and the method being invoked takes three parameters, + * you might optimize by supplying 3 to the method + * create_list. Note that the new NVList + * will not necessarily have a length of 3; it + * could have a length of 2 or 4, for instance. + * Note also that you can add any number of + * NamedValue objects to this list regardless of + * its original length. + *

      + *

    2. org.omg.CORBA.ORB.create_operation_list + *
      + *    org.omg.CORBA.NVList nv = orb.create_operation_list(myOperationDef);
      + * 
      + * The variable nv represents a newly-created + * NVList object that contains descriptions of the + * arguments to the method described in the given + * OperationDef object. + *
    + *

    + * The methods in the class NVList all deal with + * the NamedValue objects in the list. + * There are three methods for adding a NamedValue object, + * a method for getting the count of NamedValue objects in + * the list, a method for retrieving a NamedValue object + * at a given index, and a method for removing a NamedValue object + * at a given index. + * + * @see org.omg.CORBA.Request + * @see org.omg.CORBA.ServerRequest + * @see org.omg.CORBA.NamedValue + * @see org.omg.CORBA.Context + * + * @version 1.14 ,09/09/97 + * @since JDK1.2 + */ + +public abstract class NVList { + + /** + * Returns the number of NamedValue objects that have + * been added to this NVList object. + * + * @return an int indicating the number of + * NamedValue objects in this NVList. + */ + + public abstract int count(); + + /** + * Creates a new NamedValue object initialized with the given flag + * and adds it to the end of this NVList object. + * The flag can be any one of the argument passing modes: + * ARG_IN.value, ARG_OUT.value, or + * ARG_INOUT.value. + * + * @param flags one of the argument mode flags + * @return the newly-created NamedValue object + */ + + public abstract NamedValue add(int flags); + + /** + * Creates a new NamedValue object initialized with the + * given name and flag, + * and adds it to the end of this NVList object. + * The flag can be any one of the argument passing modes: + * ARG_IN.value, ARG_OUT.value, or + * ARG_INOUT.value. + * + * @param item_name the name for the new NamedValue object + * @param flags one of the argument mode flags + * @return the newly-created NamedValue object + */ + + public abstract NamedValue add_item(String item_name, int flags); + + /** + * Creates a new NamedValue object initialized with the + * given name, value, and flag, + * and adds it to the end of this NVList object. + * + * @param item_name the name for the new NamedValue object + * @param val an Any object containing the value + * for the new NamedValue object + * @param flags one of the following argument passing modes: + * ARG_IN.value, ARG_OUT.value, or + * ARG_INOUT.value + * @return the newly created NamedValue object + */ + + public abstract NamedValue add_value(String item_name, Any val, int flags); + + /** + * Retrieves the NamedValue object at the given index. + * + * @param index the index of the desired NamedValue object, + * which must be between zero and the length of the list + * minus one, inclusive. The first item is at index zero. + * @return the NamedValue object at the given index + * @exception org.omg.CORBA.Bounds if the index is greater than + * or equal to number of NamedValue objects + */ + + public abstract NamedValue item(int index) throws org.omg.CORBA.Bounds; + + /** + * Removes the NamedValue object at the given index. + * Note that the indices of all NamedValue objects following + * the one removed are shifted down by one. + * + * @param index the index of the NamedValue object to be + * removed, which must be between zero and the length + * of the list minus one, inclusive. + * The first item is at index zero. + * @exception org.omg.CORBA.Bounds if the index is greater than + * or equal to number of NamedValue objects in + * the list + */ + + public abstract void remove(int index) throws org.omg.CORBA.Bounds; + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NameValuePair.java b/omgapi/src/main/java/org/omg/CORBA/NameValuePair.java new file mode 100644 index 000000000..cb2566096 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NameValuePair.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Associates a name with a value that is an + * attribute of an IDL struct, and is used in the DynStruct APIs. + */ + +// @SuppressWarnings({"serial"}) +public final class NameValuePair implements org.omg.CORBA.portable.IDLEntity { + + /** + * The name to be associated with a value by this NameValuePair object. + */ + public String id; + + /** + * The value to be associated with a name by this NameValuePair object. + */ + public org.omg.CORBA.Any value; + + /** + * Constructs an empty NameValuePair object. + * To associate a name with a value after using this constructor, the fields + * of this object have to be accessed individually. + */ + public NameValuePair() { } + + /** + * Constructs a NameValuePair object that associates + * the given name with the given org.omg.CORBA.Any object. + * @param __id the name to be associated with the given Any object + * @param __value the Any object to be associated with the given name + */ + public NameValuePair(String __id, org.omg.CORBA.Any __value) { + id = __id; + value = __value; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NameValuePairHelper.java b/omgapi/src/main/java/org/omg/CORBA/NameValuePairHelper.java new file mode 100644 index 000000000..a391dc7d3 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NameValuePairHelper.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for NameValuePair. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/NameValuePairHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* 03 June 1999 11:52:03 o'clock GMT+00:00 +*/ + +abstract public class NameValuePairHelper +{ + private static String _id = "IDL:omg.org/CORBA/NameValuePair:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.NameValuePair that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.NameValuePair extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.FieldNameHelper.id (), "FieldName", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[1] = new org.omg.CORBA.StructMember ( + "value", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.NameValuePairHelper.id (), "NameValuePair", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.NameValuePair read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.NameValuePair value = new org.omg.CORBA.NameValuePair (); + value.id = istream.read_string (); + value.value = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.NameValuePair value) + { + ostream.write_string (value.id); + ostream.write_any (value.value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/NamedValue.java b/omgapi/src/main/java/org/omg/CORBA/NamedValue.java new file mode 100644 index 000000000..2dc78110a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/NamedValue.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object used in the DII and DSI to describe + * arguments and return values. NamedValue objects + * are also used in the Context + * object routines to pass lists of property names and values. + *

    + * A NamedValue object contains: + *

      + *
    • a name -- If the NamedValue object is used to + * describe arguments to a request, the name will be an argument + * identifier specified in the OMG IDL interface definition + * for the operation being described. + *
    • a value -- an Any object + *
    • an argument mode flag -- one of the following: + *
        + *
      • ARG_IN.value + *
      • ARG_OUT.value + *
      • ARG_INOUT.value + *
      • zero -- if this NamedValue object represents a property + * in a Context object rather than a parameter or + * return value + *
      + *
    + *

    + * The class NamedValue has three methods, which + * access its fields. The following code fragment demonstrates + * creating a NamedValue object and then accessing + * its fields: + *

    + *    ORB orb = ORB.init(args, null);
    + *    String s = "argument_1";
    + *    org.omg.CORBA.Any myAny = orb.create_any();
    + *    myAny.insert_long(12345);
    + *    int in = org.omg.CORBA.ARG_IN.value;
    +
    + *    org.omg.CORBA.NamedValue nv = orb.create_named_value(
    + *        s, myAny, in);
    + *    System.out.println("This nv name is " + nv.name());
    + *    try {
    + *        System.out.println("This nv value is " + nv.value().extract_long());
    + *        System.out.println("This nv flag is " + nv.flags());
    + *    } catch (org.omg.CORBA.BAD_OPERATION b) {
    + *      System.out.println("extract failed");
    + *    }
    + * 
    + * + *

    + * If this code fragment were put into a main method, + * the output would be something like the following: + *

    + *    This nv name is argument_1
    + *    This nv value is 12345
    + *    This nv flag is 1
    + * 
    + *

    + * Note that the method value returns an Any + * object. In order to access the long contained in the + * Any object, + * we used the method extract_long. + * + * @see Any + * @see ARG_IN + * @see ARG_INOUT + * @see ARG_OUT + * + * @version 1.12 ,09/09/97 + * @since JDK1.2 + */ + +public abstract class NamedValue { + + /** + * Retrieves the name for this NamedValue object. + * + * @return a String object representing + * the name of this NamedValue object + */ + + public abstract String name(); + + /** + * Retrieves the value for this NamedValue object. + * + * @return an Any object containing + * the value of this NamedValue object + */ + + public abstract Any value(); + + /** + * Retrieves the argument mode flag for this NamedValue object. + * + * @return an int representing the argument + * mode for this NamedValue object + */ + + public abstract int flags(); + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/OBJECT_NOT_EXIST.java b/omgapi/src/main/java/org/omg/CORBA/OBJECT_NOT_EXIST.java new file mode 100644 index 000000000..d1a3399e7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/OBJECT_NOT_EXIST.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception raised whenever an invocation on a deleted object was + * performed. It is an authoritative "hard" fault report. Anyone + * receiving it is allowed (even expected) to delete all copies of + * this object reference and to perform other appropriate "final + * recovery" style procedures. Bridges forward this exception to + * clients, also destroying any records they may hold (for example, + * proxy objects used in reference translation). The clients could + * in turn purge any of their own data structures. + *

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section Minor + * Code Meanings to see the minor codes for this exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.13, 09/09/97 + * @since JDK1.2 + */ + +public final class OBJECT_NOT_EXIST extends SystemException { + /** + * Constructs an OBJECT_NOT_EXIST exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public OBJECT_NOT_EXIST() { + this(""); + } + + /** + * Constructs an OBJECT_NOT_EXIST exception with the specified description, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description message + */ + public OBJECT_NOT_EXIST(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an OBJECT_NOT_EXIST exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public OBJECT_NOT_EXIST(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an OBJECT_NOT_EXIST exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public OBJECT_NOT_EXIST(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/OBJ_ADAPTER.java b/omgapi/src/main/java/org/omg/CORBA/OBJ_ADAPTER.java new file mode 100644 index 000000000..9c71d0e7e --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/OBJ_ADAPTER.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception typically indicates an administrative mismatch, for + * example, a server may have made an attempt to register itself with + * an implementation repository under a name that is already in use, + * or is unknown to the repository.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section Minor + * Code Meanings to see the minor codes for this exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17, 09/09/97 + * @since JDK1.2 + */ + +public final class OBJ_ADAPTER extends SystemException { + /** + * Constructs an OBJ_ADAPTER exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public OBJ_ADAPTER() { + this(""); + } + + /** + * Constructs an OBJ_ADAPTER exception with the specified description, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a description message + */ + public OBJ_ADAPTER(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an OBJ_ADAPTER exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public OBJ_ADAPTER(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an OBJ_ADAPTER exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public OBJ_ADAPTER(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/OMGVMCID.java b/omgapi/src/main/java/org/omg/CORBA/OMGVMCID.java new file mode 100644 index 000000000..f9981fd05 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/OMGVMCID.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The vendor minor code ID reserved for OMG. Minor codes for the standard + * exceptions are prefaced by the VMCID assigned to OMG, defined as the + * constant OMGVMCID, which, like all VMCIDs, occupies the high order 20 bits. + */ + +public interface OMGVMCID { + + /** + * The vendor minor code ID reserved for OMG. This value is or'd with + * the high order 20 bits of the minor code to produce the minor value + * in a system exception. + */ + static final int value = 0x4f4d0000; +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/ORB.java b/omgapi/src/main/java/org/omg/CORBA/ORB.java new file mode 100644 index 000000000..50c5b56b0 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ORB.java @@ -0,0 +1,1344 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.*; +import org.omg.CORBA.ORBPackage.InvalidName; + +import java.util.Properties; +import java.applet.Applet; +import java.io.File; +import java.io.FileInputStream; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * A class providing APIs for the CORBA Object Request Broker + * features. The ORB class also provides + * "pluggable ORB implementation" APIs that allow another vendor's ORB + * implementation to be used. + *

    + * An ORB makes it possible for CORBA objects to communicate + * with each other by connecting objects making requests (clients) with + * objects servicing requests (servers). + *

    + * + * The ORB class, which + * encapsulates generic CORBA functionality, does the following: + * (Note that items 5 and 6, which include most of the methods in + * the class ORB, are typically used with the Dynamic Invocation + * Interface (DII) and the Dynamic Skeleton Interface + * (DSI). + * These interfaces may be used by a developer directly, but + * most commonly they are used by the ORB internally and are + * not seen by the general programmer.) + *

      + *
    1. initializes the ORB implementation by supplying values for + * predefined properties and environmental parameters + *
    2. obtains initial object references to services such as + * the NameService using the method resolve_initial_references + *
    3. converts object references to strings and back + *
    4. connects the ORB to a servant (an instance of a CORBA object + * implementation) and disconnects the ORB from a servant + *
    5. creates objects such as + *
        + *
      • TypeCode + *
      • Any + *
      • NamedValue + *
      • Context + *
      • Environment + *
      • lists (such as NVList) containing these objects + *
      + *
    6. sends multiple messages in the DII + *
    + * + *

    + * The ORB class can be used to obtain references to objects + * implemented anywhere on the network. + *

    + * An application or applet gains access to the CORBA environment + * by initializing itself into an ORB using one of + * three init methods. Two of the three methods use the properties + * (associations of a name with a value) shown in the + * table below.
    + * + * + * + * + * + * + * + *
    Property Name Property Value
    Standard Java CORBA Properties:
    org.omg.CORBA.ORBClassclass name of an ORB implementation
    org.omg.CORBA.ORBSingletonClassclass name of the ORB returned by init()
    + *

    + * These properties allow a different vendor's ORB + * implementation to be "plugged in." + *

    + * When an ORB instance is being created, the class name of the ORB + * implementation is located using + * the following standard search order:

    + * + *

      + *
    1. check in Applet parameter or application string array, if any + * + *
    2. check in properties parameter, if any + * + *
    3. check in the System properties + * + *
    4. check in the orb.properties file located in the user.home + * directory (if any) + * + *
    5. check in the orb.properties file located in the java.home/lib + * directory (if any) + * + *
    6. fall back on a hardcoded default behavior (use the Java IDL + * implementation) + *
    + *

    + * Note that Java IDL provides a default implementation for the + * fully-functional ORB and for the Singleton ORB. When the method + * init is given no parameters, the default Singleton + * ORB is returned. When the method init is given parameters + * but no ORB class is specified, the Java IDL ORB implementation + * is returned. + *

    + * The following code fragment creates an ORB object + * initialized with the default ORB Singleton. + * This ORB has a + * restricted implementation to prevent malicious applets from doing + * anything beyond creating typecodes. + * It is called a singleton + * because there is only one instance for an entire virtual machine. + *

    + *    ORB orb = ORB.init();
    + * 
    + *

    + * The following code fragment creates an ORB object + * for an application. The parameter args + * represents the arguments supplied to the application's main + * method. Since the property specifies the ORB class to be + * "SomeORBImplementation", the new ORB will be initialized with + * that ORB implementation. If p had been null, + * and the arguments had not specified an ORB class, + * the new ORB would have been + * initialized with the default Java IDL implementation. + *

    + *    Properties p = new Properties();
    + *    p.put("org.omg.CORBA.ORBClass", "SomeORBImplementation");
    + *    ORB orb = ORB.init(args, p);
    + * 
    + *

    + * The following code fragment creates an ORB object + * for the applet supplied as the first parameter. If the given + * applet does not specify an ORB class, the new ORB will be + * initialized with the default Java IDL implementation. + *

    + *    ORB orb = ORB.init(myApplet, null);
    + * 
    + *

    + * An application or applet can be initialized in one or more ORBs. + * ORB initialization is a bootstrap call into the CORBA world. + * @version 1.70, 09/09/97 + * @since JDK1.2 + */ +abstract public class ORB { + + // + // This is the ORB implementation used when nothing else is specified. + // Whoever provides this class customizes this string to + // point at their ORB implementation. + // + private static final String ORBClassKey = "org.omg.CORBA.ORBClass"; + private static final String ORBSingletonClassKey = "org.omg.CORBA.ORBSingletonClass"; + + // + // The last resort fallback ORB implementation classes in case + // no ORB implementation class is dynamically configured through + // properties or applet parameters. Change these values to + // vendor-specific class names. + // + private static final String defaultORB = "com.sun.corba.ee.impl.orb.ORBImpl"; + private static final String defaultORBSingleton = "com.sun.corba.ee.impl.orb.ORBSingleton"; + + // + // The global instance of the singleton ORB implementation which + // acts as a factory for typecodes for generated Helper classes. + // TypeCodes should be immutable since they may be shared across + // different security contexts (applets). There should be no way to + // use a TypeCode as a storage depot for illicitly passing + // information or Java objects between different security contexts. + // + static private ORB singleton; + + // Get System property + private static String getSystemProperty(final String name) { + // This will not throw a SecurityException because this + // class was loaded from rt.jar using the bootstrap classloader. + String propValue = AccessController.doPrivileged( + new PrivilegedAction() { + public String run() { + return System.getProperty(name); + } + } + ) ; + + return propValue; + } + + // Get property from orb.properties in either or /lib + // directories. + private static String getPropertyFromFile(final String name) { + // This will not throw a SecurityException because this + // class was loaded from rt.jar using the bootstrap classloader. + + String propValue = (String)AccessController.doPrivileged( + new PrivilegedAction() { + private Properties getFileProperties( String fileName ) { + try { + File propFile = new File( fileName ) ; + if (!propFile.exists()) + return null ; + + Properties props = new Properties() ; + FileInputStream fis = new FileInputStream(propFile); + try { + props.load( fis ); + } finally { + fis.close() ; + } + + return props ; + } catch (Exception exc) { + return null ; + } + } + + public java.lang.Object run() { + String userHome = System.getProperty("user.home"); + String fileName = userHome + File.separator + + "orb.properties" ; + Properties props = getFileProperties( fileName ) ; + + if (props != null) { + String value = props.getProperty( name ) ; + if (value != null) + return value ; + } + + String javaHome = System.getProperty("java.home"); + fileName = javaHome + File.separator + + "lib" + File.separator + "orb.properties"; + props = getFileProperties( fileName ) ; + + if (props == null) + return null ; + else + return props.getProperty( name ) ; + } + } + ); + + return propValue; + } + + /** + * Returns the ORB singleton object. This method always returns the + * same ORB instance, which is an instance of the class described by the + * org.omg.CORBA.ORBSingletonClass system property. + *

    + * This no-argument version of the method init is used primarily + * as a factory for TypeCode objects, which are used by + * Helper classes to implement the method type. + * It is also used to create Any objects that are used to + * describe union labels (as part of creating a + * TypeCode object for a union). + *

    + * This method is not intended to be used by applets, and in the event + * that it is called in an applet environment, the ORB it returns + * is restricted so that it can be used only as a factory for + * TypeCode objects. Any TypeCode objects + * it produces can be safely shared among untrusted applets. + *

    + * If an ORB is created using this method from an applet, + * a system exception will be thrown if + * methods other than those for + * creating TypeCode objects are invoked. + * + * @return the singleton ORB + */ + public static synchronized ORB init() { + if (singleton == null) { + String className = getSystemProperty(ORBSingletonClassKey); + if (className == null) + className = getPropertyFromFile(ORBSingletonClassKey); + if (className == null) + className = defaultORBSingleton; + + singleton = create_impl_with_systemclassloader(className); + } + return singleton; + } + + private static ORB create_impl_with_systemclassloader(String className) { + try { + checkPackageAccess(className); + ClassLoader cl = ClassLoader.getSystemClassLoader(); + Class orbBaseClass = org.omg.CORBA.ORB.class; + Class singletonOrbClass = Class.forName(className, true, cl).asSubclass(orbBaseClass); + return (ORB)singletonOrbClass.newInstance(); + } catch (Throwable ex) { + SystemException systemException = new INITIALIZE( + "can't instantiate default ORB implementation " + className); + systemException.initCause(ex); + throw systemException; + } + + } + + private static ORB create_impl(String className) { + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl == null) { + cl = ClassLoader.getSystemClassLoader(); + } + + try { + checkPackageAccess(className); + Class orbBaseClass = org.omg.CORBA.ORB.class; + Class orbClass = Class.forName(className, true, cl).asSubclass(orbBaseClass); + return (ORB) orbClass.newInstance(); + } catch (Throwable ex) { + SystemException systemException = new INITIALIZE( + "can't instantiate default ORB implementation " + className); + systemException.initCause(ex); + throw systemException; + } + } + + /** + * Creates a new ORB instance for a standalone + * application. This method may be called from applications + * only and returns a new fully functional ORB object + * each time it is called. + * @param args command-line arguments for the application's main + * method; may be null + * @param props application-specific properties; may be null + * @return the newly-created ORB instance + */ + public static ORB init(String[] args, Properties props) { + // + // Note that there is no standard command-line argument for + // specifying the default ORB implementation. For an + // application you can choose an implementation either by + // setting the CLASSPATH to pick a different org.omg.CORBA + // and it's baked-in ORB implementation default or by + // setting an entry in the properties object or in the + // system properties. + // + String className = null; + ORB orb; + + if (props != null) + className = props.getProperty(ORBClassKey); + if (className == null) + className = getSystemProperty(ORBClassKey); + if (className == null) + className = getPropertyFromFile(ORBClassKey); + if (className == null) + className = defaultORB; + + orb = create_impl(className); + orb.set_parameters(args, props); + return orb; + } + + + /** + * Creates a new ORB instance for an applet. This + * method may be called from applets only and returns a new + * fully-functional ORB object each time it is called. + * @param app the applet; may be null + * @param props applet-specific properties; may be null + * @return the newly-created ORB instance + */ + public static ORB init(Applet app, Properties props) { + String className; + ORB orb; + + className = app.getParameter(ORBClassKey); + if (className == null && props != null) + className = props.getProperty(ORBClassKey); + if (className == null) + className = getSystemProperty(ORBClassKey); + if (className == null) + className = getPropertyFromFile(ORBClassKey); + if (className == null) + className = defaultORB; + + orb = create_impl(className); + orb.set_parameters(app, props); + return orb; + } + + /** + * Allows the ORB implementation to be initialized with the given + * parameters and properties. This method, used in applications only, + * is implemented by subclass ORB implementations and called + * by the appropriate init method to pass in its parameters. + * + * @param args command-line arguments for the application's main + * method; may be null + * @param props application-specific properties; may be null + */ + abstract protected void set_parameters(String[] args, Properties props); + + /** + * Allows the ORB implementation to be initialized with the given + * applet and parameters. This method, used in applets only, + * is implemented by subclass ORB implementations and called + * by the appropriate init method to pass in its parameters. + * + * @param app the applet; may be null + * @param props applet-specific properties; may be null + */ + abstract protected void set_parameters(Applet app, Properties props); + + /** + * Connects the given servant object (a Java object that is + * an instance of the server implementation class) + * to the ORB. The servant class must + * extend the ImplBase class corresponding to the interface that is + * supported by the server. The servant must thus be a CORBA object + * reference, and inherit from org.omg.CORBA.Object. + * Servants created by the user can start receiving remote invocations + * after the method connect has been called. A servant may also be + * automatically and implicitly connected to the ORB if it is passed as + * an IDL parameter in an IDL method invocation on a non-local object, + * that is, if the servant object has to be marshalled and sent outside of the + * process address space. + *

    + * Calling the method connect has no effect + * when the servant object is already connected to the ORB. + *

    + * Deprecated by the OMG in favor of the Portable Object Adapter APIs. + * + * @param obj The servant object reference + */ + public void connect(org.omg.CORBA.Object obj) { + throw new NO_IMPLEMENT(); + } + + /** + * Destroys the ORB so that its resources can be reclaimed. + * Any operation invoked on a destroyed ORB reference will throw the + * OBJECT_NOT_EXIST exception. + * Once an ORB has been destroyed, another call to init + * with the same ORBid will return a reference to a newly constructed ORB.

    + * If destroy is called on an ORB that has not been shut down, + * it will start the shut down process and block until the ORB has shut down + * before it destroys the ORB.
    + * If an application calls destroy in a thread that is currently servicing + * an invocation, the BAD_INV_ORDER system exception will be thrown + * with the OMG minor code 3, since blocking would result in a deadlock.

    + * For maximum portability and to avoid resource leaks, an application should + * always call shutdown and destroy + * on all ORB instances before exiting. + * + * @throws org.omg.CORBA.BAD_INV_ORDER if the current thread is servicing an invocation + */ + public void destroy( ) { + throw new NO_IMPLEMENT(); + } + + /** + * Disconnects the given servant object from the ORB. After this method returns, + * the ORB will reject incoming remote requests for the disconnected + * servant and will send the exception + * org.omg.CORBA.OBJECT_NOT_EXIST back to the + * remote client. Thus the object appears to be destroyed from the + * point of view of remote clients. Note, however, that local requests issued + * using the servant directly do not + * pass through the ORB; hence, they will continue to be processed by the + * servant. + *

    + * Calling the method disconnect has no effect + * if the servant is not connected to the ORB. + *

    + * Deprecated by the OMG in favor of the Portable Object Adapter APIs. + * + * @param obj The servant object to be disconnected from the ORB + */ + public void disconnect(org.omg.CORBA.Object obj) { + throw new NO_IMPLEMENT(); + } + + // + // ORB method implementations. + // + // We are trying to accomplish 2 things at once in this class. + // It can act as a default ORB implementation front-end, + // creating an actual ORB implementation object which is a + // subclass of this ORB class and then delegating the method + // implementations. + // + // To accomplish the delegation model, the 'delegate' private instance + // variable is set if an instance of this class is created directly. + // + + /** + * Returns a list of the initially available CORBA object references, + * such as "NameService" and "InterfaceRepository". + * + * @return an array of String objects that represent + * the object references for CORBA services + * that are initially available with this ORB + */ + abstract public String[] list_initial_services(); + + /** + * Resolves a specific object reference from the set of available + * initial service names. + * + * @param object_name the name of the initial service as a string + * @return the object reference associated with the given name + * @exception InvalidName if the given name is not associated with a + * known service + */ + abstract public org.omg.CORBA.Object resolve_initial_references(String object_name) + throws InvalidName; + + /** + * Converts the given CORBA object reference to a string. + * Note that the format of this string is predefined by IIOP, allowing + * strings generated by a different ORB to be converted back into an object + * reference. + *

    + * The resulting String object may be stored or communicated + * in any way that a String object can be manipulated. + * + * @param obj the object reference to stringify + * @return the string representing the object reference + */ + abstract public String object_to_string(org.omg.CORBA.Object obj); + + /** + * Converts a string produced by the method object_to_string + * back to a CORBA object reference. + * + * @param str the string to be converted back to an object reference. It must + * be the result of converting an object reference to a string using the + * method object_to_string. + * @return the object reference + */ + abstract public org.omg.CORBA.Object string_to_object(String str); + + /** + * Allocates an NVList with (probably) enough + * space for the specified number of NamedValue objects. + * Note that the specified size is only a hint to help with + * storage allocation and does not imply the maximum size of the list. + * + * @param count suggested number of NamedValue objects for + * which to allocate space + * @return the newly-created NVList + * + * @see NVList + */ + abstract public NVList create_list(int count); + + /** + * Creates an NVList initialized with argument + * descriptions for the operation described in the given + * OperationDef object. This OperationDef object + * is obtained from an Interface Repository. The arguments in the + * returned NVList object are in the same order as in the + * original IDL operation definition, which makes it possible for the list + * to be used in dynamic invocation requests. + * + * @param oper the OperationDef object to use to create the list + * @return a newly-created NVList object containing + * descriptions of the arguments to the method described in the given + * OperationDef object + * + * @see NVList + */ + public NVList create_operation_list(org.omg.CORBA.Object oper) + { + // If we came here, it means that the actual ORB implementation + // did not override the create_operation_list(CORBA.Object oper) method, + // so lets check if it has a create_operation_list(OperationDef oper) + // method. + try { + // First try to load the OperationDef class + String opDefClassName = "org.omg.CORBA.OperationDef"; + Class opDefClass = null; + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if ( cl == null ) + cl = ClassLoader.getSystemClassLoader(); + // if this throws a ClassNotFoundException, it will be caught below. + opDefClass = Class.forName(opDefClassName, true, cl); + + Class[] args = { opDefClass } ; + java.lang.reflect.Method meth = + this.getClass().getMethod("create_operation_list", + args ); + + Object[] args2 = { oper } ; + // The following line causes a warning on JDK 1.5 and later + // because invoke is a varargs method and this is not + // a varargs call. But using varargs here causes rmic -iiop + // to fail! Fixing rmic requires rewriting the IIOP + // backend to avoid using the old sun.tools code. + return (org.omg.CORBA.NVList)meth.invoke(this, args2); + } catch( java.lang.reflect.InvocationTargetException exs ) { + Throwable t = exs.getTargetException(); + if (t instanceof Error) { + throw (Error) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } catch( RuntimeException ex ) { + throw ex; + } catch( Exception exr ) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } + + + /** + * Creates a NamedValue object + * using the given name, value, and argument mode flags. + *

    + * A NamedValue object serves as (1) a parameter or return + * value or (2) a context property. + * It may be used by itself or + * as an element in an NVList object. + * + * @param s the name of the NamedValue object + * @param any the Any value to be inserted into the + * NamedValue object + * @param flags the argument mode flags for the NamedValue: one of + * ARG_IN.value, ARG_OUT.value, + * or ARG_INOUT.value. + * + * @return the newly-created NamedValue object + * @see NamedValue + */ + abstract public NamedValue create_named_value(String s, Any any, int flags); + + /** + * Creates an empty ExceptionList object. + * + * @return the newly-created ExceptionList object + */ + abstract public ExceptionList create_exception_list(); + + /** + * Creates an empty ContextList object. + * + * @return the newly-created ContextList object + * @see ContextList + * @see Context + */ + abstract public ContextList create_context_list(); + + /** + * Gets the default Context object. + * + * @return the default Context object + * @see Context + */ + abstract public Context get_default_context(); + + /** + * Creates an Environment object. + * + * @return the newly-created Environment object + * @see Environment + */ + abstract public Environment create_environment(); + + /** + * Creates a new org.omg.CORBA.portable.OutputStream into which + * IDL method parameters can be marshalled during method invocation. + * @return the newly-created + * org.omg.CORBA.portable.OutputStream object + */ + abstract public org.omg.CORBA.portable.OutputStream create_output_stream(); + + /** + * Sends multiple dynamic (DII) requests asynchronously without expecting + * any responses. Note that oneway invocations are not guaranteed to + * reach the server. + * + * @param req an array of request objects + */ + abstract public void send_multiple_requests_oneway(Request[] req); + + /** + * Sends multiple dynamic (DII) requests asynchronously. + * + * @param req an array of Request objects + */ + abstract public void send_multiple_requests_deferred(Request[] req); + + /** + * Finds out if any of the deferred (asynchronous) invocations have + * a response yet. + * @return true if there is a response available; + * false otherwise + */ + abstract public boolean poll_next_response(); + + /** + * Gets the next Request instance for which a response + * has been received. + * + * @return the next Request object ready with a response + * @exception WrongTransaction if the method get_next_response + * is called from a transaction scope different + * from the one from which the original request was sent. See the + * OMG Transaction Service specification for details. + */ + abstract public Request get_next_response() throws WrongTransaction; + + /** + * Retrieves the TypeCode object that represents + * the given primitive IDL type. + * + * @param tcKind the TCKind instance corresponding to the + * desired primitive type + * @return the requested TypeCode object + */ + abstract public TypeCode get_primitive_tc(TCKind tcKind); + + /** + * Creates a TypeCode object representing an IDL struct. + * The TypeCode object is initialized with the given id, + * name, and members. + * + * @param id the repository id for the struct + * @param name the name of the struct + * @param members an array describing the members of the struct + * @return a newly-created TypeCode object describing + * an IDL struct + */ + abstract public TypeCode create_struct_tc(String id, String name, + StructMember[] members); + + /** + * Creates a TypeCode object representing an IDL union. + * The TypeCode object is initialized with the given id, + * name, discriminator type, and members. + * + * @param id the repository id of the union + * @param name the name of the union + * @param discriminator_type the type of the union discriminator + * @param members an array describing the members of the union + * @return a newly-created TypeCode object describing + * an IDL union + */ + abstract public TypeCode create_union_tc(String id, String name, + TypeCode discriminator_type, + UnionMember[] members); + + /** + * Creates a TypeCode object representing an IDL enum. + * The TypeCode object is initialized with the given id, + * name, and members. + * + * @param id the repository id for the enum + * @param name the name for the enum + * @param members an array describing the members of the enum + * @return a newly-created TypeCode object describing + * an IDL enum + */ + abstract public TypeCode create_enum_tc(String id, String name, String[] members); + + /** + * Creates a TypeCode object representing an IDL alias + * (typedef). + * The TypeCode object is initialized with the given id, + * name, and original type. + * + * @param id the repository id for the alias + * @param name the name for the alias + * @param original_type + * the TypeCode object describing the original type + * for which this is an alias + * @return a newly-created TypeCode object describing + * an IDL alias + */ + abstract public TypeCode create_alias_tc(String id, String name, + TypeCode original_type); + + /** + * Creates a TypeCode object representing an IDL exception. + * The TypeCode object is initialized with the given id, + * name, and members. + * + * @param id the repository id for the exception + * @param name the name for the exception + * @param members an array describing the members of the exception + * @return a newly-created TypeCode object describing + * an IDL exception + */ + abstract public TypeCode create_exception_tc(String id, String name, + StructMember[] members); + + /** + * Creates a TypeCode object representing an IDL interface. + * The TypeCode object is initialized with the given id + * and name. + * + * @param id the repository id for the interface + * @param name the name for the interface + * @return a newly-created TypeCode object describing + * an IDL interface + */ + + abstract public TypeCode create_interface_tc(String id, String name); + + /** + * Creates a TypeCode object representing a bounded IDL + * string. + * The TypeCode object is initialized with the given bound, + * which represents the maximum length of the string. Zero indicates + * that the string described by this type code is unbounded. + * + * @param bound the bound for the string; cannot be negative + * @return a newly-created TypeCode object describing + * a bounded IDL string + * @exception BAD_PARAM if bound is a negative value + */ + + abstract public TypeCode create_string_tc(int bound); + + /** + * Creates a TypeCode object representing a bounded IDL + * wstring (wide string). + * The TypeCode object is initialized with the given bound, + * which represents the maximum length of the wide string. Zero indicates + * that the string described by this type code is unbounded. + * + * @param bound the bound for the wstring; cannot be negative + * @return a newly-created TypeCode object describing + * a bounded IDL wstring + * @exception BAD_PARAM if bound is a negative value + */ + abstract public TypeCode create_wstring_tc(int bound); + + /** + * Creates a TypeCode object representing an IDL sequence. + * The TypeCode object is initialized with the given bound and + * element type. + * + * @param bound the bound for the sequence, 0 if unbounded + * @param element_type + * the TypeCode object describing the elements + * contained in the sequence + * @return a newly-created TypeCode object describing + * an IDL sequence + */ + abstract public TypeCode create_sequence_tc(int bound, TypeCode element_type); + + /** + * Creates a TypeCode object representing a + * a recursive IDL sequence. + *

    + * For the IDL struct Node in following code fragment, + * the offset parameter for creating its sequence would be 1: + *

    +     *    Struct Node {
    +     *        long value;
    +     *        Sequence <Node> subnodes;
    +     *    };
    +     * 
    + * + * @param bound the bound for the sequence, 0 if unbounded + * @param offset the index to the enclosing TypeCode object + * that describes the elements of this sequence + * @return a newly-created TypeCode object describing + * a recursive sequence + * @deprecated Use a combination of create_recursive_tc and create_sequence_tc instead + * @see #create_recursive_tc(String) create_recursive_tc + * @see #create_sequence_tc(int, TypeCode) create_sequence_tc + */ + // @Deprecated + abstract public TypeCode create_recursive_sequence_tc(int bound, int offset); + + /** + * Creates a TypeCode object representing an IDL array. + * The TypeCode object is initialized with the given length and + * element type. + * + * @param length the length of the array + * @param element_type a TypeCode object describing the type + * of element contained in the array + * @return a newly-created TypeCode object describing + * an IDL array + */ + abstract public TypeCode create_array_tc(int length, TypeCode element_type); + + /** + * Create a TypeCode object for an IDL native type. + * + * @param id the logical id for the native type. + * @param name the name of the native type. + * @return the requested TypeCode. + */ + public org.omg.CORBA.TypeCode create_native_tc(String id, + String name) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Create a TypeCode object for an IDL abstract interface. + * + * @param id the logical id for the abstract interface type. + * @param name the name of the abstract interface type. + * @return the requested TypeCode. + */ + public org.omg.CORBA.TypeCode create_abstract_interface_tc( + String id, + String name) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * Create a TypeCode object for an IDL fixed type. + * + * @param digits specifies the total number of decimal digits in the number + * and must be from 1 to 31 inclusive. + * @param scale specifies the position of the decimal point. + * @return the requested TypeCode. + */ + public org.omg.CORBA.TypeCode create_fixed_tc(short digits, short scale) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + // orbos 98-01-18: Objects By Value -- begin + + + /** + * Create a TypeCode object for an IDL value type. + * The concrete_base parameter is the TypeCode for the immediate + * concrete valuetype base of the valuetype for which the TypeCode + * is being created. + * It may be null if the valuetype does not have a concrete base. + * + * @param id the logical id for the value type. + * @param name the name of the value type. + * @param type_modifier one of the value type modifier constants: + * VM_NONE, VM_CUSTOM, VM_ABSTRACT or VM_TRUNCATABLE + * @param concrete_base a TypeCode object + * describing the concrete valuetype base + * @param members an array containing the members of the value type + * @return the requested TypeCode + */ + public org.omg.CORBA.TypeCode create_value_tc(String id, + String name, + short type_modifier, + TypeCode concrete_base, + ValueMember[] members) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Create a recursive TypeCode object which + * serves as a placeholder for a concrete TypeCode during the process of creating + * TypeCodes which contain recursion. The id parameter specifies the repository id of + * the type for which the recursive TypeCode is serving as a placeholder. Once the + * recursive TypeCode has been properly embedded in the enclosing TypeCode which + * corresponds to the specified repository id, it will function as a normal TypeCode. + * Invoking operations on the recursive TypeCode before it has been embedded in the + * enclosing TypeCode will result in a BAD_TYPECODE exception. + *

    + * For example, the following IDL type declaration contains recursion: + *

    +     *    Struct Node {
    +     *        Sequence<Node> subnodes;
    +     *    };
    +     * 
    + *

    + * To create a TypeCode for struct Node, you would invoke the TypeCode creation + * operations as shown below: + *

    +     * String nodeID = "IDL:Node:1.0";
    +     * TypeCode recursiveSeqTC = orb.create_sequence_tc(0, orb.create_recursive_tc(nodeID));
    +     * StructMember[] members = { new StructMember("subnodes", recursiveSeqTC, null) };
    +     * TypeCode structNodeTC = orb.create_struct_tc(nodeID, "Node", members);
    +     * 
    + *

    + * Also note that the following is an illegal IDL type declaration: + *

    +     *    Struct Node {
    +     *        Node next;
    +     *    };
    +     * 
    + *

    + * Recursive types can only appear within sequences which can be empty. + * That way marshaling problems, when transmitting the struct in an Any, are avoided. + *

    + * @param id the logical id of the referenced type + * @return the requested TypeCode + */ + public org.omg.CORBA.TypeCode create_recursive_tc(String id) { + // implemented in subclass + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Creates a TypeCode object for an IDL value box. + * + * @param id the logical id for the value type + * @param name the name of the value type + * @param boxed_type the TypeCode for the type + * @return the requested TypeCode + */ + public org.omg.CORBA.TypeCode create_value_box_tc(String id, + String name, + TypeCode boxed_type) + { + // implemented in subclass + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + // orbos 98-01-18: Objects By Value -- end + + /** + * Creates an IDL Any object initialized to + * contain a Typecode object whose kind field + * is set to TCKind.tc_null. + * + * @return a newly-created Any object + */ + abstract public Any create_any(); + + + + + /** + * Retrieves a Current object. + * The Current interface is used to manage thread-specific + * information for use by services such as transactions and security. + * + * @see CORBA package + * comments for unimplemented features + * + * @return a newly-created Current object + * @deprecated use resolve_initial_references. + */ + // @Deprecated + public org.omg.CORBA.Current get_current() + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * This operation blocks the current thread until the ORB has + * completed the shutdown process, initiated when some thread calls + * shutdown. It may be used by multiple threads which + * get all notified when the ORB shuts down. + * + */ + public void run() + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Instructs the ORB to shut down, which causes all + * object adapters to shut down, in preparation for destruction.
    + * If the wait_for_completion parameter + * is true, this operation blocks until all ORB processing (including + * processing of currently executing requests, object deactivation, + * and other object adapter operations) has completed. + * If an application does this in a thread that is currently servicing + * an invocation, the BAD_INV_ORDER system exception + * will be thrown with the OMG minor code 3, + * since blocking would result in a deadlock.
    + * If the wait_for_completion parameter is FALSE, + * then shutdown may not have completed upon return.

    + * While the ORB is in the process of shutting down, the ORB operates as normal, + * servicing incoming and outgoing requests until all requests have been completed. + * Once an ORB has shutdown, only object reference management operations + * may be invoked on the ORB or any object reference obtained from it. + * An application may also invoke the destroy operation on the ORB itself. + * Invoking any other operation will throw the BAD_INV_ORDER + * system exception with the OMG minor code 4.

    + * The ORB.run method will return after + * shutdown has been called. + * + * @param wait_for_completion true if the call + * should block until the shutdown is complete; + * false if it should return immediately + * @throws org.omg.CORBA.BAD_INV_ORDER if the current thread is servicing + * an invocation + */ + public void shutdown(boolean wait_for_completion) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Returns true if the ORB needs the main thread to + * perform some work, and false if the ORB does not + * need the main thread. + * + * @return true if there is work pending, meaning that the ORB + * needs the main thread to perform some work; false + * if there is no work pending and thus the ORB does not need the + * main thread + * + */ + public boolean work_pending() + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Performs an implementation-dependent unit of work if called + * by the main thread. Otherwise it does nothing. + * The methods work_pending and perform_work + * can be used in + * conjunction to implement a simple polling loop that multiplexes + * the main thread among the ORB and other activities. + * + */ + public void perform_work() + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Used to obtain information about CORBA facilities and services + * that are supported by this ORB. The service type for which + * information is being requested is passed in as the in + * parameter service_type, the values defined by + * constants in the CORBA module. If service information is + * available for that type, that is returned in the out parameter + * service_info, and the operation returns the + * value true. If no information for the requested + * services type is available, the operation returns false + * (i.e., the service is not supported by this ORB). + *

    + * @param service_type a short indicating the + * service type for which information is being requested + * @param service_info a ServiceInformationHolder object + * that will hold the ServiceInformation object + * produced by this method + * @return true if service information is available + * for the service_type; + * false if no information for the + * requested services type is available + * @see CORBA package + * comments for unimplemented features + */ + public boolean get_service_information(short service_type, + ServiceInformationHolder service_info) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + // orbos 98-01-18: Objects By Value -- begin + + /** + * Creates a new DynAny object from the given + * Any object. + *

    + * @param value the Any object from which to create a new + * DynAny object + * @return the new DynAny object created from the given + * Any object + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynAny create_dyn_any(org.omg.CORBA.Any value) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Creates a basic DynAny object from the given + * TypeCode object. + *

    + * @param type the TypeCode object from which to create a new + * DynAny object + * @return the new DynAny object created from the given + * TypeCode object + * @throws org.omg.CORBA.ORBPackage.InconsistentTypeCode if the given + * TypeCode object is not consistent with the operation. + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynAny create_basic_dyn_any(org.omg.CORBA.TypeCode type) throws org.omg.CORBA.ORBPackage.InconsistentTypeCode + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Creates a new DynStruct object from the given + * TypeCode object. + *

    + * @param type the TypeCode object from which to create a new + * DynStruct object + * @return the new DynStruct object created from the given + * TypeCode object + * @throws org.omg.CORBA.ORBPackage.InconsistentTypeCode if the given + * TypeCode object is not consistent with the operation. + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynStruct create_dyn_struct(org.omg.CORBA.TypeCode type) throws org.omg.CORBA.ORBPackage.InconsistentTypeCode + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Creates a new DynSequence object from the given + * TypeCode object. + *

    + * @param type the TypeCode object from which to create a new + * DynSequence object + * @return the new DynSequence object created from the given + * TypeCode object + * @throws org.omg.CORBA.ORBPackage.InconsistentTypeCode if the given + * TypeCode object is not consistent with the operation. + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynSequence create_dyn_sequence(org.omg.CORBA.TypeCode type) throws org.omg.CORBA.ORBPackage.InconsistentTypeCode + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * Creates a new DynArray object from the given + * TypeCode object. + *

    + * @param type the TypeCode object from which to create a new + * DynArray object + * @return the new DynArray object created from the given + * TypeCode object + * @throws org.omg.CORBA.ORBPackage.InconsistentTypeCode if the given + * TypeCode object is not consistent with the operation. + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynArray create_dyn_array(org.omg.CORBA.TypeCode type) throws org.omg.CORBA.ORBPackage.InconsistentTypeCode + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Creates a new DynUnion object from the given + * TypeCode object. + *

    + * @param type the TypeCode object from which to create a new + * DynUnion object + * @return the new DynUnion object created from the given + * TypeCode object + * @throws org.omg.CORBA.ORBPackage.InconsistentTypeCode if the given + * TypeCode object is not consistent with the operation. + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynUnion create_dyn_union(org.omg.CORBA.TypeCode type) throws org.omg.CORBA.ORBPackage.InconsistentTypeCode + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Creates a new DynEnum object from the given + * TypeCode object. + *

    + * @param type the TypeCode object from which to create a new + * DynEnum object + * @return the new DynEnum object created from the given + * TypeCode object + * @throws org.omg.CORBA.ORBPackage.InconsistentTypeCode if the given + * TypeCode object is not consistent with the operation. + * @see CORBA package + * comments for unimplemented features + * @deprecated Use the new DynAnyFactory API instead + */ + // @Deprecated + public org.omg.CORBA.DynEnum create_dyn_enum(org.omg.CORBA.TypeCode type) throws org.omg.CORBA.ORBPackage.InconsistentTypeCode + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Can be invoked to create new instances of policy objects + * of a specific type with specified initial state. If + * create_policy fails to instantiate a new Policy + * object due to its inability to interpret the requested type + * and content of the policy, it raises the PolicyError + * exception with the appropriate reason. + * @param type the PolicyType of the policy object to + * be created + * @param val the value that will be used to set the initial + * state of the Policy object that is created + * @return Reference to a newly created Policy object + * of type specified by the type parameter and + * initialized to a state specified by the val + * parameter + * @throws org.omg.CORBA.PolicyError when the requested + * policy is not supported or a requested initial state + * for the policy is not supported. + */ + public org.omg.CORBA.Policy create_policy(int type, org.omg.CORBA.Any val) + throws org.omg.CORBA.PolicyError + { + // Currently not implemented until PIORB. + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + private final static void checkPackageAccess(String name) { + SecurityManager s = System.getSecurityManager(); + if (s == null) return; + + String cname = name.replace('/', '.'); + if (cname.startsWith("[")) { + int b = cname.lastIndexOf('[') + 2; + if (b > 1 && b < cname.length()) { + cname = cname.substring(b); + } + } + int i = cname.lastIndexOf('.'); + if (i != -1) { + s.checkPackageAccess(cname.substring(0, i)); + } + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ORBPackage/InconsistentTypeCode.java b/omgapi/src/main/java/org/omg/CORBA/ORBPackage/InconsistentTypeCode.java new file mode 100644 index 000000000..76a8e7f7b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ORBPackage/InconsistentTypeCode.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.ORBPackage; + +/** + * InconsistentTypeCode is thrown when an attempt is made to create a + * dynamic any with a type code that does not match the particular + * subclass of DynAny. + */ +// @SuppressWarnings({"serial"}) +public final class InconsistentTypeCode + extends org.omg.CORBA.UserException { + /** + * Constructs an InconsistentTypeCode user exception + * with no reason message. + */ + public InconsistentTypeCode() { + super(); + } + + /** + * Constructs an InconsistentTypeCode user exception + * with the specified reason message. + * @param reason The String containing a reason message + */ + public InconsistentTypeCode(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ORBPackage/InvalidName.java b/omgapi/src/main/java/org/omg/CORBA/ORBPackage/InvalidName.java new file mode 100644 index 000000000..3aabe8cdf --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ORBPackage/InvalidName.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.ORBPackage; + +/** + * The InvalidName exception is raised when + * ORB.resolve_initial_references is passed a name + * for which there is no initial reference. + * + * @see org.omg.CORBA.ORB#resolve_initial_references(String) + * @version 1.6, 03/18/98 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +final public class InvalidName extends org.omg.CORBA.UserException { + /** + * Constructs an InvalidName exception with no reason message. + */ + public InvalidName() { + super(); + } + + /** + * Constructs an InvalidName exception with the specified + * reason message. + * @param reason the String containing a reason message + */ + public InvalidName(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ORBPackage/package.html b/omgapi/src/main/java/org/omg/CORBA/ORBPackage/package.html new file mode 100644 index 000000000..fe58eaae8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ORBPackage/package.html @@ -0,0 +1,38 @@ + + + + + + + + +Provides the exception InvalidName, which is thrown +by the method ORB.resolve_initial_references +and the exception InconsistentTypeCode, which is thrown +by the Dynamic Any creation methods in the ORB class. + + +

    Related Documentation

    + +For an overview, please see: + + + +@since JDK1.2 +@serial exclude + + diff --git a/omgapi/src/main/java/org/omg/CORBA/Object.java b/omgapi/src/main/java/org/omg/CORBA/Object.java new file mode 100644 index 000000000..2b897ae76 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Object.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The definition for a CORBA object reference. + *

    + * A CORBA object reference is a handle for a particular + * CORBA object implemented by a server. A CORBA object reference + * identifies the same CORBA object each time the reference is used to invoke + * a method on the object. + * A CORBA object may have multiple, distinct object references. + *

    + * The org.omg.CORBA.Object interface is the root of + * the inheritance hierarchy for all CORBA object references in the Java + * programming language, analogous to java.rmi.Remote + * for RMI remote objects. + *

    + * A CORBA object may be either local or remote. + * If it is a local object (that is, running in the same + * VM as the client), invocations may be directly serviced by + * the object instance, and the object reference could point to the actual + * instance of the object implementation class. + * If a CORBA object is a remote object (that is, running in a different + * VM from the client), the object reference points to a stub (proxy) which uses the + * ORB machinery to make a remote invocation on the server where the object + * implementation resides. + *

    + * Default implementations of the methods in the interface + * org.omg.CORBA.Object + * are provided in the class org.omg.CORBA.portable.ObjectImpl, + * which is the base class for stubs and object implementations. + *

    + * @see org.omg.CORBA.portable.ObjectImpl + */ + +public interface Object { + + /** + * Checks whether this object is an instance of a class that + * implements the given interface. + * + * @param repositoryIdentifier the interface to check against + * @return true if this object reference is an instance + * of a class that implements the interface; + * false otherwise + */ + boolean _is_a(String repositoryIdentifier); + + + /** + * Determines whether the two object references are equivalent, + * so far as the ORB can easily determine. Two object references are equivalent + * if they are identical. Two distinct object references which in fact refer to + * the same object are also equivalent. However, ORBs are not required + * to attempt determination of whether two distinct object references + * refer to the same object, since such determination could be impractically + * expensive. + * @param other the other object reference with which to check for equivalence + * @return true if this object reference is known to be + * equivalent to the given object reference. + * Note that false indicates only that the two + * object references are distinct, not necessarily that + * they reference distinct objects. + */ + boolean _is_equivalent(org.omg.CORBA.Object other); + + + /** + * Determines whether the server object for this object reference has been + * destroyed. + * @return true if the ORB knows authoritatively that the + * server object does not exist; false otherwise + */ + boolean _non_existent(); + + + /** + * Returns an ORB-internal identifier for this object reference. + * This is a hash identifier, which does + * not change during the lifetime of the object reference, and so + * neither will any hash function of that identifier change. The value returned + * is not guaranteed to be unique; in other words, another object + * reference may have the same hash value. + * If two object references hash differently, + * then they are distinct object references; however, both may still refer + * to the same CORBA object. + * + * @param maximum the upper bound on the hash value returned by the ORB + * @return the ORB-internal hash identifier for this object reference + */ + int _hash(int maximum); + + + /** + * Returns a duplicate of this CORBA object reference. + * The server object implementation is not involved in creating + * the duplicate, and the implementation cannot distinguish whether + * the original object reference or a duplicate was used to make a request. + *

    + * Note that this method is not very useful in the Java platform, + * since memory management is handled by the VM. + * It is included for compliance with the CORBA APIs. + *

    + * The method _duplicate may return this object reference itself. + * + * @return a duplicate of this object reference or this object reference + * itself + */ + org.omg.CORBA.Object _duplicate(); + + + /** + * Signals that the caller is done using this object reference, so + * internal ORB resources associated with this object reference can be + * released. Note that the object implementation is not involved in + * this operation, and other references to the same object are not affected. + */ + void _release(); + + + /** + * Obtains an InterfaceDef for the object implementation + * referenced by this object reference. + * The InterfaceDef object + * may be used to introspect on the methods, attributes, and other + * type information for the object referred to by this object reference. + * + * @return the InterfaceDef object in the Interface Repository + * which provides type information about the object referred to by + * this object reference + */ + org.omg.CORBA.Object _get_interface_def(); + + + + /** + * Creates a Request instance for use in the + * Dynamic Invocation Interface. + * + * @param operation the name of the method to be invoked using the + * Request instance + * @return the newly-created Request instance + */ + Request _request(String operation); + + + + /** + * Creates a Request instance initialized with the + * given context, method name, list of arguments, and container + * for the method's return value. + * + * @param ctx a Context object containing + * a list of properties + * @param operation the name of the method to be invoked + * @param arg_list an NVList containing the actual arguments + * to the method being invoked + * @param result a NamedValue object to serve as a + * container for the method's return value + * @return the newly-created Request object + * + * @see Request + * @see NVList + * @see NamedValue + */ + + Request _create_request(Context ctx, + String operation, + NVList arg_list, + NamedValue result); + + /** + * Creates a Request instance initialized with the + * given context, method name, list of arguments, container + * for the method's return value, list of possible exceptions, + * and list of context strings needing to be resolved. + * + * @param ctx a Context object containing + * a list of properties + * @param operation the name of the method to be invoked + * @param arg_list an NVList containing the actual arguments + * to the method being invoked + * @param result a NamedValue object to serve as a + * container for the method's return value + * @param exclist an ExceptionList object containing a + * list of possible exceptions the method can throw + * @param ctxlist a ContextList object containing a list of + * context strings that need to be resolved and sent with the + * Request instance + * @return the newly-created Request object + * + * @see Request + * @see NVList + * @see NamedValue + * @see ExceptionList + * @see ContextList + */ + + Request _create_request(Context ctx, + String operation, + NVList arg_list, + NamedValue result, + ExceptionList exclist, + ContextList ctxlist); + + + + + /** + * Returns the Policy object of the specified type + * which applies to this object. + * + * @param policy_type the type of policy to be obtained + * @return A Policy object of the type specified by + * the policy_type parameter + * @exception org.omg.CORBA.BAD_PARAM when the value of policy type + * is not valid either because the specified type is not supported by this + * ORB or because a policy object of that type is not associated with this + * Object + */ + Policy _get_policy(int policy_type); + + + /** + * Retrieves the DomainManagers of this object. + * This allows administration services (and applications) to retrieve the + * domain managers, and hence the security and other policies applicable + * to individual objects that are members of the domain. + * + * @return the list of immediately enclosing domain managers of this object. + * At least one domain manager is always returned in the list since by + * default each object is associated with at least one domain manager at + * creation. + */ + DomainManager[] _get_domain_managers(); + + + /** + * Returns a new Object with the given policies + * either replacing any existing policies in this + * Object or with the given policies added + * to the existing ones, depending on the value of the + * given SetOverrideType object. + * + * @param policies an array of Policy objects containing + * the policies to be added or to be used as replacements + * @param set_add either SetOverrideType.SET_OVERRIDE, indicating + * that the given policies will replace any existing ones, or + * SetOverrideType.ADD_OVERRIDE, indicating that + * the given policies should be added to any existing ones + * @return a new Object with the given policies replacing + * or added to those in this Object + */ + org.omg.CORBA.Object _set_policy_override(Policy[] policies, + SetOverrideType set_add); + + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ObjectHelper.java b/omgapi/src/main/java/org/omg/CORBA/ObjectHelper.java new file mode 100644 index 000000000..e6e13842c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ObjectHelper.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** +* The Helper for Object. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +*/ + +package org.omg.CORBA; + +abstract public class ObjectHelper +{ + private static String _id = ""; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Object that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Object extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (TCKind.tk_objref); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Object read (org.omg.CORBA.portable.InputStream istream) + { + return istream.read_Object (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Object value) + { + ostream.write_Object (value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ObjectHolder.java b/omgapi/src/main/java/org/omg/CORBA/ObjectHolder.java new file mode 100644 index 000000000..e83171e0c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ObjectHolder.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + + +/** + * The Holder for Object. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a CORBA object reference (a value of type + * org.omg.CORBA.Object). It is usually + * used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has a CORBA Object reference as an "out" + * or "inout" parameter, the programmer must pass an instance of + * ObjectHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myObjectHolder is an instance of ObjectHolder, + * the value stored in its value field can be accessed with + * myObjectHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class ObjectHolder implements Streamable { + /** + * The Object value held by this ObjectHolder + * object. + */ + public Object value; + + /** + * Constructs a new ObjectHolder object with its + * value field initialized to null. + */ + public ObjectHolder() { + } + + /** + * Constructs a new ObjectHolder object with its + * value field initialized to the given + * Object. + * @param initial the Object with which to initialize + * the value field of the newly-created + * ObjectHolder object + */ + public ObjectHolder(Object initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in + * this ObjectHolder object + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire. + */ + public void _read(InputStream input) { + value = input.read_Object(); + } + + /** + * Marshals to output the value in + * this ObjectHolder object. + * + * @param output the OutputStream which will contain the CDR formatted data. + */ + public void _write(OutputStream output) { + output.write_Object(value); + } + + /** + * Returns the TypeCode corresponding to the value held in + * this ObjectHolder object + * + * @return the TypeCode of the value held in + * this ObjectHolder object + */ + public org.omg.CORBA.TypeCode _type() { + return org.omg.CORBA.ORB.init().get_primitive_tc(TCKind.tk_objref); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PERSIST_STORE.java b/omgapi/src/main/java/org/omg/CORBA/PERSIST_STORE.java new file mode 100644 index 000000000..0d6f270a9 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PERSIST_STORE.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception indicates a persistent storage failure, for example, + * failure to establish a database connection or corruption of a + * database.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.16 09/09/97 + */ + +public final class PERSIST_STORE extends SystemException { + /** + * Constructs a PERSIST_STORE exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public PERSIST_STORE() { + this(""); + } + + /** + * Constructs a PERSIST_STORE exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public PERSIST_STORE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a PERSIST_STORE exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public PERSIST_STORE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a PERSIST_STORE exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public PERSIST_STORE(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PRIVATE_MEMBER.java b/omgapi/src/main/java/org/omg/CORBA/PRIVATE_MEMBER.java new file mode 100644 index 000000000..663870059 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PRIVATE_MEMBER.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/PRIVATE_MEMBER.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; + +/** + * Constant to define a private member in the ValueMember class. + *

    + * PRIVATE_MEMBER is one of the two constants of typedef + * Visibility used in the interface repository + * to identify visibility of a ValueMember type. + * The other constant is PUBLIC_MEMBER. + * + * @author unattributed + * @version 1.20 07/27/07 + */ +public interface PRIVATE_MEMBER { + final short value = (short) (0L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/PUBLIC_MEMBER.java b/omgapi/src/main/java/org/omg/CORBA/PUBLIC_MEMBER.java new file mode 100644 index 000000000..f1f4f4e96 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PUBLIC_MEMBER.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/PUBLIC_MEMBER.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; + +/** + * Constant to define a public member in the ValueMember + * class. + *

    + * PUBLIC_MEMBER is one of the two constants of typedef + * Visibility used in the interface repository + * to identify visibility of a ValueMember type. + * The other constant is PRIVATE_MEMBER. + * + * @author unattributed + * @version 1.20 07/27/07 + */ +public interface PUBLIC_MEMBER { + final short value = (short) (1L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/Policy.java b/omgapi/src/main/java/org/omg/CORBA/Policy.java new file mode 100644 index 000000000..73ea7f5df --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Policy.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* Interfaces derived from the Policy interface allow an +* ORB or CORBA service access to certain choices that affect +* its operation. This information is accessed in a structured +* manner using interfaces derived from the Policy +* interface defined in the CORBA module. A CORBA service does not +* have to use this method of accessing operating options, but +* may choose to do so. The Security Service in particular uses +* this technique for associating Security Policy with objects +* in the system. +* An interface generated by the IDL-to-Java compiler. +* org/omg/CORBA/Policy.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:20 AM PDT +*/ + +public interface Policy extends PolicyOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} // interface Policy diff --git a/omgapi/src/main/java/org/omg/CORBA/PolicyHelper.java b/omgapi/src/main/java/org/omg/CORBA/PolicyHelper.java new file mode 100644 index 000000000..f312181fd --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PolicyHelper.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for Policy. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/PolicyHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:20 AM PDT +*/ + +abstract public class PolicyHelper +{ + private static String _id = "IDL:omg.org/CORBA/Policy:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Policy that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Policy extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.CORBA.PolicyHelper.id (), "Policy"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Policy read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_PolicyStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Policy value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.omg.CORBA.Policy narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.CORBA.Policy) + return (org.omg.CORBA.Policy)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + return new org.omg.CORBA._PolicyStub (delegate); + } + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PolicyHolder.java b/omgapi/src/main/java/org/omg/CORBA/PolicyHolder.java new file mode 100644 index 000000000..6a706b96d --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PolicyHolder.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The Holder for Policy. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/PolicyHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:20 AM PDT +*/ + +public final class PolicyHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Policy value = null; + + public PolicyHolder () + { + } + + public PolicyHolder (org.omg.CORBA.Policy initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.PolicyHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.PolicyHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.PolicyHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PolicyListHelper.java b/omgapi/src/main/java/org/omg/CORBA/PolicyListHelper.java new file mode 100644 index 000000000..7ade26395 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PolicyListHelper.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for PolicyList. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/PolicyListHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:21 AM PDT +*/ + +abstract public class PolicyListHelper +{ + private static String _id = "IDL:omg.org/CORBA/PolicyList:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Policy[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Policy[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.PolicyHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.PolicyListHelper.id (), "PolicyList", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Policy[] read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.Policy value[] = null; + int _len0 = istream.read_long (); + value = new org.omg.CORBA.Policy[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = org.omg.CORBA.PolicyHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Policy[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + org.omg.CORBA.PolicyHelper.write (ostream, value[_i0]); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PolicyListHolder.java b/omgapi/src/main/java/org/omg/CORBA/PolicyListHolder.java new file mode 100644 index 000000000..1b82dabb9 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PolicyListHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for PolicyList. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/PolicyListHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:21 AM PDT +*/ + +public final class PolicyListHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.Policy value[] = null; + + public PolicyListHolder () + { + } + + public PolicyListHolder (org.omg.CORBA.Policy[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.PolicyListHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.PolicyListHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.PolicyListHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PolicyOperations.java b/omgapi/src/main/java/org/omg/CORBA/PolicyOperations.java new file mode 100644 index 000000000..456de69f4 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PolicyOperations.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The interface for Policy. For more information on +* Operations interfaces, see +* "Generated Files: Operations files". +*

    +* org/omg/CORBA/PolicyOperations.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:20 AM PDT +*/ + +/** + * Provides the operations for a Policy object. + */ +public interface PolicyOperations +{ + + /** + * Returns the constant value that corresponds to the + * type of the policy object. The values of + * the policy objects are allocated by the OMG. + * New values for PolicyType should be obtained from the OMG by + * sending mail to request@omg.org. In general the constant + * values that are allocated are defined in conjunction with + * the definition of the corresponding policy object. + * + * @return the constant value that corresponds to the type of + * the policy object + */ + int policy_type (); + + /** + * Returns a copy of the Policy object. The copy does not retain + * any relationships that the policy had with any domain or object. + * + * @return a copy of the Policy object + */ + org.omg.CORBA.Policy copy (); + + /** + * Destroys the Policy object. It is the responsibility of + * the Policy object to determine whether it can be destroyed. + */ + void destroy (); +} // interface PolicyOperations diff --git a/omgapi/src/main/java/org/omg/CORBA/PolicyTypeHelper.java b/omgapi/src/main/java/org/omg/CORBA/PolicyTypeHelper.java new file mode 100644 index 000000000..d6a0d4a49 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PolicyTypeHelper.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for PolicyType. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/PolicyTypeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl +* Saturday, July 17, 1999 12:26:20 AM PDT +*/ + + +// basic Policy definition +abstract public class PolicyTypeHelper +{ + private static String _id = "IDL:omg.org/CORBA/PolicyType:1.0"; + + public static void insert (org.omg.CORBA.Any a, int that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static int extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ulong); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.PolicyTypeHelper.id (), "PolicyType", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static int read (org.omg.CORBA.portable.InputStream istream) + { + int value = (int)0; + value = istream.read_ulong (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, int value) + { + ostream.write_ulong (value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/Principal.java b/omgapi/src/main/java/org/omg/CORBA/Principal.java new file mode 100644 index 000000000..618191d59 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Principal.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** + * A class that contains information about the identity of + * the client, for access control + * and other purposes. It contains a single attribute, the name of the + * Principal, encoded as a sequence of bytes. + *

    + * @deprecated Deprecated by CORBA 2.2. + */ + +// @Deprecated +public class Principal { + /** + * Sets the name of this Principal object to the given value. + * @param value the value to be set in the Principal + * @deprecated Deprecated by CORBA 2.2. + */ + // @Deprecated + public void name(byte[] value) { + throw new org.omg.CORBA.NO_IMPLEMENT() ; + } + + /** + * Gets the name of this Principal object. + * @return the name of this Principal object + * @deprecated Deprecated by CORBA 2.2. + */ + // @Deprecated + public byte[] name() { + throw new org.omg.CORBA.NO_IMPLEMENT() ; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/PrincipalHolder.java b/omgapi/src/main/java/org/omg/CORBA/PrincipalHolder.java new file mode 100644 index 000000000..f0b19407d --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/PrincipalHolder.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + + +/** + * The Holder for Principal. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A container class for values of type Principal + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL Principal as an "out" + * or "inout" parameter, the programmer must pass an instance of + * PrincipalHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myPrincipalHolder is an instance of PrincipalHolder, + * the value stored in its value field can be accessed with + * myPrincipalHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + * @deprecated Deprecated by CORBA 2.2. + */ +// @Deprecated +public final class PrincipalHolder implements Streamable { + /** + * The Principal value held by this PrincipalHolder + * object. + */ + public Principal value; + + /** + * Constructs a new PrincipalHolder object with its + * value field initialized to null. + */ + public PrincipalHolder() { + } + + /** + * Constructs a new PrincipalHolder object with its + * value field initialized to the given + * Principal object. + * @param initial the Principal with which to initialize + * the value field of the newly-created + * PrincipalHolder object + */ + // @SuppressWarnings({"deprecation"}) + public PrincipalHolder(Principal initial) { + value = initial; + } + + public void _read(InputStream input) { + value = input.read_Principal(); + } + + public void _write(OutputStream output) { + output.write_Principal(value); + } + + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_Principal); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/REBIND.java b/omgapi/src/main/java/org/omg/CORBA/REBIND.java new file mode 100644 index 000000000..66448b9ee --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/REBIND.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * REBIND is raised when the current effective RebindPolicy, + * has a value of NO_REBIND or NO_RECONNECT and an invocation on a bound + * object reference results in a LocateReply message with status + * OBJECT_FORWARD or a Reply message with status LOCATION_FORWARD. + * This exception is also raised if the current effective RebindPolicy has + * a value of NO_RECONNECT and a connection must be reopened. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class REBIND extends SystemException { + + /** + * Constructs an REBIND exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public REBIND() { + this(""); + } + + /** + * Constructs an REBIND exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public REBIND(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an REBIND exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public REBIND(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an REBIND exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public REBIND(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/Request.java b/omgapi/src/main/java/org/omg/CORBA/Request.java new file mode 100644 index 000000000..b1ffd8b2b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/Request.java @@ -0,0 +1,287 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object containing the information necessary for + * invoking a method. This class is + * the cornerstone of the ORB Dynamic + * Invocation Interface (DII), which allows dynamic creation and + * invocation of requests. + * A server cannot tell the difference between a client + * invocation using a client stub and a request using the DII. + *

    + * A Request object consists of: + *

      + *
    • the name of the operation to be invoked + *
    • an NVList containing arguments for the operation.
      + * Each item in the list is a NamedValue object, which has three + * parts: + *
        + *
      1. the name of the argument + *
      2. the value of the argument (as an Any object) + *
      3. the argument mode flag indicating whether the argument is + * for input, output, or both + *
      + *
    + *

    + * Request objects may also contain additional information, + * depending on how an operation was defined in the original IDL + * interface definition. For example, where appropriate, they may contain + * a NamedValue object to hold the return value or exception, + * a context, a list of possible exceptions, and a list of + * context strings that need to be resolved. + *

    + * New Request objects are created using one of the + * create_request methods in the Object class. + * In other words, a create_request method is performed on the + * object which is to be invoked. + * + * @see org.omg.CORBA.NamedValue + * + * @version 1.13 09/09/97 + */ + +public abstract class Request { + + /** + * Retrieves the the target object reference. + * + * @return the object reference that points to the + * object implementation for the method + * to be invoked + */ + + public abstract org.omg.CORBA.Object target(); + + /** + * Retrieves the name of the method to be invoked. + * + * @return the name of the method to be invoked + */ + + public abstract String operation(); + + /** + * Retrieves the NVList object containing the arguments + * to the method being invoked. The elements in the list are + * NamedValue objects, with each one describing an argument + * to the method. + * + * @return the NVList object containing the arguments + * for the method + * + */ + + public abstract NVList arguments(); + + /** + * Retrieves the NamedValue object containing the return + * value for the method. + * + * @return the NamedValue object containing the result + * of the method + */ + + public abstract NamedValue result(); + + /** + * Retrieves the Environment object for this request. + * It contains the exception that the method being invoked has + * thrown (after the invocation returns). + * + * + * @return the Environment object for this request + */ + + public abstract Environment env(); + + /** + * Retrieves the ExceptionList object for this request. + * This list contains TypeCode objects describing the + * exceptions that may be thrown by the method being invoked. + * + * @return the ExceptionList object describing the exceptions + * that may be thrown by the method being invoked + */ + + public abstract ExceptionList exceptions(); + + /** + * Retrieves the ContextList object for this request. + * This list contains context Strings that need to + * be resolved and sent with the invocation. + * + * + * @return the list of context strings whose values + * need to be resolved and sent with the + * invocation. + */ + + public abstract ContextList contexts(); + + /** + * Retrieves the Context object for this request. + * This is a list of properties giving information about the + * client, the environment, or the circumstances of this request. + * + * @return the Context object that is to be used + * to resolve any context strings whose + * values need to be sent with the invocation + */ + + public abstract Context ctx(); + + /** + * Sets this request's Context object to the one given. + * + * @param c the new Context object to be used for + * resolving context strings + */ + + public abstract void ctx(Context c); + + + /** + * Creates an input argument and adds it to this Request + * object. + * + * @return an Any object that contains the + * value and typecode for the input argument added + */ + + public abstract Any add_in_arg(); + + /** + * Creates an input argument with the given name and adds it to + * this Request object. + * + * @param name the name of the argument being added + * @return an Any object that contains the + * value and typecode for the input argument added + */ + + public abstract Any add_named_in_arg(String name); + + /** + * Adds an input/output argument to this Request object. + * + * @return an Any object that contains the + * value and typecode for the input/output argument added + */ + + public abstract Any add_inout_arg(); + + /** + * Adds an input/output argument with the given name to this + * Request object. + * + * @param name the name of the argument being added + * @return an Any object that contains the + * value and typecode for the input/output argument added + */ + + public abstract Any add_named_inout_arg(String name); + + + /** + * Adds an output argument to this Request object. + * + * @return an Any object that contains the + * value and typecode for the output argument added + */ + + public abstract Any add_out_arg(); + + /** + * Adds an output argument with the given name to this + * Request object. + * + * @param name the name of the argument being added + * @return an Any object that contains the + * value and typecode for the output argument added + */ + + public abstract Any add_named_out_arg(String name); + + /** + * Sets the typecode for the return + * value of the method. + * + * @param tc the TypeCode object containing type information + * for the return value + */ + + public abstract void set_return_type(TypeCode tc); + + /** + * Returns the Any object that contains the value for the + * result of the method. + * + * @return an Any object containing the value and + * typecode for the return value + */ + + public abstract Any return_value(); + + /** + * Makes a synchronous invocation using the + * information in the Request object. Exception information is + * placed into the Request object's environment object. + */ + + public abstract void invoke(); + + /** + * Makes a oneway invocation on the + * request. In other words, it does not expect or wait for a + * response. Note that this can be used even if the operation was + * not declared as oneway in the IDL declaration. No response or + * exception information is returned. + */ + + public abstract void send_oneway(); + + /** + * Makes an asynchronous invocation on + * the request. In other words, it does not wait for a response before it + * returns to the user. The user can then later use the methods + * poll_response and get_response to get + * the result or exception information for the invocation. + */ + + public abstract void send_deferred(); + + /** + * Allows the user to determine + * whether a response has been received for the invocation triggered + * earlier with the send_deferred method. + * + * @return true if the method response has + * been received; false otherwise + */ + + public abstract boolean poll_response(); + + /** + * Allows the user to access the + * response for the invocation triggered earlier with the + * send_deferred method. + * + * @exception WrongTransaction if the method get_response was invoked + * from a different transaction's scope than the one from which the + * request was originally sent. See the OMG Transaction Service specification + * for details. + */ + + public abstract void get_response() throws WrongTransaction; + +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/ServerRequest.java b/omgapi/src/main/java/org/omg/CORBA/ServerRequest.java new file mode 100644 index 000000000..8dd69d947 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ServerRequest.java @@ -0,0 +1,296 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object that captures the explicit state of a request + * for the Dynamic Skeleton Interface (DSI). This class, the + * cornerstone of the DSI, is analogous to the Request + * object in the DII. + *

    + * The ORB is responsible for creating this embodiment of a request, + * and delivering it to a Dynamic Implementation Routine (DIR). + * A dynamic servant (a DIR) is created by implementing the + * DynamicImplementation class, + * which has a single invoke method. This method accepts a + * ServerRequest object. + * + * The abstract class ServerRequest defines + * methods for accessing the + * method name, the arguments and the context of the request, as + * well as methods for setting the result of the request either as a + * return value or an exception.

    + * + * A subtlety with accessing the arguments of the request is that the + * DIR needs to provide type information about the + * expected arguments, since there is no compiled information about + * these. This information is provided through an NVList, + * which is a list of NamedValue objects. + * Each NamedValue object + * contains an Any object, which in turn + * has a TypeCode object representing the type + * of the argument.

    + * + * Similarly, type information needs to be provided for the response, + * for either the expected result or for an exception, so the methods + * result and except take an Any + * object as a parameter.

    + * + * @see org.omg.CORBA.DynamicImplementation + * @see org.omg.CORBA.NVList + * @see org.omg.CORBA.NamedValue + * + * @version 1.15 09/09/97 + */ + +public abstract class ServerRequest { + + /** + * Retrieves the name of the operation being + * invoked. According to OMG IDL's rules, these names must be unique + * among all operations supported by this object's "most-derived" + * interface. Note that the operation names for getting and setting + * attributes are _get_<attribute_name> + * and _set_<attribute_name>, + * respectively. + * + * @return the name of the operation to be invoked + * @deprecated use operation() + */ + public String op_name() + { + return operation(); + } + + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception. + *

    + * Retrieves the name of the operation being + * invoked. According to OMG IDL's rules, these names must be unique + * among all operations supported by this object's "most-derived" + * interface. Note that the operation names for getting and setting + * attributes are _get_<attribute_name> + * and _set_<attribute_name>, + * respectively. + * + * @return the name of the operation to be invoked + * @see CORBA + * package comments for unimplemented features + */ + public String operation() + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * Specifies method parameter types and retrieves "in" and "inout" + * argument values. + *

    + * Note that this method is deprecated; use the method + * arguments in its place. + *

    + * Unless it calls the method set_exception, + * the DIR must call this method exactly once, even if the + * method signature contains no parameters. Once the method + * arguments or set_exception + * has been called, calling arguments on the same + * ServerRequest object + * will result in a BAD_INV_ORDER system exception. + * The DIR must pass in to the method arguments + * an NVList initialized with TypeCodes and Flags + * describing the parameter types for the operation, in the order in which + * they appear in the IDL specification (left to right). A + * potentially-different NVList will be returned from + * arguments, with the + * "in" and "inout" argument values supplied. If it does not call + * the method set_exception, + * the DIR must supply the returned NVList with return + * values for any "out" arguments before returning, and may also change + * the return values for any "inout" arguments. + * + * @param params the arguments of the method, in the + * form of an NVList object + * @deprecated use the method arguments + */ + public void params(NVList params) + { + arguments(params); + } + + /** + * Specifies method parameter types and retrieves "in" and "inout" + * argument values. + * Unless it calls the method set_exception, + * the DIR must call this method exactly once, even if the + * method signature contains no parameters. Once the method + * arguments or set_exception + * has been called, calling arguments on the same + * ServerRequest object + * will result in a BAD_INV_ORDER system exception. + * The DIR must pass in to the method arguments + * an NVList initialized with TypeCodes and Flags + * describing the parameter types for the operation, in the order in which + * they appear in the IDL specification (left to right). A + * potentially-different NVList will be returned from + * arguments, with the + * "in" and "inout" argument values supplied. If it does not call + * the method set_exception, + * the DIR must supply the returned NVList with return + * values for any "out" arguments before returning, and it may also change + * the return values for any "inout" arguments. + * + * @param args the arguments of the method, in the + * form of an NVList + * @see CORBA + * package comments for unimplemented features + */ + public void arguments(org.omg.CORBA.NVList args) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + + /** + * Specifies any return value for the call. + *

    + * Note that this method is deprecated; use the method + * set_result in its place. + *

    + * Unless the method + * set_exception is called, if the invoked method + * has a non-void result type, the method set_result + * must be called exactly once before the DIR returns. + * If the operation has a void result type, the method + * set_result may optionally be + * called once with an Any object whose type is + * tk_void. Calling the method set_result before + * the method arguments has been called or after + * the method set_result or set_exception has been + * called will result in a BAD_INV_ORDER exception. Calling the method + * set_result without having previously called + * the method ctx when the IDL operation contains a + * context expression, or when the NVList passed to arguments did not + * describe all parameters passed by the client, may result in a MARSHAL + * system exception. + * + * @param any an Any object containing the return value to be set + * @deprecated use the method set_result + */ + public void result(Any any) + { + set_result(any); + } + + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception. + *

    + * Specifies any return value for the call. Unless the method + * set_exception is called, if the invoked method + * has a non-void result type, the method set_result + * must be called exactly once before the DIR returns. + * If the operation has a void result type, the method + * set_result may optionally be + * called once with an Any object whose type is + * tk_void. Calling the method set_result before + * the method arguments has been called or after + * the method set_result or set_exception has been + * called will result in a BAD_INV_ORDER exception. Calling the method + * set_result without having previously called + * the method ctx when the IDL operation contains a + * context expression, or when the NVList passed to arguments did not + * describe all parameters passed by the client, may result in a MARSHAL + * system exception. + * + * @param any an Any object containing the return value to be set + * @see CORBA + * package comments for unimplemented features + */ + public void set_result(org.omg.CORBA.Any any) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * The DIR may call set_exception at any time to return an exception to the + * client. The Any passed to set_exception must contain either a system + * exception or a user exception specified in the raises expression + * of the invoked operation's IDL definition. Passing in an Any that does + * not + * contain an exception will result in a BAD_PARAM system exception. Passing + * in an unlisted user exception will result in either the DIR receiving a + * BAD_PARAM system exception or in the client receiving an + * UNKNOWN_EXCEPTION system exception. + * + * @param any the Any object containing the exception + * @deprecated use set_exception() + */ + public void except(Any any) + { + set_exception(any); + } + + /** + * Throws an org.omg.CORBA.NO_IMPLEMENT exception. + *

    + * Returns the given exception to the client. This method + * is invoked by the DIR, which may call it at any time. + * The Any object passed to this method must + * contain either a system + * exception or one of the user exceptions specified in the + * invoked operation's IDL definition. Passing in an + * Any object that does not contain an exception + * will cause a BAD_PARAM system exception to be thrown. Passing + * in an unlisted user exception will result in either the DIR receiving a + * BAD_PARAM system exception or in the client receiving an + * UNKNOWN_EXCEPTION system exception. + * + * @param any the Any object containing the exception + * @exception BAD_PARAM if the given Any object does not + * contain an exception or the exception is an + * unlisted user exception + * @exception UNKNOWN_EXCEPTION if the given exception is an unlisted + * user exception and the DIR did not + * receive a BAD_PARAM exception + * @see CORBA + * package comments for unimplemented features + */ + public void set_exception(Any any) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Returns the context information specified in IDL for the operation + * when the operation is not an attribute access and the operation's IDL + * definition contains a context expression; otherwise it returns + * a nil Context reference. Calling the method + * ctx before the method arguments has + * been called or after the method ctx, + * set_result, or set_exception + * has been called will result in a + * BAD_INV_ORDER system exception. + * + * @return the context object that is to be used + * to resolve any context strings whose + * values need to be sent with the invocation. + * @exception BAD_INV_ORDER if (1) the method ctx is called + * before the method arguments or + * (2) the method ctx is called + * after calling set_result or + * set_exception + */ + public abstract Context ctx(); + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ServiceDetail.java b/omgapi/src/main/java/org/omg/CORBA/ServiceDetail.java new file mode 100644 index 000000000..15f018d65 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ServiceDetail.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * An object that represents an ORB service: its service_detail_type + * field contains the type of the ORB service, and its service_detail + * field contains a description of the ORB service. + + * + * @author RIP Team + * @version 1.11 11/15/00 + */ +// @SuppressWarnings({"serial"}) +public final class ServiceDetail implements org.omg.CORBA.portable.IDLEntity +{ + /** + * The type of the ORB service that this ServiceDetail + * object represents. + */ + public int service_detail_type; + + /** + * The data describing the ORB service that this ServiceDetail + * object represents. + */ + public byte[] service_detail; + + /** + * Constructs a ServiceDetail object with 0 for the type of + * ORB service and an empty description. + */ + public ServiceDetail() { } + + /** + * Constructs a ServiceDetail object with the given + * ORB service type and the given description. + * + * @param service_detail_type an int specifying the type of + * ORB service + * @param service_detail a byte array describing the ORB service + */ + public ServiceDetail(int service_detail_type, byte[] service_detail) { + this.service_detail_type = service_detail_type; + this.service_detail = service_detail; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ServiceDetailHelper.java b/omgapi/src/main/java/org/omg/CORBA/ServiceDetailHelper.java new file mode 100644 index 000000000..c087f44c1 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ServiceDetailHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + + /** + * The Helper for ServiceDetail. For more information on + * Helper files, see + * "Generated Files: Helper Files".

    + */ + +package org.omg.CORBA; + + +public abstract class ServiceDetailHelper { + + public static void write(org.omg.CORBA.portable.OutputStream out, org.omg.CORBA.ServiceDetail that) { + out.write_ulong(that.service_detail_type); + { + out.write_long(that.service_detail.length); + out.write_octet_array(that.service_detail, 0, that.service_detail.length); + } + } + public static org.omg.CORBA.ServiceDetail read(org.omg.CORBA.portable.InputStream in) { + org.omg.CORBA.ServiceDetail that = new org.omg.CORBA.ServiceDetail(); + that.service_detail_type = in.read_ulong(); + { + int __length = in.read_long(); + that.service_detail = new byte[__length]; + in.read_octet_array(that.service_detail, 0, that.service_detail.length); + } + return that; + } + public static org.omg.CORBA.ServiceDetail extract(org.omg.CORBA.Any a) { + org.omg.CORBA.portable.InputStream in = a.create_input_stream(); + return read(in); + } + public static void insert(org.omg.CORBA.Any a, org.omg.CORBA.ServiceDetail that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + private static org.omg.CORBA.TypeCode _tc; + synchronized public static org.omg.CORBA.TypeCode type() { + int _memberCount = 2; + org.omg.CORBA.StructMember[] _members = null; + if (_tc == null) { + _members= new org.omg.CORBA.StructMember[2]; + _members[0] = new org.omg.CORBA.StructMember( + "service_detail_type", + org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ulong), + null); + + _members[1] = new org.omg.CORBA.StructMember( + "service_detail", + org.omg.CORBA.ORB.init().create_sequence_tc(0, org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_octet)), + null); + _tc = org.omg.CORBA.ORB.init().create_struct_tc(id(), "ServiceDetail", _members); + } + return _tc; + } + public static String id() { + return "IDL:omg.org/CORBA/ServiceDetail:1.0"; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ServiceInformation.java b/omgapi/src/main/java/org/omg/CORBA/ServiceInformation.java new file mode 100644 index 000000000..d8aa125c1 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ServiceInformation.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** An IDL struct in the CORBA module that + * stores information about a CORBA service available in the + * ORB implementation and is obtained from the ORB.get_service_information + * method. + */ +// @SuppressWarnings({"serial"}) +public final class ServiceInformation implements org.omg.CORBA.portable.IDLEntity +{ + /** Array of ints representing service options. + */ + public int[] service_options; + + /** Array of ServiceDetails giving more details about the service. + */ + public org.omg.CORBA.ServiceDetail[] service_details; + + /** Constructs a ServiceInformation object with empty service_options + * and service_details. + */ + public ServiceInformation() { } + + /** Constructs a ServiceInformation object with the given service_options + * and service_details. + * @param __service_options An array of ints describing the service options. + * @param __service_details An array of ServiceDetails describing the service + * details. + */ + public ServiceInformation(int[] __service_options, + org.omg.CORBA.ServiceDetail[] __service_details) + { + service_options = __service_options; + service_details = __service_details; + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/ServiceInformationHelper.java b/omgapi/src/main/java/org/omg/CORBA/ServiceInformationHelper.java new file mode 100644 index 000000000..9c3e20562 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ServiceInformationHelper.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + + /** + * The Helper for ServiceInformation. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +*/ + +package org.omg.CORBA; + + +public abstract class ServiceInformationHelper { + + public static void write(org.omg.CORBA.portable.OutputStream out, org.omg.CORBA.ServiceInformation that) + { + out.write_long(that.service_options.length); + out.write_ulong_array(that.service_options, 0, that.service_options.length); + out.write_long(that.service_details.length); + for (int i = 0 ; i < that.service_details.length ; i += 1) { + org.omg.CORBA.ServiceDetailHelper.write(out, that.service_details[i]); + } + } + + public static org.omg.CORBA.ServiceInformation read(org.omg.CORBA.portable.InputStream in) { + org.omg.CORBA.ServiceInformation that = new org.omg.CORBA.ServiceInformation(); + { + int __length = in.read_long(); + that.service_options = new int[__length]; + in.read_ulong_array(that.service_options, 0, that.service_options.length); + } + { + int __length = in.read_long(); + that.service_details = new org.omg.CORBA.ServiceDetail[__length]; + for (int __index = 0 ; __index < that.service_details.length ; __index += 1) { + that.service_details[__index] = org.omg.CORBA.ServiceDetailHelper.read(in); + } + } + return that; + } + public static org.omg.CORBA.ServiceInformation extract(org.omg.CORBA.Any a) { + org.omg.CORBA.portable.InputStream in = a.create_input_stream(); + return read(in); + } + public static void insert(org.omg.CORBA.Any a, org.omg.CORBA.ServiceInformation that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + private static org.omg.CORBA.TypeCode _tc; + synchronized public static org.omg.CORBA.TypeCode type() { + int _memberCount = 2; + org.omg.CORBA.StructMember[] _members = null; + if (_tc == null) { + _members= new org.omg.CORBA.StructMember[2]; + _members[0] = new org.omg.CORBA.StructMember( + "service_options", + org.omg.CORBA.ORB.init().create_sequence_tc(0, org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ulong)), + null); + + _members[1] = new org.omg.CORBA.StructMember( + "service_details", + org.omg.CORBA.ORB.init().create_sequence_tc(0, org.omg.CORBA.ServiceDetailHelper.type()), + null); + _tc = org.omg.CORBA.ORB.init().create_struct_tc(id(), "ServiceInformation", _members); + } + return _tc; + } + public static String id() { + return "IDL:omg.org/CORBA/ServiceInformation:1.0"; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ServiceInformationHolder.java b/omgapi/src/main/java/org/omg/CORBA/ServiceInformationHolder.java new file mode 100644 index 000000000..c292b86a7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ServiceInformationHolder.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The Holder for ServiceInformation. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a ServiceInformation object + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL xxx as an "out" + * or "inout" parameter, the programmer must pass an instance of + * ServiceInformationHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myServiceInformationHolder is an instance of ServiceInformationHolder, + * the value stored in its value field can be accessed with + * myServiceInformationHolder.value. + */ +public final class ServiceInformationHolder + implements org.omg.CORBA.portable.Streamable { + + /** + * The ServiceInformation value held by this + * ServiceInformationHolder object in its value field. + */ + public ServiceInformation value; + + /** + * Constructs a new ServiceInformationHolder object with its + * value field initialized to null. + */ + public ServiceInformationHolder() { + this(null); + } + + /** + * Constructs a new ServiceInformationHolder object with its + * value field initialized to the given + * ServiceInformation object. + * + * @param arg the ServiceInformation object with which to initialize + * the value field of the newly-created + * ServiceInformationHolder object + */ + public ServiceInformationHolder(org.omg.CORBA.ServiceInformation arg) { + value = arg; + } + + + /** + * Marshals the value in this ServiceInformationHolder object's + * value field to the output stream out. + * + * @param out the OutputStream object that will contain + * the CDR formatted data + */ + public void _write(org.omg.CORBA.portable.OutputStream out) { + org.omg.CORBA.ServiceInformationHelper.write(out, value); + } + + /** + * Reads unmarshalled data from the input stream in and assigns it to + * the value field in this ServiceInformationHolder object. + * + * @param in the InputStream object containing CDR + * formatted data from the wire + */ + public void _read(org.omg.CORBA.portable.InputStream in) { + value = org.omg.CORBA.ServiceInformationHelper.read(in); + } + + /** + * Retrieves the TypeCode object that corresponds + * to the value held in this ServiceInformationHolder object's + * value field. + * + * @return the type code for the value held in this ServiceInformationHolder + * object + */ + public org.omg.CORBA.TypeCode _type() { + return org.omg.CORBA.ServiceInformationHelper.type(); + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/SetOverrideType.java b/omgapi/src/main/java/org/omg/CORBA/SetOverrideType.java new file mode 100644 index 000000000..e6fb7a7ec --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/SetOverrideType.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The mapping of a CORBA enum tagging + * SET_OVERRIDE and ADD_OVERRIDE, which + * indicate whether policies should replace the + * existing policies of an Object or be added to them. + *

    + * The method {@link omg.org.CORBA.Object#_set_policy_override} takes + * either SetOverrideType.SET_OVERRIDE or + * SetOverrideType.ADD_OVERRIDE as its second argument. + * The method _set_policy_override + * creates a new Object initialized with the + * Policy objects supplied as the first argument. If the + * second argument is ADD_OVERRIDE, the new policies + * are added to those of the Object instance that is + * calling the _set_policy_override method. If + * SET_OVERRIDE is given instead, the existing policies + * are replaced with the given ones. + * + * @author OMG + * @version 1.20 07/27/07 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public class SetOverrideType implements org.omg.CORBA.portable.IDLEntity { + + /** + * The int constant for the enum value SET_OVERRIDE. + */ + public static final int _SET_OVERRIDE = 0; + + /** + * The int constant for the enum value ADD_OVERRIDE. + */ + public static final int _ADD_OVERRIDE = 1; + + /** + * The SetOverrideType constant for the enum value SET_OVERRIDE. + */ + public static final SetOverrideType SET_OVERRIDE = new SetOverrideType(_SET_OVERRIDE); + + /** + * The SetOverrideType constant for the enum value ADD_OVERRIDE. + */ + public static final SetOverrideType ADD_OVERRIDE = new SetOverrideType(_ADD_OVERRIDE); + + /** + * Retrieves the value of this SetOverrideType instance. + * + * @return the int for this SetOverrideType instance. + */ + public int value() { + return _value; + } + + /** + * Converts the given int to the corresponding + * SetOverrideType instance. + * + * @param i the int to convert; must be either + * SetOverrideType._SET_OVERRIDE or + * SetOverrideType._ADD_OVERRIDE + * @return the SetOverrideType instance whose value + * matches the given int + * @exception BAD_PARAM if the given int does not + * match the value of + * any SetOverrideType instance + */ + public static SetOverrideType from_int(int i) + { + switch (i) { + case _SET_OVERRIDE: + return SET_OVERRIDE; + case _ADD_OVERRIDE: + return ADD_OVERRIDE; + default: + throw new org.omg.CORBA.BAD_PARAM(); + } + } + + /** + * Constructs a SetOverrideType instance from an + * int. + * @param _value must be either SET_OVERRIDE or + * ADD_OVERRIDE + */ + protected SetOverrideType(int _value){ + this._value = _value; + } + + /** + * The field containing the value for this SetOverrideType + * object. + * + */ + private int _value; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/SetOverrideTypeHelper.java b/omgapi/src/main/java/org/omg/CORBA/SetOverrideTypeHelper.java new file mode 100644 index 000000000..5c890aee7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/SetOverrideTypeHelper.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for SetOverrideType. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/SetOverrideTypeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* 03 June 1999 11:52:03 o'clock GMT+00:00 +*/ + +abstract public class SetOverrideTypeHelper +{ + private static String _id = "IDL:omg.org/CORBA/SetOverrideType:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.SetOverrideType that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.SetOverrideType extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (org.omg.CORBA.SetOverrideTypeHelper.id (), "SetOverrideType", new String[] { "SET_OVERRIDE", "ADD_OVERRIDE"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.SetOverrideType read (org.omg.CORBA.portable.InputStream istream) + { + return org.omg.CORBA.SetOverrideType.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.SetOverrideType value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ShortHolder.java b/omgapi/src/main/java/org/omg/CORBA/ShortHolder.java new file mode 100644 index 000000000..0bb87a497 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ShortHolder.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for Short. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    short + * that is used to store "out" and "inout" parameters in IDL operations. + * If an IDL operation signature has an IDL short as an "out" + * or "inout" parameter, the programmer must pass an instance of + * ShortHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myShortHolder is an instance of ShortHolder, + * the value stored in its value field can be accessed with + * myShortHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class ShortHolder implements Streamable { + + /** + * The short value held by this ShortHolder + * object. + */ + public short value; + + /** + * Constructs a new ShortHolder object with its + * value field initialized to 0. + */ + public ShortHolder() { + } + + /** + * Constructs a new ShortHolder object with its + * value field initialized to the given + * short. + * @param initial the short with which to initialize + * the value field of the newly-created + * ShortHolder object + */ + public ShortHolder(short initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in + * this ShortHolder object + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire. + */ + public void _read(InputStream input) { + value = input.read_short(); + } + + /** + * Marshals to output the value in + * this ShortHolder object. + * + * @param output the OutputStream which will contain the CDR formatted data. + */ + public void _write(OutputStream output) { + output.write_short(value); + } + + /** + * Returns the TypeCode corresponding to the value held in + * this ShortHolder object. + * + * @return the TypeCode of the value held in + * this ShortHolder object + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_short); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ShortSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/ShortSeqHelper.java new file mode 100644 index 000000000..1038a3636 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ShortSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for ShortSeqHelper. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/ShortSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class ShortSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ShortSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, short[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static short[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ShortSeqHelper.id (), "ShortSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static short[] read (org.omg.CORBA.portable.InputStream istream) + { + short value[] = null; + int _len0 = istream.read_long (); + value = new short[_len0]; + istream.read_short_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, short[] value) + { + ostream.write_long (value.length); + ostream.write_short_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ShortSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/ShortSeqHolder.java new file mode 100644 index 000000000..4c5354f9b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ShortSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for ShortSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/ShortSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class ShortSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public short value[] = null; + + public ShortSeqHolder () + { + } + + public ShortSeqHolder (short[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ShortSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ShortSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ShortSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/StringHolder.java b/omgapi/src/main/java/org/omg/CORBA/StringHolder.java new file mode 100644 index 000000000..eb819d03a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/StringHolder.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for String. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a String + * that is used to store "out" and "inout" parameters in IDL operations. + * If an IDL operation signature has an IDL string as an "out" + * or "inout" parameter, the programmer must pass an instance of + * StringHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myStringHolder is an instance of StringHolder, + * the value stored in its value field can be accessed with + * myStringHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class StringHolder implements Streamable { + + /** + * The String value held by this StringHolder + * object. + */ + public String value; + + /** + * Constructs a new StringHolder object with its + * value field initialized to null. + */ + public StringHolder() { + } + + /** + * Constructs a new StringHolder object with its + * value field initialized to the given + * String. + * @param initial the String with which to initialize + * the value field of the newly-created + * StringHolder object + */ + public StringHolder(String initial) { + value = initial; + } + + /** + * Reads the unmarshalled data from input and assigns it to + * the value field of this StringHolder object. + * + * @param input the InputStream containing CDR formatted data from the wire. + */ + public void _read(InputStream input) { + value = input.read_string(); + } + + /** + * Marshals the value held by this StringHolder object + * to the output stream output. + * + * @param output the OutputStream which will contain the CDR formatted data. + */ + public void _write(OutputStream output) { + output.write_string(value); + } + + /** + * Retrieves the TypeCode object that corresponds to + * the value held in this StringHolder object. + * + * @return the type code of the value held in this StringHolder + * object + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_string); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/StringValueHelper.java b/omgapi/src/main/java/org/omg/CORBA/StringValueHelper.java new file mode 100644 index 000000000..5682f101f --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/StringValueHelper.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The Helper for StringValue. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/StringValueHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from orb.idl +* 31 May 1999 22:27:30 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public class StringValueHelper implements org.omg.CORBA.portable.BoxedValueHelper +{ + private static String _id = "IDL:omg.org/CORBA/StringValue:1.0"; + + private static StringValueHelper _instance = new StringValueHelper (); + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_value_box_tc (_id, "StringValue", __typeCode); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + if (!(istream instanceof org.omg.CORBA_2_3.portable.InputStream)) { + throw new org.omg.CORBA.BAD_PARAM(); } + return (String) ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (_instance); + } + + public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream) + { + String tmp; + tmp = istream.read_string (); + return (java.io.Serializable) tmp; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + if (!(ostream instanceof org.omg.CORBA_2_3.portable.OutputStream)) { + throw new org.omg.CORBA.BAD_PARAM(); } + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, _instance); + } + + public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable value) + { + if (!(value instanceof String)) { + throw new org.omg.CORBA.MARSHAL(); } + String valueType = (String) value; + ostream.write_string (valueType); + } + + public String get_id () + { + return _id; + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/StructMember.java b/omgapi/src/main/java/org/omg/CORBA/StructMember.java new file mode 100644 index 000000000..d2fcd4c2c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/StructMember.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/StructMember.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; + +/** + * Describes a member of an IDL struct in the + * Interface Repository, including + * the name of the struct member, the type of + * the struct member, and + * the typedef that represents the IDL type of the + * struct member + * described the struct member object. + */ +// @SuppressWarnings({"serial"}) +public final class StructMember implements org.omg.CORBA.portable.IDLEntity { + + // instance variables + + /** + * The name of the struct member described by + * this StructMember object. + * @serial + */ + public String name; + + /** + * The type of the struct member described by + * this StructMember object. + * @serial + */ + public org.omg.CORBA.TypeCode type; + + /** + * The typedef that represents the IDL type of the struct member described by + * this StructMember object. + * @serial + */ + public org.omg.CORBA.IDLType type_def; + // constructors + + /** + * Constructs a default StructMember object. + */ + public StructMember() { } + + /** + * Constructs a StructMember object initialized with the + * given values. + * @param __name a String object with the name of the struct + * member + * @param __type a TypeCode object describing the type of the struct + * member + * @param __type_def an IDLType object representing the IDL type + * of the struct member + */ + public StructMember(String __name, org.omg.CORBA.TypeCode __type, org.omg.CORBA.IDLType __type_def) { + name = __name; + type = __type; + type_def = __type_def; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/StructMemberHelper.java b/omgapi/src/main/java/org/omg/CORBA/StructMemberHelper.java new file mode 100644 index 000000000..aae2c5b61 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/StructMemberHelper.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for StructMember. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/StructMemberHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:43 o'clock GMT+00:00 +*/ + +abstract public class StructMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/StructMember:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StructMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.StructMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [3]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[1] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[2] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.StructMemberHelper.id (), "StructMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.StructMember read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.StructMember value = new org.omg.CORBA.StructMember (); + value.name = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StructMember value) + { + ostream.write_string (value.name); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/SystemException.java b/omgapi/src/main/java/org/omg/CORBA/SystemException.java new file mode 100644 index 000000000..6e67affcc --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/SystemException.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import java.util.*; +import org.omg.CORBA.OMGVMCID; +import com.sun.corba.ee.org.omg.CORBA.SUNVMCID; + +/** + * The root class for all CORBA standard exceptions. These exceptions + * may be thrown as a result of any CORBA operation invocation and may + * also be returned by many standard CORBA API methods. The standard + * exceptions contain a minor code, allowing more detailed specification, and a + * completion status. This class is subclassed to + * generate each one of the set of standard ORB exceptions. + * SystemException extends + * java.lang.RuntimeException; thus none of the + * SystemException exceptions need to be + * declared in signatures of the Java methods mapped from operations in + * IDL interfaces. + * + * @see documentation on + * Java IDL exceptions + */ + +public abstract class SystemException extends java.lang.RuntimeException { + + /** + * The CORBA Exception minor code. + * @serial + */ + public int minor; + + /** + * The status of the operation that threw this exception. + * @serial + */ + public CompletionStatus completed; + + /** + * Constructs a SystemException exception with the specified detail + * message, minor code, and completion status. + * A detail message is a String that describes this particular exception. + * @param reason the String containing a detail message + * @param minor the minor code + * @param completed the completion status + */ + protected SystemException(String reason, int minor, CompletionStatus completed) { + super(reason); + this.minor = minor; + this.completed = completed; + } + + /** + * Converts this exception to a representative string. + */ + public String toString() { + // The fully qualified exception class name + String result = super.toString(); + + // The vmcid part + int vmcid = minor & 0xFFFFF000; + switch (vmcid) { + case OMGVMCID.value: + result += " vmcid: OMG"; + break; + case SUNVMCID.value: + result += " vmcid: SUN"; + break; + default: + result += " vmcid: 0x" + Integer.toHexString(vmcid); + break; + } + + // The minor code part + int mc = minor & 0x00000FFF; + result += " minor code: " + mc; + + // The completion status part + switch (completed.value()) { + case CompletionStatus._COMPLETED_YES: + result += " completed: Yes"; + break; + case CompletionStatus._COMPLETED_NO: + result += " completed: No"; + break; + case CompletionStatus._COMPLETED_MAYBE: + default: + result += " completed: Maybe"; + break; + } + return result; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TCKind.java b/omgapi/src/main/java/org/omg/CORBA/TCKind.java new file mode 100644 index 000000000..cb990e9ad --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TCKind.java @@ -0,0 +1,540 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** + * The Java mapping of the IDL enum TCKind, which + * specifies the kind of a TypeCode object. There is + * one kind for each primitive and essential IDL data type. + *

    + * The class TCKind consists of: + *

      + *
    • a set of int constants, one for each + * kind of IDL data type. These int constants + * make it possible to use a switch statement. + *
    • a set of TCKind constants, one for each + * kind of IDL data type. The value field for + * each TCKind instance is initialized with + * the int constant that corresponds with + * the IDL data type that the instance represents. + *
    • the method from_intfor converting + * an int to its + * corresponding TCKind instance + *

      Example: + *

      + *      org.omg.CORBA.TCKind k = org.omg.CORBA.TCKind.from_int(
      + *                         org.omg.CORBA.TCKind._tk_string);
      + * 
      + * The variable k represents the TCKind + * instance for the IDL type string, which is + * tk_string. + *

      + *

    • the method value for accessing the + * _value field of a TCKind constant + *

      Example: + *

      + *   int i = org.omg.CORBA.TCKind.tk_char.value();
      + * 
      + * The variable i represents 9, the value for the + * IDL data type char. + *
    + *

    The value field of a TCKind instance + * is the CDR encoding used for a TypeCode object in + * an IIOP message. + */ + +public class TCKind { + + /** + * The int constant for a null IDL data type. + */ + public static final int _tk_null = 0; + + /** + * The int constant for the IDL data type void. + */ + public static final int _tk_void = 1; + + /** + * The int constant for the IDL data type short. + */ + public static final int _tk_short = 2; + + /** + * The int constant for the IDL data type long. + */ + public static final int _tk_long = 3; + + /** + * The int constant for the IDL data type ushort. + */ + public static final int _tk_ushort = 4; + + /** + * The int constant for the IDL data type ulong. + */ + public static final int _tk_ulong = 5; + + /** + * The int constant for the IDL data type float. + */ + public static final int _tk_float = 6; + + /** + * The int constant for the IDL data type double. + */ + public static final int _tk_double = 7; + + /** + * The int constant for the IDL data type boolean. + */ + public static final int _tk_boolean = 8; + + /** + * The int constant for the IDL data type char. + */ + public static final int _tk_char = 9; + + /** + * The int constant for the IDL data type octet. + */ + public static final int _tk_octet = 10; + + /** + * The int constant for the IDL data type any. + */ + public static final int _tk_any = 11; + + /** + * The int constant for the IDL data type TypeCode. + */ + public static final int _tk_TypeCode = 12; + + /** + * The int constant for the IDL data type Principal. + */ + public static final int _tk_Principal = 13; + + /** + * The int constant for the IDL data type objref. + */ + public static final int _tk_objref = 14; + + /** + * The int constant for the IDL data type struct. + */ + public static final int _tk_struct = 15; + + /** + * The int constant for the IDL data type union. + */ + public static final int _tk_union = 16; + + /** + * The int constant for the IDL data type enum. + */ + public static final int _tk_enum = 17; + + /** + * The int constant for the IDL data type string. + */ + public static final int _tk_string = 18; + + /** + * The int constant for the IDL data type sequence. + */ + public static final int _tk_sequence = 19; + + /** + * The int constant for the IDL data type array. + */ + public static final int _tk_array = 20; + + /** + * The int constant for the IDL data type alias. + */ + public static final int _tk_alias = 21; + + /** + * The int constant for the IDL data type except. + */ + public static final int _tk_except = 22; + + /** + * The int constant for the IDL data type longlong. + */ + public static final int _tk_longlong = 23; + + /** + * The int constant for the IDL data type ulonglong. + */ + public static final int _tk_ulonglong = 24; + + /** + * The int constant for the IDL data type longdouble. + */ + public static final int _tk_longdouble = 25; + + /** + * The int constant for the IDL data type wchar. + */ + public static final int _tk_wchar = 26; + + /** + * The int constant for the IDL data type wstring. + */ + public static final int _tk_wstring = 27; + + /** + * The int constant for the IDL data type fixed. + */ + public static final int _tk_fixed = 28; + + /** + * The int constant for the IDL data type value. + */ + public static final int _tk_value = 29; // orbos 98-01-18: Objects By Value + + /** + * The int constant for the IDL data type value_box. + */ + public static final int _tk_value_box = 30; // orbos 98-01-18: Objects By Value + + /** + * The int constant for the IDL data type native. + */ + public static final int _tk_native = 31; // Verify + + /** + * The int constant for the IDL data type abstract interface. + */ + public static final int _tk_abstract_interface = 32; + + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_null. + */ + public static final TCKind tk_null = new TCKind(_tk_null); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_void. + */ + public static final TCKind tk_void = new TCKind(_tk_void); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_short. + */ + public static final TCKind tk_short = new TCKind(_tk_short); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_long. + */ + public static final TCKind tk_long = new TCKind(_tk_long); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_ushort. + */ + public static final TCKind tk_ushort = new TCKind(_tk_ushort); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_ulong. + */ + public static final TCKind tk_ulong = new TCKind(_tk_ulong); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_float. + */ + public static final TCKind tk_float = new TCKind(_tk_float); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_double. + */ + public static final TCKind tk_double = new TCKind(_tk_double); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_boolean. + */ + public static final TCKind tk_boolean = new TCKind(_tk_boolean); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_char. + */ + public static final TCKind tk_char = new TCKind(_tk_char); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_octet. + */ + public static final TCKind tk_octet = new TCKind(_tk_octet); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_any. + */ + public static final TCKind tk_any = new TCKind(_tk_any); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_TypeCode. + */ + public static final TCKind tk_TypeCode = new TCKind(_tk_TypeCode); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_Principal. + */ + public static final TCKind tk_Principal = new TCKind(_tk_Principal); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_objref. + */ + public static final TCKind tk_objref = new TCKind(_tk_objref); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_struct. + */ + public static final TCKind tk_struct = new TCKind(_tk_struct); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_union. + */ + public static final TCKind tk_union = new TCKind(_tk_union); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_enum. + */ + public static final TCKind tk_enum = new TCKind(_tk_enum); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_string. + */ + public static final TCKind tk_string = new TCKind(_tk_string); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_sequence. + */ + public static final TCKind tk_sequence = new TCKind(_tk_sequence); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_array. + */ + public static final TCKind tk_array = new TCKind(_tk_array); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_alias. + */ + public static final TCKind tk_alias = new TCKind(_tk_alias); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_except. + */ + public static final TCKind tk_except = new TCKind(_tk_except); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_longlong. + */ + public static final TCKind tk_longlong = new TCKind(_tk_longlong); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_ulonglong. + */ + public static final TCKind tk_ulonglong = new TCKind(_tk_ulonglong); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_longdouble. + */ + public static final TCKind tk_longdouble = new TCKind(_tk_longdouble); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_wchar. + */ + public static final TCKind tk_wchar = new TCKind(_tk_wchar); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_wstring. + */ + public static final TCKind tk_wstring = new TCKind(_tk_wstring); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_fixed. + */ + public static final TCKind tk_fixed = new TCKind(_tk_fixed); + + // orbos 98-01-18: Objects By Value -- begin + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_value. + */ + public static final TCKind tk_value = new TCKind(_tk_value); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_value_box. + */ + public static final TCKind tk_value_box = new TCKind(_tk_value_box); + // orbos 98-01-18: Objects By Value -- end + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_native. + */ + public static final TCKind tk_native = new TCKind(_tk_native); + + /** + * The TCKind constant whose value field is + * initialized with TCKind._tk_abstract_interface. + */ + public static final TCKind tk_abstract_interface = new TCKind(_tk_abstract_interface); + + + + + /** + * Retrieves the value of this TCKind instance. + * + * @return the int that represents the kind of + * IDL data type for this TCKind instance + */ + public int value() { + return _value; + } + + /** + * Converts the given int to the corresponding + * TCKind instance. + * + * @param i the int to convert. It must be one of + * the int constants in the class + * TCKind. + * @return the TCKind instance whose value + * field matches the given int + * @exception BAD_PARAM if the given int does not + * match the _value field of + * any TCKind instance + */ + public static TCKind from_int(int i) { + switch (i) { + case _tk_null: + return tk_null; + case _tk_void: + return tk_void; + case _tk_short: + return tk_short; + case _tk_long: + return tk_long; + case _tk_ushort: + return tk_ushort; + case _tk_ulong: + return tk_ulong; + case _tk_float: + return tk_float; + case _tk_double: + return tk_double; + case _tk_boolean: + return tk_boolean; + case _tk_char: + return tk_char; + case _tk_octet: + return tk_octet; + case _tk_any: + return tk_any; + case _tk_TypeCode: + return tk_TypeCode; + case _tk_Principal: + return tk_Principal; + case _tk_objref: + return tk_objref; + case _tk_struct: + return tk_struct; + case _tk_union: + return tk_union; + case _tk_enum: + return tk_enum; + case _tk_string: + return tk_string; + case _tk_sequence: + return tk_sequence; + case _tk_array: + return tk_array; + case _tk_alias: + return tk_alias; + case _tk_except: + return tk_except; + case _tk_longlong: + return tk_longlong; + case _tk_ulonglong: + return tk_ulonglong; + case _tk_longdouble: + return tk_longdouble; + case _tk_wchar: + return tk_wchar; + case _tk_wstring: + return tk_wstring; + case _tk_fixed: + return tk_fixed; + case _tk_value: // orbos 98-01-18: Objects By Value + return tk_value; + case _tk_value_box: // orbos 98-01-18: Objects By Value + return tk_value_box; + case _tk_native: + return tk_native; + case _tk_abstract_interface: + return tk_abstract_interface; + default: + throw new org.omg.CORBA.BAD_PARAM(); + } + } + + + /** + * Creates a new TCKind instance initialized with the given + * int. + * @deprecated Do not use this constructor as this method should be private + * according to the OMG specification. Use {@link #from_int(int)} instead. + * + * @param _value the int to convert. It must be one of + * the int constants in the class + * TCKind. + */ + // @Deprecated + protected TCKind(int _value){ + this._value = _value; + } + + private int _value; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TIMEOUT.java b/omgapi/src/main/java/org/omg/CORBA/TIMEOUT.java new file mode 100644 index 000000000..eab01c23c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TIMEOUT.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * TIMEOUT is raised when no delivery has been made and the + * specified time-to-live period has been exceeded. It is a standard system + * exception because time-to-live QoS can be applied to any invocation. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0, 03/05/2004 + * @since J2SE 1.5 + */ + +public final class TIMEOUT extends SystemException { + + /** + * Constructs an TIMEOUT exception with + * minor code set to 0 and CompletionStatus set to COMPLETED_NO. + */ + public TIMEOUT() { + this(""); + } + + /** + * Constructs an TIMEOUT exception with the + * specified message. + * + * @param detailMessage string containing a detailed message. + */ + public TIMEOUT(String detailMessage) { + this(detailMessage, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an TIMEOUT exception with the + * specified minor code and completion status. + * + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public TIMEOUT(int minorCode, + CompletionStatus completionStatus) { + this("", minorCode, completionStatus); + } + + /** + * Constructs an TIMEOUT exception with the + * specified message, minor code, and completion status. + * + * @param detailMessage string containing a detailed message. + * @param minorCode minor code. + * @param completionStatus completion status. + */ + public TIMEOUT(String detailMessage, + int minorCode, + CompletionStatus completionStatus) { + super(detailMessage, minorCode, completionStatus); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_MODE.java b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_MODE.java new file mode 100644 index 000000000..edf5ee949 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_MODE.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The CORBA TRANSACTION_MODE exception is thrown + * by the client ORB if it detects a mismatch between the + * InvocationPolicy in the IOR and the chosen invocation path + * (i.e, direct or routed invocation). + * It contains a minor code, which gives information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * The OMG CORBA core 2.4 specification has details. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0 10/22/2000 + */ + +public final class TRANSACTION_MODE extends SystemException { + /** + * Constructs a TRANSACTION_MODE exception with a default + * minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public TRANSACTION_MODE() { + this(""); + } + + /** + * Constructs a TRANSACTION_MODE exception with the specified + * description message, a minor code of 0, and a completion state of + * COMPLETED_NO. + * @param s the String containing a detail message + */ + public TRANSACTION_MODE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a TRANSACTION_MODE exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_MODE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a TRANSACTION_MODE exception with the specified + * description message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_MODE(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_REQUIRED.java b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_REQUIRED.java new file mode 100644 index 000000000..c031168ee --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_REQUIRED.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception indicates that the request carried a null transaction context, + * but an active transaction is required.

    + * It contains a minor code, which gives information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * The OMG Transaction Service specfication has details. + * + * @see documentation on + * Java IDL exceptions + * @version 1.5 09/09/97 + */ + +public final class TRANSACTION_REQUIRED extends SystemException { + /** + * Constructs a TRANSACTION_REQUIRED exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public TRANSACTION_REQUIRED() { + this(""); + } + + /** + * Constructs a TRANSACTION_REQUIRED exception with the specified + * description message, a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public TRANSACTION_REQUIRED(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a TRANSACTION_REQUIRED exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_REQUIRED(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a TRANSACTION_REQUIRED exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_REQUIRED(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_ROLLEDBACK.java b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_ROLLEDBACK.java new file mode 100644 index 000000000..fc2f48603 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_ROLLEDBACK.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when the transaction associated with the request has + * already been rolled back or marked to roll back. Thus, the requested + * operation either could not be performed or was not performed because + * further computation on behalf of the transaction would be fruitless.

    + * See the OMG Transaction + * Service specification for details. + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.5 09/09/97 + */ + +public final class TRANSACTION_ROLLEDBACK extends SystemException { + /** + * Constructs a TRANSACTION_ROLLEDBACK exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public TRANSACTION_ROLLEDBACK() { + this(""); + } + + /** + * Constructs a TRANSACTION_ROLLEDBACK exception with the + * specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public TRANSACTION_ROLLEDBACK(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a TRANSACTION_ROLLEDBACK exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_ROLLEDBACK(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a TRANSACTION_ROLLEDBACK exception with the + * specified description message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_ROLLEDBACK(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_UNAVAILABLE.java b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_UNAVAILABLE.java new file mode 100644 index 000000000..de83aefb8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TRANSACTION_UNAVAILABLE.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The CORBA TRANSACTION_UNAVAILABLE exception is thrown + * by the ORB when it cannot process a transaction service context because + * its connection to the Transaction Service has been abnormally terminated. + * + * It contains a minor code, which gives information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * The OMG CORBA core 2.4 specification has details. + * + * @see documentation on + * Java IDL exceptions + * @version 1.0 10/22/2000 + */ + +public final class TRANSACTION_UNAVAILABLE extends SystemException { + /** + * Constructs a TRANSACTION_UNAVAILABLE exception + * with a default minor code of 0, a completion state of + * CompletionStatus.COMPLETED_NO, and a null description. + */ + public TRANSACTION_UNAVAILABLE() { + this(""); + } + + /** + * Constructs a TRANSACTION_UNAVAILABLE exception with the + * specifieddescription message, a minor code of 0, and a completion state + * of COMPLETED_NO. + * @param s the String containing a detail message + */ + public TRANSACTION_UNAVAILABLE(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a TRANSACTION_UNAVAILABLE exception with the + * specified minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_UNAVAILABLE(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a TRANSACTION_UNAVAILABLE exception with the + * specified description message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public TRANSACTION_UNAVAILABLE(String s, int minor, + CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TRANSIENT.java b/omgapi/src/main/java/org/omg/CORBA/TRANSIENT.java new file mode 100644 index 000000000..52dd0d770 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TRANSIENT.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Exception thrown when the ORB attempted to reach an object and failed. + * It is not an indication that an object does not exist. Instead, it simply + * means that no further determination of an object's status was possible + * because it could not be reached. This exception is raised if an attempt + * to establish a connection fails, for example, because the server or the + * implementation repository is down.

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.17 09/09/97 + */ + +public final class TRANSIENT extends SystemException { + /** + * Constructs a TRANSIENT exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public TRANSIENT() { + this(""); + } + + /** + * Constructs a TRANSIENT exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public TRANSIENT(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs a TRANSIENT exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public TRANSIENT(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs a TRANSIENT exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public TRANSIENT(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TSIdentification.java b/omgapi/src/main/java/org/omg/CORBA/TSIdentification.java new file mode 100644 index 000000000..d962b5080 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TSIdentification.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** + * An interface defined in the OMG Transactions Service Specification + * that provides methods to allow the JTS to register + * its Sender and Receiver interfaces with the ORB. TSIdentification + * methods are always called from the same address space (i.e. it is + * a pseudo-object), hence it is not necessary to define any stubs/skeletons. + * During initialization, an instance of TSIdentification is provided + * to the JTS by the ORB using the method + * com.sun.corba.ee.spi.costransactions.TransactionService.identify_ORB. +*/ + +public interface TSIdentification { + + /** + * Called by the OTS + * during initialization in order to register its Sender + * callback interface with the ORB. This method + * may throw an AlreadyIdentified exception if + * the registration has already been done previously. + * @param senderOTS the Sender object to be + * registered + * @throws org.omg.CORBA.TSIdentificationPackage.NotAvailable + * if the ORB is unavailable to register the given Sender + * object + * @throws org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified + * if the given Sender object has already been registered + * with the ORB + * + */ + public void + identify_sender(org.omg.CosTSPortability.Sender senderOTS) + throws org.omg.CORBA.TSIdentificationPackage.NotAvailable, + org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified ; + + + /** + * Called by the OTS during + * initialization to register its Receiver callback interface + * with the ORB. This operation may throw an AlreadyIdentified + * exception if the registration has already been done previously. + * @param receiverOTS the Receiver object to register with the ORB + * @throws org.omg.CORBA.TSIdentificationPackage.NotAvailable + * if the ORB is unavailable to register the given Receiver + * object + * @throws org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified + * if the given Receiver object has already been registered + * with the ORB + */ + public void + identify_receiver(org.omg.CosTSPortability.Receiver receiverOTS) + throws org.omg.CORBA.TSIdentificationPackage.NotAvailable, + org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified ; +} + + diff --git a/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/AlreadyIdentified.java b/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/AlreadyIdentified.java new file mode 100644 index 000000000..c3a5363f8 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/AlreadyIdentified.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.TSIdentificationPackage; + +/** + * This exception is thrown if OTS call-back interfaces + * have already been registered with the ORB. + * @see TSIdentification + * @see NotAvailable + */ +public final class AlreadyIdentified + extends org.omg.CORBA.UserException { + // constructor + public AlreadyIdentified() { + super(); + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/NotAvailable.java b/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/NotAvailable.java new file mode 100644 index 000000000..08c707ec5 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/NotAvailable.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.TSIdentificationPackage; +/** + * A user-defined exception thrown if the ORB is unavailable + * to register the call-back interfaces identified by the + * OTS during initialization. + * @see TSIdentification + * @see AlreadyIdentified + */ +public final class NotAvailable + extends org.omg.CORBA.UserException { + + // constructor +/** + * Constructs a NotAvailable exception. + */ + public NotAvailable() { + super(); + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/package.html b/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/package.html new file mode 100644 index 000000000..60d337afd --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TSIdentificationPackage/package.html @@ -0,0 +1,28 @@ + + + + + + + + Provides the exceptions that may be thrown during OTS or JTS registration + of call-back interfaces with the ORB. The exception + AlreadyIdentified is thrown if OTS call-back interfaces + have already been registered with the ORB. + The exception NotAvailable is thrown if the ORB is not + available to register the call-back interfaces identified by the OTS + during initialization. +

    +@since 1.3 + + diff --git a/omgapi/src/main/java/org/omg/CORBA/TypeCode.java b/omgapi/src/main/java/org/omg/CORBA/TypeCode.java new file mode 100644 index 000000000..e2285720b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TypeCode.java @@ -0,0 +1,520 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.TypeCodePackage.*; +import org.omg.CORBA.portable.IDLEntity; + +/** + * A container for information about a specific CORBA data + * type. + *

    + * TypeCode objects are used: + *

      + *
    • in the Dynamic Invocation Interface -- to indicate the types + * of the actual arguments or the type of the return value.
      + * NamedValue objects are used to represent arguments and + * return values. One of their components is an Any + * object, which in turn has as one of its components a + * TypeCode object. + *
    • by an Interface Repository to represent the type specifications + * that are part of many OMG IDL declarations + *
    + *

    + * The representation of a TypeCode object is opaque, + * but abstractly, a TypeCode object consists of: + *

      + *
    • a kind field, which is set to an instance + * of the class TCKind + *
    • zero or more additional fields appropriate + * for the particular kind. For example, the + * TypeCode object + * describing the OMG IDL type 1ong has kind + * TCKind.tk_long and no additional fields. + * The TypeCode describing OMG IDL type + * sequence<boolean, 10> has a kind field + * with the value + * TCKind.tk_sequence and also fields with the values + * boolean and 10 for the + * type of sequence elements and the length of the sequence.

      + *

    + * + * TypeCode objects can be obtained in various ways: + *
      + *
    1. from a call to the method Any.insert_X, where X is + * a basic IDL type. This method creates a TypeCode object + * for type X and assigns it to the Any object's + * type field. + *
    2. from invocations of methods in the ORB class + *

      For example, the following creates a TypeCode + * object for a string with a maximum of 30 characters: + *

      + *   org.omg.CORBA.TypeCode tcString = orb.create_string_tc(30);
      + * 
      + *

      The following creates a TypeCode + * object for an array of five strings: + *

      + *   org.omg.CORBA.TypeCode tcArray = orb.create_array_tc(
      + *                                       5, TCKind.tk_string);
      + * 
      + *

      The following creates a TypeCode + * object for an interface named "Account": + *

      + *   org.omg.CORBA.TypeCode tcInterface = orb.create_interface_tc(
      + *                                                 "thisId", "Account");
      + * 
      + *
    3. as the return value from the _type method + * in Holder classes for user-defined + * IDL types. These Holder classes are generated + * by the idltojava compiler. + *
    4. from a CORBA Interface Repository + *
    + *

    + * Most of the methods in the class TypeCode + * are accessors, and the information contained in a TypeCode + * object is specific to a particular type. Therefore, methods + * must be invoked + * only on the kind of type codes to which they apply. If an + * accessor method + * tries to access information from an inappropriate kind of + * type code, it will throw + * the exception TypeCodePackage.BadKind. For example, + * if the method discriminator_type is called on anything + * other than a union, it will throw BadKind + * because only unions have a discriminator. + * The following list shows which methods apply to which kinds of + * type codes: + *

    + * These methods may be invoked on all TypeCode kinds: + *

      + *
    • equal + *
    • kind + *
    + *

    + * These methods may be invoked on objref, struct, + * union, enum, + * alias, exception, value, + * value_box, native, + * and abstract_interface: + *

      + *
    • id + *
    • name + *
    + *

    + * These methods may be invoked on struct, + * union, enum, + * and exception: + *

      + *
    • member_count + *
    • member_name + *
    + *

    + * These methods may be invoked on struct, + * union, and exception: + *

      + *
    • member_type(int index) + *
    + *

    + * These methods may be invoked on union: + *

      + *
    • member_label + *
    • discriminator_type + *
    • default_index + *
    + *

    + * These methods may be invoked on string, + * sequence, and array: + *

      + *
    • length + *
    + *

    + * These methods may be invoked on alias, + * sequence, array, and value_box: + *

      + *
    • content_type + *
    + *

    + * Unlike other CORBA pseudo-objects, TypeCode + * objects can be passed as general IDL parameters.

    + * The methods parameter and param_count, + * which are deprecated, are not mapped.

    + * + * Java IDL extends the CORBA specification to allow all operations permitted + * on a struct TypeCode to be permitted + * on an exception TypeCode as well.

    + * + * @version 1.25 09/09/97 + */ +public abstract class TypeCode implements IDLEntity { + + /** + * Compares this TypeCode object with the given one, + * testing for equality. TypeCode objects are equal if + * they are interchangeable and give identical results when + * TypeCode operations are applied to them. + * + * @param tc the TypeCode object to compare against + * @return true if the type codes are equal; + * false otherwise + */ + + public abstract boolean equal(TypeCode tc); + + /** + * Tests to see if the given TypeCode object is + * equivalent to this TypeCode object. + *

    + * Not implemented; see package comments. + * + * @param tc the typecode to compare with this typecode + * + * @return true if the given typecode is equivalent to + * this typecode; false otherwise + * @see CORBA package + * comments for unimplemented features + */ + public abstract boolean equivalent(TypeCode tc); + + /** + * Strips out all optional name and member name fields, + * but leaves all alias typecodes intact. + * @return a TypeCode object with optional name and + * member name fields stripped out, except for alias typecodes, + * which are left intact + * @see CORBA package + * comments for unimplemented features + */ + public abstract TypeCode get_compact_typecode(); + + + /** + * Retrieves the kind of this TypeCode object. + * The kind of a type code determines which TypeCode + * methods may legally be invoked on it. + *

    + * The method kind may be invoked on any + * TypeCode object. + * + * @return the TCKind instance indicating the + * value of the kind field of this + * TypeCode object + */ + + public abstract TCKind kind(); + + /** + * Retrieves the RepositoryId globally identifying the type + * of this TypeCode object. + *

    + * The method id can be invoked on object reference, + * structure, union, enumeration, alias, exception, valuetype, + * boxed valuetype, native, and abstract interface type codes. + * Object reference, exception, valuetype, boxed valuetype, + * native, and abstract interface TypeCode objects + * always have a RepositoryId. + * Structure, union, enumeration, and alias TypeCode objects + * obtained from the Interface Repository or the method + * ORB.create_operation_list + * also always have a RepositoryId. If there is no RepositoryId, the + * method can return an empty string. + * + * @return the RepositoryId for this TypeCode object + * or an empty string if there is no RepositoryID + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind ofTypeCode + * object + */ + + public abstract String id() throws BadKind; + + /** + * Retrieves the simple name identifying this TypeCode + * object within its + * enclosing scope. Since names are local to a Repository, the + * name returned from a TypeCode object + * may not match the name of the + * type in any particular Repository, and may even be an empty + * string. + *

    + * The method name can be invoked on object reference, + * structure, union, enumeration, alias, exception, valuetype, + * boxed valuetype, native, and abstract interface + * TypeCode objects. + * + * @return the name identifying this TypeCode object + * or an empty string + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind ofTypeCode + * object + */ + + public abstract String name() throws BadKind; + + /** + * Retrieves the number of members in the type described by + * this TypeCode object. + *

    + * The method member_count can be invoked on + * structure, union, and enumeration TypeCode objects. + * Java IDL extends the CORBA specification to allow this method to + * operate on exceptions as well. + * + * @return the number of members constituting the type described + * by this TypeCode object + * + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind of TypeCode + * object + */ + + public abstract int member_count() throws BadKind; + + /** + * Retrieves the simple name of the member identified by + * the given index. Since names are local to a + * Repository, the name returned from a TypeCode object + * may not match the name of the member in any particular + * Repository, and may even be an empty string. + *

    + * The method member_name can be invoked on structure, union, + * and enumeration TypeCode objects. + * Java IDL extends the CORBA specification to allow this method to + * operate on exceptions as well. + * + * @param index index of the member for which a name is being reqested + * @return simple name of the member identified by the + * index or an empty string + * @throws org.omg.CORBA.TypeCodePackage.Bounds if the index is equal + * to or greater than + * the number of members constituting the type + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind of TypeCode + * object + */ + + public abstract String member_name(int index) + throws BadKind, org.omg.CORBA.TypeCodePackage.Bounds; + + /** + * Retrieves the TypeCode object describing the type + * of the member identified by the given index. + *

    + * The method member_type can be invoked on structure + * and union TypeCode objects. + * Java IDL extends the CORBA specification to allow this method to + * operate on exceptions as well. + * + * @param index index of the member for which type information + * is begin requested + * @return the TypeCode object describing the + * member at the given index + * @throws org.omg.CORBA.TypeCodePackage.Bounds if the index is + * equal to or greater than + * the number of members constituting the type + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind of TypeCode + * object + */ + + public abstract TypeCode member_type(int index) + throws BadKind, org.omg.CORBA.TypeCodePackage.Bounds; + + /** + * Retrieves the label of the union member + * identified by the given index. For the default member, + * the label is the zero octet. + *

    + * The method member_label can only be invoked on union + * TypeCode objects. + * + * @param index index of the union member for which the + * label is being requested + * @return an Any object describing the label of + * the requested union member or the zero octet for + * the default member + * @throws org.omg.CORBA.TypeCodePackage.Bounds if the index is + * equal to or greater than + * the number of members constituting the union + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on a non-union TypeCode + * object + */ + + public abstract Any member_label(int index) + throws BadKind, org.omg.CORBA.TypeCodePackage.Bounds; + + /** + * Returns a TypeCode object describing + * all non-default member labels. + * The method discriminator_type can be invoked only + * on union TypeCode objects. + * + * @return the TypeCode object describing + * the non-default member labels + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on a non-union TypeCode + * object + */ + + public abstract TypeCode discriminator_type() + throws BadKind; + + /** + * Returns the index of the + * default member, or -1 if there is no default member. + *

    + * The method default_index can be invoked only on union + * TypeCode objects. + * + * @return the index of the default member, or -1 if + * there is no default member + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on a non-union TypeCode + * object + */ + + public abstract int default_index() throws BadKind; + + /** + * Returns the number of elements in the type described by + * this TypeCode object. + * For strings and sequences, it returns the + * bound, with zero indicating an unbounded string or sequence. + * For arrays, it returns the number of elements in the array. + *

    + * The method length can be invoked on string, sequence, and + * array TypeCode objects. + * + * @return the bound for strings and sequences, or the + * number of elements for arrays + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind of TypeCode + * object + */ + + public abstract int length() throws BadKind; + + /** + * Returns the TypeCode object representing the + * IDL type for the members of the object described by this + * TypeCode object. + * For sequences and arrays, it returns the + * element type. For aliases, it returns the original type. Note + * that multidimensional arrays are represented by nesting + * TypeCode objects, one per dimension. + * For boxed valuetypes, it returns the boxed type. + *

    + * The method content_type can be invoked on sequence, array, + * alias, and boxed valuetype TypeCode objects. + * + * @return a TypeCode object representing + * the element type for sequences and arrays, the + * original type for aliases, or the + * boxed type for boxed valuetypes. + * @throws org.omg.CORBA.TypeCodePackage.BadKind if the method + * is invoked on an inappropriate kind of TypeCode + * object + */ + + public abstract TypeCode content_type() throws BadKind; + + + /** + * Returns the number of digits in the fixed type described by this + * TypeCode object. For example, the typecode for + * the number 3000.275d could be fixed<7,3>, where + * 7 is the precision and 3 is the scale. + * + * @return the total number of digits + * @throws org.omg.CORBA.TypeCodePackage.BadKind if this method + * is invoked on an inappropriate kind of TypeCode + * object + * + */ + public abstract short fixed_digits() throws BadKind ; + + /** + * Returns the scale of the fixed type described by this + * TypeCode object. A positive number indicates the + * number of digits to the right of the decimal point. + * For example, the number 3000d could have the + * typecode fixed<4,0>, where the first number is + * the precision and the second number is the scale. + * A negative number is also possible and adds zeroes to the + * left of the decimal point. In this case, fixed<1,-3>, + * could be the typecode for the number 3000d. + * + * @return the scale of the fixed type that this + * TypeCode object describes + * @throws org.omg.CORBA.TypeCodePackage.BadKind if this method + * is invoked on an inappropriate kind of TypeCode + * object + */ + public abstract short fixed_scale() throws BadKind ; + + /** + * Returns the constant that indicates the visibility of the member + * at the given index. + * + * This operation can only be invoked on non-boxed value + * TypeCode objects. + * + * @param index an int indicating the index into the + * value + * @return either PRIVATE_MEMBER.value or + * PUBLIC_MEMBER.value + * @throws org.omg.CORBA.TypeCodePackage.BadKind if this method + * is invoked on a non-value type TypeCode + * object + * @throws org.omg.CORBA.TypeCodePackage.Bounds + * if the given index is out of bounds + * @see CORBA package + * comments for unimplemented features + */ + + abstract public short member_visibility(int index) + throws BadKind, org.omg.CORBA.TypeCodePackage.Bounds ; + + /** + * Returns a constant indicating the modifier of the value type + * that this TypeCode object describes. The constant + * returned must be one of the following: VM_NONE.value, + * VM_ABSTRACT.value, VM_CUSTOM.value, + * or VM_TRUNCATABLE.value, + * + * @return a constant describing the value type + * that this TypeCode object describes + * @throws org.omg.CORBA.TypeCodePackage.BadKind + * if this method + * is invoked on a non-value type TypeCode + * object + * @see CORBA package + * comments for unimplemented features + */ + + abstract public short type_modifier() throws BadKind ; + + /** + * Returns the TypeCode object that describes the concrete base type + * of the value type that this TypeCode object describes. + * Returns null if it doesn't have a concrete base type. + * + * @return the TypeCode object that describes the + * concrete base type of the value type + * that this TypeCode object describes + * @throws org.omg.CORBA.TypeCodePackage.BadKind if this method + * is invoked on a non-boxed value type TypeCode object + * @see CORBA package + * comments for unimplemented features + */ + + abstract public TypeCode concrete_base_type() throws BadKind ; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TypeCodeHolder.java b/omgapi/src/main/java/org/omg/CORBA/TypeCodeHolder.java new file mode 100644 index 000000000..cdd52d65e --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TypeCodeHolder.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for TypeCode. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a TypeCode object + * that is used to store "out" and "inout" parameters in IDL operations. + * If an IDL operation signature has an IDL TypeCode as an "out" + * or "inout" parameter, the programmer must pass an instance of + * TypeCodeHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myTypeCodeHolder is an instance of TypeCodeHolder, + * the value stored in its value field can be accessed with + * myTypeCodeHolder.value. + * + * @version 1.14, 09/09/97 + * @since JDK1.2 + */ +public final class TypeCodeHolder implements Streamable { + + /** + * The TypeCode value held by + * this TypeCodeHolder object. + */ + public TypeCode value; + + /** + * Constructs a new TypeCodeHolder object with its + * value field initialized to null. + */ + public TypeCodeHolder() { + } + + /** + * Constructs a new TypeCodeHolder object with its + * value field initialized to the given + * TypeCode object. + * @param initial the TypeCode object with which to initialize + * the value field of the newly-created + * TypeCodeHolder object + */ + public TypeCodeHolder(TypeCode initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in + * this TypeCodeHolder object + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire + */ + public void _read(InputStream input) { + value = input.read_TypeCode(); + } + + /** + * Marshals to output the value in + * this TypeCodeHolder object. + * + * @param output the OutputStream which will contain the CDR formatted data + */ + public void _write(OutputStream output) { + output.write_TypeCode(value); + } + + /** + * Returns the TypeCode corresponding to the value held in + * this TypeCodeHolder object. + * + * @return the TypeCode of the value held in + * this TypeCodeHolder object + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_TypeCode); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/BadKind.java b/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/BadKind.java new file mode 100644 index 000000000..2a81c4eb5 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/BadKind.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.TypeCodePackage; + +/** + * The exception BadKind is thrown when + * an inappropriate operation is invoked on a TypeCode object. For example, + * invoking the method discriminator_type() on an instance of + * TypeCode that does not represent an IDL union will cause the + * exception BadKind to be thrown. + * + * @see org.omg.CORBA.TypeCode + * @version 1.7, 03/18/98 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class BadKind extends org.omg.CORBA.UserException { + /** + * Constructs a BadKind exception with no reason message. + */ + public BadKind() { + super(); + } + + /** + * Constructs a BadKind exception with the specified + * reason message. + * @param reason the String containing a reason message + */ + public BadKind(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/Bounds.java b/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/Bounds.java new file mode 100644 index 000000000..bfbdb4725 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/Bounds.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.TypeCodePackage; + +/** + * Provides the TypeCode operations member_name(), + * member_type(), and member_label. + * These methods + * raise Bounds when the index parameter is greater than or equal + * to the number of members constituting the type. + * + * @version 1.7, 03/18/98 + * @since JDK1.2 + */ + +// @SuppressWarnings({"serial"}) +public final class Bounds extends org.omg.CORBA.UserException { + + /** + * Constructs a Bounds exception with no reason message. + */ + public Bounds() { + super(); + } + + /** + * Constructs a Bounds exception with the specified + * reason message. + * @param reason the String containing a reason message + */ + public Bounds(String reason) { + super(reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/package.html b/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/package.html new file mode 100644 index 000000000..b5715be80 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/TypeCodePackage/package.html @@ -0,0 +1,37 @@ + + + + + + + + +Provides the user-defined exceptions BadKind +and Bounds, which are thrown by methods in +in the class TypeCode. + + +

    Related Documentation

    + +For an overview, please see: + + + +@since JDK1.2 +@serial exclude + + diff --git a/omgapi/src/main/java/org/omg/CORBA/ULongLongSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/ULongLongSeqHelper.java new file mode 100644 index 000000000..8cd082b71 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ULongLongSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for ULongLongSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/ULongLongSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class ULongLongSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ULongLongSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, long[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static long[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ulonglong); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ULongLongSeqHelper.id (), "ULongLongSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static long[] read (org.omg.CORBA.portable.InputStream istream) + { + long value[] = null; + int _len0 = istream.read_long (); + value = new long[_len0]; + istream.read_ulonglong_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, long[] value) + { + ostream.write_long (value.length); + ostream.write_ulonglong_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ULongLongSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/ULongLongSeqHolder.java new file mode 100644 index 000000000..5a24e4120 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ULongLongSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for ULongLongSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/ULongLongSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:37 o'clock GMT+00:00 +*/ + +public final class ULongLongSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public long value[] = null; + + public ULongLongSeqHolder () + { + } + + public ULongLongSeqHolder (long[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ULongLongSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ULongLongSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ULongLongSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ULongSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/ULongSeqHelper.java new file mode 100644 index 000000000..594dc61d0 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ULongSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for ULongSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/ULongSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class ULongSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ULongSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, int[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static int[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ulong); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.ULongSeqHelper.id (), "ULongSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static int[] read (org.omg.CORBA.portable.InputStream istream) + { + int value[] = null; + int _len0 = istream.read_long (); + value = new int[_len0]; + istream.read_ulong_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, int[] value) + { + ostream.write_long (value.length); + ostream.write_ulong_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ULongSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/ULongSeqHolder.java new file mode 100644 index 000000000..0bd7a3ef5 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ULongSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for ULongSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/ULongSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class ULongSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public int value[] = null; + + public ULongSeqHolder () + { + } + + public ULongSeqHolder (int[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.ULongSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.ULongSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.ULongSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UNKNOWN.java b/omgapi/src/main/java/org/omg/CORBA/UNKNOWN.java new file mode 100644 index 000000000..88ab43108 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UNKNOWN.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * This exception is raised if an operation implementation + * throws a non-CORBA exception (such as an exception + * specific to the implementation's programming language), + * or if an operation raises a user exception that does not + * appear in the operation's raises expression. UNKNOWN is + * also raised if the server returns a system exception that + * is unknown to the client. (This can happen if the server + * uses a later version of CORBA than the client and new system + * exceptions have been added to the later version.)

    + * It contains a minor code, which gives more detailed information about + * what caused the exception, and a completion status. It may also contain + * a string describing the exception. + *

    + * See the section Minor + * Code Meanings to see the minor codes for this exception. + * + * @see documentation on + * Java IDL exceptions + * @version 1.10 07 Nov 1996 + */ + +public final class UNKNOWN extends SystemException { + /** + * Constructs an UNKNOWN exception with a default minor code + * of 0, a completion state of CompletionStatus.COMPLETED_NO, + * and a null description. + */ + public UNKNOWN() { + this(""); + } + + /** + * Constructs an UNKNOWN exception with the specified description message, + * a minor code of 0, and a completion state of COMPLETED_NO. + * @param s the String containing a detail message + */ + public UNKNOWN(String s) { + this(s, 0, CompletionStatus.COMPLETED_NO); + } + + /** + * Constructs an UNKNOWN exception with the specified + * minor code and completion status. + * @param minor the minor code + * @param completed the completion status + */ + public UNKNOWN(int minor, CompletionStatus completed) { + this("", minor, completed); + } + + /** + * Constructs an UNKNOWN exception with the specified description + * message, minor code, and completion status. + * @param s the String containing a description message + * @param minor the minor code + * @param completed the completion status + */ + public UNKNOWN(String s, int minor, CompletionStatus completed) { + super(s, minor, completed); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UNSUPPORTED_POLICY.java b/omgapi/src/main/java/org/omg/CORBA/UNSUPPORTED_POLICY.java new file mode 100644 index 000000000..9382fe0ac --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UNSUPPORTED_POLICY.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * One of the PolicyErrorCodes which would be filled if + * the requested Policy is understood to be valid by the + * ORB, but is not currently supported. + * + * @author rip-dev + * @version 1.15 07/27/07 + */ +public interface UNSUPPORTED_POLICY { + /** + * The Error code for PolicyError exception. + */ + final short value = (short) (1L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/UNSUPPORTED_POLICY_VALUE.java b/omgapi/src/main/java/org/omg/CORBA/UNSUPPORTED_POLICY_VALUE.java new file mode 100644 index 000000000..ffb4a8762 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UNSUPPORTED_POLICY_VALUE.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A PolicyErrorCode which would be filled if the value + * requested for the Policy is of a + * valid type and within the valid range for that type, but this valid value + * is not currently supported. + * + * @author rip-dev + * @version 1.14 07/27/07 + */ +public interface UNSUPPORTED_POLICY_VALUE { + /** + * The Error code for PolicyError exception. + */ + final short value = (short) (4L); +}; diff --git a/omgapi/src/main/java/org/omg/CORBA/UShortSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/UShortSeqHelper.java new file mode 100644 index 000000000..1085b4647 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UShortSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for UShortSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/UShortSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class UShortSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/UShortSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, short[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static short[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_ushort); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.UShortSeqHelper.id (), "UShortSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static short[] read (org.omg.CORBA.portable.InputStream istream) + { + short value[] = null; + int _len0 = istream.read_long (); + value = new short[_len0]; + istream.read_ushort_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, short[] value) + { + ostream.write_long (value.length); + ostream.write_ushort_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UShortSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/UShortSeqHolder.java new file mode 100644 index 000000000..501322629 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UShortSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for UShortSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/UShortSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class UShortSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public short value[] = null; + + public UShortSeqHolder () + { + } + + public UShortSeqHolder (short[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.UShortSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.UShortSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.UShortSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UnionMember.java b/omgapi/src/main/java/org/omg/CORBA/UnionMember.java new file mode 100644 index 000000000..9d1057f60 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UnionMember.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/UnionMember.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; + +/** + * A description in the Interface Repository of a member of an IDL union. + */ +// @SuppressWarnings({"serial"}) +public final class UnionMember implements org.omg.CORBA.portable.IDLEntity { + // instance variables + + /** + * The name of the union member described by this + * UnionMember object. + * @serial + */ + public String name; + + /** + * The label of the union member described by this + * UnionMember object. + * @serial + */ + public org.omg.CORBA.Any label; + + /** + * The type of the union member described by this + * UnionMember object. + * @serial + */ + public org.omg.CORBA.TypeCode type; + + /** + * The typedef that represents the IDL type of the union member described by this + * UnionMember object. + * @serial + */ + public org.omg.CORBA.IDLType type_def; + + // constructors + + /** + * Constructs a new UnionMember object with its fields initialized + * to null. + */ + public UnionMember() { } + + /** + * Constructs a new UnionMember object with its fields initialized + * to the given values. + * + * @param __name a String object with the name of this + * UnionMember object + * @param __label an Any object with the label of this + * UnionMember object + * @param __type a TypeCode object describing the type of this + * UnionMember object + * @param __type_def an IDLType object that represents the + * IDL type of this UnionMember object + */ + public UnionMember(String __name, org.omg.CORBA.Any __label, org.omg.CORBA.TypeCode __type, org.omg.CORBA.IDLType __type_def) { + name = __name; + label = __label; + type = __type; + type_def = __type_def; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UnionMemberHelper.java b/omgapi/src/main/java/org/omg/CORBA/UnionMemberHelper.java new file mode 100644 index 000000000..f323afa26 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UnionMemberHelper.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for UnionMember. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/UnionMemberHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:43 o'clock GMT+00:00 +*/ + +abstract public class UnionMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/UnionMember:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.UnionMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.UnionMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[1] = new org.omg.CORBA.StructMember ( + "label", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[2] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[3] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.UnionMemberHelper.id (), "UnionMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.UnionMember read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.UnionMember value = new org.omg.CORBA.UnionMember (); + value.name = istream.read_string (); + value.label = istream.read_any (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.UnionMember value) + { + ostream.write_string (value.name); + ostream.write_any (value.label); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UnknownUserException.java b/omgapi/src/main/java/org/omg/CORBA/UnknownUserException.java new file mode 100644 index 000000000..d475c338a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UnknownUserException.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * A class that contains user exceptions returned by the server. + * When the client uses the DII to make an invocation, any user exception + * returned from the server is enclosed in an Any object contained in the + * UnknownUserException object. This is available from the + * Environment object returned by the method Request.env. + * + * @see documentation on + * Java IDL exceptions + * @see Request + */ + +public final class UnknownUserException extends UserException { + + /** The Any instance that contains the actual user exception thrown + * by the server. + * @serial + */ + public Any except; + + /** + * Constructs an UnknownUserException object. + */ + public UnknownUserException() { + super(); + } + + /** + * Constructs an UnknownUserException object that contains the given + * Any object. + * + * @param a an Any object that contains a user exception returned + * by the server + */ + public UnknownUserException(Any a) { + super(); + except = a; + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/UnknownUserExceptionHelper.java b/omgapi/src/main/java/org/omg/CORBA/UnknownUserExceptionHelper.java new file mode 100644 index 000000000..9c1ca34fd --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UnknownUserExceptionHelper.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for UnknownUserException. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/UnknownUserExceptionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from CORBA.idl +* Thursday, August 24, 2000 5:52:22 PM PDT +*/ + +abstract public class UnknownUserExceptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/UnknownUserException:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.UnknownUserException that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.UnknownUserException extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [1]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + _members0[0] = new org.omg.CORBA.StructMember ( + "except", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.CORBA.UnknownUserExceptionHelper.id (), "UnknownUserException", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.UnknownUserException read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.UnknownUserException value = new org.omg.CORBA.UnknownUserException (); + // read and discard the repository ID + istream.read_string (); + value.except = istream.read_any (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.UnknownUserException value) + { + // write the repository ID + ostream.write_string (id ()); + ostream.write_any (value.except); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UnknownUserExceptionHolder.java b/omgapi/src/main/java/org/omg/CORBA/UnknownUserExceptionHolder.java new file mode 100644 index 000000000..37a60add9 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UnknownUserExceptionHolder.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The Holder for UnknownUserException. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/UnknownUserExceptionHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from CORBA.idl +* Thursday, August 24, 2000 5:52:22 PM PDT +*/ + +public final class UnknownUserExceptionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.UnknownUserException value = null; + + public UnknownUserExceptionHolder () + { + } + + public UnknownUserExceptionHolder (org.omg.CORBA.UnknownUserException initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.UnknownUserExceptionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.UnknownUserExceptionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.UnknownUserExceptionHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/UserException.java b/omgapi/src/main/java/org/omg/CORBA/UserException.java new file mode 100644 index 000000000..e1c14ad32 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/UserException.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The root class for CORBA IDL-defined user exceptions. + * All CORBA user exceptions are checked exceptions, which + * means that they need to + * be declared in method signatures. + * + * @see documentation on + * Java IDL exceptions + * @version 1.28 09/09/97 + */ +public abstract class UserException extends java.lang.Exception implements org.omg.CORBA.portable.IDLEntity { + + /** + * Constructs a UserException object. + * This method is called only by subclasses. + */ + protected UserException() { + super(); + } + + /** + * Constructs a UserException object with a + * detail message. This method is called only by subclasses. + * + * @param reason a String object giving the reason for this + * exception + */ + protected UserException(String reason) { + super(reason); + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/VM_ABSTRACT.java b/omgapi/src/main/java/org/omg/CORBA/VM_ABSTRACT.java new file mode 100644 index 000000000..451689f8b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/VM_ABSTRACT.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Defines the code used to represent an Abstract interface in +* a typecode. +* This is one of the possible results of the type_modified +* method on the TypeCode interface. +* @see org.omg.CORBA.TypeCode +* @version 1.11 07/27/07 +*/ +public interface VM_ABSTRACT { + /** The value representing an abstract interface value type in + * a typecode. + */ + final short value = (short) (2L); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/VM_CUSTOM.java b/omgapi/src/main/java/org/omg/CORBA/VM_CUSTOM.java new file mode 100644 index 000000000..5e1e06862 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/VM_CUSTOM.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Defines the code used to represent a custom marshalled value type in +* a typecode. +* This is one of the possible results of the type_modifier +* method on the TypeCode interface. +* @see org.omg.CORBA.TypeCode +* @version 1.12 07/27/07 +*/ +public interface VM_CUSTOM { + /** The value representing a custom marshalled value type in + * a typecode. + */ + final short value = (short) (1L); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/VM_NONE.java b/omgapi/src/main/java/org/omg/CORBA/VM_NONE.java new file mode 100644 index 000000000..9aac2a6d5 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/VM_NONE.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * Defines the code used to represent the one of the values of a value type + * in a typecode. + * + * @author OMG + * @see org.omg.CORBA.TypeCode + * @version 1.12 07/27/07 + * @since JDK1.2 + */ + + +public interface VM_NONE { + /** + * The value representing the value type in a typecode as per + * CORBA 2.3 spec. + */ + final short value = (short) (0L); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/VM_TRUNCATABLE.java b/omgapi/src/main/java/org/omg/CORBA/VM_TRUNCATABLE.java new file mode 100644 index 000000000..4e472eb71 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/VM_TRUNCATABLE.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** Defines the code used to represent a truncatable value type in +* a typecode. A value type is truncatable if it inherits "safely" +* from another value type, which means it can be cast to a more +* general inherited type. +* This is one of the possible results of the type_modifier +* method on the TypeCode interface. +* @see org.omg.CORBA.TypeCode +* @version 1.12 07/27/07 +*/ +public interface VM_TRUNCATABLE { + /** The value representing a truncatable value type in + * a typecode. + */ + final short value = (short) (3L); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ValueBaseHelper.java b/omgapi/src/main/java/org/omg/CORBA/ValueBaseHelper.java new file mode 100644 index 000000000..27105ac8a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ValueBaseHelper.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + + /** + * The Helper for ValueBase. For more information on + * Helper files, see + * "Generated Files: Helper Files".

    + */ + +package org.omg.CORBA; + +abstract public class ValueBaseHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueBase:1.0"; + + public static void insert (org.omg.CORBA.Any a, java.io.Serializable that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static java.io.Serializable extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (TCKind.tk_value); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static java.io.Serializable read (org.omg.CORBA.portable.InputStream istream) + { + return ((org.omg.CORBA_2_3.portable.InputStream)istream).read_value (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable value) + { + ((org.omg.CORBA_2_3.portable.OutputStream)ostream).write_value (value); + } + + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ValueBaseHolder.java b/omgapi/src/main/java/org/omg/CORBA/ValueBaseHolder.java new file mode 100644 index 000000000..e9a0fb66a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ValueBaseHolder.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * The Holder for ValueBase. For more information on + * Holder files, see + * "Generated Files: Holder Files".

    + * A Holder class for a java.io.Serializable + * that is used to store "out" and "inout" parameters in IDL methods. + * If an IDL method signature has an IDL ValueBase as an "out" + * or "inout" parameter, the programmer must pass an instance of + * ValueBaseHolder as the corresponding + * parameter in the method invocation; for "inout" parameters, the programmer + * must also fill the "in" value to be sent to the server. + * Before the method invocation returns, the ORB will fill in the + * value corresponding to the "out" value returned from the server. + *

    + * If myValueBaseHolder is an instance of ValueBaseHolder, + * the value stored in its value field can be accessed with + * myValueBaseHolder.value. + * + */ +public final class ValueBaseHolder implements Streamable { + + /** + * The java.io.Serializable value held by this + * ValueBaseHolder object. + */ + public java.io.Serializable value; + + /** + * Constructs a new ValueBaseHolder object with its + * value field initialized to 0. + */ + public ValueBaseHolder() { + } + + /** + * Constructs a new ValueBaseHolder object with its + * value field initialized to the given + * java.io.Serializable. + * @param initial the java.io.Serializable with which to initialize + * the value field of the newly-created + * ValueBaseHolder object + */ + public ValueBaseHolder(java.io.Serializable initial) { + value = initial; + } + + /** + * Reads from input and initalizes the value in the Holder + * with the unmarshalled data. + * + * @param input the InputStream containing CDR formatted data from the wire + */ + public void _read(InputStream input) { + value = ((org.omg.CORBA_2_3.portable.InputStream)input).read_value(); + } + + /** + * Marshals to output the value in the Holder. + * + * @param output the OutputStream which will contain the CDR formatted data + */ + public void _write(OutputStream output) { + ((org.omg.CORBA_2_3.portable.OutputStream)output).write_value(value); + } + + /** + * Returns the TypeCode object + * corresponding to the value held in the Holder. + * + * @return the TypeCode of the value held in the holder + */ + public org.omg.CORBA.TypeCode _type() { + return ORB.init().get_primitive_tc(TCKind.tk_value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ValueMember.java b/omgapi/src/main/java/org/omg/CORBA/ValueMember.java new file mode 100644 index 000000000..33e9338a6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ValueMember.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CORBA/ValueMember.java + * From: ./ir.idl + * Date: Fri Aug 28 16:03:31 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + */ + +package org.omg.CORBA; + +/** + * A description in the Interface Repository of + * a member of a value object. + */ +// @SuppressWarnings({"serial"}) +public final class ValueMember implements org.omg.CORBA.portable.IDLEntity { + + // instance variables + + /** + * The name of the value member described by this + * ValueMember object. + * @serial + */ + public String name; + + /** + * The repository ID of the value member described by + * this ValueMember object; + * @serial + */ + public String id; + + /** + * The repository ID of the value in which this member + * is defined. + * @serial + */ + public String defined_in; + + /** + * The version of the value in which this member is defined. + * @serial + */ + public String version; + + /** + * The type of of this value member. + * @serial + */ + public org.omg.CORBA.TypeCode type; + + /** + * The typedef that represents the IDL type of the value + * member described by this ValueMember object. + * @serial + */ + public org.omg.CORBA.IDLType type_def; + + /** + * The type of access (public, private) for the value + * member described by this ValueMember object. + * @serial + */ + public short access; + // constructors + + /** + * Constructs a default ValueMember object. + */ + public ValueMember() { } + + /** + * Constructs a ValueMember object initialized with + * the given values. + * + *@param __name The name of the value member described by this + * ValueMember object. + *@param __id The repository ID of the value member described by + * this ValueMember object; + *@param __defined_in The repository ID of the value in which this member + * is defined. + *@param __version The version of the value in which this member is defined. + *@param __type The type of of this value member. + *@param __type_def The typedef that represents the IDL type of the value + * member described by this ValueMember object. + *@param __access The type of access (public, private) for the value + * member described by this ValueMember object. + */ + public ValueMember(String __name, String __id, String __defined_in, String __version, org.omg.CORBA.TypeCode __type, org.omg.CORBA.IDLType __type_def, short __access) { + name = __name; + id = __id; + defined_in = __defined_in; + version = __version; + type = __type; + type_def = __type_def; + access = __access; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/ValueMemberHelper.java b/omgapi/src/main/java/org/omg/CORBA/ValueMemberHelper.java new file mode 100644 index 000000000..bb3844bae --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/ValueMemberHelper.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for ValueMember. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/ValueMemberHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:44 o'clock GMT+00:00 +*/ + +abstract public class ValueMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueMember:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.ValueMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [7]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.IDLTypeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VisibilityHelper.id (), "Visibility", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "access", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.omg.CORBA.ValueMemberHelper.id (), "ValueMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.ValueMember read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.ValueMember value = new org.omg.CORBA.ValueMember (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = org.omg.CORBA.IDLTypeHelper.read (istream); + value.access = istream.read_short (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueMember value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + ostream.write_short (value.access); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/VersionSpecHelper.java b/omgapi/src/main/java/org/omg/CORBA/VersionSpecHelper.java new file mode 100644 index 000000000..ee1f89afb --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/VersionSpecHelper.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for VersionSpec. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/VersionSpecHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:43 o'clock GMT+00:00 +*/ + +abstract public class VersionSpecHelper +{ + private static String _id = "IDL:omg.org/CORBA/VersionSpec:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/VisibilityHelper.java b/omgapi/src/main/java/org/omg/CORBA/VisibilityHelper.java new file mode 100644 index 000000000..5c84c0a16 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/VisibilityHelper.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for Visibility. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/VisibilityHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:44 o'clock GMT+00:00 +*/ + + +// orbos 98-01-18: Objects By Value -- begin +abstract public class VisibilityHelper +{ + private static String _id = "IDL:omg.org/CORBA/Visibility:1.0"; + + public static void insert (org.omg.CORBA.Any a, short that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static short extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.VisibilityHelper.id (), "Visibility", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static short read (org.omg.CORBA.portable.InputStream istream) + { + short value = (short)0; + value = istream.read_short (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, short value) + { + ostream.write_short (value); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/WCharSeqHelper.java b/omgapi/src/main/java/org/omg/CORBA/WCharSeqHelper.java new file mode 100644 index 000000000..58bd6f049 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/WCharSeqHelper.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for WCharSeq. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/WCharSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public abstract class WCharSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/WCharSeq:1.0"; + + public static void insert (org.omg.CORBA.Any a, char[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static char[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_wchar); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.WCharSeqHelper.id (), "WCharSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static char[] read (org.omg.CORBA.portable.InputStream istream) + { + char value[] = null; + int _len0 = istream.read_long (); + value = new char[_len0]; + istream.read_wchar_array (value, 0, _len0); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, char[] value) + { + ostream.write_long (value.length); + ostream.write_wchar_array (value, 0, value.length); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/WCharSeqHolder.java b/omgapi/src/main/java/org/omg/CORBA/WCharSeqHolder.java new file mode 100644 index 000000000..d2756d9c3 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/WCharSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for WCharSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/WCharSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class WCharSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public char value[] = null; + + public WCharSeqHolder () + { + } + + public WCharSeqHolder (char[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.WCharSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.WCharSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.WCharSeqHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/WStringValueHelper.java b/omgapi/src/main/java/org/omg/CORBA/WStringValueHelper.java new file mode 100644 index 000000000..9204f9a39 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/WStringValueHelper.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** +* The Helper for WStringValue. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +*/ + +package org.omg.CORBA; + +/** +* org/omg/CORBA/WStringValueHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from orb.idl +* 31 May 1999 22:27:30 o'clock GMT+00:00 +* +* The class definition has been modified to conform to the following +* OMG specifications : +*

    +*/ + +public class WStringValueHelper implements org.omg.CORBA.portable.BoxedValueHelper +{ + private static String _id = "IDL:omg.org/CORBA/WStringValue:1.0"; + + private static WStringValueHelper _instance = new WStringValueHelper (); + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + __typeCode = org.omg.CORBA.ORB.init ().create_wstring_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_value_box_tc (_id, "WStringValue", __typeCode); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + if (!(istream instanceof org.omg.CORBA_2_3.portable.InputStream)) { + throw new org.omg.CORBA.BAD_PARAM(); } + return (String) ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (_instance); + } + + public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream) + { + String tmp; + tmp = istream.read_wstring (); + return (java.io.Serializable) tmp; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + if (!(ostream instanceof org.omg.CORBA_2_3.portable.OutputStream)) { + throw new org.omg.CORBA.BAD_PARAM(); } + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, _instance); + } + + public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable value) + { + if (!(value instanceof String)) { + throw new org.omg.CORBA.MARSHAL(); } + String valueType = (String) value; + ostream.write_wstring (valueType); + } + + public String get_id () + { + return _id; + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/WrongTransaction.java b/omgapi/src/main/java/org/omg/CORBA/WrongTransaction.java new file mode 100644 index 000000000..483bfa7a6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/WrongTransaction.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** + * The CORBA WrongTransaction user-defined exception. + * This exception is thrown only by the methods + * Request.get_response + * and ORB.get_next_response when they are invoked + * from a transaction scope that is different from the one in + * which the client originally sent the request. + * See the OMG Transaction Service Specification for details. + * + * @see documentation on + * Java IDL exceptions + */ + +// @SuppressWarnings({"serial"}) +public final class WrongTransaction extends UserException { + /** + * Constructs a WrongTransaction object with an empty detail message. + */ + public WrongTransaction() { + super(WrongTransactionHelper.id()); + } + + /** + * Constructs a WrongTransaction object with the given detail message. + * @param reason The detail message explaining what caused this exception to be thrown. + */ + public WrongTransaction(String reason) { + super(WrongTransactionHelper.id() + " " + reason); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/WrongTransactionHelper.java b/omgapi/src/main/java/org/omg/CORBA/WrongTransactionHelper.java new file mode 100644 index 000000000..575d0ab56 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/WrongTransactionHelper.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The Helper for WrongTransaction. For more information on +* Helper files, see +* "Generated Files: Helper Files".

    +* org/omg/CORBA/WrongTransactionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from CORBA.idl +* Thursday, August 24, 2000 5:32:50 PM PDT +*/ + +abstract public class WrongTransactionHelper +{ + private static String _id = "IDL:omg.org/CORBA/WrongTransaction:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.WrongTransaction that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.WrongTransaction extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + __typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.CORBA.WrongTransactionHelper.id (), "WrongTransaction", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.WrongTransaction read (org.omg.CORBA.portable.InputStream istream) + { + org.omg.CORBA.WrongTransaction value = new org.omg.CORBA.WrongTransaction (); + // read and discard the repository ID + istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.WrongTransaction value) + { + // write the repository ID + ostream.write_string (id ()); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/WrongTransactionHolder.java b/omgapi/src/main/java/org/omg/CORBA/WrongTransactionHolder.java new file mode 100644 index 000000000..e4c253fd7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/WrongTransactionHolder.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* The Holder for WrongTransaction. For more information on +* Holder files, see +* "Generated Files: Holder Files".

    +* org/omg/CORBA/WrongTransactionHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from CORBA.idl +* Thursday, August 24, 2000 5:32:50 PM PDT +*/ + +public final class WrongTransactionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.omg.CORBA.WrongTransaction value = null; + + public WrongTransactionHolder () + { + } + + public WrongTransactionHolder (org.omg.CORBA.WrongTransaction initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.WrongTransactionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.WrongTransactionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.WrongTransactionHelper.type (); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/_IDLTypeStub.java b/omgapi/src/main/java/org/omg/CORBA/_IDLTypeStub.java new file mode 100644 index 000000000..bfd813845 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/_IDLTypeStub.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Stub for IDLType. For more information on +* Stub files, see +* "Generated Files: Stubs".

    +* org/omg/CORBA/_IDLTypeStub.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl. +* 03 June 1999 11:33:44 o'clock GMT+00:00 +*/ + +public class _IDLTypeStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.IDLType +{ + /** + * Constructs a default _IDLTypeStub object. + * NOTE: If the default constructor is used, the + * object is useless until the method _set_delegate + * has been called. + */ + // NOTE: This constructor is not required according to the spec. Only JCK expects it now. + public _IDLTypeStub () + { + super (); + } + + /** + * Constructs an _IDLTypeStub object initialized + * with the given Delegate object. + * + * @param delegate a Delegate object + */ + // NOTE: This constructor is not required according to the spec. We keep it as a convenience method. + public _IDLTypeStub (org.omg.CORBA.portable.Delegate delegate) + { + super (); + _set_delegate (delegate); + } + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("_get_type", true); + _in = _invoke (_out); + org.omg.CORBA.TypeCode __result = _in.read_TypeCode (); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return type (); + } finally { + _releaseReply (_in); + } + } // type + + + // read interface + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("_get_def_kind", true); + _in = _invoke (_out); + org.omg.CORBA.DefinitionKind __result = org.omg.CORBA.DefinitionKindHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return def_kind (); + } finally { + _releaseReply (_in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("destroy", true); + _in = _invoke (_out); + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + destroy (); + } finally { + _releaseReply (_in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) + { + try + { + String str = s.readUTF (); + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init ().string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } catch (java.io.IOException e) {} + } + + private void writeObject (java.io.ObjectOutputStream s) + { + try + { + String str = org.omg.CORBA.ORB.init ().object_to_string (this); + s.writeUTF (str); + } catch (java.io.IOException e) {} + } +} // class _IDLTypeStub diff --git a/omgapi/src/main/java/org/omg/CORBA/_PolicyStub.java b/omgapi/src/main/java/org/omg/CORBA/_PolicyStub.java new file mode 100644 index 000000000..dae0aa35f --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/_PolicyStub.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Stub for Policy. For more information on +* Stub files, see +* "Generated Files: Stubs".

    +* org/omg/CORBA/_PolicyStub.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl. +* Saturday, July 17, 1999 12:26:20 AM PDT +*/ + +public class _PolicyStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.Policy +{ + /** Constructors + * NOTE: If the default constructor is used, the + * object is useless until _set_delegate (...) + * is called. + */ + public _PolicyStub () + { + super (); + } + + /** Constructs a _PolicyStub object initialized + * with the given Delegate object. + * + * @param delegate a Delegate Object + */ + public _PolicyStub (org.omg.CORBA.portable.Delegate delegate) + { + super (); + _set_delegate (delegate); + } + + + /** Returns the constant value that corresponds to the + * type of the policy object. The values of + * the polivy objectys are allocated by the OMG. + * New values for PolicyType should be obtained from the OMG by + * sending mail to request@omg.org. In general the constant + * values that are allocated are defined in conjunction with + * the definition of the corresponding policy object. + * @return the constant value that corresponds to the type of + * the policy object. + */ + public int policy_type () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("_get_policy_type", true); + _in = _invoke (_out); + int __result = org.omg.CORBA.PolicyTypeHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return policy_type (); + } finally { + _releaseReply (_in); + } + } // policy_type + + + /** Copies the policy object. The copy does not retain any + * relationships that the policy had with any domain or object. + * @return the copy of the policy object. + */ + public org.omg.CORBA.Policy copy () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("copy", true); + _in = _invoke (_out); + org.omg.CORBA.Policy __result = org.omg.CORBA.PolicyHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return copy (); + } finally { + _releaseReply (_in); + } + } // copy + + + /** Destroys the policy object. It is the responsibility of + * the policy object to determine whether it can be destroyed. + */ + public void destroy () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("destroy", true); + _in = _invoke (_out); + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + destroy (); + } finally { + _releaseReply (_in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/Policy:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) + { + try + { + String str = s.readUTF (); + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init ().string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } catch (java.io.IOException e) {} + } + + private void writeObject (java.io.ObjectOutputStream s) + { + try + { + String str = org.omg.CORBA.ORB.init ().object_to_string (this); + s.writeUTF (str); + } catch (java.io.IOException e) {} + } +} // class _PolicyStub diff --git a/omgapi/src/main/java/org/omg/CORBA/package.html b/omgapi/src/main/java/org/omg/CORBA/package.html new file mode 100644 index 000000000..2d1dfb3c6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/package.html @@ -0,0 +1,978 @@ + + + + +package + + +Provides the mapping of the OMG CORBA APIs to the JavaTM +programming language, including the class ORB, which is implemented +so that a programmer can use it as a fully-functional Object Request Broker +(ORB). + +

    For a precise list of supported sections of official CORBA specifications with which +the Java[TM] Platform, Standard Edition 6, complies, see Official Specifications for CORBA support in +Java[TM] SE 6. + + +

    General Information

    +The information in this section is information relevant to someone who +compiles Interface Definition Language (IDL) files and uses the +ORB to write clients and servers. + +

    The classes and interfaces described in this section can be put into +four groups: ORB classes, Exceptions, Helper classes, +and Holder classes. + +

    +The ORB Class

    + +

    An ORB handles (or brokers) method invocations between a client and +the method's implementation on a server. Because the client and server +may be anywhere on a network, and because the invocation and implementation +may be written in different programming languages, an ORB does a great +deal of work behind the scenes to accomplish this communication. + +

    Most of what an ORB does is completely transparent to the user, and a major +portion of the CORBA package consists of classes used by the ORB +behind the scenes. The result is that most programmers will use only a +small part of this package directly. In fact, most programmers will use +only a few methods from the ORB class, some exceptions, and +occasionally, +a holder class. +

    +ORB Methods

    + +

    Before an application can enter the CORBA environment, it must first: +

    +

      +
    • Be initialized into the ORB and possibly the object adapter (POA) environments. +
    • Get references to ORB object (for use in future ORB operations) +and perhaps other objects (including the root POA or some Object Adapter objects). +
    +

    The following operations are provided to initialize applications and obtain + the appropriate object references: +

    +

      +
    • Operations providing access to the ORB, which are discussed in this + section. +
    • Operations providing access to Object Adapters, Interface Repository, + Naming Service, and other Object Services. These operations are described + in Other Classes. +
    +

    +When an application requires a CORBA environment it needs a mechanism to +get an ORB object reference and possibly an OA object reference +(such as the root POA). This serves two purposes. First, it initializes +an application into the ORB and OA environments. Second, it returns the +ORB object reference and the OA object reference to the application +for use in future ORB and OA operations. + +

    In order to obtain an ORB object reference, applications call +the ORB.init operation. The parameters to the call can comprise an +identifier for the ORB for which the object reference is required, + and an arg_list, which is used to allow environment-specific data to be + passed into the call. + +

    These are the ORB methods + that provide access to the ORB: +

      +
    • +init() + +
    • +init(String [] args, Properties props) + +
    • +init(Applet app, Properties props) +
    + +

    Using the init() method without parameters initiates +a singleton ORB, which can only +give typecode creation anys needed in code generated +in Helper classes by idlj. + +

    Applications require a portable means by which to obtain their +initial object references. References are required for the root +POA, POA Current, Interface Repository, and various Object Services +instances. The functionality required by the application is similar + to that provided by the Naming Service. However, the OMG does not + want to mandate that the Naming Service be made available to all + applications in order that they may be portably initialized. + Consequently, the operations shown in this section provide a + simplified, local version of the Naming Service that applications + can use to obtain a small, defined set of object references which + are essential to its operation. Because only a small well-defined + set of objects are expected with this mechanism, the naming context + can be flattened to be a single-level name space. This simplification + results in only two operations being defined to achieve the functionality + required. + +

    Initial references are obtained via two operations provided in +the ORB object interface, providing facilities to list and +resolve initial object references. These are: +

      +
    • +resolve_initial_references(String name) +
    • +list_initial_services() +
    • +register_initial_reference(String id, +org.omg.CORBA.Object obj) +
    + +

    An example that uses some of these methods is +Getting Started with Java IDL. + +

    +Exceptions

    +Exceptions in Java IDL are similar to those in any code written in the +Java programming language. If a method is defined to throw an exception, +then any code using that method must have a try/catch +block and handle that exception when it is thrown. + +

    The documentation on Java +IDL exceptions has more information and explains the difference between +system exceptions and user-defined exceptions. + +

    The following is a list of the system exceptions (which are unchecked +exceptions inheriting through +org.omg.CORBA.SystemException from +java.lang.RuntimeException) that are defined in the package +org.omg.CORBA: +

    
    +        BAD_CONTEXT
    +        BAD_INV_ORDER
    +        BAD_OPERATION
    +        BAD_PARAM
    +        BAD_TYPECODE
    +        COMM_FAILURE
    +        DATA_CONVERSION
    +        FREE_MEM
    +        IMP_LIMIT
    +        INITIALIZE
    +        INTERNAL
    +        INTF_REPOS
    +        INVALID_TRANSACTION
    +        INV_FLAG
    +        INV_IDENT
    +        INV_OBJREF
    +        INV_POLICY
    +        MARSHAL
    +        NO_IMPLEMENT
    +        NO_MEMORY
    +        NO_PERMISSION
    +        NO_RESOURCES
    +        NO_RESPONSE
    +        OBJECT_NOT_EXIST
    +        OBJ_ADAPTER
    +        PERSIST_STORE
    +        TRANSACTION_REQUIRED
    +        TRANSACTION_ROLLEDBACK
    +        TRANSIENT
    +        UNKNOWN
    +
    +

    +The following is a list of user-defined exceptions defined in the package +org.omg.CORBA. +

    
    +        Bounds
    +        UnknownUserException
    +        WrongTransaction 
    +        PolicyError
    +
    + +

    Subpackages

    +There are some packages inside the CORBA package with +"Package" as part of their names. These packages are generally quite small +because all they do is provide exceptions or classes for use by interfaces +and classes in the CORBA package. + +

    For example, the package +org.omg.CORBA.TypeCodePackage contains +two exceptions thrown by methods in the class TypeCode. These +exceptions are: +

      +
    • +BadKind + +
    • +Bounds +
    +The package +org.omg.CORBA.ORBPackage contains two exceptions: +
      +
    • +InvalidName + +
    • +InconsistentTypeCode +
    + +

    Another package that is a subpackage of CORBA is the +portable package. It +provides a set of ORB APIs that makes it +possible for code generated by one vendor's IDL compiler to run +on another vendor's ORB. + + + + +

    +Holder classes

    + + +

    Support for out and inout parameter passing modes requires the use of +additional holder +classes. Because the Java programming language does not support out or +inout parameters, holder classes are needed as a means of passing a parameter +that can be modified. To support portable stubs and skeletons, holder classes also implement + the org.omg.CORBA.portable.Streamable + interface. + +

    Holder classes are named by appending "Holder" to the name of the type. + The name of the type refers to its name in the Java programming language. For + example, a holder class for the interface named Account in the Java programming + language would be named AccountHolder. + + +

    Holder classes are available for all of the basic IDL + datatypes in the org.omg.CORBA package. So, for example, + there are already-defined classes for LongHolder, ShortHolder, + FloatHolder, and so on. Classes are also generated for + all named user-defined IDL types except those defined by typedefs. + (Note that in this context user defined includes types that are + defined in OMG specifications such as those for the Interface + Repository, and other OMG services.) + + +

    Each holder class has: +

    +

      +
    • a constructor from an instance +
    • a default constructor +
    • a public instance member, value which is the typed value. +
    • a method for reading an input stream and assigning the contents to the +type's value field +
    • a method for writing the value of the value field to an output stream +
    • a method for getting the typecode of the type +
    + +

    The default constructor sets the value field to the default value for the +type as defined by the Java language: +

    +

      +
    • false for boolean +
    • 0 for numeric and char types +
    • null for strings and object references +
    + + + +

    +As an example, if the interface Account, defined in OMG IDL, +were mapped to the Java programming language, the following holder class +would be generated: +

    +public final class AccountHolder implements 
    +    org.omg.CORBA.portable.Streamable
    +{
    +  // field that holds an Account object
    +  public Account value = null;
    +
    +  // default constructor
    +  public AccountHolder ()
    +  {
    +  }
    +  
    +  // creates a new AccountHolder from initialValue
    +  public AccountHolder (Account initialValue)
    +  {
    +    value = initialValue;
    +  }
    +  
    +  // reads the contents of i and assigns the contents to value
    +  public void _read (org.omg.CORBA.portable.InputStream i)
    +  {
    +    value = AccountHelper.read (i);
    +  }
    +
    +  // writes value to o
    +  public void _write (org.omg.CORBA.portable.OutputStream o)
    +  {
    +    AccountHelper.write (o, value);
    +  }
    + 
    +  // returns the typecode for Account
    +  public org.omg.CORBA.TypeCode _type ()
    +  {
    +    return AccountHelper.type ();
    +  }
    +
    +}
    +
    + +

    For more information on Holder classes, see Chapter 1.4, Mapping for +Basic Types in the +OMG IDL to Java Language Mapping. The Holder classes defined +in the package org.omg.CORBA are: +

    +     AnyHolder
    +     AnySeqHolder
    +     BooleanHolder
    +     BooleanSeqHolder
    +     ByteHolder
    +     CharHolder
    +     CharSeqHolder
    +     CurrentHolder
    +     DoubleHolder
    +     DoubleSeqHolder
    +     FixedHolder
    +     FloatHolder
    +     FloatSeqHolder
    +     IntHolder
    +     LongHolder
    +     LongLongSeqHolder
    +     LongSeqHolder
    +     ObjectHolder
    +     OctetSeqHolder
    +     ParameterModeHolder
    +     PolicyErrorHolder
    +     PolicyListHolder
    +     PrincipalHolder
    +     ServiceInformationHolder
    +     ShortHolder
    +     ShortSeqHolder
    +     StringHolder
    +     StringSeqHolder
    +     TypeCodeHolder
    +     ULongLongSeqHolder
    +     ULongSeqHolder
    +     UnknownUserExceptionHolder
    +     UShortSeqHolder
    +     ValueBaseHolder
    +     WCharSeqHolder
    +     WrongTransactionHolder
    +     WStringSeqHolder
    +
    +
    + +

    Helper Classes

    +

    Helper files supply several static methods needed to manipulate the type. + These include: +

    +

      +
    • Any insert and extract operations for the type +
    • getting the repository id +
    • getting the typecode +
    • reading and writing the type from and to a stream +
    • implement the ValueHelper interface (if it is a user-defined + value type) +
    + +

    The helper class for a mapped IDL interface or abstract interface + also include narrow operation(s). The static narrow method allows + an org.omg.CORBA.Object to be narrowed to the object reference + of a more specific type. The IDL exception CORBA.BAD_PARAM + is thrown if the narrow fails because the object reference does not + support the requested type. A different system exception is raised + to indicate other kinds of errors. Trying to narrow a null will always + succeed with a return value of null. Generally, the only helper method an application programmer uses is +the narrow method. The other methods are normally used behind +the scenes and are transparent to the programmer. + +

    Helper classes +fall into two broad categories, helpers for value types and +helpers for non value types. Because all of the helper +classes in one category +provide the same methods, one generic explanation of each +category of helper classes is presented here. + +

    +When OMG IDL is mapped to the Java programming language, +a "helper" class is generated for each user-defined type. +This generated class will have the name of the user-defined type with +the suffix Helper appended. For example, if the +interface Account is defined in OMG IDL, the +idlj compiler will automatically generate a class named +AccountHelper. The AccountHelper class +will contain the static methods needed for manipulating instances of the type, +in this case, Account objects. + + + +

    The narrow Method

    +When an object is the return value for a method, it is returned in the +form of a generic object, either an org.omg.CORBA.Object object +or a java.lang.Object object. This object must be cast to its +more specific type before it can be operated on. For example, an +Account object will be returned as a generic object and must +be narrowed to an Account object so that Account +methods may be called on it. +

    +The narrow method has two forms, one that takes an +org.omg.CORBA.Object object and one that takes a +java.lang.Object object. Whether the interface is abstract or +not determines which narrow method its helper class will provide. +The helper class for an interface +that is not abstract will have a narrow method that takes a CORBA +object, whereas the narrow method for an interface that is abstract +will +take an object in the Java programming language. The helper class for a +non-abstract interface that has at least one abstract base interface will provide +both versions of the narrow method. +

    The Hello World +tutorial uses a narrow method that looks +like this: +

    +

    +        // create and initialize the ORB
    +        ORB orb = ORB.init(args, null);
    +
    +        // get the root naming context
    +        org.omg.CORBA.Object objRef = 
    +            orb.resolve_initial_references("NameService");
    +        // Use NamingContextExt instead of NamingContext. This is 
    +        // part of latest Inter-Operable naming Service.  
    +        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
    + 
    +        // resolve the Object Reference in Naming
    +        String name = "Hello";
    +        helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));
    +
    + + +

    Example of a Basic Helper Class

    +A basic helper class, for purposes of this explanation, is one with +the methods that are provided by every helper class, plus a narrow +method if the type defined in OMG IDL maps to an interface in the Java +programming language. Types that are not value types will have a basic +helper class generated for them. +

    +For example, assuming that the interface Account is not a +value type IDL type and is also not an abstract interface and has no +abstract base interfaces, its AccountHelper class will look +like this: +

    +abstract public class AccountHelper
    +{
    +  private static String  _id = "IDL:Account:1.0";
    +
    +  // inserts an Account object into an Any object
    +  public static void insert (org.omg.CORBA.Any a, Account that)
    +  {
    +    org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
    +    a.type (type ());
    +    write (out, that);
    +    a.read_value (out.create_input_stream (), type ());
    +  }
    +
    +  // extracts an Account object from an Any object
    +  public static Account extract (org.omg.CORBA.Any a)
    +  {
    +    return read (a.create_input_stream ());
    +  }
    +
    +  
    +  private static org.omg.CORBA.TypeCode __typeCode = null;
    +  // gets the typecode for this type
    +  synchronized public static org.omg.CORBA.TypeCode type ()
    +  {
    +    if (__typeCode == null)
    +    {
    +      __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (AccountHelper.id (), "Account");
    +    }
    +    return __typeCode;
    +  }
    +
    +  // gets the repository id for this type
    +  public static String id ()
    +  {
    +    return _id;
    +  }
    +
    +  // reads an Account object from an input stream
    +  public static Account read (org.omg.CORBA.portable.InputStream istream)
    +  {
    +    return narrow (istream.read_Object (_AccountStub.class));
    +  }
    +
    +  // writes an Account object to an outputstream
    +  public static void write (org.omg.CORBA.portable.OutputStream ostream, Account value)
    +  {
    +    ostream.write_Object ((org.omg.CORBA.Object) value);
    +  }
    +
    +  // converts (narrows) an Object to an Account object
    +  public static Account narrow (org.omg.CORBA.Object obj)
    +  {
    +    if (obj == null)
    +      return null;
    +    else if (obj instanceof Account)
    +      return (Account)obj;
    +    else if (!obj._is_a (id ()))
    +      throw new org.omg.CORBA.BAD_PARAM ();
    +    else
    +    {
    +      org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
    +      _AccountStub stub = new _AccountStub ();
    +      stub._set_delegate(delegate);
    +      return stub;
    +    }
    +  }
    +
    +}
    +
    +

    + +

    Value Type Helper Classes

    +A helper class for a value type includes different renderings of +the same methods generated for non-value type methods. The main difference + is that value types are types that can be +passed by value as parameters or return values of a method, which means that +they must be serializable. +

    Assuming that Address is a value type, the +AddressHelper class will look like this: +

    +abstract public class AddressHelper
    +{
    +  private static String  _id = "IDL:Address:1.0";
    +
    +  // same as for non-value type
    +  public static void insert (org.omg.CORBA.Any a, Address that)
    +  {
    +    org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
    +    a.type (type ());
    +    write (out, that);
    +    a.read_value (out.create_input_stream (), type ());
    +  }
    +
    +  // same as for non-value type
    +  public static Address extract (org.omg.CORBA.Any a)
    +  {
    +    return read (a.create_input_stream ());
    +  }
    +
    +  private static org.omg.CORBA.TypeCode __typeCode = null;
    +  private static boolean __active = false;
    +  
    +  // getting the typecode for the type
    +  synchronized public static org.omg.CORBA.TypeCode type ()
    +  {
    +    if (__typeCode == null)
    +    {
    +      synchronized (org.omg.CORBA.TypeCode.class)
    +      {
    +        if (__typeCode == null)
    +        {
    +          if (__active)
    +          {
    +            return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
    +          }
    +          __active = true;
    +          org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[0];
    +          org.omg.CORBA.TypeCode _tcOf_members0 = null;
    +          __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "Address", org.omg.CORBA.VM_NONE.value, null, _members0);
    +          __active = false;
    +        }
    +      }
    +    }
    +    return __typeCode;
    +  }
    +
    +  // same as for non-value type
    +  public static String id ()
    +  {
    +    return _id;
    +  }
    +
    +  // reads a serializable instance of Address from the given input stream
    +  public static Address read (org.omg.CORBA.portable.InputStream istream)
    +  {
    +    return (Address)((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ());
    +  }
    +
    +  // writes a serializable instance of Address to the given output stream
    +  public static void write (org.omg.CORBA.portable.OutputStream ostream, Address value)
    +  {
    +    ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ());
    +  }
    +
    +
    +}
    +
    + +

    The Helper classes defined in the package org.omg.CORBA are: +

    
    +     AnySeqHelper
    +     BooleanSeqHelper
    +     CharSeqHelper
    +     CompletionStatusHelper
    +     CurrentHelper
    +     DefinitionKindHelper
    +     DoubleSeqHelper
    +     FieldNameHelper
    +     FloatSeqHelper
    +     IdentifierHelper
    +     IDLTypeHelper
    +     LongLongSeqHelper
    +     LongSeqHelper
    +     NameValuePairHelper
    +     ObjectHelper
    +     OctetSeqHelper
    +     ParameterModeHelper
    +     PolicyErrorCodeHelper
    +     PolicyErrorHelper
    +     PolicyHelper
    +     PolicyListHelper
    +     PolicyTypeHelper
    +     RepositoryIdHelper
    +     ServiceDetailHelper
    +     ServiceInformationHelper
    +     SetOverrideTypeHelper
    +     ShortSeqHelper
    +     StringSeqHelper
    +     StringValueHelper
    +     StructMemberHelper
    +     ULongLongSeqHelper
    +     ULongSeqHelper
    +     UnionMemberHelper
    +     UnknownUserExceptionHelper
    +     UShortSeqHelper
    +     ValueBaseHelper
    +     ValueMemberHelper
    +     VersionSpecHelper
    +     VisibilityHelper
    +     WCharSeqHelper
    +     WrongTransactionHelper
    +     WStringSeqHelper
    +     WStringValueHelper
    +
    +
    + +

    +Other Classes

    +The other classes and interfaces in the CORBA package, which are +used behind the scenes, can be put into four groups. Three of the groups +are used with requests in some capacity, and the fourth group, concerning +the Interface Repository, is a category by itself. +

    +Classes Created by an ORB

    +The first group contains classes that are created by an ORB and contain +information used in request operations. +
      +
    • +TCKind -- indicates the kind (datatype) for a TypeCode +object + +
    • +TypeCode -- indicates a datatype and possibly other information + +
    • +Any -- contains a value and its typecode + +
    • +NamedValue -- contains a name, an Any object, and an +argument mode flag. NamedValue objects contain information about +method arguments, method return values, or a context. + +
    • +ContextList -- a list of strings that describe the contexts that +need to be resolved and sent with an invocation + +
    • +ExceptionList -- a list of TypeCodes for exceptions that +may be thrown by a method + +
    • +Environment -- a container for the exception thrown during a method +invocation + +
    • +Context -- a list of NamedValue objects used to pass +auxiliary information from client to server + +
    • +NVList -- a list of NamedValue objects, used to pass +arguments or get results +
    + +

    +Classes That Deal with Requests

    +The second group of classes deals with requests: +
      +
    • +Object -- the base class for all CORBA object references + +
    • +Request -- the main class in the DII, which contains methods for +adding arguments to the request, for accessing information about the method +being invoked (the method name, its arguments, exceptions it throws, and +so on), and for making invocations on the request + +
    • +DynamicImplementation -- the base class for server implementations +using the DSI. It has the method invoke, which is used by an +implementation +of this class to determine the state of a ServerRequest object +and to set its result or exception + +
    • +ServerRequest -- captures the explicit state of a request for +the Dynamic Skeleton Interface +
    + +

    +Interfaces That Serve as Constants

    +The third group contains interfaces that serve as constants. The IDL-to-Java +mapping mandates that IDL enums are mapped to a Java class with the enumerated +values represented as public static final fields in that class (e.g. +DefinitionKind). +On the other hand IDL constants defined outside of an IDL interface are +mapped to a Java interface for each constant. + +

    This is why several interfaces in the org.omg.CORBA package +consist of a single field, value, which is a short. This +field is a constant used for such things as an error code or value modifier. +For example, the value field of the interface BAD_POLICY +is one of the possible reasons for the exception PolicyError to +be thrown. To specify this error code, you would use BAD_POLICY.value. + +

    The exception PolicyError uses the value field of +the following interfaces as its possible error codes. +

      +
    • +BAD_POLICY + +
    • +BAD_POLICY_TYPE + +
    • +BAD_POLICY_VALUE + +
    • +UNSUPPORTED_POLICY + +
    • +UNSUPPORTED_POLICY_VALUE +
    +The method TypeCode.type_modifier returns the value field +of one of the following interfaces. The VM in the names of these +interfaces stands for "value modifier." +
      +
    • +VM_NONE + +
    • +VM_ABSTRACT + +
    • +VM_CUSTOM + +
    • +VM_TRUNCATABLE +
    +The following constants are returned by a ValueMember object's +access method to denote the visibility of the ValueMember object. +
      +
    • +PRIVATE_MEMBER + +
    • +PUBLIC_MEMBER +
    +These flags, used in NamedValue objects or as parameters to methods, +are defined in the following interfaces: +
      +
    • +ARG_IN + +
    • +ARG_INOUT + +
    • +ARG_OUT + +
    • +CTX_RESTRICT_SCOPE +
    + +

    +Interface Repository Interfaces and Classes

    +A fourth group contains the Interface Repository interfaces and classes, +which are generated by the idlj compiler from the OMG IDL +interface ir.idl. The purpose of the Interface Repository is to +identify the interfaces stored in it so that they can be accessed by an +ORB. Each module, type, interface, attribute, operation, parameter, exception, +constant, and so on is described completely by the Interface Repository +API. + +

    An ORB does not require that there be an interface repository, and Java +IDL does not include one. Even though this release does not include an +implementation of an interface repository, the following IR classes and +interfaces have been included for the purpose of creating typecodes (see +create_value_tc, create_struct_tc, create_union_tc and create_exception_tc +methods in interface org.omg.CORBA.ORB): +
    &nbs +

      +
    • +IRObject + +
    • +IDLType + +
    • +DefinitionKind + +
    • +StructMember + +
    • +UnionMember + +
    • +ValueMember +
    + +
    +

    +Related Documentation

    +For overviews, guides, and a tutorial, please see: + + + + + +

    +

    +CORBA Features Not Implemented in Java IDL

    + +

    Some of the API included in org.omg subpackages is provided for +conformance with the current OMG CORBA specification but is not implemented +in Sun's release of the JDKTM. This enables +other JDK licensees to provide implementations of this API in standard +extensions and products. + +

    +

    Features That Throw NO_IMPLEMENT

    + +

    Some of the API included in org.omg subpackages throw +NO_IMPLEMENT exceptions for various reasons. Among these reasons +are: +

    +

      +
    • In some cases, for example LocalObject, the complete + implementation according to the specification indicates that + these API should throw NO_IMPLEMENT. +

      +

    • In most cases, for example methods in ORB.java, + methods that throw + NO_IMPLEMENT are actually implemented in subclasses + elsewhere in the ORB code. +

      +

    • In some cases, for example _get_interface_def() + and _get_interface, API are really not yet implemented. +
    + + + + +

    +General Summary of Features or API Not Implemented in This Release:

    + +
      +
    • +Interface Repository. An Interface Repository is not required for normal +operation of Java IDL. + +
    • +Java IDL does not support long double. + + +
    • +Policies (org.omg.CORBA.Policy) and methods for getting them are not implemented. + +
    • +Domain managers (org.omg.CORBA.DomainManager) and methods for +getting them are not implemented. + +
    • +Service Information org.omg.CORBA.ServiceInformation and ORB method public boolean get_service_information(short service_type, +ServiceInformationHolder +service_info) are not implemented. + +
    • ORB methods for supporting single-threading (perform_work, work_pending) are not implemented. + +
    • IDL contexts. +
    + +
    +

    +Specific List of Unimplemented Features in Package org.omg.CORBA

    + + +

    +Unimplemented Methods in package org.omg.CORBA:

    + +
      +
    • +ORB + +
        +
      • +public org.omg.CORBA.Policy create_policy(int type, org.omg.CORBA.Any +val) + + + +
      • +public void perform_work() + +
      • +public boolean work_pending() + +
      • +public org.omg.CORBA.Current get_current() + +
      • +create_operation_list + +
      • +get_default_context + +
      • +get_service_information + +
      • +obsolete DynAnys (deprecated in favor of DynamicAny package) + + +
      + + + +
    +@since JDK1.2 +@serial exclude + + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ApplicationException.java b/omgapi/src/main/java/org/omg/CORBA/portable/ApplicationException.java new file mode 100644 index 000000000..db91b497a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ApplicationException.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** +This class is used for reporting application level exceptions between ORBs and stubs. +*/ + +public class ApplicationException extends Exception { + /** + * Constructs an ApplicationException from the CORBA repository ID of the exception + * and an input stream from which the exception data can be read as its parameters. + * @param id the repository id of the user exception + * @param ins the stream which contains the user exception data + */ + public ApplicationException(String id, + InputStream ins) { + this.id = id; + this.ins = ins; + } + + /** + * Returns the CORBA repository ID of the exception + * without removing it from the exceptions input stream. + * @return The CORBA repository ID of this exception + */ + public String getId() { + return id; + } + + /** + * Returns the input stream from which the exception data can be read as its parameters. + * @return The stream which contains the user exception data + */ + public InputStream getInputStream() { + return ins; + } + + private String id; + private InputStream ins; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/BoxedValueHelper.java b/omgapi/src/main/java/org/omg/CORBA/portable/BoxedValueHelper.java new file mode 100644 index 000000000..a33a35b1a --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/BoxedValueHelper.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; +import java.io.Serializable; + +public interface BoxedValueHelper { + Serializable read_value(InputStream is); + void write_value(OutputStream os, Serializable value); + String get_id(); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/CustomValue.java b/omgapi/src/main/java/org/omg/CORBA/portable/CustomValue.java new file mode 100644 index 000000000..fa2930f44 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/CustomValue.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** + * Defines the base interface for all custom value types + * generated from IDL. + * + * All value types implement ValueBase either directly + * or indirectly by implementing either the StreamableValue + * or CustomValue interface. + * @author OMG + * @version 1.16 07/27/07 + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.CustomMarshal; +/** + * An extension of ValueBase that is implemented by custom value + * types. + */ +public interface CustomValue extends ValueBase, CustomMarshal { + +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/Delegate.java b/omgapi/src/main/java/org/omg/CORBA/portable/Delegate.java new file mode 100644 index 000000000..ddb0dc406 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/Delegate.java @@ -0,0 +1,395 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.Request; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.NVList; +import org.omg.CORBA.Context; +import org.omg.CORBA.ContextList; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.SystemException; + +/** + * Specifies a portable API for ORB-vendor-specific + * implementation of the org.omg.CORBA.Object methods. + * + * Each stub (proxy) contains a delegate + * object, to which all org.omg.CORBA.Object methods are forwarded. + * This allows a stub generated by one vendor's ORB to work with the delegate + * from another vendor's ORB. + * + * @see org.omg.CORBA.Object + * @author OMG + * @version 1.39 07/27/07 + */ + +public abstract class Delegate { + + /** + * Return an InterfaceDef for the object reference provided. + * @param self The object reference whose InterfaceDef needs to be returned + * @return the InterfaceDef + */ + public abstract org.omg.CORBA.Object get_interface_def( + org.omg.CORBA.Object self); + + /** + * Returns a duplicate of the object reference provided. + * @param obj The object reference whose duplicate needs to be returned + * @return the duplicate object reference + */ + public abstract org.omg.CORBA.Object duplicate(org.omg.CORBA.Object obj); + + /** + * Releases resources associated with the object reference provided. + * @param obj The object reference whose resources need to be released + */ + public abstract void release(org.omg.CORBA.Object obj); + + /** + * Checks if the object reference is an instance of the given interface. + * @param obj The object reference to be checked. + * @param repository_id The repository identifier of the interface + * to check against. + * @return true if the object reference supports the interface + */ + public abstract boolean is_a(org.omg.CORBA.Object obj, String repository_id); + + /** + * Determines whether the server object for the object reference has been + * destroyed. + * @param obj The object reference which delegated to this delegate. + * @return true if the ORB knows authoritatively that the server object does + * not exist, false otherwise + */ + public abstract boolean non_existent(org.omg.CORBA.Object obj); + + /** + * Determines if the two object references are equivalent. + * @param obj The object reference which delegated to this delegate. + * @param other The object reference to check equivalence against. + * @return true if the objects are CORBA-equivalent. + */ + public abstract boolean is_equivalent(org.omg.CORBA.Object obj, + org.omg.CORBA.Object other); + + /** + * Returns an ORB-internal identifier (hashcode) for this object reference. + * @param obj The object reference which delegated to this delegate. + * @param max specifies an upper bound on the hash value returned by + * the ORB. + * @return ORB-internal hash identifier for object reference + */ + public abstract int hash(org.omg.CORBA.Object obj, int max); + + /** + * Creates a Request instance for use in the Dynamic Invocation Interface. + * @param obj The object reference which delegated to this delegate. + * @param operation The name of the operation to be invoked using the + * Request instance. + * @return the created Request instance + */ + public abstract Request request(org.omg.CORBA.Object obj, String operation); + + /** + * Creates a Request instance for use in the Dynamic Invocation Interface. + * + * @param obj The object reference which delegated to this delegate. + * @param ctx The context to be used. + * @param operation The name of the operation to be + * invoked. + * @param arg_list The arguments to the operation in the + * form of an NVList. + * @param result A container for the result as a NamedValue. + * @return The created Request object. + * + */ + public abstract Request create_request(org.omg.CORBA.Object obj, + Context ctx, + String operation, + NVList arg_list, + NamedValue result); + + /** + * Creates a Request instance for use in the Dynamic Invocation Interface. + * + * @param obj The object reference which delegated to this delegate. + * @param ctx The context to be used. + * @param operation The name of the operation to be + * invoked. + * @param arg_list The arguments to the operation in the + * form of an NVList. + * @param result A container for the result as a NamedValue. + * @param exclist A list of possible exceptions the + * operation can throw. + * @param ctxlist A list of context strings that need + * to be resolved and sent with the + * Request. + * @return The created Request object. + */ + public abstract Request create_request(org.omg.CORBA.Object obj, + Context ctx, + String operation, + NVList arg_list, + NamedValue result, + ExceptionList exclist, + ContextList ctxlist); + + /** + * Provides a reference to the orb associated with its parameter. + * + * @param obj the object reference which delegated to this delegate. + * @return the associated orb. + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.ORB orb(org.omg.CORBA.Object obj) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Returns the Policy object of the specified type + * which applies to this object. + * + * @param self The object reference which delegated to this delegate. + * @param policy_type The type of policy to be obtained. + * @return A Policy object of the type specified by + * the policy_type parameter. + * @exception org.omg.CORBA.BAD_PARAM raised when the value of policy type + * is not valid either because the specified type is not supported by this + * ORB or because a policy object of that type is not associated with this + * Object. + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.Policy get_policy(org.omg.CORBA.Object self, + int policy_type) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * Retrieves the DomainManagers of this object. + * This allows administration services (and applications) to retrieve the + * domain managers, and hence the security and other policies applicable + * to individual objects that are members of the domain. + * + * @param self The object reference which delegated to this delegate. + * @return The list of immediately enclosing domain managers of this object. + * At least one domain manager is always returned in the list since by + * default each object is associated with at least one domain manager at + * creation. + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.DomainManager[] get_domain_managers( + org.omg.CORBA.Object + self) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * Associates the policies passed in + * with a newly created object reference that it returns. Only certain + * policies that pertain to the invocation of an operation at the client + * end can be overridden using this operation. Attempts to override any + * other policy will result in the raising of the CORBA::NO_PERMISSION + * exception. + * + * @param self The object reference which delegated to this delegate. + * @param policies A sequence of references to Policy objects. + * @param set_add Indicates whether these policies should be added + * onto any otheroverrides that already exist (ADD_OVERRIDE) in + * the object reference, or they should be added to a clean + * override free object reference (SET_OVERRIDE). + * @return A new object reference with the new policies associated with it. + * + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.Object set_policy_override(org.omg.CORBA.Object self, + org.omg.CORBA.Policy[] policies, + org.omg.CORBA.SetOverrideType set_add) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * Returns true if this object is implemented by a local servant. + * + * @param self The object reference which delegated to this delegate. + * @return true only if the servant incarnating this object is located in + * this Java VM. Return false if the servant is not local or the ORB + * does not support local stubs for this particular servant. The default + * behavior of is_local() is to return false. + */ + public boolean is_local(org.omg.CORBA.Object self) { + return false; + } + + /** + * Returns a Java reference to the servant which should be used for this + * request. servant_preinvoke() is invoked by a local stub. + * If a ServantObject object is returned, then its servant field + * has been set to an object of the expected type (Note: the object may + * or may not be the actual servant instance). The local stub may cast + * the servant field to the expected type, and then invoke the operation + * directly. The ServantRequest object is valid for only one invocation, + * and cannot be used for more than one invocation. + * + * @param self The object reference which delegated to this delegate. + * + * @param operation a string containing the operation name. + * The operation name corresponds to the operation name as it would be + * encoded in a GIOP request. + * + * @param expectedType a Class object representing the expected type of the servant. + * The expected type is the Class object associated with the operations + * class of the stub's interface (e.g. A stub for an interface Foo, + * would pass the Class object for the FooOperations interface). + * + * @return a ServantObject object. + * The method may return a null value if it does not wish to support + * this optimization (e.g. due to security, transactions, etc). + * The method must return null if the servant is not of the expected type. + */ + public ServantObject servant_preinvoke(org.omg.CORBA.Object self, + String operation, + Class expectedType) { + return null; + } + + /** + * servant_postinvoke() is invoked by the local stub after the operation + * has been invoked on the local servant. + * This method must be called if servant_preinvoke() returned a non-null + * value, even if an exception was thrown by the servant's method. + * For this reason, the call to servant_postinvoke() should be placed + * in a Java finally clause. + * + * @param self The object reference which delegated to this delegate. + * + * @param servant the instance of the ServantObject returned from + * the servant_preinvoke() method. + */ + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servant) { + } + + /** + * request is called by a stub to obtain an OutputStream for + * marshaling arguments. The stub must supply the operation name, + * and indicate if a response is expected (i.e is this a oneway + * call). + * + * @param self The object reference which delegated to this delegate. + * @param operation a string containing the operation name. + * The operation name corresponds to the operation name as it would be + * encoded in a GIOP request. + * @param responseExpected false if the operation is a one way operation, + * and true otherwise. + * @return OutputStream the OutputStream into which request arguments + * can be marshaled. + * @see portable + * package comments for unimplemented features + */ + public OutputStream request(org.omg.CORBA.Object self, + String operation, + boolean responseExpected) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * invoke is called by a stub to invoke an operation. The stub provides an + * OutputStream that was previously returned by a request() + * call. invoke returns an InputStream which contains the + * marshaled reply. If an exception occurs, invoke may throw an + * ApplicationException object which contains an InputStream from + * which the user exception state may be unmarshaled. + * + * @param self The object reference which delegated to this delegate. + * @param output the OutputStream which contains marshaled arguments + * @return input the InputStream from which reply parameters can be + * unmarshaled. + * @throws ApplicationException thrown when implementation throws + * (upon invocation) an exception defined as part of its remote method + * definition. + * @throws RemarshalException thrown when remarshalling fails. + * @see portable + * package comments for unimplemented features + */ + public InputStream invoke(org.omg.CORBA.Object self, + OutputStream output) + throws ApplicationException, RemarshalException { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * releaseReply may optionally be called by a stub to release a + * reply stream back to the ORB when the unmarshaling has + * completed. The stub passes the InputStream returned by + * invoke() or ApplicationException.getInputStream(). A null + * value may also be passed to releaseReply, in which case the + * method is a noop. + * + * @param self The object reference which delegated to this delegate. + * @param input the InputStream returned from invoke(). + * @see portable + * package comments for unimplemented features + */ + public void releaseReply(org.omg.CORBA.Object self, + InputStream input) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Provides the implementation to override the toString() method + * of the delegating CORBA object. + * + * @param self the object reference that delegated to this delegate + * @return a String object that represents the object + * reference that delegated to this Delegate + * object + */ + + public String toString(org.omg.CORBA.Object self) { + return self.getClass().getName() + ":" + this.toString(); + } + + /** + * Provides the implementation to override the hashCode() method + * of the delegating CORBA object. + * + * @param self the object reference that delegated to this delegate + * @return an int that represents the hashcode for the + * object reference that delegated to this Delegate + * object + */ + public int hashCode(org.omg.CORBA.Object self) { + return System.identityHashCode(self); + } + + /** + * Provides the implementation to override the equals(java.lang.Object obj) + * method of the delegating CORBA object. + * + * @param self the object reference that delegated to this delegate + * @param obj the Object with which to compare + * @return true if obj equals self; + * false otherwise + */ + public boolean equals(org.omg.CORBA.Object self, java.lang.Object obj) { + return (self == obj); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/IDLEntity.java b/omgapi/src/main/java/org/omg/CORBA/portable/IDLEntity.java new file mode 100644 index 000000000..8b902729b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/IDLEntity.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** + * An interface with no members whose only purpose is to serve as a marker + * indicating that an implementing class is a + * Java value type from IDL that has a corresponding Helper class. + * RMI IIOP serialization looks for such a marker to perform + * marshalling/unmarshalling. + **/ +public interface IDLEntity extends java.io.Serializable { + +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/IndirectionException.java b/omgapi/src/main/java/org/omg/CORBA/portable/IndirectionException.java new file mode 100644 index 000000000..5500288b7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/IndirectionException.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.SystemException; +/** + * The Indirection exception is a Java specific system exception. + * It is thrown when the ORB's input stream is called to demarshal + * a value that is encoded as an indirection that is in the process + * of being demarshaled. This can occur when the ORB input stream + * calls the ValueHandler to demarshal an RMI value whose state + * contains a recursive reference to itself. Because the top-level + * ValueHandler.read_value() call has not yet returned a value, + * the ORB input stream's indirection table does not contain an entry + * for an object with the stream offset specified by the indirection + * tag. The stream offset is returned in the exception's offset field. + * @see org.omg.CORBA_2_3.portable.InputStream + * @see org.omg.CORBA_2_3.portable.OuputStream + */ +public class IndirectionException extends SystemException { + + /** + * Points to the stream's offset. + */ + public int offset; + + /** + * Creates an IndirectionException with the right offset value. + * The stream offset is returned in the exception's offset field. + * This exception is constructed and thrown during reading + * recursively defined values off of a stream. + * + * @param offset the stream offset where recursion is detected. + */ + public IndirectionException(int offset){ + super("", 0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + this.offset = offset; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/InputStream.java b/omgapi/src/main/java/org/omg/CORBA/portable/InputStream.java new file mode 100644 index 000000000..f51a4b295 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/InputStream.java @@ -0,0 +1,306 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +/** + * InputStream is the Java API for reading IDL types + * from CDR marshal streams. These methods are used by the ORB to + * unmarshal IDL types as well as to extract IDL types out of Anys. + * The _array versions of the methods can be directly + * used to read sequences and arrays of IDL types. + * + * @version 1.12, 04/22/98 + * @since JDK1.2 + */ + +public abstract class InputStream extends java.io.InputStream +{ + /** + * Reads a boolean value from this input stream. + * + * @return the boolean value read from this input stream + */ + public abstract boolean read_boolean(); + /** + * Reads a char value from this input stream. + * + * @return the char value read from this input stream + */ + public abstract char read_char(); + /** + * Reads a wide char value from this input stream. + * + * @return the char value read from this input stream + */ + public abstract char read_wchar(); + /** + * Reads an octet (that is, a byte) value from this input stream. + * + * @return the byte value read from this input stream + */ + public abstract byte read_octet(); + /** + * Reads a short value from this input stream. + * + * @return the short value read from this input stream + */ + public abstract short read_short(); + /** + * Reads a unsigned short value from this input stream. + * + * @return the short value read from this input stream + */ + public abstract short read_ushort(); + /** + * Reads a CORBA long (that is, Java int) value from this input stream. + * + * @return the int value read from this input stream + */ + public abstract int read_long(); + /** + * Reads an unsigned CORBA long (that is, Java int) value from this input +stream. + * + * @return the int value read from this input stream + */ + public abstract int read_ulong(); + /** + * Reads a CORBA longlong (that is, Java long) value from this input stream. + * + * @return the long value read from this input stream + */ + public abstract long read_longlong(); + /** + * Reads a CORBA unsigned longlong (that is, Java long) value from this input +stream. + * + * @return the long value read from this input stream + */ + public abstract long read_ulonglong(); + /** + * Reads a float value from this input stream. + * + * @return the float value read from this input stream + */ + public abstract float read_float(); + /** + * Reads a double value from this input stream. + * + * @return the double value read from this input stream + */ + public abstract double read_double(); + /** + * Reads a string value from this input stream. + * + * @return the String value read from this input stream + */ + public abstract String read_string(); + /** + * Reads a wide string value from this input stream. + * + * @return the String value read from this input stream + */ + public abstract String read_wstring(); + + /** + * Reads an array of booleans from this input stream. + * @param value returned array of booleans. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_boolean_array(boolean[] value, int offset, int +length); + /** + * Reads an array of chars from this input stream. + * @param value returned array of chars. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_char_array(char[] value, int offset, int +length); + /** + * Reads an array of wide chars from this input stream. + * @param value returned array of wide chars. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_wchar_array(char[] value, int offset, int +length); + /** + * Reads an array of octets (that is, bytes) from this input stream. + * @param value returned array of octets (that is, bytes). + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_octet_array(byte[] value, int offset, int +length); + /** + * Reads an array of shorts from this input stream. + * @param value returned array of shorts. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_short_array(short[] value, int offset, int +length); + /** + * Reads an array of unsigned shorts from this input stream. + * @param value returned array of shorts. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_ushort_array(short[] value, int offset, int +length); + /** + * Reads an array of CORBA longs (that is, Java ints) from this input stream. + * @param value returned array of CORBA longs (that is, Java ints). + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_long_array(int[] value, int offset, int +length); + /** + * Reads an array of unsigned CORBA longs (that is, Java ints) from this input +stream. + * @param value returned array of CORBA longs (that is, Java ints). + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_ulong_array(int[] value, int offset, int +length); + /** + * Reads an array of CORBA longlongs (that is, Java longs) from this input +stream. + * @param value returned array of CORBA longs (that is, Java longs). + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_longlong_array(long[] value, int offset, int +length); + /** + * Reads an array of unsigned CORBA longlongs (that is, Java longs) from this +input stream. + * @param value returned array of CORBA longs (that is, Java longs). + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_ulonglong_array(long[] value, int offset, int +length); + /** + * Reads an array of floats from this input stream. + * @param value returned array of floats. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_float_array(float[] value, int offset, int +length); + /** + * Reads an array of boubles from this input stream. + * @param value returned array of doubles. + * @param offset offset on the stream. + * @param length length of buffer to read + */ + public abstract void read_double_array(double[] value, int offset, int +length); + + /** + * Reads a CORBA object from this input stream. + * + * @return the Object instance read from this input stream + */ + public abstract org.omg.CORBA.Object read_Object(); + /** + * Reads a TypeCode from this input stream. + * + * @return the TypeCode instance read from this input stream + */ + public abstract TypeCode read_TypeCode(); + /** + * Reads an Any from this input stream. + * + * @return the Any instance read from this input stream + */ + public abstract Any read_any(); + + /** + * Returns principle for invocation. + * @return Principle for invocation + * @deprecated Deprecated by CORBA 2.2. + */ + // @Deprecated + public org.omg.CORBA.Principal read_Principal() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + + /** + * @see portable + * package comments for unimplemented features + */ + public int read() throws java.io.IOException { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Reads a BigDecimal number. + * @return a java.math.BigDecimal number + */ + public java.math.BigDecimal read_fixed() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Reads a CORBA context from the stream. + * @return a CORBA context + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.Context read_Context() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + /* + * The following methods were added by orbos/98-04-03: Java to IDL + * Mapping. These are used by RMI over IIOP. + */ + + /** + * Unmarshals an object and returns a CORBA Object, + * which is an instance of the class passed as its argument. + * This class is the stub class of the expected type. + * + * @param clz The Class object for the stub class which + * corresponds to the type that is statistically expected, or + * the Class object for the RMI/IDL interface type that + * is statistically expected. + * @return an Object instance of clz read from this stream + * + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.Object read_Object(java.lang.Class + clz) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Returns the ORB that created this InputStream. + * + * @return the ORB object that created this stream + * + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.ORB orb() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/InvokeHandler.java b/omgapi/src/main/java/org/omg/CORBA/portable/InvokeHandler.java new file mode 100644 index 000000000..74f4d3dd7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/InvokeHandler.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** +This interface provides a dispatching mechanism for an incoming call. +It is invoked by the ORB to dispatch a request to a servant. +*/ + +public interface InvokeHandler { + /** + * Invoked by the ORB to dispatch a request to the servant. + * + * ORB passes the method name, an InputStream containing the + * marshalled arguments, and a ResponseHandler which the servant + * uses to construct a proper reply. + * + * Only CORBA SystemException may be thrown by this method. + * + * The method must return an OutputStream created by the + * ResponseHandler which contains the marshalled reply. + * + * A servant must not retain a reference to the ResponseHandler + * beyond the lifetime of a method invocation. + * + * Servant behaviour is defined as follows: + *

    1. Determine correct method, and unmarshal parameters from + * InputStream. + *

    2. Invoke method implementation. + *

    3. If no user exception, create a normal reply using + * ResponseHandler. + *

    4. If user exception occurred, create exception reply using + * ResponseHandler. + *

    5. Marshal reply into OutputStream returned by + * ResponseHandler. + *

    6. Return OutputStream to ORB. + *

    + * @param method The method name. + * @param input The InputStream containing the marshalled arguments. + * @param handler The ResponseHandler which the servant uses + * to construct a proper reply + * @return The OutputStream created by the + * ResponseHandler which contains the marshalled reply + * @throws SystemException is thrown when invocation fails due to a CORBA system exception. + */ + + OutputStream _invoke(String method, InputStream input, + ResponseHandler handler) + throws org.omg.CORBA.SystemException; +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ObjectImpl.java b/omgapi/src/main/java/org/omg/CORBA/portable/ObjectImpl.java new file mode 100644 index 000000000..9274bed5c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ObjectImpl.java @@ -0,0 +1,521 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.Request; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.NVList; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.ContextList; +import org.omg.CORBA.Context; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.SystemException; + + +/** + * The common base class for all stub classes; provides default implementations + * of the org.omg.CORBA.Object methods. All method implementations are + * forwarded to a Delegate object stored in the ObjectImpl + * instance. ObjectImpl allows for portable stubs because the + * Delegate can be implemented by a different vendor-specific ORB. + */ + +abstract public class ObjectImpl implements org.omg.CORBA.Object +{ + + /** + * The field that stores the Delegate instance for + * this ObjectImpl object. This Delegate + * instance can be implemented by a vendor-specific ORB. Stub classes, + * which are derived from this ObjectImpl class, can be + * portable because they delegate all of the methods called on them to this + * Delegate object. + */ + private transient Delegate __delegate; + + + /** + * Retrieves the reference to the vendor-specific Delegate + * object to which this ObjectImpl object delegates all + * methods invoked on it. + * + * @return the Delegate contained in this ObjectImpl instance + * @throws BAD_OPERATION if the delegate has not been set + * @see #_set_delegate + */ + public Delegate _get_delegate() { + if (__delegate == null) + throw new BAD_OPERATION("The delegate has not been set!"); + return __delegate; + } + + + /** + * Sets the Delegate for this ObjectImpl instance to the given + * Delegate object. All method invocations on this + * ObjectImpl object will be forwarded to this delegate. + * + * @param delegate the Delegate instance to which + * all method calls on this ObjectImpl object + * will be delegated; may be implemented by a third-party ORB + * @see #_get_delegate + */ + public void _set_delegate(Delegate delegate) { + __delegate = delegate; + } + + /** + * Retrieves a string array containing the repository identifiers + * supported by this ObjectImpl object. For example, + * for a stub, this method returns information about all the + * interfaces supported by the stub. + * + * @return the array of all repository identifiers supported by this + * ObjectImpl instance + */ + public abstract String[] _ids(); + + + /** + * Returns a duplicate of this ObjectImpl object. + * + * @return an orb.omg.CORBA.Object object that is + * a duplicate of this object + */ + public org.omg.CORBA.Object _duplicate() { + return _get_delegate().duplicate(this); + } + + /** + * Releases the resources associated with this ObjectImpl object. + */ + public void _release() { + _get_delegate().release(this); + } + + /** + * Checks whether the object identified by the given repository + * identifier is an ObjectImpl object. + * + * @param repository_id a String object with the repository + * identifier to check + * @return true if the object identified by the given + * repository id is an instance of ObjectImpl; + * false otherwise + */ + public boolean _is_a(String repository_id) { + return _get_delegate().is_a(this, repository_id); + } + + /** + * Checks whether the the given ObjectImpl object is + * equivalent to this ObjectImpl object. + * + * @param that an instance of ObjectImpl to compare with + * this ObjectImpl object + * @return true if the given object is equivalent + * to this ObjectImpl object; + * false otherwise + */ + public boolean _is_equivalent(org.omg.CORBA.Object that) { + return _get_delegate().is_equivalent(this, that); + } + + /** + * Checks whether the server object for this ObjectImpl + * object has been destroyed. + * + * @return true if the ORB knows authoritatively that the + * server object does not exist; false otherwise + */ + public boolean _non_existent() { + return _get_delegate().non_existent(this); + } + + /** + * Retrieves the hash code that serves as an ORB-internal identifier for + * this ObjectImpl object. + * + * @param maximum an int indicating the upper bound on the hash + * value returned by the ORB + * @return an int representing the hash code for this + * ObjectImpl object + */ + public int _hash(int maximum) { + return _get_delegate().hash(this, maximum); + } + + /** + * Creates a Request object containing the given method + * that can be used with the Dynamic Invocation Interface. + * + * @param operation the method to be invoked by the new Request + * object + * @return a new Request object initialized with the + * given method + */ + public Request _request(String operation) { + return _get_delegate().request(this, operation); + } + + /** + * Creates a Request object that contains the given context, + * method, argument list, and container for the result. + * + * @param ctx the Context for the request + * @param operation the method that the new Request + * object will invoke + * @param arg_list the arguments for the method; an NVList + * in which each argument is a NamedValue object + * @param result a NamedValue object to be used for + * returning the result of executing the request's method + * @return a new Request object initialized with the + * given context, method, argument list, and container for the + * return value + */ + public Request _create_request(Context ctx, + String operation, + NVList arg_list, + NamedValue result) { + return _get_delegate().create_request(this, + ctx, + operation, + arg_list, + result); + } + + /** + * Creates a Request object that contains the given context, + * method, argument list, container for the result, exceptions, and + * list of property names to be used in resolving the context strings. + * This Request object is for use in the Dynamic + * Invocation Interface. + * + * @param ctx the Context object that contains the + * context strings that must be resolved before they are + * sent along with the request + * @param operation the method that the new Request + * object will invoke + * @param arg_list the arguments for the method; an NVList + * in which each argument is a NamedValue object + * @param result a NamedValue object to be used for + * returning the result of executing the request's method + * @param exceptions a list of the exceptions that the given method + * throws + * @param contexts a list of the properties that are needed to + * resolve the contexts in ctx; the strings in + * contexts are used as arguments to the method + * Context.get_values, + * which returns the value associated with the given property + * @return a new Request object initialized with the + * given context strings to resolve, method, argument list, + * container for the result, exceptions, and list of property + * names to be used in resolving the context strings + */ + public Request _create_request(Context ctx, + String operation, + NVList arg_list, + NamedValue result, + ExceptionList exceptions, + ContextList contexts) { + return _get_delegate().create_request(this, + ctx, + operation, + arg_list, + result, + exceptions, + contexts); + } + + /** + * Retrieves the interface definition for this ObjectImpl + * object. + * + * @return the org.omg.CORBA.Object instance that is the + * interface definition for this ObjectImpl object + */ + public org.omg.CORBA.Object _get_interface_def() + { + // First try to call the delegate implementation class's + // "Object get_interface_def(..)" method (will work for JDK1.2 ORBs). + // Else call the delegate implementation class's + // "InterfaceDef get_interface(..)" method using reflection + // (will work for pre-JDK1.2 ORBs). + + org.omg.CORBA.portable.Delegate delegate = _get_delegate(); + try { + // If the ORB's delegate class does not implement + // "Object get_interface_def(..)", this will call + // get_interface_def(..) on portable.Delegate. + return delegate.get_interface_def(this); + } + catch( org.omg.CORBA.NO_IMPLEMENT ex ) { + // Call "InterfaceDef get_interface(..)" method using reflection. + try { + Class[] argc = { org.omg.CORBA.Object.class }; + java.lang.reflect.Method meth = + delegate.getClass().getMethod("get_interface", argc); + Object[] argx = { this }; + return (org.omg.CORBA.Object)meth.invoke(delegate, argx); + } + catch( java.lang.reflect.InvocationTargetException exs ) { + Throwable t = exs.getTargetException(); + if (t instanceof Error) { + throw (Error) t; + } + else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + else { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } catch( RuntimeException rex ) { + throw rex; + } catch( Exception exr ) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } + } + + /** + * Returns a reference to the ORB associated with this object and + * its delegate. This is the ORB object that created + * the delegate. + * + * @return the ORB instance that created the + * Delegate object contained in this + * ObjectImpl object + */ + public org.omg.CORBA.ORB _orb() { + return _get_delegate().orb(this); + } + + + /** + * Retrieves the Policy object for this + * ObjectImpl object that has the given + * policy type. + * + * @param policy_type an int indicating the policy type + * @return the Policy object that is the specified policy type + * and that applies to this ObjectImpl object + * @see org.omg.CORBA.PolicyOperations#policy_type + */ + public org.omg.CORBA.Policy _get_policy(int policy_type) { + return _get_delegate().get_policy(this, policy_type); + } + + /** + * Retrieves a list of the domain managers for this + * ObjectImpl object. + * + * @return an array containing the DomainManager + * objects for this instance of ObjectImpl + */ + public org.omg.CORBA.DomainManager[] _get_domain_managers() { + return _get_delegate().get_domain_managers(this); + } + + /** + * Sets this ObjectImpl object's override type for + * the given policies to the given instance of + * SetOverrideType. + * + * @param policies an array of Policy objects with the + * policies that will replace the current policies or be + * added to the current policies + * @param set_add either SetOverrideType.SET_OVERRIDE, + * indicating that the given policies will replace any existing + * ones, or SetOverrideType.ADD_OVERRIDE, indicating + * that the given policies should be added to any existing ones + * @return an Object with the given policies replacing or + * added to its previous policies + */ + public org.omg.CORBA.Object + _set_policy_override(org.omg.CORBA.Policy[] policies, + org.omg.CORBA.SetOverrideType set_add) { + return _get_delegate().set_policy_override(this, policies, + set_add); + } + + /** + * Checks whether this ObjectImpl object is implemented + * by a local servant. If so, local invocation API's may be used. + * + * @return true if this object is implemented by a local + * servant; false otherwise + */ + public boolean _is_local() { + return _get_delegate().is_local(this); + } + + /** + * Returns a Java reference to the local servant that should be used for sending + * a request for the method specified. If this ObjectImpl + * object is a local stub, it will invoke the _servant_preinvoke + * method before sending a request in order to obtain the + * ServantObject instance to use. + *

    + * If a ServantObject object is returned, its servant + * field has been set to an object of the expected type (Note: the object may + * or may not be the actual servant instance). The local stub may cast + * the servant field to the expected type, and then invoke the operation + * directly. The ServantRequest object is valid for only one + * invocation and cannot be used for more than one invocation. + * + * @param operation a String containing the name of the method + * to be invoked. This name should correspond to the method name as + * it would be encoded in a GIOP request. + * + * @param expectedType a Class object representing the + * expected type of the servant that is returned. This expected + * type is the Class object associated with the + * operations class for the stub's interface. For example, a + * stub for an interface Foo would pass the + * Class object for the FooOperations + * interface. + * + * @return (1) a ServantObject object, which may or may + * not be the actual servant instance, or (2) null if + * (a) the servant is not local or (b) the servant has ceased to + * be local due to a ForwardRequest from a POA ServantManager + * @throws org.omg.CORBA.BAD_PARAM if the servant is not the expected type + */ + public ServantObject _servant_preinvoke(String operation, + Class expectedType) { + return _get_delegate().servant_preinvoke(this, operation, + expectedType); + } + + /** + * Is called by the local stub after it has invoked an operation + * on the local servant that was previously retrieved from a + * call to the method _servant_preinvoke. + * The _servant_postinvoke method must be called + * if the _servant_preinvoke + * method returned a non-null value, even if an exception was thrown + * by the method invoked by the servant. For this reason, the call + * to the method _servant_postinvoke should be placed + * in a Java finally clause. + * + * @param servant the instance of the ServantObject + * returned by the _servant_preinvoke method + */ + public void _servant_postinvoke(ServantObject servant) { + _get_delegate().servant_postinvoke(this, servant); + } + + /* + * The following methods were added by orbos/98-04-03: Java to IDL + * Mapping. These are used by RMI over IIOP. + */ + + /** + * Returns an OutputStream object to use for marshalling + * the arguments of the given method. This method is called by a stub, + * which must indicate if a response is expected, that is, whether or not + * the call is oneway. + * + * @param operation a String giving the name of the method. + * @param responseExpected a boolean -- true if the + * request is not one way, that is, a response is expected + * @return an OutputStream object for dispatching the request + */ + public OutputStream _request(String operation, + boolean responseExpected) { + return _get_delegate().request(this, operation, responseExpected); + } + + /** + * Invokes an operation and returns an InputStream + * object for reading the response. The stub provides the + * OutputStream object that was previously returned by a + * call to the _request method. The method specified + * as an argument to _request when it was + * called previously is the method that this method invokes. + *

    + * If an exception occurs, the _invoke method may throw an + * ApplicationException object that contains an InputStream from + * which the user exception state may be unmarshalled. + * + * @param output an OutputStream object for dispatching the request + * @return an InputStream object containing the marshalled + * response to the method invoked + * @throws ApplicationException if the invocation + * meets application-defined exception + * @throws RemarshalException if the invocation leads + * to a remarshalling error + * @see #_request + */ + public InputStream _invoke(OutputStream output) + throws ApplicationException, RemarshalException { + return _get_delegate().invoke(this, output); + } + + /** + * Releases the given + * reply stream back to the ORB when unmarshalling has + * completed after a call to the method _invoke. + * Calling this method is optional for the stub. + * + * @param input the InputStream object that was returned + * by the _invoke method or the + * ApplicationException.getInputStream method; + * may be null, in which case this method does + * nothing + * @see #_invoke + */ + public void _releaseReply(InputStream input) { + _get_delegate().releaseReply(this, input); + } + + /** + * Returns a String object that represents this + * ObjectImpl object. + * + * @return the String representation of this object + */ + public String toString() { + if ( __delegate != null ) + return __delegate.toString(this); + else + return getClass().getName() + ": no delegate set"; + } + + /** + * Returns the hash code for this ObjectImpl object. + * + * @return the hash code for this object + */ + public int hashCode() { + if ( __delegate != null ) + return __delegate.hashCode(this); + else + return System.identityHashCode(this); + } + + /** + * Compares this ObjectImpl object with the given one + * for equality. + * + *@param obj the object with which to compare this object + *@return true if the two objects are equal; + * false otherwise + */ + public boolean equals(java.lang.Object obj) { + if ( __delegate != null ) + return __delegate.equals(this, obj); + else + return (this==obj); + } +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/OutputStream.java b/omgapi/src/main/java/org/omg/CORBA/portable/OutputStream.java new file mode 100644 index 000000000..0a4389123 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/OutputStream.java @@ -0,0 +1,272 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +/** + * OuputStream is the Java API for writing IDL types + * to CDR marshal streams. These methods are used by the ORB to + * marshal IDL types as well as to insert IDL types into Anys. + * The _array versions of the methods can be directly + * used to write sequences and arrays of IDL types. + * + * @version 1.13, 04/22/98 + * @since JDK1.2 + */ + +public abstract class OutputStream extends java.io.OutputStream +{ + /** + * Returns an input stream with the same buffer. + *@return an input stream with the same buffer. + */ + public abstract InputStream create_input_stream(); + + /** + * Writes a boolean value to this stream. + * @param value the value to be written. + */ + public abstract void write_boolean(boolean value); + /** + * Writes a char value to this stream. + * @param value the value to be written. + */ + public abstract void write_char(char value); + /** + * Writes a wide char value to this stream. + * @param value the value to be written. + */ + public abstract void write_wchar(char value); + /** + * Writes a CORBA octet (i.e. byte) value to this stream. + * @param value the value to be written. + */ + public abstract void write_octet(byte value); + /** + * Writes a short value to this stream. + * @param value the value to be written. + */ + public abstract void write_short(short value); + /** + * Writes an unsigned short value to this stream. + * @param value the value to be written. + */ + public abstract void write_ushort(short value); + /** + * Writes a CORBA long (i.e. Java int) value to this stream. + * @param value the value to be written. + */ + public abstract void write_long(int value); + /** + * Writes an unsigned CORBA long (i.e. Java int) value to this stream. + * @param value the value to be written. + */ + public abstract void write_ulong(int value); + /** + * Writes a CORBA longlong (i.e. Java long) value to this stream. + * @param value the value to be written. + */ + public abstract void write_longlong(long value); + /** + * Writes an unsigned CORBA longlong (i.e. Java long) value to this stream. + * @param value the value to be written. + */ + public abstract void write_ulonglong(long value); + /** + * Writes a float value to this stream. + * @param value the value to be written. + */ + public abstract void write_float(float value); + /** + * Writes a double value to this stream. + * @param value the value to be written. + */ + public abstract void write_double(double value); + /** + * Writes a string value to this stream. + * @param value the value to be written. + */ + public abstract void write_string(String value); + /** + * Writes a wide string value to this stream. + * @param value the value to be written. + */ + public abstract void write_wstring(String value); + + /** + * Writes an array of booleans on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_boolean_array(boolean[] value, int offset, + int length); + /** + * Writes an array of chars on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_char_array(char[] value, int offset, + int length); + /** + * Writes an array of wide chars on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_wchar_array(char[] value, int offset, + int length); + /** + * Writes an array of CORBA octets (bytes) on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_octet_array(byte[] value, int offset, + int length); + /** + * Writes an array of shorts on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_short_array(short[] value, int offset, + int length); + /** + * Writes an array of unsigned shorts on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_ushort_array(short[] value, int offset, + int length); + /** + * Writes an array of CORBA longs (i.e. Java ints) on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_long_array(int[] value, int offset, + int length); + /** + * Writes an array of unsigned CORBA longs (i.e. Java ints) on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_ulong_array(int[] value, int offset, + int length); + /** + * Writes an array of CORBA longlongs (i.e. Java longs) on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_longlong_array(long[] value, int offset, + int length); + /** + * Writes an array of unsigned CORBA longlongs (i.e. Java ints) on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_ulonglong_array(long[] value, int offset, + int length); + /** + * Writes an array of floats on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_float_array(float[] value, int offset, + int length); + /** + * Writes an array of doubles on this output stream. + * @param value the array to be written. + * @param offset offset on the stream. + * @param length length of buffer to write. + */ + public abstract void write_double_array(double[] value, int offset, + int length); + /** + * Writes a CORBA Object on this output stream. + * @param value the value to be written. + */ + public abstract void write_Object(org.omg.CORBA.Object value); + /** + * Writes a TypeCode on this output stream. + * @param value the value to be written. + */ + public abstract void write_TypeCode(TypeCode value); + /** + * Writes an Any on this output stream. + * @param value the value to be written. + */ + public abstract void write_any(Any value); + + /** + * Writes a Principle on this output stream. + * @param value the value to be written. + * @deprecated Deprecated by CORBA 2.2. + */ + // @Deprecated + public void write_Principal(org.omg.CORBA.Principal value) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Writes an integer (length of arrays) onto this stream. + * @param b the value to be written. + * @throws java.io.IOException if there is an input/output error + * @see portable + * package comments for unimplemented features + */ + public void write(int b) throws java.io.IOException { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Writes a BigDecimal number. + * @param value a BidDecimal--value to be written. + */ + public void write_fixed(java.math.BigDecimal value) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Writes a CORBA context on this stream. The + * Context is marshaled as a sequence of strings. + * Only those Context values specified in the contexts + * parameter are actually written. + * @param ctx a CORBA context + * @param contexts a ContextList object containing the list of contexts + * to be written + * @see portable + * package comments for unimplemented features + */ + public void write_Context(org.omg.CORBA.Context ctx, + org.omg.CORBA.ContextList contexts) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Returns the ORB that created this OutputStream. + * @return the ORB that created this OutputStream + * @see portable + * package comments for unimplemented features + */ + public org.omg.CORBA.ORB orb() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/RemarshalException.java b/omgapi/src/main/java/org/omg/CORBA/portable/RemarshalException.java new file mode 100644 index 000000000..55b09f3a5 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/RemarshalException.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** +This class is used for reporting locate forward exceptions and object forward +GIOP messages back to the ORB. In this case the ORB must remarshal the request +before trying again. +Stubs which use the stream-based model shall catch the RemarshalException +which is potentially thrown from the _invoke() method of ObjectImpl. +Upon catching the exception, the stub shall immediately remarshal the request by calling +_request(), marshalling the arguments (if any), and then calling +_invoke(). The stub shall repeat this process until _invoke() +returns normally or raises some exception other than RemarshalException. +*/ + +public final class RemarshalException extends Exception { + /** + * Constructs a RemarshalException. + */ + public RemarshalException() { + super(); + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ResponseHandler.java b/omgapi/src/main/java/org/omg/CORBA/portable/ResponseHandler.java new file mode 100644 index 000000000..e7536b00b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ResponseHandler.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** +This interface is supplied by an ORB to a servant at invocation time and allows +the servant to later retrieve an OutputStream for returning the invocation results. +*/ + +public interface ResponseHandler { + /** + * Called by the servant during a method invocation. The servant + * should call this method to create a reply marshal buffer if no + * exception occurred. + * + * @return an OutputStream suitable for marshalling the reply. + * + * @see portable + * package comments for unimplemented features + */ + OutputStream createReply(); + + /** + * Called by the servant during a method invocation. The servant + * should call this method to create a reply marshal buffer if a + * user exception occurred. + * + * @return an OutputStream suitable for marshalling the exception + * ID and the user exception body. + */ + OutputStream createExceptionReply(); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ServantObject.java b/omgapi/src/main/java/org/omg/CORBA/portable/ServantObject.java new file mode 100644 index 000000000..d89c280ad --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ServantObject.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** + This class is part of the local stub API, the purpose of which is to provide + high performance calls for collocated clients and servers + (i.e. clients and servers residing in the same Java VM). + The local stub API is supported via three additional methods on + ObjectImpl and Delegate. + ORB vendors may subclass this class to return additional + request state that may be required by their implementations. + @see ObjectImpl + @see Delegate +*/ + +public class ServantObject +{ + /** The real servant. The local stub may cast this field to the expected type, and then + * invoke the operation directly. Note, the object may or may not be the actual servant + * instance. + */ + public java.lang.Object servant; +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/Streamable.java b/omgapi/src/main/java/org/omg/CORBA/portable/Streamable.java new file mode 100644 index 000000000..881e1e013 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/Streamable.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +import org.omg.CORBA.TypeCode; + +/** + * The base class for the Holder classess of all complex + * IDL types. The ORB treats all generated Holders as Streamable to invoke + * the methods for marshalling and unmarshalling. + * + * @version 1.11, 03/18/98 + * @since JDK1.2 + */ + +public interface Streamable { + /** + * Reads data from istream and initalizes the + * value field of the Holder with the unmarshalled data. + * + * @param istream the InputStream that represents the CDR data from the wire. + */ + void _read(InputStream istream); + /** + * Marshals to ostream the value in the + * value field of the Holder. + * + * @param ostream the CDR OutputStream + */ + void _write(OutputStream ostream); + + /** + * Retrieves the TypeCode object corresponding to the value + * in the value field of the Holder. + * + * @return the TypeCode object for the value held in the holder + */ + TypeCode _type(); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/StreamableValue.java b/omgapi/src/main/java/org/omg/CORBA/portable/StreamableValue.java new file mode 100644 index 000000000..4f51aa7ed --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/StreamableValue.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** + * Defines the base type for all non-boxed IDL valuetypes + * that are not custom marshaled. + * + * All value types implement ValueBase either directly or + * indirectly by implementing either the + * StreamableValue or CustomValue interface. + * + * @author OMG + * @version 1.15 07/27/07 + */ +public interface StreamableValue extends Streamable, ValueBase { + +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/UnknownException.java b/omgapi/src/main/java/org/omg/CORBA/portable/UnknownException.java new file mode 100644 index 000000000..e817d57c6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/UnknownException.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; +/** + * The org.omg.CORBA.portable.UnknownException is used for reporting + * unknown exceptions between ties and ORBs and between ORBs and stubs. + * It provides a Java representation of an UNKNOWN system exception + * that has an UnknownExceptionInfo service context. + * If the CORBA system exception org.omg.CORBA.portable.UnknownException + * is thrown, then the stub does one of the following: + * (1) Translates it to org.omg.CORBA.UNKNOWN. + * (2) Translates it to the nested exception that the UnknownException contains. + * (3) Passes it on directly to the user. + */ +public class UnknownException extends org.omg.CORBA.SystemException { + /** + * A throwable--the original exception that was wrapped in a CORBA + * UnknownException. + */ + public Throwable originalEx; + /** + * Constructs an UnknownException object. + * @param ex a Throwable object--to be wrapped in this exception. + */ + public UnknownException(Throwable ex) { + super("", 0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + originalEx = ex; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ValueBase.java b/omgapi/src/main/java/org/omg/CORBA/portable/ValueBase.java new file mode 100644 index 000000000..e85055abe --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ValueBase.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; +/** + * The generated Java classes corresponding to valuetype IDL types + * implement this interface. In other words, the Java mapping of + * valuetype objects implement the ValueBase interface. The generated + * Java class for valuetype's shall provide an implementation of the + * ValueBase interface for the corresponding value type. + * For value types that are streamable (i.e. non-custom), + * the generated Java class shall also provide an implementation + * for the org.omg.CORBA.portable.Streamable interface. + * (CORBA::ValueBase is mapped to java.io.Serializable.) + */ +public interface ValueBase extends IDLEntity { + /** + * Provides truncatable repository ids. + * @return a String array--list of truncatable repository ids. + */ + String[] _truncatable_ids(); +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ValueFactory.java b/omgapi/src/main/java/org/omg/CORBA/portable/ValueFactory.java new file mode 100644 index 000000000..9988fbd75 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ValueFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; +import java.io.Serializable; + +/** + * The ValueFactory interface is the native mapping for the IDL + * type CORBA::ValueFactory. The read_value() method is called by + * the ORB runtime while in the process of unmarshaling a value type. + * A user shall implement this method as part of implementing a type + * specific value factory. In the implementation, the user shall call + * is.read_value(java.io.Serializable) with a uninitialized valuetype + * to use for unmarshaling. The value returned by the stream is + * the same value passed in, with all the data unmarshaled. + * @see org.omg.CORBA_2_3.ORB + */ + +public interface ValueFactory { + /** + * Is called by + * the ORB runtime while in the process of unmarshaling a value type. + * A user shall implement this method as part of implementing a type + * specific value factory. + * @param is an InputStream object--from which the value will be read. + * @return a Serializable object--the value read off of "is" Input stream. + */ + Serializable read_value(org.omg.CORBA_2_3.portable.InputStream is); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ValueInputStream.java b/omgapi/src/main/java/org/omg/CORBA/portable/ValueInputStream.java new file mode 100644 index 000000000..e1eb5b1e3 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ValueInputStream.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** + * Java to IDL ptc 02-01-12 1.5.1.4 + * + * ValueInputStream is used for implementing RMI-IIOP + * stream format version 2. + */ +public interface ValueInputStream { + + /** + * The start_value method reads a valuetype + * header for a nested custom valuetype and + * increments the valuetype nesting depth. + */ + void start_value(); + + /** + * The end_value method reads the end tag + * for the nested custom valuetype (after + * skipping any data that precedes the end + * tag) and decrements the valuetype nesting + * depth. + */ + void end_value(); +} + diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/ValueOutputStream.java b/omgapi/src/main/java/org/omg/CORBA/portable/ValueOutputStream.java new file mode 100644 index 000000000..ad3864255 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/ValueOutputStream.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA.portable; + +/** + * Java to IDL ptc 02-01-12 1.5.1.3 + * + * ValueOutputStream is used for implementing RMI-IIOP + * stream format version 2. + */ +public interface ValueOutputStream { + /** + * The start_value method ends any currently open chunk, + * writes a valuetype header for a nested custom valuetype + * (with a null codebase and the specified repository ID), + * and increments the valuetype nesting depth. + */ + void start_value(java.lang.String rep_id); + + /** + * The end_value method ends any currently open chunk, + * writes the end tag for the nested custom valuetype, + * and decrements the valuetype nesting depth. + */ + void end_value(); +} diff --git a/omgapi/src/main/java/org/omg/CORBA/portable/package.html b/omgapi/src/main/java/org/omg/CORBA/portable/package.html new file mode 100644 index 000000000..31bb5b09b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA/portable/package.html @@ -0,0 +1,86 @@ + + + + + + + + +Provides a portability layer, that is, a set of ORB APIs +that makes it possible for code generated +by one vendor to run on another vendor's ORB. +Stubs and other code, generated either from IDL or +interfaces written in the Java programming language, +can call into these ORB APIs. + + + +

    + +


    +

    CORBA Features Throwing NO_IMPLEMENT() Exceptions

    +
    +Some methods throw NO_IMPLEMENT() exceptions by default, but ORB vendors +can override them to provide real implementations. The ORB included in +Sun's release of the Java[tm] Platform, Standard Edition 6, includes +implementations for the following methods. +

    +

    List of Unimplemented Features in Package +org.omg.CORBA.portable

    +

    +

    Unimplemented Interfaces in package org.omg.CORBA.portable

    +
      +
    • InvokeHandler +
    • ResponseHandler +
    +

    +

    Unimplemented Methods in package org.omg.CORBA.portable

    +
      +
    • InputStream +
        +
      • public int read() +
      • public.math.BigDecimal read_fixed() +
      • public org.omg.CORBA.Context read_Context() +
      • public org.omg.CORBA.Object read_Object(java.lang.Class clz) +
      • public org.omg.CORBA.ORB orb() +
      +
    • OutputStream +
        +
      • public org.omg.CORBA.ORB orb() +
      • public void write_Context(org.omg.CORBA.Context ctx, + org.omg.CORBA.ContextList contexts) +
      • public void write_fixed(java.math.BigDecimal value) +
      • public void write(int b) +
      +
    • Delegate +
        +
      • public void releaseReply(org.omg.CORBA.Object self, InputStream input) +
      • public InputStream invoke(org.omg.CORBA.Object self, OutputStream output) +
      • public OutputStream request(org.omg.CORBA.Object self, String operation, + boolean responseExpected) +
      • public org.omg.CORBA.Object set_policy_override(org.omg.CORBA.Object self, + org.omg.CORBA.Policy[] policies, + org.omg.CORBA.SetOverrideType set_add) +
      • public org.omg.CORBA.DomainManager[] get_domain_managers( + org.omg.CORBA.Object + self) +
      • public org.omg.CORBA.Policy get_policy(org.omg.CORBA.Object self, + int policy_type) +
      +
    + +@since JDK1.2 +@serial exclude + + + diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/ORB.java b/omgapi/src/main/java/org/omg/CORBA_2_3/ORB.java new file mode 100644 index 000000000..39cc82b0c --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/ORB.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA_2_3; + +/** + * A class extending org.omg.CORBA.ORB to make the ORB + * portable under the OMG CORBA version 2.3 specification. + */ +public abstract class ORB extends org.omg.CORBA.ORB { + +/** + * @see CORBA_2_3 package + * comments for unimplemented features + */ + public org.omg.CORBA.portable.ValueFactory register_value_factory(String id, + org.omg.CORBA.portable.ValueFactory factory) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + +/** + * @see CORBA_2_3 package + * comments for unimplemented features + */ + public void unregister_value_factory(String id) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + +/** + * @see CORBA_2_3 package + * comments for unimplemented features + */ + public org.omg.CORBA.portable.ValueFactory lookup_value_factory(String id) + { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + +/** + * @see CORBA_2_3 package + * comments for unimplemented features + */ + // always return a ValueDef or throw BAD_PARAM if + // repid does not represent a valuetype + public org.omg.CORBA.Object get_value_def(String repid) + throws org.omg.CORBA.BAD_PARAM { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + +/** + * @see CORBA_2_3 package + * comments for unimplemented features + */ + public void set_delegate(java.lang.Object wrapper) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + +} diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/package.html b/omgapi/src/main/java/org/omg/CORBA_2_3/package.html new file mode 100644 index 000000000..160794dc6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/package.html @@ -0,0 +1,55 @@ + + + + + + + +package + + +The CORBA_2_3 package defines additions to existing CORBA interfaces +in the Java[tm] Standard Edition 6.   These changes occurred in recent +revisions to the CORBA API defined by the OMG.  The new methods were +added to  interfaces derived from the corresponding interfaces in +the CORBA package.  This provides backward compatibility and avoids +breaking the JCK tests. + +

    Package Specification

    + +

    For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

    + +The following methods in the abstract class +org.omg.CORBA_2_3.ORB are unimplemented: +

      + +
    • public org.omg.CORBA.portable.ValueFactory + register_value_factory(String id, org.omg.CORBA.portable.ValueFactory +factory) +
    • public void unregister_value_factory(String id) +
    • public org.omg.CORBA.portable.ValueFactory + lookup_value_factory(String id) +
    • public org.omg.CORBA.Object get_value_def(String repid) +
    • public void set_delegate(java.lang.Object wrapper) + +
    +@since JDK 1.3 +
    +@serial exclude + + + diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/portable/Delegate.java b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/Delegate.java new file mode 100644 index 000000000..5a9284aa7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/Delegate.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA_2_3.portable; + +/** + * Delegate class provides the ORB vendor specific implementation + * of CORBA object. It extends org.omg.CORBA.portable.Delegate and + * provides new methods that were defined by CORBA 2.3. + * + * @see org.omg.CORBA.portable.Delegate + * @author OMG + * @version 1.16 07/27/07 + * @since JDK1.2 + */ + +public abstract class Delegate extends org.omg.CORBA.portable.Delegate { + + /** Returns the codebase for object reference provided. + * @param self the object reference whose codebase needs to be returned. + * @return the codebase as a space delimited list of url strings or + * null if none. + */ + public java.lang.String get_codebase(org.omg.CORBA.Object self) { + return null; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/portable/InputStream.java b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/InputStream.java new file mode 100644 index 000000000..a2d4221e7 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/InputStream.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA_2_3.portable; + +import java.io.SerializablePermission; +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * InputStream provides for the reading of all of the mapped IDL types + * from the stream. It extends org.omg.CORBA.portable.InputStream. This + * class defines new methods that were added for CORBA 2.3. + * + * @see org.omg.CORBA.portable.InputStream + * @author OMG + * @version 1.17 07/27/07 + * @since JDK1.2 + */ + +public abstract class InputStream extends org.omg.CORBA.portable.InputStream { + private static final String ALLOW_SUBCLASS_PROP = "jdk.corba.allowInputStreamSubclass"; + + + private static final boolean allowSubclass = AccessController.doPrivileged( + new PrivilegedAction() { + @Override + public Boolean run() { + String prop = System.getProperty(ALLOW_SUBCLASS_PROP); + + return prop == null ? false : + (prop.equalsIgnoreCase("false") ? false : true); + } + }); + + private static Void checkPermission() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + if (!allowSubclass) + sm.checkPermission(new + SerializablePermission("enableSubclassImplementation")); + } + + return null; + } + + + private InputStream(Void ignore) { } + + + /** + * Create a new instance of this class. + * + * throw SecurityException if SecurityManager is installed and + * enableSubclassImplementation SerializablePermission + * is not granted or jdk.corba.allowOutputStreamSubclass system + * property is either not set or is set to 'false' + */ + public InputStream() { + this(checkPermission()); + } + + /** + * Unmarshalls a value type from the input stream. + * @return the value type unmarshalled from the input stream + */ + public java.io.Serializable read_value() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Unmarshalls a value type from the input stream. + * @param clz is the declared type of the value to be unmarshalled + * @return the value unmarshalled from the input stream + */ + public java.io.Serializable read_value(java.lang.Class clz) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Unmarshalls a value type from the input stream. + * @param factory is the instance fo the helper to be used for + * unmarshalling the value type + * @return the value unmarshalled from the input stream + */ + public java.io.Serializable read_value(org.omg.CORBA.portable.BoxedValueHelper factory) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Unmarshalls a value type from the input stream. + * @param rep_id identifies the type of the value to be unmarshalled + * @return value type unmarshalled from the input stream + */ + public java.io.Serializable read_value(java.lang.String rep_id) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Unmarshalls a value type from the input stream. + * @param value is an uninitialized value which is added to the orb's + * indirection table before calling Streamable._read() or + * CustomMarshal.unmarshal() to unmarshal the value. + * @return value type unmarshalled from the input stream + */ + public java.io.Serializable read_value(java.io.Serializable value) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Unmarshal the value object or a suitable stub object. + * @return ORB runtime returns the value object or a suitable stub object. + */ + public java.lang.Object read_abstract_interface() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Unmarshal the class object or the stub class corresponding to the passed type. + * @param clz is the Class object for the stub class which corresponds to + * the type that is statically expected. + * @return ORB runtime returns the value object or a suitable stub object. + */ + public java.lang.Object read_abstract_interface(java.lang.Class clz) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/portable/ObjectImpl.java b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/ObjectImpl.java new file mode 100644 index 000000000..4f8ff93c9 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/ObjectImpl.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA_2_3.portable; + +import org.omg.CORBA_2_3.portable.Delegate; + +/** + * ObjectImpl class is the base class for all stubs. It provides the + * basic delegation mechanism. It extends org.omg.CORBA.portable.ObjectImpl + * and provides new methods defined by CORBA 2.3. + * + * @see org.omg.CORBA.portable.ObjectImpl + * @author OMG + * @version 1.16 07/27/07 + * @since JDK1.2 + */ + + +public abstract class ObjectImpl extends org.omg.CORBA.portable.ObjectImpl { + + /** Returns the codebase for this object reference. + * @return the codebase as a space delimited list of url strings or + * null if none. + */ + public java.lang.String _get_codebase() { + org.omg.CORBA.portable.Delegate delegate = _get_delegate(); + if (delegate instanceof Delegate) + return ((Delegate) delegate).get_codebase(this); + return null; + } +} diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/portable/OutputStream.java b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/OutputStream.java new file mode 100644 index 000000000..7e821ae08 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/OutputStream.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA_2_3.portable; + +/** + * OutputStream provides interface for writing of all of the mapped IDL type + * to the stream. It extends org.omg.CORBA.portable.OutputStream, and defines + * new methods defined by CORBA 2.3. + * + * @see org.omg.CORBA.portable.OutputStream + * @author OMG + * @version 1.19 07/27/07 + * @since JDK1.2 + */ + +public abstract class OutputStream extends org.omg.CORBA.portable.OutputStream { + + /** + * Marshals a value type to the output stream. + * @param value is the acutal value to write + */ + public void write_value(java.io.Serializable value) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Marshals a value type to the output stream. + * @param value is the acutal value to write + * @param clz is the declared type of the value to be marshaled + */ + public void write_value(java.io.Serializable value, java.lang.Class clz) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Marshals a value type to the output stream. + * @param value is the acutal value to write + * @param repository_id identifies the type of the value type to + * be marshaled + */ + public void write_value(java.io.Serializable value, String repository_id) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Marshals a value type to the output stream. + * @param value is the acutal value to write + * @param factory is the instance of the helper to be used for marshaling + * the boxed value + */ + public void write_value(java.io.Serializable value, org.omg.CORBA.portable.BoxedValueHelper factory) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + /** + * Marshals a value object or a stub object. + * @param obj the actual value object to marshal or the stub to be marshalled + */ + public void write_abstract_interface(java.lang.Object obj) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + +} diff --git a/omgapi/src/main/java/org/omg/CORBA_2_3/portable/package.html b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/package.html new file mode 100644 index 000000000..e94465287 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CORBA_2_3/portable/package.html @@ -0,0 +1,25 @@ + + + + + + + + + Provides methods for the input and output of value types, and contains + other updates to the org/omg/CORBA/portable package. +

    +@since 1.3 +@serial exclude + + diff --git a/omgapi/src/main/java/org/omg/CosTSPortability/Receiver.java b/omgapi/src/main/java/org/omg/CosTSPortability/Receiver.java new file mode 100644 index 000000000..0cca9f08e --- /dev/null +++ b/omgapi/src/main/java/org/omg/CosTSPortability/Receiver.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// org/omg/CosTSPortability/Receiver.java + +package org.omg.CosTSPortability; + +public interface Receiver { + + void received_request(int id, org.omg.CosTransactions.PropagationContext ctx); + + void sending_reply(int id, org.omg.CosTransactions.PropagationContextHolder ctxh); +} diff --git a/omgapi/src/main/java/org/omg/CosTSPortability/ReceiverHolder.java b/omgapi/src/main/java/org/omg/CosTSPortability/ReceiverHolder.java new file mode 100644 index 000000000..6adbcb76e --- /dev/null +++ b/omgapi/src/main/java/org/omg/CosTSPortability/ReceiverHolder.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// org/omg/CosTSPortability/ReceiverHolder.java + +package org.omg.CosTSPortability; +public class ReceiverHolder +{ + // instance variable + public org.omg.CosTSPortability.Receiver value; + // constructors + public ReceiverHolder() { + this(null); + } + public ReceiverHolder(org.omg.CosTSPortability.Receiver __arg) { + value = __arg; + } +} diff --git a/omgapi/src/main/java/org/omg/CosTSPortability/Sender.java b/omgapi/src/main/java/org/omg/CosTSPortability/Sender.java new file mode 100644 index 000000000..28f993722 --- /dev/null +++ b/omgapi/src/main/java/org/omg/CosTSPortability/Sender.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// org/omg/CosTSPortability/Sender.java + +package org.omg.CosTSPortability; + +public interface Sender { + + void sending_request(int id, org.omg.CosTransactions.PropagationContextHolder ctxh) ; + + void received_reply(int id, org.omg.CosTransactions.PropagationContext ctx, org.omg.CORBA.Environment env) throws org.omg.CORBA.WrongTransaction; +} diff --git a/omgapi/src/main/java/org/omg/CosTSPortability/SenderHolder.java b/omgapi/src/main/java/org/omg/CosTSPortability/SenderHolder.java new file mode 100644 index 000000000..17183762b --- /dev/null +++ b/omgapi/src/main/java/org/omg/CosTSPortability/SenderHolder.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// org/omg/CosTSPortability/SenderHolder.java + +package org.omg.CosTSPortability; +public class SenderHolder +{ + // instance variable + public org.omg.CosTSPortability.Sender value; + // constructors + public SenderHolder() { + this(null); + } + public SenderHolder(org.omg.CosTSPortability.Sender __arg) { + value = __arg; + } +} diff --git a/omgapi/src/main/java/org/omg/PortableServer/DynamicImplementation.java b/omgapi/src/main/java/org/omg/PortableServer/DynamicImplementation.java new file mode 100644 index 000000000..26da7313f --- /dev/null +++ b/omgapi/src/main/java/org/omg/PortableServer/DynamicImplementation.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + +/** + * Allows dynamic handling of object invocations. POA-based DSI + * servants inherit from the + * standard DynamicImplementation class, this class inherits + * from the Servant class. Based on IDL to Java spec. + * CORBA V 2.3.1 ptc/00-01-08.pdf. + */ +abstract public class DynamicImplementation extends Servant { + +/** + * Receives requests issued to any CORBA object + * incarnated by the DSI servant and performs the processing + * necessary to execute the request. + * @param request the request issued to the CORBA object. + */ + abstract public void invoke(org.omg.CORBA.ServerRequest request); +} diff --git a/omgapi/src/main/java/org/omg/PortableServer/POAHelper.java b/omgapi/src/main/java/org/omg/PortableServer/POAHelper.java new file mode 100644 index 000000000..8a17d6732 --- /dev/null +++ b/omgapi/src/main/java/org/omg/PortableServer/POAHelper.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2001, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + +/** +* org/omg/PortableServer/POAHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.1" +* from ../../../../src/share/classes/org/omg/PortableServer/poa.idl +* Tuesday, October 23, 2001 1:16:58 PM PDT +*/ + + +/** + * A POA object manages the implementation of a + * collection of objects. The POA supports a name space + * for the objects, which are identified by Object Ids. + * A POA also provides a name space for POAs. A POA is + * created as a child of an existing POA, which forms a + * hierarchy starting with the root POA. A POA object + * must not be exported to other processes, or + * externalized with ORB::object_to_string. + */ +abstract public class POAHelper +{ + private static String _id = "IDL:omg.org/PortableServer/POA:2.3"; + + public static void insert (org.omg.CORBA.Any a, + org.omg.PortableServer.POA that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.PortableServer.POA extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.PortableServer.POAHelper.id (), "POA"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.PortableServer.POA read ( + org.omg.CORBA.portable.InputStream istream) + { + throw new org.omg.CORBA.MARSHAL (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, + org.omg.PortableServer.POA value) + { + throw new org.omg.CORBA.MARSHAL (); + } + + public static org.omg.PortableServer.POA narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.PortableServer.POA) + return (org.omg.PortableServer.POA)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + return null; + } +} diff --git a/omgapi/src/main/java/org/omg/PortableServer/Servant.java b/omgapi/src/main/java/org/omg/PortableServer/Servant.java new file mode 100644 index 000000000..9e57e9fe6 --- /dev/null +++ b/omgapi/src/main/java/org/omg/PortableServer/Servant.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.portable.Delegate; + +/** + * Defines the native Servant type. In Java, the + * Servant type is mapped to the Java + * org.omg.PortableServer.Servant class. + * It serves as the base class for all POA servant + * implementations and provides a number of methods that may + * be invoked by the application programmer, as well as methods + * which are invoked by the POA itself and may be overridden by + * the user to control aspects of servant behavior. + * Based on IDL to Java spec. (CORBA V2.3.1) ptc/00-01-08.pdf. + */ + +abstract public class Servant { + + private transient Delegate _delegate = null; + /** + * Gets the ORB vendor-specific implementation of + * PortableServer::Servant. + * @return _delegate the ORB vendor-specific + * implementation of PortableServer::Servant. + */ + final public Delegate _get_delegate() { + if (_delegate == null) { + throw + new + org.omg.CORBA.BAD_INV_ORDER + ("The Servant has not been associated with an ORB instance"); + } + return _delegate; + } + + /** + * Supports the Java ORB portability + * interfaces by providing a method for classes that support + * ORB portability through delegation to set their delegate. + * @param delegate ORB vendor-specific implementation of + * the PortableServer::Servant. + */ + final public void _set_delegate(Delegate delegate) { + _delegate = delegate; + } + + /** + * Allows the servant to obtain the object reference for + * the target CORBA object it is incarnating for that request. + * @return this_object Object reference + * associated with the request. + */ + final public org.omg.CORBA.Object _this_object() { + return _get_delegate().this_object(this); + } + + /** + * Allows the servant to obtain the object reference for + * the target CORBA Object it is incarnating for that request. + * @param orb ORB with which the servant is associated. + * @return _this_object reference associated with the request. + */ + final public org.omg.CORBA.Object _this_object(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw + new + org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + return _this_object(); + } + + /** + * Returns the instance of the ORB + * currently associated with the Servant (convenience method). + * @return orb the instance of the ORB currently + * associated with the Servant. + */ + final public ORB _orb() { + return _get_delegate().orb(this); + } + + /** + * Allows easy execution of common methods, equivalent to + * PortableServer::Current:get_POA. + * @return poa POA associated with the servant. + */ + final public POA _poa() { + return _get_delegate().poa(this); + } + + /** + * Allows easy execution of + * common methods, equivalent + * to calling PortableServer::Current::get_object_id. + * @return object_id the Object ID associated + * with this servant. + */ + final public byte[] _object_id() { + return _get_delegate().object_id(this); + } + + /** + * Returns the + * root POA from the ORB instance associated with the servant. + * Subclasses may override this method to return a different POA. + * @return default_POA the POA associated with the + * Servant. + */ + public POA _default_POA() { + return _get_delegate().default_POA(this); + } + + /** + * Checks to see if the specified repository_id is present + * on the list returned by _all_interfaces() or is the + * repository_id for the generic CORBA Object. + * @param repository_id the repository_id + * to be checked in the repository list or against the id + * of generic CORBA objects. + * @return is_a boolean indicating whether the specified + * repository_id is + * in the repository list or is same as a generic CORBA + * object. + */ + public boolean _is_a(String repository_id) { + return _get_delegate().is_a(this, repository_id); + } + + /** + * Checks for the existence of an + * Object. + * The Servant provides a default implementation of + * _non_existent() that can be overridden by derived servants. + * @return non_existent true if that object does + * not exist, false otherwise. + */ + public boolean _non_existent() { + return _get_delegate().non_existent(this); + } + + // Ken and Simon will ask about editorial changes + // needed in IDL to Java mapping to the following + // signature. + /** + * Returns an object in the Interface Repository + * which provides type information that may be useful to a program. + * Servant provides a default implementation of + * _get_interface() + * that can be overridden by derived servants if the default + * behavior is not adequate. + * @return get_interface type information that corresponds to this servant. + */ + /* + public org.omg.CORBA.Object _get_interface() { + return _get_delegate().get_interface(this); + } + */ + + // _get_interface_def() replaces the _get_interface() method + + /** + * Returns an InterfaceDef object as a + * CORBA::Object that defines the runtime type of the + * CORBA::Object implemented by the Servant. + * The invoker of _get_interface_def + * must narrow the result to an InterfaceDef in order + * to use it. + *

    This default implementation of _get_interface_def() + * can be overridden + * by derived servants if the default behavior is not adequate. + * As defined in the CORBA 2.3.1 specification, section 11.3.1, the + * default behavior of _get_interface_def() is to use + * the most derived + * interface of a static servant or the most derived interface retrieved + * from a dynamic servant to obtain the InterfaceDef. + * This behavior must + * be supported by the Delegate that implements the + * Servant. + * @return get_interface_def an InterfaceDef + * object as a + * CORBA::Object that defines the runtime type of the + * CORBA::Object implemented by the Servant. + */ + public org.omg.CORBA.Object _get_interface_def() + { + // First try to call the delegate implementation class's + // "Object get_interface_def(..)" method (will work for ORBs + // whose delegates implement this method). + // Else call the delegate implementation class's + // "InterfaceDef get_interface(..)" method using reflection + // (will work for ORBs that were built using an older version + // of the Delegate interface with a get_interface method + // but not a get_interface_def method). + + org.omg.PortableServer.portable.Delegate delegate = _get_delegate(); + try { + // If the ORB's delegate class does not implement + // "Object get_interface_def(..)", this will throw + // an AbstractMethodError. + return delegate.get_interface_def(this); + } catch( AbstractMethodError aex ) { + // Call "InterfaceDef get_interface(..)" method using reflection. + try { + Class[] argc = { org.omg.PortableServer.Servant.class }; + java.lang.reflect.Method meth = + delegate.getClass().getMethod("get_interface", argc); + Object[] argx = { this }; + return (org.omg.CORBA.Object)meth.invoke(delegate, argx); + } catch( java.lang.reflect.InvocationTargetException exs ) { + Throwable t = exs.getTargetException(); + if (t instanceof Error) { + throw (Error) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } catch( RuntimeException rex ) { + throw rex; + } catch( Exception exr ) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } + } + + // methods for which the user must provide an + // implementation + /** + * Used by the ORB to obtain complete type + * information from the servant. + * @param poa POA with which the servant is associated. + * @param objectId is the id corresponding to the object + * associated with this servant. + * @return list of type information for the object. + */ + abstract public String[] _all_interfaces( POA poa, byte[] objectId); +} diff --git a/omgapi/src/main/java/org/omg/PortableServer/ServantLocatorPackage/CookieHolder.java b/omgapi/src/main/java/org/omg/PortableServer/ServantLocatorPackage/CookieHolder.java new file mode 100644 index 000000000..cdb182606 --- /dev/null +++ b/omgapi/src/main/java/org/omg/PortableServer/ServantLocatorPackage/CookieHolder.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer.ServantLocatorPackage; + +/** + * The native type PortableServer::ServantLocator::Cookie is mapped + * to java.lang.Object. A CookieHolder class is provided for passing + * the Cookie type as an out parameter. The CookieHolder class + * follows exactly the same pattern as the other holder classes + * for basic types. + */ + +final public class CookieHolder implements org.omg.CORBA.portable.Streamable +{ + public java.lang.Object value; + + public CookieHolder() { } + + public CookieHolder(java.lang.Object initial) { + value = initial; + } + + public void _read( org.omg.CORBA.portable.InputStream is) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + public void _write( org.omg.CORBA.portable.OutputStream os) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + public org.omg.CORBA.TypeCode _type() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/omgapi/src/main/java/org/omg/PortableServer/portable/Delegate.java b/omgapi/src/main/java/org/omg/PortableServer/portable/Delegate.java new file mode 100644 index 000000000..7ad7f4cbf --- /dev/null +++ b/omgapi/src/main/java/org/omg/PortableServer/portable/Delegate.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer.portable; + +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.POA; + +/** + * The portability package contains interfaces and classes + * that are designed for and intended to be used by ORB + * implementor. It exposes the publicly defined APIs that + * are used to connect stubs and skeletons to the ORB. + * The Delegate interface provides the ORB vendor specific + * implementation of PortableServer::Servant. + * Conformant to spec CORBA V2.3.1, ptc/00-01-08.pdf + */ +public interface Delegate { +/** + * Convenience method that returns the instance of the ORB + * currently associated with the Servant. + * @param Self the servant. + * @return ORB associated with the Servant. + */ + org.omg.CORBA.ORB orb(Servant Self); + +/** + * This allows the servant to obtain the object reference for + * the target CORBA Object it is incarnating for that request. + * @param Self the servant. + * @return Object reference associated with the request. + */ + org.omg.CORBA.Object this_object(Servant Self); + +/** + * The method _poa() is equivalent to + * calling PortableServer::Current:get_POA. + * @param Self the servant. + * @return POA associated with the servant. + */ + POA poa(Servant Self); + +/** + * The method _object_id() is equivalent + * to calling PortableServer::Current::get_object_id. + * @param Self the servant. + * @return ObjectId associated with this servant. + */ + byte[] object_id(Servant Self); + +/** + * The default behavior of this function is to return the + * root POA from the ORB instance associated with the servant. + * @param Self the servant. + * @return POA associated with the servant class. + */ + POA default_POA(Servant Self); + +/** + * This method checks to see if the specified repid is present + * on the list returned by _all_interfaces() or is the + * repository id for the generic CORBA Object. + * @param Self the servant. + * @param Repository_Id the repository_id to be checked in the + * repository list or against the id of generic CORBA + * object. + * @return boolean indicating whether the specified repid is + * in the list or is same as that got generic CORBA + * object. + */ + boolean is_a(Servant Self, String Repository_Id); + +/** + * This operation is used to check for the existence of the + * Object. + * @param Self the servant. + * @return boolean true to indicate that object does not exist, + * and false otherwise. + */ + boolean non_existent(Servant Self); + //Simon And Ken Will Ask About Editorial Changes + //In Idl To Java For The Following Signature. + +/** + * This operation returns an object in the Interface Repository + * which provides type information that may be useful to a program. + * @param self the servant. + * @return type information corresponding to the object. + */ + // The get_interface() method has been replaced by get_interface_def() + //org.omg.CORBA.Object get_interface(Servant Self); + + org.omg.CORBA.Object get_interface_def(Servant self); +} diff --git a/omgapi/src/main/java/org/omg/stub/java/rmi/_Remote_Stub.java b/omgapi/src/main/java/org/omg/stub/java/rmi/_Remote_Stub.java new file mode 100644 index 000000000..f5198bb0c --- /dev/null +++ b/omgapi/src/main/java/org/omg/stub/java/rmi/_Remote_Stub.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.omg.stub.java.rmi; + +import java.rmi.Remote; +import javax.rmi.CORBA.Stub; + +/** + * This class provides the Stub for the Remote Type. The class is generated + * by the rmic compiler, and is still under works at OMG. It's contents are + * subject to change without notice as the specification evolves. + */ +public final class _Remote_Stub extends Stub implements Remote { + + private static final String _type_ids[] = { + "" + }; + + /** + * Returns an array of repository ids that an object implements. + * The string at index zero represents the most derived interface. The last id, + * for the generic CORBA object is (i.e., IDL:omg.org/CORBA/Object:1.0") is + * implied and not present. + * @return an array of repository ids that an object implements. + */ + public String[] _ids() { + return (String[]) _type_ids.clone(); + } +} diff --git a/omgapi/src/main/java/org/omg/stub/java/rmi/package.html b/omgapi/src/main/java/org/omg/stub/java/rmi/package.html new file mode 100644 index 000000000..5eff6d214 --- /dev/null +++ b/omgapi/src/main/java/org/omg/stub/java/rmi/package.html @@ -0,0 +1,25 @@ + + + + + + + + Contains RMI-IIOP Stubs for the Remote types that occur in the + java.rmi package. +

    +@since 1.3 +
    +@serial exclude + + diff --git a/orbmain/pom.xml b/orbmain/pom.xml new file mode 100644 index 000000000..f79f5d308 --- /dev/null +++ b/orbmain/pom.xml @@ -0,0 +1,123 @@ + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + glassfish-corba-orb + GlassFish Corba ORB + bundle + + + + ${project.groupId} + glassfish-corba-csiv2-idl + ${project.version} + + + ${project.groupId} + glassfish-corba-omgapi + ${project.version} + + + ${project.groupId} + glassfish-corba-internal-api + ${project.version} + + + ${project.groupId} + exception-annotation-processor + ${project.version} + compile + + + org.osgi + org.osgi.core + 6.0.0 + + + org.glassfish.gmbal + gmbal + ${gmbal-version} + + + org.glassfish.pfl + pfl-basic + ${pfl-version} + + + org.glassfish.pfl + pfl-dynamic + ${pfl-version} + + + org.glassfish.pfl + pfl-tf + ${pfl-version} + + + org.glassfish.pfl + pfl-test + ${pfl-version} + test + + + org.glassfish.grizzly + grizzly-framework + 2.4.3 + + + org.hamcrest + hamcrest-all + + + junit + junit + + + com.meterware.simplestub + simplestub + + + + + + + org.apache.felix + maven-bundle-plugin + + + + !com.sun.corba.ee.spi.threadpool, !com.sun.corba.ee.spi.logex.stdcorba, + com.sun.corba.ee.spi.*; version=1, + com.sun.corba.ee.impl.corba; version=1, + com.sun.corba.ee.impl.encoding.*; version=1, + com.sun.corba.ee.impl.folb; version=1, + com.sun.corba.ee.impl.javax.*; version=1, + com.sun.corba.ee.impl.misc; version=1, + com.sun.corba.ee.impl.naming.*; version=1, + com.sun.corba.ee.impl.oa.*; version=1, + com.sun.corba.ee.impl.orb; version=1, + com.sun.corba.ee.impl.presentation.*; version=1, + com.sun.corba.ee.impl.txpoa; version=1 + + + + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/CopierManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/CopierManagerImpl.java new file mode 100644 index 000000000..8fbd67493 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/CopierManagerImpl.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.copyobject ; + +import com.sun.corba.ee.spi.copyobject.CopierManager; +import org.glassfish.pfl.basic.contain.DenseIntMapImpl; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; + +public class CopierManagerImpl implements CopierManager +{ + private int defaultId ; + private DenseIntMapImpl map ; + + public CopierManagerImpl() + { + defaultId = 0 ; + map = new DenseIntMapImpl() ; + } + + public void setDefaultId( int id ) + { + defaultId = id ; + } + + public int getDefaultId() + { + return defaultId ; + } + + public ObjectCopierFactory getObjectCopierFactory( int id ) + { + return map.get( id ) ; + } + + public ObjectCopierFactory getDefaultObjectCopierFactory() + { + return map.get( defaultId ) ; + } + + public void registerObjectCopierFactory( ObjectCopierFactory factory, int id ) + { + map.set( id, factory ) ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/JavaStreamORBObjectCopierImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/JavaStreamORBObjectCopierImpl.java new file mode 100644 index 000000000..d7669152b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/JavaStreamORBObjectCopierImpl.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.copyobject ; + +import java.rmi.Remote; + +import org.omg.CORBA.ORB ; + +import com.sun.corba.ee.impl.util.Utility; + +import org.glassfish.pfl.dynamic.copyobject.impl.JavaStreamObjectCopierImpl ; + + +public class JavaStreamORBObjectCopierImpl extends JavaStreamObjectCopierImpl { + private ORB orb ; + + public JavaStreamORBObjectCopierImpl( ORB orb ) { + this.orb = orb ; + } + + public Object copy(Object obj, boolean debug ) { + return copy( obj ) ; + } + + @Override + public Object copy(Object obj) { + if (obj instanceof Remote) { + // Yes, so make sure it is connected and converted + // to a stub (if needed)... + return Utility.autoConnect(obj,orb,true); + } + + return super.copy( obj ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/ORBStreamObjectCopierImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/ORBStreamObjectCopierImpl.java new file mode 100644 index 000000000..9fcd3bc8f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/ORBStreamObjectCopierImpl.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.copyobject ; + + +import java.io.Serializable; +import java.rmi.Remote; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import org.omg.CORBA.ORB ; + +import com.sun.corba.ee.impl.util.Utility; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopier; + +public class ORBStreamObjectCopierImpl implements ObjectCopier { + + public ORBStreamObjectCopierImpl( ORB orb ) + { + this.orb = orb ; + } + + public Object copy(Object obj, boolean debug) { + return copy( obj ) ; + } + + public Object copy(Object obj) { + if (obj instanceof Remote) { + // Yes, so make sure it is connected and converted + // to a stub (if needed)... + return Utility.autoConnect(obj,orb,true); + } + + OutputStream out = (OutputStream)orb.create_output_stream(); + out.write_value((Serializable)obj); + InputStream in = (InputStream)out.create_input_stream(); + return in.read_value(); + } + + private ORB orb; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/OldReflectObjectCopierImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/OldReflectObjectCopierImpl.java new file mode 100644 index 000000000..da5fcef8a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/copyobject/OldReflectObjectCopierImpl.java @@ -0,0 +1,484 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Appserver logging has been added to this class, levels of + * verbosity are as follows: + * + * INFO = no extra output in logs, standard production setting + * FINE = (IasUtilDelegate) logs message stating if HIGHP or STDP + * copyObject code is executed. Can be used to determine + * how often the sun.reflect code falls back to std ORB copy + * FINER = logs tracing info for arrayCopy and copyFields + * FINEST = logs everything, including exception stack traces + */ + +package com.sun.corba.ee.impl.copyobject ; + +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.orb.ORB; +import org.glassfish.pfl.basic.reflection.Bridge; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopier; +import org.glassfish.pfl.dynamic.copyobject.spi.ReflectiveCopyException; + +import java.io.Externalizable; +import java.io.Serializable; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.PrivilegedExceptionAction; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * Provides the functionality of copying objects using reflection. + * NOTE: Currently the implementation does not implement this copying + * functionality for objects which have fields whose types are + * based on inner classes. + * If for any reason copying cannot be done using reflection it uses + * the original ORB serialization to implement the copying + */ +public class OldReflectObjectCopierImpl implements ObjectCopier +{ + private IdentityHashMap objRefs; + private ORB orb ; + + public OldReflectObjectCopierImpl( org.omg.CORBA.ORB orb ) + { + objRefs = new IdentityHashMap(); + this.orb = (ORB)orb ; + } + + /** + * reflectCache is used to cache the reflection attributes of + * a class + */ + private static Map reflectCache = new HashMap(); + + /** + * Provides the functionality of a cache for storing the various + * reflection attributes of a class so that access to these methods + * is not done repeatedly + */ + class ReflectAttrs { + public Field[] fields; + public Constructor constr; + public Class thisClass ; + public Class arrayClass; + public Class superClass; + public boolean isImmutable; + public boolean isDate; + public boolean isSQLDate; + + public ReflectAttrs(Class cls) { + thisClass = cls ; + String name = cls.getName(); + char ch = name.charAt(0); + + isImmutable = false; + isDate = false; + isSQLDate = false; + fields = null; + constr = null; + superClass = null; + if (ch == '[') { + arrayClass = cls.getComponentType(); + } else if (isImmutable(name)) { + isImmutable = true; + } else if (name.equals("java.util.Date")) { + isDate = true; + } else if (name.equals("java.sql.Date")) { + isSQLDate = true; + } else { + if (Externalizable.class.isAssignableFrom( cls )) + constr = getExternalizableConstructor(cls) ; + else if (Serializable.class.isAssignableFrom( cls )) + constr = getSerializableConstructor(cls) ; + if (constr != null) { constr.setAccessible(true); } + fields = cls.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + superClass = cls.getSuperclass(); + } + } + }; + + /** Bridge is used to access the reflection factory for + * obtaining serialization constructors. + * This must be carefully protected! + */ + private static final Bridge bridge = + (Bridge)AccessController.doPrivileged( + new PrivilegedAction() { + public Object run() { + return Bridge.get() ; + } + } + ) ; + + /** + * Returns public no-arg constructor of given class, or null if none found. + * Access checks are disabled on the returned constructor (if any), since + * the defining class may still be non-public. + */ + private Constructor getExternalizableConstructor(Class cl) { + try { + Constructor cons = cl.getDeclaredConstructor(new Class[0]); + cons.setAccessible(true); + return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ? cons : null; + } catch (NoSuchMethodException ex) { + //test for null on calling routine will avoid NPE just to be safe + return null; + } + } + + /** + * Returns true if classes are defined in the same package, false + * otherwise. + * + * Copied from the Merlin java.io.ObjectStreamClass. + */ + private boolean packageEquals(Class cl1, Class cl2) { + Package pkg1 = cl1.getPackage(), pkg2 = cl2.getPackage(); + return ((pkg1 == pkg2) || ((pkg1 != null) && (pkg1.equals(pkg2)))); + } + + /** + * Returns subclass-accessible no-arg constructor of first non-serializable + * superclass, or null if none found. Access checks are disabled on the + * returned constructor (if any). + */ + private Constructor getSerializableConstructor(Class cl) { + Class initCl = cl; + if (initCl == null) { + //should not be possible for initCl==null but log and return null + //test for null on calling routine will avoid NPE just to be safe + return null; + } + while (Serializable.class.isAssignableFrom(initCl)) { + if ((initCl = initCl.getSuperclass()) == null) { + return null; + } + } + try { + Constructor cons = initCl.getDeclaredConstructor(new Class[0]); + int mods = cons.getModifiers(); + if ((mods & Modifier.PRIVATE) != 0 || + ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 && + !packageEquals(cl, initCl))) + { + //test for null on calling routine will avoid NPE just to be safe + return null; + } + cons = bridge.newConstructorForSerialization(cl, cons); + cons.setAccessible(true); + return cons; + } catch (NoSuchMethodException ex) { + //test for null on calling routine will avoid NPE just to be safe + return null; + } + } + + /** + * Gets the reflection attributes for a class from the cache or + * if it is not in the cache yet, computes the attributes and + * populates the cache + * @param cls the class whose attributes are needed + * @return the attributes needed for reflection + * + * This method must be synchronized so that reflectCache.put can + * safely update the reflectCache. + */ + private final synchronized ReflectAttrs getClassAttrs(Class cls) { + ReflectAttrs attrs = null; + + attrs = (ReflectAttrs)reflectCache.get(cls); + if (attrs == null) { + attrs = new ReflectAttrs(cls); + reflectCache.put(cls, (Object)attrs); + } + return attrs; + } + + public static boolean isImmutable(String classname) { + if (classname.startsWith("java.lang.")) { + String typename = classname.substring(10); + if (typename.compareTo("String") == 0 || + typename.compareTo("Class") == 0 || + typename.compareTo("Integer") == 0 || + typename.compareTo("Boolean") == 0 || + typename.compareTo("Long") == 0 || + typename.compareTo("Double") == 0 || + typename.compareTo("Byte") == 0 || + typename.compareTo("Char") == 0 || + typename.compareTo("Short") == 0 || + typename.compareTo("Object") == 0 || + typename.compareTo("Float") == 0) { + return true; + } + } + return false; + } + + /** + * Utility to copy array of primitive types or objects. Used by local + * stubs to copy objects + * @param obj the object to copy or connect. + * @return the copied object. + * @exception RemoteException if any object could not be copied. + */ + private final Object arrayCopy(Object obj, Class aClass) + throws RemoteException, InstantiationException, + IllegalAccessException, InvocationTargetException + { + Object acopy = null; + + if (aClass.isPrimitive()) { + if (aClass == byte.class) { + acopy = ((byte[])obj).clone(); + } else if (aClass == char.class) { + acopy = ((char[])obj).clone(); + } else if (aClass == short.class) { + acopy = ((short[])obj).clone(); + } else if (aClass == int.class) { + acopy = ((int[])obj).clone(); + } else if (aClass == long.class) { + acopy = ((long[])obj).clone(); + } else if (aClass == double.class) { + acopy = ((double[])obj).clone(); + } else if (aClass == float.class) { + acopy = ((float[])obj).clone(); + } else if (aClass == boolean.class) { + acopy = ((boolean[])obj).clone(); + } + objRefs.put(obj, acopy); + } else if (aClass == String.class) { + acopy = ((String [])obj).clone(); + objRefs.put(obj, acopy); + } else { + int alen = Array.getLength(obj); + + aClass = obj.getClass().getComponentType(); + + acopy = Array.newInstance(aClass, alen); + + + objRefs.put(obj, acopy); + for (int idx=0; idx cls = obj.getClass() ; + ClassCopier copier = ccf.getClassCopier( cls ) ; + return copier.copy( oldToNew, obj) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AnyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AnyImpl.java new file mode 100644 index 000000000..63c87d955 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AnyImpl.java @@ -0,0 +1,1334 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.EncapsInputStream; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream; +import com.sun.corba.ee.impl.io.ValueUtility; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.misc.RepositoryIdFactory; +import com.sun.corba.ee.impl.misc.RepositoryIdStrings; +import com.sun.corba.ee.impl.orb.ORBSingleton; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.trace.DynamicType; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.math.BigDecimal; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.List; + +import org.glassfish.pfl.dynamic.copyobject.spi.Copy; +import org.glassfish.pfl.dynamic.copyobject.spi.CopyType; +import org.omg.CORBA.Any; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.TypeCodePackage.Bounds; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.Streamable; + +// subclasses must provide a matching helper class +@DynamicType +public class AnyImpl extends Any { + private static final long serialVersionUID = -8646067979785949029L; + + private static final class AnyInputStream extends EncapsInputStream + { + private static final long serialVersionUID = -1719923004953871705L; + public AnyInputStream(EncapsInputStream theStream ) + { + super( theStream ); + } + } + + private static final class AnyOutputStream extends EncapsOutputStream + { + private static final long serialVersionUID = 9105274185226938185L; + public AnyOutputStream(ORB orb) + { + super(orb); + } + + @Override + public org.omg.CORBA.portable.InputStream create_input_stream() + { + final org.omg.CORBA.portable.InputStream is = super + .create_input_stream(); + AnyInputStream aIS = AccessController + .doPrivileged(new PrivilegedAction() { + @Override + public AnyInputStream run() { + return new AnyInputStream( + (com.sun.corba.ee.impl.encoding.EncapsInputStream) is); + } + + }); + + return aIS; + } + } + + // + // Always valid. + // + private TypeCodeImpl typeCode; + + @Copy( CopyType.IDENTITY ) + protected transient ORB orb; + + @Copy( CopyType.IDENTITY ) + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // + // Validity depends upon typecode. The 'value' and 'object' instance + // members are used to hold immutable types as defined by the + // isStreamed[] table below. Otherwise, 'stream' is non-null and + // holds the value in CDR marshaled format. As an optimization, the + // stream type is an Any extension of CDR stream that is used to + // detect an optimization in read_value(). + // + @Copy( CopyType.IDENTITY ) + private transient CDRInputObject stream; + + private long value; + private java.lang.Object object; + + // Setting the typecode via the type() accessor wipes out the value. + // An attempt to extract before the value is set will result + // in a BAD_OPERATION exception being raised. + private boolean isInitialized = false; + + /* + * This boolean array tells us if a given typecode must be + * streamed. Objects that are immutable don't have to be streamed. + */ + static boolean isStreamed[] = { + false, // null + false, // void + false, // short + false, // long + false, // ushort + false, // ulong + false, // float + false, // double + false, // boolean + false, // char + false, // octet + false, // any + false, // TypeCode + true, // Principal + false, // objref + true, // struct + true, // union + false, // enum + false, // string + true, // sequence + true, // array + true, // alias + true, // except + false, // longlong + false, // ulonglong + false, // longdouble + false, // wchar + false, // wstring + false, // fixed + false, // value + false, // value_box (used to be true) + false, // native + false // abstract interface + }; + + // Usual FindBugs Kluge: this class isn't really Serializable in the + // normal Java sense (it is marshallable to a CDR stream), so we need + // to create a method that sets transients to null (which will never be + // called) to remove large numbers of FindBugs errors. + private void readObject( ObjectInputStream is ) + throws IOException, ClassNotFoundException { + + is.defaultReadObject(); + + stream = null ; + orb = null ; + } + + /////////////////////////////////////////////////////////////////////////// + // Constructors + + /** + * A constructor that sets the Any to contain a null. It also marks + * the value as being invalid so that extractions throw an exception + * until an insertion has been performed. + * @param orb ORB to use for this any + */ + public AnyImpl(ORB orb) + { + this.orb = orb; + + typeCode = orb.get_primitive_tc(TCKind._tk_null); + stream = null; + object = null; + value = 0; + // null is a valid value + isInitialized = true; + } + + // + // Create a new AnyImpl which is a copy of obj. + // + public AnyImpl(ORB orb, Any obj) { + this(orb); + + if ((obj instanceof AnyImpl)) { + AnyImpl objImpl = (AnyImpl)obj; + typeCode = objImpl.typeCode; + value = objImpl.value; + object = objImpl.object; + isInitialized = objImpl.isInitialized; + + if (objImpl.stream != null) { + stream = objImpl.stream.dup(); + } + + } else { + read_value(obj.create_input_stream(), obj.type()); + } + } + + /////////////////////////////////////////////////////////////////////////// + // basic accessors + + /** + * returns the type of the element contained in the Any. + * + * @return the TypeCode for the element in the Any + */ + public TypeCode type() { + return typeCode; + } + + private TypeCode realType() { + return realType(typeCode); + } + + private TypeCode realType(TypeCode aType) { + TypeCode realType = aType; + try { + // Note: Indirect types are handled in kind() method + while (realType.kind().value() == TCKind._tk_alias) { + realType = realType.content_type(); + } + } catch (BadKind bad) { // impossible + throw wrapper.badkindCannotOccur( bad ) ; + } + return realType; + } + + /** + * sets the type of the element to be contained in the Any. + * + * @param tc the TypeCode for the element in the Any + */ + public void type(TypeCode tc) + { + //debug.log ("type2"); + // set the typecode + typeCode = TypeCodeImpl.convertToNative(orb, tc); + + stream = null; + value = 0; + object = null; + // null is the only legal value this Any can have after resetting the type code + isInitialized = (tc.kind().value() == TCKind._tk_null); + } + + /** + * checks for equality between Anys. + * + * @param otherAny the Any to be compared with. + * @return true if the Anys are equal, false otherwise. + */ + @DynamicType + public boolean equal(Any otherAny) { + if (otherAny == this) { + return true; + } + + // first check for typecode equality. + // note that this will take aliases into account + if (!typeCode.equal(otherAny.type())) { + return false; + } + + // Resolve aliases here + TypeCode realType = realType(); + + switch (realType.kind().value()) { + // handle primitive types + case TCKind._tk_null: + case TCKind._tk_void: + return true; + case TCKind._tk_short: + return (extract_short() == otherAny.extract_short()); + case TCKind._tk_long: + return (extract_long() == otherAny.extract_long()); + case TCKind._tk_ushort: + return (extract_ushort() == otherAny.extract_ushort()); + case TCKind._tk_ulong: + return (extract_ulong() == otherAny.extract_ulong()); + case TCKind._tk_float: + return (extract_float() == otherAny.extract_float()); + case TCKind._tk_double: + return (extract_double() == otherAny.extract_double()); + case TCKind._tk_boolean: + return (extract_boolean() == otherAny.extract_boolean()); + case TCKind._tk_char: + return (extract_char() == otherAny.extract_char()); + case TCKind._tk_wchar: + return (extract_wchar() == otherAny.extract_wchar()); + case TCKind._tk_octet: + return (extract_octet() == otherAny.extract_octet()); + case TCKind._tk_any: + return extract_any().equal(otherAny.extract_any()); + case TCKind._tk_TypeCode: + return extract_TypeCode().equal(otherAny.extract_TypeCode()); + case TCKind._tk_string: + return extract_string().equals(otherAny.extract_string()); + case TCKind._tk_wstring: + return (extract_wstring().equals(otherAny.extract_wstring())); + case TCKind._tk_longlong: + return (extract_longlong() == otherAny.extract_longlong()); + case TCKind._tk_ulonglong: + return (extract_ulonglong() == otherAny.extract_ulonglong()); + + case TCKind._tk_objref: + return (extract_Object().equals(otherAny.extract_Object())); + case TCKind._tk_Principal: + return (extract_Principal().equals(otherAny.extract_Principal())); + + case TCKind._tk_enum: + return (extract_long() == otherAny.extract_long()); + case TCKind._tk_fixed: + return (extract_fixed().compareTo(otherAny.extract_fixed()) == 0); + case TCKind._tk_except: + case TCKind._tk_struct: + case TCKind._tk_union: + case TCKind._tk_sequence: + case TCKind._tk_array: + InputStream copyOfMyStream = this.create_input_stream(); + InputStream copyOfOtherStream = otherAny.create_input_stream(); + return equalMember(realType, copyOfMyStream, copyOfOtherStream); + + // Too complicated to handle value types the way we handle + // other complex types above. Don't try to decompose it here + // for faster comparison, just use Object.equals(). + case TCKind._tk_value: + case TCKind._tk_value_box: + return extract_Value().equals(otherAny.extract_Value()); + + case TCKind._tk_alias: + throw wrapper.errorResolvingAlias() ; + + case TCKind._tk_longdouble: + // Unspecified for Java + throw wrapper.tkLongDoubleNotSupported() ; + + default: + throw wrapper.typecodeNotSupported() ; + } + } + + // Needed for equal() in order to achieve linear performance for complex types. + // Uses up (recursively) copies of the InputStream in both Anys that got created in equal(). + @DynamicType + private boolean equalMember(TypeCode memberType, InputStream myStream, InputStream otherStream) { + // Resolve aliases here + TypeCode realType = realType(memberType); + + try { + switch (realType.kind().value()) { + // handle primitive types + case TCKind._tk_null: + case TCKind._tk_void: + return true; + case TCKind._tk_short: + return (myStream.read_short() == otherStream.read_short()); + case TCKind._tk_long: + return (myStream.read_long() == otherStream.read_long()); + case TCKind._tk_ushort: + return (myStream.read_ushort() == otherStream.read_ushort()); + case TCKind._tk_ulong: + return (myStream.read_ulong() == otherStream.read_ulong()); + case TCKind._tk_float: + return (myStream.read_float() == otherStream.read_float()); + case TCKind._tk_double: + return (myStream.read_double() == otherStream.read_double()); + case TCKind._tk_boolean: + return (myStream.read_boolean() == otherStream.read_boolean()); + case TCKind._tk_char: + return (myStream.read_char() == otherStream.read_char()); + case TCKind._tk_wchar: + return (myStream.read_wchar() == otherStream.read_wchar()); + case TCKind._tk_octet: + return (myStream.read_octet() == otherStream.read_octet()); + case TCKind._tk_any: + return myStream.read_any().equal(otherStream.read_any()); + case TCKind._tk_TypeCode: + return myStream.read_TypeCode().equal(otherStream.read_TypeCode()); + case TCKind._tk_string: + return myStream.read_string().equals(otherStream.read_string()); + case TCKind._tk_wstring: + return (myStream.read_wstring().equals(otherStream.read_wstring())); + case TCKind._tk_longlong: + return (myStream.read_longlong() == otherStream.read_longlong()); + case TCKind._tk_ulonglong: + return (myStream.read_ulonglong() == otherStream.read_ulonglong()); + + case TCKind._tk_objref: + return (myStream.read_Object().equals(otherStream.read_Object())); + case TCKind._tk_Principal: + return (myStream.read_Principal().equals(otherStream.read_Principal())); + + case TCKind._tk_enum: + return (myStream.read_long() == otherStream.read_long()); + case TCKind._tk_fixed: + return (myStream.read_fixed().compareTo(otherStream.read_fixed()) == 0); + case TCKind._tk_except: + case TCKind._tk_struct: { + int length = realType.member_count(); + for (int i=0; i() { + + @Override + public OutputStream run() { + return new AnyOutputStream(finalOrb); + } + + }); + } + + /** + * returns an input stream that an Any value can be marshaled out of. + * + * @return the InputStream to marshal value of Any out of. + */ + @DynamicType + public org.omg.CORBA.portable.InputStream create_input_stream() { + // We create a new InputStream so that multiple threads can call here + // and read the streams in parallel without thread safety problems. + // + //debug.log ("create_input_stream"); + if (AnyImpl.isStreamed[realType().kind().value()]) { + return stream.dup(); + } else { + OutputStream os = orb.create_output_stream(); + TCUtility.marshalIn(os, realType(), value, object); + + return os.create_input_stream(); + } + } + + /////////////////////////////////////////////////////////////////////////// + // marshaling/unmarshaling routines + + // + // If the InputStream is a CDRInputStream then we can copy the bytes + // since it is in our format and does not have alignment issues. + // + @DynamicType + public void read_value(org.omg.CORBA.portable.InputStream in, TypeCode tc) { + // Assume that someone isn't going to think they can keep reading + // from this stream after calling us. That would be likely for + // an IIOPInputStream but if it is an AnyInputStream then they + // presumably obtained it via our create_output_stream() so they could + // write the contents of an IDL data type to it and then call + // create_input_stream() for us to read it. This is how Helper classes + // typically implement the insert() method. + + typeCode = TypeCodeImpl.convertToNative(orb, tc); + int kind = realType().kind().value(); + if (kind >= isStreamed.length) { + throw wrapper.invalidIsstreamedTckind( kind) ; + } + + if (AnyImpl.isStreamed[kind]) { + if ( in instanceof AnyInputStream ) { + // could only have been created here + stream = (CDRInputObject)in; + } else { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream)orb.create_output_stream(); + typeCode.copy(in, out); + stream = (CDRInputObject)out.create_input_stream(); + } + } else { + java.lang.Object[] objholder = new java.lang.Object[1]; + objholder[0] = object; + long[] longholder = new long[1]; + // Fix for bug 5036554/4712731: realType() instead of typecode + TCUtility.unmarshalIn(in, realType(), longholder, objholder); + value = longholder[0]; + object = objholder[0]; + stream = null; + } + isInitialized = true; + } + + + // + // We could optimize this by noticing whether the target stream + // has ever had anything marshaled on it that required an + // alignment of greater than 4 (was write_double() ever called on it). + // If not, then we can just do a byte array copy without having to + // drive the remarshaling through typecode interpretation. + // + @DynamicType + public void write_value(OutputStream out) { + if (AnyImpl.isStreamed[realType().kind().value()]) { + typeCode.copy(stream.dup(), out); + } else { + // _REVISIT_ check isInitialized whether all we write is TypeCode! + TCUtility.marshalIn(out, realType(), value, object); + } + } + + /** + * takes a streamable and inserts its reference into the any + * + * @param s the streamable to insert + */ + @Override + public void insert_Streamable(Streamable s) + { + //debug.log ("insert_Streamable"); + typeCode = TypeCodeImpl.convertToNative(orb, s._type()); + object = s; + isInitialized = true; + } + + @Override + public Streamable extract_Streamable() + { + //debug.log( "extract_Streamable" ) ; + return (Streamable)object; + } + + /////////////////////////////////////////////////////////////////////////// + // insertion/extraction/replacement for all basic types + + /** + * See the description of the general Any operations. + */ + public void insert_short(short s) + { + //debug.log ("insert_short"); + typeCode = orb.get_primitive_tc(TCKind._tk_short); + value = s; + isInitialized = true; + } + + private String getTCKindName( int tc ) + { + if ((tc >= 0) && (tc < TypeCodeImpl.kindNames.length)) { + return TypeCodeImpl.kindNames[tc]; + } else { + return "UNKNOWN(" + tc + ")"; + } + } + + private void checkExtractBadOperation( int expected ) + { + if (!isInitialized) { + throw wrapper.extractNotInitialized(); + } + + int tc = realType().kind().value() ; + if (tc != expected) { + String tcName = getTCKindName( tc ) ; + String expectedName = getTCKindName( expected ) ; + throw wrapper.extractWrongType( expectedName, tcName ) ; + } + } + + private void checkExtractBadOperationList( int[] expected ) + { + if (!isInitialized) { + throw wrapper.extractNotInitialized(); + } + + int tc = realType().kind().value() ; + for (int anExpected1 : expected) { + if (tc == anExpected1) { + return; + } + } + + List list = new ArrayList() ; + for (int anExpected : expected) { + list.add(getTCKindName(anExpected)); + } + + String tcName = getTCKindName( tc ) ; + throw wrapper.extractWrongTypeList( list, tcName ) ; + } + + /** + * See the description of the general Any operations. + */ + public short extract_short() + { + //debug.log ("extract_short"); + checkExtractBadOperation( TCKind._tk_short ) ; + return (short)value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_long(int l) + { + //debug.log ("insert_long"); + // A long value is applicable to enums as well, so don't erase the enum type code + // in case it was initialized that way before. + int kind = realType().kind().value(); + if (kind != TCKind._tk_long && kind != TCKind._tk_enum) { + typeCode = orb.get_primitive_tc(TCKind._tk_long); + } + value = l; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public int extract_long() + { + //debug.log ("extract_long"); + checkExtractBadOperationList( new int[] { TCKind._tk_long, TCKind._tk_enum } ) ; + return (int)value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_ushort(short s) + { + //debug.log ("insert_ushort"); + typeCode = orb.get_primitive_tc(TCKind._tk_ushort); + value = s; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public short extract_ushort() + { + //debug.log ("extract_ushort"); + checkExtractBadOperation( TCKind._tk_ushort ) ; + return (short)value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_ulong(int l) + { + //debug.log ("insert_ulong"); + typeCode = orb.get_primitive_tc(TCKind._tk_ulong); + value = l; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public int extract_ulong() + { + //debug.log ("extract_ulong"); + checkExtractBadOperation( TCKind._tk_ulong ) ; + return (int)value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_float(float f) + { + //debug.log ("insert_float"); + typeCode = orb.get_primitive_tc(TCKind._tk_float); + value = Float.floatToIntBits(f); + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public float extract_float() + { + //debug.log ("extract_float"); + checkExtractBadOperation( TCKind._tk_float ) ; + return Float.intBitsToFloat((int)value); + } + + /** + * See the description of the general Any operations. + */ + public void insert_double(double d) + { + //debug.log ("insert_double"); + typeCode = orb.get_primitive_tc(TCKind._tk_double); + value = Double.doubleToLongBits(d); + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public double extract_double() + { + //debug.log ("extract_double"); + checkExtractBadOperation( TCKind._tk_double ) ; + return Double.longBitsToDouble(value); + } + + /** + * See the description of the general Any operations. + */ + public void insert_longlong(long l) + { + //debug.log ("insert_longlong"); + typeCode = orb.get_primitive_tc(TCKind._tk_longlong); + value = l; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public long extract_longlong() + { + //debug.log ("extract_longlong"); + checkExtractBadOperation( TCKind._tk_longlong ) ; + return value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_ulonglong(long l) + { + //debug.log ("insert_ulonglong"); + typeCode = orb.get_primitive_tc(TCKind._tk_ulonglong); + value = l; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public long extract_ulonglong() + { + //debug.log ("extract_ulonglong"); + checkExtractBadOperation( TCKind._tk_ulonglong ) ; + return value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_boolean(boolean b) + { + //debug.log ("insert_boolean"); + typeCode = orb.get_primitive_tc(TCKind._tk_boolean); + value = (b)? 1:0; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public boolean extract_boolean() + { + //debug.log ("extract_boolean"); + checkExtractBadOperation( TCKind._tk_boolean ) ; + return value != 0; + } + + /** + * See the description of the general Any operations. + */ + public void insert_char(char c) + { + //debug.log ("insert_char"); + typeCode = orb.get_primitive_tc(TCKind._tk_char); + value = c; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public char extract_char() + { + //debug.log ("extract_char"); + checkExtractBadOperation( TCKind._tk_char ) ; + return (char)value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_wchar(char c) + { + //debug.log ("insert_wchar"); + typeCode = orb.get_primitive_tc(TCKind._tk_wchar); + value = c; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public char extract_wchar() + { + //debug.log ("extract_wchar"); + checkExtractBadOperation( TCKind._tk_wchar ) ; + return (char)value; + } + + + /** + * See the description of the general Any operations. + */ + public void insert_octet(byte b) + { + //debug.log ("insert_octet"); + typeCode = orb.get_primitive_tc(TCKind._tk_octet); + value = b; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public byte extract_octet() + { + //debug.log ("extract_octet"); + checkExtractBadOperation( TCKind._tk_octet ) ; + return (byte)value; + } + + /** + * See the description of the general Any operations. + */ + public void insert_string(String s) + { + //debug.log ("insert_string"); + // Make sure type code information for bounded strings is not erased + if (typeCode.kind() == TCKind.tk_string) { + int length; + try { + length = typeCode.length(); + } catch (BadKind bad) { + throw wrapper.badkindCannotOccur() ; + } + + // Check if bounded strings length is not exceeded + if (length != 0 && s != null && s.length() > length) { + throw wrapper.badStringBounds(s.length(), length) ; + } + } else { + typeCode = orb.get_primitive_tc(TCKind._tk_string); + } + object = s; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public String extract_string() + { + //debug.log ("extract_string"); + checkExtractBadOperation( TCKind._tk_string ) ; + return (String)object; + } + + /** + * See the description of the general Any operations. + */ + public void insert_wstring(String s) + { + //debug.log ("insert_wstring"); + // Make sure type code information for bounded strings is not erased + if (typeCode.kind() == TCKind.tk_wstring) { + int length; + try { + length = typeCode.length(); + } catch (BadKind bad) { + throw wrapper.badkindCannotOccur() ; + } + + // Check if bounded strings length is not exceeded + if (length != 0 && s != null && s.length() > length) { + throw wrapper.badStringBounds( s.length(), length ) ; + } + } else { + typeCode = orb.get_primitive_tc(TCKind._tk_wstring); + } + object = s; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public String extract_wstring() + { + //debug.log ("extract_wstring"); + checkExtractBadOperation( TCKind._tk_wstring ) ; + return (String)object; + } + + /** + * See the description of the general Any operations. + */ + public void insert_any(Any a) + { + //debug.log ("insert_any"); + typeCode = orb.get_primitive_tc(TCKind._tk_any); + object = a; + stream = null; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public Any extract_any() + { + //debug.log ("extract_any"); + checkExtractBadOperation( TCKind._tk_any ) ; + return (Any)object; + } + + /** + * See the description of the general Any operations. + */ + public void insert_Object(org.omg.CORBA.Object o) + { + //debug.log ("insert_Object"); + if ( o == null ) { + typeCode = orb.get_primitive_tc(TCKind._tk_objref); + } else { + if (StubAdapter.isStub(o)) { + String[] ids = StubAdapter.getTypeIds( o ) ; + typeCode = new TypeCodeImpl(orb, TCKind._tk_objref, ids[0], ""); + } else { + throw wrapper.badInsertobjParam( o.getClass().getName() ) ; + } + } + + object = o; + isInitialized = true; + } + + /** + * A variant of the insertion operation that takes a typecode + * argument as well. + * @param tc TypeCode to insert into o. + */ + public void insert_Object(org.omg.CORBA.Object o, TypeCode tc) + { + //debug.log ("insert_Object2"); + try { + if ( tc.id().equals("IDL:omg.org/CORBA/Object:1.0") || o._is_a(tc.id()) ) { + typeCode = TypeCodeImpl.convertToNative(orb, tc); + object = o; + } else { + throw wrapper.insertObjectIncompatible() ; + } + } catch ( Exception ex ) { + throw wrapper.insertObjectFailed(ex) ; + } + + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public org.omg.CORBA.Object extract_Object() + { + //debug.log ("extract_Object"); + if (!isInitialized) { + throw wrapper.extractNotInitialized(); + } + + // Check if the object contained here is of the type in typeCode + org.omg.CORBA.Object obj; + try { + obj = (org.omg.CORBA.Object) object; + if (typeCode.id().equals("IDL:omg.org/CORBA/Object:1.0") || obj._is_a(typeCode.id())) { + return obj; + } else { + throw wrapper.extractObjectIncompatible() ; + } + } catch ( Exception ex ) { + throw wrapper.extractObjectFailed(ex); + } + } + + /** + * See the description of the general Any operations. + * @param tc TypeCode to insert. + */ + public void insert_TypeCode(TypeCode tc) + { + //debug.log ("insert_TypeCode"); + typeCode = orb.get_primitive_tc(TCKind._tk_TypeCode); + object = tc; + isInitialized = true; + } + + /** + * See the description of the general Any operations. + */ + public TypeCode extract_TypeCode() + { + //debug.log ("extract_TypeCode"); + checkExtractBadOperation( TCKind._tk_TypeCode ) ; + return (TypeCode)object; + } + + @SuppressWarnings({"deprecation"}) + @Override + public void insert_Principal(org.omg.CORBA.Principal p) + { + typeCode = orb.get_primitive_tc(TCKind._tk_Principal); + object = p; + isInitialized = true; + } + + @SuppressWarnings({"deprecation"}) + @Override + public org.omg.CORBA.Principal extract_Principal() + { + checkExtractBadOperation( TCKind._tk_Principal ) ; + return org.omg.CORBA.Principal.class.cast( object ) ; + } + + /** + * Note that the Serializable really should be an IDLEntity of + * some kind. It shouldn't just be an RMI-IIOP type. Currently, + * we accept and will produce RMI repIds with the latest + * calculations if given a non-IDLEntity Serializable. + */ + public Serializable extract_Value() + { + //debug.log ("extract_Value"); + checkExtractBadOperationList( new int[] { TCKind._tk_value, + TCKind._tk_value_box, TCKind._tk_abstract_interface } ) ; + return (Serializable)object; + } + + public void insert_Value(Serializable v) + { + //debug.log ("insert_Value"); + object = v; + + TypeCode tc; + + if ( v == null ) { + tc = orb.get_primitive_tc (TCKind.tk_value); + } else { + // See note in getPrimitiveTypeCodeForClass. We + // have to use the latest type code fixes in this + // case since there is no way to know what ORB will + // actually send this Any. In RMI-IIOP, when using + // Util.writeAny, we can do the versioning correctly, + // and use the insert_Value(Serializable, TypeCode) + // method. + // + // The ORB singleton uses the latest version. + tc = createTypeCodeForClass(v.getClass(), new ORBSingleton()); + } + + typeCode = TypeCodeImpl.convertToNative(orb, tc); + isInitialized = true; + } + + public void insert_Value(Serializable v, org.omg.CORBA.TypeCode t) + { + //debug.log ("insert_Value2"); + object = v; + typeCode = TypeCodeImpl.convertToNative(orb, t); + isInitialized = true; + } + + @Override + public void insert_fixed(java.math.BigDecimal value) { + typeCode = TypeCodeImpl.convertToNative(orb, + orb.create_fixed_tc(TypeCodeImpl.digits(value), TypeCodeImpl.scale(value))); + object = value; + isInitialized = true; + } + + @Override + public void insert_fixed(java.math.BigDecimal value, org.omg.CORBA.TypeCode type) + { + try { + if (TypeCodeImpl.digits(value) > type.fixed_digits() || + TypeCodeImpl.scale(value) > type.fixed_scale()) + { + throw wrapper.fixedNotMatch() ; + } + } catch (org.omg.CORBA.TypeCodePackage.BadKind bk) { + // type isn't even of kind fixed + throw wrapper.fixedBadTypecode( bk ) ; + } + typeCode = TypeCodeImpl.convertToNative(orb, type); + object = value; + isInitialized = true; + } + + @Override + public java.math.BigDecimal extract_fixed() { + checkExtractBadOperation( TCKind._tk_fixed ) ; + return (BigDecimal)object; + } + + /** + * Utility method for insert_Value and Util.writeAny. + * + * The ORB passed in should have the desired ORBVersion. It + * is used to generate the type codes. + * @param c The Class for which a TypeCode is needed. + * @param tcORB ORB to use when creating TypeCode. + * @return The newly created TypeCode. + */ + @DynamicType + public static TypeCode createTypeCodeForClass (java.lang.Class c, ORB tcORB) { + // Look in the cache first + TypeCodeImpl classTC = tcORB.getTypeCodeForClass(c); + if (classTC != null) { + return classTC; + } + + // All cases need to be able to create repository IDs. + // + // See bug 4391648 for more info about the tcORB in this + // case. + RepositoryIdStrings repStrs + = RepositoryIdFactory.getRepIdStringsFactory(); + + + // Assertion: c instanceof Serializable? + + if ( c.isArray() ) { + // Arrays - may recurse for multi-dimensional arrays + Class componentClass = c.getComponentType(); + TypeCode embeddedType; + if ( componentClass.isPrimitive() ) { + embeddedType = getPrimitiveTypeCodeForClass(componentClass, + tcORB); + } else { + embeddedType = createTypeCodeForClass (componentClass, + tcORB); + } + TypeCode t = tcORB.create_sequence_tc (0, embeddedType); + + String id = repStrs.createForJavaType(c); + + return tcORB.create_value_box_tc (id, "Sequence", t); + } else if ( c == java.lang.String.class ) { + // Strings + TypeCode t = tcORB.create_string_tc (0); + + String id = repStrs.createForJavaType(c); + + return tcORB.create_value_box_tc (id, "StringValue", t); + } + + // Anything else + // We know that this is a TypeCodeImpl since it is our ORB + classTC = (TypeCodeImpl)ValueUtility.createTypeCodeForClass(tcORB, c, ORBUtility.createValueHandler()); + // Intruct classTC to store its buffer + classTC.setCaching(true); + // Update the cache + tcORB.setTypeCodeForClass(c, classTC); + return classTC; + } + + /** + * It looks like this was copied from io.ValueUtility at some + * point. + * + * It's used by createTypeCodeForClass. The tcORB passed in + * should have the desired ORB version, and is used to + * create the type codes. + * @param c the class + * @param tcORB the orb to use to find the type code + * @return the appropriate primitive type code + */ + private static TypeCode getPrimitiveTypeCodeForClass (Class c, ORB tcORB) + { + //debug.log ("getPrimitiveTypeCodeForClass"); + + if (c == Integer.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_long); + } else if (c == Byte.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_octet); + } else if (c == Long.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_longlong); + } else if (c == Float.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_float); + } else if (c == Double.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_double); + } else if (c == Short.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_short); + } else if (c == Character.TYPE) { + // For Merlin or later JDKs, or for foreign ORBs, + // we correctly say that a Java char maps to a + // CORBA wchar. For backwards compatibility + // with our older ORBs, we say it maps to a + // CORBA char. This is only used in RMI-IIOP + // in our javax.rmi.CORBA.Util delegate's + // writeAny method. In Java IDL, there's no way + // to know the ORB version that the Any will be + // sent out with -- it could be different than + // the one used to create the Any -- so we use the + // most recent version (see insert_Value). + if (ORBVersionFactory.getFOREIGN().compareTo(tcORB.getORBVersion()) == 0 || + ORBVersionFactory.getNEWER().compareTo(tcORB.getORBVersion()) <= 0) { + return tcORB.get_primitive_tc(TCKind.tk_wchar); + } else { + return tcORB.get_primitive_tc(TCKind.tk_char); + } + } else if (c == Boolean.TYPE) { + return tcORB.get_primitive_tc (TCKind.tk_boolean); + } else { + // _REVISIT_ Not sure if this is right. + return tcORB.get_primitive_tc (TCKind.tk_any); + } + } + + // This method could very well be moved into TypeCodeImpl or a common utility class, + // but is has to be in this package. + static public Any extractAnyFromStream(TypeCode memberType, InputStream input, ORB orb) { + Any returnValue = orb.create_any(); + OutputStream out = returnValue.create_output_stream(); + TypeCodeImpl.convertToNative(orb, memberType).copy(input, out); + returnValue.read_value(out.create_input_stream(), memberType); + return returnValue; + } + + // There is no other way for DynAnys to find out whether the Any is initialized. + public boolean isInitialized() { + return isInitialized; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AnyImplHelper.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AnyImplHelper.java new file mode 100644 index 000000000..a348f4ee5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AnyImplHelper.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +abstract public class AnyImplHelper +{ + private static String _id = "IDL:omg.org/CORBA/Any:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.Any that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.CORBA.Any extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_any); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.CORBA.Any read (org.omg.CORBA.portable.InputStream istream) + { + return istream.read_any (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.Any value) + { + ostream.write_any (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AsynchInvoke.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AsynchInvoke.java new file mode 100644 index 000000000..8544a1809 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/AsynchInvoke.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import com.sun.corba.ee.spi.orb.ORB ; + +/////////////////////////////////////////////////////////////////////////// +// helper class for deferred invocations + +/* + * The AsynchInvoke class allows for the support of asynchronous + * invocations. Instances of these are created with a request object, + * and when run, perform an invocation. The instance is also + * responsible for waking up a client that might be waiting on the + * 'get_response' method. + */ + +public class AsynchInvoke implements Runnable { + + private final RequestImpl _req; + private final ORB _orb; + private final boolean _notifyORB; + + public AsynchInvoke (ORB o, RequestImpl reqToInvokeOn, boolean n) + { + _orb = o; + _req = reqToInvokeOn; + _notifyORB = n; + }; + + + /* + * The run operation calls the invocation on the request object, + * updates the RequestImpl state to indicate that the asynchronous + * invocation is complete, and wakes up any client that might be + * waiting on a 'get_response' call. + * + */ + + public void run() + { + synchronized (_req) { + // do the actual invocation + _req.doInvocation(); + } + + // for the asynchronous case, note that the response has been + // received. + synchronized (_req) { + // update local boolean indicator + _req.gotResponse = true; + + // notify any client waiting on a 'get_response' + _req.notify(); + } + + if (_notifyORB == true) { + _orb.notifyORB() ; + } + } + +}; + +/////////////////////////////////////////////////////////////////////////// diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/CORBAObjectImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/CORBAObjectImpl.java new file mode 100644 index 000000000..1cd1eb637 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/CORBAObjectImpl.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +// +// Bare implementation of CORBA Object. +// +public class CORBAObjectImpl extends org.omg.CORBA_2_3.portable.ObjectImpl { + public String[] _ids() { + String[] typeids = new String[1]; + typeids[0] = "IDL:omg.org/CORBA/Object:1.0"; + return typeids; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ContextImpl.java new file mode 100644 index 000000000..0b2ceb2ab --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ContextImpl.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import org.omg.CORBA.Any; +import org.omg.CORBA.Context; +import org.omg.CORBA.NVList; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +public final class ContextImpl extends Context { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private org.omg.CORBA.ORB _orb; + + public ContextImpl(org.omg.CORBA.ORB orb) + { + _orb = orb; + } + + public ContextImpl(Context parent) + { + // Ignore: no wrapper available + } + + public String context_name() + { + throw wrapper.contextNotImplemented() ; + } + + public Context parent() + { + throw wrapper.contextNotImplemented() ; + } + + public Context create_child(String name) + { + throw wrapper.contextNotImplemented() ; + } + + public void set_one_value(String propName, Any propValue) + { + throw wrapper.contextNotImplemented() ; + } + + public void set_values(NVList values) + { + throw wrapper.contextNotImplemented() ; + } + + + public void delete_values(String propName) + { + throw wrapper.contextNotImplemented() ; + } + + public NVList get_values(String startScope, + int opFlags, + String propName) + { + throw wrapper.contextNotImplemented() ; + } +}; + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ContextListImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ContextListImpl.java new file mode 100644 index 000000000..1e7dc62b5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ContextListImpl.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import java.util.List; +import java.util.ArrayList; +import org.omg.CORBA.ContextList; +import org.omg.CORBA.Bounds; +import org.omg.CORBA.ORB; + +public class ContextListImpl extends ContextList +{ + private final static int INITIAL_CAPACITY = 2; + + private org.omg.CORBA.ORB _orb; + private List _contexts; + + public ContextListImpl(org.omg.CORBA.ORB orb) + { + // Note: This orb could be an instanceof ORBSingleton or ORB + _orb = orb; + _contexts = new ArrayList(INITIAL_CAPACITY); + } + + public synchronized int count() + { + return _contexts.size(); + } + + public synchronized void add(String ctxt) + { + _contexts.add(ctxt); + } + + public synchronized String item(int index) + throws Bounds + { + try { + return _contexts.get(index); + } catch (IndexOutOfBoundsException e) { + throw new Bounds(); + } + } + + public synchronized void remove(int index) + throws Bounds + { + try { + _contexts.remove(index); + } catch (IndexOutOfBoundsException e) { + throw new Bounds(); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/EnvironmentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/EnvironmentImpl.java new file mode 100644 index 000000000..2930d6458 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/EnvironmentImpl.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import org.omg.CORBA.Environment; +import org.omg.CORBA.UserException; +import org.omg.CORBA.ORB; + +public class EnvironmentImpl extends Environment { + + private Exception _exc; + + public EnvironmentImpl() + { + } + + public Exception exception() + { + return _exc; + } + + public void exception(Exception exc) + { + _exc = exc; + } + + public void clear() + { + _exc = null; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ExceptionListImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ExceptionListImpl.java new file mode 100644 index 000000000..68eef4515 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ExceptionListImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import java.util.List; +import java.util.ArrayList; + +import org.omg.CORBA.Bounds; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.ORB; + + +public class ExceptionListImpl extends ExceptionList { + + private static final int INITIAL_CAPACITY = 2; + + private List _exceptions; + + public ExceptionListImpl() { + _exceptions = new ArrayList(INITIAL_CAPACITY); + } + + public synchronized int count() + { + return _exceptions.size(); + } + + public synchronized void add(TypeCode tc) + { + _exceptions.add(tc); + } + + public synchronized TypeCode item(int index) + throws Bounds + { + try { + return _exceptions.get(index); + } catch (IndexOutOfBoundsException e) { + throw new Bounds(); + } + } + + public synchronized void remove(int index) + throws Bounds + { + try { + _exceptions.remove(index); + } catch (IndexOutOfBoundsException e) { + throw new Bounds(); + } + } + +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/NVListImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/NVListImpl.java new file mode 100644 index 000000000..48948fc93 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/NVListImpl.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import java.util.List; +import java.util.ArrayList; + +import org.omg.CORBA.Any; +import org.omg.CORBA.Bounds; +import org.omg.CORBA.NVList; +import org.omg.CORBA.NamedValue; + +import com.sun.corba.ee.spi.orb.ORB ; + +public class NVListImpl extends NVList +{ + private final static int INITIAL_CAPACITY = 4; + + private List _namedValues; + private ORB orb; + + public NVListImpl(ORB orb) + { + // Note: This orb could be an instanceof ORBSingleton or ORB + this.orb = orb; + _namedValues = new ArrayList(INITIAL_CAPACITY); + } + + public NVListImpl(ORB orb, int size) + { + this.orb = orb; + + // Note: the size arg is only a hint of the size of the NVList. + _namedValues = new ArrayList(size); + } + + public synchronized int count() + { + return _namedValues.size(); + } + + public synchronized NamedValue add(int flags) + { + NamedValue tmpVal = new NamedValueImpl(orb, "", new AnyImpl(orb), flags); + _namedValues.add(tmpVal); + return tmpVal; + } + + public synchronized NamedValue add_item(String itemName, int flags) + { + NamedValue tmpVal = new NamedValueImpl(orb, itemName, new AnyImpl(orb), + flags); + _namedValues.add(tmpVal); + return tmpVal; + } + + public synchronized NamedValue add_value(String itemName, Any val, int flags) + { + NamedValue tmpVal = new NamedValueImpl(orb, itemName, val, flags); + _namedValues.add(tmpVal); + return tmpVal; + } + + public synchronized NamedValue item(int index) + throws Bounds + { + try { + return _namedValues.get(index); + } catch (IndexOutOfBoundsException e) { + throw new Bounds(); + } + } + + public synchronized void remove(int index) + throws Bounds + { + try { + _namedValues.remove(index); + } catch (IndexOutOfBoundsException e) { + throw new Bounds(); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/NamedValueImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/NamedValueImpl.java new file mode 100644 index 000000000..4c63a1c48 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/NamedValueImpl.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.Any; + +import com.sun.corba.ee.spi.orb.ORB ; + +public class NamedValueImpl extends NamedValue +{ + private String _name; + private Any _value; + private int _flags; + private ORB _orb; + + public NamedValueImpl(ORB orb) + { + // Note: This orb could be an instanceof ORBSingleton or ORB + _orb = orb; + _value = new AnyImpl(_orb); + } + + public NamedValueImpl(ORB orb, + String name, + Any value, + int flags) + { + // Note: This orb could be an instanceof ORBSingleton or ORB + _orb = orb; + _name = name; + _value = value; + _flags = flags; + } + + public String name() + { + return _name; + } + + public Any value() + { + return _value; + } + + public int flags() + { + return _flags; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/PrincipalImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/PrincipalImpl.java new file mode 100644 index 000000000..bd26a3750 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/PrincipalImpl.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + + +@SuppressWarnings({"deprecation"}) +public class PrincipalImpl extends org.omg.CORBA.Principal +{ + private byte[] value; + + public void name(byte[] value) + { + this.value = value.clone(); + } + + public byte[] name() + { + return value.clone() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/RequestImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/RequestImpl.java new file mode 100644 index 000000000..4f90a95f9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/RequestImpl.java @@ -0,0 +1,350 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + + +import org.omg.CORBA.Any; +import org.omg.CORBA.ARG_IN; +import org.omg.CORBA.ARG_OUT; +import org.omg.CORBA.ARG_INOUT; +import org.omg.CORBA.Context; +import org.omg.CORBA.ContextList; +import org.omg.CORBA.Environment; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.NVList; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.Request; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; + +import org.omg.CORBA.portable.ApplicationException ; +import org.omg.CORBA.portable.RemarshalException ; +import org.omg.CORBA.portable.InputStream ; +import org.omg.CORBA.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +public class RequestImpl + extends Request +{ + /////////////////////////////////////////////////////////////////////////// + // data members + + protected org.omg.CORBA.Object _target; + protected String _opName; + protected NVList _arguments; + protected ExceptionList _exceptions; + private NamedValue _result; + protected Environment _env; + private Context _ctx; + private ContextList _ctxList; + protected ORB _orb; + private static final ORBUtilSystemException _wrapper = + ORBUtilSystemException.self ; + + // invocation-specific stuff + protected boolean _isOneWay = false; + private int[] _paramCodes; + private long[] _paramLongs; + private java.lang.Object[] _paramObjects; + + // support for deferred invocations. + // protected instead of private since it needs to be set by the + // thread object doing the asynchronous invocation. + protected boolean gotResponse = false; + + /////////////////////////////////////////////////////////////////////////// + // constructor + + // REVISIT - used to be protected. Now public so it can be + // accessed from xgiop. + public RequestImpl (ORB orb, + org.omg.CORBA.Object targetObject, + Context ctx, + String operationName, + NVList argumentList, + NamedValue resultContainer, + ExceptionList exceptionList, + ContextList ctxList) + { + + // initialize the orb + _orb = orb; + + // initialize target, context and operation name + _target = targetObject; + _ctx = ctx; + _opName = operationName; + + // initialize argument list if not passed in + if (argumentList == null) { + _arguments = new NVListImpl(_orb); + } else { + _arguments = argumentList; + } + + // set result container. + _result = resultContainer; + + // initialize exception list if not passed in + if (exceptionList == null) { + _exceptions = new ExceptionListImpl(); + } else { + _exceptions = exceptionList; + } + + // initialize context list if not passed in + if (ctxList == null) { + _ctxList = new ContextListImpl(_orb); + } else { + _ctxList = ctxList; + } + + // initialize environment + _env = new EnvironmentImpl(); + + } + + public synchronized org.omg.CORBA.Object target() + { + return _target; + } + + public synchronized String operation() + { + return _opName; + } + + public synchronized NVList arguments() + { + return _arguments; + } + + public synchronized NamedValue result() + { + return _result; + } + + public synchronized Environment env() + { + return _env; + } + + public synchronized ExceptionList exceptions() + { + return _exceptions; + } + + public synchronized ContextList contexts() + { + return _ctxList; + } + + public synchronized Context ctx() + { + if (_ctx == null) { + _ctx = new ContextImpl(_orb); + } + return _ctx; + } + + public synchronized void ctx(Context newCtx) + { + _ctx = newCtx; + } + + public synchronized Any add_in_arg() + { + return _arguments.add(org.omg.CORBA.ARG_IN.value).value(); + } + + public synchronized Any add_named_in_arg(String name) + { + return _arguments.add_item(name, org.omg.CORBA.ARG_IN.value).value(); + } + + public synchronized Any add_inout_arg() + { + return _arguments.add(org.omg.CORBA.ARG_INOUT.value).value(); + } + + public synchronized Any add_named_inout_arg(String name) + { + return _arguments.add_item(name, org.omg.CORBA.ARG_INOUT.value).value(); + } + + public synchronized Any add_out_arg() + { + return _arguments.add(org.omg.CORBA.ARG_OUT.value).value(); + } + + public synchronized Any add_named_out_arg(String name) + { + return _arguments.add_item(name, org.omg.CORBA.ARG_OUT.value).value(); + } + + public synchronized void set_return_type(TypeCode tc) + { + if (_result == null) { + _result = new NamedValueImpl(_orb); + } + _result.value().type(tc); + } + + public synchronized Any return_value() + { + if (_result == null) { + _result = new NamedValueImpl(_orb); + } + return _result.value(); + } + + public synchronized void add_exception(TypeCode exceptionType) + { + _exceptions.add(exceptionType); + } + + public synchronized void invoke() + { + doInvocation(); + } + + public synchronized void send_oneway() + { + _isOneWay = true; + doInvocation(); + } + + public synchronized void send_deferred() + { + AsynchInvoke invokeObject = new AsynchInvoke(_orb, this, false); + new Thread(invokeObject).start(); + } + + public synchronized boolean poll_response() + { + // this method has to be synchronized even though it seems + // "readonly" since the thread object doing the asynchronous + // invocation can potentially update this variable in parallel. + // updates are currently simply synchronized againt the request + // object. + return gotResponse; + } + + public synchronized void get_response() + throws org.omg.CORBA.WrongTransaction + { + while (gotResponse == false) { + // release the lock. wait to be notified by the thread that is + // doing the asynchronous invocation. + try { + wait(); + } + catch (InterruptedException e) {} + } + } + + /////////////////////////////////////////////////////////////////////////// + // private helper methods + + /* + * The doInvocation operation is where the real mechanics of + * performing the request invocation is done. + */ + protected void doInvocation() + { + org.omg.CORBA.portable.Delegate delegate = StubAdapter.getDelegate( + _target ) ; + + // Initiate Client Portable Interceptors. Inform the PIHandler that + // this is a DII request so that it knows to ignore the second + // inevitable call to initiateClientPIRequest in createRequest. + // Also, save the RequestImpl object for later use. + _orb.getPIHandler().initiateClientPIRequest( true ); + _orb.getPIHandler().setClientPIInfo( this ); + + InputStream $in = null; + try { + OutputStream $out = delegate.request(null, _opName, !_isOneWay); + // Marshal args + try { + for (int i=0; i<_arguments.count() ; i++) { + NamedValue nv = _arguments.item(i); + switch (nv.flags()) { + case ARG_IN.value: + nv.value().write_value($out); + break; + case ARG_OUT.value: + break; + case ARG_INOUT.value: + nv.value().write_value($out); + break; + default: + } + } + } catch ( org.omg.CORBA.Bounds ex ) { + throw _wrapper.boundsErrorInDiiRequest( ex ) ; + } + + $in = delegate.invoke(null, $out); + } catch (ApplicationException e) { + // REVISIT - minor code. + // This is already handled in subcontract. + // REVISIT - uncomment. + //throw new INTERNAL(); + } catch (RemarshalException e) { + doInvocation(); + } catch( SystemException ex ) { + _env.exception(ex); + // NOTE: The exception should not be thrown. + // However, JDK 1.4 and earlier threw the exception, + // so we keep the behavior to be compatible. + throw ex; + } finally { + delegate.releaseReply(null, $in); + } + } + + // REVISIT - make protected after development - so xgiop can get it. + public synchronized void unmarshalReply(InputStream is) + { + // First unmarshal the return value if it is not void + if ( _result != null ) { + Any returnAny = _result.value(); + TypeCode returnType = returnAny.type(); + if ( returnType.kind().value() != TCKind._tk_void ) + returnAny.read_value(is, returnType); + } + + // Now unmarshal the out/inout args + try { + for ( int i=0; i<_arguments.count() ; i++) { + NamedValue nv = _arguments.item(i); + switch( nv.flags() ) { + case ARG_IN.value: + break; + case ARG_OUT.value: + case ARG_INOUT.value: + Any any = nv.value(); + any.read_value(is, any.type()); + break; + default: + } + } + } catch ( org.omg.CORBA.Bounds ex ) { + // Cannot happen since we only iterate till _arguments.count() + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ServerRequestImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ServerRequestImpl.java new file mode 100644 index 000000000..24a2408b5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/ServerRequestImpl.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import org.omg.CORBA.Any; +import org.omg.CORBA.Context; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.NVList; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.ServerRequest; +import org.omg.CORBA.Bounds; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +public class ServerRequestImpl extends ServerRequest { + private static final ORBUtilSystemException _wrapper = + ORBUtilSystemException.self ; + + /////////////////////////////////////////////////////////////////////////// + // data members + + private ORB _orb = null; + private String _opName = null; + private NVList _arguments = null; + private Context _ctx = null; + private InputStream _ins = null; + + // booleans to check for various operation invocation restrictions + private boolean _paramsCalled = false; + private boolean _resultSet = false; + private boolean _exceptionSet = false; + private Any _resultAny = null; + private Any _exception = null; + + + public ServerRequestImpl (MessageMediator req, ORB orb) { + _opName = req.getOperationName(); + _ins = (InputStream)req.getInputObject(); + _ctx = null; // if we support contexts, this would + // presumably also be available on + // the server invocation + _orb = orb; + } + + @Override + public String operation() { + return _opName; + } + + @Override + public void arguments(NVList args) + { + if (_paramsCalled) + throw _wrapper.argumentsCalledMultiple() ; + + if (_exceptionSet) + throw _wrapper.argumentsCalledAfterException() ; + + if (args == null ) + throw _wrapper.argumentsCalledNullArgs() ; + + _paramsCalled = true; + + NamedValue arg = null; + for (int i=0; i < args.count() ; i++) { + try { + arg = args.item(i); + } catch (Bounds e) { + throw _wrapper.boundsCannotOccur(e) ; + } + + try { + if ((arg.flags() == org.omg.CORBA.ARG_IN.value) || + (arg.flags() == org.omg.CORBA.ARG_INOUT.value)) { + // unmarshal the value into the Any + arg.value().read_value(_ins, arg.value().type()); + } + } catch ( Exception ex ) { + throw _wrapper.badArgumentsNvlist( ex ) ; + } + } + + // hang on to the NVList for marshaling the result + _arguments = args; + + _orb.getPIHandler().setServerPIInfo( _arguments ); + _orb.getPIHandler().invokeServerPIIntermediatePoint(); + } + + @Override + public void set_result(Any res) { + // check for invocation restrictions + if (!_paramsCalled) + throw _wrapper.argumentsNotCalled() ; + if (_resultSet) + throw _wrapper.setResultCalledMultiple() ; + if (_exceptionSet) + throw _wrapper.setResultAfterException() ; + if ( res == null ) + throw _wrapper.setResultCalledNullArgs() ; + + _resultAny = res; + _resultSet = true; + + // Notify portable interceptors of the result so that + // ServerRequestInfo.result() functions as desired. + _orb.getPIHandler().setServerPIInfo( _resultAny ); + + // actual marshaling of the reply msg header and params takes place + // after the DSI returns control to the ORB. + } + + @Override + public void set_exception(Any exc) + { + // except can be called by the DIR at any time (CORBA 2.2 section 6.3). + + if ( exc == null ) + throw _wrapper.setExceptionCalledNullArgs() ; + + // Ensure that the Any contains a SystemException or a + // UserException. If the UserException is not a declared exception, + // the client will get an UNKNOWN exception. + TCKind kind = exc.type().kind(); + if ( kind != TCKind.tk_except ) + throw _wrapper.setExceptionCalledBadType() ; + + _exception = exc; + + // Inform Portable interceptors of the exception that was set + // so sending_exception can return the right value. + _orb.getPIHandler().setServerPIExceptionInfo( _exception ); + + // The user can only call arguments once and not at all after + // set_exception. (internal flags ensure this). However, the user + // can call set_exception multiple times. Therefore, we only + // invoke receive_request the first time set_exception is + // called (if they haven't already called arguments). + if( !_exceptionSet && !_paramsCalled ) { + // We need to invoke intermediate points here. + _orb.getPIHandler().invokeServerPIIntermediatePoint(); + } + + _exceptionSet = true; + + // actual marshaling of the reply msg header and exception takes place + // after the DSI returns control to the ORB. + } + + + /** This is called from the ORB after the DynamicImplementation.invoke + * returns. Here we set the result if result() has not already been called. + * @return the exception if there is one (then ORB will not call + * marshalReplyParams()) otherwise return null. + */ + public Any checkResultCalled() + { + // Two things to be checked (CORBA 2.2 spec, section 6.3): + // 1. Unless it calls set_exception(), the DIR must call arguments() + // exactly once, even if the operation signature contains + // no parameters. + // 2. Unless set_exception() is called, if the invoked operation has a + // non-void result type, set_result() must be called exactly once + // before the DIR returns. + + if ( _paramsCalled && _resultSet ) // normal invocation return + return null; + else if ( _paramsCalled && !_resultSet && !_exceptionSet ) { + try { + // Neither a result nor an exception has been set. + // Assume that the return type is void. If this is not so, + // the client will throw a MARSHAL exception while + // unmarshaling the return value. + TypeCode result_tc = _orb.get_primitive_tc( + org.omg.CORBA.TCKind.tk_void); + _resultAny = _orb.create_any(); + _resultAny.type(result_tc); + _resultSet = true; + + return null; + } catch ( Exception ex ) { + throw _wrapper.dsiResultException( ex ) ; + } + } else if ( _exceptionSet ) + return _exception; + else { + throw _wrapper.dsimethodNotcalled( ) ; + } + } + + /** This is called from the ORB after the DynamicImplementation.invoke + * returns. Here we marshal the return value and inout/out params. + */ + public void marshalReplyParams(OutputStream os) + { + // marshal the operation return value + _resultAny.write_value(os); + + // marshal the inouts/outs + NamedValue arg = null; + + for (int i=0; i < _arguments.count() ; i++) { + try { + arg = _arguments.item(i); + } catch (Bounds e) {} + + if ((arg.flags() == org.omg.CORBA.ARG_OUT.value) || + (arg.flags() == org.omg.CORBA.ARG_INOUT.value)) { + arg.value().write_value(os); + } + } + } + + public Context ctx() + { + if ( !_paramsCalled || _resultSet || _exceptionSet ) + throw _wrapper.contextCalledOutOfOrder() ; + + throw _wrapper.contextNotImplemented() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TCUtility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TCUtility.java new file mode 100644 index 000000000..d96edba0e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TCUtility.java @@ -0,0 +1,293 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import org.omg.CORBA.TCKind; +import org.omg.CORBA.Any; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.Streamable; +import org.omg.CORBA.TypeCodePackage.BadKind; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import java.io.Serializable; +import java.math.BigDecimal; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * Static functions for TypeCode interpretation. + */ +public final class TCUtility { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + @SuppressWarnings({"deprecation"}) + static void marshalIn(org.omg.CORBA.portable.OutputStream s, TypeCode typeCode, long l, Object o) { + switch (typeCode.kind().value()) { + case TCKind._tk_null: + case TCKind._tk_void: + case TCKind._tk_native: + // nothing to write + break; + + case TCKind._tk_short: + s.write_short((short)(l & 0xFFFFL)); + break; + + case TCKind._tk_ushort: + s.write_ushort((short)(l & 0xFFFFL)); + break; + + case TCKind._tk_enum: + case TCKind._tk_long: + s.write_long((int)(l & 0xFFFFFFFFL)); + break; + + case TCKind._tk_ulong: + s.write_ulong((int)(l & 0xFFFFFFFFL)); + break; + + case TCKind._tk_float: + s.write_float(Float.intBitsToFloat((int)(l & 0xFFFFFFFFL))); + break; + + case TCKind._tk_double: + s.write_double(Double.longBitsToDouble(l)); + break; + + case TCKind._tk_boolean: + if ( l == 0 ) + s.write_boolean(false); + else + s.write_boolean(true); + break; + + case TCKind._tk_char: + s.write_char((char)(l & 0xFFFFL)); + break; + + case TCKind._tk_octet: + s.write_octet((byte)(l & 0xFFL)); + break; + + case TCKind._tk_any: + s.write_any((Any)o); + break; + + case TCKind._tk_TypeCode: + s.write_TypeCode((TypeCode)o); + break; + + case TCKind._tk_Principal: + s.write_Principal(org.omg.CORBA.Principal.class.cast(o)); + break; + + case TCKind._tk_objref: + s.write_Object((org.omg.CORBA.Object)o); + break; + + case TCKind._tk_longlong: + s.write_longlong(l); + break; + + case TCKind._tk_ulonglong: + s.write_ulonglong(l); + break; + + case TCKind._tk_wchar: + s.write_wchar((char)(l & 0xFFFFL)); + break; + + case TCKind._tk_string: + s.write_string((String)o); + break; + + case TCKind._tk_wstring: + s.write_wstring((String)o); + break; + + case TCKind._tk_value: + case TCKind._tk_value_box: + ((org.omg.CORBA_2_3.portable.OutputStream)s).write_value((Serializable)o); + break; + + case TCKind._tk_fixed: + // _REVISIT_ As soon as the java-rtf adds digits and scale parameters to + // OutputStream, this check will be unnecessary + if (s instanceof CDROutputObject) { + try { + ((CDROutputObject)s).write_fixed((BigDecimal)o, + typeCode.fixed_digits(), + typeCode.fixed_scale()); + } catch (BadKind badKind) { // impossible + } + } else { + s.write_fixed((BigDecimal)o); + } + break; + + case TCKind._tk_struct: + case TCKind._tk_union: + case TCKind._tk_sequence: + case TCKind._tk_array: + case TCKind._tk_alias: + case TCKind._tk_except: + ((Streamable)o)._write(s); + break; + + case TCKind._tk_abstract_interface: + ((org.omg.CORBA_2_3.portable.OutputStream)s).write_abstract_interface(o); + break; + + case TCKind._tk_longdouble: + // Unspecified for Java + default: + throw wrapper.typecodeNotSupported() ; + } + } + + static void unmarshalIn(org.omg.CORBA.portable.InputStream s, TypeCode typeCode, long[] la, Object[] oa) + { + int type = typeCode.kind().value(); + long l=0; + Object o=oa[0]; + + switch (type) { + case TCKind._tk_null: + case TCKind._tk_void: + case TCKind._tk_native: + // Nothing to read + break; + + case TCKind._tk_short: + l = s.read_short() & 0xFFFFL; + break; + + case TCKind._tk_ushort: + l = s.read_ushort() & 0xFFFFL; + break; + + case TCKind._tk_enum: + case TCKind._tk_long: + l = s.read_long() & 0xFFFFFFFFL; + break; + + case TCKind._tk_ulong: + l = s.read_ulong() & 0xFFFFFFFFL; + break; + + case TCKind._tk_float: + l = Float.floatToIntBits(s.read_float()) & 0xFFFFFFFFL; + break; + + case TCKind._tk_double: + l = Double.doubleToLongBits(s.read_double()); + break; + + case TCKind._tk_char: + l = s.read_char() & 0xFFFFL; + break; + + case TCKind._tk_octet: + l = s.read_octet() & 0xFFL; + break; + + case TCKind._tk_boolean: + if ( s.read_boolean() ) + l = 1; + else + l = 0; + break; + + case TCKind._tk_any: + o = s.read_any(); + break; + + case TCKind._tk_TypeCode: + o = s.read_TypeCode(); + break; + + case TCKind._tk_Principal: + o = s.read_Principal(); + break; + + case TCKind._tk_objref: + if (o instanceof Streamable) + ((Streamable)o)._read(s); + else + o = s.read_Object(); + break; + + case TCKind._tk_longlong: + l = s.read_longlong(); + break; + + case TCKind._tk_ulonglong: + l = s.read_ulonglong(); + break; + + case TCKind._tk_wchar: + l = s.read_wchar() & 0xFFFFL; + break; + + case TCKind._tk_string: + o = s.read_string(); + break; + + case TCKind._tk_wstring: + o = s.read_wstring(); + break; + + case TCKind._tk_value: + case TCKind._tk_value_box: + o = ((org.omg.CORBA_2_3.portable.InputStream)s).read_value (); + break; + + case TCKind._tk_fixed: + try { + // _REVISIT_ As soon as the java-rtf adds digits and scale parameters to + // InputStream, this check will be unnecessary + if (s instanceof CDRInputObject) { + o = ((CDRInputObject)s).read_fixed(typeCode.fixed_digits(), + typeCode.fixed_scale()); + } else { + BigDecimal bigDecimal = s.read_fixed(); + o = bigDecimal.movePointLeft((int)typeCode.fixed_scale()); + } + } catch (BadKind badKind) { // impossible + } + break; + + case TCKind._tk_struct: + case TCKind._tk_union: + case TCKind._tk_sequence: + case TCKind._tk_array: + case TCKind._tk_alias: + case TCKind._tk_except: + ((Streamable)o)._read(s); + break; + + case TCKind._tk_abstract_interface: + o = ((org.omg.CORBA_2_3.portable.InputStream)s).read_abstract_interface(); + break; + + case TCKind._tk_longdouble: + // Unspecified for Java + default: + throw wrapper.typecodeNotSupported() ; + } + + oa[0] = o; + la[0] = l; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TypeCodeFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TypeCodeFactory.java new file mode 100644 index 000000000..474328d54 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TypeCodeFactory.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +public interface TypeCodeFactory { + void setTypeCode(String id, TypeCodeImpl code); + + TypeCodeImpl getTypeCode(String id); + + void setTypeCodeForClass( Class c, TypeCodeImpl tcimpl ) ; + + TypeCodeImpl getTypeCodeForClass( Class c ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TypeCodeImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TypeCodeImpl.java new file mode 100644 index 000000000..7ae5497f0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/corba/TypeCodeImpl.java @@ -0,0 +1,2279 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import java.io.PrintStream; +import java.io.ByteArrayOutputStream; + +import org.omg.CORBA.TypeCode ; +import org.omg.CORBA.StructMember ; +import org.omg.CORBA.UnionMember ; +import org.omg.CORBA.ValueMember ; +import org.omg.CORBA.TCKind ; +import org.omg.CORBA.Any ; +import org.omg.CORBA.TypeCodePackage.BadKind ; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.encoding.TypeCodeInputStream; +import com.sun.corba.ee.impl.encoding.TypeCodeOutputStream; +import com.sun.corba.ee.impl.encoding.TypeCodeReader; +import com.sun.corba.ee.impl.encoding.WrapperInputStream; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import java.io.IOException; +import java.io.ObjectInputStream; + +import com.sun.corba.ee.spi.trace.DynamicType ; +import org.glassfish.pfl.dynamic.copyobject.spi.Copy; +import org.glassfish.pfl.dynamic.copyobject.spi.CopyType; + +// no chance of subclasses, so no problems with runtime helper lookup +@DynamicType +public final class TypeCodeImpl extends TypeCode { + private static final long serialVersionUID = -5320808494290154449L; + + // the indirection TCKind, needed for recursive typecodes. + private static final int tk_indirect = 0xFFFFFFFF; + + // typecode encodings have three different categories that determine + // how the encoding should be done. + + private static final int EMPTY = 0; // no parameters + private static final int SIMPLE = 1; // simple parameters. + private static final int COMPLEX = 2; // complex parameters. need to + // use CDR encapsulation for parameters + + // a table storing the encoding category for the various typecodes. + private static final int typeTable[] = { + EMPTY, // tk_null + EMPTY, // tk_void + EMPTY, // tk_short + EMPTY, // tk_long + EMPTY, // tk_ushort + EMPTY, // tk_ulong + EMPTY, // tk_float + EMPTY, // tk_double + EMPTY, // tk_boolean + EMPTY, // tk_char + EMPTY, // tk_octet + EMPTY, // tk_any + EMPTY, // tk_typecode + EMPTY, // tk_principal + COMPLEX, // tk_objref + COMPLEX, // tk_struct + COMPLEX, // tk_union + COMPLEX, // tk_enum + SIMPLE, // tk_string + COMPLEX, // tk_sequence + COMPLEX, // tk_array + COMPLEX, // tk_alias + COMPLEX, // tk_except + EMPTY, // tk_longlong + EMPTY, // tk_ulonglong + EMPTY, // tk_longdouble + EMPTY, // tk_wchar + SIMPLE, // tk_wstring + SIMPLE, // tk_fixed + COMPLEX, // tk_value + COMPLEX, // tk_value_box + COMPLEX, // tk_native + COMPLEX // tk_abstract_interface + }; + + // Maps TCKind values to names + // This is also used in AnyImpl. + static final String[] kindNames = { + "null", + "void", + "short", + "long", + "ushort", + "ulong", + "float", + "double", + "boolean", + "char", + "octet", + "any", + "typecode", + "principal", + "objref", + "struct", + "union", + "enum", + "string", + "sequence", + "array", + "alias", + "exception", + "longlong", + "ulonglong", + "longdouble", + "wchar", + "wstring", + "fixed", + "value", + "valueBox", + "native", + "abstractInterface" + }; + + private int _kind = 0; // the typecode kind + + // data members for representing the various kinds of typecodes. + private String _id = ""; // the typecode repository id + private String _name = ""; // the typecode name + private int _memberCount = 0; // member count + private String _memberNames[] = null; // names of members + private TypeCodeImpl _memberTypes[] = null; // types of members + private AnyImpl _unionLabels[] = null; // values of union labels + private TypeCodeImpl _discriminator = null; // union discriminator type + private int _defaultIndex = -1; // union default index + private int _length = 0; // string/seq/array length + private TypeCodeImpl _contentType = null; // seq/array/alias type + // fixed + private short _digits = 0; + private short _scale = 0; + // value type + private short _type_modifier = -1; // VM_NONE, VM_CUSTOM, + // VM_ABSTRACT, VM_TRUNCATABLE + private TypeCodeImpl _concrete_base = null; // concrete base type + private short _memberAccess[] = null; // visibility of ValueMember + // recursive sequence support + private TypeCodeImpl _parent = null; // the enclosing type code + private int _parentOffset = 0; // the level of enclosure + // recursive type code support + private TypeCodeImpl _indirectType = null; + + // caches the byte buffer written in write_value for quick remarshaling... + private byte[] outBuffer = null; + // ... but only if caching is enabled + private boolean cachingEnabled = false; + + // the ORB instance: may be instanceof ORBSingleton or ORB + @Copy( CopyType.IDENTITY ) + private transient ORB _orb; + + @Copy( CopyType.IDENTITY ) + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Present only to suppress FindBugs warnings + private void readObject( ObjectInputStream is ) throws IOException, + ClassNotFoundException { + _orb = null ; + } + + /////////////////////////////////////////////////////////////////////////// + // Constructors... + + public TypeCodeImpl(ORB orb) { + // initialized to tk_null + _orb = orb; + } + + public TypeCodeImpl(ORB orb, TypeCode tc) + // to handle conversion of "remote" typecodes into "native" style. + // also see the 'convertToNative(ORB orb, TypeCode tc)' function + { + this(orb) ; + + createFromNonNativeTypeCode( orb, tc ) ; + } + + @DynamicType + private void createFromNonNativeTypeCode( ORB orb, TypeCode tc ) { + // This is a protection against misuse of this constructor. + // Should only be used if tc is not an instance of this class! + // Otherwise we run into problems with recursive/indirect type codes. + // _REVISIT_ We should make this constructor private + if (tc instanceof TypeCodeImpl) { + TypeCodeImpl tci = (TypeCodeImpl)tc; + if (tci._kind == tk_indirect) { + throw wrapper.badRemoteTypecode(); + } + if (tci._kind == TCKind._tk_sequence && tci._contentType == null) { + throw wrapper.badRemoteTypecode(); + } + } + + // set up kind + _kind = tc.kind().value(); + + try { + // set up parameters + switch (_kind) { + case TCKind._tk_value: + _type_modifier = tc.type_modifier(); + // concrete base may be null + TypeCode tccb = tc.concrete_base_type(); + if (tccb != null) { + _concrete_base = convertToNative(_orb, tccb); + } else { + _concrete_base = null; + } + //_memberAccess = tc._memberAccess; + // Need to reconstruct _memberAccess using member_count() and member_visibility() + _memberAccess = new short[tc.member_count()]; + for (int i=0; i < tc.member_count(); i++) { + _memberAccess[i] = tc.member_visibility(i); + } + case TCKind._tk_except: + case TCKind._tk_struct: + case TCKind._tk_union: + // set up member types + _memberTypes = new TypeCodeImpl[tc.member_count()]; + for (int i=0; i < tc.member_count(); i++) { + _memberTypes[i] = convertToNative(_orb, tc.member_type(i)); + _memberTypes[i].setParent(this); + } + case TCKind._tk_enum: + // set up member names + _memberNames = new String[tc.member_count()]; + for (int i=0; i < tc.member_count(); i++) { + _memberNames[i] = tc.member_name(i); + } + // set up member count + _memberCount = tc.member_count(); + case TCKind._tk_objref: + case TCKind._tk_alias: + case TCKind._tk_value_box: + case TCKind._tk_native: + case TCKind._tk_abstract_interface: + setId(tc.id()); + _name = tc.name(); + break; + } + + // set up stuff for unions + switch (_kind) { + case TCKind._tk_union: + _discriminator = convertToNative(_orb, tc.discriminator_type()); + _defaultIndex = tc.default_index(); + _unionLabels = new AnyImpl[_memberCount]; + for (int i=0; i < _memberCount; i++) { + _unionLabels[i] = new AnyImpl(_orb, tc.member_label(i)); + } + break; + } + + // set up length + switch (_kind) { + case TCKind._tk_string: + case TCKind._tk_wstring: + case TCKind._tk_sequence: + case TCKind._tk_array: + _length = tc.length(); + } + + // set up content type + switch (_kind) { + case TCKind._tk_sequence: + case TCKind._tk_array: + case TCKind._tk_alias: + case TCKind._tk_value_box: + _contentType = convertToNative(_orb, tc.content_type()); + } + } catch (org.omg.CORBA.TypeCodePackage.Bounds e) { + wrapper.exceptionOnCreatingTypecode( e ) ; + } catch (BadKind e) { + wrapper.exceptionOnCreatingTypecode( e ) ; + } + // dont have to worry about these since code ensures we dont step + // out of bounds. + } + + public TypeCodeImpl(ORB orb, int creationKind) { + this(orb); + + createPrimitiveTypeCode( orb, creationKind ) ; + } + + @DynamicType + private void createPrimitiveTypeCode( ORB orb, int creationKind ) { + // private API. dont bother checking that + // (creationKind < 0 || creationKind > typeTable.length) + _kind = creationKind; + + // do initialization for special cases + switch (_kind) { + case TCKind._tk_objref: + // this is being used to create typecode for CORBA::Object + setId("IDL:omg.org/CORBA/Object:1.0"); + _name = "Object"; + break; + + case TCKind._tk_string: + case TCKind._tk_wstring: + _length =0; + break; + + case TCKind._tk_value: + _concrete_base = null; + break; + } + } + + public TypeCodeImpl(ORB orb, int creationKind, + String id, String name, StructMember[] members) { + this(orb); + + createStructTypeCode( orb, creationKind, id, name, members ) ; + } + + @DynamicType + private void createStructTypeCode(ORB orb, int creationKind, + String id, String name, StructMember[] members) { + + if ((creationKind == TCKind._tk_struct) || (creationKind == TCKind._tk_except)) { + _kind = creationKind; + setId(id); + _name = name; + _memberCount = members.length; + + _memberNames = new String[_memberCount]; + _memberTypes = new TypeCodeImpl[_memberCount]; + + for (int i = 0 ; i < _memberCount ; i++) { + _memberNames[i] = members[i].name; + _memberTypes[i] = convertToNative(_orb, members[i].type); + _memberTypes[i].setParent(this); + } + } + } + + @DynamicType + private void createUnionTypeCode(ORB orb, int creationKind, String id, String name, + TypeCode discriminator_type, UnionMember[] members) { + + if (creationKind == TCKind._tk_union) { + _kind = creationKind; + setId(id); + _name = name; + _memberCount = members.length; + _discriminator = convertToNative(_orb, discriminator_type); + + _memberNames = new String[_memberCount]; + _memberTypes = new TypeCodeImpl[_memberCount]; + _unionLabels = new AnyImpl[_memberCount]; + + for (int i = 0 ; i < _memberCount ; i++) { + _memberNames[i] = members[i].name; + _memberTypes[i] = convertToNative(_orb, members[i].type); + _memberTypes[i].setParent(this); + _unionLabels[i] = new AnyImpl(_orb, members[i].label); + // check whether this is the default branch. + if (_unionLabels[i].type().kind() == TCKind.tk_octet) { + if (_unionLabels[i].extract_octet() == (byte)0) { + _defaultIndex = i; + } + } + } + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, String id, String name, + TypeCode discriminator_type, UnionMember[] members) { + + this(orb) ; + createUnionTypeCode( orb, creationKind, id, name, discriminator_type, members ) ; + } + + @DynamicType + private void createValueTypeCode(ORB orb, int creationKind, String id, String name, + short type_modifier, TypeCode concrete_base, ValueMember[] members) { + + if (creationKind == TCKind._tk_value) { + _kind = creationKind; + setId(id); + _name = name; + _type_modifier = type_modifier; + if (_concrete_base != null) { + _concrete_base = convertToNative(_orb, concrete_base); + } + _memberCount = members.length; + + _memberNames = new String[_memberCount]; + _memberTypes = new TypeCodeImpl[_memberCount]; + _memberAccess = new short[_memberCount]; + + for (int i = 0 ; i < _memberCount ; i++) { + _memberNames[i] = members[i].name; + _memberTypes[i] = convertToNative(_orb, members[i].type); + _memberTypes[i].setParent(this); + _memberAccess[i] = members[i].access; + } + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, String id, String name, + short type_modifier, TypeCode concrete_base, ValueMember[] members) { + this(orb) ; + + createValueTypeCode( orb, creationKind, id, name, type_modifier, concrete_base, members ) ; + } + + @DynamicType + private void createEnumTypeCode(ORB orb, int creationKind, String id, String name, + String[] members) { + + if (creationKind == TCKind._tk_enum) { + _kind = creationKind; + setId(id); + _name = name; + _memberCount = members.length; + + _memberNames = new String[_memberCount]; + + for (int i = 0 ; i < _memberCount ; i++) { + _memberNames[i] = members[i]; + } + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, String id, String name, String[] members) { + this(orb) ; + + createEnumTypeCode( orb, creationKind, id, name, members ) ; + } + + @DynamicType + private void createAliasTypeCode(ORB orb, int creationKind, String id, String name, + TypeCode original_type) { + + if (creationKind == TCKind._tk_alias + || creationKind == TCKind._tk_value_box) { + + _kind = creationKind; + setId(id); + _name = name; + _contentType = convertToNative(_orb, original_type); + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, String id, String name, TypeCode original_type) { + this(orb) ; + createAliasTypeCode( orb, creationKind, id, name, original_type ) ; + } + + @DynamicType + private void createObjrefTypeCode(ORB orb, int creationKind, String id, String name) { + if (creationKind == TCKind._tk_objref || + creationKind == TCKind._tk_native || + creationKind == TCKind._tk_abstract_interface) { + + _kind = creationKind; + setId(id); + _name = name; + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, String id, String name) { + this(orb) ; + createObjrefTypeCode( orb, creationKind, id, name ) ; + } + + + @DynamicType + private void createStringTypeCode(ORB orb, int creationKind, int bound) { + if (bound < 0) { + throw wrapper.negativeBounds(); + } + + if ((creationKind == TCKind._tk_string) || (creationKind == TCKind._tk_wstring)) { + _kind = creationKind; + _length = bound; + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, int bound) { + this(orb) ; + createStringTypeCode( orb, creationKind, bound ) ; + } + + @DynamicType + private void createArrayTypeCode(ORB orb, int creationKind, int bound, TypeCode element_type) { + if ( creationKind == TCKind._tk_sequence || creationKind == TCKind._tk_array ) { + _kind = creationKind; + _length = bound; + _contentType = convertToNative(_orb, element_type); + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, int bound, TypeCode element_type) { + this(orb) ; + createArrayTypeCode( orb, creationKind, bound, element_type ) ; + } + + @DynamicType + private void createRecursiveSequenceTypeCode(ORB orb, int creationKind, int bound, int offset) { + if (creationKind == TCKind._tk_sequence) { + _kind = creationKind; + _length = bound; + _parentOffset = offset; + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, int bound, int offset) { + this(orb) ; + + createRecursiveSequenceTypeCode( orb, creationKind, bound, offset ) ; + } + + + @DynamicType + private void createRecursiveTypeCode(ORB orb, String id) { + _kind = tk_indirect; + // This is the type code of the type we stand in for, not our own. + _id = id; + // Try to resolve it now. May return null in which case + // we try again later (see indirectType()). + tryIndirectType(); + } + + public TypeCodeImpl(ORB orb, String id) { + this(orb) ; + + createRecursiveTypeCode( orb, id ) ; + } + + @DynamicType + private void createFixedTypeCode(ORB orb, int creationKind, short digits, short scale) { + if (creationKind == TCKind._tk_fixed) { + _kind = creationKind; + _digits = digits; + _scale = scale; + } // else initializes to null + } + + public TypeCodeImpl(ORB orb, int creationKind, short digits, short scale) { + this(orb) ; + + createFixedTypeCode( orb, creationKind, digits, scale ) ; + } + + /////////////////////////////////////////////////////////////////////////// + // Other creation functions... + + // Optimization: + // If we checked for and returned constant primitive typecodes + // here we could reduce object creation and also enable more + // efficient typecode comparisons for primitive typecodes. + // + protected static TypeCodeImpl convertToNative(ORB orb, + TypeCode tc) + { + if (tc instanceof TypeCodeImpl) { + return (TypeCodeImpl) tc; + } else { + return new TypeCodeImpl(orb, tc); + } + } + + public static CDROutputObject newOutputStream(ORB orb) { + TypeCodeOutputStream tcos = OutputStreamFactory.newTypeCodeOutputStream(orb); + //if (debug) System.out.println("Created TypeCodeOutputStream " + tcos + + // " with no parent"); + return tcos; + } + + // Support for indirect/recursive type codes + + private TypeCodeImpl indirectType() { + _indirectType = tryIndirectType(); + if (_indirectType == null) { + // Nothing we can do about that. + throw wrapper.unresolvedRecursiveTypecode() ; + } + return _indirectType; + } + + private TypeCodeImpl tryIndirectType() { + // Assert that _kind == tk_indirect + if (_indirectType != null) { + return _indirectType; + } + + setIndirectType(_orb.getTypeCode(_id)); + + return _indirectType; + } + + private void setIndirectType(TypeCodeImpl newType) { + _indirectType = newType; + if (_indirectType != null) { + try { + _id = _indirectType.id(); + } catch (BadKind e) { + // can't happen + throw wrapper.badkindCannotOccur() ; + } + } + } + + private void setId(String newID) { + _id = newID; + _orb.setTypeCode(_id, this); + } + + private void setParent(TypeCodeImpl parent) { + _parent = parent; + } + + private TypeCodeImpl getParentAtLevel(int level) { + if (level == 0) { + return this; + } + + if (_parent == null) { + throw wrapper.unresolvedRecursiveTypecode(); + } + + return _parent.getParentAtLevel(level - 1); + } + + private TypeCodeImpl lazy_content_type() { + if (_contentType == null) { + if (_kind == TCKind._tk_sequence && _parentOffset > 0 && _parent != null) { + // This is an unresolved recursive sequence tc. + // Try to resolve it now if the hierarchy is complete. + TypeCodeImpl realParent = getParentAtLevel(_parentOffset); + if (realParent != null && realParent._id != null) { + // Create a recursive type code object as the content type. + // This is when the recursive sequence typecode morphes + // into a sequence typecode containing a recursive typecode. + _contentType = new TypeCodeImpl(_orb, realParent._id); + } + } + } + return _contentType; + } + + // Other private functions + + private TypeCode realType(TypeCode aType) { + TypeCode realType = aType; + try { + // Note: Indirect types are handled in kind() method + while (realType.kind().value() == TCKind._tk_alias) { + realType = realType.content_type(); + } + } catch (BadKind bad) { + // impossible + throw wrapper.badkindCannotOccur() ; + } + return realType; + } + + /////////////////////////////////////////////////////////////////////////// + // TypeCode operations + + @DynamicType + public final boolean equal(TypeCode tc) { + if (tc == this) { + return true; + } + + try { + + if (_kind == tk_indirect) { + //return indirectType().equal(tc); + if (_id != null && tc.id() != null) { + return _id.equals(tc.id()); + } + return (_id == null && tc.id() == null); + } + + // make sure kinds are identical. + if (_kind != tc.kind().value()) { + return false; + } + + switch (typeTable[_kind]) { + case EMPTY: + // no parameters to check. + return true; + + case SIMPLE: + switch (_kind) { + case TCKind._tk_string: + case TCKind._tk_wstring: + // check for bound. + return (_length == tc.length()); + + case TCKind._tk_fixed: + return (_digits == tc.fixed_digits() && _scale == tc.fixed_scale()); + default: + return false; + } + + case COMPLEX: + + switch(_kind) { + + case TCKind._tk_objref: + { + // check for logical id. + if (_id.compareTo(tc.id()) == 0) { + return true; + } + + if (_id.compareTo( + (_orb.get_primitive_tc(_kind)).id()) == 0) + { + return true; + } + + if (tc.id().compareTo( + (_orb.get_primitive_tc(_kind)).id()) == 0) + { + return true; + } + + return false; + } + + case TCKind._tk_native: + case TCKind._tk_abstract_interface: + { + // check for logical id. + if (_id.compareTo(tc.id()) != 0) { + return false; + + } + // ignore name since its optional. + return true; + } + + case TCKind._tk_struct: + case TCKind._tk_except: + { + // check for member count + if (_memberCount != tc.member_count()) { + return false; + } + // check for repository id + if (_id.compareTo(tc.id()) != 0) { + return false; + } + // check for member types. + for (int i = 0 ; i < _memberCount ; i++) { + if (!_memberTypes[i].equal(tc.member_type(i))) { + return false; + } + } + // ignore id and names since those are optional. + return true; + } + + case TCKind._tk_union: + { + // check for member count + if (_memberCount != tc.member_count()) { + return false; + } + // check for repository id + if (_id.compareTo(tc.id()) != 0) { + return false; + } + // check for default index + if (_defaultIndex != tc.default_index()) { + return false; + } + // check for discriminator type + if (!_discriminator.equal(tc.discriminator_type())) { + return false; + } + // check for label types and values + for (int i = 0 ; i < _memberCount ; i++) { + if (!_unionLabels[i].equal(tc.member_label(i))) { + return false; + } + } + // check for branch types + for (int i = 0 ; i < _memberCount ; i++) { + if (!_memberTypes[i].equal(tc.member_type(i))) { + return false; + } + } + // ignore id and names since those are optional. + return true; + } + + case TCKind._tk_enum: + { + // check for repository id + if (_id.compareTo(tc.id()) != 0) { + return false; + } + // check member count + if (_memberCount != tc.member_count()) { + return false; + } + // ignore names since those are optional. + return true; + } + + case TCKind._tk_sequence: + case TCKind._tk_array: + { + // check bound/length + if (_length != tc.length()) { + return false; + } + // check content type + if (! lazy_content_type().equal(tc.content_type())) { + return false; + } + // ignore id and name since those are optional. + return true; + } + + case TCKind._tk_value: + { + // check for member count + if (_memberCount != tc.member_count()) { + return false; + } + + // check for repository id + if (_id.compareTo(tc.id()) != 0) { + return false; + } + + // check for member types. + for (int i = 0 ; i < _memberCount ; i++) { + if (_memberAccess[i] != tc.member_visibility(i) || !_memberTypes[i].equal(tc.member_type(i))) { + return false; + } + } + if (_type_modifier == tc.type_modifier()) { + return false; + } + + // concrete_base may be null + TypeCode tccb = tc.concrete_base_type(); + + if (_concrete_base == null) { + return tccb == null ; + } + + if (tccb == null) { + return false ; + } + + // ignore id and names since those are optional. + return _concrete_base.equal(tccb) ; + } + + case TCKind._tk_alias: + case TCKind._tk_value_box: + { + // check for repository id + if (_id.compareTo(tc.id()) != 0) { + return false; + } + // check for equality with the true type + return _contentType.equal(tc.content_type()); + } + } + } + } catch (org.omg.CORBA.TypeCodePackage.Bounds e) { + wrapper.exceptionInTypecodeEquals( e ) ; + } catch (BadKind e) { + wrapper.exceptionInTypecodeEquals( e ) ; + } + + return false; + } + + /** + * The equivalent operation is used by the ORB when determining type equivalence + * for values stored in an IDL any. + */ + @DynamicType + public boolean equivalent(TypeCode tc) { + if (tc == this) { + return true; + } + + // If the result of the kind operation on either TypeCode is tk_alias, recursively + // replace the TypeCode with the result of calling content_type, until the kind + // is no longer tk_alias. + // Note: Always resolve indirect types first! + TypeCode myRealType = (_kind == tk_indirect ? indirectType() : this); + myRealType = realType(myRealType); + TypeCode otherRealType = realType(tc); + + // If results of the kind operation on each typecode differ, + // equivalent returns false. + if (myRealType.kind().value() != otherRealType.kind().value()) { + return false; + } + + String myID = null; + String otherID = null; + try { + myID = this.id(); + otherID = tc.id(); + // At this point the id operation is valid for both TypeCodes. + + // Return true if the results of id for both TypeCodes are non-empty strings + // and both strings are equal. + // If both ids are non-empty but are not equal, then equivalent returns FALSE. + if (myID != null && otherID != null) { + return (myID.equals(otherID)); + } + } catch (BadKind e) { + // id operation is not valid for either or both TypeCodes + } + + // If either or both id is an empty string, or the TypeCode kind does not support + // the id operation, perform a structural comparison of the TypeCodes. + + int myKind = myRealType.kind().value(); + try { + if (myKind == TCKind._tk_struct || + myKind == TCKind._tk_union || + myKind == TCKind._tk_enum || + myKind == TCKind._tk_except || + myKind == TCKind._tk_value) + { + if (myRealType.member_count() != otherRealType.member_count()) { + return false; + } + } + if (myKind == TCKind._tk_union) + { + if (myRealType.default_index() != otherRealType.default_index()) { + return false; + } + } + if (myKind == TCKind._tk_string || + myKind == TCKind._tk_wstring || + myKind == TCKind._tk_sequence || + myKind == TCKind._tk_array) + { + if (myRealType.length() != otherRealType.length()) { + return false; + } + } + if (myKind == TCKind._tk_fixed) + { + if (myRealType.fixed_digits() != otherRealType.fixed_digits() || + myRealType.fixed_scale() != otherRealType.fixed_scale()) { + return false; + } + } + if (myKind == TCKind._tk_union) + { + for (int i=0; i typeTable.length) && _kind != tk_indirect) { + throw wrapper.cannotMarshalBadTckind() ; + } + + // Don't do any work if this is native + if (_kind == TCKind._tk_native) { + throw wrapper.cannotMarshalNative(); + } + + // We have to remember the stream and position for EVERY type code + // in case some recursive or indirect type code references it. + TypeCodeReader topStream = tcis.getTopLevelStream(); + + if (_kind == tk_indirect) { + int streamOffset = tcis.read_long(); + if (streamOffset > -4) { + throw wrapper.invalidIndirection(streamOffset); + } + + // The encoding used for indirection is the same as that used for recursive , + // TypeCodes i.e., a 0xffffffff indirection marker followed by a long offset + // (in units of octets) from the beginning of the long offset. + int topPos = tcis.getTopLevelPosition(); + // substract 4 to get back to the beginning of the long offset. + int indirectTypePosition = topPos - 4 + streamOffset; + + // Now we have to find the referenced type + // by its indirectTypePosition within topStream. + //if (debug) System.out.println( + // "TypeCodeImpl looking up indirection at position topPos " + + //topPos + " - 4 + offset " + streamOffset + " = " + indirectTypePosition); + TypeCodeImpl type = topStream.getTypeCodeAtPosition(indirectTypePosition); + if (type == null) { + throw wrapper.indirectionNotFound(indirectTypePosition); + } + setIndirectType(type); + return false; + } + + topStream.addTypeCodeAtPosition(this, myPosition); + return true; + } + + void read_value_kind(InputStream is) { + // unmarshal the kind + _kind = is.read_long(); + + // check validity of kind + if ((_kind < 0 || _kind > typeTable.length) && _kind != tk_indirect) { + throw wrapper.cannotMarshalBadTckind() ; + } + + // Don't do any work if this is native + if (_kind == TCKind._tk_native) { + throw wrapper.cannotMarshalNative(); + } + + if (_kind == tk_indirect) { + throw wrapper.recursiveTypecodeError() ; + } + } + + @DynamicType + private void readValueBodySimple( InputStream is ) { + switch (_kind) { + case TCKind._tk_string: + case TCKind._tk_wstring: + _length = is.read_long(); + break; + case TCKind._tk_fixed: + _digits = is.read_ushort(); + _scale = is.read_short(); + break; + default: + throw wrapper.invalidSimpleTypecode() ; + } + } + + @DynamicType + private void readValueBodyComplexObjref( TypeCodeInputStream _encap ) { + // get the repository id + setId(_encap.read_string()); + // get the name + _name = _encap.read_string(); + } + + @DynamicType + private void readValueBodyComplexUnion( InputStream is, + TypeCodeInputStream _encap ) { + + setId(_encap.read_string()); + _name = _encap.read_string(); + _discriminator = new TypeCodeImpl((ORB)is.orb()); + _discriminator.read_value_recursive(_encap); + _defaultIndex = _encap.read_long(); + _memberCount = _encap.read_long(); + _unionLabels = new AnyImpl[_memberCount]; + _memberNames = new String[_memberCount]; + _memberTypes = new TypeCodeImpl[_memberCount]; + + for (int i=0; i < _memberCount; i++) { + _unionLabels[i] = new AnyImpl((ORB)is.orb()); + if (i == _defaultIndex) { + _unionLabels[i].insert_octet(_encap.read_octet()); + } else { + switch (realType(_discriminator).kind().value()) { + case TCKind._tk_short: + _unionLabels[i].insert_short(_encap.read_short()); + break; + case TCKind._tk_long: + _unionLabels[i].insert_long(_encap.read_long()); + break; + case TCKind._tk_ushort: + _unionLabels[i].insert_ushort(_encap.read_short()); + break; + case TCKind._tk_ulong: + _unionLabels[i].insert_ulong(_encap.read_long()); + break; + case TCKind._tk_float: + _unionLabels[i].insert_float(_encap.read_float()); + break; + case TCKind._tk_double: + _unionLabels[i].insert_double(_encap.read_double()); + break; + case TCKind._tk_boolean: + _unionLabels[i].insert_boolean(_encap.read_boolean()); + break; + case TCKind._tk_char: + _unionLabels[i].insert_char(_encap.read_char()); + break; + case TCKind._tk_enum: + _unionLabels[i].type(_discriminator); + _unionLabels[i].insert_long(_encap.read_long()); + break; + case TCKind._tk_longlong: + _unionLabels[i].insert_longlong(_encap.read_longlong()); + break; + case TCKind._tk_ulonglong: + _unionLabels[i].insert_ulonglong(_encap.read_longlong()); + break; + // _REVISIT_ figure out long double mapping + // case TCKind.tk_longdouble: + // _unionLabels[i].insert_longdouble(_encap.getDouble()); + // break; + case TCKind._tk_wchar: + _unionLabels[i].insert_wchar(_encap.read_wchar()); + break; + default: + throw wrapper.invalidComplexTypecode() ; + } + } + _memberNames[i] = _encap.read_string(); + _memberTypes[i] = new TypeCodeImpl((ORB)is.orb()); + _memberTypes[i].read_value_recursive(_encap); + _memberTypes[i].setParent(this); + } + } + + @DynamicType + private void readValueBodyComplexEnum( TypeCodeInputStream _encap ) { + setId(_encap.read_string()); + _name = _encap.read_string(); + _memberCount = _encap.read_long(); + _memberNames = new String[_memberCount]; + + for (int i=0; i < _memberCount; i++) { + _memberNames[i] = _encap.read_string(); + } + } + + @DynamicType + private void readValueBodyComplexSequence( InputStream is, + TypeCodeInputStream _encap ) { + + _contentType = new TypeCodeImpl((ORB)is.orb()); + _contentType.read_value_recursive(_encap); + _length = _encap.read_long(); + } + + @DynamicType + private void readValueBodyComplexArray( InputStream is, + TypeCodeInputStream _encap ) { + _contentType = new TypeCodeImpl((ORB)is.orb()); + _contentType.read_value_recursive(_encap); + _length = _encap.read_long(); + } + + @DynamicType + private void readValueBodyComplexAlias( InputStream is, + TypeCodeInputStream _encap ) { + setId(_encap.read_string()); + _name = _encap.read_string(); + _contentType = new TypeCodeImpl((ORB)is.orb()); + _contentType.read_value_recursive(_encap); + } + + @DynamicType + private void readValueBodyComplexStruct( InputStream is, + TypeCodeInputStream _encap ) { + + setId(_encap.read_string()); + _name = _encap.read_string(); + _memberCount = _encap.read_long(); + _memberNames = new String[_memberCount]; + _memberTypes = new TypeCodeImpl[_memberCount]; + + for (int i=0; i < _memberCount; i++) { + _memberNames[i] = _encap.read_string(); + _memberTypes[i] = new TypeCodeImpl((ORB)is.orb()); + _memberTypes[i].read_value_recursive(_encap); + _memberTypes[i].setParent(this); + } + } + + @DynamicType + private void readValueBodyComplexValue( InputStream is, + TypeCodeInputStream _encap ) { + + setId(_encap.read_string()); + _name = _encap.read_string(); + _type_modifier = _encap.read_short(); + _concrete_base = new TypeCodeImpl((ORB)is.orb()); + _concrete_base.read_value_recursive(_encap); + if (_concrete_base.kind().value() == TCKind._tk_null) { + _concrete_base = null; + } + + _memberCount = _encap.read_long(); + _memberNames = new String[_memberCount]; + _memberTypes = new TypeCodeImpl[_memberCount]; + _memberAccess = new short[_memberCount]; + + for (int i=0; i < _memberCount; i++) { + _memberNames[i] = _encap.read_string(); + _memberTypes[i] = new TypeCodeImpl((ORB)is.orb()); + _memberTypes[i].read_value_recursive(_encap); + _memberTypes[i].setParent(this); + _memberAccess[i] = _encap.read_short(); + } + } + + @DynamicType + void read_value_body(InputStream is) { + switch (typeTable[_kind]) { + case EMPTY: + break; + + case SIMPLE: + readValueBodySimple( is ) ; + break ; + + case COMPLEX: + TypeCodeInputStream _encap ; + _encap = TypeCodeInputStream.readEncapsulation(is, + is.orb()); + + switch(_kind) { + case TCKind._tk_objref: + case TCKind._tk_abstract_interface: + readValueBodyComplexObjref( _encap ) ; + break; + + case TCKind._tk_union: + readValueBodyComplexUnion( is, _encap ) ; + break; + + case TCKind._tk_enum: + readValueBodyComplexEnum( _encap ) ; + break; + + case TCKind._tk_sequence: + readValueBodyComplexSequence( is, _encap ) ; + break; + + case TCKind._tk_array: + readValueBodyComplexArray( is, _encap ) ; + break; + + case TCKind._tk_alias: + case TCKind._tk_value_box: + readValueBodyComplexAlias( is, _encap ) ; + break; + + case TCKind._tk_except: + case TCKind._tk_struct: + readValueBodyComplexStruct( is, _encap ) ; + break; + + case TCKind._tk_value: + readValueBodyComplexValue( is, _encap ) ; + break; + + default: + throw wrapper.invalidTypecodeKindMarshal() ; + } + break; + } + } + + @DynamicType + public void write_value(OutputStream os) { + if (os instanceof TypeCodeOutputStream) { + this.write_value((TypeCodeOutputStream)os); + } else { + if (outBuffer == null) { + TypeCodeOutputStream wrapperOutStream = TypeCodeOutputStream.wrapOutputStream(os); + this.write_value(wrapperOutStream); + outBuffer = wrapperOutStream.getTypeCodeBuffer(); + } + os.write_long(_kind); + os.write_octet_array(outBuffer, 0, outBuffer.length); + } + } + + @DynamicType + public void write_value(TypeCodeOutputStream tcos) { + // Don't do any work if this is native + if (_kind == TCKind._tk_native) { + throw wrapper.cannotMarshalNative(); + } + + TypeCodeOutputStream topStream = tcos.getTopLevelStream(); + + if (_kind == tk_indirect) { + // The encoding used for indirection is the same as that used for recursive , + // TypeCodes i.e., a 0xffffffff indirection marker followed by a long offset + // (in units of octets) from the beginning of the long offset. + int pos = topStream.getPositionForID(_id); + int topPos = tcos.getTopLevelPosition(); + tcos.writeIndirection(tk_indirect, pos); + return; + } + + tcos.write_long(_kind); + + // Bug fix 5034649: + // Do this AFTER the write of the _kind in case the alignment + // for the long changes the position. + topStream.addIDAtPosition(_id, tcos.getTopLevelPosition()-4); + + switch (typeTable[_kind]) { + case EMPTY: + // nothing more to marshal + break; + + case SIMPLE: + switch (_kind) { + case TCKind._tk_string: + case TCKind._tk_wstring: + // marshal the bound on string length + tcos.write_long(_length); + break; + + case TCKind._tk_fixed: + tcos.write_ushort(_digits); + tcos.write_short(_scale); + break; + + default: + // unknown typecode kind + throw wrapper.invalidSimpleTypecode() ; + } + break; + + case COMPLEX: + TypeCodeOutputStream _encap = tcos.createEncapsulation(tcos.orb()); + + switch(_kind) { + case TCKind._tk_objref: + case TCKind._tk_abstract_interface: + _encap.write_string(_id); + _encap.write_string(_name); + break; + + case TCKind._tk_union: + _encap.write_string(_id); + _encap.write_string(_name); + _discriminator.write_value(_encap); + _encap.write_long(_defaultIndex); + _encap.write_long(_memberCount); + + for (int i=0; i < _memberCount; i++) { + if (i == _defaultIndex) { + _encap.write_octet(_unionLabels[i].extract_octet()); + } else { + switch (realType(_discriminator).kind().value()) { + case TCKind._tk_short: + _encap.write_short(_unionLabels[i].extract_short()); + break; + case TCKind._tk_long: + _encap.write_long(_unionLabels[i].extract_long()); + break; + case TCKind._tk_ushort: + _encap.write_short(_unionLabels[i].extract_ushort()); + break; + case TCKind._tk_ulong: + _encap.write_long(_unionLabels[i].extract_ulong()); + break; + case TCKind._tk_float: + _encap.write_float(_unionLabels[i].extract_float()); + break; + case TCKind._tk_double: + _encap.write_double(_unionLabels[i].extract_double()); + break; + case TCKind._tk_boolean: + _encap.write_boolean(_unionLabels[i].extract_boolean()); + break; + case TCKind._tk_char: + _encap.write_char(_unionLabels[i].extract_char()); + break; + case TCKind._tk_enum: + _encap.write_long(_unionLabels[i].extract_long()); + break; + case TCKind._tk_longlong: + _encap.write_longlong(_unionLabels[i].extract_longlong()); + break; + case TCKind._tk_ulonglong: + _encap.write_longlong(_unionLabels[i].extract_ulonglong()); + break; + case TCKind._tk_wchar: + _encap.write_wchar(_unionLabels[i].extract_wchar()); + break; + default: + throw wrapper.invalidComplexTypecode() ; + } + } + _encap.write_string(_memberNames[i]); + _memberTypes[i].write_value(_encap); + } + break; + + case TCKind._tk_enum: + _encap.write_string(_id); + _encap.write_string(_name); + _encap.write_long(_memberCount); + + for (int i=0; i < _memberCount; i++) { + _encap.write_string(_memberNames[i]); + } + break; + + case TCKind._tk_sequence: + lazy_content_type().write_value(_encap); + _encap.write_long(_length); + break; + + case TCKind._tk_array: + _contentType.write_value(_encap); + _encap.write_long(_length); + break; + + case TCKind._tk_alias: + case TCKind._tk_value_box: + _encap.write_string(_id); + _encap.write_string(_name); + _contentType.write_value(_encap); + break; + + case TCKind._tk_struct: + case TCKind._tk_except: + _encap.write_string(_id); + _encap.write_string(_name); + _encap.write_long(_memberCount); + + for (int i=0; i < _memberCount; i++) { + _encap.write_string(_memberNames[i]); + _memberTypes[i].write_value(_encap); + } + break; + + case TCKind._tk_value: + _encap.write_string(_id); + _encap.write_string(_name); + _encap.write_short(_type_modifier); + + if (_concrete_base == null) { + _orb.get_primitive_tc(TCKind._tk_null).write_value(_encap); + } else { + _concrete_base.write_value(_encap); + } + + _encap.write_long(_memberCount); + + for (int i=0; i < _memberCount; i++) { + _encap.write_string(_memberNames[i]); + _memberTypes[i].write_value(_encap); + _encap.write_short(_memberAccess[i]); + } + break; + + default: + throw wrapper.invalidTypecodeKindMarshal() ; + } + + // marshal the encapsulation + _encap.writeOctetSequenceTo(tcos); + break; + } + } + + /** + * This is not a copy of the TypeCodeImpl objects, but instead it + * copies the value this type code is representing. + * See AnyImpl read_value and write_value for usage. + * The state of this TypeCodeImpl instance isn't changed, only used + * by the Any to do the correct copy. + * @param src InputStream to copy. + * @param dst target for copy. + */ + @DynamicType + protected void copy(org.omg.CORBA.portable.InputStream src, + org.omg.CORBA.portable.OutputStream dst) { + switch (_kind) { + + case TCKind._tk_null: + case TCKind._tk_void: + case TCKind._tk_native: + case TCKind._tk_abstract_interface: + break; + + case TCKind._tk_short: + case TCKind._tk_ushort: + dst.write_short(src.read_short()); + break; + + case TCKind._tk_long: + case TCKind._tk_ulong: + dst.write_long(src.read_long()); + break; + + case TCKind._tk_float: + dst.write_float(src.read_float()); + break; + + case TCKind._tk_double: + dst.write_double(src.read_double()); + break; + + case TCKind._tk_longlong: + case TCKind._tk_ulonglong: + dst.write_longlong(src.read_longlong()); + break; + + case TCKind._tk_longdouble: + throw wrapper.tkLongDoubleNotSupported() ; + + case TCKind._tk_boolean: + dst.write_boolean(src.read_boolean()); + break; + + case TCKind._tk_char: + dst.write_char(src.read_char()); + break; + + case TCKind._tk_wchar: + dst.write_wchar(src.read_wchar()); + break; + + case TCKind._tk_octet: + dst.write_octet(src.read_octet()); + break; + + case TCKind._tk_string: { + String s; + s = src.read_string(); + // make sure length bound in typecode is not violated + if ((_length != 0) && (s.length() > _length)) { + throw wrapper.badStringBounds(s.length(), _length); + } + dst.write_string(s); + break; + } + + case TCKind._tk_wstring: { + String s; + s = src.read_wstring(); + // make sure length bound in typecode is not violated + if ((_length != 0) && (s.length() > _length)) { + throw wrapper.badStringBounds(s.length(), _length); + } + dst.write_wstring(s); + break; + } + + case TCKind._tk_fixed: + dst.write_ushort(src.read_ushort()); + dst.write_short(src.read_short()); + break; + + case TCKind._tk_any: + Any tmp = ((CDRInputObject)src).orb().create_any(); + TypeCodeImpl t = new TypeCodeImpl((ORB)dst.orb()); + t.read_value((org.omg.CORBA_2_3.portable.InputStream)src); + t.write_value((org.omg.CORBA_2_3.portable.OutputStream)dst); + tmp.read_value(src, t); + tmp.write_value(dst); + break; + + case TCKind._tk_TypeCode: + dst.write_TypeCode(src.read_TypeCode()); + break; + + case TCKind._tk_Principal: + dst.write_Principal(src.read_Principal()); + break; + + case TCKind._tk_objref: + dst.write_Object(src.read_Object()); + break; + + case TCKind._tk_except: + // Copy repositoryId + dst.write_string(src.read_string()); + + // Fall into ... + // _REVISIT_ what about the inherited members of this values concrete base type? + case TCKind._tk_value: + case TCKind._tk_struct: + // copy each element, using the corresponding member type + for (int i=0; i < _memberTypes.length; i++) { + _memberTypes[i].copy(src, dst); + } + break; + + case TCKind._tk_union: + Any tagValue = new AnyImpl( (ORB)src.orb()); + + switch (realType(_discriminator).kind().value()) { + case TCKind._tk_short: { + short value = src.read_short(); + tagValue.insert_short(value); + dst.write_short(value); + break; + } + + case TCKind._tk_long: { + int value = src.read_long(); + tagValue.insert_long(value); + dst.write_long(value); + break; + } + + case TCKind._tk_ushort: { + short value = src.read_short(); + tagValue.insert_ushort(value); + dst.write_short(value); + break; + } + + case TCKind._tk_ulong: { + int value = src.read_long(); + tagValue.insert_ulong(value); + dst.write_long(value); + break; + } + + case TCKind._tk_float: { + float value = src.read_float(); + tagValue.insert_float(value); + dst.write_float(value); + break; + } + + case TCKind._tk_double: { + double value = src.read_double(); + tagValue.insert_double(value); + dst.write_double(value); + break; + } + + case TCKind._tk_boolean: { + boolean value = src.read_boolean(); + tagValue.insert_boolean(value); + dst.write_boolean(value); + break; + } + + case TCKind._tk_char: { + char value = src.read_char(); + tagValue.insert_char(value); + dst.write_char(value); + break; + } + + case TCKind._tk_enum: { + int value = src.read_long(); + tagValue.type(_discriminator); + tagValue.insert_long(value); + dst.write_long(value); + break; + } + + case TCKind._tk_longlong: { + long value = src.read_longlong(); + tagValue.insert_longlong(value); + dst.write_longlong(value); + break; + } + + case TCKind._tk_ulonglong: { + long value = src.read_longlong(); + tagValue.insert_ulonglong(value); + dst.write_longlong(value); + break ; + } + + case TCKind._tk_wchar: { + char value = src.read_wchar(); + tagValue.insert_wchar(value); + dst.write_wchar(value); + break; + } + + default: + throw wrapper.illegalUnionDiscriminatorType() ; + } + + // using the value of the tag, find out the type of the value + // following. + + int labelIndex; + for (labelIndex = 0; labelIndex < _unionLabels.length; labelIndex++) { + // use equality over anys + if (tagValue.equal(_unionLabels[labelIndex])) { + _memberTypes[labelIndex].copy(src, dst); + break; + } + } + + if (labelIndex == _unionLabels.length) { + // check if label has not been found + if (_defaultIndex == -1) { + throw wrapper.unexpectedUnionDefault(); + } else { + _memberTypes[_defaultIndex].copy(src, dst); + } + } + break; + + case TCKind._tk_enum: + dst.write_long(src.read_long()); + break; + + case TCKind._tk_sequence: + int seqLength = src.read_long(); + + if ((_length != 0) && (seqLength > _length)) { + throw wrapper.badSequenceBounds(seqLength, _length); + } + + dst.write_long(seqLength); + + lazy_content_type(); // make sure it's resolved + for (int i=0; i < seqLength; i++) { + _contentType.copy(src, dst); + } + break; + + case TCKind._tk_array: + for (int i=0; i < _length; i++) { + _contentType.copy(src, dst); + } + break; + + case TCKind._tk_alias: + case TCKind._tk_value_box: + _contentType.copy(src, dst); + break; + + case tk_indirect: + // need to follow offset, get unmarshal typecode from that + // offset, and use that to do the copy + // Don't need to read type code before using it to do the copy. + // It should be fully usable. + indirectType().copy(src, dst); + break; + + default: + throw wrapper.invalidTypecodeKindMarshal() ; + } + } + + + static protected short digits(java.math.BigDecimal value) { + if (value == null) { + return 0; + } + short length = (short)value.unscaledValue().toString().length(); + if (value.signum() == -1) { + length--; + } + return length; + } + + static protected short scale(java.math.BigDecimal value) { + if (value == null) { + return 0; + } + return (short)value.scale(); + } + + // Utility methods + + // Only for union type. Returns the index of the union member + // corresponding to the discriminator. If not found returns the + // default index or -1 if there is no default index. + int currentUnionMemberIndex(Any discriminatorValue) throws BadKind { + if (_kind != TCKind._tk_union) { + throw new BadKind(); + } + + try { + for (int i=0; i"); + } + + s.println(" " + _memberNames[i] + ";"); + } + s.print(indent(level) + "}"); + break; + + case TCKind._tk_union: + s.print("union " + _name + "..."); + break; + + case TCKind._tk_enum: + s.print("enum " + _name + "..."); + break; + + case TCKind._tk_string: + if (_length == 0) { + s.print("unbounded string " + _name); + } else { + s.print("bounded string(" + _length + ") " + _name); + } + break; + + case TCKind._tk_sequence: + case TCKind._tk_array: + s.println(kindNames[_kind] + "[" + _length + "] " + _name + " = {"); + s.print(indent(level + 1)); + if (lazy_content_type() != null) { + lazy_content_type().printStream(s, level + 1); + } + s.println(indent(level) + "}"); + break; + + case TCKind._tk_alias: + s.print("alias " + _name + " = " + + (_contentType != null ? _contentType._name : "")); + break; + + case TCKind._tk_wstring: + s.print("wstring[" + _length + "] " + _name); + break; + + case TCKind._tk_fixed: + s.print("fixed(" + _digits + ", " + _scale + ") " + _name); + break; + + case TCKind._tk_value_box: + s.print("valueBox " + _name + "..."); + break; + + case TCKind._tk_abstract_interface: + s.print("abstractInterface " + _name + "..."); + break; + + default: + s.print(""); + break; + } + } + + private String indent(int level) { + StringBuilder sb = new StringBuilder() ; + for(int i=0; i create config data + b. parse props -> create config data -> create components + + However, long-term bean persistence can be used in either model. Separation of + concerns (and the large size of the ORB class) argues for separating data from + components. + +2. get configuration out of ORB (except for finding config class) + ORB responsibility: + - gather all property, arg data together and make it available + - load the ORB configurator and let it process the data, generate a config object + - ORB is central registry, so ORB configurator store config data in ORB + +3. Extensibility is required + + The ORB will have large subsystems that are pluggable components (examples: aobject adaptors, + transport plugins). Individual instances of these frameworks will have their own configuration + data. To solve this, the ORB class will provide (read-only perhaps?) access to the collected + properties. + + While the component config data is not needed in the ORB, it is needed in the ORB config data + so that bean persistence can be used to create an XML version of the data. + + problem: properties vs. config data: same or not? + + properties: easier to use, also necessary to indicate where to get config data if not default + config data: more powerful + +4. Basic principle: A parser performs an action A based on a value V when it matches a property P. + Actions can be: + + configObject.setP( V ) + configObject.setP( A(V) ) + A(V) + +5. ParserActions are composable + + Basic action: Object parse( String arg, String value ) + which nicely handles prefix parsing and sharing of actions across multiple keys + + interface Operation { + Object operate( String arg, String value ) + } + + interface OperationFactory { + Operation booleanAction() ; + + Operation integerAction() ; + + Operation stringAction() ; + + Operation integerRangeAction( int min, int max ) ; + + Operation listAction( char sep, Operation act ) ; + } + + interface ParserAction { + void parse( String arg, String value ) ; + } + + interface ParserActionFactory { + ParserAction setFieldAction( String fieldName ) ; + + ParserAction setFieldAction( String fieldName, Operation op ) ; + + ParserAction operationAction( Operation op ) ; + } + +6. Parsers are created incrementally: + + Constructor: + new Parser( Class configurationDataClass ) + - has the parser class available for useful defaults + + interface PropertyParser { + /** Option must look like a standard property name, which we require here to + * be ( JavaIdent "." ) * JavaIdent. The last java ident we will call the tail. + * If tail starts with "ORB", this option will be used in augmentWithArguments. + * This match operates as follows: + * Let name = tail stripped of its ORB prefix. + * (e.g. if tail = ORBLowWaterMark, name = LowWaterMark). + * Then if option is matched, a conversion to the result type of the method named + * get is performed, and set is called on the data object to set the + * result. + */ + void addMatch( String option ) ; + + void addMatch( String option, ParserAction pa ) + + void addPrefixMatch( String prefix, ParserAction pa ) + + /** First constructs a new property object that has props as its default, + * then enters args into new property object that correspond to property + * names registered in match() calls. + */ + Properties augmentWithArguments( Properties props, String[] args ) ; + + /** Parse all matched properties in props, updating data as required + * by the actions. + */ + void parse( Properties props, ORBConfigurationData data ) ; + } + +7. A useful model: + + Provide + + abstract class ConfigDataBase { + ConfigDataBase( Properties props ) + { + ... + } + } + + and then a specific class + + public class ORBConfigData extends ConfigDataBase { + ORBConfigData( Properties props ) + { + super( props ) ; + } + + private int foo1 = fooDefault ; + private String foo2 = fooDefault2 ; + private boolean foo3 = fooDefault3 ; + private SomeObject foo4 = fooDefault4 ; + + public int getFoo1() { return foo1 ; } + // and similarly + } + + The constructor then uses reflection to automatically handle all of these variables with a number of + assumptions: + a. Standard names: + private foo { = } + public getFoo() { return foo ; } + as argument: -ORBfoo + as property: com.sun.corba.ee.foo (problems here) + b. type specific parsing + int: from Integer + String: no-op + boolean: true/false (from Boolean) + Class: must be able to load class + class XXX: XXX must have a public XXX( String ) constructor + + Custom parsing? + + What are valid prefixes? + 1. provide com.sun.corba.prefix.XXX where XXX defines a prefix to look for + (some security implications) + 2. Extend security model to ORB implementation (I like this approach best so far) + +8. ORB config + + public interface ORBConfigurator { + /** This method is called from ORB.init after all ORB properties have been + * collected. The corba.ORB constructor will make sure that all required + * registries are initialized and empty. This constructor will also initialize + * some data used in the corba ORB public API, such as support for deferred + * asynchronous invocation. However, all regisitration including things like + * the dyanmic any factory should take place in the configurator. This method + * is resonsible for making PI ORBInitializer calls, if PI is configured. + */ + void configure( com.sun.corba.ee.impl.core.ORB orb ) ; + } + + The ORB will have a default configurator named + + com.sun.corba.ee.impl.core.ORBConfiguratorImpl + + and also a property + + com.sun.CORBA.ORBConfiguratorClass + + than can be set to the name of the ORB configurator class to use. Note that this + implementation can either be a straight Java implementation, or something more + interpretive, such as an XML-based config description. + +9. We need to construct a list of all properties, and then make sure that security is respected. + The basic security check is just: + + SecurityManager sman = System.getSecurityManager() ; + if (sman != null) + sman.checkPropertyAccess( key ) + + and also + + sman.checkPropertiesAccess() + + We can construct a list of all properties as we do now, which allows the ORB + to call System.getProperties() inside a doPrivileged() block. Then we create + a subclass of java.util.Properties that overrides getProperty to + do the checkPropertyAccess( key ) call. We also need to overload the + enumerate method, either to make it illegal, call sman.checkPropertiesAccess, + or just filter it to include only the accessible properties. + And we also need to overload store, because it does not call enumerate internally. + + This allows us to provide all properties to an ORBConfigurator, while still preserving + the security model. Then anyone that needs security can set up property permissions + like com.foo.corba.* to allow access to only the properties they care about. + +10. ORB APIs + + The ORB needs registry support including: + getSubcontractRegistry + getServiceContextRegistry + + The ORB needs to provide access to a basic (and extensible) ORB configuration object, + which supports at a minimum all of the standard CORBA defined properties. + + Also need registries for: + ObjectAdapter (actually already in SubcontractRegistry, but needs extensions to + ObjectAdapterFactory to work fully) + TaggedComponentFactory + TaggedProfileFactory + + What does an empty ORB provide? + - Registration of all ORB components + - Request dispatching to object adapters + - Access to ORB properties data (as secure Properties object) + - Access to ORB arguments + - Access to ORB configuration data (base class, plus collections of base config + data for plugins such as OAs and transports) + - shutdown support (separate tracking of invocations vs. OA tracking in POA case? + How should this be designed?) + - INS support? (perhaps this could be pluggable too?) + - How does create_output_stream get plugged in? + - Can we separate the current IIOP transport into a TransportPluging? + - PI support + - CORBA::ORB API + - NVList, DII + - object <-> string (which includes INS?) + - (dis)connect API for TOA (move all impl to TOAImpl?) + - typecode/any + - FVD + - initial services registry + - value factory registry + - logging, other M&M support as needed + +ORB classes: + + core.ORB: abstract class providing internal interface + corba.ORBImpl: internal implementation of CORBA APIs + corba.ORBSingleton: the singleton ORB (not much change needed) + corba.ConfigurationDataCollector: collects all source of config data and canonicalizes it + Interceptor.PIHandler: the interface for PI + Interceptor.PIHandlerImpl: standard implementation of PIHandler + corba.ORBConfigurationData: extensible bean containing all ORB config data + +11. RequestHandler and ORB + + The RH interface is currently implemented in the ORB class, but mig???t better be a separate + class. The API is currently almost the same as a ServerSubcontract. Should we regularize + this? Also, the API would need to be extended to handle shutdown properly. + + Extended API: + - void run(): does not return until shutdown(boolean) is called. + - shutdown(boolean) needs to be here so that requests can be + synchhronized with shutdown. This is also a point where OAs + need to be included (currently in shutdownServants) + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynAnyBasicImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynAnyBasicImpl.java new file mode 100644 index 000000000..d03ea63e6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynAnyBasicImpl.java @@ -0,0 +1,663 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.dynamicany; + +import org.omg.CORBA.Any; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.TCKind; + +import org.omg.DynamicAny.DynAnyPackage.TypeMismatch; +import org.omg.DynamicAny.DynAnyPackage.InvalidValue; +import org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode; + +import com.sun.corba.ee.spi.orb.ORB ; + +public class DynAnyBasicImpl extends DynAnyImpl +{ + private static final long serialVersionUID = -6855799336532160409L; + // + // Constructors + // + + private DynAnyBasicImpl() { + this(null, (Any)null, false); + } + + protected DynAnyBasicImpl(ORB orb, Any any, boolean copyValue) { + super(orb, any, copyValue); + // set the current position to 0 if any has components, otherwise to -1. + index = NO_INDEX; + } + + protected DynAnyBasicImpl(ORB orb, TypeCode typeCode) { + super(orb, typeCode); + // set the current position to 0 if any has components, otherwise to -1. + index = NO_INDEX; + } + + // + // DynAny interface methods + // + + @Override + public void assign (org.omg.DynamicAny.DynAny dyn_any) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + super.assign(dyn_any); + index = NO_INDEX; + } + + @Override + public void from_any (org.omg.CORBA.Any value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + super.from_any(value); + index = NO_INDEX; + } + + // Spec: Returns a copy of the internal Any + public org.omg.CORBA.Any to_any() { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + return DynAnyUtil.copy(any, orb); + } + + public boolean equal (org.omg.DynamicAny.DynAny dyn_any) { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (dyn_any == this) { + return true; + } + // If the other DynAny is a constructed one we don't want it to have + // to create its Any representation just for this test. + if ( ! any.type().equal(dyn_any.type())) { + return false; + } + //System.out.println("Comparing anys"); + return any.equal(getAny(dyn_any)); + } + + public void destroy() { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (status == STATUS_DESTROYABLE) { + status = STATUS_DESTROYED; + } + } + + public org.omg.DynamicAny.DynAny copy() { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + // The flag "true" indicates copying the Any value + try { + return DynAnyUtil.createMostDerivedDynAny(any, orb, true); + } catch (InconsistentTypeCode ictc) { + return null; // impossible + } + } + + public org.omg.DynamicAny.DynAny current_component() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch + { + return null; + } + + public int component_count() { + return 0; + } + + public boolean next() { + return false; + } + + public boolean seek(int index) { + return false; + } + + public void rewind() { + } + + public void insert_boolean(boolean value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_boolean) { + throw new TypeMismatch(); + } + any.insert_boolean(value); + } + + public void insert_octet(byte value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_octet) { + throw new TypeMismatch(); + } + any.insert_octet(value); + } + + public void insert_char(char value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_char) { + throw new TypeMismatch(); + } + any.insert_char(value); + } + + public void insert_short(short value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_short) { + throw new TypeMismatch(); + } + any.insert_short(value); + } + + public void insert_ushort(short value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_ushort) { + throw new TypeMismatch(); + } + any.insert_ushort(value); + } + + public void insert_long(int value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_long) { + throw new TypeMismatch(); + } + any.insert_long(value); + } + + public void insert_ulong(int value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_ulong) { + throw new TypeMismatch(); + } + any.insert_ulong(value); + } + + public void insert_float(float value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_float) { + throw new TypeMismatch(); + } + any.insert_float(value); + } + + public void insert_double(double value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_double) { + throw new TypeMismatch(); + } + any.insert_double(value); + } + + public void insert_string(String value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_string) { + throw new TypeMismatch(); + } + if (value == null) { + throw new InvalidValue(); + } + // Throw InvalidValue if this is a bounded string and the length is exceeded + try { + if (any.type().length() > 0 && any.type().length() < value.length()) { + throw new InvalidValue(); + } + } catch (BadKind bad) { // impossible + } + any.insert_string(value); + } + + public void insert_reference(org.omg.CORBA.Object value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_objref) { + throw new TypeMismatch(); + } + any.insert_Object(value); + } + + public void insert_typecode(org.omg.CORBA.TypeCode value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_TypeCode) { + throw new TypeMismatch(); + } + any.insert_TypeCode(value); + } + + public void insert_longlong(long value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_longlong) { + throw new TypeMismatch(); + } + any.insert_longlong(value); + } + + public void insert_ulonglong(long value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_ulonglong) { + throw new TypeMismatch(); + } + any.insert_ulonglong(value); + } + + public void insert_wchar(char value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_wchar) { + throw new TypeMismatch(); + } + any.insert_wchar(value); + } + + public void insert_wstring(String value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_wstring) { + throw new TypeMismatch(); + } + if (value == null) { + throw new InvalidValue(); + } + // Throw InvalidValue if this is a bounded string and the length is exceeded + try { + if (any.type().length() > 0 && any.type().length() < value.length()) { + throw new InvalidValue(); + } + } catch (BadKind bad) { // impossible + } + any.insert_wstring(value); + } + + public void insert_any(org.omg.CORBA.Any value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_any) { + throw new TypeMismatch(); + } + any.insert_any(value); + } + + public void insert_dyn_any (org.omg.DynamicAny.DynAny value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_any) { + throw new TypeMismatch(); + } + // _REVISIT_ Copy value here? + any.insert_any(value.to_any()); + } + + public void insert_val(java.io.Serializable value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + int kind = any.type().kind().value(); + if (kind != TCKind._tk_value && kind != TCKind._tk_value_box) { + throw new TypeMismatch(); + } + any.insert_Value(value); + } + + public java.io.Serializable get_val() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + int kind = any.type().kind().value(); + if (kind != TCKind._tk_value && kind != TCKind._tk_value_box) { + throw new TypeMismatch(); + } + return any.extract_Value(); + } + + public boolean get_boolean() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_boolean) { + throw new TypeMismatch(); + } + return any.extract_boolean(); + } + + public byte get_octet() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_octet) { + throw new TypeMismatch(); + } + return any.extract_octet(); + } + + public char get_char() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_char) { + throw new TypeMismatch(); + } + return any.extract_char(); + } + + public short get_short() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_short) { + throw new TypeMismatch(); + } + return any.extract_short(); + } + + public short get_ushort() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_ushort) { + throw new TypeMismatch(); + } + return any.extract_ushort(); + } + + public int get_long() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_long) { + throw new TypeMismatch(); + } + return any.extract_long(); + } + + public int get_ulong() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_ulong) { + throw new TypeMismatch(); + } + return any.extract_ulong(); + } + + public float get_float() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_float) { + throw new TypeMismatch(); + } + return any.extract_float(); + } + + public double get_double() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_double) { + throw new TypeMismatch(); + } + return any.extract_double(); + } + + public String get_string() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_string) { + throw new TypeMismatch(); + } + return any.extract_string(); + } + + public org.omg.CORBA.Object get_reference() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_objref) { + throw new TypeMismatch(); + } + return any.extract_Object(); + } + + public org.omg.CORBA.TypeCode get_typecode() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_TypeCode) { + throw new TypeMismatch(); + } + return any.extract_TypeCode(); + } + + public long get_longlong() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_longlong) { + throw new TypeMismatch(); + } + return any.extract_longlong(); + } + + public long get_ulonglong() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_ulonglong) { + throw new TypeMismatch(); + } + return any.extract_ulonglong(); + } + + public char get_wchar() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_wchar) { + throw new TypeMismatch(); + } + return any.extract_wchar(); + } + + public String get_wstring() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_wstring) { + throw new TypeMismatch(); + } + return any.extract_wstring(); + } + + public org.omg.CORBA.Any get_any() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_any) { + throw new TypeMismatch(); + } + return any.extract_any(); + } + + public org.omg.DynamicAny.DynAny get_dyn_any() + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (any.type().kind().value() != TCKind._tk_any) { + throw new TypeMismatch(); + } + // _REVISIT_ Copy value here? + try { + return DynAnyUtil.createMostDerivedDynAny(any.extract_any(), orb, true); + } catch (InconsistentTypeCode ictc) { + // The spec doesn't allow us to throw back this exception + // incase the anys any if of type Principal, native or abstract interface. + return null; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynAnyCollectionImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynAnyCollectionImpl.java new file mode 100644 index 000000000..b8097278c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynAnyCollectionImpl.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.dynamicany; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.DynamicAny.*; +import org.omg.DynamicAny.DynAnyPackage.TypeMismatch; +import org.omg.DynamicAny.DynAnyPackage.InvalidValue; +import org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode; + +import com.sun.corba.ee.spi.orb.ORB ; + +abstract class DynAnyCollectionImpl extends DynAnyConstructedImpl +{ + private static final long serialVersionUID = -4420130353899323070L; + + // + // Instance variables + // + + // Keep in sync with DynAny[] components at all times. + Any[] anys = null; + + // + // Constructors + // + + protected DynAnyCollectionImpl(ORB orb, Any any, boolean copyValue) { + super(orb, any, copyValue); + } + + protected DynAnyCollectionImpl(ORB orb, TypeCode typeCode) { + super(orb, typeCode); + } + + // + // Utility methods + // + + protected void createDefaultComponentAt(int i, TypeCode contentType) { + try { + components[i] = DynAnyUtil.createMostDerivedDynAny(contentType, orb); + } catch (InconsistentTypeCode itc) { // impossible + } + // get a hold of the default initialized Any without copying + anys[i] = getAny(components[i]); + } + + protected TypeCode getContentType() { + try { + return any.type().content_type(); + } catch (BadKind badKind) { // impossible + return null; + } + } + + // This method has a different meaning for sequence and array: + // For sequence value of 0 indicates an unbounded sequence, + // values > 0 indicate a bounded sequence. + // For array any value indicates the boundary. + protected int getBound() { + try { + return any.type().length(); + } catch (BadKind badKind) { // impossible + return 0; + } + } + + // + // DynAny interface methods + // + + // _REVISIT_ More efficient copy operation + + // + // Collection methods + // + + public org.omg.CORBA.Any[] get_elements () { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + return (checkInitComponents() ? anys : null); + } + + protected abstract void checkValue(Object[] value) + throws org.omg.DynamicAny.DynAnyPackage.InvalidValue; + + // Initializes the elements of the ordered collection. + // If value does not contain the same number of elements as the array dimension, + // the operation raises InvalidValue. + // If one or more elements have a type that is inconsistent with the collections TypeCode, + // the operation raises TypeMismatch. + // This operation does not change the current position. + public void set_elements (org.omg.CORBA.Any[] value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + checkValue(value); + + components = new DynAny[value.length]; + anys = value; + + // We know that this is of kind tk_sequence or tk_array + TypeCode expectedTypeCode = getContentType(); + for (int i=0; i= names.length) { + throw new InvalidValue(); + } + return names[index]; + } + + public TCKind current_member_kind () + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if( ! checkInitComponents() || index < 0 || index >= components.length) { + throw new InvalidValue(); + } + return components[index].type().kind(); + } + + // Creates references to the parameter instead of copying it. + public void set_members (org.omg.DynamicAny.NameValuePair[] value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (value == null || value.length == 0) { + clearData(); + return; + } + + Any memberAny; + DynAny memberDynAny = null; + String memberName; + // We know that this is of kind tk_struct + TypeCode expectedTypeCode = any.type(); + + int expectedMemberCount = 0; + try { + expectedMemberCount = expectedTypeCode.member_count(); + } catch (BadKind badKind) { // impossible + } + if (expectedMemberCount != value.length) { + clearData(); + throw new InvalidValue(); + } + + allocComponents(value); + + for (int i=0; i= 0 && index < components.length) { + return true; + } else { + index = NO_INDEX; + return false; + } + } + + public boolean seek(int newIndex) { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + if (newIndex < 0) { + this.index = NO_INDEX; + return false; + } + if (checkInitComponents() == false) { + return false; + } + if (newIndex < components.length) { + index = newIndex; + return true; + } + return false; + } + + public void rewind() { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + this.seek(0); + } + + // + // Utility methods + // + + @Override + protected void clearData() { + super.clearData(); + // _REVISIT_ What about status? + components = emptyComponents; + index = NO_INDEX; + representations = REPRESENTATION_NONE; + } + + @Override + protected void writeAny(OutputStream out) { + // If all we got is TypeCode representation (no value) + // then we don't want to force creating a default value + //System.out.println(this + " checkInitAny before writeAny"); + checkInitAny(); + super.writeAny(out); + } + + // Makes sure that the components representation is initialized + protected boolean checkInitComponents() { + if ((representations & REPRESENTATION_COMPONENTS) == 0) { + if ((representations & REPRESENTATION_ANY) != 0) { + if (initializeComponentsFromAny()) { + representations |= REPRESENTATION_COMPONENTS; + } else { + return false; + } + } else if ((representations & REPRESENTATION_TYPECODE) != 0) { + if (initializeComponentsFromTypeCode()) { + representations |= REPRESENTATION_COMPONENTS; + } else { + return false; + } + } + } + return true; + } + + // Makes sure that the Any representation is initialized + protected void checkInitAny() { + if ((representations & REPRESENTATION_ANY) == 0) { + //System.out.println(this + " checkInitAny: reps does not have REPRESENTATION_ANY"); + if ((representations & REPRESENTATION_COMPONENTS) != 0) { + //System.out.println(this + " checkInitAny: reps has REPRESENTATION_COMPONENTS"); + if (initializeAnyFromComponents()) { + representations |= REPRESENTATION_ANY; + } + } else if ((representations & REPRESENTATION_TYPECODE) != 0) { + //System.out.println(this + " checkInitAny: reps has REPRESENTATION_TYPECODE"); + if (representations == REPRESENTATION_TYPECODE && isRecursive()) { + return; + } + if (initializeComponentsFromTypeCode()) { + representations |= REPRESENTATION_COMPONENTS; + } + if (initializeAnyFromComponents()) { + representations |= REPRESENTATION_ANY; + } + } + } else { + //System.out.println(this + " checkInitAny: reps != REPRESENTATION_ANY"); + } + return; + } + + protected abstract boolean initializeComponentsFromAny(); + protected abstract boolean initializeComponentsFromTypeCode(); + + // Collapses the whole DynAny hierarchys values into one single streamed Any + protected boolean initializeAnyFromComponents() { + //System.out.println(this + " initializeAnyFromComponents"); + OutputStream out = any.create_output_stream(); + for (int i=0; i= memberCount()) { + throw new InvalidValue(); + } + currentEnumeratorIndex = value; + any.insert_long(value); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynFixedImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynFixedImpl.java new file mode 100644 index 000000000..49da91833 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynFixedImpl.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.dynamicany; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import java.math.BigDecimal; +import java.math.BigInteger; +import org.omg.CORBA.TypeCodePackage.BadKind; + +import com.sun.corba.ee.spi.orb.ORB ; +import org.omg.DynamicAny.DynAnyPackage.InvalidValue; +import org.omg.DynamicAny.DynAnyPackage.TypeMismatch; +import org.omg.DynamicAny.DynFixed; + +public class DynFixedImpl extends DynAnyBasicImpl implements DynFixed +{ + private static final long serialVersionUID = -426296363713464920L; + // + // Constructors + // + + private DynFixedImpl() { + this(null, (Any)null, false); + } + + protected DynFixedImpl(ORB orb, Any any, boolean copyValue) { + super(orb, any, copyValue); + } + + // Sets the current position to -1 and the value to zero. + protected DynFixedImpl(ORB orb, TypeCode typeCode) { + super(orb, typeCode); + index = NO_INDEX; + } + + // + // DynAny interface methods + // +/* + public int component_count() { + return 0; + } +*/ + // + // DynFixed interface methods + // + + public String get_value () { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + return any.extract_fixed().toString(); + } + + // Initializes the value of the DynFixed. + // The val string must contain a fixed string constant in the same format + // as used for IDL fixed-point literals. + // + // It may consist of an integer part, an optional decimal point, + // a fraction part and an optional letter d or D. + // The integer and fraction parts both must be sequences of decimal (base 10) digits. + // Either the integer part or the fraction part, but not both, may be missing. + // + // If val contains a value whose scale exceeds that of the DynFixed or is not initialized, + // the operation raises InvalidValue. + // The return value is true if val can be represented as the DynFixed without loss of precision. + // If val has more fractional digits than can be represented in the DynFixed, + // fractional digits are truncated and the return value is false. + // If val does not contain a valid fixed-point literal or contains extraneous characters + // other than leading or trailing white space, the operation raises TypeMismatch. + // + public boolean set_value (String val) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + int digits = 0; + boolean preservedPrecision = true; + try { + digits = any.type().fixed_digits(); + } catch (BadKind ex) { // impossible + } + // First get rid of leading or trailing whitespace which is allowed + String string = val.trim(); + if (string.length() == 0) { + throw new TypeMismatch(); + } + // Now scan for the sign + String sign = ""; + if (string.charAt(0) == '-') { + sign = "-"; + string = string.substring(1); + } else if (string.charAt(0) == '+') { + sign = "+"; + string = string.substring(1); + } + // Now get rid of the letter d or D. + int dIndex = string.indexOf('d'); + if (dIndex == -1) { + dIndex = string.indexOf('D'); + } + if (dIndex != -1) { + string = string.substring(0, dIndex); + } + // Just to be sure + if (string.length() == 0) { + throw new TypeMismatch(); + } + // Now look for the dot to determine the integer part + String integerPart; + String fractionPart; + int currentScale; + int currentDigits; + int dotIndex = string.indexOf('.'); + if (dotIndex == -1) { + integerPart = string; + fractionPart = null; + currentScale = 0; + currentDigits = integerPart.length(); + } else if (dotIndex == 0 ) { + integerPart = null; + fractionPart = string; + currentScale = fractionPart.length(); + currentDigits = currentScale; + } else { + integerPart = string.substring(0, dotIndex); + fractionPart = string.substring(dotIndex + 1); + currentScale = fractionPart.length(); + currentDigits = integerPart.length() + currentScale; + } + + int integerPartLength = (integerPart == null) ? 0 + : integerPart.length() ; + + // Let's see if we have to drop some precision + if (currentDigits > digits) { + preservedPrecision = false; + // truncate the fraction part + if (integerPartLength < digits) { + fractionPart = fractionPart.substring(0, digits - integerPartLength ) ; + } else if (integerPartLength == digits) { + // currentScale > 0 + // drop the fraction completely + fractionPart = null; + } else { + // integerPartLength > digits + // unable to truncate fraction part + throw new InvalidValue(); + } + } + // If val contains a value whose scale exceeds that of the DynFixed or is not initialized, + // the operation raises InvalidValue. + // Reinterpreted to mean raise InvalidValue only if the integer part exceeds precision, + // which is handled above (integerPart.length() > digits) +/* + if (currentScale > scale) { + throw new InvalidValue("Scale exceeds " + scale); + } +*/ + // Now check whether both parts are valid numbers + BigDecimal result; + try { + if (fractionPart == null) { + result = new BigDecimal(sign + integerPart); + } else { + result = new BigDecimal(sign + integerPart + "." + fractionPart); + } + } catch (NumberFormatException nfe) { + throw new TypeMismatch(); + } + any.insert_fixed(result, any.type()); + return preservedPrecision; + } + + @Override + public String toString() { + int digits = 0; + int scale = 0; + try { + digits = any.type().fixed_digits(); + scale = any.type().fixed_scale(); + } catch (BadKind ex) { // impossible + } + return "DynFixed with value=" + this.get_value() + ", digits=" + digits + ", scale=" + scale; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynSequenceImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynSequenceImpl.java new file mode 100644 index 000000000..f2501860e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynSequenceImpl.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.dynamicany; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.DynamicAny.DynAnyPackage.InvalidValue; +import org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode; + +import com.sun.corba.ee.spi.orb.ORB ; +import org.omg.DynamicAny.DynAny; +import org.omg.DynamicAny.DynSequence; + +// _REVIST_ Could make this a subclass of DynArrayImpl +// But that would mean that an object that implements DynSequence also implements DynArray +// which the spec doesn't mention (it also doesn't forbid it). +public class DynSequenceImpl extends DynAnyCollectionImpl implements DynSequence +{ + private static final long serialVersionUID = 5355861023015151151L; + // + // Constructors + // + protected DynSequenceImpl(ORB orb, Any any, boolean copyValue) { + super(orb, any, copyValue); + } + + // Sets the current position to -1 and creates an empty sequence. + protected DynSequenceImpl(ORB orb, TypeCode typeCode) { + super(orb, typeCode); + } + + // Initializes components and anys representation + // from the Any representation + protected boolean initializeComponentsFromAny() { + // This typeCode is of kind tk_sequence. + int length; + TypeCode contentType = getContentType(); + InputStream input; + + try { + input = any.create_input_stream(); + } catch (BAD_OPERATION e) { + return false; + } + + length = input.read_long(); + components = new DynAny[length]; + anys = new Any[length]; + + for (int i=0; i 0 && len > bound) { + throw new InvalidValue(); + } + + checkInitComponents(); + + int oldLength = components.length; + if (len > oldLength) { + // Increase length + DynAny[] newComponents = new DynAny[len]; + Any[] newAnys = new Any[len]; + System.arraycopy(components, 0, newComponents, 0, oldLength); + System.arraycopy(anys, 0, newAnys, 0, oldLength); + components = newComponents; + anys = newAnys; + + // Newly added elements are default-initialized + TypeCode contentType = getContentType(); + for (int i=oldLength; i= len) { + index = NO_INDEX; + } + } else { + // Length unchanged + // Maybe components is now default initialized from type code + if (index == NO_INDEX && len > 0) { + index = 0; + } + } + } + + // Initializes the elements of the sequence. + // The length of the DynSequence is set to the length of value. + // The current position is set to zero if value has non-zero length + // and to -1 if value is a zero-length sequence. + // If the length of value exceeds the bound of a bounded sequence, + // the operation raises InvalidValue. + // If value contains one or more elements whose TypeCode is not equivalent + // to the element TypeCode of the DynSequence, the operation raises TypeMismatch. +/* + public void set_elements(org.omg.CORBA.Any[] value) + throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, + org.omg.DynamicAny.DynAnyPackage.InvalidValue; +*/ + + // + // Utility methods + // + + protected void checkValue(Object[] value) + throws org.omg.DynamicAny.DynAnyPackage.InvalidValue + { + if (value == null || value.length == 0) { + clearData(); + index = NO_INDEX; + return; + } else { + index = 0; + } + int bound = getBound(); + if (bound > 0 && value.length > bound) { + throw new InvalidValue(); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynStructImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynStructImpl.java new file mode 100644 index 000000000..f65469e10 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynStructImpl.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.dynamicany; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +import com.sun.corba.ee.spi.orb.ORB ; +import org.omg.DynamicAny.DynStruct; + +public class DynStructImpl extends DynAnyComplexImpl implements DynStruct +{ + private static final long serialVersionUID = 2832306671453429704L; + + // + // Constructors + // + protected DynStructImpl(ORB orb, Any any, boolean copyValue) { + // We can be sure that typeCode is of kind tk_struct + super(orb, any, copyValue); + // Initialize components lazily, on demand. + // This is an optimization in case the user is only interested in storing Anys. + } + + protected DynStructImpl(ORB orb, TypeCode typeCode) { + // We can be sure that typeCode is of kind tk_struct + super(orb, typeCode); + // For DynStruct, the operation sets the current position to -1 + // for empty exceptions and to zero for all other TypeCodes. + // The members (if any) are (recursively) initialized to their default values. + index = 0; + } + + // + // Methods differing from DynValues + // + public org.omg.DynamicAny.NameValuePair[] get_members () { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + checkInitComponents(); + return nameValuePairs.clone() ; + } + + public org.omg.DynamicAny.NameDynAnyPair[] get_members_as_dyn_any () { + if (status == STATUS_DESTROYED) { + throw wrapper.dynAnyDestroyed() ; + } + checkInitComponents(); + return nameDynAnyPairs.clone() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynUnionImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynUnionImpl.java new file mode 100644 index 000000000..1bdb094e8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/dynamicany/DynUnionImpl.java @@ -0,0 +1,369 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.dynamicany; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.TypeCodePackage.Bounds; +import org.omg.CORBA.portable.InputStream; +import org.omg.DynamicAny.DynAnyPackage.TypeMismatch; +import org.omg.DynamicAny.DynAnyPackage.InvalidValue; +import org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode; + +import com.sun.corba.ee.spi.orb.ORB ; +import org.omg.DynamicAny.DynAny; +import org.omg.DynamicAny.DynUnion; + +public class DynUnionImpl extends DynAnyConstructedImpl implements DynUnion +{ + private static final long serialVersionUID = 5712467966035057576L; + // + // Instance variables + // + + DynAny discriminator = null; + // index either points to the discriminator or the named member is it exists. + // The currently active member, which is of the same type as the discriminator. + DynAny currentMember = null; + int currentMemberIndex = NO_INDEX; + + // + // Constructors + // + protected DynUnionImpl(ORB orb, Any any, boolean copyValue) { + // We can be sure that typeCode is of kind tk_union + super(orb, any, copyValue); + } + + protected DynUnionImpl(ORB orb, TypeCode typeCode) { + // We can be sure that typeCode is of kind tk_union + super(orb, typeCode); + } + + protected boolean initializeComponentsFromAny() { + try { + InputStream input = any.create_input_stream(); + Any discriminatorAny = DynAnyUtil.extractAnyFromStream(discriminatorType(), input, orb); + discriminator = DynAnyUtil.createMostDerivedDynAny(discriminatorAny, orb, false); + currentMemberIndex = currentUnionMemberIndex(discriminatorAny); + Any memberAny = DynAnyUtil.extractAnyFromStream(memberType(currentMemberIndex), input, orb); + currentMember = DynAnyUtil.createMostDerivedDynAny(memberAny, orb, false); + components = new DynAny[] {discriminator, currentMember}; + } catch (InconsistentTypeCode ictc) { // impossible + } + return true; + } + + // Sets the current position to zero. + // The discriminator value is set to a value consistent with the first named member + // of the union. That member is activated and (recursively) initialized to its default value. + protected boolean initializeComponentsFromTypeCode() { + //System.out.println(this + " initializeComponentsFromTypeCode"); + try { + // We can be sure that memberCount() > 0 according to the IDL language spec + discriminator = DynAnyUtil.createMostDerivedDynAny(memberLabel(0), orb, false); + index = 0; + currentMemberIndex = 0; + currentMember = DynAnyUtil.createMostDerivedDynAny(memberType(0), orb); + components = new DynAny[] {discriminator, currentMember}; + } catch (InconsistentTypeCode ictc) { // impossible + } + return true; + } + + // + // Convenience methods + // + + private TypeCode discriminatorType() { + TypeCode discriminatorType = null; + try { + discriminatorType = any.type().discriminator_type(); + } catch (BadKind bad) { + } + return discriminatorType; + } + + private int memberCount() { + int memberCount = 0; + try { + memberCount = any.type().member_count(); + } catch (BadKind bad) { + } + return memberCount; + } + + private Any memberLabel(int i) { + Any memberLabel = null; + try { + memberLabel = any.type().member_label(i); + } catch (BadKind bad) { + } catch (Bounds bounds) { + } + return memberLabel; + } + + private TypeCode memberType(int i) { + TypeCode memberType = null; + try { + memberType = any.type().member_type(i); + } catch (BadKind bad) { + } catch (Bounds bounds) { + } + return memberType; + } + + private String memberName(int i) { + String memberName = null; + try { + memberName = any.type().member_name(i); + } catch (BadKind bad) { + } catch (Bounds bounds) { + } + return memberName; + } + + private int defaultIndex() { + int defaultIndex = -1; + try { + defaultIndex = any.type().default_index(); + } catch (BadKind bad) { + } + return defaultIndex; + } + + private int currentUnionMemberIndex(Any discriminatorValue) { + int memberCount = memberCount(); + Any memberLabel; + for (int i=0; i fragmentStack = null; + private RestorableInputStream inputStream = null; + + // Original state of the stream + private Object streamMemento = null; + + public void mark(RestorableInputStream inputStream) { + this.inputStream = inputStream; + markEngaged = true; + + // Get the magic Object that the stream will use to + // reconstruct it's state when reset is called + streamMemento = inputStream.createStreamMemento(); + + if (fragmentStack != null) { + fragmentStack.clear(); + } + } + + // Collects fragments received since the mark was engaged. + public void fragmentationOccured(ByteBuffer newFrament) { + if (!markEngaged) { + return; + } + + if (fragmentStack == null) { + fragmentStack = new LinkedList(); + } + + fragmentStack.addFirst(newFrament.duplicate()); + } + + public void reset() { + if (!markEngaged) { + // REVISIT - call to reset without call to mark + return; + } + + markEngaged = false; + + // If we actually did peek across fragments, we need + // to push those fragments onto the front of the + // buffer queue. + if (fragmentStack != null && fragmentStack.size() != 0) { + + synchronized (fragmentQueue) { + for (ByteBuffer aBuffer : fragmentStack) { + fragmentQueue.push(aBuffer); + } + } + + fragmentStack.clear(); + } + + // Give the stream the magic Object to restore + // it's state. + inputStream.restoreInternalState(streamMemento); + } + + public MarkAndResetHandler getMarkAndResetHandler() { + return this; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWrite.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWrite.java new file mode 100644 index 000000000..30b35130b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWrite.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import java.nio.ByteBuffer; + +/** + * Defines the contract between the BufferManager and + * CDR stream on the writing side. The CDR stream + * calls back to the BufferManagerWrite when it needs + * more room in the output buffer to continue. The + * BufferManager can then grow the output buffer or + * use some kind of fragmentation technique. + */ +public abstract class BufferManagerWrite +{ + protected ORB orb ; + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + BufferManagerWrite( ORB orb ) + { + this.orb = orb ; + } + + /** + * Has the stream sent out any fragments so far? + */ + public abstract boolean sentFragment(); + + /** + * Has the entire message been sent? (Has + * sendMessage been called?) + */ + public boolean sentFullMessage() { + return sentFullMessage; + } + + /** + * Returns the correct buffer size for this type of + * buffer manager as set in the ORB. + */ + public abstract int getBufferSize(); + + /* + * Invoked when we run out of room to write. Must either expand the buffer or send it as a fragment and clear it. + */ + protected abstract ByteBuffer overflow(ByteBuffer byteBuffer, int numBytesNeeded); + + /** + * Returns true if this buffer manager fragments when an overflow occurs. + */ + public abstract boolean isFragmentOnOverflow(); + + /** + * Called after Stub._invoke (i.e., before complete message has been sent). + * + * IIOPOutputStream.writeTo called from IIOPOutputStream.invoke + * + * Case: overflow was never called (bbwi.buf contains complete message). + * Backpatch size field. + * If growing or collecting: + * this.bufQ.put(bbwi). + * this.bufQ.iterate // However, see comment in getBufferQ + * this.connection.send(fragment) + * If streaming: + * this.connection.send(bbwi). + * + * Case: overflow was called N times (bbwi.buf contains last buffer). + * If growing or collecting: + * this.bufQ.put(bbwi). + * backpatch size field in first buffer. + * this.bufQ.iterate // However, see comment in getBufferQ + * this.connection.send(fragment) + * If streaming: + * backpatch fragment size field in bbwi.buf. + * Set no more fragments bit. + * this.connection.send(bbwi). + */ + + public abstract void sendMessage (); + + + /** + * A reference to the connection level stream will be required when + * sending fragments. + */ + public void setOutputObject(Object outputObject) { + this.outputObject = outputObject; + } + + /** + * Close the BufferManagerWrite and do any outstanding cleanup. + */ + abstract public void close(); + + // XREVISIT - Currently a java.lang.Object during + // the rip-int-generic transition. Should eventually + // become a GIOPOutputObject. + protected Object outputObject; + + protected boolean sentFullMessage = false; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWriteGrow.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWriteGrow.java new file mode 100644 index 000000000..7363b2ff9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWriteGrow.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.transport.ByteBufferPool; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.orb.ORB; + +import java.nio.ByteBuffer; + +public class BufferManagerWriteGrow extends BufferManagerWrite +{ + BufferManagerWriteGrow( ORB orb ) + { + super(orb) ; + } + + public boolean sentFragment() { + return false; + } + + /** + * Returns the correct buffer size for this type of + * buffer manager as set in the ORB. + */ + public int getBufferSize() { + return orb.getORBData().getGIOPBufferSize(); + } + + @Override + protected ByteBuffer overflow(ByteBuffer byteBuffer, int numBytesNeeded) { + int newLength = byteBuffer.limit() * 2; + + while (byteBuffer.position() + numBytesNeeded >= newLength) + newLength = newLength * 2; + + ByteBufferPool byteBufferPool = orb.getByteBufferPool(); + ByteBuffer newBB = byteBufferPool.getByteBuffer(newLength); + + byteBuffer.flip(); + newBB.put(byteBuffer); + + byteBufferPool.releaseByteBuffer(byteBuffer); + return newBB; + } + + @Override + public boolean isFragmentOnOverflow() { + return false; + } + + public void sendMessage () { + Connection conn = + ((CDROutputObject)outputObject).getMessageMediator().getConnection(); + + conn.writeLock(); + + try { + + conn.sendWithoutLock((CDROutputObject)outputObject); + + sentFullMessage = true; + + } finally { + + conn.writeUnlock(); + } + } + + /** + * Close the BufferManagerWrite and do any outstanding cleanup. + * + * No work to do for a BufferManagerWriteGrow. + */ + public void close() {} + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWriteStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWriteStream.java new file mode 100644 index 000000000..6a21e1926 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferManagerWriteStream.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.FragmentMessage; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ContactInfoListIterator; +import org.glassfish.pfl.basic.reflection.Bridge; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.RemarshalException; + +import java.nio.ByteBuffer; +import java.util.EmptyStackException; + +/** + * Streaming buffer manager. + */ +public class BufferManagerWriteStream extends BufferManagerWrite +{ + private int fragmentCount = 0; + + BufferManagerWriteStream( ORB orb ) + { + super(orb) ; + } + + public boolean sentFragment() { + return fragmentCount > 0; + } + + /** + * Returns the correct buffer size for this type of + * buffer manager as set in the ORB. + */ + public int getBufferSize() { + return orb.getORBData().getGIOPFragmentSize(); + } + + protected ByteBuffer overflow(ByteBuffer byteBuffer, int numBytesNeeded) { + // Set the fragment's moreFragments field to true + MessageBase.setFlag(byteBuffer, Message.MORE_FRAGMENTS_BIT); + + try { + sendFragment(false); + } catch (SystemException se) { + // REVISIT: this part similar to + // CorbaClientRequestDispatchImpl.beginRequest() + // and CorbaClientRequestDelegate.request() + ContactInfoListIterator itr; + try { + itr = getContactInfoListIterator(); + } catch (EmptyStackException ese) { + // server side, don't reportException + throw se; + } + + // bug 6382377: must not lose exception in PI + orb.getPIHandler().invokeClientPIEndingPoint( ReplyMessage.SYSTEM_EXCEPTION, se ) ; + + boolean retry = itr.reportException(null, se); + if (retry) { + Bridge bridge = Bridge.get(); + bridge.throwException(new RemarshalException()); + } else { + // re-throw the SystemException + throw se; + } + } + + // Reuse the old buffer + + // REVISIT - need to account for case when needed > available + // even after fragmenting. This is the large array case, so + // the caller should retry when it runs out of space. + byteBuffer.position(0); + byteBuffer.limit(byteBuffer.capacity()); + + // Now we must marshal in the fragment header/GIOP header + + // REVISIT - we can optimize this by not creating the fragment message + // each time. + + FragmentMessage header = ((CDROutputObject)outputObject).getMessageHeader().createFragmentMessage(); + + header.write(((CDROutputObject)outputObject)); + return byteBuffer; + } + + @Override + public boolean isFragmentOnOverflow() { + return true; + } + + private void sendFragment(boolean isLastFragment) + { + Connection conn = ((CDROutputObject)outputObject).getMessageMediator().getConnection(); + + // REVISIT: need an ORB + //System.out.println("sendFragment: last?: " + isLastFragment); + conn.writeLock(); + + try { + // Send the fragment + conn.sendWithoutLock(((CDROutputObject)outputObject)); + + fragmentCount++; + + } finally { + + conn.writeUnlock(); + } + + } + + // Sends the last fragment + public void sendMessage () + { + sendFragment(true); + + sentFullMessage = true; + } + + /** + * Close the BufferManagerWrite and do any outstanding cleanup. + * + * No work to do for a BufferManagerWriteStream + */ + public void close(){}; + + /** + * Get CorbaContactInfoListIterator + * + * NOTE: Requires this.orb + */ + protected ContactInfoListIterator getContactInfoListIterator() { + return (ContactInfoListIterator) this.orb.getInvocationInfo().getContactInfoListIterator(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferQueue.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferQueue.java new file mode 100644 index 000000000..c5091ffeb --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/BufferQueue.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.NoSuchElementException; + +/** + * Simple unsynchronized queue implementation for ByteBuffer. + */ +public class BufferQueue +{ + private LinkedList list = + new LinkedList(); + + public void enqueue(ByteBuffer item) + { + list.addLast(item); + } + + public ByteBuffer dequeue() throws NoSuchElementException + { + return list.removeFirst(); + } + + public int size() + { + return list.size(); + } + + // Adds the given ByteBuffer to the front of the queue. + public void push(ByteBuffer item) + { + list.addFirst(item); + } + + public void clear() { + list.clear() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputObject.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputObject.java new file mode 100644 index 000000000..f09dcc0dd --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputObject.java @@ -0,0 +1,763 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteBuffer; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.FragmentMessage; +import com.sun.org.omg.SendingContext.CodeBase; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.trace.Transport; +import com.sun.corba.ee.spi.trace.MonitorRead ; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.nio.ByteOrder; + +import org.omg.CORBA.Any; +import org.omg.CORBA.TypeCode; + +/** + * @author Harold Carr + */ +@Transport +@MonitorRead +public class CDRInputObject + extends org.omg.CORBA_2_3.portable.InputStream + implements com.sun.corba.ee.impl.encoding.MarshalInputStream, + org.omg.CORBA.DataInputStream, org.omg.CORBA.portable.ValueInputStream +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + private static final long serialVersionUID = 3654171034620991056L; + + private transient ORB orb ; + private transient CDRInputStreamBase impl; + private transient Connection corbaConnection; + private transient Message header; + protected transient MessageMediator messageMediator; + + // Present only to suppress FindBugs errors + private void readObject( ObjectInputStream is ) throws IOException, + ClassNotFoundException { + + orb = null ; + impl = null ; + corbaConnection = null ; + header = null ; + messageMediator = null ; + } + + private boolean unmarshaledHeader; + + public void addFragment(FragmentMessage header, ByteBuffer byteBuffer) { + getBufferManager().processFragment(byteBuffer, header); + } + + public void cancelProcessing(int requestId) { + BufferManagerReadStream bufferManager = (BufferManagerReadStream) getBufferManager(); + bufferManager.cancelProcessing(requestId); + } + + private static class InputStreamFactory { + public static CDRInputStreamBase newInputStream(GIOPVersion version) { + switch(version.intValue()) { + case GIOPVersion.VERSION_1_0: + return new CDRInputStream_1_0(); + case GIOPVersion.VERSION_1_1: + return new CDRInputStream_1_1(); + case GIOPVersion.VERSION_1_2: + return new CDRInputStream_1_2(); + default: + throw wrapper.unsupportedGiopVersion( version ) ; + } + } + } + + // Required for the case when a ClientResponseImpl is + // created with a SystemException due to a dead server/closed + // connection with no warning. Note that the stream will + // not be initialized in this case. + // + // Probably also required by ServerRequestImpl. + // + // REVISIT. + public CDRInputObject() { + } + + public CDRInputObject(CDRInputObject is) { + impl = is.impl.dup(); + impl.setParent(this); + } + + protected CDRInputObject(org.omg.CORBA.ORB orb, ByteBuffer byteBuffer, int size, + ByteOrder byteOrder, GIOPVersion version, + BufferManagerRead bufMgr) { + + this.orb = (ORB)orb ; + createCDRInputStream(version, byteBuffer, size, byteOrder, bufMgr); + + this.corbaConnection = null ; + this.header = null ; + this.unmarshaledHeader = false ; + this.messageMediator = null ; + } + + private void createCDRInputStream(GIOPVersion version, ByteBuffer byteBuffer, int size, + ByteOrder byteOrder, BufferManagerRead bufMgr) { + impl = InputStreamFactory.newInputStream(version); + impl.init(orb, byteBuffer, size, byteOrder, bufMgr); + impl.setParent(this); + } + + protected static ByteOrder toByteOrder(boolean littleEndian) { + return littleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; + } + + public CDRInputObject(ORB orb, Connection corbaConnection, ByteBuffer byteBuffer, Message header) { + this(orb, byteBuffer, header.getSize(), toByteOrder(header.isLittleEndian()), header.getGIOPVersion(), + createBufferManagerRead(orb, header)); + + this.corbaConnection = corbaConnection; + this.header = header ; + + getBufferManager().init(header); + setIndex(Message.GIOPMessageHeaderLength); + setBufferLength(header.getSize()); + } + + private static BufferManagerRead createBufferManagerRead(ORB orb, Message header) { + return BufferManagerFactory.newBufferManagerRead(header.getGIOPVersion(), header.getEncodingVersion(), orb); + } + + // REVISIT - think about this some more. + // This connection normally is accessed from the message mediator. + // However, giop input needs to get code set info from the connetion + // *before* the message mediator is available. + public final Connection getConnection() + { + return corbaConnection; + } + + // XREVISIT - Should the header be kept in the stream or the + // message mediator? Or should we not have a header and + // have the information stored in the message mediator + // directly? + public Message getMessageHeader() + { + return header; + } + + private void unmarshalledHeader( Message msg ) { } + + /** + * Unmarshal the extended GIOP header + * NOTE: May be fragmented, so should not be called by the ReaderThread. + * See CorbaResponseWaitingRoomImpl.waitForResponse. It is done + * there in the client thread. + */ + @Transport + public void unmarshalHeader() + { + // Unmarshal the extended GIOP message from the buffer. + + if (!unmarshaledHeader) { + try { + getMessageHeader().read(this); + unmarshalledHeader( getMessageHeader() ) ; + unmarshaledHeader= true; + } catch (RuntimeException e) { + throw e; + } + } + } + + /** + * Override the default CDR factory behavior to get the + * negotiated code sets from the connection. + * + * These are only called once per message, the first time needed. + * + * In the local case, there is no Connection, so use the + * local code sets. + * @return The converter. + */ + protected CodeSetConversion.BTCConverter createCharBTCConverter() { + CodeSetComponentInfo.CodeSetContext codesets = getCodeSets(); + + // If the connection doesn't have its negotiated + // code sets by now, fall back on the defaults defined + // in CDRInputStream. + if (codesets == null) { + return CodeSetConversion.impl().getBTCConverter(OSFCodeSetRegistry.ISO_8859_1, impl.getByteOrder()); + } + + OSFCodeSetRegistry.Entry charSet + = OSFCodeSetRegistry.lookupEntry(codesets.getCharCodeSet()); + + if (charSet == null) { + throw wrapper.unknownCodeset(codesets.getCharCodeSet()); + } + + return CodeSetConversion.impl().getBTCConverter(charSet, getByteOrder()); + } + + protected CodeSetConversion.BTCConverter createWCharBTCConverter() { + + CodeSetComponentInfo.CodeSetContext codesets = getCodeSets(); + + // If the connection doesn't have its negotiated + // code sets by now, we have to throw an exception. + // See CORBA formal 00-11-03 13.9.2.6. + if (codesets == null) { + if (getConnection().isServer()) { + throw omgWrapper.noClientWcharCodesetCtx(); + } else { + throw omgWrapper.noServerWcharCodesetCmp(); + } + } + + OSFCodeSetRegistry.Entry wcharSet + = OSFCodeSetRegistry.lookupEntry(codesets.getWCharCodeSet()); + + if (wcharSet == null) { + throw wrapper.unknownCodeset(codesets.getWCharCodeSet()); + } + + // For GIOP 1.2 and UTF-16, use big endian if there is no byte + // order marker. (See issue 3405b) + // + // For GIOP 1.1 and UTF-16, use the byte order the stream if + // there isn't (and there shouldn't be) a byte order marker. + // + // GIOP 1.0 doesn't have wchars. If we're talking to a legacy ORB, + // we do what our old ORBs did. + if (wcharSet == OSFCodeSetRegistry.UTF_16) { + if (getGIOPVersion().equals(GIOPVersion.V1_2)) { + return CodeSetConversion.impl().getBTCConverter(wcharSet, ByteOrder.BIG_ENDIAN); + } + } + + return CodeSetConversion.impl().getBTCConverter(wcharSet, getByteOrder()); + } + + // If we're local and don't have a Connection, use the + // local code sets, otherwise get them from the connection. + // If the connection doesn't have negotiated code sets + // yet, then we use ISO8859-1 for char/string and wchar/wstring + // are illegal. + private CodeSetComponentInfo.CodeSetContext getCodeSets() { + if (getConnection() == null) { + return CodeSetComponentInfo.LOCAL_CODE_SETS; + } else { + return getConnection().getCodeSetContext(); + } + } + + public CodeBase getCodeBase() { + if (getConnection() == null) { + return null; + } else { + return getConnection().getCodeBase(); + } + } + + public CDRInputObject dup() { + return null; + } + + protected void dprint(String msg) + { + ORBUtility.dprint("CDRInputObject", msg); + } + + // org.omg.CORBA.portable.InputStream + @MonitorRead + public final boolean read_boolean() { + return impl.read_boolean(); + } + + @MonitorRead + public final char read_char() { + return impl.read_char(); + } + + @MonitorRead + public final char read_wchar() { + return impl.read_wchar(); + } + + @MonitorRead + public final byte read_octet() { + return impl.read_octet(); + } + + @MonitorRead + public final short read_short() { + return impl.read_short(); + } + + @MonitorRead + public final short read_ushort() { + return impl.read_ushort(); + } + + @MonitorRead + public final int read_long() { + return impl.read_long(); + } + + @MonitorRead + public final int read_ulong() { + return impl.read_ulong(); + } + + @MonitorRead + public final long read_longlong() { + return impl.read_longlong(); + } + + @MonitorRead + public final long read_ulonglong() { + return impl.read_ulonglong(); + } + + @MonitorRead + public final float read_float() { + return impl.read_float(); + } + + @MonitorRead + public final double read_double() { + return impl.read_double(); + } + + @MonitorRead + public final String read_string() { + return impl.read_string(); + } + + @MonitorRead + public final String read_wstring() { + return impl.read_wstring(); + } + + @MonitorRead + public final void read_boolean_array(boolean[] value, int offset, int length) { + impl.read_boolean_array(value, offset, length); + } + + @MonitorRead + public final void read_char_array(char[] value, int offset, int length) { + impl.read_char_array(value, offset, length); + } + + @MonitorRead + public final void read_wchar_array(char[] value, int offset, int length) { + impl.read_wchar_array(value, offset, length); + } + + @MonitorRead + public final void read_octet_array(byte[] value, int offset, int length) { + impl.read_octet_array(value, offset, length); + } + + @MonitorRead + public final void read_short_array(short[] value, int offset, int length) { + impl.read_short_array(value, offset, length); + } + + @MonitorRead + public final void read_ushort_array(short[] value, int offset, int length) { + impl.read_ushort_array(value, offset, length); + } + + @MonitorRead + public final void read_long_array(int[] value, int offset, int length) { + impl.read_long_array(value, offset, length); + } + + @MonitorRead + public final void read_ulong_array(int[] value, int offset, int length) { + impl.read_ulong_array(value, offset, length); + } + + @MonitorRead + public final void read_longlong_array(long[] value, int offset, int length) { + impl.read_longlong_array(value, offset, length); + } + + @MonitorRead + public final void read_ulonglong_array(long[] value, int offset, int length) { + impl.read_ulonglong_array(value, offset, length); + } + + @MonitorRead + public final void read_float_array(float[] value, int offset, int length) { + impl.read_float_array(value, offset, length); + } + + @MonitorRead + public final void read_double_array(double[] value, int offset, int length) { + impl.read_double_array(value, offset, length); + } + + @MonitorRead + public final org.omg.CORBA.Object read_Object() { + return impl.read_Object(); + } + + @MonitorRead + public final TypeCode read_TypeCode() { + return impl.read_TypeCode(); + } + + @MonitorRead + public final Any read_any() { + return impl.read_any(); + } + + @MonitorRead + @SuppressWarnings({"deprecation"}) + @Override + public final org.omg.CORBA.Principal read_Principal() { + return impl.read_Principal(); + } + + @MonitorRead + @Override + public final int read() throws java.io.IOException { + return impl.read(); + } + + @MonitorRead + @Override + public final java.math.BigDecimal read_fixed() { + return impl.read_fixed(); + } + + @MonitorRead + @Override + public final org.omg.CORBA.Context read_Context() { + return impl.read_Context(); + } + + @MonitorRead + @Override + public final org.omg.CORBA.Object read_Object(java.lang.Class clz) { + return impl.read_Object(clz); + } + + @Override + public final org.omg.CORBA.ORB orb() { + return impl.orb(); + } + + // org.omg.CORBA_2_3.portable.InputStream + @MonitorRead + @Override + public final java.io.Serializable read_value() { + return impl.read_value(); + } + + @MonitorRead + @Override + public final java.io.Serializable read_value(java.lang.Class clz) { + return impl.read_value(clz); + } + + @MonitorRead + @Override + public final java.io.Serializable read_value( + org.omg.CORBA.portable.BoxedValueHelper factory) { + + return impl.read_value(factory); + } + + @MonitorRead + @Override + public final java.io.Serializable read_value(java.lang.String rep_id) { + return impl.read_value(rep_id); + } + + @MonitorRead + @Override + public final java.io.Serializable read_value(java.io.Serializable value) { + return impl.read_value(value); + } + + @MonitorRead + @Override + public final java.lang.Object read_abstract_interface() { + return impl.read_abstract_interface(); + } + + @MonitorRead + @Override + public final java.lang.Object read_abstract_interface(java.lang.Class clz) { + return impl.read_abstract_interface(clz); + } + // com.sun.corba.ee.impl.encoding.MarshalInputStream + + @MonitorRead + public final void consumeEndian() { + impl.consumeEndian(); + } + + public final int getPosition() { + return impl.getPosition(); + } + + // org.omg.CORBA.DataInputStream + + @MonitorRead + public final java.lang.Object read_Abstract () { + return impl.read_Abstract(); + } + + @MonitorRead + public final java.io.Serializable read_Value () { + return impl.read_Value(); + } + + @MonitorRead + public final void read_any_array (org.omg.CORBA.AnySeqHolder seq, int offset, int length) { + impl.read_any_array(seq, offset, length); + } + + @MonitorRead + public final void read_boolean_array (org.omg.CORBA.BooleanSeqHolder seq, int offset, int length) { + impl.read_boolean_array(seq, offset, length); + } + + @MonitorRead + public final void read_char_array (org.omg.CORBA.CharSeqHolder seq, int offset, int length) { + impl.read_char_array(seq, offset, length); + } + + @MonitorRead + public final void read_wchar_array (org.omg.CORBA.WCharSeqHolder seq, int offset, int length) { + impl.read_wchar_array(seq, offset, length); + } + + @MonitorRead + public final void read_octet_array (org.omg.CORBA.OctetSeqHolder seq, int offset, int length) { + impl.read_octet_array(seq, offset, length); + } + + @MonitorRead + public final void read_short_array (org.omg.CORBA.ShortSeqHolder seq, int offset, int length) { + impl.read_short_array(seq, offset, length); + } + + @MonitorRead + public final void read_ushort_array (org.omg.CORBA.UShortSeqHolder seq, int offset, int length) { + impl.read_ushort_array(seq, offset, length); + } + + @MonitorRead + public final void read_long_array (org.omg.CORBA.LongSeqHolder seq, int offset, int length) { + impl.read_long_array(seq, offset, length); + } + + @MonitorRead + public final void read_ulong_array (org.omg.CORBA.ULongSeqHolder seq, int offset, int length) { + impl.read_ulong_array(seq, offset, length); + } + + @MonitorRead + public final void read_ulonglong_array (org.omg.CORBA.ULongLongSeqHolder seq, int offset, int length) { + impl.read_ulonglong_array(seq, offset, length); + } + + @MonitorRead + public final void read_longlong_array (org.omg.CORBA.LongLongSeqHolder seq, int offset, int length) { + impl.read_longlong_array(seq, offset, length); + } + + @MonitorRead + public final void read_float_array (org.omg.CORBA.FloatSeqHolder seq, int offset, int length) { + impl.read_float_array(seq, offset, length); + } + + @MonitorRead + public final void read_double_array (org.omg.CORBA.DoubleSeqHolder seq, int offset, int length) { + impl.read_double_array(seq, offset, length); + } + + // org.omg.CORBA.portable.ValueBase + public final String[] _truncatable_ids() { + return impl._truncatable_ids(); + } + + // java.io.InputStream + @MonitorRead + @Override + public final int read(byte b[]) throws IOException { + return impl.read(b); + } + + @MonitorRead + @Override + public final int read(byte b[], int off, int len) throws IOException { + return impl.read(b, off, len); + } + + @MonitorRead + @Override + public final long skip(long n) throws IOException { + return impl.skip(n); + } + + @Override + public final int available() throws IOException { + return impl.available(); + } + + @MonitorRead + @Override + public void close() throws IOException { + impl.close(); + } + + @MonitorRead + @Override + public final void mark(int readlimit) { + impl.mark(readlimit); + } + + @MonitorRead + @Override + public final void reset() { + impl.reset(); + } + + @Override + public final boolean markSupported() { + return impl.markSupported(); + } + + // Needed by TCUtility + @MonitorRead + public final java.math.BigDecimal read_fixed(short digits, short scale) { + return impl.read_fixed(digits, scale); + } + + public final ByteOrder getByteOrder() { + return impl.getByteOrder(); + } + + public final int getBufferLength() { + return impl.getBufferLength(); + } + + protected final void setBufferLength(int value) { + impl.setBufferLength(value); + } + + protected final void setIndex(int value) { + impl.setIndex(value); + } + + public final void orb(org.omg.CORBA.ORB orb) { + impl.orb(orb); + } + + public final GIOPVersion getGIOPVersion() { + return impl.getGIOPVersion(); + } + + public final BufferManagerRead getBufferManager() { + return impl.getBufferManager(); + } + + /** + * Aligns the current position on the given octet boundary + * if there are enough bytes available to do so. Otherwise, + * it just returns. This is used for some (but not all) + * GIOP 1.2 message headers. + * @param octetBoundary alignment boundary. + */ + @MonitorRead + public void alignOnBoundary(int octetBoundary) { + impl.alignOnBoundary(octetBoundary); + } + + // Needed by request and reply messages for GIOP versions >= 1.2 only. + @MonitorRead + public void setHeaderPadding(boolean headerPadding) { + impl.setHeaderPadding(headerPadding); + } + + /** + * This must be called after determining the proper ORB version, + * and setting it on the stream's ORB instance. It can be called + * after reading the service contexts, since that is the only place + * we can get the ORB version info. + * + * Trying to unmarshal things requiring repository IDs before calling + * this will result in NullPtrExceptions. + */ + public void performORBVersionSpecificInit() { + // In the case of SystemExceptions, a stream is created + // with its default constructor (and thus no impl is set). + if (impl != null) { + impl.performORBVersionSpecificInit(); + } + } + + /** + * Resets any internal references to code set converters. + * This is useful for forcing the CDR stream to reacquire + * converters (probably from its subclasses) when state + * has changed. + */ + public void resetCodeSetConverters() { + impl.resetCodeSetConverters(); + } + + public void setMessageMediator(MessageMediator messageMediator) + { + this.messageMediator = messageMediator; + } + + public MessageMediator getMessageMediator() + { + return messageMediator; + } + + // ValueInputStream ----------------------------- + @MonitorRead + public void start_value() { + impl.start_value(); + } + + @MonitorRead + public void end_value() { + impl.end_value(); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStreamBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStreamBase.java new file mode 100644 index 000000000..758638788 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStreamBase.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.org.omg.SendingContext.CodeBase; + +/** + * Describes CDRInputStream delegates and provides some + * implementation. Non-default constructors are avoided in + * the delegation to separate instantiation from initialization, + * so we use init methods. + */ +abstract class CDRInputStreamBase extends java.io.InputStream +{ + protected CDRInputObject parent; + + public void setParent(CDRInputObject parent) { + this.parent = parent; + } + + abstract void init(org.omg.CORBA.ORB orb, + ByteBuffer byteBuffer, + int bufferSize, + ByteOrder byteOrder, + BufferManagerRead bufferManager); + + // org.omg.CORBA.portable.InputStream + public abstract boolean read_boolean(); + public abstract char read_char(); + public abstract char read_wchar(); + public abstract byte read_octet(); + public abstract short read_short(); + public abstract short read_ushort(); + public abstract int read_long(); + public abstract int read_ulong(); + public abstract long read_longlong(); + public abstract long read_ulonglong(); + public abstract float read_float(); + public abstract double read_double(); + public abstract String read_string(); + public abstract String read_wstring(); + public abstract void read_boolean_array(boolean[] value, int offset, int length); + public abstract void read_char_array(char[] value, int offset, int length); + public abstract void read_wchar_array(char[] value, int offset, int length); + public abstract void read_octet_array(byte[] value, int offset, int length); + public abstract void read_short_array(short[] value, int offset, int length); + public abstract void read_ushort_array(short[] value, int offset, int length); + public abstract void read_long_array(int[] value, int offset, int length); + public abstract void read_ulong_array(int[] value, int offset, int length); + public abstract void read_longlong_array(long[] value, int offset, int length); + public abstract void read_ulonglong_array(long[] value, int offset, int length); + public abstract void read_float_array(float[] value, int offset, int length); + public abstract void read_double_array(double[] value, int offset, int length); + public abstract org.omg.CORBA.Object read_Object(); + public abstract TypeCode read_TypeCode(); + public abstract Any read_any(); + @SuppressWarnings({"deprecation"}) + public abstract org.omg.CORBA.Principal read_Principal(); + public int read() throws java.io.IOException { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + public abstract java.math.BigDecimal read_fixed(); + public org.omg.CORBA.Context read_Context() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + public abstract org.omg.CORBA.Object read_Object(java.lang.Class clz); + + public abstract org.omg.CORBA.ORB orb(); + // org.omg.CORBA_2_3.portable.InputStream + public abstract java.io.Serializable read_value(); + public abstract java.io.Serializable read_value(java.lang.Class clz); + public abstract java.io.Serializable read_value(org.omg.CORBA.portable.BoxedValueHelper factory); + public abstract java.io.Serializable read_value(java.lang.String rep_id); + public abstract java.io.Serializable read_value(java.io.Serializable value); + public abstract java.lang.Object read_abstract_interface(); + + public abstract java.lang.Object read_abstract_interface(java.lang.Class clz); + // com.sun.corba.ee.impl.encoding.MarshalInputStream + public abstract void consumeEndian(); + + public abstract int getPosition(); + // org.omg.CORBA.DataInputStream + public abstract java.lang.Object read_Abstract (); + public abstract java.io.Serializable read_Value (); + public abstract void read_any_array (org.omg.CORBA.AnySeqHolder seq, int offset, int length); + public abstract void read_boolean_array (org.omg.CORBA.BooleanSeqHolder seq, int offset, int length); + public abstract void read_char_array (org.omg.CORBA.CharSeqHolder seq, int offset, int length); + public abstract void read_wchar_array (org.omg.CORBA.WCharSeqHolder seq, int offset, int length); + public abstract void read_octet_array (org.omg.CORBA.OctetSeqHolder seq, int offset, int length); + public abstract void read_short_array (org.omg.CORBA.ShortSeqHolder seq, int offset, int length); + public abstract void read_ushort_array (org.omg.CORBA.UShortSeqHolder seq, int offset, int length); + public abstract void read_long_array (org.omg.CORBA.LongSeqHolder seq, int offset, int length); + public abstract void read_ulong_array (org.omg.CORBA.ULongSeqHolder seq, int offset, int length); + public abstract void read_ulonglong_array (org.omg.CORBA.ULongLongSeqHolder seq, int offset, int length); + public abstract void read_longlong_array (org.omg.CORBA.LongLongSeqHolder seq, int offset, int length); + public abstract void read_float_array (org.omg.CORBA.FloatSeqHolder seq, int offset, int length); + + public abstract void read_double_array (org.omg.CORBA.DoubleSeqHolder seq, int offset, int length); + + // org.omg.CORBA.portable.ValueBase + public abstract String[] _truncatable_ids(); + + // java.io.InputStream + // REVISIT - should we make these throw UnsupportedOperationExceptions? + // Right now, they'll go up to the java.io versions! + // public abstract int read(byte b[]) throws IOException; +// public abstract int read(byte b[], int off, int len) throws IOException +// public abstract long skip(long n) throws IOException; +// public abstract int available() throws IOException; +// public abstract void close() throws IOException; + public abstract void mark(int readlimit); + + public abstract void reset(); + + // This should return false so that outside users (people using the JDK) + // don't have any guarantees that mark/reset will work in their + // custom marshaling code. This is necessary since they could do things + // like expect obj1a == obj1b in the following code: + // + // is.mark(10000); + // Object obj1a = is.readObject(); + // is.reset(); + // Object obj1b = is.readObject(); + // + public boolean markSupported() { return false; } + + // Needed by AnyImpl and ServiceContexts + public abstract CDRInputStreamBase dup(); + + // Needed by TCUtility + public abstract java.math.BigDecimal read_fixed(short digits, short scale); + + public abstract ByteOrder getByteOrder(); + + // Needed by request and reply messages for GIOP versions >= 1.2 only. + abstract void setHeaderPadding(boolean headerPadding); + + // Needed by IIOPInputStream and other subclasses + public abstract int getBufferLength(); + + public abstract void setBufferLength(int value); + + public abstract void setIndex(int value); + + public abstract void orb(org.omg.CORBA.ORB orb); + public abstract BufferManagerRead getBufferManager(); + + public abstract GIOPVersion getGIOPVersion(); + + abstract CodeBase getCodeBase(); + + abstract void alignOnBoundary(int octetBoundary); + + abstract void performORBVersionSpecificInit(); + + public abstract void resetCodeSetConverters(); + // ValueInputStream ------------------------- + public abstract void start_value(); + + public abstract void end_value(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_0.java new file mode 100644 index 000000000..d2915ba74 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_0.java @@ -0,0 +1,2181 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.corba.CORBAObjectImpl; +import com.sun.corba.ee.impl.corba.PrincipalImpl; +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.impl.misc.*; +import com.sun.corba.ee.impl.util.JDKBridge; +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.orb.ClassCodeBaseHandler; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.trace.CdrRead; +import com.sun.corba.ee.spi.trace.PrimitiveRead; +import com.sun.corba.ee.spi.transport.ByteBufferPool; +import com.sun.org.omg.SendingContext.CodeBase; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.*; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.portable.*; +import org.omg.CORBA_2_3.portable.InputStream; + +import javax.rmi.CORBA.EnumDesc; +import javax.rmi.CORBA.ProxyDesc; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.ValueHandler; +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.math.BigDecimal; +import java.net.MalformedURLException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.rmi.server.RMIClassLoader; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.Arrays; +import java.util.List; +import java.lang.Object; + +@CdrRead +@PrimitiveRead +public class CDRInputStream_1_0 extends CDRInputStreamBase + implements RestorableInputStream +{ + protected static final ORBUtilSystemException wrapper = ORBUtilSystemException.self; + private static final OMGSystemException omgWrapper = OMGSystemException.self; + private static final String K_READ_METHOD = "read"; + private static final int MAX_BLOCK_LENGTH = 0x7fffff00; + + protected BufferManagerRead bufferManagerRead; + protected ByteBuffer byteBuffer; + + protected ORB orb; + protected ValueHandler valueHandler = null; + + // Value cache + private CacheTable valueCache = null; + + // Repository ID cache + private CacheTable repositoryIdCache = null; + + // codebase cache + private CacheTable codebaseCache = null; + + // Current Class Stack (repository Ids of current class being read) + // private Stack currentStack = null; + + // Length of current chunk, or a large positive number if not in a chunk + protected int blockLength = MAX_BLOCK_LENGTH; + + // Read end flag (value nesting depth) + protected int end_flag = 0; + + // Beginning with the resolution to interop issue 3526 (4328?), + // only enclosing chunked valuetypes are taken into account + // when computing the nesting level. However, we still need + // the old computation around for interoperability with our + // older ORBs. + private int chunkedValueNestingLevel = 0; + + // Flag used to determine whether blocksize was zero + // private int checkForNullBlock = -1; + + // In block flag + // private boolean inBlock = false; + + // Indicates whether we are inside a value + // private boolean outerValueDone = true; + + // Int used by read_value(Serializable) that is set by this class + // before calling ValueFactory.read_value + protected int valueIndirection = 0; + + // Int set by readStringOrIndirection to communicate the actual + // offset of the string length field back to the caller + protected int stringIndirection = 0; + + // Flag indicating whether we are unmarshalling a chunked value + protected boolean isChunked = false; + + // Repository ID handlers + private RepositoryIdUtility repIdUtil; + private RepositoryIdStrings repIdStrs; + + // Code set converters (created when first needed) + private CodeSetConversion.BTCConverter charConverter; + private CodeSetConversion.BTCConverter wcharConverter; + + // RMI-IIOP stream format version 2 case in which we know + // that there is no more optional data available. If the + // Serializable's readObject method tries to read anything, + // we must throw a MARSHAL with the special minor code + // so that the ValueHandler can give the correct exception + // to readObject. The state is cleared when the ValueHandler + // calls end_value after the readObject method exits. + private boolean specialNoOptionalDataState = false; + + // IMPORTANT: Do not replace 'new String("")' with "", it may result + // in a Serialization bug. See http://bugs.java.com/view_bug.do?bug_id=4728756 for details + @SuppressWarnings("RedundantStringConstructorCall") + final String newEmptyString() { + return new String(""); + } + + // Template method + public CDRInputStreamBase dup() + { + CDRInputStreamBase result = null ; + + try { + result = this.getClass().newInstance(); + } catch (Exception e) { + throw wrapper.couldNotDuplicateCdrInputStream( e ) ; + } + result.init(this.orb, + byteBuffer, + byteBuffer.limit(), + byteBuffer.order(), + this.bufferManagerRead); + + return result; + } + + @Override + void init(org.omg.CORBA.ORB orb, ByteBuffer byteBuffer, int bufferSize, ByteOrder byteOrder, BufferManagerRead bufferManager) { + this.orb = (ORB)orb; + this.bufferManagerRead = bufferManager; + this.byteBuffer = byteBuffer; + this.byteBuffer.position(0); + this.byteBuffer.order(byteOrder); + this.byteBuffer.limit(bufferSize); + this.markAndResetHandler = bufferManagerRead.getMarkAndResetHandler(); + } + + // See description in CDRInputStream + void performORBVersionSpecificInit() { + createRepositoryIdHandlers(); + } + + private void createRepositoryIdHandlers() + { + repIdUtil = RepositoryIdFactory.getRepIdUtility(); + repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); + } + + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_0; + } + + // Called by Request and Reply message. Valid for GIOP versions >= 1.2 only. + // Illegal for GIOP versions < 1.2. + void setHeaderPadding(boolean headerPadding) { + throw wrapper.giopVersionError(); + } + + protected final int computeAlignment(int index, int align) { + if (align > 1) { + int incr = index & (align - 1); + if (incr != 0) { + return align - incr; + } + } + + return 0; + } + + @InfoMethod + private void notChunked() { } + + @CdrRead + protected void checkBlockLength(int align, int dataSize) { + // Since chunks can end at arbitrary points (though not within + // primitive CDR types, arrays of primitives, strings, wstrings, + // or indirections), + // we must check here for termination of the current chunk. + if (!isChunked) { + notChunked() ; + return; + } + + // RMI-IIOP stream format version 2 case in which we know + // that there is no more optional data available. If the + // Serializable's readObject method tries to read anything, + // we must throw a MARSHAL exception with the special minor code + // so that the ValueHandler can give the correct exception + // to readObject. The state is cleared when the ValueHandler + // calls end_value after the readObject method exits. + if (specialNoOptionalDataState) { + throw omgWrapper.rmiiiopOptionalDataIncompatible1() ; + } + + boolean checkForEndTag = false; + + // Are we at the end of the current chunk? If so, + // try to interpret the next long as a chunk length. + // (It has to be either a chunk length, end tag, + // or valuetag.) + // + // If it isn't a chunk length, blockLength will + // remain set to maxBlockLength. + if (blockLength == get_offset()) { + + blockLength = MAX_BLOCK_LENGTH; + start_block(); + + // What's next is either a valuetag or + // an end tag. If it's a valuetag, we're + // probably being called as part of the process + // to read the valuetag. If it's an end tag, + // then there isn't enough data left in + // this valuetype to read! + if (blockLength == MAX_BLOCK_LENGTH) { + checkForEndTag = true; + } + + } else if (blockLength < get_offset()) { + // Are we already past the end of the current chunk? + // This is always an error. + throw wrapper.chunkOverflow() ; + } + + // If what's next on the wire isn't a chunk length or + // what we want to read (which can't be split across chunks) + // won't fit in the current chunk, throw this exception. + // This probably means that we're in an RMI-IIOP + // Serializable's readObject method or a custom marshaled + // IDL type is reading too much/in an incorrect order + int requiredNumBytes = computeAlignment(byteBuffer.position(), align) + dataSize; + + if (blockLength != MAX_BLOCK_LENGTH && + blockLength < get_offset() + requiredNumBytes) { + throw omgWrapper.rmiiiopOptionalDataIncompatible2() ; + } + + // IMPORTANT - read_long() will advance the position of the ByteBuffer. + // Hence, in the logic below, we need to reset the position + // back to its original location. + if (checkForEndTag) { + int nextLong = read_long(); + byteBuffer.position(byteBuffer.position() - 4); + + // It was an end tag, so there wasn't enough data + // left in the valuetype's encoding on the wire + // to read what we wanted + if (nextLong < 0) { + throw omgWrapper.rmiiiopOptionalDataIncompatible3(); + } + } + } + + @CdrRead + protected void alignAndCheck(int align, int n) { + checkBlockLength(align, n); + + // WARNING: Must compute real alignment after calling + // checkBlockLength since it may move the position + int alignResult = computeAlignment(byteBuffer.position(), align); + byteBuffer.position(byteBuffer.position() + alignResult); + + if (byteBuffer.position() + n > byteBuffer.limit()) { + grow(align, n); + } + } + + // + // This can be overridden.... + @CdrRead + protected void grow(int align, int n) { + byteBuffer = bufferManagerRead.underflow(byteBuffer); + + } + + // + // Marshal primitives. + // + + public final void consumeEndian() { + ByteOrder byteOrder = read_boolean() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; + byteBuffer.order(byteOrder); + } + + public final boolean read_boolean() { + return (read_octet() != 0); + } + + public final char read_char() { + alignAndCheck(1, 1); + + return getConvertedChars(1, getCharConverter())[0]; + } + + @CdrRead + public char read_wchar() { + // Don't allow transmission of wchar/wstring data with foreign ORBs since it's against the spec. + if (ORBUtility.isForeignORB(orb)) { + throw wrapper.wcharDataInGiop10() ; + } + + // If we're talking to one of our legacy ORBs, do what they did: + return (char) byteBuffer.getShort(); + } + + @CdrRead + public final byte read_octet() { + alignAndCheck(1, 1); + return byteBuffer.get(); + } + + @CdrRead + public final short read_short() { + alignAndCheck(2, 2); + return byteBuffer.getShort(); + } + + public final short read_ushort() { + return read_short(); + } + + @CdrRead + public final int read_long() { + alignAndCheck(4, 4); + return byteBuffer.getInt(); + } + + public final int read_ulong() { + return read_long(); + } + + @CdrRead + public final long read_longlong() { + alignAndCheck(8, 8); + return byteBuffer.getLong(); + } + + public final long read_ulonglong() { + return read_longlong(); + } + + public final float read_float() { + return Float.intBitsToFloat(read_long()); + } + + public final double read_double() { + return Double.longBitsToDouble(read_longlong()); + } + + protected final void checkForNegativeLength(int length) { + if (length < 0) { + throw wrapper.negativeStringLength(length); + } + } + + // Note that this has the side effect of setting the value of stringIndirection. + @CdrRead + protected final String readStringOrIndirection(boolean allowIndirection) { + String result = "" ; + + int len = read_long(); + + // + // Check for indirection + // + if (allowIndirection) { + if (len == 0xffffffff) { + return null; + } else { + stringIndirection = get_offset() - 4; + } + } + + checkForNegativeLength(len); + + result = internalReadString(len); + + return result ; + } + + @CdrRead + private String internalReadString(int len) { + // Workaround for ORBs which send string lengths of + // zero to mean empty string. + // + if (len == 0) { + return newEmptyString(); + } + + char[] result = getConvertedChars(len - 1, getCharConverter()); + + // Skip over the 1 byte null + read_octet(); + + return new String(result, 0, getCharConverter().getNumChars()); + } + + public final String read_string() { + return readStringOrIndirection(false); + } + + @CdrRead + public String read_wstring() { + // Don't allow transmission of wchar/wstring data with + // foreign ORBs since it's against the spec. + if (ORBUtility.isForeignORB(orb)) { + throw wrapper.wcharDataInGiop10(); + } + + int len = read_long(); + + // + // Workaround for ORBs which send string lengths of + // zero to mean empty string. + // + if (len == 0) { + return newEmptyString(); + } + + checkForNegativeLength(len); + + len--; + char[] c = new char[len]; + + for (int i = 0; i < len; i++) { + c[i] = read_wchar(); + } + + // skip the two null terminator bytes + read_wchar(); + + return new String(c); + } + + @CdrRead + public final void read_octet_array(byte[] buffer, int offset, int length) { + if ( buffer == null ) { + throw wrapper.nullParam(); + } + + if (length == 0) { + return; + } + + alignAndCheck(1, 1); + + int numWritten = 0; + while (numWritten < length) { + if (!byteBuffer.hasRemaining()) grow(1, 1); + + int count = Math.min(length - numWritten, byteBuffer.remaining()); + byteBuffer.get(buffer, numWritten + offset, count); + numWritten += count; + } + } + + @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.Principal read_Principal() { + int len = read_long(); + byte[] pvalue = new byte[len]; + read_octet_array(pvalue,0,len); + + org.omg.CORBA.Principal p = new PrincipalImpl(); + p.name(pvalue); + return p; + } + + @CdrRead + public TypeCode read_TypeCode() { + TypeCodeImpl tc = new TypeCodeImpl(orb); + tc.read_value(parent); + return tc ; + } + + @CdrRead + public Any read_any() { + Any any = null ; + + any = orb.create_any(); + TypeCodeImpl tc = new TypeCodeImpl(orb); + + // read off the typecode + + // REVISIT We could avoid this try-catch if we could peek the typecode + // kind off this stream and see if it is a tk_value. Looking at the + // code we know that for tk_value the Any.read_value() below + // ignores the tc argument anyway (except for the kind field). + // But still we would need to make sure that the whole typecode, + // including encapsulations, is read off. + try { + tc.read_value(parent); + } catch (MARSHAL ex) { + if (tc.kind().value() != TCKind._tk_value) { + throw ex; + } + // We can be sure that the whole typecode encapsulation has been + // read off. + } + // read off the value of the any + any.read_value(parent, tc); + + return any; + } + + @CdrRead + public org.omg.CORBA.Object read_Object() { + return read_Object(null); + } + + @InfoMethod + private void nullIOR() { } + + @InfoMethod + private void className( String name ) { } + + @InfoMethod + private void stubFactory( PresentationManager.StubFactory fact ) { } + + // ------------ RMI related methods -------------------------- + + // IDL to Java ptc-00-01-08 1.21.4.1 + // + // The clz argument to read_Object can be either a stub + // Class or the "Class object for the RMI/IDL interface type + // that is statically expected." + // This functions as follows: + // 1. If clz==null, just use the repository ID from the stub + // 2. If clz is a stub class, just use it as a static factory. + // clz is a stub class iff StubAdapter.isStubClass( clz ). + // In addition, clz is a IDL stub class iff + // IDLEntity.class.isAssignableFrom( clz ). + // 3. If clz is an interface, use it to create the appropriate + // stub factory. + @CdrRead + public org.omg.CORBA.Object read_Object(Class clz) + { + // In any case, we must first read the IOR. + IOR ior = IORFactories.makeIOR( orb, (InputStream)parent) ; + if (ior.isNil()) { + nullIOR() ; + return null; + } + + PresentationManager.StubFactoryFactory sff = ORB.getStubFactoryFactory() ; + String codeBase = ior.getProfile().getCodebase() ; + PresentationManager.StubFactory stubFactory = null ; + + if (clz == null) { + RepositoryId rid = RepositoryId.cache.getId( ior.getTypeId() ) ; + String className = rid.getClassName() ; + className( className ) ; + boolean isIDLInterface = rid.isIDLType() ; + + if (className == null || className.equals( "" )) { + stubFactory = null; + } else { + try { + stubFactory = sff.createStubFactory(className, + isIDLInterface, codeBase, (Class) null, + (ClassLoader) null); + } catch (Exception exc) { + stubFactory = null; + } + } + stubFactory( stubFactory ) ; + } else if (StubAdapter.isStubClass( clz )) { + stubFactory = PresentationDefaults.makeStaticStubFactory( + clz ) ; + stubFactory( stubFactory ) ; + } else { + // clz is an interface class + boolean isIDL = ClassInfoCache.get( clz ).isAIDLEntity(clz) ; + + stubFactory = sff.createStubFactory( clz.getName(), + isIDL, codeBase, clz, clz.getClassLoader() ) ; + stubFactory( stubFactory ) ; + } + + return internalIORToObject( ior, stubFactory, orb ); + } + + /* + * This is used as a general utility (e.g., the PortableInterceptor + * implementation uses it. If stubFactory is null, the ior's + * IIOPProfile must support getServant. + */ + @CdrRead + public static org.omg.CORBA.Object internalIORToObject( + IOR ior, PresentationManager.StubFactory stubFactory, ORB orb) + { + java.lang.Object servant = ior.getProfile().getServant() ; + if (servant != null ) { + if (servant instanceof Tie) { + String codebase = ior.getProfile().getCodebase(); + org.omg.CORBA.Object objref = (org.omg.CORBA.Object) + Utility.loadStub( (Tie)servant, stubFactory, codebase, + false); + + // If we managed to load a stub, return it, otherwise we + // must fail... + if (objref != null) { + return objref; + } else { + throw wrapper.readObjectException() ; + } + } else if (servant instanceof org.omg.CORBA.Object) { + if (!(servant instanceof + org.omg.CORBA.portable.InvokeHandler)) { + return (org.omg.CORBA.Object)servant; + } + } else { + throw wrapper.badServantReadObject(); + } + } + + ClientDelegate del = ORBUtility.makeClientDelegate( ior ) ; + + org.omg.CORBA.Object objref = null ; + if (stubFactory == null) { + objref = new CORBAObjectImpl(); + } else { + try { + objref = stubFactory.makeStub() ; + } catch (Throwable e) { + wrapper.stubCreateError( e ) ; + + if (e instanceof ThreadDeath) { + throw (ThreadDeath) e; + } + + // Return the "default" stub... + objref = new CORBAObjectImpl() ; + } + } + + StubAdapter.setDelegate( objref, del ) ; + return objref; + } + + @CdrRead + public java.lang.Object read_abstract_interface() + { + return read_abstract_interface(null); + } + + public java.lang.Object read_abstract_interface(java.lang.Class clz) + { + boolean object = read_boolean(); + + if (object) { + return read_Object(clz); + } else { + return read_value(); + } + } + + @CdrRead + public Serializable read_value() + { + return read_value((Class)null); + } + + @InfoMethod + private void indirectionValue( int indir ) { } + + @CdrRead + private Serializable handleIndirection() { + int indirection = read_long() + get_offset() - 4; + + indirectionValue( indirection ) ; + + if (valueCache != null && valueCache.containsVal(indirection)) { + + java.io.Serializable cachedValue + = (java.io.Serializable)valueCache.getKey(indirection); + return cachedValue; + } else { + // In RMI-IIOP the ValueHandler will recognize this + // exception and use the provided indirection value + // to lookup a possible indirection to an object + // currently on the deserialization stack. + throw new IndirectionException(indirection); + } + } + + private String readRepositoryIds(int valueTag, + Class expectedType, + ClassInfoCache.ClassInfo cinfo, + String expectedTypeRepId) { + return readRepositoryIds(valueTag, expectedType, + cinfo, expectedTypeRepId, null); + } + + /** + * Examines the valuetag to see how many (if any) repository IDs + * are present on the wire. If no repository ID information + * is on the wire but the expectedType or expectedTypeRepId + * is known, it will return one of those (favoring the + * expectedType's repId). Failing that, it uses the supplied + * BoxedValueHelper to obtain the repository ID, as a last resort. + */ + private String readRepositoryIds(int valueTag, + Class expectedType, + ClassInfoCache.ClassInfo cinfo, + String expectedTypeRepId, + BoxedValueHelper factory) { + switch(repIdUtil.getTypeInfo(valueTag)) { + case RepositoryIdUtility.NO_TYPE_INFO : + // Throw an exception if we have no repository ID info and + // no expectedType to work with. Otherwise, how would we + // know what to unmarshal? + if (expectedType == null) { + if (expectedTypeRepId != null) { + return expectedTypeRepId; + } else if (factory != null) { + return factory.get_id(); + } else { + throw wrapper.expectedTypeNullAndNoRepId( ) ; + } + } + return repIdStrs.createForAnyType(expectedType,cinfo); + case RepositoryIdUtility.SINGLE_REP_TYPE_INFO : + return read_repositoryId(); + case RepositoryIdUtility.PARTIAL_LIST_TYPE_INFO : + return read_repositoryIds(); + default: + throw wrapper.badValueTag( Integer.toHexString(valueTag) ) ; + } + } + + @CdrRead + private Object readRMIIIOPValueType( int indirection, + Class valueClass, String repositoryIDString ) { + + try { + if (valueHandler == null) { + valueHandler = ORBUtility.createValueHandler(); + } + + return valueHandler.readValue(parent, indirection, valueClass, + repositoryIDString, getCodeBase()); + } catch(SystemException sysEx) { + // Just rethrow any CORBA system exceptions + // that come out of the ValueHandler + throw sysEx; + } catch(Exception ex) { + throw wrapper.valuehandlerReadException( ex ) ; + } catch(Error e) { + throw wrapper.valuehandlerReadError( e ) ; + } + } + + @InfoMethod + private void repositoryIdString( String str ) { } + + @InfoMethod + private void valueClass( Class cls ) { } + + @InfoMethod + private void noProxyInterfaces() { } + + @CdrRead + public Serializable read_value(Class expectedType) { + Object value = null ; + int vType = readValueTag(); + if (vType == 0) { + return null; + } + + if (vType == 0xffffffff) { + value = handleIndirection(); + } else { + ClassInfoCache.ClassInfo cinfo = null ; + if (expectedType != null) { + cinfo = ClassInfoCache.get(expectedType); + } + + int indirection = get_offset() - 4; + + // Need to save this special marker variable + // to restore its value during recursion + boolean saveIsChunked = isChunked; + isChunked = repIdUtil.isChunkedEncoding(vType); + + String codebase_URL = null; + if (repIdUtil.isCodeBasePresent(vType)) { + codebase_URL = read_codebase_URL(); + } + + // Read repository id(s) + String repositoryIDString = readRepositoryIds(vType, expectedType, + cinfo, null); + repositoryIdString( repositoryIDString ) ; + + // If isChunked was determined to be true based + // on the valuetag, this will read a chunk length + start_block(); + + // Remember that end_flag keeps track of all nested + // valuetypes and is used for older ORBs + end_flag--; + if (isChunked) { + chunkedValueNestingLevel--; + } + + if (repositoryIDString.equals(repIdStrs.getWStringValueRepId())) { + value = read_wstring(); + } else if (repositoryIDString.equals(repIdStrs.getClassDescValueRepId())) { + value = readClass(); + } else { + Class valueClass = expectedType; + + // By this point, either the expectedType or repositoryIDString + // is guaranteed to be non-null. + if (valueClass == null || !repositoryIDString.equals(repIdStrs.createForAnyType(expectedType,cinfo))) { + + valueClass = getClassFromString(repositoryIDString, codebase_URL, expectedType); + cinfo = ClassInfoCache.get( valueClass ) ; + } + + valueClass( valueClass ) ; + + if (valueClass == null) { + // No point attempting to use value handler below, since the + // class information is not available. + // Fix for issue 1828: pass the class name for a better log + // message. + RepositoryIdInterface repositoryID = repIdStrs.getFromString(repositoryIDString); + + throw wrapper.couldNotFindClass(repositoryID.getClassName()) ; + } + + if (cinfo.isEnum()) { + final Class enumClass = ClassInfoCache.getEnumClass( cinfo, + valueClass ) ; + String enumValue = read_string() ; + value = Enum.valueOf( enumClass, enumValue ) ; + } else if (valueClass != null && cinfo.isAIDLEntity(valueClass)) { + value = readIDLValue(indirection, repositoryIDString, + valueClass, cinfo, codebase_URL); + } else { + value = readRMIIIOPValueType( indirection, + valueClass, repositoryIDString ) ; + } + } + + // Skip any remaining chunks until we get to + // an end tag or a valuetag. If we see a valuetag, + // that means there was another valuetype in the sender's + // version of this class that we need to skip over. + handleEndOfValue(); + + // Read and process the end tag if we're chunking. + // Assumes that we're at the position of the end tag + // (handleEndOfValue should assure this) + readEndTag(); + + // Cache the valuetype that we read + if (valueCache == null) { + valueCache = new CacheTable("Input valueCache", orb, + false); + } + valueCache.put(value, indirection); + + // Allow for possible continuation chunk. + // If we're a nested valuetype inside of a chunked + // valuetype, and that enclosing valuetype has + // more data to write, it will need to have this + // new chunk begin after we wrote our end tag. + isChunked = saveIsChunked; + start_block(); + } + + // Convert an EnumDesc into the enum instance it represents + if (value.getClass()==EnumDesc.class) { + EnumDesc desc = EnumDesc.class.cast( value ) ; + + Class cls = null ; + try { + cls = JDKBridge.loadClass( desc.className, null, null ) ; + } catch (ClassNotFoundException cnfe) { + throw wrapper.enumClassNotFound( cnfe, desc.className ) ; + } + + // Issue 11681: deal with enum with abstract methods. + Class current = cls ; + while (current != null) { + if (current.isEnum()) { + break ; + } + current = current.getSuperclass() ; + } + + if (current != null) { + value = Enum.valueOf( current, desc.value ) ; + } else { + throw wrapper.couldNotUnmarshalEnum( desc.className, + desc.value ) ; + } + } + + // Convert ProxyDesc into the proxy instance it represents + if (value.getClass()==ProxyDesc.class) { + ProxyDesc desc = ProxyDesc.class.cast( value ) ; + int numberOfInterfaces = desc.interfaces.length; + + // Write code if the number is Zero. Unusual case + if (numberOfInterfaces==0) { + noProxyInterfaces() ; + return null; + } + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + RMIClassLoader.loadProxyClass( desc.codebase, desc.interfaces, + value.getClass().getClassLoader()) ; + } catch (ClassNotFoundException cnfe) { + throw wrapper.proxyClassNotFound( cnfe, + getInterfacesList(desc.interfaces)) ; + } catch (MalformedURLException mue) { + throw wrapper.malformedProxyUrl( mue, + getInterfacesList(desc.interfaces), desc.codebase) ; + } + + Class[] list = new Class[desc.interfaces.length]; + for(int i=0; i < numberOfInterfaces; ++i) { + try { + list[i] = JDKBridge.loadClass(desc.interfaces[i], + desc.codebase, cl); + } catch (ClassNotFoundException cnfe) { + throw wrapper.proxyClassNotFound(cnfe, desc.interfaces[i]); + } + } + + try { + value = Proxy.newProxyInstance(cl, list, desc.handler); + } catch (IllegalArgumentException iage) { + throw wrapper.proxyWithIllegalArgs(iage); + } catch (NullPointerException npe) { + throw wrapper.emptyProxyInterfaceList(npe); + } + } + + return (java.io.Serializable)value; + } + + private List getInterfacesList(String [] interfaces) { + return Arrays.asList(interfaces); + } + + @CdrRead + @SuppressWarnings("deprecation") + public Serializable read_value(BoxedValueHelper factory) { + + // Read value tag + int vType = readValueTag(); + + if (vType == 0) { + return null; + } else if (vType == 0xffffffff) { // Indirection tag + int indirection = read_long() + get_offset() - 4; + if (valueCache != null && valueCache.containsVal(indirection)) { + Serializable cachedValue = + (Serializable)valueCache.getKey(indirection); + return cachedValue; + } else { + throw new IndirectionException(indirection); + } + } else { + int indirection = get_offset() - 4; + + boolean saveIsChunked = isChunked; + isChunked = repIdUtil.isChunkedEncoding(vType); + + java.lang.Object value = null; + + String codebase_URL = null; + if (repIdUtil.isCodeBasePresent(vType)){ + codebase_URL = read_codebase_URL(); + } + + // Read repository id + String repositoryIDString + = readRepositoryIds(vType, null, null, null, factory); + + // Compare rep. ids to see if we should use passed helper + if (!repositoryIDString.equals(factory.get_id())) { + factory = Utility.getHelper(null, codebase_URL, repositoryIDString); + } + + start_block(); + end_flag--; + if (isChunked) { + chunkedValueNestingLevel--; + } + + if (factory instanceof com.sun.org.omg.CORBA.portable.ValueHelper) { + value = readIDLValueWithHelper( + (com.sun.org.omg.CORBA.portable.ValueHelper)factory, indirection); + } else { + valueIndirection = indirection; // for callback + value = factory.read_value(parent); + } + + handleEndOfValue(); + readEndTag(); + + // Put into valueCache + if (valueCache == null) { + valueCache = new CacheTable("Input valueCache", orb, false); + } + valueCache.put(value, indirection); + + // allow for possible continuation chunk + isChunked = saveIsChunked; + start_block(); + + return (java.io.Serializable)value; + } + } + + @SuppressWarnings({"deprecation"}) + private boolean isCustomType(@SuppressWarnings("deprecation") com.sun.org.omg.CORBA.portable.ValueHelper helper) { + try{ + TypeCode tc = helper.get_type(); + int kind = tc.kind().value(); + if (kind == TCKind._tk_value) { + return (tc.type_modifier() == org.omg.CORBA.VM_CUSTOM.value); + } + } catch(BadKind ex) { + throw wrapper.badKind(ex) ; + } + + return false; + } + + // This method is actually called indirectly by + // read_value(String repositoryId). + // Therefore, it is not a truly independent read call that handles + // header information itself. + @CdrRead + public java.io.Serializable read_value(java.io.Serializable value) { + + // Put into valueCache using valueIndirection + if (valueCache == null) { + valueCache = new CacheTable("Input valueCache", orb, false); + } + valueCache.put(value, valueIndirection); + + if (value instanceof StreamableValue) { + ((StreamableValue) value)._read(parent); + } else if (value instanceof CustomValue) { + ((CustomValue) value).unmarshal(parent); + } + + return value; + } + + @CdrRead + public java.io.Serializable read_value(java.lang.String repositoryId) { + + // if (inBlock) + // end_block(); + + // Read value tag + int vType = readValueTag(); + + if (vType == 0) { + return null; + } else if (vType == 0xffffffff) { // Indirection tag + int indirection = read_long() + get_offset() - 4; + if (valueCache != null && valueCache.containsVal(indirection)) + { + java.io.Serializable cachedValue = + (java.io.Serializable)valueCache.getKey(indirection); + return cachedValue; + } + else { + throw new IndirectionException(indirection); + } + } else { + int indirection = get_offset() - 4; + + // end_block(); + + boolean saveIsChunked = isChunked; + isChunked = repIdUtil.isChunkedEncoding(vType); + + java.lang.Object value = null; + + String codebase_URL = null; + if (repIdUtil.isCodeBasePresent(vType)){ + codebase_URL = read_codebase_URL(); + } + + // Read repository id + String repositoryIDString + = readRepositoryIds(vType, null, null, repositoryId); + + ValueFactory factory = + Utility.getFactory(null, codebase_URL, orb, repositoryIDString); + + start_block(); + end_flag--; + if (isChunked) { + chunkedValueNestingLevel--; + } + + valueIndirection = indirection; // for callback + value = factory.read_value(parent); + + handleEndOfValue(); + readEndTag(); + + // Put into valueCache + if (valueCache == null) { + valueCache = new CacheTable("Input valueCache", orb, false); + } + valueCache.put(value, indirection); + + // allow for possible continuation chunk + isChunked = saveIsChunked; + start_block(); + + return (java.io.Serializable)value; + } + } + + @InfoMethod + private void readClassCodebases( String codebases, String repoId ) { } + + @CdrRead + private Class readClass() { + + String codebases, classRepId; + + if (orb == null || + ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) || + ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) { + + codebases = (String)read_value(java.lang.String.class); + classRepId = (String)read_value(java.lang.String.class); + } else { + // Pre-Merlin/J2EE 1.3 ORBs wrote the repository ID + // and codebase strings in the wrong order. + classRepId = (String)read_value(java.lang.String.class); + codebases = (String)read_value(java.lang.String.class); + } + + readClassCodebases( codebases, classRepId ) ; + + Class cl = null; + + RepositoryIdInterface repositoryID + = repIdStrs.getFromString(classRepId); + + try { + cl = repositoryID.getClassFromType(codebases); + } catch(ClassNotFoundException cnfe) { + throw wrapper.cnfeReadClass( cnfe, repositoryID.getClassName() ) ; + } catch(MalformedURLException me) { + throw wrapper.malformedUrl( + me, repositoryID.getClassName(), codebases ) ; + } + + return cl; + } + + @SuppressWarnings({"deprecation"}) + @CdrRead + private java.lang.Object readIDLValueWithHelper( + com.sun.org.omg.CORBA.portable.ValueHelper helper, int indirection) + { + // look for two-argument static read method + Method readMethod; + try { + readMethod = helper.getClass().getDeclaredMethod(K_READ_METHOD, + org.omg.CORBA.portable.InputStream.class, helper.get_class()); + } + catch(NoSuchMethodException nsme) { // must be boxed value helper + java.lang.Object result = helper.read_value(parent); + return result; + } + + // found two-argument read method, so must be non-boxed value... + // ...create a blank instance + java.lang.Object val = null; + try { + val = helper.get_class().newInstance(); + } catch(java.lang.InstantiationException ie) { + throw wrapper.couldNotInstantiateHelper( ie, + helper.get_class() ) ; + } catch(IllegalAccessException iae){ + // Value's constructor is protected or private + // + // So, use the helper to read the value. + // + // NOTE : This means that in this particular case a recursive ref. + // would fail. + return helper.read_value(parent); + } + + // add blank instance to cache table + if (valueCache == null) { + valueCache = new CacheTable("Input valueCache", orb, false); + } + valueCache.put(val, indirection); + + // if custom type, call unmarshal method + if (val instanceof CustomMarshal && isCustomType(helper)) { + ((CustomMarshal)val).unmarshal(parent); + return val; + } + + // call two-argument read method using reflection + try { + readMethod.invoke(helper, parent, val ); + return val; + } catch(IllegalAccessException iae2) { + throw wrapper.couldNotInvokeHelperReadMethod( iae2, + helper.get_class() ) ; + } catch(InvocationTargetException ite){ + throw wrapper.couldNotInvokeHelperReadMethod( ite, + helper.get_class() ) ; + } + } + + @CdrRead + private java.lang.Object readBoxedIDLEntity(Class clazz, String codebase) + { + Class cls = null ; + + try { + ClassLoader clazzLoader = clazz.getClassLoader(); + + cls = Utility.loadClassForClass(clazz.getName()+"Helper", codebase, + clazzLoader, clazz, clazzLoader); + final Class helperClass = cls ; + + // getDeclaredMethod requires RuntimePermission + // accessDeclaredMembers if a different class loader is used + // (even though the javadoc says otherwise) + Method readMethod = null; + try { + readMethod = AccessController.doPrivileged( + new PrivilegedExceptionAction() { + @SuppressWarnings("unchecked") + public Method run() throws NoSuchMethodException { + return helperClass.getDeclaredMethod(K_READ_METHOD, + org.omg.CORBA.portable.InputStream.class ) ; + } + } + ); + } catch (PrivilegedActionException pae) { + // this gets caught below + throw (NoSuchMethodException)pae.getException(); + } + + return readMethod.invoke(null, parent); + } catch (ClassNotFoundException cnfe) { + throw wrapper.couldNotInvokeHelperReadMethod( cnfe, cls ) ; + } catch(NoSuchMethodException nsme) { + throw wrapper.couldNotInvokeHelperReadMethod( nsme, cls ) ; + } catch(IllegalAccessException iae) { + throw wrapper.couldNotInvokeHelperReadMethod( iae, cls ) ; + } catch(InvocationTargetException ite) { + throw wrapper.couldNotInvokeHelperReadMethod( ite, cls ) ; + } + } + + @CdrRead + @SuppressWarnings({"deprecation", "deprecation"}) + private java.lang.Object readIDLValue(int indirection, String repId, + Class clazz, ClassInfoCache.ClassInfo cinfo, String codebase) + { + ValueFactory factory ; + + // Always try to find a ValueFactory first, as required by the spec. + // There are some complications here in the IDL 3.0 mapping + // (see 1.13.8), but basically we must always be able to override the + // DefaultFactory or Helper mappings that are also used. This appears + // to be the case even in the boxed value cases. The original code + // only did the lookup in the case of class implementing either + // StreamableValue or CustomValue, but abstract valuetypes only + // implement ValueBase, and really require the use of the repId to + // find a factory (including the DefaultFactory). + try { + // use new-style OBV support (factory object) + factory = Utility.getFactory(clazz, codebase, orb, repId); + } catch (MARSHAL marshal) { + wrapper.marshalErrorInReadIDLValue( marshal ) ; + + // Could not get a factory, so try alternatives + if (!cinfo.isAStreamableValue(clazz) && + !cinfo.isACustomValue(clazz) && cinfo.isAValueBase(clazz)) { + + // use old-style OBV support (helper object) + BoxedValueHelper helper = Utility.getHelper(clazz, codebase, + repId); + if (helper instanceof com.sun.org.omg.CORBA.portable.ValueHelper) { + return readIDLValueWithHelper( + (com.sun.org.omg.CORBA.portable.ValueHelper) helper, + indirection); + } else { + return helper.read_value(parent); + } + } else { + // must be a boxed IDLEntity, so make a reflective call to the + // helper's static read method... + return readBoxedIDLEntity(clazz, codebase); + } + } + + // If there was no error in getting the factory, use it. + valueIndirection = indirection; // for callback + return factory.read_value(parent); + } + + @InfoMethod + private void endTag( int endTag ) { } + + @InfoMethod + private void chunkedNestingLevel( int nl ) { } + + @InfoMethod + private void endFlag( int value ) { } + + /** + * End tags are only written for chunked valuetypes. + * + * Before Merlin, our ORBs wrote end tags which took into account + * all enclosing valuetypes. This was changed by an interop resolution + * (see details around chunkedValueNestingLevel) to only include + * enclosing chunked types. + * + * ORB versioning and end tag compaction are handled here. + */ + @CdrRead + private void readEndTag() { + if (isChunked) { + // Read the end tag + int anEndTag = read_long(); + endTag( anEndTag ) ; + + // End tags should always be negative, and the outermost + // enclosing chunked valuetype should have a -1 end tag. + // + // handleEndOfValue should have assured that we were + // at the end tag position! + if (anEndTag >= 0) { + throw wrapper.positiveEndTag( anEndTag, get_offset() - 4 ) ; + } + + // If the ORB is null, or if we're sure we're talking to + // a foreign ORB, Merlin, or something more recent, we + // use the updated end tag computation, and are more strenuous + // about the values. + if (orb == null || + ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) || + ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) { + + // If the end tag we read was less than what we were expecting, + // then the sender must think it's sent more enclosing + // chunked valuetypes than we have. Throw an exception. + if (anEndTag < chunkedValueNestingLevel) { + throw wrapper.unexpectedEnclosingValuetype( anEndTag, chunkedValueNestingLevel ); + } + + // If the end tag is bigger than what we expected, but + // still negative, then the sender has done some end tag + // compaction. We back up the stream 4 bytes so that the + // next time readEndTag is called, it will get down here + // again. Even with fragmentation, we'll always be able + // to do this. + if (anEndTag != chunkedValueNestingLevel) { + byteBuffer.position(byteBuffer.position() - 4); + } + } else { + // When talking to Kestrel (JDK 1.3) or Ladybird (JDK 1.3.1), we use our old + // end tag rules and are less strict. If the end tag + // isn't what we expected, we back up, assuming + // compaction. + if (anEndTag != end_flag) { + byteBuffer.position(byteBuffer.position() - 4); + } + } + + // This only keeps track of the enclosing chunked + // valuetypes + chunkedValueNestingLevel++; + chunkedNestingLevel( chunkedValueNestingLevel ) ; + } + + // This keeps track of all enclosing valuetypes + end_flag++; + endFlag( end_flag ) ; + } + + protected int get_offset() { + return byteBuffer.position(); + } + + @InfoMethod + private void unreadLastLong() { } + + @CdrRead + private void start_block() { + // if (outerValueDone) + if (!isChunked) { + return; + } + + // if called from alignAndCheck, need to reset blockLength + // to avoid an infinite recursion loop on read_long() call + blockLength = MAX_BLOCK_LENGTH; + + blockLength = read_long(); + + // Must remember where we began the chunk to calculate how far + // along we are. See notes above about chunkBeginPos. + + if (blockLength > 0 && blockLength < MAX_BLOCK_LENGTH) { + blockLength += get_offset(); // _REVISIT_ unsafe, should use a Java long + } else { + blockLength = MAX_BLOCK_LENGTH; + byteBuffer.position(byteBuffer.position() - 4); + } + } + + @InfoMethod + private void peekNextLong( long val ) { } + + // Makes sure that if we were reading a chunked value, we end up + // at the right place in the stream, no matter how little the + // unmarshalling code read. + // + // After calling this method, if we are chunking, we should be + // in position to read the end tag. + @CdrRead + private void handleEndOfValue() { + // If we're not chunking, we don't have to worry about + // skipping remaining chunks or finding end tags + if (!isChunked) { + return; + } + + // Skip any remaining chunks + while (blockLength != MAX_BLOCK_LENGTH) { + end_block(); + start_block(); + } + + // Now look for the end tag + + // This is a little wasteful since we're reading + // this long up to 3 times in the worst cases (once + // in start_block, once here, and once in readEndTag + // + // Peek next long + int nextLong = read_long(); + peekNextLong( nextLong ) ; + byteBuffer.position(byteBuffer.position() - 4); + + // We did find an end tag, so we're done. readEndTag + // should take care of making sure it's the correct + // end tag, etc. Remember that since end tags, + // chunk lengths, and valuetags have non overlapping + // ranges, we can tell by the value what the longs are. + if (nextLong < 0) { + return; + } + + if (nextLong == 0 || nextLong >= MAX_BLOCK_LENGTH) { + + // A custom marshaled valuetype left extra data + // on the wire, and that data had another + // nested value inside of it. We've just + // read the value tag or null of that nested value. + // + // In an attempt to get by it, we'll try to call + // read_value() to get the nested value off of + // the wire. Afterwards, we must call handleEndOfValue + // recursively to read any further chunks that the containing + // valuetype might still have after the nested + // value. + read_value(); + handleEndOfValue(); + } else { + // This probably means that the code to skip chunks has + // an error, and ended up setting blockLength to something + // other than maxBlockLength even though we weren't + // starting a new chunk. + throw wrapper.couldNotSkipBytes( nextLong , get_offset() ) ; + } + } + + @CdrRead + private void end_block() { + // if in a chunk, check for underflow or overflow + if (blockLength != MAX_BLOCK_LENGTH) { + if (blockLength == get_offset()) { + // Chunk ended correctly + blockLength = MAX_BLOCK_LENGTH; + } else { + // Skip over anything left by bad unmarshaling code (ex: + // a buggy custom unmarshaler). See handleEndOfValue. + if (blockLength > get_offset()) { + skipToOffset(blockLength); + } else { + throw wrapper.badChunkLength( blockLength, get_offset() ) ; + } + } + } + } + + @CdrRead + private int readValueTag(){ + // outerValueDone = false; + return read_long(); + } + + public org.omg.CORBA.ORB orb() { + return orb; + } + + // ------------ End RMI related methods -------------------------- + + public final void read_boolean_array(boolean[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_boolean(); + } + } + + public final void read_char_array(char[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_char(); + } + } + + public final void read_wchar_array(char[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_wchar(); + } + } + + public final void read_short_array(short[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_short(); + } + } + + public final void read_ushort_array(short[] value, int offset, int length) { + read_short_array(value, offset, length); + } + + public final void read_long_array(int[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_long(); + } + } + + public final void read_ulong_array(int[] value, int offset, int length) { + read_long_array(value, offset, length); + } + + public final void read_longlong_array(long[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_longlong(); + } + } + + public final void read_ulonglong_array(long[] value, int offset, int length) { + read_longlong_array(value, offset, length); + } + + public final void read_float_array(float[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_float(); + } + } + + public final void read_double_array(double[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_double(); + } + } + + public final void read_any_array(org.omg.CORBA.Any[] value, int offset, int length) { + for(int i=0; i < length; i++) { + value[i+offset] = read_any(); + } + } + + //--------------------------------------------------------------------// + // CDRInputStream state management. + // + + + @CdrRead + private String read_repositoryIds() { + + // Read # of repository ids + int numRepIds = read_long(); + if (numRepIds == 0xffffffff) { + int indirection = read_long() + get_offset() - 4; + if (repositoryIdCache != null && repositoryIdCache.containsVal(indirection)) { + return repositoryIdCache.getKey(indirection); + } else { + throw wrapper.unableToLocateRepIdArray(indirection); + } + } else { + // read first array element and store it as an indirection to the whole array + int indirection = get_offset(); + String repID = read_repositoryId(); + if (repositoryIdCache == null) { + repositoryIdCache = new CacheTable("Input repositoryIdCache", orb, false); + } + repositoryIdCache.put(repID, indirection); + + // read and ignore the subsequent array elements, but put them in the + // indirection table in case there are later indirections back to them + for (int i = 1; i < numRepIds; i++) { + read_repositoryId(); + } + + return repID; + } + } + + @CdrRead + private String read_repositoryId() { + String result = readStringOrIndirection(true); + if (result == null) { // Indirection + int indirection = read_long() + get_offset() - 4; + + if (repositoryIdCache != null) { + result = repositoryIdCache.getKey(indirection); + } + } else { + if (repositoryIdCache == null) { + repositoryIdCache = new CacheTable("Input repositoryIdCache", orb, false); + } + repositoryIdCache.put(result, stringIndirection); + } + + if (result != null) { + return result; + } + + throw wrapper.badRepIdIndirection(byteBuffer.position()) ; // todo test this case + } + + @CdrRead + private String read_codebase_URL() { + String result = readStringOrIndirection(true); + if (result == null) { // Indirection + int indirection = read_long() + get_offset() - 4; + + if (codebaseCache != null) { + result = codebaseCache.getKey(indirection) ; + } + } else { + if (codebaseCache == null) { + codebaseCache = new CacheTable("Input codebaseCache", orb, false); + } + codebaseCache.put(result, stringIndirection); + } + + if (result != null) { + return result; + } + + throw wrapper.badCodebaseIndirection(byteBuffer.position()) ; // todo test this case + } + + /* DataInputStream methods */ + + public java.lang.Object read_Abstract () { + return read_abstract_interface(); + } + + public java.io.Serializable read_Value () { + return read_value(); + } + + public void read_any_array (org.omg.CORBA.AnySeqHolder seq, int offset, int length) { + read_any_array(seq.value, offset, length); + } + + public void read_boolean_array (org.omg.CORBA.BooleanSeqHolder seq, int offset, int length) { + read_boolean_array(seq.value, offset, length); + } + + public void read_char_array (org.omg.CORBA.CharSeqHolder seq, int offset, int length) { + read_char_array(seq.value, offset, length); + } + + public void read_wchar_array (org.omg.CORBA.WCharSeqHolder seq, int offset, int length) { + read_wchar_array(seq.value, offset, length); + } + + public void read_octet_array (org.omg.CORBA.OctetSeqHolder seq, int offset, int length) { + read_octet_array(seq.value, offset, length); + } + + public void read_short_array (org.omg.CORBA.ShortSeqHolder seq, int offset, int length) { + read_short_array(seq.value, offset, length); + } + + public void read_ushort_array (org.omg.CORBA.UShortSeqHolder seq, int offset, int length) { + read_ushort_array(seq.value, offset, length); + } + + public void read_long_array (org.omg.CORBA.LongSeqHolder seq, int offset, int length) { + read_long_array(seq.value, offset, length); + } + + public void read_ulong_array (org.omg.CORBA.ULongSeqHolder seq, int offset, int length) { + read_ulong_array(seq.value, offset, length); + } + + public void read_ulonglong_array (org.omg.CORBA.ULongLongSeqHolder seq, int offset, int length) { + read_ulonglong_array(seq.value, offset, length); + } + + public void read_longlong_array (org.omg.CORBA.LongLongSeqHolder seq, int offset, int length) { + read_longlong_array(seq.value, offset, length); + } + + public void read_float_array (org.omg.CORBA.FloatSeqHolder seq, int offset, int length) { + read_float_array(seq.value, offset, length); + } + + public void read_double_array (org.omg.CORBA.DoubleSeqHolder seq, int offset, int length) { + read_double_array(seq.value, offset, length); + } + + public java.math.BigDecimal read_fixed(short digits, short scale) { + // digits isn't really needed here + StringBuffer buffer = read_fixed_buffer(); + if (digits != buffer.length()) { + throw wrapper.badFixed(digits, buffer.length()); + } + buffer.insert(digits - scale, '.'); + return new BigDecimal(buffer.toString()); + } + + // This method is unable to yield the correct scale. + public java.math.BigDecimal read_fixed() { + return new BigDecimal(read_fixed_buffer().toString()); + } + + // Each octet contains (up to) two decimal digits. + // If the fixed type has an odd number of decimal digits, then the representation + // begins with the first (most significant) digit. + // Otherwise, this first half-octet is all zero, and the first digit + // is in the second half-octet. + // The sign configuration, in the last half-octet of the representation, + // is 0xD for negative numbers and 0xC for positive and zero values. + private StringBuffer read_fixed_buffer() { + StringBuffer buffer = new StringBuffer(64); + byte doubleDigit; + int firstDigit; + int secondDigit; + boolean wroteFirstDigit = false; + boolean more = true; + while (more) { + doubleDigit = this.read_octet(); + firstDigit = (doubleDigit & 0xf0) >> 4; + secondDigit = doubleDigit & 0x0f; + if (wroteFirstDigit || firstDigit != 0) { + buffer.append(Character.forDigit(firstDigit, 10)); + wroteFirstDigit = true; + } + if (secondDigit == 12) { + // positive number or zero + if ( ! wroteFirstDigit) { + // zero + return new StringBuffer("0.0"); + } else { + // positive number + // done + } + more = false; + } else if (secondDigit == 13) { + // negative number + buffer.insert(0, '-'); + more = false; + } else { + buffer.append(Character.forDigit(secondDigit, 10)); + wroteFirstDigit = true; + } + } + return buffer; + } + + private final static String _id = "IDL:omg.org/CORBA/DataInputStream:1.0"; + private final static String[] _ids = { _id }; + + public String[] _truncatable_ids() { + if (_ids == null) { + return null; + } + + return _ids.clone(); + } + + public int getBufferLength() { + return byteBuffer.limit(); + } + + public void setBufferLength(int value) { + byteBuffer.limit(value); + } + + public void setIndex(int value) { + byteBuffer.position(value); + } + + @Override + public ByteOrder getByteOrder() { + return byteBuffer.order(); + } + + public void orb(org.omg.CORBA.ORB orb) { + this.orb = (ORB)orb; + } + + public BufferManagerRead getBufferManager() { + return bufferManagerRead; + } + + @CdrRead + private void skipToOffset(int offset) { // todo test this + // Number of bytes to skip + int len = offset - get_offset(); + + int n = 0; + + while (n < len) { + int wanted; + int bytes; + + if (!byteBuffer.hasRemaining()) grow(1, 1); + int avail = byteBuffer.remaining(); + + wanted = len - n; + bytes = (wanted < avail) ? wanted : avail; + byteBuffer.position(byteBuffer.position() + bytes); + n += bytes; + } + } + + + // Mark and reset ------------------------------------------------- + + protected MarkAndResetHandler markAndResetHandler = null; + + protected class StreamMemento { + // These are the fields that may change after marking + // the stream position, so we need to save them. + private int blockLength_; + private int end_flag_; + private int chunkedValueNestingLevel_; + private int valueIndirection_; + private int stringIndirection_; + private boolean isChunked_; + private ValueHandler valueHandler_; + private ByteBuffer byteBuffer_; + private boolean specialNoOptionalDataState_; + + public StreamMemento() { + blockLength_ = blockLength; + end_flag_ = end_flag; + chunkedValueNestingLevel_ = chunkedValueNestingLevel; + valueIndirection_ = valueIndirection; + stringIndirection_ = stringIndirection; + isChunked_ = isChunked; + valueHandler_ = valueHandler; + specialNoOptionalDataState_ = specialNoOptionalDataState; + byteBuffer_ = byteBuffer.duplicate(); + } + } + + public java.lang.Object createStreamMemento() { + return new StreamMemento(); + } + + public void restoreInternalState(java.lang.Object streamMemento) { + + StreamMemento mem = (StreamMemento)streamMemento; + + blockLength = mem.blockLength_; + end_flag = mem.end_flag_; + chunkedValueNestingLevel = mem.chunkedValueNestingLevel_; + valueIndirection = mem.valueIndirection_; + stringIndirection = mem.stringIndirection_; + isChunked = mem.isChunked_; + valueHandler = mem.valueHandler_; + specialNoOptionalDataState = mem.specialNoOptionalDataState_; + byteBuffer = mem.byteBuffer_; + } + + public int getPosition() { + return get_offset(); + } + + public void mark(int readlimit) { + markAndResetHandler.mark(this); + } + + public void reset() { + markAndResetHandler.reset(); + } + + // ---------------------------------- end Mark and Reset + + // Provides a hook so subclasses of CDRInputStream can provide + // a CodeBase. This ultimately allows us to grab a Connection + // instance in IIOPInputStream, the only subclass where this + // is actually used. + CodeBase getCodeBase() { + return parent.getCodeBase(); + } + + /** + * Attempts to find the class described by the given + * repository ID string and expected type. The first + * attempt is to find the class locally, falling back + * on the URL that came with the value. The second + * attempt is to use a URL from the remote CodeBase. + */ + @CdrRead + private Class getClassFromString(String repositoryIDString, + String codebaseURL, + Class expectedType) + { + RepositoryIdInterface repositoryID = repIdStrs.getFromString(repositoryIDString); + + ClassCodeBaseHandler ccbh = orb.classCodeBaseHandler() ; + if (ccbh != null) { + String className = repositoryID.getClassName() ; + Class result = ccbh.loadClass( codebaseURL, className ) ; + + if (result != null) { + return result ; + } + } + + try { + try { + // First try to load the class locally, then use + // the provided URL (if it isn't null) + return repositoryID.getClassFromType(expectedType, + codebaseURL); + } catch (ClassNotFoundException cnfeOuter) { + + try { + + if (getCodeBase() == null) { + return null; // class cannot be loaded remotely. + } + + // Get a URL from the remote CodeBase and retry + codebaseURL = getCodeBase().implementation(repositoryIDString); + + // Don't bother trying to find it locally again if + // we got a null URL + if (codebaseURL == null) { + return null; + } + + return repositoryID.getClassFromType(expectedType, + codebaseURL); + } catch (ClassNotFoundException cnfeInner) { + // Failed to load the class + return null; + } + } + } catch (MalformedURLException mue) { + // Always report a bad URL + throw wrapper.malformedUrl( mue, repositoryIDString, codebaseURL ) ; + } + } + + + // Utility method used to get chars from bytes + char[] getConvertedChars(int numBytes, + CodeSetConversion.BTCConverter converter) { + + + if (byteBuffer.remaining() >= numBytes) { + // If the entire string is in this buffer, + // just convert directly from the buffer rather than + // allocating and copying. + int pos = byteBuffer.position(); + char[] result = converter.getChars(byteBuffer.slice(), 0, numBytes); + byteBuffer.position(pos + numBytes); + return result; + } else { + // Stretches across buffers. Unless we provide an + // incremental conversion interface, allocate and + // copy the bytes. + byte[] bytes = new byte[numBytes]; + + // REVISIT - We should avoid getting the bytes into an array if + // possible. Extend the logic used above for the if() case , send + // the bytebuffer, as it is, for reading the strings. If any + // string is spread across multiple messages, the logic is going + // to be complex- which is, to decode strings in parts and then + // concatenate them in order. + read_octet_array(bytes, 0, bytes.length); + + return converter.getChars(bytes, 0, numBytes); + } + } + + protected CodeSetConversion.BTCConverter getCharConverter() { + if (charConverter == null) { + charConverter = parent.createCharBTCConverter(); + } + + return charConverter; + } + + protected CodeSetConversion.BTCConverter getWCharConverter() { + if (wcharConverter == null) { + wcharConverter = parent.createWCharBTCConverter(); + } + + return wcharConverter; + } + + /** + * Aligns the current position on the given octet boundary + * if there are enough bytes available to do so. Otherwise, + * it just returns. This is used for some (but not all) + * GIOP 1.2 message headers. + */ + + void alignOnBoundary(int octetBoundary) { + int needed = computeAlignment(byteBuffer.position(), octetBoundary); + + if (byteBuffer.position() + needed <= byteBuffer.limit()) + { + byteBuffer.position(byteBuffer.position() + needed); + } + } + + public void resetCodeSetConverters() { + charConverter = null; + wcharConverter = null; + } + + @InfoMethod + private void valueTag( int value ) { } + + @CdrRead + public void start_value() { + // Read value tag + int vType = readValueTag(); + valueTag( vType ) ; + + if (vType == 0) { + // Stream needs to go into a state where it + // throws standard exception until end_value + // is called. This means the sender didn't + // send any custom data. If the reader here + // tries to read more, we need to throw an + // exception before reading beyond where + // we're supposed to + specialNoOptionalDataState = true; + + return; + } + + if (vType == 0xffffffff) { + // One should never indirect to a custom wrapper + throw wrapper.customWrapperIndirection( ); + } + + if (repIdUtil.isCodeBasePresent(vType)) { + throw wrapper.customWrapperWithCodebase(); + } + + if (repIdUtil.getTypeInfo(vType) + != RepositoryIdUtility.SINGLE_REP_TYPE_INFO) { + throw wrapper.customWrapperNotSingleRepid( ); + } + + + // REVISIT - Could verify repository ID even though + // it isn't used elsewhere + read_repositoryId(); + + // Note: isChunked should be true here. Should have + // been set to true in the containing value's read_value + // method. + + start_block(); + end_flag--; + chunkedValueNestingLevel--; + } + + @CdrRead + public void end_value() { + + if (specialNoOptionalDataState) { + specialNoOptionalDataState = false; + return; + } + + handleEndOfValue(); + readEndTag(); + + // Note that isChunked should still be true here. + // If the containing valuetype is the highest + // chunked value, it will get set to false + // at the end of read_value. + + // allow for possible continuation chunk + start_block(); + } + + @Override + @CdrRead + public void close() throws IOException { + + // tell BufferManagerRead to release any ByteBuffers + getBufferManager().close(byteBuffer); + + if (byteBuffer != null) { + + // release this stream's ByteBuffer to the pool + ByteBufferPool byteBufferPool = orb.getByteBufferPool(); + byteBufferPool.releaseByteBuffer(byteBuffer); + byteBuffer = null; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_1.java new file mode 100644 index 000000000..e0a878294 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_1.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +public class CDRInputStream_1_1 extends CDRInputStream_1_0 +{ + // See notes in CDROutputStream + protected int fragmentOffset = 0; + + @Override + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_1; + } + + // Template method + @Override + public CDRInputStreamBase dup() { + CDRInputStreamBase result = super.dup(); + + ((CDRInputStream_1_1)result).fragmentOffset = this.fragmentOffset; + + return result; + } + + @Override + protected int get_offset() { + return byteBuffer.position() + fragmentOffset; + } + + @Override + protected void alignAndCheck(int align, int n) { + + + checkBlockLength(align, n); + + // WARNING: Must compute real alignment after calling + // checkBlockLength since it may move the position + int alignment = computeAlignment(byteBuffer.position(), align); + + if (byteBuffer.position() + n + alignment > byteBuffer.limit()) { + + // Some other ORBs may have found a way to send 1.1 + // fragments which put alignment bytes at the end + // of a fragment + if (byteBuffer.position() + alignment == byteBuffer.limit()) + { + byteBuffer.position(byteBuffer.position() + alignment); + } + + grow(align, n); + + // We must recalculate the alignment after a possible + // fragmentation since the new bbwi.position() (after the header) + // may require a different alignment. + + alignment = computeAlignment(byteBuffer.position(), align); + } + + byteBuffer.position(byteBuffer.position() + alignment); + } + + // + // This can be overridden.... + // + @Override + protected void grow(int align, int n) { + + // Save the size of the current buffer for + // possible fragmentOffset calculation + int oldSize = byteBuffer.position(); + + byteBuffer = bufferManagerRead.underflow(byteBuffer); + + if (bufferManagerRead.isFragmentOnUnderflow()) { + + // By this point we should be guaranteed to have + // a new fragment whose header has already been + // unmarshalled. bbwi.position() should point to the + // end of the header. + fragmentOffset += (oldSize - byteBuffer.position()); + + markAndResetHandler.fragmentationOccured(byteBuffer); + } + } + + // Mark/reset --------------------------------------- + + private class FragmentableStreamMemento extends StreamMemento + { + private int fragmentOffset_; + + public FragmentableStreamMemento() + { + super(); + + fragmentOffset_ = fragmentOffset; + } + } + + @Override + public java.lang.Object createStreamMemento() { + return new FragmentableStreamMemento(); + } + + @Override + public void restoreInternalState(java.lang.Object streamMemento) + { + super.restoreInternalState(streamMemento); + + fragmentOffset + = ((FragmentableStreamMemento)streamMemento).fragmentOffset_; + } + + // -------------------------------------------------- + + @Override + public char read_wchar() { + // In GIOP 1.1, interoperability with wchar is limited + // to 2 byte fixed width encodings. CORBA formal 99-10-07 15.3.1.6. + // WARNING: For UTF-16, this means that there can be no + // byte order marker, so it must default to big endian! + alignAndCheck(2, 2); + + // Because of the alignAndCheck, we should be guaranteed + // 2 bytes of real data. + char[] result = getConvertedChars(2, getWCharConverter()); + + // Did the provided bytes convert to more than one + // character? This may come up as more unicode values are + // assigned, and a single 16 bit Java char isn't enough. + // Better to use strings for i18n purposes. + if (getWCharConverter().getNumChars() > 1) + throw wrapper.btcResultMoreThanOneChar() ; + + return result[0]; + } + + @Override + public String read_wstring() { + // In GIOP 1.1, interoperability with wchar is limited + // to 2 byte fixed width encodings. CORBA formal 99-10-07 15.3.1.6. + int len = read_long(); + + // Workaround for ORBs which send string lengths of + // zero to mean empty string. + // + if (len == 0) + return newEmptyString(); + + checkForNegativeLength(len); + + // Don't include the two byte null for the + // following computations. Remember that since we're limited + // to a 2 byte fixed width code set, the "length" was the + // number of such 2 byte code points plus a 2 byte null. + len = len - 1; + + char[] result = getConvertedChars(len * 2, getWCharConverter()); + + // Skip over the 2 byte null + read_short(); + + return new String(result, 0, getWCharConverter().getNumChars()); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_2.java new file mode 100644 index 000000000..07f5307fa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDRInputStream_1_2.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.trace.CdrRead; + +@CdrRead +public class CDRInputStream_1_2 extends CDRInputStream_1_1 +{ + // Indicates whether the header is padded. In GIOP 1.2 and above, + // the body must be aligned on an 8-octet boundary, and so the header is + // padded appropriately. However, if there is no body to a request or reply + // message, there is no header padding, in the unfragmented case. + protected boolean headerPadding; + + // used to remember headerPadding flag when mark() and restore() are used. + protected boolean restoreHeaderPadding; + + // Called by RequestMessage_1_2 or ReplyMessage_1_2 classes only. + @Override + void setHeaderPadding(boolean headerPadding) { + this.headerPadding = headerPadding; + } + + // the mark and reset methods have been overridden to remember the + // headerPadding flag. + + @Override + public void mark(int readlimit) { + super.mark(readlimit); + restoreHeaderPadding = headerPadding; + } + + @Override + public void reset() { + super.reset(); + headerPadding = restoreHeaderPadding; + restoreHeaderPadding = false; + } + + // Template method + // This method has been overriden to ensure that the duplicated stream + // inherits the headerPadding flag, in case of GIOP 1.2 and above, streams. + @Override + public CDRInputStreamBase dup() { + CDRInputStreamBase result = super.dup(); + ((CDRInputStream_1_2)result).headerPadding = this.headerPadding; + return result; + } + + @CdrRead + @Override + protected void alignAndCheck(int align, int n) { + // headerPadding bit is set by read method of the RequestMessage_1_2 + // or ReplyMessage_1_2 classes. When set, the very first body read + // operation (from the stub code) would trigger an alignAndCheck + // method call, that would in turn skip the header padding that was + // inserted during the earlier write operation by the sender. The + // padding ensures that the body is aligned on an 8-octet boundary, + // for GIOP versions 1.2 and beyond. + if (headerPadding == true) { + headerPadding = false; + alignOnBoundary(ORBConstants.GIOP_12_MSG_BODY_ALIGNMENT); + } + + checkBlockLength(align, n); + + // WARNING: Must compute real alignment after calling + // checkBlockLength since it may move the position + + // In GIOP 1.2, a fragment may end with some alignment + // padding (which leads to all fragments ending perfectly + // on evenly divisible 8 byte boundaries). A new fragment + // never requires alignment with the header since it ends + // on an 8 byte boundary. + // NOTE: Change underlying ByteBuffer's position only if + // alignIncr is less than or equal to underlying + // ByteBuffer's limit. + int savedPosition = byteBuffer.position(); + int alignIncr = computeAlignment(savedPosition,align); + int bytesNeeded = alignIncr + n; + if (savedPosition + alignIncr <= byteBuffer.limit()) { + byteBuffer.position(savedPosition + alignIncr); + } + + if (savedPosition + bytesNeeded > byteBuffer.limit()) { + grow(1, n); + } + } + + @Override + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_2; + } + + @Override + public char read_wchar() { + // In GIOP 1.2, a wchar is encoded as an unsigned octet length + // followed by the octets of the converted wchar. + int numBytes = read_octet(); + + char[] result = getConvertedChars(numBytes, getWCharConverter()); + + // Did the provided bytes convert to more than one + // character? This may come up as more unicode values are + // assigned, and a single 16 bit Java char isn't enough. + // Better to use strings for i18n purposes. + if (getWCharConverter().getNumChars() > 1) + throw wrapper.btcResultMoreThanOneChar() ; + + return result[0]; + } + + @Override + public String read_wstring() { + // In GIOP 1.2, wstrings are not terminated by a null. The + // length is the number of octets in the converted format. + // A zero length string is represented with the 4 byte length + // value of 0. + + int len = read_long(); + + if (len == 0) + return newEmptyString(); + + checkForNegativeLength(len); + + return new String(getConvertedChars(len, getWCharConverter()), + 0, + getWCharConverter().getNumChars()); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputObject.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputObject.java new file mode 100644 index 000000000..ebd87e1fd --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputObject.java @@ -0,0 +1,639 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator ; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.transport.MessageTraceManagerImpl; + +import java.io.IOException ; +import java.io.ObjectInputStream; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import org.omg.CORBA.Any; +import org.omg.CORBA.DataOutputStream; +import org.omg.CORBA.TypeCode; + +import com.sun.corba.ee.spi.trace.CdrWrite ; +import org.omg.CORBA.portable.BoxedValueHelper; +import org.omg.CORBA.portable.ValueOutputStream; + +/** + * @author Harold Carr + */ +@CdrWrite +public class CDROutputObject extends org.omg.CORBA_2_3.portable.OutputStream + implements MarshalOutputStream, DataOutputStream, ValueOutputStream { + + private static final CDRInputObjectFactory INPUT_OBJECT_FACTORY = new CDRInputObjectFactory(); + protected static final ORBUtilSystemException wrapper = ORBUtilSystemException.self ; + private static final OMGSystemException omgWrapper = OMGSystemException.self ; + private static final long serialVersionUID = -3801946738338642735L; + + private transient CDROutputStreamBase impl; + + private transient Message header; + private transient MessageMediator corbaMessageMediator; + private transient Connection connection; + + // todo this is only used in a pair of legacy tests. Rewrite them as unit tests and remove this method. + public void sendFirstFragment() { + ByteBuffer buffer = getBufferManager().overflow(impl.getByteBuffer(), 0); + setPrivateFieldValue(impl, "byteBuffer", buffer); + } + + protected void setPrivateFieldValue(Object obj, String fieldName, Object value) { + try { + Class theClass = obj.getClass(); + setPrivateFieldValue(obj, theClass, fieldName, value); + } catch (NoSuchFieldException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + private void setPrivateFieldValue(Object obj, Class theClass, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { + try { + Field field = theClass.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(obj, value); + } catch (NoSuchFieldException e) { + if (theClass.equals(Object.class)) + throw e; + else + setPrivateFieldValue(obj, theClass.getSuperclass(), fieldName, value); + } + } + + // This needed only to get FindBugs to shut up about transient fields. + // Should never be called. + private void readObject( ObjectInputStream is ) throws IOException, + ClassNotFoundException { + impl = null ; + corbaMessageMediator = null ; + connection = null ; + throw new IllegalStateException( "Should not be called" ) ; + } + + @CdrWrite + private void createCDROutputStream(ORB orb, GIOPVersion version, + BufferManagerWrite bufferManager, + byte streamFormatVersion, boolean usePooledByteBuffers) { + impl = OutputStreamFactory.newOutputStream(version); + impl.init(orb, bufferManager, streamFormatVersion, usePooledByteBuffers); + impl.setParent(this); + } + + public CDROutputObject(ORB orb, GIOPVersion version, + BufferManagerWrite bufferManager, + byte streamFormatVersion, boolean usePooledByteBuffers) { + createCDROutputStream( orb, version, bufferManager, streamFormatVersion, usePooledByteBuffers) ; + + this.header = null ; + this.corbaMessageMediator = null ; + this.connection = null ; + } + + + private CDROutputObject( ORB orb, GIOPVersion giopVersion, + Message header, BufferManagerWrite manager, + byte streamFormatVersion, MessageMediator mediator) { + this(orb, giopVersion, manager, streamFormatVersion, usePooledBuffers(mediator)) ; + + this.header = header; + this.corbaMessageMediator = mediator; + + getBufferManager().setOutputObject(this); + } + + private static boolean usePooledBuffers(MessageMediator mediator) { + return (mediator != null && mediator.getConnection() != null) && mediator.getConnection().hasSocketChannel(); + } + + public CDROutputObject(ORB orb, MessageMediator messageMediator, Message header, byte streamFormatVersion) { + this(orb, messageMediator.getGIOPVersion(), header, + BufferManagerFactory.newBufferManagerWrite(messageMediator.getGIOPVersion(), header.getEncodingVersion(), orb), + streamFormatVersion, messageMediator); + } + + // NOTE: + // Used in SharedCDR (i.e., must be grow). + // Used in msgtypes test. + public CDROutputObject(ORB orb, MessageMediator messageMediator, + Message header, + byte streamFormatVersion, + int strategy) { + this(orb, messageMediator.getGIOPVersion(), header, + BufferManagerFactory.newBufferManagerWrite(strategy, header.getEncodingVersion(), orb), + streamFormatVersion, messageMediator); + } + + // REVISIT + // Used on sendCancelRequest. + // Used for needs addressing mode. + public CDROutputObject(ORB orb, MessageMediator mediator, GIOPVersion giopVersion, + Connection connection, Message header, byte streamFormatVersion) { + + this( orb, giopVersion, header, + BufferManagerFactory.newBufferManagerWrite( giopVersion, header.getEncodingVersion(), orb), + streamFormatVersion, mediator ) ; + this.connection = connection ; + } + + // XREVISIT + // Header should only be in message mediator. + // Another possibility: merge header and message mediator. + // REVISIT - make protected once all encoding together + public Message getMessageHeader() { + return header; + } + + public final void finishSendingMessage() { + getBufferManager().sendMessage(); + } + + /* + * Write the contents of the CDROutputStream to the specified + * output stream. Has the side-effect of pushing any current + * Message onto the Message list. + */ + public void writeTo(Connection connection) throws java.io.IOException { + // + // Update the GIOP MessageHeader size field. + // + + ByteBuffer byteBuffer = impl.getByteBuffer(); + + getMessageHeader().setSize(byteBuffer, byteBuffer.position()); + + ORB lorb = (ORB)orb() ; + if (lorb != null) { + TransportManager ctm = lorb.getTransportManager() ; + MessageTraceManagerImpl mtm = (MessageTraceManagerImpl)ctm.getMessageTraceManager() ; + if (mtm.isEnabled()) + mtm.recordDataSent(byteBuffer) ; + } + + byteBuffer.flip(); + connection.write(byteBuffer); + } + + /** overrides create_input_stream from CDROutputStream */ + public org.omg.CORBA.portable.InputStream create_input_stream() { + // XREVISIT + return null; + } + + public Connection getConnection() { + // REVISIT - only set when doing sendCancelRequest. + if (connection != null) { + return connection; + } + return corbaMessageMediator.getConnection(); + } + + // todo this is only used in a legacy test - rewrite the test as a unit test and remove this method + public final int getBufferPosition() { + return impl.getByteBuffer().position(); + } + + /* + * Override the default CDR factory behavior to get the + * negotiated code sets from the connection. + * + * These are only called once per message, the first time needed. + * + * In the local case, there is no Connection, so use the + * local code sets. + */ + protected CodeSetConversion.CTBConverter createCharCTBConverter() { + CodeSetComponentInfo.CodeSetContext codesets = getCodeSets(); + + // If the connection doesn't have its negotiated + // code sets by now, fall back on the defaults defined + // in CDRInputStream. + if (codesets == null) { + return CodeSetConversion.impl().getCTBConverter(OSFCodeSetRegistry.ISO_8859_1); + } + + OSFCodeSetRegistry.Entry charSet + = OSFCodeSetRegistry.lookupEntry(codesets.getCharCodeSet()); + + if (charSet == null) { + throw wrapper.unknownCodeset(null); + } + + return CodeSetConversion.impl().getCTBConverter(charSet, false, false); + } + + protected CodeSetConversion.CTBConverter createWCharCTBConverter() { + + CodeSetComponentInfo.CodeSetContext codesets = getCodeSets(); + + // If the connection doesn't have its negotiated + // code sets by now, we have to throw an exception. + // See CORBA formal 00-11-03 13.9.2.6. + if (codesets == null) { + if (getConnection().isServer()) { + throw omgWrapper.noClientWcharCodesetCtx(); + } else { + throw omgWrapper.noServerWcharCodesetCmp(); + } + } + + OSFCodeSetRegistry.Entry wcharSet + = OSFCodeSetRegistry.lookupEntry(codesets.getWCharCodeSet()); + + if (wcharSet == null) { + throw wrapper.unknownCodeset(null); + } + + boolean useByteOrderMarkers + = ((ORB)orb()).getORBData().useByteOrderMarkers(); + + // With UTF-16: + // + // For GIOP 1.2, we can put byte order markers if we want to, and + // use the default of big endian otherwise. (See issue 3405b) + // + // For GIOP 1.1, we don't use BOMs and use the endianness of + // the stream. + if (wcharSet == OSFCodeSetRegistry.UTF_16) { + if (getGIOPVersion().equals(GIOPVersion.V1_2)) { + return CodeSetConversion.impl().getCTBConverter(wcharSet, false, useByteOrderMarkers); + } + + if (getGIOPVersion().equals(GIOPVersion.V1_1)) { + return CodeSetConversion.impl().getCTBConverter(wcharSet, false, false); + } + } + + // In the normal case, let the converter system handle it + return CodeSetConversion.impl().getCTBConverter(wcharSet, false, useByteOrderMarkers); + } + + // If we're local and don't have a Connection, use the + // local code sets, otherwise get them from the connection. + // If the connection doesn't have negotiated code sets + // yet, then we use ISO8859-1 for char/string and wchar/wstring + // are illegal. + private CodeSetComponentInfo.CodeSetContext getCodeSets() { + if (getConnection() == null) { + return CodeSetComponentInfo.LOCAL_CODE_SETS; + } else { + return getConnection().getCodeSetContext(); + } + } + + protected void dprint(String msg) + { + ORBUtility.dprint("CDROutputObject", msg); + } + + public void setMessageMediator(MessageMediator messageMediator) + { + this.corbaMessageMediator = messageMediator; + } + + public MessageMediator getMessageMediator() + { + return corbaMessageMediator; + } + + public CDRInputObject createInputObject(ORB orb) { + return createInputObject(orb, INPUT_OBJECT_FACTORY); + } + + protected CDRInputObject createInputObject(ORB orb, InputObjectFactory factory) { + CDRInputObject inputObject = factory.createInputObject(this, orb, impl.getByteBuffer(), getSize(), getGIOPVersion()); + impl.dereferenceBuffer(); + return inputObject; + } + + // We can move this out somewhere later. For now, it serves its purpose + // to create a concrete CDR delegate based on the GIOP version. + private static class OutputStreamFactory { + + public static CDROutputStreamBase newOutputStream(GIOPVersion version) { + switch(version.intValue()) { + case GIOPVersion.VERSION_1_0: + return new CDROutputStream_1_0(); + case GIOPVersion.VERSION_1_1: + return new CDROutputStream_1_1(); + case GIOPVersion.VERSION_1_2: + return new CDROutputStream_1_2(); + default: + // REVISIT - what is appropriate? INTERNAL exceptions + // are really hard to track later. + throw wrapper.unsupportedGiopVersion( version ) ; + } + } + } + + // org.omg.CORBA.portable.OutputStream + + public final void write_boolean(boolean value) { + impl.write_boolean(value); + } + public final void write_char(char value) { + impl.write_char(value); + } + public final void write_wchar(char value) { + impl.write_wchar(value); + } + public final void write_octet(byte value) { + impl.write_octet(value); + } + public final void write_short(short value) { + impl.write_short(value); + } + public final void write_ushort(short value) { + impl.write_ushort(value); + } + public final void write_long(int value) { + impl.write_long(value); + } + public final void write_ulong(int value) { + impl.write_ulong(value); + } + public final void write_longlong(long value) { + impl.write_longlong(value); + } + public final void write_ulonglong(long value) { + impl.write_ulonglong(value); + } + public final void write_float(float value) { + impl.write_float(value); + } + public final void write_double(double value) { + impl.write_double(value); + } + public final void write_string(String value) { + impl.write_string(value); + } + public final void write_wstring(String value) { + impl.write_wstring(value); + } + + public final void write_boolean_array(boolean[] value, int offset, int length) { + impl.write_boolean_array(value, offset, length); + } + public final void write_char_array(char[] value, int offset, int length) { + impl.write_char_array(value, offset, length); + } + public final void write_wchar_array(char[] value, int offset, int length) { + impl.write_wchar_array(value, offset, length); + } + public final void write_octet_array(byte[] value, int offset, int length) { + impl.write_octet_array(value, offset, length); + } + public final void write_short_array(short[] value, int offset, int length) { + impl.write_short_array(value, offset, length); + } + public final void write_ushort_array(short[] value, int offset, int length){ + impl.write_ushort_array(value, offset, length); + } + public final void write_long_array(int[] value, int offset, int length) { + impl.write_long_array(value, offset, length); + } + public final void write_ulong_array(int[] value, int offset, int length) { + impl.write_ulong_array(value, offset, length); + } + public final void write_longlong_array(long[] value, int offset, int length) { + impl.write_longlong_array(value, offset, length); + } + public final void write_ulonglong_array(long[] value, int offset,int length) { + impl.write_ulonglong_array(value, offset, length); + } + public final void write_float_array(float[] value, int offset, int length) { + impl.write_float_array(value, offset, length); + } + public final void write_double_array(double[] value, int offset, int length) { + impl.write_double_array(value, offset, length); + } + public final void write_Object(org.omg.CORBA.Object value) { + impl.write_Object(value); + } + public final void write_TypeCode(TypeCode value) { + impl.write_TypeCode(value); + } + public final void write_any(Any value) { + impl.write_any(value); + } + + @SuppressWarnings({"deprecation"}) + public final void write_Principal(org.omg.CORBA.Principal value) { + impl.write_Principal(value); + } + + @Override + public final void write(int b) throws java.io.IOException { + impl.write(b); + } + + @Override + public final void write_fixed(java.math.BigDecimal value) { + impl.write_fixed(value); + } + + @Override + public final void write_Context(org.omg.CORBA.Context ctx, + org.omg.CORBA.ContextList contexts) { + impl.write_Context(ctx, contexts); + } + + @Override + public final org.omg.CORBA.ORB orb() { + return impl.orb(); + } + + // org.omg.CORBA_2_3.portable.OutputStream + @Override + public final void write_value(java.io.Serializable value) { + impl.write_value(value); + } + + @Override + public final void write_value(java.io.Serializable value, + java.lang.Class clz) { + impl.write_value(value, clz); + } + + @Override + public final void write_value(java.io.Serializable value, + String repository_id) { + + impl.write_value(value, repository_id); + } + + @Override + public final void write_value(java.io.Serializable value, BoxedValueHelper factory) { + impl.write_value(value, factory); + } + + @Override + public final void write_abstract_interface(java.lang.Object obj) { + impl.write_abstract_interface(obj); + } + + // java.io.OutputStream + @Override + public final void write(byte b[]) throws IOException { + impl.write(b); + } + + @Override + public final void write(byte b[], int off, int len) throws IOException { + impl.write(b, off, len); + } + + @Override + public final void flush() throws IOException { + impl.flush(); + } + + @Override + public final void close() throws IOException { + impl.close(); + } + + // com.sun.corba.ee.impl.encoding.MarshalOutputStream + public final void start_block() { + impl.start_block(); + } + + public final void end_block() { + impl.end_block(); + } + + public final void putEndian() { + impl.putEndian(); + } + + public void writeTo(java.io.OutputStream s) + throws IOException + { + impl.writeTo(s); + } + + public final byte[] toByteArray() { + return impl.toByteArray(); + } + + /** + * Returns the contents of this stream, from the specified start index to the current output position. + * @param start the index at which to start copying the data. + * @return a byte array representation of part of the output. + */ + public final byte[] toByteArray(int start) { + return impl.toByteArray(start); + } + + // org.omg.CORBA.DataOutputStream + public final void write_Abstract (java.lang.Object value) { + impl.write_Abstract(value); + } + + public final void write_Value (java.io.Serializable value) { + impl.write_Value(value); + } + + public final void write_any_array(org.omg.CORBA.Any[] seq, int offset, int length) { + impl.write_any_array(seq, offset, length); + } + + // org.omg.CORBA.portable.ValueBase + public final String[] _truncatable_ids() { + return impl._truncatable_ids(); + } + + // Other + protected final int getSize() { + return impl.getSize(); + } + + protected final int getIndex() { + return impl.getIndex(); + } + + protected int getRealIndex(int index) { + // Used in indirections. Overridden by TypeCodeOutputStream. + return index; + } + + protected final void setIndex(int value) { + impl.setIndex(value); + } + + // REVISIT: was protected - but need to access from xgiop. + public final BufferManagerWrite getBufferManager() { + return impl.getBufferManager(); + } + + public final void write_fixed(java.math.BigDecimal bigDecimal, short digits, short scale) { + impl.write_fixed(bigDecimal, digits, scale); + } + + public final void writeOctetSequenceTo(org.omg.CORBA.portable.OutputStream s) { + impl.writeOctetSequenceTo(s); + } + + public final GIOPVersion getGIOPVersion() { + return impl.getGIOPVersion(); + } + + public final void writeIndirection(int tag, int posIndirectedTo) { + impl.writeIndirection(tag, posIndirectedTo); + } + + protected final void freeInternalCaches() { + impl.freeInternalCaches(); + } + + // Needed by request and reply messages for GIOP versions >= 1.2 only. + public void setHeaderPadding(boolean headerPadding) { + impl.setHeaderPadding(headerPadding); + } + + // ValueOutputStream ----------------------------- + + public void start_value(String rep_id) { + impl.start_value(rep_id); + } + + public void end_value() { + impl.end_value(); + } + + protected interface InputObjectFactory { + CDRInputObject createInputObject(CDROutputObject outputObject, ORB orb, ByteBuffer byteBuffer, int size, GIOPVersion giopVersion); + } + + private static class CDRInputObjectFactory implements InputObjectFactory { + @Override + public CDRInputObject createInputObject(CDROutputObject outputObject, ORB orb, ByteBuffer byteBuffer, int size, GIOPVersion giopVersion) { + Message messageHeader = outputObject.getMessageHeader(); + messageHeader.setSize(byteBuffer, size); + return new CDRInputObject(orb, null, byteBuffer, messageHeader); + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStreamBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStreamBase.java new file mode 100644 index 000000000..03d2d5c3b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStreamBase.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +/** + * Describes CDROutputObject delegates and provides some + * implementation. Non-default constructors are avoided in + * the delegation to separate instantiation from initialization, + * so we use init methods. + */ +abstract class CDROutputStreamBase extends java.io.OutputStream +{ + protected CDROutputObject parent; + + // Required by parent CDROutputObject + public void setParent(CDROutputObject parent) { + this.parent = parent; + } + + // See EncapsOutputStream, the only one that uses the + // non-pooled ByteBuffers, for additional info. + protected abstract void init(org.omg.CORBA.ORB orb, + BufferManagerWrite bufferManager, + byte streamFormatVersion, + boolean usePooledByteBuffers); + + public abstract void write_boolean(boolean value); + + public abstract void write_char(char value); + public abstract void write_wchar(char value); + public abstract void write_octet(byte value); + public abstract void write_short(short value); + public abstract void write_ushort(short value); + public abstract void write_long(int value); + public abstract void write_ulong(int value); + public abstract void write_longlong(long value); + public abstract void write_ulonglong(long value); + public abstract void write_float(float value); + public abstract void write_double(double value); + public abstract void write_string(String value); + public abstract void write_wstring(String value); + public abstract void write_boolean_array(boolean[] value, int offset, int length); + public abstract void write_char_array(char[] value, int offset, int length); + public abstract void write_wchar_array(char[] value, int offset, int length); + public abstract void write_octet_array(byte[] value, int offset, int length); + public abstract void write_short_array(short[] value, int offset, int length); + public abstract void write_ushort_array(short[] value, int offset, int length); + public abstract void write_long_array(int[] value, int offset, int length); + public abstract void write_ulong_array(int[] value, int offset, int length); + public abstract void write_longlong_array(long[] value, int offset, int length); + public abstract void write_ulonglong_array(long[] value, int offset, int length); + public abstract void write_float_array(float[] value, int offset, int length); + public abstract void write_double_array(double[] value, int offset, int length); + public abstract void write_Object(org.omg.CORBA.Object value); + public abstract void write_TypeCode(TypeCode value); + public abstract void write_any(Any value); + @SuppressWarnings({"deprecation"}) + public abstract void write_Principal(org.omg.CORBA.Principal value); + public void write(int b) throws java.io.IOException { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + public abstract void write_fixed(java.math.BigDecimal value); + public void write_Context(org.omg.CORBA.Context ctx, + org.omg.CORBA.ContextList contexts) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + public abstract org.omg.CORBA.ORB orb(); + + // org.omg.CORBA_2_3.portable.OutputStream + public abstract void write_value(java.io.Serializable value); + + public abstract void write_value(java.io.Serializable value, java.lang.Class clz); + public abstract void write_value(java.io.Serializable value, String repository_id); + public abstract void write_value(java.io.Serializable value, + org.omg.CORBA.portable.BoxedValueHelper factory); + public abstract void write_abstract_interface(java.lang.Object obj); + // java.io.OutputStream + + // com.sun.corba.ee.impl.encoding.MarshalOutputStream + public abstract void start_block(); + + public abstract void end_block(); + public abstract void putEndian(); + public abstract void writeTo(java.io.OutputStream s) + throws IOException; + public abstract byte[] toByteArray(); + protected abstract byte[] toByteArray(int start); + + // org.omg.CORBA.DataOutputStream + public abstract void write_Abstract (java.lang.Object value); + + public abstract void write_Value (java.io.Serializable value); + public abstract void write_any_array(org.omg.CORBA.Any[] seq, int offset, int length); + // org.omg.CORBA.portable.ValueBase + public abstract String[] _truncatable_ids(); + + // Needed by request and reply messages for GIOP versions >= 1.2 only. + abstract void setHeaderPadding(boolean headerPadding); + + // Required by IIOPOutputStream and other subclasses + public abstract int getSize(); + + public abstract int getIndex(); + + public abstract void setIndex(int value); + // public abstract void close() throws IOException; +// public abstract void flush() throws IOException; +// public abstract void write(byte b[], int off, int len) throws IOException; +// public abstract void write(byte b[]) throws IOException; + + abstract void dereferenceBuffer(); + public abstract ByteBuffer getByteBuffer(); + + public abstract BufferManagerWrite getBufferManager(); + + public abstract void write_fixed(java.math.BigDecimal bigDecimal, short digits, short scale); + public abstract void writeOctetSequenceTo(org.omg.CORBA.portable.OutputStream s); + + public abstract GIOPVersion getGIOPVersion(); + + public abstract void writeIndirection(int tag, int posIndirectedTo); + + abstract void freeInternalCaches(); + + abstract void alignOnBoundary(int octetBoundary); + + // org.omg.CORBA.portable.ValueOutputStream + + public abstract void start_value(String rep_id); + + public abstract void end_value(); +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_0.java new file mode 100644 index 000000000..439238a35 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_0.java @@ -0,0 +1,1688 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.Serializable; +import java.io.IOException; + +import java.lang.reflect.Method; + +import java.nio.ByteBuffer; + +import java.security.AccessController; +import java.security.PrivilegedExceptionAction; +import java.security.PrivilegedActionException; + +import java.util.Map; +import java.util.HashMap; + +import javax.rmi.CORBA.EnumDesc; +import javax.rmi.CORBA.ProxyDesc; +import java.lang.reflect.Proxy; + +import javax.rmi.CORBA.ValueHandler; +import javax.rmi.CORBA.ValueHandlerMultiFormat; + +import com.sun.org.omg.CORBA.portable.ValueHelper; +import org.omg.CORBA.CustomMarshal; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.CORBA.VM_CUSTOM; +import org.omg.CORBA.VM_TRUNCATABLE; +import org.omg.CORBA.VM_NONE; +import org.omg.CORBA.portable.IDLEntity; +import org.omg.CORBA.portable.CustomValue; +import org.omg.CORBA.portable.StreamableValue; +import org.omg.CORBA.portable.BoxedValueHelper; + +import com.sun.corba.ee.spi.transport.ByteBufferPool; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.orb.ClassCodeBaseHandler; + +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.impl.misc.CacheTable; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.misc.RepositoryIdStrings; +import com.sun.corba.ee.impl.misc.RepositoryIdUtility; +import com.sun.corba.ee.impl.misc.RepositoryIdFactory; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +import com.sun.corba.ee.impl.misc.ClassInfoCache; + +import com.sun.corba.ee.spi.trace.*; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@CdrWrite +@PrimitiveWrite +public class CDROutputStream_1_0 extends CDROutputStreamBase { + private static final int INDIRECTION_TAG = 0xffffffff; + private static final boolean BIG_ENDIAN = false; + + protected BufferManagerWrite bufferManagerWrite; + ByteBuffer byteBuffer; + + protected ORB orb; + protected static final ORBUtilSystemException wrapper = ORBUtilSystemException.self; + + protected int blockSizeIndex = -1; + protected int blockSizePosition = 0; + + protected byte streamFormatVersion; + + private static final String kWriteMethod = "write"; + + // Enum cache + Map> enumCache = null; + + // Codebase cache + // Note that a CacheTable here fails badly on read. Why? + // This suggests that different codebase strings with the + // same characters are being used, but that does not explain + // the read-side failure. + // ALTCODEBASE + // private CacheTable codebaseCache = null; + private Map codebaseCache = null; + + // Value cache + private CacheTable valueCache = null; + + // Repository ID cache + private CacheTable repositoryIdCache = null; + + // Write end flag + private int end_flag = 0; + + // Beginning with the resolution to interop issue 3526, + // only enclosing chunked valuetypes are taken into account + // when computing the nesting level. However, we still need + // the old computation around for interoperability with our + // older ORBs. + private int chunkedValueNestingLevel = 0; + + private boolean mustChunk = false; + + // In block marker + protected boolean inBlock = false; + + // Last end tag position + private int end_flag_position = 0; + private int end_flag_index = 0; + + // ValueHandler + private ValueHandler valueHandler = null; + + // Repository ID handlers + private RepositoryIdUtility repIdUtil; + private RepositoryIdStrings repIdStrs; + + // Code set converters (created when first needed) + private CodeSetConversion.CTBConverter charConverter; + private CodeSetConversion.CTBConverter wcharConverter; + + // REVISIT - This should be re-factored so that including whether + // to use pool byte buffers or not doesn't need to be known. + public void init(org.omg.CORBA.ORB orb, + BufferManagerWrite bufferManager, + byte streamFormatVersion, + boolean usePooledByteBuffers) { + // ORB must not be null. See CDROutputStream constructor. + this.orb = (ORB) orb; + + this.bufferManagerWrite = bufferManager; + byteBuffer = allocateBuffer(orb, bufferManager, usePooledByteBuffers); + byteBuffer.position(0); + this.streamFormatVersion = streamFormatVersion; + + createRepositoryIdHandlers(); + } + + static ByteBuffer allocateBuffer(org.omg.CORBA.ORB orb, BufferManagerWrite bufferManager, + boolean usePooledByteBuffers) { + int bufferSize = bufferManager.getBufferSize(); + ByteBuffer buffer; + if (usePooledByteBuffers) { + ByteBufferPool byteBufferPool = ((ORB) orb).getByteBufferPool(); + buffer = byteBufferPool.getByteBuffer(bufferSize); + } else { + // don't allocate from pool, allocate non-direct ByteBuffer + buffer = ByteBuffer.allocate(bufferSize); + } + buffer.limit(bufferSize); + return buffer; + } + + private void createRepositoryIdHandlers() { + repIdUtil = RepositoryIdFactory.getRepIdUtility(); + repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); + } + + public BufferManagerWrite getBufferManager() { + return bufferManagerWrite; + } + + public byte[] toByteArray() { + return toByteArray(0); + } + + @Override + protected byte[] toByteArray(int start) { + byte[] it; + + it = new byte[byteBuffer.position() - start]; + + byteBuffer.position(start); + byteBuffer.get(it); + + return it; + } + + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_0; + } + + // Called by Request and Reply message. Valid for GIOP versions >= 1.2 only. + // Illegal for GIOP versions < 1.2. + void setHeaderPadding(boolean headerPadding) { + throw wrapper.giopVersionError(); + } + + @CdrWrite + protected void handleSpecialChunkBegin(int requiredSize) { + // No-op for GIOP 1.0 + } + + @CdrWrite + protected void handleSpecialChunkEnd() { + // No-op for GIOP 1.0 + } + + protected final int computeAlignment(int align) { + if (align > 1) { + int incr = byteBuffer.position() & (align - 1); + if (incr != 0) { + return align - incr; + } + } + + return 0; + } + + protected void alignAndReserve(int align, int n) { + byteBuffer.position(byteBuffer.position() + computeAlignment(align)); + + if (byteBuffer.position() + n > byteBuffer.limit()) { + grow(align, n); + } + } + + // + // Default implementation of grow. Subclassers may override this. + // Always grow the single buffer. This needs to delegate + // fragmentation policy for IIOP 1.1. + // + protected void grow(int align, int n) { + byteBuffer = bufferManagerWrite.overflow(byteBuffer, n); + } + + public final void putEndian() throws SystemException { + write_boolean(BIG_ENDIAN); // Java always writes big-endian + } + + void freeInternalCaches() { + if (codebaseCache != null) { + // ALTCODEBASE + // codebaseCache.done() ; + codebaseCache.clear(); + } + + freeValueCache(); + + if (repositoryIdCache != null) { + repositoryIdCache.done(); + } + } + + @PrimitiveWrite + public void write_octet(byte x) { + alignAndReserve(1, 1); + byteBuffer.put(x); + } + + public final void write_boolean(boolean x) { + write_octet(x ? (byte) 1 : (byte) 0); + } + + public void write_char(char x) { + CodeSetConversion.CTBConverter converter = getCharConverter(); + + converter.convert(x); + + // CORBA formal 99-10-07 15.3.1.6: "In the case of multi-byte encodings + // of characters, a single instance of the char type may only + // hold one octet of any multi-byte character encoding." + if (converter.getNumBytes() > 1) { + throw wrapper.invalidSingleCharCtb(); + } + + write_octet(converter.getBytes()[0]); + } + + private void writeBigEndianWchar(char x) { + byteBuffer.put((byte) ((x >>> 8) & 0xFF)); + byteBuffer.put((byte) (x & 0xFF)); + } + + @PrimitiveWrite + public void write_wchar(char x) { + // Don't allow transmission of wchar/wstring data with + // foreign ORBs since it's against the spec. + if (ORBUtility.isForeignORB(orb)) { + throw wrapper.wcharDataInGiop10(); + } + + // If it's one of our legacy ORBs, do what they did: + alignAndReserve(2, 2); + + writeBigEndianWchar(x); + } + + @PrimitiveWrite + public void write_short(short x) { + alignAndReserve(2, 2); + byteBuffer.putShort(x); + } + + public final void write_ushort(short x) { + write_short(x); + } + + @PrimitiveWrite + public void write_long(int x) { + alignAndReserve(4, 4); + byteBuffer.putInt(x); + } + + public final void write_ulong(int x) { + write_long(x); + } + + @PrimitiveWrite + public void write_longlong(long x) { + alignAndReserve(8, 8); + + byteBuffer.putLong(x); + } + + public final void write_ulonglong(long x) { + write_longlong(x); + } + + public final void write_float(float x) { + write_long(Float.floatToIntBits(x)); + } + + public final void write_double(double x) { + write_longlong(Double.doubleToLongBits(x)); + } + + public void write_string(String value) { + writeString(value); + } + + @PrimitiveWrite + protected int writeString(String value) { + if (value == null) { + throw wrapper.nullParam(); + } + + CodeSetConversion.CTBConverter converter = getCharConverter(); + + converter.convert(value); + + // A string is encoded as an unsigned CORBA long for the + // number of bytes to follow (including a terminating null). + // There is only one octet per character in the string. + int len = converter.getNumBytes() + 1; + + handleSpecialChunkBegin(computeAlignment(4) + 4 + len); + + write_long(len); + int indirection = get_offset() - 4; + + internalWriteOctetArray(converter.getBytes(), 0, converter.getNumBytes()); + + // Write the null ending + write_octet((byte) 0); + + handleSpecialChunkEnd(); + return indirection; + } + + public void write_wstring(String value) { + if (value == null) { + throw wrapper.nullParam(); + } + + // Don't allow transmission of wchar/wstring data with + // foreign ORBs since it's against the spec. + if (ORBUtility.isForeignORB(orb)) { + throw wrapper.wcharDataInGiop10(); + } + + // When talking to our legacy ORBs, do what they did: + int len = value.length() + 1; + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(4 + (len * 2) + computeAlignment(4)); + + write_long(len); + + for (int i = 0; i < len - 1; i++) { + write_wchar(value.charAt(i)); + } + + // Write the null ending + write_short((short) 0); + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + // Performs no checks and doesn't tamper with chunking + void internalWriteOctetArray(byte[] value, int offset, int length) { + if (length == 0) return; + + alignAndReserve(1, 1); // this gives the code the chance to do the eight-byte alignment, if needed + + int numWritten = 0; + while (numWritten < length) { + if (!byteBuffer.hasRemaining()) alignAndReserve(1, 1); + + int count = Math.min(length - numWritten, byteBuffer.remaining()); + byteBuffer.put(value, offset + numWritten, count); + numWritten += count; + } + } + + public final void write_octet_array(byte b[], int offset, int length) { + if (b == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(length); + + internalWriteOctetArray(b, offset, length); + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + @SuppressWarnings({"deprecation"}) + public void write_Principal(org.omg.CORBA.Principal p) { + write_long(p.name().length); + write_octet_array(p.name(), 0, p.name().length); + } + + @CdrWrite + public void write_any(Any any) { + if (any == null) { + throw wrapper.nullParam(); + } + + write_TypeCode(any.type()); + any.write_value(parent); + } + + @CdrWrite + public void write_TypeCode(TypeCode tc) { + if (tc == null) { + throw wrapper.nullParam(); + } + TypeCodeImpl tci; + if (tc instanceof TypeCodeImpl) { + tci = (TypeCodeImpl) tc; + } else { + tci = new TypeCodeImpl(orb, tc); + } + + tci.write_value(parent); + } + + @CdrWrite + public void write_Object(org.omg.CORBA.Object ref) { + if (ref == null) { + IOR nullIOR = IORFactories.makeIOR(orb); + nullIOR.write(parent); + return; + } + + // IDL to Java formal 01-06-06 1.21.4.2 + if (ref instanceof org.omg.CORBA.LocalObject) { + throw wrapper.writeLocalObject(); + } + + IOR ior = orb.getIOR(ref, true); + ior.write(parent); + } + + // ------------ RMI related methods -------------------------- + + @CdrWrite + public void write_abstract_interface(java.lang.Object obj) { + boolean corbaObject = false; // Assume value type. + org.omg.CORBA.Object theObject = null; + + // Is it a CORBA.Object? + + if (obj != null && obj instanceof org.omg.CORBA.Object) { + + // Yes. + + theObject = (org.omg.CORBA.Object) obj; + corbaObject = true; + } + + // Write our flag... + + write_boolean(corbaObject); + + // Now write out the object... + + if (corbaObject) { + write_Object(theObject); + } else { + try { + write_value((java.io.Serializable) obj); + } catch (ClassCastException cce) { + if (obj instanceof java.io.Serializable) { + throw cce; + } else { + ORBUtility.throwNotSerializableForCorba(obj.getClass().getName()); + } + } + } + } + + @CdrWrite + public void write_value(Serializable object, Class clz) { + + write_value(object); + } + + @CdrWrite + private void startValueChunk(boolean useChunking) { + if (useChunking) { + start_block(); + chunkedValueNestingLevel--; + } + + end_flag--; + } + + @CdrWrite + private void endValueChunk(boolean useChunking) { + if (useChunking) { + end_block(); + } + + writeEndTag(useChunking); + } + + private void writeWStringValue(String string) { + + int indirection = writeValueTag(mustChunk, true, null); + + write_repositoryId(repIdStrs.getWStringValueRepId()); + + updateIndirectionTable(indirection, string); + + startValueChunk(mustChunk); + write_wstring(string); + endValueChunk(mustChunk); + } + + private String getCodebase(Class cls) { + ClassCodeBaseHandler ccbh = orb.classCodeBaseHandler(); + if (ccbh != null) { + String result = ccbh.getCodeBase(cls); + if (result != null) { + return result; + } + } + + return Util.getInstance().getCodebase(cls); + } + + @CdrWrite + private void writeArray(Serializable array, Class clazz) { + if (valueHandler == null) { + valueHandler = ORBUtility.createValueHandler(); + } + + // Write value_tag + int indirection = writeValueTag(mustChunk, true, getCodebase(clazz)); + + // Write repository ID + write_repositoryId(repIdStrs.createSequenceRepID(clazz)); + + // Add indirection for object to indirection table + updateIndirectionTable(indirection, array); + + callWriteValue(parent, array, streamFormatVersion); + } + + @CdrWrite + private void writeValueBase(org.omg.CORBA.portable.ValueBase object, + Class clazz) { + // _REVISIT_ could check to see whether chunking really needed + mustChunk = true; + + int indirection = writeValueTag(true, true, getCodebase(clazz)); + + String repId = object._truncatable_ids()[0]; + write_repositoryId(repId); + + updateIndirectionTable(indirection, object); + + startValueChunk(true); + writeIDLValue(object, repId); + endValueChunk(true); + } + + // We know that object is not null, because that was checked in + // write_value( Serializable, String ) + @CdrWrite + private void writeRMIIIOPValueType(Serializable object, Class clazz, + ClassInfoCache.ClassInfo cinfo) { + + if (valueHandler == null) { + valueHandler = ORBUtility.createValueHandler(); + } + + Serializable key = object; + + // Allow the ValueHandler to call writeReplace on + // the Serializable (if the method is present) + object = valueHandler.writeReplace(key); + + if (object != key) { + if (object == null) { + // If replaced value is null, write null tag and return + write_long(0); + return; + } + + // write replace changed something + if (writeIndirectionIfPossible(object)) { + return; + } + + clazz = object.getClass(); + } + + mustChunk |= valueHandler.isCustomMarshaled(clazz); + + // Write value_tag + int indirection = writeValueTag(mustChunk, true, getCodebase(clazz)); + + // Write rep. id + write_repositoryId(repIdStrs.createForJavaType(clazz, cinfo)); + + // Add indirection for object to indirection table. + // If writeReplace nominated a replacement object, + // store both the replacement and the original object in the + // table. + updateIndirectionTable(indirection, key); + if (object != key) { + updateIndirectionTable(indirection, object); + } + + callWriteValue(parent, object, streamFormatVersion); + } + + @CdrWrite + private void callWriteValue(org.omg.CORBA.portable.OutputStream parent, + java.io.Serializable object, byte streamFormatVersion) { + if (valueHandler == null) { + valueHandler = ORBUtility.createValueHandler(); + } + + boolean currentMustChunk = mustChunk; + startValueChunk(currentMustChunk); + + if (valueHandler instanceof ValueHandlerMultiFormat) { + ValueHandlerMultiFormat vh = (ValueHandlerMultiFormat) valueHandler; + vh.writeValue(parent, object, streamFormatVersion); + } else { + valueHandler.writeValue(parent, object); + } + + endValueChunk(currentMustChunk); + } + + private EnumDesc getEnumDesc(String className, String enumValue) { + EnumDesc result = null; + Map map = null; + + if (enumCache == null) { + enumCache = new HashMap>(); + } else { + map = enumCache.get(className); + } + + if (map == null) { + map = new HashMap(); + enumCache.put(className, map); + } else { + result = map.get(enumValue); + } + + if (result == null) { + result = new EnumDesc(); + result.className = className; + result.value = enumValue; + + map.put(enumValue, result); + } + + return result; + } + + @CdrWrite + public void write_value(Serializable object, String repository_id) { + // Handle null references + if (object == null) { + // Write null tag and return + write_long(0); + return; + } + + Class clazz = object.getClass(); + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get(clazz); + if (cinfo.isEnum()) { + String enumValue = ((Enum) object).name(); + if (orb.getORBData().useEnumDesc()) { + EnumDesc desc = getEnumDesc(clazz.getName(), enumValue); + write_value(desc, (String) null); + } else { + // Write value_tag + mustChunk = false; + int indirection = writeValueTag(mustChunk, true, getCodebase(clazz)); + + // Write rep. id + write_repositoryId(repIdStrs.createForJavaType(clazz, cinfo)); + updateIndirectionTable(indirection, object); + + // Just write the enum member name + writeString(enumValue); + } + + return; + } + + if (cinfo.isProxyClass()) { + Class[] ifaces = clazz.getInterfaces(); + ProxyDesc pd = new ProxyDesc(); + + pd.interfaces = new String[ifaces.length]; + for (int i = 0; i < ifaces.length; ++i) { + pd.interfaces[i] = ifaces[i].getName(); + } + pd.handler = Proxy.getInvocationHandler(object); + pd.codebase = getCodebase(object.getClass()); + write_value(pd, (String) null); + return; + } + + // Handle shared references + if (writeIndirectionIfPossible(object)) { + return; + } + + // Save mustChunk in case a recurisive call from the ValueHandler or IDL + // generated code calls write_value with a possibly different value of mustChunk + boolean oldMustChunk = mustChunk; + + if (inBlock) { + end_block(); + } + + if (cinfo.isArray()) { + // Handle arrays + writeArray(object, clazz); + } else if (cinfo.isAValueBase(clazz)) { + // Handle IDL Value types + writeValueBase((org.omg.CORBA.portable.ValueBase) object, clazz); + } else if (cinfo.isAIDLEntity(clazz) && !cinfo.isACORBAObject(clazz)) { + writeIDLEntity((IDLEntity) object); + } else if (cinfo.isAString(clazz)) { + writeWStringValue((String) object); + } else if (cinfo.isAClass(clazz)) { + ClassInfoCache.ClassInfo lcinfo = ClassInfoCache.get((Class) object); + writeClass(repository_id, (Class) object, lcinfo); + } else { + // RMI-IIOP value type + writeRMIIIOPValueType(object, clazz, cinfo); + } + + mustChunk = oldMustChunk; + + // Check to see if we need to start another block for a + // possible outer value + if (mustChunk) { + start_block(); + } + } + + public void write_value(Serializable object) { + write_value(object, (String) null); + } + + @SuppressWarnings({"deprecation"}) + @CdrWrite + public void write_value(Serializable object, BoxedValueHelper factory) { + if (object == null) { + // Write null tag and return + write_long(0); + return; + } + + // Handle shared references + if (writeIndirectionIfPossible(object)) { + return; + } + + // Save mustChunk in case a recursive call from the ValueHandler or IDL + // generated code calls write_value with a possibly different value of mustChunk + boolean oldMustChunk = mustChunk; + + // can set mustChunk + boolean isCustom = isCustom(object, factory); + + if (mustChunk && inBlock) { + end_block(); + } + + int indirection = writeValueTag(mustChunk, orb.getORBData().useRepId(), getCodebase(object.getClass())); + + if (orb.getORBData().useRepId()) { + write_repositoryId(factory.get_id()); + } + + updateIndirectionTable(indirection, object); + + boolean currentMustChunk = mustChunk; + startValueChunk(currentMustChunk); + if (mustChunk && isCustom) { + ((CustomMarshal) object).marshal(parent); + } else { + factory.write_value(parent, object); + } + endValueChunk(currentMustChunk); + + mustChunk = oldMustChunk; + + // Check to see if we need to start another block for a + // possible outer value + if (mustChunk) { + start_block(); + } + + } + + private boolean isCustom(Serializable object, BoxedValueHelper factory) { + boolean isCustom = false; + if (factory instanceof com.sun.org.omg.CORBA.portable.ValueHelper) { + short modifier = getTypeModifier((ValueHelper) factory); + + if (object instanceof CustomMarshal && modifier == VM_CUSTOM.value) { + isCustom = true; + mustChunk = true; + } else if (modifier == VM_TRUNCATABLE.value) { + mustChunk = true; + } + } + return isCustom; + } + + @SuppressWarnings("deprecated") + private short getTypeModifier(ValueHelper factory) { + short modifier; + try { + modifier = factory.get_type().type_modifier(); + } catch (BadKind ex) { // tk_value_box + modifier = VM_NONE.value; + } + return modifier; + } + + /** + * Returns the current position relative to the start of the message. + * + * @return + */ + public int get_offset() { + return byteBuffer.position(); + } + + @CdrWrite + public void start_block() { + // Save space in the buffer for block size + write_long(0); + + // Has to happen after write_long since write_long could + // trigger grow which is overridden by subclasses to + // depend on inBlock. + inBlock = true; + + // Note that get_offset is overridden in subclasses to handle fragmentation! + // Thus blockSizePosition and blockSizeIndex are not always the same! + blockSizePosition = get_offset(); + blockSizeIndex = byteBuffer.position(); + } + + // Utility method which will hopefully decrease chunking complexity + // by allowing us to end_block and update chunk lengths without + // calling alignAndReserve. Otherwise, it's possible to get into + // recursive scenarios which lose the chunking state. + protected void writeLongWithoutAlign(int x) { + byteBuffer.putInt(x); + } + + @InfoMethod + private void inABlock() { + } + + @InfoMethod + private void blockSizePosition(int blockSize) { + } + + @InfoMethod + private void removingZeroLengthBlock() { + } + + @CdrWrite + public void end_block() { + if (!inBlock) { + return; + } + + inABlock(); + + inBlock = false; + + // Test to see if the block was of zero length + // If so, remove the block instead of ending it + // (This can happen if the last field written + // in a value was another value) + blockSizePosition(blockSizePosition); + + if (get_offset() == blockSizePosition) { + removingZeroLengthBlock(); + + // Need to assert that blockSizeIndex == bbwi.position()? REVISIT + + byteBuffer.position(byteBuffer.position() - 4); + blockSizeIndex = -1; + blockSizePosition = -1; + return; + } + + int oldSize = byteBuffer.position(); + byteBuffer.position(blockSizeIndex - 4); + + writeLongWithoutAlign(oldSize - blockSizeIndex); + + byteBuffer.position(oldSize); + blockSizeIndex = -1; + blockSizePosition = -1; + } + + public org.omg.CORBA.ORB orb() { + return orb; + } + + // ------------ End RMI related methods -------------------------- + + @CdrWrite + public final void write_boolean_array(boolean[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(length); + + for (int i = 0; i < length; i++) { + write_boolean(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + @CdrWrite + public final void write_char_array(char[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(length); + + for (int i = 0; i < length; i++) { + write_char(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + @CdrWrite + public void write_wchar_array(char[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(computeAlignment(2) + (length * 2)); + + for (int i = 0; i < length; i++) { + write_wchar(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + @CdrWrite + public final void write_short_array(short[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(computeAlignment(2) + (length * 2)); + + for (int i = 0; i < length; i++) { + write_short(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + public final void write_ushort_array(short[] value, int offset, int length) { + write_short_array(value, offset, length); + } + + @CdrWrite + public final void write_long_array(int[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(computeAlignment(4) + (length * 4)); + + for (int i = 0; i < length; i++) { + write_long(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + public final void write_ulong_array(int[] value, int offset, int length) { + write_long_array(value, offset, length); + } + + @CdrWrite + public final void write_longlong_array(long[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(computeAlignment(8) + (length * 8)); + + for (int i = 0; i < length; i++) { + write_longlong(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + public final void write_ulonglong_array(long[] value, int offset, int length) { + write_longlong_array(value, offset, length); + } + + @CdrWrite + public final void write_float_array(float[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(computeAlignment(4) + (length * 4)); + + for (int i = 0; i < length; i++) { + write_float(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + @CdrWrite + public final void write_double_array(double[] value, int offset, int length) { + if (value == null) { + throw wrapper.nullParam(); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkBegin(computeAlignment(8) + (length * 8)); + + for (int i = 0; i < length; i++) { + write_double(value[offset + i]); + } + + // This will only have an effect if we're already chunking + handleSpecialChunkEnd(); + } + + @CdrWrite + public final void write_any_array(org.omg.CORBA.Any value[], int offset, int length) { + for (int i = 0; i < length; i++) { + write_any(value[offset + i]); + } + } + + //--------------------------------------------------------------------// + // CDROutputStream state management. + // + + public void writeTo(java.io.OutputStream s) throws java.io.IOException { + byte[] tmpBuf = ORBUtility.getByteBufferArray(byteBuffer); + s.write(tmpBuf, 0, byteBuffer.position()); + } + + public void writeOctetSequenceTo(org.omg.CORBA.portable.OutputStream s) { + byte[] buf = ORBUtility.getByteBufferArray(byteBuffer); + s.write_long(byteBuffer.position()); + s.write_octet_array(buf, 0, byteBuffer.position()); + } + + public final int getSize() { + return byteBuffer.position(); + } + + public int getIndex() { + return byteBuffer.position(); + } + + public void setIndex(int value) { + byteBuffer.position(value); + } + + public ByteBuffer getByteBuffer() { + return byteBuffer; + } + + private void freeValueCache() { + if (valueCache != null) { + valueCache.done(); + } + } + + private void updateIndirectionTable(int indirection, + java.lang.Object key) { + + if (valueCache == null) { + valueCache = new CacheTable("Output valueCache", + orb, true); + } + valueCache.put(key, indirection); + } + + private boolean writeIndirectionIfPossible(final Serializable object) { + if (valueCache != null) { + final int indir = valueCache.getVal(object); + if (indir != -1) { + writeIndirection(INDIRECTION_TAG, indir); + return true; + } + } + + return false; + } + + @CdrWrite + private void write_repositoryId(String id) { + // Use an indirection if available + if (repositoryIdCache != null) { + int indir = repositoryIdCache.getVal(id); + if (indir != -1) { + writeIndirection(INDIRECTION_TAG, indir); + return; + } + } + + // Write it as a string. Note that we have already done the + // special case conversion of non-Latin-1 characters to escaped + // Latin-1 sequences in RepositoryId. + + // It's not a good idea to cache them now that we can have + // multiple code sets. + int indirection = writeString(id); + + // Add indirection for id to indirection table + if (repositoryIdCache == null) { + repositoryIdCache = new CacheTable("Output repositoryIdCache", orb, true); + } + repositoryIdCache.put(id, indirection); + } + + @CdrWrite + private void write_codebase(String str, int pos) { + Integer value = null; + if (codebaseCache != null) { + // ALTCODEBASE + // value = codebaseCache.getVal(str) ; + value = codebaseCache.get(str); + } + + if (value != null) { + writeIndirection(INDIRECTION_TAG, value); + } else { + write_string(str); + if (codebaseCache == null) { + // ALTCODEBASE + // codebaseCache = new CacheTable("Output codebaseCache",orb,true); + codebaseCache = new HashMap(); + } + + codebaseCache.put(str, pos); + } + } + + @CdrWrite + private int writeValueTag(boolean chunkIt, boolean useRepId, String codebase) { + int indirection; + if (chunkIt && !useRepId) { + if (codebase == null) { + write_long(repIdUtil.getStandardRMIChunkedNoRepStrId()); + indirection = get_offset() - 4; + } else { + write_long(repIdUtil.getCodeBaseRMIChunkedNoRepStrId()); + indirection = get_offset() - 4; + write_codebase(codebase, get_offset()); + } + } else if (chunkIt && useRepId) { + if (codebase == null) { + write_long(repIdUtil.getStandardRMIChunkedId()); + indirection = get_offset() - 4; + } else { + write_long(repIdUtil.getCodeBaseRMIChunkedId()); + indirection = get_offset() - 4; + write_codebase(codebase, get_offset()); + } + } else if (!useRepId) { + if (codebase == null) { + write_long(repIdUtil.getStandardRMIUnchunkedNoRepStrId()); + indirection = get_offset() - 4; + } else { + write_long(repIdUtil.getCodeBaseRMIUnchunkedNoRepStrId()); + indirection = get_offset() - 4; + write_codebase(codebase, get_offset()); + } + } else { + if (codebase == null) { + write_long(repIdUtil.getStandardRMIUnchunkedId()); + indirection = get_offset() - 4; + } else { + write_long(repIdUtil.getCodeBaseRMIUnchunkedId()); + indirection = get_offset() - 4; + write_codebase(codebase, get_offset()); + } + } + return indirection; + } + + @SuppressWarnings({"deprecation"}) + @CdrWrite + private void writeIDLValue(Serializable object, String repID) { + if (object instanceof StreamableValue) { + ((StreamableValue) object)._write(parent); + } else if (object instanceof CustomValue) { + ((CustomValue) object).marshal(parent); + } else { + BoxedValueHelper helper = Utility.getHelper(object.getClass(), null, repID); + boolean isCustom = false; + + if (helper instanceof com.sun.org.omg.CORBA.portable.ValueHelper && + object instanceof CustomMarshal) { + try { + if (((com.sun.org.omg.CORBA.portable.ValueHelper) helper) + .get_type().type_modifier() == VM_CUSTOM.value) { + isCustom = true; + } + } catch (BadKind ex) { + throw wrapper.badTypecodeForCustomValue(ex); + } + } + + if (isCustom) { + ((CustomMarshal) object).marshal(parent); + } else { + helper.write_value(parent, object); + } + } + } + + // Handles end tag compaction... + @CdrWrite + private void writeEndTag(boolean chunked) { + if (chunked) { + if (get_offset() == end_flag_position) { + if (byteBuffer.position() == end_flag_index) { + // We are exactly at the same position and index as the + // end of the last end tag. Thus, we can back up over it + // and compact the tags. + byteBuffer.position(byteBuffer.position() - 4); + } else { // reg - is this even possible any more? + // Special case in which we're at the beginning of a new + // fragment, but the position is the same. We can't back up, + // so we just write the new end tag without compaction. This + // occurs when a value ends and calls start_block to open a + // continuation chunk, but it's called at the very end of + // a fragment. + } + } + + writeNestingLevel(); + + // Remember the last index and position. + // These are only used when chunking. + end_flag_index = byteBuffer.position(); + end_flag_position = get_offset(); + + chunkedValueNestingLevel++; + } + + // Increment the nesting level + end_flag++; + } + + /** + * Handles ORB versioning of the end tag. Should only + * be called if chunking. + *

    + * If talking to our older ORBs (Standard Extension, + * Kestrel, and Ladybird), write the end flag that takes + * into account all enclosing valuetypes. + *

    + * If talking a newer or foreign ORB, or if the orb + * instance is null, write the end flag that only takes + * into account the enclosing chunked valuetypes. + */ + @CdrWrite + private void writeNestingLevel() { + if (orb == null || + ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) || + ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) { + + write_long(chunkedValueNestingLevel); + } else { + write_long(end_flag); + } + } + + @CdrWrite + private void writeClass(String repository_id, Class clz, + ClassInfoCache.ClassInfo cinfo) { + + if (repository_id == null) { + repository_id = repIdStrs.getClassDescValueRepId(); + } + + // Write value_tag + int indirection = writeValueTag(mustChunk, true, null); + updateIndirectionTable(indirection, clz); + + write_repositoryId(repository_id); + + startValueChunk(mustChunk); + writeClassBody(clz, cinfo); + endValueChunk(mustChunk); + } + + // Pre-Merlin/J2EE 1.3 ORBs wrote the repository ID + // and codebase strings in the wrong order. This handles + // backwards compatibility. + @CdrWrite + private void writeClassBody(Class clz, ClassInfoCache.ClassInfo cinfo) { + if (orb == null || + ORBVersionFactory.getFOREIGN().equals(orb.getORBVersion()) || + ORBVersionFactory.getNEWER().compareTo(orb.getORBVersion()) <= 0) { + + write_value(getCodebase(clz)); + write_value(repIdStrs.createForAnyType(clz, cinfo)); + } else { + write_value(repIdStrs.createForAnyType(clz, cinfo)); + write_value(getCodebase(clz)); + } + } + + @CdrWrite + private void writeIDLEntity(IDLEntity object) { + // _REVISIT_ could check to see whether chunking really needed + mustChunk = true; + + String repository_id = repIdStrs.createForJavaType(object); + final Class clazz = object.getClass(); + String codebase = getCodebase(clazz); + + int indirection = writeValueTag(true, true, codebase); + updateIndirectionTable(indirection, object); + write_repositoryId(repository_id); + + // Write Value chunk + startValueChunk(true); + + // Write the IDLEntity using reflection + try { + ClassLoader clazzLoader = (clazz == null ? null : clazz.getClassLoader()); + final Class helperClass = Utility.loadClassForClass( + clazz.getName() + "Helper", codebase, clazzLoader, + clazz, clazzLoader); + + // getDeclaredMethod requires RuntimePermission accessDeclaredMembers + // if a different class loader is used (even though the javadoc says otherwise) + Method writeMethod; + try { + writeMethod = AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Method run() throws NoSuchMethodException { + return helperClass.getDeclaredMethod(kWriteMethod, + org.omg.CORBA.portable.OutputStream.class, clazz); + } + } + ); + } catch (PrivilegedActionException pae) { + // this gets caught below + throw (NoSuchMethodException) pae.getException(); + } + writeMethod.invoke(null, parent, object); + } catch (Exception exc) { + throw wrapper.errorInvokingHelperWrite(exc); + } + + endValueChunk(true); + } + + /* DataOutputStream methods */ + + @CdrWrite + public void write_Abstract(java.lang.Object value) { + write_abstract_interface(value); + } + + @CdrWrite + public void write_Value(java.io.Serializable value) { + write_value(value); + } + + // This will stay a custom add-on until the java-rtf issue is resolved. + // Then it should be declared in org.omg.CORBA.portable.OutputStream. + // + // Pads the string representation of bigDecimal with zeros to fit the given + // digits and scale before it gets written to the stream. + public void write_fixed(java.math.BigDecimal bigDecimal, short digits, short scale) { + String string = bigDecimal.toString(); + String integerPart; + String fractionPart; + StringBuffer stringBuffer; + + // Get rid of the sign + if (string.charAt(0) == '-' || string.charAt(0) == '+') { + string = string.substring(1); + } + + // Determine integer and fraction parts + int dotIndex = string.indexOf('.'); + if (dotIndex == -1) { + integerPart = string; + fractionPart = null; + } else if (dotIndex == 0) { + integerPart = null; + fractionPart = string; + } else { + integerPart = string.substring(0, dotIndex); + fractionPart = string.substring(dotIndex + 1); + } + + // Pad both parts with zeros as necessary + stringBuffer = new StringBuffer(digits); + if (fractionPart != null) { + stringBuffer.append(fractionPart); + } + while (stringBuffer.length() < scale) { + stringBuffer.append('0'); + } + if (integerPart != null) { + stringBuffer.insert(0, integerPart); + } + while (stringBuffer.length() < digits) { + stringBuffer.insert(0, '0'); + } + + // This string contains no sign or dot + this.write_fixed(stringBuffer.toString(), bigDecimal.signum()); + } + + // This method should be remove by the java-rtf issue. + // Right now the scale and digits information of the type code is lost. + public void write_fixed(java.math.BigDecimal bigDecimal) { + // This string might contain sign and/or dot + this.write_fixed(bigDecimal.toString(), bigDecimal.signum()); + } + + // The string may contain a sign and dot + public void write_fixed(String string, int signum) { + int stringLength = string.length(); + // Each octet contains (up to) two decimal digits + byte doubleDigit = 0; + char ch; + byte digit; + + // First calculate the length of the string without optional sign and dot + int numDigits = 0; + for (int i = 0; i < stringLength; i++) { + ch = string.charAt(i); + if (ch == '-' || ch == '+' || ch == '.') { + continue; + } + numDigits++; + } + for (int i = 0; i < stringLength; i++) { + ch = string.charAt(i); + if (ch == '-' || ch == '+' || ch == '.') { + continue; + } + digit = (byte) Character.digit(ch, 10); + if (digit == -1) { + throw wrapper.badDigitInFixed(); + } + // If the fixed type has an odd number of decimal digits, + // then the representation begins with the first (most significant) digit. + // Otherwise, this first half-octet is all zero, and the first digit + // is in the second half-octet. + if (numDigits % 2 == 0) { + doubleDigit |= digit; + this.write_octet(doubleDigit); + doubleDigit = 0; + } else { + doubleDigit |= (digit << 4); + } + numDigits--; + } + // The sign configuration, in the last half-octet of the representation, + // is 0xD for negative numbers and 0xC for positive and zero values + if (signum == -1) { + doubleDigit |= 0xd; + } else { + doubleDigit |= 0xc; + } + this.write_octet(doubleDigit); + } + + private final static String _id = "IDL:omg.org/CORBA/DataOutputStream:1.0"; + private final static String[] _ids = {_id}; + + public String[] _truncatable_ids() { + if (_ids == null) { + return null; + } + + return _ids.clone(); + } + + public void writeIndirection(int tag, int posIndirectedTo) { + // Must ensure that there are no chunks between the tag + // and the actual indirection value. This isn't talked about + // in the spec, but seems to cause headaches in our code. + // At the very least, this method isolates the indirection code + // that was duplicated so often. + + handleSpecialChunkBegin(computeAlignment(4) + 8); + + // write indirection tag + write_long(tag); + + // write indirection + // Use parent.getRealIndex() so that it can be overridden by TypeCodeOutputStreams +/* + System.out.println("CDROutputStream_1_0 writing indirection pos " + posIndirectedTo + + " - real index " + parent.getRealIndex(get_offset()) + " = " + + (posIndirectedTo - parent.getRealIndex(get_offset()))); +*/ + write_long(posIndirectedTo - parent.getRealIndex(get_offset())); + + handleSpecialChunkEnd(); + } + + protected CodeSetConversion.CTBConverter getCharConverter() { + if (charConverter == null) { + charConverter = parent.createCharCTBConverter(); + } + + return charConverter; + } + + protected CodeSetConversion.CTBConverter getWCharConverter() { + if (wcharConverter == null) { + wcharConverter = parent.createWCharCTBConverter(); + } + + return wcharConverter; + } + + void alignOnBoundary(int octetBoundary) { + alignAndReserve(octetBoundary, 0); + } + + @InfoMethod + private void startValueInfo(String repId, int offset, int position) { + } + + @CdrWrite + public void start_value(String rep_id) { + startValueInfo(rep_id, get_offset(), byteBuffer.position()); + + if (inBlock) { + end_block(); + } + + // Write value_tag + writeValueTag(true, true, null); + + // Write rep. id + write_repositoryId(rep_id); + + // Write Value chunk + end_flag--; + chunkedValueNestingLevel--; + + // Make sure to chunk the custom data + start_block(); + } + + @InfoMethod + private void mustChunk(boolean flag) { + } + + @CdrWrite + public void end_value() { + end_block(); + + writeEndTag(true); + + // Check to see if we need to start another block for a + // possible outer value. Since we're in the stream + // format 2 custom type contained by another custom + // type, mustChunk should always be true. + // + // Here's why we need to open a continuation chunk: + // + // We need to enclose the default data of the + // next subclass down in chunks. There won't be + // an end tag separating the superclass optional + // data and the subclass's default data. + + mustChunk(mustChunk); + + if (mustChunk) { + start_block(); + } + } + + @Override + @CdrWrite + public void close() throws IOException { + // tell BufferManagerWrite to release any ByteBuffers + getBufferManager().close(); + + if (byteBuffer != null) { + + // release this stream's ByteBuffer to the pool + ByteBufferPool byteBufferPool = orb.getByteBufferPool(); + byteBufferPool.releaseByteBuffer(byteBuffer); + byteBuffer = null; + } + } + + void dereferenceBuffer() { + byteBuffer = null; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_1.java new file mode 100644 index 000000000..54aafc142 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_1.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +public class CDROutputStream_1_1 extends CDROutputStream_1_0 +{ + // This is used to keep indirections working across fragments. When added + // to the current bbwi.position(), the result is the current position + // in the byte stream without any fragment headers. + // + // It is equal to the following: + // + // n = number of buffers (0 is original buffer, 1 is first fragment, etc) + // + // n == 0, fragmentOffset = 0 + // + // n > 0, fragmentOffset + // = sum i=[1,n] { bbwi_i-1_.size - buffer i header length } + // + protected int fragmentOffset = 0; + + @Override + protected void alignAndReserve(int align, int n) { + + // Notice that in 1.1, we won't end a fragment with + // alignment padding. We also won't guarantee that + // our fragments end on evenly divisible 8 byte + // boundaries. There may be alignment + // necessary with the header of the next fragment + // since the header isn't aligned on an 8 byte + // boundary, so we have to calculate it twice. + + int alignment = computeAlignment(align); + + if (byteBuffer.position() + n + alignment > byteBuffer.limit()) { + grow(align, n); + + // Must recompute the alignment after a grow. + // In the case of fragmentation, the alignment + // calculation may no longer be correct. + + // People shouldn't be able to set their fragment + // sizes so small that the fragment header plus + // this alignment fills the entire buffer. + alignment = computeAlignment(align); + } + + byteBuffer.position(byteBuffer.position() + alignment); + } + + @Override + protected void grow(int align, int n) { + // Save the current size for possible post-fragmentation calculation + int oldSize = byteBuffer.position(); + + byteBuffer = bufferManagerWrite.overflow(byteBuffer, n); + + // At this point, if we fragmented, we should have a ByteBuffer + // with the fragment header already marshalled. The size and length fields + // should be updated accordingly, and the fragmented flag should be set. + if (bufferManagerWrite.isFragmentOnOverflow()) { + + // Update fragmentOffset so indirections work properly. + // At this point, oldSize is the entire length of the + // previous buffer. bbwi.position() is the length of the + // fragment header of this buffer. + fragmentOffset += (oldSize - byteBuffer.position()); + } + } + + @Override + public int get_offset() { + return byteBuffer.position() + fragmentOffset; + } + + @Override + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_1; + } + + @Override + public void write_wchar(char x) + { + // In GIOP 1.1, interoperability with wchar is limited + // to 2 byte fixed width encodings. CORBA formal 99-10-07 15.3.1.6. + // Note that the following code prohibits UTF-16 with a byte + // order marker (which would result in 4 bytes). + CodeSetConversion.CTBConverter converter = getWCharConverter(); + + converter.convert(x); + + if (converter.getNumBytes() != 2) + throw wrapper.badGiop11Ctb(); + + alignAndReserve(converter.getAlignment(), + converter.getNumBytes()); + + parent.write_octet_array(converter.getBytes(), + 0, + converter.getNumBytes()); + } + + @Override + public void write_wstring(String value) + { + if (value == null) { + throw wrapper.nullParam(); + } + + // The length is the number of code points (which are 2 bytes each) + // including the 2 byte null. See CORBA formal 99-10-07 15.3.2.7. + + int len = value.length() + 1; + + write_long(len); + + CodeSetConversion.CTBConverter converter = getWCharConverter(); + + converter.convert(value); + + internalWriteOctetArray(converter.getBytes(), 0, converter.getNumBytes()); + + // Write the 2 byte null ending + write_short((short)0); + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_2.java new file mode 100644 index 000000000..0b4fc3e19 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CDROutputStream_1_2.java @@ -0,0 +1,365 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.trace.CdrWrite; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@CdrWrite +public class CDROutputStream_1_2 extends CDROutputStream_1_1 +{ + // There's a situation with chunking with fragmentation + // in which the alignment for a primitive value is needed + // to fill fragment N, but the primitive won't fit so + // must go into fragment N + 1. The behavior is the same + // as that for specialChunks. + // + // Unfortunately, given the current code, we can't reuse + // specialChunk. If you wrap each of the following + // write calls with handleSpecialChunkBegin/End, you + // will lose your state because the primitive calls will + // change the variables, etc. + // + // All of the CDR code should be rewritten moving chunking + // to a different level, perhaps in the buffer managers. + // We want to move to a compositional model rather than + // using inheritance. + // + // Note that in the grow case, chunks are _NOT_ closed + // at grow points, now. + // + // **** NOTE **** + // Since we will not support valuetypes with GIOP 1.1, that + // also means we do not support chunking there. + // + protected boolean primitiveAcrossFragmentedChunk = false; + + // Used in chunking. Here's how this works: + // + // When chunking and writing an array of primitives, a string, or a + // wstring, _AND_ it won't fit in the buffer do the following. (As + // you can see, this is a very "special" chunk.) + // + // 1. Write the length of the chunk including the array length + // 2. Set specialChunk to true + // 3 applies to ALL chunking: + // 3. In grow, if we need to fragment and specialChunk is false + // a) call end_block + // b) fragment + // Now back to the array only case: + // [write the data] + // 4. if specialChunk is true + // a) Close the chunk + // b) Set specialChunk to false + + protected boolean specialChunk = false; + + // Indicates whether the header should be padded. In GIOP 1.2 and above, the + // body must be aligned on a 8-octet boundary, and so the header needs to be + // padded appropriately. However, if there is no body to a request or reply + // message, there is no need to pad the header, in the unfragmented case. + private boolean headerPadding; + + @InfoMethod + private void specialChunkCase() { } + + @CdrWrite + @Override + protected void handleSpecialChunkBegin(int requiredSize) { + // If we're chunking and the item won't fit in the buffer + if (inBlock && requiredSize + byteBuffer.position() > byteBuffer.limit()) { + specialChunkCase() ; + + // Duplicating some code from end_block. Compute + // and write the total chunk length. + + int oldSize = byteBuffer.position(); + byteBuffer.position(blockSizeIndex - 4); + + //write_long(oldSize - blockSizeIndex); + writeLongWithoutAlign((oldSize - blockSizeIndex) + requiredSize); + byteBuffer.position(oldSize); + + // Set the special flag so we don't end the chunk when + // we fragment + specialChunk = true; + } + } + + @CdrWrite + @Override + protected void handleSpecialChunkEnd() { + // If we're in a chunk and the item spanned fragments + if (inBlock && specialChunk) { + specialChunkCase(); + + // This is unnecessary, but I just want to show that + // we're done with the current chunk. (the end_block + // call is inappropriate here) + inBlock = false; + blockSizeIndex = -1; + blockSizePosition = -1; + + // Start a new chunk since we fragmented during the item. + // Thus, no one can go back to add more to the chunk length + start_block(); + + // Now turn off the flag so we go back to the normal + // behavior of closing a chunk when we fragment and + // reopening afterwards. + specialChunk = false; + } + } + + // Called after writing primitives + @CdrWrite + private void checkPrimitiveAcrossFragmentedChunk() + { + if (primitiveAcrossFragmentedChunk) { + primitiveAcrossFragmentedChunk = false; + + inBlock = false; + + // It would be nice to have a StreamPosition + // abstraction if we could avoid allocation + // overhead. + blockSizeIndex = -1; + blockSizePosition = -1; + + // Start a new chunk + start_block(); + } + } + + + @Override + public void write_octet(byte x) { + super.write_octet(x); + checkPrimitiveAcrossFragmentedChunk(); + } + + @Override + public void write_short(short x) { + super.write_short(x); + checkPrimitiveAcrossFragmentedChunk(); + } + + @Override + public void write_long(int x) { + super.write_long(x); + checkPrimitiveAcrossFragmentedChunk(); + } + + @Override + public void write_longlong(long x) { + super.write_longlong(x); + checkPrimitiveAcrossFragmentedChunk(); + } + + // Called by RequestMessage_1_2 or ReplyMessage_1_2 classes only. + @Override + void setHeaderPadding(boolean headerPadding) { + this.headerPadding = headerPadding; + } + + @Override + @CdrWrite + protected void alignAndReserve(int align, int n) { + + // headerPadding bit is set by the write operation of RequestMessage_1_2 + // or ReplyMessage_1_2 classes. When set, the very first body write + // operation (from the stub code) would trigger an alignAndReserve + // method call, that would in turn add the appropriate header padding, + // such that the body is aligned on a 8-octet boundary. The padding + // is required for GIOP versions 1.2 and above, only if body is present. + if (headerPadding == true) { + headerPadding = false; + alignOnBoundary(ORBConstants.GIOP_12_MSG_BODY_ALIGNMENT); + } + + // In GIOP 1.2, we always end fragments at our + // fragment size, which is an "evenly divisible + // 8 byte boundary" (aka divisible by 16). A fragment can + // end with appropriate alignment padding, but no padding + // is needed with respect to the next GIOP fragment + // header since it ends on an 8 byte boundary. + + byteBuffer.position(byteBuffer.position() + computeAlignment(align)); + + if (byteBuffer.position() + n > byteBuffer.limit()) + grow(align, n); + } + + @InfoMethod + private void outOfSequenceWrite() { } + + @InfoMethod + private void handlingFragmentCase() { } + + + @Override + @CdrWrite + protected void grow(int align, int n) { + + // Save the current size for possible post-fragmentation calculation + int oldSize = byteBuffer.position(); + + // See notes where specialChunk is defined, as well as the + // above notes for primitiveAcrossFragmentedChunk. + // + // If we're writing a primitive and chunking, we need to update + // the chunk length to include the length of the primitive (unless + // this complexity is handled by specialChunk). + // + // Note that this is wasted processing in the grow case, but that + // we don't actually close the chunk in that case. + boolean handleChunk = (inBlock && !specialChunk); + if (handleChunk) { + int oldIndex = byteBuffer.position(); + + byteBuffer.position(blockSizeIndex - 4); + + writeLongWithoutAlign((oldIndex - blockSizeIndex) + n); + + byteBuffer.position(oldIndex); + } + + byteBuffer = bufferManagerWrite.overflow(byteBuffer, n); + + // At this point, if we fragmented, we should have a ByteBuffer + // with the fragment header already marshaled. The buflen and position + // should be updated accordingly. + if (bufferManagerWrite.isFragmentOnOverflow()) { + + // Update fragmentOffset so indirections work properly. + // At this point, oldSize is the entire length of the + // previous buffer. bbwi.position() is the length of the + // fragment header of this buffer. + fragmentOffset += (oldSize - byteBuffer.position()); + + // We just fragmented, and need to signal that we should + // start a new chunk after writing the primitive. + if (handleChunk) + primitiveAcrossFragmentedChunk = true; + } + } + + @Override + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_2; + } + + @Override + public void write_wchar(char x) + { + // In GIOP 1.2, a wchar is encoded as an unsigned octet length + // followed by the octets of the converted wchar. This is good, + // but it causes problems with our chunking code. We don't + // want that octet to get put in a different chunk at the end + // of the previous fragment. + // + // Ensure that this won't happen by overriding write_wchar_array + // and doing our own handleSpecialChunkBegin/End here. + CodeSetConversion.CTBConverter converter = getWCharConverter(); + + converter.convert(x); + + handleSpecialChunkBegin(1 + converter.getNumBytes()); + + write_octet((byte)converter.getNumBytes()); + + byte[] result = converter.getBytes(); + + // Write the bytes without messing with chunking + // See CDROutputStream_1_0 + internalWriteOctetArray(result, 0, converter.getNumBytes()); + + handleSpecialChunkEnd(); + } + + @Override + public void write_wchar_array(char[] value, int offset, int length) + { + if (value == null) { + throw wrapper.nullParam(); + } + + CodeSetConversion.CTBConverter converter = getWCharConverter(); + + // Unfortunately, because of chunking, we have to convert the + // entire char[] to a byte[] array first so we can know how + // many bytes we're writing ahead of time. You can't split + // an array of primitives into multiple chunks. + int totalNumBytes = 0; + + // Remember that every wchar starts with an octet telling + // its length. The buffer size is an upper bound estimate. + int maxLength = (int)Math.ceil(converter.getMaxBytesPerChar() * length); + byte[] buffer = new byte[maxLength + length]; + + for (int i = 0; i < length; i++) { + // Convert one wchar + converter.convert(value[offset + i]); + + // Make sure to add the octet length + buffer[totalNumBytes++] = (byte)converter.getNumBytes(); + + // Copy it into our buffer + System.arraycopy(converter.getBytes(), 0, + buffer, totalNumBytes, + converter.getNumBytes()); + + totalNumBytes += converter.getNumBytes(); + } + + // Now that we know the total length, we can deal with chunking. + // Note that we don't have to worry about alignment since they're + // just octets. + handleSpecialChunkBegin(totalNumBytes); + + // Must use totalNumBytes rather than buffer.length since the + // buffer.length is only the upper bound estimate. + internalWriteOctetArray(buffer, 0, totalNumBytes); + + handleSpecialChunkEnd(); + } + + @Override + public void write_wstring(String value) { + if (value == null) { + throw wrapper.nullParam(); + } + + // In GIOP 1.2, wstrings are not terminated by a null. The + // length is the number of octets in the converted format. + // A zero length string is represented with the 4 byte length + // value of 0. + if (value.length() == 0) { + write_long(0); + return; + } + + CodeSetConversion.CTBConverter converter = getWCharConverter(); + + converter.convert(value); + + handleSpecialChunkBegin(computeAlignment(4) + 4 + converter.getNumBytes()); + + write_long(converter.getNumBytes()); + + // Write the octet array without tampering with chunking + internalWriteOctetArray(converter.getBytes(), 0, converter.getNumBytes()); + + handleSpecialChunkEnd(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CachedCodeBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CachedCodeBase.java new file mode 100644 index 000000000..09f69a71a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CachedCodeBase.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription; + +import com.sun.org.omg.SendingContext.CodeBase; +import com.sun.org.omg.SendingContext.CodeBaseHelper; +import com.sun.org.omg.SendingContext._CodeBaseImplBase; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.orb.ORB ; +import java.util.Hashtable; + +/** + * Provides the reading side with a per connection cache of + * info obtained via calls to the remote CodeBase. + * + * Previously, most of this was in IIOPConnection. + * + * Features: + * Delays cache creation unless used + * Postpones remote calls until necessary + * Handles creating obj ref from IOR + * Maintains caches for the following maps: + * CodeBase IOR to obj ref (global) + * RepId to implementation URL(s) + * RepId to remote FVD + * RepId to superclass type list + * + * Needs cache management. + */ +public class CachedCodeBase extends _CodeBaseImplBase +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private Hashtable implementations ; + private Hashtable fvds ; + private Hashtable bases ; + + private volatile CodeBase delegate; + private Connection conn; + + private static Object iorMapLock = new Object() ; + private static Hashtable iorMap = + new Hashtable(); + + public static synchronized void cleanCache( ORB orb ) { + synchronized (iorMapLock) { + for (IOR ior : iorMap.keySet()) { + if (ior.getORB() == orb) { + iorMap.remove( ior ) ; + } + } + } + } + + public CachedCodeBase(Connection connection) { + conn = connection; + } + + public com.sun.org.omg.CORBA.Repository get_ir () { + return null; + } + + public synchronized String implementation (String repId) { + String urlResult = null; + + if (implementations == null) + implementations = new Hashtable(); + else + urlResult = implementations.get(repId); + + if (urlResult == null && connectedCodeBase()) { + urlResult = delegate.implementation(repId); + + if (urlResult != null) + implementations.put(repId, urlResult); + } + + return urlResult; + } + + public synchronized String[] implementations (String[] repIds) { + String[] urlResults = new String[repIds.length]; + + for (int i = 0; i < urlResults.length; i++) + urlResults[i] = implementation(repIds[i]); + + return urlResults; + } + + public synchronized FullValueDescription meta (String repId) { + FullValueDescription result = null; + + if (fvds == null) + fvds = new Hashtable(); + else + result = fvds.get(repId); + + if (result == null && connectedCodeBase()) { + result = delegate.meta(repId); + + if (result != null) + fvds.put(repId, result); + } + + return result; + } + + public synchronized FullValueDescription[] metas (String[] repIds) { + FullValueDescription[] results + = new FullValueDescription[repIds.length]; + + for (int i = 0; i < results.length; i++) + results[i] = meta(repIds[i]); + + return results; + } + + public synchronized String[] bases (String repId) { + + String[] results = null; + + if (bases == null) + bases = new Hashtable(); + else + results = bases.get(repId); + + if (results == null && connectedCodeBase()) { + results = delegate.bases(repId); + + if (results != null) + bases.put(repId, results); + } + + return results; + } + + // Ensures that we've used the connection's IOR to create + // a valid CodeBase delegate. If this returns false, then + // it is not valid to access the delegate. + private synchronized boolean connectedCodeBase() { + if (delegate != null) + return true; + + if (conn.getCodeBaseIOR() == null) { + // The delegate was null, so see if the connection's + // IOR was set. If so, then we just need to connect + // it. Otherwise, there is no hope of checking the + // remote code base. That could be a bug if the + // service context processing didn't occur, or it + // could be that we're talking to a foreign ORB which + // doesn't include this optional service context. + + wrapper.codeBaseUnavailable( conn ) ; + + return false; + } + + synchronized(iorMapLock) { + // Do we have a reference initialized by another connection? + delegate = iorMap.get( conn.getCodeBaseIOR() ); + if (delegate != null) + return true; + + // Connect the delegate and update the cache + delegate = CodeBaseHelper.narrow( getObjectFromIOR() ); + + // Save it for the benefit of other connections + iorMap.put( conn.getCodeBaseIOR(), delegate ); + } + + // It's now safe to use the delegate + return true; + } + + private org.omg.CORBA.Object getObjectFromIOR() { + return CDRInputStream_1_0.internalIORToObject( + conn.getCodeBaseIOR(), null /*stubFactory*/, conn.getBroker()); + } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetCache.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetCache.java new file mode 100644 index 000000000..be4694611 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetCache.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.util.WeakHashMap; + +/** + * Thread local cache of sun.io code set converters for performance. + * + * The thread local class contains a single reference to a Map[] + * containing two WeakHashMaps. One for CharsetEncoders and + * one for CharsetDecoders. Constants are defined for indexing. + * + * This is used internally by CodeSetConversion. + */ +class CodeSetCache +{ + private ThreadLocal> ctbMapLocal = + new ThreadLocal>() { + protected WeakHashMap initialValue() { + return new WeakHashMap() ; + } + } ; + + private ThreadLocal> btcMapLocal = + new ThreadLocal>() { + protected WeakHashMap initialValue() { + return new WeakHashMap() ; + } + } ; + + /** + * Retrieve a CharsetDecoder from the Map using the given key. + */ + CharsetDecoder getByteToCharConverter(String key) { + return btcMapLocal.get().get( key ) ; + } + + /** + * Retrieve a CharsetEncoder from the Map using the given key. + */ + CharsetEncoder getCharToByteConverter(String key) { + return ctbMapLocal.get().get( key ) ; + } + + /** + * Stores the given CharsetDecoder in the thread local cache, + * and returns the same converter. + */ + CharsetDecoder setConverter(String key, CharsetDecoder converter) { + btcMapLocal.get().put( key, converter ) ; + return converter; + } + + /** + * Stores the given CharsetEncoder in the thread local cache, + * and returns the same converter. + */ + CharsetEncoder setConverter(String key, CharsetEncoder converter) { + ctbMapLocal.get().put( key, converter ) ; + return converter; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetComponentInfo.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetComponentInfo.java new file mode 100644 index 000000000..463a19f1b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetComponentInfo.java @@ -0,0 +1,324 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.util.StringTokenizer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +public final class CodeSetComponentInfo { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + /** + * CodeSetComponent is part of an IOR multi-component profile. Two + * instances constitute a CodeSetComponentInfo (one for char and one + * for wchar data) + */ + public static final class CodeSetComponent { + int nativeCodeSet; + int[] conversionCodeSets; + + @Override + public boolean equals( Object obj ) + { + if (this == obj) + return true ; + + if (!(obj instanceof CodeSetComponent)) + return false ; + + CodeSetComponent other = (CodeSetComponent)obj ; + + return (nativeCodeSet == other.nativeCodeSet) && + Arrays.equals( conversionCodeSets, other.conversionCodeSets ) ; + } + + @Override + public int hashCode() + { + int result = nativeCodeSet ; + for (int ctr=0; ctr conversionList = new ArrayList(10); + + // Now process the other values as part of the + // conversion code set list. + while (stok.hasMoreTokens()) { + + // decode allows us to specify hex, decimal, etc + Integer value = Integer.decode(stok.nextToken()); + + if (OSFCodeSetRegistry.lookupEntry(value.intValue()) == null) + throw wrapper.unknownConversionCodeSet( value ) ; + + conversionList.add(value); + } + + conversionInts = new int[conversionList.size()]; + + for (int i = 0; i < conversionInts.length; i++) + conversionInts[i] = ((Integer)conversionList.get(i)).intValue(); + + } catch (NumberFormatException nfe) { + throw wrapper.invalidCodeSetNumber( nfe ) ; + } catch (NoSuchElementException nsee) { + throw wrapper.invalidCodeSetString( nsee, str ) ; + } + + // Otherwise return the CodeSetComponent representing + // the given values + return new CodeSetComponent(nativeSet, conversionInts); + } + + /** + * Code sets for local cases without a connection. + */ + public static final CodeSetContext LOCAL_CODE_SETS + = new CodeSetContext(OSFCodeSetRegistry.ISO_8859_1.getNumber(), + OSFCodeSetRegistry.UTF_16.getNumber()); +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetConversion.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetConversion.java new file mode 100644 index 000000000..eac243ac4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/CodeSetConversion.java @@ -0,0 +1,749 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteOrder; +import java.util.Map; +import java.util.HashMap; +import java.util.WeakHashMap; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.IllegalCharsetNameException; +import java.nio.charset.MalformedInputException; +import java.nio.charset.UnsupportedCharsetException; +import java.nio.charset.UnmappableCharacterException; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; + +/** + * Collection of classes, interfaces, and factory methods for + * CORBA code set conversion. + * + * This is mainly used to shield other code from the sun.io + * converters which might change, as well as provide some basic + * translation from conversion to CORBA error exceptions. Some + * extra work is required here to facilitate the way CORBA + * says it uses UTF-16 as of the 00-11-03 spec. + * + * REVISIT - Since the nio.Charset and nio.Charset.Encoder/Decoder + * use NIO ByteBuffer and NIO CharBuffer, the interaction + * and interface between this class and the CDR streams + * should be looked at more closely for optimizations to + * avoid unnecessary copying of data between char[] & + * CharBuffer and byte[] & ByteBuffer, especially + * DirectByteBuffers. + * + */ +public class CodeSetConversion +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + /** + * Abstraction for char to byte conversion. + * + * Must be used in the proper sequence: + * + * 1) convert + * 2) Optional getNumBytes and/or getAlignment (if necessary) + * 3) getBytes (see warning) + */ + public abstract static class CTBConverter + { + // Perform the conversion of the provided char or String, + // allowing the caller to query for more information + // before writing. + public abstract void convert(char chToConvert); + public abstract void convert(String strToConvert); + + // How many bytes resulted from the conversion? + public abstract int getNumBytes(); + + // What's the maximum number of bytes per character? + public abstract float getMaxBytesPerChar(); + + // What byte boundary should the stream align to before + // calling writeBytes? For instance, a fixed width + // encoding with 2 bytes per char in a stream which + // doesn't encapsulate the char's bytes should align + // on a 2 byte boundary. (Ex: UTF16 in GIOP1.1) + // + // Note: This has no effect on the converted bytes. It + // is just information available to the caller. + public abstract int getAlignment(); + + // Get the resulting bytes. Warning: You must use getNumBytes() + // to determine the end of the data in the byte array instead + // of array.length! The array may be used internally, so don't + // save references. + public abstract byte[] getBytes(); + } + + /** + * Abstraction for byte to char conversion. + */ + public abstract static class BTCConverter { + + // Called after getChars to determine the true size of the + // converted array. + public abstract int getNumChars(); + + // Perform the conversion using length bytes from the given + // input stream. Warning: You must use getNumChars() to + // determine the correct length of the resulting array. + // The same array may be used internally over multiple + // calls. + public abstract char[] getChars(byte[] bytes, int offset, int length); + public abstract char[] getChars(ByteBuffer byteBuffer, int offset, int length); + + } + + /** + * Implementation of CTBConverter which uses a nio.Charset.CharsetEncoder + * to do the real work. Handles translation of exceptions to the + * appropriate CORBA versions. + */ + private class JavaCTBConverter extends CTBConverter + { + // nio.Charset.CharsetEncoder actually does the work here + // have to use it directly rather than through String's interface + // because we want to know when errors occur during the conversion. + private CharsetEncoder ctb; + + // Proper alignment for this type of converter. For instance, + // ASCII has alignment of 1 (1 byte per char) but UTF16 has + // alignment of 2 (2 bytes per char) + private int alignment; + + // Char buffer to hold the input. + private char[] chars = null; + + // How many bytes are generated from the conversion? + private int numBytes = 0; + + // How many characters were converted (temporary variable + // for cross method communication) + private int numChars = 0; + + // ByteBuffer holding the converted input. This is necessary + // since we have to do calculations that require the conversion + // before writing the array to the stream. + private ByteBuffer buffer; + + WeakHashMap cacheEncoder = new WeakHashMap(); + + public JavaCTBConverter(OSFCodeSetRegistry.Entry codeset, + int alignmentForEncoding) { + + try { + ctb = cache.getCharToByteConverter(codeset.getName()); + if (ctb == null) { + Charset tmpCharset = Charset.forName(codeset.getName()); + ctb = tmpCharset.newEncoder(); + cache.setConverter(codeset.getName(), ctb); + } + } catch(IllegalCharsetNameException icne) { + + // This can only happen if one of our Entries has + // an invalid name. + throw wrapper.invalidCtbConverterName(icne,codeset.getName()); + } catch(UnsupportedCharsetException ucne) { + + // This can only happen if one of our Entries has + // an unsupported name. + throw wrapper.invalidCtbConverterName(ucne,codeset.getName()); + } + + alignment = alignmentForEncoding; + } + + public final float getMaxBytesPerChar() { + return ctb.maxBytesPerChar(); + } + + public void convert(char chToConvert) { + if (chars == null) + chars = new char[1]; + + // The CharToByteConverter only takes a char[] + chars[0] = chToConvert; + numChars = 1; + + convertCharArray(); + } + + public void convert(String strToConvert) { + // Try to save a memory allocation if possible. Usual + // space/time trade off. If we could get the char[] out of + // the String without copying, that would be great, but + // it's forbidden since String is immutable. + if (chars == null || chars.length < strToConvert.length()) + chars = new char[strToConvert.length()]; + + numChars = strToConvert.length(); + + buffer = cacheEncoder.get(strToConvert); + if (buffer != null) { + numBytes = buffer.limit(); + //We need to set the buffer position to zero; becoz a + //previous read would have set the buffer position to its limit + buffer.position(0); + } + else { + strToConvert.getChars(0, numChars, chars, 0); + convertCharArray(); + cacheEncoder.put(strToConvert, buffer); + } + + //ToDo: if encoding debug is turned on call the below method + //validateCodesetCache(buffer, strToConvert); + } + + public final int getNumBytes() { + return numBytes; + } + + public final int getAlignment() { + return alignment; + } + + public final void setAlignment(int newAlignment) { + this.alignment = newAlignment; + } + + public byte[] getBytes() { + // Note that you can't use buffer.length since the buffer might + // be larger than the actual number of converted bytes depending + // on the encoding. + return buffer.array(); + } + + private void convertCharArray() { + try { + + // Possible optimization of directly converting into the CDR buffer. + // However, that means the CDR code would have to reserve + // a 4 byte string length ahead of time, and we'd need a + // confusing partial conversion scheme for when we couldn't + // fit everything in the buffer but needed to know the + // converted length before proceeding due to fragmentation. + // Then there's the issue of the chunking code. + // + // For right now, this is less messy and basic tests don't + // show more than a 1 ms penalty worst case. Less than a + // factor of 2 increase. + + // Convert the characters + buffer = ctb.encode(CharBuffer.wrap(chars,0,numChars)); + + // ByteBuffer returned by the encoder will set its limit + // to byte immediately after the last written byte. + numBytes = buffer.limit(); + + } catch (IllegalStateException ise) { + // an encoding operation is already in progress + throw wrapper.ctbConverterFailure( ise ) ; + } catch (MalformedInputException mie) { + // There were illegal Unicode char pairs + throw wrapper.badUnicodePair( mie ) ; + } catch (UnmappableCharacterException uce) { + // A character doesn't map to the desired code set + // CORBA formal 00-11-03. + throw omgWrapper.charNotInCodeset( uce ) ; + } catch (CharacterCodingException cce) { + // If this happens, then some other encoding error occured + throw wrapper.ctbConverterFailure( cce ) ; + } + } + } + + /** + * Special UTF16 converter which can either always write a BOM + * or use a specified byte order without one. + */ + private class UTF16CTBConverter extends JavaCTBConverter + { + // Using this constructor, we will always write a BOM + public UTF16CTBConverter() { + super(OSFCodeSetRegistry.UTF_16, 2); + } + + // Using this constructor, we don't use a BOM and use the byte order specified + public UTF16CTBConverter(boolean littleEndian) { + super(littleEndian ? OSFCodeSetRegistry.UTF_16LE : OSFCodeSetRegistry.UTF_16BE, 2); + } + } + + /** + * Implementation of BTCConverter which uses a sun.io.ByteToCharConverter + * for the real work. Handles translation of exceptions to the + * appropriate CORBA versions. + */ + private class JavaBTCConverter extends BTCConverter { + protected CharsetDecoder decoder; + private int resultingNumChars; + + public JavaBTCConverter(OSFCodeSetRegistry.Entry codeset) { + decoder = this.getConverter(codeset.getName()); + } + + public final int getNumChars() { + return resultingNumChars; + } + + public char[] getChars(ByteBuffer byteBuffer, int offset, int numBytes) { + try { + byteBuffer.limit(numBytes); + CharBuffer charBuf = decoder.decode(byteBuffer); + resultingNumChars = charBuf.limit(); + char[] buffer = new char[resultingNumChars]; + charBuf.get(buffer, 0, resultingNumChars).position(0); + return buffer; + + } catch (IllegalStateException ile) { + // There were a decoding operation already in progress + throw wrapper.btcConverterFailure( ile ) ; + } catch (MalformedInputException mie) { + // There were illegal Unicode char pairs + throw wrapper.badUnicodePair( mie ) ; + } catch (UnmappableCharacterException uce) { + // A character doesn't map to the desired code set. + // CORBA formal 00-11-03. + throw omgWrapper.charNotInCodeset( uce ) ; + } catch (CharacterCodingException cce) { + // If this happens, then a character decoding error occured. + throw wrapper.btcConverterFailure( cce ) ; + } + } + + public char[] getChars(byte[] bytes, int offset, int numBytes) { + + // Possible optimization of reading directly from the CDR + // byte buffer. The sun.io converter supposedly can handle + // incremental conversions in which a char is broken across + // two convert calls. + // + // Basic tests didn't show more than a 1 ms increase + // worst case. It's less than a factor of 2 increase. + // Also makes the interface more difficult. + + + try { + + ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes); + CharBuffer charBuf = decoder.decode(byteBuf); + + // CharBuffer returned by the decoder will set its limit + // to byte immediately after the last written byte. + resultingNumChars = charBuf.limit(); + + // IMPORTANT - It's possible the underlying char[] in the + // CharBuffer returned by btc.decode(byteBuf) + // is longer in length than the number of characters + // decoded. Hence, the check below to ensure the + // char[] returned contains all the chars that have + // been decoded and no more. + char[] buffer; + if (charBuf.limit() == charBuf.capacity()) { + buffer = charBuf.array(); + } else { + buffer = new char[charBuf.limit()]; + charBuf.get(buffer, 0, charBuf.limit()).position(0); + } + + return buffer; + + } catch (IllegalStateException ile) { + // There were a decoding operation already in progress + throw wrapper.btcConverterFailure( ile ) ; + } catch (MalformedInputException mie) { + // There were illegal Unicode char pairs + throw wrapper.badUnicodePair( mie ) ; + } catch (UnmappableCharacterException uce) { + // A character doesn't map to the desired code set. + // CORBA formal 00-11-03. + throw omgWrapper.charNotInCodeset( uce ) ; + } catch (CharacterCodingException cce) { + // If this happens, then a character decoding error occured. + throw wrapper.btcConverterFailure( cce ) ; + } + } + + /** + * Utility method to find a CharsetDecoder in the + * cache or create a new one if necessary. Throws an + * INTERNAL if the code set is unknown. + */ + protected CharsetDecoder getConverter(String javaCodeSetName) { + + CharsetDecoder result = null; + try { + result = cache.getByteToCharConverter(javaCodeSetName); + + if (result == null) { + Charset tmpCharset = Charset.forName(javaCodeSetName); + result = tmpCharset.newDecoder(); + cache.setConverter(javaCodeSetName, result); + } + + } catch(IllegalCharsetNameException icne) { + // This can only happen if one of our charset entries has + // an illegal name. + throw wrapper.invalidBtcConverterName( icne, javaCodeSetName ) ; + } + + return result; + } + } + + /** + * Special converter for UTF16 since it's required to optionally + * support a byte order marker while the internal Java converters + * either require it or require that it isn't there. + * + * The solution is to check for the byte order marker, and if we + * need to do something differently, switch internal converters. + */ + private class UTF16BTCConverter extends JavaBTCConverter + { + private ByteOrder defaultByteOrder; + private boolean converterUsesBOM = true; + + private static final char UTF16_BE_MARKER = (char) 0xfeff; + private static final char UTF16_LE_MARKER = (char) 0xfffe; + + // When there isn't a byte order marker, used the byte order specified. + UTF16BTCConverter(ByteOrder defaultByteOrder) { + super(OSFCodeSetRegistry.UTF_16); + + this.defaultByteOrder = defaultByteOrder; + } + + public char[] getChars(ByteBuffer byteBuffer, int offset, int numBytes) { + byte [] marker = {byteBuffer.get(), byteBuffer.get()}; + byteBuffer.position(0); + + if (hasUTF16ByteOrderMarker(marker, 0, numBytes)) { + if (!converterUsesBOM) + switchToConverter(OSFCodeSetRegistry.UTF_16); + + converterUsesBOM = true; + return super.getChars(byteBuffer, offset, numBytes); + } else { + if (converterUsesBOM) { + if (defaultByteOrder == ByteOrder.LITTLE_ENDIAN) + switchToConverter(OSFCodeSetRegistry.UTF_16LE); + else + switchToConverter(OSFCodeSetRegistry.UTF_16BE); + + converterUsesBOM = false; + } + return super.getChars(byteBuffer, offset, numBytes); + } + } + + @Override + public char[] getChars(byte[] bytes, int offset, int numBytes) { + + if (hasUTF16ByteOrderMarker(bytes, offset, numBytes)) { + if (!converterUsesBOM) + switchToConverter(OSFCodeSetRegistry.UTF_16); + + converterUsesBOM = true; + + return super.getChars(bytes, offset, numBytes); + } else { + if (converterUsesBOM) { + if (defaultByteOrder == ByteOrder.LITTLE_ENDIAN) + switchToConverter(OSFCodeSetRegistry.UTF_16LE); + else + switchToConverter(OSFCodeSetRegistry.UTF_16BE); + + converterUsesBOM = false; + } + + return super.getChars(bytes, offset, numBytes); + } + } + + /** + * Utility method for determining if a UTF-16 byte order marker is present. + */ + private boolean hasUTF16ByteOrderMarker(byte[] array, int offset, int length) { + // If there aren't enough bytes to represent the marker and data, + // return false. + if (length >= 4) { + + int b1 = array[offset] & 0x00FF; + int b2 = array[offset + 1] & 0x00FF; + + char marker = (char)((b1 << 8) | (b2)); + + return (marker == UTF16_BE_MARKER || marker == UTF16_LE_MARKER); + } else + return false; + } + + /** + * The current solution for dealing with UTF-16 in CORBA + * is that if our sun.io converter requires byte order markers, + * and then we see a CORBA wstring/wchar without them, we + * switch to the sun.io converter that doesn't require them. + */ + private void switchToConverter(OSFCodeSetRegistry.Entry newCodeSet) { + + // Use the getConverter method from our superclass. + decoder = super.getConverter(newCodeSet.getName()); + } + } + + /** + * CTB converter factory for single byte or variable length encodings. + */ + public CTBConverter getCTBConverter(OSFCodeSetRegistry.Entry codeset) { + int alignment = (!codeset.isFixedWidth() ? + 1 : + codeset.getMaxBytesPerChar()); + + return new JavaCTBConverter(codeset, alignment); + } + + /** + * CTB converter factory for multibyte (mainly fixed) encodings. + * + * Because of the awkwardness with byte order markers and the possibility of + * using UCS-2, you must specify both the endianness of the stream as well as + * whether or not to use byte order markers if applicable. UCS-2 has no byte + * order markers. UTF-16 has optional markers. + * + * If you select useByteOrderMarkers, there is no guarantee that the encoding + * will use the endianness specified. + * + */ + CTBConverter getCTBConverter(OSFCodeSetRegistry.Entry codeset, + boolean littleEndian, + boolean useByteOrderMarkers) { + + // UCS2 doesn't have byte order markers, and we're encoding it + // as UTF-16 since UCS2 isn't available in all Java platforms. + // They should be identical with only minor differences in + // negative cases. + if (codeset == OSFCodeSetRegistry.UCS_2) + return new UTF16CTBConverter(littleEndian); + + // We can write UTF-16 with or without a byte order marker. + if (codeset == OSFCodeSetRegistry.UTF_16) { + if (useByteOrderMarkers) + return new UTF16CTBConverter(); + else + return new UTF16CTBConverter(littleEndian); + } + + // Everything else uses the generic JavaCTBConverter. + // + // Variable width encodings are aligned on 1 byte boundaries. + // A fixed width encoding with a max. of 4 bytes/char should + // align on a 4 byte boundary. Note that UTF-16 is a special + // case because of the optional byte order marker, so it's + // handled above. + // + // This doesn't matter for GIOP 1.2 wchars and wstrings + // since the encoded bytes are treated as an encapsulation. + int alignment = (!codeset.isFixedWidth() ? + 1 : + codeset.getMaxBytesPerChar()); + + CTBConverter converter; + + Map m = cacheCTBC.get(); + converter = m.get(codeset); + if (converter == null ) { + converter = new JavaCTBConverter(codeset, alignment); + m.put(codeset, converter); + } else if(converter.getAlignment() != alignment) { + ((JavaCTBConverter) converter).setAlignment(alignment); + } + return converter; + } + + /** + * BTCConverter factory for single byte or variable width encodings. + */ + public BTCConverter getBTCConverter(OSFCodeSetRegistry.Entry codeset) { + return new JavaBTCConverter(codeset); + } + + /** + * BTCConverter factory for fixed width multibyte encodings. + */ + public BTCConverter getBTCConverter(OSFCodeSetRegistry.Entry codeset, + ByteOrder defaultByteOrder) { + + if (codeset == OSFCodeSetRegistry.UTF_16 || codeset == OSFCodeSetRegistry.UCS_2) { + return new UTF16BTCConverter(defaultByteOrder); + } else { + Map m = cacheBTCC.get(); + BTCConverter converter = m.get(codeset); + if (converter == null) { + converter = new JavaBTCConverter(codeset); + m.put(codeset, converter); + } + return converter; + } + } + + /** + * Follows the code set negotiation algorithm in CORBA formal 99-10-07 13.7.2. + * + * Returns the proper negotiated OSF character encoding number or + * CodeSetConversion.FALLBACK_CODESET. + */ + private int selectEncoding(CodeSetComponentInfo.CodeSetComponent client, + CodeSetComponentInfo.CodeSetComponent server) { + + // A "null" value for the server's nativeCodeSet means that + // the server desired not to indicate one. We'll take that + // to mean that it wants the first thing in its conversion list. + // If it's conversion list is empty, too, then use the fallback + // codeset. + int serverNative = server.nativeCodeSet; + + if (serverNative == 0) { + if (server.conversionCodeSets.length > 0) + serverNative = server.conversionCodeSets[0]; + else + return CodeSetConversion.FALLBACK_CODESET; + } + + if (client.nativeCodeSet == serverNative) { + // Best case -- client and server don't have to convert + return serverNative; + } + + // Is this client capable of converting to the server's + // native code set? + for (int i = 0; i < client.conversionCodeSets.length; i++) { + if (serverNative == client.conversionCodeSets[i]) { + // The client will convert to the server's + // native code set. + return serverNative; + } + } + + // Is the server capable of converting to the client's + // native code set? + for (int i = 0; i < server.conversionCodeSets.length; i++) { + if (client.nativeCodeSet == server.conversionCodeSets[i]) { + // The server will convert to the client's + // native code set. + return client.nativeCodeSet; + } + } + + // See if there are any code sets that both the server and client + // support (giving preference to the server). The order + // of conversion sets is from most to least desired. + for (int i = 0; i < server.conversionCodeSets.length; i++) { + for (int y = 0; y < client.conversionCodeSets.length; y++) { + if (server.conversionCodeSets[i] == client.conversionCodeSets[y]) { + return server.conversionCodeSets[i]; + } + } + } + + // Before using the fallback codesets, the spec calls for a + // compatibility check on the native code sets. It doesn't make + // sense because loss free communication is always possible with + // UTF8 and UTF16, the fall back code sets. It's also a lot + // of work to implement. In the case of incompatibility, the + // spec says to throw a CODESET_INCOMPATIBLE exception. + + // Use the fallback + return CodeSetConversion.FALLBACK_CODESET; + } + + /** + * Perform the code set negotiation algorithm and come up with + * the two encodings to use. + */ + public CodeSetComponentInfo.CodeSetContext negotiate(CodeSetComponentInfo client, + CodeSetComponentInfo server) { + int charData + = selectEncoding(client.getCharComponent(), + server.getCharComponent()); + + if (charData == CodeSetConversion.FALLBACK_CODESET) { + charData = OSFCodeSetRegistry.UTF_8.getNumber(); + } + + int wcharData + = selectEncoding(client.getWCharComponent(), + server.getWCharComponent()); + + if (wcharData == CodeSetConversion.FALLBACK_CODESET) { + wcharData = OSFCodeSetRegistry.UTF_16.getNumber(); + } + + return new CodeSetComponentInfo.CodeSetContext(charData, + wcharData); + } + + // No one should instantiate a CodeSetConversion but the singleton + // instance method + private CodeSetConversion() {} + + // initialize-on-demand holder + private static class CodeSetConversionHolder { + static final CodeSetConversion csc = new CodeSetConversion() ; + } + + /** + * CodeSetConversion is a singleton, and this is the access point. + */ + public static CodeSetConversion impl() { + return CodeSetConversionHolder.csc ; + } + + // Number used internally to indicate the fallback code + // set. + private static final int FALLBACK_CODESET = 0; + + // Provides a thread local cache for the sun.io + // converters. + private CodeSetCache cache = new CodeSetCache(); + + // CodeSet converters are cached once created and are shared with multiple + // worker threads as shared objects. Each converter's + // btc/ctb object has cached string<-->byte[] cache on a per thread basis. + // Everytime a string is encoded/decoded it's result will be stored in + // the weak HashMap of the respective converters. + private ThreadLocal > + cacheBTCC = new ThreadLocal() { + @Override + public HashMap initialValue() { + return new HashMap() ; + } + }; + private ThreadLocal > + cacheCTBC = new ThreadLocal() { + @Override + public HashMap initialValue() { + return new HashMap() ; + } + }; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsInputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsInputStream.java new file mode 100644 index 000000000..03a58a136 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsInputStream.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import com.sun.org.omg.SendingContext.CodeBase; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * Encapsulations are supposed to explicitly define their + * code sets and GIOP version. The original resolution to issue 2784 + * said that the defaults were UTF-8 and UTF-16, but that was not + * agreed upon. + * + * These streams currently use CDR 1.2 with ISO8859-1 for char/string and + * UTF16 for wchar/wstring. If no byte order marker is available, + * the endianness of the encapsulation is used. + * + * When more encapsulations arise that have their own special code + * sets defined, we can make all constructors take such parameters. + */ +public class EncapsInputStream extends CDRInputObject +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public EncapsInputStream(org.omg.CORBA.ORB orb, byte[] buf, + int size, ByteOrder byteOrder, + GIOPVersion version) { + super(orb, ByteBuffer.wrap(buf), size, byteOrder, version, + BufferManagerFactory.newReadEncapsulationBufferManager() + ); + + performORBVersionSpecificInit(); + } + + public EncapsInputStream(org.omg.CORBA.ORB orb, ByteBuffer byteBuffer, + int size, ByteOrder byteOrder, + GIOPVersion version) { + super(orb, byteBuffer, size, byteOrder, version, + BufferManagerFactory.newReadEncapsulationBufferManager() + ); + + performORBVersionSpecificInit(); + } + + // exported to Glassfish - DON'T change this!!! + public EncapsInputStream(org.omg.CORBA.ORB orb, byte[] data, int size) + { + this(orb, data, size, GIOPVersion.V1_2); + } + + // corba/AnyImpl + public EncapsInputStream(EncapsInputStream eis) + { + super(eis); + + performORBVersionSpecificInit(); + } + + // CDREncapsCodec + // ServiceContext + // + // Assumes big endian (can use consumeEndian to read and set + // the endianness if it is an encapsulation with a byte order + // mark at the beginning) + public EncapsInputStream(org.omg.CORBA.ORB orb, byte[] data, int size, GIOPVersion version) + { + this(orb, data, size, ByteOrder.BIG_ENDIAN, version); + } + + /** + * Full constructor with a CodeBase parameter useful for + * unmarshaling RMI-IIOP valuetypes (technically against the + * intention of an encapsulation, but necessary due to OMG + * issue 4795. Used by ServiceContexts. + */ + public EncapsInputStream(org.omg.CORBA.ORB orb, + byte[] data, + int size, + GIOPVersion version, + CodeBase codeBase) { + super(orb, + ByteBuffer.wrap(data), + size, + ByteOrder.BIG_ENDIAN, + version, + BufferManagerFactory.newReadEncapsulationBufferManager() + ); // IDLJavaSerializationInputStream::directRead == false + + this.codeBase = codeBase; + + performORBVersionSpecificInit(); + } + + @Override + public CDRInputObject dup() { + return EncapsInputStreamFactory.newEncapsInputStream(this); + } + + @Override + protected CodeSetConversion.BTCConverter createCharBTCConverter() { + return CodeSetConversion.impl().getBTCConverter( + OSFCodeSetRegistry.ISO_8859_1); + } + + @Override + protected CodeSetConversion.BTCConverter createWCharBTCConverter() { + // Wide characters don't exist in GIOP 1.0 + if (getGIOPVersion().equals(GIOPVersion.V1_0)) + throw wrapper.wcharDataInGiop10(); + + // In GIOP 1.1, we shouldn't have byte order markers. Take the order + // of the stream if we don't see them. + if (getGIOPVersion().equals(GIOPVersion.V1_1)) + return CodeSetConversion.impl().getBTCConverter(OSFCodeSetRegistry.UTF_16, getByteOrder()); + + // Assume anything else adheres to GIOP 1.2 requirements. + // + // Our UTF_16 converter will work with byte order markers, and if + // they aren't present, it will use the provided endianness. + // + // With no byte order marker, it's big endian in GIOP 1.2. + // formal 00-11-03 15.3.16. + return CodeSetConversion.impl().getBTCConverter(OSFCodeSetRegistry.UTF_16, ByteOrder.BIG_ENDIAN); + } + + @Override + public CodeBase getCodeBase() { + return codeBase; + } + + private CodeBase codeBase; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsInputStreamFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsInputStreamFactory.java new file mode 100644 index 000000000..af5b55709 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsInputStreamFactory.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.org.omg.SendingContext.CodeBase; + +/** + * @author jwells + * + */ +public class EncapsInputStreamFactory { + public static EncapsInputStream newEncapsInputStream(final EncapsInputStream eis) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public EncapsInputStream run() { + return new EncapsInputStream(eis); + } + + }); + } + + public static EncapsInputStream newEncapsInputStream(final org.omg.CORBA.ORB orb, + final byte[] buf, + final int size, + final ByteOrder byteOrder, + final GIOPVersion version) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public EncapsInputStream run() { + return new EncapsInputStream(orb, buf, size, byteOrder, version); + } + + }); + + } + + public static EncapsInputStream newEncapsInputStream(final org.omg.CORBA.ORB orb, + final byte[] data, + final int size, + final GIOPVersion version) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public EncapsInputStream run() { + return new EncapsInputStream(orb, data, size, version); + } + + }); + + } + + public static EncapsInputStream newEncapsInputStream(final org.omg.CORBA.ORB orb, + final byte[] data, + final int size) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public EncapsInputStream run() { + return new EncapsInputStream(orb, data, size); + } + + }); + + } + + public static EncapsInputStream newEncapsInputStream(final org.omg.CORBA.ORB orb, + final ByteBuffer byteBuffer, + final int size, + final ByteOrder byteOrder, + final GIOPVersion version) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public EncapsInputStream run() { + return new EncapsInputStream(orb, byteBuffer, size, byteOrder, version); + } + + }); + + } + + public static EncapsInputStream newEncapsInputStream(final org.omg.CORBA.ORB orb, + final byte[] data, + final int size, + final GIOPVersion version, + final CodeBase codeBase) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public EncapsInputStream run() { + return new EncapsInputStream(orb, data, size, version, codeBase); + } + + }); + + } + + public static TypeCodeInputStream newTypeCodeInputStream(final org.omg.CORBA.ORB orb, + final byte[] data, + final int size, + final ByteOrder byteOrder, + final GIOPVersion version) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public TypeCodeInputStream run() { + return new TypeCodeInputStream(orb, data, size, byteOrder, version); + } + + }); + + } + + public static TypeCodeInputStream newTypeCodeInputStream(final org.omg.CORBA.ORB orb, + final byte[] data, + final int size) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public TypeCodeInputStream run() { + return new TypeCodeInputStream(orb, data, size); + } + + }); + + } + + public static TypeCodeInputStream newTypeCodeInputStream(final org.omg.CORBA.ORB orb, + final ByteBuffer byteBuffer, + final int size, + final ByteOrder byteOrder, + final GIOPVersion version) { + return AccessController. + doPrivileged(new PrivilegedAction() { + + @Override + public TypeCodeInputStream run() { + return new TypeCodeInputStream(orb, byteBuffer, size, byteOrder, version); + } + + }); + + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsOutputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsOutputStream.java new file mode 100644 index 000000000..1ecec7a39 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/EncapsOutputStream.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * Encapsulations are supposed to explicitly define their + * code sets and GIOP version. The original resolution to issue 2784 + * said that the defaults were UTF-8 and UTF-16, but that was not + * agreed upon. + * + * These streams currently use CDR 1.2 with ISO8859-1 for char/string and + * UTF16 for wchar/wstring. If no byte order marker is available, + * the endianness of the encapsulation is used. + * + * When more encapsulations arise that have their own special code + * sets defined, we can make all constructors take such parameters. + */ +public class EncapsOutputStream extends CDROutputObject +{ + + // REVISIT - Right now, EncapsOutputStream's do not use + // pooled byte buffers. This is controlled by the following + // static constant. This should be re-factored such that + // the EncapsOutputStream doesn't know it's using pooled + // byte buffers. + final static boolean usePooledByteBuffers = false; + private static final InputObjectFactory INPUT_STREAM_FACTORY = new EncapsInputStreamFactory(); + + // REVISIT - Right now, valuetypes in encapsulations will + // only use stream format version 1, which may create problems + // for service contexts or codecs (?). + + // corba/ORB + // corba/ORBSingleton + // iiop/ORB + // iiop/GIOPImpl + // corba/AnyImpl + // IIOPProfileTemplate + public EncapsOutputStream(ORB orb) { + // GIOP version 1.2 with no fragmentation, big endian, + // UTF8 for char data and UTF-16 for wide char data; + this(orb, GIOPVersion.V1_2); + } + + // CDREncapsCodec + // + // REVISIT. A UTF-16 encoding with GIOP 1.1 will not work + // with byte order markers. + public EncapsOutputStream(ORB orb, GIOPVersion version) { + super(orb, version, BufferManagerFactory.newWriteEncapsulationBufferManager(orb), + ORBConstants.STREAM_FORMAT_VERSION_1, usePooledByteBuffers + ); + } + + @Override + public org.omg.CORBA.portable.InputStream create_input_stream() { + freeInternalCaches(); + return createInputObject(null, INPUT_STREAM_FACTORY); + } + + private static class EncapsInputStreamFactory implements InputObjectFactory { + @Override + public CDRInputObject createInputObject(CDROutputObject outputObject, ORB orb, ByteBuffer byteBuffer, int size, GIOPVersion giopVersion) { + return com.sun.corba.ee.impl.encoding.EncapsInputStreamFactory.newEncapsInputStream(outputObject.orb(), + byteBuffer, size, ByteOrder.BIG_ENDIAN, giopVersion); + } + } + + @Override + protected CodeSetConversion.CTBConverter createCharCTBConverter() { + return CodeSetConversion.impl().getCTBConverter( + OSFCodeSetRegistry.ISO_8859_1); + } + + @Override + protected CodeSetConversion.CTBConverter createWCharCTBConverter() { + if (getGIOPVersion().equals(GIOPVersion.V1_0)) + throw wrapper.wcharDataInGiop10(); + + // In the case of GIOP 1.1, we take the byte order of the stream + // and don't use byte order markers since we're limited to a 2 byte + // fixed width encoding. + if (getGIOPVersion().equals(GIOPVersion.V1_1)) + return CodeSetConversion.impl().getCTBConverter(OSFCodeSetRegistry.UTF_16, false, false); + + // Assume anything else meets GIOP 1.2 requirements + // + // Use byte order markers? If not, use big endian in GIOP 1.2. + // (formal 00-11-03 15.3.16) + + boolean useBOM = ((ORB)orb()).getORBData().useByteOrderMarkersInEncapsulations(); + + return CodeSetConversion.impl().getCTBConverter(OSFCodeSetRegistry.UTF_16, false, useBOM); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarkAndResetHandler.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarkAndResetHandler.java new file mode 100644 index 000000000..0c58217c9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarkAndResetHandler.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + + +import java.nio.ByteBuffer; + +/** + * Defines an abstraction for a RestorableInputStream to + * implement mark/reset. + */ +interface MarkAndResetHandler +{ + void mark(RestorableInputStream inputStream); + + void fragmentationOccured(ByteBuffer byteBuffer); + + void reset(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarshalInputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarshalInputStream.java new file mode 100644 index 000000000..bd0e0f7b9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarshalInputStream.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +public interface MarshalInputStream { + public boolean read_boolean(); + public char read_char(); + public char read_wchar(); + public byte read_octet(); + public short read_short(); + public short read_ushort(); + public int read_long(); + public int read_ulong(); + public long read_longlong(); + public long read_ulonglong(); + public float read_float(); + public double read_double(); + public String read_string(); + public String read_wstring(); + + public void read_boolean_array(boolean[] value, int offset, int length); + public void read_char_array(char[] value, int offset, int length); + public void read_wchar_array(char[] value, int offset, int length); + public void read_octet_array(byte[] value, int offset, int length); + public void read_short_array(short[] value, int offset, int length); + public void read_ushort_array(short[] value, int offset, int length); + public void read_long_array(int[] value, int offset, int length); + public void read_ulong_array(int[] value, int offset, int length); + public void read_longlong_array(long[] value, int offset, int length); + public void read_ulonglong_array(long[] value, int offset, int length); + public void read_float_array(float[] value, int offset, int length); + public void read_double_array(double[] value, int offset, int length); + + public org.omg.CORBA.Object read_Object(); + public TypeCode read_TypeCode(); + public Any read_any(); + @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.Principal read_Principal(); + + /* + * The methods necessary to support RMI + */ + public org.omg.CORBA.Object read_Object(Class stubClass); + public java.io.Serializable read_value() throws Exception; + + /* + * Additional Methods + */ + public void consumeEndian(); + + // Determines the current byte stream position + // (also handles fragmented streams) + public int getPosition(); + + // mark/reset from java.io.InputStream + public void mark(int readAheadLimit); + public void reset(); + + /** + * This must be called once before unmarshaling valuetypes or anything + * that uses repository IDs. The ORB's version should be set + * to the desired value prior to calling. + */ + public void performORBVersionSpecificInit(); + + /** + * Tells the input stream to null any code set converter + * references, forcing it to reacquire them if it needs + * converters again. This is used when the server + * input stream needs to switch the connection's char code set + * converter to something different after reading the + * code set service context for the first time. Initially, + * we use ISO8859-1 to read the operation name (it can't + * be more than ASCII). + */ + public void resetCodeSetConverters(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarshalOutputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarshalOutputStream.java new file mode 100644 index 000000000..f2091010d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/MarshalOutputStream.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.IOException; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; + +import org.omg.CORBA.portable.InputStream; + +public interface MarshalOutputStream { + + public InputStream create_input_stream(); + + public void write_boolean(boolean value); + public void write_char(char value); + public void write_wchar(char value); + public void write_octet(byte value); + public void write_short(short value); + public void write_ushort(short value); + public void write_long(int value); + public void write_ulong(int value); + public void write_longlong(long value); + public void write_ulonglong(long value); + public void write_float(float value); + public void write_double(double value); + public void write_string(String value); + public void write_wstring(String value); + + public void write_boolean_array(boolean[] value, int offset, int length); + public void write_char_array(char[] value, int offset, int length); + public void write_wchar_array(char[] value, int offset, int length); + public void write_octet_array(byte[] value, int offset, int length); + public void write_short_array(short[] value, int offset, int length); + public void write_ushort_array(short[] value, int offset, int length); + public void write_long_array(int[] value, int offset, int length); + public void write_ulong_array(int[] value, int offset, int length); + public void write_longlong_array(long[] value, int offset, int length); + public void write_ulonglong_array(long[] value, int offset, int length); + public void write_float_array(float[] value, int offset, int length); + public void write_double_array(double[] value, int offset, int length); + + public void write_Object(org.omg.CORBA.Object value); + public void write_TypeCode(TypeCode value); + public void write_any(Any value); + @SuppressWarnings({"deprecation"}) + public void write_Principal(org.omg.CORBA.Principal value); + + + /* + * The methods necessary to support RMI + */ + public void write_value(java.io.Serializable value); + public void start_block(); + public void end_block(); + + /* + * Additional Methods + */ + + public void putEndian(); + public void writeTo(java.io.OutputStream s) + throws IOException; + + public byte[] toByteArray(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/OSFCodeSetRegistry.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/OSFCodeSetRegistry.java new file mode 100644 index 000000000..a9e452690 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/OSFCodeSetRegistry.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +/** + * + * Information from the OSF code set registry version 1.2g. + * + * Use the Entry corresponding to the desired code set. + * + * Consider rename to CodeSetRegistry since OSF is dead. + */ +public final class OSFCodeSetRegistry +{ + // Numbers from the OSF code set registry version 1.2g. + // + // Please see the individual Entry definitions for + // more details. + public static final int ISO_8859_1_VALUE = 0x00010001; + public static final int UTF_16_VALUE = 0x00010109; + public static final int UTF_8_VALUE = 0x05010001; + public static final int UCS_2_VALUE = 0x00010100; + public static final int ISO_646_VALUE = 0x00010020; + + private OSFCodeSetRegistry() {} + + /** + * An entry in the OSF registry which allows users + * to find out the equivalent Java character encoding + * name as well as some other facts from the registry. + */ + public final static class Entry + { + private String javaName; + private int encodingNum; + private boolean isFixedWidth; + private int maxBytesPerChar; + + private Entry(String javaName, + int encodingNum, + boolean isFixedWidth, + int maxBytesPerChar) { + this.javaName = javaName; + this.encodingNum = encodingNum; + this.isFixedWidth = isFixedWidth; + this.maxBytesPerChar = maxBytesPerChar; + } + + /** + * Returns the Java equivalent name. If the encoding has + * an optional byte order marker, this name will map to the + * Java encoding that includes the marker. + */ + public String getName() { + return javaName; + } + + /** + * Get the OSF registry number for this code set. + */ + public int getNumber() { + return encodingNum; + } + + /** + * Is this a fixed or variable width code set? (In CORBA + * terms, "non-byte-oriented" or a "byte-oriented" + * code set, respectively) + */ + public boolean isFixedWidth() { + return isFixedWidth; + } + + public int getMaxBytesPerChar() { + return maxBytesPerChar; + } + + /** + * First checks reference equality since it's expected + * people will use the pre-defined constant Entries. + */ + public boolean equals(Object obj) { + if (this == obj) + return true; + + if (!(obj instanceof OSFCodeSetRegistry.Entry)) + return false; + + OSFCodeSetRegistry.Entry other + = (OSFCodeSetRegistry.Entry)obj; + + return (javaName.equals(other.javaName) && + encodingNum == other.encodingNum && + isFixedWidth == other.isFixedWidth && + maxBytesPerChar == other.maxBytesPerChar); + } + + /** + * Uses the registry number as the hash code. + */ + public int hashCode() { + return encodingNum; + } + } + + /** + * 8-bit encoding required for GIOP 1.0, and used as the char set + * when nothing else is specified. + */ + public static final Entry ISO_8859_1 + = new Entry("ISO-8859-1", + ISO_8859_1_VALUE, + true, + 1); + + /** + * UTF-16 as specified in the OSF registry has an optional + * byte order marker. UTF-16BE and UTF-16LE are not in the OSF + * registry since it is no longer being developed. When the OMG + * switches to the IANA registry, these can be public. Right + * now, they're used internally by CodeSetConversion. + */ + static final Entry UTF_16BE + = new Entry("UTF-16BE", + -1, + true, + 2); + + static final Entry UTF_16LE + = new Entry("UTF-16LE", + -2, + true, + 2); + + /** + * Fallback wchar code set. + * + * In the resolution of issue 3405b, UTF-16 defaults to big endian, so + * doesn't have to have a byte order marker. Unfortunately, this has to be + * a special case for compatibility. + */ + public static final Entry UTF_16 + = new Entry("UTF-16", + UTF_16_VALUE, + true, + 4); + + /** + * Fallback char code set. Also the code set for char data + * in encapsulations. However, since CORBA says chars are + * only one octet, it is really the same as Latin-1. + */ + public static final Entry UTF_8 + = new Entry("UTF-8", + UTF_8_VALUE, + false, + 6); + + /* + * At least in JDK 1.3, UCS-2 isn't one of the mandatory Java character + * encodings. However, our old ORBs require what they call UCS2, even + * though they didn't necessarily do the correct encoding of it. + * + * This is a special case for our legacy ORBs, and put as the last thing + * in our conversion list for wchar data. + * + * If a foreign ORB actually tries to speak UCS2 with us, it probably + * won't work! Beware! + */ + public static final Entry UCS_2 + = new Entry("UCS-2", + UCS_2_VALUE, + true, + 2); + + /** + * This is the encoding older JavaSoft ORBs advertised as their + * CORBA char code set. Actually, they took the lower byte of + * the Java char. This is a 7-bit encoding, so they + * were really sending ISO8859-1. + */ + public static final Entry ISO_646 + = new Entry("US-ASCII", + ISO_646_VALUE, + true, + 1); + + /** + * Given an OSF registry value, return the corresponding Entry. + * Returns null if an Entry for that value is unavailable. + */ + public static Entry lookupEntry(int encodingValue) { + switch(encodingValue) { + case ISO_8859_1_VALUE: + return OSFCodeSetRegistry.ISO_8859_1; + case UTF_16_VALUE: + return OSFCodeSetRegistry.UTF_16; + case UTF_8_VALUE: + return OSFCodeSetRegistry.UTF_8; + case ISO_646_VALUE: + return OSFCodeSetRegistry.ISO_646; + case UCS_2_VALUE: + return OSFCodeSetRegistry.UCS_2; + default: + return null; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/OutputStreamFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/OutputStreamFactory.java new file mode 100644 index 000000000..49598d263 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/OutputStreamFactory.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.Connection; + +/** + * Factory for creating various output streams with AccessController + * + * @author jwells + */ +public class OutputStreamFactory { + public static TypeCodeOutputStream newTypeCodeOutputStream(final ORB orb) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public TypeCodeOutputStream run() { + return new TypeCodeOutputStream(orb); + } + + }); + } + + public static EncapsOutputStream newEncapsOutputStream(final ORB orb, + final GIOPVersion version) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public EncapsOutputStream run() { + return new EncapsOutputStream(orb, version); + } + + }); + } + + public static EncapsOutputStream newEncapsOutputStream(final ORB orb) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public EncapsOutputStream run() { + return new EncapsOutputStream(orb); + } + + }); + + } + + public static CDROutputObject newCDROutputObject(final ORB orb, + final MessageMediator mediator, + final GIOPVersion giopVersion, + final Connection connection, + final Message header, + final byte streamFormatVersion) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public CDROutputObject run() { + return new CDROutputObject(orb, mediator, giopVersion, connection, header, streamFormatVersion); + } + }); + } + + public static CDROutputObject newCDROutputObject(final ORB orb, + final MessageMediator messageMediator, + final Message header, + final byte streamFormatVersion) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public CDROutputObject run() { + return new CDROutputObject(orb, messageMediator, header, streamFormatVersion); + } + }); + + } + + public static CDROutputObject newCDROutputObject(final ORB orb, + final MessageMediator messageMediator, + final Message header, + final byte streamFormatVersion, + final int strategy) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public CDROutputObject run() { + return new CDROutputObject(orb, messageMediator, header, streamFormatVersion, strategy); + } + }); + + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/RestorableInputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/RestorableInputStream.java new file mode 100644 index 000000000..022ce7bce --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/RestorableInputStream.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +/** + * Defines the methods on an input stream which provide + * a way to get and restore its internal state without + * violating encapsulation. + */ +interface RestorableInputStream +{ + Object createStreamMemento(); + + void restoreInternalState(Object streamMemento); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeInputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeInputStream.java new file mode 100644 index 000000000..9d84065c3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeInputStream.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.nio.ByteOrder; +import java.util.HashMap; +import java.util.Map; +import java.nio.ByteBuffer; + + + +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.impl.encoding.CDRInputObject; + +public class TypeCodeInputStream extends EncapsInputStream implements TypeCodeReader +{ + private Map typeMap = null; + private InputStream enclosure = null; + + public TypeCodeInputStream(org.omg.CORBA.ORB orb, byte[] data, int size) { + super(orb, data, size); + } + + public TypeCodeInputStream(org.omg.CORBA.ORB orb, + byte[] data, + int size, + ByteOrder byteOrder, + GIOPVersion version) { + super(orb, data, size, byteOrder, version); + } + + TypeCodeInputStream(org.omg.CORBA.ORB orb, + ByteBuffer byteBuffer, + int size, + ByteOrder byteOrder, + GIOPVersion version) { + super(orb, byteBuffer, size, byteOrder, version); + } + + public void addTypeCodeAtPosition(TypeCodeImpl tc, int position) { + if (typeMap == null) { + typeMap = new HashMap(16); + } + typeMap.put(position, tc); + } + + public TypeCodeImpl getTypeCodeAtPosition(int position) { + if (typeMap == null) + return null; + return typeMap.get(position); + } + + public void setEnclosingInputStream(InputStream enclosure) { + this.enclosure = enclosure; + } + + public TypeCodeReader getTopLevelStream() { + if (enclosure == null) + return this; + if (enclosure instanceof TypeCodeReader) + return ((TypeCodeReader)enclosure).getTopLevelStream(); + return this; + } + + public int getTopLevelPosition() { + if (enclosure != null && enclosure instanceof TypeCodeReader) { + // The enclosed stream has to consider if the enclosing stream + // had to read the enclosed stream completely when creating it. + // This is why the size of the enclosed stream needs to be substracted. + int topPos = ((TypeCodeReader)enclosure).getTopLevelPosition(); + // Subtract getBufferLength from the parents pos because it read this stream + // from its own when creating it + return topPos - getBufferLength() + getPosition(); + } + return getPosition(); + } + + public static TypeCodeInputStream readEncapsulation(InputStream is, org.omg.CORBA.ORB _orb) { + // _REVISIT_ Would be nice if we didn't have to copy the buffer! + TypeCodeInputStream encap; + + int encapLength = is.read_long(); + + // read off part of the buffer corresponding to the encapsulation + byte[] encapBuffer = new byte[encapLength]; + is.read_octet_array(encapBuffer, 0, encapBuffer.length); + + // create an encapsulation using the marshal buffer + if (is instanceof CDRInputObject) { + encap = EncapsInputStreamFactory.newTypeCodeInputStream(_orb, encapBuffer, encapBuffer.length, + ((CDRInputObject)is).getByteOrder(), + ((CDRInputObject)is).getGIOPVersion()); + } else { + encap = EncapsInputStreamFactory.newTypeCodeInputStream(_orb, encapBuffer, encapBuffer.length); + } + encap.setEnclosingInputStream(is); + encap.makeEncapsulation(); + return encap; + } + + protected void makeEncapsulation() { + // first entry in an encapsulation is the endianess + consumeEndian(); + } + + public void printTypeMap() { + System.out.println("typeMap = {"); + for (Integer pos : typeMap.keySet() ) { + System.out.println( " key = " + pos + ", value = " + + typeMap.get(pos).description() ) ; + } + System.out.println("}") ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeOutputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeOutputStream.java new file mode 100644 index 000000000..7fb634dbb --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeOutputStream.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.orb.ORB; + +import java.nio.ByteOrder; +import java.util.HashMap; +import java.util.Map; +import java.nio.ByteBuffer; + +public final class TypeCodeOutputStream extends EncapsOutputStream { + + private static final InputObjectFactory TYPE_CODE_INPUT_OBJECT_FACTORY = new TypeCodeInputStreamFactory(); + + private OutputStream enclosure = null; + private Map typeMap = null; + private boolean isEncapsulation = false; + + public TypeCodeOutputStream(ORB orb) { + super(orb); + } + + @Override + public org.omg.CORBA.portable.InputStream create_input_stream() { + return createInputObject(null, TYPE_CODE_INPUT_OBJECT_FACTORY); + } + + private static class TypeCodeInputStreamFactory implements InputObjectFactory { + @Override + public CDRInputObject createInputObject(CDROutputObject outputObject, ORB orb, ByteBuffer byteBuffer, int size, GIOPVersion giopVersion) { + return EncapsInputStreamFactory.newTypeCodeInputStream(outputObject.orb(), byteBuffer, size, ByteOrder.BIG_ENDIAN, giopVersion); + } + } + + public void setEnclosingOutputStream(OutputStream enclosure) { + this.enclosure = enclosure; + } + + public TypeCodeOutputStream getTopLevelStream() { + if (enclosure == null) + return this; + if (enclosure instanceof TypeCodeOutputStream) + return ((TypeCodeOutputStream)enclosure).getTopLevelStream(); + return this; + } + + public int getTopLevelPosition() { + if (enclosure != null && enclosure instanceof TypeCodeOutputStream) { + int pos = ((TypeCodeOutputStream)enclosure).getTopLevelPosition() + + getPosition(); + // Add four bytes for the encaps length, not another 4 for the + // byte order which is included in getPosition(). + if (isEncapsulation) { + pos += 4; + } + + return pos; + } + return getPosition(); + } + + public void addIDAtPosition(String id, int position) { + if (typeMap == null) + typeMap = new HashMap(16); + typeMap.put(id, position); + } + + public int getPositionForID(String id) { + if (typeMap == null) + throw wrapper.refTypeIndirType() ; + return + typeMap.get(id) ; + } + + public TypeCodeOutputStream createEncapsulation(org.omg.CORBA.ORB _orb) { + TypeCodeOutputStream encap = OutputStreamFactory.newTypeCodeOutputStream((ORB)_orb); + encap.setEnclosingOutputStream(this); + encap.makeEncapsulation(); + return encap; + } + + protected void makeEncapsulation() { + // first entry in an encapsulation is the endianess + putEndian(); + isEncapsulation = true; + } + + public static TypeCodeOutputStream wrapOutputStream(OutputStream os) { + TypeCodeOutputStream tos = OutputStreamFactory.newTypeCodeOutputStream((ORB)os.orb()); + tos.setEnclosingOutputStream(os); + return tos; + } + + public int getPosition() { + return getIndex(); + } + + @Override + public int getRealIndex(int index) { + return getTopLevelPosition(); + } + + public byte[] getTypeCodeBuffer() { + return toByteArray(4); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeReader.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeReader.java new file mode 100644 index 000000000..34e48d4ab --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/TypeCodeReader.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.util.HashMap; +import java.util.Map; +import java.util.Iterator; +import java.util.List; +import java.util.Collections; +import java.util.ArrayList; +import java.io.IOException; +import java.io.PrintStream; +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.omg.CORBA.TypeCode ; +import org.omg.CORBA.StructMember ; +import org.omg.CORBA.UnionMember ; +import org.omg.CORBA.ValueMember ; +import org.omg.CORBA.TCKind ; +import org.omg.CORBA.Any ; +import org.omg.CORBA.BAD_TYPECODE ; +import org.omg.CORBA.BAD_PARAM ; +import org.omg.CORBA.BAD_OPERATION ; +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.MARSHAL ; + +import org.omg.CORBA.TypeCodePackage.BadKind ; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.impl.encoding.OSFCodeSetRegistry; +import com.sun.corba.ee.impl.encoding.MarshalInputStream; +import com.sun.corba.ee.impl.encoding.CodeSetConversion; + +public interface TypeCodeReader extends MarshalInputStream { + public void addTypeCodeAtPosition(TypeCodeImpl tc, int position); + public TypeCodeImpl getTypeCodeAtPosition(int position); + public void setEnclosingInputStream(InputStream enclosure); + public TypeCodeReader getTopLevelStream(); + public int getTopLevelPosition(); + public int getPosition(); + public void printTypeMap(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/WrapperInputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/WrapperInputStream.java new file mode 100644 index 000000000..87f9440c5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/encoding/WrapperInputStream.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.util.HashMap; +import java.util.Map; +import java.util.Iterator; +import java.util.List; +import java.util.Collections; +import java.util.ArrayList; +import java.io.IOException; + +import org.omg.CORBA.TypeCode ; +import org.omg.CORBA.Any ; + + +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.impl.corba.TypeCodeImpl; + +public class WrapperInputStream extends org.omg.CORBA_2_3.portable.InputStream implements TypeCodeReader +{ + private CDRInputObject stream; + private Map typeMap = null; + private int startPos = 0; + + public WrapperInputStream(CDRInputObject s) { + super(); + stream = s; + startPos = stream.getPosition(); + } + + public int read() throws IOException { return stream.read(); } + public int read(byte b[]) throws IOException { return stream.read(b); } + public int read(byte b[], int off, int len) throws IOException { + return stream.read(b, off, len); + } + public long skip(long n) throws IOException { return stream.skip(n); } + public int available() throws IOException { return stream.available(); } + public void close() throws IOException { stream.close(); } + public void mark(int readlimit) { stream.mark(readlimit); } + public void reset() { stream.reset(); } + public boolean markSupported() { return stream.markSupported(); } + public int getPosition() { return stream.getPosition(); } + public void consumeEndian() { stream.consumeEndian(); } + public boolean read_boolean() { return stream.read_boolean(); } + public char read_char() { return stream.read_char(); } + public char read_wchar() { return stream.read_wchar(); } + public byte read_octet() { return stream.read_octet(); } + public short read_short() { return stream.read_short(); } + public short read_ushort() { return stream.read_ushort(); } + public int read_long() { return stream.read_long(); } + public int read_ulong() { return stream.read_ulong(); } + public long read_longlong() { return stream.read_longlong(); } + public long read_ulonglong() { return stream.read_ulonglong(); } + public float read_float() { return stream.read_float(); } + public double read_double() { return stream.read_double(); } + public String read_string() { return stream.read_string(); } + public String read_wstring() { return stream.read_wstring(); } + + public void read_boolean_array(boolean[] value, int offset, int length) { + stream.read_boolean_array(value, offset, length); + } + public void read_char_array(char[] value, int offset, int length) { + stream.read_char_array(value, offset, length); + } + public void read_wchar_array(char[] value, int offset, int length) { + stream.read_wchar_array(value, offset, length); + } + public void read_octet_array(byte[] value, int offset, int length) { + stream.read_octet_array(value, offset, length); + } + public void read_short_array(short[] value, int offset, int length) { + stream.read_short_array(value, offset, length); + } + public void read_ushort_array(short[] value, int offset, int length) { + stream.read_ushort_array(value, offset, length); + } + public void read_long_array(int[] value, int offset, int length) { + stream.read_long_array(value, offset, length); + } + public void read_ulong_array(int[] value, int offset, int length) { + stream.read_ulong_array(value, offset, length); + } + public void read_longlong_array(long[] value, int offset, int length) { + stream.read_longlong_array(value, offset, length); + } + public void read_ulonglong_array(long[] value, int offset, int length) { + stream.read_ulonglong_array(value, offset, length); + } + public void read_float_array(float[] value, int offset, int length) { + stream.read_float_array(value, offset, length); + } + public void read_double_array(double[] value, int offset, int length) { + stream.read_double_array(value, offset, length); + } + + public org.omg.CORBA.Object read_Object() { return stream.read_Object(); } + public java.io.Serializable read_value() {return stream.read_value();} + public TypeCode read_TypeCode() { return stream.read_TypeCode(); } + public Any read_any() { return stream.read_any(); } + @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.Principal read_Principal() { return stream.read_Principal(); } + public java.math.BigDecimal read_fixed() { return stream.read_fixed(); } + public org.omg.CORBA.Context read_Context() { return stream.read_Context(); } + + public org.omg.CORBA.ORB orb() { return stream.orb(); } + + public void addTypeCodeAtPosition(TypeCodeImpl tc, int position) { + if (typeMap == null) { + //if (TypeCodeImpl.debug) System.out.println("Creating typeMap"); + typeMap = new HashMap(16); + } + //if (TypeCodeImpl.debug) System.out.println(this + " adding tc " + // + tc + " at position " + position); + typeMap.put(position, tc); + } + + public TypeCodeImpl getTypeCodeAtPosition(int position) { + if (typeMap == null) + return null; + //if (TypeCodeImpl.debug) System.out.println("Getting tc " + // + typeMap.get(position) + " at position " + position); + return typeMap.get(position); + } + + public void setEnclosingInputStream(InputStream enclosure) { + // WrapperInputStream has no enclosure + } + + public TypeCodeReader getTopLevelStream() { + // WrapperInputStream has no enclosure + return this; + } + + public int getTopLevelPosition() { + //if (TypeCodeImpl.debug) System.out.println("WrapperInputStream.getTopLevelPosition " + + //"returning getPosition " + getPosition() + " - startPos " + startPos + + //" = " + (getPosition() - startPos)); + return getPosition() - startPos; + } + + public void performORBVersionSpecificInit() { + // This is never actually called on a WrapperInputStream, but + // exists to satisfy the interface requirement. + stream.performORBVersionSpecificInit(); + } + + public void resetCodeSetConverters() { + stream.resetCodeSetConverters(); + } + + public void printTypeMap() { + System.out.println("typeMap = {"); + List sortedKeys = new ArrayList(typeMap.keySet()); + Collections.sort(sortedKeys); + Iterator i = sortedKeys.iterator(); + while (i.hasNext()) { + Integer pos = i.next(); + TypeCodeImpl tci = typeMap.get(pos); + System.out.println(" key = " + pos.intValue() + ", value = " + tci.description()); + } + System.out.println("}"); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/folb/CSIv2SSLTaggedComponentHandler.java b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/CSIv2SSLTaggedComponentHandler.java new file mode 100644 index 000000000..f0fe2b884 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/CSIv2SSLTaggedComponentHandler.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jul 29 (Fri) 07:52:10 by Harold Carr. +// Last Modified : 2005 Aug 29 (Mon) 14:09:31 by Harold Carr. +// + +package com.sun.corba.ee.impl.folb; + +import java.util.List; +import org.omg.IOP.TaggedComponent; +import org.omg.PortableInterceptor.IORInfo; +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.transport.SocketInfo; + +/** + * An implementation of this interface org.omg.CORBA.LocalObject. + * An instance of this interface is plugged into the ORB via + * ORB.register_initial_reference(ORBConstants.CSIv2SSLTaggedComponentHandler, instance). + * + * @author Harold Carr + */ +public interface CSIv2SSLTaggedComponentHandler +{ + /** + * @param iorInfo - from IORInterceptor.establish_components. + * @param clusterInstanceInfo On the server-side, the FOLB system will pass all ClusterInstanceInfo + * to the CSIv2/SSL system. + * @return null or org.omg.IOP.TaggedComponent. + * The CSIv2SSL system returns null if no security + * information is to be added to IORs. Otherwise it returns the + * CSIv2SSL org.omg.IOP.TaggedComponent that will be + * added to IORs. + */ + public TaggedComponent insert(IORInfo iorInfo, + List clusterInstanceInfo); + + /** Extract is called on each invocation of the IOR, so that the security code can + * run properly. + * If the given IOR contains CSIv2SSL host/port + * info that should be used for this invocation then + * extract should return a List of SocketInfo. + * Otherwise it should return null. + * @param ior The target ior of the current invocation. + * @return List of all SocketInfos found in the IOR. + */ + public List extract(IOR ior); +} + +// End of file. + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/folb/ClientGroupManager.java b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/ClientGroupManager.java new file mode 100644 index 000000000..db30b4192 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/ClientGroupManager.java @@ -0,0 +1,761 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 07 (Tue) 13:04:09 by Harold Carr. +// Last Modified : 2005 Oct 03 (Mon) 15:09:46 by Harold Carr. +// + +package com.sun.corba.ee.impl.folb; + +import java.util.LinkedList; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecPackage.FormatMismatch; +import org.omg.IOP.CodecPackage.TypeMismatch; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.CodecFactoryPackage.UnknownEncoding; +import org.omg.IOP.Encoding; +import org.omg.IOP.ServiceContext; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ForwardRequestHelper; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; + +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; +import com.sun.corba.ee.spi.folb.GroupInfoService; +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBConfigurator ; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.impl.interceptors.ClientRequestInfoImpl; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; + +// BEGIN imports for IIOPPrimaryToContactInfo +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +// END imports for IIOPPrimaryToContactInfo + +// BEGIN import for IORToSocketInfo +import java.util.ArrayList; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent; +import com.sun.corba.ee.spi.ior.iiop.ClusterInstanceInfoComponent; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.trace.Folb; + +import org.omg.CosNaming.NamingContext ; +import org.omg.CosNaming.NamingContextHelper ; +import org.omg.CosNaming.NameComponent ; + +import javax.rmi.PortableRemoteObject ; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + + +// END import for IORToSocketInfo + +// REVISIT - log messages must be internationalized. + +/** + * @author Harold Carr + */ +@Folb +public class ClientGroupManager + extends + org.omg.CORBA.LocalObject + implements + ClientRequestInterceptor, + GroupInfoService, + IIOPPrimaryToContactInfo, + IORToSocketInfo, + ORBConfigurator, + ORBInitializer +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static final long serialVersionUID = 7849660203226017842L; + public final String baseMsg = ClientGroupManager.class.getName(); + + public static boolean sentMemberShipLabel = false; // For test. + public static boolean receivedIORUpdate = false; // For test. + + private ORB orb; + private Codec codec; + + private boolean initialized = false; + + private IOR lastIOR; // Initially null, thus the separate lock object. + private final Object lastIORLock = new Object(); + private CSIv2SSLTaggedComponentHandler csiv2SSLTaggedComponentHandler; + private transient GIS gis = new GIS(); + + public ClientGroupManager() { + } + + @InfoMethod + private void reportException( Exception exc ) { } + + @InfoMethod + private void notFound( String name ) { } + + @Folb + private void initialize() + { + if (initialized) { + return; + } + + try { + initialized = true; + + try { + csiv2SSLTaggedComponentHandler = + (CSIv2SSLTaggedComponentHandler) + orb.resolve_initial_references( + ORBConstants.CSI_V2_SSL_TAGGED_COMPONENT_HANDLER); + } catch (InvalidName e) { + csiv2SSLTaggedComponentHandler = null; + notFound( ORBConstants.CSI_V2_SSL_TAGGED_COMPONENT_HANDLER ); + } + CodecFactory codecFactory = + CodecFactoryHelper.narrow( + orb.resolve_initial_references( + ORBConstants.CODEC_FACTORY_NAME)); + + codec = codecFactory.create_codec( + new Encoding((short)0, (byte)1, (byte)2)); + } catch (InvalidName e) { + reportException( e ) ; + } catch (UnknownEncoding e) { + reportException( e ) ; + } + } + + //////////////////////////////////////////////////// + // + // IORToSocketInfo + // + + @InfoMethod + private void nonSSLSocketInfo() { } + + @InfoMethod + private void returningPreviousSocketInfo( List lst ) { } + + @Folb + public List getSocketInfo(IOR ior, List previous) + { + initialize(); + + try { + if (csiv2SSLTaggedComponentHandler != null) { + List csiv2 = + csiv2SSLTaggedComponentHandler.extract(ior); + if (csiv2 != null) { + /* The contract with CSIv2 says if SSL is to be used + then ONLY try SSL addresssses. */ + return csiv2; + } + } + + nonSSLSocketInfo(); + + if (! previous.isEmpty()) { + returningPreviousSocketInfo(previous); + return previous; + } + + List result = new ArrayList(); + + // + // IIOPProfile Primary address + // + + IIOPProfileTemplate iiopProfileTemplate = (IIOPProfileTemplate) + ior.getProfile().getTaggedProfileTemplate(); + IIOPAddress primary = iiopProfileTemplate.getPrimaryAddress() ; + String host = primary.getHost().toLowerCase(); + int port = primary.getPort(); + + SocketInfo primarySocketInfo = + createSocketInfo("primary", + SocketInfo.IIOP_CLEAR_TEXT, host, port); + result.add(primarySocketInfo); + + // + // List alternate cluster addresses + // + + final Iterator iterator = + iiopProfileTemplate.iteratorById( + ORBConstants.FOLB_MEMBER_ADDRESSES_TAGGED_COMPONENT_ID, + ClusterInstanceInfoComponent.class ); + + while (iterator.hasNext()) { + ClusterInstanceInfo clusterInstanceInfo = + iterator.next().getClusterInstanceInfo() ; + List endpoints = + clusterInstanceInfo.endpoints(); + for (com.sun.corba.ee.spi.folb.SocketInfo socketInfo : endpoints) { + result.add( createSocketInfo( + "ClusterInstanceInfo.endpoint", + socketInfo.type(), socketInfo.host(), + socketInfo.port())); + } + } + + // + // List alternate TAG_ALTERNATE_IIOP_ADDRESS (for corbaloc) + // + + final Iterator aiterator = + iiopProfileTemplate.iteratorById( + org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS.value, + AlternateIIOPAddressComponent.class ); + + while (aiterator.hasNext()) { + AlternateIIOPAddressComponent alternate = + aiterator.next(); + + host = alternate.getAddress().getHost().toLowerCase(); + port = alternate.getAddress().getPort(); + + result.add(createSocketInfo( + "AlternateIIOPAddressComponent", + SocketInfo.IIOP_CLEAR_TEXT, host, port)); + } + + return result; + + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + RuntimeException rte = new RuntimeException(e.getMessage()); + rte.initCause(e); + throw rte; + } + } + + @Folb + private SocketInfo createSocketInfo(final String msg, + final String type, + final String host, + final int port) + { + return new SocketInfo() { + public String getType() { + return type; + } + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } + + @Override + public boolean equals(Object o) { + if (o == null) { + return false; + } + if (! (o instanceof SocketInfo)) { + return false; + } + SocketInfo other = (SocketInfo)o; + if (other.getPort() != port) { + return false; + } + if (! other.getHost().equals(host)) { + return false; + } + if (! other.getType().equals(type)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "SocketInfo[" + type + " " + host + " " + port +"]"; + } + + @Override + public int hashCode() { + return port ^ host.hashCode() ^ type.hashCode() ; + } + }; + } + + //////////////////////////////////////////////////// + // + // IIOPPrimaryToContactInfo + // + + private Map map = new HashMap(); + + @Folb + public synchronized void reset(ContactInfo primary) + { + initialize(); + try { + map.remove(getKey(primary)); + } catch (Throwable t) { + throw wrapper.exceptionInReset( t ) ; + } + } + + @InfoMethod + private void hasNextInfo( int previousIndex, int contactInfoSize ) { } + + @Folb + public synchronized boolean hasNext(ContactInfo primary, + ContactInfo previous, + List contactInfos) + { + initialize(); + try { + boolean result; + if (previous == null) { + result = true; + } else { + int previousIndex = contactInfos.indexOf(previous); + int contactInfosSize = contactInfos.size(); + hasNextInfo(previousIndex, contactInfosSize); + if (previousIndex < 0) { + // This SHOULD not happen. + // It would only happen if the previous is NOT + // found in the current list of contactInfos. + RuntimeException rte = new RuntimeException( + + + "Problem in " + baseMsg + ".hasNext: previousIndex: " + + previousIndex); + // REVISIT - error message + throw rte; + } else { + // Since this is a retry, ensure that there is a following + // ContactInfo for .next + result = (contactInfosSize - 1) > previousIndex; + } + } + return result; + } catch (Throwable t) { + // REVISIT - error msg + RuntimeException rte = + new RuntimeException(baseMsg + ".hasNext error"); + rte.initCause(t); + throw rte; + } + } + + @InfoMethod + private void initializeMap() { } + + @InfoMethod + private void primaryMappedTo( Object obj ) { } + + @InfoMethod + private void cannotFindMappedEntry() { } + + @InfoMethod + private void iiopFailoverTo( Object obj ) { } + + @InfoMethod + private void mappedResult( Object obj ) { } + + @InfoMethod + private void mappedResultWithUpdate( Object obj, int prevIndex, int size ) { } + + @Folb + public synchronized ContactInfo next(ContactInfo primary, + ContactInfo previous, + List contactInfos) + { + initialize(); + try { + Object result = null; + + if (previous == null) { + // This is NOT a retry. + result = map.get(getKey(primary)); + if (result == null) { + initializeMap(); + // NOTE: do not map primary to primary. + // In case of local transport we NEVER use primary. + result = contactInfos.get(0); + map.put(getKey(primary), result); + } else { + primaryMappedTo(result); + int position = contactInfos.indexOf(result); + if (position == -1) { + // It is possible that communication to the key + // took place on SharedCDR, then a corbaloc to + // same location uses a SocketOrChannelContactInfo + // and vice versa. + cannotFindMappedEntry(); + reset(primary); + return next(primary, previous, contactInfos); + } + // NOTE: This step is critical. You do NOT want to + // return contact info from the map. You want to find + // it, as a SocketInfo, in the current list, and then + // return that ContactInfo. Otherwise you will potentially + // return a ContactInfo pointing to an incorrect IOR. + result = contactInfos.get(position); + mappedResult( result ) ; + } + } else { + // This is a retry. + // If previous is last element then .next is not called + // because hasNext will return false. + result = contactInfos.get(contactInfos.indexOf(previous) + 1); + map.put(getKey(primary), result); + + iiopFailoverTo(result); + + if (orb.folbDebugFlag) { + // Only compute if debugging here. + mappedResultWithUpdate(result, contactInfos.indexOf(previous), + contactInfos.size() ); + } + } + return (ContactInfo) result; + } catch (Throwable t) { + throw wrapper.exceptionInNext( t ) ; + } + } + + @Folb + private Object getKey(ContactInfo contactInfo) + { + if (((SocketInfo)contactInfo).getPort() == 0) { + // When CSIv2 is used the primary will have a zero port. + // Therefore type/host/port will NOT be unique. + // So use the entire IOR for the key in that case. + return contactInfo.getContactInfoList() + .getEffectiveTargetIOR(); + } else { + return contactInfo; + } + } + + //////////////////////////////////////////////////// + // + // GroupInfoService + // + + @Folb + public List getInitialClusterInstanceInfo(ORB orb, + List endpoints ) { + try { + org.omg.CORBA.Object ref ; + if (endpoints.isEmpty()) { + ref = orb.resolve_initial_references( "NameService"); + } else { + final StringBuilder sb = new StringBuilder() ; + sb.append( "corbaloc:" ) ; + boolean first = true ; + for (String str : endpoints ) { + if (first) { + first = false ; + } else { + sb.append( ',' ) ; + } + + sb.append( "iiop:1.2@" ).append( str ) ; + } + + sb.append( "/NameService" ) ; + ref = orb.string_to_object( sb.toString() ) ; + } + + NamingContext nctx = NamingContextHelper.narrow(ref); + NameComponent[] path = + { new NameComponent(ORBConstants.INITIAL_GROUP_INFO_SERVICE, "") }; + InitialGroupInfoService.InitialGIS initGIS = + (InitialGroupInfoService.InitialGIS)PortableRemoteObject.narrow( + nctx.resolve(path), InitialGroupInfoService.InitialGIS.class); + return initGIS.getClusterInstanceInfo(); + } catch (Exception e) { + reportException(e); + return null; + } + } + + private class GIS extends GroupInfoServiceBase + { + public List internalClusterInstanceInfo( List endpoints ) + { + if (lastIOR == null) { + return getInitialClusterInstanceInfo(orb, endpoints ); + } + + IIOPProfileTemplate iiopProfileTemplate; + synchronized (lastIORLock) { + iiopProfileTemplate = (IIOPProfileTemplate) + lastIOR.getProfile().getTaggedProfileTemplate(); + } + Iterator iterator = + iiopProfileTemplate.iteratorById( + ORBConstants.FOLB_MEMBER_ADDRESSES_TAGGED_COMPONENT_ID, + ClusterInstanceInfoComponent.class ); + + LinkedList results = + new LinkedList(); + + while (iterator.hasNext()) { + ClusterInstanceInfo clusterInstanceInfo = + iterator.next().getClusterInstanceInfo() ; + results.add(clusterInstanceInfo); + } + + return results; + } + + @Override + public boolean shouldAddAddressesToNonReferenceFactory(String[] x) + { + throw new RuntimeException("Should not be called in this context"); + } + + @Override + public boolean shouldAddMembershipLabel (String[] adapterName) + { + throw new RuntimeException("Should not be called in this context"); + } + } + + public boolean addObserver(GroupInfoServiceObserver x) + { + return gis.addObserver(x); + } + public void notifyObservers() + { + gis.notifyObservers(); + } + public List getClusterInstanceInfo( + String[] adapterName) + { + return gis.getClusterInstanceInfo(adapterName); + } + public List getClusterInstanceInfo( + String[] adapterName, List endpoints ) + { + return gis.getClusterInstanceInfo(adapterName,endpoints); + } + public boolean shouldAddAddressesToNonReferenceFactory(String[] x) + { + return gis.shouldAddAddressesToNonReferenceFactory(x); + } + public boolean shouldAddMembershipLabel (String[] adapterName) + { + return gis.shouldAddMembershipLabel(adapterName); + } + + //////////////////////////////////////////////////// + // + // Interceptor operations + // + + public String name() + { + return baseMsg; + } + + public void destroy() + { + } + + //////////////////////////////////////////////////// + // + // ClientRequestInterceptor + // + + @InfoMethod + private void sendRequestMembershipLabel( String label ) { } + + @InfoMethod + private void sendRequestNoMembershipLabel( ) { } + + @Folb + public void send_request(ClientRequestInfo ri) + { + try { + operation( ri.operation() ) ; + initialize(); // REVISIT - remove this one later? + + org.omg.CORBA.Object ref = ri.effective_target(); + IOR ior = orb.getIOR(ref,false); + IIOPProfileTemplate iiopProfileTemplate = (IIOPProfileTemplate) + ior.getProfile().getTaggedProfileTemplate(); + Iterator iterator = iiopProfileTemplate.iteratorById( + ORBConstants.FOLB_MEMBERSHIP_LABEL_TAGGED_COMPONENT_ID); + if (iterator.hasNext()) { + org.omg.IOP.TaggedComponent membershipLabelTaggedComponent = + ((com.sun.corba.ee.spi.ior.TaggedComponent)iterator.next()) + .getIOPComponent(orb); + byte[] data = membershipLabelTaggedComponent.component_data; + sentMemberShipLabel = true; // For test + sendRequestMembershipLabel( new String(data) ); + ServiceContext sc = new ServiceContext( + ORBConstants.FOLB_MEMBERSHIP_LABEL_SERVICE_CONTEXT_ID, + data); + ri.add_request_service_context(sc, false); + } else { + sentMemberShipLabel = false; // For test + sendRequestNoMembershipLabel() ; + } + } catch (RuntimeException e) { + throw e; + } + } + + public void send_poll(ClientRequestInfo ri) + { + } + + public void receive_reply(ClientRequestInfo ri) + { + receive_star(".receive_reply", ri); + } + + public void receive_exception(ClientRequestInfo ri) + { + receive_star(".receive_exception", ri); + } + + public void receive_other(ClientRequestInfo ri) + { + receive_star(".receive_other", ri); + } + + @InfoMethod + private void operation( String op ) { } + + @InfoMethod + private void noIORUpdate() { } + + @InfoMethod + private void receivedIORUpdateInfo() { } + + @Folb + private void receive_star(String point, ClientRequestInfo ri) + { + operation( ri.operation() ) ; + ServiceContext iorServiceContext = null; + try { + iorServiceContext = + ri.get_reply_service_context( + ORBConstants.FOLB_IOR_UPDATE_SERVICE_CONTEXT_ID); + } catch (BAD_PARAM e) { + wrapper.noIORUpdateServicateContext( e ) ; + } + + if (iorServiceContext == null) { + noIORUpdate(); + receivedIORUpdate = false; // For testing. + return; + } + + receivedIORUpdateInfo() ; + receivedIORUpdate = true ; + + IOR ior = extractIOR(iorServiceContext.context_data); + synchronized (lastIORLock) { + lastIOR = ior; // Used by LB. + gis.notifyObservers(); + } + reportLocatedIOR(ri, ior); + + } + + protected void reportLocatedIOR(ClientRequestInfo ri, IOR ior) { + // REVISIT - interface; + ((ClientRequestInfoImpl)ri).setLocatedIOR(ior); + } + + protected IOR extractIOR(byte[] data) { + Any any = null; + try { + any = codec.decode_value(data, ForwardRequestHelper.type()); + } catch (FormatMismatch e) { + reportException( e ) ; + } catch (TypeMismatch e) { + reportException( e ) ; + } + + // ForwardRequest is used for convenience. + // This code has nothing to do with PortableInterceptor. + ForwardRequest fr = ForwardRequestHelper.extract(any); + org.omg.CORBA.Object ref = fr.forward; + return orb.getIOR(ref,false); + } + + //////////////////////////////////////////////////// + // + // ORBInitializer + // + + public void pre_init(ORBInitInfo info) + { + } + + @Folb + public void post_init(ORBInitInfo info) { + try { + info.add_client_request_interceptor(this); + } catch (Exception e) { + reportException(e); + } + } + + //////////////////////////////////////////////////// + // + // ORBConfigurator + // + + @Folb + public void configure(DataCollector collector, ORB orb) + { + this.orb = orb; + orb.getORBData().addORBInitializer(this); + orb.getORBData().setIIOPPrimaryToContactInfo(this); + orb.getORBData().setIORToSocketInfo(this); + // So the load-balancer register to get get updates. + try { + orb.register_initial_reference( + ORBConstants.FOLB_CLIENT_GROUP_INFO_SERVICE, + this); + } catch (InvalidName e) { + reportException(e); + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/folb/GroupInfoServiceBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/GroupInfoServiceBase.java new file mode 100644 index 000000000..04f89ebb8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/GroupInfoServiceBase.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 13 (Mon) 11:04:09 by Harold Carr. +// Last Modified : 2005 Aug 09 (Tue) 16:31:38 by Harold Carr. +// + +package com.sun.corba.ee.impl.folb; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; + +import com.sun.corba.ee.spi.trace.Folb ; + +import com.sun.corba.ee.spi.folb.GroupInfoService; +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Folb +public abstract class GroupInfoServiceBase + extends org.omg.CORBA.LocalObject + implements GroupInfoService +{ + private List observers = + new LinkedList(); + + @Folb + public boolean addObserver(GroupInfoServiceObserver x) { + return observers.add(x); + } + + @InfoMethod + private void observerInfo( GroupInfoServiceObserver obs ) { } + + @Folb + public void notifyObservers() { + for (GroupInfoServiceObserver observer : observers) { + observerInfo( observer ) ; + observer.membershipChange(); + } + } + + @Folb + public List getClusterInstanceInfo( + String[] adapterName) { + + // Make a copy of the internal data + return new ArrayList( internalClusterInstanceInfo() ) ; + } + + public List getClusterInstanceInfo( + String[] adapterName, List endpoints ) { + + // Make a copy of the internal data + return new ArrayList( internalClusterInstanceInfo( endpoints ) ) ; + } + + @Folb + public boolean shouldAddAddressesToNonReferenceFactory( + String[] adapterName) { + return false ; + } + + @Folb + public boolean shouldAddMembershipLabel (String[] adapterName) { + return true ; + } + + public List internalClusterInstanceInfo() { + final List endpoints = new ArrayList() ; + return internalClusterInstanceInfo( endpoints ) ; + } + + public abstract List internalClusterInstanceInfo( List endpoints ) ; +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/folb/InitialGroupInfoService.java b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/InitialGroupInfoService.java new file mode 100644 index 000000000..e1e126f58 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/InitialGroupInfoService.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.folb; + + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +import java.util.List ; + +import javax.rmi.PortableRemoteObject ; + +import org.omg.CORBA.LocalObject ; + +import org.omg.CosNaming.NamingContext ; +import org.omg.CosNaming.NamingContextHelper ; +import org.omg.CosNaming.NameComponent ; + +//import com.sun.corba.ee.spi.orb.ORB ; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.spi.folb.GroupInfoService; + +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.ServantLocator ; + +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.CORBA.Policy; +import javax.rmi.CORBA.Tie; + +import org.omg.PortableServer.RequestProcessingPolicyValue ; +import org.omg.PortableServer.ServantRetentionPolicyValue ; +import com.sun.corba.ee.spi.trace.Folb; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + + +/** + * This class consists of : + * - Remote interface + * - Impl of the Remote interface + * - ServantLocator + * + * This is needed for getting the information about all the cluster endpoints + * when an appclient/standalone client enables FOLB. + * Without this feature, the client always ends up talking to only the endpoints specified + * as part of the endpoints property. But in reality, the the endpoints property only contains + * around 2 endpoints for bootstrapping purposes. + * + * In this design, we register the following remote object with CosNaming + * and then look it up in CosNaming to get hold of the cluster instances + * This is done only once (during the first call to new InitialContext()). + * + * @author Sheetal Vartak + */ +@Folb +public class InitialGroupInfoService { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public interface InitialGIS extends Remote { + public List getClusterInstanceInfo() + throws RemoteException ; + } + + @Folb + public static class InitialGISImpl extends PortableRemoteObject + implements InitialGIS { + + private ORB orb; + + public InitialGISImpl(ORB orb) throws RemoteException { + super() ; + this.orb = orb; + } + + @InfoMethod + private void exceptionReport( Exception exc ) { } + + @Folb + public List getClusterInstanceInfo() + throws RemoteException { + + try { + GroupInfoService gis = + (GroupInfoService)PortableRemoteObject.narrow( + orb.resolve_initial_references( + ORBConstants.FOLB_SERVER_GROUP_INFO_SERVICE), + GroupInfoService.class); + return gis.getClusterInstanceInfo(null); + } catch (org.omg.CORBA.ORBPackage.InvalidName inv) { + exceptionReport( inv ) ; + return null; + } + } + } + + public static class InitialGISServantLocator extends LocalObject + implements ServantLocator { + private Servant servant ; + private InitialGISImpl impl = null; + + public InitialGISServantLocator(ORB orb) { + try { + impl = new InitialGISImpl(orb) ; + } catch (Exception exc) { + wrapper.couldNotInitializeInitialGIS( exc ) ; + } + + Tie tie = com.sun.corba.ee.spi.orb.ORB.class.cast( orb ) + .getPresentationManager().getTie() ; + tie.setTarget( impl ) ; + servant = Servant.class.cast( tie ) ; + } + + public String getType() { + return servant._all_interfaces(null, null)[0]; + } + + public synchronized Servant preinvoke( byte[] oid, POA adapter, + String operation, CookieHolder the_cookie + ) throws ForwardRequest { + return servant ; + } + + public void postinvoke( byte[] oid, POA adapter, + String operation, Object the_cookie, Servant the_servant ) { + } + } + + public InitialGroupInfoService(ORB orb) { + bindName(orb); + } + + + public void bindName (ORB orb) { + try { + POA rootPOA = (POA)orb.resolve_initial_references( + ORBConstants.ROOT_POA_NAME ) ; + + Policy[] arr = new Policy[] { + rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN ), + rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER ), + rootPOA.create_lifespan_policy( + LifespanPolicyValue.TRANSIENT ) } ; + + POA poa = rootPOA.create_POA( ORBConstants.INITIAL_GROUP_INFO_SERVICE, + null, arr ) ; + + InitialGISServantLocator servantLocator = + new InitialGISServantLocator(orb); + poa.set_servant_manager(servantLocator) ; + poa.the_POAManager().activate(); + + byte[] id = new byte[]{ 1, 2, 3 } ; + org.omg.CORBA.Object provider = + poa.create_reference_with_id(id, servantLocator.getType()); + + // put object in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = + new NameComponent(ORBConstants.INITIAL_GROUP_INFO_SERVICE, ""); + NameComponent path[] = {nc}; + ncRef.rebind(path, provider); + } catch (Exception e) { + throw wrapper.bindNameException( e ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/folb/ServerGroupManager.java b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/ServerGroupManager.java new file mode 100644 index 000000000..78931ccb4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/folb/ServerGroupManager.java @@ -0,0 +1,617 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 08 (Tue) 14:04:09 by Harold Carr. +// Last Modified : 2005 Sep 28 (Wed) 09:40:45 by Harold Carr. +// + +package com.sun.corba.ee.impl.folb; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.rmi.server.UID; +import java.util.List; +import java.util.LinkedList; +import javax.rmi.PortableRemoteObject; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryHelper; +import org.omg.IOP.CodecFactoryPackage.UnknownEncoding; +import org.omg.IOP.Encoding; +import org.omg.IOP.ServiceContext; +import org.omg.IOP.TaggedComponent; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ForwardRequestHelper; +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.IORInterceptor; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; + +import com.sun.corba.ee.spi.folb.GroupInfoService; +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; +import com.sun.corba.ee.spi.folb.SocketInfo; + +import com.sun.corba.ee.spi.ior.iiop.ClusterInstanceInfoComponent ; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.legacy.interceptor.ServerRequestInfoExt; + +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager; +import com.sun.corba.ee.spi.orb.ORBConfigurator ; +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.trace.Folb; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Folb +public class ServerGroupManager + extends + org.omg.CORBA.LocalObject + implements + GroupInfoServiceObserver, + IORInterceptor, + ORBConfigurator, + ORBInitializer, + ServerRequestInterceptor +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static final String baseMsg = ServerGroupManager.class.getName(); + private static final long serialVersionUID = -3197578705750630503L; + + private transient ORB orb; + private transient GroupInfoService gis; + private transient CSIv2SSLTaggedComponentHandler + csiv2SSLTaggedComponentHandler; + private String membershipLabel; + + private enum MembershipChangeState { IDLE, DOING_WORK, RETRY_REQUIRED }; + private MembershipChangeState membershipChangeState = + MembershipChangeState.IDLE; + + private ReferenceFactoryManager referenceFactoryManager; + private Codec codec; + private boolean initialized = false; + + // REVISIT - the app server identifies socket "types" with + // these strings. Should be an official API. + private static final String SSL = com.sun.corba.ee.spi.transport.SocketInfo.SSL_PREFIX ; + private static final String CLEAR = com.sun.corba.ee.spi.transport.SocketInfo.IIOP_CLEAR_TEXT ; + + @InfoMethod + private void alreadyInitialized() { } + + @Folb + private void initialize() { + + if (initialized) { + alreadyInitialized(); + return; + } + + try { + initialized = true; + + updateMembershipLabel(); + + CodecFactory codecFactory = + CodecFactoryHelper.narrow( + orb.resolve_initial_references( + ORBConstants.CODEC_FACTORY_NAME)); + + codec = codecFactory.create_codec( + new Encoding((short)0, (byte)1, (byte)2)); + + referenceFactoryManager = (ReferenceFactoryManager) + orb.resolve_initial_references( + ORBConstants.REFERENCE_FACTORY_MANAGER); + + gis = (GroupInfoService) PortableRemoteObject.narrow( + orb.resolve_initial_references( + ORBConstants.FOLB_SERVER_GROUP_INFO_SERVICE), + GroupInfoService.class); + + gis.addObserver(this); + + try { + csiv2SSLTaggedComponentHandler = + (CSIv2SSLTaggedComponentHandler) + orb.resolve_initial_references( + ORBConstants.CSI_V2_SSL_TAGGED_COMPONENT_HANDLER); + } catch (InvalidName e) { + csiv2SSLTaggedComponentHandler = null; + wrapper.noCSIV2Handler( e ) ; + } + } catch (InvalidName e) { + wrapper.serverGroupManagerException( e ) ; + } catch (UnknownEncoding e) { + wrapper.serverGroupManagerException( e ) ; + } + } + + //////////////////////////////////////////////////// + // + // Interceptor operations + // + + public String name() { + return baseMsg; + } + + public void destroy() { + } + + //////////////////////////////////////////////////// + // + // IORInterceptor + // + + @InfoMethod + private void adapterName( String[] arr ) { } + + @InfoMethod + private void addingAddresses() { } + + @InfoMethod + private void notAddingAddress() { } + + @InfoMethod + private void addingMembershipLabel( String ml ) { } + + @InfoMethod + private void notAddingMembershipLabel( ) { } + + @InfoMethod + private void skippingEndpoint( SocketInfo si ) {} + + @InfoMethod + private void includingEndpoint( SocketInfo si ) {} + + @InfoMethod + private void addingInstanceInfoFor( String name, int weight ) {} + + @Folb + public void establish_components(IORInfo iorInfo) { + try { + initialize(); + + // Only handle ReferenceFactory adapters. + String[] adapterName = + ((com.sun.corba.ee.impl.interceptors.IORInfoImpl)iorInfo) + .getObjectAdapter().getAdapterTemplate().adapter_name(); + + adapterName( adapterName ) ; + + ReferenceFactory rf = referenceFactoryManager.find(adapterName); + if (rf == null) { + if (gis.shouldAddAddressesToNonReferenceFactory(adapterName)) { + addingAddresses() ; + } else { + notAddingAddress(); + return; + } + } + + // Get all addressing information. + + // both CLEAR and SSL + List info = + gis.getClusterInstanceInfo(adapterName); + + // Let security handle SSL infomation. + if (csiv2SSLTaggedComponentHandler != null) { + TaggedComponent csiv2 = + csiv2SSLTaggedComponentHandler.insert(iorInfo, info); + if (csiv2 != null) { + iorInfo.add_ior_component(csiv2); + } + } + + // Handle CLEAR_TEXT addresses. + for (ClusterInstanceInfo clusterInstanceInfo : info) { + addingInstanceInfoFor( clusterInstanceInfo.name(), + clusterInstanceInfo.weight() ) ; + + List listOfSocketInfo = + new LinkedList(); + + for (SocketInfo sinfo : clusterInstanceInfo.endpoints()) { + if (sinfo.type().startsWith( SSL )) { + skippingEndpoint(sinfo); + } else { + includingEndpoint(sinfo); + // Don't want junk like orb-listener-1 from GlassFish here + final SocketInfo si = new SocketInfo( CLEAR, sinfo.host(), sinfo.port() ) ; + listOfSocketInfo.add( si ) ; + } + } + + final ClusterInstanceInfo ninfo = new ClusterInstanceInfo( + clusterInstanceInfo.name(), + clusterInstanceInfo.weight(), + listOfSocketInfo ) ; + + ClusterInstanceInfoComponent comp = + IIOPFactories.makeClusterInstanceInfoComponent( + ninfo ) ; + + iorInfo.add_ior_component( comp.getIOPComponent(orb) ) ; + } + + // Handle membership label. + if (gis.shouldAddMembershipLabel(adapterName)) { + TaggedComponent tc = new TaggedComponent( + ORBConstants.FOLB_MEMBERSHIP_LABEL_TAGGED_COMPONENT_ID, + membershipLabel.getBytes()); + + addingMembershipLabel( membershipLabel ); + iorInfo.add_ior_component(tc); + } else { + notAddingMembershipLabel(); + } + } catch (RuntimeException e) { + wrapper.serverGroupManagerException(e); + } + } + + public void components_established( IORInfo iorInfo ) { + } + + public void adapter_manager_state_changed( int managerId, short state ) { + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, + short state ) { + } + + //////////////////////////////////////////////////// + // + // GroupInfoServiceObserver + // + + @InfoMethod + private void alreadyChangingMembership() { } + + @InfoMethod + private void loopingForMembershipChange() { } + + @InfoMethod + private void unexpectedStateForMembershipChange() { } + + @Folb + public void membershipChange() { + try { + synchronized (this) { + if (membershipChangeState == MembershipChangeState.IDLE) { + membershipChangeState = MembershipChangeState.DOING_WORK; + } else { + // State is DOING_WORK or RETRY_REQUIRED. + membershipChangeState = MembershipChangeState.RETRY_REQUIRED; + alreadyChangingMembership(); + return; + } + } + + boolean loop; + + do { + loop = false; + + restartFactories(); + + synchronized (this) { + if (membershipChangeState == MembershipChangeState.RETRY_REQUIRED) { + membershipChangeState = MembershipChangeState.DOING_WORK; + // One or more notifies arrived while processing + // this notify. Therefore do the restart again. + loop = true; + loopingForMembershipChange(); + } else if (membershipChangeState == MembershipChangeState.DOING_WORK) { + membershipChangeState = MembershipChangeState.IDLE; + } else if (membershipChangeState == MembershipChangeState.IDLE) { + unexpectedStateForMembershipChange(); + } + } + } while (loop); + + } catch (RuntimeException e) { + wrapper.serverGroupManagerException(e); + + // If we get an exception we need to ensure that we do not + // lock out further changes. + synchronized (this) { + membershipChangeState = MembershipChangeState.IDLE; + } + } + } + + + @Folb + public class WorkerThread extends Thread { + @InfoMethod + private void suspendRFM() { } + + @InfoMethod + private void updateMembershipLabelInfo() { } + + @InfoMethod + private void restartFactories() { } + + @InfoMethod + private void resumeRFM() { } + + @Folb + @Override + public void run() { + try { + suspendRFM() ; + referenceFactoryManager.suspend(); + + // Requests have drained so update label. + // IMPORTANT: do not update label until requests + // have drained. Otherwise responses will compare + // against wrong label. + updateMembershipLabelInfo(); + updateMembershipLabel(); + + restartFactories(); + referenceFactoryManager.restartFactories(); + } finally { + resumeRFM(); + referenceFactoryManager.resume(); + } + } + } + + @InfoMethod + private void waitingForWorkerTermination() { } + + @Folb + private void restartFactories() { + // + // REVISIT + // + // restart gets exception since a remote call is coming + // in on a non-ReferenceFactory POA. The ORB does not + // discriminate the granularity of restart. + // See ORBImpl.isDuringDispatch + // + // Workaround by using a different thread. + // + // Note: this is only a problem in the test because + // the test client sends an "add" message that + // is serviced by a server worker thread that calls + // membershipChange. This method calls restartFactories + // that calls destory POA that calls isDuringDispatch. + // isDuringDispatch uses a thread local to determine + // it is a dispatch. Using another thread fools + // isDuringDispatch into letting this chain proceed. + // + + final ReferenceFactoryManager rfm = referenceFactoryManager; + + Thread worker = new WorkerThread() ; + + worker.start(); + + // Make sure the worker terminates before we continue + waitingForWorkerTermination(); + boolean tryAgain; + do { + tryAgain = false; + + try { + worker.join(); + } catch (InterruptedException e) { + Thread.interrupted() ; + tryAgain = true; + } + } while (tryAgain); + } + + @InfoMethod + private void newMembershipLabel( String ml ) { } + + @Folb + private void updateMembershipLabel() { + UID uid = new UID(); + String hostAddress = null; + try { + // REVISIT + // name could match GroupInfoService's idea of instance id/name. + // Not necessary but easier to debug. + hostAddress = InetAddress.getLocalHost().getHostAddress(); + membershipLabel = hostAddress + ":::" + uid; + newMembershipLabel( membershipLabel ); + } catch (UnknownHostException e) { + wrapper.serverGroupManagerException(e); + } + } + + //////////////////////////////////////////////////// + // + // ServerRequestInterceptor + // + + @Folb + public void receive_request_service_contexts(ServerRequestInfo ri) + { + initialize(); + } + + @Folb + public void receive_request(ServerRequestInfo ri) + { + initialize(); + } + + public void send_reply(ServerRequestInfo ri) + { + send_star(".send_reply", ri); + } + + public void send_exception(ServerRequestInfo ri) + { + send_star(".send_exception", ri); + } + + public void send_other(ServerRequestInfo ri) + { + send_star(".send_other", ri); + } + + @InfoMethod + private void rfmIsHolding() { } + + @InfoMethod + private void notManagedByReferenceFactory( String[] adapterName ) { } + + @InfoMethod + private void membershipLabelsEqual() { } + + @InfoMethod + private void membershipLabelsNotEqual() { } + + @InfoMethod + private void membershipLabelsNotPresent() { } + + @InfoMethod + private void sendingUpdatedIOR( String[] adapterName ) { } + + /** + * If the request membership label is out-of-date or missing + * then return an updated IOR. + */ + @Folb + private void send_star(String point, ServerRequestInfo ri) + { + String[] adapterName = null; + try { + adapterName = ri.adapter_name(); + + if (referenceFactoryManager.getState() == + ReferenceFactoryManager.RFMState.SUSPENDED) { + + rfmIsHolding(); + return; + } + + ReferenceFactory referenceFactory = + referenceFactoryManager.find(adapterName); + + // Only handle RefenceFactory adapters. + if (referenceFactory == null && + !((ServerRequestInfoExt)ri).isNameService()) { + notManagedByReferenceFactory( adapterName ) ; + return; + } + + // Handle membership label from request. + String requestMembershipLabel = null; + try { + ServiceContext sc = ri.get_request_service_context( + ORBConstants.FOLB_MEMBERSHIP_LABEL_SERVICE_CONTEXT_ID); + // REVISIT - internationalization + if (sc != null) { + byte[] data = sc.context_data; + requestMembershipLabel = new String(data); + + if (membershipLabel.equals(requestMembershipLabel)) { + membershipLabelsEqual(); + return; + } + membershipLabelsNotEqual(); + } + } catch (BAD_PARAM e) { + membershipLabelsNotPresent(); + // REVISIT: CHECK: if not our ORB then return. -- + } + + // Send IOR UPDATE + // + // At this point either the labels do not match + // or our ORB has sent a request without a label (e.g., bootstrap). + // Therefore send an updated IOR. + sendingUpdatedIOR( adapterName ) ; + + byte[] objectId = ri.object_id(); + org.omg.CORBA.Object ref = + referenceFactory.createReference(objectId); + Any any = orb.create_any(); + // ForwardRequest is used for convenience. + // This code has nothing to do with PortableInterceptor. + ForwardRequest fr = new ForwardRequest(ref); + ForwardRequestHelper.insert(any, fr); + byte[] data = null; + try { + data = codec.encode_value(any); + } catch (InvalidTypeForEncoding e) { + wrapper.serverGroupManagerException(e); + } + ServiceContext sc = new ServiceContext( + ORBConstants.FOLB_IOR_UPDATE_SERVICE_CONTEXT_ID, data); + ri.add_reply_service_context(sc, false); + } catch (RuntimeException e) { + wrapper.serverGroupManagerException(e); + } + } + + //////////////////////////////////////////////////// + // + // ORBInitializer + // + + public void pre_init(ORBInitInfo info) + { + } + + @Folb + public void post_init(ORBInitInfo info) { + try { + info.add_ior_interceptor(this); + info.add_server_request_interceptor(this); + } catch (Exception e) { + wrapper.serverGroupManagerException(e); + } + } + + //////////////////////////////////////////////////// + // + // ORBConfigurator + // + + @Folb + public void configure(DataCollector collector, ORB orb) + { + this.orb = orb; + + // Setup for IOR and ServerRequest Interceptors + orb.getORBData().addORBInitializer(this); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/CDREncapsCodec.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/CDREncapsCodec.java new file mode 100644 index 000000000..ffb3e0cf4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/CDREncapsCodec.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TypeCode; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.impl.encoding.EncapsInputStream; +import com.sun.corba.ee.impl.encoding.EncapsInputStreamFactory; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import org.omg.IOP.Codec; +import org.omg.IOP.CodecPackage.FormatMismatch; +import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; +import org.omg.IOP.CodecPackage.TypeMismatch; + +/** + * CDREncapsCodec is an implementation of Codec, as described + * in orbos/99-12-02, that supports CDR encapsulation version 1.0, 1.1, and + * 1.2. + */ +public final class CDREncapsCodec + extends org.omg.CORBA.LocalObject + implements Codec +{ + // The ORB that created the factory this codec was created from + private transient ORB orb; + static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // The GIOP version we are encoding for + private transient GIOPVersion giopVersion; + + /* + ******************************************************************* + * NOTE: CDREncapsCodec must remain immutable! This is so that we + * can pre-create CDREncapsCodecs for each version of GIOP in + * CodecFactoryImpl. + *******************************************************************/ + + /** + * Creates a new codec implementation. Uses the given ORB to create + * CDRInputStreams when necessary. + * + * @param orb The ORB to use to create a CDRInputStream or CDROutputStream + * @param major The major version of GIOP we are encoding for + * @param minor The minor version of GIOP we are encoding for + */ + public CDREncapsCodec( ORB orb, int major, int minor ) { + this.orb = orb; + + giopVersion = GIOPVersion.getInstance( (byte)major, (byte)minor ); + } + + /** + * Convert the given any into a CDR encapsulated octet sequence + */ + public byte[] encode( Any data ) + throws InvalidTypeForEncoding + { + if ( data == null ) + throw wrapper.nullParamNoComplete() ; + return encodeImpl( data, true ); + } + + /** + * Decode the given octet sequence into an any based on a CDR + * encapsulated octet sequence. + */ + public Any decode ( byte[] data ) + throws FormatMismatch + { + if( data == null ) + throw wrapper.nullParamNoComplete() ; + return decodeImpl( data, null ); + } + + /** + * Convert the given any into a CDR encapsulated octet sequence. Only + * the data is stored. The type code is not. + */ + public byte[] encode_value( Any data ) + throws InvalidTypeForEncoding + { + if( data == null ) + throw wrapper.nullParamNoComplete() ; + return encodeImpl( data, false ); + } + + /** + * Decode the given octet sequence into an any based on a CDR + * encapsulated octet sequence. The type code is expected not to appear + * in the octet sequence, and the given type code is used instead. + */ + public Any decode_value( byte[] data, TypeCode tc ) + throws FormatMismatch, TypeMismatch + { + if( data == null ) + throw wrapper.nullParamNoComplete() ; + if( tc == null ) + throw wrapper.nullParamNoComplete() ; + return decodeImpl( data, tc ); + } + + /** + * Convert the given any into a CDR encapsulated octet sequence. + * If sendTypeCode is true, the type code is sent with the message, as in + * a standard encapsulation. If it is false, only the data is sent. + * Either way, the endian type is sent as the first part of the message. + */ + private byte[] encodeImpl( Any data, boolean sendTypeCode ) + throws InvalidTypeForEncoding + { + if( data == null ) + throw wrapper.nullParamNoComplete() ; + + // _REVISIT_ Note that InvalidTypeForEncoding is never thrown in + // the body of this method. This is due to the fact that CDR*Stream + // will never throw an exception if the encoding is invalid. To + // fix this, the CDROutputStream must know the version of GIOP it + // is encoding for and it must check to ensure that, for example, + // wstring cannot be encoded in GIOP 1.0. + // + // As part of the GIOP 1.2 work, the CDRInput and OutputStream will + // be versioned. This can be handled once this work is complete. + + byte[] retValue; + + // Always use CDR encoding for codec streams. If the thread local + // encoding version is set to JSG, push CDR encoding to the thread + // local state, and pop it at the end of this method. + + boolean pop = false; + if (ORBUtility.getEncodingVersion() != + ORBConstants.CDR_ENC_VERSION) { + ORBUtility.pushEncVersionToThreadLocalState(ORBConstants.CDR_ENC_VERSION); + pop = true; + } + + try { + + // Create output stream with default endianness. + EncapsOutputStream cdrOut = + OutputStreamFactory.newEncapsOutputStream((com.sun.corba.ee.spi.orb.ORB)orb, + giopVersion); + + // This is an encapsulation, so put out the endian: + cdrOut.putEndian(); + + // Sometimes encode type code: + if( sendTypeCode ) { + cdrOut.write_TypeCode( data.type() ); + } + + // Encode value and return. + data.write_value( cdrOut ); + + retValue = cdrOut.toByteArray(); + + } finally { + if (pop) { + ORBUtility.popEncVersionFromThreadLocalState(); + } + } + + return retValue; + } + + /** + * Decode the given octet sequence into an any based on a CDR + * encapsulated octet sequence. If the type code is null, it is + * expected to appear in the octet sequence. Otherwise, the given + * type code is used. + */ + private Any decodeImpl( byte[] data, TypeCode tc ) + throws FormatMismatch + { + if( data == null ) + throw wrapper.nullParamNoComplete() ; + + AnyImpl any = null; // return value + + // _REVISIT_ Currently there is no way for us to distinguish between + // a FormatMismatch and a TypeMismatch because we cannot get this + // information from the CDRInputStream. If a RuntimeException occurs, + // it is turned into a FormatMismatch exception. + + // Always use CDR encoding for codec streams. If the thread local + // encoding version is set to JSG, push CDR encoding to the thread + // local state, and pop it at the end of this method. + + boolean pop = false; + if (ORBUtility.getEncodingVersion() != + ORBConstants.CDR_ENC_VERSION) { + ORBUtility.pushEncVersionToThreadLocalState(ORBConstants.CDR_ENC_VERSION); + pop = true; + } + + try { + + EncapsInputStream cdrIn = EncapsInputStreamFactory.newEncapsInputStream( orb, data, + data.length, giopVersion ); + + cdrIn.consumeEndian(); + + // If type code not specified, read it from octet stream: + if( tc == null ) { + tc = cdrIn.read_TypeCode(); + } + + // Create a new Any object: + any = new AnyImpl( (com.sun.corba.ee.spi.orb.ORB)orb ); + any.read_value( cdrIn, tc ); + + } catch( RuntimeException e ) { + // See above note. + throw new FormatMismatch(); + } finally { + if (pop) { + ORBUtility.popEncVersionFromThreadLocalState(); + } + } + + return any; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ClientRequestInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ClientRequestInfoImpl.java new file mode 100644 index 000000000..813f48e7d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ClientRequestInfoImpl.java @@ -0,0 +1,990 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import java.util.Map ; +import java.util.HashMap ; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.Context; +import org.omg.CORBA.ContextList; +import org.omg.CORBA.CTX_RESTRICT_SCOPE; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.NVList; +import org.omg.CORBA.Object; +import org.omg.CORBA.Policy; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.ApplicationException; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; + +import org.omg.IOP.ServiceContext; +import org.omg.IOP.TaggedProfile; +import org.omg.IOP.TaggedComponent; +import org.omg.Dynamic.Parameter; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.LOCATION_FORWARD; +import org.omg.PortableInterceptor.SUCCESSFUL; +import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; +import org.omg.PortableInterceptor.TRANSPORT_RETRY; +import org.omg.PortableInterceptor.USER_EXCEPTION; + + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +// 6763340 +import com.sun.corba.ee.spi.protocol.RetryType; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfoListIterator; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.protocol.InvocationInfo; +import com.sun.corba.ee.spi.trace.TraceInterceptor; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * Implementation of the ClientRequestInfo interface as specified in + * orbos/99-12-02 section 5.4.2. + */ +@TraceInterceptor +public final class ClientRequestInfoImpl + extends RequestInfoImpl + implements ClientRequestInfo +{ + + // The available constants for startingPointCall + static final int CALL_SEND_REQUEST = 0; + static final int CALL_SEND_POLL = 1; + + // The available constants for endingPointCall + static final int CALL_RECEIVE_REPLY = 0; + static final int CALL_RECEIVE_EXCEPTION = 1; + static final int CALL_RECEIVE_OTHER = 2; + + ////////////////////////////////////////////////////////////////////// + // + // NOTE: IF AN ATTRIBUTE IS ADDED, PLEASE UPDATE RESET(); + // + ////////////////////////////////////////////////////////////////////// + + // The current retry request status. True if this request is being + // retried and this info object is to be reused, or false otherwise. + private RetryType retryRequest; + + // The number of times this info object has been (re)used. This is + // incremented every time a request is retried, and decremented every + // time a request is complete. When this reaches zero, the info object + // is popped from the ClientRequestInfoImpl ThreadLocal stack in the ORB. + private int entryCount = 0; + + // The RequestImpl is set when the call is DII based. + // The DII query calls like ParameterList, ExceptionList, + // ContextList will be delegated to RequestImpl. + private org.omg.CORBA.Request request; + + // Sources of client request information + private boolean diiInitiate; + private MessageMediator messageMediator; + + // Cached information: + private org.omg.CORBA.Object cachedTargetObject; + private org.omg.CORBA.Object cachedEffectiveTargetObject; + private Parameter[] cachedArguments; + private TypeCode[] cachedExceptions; + private String[] cachedContexts; + private String[] cachedOperationContext; + private String cachedReceivedExceptionId; + private Any cachedResult; + private Any cachedReceivedException; + private TaggedProfile cachedEffectiveProfile; + // key = Integer, value = IOP.ServiceContext. + private Map cachedRequestServiceContexts; + private Map cachedReplyServiceContexts; + private Map cachedEffectiveComponents; + + + private boolean piCurrentPushed; + + ////////////////////////////////////////////////////////////////////// + // + // NOTE: IF AN ATTRIBUTE IS ADDED, PLEASE UPDATE RESET(); + // + ////////////////////////////////////////////////////////////////////// + + /** + * Reset the info object so that it can be reused for a retry, + * for example. + */ + @TraceInterceptor + @Override + void reset() { + super.reset(); + + // Please keep these in the same order that they're declared above. + + // 6763340 + retryRequest = RetryType.NONE; + + // Do not reset entryCount because we need to know when to pop this + // from the stack. + + request = null; + diiInitiate = false; + messageMediator = null; + + // Clear cached attributes: + cachedTargetObject = null; + cachedEffectiveTargetObject = null; + cachedArguments = null; + cachedExceptions = null; + cachedContexts = null; + cachedOperationContext = null; + cachedReceivedExceptionId = null; + cachedResult = null; + cachedReceivedException = null; + cachedEffectiveProfile = null; + cachedRequestServiceContexts = null; + cachedReplyServiceContexts = null; + cachedEffectiveComponents = null; + + piCurrentPushed = false; + + startingPointCall = CALL_SEND_REQUEST; + endingPointCall = CALL_RECEIVE_REPLY; + } + + /* + ********************************************************************** + * Access protection + **********************************************************************/ + + // Method IDs for all methods in ClientRequestInfo. This allows for a + // convenient O(1) lookup for checkAccess(). + private static final int MID_TARGET = MID_RI_LAST + 1; + private static final int MID_EFFECTIVE_TARGET = MID_RI_LAST + 2; + private static final int MID_EFFECTIVE_PROFILE = MID_RI_LAST + 3; + private static final int MID_RECEIVED_EXCEPTION = MID_RI_LAST + 4; + private static final int MID_RECEIVED_EXCEPTION_ID = MID_RI_LAST + 5; + private static final int MID_GET_EFFECTIVE_COMPONENT = MID_RI_LAST + 6; + private static final int MID_GET_EFFECTIVE_COMPONENTS = MID_RI_LAST + 7; + private static final int MID_GET_REQUEST_POLICY = MID_RI_LAST + 8; + private static final int MID_ADD_REQUEST_SERVICE_CONTEXT = MID_RI_LAST + 9; + + // ClientRequestInfo validity table (see ptc/00-08-06 table 21-1). + // Note: These must be in the same order as specified in contants. + private static final boolean validCall[][] = { + // LEGEND: + // s_req = send_request r_rep = receive_reply + // s_pol = send_poll r_exc = receive_exception + // r_oth = receive_other + // + // A true value indicates call is valid at specified point. + // A false value indicates the call is invalid. + // + // + // NOTE: If the order or number of columns change, update + // checkAccess() accordingly. + // + // { s_req, s_pol, r_rep, r_exc, r_oth } + // RequestInfo methods: + /*request_id*/ { true , true , true , true , true }, + /*operation*/ { true , true , true , true , true }, + /*arguments*/ { true , false, true , false, false }, + /*exceptions*/ { true , false, true , true , true }, + /*contexts*/ { true , false, true , true , true }, + /*operation_context*/ { true , false, true , true , true }, + /*result*/ { false, false, true , false, false }, + /*response_expected*/ { true , true , true , true , true }, + /*sync_scope*/ { true , false, true , true , true }, + /*reply_status*/ { false, false, true , true , true }, + /*forward_reference*/ { false, false, false, false, true }, + /*get_slot*/ { true , true , true , true , true }, + /*get_request_service_context*/ { true , false, true , true , true }, + /*get_reply_service_context*/ { false, false, true , true , true }, + // + // ClientRequestInfo methods:: + /*target*/ { true , true , true , true , true }, + /*effective_target*/ { true , true , true , true , true }, + /*effective_profile*/ { true , true , true , true , true }, + /*received_exception*/ { false, false, false, true , false }, + /*received_exception_id*/ { false, false, false, true , false }, + /*get_effective_component*/ { true , false, true , true , true }, + /*get_effective_components*/ { true , false, true , true , true }, + /*get_request_policy*/ { true , false, true , true , true }, + /*add_request_service_context*/ { true , false, false, false, false } + }; + + + /* + ********************************************************************** + * Public ClientRequestInfo interfaces + **********************************************************************/ + + /** + * Creates a new ClientRequestInfo implementation. + * The constructor is package scope since no other package need create + * an instance of this class. + */ + protected ClientRequestInfoImpl( ORB myORB ) { + super( myORB ); + startingPointCall = CALL_SEND_REQUEST; + endingPointCall = CALL_RECEIVE_REPLY; + } + + /** + * The object which the client called to perform the operation. + */ + @TraceInterceptor + public org.omg.CORBA.Object target (){ + // access is currently valid for all states: + //checkAccess( MID_TARGET ); + if (messageMediator != null && cachedTargetObject == null) { + ContactInfo corbaContactInfo = (ContactInfo) + messageMediator.getContactInfo(); + cachedTargetObject = + iorToObject(corbaContactInfo.getTargetIOR()); + } + return cachedTargetObject; + } + + /** + * The actual object on which the operation will be invoked. If the + * reply_status is LOCATION_FORWARD, then on subsequent requests, + * effective_target will contain the forwarded IOR while target will + * remain unchanged. + */ + @TraceInterceptor + public org.omg.CORBA.Object effective_target() { + // access is currently valid for all states: + //checkAccess( MID_EFFECTIVE_TARGET ); + + // Note: This is not necessarily the same as locatedIOR. + // Reason: See the way we handle COMM_FAILURES in + // ClientRequestDispatcher.createRequest, v1.32 + + if (messageMediator != null && cachedEffectiveTargetObject == null) { + ContactInfo corbaContactInfo = messageMediator.getContactInfo(); + // REVISIT - get through chain like getLocatedIOR helper below. + cachedEffectiveTargetObject = + iorToObject(corbaContactInfo.getEffectiveTargetIOR()); + } + return cachedEffectiveTargetObject; + } + + /** + * The profile that will be used to send the request. If a location + * forward has occurred for this operation's object and that object's + * profile change accordingly, then this profile will be that located + * profile. + */ + @TraceInterceptor + public TaggedProfile effective_profile (){ + // access is currently valid for all states: + //checkAccess( MID_EFFECTIVE_PROFILE ); + + if(messageMediator != null && cachedEffectiveProfile == null ) { + ContactInfo corbaContactInfo = messageMediator.getContactInfo(); + cachedEffectiveProfile = + corbaContactInfo.getEffectiveProfile().getIOPProfile(); + } + + // Good citizen: In the interest of efficiency, we assume interceptors + // will not modify the returned TaggedProfile in any way so we need + // not make a deep copy of it. + + return cachedEffectiveProfile; + } + + /** + * Contains the exception to be returned to the client. + */ + @TraceInterceptor + public Any received_exception (){ + checkAccess( MID_RECEIVED_EXCEPTION ); + + if( cachedReceivedException == null ) { + cachedReceivedException = exceptionToAny( exception ); + } + + // Good citizen: In the interest of efficiency, we assume interceptors + // will not modify the returned Any in any way so we need + // not make a deep copy of it. + + return cachedReceivedException; + } + + /** + * The CORBA::RepositoryId of the exception to be returned to the client. + */ + @TraceInterceptor + public String received_exception_id (){ + checkAccess( MID_RECEIVED_EXCEPTION_ID ); + + if( cachedReceivedExceptionId == null ) { + String result = null; + + if( exception == null ) { + // Note: exception should never be null here since we will + // throw a BAD_INV_ORDER if this is not called from + // receive_exception. + throw wrapper.exceptionWasNull() ; + } else if( exception instanceof SystemException ) { + String name = exception.getClass().getName(); + result = ORBUtility.repositoryIdOf(name); + } else if( exception instanceof ApplicationException ) { + result = ((ApplicationException)exception).getId(); + } + + // _REVISIT_ We need to be able to handle a UserException in the + // DII case. How do we extract the ID from a UserException? + + cachedReceivedExceptionId = result; + } + + return cachedReceivedExceptionId; + } + + /** + * Returns the IOP::TaggedComponent with the given ID from the profile + * selected for this request. IF there is more than one component for a + * given component ID, it is undefined which component this operation + * returns (get_effective_component should be called instead). + */ + @TraceInterceptor + public TaggedComponent get_effective_component (int id){ + checkAccess( MID_GET_EFFECTIVE_COMPONENT ); + + TaggedComponent[] comps = get_effective_components( id ) ; + if ((comps != null) && (comps.length > 0)) { + return comps[0]; + } else { + return null ; + } + } + + /** + * Returns all the tagged components with the given ID from the profile + * selected for this request. + */ + @TraceInterceptor + public TaggedComponent[] get_effective_components (int id){ + checkAccess( MID_GET_EFFECTIVE_COMPONENTS ); + TaggedComponent[] result = null; + boolean justCreatedCache = false; + + if( cachedEffectiveComponents == null ) { + cachedEffectiveComponents = new HashMap(); + justCreatedCache = true; + } else { + // Look in cache: + result = cachedEffectiveComponents.get( id ); + } + + // null could mean we cached null or not in cache. + if( (messageMediator != null) && (result == null) && + (justCreatedCache || + !cachedEffectiveComponents.containsKey( id ) ) ) + { + // Not in cache. Get it from the profile: + ContactInfo corbaContactInfo = messageMediator.getContactInfo(); + IIOPProfileTemplate ptemp = + (IIOPProfileTemplate)corbaContactInfo.getEffectiveProfile(). + getTaggedProfileTemplate(); + result = ptemp.getIOPComponents(myORB, id); + cachedEffectiveComponents.put( id, result ); + } + + // As per ptc/00-08-06, section 21.3.13.6., If not found, raise + // BAD_PARAM with minor code INVALID_COMPONENT_ID. + if( (result == null) || (result.length == 0) ) { + if (!myORB.getORBData().isAppServerMode()) { + /** Issue 15931: the new wrapper mechanism is currently + * a lot slower than the old, and this is taking too + * long. We shouldn't indicate a normal condition with + * an exception in any case, but that's a flaw in the + * standard. So, if we are running in the app server, + * don't do this: just return null. + */ + throw stdWrapper.invalidComponentId( id ) ; + } + } + + // Good citizen: In the interest of efficiency, we will assume + // interceptors will not modify the returned TaggedCompoent[], or + // the TaggedComponents inside of it. Otherwise, we would need to + // clone the array and make a deep copy of its contents. + + return result; + } + + /** + * Returns the given policy in effect for this operation. + */ + @TraceInterceptor + public Policy get_request_policy (int type){ + checkAccess( MID_GET_REQUEST_POLICY ); + // _REVISIT_ Our ORB is not policy-based at this time. + throw wrapper.piOrbNotPolicyBased() ; + } + + /** + * Allows interceptors to add service contexts to the request. + *

    + * There is no declaration of the order of the service contexts. They + * may or may not appear in the order they are added. + */ + @TraceInterceptor + public void add_request_service_context (ServiceContext service_context, + boolean replace) { + + checkAccess( MID_ADD_REQUEST_SERVICE_CONTEXT ); + + if( cachedRequestServiceContexts == null ) { + cachedRequestServiceContexts = + new HashMap(); + } + + addServiceContext( cachedRequestServiceContexts, + messageMediator.getRequestServiceContexts(), + service_context, replace ); + } + + // NOTE: When adding a method, be sure to: + // 1. Add a MID_* constant for that method + // 2. Call checkAccess at the start of the method + // 3. Define entries in the validCall[][] table for interception points. + + /* + ********************************************************************** + * Public RequestInfo interfaces + * + * These are implemented here because they have differing + * implementations depending on whether this is a client or a server + * request info object. + **********************************************************************/ + + /** + * See RequestInfoImpl for javadoc. + */ + public int request_id (){ + // access is currently valid for all states: + //checkAccess( MID_REQUEST_ID ); + /* + * NOTE: The requestId in client interceptors is the same as the + * GIOP request id. This works because both interceptors and + * request ids are scoped by the ORB on the client side. + */ + return messageMediator.getRequestId(); + } + + /** + * See RequestInfoImpl for javadoc. + */ + public String operation(){ + // access is currently valid for all states: + //checkAccess( MID_OPERATION ); + if (messageMediator != null) { + return messageMediator.getOperationName(); + } else { + return ""; + } + } + + @Override + public String toString() { + return "ClientRequestInfoImpl[operation=" + + operation() + "]" ; + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public Parameter[] arguments (){ + checkAccess( MID_ARGUMENTS ); + + if( cachedArguments == null ) { + if( request == null ) { + throw stdWrapper.piOperationNotSupported1() ; + } + + // If it is DII request then get the arguments from the DII req + // and convert that into parameters. + cachedArguments = nvListToParameterArray( request.arguments() ); + } + + // Good citizen: In the interest of efficiency, we assume + // interceptors will be "good citizens" in that they will not + // modify the contents of the Parameter[] array. We also assume + // they will not change the values of the containing Anys. + + return cachedArguments; + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public TypeCode[] exceptions (){ + checkAccess( MID_EXCEPTIONS ); + + if( cachedExceptions == null ) { + if( request == null ) { + throw stdWrapper.piOperationNotSupported2() ; + } + + // Get the list of exceptions from DII request data, If there are + // no exceptions raised then this method will return null. + ExceptionList excList = request.exceptions( ); + int count = excList.count(); + TypeCode[] excTCList = new TypeCode[count]; + try { + for( int i = 0; i < count; i++ ) { + excTCList[i] = excList.item( i ); + } + } catch( Exception e ) { + throw wrapper.exceptionInExceptions( e ) ; + } + + cachedExceptions = excTCList; + } + + // Good citizen: In the interest of efficiency, we assume + // interceptors will be "good citizens" in that they will not + // modify the contents of the TypeCode[] array. We also assume + // they will not change the values of the containing TypeCodes. + + return cachedExceptions; + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public String[] contexts (){ + checkAccess( MID_CONTEXTS ); + + if( cachedContexts == null ) { + if( request == null ) { + throw stdWrapper.piOperationNotSupported3() ; + } + + // Get the list of contexts from DII request data, If there are + // no contexts then this method will return null. + ContextList ctxList = request.contexts( ); + int count = ctxList.count(); + String[] ctxListToReturn = new String[count]; + try { + for( int i = 0; i < count; i++ ) { + ctxListToReturn[i] = ctxList.item( i ); + } + } catch( Exception e ) { + throw wrapper.exceptionInContexts( e ) ; + } + + cachedContexts = ctxListToReturn; + } + + // Good citizen: In the interest of efficiency, we assume + // interceptors will be "good citizens" in that they will not + // modify the contents of the String[] array. + + return cachedContexts; + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public String[] operation_context (){ + checkAccess( MID_OPERATION_CONTEXT ); + + if( cachedOperationContext == null ) { + if( request == null ) { + throw stdWrapper.piOperationNotSupported4() ; + } + + // Get the list of contexts from DII request data, If there are + // no contexts then this method will return null. + Context ctx = request.ctx( ); + // The first parameter in get_values is the start_scope which + // if blank makes it as a global scope. + // The second parameter is op_flags which is set to RESTRICT_SCOPE + // As there is only one defined in the spec. + // The Third param is the pattern which is '*' requiring it to + // get all the contexts. + NVList nvList = ctx.get_values( "", CTX_RESTRICT_SCOPE.value,"*" ); + String[] context = new String[(nvList.count() * 2) ]; + if( nvList.count() != 0 ) { + // The String[] array will contain Name and Value for each + // context and hence double the size in the array. + int index = 0; + for( int i = 0; i < nvList.count(); i++ ) { + NamedValue nv; + try { + nv = nvList.item( i ); + } + catch (Exception e ) { + return (String[]) null; + } + context[index] = nv.name(); + index++; + context[index] = nv.value().extract_string(); + index++; + } + } + + cachedOperationContext = context; + } + + // Good citizen: In the interest of efficiency, we assume + // interceptors will be "good citizens" in that they will not + // modify the contents of the String[] array. + + return cachedOperationContext; + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public Any result (){ + checkAccess( MID_RESULT ); + + if( cachedResult == null ) { + if( request == null ) { + throw stdWrapper.piOperationNotSupported5() ; + } + // Get the result from the DII request data. + NamedValue nvResult = request.result( ); + + if( nvResult == null ) { + throw wrapper.piDiiResultIsNull() ; + } + + cachedResult = nvResult.value(); + } + + // Good citizen: In the interest of efficiency, we assume that + // interceptors will not modify the contents of the result Any. + // Otherwise, we would need to create a deep copy of the Any. + + return cachedResult; + } + + /** + * See RequestInfoImpl for javadoc. + */ + public boolean response_expected (){ + // access is currently valid for all states: + //checkAccess( MID_RESPONSE_EXPECTED ); + return ! messageMediator.isOneWay(); + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public Object forward_reference (){ + checkAccess( MID_FORWARD_REFERENCE ); + // Check to make sure we are in LOCATION_FORWARD + // state as per ptc/00-08-06, table 21-1 + // footnote 2. + if( replyStatus != LOCATION_FORWARD.value ) { + throw stdWrapper.invalidPiCall1() ; + } + + // Do not cache this value since if an interceptor raises + // forward request then the next interceptor in the + // list should see the new value. + IOR ior = getLocatedIOR(); + return iorToObject(ior); + } + + @TraceInterceptor + private IOR getLocatedIOR() { + IOR ior; + ContactInfoList contactInfoList = messageMediator.getContactInfo(). + getContactInfoList(); + ior = contactInfoList.getEffectiveTargetIOR(); + return ior; + } + + // Used to be protected. public for IIOPFailoverManagerImpl. + @TraceInterceptor + public void setLocatedIOR(IOR ior) { + ORB orb = messageMediator.getBroker(); + + ContactInfoListIterator iterator = (ContactInfoListIterator) + ((InvocationInfo)orb.getInvocationInfo()) + .getContactInfoListIterator(); + + // REVISIT - this most likely causes reportRedirect to happen twice. + // Once here and once inside the request dispatcher. + iterator.reportRedirect( messageMediator.getContactInfo(), ior); + } + + /** + * See RequestInfoImpl for javadoc. + */ + @TraceInterceptor + public org.omg.IOP.ServiceContext get_request_service_context( int id ) { + checkAccess( MID_GET_REQUEST_SERVICE_CONTEXT ); + + if( cachedRequestServiceContexts == null ) { + cachedRequestServiceContexts = + new HashMap(); + } + + return getServiceContext(cachedRequestServiceContexts, + messageMediator.getRequestServiceContexts(), + id); + } + + /** + * does not contain an etry for that ID, BAD_PARAM with a minor code of + * TBD_BP is raised. + */ + @TraceInterceptor + public org.omg.IOP.ServiceContext get_reply_service_context( int id ) { + checkAccess( MID_GET_REPLY_SERVICE_CONTEXT ); + + if( cachedReplyServiceContexts == null ) { + cachedReplyServiceContexts = + new HashMap(); + } + + // In the event this is called from a oneway, we will have no + // response object. + // + // In the event this is called after a IIOPConnection.purgeCalls, + // we will have a response object, but that object will + // not contain a header (which would hold the service context + // container). See bug 4624102. + // + + // REVISIT: getReplyHeader should not be visible here. + if (messageMediator.getReplyHeader() != null) { + ServiceContexts sctxs = + messageMediator.getReplyServiceContexts(); + if (sctxs != null) { + return getServiceContext(cachedReplyServiceContexts, + sctxs, id); + } + } + // See purge calls test. The waiter is woken up by the + // call to purge calls - but there is no reply containing + // service contexts. + throw stdWrapper.invalidServiceContextId() ; + } + + // + // REVISIT + // Override RequestInfoImpl connection to work in framework. + // + + @Override + public com.sun.corba.ee.spi.legacy.connection.Connection connection() + { + return (com.sun.corba.ee.spi.legacy.connection.Connection) + messageMediator.getConnection(); + } + + + + /* + ********************************************************************** + * Package-scope interfaces + **********************************************************************/ + + protected void setInfo(MessageMediator messageMediator) + { + this.messageMediator = messageMediator; + // REVISIT - so mediator can handle DII in subcontract. + this.messageMediator.setDIIInfo(request); + } + + /** + * Set or reset the retry request flag. + */ + void setRetryRequest( RetryType retryRequest ) { + // 6763340 + this.retryRequest = retryRequest; + } + + /** + * Retrieve the current retry request status. + */ + RetryType getRetryRequest() { + // 6763340 + return this.retryRequest; + } + + /** + * Increases the entry count by 1. + */ + @TraceInterceptor + void incrementEntryCount() { + this.entryCount++; + entryCount( this.entryCount ) ; + } + + @InfoMethod + private void entryCount( int count ) { } + + /** + * Decreases the entry count by 1. + */ + @TraceInterceptor + void decrementEntryCount() { + this.entryCount--; + entryCount( this.entryCount ) ; + } + + /** + * Retrieve the current entry count + */ + @TraceInterceptor + int getEntryCount() { + return this.entryCount; + } + + /** + * Overridden from RequestInfoImpl. Calls the super class, then + * sets the ending point call depending on the reply status. + */ + @TraceInterceptor + @Override + protected void setReplyStatus( short replyStatus ) { + super.setReplyStatus( replyStatus ); + switch( replyStatus ) { + case SUCCESSFUL.value: + endingPointCall = CALL_RECEIVE_REPLY; + break; + case SYSTEM_EXCEPTION.value: + case USER_EXCEPTION.value: + endingPointCall = CALL_RECEIVE_EXCEPTION; + break; + case LOCATION_FORWARD.value: + case TRANSPORT_RETRY.value: + endingPointCall = CALL_RECEIVE_OTHER; + break; + } + } + + @TraceInterceptor + @Override + protected short getReplyStatus() { + return super.getReplyStatus() ; + } + + /** + * Sets DII request object in the RequestInfoObject. + */ + protected void setDIIRequest(org.omg.CORBA.Request req) { + request = req; + } + + /** + * Keeps track of whether initiate was called for a DII request. The ORB + * needs to know this so it knows whether to ignore a second call to + * initiateClientPIRequest or not. + */ + protected void setDIIInitiate( boolean diiInitiate ) { + this.diiInitiate = diiInitiate; + } + + /** + * See comment for setDIIInitiate + */ + protected boolean isDIIInitiate() { + return this.diiInitiate; + } + + /** + * The PICurrent stack should only be popped if it was pushed. + * This is generally the case. But exceptions which occur + * after the stub's entry to _request but before the push + * end up in _releaseReply which will try to pop unless told not to. + */ + protected void setPICurrentPushed( boolean piCurrentPushed ) { + this.piCurrentPushed = piCurrentPushed; + } + + protected boolean isPICurrentPushed() { + return this.piCurrentPushed; + } + + /** + * Overridden from RequestInfoImpl. + */ + @Override + protected void setException( Exception exception ) { + super.setException( exception ); + + // Clear cached values: + cachedReceivedException = null; + cachedReceivedExceptionId = null; + } + + protected boolean getIsOneWay() { + return ! response_expected(); + } + + /** + * See description for RequestInfoImpl.checkAccess + */ + protected void checkAccess( int methodID ) + throws BAD_INV_ORDER + { + // Make sure currentPoint matches the appropriate index in the + // validCall table: + int validCallIndex = 0; + switch( currentExecutionPoint ) { + case EXECUTION_POINT_STARTING: + switch( startingPointCall ) { + case CALL_SEND_REQUEST: + validCallIndex = 0; + break; + case CALL_SEND_POLL: + validCallIndex = 1; + break; + } + break; + case EXECUTION_POINT_ENDING: + switch( endingPointCall ) { + case CALL_RECEIVE_REPLY: + validCallIndex = 2; + break; + case CALL_RECEIVE_EXCEPTION: + validCallIndex = 3; + break; + case CALL_RECEIVE_OTHER: + validCallIndex = 4; + break; + } + break; + } + + // Check the validCall table: + if( !validCall[methodID][validCallIndex] ) { + throw stdWrapper.invalidPiCall2() ; + } + } + +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/CodecFactoryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/CodecFactoryImpl.java new file mode 100644 index 000000000..e3b98952d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/CodecFactoryImpl.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.CodecFactoryPackage.UnknownEncoding; +import org.omg.IOP.Encoding; +import org.omg.IOP.ENCODING_CDR_ENCAPS; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import org.omg.CORBA.ORB; + +/** + * CodecFactoryImpl is the implementation of the Codec Factory, as described + * in orbos/99-12-02. + */ +public final class CodecFactoryImpl + extends org.omg.CORBA.LocalObject + implements CodecFactory +{ + // The ORB that created this Codec Factory + private transient ORB orb; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // The maximum minor version of GIOP supported by this codec factory. + // Currently, this is 1.2. + private static final int MAX_MINOR_VERSION_SUPPORTED = 2; + + // The pre-created minor versions of Codec version 1.0, 1.1, ..., + // 1.(MAX_MINOR_VERSION_SUPPORTED) + private Codec codecs[] = new Codec[MAX_MINOR_VERSION_SUPPORTED + 1]; + + /** + * Creates a new CodecFactory implementation. Stores the ORB that + * created this factory, for later use by the Codec. + */ + public CodecFactoryImpl( ORB orb ) { + this.orb = orb; + + // Precreate a codec for version 1.0 through + // 1.(MAX_MINOR_VERSION_SUPPORTED). This can be + // done since Codecs are immutable in their current implementation. + // This is an optimization that eliminates the overhead of creating + // a new Codec each time create_codec is called. + for( int minor = 0; minor <= MAX_MINOR_VERSION_SUPPORTED; minor++ ) { + codecs[minor] = new CDREncapsCodec( orb, 1, minor ); + } + } + + /** + * Creates a codec of the given encoding. The only format recognized + * by this factory is ENCODING_CDR_ENCAPS, versions 1.0 through + * 1.(MAX_MINOR_VERSION_SUPPORTED). + * + * @exception UnknownEncoding Thrown if this factory cannot create a + * Codec of the given encoding. + */ + public Codec create_codec ( Encoding enc ) + throws UnknownEncoding + { + if( enc == null ) nullParam(); + + Codec result = null; + + // This is the only format we can currently create codecs for: + if( (enc.format == ENCODING_CDR_ENCAPS.value) && + (enc.major_version == 1) ) + { + if( (enc.minor_version >= 0) && + (enc.minor_version <= MAX_MINOR_VERSION_SUPPORTED) ) + { + result = codecs[enc.minor_version]; + } + } + + if( result == null ) { + throw new UnknownEncoding(); + } + + return result; + } + + /** + * Called when an invalid null parameter was passed. Throws a + * BAD_PARAM with a minor code of 1 + */ + private void nullParam() + { + throw wrapper.nullParamNoComplete() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/IORInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/IORInfoImpl.java new file mode 100644 index 000000000..5491304f6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/IORInfoImpl.java @@ -0,0 +1,289 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import java.util.Iterator ; + +import org.omg.IOP.TaggedComponent; + +import org.omg.CORBA.Policy; +import org.omg.CORBA.LocalObject; + +import org.omg.PortableInterceptor.IORInfo; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; +import org.omg.PortableInterceptor.ObjectReferenceFactory; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; + +import com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt; +import com.sun.corba.ee.spi.legacy.interceptor.UnknownType; + +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.TaggedComponentFactoryFinder ; + +import com.sun.corba.ee.spi.logging.InterceptorsSystemException ; +import com.sun.corba.ee.spi.logging.OMGSystemException ; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * IORInfoImpl is the implementation of the IORInfo class, as described + * in orbos/99-12-02, section 7. + */ +public final class IORInfoImpl + extends LocalObject + implements IORInfo, IORInfoExt +{ + // State values that determine which methods are allowed. + // get_effective_policy, manager_id, and adapter_state are valid unless STATE_DONE + + // add_component, and add_component_to_profile are valid. + private static final int STATE_INITIAL = 0 ; + + // adapter_template, and R/W to current_factory are valid + private static final int STATE_ESTABLISHED = 1 ; + + // No methods are valid in this state + private static final int STATE_DONE = 2 ; + + // The current state of this object + private int state = STATE_INITIAL ; + + // The ObjectAdapter associated with this IORInfo object. + private transient ObjectAdapter adapter; + + private transient ORB orb ; + + private static final ORBUtilSystemException orbutilWrapper = + ORBUtilSystemException.self ; + private static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + /** + * Creates a new IORInfo implementation. This info object will establish + * tagged components with the template for the provided IOR Template. + */ + IORInfoImpl( ObjectAdapter adapter ) { + this.orb = adapter.getORB() ; + this.adapter = adapter; + } + + /** + * An ORB service implementation may determine what server side policy + * of a particular type is in effect for an IOR being constructed by + * calling the get_effective_policy operation. When the IOR being + * constructed is for an object implemented using a POA, all Policy + * objects passed to the PortableServer::POA::create_POA call that + * created that POA are accessible via get_effective_policy. + *

    + * If a policy for the given type is not known to the ORB, then this + * operation will raise INV_POLICY with a standard minor code of 2. + * + * @param type The CORBA::PolicyType specifying the type of policy to + * return. + * @return The effective CORBA::Policy object of the requested type. + * If the given policy type is known, but no policy of that type is + * in effect, then this operation will return a nil object reference. + */ + public Policy get_effective_policy (int type) { + checkState( STATE_INITIAL, STATE_ESTABLISHED ) ; + + return adapter.getEffectivePolicy( type ); + } + + /** + * A portable ORB service implementation calls this method from its + * implementation of establish_components to add a tagged component to + * the set which will be included when constructing IORs. The + * components in this set will be included in all profiles. + *

    + * Any number of components may exist with the same component ID. + * + * @param tagged_component The IOP::TaggedComponent to add + */ + public void add_ior_component (TaggedComponent tagged_component) { + checkState( STATE_INITIAL ) ; + + if( tagged_component == null ) nullParam(); + addIORComponentToProfileInternal( tagged_component, + adapter.getIORTemplate().iterator()); + } + + /** + * A portable ORB service implementation calls this method from its + * implementation of establish_components to add a tagged component to + * the set which will be included when constructing IORs. The + * components in this set will be included in the specified profile. + *

    + * Any number of components may exist with the same component ID. + *

    + * If the given profile ID does not define a known profile or it is + * impossible to add components to thgat profile, BAD_PARAM is raised + * with a minor code of TBD_BP + 3. + * + * @param tagged_component The IOP::TaggedComponent to add. + * @param profile_id The IOP::ProfileId tof the profile to which this + * component will be added. + */ + public void add_ior_component_to_profile ( + TaggedComponent tagged_component, int profile_id ) + { + checkState( STATE_INITIAL ) ; + + if( tagged_component == null ) nullParam(); + addIORComponentToProfileInternal( + tagged_component, adapter.getIORTemplate().iteratorById( + profile_id ) ); + } + + /** + * @param type The type of the server port + * (see connection.ORBSocketFactory for discussion). + * @return The listen port number for that type. + * @throws UnknownType if no port of the given type is found. + */ + public int getServerPort(String type) + throws UnknownType + { + checkState( STATE_INITIAL, STATE_ESTABLISHED ) ; + + int port = + orb.getLegacyServerSocketManager() + .legacyGetTransientOrPersistentServerPort(type); + if (port == -1) { + throw new UnknownType(); + } + return port; + } + + public ObjectAdapter getObjectAdapter() + { + return adapter; + } + + public int manager_id() + { + checkState( STATE_INITIAL, STATE_ESTABLISHED) ; + + return adapter.getManagerId() ; + } + + public short state() + { + checkState( STATE_INITIAL, STATE_ESTABLISHED) ; + + return adapter.getState() ; + } + + public ObjectReferenceTemplate adapter_template() + { + checkState( STATE_ESTABLISHED) ; + + // At this point, the iortemp must contain only a single + // IIOPProfileTemplate. This is a restriction of our + // implementation. Also, note the the ObjectReferenceTemplate + // is called when a certain POA is created in a certain ORB + // in a certain server, so the server_id, orb_id, and + // poa_id operations must be well-defined no matter what + // kind of implementation is used: e.g., if a POA creates + // IORs with multiple profiles, they must still all agree + // about this information. Thus, we are justified in + // extracting the single IIOPProfileTemplate to create + // an ObjectReferenceTemplate here. + + return adapter.getAdapterTemplate() ; + } + + public ObjectReferenceFactory current_factory() + { + checkState( STATE_ESTABLISHED) ; + + return adapter.getCurrentFactory() ; + } + + public void current_factory( ObjectReferenceFactory factory ) + { + checkState( STATE_ESTABLISHED) ; + + adapter.setCurrentFactory( factory ) ; + } + + /** + * Internal utility method to add an IOR component to the set of profiles + * present in the iterator. + */ + private void addIORComponentToProfileInternal( + TaggedComponent tagged_component, Iterator iterator ) + { + // Convert the given IOP::TaggedComponent into the appropriate + // type for the TaggedProfileTemplate + TaggedComponentFactoryFinder finder = + orb.getTaggedComponentFactoryFinder(); + com.sun.corba.ee.spi.ior.TaggedComponent newTaggedComponent = + finder.create( orb, tagged_component ); + + // Iterate through TaggedProfileTemplates and add the given tagged + // component to the appropriate one(s). + boolean found = false; + while( iterator.hasNext() ) { + found = true; + TaggedProfileTemplate taggedProfileTemplate = + (TaggedProfileTemplate)iterator.next(); + taggedProfileTemplate.add( newTaggedComponent ); + } + + // If no profile was found with the given id, throw a BAD_PARAM: + // (See orbos/00-08-06, section 21.5.3.3.) + if( !found ) { + throw omgWrapper.invalidProfileId() ; + } + } + + /** + * Called when an invalid null parameter was passed. Throws a + * BAD_PARAM with a minor code of 1 + */ + private void nullParam() + { + throw orbutilWrapper.nullParamNoComplete() ; + } + + // REVISIT: add minor codes! + + private void checkState( int expectedState ) + { + if (expectedState != state) + throw wrapper.badState1( expectedState, state ) ; + } + + private void checkState( int expectedState1, int expectedState2 ) + { + if ((expectedState1 != state) && (expectedState2 != state)) + throw wrapper.badState2( expectedState1, expectedState2, state ) ; + } + + void makeStateEstablished() + { + checkState( STATE_INITIAL ) ; + + state = STATE_ESTABLISHED ; + } + + void makeStateDone() + { + checkState( STATE_ESTABLISHED ) ; + + state = STATE_DONE ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/InterceptorInvoker.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/InterceptorInvoker.java new file mode 100644 index 000000000..08b2b4182 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/InterceptorInvoker.java @@ -0,0 +1,746 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import org.omg.CORBA.SystemException; +import org.omg.PortableInterceptor.LOCATION_FORWARD; +import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.IORInterceptor; +import org.omg.PortableInterceptor.IORInterceptor_3_0; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.trace.TraceInterceptor; + +import com.sun.corba.ee.spi.logging.InterceptorsSystemException; +import java.util.Arrays; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * Handles invocation of interceptors. Has specific knowledge of how to + * invoke IOR, ClientRequest, and ServerRequest interceptors. + * Makes use of the InterceptorList to retrieve the list of interceptors to + * be invoked. Most methods in this class are package scope so that they + * may only be called from the PIHandlerImpl. + */ +@TraceInterceptor +public class InterceptorInvoker { + private ORB orb; + + private static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + + // The list of interceptors to be invoked + private InterceptorList interceptorList; + + // True if interceptors are to be invoked, or false if not + // Note: This is a global enable/disable flag, whereas the enable flag + // in the RequestInfoStack in PIHandlerImpl is only for a particular Thread. + private boolean enabled = false; + + // PICurrent variable. + private PICurrent current; + + // NOTE: Be careful about adding additional attributes to this class. + // Multiple threads may be calling methods on this invoker at the same + // time. + + /** + * Creates a new Interceptor Invoker. Constructor is package scope so + * only the ORB can create it. The invoker is initially disabled, and + * must be explicitly enabled using setEnabled(). + */ + InterceptorInvoker( ORB orb, InterceptorList interceptorList, + PICurrent piCurrent ) + { + this.orb = orb; + this.interceptorList = interceptorList; + this.enabled = false; + this.current = piCurrent; + } + + /** + * Enables or disables the interceptor invoker + */ + synchronized void setEnabled( boolean enabled ) { + this.enabled = enabled; + } + + synchronized boolean getEnabled() { + return this.enabled ; + } + + /* + ********************************************************************** + * IOR Interceptor invocation + **********************************************************************/ + + /** + * Called when a new POA is created. + * + * @param oa The Object Adapter associated with the IOR interceptor. + */ + @TraceInterceptor + void objectAdapterCreated( ObjectAdapter oa ) { + // If invocation is not yet enabled, don't do anything. + if( getEnabled() ) { + // Create IORInfo object to pass to IORInterceptors: + IORInfoImpl info = new IORInfoImpl( oa ); + + // Call each IORInterceptor: + IORInterceptor[] iorInterceptors = + (IORInterceptor[])interceptorList.getInterceptors( + InterceptorList.INTERCEPTOR_TYPE_IOR ); + int size = iorInterceptors.length; + + // Implementation note: + // This loop counts backwards for greater efficiency. + // Benchmarks have shown that counting down is more efficient + // than counting up in Java for loops, as a compare to zero is + // faster than a subtract and compare to zero. In this case, + // it doesn't really matter much, but it's simply a force of habit. + + for( int i = (size - 1); i >= 0; i-- ) { + IORInterceptor interceptor = iorInterceptors[i]; + try { + interceptor.establish_components( info ); + } catch( Exception e ) { + // as per PI spec (orbos/99-12-02 sec 7.2.1), if + // establish_components throws an exception, ignore it. + // But do log something for debugging. + wrapper.ignoredExceptionInEstablishComponents( e, oa ) ; + } + } + + // Change the state so that only template operations are valid + info.makeStateEstablished() ; + + for( int i = (size - 1); i >= 0; i-- ) { + IORInterceptor interceptor = iorInterceptors[i]; + if (interceptor instanceof IORInterceptor_3_0) { + IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; + // Note that exceptions here are NOT ignored, as per the + // ORT spec (orbos/01-01-04) + try { + interceptor30.components_established( info ); + } catch (Exception exc) { + wrapper.exceptionInComponentsEstablished( exc, oa ) ; + } + } + } + + // Change the state so that no operations are valid, + // in case a reference to info escapes this scope. + // This also completes the actions associated with the + // template interceptors on this POA. + info.makeStateDone() ; + } + } + + @TraceInterceptor + void adapterManagerStateChanged( int managerId, short newState ) { + if (getEnabled()) { + IORInterceptor[] interceptors = + (IORInterceptor[])interceptorList.getInterceptors( + InterceptorList.INTERCEPTOR_TYPE_IOR ); + int size = interceptors.length; + + for( int i = (size - 1); i >= 0; i-- ) { + try { + IORInterceptor interceptor = interceptors[i]; + if (interceptor instanceof IORInterceptor_3_0) { + IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; + interceptor30.adapter_manager_state_changed( managerId, + newState ); + } + } catch (Exception exc) { + // No-op: ignore exception in this case + // But do log something for debugging. + wrapper.ignoredExceptionInAdapterManagerStateChanged( + exc, managerId, newState ) ; + } + } + } + } + + @TraceInterceptor + void adapterStateChanged( ObjectReferenceTemplate[] templates, + short newState ) { + + if (getEnabled()) { + IORInterceptor[] interceptors = + (IORInterceptor[])interceptorList.getInterceptors( + InterceptorList.INTERCEPTOR_TYPE_IOR ); + int size = interceptors.length; + + for( int i = (size - 1); i >= 0; i-- ) { + try { + IORInterceptor interceptor = interceptors[i]; + if (interceptor instanceof IORInterceptor_3_0) { + IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; + interceptor30.adapter_state_changed( templates, newState ); + } + } catch (Exception exc) { + // No-op: ignore exception in this case + // But do log something for debugging. + wrapper.ignoredExceptionInAdapterStateChanged( exc, + Arrays.asList( templates ), newState ) ; + } + } + } + } + + /* + ********************************************************************** + * Client Interceptor invocation + **********************************************************************/ + + @InfoMethod + private void invokeClientStartingCall( String name ) { } + + @InfoMethod + private void invokeClientStartingForwardRequest( String name ) { } + + @InfoMethod + private void invokeClientStartingSystemException( String name, + SystemException exc ) { } + + + /** + * Invokes either send_request, or send_poll, depending on the value + * of info.getStartingPointCall() + */ + @TraceInterceptor + void invokeClientInterceptorStartingPoint( ClientRequestInfoImpl info ) { + info.interceptorsEnabledForThisRequest = getEnabled() ; + + // If invocation is not yet enabled, don't do anything. + if( info.interceptorsEnabledForThisRequest ) { + try { + // Make a a fresh slot table available to TSC in case + // interceptors need to make out calls. + // Client's TSC is now RSC via RequestInfo. + current.pushSlotTable( ); + info.setPICurrentPushed( true ); + info.setCurrentExecutionPoint( + ClientRequestInfoImpl.EXECUTION_POINT_STARTING ); + + // Get all ClientRequestInterceptors: + ClientRequestInterceptor[] clientInterceptors = + (ClientRequestInterceptor[])interceptorList. + getInterceptors( InterceptorList.INTERCEPTOR_TYPE_CLIENT ); + int size = clientInterceptors.length; + + // We will assume that all interceptors returned successfully, + // and adjust the flowStackIndex to the appropriate value if + // we later discover otherwise. + int flowStackIndex = size; + boolean continueProcessing = true; + + // This ORB only supports send_request. It does not implement + // the CORBA messaging specification, so send_poll is not + // needed. + for( int i = 0; continueProcessing && (i < size); i++ ) { + ClientRequestInterceptor cri = clientInterceptors[i] ; + + try { + invokeClientStartingCall( cri.name() ); + cri.send_request( info ); + } catch( ForwardRequest e ) { + invokeClientStartingForwardRequest( cri.name() ); + + // as per PI spec (orbos/99-12-02 sec 5.2.1.), if + // interception point throws a ForwardRequest, + // no other Interceptors' send_request operations are + // called. + flowStackIndex = i; + info.setForwardRequest( e ); + info.setEndingPointCall( + ClientRequestInfoImpl.CALL_RECEIVE_OTHER ); + info.setReplyStatus( LOCATION_FORWARD.value ); + + updateClientRequestDispatcherForward( info ); + + // For some reason, using break here causes the VM on + // NT to lose track of the value of flowStackIndex + // after exiting the for loop. I changed this to + // check a boolean value instead and it seems to work + // fine. + continueProcessing = false; + } catch( SystemException e ) { + invokeClientStartingSystemException( cri.name(), e); + + // as per PI spec (orbos/99-12-02 sec 5.2.1.), if + // interception point throws a SystemException, + // no other Interceptors' send_request operations are + // called. + flowStackIndex = i; + info.setEndingPointCall( + ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION ); + info.setReplyStatus( SYSTEM_EXCEPTION.value ); + info.setException( e ); + + // For some reason, using break here causes the VM on + // NT to lose track of the value of flowStackIndex + // after exiting the for loop. I changed this to + // check a boolean value instead and it seems to + // work fine. + continueProcessing = false; + } + } + + // Remember where we left off in the flow stack: + info.setFlowStackIndex( flowStackIndex ); + } finally { + // Make the SlotTable fresh for the next interception point. + current.resetSlotTable( ); + } + } // end enabled check + } + + private String getClientEndMethodName( int endingPointCall ) { + switch( endingPointCall ) { + case ClientRequestInfoImpl.CALL_RECEIVE_REPLY: + return "receive_reply" ; + case ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION: + return "receive_exception" ; + case ClientRequestInfoImpl.CALL_RECEIVE_OTHER: + return "receive_other" ; + } + return "" ; + } + + @InfoMethod + private void invokeClientEndingCall( String name, String call ) { } + + @InfoMethod + private void invokeClientEndingForwardRequest( String name ) { } + + @InfoMethod + private void invokeClientEndingSystemException( String name, + SystemException exc ) { } + + /** + * Invokes either receive_reply, receive_exception, or receive_other, + * depending on the value of info.getEndingPointCall() + */ + @TraceInterceptor + void invokeClientInterceptorEndingPoint( ClientRequestInfoImpl info ) { + // If invocation is not yet enabled, don't do anything. + if( info.interceptorsEnabledForThisRequest ) { + try { + // NOTE: It is assumed someplace else prepared a + // fresh TSC slot table. + + info.setCurrentExecutionPoint( + ClientRequestInfoImpl.EXECUTION_POINT_ENDING ); + + // Get all ClientRequestInterceptors: + ClientRequestInterceptor[] clientInterceptors = + (ClientRequestInterceptor[])interceptorList. + getInterceptors( InterceptorList.INTERCEPTOR_TYPE_CLIENT ); + int flowStackIndex = info.getFlowStackIndex(); + + // Determine whether we are calling receive_reply, + // receive_exception, or receive_other: + int endingPointCall = info.getEndingPointCall(); + + // If we would be calling RECEIVE_REPLY, but this is a + // one-way call, override this and call receive_other: + if( ( endingPointCall == + ClientRequestInfoImpl.CALL_RECEIVE_REPLY ) && + info.getIsOneWay() ) + { + endingPointCall = ClientRequestInfoImpl.CALL_RECEIVE_OTHER; + info.setEndingPointCall( endingPointCall ); + } + + // Only step through the interceptors whose starting points + // have successfully returned. + // Unlike the previous loop, this one counts backwards for a + // reason - we must execute these in the reverse order of the + // starting points. + for( int i = (flowStackIndex - 1); i >= 0; i-- ) { + ClientRequestInterceptor cri = clientInterceptors[i] ; + + try { + invokeClientEndingCall( cri.name(), + getClientEndMethodName( endingPointCall ) ) ; + + switch( endingPointCall ) { + case ClientRequestInfoImpl.CALL_RECEIVE_REPLY: + cri.receive_reply( info ); + break; + case ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION: + cri.receive_exception( info ); + break; + case ClientRequestInfoImpl.CALL_RECEIVE_OTHER: + cri.receive_other( info ); + break; + } + } catch( ForwardRequest e ) { + invokeClientEndingForwardRequest( cri.name() ); + + // as per PI spec (orbos/99-12-02 sec 5.2.1.), if + // interception point throws a ForwardException, + // ending point call changes to receive_other. + endingPointCall = + ClientRequestInfoImpl.CALL_RECEIVE_OTHER; + info.setEndingPointCall( endingPointCall ); + info.setReplyStatus( LOCATION_FORWARD.value ); + info.setForwardRequest( e ); + updateClientRequestDispatcherForward( info ); + } catch( SystemException e ) { + invokeClientEndingSystemException( cri.name(), e); + + // as per PI spec (orbos/99-12-02 sec 5.2.1.), if + // interception point throws a SystemException, + // ending point call changes to receive_exception. + endingPointCall = + ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION; + info.setEndingPointCall( endingPointCall ); + info.setReplyStatus( SYSTEM_EXCEPTION.value ); + info.setException( e ); + } + } + } finally { + // See doc for setPICurrentPushed as to why this is necessary. + // Check info for null in case errors happen before initiate. + if (info.isPICurrentPushed()) { + current.popSlotTable( ); + // After the pop, original client's TSC slot table + // remains avaiable via PICurrent. + } + } + } // end enabled check + } + + /* + ********************************************************************** + * Server Interceptor invocation + **********************************************************************/ + + @InfoMethod + private void invokeServerStartingCall( String name ) { } + + @InfoMethod + private void invokeServerStartingForwardRequest( String name ) { } + + @InfoMethod + private void invokeServerStartingSystemException( String name, + SystemException exc ) { } + + /** + * Invokes receive_request_service_context interception points. + */ + @TraceInterceptor + void invokeServerInterceptorStartingPoint( ServerRequestInfoImpl info ) { + info.interceptorsEnabledForThisRequest = getEnabled() ; + + // If invocation is not yet enabled, don't do anything. + if( info.interceptorsEnabledForThisRequest ) { + try { + // Make a fresh slot table for RSC. + current.pushSlotTable(); + info.setSlotTable(current.getSlotTable()); + + // Make a fresh slot table for TSC in case + // interceptors need to make out calls. + current.pushSlotTable( ); + + info.setCurrentExecutionPoint( + ServerRequestInfoImpl.EXECUTION_POINT_STARTING ); + + // Get all ServerRequestInterceptors: + ServerRequestInterceptor[] serverInterceptors = + (ServerRequestInterceptor[])interceptorList. + getInterceptors( InterceptorList.INTERCEPTOR_TYPE_SERVER ); + int size = serverInterceptors.length; + + // We will assume that all interceptors returned successfully, + // and adjust the flowStackIndex to the appropriate value if + // we later discover otherwise. + int flowStackIndex = size; + boolean continueProcessing = true; + + // Currently, there is only one server-side starting point + // interceptor called receive_request_service_contexts. + for( int i = 0; continueProcessing && (i < size); i++ ) { + ServerRequestInterceptor sri = serverInterceptors[i] ; + try { + invokeServerStartingCall( sri.name() ); + sri.receive_request_service_contexts( info ); + } catch( ForwardRequest e ) { + invokeServerStartingForwardRequest( sri.name() ); + + // as per PI spec (orbos/99-12-02 sec 5.3.1.), if + // interception point throws a ForwardRequest, + // no other Interceptors' starting points are + // called and send_other is called. + flowStackIndex = i; + info.setForwardRequest( e ); + info.setIntermediatePointCall( + ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ); + info.setEndingPointCall( + ServerRequestInfoImpl.CALL_SEND_OTHER ); + info.setReplyStatus( LOCATION_FORWARD.value ); + + // For some reason, using break here causes the VM on + // NT to lose track of the value of flowStackIndex + // after exiting the for loop. I changed this to + // check a boolean value instead and it seems to work + // fine. + continueProcessing = false; + } catch( SystemException e ) { + invokeServerStartingSystemException( sri.name(), e); + + // as per PI spec (orbos/99-12-02 sec 5.3.1.), if + // interception point throws a SystemException, + // no other Interceptors' starting points are + // called. + flowStackIndex = i; + info.setException( e ); + info.setIntermediatePointCall( + ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ); + info.setEndingPointCall( + ServerRequestInfoImpl.CALL_SEND_EXCEPTION ); + info.setReplyStatus( SYSTEM_EXCEPTION.value ); + + // For some reason, using break here causes the VM on + // NT to lose track of the value of flowStackIndex + // after exiting the for loop. I changed this to + // check a boolean value instead and it seems to + // work fine. + continueProcessing = false; + } + } + + // Remember where we left off in the flow stack: + info.setFlowStackIndex( flowStackIndex ); + } finally { + // The remaining points, ServantManager and Servant + // all run in the same logical thread. + current.popSlotTable( ); + // Now TSC and RSC are equivalent. + } + } // end enabled check + } + + @InfoMethod + private void invokeServerIntermediateCall( String name ) { } + + @InfoMethod + private void invokeServerIntermediateForwardRequest( String name ) { } + + @InfoMethod + private void invokeServerIntermediateSystemException( String name, + SystemException exc ) { } + + /** + * Invokes receive_request interception points + */ + @TraceInterceptor + void invokeServerInterceptorIntermediatePoint( + ServerRequestInfoImpl info ) { + + int intermediatePointCall = info.getIntermediatePointCall(); + // If invocation is not yet enabled, don't do anything. + if( info.interceptorsEnabledForThisRequest && ( intermediatePointCall != + ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ) ) { + + // NOTE: do not touch the slotStack. The RSC and TSC are + // equivalent at this point. + + info.setCurrentExecutionPoint( + ServerRequestInfoImpl.EXECUTION_POINT_INTERMEDIATE ); + + // Get all ServerRequestInterceptors: + ServerRequestInterceptor[] serverInterceptors = + (ServerRequestInterceptor[]) + interceptorList.getInterceptors( + InterceptorList.INTERCEPTOR_TYPE_SERVER ); + int size = serverInterceptors.length; + + // Currently, there is only one server-side intermediate point + // interceptor called receive_request. + for( int i = 0; i < size; i++ ) { + ServerRequestInterceptor sri = serverInterceptors[i] ; + try { + invokeServerIntermediateCall( sri.name() ); + sri.receive_request( info ); + } catch( ForwardRequest e ) { + invokeServerIntermediateForwardRequest( sri.name() ); + + // as per PI spec (orbos/99-12-02 sec 5.3.1.), if + // interception point throws a ForwardRequest, + // no other Interceptors' intermediate points are + // called and send_other is called. + info.setForwardRequest( e ); + info.setEndingPointCall( + ServerRequestInfoImpl.CALL_SEND_OTHER ); + info.setReplyStatus( LOCATION_FORWARD.value ); + break; + } catch( SystemException e ) { + invokeServerIntermediateSystemException( sri.name(), e); + + // as per PI spec (orbos/99-12-02 sec 5.3.1.), if + // interception point throws a SystemException, + // no other Interceptors' starting points are + // called. + info.setException( e ); + info.setEndingPointCall( + ServerRequestInfoImpl.CALL_SEND_EXCEPTION ); + info.setReplyStatus( SYSTEM_EXCEPTION.value ); + break; + } + } + } // end enabled check + } + + private String getServerEndMethodName( int endingPointCall ) { + switch( endingPointCall ) { + case ServerRequestInfoImpl.CALL_SEND_REPLY: + return "send_reply" ; + case ServerRequestInfoImpl.CALL_SEND_EXCEPTION: + return "send_exception" ; + case ServerRequestInfoImpl.CALL_SEND_OTHER: + return "send_other" ; + } + return "" ; + } + + @InfoMethod + private void serverInvokeEndingPoint( String name, String call ) { } + + @InfoMethod + private void caughtForwardRequest( String name ) { } + + @InfoMethod + private void caughtSystemException( String name, SystemException ex ) { } + + /** + * Invokes either send_reply, send_exception, or send_other, + * depending on the value of info.getEndingPointCall() + */ + @TraceInterceptor + void invokeServerInterceptorEndingPoint( ServerRequestInfoImpl info ) { + // If invocation is not yet enabled, don't do anything. + if( info.interceptorsEnabledForThisRequest ) { + try { + // NOTE: do not touch the slotStack. The RSC and TSC are + // equivalent at this point. + + // REVISIT: This is moved out to PIHandlerImpl until dispatch + // path is rearchitected. It must be there so that + // it always gets executed so if an interceptor raises + // an exception any service contexts added in earlier points + // this point get put in the exception reply (via the SC Q). + + // Get all ServerRequestInterceptors: + ServerRequestInterceptor[] serverInterceptors = + (ServerRequestInterceptor[])interceptorList. + getInterceptors( InterceptorList.INTERCEPTOR_TYPE_SERVER ); + int flowStackIndex = info.getFlowStackIndex(); + + // Determine whether we are calling + // send_exception, or send_other: + int endingPointCall = info.getEndingPointCall(); + + // Only step through the interceptors whose starting points + // have successfully returned. + for( int i = (flowStackIndex - 1); i >= 0; i-- ) { + ServerRequestInterceptor sri = serverInterceptors[i] ; + + try { + serverInvokeEndingPoint( sri.name(), + getServerEndMethodName( endingPointCall ) ) ; + + switch( endingPointCall ) { + case ServerRequestInfoImpl.CALL_SEND_REPLY: + sri.send_reply( info ); + break; + case ServerRequestInfoImpl.CALL_SEND_EXCEPTION: + sri.send_exception( info ); + break; + case ServerRequestInfoImpl.CALL_SEND_OTHER: + sri.send_other( info ); + break; + } + } catch( ForwardRequest e ) { + caughtForwardRequest( sri.name() ) ; + + // as per PI spec (orbos/99-12-02 sec 5.3.1.), if + // interception point throws a ForwardException, + // ending point call changes to receive_other. + endingPointCall = + ServerRequestInfoImpl.CALL_SEND_OTHER; + info.setEndingPointCall( endingPointCall ); + info.setForwardRequest( e ); + info.setReplyStatus( LOCATION_FORWARD.value ); + info.setForwardRequestRaisedInEnding(); + } catch( SystemException e ) { + caughtSystemException( sri.name(), e ) ; + + // as per PI spec (orbos/99-12-02 sec 5.3.1.), if + // interception point throws a SystemException, + // ending point call changes to send_exception. + endingPointCall = + ServerRequestInfoImpl.CALL_SEND_EXCEPTION; + info.setEndingPointCall( endingPointCall ); + info.setException( e ); + info.setReplyStatus( SYSTEM_EXCEPTION.value ); + } + } + + // Remember that all interceptors' starting and ending points + // have already been executed so we need not do anything. + info.setAlreadyExecuted( true ); + } finally { + // Get rid of the Server side RSC. + current.popSlotTable(); + } + } // end enabled check + } + + /* + ********************************************************************** + * Private utility methods + **********************************************************************/ + + /** + * Update the client delegate in the event of a ForwardRequest, given the + * information in the passed-in info object. + */ + @TraceInterceptor + private void updateClientRequestDispatcherForward( + ClientRequestInfoImpl info ) { + + ForwardRequest forwardRequest = info.getForwardRequestException(); + + // ForwardRequest may be null if the forwarded IOR is set internal + // to the ClientRequestDispatcher rather than explicitly through Portable + // Interceptors. In this case, we need not update the client + // delegate ForwardRequest object. + if( forwardRequest != null ) { + org.omg.CORBA.Object object = forwardRequest.forward; + + // Convert the forward object into an IOR: + IOR ior = orb.getIOR( object, false ) ; + info.setLocatedIOR( ior ); + } + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/InterceptorList.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/InterceptorList.java new file mode 100644 index 000000000..422f7c692 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/InterceptorList.java @@ -0,0 +1,247 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import org.omg.PortableInterceptor.Interceptor; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.lang.reflect.Array; + +import com.sun.corba.ee.spi.logging.InterceptorsSystemException ; + +/** + * Provides a repository of registered Portable Interceptors, organized + * by type. This list is designed to be accessed as efficiently as + * possible during runtime, with the expense of added complexity during + * initialization and interceptor registration. The class is designed + * to easily allow for the addition of new interceptor types. + */ +public class InterceptorList { + private static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + + // Interceptor type list. If additional interceptors are needed, + // add additional types in numerical order (do not skip numbers), + // and update NUM_INTERCEPTOR_TYPES and classTypes accordingly. + // NUM_INTERCEPTOR_TYPES represents the number of interceptor + // types, so we know how many lists to maintain. + static final int INTERCEPTOR_TYPE_CLIENT = 0; + static final int INTERCEPTOR_TYPE_SERVER = 1; + static final int INTERCEPTOR_TYPE_IOR = 2; + + static final int NUM_INTERCEPTOR_TYPES = 3; + + // Array of class types for interceptors. This is used to create the + // appropriate array type for each interceptor type. These must + // match the indices of the constants declared above. + static final Class[] classTypes = { + org.omg.PortableInterceptor.ClientRequestInterceptor.class, + org.omg.PortableInterceptor.ServerRequestInterceptor.class, + org.omg.PortableInterceptor.IORInterceptor.class + }; + + // True if no further interceptors may be registered with this list. + private boolean locked = false; + + // List of interceptors currently registered. There are + // NUM_INTERCEPTOR_TYPES lists of registered interceptors. + // For example, interceptors[INTERCEPTOR_TYPE_CLIENT] contains an array + // of objects of type ClientRequestInterceptor. + private Interceptor[][] interceptors = + new Interceptor[NUM_INTERCEPTOR_TYPES][]; + + /** + * Creates a new Interceptor List. Constructor is package scope so + * only the ORB can create it. + */ + InterceptorList() { + // Create empty interceptors arrays for each type: + initInterceptorArrays(); + } + + /** + * Registers an interceptor of the given type into the interceptor list. + * The type is one of: + *

      + *
    • INTERCEPTOR_TYPE_CLIENT - ClientRequestInterceptor + *
    • INTERCEPTOR_TYPE_SERVER - ServerRequestInterceptor + *
    • INTERCEPTOR_TYPE_IOR - IORInterceptor + *
    + * + * @exception DuplicateName Thrown if an interceptor of the given + * name already exists for the given type. + */ + void register_interceptor( Interceptor interceptor, int type ) + throws DuplicateName + { + // If locked, deny any further addition of interceptors. + if( locked ) { + throw wrapper.interceptorListLocked() ; + } + + // Cache interceptor name: + String interceptorName = interceptor.name(); + boolean anonymous = interceptorName.equals( "" ); + boolean foundDuplicate = false; + Interceptor[] interceptorList = interceptors[type]; + + // If this is not an anonymous interceptor, + // search for an interceptor of the same name in this category: + if( !anonymous ) { + int size = interceptorList.length; + + // An O(n) search will suffice because register_interceptor is not + // likely to be called often. + for( int i = 0; i < size; i++ ) { + Interceptor in = (Interceptor)interceptorList[i]; + if( in.name().equals( interceptorName ) ) { + foundDuplicate = true; + break; + } + } + } + + if( !foundDuplicate ) { + growInterceptorArray( type ); + interceptors[type][interceptors[type].length-1] = interceptor; + } + else { + throw new DuplicateName( interceptorName ); + } + } + + /** + * Locks this interceptor list so that no more interceptors may be + * registered. This method is called after all interceptors are + * registered for security reasons. + */ + void lock() { + locked = true; + } + + /** + * Retrieves an array of interceptors of the given type. For efficiency, + * the type parameter is assumed to be valid. + */ + Interceptor[] getInterceptors( int type ) { + return interceptors[type]; + } + + /** + * Returns true if there is at least one interceptor of the given type, + * or false if not. + */ + boolean hasInterceptorsOfType( int type ) { + return interceptors[type].length > 0; + } + + /** + * Initializes all interceptors arrays to zero-length arrays of the + * correct type, based on the classTypes list. + */ + private void initInterceptorArrays() { + for( int type = 0; type < NUM_INTERCEPTOR_TYPES; type++ ) { + Class classType = classTypes[type]; + + // Create a zero-length array for each type: + interceptors[type] = + (Interceptor[])Array.newInstance( classType, 0 ); + } + } + + /** + * Grows the given interceptor array by one: + */ + private void growInterceptorArray( int type ) { + Class classType = classTypes[type]; + int currentLength = interceptors[type].length; + Interceptor[] replacementArray; + + // Create new array to replace the old one. The new array will be + // one element larger but have the same type as the old one. + replacementArray = (Interceptor[]) + Array.newInstance( classType, currentLength + 1 ); + System.arraycopy( interceptors[type], 0, + replacementArray, 0, currentLength ); + interceptors[type] = replacementArray; + } + + /** + * Destroys all interceptors in this list by invoking their destroy() + * method. + */ + void destroyAll() { + int numTypes = interceptors.length; + + for( int i = 0; i < numTypes; i++ ) { + int numInterceptors = interceptors[i].length; + for( int j = 0; j < numInterceptors; j++ ) { + interceptors[i][j].destroy(); + } + } + } + + /** + * Sort interceptors. + */ + void sortInterceptors() { + List sorted = null; + List unsorted = null; + + int numTypes = interceptors.length; + + for( int i = 0; i < numTypes; i++ ) { + int numInterceptors = interceptors[i].length; + if (numInterceptors > 0) { + // Get fresh sorting bins for each non empty type. + sorted = new ArrayList(); // not synchronized like we want. + unsorted = new ArrayList(); + } + for( int j = 0; j < numInterceptors; j++ ) { + Interceptor interceptor = interceptors[i][j]; + if (interceptor instanceof Comparable) { + sorted.add(interceptor); + } else { + unsorted.add(interceptor); + } + } + if (numInterceptors > 0 && sorted.size() > 0) { + // Let the RuntimeExceptions thrown by sort + // (i.e., ClassCastException and UnsupportedOperationException) + // flow back to the user. + // Note that this will cause an unchecked conversion warning + // because Interceptor is not Comparable. We rely on dynamic + // typing here: if an Interceptor is in the sorted list, + // it IS comparable by construction. I don't think there + // is any way to capture this in a Java type. + Collections.sort(List.class.cast( sorted )); + Iterator sortedIterator = sorted.iterator(); + Iterator unsortedIterator = unsorted.iterator(); + for( int j = 0; j < numInterceptors; j++ ) { + if (sortedIterator.hasNext()) { + interceptors[i][j] = + sortedIterator.next(); + } else if (unsortedIterator.hasNext()) { + interceptors[i][j] = + unsortedIterator.next(); + } else { + throw wrapper.sortSizeMismatch() ; + } + } + } + } + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ORBInitInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ORBInitInfoImpl.java new file mode 100644 index 000000000..09003723b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ORBInitInfoImpl.java @@ -0,0 +1,342 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.Policy; +import org.omg.CORBA.PolicyError; +import org.omg.IOP.CodecFactory; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.IORInterceptor; +import org.omg.PortableInterceptor.PolicyFactory; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; +import org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.legacy.interceptor.ORBInitInfoExt ; + +import com.sun.corba.ee.spi.logging.InterceptorsSystemException; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; + +/** + * ORBInitInfoImpl is the implementation of the ORBInitInfo class to be + * passed to ORBInitializers, as described in orbos/99-12-02. + */ +public final class ORBInitInfoImpl + extends org.omg.CORBA.LocalObject + implements ORBInitInfo, ORBInitInfoExt +{ + // The ORB we are initializing + private transient ORB orb; + + private static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + private static final ORBUtilSystemException orbutilWrapper = + ORBUtilSystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + // The arguments passed to ORB_init + private String[] args; + + // The ID of the ORB being initialized + private String orbId; + + // The CodecFactory + private CodecFactory codecFactory; + + // The current stage of initialization + private int stage = STAGE_PRE_INIT; + + // The pre-initialization stage (pre_init() being called) + public static final int STAGE_PRE_INIT = 0; + + // The post-initialization stage (post_init() being called) + public static final int STAGE_POST_INIT = 1; + + // Reject all calls - this object should no longer be around. + public static final int STAGE_CLOSED = 2; + + // The description for the OBJECT_NOT_EXIST exception in STAGE_CLOSED + private static final String MESSAGE_ORBINITINFO_INVALID = + "ORBInitInfo object is only valid during ORB_init"; + + /** + * Creates a new ORBInitInfoImpl object (scoped to package) + * + * @param args The arguments passed to ORB_init. + */ + ORBInitInfoImpl( ORB orb, String[] args, + String orbId, CodecFactory codecFactory ) + { + this.orb = orb; + this.args = args; + this.orbId = orbId; + this.codecFactory = codecFactory; + } + + /** Return the ORB behind this ORBInitInfo. This is defined in the + * ORBInitInfoExt interface. + */ + public ORB getORB() + { + return orb ; + } + + /** + * Sets the current stage we are in. This limits access to certain + * functionality. + */ + void setStage( int stage ) { + this.stage = stage; + } + + /** + * Throws an exception if the current stage is STAGE_CLOSED. + * This is called before any method is invoked to ensure that + * no method invocations are attempted after all calls to post_init() + * are completed. + */ + private void checkStage() { + if( stage == STAGE_CLOSED ) { + throw wrapper.orbinitinfoInvalid() ; + } + } + + /* + ******************************************************************* + * The following are implementations of the ORBInitInfo operations. + *******************************************************************/ + + /** + * This attribute contains the arguments passed to ORB_init. They may + * or may not contain the ORB's arguments + */ + public String[] arguments () { + checkStage(); + return args.clone() ; + } + + /** + * This attribute is the ID of the ORB being initialized + */ + public String orb_id () { + checkStage(); + return orbId; + } + + /** + * This attribute is the IOP::CodecFactory. The CodecFactory is normally + * obtained via a call to ORB::resolve_initial_references( "CodecFactory" ) + * but since the ORB is not yet available and Interceptors, particularly + * when processing service contexts, will require a Codec, a means of + * obtaining a Codec is necessary during ORB intialization. + */ + public CodecFactory codec_factory () { + checkStage(); + return codecFactory; + } + + /** + * See orbos/99-12-02, Chapter 11, Dynamic Initial References on page + * 11-81. This operation is identical to ORB::register_initial_reference + * described there. This same functionality exists here because the ORB, + * not yet fully initialized, is not yet available but initial references + * may need to be registered as part of Interceptor registration. + *

    + * This method may not be called during post_init. + */ + public void register_initial_reference( String id, + org.omg.CORBA.Object obj ) + throws InvalidName + { + checkStage(); + if( id == null ) nullParam(); + + // As per CORBA 3.0 section 21.8.1, + // if null is passed as the obj parameter, + // throw BAD_PARAM with minor code OMGSystemException.RIR_WITH_NULL_OBJECT. + // Though the spec is talking about IDL null, we will address both + // Java null and IDL null: + // Note: Local Objects can never be nil! + if( obj == null ) { + throw omgWrapper.rirWithNullObject() ; + } + + // Delegate to ORB. If ORB version throws InvalidName, convert to + // equivalent Portable Interceptors InvalidName. + try { + orb.register_initial_reference( id, obj ); + } catch( org.omg.CORBA.ORBPackage.InvalidName e ) { + InvalidName exc = new InvalidName( e.getMessage() ); + exc.initCause( e ) ; + throw exc ; + } + } + + /** + * This operation is only valid during post_init. It is identical to + * ORB::resolve_initial_references. This same functionality exists here + * because the ORB, not yet fully initialized, is not yet available, + * but initial references may be required from the ORB as part + * of Interceptor registration. + *

    + * (incorporates changes from errata in orbos/00-01-01) + *

    + * This method may not be called during pre_init. + */ + public org.omg.CORBA.Object resolve_initial_references (String id) + throws InvalidName + { + checkStage(); + if( id == null ) nullParam(); + + if( stage == STAGE_PRE_INIT ) { + // Initializer is not allowed to invoke this method during + // this stage. + + // _REVISIT_ Spec issue: What exception should really be + // thrown here? + throw wrapper.rirInvalidPreInit() ; + } + + org.omg.CORBA.Object objRef = null; + + try { + objRef = orb.resolve_initial_references( id ); + } + catch( org.omg.CORBA.ORBPackage.InvalidName e ) { + // Convert PIDL to IDL exception: + throw new InvalidName(); + } + + return objRef; + } + + // New method from CORBA 3.1 + public void add_client_request_interceptor_with_policy ( + ClientRequestInterceptor interceptor, Policy[] policies ) + throws DuplicateName + { + add_client_request_interceptor( interceptor ) ; + } + + /** + * This operation is used to add a client-side request Interceptor to + * the list of client-side request Interceptors. + *

    + * If a client-side request Interceptor has already been registered + * with this Interceptor's name, DuplicateName is raised. + */ + public void add_client_request_interceptor ( + ClientRequestInterceptor interceptor) + throws DuplicateName + { + checkStage(); + if( interceptor == null ) nullParam(); + + orb.getPIHandler().register_interceptor( interceptor, + InterceptorList.INTERCEPTOR_TYPE_CLIENT ); + } + + // New method from CORBA 3.1 + public void add_server_request_interceptor_with_policy ( + ServerRequestInterceptor interceptor, Policy[] policies ) + throws DuplicateName, PolicyError + { + add_server_request_interceptor( interceptor ) ; + } + + /** + * This operation is used to add a server-side request Interceptor to + * the list of server-side request Interceptors. + *

    + * If a server-side request Interceptor has already been registered + * with this Interceptor's name, DuplicateName is raised. + */ + public void add_server_request_interceptor ( + ServerRequestInterceptor interceptor) + throws DuplicateName + { + checkStage(); + if( interceptor == null ) nullParam(); + + orb.getPIHandler().register_interceptor( interceptor, + InterceptorList.INTERCEPTOR_TYPE_SERVER ); + } + + // New method from CORBA 3.1 + public void add_ior_interceptor_with_policy ( + IORInterceptor interceptor, Policy[] policies ) + throws DuplicateName, PolicyError + { + add_ior_interceptor( interceptor ) ; + } + + /** + * This operation is used to add an IOR Interceptor to + * the list of IOR Interceptors. + *

    + * If an IOR Interceptor has already been registered + * with this Interceptor's name, DuplicateName is raised. + */ + public void add_ior_interceptor ( + IORInterceptor interceptor ) + throws DuplicateName + { + checkStage(); + if( interceptor == null ) nullParam(); + + orb.getPIHandler().register_interceptor( interceptor, + InterceptorList.INTERCEPTOR_TYPE_IOR ); + } + + /** + * A service calls allocate_slot_id to allocate a slot on + * PortableInterceptor::Current. + * + * @return The index to the slot which has been allocated. + */ + public int allocate_slot_id () { + checkStage(); + + return ((PICurrent)orb.getPIHandler().getPICurrent()).allocateSlotId( ); + + } + + /** + * Register a PolicyFactory for the given PolicyType. + *

    + * If a PolicyFactory already exists for the given PolicyType, + * BAD_INV_ORDER is raised with a minor code of TBD_BIO+2. + */ + public void register_policy_factory( int type, + PolicyFactory policy_factory ) + { + checkStage(); + if( policy_factory == null ) nullParam(); + orb.getPIHandler().registerPolicyFactory( type, policy_factory ); + } + + + /** + * Called when an invalid null parameter was passed. Throws a + * BAD_PARAM with a minor code of 1 + */ + private void nullParam() + throws BAD_PARAM + { + throw orbutilWrapper.nullParam() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PICurrent.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PICurrent.java new file mode 100644 index 000000000..32ac2ac1e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PICurrent.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.orb.ORB; + +import org.omg.CORBA.Any; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.InvalidSlot; + +/** + * PICurrent is the implementation of Current as specified in the Portable + * Interceptors Spec orbos/99-12-02. + * IMPORTANT: PICurrent is implemented with the assumption that get_slot() + * or set_slot() will not be called in ORBInitializer.pre_init() and + * post_init(). + */ +public class PICurrent extends org.omg.CORBA.LocalObject + implements Current +{ + private static final OMGSystemException wrapper = + OMGSystemException.self ; + + // slotCounter is used to keep track of ORBInitInfo.allocate_slot_id() + private int slotCounter; + + // The ORB associated with this PICurrent object. + private transient ORB myORB; + + // True if the orb is still initialzing and get_slot and set_slot are not + // to be called. + private boolean orbInitializing; + + // ThreadLocal contains a stack of SlotTable which are used + // for resolve_initial_references( "PICurrent" ); + private transient ThreadLocal threadLocalSlotTable + = new ThreadLocal() { + @Override + protected SlotTableStack initialValue( ) { + return new SlotTableStack( myORB, PICurrent.this ); + } + }; + + /** + * PICurrent constructor which will be called for every ORB + * initialization. + */ + PICurrent( ORB myORB ) { + this.myORB = myORB; + this.orbInitializing = true; + slotCounter = 0; + } + + @Override + public org.omg.CORBA.ORB _orb() { + return myORB; + } + + synchronized int getTableSize() { + return slotCounter ; + } + + /** + * This method will be called from ORBInitInfo.allocate_slot_id( ). + * simply returns a slot id by incrementing slotCounter. + */ + synchronized int allocateSlotId( ) { + int slotId = slotCounter; + slotCounter = slotCounter + 1; + return slotId; + } + + /** + * This method gets the SlotTable which is on the top of the + * ThreadLocalStack. + */ + SlotTable getSlotTable( ) { + SlotTable table = threadLocalSlotTable.get().peekSlotTable(); + return table; + } + + /** + * This method pushes a SlotTable on the SlotTableStack. When there is + * a resolve_initial_references("PICurrent") after this call. The new + * PICurrent will be returned. + */ + void pushSlotTable( ) { + SlotTableStack st = threadLocalSlotTable.get(); + st.pushSlotTable( ); + } + + + /** + * This method pops a SlotTable on the SlotTableStack. + */ + void popSlotTable( ) { + SlotTableStack st = threadLocalSlotTable.get(); + st.popSlotTable( ); + } + + /** + * This method sets the slot data at the given slot id (index) in the + * Slot Table which is on the top of the SlotTableStack. + */ + public void set_slot( int id, Any data ) throws InvalidSlot + { + if( orbInitializing ) { + // As per ptc/00-08-06 if the ORB is still initializing, disallow + // calls to get_slot and set_slot. If an attempt is made to call, + // throw a BAD_INV_ORDER. + throw wrapper.invalidPiCall3() ; + } + + getSlotTable().set_slot( id, data ); + } + + /** + * This method gets the slot data at the given slot id (index) from the + * Slot Table which is on the top of the SlotTableStack. + */ + public Any get_slot( int id ) throws InvalidSlot + { + if( orbInitializing ) { + // As per ptc/00-08-06 if the ORB is still initializing, disallow + // calls to get_slot and set_slot. If an attempt is made to call, + // throw a BAD_INV_ORDER. + throw wrapper.invalidPiCall4() ; + } + + return getSlotTable().get_slot( id ); + } + + /** + * This method resets all the slot data to null in the + * Slot Table which is on the top of SlotTableStack. + */ + void resetSlotTable( ) { + getSlotTable().resetSlots(); + } + + /** + * Called from ORB when the ORBInitializers are about to start + * initializing. + */ + void setORBInitializing( boolean init ) { + this.orbInitializing = init; + } +} + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PIHandlerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PIHandlerImpl.java new file mode 100644 index 000000000..9ae630446 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PIHandlerImpl.java @@ -0,0 +1,1017 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import java.util.*; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.BAD_POLICY; +import org.omg.CORBA.NVList; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.UserException; + +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.RemarshalException; + +import org.omg.IOP.CodecFactory; + +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.Interceptor; +import org.omg.PortableInterceptor.LOCATION_FORWARD; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; +import org.omg.PortableInterceptor.SUCCESSFUL; +import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; +import org.omg.PortableInterceptor.TRANSPORT_RETRY; +import org.omg.PortableInterceptor.USER_EXCEPTION; +import org.omg.PortableInterceptor.PolicyFactory; +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.ForwardException; +import com.sun.corba.ee.spi.protocol.PIHandler; +import com.sun.corba.ee.spi.protocol.RetryType ; + +import com.sun.corba.ee.spi.logging.InterceptorsSystemException; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.impl.corba.RequestImpl; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; +import com.sun.corba.ee.spi.trace.TraceInterceptor; +import org.glassfish.pfl.basic.func.NullaryFunction; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * Provides portable interceptor functionality. + */ +@TraceInterceptor +public class PIHandlerImpl implements PIHandler +{ + private ORB orb ; + + static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + static final ORBUtilSystemException orbutilWrapper = + ORBUtilSystemException.self ; + static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + // A unique id used in ServerRequestInfo. + // This does not correspond to the GIOP request id. + private int serverRequestIdCounter = 0; + + // Stores the codec factory for producing codecs + CodecFactory codecFactory = null; + + // The arguments passed to the application's main method. May be null. + // This is used for ORBInitializers and set from set_parameters. + String[] arguments = null; + + // The list of portable interceptors, organized by type: + private InterceptorList interceptorList; + + // Cached information for optimization - do we have any interceptors + // registered of the given types? Set during ORB initialization. + private boolean hasIORInterceptors; + private boolean hasClientInterceptors; // temp always true + private boolean hasServerInterceptors; + + // The class responsible for invoking interceptors + private InterceptorInvoker interceptorInvoker; + + // There will be one PICurrent instantiated for every ORB. + private PICurrent current; + + // This table contains a list of PolicyFactories registered using + // ORBInitInfo.registerPolicyFactory() method. + // Key for the table is PolicyType which is an Integer + // Value is PolicyFactory. + private Map policyFactoryTable; + + // Table to convert from a ReplyMessage.? to a PI replyStatus short. + // Note that this table relies on the order and constants of + // ReplyMessage not to change. + private final static short REPLY_MESSAGE_TO_PI_REPLY_STATUS[] = { + SUCCESSFUL.value, // = ReplyMessage.NO_EXCEPTION + USER_EXCEPTION.value, // = ReplyMessage.USER_EXCEPTION + SYSTEM_EXCEPTION.value, // = ReplyMessage.SYSTEM_EXCEPTION + LOCATION_FORWARD.value, // = ReplyMessage.LOCATION_FORWARD + LOCATION_FORWARD.value, // = ReplyMessage.LOCATION_FORWARD_PERM + TRANSPORT_RETRY.value // = ReplyMessage.NEEDS_ADDRESSING_MODE + }; + + static String getReplyStatus( int piReplyStatus ) { + switch (piReplyStatus) { + case SUCCESSFUL.value: return "SUCCESSFUL" ; + case USER_EXCEPTION.value: return "USER_EXCEPTION" ; + case SYSTEM_EXCEPTION.value: return "SYSTEM_EXCEPTION" ; + case LOCATION_FORWARD.value: return "LOCATION_FORWARD" ; + case TRANSPORT_RETRY.value: return "TRANSPORT_RETRY" ; + default: return "UNINITIALIZED" ; + } + } + + // ThreadLocal containing a stack to store client request info objects + // and a disable count. + private ThreadLocal> + threadLocalClientRequestInfoStack = + new ThreadLocal>() { + @Override + protected RequestInfoStack initialValue() { + return new RequestInfoStack(); + } + }; + + // ThreadLocal containing the current server request info object. + private ThreadLocal> + threadLocalServerRequestInfoStack = + new ThreadLocal>() { + @Override + protected RequestInfoStack initialValue() { + return new RequestInfoStack(); + } + }; + + @TraceInterceptor + public void close() { + orb = null ; + codecFactory = null ; + arguments = null ; + interceptorList = null ; + interceptorInvoker = null ; + current = null ; + policyFactoryTable = null ; + threadLocalClientRequestInfoStack = null ; + threadLocalServerRequestInfoStack = null ; + } + // Class to contain all ThreadLocal data for ClientRequestInfo + // maintenance. + // + // RequestInfoStack is used quite frequently. + private static final class RequestInfoStack extends Stack { + // Number of times a request has been made to disable interceptors. + // When this reaches 0, interception hooks are disabled. Any higher + // value indicates they are enabled. + // NOTE: The is only currently used on the client side. + public int disableCount = 0; + + // Get FindBugs to shut up about not overridding equals. + @Override + public boolean equals( Object o ) { + return super.equals( o ) ; + } + + @Override + public int hashCode() { + return super.hashCode() ; + } + } + + public PIHandlerImpl( ORB orb, String[] args ) { + this.orb = orb ; + + if (args == null) { + arguments = null ; + } else { + arguments = args.clone() ; + } + + // Create codec factory: + codecFactory = new CodecFactoryImpl( orb ); + + // Create new interceptor list: + interceptorList = new InterceptorList(); + + // Create a new PICurrent. + current = new PICurrent( orb ); + + // Create new interceptor invoker, initially disabled: + interceptorInvoker = new InterceptorInvoker( orb, interceptorList, + current ); + + // Register the PI current and Codec factory objects + orb.getLocalResolver().register( ORBConstants.PI_CURRENT_NAME, + NullaryFunction.Factory.makeConstant( + (org.omg.CORBA.Object)current ) ) ; + orb.getLocalResolver().register( ORBConstants.CODEC_FACTORY_NAME, + NullaryFunction.Factory.makeConstant( + (org.omg.CORBA.Object)codecFactory ) ) ; + hasClientInterceptors = true ; // Issue 11033: with the other changes, + // make sure this is true in case + // initialize gets called between + // initiateClientPIRequest and + // cleanupClientPIRequest. + hasServerInterceptors = true ; // same as hasClientInterceptors. + } + + @TraceInterceptor + public void initialize() { + // If we have any orb initializers, make use of them: + if( orb.getORBData().getORBInitializers() != null ) { + // Create the ORBInitInfo object to pass to ORB intializers: + ORBInitInfoImpl orbInitInfo = createORBInitInfo(); + + // Make sure get_slot and set_slot are not called from within + // ORB initializers: + current.setORBInitializing( true ); + + // Call pre_init on all ORB initializers: + preInitORBInitializers( orbInitInfo ); + + // Call post_init on all ORB initializers: + postInitORBInitializers( orbInitInfo ); + + // Proprietary: sort interceptors: + interceptorList.sortInterceptors(); + + // Re-enable get_slot and set_slot to be called from within + // ORB initializers: + current.setORBInitializing( false ); + + // Ensure nobody makes any more calls on this object. + orbInitInfo.setStage( ORBInitInfoImpl.STAGE_CLOSED ); + + // Set cached flags indicating whether we have interceptors + // registered of a given type. + hasIORInterceptors = interceptorList.hasInterceptorsOfType( + InterceptorList.INTERCEPTOR_TYPE_IOR ); + // This must always be true, so that using the new generic + // RPC framework can pass info between the PI stack and the + // framework invocation stack. Temporary until Harold fixes + // this. Note that this must never be true until after the + // ORBInitializer instances complete executing. + // (KMC 11/17/09 (probably 5 years later): temporary is a long time! + //hasClientInterceptors = interceptorList.hasInterceptorsOfType( + //InterceptorList.INTERCEPTOR_TYPE_CLIENT ); + // hasClientInterceptors = true; + // hasServerInterceptors = interceptorList.hasInterceptorsOfType( + // InterceptorList.INTERCEPTOR_TYPE_SERVER ); + + // Enable interceptor invoker (not necessary if no interceptors + // are registered). This should be the last stage of ORB + // initialization. + interceptorInvoker.setEnabled( true ); + } + } + + /** + * ptc/00-08-06 p 205: "When an application calls ORB::destroy, the ORB + * 1) waits for all requests in progress to complete + * 2) calls the Interceptor::destroy operation for each interceptor + * 3) completes destruction of the ORB" + * + * This must be called at the end of ORB.destroy. Note that this is not + * part of the PIHandler interface, since ORBImpl implements the ORB interface. + */ + @TraceInterceptor + public void destroyInterceptors() { + interceptorList.destroyAll(); + } + + @TraceInterceptor + public void objectAdapterCreated( ObjectAdapter oa ) { + if (!hasIORInterceptors) + return ; + + interceptorInvoker.objectAdapterCreated( oa ) ; + } + + @TraceInterceptor + public void adapterManagerStateChanged( int managerId, + short newState ) { + + if (!hasIORInterceptors) + return ; + + interceptorInvoker.adapterManagerStateChanged( managerId, newState ) ; + } + + @TraceInterceptor + public void adapterStateChanged( ObjectReferenceTemplate[] + templates, short newState ) { + + if (!hasIORInterceptors) + return ; + + interceptorInvoker.adapterStateChanged( templates, newState ) ; + } + + /* + ***************** + * Client PI hooks + *****************/ + + @TraceInterceptor + public void disableInterceptorsThisThread() { + if( !hasClientInterceptors ) return; + + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + infoStack.disableCount++; + } + + @TraceInterceptor + public void enableInterceptorsThisThread() { + if( !hasClientInterceptors ) + return; + + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + infoStack.disableCount--; + } + + @TraceInterceptor + public void invokeClientPIStartingPoint() + throws RemarshalException { + + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + // Invoke the starting interception points and record exception + // and reply status info in the info object: + ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); + interceptorInvoker.invokeClientInterceptorStartingPoint( info ); + + // Check reply status. If we will not have another chance later + // to invoke the client ending points, do it now. + short replyStatus = info.getReplyStatus(); + if( (replyStatus == SYSTEM_EXCEPTION.value) || + (replyStatus == LOCATION_FORWARD.value) ) { + // Note: Transport retry cannot happen here since this happens + // before the request hits the wire. + + Exception exception = invokeClientPIEndingPoint( + convertPIReplyStatusToReplyMessage( replyStatus ), + info.getException() ); + if( exception == null ) { + // Do not throw anything. Otherwise, it must be a + // SystemException, UserException or RemarshalException. + } if( exception instanceof SystemException ) { + throw (SystemException)exception; + } else if( exception instanceof RemarshalException ) { + throw (RemarshalException)exception; + } else if( (exception instanceof UserException) || + (exception instanceof ApplicationException) ) { + // It should not be possible for an interceptor to throw + // a UserException. By asserting instead of throwing the + // UserException, we need not declare anything but + // RemarshalException in the throws clause. + throw wrapper.exceptionInvalid() ; + } + } else if( replyStatus != ClientRequestInfoImpl.UNINITIALIZED ) { + throw wrapper.replyStatusNotInit() ; + } + } + + // Needed when an error forces a retry AFTER initiateClientPIRequest + // but BEFORE invokeClientPIStartingPoint. + public Exception makeCompletedClientRequest( int replyStatus, + Exception exception ) { + + // 6763340 + return handleClientPIEndingPoint( replyStatus, exception, false ) ; + } + + public Exception invokeClientPIEndingPoint( int replyStatus, + Exception exception ) { + + // 6763340 + return handleClientPIEndingPoint( replyStatus, exception, true ) ; + } + + @TraceInterceptor + public Exception handleClientPIEndingPoint( + int replyStatus, Exception exception, boolean invokeEndingPoint ) { + if( !hasClientInterceptors ) return exception; + if( !isClientPIEnabledForThisThread() ) return exception; + + // Translate ReplyMessage.replyStatus into PI replyStatus: + // Note: this is also an assertion to make sure a valid replyStatus + // is passed in (IndexOutOfBoundsException will be thrown otherwise) + short piReplyStatus = REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; + + // Invoke the ending interception points and record exception + // and reply status info in the info object: + ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); + info.setReplyStatus( piReplyStatus ); + info.setException( exception ); + + if (invokeEndingPoint) { + // 6763340 + interceptorInvoker.invokeClientInterceptorEndingPoint( info ); + piReplyStatus = info.getReplyStatus(); + } + + // Check reply status: + if( (piReplyStatus == LOCATION_FORWARD.value) || + (piReplyStatus == TRANSPORT_RETRY.value) ) { + // If this is a forward or a retry, reset and reuse + // info object: + info.reset(); + + // fix for 6763340: + if (invokeEndingPoint) { + info.setRetryRequest( RetryType.AFTER_RESPONSE ) ; + } else { + info.setRetryRequest( RetryType.BEFORE_RESPONSE ) ; + } + + // ... and return a RemarshalException so the orb internals know + exception = new RemarshalException(); + } else if( (piReplyStatus == SYSTEM_EXCEPTION.value) || + (piReplyStatus == USER_EXCEPTION.value) ) { + + exception = info.getException(); + } + + return exception; + } + + @InfoMethod + private void secondCallForADIIRequest() { } + + @InfoMethod + private void normalCall() { } + + @InfoMethod + private void clientInfoStackWasPushed() { } + + @TraceInterceptor + public void initiateClientPIRequest( boolean diiRequest ) { + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + // Get the most recent info object from the thread local + // ClientRequestInfoImpl stack: + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + ClientRequestInfoImpl info = null; + + if (!infoStack.empty() ) { + info = infoStack.peek(); + } + + if (!diiRequest && (info != null) && info.isDIIInitiate() ) { + // In RequestImpl.doInvocation we already called + // initiateClientPIRequest( true ), so ignore this initiate. + secondCallForADIIRequest(); + info.setDIIInitiate( false ); + } else { + // If there is no info object or if we are not retrying a request, + // push a new ClientRequestInfoImpl on the stack: + normalCall(); + + // 6763340: don't push unless this is not a retry + if( (info == null) || !info.getRetryRequest().isRetry() ) { + info = new ClientRequestInfoImpl( orb ); + infoStack.push( info ); + clientInfoStackWasPushed(); + // Note: the entry count is automatically initialized to 0. + } + + // Reset the retry request flag so that recursive calls will + // push a new info object, and bump up entry count so we know + // when to pop this info object: + info.setRetryRequest( RetryType.NONE ); + info.incrementEntryCount(); + + // KMC 6763340: I don't know why this wasn't set earlier, + // but we do not want a retry to pick up the previous + // reply status, so clear it here. Most likely a new + // info was pushed before, so that this was not a problem. + info.setReplyStatus( RequestInfoImpl.UNINITIALIZED ) ; + + // If this is a DII request, make sure we ignore the next initiate. + if( diiRequest ) { + info.setDIIInitiate( true ); + } + } + } + + @InfoMethod + private void clientInfoStackWasPopped() { } + + @TraceInterceptor + public void cleanupClientPIRequest() { + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); + RetryType rt = info.getRetryRequest() ; + + // fix for 6763340 + if (!rt.equals( RetryType.BEFORE_RESPONSE )) { + // If the replyStatus has not yet been set, this is an indication + // that the ORB threw an exception before we had a chance to + // invoke the client interceptor ending points. + // + // _REVISIT_ We cannot handle any exceptions or ForwardRequests + // flagged by the ending points here because there is no way + // to gracefully handle this in any of the calling code. + // This is a rare corner case, so we will ignore this for now. + short replyStatus = info.getReplyStatus(); + if (replyStatus == ClientRequestInfoImpl.UNINITIALIZED ) { + invokeClientPIEndingPoint( ReplyMessage.SYSTEM_EXCEPTION, + wrapper.unknownRequestInvoke() ) ; + } + } + + // Decrement entry count, and if it is zero, pop it from the stack. + info.decrementEntryCount(); + + // fix for 6763340, and probably other cases (non-recursive retry) + if (info.getEntryCount() == 0 && !info.getRetryRequest().isRetry()) { + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + infoStack.pop(); + clientInfoStackWasPopped(); + } + } + + @TraceInterceptor + public void setClientPIInfo(MessageMediator messageMediator) + { + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + peekClientRequestInfoImplStack().setInfo(messageMediator); + } + + @TraceInterceptor + public void setClientPIInfo( RequestImpl requestImpl ) { + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + peekClientRequestInfoImplStack().setDIIRequest( requestImpl ); + } + + /* + ***************** + * Server PI hooks + *****************/ + + @TraceInterceptor + public void invokeServerPIStartingPoint() { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + interceptorInvoker.invokeServerInterceptorStartingPoint( info ); + + // Handle SystemException or ForwardRequest: + serverPIHandleExceptions( info ); + } + + @TraceInterceptor + public void invokeServerPIIntermediatePoint() { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + interceptorInvoker.invokeServerInterceptorIntermediatePoint( info ); + + // Clear servant from info object so that the user has control over + // its lifetime: + info.releaseServant(); + + // Handle SystemException or ForwardRequest: + serverPIHandleExceptions( info ); + } + + @TraceInterceptor + public void invokeServerPIEndingPoint( ReplyMessage replyMessage ) { + if( !hasServerInterceptors ) return; + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + + // REVISIT: This needs to be done "early" for the following workaround. + info.setReplyMessage( replyMessage ); + + // REVISIT: This was done inside of invokeServerInterceptorEndingPoint + // but needs to be here for now. See comment in that method for why. + info.setCurrentExecutionPoint( + ServerRequestInfoImpl.EXECUTION_POINT_ENDING ); + + // It is possible we might have entered this method more than + // once (e.g. if an ending point threw a SystemException, then + // a new ServerResponseImpl is created). + if( !info.getAlreadyExecuted() ) { + int replyStatus = replyMessage.getReplyStatus(); + + // Translate ReplyMessage.replyStatus into PI replyStatus: + // Note: this is also an assertion to make sure a valid + // replyStatus is passed in (IndexOutOfBoundsException will be + // thrown otherwise) + short piReplyStatus = + REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; + + // Make forwarded IOR available to interceptors, if applicable: + if( ( piReplyStatus == LOCATION_FORWARD.value ) || + ( piReplyStatus == TRANSPORT_RETRY.value ) ) + { + info.setForwardRequest( replyMessage.getIOR() ); + } + + // REVISIT: Do early above for now. + // Make reply message available to interceptors: + //info.setReplyMessage( replyMessage ); + + // Remember exception so we can tell if an interceptor changed it. + Exception prevException = info.getException(); + + // _REVISIT_ We do not have access to the User Exception at + // this point, so treat it as an UNKNOWN for now. + // Note that if this is a DSI call, we do have the user exception. + if( !info.isDynamic() && + (piReplyStatus == USER_EXCEPTION.value) ) + { + info.setException( omgWrapper.unknownUserException() ) ; + } + + // Invoke the ending interception points: + info.setReplyStatus( piReplyStatus ); + interceptorInvoker.invokeServerInterceptorEndingPoint( info ); + short newPIReplyStatus = info.getReplyStatus(); + Exception newException = info.getException(); + + // Check reply status. If an interceptor threw a SystemException + // and it is different than the one that we came in with, + // rethrow it so the proper response can be constructed: + if( ( newPIReplyStatus == SYSTEM_EXCEPTION.value ) && + ( newException != prevException ) ) + { + throw (SystemException)newException; + } + + // If we are to forward the location: + if( newPIReplyStatus == LOCATION_FORWARD.value ) { + if( piReplyStatus != LOCATION_FORWARD.value ) { + // Treat a ForwardRequest as a ForwardException. + IOR ior = info.getForwardRequestIOR(); + throw new ForwardException( orb, ior ) ; + } + else if( info.isForwardRequestRaisedInEnding() ) { + // Treat a ForwardRequest by changing the IOR. + replyMessage.setIOR( info.getForwardRequestIOR() ); + } + } + } + } + + @TraceInterceptor + public void setServerPIInfo( Exception exception ) { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + info.setException( exception ); + } + + @TraceInterceptor + public void setServerPIInfo( NVList arguments ) { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + info.setDSIArguments( arguments ); + } + + @TraceInterceptor + public void setServerPIExceptionInfo( Any exception ) { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + info.setDSIException( exception ); + } + + @TraceInterceptor + public void setServerPIInfo( Any result ) { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + info.setDSIResult( result ); + } + + @InfoMethod + private void serverInfoStackWasPushed() { } + + @InfoMethod + private void serverInfoStackWasPopped() { } + + @TraceInterceptor + public void initializeServerPIInfo( MessageMediator request, + ObjectAdapter oa, byte[] objectId, ObjectKeyTemplate oktemp ) { + + if( !hasServerInterceptors ) return; + + RequestInfoStack infoStack = + threadLocalServerRequestInfoStack.get(); + ServerRequestInfoImpl info = new ServerRequestInfoImpl( orb ); + infoStack.push( info ); + serverInfoStackWasPushed(); + + // Notify request object that once response is constructed, make + // sure we execute ending points. + request.setExecutePIInResponseConstructor( true ); + + info.setInfo( request, oa, objectId, oktemp ); + } + + @TraceInterceptor + public void setServerPIInfo( java.lang.Object servant, + String targetMostDerivedInterface ) { + if( !hasServerInterceptors ) return; + + ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + info.setInfo( servant, targetMostDerivedInterface ); + } + + @TraceInterceptor + public void cleanupServerPIRequest() { + if( !hasServerInterceptors ) return; + + RequestInfoStack infoStack = + threadLocalServerRequestInfoStack.get(); + infoStack.pop(); + + serverInfoStackWasPopped(); + } + + /* + ********************************************************************** + * The following methods are private utility methods. + ************************************************************************/ + + /** + * Handles exceptions for the starting and intermediate points for + * server request interceptors. This is common code that has been + * factored out into this utility method. + *

    + * This method will NOT work for ending points. + */ + @TraceInterceptor + private void serverPIHandleExceptions( ServerRequestInfoImpl info ) { + int endingPointCall = info.getEndingPointCall(); + if(endingPointCall == ServerRequestInfoImpl.CALL_SEND_EXCEPTION) { + // If a system exception was thrown, throw it to caller: + throw (SystemException)info.getException(); + } + else if( (endingPointCall == ServerRequestInfoImpl.CALL_SEND_OTHER) && + (info.getForwardRequestException() != null) ) + { + // If an interceptor throws a forward request, convert it + // into a ForwardException for easier handling: + IOR ior = info.getForwardRequestIOR(); + throw new ForwardException( orb, ior ); + } + } + + /** + * Utility method to convert a PI reply status short to a ReplyMessage + * constant. This is a reverse lookup on the table defined in + * REPLY_MESSAGE_TO_PI_REPLY_STATUS. The reverse lookup need not be + * performed as quickly since it is only executed in exception + * conditions. + */ + @TraceInterceptor + private int convertPIReplyStatusToReplyMessage( short replyStatus ) { + int result = 0; + for( int i = 0; i < REPLY_MESSAGE_TO_PI_REPLY_STATUS.length; i++ ) { + if( REPLY_MESSAGE_TO_PI_REPLY_STATUS[i] == replyStatus ) { + result = i; + break; + } + } + return result; + } + + /** + * Convenience method to get the ClientRequestInfoImpl object off the + * top of the ThreadLocal stack. Throws an INTERNAL exception if + * the Info stack is empty. + */ + @TraceInterceptor + private ClientRequestInfoImpl peekClientRequestInfoImplStack() { + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + ClientRequestInfoImpl info = null; + if( !infoStack.empty() ) { + info = infoStack.peek(); + } else { + throw wrapper.clientInfoStackNull() ; + } + + return info; + } + + /** + * Convenience method to get the ServerRequestInfoImpl object off the + * top of the ThreadLocal stack. Returns null if there are none. + */ + @TraceInterceptor + private ServerRequestInfoImpl peekServerRequestInfoImplStack() { + RequestInfoStack infoStack = + threadLocalServerRequestInfoStack.get(); + ServerRequestInfoImpl info = null; + + if( !infoStack.empty() ) { + info = infoStack.peek(); + } else { + throw wrapper.serverInfoStackNull() ; + } + + return info; + } + + /** + * Convenience method to determine whether Client PI is enabled + * for requests on this thread. + */ + @TraceInterceptor + private boolean isClientPIEnabledForThisThread() { + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + return (infoStack.disableCount == 0); + } + + /** + * Call pre_init on all ORB initializers + */ + @TraceInterceptor + private void preInitORBInitializers( ORBInitInfoImpl info ) { + // Inform ORBInitInfo we are in pre_init stage + info.setStage( ORBInitInfoImpl.STAGE_PRE_INIT ); + + // Step through each initializer instantiation and call its + // pre_init. Ignore any exceptions. + for( int i = 0; i < orb.getORBData().getORBInitializers().length; + i++ ) { + ORBInitializer init = orb.getORBData().getORBInitializers()[i]; + if( init != null ) { + try { + init.pre_init( info ); + } + catch( Exception e ) { + // As per orbos/99-12-02, section 9.3.1.2, "If there are + // any exceptions, the ORB shall ignore them and proceed." + } + } + } + } + + /** + * Call post_init on all ORB initializers + */ + @TraceInterceptor + private void postInitORBInitializers( ORBInitInfoImpl info ) { + // Inform ORBInitInfo we are in post_init stage + info.setStage( ORBInitInfoImpl.STAGE_POST_INIT ); + + // Step through each initializer instantiation and call its post_init. + // Ignore any exceptions. + for( int i = 0; i < orb.getORBData().getORBInitializers().length; + i++ ) { + ORBInitializer init = orb.getORBData().getORBInitializers()[i]; + if( init != null ) { + try { + init.post_init( info ); + } + catch( Exception e ) { + // As per orbos/99-12-02, section 9.3.1.2, "If there are + // any exceptions, the ORB shall ignore them and proceed." + } + } + } + } + + /** + * Creates the ORBInitInfo object to be passed to ORB intializers' + * pre_init and post_init methods + */ + @TraceInterceptor + private ORBInitInfoImpl createORBInitInfo() { + ORBInitInfoImpl result = null; + + // arguments comes from set_parameters. May be null. + + // _REVISIT_ The spec does not specify which ID this is to be. + // We currently get this from the corba.ORB, which reads it from + // the ORB_ID_PROPERTY property. + String orbId = orb.getORBData().getORBId() ; + + result = new ORBInitInfoImpl( orb, arguments, orbId, codecFactory ); + + return result; + } + + /** + * Called by ORBInitInfo when an interceptor needs to be registered. + * The type is one of: + *

      + *
    • INTERCEPTOR_TYPE_CLIENT - ClientRequestInterceptor + *
    • INTERCEPTOR_TYPE_SERVER - ServerRequestInterceptor + *
    • INTERCEPTOR_TYPE_IOR - IORInterceptor + *
    + * + * @exception DuplicateName Thrown if an interceptor of the given + * name already exists for the given type. + */ + @TraceInterceptor + public void register_interceptor( Interceptor interceptor, int type ) + throws DuplicateName { + // We will assume interceptor is not null, since it is called + // internally. + if( (type >= InterceptorList.NUM_INTERCEPTOR_TYPES) || (type < 0) ) { + throw wrapper.typeOutOfRange( type ) ; + } + + String interceptorName = interceptor.name(); + + if( interceptorName == null ) { + throw wrapper.nameNull() ; + } + + // Register with interceptor list: + interceptorList.register_interceptor( interceptor, type ); + } + + public Current getPICurrent( ) { + return current; + } + + /** + * Called when an invalid null parameter was passed. Throws a + * BAD_PARAM with a minor code of 1 + */ + private void nullParam() + throws BAD_PARAM + { + throw orbutilWrapper.nullParam() ; + } + + /** This is the implementation of standard API defined in org.omg.CORBA.ORB + * class. This method finds the Policy Factory for the given Policy Type + * and instantiates the Policy object from the Factory. It will throw + * PolicyError exception, If the PolicyFactory for the given type is + * not registered. + * _REVISIT_, Once Policy Framework work is completed, Reorganize + * this method to com.sun.corba.ee.spi.orb.ORB. + */ + @TraceInterceptor + public org.omg.CORBA.Policy create_policy(int type, org.omg.CORBA.Any val) + throws org.omg.CORBA.PolicyError { + if( val == null ) { + nullParam( ); + } + + if( policyFactoryTable == null ) { + throw new org.omg.CORBA.PolicyError( + "There is no PolicyFactory Registered for type " + type, + BAD_POLICY.value ); + } + + PolicyFactory factory = policyFactoryTable.get( type ); + if( factory == null ) { + throw new org.omg.CORBA.PolicyError( + " Could Not Find PolicyFactory for the Type " + type, + BAD_POLICY.value); + } + + org.omg.CORBA.Policy policy = factory.create_policy( type, val ); + return policy; + } + + /** This method registers the Policy Factory in the policyFactoryTable, + * which is a HashMap. This method is made package private, because + * it is used internally by the Interceptors. + */ + @TraceInterceptor + public void registerPolicyFactory( int type, PolicyFactory factory ) { + if( policyFactoryTable == null ) { + policyFactoryTable = new HashMap(); + } + Integer key = Integer.valueOf( type ); + PolicyFactory val = policyFactoryTable.get( key ); + if (val == null) { + policyFactoryTable.put( key, factory ); + } else { + throw omgWrapper.policyFactoryRegFailed( type ) ; + } + } + + public synchronized int allocateServerRequestId () + { + return serverRequestIdCounter++; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PINoOpHandlerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PINoOpHandlerImpl.java new file mode 100644 index 000000000..ba00ddf9d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/PINoOpHandlerImpl.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + + +import org.omg.CORBA.Any; +import org.omg.CORBA.NVList; + + +import org.omg.CORBA.portable.RemarshalException; + +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.Interceptor; +import org.omg.PortableInterceptor.PolicyFactory; +import org.omg.PortableInterceptor.Current; + +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName ; + + +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; + + +import com.sun.corba.ee.spi.protocol.PIHandler; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.impl.corba.RequestImpl; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; + +/** + * This is No-Op implementation of PIHandler. It is used in ORBConfigurator + * to initialize a piHandler before the Persistent Server Activation. This + * PIHandler implementation will be replaced by the real PIHandler in + * ORB.postInit( ) call. + */ +public class PINoOpHandlerImpl implements PIHandler +{ + public PINoOpHandlerImpl( ) { + } + + public void close() { + } + + public void initialize() { + } + + public void destroyInterceptors() { + } + + public void objectAdapterCreated( ObjectAdapter oa ) + { + } + + public void adapterManagerStateChanged( int managerId, + short newState ) + { + } + + public void adapterStateChanged( ObjectReferenceTemplate[] + templates, short newState ) + { + } + + + public void disableInterceptorsThisThread() { + } + + public void enableInterceptorsThisThread() { + } + + public void invokeClientPIStartingPoint() + throws RemarshalException + { + } + + public Exception invokeClientPIEndingPoint( + int replyStatus, Exception exception ) + { + return null; + } + + public Exception makeCompletedClientRequest( + int replyStatus, Exception exception ) + { + return null; + } + + public void initiateClientPIRequest( boolean diiRequest ) { + } + + public void cleanupClientPIRequest() { + } + + public void setClientPIInfo(MessageMediator messageMediator) + { + } + + public void setClientPIInfo( RequestImpl requestImpl ) + { + } + + final public void sendCancelRequestIfFinalFragmentNotSent() + { + } + + + public void invokeServerPIStartingPoint() + { + } + + public void invokeServerPIIntermediatePoint() + { + } + + public void invokeServerPIEndingPoint( ReplyMessage replyMessage ) + { + } + + public void setServerPIInfo( Exception exception ) { + } + + public void setServerPIInfo( NVList arguments ) + { + } + + public void setServerPIExceptionInfo( Any exception ) + { + } + + public void setServerPIInfo( Any result ) + { + } + + public void initializeServerPIInfo( MessageMediator request, + ObjectAdapter oa, byte[] objectId, ObjectKeyTemplate oktemp ) + { + } + + public void setServerPIInfo( java.lang.Object servant, + String targetMostDerivedInterface ) + { + } + + public void cleanupServerPIRequest() { + } + + public void register_interceptor( Interceptor interceptor, int type ) + throws DuplicateName + { + } + + public Current getPICurrent( ) { + return null; + } + + public org.omg.CORBA.Policy create_policy(int type, org.omg.CORBA.Any val) + throws org.omg.CORBA.PolicyError + { + return null; + } + + public void registerPolicyFactory( int type, PolicyFactory factory ) { + } + + public int allocateServerRequestId () + { + return 0; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/RequestInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/RequestInfoImpl.java new file mode 100644 index 000000000..62d711a47 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/RequestInfoImpl.java @@ -0,0 +1,891 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import com.sun.corba.ee.impl.encoding.EncapsOutputStream; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.legacy.connection.Connection; +import com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt; +import com.sun.corba.ee.spi.logging.InterceptorsSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.misc.ORBClassLoader; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.servicecontext.UnknownServiceContext; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Map; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.LocalObject; +import org.omg.CORBA.NVList; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.Object; +import org.omg.CORBA.ParameterMode; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.UNKNOWN; +import org.omg.CORBA.UserException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.Dynamic.Parameter; +import org.omg.IOP.ServiceContextHelper; +import org.omg.Messaging.SYNC_WITH_TRANSPORT; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.PortableInterceptor.RequestInfo; + +/** + * Implementation of the RequestInfo interface as specified in + * orbos/99-12-02 section 5.4.1. + */ +public abstract class RequestInfoImpl + extends LocalObject + implements RequestInfo, RequestInfoExt +{ + protected static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + static final OMGSystemException stdWrapper = + OMGSystemException.self ; + + ////////////////////////////////////////////////////////////////////// + // + // NOTE: IF AN ATTRIBUTE IS ADDED, PLEASE UPDATE RESET(); + // + ////////////////////////////////////////////////////////////////////// + + // The ORB from which to get PICurrent and other info + protected ORB myORB; + + // The number of interceptors actually invoked for this client request. + // See setFlowStackIndex for a detailed description. + private int flowStackIndex = 0; + + // The type of starting point call to make to the interceptors + // See ClientRequestInfoImpl and ServerRequestInfoImpl for a list of + // appropriate constants. + int startingPointCall; + + // The type of intermediate point call to make to the interceptors + // See ServerRequestInfoImpl for a list of appropriate constants. + // This does not currently apply to client request interceptors but is + // here in case intermediate points are introduced in the future. + int intermediatePointCall; + + // The type of ending point call to make to the interceptors + // See ClientRequestInfoImpl and ServerRequestInfoImpl for a list of + // appropriate constants. + int endingPointCall; + + // The reply status to return in reply_status. This is initialized + // to UNINITIALIZED so that we can tell if this has been set or not. + protected short replyStatus = UNINITIALIZED; + + // Constant for an uninitizlied reply status. + static final short UNINITIALIZED = -1; + + // Which points we are currently executing (so we can implement the + // validity table). + int currentExecutionPoint; + static final int EXECUTION_POINT_STARTING = 0; + static final int EXECUTION_POINT_INTERMEDIATE = 1; + static final int EXECUTION_POINT_ENDING = 2; + + // Set to true if all interceptors have had all their points + // executed. + private boolean alreadyExecuted; + + // Sources of request information + protected Connection connection; + + // The ForwardRequest object if this request is being forwarded. + // Either the forwardRequest or the forwardRequestIOR field is set. + // When set, the other field is set to null initially. If the other + // field is queried, it is lazily calculated and cached. These + // two attributes are always kept in sync. + private ForwardRequest forwardRequest; + private IOR forwardRequestIOR; + + // PICurrent's SlotTable + SlotTable slotTable; + + // The exception to be returned by received_exception and + // received_exception_id + protected Exception exception; + + boolean interceptorsEnabledForThisRequest ; + + ////////////////////////////////////////////////////////////////////// + // + // NOTE: IF AN ATTRIBUTE IS ADDED, PLEASE UPDATE RESET(); + // + ////////////////////////////////////////////////////////////////////// + + @Override + public org.omg.CORBA.ORB _orb() { + return myORB; + } + + /** + * Reset the info object so that it can be reused for a retry, + * for example. + */ + void reset() { + + // Please keep these in the same order as declared above. + + flowStackIndex = 0; + startingPointCall = 0; + intermediatePointCall = 0; + endingPointCall = 0; + // 6763340 + setReplyStatus( UNINITIALIZED ) ; + currentExecutionPoint = EXECUTION_POINT_STARTING; + alreadyExecuted = false; + connection = null; + ServiceContexts serviceContexts = null; + forwardRequest = null; + forwardRequestIOR = null; + exception = null; + + // We don't need to reset the Slots because they are + // already in the clean state after recieve_ interceptor + // are called. + + interceptorsEnabledForThisRequest = false ; + } + + /* + ********************************************************************** + * Access protection + **********************************************************************/ + + // Method IDs for all methods in RequestInfo. This allows for a + // convenient O(1) lookup for checkAccess(). + protected static final int MID_REQUEST_ID = 0; + protected static final int MID_OPERATION = 1; + protected static final int MID_ARGUMENTS = 2; + protected static final int MID_EXCEPTIONS = 3; + protected static final int MID_CONTEXTS = 4; + protected static final int MID_OPERATION_CONTEXT = 5; + protected static final int MID_RESULT = 6; + protected static final int MID_RESPONSE_EXPECTED = 7; + protected static final int MID_SYNC_SCOPE = 8; + protected static final int MID_REPLY_STATUS = 9; + protected static final int MID_FORWARD_REFERENCE = 10; + protected static final int MID_GET_SLOT = 11; + protected static final int MID_GET_REQUEST_SERVICE_CONTEXT = 12; + protected static final int MID_GET_REPLY_SERVICE_CONTEXT = 13; + // The last value from RequestInfo (be sure to update this): + protected static final int MID_RI_LAST = 13; + + /* + ********************************************************************** + * Public interfaces + **********************************************************************/ + + /** + * Creates a new RequestInfoImpl object. + */ + public RequestInfoImpl( ORB myORB ) { + super(); + + this.myORB = myORB; + + // Capture the current TSC and make it the RSC of this request. + PICurrent current = (PICurrent)(myORB.getPIHandler().getPICurrent()); + slotTable = current.getSlotTable( ); + + interceptorsEnabledForThisRequest = false ; + } + + /** + * Implementation for request_id() differs for client and server + * implementations. + * + * Uniquely identifies an active request/reply sequence. Once a + * request/reply sequence is concluded this ID may be reused. (this + * is NOT necessarily the same as the GIOP request_id). + */ + abstract public int request_id (); + + /** + * Implementation for operation() differs for client and server + * implementations. + * + * The name of the operation being invoked. + */ + abstract public String operation (); + + + /** + * This method returns the list of arguments for the operation that was + * invoked. It raises NO_RESOURCES exception if the operation is not invoked + * by using DII mechanism. + */ + abstract public Parameter[] arguments (); + + /** + * This method returns the list of exceptios that was raised when the + * operation was invoked. It raises NO_RESOURCES exception if the operation + * is not invoked by using DII mechanism. + */ + abstract public TypeCode[] exceptions (); + + /** + * This method returns the list of contexts for the DII operation. + * It raises NO_RESOURCES exception if the operation is not invoked by + * using DII mechanism. + */ + abstract public String[] contexts (); + + /** + * This method returns the list of operation_context for the DII operation. + * It raises NO_RESOURCES exception if the operation is not invoked by + * using DII mechanism. + */ + abstract public String[] operation_context (); + + /** + * This method returns the result from the invoked DII operation. + * It raises NO_RESOURCES exception if the operation is not invoked by + * using DII mechanism. + */ + abstract public Any result (); + + /** + * Implementation for response_expected() differs for client and server + * implementations. + * + * Indicates whether a response is expected. On the client, a reply is + * not returned when response_expected is false, so receive_reply cannot + * be called. receive_other is called unless an exception occurs, in + * which case receive_exception is called. On the client, within + * send_poll, this attribute is true. + */ + abstract public boolean response_expected (); + + /** + * Defined in the Messaging specification. Pertinent only when + * response_expected is false. If response_expected is true, the value + * of sync_scope is undefined. It defines how far the request shall + * progress before control is returned to the client. This attribute may + * have one of the follwing values: + *
      + *
    • Messaging::SYNC_NONE
    • + *
    • Messaging::SYNC_WITH_TRANSPORT
    • + *
    • Messaging::SYNC_WITH_SERVER
    • + *
    • Messaging::SYNC_WITH_TARGET
    • + *
    + */ + public short sync_scope (){ + checkAccess( MID_SYNC_SCOPE ); + return SYNC_WITH_TRANSPORT.value; // REVISIT - get from MessageMediator + } + + /** + * Describes the state of the result of the operation invocation. Its + * value can be one of the following: + *
      + *
    • PortableInterceptor::SUCCESSFUL
    • + *
    • PortableInterceptor::SYSTEM_EXCEPTION
    • + *
    • PortableInterceptor::USER_EXCEPTION
    • + *
    • PortableInterceptor::LOCATION_FORWARD
    • + *
    • PortableInterceptor::TRANSPORT_RETRY
    • + *
    + */ + public short reply_status (){ + checkAccess( MID_REPLY_STATUS ); + return replyStatus; + } + + /** + * Implementation for forward_reference() differs for client and server + * implementations. + * + * If the reply_status attribute is LOCATION_FORWARD + * then this attribute will contain the object + * to which the request will be forwarded. It is indeterminate whether a + * forwarded request will actually occur. + */ + abstract public Object forward_reference (); + + + /** + * Returns the data from the given slot of the PortableInterceptor::Current + * that is in the scope of the request. + *

    + * If the given slot has not been set, then an any containing a type code + * with a TCKind value of tk_null is returned. + *

    + * If the ID does not define an allocated slot, InvalidSlot is raised. + */ + public Any get_slot (int id) + throws InvalidSlot + { + // access is currently valid for all states: + //checkAccess( MID_GET_SLOT ); + // Delegate the call to the slotTable which was set when RequestInfo was + // created. + return slotTable.get_slot( id ); + } + + /** + * Implementation for get_request_service_context() differs for client + * and server implementations. + * + * This operation returns a copy of the service context with the given ID + * that is associated with the request. If the request's service context + * does not contain an etry for that ID, BAD_PARAM with a minor code of + * TBD_BP is raised. + */ + abstract public org.omg.IOP.ServiceContext + get_request_service_context(int id); + + /** + * Implementation for get_reply_service_context() differs for client + * and server implementations. + * + * This operation returns a copy of the service context with the given ID + * that is associated with the reply. IF the request's service context + * does not contain an entry for that ID, BAD_PARAM with a minor code of + * TBD_BP is raised. + */ + abstract public org.omg.IOP.ServiceContext + get_reply_service_context (int id); + + + // NOTE: When adding a method, be sure to: + // 1. Add a MID_* constant for that method + // 2. Call checkAccess at the start of the method + // 3. Define entries in the validCall[][] table for interception points + // in both ClientRequestInfoImpl and ServerRequestInfoImpl. + + + + /* + ********************************************************************** + * Proprietary methods + **********************************************************************/ + + /** + * @return The connection on which the request is made. + * + * Note: we store the connection as an internal type but + * expose it here as an external type. + */ + public com.sun.corba.ee.spi.legacy.connection.Connection connection() + { + return connection; + } + + /* + ********************************************************************** + * Private utility methods + **********************************************************************/ + + /** + * Inserts the UserException inside the given ApplicationException + * into the given Any. Throws an UNKNOWN with minor code + * OMGSYstemException.UNKNOWN_USER_EXCEPTION if the Helper class could not be + * found to insert it with. + */ + private void insertApplicationException( ApplicationException appException, + Any result ) + throws UNKNOWN + { + try { + // Extract the UserException from the ApplicationException. + // Look up class name from repository id: + RepositoryId repId = RepositoryId.cache.getId( + appException.getId() ); + String className = repId.getClassName(); + + // Find the read method on the helper class: + String helperClassName = className + "Helper"; + Class helperClass = ORBClassLoader.loadClass( helperClassName ); + Class[] readParams = new Class[1]; + readParams[0] = org.omg.CORBA.portable.InputStream.class; + Method readMethod = helperClass.getMethod( "read", readParams ); + + // Invoke the read method, passing in the input stream to + // retrieve the user exception. Mark and reset the stream + // as to not disturb it. + InputStream ueInputStream = appException.getInputStream(); + ueInputStream.mark( 0 ); + UserException userException = null; + try { + java.lang.Object[] readArguments = new java.lang.Object[1]; + readArguments[0] = ueInputStream; + userException = (UserException)readMethod.invoke( + null, readArguments ); + } + finally { + try { + ueInputStream.reset(); + } + catch( IOException e ) { + throw wrapper.markAndResetFailed( e ) ; + } + } + + // Insert this UserException into the provided Any using the + // helper class. + insertUserException( userException, result ); + } catch( ClassNotFoundException e ) { + throw stdWrapper.unknownUserException( e ) ; + } catch( NoSuchMethodException e ) { + throw stdWrapper.unknownUserException( e ) ; + } catch( SecurityException e ) { + throw stdWrapper.unknownUserException( e ) ; + } catch( IllegalAccessException e ) { + throw stdWrapper.unknownUserException( e ) ; + } catch( IllegalArgumentException e ) { + throw stdWrapper.unknownUserException( e ) ; + } catch( InvocationTargetException e ) { + throw stdWrapper.unknownUserException( e ) ; + } + } + + /** + * Inserts the UserException into the given Any. + * Throws an UNKNOWN with minor code + * OMGSYstemException.UNKNOWN_USER_EXCEPTION if the Helper class could not be + * found to insert it with. + */ + private void insertUserException( UserException userException, Any result ) + throws UNKNOWN + { + try { + // Insert this UserException into the provided Any using the + // helper class. + if( userException != null ) { + Class exceptionClass = userException.getClass(); + String className = exceptionClass.getName(); + String helperClassName = className + "Helper"; + Class helperClass = ORBClassLoader.loadClass( helperClassName ); + + Method insertMethod = helperClass.getMethod( + "insert", org.omg.CORBA.Any.class, exceptionClass ); + + insertMethod.invoke( null, result, userException ); + } + } catch( ClassNotFoundException e ) { + throw stdWrapper.unknownUserException( e ); + } catch( NoSuchMethodException e ) { + throw stdWrapper.unknownUserException( e ); + } catch( SecurityException e ) { + throw stdWrapper.unknownUserException( e ); + } catch( IllegalAccessException e ) { + throw stdWrapper.unknownUserException( e ); + } catch( IllegalArgumentException e ) { + throw stdWrapper.unknownUserException( e ); + } catch( InvocationTargetException e ) { + throw stdWrapper.unknownUserException( e ); + } + } + + /* + ********************************************************************** + * Protected utility methods + **********************************************************************/ + + /** + * Internal utility method to convert an NVList into a PI Parameter[] + */ + protected Parameter[] nvListToParameterArray( NVList parNVList ) { + + // _REVISIT_ This utility method should probably be doing a deep + // copy so interceptor can't accidentally change the arguments. + + int count = parNVList.count(); + Parameter[] plist = new Parameter[count]; + try { + for( int i = 0; i < count; i++ ) { + Parameter p = new Parameter(); + plist[i] = p; + NamedValue nv = parNVList.item( i ); + plist[i].argument = nv.value(); + // ParameterMode spec can be found in 99-10-07.pdf + // Section:10.5.22 + // nv.flags spec can be found in 99-10-07.pdf + // Section 7.1.1 + // nv.flags has ARG_IN as 1, ARG_OUT as 2 and ARG_INOUT as 3 + // To convert this into enum PARAM_IN, PARAM_OUT and + // PARAM_INOUT the value is subtracted by 1. + plist[i].mode = ParameterMode.from_int( nv.flags() - 1 ); + } + } catch ( Exception e ) { + throw wrapper.exceptionInArguments( e ) ; + } + + return plist; + } + + /** + * Utility to wrap the given Exception in an Any object and return it. + * If the exception is a UserException which cannot be inserted into + * an any, then this returns an Any containing the system exception + * UNKNOWN. + */ + protected Any exceptionToAny( Exception exception ){ + Any result = myORB.create_any(); + + if( exception == null ) { + // Note: exception should never be null here since we will throw + // a BAD_INV_ORDER if this is not called from receive_exception. + throw wrapper.exceptionWasNull2() ; + } else if( exception instanceof SystemException ) { + ORBUtility.insertSystemException( + (SystemException)exception, result ); + } else if( exception instanceof ApplicationException ) { + // Use the Helper class for this exception to insert it into an + // Any. + try { + // Insert the user exception inside the application exception + // into the Any result: + ApplicationException appException = + (ApplicationException)exception; + insertApplicationException( appException, result ); + } catch( UNKNOWN e ) { + // As per ptc/00-08-06, 21.3.13.4. if we cannot find the + // appropriate class, then return an any containing UNKNOWN, + // with a minor code of 1. This is conveniently the same + // exception that is returned from the + // insertApplicationException utility method. + ORBUtility.insertSystemException( e, result ); + } + } else if( exception instanceof UserException ) { + try { + UserException userException = (UserException)exception; + insertUserException( userException, result ); + } catch( UNKNOWN e ) { + ORBUtility.insertSystemException( e, result ); + } + } + + + return result; + } + + /** + * Utility method to look up a service context with the given id and + * convert it to an IOP.ServiceContext. Uses the given HashMap as + * a cache. If not found in cache, the result is inserted in the cache. + */ + protected org.omg.IOP.ServiceContext getServiceContext( + Map cachedServiceContexts, + ServiceContexts serviceContexts, int id ) + { + org.omg.IOP.ServiceContext result = null; + + // Search cache first: + result = cachedServiceContexts.get( id ); + + // null could normally mean that either we cached the value null + // or it's not in the cache. However, there is no way for us to + // cache the value null in the following code. + if( result == null ) { + // Not in cache. Find it and put in cache. + // Get the desired "core" service context. + com.sun.corba.ee.spi.servicecontext.ServiceContext context = + serviceContexts.get( id ); + + if (context == null) { + // The OMG PI standard requires throwing an exception, + // but that is slow, so we allow disabling this behavior. + if (myORB.getORBData().getServiceContextReturnsNull()) { + return null ; + } else { + throw stdWrapper.invalidServiceContextId() ; + } + } + + // Convert the "core" service context to an + // "IOP" ServiceContext by writing it to a + // CDROutputStream and reading it back. + EncapsOutputStream out = OutputStreamFactory.newEncapsOutputStream(myORB); + + context.write( out, GIOPVersion.V1_2 ); + InputStream inputStream = out.create_input_stream(); + result = ServiceContextHelper.read( inputStream ); + + cachedServiceContexts.put( id, result ); + } + + // Good citizen: For increased efficiency, we assume that interceptors + // will not modify the returned ServiceContext. Otherwise, we would + // have to make a deep copy. + + return result; + } + + + /** + * Utility method to add an IOP.ServiceContext to a core.ServiceContexts + * object. If replace is true, any service context with the given id + * is replaced. + *

    + * Raises BAD_INV_ORDER if replace is false and a service context with + * the given id already exists. + *

    + * Uses the given HashMap as a cache. If a service context is placed + * in the container, it goes in the HashMap as well. + */ + protected void addServiceContext( + Map cachedServiceContexts, + ServiceContexts serviceContexts, + org.omg.IOP.ServiceContext service_context, + boolean replace ) + { + int id = 0 ; + // Convert IOP.service_context to core.ServiceContext: + EncapsOutputStream outputStream = OutputStreamFactory.newEncapsOutputStream( + myORB ); + InputStream inputStream = null; + UnknownServiceContext coreServiceContext = null; + ServiceContextHelper.write( outputStream, service_context ); + inputStream = outputStream.create_input_stream(); + + // Constructor expects id to already have been read from stream. + coreServiceContext = ServiceContextDefaults.makeUnknownServiceContext( + inputStream.read_long(), + (org.omg.CORBA_2_3.portable.InputStream)inputStream ); + + id = coreServiceContext.getId(); + + if (serviceContexts.get(id) != null) { + if (replace) { + serviceContexts.delete(id); + } else { + throw stdWrapper.serviceContextAddFailed(id); + } + } + + serviceContexts.put( coreServiceContext ); + + // Place IOP.ServiceContext in cache as well: + cachedServiceContexts.put( id, service_context ); + } + + /** + * Sets the number of interceptors whose starting interception + * points were successfully invoked on this client call. As specified + * in orbos/99-12-02, section 5.2.1., not all interceptors will + * be invoked if a ForwardRequest exception or a system exception + * is raised. This keeps track of how many were successfully executed + * so we know not to execute the corresponding ending interception + * points for the interceptors whose starting interception points + * were not completed. This simulates the "Flow Stack Visual Model" + * presented in section 5.1.3.*/ + protected void setFlowStackIndex(int num ) { + this.flowStackIndex = num; + } + + /** + * Returns the number of interceptors whose starting interception + * points were actually invoked on this client request. See + * setFlowStackIndex for more details. + */ + protected int getFlowStackIndex() { + return this.flowStackIndex; + } + + /** + * Sets which ending interception point should be called + * for each interceptor in the virtual flow stack. + */ + protected void setEndingPointCall( int call ) { + this.endingPointCall = call; + } + + /** + * Retrieves the current ending point call type (see + * setEndingPointCall for more details). + */ + protected int getEndingPointCall() { + return this.endingPointCall; + } + + /** + * Sets which intermediate interception point should be called + * for each interceptor in the virtual flow stack. + */ + protected void setIntermediatePointCall( int call ) { + this.intermediatePointCall = call; + } + + /** + * Retrieves the current intermediate point call type (see + * setEndingPointCall for more details). + */ + protected int getIntermediatePointCall() { + return this.intermediatePointCall; + } + + /** + * Sets which starting interception point should be called + * for each interceptor in the virtual flow stack. + */ + protected void setStartingPointCall( int call ) { + this.startingPointCall = call; + } + + /** + * Retrieves the current starting point call type (see + * setStartingPointCall for more details). + */ + protected int getStartingPointCall() { + return this.startingPointCall; + } + + /** + * Returns true if all interceptors' starting and ending points + * have already executed to completion, or false if not yet. + */ + protected boolean getAlreadyExecuted() { + return this.alreadyExecuted; + } + + /** + * Sets whether all interceotrs' starting and ending points + * have already been executed to completion. + */ + protected void setAlreadyExecuted( boolean alreadyExecuted ) { + this.alreadyExecuted = alreadyExecuted; + } + + /** + * Sets the value to be returned by reply_status + */ + protected void setReplyStatus( short replyStatus ) { + this.replyStatus = replyStatus; + } + + /** + * Gets the current reply_status without doing an access check + * (available only to package and subclasses) + */ + protected short getReplyStatus() { + return this.replyStatus; + } + + /** + * Stores the given ForwardRequest object for later analysis. + * This version supplements setForwardRequest( IOR ); + */ + protected void setForwardRequest( ForwardRequest forwardRequest ) { + this.forwardRequest = forwardRequest; + this.forwardRequestIOR = null; + } + + /** + * Stores the given IOR for later forward request analysis. + * This version supplements setForwardRequest( ForwardRequest ); + */ + protected void setForwardRequest( IOR ior ) { + this.forwardRequestIOR = ior; + this.forwardRequest = null; + } + + /** + * Retrieves the ForwardRequest object as a ForwardRequest exception. + */ + protected ForwardRequest getForwardRequestException() { + if( this.forwardRequest == null ) { + if( this.forwardRequestIOR != null ) { + // Convert the internal IOR to a forward request exception + // by creating an object reference. + org.omg.CORBA.Object obj = iorToObject(this.forwardRequestIOR); + this.forwardRequest = new ForwardRequest( obj ); + } + } + + return this.forwardRequest; + } + + /** + * Retrieves the IOR of the ForwardRequest exception. + */ + protected IOR getForwardRequestIOR() { + if( this.forwardRequestIOR == null ) { + if( this.forwardRequest != null ) { + this.forwardRequestIOR = myORB.getIOR( + this.forwardRequest.forward, false ) ; + } + } + + return this.forwardRequestIOR; + } + + /** + * Sets the exception to be returned by received_exception and + * received_exception_id. + */ + protected void setException( Exception exception ) { + this.exception = exception; + } + + /** + * Returns the exception to be returned by received_exception and + * received_exception_id. + */ + Exception getException() { + return this.exception; + } + + /** + * Sets the execution point that we are currently executing + * (starting points, intermediate points, or ending points). + * This allows us to enforce the validity table. + */ + protected void setCurrentExecutionPoint( int executionPoint ) { + this.currentExecutionPoint = executionPoint; + } + + /** + * Check whether the caller is allowed to access this method at + * this particular time. This is overridden in subclasses to implement + * the validity table specified in ptc/00-04-05, table 21-1 and 21-2. + * The currentExecutionPoint attribute is checked, and if access is + * forbidden at this time, BAD_INV_ORDER is raised with a minor code of + * TBD_BIO. + * + * @param methodID The ID of this method, one of the MID_* constants. + * This allows us to easily look up the method access in a table. + * Note that method ids may overlap between subclasses. + */ + protected abstract void checkAccess( int methodID ) + throws BAD_INV_ORDER; + + /** + * The server side does an explicit set rather than taking the + * current PICurrent table as is done in the general RequestInfoImpl + * constructor. + */ + void setSlotTable(SlotTable slotTable) + { + this.slotTable = slotTable; + } + + protected org.omg.CORBA.Object iorToObject( IOR ior ) + { + return ORBUtility.makeObjectReference( ior ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ServerRequestInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ServerRequestInfoImpl.java new file mode 100644 index 000000000..a429571bf --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/ServerRequestInfoImpl.java @@ -0,0 +1,889 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.NVList; +import org.omg.CORBA.Object; +import org.omg.CORBA.Policy; +import org.omg.CORBA.TypeCode; + +import org.omg.PortableServer.Servant; + +import org.omg.IOP.ServiceContext; + +import org.omg.Dynamic.Parameter; + +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.PortableInterceptor.ServerRequestInfo; +import org.omg.PortableInterceptor.LOCATION_FORWARD; +import org.omg.PortableInterceptor.SUCCESSFUL; +import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; +import org.omg.PortableInterceptor.TRANSPORT_RETRY; +import org.omg.PortableInterceptor.USER_EXCEPTION; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; +import com.sun.corba.ee.spi.legacy.interceptor.ServerRequestInfoExt; + +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import java.util.*; + +/** + * Implementation of the ServerRequestInfo interface as specified in + * orbos/99-12-02 section 5.4.3. + */ +public final class ServerRequestInfoImpl + extends RequestInfoImpl + implements ServerRequestInfo, ServerRequestInfoExt +{ + // The available constants for startingPointCall + static final int CALL_RECEIVE_REQUEST_SERVICE_CONTEXT = 0; + + // The available constants for intermediatePointCall. The default (0) + // is receive_request, but can be set to none on demand. + static final int CALL_RECEIVE_REQUEST = 0; + static final int CALL_INTERMEDIATE_NONE = 1; + + // The available constants for endingPointCall + static final int CALL_SEND_REPLY = 0; + static final int CALL_SEND_EXCEPTION = 1; + static final int CALL_SEND_OTHER = 2; + + ////////////////////////////////////////////////////////////////////// + // + // NOTE: IF AN ATTRIBUTE IS ADDED, PLEASE UPDATE RESET(); + // + ////////////////////////////////////////////////////////////////////// + + // Set to true if the server ending point raised ForwardRequest at some + // point in the ending point. + private boolean forwardRequestRaisedInEnding; + + // Sources of server request information: + private MessageMediator request; + private java.lang.Object servant; + private byte[] objectId; + private ObjectKeyTemplate oktemp ; + + // Information cached from calls to oktemp + private byte[] adapterId; + private String[] adapterName; + + private ArrayList addReplyServiceContextQueue; + private ReplyMessage replyMessage; + private String targetMostDerivedInterface; + private NVList dsiArguments; + private Any dsiResult; + private Any dsiException; + private boolean isDynamic; + private ObjectAdapter objectAdapter; + private int serverRequestId; + + // Cached information: + private Parameter[] cachedArguments; + private Any cachedSendingException; + private HashMap cachedRequestServiceContexts; + private HashMap cachedReplyServiceContexts; + + ////////////////////////////////////////////////////////////////////// + // + // NOTE: IF AN ATTRIBUTE IS ADDED, PLEASE UPDATE RESET(); + // + ////////////////////////////////////////////////////////////////////// + + + /** + * Reset the info object so that it can be reused for a retry, + * for example. + */ + synchronized void reset() { + super.reset(); + + // Please keep these in the same order as declared above. + + forwardRequestRaisedInEnding = false; + + request = null; + servant = null; + objectId = null; + oktemp = null; + + adapterId = null; + adapterName = null; + + addReplyServiceContextQueue = null; + replyMessage = null; + targetMostDerivedInterface = null; + dsiArguments = null; + dsiResult = null; + dsiException = null; + isDynamic = false; + objectAdapter = null; + serverRequestId = myORB.getPIHandler().allocateServerRequestId(); + + // reset cached attributes: + cachedArguments = null; + cachedSendingException = null; + cachedRequestServiceContexts = null; + cachedReplyServiceContexts = null; + + startingPointCall = CALL_RECEIVE_REQUEST_SERVICE_CONTEXT; + intermediatePointCall = CALL_RECEIVE_REQUEST; + endingPointCall = CALL_SEND_REPLY; + } + + /* + ********************************************************************** + * Access protection + **********************************************************************/ + + // Method IDs for all methods in ServerRequestInfo. This allows for a + // convenient O(1) lookup for checkAccess(). + private static final int MID_SENDING_EXCEPTION = MID_RI_LAST + 1; + private static final int MID_OBJECT_ID = MID_RI_LAST + 2; + private static final int MID_ADAPTER_ID = MID_RI_LAST + 3; + private static final int MID_TARGET_MOST_DERIVED_INTERFACE = MID_RI_LAST + 4; + private static final int MID_GET_SERVER_POLICY = MID_RI_LAST + 5; + private static final int MID_SET_SLOT = MID_RI_LAST + 6; + private static final int MID_TARGET_IS_A = MID_RI_LAST + 7; + private static final int MID_ADD_REPLY_SERVICE_CONTEXT = MID_RI_LAST + 8; + private static final int MID_SERVER_ID = MID_RI_LAST + 9; + private static final int MID_ORB_ID = MID_RI_LAST + 10; + private static final int MID_ADAPTER_NAME = MID_RI_LAST + 11; + + // ServerRequestInfo validity table (see ptc/00-08-06 table 21-2). + // Note: These must be in the same order as specified in contants. + private static final boolean validCall[][] = { + // LEGEND: + // r_rsc = receive_request_service_contexts + // r_req = receive_request + // s_rep = send_reply + // s_exc = send_exception + // s_oth = send_other + // + // A true value indicates call is valid at specified point. + // A false value indicates the call is invalid. + // + // NOTE: If the order or number of columns change, update + // checkAccess() accordingly. + // + // { r_rsc, r_req, s_rep, s_exc, s_oth } + // RequestInfo methods: + /*request_id*/ { true , true , true , true , true }, + /*operation*/ { true , true , true , true , true }, + /*arguments*/ { false, true , true , false, false }, + /*exceptions*/ { false, true , true , true , true }, + /*contexts*/ { false, true , true , true , true }, + /*operation_context*/ { false, true , true , false, false }, + /*result*/ { false, false, true , false, false }, + /*response_expected*/ { true , true , true , true , true }, + /*sync_scope*/ { true , true , true , true , true }, + /*reply_status*/ { false, false, true , true , true }, + /*forward_reference*/ { false, false, false, false, true }, + /*get_slot*/ { true , true , true , true , true }, + /*get_request_service_context*/ { true , true , true , true , true }, + /*get_reply_service_context*/ { false, false, true , true , true }, + // + // ServerRequestInfo methods:: + /*sending_exception*/ { false, false, false, true , false }, + /*object_id*/ { false, true , true , true , true }, + /*adapter_id*/ { false, true , true , true , true }, + /*target_most_derived_inte...*/ { false, true , false, false, false }, + /*get_server_policy*/ { true , true , true , true , true }, + /*set_slot*/ { true , true , true , true , true }, + /*target_is_a*/ { false, true , false, false, false }, + /*add_reply_service_context*/ { true , true , true , true , true }, + /*orb_id*/ { false, true , true , true , true }, + /*server_id*/ { false, true , true , true , true }, + /*adapter_name*/ { false, true , true , true , true } + }; + + /* + ********************************************************************** + * Public interfaces + **********************************************************************/ + + /** + * Creates a new ServerRequestInfo implementation. + * The constructor is package scope since no other package need create + * an instance of this class. + */ + ServerRequestInfoImpl( ORB myORB ) { + super( myORB ); + startingPointCall = CALL_RECEIVE_REQUEST_SERVICE_CONTEXT; + intermediatePointCall = CALL_RECEIVE_REQUEST; + endingPointCall = CALL_SEND_REPLY; + serverRequestId = myORB.getPIHandler().allocateServerRequestId(); + } + + /** + * Any containing the exception to be returned to the client. + */ + public Any sending_exception () { + checkAccess( MID_SENDING_EXCEPTION ); + + if( cachedSendingException == null ) { + Any result = null ; + + if( dsiException != null ) { + result = dsiException; + } else if( exception != null ) { + result = exceptionToAny( exception ); + } else { + // sending_exception should not be callable if both dsiException + // and exception are null. + throw wrapper.exceptionUnavailable() ; + } + + cachedSendingException = result; + } + + return cachedSendingException; + } + + /** + * The opaque object_id describing the target of the operation invocation. + */ + public byte[] object_id () { + checkAccess( MID_OBJECT_ID ); + + if( objectId == null ) { + // For some reason, we never set object id. This could be + // because a servant locator caused a location forward or + // raised an exception. As per ptc/00-08-06, section 21.3.14, + // we throw NO_RESOURCES + throw stdWrapper.piOperationNotSupported6() ; + } + + // Good citizen: In the interest of efficiency, we will assume + // interceptors will not change the resulting byte[] array. + // Otherwise, we would need to make a clone of this array. + + return objectId.clone() ; + } + + private void checkForNullTemplate() + { + if (oktemp == null) { + // For some reason, we never set the ObjectKeyTemplate + // because a servant locator caused a location forward or + // raised an exception. As per ptc/00-08-06, section 21.3.14, + // we throw NO_RESOURCES + throw stdWrapper.piOperationNotSupported7() ; + } + } + + public synchronized String server_id() + { + checkAccess( MID_SERVER_ID ) ; + checkForNullTemplate() ; + + // Good citizen: In the interest of efficiency, we will assume + // interceptors will not change the resulting byte[] array. + // Otherwise, we would need to make a clone of this array. + + return Integer.toString( oktemp.getServerId() ) ; + } + + public String orb_id() + { + checkAccess( MID_ORB_ID ) ; + + return myORB.getORBData().getORBId() ; + } + + synchronized public String[] adapter_name() + { + checkAccess( MID_ADAPTER_NAME ) ; + + if (adapterName == null) { + checkForNullTemplate() ; + + ObjectAdapterId oaid = oktemp.getObjectAdapterId() ; + adapterName = oaid.getAdapterName() ; + } + + return adapterName.clone() ; + } + + /** + * The opaque identifier for the object adapter. + */ + synchronized public byte[] adapter_id () + { + checkAccess( MID_ADAPTER_ID ); + + if( adapterId == null ) { + checkForNullTemplate() ; + adapterId = oktemp.getAdapterId() ; + } + + return adapterId.clone() ; + } + + /** + * The RepositoryID for the most derived interface of the servant. + */ + public String target_most_derived_interface () { + checkAccess( MID_TARGET_MOST_DERIVED_INTERFACE ); + return targetMostDerivedInterface; + } + + /** + * Returns the policy in effect for this operation for the given policy + * type. + */ + public Policy get_server_policy (int type) { + // access is currently valid for all states: + //checkAccess( MID_GET_SERVER_POLICY ); + + Policy result = null; + + if( objectAdapter != null ) { + result = objectAdapter.getEffectivePolicy( type ); + } + + // _REVISIT_ RTF Issue: get_server_policy spec not in sync with + // get_effective_policy spec. + + return result; + } + + /** + * Allows an Interceptor to set a slot in the Current that is in the scope + * of the request. If data already exists in that slot, it will be + * overwritten. If the ID does not define an allocated slot, InvalidSlot + * is raised. + */ + public void set_slot (int id, Any data) throws InvalidSlot { + // access is currently valid for all states: + //checkAccess( MID_SET_SLOT ); + + slotTable.set_slot( id, data ); + } + + /** + * Returns true if the servant is the given RepositoryId, false if it is + * not. + */ + public boolean target_is_a (String id) { + checkAccess( MID_TARGET_IS_A ); + + boolean result = false ; + if( servant instanceof Servant ) { + result = ((Servant)servant)._is_a( id ); + } else if (StubAdapter.isStub( servant )) { + result = ((org.omg.CORBA.Object)servant)._is_a( id ); + } else { + throw wrapper.servantInvalid() ; + } + + return result; + } + + /** + * Allows Interceptors to add service contexts to the request. + */ + public void add_reply_service_context ( ServiceContext service_context, + boolean replace ) + { + // access is currently valid for all states: + //checkAccess( MID_ADD_REPLY_SERVICE_CONTEXT ); + + if( currentExecutionPoint == EXECUTION_POINT_ENDING ) { + ServiceContexts scs = replyMessage.getServiceContexts(); + + if( cachedReplyServiceContexts == null ) { + cachedReplyServiceContexts = + new HashMap(); + } + + // This is during and ending point, so we now have enough + // information to add the reply service context. + addServiceContext( cachedReplyServiceContexts, scs, + service_context, replace ); + } + + // We enqueue all adds for the following reasons: + // + // If we are not in the ending point then we do not yet have a + // pointer to the ServiceContexts object so we cannot access the + // service contexts until we get to the ending point. + // So we enqueue this add reply service context request. + // It is added when we do have a handle on the service contexts object. + // + // If we are in the ending point and we just add directly to the + // SC container but then an interceptor raises a SystemException + // then that add will be lost since a new container is created + // for the SystemException response. + // + // Therefore we always enqueue and never dequeue (per request) so + // that all adds will be completed. + + AddReplyServiceContextCommand addReply = + new AddReplyServiceContextCommand(); + addReply.service_context = service_context; + addReply.replace = replace; + + if( addReplyServiceContextQueue == null ) { + addReplyServiceContextQueue = + new ArrayList(); + } + + // REVISIT: this does not add to the cache. + enqueue( addReply ); + } + + // NOTE: When adding a method, be sure to: + // 1. Add a MID_* constant for that method + // 2. Call checkAccess at the start of the method + // 3. Define entries in the validCall[][] table for interception points. + + /* + ********************************************************************** + * Public RequestInfo interfaces + * + * These are implemented here because they have differing + * implementations depending on whether this is a client or a server + * request info object. + **********************************************************************/ + + /** + * See ServerRequestInfo for javadocs. + */ + public int request_id (){ + // access is currently valid for all states: + //checkAccess( MID_REQUEST_ID ); + /* + * NOTE: The request id in server interceptors is NOT the + * same as the GIOP request id. The ORB may be servicing several + * connections, each with possibly overlapping sets of request ids. + * Therefore we create a request id specific to interceptors. + */ + return serverRequestId; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public String operation(){ + // access is currently valid for all states: + //checkAccess( MID_OPERATION ); + return request.getOperationName(); + } + + public String toString() { + return "ServerRequestInfoImpl[operation=" + + operation() + "]" ; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public Parameter[] arguments (){ + checkAccess( MID_ARGUMENTS ); + + if( cachedArguments == null ) { + if( !isDynamic ) { + throw stdWrapper.piOperationNotSupported1() ; + } + + if( dsiArguments == null ) { + throw stdWrapper.piOperationNotSupported8() ; + } + + // If it is a DSI request then get the arguments from the DSI req + // and convert that into parameters. + cachedArguments = nvListToParameterArray( dsiArguments ); + } + + // Good citizen: In the interest of efficiency, we assume + // interceptors will be "good citizens" in that they will not + // modify the contents of the Parameter[] array. We also assume + // they will not change the values of the containing Anys. + + return cachedArguments.clone() ; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public TypeCode[] exceptions (){ + checkAccess( MID_EXCEPTIONS ); + + // _REVISIT_ PI RTF Issue: No exception list on server side. + + throw stdWrapper.piOperationNotSupported2() ; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public String[] contexts (){ + checkAccess( MID_CONTEXTS ); + + // We do not support this because our ORB does not send contexts. + + throw stdWrapper.piOperationNotSupported3() ; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public String[] operation_context (){ + checkAccess( MID_OPERATION_CONTEXT ); + + // We do not support this because our ORB does not send + // operation_context. + + throw stdWrapper.piOperationNotSupported4() ; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public Any result (){ + checkAccess( MID_RESULT ); + + if( !isDynamic ) { + throw stdWrapper.piOperationNotSupported5() ; + } + + if( dsiResult == null ) { + throw wrapper.piDsiResultIsNull() ; + } + + // Good citizen: In the interest of efficiency, we assume that + // interceptors will not modify the contents of the result Any. + // Otherwise, we would need to create a deep copy of the Any. + + return dsiResult; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public boolean response_expected (){ + // access is currently valid for all states: + //checkAccess( MID_RESPONSE_EXPECTED ); + return !request.isOneWay(); + } + + /** + * See ServerRequestInfo for javadocs. + */ + public Object forward_reference (){ + checkAccess( MID_FORWARD_REFERENCE ); + // Check to make sure we are in LOCATION_FORWARD + // state as per ptc/00-08-06, table 21-2 + // footnote 2. + if( replyStatus != LOCATION_FORWARD.value ) { + throw stdWrapper.invalidPiCall1() ; + } + + return getForwardRequestException().forward; + } + + /** + * See ServerRequestInfo for javadocs. + */ + public org.omg.IOP.ServiceContext get_request_service_context( int id ) { + checkAccess( MID_GET_REQUEST_SERVICE_CONTEXT ); + + if( cachedRequestServiceContexts == null ) { + cachedRequestServiceContexts = + new HashMap(); + } + + return getServiceContext( cachedRequestServiceContexts, + request.getRequestServiceContexts(), id ); + } + + /** + * See ServerRequestInfo for javadocs. + */ + public org.omg.IOP.ServiceContext get_reply_service_context( int id ) { + checkAccess( MID_GET_REPLY_SERVICE_CONTEXT ); + + if( cachedReplyServiceContexts == null ) { + cachedReplyServiceContexts = + new HashMap(); + } + + return getServiceContext( cachedReplyServiceContexts, + replyMessage.getServiceContexts(), id ); + } + + public boolean isNameService() { + return objectAdapter.isNameService() ; + } + + /* + ********************************************************************** + * Private-scope classes and methods + **********************************************************************/ + + // A command encapsulating a request to add a reply service context. + // These commands are enqueued until we have a handle on the actual + // reply service context, at which point they are executed. + private static class AddReplyServiceContextCommand { + ServiceContext service_context; + boolean replace; + } + + // Adds the given add reply service context command to the queue of + // such commands. If a command is detected to have the same id as + // the service context in this command, and replace is false, + // BAD_INV_ORDER is thrown. If replace is true, the original command + // in the queue is replaced by this command. + private void enqueue( AddReplyServiceContextCommand addReply ) { + int size = addReplyServiceContextQueue.size(); + boolean found = false; + + for( int i = 0; i < size; i++ ) { + AddReplyServiceContextCommand cmd = + addReplyServiceContextQueue.get( i ); + + if( cmd.service_context.context_id == + addReply.service_context.context_id ) + { + found = true; + if( addReply.replace ) { + addReplyServiceContextQueue.set( i, addReply ); + } else { + throw stdWrapper.serviceContextAddFailed( + cmd.service_context.context_id ) ; + } + break; + } + } + + if( !found ) { + addReplyServiceContextQueue.add( addReply ); + } + } + + /* + ********************************************************************** + * Package and protected-scope methods + **********************************************************************/ + + /** + * Overridden from RequestInfoImpl. This version calls the super + * and then, if we are changing to ending points, executes all + * enqueued AddReplyServiceContextCommands. + */ + protected void setCurrentExecutionPoint( int executionPoint ) { + super.setCurrentExecutionPoint( executionPoint ); + + // If we are transitioning to ending point, we will now have a pointer + // to the reply service contexts, so we can execute all queued + // add reply service context requests. + if( (executionPoint == EXECUTION_POINT_ENDING) && + (addReplyServiceContextQueue != null) ) + { + int size = addReplyServiceContextQueue.size(); + for( int i = 0; i < size; i++ ) { + AddReplyServiceContextCommand addReply = + addReplyServiceContextQueue.get( i ); + try { + add_reply_service_context( addReply.service_context, + addReply.replace ); + } + catch( BAD_INV_ORDER e ) { + // _REVISIT_ The only way this can happen is if during + // rrsc or rr, the interceptor tried to add with + // replace=false to a service context that is present in + // the reply message. At that time there was no way for + // us to check for this, so the best we can do is ignore + // the original request. + } + } + + // We specifically do not empty the SC queue so that if + // the interceptor raises an exception the queued service contexts + // will be put in the exception response. + } + } + + /** + * Stores the various sources of information used for this info object. + */ + protected synchronized void setInfo( MessageMediator request, ObjectAdapter oa, + byte[] objectId, ObjectKeyTemplate oktemp ) + { + this.request = request; + this.objectId = objectId; + this.oktemp = oktemp; + this.objectAdapter = oa ; + this.connection = (com.sun.corba.ee.spi.legacy.connection.Connection) + request.getConnection(); + } + + /** + * Stores the various sources of information used for this info object. + */ + protected void setDSIArguments( NVList arguments ) { + this.dsiArguments = arguments; + } + + /** + * Stores the various sources of information used for this info object. + */ + protected void setDSIException( Any exception ) { + this.dsiException = exception; + + // Clear cached exception value: + cachedSendingException = null; + } + + /** + * Stores the various sources of information used for this info object. + */ + protected void setDSIResult( Any result ) { + this.dsiResult = result; + } + + /** + * Sets the exception to be returned by received_exception and + * received_exception_id. + */ + protected void setException( Exception exception ) { + super.setException( exception ); + + // Make sure DSIException is null because this is the more recent one. + this.dsiException = null; + + // Clear cached exception value: + cachedSendingException = null; + } + + /** + * Stores the various sources of information used for this info object. + */ + protected void setInfo( java.lang.Object servant, + String targetMostDerivedInterface ) + { + this.servant = servant; + this.targetMostDerivedInterface = targetMostDerivedInterface; + this.isDynamic = + (servant instanceof + org.omg.PortableServer.DynamicImplementation) || + (servant instanceof org.omg.CORBA.DynamicImplementation); + } + + /** + * Set reply message + */ + void setReplyMessage( ReplyMessage replyMessage ) { + this.replyMessage = replyMessage; + } + + /** + * Overridden from RequestInfoImpl. Calls the super class, then + * sets the ending point call depending on the reply status. + */ + protected void setReplyStatus( short replyStatus ) { + super.setReplyStatus( replyStatus ); + switch( replyStatus ) { + case SUCCESSFUL.value: + endingPointCall = CALL_SEND_REPLY; + break; + case SYSTEM_EXCEPTION.value: + case USER_EXCEPTION.value: + endingPointCall = CALL_SEND_EXCEPTION; + break; + case LOCATION_FORWARD.value: + case TRANSPORT_RETRY.value: + endingPointCall = CALL_SEND_OTHER; + break; + } + } + + /** + * Release the servant object so the user has control over its lifetime. + * Called after receive_request is finished executing. + */ + void releaseServant() { + this.servant = null; + } + + /** + * Sets the forwardRequestRaisedInEnding flag to true, indicating that + * a server ending point has raised location forward at some point. + */ + void setForwardRequestRaisedInEnding() { + this.forwardRequestRaisedInEnding = true; + } + + /** + * Returns true if ForwardRequest was raised by a server ending point + * or false otherwise. + */ + boolean isForwardRequestRaisedInEnding() { + return this.forwardRequestRaisedInEnding; + } + + /** + * Returns true if this is a dynamic invocation, or false if not + */ + boolean isDynamic() { + return this.isDynamic; + } + + /** + * See description for RequestInfoImpl.checkAccess + */ + protected void checkAccess( int methodID ) + { + // Make sure currentPoint matches the appropriate index in the + // validCall table: + int validCallIndex = 0; + switch( currentExecutionPoint ) { + case EXECUTION_POINT_STARTING: + validCallIndex = 0; + break; + case EXECUTION_POINT_INTERMEDIATE: + validCallIndex = 1; + break; + case EXECUTION_POINT_ENDING: + switch( endingPointCall ) { + case CALL_SEND_REPLY: + validCallIndex = 2; + break; + case CALL_SEND_EXCEPTION: + validCallIndex = 3; + break; + case CALL_SEND_OTHER: + validCallIndex = 4; + break; + } + break; + } + + // Check the validCall table: + if( !validCall[methodID][validCallIndex] ) { + throw stdWrapper.invalidPiCall2() ; + } + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/SlotTable.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/SlotTable.java new file mode 100644 index 000000000..056199e00 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/SlotTable.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.spi.orb.ORB; +import org.omg.PortableInterceptor.Current; +import org.omg.PortableInterceptor.InvalidSlot; +import org.omg.CORBA.Any; + +/** + * SlotTable is used internally by PICurrent to store the slot information. + */ +public class SlotTable { + // The vector where all the slot data for the current thread is stored + private Any[] theSlotData; + + // Required for instantiating Any object. + private ORB orb; + + // The flag to check whether there are any updates in the current SlotTable. + // The slots will be reset to null, only if this flag is set. + private boolean dirtyFlag; + + /** + * The constructor instantiates an Array of Any[] of size given by slotSize + * parameter. + */ + SlotTable( ORB orb, int slotSize ) { + dirtyFlag = false; + this.orb = orb; + theSlotData = new Any[slotSize]; + } + + /** + * This method sets the slot data at the given slot id (index). + */ + public void set_slot( int id, Any data ) throws InvalidSlot + { + // First check whether the slot is allocated + // If not, raise the invalid slot exception + if( id >= theSlotData.length ) { + throw new InvalidSlot(); + } + dirtyFlag = true; + theSlotData[id] = data; + } + + /** + * This method get the slot data for the given slot id (index). + */ + public Any get_slot( int id ) throws InvalidSlot + { + // First check whether the slot is allocated + // If not, raise the invalid slot exception + if( id >= theSlotData.length ) { + throw new InvalidSlot(); + } + if( theSlotData[id] == null ) { + theSlotData [id] = new AnyImpl(orb); + } + return theSlotData[ id ]; + } + + + /** + * This method resets all the slot data to null if dirtyFlag is set. + */ + void resetSlots( ) { + if( dirtyFlag == true ) { + for( int i = 0; i < theSlotData.length; i++ ) { + theSlotData[i] = null; + } + } + } + + /** + * This method returns the size of the allocated slots. + */ + int getSize( ) { + return theSlotData.length; + } + +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/SlotTableStack.java b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/SlotTableStack.java new file mode 100644 index 000000000..8e6accb70 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/interceptors/SlotTableStack.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.interceptors; + +import com.sun.corba.ee.spi.logging.InterceptorsSystemException; + +import com.sun.corba.ee.spi.orb.ORB; + +/** + * SlotTableStack is the container of SlotTable instances for each thread + */ +public class SlotTableStack +{ + private static final InterceptorsSystemException wrapper = + InterceptorsSystemException.self ; + + // Contains all the active SlotTables for each thread. + // The List is made to behave like a stack. + private java.util.List tableContainer; + + // Keeps track of number of PICurrents in the stack. + private int currentIndex; + + // The ORB associated with this slot table stack + private ORB orb; + + private PICurrent current ; + + /** + * Constructs the stack. This stack must always contain at least + * one element so that peek never failes. + */ + SlotTableStack( ORB orb, PICurrent current ) { + this.current = current ; + this.orb = orb; + + currentIndex = 0; + tableContainer = new java.util.ArrayList( ); + pushSlotTable() ; + } + + /** + * pushSlotTable pushes a fresh Slot Table on to the stack by + * creating a new SlotTable and pushing that into the SlotTableStack. + */ + void pushSlotTable( ) { + SlotTable table = new SlotTable( orb, current.getTableSize() ); + + // NOTE: Very important not to always "add" - otherwise a memory leak. + if (currentIndex == tableContainer.size()) { + // Add will cause the table to grow. + tableContainer.add( currentIndex, table ); + } else if (currentIndex > tableContainer.size()) { + throw wrapper.slotTableInvariant( currentIndex, + tableContainer.size() ) ; + } else { + // Set will override unused slots. + tableContainer.set( currentIndex, table ); + } + currentIndex++; + } + + /** + * popSlotTable does the following + * 1: pops the top SlotTable in the SlotTableStack (if there is more than one) + * + * 2: resets the slots in the SlotTable which resets the slotvalues to + * null if there are any previous sets. + */ + void popSlotTable( ) { + if(currentIndex == 1) { + // Do not pop the SlotTable, If there is only one. + // This should not happen, But an extra check for safety. + throw wrapper.cantPopOnlyPicurrent() ; + } + currentIndex--; + SlotTable table = tableContainer.get( currentIndex ); + tableContainer.set( currentIndex, null ); // Do not leak memory. + table.resetSlots( ); + } + + /** + * peekSlotTable gets the top SlotTable from the SlotTableStack without + * popping. + */ + SlotTable peekSlotTable( ) { + SlotTable result = tableContainer.get( currentIndex - 1 ) ; + if (result.getSize() != current.getTableSize()) { + // stale table, so throw it away + result = new SlotTable( orb, current.getTableSize() ) ; + tableContainer.set( currentIndex - 1, result ) ; + } + + return result ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/Exceptions.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/Exceptions.java new file mode 100644 index 000000000..92df3397a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/Exceptions.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import com.sun.corba.ee.spi.logex.stdcorba.StandardLogger; +import java.io.IOException; +import java.io.InvalidClassException; +import java.io.NotSerializableException; +import java.io.StreamCorruptedException; +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +/** Logging and Exception handling for the io package. + * + * @author ken + */ +@ExceptionWrapper( idPrefix="ORBIO" ) +public interface Exceptions { + public Exceptions self = WrapperGenerator.makeWrapper( Exceptions.class, + StandardLogger.self ); + + // Allow 100 exceptions per class + static final int EXCEPTIONS_PER_CLASS = 100 ; + +// IIOPInputStream + static final int IIS_START = 1 ; + + @Message( "No optional data exception constructor available" ) + @Log( id = IIS_START + 0 ) + ExceptionInInitializerError noOptionalDataExceptionConstructor( + @Chain Exception exc ); + + @Message( "Can't create optional data exception") + @Log( id = IIS_START + 1 ) + Error cantCreateOptionalDataException(@Chain Exception ex); + + @Message( "readLine method not supported") + @Log( id = IIS_START + 2 ) + IOException readLineMethodNotSupported(); + + @Message( "registerValidation method not supported") + @Log( id = IIS_START + 3 ) + Error registerValidationNotSupport(); + + @Message( "resolveClass method not supported") + @Log( id = IIS_START + 4 ) + IOException resolveClassNotSupported(); + + @Message( "resolveObject method not supported") + @Log( id = IIS_START + 5 ) + IOException resolveObjectNotSupported(); + + @Message( "IllegalAccessException when invoking readObject") + @Log( id = IIS_START + 6 ) + void illegalAccessInvokingObjectRead(@Chain IllegalAccessException e); + + @Message( "Bad type {0} for primitive field") + @Log( id = IIS_START + 7 ) + InvalidClassException invalidClassForPrimitive(String name); + + @Message( "Unknown call type {0} while reading object field: " + + "possible stream corruption") + @Log( id = IIS_START + 8 ) + StreamCorruptedException unknownCallType(int callType); + + @Message( "Unknown typecode kind {0} while reading object field: " + + "possible stream corruption") + @Log( id = IIS_START + 9 ) + StreamCorruptedException unknownTypecodeKind(int value); + + @Message( "Assigning instance of class {0} to field {1}" ) + @Log( id = IIS_START + 10 ) + ClassCastException couldNotAssignObjectToField( + @Chain IllegalArgumentException exc, String className, + String fieldName ); + + @Message( "Not setting field {0} on class {1}: " + + "likely that class has evolved") + @Log( level=LogLevel.FINE, id = IIS_START + 11 ) + void notSettingField( String fieldName, String className ); + + @Message( "Stream corrupted" ) + @Log( id = IIS_START + 12 ) + StreamCorruptedException streamCorrupted(Throwable t); + + @Log( id= IIS_START + 13 ) + @Message( "Could not unmarshal enum with cls {0}, value {1} using EnumDesc" ) + IOException couldNotUnmarshalEnum( String cls, String value ) ; + +// IIOPOutputStream + int IOS_START = IIS_START + EXCEPTIONS_PER_CLASS ; + + @Message( "method annotateClass not supported" ) + @Log( id = IOS_START + 1 ) + IOException annotateClassNotSupported(); + + @Message( "method replaceObject not supported" ) + @Log( id = IOS_START + 2 ) + IOException replaceObjectNotSupported(); + + @Message( "serialization of ObjectStreamClass not supported" ) + @Log( id = IOS_START + 3 ) + IOException serializationObjectStreamClassNotSupported(); + + @Message( "serialization of ObjectStreamClass not supported" ) + @Log( id = IOS_START + 4 ) + NotSerializableException notSerializable(String name); + + @Message( "Invalid class {0} for writing field" ) + @Log( id = IOS_START + 5 ) + InvalidClassException invalidClassForWrite(String name); + +// InputStreamHook + int ISH_START = IOS_START + EXCEPTIONS_PER_CLASS ; + + @Message( "Default data already read" ) + @Log( id = ISH_START + 1 ) + StreamCorruptedException defaultDataAlreadyRead(); + + @Message( "Default data must be read first" ) + @Log( id = ISH_START + 2 ) + StreamCorruptedException defaultDataMustBeReadFirst(); + + @Message( "Default data not sent or already read" ) + @Log( id = ISH_START + 3 ) + StreamCorruptedException defaultDataNotPresent(); + +// ObjectStreamClass + int OSC_START = ISH_START + EXCEPTIONS_PER_CLASS ; + + @Message( "Default data not sent or already read" ) + @Log( level=LogLevel.FINE, id = OSC_START + 1 ) + void couldNotAccessSerialPersistentFields( @Chain Exception e, + String name); + + @Message( "Field type mismatch in Class {0} for field (name {1}, type {2})" + + "and reflected field (name {3}, type {4})") + @Log( level=LogLevel.FINE, id = OSC_START + 2 ) + void fieldTypeMismatch( String cname, String fldName, + Class fldType, String rfldName, Class rfldType ) ; + + @Message( "Could not find field {1} in class {0}" ) + @Log( level=LogLevel.FINE, id = OSC_START + 3 ) + void noSuchField( @Chain NoSuchFieldException e, String className, + String fieldName ); + + @Message( "Could not hasStaticInitializer method in class {0}" ) + @Log( id = OSC_START + 4 ) + InternalError cantFindHasStaticInitializer(String cname); + + @Message( "Could not invoke hasStaticInitializer method" ) + @Log( id = OSC_START + 5 ) + InternalError errorInvokingHasStaticInitializer(@Chain Exception ex); + +// OutputStreamHook + int OSH_START = OSC_START + EXCEPTIONS_PER_CLASS ; + + @Message( "Call writeObject twice" ) + @Log( id = OSH_START + 1 ) + IOException calledWriteObjectTwice(); + + @Message( "Call defaultWriteObject or writeFields twice" ) + @Log( id = OSH_START + 2 ) + IOException calledDefaultWriteObjectTwice(); + + @Message( "Cannot call defaultWriteObject or writeFields after " + + "writing custom data") + @Log( id = OSH_START + 3 ) + IOException defaultWriteObjectAfterCustomData(); + +// ValueHandleImpl + int VHI_START = OSH_START + EXCEPTIONS_PER_CLASS ; + + @Message( "Invalid primitive type {0}") + @Log( id = VHI_START + 1 ) + Error invalidPrimitiveType(String name); + + @Message( "Invalid primitive component type {0}") + @Log( id = VHI_START + 2 ) + Error invalidPrimitiveComponentType(String name); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/FVDCodeBaseImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/FVDCodeBaseImpl.java new file mode 100644 index 000000000..89c899f9a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/FVDCodeBaseImpl.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import org.omg.CORBA.ORB; + +import javax.rmi.CORBA.ValueHandler; + +import java.util.Map; +import java.util.HashMap; +import java.util.Stack; + +import com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription; + +import com.sun.org.omg.SendingContext._CodeBaseImplBase; + +import com.sun.corba.ee.spi.logging.OMGSystemException; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +/** + * This class acts as the remote interface to receivers wishing to retrieve + * the information of a remote Class. + */ +public class FVDCodeBaseImpl extends _CodeBaseImplBase +{ + // Contains rep. ids as keys to FullValueDescriptions + private static Map fvds = + new HashMap(); + + // Private ORBSingleton used when we need an ORB while not + // having a delegate set. + private transient ORB orb = null; + + private static final OMGSystemException wrapper = + OMGSystemException.self ; + + // backward compatability so that appropriate rep-id calculations + // can take place + // this needs to be transient to prevent serialization during + // marshalling/unmarshalling + private transient ValueHandlerImpl vhandler = null; + + public FVDCodeBaseImpl( ValueHandler vh ) { + // vhandler will never be null + this.vhandler = (com.sun.corba.ee.impl.io.ValueHandlerImpl)vh ; + } + + // Operation to obtain the IR from the sending context + public com.sun.org.omg.CORBA.Repository get_ir (){ + return null; + } + + // Operations to obtain a URL to the implementation code + public String implementation (String x){ + try{ + // Util.getCodebase may return null which would + // cause a BAD_PARAM exception. + String result = Util.getInstance().getCodebase( + vhandler.getClassFromType(x)); + if (result == null) { + return ""; + } else { + return result; + } + } catch(ClassNotFoundException cnfe){ + throw wrapper.missingLocalValueImpl( cnfe ) ; + } + } + + public String[] implementations (String[] x){ + String result[] = new String[x.length]; + + for (int i = 0; i < x.length; i++) { + result[i] = implementation(x[i]); + } + + return result; + } + + // the same information + public FullValueDescription meta (String x){ + try{ + FullValueDescription result = fvds.get(x); + + if (result == null) { + try{ + result = ValueUtility.translate(_orb(), + ObjectStreamClass.lookup(vhandler.getAnyClassFromType(x)), vhandler); + } catch(Throwable t){ + if (orb == null) { + orb = ORB.init(); + } + + result = ValueUtility.translate(orb, + ObjectStreamClass.lookup(vhandler.getAnyClassFromType(x)), vhandler); + } + + if (result != null){ + fvds.put(x, result); + } else { + throw wrapper.missingLocalValueImpl(); + } + } + + return result; + } catch(Throwable t){ + throw wrapper.incompatibleValueImpl(t); + } + } + + public FullValueDescription[] metas (String[] x){ + FullValueDescription descriptions[] = new FullValueDescription[x.length]; + + for (int i = 0; i < x.length; i++) { + descriptions[i] = meta(x[i]); + } + + return descriptions; + } + + // information + public String[] bases (String x){ + try { + Stack repIds = new Stack(); + Class parent = ObjectStreamClass.lookup( + vhandler.getClassFromType(x)).forClass().getSuperclass(); + + while (!parent.equals(java.lang.Object.class)) { + repIds.push(vhandler.createForAnyType(parent)); + parent = parent.getSuperclass(); + } + + String result[] = new String[repIds.size()]; + for (int i = result.length - 1; i >= 0; i++) { + result[i] = repIds.pop(); + } + + return result; + } catch (Throwable t) { + throw wrapper.missingLocalValueImpl( t ); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/IIOPInputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/IIOPInputStream.java new file mode 100644 index 000000000..6ebf03846 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/IIOPInputStream.java @@ -0,0 +1,2930 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; +import com.sun.corba.ee.impl.misc.ClassInfoCache; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.trace.ValueHandlerRead; +import com.sun.org.omg.CORBA.AttributeDescription; +import com.sun.org.omg.CORBA.ExceptionDescription; +import com.sun.org.omg.CORBA.OperationDescription; +import com.sun.org.omg.CORBA.ParameterDescription; +import com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription; +import com.sun.org.omg.SendingContext.CodeBase; +import org.glassfish.pfl.basic.logex.OperationTracer; +import org.glassfish.pfl.basic.reflection.Bridge; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.ValueMember; +import org.omg.CORBA.portable.IndirectionException; +import org.omg.CORBA.portable.ValueInputStream; + +import javax.rmi.CORBA.ValueHandler; +import java.io.EOFException; +import java.io.Externalizable; +import java.io.IOException; +import java.io.InvalidClassException; +import java.io.InvalidObjectException; +import java.io.NotActiveException; +import java.io.ObjectInputValidation; +import java.io.OptionalDataException; +import java.io.StreamCorruptedException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * IIOPInputStream is used by the ValueHandlerImpl to handle Java serialization + * input semantics. + * + * @author Stephen Lewallen + * @since JDK1.1.6 + */ + +@ValueHandlerRead +public class IIOPInputStream + extends com.sun.corba.ee.impl.io.InputStreamHook +{ + private static Bridge bridge = AccessController.doPrivileged( + new PrivilegedAction() { + public Bridge run() { + return Bridge.get() ; + } + } + ) ; + + // Necessary to pass the appropriate fields into the + // defaultReadObjectDelegate method (which takes no + // parameters since it's called from + // java.io.ObjectInpuStream defaultReadObject() + // which we can't change). + // + // This is only used in the case where the fields had + // to be obtained remotely because of a serializable + // version difference. Set in inputObjectUsingFVD. + // Part of serialization evolution fixes for Ladybird, + // bug 4365188. + private ValueMember defaultReadObjectFVDMembers[] = null; + + private org.omg.CORBA_2_3.portable.InputStream orbStream; + + private CodeBase cbSender; + + private ValueHandlerImpl vhandler; //d4365188 + + private Object currentObject = null; + + private ObjectStreamClass currentClassDesc = null; + + private Class currentClass = null; + + private int recursionDepth = 0; + + private int simpleReadDepth = 0; + + // The ActiveRecursionManager replaces the old RecursionManager which + // used to record how many recursions were made, and resolve them after + // an object was completely deserialized. + // + // That created problems (as in bug 4414154) because when custom + // unmarshaling in readObject, there can be recursive references + // to one of the objects currently being unmarshaled, and the + // passive recursion system failed. + ActiveRecursionManager activeRecursionMgr = new ActiveRecursionManager(); + + private IOException abortIOException = null; + + /* Remember the first exception that stopped this stream. */ + private ClassNotFoundException abortClassNotFoundException = null; + + /* List of validation callback objects + * The vector is created as needed. The vector is maintained in + * order of highest (first) priority to lowest + */ + private List callbacks; + + // Serialization machinery fields + /* Arrays used to keep track of classes and ObjectStreamClasses + * as they are being merged; used in inputObject. + * spClass is the stack pointer for both. */ + ObjectStreamClass[] classdesc; + Class[] classes; + int spClass; + // MS: MarkStack> cstack ; + + private static final String kEmptyStr = ""; + + public static final TypeCode kRemoteTypeCode = + ORB.init().get_primitive_tc(TCKind.tk_objref); + public static final TypeCode kValueTypeCode = + ORB.init().get_primitive_tc(TCKind.tk_value); + + // TESTING CODE - useFVDOnly should be made final before FCS in order to + // optimize out the check. + private static final boolean useFVDOnly = false; + + private byte streamFormatVersion; + + // Return the stream format version currently being used + // to deserialize an object + protected byte getStreamFormatVersion() { + return streamFormatVersion; + } + + @InfoMethod + private void streamFormatVersionInfo( byte sfv ) { } + + // At the beginning of data sent by a writeObject or + // writeExternal method there is a byte telling the + // reader the stream format version. + @ValueHandlerRead + private void readFormatVersion() throws IOException { + streamFormatVersion = orbStream.read_octet(); + streamFormatVersionInfo( streamFormatVersion ) ; + + if (streamFormatVersion < 1 || + streamFormatVersion > vhandler.getMaximumStreamFormatVersion()) { + SystemException sysex = omgWrapper.unsupportedFormatVersion(); + throw new IOException("Unsupported format version: " + + streamFormatVersion, sysex) ; + } + + if (streamFormatVersion == 2) { + if (!(orbStream instanceof ValueInputStream)) { + SystemException sysex = omgWrapper.notAValueinputstream() ; + + throw new IOException("Not a ValueInputStream", sysex); + } + } + } + + public static void setTestFVDFlag(boolean val){ + // useFVDOnly = val; + } + + /** + * Dummy constructor; passes upper stream a dummy stream; + **/ + public IIOPInputStream() + throws java.io.IOException { + super(); + resetStream(); + } + + final void setOrbStream(org.omg.CORBA_2_3.portable.InputStream os) { + orbStream = os; + } + + final org.omg.CORBA_2_3.portable.InputStream getOrbStream() { + return orbStream; + } + + //added setSender and getSender + public final void setSender(CodeBase cb) { + cbSender = cb; + } + + public final CodeBase getSender() { + return cbSender; + } + + // 4365188 this is added to enable backward compatability w/ wrong + // rep-ids + public final void setValueHandler(ValueHandler vh) { + vhandler = (com.sun.corba.ee.impl.io.ValueHandlerImpl) vh; + } + + public final ValueHandler getValueHandler() { + return (javax.rmi.CORBA.ValueHandler) vhandler; + } + + @InfoMethod + private void recursionDepthInfo( int rd ) {} + + @ValueHandlerRead + final void increaseRecursionDepth(){ + recursionDepth++; + recursionDepthInfo(recursionDepth); + } + + @ValueHandlerRead + final int decreaseRecursionDepth(){ + --recursionDepth; + recursionDepthInfo(recursionDepth); + return recursionDepth ; + } + + /** + * Override the actions of the final method "readObject()" + * in ObjectInputStream. + * @since JDK1.1.6 + * + * Read an object from the ObjectInputStream. + * The class of the object, the signature of the class, and the values + * of the non-transient and non-static fields of the class and all + * of its supertypes are read. Default deserializing for a class can be + * overriden using the writeObject and readObject methods. + * Objects referenced by this object are read transitively so + * that a complete equivalent graph of objects is reconstructed by readObject.

    + * + * The root object is completly restored when all of its fields + * and the objects it references are completely restored. At this + * point the object validation callbacks are executed in order + * based on their registered priorities. The callbacks are + * registered by objects (in the readObject special methods) + * as they are individually restored. + * + * Exceptions are thrown for problems with the InputStream and for classes + * that should not be deserialized. All exceptions are fatal to the + * InputStream and leave it in an indeterminate state; it is up to the caller + * to ignore or recover the stream state. + * @exception java.lang.ClassNotFoundException Class of a serialized object + * cannot be found. + * @exception InvalidClassException Something is wrong with a class used by + * serialization. + * @exception StreamCorruptedException Control information in the + * stream is inconsistent. + * @exception OptionalDataException Primitive data was found in the + * stream instead of objects. + * @exception IOException Any of the usual Input/Output related exceptions. + * @since JDK1.1 + */ + @ValueHandlerRead + public final synchronized Object readObjectDelegate() throws IOException + { + try { + readObjectState.readData(this); + + return orbStream.read_abstract_interface(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, true); + throw marshalException; + } catch(IndirectionException cdrie) { + // The CDR stream had never seen the given offset before, + // so check the recursion manager (it will throw an + // IOException if it doesn't have a reference, either). + return activeRecursionMgr.getObject(cdrie.offset); + } + } + + @ValueHandlerRead + final synchronized Object simpleReadObject(Class clz, ClassInfoCache.ClassInfo cinfo, + String repositoryID, com.sun.org.omg.SendingContext.CodeBase sender, + int offset) { + /* Save the current state and get ready to read an object. */ + Object prevObject = currentObject; + ObjectStreamClass prevClassDesc = currentClassDesc; + Class prevClass = currentClass; + byte oldStreamFormatVersion = streamFormatVersion; + + simpleReadDepth++; // Entering + Object obj = null; + + OperationTracer.startReadValue( clz.getName() ) ; + + /* + * Check for reset, handle it before reading an object. + */ + try { + if (vhandler.useFullValueDescription(clz, repositoryID)) { + obj = inputObjectUsingFVD(clz, cinfo, repositoryID, sender, offset); + } else { + obj = inputObject(clz, cinfo, repositoryID, sender, offset); + } + + obj = currentClassDesc.readResolve(obj); + } catch(ClassNotFoundException cnfe) { + bridge.throwException( cnfe ) ; + return null; + } catch(IOException ioe) { + // System.out.println("CLZ = " + clz + "; " + ioe.toString()); + bridge.throwException(ioe) ; + return null; + } finally { + simpleReadDepth --; + currentObject = prevObject; + currentClassDesc = prevClassDesc; + currentClass = prevClass; + streamFormatVersion = oldStreamFormatVersion; + OperationTracer.endReadValue() ; + } + + /* Check for thrown exceptions and re-throw them, clearing them if + * this is the last recursive call . + */ + IOException exIOE = abortIOException; + if (simpleReadDepth == 0) { + abortIOException = null; + } + if (exIOE != null){ + bridge.throwException( exIOE ) ; + return null; + } + + + ClassNotFoundException exCNF = abortClassNotFoundException; + if (simpleReadDepth == 0) { + abortClassNotFoundException = null; + } + if (exCNF != null) { + bridge.throwException( exCNF ) ; + return null; + } + + return obj; + } + + @ValueHandlerRead + public final synchronized void simpleSkipObject( String repositoryID, + com.sun.org.omg.SendingContext.CodeBase sender) + { + /* Save the current state and get ready to read an object. */ + Object prevObject = currentObject; + ObjectStreamClass prevClassDesc = currentClassDesc; + Class prevClass = currentClass; + byte oldStreamFormatVersion = streamFormatVersion; + + simpleReadDepth++; // Entering + Object obj = null; + + /* + * Check for reset, handle it before reading an object. + */ + try { + skipObjectUsingFVD(repositoryID, sender); + } catch(ClassNotFoundException cnfe) { + bridge.throwException( cnfe ) ; + return; + } catch(IOException ioe) { + bridge.throwException( ioe ) ; + return; + } finally { + simpleReadDepth --; + streamFormatVersion = oldStreamFormatVersion; + currentObject = prevObject; + currentClassDesc = prevClassDesc; + currentClass = prevClass; + } + + + /* Check for thrown exceptions and re-throw them, clearing them if + * this is the last recursive call . + */ + IOException exIOE = abortIOException; + if (simpleReadDepth == 0) { + abortIOException = null; + } + if (exIOE != null){ + bridge.throwException( exIOE ) ; + return; + } + + + ClassNotFoundException exCNF = abortClassNotFoundException; + if (simpleReadDepth == 0) { + abortClassNotFoundException = null; + } + if (exCNF != null) { + bridge.throwException( exCNF ) ; + return; + } + + return; + } + + /** + * This method is called by trusted subclasses of ObjectOutputStream + * that constructed ObjectOutputStream using the + * protected no-arg constructor. The subclass is expected to provide + * an override method with the modifier "final". + * + * @return the Object read from the stream. + * + * @see #readObject + * @since JDK 1.2 + */ + @Override + protected final Object readObjectOverride() + throws OptionalDataException, ClassNotFoundException, IOException + { + return readObjectDelegate(); + } + + @InfoMethod + private void usingLocalFieldsToRead() { } + + /** + * Override the actions of the final method "defaultReadObject()" + * in ObjectInputStream. + * @since JDK1.1.6 + * + * Read the non-static and non-transient fields of the current class + * from this stream. This may only be called from the readObject method + * of the class being deserialized. It will throw the NotActiveException + * if it is called otherwise. + * + * @exception java.lang.ClassNotFoundException if the class of a serialized + * object could not be found. + * @exception IOException if an I/O error occurs. + * @exception NotActiveException if the stream is not currently reading + * objects. + * @since JDK1.1 + */ + @ValueHandlerRead + public final synchronized void defaultReadObjectDelegate() { + try { + if (currentObject == null || currentClassDesc == null) { + throw new NotActiveException("defaultReadObjectDelegate"); + } + + if (!currentClassDesc.forClass().isAssignableFrom( + currentObject.getClass())) { + throw new IOException("Object Type mismatch"); + } + + if (defaultReadObjectFVDMembers != null && defaultReadObjectFVDMembers.length > 0) { + // Clear this here so that a recursion back to another + // defaultReadObjectDelegate call from inputClassFields + // does NOT pick up inapplicable defaultReadObjectFVDMembers + // (see bug 6614558). + ValueMember[] valueMembers = defaultReadObjectFVDMembers ; + defaultReadObjectFVDMembers = null ; + + displayValueMembers( valueMembers ) ; + + inputClassFields(currentObject, + currentClass, + currentClassDesc, + valueMembers, + cbSender); + } else { + usingLocalFieldsToRead() ; + + // Use the local fields to unmarshal. + ObjectStreamField[] fields = + currentClassDesc.getFieldsNoCopy(); + if (fields.length > 0) { + inputClassFields(currentObject, currentClass, fields, cbSender); + } + } + } catch(NotActiveException nae) { + bridge.throwException( nae ) ; + } catch(IOException ioe) { + bridge.throwException( ioe ) ; + } catch(ClassNotFoundException cnfe) { + bridge.throwException( cnfe ) ; + } + } + + /** + * Override the actions of the final method "enableResolveObject()" + * in ObjectInputStream. + * @since JDK1.1.6 + * + * Enable the stream to allow objects read from the stream to be replaced. + * If the stream is a trusted class it is allowed to enable replacment. + * Trusted classes are those classes with a classLoader equals null.

    + * + * When enabled the resolveObject method is called for every object + * being deserialized. + * + * @exception SecurityException The classloader of this stream object is non-null. + * @since JDK1.1 + */ + public final boolean enableResolveObjectDelegate(boolean enable) + /* throws SecurityException */ + { + return false; + } + + // The following three methods allow the implementing orbStream + // to provide mark/reset behavior as defined in java.io.InputStream. + + @Override + public final void mark(int readAheadLimit) { + orbStream.mark(readAheadLimit); + } + + @Override + public final boolean markSupported() { + return orbStream.markSupported(); + } + + @Override + public final void reset() throws IOException { + try { + orbStream.reset(); + } catch (Error e) { + throw new IOException(e) ; + } + } + + @Override + public final int available() throws IOException{ + return 0; // unreliable + } + + @Override + public final void close() throws IOException{ + // no op + } + + @ValueHandlerRead + @Override + public final int read() throws IOException{ + try{ + readObjectState.readData(this); + + return (orbStream.read_octet()) & 0x000000FF; + } catch (MARSHAL marshalException) { + if (marshalException.minor + == OMGSystemException.RMIIIOP_OPTIONAL_DATA_INCOMPATIBLE) { + setState(IN_READ_OBJECT_NO_MORE_OPT_DATA); + return -1; + } + + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final int read(byte data[], int offset, int length) throws IOException{ + try{ + readObjectState.readData(this); + + orbStream.read_octet_array(data, offset, length); + return length; + } catch (MARSHAL marshalException) { + if (marshalException.minor + == OMGSystemException.RMIIIOP_OPTIONAL_DATA_INCOMPATIBLE) { + setState(IN_READ_OBJECT_NO_MORE_OPT_DATA); + return -1; + } + + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + + } + + @ValueHandlerRead + @Override + public final boolean readBoolean() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_boolean(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final byte readByte() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_octet(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final char readChar() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_wchar(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final double readDouble() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_double(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final float readFloat() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_float(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final void readFully(byte data[]) throws IOException{ +// d11623 : implement readFully, required for serializing some core classes + + readFully(data, 0, data.length); + } + + @ValueHandlerRead + @Override + public final void readFully(byte data[], int offset, int size) throws IOException{ +// d11623 : implement readFully, required for serializing some core classes + try{ + readObjectState.readData(this); + + orbStream.read_octet_array(data, offset, size); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final int readInt() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_long(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @Override + @SuppressWarnings("deprecation") + public final String readLine() throws IOException{ + throw Exceptions.self.readLineMethodNotSupported() ; + } + + @ValueHandlerRead + @Override + public final long readLong() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_longlong(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final short readShort() throws IOException{ + try{ + readObjectState.readData(this); + + return orbStream.read_short(); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @Override + protected final void readStreamHeader() throws IOException, StreamCorruptedException{ + // no op + } + + @ValueHandlerRead + @Override + public final int readUnsignedByte() throws IOException{ + try{ + readObjectState.readData(this); + + return (orbStream.read_octet()) & 0x000000FF; + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + @Override + public final int readUnsignedShort() throws IOException{ + try{ + readObjectState.readData(this); + + return (orbStream.read_ushort()) & 0x0000FFFF; + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + /** + * Helper method for correcting the Kestrel bug 4367783 (dealing + * with larger than 8-bit chars). The old behavior was preserved + * in orbutil.IIOPInputStream_1_3 in order to interoperate with + * our legacy ORBs. + */ + @ValueHandlerRead + protected String internalReadUTF(org.omg.CORBA.portable.InputStream stream) + { + return stream.read_wstring(); + } + + @ValueHandlerRead + @Override + public final String readUTF() throws IOException{ + try{ + readObjectState.readData(this); + + return internalReadUTF(orbStream); + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + // If the ORB stream detects an incompatibility between what's + // on the wire and what our Serializable's readObject wants, + // it throws a MARSHAL exception with a specific minor code. + // This is rethrown to the readObject as an OptionalDataException. + // So far in RMI-IIOP, this process isn't specific enough to + // tell the readObject how much data is available, so we always + // set the OptionalDataException's EOF marker to true. + private void handleOptionalDataMarshalException(MARSHAL marshalException, + boolean objectRead) + throws IOException { + + // Java Object Serialization spec 3.4: "If the readObject method + // of the class attempts to read more data than is present in the + // optional part of the stream for this class, the stream will + // return -1 for bytewise reads, throw an EOFException for + // primitive data reads, or throw an OptionalDataException + // with the eof field set to true for object reads." + if (marshalException.minor + == OMGSystemException.RMIIIOP_OPTIONAL_DATA_INCOMPATIBLE) { + + IOException result; + + if (!objectRead) { + result = new EOFException("No more optional data"); + } else { + result = bridge.newOptionalDataExceptionForSerialization(true); + } + + result.initCause(marshalException); + + setState(IN_READ_OBJECT_NO_MORE_OPT_DATA); + + throw result; + } + } + + @Override + public final synchronized void registerValidation(ObjectInputValidation obj, + int prio) + throws NotActiveException, InvalidObjectException{ + throw Exceptions.self.registerValidationNotSupport() ; + } + + @Override + protected final Class resolveClass(java.io.ObjectStreamClass v) + throws IOException, ClassNotFoundException{ + throw Exceptions.self.resolveClassNotSupported() ; + } + + @Override + protected final Object resolveObject(Object obj) throws IOException{ + throw Exceptions.self.resolveObjectNotSupported() ; + } + + @ValueHandlerRead + @Override + public final int skipBytes(int len) throws IOException{ + try{ + readObjectState.readData(this); + + byte buf[] = new byte[len]; + orbStream.read_octet_array(buf, 0, len); + return len; + } catch (MARSHAL marshalException) { + handleOptionalDataMarshalException(marshalException, false); + + throw marshalException; + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerRead + private Object handleEnum( Class clz, + ClassInfoCache.ClassInfo cinfo ) throws IOException { + + // Only for backwards compatibility with JDK: + // int ordinal = orbStream.read_long() ; + String value = (String)orbStream.read_value( String.class ) ; + + // Issue 11681: find the real enum class. + final Class enumClass = ClassInfoCache.getEnumClass( cinfo, clz ) ; + if (enumClass == null) { + throw Exceptions.self.couldNotUnmarshalEnum( clz.getName(), value ) ; + } else { + // Need to skip any other data marshaled from the enum, + // if the enum type has non-static non-transient state. + return Enum.valueOf( enumClass, value ); + } + } + + @InfoMethod + private void readingExternalizable() { } + + @InfoMethod + private void readingSerializable() { } + + @InfoMethod + private void newInstanceInfo( Class cls ) { } + + @InfoMethod + private void readingDataForClass( Class cls ) { } + + @InfoMethod + private void classHasWriteObject( boolean flag ) { } + + @InfoMethod + private void currentClassInfo( ObjectStreamClass ocs, Class cls ) { } + + @InfoMethod + private void matchingClassInfo( Class cls ) { } + + @ValueHandlerRead + private void callReadExternal( Externalizable ext ) + throws IOException, ClassNotFoundException { + + // KMC issue 5161: just as in the IIOPOutputStream, we must + // save and restore the state for reading as well! + ReadObjectState oldState = readObjectState; + setState(DEFAULT_STATE); + try { + ext.readExternal(this); + } finally { + setState(oldState) ; + } + } + + @ValueHandlerRead + private synchronized Object inputObject(Class clz, ClassInfoCache.ClassInfo cinfo, + String repositoryID, com.sun.org.omg.SendingContext.CodeBase sender, + int offset) throws IOException, ClassNotFoundException { + + int spBase = spClass ; + try { + currentClassDesc = ObjectStreamClass.lookup(clz); + currentClass = currentClassDesc.forClass(); + + // KMC start of enum receiver-makes-right changes + if (cinfo.isEnum()) { + return handleEnum( clz, cinfo ) ; + } else if (currentClassDesc.isExternalizable()) { + readingExternalizable(); + + try { + newInstanceInfo( currentClass ) ; + + currentObject = (currentClass == null) ? + null : currentClassDesc.newInstance(); + + if (currentObject != null) { + // Store this object and its beginning position + // since there might be indirections to it while + // it is being unmarshalled. + activeRecursionMgr.addObject(offset, currentObject); + + // Read format version + readFormatVersion(); + + callReadExternal( (Externalizable)currentObject ) ; + } + } catch (InvocationTargetException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InvocationTargetException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (UnsupportedOperationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "UnsupportedOperationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (InstantiationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InstantiationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } + } else { + readingSerializable(); + + ObjectStreamClass currdesc = currentClassDesc; + Class currclass = currentClass; + + // MS: cstack.mark() ; + spBase = spClass; // current top of stack + + if (currentClass.getName().equals("java.lang.String")) { + return this.readUTF(); + } + for (currdesc = currentClassDesc, currclass = currentClass; + currdesc != null && currdesc.isSerializable(); + currdesc = currdesc.getSuperclass()) { + + Class cc = currdesc.forClass(); + + currentClassInfo(currdesc, cc); + + Class cl; + for (cl = currclass; cl != null; cl = cl.getSuperclass()) { + if (cc == cl) { + matchingClassInfo(cl); + break; + } + } + + // MS: cstack.push( new Pair( cl, currdesc ) ) ; + // if (cl != null) + // currclass = cl.getSuperclass() ; + spClass++; + if (spClass >= classes.length) { + int newlen = classes.length * 2; + Class[] newclasses = new Class[newlen]; + ObjectStreamClass[] newclassdesc = new ObjectStreamClass[newlen]; + + System.arraycopy(classes, 0, newclasses, 0, classes.length); + System.arraycopy(classdesc, 0, newclassdesc, 0, classes.length); + + classes = newclasses; + classdesc = newclassdesc; + } + + if (cl == null) { + classdesc[spClass] = currdesc; + classes[spClass] = null; + } else { + classdesc[spClass] = currdesc; + classes[spClass] = cl; + currclass = cl.getSuperclass(); + } + } // end : for (currdesc = currentClassDesc, currclass = currentClass; + + try { + newInstanceInfo( currentClass ) ; + + currentObject = (currentClass == null) ? + null : currentClassDesc.newInstance() ; + + // Store this object and its beginning position + // since there might be indirections to it while + // it's been unmarshalled. + activeRecursionMgr.addObject(offset, currentObject); + } catch (InvocationTargetException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InvocationTargetException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (UnsupportedOperationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "UnsupportedOperationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (InstantiationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InstantiationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } + + // MS: while (!cstack.isEmpty) + // Pair pair = cstack.pop() ; + for (spClass = spClass; spClass > spBase; spClass--) { + // MS: currentClassDesc = pair.second() ; + // currentClass = pair.first() ; + currentClassDesc = classdesc[spClass]; + currentClass = classes[spClass]; + + readingDataForClass( currentClass ) ; + + // MS: if (currentClass != null) + if (classes[spClass] != null) { + ReadObjectState oldState = readObjectState; + setState(DEFAULT_STATE); + + try { + if (currentClassDesc.hasWriteObject()) { + classHasWriteObject( true ) ; + + readFormatVersion(); + + // Read defaultWriteObject indicator + boolean calledDefaultWriteObject = readBoolean(); + + readObjectState.beginUnmarshalCustomValue( this, + calledDefaultWriteObject, + (currentClassDesc.getReadObjectMethod() != null)); + } else { + classHasWriteObject( false ) ; + + if (currentClassDesc.hasReadObject()) { + setState(IN_READ_OBJECT_REMOTE_NOT_CUSTOM_MARSHALED); + } + } + + if (!invokeObjectReader(currentClassDesc, currentObject, + currentClass, null) || + readObjectState == IN_READ_OBJECT_DEFAULTS_SENT) { + + // Error case of no readObject and didn't call + // defaultWriteObject handled in default state + ObjectStreamField[] fields = + currentClassDesc.getFieldsNoCopy(); + + if (fields.length > 0) { + inputClassFields(currentObject, currentClass, fields, sender); + } + } + + if (currentClassDesc.hasWriteObject()) { + readObjectState.endUnmarshalCustomValue(this); + } + } finally { + setState(oldState); + } + } else { + // _REVISIT_ : Can we ever get here? + /* No local class for this descriptor, + * Skip over the data for this class. + * like defaultReadObject with a null currentObject. + * The code will read the values but discard them. + */ + ObjectStreamField[] fields = + currentClassDesc.getFieldsNoCopy(); + + if (fields.length > 0) { + inputClassFields(null, currentClass, fields, sender); + } + } + } + } + } finally { + // Make sure we exit at the same stack level as when we started. + // MS: cstack.popMark() ; + spClass = spBase; + + // We've completed deserializing this object. Any + // future indirections will be handled correctly at the + // CDR level. The ActiveRecursionManager only deals with + // objects currently being deserialized. + activeRecursionMgr.removeObject(offset); + } + return currentObject; + } + + @InfoMethod + private void fullValueDescriptorsInfo( List fvds ) { } + + // This retrieves a vector of FVD's for the hierarchy of serializable + // classes stemming from repositoryID. It is assumed that the sender + // will not provide base_value id's for non-serializable classes! + @ValueHandlerRead + private List getOrderedDescriptions( + String repositoryID, com.sun.org.omg.SendingContext.CodeBase sender) { + + List descs = + new ArrayList(); + + if (sender == null) { + return descs; + } + + FullValueDescription aFVD = sender.meta(repositoryID); + while (aFVD != null) { + descs.add(0, aFVD); + if ((aFVD.base_value != null) && !kEmptyStr.equals(aFVD.base_value)) { + aFVD = sender.meta(aFVD.base_value); + } else { + return descs; + } + } + + fullValueDescriptorsInfo(descs); + + return descs; + } + + // XXX Do we want to replace this with something integrated with the + // tracing facility? + // Interesting question. The full display of an FVD is likely to be + // valuable for debugging FVD issues (which we haven't had in >10 years), + // but it's too verbose for the dprint MethodMonitor. Possibly some kind + // of extra data display (not inline) might be interesting here: need + // to revisit dprint, and think about how to flag alternate formatting/handling + // of arguments. + private String displayFVD( FullValueDescription fvd ) { + StringBuilder sb = new StringBuilder() ; + sb.append( "FVD(" ) ; + sb.append( "\n\tname=" ) ; + sb.append( fvd.name ) ; + sb.append( "\n\tid=" ) ; + sb.append( fvd.id ) ; + sb.append( "\n\tis_abstract=" ) ; + sb.append( fvd.is_abstract ) ; + sb.append( "\n\tis_custom=" ) ; + sb.append( fvd.is_custom ) ; + sb.append( "\n\tdefined_in=" ) ; + sb.append( fvd.defined_in ) ; + sb.append( "\n\tversion=" ) ; + sb.append( fvd.version ) ; + sb.append( "\n\tis_truncatable=" ) ; + sb.append( fvd.is_truncatable ) ; + sb.append( "\n\tbase_value=" ) ; + sb.append( fvd.base_value ) ; + + int ctr = 0 ; + sb.append( "\n\toperations:" ) ; + for (OperationDescription opdesc : fvd.operations) { + sb.append( "\n\t [" ) ; + sb.append( ctr++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\tname=" ) ; + sb.append( opdesc.name ) ; + sb.append( "\n\t\tid=" ) ; + sb.append( opdesc.id ) ; + sb.append( "\n\t\tdefined_in=" ) ; + sb.append( opdesc.defined_in ) ; + sb.append( "\n\t\tversion=" ) ; + sb.append( opdesc.version ) ; + sb.append( "\n\t\tmode=" ) ; + sb.append( opdesc.mode ) ; + + int ctr2 = 0 ; + sb.append( "\n\t\tcontexts=" ) ; + for (String str : opdesc.contexts) { + sb.append( "\n\t\t [" ) ; + sb.append( ctr2++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\t" ) ; + sb.append( str ) ; + } + + ctr2 = 0 ; + sb.append( "\n\t\tparameters" ) ; + for (ParameterDescription pdesc : opdesc.parameters) { + sb.append( "\n\t\t [" ) ; + sb.append( ctr2++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\t\tname=" ) ; + sb.append( pdesc.name ) ; + sb.append( "\n\t\t\tmode=" ) ; + sb.append( pdesc.mode ) ; + } + + ctr2 = 0 ; + sb.append( "\n\t\texceptions" ) ; + for (ExceptionDescription edesc : opdesc.exceptions) { + sb.append( "\n\t\t [" ) ; + sb.append( ctr2++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\t\tname=" ) ; + sb.append( edesc.name ) ; + sb.append( "\n\t\t\tid=" ) ; + sb.append( edesc.id ) ; + sb.append( "\n\t\t\tdefined_in=" ) ; + sb.append( edesc.defined_in ) ; + sb.append( "\n\t\t\tversion=" ) ; + sb.append( edesc.version ) ; + } + } + + ctr = 0 ; + sb.append( "\n\tattributes:" ) ; + for (AttributeDescription atdesc : fvd.attributes) { + sb.append( "\n\t [" ) ; + sb.append( ctr++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\t\tname=" ) ; + sb.append( atdesc.name ) ; + sb.append( "\n\t\t\tid=" ) ; + sb.append( atdesc.id ) ; + sb.append( "\n\t\t\tdefined_in=" ) ; + sb.append( atdesc.defined_in ) ; + sb.append( "\n\t\t\tversion=" ) ; + sb.append( atdesc.version ) ; + sb.append( "\n\t\t\tmode=" ) ; + sb.append( atdesc.mode ) ; + } + + ctr = 0 ; + sb.append( "\n\tmembers:" ) ; + for (ValueMember vm : fvd.members) { + sb.append( "\n\t [" ) ; + sb.append( ctr++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\tname=" ) ; + sb.append( vm.name ) ; + sb.append( "\n\t\tid=" ) ; + sb.append( vm.id ) ; + sb.append( "\n\t\tdefined_in=" ) ; + sb.append( vm.defined_in ) ; + sb.append( "\n\t\tversion=" ) ; + sb.append( vm.version ) ; + sb.append( "\n\t\taccess=" ) ; + sb.append( vm.access ) ; + } + + // Ignore for now + // for (Initializer init : fvd.initializers) { + // } + + ctr = 0 ; + sb.append( "\n\tsupported_interfaces:" ) ; + for (String str : fvd.supported_interfaces) { + sb.append( "\n\t [" ) ; + sb.append( ctr++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\t" ) ; + sb.append( str ) ; + } + + ctr = 0 ; + sb.append( "\n\tabstract_base_values:" ) ; + for (String str : fvd.abstract_base_values) { + sb.append( "\n\t [" ) ; + sb.append( ctr++ ) ; + sb.append( "]" ) ; + sb.append( "\n\t\t" ) ; + sb.append( str ) ; + } + + sb.append( "\n)" ) ; + return sb.toString() ; + } + + @InfoMethod + private void readingDataUsingFVD( FullValueDescription fvd ) { } + + /** + * This input method uses FullValueDescriptions retrieved from the sender's runtime to + * read in the data. This method is capable of throwing out data not applicable to client's fields. + * This method handles instances where the reader has a class not sent by the sender, the sender sent + * a class not present on the reader, and/or the reader's class does not match the sender's class. + * + * NOTE : If the local description indicates custom marshaling and the remote type's FVD also + * indicates custom marsahling than the local type is used to read the data off the wire. However, + * if either says custom while the other does not, a MARSHAL error is thrown. Externalizable is + * a form of custom marshaling. + * + */ + @ValueHandlerRead + private synchronized Object inputObjectUsingFVD(final Class clz, + final ClassInfoCache.ClassInfo cinfo, + final String repositoryID, + final com.sun.org.omg.SendingContext.CodeBase sender, + final int offset) throws IOException, ClassNotFoundException { + + int spBase = spClass ; + try { + currentClassDesc = ObjectStreamClass.lookup(clz); + currentClass = currentClassDesc.forClass(); + + // KMC start of enum receiver-makes-right changes + if (cinfo.isEnum()) { + return handleEnum( clz, cinfo ) ; + } else if (currentClassDesc.isExternalizable()) { + readingExternalizable(); + + try { + newInstanceInfo( currentClass ) ; + + currentObject = (currentClass == null) ? + null : currentClassDesc.newInstance(); + + if (currentObject != null) { + // Store this object and its beginning position + // since there might be indirections to it while + // it's been unmarshalled. + activeRecursionMgr.addObject(offset, currentObject); + + // Read format version + readFormatVersion(); + + callReadExternal( (Externalizable)currentObject ) ; + } + } catch (InvocationTargetException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InvocationTargetException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (UnsupportedOperationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "UnsupportedOperationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (InstantiationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InstantiationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } + } else { + readingSerializable() ; + + ObjectStreamClass currdesc = currentClassDesc ; + Class currclass = currentClass = clz; + + // MS: cstack.mark() ; + spBase = spClass; // current top of stack + + for (currdesc = currentClassDesc, currclass = currentClass; + currdesc != null && currdesc.isSerializable(); + currdesc = currdesc.getSuperclass()) { + + Class cc = currdesc.forClass(); + + currentClassInfo(currdesc, cc) ; + + Class cl; + for (cl = currclass; cl != null; cl = cl.getSuperclass()) { + if (cc == cl) { + matchingClassInfo(cl); + break; + } + } + + // MS: cstack.push( new Pair( cl, currdesc ) ) ; + // if (cl != null) + // currclass = cl.getSuperclass() ; + spClass++; + if (spClass >= classes.length) { + int newlen = classes.length * 2; + Class[] newclasses = new Class[newlen]; + ObjectStreamClass[] newclassdesc = + new ObjectStreamClass[newlen]; + + System.arraycopy(classes, 0, newclasses, + 0, classes.length); + System.arraycopy(classdesc, 0, newclassdesc, + 0, classes.length); + + classes = newclasses; + classdesc = newclassdesc; + } + + if (cl == null) { + classdesc[spClass] = currdesc; + classes[spClass] = null; + } else { + classdesc[spClass] = currdesc; + classes[spClass] = cl; + currclass = cl.getSuperclass(); + } + } // end : for (currdesc = currentClassDesc, currclass = currentClass; + + try { + newInstanceInfo( currentClass ) ; + currentObject = (currentClass == null) ? + null : currentClassDesc.newInstance(); + + // Store this object and its beginning position + // since there might be indirections to it while + // it's been unmarshalled. + activeRecursionMgr.addObject(offset, currentObject); + } catch (InvocationTargetException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InvocationTargetException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (UnsupportedOperationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "UnsupportedOperationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } catch (InstantiationException e) { + InvalidClassException exc = new InvalidClassException( + currentClass.getName(), + "InstantiationException accessing no-arg constructor"); + exc.initCause( e ) ; + throw exc ; + } + + Iterator fvdsList = + getOrderedDescriptions(repositoryID, sender).iterator(); + + // MS: while (fvdsList.hasNext() && !cstack.isEmpty()) + while((fvdsList.hasNext()) && (spClass > spBase)) { + FullValueDescription fvd = fvdsList.next(); + readingDataUsingFVD(fvd); + + String repIDForFVD = vhandler.getClassName( fvd.id); + String repIDForClass = vhandler.getClassName( + vhandler.getRMIRepositoryID(currentClass)); + + // MS: while (!cstack.isEmpty() && + while ((spClass > spBase) && + (!repIDForFVD.equals(repIDForClass))) { + // MS: while (!cstack.isEmpty() && !cstack.peek().first().getName.equals( repIDForFVD )) + // cstack.pop() ; + int pos = findNextClass(repIDForFVD, classes, spClass, spBase); + // if (!cstack.isEmpty()) + // currClass = currentClass = cstack.peek.first() ; + if (pos != -1) { + spClass = pos; + currclass = currentClass = classes[spClass]; + repIDForClass = vhandler.getClassName( + vhandler.getRMIRepositoryID(currentClass)); + } else { + // Read and throw away one level of the fvdslist + // This seems to mean that the sender had a superclass that + // we don't have + + if (fvd.is_custom) { + readFormatVersion(); + boolean calledDefaultWriteObject = readBoolean(); + + if (calledDefaultWriteObject) { + inputClassFields(null, null, null, + fvd.members, sender); + } + + if (getStreamFormatVersion() == 2) { + ((ValueInputStream)getOrbStream()) + .start_value(); + ((ValueInputStream)getOrbStream()) + .end_value(); + } + + // WARNING: If stream format version is 1 and there's + // optional data, we'll get some form of exception down + // the line or data corruption. + } else { + inputClassFields(null, currentClass, null, fvd.members, sender); + } + + if (fvdsList.hasNext()){ + fvd = fvdsList.next(); + repIDForFVD = vhandler.getClassName(fvd.id); + } else { + return currentObject; + } + } + } + + currdesc = currentClassDesc + = ObjectStreamClass.lookup(currentClass); + + if (!repIDForClass.equals("java.lang.Object")) { + + // If the sender used custom marshaling, then it should have put + // the two bytes on the wire indicating stream format version + // and whether or not the writeObject method called + // defaultWriteObject/writeFields. + + ReadObjectState oldState = readObjectState; + setState(DEFAULT_STATE); + + try { + if (fvd.is_custom) { + readFormatVersion(); + boolean calledDefaultWriteObject = readBoolean(); + readObjectState.beginUnmarshalCustomValue( this, + calledDefaultWriteObject, + (currentClassDesc.getReadObjectMethod() != null)); + } + + boolean usedReadObject = false; + + // Always use readObject if it exists, and fall back to default + // unmarshaling if it doesn't. + if (!fvd.is_custom && currentClassDesc.hasReadObject()) { + setState(IN_READ_OBJECT_REMOTE_NOT_CUSTOM_MARSHALED); + } + + usedReadObject = invokeObjectReader(currentClassDesc, + currentObject, currentClass, fvd.members ); + + // Note that the !usedReadObject !calledDefaultWriteObject + // case is handled by the beginUnmarshalCustomValue method + // of the default state + if (!usedReadObject || readObjectState == IN_READ_OBJECT_DEFAULTS_SENT) { + inputClassFields(currentObject, currentClass, + currdesc, fvd.members, sender); + } + + if (fvd.is_custom) { + readObjectState.endUnmarshalCustomValue(this); + } + } finally { + setState(oldState); + } + + currclass = currentClass = classes[--spClass]; + } else { + // The remaining hierarchy of the local class does not match the sender's FVD. + // So, use remaining FVDs to read data off wire. If any remaining FVDs indicate + // custom marshaling, throw MARSHAL error. + inputClassFields(null, currentClass, null, fvd.members, sender); + + while (fvdsList.hasNext()){ + fvd = fvdsList.next(); + + if (fvd.is_custom) { + skipCustomUsingFVD(fvd.members, sender); + } else { + inputClassFields(null, currentClass, null, + fvd.members, sender); + } + } + } + } // end : while(fvdsList.hasNext()) + + while (fvdsList.hasNext()){ + FullValueDescription fvd = fvdsList.next(); + if (fvd.is_custom) { + skipCustomUsingFVD(fvd.members, sender); + } else { + throwAwayData(fvd.members, sender); + } + } + } + } finally { + // Make sure we exit at the same stack level as when we started. + // MS: cstack.popMark() ; + spClass = spBase; + + // We've completed deserializing this object. Any + // future indirections will be handled correctly at the + // CDR level. The ActiveRecursionManager only deals with + // objects currently being deserialized. + activeRecursionMgr.removeObject(offset); + } + + return currentObject; + } + + /** + * This input method uses FullValueDescriptions retrieved from the sender's runtime to + * read in the data. This method is capable of throwing out data not applicable to client's fields. + * + * NOTE : If the local description indicates custom marshaling and the remote type's FVD also + * indicates custom marsahling than the local type is used to read the data off the wire. However, + * if either says custom while the other does not, a MARSHAL error is thrown. Externalizable is + * a form of custom marshaling. + * + */ + @ValueHandlerRead + private Object skipObjectUsingFVD(String repositoryID, + com.sun.org.omg.SendingContext.CodeBase sender) + throws IOException, ClassNotFoundException { + + for (FullValueDescription fvd : + getOrderedDescriptions( repositoryID, sender )) { + + String repIDForFVD = vhandler.getClassName(fvd.id); + + if (!repIDForFVD.equals("java.lang.Object")) { + if (fvd.is_custom) { + readFormatVersion(); + + boolean calledDefaultWriteObject = readBoolean(); + + if (calledDefaultWriteObject) { + inputClassFields(null, null, null, fvd.members, sender); + } + + if (getStreamFormatVersion() == 2) { + ((ValueInputStream)getOrbStream()).start_value(); + ((ValueInputStream)getOrbStream()).end_value(); + } + + // WARNING: If stream format version is 1 and there's + // optional data, we'll get some form of exception down + // the line. + } else { + // Use default marshaling + inputClassFields(null, null, null, fvd.members, sender); + } + } + + } + + return null; + } + + /////////////////// + + @ValueHandlerRead + private int findNextClass(String classname, Class classes[], + int _spClass, int _spBase){ + + for (int i = _spClass; i > _spBase; i--){ + if (classname.equals(classes[i].getName())) { + return i ; + } + } + + return -1 ; + } + + /* + * Invoke the readObject method if present. Assumes that in the case of custom + * marshaling, the format version and defaultWriteObject indicator were already + * removed. + */ + @ValueHandlerRead + private boolean invokeObjectReader(ObjectStreamClass osc, Object obj, + Class aclass, ValueMember[] valueMembers ) + throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException + { + OperationTracer.readingField( "<>" ) ; + + boolean result = false ; + + if (osc.getReadObjectMethod() != null) { + try { + defaultReadObjectFVDMembers = valueMembers ; + osc.getReadObjectMethod().invoke( obj, this ) ; + result = true ; + } catch (Throwable t) { + if (t instanceof ClassNotFoundException) { + throw (ClassNotFoundException) t; + } else if (t instanceof IOException) { + throw (IOException) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else if (t instanceof Error) { + throw (Error) t; + } else { + throw new Error("internal error"); + } + } finally { + // Make sure this is cleared no matter what + // the readObject method does. If the readObject + // method calls either defaultReadObject or + // getFields, this will be cleared. Any other + // behavior is an error, but we want to protect + // ourselves from a bad readObject method. + defaultReadObjectFVDMembers = null ; + } + } + + return result ; + } + + /* + * Reset the stream to be just like it was after the constructor. + */ + @ValueHandlerRead + private void resetStream() throws IOException { + + if (classes == null) { + classes = new Class[20]; + } else { + for (int i = 0; i < classes.length; i++) { + classes[i] = null; + } + } + + if (classdesc == null) { + classdesc = new ObjectStreamClass[20]; + } else { + for (int i = 0; i < classdesc.length; i++) { + classdesc[i] = null; + } + } + spClass = 0; + + if (callbacks != null) { + callbacks.clear(); + } // discard any pending callbacks + } + + /** + * Factored out of inputClassFields This reads a primitive value and sets it + * in the field of o described by the ObjectStreamField field. + * + * Note that reflection cannot be used here, because reflection cannot be used + * to set final fields. + */ + @ValueHandlerRead + private void inputPrimitiveField(Object o, Class cl, + ObjectStreamField field) throws InvalidClassException, IOException { + + try { + switch (field.getTypeCode()) { + case 'B': + byte byteValue = orbStream.read_octet(); + bridge.putByte( o, field.getFieldID(), byteValue ) ; + //reflective code: field.getField().setByte( o, byteValue ) ; + break; + case 'Z': + boolean booleanValue = orbStream.read_boolean(); + bridge.putBoolean( o, field.getFieldID(), booleanValue ) ; + //reflective code: field.getField().setBoolean( o, booleanValue ) ; + break; + case 'C': + char charValue = orbStream.read_wchar(); + bridge.putChar( o, field.getFieldID(), charValue ) ; + //reflective code: field.getField().setChar( o, charValue ) ; + break; + case 'S': + short shortValue = orbStream.read_short(); + bridge.putShort( o, field.getFieldID(), shortValue ) ; + //reflective code: field.getField().setShort( o, shortValue ) ; + break; + case 'I': + int intValue = orbStream.read_long(); + bridge.putInt( o, field.getFieldID(), intValue ) ; + //reflective code: field.getField().setInt( o, intValue ) ; + break; + case 'J': + long longValue = orbStream.read_longlong(); + bridge.putLong( o, field.getFieldID(), longValue ) ; + //reflective code: field.getField().setLong( o, longValue ) ; + break; + case 'F' : + float floatValue = orbStream.read_float(); + bridge.putFloat( o, field.getFieldID(), floatValue ) ; + //reflective code: field.getField().setFloat( o, floatValue ) ; + break; + case 'D' : + double doubleValue = orbStream.read_double(); + bridge.putDouble( o, field.getFieldID(), doubleValue ) ; + //reflective code: field.getField().setDouble( o, doubleValue ) ; + break; + default: + throw Exceptions.self.invalidClassForPrimitive( + cl.getName() ) ; + } + } catch (IllegalArgumentException e) { + /* This case should never happen. If the field types + are not the same, InvalidClassException is raised when + matching the local class to the serialized ObjectStreamClass. */ + ClassCastException cce = new ClassCastException( + "Assigning instance of class " + + field.getType().getName() + " to field " + + currentClassDesc.getName() + '#' + + field.getField().getName()); + cce.initCause( e ) ; + throw cce ; + } + } + + @InfoMethod + private void callTypeInfo( int ct ) { } + + @InfoMethod + private void typeInfo( Class type ) { } + + @ValueHandlerRead + private Object inputObjectField(org.omg.CORBA.ValueMember field, + com.sun.org.omg.SendingContext.CodeBase sender) + throws IndirectionException, ClassNotFoundException, IOException, + StreamCorruptedException { + + Object objectValue = null; + Class type = null; + String id = field.id; + + try { + type = vhandler.getClassFromType(id); + } catch(ClassNotFoundException cnfe) { + // Make sure type = null + type = null; + } + + typeInfo(type); + + String signature = null; + if (type != null) { + signature = ValueUtility.getSignature(field); + } + + if (signature != null && (signature.equals("Ljava/lang/Object;") + || signature.equals("Ljava/io/Serializable;") + || signature.equals("Ljava/io/Externalizable;"))) { + objectValue = Util.getInstance().readAny(orbStream); + } else { + // Decide what method call to make based on the type. If + // it is a type for which we need to load a stub, convert + // the type to the correct stub type. + // + // NOTE : Since FullValueDescription does not allow us + // to ask whether something is an interface we do not + // have the ability to optimize this check. + + int callType = ValueHandlerImpl.kValueType; + + if (!vhandler.isSequence(id)) { + + if (field.type.kind().value() == + kRemoteTypeCode.kind().value()) { + + // RMI Object reference... + callType = ValueHandlerImpl.kRemoteType; + } else { + // REVISIT. If we don't have the local class, + // we should probably verify that it's an RMI type, + // query the remote FVD, and use is_abstract. + // Our FVD seems to get NullPointerExceptions for any + // non-RMI types. + + // This uses the local class in the same way as + // inputObjectField(ObjectStreamField) does. REVISIT + // inputObjectField(ObjectStreamField)'s loadStubClass + // logic. Assumption is that the given type cannot + // evolve to become a CORBA abstract interface or + // a RMI abstract interface. + + ClassInfoCache.ClassInfo cinfo = + ClassInfoCache.get( type ) ; + if (type != null && cinfo.isInterface() && + (vhandler.isAbstractBase(type) || + ObjectStreamClassCorbaExt.isAbstractInterface(type))) { + + callType = ValueHandlerImpl.kAbstractType; + } + } + } + + callTypeInfo(callType); + + // Now that we have used the FVD of the field to determine the proper course + // of action, it is ok to use the type (Class) from this point forward since + // the rep. id for this read will also follow on the wire. + + switch (callType) { + case ValueHandlerImpl.kRemoteType: + if (type != null) { + objectValue = + Utility.readObjectAndNarrow(orbStream, type); + } else { + objectValue = orbStream.read_Object(); + } + break; + case ValueHandlerImpl.kAbstractType: + if (type != null) { + objectValue = + Utility.readAbstractAndNarrow(orbStream, type); + } else { + objectValue = orbStream.read_abstract_interface(); + } + break; + case ValueHandlerImpl.kValueType: + if (type != null) { + objectValue = orbStream.read_value(type); + } else { + objectValue = orbStream.read_value(); + } + break; + default: + throw Exceptions.self.unknownCallType( callType ) ; + } + } + + return objectValue; + } + + /** + * Factored out of inputClassFields and reused in + * inputCurrentClassFieldsForReadFields. + * + * Reads the field (which is of an Object type as opposed to a primitive) + * described by ObjectStreamField field and returns it. + */ + @ValueHandlerRead + private Object inputObjectField(ObjectStreamField field) + throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IndirectionException, IOException { + + if (ObjectStreamClassCorbaExt.isAny(field.getTypeString())) { + return Util.getInstance().readAny(orbStream); + } + + Object objectValue = null; + + // fields have an API to provide the actual class + // corresponding to the data type + // Class type = osc.forClass(); + Class fieldType = field.getType(); + Class actualType = fieldType; // This may change if stub loaded. + + // Decide what method call to make based on the fieldType. If + // it is a type for which we need to load a stub, convert + // the type to the correct stub type. + + int callType = ValueHandlerImpl.kValueType; + boolean narrow = false; + + ClassInfoCache.ClassInfo cinfo = field.getClassInfo() ; + if (cinfo.isInterface()) { + boolean loadStubClass = false; + + if (cinfo.isARemote(fieldType)) { + // RMI Object reference... + callType = ValueHandlerImpl.kRemoteType; + } else if (cinfo.isACORBAObject(fieldType)) { + // IDL Object reference... + callType = ValueHandlerImpl.kRemoteType; + loadStubClass = true; + } else if (vhandler.isAbstractBase(fieldType)) { + // IDL Abstract Object reference... + callType = ValueHandlerImpl.kAbstractType; + loadStubClass = true; + } else if (ObjectStreamClassCorbaExt.isAbstractInterface( + fieldType)) { + // RMI Abstract Object reference... + callType = ValueHandlerImpl.kAbstractType; + } + + if (loadStubClass) { + try { + String codebase = Util.getInstance().getCodebase(fieldType); + String repID = vhandler.createForAnyType(fieldType); + Class stubType = + Utility.loadStubClass(repID, codebase, fieldType); + actualType = stubType; + } catch (ClassNotFoundException e) { + narrow = true; + } + } else { + narrow = true; + } + } + + switch (callType) { + case ValueHandlerImpl.kRemoteType: + if (!narrow) { + objectValue = (Object) orbStream.read_Object(actualType); + } else { + objectValue = + Utility.readObjectAndNarrow(orbStream, actualType); + } + break; + case ValueHandlerImpl.kAbstractType: + if (!narrow) { + objectValue = orbStream.read_abstract_interface(actualType); + } else { + objectValue = + Utility.readAbstractAndNarrow(orbStream, actualType); + } + break; + case ValueHandlerImpl.kValueType: + objectValue = (Object)orbStream.read_value(actualType); + break; + default: + throw Exceptions.self.unknownCallType(callType) ; + } + + return objectValue; + } + + // Note that this is need for getFields support. + void readFields(Map fieldToValueMap) + throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException { + + if (defaultReadObjectFVDMembers != null) { + inputRemoteMembersForReadFields(fieldToValueMap); + } else { + inputCurrentClassFieldsForReadFields(fieldToValueMap); + } + } + + @ValueHandlerRead + private void inputRemoteMembersForReadFields( + Map fieldToValueMap) + throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException { + + // Must have this local variable since defaultReadObjectFVDMembers + // may get mangled by recursion. + ValueMember fields[] = defaultReadObjectFVDMembers; + defaultReadObjectFVDMembers = null ; + + try { + for (int i = 0; i < fields.length; i++) { + OperationTracer.readingField( fields[i].name ) ; + displayValueMember( fields[i] ); + + switch (fields[i].type.kind().value()) { + case TCKind._tk_octet: + byte byteValue = orbStream.read_octet(); + fieldToValueMap.put(fields[i].name, Byte.valueOf( + byteValue)); + break; + case TCKind._tk_boolean: + boolean booleanValue = orbStream.read_boolean(); + fieldToValueMap.put(fields[i].name, Boolean.valueOf( + booleanValue)); + break; + case TCKind._tk_char: + // Backwards compatibility. Older Sun ORBs sent + // _tk_char even though they read and wrote wchars + // correctly. + // + // Fall through to the _tk_wchar case. + case TCKind._tk_wchar: + char charValue = orbStream.read_wchar(); + fieldToValueMap.put(fields[i].name, Character.valueOf( + charValue)); + break; + case TCKind._tk_short: + short shortValue = orbStream.read_short(); + fieldToValueMap.put(fields[i].name, Short.valueOf( + shortValue)); + break; + case TCKind._tk_long: + int intValue = orbStream.read_long(); + fieldToValueMap.put(fields[i].name, Integer.valueOf( + intValue)); + break; + case TCKind._tk_longlong: + long longValue = orbStream.read_longlong(); + fieldToValueMap.put(fields[i].name, Long.valueOf( + longValue)); + break; + case TCKind._tk_float: + float floatValue = orbStream.read_float(); + fieldToValueMap.put(fields[i].name, Float.valueOf( + floatValue)); + break; + case TCKind._tk_double: + double doubleValue = orbStream.read_double(); + fieldToValueMap.put(fields[i].name, Double.valueOf( + doubleValue)); + break; + case TCKind._tk_value: + case TCKind._tk_objref: + case TCKind._tk_value_box: + Object objectValue = null; + try { + objectValue = inputObjectField(fields[i], cbSender); + } catch (IndirectionException cdrie) { + // The CDR stream had never seen the given offset before, + // so check the recursion manager (it will throw an + // IOException if it doesn't have a reference, either). + objectValue = activeRecursionMgr.getObject(cdrie.offset); + } + + fieldToValueMap.put(fields[i].name, objectValue); + break; + default: + throw Exceptions.self.unknownTypecodeKind( + fields[i].type.kind().value()); + } + } + } catch (Throwable t) { + StreamCorruptedException result = new StreamCorruptedException(t.getMessage()); + result.initCause(t); + throw result; + } + } + + /** + * Called from InputStreamHook. + * + * Reads the fields of the current class (could be the ones + * queried from the remote FVD) and puts them in + * the given Map, name to value. Wraps primitives in the + * corresponding java.lang Objects. + */ + @ValueHandlerRead + private void inputCurrentClassFieldsForReadFields( + Map fieldToValueMap) throws InvalidClassException, + StreamCorruptedException, ClassNotFoundException, IOException { + + ObjectStreamField[] fields = currentClassDesc.getFieldsNoCopy(); + + int primFields = fields.length - currentClassDesc.objFields; + + // Handle the primitives first + for (int i = 0; i < primFields; ++i) { + switch (fields[i].getTypeCode()) { + case 'B': + byte byteValue = orbStream.read_octet(); + fieldToValueMap.put(fields[i].getName(), + Byte.valueOf(byteValue)); + break; + case 'Z': + boolean booleanValue = orbStream.read_boolean(); + fieldToValueMap.put(fields[i].getName(), + Boolean.valueOf(booleanValue)); + break; + case 'C': + char charValue = orbStream.read_wchar(); + fieldToValueMap.put(fields[i].getName(), + Character.valueOf(charValue)); + break; + case 'S': + short shortValue = orbStream.read_short(); + fieldToValueMap.put(fields[i].getName(), + Short.valueOf(shortValue)); + break; + case 'I': + int intValue = orbStream.read_long(); + fieldToValueMap.put(fields[i].getName(), + Integer.valueOf(intValue)); + break; + case 'J': + long longValue = orbStream.read_longlong(); + fieldToValueMap.put(fields[i].getName(), + Long.valueOf(longValue)); + break; + case 'F' : + float floatValue = orbStream.read_float(); + fieldToValueMap.put(fields[i].getName(), + Float.valueOf(floatValue)); + break; + case 'D' : + double doubleValue = orbStream.read_double(); + fieldToValueMap.put(fields[i].getName(), + Double.valueOf(doubleValue)); + break; + default: + throw Exceptions.self.invalidClassForPrimitive( + currentClassDesc.getName() ); + } + } + + /* Read and set object fields from the input stream. */ + if (currentClassDesc.objFields > 0) { + for (int i = primFields; i < fields.length; i++) { + OperationTracer.readingField( fields[i].getName() ) ; + + Object objectValue = null; + try { + objectValue = inputObjectField(fields[i]); + } catch(IndirectionException cdrie) { + // The CDR stream had never seen the given offset before, + // so check the recursion manager (it will throw an + // IOException if it doesn't have a reference, either). + objectValue = activeRecursionMgr.getObject(cdrie.offset); + } + + fieldToValueMap.put(fields[i].getName(), objectValue); + } + } + } + + @InfoMethod + private void readingPrimitiveFields( int count ) { } + + @InfoMethod + private void readingField( int index, ObjectStreamField fld ) { } + + /* + * Read the fields of the specified class from the input stream and set + * the values of the fields in the specified object. If the specified + * object is null, just consume the fields without setting any values. If + * any ObjectStreamField does not have a reflected Field, don't try to set + * that field in the object. + * + * REVISIT -- This code doesn't do what the comment says to when + * getField() is null! + */ + @ValueHandlerRead + private void inputClassFields(Object o, Class cl, + ObjectStreamField[] fields, + com.sun.org.omg.SendingContext.CodeBase sender) + throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException + { + int primFields = fields.length - currentClassDesc.objFields; + readingPrimitiveFields(primFields); + + if (o != null) { + for (int i = 0; i < primFields; ++i) { + OperationTracer.readingField( fields[i].getName() ) ; + if (fields[i].getField() == null) { + continue; + } + + inputPrimitiveField(o, cl, fields[i]); + } + } + + /* Read and set object fields from the input stream. */ + if (currentClassDesc.objFields > 0) { + for (int i = primFields; i < fields.length; i++) { + OperationTracer.readingField( fields[i].getName() ) ; + Object objectValue = null; + + try { + readingField( i, fields[i] ) ; + objectValue = inputObjectField(fields[i]); + } catch(IndirectionException cdrie) { + // The CDR stream had never seen the given offset before, + // so check the recursion manager (it will throw an + // IOException if it doesn't have a reference, either). + objectValue = activeRecursionMgr.getObject(cdrie.offset); + } + + if ((o == null) || (fields[i].getField() == null)) { + continue; + } + + try { + Class fieldCl = fields[i].getClazz(); + if ((objectValue != null) + && (!fieldCl.isAssignableFrom( + objectValue.getClass()))) { + throw new IllegalArgumentException("Field mismatch"); + } + + Field classField = null; + try { + classField = cl.getDeclaredField(fields[i].getName()); + } catch (NoSuchFieldException nsfEx) { + throw new IllegalArgumentException(nsfEx); + } catch (SecurityException secEx) { + throw new IllegalArgumentException(secEx.getCause()); + } + + Class declaredFieldClass = classField.getType(); + + // check input field type is a declared field type + // input field is a subclass of the declared field + if (!declaredFieldClass.isAssignableFrom(fieldCl)) { + throw new IllegalArgumentException( + "Field Type mismatch"); + } + + if (objectValue != null && !fieldCl.isInstance(objectValue)) { + throw new IllegalArgumentException(); + } + + bridge.putObject( o, fields[i].getFieldID(), objectValue ) ; + // reflective code: fields[i].getField().set( o, objectValue ) ; + } catch (IllegalArgumentException e) { + ClassCastException exc = new ClassCastException( + "Assigning instance of class " + + objectValue.getClass().getName() + " to field " + + currentClassDesc.getName() + '#' + + fields[i].getField().getName()); + exc.initCause( e ) ; + throw exc ; + } + } + } + } + + @InfoMethod + private void valueMemberInfo( String name, String id, String definedIn, + String version, short access ) { } + + @ValueHandlerRead + private void displayValueMember( ValueMember member ) { + valueMemberInfo( member.name, member.id, member.defined_in, + member.version, member.access ) ; + } + + @ValueHandlerRead + private void displayValueMembers( ValueMember[] members ) { + for (ValueMember member : members ) { + displayValueMember(member); + } + } + + /* + * Read the fields of the specified class from the input stream and set + * the values of the fields in the specified object. If the specified + * object is null, just consume the fields without setting any values. If + * any ObjectStreamField does not have a reflected Field, don't try to set + * that field in the object. + */ + @ValueHandlerRead + private void inputClassFields(Object o, Class cl, + ObjectStreamClass osc, + ValueMember[] fields, + com.sun.org.omg.SendingContext.CodeBase sender) + throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException + { + displayValueMembers( fields ) ; + + try { + for (int i = 0; i < fields.length; ++i) { + OperationTracer.readingField( fields[i].name ) ; + + displayValueMember( fields[i] ) ; + + try { + switch (fields[i].type.kind().value()) { + case TCKind._tk_octet: + byte byteValue = orbStream.read_octet(); + if ((o != null) && osc.hasField(fields[i])) { + setByteField(o, cl, fields[i].name, byteValue); + } + break; + case TCKind._tk_boolean: + boolean booleanValue = orbStream.read_boolean(); + if ((o != null) && osc.hasField(fields[i])) { + setBooleanField(o, cl, fields[i].name, booleanValue); + } + break; + case TCKind._tk_char: + // Backwards compatibility. Older Sun ORBs sent + // _tk_char even though they read and wrote wchars + // correctly. + // + // Fall through to the _tk_wchar case. + case TCKind._tk_wchar: + char charValue = orbStream.read_wchar(); + if ((o != null) && osc.hasField(fields[i])) { + setCharField(o, cl, fields[i].name, charValue); + } + break; + case TCKind._tk_short: + short shortValue = orbStream.read_short(); + if ((o != null) && osc.hasField(fields[i])) { + setShortField(o, cl, fields[i].name, shortValue); + } + break; + case TCKind._tk_long: + int intValue = orbStream.read_long(); + if ((o != null) && osc.hasField(fields[i])) { + setIntField(o, cl, fields[i].name, intValue); + } + break; + case TCKind._tk_longlong: + long longValue = orbStream.read_longlong(); + if ((o != null) && osc.hasField(fields[i])) { + setLongField(o, cl, fields[i].name, longValue); + } + break; + case TCKind._tk_float: + float floatValue = orbStream.read_float(); + if ((o != null) && osc.hasField(fields[i])) { + setFloatField(o, cl, fields[i].name, floatValue); + } + break; + case TCKind._tk_double: + double doubleValue = orbStream.read_double(); + if ((o != null) && osc.hasField(fields[i])) { + setDoubleField(o, cl, fields[i].name, doubleValue); + } + break; + case TCKind._tk_value: + case TCKind._tk_objref: + case TCKind._tk_value_box: + Object objectValue = null; + try { + objectValue = inputObjectField(fields[i], sender); + } catch (IndirectionException cdrie) { + // The CDR stream had never seen the given offset before, + // so check the recursion manager (it will throw an + // IOException if it doesn't have a reference, either). + objectValue = activeRecursionMgr.getObject(cdrie.offset); + } + + if (o == null) { + continue; + } + + try { + if (osc.hasField(fields[i])){ + setObjectField(o, cl, fields[i].name, + objectValue); + } else { + Exceptions.self.notSettingField( fields[i].name, + osc.getName() ) ; + } + } catch (IllegalArgumentException e) { + throw Exceptions.self.couldNotAssignObjectToField( + e, objectValue.getClass().getName(), + fields[i].name ) ; + } + break; + default: + throw Exceptions.self.unknownTypecodeKind( + fields[i].type.kind().value()); + } + } catch (IllegalArgumentException e) { + throw Exceptions.self.couldNotAssignObjectToField( e, + fields[i].id, fields[i].name ) ; + } + } + } catch(Throwable t){ + throw Exceptions.self.streamCorrupted( t ) ; + } + } + + @ValueHandlerRead + private void skipCustomUsingFVD(ValueMember[] fields, + com.sun.org.omg.SendingContext.CodeBase sender + ) throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException { + + readFormatVersion(); + boolean calledDefaultWriteObject = readBoolean(); + + if (calledDefaultWriteObject) { + throwAwayData(fields, sender); + } + + if (getStreamFormatVersion() == 2) { + + ((ValueInputStream)getOrbStream()).start_value(); + ((ValueInputStream)getOrbStream()).end_value(); + } + } + + /* + * Read the fields of the specified class from the input stream throw data + * away. This must handle same switch logic as above. + */ + @ValueHandlerRead + private void throwAwayData(ValueMember[] fields, + com.sun.org.omg.SendingContext.CodeBase sender + ) throws InvalidClassException, StreamCorruptedException, + ClassNotFoundException, IOException { + + for (int i = 0; i < fields.length; ++i) { + OperationTracer.readingField( fields[i].name ) ; + try { + switch (fields[i].type.kind().value()) { + case TCKind._tk_octet: + orbStream.read_octet(); + break; + case TCKind._tk_boolean: + orbStream.read_boolean(); + break; + case TCKind._tk_char: + // Backwards compatibility. Older Sun ORBs sent + // _tk_char even though they read and wrote wchars + // correctly. + // + // Fall through to the _tk_wchar case. + case TCKind._tk_wchar: + orbStream.read_wchar(); + break; + case TCKind._tk_short: + orbStream.read_short(); + break; + case TCKind._tk_long: + orbStream.read_long(); + break; + case TCKind._tk_longlong: + orbStream.read_longlong(); + break; + case TCKind._tk_float: + orbStream.read_float(); + break; + case TCKind._tk_double: + orbStream.read_double(); + break; + case TCKind._tk_value: + case TCKind._tk_objref: + case TCKind._tk_value_box: + Class type = null; + String id = fields[i].id; + + try { + type = vhandler.getClassFromType(id); + } + catch(ClassNotFoundException cnfe){ + // Make sure type = null + type = null; + } + String signature = null; + if (type != null) { + signature = ValueUtility.getSignature(fields[i]); + } + + // Read value + try { + if ((signature != null) && ( + signature.equals("Ljava/lang/Object;") + || signature.equals("Ljava/io/Serializable;") + || signature.equals("Ljava/io/Externalizable;")) ) { + Util.getInstance().readAny(orbStream); + } else { + // Decide what method call to make based on the type. + // + // NOTE : Since FullValueDescription does not allow + // us to ask whether something is an interface we + // do not have the ability to optimize this check. + int callType = ValueHandlerImpl.kValueType; + + if (!vhandler.isSequence(id)) { + FullValueDescription fieldFVD = + sender.meta(fields[i].id); + if (kRemoteTypeCode == fields[i].type) { + + // RMI Object reference... + callType = ValueHandlerImpl.kRemoteType; + } else if (fieldFVD.is_abstract) { + // RMI Abstract Object reference... + + callType = ValueHandlerImpl.kAbstractType; + } + } + + // Now that we have used the FVD of the field to + // determine the proper course + // of action, it is ok to use the type (Class) + // from this point forward since + // the rep. id for this read will also follow on + // the wire. + switch (callType) { + case ValueHandlerImpl.kRemoteType: + orbStream.read_Object(); + break; + case ValueHandlerImpl.kAbstractType: + orbStream.read_abstract_interface(); + break; + case ValueHandlerImpl.kValueType: + if (type != null) { + orbStream.read_value(type); + } else { + orbStream.read_value(); + } + break; + default: + throw Exceptions.self.unknownCallType(callType) ; + } + } + } catch(IndirectionException cdrie) { + // Since we are throwing this away, don't bother + // handling recursion. + continue; + } + + break; + default: + throw Exceptions.self.unknownTypecodeKind( + fields[i].type.kind().value()); + } + } catch (IllegalArgumentException e) { + throw Exceptions.self.couldNotAssignObjectToField( e, + fields[i].id, currentClassDesc.getName() ) ; + } + } + + } + + @ValueHandlerRead + private static void setObjectField(Object o, Class c, String fieldName, + Object v) { + + try { + Field fld = c.getDeclaredField( fieldName ) ; + Class fieldCl = fld.getType(); + if(v != null && !fieldCl.isInstance(v)) { + throw new Exception(); + } + long key = bridge.objectFieldOffset( fld ) ; + bridge.putObject( o, key, v ) ; + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetObjectField( e, fieldName, + o.toString(), + v.toString() ) ; + + } else { + throw utilWrapper.errorSetObjectField( e, fieldName, + "null " + c.getName() + " object", + v.toString() ) ; + } + + } + } + + @ValueHandlerRead + private static void setBooleanField(Object o, Class c, String fieldName, + boolean v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Boolean.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putBoolean( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetBooleanField( e, fieldName, + o.toString(), + new Boolean(v) ) ; + } else { + throw utilWrapper.errorSetBooleanField( e, fieldName, + "null " + c.getName() + " object", + new Boolean(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setByteField(Object o, Class c, String fieldName, + byte v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Byte.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putByte( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetByteField( e, fieldName, + o.toString(), + new Byte(v) ) ; + } else { + throw utilWrapper.errorSetByteField( e, fieldName, + "null " + c.getName() + " object", + new Byte(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setCharField(Object o, Class c, String fieldName, + char v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Character.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putChar( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetCharField( e, fieldName, + o.toString(), + new Character(v) ) ; + } else { + throw utilWrapper.errorSetCharField( e, fieldName, + "null " + c.getName() + " object", + new Character(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setShortField(Object o, Class c, String fieldName, + short v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Short.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putShort( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetShortField( e, fieldName, + o.toString(), + new Short(v) ) ; + } else { + throw utilWrapper.errorSetShortField( e, fieldName, + "null " + c.getName() + " object", + new Short(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setIntField(Object o, Class c, String fieldName, + int v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Integer.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putInt( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetIntField( e, fieldName, + o.toString(), + new Integer(v) ) ; + } else { + throw utilWrapper.errorSetIntField( e, fieldName, + "null " + c.getName() + " object", + new Integer(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setLongField(Object o, Class c, String fieldName, + long v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Long.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putLong( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetLongField( e, fieldName, + o.toString(), + new Long(v) ) ; + } else { + throw utilWrapper.errorSetLongField( e, fieldName, + "null " + c.getName() + " object", + new Long(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setFloatField(Object o, Class c, String fieldName, + float v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Float.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putFloat( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetFloatField( e, fieldName, + o.toString(), + new Float(v) ) ; + } else { + throw utilWrapper.errorSetFloatField( e, fieldName, + "null " + c.getName() + " object", + new Float(v) ) ; + } + } + } + + @ValueHandlerRead + private static void setDoubleField(Object o, Class c, String fieldName, + double v) + { + try { + Field fld = c.getDeclaredField( fieldName ) ; + if ((fld != null) && (fld.getType() == Double.TYPE)) { + long key = bridge.objectFieldOffset( fld ) ; + bridge.putDouble( o, key, v ) ; + } else { + throw new InvalidObjectException("Field Type mismatch"); + } + } catch (Exception e) { + if (o != null) { + throw utilWrapper.errorSetDoubleField( e, fieldName, + o.toString(), + new Double(v) ) ; + } else { + throw utilWrapper.errorSetDoubleField( e, fieldName, + "null " + c.getName() + " object", + new Double(v) ) ; + } + } + } + + /** + * This class maintains a map of stream position to + * an Object currently being deserialized. It is used + * to handle the cases where the are indirections to + * an object on the recursion stack. The CDR level + * handles indirections to objects previously seen + * (and completely deserialized) in the stream. + */ + static class ActiveRecursionManager + { + private Map offsetToObjectMap; + + public ActiveRecursionManager() { + // A hash map is unsynchronized and allows + // null values + offsetToObjectMap = new HashMap(); + } + + // Called right after allocating a new object. + // Offset is the starting position in the stream + // of the object. + public void addObject(int offset, Object value) { + offsetToObjectMap.put(offset, value); + } + + // If the given starting position doesn't refer + // to the beginning of an object currently being + // deserialized, this throws an IOException. + // Otherwise, it returns a reference to the + // object. + public Object getObject(int offset) throws IOException { + Integer position = Integer.valueOf(offset); + + if (!offsetToObjectMap.containsKey(position)) { + throw new IOException("Invalid indirection to offset " + offset); + } + + return offsetToObjectMap.get(position); + } + + // Called when an object has been completely + // deserialized, so it should no longer be in + // this mapping. The CDR level can handle + // further indirections. + public void removeObject(int offset) { + offsetToObjectMap.remove(offset); + } + + // If the given offset doesn't map to an Object, + // then it isn't an indirection to an object + // currently being deserialized. + public boolean containsObject(int offset) { + return offsetToObjectMap.containsKey(offset); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/IIOPOutputStream.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/IIOPOutputStream.java new file mode 100644 index 000000000..18aae228c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/IIOPOutputStream.java @@ -0,0 +1,809 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; +import com.sun.corba.ee.impl.misc.ClassInfoCache; +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.trace.ValueHandlerWrite; +import org.glassfish.pfl.basic.reflection.Bridge; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.portable.OutputStream; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.InvalidClassException; +import java.io.NotActiveException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Stack; + + +/** + * IIOPOutputStream is ... + * + * @author Stephen Lewallen + * @version 0.01, 4/6/98 + * @since JDK1.1.6 + */ + +@ValueHandlerWrite +public class IIOPOutputStream + extends com.sun.corba.ee.impl.io.OutputStreamHook +{ + private static Bridge bridge = + AccessController.doPrivileged( + new PrivilegedAction() { + public Bridge run() { + return Bridge.get() ; + } + } + ) ; + + private org.omg.CORBA_2_3.portable.OutputStream orbStream; + + private Object currentObject = null; + + private ObjectStreamClass currentClassDesc = null; + + private int recursionDepth = 0; + + private int simpleWriteDepth = 0; + + private IOException abortIOException = null; + + private Stack classDescStack = + new Stack(); + + public IIOPOutputStream() + throws java.io.IOException + { + super(); + } + + // If using RMI-IIOP stream format version 2, this tells + // the ORB stream (which must be a ValueOutputStream) to + // begin a new valuetype to contain the optional data + // of the writeObject method. + @ValueHandlerWrite + protected void beginOptionalCustomData() { + if (streamFormatVersion == 2) { + + org.omg.CORBA.portable.ValueOutputStream vout + = (org.omg.CORBA.portable.ValueOutputStream)orbStream; + + vout.start_value(currentClassDesc.getRMIIIOPOptionalDataRepId()); + } + } + + final void setOrbStream(org.omg.CORBA_2_3.portable.OutputStream os) { + orbStream = os; + } + + final org.omg.CORBA_2_3.portable.OutputStream getOrbStream() { + return orbStream; + } + + @InfoMethod + private void recursionDepthInfo( int rd ) {} + + @ValueHandlerWrite + final void increaseRecursionDepth(){ + recursionDepth++; + recursionDepthInfo( recursionDepth ) ; + } + + @ValueHandlerWrite + final int decreaseRecursionDepth(){ + --recursionDepth; + recursionDepthInfo(recursionDepth); + return recursionDepth ; + } + + @ValueHandlerWrite + private void writeFormatVersion() { + orbStream.write_octet(streamFormatVersion); + } + + /** + * Override the actions of the final method "writeObject()" + * in ObjectOutputStream. + * @since JDK1.1.6 + */ + @ValueHandlerWrite + @Override + public final void writeObjectOverride(Object obj) + throws IOException { + + writeObjectState.writeData(this); + + Util.getInstance().writeAbstractObject((OutputStream)orbStream, obj); + } + + /** + * Override the actions of the final method "writeObject()" + * in ObjectOutputStream. + * @since JDK1.1.6 + */ + @ValueHandlerWrite + public final void simpleWriteObject(Object obj, byte formatVersion) { + byte oldStreamFormatVersion = streamFormatVersion; + + streamFormatVersion = formatVersion; + + Object prevObject = currentObject; + ObjectStreamClass prevClassDesc = currentClassDesc; + simpleWriteDepth++; + + try { + // if (!checkSpecialClasses(obj) && !checkSubstitutableSpecialClasses(obj)) + outputObject(obj); + + } catch (IOException ee) { + if (abortIOException == null) { + abortIOException = ee; + } + } finally { + /* Restore state of previous call incase this is a nested call */ + streamFormatVersion = oldStreamFormatVersion; + simpleWriteDepth--; + currentObject = prevObject; + currentClassDesc = prevClassDesc; + } + + /* If the recursion depth is 0, test for and clear the pending exception. + * If there is a pending exception throw it. + */ + IOException pending = abortIOException; + if (simpleWriteDepth == 0) { + abortIOException = null; + } + + if (pending != null) { + bridge.throwException( pending ) ; + } + } + + // Required by the superclass. + ObjectStreamField[] getFieldsNoCopy() { + return currentClassDesc.getFieldsNoCopy(); + } + + /** + * Override the actions of the final method "defaultWriteObject()" + * in ObjectOutputStream. + * @since JDK1.1.6 + */ + @ValueHandlerWrite + public final void defaultWriteObjectDelegate() + /* throws IOException */ + { + try { + if (currentObject == null || currentClassDesc == null) { + throw new NotActiveException("defaultWriteObjectDelegate"); + } + + ObjectStreamField[] fields = + currentClassDesc.getFieldsNoCopy(); + if (fields.length > 0) { + outputClassFields(currentObject, currentClassDesc.forClass(), + fields); + } + } catch(IOException ioe) { + bridge.throwException(ioe); + } + } + + /** + * Override the actions of the final method "enableReplaceObject()" + * in ObjectOutputStream. + * @since JDK1.1.6 + */ + public final boolean enableReplaceObjectDelegate(boolean enable) + /* throws SecurityException */ + { + return false; + + } + + + @Override + protected final void annotateClass(Class cl) throws IOException{ + throw Exceptions.self.annotateClassNotSupported() ; + } + + @Override + public final void close() throws IOException{ + // no op + } + + @Override + protected final void drain() throws IOException{ + // no op + } + + @ValueHandlerWrite + @Override + public final void flush() throws IOException{ + try{ + orbStream.flush(); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + protected final Object replaceObject(Object obj) throws IOException{ + throw Exceptions.self.replaceObjectNotSupported() ; + } + + /** + * Reset will disregard the state of any objects already written + * to the stream. The state is reset to be the same as a new + * ObjectOutputStream. The current point in the stream is marked + * as reset so the corresponding ObjectInputStream will be reset + * at the same point. Objects previously written to the stream + * will not be refered to as already being in the stream. They + * will be written to the stream again. + * @since JDK1.1 + */ + @ValueHandlerWrite + @Override + public final void reset() throws IOException{ + try{ + //orbStream.reset(); + + if (currentObject != null || currentClassDesc != null) { + throw new IOException("Illegal call to reset"); + } + + abortIOException = null; + + if (classDescStack == null) { + classDescStack = + new Stack(); + } else { + classDescStack.setSize(0); + } + + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void write(byte b[]) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_octet_array(b, 0, b.length); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void write(byte b[], int off, int len) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_octet_array(b, off, len); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void write(int data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_octet((byte)(data & 0xFF)); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeBoolean(boolean data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_boolean(data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeByte(int data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_octet((byte)data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeBytes(String data) throws IOException{ + try{ + writeObjectState.writeData(this); + + byte buf[] = data.getBytes(); + orbStream.write_octet_array(buf, 0, buf.length); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeChar(int data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_wchar((char)data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeChars(String data) throws IOException{ + try{ + writeObjectState.writeData(this); + + char buf[] = data.toCharArray(); + orbStream.write_wchar_array(buf, 0, buf.length); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeDouble(double data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_double(data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeFloat(float data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_float(data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeInt(int data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_long(data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeLong(long data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_longlong(data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @ValueHandlerWrite + @Override + public final void writeShort(int data) throws IOException{ + try{ + writeObjectState.writeData(this); + + orbStream.write_short((short)data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + @Override + protected final void writeStreamHeader() throws IOException{ + // no op + } + + /** + * Helper method for correcting the Kestrel bug 4367783 (dealing + * with larger than 8-bit chars). The old behavior was preserved + * in orbutil.IIOPInputStream_1_3 in order to interoperate with + * our legacy ORBs. + */ + protected void internalWriteUTF(org.omg.CORBA.portable.OutputStream stream, + String data) + { + stream.write_wstring(data); + } + + @ValueHandlerWrite + @Override + public final void writeUTF(String data) throws IOException{ + try{ + writeObjectState.writeData(this); + + internalWriteUTF(orbStream, data); + } catch(Error e) { + throw new IOException(e) ; + } + } + + // INTERNAL UTILITY METHODS + /* + * Check for special cases of serializing objects. + * These objects are not subject to replacement. + */ + private boolean checkSpecialClasses(Object obj) throws IOException { + + /* + * If this is a class, don't allow substitution + */ + //if (obj instanceof Class) { + // throw new IOException("Serialization of Class not supported"); + //} + + if (obj instanceof ObjectStreamClass) { + throw Exceptions.self.serializationObjectStreamClassNotSupported() ; + } + + return false; + } + + /* + * Check for special cases of substitutable serializing objects. + * These classes are replaceable. + */ + private boolean checkSubstitutableSpecialClasses(Object obj) + throws IOException + { + if (obj instanceof String) { + orbStream.write_value((java.io.Serializable)obj); + return true; + } + + return false; + } + + /* + * Write out the object + */ + @ValueHandlerWrite + private void outputObject(final Object obj) throws IOException{ + currentObject = obj; + Class currclass = obj.getClass(); + + /* Get the Class descriptor for this class, + * Throw a NotSerializableException if there is none. + */ + currentClassDesc = ObjectStreamClass.lookup(currclass); + if (currentClassDesc == null) { + throw Exceptions.self.notSerializable( currclass.getName() ) ; + } + + /* If the object is externalizable, + * call writeExternal. + * else do Serializable processing. + */ + if (currentClassDesc.isExternalizable()) { + // Write format version + writeFormatVersion() ; + + // KMC issue 5161: need to save state for Externalizable also! + // Obviously an Externalizable may also call writeObject, which + // calls writeObjectOverride, which sends the writeData input to + // the state machine. So we need a new state machine here! + WriteObjectState oldState = writeObjectState ; + setState( NOT_IN_WRITE_OBJECT ) ; + + try { + Externalizable ext = (Externalizable)obj; + ext.writeExternal(this); + } finally { + setState(oldState) ; + } + } else { + /* The object's classes should be processed from supertype to + * subtype. Push all the clases of the current object onto a stack. + * Remember the stack pointer where this set of classes is being + * pushed. + */ + if (currentClassDesc.forClass().getName().equals("java.lang.String")) { + this.writeUTF((String)obj); + return; + } + int stackMark = classDescStack.size(); + try { + ObjectStreamClass next; + while ((next = currentClassDesc.getSuperclass()) != null) { + classDescStack.push(currentClassDesc); + currentClassDesc = next; + } + + do { + WriteObjectState oldState = writeObjectState; + + try { + setState(NOT_IN_WRITE_OBJECT); + + if (currentClassDesc.hasWriteObject()) { + invokeObjectWriter(currentClassDesc, obj ); + } else { + defaultWriteObjectDelegate(); + } + } finally { + setState(oldState); + } + } while (classDescStack.size() > stackMark && + (currentClassDesc = classDescStack.pop()) != null); + } finally { + classDescStack.setSize(stackMark); + } + } + } + + /* + * Invoke writer. + * _REVISIT_ invokeObjectWriter and invokeObjectReader behave inconsistently with each other since + * the reader returns a boolean...fix later + */ + @ValueHandlerWrite + private void invokeObjectWriter(ObjectStreamClass osc, Object obj) + throws IOException { + + Class c = osc.forClass() ; + + try { + // Write format version + writeFormatVersion() ; + + writeObjectState.enterWriteObject(this); + + try { + osc.getWriteObjectMethod().invoke( obj, this ) ; + } finally { + writeObjectState.exitWriteObject(this); + } + } catch (Throwable t) { + if (t instanceof IOException) { + throw (IOException) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else if (t instanceof Error) { + throw (Error) t; + } else { + throw new Error("invokeObjectWriter internal error", t); + } + } + } + + // This is needed for the OutputStreamHook interface. + @ValueHandlerWrite + void writeField(ObjectStreamField field, Object value) throws IOException { + switch (field.getTypeCode()) { + case 'B': + if (value == null) { + orbStream.write_octet((byte) 0); + } else { + orbStream.write_octet(((Byte) value).byteValue()); + } + break; + case 'C': + if (value == null) { + orbStream.write_wchar((char) 0); + } else { + orbStream.write_wchar(((Character) value).charValue()); + } + break; + case 'F': + if (value == null) { + orbStream.write_float((float) 0); + } else { + orbStream.write_float(((Float) value).floatValue()); + } + break; + case 'D': + if (value == null) { + orbStream.write_double((double) 0); + } else { + orbStream.write_double(((Double) value).doubleValue()); + } + break; + case 'I': + if (value == null) { + orbStream.write_long(0); + } else { + orbStream.write_long(((Integer) value).intValue()); + } + break; + case 'J': + if (value == null) { + orbStream.write_longlong((long) 0); + } else { + orbStream.write_longlong(((Long) value).longValue()); + } + break; + case 'S': + if (value == null) { + orbStream.write_short((short) 0); + } else { + orbStream.write_short(((Short) value).shortValue()); + } + break; + case 'Z': + if (value == null) { + orbStream.write_boolean(false); + } else { + orbStream.write_boolean(((Boolean) value).booleanValue()); + } + break; + case '[': + case 'L': + // What to do if it's null? + writeObjectField(field, value); + break; + default: + throw Exceptions.self.invalidClassForWrite( + currentClassDesc.getName()); + } + } + + @ValueHandlerWrite + private void writeObjectField(ObjectStreamField field, + Object objectValue) throws IOException { + + if (ObjectStreamClassCorbaExt.isAny(field.getTypeString())) { + Util.getInstance().writeAny(orbStream, objectValue); + } + else { + Class type = field.getType(); + int callType = ValueHandlerImpl.kValueType; + ClassInfoCache.ClassInfo cinfo = field.getClassInfo() ; + + if (cinfo.isInterface()) { + String className = type.getName(); + + if (cinfo.isARemote(type)) { + // RMI Object reference... + callType = ValueHandlerImpl.kRemoteType; + } else if (cinfo.isACORBAObject(type)) { + // IDL Object reference... + callType = ValueHandlerImpl.kRemoteType; + } else if (RepositoryId.isAbstractBase(type)) { + // IDL Abstract Object reference... + callType = ValueHandlerImpl.kAbstractType; + } else if (ObjectStreamClassCorbaExt.isAbstractInterface(type)) { + callType = ValueHandlerImpl.kAbstractType; + } + } + + switch (callType) { + case ValueHandlerImpl.kRemoteType: + Util.getInstance().writeRemoteObject(orbStream, objectValue); + break; + case ValueHandlerImpl.kAbstractType: + Util.getInstance().writeAbstractObject(orbStream, objectValue); + break; + case ValueHandlerImpl.kValueType: + try{ + orbStream.write_value((java.io.Serializable)objectValue, + type); + } catch(ClassCastException cce){ + if (objectValue instanceof java.io.Serializable) { + throw cce; + } else { + Utility.throwNotSerializableForCorba(objectValue.getClass(). + getName()); + } + } + } + } + } + + /* Write the fields of the specified class by invoking the appropriate + * write* method on this class. + */ + @ValueHandlerWrite + private void outputClassFields(Object o, Class cl, + ObjectStreamField[] fields) + throws IOException, InvalidClassException { + + // replace this all with + // for (int i = 0; i < fields.length; i++) { + // fields[i].write( o, orbStream ) ; + // Should we just put this into ObjectStreamClass? + // Could also unroll and codegen this. + + for (int i = 0; i < fields.length; i++) { + ObjectStreamField field = fields[i] ; + final long offset = field.getFieldID() ; + if (offset == Bridge.INVALID_FIELD_OFFSET) { + throw new InvalidClassException(cl.getName(), + "Nonexistent field " + fields[i].getName()); + } + switch (field.getTypeCode()) { + case 'B': + byte byteValue = bridge.getByte( o, offset ) ; + orbStream.write_octet(byteValue); + break; + case 'C': + char charValue = bridge.getChar( o, offset ) ; + orbStream.write_wchar(charValue); + break; + case 'F': + float floatValue = bridge.getFloat( o, offset ) ; + orbStream.write_float(floatValue); + break; + case 'D' : + double doubleValue = bridge.getDouble( o, offset ) ; + orbStream.write_double(doubleValue); + break; + case 'I': + int intValue = bridge.getInt( o, offset ) ; + orbStream.write_long(intValue); + break; + case 'J': + long longValue = bridge.getLong( o, offset ) ; + orbStream.write_longlong(longValue); + break; + case 'S': + short shortValue = bridge.getShort( o, offset ) ; + orbStream.write_short(shortValue); + break; + case 'Z': + boolean booleanValue = bridge.getBoolean( o, offset ) ; + orbStream.write_boolean(booleanValue); + break; + case '[': + case 'L': + Object objectValue = bridge.getObject( o, offset ) ; + writeObjectField(fields[i], objectValue); + break; + default: + throw Exceptions.self.invalidClassForWrite( + cl.getName() ) ; + } + } + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/InputStreamHook.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/InputStreamHook.java new file mode 100644 index 000000000..e2944023c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/InputStreamHook.java @@ -0,0 +1,522 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import java.io.IOException; +import java.io.StreamCorruptedException; +import java.io.NotActiveException; +import java.io.ObjectInputStream; + +import org.omg.CORBA.portable.ValueInputStream; + +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.logging.UtilSystemException; +import com.sun.corba.ee.spi.logging.OMGSystemException; + +import com.sun.corba.ee.spi.trace.StreamFormatVersion; +import java.util.HashMap; +import java.util.Map; + +@StreamFormatVersion +public abstract class InputStreamHook extends ObjectInputStream +{ + // These should be visible in all the nested classes + static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + static final UtilSystemException utilWrapper = + UtilSystemException.self ; + + + private class HookGetFields extends ObjectInputStream.GetField { + private Map fields = null; + + HookGetFields(Map fields){ + this.fields = fields; + } + + /** + * Get the ObjectStreamClass that describes the fields in the stream. + * + * REVISIT! This doesn't work since we have our own ObjectStreamClass. + */ + public java.io.ObjectStreamClass getObjectStreamClass() { + return null; + } + + /** + * Return true if the named field is defaulted and has no value + * in this stream. + */ + public boolean defaulted(String name) + throws IOException, IllegalArgumentException { + return (!fields.containsKey(name)); + } + + /** + * Get the value of the named boolean field from the persistent field. + */ + public boolean get(String name, boolean defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Boolean) fields.get(name)).booleanValue(); + } + } + + /** + * Get the value of the named char field from the persistent fields. + */ + public char get(String name, char defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Character) fields.get(name)).charValue(); + } + + } + + /** + * Get the value of the named byte field from the persistent fields. + */ + public byte get(String name, byte defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Byte) fields.get(name)).byteValue(); + } + + } + + /** + * Get the value of the named short field from the persistent fields. + */ + public short get(String name, short defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Short) fields.get(name)).shortValue(); + } + + } + + /** + * Get the value of the named int field from the persistent fields. + */ + public int get(String name, int defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Integer) fields.get(name)).intValue(); + } + } + + /** + * Get the value of the named long field from the persistent fields. + */ + public long get(String name, long defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Long) fields.get(name)).longValue(); + } + } + + /** + * Get the value of the named float field from the persistent fields. + */ + public float get(String name, float defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Float) fields.get(name)).floatValue(); + } + } + + /** + * Get the value of the named double field from the persistent field. + */ + public double get(String name, double defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return ((Double) fields.get(name)).doubleValue(); + } + } + + /** + * Get the value of the named Object field from the persistent field. + */ + public Object get(String name, Object defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) { + return defvalue; + } else { + return fields.get(name); + } + + } + + @Override + public String toString(){ + return fields.toString(); + } + } + + public InputStreamHook() + throws IOException { + super(); + } + + @Override + @StreamFormatVersion + public void defaultReadObject() + throws IOException, ClassNotFoundException, NotActiveException + { + readObjectState.beginDefaultReadObject(this); + + defaultReadObjectDelegate(); + + readObjectState.endDefaultReadObject(this); + } + + abstract void defaultReadObjectDelegate(); + + abstract void readFields(java.util.Map fieldToValueMap) + throws java.io.InvalidClassException, java.io.StreamCorruptedException, + ClassNotFoundException, java.io.IOException; + + + // See java.io.ObjectInputStream.GetField + // Remember that this is equivalent to defaultReadObject + // in RMI-IIOP + @Override + public ObjectInputStream.GetField readFields() + throws IOException, ClassNotFoundException, NotActiveException { + + Map fieldValueMap = new HashMap(); + + // We were treating readFields same as defaultReadObject. It is + // incorrect if the state is readOptionalData. If this line + // is uncommented, it will throw a stream corrupted exception. + // _REVISIT_: The ideal fix would be to add a new state. In + // writeObject user may do one of the following + // 1. Call defaultWriteObject() + // 2. Put out optional fields + // 3. Call writeFields + // We have the state defined for (1) and (2) but not for (3), so + // we should ideally introduce a new state for 3 and have the + // beginDefaultReadObject do nothing. + //readObjectState.beginDefaultReadObject(this); + + readFields(fieldValueMap); + + readObjectState.endDefaultReadObject(this); + + return new HookGetFields(fieldValueMap); + } + + // The following is a State pattern implementation of what + // should be done when the sender's Serializable has a + // writeObject method. This was especially necessary for + // RMI-IIOP stream format version 2. Please see the + // state diagrams in the docs directory of the workspace. + // + // On the reader's side, the main factors are whether or not + // we have a readObject method and whether or not the + // sender wrote default data + + @StreamFormatVersion + protected void setState(ReadObjectState newState) { + readObjectState = newState; + } + + protected abstract byte getStreamFormatVersion(); + abstract org.omg.CORBA_2_3.portable.InputStream getOrbStream(); + + // Description of possible actions + @StreamFormatVersion + protected static class ReadObjectState { + private final String name ; + + public ReadObjectState() { + String className = this.getClass().getName() ; + int index = className.indexOf( '$' ) ; + name = className.substring( index + 1 ) ; + } + + @StreamFormatVersion + public final void beginUnmarshalCustomValue(InputStreamHook stream, boolean calledDefaultWriteObject, + boolean hasReadObject) throws IOException { + beginUnmarshalCustomValueOverride( stream, calledDefaultWriteObject, hasReadObject ) ; + } + + @StreamFormatVersion + public final void endUnmarshalCustomValue(InputStreamHook stream) throws IOException { + endUnmarshalCustomValueOverride( stream ) ; + } + + @StreamFormatVersion + public final void beginDefaultReadObject(InputStreamHook stream) throws IOException { + beginDefaultReadObjectOverride( stream ) ; + } + + @StreamFormatVersion + public final void endDefaultReadObject(InputStreamHook stream) throws IOException { + endDefaultReadObjectOverride( stream ) ; + } + + @StreamFormatVersion + public final void readData(InputStreamHook stream) throws IOException { + readDataOverride( stream ) ; + } + + public void beginUnmarshalCustomValueOverride(InputStreamHook stream, + boolean calledDefaultWriteObject, boolean hasReadObject) throws IOException {} + public void endUnmarshalCustomValueOverride(InputStreamHook stream) throws IOException {} + public void beginDefaultReadObjectOverride(InputStreamHook stream) throws IOException {} + public void endDefaultReadObjectOverride(InputStreamHook stream) throws IOException {} + public void readDataOverride(InputStreamHook stream) throws IOException {} + + @Override + public String toString() { + return name ; + } + } + + protected ReadObjectState readObjectState = DEFAULT_STATE; + + protected static final ReadObjectState DEFAULT_STATE = new DefaultState(); + protected static final ReadObjectState IN_READ_OBJECT_OPT_DATA + = new InReadObjectOptionalDataState(); + protected static final ReadObjectState IN_READ_OBJECT_NO_MORE_OPT_DATA + = new InReadObjectNoMoreOptionalDataState(); + protected static final ReadObjectState IN_READ_OBJECT_DEFAULTS_SENT + = new InReadObjectDefaultsSentState(); + protected static final ReadObjectState NO_READ_OBJECT_DEFAULTS_SENT + = new NoReadObjectDefaultsSentState(); + + protected static final ReadObjectState IN_READ_OBJECT_REMOTE_NOT_CUSTOM_MARSHALED + = new InReadObjectRemoteDidNotUseWriteObjectState(); + protected static final ReadObjectState IN_READ_OBJECT_PAST_DEFAULTS_REMOTE_NOT_CUSTOM + = new InReadObjectPastDefaultsRemoteDidNotUseWOState(); + + protected static class DefaultState extends ReadObjectState { + + @Override + public void beginUnmarshalCustomValueOverride(InputStreamHook stream, + boolean calledDefaultWriteObject, + boolean hasReadObject) + throws IOException { + + if (hasReadObject) { + if (calledDefaultWriteObject) { + stream.setState(IN_READ_OBJECT_DEFAULTS_SENT); + } else { + try { + if (stream.getStreamFormatVersion() == 2) { + ((ValueInputStream) stream.getOrbStream()) + .start_value(); + } + } catch( Exception e ) { + // This will happen for Big Integer which uses + // writeFields in it's writeObject. We should be past + // start_value by now. + // NOTE: If we don't log any exception here we should + // be fine. If there is an error, it will be caught + // while reading the optional data. + + } + stream.setState(IN_READ_OBJECT_OPT_DATA); + } + } else { + if (calledDefaultWriteObject) { + stream.setState(NO_READ_OBJECT_DEFAULTS_SENT); + } else { + throw new StreamCorruptedException("No default data sent"); + } + } + } + } + + // REVISIT. If a readObject exits here without reading + // default data, we won't skip it. This could be done automatically + // as in line 1492 in IIOPInputStream. + protected static class InReadObjectRemoteDidNotUseWriteObjectState extends ReadObjectState { + + @Override + public void beginUnmarshalCustomValueOverride(InputStreamHook stream, + boolean calledDefaultWriteObject, + boolean hasReadObject) + { + throw utilWrapper.badBeginUnmarshalCustomValue() ; + } + + @Override + public void endDefaultReadObjectOverride(InputStreamHook stream) { + stream.setState(IN_READ_OBJECT_PAST_DEFAULTS_REMOTE_NOT_CUSTOM); + } + + @Override + public void readDataOverride(InputStreamHook stream) { + stream.throwOptionalDataIncompatibleException(); + } + } + + protected static class InReadObjectPastDefaultsRemoteDidNotUseWOState extends ReadObjectState { + + @Override + public void beginUnmarshalCustomValueOverride(InputStreamHook stream, + boolean calledDefaultWriteObject, + boolean hasReadObject) + { + throw utilWrapper.badBeginUnmarshalCustomValue() ; + } + + @Override + public void beginDefaultReadObjectOverride(InputStreamHook stream) throws IOException + { + throw Exceptions.self.defaultDataAlreadyRead() ; + } + + + @Override + public void readDataOverride(InputStreamHook stream) { + stream.throwOptionalDataIncompatibleException(); + } + } + + protected void throwOptionalDataIncompatibleException() + { + throw omgWrapper.rmiiiopOptionalDataIncompatible2() ; + } + + + protected static class InReadObjectDefaultsSentState extends ReadObjectState { + + @Override + public void beginUnmarshalCustomValueOverride(InputStreamHook stream, + boolean calledDefaultWriteObject, + boolean hasReadObject) { + // This should never happen. + throw utilWrapper.badBeginUnmarshalCustomValue() ; + } + + @Override + public void endUnmarshalCustomValueOverride(InputStreamHook stream) { + + // In stream format version 2, we can skip over + // the optional data this way. In stream format version 1, + // we will probably wind up with an error if we're + // unmarshaling a superclass. + if (stream.getStreamFormatVersion() == 2) { + ((ValueInputStream)stream.getOrbStream()).start_value(); + ((ValueInputStream)stream.getOrbStream()).end_value(); + } + + stream.setState(DEFAULT_STATE); + } + + @Override + public void endDefaultReadObjectOverride(InputStreamHook stream) throws IOException { + + // Read the fake valuetype header in stream format version 2 + if (stream.getStreamFormatVersion() == 2) { + ((ValueInputStream) stream.getOrbStream()).start_value(); + } + + stream.setState(IN_READ_OBJECT_OPT_DATA); + } + + @Override + public void readDataOverride(InputStreamHook stream) throws IOException { + org.omg.CORBA.ORB orb = stream.getOrbStream().orb(); + if ((orb == null) || + !(orb instanceof com.sun.corba.ee.spi.orb.ORB)) { + throw new StreamCorruptedException( + "Default data must be read first"); + } + ORBVersion clientOrbVersion = + ((com.sun.corba.ee.spi.orb.ORB)orb).getORBVersion(); + + // Fix Date interop bug. For older versions of the ORB don't do + // anything for readData(). Before this used to throw + // StreamCorruptedException for older versions of the ORB where + // calledDefaultWriteObject always returns true. + if ((ORBVersionFactory.getPEORB().compareTo(clientOrbVersion) <= 0) || + (clientOrbVersion.equals(ORBVersionFactory.getFOREIGN()))) { + throw Exceptions.self.defaultDataMustBeReadFirst() ; + } + } + } + + protected static class InReadObjectOptionalDataState extends ReadObjectState { + + @Override + public void beginUnmarshalCustomValueOverride(InputStreamHook stream, + boolean calledDefaultWriteObject, + boolean hasReadObject) + { + // This should never happen. + throw utilWrapper.badBeginUnmarshalCustomValue() ; + } + + @Override + public void endUnmarshalCustomValueOverride(InputStreamHook stream) throws IOException + { + if (stream.getStreamFormatVersion() == 2) { + ((ValueInputStream)stream.getOrbStream()).end_value(); + } + stream.setState(DEFAULT_STATE); + } + + @Override + public void beginDefaultReadObjectOverride(InputStreamHook stream) throws IOException + { + throw Exceptions.self.defaultDataNotPresent() ; + } + + + } + + protected static class InReadObjectNoMoreOptionalDataState + extends InReadObjectOptionalDataState { + + @Override + public void readDataOverride(InputStreamHook stream) throws IOException { + stream.throwOptionalDataIncompatibleException(); + } + } + + protected static class NoReadObjectDefaultsSentState extends ReadObjectState { + @Override + public void endUnmarshalCustomValueOverride(InputStreamHook stream) throws IOException { + // Code should read default fields before calling this + + if (stream.getStreamFormatVersion() == 2) { + ((ValueInputStream)stream.getOrbStream()).start_value(); + ((ValueInputStream)stream.getOrbStream()).end_value(); + } + + stream.setState(DEFAULT_STATE); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/JavaCorbaAccess.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/JavaCorbaAccess.java new file mode 100644 index 000000000..730d55a45 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/JavaCorbaAccess.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +public interface JavaCorbaAccess { + public ValueHandlerImpl newValueHandlerImpl(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamClass.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamClass.java new file mode 100644 index 000000000..ec1437590 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamClass.java @@ -0,0 +1,1394 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-2012 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import com.sun.corba.ee.impl.misc.ClassInfoCache; +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.spi.trace.TraceValueHandler; +import org.glassfish.pfl.basic.concurrent.SoftCache; +import org.glassfish.pfl.basic.reflection.Bridge; +import org.omg.CORBA.ValueMember; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.Serializable; +import java.lang.invoke.MethodHandle; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import java.security.AccessController; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedAction; +import java.util.Arrays; +import java.util.Comparator; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * A ObjectStreamClass describes a class that can be serialized to a stream + * or a class that was serialized to a stream. It contains the name + * and the serialVersionUID of the class. + *
    + * The ObjectStreamClass for a specific class loaded in this Java VM can + * be found using the lookup method. + * + * @author Roger Riggs + * @(#)ObjectStreamClass.java 1.17 99/06/07 + * @since JDK1.1 + */ +@TraceValueHandler +public class ObjectStreamClass implements java.io.Serializable { + private static final boolean DEBUG_SVUID = false ; + + public static final long kDefaultUID = -1; + + // True if this is an Enum type (6877056) + private boolean isEnum ; + + private static final Bridge bridge = + AccessController.doPrivileged( + new PrivilegedAction() { + public Bridge run() { + return Bridge.get() ; + } + } + ) ; + + /** Find the descriptor for a class that can be serialized. Null + * is returned if the specified class does not implement + * java.io.Serializable or java.io.Externalizable. + */ + @TraceValueHandler + static final ObjectStreamClass lookup(Class cl) { + ObjectStreamClass desc = lookupInternal(cl); + if (desc.isSerializable() || desc.isExternalizable()) + return desc; + return null; + } + + /* + * Find the class descriptor for the specified class. + * Package access only so it can be called from ObjectIn/OutStream. + */ + static ObjectStreamClass lookupInternal(Class cl) + { + /* Synchronize on the hashtable so no two threads will do + * this at the same time. + */ + ObjectStreamClass desc = null; + synchronized (descriptorFor) { + /* Find the matching descriptor if it already known */ + desc = (ObjectStreamClass)descriptorFor.get( cl ) ; + if (desc == null) { + /* Check if it's serializable */ + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( cl ) ; + boolean serializable = Serializable.class.isAssignableFrom(cl) ; + + /* If the class is only Serializable, + * lookup the descriptor for the superclass. + */ + ObjectStreamClass superdesc = null; + if (serializable) { + Class superclass = cl.getSuperclass(); + if (superclass != null) + superdesc = lookup(superclass); + } + + /* Check if its' externalizable. + * If it's Externalizable, clear the serializable flag. + * Only one or the other may be set in the protocol. + */ + boolean externalizable = false; + if (serializable) { + externalizable = + ((superdesc != null) && superdesc.isExternalizable()) || + cinfo.isAExternalizable(cl); + if (externalizable) { + serializable = false; + } + } + + /* Create a new version descriptor, + * it put itself in the known table. + */ + desc = new ObjectStreamClass(cl, superdesc, + serializable, externalizable); + } + + // Must always call init. See bug 4488137. This code was + // incorrectly changed to return immediately on a non-null + // cache result. That allowed threads to gain access to + // unintialized instances. + // + // All threads must sync on the member variable lock + // and check the initialization state. + // + // Another possibility is to continue to synchronize on the + // descriptorFor map, but that leads to poor performance + // (see bug 4165204 "ObjectStreamClass can hold global lock + // for a very long time"). + // + // We will need to live with 4165204 until we can rewrite + // this to follow the improved java.io.ObjectStreamClass + // in J2SE 1.4 and later. Calling desc.init() outside of + // this synchronized block can lead to deadlocks as + // reported in 5104239. + desc.init(); + } + + return desc; + } + + /** + * The name of the class described by this descriptor. + */ + public final String getName() { + return name; + } + + /** + * Return the serialVersionUID for this class. + * The serialVersionUID defines a set of classes all with the same name + * that have evolved from a common root class and agree to be serialized + * and deserialized using a common format. + */ + public static final long getSerialVersionUID( java.lang.Class clazz) { + ObjectStreamClass theosc = ObjectStreamClass.lookup( clazz ); + if (theosc != null) { + return theosc.getSerialVersionUID( ); + } + return 0; + } + + /** + * Return the serialVersionUID for this class. + * The serialVersionUID defines a set of classes all with the same name + * that have evolved from a common root class and agree to be serialized + * and deserialized using a common format. + */ + public final long getSerialVersionUID() { + return suid; + } + + /** + * Return the serialVersionUID string for this class. + * The serialVersionUID defines a set of classes all with the same name + * that have evolved from a common root class and agree to be serialized + * and deserialized using a common format. + */ + public final String getSerialVersionUIDStr() { + if (suidStr == null) + suidStr = Long.toHexString(suid).toUpperCase(); + return suidStr; + } + + /** + * Return the actual (computed) serialVersionUID for this class. + */ + public static final long getActualSerialVersionUID( java.lang.Class clazz ) + { + ObjectStreamClass theosc = ObjectStreamClass.lookup( clazz ); + if( theosc != null ) + { + return theosc.getActualSerialVersionUID( ); + } + return 0; + } + + /** + * Return the actual (computed) serialVersionUID for this class. + */ + public final long getActualSerialVersionUID() { + return actualSuid; + } + + /** + * Return the actual (computed) serialVersionUID for this class. + */ + public final String getActualSerialVersionUIDStr() { + if (actualSuidStr == null) + actualSuidStr = Long.toHexString(actualSuid).toUpperCase(); + return actualSuidStr; + } + + /** + * Return the class in the local VM that this version is mapped to. + * Null is returned if there is no corresponding local class. + */ + public final Class forClass() { + return ofClass; + } + + /** + * Return an array of the fields of this serializable class. + * @return an array containing an element for each persistent + * field of this class. Returns an array of length zero if + * there are no fields. + * @since JDK1.2 + */ + public ObjectStreamField[] getFields() { + // Return a copy so the caller can't change the fields. + if (fields.length > 0) { + ObjectStreamField[] dup = new ObjectStreamField[fields.length]; + System.arraycopy(fields, 0, dup, 0, fields.length); + return dup; + } else { + return fields; + } + } + + public boolean hasField(ValueMember field) + { + try { + for (int i = 0; i < fields.length; i++) { + if (fields[i].getName().equals(field.name)) { + if (fields[i].getSignature().equals( + ValueUtility.getSignature(field))) + return true; + } + } + } catch (Exception exc) { + // Ignore this; all we want to do is return false + // Note that ValueUtility.getSignature can throw checked exceptions. + } + + return false; + } + + /* Avoid unnecessary allocations. */ + final ObjectStreamField[] getFieldsNoCopy() { + return fields; + } + + /** + * Get the field of this class by name. + * @return The ObjectStreamField object of the named field or null if there + * is no such named field. + */ + public final ObjectStreamField getField(String name) { + /* Binary search of fields by name. + */ + for (int i = fields.length-1; i >= 0; i--) { + if (name.equals(fields[i].getName())) { + return fields[i]; + } + } + return null; + } + + public Serializable writeReplace(Serializable value) { + if (writeReplaceObjectMethod != null) { + try { + return (Serializable) writeReplaceObjectMethod.invoke(value); + } catch(Throwable t) { + throw new RuntimeException(t); + } + } + else return value; + } + + public Object readResolve(Object value) { + if (readResolveObjectMethod != null) { + try { + return readResolveObjectMethod.invoke(value); + } catch(Throwable t) { + throw new RuntimeException(t); + } + } + else return value; + } + + /** + * Return a string describing this ObjectStreamClass. + */ + @Override + public final String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append(name); + sb.append(": static final long serialVersionUID = "); + sb.append(Long.toString(suid)); + sb.append("L;"); + return sb.toString(); + } + + /* + * Create a new ObjectStreamClass from a loaded class. + * Don't call this directly, call lookup instead. + */ + private ObjectStreamClass(java.lang.Class cl, ObjectStreamClass superdesc, + boolean serial, boolean extern) + { + ofClass = cl; /* created from this class */ + + if (Proxy.isProxyClass(cl)) { + forProxyClass = true; + } + + name = cl.getName(); + // 6877056 + final ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( cl ) ; + isEnum = cinfo.isEnum() ; + superclass = superdesc; + serializable = serial; + if (!forProxyClass) { + // proxy classes are never externalizable + externalizable = extern; + } + + /* + * Enter this class in the table of known descriptors. + * Otherwise, when the fields are read it may recurse + * trying to find the descriptor for itself. + */ + descriptorFor.put( cl, this ) ; + } + + MethodHandle getWriteObjectMethod() { + return writeObjectMethod; + } + + MethodHandle getReadObjectMethod() { + return readObjectMethod; + } + + private static final class PersistentFieldsValue { + private final ConcurrentMap, Object> map = new ConcurrentHashMap, Object>(); + private static final Object NULL_VALUE = + (PersistentFieldsValue.class.getName() + ".NULL_VALUE"); + + PersistentFieldsValue() { } + + ObjectStreamField[] get(Class type) { + Object value = map.get(type); + if (value == null) { + value = computeValue(type); + Object oldValue = map.putIfAbsent(type, value); + if (oldValue != null) { + value = oldValue; + } + } + return ((value == NULL_VALUE) ? null : (ObjectStreamField[])value); + } + + private static Object computeValue(Class type) { + try { + bridge.ensureClassInitialized(type); + Field pf = type.getDeclaredField("serialPersistentFields"); + int mods = pf.getModifiers(); + if (Modifier.isPrivate(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) { + java.io.ObjectStreamField[] fields = bridge.getObject(type, bridge.staticFieldOffset(pf)); + return translateFields(fields); + } + } catch (NoSuchFieldException | IllegalArgumentException | ClassCastException ignored) { + } + return NULL_VALUE; + } + + private static ObjectStreamField[] translateFields(java.io.ObjectStreamField[] fields) { + ObjectStreamField[] translation = new ObjectStreamField[fields.length]; + for (int i = 0; i < fields.length; i++) + translation[i] = new ObjectStreamField(fields[i].getName(), fields[i].getType()); + return translation; + } + } + + private static final PersistentFieldsValue persistentFieldsValue = + new PersistentFieldsValue(); + /* + * Initialize class descriptor. This method is only invoked on class + * descriptors created via calls to lookupInternal(). This method was kept + * separate from the ObjectStreamClass constructor so that lookupInternal + * does not have to hold onto a global class descriptor table lock while the + * class descriptor is being initialized (see bug 4165204). However, + * this change leads to a (rare) deadlock. This code needs to be + * significantly re-written as in later (1.4) JDK releases. + */ + private void init() { + synchronized (lock) { + // See description at definition of initialized. + if (initialized) + return; + + final Class cl = ofClass; + + // 6877056 + if (!serializable || externalizable || forProxyClass || isEnum || + name.equals("java.lang.String")) { + fields = NO_FIELDS; + } else if (serializable) { + fields = null ; + + /* Ask for permission to override field access checks. + */ + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + /* Fill in the list of persistent fields. + * If it is declared, use the declared serialPersistentFields. + * Otherwise, extract the fields from the class itself. + */ + fields = persistentFieldsValue.get(cl); + + if (fields == null) { + /* Get all of the declared fields for this + * Class. setAccessible on all fields so they + * can be accessed later. Create a temporary + * ObjectStreamField array to hold each + * non-static, non-transient field. Then copy the + * temporary array into an array of the correct + * size once the number of fields is known. + */ + Field[] actualfields = cl.getDeclaredFields(); + + int numFields = 0; + ObjectStreamField[] tempFields = + new ObjectStreamField[actualfields.length]; + for (int i = 0; i < actualfields.length; i++) { + Field fld = actualfields[i] ; + int modifiers = fld.getModifiers(); + if (!Modifier.isStatic(modifiers) && + !Modifier.isTransient(modifiers)) { + // fld.setAccessible(true) ; + tempFields[numFields++] = new ObjectStreamField(fld); + } + } + + fields = new ObjectStreamField[numFields]; + System.arraycopy(tempFields, 0, fields, 0, numFields); + } else { + // For each declared persistent field, look for an actual + // reflected Field. If there is one, make sure it's the correct + // type and cache it in the ObjectStreamClass for that field. + for (int j = fields.length-1; j >= 0; j--) { + try { + Field reflField = cl.getDeclaredField(fields[j].getName()); + if (fields[j].getType() == reflField.getType()) { + reflField.setAccessible(true); + fields[j].setField(reflField); + } else { + Exceptions.self.fieldTypeMismatch( + cl.getName(), + fields[j].getName(), + fields[j].getType(), + reflField.getName(), + reflField.getType() ) ; + } + } catch (NoSuchFieldException e) { + Exceptions.self.noSuchField( e, cl.getName(), + fields[j].getName() ) ; + } + } + } + + return null; + } + }); + + if (fields.length > 1) + Arrays.sort(fields); + + /* Set up field data for use while writing using the API api. */ + computeFieldInfo(); + } + + /* Get the serialVersionUID from the class. + * It uses the access override mechanism so make sure + * the field objects is only used here. + * + * NonSerializable classes have a serialVerisonUID of 0L. + */ + // 6877056 + if (isNonSerializable() || isEnum) { + suid = 0L; + } else { + // Lookup special Serializable members using reflection. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + if (forProxyClass) { + // proxy classes always have serialVersionUID of 0L + suid = 0L; + } else { + try { + final Field f = cl.getDeclaredField("serialVersionUID"); + int mods = f.getModifiers(); + // SerialBug 5: static final SUID should be read + if (Modifier.isStatic(mods) && Modifier.isFinal(mods) ) { + long offset = bridge.staticFieldOffset(f); + suid = bridge.getLong(cl, offset); + // SerialBug 2: should be computed after writeObject + // actualSuid = computeStructuralUID(cl); + } else { + suid = _computeSerialVersionUID(cl); + // SerialBug 2: should be computed after writeObject + // actualSuid = computeStructuralUID(cl); + } + } catch (NoSuchFieldException ex) { + suid = _computeSerialVersionUID(cl); + // SerialBug 2: should be computed after writeObject + // actualSuid = computeStructuralUID(cl); + } + } + + writeReplaceObjectMethod = bridge.writeReplaceForSerialization(cl); + readResolveObjectMethod = bridge.readResolveForSerialization(cl); + + if (externalizable) + cons = bridge.newConstructorForExternalization(cl) ; + else + cons = bridge.newConstructorForSerialization(cl) ; + + if (serializable && !forProxyClass) { + /* Look for the readObject and writeObject methods. ObjectOutputStream will call them as necessary. */ + writeObjectMethod = bridge.writeObjectForSerialization(cl); + readObjectMethod = bridge.readObjectForSerialization(cl); + } + return null; + } + }); + } + + // This call depends on a lot of information computed above! + actualSuid = ObjectStreamClass.computeStructuralUID(this, cl); + + // Part of GlassFish issue 5161: also need the repo id if the + // class is Externalizable. + // If we have a write object method, precompute the + // RMI-IIOP stream format version 2 optional data + // repository ID. + if (hasWriteObject() || isExternalizable()) + rmiiiopOptionalDataRepId = computeRMIIIOPOptionalDataRepId(); + + // This must be done last. + initialized = true; + } + } + + /** + * Java to IDL ptc-02-01-12 1.5.1 + * + * "The rep_id string passed to the start_value method must be + * 'RMI:org.omg.custom.class:hashcode:suid' where class is the + * fully-qualified name of the class whose writeObject method + * is being invoked and hashcode and suid are the class's hashcode + * and SUID." + */ + private String computeRMIIIOPOptionalDataRepId() { + + StringBuffer sbuf = new StringBuffer("RMI:org.omg.custom."); + sbuf.append(RepositoryId.convertToISOLatin1(this.getName())); + sbuf.append(':'); + sbuf.append(this.getActualSerialVersionUIDStr()); + sbuf.append(':'); + sbuf.append(this.getSerialVersionUIDStr()); + + return sbuf.toString(); + } + + /** + * This will return null if there is no writeObject method. + */ + public final String getRMIIIOPOptionalDataRepId() { + return rmiiiopOptionalDataRepId; + } + + /* + * Create an empty ObjectStreamClass for a class about to be read. + * This is separate from read so ObjectInputStream can assign the + * wire handle early, before any nested ObjectStreamClass might + * be read. + */ + ObjectStreamClass(String n, long s) { + name = n; + suid = s; + superclass = null; + } + + public static final synchronized ObjectStreamField[] translateFields( + java.io.ObjectStreamField fields[]) { + return PersistentFieldsValue.translateFields(fields); + } + + /* Compare the base class names of streamName and localName. + * + * @return Return true iff the base class name compare. + * @parameter streamName Fully qualified class name. + * @parameter localName Fully qualified class name. + * @parameter pkgSeparator class names use either '.' or '/'. + * + * Only compare base class name to allow package renaming. + */ + static boolean compareClassNames(String streamName, + String localName, + char pkgSeparator) { + /* compare the class names, stripping off package names. */ + int streamNameIndex = streamName.lastIndexOf(pkgSeparator); + if (streamNameIndex < 0) + streamNameIndex = 0; + + int localNameIndex = localName.lastIndexOf(pkgSeparator); + if (localNameIndex < 0) + localNameIndex = 0; + + return streamName.regionMatches(false, streamNameIndex, + localName, localNameIndex, + streamName.length() - streamNameIndex); + } + + /* + * Compare the types of two class descriptors. + * They match if they have the same class name and suid + */ + final boolean typeEquals(ObjectStreamClass other) { + return (suid == other.suid) && + compareClassNames(name, other.name, '.'); + } + + /* + * Return the superclass descriptor of this descriptor. + */ + final void setSuperclass(ObjectStreamClass s) { + superclass = s; + } + + /* + * Return the superclass descriptor of this descriptor. + */ + final ObjectStreamClass getSuperclass() { + return superclass; + } + + /** + * Return whether the class has a readObject method + */ + final boolean hasReadObject() { + return readObjectMethod != null; + } + + /* + * Return whether the class has a writeObject method + */ + final boolean hasWriteObject() { + return writeObjectMethod != null ; + } + + /** + * Returns when or not this class should be custom + * marshaled (use chunking). This should happen if + * it is Externalizable OR if it or + * any of its superclasses has a writeObject method, + */ + final boolean isCustomMarshaled() { + return (hasWriteObject() || isExternalizable()) + || (superclass != null && superclass.isCustomMarshaled()); + } + + /* + * Return true if all instances of 'this' Externalizable class + * are written in block-data mode from the stream that 'this' was read + * from.

    + * + * In JDK 1.1, all Externalizable instances are not written + * in block-data mode. + * In JDK 1.2, all Externalizable instances, by default, are written + * in block-data mode and the Externalizable instance is terminated with + * tag TC_ENDBLOCKDATA. Change enabled the ability to skip Externalizable + * instances. + * + * IMPLEMENTATION NOTE: + * This should have been a mode maintained per stream; however, + * for compatibility reasons, it was only possible to record + * this change per class. All Externalizable classes within + * a given stream should either have this mode enabled or + * disabled. This is enforced by not allowing the PROTOCOL_VERSION + * of a stream to he changed after any objects have been written. + * + * @see ObjectOuputStream#useProtocolVersion + * @see ObjectStreamConstants#PROTOCOL_VERSION_1 + * @see ObjectStreamConstants#PROTOCOL_VERSION_2 + * + * @since JDK 1.2 + */ + boolean hasExternalizableBlockDataMode() { + return hasExternalizableBlockData; + } + + /** + * Creates a new instance of the represented class. If the class is + * externalizable, invokes its public no-arg constructor; otherwise, if the + * class is serializable, invokes the no-arg constructor of the first + * non-serializable superclass. Throws UnsupportedOperationException if + * this class descriptor is not associated with a class, if the associated + * class is non-serializable or if the appropriate no-arg constructor is + * inaccessible/unavailable. + */ + Object newInstance() + throws InstantiationException, InvocationTargetException, + UnsupportedOperationException + { + if (cons != null) { + try { + return cons.newInstance(new Object[0]); + } catch (IllegalAccessException ex) { + // should not occur, as access checks have been suppressed + InternalError ie = new InternalError(); + ie.initCause( ex ) ; + throw ie ; + } + } else { + throw new UnsupportedOperationException(); + } + } + + /* + * Get the Serializability of the class. + */ + boolean isSerializable() { + return serializable; + } + + /* + * Get the externalizability of the class. + */ + boolean isExternalizable() { + return externalizable; + } + + boolean isNonSerializable() { + return ! (externalizable || serializable); + } + + /* + * Calculate the size of the array needed to store primitive data and the + * number of object references to read when reading from the input + * stream. + */ + private void computeFieldInfo() { + primBytes = 0; + objFields = 0; + + for (int i = 0; i < fields.length; i++ ) { + switch (fields[i].getTypeCode()) { + case 'B': + case 'Z': + primBytes += 1; + break; + case 'C': + case 'S': + primBytes += 2; + break; + + case 'I': + case 'F': + primBytes += 4; + break; + case 'J': + case 'D' : + primBytes += 8; + break; + + case 'L': + case '[': + objFields += 1; + break; + } + } + } + + private static void msg( String str ) + { + System.out.println( str ) ; + } + + /* JDK 1.5 has introduced some new modifier bits (such as SYNTHETIC) + * that can affect the SVUID computation (see bug 4897937). These bits + * must be ignored, as otherwise interoperability with ORBs in earlier + * JDK versions can be compromised. I am adding these masks for this + * purpose as discussed in the CCC for this bug (see http://ccc.sfbay/4897937). + */ + + public static final int CLASS_MASK = Modifier.PUBLIC | Modifier.FINAL | + Modifier.INTERFACE | Modifier.ABSTRACT ; + public static final int FIELD_MASK = Modifier.PUBLIC | Modifier.PRIVATE | + Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | + Modifier.TRANSIENT | Modifier.VOLATILE ; + public static final int METHOD_MASK = Modifier.PUBLIC | Modifier.PRIVATE | + Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | + Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.ABSTRACT | + Modifier.STRICT ; + + /* + * Compute a hash for the specified class. Incrementally add + * items to the hash accumulating in the digest stream. + * Fold the hash into a long. Use the SHA secure hash function. + */ + private static long _computeSerialVersionUID(Class cl) { + if (DEBUG_SVUID) + msg( "Computing SerialVersionUID for " + cl ) ; + ByteArrayOutputStream devnull = new ByteArrayOutputStream(512); + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( cl ) ; + + long h = 0; + try { + MessageDigest md = MessageDigest.getInstance("SHA"); + DigestOutputStream mdo = new DigestOutputStream(devnull, md); + DataOutputStream data = new DataOutputStream(mdo); + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + cl.getName() + "\" )" ) ; + data.writeUTF(cl.getName()); + + int classaccess = cl.getModifiers(); + classaccess &= (Modifier.PUBLIC | Modifier.FINAL | + Modifier.INTERFACE | Modifier.ABSTRACT); + + /* Workaround for javac bug that only set ABSTRACT for + * interfaces if the interface had some methods. + * The ABSTRACT bit reflects that the number of methods > 0. + * This is required so correct hashes can be computed + * for existing class files. + * Previously this hack was previously present in the VM. + */ + Method[] method = cl.getDeclaredMethods(); + if ((classaccess & Modifier.INTERFACE) != 0) { + classaccess &= (~Modifier.ABSTRACT); + if (method.length > 0) { + classaccess |= Modifier.ABSTRACT; + } + } + + // Mask out any post-1.4 attributes + classaccess &= CLASS_MASK ; + + if (DEBUG_SVUID) + msg( "\twriteInt( " + classaccess + " ) " ) ; + data.writeInt(classaccess); + + /* + * Get the list of interfaces supported, + * Accumulate their names their names in Lexical order + * and add them to the hash + */ + if (!cinfo.isArray()) { + /* In 1.2fcs, getInterfaces() was modified to return + * {java.lang.Cloneable, java.io.Serializable} when + * called on array classes. These values would upset + * the computation of the hash, so we explicitly omit + * them from its computation. + */ + + Class interfaces[] = cl.getInterfaces(); + Arrays.sort(interfaces, compareClassByName); + + for (int i = 0; i < interfaces.length; i++) { + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + interfaces[i].getName() + "\" ) " ) ; + data.writeUTF(interfaces[i].getName()); + } + } + + /* Sort the field names to get a deterministic order */ + Field[] field = cl.getDeclaredFields(); + Arrays.sort(field, compareMemberByName); + + for (int i = 0; i < field.length; i++) { + Field f = field[i]; + + /* Include in the hash all fields except those that are + * private transient and private static. + */ + int m = f.getModifiers(); + if (Modifier.isPrivate(m) && + (Modifier.isTransient(m) || Modifier.isStatic(m))) + continue; + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + f.getName() + "\" ) " ) ; + data.writeUTF(f.getName()); + + // Mask out any post-1.4 bits + m &= FIELD_MASK ; + + if (DEBUG_SVUID) + msg( "\twriteInt( " + m + " ) " ) ; + data.writeInt(m); + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + getSignature(f.getType()) + "\" ) " ) ; + data.writeUTF(getSignature(f.getType())); + } + + if (bridge.hasStaticInitializerForSerialization(cl)) { + if (DEBUG_SVUID) + msg( "\twriteUTF( \"\" ) " ) ; + data.writeUTF(""); + + if (DEBUG_SVUID) + msg( "\twriteInt( " + Modifier.STATIC + " )" ) ; + data.writeInt(Modifier.STATIC); // TBD: what modifiers does it have + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"()V\" )" ) ; + data.writeUTF("()V"); + } + + /* + * Get the list of constructors including name and signature + * Sort lexically, add all except the private constructors + * to the hash with their access flags + */ + + MethodSignature[] constructors = + MethodSignature.removePrivateAndSort(cl.getDeclaredConstructors()); + for (int i = 0; i < constructors.length; i++) { + MethodSignature c = constructors[i]; + String mname = ""; + String desc = c.signature; + desc = desc.replace('/', '.'); + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + mname + "\" )" ) ; + data.writeUTF(mname); + + // mask out post-1.4 modifiers + int modifier = c.member.getModifiers() & METHOD_MASK ; + + if (DEBUG_SVUID) + msg( "\twriteInt( " + modifier + " ) " ) ; + data.writeInt( modifier ) ; + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + desc+ "\" )" ) ; + data.writeUTF(desc); + } + + /* Include in the hash all methods except those that are + * private transient and private static. + */ + MethodSignature[] methods = + MethodSignature.removePrivateAndSort(method); + for (int i = 0; i < methods.length; i++ ) { + MethodSignature m = methods[i]; + String desc = m.signature; + desc = desc.replace('/', '.'); + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + m.member.getName()+ "\" )" ) ; + data.writeUTF(m.member.getName()); + + // mask out post-1.4 modifiers + int modifier = m.member.getModifiers() & METHOD_MASK ; + + if (DEBUG_SVUID) + msg( "\twriteInt( " + modifier + " ) " ) ; + data.writeInt( modifier ) ; + + if (DEBUG_SVUID) + msg( "\twriteUTF( \"" + desc + "\" )" ) ; + data.writeUTF(desc); + } + + /* Compute the hash value for this class. + * Use only the first 64 bits of the hash. + */ + data.flush(); + byte hasharray[] = md.digest(); + for (int i = 0; i < Math.min(8, hasharray.length); i++) { + h += (long)(hasharray[i] & 255) << (i * 8); + } + } catch (IOException ignore) { + /* can't happen, but be deterministic anyway. */ + h = -1; + } catch (NoSuchAlgorithmException complain) { + SecurityException se = new SecurityException() ; + se.initCause( complain ) ; + throw se ; + } + + return h; + } + + private static long computeStructuralUID( + com.sun.corba.ee.impl.io.ObjectStreamClass osc, Class cl) { + + ByteArrayOutputStream devnull = new ByteArrayOutputStream(512); + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( cl ) ; + + long h = 0; + try { + if (!cinfo.isASerializable(cl) || cinfo.isInterface()) { + return 0; + } + + if (cinfo.isAExternalizable(cl)) { + return 1; + } + + MessageDigest md = MessageDigest.getInstance("SHA"); + DigestOutputStream mdo = new DigestOutputStream(devnull, md); + DataOutputStream data = new DataOutputStream(mdo); + + // Get SUID of parent + Class parent = cl.getSuperclass(); + if ((parent != null)) + // SerialBug 1; acc. to spec the one for + // java.lang.object + // should be computed and put + // && (parent != java.lang.Object.class)) + { + data.writeLong(computeStructuralUID(lookup(parent), parent)); + } + + if (osc.hasWriteObject()) + data.writeInt(2); + else + data.writeInt(1); + + // CORBA formal 00-11-03 10.6.2: For each field of the + // class that is mapped to IDL, sorted lexicographically + // by Java field name, in increasing order... + ObjectStreamField[] field = osc.getFields(); + if (field.length > 1) { + Arrays.sort(field, compareObjStrFieldsByName); + } + + // ...Java field name in UTF encoding, field + // descriptor, as defined by the JVM spec... + for (int i = 0; i < field.length; i++) { + data.writeUTF(field[i].getName()); + data.writeUTF(field[i].getSignature()); + } + + /* Compute the hash value for this class. + * Use only the first 64 bits of the hash. + */ + data.flush(); + byte hasharray[] = md.digest(); + // int minimum = Math.min(8, hasharray.length); + // SerialBug 3: SHA computation is wrong; for loop reversed + //for (int i = minimum; i > 0; i--) + for (int i = 0; i < Math.min(8, hasharray.length); i++) { + h += (long)(hasharray[i] & 255) << (i * 8); + } + } catch (IOException ignore) { + /* can't happen, but be deterministic anyway. */ + h = -1; + } catch (NoSuchAlgorithmException complain) { + SecurityException se = new SecurityException(); + se.initCause( complain ) ; + throw se ; + } + return h; + } + + /** + * Compute the JVM signature for the class. + */ + static String getSignature(Class clazz) { + String type = null; + if (ClassInfoCache.get( clazz ).isArray()) { + Class cl = clazz; + int dimensions = 0; + while (ClassInfoCache.get( cl ).isArray()) { + dimensions++; + cl = cl.getComponentType(); + } + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < dimensions; i++) { + sb.append("["); + } + sb.append(getSignature(cl)); + type = sb.toString(); + } else if (clazz.isPrimitive()) { + if (clazz == Integer.TYPE) { + type = "I"; + } else if (clazz == Byte.TYPE) { + type = "B"; + } else if (clazz == Long.TYPE) { + type = "J"; + } else if (clazz == Float.TYPE) { + type = "F"; + } else if (clazz == Double.TYPE) { + type = "D"; + } else if (clazz == Short.TYPE) { + type = "S"; + } else if (clazz == Character.TYPE) { + type = "C"; + } else if (clazz == Boolean.TYPE) { + type = "Z"; + } else if (clazz == Void.TYPE) { + type = "V"; + } + } else { + type = "L" + clazz.getName().replace('.', '/') + ";"; + } + return type; + } + + /* + * Compute the JVM method descriptor for the method. + */ + static String getSignature(Method meth) { + StringBuffer sb = new StringBuffer(); + + sb.append("("); + + Class[] params = meth.getParameterTypes(); // avoid clone + for (int j = 0; j < params.length; j++) { + sb.append(getSignature(params[j])); + } + sb.append(")"); + sb.append(getSignature(meth.getReturnType())); + return sb.toString(); + } + + /* + * Compute the JVM constructor descriptor for the constructor. + */ + static String getSignature(Constructor cons) { + StringBuffer sb = new StringBuffer(); + + sb.append("("); + + Class[] params = cons.getParameterTypes(); // avoid clone + for (int j = 0; j < params.length; j++) { + sb.append(getSignature(params[j])); + } + sb.append(")V"); + return sb.toString(); + } + + /* + * Cache of Class -> ClassDescriptor Mappings. + */ + static private final SoftCache,ObjectStreamClass> descriptorFor = + new SoftCache,ObjectStreamClass>() ; + + /* + * The name of this descriptor + */ + private String name; + + /* + * The descriptor of the supertype. + */ + private ObjectStreamClass superclass; + + /* + * Flags for Serializable and Externalizable. + */ + private boolean serializable; + private boolean externalizable; + + /* + * Array of persistent fields of this class, sorted by + * type and name. + */ + private ObjectStreamField[] fields; + + /* + * Class that is a descriptor for in this virtual machine. + */ + private Class ofClass; + + /* + * True if descriptor for a proxy class. + */ + boolean forProxyClass; + + + /* + * SerialVersionUID for this class. + */ + private long suid = kDefaultUID; + private String suidStr = null; + + /* + * Actual (computed) SerialVersionUID for this class. + */ + private long actualSuid = kDefaultUID; + private String actualSuidStr = null; + + /* + * The total number of bytes of primitive fields. + * The total number of object fields. + */ + int primBytes; + int objFields; + + /** + * Flag indicating whether or not this instance has + * successfully completed initialization. This is to + * try to fix bug 4373844. Working to move to + * reusing java.io.ObjectStreamClass for JDK 1.5. + */ + private boolean initialized = false; + + /* Internal lock object. */ + private final Object lock = new Object(); + + /* In JDK 1.1, external data was not written in block mode. + * As of JDK 1.2, external data is written in block data mode. This + * flag enables JDK 1.2 to be able to read JDK 1.1 written external data. + * + * @since JDK 1.2 + */ + private boolean hasExternalizableBlockData; + + private MethodHandle writeObjectMethod; + private MethodHandle readObjectMethod; + private transient MethodHandle writeReplaceObjectMethod; + private transient MethodHandle readResolveObjectMethod; + private Constructor cons ; + + /** + * Beginning in Java to IDL ptc/02-01-12, RMI-IIOP has a + * stream format version 2 which puts a fake valuetype around + * a Serializable's optional custom data. This valuetype has + * a special repository ID made from the Serializable's + * information which we are pre-computing and + * storing here. + */ + private String rmiiiopOptionalDataRepId = null; + + /** use serialVersionUID from JDK 1.1. for interoperability */ + private static final long serialVersionUID = -6120832682080437368L; + + /** + * Set serialPersistentFields of a Serializable class to this value to + * denote that the class has no Serializable fields. + */ + public static final ObjectStreamField[] NO_FIELDS = + new ObjectStreamField[0]; + + /* + * Comparator object for Classes and Interfaces + */ + private static Comparator> compareClassByName = + new CompareClassByName(); + + private static class CompareClassByName + implements Comparator> { + + public int compare(Class c1, Class c2) { + return c1.getName().compareTo(c2.getName()); + } + } + + /** + * Comparator for ObjectStreamFields by name + */ + private final static Comparator compareObjStrFieldsByName + = new CompareObjStrFieldsByName(); + + private static class CompareObjStrFieldsByName + implements Comparator { + + public int compare(ObjectStreamField o1, ObjectStreamField o2) { + return o1.getName().compareTo(o2.getName()); + } + } + + /* + * Comparator object for Members, Fields, and Methods + */ + private static Comparator compareMemberByName = + new CompareMemberByName(); + + private static class CompareMemberByName + implements Comparator { + + public int compare(Member o1, Member o2) { + String s1 = o1.getName(); + String s2 = o2.getName(); + + if ((o1 instanceof Method) && (o2 instanceof Method)) { + s1 += getSignature((Method)o1); + s2 += getSignature((Method)o2); + } else if ((o1 instanceof Constructor) && (o2 instanceof Constructor)) { + s1 += getSignature((Constructor)o1); + s2 += getSignature((Constructor)o2); + } + return s1.compareTo(s2); + } + } + + /* It is expensive to recompute a method or constructor signature + many times, so compute it only once using this data structure. */ + private static class MethodSignature + implements Comparator { + + Member member; + String signature; // cached parameter signature + + /* Given an array of Method or Constructor members, + return a sorted array of the non-private members.*/ + /* A better implementation would be to implement the returned data + structure as an insertion sorted link list.*/ + static MethodSignature[] removePrivateAndSort(Member[] m) { + int numNonPrivate = 0; + for (int i = 0; i < m.length; i++) { + if (! Modifier.isPrivate(m[i].getModifiers())) { + numNonPrivate++; + } + } + MethodSignature[] cm = new MethodSignature[numNonPrivate]; + int cmi = 0; + for (int i = 0; i < m.length; i++) { + if (! Modifier.isPrivate(m[i].getModifiers())) { + cm[cmi] = new MethodSignature(m[i]); + cmi++; + } + } + if (cmi > 0) + Arrays.sort(cm, cm[0]); + return cm; + } + + /* Assumes that o1 and o2 are either both methods + or both constructors.*/ + public int compare(MethodSignature c1, MethodSignature c2) { + /* Arrays.sort calls compare when o1 and o2 are equal.*/ + if (c1 == c2) + return 0; + + int result; + if (isConstructor()) { + result = c1.signature.compareTo(c2.signature); + } else { // is a Method. + result = c1.member.getName().compareTo(c2.member.getName()); + if (result == 0) + result = c1.signature.compareTo(c2.signature); + } + return result; + } + + private boolean isConstructor() { + return member instanceof Constructor; + } + + private MethodSignature(Member m) { + member = m; + if (isConstructor()) { + signature = ObjectStreamClass.getSignature((Constructor)m); + } else { + signature = ObjectStreamClass.getSignature((Method)m); + } + } + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamClassCorbaExt.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamClassCorbaExt.java new file mode 100644 index 000000000..3c63c7d84 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamClassCorbaExt.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import java.security.AccessController; +import java.security.PrivilegedExceptionAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedAction; + +import java.lang.reflect.Modifier; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +import com.sun.corba.ee.impl.misc.ORBUtility ; + +// This file contains some utility methods that +// originally were in the OSC in the RMI-IIOP +// code delivered by IBM. They don't make +// sense there, and hence have been put +// here so that they can be factored out in +// an attempt to eliminate redundant code from +// ObjectStreamClass. Eventually the goal is +// to move to java.io.ObjectStreamClass, and +// java.io.ObjectStreamField. + +// class is package private for security reasons + +class ObjectStreamClassCorbaExt { + + /** + * Return true, iff, + * + * 1. 'cl' is an interface, and + * 2. 'cl' and all its ancestors do not implement java.rmi.Remote, and + * 3. if 'cl' has no methods (including those of its ancestors), or, + * if all the methods (including those of its ancestors) throw an + * exception that is atleast java.rmi.RemoteException or one of + * java.rmi.RemoteException's super classes. + */ + static final boolean isAbstractInterface(Class cl) { + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( cl ) ; + if (!cinfo.isInterface() || cinfo.isARemote(cl)) { + return false; + } + + Method[] methods = cl.getMethods(); + for (int i = 0; i < methods.length; i++) { + Class exceptions[] = methods[i].getExceptionTypes(); + boolean exceptionMatch = false; + for (int j = 0; (j < exceptions.length) && !exceptionMatch; j++) { + if ((java.rmi.RemoteException.class == exceptions[j]) || + (java.lang.Throwable.class == exceptions[j]) || + (java.lang.Exception.class == exceptions[j]) || + (java.io.IOException.class == exceptions[j])) { + exceptionMatch = true; + } + } + if (!exceptionMatch) { + return false; + } + } + + return true; + } + + // Common collisions (same length): + // java.lang.String + // java.math.BigDecimal + // java.math.BigInteger + private static final String objectString = "Ljava/lang/Object;" ; + private static final String serializableString = "Ljava/io/Serializable;" ; + private static final String externalizableString = "Ljava/io/Externalizable;" ; + + // Note that these 3 lengths are different! + private static final int objectLength = objectString.length() ; + private static final int serializableLength = serializableString.length() ; + private static final int externalizableLength = externalizableString.length() ; + + private static final boolean debugIsAny = false ; + + /* + * Returns TRUE if type is 'any'. + * This is in the marshaling path, so we want it to run as + * fast as possible. + */ + static final boolean isAny(String typeString) { + if (debugIsAny) { + ORBUtility.dprint( + ObjectStreamClassCorbaExt.class.getName(), + "IsAny: typeString = " + typeString ) ; + } + + int length = typeString.length() ; + + if (length == objectLength) { + // Note that java.lang.String occurs a lot, and has the + // same length as java.lang.Object! + if (typeString.charAt(length-2) == 't') + return objectString.equals( typeString ) ; + else + return false ; + } + + if (length == serializableLength) { + // java.math.BigInteger and java.math.BigDecimal have the same + // length as java.io.Serializable + if (typeString.charAt(length-2) == 'e') + return serializableString.equals( typeString ) ; + else + return false ; + } + + if (length == externalizableLength) + return externalizableString.equals( typeString ) ; + + return false ; + } + + private static final Method[] getDeclaredMethods(final Class clz) { + return AccessController.doPrivileged( + new PrivilegedAction() { + public Method[] run() { + return clz.getDeclaredMethods(); + } + } + ); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamField.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamField.java new file mode 100644 index 000000000..202ae63ce --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ObjectStreamField.java @@ -0,0 +1,230 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import com.sun.corba.ee.impl.misc.ClassInfoCache; +import org.glassfish.pfl.basic.reflection.Bridge; + +import java.lang.reflect.Field; +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * A description of a field in a serializable class. + * A array of these is used to declare the persistent fields of + * a class. + * + */ +public class ObjectStreamField implements Comparable +{ + private static final Bridge bridge = + AccessController.doPrivileged( + new PrivilegedAction() { + public Bridge run() { + return Bridge.get() ; + } + } + ) ; + + // Create a named field with the specified type. + public ObjectStreamField(String n, Class clazz) { + name = n; + this.clazz = clazz; + cinfo = ClassInfoCache.get( clazz ) ; + + // Compute the typecode for easy switching + if (clazz.isPrimitive()) { + if (clazz == Integer.TYPE) { + type = 'I'; + } else if (clazz == Byte.TYPE) { + type = 'B'; + } else if (clazz == Long.TYPE) { + type = 'J'; + } else if (clazz == Float.TYPE) { + type = 'F'; + } else if (clazz == Double.TYPE) { + type = 'D'; + } else if (clazz == Short.TYPE) { + type = 'S'; + } else if (clazz == Character.TYPE) { + type = 'C'; + } else if (clazz == Boolean.TYPE) { + type = 'Z'; + } + } else if (cinfo.isArray()) { + type = '['; + typeString = ObjectStreamClass.getSignature(clazz); + } else { + type = 'L'; + typeString = ObjectStreamClass.getSignature(clazz); + } + + if (typeString != null) + signature = typeString; + else + signature = String.valueOf(type); + + } + + public ObjectStreamField(Field field) { + this(field.getName(), field.getType()); + setField( field ) ; + } + + /** + * Get the name of this field. + */ + public String getName() { + return name; + } + + public ClassInfoCache.ClassInfo getClassInfo() { + return cinfo ; + } + + /** + * Get the type of the field. + */ + public Class getType() { + if (clazz != null) + return clazz; + switch (type) { + case 'B': clazz = Byte.TYPE; + break; + case 'C': clazz = Character.TYPE; + break; + case 'S': clazz = Short.TYPE; + break; + case 'I': clazz = Integer.TYPE; + break; + case 'J': clazz = Long.TYPE; + break; + case 'F': clazz = Float.TYPE; + break; + case 'D': clazz = Double.TYPE; + break; + case 'Z': clazz = Boolean.TYPE; + break; + case '[': + case 'L': + clazz = Object.class; + break; + } + + return clazz; + } + + public char getTypeCode() { + return type; + } + + public String getTypeString() { + return typeString; + } + + Field getField() { + return field; + } + + void setField(Field field) { + this.field = field; + this.fieldID = bridge.objectFieldOffset( field ) ; + } + + + /** + * test if this field is a primitive or not. + */ + public boolean isPrimitive() { + return (type != '[' && type != 'L'); + } + + /** + * Compare this with another ObjectStreamField. + * return -1 if this is smaller, 0 if equal, 1 if greater + * types that are primitives are "smaller" than objects. + * if equal, the names are compared. + */ + public int compareTo(Object o) { + ObjectStreamField f2 = (ObjectStreamField)o; + boolean thisprim = (this.typeString == null); + boolean otherprim = (f2.typeString == null); + + if (thisprim != otherprim) { + return (thisprim ? -1 : 1); + } + return this.name.compareTo(f2.name); + } + + /** + * Compare the types of two class descriptors. + * The match if they have the same primitive types. + * or if they are both objects and the object types match. + */ + public boolean typeEquals(ObjectStreamField other) { + if (other == null || type != other.type) + return false; + + /* Return true if the primitive types matched */ + if (typeString == null && other.typeString == null) + return true; + + return ObjectStreamClass.compareClassNames(typeString, + other.typeString, + '/'); + } + + /* Returns the signature of the Field. + * + */ + public String getSignature() { + + return signature; + + } + + /** + * Return a string describing this field. + */ + public String toString() { + if (typeString != null) + return typeString + " " + name; + else + return type + " " + name; + } + + public Class getClazz() { + return clazz; + } + + /* Returns the Field ID + * + */ + public long getFieldID() { + return fieldID ; + } + + private String name; // the name of the field + private char type; // type first byte of the type signature + private Field field; // Reflected field + private String typeString; // iff object, typename + private Class clazz; // the type of this field, if has been resolved + private ClassInfoCache.ClassInfo cinfo ; + + // the next 2 things are RMI-IIOP specific, it can be easily + // removed, if we can figure out all place where there are dependencies + // to this. Signature is esentially equal to typestring. Then + // essentially we can use the java.io.ObjectStreamField as such. + + private String signature; // the signature of the field + private long fieldID = Bridge.INVALID_FIELD_OFFSET ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/OptionalDataException.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/OptionalDataException.java new file mode 100644 index 000000000..c04ac1083 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/OptionalDataException.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +/** + * Unexpected data appeared in an ObjectInputStream trying to read + * an Object. + * This exception occurs when the stream contains primitive data + * instead of the object expected by readObject. + * The eof flag in the exception is true to indicate that no more + * primitive data is available. + * The count field contains the number of bytes available to read. + * + * @author unascribed + * @version 1.7, 11/02/98 + * @since JDK1.1 + */ +public class OptionalDataException extends java.io.IOException { + /* + * Create an OptionalDataException with a length. + */ + OptionalDataException(int len) { + eof = false; + length = len; + } + + /* + * Create an OptionalDataException signifing no + * more primitive data is available. + */ + OptionalDataException(boolean end) { + length = 0; + eof = end; + } + + /** + * The number of bytes of primitive data available to be read + * in the current buffer. + */ + public int length; + + /** + * True if there is no more data in the buffered part of the stream. + */ + public boolean eof; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/OutputStreamHook.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/OutputStreamHook.java new file mode 100644 index 000000000..6c2578be4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/OutputStreamHook.java @@ -0,0 +1,355 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.ObjectOutput; +import java.util.Map; +import java.util.HashMap; + +import com.sun.corba.ee.spi.trace.StreamFormatVersion; + +@StreamFormatVersion +public abstract class OutputStreamHook extends ObjectOutputStream +{ + private HookPutFields putFields = null; + + /** + * Since ObjectOutputStream.PutField methods specify no exceptions, + * we are not checking for null parameters on put methods. + */ + private class HookPutFields extends ObjectOutputStream.PutField { + private Map fields = new HashMap(); + + /** + * Put the value of the named boolean field into the persistent field. + */ + public void put(String name, boolean value){ + fields.put(name, Boolean.valueOf(value)); + } + + /** + * Put the value of the named char field into the persistent fields. + */ + public void put(String name, char value){ + fields.put(name, Character.valueOf(value)); + } + + /** + * Put the value of the named byte field into the persistent fields. + */ + public void put(String name, byte value){ + fields.put(name, Byte.valueOf(value)); + } + + /** + * Put the value of the named short field into the persistent fields. + */ + public void put(String name, short value){ + fields.put(name, Short.valueOf(value)); + } + + /** + * Put the value of the named int field into the persistent fields. + */ + public void put(String name, int value){ + fields.put(name, Integer.valueOf(value)); + } + + /** + * Put the value of the named long field into the persistent fields. + */ + public void put(String name, long value){ + fields.put(name, Long.valueOf(value)); + } + + /** + * Put the value of the named float field into the persistent fields. + * + */ + public void put(String name, float value){ + fields.put(name, Float.valueOf(value)); + } + + /** + * Put the value of the named double field into the persistent field. + */ + public void put(String name, double value){ + fields.put(name, Double.valueOf(value)); + } + + /** + * Put the value of the named Object field into the persistent field. + */ + public void put(String name, Object value){ + fields.put(name, value); + } + + /** + * Write the data and fields to the specified ObjectOutput stream. + */ + public void write(ObjectOutput out) throws IOException { + OutputStreamHook hook = (OutputStreamHook)out; + + ObjectStreamField[] osfields = hook.getFieldsNoCopy(); + + // Write the fields to the stream in the order + // provided by the ObjectStreamClass. (They should + // be sorted appropriately already.) + for (int i = 0; i < osfields.length; i++) { + + Object value = fields.get(osfields[i].getName()); + + hook.writeField(osfields[i], value); + } + } + } + + abstract void writeField(ObjectStreamField field, Object value) throws IOException; + + public OutputStreamHook() + throws java.io.IOException { + super(); + + } + + @StreamFormatVersion + @Override + public void defaultWriteObject() throws IOException { + writeObjectState.defaultWriteObject(this); + + defaultWriteObjectDelegate(); + } + + public abstract void defaultWriteObjectDelegate(); + + @Override + public ObjectOutputStream.PutField putFields() + throws IOException { + putFields = new HookPutFields(); + return putFields; + } + + // Stream format version, saved/restored during recursive calls + protected byte streamFormatVersion = 1; + + // Return the stream format version currently being used + // to serialize an object + public byte getStreamFormatVersion() { + return streamFormatVersion; + } + + abstract ObjectStreamField[] getFieldsNoCopy(); + + // User uses PutFields to simulate default data. + // See java.io.ObjectOutputStream.PutFields + @Override + @StreamFormatVersion + public void writeFields() + throws IOException { + + writeObjectState.defaultWriteObject(this); + + putFields.write(this); + } + + abstract org.omg.CORBA_2_3.portable.OutputStream getOrbStream(); + + protected abstract void beginOptionalCustomData(); + + + // The following is a State pattern implementation of what + // should be done when a Serializable has a + // writeObject method. This was especially necessary for + // RMI-IIOP stream format version 2. Please see the + // state diagrams in the docs directory of the workspace. + + protected WriteObjectState writeObjectState = NOT_IN_WRITE_OBJECT; + + @StreamFormatVersion + protected void setState(WriteObjectState newState) { + writeObjectState = newState; + } + + protected static final WriteObjectState NOT_IN_WRITE_OBJECT = new DefaultState(); + protected static final WriteObjectState IN_WRITE_OBJECT = new InWriteObjectState(); + protected static final WriteObjectState WROTE_DEFAULT_DATA = new WroteDefaultDataState(); + protected static final WriteObjectState WROTE_CUSTOM_DATA = new WroteCustomDataState(); + + // Description of possible actions + @StreamFormatVersion + protected static class WriteObjectState { + private final String name ; + + public WriteObjectState() { + String className = this.getClass().getName() ; + int index = className.indexOf( '$' ) ; + name = className.substring( index + 1 ) ; + } + + @StreamFormatVersion + public final void enterWriteObject(OutputStreamHook stream) throws IOException { + enterWriteObjectOverride( stream ) ; + } + + @StreamFormatVersion + public final void exitWriteObject(OutputStreamHook stream) throws IOException { + exitWriteObjectOverride( stream ) ; + } + + @StreamFormatVersion + public final void defaultWriteObject(OutputStreamHook stream) throws IOException { + defaultWriteObjectOverride( stream ) ; + } + + @StreamFormatVersion + public final void writeData(OutputStreamHook stream) throws IOException { + writeDataOverride( stream ) ; + } + + public void enterWriteObjectOverride(OutputStreamHook stream) throws IOException {} + public void exitWriteObjectOverride(OutputStreamHook stream) throws IOException {} + public void defaultWriteObjectOverride(OutputStreamHook stream) throws IOException {} + public void writeDataOverride(OutputStreamHook stream) throws IOException {} + + @Override + public String toString() { + return name ; + } + } + + @StreamFormatVersion + protected static class DefaultState extends WriteObjectState { + @Override + @StreamFormatVersion + public void enterWriteObjectOverride(OutputStreamHook stream) throws IOException { + stream.setState(IN_WRITE_OBJECT); + } + } + + @StreamFormatVersion + protected static class InWriteObjectState extends WriteObjectState { + + @Override + @StreamFormatVersion + public void enterWriteObjectOverride(OutputStreamHook stream) throws IOException { + throw Exceptions.self.calledWriteObjectTwice() ; + } + + @Override + @StreamFormatVersion + public void exitWriteObjectOverride(OutputStreamHook stream) throws IOException { + + // We didn't write any data, so write the + // called defaultWriteObject indicator as false + stream.getOrbStream().write_boolean(false); + + // If we're in stream format verison 2, we must + // put the "null" marker to say that there isn't + // any optional data + if (stream.getStreamFormatVersion() == 2) { + stream.getOrbStream().write_long(0); + } + + stream.setState(NOT_IN_WRITE_OBJECT); + } + + @Override + @StreamFormatVersion + public void defaultWriteObjectOverride(OutputStreamHook stream) throws IOException { + + // The writeObject method called defaultWriteObject + // or writeFields, so put the called defaultWriteObject + // indicator as true + stream.getOrbStream().write_boolean(true); + + stream.setState(WROTE_DEFAULT_DATA); + } + + @Override + @StreamFormatVersion + public void writeDataOverride(OutputStreamHook stream) throws IOException { + + // The writeObject method first called a direct + // write operation. Write the called defaultWriteObject + // indicator as false, put the special stream format + // version 2 header (if stream format version 2, of course), + // and write the data + stream.getOrbStream().write_boolean(false); + stream.beginOptionalCustomData(); + stream.setState(WROTE_CUSTOM_DATA); + } + } + + @StreamFormatVersion + protected static class WroteDefaultDataState extends InWriteObjectState { + @Override + @StreamFormatVersion + public void exitWriteObjectOverride(OutputStreamHook stream) throws IOException { + + // We only wrote default data, so if in stream format + // version 2, put the null indicator to say that there + // is no optional data + if (stream.getStreamFormatVersion() == 2) { + stream.getOrbStream().write_long(0); + } + + stream.setState(NOT_IN_WRITE_OBJECT); + } + + @Override + @StreamFormatVersion + public void defaultWriteObjectOverride(OutputStreamHook stream) throws IOException { + throw Exceptions.self.calledDefaultWriteObjectTwice() ; + } + + @Override + @StreamFormatVersion + public void writeDataOverride(OutputStreamHook stream) throws IOException { + + // The writeObject method called a direct write operation. + // If in stream format version 2, put the fake valuetype + // header. + stream.beginOptionalCustomData(); + + stream.setState(WROTE_CUSTOM_DATA); + } + } + + @StreamFormatVersion + protected static class WroteCustomDataState extends InWriteObjectState { + @Override + @StreamFormatVersion + public void exitWriteObjectOverride(OutputStreamHook stream) throws IOException { + // In stream format version 2, we must tell the ORB + // stream to close the fake custom valuetype. + if (stream.getStreamFormatVersion() == 2) { + ((org.omg.CORBA.portable.ValueOutputStream) stream.getOrbStream()).end_value(); + } + + stream.setState(NOT_IN_WRITE_OBJECT); + } + + @Override + @StreamFormatVersion + public void defaultWriteObjectOverride(OutputStreamHook stream) + throws IOException { + throw Exceptions.self.defaultWriteObjectAfterCustomData() ; + } + + // We don't have to do anything special here, just let + // the stream write the data. + @Override + public void writeDataOverride(OutputStreamHook stream) throws IOException {} + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/SharedSecrets.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/SharedSecrets.java new file mode 100644 index 000000000..35e841b3f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/SharedSecrets.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +/** + * A repository of "shared secrets", which are a mechanism for + * calling implementation-private methods in another package without + * using reflection. A package-private class implements a public + * interface and provides the ability to call package-private methods + * within that package; the object implementing that interface is + * provided through a third package to which access is restricted. + * This framework avoids the primary disadvantage of using reflection + * for this purpose, namely the loss of compile-time checking. + */ +public class SharedSecrets { + private static JavaCorbaAccess javaCorbaAccess; + + public static JavaCorbaAccess getJavaCorbaAccess() { + if (javaCorbaAccess == null) { + // Ensure ValueUtility is initialized; we know that that class + // provides the shared secret + try { + Class.forName(ValueUtility.class.getName(), true, ValueUtility.class.getClassLoader()); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + return javaCorbaAccess; + } + + public static void setJavaCorbaAccess(JavaCorbaAccess access) { + javaCorbaAccess = access; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/TypeMismatchException.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/TypeMismatchException.java new file mode 100644 index 000000000..c0fbc2c26 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/TypeMismatchException.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +public class TypeMismatchException extends Error +{ + public TypeMismatchException() + { + super(); + } + + public TypeMismatchException(String mssg) + { + super(mssg); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/ValueHandlerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ValueHandlerImpl.java new file mode 100644 index 000000000..e6cb256f5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ValueHandlerImpl.java @@ -0,0 +1,803 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + + +import java.util.Map ; +import java.io.IOException; + +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.impl.util.Utility; + +import org.omg.CORBA.TCKind; + +import org.omg.CORBA.portable.IndirectionException; +import com.sun.org.omg.SendingContext.CodeBase; +import com.sun.org.omg.SendingContext.CodeBaseHelper; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.logging.UtilSystemException; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +import com.sun.corba.ee.spi.trace.ValueHandlerWrite ; +import com.sun.corba.ee.spi.trace.ValueHandlerRead ; +import java.util.concurrent.ConcurrentHashMap; +import org.glassfish.pfl.basic.logex.OperationTracer; + +@ValueHandlerRead +@ValueHandlerWrite +public final class ValueHandlerImpl implements javax.rmi.CORBA.ValueHandlerMultiFormat { + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + protected static final UtilSystemException utilWrapper = + UtilSystemException.self ; + + // Property to override our maximum stream format version + public static final String FORMAT_VERSION_PROPERTY + = "com.sun.corba.ee.MaxStreamFormatVersion"; + + private static final byte MAX_SUPPORTED_FORMAT_VERSION = (byte)2; + private static final byte STREAM_FORMAT_VERSION_1 = (byte)1; + + // The ValueHandler's maximum stream format version to advertise, + // set in a static initializer. + private static final byte MAX_STREAM_FORMAT_VERSION; + + static { + MAX_STREAM_FORMAT_VERSION = getMaxStreamFormatVersion(); + } + + // Looks for the FORMAT_VERSION_PROPERTY system property + // to allow the user to override our default stream format + // version. Note that this still only allows them to pick + // a supported version (1 through MAX_STREAM_FORMAT_VERSION). + private static byte getMaxStreamFormatVersion() { + + try { + String propValue = AccessController.doPrivileged( + new PrivilegedAction() { + public String run() { + return System.getProperty( + ValueHandlerImpl.FORMAT_VERSION_PROPERTY); + } + }); + + // The property wasn't set + if (propValue == null) { + return MAX_SUPPORTED_FORMAT_VERSION; + } + + byte result = Byte.parseByte(propValue); + + // REVISIT. Just set to MAX_SUPPORTED_FORMAT_VERSION + // or really let the system shutdown with this Error? + if (result < 1 || result > MAX_SUPPORTED_FORMAT_VERSION) { + throw new ExceptionInInitializerError( + "Invalid stream format version: " + result + + ". Valid range is 1 through " + + MAX_SUPPORTED_FORMAT_VERSION); + } + + return result; + + } catch (Exception ex) { + // REVISIT. Swallow this or really let + // the system shutdown with this Error? + + Error err = new ExceptionInInitializerError(ex); + err.initCause( ex ) ; + throw err ; + } + } + + public static final short kRemoteType = 0; + public static final short kAbstractType = 1; + public static final short kValueType = 2; + + // Since the Input/OutputStream is unique to a thread, only one thread + // can ever put a particular key into the stream pairs maps. Multiple threads + // will simultaneously update these maps, so we need a ConcurrentHashMap. + // But we don't need to use putIfAbsent to store into the maps. + private final Map + inputStreamPairs = new ConcurrentHashMap(); + private final Map + outputStreamPairs = new ConcurrentHashMap(); + + // See javax.rmi.CORBA.ValueHandlerMultiFormat + public byte getMaximumStreamFormatVersion() { + return MAX_STREAM_FORMAT_VERSION; + } + + // See javax.rmi.CORBA.ValueHandlerMultiFormat + @ValueHandlerWrite + public void writeValue(org.omg.CORBA.portable.OutputStream out, + java.io.Serializable value, + byte streamFormatVersion) { + + if (streamFormatVersion == 2) { + if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) { + throw omgWrapper.notAValueoutputstream() ; + } + } else if (streamFormatVersion != 1) { + throw omgWrapper.invalidStreamFormatVersion( + streamFormatVersion ) ; + } + + writeValueWithVersion( out, value, streamFormatVersion); + } + + private ValueHandlerImpl(){} + + static ValueHandlerImpl getInstance() { + return new ValueHandlerImpl(); + } + + /** + * Writes the value to the stream using java semantics. + * @param _out The stream to write the value to + * @param value The value to be written to the stream + **/ + @ValueHandlerWrite + public void writeValue(org.omg.CORBA.portable.OutputStream _out, + java.io.Serializable value) { + + writeValueWithVersion( _out, value, STREAM_FORMAT_VERSION_1); + } + + @ValueHandlerWrite + private void writeValueWithVersion( org.omg.CORBA.portable.OutputStream _out, + java.io.Serializable value, byte streamFormatVersion) { + + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) _out; + + IIOPOutputStream jdkToOrbOutputStreamBridge = null; + + jdkToOrbOutputStreamBridge = outputStreamPairs.get(_out); + + if (jdkToOrbOutputStreamBridge == null) { + jdkToOrbOutputStreamBridge = createOutputStream(); + jdkToOrbOutputStreamBridge.setOrbStream(out); + outputStreamPairs.put(_out, jdkToOrbOutputStreamBridge); + } + + try { + jdkToOrbOutputStreamBridge.increaseRecursionDepth(); + writeValueInternal(jdkToOrbOutputStreamBridge, out, + value, streamFormatVersion); + } finally { + if (jdkToOrbOutputStreamBridge.decreaseRecursionDepth() == 0) { + outputStreamPairs.remove(_out); + } + } + } + + @ValueHandlerWrite + private void writeValueInternal( IIOPOutputStream bridge, + org.omg.CORBA_2_3.portable.OutputStream out, + java.io.Serializable value, byte streamFormatVersion) { + + Class clazz = value.getClass(); + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( clazz ) ; + if (cinfo.isArray()) { + write_Array(out, value, clazz.getComponentType()); + } else { + bridge.simpleWriteObject(value, streamFormatVersion); + } + } + + /** + * Reads a value from the stream using java semantics. + * @param _in The stream to read the value from + * @param offset offset position in the stream + * @param clazz The type of the value to be read in + * @param repositoryID repo ID for the value to read + * @param _sender The sending context runtime + * @return The serializable value read from the stream + **/ + @ValueHandlerRead + public java.io.Serializable readValue(org.omg.CORBA.portable.InputStream _in, + int offset, java.lang.Class clazz, String repositoryID, + org.omg.SendingContext.RunTime _sender) { + + java.io.Serializable result = null; + + // Must use narrow rather than a direct cast to a com.sun + // class. Fix for bug 4379539. + CodeBase sender = CodeBaseHelper.narrow(_sender); + + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + + IIOPInputStream jdkToOrbInputStreamBridge = inputStreamPairs.get(_in); + if (jdkToOrbInputStreamBridge == null) { + jdkToOrbInputStreamBridge = createInputStream(); + jdkToOrbInputStreamBridge.setOrbStream(in); + jdkToOrbInputStreamBridge.setSender(sender); + // backward compatability 4365188 + jdkToOrbInputStreamBridge.setValueHandler(this); + inputStreamPairs.put(_in, jdkToOrbInputStreamBridge); + } + + try { + jdkToOrbInputStreamBridge.increaseRecursionDepth(); + result = readValueInternal(jdkToOrbInputStreamBridge, in, offset, + clazz, repositoryID, sender); + } finally { + if (jdkToOrbInputStreamBridge.decreaseRecursionDepth() == 0) { + inputStreamPairs.remove(_in); + } + } + + return result; + } + + @ValueHandlerRead + private java.io.Serializable readValueInternal(IIOPInputStream bridge, + org.omg.CORBA_2_3.portable.InputStream in, int offset, + java.lang.Class clazz, String repositoryID, + com.sun.org.omg.SendingContext.CodeBase sender) { + + java.io.Serializable result = null; + + if (clazz == null) { + // clazz == null indicates an FVD situation for a nonexistant class + if (isArray(repositoryID)){ + read_Array( bridge, in, null, sender, offset); + } else { + bridge.simpleSkipObject( repositoryID, sender); + } + return result; + } + + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( clazz ) ; + if (cinfo.isArray()) { + result = (java.io.Serializable)read_Array( + bridge, in, clazz, sender, offset); + } else { + result = (java.io.Serializable)bridge.simpleReadObject( + clazz, cinfo, repositoryID, sender, offset); + } + + return result; + } + + /** + * Returns the repository ID for the given RMI value Class. + * @param clz The class to return a repository ID for. + * @return the repository ID of the Class. + **/ + public java.lang.String getRMIRepositoryID(java.lang.Class clz) { + return RepositoryId.createForJavaType(clz); + } + + /** + * Indicates whether the given Class performs custom or + * default marshaling. + * @param clz The class to test for custom marshaling. + * @return True if the class performs custom marshaling, false + * if it does not. + **/ + public boolean isCustomMarshaled(java.lang.Class clz) { + return ObjectStreamClass.lookup(clz).isCustomMarshaled(); + } + + /** + * Returns the CodeBase for this ValueHandler. This is used by + * the ORB runtime. The server sends the service context containing + * the IOR for this CodeBase on the first GIOP reply. The clients + * do the same on the first GIOP request. + * @return the SendingContext.CodeBase of this ValueHandler. + **/ + public org.omg.SendingContext.RunTime getRunTimeCodeBase() { + CodeBase codeBase = new FVDCodeBaseImpl(this); + return codeBase; + } + + + // methods supported for backward compatability so that the appropriate + // Rep-id calculations take place based on the ORB version + + /** + * Returns a boolean of whether or not RepositoryId indicates + * FullValueDescriptor. + * used for backward compatability + */ + + public boolean useFullValueDescription(Class clazz, String repositoryID) + throws IOException + { + return RepositoryId.useFullValueDescription(clazz, repositoryID); + } + + public String getClassName(String id) + { + RepositoryId repID = RepositoryId.cache.getId(id); + return repID.getClassName(); + } + + public Class getClassFromType(String id) + throws ClassNotFoundException + { + RepositoryId repId = RepositoryId.cache.getId(id); + return repId.getClassFromType(); + } + + public Class getAnyClassFromType(String id) + throws ClassNotFoundException + { + RepositoryId repId = RepositoryId.cache.getId(id); + return repId.getAnyClassFromType(); + } + + public String createForAnyType(Class cl) + { + return RepositoryId.createForAnyType(cl); + } + + public String getDefinedInId(String id) + { + RepositoryId repId = RepositoryId.cache.getId(id); + return repId.getDefinedInId(); + } + + public String getUnqualifiedName(String id) + { + RepositoryId repId = RepositoryId.cache.getId(id); + return repId.getUnqualifiedName(); + } + + public String getSerialVersionUID(String id) + { + RepositoryId repId = RepositoryId.cache.getId(id); + return repId.getSerialVersionUID(); + } + + + public boolean isAbstractBase(Class clazz) + { + return RepositoryId.isAbstractBase(clazz); + } + + public boolean isSequence(String id) + { + RepositoryId repId = RepositoryId.cache.getId(id); + return repId.isSequence(); + } + + /** + * If the value contains a writeReplace method then the result + * is returned. Otherwise, the value itself is returned. + * @return the true value to marshal on the wire. + **/ + @ValueHandlerWrite + public java.io.Serializable writeReplace(java.io.Serializable value) { + return ObjectStreamClass.lookup(value.getClass()).writeReplace(value); + } + + /** + * Encapsulates writing of Java char arrays so that the 1.3 subclass + * can override it without exposing internals across packages. This + * is a fix for bug 4367783. + */ + @ValueHandlerWrite + private void writeCharArray(org.omg.CORBA_2_3.portable.OutputStream out, + char[] array, + int offset, + int length) + { + out.write_wchar_array(array, offset, length); + } + + @ValueHandlerWrite + private void write_Array(org.omg.CORBA_2_3.portable.OutputStream out, + java.io.Serializable obj, Class type) { + + int i, length; + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( type ) ; + + if (type.isPrimitive()) { + if (type == Integer.TYPE) { + int[] array = (int[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_long_array(array, 0, length); + } else if (type == Byte.TYPE) { + byte[] array = (byte[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_octet_array(array, 0, length); + } else if (type == Long.TYPE) { + long[] array = (long[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_longlong_array(array, 0, length); + } else if (type == Float.TYPE) { + float[] array = (float[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_float_array(array, 0, length); + } else if (type == Double.TYPE) { + double[] array = (double[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_double_array(array, 0, length); + } else if (type == Short.TYPE) { + short[] array = (short[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_short_array(array, 0, length); + } else if (type == Character.TYPE) { + char[] array = (char[])((Object)obj); + length = array.length; + out.write_ulong(length); + writeCharArray(out, array, 0, length); + } else if (type == Boolean.TYPE) { + boolean[] array = (boolean[])((Object)obj); + length = array.length; + out.write_ulong(length); + out.write_boolean_array(array, 0, length); + } else { + throw Exceptions.self.invalidPrimitiveType( + obj.getClass().getName() ) ; + } + } else if (type == java.lang.Object.class) { + Object[] array = (Object[])((Object)obj); + length = array.length; + out.write_ulong(length); + for (i = 0; i < length; i++) { + Util.getInstance().writeAny(out, array[i]); + } + } else { + Object[] array = (Object[])((Object)obj); + length = array.length; + out.write_ulong(length); + int callType = kValueType; + + if (cinfo.isInterface()) { + String className = type.getName(); + + if (cinfo.isARemote(type)) { + // RMI Object reference... + callType = kRemoteType; + } else if (cinfo.isACORBAObject(type)) { + // IDL Object reference... + callType = kRemoteType; + } else if (RepositoryId.isAbstractBase(type)) { + // IDL Abstract Object reference... + callType = kAbstractType; + } else if (ObjectStreamClassCorbaExt.isAbstractInterface(type)) { + callType = kAbstractType; + } + } + + for (i = 0; i < length; i++) { + switch (callType) { + case kRemoteType: + Util.getInstance().writeRemoteObject(out, array[i]); + break; + case kAbstractType: + Util.getInstance().writeAbstractObject(out,array[i]); + break; + case kValueType: + try{ + out.write_value((java.io.Serializable)array[i]); + } catch(ClassCastException cce){ + if (array[i] instanceof java.io.Serializable) { + throw cce; + } else { + Utility.throwNotSerializableForCorba( + array[i].getClass().getName()); + } + } + break; + } + } + } + } + + /** + * Encapsulates reading of Java char arrays so that the 1.3 subclass + * can override it without exposing internals across packages. This + * is a fix for bug 4367783. + */ + @ValueHandlerRead + private void readCharArray(org.omg.CORBA_2_3.portable.InputStream in, + char[] array, + int offset, + int length) + { + in.read_wchar_array(array, offset, length); + } + + @ValueHandlerRead + private java.lang.Object read_Array( IIOPInputStream bridge, + org.omg.CORBA_2_3.portable.InputStream in, + Class sequence, com.sun.org.omg.SendingContext.CodeBase sender, + int offset) + { + try { + // Read length of coming array + int length = in.read_ulong(); + int i; + + if (sequence == null) { + for (i = 0; i < length; i++) { + in.read_value(); + } + + return null; + } + + OperationTracer.startReadArray( sequence.getName(), length ) ; + + Class componentType = sequence.getComponentType(); + Class actualType = componentType; + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( + componentType ) ; + + if (componentType.isPrimitive()) { + if (componentType == Integer.TYPE) { + int[] array = new int[length]; + in.read_long_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Byte.TYPE) { + byte[] array = new byte[length]; + in.read_octet_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Long.TYPE) { + long[] array = new long[length]; + in.read_longlong_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Float.TYPE) { + float[] array = new float[length]; + in.read_float_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Double.TYPE) { + double[] array = new double[length]; + in.read_double_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Short.TYPE) { + short[] array = new short[length]; + in.read_short_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Character.TYPE) { + char[] array = new char[length]; + readCharArray(in, array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else if (componentType == Boolean.TYPE) { + boolean[] array = new boolean[length]; + in.read_boolean_array(array, 0, length); + return ((java.io.Serializable)((Object)array)); + } else { + throw Exceptions.self.invalidPrimitiveComponentType( + sequence.getName()); + } + } else if (componentType == java.lang.Object.class) { + Object[] array = (Object[])java.lang.reflect.Array.newInstance( + componentType, length); + + // Store this object and its beginning position + // since there might be indirections to it while + // it's been unmarshalled. + bridge.activeRecursionMgr.addObject(offset, array); + + for (i = 0; i < length; i++) { + Object objectValue = null; + try { + OperationTracer.readingIndex( i ) ; + objectValue = Util.getInstance().readAny(in); + } catch(IndirectionException cdrie) { + try { + // The CDR stream had never seen the given offset + // before, so check the recursion manager (it will + // throw an IOException if it doesn't have a + // reference, either). + objectValue = bridge.activeRecursionMgr.getObject( + cdrie.offset); + } catch (IOException ie) { + // Translate to a MARSHAL exception since + // ValueHandlers aren't allowed to throw + // IOExceptions + throw utilWrapper.invalidIndirection( ie, + cdrie.offset ) ; + } + } + + array[i] = objectValue; + } + return ((java.io.Serializable)((Object)array)); + } else { + Object[] array = (Object[])java.lang.reflect.Array.newInstance( + componentType, length); + // Store this object and its beginning position + // since there might be indirections to it while + // it's been unmarshalled. + bridge.activeRecursionMgr.addObject(offset, array); + + // Decide what method call to make based on the componentType. + // If it is a componentType for which we need to load a stub, + // convert the componentType to the correct stub type. + + int callType = kValueType; + boolean narrow = false; + + if (cinfo.isInterface()) { + boolean loadStubClass = false; + // String className = componentType.getName(); + + if (cinfo.isARemote(componentType)) { + // RMI Object reference... + callType = kRemoteType; + + // for better performance, load the stub class once + // instead of for each element of the array + loadStubClass = true; + } else if (cinfo.isACORBAObject(componentType)) { + // IDL Object reference... + callType = kRemoteType; + loadStubClass = true; + } else if (RepositoryId.isAbstractBase(componentType)) { + // IDL Abstract Object reference... + callType = kAbstractType; + loadStubClass = true; + } else if (ObjectStreamClassCorbaExt.isAbstractInterface( + componentType)) { + // RMI Abstract Object reference... + callType = kAbstractType; + } + + if (loadStubClass) { + try { + String codebase = Util.getInstance().getCodebase( + componentType); + String repID = RepositoryId.createForAnyType( + componentType); + Class stubType = + Utility.loadStubClass(repID, codebase, + componentType); + actualType = stubType; + } catch (ClassNotFoundException e) { + narrow = true; + } + } else { + narrow = true; + } + } + + for (i = 0; i < length; i++) { + + try { + OperationTracer.readingIndex( i ) ; + + switch (callType) { + case kRemoteType: + if (!narrow) { + array[i] = (Object)in.read_Object(actualType); + } else { + array[i] = Utility.readObjectAndNarrow(in, + actualType); + } + break; + case kAbstractType: + if (!narrow) { + array[i] = in.read_abstract_interface( + actualType); + } else { + array[i] = Utility.readAbstractAndNarrow(in, + actualType); + } + break; + case kValueType: + array[i] = (Object)in.read_value(actualType); + break; + } + } catch(IndirectionException cdrie) { + // The CDR stream had never seen the given offset before, + // so check the recursion manager (it will throw an + // IOException if it doesn't have a reference, either). + try { + array[i] = bridge.activeRecursionMgr.getObject( + cdrie.offset); + } catch (IOException ioe) { + // Translate to a MARSHAL exception since + // ValueHandlers aren't allowed to throw + // IOExceptions + throw utilWrapper.invalidIndirection( ioe, + cdrie.offset ) ; + } + } + + } + + return ((java.io.Serializable)((Object)array)); + } + } finally { + // We've completed deserializing this object. Any + // future indirections will be handled correctly at the + // CDR level. The ActiveRecursionManager only deals with + // objects currently being deserialized. + bridge.activeRecursionMgr.removeObject(offset); + + if (sequence != null) { + OperationTracer.endReadArray() ; + } + } + } + + private boolean isArray(String repId){ + return RepositoryId.cache.getId(repId).isSequence(); + } + + private IIOPOutputStream createOutputStream() { + if (System.getSecurityManager() != null) { + return AccessController.doPrivileged( + new PrivilegedAction() { + public IIOPOutputStream run() { + try { + return new IIOPOutputStream() ; + } catch (IOException exc) { + throw utilWrapper.exceptionInCreateIiopOutputStream( + exc ) ; + } + } + } + ); + } else { + try { + return new IIOPOutputStream() ; + } catch (IOException exc) { + throw utilWrapper.exceptionInCreateIiopOutputStream( exc ) ; + } + } + } + + private IIOPInputStream createInputStream() { + if (System.getSecurityManager() != null) { + return AccessController.doPrivileged( + new PrivilegedAction() { + public IIOPInputStream run() { + try { + return new IIOPInputStream() ; + } catch (IOException exc) { + throw utilWrapper.exceptionInCreateIiopInputStream( + exc ) ; + } + } + } + ); + } else { + try { + return new IIOPInputStream() ; + } catch (IOException exc) { + throw utilWrapper.exceptionInCreateIiopInputStream( exc ) ; + } + } + } + + /** + * Our JDK 1.3 and JDK 1.3.1 behavior subclasses override this. + * The correct behavior is for a Java char to map to a CORBA wchar, + * but our older code mapped it to a CORBA char. + */ + TCKind getJavaCharTCKind() { + return TCKind.tk_wchar; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/io/ValueUtility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ValueUtility.java new file mode 100644 index 000000000..c52c8898c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/io/ValueUtility.java @@ -0,0 +1,463 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription; +import com.sun.org.omg.CORBA.OperationDescription; +import com.sun.org.omg.CORBA.AttributeDescription; +import com.sun.org.omg.CORBA.Initializer; +import org.glassfish.corba.org.omg.CORBA._IDLTypeStub; + +import com.sun.corba.ee.impl.util.RepositoryId; +import org.omg.CORBA.ValueMember; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.TCKind; + +import javax.rmi.CORBA.ValueHandler; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; +import java.lang.reflect.Modifier; +import java.util.Stack; +import org.glassfish.pfl.basic.contain.Pair; + +/** + * Holds utility methods for converting from ObjectStreamClass to + * FullValueDescription and generating typecodes from ObjectStreamClass. + **/ +public class ValueUtility { + + public static final short PRIVATE_MEMBER = 0; + public static final short PUBLIC_MEMBER = 1; + + private static final String primitiveConstants[] = { + null, // tk_null 0 + null, // tk_void 1 + "S", // tk_short 2 + "I", // tk_long 3 + "S", // tk_ushort 4 + "I", // tk_ulong 5 + "F", // tk_float 6 + "D", // tk_double 7 + "Z", // tk_boolean 8 + "C", // tk_char 9 + "B", // tk_octet 10 + null, // tk_any 11 + null, // tk_typecode 12 + null, // tk_principal 13 + null, // tk_objref 14 + null, // tk_struct 15 + null, // tk_union 16 + null, // tk_enum 17 + null, // tk_string 18 + null, // tk_sequence 19 + null, // tk_array 20 + null, // tk_alias 21 + null, // tk_except 22 + "J", // tk_longlong 23 + "J", // tk_ulonglong 24 + "D", // tk_longdouble 25 + "C", // tk_wchar 26 + null, // tk_wstring 27 + null, // tk_fixed 28 + null, // tk_value 29 + null, // tk_value_box 30 + null, // tk_native 31 + null, // tk_abstract_interface 32 + }; + + static { + SharedSecrets.setJavaCorbaAccess(new JavaCorbaAccess() { + @Override + public ValueHandlerImpl newValueHandlerImpl() { + return ValueHandlerImpl.getInstance(); + } + }); + } + + public static String getSignature(ValueMember member) + throws ClassNotFoundException { + + // REVISIT. Can the type be something that is + // non-primitive yet not a value_box, value, or objref? + // If so, should use ObjectStreamClass or throw + // exception. + + if (member.type.kind().value() == TCKind._tk_value_box || + member.type.kind().value() == TCKind._tk_value || + member.type.kind().value() == TCKind._tk_objref) { + Class c = RepositoryId.cache.getId(member.id).getClassFromType(); + return ObjectStreamClass.getSignature(c); + + } else { + + return primitiveConstants[member.type.kind().value()]; + } + + } + + public static FullValueDescription translate(ORB orb, ObjectStreamClass osc, + ValueHandler vh){ + + // Create FullValueDescription + FullValueDescription result = new FullValueDescription(); + Class className = osc.forClass(); + + ValueHandlerImpl vhandler = (com.sun.corba.ee.impl.io.ValueHandlerImpl) vh; + String repId = vhandler.createForAnyType(className); + + // Set FVD name + result.name = vhandler.getUnqualifiedName(repId); + if (result.name == null) + result.name = ""; + + // Set FVD id _REVISIT_ : Manglings + result.id = vhandler.getRMIRepositoryID(className); + if (result.id == null) + result.id = ""; + + // Set FVD is_abstract + result.is_abstract = + ObjectStreamClassCorbaExt.isAbstractInterface(className); + + // Set FVD is_custom + result.is_custom = osc.hasWriteObject() || osc.isExternalizable(); + + // Set FVD defined_in _REVISIT_ : Manglings + result.defined_in = vhandler.getDefinedInId(repId); + if (result.defined_in == null) + result.defined_in = ""; + + // Set FVD version + result.version = vhandler.getSerialVersionUID(repId); + if (result.version == null) + result.version = ""; + + // Skip FVD operations - N/A + result.operations = new OperationDescription[0]; + + // Skip FVD attributed - N/A + result.attributes = new AttributeDescription[0]; + + // Set FVD members + // Maps classes to repositoryIDs strings. + // This is used to detect recursive types. + IdentityKeyValueStack createdIDs = new IdentityKeyValueStack(); + + // Stores all types created for resolving indirect types at the end. + result.members = translateMembers(orb, osc, vh, createdIDs); + + // Skip FVD initializers - N/A + result.initializers = new Initializer[0]; + + Class interfaces[] = osc.forClass().getInterfaces(); + int abstractCount = 0; + + // Skip FVD supported_interfaces + result.supported_interfaces = new String[interfaces.length]; + for (int interfaceIndex = 0; interfaceIndex < interfaces.length; + interfaceIndex++) { + result.supported_interfaces[interfaceIndex] = + vhandler.createForAnyType(interfaces[interfaceIndex]); + + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( + interfaces[interfaceIndex] ) ; + if (!cinfo.isARemote(interfaces[interfaceIndex]) || + (!Modifier.isPublic(interfaces[interfaceIndex].getModifiers()))) + abstractCount++; + } + + // Skip FVD abstract_base_values - N/A + result.abstract_base_values = new String[abstractCount]; + for (int interfaceIndex = 0; interfaceIndex < interfaces.length; + interfaceIndex++) { + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( + interfaces[interfaceIndex] ) ; + if (!cinfo.isARemote(interfaces[interfaceIndex]) || + (!Modifier.isPublic(interfaces[interfaceIndex].getModifiers()))) + result.abstract_base_values[interfaceIndex] = + vhandler.createForAnyType(interfaces[interfaceIndex]); + + } + + result.is_truncatable = false; + + // Set FVD base_value + Class superClass = osc.forClass().getSuperclass(); + if (ClassInfoCache.get( superClass ).isASerializable(superClass)) + result.base_value = vhandler.getRMIRepositoryID(superClass); + else + result.base_value = ""; + + // Set FVD type + //result.type = createTypeCodeForClass(orb, osc.forClass()); + result.type = orb.get_primitive_tc(TCKind.tk_value); + + return result; + } + + private static ValueMember[] translateMembers( ORB orb, + ObjectStreamClass osc, ValueHandler vh, + IdentityKeyValueStack createdIDs) { + + ValueHandlerImpl vhandler = (com.sun.corba.ee.impl.io.ValueHandlerImpl) vh; + ObjectStreamField fields[] = osc.getFields(); + int fieldsLength = fields.length; + ValueMember[] members = new ValueMember[fieldsLength]; + // Note : fields come out of ObjectStreamClass in correct order for + // writing. So, we will create the same order in the members array. + for (int i = 0; i < fieldsLength; i++) { + String valRepId = vhandler.getRMIRepositoryID(fields[i].getClazz()); + members[i] = new ValueMember(); + members[i].name = fields[i].getName(); + + // _REVISIT_ : Manglings + members[i].id = valRepId; + + // _REVISIT_ : Manglings + members[i].defined_in = vhandler.getDefinedInId(valRepId); + + members[i].version = "1.0"; + + // _REVISIT_ : IDLType implementation missing + members[i].type_def = new _IDLTypeStub(); + + if (fields[i].getField() == null) { + // When using serialPersistentFields, the class may + // no longer have an actual Field that corresponds + // to one of the items. The Java to IDL spec + // ptc-00-01-06 1.3.5.6 says that the IDL field + // should be private in this case. + members[i].access = PRIVATE_MEMBER; + } else { + int m = fields[i].getField().getModifiers(); + if (Modifier.isPublic(m)) + members[i].access = PUBLIC_MEMBER; + else + members[i].access = PRIVATE_MEMBER; + } + + switch (fields[i].getTypeCode()) { + case 'B': + members[i].type = orb.get_primitive_tc(TCKind.tk_octet); + break; + case 'C': + members[i].type + = orb.get_primitive_tc(vhandler.getJavaCharTCKind()); + break; + case 'F': + members[i].type = orb.get_primitive_tc(TCKind.tk_float); + break; + case 'D' : + members[i].type = orb.get_primitive_tc(TCKind.tk_double); + break; + case 'I': + members[i].type = orb.get_primitive_tc(TCKind.tk_long); + break; + case 'J': + members[i].type = orb.get_primitive_tc(TCKind.tk_longlong); + break; + case 'S': + members[i].type = orb.get_primitive_tc(TCKind.tk_short); + break; + case 'Z': + members[i].type = orb.get_primitive_tc(TCKind.tk_boolean); + break; + // case '[': + // members[i].type = orb.get_primitive_tc(TCKind.tk_value_box); + // members[i].id = RepositoryId.createForAnyType(fields[i].getType()); + // break; + default: + members[i].type = createTypeCodeForClassInternal(orb, + fields[i].getClazz(), vhandler, createdIDs); + members[i].id = vhandler.createForAnyType(fields[i].getType()); + break; + } // end switch + + } // end for loop + + return members; + } + + private static boolean exists(String str, String strs[]){ + for (int i = 0; i < strs.length; i++) + if (str.equals(strs[i])) + return true; + + return false; + } + + public static boolean isAssignableFrom(String clzRepositoryId, + FullValueDescription type, com.sun.org.omg.SendingContext.CodeBase sender){ + + if (exists(clzRepositoryId, type.supported_interfaces)) + return true; + + if (clzRepositoryId.equals(type.id)) + return true; + + if ((type.base_value != null) && + (!type.base_value.equals(""))) { + FullValueDescription parent = sender.meta(type.base_value); + + return isAssignableFrom(clzRepositoryId, parent, sender); + } + + return false; + } + + public static TypeCode createTypeCodeForClass( ORB orb, java.lang.Class c, + ValueHandler vh) { + + // Maps classes to repositoryIDs strings. + // This is used to detect recursive types. + IdentityKeyValueStack createdIDs = new IdentityKeyValueStack(); + + // Stores all types created for resolving indirect types at the end. + TypeCode tc = createTypeCodeForClassInternal(orb, c, vh, createdIDs); + + return tc; + } + + private static TypeCode createTypeCodeForClassInternal( ORB orb, + java.lang.Class c, ValueHandler vh, IdentityKeyValueStack createdIDs) { + + // This wrapper method is the protection against infinite recursion. + TypeCode tc = null; + String id = createdIDs.get(c); + if (id != null) { + return orb.create_recursive_tc(id); + } else { + id = vh.getRMIRepositoryID(c); + if (id == null) id = ""; + // cache the rep id BEFORE creating a new typecode. + // so that recursive tc can look up the rep id. + createdIDs.push(c, id); + tc = createTypeCodeInternal(orb, c, vh, id, createdIDs); + createdIDs.pop(); + return tc; + } + } + + // Maintains a stack of key-value pairs. Compares elements using == operator. + private static class IdentityKeyValueStack { + Stack,String>> pairs = null ; + + String get(Class key) { + if (pairs == null) { + return null; + } + + for (Pair,String> pair : pairs ) { + if (pair.first() == key) { + return pair.second(); + } + } + + return null; + } + + void push(Class key, String value) { + if (pairs == null) { + pairs = new Stack,String>>(); + } + pairs.push(new Pair,String>(key, value)); + } + + void pop() { + pairs.pop(); + } + } + + private static TypeCode createTypeCodeInternal (ORB orb, java.lang.Class c, + ValueHandler vh, String id, IdentityKeyValueStack createdIDs) { + + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( c ) ; + if (cinfo.isArray()) { + // Arrays - may recurse for multi-dimensional arrays + Class componentClass = c.getComponentType(); + TypeCode embeddedType; + if (componentClass.isPrimitive()) { + embeddedType = ValueUtility.getPrimitiveTypeCodeForClass( orb, + componentClass, vh); + } else { + embeddedType = createTypeCodeForClassInternal(orb, + componentClass, vh, createdIDs); + } + + TypeCode t = orb.create_sequence_tc (0, embeddedType); + return orb.create_value_box_tc (id, "Sequence", t); + } else if ( c == java.lang.String.class ) { + // Strings + TypeCode t = orb.create_string_tc (0); + return orb.create_value_box_tc (id, "StringValue", t); + } else if (cinfo.isARemote(c)) { + return orb.get_primitive_tc(TCKind.tk_objref); + } else if (cinfo.isACORBAObject(c)) { + return orb.get_primitive_tc(TCKind.tk_objref); + } + + // Anything else + + ObjectStreamClass osc = ObjectStreamClass.lookup(c); + + if (osc == null) { + return orb.create_value_box_tc (id, "Value", + orb.get_primitive_tc (TCKind.tk_value)); + } + + // type modifier + // REVISIT truncatable and abstract? + short modifier = (osc.isCustomMarshaled() ? + org.omg.CORBA.VM_CUSTOM.value : org.omg.CORBA.VM_NONE.value); + + // concrete base + TypeCode base = null; + Class superClass = c.getSuperclass(); + if (superClass != null && + ClassInfoCache.get( superClass ).isASerializable( superClass )) { + base = createTypeCodeForClassInternal(orb, superClass, vh, + createdIDs); + } + + // members + ValueMember[] members = translateMembers (orb, osc, vh, createdIDs); + + return orb.create_value_tc(id, c.getName(), modifier, base, members); + } + + public static TypeCode getPrimitiveTypeCodeForClass (ORB orb, + Class c, ValueHandler vh) { + + if (c == Integer.TYPE) { + return orb.get_primitive_tc(TCKind.tk_long); + } else if (c == Byte.TYPE) { + return orb.get_primitive_tc(TCKind.tk_octet); + } else if (c == Long.TYPE) { + return orb.get_primitive_tc(TCKind.tk_longlong); + } else if (c == Float.TYPE) { + return orb.get_primitive_tc(TCKind.tk_float); + } else if (c == Double.TYPE) { + return orb.get_primitive_tc(TCKind.tk_double); + } else if (c == Short.TYPE) { + return orb.get_primitive_tc (TCKind.tk_short); + } else if (c == Character.TYPE) { + return orb.get_primitive_tc( + ((ValueHandlerImpl)vh).getJavaCharTCKind()); + } else if (c == Boolean.TYPE) { + return orb.get_primitive_tc (TCKind.tk_boolean); + } else { + // _REVISIT_ Not sure if this is right. + return orb.get_primitive_tc (TCKind.tk_any); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ByteBuffer.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ByteBuffer.java new file mode 100644 index 000000000..bf80cd193 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ByteBuffer.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + + +public class ByteBuffer { + /** + * The array buffer into which the components of the ByteBuffer are + * stored. The capacity of the ByteBuffer is the length of this array buffer, + * and is at least large enough to contain all the ByteBuffer's elements.

    + * + * Any array elements following the last element in the ByteBuffer are 0. + */ + protected byte elementData[]; + + /** + * The number of valid components in this ByteBuffer object. + * Components elementData[0] through + * elementData[elementCount-1] are the actual items. + * + * @serial + */ + protected int elementCount; + + /** + * The amount by which the capacity of the ByteBuffer is automatically + * incremented when its size becomes greater than its capacity. If + * the capacity increment is less than or equal to zero, the capacity + * of the ByteBuffer is doubled each time it needs to grow. + * + * @serial + */ + protected int capacityIncrement; + + /** + * Constructs an empty ByteBuffer with the specified initial capacity and + * capacity increment. + * + * @param initialCapacity the initial capacity of the ByteBuffer. + * @param capacityIncrement the amount by which the capacity is + * increased when the ByteBuffer overflows. + * @exception IllegalArgumentException if the specified initial capacity + * is negative + */ + public ByteBuffer(int initialCapacity, int capacityIncrement) { + super(); + if (initialCapacity < 0) + throw new IllegalArgumentException("Illegal Capacity: "+ + initialCapacity); + this.elementData = new byte[initialCapacity]; + this.capacityIncrement = capacityIncrement; + } + + /** + * Constructs an empty ByteBuffer with the specified initial capacity and + * with its capacity increment equal to zero. + * + * @param initialCapacity the initial capacity of the ByteBuffer. + * @exception IllegalArgumentException if the specified initial capacity + * is negative + */ + public ByteBuffer(int initialCapacity) { + this(initialCapacity, 0); + } + + /** + * Constructs an empty ByteBuffer so that its internal data array + * has size 10 and its standard capacity increment is + * zero. + */ + public ByteBuffer() { + this(200); + } + + /** + * Trims the capacity of this ByteBuffer to be the ByteBuffer's current + * size. If the capacity of this cector is larger than its current + * size, then the capacity is changed to equal the size by replacing + * its internal data array, kept in the field elementData, + * with a smaller one. An application can use this operation to + * minimize the storage of a ByteBuffer. + */ + public void trimToSize() { + int oldCapacity = elementData.length; + if (elementCount < oldCapacity) { + byte oldData[] = elementData; + elementData = new byte[elementCount]; + System.arraycopy(oldData, 0, elementData, 0, elementCount); + } + } + + /** + * This implements the unsynchronized semantics of ensureCapacity. + * Synchronized methods in this class can internally call this + * method for ensuring capacity without incurring the cost of an + * extra synchronization. + * + * @see java.util.ByteBuffer#ensureCapacity(int) + */ + private void ensureCapacityHelper(int minCapacity) { + int oldCapacity = elementData.length; + if (minCapacity > oldCapacity) { + byte oldData[] = elementData; + int newCapacity = (capacityIncrement > 0) ? + (oldCapacity + capacityIncrement) : (oldCapacity * 2); + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + elementData = new byte[newCapacity]; + System.arraycopy(oldData, 0, elementData, 0, elementCount); + } + } + + /** + * Returns the current capacity of this ByteBuffer. + * + * @return the current capacity (the length of its internal + * data arary, kept in the field elementData + * of this ByteBuffer. + */ + public int capacity() { + return elementData.length; + } + + /** + * Returns the number of components in this ByteBuffer. + * + * @return the number of components in this ByteBuffer. + */ + public int size() { + return elementCount; + } + + /** + * Tests if this ByteBuffer has no components. + * + * @return true if and only if this ByteBuffer has + * no components, that is, its size is zero; + * false otherwise. + */ + public boolean isEmpty() { + return elementCount == 0; + } + + public void append(byte value) + { + ensureCapacityHelper(elementCount + 1); + elementData[elementCount++] = value; + } + + public void append( int value ) + { + ensureCapacityHelper(elementCount + 4); + doAppend( value ) ; + } + + private void doAppend( int value ) + { + int current = value ; + for (int ctr=0; ctr<4; ctr++) { + elementData[elementCount+ctr] = (byte)(current & 255) ; + current = current >> 8 ; + } + elementCount += 4 ; + } + + public void append( String value ) + { + byte[] data = value.getBytes() ; + ensureCapacityHelper( elementCount + data.length + 4 ) ; + doAppend( data.length ) ; + System.arraycopy( data, 0, elementData, elementCount, data.length ) ; + elementCount += data.length ; + } + + /** + * Returns an array containing all of the elements in this ByteBuffer + * in the correct order. + * + * @since 1.2 + */ + public byte[] toArray() { + return (byte[])elementData.clone() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/EncapsulationUtility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/EncapsulationUtility.java new file mode 100644 index 000000000..c9e89cd6a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/EncapsulationUtility.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import java.util.List; + +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.WriteContents ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.impl.encoding.CDROutputObject ; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.encoding.EncapsInputStream ; +import com.sun.corba.ee.impl.encoding.EncapsInputStreamFactory; + +/** + * This static utility class contains various utility methods for reading and + * writing CDR encapsulations. + * + * @author Ken Cavanaugh + */ +public final class EncapsulationUtility +{ + private EncapsulationUtility() + { + } + + /** Read the count from is, then read count Identifiables from + * is using the factory. Add each constructed Identifiable to container. + */ + public static void readIdentifiableSequence( + List container, + IdentifiableFactoryFinder finder, InputStream istr) + { + int count = istr.read_long() ; + for (int ctr = 0; ctr void writeIdentifiableSequence( + List container, OutputStream os) + { + os.write_long( container.size() ) ; + for (Identifiable obj : container) { + os.write_long( obj.getId() ) ; + obj.write( os ) ; + } + } + + /** Helper method that is used to extract data from an output + * stream and write the data to another output stream. Defined + * as static so that it can be used in another class. + */ + public static void writeOutputStream( OutputStream dataStream, + OutputStream os ) + { + byte[] data = ((CDROutputObject)dataStream).toByteArray() ; + os.write_long( data.length ) ; + os.write_octet_array( data, 0, data.length ) ; + } + + /** Helper method to read the octet array from is, deencapsulate it, + * and return + * as another InputStream. This must be called inside the + * constructor of a derived class to obtain the correct stream + * for unmarshalling data. + */ + public static InputStream getEncapsulationStream( ORB orb, InputStream is ) + { + byte[] data = readOctets( is ) ; + EncapsInputStream result = EncapsInputStreamFactory.newEncapsInputStream( orb, data, + data.length ) ; + result.consumeEndian() ; + return result ; + } + + /** Helper method that reads an octet array from an input stream. + * Defined as static here so that it can be used in another class. + */ + public static byte[] readOctets( InputStream is ) + { + int len = is.read_ulong() ; + byte[] data = new byte[len] ; + is.read_octet_array( data, 0, len ) ; + return data ; + } + + public static void writeEncapsulation( WriteContents obj, + OutputStream os ) + { + EncapsOutputStream out = OutputStreamFactory.newEncapsOutputStream( (ORB)os.orb() ) ; + + out.putEndian() ; + + obj.writeContents( out ) ; + + writeOutputStream( out, os ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/FreezableList.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/FreezableList.java new file mode 100644 index 000000000..a2e9ca536 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/FreezableList.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import java.util.List ; +import java.util.AbstractList ; + +import com.sun.corba.ee.spi.ior.MakeImmutable ; + +/** Simple class that delegates all List operations to +* another list. It also can be frozen, which means that +* a number of operations can be performed on the list, +* and then the list can be made immutable, so that no +* further changes are possible. A FreezableList is frozen +* using the makeImmutable method. +*/ +public class FreezableList extends AbstractList { + private List delegate = null ; + private boolean immutable = false ; + + @Override + public boolean equals( Object obj ) + { + if (obj == null) + return false ; + + if (!(obj instanceof FreezableList)) + return false ; + + FreezableList other = FreezableList.class.cast( obj ) ; + + return delegate.equals( other.delegate ) && + (immutable == other.immutable) ; + } + + @Override + public int hashCode() + { + return delegate.hashCode() ; + } + + public FreezableList( List delegate, boolean immutable ) + { + this.delegate = delegate ; + this.immutable = immutable ; + } + + public FreezableList( List delegate ) + { + this( delegate, false ) ; + } + + public void makeImmutable() + { + immutable = true ; + } + + public boolean isImmutable() + { + return immutable ; + } + + public void makeElementsImmutable() + { + for (E x : this) { + if (x instanceof MakeImmutable) { + MakeImmutable element = MakeImmutable.class.cast( x ) ; + element.makeImmutable() ; + } + } + } + + // Methods overridden from AbstractList + + public int size() + { + return delegate.size() ; + } + + public E get(int index) + { + return delegate.get(index) ; + } + + @Override + public E set(int index, E element) + { + if (immutable) + throw new UnsupportedOperationException() ; + + return delegate.set(index, element) ; + } + + @Override + public void add(int index, E element) + { + if (immutable) + throw new UnsupportedOperationException() ; + + delegate.add(index, element) ; + } + + @Override + public E remove(int index) + { + if (immutable) + throw new UnsupportedOperationException() ; + + return delegate.remove(index) ; + } + + // We also override subList so that the result is a FreezableList. + @Override + public List subList(int fromIndex, int toIndex) + { + List list = delegate.subList(fromIndex, toIndex) ; + List result = new FreezableList( list, immutable ) ; + return result ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/GenericIdentifiable.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/GenericIdentifiable.java new file mode 100644 index 000000000..6d0f943af --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/GenericIdentifiable.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import java.util.Arrays ; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.Identifiable ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * @author + * This is used for unknown components and profiles. A TAG_MULTICOMPONENT_PROFILE will be represented this way. + */ +@ManagedData +@Description( "A generic implementation of an IIOP encapsulation with an integer id" ) +public abstract class GenericIdentifiable implements Identifiable +{ + private int id; + private byte data[]; + + public GenericIdentifiable(int id, InputStream is) + { + this.id = id ; + data = EncapsulationUtility.readOctets( is ) ; + } + + public int getId() + { + return id ; + } + + public void write(OutputStream os) + { + os.write_ulong( data.length ) ; + os.write_octet_array( data, 0, data.length ) ; + } + + public String toString() + { + return "GenericIdentifiable[id=" + getId() + "]" ; + } + + public boolean equals(Object obj) + { + if (obj == null) + return false ; + + if (!(obj instanceof GenericIdentifiable)) + return false ; + + GenericIdentifiable encaps = (GenericIdentifiable)obj ; + + return (getId() == encaps.getId()) && + Arrays.equals( data, encaps.data ) ; + } + + public int hashCode() + { + int result = 17 ; + for (int ctr=0; ctr + implements IOR +{ + private String typeId; + private ORB factory = null ; + static final IORSystemException wrapper = + IORSystemException.self ; + private boolean isCachedHashValue = false; + private int cachedHashValue; + + public Iterator getTaggedProfiles() { + return iterator() ; + } + + public ORB getORB() + { + return factory ; + } + + /* This variable is set directly from the constructors that take + * an IORTemplate or IORTemplateList as arguments; otherwise it + * is derived from the list of TaggedProfile instances on the first + * call to getIORTemplates. Note that we assume that an IOR with + * mutiple TaggedProfile instances has the same ObjectId in each + * TaggedProfile, as otherwise the IOR could never be created through + * an ObjectReferenceFactory. + */ + private IORTemplateList iortemps = null ; + + @Override + public boolean equals( Object obj ) + { + if (obj == null) { + return false; + } + + if (!(obj instanceof IOR)) { + return false; + } + + IOR other = (IOR)obj ; + + return super.equals( obj ) && typeId.equals( other.getTypeId() ) ; + } + + @Override + public int hashCode() + { + if (!isCachedHashValue) { + cachedHashValue = (super.hashCode() ^ typeId.hashCode()); + isCachedHashValue = true; + } + return cachedHashValue; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder() ; + sb.append( "IORImpl[type=") ; + sb.append( typeId ) ; + sb.append( " iorTemplates=" ) ; + + IORTemplateList list = getIORTemplates() ; + sb.append( list.toString() ) ; + return sb.toString() ; + } + + /** Construct an empty IOR. This is needed for null object references. + */ + public IORImpl( ORB orb ) + { + this( orb, "" ) ; + } + + public IORImpl( ORB orb, String typeid ) + { + factory = orb ; + this.typeId = typeid ; + } + + /** Construct an IOR from an IORTemplate by applying the same + * object id to each TaggedProfileTemplate in the IORTemplate. + */ + public IORImpl( ORB orb, String typeId, IORTemplate iortemp, ObjectId id) + { + this( orb, typeId ) ; + + this.iortemps = IORFactories.makeIORTemplateList() ; + this.iortemps.add( iortemp ) ; + + addTaggedProfiles( iortemp, id ) ; + + makeImmutable() ; + } + + private void addTaggedProfiles( IORTemplate iortemp, ObjectId id ) + { + ObjectKeyTemplate oktemp = iortemp.getObjectKeyTemplate() ; + for( TaggedProfileTemplate temp : iortemp) { + TaggedProfile profile = temp.create( oktemp, id ) ; + add( profile ) ; + } + } + + /** Construct an IOR from an IORTemplate by applying the same + * object id to each TaggedProfileTemplate in the IORTemplate. + */ + public IORImpl( ORB orb, String typeId, IORTemplateList iortemps, ObjectId id) + { + this( orb, typeId ) ; + + this.iortemps = iortemps ; + + Iterator iter = iortemps.iterator() ; + while (iter.hasNext()) { + IORTemplate iortemp = iter.next() ; + addTaggedProfiles( iortemp, id ) ; + } + + makeImmutable() ; + } + + // Note that orb is not always the ORB of is! + public IORImpl(ORB orb, InputStream is) + { + this( orb, is.read_string() ) ; + + IdentifiableFactoryFinder finder = + factory.getTaggedProfileFactoryFinder() ; + + EncapsulationUtility.readIdentifiableSequence( this, finder, is ) ; + + makeImmutable() ; + } + + public String getTypeId() + { + return typeId ; + } + + public void write(OutputStream os) + { + os.write_string( typeId ) ; + EncapsulationUtility.writeIdentifiableSequence( this, os ) ; + } + + public String stringify() + { + StringWriter bs; + + MarshalOutputStream s = OutputStreamFactory.newEncapsOutputStream(factory); + s.putEndian(); + write( (OutputStream)s ); + bs = new StringWriter(); + try { + s.writeTo(new HexOutputStream(bs)); + } catch (IOException ex) { + throw wrapper.stringifyWriteError( ex ) ; + } + + return ORBConstants.STRINGIFY_PREFIX + bs; + } + + @Override + public synchronized void makeImmutable() + { + makeElementsImmutable() ; + + if (iortemps != null) { + iortemps.makeImmutable(); + } + + super.makeImmutable() ; + } + + public org.omg.IOP.IOR getIOPIOR() { + EncapsOutputStream os = OutputStreamFactory.newEncapsOutputStream(factory); + write(os); + InputStream is = (InputStream) (os.create_input_stream()); + return org.omg.IOP.IORHelper.read(is); + } + + public boolean isNil() + { + // + // The check for typeId length of 0 below is commented out + // as a workaround for a bug in ORBs which send a + // null objref with a non-empty typeId string. + // + return ((size() == 0) /* && (typeId.length() == 0) */); + } + + public boolean isEquivalent(IOR ior) + { + Iterator myIterator = iterator() ; + Iterator otherIterator = ior.iterator() ; + while (myIterator.hasNext() && otherIterator.hasNext()) { + TaggedProfile myProfile = myIterator.next() ; + TaggedProfile otherProfile = otherIterator.next() ; + if (!myProfile.isEquivalent( otherProfile )) { + return false; + } + } + + return myIterator.hasNext() == otherIterator.hasNext() ; + } + + private void initializeIORTemplateList() + { + // Maps ObjectKeyTemplate to IORTemplate + Map oktempToIORTemplate = + new HashMap() ; + + iortemps = IORFactories.makeIORTemplateList() ; + Iterator iter = iterator() ; + ObjectId oid = null ; // used to check that all profiles have the same oid. + while (iter.hasNext()) { + TaggedProfile prof = iter.next() ; + TaggedProfileTemplate ptemp = prof.getTaggedProfileTemplate() ; + ObjectKeyTemplate oktemp = prof.getObjectKeyTemplate() ; + + // Check that all oids for all profiles are the same: if they are not, + // throw exception. + if (oid == null) { + oid = prof.getObjectId(); + } else if (!oid.equals( prof.getObjectId() )) { + throw wrapper.badOidInIorTemplateList(); + } + + // Find or create the IORTemplate for oktemp. + IORTemplate iortemp = oktempToIORTemplate.get( oktemp ) ; + if (iortemp == null) { + iortemp = IORFactories.makeIORTemplate( oktemp ) ; + oktempToIORTemplate.put( oktemp, iortemp ) ; + iortemps.add( iortemp ) ; + } + + iortemp.add( ptemp ) ; + } + + iortemps.makeImmutable() ; + } + + /** Return the IORTemplateList for this IOR. Will throw + * exception if it is not possible to generate an IOR + * from the IORTemplateList that is equal to this IOR, + * which can only happen if not every TaggedProfile in the + * IOR has the same ObjectId. + */ + public synchronized IORTemplateList getIORTemplates() + { + if (iortemps == null) { + initializeIORTemplateList(); + } + + return iortemps ; + } + + /** Return the first IIOPProfile in this IOR. + * Originally we planned to remove this, because we planned to use + * multiple IIOP profiles. However, we really have no need for + * multiple profiles in the ORB, so we will probably never remove + * this API. + */ + public IIOPProfile getProfile() + { + IIOPProfile iop = null ; + Iterator iter = + iteratorById( TAG_INTERNET_IOP.value ) ; + if (iter.hasNext()) { + iop = + IIOPProfile.class.cast(iter.next()); + } + + if (iop != null) { + return iop; + } + + // if we come to this point then no IIOP Profile + // is present. Therefore, throw an exception. + throw wrapper.iorMustHaveIiopProfile() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IORTemplateImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IORTemplateImpl.java new file mode 100644 index 000000000..368d5e359 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IORTemplateImpl.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import java.util.Iterator ; + +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.ior.IdentifiableContainerBase ; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactory ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** + * This class is a container of TaggedProfileTemplates. + * @author + */ +public class IORTemplateImpl + extends IdentifiableContainerBase + implements IORTemplate +{ + private ObjectKeyTemplate oktemp ; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "IORTemplate[oktemp=") ; + sb.append( oktemp.toString() ) ; + sb.append( " profile templates:") ; + sb.append( super.toString() ) ; + sb.append( ']' ) ; + return sb.toString() ; + } + + @Override + public boolean equals( Object obj ) + { + if (obj == null) + return false ; + + if (!(obj instanceof IORTemplateImpl)) + return false ; + + IORTemplateImpl other = (IORTemplateImpl)obj ; + + return super.equals( obj ) && oktemp.equals( other.getObjectKeyTemplate() ) ; + } + + @Override + public int hashCode() + { + return super.hashCode() ^ oktemp.hashCode() ; + } + + public ObjectKeyTemplate getObjectKeyTemplate() + { + return oktemp ; + } + + public IORTemplateImpl( ObjectKeyTemplate oktemp ) + { + this.oktemp = oktemp ; + } + + public IOR makeIOR( ORB orb, String typeid, ObjectId oid ) + { + return new IORImpl( orb, typeid, this, oid ) ; + } + + public boolean isEquivalent( IORFactory other ) + { + if (!(other instanceof IORTemplate)) + return false ; + + IORTemplate list = (IORTemplate)other ; + + Iterator thisIterator = iterator() ; + Iterator listIterator = list.iterator() ; + while (thisIterator.hasNext() && listIterator.hasNext()) { + TaggedProfileTemplate thisTemplate = thisIterator.next() ; + TaggedProfileTemplate listTemplate = listIterator.next() ; + if (!thisTemplate.isEquivalent( listTemplate )) + return false ; + } + + return (thisIterator.hasNext() == listIterator.hasNext()) && + getObjectKeyTemplate().equals( list.getObjectKeyTemplate() ) ; + } + + /** Ensure that this IORTemplate and all of its profiles can not be + * modified. This overrides the method inherited from + * FreezableList through IdentifiableContainerBase. + */ + @Override + public void makeImmutable() + { + makeElementsImmutable() ; + super.makeImmutable() ; + } + + public void write( OutputStream os ) + { + oktemp.write( os ) ; + EncapsulationUtility.writeIdentifiableSequence( this, os ) ; + } + + public IORTemplateImpl( InputStream is ) + { + ORB orb = (ORB)(is.orb()) ; + IdentifiableFactoryFinder finder = + orb.getTaggedProfileTemplateFactoryFinder() ; + + oktemp = orb.getObjectKeyFactory().createTemplate( is ) ; + EncapsulationUtility.readIdentifiableSequence( this, finder, is ) ; + + makeImmutable() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IORTemplateListImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IORTemplateListImpl.java new file mode 100644 index 000000000..7606e90a3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IORTemplateListImpl.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import java.util.ArrayList ; +import java.util.Iterator ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.IORTemplateList ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactory ; +import com.sun.corba.ee.spi.ior.IORFactories ; + +import com.sun.corba.ee.spi.orb.ORB ; + +public class IORTemplateListImpl extends FreezableList + implements IORTemplateList +{ + public IORTemplateListImpl() + { + super( new ArrayList() ) ; + } + + public IORTemplateListImpl( InputStream is ) + { + this() ; + int size = is.read_long() ; + for (int ctr=0; ctr thisIterator = iterator() ; + Iterator listIterator = list.iterator() ; + while (thisIterator.hasNext() && listIterator.hasNext()) { + IORTemplate thisTemplate = thisIterator.next() ; + IORTemplate listTemplate = listIterator.next() ; + if (!thisTemplate.isEquivalent( listTemplate )) + return false ; + } + + return thisIterator.hasNext() == listIterator.hasNext() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IdentifiableFactoryFinderBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IdentifiableFactoryFinderBase.java new file mode 100644 index 000000000..2fe04b128 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/IdentifiableFactoryFinderBase.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import java.util.Map ; +import java.util.HashMap ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.IdentifiableFactory ; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; + +import com.sun.corba.ee.spi.logging.IORSystemException ; + +public abstract class IdentifiableFactoryFinderBase + implements IdentifiableFactoryFinder +{ + protected static final IORSystemException wrapper = + IORSystemException.self ; + + private ORB orb ; + private Map> map ; + + protected IdentifiableFactoryFinderBase( ORB orb ) + { + map = new HashMap>() ; + this.orb = orb ; + } + + protected IdentifiableFactory getFactory(int id) + { + return map.get( id ) ; + } + + public abstract E handleMissingFactory( int id, + InputStream is ) ; + + public E create(int id, InputStream is) + { + IdentifiableFactory factory = getFactory( id ) ; + + if (factory != null) { + return factory.create(orb, is); + } else { + return handleMissingFactory(id, is); + } + } + + public void registerFactory(IdentifiableFactory factory) + { + map.put( factory.getId(), factory ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/JIDLObjectKeyTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/JIDLObjectKeyTemplate.java new file mode 100644 index 000000000..2b6fa7072 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/JIDLObjectKeyTemplate.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import org.omg.CORBA.OctetSeqHolder ; + +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectKeyFactory ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl ; + +/** + * @author Ken Cavanaugh + */ +public final class JIDLObjectKeyTemplate extends NewObjectKeyTemplateBase +{ + /** This constructor reads the template ONLY from the stream. + */ + public JIDLObjectKeyTemplate( ORB orb, int magic, int scid, InputStream is ) + { + super( orb, magic, scid, is.read_long(), JIDL_ORB_ID, JIDL_OAID ); + + setORBVersion( is ) ; + } + + /** This constructor reads a complete ObjectKey (template and Id) + * from the stream. + */ + public JIDLObjectKeyTemplate( ORB orb, int magic, int scid, InputStream is, + OctetSeqHolder osh ) + { + super( orb, magic, scid, is.read_long(), JIDL_ORB_ID, JIDL_OAID ); + + osh.value = readObjectKey( is ) ; + + setORBVersion( is ) ; + } + + public JIDLObjectKeyTemplate( ORB orb, int scid, int serverid ) + { + super( orb, ObjectKeyFactoryImpl.JAVAMAGIC_NEWER, scid, serverid, + JIDL_ORB_ID, JIDL_OAID ) ; + + setORBVersion( ORBVersionFactory.getORBVersion() ) ; + } + + protected void writeTemplate( OutputStream os ) + { + os.write_long( getMagic() ) ; + os.write_long( getSubcontractId() ) ; + os.write_long( getServerId() ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/NewObjectKeyTemplateBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/NewObjectKeyTemplateBase.java new file mode 100644 index 000000000..6f924f912 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/NewObjectKeyTemplateBase.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +public abstract class NewObjectKeyTemplateBase extends ObjectKeyTemplateBase +{ + public NewObjectKeyTemplateBase( ORB orb, int magic, int scid, int serverid, + String orbid, ObjectAdapterId oaid ) + { + super( orb, magic, scid, serverid, orbid, oaid ) ; + // subclass must set the version, since we don't have the object key here. + + if (magic != ObjectKeyFactoryImpl.JAVAMAGIC_NEWER) { + throw wrapper.badMagic(magic); + } + } + + @Override + public void write(ObjectId objectId, OutputStream os) + { + super.write( objectId, os ) ; + getORBVersion().write( os ) ; + } + + @Override + public void write(OutputStream os) + { + super.write( os ) ; + getORBVersion().write( os ) ; + } + + protected void setORBVersion( InputStream is ) + { + ORBVersion version = ORBVersionFactory.create( is ) ; + setORBVersion( version ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdArray.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdArray.java new file mode 100644 index 000000000..c51e8eafe --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdArray.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import java.util.Iterator ; +import java.util.Arrays ; + +public class ObjectAdapterIdArray extends ObjectAdapterIdBase { + private final String[] objectAdapterId ; + + @Override + public boolean equals( Object obj ) { + // Note that the superclass equals method is correct and general, + // because it tests for equality using the iterator. The state of + // the derived classes simply implements the iterator. + // This equals method is added here to appease findbugs. + return super.equals( obj ) ; + } + + public ObjectAdapterIdArray( String[] objectAdapterId ) + { + this.objectAdapterId = (String[])objectAdapterId.clone() ; + } + + /** Special constructor used for OA IDs of length 2. + */ + public ObjectAdapterIdArray( String name1, String name2 ) + { + objectAdapterId = new String[2] ; + objectAdapterId[0] = name1 ; + objectAdapterId[1] = name2 ; + } + + public int getNumLevels() + { + return objectAdapterId.length ; + } + + public Iterator iterator() + { + return Arrays.asList( objectAdapterId ).iterator() ; + } + + public String[] getAdapterName() + { + return (String[])objectAdapterId.clone() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdBase.java new file mode 100644 index 000000000..964506a2d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdBase.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import java.util.Iterator ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + +abstract class ObjectAdapterIdBase implements ObjectAdapterId { + @Override + public boolean equals( Object other ) { + if (!(other instanceof ObjectAdapterId)) + return false ; + + ObjectAdapterId theOther = (ObjectAdapterId)other ; + + Iterator iter1 = iterator() ; + Iterator iter2 = theOther.iterator() ; + + while (iter1.hasNext() && iter2.hasNext()) { + String str1 = iter1.next() ; + String str2 = iter2.next() ; + + if (!str1.equals( str2 )) + return false ; + } + + return iter1.hasNext() == iter2.hasNext() ; + } + + @Override + public int hashCode() { + int result = 17 ; + for (String str : this) { + result = 37*result + str.hashCode() ; + } + return result ; + } + + @Override + public String toString() { + StringBuilder buff = new StringBuilder() ; + buff.append( "ObjectAdapterID[" ) ; + + boolean first = true ; + for (String str : this) { + if (first) + first = false ; + else + buff.append( "/" ) ; + + buff.append( str ) ; + } + + buff.append( "]" ) ; + + return buff.toString() ; + } + + public void write( OutputStream os ) { + os.write_long( getNumLevels() ) ; + for (String str : this) { + os.write_string( str ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdNumber.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdNumber.java new file mode 100644 index 000000000..6652ce554 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectAdapterIdNumber.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +/** ObjectAdapterIdNumber is used to represent pre-JDK 1.4 POA adapter + * IDs. The POA ID was simply represented as a single integer, which was + * mapped to the actual POA instance. Here, we just represent these + * internally as arrays of the form { "OldRootPOA", "" }, + * and provide an extra method to get the number back. + */ +public class ObjectAdapterIdNumber extends ObjectAdapterIdArray { + private int poaid ; + + public ObjectAdapterIdNumber( int poaid ) + { + super( "OldRootPOA", Integer.toString( poaid ) ) ; + this.poaid = poaid ; + } + + public int getOldPOAId() + { + return poaid ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectIdImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectIdImpl.java new file mode 100644 index 000000000..8ed145b4e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectIdImpl.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import java.util.Arrays ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import org.omg.CORBA_2_3.portable.OutputStream ; +import com.sun.corba.ee.impl.misc.ORBUtility ; + +/** + * @author Ken Cavanaugh + */ +public final class ObjectIdImpl implements ObjectId +{ + private byte[] id; + + @Override + public boolean equals( Object obj ) + { + if (!(obj instanceof ObjectIdImpl)) + return false ; + + ObjectIdImpl other = (ObjectIdImpl)obj ; + + return Arrays.equals( this.id, other.id ) ; + } + + @Override + public int hashCode() + { + int result = 17 ; + for (int ctr=0; ctr= ORBConstants.FIRST_POA_SCID) && + (scid <= ORBConstants.MAX_POA_SCID)) { + if (magic >= JAVAMAGIC_NEWER) { + oktemp = new POAObjectKeyTemplate(orb, magic, scid, + is, osh); + } else { + oktemp = new OldPOAObjectKeyTemplate(orb, magic, scid, + is, osh); + } + } else if ((scid >= 0) && (scid < ORBConstants.FIRST_POA_SCID)) { + if (magic >= JAVAMAGIC_NEWER) { + oktemp = + new JIDLObjectKeyTemplate(orb, magic, scid, + is, osh); + } else { + oktemp = + new OldJIDLObjectKeyTemplate(orb, magic, scid, + is, osh); + } + } + + return oktemp ; + } + } ; + + /** This handler reads only the oktemp. + */ + private Handler oktempOnly = new Handler() { + public ObjectKeyTemplate handle( int magic, int scid, + InputStream is, OctetSeqHolder osh ) { + ObjectKeyTemplate oktemp = null ; + + if ((scid >= ORBConstants.FIRST_POA_SCID) && + (scid <= ORBConstants.MAX_POA_SCID)) { + if (magic >= JAVAMAGIC_NEWER) { + oktemp = new POAObjectKeyTemplate(orb, magic, scid, is); + } else { + oktemp = + new OldPOAObjectKeyTemplate(orb, magic, scid, is); + } + } else if ((scid >= 0) && (scid < ORBConstants.FIRST_POA_SCID)) { + if (magic >= JAVAMAGIC_NEWER) { + oktemp = + new JIDLObjectKeyTemplate(orb, magic, scid, is); + } else { + oktemp = + new OldJIDLObjectKeyTemplate(orb, magic, scid, is); + } + } + + return oktemp ; + } + } ; + + /** Returns true iff magic is in the range of valid magic numbers + * for our ORB. + */ + private boolean validMagic( int magic ) + { + return (magic >= MAGIC_BASE) && (magic <= MAX_MAGIC) ; + } + + /** Creates an ObjectKeyTemplate from the InputStream. Most of the + * decoding is done inside the handler. + */ + private ObjectKeyTemplate create( InputStream is, Handler handler, + OctetSeqHolder osh ) + { + ObjectKeyTemplate oktemp = null ; + + try { + int magic = is.read_long() ; + + if (validMagic( magic )) { + int scid = is.read_long() ; + oktemp = handler.handle( magic, scid, is, osh ) ; + } + } catch (MARSHAL mexc) { + wrapper.createMarshalError( mexc ) ; + } + + return oktemp ; + } + + public ObjectKey create(byte[] key) { + + OctetSeqHolder osh = new OctetSeqHolder(); + EncapsInputStream is = EncapsInputStreamFactory.newEncapsInputStream(orb, key, key.length); + + ObjectKeyTemplate oktemp; + try { + oktemp = create(is, fullKey, osh); + } finally { + try { + is.close(); + } catch (java.io.IOException e) { + wrapper.ioexceptionDuringStreamClose(e); + } + } + if (oktemp == null) { + oktemp = orb.getWireObjectKeyTemplate(); // cached singleton + osh.value = key; + } + + ObjectId oid = new ObjectIdImpl( osh.value ) ; + return new ObjectKeyImpl( oktemp, oid ) ; + } + + public ObjectKeyTemplate createTemplate( InputStream is ) + { + ObjectKeyTemplate oktemp = create( is, oktempOnly, null ) ; + if (oktemp == null) { + oktemp = orb.getWireObjectKeyTemplate(); // cached singleton + } + + return oktemp ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectKeyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectKeyImpl.java new file mode 100644 index 000000000..bfd4c3ef1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectKeyImpl.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; + +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.logging.IORSystemException; + +/** + * @author Ken Cavanaugh + */ +public class ObjectKeyImpl implements ObjectKey +{ + private static final IORSystemException wrapper = + IORSystemException.self ; + + private ObjectKeyTemplate oktemp; + private ObjectId id; + private byte[] array; + + public ObjectKeyImpl( ObjectKeyTemplate oktemp, ObjectId id) { + this.oktemp = oktemp ; + this.id = id ; + } + + @Override + public boolean equals( Object obj ) + { + if (obj == null) { + return false; + } + + if (!(obj instanceof ObjectKeyImpl)) { + return false; + } + + ObjectKeyImpl other = (ObjectKeyImpl)obj ; + + return oktemp.equals( other.oktemp ) && + id.equals( other.id ) ; + } + + @Override + public int hashCode() + { + return oktemp.hashCode() ^ id.hashCode() ; + } + + public ObjectKeyTemplate getTemplate() + { + return oktemp ; + } + + public ObjectId getId() + { + return id ; + } + + public void write( OutputStream os ) + { + oktemp.write( id, os ) ; + } + + public synchronized byte[] getBytes(org.omg.CORBA.ORB orb) + { + if (array == null) { + EncapsOutputStream os = OutputStreamFactory.newEncapsOutputStream((ORB)orb); + try { + write(os); + array = os.toByteArray(); + } finally { + try { + os.close(); + } catch (java.io.IOException e) { + wrapper.ioexceptionDuringStreamClose(e); + } + } + } + + return array.clone() ; + } + + public ServerRequestDispatcher getServerRequestDispatcher() + { + return oktemp.getServerRequestDispatcher( id ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectKeyTemplateBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectKeyTemplateBase.java new file mode 100644 index 000000000..7c6649172 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectKeyTemplateBase.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; + +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; + + +import com.sun.corba.ee.spi.logging.IORSystemException ; + +/** + * @author Ken Cavanaugh + */ +public abstract class ObjectKeyTemplateBase implements ObjectKeyTemplate +{ + protected static final IORSystemException wrapper = + IORSystemException.self ; + + // Fixed constants for Java IDL object key template forms + public static final String JIDL_ORB_ID = "" ; + private static final String[] JIDL_OAID_STRINGS = { "TransientObjectAdapter" } ; + public static final ObjectAdapterId JIDL_OAID = new ObjectAdapterIdArray( JIDL_OAID_STRINGS ) ; + + private ORB orb ; + private ORBVersion version ; + private int magic ; + private int scid ; + private int serverid ; + private String orbid ; + private ObjectAdapterId oaid ; + + private byte[] adapterId ; + + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "ObjectKeyTemplate[magic=") ; + sb.append( Integer.toHexString( magic ) ) ; + sb.append( " scid=" ) ; + sb.append( scid ) ; + sb.append( " serverid=") ; + sb.append( serverid ) ; + sb.append( " orbid=") ; + sb.append( orbid ) ; + sb.append( " oaid=" ) ; + sb.append( oaid.toString() ) ; + return sb.toString() ; + } + + public synchronized byte[] getAdapterId() { + if (adapterId == null) { + adapterId = computeAdapterId(); + } + + return (byte[])(adapterId.clone()) ; + } + + private byte[] computeAdapterId() + { + // write out serverid, orbid, oaid + ByteBuffer buff = new ByteBuffer() ; + + buff.append( getServerId() ) ; + buff.append( orbid ) ; + + buff.append( oaid.getNumLevels() ) ; + for (String comp : oaid) { + buff.append( comp ) ; + } + + buff.trimToSize() ; + + return buff.toArray() ; + } + + public ObjectKeyTemplateBase( ORB orb, int magic, int scid, int serverid, + String orbid, ObjectAdapterId oaid ) + { + this.orb = orb ; + this.magic = magic ; + this.scid = scid ; + this.serverid = serverid ; + this.orbid = orbid ; + this.oaid = oaid ; + + adapterId = null; + } + + @Override + public boolean equals( Object obj ) { + if (!(obj instanceof ObjectKeyTemplateBase)) + return false ; + + ObjectKeyTemplateBase other = (ObjectKeyTemplateBase)obj ; + + return (magic == other.magic) && (scid == other.scid) && + (serverid == other.serverid) && (version.equals( other.version ) && + orbid.equals( other.orbid ) && oaid.equals( other.oaid )) ; + } + + public int hashCode() { + int result = 17 ; + result = 37*result + magic ; + result = 37*result + scid ; + result = 37*result + serverid ; + result = 37*result + version.hashCode() ; + result = 37*result + orbid.hashCode() ; + result = 37*result + oaid.hashCode() ; + return result ; + } + + public int getSubcontractId() { + return scid ; + } + + public int getServerId() { + return serverid ; + } + + public String getORBId() { + return orbid ; + } + + public ObjectAdapterId getObjectAdapterId() { + return oaid ; + } + + public void write(ObjectId objectId, OutputStream os) { + writeTemplate( os ) ; + objectId.write( os ) ; + } + + public void write( OutputStream os ) + { + writeTemplate( os ) ; + } + + abstract protected void writeTemplate( OutputStream os ) ; + + protected int getMagic() { + return magic ; + } + + // All subclasses should set the version in their constructors. + // Public so it can be used in a white-box test. + public void setORBVersion( ORBVersion version ) { + this.version = version ; + } + + public ORBVersion getORBVersion() { + return version ; + } + + protected byte[] readObjectKey( InputStream is ) { + int len = is.read_long() ; + byte[] result = new byte[len] ; + is.read_octet_array( result, 0, len ) ; + return result ; + } + + public ServerRequestDispatcher getServerRequestDispatcher( + ObjectId id ) { + + return orb.getRequestDispatcherRegistry().getServerRequestDispatcher( + scid ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceFactoryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceFactoryImpl.java new file mode 100644 index 000000000..44f495cd8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceFactoryImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import org.omg.CORBA.portable.InputStream ; +import org.omg.CORBA.portable.OutputStream ; +import org.omg.CORBA.portable.StreamableValue ; + +import org.omg.CORBA.TypeCode ; + +import org.omg.PortableInterceptor.ObjectReferenceFactory ; +import org.omg.PortableInterceptor.ObjectReferenceFactoryHelper ; + + +import com.sun.corba.ee.spi.ior.IORFactory; +import com.sun.corba.ee.spi.ior.IORTemplateList; +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** This is an implementation of the ObjectReferenceFactory abstract value +* type defined by the portable interceptors IDL. +* Note that this is a direct Java implementation +* of the abstract value type: there is no stateful value type defined in IDL, +* since defining the state in IDL is awkward and inefficient. The best way +* to define the state is to use internal data structures that can be written +* to and read from CORBA streams. +*/ +public class ObjectReferenceFactoryImpl extends ObjectReferenceProducerBase + implements ObjectReferenceFactory, StreamableValue +{ + // private static long serialVersionUID = 0 ; + + transient private IORTemplateList iorTemplates ; + + public ObjectReferenceFactoryImpl( InputStream is ) + { + super( (ORB)(is.orb()) ) ; + _read( is ) ; + } + + public ObjectReferenceFactoryImpl( ORB orb, IORTemplateList iortemps ) + { + super( orb ) ; + iorTemplates = iortemps ; + } + + @Override + public boolean equals( Object obj ) + { + if (!(obj instanceof ObjectReferenceFactoryImpl)) + return false ; + + ObjectReferenceFactoryImpl other = (ObjectReferenceFactoryImpl)obj ; + + return (iorTemplates != null) && + iorTemplates.equals( other.iorTemplates ) ; + } + + @Override + public int hashCode() + { + return iorTemplates.hashCode() ; + } + + // Note that this repository ID must reflect the implementation + // of the abstract valuetype (that is, this class), not the + // repository ID of the org.omg.PortableInterceptor.ObjectReferenceFactory + // class. This allows for multiple independent implementations + // of the abstract valuetype, should that become necessary. + public static final String repositoryId = + "IDL:com/sun/corba/ee/impl/ior/ObjectReferenceFactoryImpl:1.0" ; + + public String[] _truncatable_ids() + { + return new String[] { repositoryId } ; + } + + public TypeCode _type() + { + return ObjectReferenceFactoryHelper.type() ; + } + + /** Read the data into a (presumably) empty ObjectReferenceFactoryImpl. + * This sets the orb to the ORB of the InputStream. + */ + public void _read( InputStream is ) + { + org.omg.CORBA_2_3.portable.InputStream istr = + (org.omg.CORBA_2_3.portable.InputStream)is ; + + iorTemplates = IORFactories.makeIORTemplateList( istr ) ; + } + + /** Write the state to the OutputStream. + */ + public void _write( OutputStream os ) + { + org.omg.CORBA_2_3.portable.OutputStream ostr = + (org.omg.CORBA_2_3.portable.OutputStream)os ; + + iorTemplates.write( ostr ) ; + } + + public IORFactory getIORFactory() + { + return iorTemplates ; + } + + public IORTemplateList getIORTemplateList() + { + return iorTemplates ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceProducerBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceProducerBase.java new file mode 100644 index 000000000..45d5b43ee --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceProducerBase.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.IORFactory ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.IORTemplateList ; +import com.sun.corba.ee.spi.ior.ObjectId ; + +import com.sun.corba.ee.impl.misc.ORBUtility ; +import java.io.Serializable; + + +// Made this serializable so that derived class ObjectReferenceFactoryImpl +// does not require a void constructor. Instead, this class is Serializable, +// and Object is its superclass, so Object provides the void constructor. +// This change cleans up a findbugs issue. +public abstract class ObjectReferenceProducerBase implements Serializable { + private static final long serialVersionUID = 6478965304620421549L; + transient protected ORB orb ; + + public abstract IORFactory getIORFactory() ; + + public abstract IORTemplateList getIORTemplateList() ; + + public ObjectReferenceProducerBase( ORB orb ) + { + this.orb = orb ; + } + + public org.omg.CORBA.Object make_object (String repositoryId, + byte[] objectId) + { + ObjectId oid = IORFactories.makeObjectId( objectId ) ; + IOR ior = getIORFactory().makeIOR( orb, repositoryId, oid ) ; + + return ORBUtility.makeObjectReference( ior ) ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceTemplateImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceTemplateImpl.java new file mode 100644 index 000000000..e7271e608 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/ObjectReferenceTemplateImpl.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior ; + +import org.omg.CORBA.portable.InputStream ; +import org.omg.CORBA.portable.OutputStream ; +import org.omg.CORBA.portable.StreamableValue ; + +import org.omg.CORBA.TypeCode ; + +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.ObjectReferenceTemplateHelper ; + + +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; +import com.sun.corba.ee.spi.ior.IORFactory; +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.IORTemplateList; +import com.sun.corba.ee.spi.ior.IORFactories; + + +import com.sun.corba.ee.spi.orb.ORB ; + +/** This is an implementation of the ObjectReferenceTemplate abstract value +* type defined by the portable interceptors IDL. +* Note that this is a direct Java implementation +* of the abstract value type: there is no stateful value type defined in IDL, +* since defining the state in IDL is awkward and inefficient. The best way +* to define the state is to use internal data structures that can be written +* to and read from CORBA streams. +*/ +public class ObjectReferenceTemplateImpl extends ObjectReferenceProducerBase + implements ObjectReferenceTemplate, StreamableValue +{ + private static final long serialVersionUID = 6441570404699638098L; + transient private IORTemplate iorTemplate ; + + public ObjectReferenceTemplateImpl( InputStream is ) + { + super( (ORB)(is.orb()) ) ; + _read( is ) ; + } + + public ObjectReferenceTemplateImpl( ORB orb, IORTemplate iortemp ) + { + super( orb ) ; + iorTemplate = iortemp ; + } + + @Override + public boolean equals( Object obj ) + { + if (!(obj instanceof ObjectReferenceTemplateImpl)) { + return false ; + } + + ObjectReferenceTemplateImpl other = (ObjectReferenceTemplateImpl)obj ; + + return (iorTemplate != null) && + iorTemplate.equals( other.iorTemplate ) ; + } + + @Override + public int hashCode() + { + return iorTemplate.hashCode() ; + } + + // Note that this repository ID must reflect the implementation + // of the abstract valuetype (that is, this class), not the + // repository ID of the org.omg.PortableInterceptor.ObjectReferenceTemplate + // class. This allows for multiple independent implementations + // of the abstract valuetype, should that become necessary. + public static final String repositoryId = + "IDL:com/sun/corba/ee/impl/ior/ObjectReferenceTemplateImpl:1.0" ; + + public String[] _truncatable_ids() + { + return new String[] { repositoryId } ; + } + + public TypeCode _type() + { + return ObjectReferenceTemplateHelper.type() ; + } + + // Read the data into a (presumably) empty ORTImpl. This sets the + // orb to the ORB of the InputStream. + public void _read( InputStream is ) + { + org.omg.CORBA_2_3.portable.InputStream istr = + (org.omg.CORBA_2_3.portable.InputStream)is ; + iorTemplate = IORFactories.makeIORTemplate( istr ) ; + orb = (ORB)(istr.orb()) ; + } + + public void _write( OutputStream os ) + { + org.omg.CORBA_2_3.portable.OutputStream ostr = + (org.omg.CORBA_2_3.portable.OutputStream)os ; + + iorTemplate.write( ostr ) ; + } + + public String server_id () + { + int val = iorTemplate.getObjectKeyTemplate().getServerId() ; + return Integer.toString( val ) ; + } + + public String orb_id () + { + return iorTemplate.getObjectKeyTemplate().getORBId() ; + } + + public String[] adapter_name() + { + ObjectAdapterId poaid = + iorTemplate.getObjectKeyTemplate().getObjectAdapterId() ; + + return poaid.getAdapterName() ; + } + + public IORFactory getIORFactory() + { + return iorTemplate ; + } + + public IORTemplateList getIORTemplateList() + { + IORTemplateList tl = IORFactories.makeIORTemplateList() ; + tl.add( iorTemplate ) ; + tl.makeImmutable() ; + return tl ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldJIDLObjectKeyTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldJIDLObjectKeyTemplate.java new file mode 100644 index 000000000..236c30d13 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldJIDLObjectKeyTemplate.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import org.omg.CORBA.OctetSeqHolder ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.ObjectId ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + + +import com.sun.corba.ee.impl.encoding.CDRInputObject ; + +/** + * Handles object keys created by JDK ORBs from before JDK 1.4.0. + */ +public final class OldJIDLObjectKeyTemplate extends OldObjectKeyTemplateBase +{ + /** + * JDK 1.3.1 FCS did not include a version byte at the end of + * its object keys. JDK 1.3.1_01 included the byte with the + * value 1. Anything below 1 is considered an invalid value. + */ + public static final byte NULL_PATCH_VERSION = 0; + + byte patchVersion = OldJIDLObjectKeyTemplate.NULL_PATCH_VERSION; + + public OldJIDLObjectKeyTemplate( ORB orb, int magic, int scid, + InputStream is, OctetSeqHolder osh ) + { + this( orb, magic, scid, is ); + + osh.value = readObjectKey( is ) ; + + /** + * Beginning with JDK 1.3.1_01, a byte was placed at the end of + * the object key with a value indicating the patch version. + * JDK 1.3.1_01 had the value 1. If other patches are necessary + * which involve ORB versioning changes, they should increment + * the patch version. + * + * Note that if we see a value greater than 1 in this code, we + * will treat it as if we're talking to the most recent ORB version. + * + * WARNING: This code is sensitive to changes in CDRInputStream + * getPosition. It assumes that the CDRInputStream is an + * encapsulation whose position can be compared to the object + * key array length. + */ + if (magic == ObjectKeyFactoryImpl.JAVAMAGIC_NEW && + osh.value.length > ((CDRInputObject)is).getPosition()) { + + patchVersion = is.read_octet(); + + if (patchVersion == ObjectKeyFactoryImpl.JDK1_3_1_01_PATCH_LEVEL) { + setORBVersion(ORBVersionFactory.getJDK1_3_1_01()); + } else if (patchVersion > ObjectKeyFactoryImpl.JDK1_3_1_01_PATCH_LEVEL) { + setORBVersion(ORBVersionFactory.getORBVersion()); + } else { + throw wrapper.invalidJdk131PatchLevel(patchVersion); + } + } + } + + + public OldJIDLObjectKeyTemplate( ORB orb, int magic, int scid, int serverid) + { + super( orb, magic, scid, serverid, JIDL_ORB_ID, JIDL_OAID ) ; + } + + public OldJIDLObjectKeyTemplate(ORB orb, int magic, int scid, InputStream is) + { + this( orb, magic, scid, is.read_long() ) ; + } + + protected void writeTemplate( OutputStream os ) + { + os.write_long( getMagic() ) ; + os.write_long( getSubcontractId() ) ; + os.write_long( getServerId() ) ; + } + + @Override + public void write(ObjectId objectId, OutputStream os) + { + super.write(objectId, os); + + if (patchVersion != OldJIDLObjectKeyTemplate.NULL_PATCH_VERSION) { + os.write_octet(patchVersion); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldObjectKeyTemplateBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldObjectKeyTemplateBase.java new file mode 100644 index 000000000..d9b9d93d4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldObjectKeyTemplateBase.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl ; + +/** + * @author Ken Cavanaugh + */ +public abstract class OldObjectKeyTemplateBase extends ObjectKeyTemplateBase +{ + public OldObjectKeyTemplateBase( ORB orb, int magic, int scid, int serverid, + String orbid, ObjectAdapterId oaid ) + { + super( orb, magic, scid, serverid, orbid, oaid ) ; + + // set version based on magic + if (magic == ObjectKeyFactoryImpl.JAVAMAGIC_OLD) + setORBVersion( ORBVersionFactory.getOLD() ) ; + else if (magic == ObjectKeyFactoryImpl.JAVAMAGIC_NEW) + setORBVersion( ORBVersionFactory.getNEW() ) ; + else // any other magic should not be here + throw wrapper.badMagic( Integer.valueOf( magic ) ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldPOAObjectKeyTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldPOAObjectKeyTemplate.java new file mode 100644 index 000000000..c7ea3017c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/OldPOAObjectKeyTemplate.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.OctetSeqHolder ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + + +/** + * @author Ken Cavanaugh + */ +public final class OldPOAObjectKeyTemplate extends OldObjectKeyTemplateBase +{ + /** This constructor reads the template ONLY from the stream + */ + public OldPOAObjectKeyTemplate( ORB orb, int magic, int scid, InputStream is ) + { + this( orb, magic, scid, is.read_long(), is.read_long(), is.read_long() ) ; + } + + /** This constructor reads a complete ObjectKey (template and Id) + * from the stream. + */ + public OldPOAObjectKeyTemplate( ORB orb, int magic, int scid, InputStream is, + OctetSeqHolder osh ) + { + this( orb, magic, scid, is ) ; + osh.value = readObjectKey( is ) ; + } + + public OldPOAObjectKeyTemplate( ORB orb, int magic, int scid, int serverid, + int orbid, int poaid) + { + super( orb, magic, scid, serverid, + Integer.toString( orbid ), + new ObjectAdapterIdNumber( poaid ) ) ; + } + + public void writeTemplate(OutputStream os) + { + os.write_long( getMagic() ) ; + os.write_long( getSubcontractId() ) ; + os.write_long( getServerId() ) ; + + int orbid = Integer.parseInt( getORBId() ) ; + os.write_long( orbid ) ; + + ObjectAdapterIdNumber oaid = (ObjectAdapterIdNumber)(getObjectAdapterId()) ; + int poaid = oaid.getOldPOAId() ; + os.write_long( poaid ) ; + } + + @Override + public ORBVersion getORBVersion() + { + if (getMagic() == ObjectKeyFactoryImpl.JAVAMAGIC_OLD) + return ORBVersionFactory.getOLD() ; + else if (getMagic() == ObjectKeyFactoryImpl.JAVAMAGIC_NEW) + return ORBVersionFactory.getNEW() ; + else + throw new INTERNAL() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/POAObjectKeyTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/POAObjectKeyTemplate.java new file mode 100644 index 000000000..f9e9b7284 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/POAObjectKeyTemplate.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import org.omg.CORBA.OctetSeqHolder ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl ; + +/** + * @author + */ +public final class POAObjectKeyTemplate extends NewObjectKeyTemplateBase +{ + public static String[] readPOAName( + org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long(); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) { + value[_o1] = istream.read_string(); + } + return value; + } + + /** This constructor reads the template ONLY from the stream. + */ + public POAObjectKeyTemplate( ORB orb, int magic, int scid, InputStream is ) + { + super( orb, magic, scid, is.read_long(), is.read_string(), + new ObjectAdapterIdArray( readPOAName( is ) ) ) ; + + setORBVersion( is ) ; + } + + /** This constructor reads a complete ObjectKey (template and Id) + * from the stream. + */ + public POAObjectKeyTemplate( ORB orb, int magic, int scid, InputStream is, + OctetSeqHolder osh ) + { + super( orb, magic, scid, is.read_long(), is.read_string(), + new ObjectAdapterIdArray( readPOAName( is ) ) ) ; + + osh.value = readObjectKey( is ) ; + + setORBVersion( is ) ; + } + + public POAObjectKeyTemplate( ORB orb, int scid, int serverid, String orbid, + ObjectAdapterId objectAdapterId) + { + super( orb, ObjectKeyFactoryImpl.JAVAMAGIC_NEWER, scid, serverid, orbid, + objectAdapterId ) ; + + setORBVersion( ORBVersionFactory.getORBVersion() ) ; + } + + public void writeTemplate(OutputStream os) + { + os.write_long( getMagic() ) ; + os.write_long( getSubcontractId() ) ; + os.write_long( getServerId() ) ; + os.write_string( getORBId() ) ; + getObjectAdapterId().write( os ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/StubIORImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/StubIORImpl.java new file mode 100644 index 000000000..5d53d6a66 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/StubIORImpl.java @@ -0,0 +1,263 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import java.io.ObjectOutputStream ; +import java.io.IOException ; +import java.io.Serializable ; + +import java.util.Arrays ; + +import org.omg.CORBA.ORB ; + +import org.omg.CORBA.portable.Delegate ; +import org.omg.CORBA.portable.InputStream ; +import org.omg.CORBA.portable.OutputStream ; + +// Be very careful: com.sun.corba imports must not depend on +// PEORB internal classes in ways that prevent portability to +// other vendor's ORBs. +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * This class implements a very simply IOR representation + * which must be completely ORBImpl free so that this class + * can be used in the implementation of a portable StubDelegateImpl. + */ +public class StubIORImpl implements Serializable +{ + private static final long serialVersionUID = -6261452601247416282L; + // cached hash code + transient private int hashCode = 0 ; + + // IOR components + private byte[] typeData; + private int[] profileTags; + private byte[][] profileData; + + public StubIORImpl() + { + typeData = null ; + profileTags = null ; + profileData = null ; + } + + public String getRepositoryId() + { + if (typeData == null) { + return null ; + } + + return new String( typeData ) ; + } + + public StubIORImpl( org.omg.CORBA.Object obj ) { + + // All externally visible IOR representations must be handled + // using the standard CDR encoding, irrespective of encoding setting. + byte encodingVersion = ORBUtility.getEncodingVersion(); + if (encodingVersion != ORBConstants.CDR_ENC_VERSION) { + ORBUtility.pushEncVersionToThreadLocalState(ORBConstants.CDR_ENC_VERSION); // set + } + + try { + // write the IOR to an OutputStream and get an InputStream + OutputStream ostr = StubAdapter.getORB(obj).create_output_stream(); + ostr.write_Object(obj); + InputStream istr = ostr.create_input_stream(); + + // read the IOR components back from the stream + int typeLength = istr.read_long(); + typeData = new byte[typeLength]; + istr.read_octet_array(typeData, 0, typeLength); + int numProfiles = istr.read_long(); + profileTags = new int[numProfiles]; + profileData = new byte[numProfiles][]; + for (int i = 0; i < numProfiles; i++) { + profileTags[i] = istr.read_long(); + profileData[i] = new byte[istr.read_long()]; + istr.read_octet_array(profileData[i], 0, + profileData[i].length); + } + + } finally { + if (encodingVersion != ORBConstants.CDR_ENC_VERSION) { + ORBUtility.popEncVersionFromThreadLocalState(); // unset + } + } + + } + + public Delegate getDelegate(ORB orb) { + + // All externally visible IOR representations must be handled + // using the standard CDR encoding, irrespective of encoding setting. + byte encodingVersion = ORBUtility.getEncodingVersion(); + if (encodingVersion != ORBConstants.CDR_ENC_VERSION) { + ORBUtility.pushEncVersionToThreadLocalState(ORBConstants.CDR_ENC_VERSION); // set + } + + try { + + // write IOR components to an org.omg.CORBA.portable.OutputStream + OutputStream ostr = orb.create_output_stream(); + ostr.write_long(typeData.length); + ostr.write_octet_array(typeData, 0, typeData.length); + ostr.write_long(profileTags.length); + for (int i = 0; i < profileTags.length; i++) { + ostr.write_long(profileTags[i]); + ostr.write_long(profileData[i].length); + ostr.write_octet_array(profileData[i], 0, + profileData[i].length); + } + InputStream istr = ostr.create_input_stream() ; + + // read the IOR back from the stream + org.omg.CORBA.Object obj = istr.read_Object(); + return StubAdapter.getDelegate( obj ) ; + + } finally { + if (encodingVersion != ORBConstants.CDR_ENC_VERSION) { + ORBUtility.popEncVersionFromThreadLocalState(); // unset + } + } + + } + + // DO NOT MODIFY THIS METHOD - implements OMG standard behavior. + public void doRead( java.io.ObjectInputStream stream ) + throws IOException, ClassNotFoundException + { + // read the IOR from the ObjectInputStream + int typeLength = stream.readInt(); + typeData = new byte[typeLength]; + stream.readFully(typeData); + int numProfiles = stream.readInt(); + profileTags = new int[numProfiles]; + profileData = new byte[numProfiles][]; + for (int i = 0; i < numProfiles; i++) { + profileTags[i] = stream.readInt(); + profileData[i] = new byte[stream.readInt()]; + stream.readFully(profileData[i]); + } + } + + // DO NOT MODIFY THIS METHOD - implements OMG standard behavior. + public void doWrite( ObjectOutputStream stream ) + throws IOException + { + // write the IOR to the ObjectOutputStream + stream.writeInt(typeData.length); + stream.write(typeData); + stream.writeInt(profileTags.length); + for (int i = 0; i < profileTags.length; i++) { + stream.writeInt(profileTags[i]); + stream.writeInt(profileData[i].length); + stream.write(profileData[i]); + } + } + + /** + * Returns a hash code value for the object which is the same for all stubs + * that represent the same remote object. + * @return the hash code value. + */ + @Override + public synchronized int hashCode() + { + if (hashCode == 0) { + + // compute the hash code + for (int i = 0; i < typeData.length; i++) { + hashCode = hashCode * 37 + typeData[i]; + } + + for (int i = 0; i < profileTags.length; i++) { + hashCode = hashCode * 37 + profileTags[i]; + for (int j = 0; j < profileData[i].length; j++) { + hashCode = hashCode * 37 + profileData[i][j]; + } + } + } + + return hashCode; + } + + private boolean equalArrays( byte[][] data1, byte[][] data2 ) + { + if (data1.length != data2.length) { + return false ; + } + + for (int ctr=0; ctr,[]data, ...]" + * @return a string representation of this stub. + */ + @Override + public String toString() + { + StringBuffer result = new StringBuffer() ; + result.append( "SimpleIORImpl[" ) ; + String repositoryId = new String( typeData ) ; + result.append( repositoryId ) ; + for (int ctr=0; ctr + implements TaggedComponentFactoryFinder +{ + public TaggedComponentFactoryFinderImpl( ORB orb ) + { + super( orb ) ; + } + + public TaggedComponent handleMissingFactory( int id, InputStream is ) { + return new GenericTaggedComponent( id, is ) ; + } + + public TaggedComponent create( org.omg.CORBA.ORB orb, + org.omg.IOP.TaggedComponent comp ) + { + EncapsOutputStream os = OutputStreamFactory.newEncapsOutputStream( (ORB)orb ) ; + org.omg.IOP.TaggedComponentHelper.write( os, comp ) ; + InputStream is = (InputStream)(os.create_input_stream() ) ; + // Skip the component ID: we just wrote it out above + is.read_ulong() ; + + return (TaggedComponent)create( comp.tag, is ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TaggedProfileFactoryFinderImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TaggedProfileFactoryFinderImpl.java new file mode 100644 index 000000000..601aa487e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TaggedProfileFactoryFinderImpl.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import com.sun.corba.ee.spi.ior.TaggedProfile ; + +import com.sun.corba.ee.spi.orb.ORB ; + + +import org.omg.CORBA_2_3.portable.InputStream ; + +/** + * @author + */ +public class TaggedProfileFactoryFinderImpl extends + IdentifiableFactoryFinderBase +{ + public TaggedProfileFactoryFinderImpl( ORB orb ) + { + super( orb ) ; + } + + public TaggedProfile handleMissingFactory( int id, InputStream is) + { + return new GenericTaggedProfile( id, is ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TaggedProfileTemplateFactoryFinderImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TaggedProfileTemplateFactoryFinderImpl.java new file mode 100644 index 000000000..a66e2a1aa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TaggedProfileTemplateFactoryFinderImpl.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +/** + * @author Ken Cavanaugh + */ +public class TaggedProfileTemplateFactoryFinderImpl extends + IdentifiableFactoryFinderBase +{ + public TaggedProfileTemplateFactoryFinderImpl( ORB orb ) + { + super( orb ) ; + } + + public TaggedProfileTemplate handleMissingFactory( int id, InputStream is) + { + throw wrapper.taggedProfileTemplateFactoryNotFound( id ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TestAssertions.txt b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TestAssertions.txt new file mode 100644 index 000000000..646728bde --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/TestAssertions.txt @@ -0,0 +1,146 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Remaining work +- Look at the relation between TaggedComponents and Codecs. +- Add TaggedComponentFactories to ORB init +- look at PI and codecs +- Implement PoliciesComponent + +===================== +Testing: +Tagged Components: (DONE) + General: + - Constructed data can be retrieved + - read and written correctly as part of IOR + (test this first in IdEncapsulationContainerBase test) + AlternateIIOPAddressComponent: + - can correctly write out TCP port >32K + CodeSetsComponent + - none additional + JavaCodebaseComponent + - none additional + ORBTypeComponent + - none additional + PoliciesComponent + - none additional + +IdentifiableContainerBase (DONE) + - Test iteratorById on Identifiables (DONE) + - Iterator on id not present is empty (hasNext() == false) + - Iterator on id present returns all ids in sequence +IdEncapsulationContainerBase (DONE) + - Test read sequence of TaggedComponents + - Test writing sequence of TaggedComponents +GenericIdEncapsulation (DONE) + - Test by using for tagged profile and tagged component + - write out and read back test +IIOPAddress (DONE) + - Constructed object returns correct values + - equals: + - false for non-IIOPAddress value + - true iff ports and hosts match +IIOPProfile (DONE) + - construct from id, template; check that correct values are returned + - write out and read back + - no components for 1.0 + - components for >1.0 + - getObjectKey returns value constructed correctly + - isEquivalent iff ids equal and templates equivalent +IIOPProfileTemplate (DONE) + - Constructed object contains correct values + - isEquivalent iff address and template are equal + - cannot have new components added after makeImmutable call +IOR (DONE) + - Constructed object contains correct values + - IOR() has null typeid and no profiles (DONE) + - IOR( String ) has given typeid and no profiles (DONE) + - IOR( String, IIOPProfileTemplate, ObjectId ) has given typeid and + one IIOPProfile corresponding to template and objectid + - IOR( String, IORTemplate, ObjectId ) has profiles corresponding to + IORTemplate and ObjectIds. (DONE) + - IORTemplate( String, IORTemplate, ObjectIds ) has profiles + corresponding to IORTemplate and ObjectIds (DONE) + - IOR( IORTemplate, ObjectIds ) usual test (DONE) + - write out/read back test (DONE) + - Construct IOR with 2 IIOPProfiles, each with several components, + and 2 GenericIdEncapsulation profiles, write out, read back, + check for equals directly and by calling equals + - cannot have new profiles added after makeImmutable call (DONE) + - contained IIOPProfiles cannot have added components after + makeImmutable call. (DONE) +IORTemplate (DONE) + - Constructed object contains correct value +JIDLObjectKeyTemplate (DONE) + - test that IDs match expected values when created from + byte[] in ObjectKeyFactory.create + - Constructed object contains correct values + - write out and read back test + - getId correctly extract id from key +FreezableList (DONE) + - ASSUME that it acts like a linked list: don't test entire interface + - all modification operations throw UnsupportedOperationException + after makeImmutable call + - all iterators (whether created before or after makeImmutable call) + throw U.O.E. after makeImmutable +ObjectId (DONE) + - constructed object returns same id + - test cases in equals +ObjectKey (DONE) + - constructed object returns same id, template + - write/read test + - getBytes returns correct value (test by using factory and + comparing) +ObjectKeyFactory (DONE) + - test create with hand created keys + - key length < 4 + - key length >= 4 + - magic is JAVAMAGIC + - scid is POA scid + - scid is JIDL scid + - other scid + - magic is not JAVAMAGIC + - test with error cases on length +POAObjectKeyTemplate (DONE) + - test that IDs match expected values when created from + byte[] in ObjectKeyFactory.create + - test that IDs match when created with explicit values + - write out and read back test + - getId correctly extracts id from key +TaggedComponentFactories (DONE) + - only tested inditectly by reading and writing IIOPProfileTemplate + that contains all components +TaggedComponentFactoryFinder (DONE) + - registered factory can be looked up + - lookup of unregistered factory returns null + - reads tagged component from stream as correct type if registered + - reads tagged component from stream as generic if not registered +TaggedProfileFactoryFinder (DONE) + - reads IIOP profile as IIOPProfile + - reads others as Generic +WireObjectTemplate (DONE) + - getId returns entire key as id + - serverId is -1 + - write out and read back test + +Interfaces (no tests): + IdEncapsulation + IdEncapsulationFactory + IdEncapsulationFactoryFinder + Identifiable + ObjectKeyTemplateo + ObjectKeyTemplate + TaggedComponent + TaggedProfile + TaggedProfileTemplate + Writeable + +Trivial classes: + ObjectIds diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/WireObjectKeyTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/WireObjectKeyTemplate.java new file mode 100644 index 000000000..e04d1824d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/WireObjectKeyTemplate.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; + +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.spi.logging.IORSystemException ; + +/** + * @author Ken Cavanaugh + */ +public class WireObjectKeyTemplate implements ObjectKeyTemplate +{ + private ORB orb ; + private static final IORSystemException wrapper = + IORSystemException.self ; + private static ObjectAdapterId NULL_OBJECT_ADAPTER_ID = + new ObjectAdapterIdArray( new String[0] ) ; + + @Override + public boolean equals( Object obj ) + { + if (obj == null) { + return false ; + } + + return obj instanceof WireObjectKeyTemplate ; + } + + @Override + public int hashCode() + { + return 53 ; // All WireObjectKeyTemplates are the same, so they should + // have the same hashCode. + } + + public WireObjectKeyTemplate( ORB orb ) + { + initORB( orb ) ; + } + + private void initORB( ORB orb ) + { + this.orb = orb ; + } + + public void write( ObjectId id, OutputStream os ) + { + byte[] key = id.getId() ; + os.write_octet_array( key, 0, key.length ) ; + } + + public void write( OutputStream os ) + { + // Does nothing + } + + public int getSubcontractId() + { + return ORBConstants.DEFAULT_SCID ; + } + + // While it might make sense to throw an exception here, this causes + // problems since we need to check whether unusual object references + // are local or not. It seems that the easiest way to handle this is + // to return an invalid server id. + public int getServerId() + { + return -1 ; + } + + public String getORBId() + { + throw wrapper.orbIdNotAvailable() ; + } + + public ObjectAdapterId getObjectAdapterId() + { + return NULL_OBJECT_ADAPTER_ID ; + + // throw wrapper.objectAdapterIdNotAvailable() ; + } + + // Adapter ID is not available, since our + // ORB did not implement the object carrying this key. + public byte[] getAdapterId() + { + throw wrapper.adapterIdNotAvailable() ; + } + + public ORBVersion getORBVersion() + { + return ORBVersionFactory.getFOREIGN() ; + } + + public ServerRequestDispatcher getServerRequestDispatcher( ObjectId id ) + { + byte[] bid = id.getId() ; + String str = new String( bid ) ; + return orb.getRequestDispatcherRegistry().getServerRequestDispatcher( + str ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/AlternateIIOPAddressComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/AlternateIIOPAddressComponentImpl.java new file mode 100644 index 000000000..1e60b1454 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/AlternateIIOPAddressComponentImpl.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent ; + +import org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS ; + +/** + * @author Ken Cavanaugh + */ +public class AlternateIIOPAddressComponentImpl extends TaggedComponentBase + implements AlternateIIOPAddressComponent +{ + private IIOPAddress addr ; + + public boolean equals( Object obj ) + { + if (!(obj instanceof AlternateIIOPAddressComponentImpl)) + return false ; + + AlternateIIOPAddressComponentImpl other = + (AlternateIIOPAddressComponentImpl)obj ; + + return addr.equals( other.addr ) ; + } + + public int hashCode() + { + return addr.hashCode() ; + } + + public String toString() + { + return "AlternateIIOPAddressComponentImpl[addr=" + addr + "]" ; + } + + public AlternateIIOPAddressComponentImpl( IIOPAddress addr ) + { + this.addr = addr ; + } + + public IIOPAddress getAddress() + { + return addr ; + } + + public void writeContents(OutputStream os) + { + addr.write( os ) ; + } + + public int getId() + { + return TAG_ALTERNATE_IIOP_ADDRESS.value ; // 3 in CORBA 2.3.1 13.6.3 + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/ClusterInstanceInfoComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/ClusterInstanceInfoComponentImpl.java new file mode 100644 index 000000000..6be732f80 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/ClusterInstanceInfoComponentImpl.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase; +import com.sun.corba.ee.spi.ior.iiop.ClusterInstanceInfoComponent; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class ClusterInstanceInfoComponentImpl extends TaggedComponentBase + implements ClusterInstanceInfoComponent { + + private final ClusterInstanceInfo clusterInstanceInfoValue; + + @Override + public boolean equals(Object obj) + { + if (!(obj instanceof ClusterInstanceInfoComponentImpl)) { + return false; + } + + ClusterInstanceInfoComponentImpl other = + (ClusterInstanceInfoComponentImpl)obj ; + + return clusterInstanceInfoValue.equals( + other.clusterInstanceInfoValue ) ; + } + + @Override + public int hashCode() { + return clusterInstanceInfoValue.hashCode() ; + } + + @Override + public String toString() { + return "ClusterInstanceInfoComponentImpl[clusterInstanceInfoValue=" + + clusterInstanceInfoValue + "]" ; + } + + public ClusterInstanceInfoComponentImpl( + ClusterInstanceInfo theClusterInstanceInfoValue) { + clusterInstanceInfoValue = theClusterInstanceInfoValue ; + } + + public ClusterInstanceInfo getClusterInstanceInfo() + { + return clusterInstanceInfoValue; + } + + public void writeContents(OutputStream os) { + clusterInstanceInfoValue.write(os); + } + + public int getId() { + return ORBConstants.FOLB_MEMBER_ADDRESSES_TAGGED_COMPONENT_ID ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/CodeSetsComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/CodeSetsComponentImpl.java new file mode 100644 index 000000000..827e5b368 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/CodeSetsComponentImpl.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase ; + +import com.sun.corba.ee.spi.ior.iiop.CodeSetsComponent ; + +import org.omg.IOP.TAG_CODE_SETS ; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; +import com.sun.corba.ee.impl.encoding.MarshalOutputStream ; +import com.sun.corba.ee.impl.encoding.MarshalInputStream ; + +/** + * @author + */ +public class CodeSetsComponentImpl extends TaggedComponentBase + implements CodeSetsComponent +{ + CodeSetComponentInfo csci ; + + public boolean equals( Object obj ) + { + if (!(obj instanceof CodeSetsComponentImpl)) + return false ; + + CodeSetsComponentImpl other = (CodeSetsComponentImpl)obj ; + + return csci.equals( other.csci ) ; + } + + public int hashCode() + { + return csci.hashCode() ; + } + + public String toString() + { + return "CodeSetsComponentImpl[csci=" + csci + "]" ; + } + + public CodeSetsComponentImpl() + { + // Uses our default code sets (see CodeSetComponentInfo) + csci = new CodeSetComponentInfo() ; + } + + public CodeSetsComponentImpl( InputStream is ) + { + csci = new CodeSetComponentInfo() ; + csci.read( (MarshalInputStream)is ) ; + } + + public CodeSetsComponentImpl(com.sun.corba.ee.spi.orb.ORB orb) + { + if (orb == null) + csci = new CodeSetComponentInfo(); + else + csci = orb.getORBData().getCodeSetComponentInfo(); + } + + public CodeSetComponentInfo getCodeSetComponentInfo() + { + return csci ; + } + + public void writeContents(OutputStream os) + { + csci.write( (MarshalOutputStream)os ) ; + } + + public int getId() + { + return TAG_CODE_SETS.value ; // 1 in CORBA 2.3.1 13.6.3 + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressBase.java new file mode 100644 index 000000000..3a63b472a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressBase.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop ; + +import org.omg.CORBA.BAD_PARAM ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; + +/** + * @author + */ +abstract class IIOPAddressBase implements IIOPAddress +{ + // Ports are marshalled as shorts on the wire. The IDL + // type is unsigned short, which lacks a convenient representation + // in Java in the 32768-65536 range. So, we treat ports as + // ints throught this code, except that marshalling requires a + // scaling conversion. intToShort and shortToInt are provided + // for this purpose. + protected short intToShort( int value ) + { + if (value > 32767) + return (short)(value - 65536) ; + return (short)value ; + } + + protected int shortToInt( short value ) + { + if (value < 0) + return value + 65536 ; + return value ; + } + + public void write( OutputStream os ) + { + os.write_string( getHost() ) ; + int port = getPort() ; + os.write_short( intToShort( port ) ) ; + } + + public boolean equals( Object obj ) + { + if (!(obj instanceof IIOPAddress)) + return false ; + + IIOPAddress other = (IIOPAddress)obj ; + + return getHost().equals(other.getHost()) && + (getPort() == other.getPort()) ; + } + + public int hashCode() + { + return getHost().hashCode() ^ getPort() ; + } + + public String toString() + { + return "IIOPAddress[" + getHost() + "," + getPort() + "]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressClosureImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressClosureImpl.java new file mode 100644 index 000000000..871118a67 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressClosureImpl.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.glassfish.pfl.basic.func.NullaryFunction; + +/** + * @author + */ +public final class IIOPAddressClosureImpl extends IIOPAddressBase +{ + private NullaryFunction host; + private NullaryFunction port; + + public IIOPAddressClosureImpl( NullaryFunction host, + NullaryFunction port ) { + this.host = host ; + this.port = port ; + } + + public String getHost() + { + return host.evaluate() ; + } + + public int getPort() + { + return port.evaluate() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressImpl.java new file mode 100644 index 000000000..1af20211f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPAddressImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.logging.IORSystemException ; + +/** + * @author Ken Cavanaugh + */ +public final class IIOPAddressImpl extends IIOPAddressBase +{ + private static final IORSystemException wrapper = + IORSystemException.self ; + + private String host; + private int port; + + public IIOPAddressImpl( String host, int port ) + { + if ((port < 0) || (port > 65535)) { + throw wrapper.badIiopAddressPort(port); + } + + this.host = host ; + this.port = port ; + } + + public IIOPAddressImpl( InputStream is ) + { + host = is.read_string() ; + short thePort = is.read_short() ; + port = shortToInt( thePort ) ; + } + + public String getHost() + { + return host ; + } + + public int getPort() + { + return port ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileImpl.java new file mode 100644 index 000000000..0cf94ce02 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileImpl.java @@ -0,0 +1,363 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import com.sun.corba.ee.impl.encoding.EncapsInputStream; +import com.sun.corba.ee.impl.encoding.EncapsInputStreamFactory; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.ior.EncapsulationUtility; +import com.sun.corba.ee.impl.orb.ORBVersionImpl; +import com.sun.corba.ee.impl.util.JDKBridge; +import com.sun.corba.ee.spi.ior.IORFactories; +import com.sun.corba.ee.spi.ior.IdentifiableBase; +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import com.sun.corba.ee.spi.ior.ObjectId; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +import com.sun.corba.ee.spi.ior.TaggedComponent; +import com.sun.corba.ee.spi.ior.TaggedProfile; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.JavaCodebaseComponent; +import com.sun.corba.ee.spi.logging.IORSystemException; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.trace.IsLocal; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import org.omg.IOP.TAG_INTERNET_IOP; +import org.omg.IOP.TAG_JAVA_CODEBASE; + +import java.util.Iterator; + +/** + * @author + */ +@IsLocal +public class IIOPProfileImpl extends IdentifiableBase implements IIOPProfile +{ + private static final IORSystemException wrapper = + IORSystemException.self ; + + private ORB orb ; + private ObjectId oid; + private IIOPProfileTemplate proftemp; + private ObjectKeyTemplate oktemp ; + private ObjectKey objectKey; + + // Cached lookups + protected String codebase = null ; + protected boolean cachedCodebase = false; + + private boolean checkedIsLocal = false ; + private boolean cachedIsLocal = false ; + + // initialize-on-demand holder + private static class LocalCodeBaseSingletonHolder { + public static JavaCodebaseComponent comp ; + + static { + String localCodebase = JDKBridge.getLocalCodebase() ; + if (localCodebase == null) { + comp = null; + } else { + comp = IIOPFactories.makeJavaCodebaseComponent(localCodebase); + } + } + } + + private GIOPVersion giopVersion = null; + + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "IIOPProfileImpl[proftemp=") ; + sb.append( proftemp.toString() ) ; + sb.append( " oktemp=" ) ; + sb.append( oktemp.toString() ) ; + sb.append( " oid=" ) ; + sb.append( oid.toString() ) ; + return sb.toString() ; + } + + @Override + public boolean equals( Object obj ) + { + if (!(obj instanceof IIOPProfileImpl)) { + return false; + } + + IIOPProfileImpl other = (IIOPProfileImpl)obj ; + + return oid.equals( other.oid ) && proftemp.equals( other.proftemp ) && + oktemp.equals( other.oktemp ) ; + } + + @Override + public int hashCode() + { + return oid.hashCode() ^ proftemp.hashCode() ^ oktemp.hashCode() ; + } + + public ObjectId getObjectId() + { + return oid ; + } + + public TaggedProfileTemplate getTaggedProfileTemplate() + { + return proftemp ; + } + + public ObjectKeyTemplate getObjectKeyTemplate() + { + return oktemp ; + } + + private IIOPProfileImpl( ORB orb ) + { + this.orb = orb ; + } + + public IIOPProfileImpl( ORB orb, ObjectKeyTemplate oktemp, ObjectId oid, + IIOPProfileTemplate proftemp ) + { + this( orb ) ; + this.oktemp = oktemp ; + this.oid = oid ; + this.proftemp = proftemp ; + } + + public IIOPProfileImpl( InputStream is ) + { + this( (ORB)(is.orb()) ) ; + init( is ) ; + } + + public IIOPProfileImpl( ORB orb, org.omg.IOP.TaggedProfile profile) + { + this( orb ) ; + + if (profile == null || profile.tag != TAG_INTERNET_IOP.value || + profile.profile_data == null) { + throw wrapper.invalidTaggedProfile() ; + } + + EncapsInputStream istr = EncapsInputStreamFactory.newEncapsInputStream(orb, profile.profile_data, + profile.profile_data.length); + istr.consumeEndian(); + init( istr ) ; + } + + private void init( InputStream istr ) + { + // First, read all of the IIOP IOR data + GIOPVersion version = new GIOPVersion() ; + version.read( istr ) ; + IIOPAddress primary = new IIOPAddressImpl( istr ) ; + byte[] key = EncapsulationUtility.readOctets( istr ) ; + + ObjectKey okey = orb.getObjectKeyFactory().create( key ) ; + oktemp = okey.getTemplate() ; + oid = okey.getId() ; + + proftemp = IIOPFactories.makeIIOPProfileTemplate( orb, + version, primary ) ; + + // Handle any tagged components (if applicable) + if (version.getMinor() > 0) { + EncapsulationUtility.readIdentifiableSequence(proftemp, + orb.getTaggedComponentFactoryFinder(), istr); + } + + // If there is no codebase in this IOR and there IS a + // java.rmi.server.codebase property set, we need to + // update the IOR with the local codebase. Note that + // there is only one instance of the local codebase, but it + // can be safely shared in multiple IORs since it is immutable. + if (uncachedGetCodeBase() == null) { + JavaCodebaseComponent jcc = LocalCodeBaseSingletonHolder.comp ; + + if (jcc != null) { + if (version.getMinor() > 0) { + proftemp.add(jcc); + } + + codebase = jcc.getURLs() ; + } + + // Whether codebase is null or not, we have it, + // and so getCodebase ned never call uncachedGetCodebase. + cachedCodebase = true; + } + } + + public void writeContents(OutputStream os) + { + proftemp.write( oktemp, oid, os ) ; + } + + public int getId() + { + return proftemp.getId() ; + } + + public boolean isEquivalent( TaggedProfile prof ) + { + if (!(prof instanceof IIOPProfile)) { + return false; + } + + IIOPProfile other = (IIOPProfile)prof ; + + return oid.equals( other.getObjectId() ) && + proftemp.isEquivalent( other.getTaggedProfileTemplate() ) && + oktemp.equals( other.getObjectKeyTemplate() ) ; + } + + public synchronized ObjectKey getObjectKey() + { + if (objectKey == null) { + objectKey = IORFactories.makeObjectKey( oktemp, oid ) ; + } + return objectKey ; + } + + public org.omg.IOP.TaggedProfile getIOPProfile() + { + EncapsOutputStream os = OutputStreamFactory.newEncapsOutputStream( orb ) ; + os.write_long( getId() ) ; + write( os ) ; + InputStream is = (InputStream)(os.create_input_stream()) ; + return org.omg.IOP.TaggedProfileHelper.read( is ) ; + } + + private String uncachedGetCodeBase() { + Iterator iter = + proftemp.iteratorById( TAG_JAVA_CODEBASE.value ) ; + + if (iter.hasNext()) { + JavaCodebaseComponent jcbc = + JavaCodebaseComponent.class.cast( iter.next() ) ; + return jcbc.getURLs() ; + } + + return null ; + } + + public synchronized String getCodebase() { + if (!cachedCodebase) { + cachedCodebase = true ; + codebase = uncachedGetCodeBase() ; + } + + return codebase ; + } + + /** + * @return the ORBVersion associated with the object key in the IOR. + */ + public ORBVersion getORBVersion() { + return oktemp.getORBVersion(); + } + + @InfoMethod + private void computingIsLocal( String host, int scid, int sid, int port ) {} + + @InfoMethod + private void isLocalResults( boolean isLocalHost, boolean isLocalServerId, + boolean isLocalPort ) {} + + @IsLocal + public synchronized boolean isLocal() + { + if (!checkedIsLocal) { + checkedIsLocal = true ; + if (isForeignObject()) return false; + + final int port = proftemp.getPrimaryAddress().getPort(); + final String host = proftemp.getPrimaryAddress().getHost() ; + final int scid = oktemp.getSubcontractId() ; + final int sid = oktemp.getServerId() ; + computingIsLocal( host, scid, sid, port ) ; + + final boolean isLocalHost = orb.isLocalHost( host ) ; + final boolean isLocalServerId = (sid == -1) || orb.isLocalServerId( scid, sid ) ; + final boolean isLocalServerPort = orb.getLegacyServerSocketManager().legacyIsLocalServerPort( port ) ; + isLocalResults( isLocalHost, isLocalServerId, isLocalServerPort ) ; + + cachedIsLocal = isLocalHost && isLocalServerId && isLocalServerPort ; + } + + return cachedIsLocal ; + } + + private boolean isForeignObject() { + return oktemp.getORBVersion() == ORBVersionImpl.FOREIGN; + } + + /** Return the servant for this IOR, if it is local AND if the OA that + * implements this objref supports direct access to servants outside of an + * invocation. + */ + @IsLocal + public java.lang.Object getServant() + { + if (!isLocal()) { + return null; + } + + RequestDispatcherRegistry scr = orb.getRequestDispatcherRegistry() ; + ObjectAdapterFactory oaf = scr.getObjectAdapterFactory( + oktemp.getSubcontractId() ) ; + + ObjectAdapterId oaid = oktemp.getObjectAdapterId() ; + ObjectAdapter oa = null ; + + try { + oa = oaf.find( oaid ) ; + } catch (SystemException exc) { + // Could not find the OA, so just return null. + // This usually happens when POAs are being deleted, + // and the POA always return null for getLocalServant anyway. + wrapper.getLocalServantFailure( exc, oaid ) ; + return null ; + } + + byte[] boid = oid.getId() ; + java.lang.Object servant = oa.getLocalServant( boid ) ; + return servant ; + } + + /** + * Return GIOPVersion for this IOR. + * Requests created against this IOR will be of the + * return Version. + */ + public synchronized GIOPVersion getGIOPVersion() + { + return proftemp.getGIOPVersion() ; + } + + public void makeImmutable() + { + proftemp.makeImmutable() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileTemplateImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileTemplateImpl.java new file mode 100644 index 000000000..edba0a5f8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileTemplateImpl.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import java.util.Iterator ; + +import org.omg.IOP.TAG_INTERNET_IOP ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import com.sun.corba.ee.spi.ior.TaggedProfile ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplateBase ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.ObjectId ; + +import com.sun.corba.ee.impl.ior.EncapsulationUtility ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; + +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.orb.ORB ; + +/** + * @author + * If getMinorVersion==0, this does not contain any tagged components + */ +public class IIOPProfileTemplateImpl extends TaggedProfileTemplateBase + implements IIOPProfileTemplate +{ + private ORB orb ; + private GIOPVersion giopVersion ; + private IIOPAddress primary ; + + public Iterator getTaggedComponents() { + return iterator() ; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "IIOPProfileTemplateImpl[giopVersion=") ; + sb.append(giopVersion.getMajor()).append('.').append(giopVersion.getMinor()) ; + sb.append( " primary=" ) ; + sb.append(primary.getHost()).append(':').append(primary.getPort()) ; + sb.append( ']' ) ; + return sb.toString() ; + } + + public boolean equals( Object obj ) + { + if (!(obj instanceof IIOPProfileTemplateImpl)) + return false ; + + IIOPProfileTemplateImpl other = (IIOPProfileTemplateImpl)obj ; + + return super.equals( obj ) && giopVersion.equals( other.giopVersion ) && + primary.equals( other.primary ) ; + } + + public int hashCode() + { + return super.hashCode() ^ giopVersion.hashCode() ^ primary.hashCode() ; + } + + public TaggedProfile create( ObjectKeyTemplate oktemp, ObjectId id ) + { + return IIOPFactories.makeIIOPProfile( orb, oktemp, id, this ) ; + } + + public GIOPVersion getGIOPVersion() + { + return giopVersion ; + } + + public IIOPAddress getPrimaryAddress() + { + return primary ; + } + + public IIOPProfileTemplateImpl( ORB orb, GIOPVersion version, IIOPAddress primary ) + { + this.orb = orb ; + this.giopVersion = version ; + this.primary = primary ; + if (giopVersion.getMinor() == 0) + // Adding tagged components is not allowed for IIOP 1.0, + // so this template is complete and should be made immutable. + makeImmutable() ; + } + + public IIOPProfileTemplateImpl( InputStream istr ) + { + byte major = istr.read_octet() ; + byte minor = istr.read_octet() ; + giopVersion = GIOPVersion.getInstance( major, minor ) ; + primary = new IIOPAddressImpl( istr ) ; + orb = (ORB)(istr.orb()) ; + // Handle any tagged components (if applicable) + if (minor > 0) + EncapsulationUtility.readIdentifiableSequence( + this, orb.getTaggedComponentFactoryFinder(), istr ) ; + + makeImmutable() ; + } + + public void write( ObjectKeyTemplate okeyTemplate, ObjectId id, OutputStream os) + { + giopVersion.write( os ) ; + primary.write( os ) ; + + // Note that this is NOT an encapsulation: do not marshal + // the endianness flag. However, the length is required. + // Note that this cannot be accomplished with a codec! + + // Use the byte order of the given stream + OutputStream encapsulatedOS = OutputStreamFactory.newEncapsOutputStream( (ORB)os.orb() + ) ; + + okeyTemplate.write( id, encapsulatedOS ) ; + EncapsulationUtility.writeOutputStream( encapsulatedOS, os ) ; + + if (giopVersion.getMinor() > 0) + EncapsulationUtility.writeIdentifiableSequence( this, os ) ; + } + + /** Write out this IIOPProfileTemplateImpl only. + */ + public void writeContents( OutputStream os) + { + giopVersion.write( os ) ; + primary.write( os ) ; + + if (giopVersion.getMinor() > 0) + EncapsulationUtility.writeIdentifiableSequence( this, os ) ; + } + + public int getId() + { + return TAG_INTERNET_IOP.value ; + } + + public boolean isEquivalent( TaggedProfileTemplate temp ) + { + if (!(temp instanceof IIOPProfileTemplateImpl)) + return false ; + + IIOPProfileTemplateImpl tempimp = (IIOPProfileTemplateImpl)temp ; + + return primary.equals( tempimp.primary ) ; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/JavaCodebaseComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/JavaCodebaseComponentImpl.java new file mode 100644 index 000000000..1b219032a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/JavaCodebaseComponentImpl.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.IOP.TAG_JAVA_CODEBASE ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase ; + +import com.sun.corba.ee.spi.ior.iiop.JavaCodebaseComponent ; + +/** + * @author + */ +public class JavaCodebaseComponentImpl extends TaggedComponentBase + implements JavaCodebaseComponent +{ + private String URLs ; + + public boolean equals( Object obj ) + { + if (obj == null) + return false ; + + if (!(obj instanceof JavaCodebaseComponentImpl)) + return false ; + + JavaCodebaseComponentImpl other = (JavaCodebaseComponentImpl)obj ; + + return URLs.equals( other.getURLs() ) ; + } + + public int hashCode() + { + return URLs.hashCode() ; + } + + public String toString() + { + return "JavaCodebaseComponentImpl[URLs=" + URLs + "]" ; + } + + public String getURLs() + { + return URLs ; + } + + public JavaCodebaseComponentImpl( String URLs ) + { + this.URLs = URLs ; + } + + public void writeContents(OutputStream os) + { + os.write_string( URLs ) ; + } + + public int getId() + { + return TAG_JAVA_CODEBASE.value ; // 25 in CORBA 2.3.1 13.6.3 + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/JavaSerializationComponent.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/JavaSerializationComponent.java new file mode 100644 index 000000000..2655fd579 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/JavaSerializationComponent.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.ior.TaggedComponentBase; + +/** + * Tagged component that contains a value that indicates the Java + * serialization version supported by the ORB. + * + * ORB Java serialization uses IIOP as the transport protocol, but uses + * Java serialization mechanism and its accompanying encodings, instead + * of IIOP CDR serialization mechanism. Java serialization is generally + * observed to be faster than CDR. + */ +public class JavaSerializationComponent extends TaggedComponentBase { + + private byte version; + + private static JavaSerializationComponent singleton; + + static { + singleton = new JavaSerializationComponent( + ORBConstants.JAVA_ENC_VERSION); + } + + public static JavaSerializationComponent singleton() { + return singleton; + } + + public JavaSerializationComponent(byte version) { + this.version = version; + } + + public byte javaSerializationVersion() { + return this.version; + } + + public void writeContents(OutputStream os) { + os.write_octet(version); + } + + public int getId() { + return ORBConstants.TAG_JAVA_SERIALIZATION_ID; + } + + public boolean equals(Object obj) { + if (!(obj instanceof JavaSerializationComponent)) { + return false; + } + JavaSerializationComponent other = (JavaSerializationComponent) obj; + return this.version == other.version; + } + + public int hashCode() { + return this.version; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/LoadBalancingComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/LoadBalancingComponentImpl.java new file mode 100644 index 000000000..e26cc3d52 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/LoadBalancingComponentImpl.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase; +import com.sun.corba.ee.spi.ior.iiop.LoadBalancingComponent; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class LoadBalancingComponentImpl extends TaggedComponentBase + implements LoadBalancingComponent +{ + + private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private int loadBalancingValue; + + @Override + public boolean equals(Object obj) + { + if (!(obj instanceof LoadBalancingComponentImpl)) { + return false; + } + + LoadBalancingComponentImpl other = + (LoadBalancingComponentImpl)obj ; + + return loadBalancingValue == other.loadBalancingValue ; + } + + @Override + public int hashCode() + { + return loadBalancingValue; + } + + @Override + public String toString() + { + return "LoadBalancingComponentImpl[loadBalancingValue=" + loadBalancingValue + "]" ; + } + + public LoadBalancingComponentImpl() + { + loadBalancingValue = 0; + } + + public LoadBalancingComponentImpl(int theLoadBalancingValue) { + if (theLoadBalancingValue < ORBConstants.FIRST_LOAD_BALANCING_VALUE || + theLoadBalancingValue > ORBConstants.LAST_LOAD_BALANCING_VALUE) { + throw wrapper.invalidLoadBalancingComponentValue( + theLoadBalancingValue, + ORBConstants.FIRST_LOAD_BALANCING_VALUE, + ORBConstants.LAST_LOAD_BALANCING_VALUE ); + } + loadBalancingValue = theLoadBalancingValue; + } + + public int getLoadBalancingValue() + { + return loadBalancingValue; + } + + public void writeContents(OutputStream os) + { + os.write_ulong(loadBalancingValue); + } + + public int getId() + { + return ORBConstants.TAG_LOAD_BALANCING_ID; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/MaxStreamFormatVersionComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/MaxStreamFormatVersionComponentImpl.java new file mode 100644 index 000000000..3a4307ff4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/MaxStreamFormatVersionComponentImpl.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.IOP.TAG_RMI_CUSTOM_MAX_STREAM_FORMAT; + +import org.omg.CORBA_2_3.portable.OutputStream; + +import javax.rmi.CORBA.ValueHandler; +import javax.rmi.CORBA.ValueHandlerMultiFormat; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase; + +import com.sun.corba.ee.spi.ior.iiop.MaxStreamFormatVersionComponent; + +// Java to IDL ptc 02-01-12 1.4.11 +// TAG_RMI_CUSTOM_MAX_STREAM_FORMAT +public class MaxStreamFormatVersionComponentImpl extends TaggedComponentBase + implements MaxStreamFormatVersionComponent +{ + private byte version; + + public static final MaxStreamFormatVersionComponentImpl singleton + = new MaxStreamFormatVersionComponentImpl(); + + public boolean equals(Object obj) + { + if (!(obj instanceof MaxStreamFormatVersionComponentImpl)) + return false ; + + MaxStreamFormatVersionComponentImpl other = + (MaxStreamFormatVersionComponentImpl)obj ; + + return version == other.version ; + } + + public int hashCode() + { + return version ; + } + + public String toString() + { + return "MaxStreamFormatVersionComponentImpl[version=" + version + "]" ; + } + + public MaxStreamFormatVersionComponentImpl() + { + version = ORBUtility.getMaxStreamFormatVersion(); + } + + public MaxStreamFormatVersionComponentImpl(byte streamFormatVersion) { + version = streamFormatVersion; + } + + public byte getMaxStreamFormatVersion() + { + return version; + } + + public void writeContents(OutputStream os) + { + os.write_octet(version); + } + + public int getId() + { + return TAG_RMI_CUSTOM_MAX_STREAM_FORMAT.value; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/ORBTypeComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/ORBTypeComponentImpl.java new file mode 100644 index 000000000..01fbbf325 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/ORBTypeComponentImpl.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.IOP.TAG_ORB_TYPE ; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase ; + +import com.sun.corba.ee.spi.ior.iiop.ORBTypeComponent ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +/** + * @author Ken Cavanaugh + */ +public class ORBTypeComponentImpl extends TaggedComponentBase + implements ORBTypeComponent +{ + private int ORBType; + + public boolean equals( Object obj ) + { + if (!(obj instanceof ORBTypeComponentImpl)) + return false ; + + ORBTypeComponentImpl other = (ORBTypeComponentImpl)obj ; + + return ORBType == other.ORBType ; + } + + public int hashCode() + { + return ORBType ; + } + + public String toString() + { + return "ORBTypeComponentImpl[ORBType=" + ORBType + "]" ; + } + + public ORBTypeComponentImpl(int ORBType) + { + this.ORBType = ORBType ; + } + + public int getId() + { + return TAG_ORB_TYPE.value ; // 0 in CORBA 2.3.1 13.6.3 + } + + public int getORBType() + { + return ORBType ; + } + + public void writeContents(OutputStream os) + { + os.write_ulong( ORBType ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/RequestPartitioningComponentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/RequestPartitioningComponentImpl.java new file mode 100644 index 000000000..e8c7f2be0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/iiop/RequestPartitioningComponentImpl.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.TaggedComponentBase; +import com.sun.corba.ee.spi.ior.iiop.RequestPartitioningComponent; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class RequestPartitioningComponentImpl extends TaggedComponentBase + implements RequestPartitioningComponent +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private int partitionToUse; + + @Override + public boolean equals(Object obj) + { + if (!(obj instanceof RequestPartitioningComponentImpl)) { + return false; + } + + RequestPartitioningComponentImpl other = + (RequestPartitioningComponentImpl)obj ; + + return partitionToUse == other.partitionToUse ; + } + + @Override + public int hashCode() + { + return partitionToUse; + } + + @Override + public String toString() + { + return "RequestPartitioningComponentImpl[partitionToUse=" + partitionToUse + "]" ; + } + + public RequestPartitioningComponentImpl() + { + partitionToUse = 0; + } + + public RequestPartitioningComponentImpl(int thePartitionToUse) { + if (thePartitionToUse < ORBConstants.REQUEST_PARTITIONING_MIN_THREAD_POOL_ID || + thePartitionToUse > ORBConstants.REQUEST_PARTITIONING_MAX_THREAD_POOL_ID) { + throw wrapper.invalidRequestPartitioningComponentValue( + thePartitionToUse, + ORBConstants.REQUEST_PARTITIONING_MIN_THREAD_POOL_ID, + ORBConstants.REQUEST_PARTITIONING_MAX_THREAD_POOL_ID); + } + partitionToUse = thePartitionToUse; + } + + public int getRequestPartitioningId() + { + return partitionToUse; + } + + public void writeContents(OutputStream os) + { + os.write_ulong(partitionToUse); + } + + public int getId() + { + return ORBConstants.TAG_REQUEST_PARTITIONING_ID; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/ior/notes.txt b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/notes.txt new file mode 100644 index 000000000..4de511e61 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/ior/notes.txt @@ -0,0 +1,327 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Notes on IOR implementation + +1. Writeable is an interface that can write itself to an OutputStream. + +2. IdEncapsulation is a particular kind of Writeable that has an Id and + an Encapsulation (a sequence of bytes) representing some other structure + in a CDR encapsulation. + +3. ContainerBase is a base class for containers of IdEncapsulations. + +4. An IOR is a ContainerBase. + +5. A TaggedComponent is not a ContainerBase. + +6. Some (not all) Profiles are ContainerBases. + +7. IIOPAddress contains (host, port) + IIOPServerLocation contains: + - A primary IIOPAddress + - 0 or more secondary IIOPAddresses (these get placed in + TAG_ALTERNATE_IIOP_ADDRESS components) + +8. IIOPProfileTemplate: + - major, minor version + - 0 or more TaggedComponents + - ObjectKeyTemplate + +9. ObjectKeyTemplate: + - contains only wire data, not internal structures + + write( object id, output stream ): write the object key out + to the output stream with the given object id + +10. Significant problem: must of the dispatch path code is written in terms of + IORs when it should be based on profiles. Only a single profile is used in + a request, and that is what should be passed around. This needs fixing soon + to accommodate the eventual implementation of CORBA FT, and also to work + properly with the new IOR. + +11. Another question: since profile contains key which contains scid, what if + we have multiple profiles with different scids? + One answer: create a cluster subcontract that invokes the individual + profiles for FT. This may not mesh well with the FT spec. + +12. Uses of IORs in the ORB: + +Activation/ServerManagerImpl.java + - Construct IOR for bad ID handler location forward +corba/ClientDelegate.java + - marshal, getIOR, unmarshal are all questionable and make + poor use of IOR. + - gets forwarded IOR from response + - IORs handled in some service contexts + - createRequest needs to parse IOR + - gets the (one) IIOP profile that we care about + - gets the object key +corba/InitialNamingClient.java + - constructs IOR from address info, object key + - current implementation should use AlternateIIOPAddress components + - constructs IOR with key "INIT" for old bootstrap +corba/ORB.java + - stringify and destringify IOR +corba/ServerDelegate.java + - access IOR from sending context service context + - destroyObjref directly access transient key from a known offset. + - creation sets up key inline with known offsets +core/IOR.java + - IOR sometimes stores a servant + - IOR contains the following + - Object servant + - Endpoint ep + - String codebase + - boolean cachedCodebase + - TaggedComponent localCodeBaseTC + - InternetIOPTag + - The two constructors that take full args also + construct tagged components + - will need alternate address components for INS +core/SendingContextServiceContext.java + - reads IOR from input stream +iiop/CDRInputStream.java + - needs type id, code base from IOR +iiop/IIOPOutputStream.java + - needs to access objkey as a sequence of bytes to realing requests. +POA/GenericPOAClientSC.java + - needs to pull POA ID out of object key + - needs to created a new IOR that has an updated scid +POA/GenericPOAServerSC.java + - creates IORs +TransactionalPOA/TransactionalServerSC.java + - inline access to known offset in object key to + determine whether transactional + +Guide to the files: + +Basic Interfaces: + Identifiable.java (Object has an Id) + Writeable.java (Object can write to OutputStream) + IdEncapsulation.java (Writeable, Identifiable interface) + IdEncapsulationFactory.java (Factory interface for IdEncapsulation) + IdEncapsulationFactoryFinder.java (Finder interface for IdEncapsulationFactoryFinder) + + IIOPAddress.java (class containing host and port for IIOP) + +Basic support for IdEncapsulations (shared for components and profiles): + GenericIdEncapsulation.java (Has id, octet sequence: used for generic + TaggedComponent and TaggedProfile objects) + FreezableList.java (Delegated implementation of List that can be made + immutable after construction) + IdentifiableContainerBase.java (extends FreezableList: container of Identifiable: + supports iteratorById.) + IdEncapsulationContainerBase.java (extends IdenitifableContainerBase: + container of IdEncapsulation: supports read/write IdEncapsulationSequence) + +Object Keys: + ObjectKeyFactory.java + ObjectKeyTemplate.java (interface for the following:) + JIDLObjectKeyTemplate.java (object key used in *Delegate) + POAObjectKeyTemplate.java (object key used in GenericPOA*SC) + WireObjectKeyTemplate.java (used for non-Sun ORB IORs) + ObjectId.java (a simple wrapper for byte[]) + ObjectKey.java (contains ObjectId and ObjectKeyTemplate) + +Components: + TaggedComponentFactories.java (contains method for registering factories) + TaggedComponentFactoryFinder.java (contains registered factories) + TaggedComponent.java (interface of all tagged components) + AlternateIIOPAddressComponent.java + CodeSetsComponent.java + JavaCodebaseComponent.java + ORBTypeComponent.java + PoliciesComponent.java + +Profiles: + IIOPProfile.java (IIOPProfileTemplate and ObjectId) + IIOPProfileTemplate.java (contains version, address, ObjectKeyTemplate, + list of TaggedComponent) + TaggedProfile.java (interface for all TaggedProfiles) + TaggedProfileFactoryFinder.java + TaggedProfileTemplate.java + +IOR: + IOR.java + IORTemplate.java (List of IIOPProfileTemplate + ObjectIds.java (List of ObjectId: needed for an IOR constructor) + +Notes from integration code review: + +General: + - Look at making IOR API public, or + move everything into com.sun.corba.ee.impl.ior + (don't hold up putback for this) + Making public: + - Writeable needs getBytes() as well as write() + methods. + - codec can be used with an Any to convert between + IDL data type and sequence of bytes. + - write() needs to use getBytes, then write id, length, + octets to output stream. + - getBytes() method needs to get typecode from IDL + then create Any. + - IdEncapsulations need to have constructor that takes + byte[] (encapsulation of value). + Why not? + - Unencapsulated object keys can't be made portable + - Lots of dependencies on ORB code in ObjectKey support + Conclusion: + - move to internal (DONE) + - JAVA_MAGIC should move to ObjectKeyTemplates (DONE) + - check for intToBytes/bytesToInt related to object key + corba/ServerDelegate (DONE) + POA/GenericPOAServerSC (DONE) + POA/SubcontractResponseHandler (DONE) + TransactionalPOA/TransactionalClientSC.java (DONE) + TransactionalPOA/TransactionalServerSC.java (DONE) + +./com/sun/corba/ee/impl/cosnaming/BootstrapServer.java + - remove sc_init_key_* (DONE) + +./com/sun/corba/ee/impl/poa/POAImpl.java + - remove line 130: comment on other endpoints, e.g. SSL (DONE) + - add revisit comment on line 133: use multiple server port API (DONE) + +./com/sun/corba/ee/impl/corba/ORB.java + - object_to_string: add comment that connect only takes place in + non-POA cases. (DONE) + +./com/sun/corba/ee/impl/corba/ServerDelegate.java + - chase down the object key offsets (DONE) + (search for bytesToInt and intToBytes) + +./com/sun/corba/ee/impl/core/SubcontractRegistry.java + - getServerSubcontract: add b-e l-e comment and history on INIT, TINI (DONE) + - getServerSubcontract: reference to constants (May not do this?) + - getServerSubcontract: return null at end IS reachable, in the + case where we have essentially a name in the key that isn't + one of the ones we support. Throw an exception? (DONE) + - add minor code for INTERNAL (and string) (DONE) + - remove setId calls in callers to getClientSubcontract (DONE) + - throw INTERNAL exception for temp.size() != 1 case (DONE) + Think about INST corbaloc problems (multi-profile IORs) + both return nulls should throw exceptions (DONE) + +./com/sun/corba/ee/impl/core/IOR.java + - Add some comments to getIORfromString about 4/2 constants (DONE) + - fix name: should be getIORFromString (DONE) + - IOR( InputStream ) has a problem with cachedCodeBase: + is should not call getCodeBase: must refactor to + an internal implementation method. (DONE) + - isEquivalent and isLocal should assert failure + if multiple profiles (through exception in getProfile) (DONE) + (add comments about multi case) + +./com/sun/corba/ee/impl/iiop/CDRInputStream_1_0.java + - read_Object: add assert in case servant is not Tie or objref (DONE) + +./com/sun/corba/ee/internal/TransactionalPOA/TransactionalPOAImpl.java + - add comment about transactionalIortemplate: goes away after + we get to OTS 1.2 transactional policy. (DONE) + - change transactionalClone( ObjectKeyTemplate ) so that + we get an error (INTERNAL) if NOT POAObjectKeyTemplate (DONE) + - line 138: get string constant from + org.omg.CosTransactions.TransactionalObject (DONE) + - remove Delegate d decl. (DONE) + +We need to assign minor codes for all exceptions! + +We need to clean up the minor code base usage! (DONE) + +Add equals/toString to: + Do not try to develop a reflective universal equals: too slow! + Do we really want equals on lists? + If we do, define collectionEqual on FreezableList + +CodeSetsComponent: toString +FreezableList: basic toString, equals methods +IIOPProfile: toString +IIOPProfileTemplate: toString +IOR: toString +IORTemplate.java: toString, equals (inherit?) +IdEncapsulationContainerBase.java: make abstract, but provide base toString/equals +IdentifiableContainerBase.java: make abstract (no other changes) + (ContainerBase classes need some explanation) +ObjectIds.java needs toString, equals (use FreezableList?) +ObjectKey: toString +ObjectKeyFactory.java: singleton: don't add toString or equals +PoliciesComponent.java: should finish this sometime (after we figure out + exactly what to do with it) +TaggedComponentBase.java: should be abstract +TaggedComponentFactories.java: a singelton +TaggedComponentFactoryFinder.java: a singleton +TaggedProfileFactoryFinder.java: a singleton +JIDLObjectKeyTemplate: toString +POAObjectKeyTemplate: toString +WireObjectKeyTemplate: toString uninteresting: no data, equals not useful + +use util/Utility.objectToString to implement toString methods. + +Other changes: + + IIOPAddress.toString should include class name (DONE) + + New tests needed: + IIOPProfile.getIOPComponents + IIOPProfile.getIOPProfile + GenericTaggedProfile.getIOPComponents + GenericTaggedProfile.getIOPProfile + GenericTaggedComponent.getIOPComponent + ObjectKeyTemplate.getAdapterId + + Plus, do a read/write test for IOP stuff: + construct profile + convert to IOP.TaggedProfile + write to stream + get input stream + construct profile + check for equal + + do some tests on IOR.toString() just to see what gets printed. + + Add getAdapterId to *ObjectKeyTemplate.java (DONE) + Add some tests for this: + - WireObjectKeyTemplate throws an exception + - Identically constructed ObjectKeyTemplates produce identical Adapter Ids. + - Different OKTs produce different adapter IDs. + +New tests for versioning support: + +ORBVersionFactory: + - for create array methods (DONE) + - returns expected values for version encodings + - throws INTERNAL for negative version + - test one case for create stream method (DONE) + - getORBVersion returns correct version (DONE) +ORBVersionImpl: + - check equals on some ORBVersions (DONE) + - check that each ORBVersion returns correct orbtype (DONE) +JIDLObjectKeyTemplate: + - non-key constructor gives NEWER version (DONE) +POAObjectKeyTemplate: + - non-key constructor gives NEWER version (DONE) +OldJIDLObjectKeyTemplate: (DONE) + - non-key constructor with OLD, NEW MAGIC and check version + - other values throw exception +OldPOAObjectKeyTemplate: (DONE) + - non-key constructor with OLD, NEW MAGIC and check version (DONE) + - other values throw exception (DONE) +WireObjectKeyTemplate (DONE) + - version is FOREIGN +ObjectKeyFactory (DONE) + create the following keys and check results: + JIDL OLD OldJIDL with correct magic, version + JIDL NEW OldJIDL + JIDL NEWER JIDL + POA OLD OldPOA + POA NEW OldPOA + POA NEWER POA diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/CORBA/StubDelegateImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/CORBA/StubDelegateImpl.java new file mode 100644 index 000000000..23408e5c4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/CORBA/StubDelegateImpl.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.javax.rmi.CORBA; + +import java.io.IOException; + +import java.rmi.RemoteException; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.impl.ior.StubIORImpl ; +import com.sun.corba.ee.impl.presentation.rmi.StubConnectImpl ; + +import com.sun.corba.ee.spi.logging.UtilSystemException ; + +/** + * Base class from which all static RMI-IIOP stubs must inherit. + */ +public class StubDelegateImpl implements javax.rmi.CORBA.StubDelegate +{ + private static final UtilSystemException wrapper = + UtilSystemException.self ; + + private StubIORImpl ior ; + + public synchronized StubIORImpl getIOR() + { + return ior ; + } + + public synchronized void setIOR( StubIORImpl ior ) + { + this.ior = ior ; + } + + public StubDelegateImpl() + { + ior = null ; + } + + /** + * Sets the IOR components if not already set. + */ + private synchronized void init (javax.rmi.CORBA.Stub self) + { + // If the Stub is not connected to an ORB, BAD_OPERATION exception + // will be raised by the code below. + if (ior == null) { + ior = new StubIORImpl(self); + } + } + + /** + * Returns a hash code value for the object which is the same for all stubs + * that represent the same remote object. + * @return the hash code value. + */ + public synchronized int hashCode(javax.rmi.CORBA.Stub self) + { + init(self); + return ior.hashCode() ; + } + + /** + * Compares two stubs for equality. Returns true when used to compare stubs + * that represent the same remote object, and false otherwise. + * @param obj the reference object with which to compare. + * @return true if this object is the same as the obj + * argument; false otherwise. + */ + public synchronized boolean equals(javax.rmi.CORBA.Stub self, java.lang.Object obj) + { + if (self == obj) { + return true; + } + + if (!(obj instanceof javax.rmi.CORBA.Stub)) { + return false; + } + + // no need to call init() because of calls to hashCode() below + + javax.rmi.CORBA.Stub other = (javax.rmi.CORBA.Stub) obj; + if (other.hashCode() != self.hashCode()) { + return false; + } + + // hashCodes being the same does not mean equality. The stubs still + // could be pointing to different IORs. So, do a literal comparison. + // Apparently the ONLY way to do this (other than using private + // reflection) is toString, because it is not possible to directly + // access the StubDelegateImpl from the Stub. + return self.toString().equals( other.toString() ) ; + } + + @Override + public synchronized boolean equals( Object obj ) + { + if (this == obj) { + return true; + } + + if (!(obj instanceof StubDelegateImpl)) { + return false; + } + + StubDelegateImpl other = (StubDelegateImpl)obj ; + + if (ior == null) { + return ior == other.ior; + } else { + return ior.equals(other.ior); + } + } + + @Override + public synchronized int hashCode() { + if (ior == null) { + return 0; + } else { + return ior.hashCode(); + } + } + + /** + * Returns a string representation of this stub. Returns the same string + * for all stubs that represent the same remote object. + * @return a string representation of this stub. + */ + public synchronized String toString(javax.rmi.CORBA.Stub self) + { + if (ior == null) { + return null; + } else { + return ior.toString(); + } + } + + /** + * Connects this stub to an ORB. Required after the stub is deserialized + * but not after it is demarshalled by an ORB stream. If an unconnected + * stub is passed to an ORB stream for marshalling, it is implicitly + * connected to that ORB. Application code should not call this method + * directly, but should call the portable wrapper method + * {@link javax.rmi.PortableRemoteObject#connect}. + * @param orb the ORB to connect to. + * @exception RemoteException if the stub is already connected to a different + * ORB, or if the stub does not represent an exported remote or local object. + */ + public synchronized void connect(javax.rmi.CORBA.Stub self, ORB orb) + throws RemoteException + { + ior = StubConnectImpl.connect( ior, self, self, orb ) ; + } + + /** + * Serialization method to restore the IOR state. + */ + public synchronized void readObject(javax.rmi.CORBA.Stub self, + java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException + { + if (ior == null) { + ior = new StubIORImpl(); + } + + ior.doRead( stream ) ; + } + + /** + * Serialization method to save the IOR state. + * @serialData The length of the IOR type ID (int), followed by the IOR type ID + * (byte array encoded using ISO8859-1), followed by the number of IOR profiles + * (int), followed by the IOR profiles. Each IOR profile is written as a + * profile tag (int), followed by the length of the profile data (int), followed + * by the profile data (byte array). + */ + public synchronized void writeObject(javax.rmi.CORBA.Stub self, + java.io.ObjectOutputStream stream) throws IOException + { + init(self); + ior.doWrite( stream ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/CORBA/Util.java b/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/CORBA/Util.java new file mode 100644 index 000000000..7ce022c73 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/CORBA/Util.java @@ -0,0 +1,749 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.javax.rmi.CORBA; // Util (sed marker, don't remove!) + +import com.sun.corba.ee.impl.io.SharedSecrets; +import com.sun.corba.ee.impl.misc.ClassInfoCache; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.util.JDKBridge; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.copyobject.CopierManager; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.logging.UtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import org.glassfish.pfl.basic.logex.OperationTracer; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopier; +import org.glassfish.pfl.dynamic.copyobject.spi.ReflectiveCopyException; +import org.omg.CORBA.*; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.UnknownException; + +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.ValueHandler; +import javax.transaction.InvalidTransactionException; +import javax.transaction.TransactionRequiredException; +import javax.transaction.TransactionRolledbackException; +import java.io.NotSerializableException; +import java.io.Serializable; +import java.rmi.AccessException; +import java.rmi.MarshalException; +import java.rmi.NoSuchObjectException; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.ServerError; +import java.rmi.ServerException; +import java.rmi.UnexpectedException; +import java.rmi.server.RMIClassLoader; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.WeakHashMap; +import java.lang.Object; + +// These classes only exist in Java SE 6 and later. +// This class must be able to function with non-Sun ORBs. +// This means that any of the following com.sun.corba classes +// must only occur in contexts that also handle the non-Sun case. + +/** + * Provides utility methods that can be used by stubs and ties to + * perform common operations. + */ +public class Util implements javax.rmi.CORBA.UtilDelegate +{ + // Runs as long as there are exportedServants + private static KeepAlive keepAlive = null; + + // Maps targets to ties. + private static final IdentityHashMap exportedServants = new IdentityHashMap<>(); + + private static ValueHandler valueHandlerSingleton; + + private static final UtilSystemException utilWrapper = UtilSystemException.self ; + + private static Util instance = null; + + // XXX Would like to have a WeakConcurrentHashMap here to reduce contention, + // but that is only available with Google collections at present. + private WeakHashMap, String> annotationMap = new WeakHashMap<>(); + + private static final java.lang.Object annotObj = new java.lang.Object(); + + static { + // Note: there uses to be code here to use the JDK value handler for embedded + // web logic. I removed it after 3.1.0-b008. + valueHandlerSingleton = SharedSecrets.getJavaCorbaAccess().newValueHandlerImpl(); + } + + // This constructor MUST be public, or Util.createDelegateIfSpecified will fail! + // It is only called from getInstance and javax.rmi.CORBA.Util.createDelegateIfSpecified (in + // the newInstance call). + // + // Note that it is possible to construct more than one instance of Util. This can happen + // if we both do something to javax.rmi.CORBA.Util that causes the delegate to be initialized + // AND we call getInstance inside the ORB. This MAY cause problems with ORB shutdown and + // the unexport. I tried to modify this class to guarantee that only one copy gets created. + // That resulted in Issue 3080 filed against GlassFish v2 b49, where an ORB client called + // new InitialContext, which initialized the se version of the UtilDelegate, which consequently caused + // every call to getInstance to return null. BAD BUG! As it is currently (5/30/07) very + // close to the end of the development cycle for GFv2, I am reverting this change back to the + // previous version, which has worked well in GF. + public Util() { } + + public static synchronized Util getInstance() { + if (instance == null) { + instance = new Util() ; + } + + return instance ; + } + + // Used by TOAFactory.shutdown to unexport all targets for this + // particular ORB. This happens during ORB shutdown. + public void unregisterTargetsForORB(org.omg.CORBA.ORB orb) + { + // Copy exportedServants set we don't get a + // ConcurrentModificationException. + Map copy = new IdentityHashMap<>(exportedServants) ; + + for (Remote key : copy.keySet() ) { + Remote target = key instanceof Tie ? ((Tie)key).getTarget() : key ; + + // Bug 4476347: BAD_OPERATION is thrown if the ties delegate isn't set. + // We can ignore this because it means the tie is not connected to an ORB. + try { + if (orb == getTie(target).orb()) { + try { + unexportObject(target); + } catch( java.rmi.NoSuchObjectException ex ) { + // We neglect this exception if at all if it is + // raised. It is not harmful. + } + } + } catch (SystemException se) { + utilWrapper.handleSystemException(se); + } + } + } + + /** + * Maps a SystemException to a RemoteException. + * @param ex the SystemException to map. + * @return the mapped exception. + */ + public RemoteException mapSystemException(SystemException ex) + { + if (ex instanceof UnknownException) { + Throwable orig = ((UnknownException)ex).originalEx; + if (orig instanceof Error) { + return new ServerError("Error occurred in server thread",(Error)orig); + } else if (orig instanceof RemoteException) { + return new ServerException("RemoteException occurred in server thread", + (Exception)orig); + } else if (orig instanceof RuntimeException) { + throw (RuntimeException) orig; + } + } + + // Build the message string... + String name = ex.getClass().getName(); + String corbaName = name.substring(name.lastIndexOf('.')+1); + String status; + switch (ex.completed.value()) { + case CompletionStatus._COMPLETED_YES: + status = "Yes"; + break; + case CompletionStatus._COMPLETED_NO: + status = "No"; + break; + case CompletionStatus._COMPLETED_MAYBE: + default: + status = "Maybe"; + break; + } + + String message = "CORBA " + corbaName + " " + ex.minor + " " + status; + + // Now map to the correct RemoteException type... + if (ex instanceof COMM_FAILURE) { + return new MarshalException(message, ex); + } else if (ex instanceof INV_OBJREF) { + RemoteException newEx = new NoSuchObjectException(message); + newEx.detail = ex; + return newEx; + } else if (ex instanceof NO_PERMISSION) { + return new AccessException(message, ex); + } else if (ex instanceof MARSHAL) { + return new MarshalException(message, ex); + } else if (ex instanceof OBJECT_NOT_EXIST) { + RemoteException newEx = new NoSuchObjectException(message); + newEx.detail = ex; + return newEx; + } else if (ex instanceof TRANSACTION_REQUIRED) { + RemoteException newEx = new TransactionRequiredException(message); + newEx.detail = ex; + return newEx; + } else if (ex instanceof TRANSACTION_ROLLEDBACK) { + RemoteException newEx = new TransactionRolledbackException(message); + newEx.detail = ex; + return newEx; + } else if (ex instanceof INVALID_TRANSACTION) { + RemoteException newEx = new InvalidTransactionException(message); + newEx.detail = ex; + return newEx; + } else if (ex instanceof BAD_PARAM) { + Exception inner = ex; + + // Pre-Merlin Sun ORBs used the incorrect minor code for + // this case. See Java to IDL ptc-00-01-08 1.4.8. + if (ex.minor == ORBConstants.LEGACY_SUN_NOT_SERIALIZABLE || + ex.minor == OMGSystemException.NOT_SERIALIZABLE) { + + if (ex.getMessage() != null) { + inner = new NotSerializableException(ex.getMessage()); + } else { + inner = new NotSerializableException(); + } + + inner.initCause( ex ) ; + } + + return new MarshalException(message,inner); + } + + // Just map to a generic RemoteException... + return new RemoteException(message, ex); + } + + /** + * Writes any java.lang.Object as a CORBA any. + * @param out the stream in which to write the any. + * @param obj the object to write as an any. + */ + public void writeAny( org.omg.CORBA.portable.OutputStream out, + java.lang.Object obj) + { + org.omg.CORBA.ORB orb = out.orb(); + + // Make sure we have a connected object... + java.lang.Object newObj = Utility.autoConnect(obj, orb, false); + + // In JSG (Java Serialization with GIOP) we avoid using Any and + // Typecode implementations, as they are not necessary for + // serialization using Java. Further, the current Typecode IO + // stream objects are error-prone, and they tend to use encoding + // specific details such as indirections, etc. + if (ORBUtility.getEncodingVersion() != ORBConstants.CDR_ENC_VERSION) { + ((org.omg.CORBA_2_3.portable.OutputStream)out). + write_abstract_interface(newObj); + return; + } + + // Create Any + Any any = orb.create_any(); + + if (newObj instanceof org.omg.CORBA.Object) { + any.insert_Object((org.omg.CORBA.Object)newObj); + } else { + if (newObj == null) { + // Handle the null case, including backwards + // compatibility issues + any.insert_Value(null, createTypeCodeForNull(orb)); + } else { + if (newObj instanceof Serializable) { + // If they're our Any and ORB implementations, + // we may want to do type code related versioning. + TypeCode tc = createTypeCode((Serializable)newObj, any, orb); + if (tc == null) { + any.insert_Value((Serializable) newObj); + } else { + any.insert_Value((Serializable) newObj, tc); + } + } else if (newObj instanceof Remote) { + ORBUtility.throwNotSerializableForCorba(newObj.getClass().getName()); + } else { + ORBUtility.throwNotSerializableForCorba(newObj.getClass().getName()); + } + } + } + + out.write_any(any); + } + + /** + * When using our own ORB and Any implementations, we need to get + * the ORB version and create the type code appropriately. This is + * to overcome a bug in which the JDK 1.3.x ORBs used a tk_char + * rather than a tk_wchar to describe a Java char field. + * + * This only works in RMI-IIOP with Util.writeAny since we actually + * know what ORB and stream we're writing with when we insert + * the value. + * + * Returns null if it wasn't possible to create the TypeCode (means + * it wasn't our ORB or Any implementation). + * + * This does not handle null objs. + */ + private TypeCode createTypeCode(Serializable obj, + org.omg.CORBA.Any any, + org.omg.CORBA.ORB orb) { + + if (any instanceof com.sun.corba.ee.impl.corba.AnyImpl && + orb instanceof ORB) { + + com.sun.corba.ee.impl.corba.AnyImpl anyImpl + = (com.sun.corba.ee.impl.corba.AnyImpl)any; + + ORB ourORB = (ORB)orb; + + return anyImpl.createTypeCodeForClass(obj.getClass(), ourORB); + } else { + return null; + } + } + + + /** + * This is used to create the TypeCode for a null reference. + * It also handles backwards compatibility with JDK 1.3.x. + * + * This method will not return null. + */ + private TypeCode createTypeCodeForNull(org.omg.CORBA.ORB orb) + { + if (orb instanceof ORB) { + + ORB ourORB = (ORB)orb; + + // Preserve backwards compatibility with Kestrel and Ladybird + // by not fully implementing interop issue resolution 3857, + // and returning a null TypeCode with a tk_value TCKind. + // If we're not talking to Kestrel or Ladybird, fall through + // to the abstract interface case (also used for foreign ORBs). + if (!ORBVersionFactory.getFOREIGN().equals(ourORB.getORBVersion()) && + ORBVersionFactory.getNEWER().compareTo(ourORB.getORBVersion()) > 0) { + + return orb.get_primitive_tc(TCKind.tk_value); + } + } + + // Use tk_abstract_interface as detailed in the resolution + + // REVISIT: Define this in IDL and get the ID in generated code + String abstractBaseID = "IDL:omg.org/CORBA/AbstractBase:1.0"; + + return orb.create_abstract_interface_tc(abstractBaseID, ""); + } + + /** + * Reads a java.lang.Object as a CORBA any. + * @param in the stream from which to read the any. + * @return the object read from the stream. + */ + public Object readAny(InputStream in) + { + // In JSG (Java Serialization with GIOP) we avoid using Any and + // Typecode implementations, as they are not necessary for + // serialization using Java. Further, the current Typecode IO + // stream objects are error-prone, and they tend to use encoding + // specific details such as indirections, etc. + if (ORBUtility.getEncodingVersion() != ORBConstants.CDR_ENC_VERSION) { + return ((org.omg.CORBA_2_3.portable.InputStream)in). + read_abstract_interface(); + } + + Any any = in.read_any(); + if ( any.type().kind().value() == TCKind._tk_objref ) { + return any.extract_Object(); + } else { + return any.extract_Value(); + } + } + + /** + * Writes a java.lang.Object as a CORBA Object. If obj is + * an exported RMI-IIOP server object, the tie is found + * and wired to obj, then written to out.write_Object(org.omg.CORBA.Object). + * If obj is a CORBA Object, it is written to + * out.write_Object(org.omg.CORBA.Object). + * @param out the stream in which to write the object. + * @param obj the object to write. + */ + public void writeRemoteObject(OutputStream out, java.lang.Object obj) + { + // Make sure we have a connected object, then + // write it out... + + Object newObj = Utility.autoConnect(obj,out.orb(),false); + out.write_Object((org.omg.CORBA.Object)newObj); + } + + /** + * Writes a java.lang.Object as either a value or a CORBA Object. + * If obj is a value object or a stub object, it is written to + * out.write_abstract_interface(java.lang.Object). If obj is an exported + * RMI-IIOP server object, the tie is found and wired to obj, + * then written to out.write_abstract_interface(java.lang.Object). + * @param out the stream in which to write the object. + * @param obj the object to write. + */ + public void writeAbstractObject( OutputStream out, java.lang.Object obj ) + { + // Make sure we have a connected object, then + // write it out... + + Object newObj = Utility.autoConnect(obj,out.orb(),false); + ((org.omg.CORBA_2_3.portable.OutputStream)out).write_abstract_interface(newObj); + } + + /** + * Registers a target for a tie. Adds the tie to an internal table and calls + * {@link Tie#setTarget} on the tie object. + * @param tie the tie to register. + * @param target the target for the tie. + */ + @SuppressWarnings("unchecked") + public void registerTarget(javax.rmi.CORBA.Tie tie, java.rmi.Remote target) + { + synchronized (exportedServants) { + // Do we already have this target registered? + if (lookupTie(target) == null) { + // No, so register it and set the target... + exportedServants.put(target,tie); + tie.setTarget(target); + + // Do we need to instantiate our keep-alive thread? + if (keepAlive == null) { + // Yes. Instantiate our keep-alive thread and start + // it up... + keepAlive = (KeepAlive)AccessController.doPrivileged( + new PrivilegedAction() { + public java.lang.Object run() { + return new KeepAlive(); + } + }); + keepAlive.start(); + } + } + } + } + + /** + * Removes the associated tie from an internal table and calls {@link Tie#deactivate} + * to deactivate the object. + * @param target the object to unexport. + */ + public void unexportObject(java.rmi.Remote target) + throws java.rmi.NoSuchObjectException + { + synchronized (exportedServants) { + Tie cachedTie = lookupTie(target); + if (cachedTie != null) { + exportedServants.remove(target); + Utility.purgeStubForTie(cachedTie); + Utility.purgeTieAndServant(cachedTie); + try { + cleanUpTie(cachedTie); + } catch (BAD_OPERATION e) { + // ignore + } catch (org.omg.CORBA.OBJ_ADAPTER e) { + // This can happen when the target was never associated with a POA. + // We can safely ignore this case. + } + + // Is it time to shut down our keep alive thread? + if (exportedServants.isEmpty()) { + keepAlive.quit(); + keepAlive = null; + } + } else { + throw new java.rmi.NoSuchObjectException("Tie not found" ); + } + } + } + + protected void cleanUpTie(Tie cachedTie) + throws java.rmi.NoSuchObjectException + { + cachedTie.setTarget(null); + cachedTie.deactivate(); + } + + /** + * Returns the tie (if any) for a given target object. + * @return the tie or null if no tie is registered for the given target. + */ + public Tie getTie (Remote target) + { + synchronized (exportedServants) { + return lookupTie(target); + } + } + + /** + * An unsynchronized version of getTie() for internal use. + */ + private static Tie lookupTie (Remote target) + { + Tie result = exportedServants.get(target); + if (result == null && target instanceof Tie) { + if (exportedServants.containsKey(target)) { + result = (Tie)target; + } + } + return result; + } + + /** + * Returns a singleton instance of a class that implements the + * {@link ValueHandler} interface. + * @return a class which implements the ValueHandler interface. + */ + public ValueHandler createValueHandler() + { + return valueHandlerSingleton; + } + + /** + * Returns the codebase, if any, for the given class. + * @param clz the class to get a codebase for. + * @return a space-separated list of URLs, or null. + */ + public String getCodebase(java.lang.Class clz) { + String annot ; + synchronized (annotObj) { + annot = annotationMap.get(clz); + } + + if (annot == null) { + // This can be an expensive operation, so don't hold the lock here. + annot = RMIClassLoader.getClassAnnotation(clz); + + synchronized( annotObj ) { + annotationMap.put(clz, annot); + } + } + + return annot; + } + + /** + * Returns a class instance for the specified class. + * @param className the name of the class. + * @param remoteCodebase a space-separated list of URLs at which + * the class might be found. May be null. + * @param loader a ClassLoader who may be used to + * load the class if all other methods fail. + * @return the Class object representing the loaded class. + * @exception ClassNotFoundException if class cannot be loaded. + */ + public Class loadClass( String className, String remoteCodebase, + ClassLoader loader) throws ClassNotFoundException + { + return JDKBridge.loadClass(className,remoteCodebase,loader); + } + + /** + * The isLocal method has the same semantics as the + * ObjectImpl._is_local method, except that it can throw a RemoteException. + * (no it doesn't but the spec says it should.) + * + * The _is_local() method is provided so that stubs may determine + * if a particular object is implemented by a local servant and hence local + * invocation APIs may be used. + * + * @param stub the stub to test. + * + * @return The _is_local() method returns true if + * the servant incarnating the object is located in the same process as + * the stub and they both share the same ORB instance. The _is_local() + * method returns false otherwise. The default behavior of _is_local() is + * to return false. + * + * @throws RemoteException The Java to IDL specification does to + * specify the conditions that cause a RemoteException to be thrown. + */ + public boolean isLocal(javax.rmi.CORBA.Stub stub) throws RemoteException + { + boolean result = false ; + + try { + org.omg.CORBA.portable.Delegate delegate = stub._get_delegate() ; + if (delegate instanceof ClientDelegate) { + // For the Sun ORB + ClientDelegate cdel = (ClientDelegate)delegate ; + ContactInfoList cil = cdel.getContactInfoList() ; + LocalClientRequestDispatcher lcs = + cil.getLocalClientRequestDispatcher() ; + result = lcs.useLocalInvocation( null ) ; + } else { + // For a non-Sun ORB + result = delegate.is_local( stub ) ; + } + } catch (SystemException e) { + throw mapSystemException(e); + } + + return result ; + } + + /** + * Wraps an exception thrown by an implementation + * method. It returns the corresponding client-side exception. + * @param orig the exception to wrap. + * @return the wrapped exception. + */ + public RemoteException wrapException(Throwable orig) + { + if (orig instanceof SystemException) { + return mapSystemException((SystemException)orig); + } + + if (orig instanceof Error) { + return new ServerError("Error occurred in server thread",(Error)orig); + } else if (orig instanceof RemoteException) { + return new ServerException("RemoteException occurred in server thread", + (Exception)orig); + } else if (orig instanceof RuntimeException) { + throw (RuntimeException) orig; + } + + if (orig instanceof Exception) { + return new UnexpectedException(orig.toString(), + (Exception) orig); + } else { + return new UnexpectedException(orig.toString()); + } + } + + /** + * Copies or connects an array of objects. Used by local stubs + * to copy any number of actual parameters, preserving sharing + * across parameters as necessary to support RMI semantics. + * @param obj the objects to copy or connect. + * @param orb the ORB. + * @return the copied or connected objects. + * @exception RemoteException if any object could not be copied or connected. + */ + public Object[] copyObjects (Object[] obj, org.omg.CORBA.ORB orb) + throws RemoteException + { + if (obj == null) { + throw new NullPointerException(); + } + + Class compType = obj.getClass().getComponentType() ; + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( compType ) ; + if (cinfo.isARemote(compType) && cinfo.isInterface()) { + // obj is an array of remote impl types. This + // causes problems with stream copier, so we copy + // it over to an array of Remotes instead. + Remote[] result = new Remote[obj.length] ; + System.arraycopy( (Object)obj, 0, (Object)result, 0, obj.length ) ; + return (Object[])copyObject( result, orb ) ; + } else { + return (Object[]) copyObject( obj, orb ); + } + } + + /** + * Copies or connects an object. Used by local stubs to copy + * an actual parameter, result object, or exception. + * @param obj the object to copy. + * @param orb the ORB. + * @return the copy or connected object. + * @exception RemoteException if the object could not be copied or connected. + */ + public Object copyObject (Object obj, org.omg.CORBA.ORB orb) + throws RemoteException + { + try { + if (((ORB)orb).operationTraceDebugFlag) { + OperationTracer.enable() ; + } + + OperationTracer.begin( "copyObject") ; + + if (orb instanceof ORB) { + ORB lorb = (ORB)orb ; + + try { + try { + // This gets the copier for the current invocation, which was + // previously set by preinvoke. + return lorb.peekInvocationInfo().getCopierFactory().make().copy( obj ) ; + } catch (java.util.EmptyStackException exc) { + // copyObject was invoked outside of an invocation, probably by + // a test. Get the default copier from the ORB. + CopierManager cm = lorb.getCopierManager() ; + ObjectCopier copier = cm.getDefaultObjectCopierFactory().make() ; + return copier.copy( obj ) ; + } + } catch (ReflectiveCopyException exc) { + RemoteException rexc = new RemoteException() ; + rexc.initCause( exc ) ; + throw rexc ; + } + } else { + if (obj instanceof Remote) { + // Make sure obj is connected and converted to a stub, + // if necessary. + return Utility.autoConnect( obj, orb, true ) ; + } + + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream)orb.create_output_stream(); + out.write_value((Serializable)obj); + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream)out.create_input_stream(); + return in.read_value(); + } + } finally { + OperationTracer.disable(); + OperationTracer.finish(); + } + } +} + +class KeepAlive extends Thread +{ + boolean quit = false; + + public KeepAlive () + { + setDaemon(false); + } + + @Override + public synchronized void run () + { + while (!quit) { + try { + wait(); + } catch (InterruptedException e) {} + } + } + + public synchronized void quit () + { + quit = true; + notifyAll(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/PortableRemoteObject.java b/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/PortableRemoteObject.java new file mode 100644 index 000000000..c30e64a8d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/javax/rmi/PortableRemoteObject.java @@ -0,0 +1,342 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.javax.rmi; + +import java.lang.reflect.Method ; + +import javax.rmi.CORBA.Tie; + +import java.rmi.RemoteException; +import java.rmi.NoSuchObjectException; +import java.rmi.Remote; + +import java.util.Properties; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.portable.Delegate; +import org.omg.CORBA.SystemException; + +import java.rmi.server.UnicastRemoteObject; +import java.rmi.server.RemoteStub; +import java.rmi.server.ExportException; + +import java.net.URL; + +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; + +import java.security.AccessController; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +/** + * Server implementation objects may either inherit from + * javax.rmi.PortableRemoteObject or they may implement a remote interface + * and then use the exportObject method to register themselves as a server object. + * The toStub method takes a server implementation and returns a stub that + * can be used to access that server object. + * The connect method makes a Remote object ready for remote communication. + * The unexportObject method is used to deregister a server object, allowing it to become + * available for garbage collection. + * The narrow method takes an object reference or abstract interface type and + * attempts to narrow it to conform to + * the given interface. If the operation is successful the result will be an + * object of the specified type, otherwise an exception will be thrown. + */ +public class PortableRemoteObject + implements javax.rmi.CORBA.PortableRemoteObjectDelegate { + + /** + * Makes a server object ready to receive remote calls. Note + * that subclasses of PortableRemoteObject do not need to call this + * method, as it is called by the constructor. + * @param obj the server object to export. + * @exception RemoteException if export fails. + */ + public void exportObject(Remote obj) + throws RemoteException { + + if (obj == null) { + throw new NullPointerException("invalid argument"); + } + + // Has this object already been exported to IIOP? + + if (Util.getInstance().getTie(obj) != null) { + + // Yes, so this is an error... + + throw new ExportException (obj.getClass().getName() + " already exported"); + } + + // Can we load a Tie? + + Tie theTie = Utility.loadTie(obj); + + if (theTie != null) { + + // Yes, so export it to IIOP... + + Util.getInstance().registerTarget(theTie,obj); + + } else { + + // No, so export to JRMP. If this is called twice for the + // same object, it will throw an ExportException... + + UnicastRemoteObject.exportObject(obj); + } + } + + /** + * Returns a stub for the given server object. + * @param obj the server object for which a stub is required. Must either be a subclass + * of PortableRemoteObject or have been previously the target of a call to + * {@link #exportObject}. + * @return the most derived stub for the object. + * @exception NoSuchObjectException if a stub cannot be located for the given server object. + */ + public Remote toStub (Remote obj) + throws NoSuchObjectException + { + Remote result = null; + if (obj == null) { + throw new NullPointerException("invalid argument"); + } + + // If the class is already an IIOP stub then return it. + if (StubAdapter.isStub( obj )) { + return obj; + } + + // If the class is already a JRMP stub then return it. + if (obj instanceof java.rmi.server.RemoteStub) { + return obj; + } + + // Has it been exported to IIOP? + Tie theTie = Util.getInstance().getTie(obj); + + if (theTie != null) { + result = Utility.loadStub(theTie,null,null,true); + } else { + if (Utility.loadTie(obj) == null) { + result = java.rmi.server.RemoteObject.toStub(obj); + } + } + + if (result == null) { + throw new NoSuchObjectException("object not exported"); + } + + return result; + } + + /** + * Deregisters a server object from the runtime, allowing the object to become + * available for garbage collection. + * @param obj the object to unexport. + * @exception NoSuchObjectException if the remote object is not + * currently exported. + */ + public void unexportObject(Remote obj) + throws NoSuchObjectException { + + if (obj == null) { + throw new NullPointerException("invalid argument"); + } + + if (StubAdapter.isStub(obj) || + obj instanceof java.rmi.server.RemoteStub) { + throw new NoSuchObjectException( + "Can only unexport a server object."); + } + + Tie theTie = Util.getInstance().getTie(obj); + if (theTie != null) { + Util.getInstance().unexportObject(obj); + } else { + if (Utility.loadTie(obj) == null) { + UnicastRemoteObject.unexportObject(obj,true); + } else { + throw new NoSuchObjectException("Object not exported."); + } + } + } + + /** + * Checks to ensure that an object of a remote or abstract interface type + * can be cast to a desired type. + * @param narrowFrom the object to check. + * @param narrowTo the desired type. + * @return an object which can be cast to the desired type. + * @throws ClassCastException if narrowFrom cannot be cast to narrowTo. + */ + public java.lang.Object narrow ( java.lang.Object narrowFrom, + java.lang.Class narrowTo) throws ClassCastException + { + java.lang.Object result = null; + + if (narrowFrom == null) + return null; + + if (narrowTo == null) + throw new NullPointerException("invalid argument"); + + try { + if (narrowTo.isAssignableFrom(narrowFrom.getClass())) + return narrowFrom; + + // Is narrowTo an interface that might be + // implemented by a servant running on iiop? + if (ClassInfoCache.get( narrowTo ).isInterface() && + narrowTo != java.io.Serializable.class && + narrowTo != java.io.Externalizable.class) { + + org.omg.CORBA.Object narrowObj + = (org.omg.CORBA.Object) narrowFrom; + + // Create an id from the narrowTo type... + String id = RepositoryId.createForAnyType(narrowTo); + + if (narrowObj._is_a(id)) { + return Utility.loadStub(narrowObj,narrowTo); + } else { + throw new ClassCastException( "Object is not of remote type " + + narrowTo.getName() ) ; + } + } else { + throw new ClassCastException( "Class " + narrowTo.getName() + + " is not a valid remote interface" ) ; + } + } catch(Exception error) { + ClassCastException cce = new ClassCastException() ; + cce.initCause( error ) ; + throw cce ; + } + } + + /** + * Makes a Remote object ready for remote communication. This normally + * happens implicitly when the object is sent or received as an argument + * on a remote method call, but in some circumstances it is useful to + * perform this action by making an explicit call. See the + * {@link Stub#connect} method for more information. + * @param target the object to connect. + * @param source a previously connected object. + * @throws RemoteException if source is not connected + * or if target is already connected to a different ORB than + * source. + */ + public void connect (Remote target, Remote source) + throws RemoteException + { + if (target == null || source == null) { + throw new NullPointerException("invalid argument"); + } + + ORB orb = null; + try { + if (StubAdapter.isStub( source )) { + orb = StubAdapter.getORB( source ) ; + } else { + // Is this a servant that was exported to iiop? + Tie tie = Util.getInstance().getTie(source); + if (tie == null) { + /* loadTie always succeeds for dynamic RMI-IIOP + // No, can we get a tie for it? If not, + // assume that source is a JRMP object... + if (Utility.loadTie(source) != null) { + // Yes, so it is an iiop object which + // has not been exported... + throw new RemoteException( + "'source' object not exported"); + } + */ + } else { + orb = tie.orb(); + } + } + } catch (SystemException e) { + throw new RemoteException("'source' object not connected", e ); + } + + boolean targetIsIIOP = false ; + Tie targetTie = null; + if (StubAdapter.isStub(target)) { + targetIsIIOP = true; + } else { + targetTie = Util.getInstance().getTie(target); + if (targetTie != null) { + targetIsIIOP = true; + } else { + /* loadTie always succeeds for dynamic RMI-IIOP + if (Utility.loadTie(target) != null) { + throw new RemoteException("'target' servant not exported"); + } + */ + } + } + + if (!targetIsIIOP) { + // Yes. Do we have an ORB from the source object? + // If not, we're done - there is nothing to do to + // connect a JRMP object. If so, it is an error because + // the caller mixed JRMP and IIOP... + if (orb != null) { + throw new RemoteException( + "'source' object exported to IIOP, 'target' is JRMP"); + } + } else { + // The target object is IIOP. Make sure we have a + // valid ORB from the source object... + if (orb == null) { + throw new RemoteException( + "'source' object is JRMP, 'target' is IIOP"); + } + + // And, finally, connect it up... + try { + if (targetTie != null) { + // Is the tie already connected? + try { + ORB existingOrb = targetTie.orb(); + + // Yes. Is it the same orb? + if (existingOrb == orb) { + + // Yes, so nothing to do... + return; + } else { + // No, so this is an error... + throw new RemoteException( + "'target' object was already connected"); + } + } catch (SystemException e) {} + + // No, so do it... + targetTie.orb(orb); + } else { + StubAdapter.connect( target, orb ) ; + } + } catch (SystemException e) { + + // The stub or tie was already connected... + throw new RemoteException( + "'target' object was already connected", e ); + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/DefaultSocketFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/DefaultSocketFactory.java new file mode 100644 index 000000000..bfba9d075 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/DefaultSocketFactory.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.legacy.connection.GetEndPointInfoAgainException; +import com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class DefaultSocketFactory + implements + ORBSocketFactory +{ + private com.sun.corba.ee.spi.orb.ORB orb; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public DefaultSocketFactory() + { + } + + public void setORB(com.sun.corba.ee.spi.orb.ORB orb) + { + this.orb = orb; + } + + public ServerSocket createServerSocket(String type, int port) + throws + IOException + { + if (! type.equals(ORBSocketFactory.IIOP_CLEAR_TEXT)) { + throw wrapper.defaultCreateServerSocketGivenNonIiopClearText( type ) ; + } + + ServerSocket serverSocket; + + if (orb.getORBData().acceptorSocketType().equals(ORBConstants.SOCKETCHANNEL)) { + ServerSocketChannel serverSocketChannel = + ServerSocketChannel.open(); + serverSocket = serverSocketChannel.socket(); + } else { + serverSocket = new ServerSocket(); + } + serverSocket.bind(new InetSocketAddress(port)); + return serverSocket; + } + + public SocketInfo getEndPointInfo(ORB orb, + IOR ior, + SocketInfo socketInfo) + { + IIOPProfileTemplate temp = + (IIOPProfileTemplate)ior.getProfile().getTaggedProfileTemplate() ; + IIOPAddress primary = temp.getPrimaryAddress() ; + + return new EndPointInfoImpl(ORBSocketFactory.IIOP_CLEAR_TEXT, + primary.getPort(), + primary.getHost().toLowerCase()); + } + + public Socket createSocket(SocketInfo socketInfo) + throws + IOException, + GetEndPointInfoAgainException + { + Socket socket; + + if (orb.getORBData().acceptorSocketType().equals(ORBConstants.SOCKETCHANNEL)) { + InetSocketAddress address = + new InetSocketAddress(socketInfo.getHost(), + socketInfo.getPort()); + SocketChannel socketChannel = ORBUtility.openSocketChannel(address); + socket = socketChannel.socket(); + } else { + socket = new Socket(socketInfo.getHost(), + socketInfo.getPort()); + } + + // REVISIT - this is done in SocketOrChannelConnectionImpl + try { + socket.setTcpNoDelay(true); + } catch (Exception e) { + wrapper.couldNotSetTcpNoDelay( e ) ; + } + return socket; + } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/EndPointInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/EndPointInfoImpl.java new file mode 100644 index 000000000..83524e7d4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/EndPointInfoImpl.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; + +public class EndPointInfoImpl + implements + SocketInfo, + LegacyServerSocketEndPointInfo +{ + + protected String type; + protected String hostname; + protected int port; + protected int locatorPort; + protected String name; + + public EndPointInfoImpl(String type, int port, String hostname) { + this.type = type; + this.port = port; + this.hostname = hostname; + this.locatorPort = -1; + this.name = LegacyServerSocketEndPointInfo.NO_NAME; + } + + public String getType() { + return type; + } + + public String getHost() { + return hostname; + } + + public String getHostName() { + return hostname; + } + + public int getPort() { + return port; + } + + public int getLocatorPort () + { + return locatorPort; + } + + public void setLocatorPort (int port) + { + locatorPort = port; + } + + public String getName() + { + return name; + } + + public int hashCode() { + return type.hashCode() ^ hostname.hashCode() ^ port; + } + + public boolean equals(Object obj) { + if (!(obj instanceof EndPointInfoImpl)) { + return false; + } + EndPointInfoImpl other = (EndPointInfoImpl)obj; + if (type == null) { + if (other.type != null) { + return false; + } + } else if (!type.equals(other.type)) { + return false; + } + if (port != other.port) { + return false; + } + if (!hostname.equals(other.hostname)) { + return false; + } + return true; + } + + public String toString () + { + return + type + " " + + name + " " + + hostname + " " + + port; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/LegacyServerSocketManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/LegacyServerSocketManagerImpl.java new file mode 100644 index 000000000..197a59e57 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/LegacyServerSocketManagerImpl.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import java.util.Collection; +import java.util.Iterator; + +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.CompletionStatus; + + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketManager; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +public class LegacyServerSocketManagerImpl + implements + LegacyServerSocketManager +{ + protected ORB orb; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public LegacyServerSocketManagerImpl(ORB orb) { + this.orb = orb; + } + + //////////////////////////////////////////////////// + // + // LegacyServerSocketManager + // + + // Only used in ServerManagerImpl. + public int legacyGetTransientServerPort(String type) + { + return legacyGetServerPort(type, false); + } + + // Only used by POAPolicyMediatorBase. + public synchronized int legacyGetPersistentServerPort(String socketType) + { + if (orb.getORBData().getServerIsORBActivated()) { + // this server is activated by orbd + return legacyGetServerPort(socketType, true); + } else if (orb.getORBData().getPersistentPortInitialized()) { + // this is a user-activated server + return orb.getORBData().getPersistentServerPort(); + } else { + throw wrapper.persistentServerportNotSet(); + } + } + + // Only used by PI IORInfoImpl. + public synchronized int legacyGetTransientOrPersistentServerPort( + String socketType) + { + return legacyGetServerPort(socketType, + orb.getORBData() + .getServerIsORBActivated()); + } + + // Used in RepositoryImpl, ServerManagerImpl, POAImpl, + // POAPolicyMediatorBase, TOAImpl. + // To get either default or bootnaming endpoint. + public synchronized LegacyServerSocketEndPointInfo legacyGetEndpoint( + String name) + { + Iterator iterator = getAcceptorIterator(); + while (iterator.hasNext()) { + LegacyServerSocketEndPointInfo endPoint = cast(iterator.next()); + if (endPoint != null && name.equals(endPoint.getName())) { + return endPoint; + } + } + throw new INTERNAL("No acceptor for: " + name); + } + + // Check to see if the given port is equal to any of the ORB Server Ports. + // Used in IIOPProfileImpl, ORBImpl. + public boolean legacyIsLocalServerPort(int port) + { + // If port is 0 (which signifies in CSIv2 that clear text + // communication is not allowed), we must return true, because + // this check is not meaningful. + if (port == 0) { + return true ; + } + + Iterator iterator = getAcceptorIterator(); + while (iterator.hasNext()) { + LegacyServerSocketEndPointInfo endPoint = cast(iterator.next()); + if (endPoint != null && endPoint.getPort() == port) { + return true; + } + } + return false; + } + + //////////////////////////////////////////////////// + // + // Implementation. + // + + private int legacyGetServerPort (String socketType, boolean isPersistent) + { + Iterator endpoints = getAcceptorIterator(); + while (endpoints.hasNext()) { + LegacyServerSocketEndPointInfo ep = cast(endpoints.next()); + if (ep != null && ep.getType().equals(socketType)) { + if (isPersistent) { + return ep.getLocatorPort(); + } else { + return ep.getPort(); + } + } + } + return -1; + } + + private Iterator getAcceptorIterator() + { + Collection acceptors = + orb.getCorbaTransportManager().getAcceptors(null, null); + if (acceptors != null) { + return acceptors.iterator(); + } + + throw wrapper.getServerPortCalledBeforeEndpointsInitialized() ; + } + + private LegacyServerSocketEndPointInfo cast(Object o) + { + if (o instanceof LegacyServerSocketEndPointInfo) { + return (LegacyServerSocketEndPointInfo) o; + } + return null; + } + + protected void dprint(String msg) + { + ORBUtility.dprint("LegacyServerSocketManagerImpl", msg); + } +} + +// End of file. + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryAcceptorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryAcceptorImpl.java new file mode 100644 index 000000000..48f0b4ed1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryAcceptorImpl.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import java.util.Iterator ; + +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.oa.poa.Policies; +import com.sun.corba.ee.impl.transport.AcceptorImpl; +import com.sun.corba.ee.spi.trace.Transport; + +/** + * @author Harold Carr + */ +@Transport +public class SocketFactoryAcceptorImpl + extends + AcceptorImpl +{ + public SocketFactoryAcceptorImpl(ORB orb, int port, + String name, String type) + { + super(orb, port, name, type); + } + + @Transport + @Override + public boolean initialize() + { + if (initialized) { + return false; + } + try { + serverSocket = orb.getORBData() + .getLegacySocketFactory().createServerSocket(type, port); + internalInitialize(); + } catch (Throwable t) { + throw wrapper.createListenerFailed( t, "localhost", port ) ; + } + initialized = true; + return true; + } + + //////////////////////////////////////////////////// + // + // Implementation. + // + + @Override + protected String toStringName() + { + return "SocketFactoryAcceptorImpl"; + } + + // Fix for 6331566. + // This Acceptor must NOT contribute alternate IIOP address components + // to the standard IIOPProfileTemplate, + // because typically this is used for special addresses (such as SSL + // ports) that must NOT be present in tag alternate components. + // However, this method MUST add an IIOPProfileTemplate if one is + // not already present. + @Override + public void addToIORTemplate( IORTemplate iorTemplate, + Policies policies, String codebase ) + { + Iterator iterator = iorTemplate.iteratorById( + org.omg.IOP.TAG_INTERNET_IOP.value); + + if (!iterator.hasNext()) { + // If this is the first call, create the IIOP profile template. + IIOPProfileTemplate iiopProfile = makeIIOPProfileTemplate( + policies, codebase ) ; + iorTemplate.add(iiopProfile); + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryConnectionImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryConnectionImpl.java new file mode 100644 index 000000000..febb6b336 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryConnectionImpl.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + + + + +import com.sun.corba.ee.spi.legacy.connection.GetEndPointInfoAgainException; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.transport.ConnectionImpl; +import com.sun.corba.ee.spi.trace.Transport; +import java.net.Socket; + +/** + * @author Harold Carr + */ +@Transport +public class SocketFactoryConnectionImpl + extends + ConnectionImpl +{ + @Transport + private void connectionCreated( Socket socket ) { } + + // Socket-factory client constructor. + public SocketFactoryConnectionImpl(ORB orb, + ContactInfo contactInfo, + boolean useSelectThreadToWait, + boolean useWorkerThread) + { + super(orb, useSelectThreadToWait, useWorkerThread); + + // REVISIT - probably need a contact info for both + // client and server for removing connections from cache? + this.contactInfo = contactInfo; + + SocketInfo socketInfo = + // REVISIT - case - needs interface method + ((SocketFactoryContactInfoImpl)contactInfo).socketInfo; + try { + defineSocket(useSelectThreadToWait, orb.getORBData().getLegacySocketFactory().createSocket(socketInfo)); + connectionCreated( socket ) ; + } catch (GetEndPointInfoAgainException ex) { + throw wrapper.connectFailure( + ex, socketInfo.getType(), socketInfo.getHost(), + Integer.toString(socketInfo.getPort())) ; + } catch (Exception ex) { + throw wrapper.connectFailure( + ex, socketInfo.getType(), socketInfo.getHost(), + Integer.toString(socketInfo.getPort())) ; + } + setState(OPENING); + } + + public String toString() + { + synchronized ( stateEvent ){ + return + "SocketFactoryConnectionImpl[" + " " + + (socketChannel == null ? + socket.toString() : socketChannel.toString()) + " " + + getStateString(getState()) + " " + + shouldUseSelectThreadToWait() + " " + + shouldUseWorkerThreadForEvent() + + "]" ; + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoImpl.java new file mode 100644 index 000000000..c2f425759 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoImpl.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.transport.ContactInfoImpl; + + +/** + * @author Harold Carr + */ +public class SocketFactoryContactInfoImpl + extends + ContactInfoImpl +{ + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + protected SocketInfo socketInfo; + + // XREVISIT + // See SocketOrChannelAcceptorImpl.createMessageMediator + // See SocketFactoryContactInfoImpl.constructor() + // See SocketOrChannelContactInfoImpl.constructor() + public SocketFactoryContactInfoImpl() + { + } + + public SocketFactoryContactInfoImpl( + ORB orb, + ContactInfoList contactInfoList, + IOR effectiveTargetIOR, + short addressingDisposition, + SocketInfo cookie) + { + super(orb, contactInfoList); + this.effectiveTargetIOR = effectiveTargetIOR; + this.addressingDisposition = addressingDisposition; + + socketInfo = + orb.getORBData().getLegacySocketFactory() + .getEndPointInfo(orb, effectiveTargetIOR, cookie); + + socketType = socketInfo.getType(); + hostname = socketInfo.getHost(); + port = socketInfo.getPort(); + } + + @Override + public Connection createConnection() + { + Connection connection = + new SocketFactoryConnectionImpl( + orb, this, + orb.getORBData().connectionSocketUseSelectThreadToWait(), + orb.getORBData().connectionSocketUseWorkerThreadForEvent()); + return connection; + } + + //////////////////////////////////////////////////// + // + // java.lang.Object + // + + @Override + public String toString() + { + return + "SocketFactoryContactInfoImpl[" + + socketType + " " + + hostname + " " + + port + + "]"; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoListImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoListImpl.java new file mode 100644 index 000000000..3bc980db4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoListImpl.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import java.util.Iterator; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.impl.transport.ContactInfoListImpl; +import com.sun.corba.ee.impl.transport.ContactInfoListIteratorImpl; + +/** + * @author Harold Carr + */ +public class SocketFactoryContactInfoListImpl + extends + ContactInfoListImpl +{ + // XREVISIT - is this used? + public SocketFactoryContactInfoListImpl(ORB orb) + { + super(orb); + } + + public SocketFactoryContactInfoListImpl(ORB orb, IOR targetIOR) + { + super(orb, targetIOR); + } + + public Iterator iterator() + { + return new SocketFactoryContactInfoListIteratorImpl(orb, this); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoListIteratorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoListIteratorImpl.java new file mode 100644 index 000000000..a9a96b900 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/SocketFactoryContactInfoListIteratorImpl.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; + +import com.sun.corba.ee.spi.legacy.connection.GetEndPointInfoAgainException; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.transport.ContactInfoListIteratorImpl; +import com.sun.corba.ee.impl.transport.SharedCDRContactInfoImpl; +import com.sun.corba.ee.spi.trace.IsLocal; + +@IsLocal +public class SocketFactoryContactInfoListIteratorImpl + extends ContactInfoListIteratorImpl +{ + private SocketInfo socketInfoCookie; + + public SocketFactoryContactInfoListIteratorImpl( + ORB orb, + ContactInfoList corbaContactInfoList) + { + super(orb, corbaContactInfoList, null, null, false); + } + + //////////////////////////////////////////////////// + // + // java.util.Iterator + // + + @Override + @IsLocal + public boolean hasNext() + { + return true; + } + + @Override + @IsLocal + public ContactInfo next() + { + if (contactInfoList.getEffectiveTargetIOR().getProfile().isLocal()){ + return new SharedCDRContactInfoImpl( + orb, contactInfoList, + contactInfoList.getEffectiveTargetIOR(), + orb.getORBData().getGIOPAddressDisposition()); + } else { + // REVISIT: + // on comm_failure maybe need to give IOR instead of located. + return new SocketFactoryContactInfoImpl( + orb, contactInfoList, + contactInfoList.getEffectiveTargetIOR(), + orb.getORBData().getGIOPAddressDisposition(), + socketInfoCookie); + } + } + + @Override + public boolean reportException(ContactInfo contactInfo, + RuntimeException ex) + { + this.failureException = ex; + if (ex instanceof org.omg.CORBA.COMM_FAILURE) { + + SystemException se = (SystemException) ex; + + if (se.minor == ORBUtilSystemException.CONNECTION_REBIND) + { + return true; + } else { + if (ex.getCause() instanceof GetEndPointInfoAgainException) { + socketInfoCookie = + ((GetEndPointInfoAgainException) ex.getCause()) + .getEndPointInfo(); + return true; + } + + if (se.completed == CompletionStatus.COMPLETED_NO) { + if (contactInfoList.getEffectiveTargetIOR() != + contactInfoList.getTargetIOR()) + { + // retry from root ior + contactInfoList.setEffectiveTargetIOR( + contactInfoList.getTargetIOR()); + return true; + } + } + } + } + return false; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/USLPort.java b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/USLPort.java new file mode 100644 index 000000000..d755cbb47 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/legacy/connection/USLPort.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.legacy.connection; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; + +@ManagedData +@Description( "An address of a transport endpoint that the ORB " + + "uses for listening to incoming requests" ) +public class USLPort +{ + private String type; + private int port; + + public USLPort (String type, int port) + { + this.type = type; + this.port = port; + } + + @ManagedAttribute + @Description( "The type of the port (e.g. plain text vs. SSL)" ) + public String getType () { return type; } + + @ManagedAttribute + @Description( "The TCP port number" ) + public int getPort () { return port; } + public String toString () { return type + ":" + port; } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ByteArrayWrapper.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ByteArrayWrapper.java new file mode 100644 index 000000000..0bf50887e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ByteArrayWrapper.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.util.Arrays; + +public class ByteArrayWrapper { + + private byte[] objKey; + + public ByteArrayWrapper(byte[] objKey) { + this.objKey = objKey; + } + + public byte[] getObjKey() { + return objKey; + } + + public boolean equals( Object obj ) { + if (obj == null) + return false ; + + if (obj instanceof ByteArrayWrapper) { + return Arrays.equals(objKey, ((ByteArrayWrapper)obj).getObjKey()); + } else { + return false; + } + } + + public int hashCode() { + return Arrays.hashCode(objKey); + + } + + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/CacheTable.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/CacheTable.java new file mode 100644 index 000000000..4d44789b1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/CacheTable.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import com.sun.corba.ee.spi.trace.Cdr; + +/** This is a hash table implementation that simultaneously maps key to value + * and value to key. It is used for marshalling and unmarshalling value types, + * where it is necessary to track the correspondence between object instances + * and their offsets in a stream. It is also used for tracking indirections for + * Strings that represent codebases and repositoryids. + * Since the offset is always non-negative, + * only non-negative values should be stored here (and storing -1 will cause + * failures). Also note that the same key (Object) may be stored with multiple + * values (int offsets) due to the way readResolve works (see also GlassFish issue 1605). + * + * @since 1.1 + * + * @author Ken Cavanaugh + */ +@Cdr +public class CacheTable { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private class Entry { + private K key; + private int val; + private Entry next; // this chains the collision list of table "map" + private Entry rnext; // this chains the collision list of table "rmap" + public Entry(K k, int v) { + key = k; + val = v; + next = null; + rnext = null; + } + } + + private boolean noReverseMap; + private String cacheType ; + + // size must be power of 2 + private static final int INITIAL_SIZE = 64 ; + private static final int MAX_SIZE = 1 << 30; + private static final int INITIAL_THRESHHOLD = 48 ; + private int size; + private int threshhold ; + private int entryCount; + private Entry[] map; + private Entry[] rmap; + + private ORB orb; + + public CacheTable(String cacheType, ORB orb, boolean u) { + this.orb = orb; + this.cacheType = cacheType ; + noReverseMap = u; + size = INITIAL_SIZE; + threshhold = INITIAL_THRESHHOLD ; + entryCount = 0; + initTables(); + } + + private void initTables() { + map = new Entry[size]; + if (noReverseMap) { + rmap = null; + } else { + rmap = new Entry[size]; + } + } + + private void grow() { + if (size == MAX_SIZE) { + return; + } + + Entry[] oldMap = map; + int oldSize = size; + size <<= 1; + threshhold <<= 1 ; + + initTables(); + // now rehash the entries into the new table + for (int i = 0; i < oldSize; i++) { + for (Entry e = oldMap[i]; e != null; e = e.next) { + put_table(e.key, e.val); + } + } + } + + private int hashModTableSize(int h) { + // This is taken from the hash method in the JDK 6 HashMap. + // This is used for both the + // key and the value side of the mapping. It's not clear + // how useful this is in this application, as the low-order + // bits change a lot for both sides. + h ^= (h >>> 20) ^ (h >>> 12) ; + return (h ^ (h >>> 7) ^ (h >>> 4)) & (size - 1) ; + } + + private int hash(K key) { + return hashModTableSize(System.identityHashCode(key)); + } + + private int hash(int val) { + return hashModTableSize(val); + } + + /** Store the (key,val) pair in the hash table, unless + * (key,val) is already present. Returns true if a new (key,val) + * pair was added, else false. val must be non-negative, but + * this is not checked. + */ + public final void put(K key, int val) { + if (put_table(key, val)) { + entryCount++; + if (entryCount > threshhold) { + grow(); + } + } + } + + @Cdr + private boolean put_table(K key, int val) { + int index = hash(key); + + for (Entry e = map[index]; e != null; e = e.next) { + if (e.key == key) { + if (e.val != val) { + // duplicateIndirectionOffset error here is not an error: + // A serializable/externalizable class that defines + // a readResolve method that creates a canonical representation + // of a value can legally have the same key occuring at + // multiple values. This is GlassFish issue 1605. + // Note: we store this anyway, so that getVal can find the key. + wrapper.duplicateIndirectionOffset(); + } else { + // if we get here we are trying to put in the same key/val pair + // this is a no-op, so we just return + return false; + } + } + } + + Entry newEntry = new Entry(key, val); + newEntry.next = map[index]; + map[index] = newEntry; + if (!noReverseMap) { + int rindex = hash(val); + newEntry.rnext = rmap[rindex]; + rmap[rindex] = newEntry; + } + + return true; + } + + public final boolean containsKey(K key) { + return (getVal(key) != -1); + } + + /** Returns some int val where (key,val) is in this CacheTable. + */ + public final int getVal(K key) { + int index = hash(key); + for (Entry e = map[index]; e != null; e = e.next) { + if (e.key == key) { + return e.val; + } + } + + return -1; + } + + public final boolean containsVal(int val) { + return (getKey(val) != null); + } + + /** Return the key where (key,val) is present in the map. + */ + public final K getKey(int val) { + if (noReverseMap) { + throw wrapper.getKeyInvalidInCacheTable(); + } + + int index = hash(val); + for (Entry e = rmap[index]; e != null; e = e.rnext) { + if (e.val == val) { + return e.key; + } + } + + return null; + } + + public void done() { + map = null; + rmap = null; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ClassInfoCache.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ClassInfoCache.java new file mode 100644 index 000000000..81a11a5c1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ClassInfoCache.java @@ -0,0 +1,277 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.lang.reflect.Proxy ; + +import java.io.Serializable ; +import java.io.Externalizable ; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +import java.util.Map ; +import java.util.WeakHashMap ; + +import org.omg.CORBA.UserException ; + +import org.omg.CORBA.portable.ObjectImpl ; +import org.omg.CORBA.portable.Streamable ; +import org.omg.CORBA.portable.StreamableValue ; +import org.omg.CORBA.portable.CustomValue ; +import org.omg.CORBA.portable.ValueBase ; +import org.omg.CORBA.portable.IDLEntity ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** This class caches information about classes that is somewhat expensive + * to obtain, notably the results of isInterface(), isArray(), and isAssignableFrom. + * A user simply calls ClassInfoCache.get( Class ) to get the information about + * a class. + *

    + * All of the isA methods on ClassInfo need to be passed the same Class that was + * used in the get call! This is an awkward interface, but the alternative is + * to store the class in the ClassInfo, which would create a strong reference from + * the value to the key, making the WeakHashMap useless. It also appears to be + * difficult to use a weak or soft reference here, because I can't handle the + * case of an empty reference to the class inside the ClassInfo object. + * If ClassInfoCache supported the methods directly, we could work around this, + * but then we would in some case be doing multiple lookups for a class to get + * class information, which would slow things down significantly (the get call + * is a significant cost in the benchmarks). + *

    + * XXX There is a better solution: add MORE information to the cache. In + * particular, use a ClassAnalyzer to construct the linearized inheritance + * chain (order doesn't matter in this case, but we already have the implementation) + * and implement all of the isA methods by a simple check on whether the class + * is in the chain (or perhaps convert to Set). We can statically fill the cache + * with all of the basic objects (e.g. Streamable, Serializable, etc.) needs + * in a static initializer. + */ + +public class ClassInfoCache { + // Do NOT put a strong reference to the Class in ClassInfo: we don't want to + // pin ClassLoaders in memory! + public static class ClassInfo { + + public static class LazyWrapper { + Class isAClass ; + boolean initialized ; + boolean value ; + + public LazyWrapper( Class isAClass ) { + this.isAClass = isAClass ; + this.initialized = false ; + this.value = false ; + } + + synchronized boolean get( Class cls ) { + if (!initialized) { + initialized = true ; + value = isAClass.isAssignableFrom( cls ) ; + } + + return value ; + } + } + + private boolean isAValueBase ; + private boolean isAString ; + private boolean isAIDLEntity ; + + private LazyWrapper isARemote = new LazyWrapper( + Remote.class ) ; + private LazyWrapper isARemoteException = new LazyWrapper( + RemoteException.class ) ; + private LazyWrapper isAUserException = new LazyWrapper( + UserException.class ) ; + private LazyWrapper isAObjectImpl = new LazyWrapper( + ObjectImpl.class ) ; + private LazyWrapper isAORB = new LazyWrapper( + ORB.class ) ; + private LazyWrapper isAStreamable = new LazyWrapper( + Streamable.class ) ; + private LazyWrapper isAStreamableValue = new LazyWrapper( + StreamableValue.class ) ; + private LazyWrapper isACustomValue = new LazyWrapper( + CustomValue.class ) ; + private LazyWrapper isACORBAObject = new LazyWrapper( + org.omg.CORBA.Object.class ) ; + private LazyWrapper isASerializable = new LazyWrapper( + Serializable.class ) ; + private LazyWrapper isAExternalizable = new LazyWrapper( + Externalizable.class ) ; + private LazyWrapper isAClass = new LazyWrapper( + Class.class ) ; + + private String repositoryId = null ; + + private boolean isArray ; + private boolean isEnum ; + private boolean isInterface ; + private boolean isProxyClass ; + private ClassInfo superInfo ; + + ClassInfo( Class cls ) { + isArray = cls.isArray() ; + isEnum = isEnum(cls) ; + isInterface = cls.isInterface() ; + isProxyClass = Proxy.isProxyClass( cls ) ; + + isAValueBase = ValueBase.class.isAssignableFrom( cls ) ; + isAString = String.class.isAssignableFrom( cls ) ; + isAIDLEntity = IDLEntity.class.isAssignableFrom( cls ) ; + + Class superClass = cls.getSuperclass() ; + if (superClass != null) { + superInfo = ClassInfoCache.get( superClass ) ; + } + } + + private boolean isEnum(Class cls) { + // Issue 11681 + // This ugly method is needed because isEnum returns FALSE + // on enum.getClass().isEnum() if enum has an abstract method, + // which results in another subclass. So for us, a class is an + // enum if any superclass is java.lang.Enum. + Class current = cls ; + while (current != null) { + if (current.equals( Enum.class )) { + return true ; + } + current = current.getSuperclass() ; + } + + return false ; + } + + public synchronized String getRepositoryId() { + return repositoryId ; + } + + public synchronized void setRepositoryId( String repositoryId ) { + this.repositoryId = repositoryId ; + } + + public boolean isARemote( Class cls ) { + return isARemote.get(cls) ; + } + public boolean isARemoteException( Class cls ) { + return isARemoteException.get(cls) ; + } + public boolean isAUserException( Class cls ) { + return isAUserException.get(cls) ; + } + public boolean isAObjectImpl( Class cls ) { + return isAObjectImpl.get(cls) ; + } + public boolean isAORB( Class cls ) { + return isAORB.get(cls) ; + } + public boolean isAIDLEntity( Class cls ) { + return isAIDLEntity ; + } + public boolean isAStreamable( Class cls ) { + return isAStreamable.get(cls) ; + } + public boolean isAStreamableValue( Class cls ) { + return isAStreamableValue.get(cls) ; + } + public boolean isACustomValue( Class cls ) { + return isACustomValue.get(cls) ; + } + public boolean isAValueBase( Class cls ) { + return isAValueBase ; + } + public boolean isACORBAObject( Class cls ) { + return isACORBAObject.get(cls) ; + } + public boolean isASerializable( Class cls ) { + return isASerializable.get(cls) ; + } + public boolean isAExternalizable( Class cls ) { + return isAExternalizable.get(cls) ; + } + public boolean isAString( Class cls ) { + return isAString ; + } + public boolean isAClass( Class cls ) { + return isAClass.get(cls) ; + } + + public boolean isArray() { return isArray ; } + public boolean isEnum() { return isEnum ; } + public boolean isInterface() { return isInterface ; } + public boolean isProxyClass() { return isProxyClass ; } + public ClassInfo getSuper() { return superInfo ; } + } + + // This shows up as a locking hotspot in heavy marshaling tests. + // Ideally we need a WeakConcurrentMap, which is not available in + // the JDK (Google's MapMaker can easily construct such a class). + + /* Version using ConcurrentMap for testing ONLY + * (This would pin Classes (and thus ClassLoaders), leading to + * App server deployment memory leaks. + + private static ConcurrentMap classData = + new ConcurrentHashMap() ; + + public static ClassInfo get( Class cls ) { + ClassInfo result = classData.get( cls ) ; + if (result == null) { + final ClassInfo cinfo = new ClassInfo( cls ) ; + final ClassInfo putResult = classData.putIfAbsent( cls, cinfo ) ; + if (putResult == null) { + result = cinfo ; + } else { + result = putResult ; + } + } + + return result ; + } + */ + + private static Map classData = new WeakHashMap() ; + + public static synchronized ClassInfo get( Class cls ) { + ClassInfo result = classData.get( cls ) ; + if (result == null && cls != null) { + result = new ClassInfo( cls ) ; + classData.put( cls, result ) ; + } + + return result ; + } + + /** Find the class that is an enum in the superclass chain starting at cls. + * cinfo MUST be the ClassInfo for cls. + * @param cinfo ClassInfo for cls + * @param cls Class which may have java.lang.Enum in its superclass chain. + * @return A class for which isEnum() is true, or null if no such class + * exists in the superclass chain of cls. + */ + public static Class getEnumClass( ClassInfo cinfo, Class cls ) { + ClassInfo currInfo = cinfo ; + Class currClass = cls ; + while (currClass != null) { + if (currClass.isEnum()) { + break ; + } + + currClass = currClass.getSuperclass() ; + currInfo = currInfo.getSuper() ; + } + + return currClass ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/CorbaResourceUtil.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/CorbaResourceUtil.java new file mode 100644 index 000000000..3e3ba30c6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/CorbaResourceUtil.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.util.ResourceBundle; +import java.util.MissingResourceException; + +public class CorbaResourceUtil { + public static String getString(String key) { + if (!resourcesInitialized) { + initResources(); + } + + try { + return resources.getString(key); + } catch (MissingResourceException ignore) { + } + return null; + } + + public static String getText(String key) { + String message = getString(key); + if (message == null) { + message = "no text found: \"" + key + "\""; + } + return message; + } + + public static String getText(String key, Object... args ) + { + String format = getString(key); + + if (format == null) { + StringBuilder sb = new StringBuilder( + "no text found: key = \"" ) ; + sb.append( key ) ; + sb.append( "\", arguments = " ) ; + + for (int ctr=0; ctr> 4) & 0xF)]); + writer.write(hex[((b >> 0) & 0xF)]); + } + + public synchronized void write(byte[] b) throws IOException { + write(b, 0, b.length); + } + + public synchronized void write(byte[] b, int off, int len) + throws IOException + { + for(int i=0; i < len; i++) { + write(b[off + i]); + } + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LegacyHookGetFields.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LegacyHookGetFields.java new file mode 100644 index 000000000..001d00c61 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LegacyHookGetFields.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.io.*; +import java.util.Hashtable; + +class LegacyHookGetFields extends ObjectInputStream.GetField { + private Hashtable fields = null; + + LegacyHookGetFields(Hashtable fields){ + this.fields = fields; + } + + /** + * Get the ObjectStreamClass that describes the fields in the stream. + */ + public java.io.ObjectStreamClass getObjectStreamClass() { + return null; + } + + /** + * Return true if the named field is defaulted and has no value + * in this stream. + */ + public boolean defaulted(String name) + throws IOException, IllegalArgumentException { + return (!fields.containsKey(name)); + } + + /** + * Get the value of the named boolean field from the persistent field. + */ + public boolean get(String name, boolean defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Boolean)fields.get(name)).booleanValue(); + } + + /** + * Get the value of the named char field from the persistent fields. + */ + public char get(String name, char defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Character)fields.get(name)).charValue(); + + } + + /** + * Get the value of the named byte field from the persistent fields. + */ + public byte get(String name, byte defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Byte)fields.get(name)).byteValue(); + + } + + /** + * Get the value of the named short field from the persistent fields. + */ + public short get(String name, short defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Short)fields.get(name)).shortValue(); + + } + + /** + * Get the value of the named int field from the persistent fields. + */ + public int get(String name, int defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Integer)fields.get(name)).intValue(); + + } + + /** + * Get the value of the named long field from the persistent fields. + */ + public long get(String name, long defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Long)fields.get(name)).longValue(); + + } + + /** + * Get the value of the named float field from the persistent fields. + */ + public float get(String name, float defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Float)fields.get(name)).floatValue(); + + } + + /** + * Get the value of the named double field from the persistent field. + */ + public double get(String name, double defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return ((Double)fields.get(name)).doubleValue(); + + } + + /** + * Get the value of the named Object field from the persistent field. + */ + public Object get(String name, Object defvalue) + throws IOException, IllegalArgumentException { + if (defaulted(name)) + return defvalue; + else return fields.get(name); + + } + + public String toString(){ + return fields.toString(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LegacyHookPutFields.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LegacyHookPutFields.java new file mode 100644 index 000000000..5a7fa5442 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LegacyHookPutFields.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.io.IOException; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.Map; + +/** + * Since ObjectOutputStream.PutField methods specify no exceptions, + * we are not checking for null parameters on put methods. + */ +class LegacyHookPutFields extends ObjectOutputStream.PutField +{ + private Map fields = new HashMap(); + + /** + * Put the value of the named boolean field into the persistent field. + */ + public void put(String name, boolean value){ + fields.put(name, Boolean.valueOf(value)); + } + + /** + * Put the value of the named char field into the persistent fields. + */ + public void put(String name, char value){ + fields.put(name, Character.valueOf(value)); + } + + /** + * Put the value of the named byte field into the persistent fields. + */ + public void put(String name, byte value){ + fields.put(name, Byte.valueOf(value)); + } + + /** + * Put the value of the named short field into the persistent fields. + */ + public void put(String name, short value){ + fields.put(name, Short.valueOf(value)); + } + + /** + * Put the value of the named int field into the persistent fields. + */ + public void put(String name, int value){ + fields.put(name, Integer.valueOf(value)); + } + + /** + * Put the value of the named long field into the persistent fields. + */ + public void put(String name, long value){ + fields.put(name, Long.valueOf(value)); + } + + /** + * Put the value of the named float field into the persistent fields. + * + */ + public void put(String name, float value){ + fields.put(name, Float.valueOf(value)); + } + + /** + * Put the value of the named double field into the persistent field. + */ + public void put(String name, double value){ + fields.put(name, Double.valueOf(value)); + } + + /** + * Put the value of the named Object field into the persistent field. + */ + public void put(String name, Object value){ + fields.put(name, value); + } + + /** + * Write the data and fields to the specified ObjectOutput stream. + */ + public void write(ObjectOutput out) throws IOException { + out.writeObject(fields); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LogKeywords.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LogKeywords.java new file mode 100644 index 000000000..8523e91d7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/LogKeywords.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; +/** + * All the Keywords that will be used in Logging Messages for CORBA need to + * be defined here. The LogKeywords will be useful for searching log messages + * based on the standard keywords, it is also useful to work with LogAnalyzing + * tools. + * We will try to standardize these keywords in JSR 117 Logging + */ +public class LogKeywords { + + /** + ** Keywords for Lifecycle Loggers. + ** _REVISIT_ After it is clearly defined in JSR 117 + **/ + public final static String LIFECYCLE_CREATE = "<>"; + public final static String LIFECYCLE_INITIALIZE = "<>"; + public final static String LIFECYCLE_SHUTDOWN = "<>"; + public final static String LIFECYCLE_DESTROY = "<>"; + public final static String NAMING_RESOLVE = "<>"; + public final static String NAMING_LIST = "<>"; + public final static String NAMING_BIND = "<>"; + public final static String NAMING_UNBIND = "<>"; + public final static String NAMING_REBIND = "<>"; +} + + + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ORBUtility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ORBUtility.java new file mode 100644 index 000000000..5b92b202b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/ORBUtility.java @@ -0,0 +1,1003 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.security.AccessController; +import java.security.PermissionCollection; +import java.security.Policy; +import java.security.PrivilegedAction; +import java.security.ProtectionDomain; +import java.util.LinkedList; +import java.util.Hashtable; +import java.util.Enumeration; +import java.util.StringTokenizer; +import java.util.NoSuchElementException; + +import java.io.PrintStream ; +import java.io.IOException ; + +import java.nio.ByteBuffer ; + +import java.net.SocketAddress ; + +import java.nio.channels.SocketChannel ; + +import javax.rmi.CORBA.ValueHandler; +import javax.rmi.CORBA.ValueHandlerMultiFormat; + +import org.omg.CORBA.StructMember ; +import org.omg.CORBA.TypeCode ; +import org.omg.CORBA.Any ; +import org.omg.CORBA.TCKind ; +import org.omg.CORBA.SystemException ; +import org.omg.CORBA.CompletionStatus ; +import org.omg.CORBA.TypeCodePackage.BadKind ; +import org.omg.CORBA.portable.OutputStream ; +import org.omg.CORBA.portable.InputStream ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; +import com.sun.corba.ee.spi.protocol.ClientDelegate ; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.ContactInfoList ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.misc.ORBClassLoader; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.corba.CORBAObjectImpl ; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.logging.OMGSystemException ; +import com.sun.corba.ee.impl.ior.iiop.JavaSerializationComponent; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; +import com.sun.corba.ee.impl.io.ValueHandlerImpl; + +/** + * Handy class full of static functions that don't belong in util.Utility for pure ORB reasons. + */ +public final class ORBUtility { + /** Utility method for working around leak in SocketChannel.open( SocketAddress ) + * method. + */ + public static SocketChannel openSocketChannel( SocketAddress sa ) + throws IOException { + + SocketChannel sc = SocketChannel.open() ; + + try { + sc.connect( sa ) ; + return sc ; + } catch (RuntimeException exc ) { + try { + sc.close() ; + } catch (IOException ioe) { + // Ignore this: close exceptions are useless. + } + + throw exc ; + } catch (IOException exc ) { + try { + sc.close() ; + } catch (IOException ioe) { + // Ignore this: close exceptions are useless. + } + + throw exc ; + } + } + + private static final ThreadLocal> encVersionThreadLocal = + new ThreadLocal>() { + protected LinkedList initialValue() { + return new LinkedList(); + } + }; + + public static void pushEncVersionToThreadLocalState(byte value) { + LinkedList stack = encVersionThreadLocal.get(); + stack.addLast(value); + } + + public static void popEncVersionFromThreadLocalState() { + LinkedList stack = encVersionThreadLocal.get(); + stack.removeLast(); + } + + public static byte getEncodingVersion() { + byte encodingVersion = ORBConstants.CDR_ENC_VERSION; // default + LinkedList stack = encVersionThreadLocal.get(); + if (stack.size() > 0) { + Byte last = stack.getLast(); + // LinkedList allows a null object to be added to the list + if (last != null) { + encodingVersion = last.byteValue(); + } // if null, return default CDR_ENC_VERSION + } // if nothing on list, use default encoding + return encodingVersion; + } + + public static byte[] getByteBufferArray(ByteBuffer byteBuffer) { + + if (byteBuffer.hasArray()) { + byte[] buf = new byte[byteBuffer.limit()]; + System.arraycopy(byteBuffer.array(), byteBuffer.arrayOffset(), + buf, 0, buf.length); + // NOTE: Cannot simply do return byteBuffer.array() since byteBuffer + // could be a view buffer / sliced ByteBuffer. View buffers / + // sliced ByteBuffer will return the entired backed array. + // Not a byte array beginning at view buffer position 0. + return buf; + } + + byte[] buf = new byte[byteBuffer.limit()]; + int pos = byteBuffer.position(); + byteBuffer.position(0); + byteBuffer.get(buf); + byteBuffer.position(pos); + + return buf; + } + + /** + * @return the Java serialization encoding version. + */ + public static byte chooseEncodingVersion(ORB orb, IOR ior, + GIOPVersion gv) { + + // Is Java serialization enabled? + // Check the JavaSerializationComponent (tagged component) + // in the IIOPProfile. If present, the peer ORB's GIOP is capable + // of using Java serialization instead of CDR serialization. + // In such a case, use Java serialization, iff the java serialization + // versions match. + + if (orb.getORBData().isJavaSerializationEnabled() && + !(gv.lessThan(GIOPVersion.V1_2))) { + IIOPProfile prof = ior.getProfile(); + IIOPProfileTemplate profTemp = + (IIOPProfileTemplate) prof.getTaggedProfileTemplate(); + java.util.Iterator iter = profTemp.iteratorById( + ORBConstants.TAG_JAVA_SERIALIZATION_ID); + if (iter.hasNext()) { + JavaSerializationComponent jc = + (JavaSerializationComponent) iter.next(); + byte jcVersion = jc.javaSerializationVersion(); + if (jcVersion >= ORBConstants.JAVA_ENC_VERSION) { + return ORBConstants.JAVA_ENC_VERSION; + } else if (jcVersion > ORBConstants.CDR_ENC_VERSION) { + return jcVersion; + } else { + // ERROR: encodingVersion is <= 0 (CDR_ENC_VERSION). + wrapper.invalidJavaSerializationVersion(jc); + } + } + } + return ORBConstants.CDR_ENC_VERSION; // default + } + + private ORBUtility() {} + + private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static OMGSystemException omgWrapper = + OMGSystemException.self ; + + private static StructMember[] members = null; + + private synchronized static StructMember[] systemExceptionMembers (ORB orb) { + if (members == null) { + members = new StructMember[3]; + members[0] = new StructMember("id", orb.create_string_tc(0), null); + members[1] = new StructMember("minor", orb.get_primitive_tc(TCKind.tk_long), null); + members[2] = new StructMember("completed", orb.get_primitive_tc(TCKind.tk_long), null); + } + return members; + } + + private static TypeCode getSystemExceptionTypeCode(ORB orb, String repID, String name) { + synchronized (TypeCode.class) { + return orb.create_exception_tc(repID, name, systemExceptionMembers(orb)); + } + } + + private static boolean isSystemExceptionTypeCode(TypeCode type, ORB orb) { + StructMember[] systemExceptionMembers = systemExceptionMembers(orb); + try { + return (type.kind().value() == TCKind._tk_except && + type.member_count() == 3 && + type.member_type(0).equal(systemExceptionMembers[0].type) && + type.member_type(1).equal(systemExceptionMembers[1].type) && + type.member_type(2).equal(systemExceptionMembers[2].type)); + } catch (BadKind ex) { + return false; + } catch (org.omg.CORBA.TypeCodePackage.Bounds ex) { + return false; + } + } + + /** + * Static method for writing a CORBA standard exception to an Any. + * @param any The Any to write the SystemException into. + */ + public static void insertSystemException(SystemException ex, Any any) { + OutputStream out = any.create_output_stream(); + ORB orb = (ORB)(out.orb()); + String name = ex.getClass().getName(); + String repID = ORBUtility.repositoryIdOf(name); + out.write_string(repID); + out.write_long(ex.minor); + out.write_long(ex.completed.value()); + any.read_value(out.create_input_stream(), + getSystemExceptionTypeCode(orb, repID, name)); + } + + public static SystemException extractSystemException(Any any) { + InputStream in = any.create_input_stream(); + ORB orb = (ORB)(in.orb()); + if ( ! isSystemExceptionTypeCode(any.type(), orb)) { + throw wrapper.unknownDsiSysex(); + } + return ORBUtility.readSystemException(in); + } + + private static ValueHandler vhandler = + Util.getInstance().createValueHandler(); + + /** + * Gets the ValueHandler from Util.createValueHandler. + */ + public static ValueHandler createValueHandler() { + return vhandler; + } + + /** + * Creates the correct ValueHandler. The parameter + * is ignored + */ + public static ValueHandler createValueHandler(ORB orb) { + return vhandler; + } + + /** + * Returns true if it was accurately determined that the remote ORB is + * a foreign (non-JavaSoft) ORB. Note: If passed the ORBSingleton, this + * will return false. + */ + public static boolean isForeignORB(ORB orb) + { + if (orb == null) { + return false; + } + + try { + return orb.getORBVersion().equals(ORBVersionFactory.getFOREIGN()); + } catch (SecurityException se) { + return false; + } + } + + /** Unmarshal a byte array to an integer. + Assume the bytes are in BIGENDIAN order. + i.e. array[offset] is the most-significant-byte + and array[offset+3] is the least-significant-byte. + @param array The array of bytes. + @param offset The offset from which to start unmarshalling. + */ + public static int bytesToInt(byte[] array, int offset) + { + int b1, b2, b3, b4; + + b1 = (array[offset++] << 24) & 0xFF000000; + b2 = (array[offset++] << 16) & 0x00FF0000; + b3 = (array[offset++] << 8) & 0x0000FF00; + b4 = (array[offset++] << 0) & 0x000000FF; + + return (b1 | b2 | b3 | b4); + } + + /** Marshal an integer to a byte array. + The bytes are in BIGENDIAN order. + i.e. array[offset] is the most-significant-byte + and array[offset+3] is the least-significant-byte. + @param array The array of bytes. + @param offset The offset from which to start marshalling. + */ + public static void intToBytes(int value, byte[] array, int offset) + { + array[offset++] = (byte)((value >>> 24) & 0xFF); + array[offset++] = (byte)((value >>> 16) & 0xFF); + array[offset++] = (byte)((value >>> 8) & 0xFF); + array[offset++] = (byte)((value >>> 0) & 0xFF); + } + + /** Converts an Ascii Character into Hexadecimal digit + */ + public static int hexOf( char x ) + { + int val; + + val = x - '0'; + if (val >=0 && val <= 9) { + return val; + } + + val = (x - 'a') + 10; + if (val >= 10 && val <= 15) { + return val; + } + + val = (x - 'A') + 10; + if (val >= 10 && val <= 15) { + return val; + } + + throw wrapper.badHexDigit() ; + } + + // method moved from util.Utility + + /** + * Static method for writing a CORBA standard exception to a stream. + * @param strm The OutputStream to use for marshaling. + */ + public static void writeSystemException(SystemException ex, OutputStream strm) + { + String s; + + s = repositoryIdOf(ex.getClass().getName()); + strm.write_string(s); + strm.write_long(ex.minor); + strm.write_long(ex.completed.value()); + } + + /** + * Static method for reading a CORBA standard exception from a stream. + * @param strm The InputStream to use for unmarshaling. + */ + public static SystemException readSystemException(InputStream strm) + { + try { + String name = classNameOf(strm.read_string()); + SystemException ex + = (SystemException)ORBClassLoader.loadClass(name).newInstance(); + ex.minor = strm.read_long(); + ex.completed = CompletionStatus.from_int(strm.read_long()); + return ex; + } catch ( Exception ex ) { + throw wrapper.unknownSysex( ex ); + } + } + + /** + * Get the class name corresponding to a particular repository Id. + * This is used by the system to unmarshal (instantiate) the + * appropriate exception class for an marshaled as the value of + * its repository Id. + * @param repositoryId The repository Id for which we want a class name. + */ + public static String classNameOf(String repositoryId) + { + String className=null; + + className = (String) exceptionClassNames.get(repositoryId); + if (className == null) { + className = "org.omg.CORBA.UNKNOWN"; + } + + return className; + } + + /** + * Return true if this repositoryId is a SystemException. + * @param repositoryId The repository Id to check. + */ + public static boolean isSystemException(String repositoryId) + { + String className=null; + + className = (String) exceptionClassNames.get(repositoryId); + return className != null ; + } + + /** + * Get the repository id corresponding to a particular class. + * This is used by the system to write the + * appropriate repository id for a system exception. + * @param name The class name of the system exception. + */ + public static String repositoryIdOf(String name) + { + String id; + + id = (String) exceptionRepositoryIds.get(name); + if (id == null) { + id = "IDL:omg.org/CORBA/UNKNOWN:1.0"; + } + + return id; + } + + private static final Hashtable exceptionClassNames = new Hashtable(); + private static final Hashtable exceptionRepositoryIds = new Hashtable(); + + static { + + // + // construct repositoryId -> className hashtable + // + exceptionClassNames.put("IDL:omg.org/CORBA/BAD_CONTEXT:1.0", + "org.omg.CORBA.BAD_CONTEXT"); + exceptionClassNames.put("IDL:omg.org/CORBA/BAD_INV_ORDER:1.0", + "org.omg.CORBA.BAD_INV_ORDER"); + exceptionClassNames.put("IDL:omg.org/CORBA/BAD_OPERATION:1.0", + "org.omg.CORBA.BAD_OPERATION"); + exceptionClassNames.put("IDL:omg.org/CORBA/BAD_PARAM:1.0", + "org.omg.CORBA.BAD_PARAM"); + exceptionClassNames.put("IDL:omg.org/CORBA/BAD_TYPECODE:1.0", + "org.omg.CORBA.BAD_TYPECODE"); + exceptionClassNames.put("IDL:omg.org/CORBA/COMM_FAILURE:1.0", + "org.omg.CORBA.COMM_FAILURE"); + exceptionClassNames.put("IDL:omg.org/CORBA/DATA_CONVERSION:1.0", + "org.omg.CORBA.DATA_CONVERSION"); + exceptionClassNames.put("IDL:omg.org/CORBA/IMP_LIMIT:1.0", + "org.omg.CORBA.IMP_LIMIT"); + exceptionClassNames.put("IDL:omg.org/CORBA/INTF_REPOS:1.0", + "org.omg.CORBA.INTF_REPOS"); + exceptionClassNames.put("IDL:omg.org/CORBA/INTERNAL:1.0", + "org.omg.CORBA.INTERNAL"); + exceptionClassNames.put("IDL:omg.org/CORBA/INV_FLAG:1.0", + "org.omg.CORBA.INV_FLAG"); + exceptionClassNames.put("IDL:omg.org/CORBA/INV_IDENT:1.0", + "org.omg.CORBA.INV_IDENT"); + exceptionClassNames.put("IDL:omg.org/CORBA/INV_OBJREF:1.0", + "org.omg.CORBA.INV_OBJREF"); + exceptionClassNames.put("IDL:omg.org/CORBA/MARSHAL:1.0", + "org.omg.CORBA.MARSHAL"); + exceptionClassNames.put("IDL:omg.org/CORBA/NO_MEMORY:1.0", + "org.omg.CORBA.NO_MEMORY"); + exceptionClassNames.put("IDL:omg.org/CORBA/FREE_MEM:1.0", + "org.omg.CORBA.FREE_MEM"); + exceptionClassNames.put("IDL:omg.org/CORBA/NO_IMPLEMENT:1.0", + "org.omg.CORBA.NO_IMPLEMENT"); + exceptionClassNames.put("IDL:omg.org/CORBA/NO_PERMISSION:1.0", + "org.omg.CORBA.NO_PERMISSION"); + exceptionClassNames.put("IDL:omg.org/CORBA/NO_RESOURCES:1.0", + "org.omg.CORBA.NO_RESOURCES"); + exceptionClassNames.put("IDL:omg.org/CORBA/NO_RESPONSE:1.0", + "org.omg.CORBA.NO_RESPONSE"); + exceptionClassNames.put("IDL:omg.org/CORBA/OBJ_ADAPTER:1.0", + "org.omg.CORBA.OBJ_ADAPTER"); + exceptionClassNames.put("IDL:omg.org/CORBA/INITIALIZE:1.0", + "org.omg.CORBA.INITIALIZE"); + exceptionClassNames.put("IDL:omg.org/CORBA/PERSIST_STORE:1.0", + "org.omg.CORBA.PERSIST_STORE"); + exceptionClassNames.put("IDL:omg.org/CORBA/TRANSIENT:1.0", + "org.omg.CORBA.TRANSIENT"); + exceptionClassNames.put("IDL:omg.org/CORBA/UNKNOWN:1.0", + "org.omg.CORBA.UNKNOWN"); + exceptionClassNames.put("IDL:omg.org/CORBA/OBJECT_NOT_EXIST:1.0", + "org.omg.CORBA.OBJECT_NOT_EXIST"); + + // SystemExceptions from OMG Transactions Service Spec + exceptionClassNames.put("IDL:omg.org/CORBA/INVALID_TRANSACTION:1.0", + "org.omg.CORBA.INVALID_TRANSACTION"); + exceptionClassNames.put("IDL:omg.org/CORBA/TRANSACTION_REQUIRED:1.0", + "org.omg.CORBA.TRANSACTION_REQUIRED"); + exceptionClassNames.put("IDL:omg.org/CORBA/TRANSACTION_ROLLEDBACK:1.0", + "org.omg.CORBA.TRANSACTION_ROLLEDBACK"); + + // from portability RTF 98-07-01.txt + exceptionClassNames.put("IDL:omg.org/CORBA/INV_POLICY:1.0", + "org.omg.CORBA.INV_POLICY"); + + // from orbrev/00-09-01 (CORBA 2.4 Draft Specification) + exceptionClassNames. + put("IDL:omg.org/CORBA/TRANSACTION_UNAVAILABLE:1.0", + "org.omg.CORBA.TRANSACTION_UNAVAILABLE"); + exceptionClassNames.put("IDL:omg.org/CORBA/TRANSACTION_MODE:1.0", + "org.omg.CORBA.TRANSACTION_MODE"); + + // Exception types introduced between CORBA 2.4 and 3.0 + exceptionClassNames.put("IDL:omg.org/CORBA/CODESET_INCOMPATIBLE:1.0", + "org.omg.CORBA.CODESET_INCOMPATIBLE"); + exceptionClassNames.put("IDL:omg.org/CORBA/REBIND:1.0", + "org.omg.CORBA.REBIND"); + exceptionClassNames.put("IDL:omg.org/CORBA/TIMEOUT:1.0", + "org.omg.CORBA.TIMEOUT"); + exceptionClassNames.put("IDL:omg.org/CORBA/BAD_QOS:1.0", + "org.omg.CORBA.BAD_QOS"); + + // Exception types introduced in CORBA 3.0 + exceptionClassNames.put("IDL:omg.org/CORBA/INVALID_ACTIVITY:1.0", + "org.omg.CORBA.INVALID_ACTIVITY"); + exceptionClassNames.put("IDL:omg.org/CORBA/ACTIVITY_COMPLETED:1.0", + "org.omg.CORBA.ACTIVITY_COMPLETED"); + exceptionClassNames.put("IDL:omg.org/CORBA/ACTIVITY_REQUIRED:1.0", + "org.omg.CORBA.ACTIVITY_REQUIRED"); + + // + // construct className -> repositoryId hashtable + // + Enumeration keys = exceptionClassNames.keys(); + java.lang.Object s; + String rId; + String cName; + + try{ + while (keys.hasMoreElements()) { + s = keys.nextElement(); + rId = (String) s; + cName = (String) exceptionClassNames.get(rId); + exceptionRepositoryIds.put (cName, rId); + } + } catch (NoSuchElementException e) { } + } + + /** Parse a version string such as "1.1.6" or "jdk1.2fcs" into + a version array of integers {1, 1, 6} or {1, 2}. + A string of "n." or "n..m" is equivalent to "n.0" or "n.0.m" respectively. + */ + public static int[] parseVersion(String version) { + if (version == null) { + return new int[0]; + } + char[] s = version.toCharArray(); + //find the maximum span of the string "n.n.n..." where n is an integer + int start = 0; + for (; start < s.length && (s[start] < '0' || s[start] > '9'); ++start) { + if (start == s.length) { + return new int[0]; + } + } + int end = start + 1; + int size = 1; + for (; end < s.length; ++end) { + if (s[end] == '.') { + ++size; + } else if (s[end] < '0' || s[end] > '9') { + break; + } + } + int[] val = new int[size]; + for (int i = 0; i < size; ++i) { + int dot = version.indexOf('.', start); + if (dot == -1 || dot > end) { + dot = end; + } + if (start >= dot) { + val[i] = 0; + } //convert equivalent to "n.0" or "n.0.m" + else { + val[i] = + Integer.parseInt(version.substring(start, dot)); + } + start = dot + 1; + } + return val; + } + + /** Compare two version arrays. + Return 1, 0 or -1 if v1 is greater than, equal to, or less than v2. + */ + public static int compareVersion(int[] v1, int[] v2) { + if (v1 == null) { + v1 = new int[0]; + } + if (v2 == null) { + v2 = new int[0]; + } + for (int i = 0; i < v1.length; ++i) { + if (i >= v2.length || v1[i] > v2[i]) { + return 1; + } + if (v1[i] < v2[i]) { + return -1; + } + } + return v1.length == v2.length ? 0 : -1; + } + + /** Compare two version strings. + Return 1, 0 or -1 if v1 is greater than, equal to, or less than v2. + */ + public static synchronized int compareVersion(String v1, String v2) { + return compareVersion(parseVersion(v1), parseVersion(v2)); + } + + private static String compressClassName( String name ) + { + // Note that this must end in . in order to be renamed correctly. + String prefix = "com.sun.corba.ee." ; + if (name.startsWith( prefix ) ) { + return "(ORB)." + name.substring( prefix.length() ) ; + } else { + return name; + } + } + + // Return a compressed representation of the thread name. This is particularly + // useful on the server side, where there are many SelectReaderThreads, and + // we need a short unambiguous name for such threads. + public static String getThreadName( Thread thr ) + { + if (thr == null) { + return "null"; + } + + // This depends on the formatting in SelectReaderThread and CorbaConnectionImpl. + // Pattern for SelectReaderThreads: + // SelectReaderThread CorbaConnectionImpl[ ] + // Any other pattern in the Thread's name is just returned. + String name = thr.getName() ; + StringTokenizer st = new StringTokenizer( name ) ; + int numTokens = st.countTokens() ; + if (numTokens != 5) { + return name; + } + + String[] tokens = new String[numTokens] ; + for (int ctr=0; ctr= 0 ? + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")" : + (ste.getFileName() != null ? "("+ste.getFileName()+")" : "(Unknown Source)"))); + } + + private static void printStackTrace( StackTraceElement[] trace ) + { + System.out.println( " Stack Trace:" ) ; + // print the stack trace, ommitting the zeroth element, which is + // always this method. + for ( int ctr = 1; ctr < trace.length; ctr++ ) { + System.out.print( " >" ) ; + System.out.println( formatStackTraceElement( trace[ctr] ) ) ; + } + } + + // + // Implements all dprint calls in this package. + // + public static synchronized void dprint(java.lang.Object obj, String msg) { + System.out.println( + compressClassName( obj.getClass().getName() ) + "(" + + getThreadName( Thread.currentThread() ) + "): " + msg); + } + + public static synchronized void dprint(String className, String msg) { + System.out.println( + compressClassName( className ) + "(" + + getThreadName( Thread.currentThread() ) + "): " + msg); + } + + public synchronized void dprint(String msg) { + ORBUtility.dprint(this, msg); + } + + public static synchronized void dprintTrace(Object obj, String msg) { + ORBUtility.dprint(obj, msg); + + Throwable thr = new Throwable() ; + printStackTrace( thr.getStackTrace() ) ; + } + + public static synchronized void dprint(java.lang.Object caller, + String msg, Throwable t) + { + System.out.println( + compressClassName( caller.getClass().getName() ) + + '(' + Thread.currentThread() + "): " + msg); + + if (t != null) { + printStackTrace(t.getStackTrace()); + } + } + + public static String[] concatenateStringArrays( String[] arr1, String[] arr2 ) + { + String[] result = new String[ + arr1.length + arr2.length ] ; + System.arraycopy(arr1, 0, result, 0, arr1.length); + System.arraycopy(arr2, 0, result, arr1.length, arr2.length); + + return result ; + } + + /** + * Throws the CORBA equivalent of a java.io.NotSerializableException + * + * Duplicated from util/Utility for Pure ORB reasons. There are two + * reasons for this: + * + * 1) We can't introduce dependencies on the util version from outside + * of the io/util packages since it will not exist in the pure ORB + * build running on JDK 1.3.x. + * + * 2) We need to pick up the correct minor code from OMGSystemException. + */ + public static void throwNotSerializableForCorba(String className) { + throw omgWrapper.notSerializable( className ) ; + } + + /** + * Returns the maximum stream format version supported by our + * ValueHandler. + */ + public static byte getMaxStreamFormatVersion() { + ValueHandler vh = Util.getInstance().createValueHandler(); + + if (!(vh instanceof javax.rmi.CORBA.ValueHandlerMultiFormat)) { + return ORBConstants.STREAM_FORMAT_VERSION_1; + } else { + return ((ValueHandlerMultiFormat) vh).getMaximumStreamFormatVersion(); + } + } + + public static ClientDelegate makeClientDelegate( IOR ior ) + { + ORB orb = ior.getORB() ; + ContactInfoList ccil = orb.getCorbaContactInfoListFactory().create( ior ) ; + ClientDelegate del = orb.getClientDelegateFactory().create(ccil); + return del ; + } + + /** This method is used to create untyped object references. + */ + public static org.omg.CORBA.Object makeObjectReference( IOR ior ) + { + ClientDelegate del = makeClientDelegate( ior ) ; + org.omg.CORBA.Object objectImpl = new CORBAObjectImpl() ; + StubAdapter.setDelegate( objectImpl, del ) ; + return objectImpl ; + } + + public static void setDaemon(Thread thread) + { + // Catch exceptions since setDaemon can cause a + // security exception to be thrown under netscape + // in the Applet mode + final Thread finalThread = thread; + try { + AccessController.doPrivileged(new PrivilegedAction() { + public java.lang.Object run() { + finalThread.setDaemon(true); + return null; + } + }); + } catch (Exception e) { + // REVISIT: Object to get static method. Ignore it. + dprint(new Object(), "setDaemon: Exception: " + e); + } + } + + public static String operationNameAndRequestId(MessageMediator m) + { + return "op/" + m.getOperationName() + " id/" + m.getRequestId(); + } + + public static boolean isPrintable(char c) + { + if (Character.isJavaIdentifierStart(c)) { + // Letters and $ _ + return true; + } + if (Character.isDigit(c)) { + return true; + } + switch (Character.getType(c)) { + case Character.MODIFIER_SYMBOL : return true; // ` ^ + case Character.DASH_PUNCTUATION : return true; // - + case Character.MATH_SYMBOL : return true; // = ~ + | < > + case Character.OTHER_PUNCTUATION : return true; // !@#%&*;':",./? + case Character.START_PUNCTUATION : return true; // ( [ { + case Character.END_PUNCTUATION : return true; // ) ] } + } + return false; + } + + /** Given some hex data, extract it and put it into a byte buffer. + * The data must follow the following structure: + *

      + *
    1. All characters in a line after a "#" are ignored. + *
    2. All non-whitespace characters before a "#" are treated as hex data. + *
    3. All whitespace is ignored. + *
    4. Only whitespace and 0-9a-fA-F may occur before a "#" in any line. + *
    5. Each data line must contain an even number of non-whitespace + * characters. + *
    + */ + public static byte[] getBuffer( String[] data ) { + // Estimate size of result + int numChar = 0 ; + for (String str : data) { + numChar += str.length(); + } + // Maximum result size is 1/2 the number of characters. + // Usually smaller due to comments and white space. + int maxSize = numChar/2 ; + + byte[] result = new byte[maxSize] ; + int index = 0 ; + int value = 0; + boolean startByte = true ; + + for (String str : data ) { + for (int ctr = 0; ctr> ....) + // (java.io.FilePermission /export0/sunwappserv/lib/- ...) + // ... other permissions ... + // Domain ProtectionDomain (file:/export0/sunwappserv/lib-) + // java.security.Permissions@141fedb ( + // (java.io.FilePermission <> ...) + // (java.io.FilePermission /var/tmp//- ...) + + String result = + (String)AccessController.doPrivileged(new PrivilegedAction() { + public java.lang.Object run() { + StringBuffer sb = new StringBuffer(500); + ProtectionDomain pd = cl.getProtectionDomain(); + Policy policy = Policy.getPolicy(); + PermissionCollection pc = policy.getPermissions(pd); + sb.append("\nPermissionCollection "); + sb.append(pc.toString()); + // Don't need to add 'Protection Domain' string, it's + // in ProtectionDomain.toString() already. + sb.append(pd.toString()); + return sb.toString(); + } + }); + return result; + } + + public static String formatStringArray(String[] a) + { + if (a == null) { + return "null"; + } + + StringBuilder result = new StringBuilder() ; + result.append( "[" ) ; + for (int i = 0; i < a.length; ++i) { + result.append( a[i] ) ; + result.append( " " ) ; + } + result.append( "]" ) ; + return result.toString() ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepIdDelegator.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepIdDelegator.java new file mode 100644 index 000000000..86e5fa62b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepIdDelegator.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + + +import java.io.Serializable; + + +import java.net.MalformedURLException; + +import com.sun.corba.ee.impl.io.TypeMismatchException; + +import com.sun.corba.ee.impl.util.RepositoryId; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +/** + * Delegates to the current RepositoryId implementation in + * com.sun.corba.ee.impl.util. This is necessary to + * overcome the fact that many of RepositoryId's methods + * are static. + */ +public final class RepIdDelegator + implements RepositoryIdStrings, + RepositoryIdUtility, + RepositoryIdInterface +{ + // RepositoryIdFactory methods + + public String createForAnyType(Class type) { + return RepositoryId.createForAnyType(type); + } + + public String createForAnyType(Class type, ClassInfoCache.ClassInfo cinfo ) { + return RepositoryId.createForAnyType(type, cinfo); + } + + public String createForJavaType(Serializable ser) + throws TypeMismatchException + { + return RepositoryId.createForJavaType(ser); + } + + public String createForJavaType(Class clz) + throws TypeMismatchException + { + return RepositoryId.createForJavaType(clz); + } + + public String createForJavaType(Class clz, ClassInfoCache.ClassInfo cinfo ) + throws TypeMismatchException + { + return RepositoryId.createForJavaType(clz,cinfo); + } + + public String createSequenceRepID(java.lang.Object ser) { + return RepositoryId.createSequenceRepID(ser); + } + + public String createSequenceRepID(Class clazz) { + return RepositoryId.createSequenceRepID(clazz); + } + + public RepositoryIdInterface getFromString(String repIdString) { + return new RepIdDelegator(RepositoryId.cache.getId(repIdString)); + } + + // RepositoryIdUtility methods + + public boolean isChunkedEncoding(int valueTag) { + return RepositoryId.isChunkedEncoding(valueTag); + } + + public boolean isCodeBasePresent(int valueTag) { + return RepositoryId.isCodeBasePresent(valueTag); + } + + public String getClassDescValueRepId() { + return RepositoryId.kClassDescValueRepID; + } + + public String getWStringValueRepId() { + return RepositoryId.kWStringValueRepID; + } + + public int getTypeInfo(int valueTag) { + return RepositoryId.getTypeInfo(valueTag); + } + + public int getStandardRMIChunkedNoRepStrId() { + return RepositoryId.kPreComputed_StandardRMIChunked_NoRep; + } + + public int getCodeBaseRMIChunkedNoRepStrId() { + return RepositoryId.kPreComputed_CodeBaseRMIChunked_NoRep; + } + + public int getStandardRMIChunkedId() { + return RepositoryId.kPreComputed_StandardRMIChunked; + } + + public int getCodeBaseRMIChunkedId() { + return RepositoryId.kPreComputed_CodeBaseRMIChunked; + } + + public int getStandardRMIUnchunkedId() { + return RepositoryId.kPreComputed_StandardRMIUnchunked; + } + + public int getCodeBaseRMIUnchunkedId() { + return RepositoryId.kPreComputed_CodeBaseRMIUnchunked; + } + + public int getStandardRMIUnchunkedNoRepStrId() { + return RepositoryId.kPreComputed_StandardRMIUnchunked_NoRep; + } + + public int getCodeBaseRMIUnchunkedNoRepStrId() { + return RepositoryId.kPreComputed_CodeBaseRMIUnchunked_NoRep; + } + + // RepositoryIdInterface methods + + public Class getClassFromType() throws ClassNotFoundException { + return delegate.getClassFromType(); + } + + public Class getClassFromType(String codebaseURL) + throws ClassNotFoundException, MalformedURLException + { + return delegate.getClassFromType(codebaseURL); + } + + public Class getClassFromType(Class expectedType, + String codebaseURL) + throws ClassNotFoundException, MalformedURLException + { + return delegate.getClassFromType(expectedType, codebaseURL); + } + + public String getClassName() { + return delegate.getClassName(); + } + + // Constructor used for factory/utility cases + public RepIdDelegator() {} + + // Constructor used by getIdFromString. All non-static + // RepositoryId methods will use the provided delegate. + private RepIdDelegator(RepositoryId _delegate) { + this.delegate = _delegate; + } + + private RepositoryId delegate; + + public String toString() { + if (delegate != null) + return delegate.toString(); + else + return this.getClass().getName(); + } + + public boolean equals(Object obj) { + if (delegate != null) + return delegate.equals(obj); + else + return super.equals(obj); + } + + public int hashCode() { + return delegate.hashCode() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdFactory.java new file mode 100644 index 000000000..1ebcd3203 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import com.sun.corba.ee.spi.orb.ORB; + +public abstract class RepositoryIdFactory +{ + private static final RepIdDelegator currentDelegator + = new RepIdDelegator(); + + /** + * Returns the latest version RepositoryIdStrings instance + */ + public static RepositoryIdStrings getRepIdStringsFactory() + { + return currentDelegator; + } + + /** + * Checks the version of the ORB and returns the appropriate + * RepositoryIdStrings instance. + */ + public static RepositoryIdStrings getRepIdStringsFactory(ORB orb) + { + return currentDelegator; + } + + /** + * Returns the latest version RepositoryIdUtility instance + */ + public static RepositoryIdUtility getRepIdUtility() + { + return currentDelegator; + } + + /** + * Checks the version of the ORB and returns the appropriate + * RepositoryIdUtility instance. + */ + public static RepositoryIdUtility getRepIdUtility(ORB orb) + { + return currentDelegator; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdInterface.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdInterface.java new file mode 100644 index 000000000..bbd24cfd4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdInterface.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import org.omg.CORBA.ORB; +import java.io.Serializable; +import java.net.MalformedURLException; + +/** + * Methods on specific instances of RepositoryId. Hides + * versioning of our RepositoryId class. + */ +public interface RepositoryIdInterface +{ + Class getClassFromType() throws ClassNotFoundException; + + Class getClassFromType(String codebaseURL) + throws ClassNotFoundException, MalformedURLException; + + Class getClassFromType(Class expectedType, + String codebaseURL) + throws ClassNotFoundException, MalformedURLException; + + String getClassName(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdStrings.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdStrings.java new file mode 100644 index 000000000..b9a27e73a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdStrings.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import java.io.Serializable; +import com.sun.corba.ee.impl.io.TypeMismatchException; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +/** + * Factory methods for creating various repository ID strings + * and instances. + */ +public interface RepositoryIdStrings +{ + String createForAnyType(Class type); + + String createForAnyType(Class type, ClassInfoCache.ClassInfo cinfo ); + + String createForJavaType(Serializable ser) + throws TypeMismatchException; + + String createForJavaType(Class clz) + throws TypeMismatchException; + + String createForJavaType(Class clz, ClassInfoCache.ClassInfo cinfo ) + throws TypeMismatchException; + + String createSequenceRepID(java.lang.Object ser); + + String createSequenceRepID(java.lang.Class clazz); + + RepositoryIdInterface getFromString(String repIdString); + + String getClassDescValueRepId(); + String getWStringValueRepId(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdUtility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdUtility.java new file mode 100644 index 000000000..0fcc61b8f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/misc/RepositoryIdUtility.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.misc; + +import org.omg.CORBA.ORB; +import com.sun.corba.ee.impl.util.RepositoryId; + +/** + * Utility methods for working with repository IDs. + */ +public interface RepositoryIdUtility +{ + boolean isChunkedEncoding(int valueTag); + boolean isCodeBasePresent(int valueTag); + + // These are currently the same in both RepositoryId and + // RepositoryId_1_3, but provide the constants again here + // to eliminate awkardness when using this interface. + int NO_TYPE_INFO = RepositoryId.kNoTypeInfo; + int SINGLE_REP_TYPE_INFO = RepositoryId.kSingleRepTypeInfo; + int PARTIAL_LIST_TYPE_INFO = RepositoryId.kPartialListTypeInfo; + + // Determine how many (if any) repository IDs follow the value + // tag. + int getTypeInfo(int valueTag); + + // Accessors for precomputed value tags + int getStandardRMIChunkedNoRepStrId(); + int getCodeBaseRMIChunkedNoRepStrId(); + int getStandardRMIChunkedId(); + int getCodeBaseRMIChunkedId(); + int getStandardRMIUnchunkedId(); + int getCodeBaseRMIUnchunkedId(); + int getStandardRMIUnchunkedNoRepStrId(); + int getCodeBaseRMIUnchunkedNoRepStrId(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/BindingIteratorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/BindingIteratorImpl.java new file mode 100644 index 000000000..fbea939a2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/BindingIteratorImpl.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +// Import general CORBA classes +import org.omg.CORBA.ORB; + +// Import org.omg.CosNaming classes +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.BindingHolder; +import org.omg.CosNaming.BindingIteratorPOA; +import org.omg.CORBA.BAD_PARAM; + +/** + * Class BindingIteratorImpl implements the org.omg.CosNaming::BindingIterator + * interface, but does not implement the method to retrieve the next + * binding in the NamingContext for which it was created. This is left + * to a subclass, which is why this class is abstract; BindingIteratorImpl + * provides an implementation of the interface operations on top of two + * subclass methods, allowing multiple implementations of iterators that + * differ in storage and access to the contents of a NamingContext + * implementation. + *

    + * The operation next_one() is implemented by the subclass, whereas + * next_n() is implemented on top of the next_one() implementation. + * Destroy must also be implemented by the subclass. + *

    + * A subclass must implement NextOne() and Destroy(); these + * methods are invoked from synchronized methods and need therefore + * not be synchronized themselves. + */ +public abstract class BindingIteratorImpl extends BindingIteratorPOA +{ + protected ORB orb ; + + /** + * Create a binding iterator servant. + * runs the super constructor. + * @param orb an ORB object. + * @exception java.lang.Exception a Java exception. + */ + public BindingIteratorImpl(ORB orb) + throws java.lang.Exception + { + super(); + this.orb = orb ; + } + + /** + * Return the next binding. It also returns true or false, indicating + * whether there were more bindings. + * @param b The Binding as an out parameter. + * @return true if there were more bindings. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see NextOne + */ + public synchronized boolean next_one(org.omg.CosNaming.BindingHolder b) + { + // NextOne actually returns the next one + return nextOneImpl(b); + } + + /** + * Return the next n bindings. It also returns true or false, indicating + * whether there were more bindings. + * @param how_many The number of requested bindings in the BindingList. + * @param blh The BindingList as an out parameter. + * @return true if there were more bindings. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + public synchronized boolean next_n(int how_many, + org.omg.CosNaming.BindingListHolder blh) + { + if( how_many == 0 ) { + throw new BAD_PARAM( " 'how_many' parameter is set to 0 which is" + + " invalid" ); + } + return list( how_many, blh ); + } + + /** + * lists next n bindings. It returns true or false, indicating + * whether there were more bindings. This method has the package private + * scope, It will be called from NamingContext.list() operation or + * this.next_n(). + * @param how_many The number of requested bindings in the BindingList. + * @param blh The BindingList as an out parameter. + * @return true if there were more bindings. + */ + public boolean list( int how_many, org.omg.CosNaming.BindingListHolder blh) + { + // Take the smallest of what's left and what's being asked for + int numberToGet = Math.min(remainingElementsImpl(),how_many); + + // Create a resulting BindingList + Binding[] bl = new Binding[numberToGet]; + BindingHolder bh = new BindingHolder(); + int i = 0; + // Keep iterating as long as there are entries + while (i < numberToGet && this.nextOneImpl(bh) == true) { + bl[i] = bh.value; + i++; + } + // Found any at all? + if (i == 0) { + // No + blh.value = new Binding[0]; + return false; + } + + // Set into holder + blh.value = bl; + + return true; + } + + + + + /** + * Destroy this BindingIterator object. The object corresponding to this + * object reference is destroyed. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see Destroy + */ + public synchronized void destroy() + { + // Destroy actually destroys + this.destroyImpl(); + } + + /** + * Abstract method for returning the next binding in the NamingContext + * for which this BindingIterator was created. + * @param b The Binding as an out parameter. + * @return true if there were more bindings. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + protected abstract boolean nextOneImpl(org.omg.CosNaming.BindingHolder b); + + /** + * Abstract method for destroying this BindingIterator. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + protected abstract void destroyImpl(); + + /** + * Abstract method for returning the remaining number of elements. + * @return the remaining number of elements in the iterator. + */ + protected abstract int remainingElementsImpl(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InterOperableNamingImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InterOperableNamingImpl.java new file mode 100644 index 000000000..f731398a4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InterOperableNamingImpl.java @@ -0,0 +1,387 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +import java.io.StringWriter; + +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContextExtPackage.InvalidAddress; + + +/** + * Class InteroperableNamingImpl implements the methods defined + * for NamingContextExt which is part of Interoperable Naming + * Service specifications. This class is added for doing more + * of Parsing and Building of Stringified names according to INS + * Spec. + */ +public class InterOperableNamingImpl +{ + /** + * Method which stringifies the Name Components given as the input + * parameter. + * + * @param theNameComponents Array of Name Components (Simple or Compound + * Names) + * @return string which is the stringified reference. + */ + public String convertToString( org.omg.CosNaming.NameComponent[] + theNameComponents ) + { + boolean first = true ; + final StringBuffer sb = new StringBuffer() ; + for (NameComponent nc : theNameComponents) { + final String temp = convertNameComponentToString( nc ) ; + sb.append( temp ) ; + if (first) { + first = false ; + } else { + sb.append( '/' ) ; + } + } + + return sb.toString() ; + } + + private boolean isEmpty( String str ) { + return str==null || str.length() == 0 ; + } + + private boolean contains( String str, char ch ) { + return str.indexOf( ch ) != -1 ; + } + + /** This method converts a single Namecomponent to String, By adding Escapes + * If neccessary. + */ + private String convertNameComponentToString( + org.omg.CosNaming.NameComponent theNameComponent ) + { + final String id = addEscape( theNameComponent.id ) ; + final String kind = addEscape( theNameComponent.kind ) ; + final StringBuffer sb = new StringBuffer() ; + + if (!isEmpty(id)) { + sb.append( id ) ; + } + + sb.append( '.' ) ; + + if (!isEmpty(kind)) { + sb.append(kind) ; + } + + return sb.toString() ; + } + + + /** This method adds escape '\' for the Namecomponent if neccessary + */ + private String addEscape( String value ) + { + if ((value != null) && (contains( value, '.' ) || + contains( value, '/' ))) { + final StringBuffer theNewValue = new StringBuffer() ; + for( int i = 0; i < value.length( ); i++ ) { + char c = value.charAt( i ); + if ((c == '.') || (c == '/')) { + theNewValue.append( '\\' ); + } + + // Adding escape for the "." + theNewValue.append( c ); + } + + return theNewValue.toString() ; + } else { + return value; + } + } + + /** + * Method which converts the Stringified name into Array of Name Components. + * + * @param theStringifiedName which is the stringified name. + * @return Array of Name Components (Simple or Compound Names) + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + */ + public org.omg.CosNaming.NameComponent[] convertToNameComponent( + String theStringifiedName ) + throws org.omg.CosNaming.NamingContextPackage.InvalidName + { + String[] components = breakStringToNameComponents( theStringifiedName ); + if (( components == null ) || (components.length == 0)) { + return null; + } + + NameComponent[] theNameComponents = new NameComponent[components.length]; + for( int i = 0; i < components.length; i++ ) { + theNameComponents[i] = createNameComponentFromString( + components[i] ); + } + + return theNameComponents; + } + + /** Step1 in converting Stringified name into array of Name Component + * is breaking the String into multiple name components + */ + private String[] breakStringToNameComponents( final String sname ) { + int[] theIndices = new int[100]; + int theIndicesIndex = 0; + + for(int index = 0; index <= sname.length(); ) { + theIndices[theIndicesIndex] = sname.indexOf( '/', + index ); + if( theIndices[theIndicesIndex] == -1 ) { + // This is the end of all the occurence of '/' and hence come + // out of the loop + index = sname.length()+1; + } + else { + // If the '/' is found, first check whether it is + // preceded by escape '\' + // If not then set theIndices and increment theIndicesIndex + // and also set the index else just ignore the '/' + if( (theIndices[theIndicesIndex] > 0 ) + && (sname.charAt( + theIndices[theIndicesIndex]-1) == '\\') ) + { + index = theIndices[theIndicesIndex] + 1; + theIndices[theIndicesIndex] = -1; + } + else { + index = theIndices[theIndicesIndex] + 1; + theIndicesIndex++; + } + } + } + if( theIndicesIndex == 0 ) { + String[] tempString = new String[1]; + tempString[0] = sname; + return tempString; + } + if( theIndicesIndex != 0 ) { + theIndicesIndex++; + } + return StringComponentsFromIndices( theIndices, theIndicesIndex, + sname ); + } + + /** This method breaks one big String into multiple substrings based + * on the array of index passed in. + */ + private String[] StringComponentsFromIndices( int[] theIndices, + int indicesCount, String theStringifiedName ) + { + String[] theStringComponents = new String[indicesCount]; + int firstIndex = 0; + int lastIndex = theIndices[0]; + for( int i = 0; i < indicesCount; i++ ) { + theStringComponents[i] = theStringifiedName.substring( firstIndex, + lastIndex ); + if( ( theIndices[i] < theStringifiedName.length() - 1 ) + &&( theIndices[i] != -1 ) ) + { + firstIndex = theIndices[i]+1; + } + else { + firstIndex = 0; + i = indicesCount; + } + if( (i+1 < theIndices.length) + && (theIndices[i+1] < (theStringifiedName.length() - 1)) + && (theIndices[i+1] != -1) ) + { + lastIndex = theIndices[i+1]; + } + else { + i = indicesCount; + } + // This is done for the last component + if( firstIndex != 0 && i == indicesCount ) { + theStringComponents[indicesCount-1] = + theStringifiedName.substring( firstIndex ); + } + } + return theStringComponents; + } + + /** Step 2: After Breaking the Stringified name into set of NameComponent + * Strings, The next step is to create Namecomponents from the substring + * by removing the escapes if there are any. + */ + private NameComponent createNameComponentFromString( + String theStringifiedNameComponent ) + throws org.omg.CosNaming.NamingContextPackage.InvalidName + + { + String id = null; + String kind = null; + if( ( theStringifiedNameComponent == null ) + || ( theStringifiedNameComponent.length( ) == 0) + || ( theStringifiedNameComponent.endsWith(".") ) ) + { + // If any of the above is true, then we create an invalid Name + // Component to indicate that it is an invalid name. + throw new org.omg.CosNaming.NamingContextPackage.InvalidName( ); + } + + int index = theStringifiedNameComponent.indexOf( '.', 0 ); + // The format could be XYZ (Without kind) + if( index == -1 ) { + id = theStringifiedNameComponent; + } + // The format is .XYZ (Without ID) + else if( index == 0 ) { + // This check is for the Namecomponent which is just "." meaning Id + // and Kinds are null + if( theStringifiedNameComponent.length( ) != 1 ) { + kind = theStringifiedNameComponent.substring(1); + } + } + else + { + if( theStringifiedNameComponent.charAt(index-1) != '\\' ) { + id = theStringifiedNameComponent.substring( 0, index); + kind = theStringifiedNameComponent.substring( index + 1 ); + } + else { + boolean kindfound = false; + while( (index < theStringifiedNameComponent.length() ) + &&( kindfound != true ) ) + { + index = theStringifiedNameComponent.indexOf( '.',index + 1); + if( index > 0 ) { + if( theStringifiedNameComponent.charAt( + index - 1 ) != '\\' ) + { + kindfound = true; + } + } + else + { + // No more '.', which means there is no Kind + index = theStringifiedNameComponent.length(); + } + } + if( kindfound == true ) { + id = theStringifiedNameComponent.substring( 0, index); + kind = theStringifiedNameComponent.substring(index + 1 ); + } + else { + id = theStringifiedNameComponent; + } + } + } + id = cleanEscapeCharacter( id ); + kind = cleanEscapeCharacter( kind ); + if( id == null ) { + id = ""; + } + if( kind == null ) { + kind = ""; + } + return new NameComponent( id, kind ); + } + + + /** This method cleans the escapes in the Stringified name and returns the + * correct String + */ + private String cleanEscapeCharacter( String theString ) + { + if( ( theString == null ) || (theString.length() == 0 ) ) { + return theString; + } + int index = theString.indexOf( '\\' ); + if( index == 0 ) { + return theString; + } + else { + StringBuffer src = new StringBuffer( theString ); + StringBuffer dest = new StringBuffer( ); + char c; + for( int i = 0; i < theString.length( ); i++ ) { + c = src.charAt( i ); + if( c != '\\' ) { + dest.append( c ); + } else { + if( i+1 < theString.length() ) { + char d = src.charAt( i + 1 ); + // If there is a AlphaNumeric character after a \ + // then include slash, as it is not intended as an + // escape character. + if( Character.isLetterOrDigit(d) ) { + dest.append( c ); + } + } + } + } + return new String(dest); + } + } + + /** + * Method which converts the Stringified name and Host Name Address into + * a URL based Name + * + * @param address which is ip based host name + * @param name which is the stringified name. + * @return url based Name. + */ + public String createURLBasedAddress( String address, String name ) + throws InvalidAddress + { + String theurl = null; + if( ( address == null ) + ||( address.length() == 0 ) ) { + throw new InvalidAddress(); + } + else { + theurl = "corbaname:" + address + "#" + encode( name ); + } + return theurl; + } + + /** Encodes the string according to RFC 2396 IETF spec required by INS. + */ + private String encode( String stringToEncode ) { + StringWriter theStringAfterEscape = new StringWriter(); + int byteCount = 0; + for( int i = 0; i < stringToEncode.length(); i++ ) + { + char c = stringToEncode.charAt( i ) ; + if( Character.isLetterOrDigit( c ) ) { + theStringAfterEscape.write( c ); + } + // Do no Escape for characters in this list + // RFC 2396 + else if((c == ';') || (c == '/') || (c == '?') + || (c == ':') || (c == '@') || (c == '&') || (c == '=') + || (c == '+') || (c == '$') || (c == ';') || (c == '-') + || (c == '_') || (c == '.') || (c == '!') || (c == '~') + || (c == '*') || (c == ' ') || (c == '(') || (c == ')') ) + { + theStringAfterEscape.write( c ); + } + else { + // Add escape + theStringAfterEscape.write( '%' ); + String hexString = Integer.toHexString( (int) c ); + theStringAfterEscape.write( hexString ); + } + } + return theStringAfterEscape.toString(); + } + +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InternalBindingKey.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InternalBindingKey.java new file mode 100644 index 000000000..1efa7352f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InternalBindingKey.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +import org.omg.CosNaming.NameComponent; + +/** + * Class InternalBindingKey implements the necessary wrapper code + * around the org.omg.CosNaming::NameComponent class to implement the proper + * equals() method and the hashCode() method for use in a hash table. + * It computes the hashCode once and stores it, and also precomputes + * the lengths of the id and kind strings for faster comparison. + */ +public class InternalBindingKey +{ + // A key contains a name + public NameComponent name; + private int idLen; + private int kindLen; + private int hashVal; + + // Default Constructor + public InternalBindingKey() {} + + // Normal constructor + public InternalBindingKey(NameComponent n) + { + idLen = 0; + kindLen = 0; + setup(n); + } + + // Setup the object + protected void setup(NameComponent n) { + this.name = n; + // Precompute lengths and values since they will not change + if( this.name.id != null ) { + idLen = this.name.id.length(); + } + if( this.name.kind != null ) { + kindLen = this.name.kind.length(); + } + hashVal = 0; + if (idLen > 0) + hashVal += this.name.id.hashCode(); + if (kindLen > 0) + hashVal += this.name.kind.hashCode(); + } + + // Compare the keys by comparing name's id and kind + public boolean equals(java.lang.Object o) { + if (o == null) + return false; + if (o instanceof InternalBindingKey) { + InternalBindingKey that = (InternalBindingKey)o; + // Both lengths must match + if (this.idLen != that.idLen || this.kindLen != that.kindLen) { + return false; + } + // If id is set is must be equal + if (this.idLen > 0 && this.name.id.equals(that.name.id) == false) { + return false; + } + // If kind is set it must be equal + if (this.kindLen > 0 && this.name.kind.equals(that.name.kind) == false) { + return false; + } + // Must be the same + return true; + } else { + return false; + } + } + // Return precomputed value + public int hashCode() { + return this.hashVal; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InternalBindingValue.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InternalBindingValue.java new file mode 100644 index 000000000..4b4402790 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/InternalBindingValue.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +import org.omg.CORBA.Object; +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.NameComponent; + +/** + * Class InternalBindingKey acts as a container for two objects, namely + * a org.omg.CosNaming::Binding and an CORBA object reference, which are the two + * components associated with the binding. + */ +public class InternalBindingValue +{ + public Binding theBinding; + public String strObjectRef; + public org.omg.CORBA.Object theObjectRef; + + // Default constructor + public InternalBindingValue() {} + + // Normal constructor + public InternalBindingValue(Binding b, String o) { + theBinding = b; + strObjectRef = o; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingContextDataStore.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingContextDataStore.java new file mode 100644 index 000000000..849d33e2b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingContextDataStore.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +// Import general CORBA classes +import org.omg.CORBA.Object; + +// Import org.omg.CosNaming classes +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.BindingTypeHolder; +import org.omg.CosNaming.BindingListHolder; +import org.omg.CosNaming.BindingIteratorHolder; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.PortableServer.POA; + +/** + * This interface defines a set of methods that must be implemented by the + * "data store" associated with a NamingContext implementation. + * It allows for different implementations of naming contexts that + * support the same API but differ in storage mechanism. + */ +public interface NamingContextDataStore { + /** + * Method which implements binding a name to an object as + * the specified binding type. + * @param n a NameComponent which is the name under which the object + * will be bound. + * @param obj the object reference to be bound. + * @param bt Type of binding (as object or as context). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + void bindImpl(NameComponent n, org.omg.CORBA.Object obj, BindingType bt) + throws org.omg.CORBA.SystemException; + + /** + * Method which implements resolving the specified name, + * returning the type of the binding and the bound object reference. + * If the id and kind of the NameComponent are both empty, the initial + * naming context (i.e., the local root) must be returned. + * @param n a NameComponent which is the name to be resolved. + * @param bth the BindingType as an out parameter. + * @return the object reference bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + org.omg.CORBA.Object resolveImpl(NameComponent n,BindingTypeHolder bth) + throws org.omg.CORBA.SystemException; + + /** + * Method which implements unbinding a name. + * @return the object reference bound to the name, or null if not found. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + org.omg.CORBA.Object unbindImpl(NameComponent n) + throws org.omg.CORBA.SystemException; + + /** + * Method which implements listing the contents of this + * NamingContext and return a binding list and a binding iterator. + * @param how_many The number of requested bindings in the BindingList. + * @param bl The BindingList as an out parameter. + * @param bi The BindingIterator as an out parameter. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + void listImpl(int how_many, BindingListHolder bl, BindingIteratorHolder bi) + throws org.omg.CORBA.SystemException; + + /** + * Method which implements creating a new NamingContext. + * @return an object reference for a new NamingContext object implemented + * by this Name Server. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + NamingContext newContextImpl() + throws org.omg.CORBA.SystemException; + + /** + * Method which implements destroying this NamingContext. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + */ + void destroyImpl() + throws org.omg.CORBA.SystemException; + + /** + * Method which returns whether this NamingContext is empty + * or not. + * @return true if this NamingContext contains no bindings. + */ + boolean isEmptyImpl(); + + POA getNSPOA( ); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingContextImpl.java new file mode 100644 index 000000000..cb224c470 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingContextImpl.java @@ -0,0 +1,839 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +import org.omg.CORBA.BAD_PARAM; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; + +// Import org.omg.CosNaming classes +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.BindingTypeHolder; +import org.omg.CosNaming.BindingListHolder; +import org.omg.CosNaming.BindingIteratorHolder; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextExtPOA; +import org.omg.CosNaming.NamingContextPackage.NotFound; + +import com.sun.corba.ee.impl.naming.namingutil.INSURLHandler; +import com.sun.corba.ee.spi.logging.NamingSystemException ; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.trace.Naming; +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.NotFoundReason; + +/** + * Class NamingContextImpl implements the org.omg.CosNaming::NamingContext + * interface, but does not implement the methods associated with + * maintaining the "table" of current bindings in a NamingContext. + * Instead, this implementation assumes that the derived implementation + * implements the NamingContextDataStore interface, which has the necessary + * methods. This allows multiple + * NamingContext implementations that differ in storage of the bindings, + * as well as implementations of interfaces derived from + * CosNaming::NamingContext that still reuses the implementation. + *

    + * The operations bind(), rebind(), bind_context() and rebind_context() + * are all really implemented by doBind(). resolve() is really implemented + * by doResolve(), unbind() by doUnbind(). list(), new_context() and + * destroy() uses the NamingContextDataStore interface directly. All the + * doX() methods are public static. + * They synchronize on the NamingContextDataStore object. + *

    + * An implementation a NamingContext must extend this class and implement + * the NamingContextDataStore interface with the operations: + * Bind(), Resolve(), + * Unbind(), List(), NewContext() and Destroy(). Calls + * to these methods are synchronized; these methods should + * therefore not be synchronized. + */ +@Naming +public abstract class NamingContextImpl + extends NamingContextExtPOA + implements NamingContextDataStore +{ + + protected ORB orb ; + protected POA nsPOA; + private static final NamingSystemException wrapper = + NamingSystemException.self ; + + // The grammer for Parsing and Building Interoperable Stringified Names + // are implemented in this class + private InterOperableNamingImpl insImpl; + /** + * Create a naming context servant. + * Runs the super constructor. + * @param orb an ORB object. + * @param poa the POA. + * @exception java.lang.Exception a Java exception. + */ + public NamingContextImpl(ORB orb, POA poa) throws java.lang.Exception { + super(); + this.orb = orb ; + insImpl = new InterOperableNamingImpl( ); + this.nsPOA = poa; + } + + public POA getNSPOA( ) { + return nsPOA; + } + + /** + * Bind an object under a name in this NamingContext. If the name + * contains multiple (n) components, n-1 will be resolved in this + * NamingContext and the object bound in resulting NamingContext. + * An exception is thrown if a binding with the supplied name already + * exists. If the + * object to be bound is a NamingContext it will not participate in + * a recursive resolve. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could + * not proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object + * is already bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #doBind + */ + @Naming + public void bind(NameComponent[] n, org.omg.CORBA.Object obj) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, + org.omg.CosNaming.NamingContextPackage.AlreadyBound + { + if( obj == null ) { + throw wrapper.objectIsNull() ; + } + // doBind implements all four flavors of binding + NamingContextDataStore impl = this; + doBind(impl,n,obj,false,BindingType.nobject); + } + + + /** + * Bind a NamingContext under a name in this NamingContext. If the name + * contains multiple (n) components, n-1 will be resolved in this + * NamingContext and the object bound in resulting NamingContext. + * An exception is thrown if a binding with the supplied name already + * exists. The NamingContext will participate in recursive resolving. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param nc the NamingContect object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could + * not proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object + * is already bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #doBind + */ + @Naming + public void bind_context(NameComponent[] n, NamingContext nc) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, + org.omg.CosNaming.NamingContextPackage.AlreadyBound + { + if( nc == null ) { + wrapper.objectIsNull() ; + } + // doBind implements all four flavors of binding + NamingContextDataStore impl = this; + doBind(impl,n,nc,false,BindingType.ncontext); + } + + /** + * Bind an object under a name in this NamingContext. If the name + * contains multiple (n) components, n-1 will be resolved in this + * NamingContext and the object bound in resulting NamingContext. + * If a binding under the supplied name already exists it will be + * unbound first. If the + * object to be bound is a NamingContext it will not participate in + * a recursive resolve. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not + * proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #doBind + */ + @Naming + public void rebind(NameComponent[] n, org.omg.CORBA.Object obj) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + if( obj == null ) { + throw wrapper.objectIsNull() ; + } + + try { + // doBind implements all four flavors of binding + NamingContextDataStore impl = this; + doBind(impl,n,obj,true,BindingType.nobject); + } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { + throw wrapper.namingCtxRebindAlreadyBound( ex ) ; + } + } + + /** + * Bind a NamingContext under a name in this NamingContext. If the name + * contains multiple (n) components, the first n-1 components will be + * resolved in this NamingContext and the object bound in resulting + * NamingContext. If a binding under the supplied name already exists it + * will be unbound first. The NamingContext will participate in recursive + * resolving. + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param nc the object reference to be bound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not + * proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #doBind + */ + @Naming + public void rebind_context(NameComponent[] n, NamingContext nc) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + if( nc == null ) { + throw wrapper.objectIsNull() ; + } + + try { + // doBind implements all four flavors of binding + NamingContextDataStore impl = this; + doBind(impl,n,nc,true,BindingType.ncontext); + } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { + throw wrapper.namingCtxRebindctxAlreadyBound( ex ) ; + } + } + + /** + * Resolve a name in this NamingContext and return the object reference + * bound to the name. If the name contains multiple (n) components, + * the first component will be resolved in this NamingContext and the + * remaining components resolved in the resulting NamingContext, provided + * that the NamingContext bound to the first component of the name was + * bound with bind_context(). + * @param n a sequence of NameComponents which is the name to be resolved. + * @return the object reference bound under the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not + * proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #doResolve + */ + @Naming + public org.omg.CORBA.Object resolve(NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + // doResolve actually resolves + NamingContextDataStore impl = this; + return doResolve(impl,n); + } + + + /** + * Remove a binding from this NamingContext. If the name contains + * multiple (n) components, the first n-1 components will be resolved + * from this NamingContext and the final component unbound in + * the resulting NamingContext. + * @param n a sequence of NameComponents which is the name to be unbound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not + * proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #doUnbind + */ + @Naming + public void unbind(NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + // doUnbind actually unbinds + NamingContextDataStore impl = this; + doUnbind(impl,n); + } + + /** + * List the contents of this NamingContest. A sequence of bindings + * is returned (a BindingList) containing up to the number of requested + * bindings, and a BindingIterator object reference is returned for + * iterating over the remaining bindings. + * @param how_many The number of requested bindings in the BindingList. + * @param bl The BindingList as an out parameter. + * @param bi The BindingIterator as an out parameter. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see BindingListHolder + * @see BindingIteratorImpl + */ + @Naming + public void list(int how_many, BindingListHolder bl, + BindingIteratorHolder bi) + { + // List actually generates the list + NamingContextDataStore impl = this; + synchronized (impl) { + impl.listImpl(how_many,bl,bi); + } + } + + /** + * Create a NamingContext object and return its object reference. + * @return an object reference for a new NamingContext object implemented + * by this Name Server. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public synchronized NamingContext new_context() + { + NamingContextDataStore impl = this; + synchronized (impl) { + return impl.newContextImpl(); + } + } + + /** + * Create a new NamingContext, bind it in this Naming Context and return + * its object reference. This is equivalent to using new_context() followed + * by bind_context() with the supplied name and the object reference for + * the newly created NamingContext. + * @param n a sequence of NameComponents which is the name to be unbound. + * @return an object reference for a new NamingContext object implemented + * by this Name Server, bound to the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object + * is already bound under the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not + * proceed in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #new_context + * @see #bind_context + */ + @Naming + public NamingContext bind_new_context(NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.AlreadyBound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + NamingContext nc = null; + NamingContext rnc = null; + try { + nc = this.new_context(); + this.bind_context(n,nc); + rnc = nc; + nc = null; + } finally { + try { + if (nc != null) { + nc.destroy(); + } + } catch (org.omg.CosNaming.NamingContextPackage.NotEmpty e) { + throw new CannotProceed( "Old naming context is not empty", + nc, n) ; + } + } + + return rnc; + } + + /** + * Destroy this NamingContext object. If this NamingContext contains + * no bindings, the NamingContext is deleted. + * @exception org.omg.CosNaming.NamingContextPackage.NotEmpty This + * NamingContext is not empty (i.e., contains bindings). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public void destroy() + throws org.omg.CosNaming.NamingContextPackage.NotEmpty + { + NamingContextDataStore impl = this; + synchronized (impl) { + if (impl.isEmptyImpl()) { + // The context is empty so it can be destroyed + impl.destroyImpl(); + } else { + throw new NotEmpty(); + } + } + } + + /** + * Implements all four flavors of binding. It uses Resolve() to + * check if a binding already exists (for bind and bind_context), and + * unbind() to ensure that a binding does not already exist. + * If the length of the name is 1, then Bind() is called with + * the name and the object to bind. Otherwise, the first component + * of the name is resolved in this NamingContext and the appropriate + * form of bind passed to the resulting NamingContext. + * This method is static for maximal reuse - even for extended naming + * context implementations where the recursive semantics still apply. + * @param impl an implementation of NamingContextDataStore + * @param n a sequence of NameComponents which is the name under which + * the object will be bound. + * @param obj the object reference to be bound. + * @param rebind Replace an existing binding or not. + * @param bt Type of binding (as object or as context). + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not * proceed + * in resolving the first component of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The + * supplied name is invalid (i.e., has length less than 1). + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound An object + * is already bound under the supplied name. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + * @see #resolve + * @see #unbind + * @see #bind + * @see #bind_context + * @see #rebind + * @see #rebind_context + */ + @Naming + public static void doBind(NamingContextDataStore impl, + NameComponent[] n, + org.omg.CORBA.Object obj, + boolean rebind, + org.omg.CosNaming.BindingType bt) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, + org.omg.CosNaming.NamingContextPackage.AlreadyBound + { + if (n.length < 1) { + throw new InvalidName(); + } + + if (n.length == 1) { + if ( (n[0].id.length() == 0) && (n[0].kind.length() == 0 ) ) { + throw new InvalidName(); + } + + synchronized (impl) { + BindingTypeHolder bth = new BindingTypeHolder(); + if (rebind) { + org.omg.CORBA.Object objRef = impl.resolveImpl( n[0], bth ); + if( objRef != null ) { + // Refer Naming Service Doc:00-11-01 section 2.2.3.4 + // If there is an object already bound with the name + // and the binding type is not ncontext a NotFound + // Exception with a reason of not a context has to be + // raised. + // Fix for bug Id: 4384628 + if ( bth.value.value() == BindingType.nobject.value() ){ + if ( bt.value() == BindingType.ncontext.value() ) { + throw new NotFound( + NotFoundReason.not_context, n); + } + } else { + // Previously a Context was bound and now trying to + // bind Object. It is invalid. + if ( bt.value() == BindingType.nobject.value() ) { + throw new NotFound( + NotFoundReason.not_object, n); + } + } + + impl.unbindImpl(n[0]); + } + } else { + if (impl.resolveImpl(n[0],bth) != null) { + throw new AlreadyBound(); + } + } + + // Now there are no other bindings under this name + impl.bindImpl(n[0],obj,bt); + } + } else { + NamingContext context = resolveFirstAsContext(impl,n); + NameComponent[] tail = new NameComponent[n.length - 1]; + System.arraycopy(n,1,tail,0,n.length-1); + + switch (bt.value()) { + case BindingType._nobject: + if (rebind) { + context.rebind(tail, obj); + } else { + context.bind(tail, obj); + } + break; + case BindingType._ncontext: + NamingContext objContext = (NamingContext)obj; + if (rebind) { + context.rebind_context(tail, objContext); + } + else { + context.bind_context(tail, objContext); + } + break; + default: + throw wrapper.namingCtxBadBindingtype() ; + } + } + } + + /** + * Implements resolving names in this NamingContext. The first component + * of the supplied name is resolved in this NamingContext by calling + * Resolve(). If there are no more components in the name, the + * resulting object reference is returned. Otherwise, the resulting object + * reference must have been bound as a context and be narrowable to + * a NamingContext. If this is the case, the remaining + * components of the name is resolved in the resulting NamingContext. + * This method is static for maximal reuse - even for extended naming + * context implementations where the recursive semantics still apply. + * @param impl an implementation of NamingContextDataStore + * @param n a sequence of NameComponents which is the name to be resolved. + * @return the object reference bound under the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with + * multiple components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not + * proceed + * in resolving the first component of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied + * name is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system + * exceptions. + * @see #resolve + */ + @Naming + public static org.omg.CORBA.Object doResolve(NamingContextDataStore impl, + NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + org.omg.CORBA.Object obj; + BindingTypeHolder bth = new BindingTypeHolder(); + + if (n.length < 1) { + throw new InvalidName(); + } + + if (n.length == 1) { + synchronized (impl) { + obj = impl.resolveImpl(n[0],bth); + } + if (obj == null) { + throw new NotFound(NotFoundReason.missing_node,n); + } + return obj; + } else { + if ( (n[1].id.length() == 0) && (n[1].kind.length() == 0) ) { + throw new InvalidName(); + } + + NamingContext context = resolveFirstAsContext(impl,n); + NameComponent[] tail = new NameComponent[n.length -1]; + System.arraycopy(n,1,tail,0,n.length-1); + + try { + // First try to resolve using the local call, this should work + // most of the time unless there are federated naming contexts. + Servant servant = impl.getNSPOA().reference_to_servant( + context ); + return doResolve(((NamingContextDataStore)servant), tail) ; + } catch( Exception e ) { + return context.resolve(tail); + } + } + } + + /** + * Implements unbinding bound names in this NamingContext. If the + * name contains only one component, the name is unbound in this + * NamingContext using Unbind(). Otherwise, the first component + * of the name is resolved in this NamingContext and + * unbind passed to the resulting NamingContext. + * This method is static for maximal reuse - even for extended naming + * context implementations where the recursive semantics still apply. + * @param impl an implementation of NamingContextDataStore + * @param n a sequence of NameComponents which is the name to be unbound. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound A name with multiple + * components was supplied, but the first component could not be + * resolved. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Could not proceed + * in resolving the n-1 components of the supplied name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName The supplied name + * is invalid (i.e., has length less than 1). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see #resolve + */ + @Naming + public static void doUnbind(NamingContextDataStore impl, + NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + if (n.length < 1) { + throw new InvalidName(); + } + + if (n.length == 1) { + if ( (n[0].id.length() == 0) && (n[0].kind.length() == 0 ) ) { + throw new InvalidName(); + } + + org.omg.CORBA.Object objRef; + synchronized (impl) { + objRef = impl.unbindImpl(n[0]); + } + + if (objRef == null) { + throw new NotFound(NotFoundReason.missing_node, n); + } + } else { + NamingContext context = resolveFirstAsContext(impl,n); + NameComponent[] tail = new NameComponent[n.length - 1]; + System.arraycopy(n,1,tail,0,n.length-1); + + context.unbind(tail); + } + } + + /** + * Implements resolving a NameComponent in this context and + * narrowing it to CosNaming::NamingContext. It will throw appropriate + * exceptions if not found or not narrowable. + * @param impl an implementation of NamingContextDataStore + * @param n a NameComponents which is the name to be found. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound The + * first component could not be resolved. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA system exceptions. + * @see #resolve + * @return a naming context + */ + @Naming + protected static NamingContext resolveFirstAsContext( + NamingContextDataStore impl, NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound { + + org.omg.CORBA.Object topRef; + BindingTypeHolder bth = new BindingTypeHolder(); + NamingContext context; + + synchronized (impl) { + topRef = impl.resolveImpl(n[0],bth); + if (topRef == null) { + throw new NotFound(NotFoundReason.missing_node,n); + } + } + + if (bth.value != BindingType.ncontext) { + throw new NotFound(NotFoundReason.not_context,n); + } + + try { + context = NamingContextHelper.narrow(topRef); + } catch (org.omg.CORBA.BAD_PARAM ex) { + throw new NotFound(NotFoundReason.not_context,n); + } + + return context; + } + + + /** + * This operation creates a stringified name from the array of Name + * components. + * @param n Name of the object + * @return the object name as a single string + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + * Indicates the name does not identify a binding. + * + */ + @Naming + public String to_string(org.omg.CosNaming.NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.InvalidName + { + if ( (n == null ) || (n.length == 0) ) { + throw new InvalidName(); + } + + String theStringifiedName = insImpl.convertToString( n ); + + if (theStringifiedName == null) { + throw new InvalidName(); + } + + return theStringifiedName; + } + + + /** + * This operation converts a Stringified Name into an equivalent array + * of Name Components. + * @param sn Stringified Name of the object

    + * @return an array of name components + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + * + */ + @Naming + public org.omg.CosNaming.NameComponent[] to_name(String sn) + throws org.omg.CosNaming.NamingContextPackage.InvalidName + { + if ((sn == null ) || (sn.length() == 0)) { + throw new InvalidName(); + } + + org.omg.CosNaming.NameComponent[] theNameComponents = + insImpl.convertToNameComponent( sn ); + if (( theNameComponents == null ) || (theNameComponents.length == 0)) { + throw new InvalidName(); + } + + for (NameComponent theNameComponent : theNameComponents) { + if (((theNameComponent.id == null) + || (theNameComponent.id.length() == 0)) + && ((theNameComponent.kind == null) + || (theNameComponent.kind.length() == 0))) { + throw new InvalidName(); + } + } + + return theNameComponents; + } + + /** + * This operation creates a URL based "iiopname://" format name + * from the Stringified Name of the object. + * @param addr internet based address of the host machine where + * Name Service is running

    + * @param sn Stringified Name of the object

    + * @return a url string + * @throws org.omg.CosNaming.NamingContextExtPackage.InvalidAddress + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + * + */ + @Naming + public String to_url(String addr, String sn) + throws org.omg.CosNaming.NamingContextExtPackage.InvalidAddress, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + if ((sn == null ) || (sn.length() == 0)) { + throw new InvalidName(); + } + + if( addr == null ) { + throw new org.omg.CosNaming.NamingContextExtPackage.InvalidAddress(); + } + + String urlBasedAddress; + urlBasedAddress = insImpl.createURLBasedAddress( addr, sn ); + + try { + INSURLHandler.getINSURLHandler( ).parseURL( urlBasedAddress ); + } catch( BAD_PARAM e ) { + throw new org.omg.CosNaming.NamingContextExtPackage.InvalidAddress(); + } + + return urlBasedAddress; + } + + /** + * This operation resolves the Stringified name into the object + * reference. + * @param sn Stringified Name of the object + * @return an object + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * Indicates there is no object reference for the given name. + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * Indicates that the given compound name is incorrect + * @throws org.omg.CosNaming.NamingContextPackage.InvalidName + * + */ + @Naming + public org.omg.CORBA.Object resolve_str(String sn) + throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName + { + org.omg.CORBA.Object theObject; + if ((sn == null) || (sn.length() == 0)) { + throw new InvalidName(); + } + + org.omg.CosNaming.NameComponent[] theNameComponents = + insImpl.convertToNameComponent( sn ); + + if ((theNameComponents == null) || (theNameComponents.length == 0 )) { + throw new InvalidName(); + } + + theObject = resolve( theNameComponents ); + return theObject; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingUtils.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingUtils.java new file mode 100644 index 000000000..e658e7583 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/NamingUtils.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +import java.io.*; +import org.omg.CosNaming.NameComponent; + + +public class NamingUtils { + // Do not instantiate this class + private NamingUtils() {}; + + /** + * Debug flag which must be true for debug streams to be created and + * dprint output to be generated. + */ + public static boolean debug = false; + + /** + * Prints the message to the debug stream if debugging is enabled. + * @param msg the debug message to print. + */ + public static void dprint(String msg) { + if (debug && debugStream != null) + debugStream.println(msg); + } + + /** + * Prints the message to the error stream (System.err is default). + * @param msg the error message to print. + */ + public static void errprint(String msg) { + if (errStream != null) + errStream.println(msg); + else + System.err.println(msg); + } + + /** + * Prints the stacktrace of the supplied exception to the error stream. + * @param e any Java exception. + */ + public static void printException(java.lang.Exception e) { + if (errStream != null) + e.printStackTrace(errStream); + else + e.printStackTrace(); + } + + /** + * Create a debug print stream to the supplied log file. + * @param logFile the file to which debug output will go. + * @exception IOException thrown if the file cannot be opened for output. + */ + public static void makeDebugStream(File logFile) + throws java.io.IOException { + // Create an outputstream for debugging + java.io.OutputStream logOStream = + new java.io.FileOutputStream(logFile); + java.io.DataOutputStream logDStream = + new java.io.DataOutputStream(logOStream); + debugStream = new java.io.PrintStream(logDStream); + + // Emit first message + debugStream.println("Debug Stream Enabled."); + } + + /** + * Create a error print stream to the supplied file. + * @param logFile the file to which error messages will go. + * @exception IOException thrown if the file cannot be opened for output. + */ + public static void makeErrStream(File errFile) + throws java.io.IOException { + if (debug) { + // Create an outputstream for errors + java.io.OutputStream errOStream = + new java.io.FileOutputStream(errFile); + java.io.DataOutputStream errDStream = + new java.io.DataOutputStream(errOStream); + errStream = new java.io.PrintStream(errDStream); + dprint("Error stream setup completed."); + } + } + + + /** + * A utility method that takes Array of NameComponent and converts + * into a directory structured name in the format of /id1.kind1/id2.kind2.. + * This is used mainly for Logging. + */ + static String getDirectoryStructuredName( NameComponent[] name ) { + StringBuffer directoryStructuredName = new StringBuffer("/"); + for( int i = 0; i < name.length; i++ ) { + directoryStructuredName.append( name[i].id + "." + name[i].kind ); + } + return directoryStructuredName.toString( ); + } + + /** + * The debug printstream. + */ + public static java.io.PrintStream debugStream; + + /** + * The error printstream. + */ + public static java.io.PrintStream errStream; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientBindingIterator.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientBindingIterator.java new file mode 100644 index 000000000..cd6e2fd3a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientBindingIterator.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +// Import general CORBA classes +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; + +// Get org.omg.CosNaming Types +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.NameComponent; + +// Get base implementation + +// Get a hash table +import java.util.Map; +import java.util.Iterator; + +/** + * Class TransientBindingIterator implements the abstract methods + * defined by BindingIteratorImpl, to use with the TransientNamingContext + * implementation of the NamingContextImpl. The TransientBindingIterator + * implementation receives a hash table of InternalBindingValues, and uses + * an Enumeration to iterate over the contents of the hash table. + * @see BindingIteratorImpl + * @see TransientNamingContext + */ +public class TransientBindingIterator extends BindingIteratorImpl +{ + // There is only one POA used for both TransientNamingContext and + // TransientBindingIteraor servants. + private POA nsPOA; + /** + * Constructs a new TransientBindingIterator object. + * @param orb a org.omg.CORBA.ORB object. + * @param aTable A hashtable containing InternalBindingValues which is + * the content of the TransientNamingContext. + * @param thePOA the POA to use. + * @throws java.lang.Exception a Java exception. + */ + public TransientBindingIterator(ORB orb, + Map aTable, + POA thePOA ) + throws java.lang.Exception + { + super(orb); + bindingMap = aTable; + bindingIterator = aTable.values().iterator() ; + currentSize = this.bindingMap.size(); + this.nsPOA = thePOA; + } + + /** + * Returns the next binding in the NamingContext. Uses the enumeration + * object to determine if there are more bindings and if so, returns + * the next binding from the InternalBindingValue. + * @param b The Binding as an out parameter. + * @return true if there were more bindings. + */ + final public boolean nextOneImpl(org.omg.CosNaming.BindingHolder b) + { + // If there are more elements get the next element + boolean hasMore = bindingIterator.hasNext(); + if (hasMore) { + b.value = bindingIterator.next().theBinding; + currentSize--; + } else { + // Return empty but marshalable binding + b.value = new Binding(new NameComponent[0],BindingType.nobject); + } + return hasMore; + } + + /** + * Destroys this BindingIterator by disconnecting from the ORB + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + final public void destroyImpl() + { + // Remove the object from the Active Object Map. + try { + byte[] objectId = nsPOA.servant_to_id( this ); + if( objectId != null ) { + nsPOA.deactivate_object( objectId ); + } + } + catch( Exception e ) { + NamingUtils.errprint("BindingIterator.Destroy():caught exception:"); + NamingUtils.printException(e); + } + } + + /** + * Returns the remaining number of elements in the iterator. + * @return the remaining number of elements in the iterator. + */ + public final int remainingElementsImpl() { + return currentSize; + } + + private int currentSize; + private Map bindingMap; + private Iterator bindingIterator; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientNameServer.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientNameServer.java new file mode 100644 index 000000000..8fc183ca6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientNameServer.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +import java.util.Properties; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.CorbaResourceUtil; +import com.sun.corba.ee.spi.logging.NamingSystemException; +import com.sun.corba.ee.spi.trace.Naming; + +/** + * Class TransientNameServer is a standalone application which + * implements a transient name service. It uses the TransientNameService + * class for the name service implementation, and the BootstrapServer + * for implementing bootstrapping, i.e., to get the initial NamingContext. + *

    + * The BootstrapServer uses a Properties object specify the initial service + * object references supported; such as Properties object is created containing + * only a "NameService" entry together with the stringified object reference + * for the initial NamingContext. The BootstrapServer's listening port + * is set by first checking the supplied arguments to the name server + * (-ORBInitialPort), and if not set, defaults to the standard port number. + * The BootstrapServer is created supplying the Properties object, using no + * external File object for storage, and the derived initial port number. + * @see TransientNameService + * @see BootstrapServer + */ +@Naming +public class TransientNameServer +{ + static private boolean debug = false ; + private static final NamingSystemException wrapper = + NamingSystemException.self ; + + @Naming + private static org.omg.CORBA.Object initializeRootNamingContext( ORB orb ) { + org.omg.CORBA.Object rootContext = null; + try { + com.sun.corba.ee.spi.orb.ORB coreORB = + (com.sun.corba.ee.spi.orb.ORB)orb ; + + TransientNameService tns = new TransientNameService(coreORB ); + return tns.initialNamingContext(); + } catch (org.omg.CORBA.SystemException e) { + throw wrapper.transNsCannotCreateInitialNcSys( e ) ; + } catch (Exception e) { + throw wrapper.transNsCannotCreateInitialNc( e ) ; + } + } + + /** + * Main startup routine. It instantiates a TransientNameService + * object and a BootstrapServer object, and then allows invocations to + * happen. + * @param args an array of strings representing the startup arguments. + */ + @Naming + public static void main(String args[]) { + boolean invalidHostOption = false; + boolean orbInitialPort0 = false; + + // Determine the initial bootstrap port to use + int initialPort = 0; + try { + // Create an ORB object + Properties props = System.getProperties() ; + + props.put( ORBConstants.ORB_SERVER_ID_PROPERTY, + ORBConstants.NAME_SERVICE_SERVER_ID ) ; + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ); + + String ips = null ; + try { + ips = System.getProperty( ORBConstants.INITIAL_PORT_PROPERTY ) ; + if (ips != null && ips.length() > 0 ) { + initialPort = java.lang.Integer.parseInt(ips); + if( initialPort == 0 ) { + orbInitialPort0 = true; + throw wrapper.transientNameServerBadPort() ; + } + } + + String hostName = + System.getProperty( ORBConstants.INITIAL_HOST_PROPERTY ) ; + + if( hostName != null ) { + invalidHostOption = true; + throw wrapper.transientNameServerBadHost() ; + } + } catch (java.lang.NumberFormatException e) { + wrapper.badInitialPortValue( ips, e ) ; + } + + // Let arguments override + for (int i=0;i + * The TransientNameService creates the initial NamingContext object. + * @see NamingContextImpl + * @see BindingIteratorImpl + * @see TransientNamingContext + * @see TransientBindingIterator + */ +@Naming +public class TransientNameService +{ + private static final NamingSystemException wrapper = + NamingSystemException.self ; + + /** + * Constructs a new TransientNameService, and creates an initial + * NamingContext, whose object + * reference can be obtained by the initialNamingContext method. + * @param orb The ORB object + * @exception org.omg.CORBA.INITIALIZE Thrown if + * the TransientNameService cannot initialize. + */ + public TransientNameService(com.sun.corba.ee.spi.orb.ORB orb ) + throws org.omg.CORBA.INITIALIZE + { + // Default constructor uses "NameService" as the key for the Root Naming + // Context. If default constructor is used then INS's object key for + // Transient Name Service is "NameService" + initialize( orb, "NameService" ); + } + + /** + * Constructs a new TransientNameService, and creates an initial + * NamingContext, whose object + * reference can be obtained by the initialNamingContext method. + * @param orb The ORB object + * @param nameserviceName Stringified key used for INS Service registry + * @exception org.omg.CORBA.INITIALIZE Thrown if + * the TransientNameService cannot initialize. + */ + public TransientNameService(com.sun.corba.ee.spi.orb.ORB orb, + String serviceName ) throws org.omg.CORBA.INITIALIZE + { + // This constructor gives the flexibility of providing the Object Key + // for the Root Naming Context that is registered with INS. + initialize( orb, serviceName ); + } + + + /** + * This method initializes Transient Name Service by associating Root + * context with POA and registering the root context with INS Object Keymap. + */ + @Naming + private void initialize( com.sun.corba.ee.spi.orb.ORB orb, + String nameServiceName ) + throws org.omg.CORBA.INITIALIZE + { + try { + POA rootPOA = (POA) orb.resolve_initial_references( + ORBConstants.ROOT_POA_NAME ); + rootPOA.the_POAManager().activate(); + + int i = 0; + Policy[] poaPolicy = new Policy[3]; + poaPolicy[i++] = rootPOA.create_lifespan_policy( + LifespanPolicyValue.TRANSIENT); + poaPolicy[i++] = rootPOA.create_id_assignment_policy( + IdAssignmentPolicyValue.SYSTEM_ID); + poaPolicy[i++] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.RETAIN); + + POA nsPOA = rootPOA.create_POA( "TNameService", null, poaPolicy ); + ObjectAdapter.class.cast( nsPOA ).setNameService(true); + nsPOA.the_POAManager().activate(); + + // Create an initial context + TransientNamingContext initialContext = + new TransientNamingContext(orb, null, nsPOA); + byte[] rootContextId = nsPOA.activate_object( initialContext ); + initialContext.localRoot = + nsPOA.id_to_reference( rootContextId ); + theInitialNamingContext = initialContext.localRoot; + orb.register_initial_reference( nameServiceName, + theInitialNamingContext ); + } catch (org.omg.CORBA.SystemException e) { + throw wrapper.transNsCannotCreateInitialNcSys( e ) ; + } catch (Exception e) { + throw wrapper.transNsCannotCreateInitialNc( e ) ; + } + } + + + /** + * Return the initial NamingContext. + * @return the object reference for the initial NamingContext. + */ + public org.omg.CORBA.Object initialNamingContext() + { + return theInitialNamingContext; + } + + + // The initial naming context for this name service + private org.omg.CORBA.Object theInitialNamingContext; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientNamingContext.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientNamingContext.java new file mode 100644 index 000000000..2432c840d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/cosnaming/TransientNamingContext.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.cosnaming; + +// Import general CORBA classes +import org.omg.PortableServer.POA; + +// Import org.omg.CosNaming types +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.BindingTypeHolder; +import org.omg.CosNaming.BindingListHolder; +import org.omg.CosNaming.BindingIteratorHolder; +import org.omg.CosNaming.NameComponent; + +import java.util.Map; +import java.util.HashMap; + +import com.sun.corba.ee.spi.logging.NamingSystemException; +import com.sun.corba.ee.spi.trace.Naming; + + +/** + * Class TransientNamingContext implements the methods defined + * by NamingContextDataStore, and extends the NamingContextImpl class to + * provide a servant implementation of CosNaming::NamingContext. + * The TransientNamingContext uses a hash table + * to store the mappings between bindings and object references and the + * hash table is not persistent; thereby the name "transient". + * This class should not be used directly; instead, the class + * TransientNameService should be instantiated. + *

    + * The keys in the hash table are InternalBindingKey objects, containing + * a single NameComponent and implementing the proper functions, i.e., + * equals() and hashCode() in an efficient manner. The values in the hash + * table are InternalBindingValues and store a org.omg.CosNaming::Binding and + * the object reference associated with the binding. For iteration, + * TransientBindingIterator objects are created, which are passed a cloned + * copy of the hashtable. Since elements are inserted and deleted and + * never modified, this provides stable iterators at the cost of cloning + * the hash table. + *

    + * To create and destroy object references, the TransientNamingContext + * uses the orb.connect() and orb.disconnect() methods. + * + * @see NamingContextImpl + * @see NamingContextDataStore + * @see TransientBindingIterator + * @see TransientNameService + */ +@Naming +public class TransientNamingContext extends NamingContextImpl implements NamingContextDataStore +{ + private NamingSystemException wrapper ; + + /** + * Constructs a new TransientNamingContext object. + * @param orb an orb object. + * @param initial the initial naming context. + * @exception Exception a Java exception thrown of the base class cannot + * initialize. + */ + public TransientNamingContext(com.sun.corba.ee.spi.orb.ORB orb, + org.omg.CORBA.Object initial, + POA nsPOA ) + throws java.lang.Exception + { + super(orb, nsPOA); + this.localRoot = initial; + } + + /** + * Binds the object to the name component as the specified binding type. + * It creates a InternalBindingKey object and a InternalBindingValue + * object and inserts them in the hash table. + * @param n A single org.omg.CosNaming::NameComponent under which the + * object will be bound. + * @param obj An object reference to be bound under the supplied name. + * @param bt The type of the binding (i.e., as object or as context). + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public final void bindImpl(NameComponent n, org.omg.CORBA.Object obj, + BindingType bt) + throws org.omg.CORBA.SystemException + { + InternalBindingKey key = new InternalBindingKey(n); + NameComponent[] name = new NameComponent[1]; + name[0] = n; + Binding b = new Binding(name,bt); + InternalBindingValue value = new InternalBindingValue(b,null); + value.theObjectRef = obj; + InternalBindingValue oldValue = bindingMap.put(key,value); + + if (oldValue != null) { + throw wrapper.transNcBindAlreadyBound() ; + } + } + + /** + * Resolves the supplied name to an object reference and returns + * the type of the resolved binding. It creates a InternalBindingKey + * and uses the key for looking up in the hash table. If nothing + * is found an exception is thrown, otherwise the object reference + * is returned and the binding type set. + * @param n a NameComponent which is the name to be resolved. + * @param bth the BindingType as an out parameter. + * @return the object reference bound under the supplied name, null if not + * found. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public final org.omg.CORBA.Object resolveImpl(NameComponent n, + BindingTypeHolder bth) + throws org.omg.CORBA.SystemException + { + if ((n.id.length() == 0) && (n.kind.length() == 0)) { + bth.value = BindingType.ncontext; + return localRoot; + } + + // Create a key and lookup the value + InternalBindingKey key = new InternalBindingKey(n); + InternalBindingValue value = bindingMap.get(key); + if (value == null) { + return null; + } + + // Copy out binding type and object reference + bth.value = value.theBinding.binding_type; + return value.theObjectRef; + } + + /** + * Deletes the binding with the supplied name. It creates a + * InternalBindingKey and uses it to remove the value associated + * with the key. If nothing is found an exception is thrown, otherwise + * the element is removed from the hash table. + * @param n a NameComponent which is the name to unbind + * @return the object reference bound to the name, or null if not found. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public final org.omg.CORBA.Object unbindImpl(NameComponent n) + throws org.omg.CORBA.SystemException + { + // Create a key and remove it from the hashtable + InternalBindingKey key = new InternalBindingKey(n); + InternalBindingValue value = bindingMap.remove(key); + + // Return what was found + if (value == null) { + return null; + } else { + return value.theObjectRef; + } + } + + /** + * List the contents of this NamingContext. It creates a new + * TransientBindingIterator object and passes it a clone of the + * hash table and an orb object. It then uses the + * newly created object to return the required number of bindings. + * @param how_many The number of requested bindings in the BindingList. + * @param bl The BindingList as an out parameter. + * @param bi The BindingIterator as an out parameter. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public final void listImpl(int how_many, BindingListHolder bl, + BindingIteratorHolder bi) + throws org.omg.CORBA.SystemException + { + try { + // Create a new binding iterator servant with a copy of this + // hashtable. nsPOA is passed to the object so that it can + // de-activate itself from the Active Object Map when + // Binding Iterator.destroy is called. + Map copy = + new HashMap( bindingMap ) ; + TransientBindingIterator bindingIterator = + new TransientBindingIterator( this.orb, copy, nsPOA); + + // Have it set the binding list + bindingIterator.list(how_many,bl); + + byte[] objectId = nsPOA.activate_object( bindingIterator ); + org.omg.CORBA.Object obj = nsPOA.id_to_reference( objectId ); + + // Get the object reference for the binding iterator servant + org.omg.CosNaming.BindingIterator bindingRef = + org.omg.CosNaming.BindingIteratorHelper.narrow( obj ); + + bi.value = bindingRef; + } catch (org.omg.CORBA.SystemException e) { + throw e; + } catch (Exception e) { + // Convert to a CORBA system exception + throw wrapper.transNcListGotExc( e ) ; + } + } + + /** + * Create a new NamingContext. It creates a new TransientNamingContext + * object, passing it the orb object. + * @return an object reference for a new NamingContext object implemented + * by this Name Server. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public final org.omg.CosNaming.NamingContext newContextImpl() + throws org.omg.CORBA.SystemException + { + try { + // Create a new servant + TransientNamingContext transContext = + new TransientNamingContext( + (com.sun.corba.ee.spi.orb.ORB) orb,localRoot, nsPOA); + + byte[] objectId = nsPOA.activate_object( transContext ); + org.omg.CORBA.Object obj = nsPOA.id_to_reference( objectId ); + return org.omg.CosNaming.NamingContextHelper.narrow( obj ); + } catch (Exception e) { + throw wrapper.transNcNewctxGotExc( e ) ; + } + } + + /** + * Destroys this NamingContext by disconnecting from the ORB. + * @exception org.omg.CORBA.SystemException One of a fixed set of CORBA + * system exceptions. + */ + @Naming + public final void destroyImpl() + throws org.omg.CORBA.SystemException + { + // Destroy the object reference by disconnecting from the ORB + try { + byte[] objectId = nsPOA.servant_to_id( this ); + if( objectId != null ) { + nsPOA.deactivate_object( objectId ); + } + } catch (Exception e) { + throw wrapper.transNcDestroyGotExc( e ) ; + } + } + + /** + * A Utility Method For Logging.. + */ + private String getName( NameComponent n ) { + return n.id + "." + n.kind; + } + + /** + * Return whether this NamingContext contains any bindings. It forwards + * this request to the hash table. + * @return true if this NamingContext contains no bindings. + */ + public final boolean isEmptyImpl() { + return bindingMap.isEmpty(); + } + + // A hashtable to store the bindings + private final Map bindingMap = + new HashMap(); + + /** + * The local root naming context. + */ + public org.omg.CORBA.Object localRoot; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/CorbalocURL.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/CorbalocURL.java new file mode 100644 index 000000000..bb471f475 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/CorbalocURL.java @@ -0,0 +1,256 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +import java.util.*; + +/** + * The corbaloc: URL definitions from the -ORBInitDef and -ORBDefaultInitDef's + * will be parsed and converted to this object. This object is capable of + * storing multiple Host profiles as defined in the CorbaLoc grammer. + * + * @author Hemanth + */ +public class CorbalocURL extends INSURLBase +{ + /** + * This constructor parses the URL and initializes all the variables. Once + * the URL Object is constructed it is immutable. URL parameter is a + * corbaloc: URL string with 'corbaloc:' prefix stripped. + */ + public CorbalocURL( String aURL ) { + String url = aURL; + + if( url != null ) { + try { + // First Clean the URL Escapes if there are any + url = Utility.cleanEscapes( url ); + } catch( Exception e ) { + // There is something wrong with the URL escapes used + // so throw an exception + badAddress( e, aURL ); + } + int endIndex = url.indexOf( '/' ); + if( endIndex == -1 ) { + // If there is no '/' then the endIndex is at the end of the URL + endIndex = url.length(); + } + // _REVISIT_: Add a testcase to check 'corbaloc:/' + if( endIndex == 0 ) { + // The url starts with a '/', it's an error + badAddress( aURL ); + } + // Anything between corbaloc: and / is the host,port information + // of the server where the Service Object is located + StringTokenizer endpoints = new StringTokenizer( + url.substring( 0, endIndex ), "," ); + // NOTE: + // There should be atleast one token, because there are checks + // to make sure that there is host information before the + // delimiter '/'. So no need to explicitly check for number of + // tokens != 0 + while( endpoints.hasMoreTokens( ) ) { + String endpointInfo = endpoints.nextToken(); + IIOPEndpointInfo iiopEndpointInfo = null; + if( endpointInfo.startsWith( "iiop:" ) ) { + iiopEndpointInfo = handleIIOPColon( endpointInfo ); + } else if( endpointInfo.startsWith( "rir:" ) ) { + handleRIRColon( endpointInfo ); + rirFlag = true; + } else if( endpointInfo.startsWith( ":" ) ) { + iiopEndpointInfo = handleColon( endpointInfo ); + } else { + // Right now we are not allowing any other protocol + // other than iiop:, rir: so raise exception indicating + // that the URL is malformed + badAddress( aURL ); + } + if ( rirFlag == false ) { + // Add the Host information if RIR flag is set, + // If RIR is set then it means use the internal Boot + // Strap protocol for Key String resolution + if( theEndpointInfo == null ) { + theEndpointInfo = new java.util.ArrayList( ); + } + theEndpointInfo.add( iiopEndpointInfo ); + } + } + // If there is something after corbaloc:endpointInfo/ + // then that is the keyString + if( url.length() > (endIndex + 1) ) { + theKeyString = url.substring( endIndex + 1 ); + } + } + } + + /** + * If there is 'iiop:' token in the URL, this method will parses + * and validates that host and port information. + */ + private IIOPEndpointInfo handleIIOPColon( String iiopInfo ) + { + // Check the iiop syntax + iiopInfo = iiopInfo.substring( NamingConstants.IIOP_LENGTH ); + return handleColon( iiopInfo ); + } + + /** + * This is to handle the case of host information with no 'iiop:' prefix. + * instead if ':' is specified then iiop is assumed. + */ + private IIOPEndpointInfo handleColon( String iiopInfo ) { + // String after ":" + iiopInfo = iiopInfo.substring( 1 ); + String hostandport = iiopInfo; + // The format can be 1.2@: + StringTokenizer tokenizer = new StringTokenizer( iiopInfo, "@" ); + IIOPEndpointInfo iiopEndpointInfo = new IIOPEndpointInfo( ); + int tokenCount = tokenizer.countTokens( ); + // There can be 1 or 2 tokens with '@' as the delimiter + // - if there is only 1 token then there is no GIOP version + // information. A Default GIOP version of 1.2 is used. + // - if there are 2 tokens then there is GIOP version is specified + // - if there are no tokens or more than 2 tokens, then that's an + // error + if( ( tokenCount == 0 ) + ||( tokenCount > 2 )) + { + badAddress( iiopInfo ); + } + if( tokenCount == 2 ) { + // There is VersionInformation after iiop: + String version = tokenizer.nextToken( ); + int dot = version.indexOf('.'); + // There is a version without ., which means + // Malformed list + if (dot == -1) { + badAddress( iiopInfo ); + } + try { + iiopEndpointInfo.setVersion( + Integer.parseInt( version.substring( 0, dot )), + Integer.parseInt( version.substring(dot+1)) ); + hostandport = tokenizer.nextToken( ); + } catch( Throwable e ) { + badAddress( e, iiopInfo ); + } + } + try { + // A Hack to differentiate IPV6 address + // from IPV4 address, Current Resolution + // is to use [ ] to differentiate ipv6 host + int squareBracketBeginIndex = hostandport.indexOf ( '[' ); + if( squareBracketBeginIndex != -1 ) { + // ipv6Host should be enclosed in + // [ ], if not it will result in a + // BAD_PARAM exception + String ipv6Port = getIPV6Port( hostandport ); + if( ipv6Port != null ) { + iiopEndpointInfo.setPort( Integer.parseInt( ipv6Port )); + } + iiopEndpointInfo.setHost( getIPV6Host( hostandport )); + return iiopEndpointInfo; + } + tokenizer = new StringTokenizer( hostandport, ":" ); + // There are three possible cases here + // 1. Host and Port is explicitly specified by using ":" as a + // a separator + // 2. Only Host is specified without the port + // 3. HostAndPort info is null + if( tokenizer.countTokens( ) == 2 ) { + // Case 1: There is Host and Port Info + iiopEndpointInfo.setHost( tokenizer.nextToken( ) ); + iiopEndpointInfo.setPort( Integer.parseInt( + tokenizer.nextToken( ))); + } else { + if( ( hostandport != null ) + &&( hostandport.length() != 0 ) ) + { + // Case 2: Only Host is specified. iiopEndpointInfo is + // initialized to use the default INS port, if no port is + // specified + iiopEndpointInfo.setHost( hostandport ); + } + // Case 3: If no Host and Port info is provided then we use the + // the default LocalHost and INSPort. iiopEndpointInfo is + // already initialized with this info. + } + } catch( Throwable e ) { + // Any kind of Exception is bad here. + // Possible causes: A Number Format exception because port info is + // malformed + badAddress( e, iiopInfo ); + } + Utility.validateGIOPVersion( iiopEndpointInfo ); + return iiopEndpointInfo; + } + + /** + * Validate 'rir:' case. + */ + private void handleRIRColon( String rirInfo ) + { + if( rirInfo.length() != NamingConstants.RIRCOLON_LENGTH ) { + badAddress( rirInfo ); + } + } + + /** + * Returns an IPV6 Port that is after []:. There is no validation + * done here, if it is an incorrect port then the request through + * this URL results in a COMM_FAILURE, otherwise malformed list will + * result in BAD_PARAM exception thrown in checkcorbalocGrammer. + */ + private String getIPV6Port( String endpointInfo ) + { + int squareBracketEndIndex = endpointInfo.indexOf ( ']' ); + // If there is port information, then it has to be after ] bracket + // indexOf returns the count from the index of zero as the base, so + // equality check requires squareBracketEndIndex + 1. + if( (squareBracketEndIndex + 1) != (endpointInfo.length( )) ) { + if( endpointInfo.charAt( squareBracketEndIndex + 1 ) != ':' ) { + throw new RuntimeException( + "Host and Port is not separated by ':'" ); + } + // PortInformation should be after ']:' delimiter + // If there is an exception then it will be caught in + // checkcorbaGrammer method and rethrown as BAD_PARAM + return endpointInfo.substring( squareBracketEndIndex + 2 ); + } + return null; + } + + + /** + * Returns an IPV6 Host that is inside [ ] tokens. There is no validation + * done here, if it is an incorrect IPV6 address then the request through + * this URL results in a COMM_FAILURE, otherwise malformed list will + * result in BAD_PARAM exception thrown in checkcorbalocGrammer. + */ + private String getIPV6Host( String endpointInfo ) { + // ipv6Host should be enclosed in + // [ ], if not it will result in a + // BAD_PARAM exception + int squareBracketEndIndex = endpointInfo.indexOf ( ']' ); + // get the host between [ ] + String ipv6Host = endpointInfo.substring( 1, squareBracketEndIndex ); + return ipv6Host; + } + + /** + * Will be true only in CorbanameURL class. + */ + public boolean isCorbanameURL( ) { + return false; + } + + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/CorbanameURL.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/CorbanameURL.java new file mode 100644 index 000000000..e8bb04f5e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/CorbanameURL.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +/** + * The corbaname: URL definitions from the -ORBInitDef and -ORBDefaultInitDef's + * will be stored in this object. This object is capable of storing CorbaLoc + * profiles as defined in the CorbaName grammer. + * + * @Author Hemanth + */ +public class CorbanameURL extends INSURLBase +{ + /** + * This constructor takes a corbaname: url with 'corbaname:' prefix stripped + * and initializes all the variables accordingly. If there are any parsing + * errors then BAD_PARAM exception is raised. + */ + public CorbanameURL( String aURL ) { + String url = aURL; + + // First Clean the URL Escapes if there are any + try { + url = Utility.cleanEscapes( url ); + } catch( Exception e ) { + badAddress( e, aURL ); + } + + int delimiterIndex = url.indexOf( '#' ); + String corbalocString = null; + if( delimiterIndex != -1 ) { + corbalocString = "corbaloc:" + url.substring( 0, delimiterIndex ) ; + } else { + corbalocString = "corbaloc:" + url ; + } + + try { + // Check the corbaloc grammar and set the returned corbaloc + // object to the CorbaName Object + INSURL insURL = + INSURLHandler.getINSURLHandler().parseURL( corbalocString ); + copyINSURL( insURL ); + // String after '#' is the Stringified name used to resolve + // the Object reference from the rootnaming context. If + // the String is null then the Root Naming context is passed + // back + if((delimiterIndex > -1) && + (delimiterIndex < (aURL.length() - 1))) + { + int start = delimiterIndex + 1 ; + String result = url.substring(start) ; + theStringifiedName = result ; + } + } catch( Exception e ) { + badAddress( e, aURL ); + } + } + + /** + * A Utility method to copy all the variables from CorbalocURL object to + * this instance. + */ + private void copyINSURL( INSURL url ) { + rirFlag = url.getRIRFlag( ); + theEndpointInfo = (java.util.ArrayList) url.getEndpointInfo( ); + theKeyString = url.getKeyString( ); + theStringifiedName = url.getStringifiedName( ); + } + + public boolean isCorbanameURL( ) { + return true; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/IIOPEndpointInfo.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/IIOPEndpointInfo.java new file mode 100644 index 000000000..bbf85b798 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/IIOPEndpointInfo.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * EndpointInfo is used internally by CorbaLoc object to store the + * host information used in creating the Service Object reference + * from the -ORBInitDef and -ORBDefaultInitDef definitions. + * + * @Author Hemanth + */ +public class IIOPEndpointInfo +{ + // Version information + private int major, minor; + + // Host Name and Port Number + private String host; + private int port; + + public String toString() { + return "IIOPEndpointInfo[" + major + "." + minor + + " " + host + ":" + port + "]" ; + } + + IIOPEndpointInfo( ) { + // Default IIOP Version + major = ORBConstants.DEFAULT_INS_GIOP_MAJOR_VERSION; + minor = ORBConstants.DEFAULT_INS_GIOP_MINOR_VERSION; + // Default host is localhost + host = ORBConstants.DEFAULT_INS_HOST; + // Default INS Port + port = ORBConstants.DEFAULT_INS_PORT; + } + + public void setHost( String theHost ) { + host = theHost; + } + + public String getHost( ) { + return host; + } + + public void setPort( int thePort ) { + port = thePort; + } + + public int getPort( ) { + return port; + } + + public void setVersion( int theMajor, int theMinor ) { + major = theMajor; + minor = theMinor; + } + + public int getMajor( ) { + return major; + } + + public int getMinor( ) { + return minor; + } + + /** Internal Debug Method. + */ + public void dump( ) { + System.out.println( " Major -> " + major + " Minor -> " + minor ); + System.out.println( "host -> " + host ); + System.out.println( "port -> " + port ); + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURL.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURL.java new file mode 100644 index 000000000..34eb7a122 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURL.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +/** + * INS URL is a generic interface for two different types of URL's specified + * in INS spec. + * + * @Author Hemanth + */ +public interface INSURL { + public boolean getRIRFlag( ); + + // There can be one or more Endpoint's in the URL, so the return value is + // a List + public java.util.List getEndpointInfo( ); + + public String getKeyString( ); + + public String getStringifiedName( ); + + // This method will return true only in CorbanameURL, It is provided because + // corbaname: URL needs special handling. + public boolean isCorbanameURL( ); + + // A debug method, which is not required for normal operation + public void dPrint( ); +} + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURLBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURLBase.java new file mode 100644 index 000000000..d123929a3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURLBase.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +import com.sun.corba.ee.spi.logging.OMGSystemException ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** The corbaloc: URL definitions from the -ORBInitDef and -ORBDefaultInitDef's + * will be stored in this object. This object is capable of storing multiple + * Host profiles as defined in the CorbaLoc grammer. + * + * @author Hemanth + */ +public abstract class INSURLBase implements INSURL { + private static OMGSystemException wrapper = + OMGSystemException.self ; + + // If rirFlag is set to true that means internal + // boot strapping technique will be used. If set to + // false then the EndpointInfo will be used to create the + // Service Object reference. + protected boolean rirFlag = false ; + protected java.util.ArrayList theEndpointInfo = null ; + protected String theKeyString = "NameService" ; + protected String theStringifiedName = null ; + + /** + * A Utility method to throw BAD_PARAM exception to signal malformed + * INS URL. + */ + protected void badAddress( String name ) + { + throw wrapper.soBadAddress( name ) ; + } + + protected void badAddress( java.lang.Throwable e, String name ) + { + throw wrapper.soBadAddress( e, name ) ; + } + + public boolean getRIRFlag( ) { + return rirFlag; + } + + public java.util.List getEndpointInfo( ) { + return theEndpointInfo; + } + + public String getKeyString( ) { + return theKeyString; + } + + public String getStringifiedName( ) { + return theStringifiedName; + } + + public abstract boolean isCorbanameURL( ); + + public void dPrint( ) { + System.out.println( "URL Dump..." ); + System.out.println( "Key String = " + getKeyString( ) ); + System.out.println( "RIR Flag = " + getRIRFlag( ) ); + System.out.println( "isCorbanameURL = " + isCorbanameURL() ); + for( int i = 0; i < theEndpointInfo.size( ); i++ ) { + ((IIOPEndpointInfo) theEndpointInfo.get( i )).dump( ); + } + if( isCorbanameURL( ) ) { + System.out.println( "Stringified Name = " + getStringifiedName() ); + } + } + +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURLHandler.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURLHandler.java new file mode 100644 index 000000000..51a58d9e6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/INSURLHandler.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +import org.omg.CORBA.CompletionStatus; +import java.util.StringTokenizer; + +/** + * This class is the entry point to parse different types of INS URL's. + * + * @Author Hemanth + */ + +public class INSURLHandler { + + private static INSURLHandler insURLHandler = null; + + // Length of corbaloc: + private static final int CORBALOC_PREFIX_LENGTH = 9; + + // Length of corbaname: + private static final int CORBANAME_PREFIX_LENGTH = 10; + + private INSURLHandler( ) { + } + + public synchronized static INSURLHandler getINSURLHandler( ) { + if( insURLHandler == null ) { + insURLHandler = new INSURLHandler( ); + } + return insURLHandler; + } + + public INSURL parseURL( String aUrl ) { + String url = aUrl; + if ( url.startsWith( "corbaloc:" ) == true ) { + return new CorbalocURL( url.substring( CORBALOC_PREFIX_LENGTH ) ); + } else if ( url.startsWith ( "corbaname:" ) == true ) { + return new CorbanameURL( url.substring( CORBANAME_PREFIX_LENGTH ) ); + } + return null; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/NamingConstants.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/NamingConstants.java new file mode 100644 index 000000000..e3dc657a5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/NamingConstants.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +/** + * Constants specific to INS parsing and validation. + */ +public class NamingConstants { + + // iiop length + public static final int IIOP_LENGTH = 4; + + // rir: length + public static final int RIRCOLON_LENGTH = 4; + + public static final int MAJORNUMBER_SUPPORTED = 1; + + public static final int MINORNUMBERMAX = 2; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/Utility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/Utility.java new file mode 100644 index 000000000..bd97d3179 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/naming/namingutil/Utility.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.naming.namingutil; + +import java.io.StringWriter; + +import org.omg.CORBA.DATA_CONVERSION; + +import com.sun.corba.ee.spi.logging.NamingSystemException; + +/** + * Utility methods for Naming. + * + * @Author Hemanth + */ +class Utility { + private static NamingSystemException wrapper = + NamingSystemException.self ; + + /** + * cleanEscapes removes URL escapes as per IETF 2386 RFP. + */ + static String cleanEscapes( String stringToDecode ) { + StringWriter theStringWithoutEscape = new StringWriter(); + for( int i = 0; i < stringToDecode.length(); i++ ) { + char c = stringToDecode.charAt( i ) ; + if( c != '%' ) { + theStringWithoutEscape.write( c ); + } else { + // Get the two hexadecimal digits and convert that into int + i++; + int Hex1 = hexOf( stringToDecode.charAt(i) ); + i++; + int Hex2 = hexOf( stringToDecode.charAt(i) ); + int value = (Hex1 * 16) + Hex2; + // Convert the integer to ASCII + theStringWithoutEscape.write( (char) value ); + } + } + return theStringWithoutEscape.toString(); + } + + /** + * Converts an Ascii Character into Hexadecimal digit + * NOTE: THIS METHOD IS DUPLICATED TO DELIVER NAMING AS A SEPARATE + * COMPONENT TO RI. + **/ + static int hexOf( char x ) + { + int val; + + val = x - '0'; + if (val >=0 && val <= 9) { + return val; + } + + val = (x - 'a') + 10; + if (val >= 10 && val <= 15) { + return val; + } + + val = (x - 'A') + 10; + if (val >= 10 && val <= 15) { + return val; + } + + throw new DATA_CONVERSION( ); + } + + /** + * If GIOP Version is not correct, This method throws a BAD_PARAM + * Exception. + **/ + static void validateGIOPVersion( IIOPEndpointInfo endpointInfo ) { + if ((endpointInfo.getMajor() > NamingConstants.MAJORNUMBER_SUPPORTED) || + (endpointInfo.getMinor() > NamingConstants.MINORNUMBERMAX ) ) + { + throw wrapper.insBadAddress() ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/NullServantImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/NullServantImpl.java new file mode 100644 index 000000000..501805928 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/NullServantImpl.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa ; + +import org.omg.CORBA.SystemException ; + +import com.sun.corba.ee.spi.oa.NullServant ; + +public class NullServantImpl implements NullServant +{ + private SystemException sysex ; + + public NullServantImpl( SystemException ex ) + { + this.sysex = ex ; + } + + public SystemException getException() + { + return sysex ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/AOMEntry.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/AOMEntry.java new file mode 100644 index 000000000..b01f846a0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/AOMEntry.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import org.glassfish.pfl.basic.fsm.StateEngine; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.glassfish.pfl.basic.fsm.Guard; +import org.glassfish.pfl.basic.fsm.Action; +import org.glassfish.pfl.basic.fsm.Input; +import org.glassfish.pfl.basic.fsm.FSM; +import org.glassfish.pfl.basic.fsm.State; +import org.glassfish.pfl.basic.fsm.Runner; +import org.glassfish.pfl.basic.fsm.FSMImpl; +import java.util.concurrent.locks.Condition ; + +import com.sun.corba.ee.spi.trace.PoaFSM; +import com.sun.corba.ee.spi.logging.POASystemException ; + +import org.omg.PortableServer.POAPackage.ObjectAlreadyActive ; + +import static org.glassfish.pfl.basic.fsm.Guard.Base.* ; + +/** AOMEntry represents a Servant or potential Servant in the ActiveObjectMap. +* It may be in several states to allow for long incarnate or etherealize +* operations. The methods on this class mostly represent input symbols to +* the state machine that controls the lifecycle of the entry. A library is +* used to build the state machine rather than the more usual state pattern +* so that the state machine transitions are explicitly visible. +*/ +@PoaFSM +public class AOMEntry extends FSMImpl { + private static final POASystemException wrapper = + POASystemException.self ; + + private Runner runner ; + private final Thread[] etherealizer ; // The actual etherealize operation + // for this entry. It is + // represented as a Thread because + // the POA.deactivate_object never + // waits for the completion. + private final int[] counter ; // single element holder for counter + // accessed in actions + private final Condition wait ; // accessed in actions + + final POAImpl poa ; + + public static final State INVALID = new State( "Invalid", + State.Kind.INITIAL ) ; + + public static final State INCARN = new State( "Incarnating" ) { + @Override + public void postAction( FSM fsm ) { + AOMEntry entry = (AOMEntry)fsm ; + entry.wait.signalAll() ; + } + }; + + public static final State VALID = new State( "Valid" ) ; + + public static final State ETHP = new State( "EtherealizePending" ) ; + + public static final State ETH = new State( "Etherealizing" ) { + @Override + public FSM preAction( FSM fsm ) { + AOMEntry entry = (AOMEntry)fsm ; + Thread etherealizer = entry.etherealizer[0] ; + if (etherealizer != null) { + etherealizer.start(); + } + return null ; + } + + @Override + public void postAction( FSM fsm ) { + AOMEntry entry = (AOMEntry)fsm ; + entry.wait.signalAll() ; + } + }; + + public static final State DESTROYED = new State( "Destroyed" ) ; + + static final Input START_ETH = new Input.Base( "startEtherealize" ) ; + static final Input ETH_DONE = new Input.Base( "etherealizeDone" ) ; + static final Input INC_DONE = new Input.Base( "incarnateDone" ) ; + static final Input INC_FAIL = new Input.Base( "incarnateFailure" ) ; + static final Input ACTIVATE = new Input.Base( "activateObject" ) ; + static final Input ENTER = new Input.Base( "enter" ) ; + static final Input EXIT = new Input.Base( "exit" ) ; + + private static final Action incrementAction = + new Action.Base( "increment" ) { + public void doIt( FSM fsm, Input in ) { + AOMEntry entry = (AOMEntry)fsm ; + entry.counter[0]++ ; + } + } ; + + private static final Action decrementAction = + new Action.Base( "decrement" ) { + public void doIt( FSM fsm, Input in ) { + AOMEntry entry = (AOMEntry)fsm ; + if (entry.counter[0] > 0) { + entry.counter[0]--; + } else { + throw wrapper.aomEntryDecZero(); + } + } + } ; + + private static final Action throwIllegalStateExceptionAction = + new Action.Base( "throwIllegalStateException" ) { + public void doIt( FSM fsm, Input in ) { + throw new IllegalStateException( + "No transitions allowed from the DESTROYED state" ) ; + } + } ; + + private static final Action oaaAction = + new Action.Base( "throwObjectAlreadyActive" ) { + public void doIt( FSM fsm, Input in ) { + throw new RuntimeException( new ObjectAlreadyActive() ) ; + } + } ; + + private static final Guard waitGuard = new Guard.Base( "wait" ) { + public Guard.Result evaluate( FSM fsm, Input in ) { + AOMEntry entry = (AOMEntry)fsm ; + try { + entry.wait.await() ; + } catch (InterruptedException exc) { + wrapper.waitGuardInterrupted() ; + } + + return Guard.Result.DEFERRED ; + } + } ; + + private static final IntFunc counterFunc = + new Guard.Base.IntFunc( "counterFunc" ) { + public Integer evaluate( FSM fsm, Input in ) { + AOMEntry entry = (AOMEntry)fsm ; + return entry.counter[0] ; + } + } ; + + private static final IntFunc one = constant( 1 ) ; + private static final IntFunc zero = constant( 0 ) ; + + private static final Guard greaterZeroGuard = + makeGuard( gt( counterFunc, zero ) ) ; + private static final Guard zeroGuard = + makeGuard( eq( counterFunc, zero ) ) ; + private static final Guard greaterOneGuard = + makeGuard( gt( counterFunc, one ) ) ; + private static final Guard oneGuard = + makeGuard( eq( counterFunc, one ) ) ; + + private static final StateEngine engine = StateEngine.create() ; + + static { + // State, Input, Guard, Action, new State + + engine.add( INVALID, ENTER, incrementAction, INCARN ) ; + engine.add( INVALID, ACTIVATE, null, VALID ) ; + engine.setDefault( INVALID ) ; + + engine.add( INCARN, ENTER, waitGuard, null, INCARN ) ; + engine.add( INCARN, EXIT, null, INCARN ) ; + engine.add( INCARN, START_ETH, waitGuard, null, INCARN ) ; + engine.add( INCARN, INC_DONE, null, VALID ) ; + engine.add( INCARN, INC_FAIL, decrementAction, INVALID ) ; + engine.add( INCARN, ACTIVATE, oaaAction, INCARN ) ; + + engine.add( VALID, ENTER, incrementAction, VALID ) ; + engine.add( VALID, EXIT, decrementAction, VALID ) ; + engine.add( VALID, START_ETH, greaterZeroGuard, null, ETHP ) ; + engine.add( VALID, START_ETH, zeroGuard, null, ETH ) ; + engine.add( VALID, ACTIVATE, oaaAction, VALID ) ; + + engine.add( ETHP, ENTER, waitGuard, null, ETHP ) ; + engine.add( ETHP, START_ETH, null, ETHP ) ; + engine.add( ETHP, EXIT, greaterOneGuard, decrementAction, ETHP ) ; + engine.add( ETHP, EXIT, oneGuard, decrementAction, ETH ) ; + engine.add( ETHP, ACTIVATE, oaaAction, ETHP ) ; + + engine.add( ETH, START_ETH, null, ETH ) ; + engine.add( ETH, ETH_DONE, null, DESTROYED ) ; + engine.add( ETH, ENTER, waitGuard, null, ETH ) ; + engine.add( ETH, ACTIVATE, oaaAction, ETH ) ; + + engine.setDefault( DESTROYED, throwIllegalStateExceptionAction, DESTROYED ) ; + + engine.done() ; + } + + public AOMEntry( POAImpl poa ) + { + super( engine, INVALID ) ; + runner = new Runner( this ) ; + this.poa = poa ; + etherealizer = new Thread[1] ; + etherealizer[0] = null ; + counter = new int[1] ; + counter[0] = 0 ; + wait = poa.makeCondition() ; + } + + @InfoMethod + private void state( State state ) { } + + @PoaFSM + @Override + public void setState( State state ) { + super.setState( state ) ; + state( getState() ) ; + } + + // Methods that drive the FSM: the real interface to this class + // Most just call the doIt method, but startEtherealize needs + // the etherealizer. + public void startEtherealize( Thread etherealizer ) + { + this.etherealizer[0] = etherealizer ; + runner.doIt( START_ETH ) ; + } + + public void etherealizeComplete() { runner.doIt( ETH_DONE ) ; } + public void incarnateComplete() { runner.doIt( INC_DONE ) ; } + public void incarnateFailure() { runner.doIt( INC_FAIL ) ; } + public void enter() { runner.doIt( ENTER ) ; } + public void exit() { runner.doIt( EXIT ) ; } + + public void activateObject() throws ObjectAlreadyActive { + try { + runner.doIt( ACTIVATE ) ; + } catch (RuntimeException exc) { + Throwable thr = exc.getCause() ; + if (thr instanceof ObjectAlreadyActive) { + throw (ObjectAlreadyActive) thr; + } else { + throw exc; + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ActiveObjectMap.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ActiveObjectMap.java new file mode 100644 index 000000000..9a38a908d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ActiveObjectMap.java @@ -0,0 +1,273 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import java.util.Set ; +import java.util.HashSet ; +import java.util.Map ; +import java.util.HashMap ; + +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; + +/** The ActiveObjectMap maintains associations between servants and + * their keys. There are two variants, to support whether or not + * multiple IDs per servant are allowed. This class supports bidirectional + * traversal of the key-servant association. Access to an instance of this + * class is serialized by the POA mutex. + */ +public abstract class ActiveObjectMap +{ + static class Key { + private byte[] id; + + byte[] id() { + return id ; + } + + Key(byte[] id) { + this.id = id; + } + + @Override + public String toString() { + StringBuilder buffer = new StringBuilder(); + for(int i = 0; i < id.length; i++) { + buffer.append(Integer.toString((int) id[i], 16)); + if (i != id.length-1) { + buffer.append(":"); + } + } + return buffer.toString(); + } + + @Override + public boolean equals(java.lang.Object key) { + if (!(key instanceof Key)) { + return false; + } + Key k = (Key) key; + if (k.id.length != this.id.length) { + return false; + } + for(int i = 0; i < this.id.length; i++) { + if (this.id[i] != k.id[i]) { + return false; + } + } + return true; + } + + // Use the same hash function as for String + @Override + public int hashCode() { + int h = 0; + for (int i = 0; i < id.length; i++) { + h = 31 * h + id[i]; + } + return h; + } + } + + protected POAImpl poa ; + + protected ActiveObjectMap( POAImpl poa ) + { + this.poa = poa ; + } + + public static ActiveObjectMap create( POAImpl poa, boolean multipleIDsAllowed ) + { + if (multipleIDsAllowed) { + return new MultipleObjectMap(poa); + } else { + return new SingleObjectMap(poa); + } + } + + private Map keyToEntry = + new HashMap() ; + private Map entryToServant = + new HashMap() ; + private Map servantToEntry = + new HashMap() ; + + public final boolean contains(Servant value) + { + return servantToEntry.containsKey( value ) ; + } + + public final boolean containsKey(Key key) + { + return keyToEntry.containsKey(key); + } + + /* get Returns the entry assigned to the key, or creates a new + * entry in state INVALID if none is present. + */ + public final AOMEntry get(Key key) + { + AOMEntry result = keyToEntry.get(key); + if (result == null) { + result = new AOMEntry( poa ) ; + putEntry( key, result ) ; + } + + return result ; + } + + public final Servant getServant( AOMEntry entry ) + { + return entryToServant.get(entry) ; + } + + public abstract Key getKey(AOMEntry value) throws WrongPolicy ; + + public Key getKey(Servant value) throws WrongPolicy + { + AOMEntry entry = servantToEntry.get(value) ; + return getKey( entry ) ; + } + + protected void putEntry( Key key, AOMEntry value ) + { + keyToEntry.put( key, value ) ; + } + + public final void putServant( Servant servant, AOMEntry value ) + { + entryToServant.put( value, servant ) ; + servantToEntry.put( servant, value ) ; + } + + protected abstract void removeEntry( AOMEntry entry, Key key ) ; + + public final void remove( Key key ) + { + AOMEntry entry = keyToEntry.remove(key) ; + Servant servant = entryToServant.remove(entry) ; + if (servant != null) { + servantToEntry.remove(servant); + } + + removeEntry( entry, key ) ; + } + + public abstract boolean hasMultipleIDs(AOMEntry value) ; + + protected void clear() + { + keyToEntry.clear(); + } + + public final Set keySet() + { + return keyToEntry.keySet() ; + } +} + +class SingleObjectMap extends ActiveObjectMap +{ + private Map entryToKey = new HashMap() ; + + SingleObjectMap( POAImpl poa ) + { + super( poa ) ; + } + + public Key getKey(AOMEntry value) throws WrongPolicy + { + return entryToKey.get(value) ; + } + + @Override + protected void putEntry(Key key, AOMEntry value) + { + super.putEntry( key, value); + + entryToKey.put( value, key ) ; + } + + public boolean hasMultipleIDs(AOMEntry value) + { + return false; + } + + // This case does not need the key. + protected void removeEntry(AOMEntry entry, Key key) + { + entryToKey.remove( entry ) ; + } + + @Override + public void clear() + { + super.clear() ; + entryToKey.clear() ; + } +} + +class MultipleObjectMap extends ActiveObjectMap +{ + private Map> entryToKeys = + new HashMap>() ; + + MultipleObjectMap( POAImpl poa ) + { + super( poa ) ; + } + + public Key getKey(AOMEntry value) throws WrongPolicy + { + throw new WrongPolicy() ; + } + + @Override + protected void putEntry(Key key, AOMEntry value) + { + super.putEntry( key, value); + + Set set = entryToKeys.get( value ) ; + if (set == null) { + set = new HashSet() ; + entryToKeys.put( value, set ) ; + } + set.add( key ) ; + } + + public boolean hasMultipleIDs(AOMEntry value) + { + Set set = entryToKeys.get( value ) ; + if (set == null) { + return false; + } + return set.size() > 1 ; + } + + protected void removeEntry(AOMEntry entry, Key key) + { + Set keys = entryToKeys.get( entry ) ; + if (keys != null) { + keys.remove( key ) ; + if (keys.isEmpty()) { + entryToKeys.remove(entry); + } + } + } + + @Override + public void clear() + { + super.clear() ; + entryToKeys.clear() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/BadServerIdHandler.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/BadServerIdHandler.java new file mode 100644 index 000000000..c5a34db16 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/BadServerIdHandler.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import com.sun.corba.ee.spi.ior.ObjectKey; + +/** + * The bad server id handler is used to locate persistent objects. + * The Locator object registers the BadServerIdHandler with the ORB + * and when requests for persistent objects for servers (other than + * itself) comes, it throws a ForwardException with the IOR pointing + * to the active server. + */ +public interface BadServerIdHandler +{ + void handle(ObjectKey objectKey) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/DelegateImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/DelegateImpl.java new file mode 100644 index 000000000..d69b33009 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/DelegateImpl.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import java.util.EmptyStackException; + +import org.omg.PortableServer.*; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.logging.POASystemException ; + +public class DelegateImpl implements org.omg.PortableServer.portable.Delegate +{ + private static final POASystemException wrapper = + POASystemException.self ; + + private ORB orb ; + private POAFactory factory; + + public DelegateImpl(ORB orb, POAFactory factory){ + this.orb = orb ; + this.factory = factory; + } + + public org.omg.CORBA.ORB orb(Servant self) + { + return orb; + } + + public org.omg.CORBA.Object this_object(Servant self) + { + byte[] oid; + POA poa; + try { + oid = orb.peekInvocationInfo().id(); + poa = (POA)orb.peekInvocationInfo().oa(); + String repId = self._all_interfaces(poa,oid)[0] ; + return poa.create_reference_with_id(oid, repId); + } catch (EmptyStackException notInInvocationE) { + //Not within an invocation context + POAImpl defaultPOA = null; + try { + defaultPOA = (POAImpl)self._default_POA(); + } catch (ClassCastException exception){ + throw wrapper.defaultPoaNotPoaimpl( exception ) ; + } + + try { + if (defaultPOA.getPolicies().isImplicitlyActivated() || + (defaultPOA.getPolicies().isUniqueIds() && + defaultPOA.getPolicies().retainServants())) { + return defaultPOA.servant_to_reference(self); + } else { + throw wrapper.wrongPoliciesForThisObject() ; + } + } catch ( org.omg.PortableServer.POAPackage.ServantNotActive e) { + throw wrapper.thisObjectServantNotActive( e ) ; + } catch ( org.omg.PortableServer.POAPackage.WrongPolicy e) { + throw wrapper.thisObjectWrongPolicy( e ) ; + } + } catch (ClassCastException e) { + throw wrapper.defaultPoaNotPoaimpl( e ) ; + } + } + + public POA poa(Servant self) + { + try { + return (POA)orb.peekInvocationInfo().oa(); + } catch (EmptyStackException exception){ + POA returnValue = factory.lookupPOA(self); + if (returnValue != null) { + return returnValue; + } + + throw wrapper.noContext( exception ) ; + } + } + + public byte[] object_id(Servant self) + { + try{ + return orb.peekInvocationInfo().id(); + } catch (EmptyStackException exception){ + throw wrapper.noContext(exception) ; + } + } + + public POA default_POA(Servant self) + { + return factory.getRootPOA(); + } + + public boolean is_a(Servant self, String repId) + { + String[] repositoryIds = self._all_interfaces(poa(self),object_id(self)); + for ( int i=0; i exportedServantsToPOA = new WeakHashMap(); + + private java.util.concurrent.ConcurrentHashMap poaManagers ; + + private int poaManagerId ; + private int poaId ; + private POAImpl rootPOA ; + private DelegateImpl delegateImpl; + private ORB orb ; + private boolean isShuttingDown = false ; + private ManagedObjectManager mom ; + + public POASystemException getWrapper() + { + return wrapper ; + } + + /** All object adapter factories must have a no-arg constructor. + */ + public POAFactory( ) + { + poaManagers = new java.util.concurrent.ConcurrentHashMap(4); + poaManagerId = 0 ; + poaId = 0 ; + rootPOA = null ; + delegateImpl = null ; + orb = null ; + } + + @ManagedData + @Description( "A servant registered with a particular POA" ) + public static class ServantPOAPair { + private Servant servant ; + private POAImpl poa ; + + public ServantPOAPair( Servant servant, POAImpl poa ) { + this.servant = servant ; + this.poa = poa ; + } + + @ManagedAttribute + @Description( "Servant" ) + Servant getServant() { return servant ; } + + @ManagedAttribute + @Description( "POA for Servant" ) + POAImpl getPOA() { return poa ; } + } + + @ManagedAttribute + @Description( "The servants managed by a particular POA" ) + private synchronized List getExportedServants() { + List result = new ArrayList() ; + for (Map.Entry entry : exportedServantsToPOA.entrySet()) { + POAImpl pimpl = (POAImpl)entry.getValue() ; + result.add( new ServantPOAPair( entry.getKey(), pimpl ) ) ; + } + return result ; + } + + @ManagedAttribute + @Description( "The POAManagers") + private synchronized Set getPOAManagers() { + return new HashSet( poaManagers.keySet() ) ; + } + + @ManagedAttribute + @Description( "The last allocated POAManager id") + private synchronized int getPOAManagerId() { + return poaManagerId ; + } + + @ManagedAttribute + @Description( "The last allocated POAManager id") + private synchronized int getPOAId() { + return poaId ; + } + + @ManagedAttribute( id = "RootPOA" ) + @Description( "The root POA") + private synchronized POAImpl getDisplayRootPOA() { + return rootPOA ; + } + + public synchronized POA lookupPOA (Servant servant) + { + return exportedServantsToPOA.get(servant); + } + + public synchronized void registerPOAForServant(POA poa, Servant servant) + { + exportedServantsToPOA.put(servant, poa); + } + + public synchronized void unregisterPOAForServant(POA poa, Servant servant) + { + exportedServantsToPOA.remove(servant); + } + +// Implementation of ObjectAdapterFactory interface + + public void init( ORB orb ) + { + this.orb = orb ; + delegateImpl = new DelegateImpl( orb, this ) ; + registerRootPOA() ; + + POACurrent poaCurrent = new POACurrent(orb); + orb.getLocalResolver().register( ORBConstants.POA_CURRENT_NAME, + NullaryFunction.Factory.makeConstant( + (org.omg.CORBA.Object)poaCurrent ) ) ; + this.mom = orb.mom() ; + mom.registerAtRoot( this ) ; + } + + public ObjectAdapter find( ObjectAdapterId oaid ) + { + POA poa=null; + try { + boolean first = true ; + Iterator iter = oaid.iterator() ; + poa = getRootPOA(); + while (iter.hasNext()) { + String name = (String)(iter.next()) ; + + if (first) { + if (!name.equals( ORBConstants.ROOT_POA_NAME )) { + throw wrapper.makeFactoryNotPoa(name); + } + first = false ; + } else { + poa = poa.find_POA( name, true ) ; + } + } + } catch ( org.omg.PortableServer.POAPackage.AdapterNonExistent ex ){ + throw omgWrapper.noObjectAdaptor( ex ) ; + } catch ( OBJECT_NOT_EXIST ex ) { + throw ex; + } catch ( TRANSIENT ex ) { + throw ex; + } catch ( Exception ex ) { + throw wrapper.poaLookupError( ex ) ; + } + + if ( poa == null ) { + throw wrapper.poaLookupError(); + } + + return (ObjectAdapter)poa; + } + + public void shutdown( boolean waitForCompletion ) + { + // It is important to copy the list of POAManagers first because + // pm.deactivate removes itself from poaManagers! + Iterator managers = null ; + synchronized (this) { + isShuttingDown = true ; + managers = poaManagers.keySet().iterator(); + } + + while ( managers.hasNext() ) { + try { + managers.next().deactivate(true, waitForCompletion); + } catch ( org.omg.PortableServer.POAManagerPackage.AdapterInactive e ) {} + } + } + +// Special methods used to manipulate global POA related state + + public synchronized void removePoaManager( POAManager manager ) + { + poaManagers.remove(manager); + mom.unregister( manager ) ; + } + + public void addPoaManager( POAManager manager ) + { + poaManagers.putIfAbsent(manager, Boolean.TRUE); // Store the key. Value is dummy + } + + synchronized public int newPOAManagerId() + { + return poaManagerId++ ; + } + + public void registerRootPOA() + { + // We delay the evaluation of makeRootPOA until + // a call to resolve_initial_references( "RootPOA" ). + // The Future guarantees that makeRootPOA is only called once. + NullaryFunction rpClosure = + new NullaryFunction() { + public org.omg.CORBA.Object evaluate() { + return POAImpl.makeRootPOA( orb ) ; + } + } ; + + orb.getLocalResolver().register( ORBConstants.ROOT_POA_NAME, + NullaryFunction.Factory.makeFuture( rpClosure ) ) ; + } + + public synchronized POA getRootPOA() + { + if (rootPOA == null) { + if (isShuttingDown) { + throw omgWrapper.noObjectAdaptor() ; + } + + try { + Object obj = orb.resolve_initial_references( + ORBConstants.ROOT_POA_NAME ) ; + rootPOA = (POAImpl)obj ; + } catch (InvalidName inv) { + throw wrapper.cantResolveRootPoa( inv ) ; + } + } + + return rootPOA; + } + + public org.omg.PortableServer.portable.Delegate getDelegateImpl() + { + return delegateImpl ; + } + + synchronized public int newPOAId() + { + return poaId++ ; + } + + public ORB getORB() + { + return orb ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAImpl.java new file mode 100644 index 000000000..6cb63f759 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAImpl.java @@ -0,0 +1,1806 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import java.util.Collection ; +import java.util.Set ; +import java.util.HashSet ; +import java.util.Map ; +import java.util.HashMap ; +import java.util.Iterator ; + +import java.util.concurrent.locks.Condition ; +import java.util.concurrent.locks.ReentrantLock ; + +import javax.management.ObjectName ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.SystemException ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.POAManager ; +import org.omg.PortableServer.AdapterActivator ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.ThreadPolicy; +import org.omg.PortableServer.LifespanPolicy; +import org.omg.PortableServer.IdUniquenessPolicy; +import org.omg.PortableServer.IdAssignmentPolicy; +import org.omg.PortableServer.ImplicitActivationPolicy; +import org.omg.PortableServer.ServantRetentionPolicy; +import org.omg.PortableServer.RequestProcessingPolicy; +import org.omg.PortableServer.ThreadPolicyValue ; +import org.omg.PortableServer.LifespanPolicyValue ; +import org.omg.PortableServer.IdUniquenessPolicyValue ; +import org.omg.PortableServer.IdAssignmentPolicyValue ; +import org.omg.PortableServer.ImplicitActivationPolicyValue ; +import org.omg.PortableServer.ServantRetentionPolicyValue ; +import org.omg.PortableServer.RequestProcessingPolicyValue ; +import org.omg.PortableServer.POAPackage.AdapterAlreadyExists ; +import org.omg.PortableServer.POAPackage.AdapterNonExistent ; +import org.omg.PortableServer.POAPackage.InvalidPolicy ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.WrongAdapter ; +import org.omg.PortableServer.POAPackage.NoServant ; +import org.omg.PortableServer.POAPackage.ServantAlreadyActive ; +import org.omg.PortableServer.POAPackage.ObjectAlreadyActive ; +import org.omg.PortableServer.POAPackage.ServantNotActive ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; + +import org.omg.PortableInterceptor.ObjectReferenceFactory ; +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.NON_EXISTENT ; + +import com.sun.corba.ee.spi.copyobject.CopierManager ; +import com.sun.corba.ee.spi.oa.OADestroyed ; +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.ObjectAdapterBase ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.IORTemplateList ; +import com.sun.corba.ee.spi.ior.TaggedProfile ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.ForwardException ; + +import com.sun.corba.ee.impl.ior.POAObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.ObjectAdapterIdArray ; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.logging.POASystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.trace.Poa; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.gmbal.ManagedObject; +import org.glassfish.gmbal.NameValue; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * POAImpl is the implementation of the Portable Object Adapter. It + * contains an implementation of the POA interfaces specified in + * COBRA 2.3.1 chapter 11 (formal/99-10-07). This implementation + * is moving to comply with CORBA 3.0 due to the many clarifications + * that have been made to the POA semantics since CORBA 2.3.1. + * Specific comments have been added where 3.0 applies, but note that + * we do not have the new 3.0 APIs yet. + */ +@Poa +@ManagedObject +public class POAImpl extends ObjectAdapterBase implements POA +{ + private static final POASystemException wrapper = + POASystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + private static final long serialVersionUID = -1746388801294205323L; + + // POA Creation + // + // POA creation takes place in 2 stages: + // first, the POAImpl constructor is called + // then, the initialize method is called. + // This separation is needed because an AdapterActivator does not know + // the POAManager or the policies when + // the unknown_adapter method is invoked. However, the POA must be created + // before the unknown_adapter method is invoked, so that the parent knows + // when concurrent attempts are made to create the same POA. + // + // Calling the POAImpl constructor results in a new POA without initializing + // the new POA. new POAImpl is called in two places: + // 1. inside create_POA: state = STATE_START + // 2. inside find_POA: state = STATE_INIT + // + // Calling initialize( POAManager, Policies ) results in state STATE_RUN + // (if the POA create created directly in create_POA) or + // state STATE_INIT_DONE (if the POA was create in an AdapterActivator). + // + // Calling destroy results in STATE_DESTROYING, which marks the beginning of + // POA destruction. + // + // destroyIfNotInitDone completes moves the POA state from STATE_INIT_DONE + // to STATE_RUN. It is called from find_POA after the unknown_adapter + // call returns. Note that unknown_adapter MUST call create_POA at some + // point. + + // Notes on concurrency + // + // The POA requires careful design for concurrency management to correctly + // implement the specification and avoid deadlocks. The order of acquiring + // locks must respect the following locking hierarchy: + // + // 1. Lock POAs before POAManagers + // 2. Lock a POA before locking its child POA + // + // Also note that there are 3 separate conditions on which threads may wait + // in the POA, as defined by invokeCV, beingDestroyedCV, and + // adapterActivatorCV. This means that (for this reason as well as others) + // we cannot simply use the standard Java synchronized primitive. + // This implementation uses a modified version of Doug Lea's + // util.concurrent (version 1.3.0) that supports reentrant + // mutexes to handle the locking. This will all be replaced by the new JSR + // 166 concurrency primitives in J2SE 1.5 and later once the ORB moves to + // J2SE 1.5. + // + // Recently I've modified the POA to support read/write locking. This works + // well for reducing lock contention, but it can be a bit tricky. ALl 3 + // condition variables are creates from poaMutex.writeLock, so + // poaMutex.writeLock() must be held whenever an acquire or signal method + // is called on one of the condition variables. Since it is not possible + // to upgrade a read lock to a write lock, using a condition variable + // requires dropping the read lock, acquiring the write lock, and possibly + // then checking again to make sure that an invariant is still satisified. + + // POA state constants + // + // Note that ordering is important here: we must have the state defined in + // this order so that ordered comparison is possible. + // DO NOT CHANGE THE VALUES OF THE STATE CONSTANTS!!! In particular, the + // initialization related states must be lower than STATE_RUN, and the + // destruction related state must be higher. + // + // A POA is created in STATE_START + // + // Valid state transitions: + // + // START to INIT after find_POA constructor call + // START to RUN after initialize completes + // INIT to INIT_DONE after initialize completes + // INIT to DESTROYED after failed unknown_adapter + // INIT_DONE to RUN after successful unknown_adapter + // STATE_RUN to STATE_DESTROYING after start of destruction + // STATE_DESTROYING to STATE_DESTROYED after destruction completes. + + private static final int STATE_START = 0 ; // constructor complete + private static final int STATE_INIT = 1 ; // waiting for adapter activator + private static final int STATE_INIT_DONE = 2 ; // adapter activator called create_POA + private static final int STATE_RUN = 3 ; // initialized and running + private static final int STATE_DESTROYING = 4 ; // being destroyed + private static final int STATE_DESTROYED = 5 ; // destruction complete + + private String stateToString() + { + switch (state) { + case STATE_START : + return "START" ; + case STATE_INIT : + return "INIT" ; + case STATE_INIT_DONE : + return "INIT_DONE" ; + case STATE_RUN : + return "RUN" ; + case STATE_DESTROYING : + return "DESTROYING" ; + case STATE_DESTROYED : + return "DESTROYED" ; + default : + return "UNKNOWN(" + state + ")" ; + } + } + + // Current state of the POA + private int state ; + + // The POA request handler that performs all policy specific operations + // Note that POAImpl handles all synchronization, so mediator is (mostly) + // unsynchronized. + private POAPolicyMediator mediator; + + // Representation of object adapter ID + private final int numLevels; // counts depth of tree. Root = 1. + private final ObjectAdapterId poaId ; // the actual object adapter ID for this POA + + private final String poaName; // the name of this POA + + private POAManagerImpl manager; // This POA's POAManager + private final int uniquePOAId ; // ID for this POA that is unique relative + // to the POAFactory, which has the same + // lifetime as the ORB. + private POAImpl parent; // The POA that created this POA. + private final Map children; // Map from name to POA of POAs + // created by this POA. + + private AdapterActivator activator; + private final AtomicInteger invocationCount ; // pending invocations on this POA. + + // Data used to control POA concurrency + + // Master lock for all POA synchronization. See lock and unlock. + // package private for access by AOMEntry. + final ReadWriteLock poaMutex ; + + // Wait on this CV for AdapterActivator upcalls to complete + private final Condition adapterActivatorCV ; + + // Wait on this CV for all active invocations to complete + private final Condition invokeCV ; + + // Wait on this CV for the destroy method to complete doing its work + private final Condition beingDestroyedCV ; + + // thread local variable to store a boolean to detect deadlock in + // POA.destroy(). + private final ThreadLocal isDestroying ; + + // Used for synchronized access to the ManagedObjectManager. + private static final Object momLock = new Object() ; + + // This includes the most important information for debugging + // POA problems. + @Override + public String toString() + { + return "POA[" + poaId.toString() + + ", uniquePOAId=" + uniquePOAId + + ", state=" + stateToString() + + ", invocationCount=" + invocationCount.get() + "]" ; + } + + @ManagedAttribute( id="POAState") + @Description( "The current state of the POA") + private String getDisplayState() { + lock() ; + try { + return stateToString() ; + } finally { + unlock() ; + } + } + + @ManagedAttribute + @Description( "The POA's mediator") + POAPolicyMediator getMediator() { + return mediator ; + } + + @ManagedAttribute + @Description( "The ObjectAdapterId for this POA") + private ObjectAdapterId getObjectAdapterId() { + return poaId ; + } + + // package private for access to servant to POA map + static POAFactory getPOAFactory( ORB orb ) + { + return (POAFactory)orb.getRequestDispatcherRegistry(). + getObjectAdapterFactory( ORBConstants.TRANSIENT_SCID ) ; + } + + @Poa + private static void registerMBean( ORB orb, Object obj ) { + orb.mom().register( getPOAFactory( orb ), obj ) ; + } + + // package private so that POAFactory can access it. + static POAImpl makeRootPOA( ORB orb ) + { + POAManagerImpl poaManager = new POAManagerImpl( getPOAFactory( orb ), + orb.getPIHandler() ) ; + registerMBean( orb, poaManager ) ; + + POAImpl result = new POAImpl( ORBConstants.ROOT_POA_NAME, + null, orb, STATE_START ) ; + result.initialize( poaManager, Policies.rootPOAPolicies ) ; + // must come after initialize! + registerMBean( orb, result ) ; + + return result ; + } + + // package private so that POAPolicyMediatorBase can access it. + @ManagedAttribute() + @Description( "The unique ID for this POA") + int getPOAId() + { + return uniquePOAId ; + } + + @InfoMethod + private void thisPoa( POAImpl p ) { } + + @InfoMethod + private void acquireLockWaiting( int count ) {} + + @Poa + // Be paranoid about lost wakeup problems like 6822370 + // GLASSFISH_CORBA-11, GLASSFISH-16217, Bug #14247062, Bug #14390811 : + // - 6822370 is resolved in JDK 6u21, hence simply call lock() + private void acquireLock( Lock lock ) { + lock.lock(); + } + + // package private so that POAPolicyMediator can access it. + @Poa + void lock() + { + acquireLock( poaMutex.writeLock() ) ; + thisPoa( this ) ; + } + + // package private so that POAPolicyMediator can access it. + @Poa + void unlock() + { + thisPoa( this ) ; + poaMutex.writeLock().unlock() ; + } + + @Poa + void readLock() + { + acquireLock( poaMutex.readLock() ) ; + thisPoa( this ) ; + } + + // package private so that POAPolicyMediator can access it. + @Poa + void readUnlock() + { + thisPoa( this ) ; + poaMutex.readLock().unlock() ; + } + + @Poa + final Condition makeCondition() { + return poaMutex.writeLock().newCondition() ; + } + + // package private so that DelegateImpl can access it. + Policies getPolicies() + { + return mediator.getPolicies() ; + } + + @Poa + private void newPOACreated( String name, String parentName ) { } + + // Note that the parent POA must be write locked when this constructor + // is called. + private POAImpl( String name, POAImpl parent, ORB orb, int initialState ) { + super( orb ) ; + + if (parent == null) { + newPOACreated( name, "null parent for root POA" ) ; + } else { + newPOACreated( name, parent.poaName ) ; + } + + this.state = initialState ; + this.poaName = name ; + this.parent = parent; + children = new HashMap(); + activator = null ; + + // This was done in initialize, but I moved it here + // to get better searchability when tracing. + uniquePOAId = getPOAFactory( orb ).newPOAId() ; + + if (parent == null) { + // This is the root POA, which counts as 1 level + numLevels = 1 ; + } else { + // My level is one more than that of my parent + numLevels = parent.numLevels + 1 ; + + parent.children.put(name, this); + } + + // Get an array of all of the POA names in order to + // create the poaid. + String[] names = new String[ numLevels ] ; + POAImpl poaImpl = this ; + int ctr = numLevels - 1 ; + while (poaImpl != null) { + names[ctr] = poaImpl.poaName ; + ctr-- ; + poaImpl = poaImpl.parent ; + } + + poaId = new ObjectAdapterIdArray( names ) ; + + invocationCount = new AtomicInteger(0) ; + + poaMutex = new ReentrantReadWriteLock() ; + adapterActivatorCV = makeCondition() ; + invokeCV = makeCondition() ; + beingDestroyedCV = makeCondition() ; + + isDestroying = new ThreadLocal() { + @Override + protected Boolean initialValue() { + return Boolean.FALSE; + } + }; + } + + @NameValue + private String getName() { + StringBuilder sb = new StringBuilder() ; + boolean first = true ; + for (String str : poaId.getAdapterName() ) { + if (first) { + first = false ; + } else { + sb.append( '.' ) ; + } + sb.append( str ) ; + } + return sb.toString() ; + } + + @InfoMethod + private void initializingPoa( int scid, int serverid, String orbid, + ObjectAdapterId poaId ) { } + + // The POA write lock must be held when this method is called. + @Poa + private void initialize( POAManagerImpl manager, Policies policies ) + { + this.manager = manager; + manager.addPOA(this); + + mediator = POAPolicyMediatorFactory.create( policies, this ) ; + + // Construct the object key template + int serverid = mediator.getServerId() ; + int scid = mediator.getScid() ; + String orbId = getORB().getORBData().getORBId(); + + ObjectKeyTemplate oktemp = new POAObjectKeyTemplate( getORB(), + scid, serverid, orbId, poaId ) ; + + + initializingPoa( scid, serverid, orbId, poaId ) ; + + // Note that parent == null iff this is the root POA. + // This was used to avoid executing interceptors on the RootPOA. + // That is no longer necessary. + boolean objectAdapterCreated = true; // parent != null ; + + // XXX extract codebase from policies and pass into initializeTemplate + // after the codebase policy change is finalized. + initializeTemplate( oktemp, objectAdapterCreated, + policies, + null, // codebase + null, // manager id + oktemp.getObjectAdapterId() + ) ; + + if (state == STATE_START) { + state = STATE_RUN; + } else if (state == STATE_INIT) { + state = STATE_INIT_DONE; + } else { + throw wrapper.illegalPoaStateTrans(); + } + } + + @InfoMethod + private void interruptedAwait( InterruptedException exc ) {} + + // The POA write lock must be held when this method is called + // The lock may be upgraded to write. + @Poa + private boolean waitUntilRunning() + { + while (state < STATE_RUN) { + try { + adapterActivatorCV.await( 1, TimeUnit.SECONDS ) ; + } catch (InterruptedException exc) { + interruptedAwait( exc ) ; + } + } + + // Note that a POA could be destroyed while in STATE_INIT due to a + // failure in the AdapterActivator upcall. + return (state == STATE_RUN) ; + } + + // This method checks that the AdapterActivator finished the + // initialization of a POA activated in find_POA. This is + // determined by checking the state of the POA. If the state is + // STATE_INIT, the AdapterActivator did not complete the + // inialization. In this case, we destroy the POA that was + // partially created and return false. Otherwise, we return true. + // In any case, we must wake up all threads waiting for the adapter + // activator, either to continue their invocations, or to return + // errors to their client. + // + // No POA lock may be held when this method is called. + private boolean destroyIfNotInitDone() + { + lock() ; + + try { + boolean success = (state == STATE_INIT_DONE) ; + + if (success) { + state = STATE_RUN ; + unlock() ; + } else { + // Issue 7061: do not hold POA lock while calling destroyer.doIt, + // because this would violate the lock ordering constraints, + // since doIt locks the parent first, then the child. + unlock() ; + + // Don't just use destroy, because the check for + // deadlock is too general, and can prevent this from + // functioning properly. + DestroyThread destroyer = new DestroyThread( false ); + destroyer.doIt( this, true ) ; + } + + return success ; + } finally { + lock() ; + + try { + adapterActivatorCV.signalAll() ; + } finally { + unlock() ; + } + } + } + + private byte[] internalReferenceToId( + org.omg.CORBA.Object reference ) throws WrongAdapter + { + IOR ior = getORB().getIOR( reference, false ) ; + IORTemplateList thisTemplate = ior.getIORTemplates() ; + + ObjectReferenceFactory orf = getCurrentFactory() ; + IORTemplateList poaTemplate = + IORFactories.getIORTemplateList( orf ) ; + + if (!poaTemplate.isEquivalent( thisTemplate )) { + throw new WrongAdapter(); + } + + // Extract the ObjectId from the first TaggedProfile in the IOR. + // If ior was created in this POA, the same ID was used for + // every profile through the profile templates in the currentFactory, + // so we will get the same result from any profile. + Iterator iter = ior.iterator() ; + if (!iter.hasNext()) { + throw wrapper.noProfilesInIor(); + } + TaggedProfile prof = (iter.next()) ; + ObjectId oid = prof.getObjectId() ; + + return oid.getId(); + } + + // Converted from anonymous class to local class + // so that we can call performDestroy() directly. + @Poa + private static class DestroyThread extends Thread { + private boolean wait ; + private boolean etherealize ; + private POAImpl thePoa ; + + DestroyThread( boolean etherealize ) { + this.etherealize = etherealize ; + } + + @Poa + public void doIt( POAImpl thePoa, boolean wait ) { + this.thePoa = thePoa ; + this.wait = wait ; + + if (wait) { + run() ; + } else { + // Catch exceptions since setDaemon can cause a + // security exception to be thrown under netscape + // in the Applet mode + try { + setDaemon(true); + } catch (Exception e) { + thePoa.wrapper.couldNotSetDaemon( e ) ; + } + + start() ; + } + } + + @Poa + @Override + public void run() + { + final Set destroyedPOATemplates = + new HashSet() ; + + performDestroy( thePoa, destroyedPOATemplates ); + + Iterator iter = destroyedPOATemplates.iterator() ; + ObjectReferenceTemplate[] orts = new ObjectReferenceTemplate[ + destroyedPOATemplates.size() ] ; + int index = 0 ; + while (iter.hasNext()) { + orts[index] = iter.next(); + index++ ; + } + + ORB myORB = thePoa.getORB() ; + + if (destroyedPOATemplates.size() > 0) { + myORB.getPIHandler().adapterStateChanged( orts, + NON_EXISTENT.value ) ; + } + } + + // Returns true if destruction must be completed, false + // if not, which means that another thread is already + // destroying poa. + @Poa + private boolean prepareForDestruction( POAImpl poa, + Set destroyedPOATemplates ) + { + POAImpl[] childPoas = null ; + + // Note that we do not synchronize on this, since this is + // the PerformDestroy instance, not the POA. + poa.lock() ; + + try { + if (poa.state <= STATE_RUN) { + poa.state = STATE_DESTROYING ; + } else { + // destroy may be called multiple times, and each call + // is allowed to proceed with its own setting of the wait + // flag, but the etherealize value is used from the first + // call to destroy. Also all children should be destroyed + // before the parent POA. If the poa is already destroyed, + // we can just return. If the poa has started destruction, + // but not completed, and wait is true, we need to wait + // until destruction is complete, then just return. + if (wait) { + while (poa.state != STATE_DESTROYED) { + try { + poa.beingDestroyedCV.await( 1, TimeUnit.SECONDS ); + } catch (InterruptedException exc) { + interruptedAwait( exc ) ; + } + } + } + + return false ; + } + + poa.isDestroying.set(Boolean.TRUE); + + // Make a copy since we can't hold the lock while destroying + // the children, and an iterator is not deletion-safe. + childPoas = poa.children.values().toArray( new POAImpl[0] ); + } finally { + poa.unlock() ; + } + + // We are not holding the POA mutex here to avoid holding it + // while destroying the POA's children, since this may involve + // upcalls to etherealize methods. + + for (int ctr=0; ctr destroyedPOATemplates ) + { + if (!prepareForDestruction( poa, destroyedPOATemplates )) { + return; + } + + // NOTE: If we are here, poa is in STATE_DESTROYING state. All + // other state checks are taken care of in prepareForDestruction. + // No other threads may either be starting new invocations + // by calling enter or starting to destroy poa. There may + // still be pending invocations. + + POAImpl parent = poa.parent ; + boolean isRoot = parent == null ; + + // Note that we must lock the parent before the child. + // The parent lock is required (if poa is not the root) + // to safely remove poa from parent's children Map. + if (!isRoot) { + parent.lock(); + } + + try { + poa.lock() ; + try { + completeDestruction( poa, parent, + destroyedPOATemplates ) ; + } finally { + poa.unlock() ; + + if (isRoot) { + poa.manager.getFactory().registerRootPOA(); + } + } + } finally { + if (!isRoot) { + parent.unlock() ; + poa.parent = null ; + } + } + } + + @InfoMethod + private void unregisteringMBean( ObjectName oname, POAImpl poa ) { } + + @InfoMethod + private void noMBean( POAImpl poa ) { } + + @InfoMethod + private void interruptedAwait( InterruptedException exc ) {} + + @Poa + private void completeDestruction( POAImpl poa, POAImpl parent, + Set destroyedPOATemplates ) + { + try { + while (poa.invocationCount.get() != 0) { + try { + poa.invokeCV.await( 1, TimeUnit.SECONDS ) ; + } catch (InterruptedException ex) { + interruptedAwait( ex ) ; + } + } + + if (poa.mediator != null) { + if (etherealize) { + poa.mediator.etherealizeAll(); + } + + poa.mediator.clearAOM() ; + } + + if (poa.manager != null) { + poa.manager.removePOA(poa); + } + + if (parent != null) { + parent.children.remove(poa.poaName); + } + + destroyedPOATemplates.add( poa.getAdapterTemplate() ) ; + + synchronized (momLock) { + // Only unregister if the poa is still registered: we may get + // here because another thread concurrently destroyed this POA. + // XXX This may not be necessary now. + ObjectName oname = poa.getORB().mom().getObjectName( poa ) ; + if (oname != null) { + unregisteringMBean( oname, poa ) ; + poa.getORB().mom().unregister( poa ); + } else { + noMBean( poa ) ; + } + } + } catch (Throwable thr) { + if (thr instanceof ThreadDeath) { + throw (ThreadDeath) thr; + } + + wrapper.unexpectedException( thr, poa.toString() ) ; + } finally { + poa.state = STATE_DESTROYED ; + poa.beingDestroyedCV.signalAll(); + poa.isDestroying.set(Boolean.FALSE); + } + } + } + + @Poa + void etherealizeAll() + { + lock() ; + + try { + mediator.etherealizeAll() ; + } finally { + unlock() ; + } + } + + //******************************************************************* + // Public POA API + //******************************************************************* + @InfoMethod + private void newPOA( POAImpl poa ) { } + + /** + * create_POA + * Section 3.3.8.2 + */ + @Poa + public POA create_POA(String name, POAManager + theManager, Policy[] policies) throws AdapterAlreadyExists, + InvalidPolicy + { + lock() ; + + try { + // We cannot create children of a POA that is (being) destroyed. + // This has been added to the CORBA 3.0 spec. + if (state > STATE_RUN) { + throw omgWrapper.createPoaDestroy(); + } + + POAImpl poa = children.get(name) ; + + if (poa == null) { + poa = new POAImpl( name, this, getORB(), STATE_START ) ; + } + + try { + poa.lock() ; + newPOA( poa ) ; + + if ((poa.state != STATE_START) && (poa.state != STATE_INIT)) { + throw new AdapterAlreadyExists(); + } + + POAManagerImpl newManager = (POAManagerImpl)theManager ; + if (newManager == null) { + newManager = new POAManagerImpl( manager.getFactory(), + getORB().getPIHandler() ); + registerMBean( getORB(), newManager ) ; + } + + int defaultCopierId = + getORB().getCopierManager().getDefaultId() ; + Policies POAPolicies = + new Policies( policies, defaultCopierId ) ; + + poa.initialize( newManager, POAPolicies ) ; + + // Issue 11334: Must come after poa.initialize! + registerMBean( getORB(), poa ) ; + + return poa; + } finally { + poa.unlock() ; + } + } finally { + unlock() ; + } + } + + @InfoMethod + private void foundPOA( POAImpl poa ) { } + + @InfoMethod + private void createdPOA( POAImpl poa ) { } + + @InfoMethod + private void noPOA() { } + + @InfoMethod + private void callingAdapterActivator() { } + + @InfoMethod + private void adapterActivatorResult( boolean result ) { } + + /** find_POA + * Section 3.3.8.3 + */ + @Poa + public POA find_POA(String name, boolean activate) throws AdapterNonExistent { + AdapterActivator act = null ; + boolean readLocked = false ; + boolean writeLocked = false ; + boolean childReadLocked = false ; + POAImpl child = null ; + + try { + // Issue 14318: Use readLock where possible to reduce contention. + readLock() ; readLocked = true ; + + child = children.get(name); + if (child != null) { + child.readLock() ; childReadLocked = true ; + foundPOA( child ) ; + try { + // No parent lock while waiting for child init to complete! + readUnlock() ; readLocked = false ; + + if (child.state != STATE_RUN) { + child.readUnlock() ; childReadLocked = false ; + child.lockAndWaitUntilRunning() ; + } + // child may be in DESTROYING or DESTROYED at this point. + // That's OK, since destruction could start at any time. + } finally { + if (childReadLocked) { child.readUnlock() ; childReadLocked = false ; } + } + } else { + try { + noPOA() ; + + if (activate && (activator != null)) { + readUnlock() ; readLocked = false ; // need writeLock: drop readLock + + // Note that another thread could create the child here + // in between the unlock and the lock. + + lock() ; writeLocked = true ; + try { + child = children.get(name); + if (child == null) { + child = new POAImpl( name, this, getORB(), STATE_INIT ) ; + createdPOA( child ) ; + act = activator ; // Issue 14917: Only set if child NOT found + } else { // Child created before writeLock + unlock() ; writeLocked = false ; // don't hold parent lock! + child.lockAndWaitUntilRunning() ; + } + } finally { + if (writeLocked) { unlock() ; writeLocked = false ; } + } + } else { + throw new AdapterNonExistent(); + } + } finally { + if (readLocked) { readUnlock() ; } // Issue 14917: was unlock() + } + } + + // assert (child != null) and not holding locks on this or child (must avoid deadlock) + if (act != null) { + doActivate( act, name, child ) ; + } + + return child; + } finally { + cleanUpLocks( child, readLocked, writeLocked, childReadLocked ) ; + } + } + + @Poa + private void lockAndWaitUntilRunning() { + // Issue 14695: waitUntilRunning requires writeLock. + lock() ; + try { + // wait for child init to complete + if (!waitUntilRunning()) { + // OMG 3.0 11.3.9.3, in reference to unknown_adapter + throw omgWrapper.poaDestroyed(); + } + } finally { + unlock() ; + } + } + + @Poa + private void doActivate( AdapterActivator act, + String name, POAImpl child ) throws AdapterNonExistent { + + boolean status = false ; + boolean adapterResult = false ; + callingAdapterActivator() ; + + try { + // Prevent more than one thread at a time from executing in act + // in case act is shared between multiple POAs. + synchronized (act) { + status = act.unknown_adapter(this, name); + } + } catch (SystemException exc) { + throw omgWrapper.adapterActivatorException( exc, + poaName, poaId ) ; + } catch (Throwable thr) { + // ignore most non-system exceptions, but log them for + // diagnostic purposes. + wrapper.unexpectedException( thr, this.toString() ) ; + + if (thr instanceof ThreadDeath) { + throw (ThreadDeath) thr; + } + } finally { + // At this point, we have completed adapter activation. + // Whether this was successful or not, we must call + // destroyIfNotInitDone so that calls to enter() and create_POA() + // that are waiting can execute again. Failing to do this + // will cause the system to hang in complex tests. + adapterResult = child.destroyIfNotInitDone() ; + } + + adapterActivatorResult(status); + + if (status) { + if (!adapterResult) { + throw omgWrapper.adapterActivatorException(name, poaId); + } + } else { + // OMG Issue 3740 is resolved to throw AdapterNonExistent if + // unknown_adapter() returns false. + throw new AdapterNonExistent(); + } + } + + @InfoMethod + private void locksWereHeld() {} + + @Poa + private void cleanUpLocks( POAImpl child, boolean readLocked, boolean writeLocked, + boolean childReadLocked ) { + // Log an error if we ever get here with a lock held! + if (readLocked || writeLocked || childReadLocked) { + locksWereHeld(); + wrapper.findPOALocksNotReleased( readLocked, writeLocked, + childReadLocked ) ; + + if (readLocked) { + readUnlock() ; + } + + if (writeLocked) { + unlock() ; + } + + if (childReadLocked && child != null) { + child.readUnlock() ; + } + } + } + + /** + * destroy + * Section 3.3.8.4 + */ + public void destroy(boolean etherealize, boolean wait_for_completion) + { + // This is to avoid deadlock + if (wait_for_completion && getORB().isDuringDispatch()) { + throw wrapper.destroyDeadlock() ; + } + + DestroyThread destroyer = new DestroyThread( etherealize ); + destroyer.doIt( this, wait_for_completion ) ; + } + + /** + * create_thread_policy + * Section 3.3.8.5 + */ + public ThreadPolicy create_thread_policy( + ThreadPolicyValue value) + { + return new ThreadPolicyImpl(value); + } + + /** + * create_lifespan_policy + * Section 3.3.8.5 + */ + public LifespanPolicy create_lifespan_policy( + LifespanPolicyValue value) + { + return new LifespanPolicyImpl(value); + } + + /** + * create_id_uniqueness_policy + * Section 3.3.8.5 + */ + public IdUniquenessPolicy create_id_uniqueness_policy( + IdUniquenessPolicyValue value) + { + return new IdUniquenessPolicyImpl(value); + } + + /** + * create_id_assignment_policy + * Section 3.3.8.5 + */ + public IdAssignmentPolicy create_id_assignment_policy( + IdAssignmentPolicyValue value) + { + return new IdAssignmentPolicyImpl(value); + } + + /** + * create_implicit_activation_policy + * Section 3.3.8.5 + */ + public ImplicitActivationPolicy create_implicit_activation_policy( + ImplicitActivationPolicyValue value) + { + return new ImplicitActivationPolicyImpl(value); + } + + /** + * create_servant_retention_policy + * Section 3.3.8.5 + */ + public ServantRetentionPolicy create_servant_retention_policy( + ServantRetentionPolicyValue value) + { + return new ServantRetentionPolicyImpl(value); + } + + /** + * create_request_processing_policy + * Section 3.3.8.5 + */ + public RequestProcessingPolicy create_request_processing_policy( + RequestProcessingPolicyValue value) + { + return new RequestProcessingPolicyImpl(value); + } + + /** + * the_name + * Section 3.3.8.6 + */ + @ManagedAttribute( id="POAName") + @Description( "The name of this POA") + public String the_name() + { + try { + lock() ; + + return poaName; + } finally { + unlock() ; + } + } + + /** + * the_parent + * Section 3.3.8.7 + */ + @ManagedAttribute( id="POAParent") + @Description( "The parent of this POA") + public POA the_parent() + { + try { + lock() ; + + return parent; + } finally { + unlock() ; + } + } + + /** + * the_children + */ + @ManagedAttribute( id="POAChildren") + @Description( "The children of this POA") + private List children() { + try { + lock() ; + return new ArrayList( children.values() ) ; + } finally { + unlock() ; + } + } + + public org.omg.PortableServer.POA[] the_children() + { + try { + lock() ; + + Collection coll = children.values() ; + int size = coll.size() ; + POA[] result = new POA[ size ] ; + int index = 0 ; + Iterator iter = coll.iterator() ; + while (iter.hasNext()) { + POA poa = iter.next() ; + result[ index ] = poa ; + index++ ; + } + + return result ; + } finally { + unlock() ; + } + } + + // We need this in order to return the correct type. + // I'm not sure a covariant return could be used here. + @ManagedAttribute( id="POAManager") + @Description( "The POAManager of this POA") + private POAManagerImpl getPOAManager() { + try { + lock() ; + + return manager; + } finally { + unlock() ; + } + } + + /** + * the_POAManager + * Section 3.3.8.8 + */ + public POAManager the_POAManager() + { + try { + lock() ; + + return manager; + } finally { + unlock() ; + } + } + + /** + * the_activator + * Section 3.3.8.9 + */ + @ManagedAttribute( id="Activator") + @Description( "The AdapterActivator of this POA") + public AdapterActivator the_activator() + { + try { + lock() ; + + return activator; + } finally { + unlock() ; + } + } + + /** + * the_activator + * Section 3.3.8.9 + */ + @Poa + public void the_activator(AdapterActivator activator) + { + try { + lock() ; + + this.activator = activator; + } finally { + unlock() ; + } + } + + /** + * get_servant_manager + * Section 3.3.8.10 + */ + public ServantManager get_servant_manager() throws WrongPolicy + { + try { + lock() ; + + return mediator.getServantManager() ; + } finally { + unlock() ; + } + } + + @ManagedAttribute + @Description( "The servant manager of this POA (may be null)") + private ServantManager servantManager() { + try { + return get_servant_manager(); + } catch (WrongPolicy ex) { + return null ; + } + } + + /** + * set_servant_manager + * Section 3.3.8.10 + */ + @Poa + public void set_servant_manager(ServantManager servantManager) + throws WrongPolicy + { + try { + lock() ; + + mediator.setServantManager( servantManager ) ; + } finally { + unlock() ; + } + } + + /** + * get_servant + * Section 3.3.8.12 + */ + public Servant get_servant() throws NoServant, WrongPolicy + { + try { + lock() ; + + return mediator.getDefaultServant() ; + } finally { + unlock() ; + } + } + + @ManagedAttribute + @Description( "The default servant of this POA (may be null)") + private Servant servant() { + try { + return get_servant(); + } catch (NoServant ex) { + return null ; + } catch (WrongPolicy ex) { + return null ; + } + } + + /** + * set_servant + * Section 3.3.8.13 + */ + @Poa + public void set_servant(Servant defaultServant) + throws WrongPolicy + { + try { + lock() ; + + mediator.setDefaultServant( defaultServant ) ; + } finally { + unlock() ; + } + } + + /** + * activate_object + * Section 3.3.8.14 + */ + @Poa + public byte[] activate_object(Servant servant) + throws ServantAlreadyActive, WrongPolicy + { + try { + lock() ; + + // Allocate a new system-generated object-id. + // This will throw WrongPolicy if not SYSTEM_ID + // policy. + byte[] id = mediator.newSystemId(); + + try { + mediator.activateObject( id, servant ) ; + } catch (ObjectAlreadyActive oaa) { + // This exception can not occur in this case, + // since id is always brand new. + // + } + + return id ; + } finally { + unlock() ; + } + } + + /** + * activate_object_with_id + * Section 3.3.8.15 + */ + @Poa + public void activate_object_with_id(byte[] id, + Servant servant) + throws ObjectAlreadyActive, ServantAlreadyActive, WrongPolicy + { + try { + lock() ; + + // Clone the id to avoid possible errors due to aliasing + // (e.g. the client passes the id in and then changes it later). + byte[] idClone = id.clone() ; + + mediator.activateObject( idClone, servant ) ; + } finally { + unlock() ; + } + } + + /** + * deactivate_object + * 3.3.8.16 + */ + @Poa + public void deactivate_object(byte[] id) + throws ObjectNotActive, WrongPolicy + { + try { + lock() ; + + mediator.deactivateObject( id ) ; + } finally { + unlock() ; + } + } + + /** + * create_reference + * 3.3.8.17 + */ + @Poa + public org.omg.CORBA.Object create_reference(String repId) + throws WrongPolicy + { + try { + lock() ; + + return makeObject( repId, mediator.newSystemId()) ; + } finally { + unlock() ; + } + } + + /** + * create_reference_with_id + * 3.3.8.18 + */ + @Poa + public org.omg.CORBA.Object + create_reference_with_id(byte[] oid, String repId) + { + try { + lock() ; + + // Clone the id to avoid possible errors due to aliasing + // (e.g. the client passes the id in and then changes it later). + byte[] idClone = (oid.clone()) ; + + return makeObject( repId, idClone ) ; + } finally { + unlock() ; + } + } + + /** + * servant_to_id + * 3.3.8.19 + */ + @Poa + public byte[] servant_to_id(Servant servant) + throws ServantNotActive, WrongPolicy + { + try { + lock() ; + + return mediator.servantToId( servant ) ; + } finally { + unlock() ; + } + } + + /** + * servant_to_reference + * 3.3.8.20 + */ + @Poa + public org.omg.CORBA.Object servant_to_reference(Servant servant) + throws ServantNotActive, WrongPolicy + { + try { + lock() ; + + byte[] oid = mediator.servantToId(servant); + String repId = servant._all_interfaces( this, oid )[0] ; + return create_reference_with_id(oid, repId); + } finally { + unlock() ; + } + } + + /** + * reference_to_servant + * 3.3.8.21 + */ + @Poa + public Servant reference_to_servant(org.omg.CORBA.Object reference) + throws ObjectNotActive, WrongPolicy, WrongAdapter + { + try { + lock() ; + + if ( state >= STATE_DESTROYING ) { + throw wrapper.adapterDestroyed() ; + } + + // reference_to_id should throw WrongAdapter + // if the objref was not created by this POA + byte [] id = internalReferenceToId(reference); + + return mediator.idToServant( id ) ; + } finally { + unlock() ; + } + } + + /** + * reference_to_id + * 3.3.8.22 + */ + @Poa + public byte[] reference_to_id(org.omg.CORBA.Object reference) + throws WrongAdapter, WrongPolicy + { + try { + lock() ; + + if( state >= STATE_DESTROYING ) { + throw wrapper.adapterDestroyed() ; + } + + return internalReferenceToId( reference ) ; + } finally { + unlock() ; + } + } + + /** + * id_to_servant + * 3.3.8.23 + */ + @Poa + public Servant id_to_servant(byte[] id) + throws ObjectNotActive, WrongPolicy + { + try { + lock() ; + + if( state >= STATE_DESTROYING ) { + throw wrapper.adapterDestroyed() ; + } + return mediator.idToServant( id ) ; + } finally { + unlock() ; + } + } + + /** + * id_to_reference + * 3.3.8.24 + */ + @Poa + public org.omg.CORBA.Object id_to_reference(byte[] id) + throws ObjectNotActive, WrongPolicy + + { + try { + lock() ; + + if( state >= STATE_DESTROYING ) { + throw wrapper.adapterDestroyed() ; + } + + Servant s = mediator.idToServant( id ) ; + String repId = s._all_interfaces( this, id )[0] ; + return makeObject(repId, id ); + } finally { + unlock() ; + } + } + + /** + * id + * 11.3.8.26 in ptc/00-08-06 + */ + public byte[] id() + { + try { + lock() ; + + return getAdapterId() ; + } finally { + unlock() ; + } + } + + //*************************************************************** + //Implementation of ObjectAdapter interface + //*************************************************************** + + public Policy getEffectivePolicy( int type ) + { + return mediator.getPolicies().get_effective_policy( type ) ; + } + + public int getManagerId() + { + return manager.getManagerId() ; + } + + public short getState() + { + return manager.getORTState() ; + } + + public String[] getInterfaces( java.lang.Object servant, byte[] objectId ) + { + Servant serv = (Servant)servant ; + return serv._all_interfaces( this, objectId ) ; + } + + protected ObjectCopierFactory getObjectCopierFactory() + { + int copierId = mediator.getPolicies().getCopierId() ; + CopierManager cm = getORB().getCopierManager() ; + return cm.getObjectCopierFactory( copierId ) ; + } + + @Poa + public void enter() throws OADestroyed + { + manager.enter(); + + readLock() ; + try { + // Hold only the read lock to check the state + if (state == STATE_RUN) { + // fast path + invocationCount.incrementAndGet(); + return ; + } + } finally { + readUnlock(); + } + + // acquire lock: may need slow path + lock() ; + + try { + // Avoid deadlock if this is the thread that is processing the + // POA.destroy because this is the only thread that can notify + // waiters on beingDestroyedCV. This can happen if an + // etherealize upcall invokes a method on a colocated object + // served by this POA. + while ((state == STATE_DESTROYING) && + (isDestroying.get() == Boolean.FALSE)) { + try { + beingDestroyedCV.await( 1, TimeUnit.SECONDS ); + } catch (InterruptedException ex) { + interruptedAwait( ex ) ; + } + } + + if (!waitUntilRunning()) { + manager.exit() ; + throw new OADestroyed() ; + } + + invocationCount.incrementAndGet(); + } finally { + unlock() ; + } + } + + @Poa + public void exit() + { + try { + readLock() ; + try { + // Hold only a read lock to check the state + if (state == STATE_RUN) { + // fast path + invocationCount.decrementAndGet(); + return ; + } + } finally { + readUnlock(); + } + + lock() ; + try { + if ((invocationCount.decrementAndGet() == 0) + && (state == STATE_DESTROYING)) { + invokeCV.signalAll(); + } + } finally { + unlock() ; + } + } finally { + manager.exit(); + } + + } + + @ManagedAttribute + @Description( "The current invocation count of this POA") + @Poa + private int getInvocationCount() { + try { + lock() ; + return invocationCount.get() ; + } finally { + unlock() ; + } + } + + @Poa + public void getInvocationServant( OAInvocationInfo info ) { + // 6878245 + if (info == null) { + return ; + } + + java.lang.Object servant = null ; + + try { + servant = mediator.getInvocationServant( info.id(), + info.getOperation() ); + } catch (ForwardRequest freq) { + throw new ForwardException( getORB(), freq.forward_reference ) ; + } + + info.setServant( servant ) ; + } + + public org.omg.CORBA.Object getLocalServant( byte[] objectId ) + { + return null ; + } + + /** Called from the subcontract to let this POA cleanup after an + * invocation. Note: If getServant was called, then returnServant + * MUST be called, even in the case of exceptions. This may be + * called multiple times for a single request. + */ + @Poa + public void returnServant() { + try { + mediator.returnServant(); + } catch (Throwable thr) { + if (thr instanceof Error) { + throw (Error) thr; + } else if (thr instanceof RuntimeException) { + throw (RuntimeException)thr ; + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAManagerImpl.java new file mode 100644 index 000000000..5ecfac50b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAManagerImpl.java @@ -0,0 +1,694 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import java.util.Set; +import java.util.HashSet; + + +import org.omg.PortableServer.POAManager; +import org.omg.PortableServer.POAManagerPackage.State; + +import org.omg.PortableInterceptor.DISCARDING ; +import org.omg.PortableInterceptor.ACTIVE ; +import org.omg.PortableInterceptor.HOLDING ; +import org.omg.PortableInterceptor.INACTIVE ; +import org.omg.PortableInterceptor.NON_EXISTENT ; + +import com.sun.corba.ee.spi.protocol.PIHandler ; + +import com.sun.corba.ee.spi.logging.POASystemException ; + +import com.sun.corba.ee.spi.trace.Poa; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.ManagedOperation ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ParameterNames ; +import org.glassfish.gmbal.NameValue ; + +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.glassfish.pfl.basic.contain.MultiSet ; + +/** POAManagerImpl is the implementation of the POAManager interface. + * Its public methods are activate(), hold_requests(), discard_requests() + * and deactivate(). + */ + +@Poa +@ManagedObject +@Description( "A POAManager which controls invocations of its POAs") +public class POAManagerImpl extends org.omg.CORBA.LocalObject implements + POAManager +{ + private static final POASystemException wrapper = + POASystemException.self ; + + private static final long serialVersionUID = -3308938242684343402L; + + // final fields: no synchronization needed + private final POAFactory factory ; // factory which contains global state + // for all POAManagers + private final PIHandler pihandler ; // for AdapterManagerStateChanged + private final int myId ; // This POAManager's ID + + // Making this a fair lock due to expected very high numbers of readers + // with an occasional writer that must NOT be starved. + // + // The state and poas fields may be READ while holding the read lock. + // Updates require holding the write lock. + private final ReentrantReadWriteLock stateLock = + new ReentrantReadWriteLock( true ) ; + + // Condition var used for waiting. Can only wait on this when the + // write lock is held! + private final Condition stateCV = stateLock.writeLock().newCondition() ; + + // fields protected by stateLock + private State state; // current state of this POAManager + + private Set poas = + new HashSet(4) ; // all poas controlled by this POAManager + + // fields using other synchronization methods + private AtomicInteger nInvocations= + new AtomicInteger(0); // Number of invocations in progress + private AtomicInteger nWaiters = + new AtomicInteger(0) ; // Number of threads waiting for + // invocations to complete + private volatile boolean explicitStateChange ; // initially false, set true as soon as + // one of activate, hold_request, + // discard_request, or deactivate is called. + + /** activeManagers is the set of POAManagerImpls for which a thread has called + * enter without exit 1 or more times. Once a thread has entered a POAManager, + * it must be able to re-enter the POAManager, even if the manager is HOLDING, + * because state transitions can be deferred until all threads have completed execution + * and called exit(). Without this change, one thread can be blocked on the + * state change method, and another thread that has entered the POAManager once + * can be blocked from re-entry on a nested co-located call. This leads to a + * permanent deadlock between the two threads. See Bug 6586417. + * + * To avoid this, we create a set of active managers, and record which managers + * a particular thread is using. A thread may re-enter any manager in HOLDING state + * once it has entered it for the first time. Note that POAManagerImpl uses the + * default equals and hashCode methods inherited from Object. This is fine, + * because two distinct POAManagerImpl instances always represent distinct + * POAManagerImpls. + * + * This is only a partial solution to the problem, but it should be sufficient for + * the app server, because all EJBs in the app server share the same POAManager. + * The problem in general is that state changes between multiple POAManager and + * invocation threads that make co-located calls to different POAManagers can still + * deadlock. This problem requires a different solution, because the hold_requests + * method may have already returned when the active thread needs to enter the + * holding POAManager, so we can't just let the thread in. I think in this case + * we need to reject the request because it may cause a deadlock. So, checkState + * needs to throw a TRANSIENT exception if it finds that the thread is already active + * in one or more POAManagers, AND it tries to enter a new POAManager. Such exceptions + * should be re-tried by the client, and will succeed after + * the holding POAManagers have been resumed. + * + * Another possible route to fix the app server bug (more globally) is to have the RFM + * suspend method use discard instead of hold. This may be better in some ways, + * but early tests with that approach led to some problems (which I can't recall right now). + * I suspect the issues may have been related to problems with the client-side retry logic, + * but those problems have now been fixed. In any case, we need to fix the POAManager + * issues. + */ + private static ThreadLocal> activeManagers = + new ThreadLocal>() { + @Override + public MultiSet initialValue() { + return new MultiSet() ; + } + } ; + + private String stateToString( State state ) { + switch (state.value()) { + case State._HOLDING : return "HOLDING" ; + case State._ACTIVE : return "ACTIVE" ; + case State._DISCARDING : return "DISCARDING" ; + case State._INACTIVE : return "INACTIVE" ; + } + + return "State[UNKNOWN]" ; + } + + @Override + public int hashCode() + { + return myId ; + } + + @Override + public boolean equals( Object obj ) + { + if (obj == this) { + return true ; + } + + if (!(obj instanceof POAManagerImpl)) { + return false ; + } + + POAManagerImpl other = (POAManagerImpl)obj ; + + return other.myId == myId ; + } + + @Override + public String toString() { + stateLock.readLock().lock(); + try { + return "POAManagerImpl[" + myId + + "," + stateToString(state) + + ",nInvocations=" + nInvocations + + ",nWaiters=" + nWaiters + "]" ; + } finally { + stateLock.readLock().unlock(); + } + } + + @ManagedAttribute + @Description( "The set of POAs managed by this POAManager" ) + Set getManagedPOAs() { + return new HashSet( poas ) ; + } + + @ManagedAttribute + @Description( "Number of active invocations executing in this POAManager" ) + public int numberOfInvocations() { + return nInvocations.get() ; + } + + @ManagedAttribute + @Description( "Number of threads waiting for invocations to complete in this POAManager" ) + public int numberOfWaiters() { + return nWaiters.get() ; + } + + @ManagedAttribute + @Description( "The current state of this POAManager" ) + public String displayState() { + stateLock.readLock().lock(); + try { + return stateToString( state ) ; + } finally { + stateLock.readLock().unlock(); + } + } + + @ManagedAttribute + @Description( "The POAFactory that manages this POAManager" ) + POAFactory getFactory() + { + return factory ; + } + + PIHandler getPIHandler() + { + return pihandler ; + } + + @InfoMethod + private void numWaitersStart( int value ) {} + + @InfoMethod + private void numWaitersEnd( int value ) {} + + @Poa + // Note: caller MUST hold write lock + private void countedWait() + { + try { + int num = nWaiters.incrementAndGet() ; + numWaitersStart( num ) ; + + // 6878245: I can see some sense in the timeout, but why this value? + stateCV.await(num*1000L, TimeUnit.MILLISECONDS); + } catch ( java.lang.InterruptedException ex ) { + // NOP + } finally { + int num = nWaiters.decrementAndGet() ; + numWaitersEnd( num ) ; + } + } + + @InfoMethod + private void nWaiters( int value ) { } + + @Poa + // Note: caller MUST hold write lock + private void notifyWaiters() + { + int num = nWaiters.get() ; + nWaiters( num ) ; + + if (num >0) { + stateCV.signalAll() ; + } + } + + @ManagedAttribute + @NameValue + @Description( "The ID of this POAManager" ) + public int getManagerId() + { + return myId ; + } + + POAManagerImpl( POAFactory factory, PIHandler pih ) + { + this.factory = factory ; + factory.addPoaManager(this); + pihandler = pih ; + myId = factory.newPOAManagerId() ; + state = State.HOLDING; + explicitStateChange = false ; + } + + void addPOA(POAImpl poa) + { + stateLock.writeLock().lock(); + try { + if (state.value() == State._INACTIVE) { + throw wrapper.addPoaInactive() ; + } + + poas.add( poa); + } finally { + stateLock.writeLock().unlock(); + } + } + + void removePOA(POAImpl poa) + { + stateLock.writeLock().lock(); + try { + poas.remove( poa); + if ( poas.isEmpty() ) { + factory.removePoaManager(this); + } + } finally { + stateLock.writeLock().unlock(); + } + } + + @ManagedAttribute + @Description( "The ObjectReferenceTemplate state of this POAManager" ) + public short getORTState() + { + switch (state.value()) { + case State._HOLDING : return HOLDING.value ; + case State._ACTIVE : return ACTIVE.value ; + case State._INACTIVE : return INACTIVE.value ; + case State._DISCARDING : return DISCARDING.value ; + default : return NON_EXISTENT.value ; + } + } + +/**************************************************************************** + * The following four public methods are used to change the POAManager's state. + ****************************************************************************/ + + /** + * activate + * Spec: pages 3-14 thru 3-18 + */ + @Poa + @ManagedOperation + @Description( "Make this POAManager active, so it can handle new requests" ) + public void activate() + throws org.omg.PortableServer.POAManagerPackage.AdapterInactive + { + explicitStateChange = true ; + + stateLock.writeLock().lock() ; + + try { + if ( state.value() == State._INACTIVE ) { + throw new org.omg.PortableServer.POAManagerPackage.AdapterInactive(); + } + + // set the state to ACTIVE + state = State.ACTIVE; + + pihandler.adapterManagerStateChanged( myId, getORTState() ) ; + + // Notify any invocations that were waiting because the previous + // state was HOLDING, as well as notify any threads that were waiting + // inside hold_requests() or discard_requests(). + notifyWaiters(); + } finally { + stateLock.writeLock().unlock() ; + } + } + + /** + * hold_requests + * Spec: pages 3-14 thru 3-18 + */ + @Poa + @ManagedOperation + @Description( "Hold all requests to this POAManager" ) + public void hold_requests(boolean wait_for_completion) + throws org.omg.PortableServer.POAManagerPackage.AdapterInactive + { + explicitStateChange = true ; + + stateLock.writeLock().lock() ; + + try { + if ( state.value() == State._INACTIVE ) { + throw new org.omg.PortableServer.POAManagerPackage.AdapterInactive(); + } + // set the state to HOLDING + state = State.HOLDING; + + pihandler.adapterManagerStateChanged( myId, getORTState() ) ; + + // Notify any threads that were waiting in the wait() inside + // discard_requests. This will cause discard_requests to return + // (which is in conformance with the spec). + notifyWaiters(); + + if ( wait_for_completion ) { + while ( state.value() == State._HOLDING + && nInvocations.get() > 0 ) { + + countedWait() ; + } + } + } finally { + stateLock.writeLock().unlock(); + } + } + + /** + * discard_requests + * Spec: pages 3-14 thru 3-18 + */ + @Poa + @ManagedOperation + @ParameterNames( { "waitForCompletion" } ) + @Description( "Make this POAManager discard all incoming requests" ) + public void discard_requests(boolean wait_for_completion) + throws org.omg.PortableServer.POAManagerPackage.AdapterInactive + { + explicitStateChange = true ; + + stateLock.writeLock().lock(); + + try { + if ( state.value() == State._INACTIVE ) { + throw new org.omg.PortableServer.POAManagerPackage.AdapterInactive(); + } + + // set the state to DISCARDING + state = State.DISCARDING; + + pihandler.adapterManagerStateChanged( myId, getORTState() ) ; + + // Notify any invocations that were waiting because the previous + // state was HOLDING. Those invocations will henceforth be rejected with + // a TRANSIENT exception. Also notify any threads that were waiting + // inside hold_requests(). + // + // Must hold writeLock for this call. + notifyWaiters(); + + if ( wait_for_completion ) { + while ( state.value() == State._DISCARDING + && nInvocations.get() > 0 ) { + + // Must hold writeLock for this call. + countedWait() ; + } + } + } finally { + stateLock.writeLock().unlock(); + } + } + + /** + * deactivate + * Spec: pages 3-14 thru 3-18 + * Note: INACTIVE is a permanent state. + */ + + @Poa + public void deactivate(boolean etherealize_objects, boolean wait_for_completion) + throws org.omg.PortableServer.POAManagerPackage.AdapterInactive + { + stateLock.writeLock().lock(); + + try { + explicitStateChange = true ; + + if ( state.value() == State._INACTIVE ) { + throw new org.omg.PortableServer.POAManagerPackage.AdapterInactive(); + } + + state = State.INACTIVE; + + pihandler.adapterManagerStateChanged( myId, getORTState() ) ; + + // Notify any invocations that were waiting because the previous + // state was HOLDING. Those invocations will then be rejected with + // an OBJ_ADAPTER exception. Also notify any threads that were waiting + // inside hold_requests() or discard_requests(). + notifyWaiters(); + } finally { + stateLock.writeLock().unlock(); + } + + POAManagerDeactivator deactivator = new POAManagerDeactivator( this, + etherealize_objects ) ; + + if (wait_for_completion) { + deactivator.run(); + } else { + Thread thr = new Thread(deactivator) ; + thr.start() ; + } + } + + @Poa + private static class POAManagerDeactivator implements Runnable + { + private boolean etherealize_objects ; + private final POAManagerImpl pmi ; + + @InfoMethod + private void poaManagerDeactivatorCall( + boolean etherealizeObjects, POAManagerImpl pmi ) { } + + @InfoMethod + private void preparingToEtherealize( POAManagerImpl pmi ) { } + + @InfoMethod + private void removeAndClear( POAManagerImpl pmi ) { } + + POAManagerDeactivator( POAManagerImpl pmi, boolean etherealize_objects ) + { + this.etherealize_objects = etherealize_objects ; + this.pmi = pmi ; + } + + @Poa + public void run() + { + pmi.stateLock.writeLock().lock(); + try { + poaManagerDeactivatorCall( etherealize_objects, pmi ) ; + while ( pmi.nInvocations.get() > 0 ) { + pmi.countedWait() ; + } + } finally { + pmi.stateLock.writeLock().unlock(); + } + + if (etherealize_objects) { + Set copyOfPOAs ; + + // Make sure that poas cannot change while we copy it! + pmi.stateLock.readLock().lock(); + try { + preparingToEtherealize( pmi ) ; + copyOfPOAs = new HashSet( pmi.poas ) ; + } finally { + pmi.stateLock.readLock().unlock(); + } + + for (POAImpl poa : copyOfPOAs) { + // Each RETAIN+USE_SERVANT_MGR poa + // must call etherealize for all its objects + poa.etherealizeAll(); + } + + pmi.stateLock.writeLock().lock(); + try { + removeAndClear( pmi ) ; + + pmi.factory.removePoaManager(pmi); + pmi.poas.clear(); + } finally { + pmi.stateLock.writeLock().unlock(); + } + } + } + } + + /** + * Added according to the spec CORBA V2.3; this returns the + * state of the POAManager + */ + + public org.omg.PortableServer.POAManagerPackage.State get_state () { + return state; + } + +/**************************************************************************** + * The following methods are used on the invocation path. + ****************************************************************************/ + + @InfoMethod + private void activeManagers( MultiSet am ) { } + + @InfoMethod + private void alreadyActive( POAManagerImpl pm ) { } + + @InfoMethod + private void activeInDifferentPoaManager() { } + + @Poa + private void checkState() + { + MultiSet am = activeManagers.get() ; + activeManagers( am ) ; + + stateLock.readLock().lock(); + try { + while ( state.value() != State._ACTIVE ) { + switch ( state.value() ) { + case State._HOLDING: + // Never block a thread that is already active in this POAManager. + if (am.contains( this )) { + alreadyActive( this ) ; + + return ; + } else { + if (am.size() == 0) { + if (state.value() == State._HOLDING) { + // Can't upgrade, so drop the read lock, + // then separately acquite the write lock. + stateLock.readLock().unlock(); + stateLock.writeLock().lock(); + } + + try { + while ( state.value() == State._HOLDING ) { + countedWait() ; + } + } finally { + // downgrade to read lock + stateLock.writeLock().unlock(); + stateLock.readLock().lock(); + } + } else { + activeInDifferentPoaManager() ; + + // This thread is already active in one or more other POAManagers. + // This could cause a deadlock, so throw a TRANSIENT exception + // to prevent it. + throw factory.getWrapper().poaManagerMightDeadlock() ; + } + } + break; + + case State._DISCARDING: + throw factory.getWrapper().poaDiscarding() ; + + case State._INACTIVE: + throw factory.getWrapper().poaInactive() ; + } + } + } finally { + stateLock.readLock().unlock(); + } + } + + @InfoMethod + private void addingThreadToActiveManagers( POAManagerImpl pmi ) { } + + @InfoMethod + private void removingThreadFromActiveManagers( POAManagerImpl pmi ) { } + + @Poa + void enter() + { + checkState(); + nInvocations.getAndIncrement() ; + + activeManagers.get().add( this ) ; + addingThreadToActiveManagers( this ) ; + } + + @Poa + void exit() + { + try { + activeManagers.get().remove( this ) ; + removingThreadFromActiveManagers( this ) ; + } finally { + if ( nInvocations.decrementAndGet() == 0 ) { + // Note: this is essentially notifyWaiters, but + // we cannot afford to acquire the writeLock unless + // there actually are waiters on the lock (GF issue 14348). + // Note that a spurious wakeup is possible here, if + // an invocation comes in between nInvocation and nWaiters + // reads, but that's OK, because the looped condition checks + // around countedWait will simply wait again. + final int num = nWaiters.get() ; + nWaiters( num ) ; + + if (num >0) { + stateLock.writeLock().lock(); + + try { + stateCV.signalAll() ; + } finally { + stateLock.writeLock().unlock(); + } + } + } + } + } + + /** Activate the POAManager if no explicit state change has ever been + * previously invoked. + */ + public void implicitActivation() + { + if (!explicitStateChange) { + try { + activate(); + } catch (org.omg.PortableServer.POAManagerPackage.AdapterInactive ai) { + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediator.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediator.java new file mode 100644 index 000000000..e5d053f12 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediator.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.gmbal.ManagedData; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ForwardRequest ; + +import org.omg.PortableServer.POAPackage.ObjectAlreadyActive ; +import org.omg.PortableServer.POAPackage.ServantAlreadyActive ; +import org.omg.PortableServer.POAPackage.ServantNotActive ; +import org.omg.PortableServer.POAPackage.NoServant ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; + +/** POAPolicyMediator defines an interface to which the POA delegates all + * policy specific operations. This permits code paths for different + * policies to be optimized by creating the correct code at POA creation + * time. Also note that as much as possible, this interface does not + * do any concurrency control, except as noted. The POA is responsible + * for concurrency control. + */ +@ManagedData +@Description( "Handles the Policy-specific parts of the POA") +public interface POAPolicyMediator { + /** Return the policies object that was used to create this + * POAPolicyMediator. + */ + @ManagedAttribute + @Description( "The policies of this POA") + Policies getPolicies() ; + + /** Return the subcontract ID to use in the IIOP profile in IORs + * created by this POAPolicyMediator's POA. This is initialized + * according to the policies and the POA used to construct this + * POAPolicyMediator in the POAPolicyMediatorFactory. + */ + @ManagedAttribute + @Description( "This POA's subcontract ID") + int getScid() ; + + /** Return the server ID to use in the IIOP profile in IORs + * created by this POAPolicyMediator's POA. This is initialized + * according to the policies and the POA used to construct this + * POAPolicyMediator in the POAPolicyMediatorFactory. + */ + @ManagedAttribute + @Description( "This POA's server ID") + int getServerId() ; + + /** Get the servant to use for an invocation with the + * given id and operation. + * @param id the object ID for which we are requesting a servant + * @param operation the name of the operation to be performed on + * the servant + * @return the resulting Servant. + */ + java.lang.Object getInvocationServant( byte[] id, + String operation ) throws ForwardRequest ; + + /** Release a servant that was obtained from getInvocationServant. + */ + void returnServant() ; + + /** Etherealize all servants associated with this POAPolicyMediator. + * Does nothing if the retention policy is non-retain. + */ + void etherealizeAll() ; + + /** Delete everything in the active object map. + */ + void clearAOM() ; + + /** Return the servant manager. Will throw WrongPolicy + * if the request processing policy is not USE_SERVANT_MANAGER. + */ + ServantManager getServantManager() throws WrongPolicy ; + + /** Set the servant manager. Will throw WrongPolicy + * if the request processing policy is not USE_SERVANT_MANAGER. + */ + void setServantManager( ServantManager servantManager ) throws WrongPolicy ; + + /** Return the default servant. Will throw WrongPolicy + * if the request processing policy is not USE_DEFAULT_SERVANT. + */ + Servant getDefaultServant() throws NoServant, WrongPolicy ; + + /** Set the default servant. Will throw WrongPolicy + * if the request processing policy is not USE_DEFAULT_SERVANT. + */ + void setDefaultServant( Servant servant ) throws WrongPolicy ; + + void activateObject( byte[] id, Servant servant ) + throws ObjectAlreadyActive, ServantAlreadyActive, WrongPolicy ; + + /** Deactivate the object that is associated with the given id. + * Returns the servant for id. + */ + Servant deactivateObject( byte[] id ) throws ObjectNotActive, WrongPolicy ; + + /** Allocate a new, unique system ID. Requires the ID assignment policy + * to be SYSTEM. + */ + byte[] newSystemId() throws WrongPolicy ; + + byte[] servantToId( Servant servant ) throws ServantNotActive, WrongPolicy ; + + Servant idToServant( byte[] id ) throws ObjectNotActive, WrongPolicy ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorBase.java new file mode 100644 index 000000000..bf489123e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorBase.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + + +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; + +import com.sun.corba.ee.spi.extension.ServantCachingPolicy ; +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.impl.misc.ORBUtility ; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.logging.POASystemException; + +/** Implementation of POARequesHandler that provides policy specific + * operations on the POA. + */ +public abstract class POAPolicyMediatorBase implements POAPolicyMediator { + protected static final POASystemException wrapper = + POASystemException.self ; + protected static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + protected POAImpl poa ; + protected ORB orb ; + + private int sysIdCounter ; + private Policies policies ; + private DelegateImpl delegateImpl ; + + private int serverid ; + private int scid ; + + protected boolean isImplicit ; + protected boolean isUnique ; + protected boolean isSystemId ; + + public final Policies getPolicies() + { + return policies ; + } + + public final int getScid() + { + return scid ; + } + + public final int getServerId() + { + return serverid ; + } + + POAPolicyMediatorBase( Policies policies, POAImpl poa ) + { + if (policies.isSingleThreaded()) { + throw wrapper.singleThreadNotSupported(); + } + + POAManagerImpl poam = (POAManagerImpl)(poa.the_POAManager()) ; + POAFactory poaf = poam.getFactory() ; + delegateImpl = (DelegateImpl)(poaf.getDelegateImpl()) ; + this.policies = policies ; + this.poa = poa ; + orb = poa.getORB() ; + + switch (policies.servantCachingLevel()) { + case ServantCachingPolicy.NO_SERVANT_CACHING : + scid = ORBConstants.TRANSIENT_SCID ; + break ; + case ServantCachingPolicy.FULL_SEMANTICS : + scid = ORBConstants.SC_TRANSIENT_SCID ; + break ; + case ServantCachingPolicy.INFO_ONLY_SEMANTICS : + scid = ORBConstants.IISC_TRANSIENT_SCID ; + break ; + case ServantCachingPolicy.MINIMAL_SEMANTICS : + scid = ORBConstants.MINSC_TRANSIENT_SCID ; + break ; + } + + if ( policies.isTransient() ) { + serverid = orb.getTransientServerId(); + } else { + serverid = orb.getORBData().getPersistentServerId(); + scid = ORBConstants.makePersistent( scid ) ; + } + + isImplicit = policies.isImplicitlyActivated() ; + isUnique = policies.isUniqueIds() ; + isSystemId = policies.isSystemAssignedIds() ; + + sysIdCounter = 0 ; + } + + public final java.lang.Object getInvocationServant( byte[] id, + String operation ) throws ForwardRequest + { + java.lang.Object result = internalGetServant( id, operation ) ; + + return result ; + } + + // Create a delegate and stick it in the servant. + // This delegate is needed during dispatch for the ObjectImpl._orb() + // method to work. + protected final void setDelegate(Servant servant, byte[] id) + { + //This new servant delegate no longer needs the id for + // its initialization. + servant._set_delegate(delegateImpl); + } + + public synchronized byte[] newSystemId() throws WrongPolicy + { + if (!isSystemId) { + throw new WrongPolicy(); + } + + byte[] array = new byte[8]; + ORBUtility.intToBytes(++sysIdCounter, array, 0); + ORBUtility.intToBytes( poa.getPOAId(), array, 4); + return array; + } + + protected abstract java.lang.Object internalGetServant( byte[] id, + String operation ) throws ForwardRequest ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorBase_R.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorBase_R.java new file mode 100644 index 000000000..d502fb3e2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorBase_R.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import org.omg.PortableServer.Servant ; + +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ServantNotActive ; +import org.omg.PortableServer.POAPackage.ServantAlreadyActive ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; +import org.omg.PortableServer.POAPackage.ObjectAlreadyActive ; + +import com.sun.corba.ee.spi.trace.Poa; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Poa +public abstract class POAPolicyMediatorBase_R extends POAPolicyMediatorBase { + protected ActiveObjectMap activeObjectMap ; + + POAPolicyMediatorBase_R( Policies policies, POAImpl poa ) + { + super( policies, poa ) ; + + // assert policies.retainServants() && policies.useActiveObjectMapOnly() + if (!policies.retainServants()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + + activeObjectMap = ActiveObjectMap.create(poa, !isUnique); + } + + public void returnServant() + { + // NO-OP + } + + public void clearAOM() + { + activeObjectMap.clear() ; + activeObjectMap = null ; + } + + protected Servant internalKeyToServant( ActiveObjectMap.Key key ) + { + AOMEntry entry = activeObjectMap.get(key); + if (entry == null) { + return null; + } + + return activeObjectMap.getServant( entry ) ; + } + + protected Servant internalIdToServant( byte[] id ) + { + ActiveObjectMap.Key key = new ActiveObjectMap.Key( id ) ; + return internalKeyToServant( key ) ; + } + + @Poa + protected void activateServant( ActiveObjectMap.Key key, AOMEntry entry, Servant servant ) + { + setDelegate(servant, key.id() ); + + activeObjectMap.putServant( servant, entry ) ; + + POAManagerImpl pm = (POAManagerImpl)poa.the_POAManager() ; + POAFactory factory = pm.getFactory() ; + factory.registerPOAForServant(poa, servant); + } + + @Poa + public final void activateObject(byte[] id, Servant servant) + throws WrongPolicy, ServantAlreadyActive, ObjectAlreadyActive + { + if (isUnique && activeObjectMap.contains(servant)) { + throw new ServantAlreadyActive(); + } + ActiveObjectMap.Key key = new ActiveObjectMap.Key( id ) ; + + AOMEntry entry = activeObjectMap.get( key ) ; + + // Check for an ObjectAlreadyActive error + entry.activateObject() ; + + activateServant( key, entry, servant ) ; + } + + @Poa + public Servant deactivateObject( byte[] id ) + throws ObjectNotActive, WrongPolicy + { + ActiveObjectMap.Key key = new ActiveObjectMap.Key( id ) ; + return deactivateObject( key ) ; + } + + @Poa + protected void deactivateHelper( ActiveObjectMap.Key key, AOMEntry entry, + Servant s ) throws ObjectNotActive, WrongPolicy + { + // Default does nothing, but the USE_SERVANT_MANAGER case + // must handle etherealization + + activeObjectMap.remove(key); + + POAManagerImpl pm = (POAManagerImpl)poa.the_POAManager() ; + POAFactory factory = pm.getFactory() ; + factory.unregisterPOAForServant(poa, s); + } + + @InfoMethod + private void deactivatingObject( Servant s, POAImpl poa ) { } + + @Poa + public Servant deactivateObject( ActiveObjectMap.Key key ) + throws ObjectNotActive, WrongPolicy { + + AOMEntry entry = activeObjectMap.get(key); + if (entry == null) { + throw new ObjectNotActive(); + } + + Servant s = activeObjectMap.getServant( entry ) ; + if (s == null) { + throw new ObjectNotActive(); + } + + deactivatingObject( s, poa ) ; + + deactivateHelper( key, entry, s ) ; + + return s ; + } + + @Poa + public byte[] servantToId( Servant servant ) throws ServantNotActive, WrongPolicy + { + if (!isUnique && !isImplicit) { + throw new WrongPolicy(); + } + + if (isUnique) { + ActiveObjectMap.Key key = activeObjectMap.getKey(servant); + if (key != null) { + return key.id(); + } + } + + // assert !isUnique || (servant not in activateObjectMap) + + if (isImplicit) { + try { + byte[] id = newSystemId(); + activateObject(id, servant); + return id; + } catch (ObjectAlreadyActive oaa) { + throw wrapper.servantToIdOaa(oaa); + } catch (ServantAlreadyActive s) { + throw wrapper.servantToIdSaa(s); + } catch (WrongPolicy w) { + throw wrapper.servantToIdWp(w); + } + } + + throw new ServantNotActive(); + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorFactory.java new file mode 100644 index 000000000..dd606b1be --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import com.sun.corba.ee.spi.logging.POASystemException; + +abstract class POAPolicyMediatorFactory { + private static final POASystemException wrapper = + POASystemException.self ; + + // create an appropriate policy mediator based on the policies. + // Note that the policies object has already been validated before + // this call, so it can only contain valid combinations of POA policies. + static POAPolicyMediator create( Policies policies, POAImpl poa ) + { + if (policies.retainServants()) { + if (policies.useActiveMapOnly()) { + return new POAPolicyMediatorImpl_R_AOM(policies, poa); + } else if (policies.useDefaultServant()) { + return new POAPolicyMediatorImpl_R_UDS(policies, poa); + } else if (policies.useServantManager()) { + return new POAPolicyMediatorImpl_R_USM(policies, poa); + } else { + throw wrapper.pmfCreateRetain(); + } + } else { + if (policies.useDefaultServant()) { + return new POAPolicyMediatorImpl_NR_UDS(policies, poa); + } + else if (policies.useServantManager()) { + return new POAPolicyMediatorImpl_NR_USM(policies, poa); + } else { + throw wrapper.pmfCreateNonRetain(); + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_NR_UDS.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_NR_UDS.java new file mode 100644 index 000000000..89426318d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_NR_UDS.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; +import org.omg.PortableServer.POAPackage.ServantNotActive ; +import org.omg.PortableServer.POAPackage.ObjectAlreadyActive ; +import org.omg.PortableServer.POAPackage.ServantAlreadyActive ; +import org.omg.PortableServer.POAPackage.NoServant ; + +/** Implementation of POAPolicyMediator that provides policy specific + * operations on the POA. + */ +public class POAPolicyMediatorImpl_NR_UDS extends POAPolicyMediatorBase { + private Servant defaultServant ; + + POAPolicyMediatorImpl_NR_UDS( Policies policies, POAImpl poa ) + { + super( policies, poa ) ; + + // assert !policies.retainServants() && policies.useDefaultServant() + if (policies.retainServants()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + + if (!policies.useDefaultServant()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + + defaultServant = null ; + } + + protected java.lang.Object internalGetServant( byte[] id, + String operation ) throws ForwardRequest { + + poa.readLock() ; + try { + if (defaultServant == null) { + throw wrapper.poaNoDefaultServant(); + } + + return defaultServant; + } finally { + poa.readUnlock() ; + } + } + + public void returnServant() + { + // NO-OP + } + + public void etherealizeAll() + { + // NO-OP + } + + public void clearAOM() + { + // NO-OP + } + + public ServantManager getServantManager() throws WrongPolicy + { + throw new WrongPolicy(); + } + + public void setServantManager( ServantManager servantManager ) throws WrongPolicy + { + throw new WrongPolicy(); + } + + public Servant getDefaultServant() throws NoServant, WrongPolicy + { + if (defaultServant == null) { + throw new NoServant(); + } + return defaultServant; + } + + public void setDefaultServant( Servant servant ) throws WrongPolicy + { + this.defaultServant = servant; + setDelegate(defaultServant, "DefaultServant".getBytes()); + } + + public final void activateObject(byte[] id, Servant servant) + throws WrongPolicy, ServantAlreadyActive, ObjectAlreadyActive + { + throw new WrongPolicy(); + } + + public Servant deactivateObject( byte[] id ) throws ObjectNotActive, WrongPolicy + { + throw new WrongPolicy(); + } + + public byte[] servantToId( Servant servant ) throws ServantNotActive, WrongPolicy + { + throw new WrongPolicy(); + } + + public Servant idToServant( byte[] id ) + throws WrongPolicy, ObjectNotActive + { + if (defaultServant != null) { + return defaultServant; + } + + throw new ObjectNotActive() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_NR_USM.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_NR_USM.java new file mode 100644 index 000000000..517a3234a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_NR_USM.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ServantLocator ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POAPackage.NoServant ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; +import org.omg.PortableServer.POAPackage.ServantNotActive ; +import org.omg.PortableServer.POAPackage.ObjectAlreadyActive ; +import org.omg.PortableServer.POAPackage.ServantAlreadyActive ; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; + + +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.impl.oa.NullServantImpl ; + +/** Implementation of POARequesHandler that provides policy specific + * operations on the POA. + */ +public class POAPolicyMediatorImpl_NR_USM extends POAPolicyMediatorBase { + // XXX How do we protect locator from multi-threaded access? + private ServantLocator locator ; + + POAPolicyMediatorImpl_NR_USM( Policies policies, POAImpl poa ) + { + super( policies, poa ) ; + + // assert !policies.retainServants() && policies.useServantManager() + if (policies.retainServants()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + + if (!policies.useServantManager()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + + locator = null ; + } + + protected java.lang.Object internalGetServant( byte[] id, + String operation ) throws ForwardRequest + { + if (locator == null) { + throw wrapper.poaNoServantManager(); + } + + CookieHolder cookieHolder = orb.peekInvocationInfo().getCookieHolder() ; + + java.lang.Object servant = locator.preinvoke(id, poa, operation, + cookieHolder); + + if (servant == null) { + servant = new NullServantImpl(omgWrapper.nullServantReturned()); + } else { + setDelegate((Servant) servant, id); + } + + + return servant; + } + + public void returnServant() + { + OAInvocationInfo info = orb.peekInvocationInfo(); + + // 6878245: added info == null check. + if (locator == null || info == null) { + return; + } + + locator.postinvoke(info.id(), (POA)(info.oa()), + info.getOperation(), info.getCookieHolder().value, + (Servant)(info.getServantContainer()) ); + } + + public void etherealizeAll() + { + // NO-OP + } + + public void clearAOM() + { + // NO-OP + } + + public ServantManager getServantManager() throws WrongPolicy + { + return locator ; + } + + public void setServantManager( ServantManager servantManager ) throws WrongPolicy + { + if (locator != null) { + throw wrapper.servantManagerAlreadySet(); + } + + if (servantManager instanceof ServantLocator) { + locator = (ServantLocator) servantManager; + } else { + throw wrapper.servantManagerBadType(); + } + } + + public Servant getDefaultServant() throws NoServant, WrongPolicy + { + throw new WrongPolicy(); + } + + public void setDefaultServant( Servant servant ) throws WrongPolicy + { + throw new WrongPolicy(); + } + + public final void activateObject(byte[] id, Servant servant) + throws WrongPolicy, ServantAlreadyActive, ObjectAlreadyActive + { + throw new WrongPolicy(); + } + + public Servant deactivateObject( byte[] id ) throws ObjectNotActive, WrongPolicy + { + throw new WrongPolicy(); + } + + public byte[] servantToId( Servant servant ) throws ServantNotActive, WrongPolicy + { + throw new WrongPolicy(); + } + + public Servant idToServant( byte[] id ) + throws WrongPolicy, ObjectNotActive + { + throw new WrongPolicy(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_AOM.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_AOM.java new file mode 100644 index 000000000..2aa0d7721 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_AOM.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; +import org.omg.PortableServer.POAPackage.NoServant ; + +import com.sun.corba.ee.impl.oa.NullServantImpl ; + +/** Implementation of POARequesHandler that provides policy specific + * operations on the POA in the case: + *

      + *
    • retain
    • + *
    • useActiveObjectMapOnly
    • + *
    + */ +public class POAPolicyMediatorImpl_R_AOM extends POAPolicyMediatorBase_R { + POAPolicyMediatorImpl_R_AOM( Policies policies, POAImpl poa ) + { + // assert policies.retainServants() + super( policies, poa ) ; + + // policies.useActiveObjectMapOnly() + if (!policies.useActiveMapOnly()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + } + + protected java.lang.Object internalGetServant( byte[] id, + String operation ) throws ForwardRequest + { + poa.lock() ; + try { + java.lang.Object servant = internalIdToServant( id ) ; + if (servant == null) { + servant = new NullServantImpl(wrapper.nullServant()); + } + return servant ; + } finally { + poa.unlock() ; + } + } + + public void etherealizeAll() { + // NO-OP + } + + public ServantManager getServantManager() throws WrongPolicy { + throw new WrongPolicy(); + } + + public void setServantManager( ServantManager servantManager ) + throws WrongPolicy { + throw new WrongPolicy(); + } + + public Servant getDefaultServant() throws NoServant, WrongPolicy { + throw new WrongPolicy(); + } + + public void setDefaultServant( Servant servant ) throws WrongPolicy { + throw new WrongPolicy(); + } + + public Servant idToServant( byte[] id ) + throws WrongPolicy, ObjectNotActive { + Servant s = internalIdToServant( id ) ; + + if (s == null) { + throw new ObjectNotActive(); + } else { + return s; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_UDS.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_UDS.java new file mode 100644 index 000000000..386fea23a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_UDS.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; +import org.omg.PortableServer.POAPackage.NoServant ; + +/** Implementation of POARequesHandler that provides policy specific + * operations on the POA. + */ +public class POAPolicyMediatorImpl_R_UDS extends POAPolicyMediatorBase_R { + private Servant defaultServant ; + + POAPolicyMediatorImpl_R_UDS( Policies policies, POAImpl poa ) { + // assert policies.retainServants() + super( policies, poa ) ; + defaultServant = null ; + + // policies.useDefaultServant() + if (!policies.useDefaultServant()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } } + + protected java.lang.Object internalGetServant( byte[] id, + String operation ) throws ForwardRequest { + + poa.readLock() ; + try { + Servant servant = internalIdToServant( id ) ; + if (servant == null) { + servant = defaultServant; + } + + if (servant == null) { + throw wrapper.poaNoDefaultServant(); + } + + return servant ; + } finally { + poa.readUnlock(); + } + } + + public void etherealizeAll() { + // NO-OP + } + + public ServantManager getServantManager() throws WrongPolicy { + throw new WrongPolicy(); + } + + public void setServantManager( + ServantManager servantManager ) throws WrongPolicy { + throw new WrongPolicy(); + } + + public Servant getDefaultServant() throws NoServant, WrongPolicy { + if (defaultServant == null) { + throw new NoServant(); + } else { + return defaultServant; + } + } + + public void setDefaultServant( Servant servant ) throws WrongPolicy { + defaultServant = servant; + setDelegate(defaultServant, "DefaultServant".getBytes()); + } + + public Servant idToServant( byte[] id ) + throws WrongPolicy, ObjectNotActive { + + ActiveObjectMap.Key key = new ActiveObjectMap.Key( id ) ; + Servant s = internalKeyToServant(key); + + if (s == null) { + if (defaultServant != null) { + s = defaultServant; + } + } + + if (s == null) { + throw new ObjectNotActive(); + } + + return s; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java new file mode 100644 index 000000000..57a812ee8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java @@ -0,0 +1,341 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa ; + +import java.util.Set ; + +import org.omg.CORBA.SystemException ; + +import org.omg.PortableServer.ServantActivator ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantManager ; +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ObjectNotActive ; +import org.omg.PortableServer.POAPackage.NoServant ; + +import com.sun.corba.ee.impl.oa.NullServantImpl ; + +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.NullServant ; +import com.sun.corba.ee.spi.trace.Poa; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** Implementation of POARequesHandler that provides policy specific + * operations on the POA. + */ +@Poa +public class POAPolicyMediatorImpl_R_USM extends POAPolicyMediatorBase_R { + protected ServantActivator activator ; + + POAPolicyMediatorImpl_R_USM( Policies policies, POAImpl poa ) + { + // assert policies.retainServants() + super( policies, poa ) ; + activator = null ; + + if (!policies.useServantManager()) { + throw wrapper.policyMediatorBadPolicyInFactory(); + } + } + + /* This handles a rather subtle bug (4939892). The problem is that + * enter will wait on the entry if it is being etherealized. When the + * deferred state transition completes, the entry is no longer in the + * AOM, and so we need to get a new entry, otherwise activator.incarnate + * will be called twice, once for the old entry, and again when a new + * entry is created. This fix also required extending the FSM StateEngine + * to allow actions to throw exceptions, and adding a new state in the + * AOMEntry FSM to detect this condition. + */ + private AOMEntry enterEntry( ActiveObjectMap.Key key ) + { + AOMEntry result = null ; + boolean failed ; + do { + failed = false ; + result = activeObjectMap.get(key) ; + + try { + result.enter() ; + } catch (Exception exc) { + failed = true ; + } + } while (failed) ; + + return result ; + } + + @InfoMethod + private void servantAlreadyActivated() { } + + @InfoMethod + private void upcallToIncarnate() { } + + @InfoMethod + private void incarnateFailed() { } + + @InfoMethod + private void incarnateComplete() { } + + @InfoMethod + private void servantAlreadyAssignedToID() { } + + @Poa + protected java.lang.Object internalGetServant( byte[] id, + String operation ) throws ForwardRequest { + + poa.lock() ; + try { + ActiveObjectMap.Key key = new ActiveObjectMap.Key( id ) ; + AOMEntry entry = enterEntry(key) ; + java.lang.Object servant = activeObjectMap.getServant( entry ) ; + if (servant != null) { + servantAlreadyActivated() ; + return servant ; + } + + if (activator == null) { + entry.incarnateFailure() ; + throw wrapper.poaNoServantManager() ; + } + + // Drop the POA lock during the incarnate call and + // re-acquire it afterwards. The entry state machine + // prevents more than one thread from executing the + // incarnate method at a time within the same POA. + try { + upcallToIncarnate() ; + + poa.unlock() ; + + servant = activator.incarnate(id, poa); + + if (servant == null) { + servant = new NullServantImpl( + omgWrapper.nullServantReturned()); + } + } catch (ForwardRequest freq) { + throw freq ; + } catch (SystemException exc) { + throw exc ; + } catch (Throwable exc) { + throw wrapper.poaServantActivatorLookupFailed( exc ) ; + } finally { + poa.lock() ; + + // servant == null means incarnate threw an exception, + // while servant instanceof NullServant means incarnate returned a + // null servant. Either case is an incarnate failure to the + // entry state machine. + if ((servant == null) || (servant instanceof NullServant)) { + incarnateFailed() ; + + // XXX Does the AOM leak in this case? Yes, + // but the problem is hard to fix. There may be + // a number of threads waiting for the state to change + // from INCARN to something else, which is VALID or + // INVALID, depending on the incarnate result. + // The activeObjectMap.get() call above creates an + // ActiveObjectMap.Entry if one does not already exist, + // and stores it in the keyToEntry map in the AOM. + entry.incarnateFailure() ; + } else { + // here check for unique_id policy, and if the servant + // is already registered for a different ID, then throw + // OBJ_ADAPTER exception, else activate it. Section 11.3.5.1 + // 99-10-07.pdf + if (isUnique) { + // check if the servant already is associated with some id + if (activeObjectMap.contains((Servant)servant)) { + servantAlreadyAssignedToID() ; + entry.incarnateFailure() ; + throw wrapper.poaServantNotUnique() ; + } + } + + incarnateComplete() ; + + entry.incarnateComplete() ; + activateServant(key, entry, (Servant)servant); + } + } + + return servant ; + } finally { + poa.unlock() ; + } + } + + @Poa + @Override + public void returnServant() { + poa.lock() ; + try { + OAInvocationInfo info = orb.peekInvocationInfo(); + // 6878245: added null check. + if (info == null) { + return ; + } + byte[] id = info.id() ; + ActiveObjectMap.Key key = new ActiveObjectMap.Key( id ) ; + AOMEntry entry = activeObjectMap.get( key ) ; + entry.exit() ; + } finally { + poa.unlock(); + } + } + + @Poa + public void etherealizeAll() { + if (activator != null) { + Set keySet = activeObjectMap.keySet() ; + + // Copy the elements in the set to an array to avoid + // changes in the set due to concurrent modification + @SuppressWarnings("unchecked") + ActiveObjectMap.Key[] keys = + keySet.toArray(new ActiveObjectMap.Key[keySet.size()]) ; + + for (int ctr=0; ctr policyMap = new HashMap() ; + + @ManagedAttribute + @Description( "The policies") + Map getPolicies() { + return new HashMap( policyMap ) ; + } + + public static final Policies defaultPolicies + = new Policies() ; + + public static final Policies rootPOAPolicies + = new Policies( + ThreadPolicyValue._ORB_CTRL_MODEL, + LifespanPolicyValue._TRANSIENT, + IdUniquenessPolicyValue._UNIQUE_ID, + IdAssignmentPolicyValue._SYSTEM_ID, + ImplicitActivationPolicyValue._IMPLICIT_ACTIVATION, + ServantRetentionPolicyValue._RETAIN, + RequestProcessingPolicyValue._USE_ACTIVE_OBJECT_MAP_ONLY ) ; + + private int[] poaPolicyValues ; + + private int getPolicyValue( int id ) + { + return poaPolicyValues[ id - MIN_POA_POLICY_ID ] ; + } + + private void setPolicyValue( int id, int value ) + { + poaPolicyValues[ id - MIN_POA_POLICY_ID ] = value ; + } + + private Policies( + int threadModel, + int lifespan, + int idUniqueness, + int idAssignment, + int implicitActivation, + int retention, + int requestProcessing ) + { + poaPolicyValues = new int[] { + threadModel, + lifespan, + idUniqueness, + idAssignment, + implicitActivation, + retention, + requestProcessing }; + } + + private Policies() { + this( ThreadPolicyValue._ORB_CTRL_MODEL, + LifespanPolicyValue._TRANSIENT, + IdUniquenessPolicyValue._UNIQUE_ID, + IdAssignmentPolicyValue._SYSTEM_ID, + ImplicitActivationPolicyValue._NO_IMPLICIT_ACTIVATION, + ServantRetentionPolicyValue._RETAIN, + RequestProcessingPolicyValue._USE_ACTIVE_OBJECT_MAP_ONLY ) ; + } + + @Override + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append( "Policies[" ) ; + boolean first = true ; + for ( Policy p : policyMap.values() ) { + if (first) + first = false ; + else + buffer.append( "," ) ; + + buffer.append( p.toString() ) ; + } + buffer.append( "]" ) ; + return buffer.toString() ; + } + + /* Returns the integer value of the POA policy, if this is a + * POA policy, otherwise returns -1. + */ + private int getPOAPolicyValue( Policy policy) + { + if (policy instanceof ThreadPolicy) { + return ((ThreadPolicy) policy).value().value(); + } else if (policy instanceof LifespanPolicy) { + return ((LifespanPolicy) policy).value().value(); + } else if (policy instanceof IdUniquenessPolicy) { + return ((IdUniquenessPolicy) policy).value().value(); + } else if (policy instanceof IdAssignmentPolicy) { + return ((IdAssignmentPolicy) policy).value().value(); + } else if (policy instanceof ServantRetentionPolicy) { + return ((ServantRetentionPolicy) policy).value().value(); + } else if (policy instanceof RequestProcessingPolicy) { + return ((RequestProcessingPolicy) policy).value().value(); + } else if (policy instanceof ImplicitActivationPolicy) { + return ((ImplicitActivationPolicy) policy).value().value(); + } else + return -1 ; + } + + /** If any errors were found, throw INVALID_POLICY with the smallest + * index of any offending policy. + */ + private void checkForPolicyError( BitSet errorSet ) throws InvalidPolicy + { + for (short ctr=0; ctr= 0) { + setPolicyValue( key, POAPolicyValue ) ; + + // if the value of this POA policy was previously set to a + // different value than the current value given in + // POAPolicyValue, record an error. + if ((prev != null) && + (getPOAPolicyValue( prev ) != POAPolicyValue)) + errorSet.set( i ) ; + } + } + + // Check for bad policy combinations + + // NON_RETAIN requires USE_DEFAULT_SERVANT or USE_SERVANT_MANAGER + if (!retainServants() && useActiveMapOnly() ) { + addToErrorSet( policies, SERVANT_RETENTION_POLICY_ID.value, + errorSet ) ; + addToErrorSet( policies, REQUEST_PROCESSING_POLICY_ID.value, + errorSet ) ; + } + + // IMPLICIT_ACTIVATION requires SYSTEM_ID and RETAIN + if (isImplicitlyActivated()) { + if (!retainServants()) { + addToErrorSet( policies, IMPLICIT_ACTIVATION_POLICY_ID.value, + errorSet ) ; + addToErrorSet( policies, SERVANT_RETENTION_POLICY_ID.value, + errorSet ) ; + } + + if (!isSystemAssignedIds()) { + addToErrorSet( policies, IMPLICIT_ACTIVATION_POLICY_ID.value, + errorSet ) ; + addToErrorSet( policies, ID_ASSIGNMENT_POLICY_ID.value, + errorSet ) ; + } + } + + checkForPolicyError( errorSet ) ; + } + + public Policy get_effective_policy( int type ) + { + return policyMap.get(type) ; + } + + /* Thread Policies */ + public final boolean isOrbControlledThreads() { + return getPolicyValue( THREAD_POLICY_ID.value ) == + ThreadPolicyValue._ORB_CTRL_MODEL; + } + public final boolean isSingleThreaded() { + return getPolicyValue( THREAD_POLICY_ID.value ) == + ThreadPolicyValue._SINGLE_THREAD_MODEL; + } + + /* Lifespan */ + public final boolean isTransient() { + return getPolicyValue( LIFESPAN_POLICY_ID.value ) == + LifespanPolicyValue._TRANSIENT; + } + public final boolean isPersistent() { + return getPolicyValue( LIFESPAN_POLICY_ID.value ) == + LifespanPolicyValue._PERSISTENT; + } + + /* ID Uniqueness */ + public final boolean isUniqueIds() { + return getPolicyValue( ID_UNIQUENESS_POLICY_ID.value ) == + IdUniquenessPolicyValue._UNIQUE_ID; + } + public final boolean isMultipleIds() { + return getPolicyValue( ID_UNIQUENESS_POLICY_ID.value ) == + IdUniquenessPolicyValue._MULTIPLE_ID; + } + + /* ID Assignment */ + public final boolean isUserAssignedIds() { + return getPolicyValue( ID_ASSIGNMENT_POLICY_ID.value ) == + IdAssignmentPolicyValue._USER_ID; + } + public final boolean isSystemAssignedIds() { + return getPolicyValue( ID_ASSIGNMENT_POLICY_ID.value ) == + IdAssignmentPolicyValue._SYSTEM_ID; + } + + /* Servant Rentention */ + public final boolean retainServants() { + return getPolicyValue( SERVANT_RETENTION_POLICY_ID.value ) == + ServantRetentionPolicyValue._RETAIN; + } + + /* Request Processing */ + public final boolean useActiveMapOnly() { + return getPolicyValue( REQUEST_PROCESSING_POLICY_ID.value ) == + RequestProcessingPolicyValue._USE_ACTIVE_OBJECT_MAP_ONLY; + } + public final boolean useDefaultServant() { + return getPolicyValue( REQUEST_PROCESSING_POLICY_ID.value ) == + RequestProcessingPolicyValue._USE_DEFAULT_SERVANT; + } + public final boolean useServantManager() { + return getPolicyValue( REQUEST_PROCESSING_POLICY_ID.value ) == + RequestProcessingPolicyValue._USE_SERVANT_MANAGER; + } + + /* Implicit Activation */ + public final boolean isImplicitlyActivated() { + return getPolicyValue( IMPLICIT_ACTIVATION_POLICY_ID.value ) == + ImplicitActivationPolicyValue._IMPLICIT_ACTIVATION; + } + + /* proprietary servant caching policy */ + public final int servantCachingLevel() + { + ServantCachingPolicy policy = + ServantCachingPolicy.class.cast( policyMap.get( + ORBConstants.SERVANT_CACHING_POLICY ) ) ; + + if (policy == null) + return ServantCachingPolicy.NO_SERVANT_CACHING ; + else + return policy.getType() ; + } + + public final boolean forceZeroPort() + { + ZeroPortPolicy policy = + ZeroPortPolicy.class.cast( policyMap.get( + ORBConstants.ZERO_PORT_POLICY ) ) ; + + if (policy == null) + return false ; + else + return policy.forceZeroPort() ; + } + + public final int getCopierId() + { + CopyObjectPolicy policy = + CopyObjectPolicy.class.cast( policyMap.get( + ORBConstants.COPY_OBJECT_POLICY ) ) ; + + if (policy != null) + return policy.getValue() ; + else + return defaultObjectCopierFactoryId ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/RequestProcessingPolicyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/RequestProcessingPolicyImpl.java new file mode 100644 index 000000000..5973cb981 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/RequestProcessingPolicyImpl.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; + +public class RequestProcessingPolicyImpl + extends org.omg.CORBA.LocalObject implements RequestProcessingPolicy { + + public RequestProcessingPolicyImpl(RequestProcessingPolicyValue + value) { + this.value = value; + } + + public RequestProcessingPolicyValue value() { + return value; + } + + public int policy_type() + { + return REQUEST_PROCESSING_POLICY_ID.value ; + } + + public Policy copy() { + return new RequestProcessingPolicyImpl(value); + } + + public void destroy() { + value = null; + } + + private RequestProcessingPolicyValue value; + + public String toString() + { + String type = null ; + switch (value.value()) { + case RequestProcessingPolicyValue._USE_ACTIVE_OBJECT_MAP_ONLY : + type = "USE_ACTIVE_OBJECT_MAP_ONLY" ; + break ; + case RequestProcessingPolicyValue._USE_DEFAULT_SERVANT : + type = "USE_DEFAULT_SERVANT" ; + break ; + case RequestProcessingPolicyValue._USE_SERVANT_MANAGER : + type = "USE_SERVANT_MANAGER" ; + break ; + } + + return "RequestProcessingPolicy[" + type + "]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ServantRetentionPolicyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ServantRetentionPolicyImpl.java new file mode 100644 index 000000000..78868bee4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ServantRetentionPolicyImpl.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import org.omg.CORBA.Policy; +import org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID; +import org.omg.PortableServer.ServantRetentionPolicy; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +final class ServantRetentionPolicyImpl + extends org.omg.CORBA.LocalObject implements ServantRetentionPolicy { + + private static final long serialVersionUID = 469062222833983100L; + + public ServantRetentionPolicyImpl(ServantRetentionPolicyValue value) { + this.value = value; + } + + public ServantRetentionPolicyValue value() { + return value; + } + + public int policy_type() + { + return SERVANT_RETENTION_POLICY_ID.value ; + } + + public Policy copy() { + return new ServantRetentionPolicyImpl(value); + } + + public void destroy() { + value = null; + } + + private ServantRetentionPolicyValue value; + + @Override + public String toString() + { + return "ServantRetentionPolicy[" + + ((value.value() == ServantRetentionPolicyValue._RETAIN) ? + "RETAIN" : "NON_RETAIN" + "]") ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ThreadPolicyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ThreadPolicyImpl.java new file mode 100644 index 000000000..0e84abdd5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/ThreadPolicyImpl.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.poa; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; + +final class ThreadPolicyImpl + extends org.omg.CORBA.LocalObject implements ThreadPolicy { + + public ThreadPolicyImpl(ThreadPolicyValue value) { + this.value = value; + } + + public ThreadPolicyValue value() { + return value; + } + + public int policy_type() + { + return THREAD_POLICY_ID.value ; + } + + public Policy copy() { + return new ThreadPolicyImpl(value); + } + + public void destroy() { + value = null; + } + + private ThreadPolicyValue value; + + public String toString() + { + return "ThreadPolicy[" + + ((value.value() == ThreadPolicyValue._SINGLE_THREAD_MODEL) ? + "SINGLE_THREAD_MODEL" : "ORB_CTRL_MODEL" + "]") ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/minor_code_example.txt b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/minor_code_example.txt new file mode 100644 index 000000000..fe29f2236 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/minor_code_example.txt @@ -0,0 +1,71 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +package @PKGNAME@ ; + +import org.omg.CORBA.OMGVMCID ; +import org.omg.CORBA.CompletionStatus ; + +import org.omg.CORBA.@SYSEX@ ; + +public abstract class StandardException { + // @SYSEX@ BAD_CONTEXT + + public void IdlContextNotFound( CompletionStatus completed ) + { + throw new BAD_CONTEXT( "IDL context not found", + OMGVMCID.value + 1, completed ) ; + } + + public void IdlContextNotFound( ) + { + IdlContextNotFound( CompletionStatus.COMPLETED_NO ) ; + } + +Data structures: list[ ... ] vector[ ... ] ( record ) + +list[ ( string{exception name} list[ ( string{code name} int{value} string{description} ] ) ] + +Processing: + + + open file (fname) + fr = new FileReader( fname ) + br = new BufferedReader( fr ) + br.readLine() returns null at EOF + + want a BufferedReader + + while not eol read line + if (line start with spaces) + add to current index + else + new exception + + create StandardException class + + foreach ( excname vec ) in data + add import statement for execname to output + + foreach ( codename value descr ) in vec + generate full method + generate short method + + +(define (read-file fname) + (begin + (let port (open-input-port fname)) + (let obj (read port)) + obj + ) +) + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/standard_minor_codes.txt b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/standard_minor_codes.txt new file mode 100644 index 000000000..76a9879d6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/poa/standard_minor_codes.txt @@ -0,0 +1,170 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +( +(BAD_CONTEXT + (IDL_CONTEXT_NOT_FOUND 1 "IDL context not found") + (NO_MATCHING_IDL_CONTEXT 2 "No matching IDL context property") +) +(BAD_INV_ORDER + (DEP_PREVENT_DESTRUCTION 1 "Dependency exists in IFR preventing destruction of this object") + (DESTROY_INDESTRUCTIBLE 2 "Attempt to destroy indestructible objects in IFR") + (OPERATION_DEADLOCK 3 "Operation would deadlock") + (ORB_SHUTDOWN 4 "ORB has shutdown") + (BAD_INVOKE 5 "Attempt to invoke send or invoke operation of the same Request object more than once ") + (BAD_SET_SERVANT_MANAGER 6 "Attempt to set a servent manager after one has already been set") + (BAD_ARGUMENTS_CALL 7 "ServerRequest::arguments called more than once or after a call to ServerRequest::set_exception") + (BAD_CTX_CALL 8 "ServerRequest::ctx called more than once or before ServerRequest::arguments or after ServerRequest::ctx, ServerRequest::set_result or ServerRequest::set_exception") + (BAD_RESULT_CALL 9 "ServerRequest::set_result called more than once or before ServerRequest::arguments or after ServerRequest::set_result or ServerRequest::set_exception") + (BAD_SEND 10 "Attempt to send a DII request after it was sent previously") + (BAD_POLL_BEFORE 11 "Attempt to poll a DII request or to retrieve its result before the request was sent") + (BAD_POLL_AFTER 12 "Attempt to poll a DII request or to retrieve its result after the result was retrieved previously") + (BAD_POLL_SYNC 13 "Attempt to poll a synchronous DII request or to retrieve results from a synchronous DII request") + (BAD_PI_CALL 14 "Invalid portable interceptor call") + (BAD_PI_ADD_SERVICE_CONTEXT 15 "Service context add failed in portable interceptor because a service context with the given id already exists") + (DUPLICATE_POLICY_FACTORY 16 "Registration of PolicyFactory failed because a factory already exists for the given PolicyType") + (CREATE_POA_DESTROY 17 "POA cannot create POAs while undergoing destruction") + (PRIORITY_REASSIGN 18 "Attempt to reassign priority") + (XA_START_OUTSIZE 19 "An OTS/XA integration xa_start() call returned XAER_OUTSIDE") + (XA_START_PROTO 20 "An OTS/XA integration xa_ call returned XAER_PROTO") +) +(BAD_OPERATION + (BAD_SERVANT_MANAGER_TYPE 1 "ServantManager returned wrong servant type") + (OPERATION_UNKNOWN_TO_TARGET 2 "Operation or attribute not known to target object ") +) +(BAD_PARAM + (VALUE_FACTORY_REG_ERROR 1 "Failure to register, unregister or lookup value factory") + (RID_ALREADY_DEFINED 2 "RID already defined in IFR") + (NAME_USED_IFR 3 "Name already used in the context in IFR ") + (TARGET_NOT_CONTAINER 4 "Target is not a valid container") + (NAME_CLASH 5 "Name clash in inherited context") + (BAD_ABSTRACT_INTERFACE_TYPE 6 "Incorrect type for abstract interface") + (SO_BAD_SCHEME_NAME 7 "string_to_object conversion failed due to bad scheme name") + (SO_BAD_ADDRESS 8 "string_to_object conversion failed due to bad address") + (SO_BAD_SCHEMA_SPECIFIC 9 "string_to_object conversion failed due to bad bad schema specific part") + (SO_NON_SPECIFIC 10 "string_to_object conversion failed due to non specific reason") + (IR_DERIVE_ABS_INT_BASE 11 "Attempt to derive abstract interface from non-abstract base interface in the Interface Repository") + (IR_VALUE_SUPPORT 12 "Attempt to let a ValueDef support more than one non-abstract interface in the Interface Repository") + (INCOMPLETE_TYPECODE 13 "Attempt to use an incomplete TypeCode as a parameter") + (INVALID_OBJECT_ID 14 "Invalid object id passed to POA::create_reference_by_id ") + (TYPECODE_BAD_NAME 15 "Bad name argument in TypeCode operation") + (TYPECODE_BAD_REPID 16 "Bad RepositoryId argument in TypeCode operation") + (TYPECODE_INV_MEMBER 17 "Invalid member name in TypeCode operation ") + (TC_UNION_DUP_LABEL 18 "Duplicate label value in create_union_tc ") + (TC_UNION_INCOMPATIBLE 19 "Incompatible TypeCode of label and discriminator in create_union_tc ") + (TC_UNION_BAD_DISC 20 "Supplied discriminator type illegitimate in create_union_tc ") + (SET_EXCEPTION_BAD_ANY 21 "Any passed to ServerRequest::set_exception does not contain an exception ") + (SET_EXCEPTION_UNLISTED 22 "Unlisted user exception passed to ServerRequest::set_exception ") + (NO_WCHAR_CODE_SET 23 "wchar transmission code set not in service context") + (ILLEGAL_SERVICE_CONTEXT 24 "Service context is not in OMG-defined range") + (ENUM_OUT_OF_RANGE 25 "Enum value out of range") + (PI_BAD_SERVICE_CONTEXT 26 "Invalid service context Id in portable interceptor") + (REG_INITIAL_NULL 27 "Attempt to call register_initial_reference with a null Object") + (PI_INV_COMPONENT_ID 28 "Invalid component Id in portable interceptor") + (PI_INV_PROFILE_ID 29 "Invalid profile Id in portable interceptor") + (POLICY_TYPE_DUPLICATE 30 "Two or more Policy objects with the same PolicyType value supplied to Object::set_policy_overrides or PolicyManager::set_policy_overrides") + (BAD_ONEWAY_DEFINITION 31 "Attempt to define a oneway operation with non-void result, out or inout parameters or user exceptions") + (DII_FOR_IMPLICIT_OPERATION 32 "DII asked to create request for an implicit operation") + (XA_CALL_INVAL 33 "An OTS/XA integration xa_ call returned XAER_INVAL") + (UNION_BAD_DISCRIMINATOR 34 "Union branch modifier method called with bad case label discriminator") + (CTX_ILLEGAL_PROPERTY_NAME 35 "Illegal IDL context property name") + (CTX_ILLEGAL_SEARCH_STRING 36 "Illegal IDL property search string") + (CTX_ILLEGAL_NAME 37 "Illegal IDL context name") + (CTX_NON_EMPTY 38 "Non-empty IDL context") + (RMI_STREAM_FORMAT 39 "Unsupported RMI/IDL custom value type stream format") + (OUTPUT_STREAM_NOT_VALUE 40 "ORB output stream does not support ValueOutputStream interface") + (INPUT_STREAM_NOT_VALUE 41 "ORB input stream does not support ValueInputStream interface") +) +(BAD_TYPECODE + (MARSHALL_INCOMPLETE_TYPECODE 1 "Attempt to marshal incomplete TypeCode") + (BAD_MEMBER_TYPECODE 2 "Member type code illegitimate in TypeCode operation") + (ILLEGAL_PARAMETER 3 "Illegal parameter type") +) +(DATA_CONVERSION + (CHAR_NOT_MAP_TCS 1 "Character does not map to negotiated transmission code set") + (PRIORITY_MAP_FAILRE 2 "Failure of PriorityMapping object") +) +(IMP_LIMIT + (NO_USABLE_PROFILE 1 "Unable to use any profile in IOR") +) +(INITIALIZE + (PRIORITY_RANGE_RESTRICT 1 "Priority range too restricted for ORB") +) +(INV_OBJREF + (NO_WCHAR_CODE_SET 1 "wchar Code Set support not specified") + (CODESET_COMPONENT_REQUIRED 2 "Codeset component required for type using wchar or wstring data") +) +(INV_POLICY + (IOR_POLICY_RECONCILE_ERROR 1 "Unable to reconcile IOR specified policy with effective policy override") + (INVALID_POLICY_TYPE 2 "Invalid PolicyType") + (NO_POLICY_FACTORY 3 "No PolicyFactory has been registered for the given PolicyType") +) +(INTERNAL + (XA_RMERR 1 "An OTS/XA integration xa_ call returned XAER_RMERR") + (XA_RMFAIL 2 "An OTS/XA integration xa_ call returned XAER_RMFAIL") +) +(INTF_REPOS + (NO_IR 1 "Interface Repository not available") + (NO_INTERFACE_IN_IR 2 "No entry for requested interface in Interface Repository") +) +(MARSHAL + (NO_VALUE_FACTORY 1 "Unable to locate value factory") + (SET_RESULT_BEFORE_CTX 2 "ServerRequest::set_result called before ServerRequest::ctx when the operation IDL contains a context clause ") + (BAD_NVLIST 3 "NVList passed to ServerRequest::arguments does not describe all parameters passed by client") + (MARSHAL_LOCAL_OBJECT 4 "Attempt to marshal Local object") + (WCHAR_BAD_GIOP_VERSION_SENT 5 "wchar or wstring data erroneosly sent by client over GIOP 1.0 connection ") + (WCHAR_BAD_GIOP_VERSION_RETURNED 6 "wchar or wstring data erroneously returned by server over GIOP 1.0 connection ") + (RMI_STREAM_FORMAT_2 7 "Unsupported RMI/IDL custom value type stream "format +) +(NO_IMPLEMENT + (NO_LOCAL_VALUE_IMPLEMENTATION 1 "Missing local value implementation") + (INCOMPAT_VALUE_IMPLEMENTATION 2 "Incompatible value implementation version") + (NO_USABLE_PROFILE_2 3 "Unable to use any profile in IOR") + (DII_LOCAL_OBJECT 4 "Attempt to use DII on Local object") + (BIO_RESET 5 "Biomolecular Sequence Analysis iterator cannot be reset") + (BIO_NOT_AVAILABLE 6 "Biomolecular Sequence Analysis metadata is not available as XML") + (BIO_GENOMIC_NO_ITERATOR 7 "Genomic Maps iterator cannot be reset") +) +(NO_RESOURCES + (PI_OPERATION_NOT_SUPPORTED 1 "Portable Interceptor operation not supported in this binding") + (NO_CONNECTION_PRIORITY 2 "No connection for request's priority") +) +(TRANSACTION_ROLLEDBACK + (XA_RB 1 "An OTS/XA integration xa_ call returned XAER_RB") + (XA_NOTA 2 "An OTS/XA integration xa_ call returned XAER_NOTA") + (XA_END_TRUE_ROLLBACK_DEFERRED 3 "OTS/XA integration end() was called with success set to TRUE while transaction rollback was deferred") +) +(TRANSIENT + (POA_REQUEST_DISCARD 1 "Request discarded because of resource exhaustion in POA or because POA is in DISCARDING state") + (NO_USABLE_PROFILE_3 2 "No usable profile in IOR") + (REQUEST_CANCELLED 3 "Request cancelled") + (POA_DESTROYED 4 "POA destroyed") +) +(OBJECT_NOT_EXIST + "(UNREGISTERED_VALUE_AS_OBJREF 1 Attempt to pass an unactivated (unregistered) value as an object reference") + (NO_OBJECT_ADAPTOR 2 "Failed to create or locate Object Adaptor") + (BIO_NOT_AVAILABLE 3 "Biomolecular Sequence Analysis Service is no longer available") + (OBJECT_ADAPTER_INACTIVE 4 "Object Adapter Inactive") +) +(OBJ_ADAPTER + (UNKNOWN_ADAPTER_SYS_EXCEPTION 1 "System exception in POA::unknown_adapter") + (BAD_SERVANT_TYPE 2 "Incorrect servant type returned by servant manager ") + (NO_DEFAULT_SERVANT 3 "No default servant available [POA policy"]) + (NO_SERVANT_MANAGER 4 "No servant manager available [POA Policy"]) + (BAD_POLICY_INCARNATE 5 "Violation of POA policy by ServantActivator::incarnate") + (PI_EXC_COMP_ESTABLISHED 6 "Exception in PortableInterceptor::IORInterceptor.components_established") + (NULL_SERVANT_RETURNED 7 "Null servant returned by servant manager") +) +(UNKNOWN + (UNLISTED_EXCEPTION_RECEIVED 1 "Unlisted user exception received by client ") + (UNSUPPORTED_SYSTEM_EXCEPTION 2 "Non-standard System Exception not supported") + (PI_UNKNOWN_USER_EXCEPTION 3 "An unknown user exception received by a portable interceptor") +) +) diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/rfm/ReferenceFactoryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/rfm/ReferenceFactoryImpl.java new file mode 100644 index 000000000..1190f1a24 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/rfm/ReferenceFactoryImpl.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.rfm; + +import org.omg.CORBA.LocalObject ; + +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory ; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager ; + +public class ReferenceFactoryImpl extends LocalObject implements ReferenceFactory +{ + private ReferenceFactoryManagerImpl manager ; + private String name ; + private String repositoryId ; + + public ReferenceFactoryImpl( ReferenceFactoryManagerImpl manager, + String name, String repositoryId ) { + this.manager = manager ; + this.name = name ; + this.repositoryId = repositoryId ; + } + + public org.omg.CORBA.Object createReference( byte[] key ) { + return manager.createReference( name, key, repositoryId ) ; + } + + public void destroy() { + manager.destroy( name ) ; + } + + public String toString() + { + return "ReferenceFactoryImpl[" + + name + + ", " + + repositoryId + + "]"; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/rfm/ReferenceFactoryManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/rfm/ReferenceFactoryManagerImpl.java new file mode 100644 index 000000000..565cdbac9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/rfm/ReferenceFactoryManagerImpl.java @@ -0,0 +1,613 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.rfm; + +import java.util.List ; +import java.util.ArrayList ; +import java.util.Map ; +import java.util.HashMap ; +import java.util.Arrays ; + +import java.util.concurrent.locks.ReentrantLock ; +import java.util.concurrent.locks.Condition ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.LocalObject ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.POAManager ; +import org.omg.PortableServer.AdapterActivator ; +import org.omg.PortableServer.ServantLocator ; +import org.omg.PortableServer.RequestProcessingPolicyValue ; +import org.omg.PortableServer.LifespanPolicyValue ; +import org.omg.PortableServer.ServantRetentionPolicyValue ; + +import org.omg.PortableServer.POAManagerPackage.AdapterInactive ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory ; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager ; + +import com.sun.corba.ee.spi.logging.POASystemException ; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.spi.trace.Poa; +import java.util.HashSet; +import java.util.Set; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedObject; +import org.glassfish.pfl.basic.contain.Pair; + +@Poa +@ManagedObject +@Description( "The ReferenceFactoryManager, used to handle dynamic cluster membership updates") +public class ReferenceFactoryManagerImpl + extends org.omg.CORBA.LocalObject + implements ReferenceFactoryManager +{ + private static final POASystemException wrapper = + POASystemException.self ; + + private static final long serialVersionUID = -6689846523143143228L; + + private static final String PARENT_POA_NAME = "#RFMBase#" ; + + // Initialized in the constructor + private RFMState state ; + private final ReentrantLock lock ; + private final Condition suspendCondition ; + private final ORB orb ; + // poatable contains the mapping from the ReferenceFactory name to + // the ServantLocator and list of policies. Note that the policy + // list is stored in the form passed to the create() call: that is, + // it does not contain the standard policies. + private final Map>> poatable ; + private final Map factories ; + private final Set managers ; + private final AdapterActivator activator ; + private volatile boolean isActive ; + + // Initialized on activation because the root POA is required. + private POA rootPOA ; + private List standardPolicies ; + private POA parentPOA ; + private String[] parentPOAAdapterName ; + + public ReferenceFactoryManagerImpl( ORB orb ) + { + lock = new ReentrantLock() ; + suspendCondition = lock.newCondition() ; + state = RFMState.READY ; + this.orb = orb ; + poatable = new HashMap>>() ; + factories = new HashMap() ; + managers = new HashSet() ; + activator = new AdapterActivatorImpl() ; + isActive = false ; + } + + @Poa + private class AdapterActivatorImpl + extends LocalObject + implements AdapterActivator + { + private static final long serialVersionUID = 7922226881290146012L; + + @Poa + public boolean unknown_adapter( POA parent, String name ) { + Pair> data = null ; + synchronized (poatable) { + // REVISIT: make sure that data can't change concurrently! + // Should be OK because Pair is immutable. + data = poatable.get( name ) ; + } + + if (data == null) { + return false ; + } else { + try { + List policies = new ArrayList() ; + // XXX What should we do if data.second() contains + // policies with the same ID as standard policies? + if (data.second() != null) { + policies.addAll(data.second()); + } + policies.addAll( standardPolicies ) ; + Policy[] arr = policies.toArray( new Policy[policies.size()] ) ; + + POA child = parentPOA.create_POA( name, null, arr ) ; + POAManager pm = child.the_POAManager() ; + + lock.lock() ; + try { + managers.add(pm) ; + } finally { + lock.unlock() ; + } + + child.set_servant_manager( data.first() ) ; + pm.activate() ; + return true ; + } catch (Exception exc) { + wrapper.rfmAdapterActivatorFailed( exc ) ; + return false ; + } + } + } + } ; + + // Policy used to indicate that a POA may particpate in the reference manager. + // If this policy is not present, and a create_POA call is made under base POA, + // an IORInterceptor will be used reject the POA creation. + private static class ReferenceManagerPolicy + extends LocalObject + implements Policy + { + private static Policy thisPolicy = new ReferenceManagerPolicy() ; + private static final long serialVersionUID = -4780983694679451387L; + + public static Policy getPolicy() { + return thisPolicy ; + } + + private ReferenceManagerPolicy() { + } + + public int policy_type() { + return ORBConstants.REFERENCE_MANAGER_POLICY ; + } + + public Policy copy() { + return this ; + } + + public void destroy() { + } + } + + public RFMState getState() + { + lock.lock() ; + try { + return state ; + } finally { + lock.unlock(); + } + } + + @Poa + public void activate() + { + lock.lock() ; + try { + if (isActive) { + throw wrapper.rfmAlreadyActive(); + } + + rootPOA = (POA)orb.resolve_initial_references( + ORBConstants.ROOT_POA_NAME ) ; + + standardPolicies = Arrays.asList( + ReferenceManagerPolicy.getPolicy(), + rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN ), + rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER ), + rootPOA.create_lifespan_policy( + LifespanPolicyValue.PERSISTENT ) + ) ; + + Policy[] policies = { ReferenceManagerPolicy.getPolicy() } ; + parentPOA = rootPOA.create_POA( PARENT_POA_NAME, + null, policies ) ; + parentPOAAdapterName = ObjectAdapter.class.cast( parentPOA ) + .getIORTemplate().getObjectKeyTemplate().getObjectAdapterId() + .getAdapterName() ; + + POAManager pm = parentPOA.the_POAManager() ; + parentPOA.the_activator( activator ) ; + pm.activate() ; + + // Don't activate if there is a failure + isActive = true ; + } catch (Exception exc) { + throw wrapper.rfmActivateFailed( exc ) ; + } finally { + lock.unlock() ; + } + } + + // XXX rfmMightDeadlock exceptions are a problem, because it is possible + // to attempt to deploy an EJB while the cluster shape is changing. + // We really need to enqueue (at least) create calls while suspended. + // It may also be better to get rid of separate suspend/resume calls, instead + // passing an object to a method that does suspend/resume (as in + // doPrivileged). See GF issue 4560. + @Poa + public ReferenceFactory create( final String name, + final String repositoryId, + final List policies, + final ServantLocator locator ) + { + lock.lock() ; + try { + if (state == RFMState.SUSPENDED) { + throw wrapper.rfmMightDeadlock(); + } + + if (!isActive) { + throw wrapper.rfmNotActive(); + } + + List newPolicies = null ; + if (policies != null) { + newPolicies = new ArrayList(policies); + } + + // Store an entry for the appropriate POA in the POA table, + // which is used by the AdapterActivator on the root. + synchronized (poatable) { + poatable.put( name, new Pair>( + locator, newPolicies ) ) ; + } + + ReferenceFactory factory = new ReferenceFactoryImpl( this, name, + repositoryId ) ; + factories.put( name, factory ) ; + return factory ; + } finally { + lock.unlock() ; + } + } + + @Poa + public ReferenceFactory find( String[] adapterName ) + { + lock.lock() ; + try { + if (state == RFMState.SUSPENDED) { + throw wrapper.rfmMightDeadlock(); + } + + if (!isActive) { + return null; + } + + int expectedLength = parentPOAAdapterName.length + 1 ; + + if (expectedLength != adapterName.length) { + return null; + } + + for (int ctr=0; ctr pms = new HashSet( managers ) ; + + // wait until all requests in the manager have completed. + try { + if (!isActive) { + throw wrapper.rfmNotActive() ; + } + + while (state == RFMState.SUSPENDED) { + try { + suspendCondition.await(); + } catch (InterruptedException exc) { + throw wrapper.rfmSuspendConditionWaitInterrupted(); + } + } + + // At this point, the state must be READY, and any other + // suspending thread has released the lock. So now + // we set the state back to SUSPENDED, drop the lock, + // and continue. + + state = RFMState.SUSPENDED ; + } finally { + lock.unlock() ; + } + + // do NOT hold the RFM lock here, because then we would hold + // first the RFM, and then the POAManager lock. Another thread + // could reverse the order, leading to a deadlock. See bug + // 6586417. + try { + for (POAManager pm : pms) { + pm.hold_requests( true ) ; + } + } catch (AdapterInactive ai) { + // This should never happen + throw wrapper.rfmManagerInactive( ai ) ; + } + } + + @Poa + public void resume() + { + lock.lock() ; + + // Clone managers so we can safely iterator over it. + final Set pms = new HashSet( managers ) ; + + try { + if (!isActive) { + throw wrapper.rfmNotActive(); + } + + state = RFMState.READY ; + suspendCondition.signalAll() ; + } finally { + lock.unlock() ; + } + + // Allow new requests to start. This will lazily + // re-create POAs as needed through the parentPOA's + // AdapterActivator. + // 6933574. But note that these POAManagers belong to + // destroyed POAs (from the restartFactories call), + // so the activation here results in + // an PADestrpyed exception, which causes a retry in + // the server request dispatcher. Re-creating the + // POA also re-creates the POAManager, so after + // activating the POAmanagers, we remove the (old) + // POAManagers from the list. Note that the list + // may (probably will) have changed by then, since other + // threads may (probably will) be re-creating the POAs and hence + // re-creates the POAmanagers and adding the new POAmanagers + // to managers. + try { + for (POAManager pm : pms) { + pm.activate() ; + } + } catch (AdapterInactive ai) { + // This should never happen + throw wrapper.rfmManagerInactive( ai ) ; + } + + lock.lock() ; + try { + // 6933574: As noted above, we need to remove all + // of the old POAManagers (to avoid a memory leak). + // Note that managers may contain new POAManagers by + // this time, so we can't just call managers.clear(). + managers.removeAll( pms ) ; + } finally { + lock.unlock(); + } + } + + @Poa + public void restartFactories( + Map>> updates ) + { + lock.lock() ; + try { + if (!isActive) { + throw wrapper.rfmNotActive(); + } + + if (state != RFMState.SUSPENDED) { + throw wrapper.rfmMethodRequiresSuspendedState("restartFactories"); + } + } finally { + lock.unlock() ; + } + + if (updates == null) { + throw wrapper.rfmNullArgRestart(); + } + + synchronized (poatable) { + // Update the poatable with the updates information. + poatable.putAll( updates ) ; + } + + try { + // Now destroy all POAs that are used to + // implement ReferenceFactory instances. + for (POA poa : parentPOA.the_children()) { + poa.destroy( false, true ) ; + } + } catch (Exception exc) { + throw wrapper.rfmRestartFailed( exc ) ; + } + } + + public void restartFactories() { + restartFactories( new HashMap>>() ) ; + } + + /** Restart all ReferenceFactories. This is done safely, so that + * any request against object references created from these factories + * complete correctly. Restart does not return until all restart + * activity completes. + * @param updates is a map giving the updated policies for + * some or all of the ReferenceFactory instances in this ReferenceFactoryManager. + * This parameter must not be null. + */ + @Poa + public void restart( Map>> updates ) + { + suspend() ; + try { + restartFactories( updates ) ; + } finally { + resume() ; + } + } + + /** Restart all ReferenceFactories. This is done safely, so that + * any request against object references created from these factories + * complete correctly. Restart does not return until all restart + * activity completes. Equivalent to calling restart( new Map() ). + */ + public void restart() { + restart( new HashMap>>() ) ; + } + + // Methods used to implement the ReferenceFactory interface. + // ReferenceFactoryImpl just delegates to these methods. + @Poa + org.omg.CORBA.Object createReference( String name, byte[] key, + String repositoryId ) + { + try { + POA child = parentPOA.find_POA( name, true ) ; + return child.create_reference_with_id( key, repositoryId ) ; + } catch (Exception exc) { + throw wrapper.rfmCreateReferenceFailed( exc ) ; + } + } + + // Called from ReferenceFactoryImpl. + @Poa + void destroy( String name ) { + try { + POA child = parentPOA.find_POA( name, true ) ; + synchronized (poatable) { + poatable.remove( name ) ; + } + + lock.lock() ; + try { + factories.remove( name ) ; + POAManager pm = child.the_POAManager() ; + managers.remove( pm ) ; + } finally { + lock.unlock() ; + } + + // Wait for all requests to complete before completing + // destruction of the POA. + child.destroy( false, true ) ; + } catch (Exception exc) { + throw wrapper.rfmDestroyFailed( exc ) ; + } + } + + // Called from ReferenceManagerConfigurator. + void validatePOACreation( POA poa ) { + // Some POAs are created before the ReferenceFactoryManager is created. + // In particular, the root POA and parentPOA are created before isActive + // is set to true. Don't check in these case. + if (!isActive) { + return; + } + + // Only check the case where poa does not have the reference manager + // policy. We assume that we handle the policy correctly inside + // the RFM itself. + Policy policy = ObjectAdapter.class.cast(poa).getEffectivePolicy( + ORBConstants.REFERENCE_MANAGER_POLICY ) ; + if (policy != null) { + return; + } + + // At this point, we know that poa comes from outside the + // active RFM. If poa's parent POA has the policy, we have an + // error. + POA parent = poa.the_parent() ; + Policy parentPolicy = + ObjectAdapter.class.cast(parent).getEffectivePolicy( + ORBConstants.REFERENCE_MANAGER_POLICY ) ; + if (parentPolicy != null) { + throw wrapper.rfmIllegalParentPoaUsage(); + } + + // If poa's POAManager is the manager for the RFM, we have + // an error. + lock.lock() ; + try { + if (managers.contains( poa.the_POAManager())) { + throw wrapper.rfmIllegalPoaManagerUsage() ; + } + } finally { + lock.unlock(); + } + } + + // locking not required + @Poa + public boolean isRfmName( String[] adapterName ) + { + if (!isActive) { + return false ; + } + + int expectedLength = parentPOAAdapterName.length + 1 ; + + if (expectedLength != adapterName.length) { + return false; + } + + for (int ctr=0; ctr + *
  • Create an instance of ReferenceFactoryManagerImpl and register it with + * register_local_reference. + *
  • Create and register an IORInterceptor that prevent outside POAs from + * interfering with the ReferenceManager. + * + */ +public class ReferenceManagerConfigurator implements ORBConfigurator { + private static final POASystemException wrapper = + POASystemException.self ; + + private static class RMIORInterceptor + extends LocalObject + implements IORInterceptor_3_0 + { + private ReferenceFactoryManagerImpl rm ; + + public RMIORInterceptor( ReferenceFactoryManagerImpl rm ) { + this.rm = rm ; + } + + public String name() { + return "##" + this.getClass().getName() + "##" ; + } + + public void destroy() { + // NO-OP + } + + public void establish_components( IORInfo info ) { + // NO-OP + } + + public void adapter_manager_state_changed( int id, short state ) { + // NO-OP + } + + public void adapter_state_changed( ObjectReferenceTemplate[] templates, short state ) { + // NO-OP + } + + // We must do the checking here, because exceptions are not + // ignored. All exceptions thrown in establish_components + // are ignored. The whole purpose of this interceptor is + // to throw an exception if an error is detected. + public void components_established( IORInfo info ) { + IORInfoExt ext = IORInfoExt.class.cast( info ) ; + ObjectAdapter oa = ext.getObjectAdapter() ; + if (!(oa instanceof POA)) { + return; + } // if not POA, then there is no chance of a conflict. + POA poa = POA.class.cast( oa ) ; + rm.validatePOACreation( poa ) ; + } + } + + private static class RMORBInitializer + extends LocalObject + implements ORBInitializer + { + private IORInterceptor_3_0 interceptor ; + + public RMORBInitializer( IORInterceptor_3_0 interceptor ) { + this.interceptor = interceptor ; + } + + public void pre_init( ORBInitInfo info ) { + // NO-OP + } + + public void post_init( ORBInitInfo info ) { + try { + info.add_ior_interceptor( interceptor ) ; + } catch (Exception exc) { + throw wrapper.rfmPostInitException( exc ) ; + } + } + } + + public void configure( DataCollector collector, ORB orb ) + { + try { + ReferenceFactoryManagerImpl rm = new ReferenceFactoryManagerImpl( orb ) ; + orb.register_initial_reference( ORBConstants.REFERENCE_FACTORY_MANAGER, rm ) ; + IORInterceptor_3_0 interceptor = new RMIORInterceptor( rm ) ; + ORBInitializer initializer = new RMORBInitializer( interceptor ) ; + orb.getORBData().addORBInitializer( initializer ) ; + } catch (Exception exc) { + throw wrapper.rfmConfigureException( exc ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOA.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOA.java new file mode 100644 index 000000000..e01fda801 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOA.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.toa ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +/** The Transient Object Adapter is used for standard RMI-IIOP and Java-IDL + * (legacy JDK 1.2) object implementations. Its protocol for managing objects is very + * simple: just connect and disconnect. There is only a single TOA instance per ORB, + * and its lifetime is the same as the ORB. The TOA instance is always ready to receive + * messages except when the ORB is shutting down. + */ +public interface TOA extends ObjectAdapter { + /** Connect the given servant to the ORB by allocating a transient object key + * and creating an IOR and object reference using the current factory. + */ + void connect( org.omg.CORBA.Object servant ) ; + + /** Disconnect the object from this ORB. + */ + void disconnect( org.omg.CORBA.Object obj ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOAFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOAFactory.java new file mode 100644 index 000000000..e3fd4d379 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOAFactory.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.toa ; + +import java.util.Map ; +import java.util.HashMap ; + + +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory ; +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util ; + +import com.sun.corba.ee.impl.ior.ObjectKeyTemplateBase ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import org.glassfish.gmbal.AMXMetadata; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.gmbal.ManagedObject; + +@ManagedObject +@Description( "The Factory for the TOA (transient object adapter)") +@AMXMetadata( isSingleton=true ) +public class TOAFactory implements ObjectAdapterFactory +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private ORB orb ; + + private TOAImpl toa ; + private Map codebaseToTOA ; + private TransientObjectManager tom ; + + @ManagedAttribute + @Description( "The default TOA used only for dispatch, not objref creation") + private TOAImpl getDefaultTOA() { + return toa ; + } + + @ManagedAttribute + @Description( "The map from Codebase to TOA") + private synchronized Map getCodebaseMap() { + return new HashMap( codebaseToTOA ) ; + } + + public ObjectAdapter find ( ObjectAdapterId oaid ) + { + if (oaid.equals( ObjectKeyTemplateBase.JIDL_OAID ) ) { + return getTOA(); + } else { + throw wrapper.badToaOaid(); + } + } + + public void init( ORB orb ) + { + this.orb = orb ; + tom = new TransientObjectManager( orb ) ; + codebaseToTOA = new HashMap() ; + orb.mom().registerAtRoot( this ) ; + } + + public void shutdown( boolean waitForCompletion ) + { + if (Util.getInstance() != null) { + Util.getInstance().unregisterTargetsForORB(orb); + } + } + + public synchronized TOA getTOA( String codebase ) + { + TOAImpl myToa = codebaseToTOA.get( codebase ) ; + if (myToa == null) { + myToa = new TOAImpl( orb, tom, codebase ) ; + + codebaseToTOA.put( codebase, myToa ) ; + } + + return myToa ; + } + + public synchronized TOA getTOA() + { + if (toa == null) { + // The dispatch-only TOA is not used for creating + // objrefs, so its codebase can be null (and must + // be, since we do not have a servant at this point) + toa = new TOAImpl( orb, tom, null ) ; + } + + return toa ; + } + + public ORB getORB() + { + return orb ; + } +} ; + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOAImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOAImpl.java new file mode 100644 index 000000000..834d7d953 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TOAImpl.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.toa ; + +import org.omg.CORBA.Policy ; +import org.omg.PortableInterceptor.ObjectReferenceFactory ; +import org.omg.PortableInterceptor.ACTIVE; + +import com.sun.corba.ee.spi.copyobject.CopierManager ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.OADestroyed ; +import com.sun.corba.ee.spi.oa.ObjectAdapterBase ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher ; +import com.sun.corba.ee.spi.transport.ContactInfoList ; + +import com.sun.corba.ee.impl.ior.JIDLObjectKeyTemplate ; +import com.sun.corba.ee.impl.oa.NullServantImpl; +import com.sun.corba.ee.impl.oa.poa.Policies; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.impl.protocol.JIDLLocalCRDImpl ; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import java.util.concurrent.atomic.AtomicLong; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.gmbal.ManagedObject; +import org.glassfish.gmbal.NameValue; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; + +/** The Transient Object Adapter (TOA) represents the OA for purely transient +* objects. It is used for standard RMI-IIOP as well as backwards compatible +* server support (i.e. the ORB.connect() method) +* Its characteristics include: +*
      +*
    • There is only one OA instance of the TOA. Its OAId is { "TOA" }
    • +*
    • There is not adapter manager. The TOA manager ID is fixed.
    • +*
    • State is the same as ORB state (TBD)
    • +*
    +* Other requirements: +*
      +*
    • All object adapters must invoke ORB.adapterCreated when they are created. +*
    • +*
    • All adapter managers must invoke ORB.adapterManagerStateChanged when +* their state changes, mapping the internal state to an ORT state.
    • +*
    • AdapterStateChanged must be invoked (from somewhere) whenever +* an adapter state changes that is not due to an adapter manager state change.
    • +*
    +*/ +@ManagedObject +@Description( "The Transient Object Adapter") +public class TOAImpl extends ObjectAdapterBase implements TOA +{ + private static AtomicLong currentId = new AtomicLong( 0 ); + + private TransientObjectManager servants ; + private long id ; + private String codebase ; + + @NameValue + private long getId() { + return id ; + } + + @ManagedAttribute + @Description( "The codebase used to create this TOA") + private String getCodebase() { + return codebase ; + } + + @ManagedAttribute + @Description( "The TransientObjectManager") + private TransientObjectManager getTransientObjectManager() { + return servants ; + } + + public TOAImpl( ORB orb, TransientObjectManager tom, String codebase ) + { + super( orb ) ; + servants = tom ; + this.codebase = codebase ; + id = currentId.getAndIncrement() ; + + // Make the object key template + int serverid = (getORB()).getTransientServerId(); + int scid = ORBConstants.TOA_SCID ; + + ObjectKeyTemplate oktemp = new JIDLObjectKeyTemplate( orb, scid, serverid ) ; + + // REVISIT - POA specific + Policies policies = Policies.defaultPolicies; + + // REVISIT - absorb codebase into a policy + initializeTemplate( oktemp, true, + policies, + codebase, + null, // manager id + oktemp.getObjectAdapterId() + ) ; + } + + // Methods required for dispatching requests + + public ObjectCopierFactory getObjectCopierFactory() + { + CopierManager cm = getORB().getCopierManager() ; + return cm.getDefaultObjectCopierFactory() ; + } + + public org.omg.CORBA.Object getLocalServant( byte[] objectId ) + { + return (org.omg.CORBA.Object)(servants.lookupServant( objectId ) ) ; + } + + /** Get the servant for the request given by the parameters. + * This will update thread Current, so that subsequent calls to + * returnServant and removeCurrent from the same thread are for the + * same request. + * @param request is the request containing the rest of the request + */ + public void getInvocationServant( OAInvocationInfo info ) + { + java.lang.Object servant = servants.lookupServant( info.id() ) ; + if (servant == null) { + servant = + new NullServantImpl(wrapper.nullServant()); + } + info.setServant( servant ) ; + } + + public void returnServant() + { + // NO-OP + } + + /** Return the most derived interface for the given servant and objectId. + */ + public String[] getInterfaces( Object servant, byte[] objectId ) + { + return StubAdapter.getTypeIds( servant ) ; + } + + public Policy getEffectivePolicy( int type ) + { + return null ; + } + + public int getManagerId() + { + return -1 ; + } + + public short getState() + { + return ACTIVE.value ; + } + + public void enter() throws OADestroyed + { + } + + public void exit() + { + } + + // Methods unique to the TOA + + public void connect( org.omg.CORBA.Object objref) + { + // Store the objref and get a userkey allocated by the transient + // object manager. + byte[] key = servants.storeServant(objref, null); + + // Find out the repository ID for this objref. + String id = StubAdapter.getTypeIds( objref )[0] ; + + // Create the new objref + ObjectReferenceFactory orf = getCurrentFactory() ; + org.omg.CORBA.Object obj = orf.make_object( id, key ) ; + + // Copy the delegate from the new objref to the argument + org.omg.CORBA.portable.Delegate delegate = StubAdapter.getDelegate( + obj ) ; + ContactInfoList ccil = ((ClientDelegate) delegate).getContactInfoList() ; + LocalClientRequestDispatcher lcs = + ccil.getLocalClientRequestDispatcher() ; + + if (lcs instanceof JIDLLocalCRDImpl) { + JIDLLocalCRDImpl jlcs = (JIDLLocalCRDImpl)lcs ; + jlcs.setServant( objref ) ; + } else { + throw new RuntimeException( + "TOAImpl.connect can not be called on " + lcs ) ; + } + + StubAdapter.setDelegate( objref, delegate ) ; + } + + public void disconnect( org.omg.CORBA.Object objref ) + { + // Get the delegate, then ior, then transientKey, then delete servant + org.omg.CORBA.portable.Delegate del = StubAdapter.getDelegate( + objref ) ; + ContactInfoList ccil = ((ClientDelegate) del).getContactInfoList() ; + LocalClientRequestDispatcher lcs = + ccil.getLocalClientRequestDispatcher() ; + + if (lcs instanceof JIDLLocalCRDImpl) { + JIDLLocalCRDImpl jlcs = (JIDLLocalCRDImpl)lcs ; + byte[] oid = jlcs.getObjectId() ; + servants.deleteServant(oid); + jlcs.unexport() ; + } else { + throw new RuntimeException( + "TOAImpl.disconnect can not be called on " + lcs ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TransientObjectManager.java b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TransientObjectManager.java new file mode 100644 index 000000000..7897319ee --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/oa/toa/TransientObjectManager.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.oa.toa; + +import com.sun.corba.ee.impl.misc.ORBUtility ; +import com.sun.corba.ee.spi.orb.ORB ; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.gmbal.ManagedData; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@com.sun.corba.ee.spi.trace.TransientObjectManager +@ManagedData +@Description( "Maintains mapping from Object ID to servant") +public final class TransientObjectManager { + private ORB orb ; + private int maxSize = 128; + private Element[] elementArray; + private Element freeList; + + @ManagedAttribute() + @Description( "The element array mapping indices into servants" ) + private synchronized Element[] getElements() { + return elementArray.clone() ; + } + + public TransientObjectManager( ORB orb ) + { + this.orb = orb ; + + elementArray = new Element[maxSize]; + elementArray[maxSize-1] = new Element(maxSize-1,null); + for ( int i=maxSize-2; i>=0; i-- ) + elementArray[i] = new Element(i,elementArray[i+1]); + freeList = elementArray[0]; + } + + @com.sun.corba.ee.spi.trace.TransientObjectManager + public synchronized byte[] storeServant(java.lang.Object servant, java.lang.Object servantData) + { + if ( freeList == null ) + doubleSize(); + + Element elem = freeList; + freeList = (Element)freeList.servant; + + byte[] result = elem.getKey(servant, servantData); + return result ; + } + + @com.sun.corba.ee.spi.trace.TransientObjectManager + public synchronized java.lang.Object lookupServant(byte transientKey[]) + { + int index = ORBUtility.bytesToInt(transientKey,0); + int counter = ORBUtility.bytesToInt(transientKey,4); + + if (elementArray[index].counter == counter && + elementArray[index].valid ) { + return elementArray[index].servant; + } + + // servant not found + return null; + } + + @com.sun.corba.ee.spi.trace.TransientObjectManager + public synchronized java.lang.Object lookupServantData(byte transientKey[]) + { + int index = ORBUtility.bytesToInt(transientKey,0); + int counter = ORBUtility.bytesToInt(transientKey,4); + + if (elementArray[index].counter == counter && + elementArray[index].valid ) { + return elementArray[index].servantData; + } + + // servant not found + return null; + } + + @InfoMethod + private void deleteAtIndex( int index ) { } + + @com.sun.corba.ee.spi.trace.TransientObjectManager + public synchronized void deleteServant(byte transientKey[]) + { + int index = ORBUtility.bytesToInt(transientKey,0); + deleteAtIndex(index); + + elementArray[index].delete(freeList); + freeList = elementArray[index]; + } + + public synchronized byte[] getKey(java.lang.Object servant) + { + for ( int i=0; i=oldSize; i-- ) + elementArray[i] = new Element(i,elementArray[i+1]); + freeList = elementArray[oldSize]; + } +} + + +@ManagedData +@Description( "A single element mapping one ObjectId to a Servant") +final class Element { + java.lang.Object servant=null; // also stores "next pointer" in free list + java.lang.Object servantData=null; + int index=-1; + int counter=0; + boolean valid=false; // valid=true if this Element contains + // a valid servant + + @ManagedAttribute + @Description( "The servant" ) + private synchronized Object getServant() { + return servant ; + } + + @ManagedAttribute + @Description( "The servant data" ) + private synchronized Object getServantData() { + return servantData ; + } + + @ManagedAttribute + @Description( "The reuse counter") + private synchronized int getReuseCounter() { + return counter ; + } + + @ManagedAttribute + @Description( "The index of this entry") + private synchronized int getIndex() { + return index ; + } + + Element(int i, java.lang.Object next) + { + servant = next; + index = i; + } + + byte[] getKey(java.lang.Object servant, java.lang.Object servantData) + { + this.servant = servant; + this.servantData = servantData; + this.valid = true; + + return toBytes(); + } + + byte[] toBytes() + { + // Convert the index+counter into an 8-byte (big-endian) key. + + byte key[] = new byte[8]; + ORBUtility.intToBytes(index, key, 0); + ORBUtility.intToBytes(counter, key, 4); + + return key; + } + + void delete(Element freeList) + { + if ( !valid ) // prevent double deletion + return; + counter++; + servantData = null; + valid = false; + + // add this to freeList + servant = freeList; + } + + @Override + public String toString() + { + return "Element[" + index + ", " + counter + "]" ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/AppletDataCollector.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/AppletDataCollector.java new file mode 100644 index 000000000..bbe8dc0fb --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/AppletDataCollector.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.applet.Applet ; +import java.util.Properties ; + +public class AppletDataCollector extends DataCollectorBase { + private Applet applet ; + + AppletDataCollector( Applet app, Properties props, String localHostName, + String configurationHostName ) + { + super( props, localHostName, configurationHostName ) ; + this.applet = app ; + } + + public boolean isApplet() + { + return true ; + } + + protected void collect( ) + { + checkPropertyDefaults() ; + + findPropertiesFromFile() ; + + // We do not use system properties for applets in order to + // avoid security exceptions. + + findPropertiesFromProperties() ; + findPropertiesFromApplet( applet ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/DataCollectorBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/DataCollectorBase.java new file mode 100644 index 000000000..380e8e49a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/DataCollectorBase.java @@ -0,0 +1,452 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import com.sun.corba.ee.org.omg.CORBA.GetPropertyAction ; + +import java.security.PrivilegedAction ; + +import java.applet.Applet ; + +import java.util.Properties ; +import java.util.Set ; +import java.util.HashSet ; +import java.util.Enumeration ; +import java.util.Iterator ; +import java.util.StringTokenizer ; + +import java.net.URL ; + +import java.security.AccessController ; + +import java.io.File ; +import java.io.FileInputStream ; + +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.PropertyParser ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +public abstract class DataCollectorBase implements DataCollector { + private Set propertyNames ; + private Set propertyPrefixes ; + private Set URLPropertyNames ; + protected String localHostName ; + protected String configurationHostName ; + private boolean setParserCalled ; + private Properties originalProps ; + private Properties resultProps ; + + public DataCollectorBase( Properties props, String localHostName, + String configurationHostName ) + { + URLPropertyNames = new HashSet() ; + URLPropertyNames.add( ORBConstants.INITIAL_SERVICES_PROPERTY ) ; + + propertyNames = new HashSet() ; + + // Make sure that we are ready to handle -ORBInitRef. This is special + // due to the need to handle multiple -ORBInitRef args as prefix + // parsing. + propertyNames.add( ORBConstants.ORB_INIT_REF_PROPERTY ) ; + + propertyPrefixes = new HashSet() ; + + this.originalProps = props ; + this.localHostName = localHostName ; + this.configurationHostName = configurationHostName ; + setParserCalled = false ; + resultProps = new Properties() ; + } + +////////////////////////////////////////////////////////// +// Public interface defined in DataCollector +////////////////////////////////////////////////////////// + + public boolean initialHostIsLocal() + { + checkSetParserCalled() ; + return localHostName.equals( resultProps.getProperty( + ORBConstants.INITIAL_HOST_PROPERTY ) ) ; + } + + public void setParser( PropertyParser parser ) + { + Iterator iter = parser.iterator() ; + while (iter.hasNext()) { + ParserAction pa = iter.next() ; + if (pa.isPrefix()) { + propertyPrefixes.add(pa.getPropertyName()); + } else { + propertyNames.add(pa.getPropertyName()); + } + } + + collect() ; + setParserCalled = true ; + } + + public Properties getProperties() + { + checkSetParserCalled() ; + return resultProps ; + } + +////////////////////////////////////////////////////////// +// public interface from DataCollector that must be defined +// in subclasses +////////////////////////////////////////////////////////// + + public abstract boolean isApplet() ; + +////////////////////////////////////////////////////////// +// Implementation methods needed in subclasses +////////////////////////////////////////////////////////// + + protected abstract void collect() ; + +////////////////////////////////////////////////////////// +// methods for use by subclasses +////////////////////////////////////////////////////////// + + protected void checkPropertyDefaults() + { + String host = + resultProps.getProperty( ORBConstants.INITIAL_HOST_PROPERTY ) ; + + if ((host == null) || (host.equals(""))) { + setProperty(ORBConstants.INITIAL_HOST_PROPERTY, + configurationHostName); + } + } + + protected void findPropertiesFromArgs( String[] params ) + { + if (params == null) { + return; + } + + // All command-line args are of the form "-ORBkey value". + // The key is mapped to .ORBkey. + + String name ; + String value ; + + for ( int i=0; i normalNames = getCORBAPrefixes( propertyNames ) ; + Set prefixNames = getCORBAPrefixes( propertyPrefixes ) ; + + PropertyCallback callback = new PropertyCallback() { + public String get(String name) { + return getSystemProperty(name); + } + } ; + + findPropertiesByName( normalNames.iterator(), callback ) ; + + findPropertiesByPrefix( prefixNames, + getSystemPropertyNames(), callback ) ; + } + +////////////////////////////////////////////////////////// +// internal implementation +////////////////////////////////////////////////////////// + + // Store name, value in resultProps, with special + // treatment of ORBInitRef. All updates to resultProps + // must happen through this method. + private void setProperty( String name, String value ) + { + if( name.equals( ORBConstants.ORB_INIT_REF_PROPERTY ) ) { + // Value is = + StringTokenizer st = new StringTokenizer( value, "=" ) ; + if (st.countTokens() != 2) { + throw new IllegalArgumentException(); + } + + String refName = st.nextToken() ; + String refValue = st.nextToken() ; + + resultProps.setProperty( name + "." + refName, refValue ) ; + } else { + resultProps.setProperty( name, value ) ; + } + } + + private void checkSetParserCalled() + { + if (!setParserCalled) { + throw new IllegalStateException("setParser not called."); + } + } + + // For each prefix in prefixes, For each name in propertyNames, + // if (prefix is a prefix of name) get value from getProperties and + // setProperty (name, value). + private void findPropertiesByPrefix( Set prefixes, + Iterator propertyNames, PropertyCallback getProperty ) + { + while (propertyNames.hasNext()) { + String name = propertyNames.next() ; + Iterator iter = prefixes.iterator() ; + while (iter.hasNext()) { + String prefix = iter.next() ; + if (name.startsWith( prefix )) { + String value = getProperty.get( name ) ; + + // Note: do a put even if value is null since just + // the presence of the property may be significant. + setProperty( name, value ) ; + } + } + } + } + + // For each prefix in names, get the corresponding property + // value from the callback, and store the name/value pair in + // the result. + private void findPropertiesByName( Iterator names, + PropertyCallback getProperty ) + { + while (names.hasNext()) { + String name = names.next() ; + String value = getProperty.get( name ) ; + if (value != null) { + setProperty(name, value); + } + } + } + + @SuppressWarnings("unchecked") + private static String getSystemProperty(final String name) + { + return (String)AccessController.doPrivileged( + new GetPropertyAction(name)); + } + + // Map command-line arguments to ORB properties. + // + private String findMatchingPropertyName( Set names, + String suffix ) + { + Iterator iter = names.iterator() ; + while (iter.hasNext()) { + String name = iter.next() ; + if (name.endsWith( suffix )) { + return name; + } + } + + return null ; + } + + private static Iterator makeIterator( + final Enumeration enumeration ) + { + return new Iterator() { + public boolean hasNext() { return enumeration.hasMoreElements() ; } + public String next() { return (String)enumeration.nextElement() ; } + public void remove() { throw new UnsupportedOperationException() ; } + } ; + } + + private static Iterator getSystemPropertyNames() + { + // This will not throw a SecurityException because this + // class was loaded from rt.jar using the bootstrap classloader. + @SuppressWarnings("unchecked") + Enumeration enumeration = + (Enumeration)AccessController.doPrivileged( + new PrivilegedAction>() { + public Enumeration run() { + return System.getProperties().propertyNames(); + } + } + ); + + return makeIterator( enumeration ) ; + } + + private void getPropertiesFromFile( Properties props, String fileName ) + { + try { + File file = new File( fileName ) ; + if (!file.exists()) { + return; + } + + FileInputStream in = new FileInputStream( file ) ; + + try { + props.load( in ) ; + } finally { + in.close() ; + } + } catch (Exception exc) { + // if (ORBInitDebug) + // dprint( "ORB properties file " + fileName + " not found: " + + // exc) ; + } + } + + private Properties getFileProperties() + { + Properties defaults = new Properties() ; + + String javaHome = getSystemProperty( "java.home" ) ; + String fileName = javaHome + File.separator + "lib" + File.separator + + "orb.properties" ; + + getPropertiesFromFile( defaults, fileName ) ; + + Properties results = new Properties( defaults ) ; + + String userHome = getSystemProperty( "user.home" ) ; + fileName = userHome + File.separator + "orb.properties" ; + + getPropertiesFromFile( results, fileName ) ; + return results ; + } + + private boolean hasCORBAPrefix( String prefix ) + { + return prefix.startsWith( ORBConstants.CORBA_PREFIX ) || + prefix.startsWith( ORBConstants.SUN_PREFIX ) ; + } + + // Return only those element of prefixes for which hasCORBAPrefix + // is true. + private Set getCORBAPrefixes( final Set prefixes ) + { + Set result = new HashSet() ; + Iterator iter = prefixes.iterator() ; + while (iter.hasNext()) { + String element = iter.next() ; + if (hasCORBAPrefix( element )) { + result.add(element); + } + } + + return result ; + } +} + +// Used to collect properties from various sources. +abstract class PropertyCallback +{ + abstract public String get(String name); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/DataCollectorFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/DataCollectorFactory.java new file mode 100644 index 000000000..f015da6fa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/DataCollectorFactory.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.applet.Applet ; +import java.util.Properties ; +import java.net.URL ; + +import com.sun.corba.ee.spi.orb.DataCollector ; + +public abstract class DataCollectorFactory { + private DataCollectorFactory() {} + + public static DataCollector create( Applet app, Properties props, + String localHostName ) + { + String appletHost = localHostName ; + + if (app != null) { + URL appletCodeBase = app.getCodeBase() ; + + if (appletCodeBase != null) + appletHost = appletCodeBase.getHost() ; + } + + return new AppletDataCollector( app, props, localHostName, + appletHost ) ; + } + + public static DataCollector create( String[] args, Properties props, + String localHostName ) + { + return new NormalDataCollector( args, props, localHostName, + localHostName ) ; + } + + public static DataCollector create( Properties props, + String localHostName ) + { + return new PropertyOnlyDataCollector( props, localHostName, + localHostName ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalDataCollector.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalDataCollector.java new file mode 100644 index 000000000..6bb480c65 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalDataCollector.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.net.InetAddress ; + +import java.util.Properties ; + +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.CompletionStatus ; + +public class NormalDataCollector extends DataCollectorBase { + private String[] args ; + + public NormalDataCollector( String[] args, Properties props, + String localHostName, String configurationHostName ) + { + super( props, localHostName, configurationHostName ) ; + this.args = args ; + } + + public boolean isApplet() + { + return false ; + } + + protected void collect() + { + checkPropertyDefaults() ; + + findPropertiesFromFile() ; + findPropertiesFromSystem() ; + findPropertiesFromProperties() ; + findPropertiesFromArgs( args ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalParserAction.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalParserAction.java new file mode 100644 index 000000000..9b29ae6e2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalParserAction.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.util.Properties ; + +import com.sun.corba.ee.spi.orb.Operation ; + +public class NormalParserAction extends ParserActionBase { + public NormalParserAction( String propertyName, + Operation operation, String fieldName ) + { + super( propertyName, false, operation, fieldName ) ; + } + + /** Create a String[] of all suffixes of property names that + * match the propertyName prefix, pass this to op, and return the + * result. + */ + public Object apply( Properties props ) + { + Object value = props.getProperty( getPropertyName() ) ; + if (value != null) + return getOperation().operate( value ) ; + else + return null ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalParserData.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalParserData.java new file mode 100644 index 000000000..d97f10317 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/NormalParserData.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.util.Properties ; + +import com.sun.corba.ee.spi.orb.Operation ; +import com.sun.corba.ee.spi.orb.PropertyParser ; + +public class NormalParserData extends ParserDataBase { + private String testData ; + + public NormalParserData( String propertyName, + Operation operation, String fieldName, Object defaultValue, + Object testValue, String testData ) + { + super( propertyName, operation, fieldName, defaultValue, testValue ) ; + this.testData = testData ; + } + public void addToParser( PropertyParser parser ) + { + parser.add( getPropertyName(), getOperation(), getFieldName() ) ; + } + + public void addToProperties( Properties props ) + { + props.setProperty( getPropertyName(), testData ) ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBConfiguratorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBConfiguratorImpl.java new file mode 100644 index 000000000..364328013 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBConfiguratorImpl.java @@ -0,0 +1,550 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.PrivilegedExceptionAction ; +import java.security.AccessController ; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher ; + +import com.sun.corba.ee.spi.copyobject.CopyobjectDefaults ; +import com.sun.corba.ee.spi.copyobject.CopierManager ; + +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; + +import com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory; + +import com.sun.corba.ee.spi.oa.OADefault ; +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory ; + +import com.sun.corba.ee.spi.orb.Operation ; +import com.sun.corba.ee.spi.orb.OperationFactory ; +import com.sun.corba.ee.spi.orb.ORBData ; +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.ORBConfigurator ; +import com.sun.corba.ee.spi.orb.ParserImplBase ; +import com.sun.corba.ee.spi.orb.PropertyParser ; +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry ; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; +import com.sun.corba.ee.spi.protocol.RequestDispatcherDefault ; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory ; + +import com.sun.corba.ee.spi.resolver.LocalResolver ; +import com.sun.corba.ee.spi.resolver.Resolver ; +import com.sun.corba.ee.spi.resolver.ResolverDefault ; + +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory; +import com.sun.corba.ee.spi.transport.SocketInfo; +import com.sun.corba.ee.spi.transport.TransportDefault ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults ; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults ; +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.impl.transport.AcceptorImpl; + +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.impl.legacy.connection.SocketFactoryAcceptorImpl; +import com.sun.corba.ee.impl.legacy.connection.SocketFactoryContactInfoListImpl; +import com.sun.corba.ee.impl.legacy.connection.USLPort; + +import com.sun.corba.ee.impl.dynamicany.DynAnyFactoryImpl ; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.spi.transport.Acceptor; +import org.glassfish.pfl.basic.func.NullaryFunction; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; + +public class ORBConfiguratorImpl implements ORBConfigurator { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + protected void persistentServerInitialization(ORB theOrb) { + // Does nothing, but can be overridden in subclass. + } + + public static class ConfigParser extends ParserImplBase { + private ORB orb ; + + public ConfigParser( ORB orb ) { + this.orb = orb ; + } ; + + public Class[] userConfigurators = null ; + + public PropertyParser makeParser() + { + PropertyParser parser = new PropertyParser() ; + Operation action = OperationFactory.compose( + OperationFactory.suffixAction(), + OperationFactory.classAction( orb.classNameResolver() ) + ) ; + parser.addPrefix( ORBConstants.USER_CONFIGURATOR_PREFIX, action, + "userConfigurators", Class.class ) ; + return parser ; + } + } + + public void configure( DataCollector collector, ORB orb ) + { + ORB theOrb = orb ; + + initObjectCopiers( theOrb ) ; + initIORFinders( theOrb ) ; + + theOrb.setClientDelegateFactory( + // REVISIT: this should be ProtocolDefault. + TransportDefault.makeClientDelegateFactory( theOrb )) ; + + initializeTransport(theOrb) ; + + initializeNaming( theOrb ) ; + initServiceContextRegistry( theOrb ) ; + initRequestDispatcherRegistry( theOrb ) ; + registerInitialReferences( theOrb ) ; + + // Set up the PIHandler now. The user configurator call is the + // earliest point at which an invocation on this ORB can occur due to + // external code extending the ORB through a configurator. + // persistentServerInitialization also needs to make invocations to ORBD. + // ORB invocations can also occur during the execution of + // the ORBInitializers. + theOrb.createPIHandler() ; + + theOrb.setInvocationInterceptor( + PresentationDefaults.getNullInvocationInterceptor() ) ; + + persistentServerInitialization( theOrb ) ; + + runUserConfigurators( collector, theOrb ) ; + } + + private void runUserConfigurators( DataCollector collector, ORB orb ) + { + // Run any pluggable configurators. This is a lot like + // ORBInitializers, only it uses the internal ORB and has + // access to all data for parsing. + ConfigParser parser = new ConfigParser( orb ) ; + parser.init( collector ) ; + if (parser.userConfigurators != null) { + for (int ctr=0; ctr() { + public Object run() + throws InstantiationException, IllegalAccessException + { + try { + Method method = + legacySocketFactory.getClass().getMethod( + "setORB", ORB.class ); + method.invoke(legacySocketFactory, orb); + } catch (NoSuchMethodException e) { + // NOTE: If there is no method then it + // is not ours - so ignore it. + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } + return null; + } + } + ); + } catch (Throwable t) { + throw wrapper.unableToSetSocketFactoryOrb(t); + } + } + + private void initializeNaming( ORB orb ) + { + LocalResolver localResolver = ResolverDefault.makeLocalResolver() ; + orb.setLocalResolver( localResolver ) ; + + Resolver bootResolver = ResolverDefault.makeBootstrapResolver( orb, + orb.getORBData().getORBInitialHost(), + orb.getORBData().getORBInitialPort() ) ; + + Operation urlOperation = ResolverDefault.makeINSURLOperation( orb ) ; + orb.setURLOperation( urlOperation ) ; + + Resolver irResolver = ResolverDefault.makeORBInitRefResolver( urlOperation, + orb.getORBData().getORBInitialReferences() ) ; + + Resolver dirResolver = ResolverDefault.makeORBDefaultInitRefResolver( + urlOperation, orb.getORBData().getORBDefaultInitialReference() ) ; + + Resolver resolver = + ResolverDefault.makeCompositeResolver( localResolver, + ResolverDefault.makeCompositeResolver( irResolver, + ResolverDefault.makeCompositeResolver( dirResolver, + bootResolver ) ) ) ; + orb.setResolver( resolver ) ; + } + + private void initServiceContextRegistry( ORB orb ) + { + ServiceContextFactoryRegistry scr = orb.getServiceContextFactoryRegistry() ; + + scr.register( + ServiceContextDefaults.makeUEInfoServiceContextFactory() ) ; + scr.register( + ServiceContextDefaults.makeCodeSetServiceContextFactory() ) ; + scr.register( + ServiceContextDefaults.makeSendingContextServiceContextFactory() ) ; + scr.register( + ServiceContextDefaults.makeORBVersionServiceContextFactory() ) ; + scr.register( + ServiceContextDefaults.makeMaxStreamFormatVersionServiceContextFactory() ) ; + } + + private void registerInitialReferences( final ORB orb ) + { + // Register the Dynamic Any factory + NullaryFunction closure = + new NullaryFunction() { + public org.omg.CORBA.Object evaluate() { + return new DynAnyFactoryImpl( orb ) ; + } + } ; + + NullaryFunction future = + NullaryFunction.Factory.makeFuture( closure ) ; + orb.getLocalResolver().register( ORBConstants.DYN_ANY_FACTORY_NAME, + future ) ; + } + + private static final int ORB_STREAM = 0 ; + + private void initObjectCopiers( ORB orb ) + { + // No optimization or policy selection here. + ObjectCopierFactory orbStream = + CopyobjectDefaults.makeORBStreamObjectCopierFactory( orb ) ; + + CopierManager cm = orb.getCopierManager() ; + cm.setDefaultId( ORB_STREAM ) ; + + cm.registerObjectCopierFactory( orbStream, ORB_STREAM ) ; + } + + private void initIORFinders( ORB orb ) + { + IdentifiableFactoryFinder profFinder = + orb.getTaggedProfileFactoryFinder() ; + profFinder.registerFactory( IIOPFactories.makeIIOPProfileFactory() ) ; + + IdentifiableFactoryFinder profTempFinder = + orb.getTaggedProfileTemplateFactoryFinder() ; + profTempFinder.registerFactory( + IIOPFactories.makeIIOPProfileTemplateFactory() ) ; + + IdentifiableFactoryFinder compFinder = + orb.getTaggedComponentFactoryFinder() ; + compFinder.registerFactory( + IIOPFactories.makeCodeSetsComponentFactory() ) ; + compFinder.registerFactory( + IIOPFactories.makeJavaCodebaseComponentFactory() ) ; + compFinder.registerFactory( + IIOPFactories.makeORBTypeComponentFactory() ) ; + compFinder.registerFactory( + IIOPFactories.makeMaxStreamFormatVersionComponentFactory() ) ; + compFinder.registerFactory( + IIOPFactories.makeAlternateIIOPAddressComponentFactory() ) ; + compFinder.registerFactory( + IIOPFactories.makeRequestPartitioningComponentFactory() ) ; + compFinder.registerFactory( + IIOPFactories.makeJavaSerializationComponentFactory()); + compFinder.registerFactory( + IIOPFactories.makeLoadBalancingComponentFactory()); + compFinder.registerFactory( + IIOPFactories.makeClusterInstanceInfoComponentFactory()); + + // Register the ValueFactory instances for ORT + IORFactories.registerValueFactories( orb ) ; + + // Register an ObjectKeyFactory + orb.setObjectKeyFactory( IORFactories.makeObjectKeyFactory(orb) ) ; + } + + private void initRequestDispatcherRegistry( ORB orb ) + { + RequestDispatcherRegistry scr = orb.getRequestDispatcherRegistry() ; + + // register client subcontracts + ClientRequestDispatcher csub = + RequestDispatcherDefault.makeClientRequestDispatcher() ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.TOA_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.TRANSIENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.PERSISTENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.SC_TRANSIENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.SC_PERSISTENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.IISC_TRANSIENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.IISC_PERSISTENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.MINSC_TRANSIENT_SCID ) ; + scr.registerClientRequestDispatcher( csub, + ORBConstants.MINSC_PERSISTENT_SCID ) ; + + // register server delegates + ServerRequestDispatcher sd = + RequestDispatcherDefault.makeServerRequestDispatcher( orb ); + scr.registerServerRequestDispatcher( sd, + ORBConstants.TOA_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.TRANSIENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.PERSISTENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.SC_TRANSIENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.SC_PERSISTENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.IISC_TRANSIENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.IISC_PERSISTENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.MINSC_TRANSIENT_SCID ) ; + scr.registerServerRequestDispatcher( sd, + ORBConstants.MINSC_PERSISTENT_SCID ) ; + + orb.setINSDelegate( + RequestDispatcherDefault.makeINSServerRequestDispatcher( orb ) ) ; + + // register local client subcontracts + LocalClientRequestDispatcherFactory lcsf = + RequestDispatcherDefault.makeJIDLLocalClientRequestDispatcherFactory( + orb ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.TOA_SCID ) ; + + lcsf = + RequestDispatcherDefault.makePOALocalClientRequestDispatcherFactory( + orb ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.TRANSIENT_SCID ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.PERSISTENT_SCID ) ; + + lcsf = RequestDispatcherDefault. + makeFullServantCacheLocalClientRequestDispatcherFactory( orb ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.SC_TRANSIENT_SCID ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.SC_PERSISTENT_SCID ) ; + + lcsf = RequestDispatcherDefault. + makeInfoOnlyServantCacheLocalClientRequestDispatcherFactory( orb ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.IISC_TRANSIENT_SCID ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.IISC_PERSISTENT_SCID ) ; + + lcsf = RequestDispatcherDefault. + makeMinimalServantCacheLocalClientRequestDispatcherFactory( orb ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.MINSC_TRANSIENT_SCID ) ; + scr.registerLocalClientRequestDispatcherFactory( lcsf, + ORBConstants.MINSC_PERSISTENT_SCID ) ; + + /* Register the server delegate that implements the ancient bootstrap + * naming protocol. This takes an object key of either "INIT" or + * "TINI" to allow for big or little endian implementations. + */ + ServerRequestDispatcher bootsd = + RequestDispatcherDefault.makeBootstrapServerRequestDispatcher( + orb ) ; + scr.registerServerRequestDispatcher( bootsd, "INIT" ) ; + scr.registerServerRequestDispatcher( bootsd, "TINI" ) ; + + // Register object adapter factories + ObjectAdapterFactory oaf = OADefault.makeTOAFactory( orb ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.TOA_SCID ) ; + + oaf = OADefault.makePOAFactory( orb ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.TRANSIENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.PERSISTENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.SC_TRANSIENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.SC_PERSISTENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.IISC_TRANSIENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.IISC_PERSISTENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.MINSC_TRANSIENT_SCID ) ; + scr.registerObjectAdapterFactory( oaf, ORBConstants.MINSC_PERSISTENT_SCID ) ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBDataParserImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBDataParserImpl.java new file mode 100644 index 000000000..955e716d9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBDataParserImpl.java @@ -0,0 +1,534 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.net.InetAddress; + +import org.omg.PortableInterceptor.ORBInitializer ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBData ; +import com.sun.corba.ee.spi.orb.ParserImplTableBase ; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; +import com.sun.corba.ee.spi.transport.TcpTimeouts; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; +import com.sun.corba.ee.impl.legacy.connection.USLPort; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.transport.Acceptor; +import org.glassfish.pfl.basic.contain.Pair; + + +public class ORBDataParserImpl extends ParserImplTableBase implements ORBData +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private String ORBInitialHost ; + private int ORBInitialPort ; + private String ORBServerHost ; + private int ORBServerPort ; + private boolean listenOnAllInterfaces; + private com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory legacySocketFactory ; + private com.sun.corba.ee.spi.transport.ORBSocketFactory socketFactory; + private USLPort[] userSpecifiedListenPorts ; + private IORToSocketInfo iorToSocketInfo; + private IIOPPrimaryToContactInfo iiopPrimaryToContactInfo; + private String orbId ; + private boolean allowLocalOptimization ; + private GIOPVersion giopVersion ; + private int highWaterMark ; + private int lowWaterMark ; + private int numberToReclaim ; + private int giopFragmentSize ; + private int giopBufferSize ; + private int giop11BuffMgr ; + private int giop12BuffMgr ; + private short giopTargetAddressPreference ; + private short giopAddressDisposition ; + private boolean useByteOrderMarkers ; + private boolean useByteOrderMarkersInEncaps ; + private boolean alwaysSendCodeSetCtx ; + private boolean persistentPortInitialized ; + private int persistentServerPort ; + private boolean persistentServerIdInitialized ; + private int persistentServerId ; + private boolean serverIsORBActivated ; + private Class badServerIdHandlerClass ; + private CodeSetComponentInfo.CodeSetComponent charData ; + private CodeSetComponentInfo.CodeSetComponent wcharData ; + private ORBInitializer[] orbInitializers ; + private Pair[] orbInitialReferences ; + private String defaultInitRef ; + private String[] debugFlags ; + private Acceptor[] acceptors; + private ContactInfoListFactory corbaContactInfoListFactory; + private String acceptorSocketType; + private boolean acceptorSocketUseSelectThreadToWait; + private boolean acceptorSocketUseWorkerThreadForEvent; + private String connectionSocketType; + private boolean connectionSocketUseSelectThreadToWait; + private boolean connectionSocketUseWorkerThreadForEvent; + private long communicationsRetryTimeout; + private long waitForResponseTimeout; + private TcpTimeouts tcpTimeouts; + private TcpTimeouts tcpConnectTimeouts; + private boolean disableDirectByteBufferUse; + private boolean enableJavaSerialization; + private boolean useRepId; + private boolean showInfoMessages; + private boolean getServiceContextReturnsNull; + private boolean isAppServerMode; + private int readByteBufferSize; + private int maxReadByteBufferSizeThreshold; + private int pooledDirectByteBufferSlabSize; + private boolean alwaysEnterBlockingRead; + private boolean nonBlockingReadCheckMessageParser; + private boolean blockingReadCheckMessageParser; + private boolean timingPointsEnabled; + private boolean useEnumDesc ; + private boolean environmentIsGFServer ; + private boolean noDefaultAcceptors ; + private boolean registerMBeans ; + private int fragmentReadTimeout ; + + // This is not initialized from ParserTable. + private CodeSetComponentInfo codesets ; + + private String[] orbInitArgs ; + private boolean disableORBD; + +// Public accessor methods ======================================================================== + + public String getORBInitialHost() + { + return ORBInitialHost; + } + + public int getORBInitialPort() + { + return ORBInitialPort; + } + + public String getORBServerHost() + { + return ORBServerHost; + } + + public boolean getListenOnAllInterfaces() + { + return listenOnAllInterfaces; + } + + public int getORBServerPort() + { + return ORBServerPort; + } + + public com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory getLegacySocketFactory() + { + return legacySocketFactory; + } + + public com.sun.corba.ee.spi.transport.ORBSocketFactory getSocketFactory() + { + return socketFactory; + } + + public USLPort[] getUserSpecifiedListenPorts () + { + return userSpecifiedListenPorts; + } + + public IORToSocketInfo getIORToSocketInfo() + { + return iorToSocketInfo; + } + + public void setIORToSocketInfo(IORToSocketInfo x) + { + iorToSocketInfo = x; + } + + public IIOPPrimaryToContactInfo getIIOPPrimaryToContactInfo() + { + return iiopPrimaryToContactInfo; + } + + public void setIIOPPrimaryToContactInfo(IIOPPrimaryToContactInfo x) + { + iiopPrimaryToContactInfo = x; + } + + public String getORBId() + { + return orbId; + } + + public boolean isLocalOptimizationAllowed() + { + return allowLocalOptimization ; + } + + public GIOPVersion getGIOPVersion() + { + return giopVersion; + } + + public int getHighWaterMark() + { + return highWaterMark; + } + + public int getLowWaterMark() + { + return lowWaterMark; + } + + public int getNumberToReclaim() + { + return numberToReclaim; + } + + public int getGIOPFragmentSize() + { + return giopFragmentSize; + } + + public int getGIOPBufferSize() + { + return giopBufferSize; + } + + public int getGIOPBuffMgrStrategy(GIOPVersion gv) + { + if(gv!=null){ + if (gv.equals(GIOPVersion.V1_0)) { + return 0; + } //Always grow for 1.0 + if (gv.equals(GIOPVersion.V1_1)) { + return giop11BuffMgr; + } + if (gv.equals(GIOPVersion.V1_2)) { + return giop12BuffMgr; + } + } + //If a "faulty" GIOPVersion is passed, it's going to return 0; + return 0; + } + + /** + * @return the GIOP Target Addressing preference of the ORB. + * This ORB by default supports all addressing dispositions unless specified + * otherwise via a java system property ORBConstants.GIOP_TARGET_ADDRESSING + */ + public short getGIOPTargetAddressPreference() + { + return giopTargetAddressPreference; + } + + public short getGIOPAddressDisposition() + { + return giopAddressDisposition; + } + + public boolean useByteOrderMarkers() + { + return useByteOrderMarkers; + } + + public boolean useByteOrderMarkersInEncapsulations() + { + return useByteOrderMarkersInEncaps; + } + + public boolean alwaysSendCodeSetServiceContext() + { + return alwaysSendCodeSetCtx; + } + + public boolean getPersistentPortInitialized() + { + return persistentPortInitialized ; + } + + public int getPersistentServerPort() + { + if ( persistentPortInitialized ) { + return persistentServerPort; + } + else { + throw wrapper.persistentServerportNotSet( ) ; + } + } + + public boolean getPersistentServerIdInitialized() + { + return persistentServerIdInitialized; + } + + /** Return the persistent-server-id of this server. This id is the same + * across multiple activations of this server. This is in contrast to + * com.sun.corba.ee.impl.iiop.ORB.getTransientServerId() which + * returns a transient id that is guaranteed to be different + * across multiple activations of + * this server. The user/environment is required to supply the + * persistent-server-id every time this server is started, in + * the ORBServerId parameter, System properties, or other means. + * The user is also required to ensure that no two persistent servers + * on the same host have the same server-id. + */ + public int getPersistentServerId() + { + if ( persistentServerIdInitialized ) { + return persistentServerId; + } else { + throw wrapper.persistentServeridNotSet( ) ; + } + } + + public boolean getServerIsORBActivated() + { + return serverIsORBActivated ; + } + + public Class getBadServerIdHandler() + { + return badServerIdHandlerClass ; + } + + /** + * Get the prefered code sets for connections. Should the client send the code set service context on every + * request? + */ + public CodeSetComponentInfo getCodeSetComponentInfo() + { + return codesets; + } + + public ORBInitializer[] getORBInitializers() + { + return orbInitializers ; + } + + public void addORBInitializer( ORBInitializer initializer ) + { + ORBInitializer[] arr = new ORBInitializer[orbInitializers.length+1] ; + System.arraycopy(orbInitializers, 0, arr, 0, orbInitializers.length); + arr[orbInitializers.length] = initializer ; + orbInitializers = arr ; + } + + public Pair[] getORBInitialReferences() + { + return orbInitialReferences ; + } + + public String getORBDefaultInitialReference() + { + return defaultInitRef ; + } + + public String[] getORBDebugFlags() + { + return debugFlags ; + } + + public Acceptor[] getAcceptors() + { + return acceptors; + } + + public ContactInfoListFactory getCorbaContactInfoListFactory() + { + return corbaContactInfoListFactory; + } + + public String acceptorSocketType() + { + return acceptorSocketType; + } + public boolean acceptorSocketUseSelectThreadToWait() + { + return acceptorSocketUseSelectThreadToWait; + } + public boolean acceptorSocketUseWorkerThreadForEvent() + { + return acceptorSocketUseWorkerThreadForEvent; + } + public String connectionSocketType() + { + return connectionSocketType; + } + public boolean connectionSocketUseSelectThreadToWait() + { + return connectionSocketUseSelectThreadToWait; + } + public boolean connectionSocketUseWorkerThreadForEvent() + { + return connectionSocketUseWorkerThreadForEvent; + } + public boolean isJavaSerializationEnabled() + { + return enableJavaSerialization; + } + public long getCommunicationsRetryTimeout() + { + return communicationsRetryTimeout; + } + public long getWaitForResponseTimeout() + { + return waitForResponseTimeout; + } + public TcpTimeouts getTransportTcpTimeouts() + { + return tcpTimeouts; + } + public TcpTimeouts getTransportTcpConnectTimeouts() + { + return tcpConnectTimeouts; + } + public boolean disableDirectByteBufferUse() + { + return disableDirectByteBufferUse ; + } + public boolean useRepId() + { + return useRepId; + } + + public boolean showInfoMessages() + { + return showInfoMessages; + } + + public boolean getServiceContextReturnsNull() + { + return getServiceContextReturnsNull; + } + + public boolean isAppServerMode() + { + return isAppServerMode; + + } + + public int getReadByteBufferSize() { + return readByteBufferSize; + } + + public int getMaxReadByteBufferSizeThreshold() { + return maxReadByteBufferSizeThreshold; + } + + public int getPooledDirectByteBufferSlabSize() { + return pooledDirectByteBufferSlabSize; + } + + public boolean alwaysEnterBlockingRead() { + return alwaysEnterBlockingRead; + } + + public void alwaysEnterBlockingRead(boolean b) { + alwaysEnterBlockingRead = b; + } + + public boolean nonBlockingReadCheckMessageParser() { + return nonBlockingReadCheckMessageParser; + } + + public boolean blockingReadCheckMessageParser() { + return blockingReadCheckMessageParser; + } + + // ====== Methods for constructing and initializing this object ========= + + public ORBDataParserImpl( ORB orb, DataCollector coll ) + { + super( ParserTable.get( + ORB.defaultClassNameResolver() ).getParserData() ) ; + init( coll ) ; + } + + @Override + public void complete() + { + codesets = new CodeSetComponentInfo(charData, wcharData); + initializeServerHostInfo(); + } + + private void initializeServerHostInfo() + { + if (ORBServerHost == null || + ORBServerHost.equals("") || + ORBServerHost.equals("0.0.0.0") || + ORBServerHost.equals("::") || + ORBServerHost.toLowerCase().equals("::ffff:0.0.0.0")) + { + try + { + ORBServerHost = InetAddress.getLocalHost().getHostAddress(); + } + catch (Exception ex) + { + throw wrapper.getLocalHostFailed(ex); + } + listenOnAllInterfaces = true; + } + else + { + listenOnAllInterfaces = false; + } + } + public boolean timingPointsEnabled() + { + return timingPointsEnabled ; + } + + public boolean useEnumDesc() + { + return useEnumDesc ; + } + + public boolean environmentIsGFServer() { + return environmentIsGFServer ; + } + + public boolean noDefaultAcceptors() { + return noDefaultAcceptors ; + } + + public boolean registerMBeans() { + return registerMBeans ; + } + + public int fragmentReadTimeout() { + return fragmentReadTimeout ; + } + + public void setOrbInitArgs( String[] args ) { + orbInitArgs = args ; + } + + public String[] getOrbInitArgs() { + return orbInitArgs ; + } + + public boolean disableORBD() { + return disableORBD ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBImpl.java new file mode 100644 index 000000000..20e33055b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBImpl.java @@ -0,0 +1,2117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.applet.Applet; + +import java.io.IOException ; + +import java.lang.reflect.Constructor; +import java.util.Arrays; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock ; + +import java.util.List ; +import java.util.Set ; +import java.util.HashSet ; +import java.util.ArrayList ; +import java.util.Iterator ; +import java.util.Properties ; +import java.util.Map ; +import java.util.HashMap ; +import java.util.WeakHashMap ; + +import java.net.InetAddress ; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.rmi.CORBA.ValueHandler; + +import org.omg.CORBA.NVList; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.Request; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.CORBA.StructMember; +import org.omg.CORBA.UnionMember; +import org.omg.CORBA.ValueMember; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.BAD_OPERATION; + +import org.omg.CORBA.portable.ValueFactory; + +import org.omg.CORBA.ORBPackage.InvalidName; + +import com.sun.org.omg.SendingContext.CodeBase; + +import com.sun.corba.ee.spi.protocol.ClientInvocationInfo ; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.TaggedProfile; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.TaggedComponentFactoryFinder; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.ObjectKeyFactory ; +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory; +import com.sun.corba.ee.spi.orb.DataCollector; +import com.sun.corba.ee.spi.orb.Operation; +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.orb.ORBConfigurator; +import com.sun.corba.ee.spi.orb.ParserImplBase; +import com.sun.corba.ee.spi.orb.PropertyParser; +import com.sun.corba.ee.spi.orb.OperationFactory; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.protocol.ClientDelegateFactory; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.protocol.PIHandler; +import com.sun.corba.ee.spi.resolver.Resolver; +import com.sun.corba.ee.spi.resolver.LocalResolver; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketManager; +import com.sun.corba.ee.spi.copyobject.CopierManager ; +import com.sun.corba.ee.spi.presentation.rmi.InvocationInterceptor ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry; +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.ServiceContextsCache; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.impl.corba.NVListImpl; +import com.sun.corba.ee.impl.corba.ExceptionListImpl; +import com.sun.corba.ee.impl.corba.ContextListImpl; +import com.sun.corba.ee.impl.corba.NamedValueImpl; +import com.sun.corba.ee.impl.corba.EnvironmentImpl; +import com.sun.corba.ee.impl.corba.AsynchInvoke; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.encoding.CachedCodeBase; +import com.sun.corba.ee.impl.interceptors.PIHandlerImpl; +import com.sun.corba.ee.impl.ior.TaggedComponentFactoryFinderImpl; +import com.sun.corba.ee.impl.ior.TaggedProfileFactoryFinderImpl; +import com.sun.corba.ee.impl.ior.TaggedProfileTemplateFactoryFinderImpl; +import com.sun.corba.ee.impl.oa.toa.TOAFactory; +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler; +import com.sun.corba.ee.impl.oa.poa.POAFactory; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.threadpool.ThreadPoolManagerImpl; +import com.sun.corba.ee.impl.protocol.RequestDispatcherRegistryImpl; +import com.sun.corba.ee.impl.protocol.InvocationInfo; +import com.sun.corba.ee.impl.transport.TransportManagerImpl; +import com.sun.corba.ee.impl.legacy.connection.LegacyServerSocketManagerImpl; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.copyobject.CopierManagerImpl; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; +import com.sun.corba.ee.impl.misc.ByteArrayWrapper; +import com.sun.corba.ee.spi.trace.OrbLifeCycle; +import com.sun.corba.ee.spi.trace.Subcontract; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReadWriteLock; +import org.glassfish.pfl.basic.algorithm.ObjectUtility; +import org.glassfish.pfl.basic.concurrent.WeakCache; +import org.glassfish.pfl.basic.contain.StackImpl; +import org.glassfish.pfl.basic.contain.ResourceFactory; +import org.glassfish.pfl.basic.func.NullaryFunction; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * The JavaIDL ORB implementation. + */ +@OrbLifeCycle +@Subcontract +public class ORBImpl extends com.sun.corba.ee.spi.orb.ORB +{ + private boolean set_parameters_called = false ; + + protected TransportManager transportManager; + protected LegacyServerSocketManager legacyServerSocketManager; + + private ThreadLocal> + OAInvocationInfoStack ; + + private ThreadLocal> + clientInvocationInfoStack ; + + // pure java orb, caching the servant IOR per ORB + private CodeBase codeBase = null ; + private IOR codeBaseIOR = null ; + + // List holding deferred Requests + private final List dynamicRequests = + new ArrayList(); + + private final SynchVariable svResponseReceived = new SynchVariable(); + + + private final Object runObj = new Object(); + private final Object shutdownObj = new Object(); + private final AtomicInteger numWaiters = new AtomicInteger() ; + private final Object waitForCompletionObj = new Object(); + private static final byte STATUS_OPERATING = 1; + private static final byte STATUS_SHUTTING_DOWN = 2; + private static final byte STATUS_SHUTDOWN = 3; + private static final byte STATUS_DESTROYED = 4; + private final ReadWriteLock statueLock = new ReentrantReadWriteLock() ; + private byte status = STATUS_OPERATING; + + private final java.lang.Object invocationObj = new java.lang.Object(); + private AtomicInteger numInvocations = new AtomicInteger(); + + // thread local variable to store a boolean to detect deadlock in + // ORB.shutdown(true). + private ThreadLocal isProcessingInvocation = + new ThreadLocal () { + @Override + protected Boolean initialValue() { + return false ; + } + }; + + // This map is caching TypeCodes created for a certain class (key) + // and is used in Util.writeAny() + private Map,TypeCodeImpl> typeCodeForClassMap ; + + // Cache to hold ValueFactories (Helper classes) keyed on repository ids + private Map valueFactoryCache = + new HashMap(); + + // thread local variable to store the current ORB version. + // default ORB version is the version of ORB with correct Rep-id + // changes + private ThreadLocal orbVersionThreadLocal ; + + private RequestDispatcherRegistry requestDispatcherRegistry ; + + private CopierManager copierManager ; + + private int transientServerId ; + + private ServiceContextFactoryRegistry serviceContextFactoryRegistry ; + + private ServiceContextsCache serviceContextsCache; + + // Needed here to implement connect/disconnect + private ResourceFactory toaFactory = + new ResourceFactory( + new NullaryFunction() { + public TOAFactory evaluate() { + return (TOAFactory)requestDispatcherRegistry.getObjectAdapterFactory( + ORBConstants.TOA_SCID) ; + } + } + ); + + // Needed here for set_delegate + private ResourceFactory poaFactory = + new ResourceFactory( + new NullaryFunction() { + public POAFactory evaluate() { + return (POAFactory)requestDispatcherRegistry.getObjectAdapterFactory( + ORBConstants.TRANSIENT_SCID) ; + } + } + ); + + // The interceptor handler, which provides portable interceptor services for + // subcontracts and object adapters. + private PIHandler pihandler ; + + private ORBData configData ; + + private BadServerIdHandler badServerIdHandler ; + + private ClientDelegateFactory clientDelegateFactory ; + + private ContactInfoListFactory corbaContactInfoListFactory ; + + // All access to resolver, localResolver, and urlOperation must be protected using + // the appropriate locks. Do not hold the ORBImpl lock while accessing + // resolver, or deadlocks may occur. + // Note that we now have separate locks for each resolver type. This is due + // to bug 6238477, which was caused by a deadlock while resolving a + // corbaname: URL that contained a reference to the same ORB as the + // ORB making the call to string_to_object. This caused a deadlock between the + // client thread holding the single lock for access to the urlOperation, + // and the server thread handling the client is_a request waiting on the + // same lock to access the localResolver. + + // Used for resolver_initial_references and list_initial_services + private Resolver resolver ; + + // Used for register_initial_references + private LocalResolver localResolver ; + + // ServerRequestDispatcher used for all INS object references. + private ServerRequestDispatcher insNamingDelegate ; + + // resolverLock must be used for all access to either resolver or + // localResolver, since it is possible for the resolver to indirectly + // refer to the localResolver. Also used to protect access to + // insNamingDelegate. + private final Object resolverLock = new Object() ; + + // Converts strings to object references for resolvers and string_to_object + private Operation urlOperation ; + private final Object urlOperationLock = new java.lang.Object() ; + + private TaggedComponentFactoryFinder + taggedComponentFactoryFinder ; + + private IdentifiableFactoryFinder + taggedProfileFactoryFinder ; + + private IdentifiableFactoryFinder + taggedProfileTemplateFactoryFinder ; + + private ObjectKeyFactory objectKeyFactory ; + + private boolean orbOwnsThreadPoolManager = false ; + + private ThreadPoolManager threadpoolMgr; + + private InvocationInterceptor invocationInterceptor ; + + private WeakCache objectKeyCache = + new WeakCache () { + @Override + protected ObjectKeyCacheEntry lookup(ByteArrayWrapper key) { + ObjectKey okey = ORBImpl.this.getObjectKeyFactory().create( + key.getObjKey()); + ObjectKeyCacheEntry entry = new ObjectKeyCacheEntryImpl( okey ) ; + return entry ; + } + } ; + + public InvocationInterceptor getInvocationInterceptor() { + return invocationInterceptor ; + } + + public void setInvocationInterceptor( InvocationInterceptor interceptor ) { + this.invocationInterceptor = interceptor ; + } + + //////////////////////////////////////////////////// + // + // NOTE: + // + // Methods that are synchronized MUST stay synchronized. + // + // Methods that are NOT synchronized must stay that way to avoid deadlock. + // + // + // REVISIT: + // + // checkShutDownState - lock on different object - and normalize usage. + // starting/FinishDispatch and Shutdown + // + + public ORBData getORBData() + { + return configData ; + } + + public PIHandler getPIHandler() + { + return pihandler ; + } + + public void createPIHandler() + { + this.pihandler = new PIHandlerImpl( this, configData.getOrbInitArgs() ) ; + } + + /** + * Create a new ORB. Should be followed by the appropriate + * set_parameters() call. + */ + public ORBImpl() + { + // All initialization is done through set_parameters(). + } + + public ORBVersion getORBVersion() + { + return orbVersionThreadLocal.get() ; + } + + public void setORBVersion(ORBVersion verObj) + { + orbVersionThreadLocal.set(verObj); + } + + + @OrbLifeCycle + private void initManagedObjectManager() { + createORBManagedObjectManager() ; + mom.registerAtRoot( configData ) ; + } + +/**************************************************************************** + * The following methods are ORB initialization + ****************************************************************************/ + + // preInit initializes all non-pluggable ORB data that is independent + // of the property parsing. + private void preInit( String[] params, Properties props ) + { + // This is the unique id of this server (JVM). Multiple incarnations + // of this server will get different ids. + // Compute transientServerId = milliseconds since Jan 1, 1970 + // Note: transientServerId will wrap in about 2^32 / 86400000 = 49.7 days. + // If two ORBS are started at the same time then there is a possibility + // of having the same transientServerId. This may result in collision + // and may be a problem in ior.isLocal() check to see if the object + // belongs to the current ORB. This problem is taken care of by checking + // to see if the IOR port matches ORB server port in legacyIsLocalServerPort() + // method. + transientServerId = (int)System.currentTimeMillis(); + + orbVersionThreadLocal = new ThreadLocal() { + @Override + protected ORBVersion initialValue() { + // set default to version of the ORB with correct Rep-ids + return ORBVersionFactory.getORBVersion() ; + } + }; + + requestDispatcherRegistry = new RequestDispatcherRegistryImpl( + ORBConstants.DEFAULT_SCID); + copierManager = new CopierManagerImpl() ; + + taggedComponentFactoryFinder = + new TaggedComponentFactoryFinderImpl(this) ; + taggedProfileFactoryFinder = + new TaggedProfileFactoryFinderImpl(this) ; + taggedProfileTemplateFactoryFinder = + new TaggedProfileTemplateFactoryFinderImpl(this) ; + + OAInvocationInfoStack = + new ThreadLocal> () { + @Override + protected StackImpl initialValue() { + return new StackImpl(); + } + }; + + clientInvocationInfoStack = + new ThreadLocal>() { + @Override + protected StackImpl initialValue() { + return new StackImpl(); + } + }; + + serviceContextFactoryRegistry = + ServiceContextDefaults.makeServiceContextFactoryRegistry( this ) ; + } + + @InfoMethod + private void configDataParsingComplete(String oRBId) { } + + @InfoMethod + private void transportInitializationComplete(String oRBId) { } + + @InfoMethod + private void userConfiguratorExecutionComplete(String oRBId) { } + + @InfoMethod + private void interceptorInitializationComplete(String oRBId) { } + + @InfoMethod + private void mbeansRegistereed(String oRBId) { } + + @InfoMethod + private void initializationComplete(String oRBId) { } + + @InfoMethod + private void startingShutdown(String oRBId) { } + + @InfoMethod + private void startingDestruction(String oRBId) { } + + @InfoMethod + private void isLocalServerIdInfo(int subcontractId, int serverId, + int transientServerId, boolean aTransient, + boolean persistentServerIdInitialized, int psid) { } + + // Class that defines a parser that gets the name of the + // ORBConfigurator class. + private class ConfigParser extends ParserImplBase { + // The default here is the ORBConfiguratorImpl that we define, + // but this can be replaced. + public Class configurator ; + + public ConfigParser( boolean disableORBD ) { + // Default configurator + configurator = ORBConfiguratorImpl.class ; + + if (!disableORBD) { + // Note: this class is NOT included in the GF bundles! + // Try to load it if present. + String cname = + "com.sun.corba.ee.impl.activation.ORBConfiguratorPersistentImpl" ; + + try { + configurator = Class.forName(cname); + } catch (ClassNotFoundException ex) { + Logger.getLogger(ORBImpl.class.getName()).log(Level.FINE, null, ex); + } + } + } + + public PropertyParser makeParser() + { + PropertyParser parser = new PropertyParser() ; + parser.add( ORBConstants.SUN_PREFIX + "ORBConfigurator", + OperationFactory.classAction( classNameResolver() ), + "configurator" ) ; + return parser ; + } + } + + // Map String to Integer to count number of ORBs with the + // same ORBId. + private static final Map idcount = + new HashMap() ; + private String rootName = null ; + + @Override + public synchronized String getUniqueOrbId() { + if (rootName == null) { + String orbid = getORBData().getORBId() ; + if (orbid.length() == 0) { + orbid = "orb"; + } + + int num = 1 ; + // Look up the current count of ORB instances with + // the same ORBId. If this is the first instance, + // the count is 1, otherwise increment the count. + synchronized (idcount) { + if (idcount.containsKey( orbid )) { + num = idcount.get( orbid ) + 1 ; + } + + idcount.put( orbid, num ) ; + } + + if (num != 1) { + rootName = orbid + "_" + num ; + } else { + rootName = orbid ; + } + } + + return rootName ; + } + + @OrbLifeCycle + private void postInit( String[] params, DataCollector dataCollector ) { + // First, create the standard ORB config data. + // This must be initialized before the ORBConfigurator + // is executed. Note that the orbId is initialized here. + configData = new ORBDataParserImpl( this, dataCollector) ; + if (orbInitDebug) { + System.out.println( "Contents of ORB configData:" ) ; + System.out.println( ObjectUtility.defaultObjectToString( configData ) ) ; + } + configData.setOrbInitArgs( params ) ; + + // Set the debug flags early so they can be used by other + // parts of the initialization. + setDebugFlags( configData.getORBDebugFlags() ) ; + configDataParsingComplete( getORBData().getORBId() ) ; + + initManagedObjectManager() ; + + // The TimerManager must be + // initialized BEFORE the pihandler.initialize() call, in + // case we want to time interceptor setup. Obviously we + // want to initialize the timerManager as early as possible + // so we can time parts of initialization if desired. + // timerManager = makeTimerManager( mom ) ; + + // This requires a valid TimerManager. + initializePrimitiveTypeCodeConstants() ; + + // REVISIT: this should go away after more transport init cleanup + // and going to ORT based ORBD. + transportManager = new TransportManagerImpl(this); + getLegacyServerSocketManager(); + + transportInitializationComplete( getORBData().getORBId() ) ; + + super.getByteBufferPool(); + serviceContextsCache = new ServiceContextsCache(this); + + // Create a parser to get the configured ORBConfigurator. + ConfigParser parser = new ConfigParser( configData.disableORBD() ) ; + parser.init( dataCollector ) ; + + ORBConfigurator configurator = null ; + String name = "NO NAME AVAILABLE" ; + if (parser.configurator == null) { + throw wrapper.badOrbConfigurator( name ) ; + } else { + try { + configurator = + (ORBConfigurator)(parser.configurator.newInstance()) ; + } catch (Exception iexc) { + name = parser.configurator.getName() ; + throw wrapper.badOrbConfigurator( iexc, name ) ; + } + } + + // Finally, run the configurator. Note that the default implementation allows + // other configurators with their own parsers to run, + // using the same DataCollector. + try { + configurator.configure( dataCollector, this ) ; + } catch (Exception exc) { + throw wrapper.orbConfiguratorError( exc ) ; + } + + userConfiguratorExecutionComplete( getORBData().getORBId() ) ; + + // Initialize the thread manager pool + // so it may be initialized & accessed without synchronization. + // This must take place here so that a user conifigurator can + // set the threadpool manager first. + getThreadPoolManager(); + + // Last of all, run the ORB initializers. + // Interceptors will not be executed until + // after pihandler.initialize(). A request that starts before + // initialize completes and completes after initialize completes does + // not see any interceptors. + pihandler.initialize() ; + + interceptorInitializationComplete( getORBData().getORBId() ) ; + + // Now the ORB is ready, so finish all of the MBean registration + if (configData.registerMBeans()) { + mom.resumeJMXRegistration() ; + mbeansRegistereed( getORBData().getORBId() ) ; + } + } + + private POAFactory getPOAFactory() { + return poaFactory.get() ; + } + + private TOAFactory getTOAFactory() { + return toaFactory.get() ; + } + + public void check_set_parameters() { + if (set_parameters_called) { + throw wrapper.setParameterCalledAgain() ; + } else { + set_parameters_called = true ; + } + } + + @OrbLifeCycle + public void set_parameters( Properties props ) + { + preInit( null, props ) ; + DataCollector dataCollector = + DataCollectorFactory.create( props, getLocalHostName() ) ; + postInit( null, dataCollector ) ; + initializationComplete( getORBData().getORBId() ) ; + } + + @OrbLifeCycle + protected void set_parameters(Applet app, Properties props) + { + preInit( null, props ) ; + DataCollector dataCollector = + DataCollectorFactory.create( app, props, getLocalHostName() ) ; + postInit( null, dataCollector ) ; + initializationComplete( getORBData().getORBId() ) ; + } + + public void setParameters( String[] params, Properties props ) { + set_parameters( params, props ) ; + } + + /* we can't create object adapters inside the ORB init path, or else we'll get this same problem + * in slightly different ways. (address in use exception) + * Having an IORInterceptor (TxSecIORInterceptor) get called during ORB init always results in a + * nested ORB.init call because of the call to getORB in the IORInterceptor. + */ + protected void set_parameters (String[] params, Properties props) + { + preInit( params, props ) ; + DataCollector dataCollector = + DataCollectorFactory.create( params, props, getLocalHostName() ) ; + postInit( params, dataCollector ) ; + } + +/**************************************************************************** + * The following methods are standard public CORBA ORB APIs + ****************************************************************************/ + + public synchronized org.omg.CORBA.portable.OutputStream create_output_stream() + { + return OutputStreamFactory.newEncapsOutputStream(this); + } + + /** + * Get a Current pseudo-object. + * The Current interface is used to manage thread-specific + * information for use by the transactions, security and other + * services. This method is deprecated, + * and replaced by ORB.resolve_initial_references("NameOfCurrentObject"); + * + * @return a Current pseudo-object. + * @deprecated + */ + @Override + public synchronized org.omg.CORBA.Current get_current() + { + checkShutdownState(); + + /* _REVISIT_ + The implementation of get_current is not clear. How would + ORB know whether the caller wants a Current for transactions + or security ?? Or is it assumed that there is just one + implementation for both ? If Current is thread-specific, + then it should not be instantiated; so where does the + ORB get a Current ? + + This should probably be deprecated. */ + + throw wrapper.genericNoImpl() ; + } + + /** + * Create an NVList + * + * @param count size of list to create + * @return NVList created + * + * @see NVList + */ + public synchronized NVList create_list(int count) + { + checkShutdownState(); + return new NVListImpl(this, count); + } + + /** + * Create an NVList corresponding to an OperationDef + * + * @param oper operation def to use to create list + * @return NVList created + * + * @see NVList + */ + @Override + public synchronized NVList create_operation_list(org.omg.CORBA.Object oper) + { + checkShutdownState(); + throw wrapper.genericNoImpl() ; + } + + /** + * Create a NamedValue + * + * @return NamedValue created + */ + public synchronized NamedValue create_named_value(String s, Any any, int flags) + { + checkShutdownState(); + return new NamedValueImpl(this, s, any, flags); + } + + /** + * Create an ExceptionList + * + * @return ExceptionList created + */ + public synchronized org.omg.CORBA.ExceptionList create_exception_list() + { + checkShutdownState(); + return new ExceptionListImpl(); + } + + /** + * Create a ContextList + * + * @return ContextList created + */ + public synchronized org.omg.CORBA.ContextList create_context_list() + { + checkShutdownState(); + return new ContextListImpl(this); + } + + /** + * Get the default Context object + * + * @return the default Context object + */ + public synchronized org.omg.CORBA.Context get_default_context() + { + checkShutdownState(); + throw wrapper.genericNoImpl() ; + } + + /** + * Create an Environment + * + * @return Environment created + */ + public synchronized org.omg.CORBA.Environment create_environment() + { + checkShutdownState(); + return new EnvironmentImpl(); + } + + public synchronized void send_multiple_requests_oneway(Request[] req) + { + checkShutdownState(); + + // Invoke the send_oneway on each new Request + for (int i = 0; i < req.length; i++) { + req[i].send_oneway(); + } + } + + /** + * Send multiple dynamic requests asynchronously. + * + * @param req an array of request objects. + */ + public synchronized void send_multiple_requests_deferred(Request[] req) + { + checkShutdownState(); + dynamicRequests.addAll(Arrays.asList(req)); + + // Invoke the send_deferred on each new Request + for (Request r : req) { + AsynchInvoke invokeObject = new AsynchInvoke( this, + (com.sun.corba.ee.impl.corba.RequestImpl)r, true); + new Thread(invokeObject).start(); + } + } + + /** + * Find out if any of the deferred invocations have a response yet. + */ + public synchronized boolean poll_next_response() + { + checkShutdownState(); + + // poll on each pending request + synchronized(dynamicRequests) { + for (Request r : dynamicRequests) { + if (r.poll_response()) { + return true; + } + } + } + return false; + } + + /** + * Get the next request that has gotten a response. + * + * @return the next request ready with a response. + */ + public org.omg.CORBA.Request get_next_response() + throws org.omg.CORBA.WrongTransaction + { + synchronized( this ) { + checkShutdownState(); + } + + while (true) { + // check if there already is a response + synchronized ( dynamicRequests ) { + Iterator iter = dynamicRequests.iterator() ; + while (iter.hasNext()) { + Request curr = iter.next() ; + if (curr.poll_response()) { + curr.get_response() ; + iter.remove() ; + return curr ; + } + } + } + + // wait for a response + synchronized(this.svResponseReceived) { + while (!this.svResponseReceived.value()) { + try { + this.svResponseReceived.wait(); + } catch(java.lang.InterruptedException ex) { + // NO-OP + } + } + // reinitialize the response flag + this.svResponseReceived.reset(); + } + } + } + + /** + * Notify response to ORB for get_next_response + */ + public void notifyORB() + { + synchronized (this.svResponseReceived) { + this.svResponseReceived.set(); + this.svResponseReceived.notify(); + } + } + + /** + * Convert an object ref to a string. + * @param obj The object to stringify. + * @return A stringified object reference. + */ + public synchronized String object_to_string(org.omg.CORBA.Object obj) + { + checkShutdownState(); + + // Handle the null objref case + if (obj == null) { + IOR nullIOR = IORFactories.makeIOR( this ) ; + return nullIOR.stringify(); + } + + IOR ior = null ; + + try { + ior = getIOR( obj, true ) ; + } catch (BAD_PARAM bp) { + // Throw MARSHAL instead if this is a LOCAL_OBJECT_NOT_ALLOWED error. + if (bp.minor == ORBUtilSystemException.LOCAL_OBJECT_NOT_ALLOWED) { + throw omgWrapper.notAnObjectImpl( bp ) ; + } else { + throw bp; + } + } + + return ior.stringify() ; + } + + /** + * Convert a stringified object reference to the object it represents. + * @param str The stringified object reference. + * @return The unstringified object reference. + */ + public org.omg.CORBA.Object string_to_object(String str) + { + Operation op ; + + synchronized (this) { + checkShutdownState(); + op = urlOperation ; + } + + if (str == null) { + throw wrapper.nullParam(); + } + + synchronized (urlOperationLock) { + org.omg.CORBA.Object obj = (org.omg.CORBA.Object)op.operate( str ) ; + return obj ; + } + } + + // pure java orb support, moved this method from FVDCodeBaseImpl. + // Note that we connect this if we have not already done so. + public synchronized IOR getFVDCodeBaseIOR() + { + if (codeBaseIOR == null) { + ValueHandler vh = ORBUtility.createValueHandler(); + codeBase = (CodeBase)vh.getRunTimeCodeBase(); + codeBaseIOR = getIOR( codeBase, true ) ; + } + + return codeBaseIOR; + } + + /** + * Get the TypeCode for a primitive type. + * + * @param tcKind the integer kind for the primitive type + * @return the requested TypeCode + */ + public TypeCode get_primitive_tc(TCKind tcKind) { + return get_primitive_tc( tcKind.value() ) ; + } + + /** + * Create a TypeCode for a structure. + * + * @param id the logical id for the typecode. + * @param name the name for the typecode. + * @param members an array describing the members of the TypeCode. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_struct_tc(String id, + String name, + StructMember[] members) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_struct, id, name, members); + } + + /** + * Create a TypeCode for a union. + * + * @param id the logical id for the typecode. + * @param name the name for the typecode. + * @param discriminator_type + * the type of the union discriminator. + * @param members an array describing the members of the TypeCode. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_union_tc(String id, + String name, + TypeCode discriminator_type, + UnionMember[] members) + { + checkShutdownState(); + return new TypeCodeImpl(this, + TCKind._tk_union, + id, + name, + discriminator_type, + members); + } + + /** + * Create a TypeCode for an enum. + * + * @param id the logical id for the typecode. + * @param name the name for the typecode. + * @param members an array describing the members of the TypeCode. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_enum_tc(String id, + String name, + String[] members) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_enum, id, name, members); + } + + /** + * Create a TypeCode for an alias. + * + * @param id the logical id for the typecode. + * @param name the name for the typecode. + * @param original_type + * the type this is an alias for. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_alias_tc(String id, + String name, + TypeCode original_type) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_alias, id, name, original_type); + } + + /** + * Create a TypeCode for an exception. + * + * @param id the logical id for the typecode. + * @param name the name for the typecode. + * @param members an array describing the members of the TypeCode. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_exception_tc(String id, + String name, + StructMember[] members) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_except, id, name, members); + } + + /** + * Create a TypeCode for an interface. + * + * @param id the logical id for the typecode. + * @param name the name for the typecode. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_interface_tc(String id, + String name) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_objref, id, name); + } + + /** + * Create a TypeCode for a string. + * + * @param bound the bound for the string. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_string_tc(int bound) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_string, bound); + } + + /** + * Create a TypeCode for a wide string. + * + * @param bound the bound for the string. + * @return the requested TypeCode. + */ + public synchronized TypeCode create_wstring_tc(int bound) { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_wstring, bound); + } + + public synchronized TypeCode create_sequence_tc(int bound, + TypeCode element_type) { + + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_sequence, bound, element_type); + } + + + @SuppressWarnings("deprecation") + public synchronized TypeCode create_recursive_sequence_tc(int bound, + int offset) { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_sequence, bound, offset); + } + + + public synchronized TypeCode create_array_tc(int length, + TypeCode element_type) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_array, length, element_type); + } + + + @Override + public synchronized org.omg.CORBA.TypeCode create_native_tc(String id, + String name) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_native, id, name); + } + + @Override + public synchronized org.omg.CORBA.TypeCode create_abstract_interface_tc( + String id, + String name) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_abstract_interface, id, name); + } + + @Override + public synchronized org.omg.CORBA.TypeCode create_fixed_tc(short digits, short scale) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_fixed, digits, scale); + } + + @Override + public synchronized org.omg.CORBA.TypeCode create_value_tc(String id, + String name, + short type_modifier, + TypeCode concrete_base, + ValueMember[] members) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_value, id, name, + type_modifier, concrete_base, members); + } + + @Override + public synchronized org.omg.CORBA.TypeCode create_recursive_tc(String id) { + checkShutdownState(); + return new TypeCodeImpl(this, id); + } + + @Override + public synchronized org.omg.CORBA.TypeCode create_value_box_tc(String id, + String name, + TypeCode boxed_type) + { + checkShutdownState(); + return new TypeCodeImpl(this, TCKind._tk_value_box, id, name, + boxed_type); + } + + public synchronized Any create_any() + { + checkShutdownState(); + return new AnyImpl(this); + } + + // TypeCodeFactory interface methods. + // Keeping track of type codes by repository id. + + // Keeping a cache of TypeCodes associated with the class + // they got created from in Util.writeAny(). + + public synchronized void setTypeCodeForClass(Class c, TypeCodeImpl tci) + { + if (typeCodeForClassMap == null) { + typeCodeForClassMap = new WeakHashMap, TypeCodeImpl>(64); + } + + // Store only one TypeCode per class. + if ( ! typeCodeForClassMap.containsKey(c)) { + typeCodeForClassMap.put(c, tci); + } + } + + public synchronized TypeCodeImpl getTypeCodeForClass(Class c) + { + if (typeCodeForClassMap == null) { + return null; + } + return typeCodeForClassMap.get(c); + } + +/**************************************************************************** + * The following methods deal with listing and resolving the initial + * (bootstrap) object references such as "NameService". + ****************************************************************************/ + + public String[] list_initial_services() { + Resolver res ; + + synchronized( this ) { + checkShutdownState(); + res = resolver ; + } + + synchronized (resolverLock) { + java.util.Set keys = res.list() ; + return keys.toArray( new String[keys.size()] ) ; + } + } + + public org.omg.CORBA.Object resolve_initial_references( + String identifier) throws InvalidName { + Resolver res ; + + synchronized( this ) { + checkShutdownState(); + res = resolver ; + } + + org.omg.CORBA.Object result = res.resolve( identifier ) ; + + if (result == null) { + throw new InvalidName(identifier + " not found"); + } else { + return result; + } + } + + @Override + public void register_initial_reference( + String id, org.omg.CORBA.Object obj ) throws InvalidName { + ServerRequestDispatcher insnd ; + + if ((id == null) || (id.length() == 0)) { + throw new InvalidName("Null or empty id string"); + } + + synchronized (this) { + checkShutdownState(); + } + + synchronized (resolverLock) { + insnd = insNamingDelegate ; + + java.lang.Object obj2 = localResolver.resolve( id ) ; + if (obj2 != null) { + throw new InvalidName(id + " already registered"); + } + + localResolver.register( id, + NullaryFunction.Factory.makeConstant( obj )) ; + } + + synchronized (this) { + if (StubAdapter.isStub(obj)) { + requestDispatcherRegistry.registerServerRequestDispatcher(insnd, id); + } + } + } + +/**************************************************************************** + * The following methods (introduced in POA / CORBA2.1) deal with + * shutdown / single threading. + ****************************************************************************/ + + @Override + public void run() + { + synchronized (this) { + checkShutdownState(); + } + + synchronized (runObj) { + try { + runObj.wait(); + } catch ( InterruptedException ex ) {} + } + } + + @Override + @OrbLifeCycle + public void shutdown(boolean wait_for_completion) { + boolean wait = false ; + + synchronized (this) { + checkShutdownState(); + + // This is to avoid deadlock: don't allow a thread that is + // processing a request to call shutdown( true ), because + // the shutdown would block waiting for the request to complete, + // while the request would block waiting for shutdown to complete. + if (wait_for_completion && + isProcessingInvocation.get() == Boolean.TRUE) { + throw omgWrapper.shutdownWaitForCompletionDeadlock() ; + } + + if (status == STATUS_SHUTTING_DOWN) { + if (wait_for_completion) { + wait = true ; + } else { + return ; + } + } + + status = STATUS_SHUTTING_DOWN ; + } + + // Avoid more than one thread performing shutdown at a time. + synchronized (shutdownObj) { + // At this point, the ORB status is certainly STATUS_SHUTTING_DOWN. + // If wait is true, another thread already called shutdown( true ), + // and so we wait for completion + if (wait) { + while (true) { + synchronized (this) { + if (status == STATUS_SHUTDOWN) { + break; + } + } + + try { + shutdownObj.wait() ; + } catch (InterruptedException exc) { + // NOP: just loop and wait until state is changed + } + } + } else { + startingShutdown( getORBData().getORBId() ) ; + + // perform the actual shutdown + shutdownServants(wait_for_completion); + + if (wait_for_completion) { + synchronized ( waitForCompletionObj ) { + while (numInvocations.get() > 0) { + try { + numWaiters.incrementAndGet() ; + waitForCompletionObj.wait(); + } catch (InterruptedException ex) { + // ignore + } finally { + numWaiters.decrementAndGet() ; + } + } + } + } + + synchronized ( runObj ) { + runObj.notifyAll(); + } + + status = STATUS_SHUTDOWN; + + shutdownObj.notifyAll() ; + } + } + } + + // Cause all ObjectAdapaterFactories to clean up all of their internal state, which + // may include activated objects that have associated state and callbacks that must + // complete in order to shutdown. This will cause new request to be rejected. + @OrbLifeCycle + protected void shutdownServants(boolean wait_for_completion) { + Set oaset ; + synchronized(this) { + oaset = new HashSet( + requestDispatcherRegistry.getObjectAdapterFactories() ) ; + } + + for (ObjectAdapterFactory oaf : oaset) { + oaf.shutdown(wait_for_completion); + } + } + + // Note that the caller must hold the ORBImpl lock. + private void checkShutdownState() + { + if (status == STATUS_DESTROYED) { + throw wrapper.orbDestroyed() ; + } + + if (status == STATUS_SHUTDOWN) { + throw omgWrapper.badOperationAfterShutdown() ; + } + } + + public boolean isDuringDispatch() { + return isProcessingInvocation.get() ; + } + + public void startingDispatch() { + isProcessingInvocation.set(true); + numInvocations.incrementAndGet() ; + } + + public void finishedDispatch() { + isProcessingInvocation.set(false); + int ni = numInvocations.decrementAndGet() ; + if (ni < 0) { + throw wrapper.numInvocationsAlreadyZero() ; + } + + if (numWaiters.get() > 0 && ni == 0) { + synchronized (waitForCompletionObj) { + waitForCompletionObj.notifyAll(); + } + } + } + + /** + * formal/99-10-07 p 159: "If destroy is called on an ORB that has + * not been shut down, it will start the shutdown process and block until + * the ORB has shut down before it destroys the ORB." + */ + @Override + @OrbLifeCycle + public void destroy() { + boolean shutdownFirst = false ; + synchronized (this) { + shutdownFirst = (status == STATUS_OPERATING) ; + } + + if (shutdownFirst) { + shutdown(true); + } + + synchronized (this) { + if (status < STATUS_DESTROYED) { + getCorbaTransportManager().close(); + getPIHandler().destroyInterceptors() ; + // timerManager.destroy() ; + // timerManager = null ; + status = STATUS_DESTROYED; + } else { + // Already destroyed: don't want to throw null pointer exceptions. + return ; + } + } + + startingDestruction( getORBData().getORBId() ) ; + + ThreadPoolManager tpToClose = null ; + synchronized (threadPoolManagerAccessLock) { + if (orbOwnsThreadPoolManager) { + tpToClose = threadpoolMgr ; + threadpoolMgr = null ; + } + } + + if (tpToClose != null) { + try { + tpToClose.close() ; + } catch (IOException exc) { + wrapper.ioExceptionOnClose( exc ) ; + } + } + + CachedCodeBase.cleanCache( this ) ; + try { + pihandler.close() ; + } catch (IOException exc) { + wrapper.ioExceptionOnClose( exc ) ; + } + + super.destroy() ; + + synchronized (this) { + corbaContactInfoListFactoryAccessLock = null ; + corbaContactInfoListFactoryReadLock = null ; + corbaContactInfoListFactoryWriteLock = null ; + + transportManager = null ; + legacyServerSocketManager = null ; + OAInvocationInfoStack = null ; + clientInvocationInfoStack = null ; + codeBase = null ; + codeBaseIOR = null ; + dynamicRequests.clear() ; + isProcessingInvocation = null ; + typeCodeForClassMap = null ; + valueFactoryCache = null ; + orbVersionThreadLocal = null ; + requestDispatcherRegistry = null ; + copierManager = null ; + serviceContextFactoryRegistry = null ; + serviceContextsCache= null ; + toaFactory = null ; + poaFactory = null ; + pihandler = null ; + configData = null ; + badServerIdHandler = null ; + clientDelegateFactory = null ; + corbaContactInfoListFactory = null ; + resolver = null ; + localResolver = null ; + insNamingDelegate = null ; + urlOperation = null ; + taggedComponentFactoryFinder = null ; + taggedProfileFactoryFinder = null ; + taggedProfileTemplateFactoryFinder = null ; + objectKeyFactory = null ; + invocationInterceptor = null ; + objectKeyCache.clear() ; + } + + try { + mom.close() ; + } catch (Exception exc) { + // ignore: stupid close exception + } + } + + /** + * Registers a value factory for a particular repository ID. + * + * @param repositoryID the repository ID. + * @param factory the factory. + * @return the previously registered factory for the given repository ID, + * or null if no such factory was previously registered. + * @exception org.omg.CORBA.BAD_PARAM if the registration fails. + **/ + @Override + public synchronized ValueFactory register_value_factory(String repositoryID, + ValueFactory factory) + { + checkShutdownState(); + + if ((repositoryID == null) || (factory == null)) { + throw omgWrapper.unableRegisterValueFactory(); + } + + return valueFactoryCache.put(repositoryID, factory); + } + + /** + * Unregisters a value factory for a particular repository ID. + * + * @param repositoryID the repository ID. + **/ + @Override + public synchronized void unregister_value_factory(String repositoryID) + { + checkShutdownState(); + + if (valueFactoryCache.remove(repositoryID) == null) { + throw wrapper.nullParam(); + } + } + + /** + * Finds and returns a value factory for the given repository ID. + * The value factory returned was previously registered by a call to + * {@link #register_value_factory} or is the default factory. + * + * @param repositoryID the repository ID. + * @return the value factory. + * @exception org.omg.CORBA.BAD_PARAM if unable to locate a factory. + **/ + @Override + public synchronized ValueFactory lookup_value_factory(String repositoryID) + { + checkShutdownState(); + + ValueFactory factory = valueFactoryCache.get(repositoryID); + + if (factory == null) { + try { + factory = Utility.getFactory(null, null, null, repositoryID); + } catch(org.omg.CORBA.MARSHAL ex) { + throw wrapper.unableFindValueFactory( ex ) ; + } + } + + return factory ; + } + + public OAInvocationInfo peekInvocationInfo() { + return OAInvocationInfoStack.get().peek() ; + } + + public void pushInvocationInfo( OAInvocationInfo info ) { + OAInvocationInfoStack.get().push( info ) ; + } + + public OAInvocationInfo popInvocationInfo() { + return OAInvocationInfoStack.get().pop() ; + } + + /** + * The bad server id handler is used by the Locator to + * send back the location of a persistant server to the client. + */ + + private final Object badServerIdHandlerAccessLock = new Object(); + + public void initBadServerIdHandler() + { + synchronized (badServerIdHandlerAccessLock) { + Class cls = configData.getBadServerIdHandler() ; + if (cls != null) { + try { + Class[] params = new Class[] { org.omg.CORBA.ORB.class }; + java.lang.Object[] args = new java.lang.Object[]{this}; + Constructor cons = cls.getConstructor(params); + badServerIdHandler = + (BadServerIdHandler) cons.newInstance(args); + } catch (Exception e) { + throw wrapper.errorInitBadserveridhandler( e ) ; + } + } + } + } + + public void setBadServerIdHandler( BadServerIdHandler handler ) + { + synchronized (badServerIdHandlerAccessLock) { + badServerIdHandler = handler; + } + } + + public void handleBadServerId( ObjectKey okey ) + { + synchronized (badServerIdHandlerAccessLock) { + if (badServerIdHandler == null) { + throw wrapper.badServerId(); + } else { + badServerIdHandler.handle(okey); + } + } + } + + @Override + public synchronized org.omg.CORBA.Policy create_policy( int type, + org.omg.CORBA.Any val ) throws org.omg.CORBA.PolicyError + { + checkShutdownState() ; + + return pihandler.create_policy( type, val ) ; + } + + @Override + public synchronized void connect(org.omg.CORBA.Object servant) + { + checkShutdownState(); + if (getTOAFactory() == null) { + throw wrapper.noToa(); + } + + try { + String codebase = Util.getInstance().getCodebase( servant.getClass() ) ; + getTOAFactory().getTOA( codebase ).connect( servant ) ; + } catch ( Exception ex ) { + throw wrapper.orbConnectError( ex ) ; + } + } + + @Override + public synchronized void disconnect(org.omg.CORBA.Object obj) + { + checkShutdownState(); + if (getTOAFactory() == null) { + throw wrapper.noToa(); + } + + try { + getTOAFactory().getTOA().disconnect( obj ) ; + } catch ( Exception ex ) { + throw wrapper.orbConnectError( ex ) ; + } + } + + public int getTransientServerId() + { + if( configData.getPersistentServerIdInitialized( ) ) { + // ORBServerId is specified then use that value + return configData.getPersistentServerId( ); + } + return transientServerId; + } + + public RequestDispatcherRegistry getRequestDispatcherRegistry() + { + return requestDispatcherRegistry; + } + + public ServiceContextFactoryRegistry getServiceContextFactoryRegistry() + { + return serviceContextFactoryRegistry ; + } + + public ServiceContextsCache getServiceContextsCache() + { + return serviceContextsCache; + } + + // XXX All of the isLocalYYY checking needs to be revisited. + // First of all, all three of these methods are called from + // only one place in impl.ior.IORImpl. Second, we have problems + // both with multi-homed hosts and with multi-profile IORs. + // A possible strategy: like the LocalClientRequestDispatcher, we need + // to determine this more abstractly at the ContactInfo level. + // This level should probably just get the CorbaContactInfoList from + // the IOR, then iterator over ContactInfo. If any ContactInfo is + // local, the IOR is local, and we can pick one to create the + // LocalClientRequestDispatcher as well. Bottom line: this code needs to move. + public boolean isLocalHost( String hostName ) + { + return hostName.equals( configData.getORBServerHost() ) || + hostName.equals( getLocalHostName() ) ; + } + + @Subcontract + public boolean isLocalServerId( int subcontractId, int serverId ) + { + if (subcontractDebugFlag) { + int psid = -1; + if (configData.getPersistentServerIdInitialized()) { + psid = configData.getPersistentServerId(); + } + + isLocalServerIdInfo( subcontractId, serverId, + getTransientServerId(), + ORBConstants.isTransient(subcontractId), + configData.getPersistentServerIdInitialized(), psid ) ; + } + + if ((subcontractId < ORBConstants.FIRST_POA_SCID) || + (subcontractId > ORBConstants.MAX_POA_SCID)) { + return serverId == getTransientServerId(); + } + + // XXX isTransient info should be stored in subcontract registry + if (ORBConstants.isTransient( subcontractId )) { + return serverId == getTransientServerId(); + } else if (configData.getPersistentServerIdInitialized()) { + return serverId == configData.getPersistentServerId(); + } else { + return false; + } + } + + /************************************************************************* + * The following public methods are for ORB shutdown. + *************************************************************************/ + + private String getHostName(String host) + throws java.net.UnknownHostException + { + return InetAddress.getByName( host ).getHostAddress(); + } + + /* keeping a copy of the getLocalHostName so that it can only be called + * internally and the unauthorized clients cannot have access to the + * localHost information, originally, the above code was calling + * getLocalHostName from Connection.java. If the hostname is cached in + * Connection.java, then + * it is a security hole, since any unauthorized client has access to + * the host information. With this change it is used internally so the + * security problem is resolved. Also in Connection.java, the + * getLocalHost() implementation has changed to always call the + * InetAddress.getLocalHost().getHostAddress() + * The above mentioned method has been removed from the connection class + */ + + private static String localHostString = null; + + private synchronized String getLocalHostName() + { + if (localHostString == null) { + try { + localHostString = InetAddress.getLocalHost().getHostAddress(); + } catch (Exception ex) { + throw wrapper.getLocalHostFailed( ex ) ; + } + } + return localHostString ; + } + + /****************************************************************************** + * The following public methods are for ORB shutdown. + * + ******************************************************************************/ + + /** This method always returns false because the ORB never needs the + * main thread to do work. + */ + @Override + public synchronized boolean work_pending() + { + checkShutdownState(); + throw wrapper.genericNoImpl() ; + } + + /** This method does nothing. It is not required by the spec to do anything! + */ + @Override + public synchronized void perform_work() + { + checkShutdownState(); + throw wrapper.genericNoImpl() ; + } + + @Override + public synchronized void set_delegate(java.lang.Object servant){ + checkShutdownState(); + + POAFactory pf = getPOAFactory() ; + if (pf != null) { + ((org.omg.PortableServer.Servant) servant)._set_delegate(pf.getDelegateImpl()); + } else { + throw wrapper.noPoa(); + } + } + + @InfoMethod + private void invocationInfoChange( String msg ) { } + + @Subcontract + public ClientInvocationInfo createOrIncrementInvocationInfo() { + ClientInvocationInfo clientInvocationInfo = null; + StackImpl invocationInfoStack = + clientInvocationInfoStack.get(); + if (!invocationInfoStack.empty()) { + clientInvocationInfo = invocationInfoStack.peek(); + } + if ((clientInvocationInfo == null) || + (!clientInvocationInfo.isRetryInvocation())) + { + // This is a new call - not a retry. + clientInvocationInfo = new InvocationInfo(); + invocationInfoStack.push(clientInvocationInfo); + invocationInfoChange( "new call" ) ; + } else { + invocationInfoChange( "retry" ) ; + } + // Reset retry so recursive calls will get a new info object. + clientInvocationInfo.setIsRetryInvocation(false); + clientInvocationInfo.incrementEntryCount(); + return clientInvocationInfo; + } + + @Subcontract + public void releaseOrDecrementInvocationInfo() { + int entryCount = -1; + ClientInvocationInfo clientInvocationInfo = null; + StackImpl invocationInfoStack = + clientInvocationInfoStack.get(); + if (!invocationInfoStack.empty()) { + clientInvocationInfo = invocationInfoStack.peek(); + } else { + throw wrapper.invocationInfoStackEmpty() ; + } + + clientInvocationInfo.decrementEntryCount(); + entryCount = clientInvocationInfo.getEntryCount(); + if (clientInvocationInfo.getEntryCount() == 0 + // 6763340: don't pop if this is a retry! + && !clientInvocationInfo.isRetryInvocation()) { + + invocationInfoStack.pop(); + invocationInfoChange( "pop" ) ; + } + } + + public ClientInvocationInfo getInvocationInfo() { + return clientInvocationInfoStack.get().peek() ; + } + + //////////////////////////////////////////////////// + // + // + // + + private final Object clientDelegateFactoryAccessorLock = new Object(); + + public void setClientDelegateFactory( ClientDelegateFactory factory ) + { + synchronized (clientDelegateFactoryAccessorLock) { + clientDelegateFactory = factory ; + } + } + + public ClientDelegateFactory getClientDelegateFactory() + { + synchronized (clientDelegateFactoryAccessorLock) { + return clientDelegateFactory ; + } + } + + private ReentrantReadWriteLock + corbaContactInfoListFactoryAccessLock = new ReentrantReadWriteLock(); + private Lock corbaContactInfoListFactoryReadLock = + corbaContactInfoListFactoryAccessLock.readLock(); + private Lock corbaContactInfoListFactoryWriteLock = + corbaContactInfoListFactoryAccessLock.writeLock(); + + public void setCorbaContactInfoListFactory( ContactInfoListFactory factory ) + { + corbaContactInfoListFactoryWriteLock.lock() ; + try { + corbaContactInfoListFactory = factory ; + } finally { + corbaContactInfoListFactoryWriteLock.unlock() ; + } + } + + public ContactInfoListFactory getCorbaContactInfoListFactory() + { + corbaContactInfoListFactoryReadLock.lock() ; + try { + return corbaContactInfoListFactory ; + } finally { + corbaContactInfoListFactoryReadLock.unlock() ; + } + } + + public void setResolver( Resolver resolver ) { + synchronized (resolverLock) { + this.resolver = resolver ; + } + } + + public Resolver getResolver() { + synchronized (resolverLock) { + return resolver ; + } + } + + public void setLocalResolver( LocalResolver resolver ) { + synchronized (resolverLock) { + this.localResolver = resolver ; + } + } + + public LocalResolver getLocalResolver() { + synchronized (resolverLock) { + return localResolver ; + } + } + + public void setURLOperation( Operation stringToObject ) { + synchronized (urlOperationLock) { + urlOperation = stringToObject ; + } + } + + public Operation getURLOperation() { + synchronized (urlOperationLock) { + return urlOperation ; + } + } + + public void setINSDelegate( ServerRequestDispatcher sdel ) { + synchronized (resolverLock) { + insNamingDelegate = sdel ; + } + } + + public TaggedComponentFactoryFinder getTaggedComponentFactoryFinder() { + return taggedComponentFactoryFinder ; + } + + public IdentifiableFactoryFinder + getTaggedProfileFactoryFinder() { + return taggedProfileFactoryFinder ; + } + + public IdentifiableFactoryFinder + getTaggedProfileTemplateFactoryFinder() { + return taggedProfileTemplateFactoryFinder ; + } + + private final Object objectKeyFactoryAccessLock = new Object(); + + public ObjectKeyFactory getObjectKeyFactory() + { + synchronized (objectKeyFactoryAccessLock) { + return objectKeyFactory ; + } + } + + public void setObjectKeyFactory( ObjectKeyFactory factory ) + { + synchronized (objectKeyFactoryAccessLock) { + objectKeyFactory = factory ; + } + } + + public TransportManager getTransportManager() + { + return transportManager; + } + + public TransportManager getCorbaTransportManager() + { + return getTransportManager(); + } + + private final Object legacyServerSocketManagerAccessLock = new Object(); + + public LegacyServerSocketManager getLegacyServerSocketManager() + { + synchronized (legacyServerSocketManagerAccessLock) { + if (legacyServerSocketManager == null) { + legacyServerSocketManager = new LegacyServerSocketManagerImpl(this); + } + return legacyServerSocketManager; + } + } + + private final Object threadPoolManagerAccessLock = new Object(); + + public void setThreadPoolManager(ThreadPoolManager mgr) { + synchronized (threadPoolManagerAccessLock) { + threadpoolMgr = mgr; + } + } + + public ThreadPoolManager getThreadPoolManager() { + synchronized (threadPoolManagerAccessLock) { + if (threadpoolMgr == null) { + threadpoolMgr = new ThreadPoolManagerImpl(); + orbOwnsThreadPoolManager = true ; + } + return threadpoolMgr; + } + } + + public CopierManager getCopierManager() { + return copierManager ; + } + + @Override + public IOR getIOR( org.omg.CORBA.Object obj, boolean connectIfNecessary ) { + IOR result ; + + if (connectIfNecessary) { + try { + result = getIOR( obj ) ; + } catch (BAD_OPERATION bop) { + if (StubAdapter.isStub(obj)) { + try { + StubAdapter.connect( obj, this ) ; + } catch (java.rmi.RemoteException exc) { + throw wrapper.connectingServant( exc ) ; + } + } else { + connect( obj ) ; + } + + result = getIOR( obj ) ; + } + } else { + // Let any exceptions propagate out + result = getIOR( obj ) ; + } + + return result ; + } + + @Override + public ObjectKeyCacheEntry extractObjectKeyCacheEntry(byte[] objKey) { + if (objKey == null) { + throw wrapper.invalidObjectKey(); + } + + ByteArrayWrapper newObjKeyWrapper = new ByteArrayWrapper(objKey); + + return objectKeyCache.get( newObjKeyWrapper ) ; + } + + @Override + public synchronized boolean orbIsShutdown() { + return ((status == STATUS_DESTROYED) || + (status == STATUS_SHUTDOWN)) ; + } +} // Class ORBImpl + +//////////////////////////////////////////////////////////////////////// +/// Helper class for a Synchronization Variable +//////////////////////////////////////////////////////////////////////// + +class SynchVariable { + // Synchronization Variable + public boolean _flag; + + // Constructor + SynchVariable() { + _flag = false; + } + + // set Flag to true + public void set() { + _flag = true; + } + + // get value + public boolean value() { + return _flag; + } + + // reset Flag to true + public void reset() { + _flag = false; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBSingleton.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBSingleton.java new file mode 100644 index 000000000..3eaf79dad --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBSingleton.java @@ -0,0 +1,789 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb; + +import java.util.Properties; + +import java.applet.Applet; + +import java.net.URL; + + + +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.CORBA.NVList; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.Request; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.CORBA.StructMember; +import org.omg.CORBA.UnionMember; +import org.omg.CORBA.ValueMember; +import org.omg.CORBA.Policy; +import org.omg.CORBA.PolicyError; + +import org.omg.CORBA.portable.OutputStream; + +import com.sun.corba.ee.spi.protocol.ClientInvocationInfo ; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ConnectionCache; +import com.sun.corba.ee.spi.transport.Selector ; +import com.sun.corba.ee.spi.transport.TransportManager; + +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.orb.Operation; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.protocol.ClientDelegateFactory; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.protocol.PIHandler; +import com.sun.corba.ee.spi.resolver.Resolver; +import com.sun.corba.ee.spi.resolver.LocalResolver; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder; +import com.sun.corba.ee.spi.ior.TaggedComponentFactoryFinder; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.ObjectKeyFactory; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory ; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketManager; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.corba.ee.spi.copyobject.CopierManager; +import com.sun.corba.ee.spi.presentation.rmi.InvocationInterceptor; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry; +import com.sun.corba.ee.spi.servicecontext.ServiceContextsCache; + +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.impl.corba.NVListImpl; +import com.sun.corba.ee.impl.corba.NamedValueImpl; +import com.sun.corba.ee.impl.corba.ExceptionListImpl; +import com.sun.corba.ee.impl.corba.ContextListImpl; +import com.sun.corba.ee.impl.corba.EnvironmentImpl; +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.impl.encoding.BufferManagerFactory; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import org.glassfish.pfl.basic.func.NullaryFunction; + +/* + * The restricted singleton ORB implementation. + * + * For now, this class must implement just enough functionality to be + * used as a factory for immutable TypeCode instances. + * + * See ORBImpl.java for the real ORB implementation. + */ +public class ORBSingleton extends ORB +{ + // This is used to support read_Object. + private static ORB fullORB; + private static PresentationManager.StubFactoryFactory staticStubFactoryFactory = + PresentationDefaults.getStaticStubFactoryFactory() ; + // private TimerManager timerManager ; + + public ORBSingleton() { + // timerManager = makeTimerManager( null ) ; + initializePrimitiveTypeCodeConstants() ; + } + + public void setParameters( String params[], Properties props ) { + // this is never called by ORB.init() + } + + public void set_parameters( Properties props ) { + // this is never called by ORB.init() + } + + protected void set_parameters(Applet app, Properties props) { + // this is never called by ORB.init() + } + + protected void set_parameters (String params[], Properties props) { + // this is never called by ORB.init() + } + + public OutputStream create_output_stream() { + return OutputStreamFactory.newEncapsOutputStream(this); + } + + public TypeCode create_struct_tc(String id, + String name, + StructMember[] members) + { + return new TypeCodeImpl(this, TCKind._tk_struct, id, name, members); + } + + public TypeCode create_union_tc(String id, + String name, + TypeCode discriminator_type, + UnionMember[] members) + { + return new TypeCodeImpl(this, + TCKind._tk_union, + id, + name, + discriminator_type, + members); + } + + public TypeCode create_enum_tc(String id, + String name, + String[] members) + { + return new TypeCodeImpl(this, TCKind._tk_enum, id, name, members); + } + + public TypeCode create_alias_tc(String id, + String name, + TypeCode original_type) + { + return new TypeCodeImpl(this, TCKind._tk_alias, id, name, original_type); + } + + public TypeCode create_exception_tc(String id, + String name, + StructMember[] members) + { + return new TypeCodeImpl(this, TCKind._tk_except, id, name, members); + } + + public TypeCode create_interface_tc(String id, + String name) + { + return new TypeCodeImpl(this, TCKind._tk_objref, id, name); + } + + public TypeCode create_string_tc(int bound) { + return new TypeCodeImpl(this, TCKind._tk_string, bound); + } + + public TypeCode create_wstring_tc(int bound) { + return new TypeCodeImpl(this, TCKind._tk_wstring, bound); + } + + public TypeCode create_sequence_tc(int bound, + TypeCode element_type) + { + return new TypeCodeImpl(this, TCKind._tk_sequence, bound, element_type); + } + + public TypeCode create_recursive_sequence_tc(int bound, + int offset) + { + return new TypeCodeImpl(this, TCKind._tk_sequence, bound, offset); + } + + public TypeCode create_array_tc(int length, + TypeCode element_type) + { + return new TypeCodeImpl(this, TCKind._tk_array, length, element_type); + } + + public org.omg.CORBA.TypeCode create_native_tc(String id, + String name) + { + return new TypeCodeImpl(this, TCKind._tk_native, id, name); + } + + public org.omg.CORBA.TypeCode create_abstract_interface_tc( + String id, + String name) + { + return new TypeCodeImpl(this, TCKind._tk_abstract_interface, id, name); + } + + public org.omg.CORBA.TypeCode create_fixed_tc(short digits, short scale) + { + return new TypeCodeImpl(this, TCKind._tk_fixed, digits, scale); + } + + // orbos 98-01-18: Objects By Value -- begin + + public org.omg.CORBA.TypeCode create_value_tc(String id, + String name, + short type_modifier, + TypeCode concrete_base, + ValueMember[] members) + { + return new TypeCodeImpl(this, TCKind._tk_value, id, name, + type_modifier, concrete_base, members); + } + + public org.omg.CORBA.TypeCode create_recursive_tc(String id) { + return new TypeCodeImpl(this, id); + } + + public org.omg.CORBA.TypeCode create_value_box_tc(String id, + String name, + TypeCode boxed_type) + { + return new TypeCodeImpl(this, TCKind._tk_value_box, id, name, boxed_type); + } + + public TypeCode get_primitive_tc( TCKind tckind ) + { + return get_primitive_tc( tckind.value() ) ; + } + + public Any create_any() { + return new AnyImpl(this); + } + + // TypeCodeFactory interface methods. + // Keeping track of type codes by repository id. + /* + * Not strictly needed for TypeCode factory duty but these seem + * harmless enough. + */ + + public NVList create_list(int count) { + return new NVListImpl(this, count); + } + + public org.omg.CORBA.NVList + create_operation_list(org.omg.CORBA.Object oper) { + throw wrapper.genericNoImpl() ; + } + + public org.omg.CORBA.NamedValue + create_named_value(String s, Any any, int flags) { + return new NamedValueImpl(this, s, any, flags); + } + + public org.omg.CORBA.ExceptionList create_exception_list() { + return new ExceptionListImpl(); + } + + public org.omg.CORBA.ContextList create_context_list() { + return new ContextListImpl(this); + } + + public org.omg.CORBA.Context get_default_context() + { + throw wrapper.genericNoImpl() ; + } + + public org.omg.CORBA.Environment create_environment() + { + return new EnvironmentImpl(); + } + + public org.omg.CORBA.Current get_current() + { + throw wrapper.genericNoImpl() ; + } + + /* + * Things that aren't allowed. + */ + + public String[] list_initial_services () + { + throw wrapper.genericNoImpl() ; + } + + public org.omg.CORBA.Object resolve_initial_references(String identifier) + throws InvalidName + { + throw wrapper.genericNoImpl() ; + } + + public void register_initial_reference( + String id, org.omg.CORBA.Object obj ) throws InvalidName + { + throw wrapper.genericNoImpl() ; + } + + public void send_multiple_requests_oneway(Request[] req) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void send_multiple_requests_deferred(Request[] req) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public boolean poll_next_response() { + throw new SecurityException("ORBSingleton: access denied"); + } + + public org.omg.CORBA.Request get_next_response() { + throw new SecurityException("ORBSingleton: access denied"); + } + + public String object_to_string(org.omg.CORBA.Object obj) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public org.omg.CORBA.Object string_to_object(String s) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public java.rmi.Remote string_to_remote(String s) + throws java.rmi.RemoteException + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void connect(org.omg.CORBA.Object servant) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void disconnect(org.omg.CORBA.Object obj) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void run() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void shutdown(boolean wait_for_completion) + { + throw new SecurityException("ORBSingleton: access denied"); + } + + protected void shutdownServants(boolean wait_for_completion) { + throw new SecurityException("ORBSingleton: access denied"); + } + + protected void destroyConnections() { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void destroy() { + throw new SecurityException("ORBSingleton: access denied"); + } + + public boolean work_pending() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void perform_work() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public org.omg.CORBA.portable.ValueFactory register_value_factory(String repositoryID, + org.omg.CORBA.portable.ValueFactory factory) + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void unregister_value_factory(String repositoryID) + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public org.omg.CORBA.portable.ValueFactory lookup_value_factory(String repositoryID) + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public TransportManager getTransportManager() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public TransportManager getCorbaTransportManager() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public LegacyServerSocketManager getLegacyServerSocketManager() + { + throw new SecurityException("ORBSingleton: access denied"); + } + +/************************************************************************* + These are methods from com.sun.corba.ee.impl.se.core.ORB + ************************************************************************/ + + private synchronized ORB getFullORB() + { + if (fullORB == null) { + Properties props = new Properties() ; + // Do NOT allow this special ORB to be created with the + // empty name, which could conflict with app server + // requirement that first ORB created with the empty name has + // root monitoring agent name "orb" + props.setProperty( ORBConstants.ORB_ID_PROPERTY, + "_$$$_INTERNAL_FULL_ORB_ID_$$$_" ) ; + + // We do not want to initialize the activation code here, because it is + // not included in the GF ORB bundles. There is no need for + // activation code, because this internal "full" ORB is only used + // to create typecodes that require a full ORB. + props.setProperty( ORBConstants.DISABLE_ORBD_INIT_PROPERTY, + "true" ) ; + + fullORB = new ORBImpl() ; + fullORB.set_parameters( props ) ; + } + + return fullORB ; + } + + public InvocationInterceptor getInvocationInterceptor() { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void setInvocationInterceptor( + InvocationInterceptor interceptor ) { + throw new SecurityException("ORBSingleton: access denied"); + } + + public RequestDispatcherRegistry getRequestDispatcherRegistry() + { + // To enable read_Object. + + return getFullORB().getRequestDispatcherRegistry(); + } + + /** + * Return the service context registry + */ + public ServiceContextFactoryRegistry getServiceContextFactoryRegistry() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + /** + * Return the service context cache as null + */ + public ServiceContextsCache getServiceContextsCache() + { + return null; + } + + /** + * Get the transient server ID + */ + public int getTransientServerId() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + /** + * Return the bootstrap naming port specified in the ORBInitialPort param. + */ + public int getORBInitialPort() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + /** + * Return the bootstrap naming host specified in the ORBInitialHost param. + */ + public String getORBInitialHost() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public String getORBServerHost() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public int getORBServerPort() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public CodeSetComponentInfo getCodeSetComponentInfo() + { + return new CodeSetComponentInfo(); + } + + public boolean isLocalHost( String host ) + { + // To enable read_Object. + return false; + } + + public boolean isLocalServerId( int subcontractId, int serverId ) + { + // To enable read_Object. + return false; + } + + /* + * Things from corba.ORB. + */ + + public ORBVersion getORBVersion() + { + // Always use our latest ORB version (latest fixes, etc) + return ORBVersionFactory.getORBVersion(); + } + + public void setORBVersion(ORBVersion verObj) + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public String getAppletHost() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public URL getAppletCodeBase() + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public int getHighWaterMark(){ + throw new SecurityException("ORBSingleton: access denied"); + } + + public int getLowWaterMark(){ + throw new SecurityException("ORBSingleton: access denied"); + } + + public int getNumberToReclaim(){ + throw new SecurityException("ORBSingleton: access denied"); + } + + public int getGIOPFragmentSize() { + return ORBConstants.GIOP_DEFAULT_BUFFER_SIZE; + } + + public int getGIOPBuffMgrStrategy(GIOPVersion gv) { + return BufferManagerFactory.GROW; + } + + public IOR getFVDCodeBaseIOR(){ + throw new SecurityException("ORBSingleton: access denied"); + } + + public Policy create_policy( int type, Any val ) throws PolicyError + { + throw new NO_IMPLEMENT(); + } + + public LegacyServerSocketEndPointInfo getServerEndpoint() + { + return null ; + } + + public void setPersistentServerId( int id ) + { + } + + public TypeCodeImpl getTypeCodeForClass( Class c ) + { + return null ; + } + + public void setTypeCodeForClass( Class c, TypeCodeImpl tcimpl ) + { + } + + public boolean alwaysSendCodeSetServiceContext() + { + return true ; + } + + public boolean isDuringDispatch() + { + return false ; + } + + public void notifyORB() { } + + public PIHandler getPIHandler() + { + return null ; + } + + public void createPIHandler() + { + } + + public void checkShutdownState() + { + } + + public void startingDispatch() + { + } + + public void finishedDispatch() + { + } + + public void registerInitialReference( String id, + NullaryFunction closure ) + { + } + + public ORBData getORBData() + { + return getFullORB().getORBData() ; + } + + public void setClientDelegateFactory( ClientDelegateFactory factory ) + { + } + + public ClientDelegateFactory getClientDelegateFactory() + { + return getFullORB().getClientDelegateFactory() ; + } + + public void setCorbaContactInfoListFactory( ContactInfoListFactory factory ) + { + } + + public ContactInfoListFactory getCorbaContactInfoListFactory() + { + return getFullORB().getCorbaContactInfoListFactory() ; + } + + public Operation getURLOperation() + { + return null ; + } + + public void setINSDelegate( ServerRequestDispatcher sdel ) + { + } + + public TaggedComponentFactoryFinder getTaggedComponentFactoryFinder() + { + return getFullORB().getTaggedComponentFactoryFinder() ; + } + + public IdentifiableFactoryFinder getTaggedProfileFactoryFinder() + { + return getFullORB().getTaggedProfileFactoryFinder() ; + } + + public IdentifiableFactoryFinder getTaggedProfileTemplateFactoryFinder() + { + return getFullORB().getTaggedProfileTemplateFactoryFinder() ; + } + + public ObjectKeyFactory getObjectKeyFactory() + { + return getFullORB().getObjectKeyFactory() ; + } + + public void setObjectKeyFactory( ObjectKeyFactory factory ) + { + throw new SecurityException("ORBSingleton: access denied"); + } + + public void handleBadServerId( ObjectKey okey ) + { + } + + public OAInvocationInfo peekInvocationInfo() + { + return null ; + } + + public void pushInvocationInfo( OAInvocationInfo info ) + { + } + + public OAInvocationInfo popInvocationInfo() + { + return null ; + } + + public ClientInvocationInfo createOrIncrementInvocationInfo() + { + return null ; + } + + public void releaseOrDecrementInvocationInfo() + { + } + + public ClientInvocationInfo getInvocationInfo() + { + return null ; + } + + public ConnectionCache getConnectionCache(ContactInfo contactInfo) + { + return null; + } + + public void setResolver( Resolver resolver ) + { + } + + public Resolver getResolver() + { + return null ; + } + + public void setLocalResolver( LocalResolver resolver ) + { + } + + public LocalResolver getLocalResolver() + { + return null ; + } + + public void setURLOperation( Operation stringToObject ) + { + } + + // NOTE: REMOVE THIS METHOD ONCE WE HAVE A ORT BASED ORBD + public void setBadServerIdHandler( BadServerIdHandler handler ) + { + } + + // NOTE: REMOVE THIS METHOD ONCE WE HAVE A ORT BASED ORBD + public void initBadServerIdHandler() + { + } + + public Selector getSelector(int x) + { + return null; + } + + public void setThreadPoolManager(ThreadPoolManager mgr) { + } + + public ThreadPoolManager getThreadPoolManager() { + return null; + } + + public CopierManager getCopierManager() { + return null ; + } + + /* + public TimerManager getTimerManager() { + return timerManager ; + } + */ +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBVersionImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBVersionImpl.java new file mode 100644 index 000000000..d67657113 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ORBVersionImpl.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import org.omg.CORBA.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORBVersion ; + +public class ORBVersionImpl implements ORBVersion { + private byte orbType ; + + public ORBVersionImpl( byte orbType ) + { + this.orbType = orbType ; + } + + public static final ORBVersion FOREIGN = new ORBVersionImpl( + ORBVersion.FOREIGN ) ; + + public static final ORBVersion OLD = new ORBVersionImpl( + ORBVersion.OLD ) ; + + public static final ORBVersion NEW = new ORBVersionImpl( + ORBVersion.NEW ) ; + + public static final ORBVersion JDK1_3_1_01 = new ORBVersionImpl( + ORBVersion.JDK1_3_1_01 ) ; + + public static final ORBVersion NEWER = new ORBVersionImpl( + ORBVersion.NEWER ) ; + + public static final ORBVersion PEORB = new ORBVersionImpl( + ORBVersion.PEORB ) ; + + public byte getORBType() + { + return orbType ; + } + + public void write( OutputStream os ) + { + os.write_octet( (byte)orbType ) ; + } + + public String toString() + { + return "ORBVersionImpl[" + Byte.toString( orbType ) + "]" ; + } + + public boolean equals( Object obj ) + { + if (!(obj instanceof ORBVersion)) + return false ; + + ORBVersion version = (ORBVersion)obj ; + return version.getORBType() == orbType ; + } + + public int hashCode() + { + return orbType ; + } + + public boolean lessThan(ORBVersion version) { + return orbType < version.getORBType(); + } + + public int compareTo(ORBVersion obj) { + // The Comparable interface says that this + // method throws a ClassCastException if the + // given object's type prevents it from being + // compared. + return getORBType() - obj.getORBType(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryBase.java new file mode 100644 index 000000000..ef32d6e5c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryBase.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry ; + +import com.sun.corba.ee.spi.ior.ObjectKey ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +public abstract class ObjectKeyCacheEntryBase implements ObjectKeyCacheEntry { + private ObjectKey okey ; + + public ObjectKeyCacheEntryBase( ObjectKey okey ) { + this.okey = okey ; + } + + public ObjectKey getObjectKey() { + return okey ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryImpl.java new file mode 100644 index 000000000..129b1c1d8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryImpl.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry ; + +import com.sun.corba.ee.spi.ior.ObjectKey ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +public class ObjectKeyCacheEntryImpl extends ObjectKeyCacheEntryBase { + private volatile ObjectAdapter oa ; + + public ObjectKeyCacheEntryImpl( ObjectKey okey ) { + super( okey ) ; + oa = null ; + } + + public ObjectAdapter getObjectAdapter() { + return oa ; + } + + public void clearObjectAdapter() { + oa = null ; + } + + public void setObjectAdapter( ObjectAdapter oa ) { + this.oa = oa ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryNoObjectAdapterImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryNoObjectAdapterImpl.java new file mode 100644 index 000000000..9e88da0c7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ObjectKeyCacheEntryNoObjectAdapterImpl.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry ; + +import com.sun.corba.ee.spi.ior.ObjectKey ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +public class ObjectKeyCacheEntryNoObjectAdapterImpl extends ObjectKeyCacheEntryBase { + public ObjectKeyCacheEntryNoObjectAdapterImpl( ObjectKey okey ) { + super( okey ) ; + } + + public ObjectAdapter getObjectAdapter() { + return null ; + } + + public void clearObjectAdapter() { } + + public void setObjectAdapter( ObjectAdapter oa ) { } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserAction.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserAction.java new file mode 100644 index 000000000..ffafb82ec --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserAction.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.util.Properties ; + +public interface ParserAction { + /** Return the property name or prefix for which this action + * is applied. + */ + String getPropertyName() ; + + /** Return whether this action is for an exact match or a prefix + * match (true). + */ + boolean isPrefix() ; + + /** Return the field name in an object that is set with the result + */ + String getFieldName() ; + + /** Apply this action to props and return the result. + */ + Object apply( Properties props ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserActionBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserActionBase.java new file mode 100644 index 000000000..68a504130 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserActionBase.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.util.Properties ; + +import com.sun.corba.ee.spi.orb.Operation ; + +public abstract class ParserActionBase implements ParserAction { + private String propertyName ; + private boolean prefix ; + private Operation operation ; + private String fieldName ; + + public int hashCode() + { + return propertyName.hashCode() ^ operation.hashCode() ^ + fieldName.hashCode() ^ (prefix ? 0 : 1) ; + } + + public boolean equals( Object obj ) + { + if (obj == this) + return true ; + + if (!(obj instanceof ParserActionBase)) + return false ; + + ParserActionBase other = (ParserActionBase)obj ; + + return propertyName.equals( other.propertyName ) && + prefix == other.prefix && + operation.equals( other.operation ) && + fieldName.equals( other.fieldName ) ; + } + + public ParserActionBase( String propertyName, boolean prefix, + Operation operation, String fieldName ) + { + this.propertyName = propertyName ; + this.prefix = prefix ; + this.operation = operation ; + this.fieldName = fieldName ; + } + + public String getPropertyName() + { + return propertyName ; + } + + public boolean isPrefix() + { + return prefix ; + } + + public String getFieldName() + { + return fieldName ; + } + + public abstract Object apply( Properties props ) ; + + protected Operation getOperation() + { + return operation ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserActionFactory.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserActionFactory.java new file mode 100644 index 000000000..ec985eea1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserActionFactory.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import com.sun.corba.ee.spi.orb.Operation ; + +public class ParserActionFactory{ + private ParserActionFactory() {} + + public static ParserAction makeNormalAction( String propertyName, + Operation operation, String fieldName ) + { + return new NormalParserAction( propertyName, operation, fieldName ) ; + } + + public static ParserAction makePrefixAction( String propertyName, + Operation operation, String fieldName, Class componentType ) + { + return new PrefixParserAction( propertyName, operation, fieldName, componentType ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserDataBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserDataBase.java new file mode 100644 index 000000000..05761e192 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserDataBase.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import com.sun.corba.ee.spi.orb.ParserData ; +import com.sun.corba.ee.spi.orb.Operation ; + +public abstract class ParserDataBase implements ParserData { + private String propertyName ; + private Operation operation ; + private String fieldName ; + private Object defaultValue ; + private Object testValue ; + + protected ParserDataBase( String propertyName, + Operation operation, String fieldName, Object defaultValue, + Object testValue ) + { + this.propertyName = propertyName ; + this.operation = operation ; + this.fieldName = fieldName ; + this.defaultValue = defaultValue ; + this.testValue = testValue ; + } + + public String getPropertyName() { return propertyName ; } + public Operation getOperation() { return operation ; } + public String getFieldName() { return fieldName ; } + public Object getDefaultValue() { return defaultValue ; } + public Object getTestValue() { return testValue ; } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserTable.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserTable.java new file mode 100644 index 000000000..6d2444802 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/ParserTable.java @@ -0,0 +1,1172 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.net.SocketException; +import java.net.InetSocketAddress; +import java.net.Socket ; +import java.net.ServerSocket ; + +import java.util.HashMap ; +import java.util.List; +import java.util.Map ; + +import java.security.AccessController ; +import java.security.PrivilegedExceptionAction ; +import java.security.PrivilegedActionException ; + +import javax.management.ObjectName ; + +import org.omg.PortableInterceptor.ORBInitializer ; +import org.omg.PortableInterceptor.ORBInitInfo ; + +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.EventHandler; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.Operation ; +import com.sun.corba.ee.spi.orb.OperationFactory ; +import com.sun.corba.ee.spi.orb.OperationFactoryExt ; +import com.sun.corba.ee.spi.orb.ParserData ; +import com.sun.corba.ee.spi.orb.ParserDataFactory ; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; +import com.sun.corba.ee.spi.transport.TcpTimeouts; +import com.sun.corba.ee.impl.oa.poa.Policies; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; +import com.sun.corba.ee.impl.encoding.OSFCodeSetRegistry ; +import com.sun.corba.ee.impl.legacy.connection.USLPort ; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler ; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr ; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr ; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReferenceAddr ; +import com.sun.corba.ee.impl.transport.DefaultIORToSocketInfoImpl; +import com.sun.corba.ee.impl.transport.DefaultSocketFactoryImpl; +import com.sun.corba.ee.impl.transport.TcpTimeoutsImpl; +import com.sun.corba.ee.spi.transport.InboundConnectionCache; +import org.glassfish.pfl.basic.contain.Pair; +import org.glassfish.pfl.basic.func.UnaryFunction; + +/** Initialize the parser data for the standard ORB parser. This is used both + * to implement ORBDataParserImpl and to provide the basic testing framework + * for ORBDataParserImpl. + */ +public class ParserTable { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // There is a serious problem here with the DefaultSocketFactory. + // It is NOT immutable: in particular is has a setORB method, so instances + // of DefaultSocketFactoryImpl CANNOT be shared across ORBs. + // To clean this up, we'll simply create a new ParserTable for each call to + // get. + private static String MY_CLASS_NAME = ParserTable.class.getName() ; + + // private static final ParserTable myInstance = new ParserTable() ; + + private Operation classAction ; + + public static ParserTable get( UnaryFunction> cnr ) + { + // return myInstance ; + return new ParserTable( cnr ) ; + } + + private ParserData[] parserData ; + + public ParserData[] getParserData() + { + return parserData ; + } + + public static ObjectName testGmbalRootParentName ; + + public final static String TEST_GMBAL_ROOT_PARENT_NAME = + "test:pp=\"/\",type=\"Foo\",name=\"1\"" ; + + static { + try { + testGmbalRootParentName = new ObjectName( TEST_GMBAL_ROOT_PARENT_NAME ) ; + } catch (Exception exc) { + testGmbalRootParentName = null ; + } + } + + private ParserTable( UnaryFunction> cnr ) { + classAction = OperationFactory.classAction( cnr ) ; + + String codeSetTestString = + OSFCodeSetRegistry.ISO_8859_1_VALUE + "," + + OSFCodeSetRegistry.UTF_16_VALUE + "," + + OSFCodeSetRegistry.ISO_646_VALUE ; + + String[] debugTestData = { "subcontract", "poa", "transport" } ; + + USLPort[] USLPorts = { new USLPort( "FOO", 2701 ), new USLPort( "BAR", 3333 ) } ; + + TcpTimeouts testTcpTimeouts = TcpTimeouts.factory.create( + 2000, 6000, 20 ) ; + + TcpTimeouts defaultTcpTimeouts = TcpTimeouts.factory.create( + ORBConstants.TRANSPORT_TCP_INITIAL_TIME_TO_WAIT, + ORBConstants.TRANSPORT_TCP_MAX_TIME_TO_WAIT, + ORBConstants.TRANSPORT_TCP_BACKOFF_FACTOR); + + TcpTimeouts testTcpConnectTimeouts = TcpTimeouts.factory.create( + 20, 60000, 100, 5000 ) ; + + TcpTimeouts defaultTcpConnectTimeouts = TcpTimeouts.factory.create( + ORBConstants.TRANSPORT_TCP_CONNECT_INITIAL_TIME_TO_WAIT, + ORBConstants.TRANSPORT_TCP_CONNECT_MAX_TIME_TO_WAIT, + ORBConstants.TRANSPORT_TCP_CONNECT_BACKOFF_FACTOR, + ORBConstants.TRANSPORT_TCP_CONNECT_MAX_SINGLE_WAIT ); + + ORBInitializer[] TestORBInitializers = + { null, + new TestORBInitializer1(), + new TestORBInitializer2() } ; + Pair[] TestORBInitData = { + new Pair( "foo.bar.blech.NonExistent", "dummy" ), + new Pair( MY_CLASS_NAME + "$TestORBInitializer1", "dummy" ), + new Pair( MY_CLASS_NAME + "$TestORBInitializer2", "dummy" ) } ; + + Acceptor[] TestAcceptors = + { null, + new TestAcceptor2(), + new TestAcceptor1() + } ; + // REVISIT: The test data gets put into a Properties object where + // order is not guaranteed. Thus the above array is in reverse. + Pair[] TestAcceptorData = { + new Pair( "foo.bar.blech.NonExistent", "dummy" ), + new Pair( MY_CLASS_NAME + "$TestAcceptor1", "dummy" ), + new Pair( MY_CLASS_NAME + "$TestAcceptor2", "dummy" ) } ; + + Pair[] TestORBInitRefData = + { new Pair( "Foo", "ior:930492049394" ), + new Pair( "Bar", "ior:3453465785633576" ) } ; + + // Why are we not handling INITIAL_SERVICES? + // URL testServicesURL = null ; + // String testServicesString = "corbaloc::camelot/NameService" ; + // try { + // testServicesURL = new URL( testServicesString ) ; + // } catch (Exception exc) { + // } + + // propertyName, + // operation, + // fieldName, defaultValue, + // testValue, testData (string or Pair[]) + ParserData[] pd = { + ParserDataFactory.make( ORBConstants.DEBUG_PROPERTY, + OperationFactory.listAction( ",", OperationFactory.stringAction()), + "debugFlags", new String[0], + debugTestData, "subcontract,poa,transport" ), + ParserDataFactory.make( ORBConstants.INITIAL_HOST_PROPERTY, + OperationFactory.stringAction(), + "ORBInitialHost", "", + "Foo", "Foo" ), + ParserDataFactory.make( ORBConstants.INITIAL_PORT_PROPERTY, + OperationFactory.integerAction(), + "ORBInitialPort", Integer.valueOf( ORBConstants.DEFAULT_INITIAL_PORT ), + Integer.valueOf( 27314 ), "27314" ), + // Where did this come from? + //ParserDataFactory.make( ORBConstants.INITIAL_PORT_PROPERTY, + //OperationFactory.booleanAction(), + //"ORBInitialPortInitialized", Boolean.FALSE, + //Boolean.TRUE, "27314" ), + ParserDataFactory.make( ORBConstants.SERVER_HOST_PROPERTY, + OperationFactory.stringAction(), + "ORBServerHost", "", + "camelot", "camelot" ), + ParserDataFactory.make( ORBConstants.SERVER_PORT_PROPERTY, + OperationFactory.integerAction(), + "ORBServerPort", Integer.valueOf( 0 ), + Integer.valueOf( 38143 ), "38143" ), + ParserDataFactory.make( ORBConstants.ORB_ID_PROPERTY, + OperationFactory.stringAction(), + "orbId", "", + "foo", "foo" ), + ParserDataFactory.make( ORBConstants.OLD_ORB_ID_PROPERTY, + OperationFactory.stringAction(), + "orbId", "", + "foo", "foo" ), + ParserDataFactory.make( ORBConstants.ORB_SERVER_ID_PROPERTY, + OperationFactory.integerAction(), + "persistentServerId", Integer.valueOf(-1), + Integer.valueOf( 1234), "1234" ), + ParserDataFactory.make( + ORBConstants.ORB_SERVER_ID_PROPERTY, + OperationFactory.setFlagAction(), + "persistentServerIdInitialized", Boolean.FALSE, + Boolean.TRUE, "1234" ), + // REVISIT after switch + // ParserDataFactory.make( ORBConstants.INITIAL_SERVICES_PROPERTY, + // OperationFactory.URLAction(), + // "servicesUrl", null, + // testServicesURL, testServicesString ), + // ParserDataFactory.make( ORBConstants.DEFAULT_INIT_REF_PROPERTY, + // OperationFactory.stringAction(), + // "defaultInitRef", null, + // "Fooref", "Fooref" ), + ParserDataFactory.make( ORBConstants.HIGH_WATER_MARK_PROPERTY, + OperationFactory.integerAction(), + "highWaterMark", Integer.valueOf( 240 ), + Integer.valueOf( 3745 ), "3745" ), + ParserDataFactory.make( ORBConstants.LOW_WATER_MARK_PROPERTY, + OperationFactory.integerAction(), + "lowWaterMark", Integer.valueOf( 100 ), + Integer.valueOf( 12 ), "12" ), + ParserDataFactory.make( ORBConstants.NUMBER_TO_RECLAIM_PROPERTY, + OperationFactory.integerAction(), + "numberToReclaim", Integer.valueOf( 5 ), + Integer.valueOf( 231 ), "231" ), + ParserDataFactory.make( ORBConstants.GIOP_VERSION, + makeGVOperation(), + "giopVersion", GIOPVersion.DEFAULT_VERSION, + new GIOPVersion( 2, 3 ), "2.3" ), + ParserDataFactory.make( ORBConstants.GIOP_FRAGMENT_SIZE, + makeFSOperation(), "giopFragmentSize", + Integer.valueOf( ORBConstants.GIOP_DEFAULT_FRAGMENT_SIZE ), + Integer.valueOf( 65536 ), "65536" ), + ParserDataFactory.make( ORBConstants.GIOP_BUFFER_SIZE, + OperationFactory.integerAction(), + "giopBufferSize", Integer.valueOf( ORBConstants.GIOP_DEFAULT_BUFFER_SIZE ), + Integer.valueOf( 234000 ), "234000" ), + ParserDataFactory.make( ORBConstants.GIOP_11_BUFFMGR, + makeBMGROperation(), + "giop11BuffMgr", Integer.valueOf( ORBConstants.DEFAULT_GIOP_11_BUFFMGR ), + Integer.valueOf( 1 ), "CLCT" ), + ParserDataFactory.make( ORBConstants.GIOP_12_BUFFMGR, + makeBMGROperation(), + "giop12BuffMgr", Integer.valueOf( ORBConstants.DEFAULT_GIOP_12_BUFFMGR ), + Integer.valueOf( 0 ), "GROW" ), + + // Note that the same property is used to set two different + // fields here. This requires that both entries use the same test + // data, or the test will fail. + ParserDataFactory.make( ORBConstants.GIOP_TARGET_ADDRESSING, + OperationFactory.compose( OperationFactory.integerRangeAction( 0, 3 ), + OperationFactory.convertIntegerToShort() ), + "giopTargetAddressPreference", + Short.valueOf( ORBConstants.ADDR_DISP_HANDLE_ALL ), + Short.valueOf( (short)2 ), "2" ), + ParserDataFactory.make( ORBConstants.GIOP_TARGET_ADDRESSING, + makeADOperation(), + "giopAddressDisposition", Short.valueOf( KeyAddr.value ), + Short.valueOf( (short)2 ), "2" ), + ParserDataFactory.make( ORBConstants.ALWAYS_SEND_CODESET_CTX_PROPERTY, + OperationFactory.booleanAction(), + "alwaysSendCodeSetCtx", Boolean.TRUE, + Boolean.FALSE, "false"), + ParserDataFactory.make( ORBConstants.USE_BOMS, + OperationFactory.booleanAction(), + "useByteOrderMarkers", + Boolean.valueOf( ORBConstants.DEFAULT_USE_BYTE_ORDER_MARKERS ), + Boolean.FALSE, "false" ), + ParserDataFactory.make( ORBConstants.USE_BOMS_IN_ENCAPS, + OperationFactory.booleanAction(), + "useByteOrderMarkersInEncaps", + Boolean.valueOf( ORBConstants.DEFAULT_USE_BYTE_ORDER_MARKERS_IN_ENCAPS ), + Boolean.FALSE, "false" ), + ParserDataFactory.make( ORBConstants.CHAR_CODESETS, + makeCSOperation(), + "charData", CodeSetComponentInfo.JAVASOFT_DEFAULT_CODESETS.getCharComponent(), + CodeSetComponentInfo.createFromString( codeSetTestString ), codeSetTestString ), + ParserDataFactory.make( ORBConstants.WCHAR_CODESETS, + makeCSOperation(), + "wcharData", CodeSetComponentInfo.JAVASOFT_DEFAULT_CODESETS.getWCharComponent(), + CodeSetComponentInfo.createFromString( codeSetTestString ), codeSetTestString ), + ParserDataFactory.make( ORBConstants.ALLOW_LOCAL_OPTIMIZATION, + OperationFactory.booleanAction(), + "allowLocalOptimization", Boolean.FALSE, + Boolean.TRUE, "true" ), + ParserDataFactory.make( ORBConstants.LEGACY_SOCKET_FACTORY_CLASS_PROPERTY, + makeLegacySocketFactoryOperation(), + // No default - must be set by user if they are using + // legacy socket factory. + "legacySocketFactory", null, + new TestLegacyORBSocketFactory(), + MY_CLASS_NAME + "$TestLegacyORBSocketFactory" ), + ParserDataFactory.make( ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + makeSocketFactoryOperation(), + "socketFactory", new DefaultSocketFactoryImpl(), + new TestORBSocketFactory(), + MY_CLASS_NAME + "$TestORBSocketFactory" ), + ParserDataFactory.make( ORBConstants.LISTEN_SOCKET_PROPERTY, + makeUSLOperation() , + "userSpecifiedListenPorts", new USLPort[0], + USLPorts, "FOO:2701,BAR:3333" ), + ParserDataFactory.make( ORBConstants.IOR_TO_SOCKET_INFO_CLASS_PROPERTY, + makeIORToSocketInfoOperation(), + "iorToSocketInfo", new DefaultIORToSocketInfoImpl(), + new TestIORToSocketInfo(), + MY_CLASS_NAME + "$TestIORToSocketInfo" ), + ParserDataFactory.make( ORBConstants.IIOP_PRIMARY_TO_CONTACT_INFO_CLASS_PROPERTY, + makeIIOPPrimaryToContactInfoOperation(), + "iiopPrimaryToContactInfo", null, + new TestIIOPPrimaryToContactInfo(), + MY_CLASS_NAME + "$TestIIOPPrimaryToContactInfo" ), + ParserDataFactory.make( ORBConstants.CONTACT_INFO_LIST_FACTORY_CLASS_PROPERTY, + makeContactInfoListFactoryOperation(), + "corbaContactInfoListFactory", null, + new TestContactInfoListFactory(), + MY_CLASS_NAME + "$TestContactInfoListFactory" ), + ParserDataFactory.make( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + OperationFactory.integerAction(), + "persistentServerPort", Integer.valueOf( 0 ), + Integer.valueOf( 2743 ), "2743" ), + ParserDataFactory.make( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + OperationFactory.setFlagAction(), + "persistentPortInitialized", Boolean.FALSE, + Boolean.TRUE, "2743" ), + ParserDataFactory.make( ORBConstants.ACTIVATED_PROPERTY, + OperationFactory.booleanAction(), + "serverIsORBActivated", Boolean.FALSE, + Boolean.TRUE, "true" ), + ParserDataFactory.make( ORBConstants.BAD_SERVER_ID_HANDLER_CLASS_PROPERTY, + classAction, + "badServerIdHandlerClass", null, + TestBadServerIdHandler.class, MY_CLASS_NAME + "$TestBadServerIdHandler" ), + ParserDataFactory.make( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX, + makeROIOperation(), + "orbInitializers", new ORBInitializer[0], + TestORBInitializers, TestORBInitData, ORBInitializer.class ), + ParserDataFactory.make( ORBConstants.ACCEPTOR_CLASS_PREFIX_PROPERTY, + makeAcceptorInstantiationOperation(), + "acceptors", new Acceptor[0], + TestAcceptors, TestAcceptorData, Acceptor.class ), + + // + // Socket/Channel control + // + + // Acceptor: + // useNIOSelector == true + // useSelectThreadToWait = true + // useWorkerThreadForEvent = false + // else + // useSelectThreadToWait = false + // useWorkerThreadForEvent = true + + // Connection: + // useNIOSelector == true + // useSelectThreadToWait = true + // useWorkerThreadForEvent = true + // else + // useSelectThreadToWait = false + // useWorkerThreadForEvent = true + + ParserDataFactory.make( ORBConstants.ACCEPTOR_SOCKET_TYPE_PROPERTY, + OperationFactory.stringAction(), + "acceptorSocketType", ORBConstants.SOCKETCHANNEL, + "foo", "foo" ), + + ParserDataFactory.make( ORBConstants.USE_NIO_SELECT_TO_WAIT_PROPERTY, + OperationFactory.booleanAction(), + "acceptorSocketUseSelectThreadToWait", Boolean.TRUE, + Boolean.TRUE, "true" ), + ParserDataFactory.make( ORBConstants.ACCEPTOR_SOCKET_USE_WORKER_THREAD_FOR_EVENT_PROPERTY, + OperationFactory.booleanAction(), + "acceptorSocketUseWorkerThreadForEvent", Boolean.TRUE, + Boolean.TRUE, "true" ), + ParserDataFactory.make( ORBConstants.CONNECTION_SOCKET_TYPE_PROPERTY, + OperationFactory.stringAction(), + "connectionSocketType", ORBConstants.SOCKETCHANNEL, + "foo", "foo" ), + ParserDataFactory.make( ORBConstants.USE_NIO_SELECT_TO_WAIT_PROPERTY, + OperationFactory.booleanAction(), + "connectionSocketUseSelectThreadToWait", Boolean.TRUE, + Boolean.TRUE, "true" ), + ParserDataFactory.make( + ORBConstants.CONNECTION_SOCKET_USE_WORKER_THREAD_FOR_EVENT_PROPERTY, + OperationFactory.booleanAction(), + "connectionSocketUseWorkerThreadForEvent", Boolean.TRUE, + Boolean.TRUE, "true" ), + ParserDataFactory.make( ORBConstants.WAIT_FOR_RESPONSE_TIMEOUT, + OperationFactory.integerAction(), + "waitForResponseTimeout", 1000 * 60 * 30, + Integer.valueOf(1234), "1234"), + ParserDataFactory.make( ORBConstants.DISABLE_DIRECT_BYTE_BUFFER_USE_PROPERTY, + OperationFactory.booleanAction(), + "disableDirectByteBufferUse", Boolean.TRUE, // was Boolean.FALSE, + Boolean.TRUE, "true" ), + ParserDataFactory.make(ORBConstants.TRANSPORT_TCP_TIMEOUTS_PROPERTY, + OperationFactoryExt.convertAction( TcpTimeoutsImpl.class ), + "tcpTimeouts", defaultTcpTimeouts, + testTcpTimeouts, "2000:6000:20" ), + ParserDataFactory.make(ORBConstants.TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY, + OperationFactoryExt.convertAction( TcpTimeoutsImpl.class ), + "tcpConnectTimeouts", defaultTcpConnectTimeouts, + testTcpConnectTimeouts, "20:60000:100:5000" ), + ParserDataFactory.make( + ORBConstants.ENABLE_JAVA_SERIALIZATION_PROPERTY, + OperationFactory.booleanAction(), + "enableJavaSerialization", Boolean.FALSE, + Boolean.FALSE, "false"), + ParserDataFactory.make( + ORBConstants.USE_REP_ID, + OperationFactory.booleanAction(), + "useRepId", Boolean.TRUE, + Boolean.TRUE, "true"), + ParserDataFactory.make( ORBConstants.ORB_INIT_REF_PROPERTY, + OperationFactory.identityAction(), + "orbInitialReferences", new Pair[0], + TestORBInitRefData, TestORBInitRefData, Pair.class ), + ParserDataFactory.make( + ORBConstants.SHOW_INFO_MESSAGES, + OperationFactory.booleanAction(), + "showInfoMessages", Boolean.FALSE, + Boolean.FALSE, "false" ), + ParserDataFactory.make( + ORBConstants.GET_SERVICE_CONTEXT_RETURNS_NULL, + OperationFactory.booleanAction(), + "getServiceContextReturnsNull", Boolean.FALSE, + Boolean.FALSE, "false" ), + ParserDataFactory.make( ORBConstants.APPSERVER_MODE, + OperationFactory.booleanAction(), + "isAppServerMode", Boolean.FALSE, + Boolean.FALSE, "FALSE"), + ParserDataFactory.make(ORBConstants.READ_BYTE_BUFFER_SIZE_PROPERTY, + OperationFactory.integerAction(), + "readByteBufferSize", + Integer.valueOf(ORBConstants.DEFAULT_READ_BYTE_BUFFER_SIZE), + Integer.valueOf(8192), "8192"), + ParserDataFactory.make(ORBConstants.MAX_READ_BYTE_BUFFER_SIZE_THRESHOLD_PROPERTY, + OperationFactory.integerAction(), + "maxReadByteBufferSizeThreshold", + Integer.valueOf(ORBConstants.MAX_READ_BYTE_BUFFER_SIZE_THRESHOLD), + Integer.valueOf(4000000), "4000000"), + ParserDataFactory.make( + ORBConstants.POOLED_DIRECT_BYTE_BUFFER_SLAB_SIZE_PROPERTY, + OperationFactory.integerAction(), + "pooledDirectByteBufferSlabSize", + Integer.valueOf(ORBConstants.DEFAULT_POOLED_DIRECT_BYTE_BUFFER_SLAB_SIZE), + Integer.valueOf(1048576), "1048576"), + ParserDataFactory.make( + ORBConstants.ALWAYS_ENTER_BLOCKING_READ_PROPERTY, + OperationFactory.booleanAction(), + "alwaysEnterBlockingRead", Boolean.TRUE, + Boolean.TRUE, "TRUE"), + ParserDataFactory.make( + ORBConstants.NON_BLOCKING_READ_CHECK_MESSAGE_PARSER_PROPERTY, + OperationFactory.booleanAction(), + "nonBlockingReadCheckMessageParser", Boolean.TRUE, + Boolean.TRUE, "TRUE"), + ParserDataFactory.make( + ORBConstants.BLOCKING_READ_CHECK_MESSAGE_PARSER_PROPERTY, + OperationFactory.booleanAction(), + "blockingReadCheckMessageParser", Boolean.FALSE, + Boolean.FALSE, "FALSE"), + ParserDataFactory.make( ORBConstants.TIMING_POINTS_ENABLED, + OperationFactory.booleanAction(), + "timingPointsEnabled", Boolean.FALSE, + Boolean.TRUE, "TRUE"), + ParserDataFactory.make( ORBConstants.USE_ENUM_DESC, + OperationFactory.booleanAction(), + "useEnumDesc", Boolean.TRUE, + Boolean.TRUE, "TRUE"), + ParserDataFactory.make( ORBConstants.ENV_IS_SERVER_PROPERTY, + OperationFactory.booleanAction(), + "environmentIsGFServer", Boolean.FALSE, + Boolean.TRUE, "TRUE"), + ParserDataFactory.make( ORBConstants.NO_DEFAULT_ACCEPTORS, + OperationFactory.booleanAction(), + "noDefaultAcceptors", Boolean.FALSE, + Boolean.TRUE, "TRUE" ), + ParserDataFactory.make( ORBConstants.REGISTER_MBEANS, + OperationFactory.booleanAction(), + "registerMBeans", Boolean.TRUE, + Boolean.FALSE, "FALSE" ), + ParserDataFactory.make( + ORBConstants.FRAGMENT_READ_TIMEOUT, + OperationFactory.integerAction(), + "fragmentReadTimeout", + Integer.valueOf(ORBConstants.DEFAULT_FRAGMENT_READ_TIMEOUT ), + Integer.valueOf(23000), "23000"), + ParserDataFactory.make( ORBConstants.DISABLE_ORBD_INIT_PROPERTY, + OperationFactory.booleanAction(), + "disableORBD", Boolean.FALSE, + Boolean.TRUE, "TRUE" ) + } ; + + parserData = pd ; + } + + public static final class TestBadServerIdHandler implements BadServerIdHandler + { + @Override + public boolean equals( Object other ) + { + return other instanceof TestBadServerIdHandler ; + } + + public void handle( ObjectKey objectKey ) + { + } + + @Override + public int hashCode() { + int hash = 3; + return hash; + } + } + + private Operation makeUSLOperation() + { + Operation[] siop = { OperationFactory.stringAction(), + OperationFactory.integerAction() } ; + Operation op2 = OperationFactory.sequenceAction( ":", siop ) ; + + Operation uslop = new Operation() { + public Object operate( Object value ) + { + Object[] values = (Object[])value ; + String type = (String)(values[0]) ; + Integer port = (Integer)(values[1]) ; + return new USLPort( type, port.intValue() ) ; + } + } ; + + Operation op3 = OperationFactory.compose( op2, uslop ) ; + Operation listenop = OperationFactory.listAction( ",", op3 ) ; + return listenop ; + } + + public static final class TestLegacyORBSocketFactory + implements com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory + { + public boolean equals( Object other ) + { + return other instanceof TestLegacyORBSocketFactory ; + } + + public ServerSocket createServerSocket( String type, int port ) + { + return null ; + } + + public SocketInfo getEndPointInfo( org.omg.CORBA.ORB orb, + IOR ior, SocketInfo socketInfo ) + { + return null ; + } + + public Socket createSocket( SocketInfo socketInfo ) + { + return null ; + } + } + + public static final class TestORBSocketFactory + implements com.sun.corba.ee.spi.transport.ORBSocketFactory + { + public boolean equals( Object other ) + { + return other instanceof TestORBSocketFactory ; + } + + public void setORB(ORB orb) + { + } + + public ServerSocket createServerSocket( String type, InetSocketAddress a ) + { + return null ; + } + + public Socket createSocket( String type, InetSocketAddress a ) + { + return null ; + } + + public void setAcceptedSocketOptions(Acceptor acceptor, ServerSocket serverSocket, Socket socket) throws SocketException { + throw new UnsupportedOperationException("Not supported yet."); + } + } + + public static final class TestIORToSocketInfo + implements IORToSocketInfo + { + public boolean equals( Object other ) + { + return other instanceof TestIORToSocketInfo; + } + + public List getSocketInfo(IOR ior, List previous) + { + return null; + } + } + + public static final class TestIIOPPrimaryToContactInfo + implements IIOPPrimaryToContactInfo + { + public void reset(ContactInfo primary) + { + } + + public boolean hasNext(ContactInfo primary, + ContactInfo previous, + List contactInfos) + { + return true; + } + + public ContactInfo next(ContactInfo primary, + ContactInfo previous, + List contactInfos) + { + return null; + } + } + + public static final class TestContactInfoListFactory + implements ContactInfoListFactory + { + public boolean equals( Object other ) + { + return other instanceof TestContactInfoListFactory; + } + + public void setORB(ORB orb) { } + + public ContactInfoList create( IOR ior ) { return null; } + } + + private Operation makeMapOperation( final Map map ) + { + return new Operation() { + public Object operate( Object value ) + { + return map.get( value ) ; + } + } ; + } + + private Operation makeBMGROperation() + { + Map map = new HashMap() ; + map.put( "GROW", Integer.valueOf(0) ) ; + map.put( "CLCT", Integer.valueOf(1) ) ; + map.put( "STRM", Integer.valueOf(2) ) ; + return makeMapOperation( map ) ; + } + + private Operation makeLegacySocketFactoryOperation() + { + Operation sfop = new Operation() { + public Object operate( Object value ) + { + String param = (String)value ; + + try { + Class legacySocketFactoryClass = + (Class)classAction.operate(param) ; + // For security reasons avoid creating an instance if + // this socket factory class is not one that would fail + // the class cast anyway. + if (com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory.class + .isAssignableFrom(legacySocketFactoryClass)) { + return legacySocketFactoryClass.newInstance(); + } else { + throw wrapper.illegalSocketFactoryType( + legacySocketFactoryClass.toString() ) ; + } + } catch (Exception ex) { + // ClassNotFoundException, IllegalAccessException, + // InstantiationException, SecurityException or + // ClassCastException + throw wrapper.badCustomSocketFactory( ex, param ) ; + } + } + } ; + + return sfop ; + } + + private Operation makeSocketFactoryOperation() + { + Operation sfop = new Operation() { + public Object operate( Object value ) + { + String param = (String)value ; + + try { + Class socketFactoryClass = + (Class)classAction.operate(param ) ; + // For security reasons avoid creating an instance if + // this socket factory class is not one that would fail + // the class cast anyway. + if (com.sun.corba.ee.spi.transport.ORBSocketFactory.class + .isAssignableFrom(socketFactoryClass)) { + return socketFactoryClass.newInstance(); + } else { + throw wrapper.illegalSocketFactoryType( socketFactoryClass.toString() ) ; + } + } catch (Exception ex) { + // ClassNotFoundException, IllegalAccessException, + // InstantiationException, SecurityException or + // ClassCastException + throw wrapper.badCustomSocketFactory( ex, param ) ; + } + } + } ; + + return sfop ; + } + + private Operation makeIORToSocketInfoOperation() + { + Operation op = new Operation() { + public Object operate( Object value ) + { + String param = (String)value ; + + try { + Class iorToSocketInfoClass = + (Class)classAction.operate(param ) ; + // For security reasons avoid creating an instance if + // this socket factory class is not one that would fail + // the class cast anyway. + if (IORToSocketInfo.class.isAssignableFrom(iorToSocketInfoClass)) { + return iorToSocketInfoClass.newInstance(); + } else { + throw wrapper.illegalIorToSocketInfoType( iorToSocketInfoClass.toString() ) ; + } + } catch (Exception ex) { + // ClassNotFoundException, IllegalAccessException, + // InstantiationException, SecurityException or + // ClassCastException + throw wrapper.badCustomIorToSocketInfo( ex, param ) ; + } + } + } ; + + return op ; + } + + private Operation makeIIOPPrimaryToContactInfoOperation() + { + Operation op = new Operation() { + public Object operate( Object value ) + { + String param = (String)value ; + + try { + Class iiopPrimaryToContactInfoClass = + (Class)classAction.operate(param ) ; + // For security reasons avoid creating an instance if + // this socket factory class is not one that would fail + // the class cast anyway. + if (IIOPPrimaryToContactInfo.class + .isAssignableFrom(iiopPrimaryToContactInfoClass)) { + return iiopPrimaryToContactInfoClass.newInstance(); + } else { + throw wrapper.illegalIiopPrimaryToContactInfoType( + iiopPrimaryToContactInfoClass.toString() ) ; + } + } catch (Exception ex) { + // ClassNotFoundException, IllegalAccessException, + // InstantiationException, SecurityException or + // ClassCastException + throw wrapper.badCustomIiopPrimaryToContactInfo( ex, param ) ; + } + } + } ; + + return op ; + } + + private Operation makeContactInfoListFactoryOperation() + { + Operation op = new Operation() { + public Object operate( Object value ) + { + String param = (String)value ; + + try { + Class contactInfoListFactoryClass = + (Class)classAction.operate(param ) ; + // For security reasons avoid creating an instance if + // this socket factory class is not one that would fail + // the class cast anyway. + if (ContactInfoListFactory.class.isAssignableFrom( + contactInfoListFactoryClass)) { + return contactInfoListFactoryClass.newInstance(); + } else { + throw wrapper.illegalContactInfoListFactoryType( + contactInfoListFactoryClass.toString() ) ; + } + } catch (Exception ex) { + // ClassNotFoundException, IllegalAccessException, + // InstantiationException, SecurityException or + // ClassCastException + throw wrapper.badContactInfoListFactory( ex, param ) ; + } + } + } ; + + return op ; + } + + private Operation makeCSOperation() + { + Operation csop = new Operation() { + public Object operate( Object value ) + { + String val = (String)value ; + return CodeSetComponentInfo.createFromString( val ) ; + } + } ; + + return csop ; + } + + private Operation makeADOperation() + { + Operation admap = new Operation() { + private Integer[] map = { + Integer.valueOf( KeyAddr.value ), + Integer.valueOf( ProfileAddr.value ), + Integer.valueOf( ReferenceAddr.value ), + Integer.valueOf( KeyAddr.value ) } ; + + public Object operate( Object value ) + { + int val = ((Integer)value).intValue() ; + return map[val] ; + } + } ; + + Operation rangeop = OperationFactory.integerRangeAction( 0, 3 ) ; + Operation op1 = OperationFactory.compose( rangeop, admap ) ; + Operation result = OperationFactory.compose( op1, + OperationFactory.convertIntegerToShort() ) ; + return result ; + } + + private Operation makeFSOperation() { + Operation fschecker = new Operation() { + public Object operate( Object value ) + { + int giopFragmentSize = ((Integer)value).intValue() ; + if (giopFragmentSize < ORBConstants.GIOP_FRAGMENT_MINIMUM_SIZE){ + throw wrapper.fragmentSizeMinimum( giopFragmentSize, + ORBConstants.GIOP_FRAGMENT_MINIMUM_SIZE ) ; + } + + if (giopFragmentSize % ORBConstants.GIOP_FRAGMENT_DIVISOR != 0) + throw wrapper.fragmentSizeDiv( giopFragmentSize, + ORBConstants.GIOP_FRAGMENT_DIVISOR ) ; + + return value ; + } + } ; + + Operation result = OperationFactory.compose( OperationFactory.integerAction(), + fschecker ) ; + return result ; + } + + private Operation makeGVOperation() { + Operation gvHelper = OperationFactory.listAction( ".", + OperationFactory.integerAction() ) ; + Operation gvMain = new Operation() { + public Object operate( Object value ) + { + Object[] nums = (Object[])value ; + int major = ((Integer)(nums[0])).intValue() ; + int minor = ((Integer)(nums[1])).intValue() ; + + return new GIOPVersion( major, minor ) ; + } + } ; + + Operation result = OperationFactory.compose( gvHelper, gvMain ); + return result ; + } + + public static final class TestORBInitializer1 extends org.omg.CORBA.LocalObject + implements ORBInitializer + { + public boolean equals( Object other ) + { + return other instanceof TestORBInitializer1 ; + } + + public void pre_init( ORBInitInfo info ) + { + } + + public void post_init( ORBInitInfo info ) + { + } + } + + public static final class TestORBInitializer2 extends org.omg.CORBA.LocalObject + implements ORBInitializer + { + public boolean equals( Object other ) + { + return other instanceof TestORBInitializer2 ; + } + + public void pre_init( ORBInitInfo info ) + { + } + + public void post_init( ORBInitInfo info ) + { + } + } + + private Operation makeROIOperation() { + Operation indexOp = OperationFactory.suffixAction() ; + Operation op1 = OperationFactory.compose( indexOp, classAction ) ; + Operation mop = OperationFactory.maskErrorAction( op1 ) ; + + Operation mkinst = new Operation() { + public Object operate( Object value ) + { + final Class initClass = (Class)value ; + if (initClass == null) + return null ; + + // For security reasons avoid creating an instance + // if this class is one that would fail the class cast + // to ORBInitializer anyway. + if( org.omg.PortableInterceptor.ORBInitializer.class.isAssignableFrom( + initClass ) ) { + // Now that we have a class object, instantiate one and + // remember it: + ORBInitializer initializer = null ; + + try { + initializer = (ORBInitializer)AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Object run() + throws InstantiationException, IllegalAccessException + { + return initClass.newInstance() ; + } + } + ) ; + } catch (PrivilegedActionException exc) { + // Unwrap the exception, as we don't care exc here + throw wrapper.orbInitializerFailure( exc.getException(), + initClass.getName() ) ; + } catch (Exception exc) { + throw wrapper.orbInitializerFailure( exc, initClass.getName() ) ; + } + + return initializer ; + } else { + throw wrapper.orbInitializerType( initClass.getName() ) ; + } + } + } ; + + Operation result = OperationFactory.compose( mop, mkinst ) ; + + return result ; + } + + public static final class TestAcceptor1 + implements Acceptor + { + public boolean equals( Object other ) + { + return other instanceof TestAcceptor1 ; + } + public boolean initialize() { return true; } + public boolean initialized() { return true; } + public String getConnectionCacheType() { return "FOO"; } + public void setConnectionCache(InboundConnectionCache connectionCache){} + public InboundConnectionCache getConnectionCache() { return null; } + public boolean shouldRegisterAcceptEvent() { return true; } + public void setUseSelectThreadForConnections(boolean x) { } + public boolean shouldUseSelectThreadForConnections() { return true; } + public void setUseWorkerThreadForConnections(boolean x) { } + public boolean shouldUseWorkerThreadForConnections() { return true; } + public Socket getAcceptedSocket() { return null ; } + public void processSocket( Socket socket ) { } + public void close() { } + public EventHandler getEventHandler() { return null; } + + public CDROutputObject createOutputObject( + ORB broker, MessageMediator messageMediator) { return null; } + public String getObjectAdapterId() { return null ; } + public String getObjectAdapterManagerId() { return null ; } + public void addToIORTemplate(IORTemplate iorTemplate, Policies policies, + String codebase) { } + public String getMonitoringName() { return null ; } + + public ServerSocket getServerSocket() { + return null ; + } + + public int getPort() { + return 0 ; + } + + public String getName() { + return "" ; + } + + public String getInterfaceName() { + return "" ; + } + + public String getType() { + return "" ; + } + + public boolean isLazy() { + return false ; + } + } + + public static final class TestAcceptor2 + implements Acceptor + { + public boolean equals( Object other ) + { + return other instanceof TestAcceptor2 ; + } + public boolean initialize() { return true; } + public boolean initialized() { return true; } + public String getConnectionCacheType() { return "FOO"; } + public void setConnectionCache(InboundConnectionCache connectionCache){} + public InboundConnectionCache getConnectionCache() { return null; } + public boolean shouldRegisterAcceptEvent() { return true; } + public void setUseSelectThreadForConnections(boolean x) { } + public boolean shouldUseSelectThreadForConnections() { return true; } + public void setUseWorkerThreadForConnections(boolean x) { } + public boolean shouldUseWorkerThreadForConnections() { return true; } + public Socket getAcceptedSocket() { return null ; } + public void processSocket( Socket socket ) { } + public void close() { } + public EventHandler getEventHandler() { return null; } + + public CDROutputObject createOutputObject( + ORB broker, MessageMediator messageMediator) { return null; } + public String getObjectAdapterId() { return null ; } + public String getObjectAdapterManagerId() { return null ; } + public void addToIORTemplate(IORTemplate iorTemplate, Policies policies, + String codebase) { } + public String getMonitoringName() { return null ; } + public ServerSocket getServerSocket() { + return null ; + } + + public int getPort() { + return 0 ; + } + + public String getName() { + return "" ; + } + + public String getInterfaceName() { + return "" ; + } + + public String getType() { + return "" ; + } + + public boolean isLazy() { + return false ; + } + } + + // REVISIT - this is a cut and paste modification of makeROIOperation. + private Operation makeAcceptorInstantiationOperation() { + Operation indexOp = OperationFactory.suffixAction() ; + Operation op1 = OperationFactory.compose( indexOp, classAction ) ; + Operation mop = OperationFactory.maskErrorAction( op1 ) ; + + Operation mkinst = new Operation() { + public Object operate( Object value ) + { + final Class initClass = (Class)value ; + if (initClass == null) + return null ; + + // For security reasons avoid creating an instance + // if this class is one that would fail the class cast + // to ORBInitializer anyway. + if( Acceptor.class.isAssignableFrom( initClass ) ) { + // Now that we have a class object, instantiate one and + // remember it: + Acceptor acceptor = null ; + + try { + acceptor = (Acceptor)AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Object run() + throws InstantiationException, IllegalAccessException + { + return initClass.newInstance() ; + } + } + ) ; + } catch (PrivilegedActionException exc) { + // Unwrap the exception, as we don't care exc here + throw wrapper.acceptorInstantiationFailure( exc.getException(), + initClass.getName() ) ; + } catch (Exception exc) { + throw wrapper.acceptorInstantiationFailure( exc, initClass.getName() ) ; + } + + return acceptor ; + } else { + throw wrapper.acceptorInstantiationTypeFailure( initClass.getName() ) ; + } + } + } ; + + Operation result = OperationFactory.compose( mop, mkinst ) ; + + return result ; + } + + private Operation makeInitRefOperation() { + return new Operation() { + public Object operate( Object value ) + { + // Object is String[] of length 2. + String[] values = (String[])value ; + if (values.length != 2) + throw wrapper.orbInitialreferenceSyntax() ; + + return values[0] + "=" + values[1] ; + } + } ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PrefixParserAction.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PrefixParserAction.java new file mode 100644 index 000000000..53e3ec38d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PrefixParserAction.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.util.Properties ; +import java.util.List ; +import java.util.LinkedList ; +import java.util.Iterator ; + +import java.lang.reflect.Array ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.orb.Operation ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import org.glassfish.pfl.basic.contain.Pair; + +public class PrefixParserAction extends ParserActionBase { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private Class componentType ; + + public PrefixParserAction( String propertyName, + Operation operation, String fieldName, Class componentType ) + { + super( propertyName, true, operation, fieldName ) ; + this.componentType = componentType ; + } + + /** For each String s that matches the prefix given by getPropertyName(), + * apply getOperation() to { suffix( s ), value } + * and add the result to an Object[] + * which forms the result of apply. Returns null if there are no + * matches. + */ + public Object apply( Properties props ) + { + String prefix = getPropertyName() ; + int prefixLength = prefix.length() ; + if (prefix.charAt( prefixLength - 1 ) != '.') { + prefix += '.' ; + prefixLength++ ; + } + + List matches = new LinkedList() ; + + // Find all keys in props that start with propertyName + Iterator iter = props.keySet().iterator() ; + while (iter.hasNext()) { + String key = (String)(iter.next()) ; + if (key.startsWith( prefix )) { + String suffix = key.substring( prefixLength ) ; + String value = props.getProperty( key ) ; + Pair data = new Pair( suffix, value ) ; + Object result = getOperation().operate( data ) ; + matches.add( result ) ; + } + } + + int size = matches.size() ; + if (size > 0) { + // Convert the list into an array of the proper type. + // An Object[] as a result does NOT work. Also report + // any errors carefully, as errors here or in parsers that + // use this Operation often show up at ORB.init(). + Object result = null ; + try { + result = Array.newInstance( componentType, size ) ; + } catch (Throwable thr) { + throw wrapper.couldNotCreateArray( thr, + getPropertyName(), componentType, size ) ; + } + + Iterator iter2 = matches.iterator() ; + int ctr = 0 ; + while (iter2.hasNext()) { + Object obj = iter2.next() ; + + try { + Array.set( result, ctr, obj ) ; + } catch (Throwable thr) { + throw wrapper.couldNotSetArray( thr, + getPropertyName(), ctr, componentType, size, + obj ) ; + } + ctr++ ; + } + + return result ; + } else { + return null; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PrefixParserData.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PrefixParserData.java new file mode 100644 index 000000000..b7bf004f2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PrefixParserData.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.util.Properties ; + +import com.sun.corba.ee.spi.orb.Operation ; +import com.sun.corba.ee.spi.orb.PropertyParser ; +import org.glassfish.pfl.basic.contain.Pair; + +public class PrefixParserData extends ParserDataBase { + + private Pair[] testData ; + private Class componentType ; + + public PrefixParserData( String propertyName, + Operation operation, String fieldName, Object defaultValue, + Object testValue, Pair[] testData, Class componentType ) + { + super( propertyName, operation, fieldName, defaultValue, testValue ) ; + this.testData = testData ; + this.componentType = componentType ; + } + + public void addToParser( PropertyParser parser ) + { + parser.addPrefix( getPropertyName(), getOperation(), getFieldName(), + componentType ) ; + } + + public void addToProperties( Properties props ) + { + for (Pair sp : testData) { + String propName = getPropertyName() ; + if (propName.charAt( propName.length() - 1 ) != '.') + propName += "." ; + + props.setProperty( propName + sp.first(), sp.second() ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PropertyOnlyDataCollector.java b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PropertyOnlyDataCollector.java new file mode 100644 index 000000000..eb5c6a169 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/PropertyOnlyDataCollector.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.orb ; + +import java.net.InetAddress ; + +import java.util.Properties ; + +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.CompletionStatus ; + +public class PropertyOnlyDataCollector extends DataCollectorBase +{ + public PropertyOnlyDataCollector( Properties props, + String localHostName, String configurationHostName ) + { + super( props, localHostName, configurationHostName ) ; + } + + public boolean isApplet() + { + return false ; + } + + protected void collect() + { + checkPropertyDefaults() ; + + findPropertiesFromProperties() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/orb/parsing_combinators.txt b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/parsing_combinators.txt new file mode 100644 index 000000000..406fada7c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/orb/parsing_combinators.txt @@ -0,0 +1,204 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Parsing + +- primtive types +- lists of various sorts + + Basic models + + prefix A,BCDF scans left-to-right + suffix ABCD:F scans right-to-left + + Model 1: + data is sep,op,next,combine + + if (sep found in data) + split data into prefix, rest + return combine( op(prefix), next(rest) ) + else + return combine( default, next(data) ) + + pop = suffix1( ":", op3, op4, ++ ) + op = prefix1( ",", op2, pop, ++ ) + + op( A,BDF.FGH:Z ) = + + op2(A) ++ pop( BDF.FGH:Z ) = + op2(A) ++ op4( BDF.FGH ) ++ op3( Z ) + + Model 2: + data is sep,op,next,combine + + if (sep found in data) + split data into prefix, rest + return combine( op(prefix), next(rest) ) + else + return op(data) + + example + op = prefix2( ":", op2, null, ++ ) + op.setNext( op ) ; + + op( A:B:C:D ) = + + op2(A) ++ op2(B) ++ op2(C) ++ op2(D) + + + +reduce( sep, initial, op, combine ) + + operate( data ) + if (sep in data) + split data into prefix, rest + return combine( op(prefix), operate( rest )) + else + return combine( op(data), initial ) + +reduce( sep, op1, op2, initial, combine ) + + operate(data) + if (sep in data) // either first from left orfirst from right + split data into prefix, rest + return combine( op1( prefix ), op2( rest ) ) + else + return opx( data ) + +type + class combine + init : X + add( X, Y ) : X + op1( String ) : X + op2( String ) : Y + + reduce( sep, op1, op2, comb ) ( String ) : X + + operate(data) + if (sep in data) // either first from left orfirst from right + split data into prefix, rest + return comb.add( op2.operate( rest ), op1.operate( prefix ) ) + else + return comb.add( comb.init(), op1.operate( data ) ) + + example + + op = reduce( ":", op1, null, comb ) + op.setop2( op ) + + op.operate( "A:B:C" ) = + comb.add( op.operate( "B:C" ), op1.operate( "A" ) ) = + comb.add( comb.add( op.operate("C"), op1.operate("B") ), op1.operate( "A" ) = + comb.add( comb.add( comb.add( comb.init(), op1.operate("C") ), op1.operate("B") ), + op1.operate("A") ) + + +Splitter interface + +interface Splitter { + List split( String str ) +} + +variations: + - separated list SL + - first sep rest FSR + - fail if not present one arg + - default value two args + - rest sep last RSL + - fail if not present one arg + - default value two args + +Have we just pushed the real problem off a level? + +How do we combine: + op1 = FSR("@",v12) + op2 = LSR(":",9090) + + str = 1.2@myhost:2345 + + op1(str) = ( "1.2" "myhost:2345" ) + + define splice( int index, Operator op ) on a list of strings, with op( String ) : (String) + to replace the indexth element of a list of strings with the list returned + from op( element ). + + compose( op1, splice( 1, op2 )) is the correct parser. + + +A grammar for parsers? + +parser : simple_parser + | parser ":" simple_parser ; + +simple_parser : ident + | ident "(" param_list ")" ; + +param_list : param + | param_list "," param ; + +param : constant + | parser ; + +constant is a Java constant +ident x is interpreted as either a public static method on OperationFactory +named xAction which takes as arguments the types of the param list, or as +the fully qualified class name of a class that implements Operation and has +a constructor which takes as arguments the types of the param list. + +From parser table: + +debugFlags string +ORBInitialHost string +ORBInitialPort integer +ORBServerHost string +ORBServerPort integer +orbId string +highWaterMark integer +lowWaterMark integer +etc. + +giopVersion construct(GIOPVersion.class):map(integer):list('.') +giopFragmentSize mod(ORBConstants.GIOP_FRAGMENT_DIVISOR):min(ORBConstants.GIOP_FRAGMENT_SIZE):integer + +Lisp notation: + parse((mod ORBConstants.GIOP_FRAGMENT_DIVISOR) (min ...) (integer)) + +giop11BuffMgr makeMap(map) where map is constructed in java with + map.get("GROW") = Integer(0) + map.get("CLCT") = Integer(1) + map.get("STRM") = Integer(2) + +giopTargetAddressPreference intToShort:integerRange(0,3) +giopAddressDisposition another map variant + +charData construct(CodeSetComponentInfo.class):string + + +What about corbaloc:? + +v12 = GIOPVersion.v12 ; + +giopVersion = construct( GIOPVersion.class ):mapSequence( [integer,integer] ):FSR(".") + +iiopAddress = mapSequence( [giopVersion,identity,integer] ): + splice( 1, LSR( ":" 9090 )): + FSR( "@", v12 ) + +addressHandler = choice( + "iiop:", iiopAddress + ":", iiopAddress +) + +addressList = map(addressHandler):SL(",") + +choice( + "corbaloc:", mapSequence( [addressList,string] ):RSL("/", "NameService"), + "corbaname:", ... +) diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/osgi/loader/OSGIListener.java b/orbmain/src/main/java/com/sun/corba/ee/impl/osgi/loader/OSGIListener.java new file mode 100644 index 000000000..9dfa00d14 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/osgi/loader/OSGIListener.java @@ -0,0 +1,443 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.osgi.loader ; + +import java.util.Dictionary; +import java.util.Map; + +import org.osgi.framework.Bundle ; +import org.osgi.framework.BundleActivator ; +import org.osgi.framework.SynchronousBundleListener ; +import org.osgi.framework.BundleContext ; +import org.osgi.framework.BundleEvent ; +import org.osgi.framework.ServiceReference ; + +import org.osgi.service.packageadmin.PackageAdmin ; +import org.osgi.service.packageadmin.ExportedPackage ; + +import com.sun.corba.ee.spi.orb.ClassCodeBaseHandler ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.trace.Osgi; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import java.security.PrivilegedAction ; +import java.security.PrivilegedExceptionAction ; +import java.security.PrivilegedActionException ; +import java.security.AccessController ; +import org.glassfish.pfl.basic.func.UnaryFunction; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** OSGi class that monitors which bundles provide classes that the ORB + * needs to instantiate for initialization. + *

    + * Note that OSGIListener must be a Bundle-Activator in the glassfish-corba-orb + * bundle. + *

    + * Any bundle that provides ORB classes to the ORB initialization code must + * declare all such classes in a comma-separated list in the bundle manifest + * with the keywork ORB-Class-Provider. + * + * @author ken + */ +@Osgi +public class OSGIListener implements BundleActivator, SynchronousBundleListener { + private static final ReadWriteLock lock = new ReentrantReadWriteLock() ; + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static final String ORB_PROVIDER_KEY = "ORB-Class-Provider" ; + + private static PackageAdmin pkgAdmin ; + + private static void setPackageAdmin( PackageAdmin pa ) { + pkgAdmin = pa ; + } + + private static Dictionary secureGetHeaders( final Bundle bundle ) { + if (System.getSecurityManager() == null) { + return bundle.getHeaders() ; + } else { + return AccessController.doPrivileged( + new PrivilegedAction() { + public Dictionary run() { + return bundle.getHeaders() ; + } + } + ) ; + } + } + + private static Class secureLoadClass( final Bundle bundle, + final String className ) throws ClassNotFoundException { + + if (System.getSecurityManager() == null) { + return bundle.loadClass( className ) ; + } else { + try { + return AccessController.doPrivileged( + new PrivilegedExceptionAction>() { + public Class run() throws ClassNotFoundException { + return bundle.loadClass( className ) ; + } + } + ) ; + } catch (PrivilegedActionException exc) { + throw (ClassNotFoundException)exc.getException() ; + } + } + } + + // Map from class name to Bundle, which identifies all known + // ORB-Class-Providers. + private static Map classNameMap = + new ConcurrentHashMap() ; + + // Map from package name to Bundle, which identifies all known + // exported packages. + private static Map packageNameMap = + new ConcurrentHashMap() ; + + private static String getBundleEventType( int type ) { + if (type == BundleEvent.INSTALLED) { + return "INSTALLED"; + } else if (type == BundleEvent.LAZY_ACTIVATION) { + return "LAZY_ACTIVATION"; + } else if (type == BundleEvent.RESOLVED) { + return "RESOLVED" ; + } else if (type == BundleEvent.STARTED) { + return "STARTED" ; + } else if (type == BundleEvent.STARTING) { + return "STARTING" ; + } else if (type == BundleEvent.STOPPED) { + return "STOPPED" ; + } else if (type == BundleEvent.STOPPING) { + return "STOPPING" ; + } else if (type == BundleEvent.UNINSTALLED) { + return "UNINSTALLED" ; + } else if (type == BundleEvent.UNRESOLVED) { + return "UNRESOLVED" ; + } else if (type == BundleEvent.UPDATED) { + return "UPDATED" ; + } else { + return "ILLEGAL-EVENT-TYPE" ; + } + } + + @InfoMethod + private void classNotFoundInBundle( String arg ) {} + + @InfoMethod + private void foundClassInBundle( String arg, String name ) {} + + @Osgi + private static class ClassNameResolverImpl implements + UnaryFunction> { + + @InfoMethod + private void classNotFoundInBundle( String arg ) {} + + @InfoMethod + private void foundClassInBundle( String arg, String name ) {} + + @Osgi + public Class evaluate(String arg) { + Bundle bundle = getBundleForClass( arg ) ; + if (bundle == null) { + classNotFoundInBundle( arg ) ; + return null ; + } else { + foundClassInBundle( arg, bundle.getSymbolicName() ) ; + } + + try { + return secureLoadClass( bundle, arg ); + } catch (ClassNotFoundException ex) { + throw wrapper.bundleCouldNotLoadClass( ex, arg, + bundle.getSymbolicName() ) ; + } + } + + @Override + public String toString() { + return "OSGiClassNameResolver" ; + } + } + + private static UnaryFunction> classNameResolver = + new ClassNameResolverImpl() ; + + @Osgi + public static UnaryFunction> classNameResolver() { + return classNameResolver ; + } + + @Osgi + private static class ClassCodeBaseHandlerImpl implements ClassCodeBaseHandler { + private static final String PREFIX = "osgi://" ; + + @InfoMethod + private void classNotFoundInBundle( String name ) {} + + @InfoMethod + private void foundClassInBundleVersion( Class cls, String name, + String version ) {} + + @Osgi + public String getCodeBase( Class cls ) { + if (cls == null) { + return null ; + } + + if (pkgAdmin == null) { + return null ; + } + + Bundle bundle = pkgAdmin.getBundle( cls ) ; + if (bundle == null) { + classNotFoundInBundle( cls.getName() ) ; + return null ; + } + + String name = bundle.getSymbolicName() ; + + Dictionary headers = secureGetHeaders( bundle ) ; + String version = "0.0.0" ; + if (headers != null) { + String hver = (String)headers.get( "Bundle-Version" ) ; + if (hver != null) { + version = hver; + } + } + + foundClassInBundleVersion( cls, name, version ) ; + + return PREFIX + name + "/" + version ; + } + + @InfoMethod + private void couldNotLoadClassInBundle( ClassNotFoundException exc, + String className, String bname ) {} + + @InfoMethod + private void foundClassInBundleVersion( String cname, + String bname, String version ) {} + + @InfoMethod + private void classNotFoundInBundleVersion( String cname, + String bname, String version ) {} + + @Osgi + public Class loadClass( String codebase, String className ) { + if (codebase == null) { + Bundle bundle = getBundleForClass( className ) ; + if (bundle != null) { + try { + return secureLoadClass( bundle, className ) ; + } catch (ClassNotFoundException exc) { + couldNotLoadClassInBundle( exc, className, + bundle.getSymbolicName() ) ; + return null ; + } + } else { + return null ; + } + } + + if (codebase.startsWith( PREFIX )) { + String rest = codebase.substring( PREFIX.length() ) ; + int index = rest.indexOf( '/') ; + if (index > 0) { + String name = rest.substring( 0, index ) ; + String version = rest.substring( index+1 ) ; + // version is a version range + if (pkgAdmin != null) { + Bundle[] defBundles = pkgAdmin.getBundles( name, + version ) ; + if (defBundles != null) { + // I think this is the highest available version + try { + foundClassInBundleVersion( + className, name, version ) ; + return secureLoadClass( defBundles[0], className ) ; + } catch (ClassNotFoundException cnfe) { + classNotFoundInBundleVersion( + className, name, version ) ; + // fall through to return null + } + } + } + } + } + + return null ; + } + } + + private static ClassCodeBaseHandler ccbHandler = + new ClassCodeBaseHandlerImpl() ; + + @Osgi + public static ClassCodeBaseHandler classCodeBaseHandler() { + return ccbHandler ; + } + + @InfoMethod + private void insertOrbProvider( String cname, String bname ) {} + + @InfoMethod + private void insertBundlePackage( String pname, String bname ) {} + + @Osgi + private void insertClasses( Bundle bundle ) { + lock.writeLock().lock() ; + try { + final Dictionary dict = secureGetHeaders( bundle ) ; + final String name = bundle.getSymbolicName() ; + if (dict != null) { + final String orbProvider = (String)dict.get( ORB_PROVIDER_KEY ) ; + if (orbProvider != null) { + for (String str : orbProvider.split(",") ) { + String className = str.trim() ; + classNameMap.put( className, bundle ) ; + insertOrbProvider( className, name ) ; + } + } + } + + if (pkgAdmin != null) { + final ExportedPackage[] epkgs = pkgAdmin.getExportedPackages( + bundle ) ; + if (epkgs != null) { + for (ExportedPackage ep : epkgs) { + final String pname = ep.getName() ; + packageNameMap.put( pname, bundle ) ; + insertBundlePackage( pname, + bundle.getSymbolicName() ) ; + } + } + } + } finally { + lock.writeLock().unlock() ; + } + } + + @InfoMethod + private void removeOrbProvider( String cname, String bname ) {} + + @InfoMethod + private void removeBundlePackage( String pname, String bname ) {} + + @Osgi + private void removeClasses( Bundle bundle ) { + lock.writeLock().lock() ; + try { + final Dictionary dict = secureGetHeaders( bundle ) ; + final String name = bundle.getSymbolicName() ; + if (dict != null) { + final String orbProvider = (String)dict.get( ORB_PROVIDER_KEY ) ; + if (orbProvider != null) { + for (String className : orbProvider.split(",") ) { + classNameMap.remove( className ) ; + removeOrbProvider( className, name ) ; + } + } + } + + if (pkgAdmin != null) { + final ExportedPackage[] epkgs = pkgAdmin.getExportedPackages( + bundle ) ; + if (epkgs != null) { + for (ExportedPackage ep : epkgs) { + final String pname = ep.getName() ; + packageNameMap.remove( pname ) ; + removeBundlePackage( pname, + bundle.getSymbolicName() ) ; + } + } + } + } finally { + lock.writeLock().unlock() ; + } + } + + @Osgi + private static Bundle getBundleForClass( String className ) { + lock.readLock().lock() ; + try { + Bundle result = classNameMap.get( className ) ; + if (result == null) { + // Get package prefix + final int index = className.lastIndexOf( '.') ; + if (index > 0) { + final String packageName = className.substring( 0, index ) ; + result = packageNameMap.get( packageName ) ; + } + } + + return result ; + } finally { + lock.readLock().unlock() ; + } + } + + @InfoMethod + private void probeBundlesForProviders() {} + + @Osgi + public void start( BundleContext context ) { + // Get a referece to the PackageAdmin service before we + // do ANYTHING else. + final ServiceReference sref = context.getServiceReference( + "org.osgi.service.packageadmin.PackageAdmin" ) ; + setPackageAdmin( (PackageAdmin)context.getService( sref ) ) ; + + if (pkgAdmin == null) { + wrapper.packageAdminServiceNotAvailable() ; + } + + context.addBundleListener(this); + + // Probe all existing bundles for ORB providers + probeBundlesForProviders() ; + for (Bundle bundle : context.getBundles()) { + insertClasses( bundle ) ; + } + } + + @Osgi + public void stop( BundleContext context ) { + final Bundle myBundle = context.getBundle() ; + removeClasses( myBundle ) ; + } + + @InfoMethod + private void receivedBundleEvent( String type, String name ) {} + + @Osgi + public void bundleChanged(BundleEvent event) { + final int type = event.getType() ; + final Bundle bundle = event.getBundle() ; + final String name = bundle.getSymbolicName() ; + + receivedBundleEvent( getBundleEventType( type ), name ) ; + + if (type == Bundle.INSTALLED) { + insertClasses( bundle ) ; + } else if (type == Bundle.UNINSTALLED) { + removeClasses( bundle ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/NoConnectionCacheImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/NoConnectionCacheImpl.java new file mode 100644 index 000000000..287068a01 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/NoConnectionCacheImpl.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.plugin.hwlb ; + +import java.util.Collection ; +import java.util.Map ; +import java.util.HashMap ; + +import org.omg.CORBA.LocalObject ; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher ; + +import com.sun.corba.ee.spi.transport.Connection ; +import com.sun.corba.ee.spi.transport.OutboundConnectionCache ; + +import com.sun.corba.ee.impl.encoding.CDRInputObject ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBConfigurator ; +import com.sun.corba.ee.spi.orb.DataCollector ; + +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoList ; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory ; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry ; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.transport.ConnectionCacheBase ; +import com.sun.corba.ee.impl.transport.ConnectionImpl ; + +// The following 3 implementation classes are needed as base +// classes. This needs some architectural changes, perhaps +// adding a codegen-based proxy layer for dynamic inheritance. +import com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl ; + +import com.sun.corba.ee.impl.transport.ContactInfoImpl ; +import com.sun.corba.ee.impl.transport.ContactInfoListImpl ; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + + +/** Install this in an ORB using the property + * ORBConstants.USER_CONFIGURATOR_PREFIX + "corba.lb.NoConnectionCacheImpl" = "dummy" + */ +@Transport +public class NoConnectionCacheImpl + extends LocalObject + implements ORBConfigurator +{ + @Transport + private static class NCCConnectionCacheImpl extends ConnectionCacheBase + implements OutboundConnectionCache { + // store is a dummy variable + private Map store = new HashMap() ; + + // holds only one connection + private Connection connection = null ; + + public NCCConnectionCacheImpl( ORB orb ) { + super( orb, "Dummy", "Dummy" ) ; + } + + public Collection values() { + return store.values() ; + } + + protected Object backingStore() { + return store ; + } + + public Connection get(ContactInfo contactInfo) { + return connection ; + } + + @Transport + public void put(ContactInfo contactInfo, Connection conn ) { + remove( contactInfo ) ; + connection = conn ; + } + + @InfoMethod + private void removeConnectionInfo( Connection conn ) { } + + @InfoMethod + private void connectionIsNull() { } + + @Transport + public void remove(ContactInfo contactInfo) { + if (connection != null) { + removeConnectionInfo(connection); + connection.close() ; + connection = null ; + } else { + connectionIsNull(); + } + } + } + + private static ThreadLocal connectionCache = new ThreadLocal() ; + + private static NCCConnectionCacheImpl getConnectionCache( ORB orb ) { + NCCConnectionCacheImpl result = (NCCConnectionCacheImpl)connectionCache.get() ; + if (result == null) { + result = new NCCConnectionCacheImpl( orb ) ; + connectionCache.set( result ) ; + } + + return result ; + } + + @Transport + private static class NCCConnectionImpl extends ConnectionImpl { + private static int count = 0 ; + private int myCount ; + + @Transport + private void constructedNCCConnectionImpl( String str ) { + } + + public NCCConnectionImpl(ORB orb, ContactInfo contactInfo, + String socketType, String hostname, int port) { + + super(orb,contactInfo, socketType, hostname, port); + myCount = count++ ; + constructedNCCConnectionImpl(toString()); + } + + @Override + public String toString() { + return "NCCConnectionImpl(" + myCount + ")[" + + super.toString() + "]" ; + } + + @Transport + @Override + public synchronized void close() { + super.closeConnectionResources() ; + } + } + + @Transport + private static class NCCContactInfoImpl extends ContactInfoImpl { + public NCCContactInfoImpl( ORB orb, + ContactInfoList contactInfoList, IOR effectiveTargetIOR, + short addressingDisposition, String socketType, String hostname, + int port) { + + super( orb, contactInfoList, effectiveTargetIOR, addressingDisposition, + socketType, hostname, port ) ; + } + + @Transport + @Override + public boolean shouldCacheConnection() { + return false ; + } + + @InfoMethod + private void createdConnection( Connection conn ) { } + + @Transport + @Override + public Connection createConnection() { + Connection connection = new NCCConnectionImpl( orb, this, + socketType, hostname, port ) ; + createdConnection(connection); + NCCConnectionCacheImpl cc = NoConnectionCacheImpl.getConnectionCache( orb ) ; + cc.put( this, connection ) ; + connection.setConnectionCache( cc ) ; + + return connection ; + } + } + + public static class NCCContactInfoListImpl extends ContactInfoListImpl { + public NCCContactInfoListImpl( ORB orb, IOR ior ) { + super( orb, ior ) ; + } + + @Override + public ContactInfo createContactInfo( String type, String hostname, + int port ) { + + return new NCCContactInfoImpl( orb, this, effectiveTargetIOR, + orb.getORBData().getGIOPAddressDisposition(), type, hostname, port ) ; + } + } + + private static class NCCClientRequestDispatcherImpl extends ClientRequestDispatcherImpl { + @Override + public void endRequest( ORB broker, Object self, CDRInputObject inputObject ) { + super.endRequest( broker, self, inputObject) ; + getConnectionCache( broker ).remove( null ) ; + } + } + + public void configure( DataCollector dc, final ORB orb ) { + ContactInfoListFactory factory = new ContactInfoListFactory() { + public void setORB(ORB orb) {} + public ContactInfoList create( IOR ior ) { + return new NCCContactInfoListImpl( orb, ior ) ; + } + } ; + + // Disable a read optimization that forces a blocking read on all + // OP_READ events. It makes little sense to enable this optimization + // when using a NCCConnectionCache because clients will close a + // Connection when a response to a request has been received. Hence, + // if the client knows when it receives a response to a request and + // then closes the Connection, there's no reason to enable an + // optimization that will force a blocking read which will wait for + // more data to arrive after the client's response has been received. + orb.getORBData().alwaysEnterBlockingRead( false ) ; + + orb.setCorbaContactInfoListFactory( factory ) ; + + ClientRequestDispatcher crd = new NCCClientRequestDispatcherImpl() ; + RequestDispatcherRegistry rdr = orb.getRequestDispatcherRegistry() ; + // Need to register crd with all scids. Assume range is 0 to MAX_POA_SCID. + for (int ctr=0; ctr= transientRetryTimeout) { + + if (debug) { + System.out.println(msg + + "exceeded transientRetryTimeout: " + + transientRetryTimeout + + " - not retrying"); + } + + return; + } + + doubleBackoff(); + + if (debug) { + System.out.println(msg + "sleep: " + getBackoff()); + } + try { + Thread.sleep(getBackoff()); + } catch (InterruptedException e) { + // Ignore + } + if (debug) { + System.out.println(msg + "done sleeping"); + } + if (isTransientException(ri)) { + throw new ForwardRequest(ri.effective_target()); + } else if (isBadServerIdException(ri)) { + throw new ForwardRequest(ri.target()); + } else { + if (debug) { + System.out.println(msg + "unexpected: " + + ri.received_exception_id()); + } + } + } + + public void receive_other(ClientRequestInfo ri) + { + setBackoff(initialBackoff); + } + + //////////////////////////////////////////////////// + // + // ORBInitializer + // + + public void pre_init(ORBInitInfo info) + { + } + + public void post_init(ORBInitInfo info) + { + try { + if (debug) { + System.out.println(".post_init: registering: " + this); + } + info.add_client_request_interceptor(this); + } catch (DuplicateName e) { + // REVISIT - LOG AND EXIT + if (debug) { + System.out.println(".post_init: exception: " + e); + } + } + } + + ////////////////////////////////////////////////// + // + // Implementation + // + + private boolean isTransientException(ClientRequestInfo ri) + { + return ri.received_exception_id().equals(TRANSIENT_REPOSITORY_ID); + } + + private boolean isBadServerIdException(ClientRequestInfo ri) + { + if (! ri.received_exception_id().equals(OBJECT_NOT_EXIST_REPOSITORY_ID)) { + return false; + } + + SystemException se = + ORBUtility.extractSystemException(ri.received_exception()); + + return + se instanceof org.omg.CORBA.OBJECT_NOT_EXIST + && se.minor == ORBUtilSystemException.BAD_SERVER_ID; + } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/RetryServerRequestInterceptor.java b/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/RetryServerRequestInterceptor.java new file mode 100644 index 000000000..2a82ee2d1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/RetryServerRequestInterceptor.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jul 01 (Fri) 13:36:46 by Harold Carr. +// + +package com.sun.corba.ee.impl.plugin.hwlb ; + +import java.util.Properties; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.TRANSIENT; +import org.omg.PortableInterceptor.ORBInitializer; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; +import org.omg.PortableInterceptor.ServerRequestInterceptor; +import org.omg.PortableInterceptor.ServerRequestInfo; + +/** + * @author Harold Carr + */ +public class RetryServerRequestInterceptor + extends org.omg.CORBA.LocalObject + implements ORBInitializer, ServerRequestInterceptor +{ + private static final String baseMsg = + RetryServerRequestInterceptor.class.getName(); + + private static boolean rejectingRequests = false; + + private static boolean debug = true; + + //////////////////////////////////////////////////// + // + // Application specific + // + + public static boolean getRejectingRequests() + { + return rejectingRequests; + } + + public static void setRejectingRequests(boolean x) + { + rejectingRequests = x; + } + + //////////////////////////////////////////////////// + // + // Interceptor operations + // + + public String name() + { + return baseMsg; + } + + public void destroy() + { + } + + //////////////////////////////////////////////////// + // + // ServerRequestInterceptor + // + + public void receive_request_service_contexts(ServerRequestInfo ri) + { + if (rejectingRequests) { + if (debug) { + System.out.println(baseMsg + + ".receive_request_service_contexts:" + + " rejecting request: " + + ri.operation()); + } + throw new TRANSIENT(); + } + if (debug) { + System.out.println(baseMsg + + ".receive_request_service_contexts:" + + " accepting request: " + + ri.operation()); + } + } + + public void receive_request(ServerRequestInfo ri) + { + } + + public void send_reply(ServerRequestInfo ri) + { + } + + public void send_exception(ServerRequestInfo ri) + { + } + + public void send_other(ServerRequestInfo ri) + { + } + + //////////////////////////////////////////////////// + // + // ORBInitializer + // + + public void pre_init(ORBInitInfo info) + { + } + + public void post_init(ORBInitInfo info) + { + try { + if (debug) { + System.out.println(".post_init: registering: " + this); + } + info.add_server_request_interceptor(this); + } catch (DuplicateName e) { + // REVISIT - LOG AND EXIT + if (debug) { + System.out.println(".post_init: exception: " + e); + } + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/VirtualAddressAgentImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/VirtualAddressAgentImpl.java new file mode 100644 index 000000000..9a5269ee0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/plugin/hwlb/VirtualAddressAgentImpl.java @@ -0,0 +1,357 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.plugin.hwlb ; + +import java.lang.reflect.Field ; + +import java.security.AccessController ; +import java.security.PrivilegedAction ; + +import java.util.Iterator ; + +import org.omg.CORBA.LocalObject ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import org.omg.IOP.TAG_INTERNET_IOP ; + +import org.omg.PortableInterceptor.ORBInitializer ; +import org.omg.PortableInterceptor.IORInterceptor_3_0 ; +import org.omg.PortableInterceptor.IORInfo ; +import org.omg.PortableInterceptor.ORBInitInfo ; +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBData ; +import com.sun.corba.ee.spi.orb.ORBConfigurator ; +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.ParserImplBase ; +import com.sun.corba.ee.spi.orb.PropertyParser ; +import com.sun.corba.ee.spi.orb.OperationFactory ; + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.EncapsulationFactoryBase ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import com.sun.corba.ee.spi.ior.TaggedProfile ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; + + + +import com.sun.corba.ee.impl.ior.iiop.IIOPProfileImpl ; +import com.sun.corba.ee.impl.ior.iiop.IIOPProfileTemplateImpl ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.orb.ORBDataParserImpl ; + + + +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler ; + +import com.sun.corba.ee.impl.interceptors.IORInfoImpl ; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.trace.Subcontract; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Subcontract +public class VirtualAddressAgentImpl + extends LocalObject + implements ORBConfigurator, ORBInitializer, IORInterceptor_3_0 +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public static final String VAA_HOST_PROPERTY = ORBConstants.SUN_PREFIX + + "ORBVAAHost" ; + public static final String VAA_PORT_PROPERTY = ORBConstants.SUN_PREFIX + + "ORBVAAPort" ; + private static final long serialVersionUID = 5670615031510472636L; + + private String host = null ; + private int port = 0 ; + private ORB orb = null ; + private IIOPAddress addr = null ; + private ORBInitializer[] newOrbInits = null ; + + @Subcontract + private class AddressParser extends ParserImplBase { + private String _host = null ; + private int _port = 0 ; + + public PropertyParser makeParser() { + PropertyParser parser = new PropertyParser() ; + parser.add( VAA_HOST_PROPERTY, OperationFactory.stringAction(), + "_host" ) ; + parser.add( VAA_PORT_PROPERTY, OperationFactory.integerAction(), + "_port" ) ; + return parser ; + } + + @Subcontract + @Override + protected void complete() { + host = _host ; + port = _port ; + } + } + + @InfoMethod + private void agentAddress( IIOPAddress addr ) { } + + @Subcontract + public void configure( DataCollector dc, final ORB orb ) { + this.orb = orb ; + + orb.setBadServerIdHandler( + new BadServerIdHandler() { + public void handle( ObjectKey objectkey ) { + // NO-OP + } + } + ) ; + + // Create a new parser to extract the virtual address + // host/port information from the data collector + final AddressParser parser = new AddressParser() ; + parser.init( dc ) ; + addr = IIOPFactories.makeIIOPAddress( host, port ) ; + agentAddress(addr); + + // Register the special IIOPProfile in the TaggedProfileFactoryFinder. + // This means that the isLocal check will be handled properly even + // when an objref leaves the server that created it and then comes + // back and gets unmarshalled. + IdentifiableFactoryFinder finder = + orb.getTaggedProfileFactoryFinder() ; + finder.registerFactory( + new EncapsulationFactoryBase( TAG_INTERNET_IOP.value ) { + public Identifiable readContents( InputStream in ) { + Identifiable result = new SpecialIIOPProfileImpl( in ) ; + return result ; + } + } + ) ; + + // Add this object to the initializer list + // by using a PropertyParser in a rather unusual fashion + + final ORBData odata = orb.getORBData() ; + + // Add this object to the end of a copy of the ORBInitializers + // from the ORBData. + final ORBInitializer[] oldOrbInits = odata.getORBInitializers() ; + final int newIndex = oldOrbInits.length ; + newOrbInits = new ORBInitializer[newIndex+1] ; + for (int ctr=0; ctr 0 ; + if (hasArguments) { + argRWs = new ReaderWriter[ argTypes.length ] ; + for (int ctr=0; ctr cls = null ; + + try { + cls = JDKBridge.loadClass( cname, null, null ) ; + } catch (ClassNotFoundException exc) { + Exceptions.self.readResolveClassNotFound( exc, cname ) ; + } + + PresentationManager pm = + com.sun.corba.ee.spi.orb.ORB.getPresentationManager() ; + PresentationManager.ClassData classData = pm.getClassData( cls ) ; + InvocationHandlerFactoryImpl ihfactory = + (InvocationHandlerFactoryImpl)classData.getInvocationHandlerFactory() ; + return ihfactory.getInvocationHandler( this ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ExceptionHandler.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ExceptionHandler.java new file mode 100644 index 000000000..d38a628dc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ExceptionHandler.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import org.omg.CORBA.portable.ApplicationException ; + +public interface ExceptionHandler +{ + /** Return true iff cls is an exception class that is + * assignment compatible with an exception declared + * on the method used to create this ExceptionHandler. + */ + boolean isDeclaredException( Class cls ) ; + + /** Write the exception ex to os. ex must be assignment + * compatible with an exception + * declared on the method used to create this + * ExceptionHandler. + */ + void writeException( OutputStream os, Exception ex ) ; + + /** Read the exception contained in the InputStream + * in the ApplicationException. If ae represents + * an exception that is assignment compatible with + * an exception on the method used to create this + * exception handler, return the exception, + * otherwise return an UnexpectedException wrapping + * the exception in ae. + */ + Exception readException( ApplicationException ae ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ExceptionHandlerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ExceptionHandlerImpl.java new file mode 100644 index 000000000..9df16a36c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ExceptionHandlerImpl.java @@ -0,0 +1,269 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.rmi.UnexpectedException ; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA.portable.ApplicationException ; + +import java.lang.reflect.Method ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +public class ExceptionHandlerImpl implements ExceptionHandler +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self; + + private ExceptionRW[] rws ; + +/////////////////////////////////////////////////////////////////////////////// +// ExceptionRW interface and implementations. +// Used to read and write exceptions. +/////////////////////////////////////////////////////////////////////////////// + + public interface ExceptionRW + { + Class getExceptionClass() ; + + String getId() ; + + void write( OutputStream os, Exception ex ) ; + + Exception read( InputStream is ) ; + } + + public abstract class ExceptionRWBase implements ExceptionRW + { + private Class cls ; + private String id ; + + public ExceptionRWBase( Class cls ) + { + this.cls = cls ; + } + + public Class getExceptionClass() + { + return cls ; + } + + public String getId() + { + return id ; + } + + void setId( String id ) + { + this.id = id ; + } + } + + public class ExceptionRWIDLImpl extends ExceptionRWBase + { + private Method readMethod ; + private Method writeMethod ; + + public ExceptionRWIDLImpl( Class cls ) + { + super( cls ) ; + + String helperName = cls.getName() + "Helper" ; + ClassLoader loader = cls.getClassLoader() ; + Class helperClass ; + + try { + helperClass = Class.forName( helperName, true, loader ) ; + Method idMethod = helperClass.getDeclaredMethod( "id" ) ; + setId( (String)idMethod.invoke( null ) ) ; + } catch (Exception ex) { + throw wrapper.badHelperIdMethod( ex, helperName ) ; + } + + try { + writeMethod = helperClass.getDeclaredMethod( "write", + org.omg.CORBA.portable.OutputStream.class, cls ) ; + } catch (Exception ex) { + throw wrapper.badHelperWriteMethod( ex, helperName ) ; + } + + try { + readMethod = helperClass.getDeclaredMethod( "read", + org.omg.CORBA.portable.InputStream.class ) ; + } catch (Exception ex) { + throw wrapper.badHelperReadMethod( ex, helperName ) ; + } + } + + public void write( OutputStream os, Exception ex ) + { + try { + writeMethod.invoke( null, os, ex ) ; + } catch (Exception exc) { + throw wrapper.badHelperWriteMethod( exc, + writeMethod.getDeclaringClass().getName() ) ; + } + } + + public Exception read( InputStream is ) + { + try { + return (Exception)readMethod.invoke( null, is ) ; + } catch (Exception ex) { + throw wrapper.badHelperReadMethod( ex, + readMethod.getDeclaringClass().getName() ) ; + } + } + } + + public class ExceptionRWRMIImpl extends ExceptionRWBase + { + public ExceptionRWRMIImpl( Class cls ) + { + super( cls ) ; + setId( IDLNameTranslatorImpl.getExceptionId( cls ) ) ; + } + + public void write( OutputStream os, Exception ex ) + { + os.write_string( getId() ) ; + os.write_value( ex, getExceptionClass() ) ; + } + + public Exception read( InputStream is ) + { + is.read_string() ; // read and ignore! + return (Exception)is.read_value( getExceptionClass() ) ; + } + } + +/////////////////////////////////////////////////////////////////////////////// + + public ExceptionHandlerImpl( Class[] exceptions ) + { + int count = 0 ; + for (int ctr=0; ctr 0) { + ExceptionRW duprw = rws[duplicateIndex] ; + String firstClassName = + erw.getExceptionClass().getName() ; + String secondClassName = + duprw.getExceptionClass().getName() ; + throw wrapper.duplicateExceptionRepositoryId( + firstClassName, secondClassName, repositoryId ) ; + } + + */ + + rws[index++] = erw ; + } + } + } + + private int findDeclaredException( Class cls ) + { + for (int ctr = 0; ctr < rws.length; ctr++) { + Class next = rws[ctr].getExceptionClass() ; + if (next.isAssignableFrom(cls)) + return ctr ; + } + + return -1 ; + } + + private int findDeclaredException( String repositoryId ) + { + for (int ctr=0; ctr= 0 ; + } + + public void writeException( OutputStream os, Exception ex ) + { + int index = findDeclaredException( ex.getClass() ) ; + if (index < 0) + throw wrapper.writeUndeclaredException( ex, + ex.getClass().getName() ) ; + + rws[index].write( os, ex ) ; + } + + public Exception readException( ApplicationException ae ) + { + // Note that the exception ID is present in both ae + // and in the input stream from ae. The exception + // reader must actually read the exception ID from + // the stream. + InputStream is = (InputStream)ae.getInputStream() ; + String excName = ae.getId() ; + int index = findDeclaredException( excName ) ; + if (index < 0) { + excName = is.read_string() ; + Exception res = new UnexpectedException( excName ) ; + res.initCause( ae ) ; + return res ; + } + + return rws[index].read( is ) ; + } + + // This is here just for the dynamicrmiiiop test + public ExceptionRW getRMIExceptionRW( Class cls ) + { + return new ExceptionRWRMIImpl( cls ) ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/Exceptions.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/Exceptions.java new file mode 100644 index 000000000..fea5b1faf --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/Exceptions.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import com.sun.corba.ee.spi.logex.stdcorba.StandardLogger; +import javax.naming.Context; +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +/** + * + * @author ken + */ +@ExceptionWrapper( idPrefix="ORBPRES" ) +public interface Exceptions { + + Exceptions self = WrapperGenerator.makeWrapper( Exceptions.class, + StandardLogger.self ) ; + + int EXCEPTIONS_PER_CLASS = 100 ; + +// JNDISateFactoryImpl + int JSFI_START = 0 ; + + @Message( "No stub could be created" ) + @Log( level=LogLevel.FINE, id = JSFI_START + 1 ) + void noStub(@Chain Exception exc); + + @Message( "Could not connect stub" ) + @Log( level=LogLevel.FINE, id = JSFI_START + 2 ) + void couldNotConnect(@Chain Exception exc); + + @Message( "Could not get ORB from naming context" ) + @Log( level=LogLevel.FINE, id = JSFI_START + 2 ) + void couldNotGetORB(@Chain Exception exc, Context nc ); + +// DynamicStubImpl + int DSI_START = JSFI_START + EXCEPTIONS_PER_CLASS ; + + @Message( "ClassNotFound exception in readResolve on class {0}") + @Log( level=LogLevel.FINE, id = DSI_START + 1 ) + void readResolveClassNotFound(@Chain ClassNotFoundException exc, String cname); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLNameTranslatorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLNameTranslatorImpl.java new file mode 100644 index 000000000..820fb892c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLNameTranslatorImpl.java @@ -0,0 +1,852 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import java.lang.reflect.Method; + +import java.util.Map; +import java.util.Set; +import java.util.HashSet; +import java.util.HashMap; +import java.util.StringTokenizer; + +import com.sun.corba.ee.spi.presentation.rmi.IDLNameTranslator ; +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults ; +import org.glassfish.pfl.basic.proxy.DynamicAccessPermission ; + +/** + * Bidirectional translator between RMI-IIOP interface methods and + * and IDL Names. + */ +public class IDLNameTranslatorImpl implements IDLNameTranslator { + + // From CORBA Spec, Table 6 Keywords. + // Note that since all IDL identifiers are case + // insensitive, java identifier comparisons to these + // will be case insensitive also. + private static String[] IDL_KEYWORDS = { + + "abstract", "any", "attribute", "boolean", "case", "char", + "const", "context", "custom", "default", "double", "enum", + "exception", "factory", "FALSE", "fixed", "float", "in", "inout", + "interface", "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" + + }; + + private static char[] HEX_DIGITS = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F' + }; + + private static final String UNDERSCORE = "_"; + + // used to mangle java inner class names + private static final String INNER_CLASS_SEPARATOR = + UNDERSCORE + UNDERSCORE; + + // used to form IDL array type names + private static final String[] BASE_IDL_ARRAY_MODULE_TYPE= + new String[] { "org", "omg", "boxedRMI" } ; + + private static final String BASE_IDL_ARRAY_ELEMENT_TYPE = "seq"; + + // used to mangling java identifiers that have a leading underscore + private static final String LEADING_UNDERSCORE_CHAR = "J"; + private static final String ID_CONTAINER_CLASH_CHAR = UNDERSCORE; + + // separator used between types in a mangled overloaded method name + private static final String OVERLOADED_TYPE_SEPARATOR = + UNDERSCORE + UNDERSCORE; + + // string appended to attribute if it clashes with a method name + private static final String ATTRIBUTE_METHOD_CLASH_MANGLE_CHARS = + UNDERSCORE + UNDERSCORE; + + // strings prepended to the attribute names in order to form their + // IDL names. + private static final String GET_ATTRIBUTE_PREFIX = "_get_"; + private static final String SET_ATTRIBUTE_PREFIX = "_set_"; + private static final String IS_ATTRIBUTE_PREFIX = "_get_"; + + private static Set idlKeywords_; + + static { + idlKeywords_ = new HashSet(); + for ( String str : IDL_KEYWORDS) { + idlKeywords_.add( str.toUpperCase() ) ; + } + } + + // + // Instance state + // + + // Remote interface for name translation. + private Class[] interf_; + + // Maps used to hold name translations. These do not need to be + // synchronized since the translation is never modified after + // initialization. + private Map methodToIDLNameMap_; + private Map IDLNameToMethodMap_; + private Method[] methods_; + + /** + * Return an IDLNameTranslator for the given interface. + * + * @throws IllegalStateException if given class is not a valid + * RMI/IIOP Remote Interface + */ + public static IDLNameTranslator get( final Class interf ) + { + return AccessController.doPrivileged( + new PrivilegedAction() { + public IDLNameTranslator run() { + return new IDLNameTranslatorImpl( new Class[] { interf } ) ; + } + } ) ; + } + + /** + * Return an IDLNameTranslator for the given interfacex. + * + * @throws IllegalStateException if given classes are not valid + * RMI/IIOP Remote Interfaces + */ + public static IDLNameTranslator get( final Class[] interfaces ) + { + return AccessController.doPrivileged( + new PrivilegedAction() { + public IDLNameTranslator run() { + return new IDLNameTranslatorImpl( interfaces ) ; + } + } ) ; + } + + public static String getExceptionId( Class cls ) + { + // Requirements for this method: + // 1. cls must be an exception but not a RemoteException. + // 2. If cls has an IDL keyword name, an underscore is prepended (1.3.2.2). + // 3. If cls jas a leading underscore, J is prepended (1.3.2.3). + // 4. If cls has an illegal IDL ident char, it is mapped to UXXXX where + // XXXX is the unicode value in hex of the char (1.3.2.4). + // 5. double underscore for inner class (1.3.2.5). + // 6. The ID is "IDL:" + name with / separators + ":1.0". + IDLType itype = classToIDLType( cls ) ; + return itype.getExceptionName() ; + } + + public Class[] getInterfaces() + { + return interf_; + } + + public Method[] getMethods() + { + return methods_ ; + } + + public Method getMethod( String idlName ) + { + return IDLNameToMethodMap_.get(idlName); + } + + public String getIDLName( Method method ) + { + return methodToIDLNameMap_.get(method); + } + + /** + * Initialize an IDLNameTranslator for the given interface. + * + * @throws IllegalStateException if given class is not a valid + * RMI/IIOP Remote Interface + */ + private IDLNameTranslatorImpl(Class[] interfaces) + { + if (!PresentationDefaults.inAppServer()) { + SecurityManager s = System.getSecurityManager() ; + if (s != null) { + s.checkPermission( new DynamicAccessPermission( "access" ) ) ; + } + } + + try { + IDLTypesUtil idlTypesUtil = new IDLTypesUtil(); + for (int ctr=0; ctr allMethodInfo = + new HashMap() ; + + for (Class interf : interf_) { + IDLTypesUtil idlTypesUtil = new IDLTypesUtil(); + final Method[] methods = interf.getMethods(); + // Handle the case of a non-public interface! + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + Method.setAccessible( methods, true ) ; + return null ; + } + } ) ; + + // Take an initial pass through all the methods and create some + // information that will be used to track the IDL name + // transformation. + for (Method nextMethod : methods) { + IDLMethodInfo methodInfo = new IDLMethodInfo(); + + methodInfo.method = nextMethod; + + if (idlTypesUtil.isPropertyAccessorMethod(nextMethod, interf)) { + methodInfo.isProperty = true; + String attributeName = idlTypesUtil. + getAttributeNameForProperty(nextMethod.getName()); + methodInfo.originalName = attributeName; + methodInfo.mangledName = attributeName; + } else { + methodInfo.isProperty = false; + methodInfo.originalName = nextMethod.getName(); + methodInfo.mangledName = nextMethod.getName(); + } + + allMethodInfo.put(nextMethod, methodInfo); + } + } + + // + // Perform case sensitivity test first. This applies to all + // method names AND attributes. Compare each method name and + // attribute to all other method names and attributes. If names + // differ only in case, apply mangling as defined in section 1.3.2.7 + // of Java2IDL spec. Note that we compare using the original names. + // + for (IDLMethodInfo outer : allMethodInfo.values()) { + for (IDLMethodInfo inner : allMethodInfo.values()) { + if( (outer != inner) && + (!outer.originalName.equals(inner.originalName)) && + outer.originalName.equalsIgnoreCase(inner.originalName) ) { + outer.mangledName = + mangleCaseSensitiveCollision(outer.originalName); + break; + } + } + } + + for (IDLMethodInfo next : allMethodInfo.values()) { + next.mangledName = + mangleIdentifier(next.mangledName, next.isProperty); + } + + // + // Now check for overloaded method names and apply 1.3.2.6. + // + for (IDLMethodInfo outer : allMethodInfo.values()) { + if( outer.isProperty ) { + continue; + } + for (IDLMethodInfo inner : allMethodInfo.values()) { + if( (outer != inner) && !inner.isProperty && + outer.originalName.equals(inner.originalName) ) { + outer.mangledName = mangleOverloadedMethod + (outer.mangledName, outer.method); + break; + } + } + } + + // + // Now mangle any properties that clash with method names. + // + for (IDLMethodInfo outer : allMethodInfo.values()) { + if( !outer.isProperty ) { + continue; + } + for (IDLMethodInfo inner : allMethodInfo.values()) { + if( (outer != inner) && !inner.isProperty && + outer.mangledName.equals(inner.mangledName) ) { + outer.mangledName += ATTRIBUTE_METHOD_CLASH_MANGLE_CHARS; + break; + } + } + } + + // + // Ensure that no mapped method names clash with mapped name + // of container(1.3.2.9). This is a case insensitive comparison. + // + for (Class interf : interf_) { + String mappedContainerName = getMappedContainerName(interf); + for (IDLMethodInfo next : allMethodInfo.values()) { + if( !next.isProperty && + identifierClashesWithContainer(mappedContainerName, + next.mangledName)) { + next.mangledName = mangleContainerClash(next.mangledName); + } + } + } + + // + // Populate name translation maps. + // + methodToIDLNameMap_ = new HashMap(); + IDLNameToMethodMap_ = new HashMap(); + methods_ = allMethodInfo.keySet().toArray( + new Method[0] ) ; + + for (IDLMethodInfo next : allMethodInfo.values()) { + String idlName = next.mangledName; + if( next.isProperty ) { + String origMethodName = next.method.getName(); + String prefix = ""; + + if( origMethodName.startsWith("get") ) { + prefix = GET_ATTRIBUTE_PREFIX; + } else if( origMethodName.startsWith("set") ) { + prefix = SET_ATTRIBUTE_PREFIX; + } else { + prefix = IS_ATTRIBUTE_PREFIX; + } + + idlName = prefix + next.mangledName; + } + + methodToIDLNameMap_.put(next.method, idlName); + + // Final check to see if there are any clashes after all the + // manglings have been applied. If so, this is treated as an + // invalid interface. Currently, we do a CASE-SENSITIVE + // comparison since that matches the rmic behavior. + if( IDLNameToMethodMap_.containsKey(idlName) ) { + Method clash = IDLNameToMethodMap_.get(idlName); + throw new IllegalStateException("Error : methods " + + clash + " and " + next.method + + " both result in IDL name '" + idlName + "'"); + } else { + IDLNameToMethodMap_.put(idlName, next.method); + } + } + + return; + + } + + + /** + * Perform all necessary stand-alone identifier mangling operations + * on a java identifier that is being transformed into an IDL name. + * That is, mangling operations that don't require looking at anything + * else but the identifier itself. This covers sections 1.3.2.2, 1.3.2.3, + * and 1.3.2.4 of the Java2IDL spec. Method overloading and + * case-sensitivity checks are handled elsewhere. + */ + + private static String mangleIdentifier(String identifier) { + return mangleIdentifier(identifier, false); + } + + private static String mangleIdentifier(String identifier, boolean attribute) { + + String mangledName = identifier; + + // + // Apply leading underscore test (1.3.2.3) + // This should be done before IDL Keyword clash test, since clashing + // IDL keywords are mangled by adding a leading underscore. + // + if( hasLeadingUnderscore(mangledName) ) { + mangledName = mangleLeadingUnderscore(mangledName); + } + + // + // Apply IDL keyword clash test (1.3.2.2). + // This is not needed for attributes since when the full property + // name is composed it cannot clash with an IDL keyword. + // (Also, rmic doesn't do it.) + // + + if( !attribute && isIDLKeyword(mangledName) ) { + mangledName = mangleIDLKeywordClash(mangledName); + } + + // + // Replace illegal IDL identifier characters (1.3.2.4) + // for all method names and attributes. + // + if( !isIDLIdentifier(mangledName) ) { + mangledName = mangleUnicodeChars(mangledName); + } + + return mangledName; + } + + // isIDLKeyword and mangleIDLKeywordClash are exposed here so that + // IDLType can use them. + + /** + * Checks whether a java identifier clashes with an + * IDL keyword. Note that this is a case-insensitive + * comparison. + * + * Used to implement section 1.3.2.2 of Java2IDL spec. + */ + static boolean isIDLKeyword(String identifier) { + + String identifierAllCaps = identifier.toUpperCase(); + + return idlKeywords_.contains(identifierAllCaps); + } + + static String mangleIDLKeywordClash(String identifier) { + return UNDERSCORE + identifier; + } + + private static String mangleLeadingUnderscore(String identifier) { + return LEADING_UNDERSCORE_CHAR + identifier; + } + + /** + * Checks whether a java identifier starts with an underscore. + * Used to implement section 1.3.2.3 of Java2IDL spec. + */ + private static boolean hasLeadingUnderscore(String identifier) { + return identifier.startsWith(UNDERSCORE); + } + + /** + * Implements Section 1.3.2.4 of Java2IDL Mapping. + * All non-IDL identifier characters must be replaced + * with their Unicode representation. + */ + static String mangleUnicodeChars(String identifier) { + StringBuilder mangledIdentifier = new StringBuilder(); + + for(int i = 0; i < identifier.length(); i++) { + char nextChar = identifier.charAt(i); + if( isIDLIdentifierChar(nextChar) ) { + mangledIdentifier.append(nextChar); + } else { + String unicode = charToUnicodeRepresentation(nextChar); + mangledIdentifier.append(unicode); + } + } + + return mangledIdentifier.toString(); + } + + /** + * Implements mangling portion of Section 1.3.2.7 of Java2IDL spec. + * This method only deals with the actual mangling. Decision about + * whether case-sensitive collision mangling is required is made + * elsewhere. + * + * + * "...a mangled name is generated consisting of the original name + * followed by an underscore separated list of decimal indices + * into the string, where the indices identify all the upper case + * characters in the original string. Indices are zero based." + * + */ + String mangleCaseSensitiveCollision(String identifier) { + + StringBuilder mangledIdentifier = new StringBuilder(identifier); + + // There is always at least one trailing underscore, whether or + // not the identifier has uppercase letters. + mangledIdentifier.append(UNDERSCORE); + + boolean needUnderscore = false; + for(int i = 0; i < identifier.length(); i++) { + char next = identifier.charAt(i); + if( Character.isUpperCase(next) ) { + // This bit of logic is needed to ensure that we have + // an underscore separated list of indices but no + // trailing underscores. Basically, after we have at least + // one uppercase letter, we always put an undercore before + // printing the next one. + if( needUnderscore ) { + mangledIdentifier.append(UNDERSCORE); + } + mangledIdentifier.append(i); + needUnderscore = true; + } + } + + return mangledIdentifier.toString(); + } + + private static String mangleContainerClash(String identifier) { + return identifier + ID_CONTAINER_CLASH_CHAR; + } + + /** + * Implements Section 1.3.2.9 of Java2IDL Mapping. Container in this + * context means the name of the java Class(excluding package) in which + * the identifier is defined. Comparison is case-insensitive. + */ + private static boolean identifierClashesWithContainer + (String mappedContainerName, String identifier) { + + return identifier.equalsIgnoreCase(mappedContainerName); + } + + /** + * Returns Unicode mangling as defined in Section 1.3.2.4 of + * Java2IDL spec. + * + * "For Java identifiers that contain illegal OMG IDL identifier + * characters such as '$' or Unicode characters outside of ISO Latin 1, + * any such illegal characters are replaced by "U" followed by the + * 4 hexadecimal characters(in upper case) representing the Unicode + * value. So, the Java name a$b is mapped to aU0024b and + * x\u03bCy is mapped to xU03BCy." + */ + public static String charToUnicodeRepresentation(char c) { + + int orig = (int) c; + StringBuilder hexString = new StringBuilder(); + + int value = orig; + + while( value > 0 ) { + int div = value / 16; + int mod = value % 16; + hexString.insert(0, HEX_DIGITS[mod]); + value = div; + } + + int numZerosToAdd = 4 - hexString.length(); + for(int i = 0; i < numZerosToAdd; i++) { + hexString.insert(0, "0"); + } + + hexString.insert(0, "U"); + return hexString.toString(); + } + + private static boolean isIDLIdentifier(String identifier) { + + boolean isIdentifier = true; + + for(int i = 0; i < identifier.length(); i++) { + char nextChar = identifier.charAt(i); + // 1st char must be alphbetic. + isIdentifier = (i == 0) ? + isIDLAlphabeticChar(nextChar) : + isIDLIdentifierChar(nextChar); + if( !isIdentifier ) { + break; + } + } + + return isIdentifier; + + } + + private static boolean isIDLIdentifierChar(char c) { + return (isIDLAlphabeticChar(c) || + isIDLDecimalDigit(c) || + isUnderscore(c)); + } + + /** + * True if character is one of 114 Alphabetic characters as + * specified in Table 2 of Chapter 3 in CORBA spec. + */ + private static boolean isIDLAlphabeticChar(char c) { + + // NOTE that we can't use the java.lang.Character + // isUpperCase, isLowerCase, etc. methods since they + // include many characters other than the Alphabetic list in + // the CORBA spec. Instead, we test for inclusion in the + // Unicode value ranges for the corresponding legal characters. + + boolean alphaChar = + ( + // A - Z + ((c >= 0x0041) && (c <= 0x005A)) + + || + + // a - z + ((c >= 0x0061) && (c <= 0x007A)) + + || + + // other letter uppercase, other letter lowercase, which is + // the entire upper half of C1 Controls except X and / + ((c >= 0x00C0) && (c <= 0x00FF) + && (c != 0x00D7) && (c != 0x00F7))); + + return alphaChar; + } + + /** + * True if character is one of 10 Decimal Digits + * specified in Table 3 of Chapter 3 in CORBA spec. + */ + private static boolean isIDLDecimalDigit(char c) { + return ( (c >= 0x0030) && (c <= 0x0039) ); + } + + private static boolean isUnderscore(char c) { + return ( c == 0x005F ); + } + + /** + * Mangle an overloaded method name as defined in Section 1.3.2.6 of + * Java2IDL spec. Current value of method name is passed in as argument. + * We can't start from original method name since the name might have + * been partially mangled as a result of the other rules. + */ + private static String mangleOverloadedMethod(String mangledName, Method m) { + + IDLTypesUtil idlTypesUtil = new IDLTypesUtil(); + + // Start by appending the separator string + String newMangledName = mangledName + OVERLOADED_TYPE_SEPARATOR; + + Class[] parameterTypes = m.getParameterTypes(); + + for(int i = 0; i < parameterTypes.length; i++) { + Class nextParamType = parameterTypes[i]; + + if( i > 0 ) { + newMangledName += OVERLOADED_TYPE_SEPARATOR; + } + IDLType idlType = classToIDLType(nextParamType); + + String moduleName = idlType.getModuleName(); + String memberName = idlType.getMemberName(); + + String typeName = (moduleName.length() > 0) ? + moduleName + UNDERSCORE + memberName : memberName; + + if( !idlTypesUtil.isPrimitive(nextParamType) && + (idlTypesUtil.getSpecialCaseIDLTypeMapping(nextParamType) + == null) && + isIDLKeyword(typeName) ) { + typeName = mangleIDLKeywordClash(typeName); + } + + typeName = mangleUnicodeChars(typeName); + + newMangledName += typeName; + } + + return newMangledName; + } + + + private static IDLType classToIDLType(Class c) { + + IDLType idlType = null; + IDLTypesUtil idlTypesUtil = new IDLTypesUtil(); + + if( idlTypesUtil.isPrimitive(c) ) { + + idlType = idlTypesUtil.getPrimitiveIDLTypeMapping(c); + + } else if( c.isArray() ) { + + // Calculate array depth, as well as base element type. + Class componentType = c.getComponentType(); + int numArrayDimensions = 1; + while(componentType.isArray()) { + componentType = componentType.getComponentType(); + numArrayDimensions++; + } + IDLType componentIdlType = classToIDLType(componentType); + + String[] modules = BASE_IDL_ARRAY_MODULE_TYPE; + if( componentIdlType.hasModule() ) { + final String[] cModules = componentIdlType.getModules() ; + final String[] newModules = new String[ modules.length + + cModules.length ] ; + System.arraycopy(modules, 0, newModules, 0, modules.length); + System.arraycopy(cModules, 0, newModules, modules.length, + cModules.length); + modules = newModules ; + } + + String memberName = BASE_IDL_ARRAY_ELEMENT_TYPE + + numArrayDimensions + UNDERSCORE + + componentIdlType.getMemberName(); + + idlType = new IDLType(c, modules, memberName); + + } else { + idlType = idlTypesUtil.getSpecialCaseIDLTypeMapping(c); + + if (idlType == null) { + // Section 1.3.2.5 of Java2IDL spec defines mangling rules for + // inner classes. + String memberName = getUnmappedContainerName(c); + + // replace inner class separator with double underscore + memberName = memberName.replaceAll("\\$", + INNER_CLASS_SEPARATOR); + + if( hasLeadingUnderscore(memberName) ) { + memberName = mangleLeadingUnderscore(memberName); + } + + // Get raw package name. If there is a package, it + // will still have the "." separators and none of the + // mangling rules will have been applied. + String packageName = getPackageName(c); + + if (packageName == null) { + idlType = new IDLType( c, memberName ) ; + } else { + // If this is a generated IDL Entity Type we need to + // prepend org_omg_boxedIDL per sections 1.3.5 and 1.3.9 + if (idlTypesUtil.isEntity(c)) { + packageName = "org.omg.boxedIDL." + packageName ; + } + + // Section 1.3.2.1 and 1.3.2.6 of Java2IDL spec defines + // rules for mapping java packages to IDL modules and for + // mangling module name portion of type name. NOTE that + // of the individual identifier mangling rules, + // only the leading underscore test is done here. + // The other two(IDL Keyword, Illegal Unicode chars) are + // done in mangleOverloadedMethodName. + StringTokenizer tokenizer = + new StringTokenizer(packageName, "."); + + String[] modules = new String[ tokenizer.countTokens() ] ; + int index = 0 ; + while (tokenizer.hasMoreElements()) { + String next = tokenizer.nextToken(); + String moreMangled = hasLeadingUnderscore( next ) ? + mangleLeadingUnderscore( next ) : next; + + modules[index++] = moreMangled ; + } + + idlType = new IDLType(c, modules, memberName); + } + } + } + + return idlType; + } + + /** + * Return Class' package name or null if there is no package. + */ + private static String getPackageName(Class c) { + Package thePackage = c.getPackage(); + String packageName = null; + + // Try to get package name by introspection. Some classloaders might + // not provide this information, so check for null. + if( thePackage != null ) { + packageName = thePackage.getName(); + } else { + // brute force method + String fullyQualifiedClassName = c.getName(); + int lastDot = fullyQualifiedClassName.indexOf('.'); + packageName = (lastDot == -1) ? null : + fullyQualifiedClassName.substring(0, lastDot); + } + return packageName; + } + + private static String getMappedContainerName(Class c) { + String unmappedName = getUnmappedContainerName(c); + + return mangleIdentifier(unmappedName); + } + + /** + * Return portion of class name excluding package name. + */ + private static String getUnmappedContainerName(Class c) { + + String memberName = null; + String packageName = getPackageName(c); + + String fullyQualifiedClassName = c.getName(); + + if( packageName != null ) { + int packageLength = packageName.length(); + memberName = fullyQualifiedClassName.substring(packageLength + 1); + } else { + memberName = fullyQualifiedClassName; + + } + + return memberName; + } + + /** + * Internal helper class for tracking information related to each + * interface method while we're building the name translation table. + */ + private static class IDLMethodInfo + { + public Method method; + public boolean isProperty; + + // If this is a property, originalName holds the original + // attribute name. Otherwise, it holds the original method name. + public String originalName; + + // If this is a property, mangledName holds the mangled attribute + // name. Otherwise, it holds the mangled method name. + public String mangledName; + + } + + @Override + public String toString() { + + StringBuilder contents = new StringBuilder(); + contents.append("IDLNameTranslator[" ); + for( int ctr=0; ctr0) + sbuff.append( separator ) ; + + if (fixIDLKeywords && IDLNameTranslatorImpl.isIDLKeyword(mod)) + mod = IDLNameTranslatorImpl.mangleIDLKeywordClash( mod ) ; + + sbuff.append( mod ) ; + } + + return sbuff.toString() ; + } + + public String getModuleName() { + // Note that this should probably be makeConcatenatedName( '/', true ) + // for spec compliance, + // but rmic does it this way, so we'll leave this. + // The effect is that an overloaded method like + // void foo( bar.typedef.Baz ) + // will get an IDL name of foo__bar_typedef_Baz instead of + // foo__bar__typedef_Baz (note the extra _ before typedef). + return makeConcatenatedName( '_', false ) ; + } + + public String getExceptionName() { + // Here we will check for IDL keyword collisions (see bug 5010332). + // This means that the repository ID for + // foo.exception.SomeException is + // "IDL:foo/_exception/SomeEx:1.0" (note the underscore in front + // of the exception module name). + String modName = makeConcatenatedName( '/', true ) ; + + String suffix = "Exception" ; + String excName = memberName_ ; + if (excName.endsWith( suffix )) { + int last = excName.length() - suffix.length() ; + excName = excName.substring( 0, last ) ; + } + + // See bug 4989312: we must always add the Ex. + excName += "Ex" ; + + if (modName.length() == 0) + return "IDL:" + excName + ":1.0" ; + else + return "IDL:" + modName + '/' + excName + ":1.0" ; + } + + public String getMemberName() { + return memberName_; + } + + /** + * True if this type doesn't have a containing module. This + * would be true of a java type defined in the default package + * or a primitive. + */ + public boolean hasModule() { + return (modules_.length > 0) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLTypeException.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLTypeException.java new file mode 100644 index 000000000..fef7c96a3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLTypeException.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +/** + * Checked exception containing information about an + * an IDL type validation. + */ +public class IDLTypeException extends Exception { + + public IDLTypeException() {} + + public IDLTypeException(String message) { + super(message); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLTypesUtil.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLTypesUtil.java new file mode 100644 index 000000000..8ac33a361 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/IDLTypesUtil.java @@ -0,0 +1,582 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.lang.reflect.Method; +import java.lang.reflect.Field; +import java.util.Set; +import java.util.HashSet; +import java.util.Iterator; + +/** + * Utility class for testing RMI/IDL Types as defined in + * Section 1.2 of The Java Language to IDL Mapping. Note that + * these are static checks only. Runtime checks, such as those + * described in Section 1.2.3, #3, are not covered. + */ +public final class IDLTypesUtil { + + private static final String GET_PROPERTY_PREFIX = "get"; + private static final String SET_PROPERTY_PREFIX = "set"; + private static final String IS_PROPERTY_PREFIX = "is"; + + public static final int VALID_TYPE = 0; + public static final int INVALID_TYPE = 1; + + /* rmic -iiop does not correctly implement the clause in 1.3.4.3 + * about is/get conflicts. The spec says that + * is is the property and get is left alone, + * but rmic does the opposite. We will follow rmic in this, + * but it's easy to change. + */ + public static final boolean FOLLOW_RMIC = true ; + + /** + * Validate a class to ensure it conforms to the rules for a + * Java RMI/IIOP interface. + * + * @throws IDLTypeException if not a valid RMI/IIOP interface. + */ + public void validateRemoteInterface(Class c) throws IDLTypeException + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + if( !c.isInterface() ) { + String msg = "Class " + c + " must be a java interface."; + throw new IDLTypeException(msg); + } + + if( !java.rmi.Remote.class.isAssignableFrom(c) ) { + String msg = "Class " + c + " must extend java.rmi.Remote, " + + "either directly or indirectly."; + throw new IDLTypeException(msg); + } + + // Get all methods, including super-interface methods. + Method[] methods = c.getMethods(); + + for(int i = 0; i < methods.length; i++) { + Method next = methods[i]; + validateExceptions(next); + } + + // Removed because of bug 4989053 + // validateDirectInterfaces(c); + validateConstants(c); + + return; + } + + public boolean isRemoteInterface(Class c) + { + boolean remoteInterface = true; + try { + validateRemoteInterface(c); + } catch(IDLTypeException ite) { + remoteInterface = false; + } + + return remoteInterface; + } + + /** + * Section 1.2.2 Primitive Types + */ + public boolean isPrimitive(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + return c.isPrimitive(); + } + + /** + * Section 1.2.4 + */ + public boolean isValue(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + return + (!c.isInterface() && + java.io.Serializable.class.isAssignableFrom(c) && + !java.rmi.Remote.class.isAssignableFrom(c)); + } + + /** + * Section 1.2.5 + */ + public boolean isArray(Class c) + { + boolean arrayType = false; + + if( c == null ) { + throw new IllegalArgumentException(); + } + + if( c.isArray() ) { + Class componentType = c.getComponentType(); + arrayType = + (isPrimitive(componentType) || isRemoteInterface(componentType) || + isEntity(componentType) || isException(componentType) || + isValue(componentType) || isObjectReference(componentType) ); + } + + return arrayType; + } + + /** + * Section 1.2.6 + */ + public boolean isException(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + // Must be a checked exception, not including RemoteException or + // its subclasses. + return isCheckedException(c) && !isRemoteException(c) && isValue(c); + } + + public boolean isRemoteException(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + return java.rmi.RemoteException.class.isAssignableFrom(c) ; + } + + public boolean isCheckedException(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + return Throwable.class.isAssignableFrom(c) && + !RuntimeException.class.isAssignableFrom(c) && + !Error.class.isAssignableFrom(c) ; + } + + /** + * Section 1.2.7 + */ + public boolean isObjectReference(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + return (c.isInterface() && + org.omg.CORBA.Object.class.isAssignableFrom(c)); + } + + /** + * Section 1.2.8 + */ + public boolean isEntity(Class c) + { + if( c == null ) { + throw new IllegalArgumentException(); + } + + Class superClass = c.getSuperclass(); + return (!c.isInterface() && + (superClass != null) && + (org.omg.CORBA.portable.IDLEntity.class.isAssignableFrom(c))); + } + + /** + * Return true if given method is legal property accessor as defined in + * Section 1.3.4.3 of Java2IDL spec. + */ + public boolean isPropertyAccessorMethod(Method m, Class c) { + + String methodName = m.getName(); + Class returnType = m.getReturnType(); + Class[] parameters = m.getParameterTypes(); + Class[] exceptionTypes = m.getExceptionTypes(); + String propertyType = null; + + if( methodName.startsWith(GET_PROPERTY_PREFIX) ) { + + if((parameters.length == 0) && (returnType != Void.TYPE) && + !readHasCorrespondingIsProperty(m, c)) { + propertyType = GET_PROPERTY_PREFIX; + } + + } else if( methodName.startsWith(SET_PROPERTY_PREFIX) ) { + + if((returnType == Void.TYPE) && (parameters.length == 1)) { + if (hasCorrespondingReadProperty(m, c, GET_PROPERTY_PREFIX) || + hasCorrespondingReadProperty(m, c, IS_PROPERTY_PREFIX)) { + propertyType = SET_PROPERTY_PREFIX; + } + } + + } else if( methodName.startsWith(IS_PROPERTY_PREFIX) ) { + if((parameters.length == 0) && (returnType == Boolean.TYPE) && + !isHasCorrespondingReadProperty(m, c)) { + propertyType = IS_PROPERTY_PREFIX; + } + } + + // Some final checks that apply to all properties. + if( propertyType != null ) { + if(!validPropertyExceptions(m) || + (methodName.length() <= propertyType.length())) { + propertyType = null; + } + } + + return (propertyType != null); + } + + private boolean hasCorrespondingReadProperty + (Method writeProperty, Class c, String readPropertyPrefix) + { + String writePropertyMethodName = writeProperty.getName(); + Class[] writePropertyParameters = writeProperty.getParameterTypes(); + boolean foundReadProperty = false; + + try { + // Look for a valid corresponding Read property + String readPropertyMethodName = + writePropertyMethodName.replaceFirst + (SET_PROPERTY_PREFIX, readPropertyPrefix); + Method readPropertyMethod = c.getMethod(readPropertyMethodName, + new Class[] {}); + foundReadProperty = + ( isPropertyAccessorMethod(readPropertyMethod, c) && + (readPropertyMethod.getReturnType() == + writePropertyParameters[0]) ); + } catch(Exception e) { + // ignore. this means we didn't find a corresponding get property. + } + + return foundReadProperty; + } + + private boolean readHasCorrespondingIsProperty(Method readProperty, + Class c) + { + if (FOLLOW_RMIC) + return false ; + + String readPropertyMethodName = readProperty.getName(); + boolean foundIsProperty = false; + + try { + // Look for a valid corresponding Is property + String isPropertyMethodName = + readPropertyMethodName.replaceFirst(GET_PROPERTY_PREFIX, + IS_PROPERTY_PREFIX); + Method isPropertyMethod = c.getMethod( isPropertyMethodName, + new Class[] {}); + foundIsProperty = isPropertyAccessorMethod(isPropertyMethod, + c) ; + } catch(Exception e) { + // ignore. this means we didn't find a corresponding Is property. + } + + return foundIsProperty; + } + + private boolean isHasCorrespondingReadProperty(Method readProperty, + Class c) + { + if (!FOLLOW_RMIC) + return false ; + + String readPropertyMethodName = readProperty.getName(); + boolean foundIsProperty = false; + + try { + // Look for a valid corresponding Read property + String isPropertyMethodName = + readPropertyMethodName.replaceFirst(IS_PROPERTY_PREFIX, + GET_PROPERTY_PREFIX); + Method isPropertyMethod = c.getMethod( isPropertyMethodName, + new Class[] {}); + foundIsProperty = isPropertyAccessorMethod(isPropertyMethod, + c) ; + } catch(Exception e) { + // ignore. this means we didn't find a corresponding read property. + } + + return foundIsProperty; + } + + public String getAttributeNameForProperty(String propertyName) { + String attributeName = null; + String prefix = null; + + if( propertyName.startsWith(GET_PROPERTY_PREFIX) ) { + prefix = GET_PROPERTY_PREFIX; + } else if( propertyName.startsWith(SET_PROPERTY_PREFIX) ) { + prefix = SET_PROPERTY_PREFIX; + } else if( propertyName.startsWith(IS_PROPERTY_PREFIX) ) { + prefix = IS_PROPERTY_PREFIX; + } + + if( (prefix != null) && (prefix.length() < propertyName.length()) ) { + String remainder = propertyName.substring(prefix.length()); + if( (remainder.length() >= 2) && + Character.isUpperCase(remainder.charAt(0)) && + Character.isUpperCase(remainder.charAt(1)) ) { + // don't set the first letter to lower-case if the + // first two are upper-case + attributeName = remainder; + } else { + attributeName = Character.toLowerCase(remainder.charAt(0)) + + remainder.substring(1); + } + } + + return attributeName; + } + + /** + * Return IDL Type name for primitive types as defined in + * Section 1.3.3 of Java2IDL spec or null if not a primitive type. + */ + public IDLType getPrimitiveIDLTypeMapping(Class c) { + + if( c == null ) { + throw new IllegalArgumentException(); + } + + if( c.isPrimitive() ) { + if( c == Void.TYPE ) { + return new IDLType( c, "void" ) ; + } else if( c == Boolean.TYPE ) { + return new IDLType( c, "boolean" ) ; + } else if( c == Character.TYPE ) { + return new IDLType( c, "wchar" ) ; + } else if( c == Byte.TYPE ) { + return new IDLType( c, "octet" ) ; + } else if( c == Short.TYPE ) { + return new IDLType( c, "short" ) ; + } else if( c == Integer.TYPE ) { + return new IDLType( c, "long" ) ; + } else if( c == Long.TYPE ) { + return new IDLType( c, "long_long" ) ; + } else if( c == Float.TYPE ) { + return new IDLType( c, "float" ) ; + } else if( c == Double.TYPE ) { + return new IDLType( c, "double" ) ; + } + } + + return null; + } + + /** + * Return IDL Type name for special case type mappings as defined in + * Table 1-1 of Java2IDL spec or null if given class is not a special + * type. + */ + public IDLType getSpecialCaseIDLTypeMapping(Class c) { + + if( c == null ) { + throw new IllegalArgumentException(); + } + + if( c == java.lang.Object.class ) { + return new IDLType( c, new String[] { "java", "lang" }, + "Object" ) ; + } else if( c == java.lang.String.class ) { + return new IDLType( c, new String[] { "CORBA" }, + "WStringValue" ) ; + } else if( c == java.lang.Class.class ) { + return new IDLType( c, new String[] { "javax", "rmi", "CORBA" }, + "ClassDesc" ) ; + } else if( c == java.io.Serializable.class ) { + return new IDLType( c, new String[] { "java", "io" }, + "Serializable" ) ; + } else if( c == java.io.Externalizable.class ) { + return new IDLType( c, new String[] { "java", "io" }, + "Externalizable" ) ; + } else if( c == java.rmi.Remote.class ) { + return new IDLType( c, new String[] { "java", "rmi" }, + "Remote" ) ; + } else if( c == org.omg.CORBA.Object.class ) { + return new IDLType( c, "Object" ) ; + } else { + return null; + } + } + + /** + * Implements 1.2.3 #2 and #4 + */ + private void validateExceptions(Method method) throws IDLTypeException { + + Class[] exceptions = method.getExceptionTypes(); + + boolean declaresRemoteExceptionOrSuperClass = false; + + // Section 1.2.3, #2 + for(int eIndex = 0; eIndex < exceptions.length; eIndex++) { + Class exception = exceptions[eIndex]; + if( isRemoteExceptionOrSuperClass(exception) ) { + declaresRemoteExceptionOrSuperClass = true; + break; + } + } + + if( !declaresRemoteExceptionOrSuperClass ) { + String msg = "Method '" + method + "' must throw at least one " + + "exception of type java.rmi.RemoteException or one of its " + + "super-classes"; + throw new IDLTypeException(msg); + } + + // Section 1.2.3, #4 + // See also bug 4972402 + // For all exceptions E in exceptions, + // (isCheckedException(E) => (isValue(E) || RemoteException.isAssignableFrom( E ) ) + for(int eIndex = 0; eIndex < exceptions.length; eIndex++) { + Class exception = exceptions[eIndex]; + + if (isCheckedException(exception) && !isValue(exception) && + !isRemoteException(exception)) + { + String msg = "Exception '" + exception + "' on method '" + + method + "' is not a allowed RMI/IIOP exception type"; + throw new IDLTypeException(msg); + } + } + + return; + } + + /** + * Returns true if the method's throw clause conforms to the exception + * restrictions for properties as defined in Section 1.3.4.3 of + * Java2IDL spec. This means that for all exceptions E declared on the + * method, E isChecked => RemoteException.isAssignableFrom( E ). + */ + private boolean validPropertyExceptions(Method method) + { + Class[] exceptions = method.getExceptionTypes(); + + for(int eIndex = 0; eIndex < exceptions.length; eIndex++) { + Class exception = exceptions[eIndex]; + + if (isCheckedException(exception) && !isRemoteException(exception)) + return false ; + } + + return true; + } + + /** + * Implements Section 1.2.3, #2. + */ + private boolean isRemoteExceptionOrSuperClass(Class c) { + return + ((c == java.rmi.RemoteException.class) || + (c == java.io.IOException.class) || + (c == java.lang.Exception.class) || + (c == java.lang.Throwable.class)); + } + + /** + * Implements Section 1.2.3, #5. + */ + private void validateDirectInterfaces(Class c) throws IDLTypeException { + + Class[] directInterfaces = c.getInterfaces(); + + if( directInterfaces.length < 2 ) { + return; + } + + Set allMethodNames = new HashSet(); + Set currentMethodNames = new HashSet(); + + for(int i = 0; i < directInterfaces.length; i++) { + Class next = directInterfaces[i]; + Method[] methods = next.getMethods(); + + // Comparison is based on method names only. First collect + // all methods from current interface, eliminating duplicate + // names. + currentMethodNames.clear(); + for(int m = 0; m < methods.length; m++) { + currentMethodNames.add(methods[m].getName()); + } + + // Now check each method against list of all unique method + // names processed so far. + for(Iterator iter=currentMethodNames.iterator(); iter.hasNext();) { + String methodName = (String) iter.next(); + if( allMethodNames.contains(methodName) ) { + String msg = "Class " + c + " inherits method " + + methodName + " from multiple direct interfaces."; + throw new IDLTypeException(msg); + } else { + allMethodNames.add(methodName); + } + } + } + + return; + } + + /** + * Implements 1.2.3 #6 + */ + private void validateConstants(final Class c) + throws IDLTypeException { + + Field[] fields = null; + + try { + fields = (Field[]) + java.security.AccessController.doPrivileged + (new java.security.PrivilegedExceptionAction() { + public java.lang.Object run() throws Exception { + return c.getFields(); + } + }); + } catch(java.security.PrivilegedActionException pae) { + IDLTypeException ite = new IDLTypeException(); + ite.initCause(pae); + throw ite; + } + + for(int i = 0; i < fields.length; i++) { + Field next = fields[i]; + Class fieldType = next.getType(); + if( (fieldType != java.lang.String.class) && + !isPrimitive(fieldType) ) { + String msg = "Constant field '" + next.getName() + + "' in class '" + next.getDeclaringClass().getName() + + "' has invalid type' " + next.getType() + "'. Constants" + + " in RMI/IIOP interfaces can only have primitive" + + " types and java.lang.String types."; + throw new IDLTypeException(msg); + } + } + + + return; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/InvocationHandlerFactoryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/InvocationHandlerFactoryImpl.java new file mode 100644 index 000000000..b9595351d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/InvocationHandlerFactoryImpl.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.lang.reflect.InvocationHandler ; +import java.lang.reflect.Proxy ; + + +import java.io.ObjectStreamException ; +import java.io.Serializable ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.DynamicStub ; +import org.glassfish.pfl.basic.proxy.CompositeInvocationHandler; +import org.glassfish.pfl.basic.proxy.CompositeInvocationHandlerImpl; +import org.glassfish.pfl.basic.proxy.DelegateInvocationHandlerImpl; +import org.glassfish.pfl.basic.proxy.InvocationHandlerFactory; +import org.glassfish.pfl.basic.proxy.LinkedInvocationHandler; + +public class InvocationHandlerFactoryImpl implements InvocationHandlerFactory +{ + private final PresentationManager.ClassData classData ; + private final PresentationManager pm ; + private Class[] proxyInterfaces ; + + public InvocationHandlerFactoryImpl( PresentationManager pm, + PresentationManager.ClassData classData ) + { + this.classData = classData ; + this.pm = pm ; + + Class[] remoteInterfaces = + classData.getIDLNameTranslator().getInterfaces() ; + proxyInterfaces = new Class[ remoteInterfaces.length + 1 ] ; + System.arraycopy(remoteInterfaces, 0, proxyInterfaces, 0, + remoteInterfaces.length); + + proxyInterfaces[remoteInterfaces.length] = DynamicStub.class ; + } + + private static class CustomCompositeInvocationHandlerImpl extends + CompositeInvocationHandlerImpl implements LinkedInvocationHandler, + Serializable + { + private transient DynamicStub stub ; + + public void setProxy( Proxy proxy ) + { + if (proxy instanceof DynamicStub) { + ((DynamicStubImpl)stub).setSelf( (DynamicStub)proxy ) ; + } else { + throw new RuntimeException( + "Proxy not instance of DynamicStub" ) ; + } + } + + public Proxy getProxy() + { + return (Proxy)((DynamicStubImpl)stub).getSelf() ; + } + + public CustomCompositeInvocationHandlerImpl( DynamicStub stub ) + { + this.stub = stub ; + } + + /** Return the stub, which will actually be written to the stream. + * It will be custom marshaled, with the actual writing done in + * StubIORImpl. There is a corresponding readResolve method on + * DynamicStubImpl which will re-create the full invocation + * handler on read, and return the invocation handler on the + * readResolve method. + */ + public Object writeReplace() throws ObjectStreamException + { + return stub ; + } + } + + public InvocationHandler getInvocationHandler() + { + final DynamicStub stub = new DynamicStubImpl( + classData.getTypeIds() ) ; + + return getInvocationHandler( stub ) ; + } + + // This is also used in DynamicStubImpl to implement readResolve. + InvocationHandler getInvocationHandler( DynamicStub stub ) + { + // Create an invocation handler for the methods defined on DynamicStub, + // which extends org.omg.CORBA.Object. This handler delegates all + // calls directly to a DynamicStubImpl, which extends + // org.omg.CORBA.portable.ObjectImpl. + InvocationHandler dynamicStubHandler = + DelegateInvocationHandlerImpl.create( stub ) ; + + // Create an invocation handler that handles any remote interface + // methods. + InvocationHandler stubMethodHandler = new StubInvocationHandlerImpl( + pm, classData, stub ) ; + + // Create a composite handler that handles the DynamicStub interface + // as well as the remote interfaces. + final CompositeInvocationHandler handler = + new CustomCompositeInvocationHandlerImpl( stub ) ; + handler.addInvocationHandler( DynamicStub.class, + dynamicStubHandler ) ; + handler.addInvocationHandler( org.omg.CORBA.Object.class, + dynamicStubHandler ) ; + handler.addInvocationHandler( Object.class, + dynamicStubHandler ) ; + + // If the method passed to invoke is not from DynamicStub or its superclasses, + // it must be from an implemented interface, so we just handle + // all of these with the stubMethodHandler. This used to be + // done be adding explicit entries for stubMethodHandler for + // each remote interface, but that does not work correctly + // for abstract interfaces, since the graph analysis ignores + // abstract interfaces in order to compute the type ids + // correctly (see PresentationManagerImpl.NodeImpl.getChildren). + // Rather than produce more graph traversal code to handle this + // problem, we simply use a default. + // This also points to a possible optimization: just use explict + // checks for the three special classes, rather than a general + // table lookup that usually fails. + handler.setDefaultHandler( stubMethodHandler ) ; + + return handler ; + } + + public Class[] getProxyInterfaces() + { + return proxyInterfaces ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/JNDIStateFactoryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/JNDIStateFactoryImpl.java new file mode 100644 index 000000000..ca77a26af --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/JNDIStateFactoryImpl.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; + +import javax.naming.ConfigurationException; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.spi.StateFactory; +import javax.rmi.PortableRemoteObject; +import java.lang.reflect.Field; +import java.rmi.Remote; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Hashtable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +// This creates a dependendcy on the implementation +// of the CosNaming service provider. + +/** + * StateFactory that turns java.rmi.Remote objects to org.omg.CORBA.Object. + * This version works either with standard RMI-IIOP or Dynamic RMI-IIOP. + * + * @author Ken Cavanaugh + */ + +public class JNDIStateFactoryImpl implements StateFactory { + + @SuppressWarnings("WeakerAccess") + public JNDIStateFactoryImpl() { } + + /** + * 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 orig or null. + * @exception ConfigurationException If the CORBA object cannot be obtained + * due to configuration problems + * @exception 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) { + return orig; + } + + if (!(orig instanceof Remote)) { + return null; + } + + ORB orb = getORB( ctx ) ; + if (orb == null) { + // Wrong kind of context, so just give up and let another StateFactory + // try to satisfy getStateToBind. + return null ; + } + + Remote stub; + + try { + stub = PortableRemoteObject.toStub( (Remote)orig ) ; + } catch (Exception exc) { + Exceptions.self.noStub( exc ) ; + // Wrong sort of object: just return null to allow another StateFactory + // to handle this. This can happen easily because this StateFactory + // is specified for the application, not the service context provider. + return null ; + } + + if (StubAdapter.isStub( stub )) { + try { + StubAdapter.connect( stub, orb ) ; + } catch (Exception exc) { + Exceptions.self.couldNotConnect( exc ) ; + + if (!(exc instanceof java.rmi.RemoteException)) { + // Wrong sort of object: just return null to allow another StateFactory + // to handle this call. + return null ; + } + + // ignore RemoteException because stub might have already + // been connected + } + } + + return stub ; + } + + // This is necessary because the _orb field is package private in + // com.sun.jndi.cosnaming.CNCtx. This is not an ideal solution. + // The best solution for our ORB is to change the CosNaming provider + // to use the StubAdapter. But this has problems as well, because + // other vendors may use the CosNaming provider with a different ORB + // entirely. + private ORB getORB( Context ctx ) { + try { + return (ORB) getOrbField(ctx).get( ctx ) ; + } catch (Exception exc) { + Exceptions.self.couldNotGetORB( exc, ctx ); + return null; + } + } + + private ConcurrentMap, Field> orbFields = new ConcurrentHashMap<>(); + + private Field getOrbField(Context ctx) { + Field orbField = orbFields.get(ctx.getClass()); + if (orbField != null) return orbField; + + orbField = AccessController.doPrivileged((PrivilegedAction) () -> getField(ctx.getClass(), "_orb")); + + orbFields.put(ctx.getClass(), orbField); + return orbField; + } + + private Field getField(Class aClass, String fieldName) { + try { + Field field = aClass.getDeclaredField(fieldName); + field.setAccessible(true); + return field; + } catch (NoSuchFieldException e) { + if (aClass.getSuperclass() == null) + return null; + else + return getField(aClass.getSuperclass(), fieldName); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/PresentationManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/PresentationManagerImpl.java new file mode 100644 index 000000000..254812371 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/PresentationManagerImpl.java @@ -0,0 +1,399 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.io.PrintStream ; + +import java.util.Map ; +import java.util.HashMap ; +import java.util.Set ; +import java.util.HashSet ; +import java.util.List ; +import java.util.ArrayList ; + +import java.lang.reflect.Method ; + +import java.rmi.Remote ; + +import javax.rmi.CORBA.Tie ; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; + +import com.sun.corba.ee.spi.presentation.rmi.IDLNameTranslator ; +import com.sun.corba.ee.spi.presentation.rmi.DynamicMethodMarshaller ; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.impl.util.RepositoryId ; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; +import org.glassfish.pfl.basic.concurrent.WeakCache; +import org.glassfish.pfl.basic.graph.Graph ; +import org.glassfish.pfl.basic.graph.GraphImpl ; +import org.glassfish.pfl.basic.graph.Node ; +import org.glassfish.pfl.basic.graph.NodeData ; +import org.glassfish.pfl.basic.proxy.InvocationHandlerFactory; + +public final class PresentationManagerImpl implements PresentationManager +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private WeakCache,ClassData> classToClassData ; + private WeakCache methodToDMM ; + private PresentationManager.StubFactoryFactory staticStubFactoryFactory ; + private PresentationManager.StubFactoryFactory dynamicStubFactoryFactory ; + private boolean useDynamicStubs ; + private boolean debug ; + private PrintStream ps ; + + public PresentationManagerImpl( boolean useDynamicStubs ) + { + this.useDynamicStubs = useDynamicStubs ; + + classToClassData = new WeakCache,ClassData>() { + @Override + protected ClassData lookup(Class key) { + return new ClassDataImpl( key ) ; + } + } ; + + methodToDMM = new WeakCache() { + @Override + protected DynamicMethodMarshaller lookup(Method key) { + return new DynamicMethodMarshallerImpl( key ) ; + } + } ; + } + +//////////////////////////////////////////////////////////////////////////////// +// PresentationManager interface +//////////////////////////////////////////////////////////////////////////////// + + public synchronized DynamicMethodMarshaller getDynamicMethodMarshaller( + Method method ) + { + if (method == null) { + return null; + } + + return methodToDMM.get(method) ; + } + + public synchronized ClassData getClassData( Class cls ) + { + return classToClassData.get(cls) ; + } + + private class ClassDataImpl implements PresentationManager.ClassData + { + private Class cls ; + private IDLNameTranslator nameTranslator ; + private String[] typeIds ; + private InvocationHandlerFactory ihfactory ; + private Map dictionary ; + + ClassDataImpl( Class cls ) { + this.cls = cls ; + Graph gr = new GraphImpl() ; + NodeImpl root = new NodeImpl( cls ) ; + Set rootSet = getRootSet( cls, root, gr ) ; + + // At this point, rootSet contains those remote interfaces + // that are not related by inheritance, and gr contains + // all reachable remote interfaces. + + Class[] interfaces = getInterfaces( rootSet ) ; + nameTranslator = IDLNameTranslatorImpl.get( interfaces ) ; + typeIds = makeTypeIds( root, gr, rootSet ) ; + ihfactory = new InvocationHandlerFactoryImpl( + PresentationManagerImpl.this, this ) ; + dictionary = new HashMap() ; + } + + public Class getMyClass() + { + return cls ; + } + + public IDLNameTranslator getIDLNameTranslator() + { + return nameTranslator ; + } + + public String[] getTypeIds() + { + return typeIds.clone() ; + } + + public InvocationHandlerFactory getInvocationHandlerFactory() + { + return ihfactory ; + } + + public Map getDictionary() + { + return dictionary ; + } + } + + public PresentationManager.StubFactoryFactory getStubFactoryFactory( + boolean isDynamic ) + { + if (isDynamic) { + return getDynamicStubFactoryFactory(); + } else { + return getStaticStubFactoryFactory(); + } + } + + @Override + public StubFactoryFactory getStaticStubFactoryFactory() { + return staticStubFactoryFactory; + } + + @Override + public StubFactoryFactory getDynamicStubFactoryFactory() { + return dynamicStubFactoryFactory; + } + + + /** Register the dynamic StubFactoryFactory. Note that + * a dynamic StubFactoryFactory is optional. + * @param sff + */ + public void setStaticStubFactoryFactory(StubFactoryFactory sff) { + staticStubFactoryFactory = sff; + } + + /** Register the static StubFactoryFactory. Note that + * a static StubFactoryFactory is always required for IDL. + * @param sff + */ + public void setDynamicStubFactoryFactory(StubFactoryFactory sff) { + dynamicStubFactoryFactory = sff; + } + + public Tie getTie() + { + return dynamicStubFactoryFactory.getTie( null ) ; + } + + public String getRepositoryId( java.rmi.Remote impl ) + { + // Get an empty reflective Tie. + Tie tie = getTie() ; + + // Setting the target causes the ReflectiveTieImpl to + // compute all of the required repo ID information. + tie.setTarget( impl ) ; + + return Servant.class.cast( tie )._all_interfaces( + (POA)null, (byte[])null)[0] ; + } + + public boolean useDynamicStubs() + { + return useDynamicStubs ; + } + + public void flushClass( final Class cls ) + { + classToClassData.remove( cls ) ; + + Method[] methods = (Method[])AccessController.doPrivileged( + new PrivilegedAction() { + public Object run() { + return cls.getMethods() ; + } + } + ) ; + + for( int ctr=0; ctr getRootSet( Class target, NodeImpl root, + Graph gr ) + { + Set rootSet = null ; + + if (ClassInfoCache.get(target).isInterface()) { + gr.add( root ) ; + rootSet = gr.getRoots() ; // rootSet just contains root here + } else { + // Use this class and its superclasses (not Object) as initial roots + Class superclass = target ; + Set initialRootSet = new HashSet() ; + while ((superclass != null) && !superclass.equals( Object.class )) { + NodeImpl node = new NodeImpl( superclass ) ; + gr.add( node ) ; + initialRootSet.add( node ) ; + superclass = superclass.getSuperclass() ; + } + + // Expand all nodes into the graph + gr.getRoots() ; + + // remove the roots and find roots again + gr.removeAll( initialRootSet ) ; + rootSet = gr.getRoots() ; + } + + return rootSet ; + } + + private Class[] getInterfaces( Set roots ) + { + int ctr = 0 ; + Class[] classes = new Class[ roots.size() ] ; + for (NodeImpl node : roots) { + classes[ctr] = node.getInterface() ; + ctr++ ; + } + + return classes ; + } + + private String[] makeTypeIds( NodeImpl root, Graph gr, + Set rootSet ) + { + Set nonRootSet = new HashSet( gr ) ; + nonRootSet.removeAll( rootSet ) ; + + // Handle the case of a remote reference that only implements + // java.rmi.Remote. + if (rootSet.isEmpty()) { + return new String[]{""}; + } + + // List for the typeids + List result = new ArrayList() ; + + if (rootSet.size() > 1) { + // If the rootSet has more than one element, we must + // put the type id of the implementation class first. + // Root represents the implementation class here. + result.add( root.getTypeId() ) ; + } + + addNodes( result, rootSet ) ; + addNodes( result, nonRootSet ) ; + + return result.toArray(new String[result.size()]) ; + } + + private void addNodes( List resultList, Set nodeSet ) + { + for (NodeImpl node : nodeSet) { + String typeId = node.getTypeId() ; + resultList.add( typeId ) ; + } + } + + private static class NodeImpl implements Node + { + private Class interf ; + + public Class getInterface() + { + return interf ; + } + + NodeImpl( Class interf ) + { + this.interf = interf ; + } + + public String getTypeId() + { + return RepositoryId.createForJavaType( interf ) ; + // return "RMI:" + interf.getName() + ":0000000000000000" ; + } + + public Set getChildren() + { + Set result = new HashSet() ; + Class[] interfaces = interf.getInterfaces() ; + for (int ctr=0; ctr cls = interfaces[ctr] ; + ClassInfoCache.ClassInfo cinfo = + ClassInfoCache.get( cls ) ; + if (cinfo.isARemote(cls) && + !Remote.class.equals(cls)) { + result.add(new NodeImpl(cls)); + } + } + + return result ; + } + + @Override + public String toString() + { + return "NodeImpl[" + interf + "]" ; + } + + @Override + public int hashCode() + { + return interf.hashCode() ; + } + + @Override + public boolean equals( Object obj ) + { + if (this == obj) { + return true; + } + + if (!(obj instanceof NodeImpl)) { + return false; + } + + NodeImpl other = (NodeImpl)obj ; + + return other.getInterface().equals( interf ) ; + } + } + + /** Turn on internal debugging flags, which dump information + * about stub code generation to the PrintStream. + * @param ps Output stream. + */ + public void enableDebug( PrintStream ps ) { + this.debug = true ; + this.ps = ps ; + } + + public void disableDebug() { + this.debug = false ; + this.ps = null ; + } + + public boolean getDebug() { + return debug ; + } + + public PrintStream getPrintStream() { + return ps ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ReflectiveTie.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ReflectiveTie.java new file mode 100644 index 000000000..485f45b1d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/ReflectiveTie.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.rmi.Remote; + +import javax.rmi.CORBA.Tie; + +import java.lang.reflect.Method ; +import java.lang.reflect.InvocationTargetException ; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults ; +import com.sun.corba.ee.spi.presentation.rmi.DynamicMethodMarshaller ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import org.glassfish.pfl.basic.proxy.DynamicAccessPermission ; + +public final class ReflectiveTie extends Servant implements Tie +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private Remote target = null ; + private PresentationManager pm ; + private PresentationManager.ClassData classData = null ; + + public ReflectiveTie( PresentationManager pm ) + { + if (!PresentationDefaults.inAppServer()) { + SecurityManager s = System.getSecurityManager(); + if (s != null) { + s.checkPermission(new DynamicAccessPermission("access")); + } + } + + this.pm = pm ; + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, + byte[] objectId) + { + return classData.getTypeIds() ; + } + + public void setTarget(Remote target) + { + this.target = target; + + if (target == null) { + classData = null ; + } else { + Class targetClass = target.getClass() ; + classData = pm.getClassData( targetClass ) ; + } + } + + public Remote getTarget() + { + return target; + } + + public org.omg.CORBA.Object thisObject() + { + return _this_object(); + } + + public void deactivate() + { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + } catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + // ignore + } catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + // ignore + } catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + // ignore + } + } + + public org.omg.CORBA.ORB orb() { + return _orb(); + } + + public void orb(org.omg.CORBA.ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } catch (ClassCastException e) { + throw wrapper.badOrbForServant( e ) ; + } + } + + public Object dispatchToMethod( Method javaMethod, Remote target, Object[] args ) + throws InvocationTargetException { + + try { + return javaMethod.invoke( target, args ) ; + } catch (IllegalAccessException ex) { + throw wrapper.invocationErrorInReflectiveTie( ex, + javaMethod.getName(), + javaMethod.getDeclaringClass().getName() ) ; + } catch (IllegalArgumentException ex) { + throw wrapper.invocationErrorInReflectiveTie( ex, + javaMethod.getName(), + javaMethod.getDeclaringClass().getName() ) ; + } + } + + public org.omg.CORBA.portable.OutputStream _invoke(String method, + org.omg.CORBA.portable.InputStream _in, ResponseHandler reply) + { + Method javaMethod = null ; + DynamicMethodMarshaller dmm = null; + + try { + InputStream in = (InputStream) _in; + + javaMethod = classData.getIDLNameTranslator().getMethod( method ) ; + if (javaMethod == null) + throw wrapper.methodNotFoundInTie( method, + target.getClass().getName() ) ; + + dmm = pm.getDynamicMethodMarshaller( javaMethod ) ; + + Object[] args = dmm.readArguments( in ) ; + + Object result = dispatchToMethod( javaMethod, target, args ) ; + + OutputStream os = (OutputStream)reply.createReply() ; + + dmm.writeResult( os, result ) ; + + return os ; + } catch (InvocationTargetException ex) { + // Unwrap the actual exception so that it can be wrapped by an + // UnknownException or thrown if it is a system exception. + // This is expected in the server dispatcher code. + Throwable thr = ex.getCause() ; + if (thr instanceof SystemException) + throw (SystemException)thr ; + else if ((thr instanceof Exception) && + dmm.isDeclaredException( thr )) { + OutputStream os = (OutputStream)reply.createExceptionReply() ; + dmm.writeException( os, (Exception)thr ) ; + return os ; + } else + throw new UnknownException( thr ) ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubConnectImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubConnectImpl.java new file mode 100644 index 000000000..9860fe277 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubConnectImpl.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import java.rmi.RemoteException; + +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_INV_ORDER; + +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.Delegate; + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; + +import com.sun.corba.ee.impl.util.Utility; + +import com.sun.corba.ee.impl.ior.StubIORImpl ; + +import com.sun.corba.ee.spi.logging.UtilSystemException ; + +import com.sun.corba.ee.impl.corba.CORBAObjectImpl ; + +public abstract class StubConnectImpl +{ + private static UtilSystemException wrapper = + UtilSystemException.self ; + + /** Connect the stub to the orb if necessary. + * @param ior The StubIORImpl for this stub (may be null) + * @param proxy The externally visible stub seen by the user (may be the same as stub) + * @param stub The stub implementation that extends ObjectImpl + * @param orb The ORB to which we connect the stub. + */ + public static StubIORImpl connect( StubIORImpl ior, org.omg.CORBA.Object proxy, + org.omg.CORBA.portable.ObjectImpl stub, ORB orb ) throws RemoteException + { + Delegate del = null ; + + try { + try { + del = StubAdapter.getDelegate( stub ); + + if (del.orb(stub) != orb) + throw wrapper.connectWrongOrb() ; + } catch (org.omg.CORBA.BAD_OPERATION err) { + if (ior == null) { + // No IOR, can we get a Tie for this stub? + Tie tie = (javax.rmi.CORBA.Tie) Utility.getAndForgetTie(proxy); + if (tie == null) + throw wrapper.connectNoTie() ; + + // Is the tie already connected? If it is, check that it's + // connected to the same ORB, otherwise connect it. + ORB existingOrb = orb ; + try { + existingOrb = tie.orb(); + } catch (BAD_OPERATION exc) { + // Thrown when tie is an ObjectImpl and its delegate is not set. + tie.orb(orb); + } catch (BAD_INV_ORDER exc) { + // Thrown when tie is a Servant and its delegate is not set. + tie.orb(orb); + } + + if (existingOrb != orb) + throw wrapper.connectTieWrongOrb() ; + + // Get the delegate for the stub from the tie. + del = StubAdapter.getDelegate( tie ) ; + ObjectImpl objref = new CORBAObjectImpl() ; + objref._set_delegate( del ) ; + ior = new StubIORImpl( objref ) ; + } else { + // ior is initialized, so convert ior to an object, extract + // the delegate, and set it on ourself + del = ior.getDelegate( orb ) ; + } + + StubAdapter.setDelegate( stub, del ) ; + } + } catch (SystemException exc) { + throw new RemoteException("CORBA SystemException", exc ); + } + + return ior ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryBase.java new file mode 100644 index 000000000..da30d99c3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryBase.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import javax.rmi.CORBA.Tie ; + +import java.lang.reflect.InvocationHandler ; +import java.lang.reflect.Proxy ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.DynamicStub ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; + +public abstract class StubFactoryBase implements PresentationManager.StubFactory +{ + private String[] typeIds = null ; + + protected final PresentationManager.ClassData classData ; + + protected StubFactoryBase( PresentationManager.ClassData classData ) + { + this.classData = classData ; + } + + public synchronized String[] getTypeIds() + { + if (typeIds == null) { + if (classData == null) { + org.omg.CORBA.Object stub = makeStub() ; + typeIds = StubAdapter.getTypeIds( stub ) ; + } else { + typeIds = classData.getTypeIds() ; + } + } + + return typeIds ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryDynamicBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryDynamicBase.java new file mode 100644 index 000000000..d07081076 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryDynamicBase.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; + +import java.io.SerializablePermission; + +import com.sun.corba.ee.spi.misc.ORBClassLoader ; + +public abstract class StubFactoryDynamicBase extends StubFactoryBase +{ + protected final ClassLoader loader ; + + private static Void checkPermission() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new SerializablePermission( + "enableSubclassImplementation")); + } + + return null; + } + + private StubFactoryDynamicBase( Void unused, PresentationManager.ClassData classData, + ClassLoader loader ) + { + super( classData ) ; + + // this.loader must not be null, or the newProxyInstance call + // will fail. + if (loader == null) { + this.loader = ORBClassLoader.getClassLoader() ; + } else { + this.loader = loader ; + } + } + + public StubFactoryDynamicBase( PresentationManager.ClassData classData, + ClassLoader loader ) + { + this(checkPermission(), classData, loader); + } + + public abstract org.omg.CORBA.Object makeStub() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryBase.java new file mode 100644 index 000000000..a3362cd87 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryBase.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; + +import com.sun.corba.ee.impl.util.Utility ; + +public abstract class StubFactoryFactoryBase implements + PresentationManager.StubFactoryFactory +{ + /** + * Returns the stub classname for the given interface name. + * + * @param fullName fully qualified name remote class + */ + public String getStubName(String fullName) + { + return Utility.stubName( fullName ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryDynamicBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryDynamicBase.java new file mode 100644 index 000000000..a58c30e21 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryDynamicBase.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import javax.rmi.CORBA.Tie ; + +import org.omg.CORBA.CompletionStatus; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; + +public abstract class StubFactoryFactoryDynamicBase extends + StubFactoryFactoryBase +{ + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public StubFactoryFactoryDynamicBase() { + } + + public PresentationManager.StubFactory createStubFactory( + String className, boolean isIDLStub, String remoteCodeBase, + Class expectedClass, ClassLoader classLoader) + { + Class cls = null ; + + try { + cls = Util.getInstance().loadClass( className, remoteCodeBase, + classLoader ) ; + } catch (ClassNotFoundException exc) { + throw wrapper.classNotFound3( exc, className ) ; + } + + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get(cls) ; + PresentationManager pm = ORB.getPresentationManager() ; + + if (cinfo.isAIDLEntity(cls) && !cinfo.isARemote(cls)) { + // IDL stubs must always use static factories. + PresentationManager.StubFactoryFactory sff = pm.getStaticStubFactoryFactory(); + return sff.createStubFactory( className, true, remoteCodeBase, expectedClass, classLoader ); + } else { + PresentationManager.ClassData classData = pm.getClassData( cls ) ; + return makeDynamicStubFactory( pm, classData, classLoader ) ; + } + } + + public abstract PresentationManager.StubFactory makeDynamicStubFactory( + PresentationManager pm, PresentationManager.ClassData classData, + ClassLoader classLoader ) ; + + public Tie getTie( Class cls ) + { + PresentationManager pm = ORB.getPresentationManager() ; + return new ReflectiveTie( pm ) ; + } + + public boolean createsDynamicStubs() + { + return true ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryStaticImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryStaticImpl.java new file mode 100644 index 000000000..8bf89f743 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryFactoryStaticImpl.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import javax.rmi.CORBA.Tie ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; + +import com.sun.corba.ee.impl.util.PackagePrefixChecker; +import com.sun.corba.ee.impl.util.Utility; + +import com.sun.corba.ee.spi.misc.ORBClassLoader; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +public class StubFactoryFactoryStaticImpl extends + StubFactoryFactoryBase +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public PresentationManager.StubFactory createStubFactory( + String className, boolean isIDLStub, String remoteCodeBase, Class + expectedClass, ClassLoader classLoader) + { + String stubName = null ; + + if (isIDLStub) { + stubName = Utility.idlStubName(className); + } else { + stubName = + Utility.stubNameForCompiler(className); + } + + ClassLoader expectedTypeClassLoader = + (expectedClass == null ? classLoader : + expectedClass.getClassLoader()); + + // The old code was optimized to try to guess which way to load classes + // first. The real stub class name could either be className or + // "org.omg.stub." + className. We will compute this as follows: + // If stubName starts with a "forbidden" package, try the prefixed + // version first, otherwise try the non-prefixed version first. + // In any case, try both forms if necessary. + + String firstStubName = stubName ; + String secondStubName = stubName ; + + if (PackagePrefixChecker.hasOffendingPrefix(stubName)) { + firstStubName = + PackagePrefixChecker.packagePrefix() + stubName; + } else { + secondStubName = + PackagePrefixChecker.packagePrefix() + stubName; + } + + Class clz = null; + + try { + clz = Util.getInstance().loadClass( firstStubName, remoteCodeBase, + expectedTypeClassLoader ) ; + } catch (ClassNotFoundException e1) { + // log only at FINE level + wrapper.classNotFound1( e1, firstStubName ) ; + try { + clz = Util.getInstance().loadClass( secondStubName, remoteCodeBase, + expectedTypeClassLoader ) ; + } catch (ClassNotFoundException e2) { + throw wrapper.classNotFound2( e2, secondStubName ) ; + } + } + + // XXX Is this step necessary, or should the Util.loadClass + // algorithm always produce a valid class if the setup is correct? + // Does the OMG standard algorithm need to be changed to include + // this step? + if ((clz == null) || + ((expectedClass != null) && !expectedClass.isAssignableFrom(clz))) { + try { + clz = ORBClassLoader.loadClass(className); + } catch (Exception exc) { + // XXX use framework + throw new IllegalStateException("Could not load class " + + stubName, exc) ; + } + } + + return new StubFactoryStaticImpl( clz ) ; + } + + public Tie getTie( Class cls ) + { + Class tieClass = null ; + String className = Utility.tieName(cls.getName()); + + // XXX log exceptions at FINE level + try { + try { + //_REVISIT_ The spec does not specify a loadingContext parameter for + //the following call. Would it be useful to pass one? + tieClass = Utility.loadClassForClass(className, Util.getInstance().getCodebase(cls), + null, cls, cls.getClassLoader()); + return (Tie) tieClass.newInstance(); + } catch (Exception err) { + tieClass = Utility.loadClassForClass( + PackagePrefixChecker.packagePrefix() + className, + Util.getInstance().getCodebase(cls), null, cls, cls.getClassLoader()); + return (Tie) tieClass.newInstance(); + } + } catch (Exception err) { + return null; + } + + } + + public boolean createsDynamicStubs() + { + return false ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryStaticImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryStaticImpl.java new file mode 100644 index 000000000..775a21fc3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubFactoryStaticImpl.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import java.lang.reflect.InvocationHandler ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; + +public class StubFactoryStaticImpl extends StubFactoryBase +{ + private Class stubClass ; + + public StubFactoryStaticImpl(Class cls) + { + super( null ) ; + this.stubClass = cls; + } + + public org.omg.CORBA.Object makeStub() + { + org.omg.CORBA.Object stub = null; + try { + stub = (org.omg.CORBA.Object) stubClass.newInstance(); + } catch (InstantiationException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + return stub ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubInvocationHandlerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubInvocationHandlerImpl.java new file mode 100644 index 000000000..cf35322c3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/StubInvocationHandlerImpl.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi ; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.presentation.rmi.DynamicMethodMarshaller; +import com.sun.corba.ee.spi.presentation.rmi.InvocationInterceptor; +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher; +import com.sun.corba.ee.spi.trace.IsLocal; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import org.glassfish.pfl.basic.proxy.DynamicAccessPermission; +import org.glassfish.pfl.basic.proxy.LinkedInvocationHandler; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.Delegate; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ServantObject; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.security.AccessController; +import java.security.PrivilegedAction; + +@IsLocal +public final class StubInvocationHandlerImpl implements LinkedInvocationHandler +{ + private transient PresentationManager.ClassData classData ; + private transient PresentationManager pm ; + private transient org.omg.CORBA.Object stub ; + private transient Proxy self ; + + public void setProxy( Proxy self ) + { + this.self = self ; + } + + public Proxy getProxy() + { + return self ; + } + + public StubInvocationHandlerImpl( PresentationManager pm, + PresentationManager.ClassData classData, org.omg.CORBA.Object stub ) + { + if (!PresentationDefaults.inAppServer()) { + SecurityManager s = System.getSecurityManager(); + if (s != null) { + s.checkPermission(new DynamicAccessPermission("access")); + } + } + + this.classData = classData ; + this.pm = pm ; + this.stub = stub ; + } + + @IsLocal + private boolean isLocal(Delegate delegate) + { + boolean result = false ; + if (delegate instanceof ClientDelegate) { + ClientDelegate cdel = (ClientDelegate)delegate ; + ContactInfoList cil = cdel.getContactInfoList() ; + LocalClientRequestDispatcher lcrd = + cil.getLocalClientRequestDispatcher() ; + result = lcrd.useLocalInvocation( null ) ; + } + + return result ; + } + + public Object invoke( Object proxy, final Method method, + Object[] args ) throws Throwable { + + Delegate delegate = null ; + try { + delegate = StubAdapter.getDelegate( stub ) ; + } catch (SystemException ex) { + throw Util.getInstance().mapSystemException(ex) ; + } + + org.omg.CORBA.ORB delORB = delegate.orb( stub ) ; + if (delORB instanceof ORB) { + ORB orb = (ORB)delORB ; + + InvocationInterceptor interceptor = orb.getInvocationInterceptor() ; + + try { + interceptor.preInvoke() ; + } catch (Exception exc) { + // XXX Should we log this? + } + + try { + return privateInvoke( delegate, proxy, method, args ) ; + } finally { + try { + interceptor.postInvoke() ; + } catch (Exception exc) { + // XXX Should we log this? + } + } + } else { + // Not our ORB: so handle without invocation interceptor. + return privateInvoke( delegate, proxy, method, args ) ; + } + } + + @InfoMethod + private void takingRemoteBranch() {} + + @InfoMethod + private void takingLocalBranch() {} + + /** Invoke the given method with the args and return the result. + * This may result in a remote invocation. + * @param proxy The proxy used for this class (null if not using java.lang.reflect.Proxy) + */ + @IsLocal + private Object privateInvoke( Delegate delegate, Object proxy, final Method method, + Object[] args ) throws Throwable + { + boolean retry; + do { + retry = false; + String giopMethodName = classData.getIDLNameTranslator(). + getIDLName( method ) ; + DynamicMethodMarshaller dmm = + pm.getDynamicMethodMarshaller( method ) ; + + if (!isLocal(delegate)) { + try { + takingRemoteBranch() ; + org.omg.CORBA_2_3.portable.InputStream in = null ; + try { + // create request + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + delegate.request( stub, giopMethodName, true); + // marshal arguments + dmm.writeArguments( out, args ) ; + // finish invocation + in = (org.omg.CORBA_2_3.portable.InputStream) + delegate.invoke( stub, out); + // unmarshal result + return dmm.readResult( in ) ; + } catch (ApplicationException ex) { + throw dmm.readException( ex ) ; + } catch (RemarshalException ex) { + //return privateInvoke( delegate, proxy, method, args ) ; + retry = true; + } finally { + delegate.releaseReply( stub, in ); + } + } catch (SystemException ex) { + throw Util.getInstance().mapSystemException(ex) ; + } + } else { + takingLocalBranch(); + org.omg.CORBA.ORB orb = delegate.orb( stub ) ; + ServantObject so = delegate.servant_preinvoke( stub, giopMethodName, + method.getDeclaringClass() ); + if (so == null) { + //return privateInvoke( delegate, proxy, method, args ) ; + retry = true; + continue; + } + + try { + Object[] copies = dmm.copyArguments( args, orb ) ; + + if (!method.isAccessible()) { + // Make sure that we can invoke a method from a normally + // inaccessible package, as this reflective class must always + // be able to invoke a non-public method. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + method.setAccessible( true ) ; + return null ; + } + } ) ; + } + + Object result = method.invoke( so.servant, copies ) ; + + return dmm.copyResult( result, orb ) ; + } catch (InvocationTargetException ex) { + Throwable mex = ex.getCause() ; + // mex should never be null, as null cannot be thrown + if (dmm.isDeclaredException( mex )) + throw mex ; + else + throw Util.getInstance().wrapException(mex); + } catch (Throwable thr) { + if (thr instanceof ThreadDeath) + throw thr; + + // This is not a user thrown exception from the + // method call, so don't copy it. This is either + // an error or a reflective invoke exception. + throw Util.getInstance().wrapException( thr ) ; + } finally { + delegate.servant_postinvoke( stub, so); + } + } + } while (retry); + return null; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/CodegenProxyCreator.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/CodegenProxyCreator.java new file mode 100644 index 000000000..44ae906f6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/CodegenProxyCreator.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi.codegen; + +import org.glassfish.pfl.dynamic.codegen.spi.Primitives; +import org.glassfish.pfl.dynamic.codegen.spi.Variable; +import org.glassfish.pfl.dynamic.codegen.spi.Expression; +import org.glassfish.pfl.basic.contain.Pair; +import org.glassfish.pfl.dynamic.codegen.spi.Utility; +import org.glassfish.pfl.dynamic.codegen.spi.MethodInfo; +import org.glassfish.pfl.dynamic.codegen.spi.Type; +import java.io.PrintStream ; + +import java.lang.reflect.Method ; + +import java.security.ProtectionDomain ; + +import java.util.Properties ; +import java.util.List ; +import java.util.ArrayList ; + +import static java.lang.reflect.Modifier.* ; + +import static org.glassfish.pfl.dynamic.codegen.spi.Wrapper.* ; + +/** Generate a proxy with a specified base class. + */ +public class CodegenProxyCreator { + private String className ; + private Type superClass ; + private List interfaces ; + private List methods ; + + private static final Properties debugProps = new Properties() ; + private static final Properties emptyProps = new Properties() ; + + static { + debugProps.setProperty( DUMP_AFTER_SETUP_VISITOR, "true" ) ; + debugProps.setProperty( TRACE_BYTE_CODE_GENERATION, "true" ) ; + debugProps.setProperty( USE_ASM_VERIFIER, "true" ) ; + } + + public CodegenProxyCreator( String className, Class sc, + Class[] interfaces, Method[] methods ) { + + this.className = className ; + this.superClass = Type.type( sc ) ; + + this.interfaces = new ArrayList() ; + for (Class cls : interfaces) { + this.interfaces.add( Type.type( cls ) ) ; + } + + this.methods = new ArrayList() ; + for (Method method : methods) { + this.methods.add( Utility.getMethodInfo( method ) ) ; + } + } + + /** Construct a generator for a proxy class + * that implements the given interfaces and extends superClass. + * superClass must satisfy the following requirements: + *
      + *
    1. It must have an accessible no args constructor
    2. + *
    3. It must have a method satisfying the signature + * Object invoke( int methodNumber, Object[] args ) throws Throwable + * + *
    4. + *
    5. The invoke method described above must be accessible + * to the generated class (generally either public or + * protected.
    6. + *
    + *

    + * Each method in methods is implemented by a method that: + *

      + *
    1. Creates an array sized to hold the args
    2. + *
    3. Wraps args of primitive type in the appropriate wrapper.
    4. + *
    5. Copies each arg or wrapper arg into the array.
    6. + *
    7. Calls invoke with a method number corresponding to the + * index of the method in methods. Note that the invoke implementation + * must use the same method array to figure out which method has been + * invoked.
    8. + *
    9. Return the result (if any), extracting values from wrappers + * as needed to handle a return value of a primitive type.
    10. + *
    + *

    + * Note that the generated methods ignore exceptions. + * It is assumed that the invoke method may throw any + * desired exception. + * @param className the name of the generated class + * @param superClassName the name of the class extends by the generated class + * @param interfaces the interfaces implemented by the generated class + * @param methods the methods that the generated class implements + */ + public Class create( ProtectionDomain pd, ClassLoader cl, + boolean debug, PrintStream ps ) { + + Pair nm = splitClassName( className ) ; + + _clear() ; + _setClassLoader( cl ) ; + _package( nm.first() ) ; + _class( PUBLIC, nm.second(), superClass, interfaces ) ; + + _constructor( PUBLIC ) ; + _body() ; + _expr(_super()); + _end() ; + + _method( PRIVATE, _Object(), "writeReplace" ) ; + _body() ; + _return(_call(_this(), "selfAsBaseClass" )) ; + _end() ; + + int ctr=0 ; + for (MethodInfo method : methods) + createMethod( ctr++, method ) ; + + _end() ; // of _class + + return _generate( cl, pd, debug ? debugProps : emptyProps, ps ) ; + } + + private static final Type objectArrayType = Type._array(_Object()) ; + + private static void createMethod( int mnum, MethodInfo method ) { + Type rtype = method.returnType() ; + _method( method.modifiers() & ~ABSTRACT, rtype, method.name()) ; + + List args = new ArrayList() ; + for (Variable var : method.arguments() ) + args.add( _arg( var.type(), var.ident() ) ) ; + + _body() ; + List wrappedArgs = new ArrayList() ; + for (Expression arg : args) { + wrappedArgs.add( Primitives.wrap( arg ) ) ; + } + + Expression invokeArgs = _define( objectArrayType, "args", + _new_array_init( _Object(), wrappedArgs ) ) ; + + // create expression to call the invoke method + Expression invokeExpression = _call( + _this(), "invoke", _const(mnum), invokeArgs ) ; + + // return result if non-void + if (rtype == _void()) { + _expr( invokeExpression ) ; + _return() ; + } else { + Expression resultExpr = _define( _Object(), "result", invokeExpression ) ; + + if (rtype != _Object()) { + if (rtype.isPrimitive()) { + // Must cast resultExpr to expected type, or unwrap won't work! + Type ctype = Primitives.getWrapperTypeForPrimitive( rtype ) ; + Expression cexpr = _cast( ctype, resultExpr ) ; + _return( Primitives.unwrap( cexpr ) ) ; + } else { + _return(_cast(rtype, resultExpr )) ; + } + } else { + _return( resultExpr ) ; + } + } + _end() ; // of method + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/CodegenStubBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/CodegenStubBase.java new file mode 100644 index 000000000..b9c941ec5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/CodegenStubBase.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi.codegen ; + +import java.io.ObjectInputStream ; +import java.io.IOException ; +import java.io.ObjectStreamException ; + +import java.lang.reflect.InvocationHandler ; +import java.lang.reflect.Method ; +import java.lang.reflect.Field ; + +import java.security.AccessController ; +import java.security.PrivilegedAction ; + +import javax.rmi.CORBA.Stub ; + + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.impl.util.JDKBridge ; +import com.sun.corba.ee.impl.util.RepositoryId ; +import com.sun.corba.ee.impl.ior.StubIORImpl ; +import com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl ; +import com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl ; + +public class CodegenStubBase extends Stub +{ + private transient String[] typeIds ; + private transient Method[] methods ; + private transient PresentationManager.ClassData classData ; + private transient InvocationHandler handler ; + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private Object readResolve( ) throws ObjectStreamException + { + // Note that we cannot use PRO.narrow here, because the + // delegate is not set by deserializing the stub. Only + // the IOR is set, because a deserialized stub is not connected + // to an ORB. + PresentationManager pm = ORB.getPresentationManager() ; + PresentationManager.StubFactoryFactory sff = pm.getDynamicStubFactoryFactory(); + PresentationManager.StubFactory sf = sff.createStubFactory( + classData.getMyClass().getName(), false, null, null, null ) ; + org.omg.CORBA.Object stub = sf.makeStub() ; + StubDelegateImpl stubSDI = getStubDelegateImpl( stub ) ; + StubDelegateImpl mySDI = getStubDelegateImpl( this ) ; + stubSDI.setIOR( mySDI.getIOR() ) ; + return stub ; + } + + // Get the StubDelegateImpl from the superclass. Unfortunately stubDelegate + // is private in javax.rmi.CORBA.Stub, and Stub must follow + // the OMG standard. So, we use reflection to get stubDelegate. + // We also need to handle the case where the stubDelegate has not + // been set yet. This reqires a call to the private method + // setDefaultDelegate. + // + private static StubDelegateImpl getStubDelegateImpl( + final org.omg.CORBA.Object stub ) + { + StubDelegateImpl sdi = getStubDelegateImplField( stub ) ; + if (sdi == null) { + setDefaultDelegate(stub); + } + sdi = getStubDelegateImplField( stub ) ; + return sdi ; + } + + private static StubDelegateImpl getStubDelegateImplField( + final org.omg.CORBA.Object stub ) + { + return (StubDelegateImpl)AccessController.doPrivileged( + new PrivilegedAction() { + public Object run() { + try { + Field fld = Stub.class.getDeclaredField( "stubDelegate" ) ; + fld.setAccessible( true ) ; + return fld.get( stub ) ; + } catch (Exception exc) { + throw wrapper.couldNotAccessStubDelegate() ; + } + } + } + ) ; + } + + private static Method setDefaultDelegateMethod = null ; + + private static void setDefaultDelegate( final org.omg.CORBA.Object stub ) + { + AccessController.doPrivileged( + new PrivilegedAction() { + public Object run() { + try { + if (setDefaultDelegateMethod == null) { + setDefaultDelegateMethod = + Stub.class.getDeclaredMethod( "setDefaultDelegate") ; + setDefaultDelegateMethod.setAccessible( true ) ; + } + + setDefaultDelegateMethod.invoke( stub ) ; + } catch (Exception exc) { + throw wrapper.couldNotAccessStubDelegate( exc ) ; + } + return null ; + } + } + ) ; + } + + private void readObject( ObjectInputStream stream ) throws + IOException, ClassNotFoundException + { + // Let the superclass do the read of the internal IOR, + // but we need to restore our transient fields. But + // let defaultReadObject do its normal processing. + stream.defaultReadObject() ; + + StubDelegateImpl sdi = getStubDelegateImpl( this ) ; + + StubIORImpl ior = sdi.getIOR() ; + String repositoryId = ior.getRepositoryId() ; + String cname = RepositoryId.cache.getId( repositoryId ).getClassName() ; + + Class cls = null ; + + try { + cls = JDKBridge.loadClass( cname, null, null ) ; + } catch (ClassNotFoundException exc) { + throw wrapper.couldNotLoadInterface( exc, cname ) ; + } + + PresentationManager pm = ORB.getPresentationManager() ; + classData = pm.getClassData( cls ) ; + + InvocationHandler handler = new StubInvocationHandlerImpl( pm, + classData, this ) ; + initialize( classData, handler ) ; + } + + public String[] _ids() + { + return typeIds.clone() ; + } + + /** Must be called to complete the initialization of the stub. + * Note that we have mutual dependence between the InvocationHandler + * and the Stub: the InvocationHandler needs the stub in order + * to get the delegate, and the Stub needs the InvocationHandler + * to perform an invocation. We resolve this dependency by + * constructing the Stub first, using the stub to construct the + * InvocationHandler, and then completing the initialization of + * the Stub by calling initialize. + */ + public void initialize( PresentationManager.ClassData classData, + InvocationHandler handler ) + { + this.classData = classData ; + this.handler = handler ; + typeIds = classData.getTypeIds() ; + methods = classData.getIDLNameTranslator().getMethods() ; + } + + // Needed in generated code: clone self (which is the generated class) + // as the base class. This is needed for a generated writeReplace method. + // This allows the readResolve method on this class to construct the + // appropriate codegen proxy when this class is deserialized. + protected Object selfAsBaseClass() + { + CodegenStubBase result = new CodegenStubBase() ; + StubAdapter.setDelegate( result, + StubAdapter.getDelegate( this )) ; + return result ; + } + + // Needed in generated code + protected Object invoke( int methodNumber, Object[] args ) throws Throwable + { + Method method = methods[methodNumber] ; + + // Pass null for the Proxy since we don't have one. + return handler.invoke( null, method, args ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/StubFactoryCodegenImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/StubFactoryCodegenImpl.java new file mode 100644 index 000000000..3482d7caa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/StubFactoryCodegenImpl.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi.codegen ; + +import java.util.Map ; + +import java.security.ProtectionDomain ; +import java.security.PrivilegedAction; +import java.security.PrivilegedExceptionAction; +import java.security.AccessController; + +import java.lang.reflect.InvocationHandler ; +import java.lang.reflect.Method ; + +import com.sun.corba.ee.impl.util.Utility ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.IDLNameTranslator ; + +import com.sun.corba.ee.impl.presentation.rmi.StubFactoryDynamicBase ; +import com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +public class StubFactoryCodegenImpl extends StubFactoryDynamicBase +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static final String CODEGEN_KEY = "CodegenStubClass" ; + private final PresentationManager pm ; + + public StubFactoryCodegenImpl( PresentationManager pm, + PresentationManager.ClassData classData, ClassLoader loader ) + { + super( classData, loader ) ; + this.pm = pm ; + } + + private Class getStubClass() + { + Class stubClass = null; + + // IMPORTANT: A get & put to classData's dictionary can occur + // by two or more threads in this method at the same + // time. Therefore, classData must be synchronized here. + + synchronized (classData) { + final Map dictionary = classData.getDictionary() ; + stubClass = (Class)dictionary.get( CODEGEN_KEY ) ; + if (stubClass == null) { + final IDLNameTranslator nt = classData.getIDLNameTranslator() ; + final Class theClass = classData.getMyClass() ; + final String stubClassName = Utility.dynamicStubName( + theClass.getName() ) ; + final Class baseClass = CodegenStubBase.class ; + final Class[] interfaces = nt.getInterfaces() ; + final Method[] methods = nt.getMethods() ; + + final ProtectionDomain pd = + AccessController.doPrivileged( + new PrivilegedAction() { + public ProtectionDomain run() { + return theClass.getProtectionDomain() ; + } + } + ) ; + + // Create a StubGenerator that generates this stub class + final CodegenProxyCreator creator = new CodegenProxyCreator( + stubClassName, baseClass, interfaces, methods ) ; + + // Invoke creator in a doPrivileged block if there is a security + // manager installed. + if (System.getSecurityManager() == null) { + stubClass = creator.create( pd, loader, pm.getDebug(), + pm.getPrintStream() ) ; + } else { + stubClass = AccessController.doPrivileged( + new PrivilegedAction>() { + public Class run() { + return creator.create( pd, loader, pm.getDebug(), + pm.getPrintStream() ) ; + } + } + ) ; + } + + dictionary.put( CODEGEN_KEY, stubClass ) ; + } + } + + return stubClass ; + } + + public org.omg.CORBA.Object makeStub() + { + final Class stubClass = getStubClass( ) ; + + CodegenStubBase stub = null ; + + try { + // Added doPriv for issue 778 + stub = AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public CodegenStubBase run() throws Exception { + return CodegenStubBase.class.cast( + stubClass.newInstance() ) ; + } + } + ) ; + } catch (Exception exc) { + wrapper.couldNotInstantiateStubClass( exc, + stubClass.getName() ) ; + } + + InvocationHandler handler = new StubInvocationHandlerImpl( pm, + classData, stub ) ; + + stub.initialize( classData, handler ) ; + + return stub ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/StubFactoryFactoryCodegenImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/StubFactoryFactoryCodegenImpl.java new file mode 100644 index 000000000..de34d0aa8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/codegen/StubFactoryFactoryCodegenImpl.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi.codegen ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; + +import com.sun.corba.ee.impl.presentation.rmi.StubFactoryFactoryDynamicBase ; + +public class StubFactoryFactoryCodegenImpl extends StubFactoryFactoryDynamicBase +{ + public StubFactoryFactoryCodegenImpl() + { + super() ; + } + + public PresentationManager.StubFactory makeDynamicStubFactory( + PresentationManager pm, PresentationManager.ClassData classData, + ClassLoader classLoader ) + { + return new StubFactoryCodegenImpl( pm, classData, classLoader ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/jndi.properties b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/jndi.properties new file mode 100644 index 000000000..4653997bf --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/jndi.properties @@ -0,0 +1,13 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Required to add a javax.naming.spi.StateFactory for CosNaming that +# supports dynamic RMI-IIOP. +java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/proxy/StubFactoryFactoryProxyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/proxy/StubFactoryFactoryProxyImpl.java new file mode 100644 index 000000000..10d8efba7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/proxy/StubFactoryFactoryProxyImpl.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi.proxy; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import com.sun.corba.ee.impl.presentation.rmi.*; +import com.sun.corba.ee.impl.presentation.rmi.proxy.StubFactoryProxyImpl; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager.StubFactory; + +public class StubFactoryFactoryProxyImpl extends StubFactoryFactoryDynamicBase +{ + public PresentationManager.StubFactory makeDynamicStubFactory( + PresentationManager pm, final PresentationManager.ClassData classData, + final ClassLoader classLoader ) + { + return AccessController.doPrivileged( + new PrivilegedAction() { + + @Override + public StubFactory run() { + return new StubFactoryProxyImpl( classData, classLoader ) ; + } + + }); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/proxy/StubFactoryProxyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/proxy/StubFactoryProxyImpl.java new file mode 100644 index 000000000..f3c4d8caf --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/presentation/rmi/proxy/StubFactoryProxyImpl.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi.proxy ; + +import com.sun.corba.ee.impl.presentation.rmi.*; +import java.lang.reflect.Proxy ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.DynamicStub ; +import org.glassfish.pfl.basic.proxy.InvocationHandlerFactory; +import org.glassfish.pfl.basic.proxy.LinkedInvocationHandler; + +public class StubFactoryProxyImpl extends StubFactoryDynamicBase +{ + public StubFactoryProxyImpl( PresentationManager.ClassData classData, + ClassLoader loader ) + { + super( classData, loader ) ; + } + + public org.omg.CORBA.Object makeStub() + { + // Construct the dynamic proxy that implements this stub + // using the composite handler + InvocationHandlerFactory factory = classData.getInvocationHandlerFactory() ; + LinkedInvocationHandler handler = + (LinkedInvocationHandler)factory.getInvocationHandler() ; + Class[] interfaces = factory.getProxyInterfaces() ; + DynamicStub stub = (DynamicStub)Proxy.newProxyInstance( loader, interfaces, + handler ) ; + handler.setProxy( (Proxy)stub ) ; + return stub ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/AddressingDispositionException.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/AddressingDispositionException.java new file mode 100644 index 000000000..062f96201 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/AddressingDispositionException.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr; + +/** + * This exception is thrown while reading GIOP 1.2 Request, LocateRequest + * to indicate that a TargetAddress disposition is unacceptable. + * If this exception is caught explicitly, this need to be rethrown. This + * is eventually handled within RequestPRocessor and an appropriate reply + * is sent back to the client. + * + * GIOP 1.2 allows three dispositions : KeyAddr (ObjectKey), ProfileAddr (ior + * profile), IORAddressingInfo (IOR). If the ORB does not support the + * disposition contained in the GIOP Request / LocateRequest 1.2 message, + * then it sends a Reply / LocateReply indicating the correct disposition, + * which the client ORB shall use to transparently retry the request + * with the correct disposition. + * + */ +public class AddressingDispositionException extends RuntimeException { + + private short expectedAddrDisp = KeyAddr.value; + + public AddressingDispositionException(short expectedAddrDisp) { + this.expectedAddrDisp = expectedAddrDisp; + } + + public short expectedAddrDisp() { + return this.expectedAddrDisp; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/BootstrapServerRequestDispatcher.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/BootstrapServerRequestDispatcher.java new file mode 100644 index 000000000..400c23a8b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/BootstrapServerRequestDispatcher.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol ; + +import java.util.Iterator ; + +import org.omg.CORBA.SystemException ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.impl.encoding.MarshalInputStream ; +import com.sun.corba.ee.impl.encoding.MarshalOutputStream ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * Class BootstrapServerRequestDispatcher handles the requests coming to the + * BootstrapServer. It implements Server so that it can be registered + * as a subcontract. It is passed a BootstrapServiceProperties object + * which contains + * the supported ids and their values for the bootstrap service. This + * Properties object is only read from, never written to, and is shared + * among all threads. + *

    + * The BootstrapServerRequestDispatcher responds primarily to GIOP requests, + * but LocateRequests are also handled for graceful interoperability. + * The BootstrapServerRequestDispatcher handles one request at a time. + */ +public class BootstrapServerRequestDispatcher + implements ServerRequestDispatcher +{ + private ORB orb; + + static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static final boolean debug = false; + + public BootstrapServerRequestDispatcher(ORB orb ) + { + this.orb = orb; + } + + /** + * Dispatch is called by the ORB and will serve get(key) and list() + * invocations on the initial object key. + */ + public void dispatch(MessageMediator messageMediator) + { + MessageMediator request = (MessageMediator) messageMediator; + MessageMediator response = null; + + try { + MarshalInputStream is = (MarshalInputStream) + request.getInputObject(); + String method = request.getOperationName(); + response = request.getProtocolHandler().createResponse(request, null); + MarshalOutputStream os = (MarshalOutputStream) + response.getOutputObject(); + + if (method.equals("get")) { + // Get the name of the requested service + String serviceKey = is.read_string(); + + // Look it up + org.omg.CORBA.Object serviceObject = + orb.getLocalResolver().resolve( serviceKey ) ; + + // Write reply value + os.write_Object(serviceObject); + } else if (method.equals("list")) { + java.util.Set keys = orb.getLocalResolver().list() ; + os.write_long( keys.size() ) ; + Iterator iter = keys.iterator() ; + while (iter.hasNext()) { + String obj = (String)iter.next() ; + os.write_string( obj ) ; + } + } else { + throw wrapper.illegalBootstrapOperation( method ) ; + } + + } catch (org.omg.CORBA.SystemException ex) { + // Marshal the exception thrown + response = request.getProtocolHandler().createSystemExceptionResponse( + request, ex, null); + } catch (java.lang.RuntimeException ex) { + // Unknown exception + SystemException sysex = wrapper.bootstrapRuntimeException( ex ) ; + response = request.getProtocolHandler().createSystemExceptionResponse( + request, sysex, null ) ; + } catch (java.lang.Exception ex) { + // Unknown exception + SystemException sysex = wrapper.bootstrapException( ex ) ; + response = request.getProtocolHandler().createSystemExceptionResponse( + request, sysex, null ) ; + } + + return; + } + + /** + * Locates the object mentioned in the locate requests, and returns + * object here iff the object is the initial object key. A SystemException + * thrown if the object key is not the initial object key. + */ + public IOR locate( ObjectKey objectKey) { + return null; + } + + /** + * Not implemented + */ + public int getId() { + throw wrapper.genericNoImpl() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ClientDelegateImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ClientDelegateImpl.java new file mode 100644 index 000000000..9d425d344 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ClientDelegateImpl.java @@ -0,0 +1,566 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import java.util.Iterator; + +import org.omg.CORBA.Context; +import org.omg.CORBA.ContextList; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.NamedValue; +import org.omg.CORBA.NVList; +import org.omg.CORBA.Request; + +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.Delegate; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ServantObject; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.protocol.ClientInvocationInfo; +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher; + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.ClientDelegate ; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfoListIterator; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.impl.corba.RequestImpl; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.util.JDKBridge; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.ior.TaggedProfile; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.trace.IsLocal; +import com.sun.corba.ee.spi.trace.Subcontract; +import org.glassfish.pfl.basic.logex.OperationTracer; +import org.glassfish.pfl.tf.spi.TimingPointType; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +// implements com.sun.corba.ee.impl.core.ClientRequestDispatcher +// so RMI-IIOP Util.isLocal can call ClientRequestDispatcher.useLocalInvocation. + +/** + * @author Harold Carr + */ +@Subcontract +@IsLocal +public class ClientDelegateImpl extends ClientDelegate +{ + private ORB orb; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private ContactInfoList contactInfoList; + + public ClientDelegateImpl(ORB orb, + ContactInfoList contactInfoList) + { + this.orb = orb; + // this.tp = orb.getTimerManager().points() ; + this.contactInfoList = contactInfoList; + } + + // + // framework.subcontract.Delegate + // + + public ORB getBroker() + { + return orb; + } + + public ContactInfoList getContactInfoList() + { + return contactInfoList; + } + + // + // CORBA_2_3.portable.Delegate + // + + @InfoMethod + private void requestInfo( String operation, ContactInfo info ) { } + + @InfoMethod + private void retryingRequest( Exception exc ) { } + + @InfoMethod( tpName="totalInvocation", tpType=TimingPointType.ENTER ) + private void enter_totalInvocation() { } + + @InfoMethod( tpName="totalInvocation", tpType=TimingPointType.EXIT ) + private void exit_totalInvocation() { } + + @InfoMethod( tpName="hasNextNext", tpType=TimingPointType.ENTER ) + private void enter_hasNextNext() { } + + @InfoMethod( tpName="hasNextNext", tpType=TimingPointType.EXIT ) + private void exit_hasNextNext() { } + + private IIOPAddress getPrimaryAddress( final IOR ior ) { + if (ior != null) { + for (TaggedProfile tprof : ior) { + final TaggedProfileTemplate tpt = tprof.getTaggedProfileTemplate() ; + if (tpt instanceof IIOPProfileTemplate) { + final IIOPProfileTemplate ipt = (IIOPProfileTemplate)tpt ; + return ipt.getPrimaryAddress() ; + } + } + } + + return null ; + } + + @InfoMethod + private void targetIOR( IOR ior ) {} + + @InfoMethod + private void effectiveTargetIOR( IOR ior ) {} + + @Subcontract + @Override + public OutputStream request(org.omg.CORBA.Object self, + String operation, + boolean responseExpected) + { + + targetIOR( contactInfoList.getTargetIOR() ) ; + effectiveTargetIOR( contactInfoList.getEffectiveTargetIOR() ); + enter_totalInvocation() ; + + try { + OutputStream result = null; + boolean retry; + do { + retry = false; + + Iterator contactInfoListIterator = null; + ContactInfo contactInfo = null; + ClientInvocationInfo invocationInfo = null; + + try { + invocationInfo = orb.createOrIncrementInvocationInfo(); + contactInfoListIterator = invocationInfo.getContactInfoListIterator(); + if (contactInfoListIterator == null) { + contactInfoListIterator = contactInfoList.iterator(); + invocationInfo.setContactInfoListIterator(contactInfoListIterator); + } + + try { + enter_hasNextNext() ; + + if (! contactInfoListIterator.hasNext()) { + // REVISIT: When we unwind the retry stack + // these are necessary. + orb.getPIHandler().initiateClientPIRequest(false); + ORBUtility.pushEncVersionToThreadLocalState(ORBConstants.JAVA_ENC_VERSION); + throw ((ContactInfoListIterator)contactInfoListIterator).getFailureException(); + } + contactInfo = (ContactInfo) contactInfoListIterator.next(); + requestInfo( operation, contactInfo ) ; + } finally { + exit_hasNextNext() ; + } + + ClientRequestDispatcher subcontract = contactInfo.getClientRequestDispatcher(); + // Remember chosen subcontract for invoke and releaseReply. + // + // NOTE: This is necessary since a stream is not available + // in releaseReply if there is a client marshaling error + // or an error in _invoke. + invocationInfo.setClientRequestDispatcher(subcontract); + result = subcontract.beginRequest(self, operation, !responseExpected, contactInfo); + } catch (RuntimeException e) { + // REVISIT: + // this part similar to BufferManagerWriteStream.overflow() + retry = contactInfoListIterator != null + && ((ContactInfoListIterator) contactInfoListIterator).reportException(contactInfo, e); + + if (retry) { + retryingRequest(e); + invocationInfo.setIsRetryInvocation(true); + } else { + throw e; + } + } + } while (retry); + return result; + } finally { + // Enable operation tracing for argument marshaling + if (orb.operationTraceDebugFlag) { + OperationTracer.enable() ; + } + OperationTracer.begin( "client argument marshaling:op=" + operation ) ; + } + } + + @Subcontract + @Override + public InputStream invoke(org.omg.CORBA.Object self, OutputStream output) + throws + ApplicationException, + RemarshalException + { + // Disable operation tracing for argment marshaling + OperationTracer.disable() ; + OperationTracer.finish() ; + + ClientRequestDispatcher subcontract = getClientRequestDispatcher(); + try { + return (InputStream) + subcontract.marshalingComplete((Object)self, (CDROutputObject)output); + } finally { + // Enable operation tracing for result unmarshaling + if (orb.operationTraceDebugFlag) { + OperationTracer.enable() ; + } + OperationTracer.begin( "client result unmarshaling" ) ; + } + } + + @Subcontract + @Override + public void releaseReply(org.omg.CORBA.Object self, InputStream input) + { + try { + // NOTE: InputStream may be null (e.g., exception request from PI). + ClientRequestDispatcher subcontract = getClientRequestDispatcher(); + if (subcontract != null) { + // Important: avoid an NPE. + // ie: Certain errors may happen before a subcontract is selected. + subcontract.endRequest(orb, self, (CDRInputObject)input); + } + orb.releaseOrDecrementInvocationInfo(); + } finally { + exit_totalInvocation() ; + + // Disable operation tracing for result unmarshaling + OperationTracer.disable() ; + OperationTracer.finish() ; + } + } + + private ClientRequestDispatcher getClientRequestDispatcher() + { + return ((InvocationInfo) orb.getInvocationInfo()).getClientRequestDispatcher(); + } + + public org.omg.CORBA.Object get_interface_def(org.omg.CORBA.Object obj) + { + InputStream is = null; + // instantiate the stub + org.omg.CORBA.Object stub = null ; + + try { + OutputStream os = request(null, "_interface", true); + is = invoke((org.omg.CORBA.Object) null, os); + + org.omg.CORBA.Object objimpl = is.read_Object(); + + // check if returned object is of correct type + if ( !objimpl._is_a("IDL:omg.org/CORBA/InterfaceDef:1.0") ) { + throw wrapper.wrongInterfaceDef(); + } + + try { + stub = (org.omg.CORBA.Object) + JDKBridge.loadClass("org.omg.CORBA._InterfaceDefStub"). + newInstance(); + } catch (Exception ex) { + throw wrapper.noInterfaceDefStub( ex ) ; + } + + org.omg.CORBA.portable.Delegate del = + StubAdapter.getDelegate( objimpl ) ; + StubAdapter.setDelegate( stub, del ) ; + } catch (ApplicationException e) { + // This cannot happen. + throw wrapper.applicationExceptionInSpecialMethod( e ) ; + } catch (RemarshalException e) { + return get_interface_def(obj); + } finally { + releaseReply((org.omg.CORBA.Object)null, is); + } + + return stub; + } + + @InfoMethod + private void foundMyId() { } + + @InfoMethod + private void foundIdInRepostioryId() { } + + @InfoMethod + private void callingServer() { } + + @InfoMethod + private void serverReturned() { } + + @InfoMethod + private void retryingRequest() { } + + @Subcontract + public boolean is_a(org.omg.CORBA.Object obj, String dest) { + while (true) { + // dest is the typeId of the interface to compare against. + // repositoryIds is the list of typeIds that the stub knows about. + + // First we look for an answer using local information. + String [] repositoryIds = StubAdapter.getTypeIds( obj ) ; + String myid = contactInfoList.getTargetIOR().getTypeId(); + if ( dest.equals(myid) ) { + foundMyId(); + return true; + } + + for ( int i=0; i maximum ) { + return 0; + } + return h; + } + + public Request request(org.omg.CORBA.Object obj, String operation) { + return new RequestImpl(orb, obj, null, operation, null, null, null, + null); + } + + public Request create_request(org.omg.CORBA.Object obj, + Context ctx, + String operation, + NVList arg_list, + NamedValue result) { + return new RequestImpl(orb, obj, ctx, operation, arg_list, + result, null, null); + } + + public Request create_request(org.omg.CORBA.Object obj, + Context ctx, + String operation, + NVList arg_list, + NamedValue result, + ExceptionList exclist, + ContextList ctxlist) { + return new RequestImpl(orb, obj, ctx, operation, arg_list, result, + exclist, ctxlist); + } + + @Override + public org.omg.CORBA.ORB orb(org.omg.CORBA.Object obj) { + return this.orb; + } + + /** + * Returns true if this object is implemented by a local servant. + * + * REVISIT: locatedIOR should be replaced with a method call that + * returns the current IOR for this request (e.g. ContactInfoChooser). + * + * @param self The object reference which delegated to this delegate. + * @return true only if the servant incarnating this object is located in + * this ORB. + */ + @Override + @IsLocal + public boolean is_local(org.omg.CORBA.Object self) { + return contactInfoList.getEffectiveTargetIOR().getProfile(). + isLocal(); + } + + @Override + public ServantObject servant_preinvoke(org.omg.CORBA.Object self, + String operation, + Class expectedType) { + return + contactInfoList.getLocalClientRequestDispatcher() + .servant_preinvoke(self, operation, expectedType); + } + + @Override + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servant) { + contactInfoList.getLocalClientRequestDispatcher() + .servant_postinvoke(self, servant); + } + + /* Returns the codebase for object reference provided. + * @param self the object reference whose codebase needs to be returned. + * @return the codebase as a space delimited list of url strings or + * null if none. + */ + @Override + public String get_codebase(org.omg.CORBA.Object self) { + if (contactInfoList.getTargetIOR() != null) { + return contactInfoList.getTargetIOR().getProfile().getCodebase(); + } + return null; + } + + @Override + public String toString(org.omg.CORBA.Object self) { + return contactInfoList.getTargetIOR().toString(); + } + + @Override + public int hashCode() { + return this.contactInfoList.hashCode(); + } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ClientRequestDispatcherImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ClientRequestDispatcherImpl.java new file mode 100644 index 000000000..c7ad028fa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ClientRequestDispatcherImpl.java @@ -0,0 +1,1015 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo; +import com.sun.corba.ee.impl.encoding.CodeSetConversion; +import com.sun.corba.ee.impl.encoding.EncapsInputStream; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.CodeSetsComponent; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.servicecontext.*; +import com.sun.corba.ee.spi.trace.Subcontract; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoListIterator; +import com.sun.corba.ee.spi.transport.OutboundConnectionCache; +import org.glassfish.pfl.tf.spi.TimingPointType; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.IOP.ExceptionDetailMessage; +import org.omg.IOP.TAG_CODE_SETS; + +import java.io.IOException; +import java.util.Iterator; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * ClientDelegate is the RMI client-side subcontract or representation + * It implements RMI delegate as well as our internal ClientRequestDispatcher + * interface. + */ +@Subcontract +public class ClientRequestDispatcherImpl + implements + ClientRequestDispatcher +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Used for locking + private final Object lock = new Object(); + + private ORBVersionServiceContext ovsc = + ServiceContextDefaults.makeORBVersionServiceContext(); + + + private MaxStreamFormatVersionServiceContext msfvc = + ServiceContextDefaults.getMaxStreamFormatVersionServiceContext(); + + private ConcurrentMap locks = + new ConcurrentHashMap() ; + + @InfoMethod + private void usingCachedConnection( Connection conn ) { } + + @InfoMethod + private void usingCreatedConnection( Connection conn ) { } + + @InfoMethod + private void connectionCached( Connection conn ) { } + + @InfoMethod + private void connectionRegistered( Connection conn ) { } + + @InfoMethod + private void createdMessageMediator( MessageMediator med ) { } + + @InfoMethod + private void createOutputObject( CDROutputObject out ) { } + + @InfoMethod + private void generalMessage ( String msg ) { } + + @InfoMethod + private void remarshalWithHasNextTrue( ContactInfo info ) { } + + @InfoMethod( tpName="totalRequest", tpType=TimingPointType.ENTER ) + private void enter_totalRequest() { } + + @InfoMethod( tpName="totalRequest", tpType=TimingPointType.EXIT ) + private void exit_totalRequest() { } + + @InfoMethod( tpName="connectionSetup", tpType=TimingPointType.ENTER ) + private void enter_connectionSetup() { } + + @InfoMethod( tpName="connectionSetup", tpType=TimingPointType.EXIT ) + private void exit_connectionSetup() { } + + @InfoMethod( tpName="clientDecoding", tpType=TimingPointType.ENTER ) + private void enter_clientDecoding() { } + + @InfoMethod( tpName="clientDecoding", tpType=TimingPointType.EXIT ) + private void exit_clientDecoding() { } + + @InfoMethod( tpName="clientEncoding", tpType=TimingPointType.ENTER ) + private void enter_clientEncoding() { } + + @InfoMethod( tpName="clientEncoding", tpType=TimingPointType.EXIT ) + private void exit_clientEncoding() { } + + @InfoMethod( tpName="clientTransportAndWait", tpType=TimingPointType.ENTER ) + private void enter_clientTransportAndWait() { } + + @InfoMethod( tpName="clientTransportAndWait", tpType=TimingPointType.EXIT ) + private void exit_clientTransportAndWait() { } + + @InfoMethod( tpName="processResponse", tpType=TimingPointType.ENTER ) + private void enter_processResponse() { } + + @InfoMethod( tpName="processResponse", tpType=TimingPointType.EXIT ) + private void exit_processResponse() { } + + @InfoMethod( tpName="requestAddServiceContexts", tpType=TimingPointType.ENTER ) + private void enter_requestAddServiceContexts() { } + + @InfoMethod( tpName="requestAddServiceContexts", tpType=TimingPointType.EXIT ) + private void exit_requestAddServiceContexts() { } + + @Subcontract + public CDROutputObject beginRequest(Object self, String opName, + boolean isOneWay, ContactInfo contactInfo) { + + final ORB orb = contactInfo.getBroker(); + + enter_totalRequest() ; + + // Portable Interceptor initialization. + orb.getPIHandler().initiateClientPIRequest( false ); + + Connection connection = null; + + Object lock = locks.get( contactInfo ) ; + + if (lock == null) { + Object newLock = new Object() ; + lock = locks.putIfAbsent( contactInfo, newLock ) ; + if (lock == null) { + lock = newLock ; + } + } + + // This locking is done so that multiple connections are not created + // for the same endpoint. Note that we are locking here on the + // same lock for different contactInfos that are equal, which is really + // what's required. This is a fix for 7016182. + // + // TODO NEW CACHE: all of this is replaced with the get() call, except + // the code needed to add the connection to the selector. + // + // Is the fix for 7016182 still needed with the new caches? + synchronized (lock) { + if (contactInfo.isConnectionBased()) { + try { + enter_connectionSetup(); + + if (contactInfo.shouldCacheConnection()) { + connection = orb.getTransportManager() + .getOutboundConnectionCache(contactInfo) + .get(contactInfo); + } + + if (connection != null) { + usingCachedConnection( connection ) ; + } else { + connection = + contactInfo.createConnection(); + usingCreatedConnection( connection ) ; + + if (connection.shouldRegisterReadEvent()) { + orb.getTransportManager().getSelector(0) + .registerForEvent(connection.getEventHandler()); + connection.setState("ESTABLISHED"); + connectionRegistered( connection ) ; + } + + // Do not do connection reclaim here since the + // connections are marked in use by registerWaiter() + // call and since this call happens later do it after + // that. + if (contactInfo.shouldCacheConnection()) { + OutboundConnectionCache connectionCache = + orb.getTransportManager() + .getOutboundConnectionCache(contactInfo); + connectionCache.stampTime(connection); + connectionCache.put(contactInfo, connection); + connectionCached( connection ) ; + } + } + } finally { + exit_connectionSetup(); + } + } + } + + MessageMediator messageMediator = + contactInfo.createMessageMediator(orb, contactInfo, connection, + opName, isOneWay); + createdMessageMediator(messageMediator); + + // NOTE: Thread data so we can get the mediator in release reply + // in order to remove the waiter in CorbaConnection. + // We cannot depend on obtaining information in releaseReply + // via its InputStream argument since, on certain errors + // (e.g., client marshaling errors), the stream may be null. + // Likewise for releaseReply "self". + // NOTE: This must be done before initializing the message since + // that may start sending fragments which may end up in "early" + // replies or client marshaling exceptions. + orb.getInvocationInfo().setMessageMediator(messageMediator); + + performCodeSetNegotiation(messageMediator); + + enter_requestAddServiceContexts() ; + try { + addServiceContexts(messageMediator); + } finally { + exit_requestAddServiceContexts() ; + } + + CDROutputObject outputObject = contactInfo.createOutputObject(messageMediator); + + createOutputObject(outputObject); + + // NOTE: Not necessary for oneways, but useful for debugging. + // This must be done BEFORE message initialization since fragments + // may be sent at that time. + registerWaiter(messageMediator); + + // Do connection reclaim now + synchronized (lock) { + if (contactInfo.isConnectionBased()) { + if (contactInfo.shouldCacheConnection()) { + generalMessage( "reclaiming connections" ); + OutboundConnectionCache connectionCache = orb.getTransportManager() + .getOutboundConnectionCache(contactInfo); + connectionCache.reclaim(); + } + } + } + + orb.getPIHandler().setClientPIInfo(messageMediator); + try { + // This MUST come before message is initialized so + // service contexts may be added by PI because + // initial fragments may be sent during message initialization. + orb.getPIHandler().invokeClientPIStartingPoint(); + } catch( RemarshalException e ) { + generalMessage( "Remarshal" ) ; + + // NOTE: We get here because an interceptor raised ForwardRequest + // and updated the IOR/Iterator. Since we have a fresh iterator + // hasNext should succeed. + + // REVISIT: We should feed ALL interceptor exceptions to + // iterator.reportException so it can determine if it wants + // to retry. Right now, SystemExceptions will flow to the + // client code. + + // REVISIT: + // This assumes that interceptors update + // ContactInfoList outside of subcontract. + // Want to move that update to here. + if (getContactInfoListIterator(orb).hasNext()) { + contactInfo = getContactInfoListIterator(orb).next(); + remarshalWithHasNextTrue(contactInfo); + + // Fix for 6763340: Complete the first attempt before starting another. + orb.getPIHandler().makeCompletedClientRequest( + ReplyMessage.LOCATION_FORWARD, null ) ; + unregisterWaiter( orb ) ; + orb.getPIHandler().cleanupClientPIRequest() ; + + return beginRequest(self, opName, isOneWay, contactInfo); + } else { + retryMessage( "RemarshalException: hasNext false" ) ; + throw wrapper.remarshalWithNowhereToGo(); + } + } + + messageMediator.initializeMessage(); + generalMessage( "initialized message"); + + enter_clientEncoding(); + + return outputObject; + } + + @InfoMethod + private void operationAndId( String op, int rid ) { } + + @Subcontract + public CDRInputObject marshalingComplete(java.lang.Object self, + CDROutputObject outputObject) + throws + ApplicationException, + org.omg.CORBA.portable.RemarshalException + { + MessageMediator messageMediator = outputObject.getMessageMediator(); + ORB orb = messageMediator.getBroker(); + operationAndId(messageMediator.getOperationName(), + messageMediator.getRequestId() ); + + try { + exit_clientEncoding(); + + enter_clientTransportAndWait(); + + CDRInputObject inputObject = null ; + try { + inputObject = marshalingComplete1(orb, messageMediator); + } finally { + exit_clientTransportAndWait(); + } + + return processResponse(orb, messageMediator, inputObject); + } finally { + // We must ALWAYS call enter_ClientDecoding, so that the + // corresponding exit_clientDecoding gets called in endRequest(). + enter_clientDecoding() ; + } + } + + @InfoMethod + private void retryMessage( String msg ) { } + + @InfoMethod + private void reportException( Throwable exc ) { } + + @InfoMethod + private void reportException( String msg, Throwable exc ) { } + + @Subcontract + public CDRInputObject marshalingComplete1( + ORB orb, MessageMediator messageMediator) + throws + ApplicationException, + org.omg.CORBA.portable.RemarshalException + { + operationAndId(messageMediator.getOperationName(), + messageMediator.getRequestId() ); + + try { + messageMediator.finishSendingRequest(); + + // TODO NEW CACHE: call release( conn, numResponse ) here + // Get connection from MessageMediator + // Get numResponse from messageMediator.isOneWay: 0 or 1 expected. + + return messageMediator.waitForResponse(); + } catch (RuntimeException e) { + reportException( e ) ; + + boolean retry = + getContactInfoListIterator(orb) + .reportException(messageMediator.getContactInfo(), e); + + // Bug 6382377: must not lose exception in PI + // Must run interceptor end point before retrying. + Exception newException = + orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.SYSTEM_EXCEPTION, e); + + if (retry) { + if (newException == e) { + retryMessage( "Retry true; same exception" ) ; + continueOrThrowSystemOrRemarshal(messageMediator, + new RemarshalException()); + } else { + retryMessage( "Retry true; new exception" ) ; + continueOrThrowSystemOrRemarshal(messageMediator, + newException); + } + } else { + // NOTE: Interceptor ending point will run in releaseReply. + if (newException instanceof RuntimeException) { + retryMessage( "Retry false; RuntimeException" ) ; + throw (RuntimeException)newException ; + } else if (newException instanceof RemarshalException) { + throw (RemarshalException) newException; + } else { + retryMessage( "Retry false; other exception" ) ; + throw e ; + } + } + + return null; // for compiler + } + } + + @InfoMethod + private void receivedUserException( String repoid ) { } + + @InfoMethod + private void receivedUserExceptionDII( Throwable exc, Throwable newExc ) { } + + @InfoMethod + private void receivedUserExceptionNotDII( Throwable exc, Throwable newExc ) { } + + @Subcontract + protected CDRInputObject processResponse(ORB orb, + MessageMediator messageMediator, CDRInputObject inputObject) + throws ApplicationException, org.omg.CORBA.portable.RemarshalException { + + operationAndId(messageMediator.getOperationName(), + messageMediator.getRequestId() ); + + enter_processResponse() ; + try { + // We know for sure now that we've sent a message. + // So OK to not send initial again. + if (messageMediator.getConnection() != null) { + generalMessage( "Non-null connection" ) ; + messageMediator.getConnection().setPostInitialContexts(); + } + + // NOTE: not necessary to set MessageMediator for PI. + // It already has it. + + // Process the response. + + Exception exception = null; + + if (messageMediator.isOneWay()) { + generalMessage( "One way request" ) ; + getContactInfoListIterator(orb) + .reportSuccess(messageMediator.getContactInfo()); + // Invoke Portable Interceptors with receive_other + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.NO_EXCEPTION, exception ); + reportException(exception); + continueOrThrowSystemOrRemarshal(messageMediator, exception); + return null; + } + + consumeServiceContexts(orb, messageMediator); + + // Now that we have the service contexts processed and the + // correct ORBVersion set, we must finish initializing the stream. + // REVISIT - need interface for this operation. + inputObject.performORBVersionSpecificInit(); + + if (messageMediator.isSystemExceptionReply()) { + SystemException se = messageMediator.getSystemExceptionReply(); + reportException( "received system exception", se); + + boolean doRemarshal = + getContactInfoListIterator(orb) + .reportException(messageMediator.getContactInfo(), se); + + if (doRemarshal) { + reportException( "Do remarshal", se); + + // Invoke Portable Interceptors with receive_exception: + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.SYSTEM_EXCEPTION, se ); + + // If PI did not change the exception, throw a + // Remarshal. + if( se == exception ) { + generalMessage( "Do remarshal: same exception"); + // exception = null is to maintain symmetry with + // GenericPOAClientSC. + exception = null; + continueOrThrowSystemOrRemarshal(messageMediator, + new RemarshalException()); + throw wrapper.statementNotReachable1() ; + } else { + reportException( "Do remarshal: new exception", exception ); + // Otherwise, throw the exception PI wants thrown. + continueOrThrowSystemOrRemarshal(messageMediator, + exception); + throw wrapper.statementNotReachable2() ; + } + } + + // No retry, so see if was unknown. + reportException( "NO remarshal", se); + + ServiceContexts contexts = + messageMediator.getReplyServiceContexts(); + if (contexts != null) { + UEInfoServiceContext usc = + (UEInfoServiceContext) + contexts.get(UEInfoServiceContext.SERVICE_CONTEXT_ID); + + if (usc != null) { + Throwable unknown = usc.getUE() ; + UnknownException ue = new UnknownException(unknown); + + reportException( "NO remarshal: UserException available", + unknown ); + + // Invoke Portable Interceptors with receive_exception: + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.SYSTEM_EXCEPTION, ue ); + + reportException( "NO remarshal: UserException available: PI exception ", + exception ); + + continueOrThrowSystemOrRemarshal(messageMediator, exception); + throw wrapper.statementNotReachable3() ; + } + } + + // It was not a comm failure nor unknown. + // This is the general case. + reportException( "general exception", se); + + // Invoke Portable Interceptors with receive_exception: + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.SYSTEM_EXCEPTION, se ); + + reportException( "general exception: PI exception", exception ); + + continueOrThrowSystemOrRemarshal(messageMediator, exception); + + // Note: We should never need to execute this line, but + // we should assert in case exception is null somehow. + throw wrapper.statementNotReachable4() ; + } else if (messageMediator.isUserExceptionReply()) { + getContactInfoListIterator(orb) + .reportSuccess(messageMediator.getContactInfo()); + + String exceptionRepoId = peekUserExceptionId(inputObject); + receivedUserException(exceptionRepoId); + + Exception newException = null; + + if (messageMediator.isDIIRequest()) { + exception = messageMediator.unmarshalDIIUserException( + exceptionRepoId, (InputStream)inputObject); + newException = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.USER_EXCEPTION, exception ); + messageMediator.setDIIException(newException); + + receivedUserExceptionDII(exception, newException); + } else { + ApplicationException appException = new ApplicationException( + exceptionRepoId, (org.omg.CORBA.portable.InputStream)inputObject); + + exception = appException; + + newException = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.USER_EXCEPTION, appException ); + + receivedUserExceptionNotDII(exception, newException); + } + + if (newException != exception) { + continueOrThrowSystemOrRemarshal(messageMediator,newException); + } + + if (newException instanceof ApplicationException) { + throw (ApplicationException)newException; + } + // For DII: + // This return will be ignored - already unmarshaled above. + return inputObject; + + } else if (messageMediator.isLocationForwardReply()) { + generalMessage( "received location forward"); + + // NOTE: Expects iterator to update target IOR + getContactInfoListIterator(orb).reportRedirect( + messageMediator.getContactInfo(), + messageMediator.getForwardedIOR()); + + // Invoke Portable Interceptors with receive_other: + Exception newException = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.LOCATION_FORWARD, null ); + + if( !(newException instanceof RemarshalException) ) { + exception = newException; + } + + // If PI did not change exception, throw Remarshal, else + // throw the exception PI wants thrown. + // KMC: GenericPOAClientSC did not check exception != null + if( exception != null ) { + continueOrThrowSystemOrRemarshal(messageMediator, exception); + } + continueOrThrowSystemOrRemarshal(messageMediator, + new RemarshalException()); + throw wrapper.statementNotReachable5() ; + + } else if (messageMediator.isDifferentAddrDispositionRequestedReply()){ + generalMessage( "received different addressing dispostion request"); + + // Set the desired target addressing disposition. + getContactInfoListIterator(orb).reportAddrDispositionRetry( + messageMediator.getContactInfo(), + messageMediator.getAddrDispositionReply()); + + // Invoke Portable Interceptors with receive_other: + Exception newException = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.NEEDS_ADDRESSING_MODE, null); + + // For consistency with corresponding code in GenericPOAClientSC: + if( !(newException instanceof RemarshalException) ) { + exception = newException; + } + + // If PI did not change exception, throw Remarshal, else + // throw the exception PI wants thrown. + // KMC: GenericPOAClientSC did not include exception != null check + if( exception != null ) { + continueOrThrowSystemOrRemarshal(messageMediator, exception); + } + continueOrThrowSystemOrRemarshal(messageMediator, + new RemarshalException()); + throw wrapper.statementNotReachable6() ; + } else /* normal response */ { + generalMessage( "received normal response"); + + getContactInfoListIterator(orb) + .reportSuccess(messageMediator.getContactInfo()); + + messageMediator.handleDIIReply((InputStream)inputObject); + + // Invoke Portable Interceptors with receive_reply: + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.NO_EXCEPTION, null ); + + // Remember: not thrown if exception is null. + continueOrThrowSystemOrRemarshal(messageMediator, exception); + + return inputObject; + } + } finally { + exit_processResponse() ; + } + } + + // Filters the given exception into a SystemException or a + // RemarshalException and throws it. Assumes the given exception is + // of one of these two types. This is a utility method for + // the above invoke code which must do this numerous times. + // If the exception is null, no exception is thrown. + // Note that this code is duplicated in GenericPOAClientSC.java + @Subcontract + protected void continueOrThrowSystemOrRemarshal( + MessageMediator messageMediator, Exception exception) + throws + SystemException, RemarshalException + { + final ORB orb = messageMediator.getBroker(); + + if ( exception == null ) { + // do nothing. + } else if( exception instanceof RemarshalException ) { + // REVISIT - unify with PI handling + orb.getInvocationInfo().setIsRetryInvocation(true); + + // NOTE - We must unregister the waiter NOW for this request + // since the retry will result in a new request id. Therefore + // the old request id would be lost and we would have a memory + // leak in the responseWaitingRoom. + unregisterWaiter(orb); + throw (RemarshalException)exception; + } else { + throw (SystemException)exception; + } + } + + protected ContactInfoListIterator getContactInfoListIterator(ORB orb) { + return (ContactInfoListIterator) orb.getInvocationInfo().getContactInfoListIterator(); + } + + @Subcontract + protected void registerWaiter(MessageMediator messageMediator) { + if (messageMediator.getConnection() != null) { + messageMediator.getConnection().registerWaiter(messageMediator); + } + } + + @Subcontract + protected void unregisterWaiter(ORB orb) { + MessageMediator messageMediator = + orb.getInvocationInfo().getMessageMediator(); + if (messageMediator!=null && messageMediator.getConnection() != null) { + // REVISIT: + // The messageMediator may be null if COMM_FAILURE before + // it is created. + messageMediator.getConnection().unregisterWaiter(messageMediator); + } + } + + @Subcontract + protected void addServiceContexts(MessageMediator messageMediator) { + ORB orb = messageMediator.getBroker(); + Connection c = messageMediator.getConnection(); + GIOPVersion giopVersion = messageMediator.getGIOPVersion(); + + ServiceContexts contexts = null; + + // If Java serialization is used. + if (ORBUtility.getEncodingVersion() != ORBConstants.CDR_ENC_VERSION) { + contexts = messageMediator.getRequestServiceContexts(); + ORBVersionServiceContext lsc = + ServiceContextDefaults.getORBVersionServiceContext() ; + contexts.put(lsc); + return; + } + + if (c != null && + giopVersion.equals(GIOPVersion.V1_2) && + c.getBroker().getORBData().alwaysSendCodeSetServiceContext()) { + if (!c.isPostInitialContexts()) { + contexts = (messageMediator.getBroker()). + getServiceContextsCache().get( + ServiceContextsCache.CASE.CLIENT_INITIAL); + } else { + contexts = messageMediator.getBroker() + .getServiceContextsCache().get( + ServiceContextsCache.CASE.CLIENT_SUBSEQUENT); + } + + addCodeSetServiceContext(c, contexts, giopVersion); + + messageMediator.setRequestServiceContexts(contexts); + + } else { + contexts = messageMediator.getRequestServiceContexts(); + + addCodeSetServiceContext(c, contexts, giopVersion); + + // Add the RMI-IIOP max stream format version + // service context to every request. Once we have GIOP 1.3, + // we could skip it since we now support version 2, but + // probably safer to always send it. + + contexts.put( msfvc ); + + // ORBVersion servicecontext needs to be sent + + contexts.put( ovsc ) ; + + // NOTE : We only want to send the runtime context the first time + if ((c != null) && !c.isPostInitialContexts()) { + // Do not do c.setPostInitialContexts() here. + // If a client interceptor send_request does a ForwardRequest + // which ends up using the same connection then the service + // context would not be sent. + SendingContextServiceContext scsc = + ServiceContextDefaults.makeSendingContextServiceContext( + orb.getFVDCodeBaseIOR() ) ; + contexts.put( scsc ) ; + } + } + } + + @Subcontract + protected void consumeServiceContexts(ORB orb, + MessageMediator messageMediator) + { + ServiceContexts ctxts = messageMediator.getReplyServiceContexts(); + ServiceContext sc ; + + if (ctxts == null) { + return; // no service context available, return gracefully. + } + + sc = ctxts.get( SendingContextServiceContext.SERVICE_CONTEXT_ID ) ; + + if (sc != null) { + SendingContextServiceContext scsc = + (SendingContextServiceContext)sc ; + IOR ior = scsc.getIOR() ; + + try { + // set the codebase returned by the server + if (messageMediator.getConnection() != null) { + messageMediator.getConnection().setCodeBaseIOR(ior); + } + } catch (ThreadDeath td) { + throw td ; + } catch (Throwable t) { + throw wrapper.badStringifiedIor( t ) ; + } + } + + // see if the version subcontract is present, if yes, then set + // the ORBversion + sc = ctxts.get( ORBVersionServiceContext.SERVICE_CONTEXT_ID ) ; + + if (sc != null) { + ORBVersionServiceContext lsc = + (ORBVersionServiceContext) sc; + + ORBVersion version = lsc.getVersion(); + orb.setORBVersion( version ) ; + } + + getExceptionDetailMessage(messageMediator, wrapper); + } + + @Subcontract + protected void getExceptionDetailMessage( + MessageMediator messageMediator, + ORBUtilSystemException wrapper) + { + ServiceContext sc = messageMediator.getReplyServiceContexts() + .get(ExceptionDetailMessage.value); + if (sc == null) { + return; + } + + if (! (sc instanceof UnknownServiceContext)) { + throw wrapper.badExceptionDetailMessageServiceContextType(); + } + byte[] data = ((UnknownServiceContext)sc).getData(); + EncapsInputStream in = new EncapsInputStream(messageMediator.getBroker(), data, data.length); + in.consumeEndian(); + + String msg = + "----------BEGIN server-side stack trace----------\n" + + in.read_wstring() + "\n" + + "----------END server-side stack trace----------"; + + messageMediator.setReplyExceptionDetailMessage(msg); + } + + @Subcontract + public void endRequest(ORB orb, Object self, CDRInputObject inputObject) + { + try { + exit_clientDecoding(); + + // Note: the inputObject may be null if an error occurs + // in request or before _invoke returns. + // Note: self may be null also (e.g., compiler generates null in stub). + + MessageMediator messageMediator = + orb.getInvocationInfo().getMessageMediator(); + if (messageMediator != null) { + ORBUtility.popEncVersionFromThreadLocalState(); + + if (messageMediator.getConnection() != null) { + messageMediator.sendCancelRequestIfFinalFragmentNotSent(); + } + + // Release any outstanding NIO ByteBuffers to the ByteBufferPool + + CDRInputObject inputObj = messageMediator.getInputObject(); + if (inputObj != null) { + inputObj.close(); + } + + CDROutputObject outputObj = messageMediator.getOutputObject(); + if (outputObj != null) { + outputObj.close(); + } + + // TODO NEW CACHE: release( conn ) : conn is in MessageMediator + } + + // XREVISIT NOTE - Assumes unregistering the waiter for + // location forwards has already happened somewhere else. + // The code below is only going to unregister the final successful + // request. + + // NOTE: In the case of a recursive stack of endRequests in a + // finally block (because of Remarshal) only the first call to + // unregisterWaiter will remove the waiter. The rest will be + // noops. + unregisterWaiter(orb); + + // Invoke Portable Interceptors cleanup. This is done to handle + // exceptions during stream marshaling. More generally, exceptions + // that occur in the ORB after send_request (which includes + // after returning from _request) before _invoke: + orb.getPIHandler().cleanupClientPIRequest(); + + // REVISIT: Early replies? + } catch (IOException ex) { + // See CDRInput/OutputObject.close() for more info. + // This won't result in a Corba error if an IOException happens. + reportException("ignoring IOException", ex ); + } finally { + exit_totalRequest() ; + } + } + + @Subcontract + protected void performCodeSetNegotiation(MessageMediator messageMediator) { + Connection conn = messageMediator.getConnection(); + if (conn == null) { + return; + } + + GIOPVersion giopVersion = messageMediator.getGIOPVersion(); + if (giopVersion.equals(GIOPVersion.V1_0)) { + return; + } + + IOR ior = (messageMediator.getContactInfo()).getEffectiveTargetIOR(); + + synchronized( conn ) { + if (conn.getCodeSetContext() != null) { + return; + } + + // This only looks at the first code set component. If + // there can be multiple locations with multiple code sets, + // this requires more work. + IIOPProfileTemplate temp = (IIOPProfileTemplate)ior.getProfile(). + getTaggedProfileTemplate(); + Iterator iter = temp.iteratorById(TAG_CODE_SETS.value); + if (!iter.hasNext()) { + // Didn't have a code set component. The default will + // be to use ISO8859-1 for char data and throw an + // exception if wchar data is used. + return; + } + + // Get the native and conversion code sets the + // server specified in its IOR + CodeSetComponentInfo serverCodeSets + = ((CodeSetsComponent)iter.next()).getCodeSetComponentInfo(); + + // Perform the negotiation between this ORB's code sets and + // the ones from the IOR + CodeSetComponentInfo.CodeSetContext result + = CodeSetConversion.impl().negotiate( + conn.getBroker().getORBData().getCodeSetComponentInfo(), + serverCodeSets); + + conn.setCodeSetContext(result); + } + } + + @Subcontract + protected void addCodeSetServiceContext(Connection conn, + ServiceContexts ctxs, GIOPVersion giopVersion) { + + // REVISIT. OMG issue 3318 concerning sending the code set + // service context more than once was deemed too much for the + // RTF. Here's our strategy for the moment: + // + // Send it on every request (necessary in cases of fragmentation + // with multithreaded clients or when the first thing on a + // connection is a LocateRequest). Provide an ORB property + // to disable multiple sends. + // + // Note that the connection is null in the local case and no + // service context is included. We use the ORB provided + // encapsulation streams. + // + // Also, there will be no negotiation or service context + // in GIOP 1.0. ISO8859-1 is used for char/string, and + // wchar/wstring are illegal. + // + if (giopVersion.equals(GIOPVersion.V1_0) || conn == null) { + return; + } + + CodeSetComponentInfo.CodeSetContext codeSetCtx = null; + + if (conn.getBroker().getORBData().alwaysSendCodeSetServiceContext() || + !conn.isPostInitialContexts()) { + + // Get the negotiated code sets (if any) out of the connection + codeSetCtx = conn.getCodeSetContext(); + } + + // Either we shouldn't send the code set service context, or + // for some reason, the connection doesn't have its code sets. + // Perhaps the server didn't include them in the IOR. Uses + // ISO8859-1 for char and makes wchar/wstring illegal. + if (codeSetCtx == null) { + return; + } + + CodeSetServiceContext cssc = + ServiceContextDefaults.makeCodeSetServiceContext(codeSetCtx); + ctxs.put(cssc); + } + + @Subcontract + protected String peekUserExceptionId(CDRInputObject inputObject) { + CDRInputObject cdrInputObject = inputObject; + // REVISIT - need interface for mark/reset + cdrInputObject.mark(Integer.MAX_VALUE); + String result = cdrInputObject.read_string(); + cdrInputObject.reset(); + return result; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/FullServantCacheLocalCRDImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/FullServantCacheLocalCRDImpl.java new file mode 100644 index 000000000..7ba8e3f65 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/FullServantCacheLocalCRDImpl.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import org.omg.CORBA.portable.ServantObject ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.OADestroyed; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.trace.Subcontract; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Subcontract +public class FullServantCacheLocalCRDImpl extends ServantCacheLocalCRDBase +{ + public FullServantCacheLocalCRDImpl( ORB orb, int scid, IOR ior ) + { + super( orb, scid, ior ) ; + } + + @Subcontract + @Override + public ServantObject internalPreinvoke( org.omg.CORBA.Object self, + String operation, Class expectedType ) throws OADestroyed { + + OAInvocationInfo cachedInfo = getCachedInfo() ; + if (!checkForCompatibleServant( cachedInfo, expectedType )) { + return null; + } + + // Note that info is shared across multiple threads + // using the same subcontract, each of which may + // have its own operation. Therefore we need to clone it. + OAInvocationInfo newInfo = new OAInvocationInfo( cachedInfo, operation ) ; + newInfo.oa().enter() ; + orb.pushInvocationInfo( newInfo ) ; + return newInfo ; + } + + @Subcontract + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servantobj) { + try { + OAInvocationInfo cachedInfo = getCachedInfo() ; + cachedInfo.oa().exit() ; + } catch (OADestroyed oades) { + caughtOADestroyed() ; + // ignore this: if I can't get the OA, I don't + // need to call exit on it. + } finally { + orb.popInvocationInfo() ; + } + } + + @InfoMethod + private void caughtOADestroyed() { } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/INSServerRequestDispatcher.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/INSServerRequestDispatcher.java new file mode 100644 index 000000000..87b969996 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/INSServerRequestDispatcher.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * INSServerRequestDispatcher handles all INS related discovery request. The INS Service + * can be registered using ORB.register_initial_reference(). + * This Singleton subcontract just + * finds the target IOR and does location forward. + * XXX PI points are not invoked in either dispatch() or locate() method this + * should be fixed in Tiger. + */ +public class INSServerRequestDispatcher + implements ServerRequestDispatcher +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private ORB orb = null; + + public INSServerRequestDispatcher( ORB orb ) { + this.orb = orb; + } + + // Need to signal one of OBJECT_HERE, OBJECT_FORWARD, OBJECT_NOT_EXIST. + public IOR locate(ObjectKey okey) { + // send a locate forward with the right IOR. If the insKey is not + // registered then it will throw OBJECT_NOT_EXIST Exception + String insKey = new String( okey.getBytes(orb) ); + return getINSReference( insKey ); + } + + public void dispatch(MessageMediator request) + { + // send a locate forward with the right IOR. If the insKey is not + // registered then it will throw OBJECT_NOT_EXIST Exception + String insKey = new String( + request.getObjectKeyCacheEntry().getObjectKey().getBytes(orb) ); + request.getProtocolHandler() + .createLocationForward(request, getINSReference( insKey ), null); + return; + } + + /** + * getINSReference if it is registered in INSObjectKeyMap. + */ + private IOR getINSReference( String insKey ) { + IOR entry = orb.getIOR( orb.getLocalResolver().resolve( insKey ), false ) ; + if( entry != null ) { + // If entry is not null then the locate is with an INS Object key, + // so send a location forward with the right IOR. + return entry; + } + + throw wrapper.servantNotFound() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/InfoOnlyServantCacheLocalCRDImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/InfoOnlyServantCacheLocalCRDImpl.java new file mode 100644 index 000000000..c7a8e910d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/InfoOnlyServantCacheLocalCRDImpl.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import org.omg.CORBA.portable.ServantObject ; + +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.OADestroyed; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory ; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher ; + +import com.sun.corba.ee.spi.ior.IOR; + +public class InfoOnlyServantCacheLocalCRDImpl extends ServantCacheLocalCRDBase +{ + public InfoOnlyServantCacheLocalCRDImpl( ORB orb, int scid, IOR ior ) + { + super( (com.sun.corba.ee.spi.orb.ORB)orb, scid, ior ) ; + } + + public ServantObject internalPreinvoke( org.omg.CORBA.Object self, + String operation, Class expectedType ) throws OADestroyed + { + OAInvocationInfo cachedInfo = getCachedInfo() ; + if (!checkForCompatibleServant( cachedInfo, expectedType )) + return null ; + + // Note that info is shared across multiple threads + // using the same subcontract, each of which may + // have its own operation. Therefore we need to copy it. + OAInvocationInfo info = new OAInvocationInfo(cachedInfo, operation) ; + orb.pushInvocationInfo( info ) ; + + return info ; + } + + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servantobj) + { + orb.popInvocationInfo() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/InvocationInfo.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/InvocationInfo.java new file mode 100644 index 000000000..019266746 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/InvocationInfo.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import java.util.Iterator; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.protocol.ClientInvocationInfo; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher; + +/** + * @author Harold Carr + */ +public class InvocationInfo implements ClientInvocationInfo +{ + // REVISIT - these needs to be an interface-based impl. + + private boolean isRetryInvocation; + private int entryCount; + private Iterator contactInfoListIterator; + private ClientRequestDispatcher clientRequestDispatcher; + private MessageMediator messageMediator; + + public InvocationInfo() + { + isRetryInvocation = false; + entryCount = 0; + } + + public Iterator getContactInfoListIterator() + { + return contactInfoListIterator; + } + + public void setContactInfoListIterator(Iterator contactInfoListIterator) + { + this.contactInfoListIterator = contactInfoListIterator; + } + + public boolean isRetryInvocation() + { + return isRetryInvocation; + } + + public void setIsRetryInvocation(boolean isRetryInvocation) + { + this.isRetryInvocation = isRetryInvocation; + } + + public int getEntryCount() + { + return entryCount; + } + + public void incrementEntryCount() + { + entryCount++; + } + + public void decrementEntryCount() + { + entryCount--; + } + + public void setClientRequestDispatcher(ClientRequestDispatcher clientRequestDispatcher) + { + this.clientRequestDispatcher = clientRequestDispatcher; + } + + public ClientRequestDispatcher getClientRequestDispatcher() + { + return clientRequestDispatcher; + } + + public void setMessageMediator(MessageMediator messageMediator) + { + this.messageMediator = messageMediator; + } + + public MessageMediator getMessageMediator() + { + return messageMediator; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/JIDLLocalCRDImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/JIDLLocalCRDImpl.java new file mode 100644 index 000000000..83329c80a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/JIDLLocalCRDImpl.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.portable.ServantObject; + +import com.sun.corba.ee.spi.orb.ORB ; + + +import com.sun.corba.ee.spi.ior.IOR ; + + +public class JIDLLocalCRDImpl extends LocalClientRequestDispatcherBase +{ + public JIDLLocalCRDImpl( ORB orb, int scid, IOR ior ) + { + super( (com.sun.corba.ee.spi.orb.ORB)orb, scid, ior ) ; + } + + protected ServantObject servant; + + public ServantObject servant_preinvoke(org.omg.CORBA.Object self, + String operation, + Class expectedType) + { + if (!checkForCompatibleServant( servant, expectedType )) + return null ; + + return servant; + } + + public void servant_postinvoke( org.omg.CORBA.Object self, + ServantObject servant ) + { + // NO-OP + } + + // REVISIT - This is called from TOAImpl. + public void setServant( java.lang.Object servant ) + { + if (servant != null && servant instanceof Tie) { + this.servant = new ServantObject(); + this.servant.servant = ((Tie)servant).getTarget(); + } else { + this.servant = null; + } + } + + public void unexport() { + // DO NOT set the IOR to null. (Un)exporting is only concerns + // the servant not the IOR. If the ior is set to null then + // null pointer exceptions happen during a colocated invocation. + // It is better to let the invocation proceed and get OBJECT_NOT_EXIST + // from the server side. + //ior = null; + servant = null; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/LocalClientRequestDispatcherBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/LocalClientRequestDispatcherBase.java new file mode 100644 index 000000000..db237fe41 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/LocalClientRequestDispatcherBase.java @@ -0,0 +1,268 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import org.omg.CORBA.TRANSIENT ; +import org.omg.CORBA.SystemException ; + +import org.omg.CORBA.portable.ServantObject; + + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.protocol.ForwardException ; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory; +import com.sun.corba.ee.spi.oa.OADestroyed ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import com.sun.corba.ee.spi.ior.TaggedProfile; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +import com.sun.corba.ee.spi.ior.ObjectId; + +import com.sun.corba.ee.spi.logging.POASystemException; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import com.sun.corba.ee.spi.trace.IsLocal; +import com.sun.corba.ee.spi.trace.Subcontract; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Subcontract +@IsLocal +public abstract class LocalClientRequestDispatcherBase implements LocalClientRequestDispatcher +{ + protected static final POASystemException poaWrapper = + POASystemException.self ; + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // XXX May want to make some of this configuratble as in the remote case + // Should this be unified? How can we better handle this retry/backoff + // implementation with a single implementation? + private static final int INITIAL_BACKOFF = 1 ; // initially start off very small + // because 1 millisecond is a long time for a local call. + + private static final int MAX_BACKOFF = 1000 ; // Never sleep longer than this + private static final int MAX_WAIT_TIME = 10 * 1000 ; // Total time to wait for a local request. + + protected ORB orb; + private int scid; + + // Cached information needed for local dispatch + protected boolean servantIsLocal ; + protected ObjectAdapterFactory oaf ; + protected ObjectAdapterId oaid ; + protected byte[] objectId ; + + // If isNextIsLocalValid.get() == Boolean.TRUE, + // the next call to isLocal should be valid + private static final ThreadLocal isNextCallValid = new ThreadLocal() { + @Override + protected synchronized Object initialValue() { + return Boolean.TRUE; + } + }; + + protected LocalClientRequestDispatcherBase(ORB orb, int scid, IOR ior) + { + this.orb = orb ; + + TaggedProfile prof = ior.getProfile() ; + servantIsLocal = orb.getORBData().isLocalOptimizationAllowed() && + prof.isLocal(); + + ObjectKeyTemplate oktemp = prof.getObjectKeyTemplate() ; + this.scid = oktemp.getSubcontractId() ; + RequestDispatcherRegistry sreg = orb.getRequestDispatcherRegistry() ; + oaf = sreg.getObjectAdapterFactory( scid ) ; + oaid = oktemp.getObjectAdapterId() ; + ObjectId oid = prof.getObjectId() ; + objectId = oid.getId() ; + } + + public byte[] getObjectId() + { + return objectId ; + } + + @IsLocal + public boolean is_local(org.omg.CORBA.Object self) + { + return false; + } + + /* + * Possible paths through + * useLocalInvocation/servant_preinvoke/servant_postinvoke: + * + * A: call useLocalInvocation + * If useLocalInvocation returns false, servant_preinvoke is not called. + * If useLocalInvocation returns true, + * call servant_preinvoke + * If servant_preinvoke returns null, + * goto A + * else + * (local invocation proceeds normally) + * servant_postinvoke is called + * + */ + @IsLocal + public boolean useLocalInvocation( org.omg.CORBA.Object self ) + { + if (isNextCallValid.get() == Boolean.TRUE) { + return servantIsLocal; + } else { + isNextCallValid.set(Boolean.TRUE); + } + + return false ; + } + + @InfoMethod + private void servantNotCompatible() {} + + /** Check that the servant in info (which must not be null) is + * an instance of the expectedType. If not, set the thread local flag + * and return false. + */ + @IsLocal + protected boolean checkForCompatibleServant( ServantObject so, + Class expectedType ) + { + if (so == null) { + return false; + } + + // Normally, this test will never fail. However, if the servant + // and the stub were loaded in different class loaders, this test + // will fail. + if (!expectedType.isInstance( so.servant )) { + servantNotCompatible() ; + isNextCallValid.set( Boolean.FALSE ) ; + + // When servant_preinvoke returns null, the stub will + // recursively re-invoke itself. Thus, the next call made from + // the stub is another useLocalInvocation call. + return false ; + } + + return true ; + } + + // The actual servant_preinvoke implementation, which must be + // overridden. This method may throw exceptions + // which are handled by servant_preinvoke. + protected ServantObject internalPreinvoke( + org.omg.CORBA.Object self, String operation, + Class expectedType ) throws OADestroyed + { + return null ; + } + + // This method is called when OADestroyed is caught. This allows + // subclasses to provide cleanup code if necessary. + protected void cleanupAfterOADestroyed() + { + // Default is NO-OP + } + + @InfoMethod + private void display( String msg ) { } + + @InfoMethod + private void display( String msg, int value ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + + // servant_preinvoke is here to contain the exception handling + // logic that is common to all POA based servant_preinvoke implementations. + @Subcontract + public ServantObject servant_preinvoke( org.omg.CORBA.Object self, + String operation, Class expectedType ) { + + long startTime = -1 ; + long backoff = INITIAL_BACKOFF ; + long maxWait = MAX_WAIT_TIME ; + + while (true) { + try { + display( "Calling internalPreinvoke") ; + return internalPreinvoke( self, operation, expectedType ) ; + } catch (OADestroyed pdes) { + display( "Caught OADestroyed: will retry") ; + cleanupAfterOADestroyed() ; + } catch (TRANSIENT exc) { + display( "Caught transient") ; + // Local calls are very fast, so don't waste time setting + // up to track the time UNLESS the first attempt fails + // with a TRANSIENT exception. + long currentTime = System.currentTimeMillis() ; + + // Delay if not too much time passed, otherwise re-throw + // the TRANSIENT exception. + if (startTime == -1) { + display( "backoff (first retry)", backoff ) ; + startTime = currentTime ; + } else if ((currentTime-startTime) > MAX_WAIT_TIME) { + display( "Total time exceeded", MAX_WAIT_TIME ) ; + throw exc ; + } else { + backoff *= 2 ; + if (backoff > MAX_BACKOFF) { + backoff = MAX_BACKOFF ; + } + + display( "increasing backoff (will retry)", backoff ) ; + } + + try { + Thread.sleep( backoff ) ; + } catch (InterruptedException iexc) { + // As usual, ignore the possible InterruptedException + } + + display( "retry" ) ; + } catch ( ForwardException ex ) { + /* REVISIT + ClientRequestDispatcher csub = (ClientRequestDispatcher) + StubAdapter.getDelegate( ex.forward_reference ) ; + IOR ior = csub.getIOR() ; + setLocatedIOR( ior ) ; + */ + display( "Unsupported ForwardException" ) ; + throw new RuntimeException("deal with this.", ex) ; + } catch ( ThreadDeath ex ) { + // ThreadDeath on the server side should not cause a client + // side thread death in the local case. We want to preserve + // this behavior for location transparency, so that a ThreadDeath + // has the same affect in either the local or remote case. + // The non-colocated case is handled in iiop.ORB.process, which + // throws the same exception. + display( "Caught ThreadDeath") ; + throw wrapper.runtimeexception( ex, ex.getClass().getName(), ex.getMessage() ) ; + } catch ( Throwable t ) { + display( "Caught Throwable") ; + + if (t instanceof SystemException) + throw (SystemException)t ; + + throw poaWrapper.localServantLookup( t ) ; + } + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MessageMediatorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MessageMediatorImpl.java new file mode 100644 index 000000000..6109484a3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MessageMediatorImpl.java @@ -0,0 +1,2214 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.ByteBuffer; +import java.util.EmptyStackException; +import java.util.Iterator; +import java.util.Queue; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.*; +import org.omg.CORBA.Any; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.ExceptionList; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.UnknownUserException; +import org.omg.CORBA.UNKNOWN; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import org.omg.IOP.ExceptionDetailMessage; +import org.omg.IOP.TAG_RMI_CUSTOM_MAX_STREAM_FORMAT; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.MaxStreamFormatVersionComponent; +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; +import com.sun.corba.ee.spi.threadpool.NoSuchWorkQueueException; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.ProtocolHandler; +import com.sun.corba.ee.spi.protocol.RequestId; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.protocol.ForwardException; +import com.sun.corba.ee.spi.servicecontext.MaxStreamFormatVersionServiceContext; +import com.sun.corba.ee.spi.servicecontext.ORBVersionServiceContext; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.servicecontext.ServiceContextsCache; +import com.sun.corba.ee.spi.servicecontext.SendingContextServiceContext; +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.UEInfoServiceContext; +import com.sun.corba.ee.spi.servicecontext.UnknownServiceContext; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.impl.corba.RequestImpl; +import com.sun.corba.ee.impl.encoding.BufferManagerFactory; +import com.sun.corba.ee.impl.encoding.BufferManagerWrite; +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.InterceptorsSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.trace.Subcontract; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Subcontract +@Transport +public class MessageMediatorImpl + implements + MessageMediator, + ProtocolHandler, + MessageHandler, + Work +{ + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + protected static final InterceptorsSystemException interceptorWrapper = + InterceptorsSystemException.self ; + + protected ORB orb; + protected ContactInfo contactInfo; + protected Connection connection; + protected short addrDisposition; + protected CDROutputObject outputObject; + protected CDRInputObject inputObject; + protected Message messageHeader; + protected RequestMessage requestHeader; + protected LocateReplyOrReplyMessage replyHeader; + protected String replyExceptionDetailMessage; + protected IOR replyIOR; + protected Message dispatchHeader; + protected ByteBuffer dispatchByteBuffer; + protected byte streamFormatVersion; + protected boolean streamFormatVersionSet = false; + + protected org.omg.CORBA.Request diiRequest; + + protected boolean cancelRequestAlreadySent = false; + + protected ProtocolHandler protocolHandler; + protected boolean _executeReturnServantInResponseConstructor = false; + protected boolean _executeRemoveThreadInfoInResponseConstructor = false; + protected boolean _executePIInResponseConstructor = false; + + // The localMaxVersion is used for caching the value of + //MaxStreamFormatVersion if the ORB has been created by the app server + private static byte localMaxVersion = ORBUtility.getMaxStreamFormatVersion(); + + // time this CorbaMessageMediator (Work) was added to a WorkQueue. + private long enqueueTime; + + // + // Client-side constructor. + // + public MessageMediatorImpl(ORB orb, + ContactInfo contactInfo, + Connection connection, + GIOPVersion giopVersion, + IOR ior, + int requestId, + short addrDisposition, + String operationName, + boolean isOneWay) + { + this( orb, connection ) ; + + this.contactInfo = contactInfo; + this.addrDisposition = addrDisposition; + + streamFormatVersion = getStreamFormatVersionForThisRequest( + this.contactInfo.getEffectiveTargetIOR(), giopVersion); + + /* Assuming streamFormatVersion can be set to 2 here + * here breaks interoperability + * with SAP, who has an ORB that does not support SFV 2 in + * GIOP 1.2. So we can't optimize this here. + if (orb.getORBData().isAppServerMode() == true) { + streamFormatVersion = localMaxVersion; + } + */ + + streamFormatVersionSet = true; + + byte encodingVersion = + ORBUtility.chooseEncodingVersion(orb, ior, giopVersion); + ORBUtility.pushEncVersionToThreadLocalState(encodingVersion); + requestHeader = MessageBase.createRequest(this.orb, giopVersion, + encodingVersion, requestId, !isOneWay, + this.contactInfo.getEffectiveTargetIOR(), this.addrDisposition, + operationName, + ServiceContextDefaults.makeServiceContexts(orb), null); + } + + // + // Acceptor constructor. + // + private MessageMediatorImpl(ORB orb, + Connection connection) + { + this.orb = orb; + this.connection = connection; + } + + // + // Dispatcher constructor. + // + + // Note: in some cases (e.g., a reply message) this message + // mediator will only be used for dispatch. Then the original + // request side mediator will take over. + public MessageMediatorImpl(ORB orb, + Connection connection, + Message dispatchHeader, + ByteBuffer byteBuffer) + { + this( orb, connection ) ; + this.dispatchHeader = dispatchHeader; + this.dispatchByteBuffer = byteBuffer; + } + + public RequestId getRequestIdFromRawBytes() { + return MessageBase.getRequestIdFromMessageBytes(getDispatchHeader(), dispatchByteBuffer); + } + + //////////////////////////////////////////////////// + // + // MessageMediator + // + + public ORB getBroker() { + return orb; + } + + public ContactInfo getContactInfo() { + return contactInfo; + } + + public Connection getConnection() { + return connection; + } + + public void initializeMessage() { + getRequestHeader().write(outputObject); + } + + public void finishSendingRequest() { + // REVISIT: probably move logic in outputObject to here. + outputObject.finishSendingMessage(); + } + + public CDRInputObject waitForResponse() { + if (getRequestHeader().isResponseExpected()) { + return connection.waitForResponse(this); + } + return null; + } + + public void setOutputObject(CDROutputObject outputObject) { + this.outputObject = outputObject; + } + + public CDROutputObject getOutputObject() { + return outputObject; + } + + public void setInputObject(CDRInputObject inputObject) { + this.inputObject = inputObject; + } + + public CDRInputObject getInputObject() { + return inputObject; + } + + //////////////////////////////////////////////////// + // CorbaMessageMediator + + public void setReplyHeader(LocateReplyOrReplyMessage header) { + this.replyHeader = header; + this.replyIOR = header.getIOR(); + } + + public LocateReplyMessage getLocateReplyHeader() { + return (LocateReplyMessage) replyHeader; + } + + public ReplyMessage getReplyHeader() { + return (ReplyMessage) replyHeader; + } + + public void setReplyExceptionDetailMessage(String message) { + replyExceptionDetailMessage = message; + } + + public RequestMessage getRequestHeader() { + return requestHeader; + } + + public GIOPVersion getGIOPVersion() { + if (messageHeader != null) { + return messageHeader.getGIOPVersion() ; + } + + if (getRequestHeader() == null) { + return GIOPVersion.V1_2 ; + } + + return getRequestHeader().getGIOPVersion(); + } + + public byte getEncodingVersion() { + if (messageHeader != null) { + return messageHeader.getEncodingVersion() ; + } + + if (getRequestHeader() == null) { + return 0 ; + } + + return getRequestHeader().getEncodingVersion(); + } + + public int getRequestId() { + if (getRequestHeader() == null) { + return -1 ; + } + + return getRequestHeader().getRequestId(); + } + + public boolean isOneWay() { + if (getRequestHeader() == null) { + return false ; + } + + return ! getRequestHeader().isResponseExpected(); + } + + public String getOperationName() { + if (getRequestHeader() == null) { + return "UNKNOWN" ; + } + + return getRequestHeader().getOperation(); + } + + public ServiceContexts getRequestServiceContexts() { + if (getRequestHeader() == null) { + return null ; + } + + return getRequestHeader().getServiceContexts(); + } + + public void setRequestServiceContexts(ServiceContexts sc) { + getRequestHeader().setServiceContexts(sc); + } + + public ServiceContexts getReplyServiceContexts() { + return getReplyHeader().getServiceContexts(); + } + + @Subcontract + public void sendCancelRequestIfFinalFragmentNotSent() { + if ((!sentFullMessage()) && sentFragment() && + (!cancelRequestAlreadySent) && !connection.isClosed()) { + + try { + connection.sendCancelRequestWithLock(getGIOPVersion(), + getRequestId()); + // Case: first a location forward, then a marshaling + // exception (e.g., non-serializable object). Only + // send cancel once. + cancelRequestAlreadySent = true; + } catch (SystemException se) { + if (se.minor == ORBUtilSystemException.CONNECTION_REBIND) { + connection.purgeCalls(se, true, false); + } else { + throw se; + } + } catch (IOException e) { + throw interceptorWrapper.ioexceptionDuringCancelRequest( e ); + } + } + } + + @Subcontract + public boolean sentFullMessage() { + if (outputObject == null) { + return false; + } else { + return outputObject.getBufferManager().sentFullMessage(); + } + } + + @Subcontract + public boolean sentFragment() { + if (outputObject != null) { + BufferManagerWrite buffMan = + outputObject.getBufferManager() ; + + if (buffMan != null) { + return outputObject.getBufferManager().sentFragment(); + } + } + + return false ; + } + + public void setDIIInfo(org.omg.CORBA.Request diiRequest) { + this.diiRequest = diiRequest; + } + + public boolean isDIIRequest() { + return diiRequest != null; + } + + @Subcontract + public Exception unmarshalDIIUserException(String repoId, InputStream is) { + if (! isDIIRequest()) { + return null; + } + + ExceptionList _exceptions = diiRequest.exceptions(); + + try { + // Find the typecode for the exception + for (int i=0; i<_exceptions.count() ; i++) { + TypeCode tc = _exceptions.item(i); + if ( tc.id().equals(repoId) ) { + // Since we dont have the actual user exception + // class, the spec says we have to create an + // UnknownUserException and put it in the + // environment. + Any eany = orb.create_any(); + eany.read_value(is, tc); + + return new UnknownUserException(eany); + } + } + } catch (Exception b) { + throw wrapper.unexpectedDiiException(b); + } + + // must be a truly unknown exception + return wrapper.unknownCorbaExc() ; + } + + public void setDIIException(Exception exception) { + diiRequest.env().exception(exception); + } + + public void handleDIIReply(InputStream inputStream) { + if (! isDIIRequest()) { + return; + } + ((RequestImpl)diiRequest).unmarshalReply(inputStream); + } + + public Message getDispatchHeader() { + return dispatchHeader; + } + + public int getThreadPoolToUse() { + int poolToUse = 0; + Message msg = dispatchHeader; + // A null msg should never happen. But, we'll be + // defensive just in case. + if (msg != null) { + poolToUse = msg.getThreadPoolToUse(); + } + return poolToUse; + } + + @InfoMethod + private void reportException( String msg, Throwable thr ) { } + + @InfoMethod + private void reportConnection( Connection conn ) { } + + /** + * NOTE: + * + * This call is the transition from the transport block to the protocol + * block. + */ + @Transport + public boolean dispatch() { + reportConnection( connection ) ; + + try { + boolean result = getProtocolHandler().handleRequest(this); + return result; + } catch (ThreadDeath td) { + try { + connection.purgeCalls(wrapper.connectionAbort(td), false, false); + } catch (Throwable t) { + reportException( "ThreadDeatch exception in dispatch", t ); + } + throw td; + } catch (Throwable ex) { + reportException( "Exception in dispatch", ex ) ; + + try { + if (ex instanceof INTERNAL) { + connection.sendMessageError(GIOPVersion.DEFAULT_VERSION); + } + } catch (IOException e) { + reportException("Exception in sendMessageError", ex); + } + connection.purgeCalls(wrapper.connectionAbort(ex), false, false); + } + return true; + } + + public byte getStreamFormatVersion() + { + // REVISIT: ContactInfo/Acceptor output object factories + // just use this. Maybe need to distinguish: + // createOutputObjectForRequest + // createOutputObjectForReply + // then do getStreamFormatVersionForRequest/ForReply here. + if (streamFormatVersionSet) { + return streamFormatVersion; + } + return getStreamFormatVersionForReply(); + } + + /** + * If the RMI-IIOP maximum stream format version service context + * is present, it indicates the maximum stream format version we + * could use for the reply. If it isn't present, the default is + * 2 for GIOP 1.3 or greater, 1 for lower. + * + * This is only sent on requests. Clients can find out the + * server's maximum by looking for a tagged component in the IOR. + */ + @Transport + public byte getStreamFormatVersionForReply() { + + // NOTE: The request service contexts may indicate the max. + ServiceContexts svc = getRequestServiceContexts(); + + MaxStreamFormatVersionServiceContext msfvsc + = (MaxStreamFormatVersionServiceContext)svc.get( + MaxStreamFormatVersionServiceContext.SERVICE_CONTEXT_ID); + + if (msfvsc != null) { + byte remoteMaxVersion = msfvsc.getMaximumStreamFormatVersion(); + + return (byte)Math.min(localMaxVersion, remoteMaxVersion); + } else { + // Defaults to 1 for GIOP 1.2 or less, 2 for + // GIOP 1.3 or higher. + if (getGIOPVersion().lessThan(GIOPVersion.V1_3)) { + return ORBConstants.STREAM_FORMAT_VERSION_1; + } else { + return ORBConstants.STREAM_FORMAT_VERSION_2; + } + } + } + + public boolean isSystemExceptionReply() { + return replyHeader.getReplyStatus() == ReplyMessage.SYSTEM_EXCEPTION; + } + + public boolean isUserExceptionReply() { + return replyHeader.getReplyStatus() == ReplyMessage.USER_EXCEPTION; + } + + public boolean isLocationForwardReply() { + return ( (replyHeader.getReplyStatus() == ReplyMessage.LOCATION_FORWARD) || + (replyHeader.getReplyStatus() == ReplyMessage.LOCATION_FORWARD_PERM) ); + //return replyHeader.getReplyStatus() == ReplyMessage.LOCATION_FORWARD; + } + + public boolean isDifferentAddrDispositionRequestedReply() { + return replyHeader.getReplyStatus() == ReplyMessage.NEEDS_ADDRESSING_MODE; + } + + public short getAddrDispositionReply() { + return replyHeader.getAddrDisposition(); + } + + public IOR getForwardedIOR() { + return replyHeader.getIOR(); + } + + public SystemException getSystemExceptionReply() { + return replyHeader.getSystemException(replyExceptionDetailMessage); + } + + //////////////////////////////////////////////////// + // + // Used by server side. + // + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + return getRequestHeader().getObjectKeyCacheEntry() ; + } + + public ProtocolHandler getProtocolHandler() { + // REVISIT: should look up in orb registry. + return this; + } + + //////////////////////////////////////////////////// + // + // ResponseHandler + // + + public org.omg.CORBA.portable.OutputStream createReply() { + // Note: relies on side-effect of setting mediator output field. + // REVISIT - cast - need interface + getProtocolHandler().createResponse(this, null); + return getOutputObject(); + } + + public org.omg.CORBA.portable.OutputStream createExceptionReply() { + // Note: relies on side-effect of setting mediator output field. + // REVISIT - cast - need interface + getProtocolHandler().createUserExceptionResponse(this, null); + return getOutputObject(); + } + + public boolean executeReturnServantInResponseConstructor() { + return _executeReturnServantInResponseConstructor; + } + + public void setExecuteReturnServantInResponseConstructor(boolean b) { + _executeReturnServantInResponseConstructor = b; + } + + public boolean executeRemoveThreadInfoInResponseConstructor() { + return _executeRemoveThreadInfoInResponseConstructor; + } + + public void setExecuteRemoveThreadInfoInResponseConstructor(boolean b) { + _executeRemoveThreadInfoInResponseConstructor = b; + } + + public boolean executePIInResponseConstructor() { + return _executePIInResponseConstructor; + } + + public void setExecutePIInResponseConstructor( boolean b ) { + _executePIInResponseConstructor = b; + } + + @Transport + private byte getStreamFormatVersionForThisRequest(IOR ior, GIOPVersion giopVersion) { + + IOR effectiveTargetIOR = + this.contactInfo.getEffectiveTargetIOR(); + IIOPProfileTemplate temp = + (IIOPProfileTemplate)effectiveTargetIOR.getProfile().getTaggedProfileTemplate(); + Iterator iter = temp.iteratorById(TAG_RMI_CUSTOM_MAX_STREAM_FORMAT.value); + if (!iter.hasNext()) { + // Didn't have the max stream format version tagged + // component. + if (giopVersion.lessThan(GIOPVersion.V1_3)) { + return ORBConstants.STREAM_FORMAT_VERSION_1; + } else { + return ORBConstants.STREAM_FORMAT_VERSION_2; + } + } + + byte remoteMaxVersion + = ((MaxStreamFormatVersionComponent)iter.next()).getMaxStreamFormatVersion(); + + return (byte)Math.min(localMaxVersion, remoteMaxVersion); + } + + //////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////// + + // REVISIT - This could be a separate implementation object looked + // up in a registry. However it needs some state in the message + // mediator so combine for now. + + + protected boolean isThreadDone = false; + + @Transport + public boolean handleRequest(MessageMediator messageMediator) { + try { + byte encodingVersion = dispatchHeader.getEncodingVersion(); + ORBUtility.pushEncVersionToThreadLocalState(encodingVersion); + dispatchHeader.callback(this); + } catch (IOException e) { + // REVISIT - this should be handled internally. + } finally { + ORBUtility.popEncVersionFromThreadLocalState(); + } + return isThreadDone; + } + + @InfoMethod + private void messageInfo( Message msg, RequestId rid ) { } + + @InfoMethod + private void connectionInfo( Connection conn ) { } + + + //////////////////////////////////////////////////// + // + // iiop.messages.MessageHandler + // + + @Transport + private void resumeOptimizedReadProcessing(Message message) { + messageInfo( message, message.getCorbaRequestId() ) ; + connectionInfo(connection); + + if (message.moreFragmentsToFollow()) { + generalMessage("getting next fragment"); + + MessageMediator messageMediator = null; + RequestId requestId = message.getCorbaRequestId(); + Queue queue = + connection.getFragmentList(requestId); + + // REVISIT - In the future, the synchronized(queue), + // wait()/notify() construct should be replaced + // with something like a LinkedBlockingQueue + // from java.util.concurrent using its offer() + // and poll() methods. But, at the time of the + // writing of this code, a LinkedBlockingQueue + // implementation is not performing as well as + // the synchronized(queue), wait(), notify() + // implementation. + synchronized (queue) { + while (messageMediator == null) { + if (queue.size() > 0) { + messageMediator = queue.poll(); + } else { + try { + queue.wait(); + } catch (InterruptedException ex) { + wrapper.resumeOptimizedReadThreadInterrupted(ex); + } + } + } + } + + // Add CorbaMessageMediator to ThreadPool's WorkQueue to process the + // next fragment. + // Although we could call messageMeditor.doWork() rather than putting + // the messageMediator on the WorkQueue, we do not because calling + // doWork() would increase the depth of the call stack. Since this + // thread is done processing the Work it was given, it is very likely + // it will be the thread that executes the Work (messageMediator)we + // put the on the WorkQueue here. + addMessageMediatorToWorkQueue(messageMediator); + } else { + if (message.getType() == Message.GIOPFragment || + message.getType() == Message.GIOPCancelRequest) { + // applies to FragmentMessage_1_[1|2] and CancelRequestMessage + // when using non-blocking NIO SocketChannels + RequestId requestId = message.getCorbaRequestId(); + generalMessage( + "done processing fragments (removing fragment list)" ); + connection.removeFragmentList(requestId); + } + } + } + + @InfoMethod + private void poolToUseInfo( int id ) { } + + @Transport + private void addMessageMediatorToWorkQueue(final MessageMediator messageMediator) { + // Add messageMediator to work queue + Throwable throwable = null; + int poolToUse = -1 ; + try { + poolToUse = messageMediator.getThreadPoolToUse(); + poolToUseInfo( poolToUse ) ; + orb.getThreadPoolManager().getThreadPool(poolToUse).getWorkQueue(0). + addWork((MessageMediatorImpl)messageMediator); + } catch (NoSuchThreadPoolException e) { + throwable = e; + } catch (NoSuchWorkQueueException e) { + throwable = e; + } + + // REVISIT: need to close connection? + if (throwable != null) { + reportException("exception from thread pool", throwable); + throw wrapper.noSuchThreadpoolOrQueue(throwable, poolToUse ); + } + } + + @Transport + private void setWorkThenPoolOrResumeOptimizedRead(Message header) { + if (getConnection().getEventHandler().shouldUseSelectThreadToWait()) { + resumeOptimizedReadProcessing(header); + } else { + // Leader/Follower when using reader thread. + // When this thread is done working it will go back in pool. + + isThreadDone = true; + + // First unregister current registration. + orb.getTransportManager().getSelector(0) + .unregisterForEvent(getConnection().getEventHandler()); + // Have another thread become the reader. + orb.getTransportManager().getSelector(0) + .registerForEvent(getConnection().getEventHandler()); + } + } + + @Transport + private void setWorkThenReadOrResumeOptimizedRead(Message header) { + if (getConnection().getEventHandler().shouldUseSelectThreadToWait()) { + resumeOptimizedReadProcessing(header); + } else { + // When using reader thread then wen this thread is + // done working it will continue reading. + isThreadDone = false; + } + } + + private void setInputObject() { + inputObject = new CDRInputObject(orb, getConnection(), dispatchByteBuffer, dispatchHeader); + inputObject.setMessageMediator(this); + } + + private void signalResponseReceived() { + // This will end up using the MessageMediator associated with + // the original request instead of the current mediator (which + // need to be constructed to hold the dispatchBuffer and connection). + connection.getResponseWaitingRoom() + .responseReceived(inputObject); + } + + // This handles message types for which we don't create classes. + @Transport + public void handleInput(Message header) throws IOException { + messageHeader = header; + setWorkThenReadOrResumeOptimizedRead(header); + + switch(header.getType()) { + case Message.GIOPCloseConnection: + generalMessage( "close connection" ) ; + connection.purgeCalls(wrapper.connectionRebind(), true, false); + break; + case Message.GIOPMessageError: + generalMessage( "message error" ) ; + connection.purgeCalls(wrapper.recvMsgError(), true, false); + break; + default: + generalMessage( "default" ) ; + throw wrapper.badGiopRequestType() ; + } + releaseByteBufferToPool(); + } + + @Transport + public void handleInput(RequestMessage_1_0 header) throws IOException { + generalMessage( "GIOP Request 1.0") ; + try { + try { + messageHeader = requestHeader = (RequestMessage) header; + setInputObject(); + } finally { + setWorkThenPoolOrResumeOptimizedRead(header); + } + getProtocolHandler().handleRequest(header, this); + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(RequestMessage_1_1 header) throws IOException { + generalMessage( "GIOP Request 1.1") ; + try { + try { + messageHeader = requestHeader = (RequestMessage) header; + setInputObject(); + connection.serverRequest_1_1_Put(this); + } finally { + setWorkThenPoolOrResumeOptimizedRead(header); + } + getProtocolHandler().handleRequest(header, this); + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @InfoMethod + private void requestIdInfo( int id ) { } + + // REVISIT: this is identical to 1_0 except for fragment part. + @Transport + public void handleInput(RequestMessage_1_2 header) throws IOException { + generalMessage("GIOP Request 1.2") ; + try { + try { + messageHeader = requestHeader = header; + + unmarshalRequestID(header); + requestIdInfo(header.getRequestId()); + setInputObject(); + + // NOTE: in the old code this used to be done conditionally: + // if (header.moreFragmentsToFollow()). + // Now we always put it in. We take it out when + // the response is done. + // This must happen now so if a header is fragmented the stream + // may be found. + connection.serverRequestMapPut(header.getRequestId(), this); + } finally { + // Leader/Follower. + // Note: This *MUST* come after putting stream in above map + // since the header may be fragmented and you do not want to + // start reading and/or processing again until the map above + // is set. + setWorkThenPoolOrResumeOptimizedRead(header); + } + //inputObject.unmarshalHeader(); // done in subcontract. + getProtocolHandler().handleRequest(header, this); + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } finally { + connection.serverRequestMapRemove(header.getRequestId()); + } + } + + private void unmarshalRequestID(Message_1_2 message) { + message.unmarshalRequestID(dispatchByteBuffer); + } + + @Transport + public void handleInput(ReplyMessage_1_0 header) throws IOException { + generalMessage( "GIOP ReplyMessage 1.0") ; + try { + try { + messageHeader = replyHeader = (ReplyMessage) header; + setInputObject(); + + // REVISIT: this should be done by waiting thread. + inputObject.unmarshalHeader(); + + signalResponseReceived(); + } finally{ + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(ReplyMessage_1_1 header) throws IOException { + generalMessage( "GIOP ReplyMessage 1.1" ) ; + try { + messageHeader = replyHeader = (ReplyMessage) header; + setInputObject(); + + if (header.moreFragmentsToFollow()) { + // More fragments are coming to complete this reply, so keep + // a reference to the InputStream so we can add the fragments + connection.clientReply_1_1_Put(this); + + // In 1.1, we can't assume that we have the request ID in the + // first fragment. Thus, another thread is used + // to be the reader while this thread unmarshals + // the extended header and wakes up the client thread. + setWorkThenPoolOrResumeOptimizedRead(header); + + // REVISIT - error handling. + // This must be done now. + inputObject.unmarshalHeader(); + + signalResponseReceived(); + } else { + // Not fragmented, therefore we know the request + // ID is here. Thus, we can unmarshal the extended header + // and wake up the client thread without using a third + // thread as above. + + // REVISIT - error handling during unmarshal. + // This must be done now to get the request id. + inputObject.unmarshalHeader(); + + signalResponseReceived(); + + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @InfoMethod + private void moreFragmentsInfo( boolean moreFragments ) { } + + @Transport + public void handleInput(ReplyMessage_1_2 header) throws IOException { + generalMessage( "GIOP ReplyMessage 1.2" ) ; + try { + try { + messageHeader = replyHeader = (ReplyMessage) header; + + // We know that the request ID is in the first fragment + unmarshalRequestID(header); + requestIdInfo( header.getRequestId() ) ; + moreFragmentsInfo(header.moreFragmentsToFollow()); + setInputObject(); + signalResponseReceived(); + } finally { + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(LocateRequestMessage_1_0 header) throws IOException { + generalMessage( "GIOP LocateRequestMessage 1.0" ) ; + try { + try { + messageHeader = header; + setInputObject(); + } finally { + setWorkThenPoolOrResumeOptimizedRead(header); + } + getProtocolHandler().handleRequest(header, this); + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + + } + + @Transport + public void handleInput(LocateRequestMessage_1_1 header) throws IOException { + generalMessage( "GIOP LocateRequestMessage 1.1" ) ; + try { + try { + messageHeader = header; + setInputObject(); + } finally { + setWorkThenPoolOrResumeOptimizedRead(header); + } + getProtocolHandler().handleRequest(header, this); + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(LocateRequestMessage_1_2 header) throws IOException { + generalMessage( "GIOP LocateRequestMessage 1.2" ) ; + try { + try { + messageHeader = header; + + unmarshalRequestID(header); + setInputObject(); + + requestIdInfo(header.getRequestId()); + moreFragmentsInfo(header.moreFragmentsToFollow()); + + if (header.moreFragmentsToFollow()) { + connection.serverRequestMapPut(header.getRequestId(),this); + } + } finally { + setWorkThenPoolOrResumeOptimizedRead(header); + } + getProtocolHandler().handleRequest(header, this); + } catch (Throwable t) { + reportException( "", t ) ; + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(LocateReplyMessage_1_0 header) throws IOException { + generalMessage("GIOP LocateReplyMessage 1.0"); + try { + try { + messageHeader = header; + setInputObject(); + inputObject.unmarshalHeader(); // REVISIT Put in subcontract. + signalResponseReceived(); + } finally { + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException("", t); + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(LocateReplyMessage_1_1 header) throws IOException { + generalMessage("GIOP LocateReplyMessage 1.1"); + try { + try { + messageHeader = header; + setInputObject(); + // Fragmented LocateReplies are not allowed in 1.1. + inputObject.unmarshalHeader(); + signalResponseReceived(); + } finally { + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException("", t); + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(LocateReplyMessage_1_2 header) throws IOException { + generalMessage("GIOP LocateReplyMessage 1.2"); + try { + try { + messageHeader = header; + + // No need to put in client reply map - already there. + unmarshalRequestID(header); + setInputObject(); + + requestIdInfo(header.getRequestId()); + + signalResponseReceived(); + } finally { + setWorkThenPoolOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException("", t); + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(FragmentMessage_1_1 header) throws IOException { + generalMessage("GIOP FragmentMessage 1.1"); + try { + moreFragmentsInfo(header.moreFragmentsToFollow()); + + try { + messageHeader = header; + MessageMediator mediator = null; + CDRInputObject inObj = null; + + if (connection.isServer()) { + mediator = connection.serverRequest_1_1_Get(); + } else { + mediator = connection.clientReply_1_1_Get(); + } + + if (mediator != null) { + inObj = mediator.getInputObject(); + } + + // If no input stream available, then discard the fragment. + // This can happen: + // 1. if a fragment message is received prior to receiving + // the original request/reply message. Very unlikely. + // 2. if a fragment message is received after the + // reply has been sent (early replies) + // Note: In the case of early replies, the fragments received + // during the request processing (which are never unmarshaled), + // will eventually be discarded by the GC. + if (inObj == null) { + generalMessage( "No input stream: discarding fragment") ; + // need to release dispatchByteBuffer to pool if we are discarding + releaseByteBufferToPool(); + return; + } + + inObj.addFragment(header, dispatchByteBuffer); + + if (! header.moreFragmentsToFollow()) { + if (connection.isServer()) { + connection.serverRequest_1_1_Remove(); + } else { + connection.clientReply_1_1_Remove(); + } + } + } finally { + // NOTE: This *must* come after queing the fragment + // when using the selector to ensure fragments stay in order. + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException("", t); + // Mask the exception from thread.; + } + } + + @Transport + public void handleInput(FragmentMessage_1_2 header) throws IOException { + generalMessage("GIOP FragmentMessage 1.1"); + try { + try { + messageHeader = header; + + // Note: We know it's a 1.2 fragment, we have the data, but + // we need the IIOPInputStream instance to unmarshal the + // request ID... but we need the request ID to get the + // IIOPInputStream instance. So we peek at the raw bytes. + + unmarshalRequestID(header); + + requestIdInfo(header.getRequestId()); + moreFragmentsInfo(header.moreFragmentsToFollow()); + + MessageMediator mediator = null; + CDRInputObject inObj = null; + + if (connection.isServer()) { + mediator = + connection.serverRequestMapGet(header.getRequestId()); + } else { + mediator = + connection.clientRequestMapGet(header.getRequestId()); + } + + if (mediator != null) { + inObj = mediator.getInputObject(); + } + + // See 1.1 comments. + if (inObj == null) { + generalMessage( "No input stream: discarding fragment") ; + + // need to release dispatchByteBuffer to pool if + // we are discarding + releaseByteBufferToPool(); + return; + } + inObj.addFragment(header, dispatchByteBuffer); + + // REVISIT: but if it is a server don't you have to remove the + // stream from the map? + if (! connection.isServer()) { + /* REVISIT + * No need to do anything. + * Should we mark that last was received? + if (! header.moreFragmentsToFollow()) { + // Last fragment. + } + */ + } + } finally { + // NOTE: This *must* come after queing the fragment + // when using the selector to ensure fragments stay in order. + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException("", t); + // Mask the exception from thread.; + } + } + + @InfoMethod + private void reportGIOPVersion( GIOPVersion vers ) { } + + @Transport + public void handleInput(CancelRequestMessage header) throws IOException { + generalMessage("GIOP CancelRequestMessage"); + try { + try { + messageHeader = header; + setInputObject(); + + // REVISIT: Move these two to subcontract. + inputObject.unmarshalHeader(); + + requestIdInfo(header.getRequestId()); + reportGIOPVersion(header.getGIOPVersion()); + + processCancelRequest(header.getRequestId()); + releaseByteBufferToPool(); + } finally { + setWorkThenReadOrResumeOptimizedRead(header); + } + } catch (Throwable t) { + reportException("", t); + // Mask the exception from thread.; + } + } + + private void throwNotImplemented(String msg) { + throw new RuntimeException( + "CorbaMessageMediatorImpl: not implemented " + msg); + } + + // REVISIT: move this to subcontract (but both client and server need it). + @Transport + private void processCancelRequest(int cancelReqId) { + // The GIOP version of CancelRequest does not matter, since + // CancelRequest_1_0 could be sent to cancel a request which + // has a different GIOP version. + + /* + * CancelRequest processing logic : + * + * - find the request with matching requestId + * + * - call cancelProcessing() in BufferManagerRead [BMR] + * + * - the hope is that worker thread would call BMR.underflow() + * to wait for more fragments to come in. When BMR.underflow() is + * called, if a CancelRequest had already arrived, + * the worker thread would throw ThreadDeath, + * else the thread would wait to be notified of the + * arrival of a new fragment or CancelRequest. Upon notification, + * the woken up thread would check to see if a CancelRequest had + * arrived and if so throw a ThreadDeath or it will continue to + * process the received fragment. + * + * - if all the fragments had been received prior to CancelRequest + * then the worker thread would never block in BMR.underflow(). + * So, setting the abort flag in BMR has no effect. The request + * processing will complete normally. + * + * - in the case where the server has received enough fragments to + * start processing the request and the server sends out + * an early reply. In such a case if the CancelRequest arrives + * after the reply has been sent, it has no effect. + */ + + if (!connection.isServer()) { + return; // we do not support bi-directional giop yet, ignore. + } + + // Try to get hold of the InputStream buffer. + // In the case of 1.0 requests there is no way to get hold of + // InputStream. Try out the 1.1 and 1.2 cases. + + // was the request 1.2 ? + MessageMediator mediator = connection.serverRequestMapGet(cancelReqId); + int requestId ; + if (mediator == null) { + // was the request 1.1 ? + mediator = connection.serverRequest_1_1_Get(); + if (mediator == null) { + wrapper.badCancelRequest() ; + // either the request was 1.0 + // or an early reply has already been sent + // or request processing is over + // or its a spurious CancelRequest + return; // do nothing. + } + + requestId = (mediator).getRequestId(); + + if (requestId != cancelReqId) { + // A spurious 1.1 CancelRequest has been received. + wrapper.bad1_1CancelRequestReceived() ; + return; // do nothing + } + + if (requestId == 0) { // special case + wrapper.cancelRequestWithId0() ; + // this means that + // 1. the 1.1 requests' requestId has not been received + // i.e., a CancelRequest was received even before the + // 1.1 request was received. The spec disallows this. + // 2. or the 1.1 request has a requestId 0. + // + // It is a little tricky to distinguish these two. So, be + // conservative and do not cancel the request. Downside is that + // 1.1 requests with requestId of 0 will never be cancelled. + return; // do nothing + } + } else { + requestId = (mediator).getRequestId(); + } + + Message msg = (mediator).getRequestHeader(); + if (msg.getType() != Message.GIOPRequest) { + // Any mediator obtained here should only ever be for a GIOP + // request. + wrapper.badMessageTypeForCancel() ; + } + + // At this point we have a valid message mediator that contains + // a valid requestId. + + // at this point we have chosen a request to be cancelled. But we + // do not know if the target object's method has been invoked or not. + // Request input stream being available simply means that the request + // processing is not over yet. simply set the abort flag in the + // BMRS and hope that the worker thread would notice it (this can + // happen only if the request stream is being unmarshalled and the + // target's method has not been invoked yet). This guarantees + // that the requests which have been dispatched to the + // target's method will never be cancelled. + + mediator.getInputObject().cancelProcessing(cancelReqId); + } + + //////////////////////////////////////////////////// + // + // spi.protocol.CorbaProtocolHandler + // + + @Transport + public void handleRequest(RequestMessage msg, + MessageMediator messageMediator) { + try { + beginRequest(messageMediator); + try { + handleRequestRequest(messageMediator); + if (messageMediator.isOneWay()) { + return; + } + } catch (Throwable t) { + if (messageMediator.isOneWay()) { + return; + } + handleThrowableDuringServerDispatch( + messageMediator, t, CompletionStatus.COMPLETED_MAYBE); + } + sendResponse(messageMediator); + } catch (Throwable t) { + wrapper.exceptionInHandleRequestForRequest( t ) ; + dispatchError(messageMediator, "RequestMessage", t); + } finally { + endRequest(messageMediator); + } + } + + @Transport + public void handleRequest(LocateRequestMessage msg, + MessageMediator messageMediator) { + try { + beginRequest(messageMediator); + try { + handleLocateRequest(messageMediator); + } catch (Throwable t) { + handleThrowableDuringServerDispatch( + messageMediator, t, CompletionStatus.COMPLETED_MAYBE); + } + sendResponse(messageMediator); + } catch (Throwable t) { + wrapper.exceptionInHandleRequestForLocateRequest( t ) ; + dispatchError(messageMediator, "LocateRequestMessage", t); + } finally { + endRequest(messageMediator); + } + } + + @Subcontract + private void beginRequest(MessageMediator messageMediator) { + ORB myOrb = messageMediator.getBroker(); + connection.serverRequestProcessingBegins(); + } + + @Subcontract + private void dispatchError(MessageMediator messageMediator, + String msg, Throwable t) { + // REVISIT - this makes hcks sendTwoObjects fail + // messageMediator.getConnection().close(); + } + + @Subcontract + private void sendResponse(MessageMediator messageMediator) { + + if (orb.orbIsShutdown()) { + return; + } + + // REVISIT - type and location + CDROutputObject outObj = messageMediator.getOutputObject(); + if (outObj != null) { + // REVISIT - can be null for TRANSIENT below. + outObj.finishSendingMessage(); + } + } + + @Subcontract + private void endRequest(MessageMediator messageMediator) { + ORB myOrb = messageMediator.getBroker(); + + if (myOrb.orbIsShutdown()) { + return; + } + + // release NIO ByteBuffers to ByteBufferPool + + try { + CDROutputObject outputObj = messageMediator.getOutputObject(); + if (outputObj != null) { + outputObj.close(); + } + CDRInputObject inputObj = messageMediator.getInputObject(); + if (inputObj != null) { + inputObj.close(); + } + } catch (IOException ex) { + // Given what close() does, this catch shouldn't ever happen. + // See CDRInput/OutputObject.close() for more info. + // It also won't result in a Corba error if an IOException happens. + reportException( "", ex ) ; + } finally { + messageMediator.getConnection().serverRequestProcessingEnds(); + } + } + + @Subcontract + protected void handleRequestRequest(MessageMediator messageMediator) { + // Does nothing if already unmarshaled. + messageMediator.getInputObject().unmarshalHeader(); + + ORB myOrb = messageMediator.getBroker(); + if (myOrb.orbIsShutdown()) { + return; + } + + ObjectKey okey = messageMediator.getObjectKeyCacheEntry().getObjectKey(); + + ServerRequestDispatcher sc = okey.getServerRequestDispatcher(); + + if (sc == null) { + throw wrapper.noServerScInDispatch() ; + } + + // NOTE: + // This is necessary so mediator can act as ResponseHandler + // and pass necessary info to response constructors located + // in the subcontract. + // REVISIT - same class right now. + //messageMediator.setProtocolHandler(this); + + try { + myOrb.startingDispatch(); + sc.dispatch(messageMediator); + } finally { + myOrb.finishedDispatch(); + } + } + + @Subcontract + protected void handleLocateRequest(MessageMediator messageMediator) { + ORB myOrb = messageMediator.getBroker(); + LocateRequestMessage msg = (LocateRequestMessage) messageMediator.getDispatchHeader(); + IOR ior = null; + LocateReplyMessage reply = null; + short addrDisp = -1; + + try { + messageMediator.getInputObject().unmarshalHeader(); + ObjectKey okey = msg.getObjectKeyCacheEntry().getObjectKey() ; + ServerRequestDispatcher sc = okey.getServerRequestDispatcher() ; + if (sc == null) { + return; + } + + ior = sc.locate(okey); + + if ( ior == null ) { + reply = MessageBase.createLocateReply( + myOrb, msg.getGIOPVersion(), + msg.getEncodingVersion(), + msg.getRequestId(), + LocateReplyMessage.OBJECT_HERE, null); + + } else { + reply = MessageBase.createLocateReply( + myOrb, msg.getGIOPVersion(), + msg.getEncodingVersion(), + msg.getRequestId(), + LocateReplyMessage.OBJECT_FORWARD, ior); + } + // REVISIT: Should we catch SystemExceptions? + + } catch (AddressingDispositionException ex) { + + // create a response containing the expected target + // addressing disposition. + + reply = MessageBase.createLocateReply( + myOrb, msg.getGIOPVersion(), + msg.getEncodingVersion(), + msg.getRequestId(), + LocateReplyMessage.LOC_NEEDS_ADDRESSING_MODE, null); + + addrDisp = ex.expectedAddrDisp(); + + } catch (RequestCanceledException ex) { + + return; // no need to send reply + + } catch ( Exception ex ) { + + // REVISIT If exception is not OBJECT_NOT_EXIST, it should + // have a different reply + + // This handles OBJECT_NOT_EXIST exceptions thrown in + // the subcontract or obj manager. Send back UNKNOWN_OBJECT. + + reply = MessageBase.createLocateReply( + myOrb, msg.getGIOPVersion(), + msg.getEncodingVersion(), + msg.getRequestId(), + LocateReplyMessage.UNKNOWN_OBJECT, null); + } + + CDROutputObject outObj = createAppropriateOutputObject(messageMediator, msg, reply); + messageMediator.setOutputObject(outObj); + outObj.setMessageMediator(messageMediator); + + reply.write(outObj); + // outputObject.setMessage(reply); // REVISIT - not necessary + if (ior != null) { + ior.write(outObj); + } + if (addrDisp != -1) { + AddressingDispositionHelper.write(outObj, addrDisp); + } + } + + @Subcontract + private CDROutputObject createAppropriateOutputObject( + MessageMediator messageMediator, + Message msg, LocateReplyMessage reply) { + CDROutputObject outObj; + + if (msg.getGIOPVersion().lessThan(GIOPVersion.V1_2)) { + // locate msgs 1.0 & 1.1 :=> grow, + // REVISIT - build from factory + outObj = OutputStreamFactory.newCDROutputObject( messageMediator.getBroker(), this, + GIOPVersion.V1_0, + messageMediator.getConnection(), + reply, + ORBConstants.STREAM_FORMAT_VERSION_1); + } else { + // 1.2 :=> stream + // REVISIT - build from factory + outObj = OutputStreamFactory.newCDROutputObject( messageMediator.getBroker(), messageMediator, + reply, + ORBConstants.STREAM_FORMAT_VERSION_1); + } + return outObj; + } + + @Subcontract + public void handleThrowableDuringServerDispatch( + MessageMediator messageMediator, + Throwable throwable, + CompletionStatus completionStatus) { + + // If we haven't unmarshaled the header, we probably don't + // have enough information to even send back a reply. + + // REVISIT + // Cannot do this check. When target addressing disposition does + // not match (during header unmarshaling) it throws an exception + // to be handled here. + /* + if (! ((CDRInputObject)messageMediator.getInputObject()) + .unmarshaledHeader()) { + return; + } + */ + handleThrowableDuringServerDispatch(messageMediator, throwable, + completionStatus, 1); + } + + + // REVISIT - catch and ignore RequestCanceledException. + + @Subcontract + protected void handleThrowableDuringServerDispatch( + MessageMediator messageMediator, + Throwable throwable, + CompletionStatus completionStatus, + int iteration) { + + if (iteration > 10) { + throw new RuntimeException("handleThrowableDuringServerDispatch: " + + "cannot create response.", throwable); + } + + try { + if (throwable instanceof ForwardException) { + ForwardException fex = (ForwardException)throwable ; + createLocationForward( messageMediator, fex.getIOR(), null ) ; + return; + } + + if (throwable instanceof AddressingDispositionException) { + handleAddressingDisposition( + messageMediator, + (AddressingDispositionException)throwable); + return; + } + + // Else. + + SystemException sex = + convertThrowableToSystemException(throwable, completionStatus); + + createSystemExceptionResponse(messageMediator, sex, null); + return; + + } catch (Throwable throwable2) { + + // User code (e.g., postinvoke, interceptors) may change + // the exception, so we end up back here. + // Report the changed exception. + + handleThrowableDuringServerDispatch(messageMediator, + throwable2, + completionStatus, + iteration + 1); + return; + } + } + + @Subcontract + protected SystemException convertThrowableToSystemException( + Throwable throwable, CompletionStatus completionStatus) { + + if (throwable instanceof SystemException) { + return (SystemException)throwable; + } + + if (throwable instanceof RequestCanceledException) { + // Reporting an exception response causes the + // poa current stack, the interceptor stacks, etc. + // to be balanced. It also notifies interceptors + // that the request was cancelled. + + return wrapper.requestCanceled( throwable ) ; + } + + // NOTE: We do not trap ThreadDeath above Throwable. + // There is no reason to stop the thread. It is + // just a worker thread. The ORB never throws + // ThreadDeath. Client code may (e.g., in ServanoutputObjecttManagers, + // interceptors, or servants) but that should not + // effect the ORB threads. So it is just handled + // generically. + + // + // Last resort. + // If user code throws a non-SystemException report it generically. + // + + return wrapper.runtimeexception( throwable, + throwable.getClass().getName(), throwable.getMessage()); + } + + @Subcontract + protected void handleAddressingDisposition( + MessageMediator messageMediator, + AddressingDispositionException ex) { + + short addrDisp = -1; + + // from iiop.RequestProcessor. + + // Respond with expected target addressing disposition. + + switch (messageMediator.getRequestHeader().getType()) { + case Message.GIOPRequest : + ORB myOrb = messageMediator.getBroker() ; + + ReplyMessage repHdr = MessageBase.createReply( myOrb, + messageMediator.getGIOPVersion(), + messageMediator.getEncodingVersion(), + messageMediator.getRequestId(), + ReplyMessage.NEEDS_ADDRESSING_MODE, + ServiceContextDefaults.makeServiceContexts(myOrb), null); + + // REVISIT: via acceptor factory. + CDROutputObject outObj = OutputStreamFactory.newCDROutputObject( + messageMediator.getBroker(), + this, + messageMediator.getGIOPVersion(), + messageMediator.getConnection(), + repHdr, + ORBConstants.STREAM_FORMAT_VERSION_1); + messageMediator.setOutputObject(outObj); + outObj.setMessageMediator(messageMediator); + repHdr.write(outObj); + AddressingDispositionHelper.write(outObj, + ex.expectedAddrDisp()); + return; + + case Message.GIOPLocateRequest : + LocateReplyMessage locateReplyHeader = MessageBase.createLocateReply( + + messageMediator.getBroker(), + messageMediator.getGIOPVersion(), + messageMediator.getEncodingVersion(), messageMediator.getRequestId(), + LocateReplyMessage.LOC_NEEDS_ADDRESSING_MODE, + null); + + addrDisp = ex.expectedAddrDisp(); + + // REVISIT: via acceptor factory. + outObj = + createAppropriateOutputObject(messageMediator, + messageMediator.getRequestHeader(), + locateReplyHeader); + messageMediator.setOutputObject(outObj); + outObj.setMessageMediator(messageMediator); + locateReplyHeader.write(outObj); + IOR ior = null; + if (ior != null) { + ior.write(outObj); + } + if (addrDisp != -1) { + AddressingDispositionHelper.write(outObj, addrDisp); + } + return; + } + } + + @Subcontract + public MessageMediator createResponse( + MessageMediator messageMediator, ServiceContexts svc) { + // REVISIT: ignore service contexts during framework transition. + // They are set in SubcontractResponseHandler to the wrong connection. + // Then they would be set again here and a duplicate contexts + // exception occurs. + return createResponseHelper( + messageMediator, + getServiceContextsForReply(messageMediator, null)); + } + + @Subcontract + public MessageMediator createUserExceptionResponse( + MessageMediator messageMediator, ServiceContexts svc) { + // REVISIT - same as above + return createResponseHelper( + messageMediator, + getServiceContextsForReply(messageMediator, null), + true); + } + + @Subcontract + public MessageMediator createUnknownExceptionResponse( + MessageMediator messageMediator, UnknownException ex) { + // NOTE: This service context container gets augmented in + // tail call. + ServiceContexts contexts = null; + SystemException sys = new UNKNOWN( 0, + CompletionStatus.COMPLETED_MAYBE); + contexts = ServiceContextDefaults.makeServiceContexts( + messageMediator.getBroker()); + UEInfoServiceContext uei = + ServiceContextDefaults.makeUEInfoServiceContext(sys); + contexts.put( uei ) ; + return createSystemExceptionResponse(messageMediator, sys, contexts); + } + + @Subcontract + public MessageMediator createSystemExceptionResponse( + MessageMediator messageMediator, + SystemException ex, + ServiceContexts svc) { + if (messageMediator.getConnection() != null) { + // It is possible that fragments of response have already been + // sent. Then an error may occur (e.g. marshaling error like + // non serializable object). In that case it is too late + // to send the exception. We just return the existing fragmented + // stream here. This will cause an incomplete last fragment + // to be sent. Then the other side will get a marshaling error + // when attempting to unmarshal. + + // REVISIT: Impl - make interface method to do the following. + MessageMediatorImpl mediator = (MessageMediatorImpl) + messageMediator.getConnection() + .serverRequestMapGet(messageMediator.getRequestId()); + + CDROutputObject existingOutputObject = null; + if (mediator != null) { + existingOutputObject = mediator.getOutputObject(); + } + + // REVISIT: need to think about messageMediator containing correct + // pointer to output object. + if (existingOutputObject != null && + mediator.sentFragment() && + ! mediator.sentFullMessage()) + { + return mediator; + } + } + + // Only do this if interceptors have been initialized on this request + // and have not completed their lifecycle (otherwise the info stack + // may be empty or have a different request's entry on top). + if (messageMediator.executePIInResponseConstructor()) { + // REVISIT: not necessary in framework now? + // Inform Portable Interceptors of the SystemException. This is + // required to be done here because the ending interception point + // is called in the when creating the response below + // but we do not currently write the SystemException into the + // response until after the ending point is called. + messageMediator.getBroker().getPIHandler().setServerPIInfo( ex ); + } + + if (ex != null) { + reportException( "Creating system exception response for", ex ) ; + } + + ServiceContexts serviceContexts = + getServiceContextsForReply(messageMediator, svc); + + // NOTE: We MUST add the service context before creating + // the response since service contexts are written to the + // stream when the response object is created. + + addExceptionDetailMessage(messageMediator, ex, serviceContexts); + + MessageMediator response = + createResponseHelper(messageMediator, serviceContexts, false); + + // NOTE: From here on, it is too late to add more service contexts. + // They have already been serialized to the stream (and maybe fragments + // sent). + + ORBUtility.writeSystemException( + ex, (OutputStream)response.getOutputObject()); + + return response; + } + + @Subcontract + private void addExceptionDetailMessage(MessageMediator mediator, + SystemException ex, ServiceContexts serviceContexts) { + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintWriter pw = new PrintWriter(baos); + ex.printStackTrace(pw); + pw.flush(); // NOTE: you must flush or baos will be empty. + EncapsOutputStream encapsOutputStream = + OutputStreamFactory.newEncapsOutputStream(mediator.getBroker()); + encapsOutputStream.putEndian(); + encapsOutputStream.write_wstring(baos.toString()); + UnknownServiceContext serviceContext = + ServiceContextDefaults.makeUnknownServiceContext( + ExceptionDetailMessage.value, + encapsOutputStream.toByteArray()); + serviceContexts.put(serviceContext); + } + + @Subcontract + public MessageMediator createLocationForward( + MessageMediator messageMediator, IOR ior, ServiceContexts svc) { + + ReplyMessage reply + = MessageBase.createReply( + messageMediator.getBroker(), + messageMediator.getGIOPVersion(), + messageMediator.getEncodingVersion(), messageMediator.getRequestId(), + ReplyMessage.LOCATION_FORWARD, + getServiceContextsForReply(messageMediator, svc), + ior); + + return createResponseHelper(messageMediator, reply, ior); + } + + @Subcontract + protected MessageMediator createResponseHelper( + MessageMediator messageMediator, ServiceContexts svc) { + ReplyMessage message = + MessageBase.createReply( + messageMediator.getBroker(), + messageMediator.getGIOPVersion(), + messageMediator.getEncodingVersion(), messageMediator.getRequestId(), ReplyMessage.NO_EXCEPTION, + svc, + null); + return createResponseHelper(messageMediator, message, null); + } + + @Subcontract + protected MessageMediator createResponseHelper( + MessageMediator messageMediator, ServiceContexts svc, + boolean user) { + + ReplyMessage message = + MessageBase.createReply( + messageMediator.getBroker(), + messageMediator.getGIOPVersion(), + messageMediator.getEncodingVersion(), messageMediator.getRequestId(), + user ? ReplyMessage.USER_EXCEPTION : + ReplyMessage.SYSTEM_EXCEPTION, + svc, + null); + return createResponseHelper(messageMediator, message, null); + } + + @InfoMethod + private void createResponseHelperInfo( ReplyMessage reply ) { } + + // REVISIT - IOR arg is ignored. + @Subcontract + protected MessageMediator createResponseHelper( + MessageMediator messageMediator, ReplyMessage reply, IOR ior) { + // REVISIT - these should be invoked from subcontract. + runServantPostInvoke(messageMediator); + runInterceptors(messageMediator, reply); + runRemoveThreadInfo(messageMediator); + + createResponseHelperInfo(reply); + + messageMediator.setReplyHeader(reply); + + CDROutputObject replyOutputObject; + // REVISIT = do not use null. + // + if (messageMediator.getConnection() == null) { + // REVISIT - needs factory + replyOutputObject = + OutputStreamFactory.newCDROutputObject(orb, messageMediator, + messageMediator.getReplyHeader(), + messageMediator.getStreamFormatVersion(), + BufferManagerFactory.GROW); + } else { + replyOutputObject = messageMediator.getConnection().getAcceptor() + .createOutputObject(messageMediator.getBroker(), messageMediator); + } + messageMediator.setOutputObject(replyOutputObject); + messageMediator.getOutputObject().setMessageMediator(messageMediator); + + reply.write((OutputStream) messageMediator.getOutputObject()); + if (reply.getIOR() != null) { + reply.getIOR().write((OutputStream) messageMediator.getOutputObject()); + } + // REVISIT - not necessary? + //messageMediator.this.replyIOR = reply.getIOR(); + + // NOTE: The mediator holds onto output object so return value + // not really necessary. + return messageMediator; + } + + @Subcontract + protected void runServantPostInvoke(MessageMediator messageMediator) { + // Run ServantLocator::postinvoke. This may cause a SystemException + // which will throw out of the constructor and return later + // to construct a reply for that exception. The internal logic + // of returnServant makes sure that postinvoke is only called once. + // REVISIT: instead of instanceof, put method on all orbs. + ORB myOrb = null; + // This flag is to deal with BootstrapServer use of reply streams, + // with ServerRequestDispatcher's use of reply streams, etc. + if (messageMediator.executeReturnServantInResponseConstructor()) { + // It is possible to get marshaling errors in the skeleton after + // postinvoke has completed. We must set this to false so that + // when the error exception reply is constructed we don't try + // to incorrectly access poa current (which will be the wrong + // one or an empty stack. + messageMediator.setExecuteReturnServantInResponseConstructor(false); + messageMediator.setExecuteRemoveThreadInfoInResponseConstructor(true); + + try { + myOrb = messageMediator.getBroker(); + OAInvocationInfo info = myOrb.peekInvocationInfo() ; + ObjectAdapter oa = info.oa(); + try { + oa.returnServant() ; + } catch (Throwable thr) { + wrapper.unexpectedException( thr ) ; + + if (thr instanceof Error) { + throw (Error) thr; + } else if (thr instanceof RuntimeException) { + throw (RuntimeException) thr; + } + } finally { + oa.exit(); + } + } catch (EmptyStackException ese) { + throw wrapper.emptyStackRunServantPostInvoke( ese ) ; + } + } + } + + @Subcontract + protected void runInterceptors(MessageMediator messageMediator, + ReplyMessage reply) { + + if( messageMediator.executePIInResponseConstructor() ) { + // Invoke server request ending interception points (send_*): + // Note: this may end up with a SystemException or an internal + // Runtime ForwardRequest + (messageMediator.getBroker()).getPIHandler(). + invokeServerPIEndingPoint( reply ); + + // Note this will be executed even if a ForwardRequest or + // SystemException is thrown by a Portable Interceptors ending + // point since we end up in this constructor again anyway. + (messageMediator.getBroker()).getPIHandler(). + cleanupServerPIRequest(); + + // See createSystemExceptionResponse for why this is necesary. + messageMediator.setExecutePIInResponseConstructor(false); + } + } + + @Subcontract + protected void runRemoveThreadInfo(MessageMediator messageMediator) { + // Once you get here then the final reply is available (i.e., + // postinvoke and interceptors have completed. + if (messageMediator.executeRemoveThreadInfoInResponseConstructor()) { + messageMediator.setExecuteRemoveThreadInfoInResponseConstructor(false); + messageMediator.getBroker().popInvocationInfo() ; + } + } + + @InfoMethod + private void generalMessage( String msg ) { } + + @Subcontract + protected ServiceContexts getServiceContextsForReply( + MessageMediator messageMediator, ServiceContexts contexts) { + Connection c = messageMediator.getConnection(); + + // NOTE : We only want to send the runtime context the first time, + // only in the case where the encoding is set to CDR. + if (contexts == null) { + if (getGIOPVersion().equals(GIOPVersion.V1_2) && + c != null && + c.getBroker().getORBData().alwaysSendCodeSetServiceContext() && + (getEncodingVersion() == ORBConstants.CDR_ENC_VERSION)) { + if (!c.isPostInitialContexts()) { + c.setPostInitialContexts(); + contexts = messageMediator.getBroker(). + getServiceContextsCache().get( + ServiceContextsCache.CASE.SERVER_INITIAL); + } else { + contexts = messageMediator.getBroker(). + getServiceContextsCache().get( + ServiceContextsCache.CASE.SERVER_SUBSEQUENT); + } + return contexts; + } else { + contexts = ServiceContextDefaults.makeServiceContexts( + messageMediator.getBroker()); + } + } + + if (c != null && !c.isPostInitialContexts() && + (getEncodingVersion() == ORBConstants.CDR_ENC_VERSION)) { + c.setPostInitialContexts(); + SendingContextServiceContext scsc = + ServiceContextDefaults.makeSendingContextServiceContext( + messageMediator.getBroker().getFVDCodeBaseIOR()) ; + + if (contexts.get( scsc.getId() ) != null) { + throw wrapper.duplicateSendingContextServiceContext(); + } + + contexts.put( scsc ) ; + generalMessage( "Added SendingContextServiceContext") ; + } + + // send ORBVersion servicecontext as part of the Reply + + ORBVersionServiceContext ovsc + = ServiceContextDefaults.makeORBVersionServiceContext(); + + if (contexts.get( ovsc.getId() ) != null) { + throw wrapper.duplicateOrbVersionServiceContext(); + } + + contexts.put( ovsc ) ; + generalMessage( "Added ORB version service context" ) ; + + return contexts; + } + + @Transport + private void releaseByteBufferToPool() { + if (dispatchByteBuffer != null) { + orb.getByteBufferPool().releaseByteBuffer(dispatchByteBuffer); + } + } + + @Subcontract + public void cancelRequest() { + CDRInputObject inObj = getInputObject(); + if (inObj != null) { + inObj.cancelProcessing(getRequestId()); + } + } + + // + // Work implementation + // + + @InfoMethod + private void ignoringThrowable( Throwable thr ) { } + + /** + * Execute dispatch in its own WorkerThread. Prior to this method being + * called this object must be initialized with a valid connection + * (CorbaConnection), orb (ORB), dispatchHeader (Message) and + * dispatchByteBuffer (ByteBuffer). + */ + @Subcontract + public void doWork() { + try { + dispatch(); + } catch (Throwable t) { + ignoringThrowable(t); + } + } + + public void setEnqueueTime(long timeInMillis) { + enqueueTime = timeInMillis; + } + + public long getEnqueueTime() { + return enqueueTime; + } + + public String getName() { + return toString(); + } +} + +// End of file. + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MessageParserImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MessageParserImpl.java new file mode 100644 index 000000000..6e0fc290c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MessageParserImpl.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.LinkedList; +import java.util.List; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.RequestId; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.protocol.MessageParser; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase; +import com.sun.corba.ee.spi.trace.Giop; +import com.sun.corba.ee.spi.trace.Transport; +import org.omg.CORBA.COMM_FAILURE; + + +/** + * + * An implementation of a MessageParser that knows how to parse + * bytes into a GIOP protocol data unit. + * + * + */ +@Transport +@Giop +public class MessageParserImpl implements MessageParser { + + private static final int NUM_BYTES_IN_INTEGER = 4; + private final static int MESSAGE_LENGTH_INDEX = Message.GIOPMessageHeaderLength - NUM_BYTES_IN_INTEGER; + private final static int MESSAGE_FLAG_INDEX = 6; + final private ORB orb; + private boolean expectingMoreData; + private boolean moreBytesToParse; + private int nextMsgStartPos; + private int sizeNeeded; + /** + * A list of request ids awaiting final fragments. When the size of + * this list is larger than 0, we have received a fragmented message + * and expecting to receive more message fragments for that given + * request id on this list. Hence, if there are entries in this list + * we are expecting more data to arrive. + * We are using a List here rather than a Set since the size of the + * List is expected to be rather small, (i.e. less than size 10). + */ + private List fragmentList; + private ByteBuffer msgByteBuffer; + + /** The buffer which will be returned for additional input. */ + private ByteBuffer remainderBuffer; + + /** wrapped message create by the last call to offerBuffer. **/ + private MessageMediator messageMediator; + private Connection connection; + private boolean expectingFragments; + + /** Creates a new instance of MessageParserImpl */ + public MessageParserImpl(ORB orb) { + this.orb = orb; + this.expectingMoreData = false; + this.moreBytesToParse = false; + this.nextMsgStartPos = 0; + this.fragmentList = new LinkedList(); + this.sizeNeeded = orb.getORBData().getReadByteBufferSize(); + } + + public MessageParserImpl(ORB orb, Connection connection) { + this(orb); + this.connection = connection; + } + + @Transport + public ByteBuffer getNewBufferAndCopyOld(ByteBuffer byteBuffer) { + ByteBuffer newByteBuffer = null; + // Set byteBuffer position to the start position of data to be + // copied into the re-allocated ByteBuffer. + byteBuffer.position(getNextMessageStartPosition()); + newByteBuffer = orb.getByteBufferPool().reAllocate(byteBuffer, + getSizeNeeded()); + setNextMessageStartPosition(0); + return newByteBuffer; + } + + /** + * Is this MessageParser expecting more data ? + * @return - True if more bytes are needed to construct at least one + * GIOP protocol data unit. False, if no additional bytes are + * remain to be parsed into a GIOP protocol data unit. + */ + public boolean isExpectingMoreData() { + return expectingMoreData; + } + + @Override + public boolean isExpectingFragments() { + return expectingFragments; + } + + @Override + public ByteBuffer getMsgByteBuffer() { + return msgByteBuffer; + } + + @Override + public void offerBuffer(ByteBuffer buffer) { + msgByteBuffer = null; + messageMediator = null; + if (buffer == null) return; + + if (!containsFullHeader(buffer) || !containsFullMessage(buffer)) + remainderBuffer = buffer; + else { + remainderBuffer = splitAndReturnRemainder(buffer, getTotalMessageLength(buffer)); + MessageBase message = MessageBase.parseGiopHeader(orb, connection, buffer, 0); + messageMediator = new MessageMediatorImpl(orb, connection, message, buffer); + msgByteBuffer = buffer; + expectingFragments = message.moreFragmentsToFollow(); + } + + } + + /** + * Splits the specified buffer at the specified position, returning the first part and + * setting {@link #remainderBuffer} to the second, or null if there is no data in the second. + * The split position must be no greater than the limit. + */ + private ByteBuffer splitAndReturnRemainder(ByteBuffer buffer, int splitPosition) { + assert splitPosition <= buffer.limit(); + + if (buffer.limit() == splitPosition) + return null; + else { + final int oldPosition = buffer.position(); + buffer.position(splitPosition); + ByteBuffer remainderBuffer = buffer.slice(); + buffer.position(oldPosition); + buffer.limit(splitPosition); + return remainderBuffer; + } + } + + private boolean containsFullHeader(ByteBuffer buffer) { + return buffer.remaining() >= Message.GIOPMessageHeaderLength; + } + + private boolean containsFullMessage(ByteBuffer buffer) { + return containsFullHeader(buffer) && buffer.remaining() >= getTotalMessageLength(buffer); + } + + private int getTotalMessageLength(ByteBuffer buffer) { + return Message.GIOPMessageHeaderLength + getMessageBodyLength(buffer); + } + + private int getMessageBodyLength(ByteBuffer buffer) { + buffer.order(getByteOrder(buffer.get(MESSAGE_FLAG_INDEX))); + return buffer.getInt(MESSAGE_LENGTH_INDEX); + } + + private ByteOrder getByteOrder(byte messageFlag) { + return (messageFlag & Message.LITTLE_ENDIAN_BIT) == 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; + } + + @Override + public ByteBuffer getRemainderBuffer() { + return remainderBuffer; + } + + @Override + public MessageMediator getMessageMediator() { + return messageMediator; + } + + @Override + public void checkTimeout(long timeSinceLastInput) { + if (isMidMessage() && timeLimitExceeded(timeSinceLastInput)) throw new COMM_FAILURE(); + } + + private boolean timeLimitExceeded(long timeSinceLastInput) { + return timeSinceLastInput > ORBConstants.TRANSPORT_TCP_MAX_TIME_TO_WAIT; + } + + private boolean isMidMessage() { + return expectingFragments || (remainderBuffer != null && !containsFullMessage(remainderBuffer)); + } + + @Transport + public Message parseBytes(ByteBuffer byteBuffer, Connection connection) { + expectingMoreData = false; + remainderBuffer = byteBuffer; + Message message = null; + int bytesInBuffer = byteBuffer.limit() - nextMsgStartPos; + // is there enough bytes available for a message header? + if (bytesInBuffer >= Message.GIOPMessageHeaderLength) { + // get message header + message = MessageBase.parseGiopHeader(orb, connection, byteBuffer, nextMsgStartPos); + + // is there enough bytes for a message body? + if (bytesInBuffer >= message.getSize()) { + + // slice the ByteBuffer into a GIOP PDU + int savedLimit = byteBuffer.limit(); + byteBuffer.position(nextMsgStartPos). + limit(nextMsgStartPos + message.getSize()); + msgByteBuffer = byteBuffer.slice(); + // update nextMsgStartPos and byteBuffer state + nextMsgStartPos = byteBuffer.limit(); + byteBuffer.position(nextMsgStartPos).limit(savedLimit); + + if (message.supportsFragments()) { + if (message.moreFragmentsToFollow()) { + addRequestIdToFragmentList(message, msgByteBuffer); + } else if (isEndOfFragmentList(message)) { + removeRequestIdFromFragmentList(message, msgByteBuffer); + } + expectingMoreData = stillLookingForFragments(); + } + + moreBytesToParse = byteBuffer.hasRemaining(); + if (!moreBytesToParse) byteBuffer.limit(byteBuffer.capacity()); + sizeNeeded = orb.getORBData().getReadByteBufferSize(); + } else { + // set state for next parseBytes invocation + moreBytesToParse = false; + expectingMoreData = true; + // nextMsgStartPos unchanged + byteBuffer.position(byteBuffer.limit()).limit(byteBuffer.capacity()); + sizeNeeded = message.getSize(); + message = null; + } + } else { + // not enough bytes for message header + // set state for next parseBytes invocation + moreBytesToParse = false; + expectingMoreData = true; + // nextMsgStartPos unchanged + byteBuffer.position(byteBuffer.limit()).limit(byteBuffer.capacity()); + sizeNeeded = orb.getORBData().getReadByteBufferSize(); + } + return message; + } + + private boolean stillLookingForFragments() { + return fragmentList.size() > 0; + } + + private boolean isEndOfFragmentList(Message message) { + return message.getType() == MessageBase.GIOPFragment || + message.getType() == MessageBase.GIOPCancelRequest; + } + + private void removeRequestIdFromFragmentList(Message message, ByteBuffer byteBuffer) { + // remove request id from fragmentList + RequestId requestId = MessageBase.getRequestIdFromMessageBytes(message, byteBuffer); + if (fragmentList.size() > 0 && + fragmentList.remove(requestId)) { + } + } + + private void addRequestIdToFragmentList(Message message, ByteBuffer byteBuffer) { + // Add to fragmentList if not already there + RequestId requestId = MessageBase.getRequestIdFromMessageBytes(message, byteBuffer); + if (!fragmentList.contains(requestId)) { + fragmentList.add(requestId); + } + } + + /** + * Are there more bytes to be parsed in the ByteBuffer given + * to this MessageParser's parseBytes ? + * + * This method is typically called after a call to parseBytes() + * to determine if the ByteBuffer has more bytes which need to + * parsed into a Message. + * + * @return true if there are more bytes to be parsed. + * Otherwise false. + */ + public boolean hasMoreBytesToParse() { + return moreBytesToParse; + } + + /** + * Set the starting position where the next message in the + * ByteBuffer given to parseBytes() begins. + */ + public void setNextMessageStartPosition(int position) { + this.nextMsgStartPos = position; + } + + /** + * Get the starting position where the next message in the + * ByteBuffer given to parseBytes() begins. + */ + public int getNextMessageStartPosition() { + return this.nextMsgStartPos; + } + + /** Return a string representing this MessageParser's state */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(toStringPrefix()).append("]"); + return sb.toString(); + } + + /** Return a common String prefix representing this MessageParser's state */ + private String toStringPrefix() { + StringBuilder sb = new StringBuilder(); + sb.append("MessageParserImpl[nextMsgStartPos=").append(nextMsgStartPos).append(", expectingMoreData=").append(expectingMoreData); + sb.append(", moreBytesToParse=").append(moreBytesToParse).append(", fragmentList size=").append(fragmentList.size()); + sb.append(", size needed=").append(sizeNeeded).append("]"); + return sb.toString(); + } + + /** + * Return the suggested number of bytes needed to hold the next message + * to be parsed. + */ + public int getSizeNeeded() { + return sizeNeeded; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MinimalServantCacheLocalCRDImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MinimalServantCacheLocalCRDImpl.java new file mode 100644 index 000000000..5b95a7a6d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/MinimalServantCacheLocalCRDImpl.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol ; + +import org.omg.CORBA.portable.ServantObject ; + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory ; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher ; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.OADestroyed; + +import com.sun.corba.ee.spi.orb.ORB ; + +public class MinimalServantCacheLocalCRDImpl extends ServantCacheLocalCRDBase +{ + public MinimalServantCacheLocalCRDImpl( ORB orb, int scid, IOR ior ) + { + super( (com.sun.corba.ee.spi.orb.ORB)orb, scid, ior ) ; + } + + public ServantObject internalPreinvoke( org.omg.CORBA.Object self, + String operation, Class expectedType ) throws OADestroyed + { + OAInvocationInfo cachedInfo = getCachedInfo() ; + if (checkForCompatibleServant( cachedInfo, expectedType )) + return cachedInfo ; + else + return null ; + } + + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servantobj) + { + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/NotLocalLocalCRDImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/NotLocalLocalCRDImpl.java new file mode 100644 index 000000000..a586e1739 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/NotLocalLocalCRDImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.portable.ServantObject; + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher ; + +/** + * @author Harold Carr + */ + +public class NotLocalLocalCRDImpl implements LocalClientRequestDispatcher +{ + public boolean useLocalInvocation(org.omg.CORBA.Object self) + { + return false; + } + + public boolean is_local(org.omg.CORBA.Object self) + { + return false; + } + + public ServantObject servant_preinvoke(org.omg.CORBA.Object self, + String operation, + Class expectedType) + { + // REVISIT: Rewrite rmic.HelloTest and rmic.LocalStubTest + // (which directly call servant_preinvoke) + // then revert to exception again. + return null; + //throw new INTERNAL(); + } + + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servant) + { + //throw new INTERNAL(); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/POALocalCRDImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/POALocalCRDImpl.java new file mode 100644 index 000000000..51d24e5cd --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/POALocalCRDImpl.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import org.omg.CORBA.portable.ServantObject; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.oa.OAInvocationInfo ; +import com.sun.corba.ee.spi.oa.OADestroyed; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.trace.Subcontract; + +@Subcontract +public class POALocalCRDImpl extends LocalClientRequestDispatcherBase { + + public POALocalCRDImpl( ORB orb, int scid, IOR ior) { + super( orb, scid, ior ); + } + + @Subcontract + private OAInvocationInfo servantEnter( ObjectAdapter oa ) throws OADestroyed { + oa.enter() ; + + OAInvocationInfo info = oa.makeInvocationInfo( objectId ) ; + orb.pushInvocationInfo( info ) ; + + return info ; + } + + @Subcontract + private void servantExit( ObjectAdapter oa ) { + try { + oa.returnServant(); + } finally { + oa.exit() ; + orb.popInvocationInfo() ; + } + } + + // Look up the servant for this request and return it in a + // ServantObject. Note that servant_postinvoke is always called + // by the stub UNLESS this method returns null. However, in all + // cases we must be sure that ObjectAdapter.getServant and + // ObjectAdapter.returnServant calls are paired, as required for + // Portable Interceptors and Servant Locators in the POA. + // Thus, this method must call returnServant if it returns null. + @Subcontract + @Override + public ServantObject internalPreinvoke( org.omg.CORBA.Object self, + String operation, Class expectedType) throws OADestroyed { + + ObjectAdapter oa = null ; + + oa = oaf.find( oaid ) ; + + OAInvocationInfo info = servantEnter( oa ) ; + info.setOperation( operation ) ; + + try { + oa.getInvocationServant( info ); + if (!checkForCompatibleServant( info, expectedType )) { + servantExit( oa ) ; + return null ; + } + + return info ; + } catch (Error err) { + // Cleanup after this call, then throw to allow + // outer try to handle the exception appropriately. + servantExit( oa ) ; + throw err ; + } catch (RuntimeException re) { + // Cleanup after this call, then throw to allow + // outer try to handle the exception appropriately. + servantExit( oa ) ; + throw re ; + } + } + + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servantobj) + { + ObjectAdapter oa = orb.peekInvocationInfo().oa() ; + servantExit( oa ) ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestCanceledException.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestCanceledException.java new file mode 100644 index 000000000..4356de342 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestCanceledException.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +/** + * If this exception is caught explicitly, this need to be rethrown. + */ +public class RequestCanceledException extends RuntimeException { + + private int requestId = 0; + + public RequestCanceledException(int requestId) { + this.requestId = requestId; + } + + public int getRequestId() { + return this.requestId; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestDispatcherRegistryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestDispatcherRegistryImpl.java new file mode 100644 index 000000000..4aaefc6ba --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestDispatcherRegistryImpl.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import java.util.Set; +import java.util.HashSet; +import java.util.Map; +import java.util.HashMap; +import java.util.Collections; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher ; + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory ; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry ; + +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory ; +import org.glassfish.pfl.basic.contain.DenseIntMapImpl; + +/** + * This is a registry of all subcontract ID dependent objects. This includes: + * LocalClientRequestDispatcherFactory, ClientRequestDispatcher, ServerSubcontract, and + * ObjectAdapterFactory. + */ +public class RequestDispatcherRegistryImpl implements RequestDispatcherRegistry { + protected int defaultId; // The default subcontract ID to use if there is no more specific ID available. + // This happens when invoking a foreign IOR. + + private DenseIntMapImpl SDRegistry ; + private DenseIntMapImpl CSRegistry ; + private DenseIntMapImpl OAFRegistry ; + private DenseIntMapImpl LCSFRegistry ; + private Set objectAdapterFactories ; + private Set objectAdapterFactoriesView ; // Read-only view of oaf instances + private Map stringToServerSubcontract ; + + public RequestDispatcherRegistryImpl(int defaultId ) + { + this.defaultId = defaultId; + SDRegistry = new DenseIntMapImpl() ; + CSRegistry = new DenseIntMapImpl() ; + OAFRegistry = new DenseIntMapImpl() ; + LCSFRegistry = new DenseIntMapImpl() ; + objectAdapterFactories = new HashSet() ; + objectAdapterFactoriesView = Collections.unmodifiableSet( objectAdapterFactories ) ; + stringToServerSubcontract = new HashMap() ; + } + + public synchronized void registerClientRequestDispatcher( + ClientRequestDispatcher csc, int scid) + { + CSRegistry.set( scid, csc ) ; + } + + public synchronized void registerLocalClientRequestDispatcherFactory( + LocalClientRequestDispatcherFactory csc, int scid) + { + LCSFRegistry.set( scid, csc ) ; + } + + public synchronized void registerServerRequestDispatcher( + ServerRequestDispatcher ssc, int scid) + { + SDRegistry.set( scid, ssc ) ; + } + + public synchronized void registerServerRequestDispatcher( + ServerRequestDispatcher scc, String name ) + { + stringToServerSubcontract.put( name, scc ) ; + } + + public synchronized void registerObjectAdapterFactory( + ObjectAdapterFactory oaf, int scid) + { + objectAdapterFactories.add( oaf ) ; + OAFRegistry.set( scid, oaf ) ; + } + + // ************************************************** + // Methods to find the subcontract side subcontract + // ************************************************** + + // Note that both forms of getServerRequestDispatcher need to return + // the default server delegate if no other match is found. + // This is essential to proper handling of errors for + // malformed requests. In particular, a bad MAGIC will + // result in a lookup in the named key table (stringToServerSubcontract), + // which must return a valid ServerRequestDispatcher. A bad subcontract ID + // will similarly need to return the default ServerRequestDispatcher. + + public ServerRequestDispatcher getServerRequestDispatcher(int scid) + { + ServerRequestDispatcher sdel = SDRegistry.get(scid) ; + if ( sdel == null ) + sdel = SDRegistry.get(defaultId) ; + + return sdel; + } + + public ServerRequestDispatcher getServerRequestDispatcher( String name ) + { + ServerRequestDispatcher sdel = stringToServerSubcontract.get( name ) ; + + if ( sdel == null ) + sdel = SDRegistry.get(defaultId) ; + + return sdel; + } + + public LocalClientRequestDispatcherFactory getLocalClientRequestDispatcherFactory( + int scid ) + { + LocalClientRequestDispatcherFactory factory = LCSFRegistry.get(scid) ; + if (factory == null) { + factory = LCSFRegistry.get(defaultId) ; + } + + return factory ; + } + + public ClientRequestDispatcher getClientRequestDispatcher( int scid ) + { + ClientRequestDispatcher subcontract = CSRegistry.get(scid) ; + if (subcontract == null) { + subcontract = CSRegistry.get(defaultId) ; + } + + return subcontract ; + } + + public ObjectAdapterFactory getObjectAdapterFactory( int scid ) + { + ObjectAdapterFactory oaf = OAFRegistry.get(scid) ; + if ( oaf == null ) + oaf = OAFRegistry.get(defaultId) ; + + return oaf; + } + + public Set getObjectAdapterFactories() + { + return objectAdapterFactoriesView ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestIdImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestIdImpl.java new file mode 100644 index 000000000..c2ce4ded4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/RequestIdImpl.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.spi.protocol.RequestId; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * Represents a protocol request id. Currently used to ensure proper + * sequencing of fragmented messages. + * + * @author Charlie Hunt + */ +public class RequestIdImpl implements RequestId { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + final private int value; + final private boolean defined; + final static private String UNDEFINED = "?"; + final static public + RequestId UNKNOWN_CORBA_REQUEST_ID = new RequestIdImpl(); + + /** Creetes a new instance of CorbaRequestIdImpl */ + public RequestIdImpl(int requestId) { + this.value = requestId; + this.defined = true; + } + + /** Creates a new instance of CorbaRequestIdImpl */ + private RequestIdImpl() { + this.defined = false; + // initialize value, but note it is a meaningless value + // and should not be used via getValue()! + this.value = -1; + } + + /** Return the value of this CorbaRequestId */ + public int getValue() { + if (defined) { + return this.value; + } else { + throw wrapper.undefinedCorbaRequestIdNotAllowed(); + } + } + + /** Is there a numeric identifier for this CorbaRequestId ? */ + public boolean isDefined() { + return defined; + } + + /** Does this CorbaRequestId equal another CorbaRequestId ? */ + @Override + public boolean equals(Object requestId) { + + if (requestId == null || !(requestId instanceof RequestId)) { + return false; + } + + if (this.isDefined()) { + if (((RequestId)requestId).isDefined()) { + return this.value == ((RequestId)requestId).getValue(); + } else { // requestId is not defined and "this" is defined + return false; + } + } else { + // "this" is not defined + // simply return result of NOT requestId.isDefined() + return !((RequestId)requestId).isDefined(); + } + } + + /** Return this CorbaRequestId's hashCode */ + @Override + public int hashCode() { + return this.value; + } + + /** String representing this CorbaRequestId */ + @Override + public String toString() { + if (defined) { + return Integer.toString(this.value); + } else { + return UNDEFINED; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ServantCacheLocalCRDBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ServantCacheLocalCRDBase.java new file mode 100644 index 000000000..fd702e062 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ServantCacheLocalCRDBase.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.spi.protocol.ForwardException; + +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.oa.OADestroyed; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.trace.Subcontract; + +@Subcontract +public abstract class ServantCacheLocalCRDBase + extends LocalClientRequestDispatcherBase { + + private OAInvocationInfo cachedInfo ; + + protected ServantCacheLocalCRDBase( ORB orb, int scid, IOR ior ) + { + super( orb, scid, ior ) ; + } + + @Subcontract + protected void cleanupAfterOADestroyed() { + cachedInfo = null ; + } + + @Subcontract + protected synchronized OAInvocationInfo getCachedInfo() throws OADestroyed { + if (!servantIsLocal) { + throw poaWrapper.servantMustBeLocal() ; + } + + if (cachedInfo == null) { + updateCachedInfo() ; + } + + return cachedInfo ; + } + + @Subcontract + private void updateCachedInfo() throws OADestroyed { + // If find throws an exception, just let it propagate out + ObjectAdapter oa = oaf.find( oaid ) ; + cachedInfo = oa.makeInvocationInfo( objectId ) ; + oa.enter( ); + + // InvocationInfo must be pushed before calling getInvocationServant + orb.pushInvocationInfo( cachedInfo ) ; + + try { + oa.getInvocationServant( cachedInfo ) ; + } catch (ForwardException freq) { + throw poaWrapper.illegalForwardRequest( freq ) ; + } finally { + oa.returnServant(); + oa.exit(); + orb.popInvocationInfo() ; + } + + return ; + } +} + +// End of File diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ServerRequestDispatcherImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ServerRequestDispatcherImpl.java new file mode 100644 index 000000000..9cc6ca9ab --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/ServerRequestDispatcherImpl.java @@ -0,0 +1,659 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + + + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.Any; + +import org.omg.CORBA.portable.InvokeHandler; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.UnknownException; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory; +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.oa.OADestroyed; +import com.sun.corba.ee.spi.oa.NullServant; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.protocol.ForwardException ; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.ServiceContext; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.servicecontext.UEInfoServiceContext; +import com.sun.corba.ee.spi.servicecontext.CodeSetServiceContext; +import com.sun.corba.ee.spi.servicecontext.SendingContextServiceContext; +import com.sun.corba.ee.spi.servicecontext.ORBVersionServiceContext; + +import com.sun.corba.ee.impl.corba.ServerRequestImpl ; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.MarshalInputStream; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo; +import com.sun.corba.ee.impl.encoding.OSFCodeSetRegistry; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.logging.POASystemException; +import com.sun.corba.ee.spi.trace.Subcontract; +import org.glassfish.pfl.basic.logex.OperationTracer; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Subcontract +public class ServerRequestDispatcherImpl + implements ServerRequestDispatcher +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static final POASystemException poaWrapper = + POASystemException.self ; + + protected ORB orb; // my ORB instance + + public ServerRequestDispatcherImpl(ORB orb) + { + this.orb = orb; + } + + /** Called from ORB.locate when a LocateRequest arrives. + * Result is not always absolutely correct: may indicate OBJECT_HERE + * for non-existent objects, which is resolved on invocation. This + * "bug" is unavoidable, since in general the object may be destroyed + * between a locate and a request. Note that this only checks that + * the appropriate ObjectAdapter is available, not that the servant + * actually exists. + * Need to signal one of OBJECT_HERE, OBJECT_FORWARD, OBJECT_NOT_EXIST. + * @return Result is null if object is (possibly) implemented here, otherwise + * an IOR indicating objref to forward the request to. + * @exception OBJECT_NOT_EXIST is thrown if we know the object does not + * exist here, and we are not forwarding. + */ + @Subcontract + public IOR locate(ObjectKey okey) { + ObjectKeyTemplate oktemp = okey.getTemplate() ; + + try { + checkServerId(okey); + } catch (ForwardException fex) { + return fex.getIOR() ; + } + + // Called only for its side-effect of throwing appropriate exceptions + findObjectAdapter(oktemp); + + return null ; + } + + @InfoMethod + private void generalMessage( String msg ) { } + + @InfoMethod + private void exceptionMessage( String msg, Throwable thr ) { } + + @Subcontract + public void dispatch(MessageMediator request) { + // to set the codebase information, if any transmitted; and also + // appropriate ORB Version. + consumeServiceContexts(request); + + // Now that we have the service contexts processed and the + // correct ORBVersion set, we must finish initializing the + // stream. + ((MarshalInputStream)request.getInputObject()) + .performORBVersionSpecificInit(); + + ObjectKeyCacheEntry entry = request.getObjectKeyCacheEntry() ; + ObjectKey okey = entry.getObjectKey(); + + // Check that this server is the right server + try { + checkServerId(okey); + } catch (ForwardException fex) { + operationAndId(request.getOperationName(), + request.getRequestId()); + + request.getProtocolHandler() + .createLocationForward(request, fex.getIOR(), null); + return; + } + + String operation = request.getOperationName(); + ObjectAdapter objectAdapter = entry.getObjectAdapter() ; + + try { + byte[] objectId = okey.getId().getId() ; + ObjectKeyTemplate oktemp = okey.getTemplate() ; + + if (objectAdapter == null) { + // This call is expensive enough to cache, hence the creation + // of the ObjectKeyCacheEntry mechanism. + objectAdapter = findObjectAdapter(oktemp); + entry.setObjectAdapter( objectAdapter ) ; + } + + java.lang.Object servant = getServantWithPI(request, objectAdapter, + objectId, oktemp, operation); + + dispatchToServant(servant, request, objectId, objectAdapter); + } catch (ForwardException ex) { + generalMessage( "Caught ForwardException") ; + // Thrown by Portable Interceptors from InterceptorInvoker, + // through Response constructor. + request.getProtocolHandler() + .createLocationForward(request, ex.getIOR(), null); + } catch (OADestroyed ex) { + generalMessage( "Caught OADestroyed" ) ; + + // Clear any cached ObjectAdapter in the ObjectKeyCacheEntry, because + // it is no longer valid. + entry.clearObjectAdapter() ; + + // DO NOT CALL releaseServant here! + // The problem is that OADestroyed is only thrown by oa.enter, in + // which case oa.exit should NOT be called, and neither should + // the invocationInfo stack be popped. + + // Destroyed POAs can be recreated by normal adapter activation. + // So just restart the dispatch. + dispatch(request); + } catch (RequestCanceledException ex) { + generalMessage( "Caught RequestCanceledException") ; + + // IDLJ generated non-tie based skeletons do not catch the + // RequestCanceledException. Rethrow the exception, which will + // cause the worker thread to unwind the dispatch and wait for + // other requests. + throw ex; + } catch (UnknownException ex) { + generalMessage( "Caught UnknownException" ) ; + + // RMIC generated tie skeletons convert all Throwable exception + // types (including RequestCanceledException, ThreadDeath) + // thrown during reading fragments into UnknownException. + // If RequestCanceledException was indeed raised, + // then rethrow it, which will eventually cause the worker + // thread to unstack the dispatch and wait for other requests. + if (ex.originalEx instanceof RequestCanceledException) { + throw (RequestCanceledException) ex.originalEx; + } + + ServiceContexts contexts = + ServiceContextDefaults.makeServiceContexts(orb); + UEInfoServiceContext usc = + ServiceContextDefaults.makeUEInfoServiceContext(ex.originalEx); + + contexts.put( usc ) ; + + SystemException sysex = wrapper.unknownExceptionInDispatch( ex ) ; + request.getProtocolHandler() + .createSystemExceptionResponse(request, sysex, + contexts); + } catch (Throwable ex) { + generalMessage( "Caught other exception" ) ; + request.getProtocolHandler() + .handleThrowableDuringServerDispatch( + request, ex, CompletionStatus.COMPLETED_MAYBE); + } + + return; + } + + @Subcontract + private void releaseServant(ObjectAdapter objectAdapter) { + if (objectAdapter == null) { + generalMessage( "Null object adapter" ) ; + return ; + } + + try { + objectAdapter.returnServant(); + } finally { + objectAdapter.exit(); + orb.popInvocationInfo() ; + } + } + + // Note that objectAdapter.enter() must be called before getServant. + @Subcontract + private java.lang.Object getServant(ObjectAdapter objectAdapter, + byte[] objectId, String operation) throws OADestroyed { + + OAInvocationInfo info = objectAdapter.makeInvocationInfo(objectId); + info.setOperation(operation); + orb.pushInvocationInfo(info); + objectAdapter.getInvocationServant(info); + return info.getServantContainer() ; + } + + @Subcontract + protected java.lang.Object getServantWithPI(MessageMediator request, + ObjectAdapter objectAdapter, byte[] objectId, ObjectKeyTemplate oktemp, + String operation) throws OADestroyed { + + // Prepare Portable Interceptors for a new server request + // and invoke receive_request_service_contexts. The starting + // point may throw a SystemException or ForwardException. + orb.getPIHandler().initializeServerPIInfo(request, objectAdapter, + objectId, oktemp); + orb.getPIHandler().invokeServerPIStartingPoint(); + + objectAdapter.enter() ; + + // This must be set just after the enter so that exceptions thrown by + // enter do not cause + // the exception reply to pop the thread stack and do an extra oa.exit. + if (request != null) { + request.setExecuteReturnServantInResponseConstructor(true); + } + + java.lang.Object servant = getServant(objectAdapter, objectId, + operation); + + // Note: we do not know the MDI on a null servant. + // We only end up in that situation if _non_existent called, + // so that the following handleNullServant call does not throw an + // exception. + String mdi = "unknown" ; + + if (servant instanceof NullServant) { + handleNullServant(operation, + (NullServant) servant); + } else { + mdi = objectAdapter.getInterfaces(servant, objectId)[0]; + } + + orb.getPIHandler().setServerPIInfo(servant, mdi); + + if (((servant != null) && + !(servant instanceof org.omg.CORBA.DynamicImplementation) && + !(servant instanceof org.omg.PortableServer.DynamicImplementation)) || + (SpecialMethod.getSpecialMethod(operation) != null)) { + orb.getPIHandler().invokeServerPIIntermediatePoint(); + } + + return servant ; + } + + @Subcontract + protected void checkServerId(ObjectKey okey) { + ObjectKeyTemplate oktemp = okey.getTemplate() ; + int sId = oktemp.getServerId() ; + int scid = oktemp.getSubcontractId() ; + + if (!orb.isLocalServerId(scid, sId)) { + generalMessage("bad server ID"); + orb.handleBadServerId(okey); + } + } + + @Subcontract + private ObjectAdapter findObjectAdapter(ObjectKeyTemplate oktemp) { + RequestDispatcherRegistry scr = orb.getRequestDispatcherRegistry() ; + int scid = oktemp.getSubcontractId() ; + ObjectAdapterFactory oaf = scr.getObjectAdapterFactory(scid); + if (oaf == null) { + throw wrapper.noObjectAdapterFactory() ; + } + + ObjectAdapterId oaid = oktemp.getObjectAdapterId() ; + ObjectAdapter oa = oaf.find(oaid); + + if (oa == null) { + throw wrapper.badAdapterId() ; + } + + return oa ; + } + + /** Always throws OBJECT_NOT_EXIST if operation is not a special method. + * If operation is _non_existent or _not_existent, this will just + * return without performing any action, so that _non_existent can return + * false. Always throws OBJECT_NOT_EXIST for any other special method. + * Update for issue 4385. + */ + @Subcontract + protected void handleNullServant(String operation, NullServant nserv ) { + SpecialMethod specialMethod = SpecialMethod.getSpecialMethod(operation); + + if ((specialMethod == null) || + !specialMethod.isNonExistentMethod()) { + throw nserv.getException() ; + } + } + + @InfoMethod + private void objectInfo( String msg, Object obj ) { } + + @Subcontract + protected void consumeServiceContexts(MessageMediator request) { + operationAndId(request.getOperationName(), request.getRequestId()); + + ServiceContexts ctxts = request.getRequestServiceContexts(); + ServiceContext sc ; + GIOPVersion giopVersion = request.getGIOPVersion(); + + // we cannot depend on this since for our local case, we do not send + // in this service context. Can we rely on just the CodeSetServiceContext? + // boolean rtSC = false; // Runtime ServiceContext + + boolean hasCodeSetContext = processCodeSetContext(request, ctxts); + + objectInfo( "GIOP version", giopVersion ) ; + objectInfo( "Has code set context?" , hasCodeSetContext ) ; + + sc = ctxts.get( + SendingContextServiceContext.SERVICE_CONTEXT_ID ) ; + + if (sc != null) { + SendingContextServiceContext scsc = + (SendingContextServiceContext)sc ; + IOR ior = scsc.getIOR() ; + + try { + request.getConnection().setCodeBaseIOR(ior); + } catch (ThreadDeath td) { + throw td ; + } catch (Throwable t) { + throw wrapper.badStringifiedIor( t ) ; + } + } + + // the RTSC is sent only once during session establishment. We + // need to find out if the CodeBaseRef is already set. If yes, + // then also the rtSC flag needs to be set to true + // this is not possible for the LocalCase since there is no + // IIOPConnection for the LocalCase + + // used for a case where we have JDK 1.3 supporting 1.0 protocol, + // but sending 2 service contexts, that is not normal as per + // GIOP rules, based on above information, we figure out that we + // are talking to the legacy ORB and set the ORB Version Accordingly. + + // this special case tell us that it is legacy SUN orb + // and not a foreign one + // rtSC is not available for localcase due to which this generic + // path would fail if relying on rtSC + //if (giopVersion.equals(GIOPVersion.V1_0) && hasCodeSetContext && rtSC) + boolean isForeignORB = false; + + if (giopVersion.equals(GIOPVersion.V1_0) && hasCodeSetContext) { + generalMessage("Old Sun ORB"); + orb.setORBVersion(ORBVersionFactory.getOLD()) ; + // System.out.println("setting legacy ORB version"); + } else { + // If it didn't include our ORB version service context (below), + // then it must be a foreign ORB. + isForeignORB = true; + } + + // try to get the ORBVersion sent as part of the ServiceContext + // if any + sc = ctxts.get( ORBVersionServiceContext.SERVICE_CONTEXT_ID ) ; + if (sc != null) { + ORBVersionServiceContext ovsc = + (ORBVersionServiceContext) sc; + + ORBVersion version = ovsc.getVersion(); + orb.setORBVersion(version); + + isForeignORB = false; + } + + if (isForeignORB) { + generalMessage("Foreign ORB" ) ; + orb.setORBVersion(ORBVersionFactory.getFOREIGN()); + } + } + + @Subcontract + protected MessageMediator dispatchToServant( + java.lang.Object servant, + MessageMediator req, + byte[] objectId, ObjectAdapter objectAdapter) + { + try { + if (orb.operationTraceDebugFlag) { + OperationTracer.enable() ; + } + + OperationTracer.begin( "Dispatch to servant" ) ; + + operationAndId( req.getOperationName(), req.getRequestId()); + objectInfo( "Servant info", servant ) ; + + MessageMediator response = null ; + + String operation = req.getOperationName() ; + + SpecialMethod method = SpecialMethod.getSpecialMethod(operation) ; + if (method != null) { + objectInfo( "Handling special method", method.getName() ) ; + + response = method.invoke(servant, req, objectId, objectAdapter); + return response ; + } + + // Invoke on the servant using the portable DSI skeleton + if (servant instanceof org.omg.CORBA.DynamicImplementation) { + generalMessage( "Handling old style DSI type servant") ; + + org.omg.CORBA.DynamicImplementation dynimpl = + (org.omg.CORBA.DynamicImplementation)servant; + ServerRequestImpl sreq = new ServerRequestImpl(req, orb); + + // Note: When/if dynimpl.invoke calls arguments() or + // set_exception() then intermediate points are run. + dynimpl.invoke(sreq); + + response = handleDynamicResult(sreq, req); + } else if (servant instanceof org.omg.PortableServer.DynamicImplementation) { + generalMessage( "Handling POA DSI type servant" ) ; + org.omg.PortableServer.DynamicImplementation dynimpl = + (org.omg.PortableServer.DynamicImplementation)servant; + ServerRequestImpl sreq = new ServerRequestImpl(req, orb); + + // Note: When/if dynimpl.invoke calls arguments() or + // set_exception() then intermediate points are run. + dynimpl.invoke(sreq); + + response = handleDynamicResult(sreq, req); + } else { + generalMessage( "Handling invoke handler type servant" ) ; + InvokeHandler invhandle = (InvokeHandler)servant ; + + OutputStream stream = null; + try { + stream = invhandle._invoke(operation, + (org.omg.CORBA.portable.InputStream) req.getInputObject(), + req); + } catch (BAD_OPERATION e) { + wrapper.badOperationFromInvoke(e, operation); + throw e; + } + response = ((CDROutputObject)stream).getMessageMediator(); + } + + return response ; + } finally { + OperationTracer.disable() ; + OperationTracer.finish( ) ; + } + } + + @Subcontract + protected MessageMediator handleDynamicResult( ServerRequestImpl sreq, + MessageMediator req) { + + MessageMediator response = null ; + + // Check if ServerRequestImpl.result() has been called + Any excany = sreq.checkResultCalled(); + + if (excany == null) { // normal return + generalMessage( "Handling normal result" ) ; + + // Marshal out/inout/return parameters into the ReplyMessage + response = sendingReply(req); + OutputStream os = (OutputStream) response.getOutputObject(); + sreq.marshalReplyParams(os); + } else { + generalMessage( "Handling error" ) ; + + response = sendingReply(req, excany); + } + + return response ; + } + + @Subcontract + protected MessageMediator sendingReply(MessageMediator req) { + ServiceContexts scs = ServiceContextDefaults.makeServiceContexts(orb); + return req.getProtocolHandler().createResponse(req, scs); + } + + /** Must always be called, just after the servant's method returns. + * Creates the ReplyMessage header and puts in the transaction context + * if necessary. + */ + @Subcontract + protected MessageMediator sendingReply(MessageMediator req, + Any excany) { + + ServiceContexts scs = ServiceContextDefaults.makeServiceContexts(orb); + operationAndId( req.getOperationName(), req.getRequestId() ) ; + + // Check if the servant set a SystemException or + // UserException + MessageMediator resp; + String repId=null; + try { + repId = excany.type().id(); + } catch (org.omg.CORBA.TypeCodePackage.BadKind e) { + throw wrapper.problemWithExceptionTypecode( e ) ; + } + + if (ORBUtility.isSystemException(repId)) { + generalMessage( "Handling system exception" ) ; + + // Get the exception object from the Any + InputStream in = excany.create_input_stream(); + SystemException ex = ORBUtility.readSystemException(in); + // Marshal the exception back + resp = req.getProtocolHandler() + .createSystemExceptionResponse(req, ex, scs); + } else { + generalMessage( "Handling user exception" ) ; + + resp = req.getProtocolHandler() + .createUserExceptionResponse(req, scs); + OutputStream os = (OutputStream)resp.getOutputObject(); + excany.write_value(os); + } + + return resp; + } + + @InfoMethod + private void codeSetServiceContextInfo( CodeSetServiceContext csctx ) { } + + /** + * Handles setting the connection's code sets if required. + * Returns true if the CodeSetContext was in the request, false + * otherwise. + */ + @Subcontract + protected boolean processCodeSetContext( + MessageMediator request, ServiceContexts contexts) { + + ServiceContext sc = contexts.get( + CodeSetServiceContext.SERVICE_CONTEXT_ID); + + if (sc != null) { + // Somehow a code set service context showed up in the local case. + if (request.getConnection() == null) { + return true; + } + + // If it's GIOP 1.0, it shouldn't have this context at all. Our legacy + // ORBs sent it and we need to know if it's here to make ORB versioning + // decisions, but we don't use the contents. + if (request.getGIOPVersion().equals(GIOPVersion.V1_0)) { + return true; + } + + CodeSetServiceContext cssc = (CodeSetServiceContext)sc ; + CodeSetComponentInfo.CodeSetContext csctx = cssc.getCodeSetContext(); + + // The connection's codeSetContext is null until we've received a + // request with a code set context with the negotiated code sets. + Connection connection = request.getConnection() ; + + synchronized (connection) { + if (connection.getCodeSetContext() == null) { + operationAndId(request.getOperationName(), + request.getRequestId() ); + codeSetServiceContextInfo(cssc); + + connection.setCodeSetContext(csctx); + + // We had to read the method name using ISO 8859-1 + // (which is the default in the CDRInputStream for + // char data), but now we may have a new char + // code set. If it isn't ISO8859-1, we must tell + // the CDR stream to null any converter references + // it has created so that it will reacquire + // the code sets again using the new info. + // + // This should probably compare with the stream's + // char code set rather than assuming it's ISO8859-1. + // (However, the operation name is almost certainly + // ISO8859-1 or ASCII.) + if (csctx.getCharCodeSet() != + OSFCodeSetRegistry.ISO_8859_1.getNumber()) { + ((MarshalInputStream)request.getInputObject()) + .resetCodeSetConverters(); + } + } + } + } + + // If no code set information is ever sent from the client, + // the server will use ISO8859-1 for char and throw an + // exception for any wchar transmissions. + // + // In the local case, we use ORB provided streams for + // marshaling and unmarshaling. Currently, they use + // ISO8859-1 for char/string and UTF16 for wchar/wstring. + return sc != null ; + } + + @InfoMethod + private void operationAndId( String operation, int rid ) { } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/SharedCDRClientRequestDispatcherImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/SharedCDRClientRequestDispatcherImpl.java new file mode 100644 index 000000000..c387248e7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/SharedCDRClientRequestDispatcherImpl.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import java.io.IOException; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.omg.CORBA.portable.ApplicationException; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.trace.Subcontract; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * ClientDelegate is the RMI client-side subcontract or representation + * It implements RMI delegate as well as our internal ClientRequestDispatcher + * interface. + */ +@Subcontract +public class SharedCDRClientRequestDispatcherImpl + extends + ClientRequestDispatcherImpl +{ + + @InfoMethod + private void operationAndId( String msg, int rid ) { } + + // REVISIT: + // Rather than have separate CDR subcontract, + // use same CorbaClientRequestDispatcherImpl but have + // different MessageMediator finishSendingRequest and waitForResponse + // handle what is done below. + // Benefit: then in ContactInfo no need to do a direct new + // of subcontract - does not complicate subcontract registry. + + @Override + @Subcontract + public CDRInputObject marshalingComplete(java.lang.Object self, + CDROutputObject outputObject) + throws + ApplicationException, + org.omg.CORBA.portable.RemarshalException + { + MessageMediator messageMediator = null; + messageMediator = (MessageMediator) + outputObject.getMessageMediator(); + operationAndId( messageMediator.getOperationName(), + messageMediator.getRequestId() ) ; + final ORB orb = (ORB) messageMediator.getBroker(); + operationAndId(messageMediator.getOperationName(), + messageMediator.getRequestId()); + + CDROutputObject cdrOutputObject = outputObject; + final CDROutputObject fCDROutputObject = cdrOutputObject; + + // + // Create server-side input object. + // + + CDRInputObject cdrInputObject = AccessController.doPrivileged( + new PrivilegedAction() { + @Override + public CDRInputObject run() { + return fCDROutputObject.createInputObject(orb); + } + }); + + messageMediator.setInputObject(cdrInputObject); + cdrInputObject.setMessageMediator(messageMediator); + + // + // Dispatch + // + + // REVISIT: Impl cast. + ((MessageMediatorImpl)messageMediator).handleRequestRequest( + messageMediator); + + // InputStream must be closed on the InputObject so that its + // ByteBuffer can be released to the ByteBufferPool. We must do + // this before we re-assign the cdrInputObject reference below. + try { + cdrInputObject.close(); + } catch (IOException ex) { + // No need to do anything since we're done with the input stream + // and cdrInputObject will be re-assigned a new client-side input + // object, (i.e. won't result in a corba error). + // XXX log this + } + + // + // Create client-side input object + // + + cdrOutputObject = messageMediator.getOutputObject(); + final CDROutputObject fCDROutputObject2 = cdrOutputObject; + cdrInputObject = AccessController.doPrivileged( + new PrivilegedAction() { + + @Override + public CDRInputObject run() { + // TODO Auto-generated method stub + return fCDROutputObject2.createInputObject(orb); + } + + }); + messageMediator.setInputObject(cdrInputObject); + cdrInputObject.setMessageMediator(messageMediator); + + cdrInputObject.unmarshalHeader(); + + CDRInputObject inputObject = cdrInputObject; + + return processResponse(orb, messageMediator, inputObject); + } + +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/SpecialMethod.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/SpecialMethod.java new file mode 100644 index 000000000..58414baa6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/SpecialMethod.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol ; + + +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; + +import com.sun.corba.ee.spi.protocol.MessageMediator; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +import com.sun.corba.ee.spi.oa.NullServant ; + +public abstract class SpecialMethod { + static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public abstract boolean isNonExistentMethod() ; + public abstract String getName(); + public abstract MessageMediator invoke(java.lang.Object servant, + MessageMediator request, + byte[] objectId, + ObjectAdapter objectAdapter); + + public static final SpecialMethod getSpecialMethod(String operation) { + for(int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(operation)) { + return methods[i]; + } + } + return null; + } + + static SpecialMethod[] methods = { + new IsA(), + new GetInterface(), + new NonExistent(), + new NotExistent() + }; +} + +class NonExistent extends SpecialMethod { + public boolean isNonExistentMethod() + { + return true ; + } + + public String getName() { // _non_existent + return "_non_existent"; + } + + public MessageMediator invoke(java.lang.Object servant, + MessageMediator request, + byte[] objectId, + ObjectAdapter objectAdapter) + { + boolean result = (servant == null) || (servant instanceof NullServant) ; + MessageMediator response = + request.getProtocolHandler().createResponse(request, null); + ((OutputStream)response.getOutputObject()).write_boolean(result); + return response; + } +} + +class NotExistent extends NonExistent { + @Override + public String getName() { // _not_existent + return "_not_existent"; + } +} + +class IsA extends SpecialMethod { // _is_a + public boolean isNonExistentMethod() + { + return false ; + } + + public String getName() { + return "_is_a"; + } + public MessageMediator invoke(java.lang.Object servant, + MessageMediator request, + byte[] objectId, + ObjectAdapter objectAdapter) + { + if ((servant == null) || (servant instanceof NullServant)) { + return request.getProtocolHandler().createSystemExceptionResponse( + request, wrapper.badSkeleton(), null); + } + + String[] ids = objectAdapter.getInterfaces( servant, objectId ); + String clientId = + ((InputStream)request.getInputObject()).read_string(); + boolean answer = false; + for(int i = 0; i < ids.length; i++) { + if (ids[i].equals(clientId)) { + answer = true; + break; + } + } + + MessageMediator response = + request.getProtocolHandler().createResponse(request, null); + ((OutputStream)response.getOutputObject()).write_boolean(answer); + return response; + } +} + +class GetInterface extends SpecialMethod { // _get_interface + public boolean isNonExistentMethod() + { + return false ; + } + + public String getName() { + return "_interface"; + } + public MessageMediator invoke(java.lang.Object servant, + MessageMediator request, + byte[] objectId, + ObjectAdapter objectAdapter) + { + if ((servant == null) || (servant instanceof NullServant)) { + return request.getProtocolHandler().createSystemExceptionResponse( + request, wrapper.badSkeleton(), null); + } else { + return request.getProtocolHandler().createSystemExceptionResponse( + request, wrapper.getinterfaceNotImplemented(), null); + } + } +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/AddressingDispositionHelper.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/AddressingDispositionHelper.java new file mode 100644 index 000000000..df1cd6454 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/AddressingDispositionHelper.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/AddressingDispositionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +abstract public class AddressingDispositionHelper +{ + private static String _id = "IDL:messages/AddressingDisposition:1.0"; + + public static void insert (org.omg.CORBA.Any a, short that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static short extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.corba.ee.impl.protocol.giopmsgheaders.AddressingDispositionHelper.id (), "AddressingDisposition", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static short read (org.omg.CORBA.portable.InputStream istream) + { + short value = (short)0; + value = istream.read_short (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, short value) + { + ostream.write_short (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage.java new file mode 100644 index 000000000..3ff1bfd21 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +/** + * This interface captures the CancelRequestMessage contract. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface CancelRequestMessage extends Message { + int CANCEL_REQ_MSG_SIZE = 4; + int getRequestId(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_0.java new file mode 100644 index 000000000..8d1127e1d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_0.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +/** + * This implements the GIOP 1.0 CancelRequest header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class CancelRequestMessage_1_0 extends Message_1_0 + implements CancelRequestMessage { + + // Instance variables + + private int request_id = (int) 0; + + // Constructors + + CancelRequestMessage_1_0() {} + + CancelRequestMessage_1_0(int _request_id) { + super(Message.GIOPBigMagic, false, Message.GIOPCancelRequest, + CANCEL_REQ_MSG_SIZE); + request_id = _request_id; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class CancelRequestMessage_1_0 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_1.java new file mode 100644 index 000000000..6930148b3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_1.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +/** + * This implements the GIOP 1.1 CancelRequest header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class CancelRequestMessage_1_1 extends Message_1_1 + implements CancelRequestMessage { + + // Instance variables + + private int request_id = (int) 0; + + // Constructors + + CancelRequestMessage_1_1() {} + + CancelRequestMessage_1_1(int _request_id) { + super(Message.GIOPBigMagic, GIOPVersion.V1_1, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPCancelRequest, CANCEL_REQ_MSG_SIZE); + request_id = _request_id; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class CancelRequestMessage_1_1 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_2.java new file mode 100644 index 000000000..b865f6a2b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/CancelRequestMessage_1_2.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.protocol.RequestId; +import com.sun.corba.ee.impl.protocol.RequestIdImpl; + +/** + * This implements the GIOP 1.2 CancelRequest header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class CancelRequestMessage_1_2 extends Message_1_1 + implements CancelRequestMessage { + + // Instance variables + + private int request_id = (int) 0; + + // Constructors + + CancelRequestMessage_1_2() {} + + CancelRequestMessage_1_2(int _request_id) { + super(Message.GIOPBigMagic, GIOPVersion.V1_2, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPCancelRequest, CANCEL_REQ_MSG_SIZE); + request_id = _request_id; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public RequestId getCorbaRequestId() { + return new RequestIdImpl(getRequestId()); + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class CancelRequestMessage_1_2 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage.java new file mode 100644 index 000000000..a67ab7fb2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +/** + * This interface captures the FragmentMessage contract. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface FragmentMessage extends Message { + int getRequestId(); + int getHeaderLength(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage_1_1.java new file mode 100644 index 000000000..f2cb18b4f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage_1_1.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +/** + * This implements the GIOP 1.1 Fragment header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class FragmentMessage_1_1 extends Message_1_1 + implements FragmentMessage { + + // Constructors + + FragmentMessage_1_1() { + } + + FragmentMessage_1_1(Message_1_1 msg11) { + this.magic = msg11.magic; + this.GIOP_version = msg11.GIOP_version; + this.flags = msg11.flags; + this.message_type = GIOPFragment; + this.message_size = 0; + } + + // Accessor methods + + public int getRequestId() { + return -1; // 1.1 has no fragment header and so no request_id + } + + public int getHeaderLength() { + return GIOPMessageHeaderLength; + } + + // IO methods + + /* This will never be called, since we do not currently read the + * request_id from an CDRInputStream. Instead we use the + * readGIOP_1_1_requestId to read the requestId from a byte buffer. + */ + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + } + + /* 1.1 has no request_id; so nothing to write */ + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class FragmentMessage_1_1 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage_1_2.java new file mode 100644 index 000000000..fd66164bc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/FragmentMessage_1_2.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +/** + * This implements the GIOP 1.2 Fragment header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class FragmentMessage_1_2 extends Message_1_2 + implements FragmentMessage { + + // Constructors + + FragmentMessage_1_2() { + } + + // This is currently never called. + FragmentMessage_1_2(int _request_id) { + super(Message.GIOPBigMagic, GIOPVersion.V1_2, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPFragment, 0); + this.message_type = GIOPFragment; + request_id = _request_id; + } + + FragmentMessage_1_2(Message_1_1 msg12) { + this.magic = msg12.magic; + this.GIOP_version = msg12.GIOP_version; + this.flags = msg12.flags; + this.message_type = GIOPFragment; + this.message_size = 0; + + switch (msg12.message_type) { + case GIOPRequest: + this.request_id = ((RequestMessage) msg12).getRequestId(); + break; + case GIOPReply: + this.request_id = ((ReplyMessage) msg12).getRequestId(); + break; + case GIOPLocateRequest: + this.request_id = ((LocateRequestMessage) msg12).getRequestId(); + break; + case GIOPLocateReply: + this.request_id = ((LocateReplyMessage) msg12).getRequestId(); + break; + case GIOPFragment: + this.request_id = ((FragmentMessage) msg12).getRequestId(); + break; + } + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getHeaderLength() { + return GIOPMessageHeaderLength + 4; + } + + // IO methods + + /* This will never be called, since we do not currently read the + * request_id from an CDRInputStream. Instead we use the + * readGIOP_1_2_requestId to read the requestId from a byte buffer. + */ + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class FragmentMessage_1_2 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfo.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfo.java new file mode 100644 index 000000000..fe2d0087c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfo.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfo.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +public final class IORAddressingInfo implements org.omg.CORBA.portable.IDLEntity +{ + public int selected_profile_index = (int)0; + public org.omg.IOP.IOR ior = null; + + public IORAddressingInfo () + { + } // ctor + + public IORAddressingInfo (int _selected_profile_index, org.omg.IOP.IOR _ior) + { + selected_profile_index = _selected_profile_index; + ior = _ior; + } // ctor + +} // class IORAddressingInfo diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfoHelper.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfoHelper.java new file mode 100644 index 000000000..73c585a99 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfoHelper.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/IORAddressingInfoHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +abstract public class IORAddressingInfoHelper +{ + private static String _id = "IDL:messages/IORAddressingInfo:1.0"; + + public static void insert (org.omg.CORBA.Any a, com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init().get_primitive_tc (org.omg.CORBA.TCKind.tk_ulong); + _members0[0] = new org.omg.CORBA.StructMember ( + "selected_profile_index", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.IOP.IORHelper.type (); + _members0[1] = new org.omg.CORBA.StructMember ( + "ior", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init().create_struct_tc (com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.id (), "IORAddressingInfo", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo value = new com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo (); + value.selected_profile_index = istream.read_ulong (); + value.ior = org.omg.IOP.IORHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo value) + { + ostream.write_ulong (value.selected_profile_index); + org.omg.IOP.IORHelper.write (ostream, value.ior); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/KeyAddr.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/KeyAddr.java new file mode 100644 index 000000000..20c26ebe2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/KeyAddr.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/KeyAddr.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +public interface KeyAddr +{ + public static final short value = (short)(0); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage.java new file mode 100644 index 000000000..58359b6dd --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.SystemException; +import com.sun.corba.ee.spi.ior.IOR; + +/** + * This interface captures the LocateReplyMessage contract. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface LocateReplyMessage extends Message, LocateReplyOrReplyMessage { + + int UNKNOWN_OBJECT = 0; + int OBJECT_HERE = 1; + int OBJECT_FORWARD = 2; + int OBJECT_FORWARD_PERM = 3; // 1.2 + int LOC_SYSTEM_EXCEPTION = 4; // 1.2 + int LOC_NEEDS_ADDRESSING_MODE = 5; // 1.2 +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_0.java new file mode 100644 index 000000000..a2c27d949 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_0.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.SystemException; + +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * This implements the GIOP 1.0 LocateReply header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class LocateReplyMessage_1_0 extends Message_1_0 + implements LocateReplyMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Instance variables + + private ORB orb = null; + private int request_id = (int) 0; + private int locate_status = (int) 0; + private IOR ior = null; + + // Constructors + + LocateReplyMessage_1_0(ORB orb) { + this.orb = orb; + } + + LocateReplyMessage_1_0(ORB orb, int _request_id, + int _locate_status, IOR _ior) { + super(Message.GIOPBigMagic, false, Message.GIOPLocateReply, 0); + this.orb = orb; + request_id = _request_id; + locate_status = _locate_status; + ior = _ior; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getReplyStatus() { + return this.locate_status; + } + + public short getAddrDisposition() { + return KeyAddr.value; + } + + public SystemException getSystemException(String message) { + return null; // 1.0 LocateReply body does not contain SystemException + } + + public IOR getIOR() { + return this.ior; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + this.locate_status = istream.read_long(); + isValidReplyStatus(this.locate_status); // raises exception on error + + // The code below reads the reply body if status is OBJECT_FORWARD + if (this.locate_status == OBJECT_FORWARD) { + CDRInputObject cdr = (CDRInputObject) istream; + this.ior = IORFactories.makeIOR( orb, (InputStream)cdr ) ; + } + } + + // Note, this writes only the header information. + // IOR may be written afterwards into the reply mesg body. + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + ostream.write_long(this.locate_status); + } + + // Static methods + + public static void isValidReplyStatus(int replyStatus) { + switch (replyStatus) { + case UNKNOWN_OBJECT : + case OBJECT_HERE : + case OBJECT_FORWARD : + break; + default : + throw wrapper.illegalReplyStatus() ; + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class LocateReplyMessage_1_0 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_1.java new file mode 100644 index 000000000..81df8a3e1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_1.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.impl.encoding.CDRInputObject; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * This implements the GIOP 1.1 LocateReply header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class LocateReplyMessage_1_1 extends Message_1_1 + implements LocateReplyMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Instance variables + + private ORB orb = null; + private int request_id = 0; + private int reply_status = 0; + private IOR ior = null; + + // Constructors + + LocateReplyMessage_1_1(ORB orb) { + this.orb = orb; + } + + LocateReplyMessage_1_1(ORB orb, int _request_id, + int _reply_status, IOR _ior) { + super(Message.GIOPBigMagic, GIOPVersion.V1_1, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPLocateReply, 0); + this.orb = orb; + request_id = _request_id; + reply_status = _reply_status; + ior = _ior; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getReplyStatus() { + return this.reply_status; + } + + public short getAddrDisposition() { + return KeyAddr.value; + } + + public SystemException getSystemException(String message) { + return null; // 1.0 LocateReply body does not contain SystemException + } + + public IOR getIOR() { + return this.ior; + } + + // IO methods + + @Override + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + this.reply_status = istream.read_long(); + isValidReplyStatus(this.reply_status); // raises exception on error + + // The code below reads the reply body if status is OBJECT_FORWARD + if (this.reply_status == OBJECT_FORWARD) { + CDRInputObject cdr = (CDRInputObject) istream; + this.ior = IORFactories.makeIOR( orb, (InputStream)cdr ) ; + } + } + + // Note, this writes only the header information. SystemException or + // IOR may be written afterwards into the reply mesg body. + @Override + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + ostream.write_long(this.reply_status); + } + + // Static methods + + public static void isValidReplyStatus(int replyStatus) { + switch (replyStatus) { + case UNKNOWN_OBJECT : + case OBJECT_HERE : + case OBJECT_FORWARD : + break; + default : + throw wrapper.illegalReplyStatus(); + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class LocateReplyMessage_1_1 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_2.java new file mode 100644 index 000000000..8bd937636 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyMessage_1_2.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.misc.ORBUtility; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * This implements the GIOP 1.2 LocateReply header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class LocateReplyMessage_1_2 extends Message_1_2 + implements LocateReplyMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self; + + // Instance variables + + private ORB orb = null; + private int reply_status = 0; + private IOR ior = null; + private String exClassName = null; + private int minorCode = 0; + private CompletionStatus completionStatus = null; + private short addrDisposition = KeyAddr.value; // default; + + // Constructors + + LocateReplyMessage_1_2(ORB orb) { + this.orb = orb; + } + + LocateReplyMessage_1_2(ORB orb, int _request_id, + int _reply_status, IOR _ior) { + super(Message.GIOPBigMagic, GIOPVersion.V1_2, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPLocateReply, 0); + this.orb = orb; + request_id = _request_id; + reply_status = _reply_status; + ior = _ior; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getReplyStatus() { + return this.reply_status; + } + + public short getAddrDisposition() { + return this.addrDisposition; + } + + public SystemException getSystemException(String message) { + return MessageBase.getSystemException( + exClassName, minorCode, completionStatus, message, wrapper); + } + + public IOR getIOR() { + return this.ior; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + this.reply_status = istream.read_long(); + isValidReplyStatus(this.reply_status); // raises exception on error + + // GIOP 1.2 LocateReply message bodies are not aligned on + // 8 byte boundaries. + + // The code below reads the reply body in some cases + // LOC_SYSTEM_EXCEPTION & OBJECT_FORWARD & OBJECT_FORWARD_PERM & + // LOC_NEEDS_ADDRESSING_MODE + if (this.reply_status == LOC_SYSTEM_EXCEPTION) { + + String reposId = istream.read_string(); + this.exClassName = ORBUtility.classNameOf(reposId); + this.minorCode = istream.read_long(); + int status = istream.read_long(); + + switch (status) { + case CompletionStatus._COMPLETED_YES: + this.completionStatus = CompletionStatus.COMPLETED_YES; + break; + case CompletionStatus._COMPLETED_NO: + this.completionStatus = CompletionStatus.COMPLETED_NO; + break; + case CompletionStatus._COMPLETED_MAYBE: + this.completionStatus = CompletionStatus.COMPLETED_MAYBE; + break; + default: + throw wrapper.badCompletionStatusInLocateReply(status); + } + } else if ((this.reply_status == OBJECT_FORWARD) || + (this.reply_status == OBJECT_FORWARD_PERM)) { + CDRInputObject cdr = (CDRInputObject) istream; + this.ior = IORFactories.makeIOR(orb, (InputStream) cdr); + } else if (this.reply_status == LOC_NEEDS_ADDRESSING_MODE) { + // read GIOP::AddressingDisposition from body and resend the + // original request using the requested addressing mode. The + // resending is transparent to the caller. + this.addrDisposition = AddressingDispositionHelper.read(istream); + } + } + + // Note, this writes only the header information. SystemException or + // IOR or GIOP::AddressingDisposition may be written afterwards into the + // reply mesg body. + @Override + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + ostream.write_long(this.reply_status); + + + // GIOP 1.2 LocateReply message bodies are not aligned on + // 8 byte boundaries. + } + + // Static methods + + public static void isValidReplyStatus(int replyStatus) { + switch (replyStatus) { + case UNKNOWN_OBJECT: + case OBJECT_HERE: + case OBJECT_FORWARD: + case OBJECT_FORWARD_PERM: + case LOC_SYSTEM_EXCEPTION: + case LOC_NEEDS_ADDRESSING_MODE: + break; + default: + throw wrapper.illegalReplyStatus(); + } + } + + @Override + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class LocateReplyMessage_1_2 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyOrReplyMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyOrReplyMessage.java new file mode 100644 index 000000000..41e3d2bf1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateReplyOrReplyMessage.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.SystemException; +import com.sun.corba.ee.spi.ior.IOR; + +public interface LocateReplyOrReplyMessage extends Message { + + int getRequestId(); + int getReplyStatus(); + SystemException getSystemException(String message); + IOR getIOR(); + short getAddrDisposition(); +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage.java new file mode 100644 index 000000000..c70877b22 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; + +/** + * This interface captures the LocateRequestMessage contract. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface LocateRequestMessage extends Message { + int getRequestId(); + ObjectKeyCacheEntry getObjectKeyCacheEntry(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_0.java new file mode 100644 index 000000000..60124649f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_0.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; + +/** + * This implements the GIOP 1.0 LocateRequest header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class LocateRequestMessage_1_0 extends Message_1_0 + implements LocateRequestMessage { + + // Instance variables + + private ORB orb = null; + private int request_id = (int) 0; + private byte[] object_key = null; + private ObjectKeyCacheEntry entry = null; + + // Constructor + + LocateRequestMessage_1_0(ORB orb) { + this.orb = orb; + } + + LocateRequestMessage_1_0(ORB orb, int _request_id, byte[] _object_key) { + super(Message.GIOPBigMagic, false, Message.GIOPLocateRequest, 0); + this.orb = orb; + request_id = _request_id; + object_key = _object_key; + } + + // Accessor methods (LocateRequestMessage interface) + + public int getRequestId() { + return this.request_id; + } + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + if (this.entry == null) { + // this will raise a MARSHAL exception upon errors. + this.entry = orb.extractObjectKeyCacheEntry(object_key); + } + + return this.entry; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream);; + this.request_id = istream.read_ulong(); + int _len0 = istream.read_long(); + this.object_key = new byte[_len0]; + istream.read_octet_array (this.object_key, 0, _len0); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + nullCheck(this.object_key); + ostream.write_long(this.object_key.length); + ostream.write_octet_array(this.object_key, 0, this.object_key.length); + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class LocateRequestMessage_1_0 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_1.java new file mode 100644 index 000000000..e76f0aac4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_1.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; + +/** + * This implements the GIOP 1.1 LocateRequest header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class LocateRequestMessage_1_1 extends Message_1_1 + implements LocateRequestMessage { + + // Instance variables + + private ORB orb = null; + private int request_id = (int) 0; + private byte[] object_key = null; + private ObjectKeyCacheEntry entry = null; + + // Constructors + + LocateRequestMessage_1_1(ORB orb) { + this.orb = orb; + } + + LocateRequestMessage_1_1(ORB orb, int _request_id, byte[] _object_key) { + super(Message.GIOPBigMagic, GIOPVersion.V1_1, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPLocateRequest, 0); + this.orb = orb; + request_id = _request_id; + object_key = _object_key; + } + + // Accessor methods (LocateRequestMessage interface) + + public int getRequestId() { + return this.request_id; + } + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + if (this.entry == null) { + // this will raise a MARSHAL exception upon errors. + this.entry = orb.extractObjectKeyCacheEntry(object_key); + } + + return this.entry; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + int _len1 = istream.read_long(); + this.object_key = new byte[_len1]; + istream.read_octet_array(this.object_key, 0, _len1); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + nullCheck(this.object_key); + ostream.write_long(this.object_key.length); + ostream.write_octet_array(this.object_key, 0, this.object_key.length); + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class LocateRequestMessage_1_1 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_2.java new file mode 100644 index 000000000..958c4028f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/LocateRequestMessage_1_2.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; + +/** + * This implements the GIOP 1.2 LocateRequest header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class LocateRequestMessage_1_2 extends Message_1_2 + implements LocateRequestMessage { + + // Instance variables + + private ORB orb = null; + private ObjectKeyCacheEntry entry = null; + private TargetAddress target = null; + + // Constructors + + LocateRequestMessage_1_2(ORB orb) { + this.orb = orb; + } + + LocateRequestMessage_1_2(ORB orb, int _request_id, TargetAddress _target) { + super(Message.GIOPBigMagic, GIOPVersion.V1_2, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPLocateRequest, 0); + this.orb = orb; + request_id = _request_id; + target = _target; + } + + // Accessor methods (LocateRequestMessage interface) + + public int getRequestId() { + return this.request_id; + } + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + if (this.entry == null) { + // this will raise a MARSHAL exception upon errors. + this.entry = MessageBase.extractObjectKeyCacheEntry(target, orb); + } + + return this.entry; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + this.target = TargetAddressHelper.read(istream); + getObjectKeyCacheEntry(); // this does AddressingDisposition check + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + nullCheck(this.target); + TargetAddressHelper.write(ostream, this.target); + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class LocateRequestMessage_1_2 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message.java new file mode 100644 index 000000000..393313f30 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.protocol.RequestId; + +/** + * This is the base interface for different message type interfaces. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface Message { + + // Generic constants + + static final int defaultBufferSize = 1024; + static final int GIOPBigMagic = 0x47494F50; + static final int GIOPMessageHeaderLength = 12; + + // Other useful constants + + static final byte LITTLE_ENDIAN_BIT = 0x01; + static final byte MORE_FRAGMENTS_BIT = 0x02; + static final byte FLAG_NO_FRAG_BIG_ENDIAN = 0x00; + static final byte TRAILING_TWO_BIT_BYTE_MASK = 0x3; + static final byte THREAD_POOL_TO_USE_MASK = 0x3F; + + // Message types + + static final byte GIOPRequest = 0; + static final byte GIOPReply = 1; + static final byte GIOPCancelRequest = 2; + static final byte GIOPLocateRequest = 3; + static final byte GIOPLocateReply = 4; + static final byte GIOPCloseConnection = 5; + static final byte GIOPMessageError = 6; + static final byte GIOPFragment = 7; // 1.1 & 1.2: + + /** + * Returns whether the Message supports message fragmenting. + * + * @return true if Message supports fragmenting or is + * a message fragment. Otherwise false it does + * not support message fragments. + */ + boolean supportsFragments(); + + // Accessor methods + + GIOPVersion getGIOPVersion(); + byte getEncodingVersion(); + boolean isLittleEndian(); + boolean moreFragmentsToFollow(); + int getType(); + int getSize(); + + int getThreadPoolToUse(); + + // Mutator methods + + void read(org.omg.CORBA.portable.InputStream istream); + void write(org.omg.CORBA.portable.OutputStream ostream); + + void setSize(ByteBuffer byteBuffer, int size); + + FragmentMessage createFragmentMessage(); + + void callback(MessageHandler handler) throws IOException; + void setEncodingVersion(byte version); + + /** + * Return a Message's CorbaRequestId. Messages which do not support + * a request id in the 4 bytes following the 12 byte GIOP message + * header shall return an undefined CorbaRequestId. + */ + RequestId getCorbaRequestId(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/MessageBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/MessageBase.java new file mode 100644 index 000000000..43f6a30c2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/MessageBase.java @@ -0,0 +1,852 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import java.lang.reflect.Constructor; +import java.nio.ByteBuffer; +import java.util.Iterator; + +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; +import org.omg.IOP.TaggedProfile; + +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.RequestPartitioningComponent; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.misc.ORBClassLoader; +import com.sun.corba.ee.spi.protocol.RequestId; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.TransportManager; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.orb.ObjectKeyCacheEntryNoObjectAdapterImpl; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.protocol.AddressingDispositionException; +import com.sun.corba.ee.impl.protocol.RequestIdImpl; +import com.sun.corba.ee.impl.transport.MessageTraceManagerImpl; +import com.sun.corba.ee.spi.trace.Giop; + +/** + * This class acts as the base class for the various GIOP message types. This + * also serves as a factory to create various message types. We currently + * support GIOP 1.0, 1.1 and 1.2 message types. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +@Giop +public abstract class MessageBase implements Message { + + private int threadPoolToUse; + + // (encodingVersion == 0x00) implies CDR encoding, + // (encodingVersion > 0x00) implies Java serialization encoding version. + private byte encodingVersion = ORBConstants.CDR_ENC_VERSION; + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self; + + // Static methods + + public static String typeToString(byte type) { + String result = type + "/"; + switch (type) { + case GIOPRequest: + result += "GIOPRequest"; + break; + case GIOPReply: + result += "GIOPReply"; + break; + case GIOPCancelRequest: + result += "GIOPCancelRequest"; + break; + case GIOPLocateRequest: + result += "GIOPLocateRequest"; + break; + case GIOPLocateReply: + result += "GIOPLocateReply"; + break; + case GIOPCloseConnection: + result += "GIOPCloseConnection"; + break; + case GIOPMessageError: + result += "GIOPMessageError"; + break; + case GIOPFragment: + result += "GIOPFragment"; + break; + default: + result += "Unknown"; + break; + } + return result; + } + + public static MessageBase parseGiopHeader(ORB orb, + Connection connection, + ByteBuffer buf, + int startPosition) { + + TransportManager ctm = orb.getTransportManager(); + MessageTraceManagerImpl mtm = + (MessageTraceManagerImpl) ctm.getMessageTraceManager(); + if (mtm.isEnabled()) { + mtm.recordHeaderReceived(buf); + } + + // Sanity checks + + /* + * check for magic corruption + * check for version incompatibility + * check if fragmentation is allowed based on mesg type. + . 1.0 fragmentation disallowed; FragmentMessage is non-existent. + . 1.1 only {Request, Reply} msgs maybe fragmented. + . 1.2 only {Request, Reply, LocateRequest, LocateReply} msgs + maybe fragmented. + */ + + byte[] it = new byte[12]; + buf.position(startPosition); + buf.get(it); + + int b1, b2, b3, b4; + b1 = (it[0] << 24) & 0xFF000000; + b2 = (it[1] << 16) & 0x00FF0000; + b3 = (it[2] << 8) & 0x0000FF00; + b4 = (it[3]) & 0x000000FF; + + int magic = (b1 | b2 | b3 | b4); + + if (magic != GIOPBigMagic) { + // If Magic is incorrect, it is an error. + // ACTION : send MessageError and close the connection. + throw wrapper.giopMagicError(); + } + + // Extract the encoding version from the request GIOP Version, + // if it contains an encoding, and set GIOP version appropriately. + // For Java serialization, we use GIOP Version 1.2 message format. + byte requestEncodingVersion = ORBConstants.CDR_ENC_VERSION; + if ((it[4] == GIOPVersion.V13_XX.getMajor()) && + (it[5] <= ORBConstants.JAVA_ENC_VERSION) && + (it[5] > ORBConstants.CDR_ENC_VERSION)) { + // Entering this block means the request is using Java encoding, + // and the encoding version is <= this ORB's Java encoding version. + requestEncodingVersion = it[5]; + buf.put(startPosition + 4, GIOPVersion.V1_2.getMajor()); + buf.put(startPosition + 5, GIOPVersion.V1_2.getMinor()); + it[4] = GIOPVersion.V1_2.getMajor();//buf.get(4); + it[5] = GIOPVersion.V1_2.getMinor();//buf.get(5); + } + + GIOPVersion orbVersion = orb.getORBData().getGIOPVersion(); + + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: Message GIOP version: " + + it[4] + '.' + it[5]); + dprint(".parseGIOPHeader: ORB Max GIOP Version: " + + orbVersion); + } + + if ((it[4] > orbVersion.getMajor()) || + ((it[4] == orbVersion.getMajor()) && (it[5] > orbVersion.getMinor())) + ) { + // For requests, sending ORB should use the version info + // published in the IOR or may choose to use a <= version + // for requests. If the version is greater than published version, + // it is an error. + + // For replies, the ORB should always receive a version it supports + // or less, but never greater (except for MessageError) + + // ACTION : Send back a MessageError() with the the highest version + // the server ORB supports, and close the connection. + if (it[7] != GIOPMessageError) { + throw wrapper.giopVersionError(); + } + } + + AreFragmentsAllowed(it[4], it[5], it[6], it[7]); + + // create appropriate messages types + + MessageBase msg; + + switch (it[7]) { + + case GIOPRequest: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating RequestMessage"); + } + //msg = new RequestMessage(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + msg = new RequestMessage_1_0(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new RequestMessage_1_1(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new RequestMessage_1_2(orb); + } else { + throw wrapper.giopVersionError(); + } + break; + + case GIOPLocateRequest: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating LocateRequestMessage"); + } + //msg = new LocateRequestMessage(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + msg = new LocateRequestMessage_1_0(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new LocateRequestMessage_1_1(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new LocateRequestMessage_1_2(orb); + } else { + throw wrapper.giopVersionError(); + } + break; + + case GIOPCancelRequest: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating CancelRequestMessage"); + } + //msg = new CancelRequestMessage(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + msg = new CancelRequestMessage_1_0(); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new CancelRequestMessage_1_1(); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new CancelRequestMessage_1_2(); + } else { + throw wrapper.giopVersionError(); + } + break; + + case GIOPReply: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating ReplyMessage"); + } + //msg = new ReplyMessage(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + msg = new ReplyMessage_1_0(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new ReplyMessage_1_1(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new ReplyMessage_1_2(orb); + } else { + throw wrapper.giopVersionError(); + } + break; + + case GIOPLocateReply: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating LocateReplyMessage"); + } + //msg = new LocateReplyMessage(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + msg = new LocateReplyMessage_1_0(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new LocateReplyMessage_1_1(orb); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new LocateReplyMessage_1_2(orb); + } else { + throw wrapper.giopVersionError(); + } + break; + + case GIOPCloseConnection: + // IMPORTANT: Must process the CloseConnection message as soon as + // its received to avoid a potential race condition on + // the connection, (i.e. another thread could try to send + // a new request on the same connection while this + // CloseConnection message would be getting dispatched + // if the CloseConnection message were not processed + // here). + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: received CloseConnection message"); + } + COMM_FAILURE comm_failure = wrapper.connectionRebind(); + connection.purgeCalls(comm_failure, false, true); + throw comm_failure; + + case GIOPMessageError: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating Message for CloseConnection or MessageError"); + } + // REVISIT a MessageError may contain the highest version server + // can support. In such a case, a new request may be made with the + // correct version or the connection be simply closed. Note the + // connection may have been closed by the server. + //msg = new Message(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + msg = new Message_1_0(); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new Message_1_1(); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new Message_1_1(); + } else { + throw wrapper.giopVersionError(); + } + break; + + case GIOPFragment: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: creating FragmentMessage"); + } + //msg = new FragmentMessage(orb.giopDebugFlag); + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + // not possible (error checking done already) + // Throw exception just for completeness, and + // for proper dataflow analysis in FindBugs + throw wrapper.giopVersionError(); + } else if ((it[4] == 0x01) && (it[5] == 0x01)) { // 1.1 + msg = new FragmentMessage_1_1(); + } else if ((it[4] == 0x01) && (it[5] == 0x02)) { // 1.2 + msg = new FragmentMessage_1_2(); + } else { + throw wrapper.giopVersionError(); + } + break; + + default: + if (orb.giopDebugFlag) { + dprint(".parseGIOPHeader: UNKNOWN MESSAGE TYPE: " + it[7]); + } + // unknown message type ? + // ACTION : send MessageError and close the connection + throw wrapper.giopVersionError(); + } + + // + // Initialize the generic GIOP header instance variables. + // + + if ((it[4] == 0x01) && (it[5] == 0x00)) { // 1.0 + Message_1_0 msg10 = (Message_1_0) msg; + msg10.magic = magic; + msg10.GIOP_version = new GIOPVersion(it[4], it[5]); + msg10.byte_order = (it[6] == LITTLE_ENDIAN_BIT); + // 'request partitioning' not supported on GIOP version 1.0 + // so just use the default thread pool, 0. + msg.threadPoolToUse = 0; + msg10.message_type = it[7]; + msg10.message_size = readSize(it[8], it[9], it[10], it[11], + msg10.isLittleEndian()) + + GIOPMessageHeaderLength; + } else { // 1.1 & 1.2 + Message_1_1 msg11 = (Message_1_1) msg; + msg11.magic = magic; + msg11.GIOP_version = new GIOPVersion(it[4], it[5]); + msg11.flags = (byte) (it[6] & TRAILING_TWO_BIT_BYTE_MASK); + // IMPORTANT: For 'request partitioning', the thread pool to use + // information is stored in the leading 6 bits of byte 6. + // + // IMPORTANT: Request partitioning is a PROPRIETARY EXTENSION !!! + // + // NOTE: Bitwise operators will promote a byte to an int before + // performing a bitwise operation and bytes, ints, longs, etc + // are signed types in Java. Thus, the need for the + // THREAD_POOL_TO_USE_MASK operation. + msg.threadPoolToUse = (it[6] >>> 2) & THREAD_POOL_TO_USE_MASK; + msg11.message_type = it[7]; + msg11.message_size = + readSize(it[8], it[9], it[10], it[11], + msg11.isLittleEndian()) + GIOPMessageHeaderLength; + + if (orb.giopSizeDebugFlag) { + StringBuilder sb = new StringBuilder(); + sb.append(typeToString(msg11.message_type)); + sb.append("("); + sb.append(msg11.message_size); + sb.append(" bytes)"); + dprint(sb.toString()); + } + } + + msg.setEncodingVersion(requestEncodingVersion); + + return msg; + } + + @SuppressWarnings("deprecation") + private static RequestMessage createRequest( + ORB orb, GIOPVersion gv, byte encodingVersion, int request_id, + boolean response_expected, byte[] object_key, String operation, + ServiceContexts service_contexts, + org.omg.CORBA.Principal requesting_principal) { + + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new RequestMessage_1_0(orb, service_contexts, request_id, + response_expected, object_key, + operation, requesting_principal); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new RequestMessage_1_1(orb, service_contexts, request_id, + response_expected, new byte[]{0x00, 0x00, 0x00}, + object_key, operation, requesting_principal); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + // Note: Currently we use response_expected flag to decide if the + // call is oneway or not. Ideally, it is possible to expect a + // response on a oneway call too, but we do not support it now. + byte response_flags = 0x03; + if (response_expected) { + response_flags = 0x03; + } else { + response_flags = 0x00; + } + /* + // REVISIT The following is the correct way to do it. This gives + // more flexibility. + if ((DII::INV_NO_RESPONSE == false) && response_expected) { + response_flags = 0x03; // regular two-way + } else if ((DII::INV_NO_RESPONSE == false) && !response_expected) { + // this condition is not possible + } else if ((DII::INV_NO_RESPONSE == true) && response_expected) { + // oneway, but we need response for LocationForwards or + // SystemExceptions. + response_flags = 0x01; + } else if ((DII::INV_NO_RESPONSE == true) && !response_expected) { + // oneway, no response required + response_flags = 0x00; + } + */ + TargetAddress target = new TargetAddress(); + target.object_key(object_key); + RequestMessage msg = + new RequestMessage_1_2(orb, request_id, response_flags, + new byte[]{0x00, 0x00, 0x00}, + target, operation, service_contexts); + msg.setEncodingVersion(encodingVersion); + return msg; + } else { + throw wrapper.giopVersionError(); + } + } + + @SuppressWarnings({"deprecation"}) + public static RequestMessage createRequest( + ORB orb, GIOPVersion gv, byte encodingVersion, int request_id, + boolean response_expected, IOR ior, + short addrDisp, String operation, + ServiceContexts service_contexts, + org.omg.CORBA.Principal requesting_principal) { + + RequestMessage requestMessage = null; + IIOPProfile profile = ior.getProfile(); + + if (addrDisp == KeyAddr.value) { + // object key will be used for target addressing + profile = ior.getProfile(); + ObjectKey objKey = profile.getObjectKey(); + byte[] object_key = objKey.getBytes(orb); + requestMessage = + createRequest(orb, gv, encodingVersion, request_id, + response_expected, object_key, + operation, service_contexts, + requesting_principal); + } else { + + if (!(gv.equals(GIOPVersion.V1_2))) { + // only object_key based target addressing is allowed for + // GIOP 1.0 & 1.1 + throw wrapper.giopVersionError(); + } + + // Note: Currently we use response_expected flag to decide if the + // call is oneway or not. Ideally, it is possible to expect a + // response on a oneway call too, but we do not support it now. + byte response_flags = 0x03; + if (response_expected) { + response_flags = 0x03; + } else { + response_flags = 0x00; + } + + TargetAddress target = new TargetAddress(); + if (addrDisp == ProfileAddr.value) { // iop profile will be used + profile = ior.getProfile(); + target.profile(profile.getIOPProfile()); + } else if (addrDisp == ReferenceAddr.value) { // ior will be used + IORAddressingInfo iorInfo = + new IORAddressingInfo(0, // profile index + ior.getIOPIOR()); + target.ior(iorInfo); + } else { + // invalid target addressing disposition value + throw wrapper.illegalTargetAddressDisposition(); + } + + requestMessage = + new RequestMessage_1_2(orb, request_id, response_flags, + new byte[]{0x00, 0x00, 0x00}, target, + operation, service_contexts); + requestMessage.setEncodingVersion(encodingVersion); + } + + if (gv.supportsIORIIOPProfileComponents()) { + // add request partitioning thread pool to use info + int poolToUse = 0; // default pool + IIOPProfileTemplate temp = + (IIOPProfileTemplate) profile.getTaggedProfileTemplate(); + Iterator iter = + temp.iteratorById(ORBConstants.TAG_REQUEST_PARTITIONING_ID); + if (iter.hasNext()) { + poolToUse = + ((RequestPartitioningComponent) iter.next()).getRequestPartitioningId(); + } + + if (poolToUse < ORBConstants.REQUEST_PARTITIONING_MIN_THREAD_POOL_ID || + poolToUse > ORBConstants.REQUEST_PARTITIONING_MAX_THREAD_POOL_ID) { + throw wrapper.invalidRequestPartitioningId(poolToUse, + ORBConstants.REQUEST_PARTITIONING_MIN_THREAD_POOL_ID, + ORBConstants.REQUEST_PARTITIONING_MAX_THREAD_POOL_ID); + } + requestMessage.setThreadPoolToUse(poolToUse); + } + + return requestMessage; + } + + public static ReplyMessage createReply( + ORB orb, GIOPVersion gv, byte encodingVersion, int request_id, + int reply_status, ServiceContexts service_contexts, IOR ior) { + + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new ReplyMessage_1_0(orb, service_contexts, request_id, + reply_status, ior); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new ReplyMessage_1_1(orb, service_contexts, request_id, + reply_status, ior); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + ReplyMessage msg = + new ReplyMessage_1_2(orb, request_id, reply_status, + service_contexts, ior); + msg.setEncodingVersion(encodingVersion); + return msg; + } else { + throw wrapper.giopVersionError(); + } + } + + public static LocateRequestMessage createLocateRequest( + ORB orb, GIOPVersion gv, byte encodingVersion, + int request_id, byte[] object_key) { + + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new LocateRequestMessage_1_0(orb, request_id, object_key); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new LocateRequestMessage_1_1(orb, request_id, object_key); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + TargetAddress target = new TargetAddress(); + target.object_key(object_key); + LocateRequestMessage msg = + new LocateRequestMessage_1_2(orb, request_id, target); + msg.setEncodingVersion(encodingVersion); + return msg; + } else { + throw wrapper.giopVersionError(); + } + } + + public static LocateReplyMessage createLocateReply( + ORB orb, GIOPVersion gv, byte encodingVersion, + int request_id, int locate_status, IOR ior) { + + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new LocateReplyMessage_1_0(orb, request_id, + locate_status, ior); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new LocateReplyMessage_1_1(orb, request_id, + locate_status, ior); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + LocateReplyMessage msg = + new LocateReplyMessage_1_2(orb, request_id, + locate_status, ior); + msg.setEncodingVersion(encodingVersion); + return msg; + } else { + throw wrapper.giopVersionError(); + } + } + + public static CancelRequestMessage createCancelRequest( + GIOPVersion gv, int request_id) { + + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new CancelRequestMessage_1_0(request_id); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new CancelRequestMessage_1_1(request_id); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + return new CancelRequestMessage_1_2(request_id); + } else { + throw wrapper.giopVersionError(); + } + } + + public static Message createCloseConnection(GIOPVersion gv) { + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new Message_1_0(Message.GIOPBigMagic, false, + Message.GIOPCloseConnection, 0); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new Message_1_1(Message.GIOPBigMagic, GIOPVersion.V1_1, + FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPCloseConnection, 0); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + return new Message_1_1(Message.GIOPBigMagic, GIOPVersion.V1_2, + FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPCloseConnection, 0); + } else { + throw wrapper.giopVersionError(); + } + } + + public static Message createMessageError(GIOPVersion gv) { + if (gv.equals(GIOPVersion.V1_0)) { // 1.0 + return new Message_1_0(Message.GIOPBigMagic, false, + Message.GIOPMessageError, 0); + } else if (gv.equals(GIOPVersion.V1_1)) { // 1.1 + return new Message_1_1(Message.GIOPBigMagic, GIOPVersion.V1_1, + FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPMessageError, 0); + } else if (gv.equals(GIOPVersion.V1_2)) { // 1.2 + return new Message_1_1(Message.GIOPBigMagic, GIOPVersion.V1_2, + FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPMessageError, 0); + } else { + throw wrapper.giopVersionError(); + } + } + + /** + * Set a flag in the given buffer (fragment bit, byte order bit, etc) + */ + public static void setFlag(ByteBuffer byteBuffer, int flag) { + byte b = byteBuffer.get(6); + b |= flag; + byteBuffer.put(6, b); + } + + private static void AreFragmentsAllowed(byte major, byte minor, byte flag, + byte msgType) { + + if ((major == 0x01) && (minor == 0x00)) { // 1.0 + if (msgType == GIOPFragment) { + throw wrapper.fragmentationDisallowed(); + } + } + + if ((flag & MORE_FRAGMENTS_BIT) == MORE_FRAGMENTS_BIT) { + switch (msgType) { + case GIOPCancelRequest: + case GIOPCloseConnection: + case GIOPMessageError: + throw wrapper.fragmentationDisallowed(); + case GIOPLocateRequest: + case GIOPLocateReply: + if ((major == 0x01) && (minor == 0x01)) { // 1.1 + throw wrapper.fragmentationDisallowed(); + } + break; + } + } + } + + /** + * Extract the object key from TargetAddress. + * + * @return ObjectKey the object key. + */ + static ObjectKeyCacheEntry extractObjectKeyCacheEntry(TargetAddress target, ORB orb) { + + short orbTargetAddrPref = orb.getORBData().getGIOPTargetAddressPreference(); + short reqAddrDisp = target.discriminator(); + + switch (orbTargetAddrPref) { + case ORBConstants.ADDR_DISP_OBJKEY: + if (reqAddrDisp != KeyAddr.value) { + throw new AddressingDispositionException(KeyAddr.value); + } + break; + case ORBConstants.ADDR_DISP_PROFILE: + if (reqAddrDisp != ProfileAddr.value) { + throw new AddressingDispositionException(ProfileAddr.value); + } + break; + case ORBConstants.ADDR_DISP_IOR: + if (reqAddrDisp != ReferenceAddr.value) { + throw new AddressingDispositionException(ReferenceAddr.value); + } + break; + case ORBConstants.ADDR_DISP_HANDLE_ALL: + break; + default: + throw wrapper.orbTargetAddrPreferenceInExtractObjectkeyInvalid(); + } + + try { + switch (reqAddrDisp) { + case KeyAddr.value: + byte[] objKey = target.object_key(); + if (objKey != null) { // AddressingDisposition::KeyAddr + return orb.extractObjectKeyCacheEntry(objKey); + } + break; + case ProfileAddr.value: + TaggedProfile profile = target.profile(); + if (profile != null) { // AddressingDisposition::ProfileAddr + IIOPProfile iiopProfile = IIOPFactories.makeIIOPProfile(orb, profile); + ObjectKey objectKey = iiopProfile.getObjectKey(); + return new ObjectKeyCacheEntryNoObjectAdapterImpl(objectKey); + } + break; + case ReferenceAddr.value: + IORAddressingInfo iorInfo = target.ior(); + if (iorInfo != null) { // AddressingDisposition::IORAddr + profile = iorInfo.ior.profiles[iorInfo.selected_profile_index]; + IIOPProfile iiopProfile = IIOPFactories.makeIIOPProfile(orb, profile); + ObjectKey objectKey = iiopProfile.getObjectKey(); + return new ObjectKeyCacheEntryNoObjectAdapterImpl(objectKey); + } + break; + default: + // this cannot happen + // There is no need for a explicit exception, since the + // TargetAddressHelper.read() would have raised a BAD_OPERATION + // exception by now. + break; + } + } catch (Exception e) { + throw wrapper.invalidObjectKey(e); + } + + // If we got here, something went wrong: the object key is null. + throw wrapper.invalidObjectKey(); + } + + private static int readSize(byte b1, byte b2, byte b3, byte b4, + boolean littleEndian) { + + int a1, a2, a3, a4; + + if (!littleEndian) { + a1 = (b1 << 24) & 0xFF000000; + a2 = (b2 << 16) & 0x00FF0000; + a3 = (b3 << 8) & 0x0000FF00; + a4 = (b4) & 0x000000FF; + } else { + a1 = (b4 << 24) & 0xFF000000; + a2 = (b3 << 16) & 0x00FF0000; + a3 = (b2 << 8) & 0x0000FF00; + a4 = (b1) & 0x000000FF; + } + + return (a1 | a2 | a3 | a4); + } + + static void nullCheck(Object obj) { + if (obj == null) { + throw wrapper.nullNotAllowed(); + } + } + + static SystemException getSystemException( + String exClassName, int minorCode, CompletionStatus completionStatus, + String message, ORBUtilSystemException wrapper) { + SystemException sysEx; + + try { + Class clazz = ORBClassLoader.loadClass(exClassName); + if (message == null) { + sysEx = (SystemException) clazz.newInstance(); + } else { + Class[] types = {String.class}; + Constructor constructor = clazz.getConstructor(types); + Object[] args = {message}; + sysEx = (SystemException) constructor.newInstance(args); + } + } catch (Exception someEx) { + throw wrapper.badSystemExceptionInReply(someEx); + } + + sysEx.minor = minorCode; + sysEx.completed = completionStatus; + + return sysEx; + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + public int getThreadPoolToUse() { + return threadPoolToUse; + } + + public byte getEncodingVersion() { + return this.encodingVersion; + } + + public void setEncodingVersion(byte version) { + this.encodingVersion = version; + } + + /** + * Return a Message's CorbaRequestId. + * NOTE: This method should be overridden for messages that support + * a 4 byte request id following the 12 byte GIOP message header. + */ + public RequestId getCorbaRequestId() { + return RequestIdImpl.UNKNOWN_CORBA_REQUEST_ID; + } + + /** + * Returns true if this message could be followed by a fragment. + */ + public boolean supportsFragments() { + return false; + } + + /** + * Get the request id from the 4 bytes following the 12 byte GIOP + * request header if the request header exists. Otherwise, return 0. + *

    + * NOTE: Assumes Message already been filtered by + * MessageBase.messageSupportsFragments(Message) + * + * @return CorbaRequestIdif Message supports a 12 + * + 4 byte GIOP header. Otherwise returns a CorbaRequestId with an + * undefined request id. + */ + public static RequestId getRequestIdFromMessageBytes(Message message, ByteBuffer byteBuffer) { + if (!(message instanceof Message_1_2)) { + return RequestIdImpl.UNKNOWN_CORBA_REQUEST_ID; // in older protocols the request ID is not so easily found + } else { + Message_1_2 message_1_2 = (Message_1_2) message; + message_1_2.unmarshalRequestID(byteBuffer); + return new RequestIdImpl(message_1_2.request_id); + } + } + + private static void dprint(String msg) { + ORBUtility.dprint("MessageBase", msg); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/MessageHandler.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/MessageHandler.java new file mode 100644 index 000000000..b2882831d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/MessageHandler.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import java.io.IOException; + +/** + * Interface which allows an implementation to use + * double dispatch when processing the various + * concrete message types found in this package. + */ +public interface MessageHandler +{ + // + // REVISIT - These should not throw IOException. + // Should be handled internally. + + /** + * Used for message types for which we don't have concrete classes, yet, + * such as CloseConnection and MessageError, as well as unknown types. + */ + void handleInput(Message header) throws IOException; + + // Request + void handleInput(RequestMessage_1_0 header) throws IOException; + void handleInput(RequestMessage_1_1 header) throws IOException; + void handleInput(RequestMessage_1_2 header) throws IOException; + + // Reply + void handleInput(ReplyMessage_1_0 header) throws IOException; + void handleInput(ReplyMessage_1_1 header) throws IOException; + void handleInput(ReplyMessage_1_2 header) throws IOException; + + // LocateRequest + void handleInput(LocateRequestMessage_1_0 header) throws IOException; + void handleInput(LocateRequestMessage_1_1 header) throws IOException; + void handleInput(LocateRequestMessage_1_2 header) throws IOException; + + // LocateReply + void handleInput(LocateReplyMessage_1_0 header) throws IOException; + void handleInput(LocateReplyMessage_1_1 header) throws IOException; + void handleInput(LocateReplyMessage_1_2 header) throws IOException; + + // Fragment + void handleInput(FragmentMessage_1_1 header) throws IOException; + void handleInput(FragmentMessage_1_2 header) throws IOException; + + // CancelRequest + void handleInput(CancelRequestMessage header) throws IOException; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_0.java new file mode 100644 index 000000000..600b2a622 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_0.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import java.nio.ByteBuffer; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/* + * This implements the GIOP 1.0 Message header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public class Message_1_0 + extends com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase { + + private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Instance variables + int magic = 0; + GIOPVersion GIOP_version = null; + boolean byte_order = false; + byte message_type = (byte) 0; + int message_size = (int) 0; + + // Constructor + + Message_1_0() { + } + + Message_1_0(int _magic, boolean _byte_order, byte _message_type, + int _message_size) { + magic = _magic; + GIOP_version = GIOPVersion.V1_0; + byte_order = _byte_order; + message_type = _message_type; + message_size = _message_size; + } + + // Accessor methods + + public GIOPVersion getGIOPVersion() { + return this.GIOP_version; + } + + public int getType() { + return this.message_type; + } + + public int getSize() { + return this.message_size; + } + + public boolean isLittleEndian() { + return this.byte_order; + } + + public boolean moreFragmentsToFollow() { + return false; + } + + // Mutator methods + + public void setSize(ByteBuffer byteBuffer, int size) { + this.message_size = size; + + // + // Patch the size field in the header. + // + int patch = size - GIOPMessageHeaderLength; + if (!isLittleEndian()) { + byteBuffer.put(8, (byte)((patch >>> 24) & 0xFF)); + byteBuffer.put(9, (byte)((patch >>> 16) & 0xFF)); + byteBuffer.put(10, (byte)((patch >>> 8) & 0xFF)); + byteBuffer.put(11, (byte)((patch) & 0xFF)); + } else { + byteBuffer.put(8, (byte)((patch) & 0xFF)); + byteBuffer.put(9, (byte)((patch >>> 8) & 0xFF)); + byteBuffer.put(10, (byte)((patch >>> 16) & 0xFF)); + byteBuffer.put(11, (byte)((patch >>> 24) & 0xFF)); + } + } + + public FragmentMessage createFragmentMessage() { + throw wrapper.fragmentationDisallowed() ; + } + + // IO methods + + // This should do nothing even if it is called. The Message Header already + // is read off java.io.InputStream (not a CDRInputStream) by IIOPConnection + // in order to choose the correct CDR Version, msg_type, and msg_size. + // So, we would never need to read the Message Header off a CDRInputStream. + public void read(org.omg.CORBA.portable.InputStream istream) { + /* + this.magic = istream.read_long(); + this.GIOP_version = (new GIOPVersion()).read(istream); + this.byte_order = istream.read_boolean(); + this.message_type = istream.read_octet(); + this.message_size = istream.read_ulong(); + */ + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + ostream.write_long(this.magic); + nullCheck(this.GIOP_version); + this.GIOP_version.write(ostream); + ostream.write_boolean(this.byte_order); + ostream.write_octet(this.message_type); + ostream.write_ulong(this.message_size); + } + +} // class Message_1_0 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_1.java new file mode 100644 index 000000000..273ab46ed --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_1.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import java.nio.ByteBuffer; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/* + * This implements the GIOP 1.1 & 1.2 Message header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public class Message_1_1 + extends com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase { + + // Constants + final static int UPPER_THREE_BYTES_OF_INT_MASK = 0xFF; + + private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Instance variables + int magic = 0; + GIOPVersion GIOP_version = null; + byte flags = 0; + byte message_type = 0; + int message_size = 0; + + // Constructor + + Message_1_1() { + } + + Message_1_1(int _magic, GIOPVersion _GIOP_version, byte _flags, + byte _message_type, int _message_size) { + magic = _magic; + GIOP_version = _GIOP_version; + flags = _flags; + message_type = _message_type; + message_size = _message_size; + } + + // Accessor methods + + public GIOPVersion getGIOPVersion() { + return this.GIOP_version; + } + + public int getType() { + return this.message_type; + } + + public int getSize() { + return this.message_size; + } + + public boolean isLittleEndian() { + return ((this.flags & LITTLE_ENDIAN_BIT) == LITTLE_ENDIAN_BIT); + } + + public boolean moreFragmentsToFollow() { + return ( (this.flags & MORE_FRAGMENTS_BIT) == MORE_FRAGMENTS_BIT ); + } + + // Mutator methods + + // NOTE: This is a SUN PROPRIETARY EXTENSION + // Add the poolToUse to the upper 6 bits of byte 6 of the GIOP header. + // this.flags represents byte 6 here. + public void setThreadPoolToUse(int poolToUse) { + // IMPORTANT: Bitwise operations will promote + // byte types to int before performing + // bitwise operations. And, Java + // types are signed. + int tmpFlags = poolToUse << 2; + tmpFlags &= UPPER_THREE_BYTES_OF_INT_MASK; + tmpFlags |= flags; + flags = (byte)tmpFlags; + } + + public void setSize(ByteBuffer byteBuffer, int size) { + + this.message_size = size; + + // + // Patch the size field in the header. + // + + int patch = size - GIOPMessageHeaderLength; + if (!isLittleEndian()) { + byteBuffer.put(8, (byte)((patch >>> 24) & 0xFF)); + byteBuffer.put(9, (byte)((patch >>> 16) & 0xFF)); + byteBuffer.put(10, (byte)((patch >>> 8) & 0xFF)); + byteBuffer.put(11, (byte)((patch >>> 0) & 0xFF)); + } else { + byteBuffer.put(8, (byte)((patch >>> 0) & 0xFF)); + byteBuffer.put(9, (byte)((patch >>> 8) & 0xFF)); + byteBuffer.put(10, (byte)((patch >>> 16) & 0xFF)); + byteBuffer.put(11, (byte)((patch >>> 24) & 0xFF)); + } + } + + /** + * Allows us to create a fragment message from any message type. + */ + public FragmentMessage createFragmentMessage() { + + // check for message type validity + + switch (this.message_type) { + case GIOPCancelRequest : + case GIOPCloseConnection : + case GIOPMessageError : + throw wrapper.fragmentationDisallowed() ; + case GIOPLocateRequest : + case GIOPLocateReply : + if (this.GIOP_version.equals(GIOPVersion.V1_1)) { + throw wrapper.fragmentationDisallowed() ; + } + break; + } + + /* + // A fragmented mesg can be created only if the current mesg' fragment + // bit is set. Otherwise, raise error + // too stringent check + if ( (this.flags & MORE_FRAGMENTS_BIT) != MORE_FRAGMENTS_BIT ) { + throw wrapper.fragmentationDisallowed( CompletionStatus.COMPLETED_MAYBE); + } + */ + if (this.GIOP_version.equals(GIOPVersion.V1_1)) { + return new FragmentMessage_1_1(this); + } else if (this.GIOP_version.equals(GIOPVersion.V1_2)) { + return new FragmentMessage_1_2(this); + } + + throw wrapper.giopVersionError() ; + } + + // IO methods + + // This should do nothing even if it is called. The Message Header is read + // off a java.io.InputStream (not a CDRInputStream) by IIOPConnection + // in order to choose the correct CDR Version , msg_type, and msg_size. + // So, we would never need to read the Message Header off a CDRInputStream. + public void read(org.omg.CORBA.portable.InputStream istream) { + /* + this.magic = istream.read_long(); + this.GIOP_version = (new GIOPVersion()).read(istream); + this.flags = istream.read_octet(); + this.message_type = istream.read_octet(); + this.message_size = istream.read_ulong(); + */ + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + ostream.write_long(this.magic); + nullCheck(this.GIOP_version); + this.GIOP_version.write(ostream); + ostream.write_octet(this.flags); + ostream.write_octet(this.message_type); + ostream.write_ulong(this.message_size); + } +} // class Message_1_1 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_2.java new file mode 100644 index 000000000..e02c425b9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/Message_1_2.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.protocol.RequestId; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.protocol.RequestIdImpl; + +public class Message_1_2 extends Message_1_1 +{ + protected int request_id = (int) 0; + + Message_1_2() {} + + Message_1_2(int _magic, GIOPVersion _GIOP_version, byte _flags, + byte _message_type, int _message_size) { + + super(_magic, + _GIOP_version, + _flags, + _message_type, + _message_size); + } + + /** + * The byteBuffer is presumed to have contents of the message already + * read in. It must have 12 bytes of space at the beginning for the GIOP header, + * but the header doesn't have to be copied in. + */ + public void unmarshalRequestID(ByteBuffer byteBuffer) { + byteBuffer.order(isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN); + request_id = byteBuffer.getInt(GIOPMessageHeaderLength); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + if (getEncodingVersion() == ORBConstants.CDR_ENC_VERSION) { + super.write(ostream); + return; + } + GIOPVersion gv = GIOP_version; // save + GIOP_version = GIOPVersion.getInstance(GIOPVersion.V13_XX.getMajor(), + getEncodingVersion()); + super.write(ostream); + GIOP_version = gv; // restore + } + + public RequestId getCorbaRequestId() { + return new RequestIdImpl(this.request_id); + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ProfileAddr.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ProfileAddr.java new file mode 100644 index 000000000..ba8d4a87e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ProfileAddr.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/ProfileAddr.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +public interface ProfileAddr +{ + public static final short value = (short)(1); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReferenceAddr.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReferenceAddr.java new file mode 100644 index 000000000..64fd67d5d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReferenceAddr.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/ReferenceAddr.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +public interface ReferenceAddr +{ + public static final short value = (short)(2); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage.java new file mode 100644 index 000000000..67d0a4548 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import org.omg.CORBA.SystemException; +import com.sun.corba.ee.spi.ior.IOR; + +/** + * This interface captures the ReplyMessage contract. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface ReplyMessage extends Message, LocateReplyOrReplyMessage { + + // Note: If the value, order, or number of these constants change, + // please update the REPLY_MESSAGE_TO_PI_REPLY_STATUS table in PIHandlerImpl. + int NO_EXCEPTION = 0; + int USER_EXCEPTION = 1; + int SYSTEM_EXCEPTION = 2; + int LOCATION_FORWARD = 3; + int LOCATION_FORWARD_PERM = 4; // 1.2 + int NEEDS_ADDRESSING_MODE = 5; // 1.2 + + ServiceContexts getServiceContexts(); + void setIOR( IOR newIOR ); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_0.java new file mode 100644 index 000000000..c83d87a4b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_0.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.impl.encoding.CDRInputObject; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * This implements the GIOP 1.0 Reply header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class ReplyMessage_1_0 extends Message_1_0 + implements ReplyMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Instance variables + + private ORB orb = null; + private ServiceContexts service_contexts = null; + private int request_id = (int) 0; + private int reply_status = (int) 0; + private IOR ior = null; + private String exClassName = null; + private int minorCode = (int) 0; + private CompletionStatus completionStatus = null; + + // Constructors + + ReplyMessage_1_0(ORB orb) { + this.service_contexts = ServiceContextDefaults.makeServiceContexts( orb ) ; + this.orb = orb; + } + + ReplyMessage_1_0(ORB orb, ServiceContexts _service_contexts, + int _request_id, int _reply_status, IOR _ior) { + super(Message.GIOPBigMagic, false, Message.GIOPReply, 0); + this.orb = orb; + service_contexts = _service_contexts; + request_id = _request_id; + reply_status = _reply_status; + ior = _ior; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getReplyStatus() { + return this.reply_status; + } + + public short getAddrDisposition() { + return KeyAddr.value; + } + + public ServiceContexts getServiceContexts() { + return this.service_contexts; + } + + public SystemException getSystemException(String message) { + return MessageBase.getSystemException( + exClassName, minorCode, completionStatus, message, wrapper); + } + + public IOR getIOR() { + return this.ior; + } + + public void setIOR( IOR ior ) { + this.ior = ior; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.service_contexts = ServiceContextDefaults.makeServiceContexts( + (org.omg.CORBA_2_3.portable.InputStream) istream); + this.request_id = istream.read_ulong(); + this.reply_status = istream.read_long(); + isValidReplyStatus(this.reply_status); // raises exception on error + + // The code below reads the reply body in some cases + // SYSTEM_EXCEPTION & LOCATION_FORWARD + if (this.reply_status == SYSTEM_EXCEPTION) { + + String reposId = istream.read_string(); + this.exClassName = ORBUtility.classNameOf(reposId); + this.minorCode = istream.read_long(); + int status = istream.read_long(); + + switch (status) { + case CompletionStatus._COMPLETED_YES: + this.completionStatus = CompletionStatus.COMPLETED_YES; + break; + case CompletionStatus._COMPLETED_NO: + this.completionStatus = CompletionStatus.COMPLETED_NO; + break; + case CompletionStatus._COMPLETED_MAYBE: + this.completionStatus = CompletionStatus.COMPLETED_MAYBE; + break; + default: + throw wrapper.badCompletionStatusInReply( status ); + } + + } else if (this.reply_status == USER_EXCEPTION) { + // do nothing. The client stub will read the exception from body. + } else if (this.reply_status == LOCATION_FORWARD) { + CDRInputObject cdr = (CDRInputObject) istream; + this.ior = IORFactories.makeIOR( orb, (InputStream)cdr ) ; + } + } + + // Note, this writes only the header information. SystemException or + // IOR may be written afterwards into the reply mesg body. + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + service_contexts.write( + (org.omg.CORBA_2_3.portable.OutputStream) ostream, + GIOPVersion.V1_0); + ostream.write_ulong(this.request_id); + ostream.write_long(this.reply_status); + } + + // Static methods + + public static void isValidReplyStatus(int replyStatus) { + switch (replyStatus) { + case NO_EXCEPTION : + case USER_EXCEPTION : + case SYSTEM_EXCEPTION : + case LOCATION_FORWARD : + break; + default : + throw wrapper.illegalReplyStatus(); + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_1.java new file mode 100644 index 000000000..7cd134cce --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_1.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.IORFactories; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.IOR; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.encoding.CDRInputObject; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * This implements the GIOP 1.1 Reply header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class ReplyMessage_1_1 extends Message_1_1 + implements ReplyMessage { + private static final ORBUtilSystemException wrapper = null; + + // Instance variables + + private ORB orb = null; + private ServiceContexts service_contexts = null; + private int request_id = (int) 0; + private int reply_status = (int) 0; + private IOR ior = null; + private String exClassName = null; + private int minorCode = (int) 0; + private CompletionStatus completionStatus = null; + + // Constructors + + ReplyMessage_1_1(ORB orb) { + this.orb = orb; + this.service_contexts = ServiceContextDefaults.makeServiceContexts(orb); + } + + ReplyMessage_1_1(ORB orb, ServiceContexts _service_contexts, + int _request_id, int _reply_status, IOR _ior) { + super(Message.GIOPBigMagic, GIOPVersion.V1_1, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPReply, 0); + this.orb = orb; + service_contexts = _service_contexts; + request_id = _request_id; + reply_status = _reply_status; + ior = _ior; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getReplyStatus() { + return this.reply_status; + } + + public short getAddrDisposition() { + return KeyAddr.value; + } + + public ServiceContexts getServiceContexts() { + return this.service_contexts; + } + + public SystemException getSystemException(String message) { + return MessageBase.getSystemException( + exClassName, minorCode, completionStatus, message, wrapper); + } + + public IOR getIOR() { + return this.ior; + } + + public void setIOR(IOR ior) { + this.ior = ior; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.service_contexts = ServiceContextDefaults.makeServiceContexts( + (org.omg.CORBA_2_3.portable.InputStream) istream); + this.request_id = istream.read_ulong(); + this.reply_status = istream.read_long(); + isValidReplyStatus(this.reply_status); // raises exception on error + + // The code below reads the reply body in some cases + // SYSTEM_EXCEPTION & LOCATION_FORWARD + if (this.reply_status == SYSTEM_EXCEPTION) { + + String reposId = istream.read_string(); + this.exClassName = ORBUtility.classNameOf(reposId); + this.minorCode = istream.read_long(); + int status = istream.read_long(); + + switch (status) { + case CompletionStatus._COMPLETED_YES: + this.completionStatus = CompletionStatus.COMPLETED_YES; + break; + case CompletionStatus._COMPLETED_NO: + this.completionStatus = CompletionStatus.COMPLETED_NO; + break; + case CompletionStatus._COMPLETED_MAYBE: + this.completionStatus = CompletionStatus.COMPLETED_MAYBE; + break; + default: + throw wrapper.badCompletionStatusInReply(status); + } + } else if (this.reply_status == USER_EXCEPTION) { + // do nothing. The client stub will read the exception from body. + } else if (this.reply_status == LOCATION_FORWARD) { + CDRInputObject cdr = (CDRInputObject) istream; + this.ior = IORFactories.makeIOR(orb, (InputStream) cdr); + } + } + + // Note, this writes only the header information. SystemException or + // IOR may be written afterwards into the reply mesg body. + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + service_contexts.write( + (org.omg.CORBA_2_3.portable.OutputStream) ostream, + GIOPVersion.V1_1); + ostream.write_ulong(this.request_id); + ostream.write_long(this.reply_status); + } + + // Static methods + + public static void isValidReplyStatus(int replyStatus) { + switch (replyStatus) { + case NO_EXCEPTION: + case USER_EXCEPTION: + case SYSTEM_EXCEPTION: + case LOCATION_FORWARD: + break; + default: + throw wrapper.illegalReplyStatus(); + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_2.java new file mode 100644 index 000000000..18e278347 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/ReplyMessage_1_2.java @@ -0,0 +1,213 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories ; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.spi.trace.Transport ; + +/** + * This implements the GIOP 1.2 Reply header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +@Transport +public final class ReplyMessage_1_2 extends Message_1_2 + implements ReplyMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + // Instance variables + + private ORB orb = null; + private int reply_status = 0; + private ServiceContexts service_contexts = null ; + private IOR ior = null; + private String exClassName = null; + private int minorCode = 0; + private CompletionStatus completionStatus = null; + private short addrDisposition = KeyAddr.value; // default; + + // Constructors + + ReplyMessage_1_2(ORB orb) { + this.service_contexts = ServiceContextDefaults.makeServiceContexts( orb ) ; + this.orb = orb; + } + + ReplyMessage_1_2(ORB orb, int _request_id, int _reply_status, + ServiceContexts _service_contexts, IOR _ior) { + super(Message.GIOPBigMagic, GIOPVersion.V1_2, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPReply, 0); + this.orb = orb; + request_id = _request_id; + reply_status = _reply_status; + service_contexts = _service_contexts; + if (service_contexts == null) { + service_contexts = + ServiceContextDefaults.makeServiceContexts(orb); + } + ior = _ior; + } + + // Accessor methods + + public int getRequestId() { + return this.request_id; + } + + public int getReplyStatus() { + return this.reply_status; + } + + public short getAddrDisposition() { + return this.addrDisposition; + } + + public ServiceContexts getServiceContexts() { + return this.service_contexts; + } + + public SystemException getSystemException(String message) { + return MessageBase.getSystemException( + exClassName, minorCode, completionStatus, message, wrapper); + } + + public IOR getIOR() { + return this.ior; + } + + public void setIOR( IOR ior ) { + this.ior = ior; + } + + // IO methods + @Transport + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + this.reply_status = istream.read_long(); + isValidReplyStatus(this.reply_status); // raises exception on error + this.service_contexts = ServiceContextDefaults.makeServiceContexts( + (org.omg.CORBA_2_3.portable.InputStream)istream ) ; + + // CORBA formal 00-11-0 15.4.2.2 GIOP 1.2 body must be + // aligned on an 8 octet boundary. + // Ensures that the first read operation called from the stub code, + // during body deconstruction, would skip the header padding, that was + // inserted to ensure that the body was aligned on an 8-octet boundary. + ((CDRInputObject)istream).setHeaderPadding(true); + + // The code below reads the reply body in some cases + // SYSTEM_EXCEPTION & LOCATION_FORWARD & LOCATION_FORWARD_PERM & + // NEEDS_ADDRESSING_MODE + if (this.reply_status == SYSTEM_EXCEPTION) { + + String reposId = istream.read_string(); + this.exClassName = ORBUtility.classNameOf(reposId); + this.minorCode = istream.read_long(); + int status = istream.read_long(); + + switch (status) { + case CompletionStatus._COMPLETED_YES: + this.completionStatus = CompletionStatus.COMPLETED_YES; + break; + case CompletionStatus._COMPLETED_NO: + this.completionStatus = CompletionStatus.COMPLETED_NO; + break; + case CompletionStatus._COMPLETED_MAYBE: + this.completionStatus = CompletionStatus.COMPLETED_MAYBE; + break; + default: + throw wrapper.badCompletionStatusInReply( status ) ; + } + + } else if (this.reply_status == USER_EXCEPTION) { + // do nothing. The client stub will read the exception from body. + } else if ( (this.reply_status == LOCATION_FORWARD) || + (this.reply_status == LOCATION_FORWARD_PERM) ){ + CDRInputObject cdr = (CDRInputObject) istream; + this.ior = IORFactories.makeIOR( orb, (InputStream)cdr ) ; + } else if (this.reply_status == NEEDS_ADDRESSING_MODE) { + // read GIOP::AddressingDisposition from body and resend the + // original request using the requested addressing mode. The + // resending is transparent to the client program. + this.addrDisposition = AddressingDispositionHelper.read(istream); + } + } + + // Note, this writes only the header information. SystemException or + // IOR or GIOP::AddressingDisposition may be written afterwards into the + // reply mesg body. + @Transport + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + ostream.write_long(this.reply_status); + service_contexts.write( + (org.omg.CORBA_2_3.portable.OutputStream) ostream, + GIOPVersion.V1_2); + + // CORBA formal 00-11-0 15.4.2.2 GIOP 1.2 body must be + // aligned on an 8 octet boundary. + // Ensures that the first write operation called from the stub code, + // during body construction, would insert a header padding, such that + // the body is aligned on an 8-octet boundary. + ((CDROutputObject)ostream).setHeaderPadding(true); + } + + // Static methods + public static void isValidReplyStatus(int replyStatus) { + switch (replyStatus) { + case NO_EXCEPTION : + case USER_EXCEPTION : + case SYSTEM_EXCEPTION : + case LOCATION_FORWARD : + case LOCATION_FORWARD_PERM : + case NEEDS_ADDRESSING_MODE : + break; + default : + throw wrapper.illegalReplyStatus() ; + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class ReplyMessage_1_2 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage.java new file mode 100644 index 000000000..d9e2c3d13 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; + +/** + * This interface captures the RequestMessage contract. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public interface RequestMessage extends Message { + + byte RESPONSE_EXPECTED_BIT = 0x01; + + ServiceContexts getServiceContexts(); + void setServiceContexts(ServiceContexts sc); + int getRequestId(); + boolean isResponseExpected(); + byte[] getReserved(); + ObjectKeyCacheEntry getObjectKeyCacheEntry(); + String getOperation(); + @SuppressWarnings({"deprecation"}) + org.omg.CORBA.Principal getPrincipal(); + + // NOTE: This is a SUN PROPRIETARY EXTENSION + void setThreadPoolToUse(int poolToUse); + + +} // interface RequestMessage diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_0.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_0.java new file mode 100644 index 000000000..9c0679811 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_0.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; + +/** + * This implements the GIOP 1.0 Request header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class RequestMessage_1_0 extends Message_1_0 + implements RequestMessage { + + // Instance variables + + private ORB orb = null; + private ServiceContexts service_contexts = null; + private int request_id = (int) 0; + private boolean response_expected = false; + private byte[] object_key = null; + private String operation = null; + @SuppressWarnings({"deprecation"}) + private org.omg.CORBA.Principal requesting_principal = null; + private ObjectKeyCacheEntry entry = null; + + // Constructor + + RequestMessage_1_0(ORB orb) { + this.orb = orb; + service_contexts = ServiceContextDefaults.makeServiceContexts( orb ) ; + } + + @SuppressWarnings({"deprecation"}) + RequestMessage_1_0(ORB orb, ServiceContexts _service_contexts, + int _request_id, boolean _response_expected, byte[] _object_key, + String _operation, org.omg.CORBA.Principal _requesting_principal) { + super(Message.GIOPBigMagic, false, Message.GIOPRequest, 0); + this.orb = orb; + service_contexts = _service_contexts; + request_id = _request_id; + response_expected = _response_expected; + object_key = _object_key; + operation = _operation; + requesting_principal = _requesting_principal; + } + + // Accessor methods (RequestMessage interface) + + public ServiceContexts getServiceContexts() { + return this.service_contexts; + } + + public void setServiceContexts(ServiceContexts sc) { + this.service_contexts = sc; + } + + public int getRequestId() { + return this.request_id; + } + + public boolean isResponseExpected() { + return this.response_expected; + } + + public byte[] getReserved() { + // REVISIT Should we throw an exception or return null ? + return null; + } + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + if (this.entry == null) { + // this will raise a MARSHAL exception upon errors. + this.entry = orb.extractObjectKeyCacheEntry(object_key); + } + + return this.entry; + } + + public String getOperation() { + return this.operation; + } + + @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.Principal getPrincipal() { + return this.requesting_principal; + } + + + // Mutators + + public void setThreadPoolToUse(int poolToUse) { + // No-op, must be GIOP Version 1.1 or greater + // to support this SUN PROPRIETARY EXTENSION. + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.service_contexts = ServiceContextDefaults.makeServiceContexts( + (org.omg.CORBA_2_3.portable.InputStream) istream); + this.request_id = istream.read_ulong(); + this.response_expected = istream.read_boolean(); + int _len0 = istream.read_long(); + this.object_key = new byte[_len0]; + istream.read_octet_array(this.object_key, 0, _len0); + this.operation = istream.read_string(); + this.requesting_principal = istream.read_Principal(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + service_contexts.write( + (org.omg.CORBA_2_3.portable.OutputStream) ostream, + GIOPVersion.V1_0); + ostream.write_ulong(this.request_id); + ostream.write_boolean(this.response_expected); + nullCheck(this.object_key); + ostream.write_long(this.object_key.length); + ostream.write_octet_array(this.object_key, 0, this.object_key.length); + ostream.write_string(this.operation); + if (this.requesting_principal != null) { + ostream.write_Principal(this.requesting_principal); + } else { + ostream.write_long(0); + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException + { + handler.handleInput(this); + } +} // class RequestMessage_1_0 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_1.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_1.java new file mode 100644 index 000000000..2ec8e231a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_1.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * This implements the GIOP 1.1 Request header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +public final class RequestMessage_1_1 extends Message_1_1 + implements RequestMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self; + + // Instance variables + + private ORB orb = null; + private ServiceContexts service_contexts = null; + private int request_id = 0; + private boolean response_expected = false; + private byte[] reserved = null; // Added in GIOP 1.1 + private byte[] object_key = null; + private String operation = null; + @SuppressWarnings({"deprecation"}) + private org.omg.CORBA.Principal requesting_principal = null; + private ObjectKeyCacheEntry entry = null; + + // Constructors + + RequestMessage_1_1(ORB orb) { + this.orb = orb; + this.service_contexts = ServiceContextDefaults.makeServiceContexts(orb); + } + + @SuppressWarnings({"deprecation"}) + RequestMessage_1_1(ORB orb, ServiceContexts _service_contexts, + int _request_id, boolean _response_expected, byte[] _reserved, + byte[] _object_key, String _operation, + org.omg.CORBA.Principal _requesting_principal) { + super(Message.GIOPBigMagic, GIOPVersion.V1_1, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPRequest, 0); + this.orb = orb; + service_contexts = _service_contexts; + request_id = _request_id; + response_expected = _response_expected; + reserved = _reserved; + object_key = _object_key; + operation = _operation; + requesting_principal = _requesting_principal; + } + + // Accessor methods (RequestMessage interface) + + public ServiceContexts getServiceContexts() { + return this.service_contexts; + } + + public void setServiceContexts(ServiceContexts sc) { + this.service_contexts = sc; + } + + public int getRequestId() { + return this.request_id; + } + + public boolean isResponseExpected() { + return this.response_expected; + } + + public byte[] getReserved() { + return this.reserved; + } + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + if (this.entry == null) { + // this will raise a MARSHAL exception upon errors. + this.entry = orb.extractObjectKeyCacheEntry(object_key); + } + + return this.entry; + } + + public String getOperation() { + return this.operation; + } + + @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.Principal getPrincipal() { + return this.requesting_principal; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.service_contexts + = ServiceContextDefaults.makeServiceContexts( + (org.omg.CORBA_2_3.portable.InputStream) istream); + this.request_id = istream.read_ulong(); + this.response_expected = istream.read_boolean(); + this.reserved = new byte[3]; + for (int _o0 = 0; _o0 < (3); ++_o0) { + this.reserved[_o0] = istream.read_octet(); + } + int _len1 = istream.read_long(); + this.object_key = new byte[_len1]; + istream.read_octet_array(this.object_key, 0, _len1); + this.operation = istream.read_string(); + this.requesting_principal = istream.read_Principal(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + service_contexts.write( + (org.omg.CORBA_2_3.portable.OutputStream) ostream, + GIOPVersion.V1_1); + ostream.write_ulong(this.request_id); + ostream.write_boolean(this.response_expected); + nullCheck(this.reserved); + if (this.reserved.length != (3)) { + throw wrapper.badReservedLength(); + } + for (int _i0 = 0; _i0 < (3); ++_i0) { + ostream.write_octet(this.reserved[_i0]); + } + nullCheck(this.object_key); + ostream.write_long(this.object_key.length); + ostream.write_octet_array(this.object_key, 0, this.object_key.length); + ostream.write_string(this.operation); + if (this.requesting_principal != null) { + ostream.write_Principal(this.requesting_principal); + } else { + ostream.write_long(0); + } + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class RequestMessage_1_1 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_2.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_2.java new file mode 100644 index 000000000..345990bd2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/RequestMessage_1_2.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import com.sun.corba.ee.spi.trace.Transport; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * This implements the GIOP 1.2 Request header. + * + * @author Ram Jeyaraman 05/14/2000 + * @version 1.0 + */ + +@Transport +public final class RequestMessage_1_2 extends Message_1_2 + implements RequestMessage { + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self; + + // Instance variables + + private ORB orb = null; + private byte response_flags = (byte) 0; + private byte reserved[] = null; + private TargetAddress target = null; + private String operation = null; + private ServiceContexts service_contexts = null; + private ObjectKeyCacheEntry entry = null; + + // Constructors + + RequestMessage_1_2(ORB orb) { + this.orb = orb; + this.service_contexts = ServiceContextDefaults.makeServiceContexts(orb); + } + + RequestMessage_1_2(ORB orb, int _request_id, byte _response_flags, + byte[] _reserved, TargetAddress _target, + String _operation, ServiceContexts _service_contexts) { + super(Message.GIOPBigMagic, GIOPVersion.V1_2, FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPRequest, 0); + this.orb = orb; + request_id = _request_id; + response_flags = _response_flags; + reserved = _reserved; + target = _target; + operation = _operation; + service_contexts = _service_contexts; + } + + // Accessor methods (RequestMessage interface) + + public int getRequestId() { + return this.request_id; + } + + public boolean isResponseExpected() { + /* + case 1: LSBit[1] == 1 + not a oneway call (DII flag INV_NO_RESPONSE is false) // Ox03 + LSBit[0] must be 1. + case 2: LSBit[1] == 0 + if (LSB[0] == 0) // Ox00 + oneway call + else if (LSB[0] == 1) // 0x01 + oneway call; but server may provide + a location forward response or system exception response. + */ + + if ((this.response_flags & RESPONSE_EXPECTED_BIT) == RESPONSE_EXPECTED_BIT) { + return true; + } + + return false; + } + + public byte[] getReserved() { + return this.reserved; + } + + public ObjectKeyCacheEntry getObjectKeyCacheEntry() { + if (this.entry == null) { + // this will raise a MARSHAL exception upon errors. + this.entry = MessageBase.extractObjectKeyCacheEntry(target, orb); + } + + return this.entry; + } + + public String getOperation() { + return this.operation; + } + + @SuppressWarnings({"deprecation"}) + public org.omg.CORBA.Principal getPrincipal() { + // REVISIT Should we throw an exception or return null ? + return null; + } + + public ServiceContexts getServiceContexts() { + return this.service_contexts; + } + + public void setServiceContexts(ServiceContexts sc) { + this.service_contexts = sc; + } + + // IO methods + + @Transport + public void read(org.omg.CORBA.portable.InputStream istream) { + super.read(istream); + this.request_id = istream.read_ulong(); + this.response_flags = istream.read_octet(); + this.reserved = new byte[3]; + for (int _o0 = 0; _o0 < (3); ++_o0) { + this.reserved[_o0] = istream.read_octet(); + } + this.target = TargetAddressHelper.read(istream); + getObjectKeyCacheEntry(); // this does AddressingDisposition check + this.operation = istream.read_string(); + this.service_contexts = ServiceContextDefaults.makeServiceContexts( + (org.omg.CORBA_2_3.portable.InputStream) istream); + + // CORBA formal 00-11-0 15.4.2.2 GIOP 1.2 body must be + // aligned on an 8 octet boundary. + // Ensures that the first read operation called from the stub code, + // during body deconstruction, would skip the header padding, that was + // inserted to ensure that the body was aligned on an 8-octet boundary. + ((CDRInputObject) istream).setHeaderPadding(true); + + } + + @Transport + public void write(org.omg.CORBA.portable.OutputStream ostream) { + super.write(ostream); + ostream.write_ulong(this.request_id); + ostream.write_octet(this.response_flags); + nullCheck(this.reserved); + if (this.reserved.length != (3)) { + throw wrapper.badReservedLength(); + } + for (int _i0 = 0; _i0 < (3); ++_i0) { + ostream.write_octet(this.reserved[_i0]); + } + nullCheck(this.target); + TargetAddressHelper.write(ostream, this.target); + ostream.write_string(this.operation); + service_contexts.write( + (org.omg.CORBA_2_3.portable.OutputStream) ostream, + GIOPVersion.V1_2); + + // CORBA formal 00-11-0 15.4.2.2 GIOP 1.2 body must be + // aligned on an 8 octet boundary. + // Ensures that the first write operation called from the stub code, + // during body construction, would insert a header padding, such that + // the body is aligned on an 8-octet boundary. + ((CDROutputObject) ostream).setHeaderPadding(true); + } + + public void callback(MessageHandler handler) + throws java.io.IOException { + handler.handleInput(this); + } + + @Override + public boolean supportsFragments() { + return true; + } +} // class RequestMessage_1_2 diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddress.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddress.java new file mode 100644 index 000000000..cf4c0d519 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddress.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddress.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +public final class TargetAddress implements org.omg.CORBA.portable.IDLEntity +{ + private byte[] ___object_key; + private org.omg.IOP.TaggedProfile ___profile; + private com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo ___ior; + private short __discriminator; + private boolean __uninitialized = true; + + public TargetAddress () + { + } + + public short discriminator () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + return __discriminator; + } + + public byte[] object_key () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyobject_key (__discriminator); + return ___object_key; + } + + public void object_key (byte[] value) + { + __discriminator = com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr.value; + ___object_key = value; + __uninitialized = false; + } + + private void verifyobject_key (short discriminator) + { + if (discriminator != com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr.value) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public org.omg.IOP.TaggedProfile profile () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyprofile (__discriminator); + return ___profile; + } + + public void profile (org.omg.IOP.TaggedProfile value) + { + __discriminator = com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr.value; + ___profile = value; + __uninitialized = false; + } + + private void verifyprofile (short discriminator) + { + if (discriminator != com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr.value) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo ior () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyior (__discriminator); + return ___ior; + } + + public void ior (com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo value) + { + __discriminator = com.sun.corba.ee.impl.protocol.giopmsgheaders.ReferenceAddr.value; + ___ior = value; + __uninitialized = false; + } + + private void verifyior (short discriminator) + { + if (discriminator != com.sun.corba.ee.impl.protocol.giopmsgheaders.ReferenceAddr.value) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public void _default () + { + __discriminator = -32768; + __uninitialized = false; + } + +} // class TargetAddress diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddressHelper.java b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddressHelper.java new file mode 100644 index 000000000..01cf4763f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddressHelper.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol.giopmsgheaders; + + +/** +* com/sun/corba/ee/impl/protocol/giopmsgheaders/TargetAddressHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ../../../../../../../src/share/classes/com/sun/corba/ee/GiopIDL/g.idl +* Sunday, June 4, 2000 5:18:54 PM PDT +*/ + +abstract public class TargetAddressHelper +{ + private static String _id = "IDL:messages/TargetAddress:1.0"; + + public static void insert (org.omg.CORBA.Any a, com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddress that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddress extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + org.omg.CORBA.TypeCode _disTypeCode0; + _disTypeCode0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + _disTypeCode0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.corba.ee.impl.protocol.giopmsgheaders.AddressingDispositionHelper.id (), "AddressingDisposition", _disTypeCode0); + org.omg.CORBA.UnionMember[] _members0 = new org.omg.CORBA.UnionMember [3]; + org.omg.CORBA.TypeCode _tcOf_members0; + org.omg.CORBA.Any _anyOf_members0; + + // Branch for object_key + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_short ((short)com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr.value); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_octet); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _members0[0] = new org.omg.CORBA.UnionMember ( + "object_key", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for profile + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_short ((short)com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr.value); + _tcOf_members0 = org.omg.IOP.TaggedProfileHelper.type (); + _members0[1] = new org.omg.CORBA.UnionMember ( + "profile", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for ior + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_short ((short)com.sun.corba.ee.impl.protocol.giopmsgheaders.ReferenceAddr.value); + _tcOf_members0 = com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.type (); + _members0[2] = new org.omg.CORBA.UnionMember ( + "ior", + _anyOf_members0, + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_union_tc (com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddressHelper.id (), "TargetAddress", _disTypeCode0, _members0); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddress read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddress value = new com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddress (); + short _dis0 = (short)0; + _dis0 = istream.read_short (); + switch (_dis0) + { + case com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr.value: + byte _object_key[] = null; + int _len1 = istream.read_long (); + _object_key = new byte[_len1]; + istream.read_octet_array (_object_key, 0, _len1); + value.object_key (_object_key); + break; + case com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr.value: + org.omg.IOP.TaggedProfile _profile = null; + _profile = org.omg.IOP.TaggedProfileHelper.read (istream); + value.profile (_profile); + break; + case com.sun.corba.ee.impl.protocol.giopmsgheaders.ReferenceAddr.value: + com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfo _ior = null; + _ior = com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.read (istream); + value.ior (_ior); + break; + default: + throw new org.omg.CORBA.BAD_OPERATION (); + } + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.corba.ee.impl.protocol.giopmsgheaders.TargetAddress value) + { + ostream.write_short (value.discriminator ()); + switch (value.discriminator ()) + { + case com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr.value: + ostream.write_long (value.object_key ().length); + ostream.write_octet_array (value.object_key (), 0, value.object_key ().length); + break; + case com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr.value: + org.omg.IOP.TaggedProfileHelper.write (ostream, value.profile ()); + break; + case com.sun.corba.ee.impl.protocol.giopmsgheaders.ReferenceAddr.value: + com.sun.corba.ee.impl.protocol.giopmsgheaders.IORAddressingInfoHelper.write (ostream, value.ior ()); + break; + default: + throw new org.omg.CORBA.BAD_OPERATION (); + } + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/BootstrapResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/BootstrapResolverImpl.java new file mode 100644 index 000000000..46c63edae --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/BootstrapResolverImpl.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import org.omg.CORBA.portable.InputStream ; +import org.omg.CORBA.portable.OutputStream ; +import org.omg.CORBA.portable.ApplicationException ; +import org.omg.CORBA.portable.RemarshalException ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.resolver.Resolver ; + +import com.sun.corba.ee.impl.ior.ObjectIdImpl; +import com.sun.corba.ee.impl.ior.ObjectKeyImpl; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.impl.misc.ORBUtility ; +import java.util.Set; + +public class BootstrapResolverImpl implements Resolver { + private org.omg.CORBA.portable.Delegate bootstrapDelegate ; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public BootstrapResolverImpl(ORB orb, String host, int port) { + // Create a new IOR with the magic of INIT + byte[] initialKey = "INIT".getBytes(); + ObjectKey okey = new ObjectKeyImpl(orb.getWireObjectKeyTemplate(), + new ObjectIdImpl(initialKey)); + + IIOPAddress addr = IIOPFactories.makeIIOPAddress( host, port ) ; + IIOPProfileTemplate ptemp = IIOPFactories.makeIIOPProfileTemplate( + orb, GIOPVersion.V1_0, addr); + + IORTemplate iortemp = IORFactories.makeIORTemplate( okey.getTemplate() ) ; + iortemp.add( ptemp ) ; + + IOR initialIOR = iortemp.makeIOR( orb, "", okey.getId() ) ; + + bootstrapDelegate = ORBUtility.makeClientDelegate( initialIOR ) ; + } + + /** + * For the BootStrap operation we do not expect to have more than one + * parameter. We do not want to extend BootStrap protocol any further, + * as INS handles most of what BootStrap can handle in a portable way. + * + * @return InputStream which contains the response from the + * BootStrapOperation. + */ + private InputStream invoke( String operationName, String parameter ) + { + boolean remarshal = true; + + // Invoke. + + InputStream inStream = null; + + // If there is a location forward then you will need + // to invoke again on the updated information. + // Just calling this same routine with the same host/port + // does not take the location forward info into account. + + while (remarshal) { + org.omg.CORBA.Object objref = null ; + remarshal = false; + + OutputStream os = bootstrapDelegate.request(objref, operationName, + true); + + if ( parameter != null ) { + os.write_string( parameter ); + } + + try { + // The only reason a null objref is passed is to get the version of + // invoke used by streams. Otherwise the PortableInterceptor + // call stack will become unbalanced since the version of + // invoke which only takes the stream does not call + // PortableInterceptor ending points. + // Note that the first parameter is ignored inside invoke. + + inStream = bootstrapDelegate.invoke( objref, os); + } catch (ApplicationException e) { + throw wrapper.bootstrapApplicationException( e ) ; + } catch (RemarshalException e) { + wrapper.bootstrapRemarshalException( e ) ; + remarshal = true; + } + } + + return inStream; + } + + public org.omg.CORBA.Object resolve( String identifier ) + { + InputStream inStream = null ; + org.omg.CORBA.Object result = null ; + + try { + inStream = invoke( "get", identifier ) ; + + result = inStream.read_Object(); + + // NOTE: do note trap and ignore errors. + // Let them flow out. + } finally { + bootstrapDelegate.releaseReply( null, inStream ) ; + } + + return result ; + } + + public Set list() + { + InputStream inStream = null ; + java.util.Set result = new java.util.HashSet() ; + + try { + inStream = invoke( "list", null ) ; + + int count = inStream.read_long(); + for (int i=0; i < count; i++) { + result.add(inStream.read_string()); + } + + // NOTE: do note trap and ignore errors. + // Let them flow out. + } finally { + bootstrapDelegate.releaseReply( null, inStream ) ; + } + + return result ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/CompositeResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/CompositeResolverImpl.java new file mode 100644 index 000000000..f72f1d7d3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/CompositeResolverImpl.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import java.util.Set ; +import java.util.HashSet ; + +import com.sun.corba.ee.spi.resolver.Resolver ; + +public class CompositeResolverImpl implements Resolver { + private Resolver first ; + private Resolver second ; + + public CompositeResolverImpl( Resolver first, Resolver second ) + { + this.first = first ; + this.second = second ; + } + + public org.omg.CORBA.Object resolve( String name ) + { + org.omg.CORBA.Object result = first.resolve( name ) ; + if (result == null) + result = second.resolve( name ) ; + return result ; + } + + public Set list() + { + Set result = new HashSet() ; + result.addAll( first.list() ) ; + result.addAll( second.list() ) ; + return result ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/FileResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/FileResolverImpl.java new file mode 100644 index 000000000..0f5787306 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/FileResolverImpl.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import com.sun.corba.ee.spi.resolver.Resolver ; + +import java.util.Enumeration; +import java.util.Properties; +import java.util.Set; +import java.util.HashSet; + +import java.io.File; +import java.io.FileInputStream; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.impl.misc.CorbaResourceUtil ; + +public class FileResolverImpl implements Resolver +{ + private ORB orb ; + private File file ; + private Properties savedProps ; + private long fileModified = 0 ; + + public FileResolverImpl( ORB orb, File file ) + { + this.orb = orb ; + this.file = file ; + savedProps = new Properties() ; + } + + public org.omg.CORBA.Object resolve( String name ) + { + check() ; + String stringifiedObject = savedProps.getProperty( name ) ; + if (stringifiedObject == null) { + return null; + } + return orb.string_to_object( stringifiedObject ) ; + } + + public Set list() + { + check() ; + + Set result = new HashSet() ; + + // Obtain all the keys from the property object + Enumeration theKeys = savedProps.propertyNames(); + while (theKeys.hasMoreElements()) { + result.add( theKeys.nextElement() ) ; + } + + return result ; + } + + /** + * Checks the lastModified() timestamp of the file and optionally + * re-reads the Properties object from the file if newer. + */ + private void check() + { + if (file == null) { + return; + } + + long lastMod = file.lastModified(); + if (lastMod > fileModified) { + try { + FileInputStream fileIS = new FileInputStream(file); + savedProps.clear(); + savedProps.load(fileIS); + fileIS.close(); + fileModified = lastMod; + } catch (java.io.FileNotFoundException e) { + System.err.println( CorbaResourceUtil.getText( + "bootstrap.filenotfound", file.getAbsolutePath())); + } catch (java.io.IOException e) { + System.err.println( CorbaResourceUtil.getText( + "bootstrap.exception", + file.getAbsolutePath(), e.toString())); + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/INSURLOperationImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/INSURLOperationImpl.java new file mode 100644 index 000000000..74bf06a94 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/INSURLOperationImpl.java @@ -0,0 +1,320 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver; + +import java.util.List ; +import java.util.Map ; +import java.util.Comparator ; +import java.util.Iterator ; +import java.util.HashMap ; +import java.util.ArrayList ; +import java.util.Collections ; + +import org.omg.CosNaming.NamingContextExt ; +import org.omg.CosNaming.NamingContextExtHelper ; +import org.omg.CORBA.ORBPackage.InvalidName ; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.IORFactories; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent; +import com.sun.corba.ee.spi.orb.Operation; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.encoding.EncapsInputStream; +import com.sun.corba.ee.impl.encoding.EncapsInputStreamFactory; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.logging.OMGSystemException ; +import com.sun.corba.ee.impl.naming.namingutil.INSURLHandler; +import com.sun.corba.ee.impl.naming.namingutil.IIOPEndpointInfo; +import com.sun.corba.ee.impl.naming.namingutil.INSURL; +import com.sun.corba.ee.impl.naming.namingutil.CorbalocURL; +import com.sun.corba.ee.impl.naming.namingutil.CorbanameURL; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +/** + * This class provides an Operation that converts from CORBA INS URL strings into + * CORBA object references. It will eventually become extensible, but for now it + * simply encapsulates the existing implementation. Once the full extensibility + * is in place, we want this operation to convert string to INSURL, which has mainly + * a public resolver method that returns an object reference. + * + * @author Hemanth + * @author Ken + */ +public class INSURLOperationImpl implements Operation +{ + private ORB orb; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + // Root Naming Context for default resolution of names. + private NamingContextExt rootNamingContextExt; + private Object rootContextCacheLock = new Object() ; + + // The URLHandler to parse INS URL's + private INSURLHandler insURLHandler = INSURLHandler.getINSURLHandler() ; + + public INSURLOperationImpl( ORB orb ) + { + this.orb = orb ; + } + + private static final int NIBBLES_PER_BYTE = 2 ; + private static final int UN_SHIFT = 4 ; // "UPPER NIBBLE" shift factor for << + + /** This static method takes a Stringified IOR and converts it into IOR object. + * It is the caller's responsibility to only pass strings that start with "IOR:". + */ + private org.omg.CORBA.Object getIORFromString( String str ) + { + // Length must be even for str to be valid + if ( (str.length() & 1) == 1 ) { + throw wrapper.badStringifiedIorLen(); + } + + byte[] buf = new byte[(str.length() - ORBConstants.STRINGIFY_PREFIX.length()) / NIBBLES_PER_BYTE]; + for (int i=ORBConstants.STRINGIFY_PREFIX.length(), j=0; i < str.length(); i +=NIBBLES_PER_BYTE, j++) { + buf[j] = (byte)((ORBUtility.hexOf(str.charAt(i)) << UN_SHIFT) & 0xF0); + buf[j] |= (byte)(ORBUtility.hexOf(str.charAt(i+1)) & 0x0F); + } + EncapsInputStream s = EncapsInputStreamFactory.newEncapsInputStream(orb, buf, buf.length, + orb.getORBData().getGIOPVersion()); + s.consumeEndian(); + return s.read_Object() ; + } + + public Object operate( Object arg ) + { + if (arg instanceof String) { + String str = (String)arg ; + + if (str.startsWith( ORBConstants.STRINGIFY_PREFIX )) { + return getIORFromString(str); + } else { + INSURL insURL = insURLHandler.parseURL( str ) ; + if (insURL == null) { + throw omgWrapper.soBadSchemeName(str); + } + return resolveINSURL( insURL ) ; + } + } + + throw wrapper.stringExpected() ; + } + + private org.omg.CORBA.Object resolveINSURL( INSURL theURLObject ) { + if( theURLObject.isCorbanameURL() ) { + return resolveCorbaname( (CorbanameURL)theURLObject ); + } else { + return resolveCorbaloc( (CorbalocURL)theURLObject ); + } + } + + /** + * resolves a corbaloc: url that is encapsulated in a CorbalocURL object. + * + * @return the CORBA.Object if resolution is successful + */ + private org.omg.CORBA.Object resolveCorbaloc( + CorbalocURL theCorbaLocObject ) + { + org.omg.CORBA.Object result = null; + // If RIR flag is true use the Bootstrap protocol + // Bug 6678177 noticed that this is incorrect: rir means use + // resolve_initial_references on the local ORB! + if( theCorbaLocObject.getRIRFlag( ) ) { + String keyString = theCorbaLocObject.getKeyString() ; + if (keyString.equals( "" )) { + keyString = "NameService"; + } + + try { + result = orb.resolve_initial_references( keyString ) ; + } catch (InvalidName exc) { + throw omgWrapper.soBadSchemaSpecific( exc, keyString ) ; + } + } else { + result = getIORUsingCorbaloc( theCorbaLocObject ); + } + + return result; + } + + /** + * resolves a corbaname: url that is encapsulated in a CorbanameURL object. + * + * @return the CORBA.Object if resolution is successful + */ + private org.omg.CORBA.Object resolveCorbaname( CorbanameURL theCorbaName ) { + org.omg.CORBA.Object result = null; + + try { + NamingContextExt theNamingContext = null; + + if( theCorbaName.getRIRFlag( ) ) { + // Case 1 of corbaname: rir# + theNamingContext = getDefaultRootNamingContext( ); + } else { + // Case 2 of corbaname: ::hostname# + org.omg.CORBA.Object corbalocResult = + getIORUsingCorbaloc( theCorbaName ); + if( corbalocResult == null ) { + return null; + } + + theNamingContext = + NamingContextExtHelper.narrow( corbalocResult ); + } + + String StringifiedName = theCorbaName.getStringifiedName( ); + + if( StringifiedName == null ) { + // This means return the Root Naming context + return theNamingContext; + } else { + return theNamingContext.resolve_str( StringifiedName ); + } + } catch( Exception e ) { + clearRootNamingContextCache( ); + // Bug 6475580 + throw omgWrapper.soBadSchemaSpecific( e, + theCorbaName.getStringifiedName() ) ; + } + } + + /** + * This is an internal method to get the IOR from the CorbalocURL object. + * + * @return the CORBA.Object if resolution is successful + */ + private org.omg.CORBA.Object getIORUsingCorbaloc( INSURL corbalocObject ) + { + Map profileMap = new HashMap(); + List profileList1_0 = new ArrayList(); + + // corbalocObject cannot be null, because it's validated during + // parsing. So no null check is required. + java.util.List theEndpointInfo = corbalocObject.getEndpointInfo(); + String theKeyString = corbalocObject.getKeyString(); + // If there is no KeyString then it's invalid + if( theKeyString == null ) { + return null; + } + + ObjectKey key = orb.getObjectKeyFactory().create( + theKeyString.getBytes() ); + IORTemplate iortemp = IORFactories.makeIORTemplate( key.getTemplate() ); + + java.util.Iterator iterator = theEndpointInfo.iterator( ); + while( iterator.hasNext( ) ) { + IIOPEndpointInfo element = + (IIOPEndpointInfo) iterator.next( ); + IIOPAddress addr = IIOPFactories.makeIIOPAddress( element.getHost(), + element.getPort() ); + GIOPVersion giopVersion = GIOPVersion.getInstance( (byte)element.getMajor(), + (byte)element.getMinor()); + IIOPProfileTemplate profileTemplate = null; + if (giopVersion.equals(GIOPVersion.V1_0)) { + profileTemplate = IIOPFactories.makeIIOPProfileTemplate( + orb, giopVersion, addr); + profileList1_0.add(profileTemplate); + } else { + if (profileMap.get(giopVersion) == null) { + profileTemplate = IIOPFactories.makeIIOPProfileTemplate( + orb, giopVersion, addr); + profileMap.put(giopVersion, profileTemplate); + } else { + profileTemplate = (IIOPProfileTemplate)profileMap.get(giopVersion); + AlternateIIOPAddressComponent iiopAddressComponent = + IIOPFactories.makeAlternateIIOPAddressComponent(addr); + profileTemplate.add(iiopAddressComponent); + } + } + } + + GIOPVersion giopVersion = orb.getORBData().getGIOPVersion(); + IIOPProfileTemplate pTemplate = (IIOPProfileTemplate)profileMap.get(giopVersion); + if (pTemplate != null) { + iortemp.add(pTemplate); // Add profile for GIOP version used by this ORB + profileMap.remove(giopVersion); // Now remove this value from the map + } + + // Create a comparator that can sort in decending order (1.2, 1.1, ...) + Comparator comp = new Comparator() { + public int compare(Object o1, Object o2) { + GIOPVersion gv1 = (GIOPVersion)o1; + GIOPVersion gv2 = (GIOPVersion)o2; + return (gv1.lessThan(gv2) ? 1 : (gv1.equals(gv2) ? 0 : -1)); + }; + }; + + // Now sort using the above comparator + List list = new ArrayList(profileMap.keySet()); + Collections.sort(list, comp); + + // Add the profiles in the sorted order + Iterator iter = list.iterator(); + while (iter.hasNext()) { + IIOPProfileTemplate pt = (IIOPProfileTemplate)profileMap.get(iter.next()); + iortemp.add(pt); + } + + // Finally add the 1.0 profiles + iortemp.addAll(profileList1_0); + + IOR ior = iortemp.makeIOR( orb, "", key.getId() ) ; + return ORBUtility.makeObjectReference( ior ) ; + } + + /** + * This is required for corbaname: resolution. Currently we + * are not caching RootNamingContext as the reference to rootNamingContext + * may not be Persistent in all the implementations. + * _REVISIT_ to clear the rootNamingContext in case of COMM_FAILURE. + * + * @return the org.omg.COSNaming.NamingContextExt if resolution is + * successful + * + */ + private NamingContextExt getDefaultRootNamingContext( ) { + synchronized( rootContextCacheLock ) { + if( rootNamingContextExt == null ) { + try { + rootNamingContextExt = + NamingContextExtHelper.narrow( + orb.getLocalResolver().resolve( "NameService" ) ); + } catch( Exception e ) { + rootNamingContextExt = null; + } + } + } + return rootNamingContextExt; + } + + /** + * A utility method to clear the RootNamingContext, if there is an + * exception in resolving CosNaming:Name from the RootNamingContext, + */ + private void clearRootNamingContextCache( ) { + synchronized( rootContextCacheLock ) { + rootNamingContextExt = null; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/LocalResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/LocalResolverImpl.java new file mode 100644 index 000000000..53a6378e2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/LocalResolverImpl.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import com.sun.corba.ee.spi.resolver.LocalResolver ; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.TimeUnit; +import org.glassfish.pfl.basic.func.NullaryFunction; + +public class LocalResolverImpl implements LocalResolver { + ConcurrentHashMap> nameToClosure = + new ConcurrentHashMap>() ; + final Lock lock = new ReentrantLock(); + + public org.omg.CORBA.Object resolve(String name) { + do { + try { + if (lock.tryLock(500, TimeUnit.MILLISECONDS)) { + try { + NullaryFunction cl = nameToClosure.get(name); + if (cl == null) { + return null; + } + return (org.omg.CORBA.Object) (cl.evaluate()); + } finally { + lock.unlock(); + } + } else { + // continue, try again + } + } catch (InterruptedException e) { + // do nothing + } + } while (true); + } + + public java.util.Set list() { + return nameToClosure.keySet() ; + } + + public void register( String name, + NullaryFunction closure ) { + nameToClosure.put( name, closure ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/ORBDefaultInitRefResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/ORBDefaultInitRefResolverImpl.java new file mode 100644 index 000000000..9148527c3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/ORBDefaultInitRefResolverImpl.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import com.sun.corba.ee.spi.resolver.Resolver ; + +import com.sun.corba.ee.spi.orb.Operation ; +import java.util.Set; + +public class ORBDefaultInitRefResolverImpl implements Resolver { + Operation urlHandler ; + String orbDefaultInitRef ; + + public ORBDefaultInitRefResolverImpl( Operation urlHandler, String orbDefaultInitRef ) + { + this.urlHandler = urlHandler ; + + this.orbDefaultInitRef = orbDefaultInitRef ; + } + + public org.omg.CORBA.Object resolve( String ident ) + { + // If the ORBDefaultInitRef is not defined simply return null + if( orbDefaultInitRef == null ) { + return null; + } + + String urlString; + // If the ORBDefaultInitDef is defined as corbaloc: then create the + // corbaloc String in the format + // / + // and resolve it using resolveCorbaloc method + if( orbDefaultInitRef.startsWith( "corbaloc:" ) ) { + urlString = orbDefaultInitRef + "/" + ident; + } else { + urlString = orbDefaultInitRef + "#" + ident; + } + + return (org.omg.CORBA.Object)urlHandler.operate( urlString ) ; + } + + public Set list() + { + return new java.util.HashSet() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/ORBInitRefResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/ORBInitRefResolverImpl.java new file mode 100644 index 000000000..4afa9f84b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/ORBInitRefResolverImpl.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import com.sun.corba.ee.spi.resolver.Resolver ; + +import com.sun.corba.ee.spi.orb.Operation ; +import java.util.Set; +import org.glassfish.pfl.basic.contain.Pair; + +public class ORBInitRefResolverImpl implements Resolver { + Operation urlHandler ; + java.util.Map orbInitRefTable ; + + public ORBInitRefResolverImpl( Operation urlHandler, Pair[] initRefs ) + { + this.urlHandler = urlHandler ; + orbInitRefTable = new java.util.HashMap() ; + + for( int i = 0; i < initRefs.length ; i++ ) { + Pair sp = initRefs[i] ; + orbInitRefTable.put( sp.first(), sp.second() ) ; + } + } + + public org.omg.CORBA.Object resolve( String ident ) + { + String url = (String)orbInitRefTable.get( ident ) ; + if (url == null) + return null ; + + org.omg.CORBA.Object result = + (org.omg.CORBA.Object)urlHandler.operate( url ) ; + return result ; + } + + public Set list() + { + return orbInitRefTable.keySet() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/SplitLocalResolverImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/SplitLocalResolverImpl.java new file mode 100644 index 000000000..effa0bb4e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/resolver/SplitLocalResolverImpl.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.resolver ; + +import com.sun.corba.ee.spi.resolver.Resolver ; +import com.sun.corba.ee.spi.resolver.LocalResolver ; +import java.util.Set; +import org.glassfish.pfl.basic.func.NullaryFunction; + +public class SplitLocalResolverImpl implements LocalResolver +{ + private Resolver resolver ; + private LocalResolver localResolver ; + + public SplitLocalResolverImpl( Resolver resolver, + LocalResolver localResolver ) { + this.resolver = resolver ; + this.localResolver = localResolver ; + } + + public void register( String name, + NullaryFunction closure ) { + localResolver.register( name, closure ) ; + } + + public org.omg.CORBA.Object resolve( String name ) { + return resolver.resolve( name ) ; + } + + public Set list() { + return resolver.list() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/CodeSetServiceContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/CodeSetServiceContextImpl.java new file mode 100644 index 000000000..0ee48eed1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/CodeSetServiceContextImpl.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextBase; +import com.sun.corba.ee.spi.servicecontext.CodeSetServiceContext; + +import com.sun.corba.ee.impl.encoding.MarshalInputStream ; +import com.sun.corba.ee.impl.encoding.MarshalOutputStream ; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; + +public class CodeSetServiceContextImpl extends ServiceContextBase + implements CodeSetServiceContext +{ + private CodeSetComponentInfo.CodeSetContext csc ; + + public CodeSetServiceContextImpl( CodeSetComponentInfo.CodeSetContext csc ) + { + this.csc = csc ; + } + + public CodeSetServiceContextImpl(InputStream is, GIOPVersion gv) + { + super(is) ; + csc = new CodeSetComponentInfo.CodeSetContext() ; + csc.read( (MarshalInputStream)in ) ; + } + + public int getId() + { + return SERVICE_CONTEXT_ID ; + } + + public void writeData( OutputStream os ) + { + csc.write( (MarshalOutputStream)os ) ; + } + + public CodeSetComponentInfo.CodeSetContext getCodeSetContext() + { + return csc ; + } + + public String toString() + { + return "CodeSetServiceContextImpl[ csc=" + csc + " ]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/MaxStreamFormatVersionServiceContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/MaxStreamFormatVersionServiceContextImpl.java new file mode 100644 index 000000000..0d205db2f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/MaxStreamFormatVersionServiceContextImpl.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.servicecontext.ServiceContextBase ; +import com.sun.corba.ee.spi.servicecontext.MaxStreamFormatVersionServiceContext ; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class MaxStreamFormatVersionServiceContextImpl extends ServiceContextBase + implements MaxStreamFormatVersionServiceContext +{ + private byte maxStreamFormatVersion; + + // The singleton uses the maximum version indicated by our + // ValueHandler. + public static final MaxStreamFormatVersionServiceContext singleton + = new MaxStreamFormatVersionServiceContextImpl(); + + private MaxStreamFormatVersionServiceContextImpl() + { + maxStreamFormatVersion = ORBUtility.getMaxStreamFormatVersion(); + } + + public MaxStreamFormatVersionServiceContextImpl(byte maxStreamFormatVersion) + { + this.maxStreamFormatVersion = maxStreamFormatVersion; + } + + public MaxStreamFormatVersionServiceContextImpl(InputStream is, GIOPVersion gv) + { + super(is) ; + + maxStreamFormatVersion = is.read_octet(); + } + + public int getId() + { + return SERVICE_CONTEXT_ID; + } + + public void writeData(OutputStream os) + { + os.write_octet(maxStreamFormatVersion); + } + + public byte getMaximumStreamFormatVersion() + { + return maxStreamFormatVersion; + } + + public String toString() + { + return "MaxStreamFormatVersionServiceContextImpl[" + + maxStreamFormatVersion + "]"; + } +} + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ORBVersionServiceContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ORBVersionServiceContextImpl.java new file mode 100644 index 000000000..cc277de16 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ORBVersionServiceContextImpl.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.servicecontext.ServiceContextBase ; +import com.sun.corba.ee.spi.servicecontext.ORBVersionServiceContext ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +public class ORBVersionServiceContextImpl extends ServiceContextBase + implements ORBVersionServiceContext +{ + // current ORB Version + private ORBVersion version = ORBVersionFactory.getORBVersion() ; + + public static final ORBVersionServiceContext singleton = + new ORBVersionServiceContextImpl() ; + + public ORBVersionServiceContextImpl( ) + { + version = ORBVersionFactory.getORBVersion() ; + } + + public ORBVersionServiceContextImpl( ORBVersion ver ) + { + this.version = ver ; + } + + public ORBVersionServiceContextImpl(InputStream is, GIOPVersion gv) + { + super(is) ; + // pay particular attention to where the version is being read from! + // is contains an encapsulation, ServiceContext reads off the + // encapsulation and leaves the pointer in the variable "in", + // which points to the long value. + + version = ORBVersionFactory.create( in ) ; + } + + public int getId() + { + return SERVICE_CONTEXT_ID ; + } + + public void writeData( OutputStream os ) throws SystemException + { + version.write( os ) ; + } + + public ORBVersion getVersion() + { + return version ; + } + + public String toString() + { + return "ORBVersionServiceContextImpl[ version=" + version + " ]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/SendingContextServiceContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/SendingContextServiceContextImpl.java new file mode 100644 index 000000000..8b4a579ad --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/SendingContextServiceContextImpl.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactories ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextBase ; +import com.sun.corba.ee.spi.servicecontext.SendingContextServiceContext ; + +public class SendingContextServiceContextImpl extends ServiceContextBase + implements SendingContextServiceContext +{ + private IOR ior = null ; + + public SendingContextServiceContextImpl( IOR ior ) + { + this.ior = ior ; + } + + public SendingContextServiceContextImpl(InputStream is, GIOPVersion gv) + { + super(is) ; + ior = IORFactories.makeIOR( (ORB)is.orb(), is ) ; + } + + public int getId() + { + return SERVICE_CONTEXT_ID ; + } + + public void writeData( OutputStream os ) + { + ior.write( os ) ; + } + + public IOR getIOR() + { + return ior ; + } + + public String toString() + { + return "SendingContexServiceContextImpl[ ior=" + ior + " ]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ServiceContextFactoryRegistryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ServiceContextFactoryRegistryImpl.java new file mode 100644 index 000000000..b505ad77a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ServiceContextFactoryRegistryImpl.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import java.util.Map ; +import java.util.HashMap ; +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +public class ServiceContextFactoryRegistryImpl + implements ServiceContextFactoryRegistry +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + final private ORB orb ; + private Map scMap ; + + public ServiceContextFactoryRegistryImpl( ORB orb ) + { + scMap = new HashMap() ; + this.orb = orb ; + } + + public void register( ServiceContext.Factory factory ) + { + if (scMap.get(factory.getId()) == null) { + scMap.put(factory.getId(), factory); + } else { + wrapper.registerDuplicateServiceContext(); + } // BAD_PARAM + } + + public ServiceContext.Factory find( int scId ) + { + ServiceContext.Factory result = scMap.get( scId ) ; + return result ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ServiceContextsImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ServiceContextsImpl.java new file mode 100644 index 000000000..6b9c9edab --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/ServiceContextsImpl.java @@ -0,0 +1,349 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import java.util.Map ; +import java.util.HashMap ; +import java.util.concurrent.atomic.AtomicInteger ; + +import org.omg.CORBA.OctetSeqHelper; +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.org.omg.SendingContext.CodeBase; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults ; +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts ; +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry ; +import com.sun.corba.ee.spi.servicecontext.UEInfoServiceContext ; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.EncapsInputStream ; +import com.sun.corba.ee.impl.encoding.EncapsInputStreamFactory; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.trace.TraceServiceContext; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@TraceServiceContext +public class ServiceContextsImpl implements ServiceContexts +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static final AtomicInteger creationCount = new AtomicInteger(0) ; + + private final ORB orb ; + + /** + * Map of all ServiceContext objects in this container. + * + * Keys are java.lang.Integers for service context IDs. + * Values are either instances of ServiceContext or the + * unmarshaled byte arrays (unmarshaled on first use). + * + * This provides a mild optimization if we don't happen to + * use a given service context, but it's main advantage is + * that it allows us to change the order in which we + * unmarshal them. We need to do the UnknownExceptionInfo service + * context after the SendingContextRunTime service context so that we can + * get the CodeBase if necessary. + */ + private final Map scMap; + + private CodeBase codeBase; + private GIOPVersion giopVersion; + + private String getValidSCIds() { + StringBuilder sb = new StringBuilder() ; + sb.append( "(" ) ; + boolean first = true ; + for (int id : scMap.keySet()) { + if (first) { + first = false; + } else { + sb.append(","); + } + + sb.append( id ) ; + } + sb.append( ")" ) ; + return sb.toString() ; + } + + @InfoMethod + private void numberValid( int num ) { } + + @InfoMethod + private void readingServiceContextId( int id ) { } + + @InfoMethod + private void serviceContextLength( int len ) { } + + /** + * Given the input stream, this fills our service + * context map. See the definition of scMap for + * details. Creates a HashMap. + * + * Note that we don't actually unmarshal the + * bytes of the service contexts here. That is + * done when they are actually requested via + * get(int). + */ + @TraceServiceContext + private void createMapFromInputStream(InputStream is) { + int numValid = is.read_long() ; + numberValid( numValid ) ; + + for (int ctr = 0; ctr < numValid; ctr++) { + int scId = is.read_long(); + readingServiceContextId(scId); + + byte[] data = OctetSeqHelper.read(is); + serviceContextLength(data.length); + + scMap.put(scId, data); + } + } + + public ServiceContextsImpl( ORB orb ) { + this.orb = orb ; + + scMap = new HashMap(); + + // Use the GIOP version of the ORB. Should + // be specified in ServiceContext. + // See REVISIT below concerning giopVersion. + giopVersion = orb.getORBData().getGIOPVersion(); + codeBase = null ; + } + + /** + * Read the Service contexts from the input stream. + */ + public ServiceContextsImpl(InputStream s) { + this( (ORB)(s.orb()) ) ; + + // We need to store this so that we can have access + // to the CodeBase for unmarshaling possible + // RMI-IIOP valuetype data within an encapsulation. + // (Known case: UnknownExceptionInfo) + codeBase = ((CDRInputObject)s).getCodeBase(); + + + createMapFromInputStream(s); + + // Fix for bug 4904723 + giopVersion = ((CDRInputObject)s).getGIOPVersion(); + } + + @InfoMethod + private void couldNotFindServiceContextFactory( int scid ) { } + + @InfoMethod + private void foundServiceContextFactory( int scid ) { } + + /** + * Find the ServiceContextData for a given scId and unmarshal + * the bytes. + */ + @TraceServiceContext + private ServiceContext unmarshal(int scId, byte[] data) { + ServiceContextFactoryRegistry scr = + orb.getServiceContextFactoryRegistry(); + + ServiceContext.Factory factory = scr.find(scId); + ServiceContext sc = null; + + if (factory == null) { + couldNotFindServiceContextFactory(scId); + sc = ServiceContextDefaults.makeUnknownServiceContext(scId, data); + } else { + foundServiceContextFactory(scId); + + // REVISIT. GIOP version should be specified as + // part of a service context's definition, so should + // be accessible from ServiceContextData via + // its ServiceContext implementation class. + // + // Since we don't have that, yet, I'm using the GIOP + // version of the input stream, presuming that someone + // can't send a service context of a later GIOP + // version than its stream version. + // + // Note: As of Jan 2001, no standard OMG or Sun service contexts + // ship wchar data or are defined as using anything but GIOP 1.0 CDR. + EncapsInputStream eis = EncapsInputStreamFactory.newEncapsInputStream(orb, data, data.length, + giopVersion, codeBase); + + try { + eis.consumeEndian(); + // Now the input stream passed to a ServiceContext + // constructor is already the encapsulation input + // stream with the endianness read off, so the + // service context should just unmarshal its own + // data. + sc =factory.create(eis, giopVersion); + } finally { + try { + eis.close(); + } catch (java.io.IOException e) { + wrapper.ioexceptionDuringStreamClose(e); + } + } + + if (sc == null) { + throw wrapper.svcctxUnmarshalError(); + } + } + + return sc; + } + + /** + * Write the service contexts to the output stream. + * + * If they haven't been unmarshaled, we don't have to + * unmarshal them. + */ + @TraceServiceContext + public void write(OutputStream os, GIOPVersion gv) { + int numsc = scMap.size(); + os.write_long( numsc ) ; + + writeServiceContextsInOrder(os, gv); + } + + /** + * Write the service contexts in scMap in a desired order. + * Right now, the only special case we have is UnknownExceptionInfo, + * so I'm merely writing it last if present. + */ + @TraceServiceContext + private void writeServiceContextsInOrder(OutputStream os, GIOPVersion gv) { + int ueid = UEInfoServiceContext.SERVICE_CONTEXT_ID ; + + for (int i : scMap.keySet() ) { + if (i != ueid) { + writeMapEntry(os, i, scMap.get(i), gv); + } + } + + // Write the UnknownExceptionInfo service context last + // (so it will be after the CodeBase) + Object uesc = scMap.get(ueid) ; + if (uesc != null) { + writeMapEntry(os, ueid, uesc, gv); + } + } + + @InfoMethod + private void writingServiceContextBytesFor( int id ) { } + + @InfoMethod + private void writingServiceContext( ServiceContext sc ) { } + + /** + * Write the given entry from the scMap to the OutputStream. + * See note on giopVersion. The service context should + * know the GIOP version it is meant for. + */ + @TraceServiceContext + private void writeMapEntry(OutputStream os, int id, Object scObj, + GIOPVersion gv) { + if (scObj instanceof byte[]) { + // If it's still in byte[] form, we don't need to + // unmarshal it here, just copy the bytes into + // the new stream. + byte[] sc = (byte[])scObj ; + + writingServiceContextBytesFor(id); + OctetSeqHelper.write(os, sc); + } else if (scObj instanceof ServiceContext) { + // We actually unmarshaled it into a ServiceContext + // at some point. + ServiceContext sc = (ServiceContext)scObj; + + writingServiceContext(sc); + sc.write(os, gv); + } else { + wrapper.errorInServiceContextMap() ; + } + } + + @TraceServiceContext + public void put( ServiceContext sc ) + { + scMap.put(sc.getId(), sc); + } + + @TraceServiceContext + public void delete( int scId ) + { + scMap.remove(scId); + } + + @InfoMethod + private void serviceContextIdFound( int id ) { } + + @InfoMethod + private void serviceContextIdNotFound( int id ) { } + + @InfoMethod + private void unmarshallingServiceContext( int id ) { } + + @TraceServiceContext + public ServiceContext get(int id) { + Object result = scMap.get(id); + if (result == null) { + serviceContextIdNotFound(id); + return null ; + } + + serviceContextIdFound(id); + + // Lazy unmarshaling on first use. + if (result instanceof byte[]) { + unmarshallingServiceContext(id) ; + + ServiceContext sc = unmarshal(id, (byte[])result); + + scMap.put(id, sc); + + return sc; + } else { + return (ServiceContext)result; + } + } + + private ServiceContextsImpl( ServiceContextsImpl scimpl ) { + this( scimpl.orb ) ; + + this.codeBase = scimpl.codeBase ; + this.giopVersion = scimpl.giopVersion ; + for (Map.Entry entry : scimpl.scMap.entrySet() ) { + this.scMap.put( entry.getKey(), entry.getValue() ) ; + } + } + + /** + * send back a shallow copy of the ServiceContexts container + */ + @TraceServiceContext + public ServiceContexts copy() { + ServiceContexts result = new ServiceContextsImpl( this ) ; + return result; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/UEInfoServiceContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/UEInfoServiceContextImpl.java new file mode 100644 index 000000000..67d82986a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/UEInfoServiceContextImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import java.io.Serializable ; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.servicecontext.ServiceContextBase ; +import com.sun.corba.ee.spi.servicecontext.UEInfoServiceContext ; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +public class UEInfoServiceContextImpl extends ServiceContextBase + implements UEInfoServiceContext +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private Throwable unknown = null ; + + public UEInfoServiceContextImpl( Throwable ex ) + { + unknown = ex ; + } + + public UEInfoServiceContextImpl(InputStream is, GIOPVersion gv) + { + super(is) ; + + try { + unknown = (Throwable) in.read_value() ; + } catch (Exception e) { + unknown = wrapper.couldNotReadInfo( e ) ; + } + } + + public int getId() + { + return SERVICE_CONTEXT_ID ; + } + + public void writeData( OutputStream os ) + { + os.write_value( (Serializable)unknown ) ; + } + + public Throwable getUE() { return unknown ; } + + @Override + public String toString() + { + return "UEInfoServiceContextImpl[ unknown=" + unknown.toString() + " ]" ; + } +} + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/UnknownServiceContextImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/UnknownServiceContextImpl.java new file mode 100644 index 000000000..44d10b4f8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/servicecontext/UnknownServiceContextImpl.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.servicecontext.ServiceContextBase ; +import com.sun.corba.ee.spi.servicecontext.UnknownServiceContext ; + +public class UnknownServiceContextImpl extends ServiceContextBase + implements UnknownServiceContext +{ + private int id = -1 ; + private byte[] data = null ; + + public UnknownServiceContextImpl( int id, byte[] data ) + { + this.id = id ; + this.data = data.clone() ; + } + + public UnknownServiceContextImpl( int id, InputStream is ) + { + this.id = id ; + + int len = is.read_long(); + data = new byte[len]; + is.read_octet_array(data,0,len); + } + + public int getId() { return id ; } + + public void writeData( OutputStream os ) + { + // Abstract method in the base class not used + // here because write overrides ServiceContextBase.write + } + + public void write( OutputStream os, GIOPVersion gv) + { + os.write_long( id ) ; + os.write_long( data.length ) ; + os.write_octet_array( data, 0, data.length ) ; + } + + public byte[] getData() + { + return data.clone() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorAcceptOnlyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorAcceptOnlyImpl.java new file mode 100644 index 000000000..e219aff4b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorAcceptOnlyImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.impl.oa.poa.Policies; +import com.sun.corba.ee.spi.ior.IORTemplate; +import java.net.Socket; + +import com.sun.corba.ee.spi.orb.ORB; +import org.glassfish.pfl.basic.func.UnaryVoidFunction ; + +/** This version of an acceptor is the other half of CorbaAcceptorLazyImpl. + * The idea is that AcceptOnly will NOT contribute to an IORTemplate, and will + * actually accept from a ServerSocket (and so it must initialize the + * server socket and close it). The LazyImpl will contribute to an IORTemplate, + * and will not actually accept, but does the actual processing of sockets + * from the server socket. + * + * @author ken + */ +public class AcceptorAcceptOnlyImpl extends AcceptorImpl { + private UnaryVoidFunction operation ; + + public AcceptorAcceptOnlyImpl( ORB orb, int port, + String name, String type, UnaryVoidFunction operation ) { + super( orb, port, name, type ) ; + this.operation = operation ; + } + + @Override + public void accept() { + operation.evaluate( getAcceptedSocket() ) ; + } + + @Override + public void addToIORTemplate(IORTemplate iorTemplate, Policies policies, String codebase) { + // does nothing in this case. + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorBase.java new file mode 100644 index 000000000..efe1a4edf --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorBase.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.oa.poa.Policies; +import com.sun.corba.ee.spi.extension.RequestPartitioningPolicy; +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress; +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketEndPointInfo; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.EventHandler; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.SocketInfo; +import com.sun.corba.ee.spi.transport.Selector; +import com.sun.corba.ee.spi.transport.InboundConnectionCache; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.extension.LoadBalancingPolicy; +import com.sun.corba.ee.spi.trace.Transport; +import java.nio.channels.SelectionKey; +import java.util.Iterator; +import java.net.Socket ; +import org.omg.IOP.TAG_INTERNET_IOP; + +/** + * + * @author ken + */ +@Transport +public abstract class AcceptorBase + extends + EventHandlerBase + implements + Acceptor, + Work, + // BEGIN Legacy + SocketInfo, + LegacyServerSocketEndPointInfo + // END Legacy +{ + protected ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + protected int port ; + protected long enqueueTime; + protected boolean initialized = false ; + + // BEGIN legacy + protected String type = ""; + protected String name = ""; + protected String hostname ; + protected int locatorPort; + // END legacy + + protected InboundConnectionCache connectionCache; + + public int getPort() { + return port ; + } + + public String getInterfaceName() { + String result = name.equals(LegacyServerSocketEndPointInfo.NO_NAME) ? this.toString() : name; + return result; + } + + // Need this for the work interface. + public String getName() { + return getInterfaceName() ; + } + + public String getType() { + return type ; + } + + public boolean isLazy() { + return false ; + } + + public AcceptorBase(ORB orb, int port, + String name, String type) + { + this.orb = orb; + + setWork(this); + + // BEGIN Legacy support. + this.hostname = orb.getORBData().getORBServerHost(); + this.name = LegacyServerSocketEndPointInfo.NO_NAME; + this.locatorPort = -1; + // END Legacy support. + + this.port = port; + this.name = name; + this.type = type; + } + + @Transport + public void processSocket( Socket socket ) { + Connection connection = + new ConnectionImpl(orb, this, socket); + + // NOTE: The connection MUST be put in the cache BEFORE being + // registered with the selector. Otherwise if the bytes + // are read on the connection it will attempt a time stamp + // but the cache will be null, resulting in NPE. + getConnectionCache().put(this, connection); + + if (connection.shouldRegisterServerReadEvent()) { + Selector selector = orb.getTransportManager().getSelector(0); + selector.registerForEvent(connection.getEventHandler()); + } + + getConnectionCache().reclaim(); + } + + @Transport + public void addToIORTemplate(IORTemplate iorTemplate, Policies policies, String codebase) { + Iterator iterator = iorTemplate.iteratorById(TAG_INTERNET_IOP.value); + String hname = orb.getORBData().getORBServerHost(); + if (iterator.hasNext()) { + // NEVER create an AlternateIIOPAddress for an SSL acceptor! + if (!type.startsWith( SocketInfo.SSL_PREFIX )) { + IIOPAddress iiopAddress = IIOPFactories.makeIIOPAddress(hname, port); + AlternateIIOPAddressComponent iiopAddressComponent = + IIOPFactories.makeAlternateIIOPAddressComponent(iiopAddress); + while (iterator.hasNext()) { + TaggedProfileTemplate taggedProfileTemplate = + (TaggedProfileTemplate)iterator.next(); + taggedProfileTemplate.add(iiopAddressComponent); + } + } + } else { + IIOPProfileTemplate iiopProfile = makeIIOPProfileTemplate(policies, codebase); + iorTemplate.add(iiopProfile); + } + } + + @Transport + protected final IIOPProfileTemplate makeIIOPProfileTemplate(Policies policies, String codebase) { + GIOPVersion version = orb.getORBData().getGIOPVersion(); + int templatePort; + if (policies.forceZeroPort()) { + templatePort = 0; + } else if (policies.isTransient()) { + templatePort = port; + } else { + templatePort = orb.getLegacyServerSocketManager() + .legacyGetPersistentServerPort(SocketInfo.IIOP_CLEAR_TEXT); + } + IIOPAddress addr = IIOPFactories.makeIIOPAddress(hostname, + templatePort); + IIOPProfileTemplate iiopProfile = IIOPFactories.makeIIOPProfileTemplate(orb, + version, addr); + + if (version.supportsIORIIOPProfileComponents()) { + iiopProfile.add(IIOPFactories.makeCodeSetsComponent(orb)); + iiopProfile.add(IIOPFactories.makeMaxStreamFormatVersionComponent()); + RequestPartitioningPolicy rpPolicy = + (RequestPartitioningPolicy) policies.get_effective_policy( + ORBConstants.REQUEST_PARTITIONING_POLICY); + + if (rpPolicy != null) { + iiopProfile.add( + IIOPFactories.makeRequestPartitioningComponent(rpPolicy.getValue())); + } + + LoadBalancingPolicy lbPolicy = (LoadBalancingPolicy) + policies.get_effective_policy( + ORBConstants.LOAD_BALANCING_POLICY); + if (lbPolicy != null) { + iiopProfile.add( + IIOPFactories.makeLoadBalancingComponent( + lbPolicy.getValue())); + } + + if (codebase != null && !codebase.equals("")) { + iiopProfile.add( + IIOPFactories.makeJavaCodebaseComponent(codebase)); + } + if (orb.getORBData().isJavaSerializationEnabled()) { + iiopProfile.add( + IIOPFactories.makeJavaSerializationComponent()); + } + } + return iiopProfile; + } + + @Override + public String toString() { + return toStringName() + "[" + port + " " + type + " " + shouldUseSelectThreadToWait() + " " + shouldUseWorkerThreadForEvent() + "]"; + } + + protected String toStringName() { + return "SocketOrChannelAcceptorImpl"; + } + + public String getHost() { + return hostname; + } + + public String getHostName() { + return hostname; + } + + public int getLocatorPort() { + return locatorPort; + } + + public void setLocatorPort(int port) { + locatorPort = port; + } + + public InboundConnectionCache getConnectionCache() { + return connectionCache; + } + + public String getConnectionCacheType() { + return TransportManager.SOCKET_OR_CHANNEL_CONNECTION_CACHE; + } + + public long getEnqueueTime() { + return enqueueTime; + } + + public String getMonitoringName() { + return "AcceptedConnections"; + } + + public synchronized boolean initialized() { + return initialized; + } + + public void setConnectionCache(InboundConnectionCache connectionCache) { + this.connectionCache = connectionCache; + } + + public void setEnqueueTime(long timeInMillis) { + enqueueTime = timeInMillis; + } + + public EventHandler getEventHandler() { + return this; + } + + public Acceptor getAcceptor() { + return this; + } + + public Connection getConnection() { + throw new RuntimeException("Should not happen."); + } + + public CDROutputObject createOutputObject(ORB broker, MessageMediator messageMediator) { + return OutputStreamFactory.newCDROutputObject(broker, messageMediator, + messageMediator.getReplyHeader(), messageMediator.getStreamFormatVersion()); + } + + public boolean shouldRegisterAcceptEvent() { + return true; + } + + public int getInterestOps() { + return SelectionKey.OP_ACCEPT; + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorImpl.java new file mode 100644 index 000000000..ee56e52ad --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorImpl.java @@ -0,0 +1,261 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.channels.SelectableChannel; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.security.AccessController; +import java.security.PrivilegedAction; + + +import com.sun.corba.ee.spi.transport.Selector; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Transport public class AcceptorImpl extends AcceptorBase { + protected ServerSocketChannel serverSocketChannel; + protected ServerSocket serverSocket; + + private Class lastExceptionClassSeen = null ; + + public AcceptorImpl(ORB orb, int port, + String name, String type) + { + super( orb, port, name, type ) ; + } + + @Transport + public synchronized boolean initialize() { + if (initialized) { + return false; + } + InetSocketAddress inetSocketAddress = null; + String host = "all interfaces"; + try { + if (orb.getORBData().getListenOnAllInterfaces()) { + inetSocketAddress = new InetSocketAddress(port); + } else { + host = orb.getORBData().getORBServerHost(); + inetSocketAddress = new InetSocketAddress(host, port); + } + serverSocket = orb.getORBData().getSocketFactory() + .createServerSocket(type, inetSocketAddress); + internalInitialize(); + if (orb.getORBData().showInfoMessages()) { + wrapper.infoCreateListenerSucceeded(host, Integer.toString(port)); + } + } catch (Throwable t) { + throw wrapper.createListenerFailed(t, host, port); + } + initialized = true; + return true; + } + + protected void internalInitialize() + throws Exception + { + // Determine the listening port (for the IOR). + // This is important when using emphemeral ports (i.e., + // when the port value to the constructor is 0). + + port = serverSocket.getLocalPort(); + + // Register with transport (also sets up monitoring). + + orb.getCorbaTransportManager().getInboundConnectionCache(this); + + // Finish configuation. + + serverSocketChannel = serverSocket.getChannel(); + + if (serverSocketChannel != null) { + setUseSelectThreadToWait( + orb.getORBData().acceptorSocketUseSelectThreadToWait()); + serverSocketChannel.configureBlocking( + ! orb.getORBData().acceptorSocketUseSelectThreadToWait()); + } else { + // Configure to use listener and reader threads. + setUseSelectThreadToWait(false); + } + setUseWorkerThreadForEvent( + orb.getORBData().acceptorSocketUseWorkerThreadForEvent()); + + } + + @InfoMethod + private void usingServerSocket( ServerSocket ss ) { } + + @InfoMethod + private void usingServerSocketChannel( ServerSocketChannel ssc ) { } + + @Transport + public Socket getAcceptedSocket() { + SocketChannel socketChannel = null; + Socket socket = null; + + try { + if (serverSocketChannel == null) { + socket = serverSocket.accept(); + usingServerSocket( serverSocket ) ; + } else { + socketChannel = serverSocketChannel.accept(); + socket = socketChannel.socket(); + usingServerSocketChannel(serverSocketChannel); + } + + orb.getORBData().getSocketFactory() + .setAcceptedSocketOptions(this, serverSocket, socket); + + // Clear the last exception after a successful accept, in case + // we get sporadic bursts of related failures. + lastExceptionClassSeen = null ; + } catch (IOException e) { + // Log the exception at WARNING level, unless the same exception + // occurs repeatedly. In that case, only log the first exception + // as a warning. Log all exceptions with the same class after the + // first of that class at FINE level. We want to avoid flooding the + // log when the same error occurs repeatedly (e.g. we are using an + // SSLSocketChannel and there is a certificate problem that causes + // ALL accepts to fail). + if (e.getClass() == lastExceptionClassSeen) { + wrapper.ioexceptionInAcceptFine(e); + } else { + lastExceptionClassSeen = e.getClass() ; + wrapper.ioexceptionInAccept(e); + } + + orb.getTransportManager().getSelector(0).unregisterForEvent(this); + // REVISIT - need to close - recreate - then register new one. + orb.getTransportManager().getSelector(0).registerForEvent(this); + // NOTE: if register cycling we do not want to shut down ORB + // since local beans will still work. Instead one will see + // a growing log file to alert admin of problem. + } + + return socket ; + } + + @InfoMethod + private void closeException( IOException exc ) { } + + @Transport + public void close () { + try { + Selector selector = orb.getTransportManager().getSelector(0); + selector.unregisterForEvent(this); + if (serverSocketChannel != null) { + serverSocketChannel.close(); + } + if (serverSocket != null) { + serverSocket.close(); + } + } catch (IOException e) { + closeException(e); + } finally { + } + } + + // EventHandler methods + // + + public SelectableChannel getChannel() { + return serverSocketChannel; + } + + //////////////////////////////////////////////////// + // + // Work methods. + // + + protected void accept() { + processSocket( getAcceptedSocket() ) ; + } + + @Transport + public void doWork() { + try { + if (selectionKey.isAcceptable()) { + AccessController.doPrivileged( + new PrivilegedAction() { + public java.lang.Object run() { + accept() ; + return null; + } + } + ); + } else { + selectionKeyNotAcceptable() ; + } + } catch (SecurityException se) { + securityException( se ) ; + String permissionStr = ORBUtility.getClassSecurityInfo(getClass()); + wrapper.securityExceptionInAccept(se, permissionStr); + } catch (Exception ex) { + otherException( ex ) ; + wrapper.exceptionInAccept(ex, ex.toString() ); + } catch (Throwable t) { + otherException( t ) ; + } finally { + + // IMPORTANT: To avoid bug (4953599), we force the + // Thread that does the NIO select to also do the + // enable/disable of Ops using SelectionKey.interestOps(). + // Otherwise, the SelectionKey.interestOps() may block + // indefinitely. + // NOTE: If "acceptorSocketUseWorkerThreadForEvent" is + // set to to false in ParserTable.java, then this method, + // doWork(), will get executed by the same thread + // (SelectorThread) that does the NIO select. + // If "acceptorSocketUseWorkerThreadForEvent" is set + // to true, a WorkerThread will execute this method, + // doWork(). Hence, the registering of the enabling of + // the SelectionKey's interestOps is done here instead + // of calling SelectionKey.interestOps(). + + Selector selector = orb.getTransportManager().getSelector(0); + selector.registerInterestOps(this); + } + } + + //////////////////////////////////////////////////// + // + // SocketOrChannelAcceptor + // + + public ServerSocket getServerSocket() + { + return serverSocket; + } + + @InfoMethod + private void selectionKeyNotAcceptable() { } + + @InfoMethod + private void securityException(SecurityException se) { } + + @InfoMethod + private void otherException(Throwable t) { } + // END Legacy support +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorLazyImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorLazyImpl.java new file mode 100644 index 000000000..3ea134184 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/AcceptorLazyImpl.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.trace.Transport; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.channels.SelectableChannel; + +/** A version of an Acceptor that does not own the ServerSocket. + * Instead, SelectableChannels obtained from the ServerSocket are + * given to the processSocket method + * + * @author ken + */ +@Transport +public class AcceptorLazyImpl extends AcceptorBase { + + public AcceptorLazyImpl( ORB orb, int port, String name, String type ) { + super( orb, port, name, type ) ; + } + + @Override + public boolean isLazy() { + return true ; + } + + public Socket getAcceptedSocket() { + throw wrapper.notSupportedOnLazyAcceptor() ; + } + + public SelectableChannel getChannel() { + throw wrapper.notSupportedOnLazyAcceptor() ; + } + + @Transport + public synchronized boolean initialize() { + if (initialized) { + return false; + } + + orb.getCorbaTransportManager().getInboundConnectionCache(this); + + initialized = true ; + + return true ; + } + + public void close() { + // NO-OP in this case + } + + public ServerSocket getServerSocket() { + throw wrapper.notSupportedOnLazyAcceptor() ; + } + + public void doWork() { + throw wrapper.notSupportedOnLazyAcceptor() ; + } + + @Override + public boolean shouldRegisterAcceptEvent() { + return false; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ByteBufferPoolImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ByteBufferPoolImpl.java new file mode 100644 index 000000000..d311d1f39 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ByteBufferPoolImpl.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.nio.ByteBuffer; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ByteBufferPool; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * @author Charlie Hunt + */ +public class ByteBufferPoolImpl implements ByteBufferPool { + final private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private ByteBuffer byteBufferSlab; + final private boolean useDirectBuffers; + final private int byteBufferSlabSize; + final private ORB orb; + + public ByteBufferPoolImpl(ORB orb) { + this.orb = orb; + this.useDirectBuffers = !this.orb.getORBData().disableDirectByteBufferUse(); + // If using DirectByteBuffers, setup a pool of DirectByteBuffers. + // Otherwise, we'll just allocate buffers as we need them with no + // pooling. + if (this.useDirectBuffers) { + this.byteBufferSlabSize = orb.getORBData().getPooledDirectByteBufferSlabSize(); + this.byteBufferSlab = allocateDirectByteBufferSlab(); + } else { + // these have no meaning when not using direct buffers + this.byteBufferSlabSize = -1; + this.byteBufferSlab = null; + } + } + + /** Return a ByteBuffer of the requested size. */ + public ByteBuffer getByteBuffer(int size) { + if (useDirectBuffers) { + if (size > byteBufferSlabSize) { + // return a HeapByteBuffer instead of allocating + // a DirectByteBuffer greater the byteBufferSlabSize. + return ByteBuffer.allocate(size); + } + synchronized (this) { + if (byteBufferSlab == null || + (byteBufferSlab.capacity() - byteBufferSlab.limit() < size)) { + byteBufferSlab = allocateDirectByteBufferSlab(); + } + + byteBufferSlab.limit(byteBufferSlab.position() + size); + ByteBuffer view = byteBufferSlab.slice(); + byteBufferSlab.position(byteBufferSlab.limit()); + + return view; + } + } else { + return ByteBuffer.allocate(size); + } + } + + + public void releaseByteBuffer(ByteBuffer buffer) { + // nothing to do here other than help the garbage collector + // Remove this, as it is not useful, and gets flagged by findbugs. + // This method is important if we are using direct ByteBuffers. + // buffer = null; + } + + + // REVISIT - Active ByteBuffers are currently not tracked. + /** + * Get a count of the outstanding allocated DirectByteBuffers. + * (Those allocated and have not been returned to the pool). + */ + public int activeCount() { + return 0; + } + + /** + * Return a new ByteBuffer of at least minimumSize + * and copy any bytes in the oldByteBuffer starting at + * oldByteBuffer.position() up to oldByteBuffer.limit() + * into the returned ByteBuffer. + */ + public ByteBuffer reAllocate(ByteBuffer oldByteBuffer, int minimumSize) { + int size = orb.getORBData().getReadByteBufferSize(); + while (size <= minimumSize) { + size *= 2; + } + + if (size > orb.getORBData().getMaxReadByteBufferSizeThreshold()) { + if (minimumSize > orb.getORBData().getMaxReadByteBufferSizeThreshold()) { + throw wrapper.maximumReadByteBufferSizeExceeded( + orb.getORBData().getMaxReadByteBufferSizeThreshold(), size, + ORBConstants.MAX_READ_BYTE_BUFFER_SIZE_THRESHOLD_PROPERTY); + } else { + // minimumSize is greater than 1/2 of size, and less than or + // equal to max read byte buffer size threshold. So, just + // re-allocate a ByteBuffer of minimumSize. + size = minimumSize; + } + } + + ByteBuffer newByteBuffer = getByteBuffer(size); + + // copy oldByteBuffer into newByteBuffer + newByteBuffer.put(oldByteBuffer); + + return newByteBuffer; + } + + /** + * Allocate a DirectByteBuffer slab. + */ + private ByteBuffer allocateDirectByteBufferSlab() { + return ByteBuffer.allocateDirect(byteBufferSlabSize); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ConnectionCacheBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ConnectionCacheBase.java new file mode 100644 index 000000000..32c48769c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ConnectionCacheBase.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.Collection; +import java.util.Iterator; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ConnectionCache; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.trace.Transport; + +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.NameValue ; + +import org.glassfish.external.statistics.CountStatistic ; +import org.glassfish.external.statistics.impl.CountStatisticImpl ; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + + + //////////////////////////////////////////////////// + // + // spi.transport.ConnectionCache + // +/** + * @author Harold Carr + */ +@Transport +public abstract class ConnectionCacheBase + implements + ConnectionCache +{ + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static final String STAT_UNIT = "count" ; + + private static final String TOTAL_ID_STD = "TotalConnections" ; + private static final String TOTAL_ID = "totalconnections" ; + private static final String IDLE_ID_STD = "ConnectionsIdle" ; + private static final String IDLE_ID = "connectionsidle" ; + private static final String BUSY_ID_STD = "ConnectionsBusy" ; + private static final String BUSY_ID = "connectionsbusy" ; + + private static final String TOTAL_DESC = + "Total number of connections in the connection cache" ; + private static final String IDLE_DESC = + "Number of connections in the connection cache that are idle" ; + private static final String BUSY_DESC = + "Number of connections in the connection cache that are in use" ; + + protected ORB orb; + protected long timestamp = 0; + protected String cacheType; + protected String monitoringName; + + protected ConnectionCacheBase(ORB orb, String cacheType, + String monitoringName) + { + this.orb = orb; + this.cacheType = cacheType; + this.monitoringName = monitoringName; + dprintCreation(); + } + + @NameValue + public String getCacheType() + { + return cacheType; + } + + public synchronized void stampTime(Connection c) + { + // _REVISIT_ Need to worry about wrap around some day + c.setTimeStamp(timestamp++); + } + + private CountStatistic makeCountStat( String name, String desc, + long value ) { + + CountStatisticImpl result = new CountStatisticImpl( name, + STAT_UNIT, desc ) ; + result.setCount( value ) ; + return result ; + } + + public void close() { + synchronized (backingStore()) { + for (Object obj : values()) { + ((Connection)obj).closeConnectionResources() ; + } + } + } + + @ManagedAttribute( id=TOTAL_ID ) + @Description( TOTAL_DESC ) + private CountStatistic numberOfConnectionsAttr() + { + return makeCountStat( TOTAL_ID_STD, TOTAL_DESC, + numberOfConnections() ) ; + } + + public long numberOfConnections() + { + long count = 0 ; + synchronized (backingStore()) { + count = values().size(); + } + + return count ; + } + + @ManagedAttribute( id=IDLE_ID ) + @Description( IDLE_DESC ) + private CountStatistic numberOfIdleConnectionsAttr() + { + return makeCountStat( IDLE_ID_STD, IDLE_DESC, + numberOfIdleConnections() ) ; + } + + public long numberOfIdleConnections() + { + long count = 0; + synchronized (backingStore()) { + Iterator connections = values().iterator(); + while (connections.hasNext()) { + if (! ((Connection)connections.next()).isBusy()) { + count++; + } + } + } + + return count ; + } + + @ManagedAttribute( id=BUSY_ID ) + @Description( BUSY_DESC ) + private CountStatistic numberOfBusyConnectionsAttr() + { + return makeCountStat( BUSY_ID_STD, BUSY_DESC, + numberOfBusyConnections() ) ; + } + + public long numberOfBusyConnections() + { + long count = 0; + synchronized (backingStore()) { + Iterator connections = values().iterator(); + while (connections.hasNext()) { + if (((Connection)connections.next()).isBusy()) { + count++; + } + } + } + + return count ; + } + + + /** + * Discarding least recently used Connections that are not busy + * + * This method must be synchronized since one WorkerThread could + * be reclaming connections inside the synchronized backingStore + * block and a second WorkerThread (or a SelectorThread) could have + * already executed the if (numberOfConnections <= .... ). As a + * result the second thread would also attempt to reclaim connections. + * + * If connection reclamation becomes a performance issue, the connection + * reclamation could make its own task and consequently executed in + * a separate thread. + * Currently, the accept & reclaim are done in the same thread, WorkerThread + * by default. It could be changed such that the SelectorThread would do + * it for SocketChannels and WorkerThreads for Sockets by updating the + * ParserTable. + */ + @Transport + synchronized public boolean reclaim() { + long numberOfConnections = numberOfConnections() ; + + reclaimInfo( numberOfConnections, + orb.getORBData().getHighWaterMark(), + orb.getORBData().getNumberToReclaim() ) ; + + if (numberOfConnections <= orb.getORBData().getHighWaterMark()) { + return false; + } + + Object backingStore = backingStore(); + synchronized (backingStore) { + + // REVISIT - A less expensive alternative connection reclaiming + // algorithm could be investigated. + + for (int i=0; i < orb.getORBData().getNumberToReclaim(); i++) { + Connection toClose = null; + long lru = java.lang.Long.MAX_VALUE; + Iterator iterator = values().iterator(); + + // Find least recently used and not busy connection in cache + while ( iterator.hasNext() ) { + Connection c = (Connection) iterator.next(); + if ( !c.isBusy() && c.getTimeStamp() < lru ) { + toClose = c; + lru = c.getTimeStamp(); + } + } + + if ( toClose == null ) { + return false; + } + + try { + closingInfo( toClose ) ; + toClose.close(); + } catch (Exception ex) { + // REVISIT - log + } + } + + connectionsReclaimedInfo( + numberOfConnections - numberOfConnections() ); + } + + return true; + } + + public String getMonitoringName() + { + return monitoringName; + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + // This is public so folb.Server test can access it. + public abstract Collection values(); + + protected abstract Object backingStore(); + + @InfoMethod + private void creationInfo(String cacheType, String monitoringName) { } + + @Transport + protected void dprintCreation() { + creationInfo( getCacheType(), getMonitoringName() ) ; + } + + @InfoMethod + private void cacheStatsInfo( long numberOfConnections, + long numberOfBusyConnections, long numberOfIdleConnections, + int highWaterMark, int numberToReclaim) { } + + @Transport + protected void cacheStatisticsInfo() { + cacheStatsInfo( numberOfConnections(), numberOfBusyConnections(), + numberOfIdleConnections(), orb.getORBData().getHighWaterMark(), + orb.getORBData().getNumberToReclaim() ) ; + } + + @InfoMethod + private void reclaimInfo(long numberOfConnections, int highWaterMark, + int numberToReclaim) { } + + @InfoMethod + private void closingInfo(Connection toClose) { } + + @InfoMethod + private void connectionsReclaimedInfo(long l) { } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ConnectionImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ConnectionImpl.java new file mode 100644 index 000000000..09ae1b5c9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ConnectionImpl.java @@ -0,0 +1,1564 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.CachedCodeBase; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo; +import com.sun.corba.ee.impl.encoding.OSFCodeSetRegistry; +import com.sun.corba.ee.impl.protocol.MessageMediatorImpl; +import com.sun.corba.ee.impl.protocol.MessageParserImpl; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.MessageParser; +import com.sun.corba.ee.spi.protocol.RequestId; +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; +import com.sun.corba.ee.spi.threadpool.NoSuchWorkQueueException; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.trace.Transport; +import com.sun.corba.ee.spi.transport.*; +import com.sun.org.omg.SendingContext.CodeBase; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.SystemException; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * @author Harold Carr + *

    + * Note: this is the version WITHOUT the purgeCalls changes. + * The changes are in the 1.106 version, which is saved as + * SocketOrChannelConnectionImpl.1.106.sjava. + */ +@Transport +public class ConnectionImpl extends EventHandlerBase implements Connection, Work { + + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self; + + /// + // New transport. + // + + protected SocketChannel socketChannel; + private MessageParser messageParser; + private SocketChannelReader socketChannelReader; + private Throwable discardedThrowable; + + public SocketChannel getSocketChannel() { + return socketChannel; + } + + protected ByteBuffer byteBuffer = null; + protected long enqueueTime; + + // REVISIT: + // protected for test: genericRPCMSGFramework.IIOPConnection constructor. + protected ContactInfo contactInfo; + protected Acceptor acceptor; + protected ConnectionCache connectionCache; + + // + // From iiop.Connection.java + // + + protected Socket socket; // The socket used for this connection. + protected long timeStamp = 0; + protected boolean isServer = false; + + // Start at some value other than zero since this is a magic + // value in some protocols. + protected AtomicInteger requestId = new AtomicInteger(5); + protected ResponseWaitingRoom responseWaitingRoom; + private int state; + protected final java.lang.Object stateEvent = new java.lang.Object(); + protected final java.lang.Object writeEvent = new java.lang.Object(); + protected boolean writeLocked; + protected int serverRequestCount = 0; + + // Server request map: used on the server side of Connection + // Maps request ID to IIOPInputStream. + Map serverRequestMap = null; + + // This is a flag associated per connection telling us if the + // initial set of sending contexts were sent to the receiver + // already... + protected boolean postInitialContexts = false; + + // Remote reference to CodeBase server (supplies + // FullValueDescription, among other things) + protected IOR codeBaseServerIOR; + + // CodeBase cache for this connection. This will cache remote operations, + // handle connecting, and ensure we don't do any remote operations until + // necessary. + protected CachedCodeBase cachedCodeBase = new CachedCodeBase(this); + + + // transport read / write timeout values + protected TcpTimeouts tcpTimeouts; + + // A temporary selector for reading from non-blocking SocketChannels + // when entire message is not read in one read. + protected TemporarySelector tmpReadSelector; + // A lock used for lazily initializing tmpReadSelector + protected final java.lang.Object tmpReadSelectorLock = new java.lang.Object(); + + private NioBufferWriter bufferWriter; + protected Dispatcher dispatcher = DISPATCHER; + + /** + * Returns the throwable, if any, that occurred during the latest {@link #doWork} call. + * Currently used only by unit tests. + */ + Throwable getDiscardedThrowable() { + return discardedThrowable; + } + + /** + * Clears the throwable, if any, that occurred during the latest {@link #doWork} call. + * Currently used only by unit tests. + */ + void clearDiscardedThrowable() { + discardedThrowable = null; + } + + interface Dispatcher { + boolean dispatch(MessageMediator messageMediator); + } + + final static Dispatcher DISPATCHER = new Dispatcher() { + @Override + public boolean dispatch(MessageMediator messageMediator) { + return messageMediator.dispatch(); + } + }; + + + // Mapping of a fragmented messages by request id and its corresponding + // fragmented messages stored in a queue. This mapping is used in the + // optimized read strategy when message fragments arrive for a given + // request id to ensure that message fragments get processed in the order + // in which they arrive. + // This is a ConcurrentHashMap because one Worker Thread can be putting + // new entries into the ConcurrentHashMap after parsing new messages + // via the MessageParser while a different Worker Thread can be removing + // a different entry as a result of a different request id's final + // message fragment having just been processed by a CorbaMessageMediator + // via one of its handleInput methods. + protected ConcurrentHashMap> fragmentMap; + + // Used in genericRPCMSGFramework test. + public ConnectionImpl(ORB orb) { + this.orb = orb; + messageParser = new MessageParserImpl(orb, this); + socketChannelReader = new SocketChannelReader(orb); + setWork(this); + responseWaitingRoom = new ResponseWaitingRoomImpl(orb, this); + setTcpTimeouts(orb.getORBData().getTransportTcpTimeouts()); + } + + // Both client and servers. + protected ConnectionImpl(ORB orb, + boolean useSelectThreadToWait, + boolean useWorkerThread) { + this(orb); + setUseSelectThreadToWait(useSelectThreadToWait); + setUseWorkerThreadForEvent(useWorkerThread); + + if (useSelectThreadToWait) { + // initialize fragmentMap + fragmentMap = new ConcurrentHashMap>(); + } + } + + // Client constructor. + private ConnectionImpl(ORB orb, + ContactInfo contactInfo, + boolean useSelectThreadToWait, + boolean useWorkerThread, + String socketType, + String hostname, + int port) { + this(orb, useSelectThreadToWait, useWorkerThread); + + this.contactInfo = contactInfo; + + try { + defineSocket(useSelectThreadToWait, + orb.getORBData().getSocketFactory().createSocket(socketType, new InetSocketAddress(hostname, port))); + } catch (Throwable t) { + throw wrapper.connectFailure(t, socketType, hostname, + Integer.toString(port)); + } + state = OPENING; + } + + protected final void defineSocket(boolean useSelectThreadToWait, Socket socket) throws IOException { + this.socket = socket; + socketChannel = socket.getChannel(); + + if (socketChannel == null) { + setUseSelectThreadToWait(false); // IMPORTANT: non-channel-backed sockets must use dedicated reader threads. + } else { + socketChannel.configureBlocking(!useSelectThreadToWait); + } + } + + // Client-side convenience. + public ConnectionImpl(ORB orb, + ContactInfo contactInfo, + String socketType, + String hostname, + int port) { + this(orb, contactInfo, + orb.getORBData().connectionSocketUseSelectThreadToWait(), + orb.getORBData().connectionSocketUseWorkerThreadForEvent(), + socketType, hostname, port); + } + + // Server-side constructor. + private ConnectionImpl(ORB orb, Acceptor acceptor, Socket socket, + boolean useSelectThreadToWait, boolean useWorkerThread) { + this(orb, useSelectThreadToWait, useWorkerThread); + + try { + defineSocket(useSelectThreadToWait, socket); + } catch (IOException e) { + RuntimeException rte = new RuntimeException(); + rte.initCause(e); + throw rte; + } + + this.acceptor = acceptor; + serverRequestMap = Collections.synchronizedMap(new HashMap()); + isServer = true; + + state = ESTABLISHED; + } + + // Server-side convenience + public ConnectionImpl(ORB orb, + Acceptor acceptor, + Socket socket) { + this(orb, acceptor, socket, + (socket.getChannel() != null && orb.getORBData().connectionSocketUseSelectThreadToWait()), + (socket.getChannel() != null && orb.getORBData().connectionSocketUseWorkerThreadForEvent())); + } + + //////////////////////////////////////////////////// + // + // framework.transport.Connection + // + + public boolean shouldRegisterReadEvent() { + return true; + } + + public boolean shouldRegisterServerReadEvent() { + return true; + } + + public boolean read() { + MessageMediator messageMediator = readBits(); + + // Null can happen when client closes stream causing purgecalls. + return messageMediator == null || dispatcher.dispatch(messageMediator); + } + + private MessageMediator readBits() { + try { + return createMessageMediator(); + } catch (ThreadDeath td) { + try { + purgeCalls(wrapper.connectionAbort(td), false, false); + } catch (Throwable t) { + exceptionInfo("purgeCalls", t); + } + throw td; + } catch (Throwable ex) { + exceptionInfo("readBits", ex); + + if (ex instanceof SystemException) { + SystemException se = (SystemException) ex; + if (se.minor == ORBUtilSystemException.CONNECTION_REBIND) { + unregisterForEventAndPurgeCalls(se); + throw se; + } else { + try { + if (se instanceof INTERNAL) { + sendMessageError(GIOPVersion.DEFAULT_VERSION); + } + } catch (IOException e) { + exceptionInfo("sendMessageError", e); + } + } + } + unregisterForEventAndPurgeCalls(wrapper.connectionAbort(ex)); + + // REVISIT + //keepRunning = false; + // REVISIT - if this is called after purgeCalls then + // the state of the socket is ABORT so the writeLock + // in close throws an exception. It is ignored but + // causes IBM (screen scraping) tests to fail. + //close(); + throw wrapper.throwableInReadBits(ex); + } + } + + private void unregisterForEventAndPurgeCalls(SystemException ex) { + // REVISIT - make sure reader thread is killed. + orb.getTransportManager().getSelector(0).unregisterForEvent(this); + // Notify anyone waiting. + purgeCalls(ex, true, false); + } + + // NOTE: This method is used only when the ORB is configured with + // "useNIOSelectToWait=false", aka use blocking Sockets/SocketChannels + private MessageMediator createMessageMediator() { + try { + ByteBuffer headerBuffer = read(0, Message.GIOPMessageHeaderLength); + Message header = MessageBase.parseGiopHeader(orb, this, headerBuffer, 0); + + headerBuffer.position(Message.GIOPMessageHeaderLength); + int msgSizeMinusHeader = header.getSize() - Message.GIOPMessageHeaderLength; + ByteBuffer buffer = read(Message.GIOPMessageHeaderLength, msgSizeMinusHeader); + + traceMessageBodyReceived(orb, buffer); + + return new MessageMediatorImpl(orb, this, header, buffer); + } catch (IOException e) { + throw wrapper.ioexceptionWhenReadingConnection(e, this); + } + } + + + private void traceMessageBodyReceived(ORB orb, ByteBuffer buf) { + TransportManager ctm = orb.getTransportManager(); + MessageTraceManagerImpl mtm = (MessageTraceManagerImpl) ctm.getMessageTraceManager(); + if (mtm.isEnabled()) { + mtm.recordBodyReceived(buf); + } + } + + public boolean hasSocketChannel() { + return getSocketChannel() != null; + } + + // NOTE: This method is used only when the ORB is configured with + // "useNIOSelectToWait=false", aka use blocking Sockets/SocketChannels. + // NOTE: This method can throw a connection rebind SystemException. + private ByteBuffer read(int offset, int length) throws IOException { + try { + int size = offset + length; + byte[] buf = new byte[size]; + // getSocket().getInputStream() can throw an IOException + // if the socket is closed. Hence, we check the connection + // state CLOSE_RECVD if an IOException is thrown here + // instead of in readFully() + readFully(getSocket().getInputStream(), buf, offset, length); + return ByteBuffer.wrap(buf); + } catch (IOException ioe) { + if (getState() == CLOSE_RECVD) { + throw wrapper.connectionRebind(ioe); + } else { + throw ioe; + } + } + } + + // NOTE: This method is used only when the ORB is configured with + // "useNIOSelectToWait=false", aka use blocking java.net.Socket + // To support non-channel connections. + + + + // case 1: asked for full header and received it: + // -> ask for full body + // case 2: asked for full header and did not receive it: + // -> read more later + // case 3: asked for full body and received it: + // -> enqueue + // case 4: asked for full body and did not receive it: + // -> read more later + /** + * Reads data from the input stream, adding it the end of the existing buffer. + * At least one byte will always be read. + * @param is the input stream from which to read + * @param buf the buffer into which to read + * @param offset the first position in the buffer into which to read + * @param length + * @throws IOException + */ + private void readFully(java.io.InputStream is, byte[] buf, int offset, int length) + throws IOException { + int n = 0; + int bytecount; + + do { + bytecount = is.read(buf, offset + n, length - n); + + if (bytecount < 0) { + throw new IOException("End-of-stream"); + } else { + n += bytecount; + } + } while (n < length); + } + + // NOTE: This method can throw a connection rebind SystemException. + @Transport + public void write(ByteBuffer byteBuffer) throws IOException { + try { + if (hasSocketChannel()) { + if (getSocketChannel().isBlocking()) { + throw wrapper.temporaryWriteSelectorWithBlockingConnection(this); + } + writeUsingNio(byteBuffer); + } else { + if (!byteBuffer.hasArray()) { + throw wrapper.unexpectedDirectByteBufferWithNonChannelSocket(); + } + + byte[] tmpBuf = new byte[byteBuffer.limit()]; + System.arraycopy(byteBuffer.array(), byteBuffer.arrayOffset(), tmpBuf, 0, tmpBuf.length); + getSocket().getOutputStream().write(tmpBuf, 0, tmpBuf.length); + getSocket().getOutputStream().flush(); + } + + // TimeStamp connection to indicate it has been used + // Note granularity of connection usage is assumed for + // now to be that of a IIOP packet. + getConnectionCache().stampTime(this); + } catch (IOException ioe) { + if (getState() == CLOSE_RECVD) { + throw wrapper.connectionRebind(ioe); + } else { + throw ioe; + } + } + } + + private void writeUsingNio(ByteBuffer byteBuffer) throws IOException { + if (bufferWriter == null) + bufferWriter = new NioBufferWriter(getSocketChannel(), tcpTimeouts); + bufferWriter.write(byteBuffer); + } + + /** + * Note:it is possible for this to be called more than once + */ + @Transport + public synchronized void close() { + writeLock(); + + // REVISIT It will be good to have a read lock on the reader thread + // before we proceed further, to avoid the reader thread (server side) + // from processing requests. This avoids the risk that a new request + // will be accepted by ReaderThread while the ListenerThread is + // attempting to close this connection. + + if (isBusy()) { // we are busy! + writeUnlock(); + doNotCloseBusyConnection(); + return; + } + + try { + try { + sendCloseConnection(GIOPVersion.V1_0); + } catch (Throwable t) { + wrapper.exceptionWhenSendingCloseConnection(t); + } + + synchronized (stateEvent) { + state = CLOSE_SENT; + stateEvent.notifyAll(); + } + + // stop the reader without causing it to do purgeCalls + //Exception ex = new Exception(); + //reader.stop(ex); // REVISIT + + // NOTE: !!!!!! + // This does writeUnlock(). + purgeCalls(wrapper.connectionRebind(), false, true); + + } catch (Exception ex) { + wrapper.exceptionInPurgeCalls(ex); + } + + closeConnectionResources(); + } + + @Transport + public void closeConnectionResources() { + Selector selector = orb.getTransportManager().getSelector(0); + selector.unregisterForEvent(this); + closeSocketAndTemporarySelectors(); + } + + @InfoMethod + private void closingSocketChannel() { + } + + @InfoMethod + private void IOExceptionOnClose(Exception e) { + } + + @Transport + protected void closeSocketAndTemporarySelectors() { + try { + if (socketChannel != null) { + closeTemporarySelectors(); + closingSocketChannel(); + socketChannel.socket().close(); + } + } catch (IOException e) { + IOExceptionOnClose(e); + } finally { + try { + if (socket != null && !socket.isClosed()) { + socket.close(); + } + } catch (Exception e) { + IOExceptionOnClose(e); + } + } + } + + public Acceptor getAcceptor() { + return acceptor; + } + + public ContactInfo getContactInfo() { + return contactInfo; + } + + public EventHandler getEventHandler() { + return this; + } + + // This is used by the GIOPOutputObject in order to + // throw the correct error when handling code sets. + // Can we determine if we are on the server side by + // other means? XREVISIT + public boolean isServer() { + return isServer; + } + + public boolean isClosed() { + boolean result = true; + if (socketChannel != null) { + result = !socketChannel.isOpen(); + } else if (socket != null) { + result = socket.isClosed(); + } + return result; + } + + public boolean isBusy() { + if (serverRequestCount > 0 || + getResponseWaitingRoom().numberRegistered() > 0) { + return true; + } else { + return false; + } + } + + public long getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(long time) { + timeStamp = time; + } + + protected int getState() { + return state; + } + + protected void setState(int state) { + this.state = state; + } + + public void setState(String stateString) { + synchronized (stateEvent) { + if (stateString.equals("ESTABLISHED")) { + state = ESTABLISHED; + stateEvent.notifyAll(); + } else { + // REVISIT: ASSERT + } + } + } + + /** + * Sets the writeLock for this connection. + * If the writeLock is already set by someone else, block till the + * writeLock is released and can set by us. + * IMPORTANT: this connection's lock must be acquired before + * setting the writeLock and must be unlocked after setting the writeLock. + */ + @Transport + public void writeLock() { + // Keep looping till we can set the writeLock. + while (true) { + int localState; + synchronized (stateEvent) { + localState = getState(); + } + + localStateInfo(localState); + + switch (localState) { + + case OPENING: + synchronized (stateEvent) { + if (getState() != OPENING) { + // somebody has changed 'state' so be careful + break; + } + try { + stateEvent.wait(); + } catch (InterruptedException ie) { + wrapper.openingWaitInterrupted(ie); + } + } + // Loop back + break; + + case ESTABLISHED: + synchronized (writeEvent) { + if (!writeLocked) { + writeLocked = true; + return; + } + + try { + // do not stay here too long if state != ESTABLISHED + // Bug 4752117 + while (getState() == ESTABLISHED && writeLocked) { + writeEvent.wait(100); + } + } catch (InterruptedException ie) { + wrapper.establishedWaitInterrupted(ie); + } + } + // Loop back + break; + + case ABORT: + synchronized (stateEvent) { + if (getState() != ABORT) { + break; + } + throw wrapper.writeErrorSend(); + } + + case CLOSE_RECVD: + // the connection has been closed or closing + // ==> throw rebind exception + synchronized (stateEvent) { + if (getState() != CLOSE_RECVD) { + break; + } + throw wrapper.connectionRebind(); + } + + default: + // REVISIT + throw new RuntimeException(".writeLock: bad state"); + } + } + } + + @Transport + public void writeUnlock() { + synchronized (writeEvent) { + writeLocked = false; + writeEvent.notify(); // wake up one guy waiting to write + } + } + + // Assumes the caller handles writeLock and writeUnlock + // NOTE: This method can throw a connection rebind SystemException. + public void sendWithoutLock(CDROutputObject outputObject) { + // Don't we need to check for CloseConnection + // here? REVISIT + + // XREVISIT - Shouldn't the MessageMediator + // be the one to handle writing the data here? + + try { + // Write the fragment/message + CDROutputObject cdrOutputObject = outputObject; + cdrOutputObject.writeTo(this); + + // REVISIT - no flush? + //socket.getOutputStream().flush(); + + } catch (IOException exc) { + // Since IIOPOutputStream's msgheader is set only once, and not + // altered during sending multiple fragments, the original + // msgheader will always have the requestId. + // REVISIT This could be optimized to send a CancelRequest only + // if any fragments had been sent already. + + // IIOPOutputStream will cleanup the connection info when it + // sees this exception. + final SystemException sysexc = (getState() == CLOSE_RECVD) ? + wrapper.connectionRebindMaybe(exc) : + wrapper.writeErrorSend(exc); + + purgeCalls(sysexc, false, true); + + throw sysexc; + } + } + + public void registerWaiter(MessageMediator messageMediator) { + responseWaitingRoom.registerWaiter(messageMediator); + } + + public void unregisterWaiter(MessageMediator messageMediator) { + responseWaitingRoom.unregisterWaiter(messageMediator); + } + + public CDRInputObject waitForResponse(MessageMediator messageMediator) { + return responseWaitingRoom.waitForResponse(messageMediator); + } + + public void setConnectionCache(ConnectionCache connectionCache) { + this.connectionCache = connectionCache; + } + + public ConnectionCache getConnectionCache() { + return connectionCache; + } + + //////////////////////////////////////////////////// + // + // EventHandler methods + // + + @Override + public void setUseSelectThreadToWait(boolean x) { + useSelectThreadToWait = x; + } + + public SelectableChannel getChannel() { + return socketChannel; + } + + public int getInterestOps() { + return SelectionKey.OP_READ; + } + + // public Acceptor getAcceptor() - already defined above. + + public Connection getConnection() { + return this; + } + + //////////////////////////////////////////////////// + // + // Work methods. + // + + public String getName() { + return this.toString(); + } + + @Transport + public void doWork() { + discardedThrowable = null; + try { + // IMPORTANT: Sanity checks on SelectionKeys such as + // SelectorKey.isValid() should not be done + // here. + // + + if (hasSocketChannel()) { + doOptimizedReadStrategy(); + } else { + read(); + } + } catch (Throwable t) { + discardedThrowable = t; + exceptionInfo(t); + } + } + + public void setEnqueueTime(long timeInMillis) { + enqueueTime = timeInMillis; + } + + public long getEnqueueTime() { + return enqueueTime; + } + + //////////////////////////////////////////////////// + // + // spi.transport.CorbaConnection. + // + + public ResponseWaitingRoom getResponseWaitingRoom() { + return responseWaitingRoom; + } + + // REVISIT - inteface defines isServer but already defined in + // higher interface. + + public void serverRequestMapPut(int reqId, MessageMediator messageMediator) { + serverRequestMap.put(reqId, messageMediator); + } + + public MessageMediator serverRequestMapGet(int reqId) { + return serverRequestMap.get(reqId); + } + + public void serverRequestMapRemove(int reqId) { + serverRequestMap.remove(reqId); + } + + public Queue getFragmentList(RequestId corbaRequestId) { + return fragmentMap.get(corbaRequestId); + } + + public void removeFragmentList(RequestId corbaRequestId) { + fragmentMap.remove(corbaRequestId); + } + + // REVISIT: this is also defined in: + // com.sun.corba.ee.spi.legacy.connection.Connection + public java.net.Socket getSocket() { + return socket; + } + + /** + * It is possible for a Close Connection to have been + * * sent here, but we will not check for this. A "lazy" + * * Exception will be thrown in the Worker thread after the + * * incoming request has been processed even though the connection + * * is closed before the request is processed. This is o.k because + * * it is a boundary condition. To prevent it we would have to add + * * more locks which would reduce performance in the normal case. + */ + public synchronized void serverRequestProcessingBegins() { + serverRequestCount++; + } + + public synchronized void serverRequestProcessingEnds() { + serverRequestCount--; + } + + // + // + // + + public int getNextRequestId() { + return requestId.getAndIncrement(); + } + + // Negotiated code sets for char and wchar data + protected CodeSetComponentInfo.CodeSetContext codeSetContext = null; + + public ORB getBroker() { + return orb; + } + + public synchronized CodeSetComponentInfo.CodeSetContext getCodeSetContext() { + return codeSetContext; + } + + public synchronized void setCodeSetContext(CodeSetComponentInfo.CodeSetContext csc) { + if (codeSetContext == null) { + + if (OSFCodeSetRegistry.lookupEntry(csc.getCharCodeSet()) == null || + OSFCodeSetRegistry.lookupEntry(csc.getWCharCodeSet()) == null) { + // If the client says it's negotiated a code set that + // isn't a fallback and we never said we support, then + // it has a bug. + throw wrapper.badCodesetsFromClient(); + } + + codeSetContext = csc; + } + } + + // + // from iiop.IIOPConnection.java + // + + // Map request ID to an InputObject. + // This is so the client thread can start unmarshaling + // the reply and remove it from the out_calls map while the + // ReaderThread can still obtain the input stream to give + // new fragments. Only the ReaderThread touches the clientReplyMap, + // so it doesn't incur synchronization overhead. + + public MessageMediator clientRequestMapGet(int requestId) { + return responseWaitingRoom.getMessageMediator(requestId); + } + + protected MessageMediator clientReply_1_1; + + public void clientReply_1_1_Put(MessageMediator x) { + clientReply_1_1 = x; + } + + public MessageMediator clientReply_1_1_Get() { + return clientReply_1_1; + } + + public void clientReply_1_1_Remove() { + clientReply_1_1 = null; + } + + protected MessageMediator serverRequest_1_1; + + public void serverRequest_1_1_Put(MessageMediator x) { + serverRequest_1_1 = x; + } + + public MessageMediator serverRequest_1_1_Get() { + return serverRequest_1_1; + } + + public void serverRequest_1_1_Remove() { + serverRequest_1_1 = null; + } + + protected String getStateString(int state) { + synchronized (stateEvent) { + switch (state) { + case OPENING: + return "OPENING"; + case ESTABLISHED: + return "ESTABLISHED"; + case CLOSE_SENT: + return "CLOSE_SENT"; + case CLOSE_RECVD: + return "CLOSE_RECVD"; + case ABORT: + return "ABORT"; + default: + return "???"; + } + } + } + + public synchronized boolean isPostInitialContexts() { + return postInitialContexts; + } + + // Can never be unset... + public synchronized void setPostInitialContexts() { + postInitialContexts = true; + } + + /** + * Wake up the outstanding requests on the connection, and hand them + * COMM_FAILURE exception with a given minor code. + *

    + * Also, delete connection from connection table and + * stop the reader thread. + *

    + * Note that this should only ever be called by the Reader thread for + * this connection. + * + * @param die Kill the reader thread (this thread) before exiting. + * @param lockHeld true if the calling thread holds the lock on the connection + */ + @Transport + public void purgeCalls(SystemException systemException, boolean die, + boolean lockHeld) { + + int minor_code = systemException.minor; + // If this invocation is a result of ThreadDeath caused + // by a previous execution of this routine, just exit. + synchronized (stateEvent) { + localStateInfo(getState()); + if ((getState() == ABORT) || (getState() == CLOSE_RECVD)) { + return; + } + } + + // Grab the writeLock (freeze the calls) + try { + if (!lockHeld) { + writeLock(); + } + } catch (SystemException ex) { + exceptionInfo(ex); + } + + // Mark the state of the connection + // and determine the request status + synchronized (stateEvent) { + if (minor_code == ORBUtilSystemException.CONNECTION_REBIND) { + state = CLOSE_RECVD; + systemException.completed = CompletionStatus.COMPLETED_NO; + } else { + state = ABORT; + systemException.completed = CompletionStatus.COMPLETED_MAYBE; + } + stateEvent.notifyAll(); + } + + closeSocketAndTemporarySelectors(); + + // Notify waiters (server-side processing only) + + if (serverRequest_1_1 != null) { // GIOP 1.1 + serverRequest_1_1.cancelRequest(); + } + + if (serverRequestMap != null) { // GIOP 1.2 + for (MessageMediator mm : serverRequestMap.values()) { + mm.cancelRequest(); + } + } + + // Signal all threads with outstanding requests on this + // connection and give them the SystemException; + + responseWaitingRoom.signalExceptionToAllWaiters(systemException); + + if (contactInfo != null) { + ((OutboundConnectionCache) connectionCache).remove(contactInfo); + } else if (acceptor != null) { + ((InboundConnectionCache) connectionCache).remove(this); + } + + // + // REVISIT: Stop the reader thread + // + + // Signal all the waiters of the writeLock. + // There are 4 types of writeLock waiters: + // 1. Send waiters: + // 2. SendReply waiters: + // 3. cleanUp waiters: + // 4. purge_call waiters: + // + + writeUnlock(); + } + + /** + * ********************************************************************** + * The following methods are for dealing with Connection cleaning for + * better scalability of servers in high network load conditions. + * ************************************************************************ + */ + + public void sendCloseConnection(GIOPVersion giopVersion) + throws IOException { + Message msg = MessageBase.createCloseConnection(giopVersion); + sendHelper(giopVersion, msg); + } + + public void sendMessageError(GIOPVersion giopVersion) + throws IOException { + Message msg = MessageBase.createMessageError(giopVersion); + sendHelper(giopVersion, msg); + } + + /** + * Send a CancelRequest message. This does not lock the connection, so the + * caller needs to ensure this method is called appropriately. + * + * @throws IOException - could be due to abortive connection closure. + */ + public void sendCancelRequest(GIOPVersion giopVersion, int requestId) + throws IOException { + + Message msg = MessageBase.createCancelRequest(giopVersion, requestId); + sendHelper(giopVersion, msg); + } + + protected void sendHelper(GIOPVersion giopVersion, Message msg) + throws IOException { + // REVISIT: See comments in CDROutputObject constructor. + CDROutputObject outputObject = + new CDROutputObject(orb, null, giopVersion, this, msg, + ORBConstants.STREAM_FORMAT_VERSION_1); + msg.write(outputObject); + + outputObject.writeTo(this); + } + + // NOTE: This method can throw a connection rebind SystemException. + public void sendCancelRequestWithLock(GIOPVersion giopVersion, + int requestId) + throws IOException { + writeLock(); + try { + sendCancelRequest(giopVersion, requestId); + } catch (IOException ioe) { + if (getState() == CLOSE_RECVD) { + throw wrapper.connectionRebind(ioe); + } else { + throw ioe; + } + } finally { + writeUnlock(); + } + } + + // Begin Code Base methods --------------------------------------- + // + // Set this connection's code base IOR. The IOR comes from the + // SendingContext. This is an optional service context, but all + // JavaSoft ORBs send it. + // + // The set and get methods don't need to be synchronized since the + // first possible get would occur during reading a valuetype, and + // that would be after the set. + + // Sets this connection's code base IOR. This is done after + // getting the IOR out of the SendingContext service context. + // Our ORBs always send this, but it's optional in CORBA. + + public final void setCodeBaseIOR(IOR ior) { + codeBaseServerIOR = ior; + } + + public final IOR getCodeBaseIOR() { + return codeBaseServerIOR; + } + + // Get a CodeBase stub to use in unmarshaling. The CachedCodeBase + // won't connect to the remote codebase unless it's necessary. + public final CodeBase getCodeBase() { + return cachedCodeBase; + } + + // End Code Base methods ----------------------------------------- + + // set transport read / write thresholds + protected void setTcpTimeouts(TcpTimeouts tcpTimeouts) { + this.tcpTimeouts = tcpTimeouts; + } + + @Transport + protected void doOptimizedReadStrategy() { + try { + /*/ + int minimumToRead = 0; + ByteBuffer byteBuffer; + do { + byteBuffer = socketChannelReader.read(getSocketChannel(), messageParser.getRemainderBuffer(), minimumToRead); + if (byteBuffer != null) { + byteBuffer.flip(); + byteBuffer = extractAndProcessMessages(byteBuffer); + minimumToRead = messageParser.getSizeNeeded(); + } + } while (byteBuffer != null); + /*/ + // get a new ByteBuffer from ByteBufferPool ? + if (byteBuffer == null || !byteBuffer.hasRemaining()) { + byteBuffer = + orb.getByteBufferPool().getByteBuffer( + orb.getORBData().getReadByteBufferSize()); + } + + // start of a message must begin at byteBuffer's current position + messageParser.setNextMessageStartPosition(byteBuffer.position()); + + int bytesRead = 0; + // When orb.getORBData().nonBlockingReadCheckMessageParser() is + // true, we check both conditions, messageParser.isExpectingMoreData() and + // bytesRead > 0. If bytesRead > 0 is the only condition checked, + // i.e. orb.getORBData().nonBlockingReadCheckMessageParser() is false, + // then an additional read() would be done before exiting the while + // loop. The default is to check both conditions. + do { + bytesRead = nonBlockingRead(); + if (bytesRead > 0) { + parseBytesAndDispatchMessages(); + } + } while ((bytesRead > 0 && messageParser.isExpectingMoreData())); + + // if expecting more data or using 'always enter blocking read' + // strategy (the default), then go to a blocking read using + // a temporary selector. + if (orb.getORBData().alwaysEnterBlockingRead() || messageParser.isExpectingMoreData()) { + blockingRead(); + } + + // Always ensure subsequent calls to this method has + // byteBuffer.position() set to the location where + // the next message should begin + byteBuffer.position(messageParser.getNextMessageStartPosition()); + /**/ + + // Conection is no longer expecting more data. + // Re-enable read event handling on main selector + resumeSelectOnMainSelector(); + + } catch (ThreadDeath td) { + try { + purgeCalls(wrapper.connectionAbort(td), false, false); + } catch (Throwable t) { + exceptionInfo(t); + } + throw td; + } catch (Throwable ex) { + if (ex instanceof SystemException) { + SystemException se = (SystemException) ex; + if (se.minor == ORBUtilSystemException.CONNECTION_REBIND) { + unregisterForEventAndPurgeCalls(se); + throw se; + } else { + try { + if (se instanceof INTERNAL) { + sendMessageError(GIOPVersion.DEFAULT_VERSION); + } + } catch (IOException e) { + exceptionInfo(e); + } + } + } + unregisterForEventAndPurgeCalls(wrapper.connectionAbort(ex)); + + // REVISIT + //keepRunning = false; + // REVISIT - if this is called after purgeCalls then + // the state of the socket is ABORT so the writeLock + // in close throws an exception. It is ignored but + // causes IBM (screen scraping) tests to fail. + //close(); + throw wrapper.throwableInDoOptimizedReadStrategy(ex); + } + } + + public ByteBuffer extractAndProcessMessages(ByteBuffer byteBuffer) { + messageParser.offerBuffer(byteBuffer); + MessageMediator messageMediator = messageParser.getMessageMediator(); + while (messageMediator != null) { + queueUpWork(messageMediator); + byteBuffer = messageParser.getRemainderBuffer(); + messageParser.offerBuffer(byteBuffer); + messageMediator = messageParser.getMessageMediator(); + } + return byteBuffer; + } + + private void parseBytesAndDispatchMessages() { + byteBuffer.limit(byteBuffer.position()) + .position(messageParser.getNextMessageStartPosition()); + do { + MessageMediator messageMediator = null; + Message message = messageParser.parseBytes(byteBuffer, this); + byteBuffer = messageParser.getRemainderBuffer(); + if (message != null) { + messageMediator = new MessageMediatorImpl(orb, this, message, messageParser.getMsgByteBuffer()); + } + + if (messageMediator != null) { + queueUpWork(messageMediator); + } + } while (messageParser.hasMoreBytesToParse()); + if (messageParser.isExpectingMoreData()) { + // End of data in byteBuffer ? + if (byteBuffer.position() == byteBuffer.capacity()) { + byteBuffer = messageParser.getNewBufferAndCopyOld(byteBuffer); + } + } + } + + @Transport + protected void blockingRead() { + // Precondition: byteBuffer's position must be pointing to where next + // bit of data should be read and MessageParser's next + // message start position must be set. + + TcpTimeouts.Waiter waiter = tcpTimeouts.waiter(); + TemporarySelector tmpSelector = null; + SelectionKey sk = null; + try { + getConnectionCache().stampTime(this); + tmpSelector = getTemporaryReadSelector(); + sk = tmpSelector.registerChannel(getSocketChannel(), SelectionKey.OP_READ); + do { + int nsel = tmpSelector.select(waiter.getTimeForSleep()); + if (nsel > 0) { + tmpSelector.removeSelectedKey(sk); + int bytesRead = getSocketChannel().read(byteBuffer); + if (bytesRead > 0) { + parseBytesAndDispatchMessages(); + // reset waiter because we got some data + waiter = tcpTimeouts.waiter(); + } else if (bytesRead < 0) { + Exception exc = new IOException("End-of-stream"); + throw wrapper.blockingReadEndOfStream( + exc, exc.toString(), this.toString()); + } else { // bytesRead == 0, unlikely but possible + waiter.advance(); + } + } else { // select operation timed out + waiter.advance(); + } + } while (!waiter.isExpired() && messageParser.isExpectingMoreData()); + + // If MessageParser is not expecting more data, then we leave this + // blocking read. Otherwise, we have timed out waiting for some + // expected data to arrive. + if (messageParser.isExpectingMoreData()) { + // failed to read data when we were expecting more + // and exceeded time willing to wait for additional data + throw wrapper.blockingReadTimeout( + tcpTimeouts.get_max_time_to_wait(), waiter.timeWaiting()); + } + } catch (IOException ioe) { + throw wrapper.exceptionBlockingReadWithTemporarySelector(ioe, this); + } finally { + if (tmpSelector != null) { + try { + tmpSelector.cancelAndFlushSelector(sk); + } catch (IOException ex) { + wrapper.unexpectedExceptionCancelAndFlushTempSelector(ex); + } + } + } + } + + private void queueUpWork(MessageMediator messageMediator) { + // Special handling of messages which are fragmented + boolean addToWorkerThreadQueue = true; + Message message = messageMediator.getDispatchHeader(); + if (message.supportsFragments()) { + // Is this the first fragment ? + if (message.getType() != Message.GIOPFragment) { + // NOTE: First message fragment will not be GIOPFragment + // type + if (message.moreFragmentsToFollow()) { + // Create an entry in fragmentMap so fragments + // will be processed in order. + RequestId corbaRequestId = messageMediator.getRequestIdFromRawBytes(); + fragmentMap.put(corbaRequestId, new LinkedList()); + addedEntryToFragmentMap(corbaRequestId); + } + } else { + // Not the first fragment. Append to the request id's + // queue in the fragmentMap so fragments will be + // processed in order. + RequestId corbaRequestId = messageMediator.getRequestIdFromRawBytes(); + Queue queue = fragmentMap.get(corbaRequestId); + if (queue != null) { + // REVISIT - In the future, the synchronized(queue), + // wait()/notify() construct should be replaced + // with something like a LinkedBlockingQueue + // from java.util.concurrent using its offer() + // and poll() methods. But, at the time of the + // writing of this code, a LinkedBlockingQueue + // implementation is not performing as well as + // the synchronized(queue), wait(), notify() + // implementation. + synchronized (queue) { + queue.add(messageMediator); + queuedMessageFragment(corbaRequestId); + // Notify anyone who might be waiting on a + // fragment for this request id. + queue.notifyAll(); + } + // Only after the previous fragment is processed + // in CorbaMessageMediatorImpl.handleInput() will + // the fragment Message that's been queued to + // the fragmentMap for a given request id be + // put on a WorkerThreadQueue for processing. + addToWorkerThreadQueue = false; + } else { + // Very, very unlikely. But, be defensive. + wrapper.noFragmentQueueForRequestId(corbaRequestId.toString()); + } + } + } + + if (addToWorkerThreadQueue) { + addMessageMediatorToWorkQueue(messageMediator); + } + } + + @Transport + protected int nonBlockingRead() { + int bytesRead = 0; + SocketChannel sc = getSocketChannel(); + try { + if (sc == null || sc.isBlocking()) { + throw wrapper.nonBlockingReadOnBlockingSocketChannel(this); + } + bytesRead = sc.read(byteBuffer); + if (bytesRead < 0) { + throw new IOException("End-of-stream"); + } + getConnectionCache().stampTime(this); + } catch (IOException ioe) { + if (getState() == CLOSE_RECVD) { + throw wrapper.connectionRebind(ioe); + } else { + throw wrapper.ioexceptionWhenReadingConnection(ioe, this); + } + } + + return bytesRead; + } + + @Transport + private void addMessageMediatorToWorkQueue(final MessageMediator messageMediator) { + // Add messageMediator to work queue + Throwable throwable = null; + int poolToUse = -1; + try { + poolToUse = messageMediator.getThreadPoolToUse(); + orb.getThreadPoolManager().getThreadPool(poolToUse).getWorkQueue(0).addWork((Work)messageMediator); + } catch (NoSuchThreadPoolException e) { + throwable = e; + } catch (NoSuchWorkQueueException e) { + throwable = e; + } + // REVISIT: need to close connection? + if (throwable != null) { + throw wrapper.noSuchThreadpoolOrQueue(throwable, poolToUse); + } + } + + @Transport + private void resumeSelectOnMainSelector() { + // NOTE: VERY IMPORTANT: + // Re-enable read event handling on main Selector after getting to + // the point that proper serialization of fragments is ensured. + // parseBytesAndDispatchMessages() and MessageParserImpl.parseBytes() + // ensures this by tracking fragment messages for a given request id + // for GIOP 1.2 and tracking GIOP 1.1 fragment messages. + + // IMPORTANT: To avoid bug (4953599), we force the Thread that does the + // NIO select to also do the enable/disable of interest ops using + // SelectionKey.interestOps(Ops of Interest). Otherwise, the + // SelectionKey.interestOps(Ops of Interest) may block indefinitely in + // this thread. + orb.getTransportManager().getSelector(0).registerInterestOps(this); + } + + @Transport + protected TemporarySelector getTemporaryReadSelector() throws IOException { + // If one asks for a temporary read selector on a blocking connection, + // it is an error. + if (getSocketChannel() == null || getSocketChannel().isBlocking()) { + throw wrapper.temporaryReadSelectorWithBlockingConnection(this); + } + synchronized (tmpReadSelectorLock) { + if (tmpReadSelector == null) { + tmpReadSelector = new TemporarySelector(getSocketChannel()); + } + } + return tmpReadSelector; + } + + @Transport + protected void closeTemporarySelectors() throws IOException { + synchronized (tmpReadSelectorLock) { + if (tmpReadSelector != null) { + closingReadSelector(tmpReadSelector); + try { + tmpReadSelector.close(); + } catch (IOException ex) { + throw ex; + } + } + } + + if (bufferWriter != null) + bufferWriter.closeTemporaryWriteSelector(); + } + + @Override + public String toString() { + synchronized (stateEvent) { + String str; + if (socketChannel != null) { + str = socketChannel.toString(); + } else if (socket != null) { + str = socket.toString(); + } else { + str = ""; + } + + return "SocketOrChannelConnectionImpl[ " + + str + " " + + getStateString(getState()) + " " + + shouldUseSelectThreadToWait() + " " + + shouldUseWorkerThreadForEvent() + + "]"; + } + } + + @InfoMethod + private void exceptionInfo(Throwable t) { + } + + @InfoMethod + private void exceptionInfo(String string, Throwable t) { + } + + @InfoMethod + private void readFullySleeping(int time) { + } + + @InfoMethod + private void doNotCloseBusyConnection() { + } + + @InfoMethod + private void localStateInfo(int localState) { + } + + @InfoMethod + private void addedEntryToFragmentMap(RequestId corbaRequestId) { + } + + @InfoMethod + private void queuedMessageFragment(RequestId corbaRequestId) { + } + + @InfoMethod + private void closingReadSelector(TemporarySelector tmpReadSelector) { + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoBase.java new file mode 100644 index 000000000..d0abbe29b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoBase.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher; +import com.sun.corba.ee.spi.transport.OutboundConnectionCache; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.impl.protocol.MessageMediatorImpl; +import com.sun.corba.ee.spi.trace.Transport; + +/** + * @author Harold Carr + */ +@Transport +public abstract class ContactInfoBase + implements + ContactInfo +{ + protected ORB orb; + protected ContactInfoList contactInfoList; + // NOTE: This may be different from same named one in CorbaContactInfoList. + protected IOR effectiveTargetIOR; + protected short addressingDisposition; + protected OutboundConnectionCache connectionCache; + + public ORB getBroker() + { + return orb; + } + + public ContactInfoList getContactInfoList() + { + return contactInfoList; + } + + public ClientRequestDispatcher getClientRequestDispatcher() + { + int scid = + getEffectiveProfile().getObjectKeyTemplate().getSubcontractId() ; + RequestDispatcherRegistry scr = orb.getRequestDispatcherRegistry() ; + return scr.getClientRequestDispatcher( scid ) ; + } + + // Note: not all derived classes will use a connection cache. + // These are convenience methods that may not be used. + public void setConnectionCache(OutboundConnectionCache connectionCache) + { + this.connectionCache = connectionCache; + } + + public OutboundConnectionCache getConnectionCache() + { + return connectionCache; + } + + // Called when client making an invocation. + @Transport + public MessageMediator createMessageMediator(ORB broker, + ContactInfo contactInfo, + Connection connection, + String methodName, + boolean isOneWay) + { + // REVISIT: Would like version, ior, requestid, etc., decisions + // to be in client subcontract. Cannot pass these to this + // factory method because it breaks generic abstraction. + // Maybe set methods on mediator called from subcontract + // after creation? + MessageMediator messageMediator = + new MessageMediatorImpl( + (ORB) broker, + (ContactInfo)contactInfo, + connection, + GIOPVersion.chooseRequestVersion( (ORB)broker, + effectiveTargetIOR), + effectiveTargetIOR, + ((Connection)connection).getNextRequestId(), + getAddressingDisposition(), + methodName, + isOneWay); + + return messageMediator; + } + + @Transport + public CDROutputObject createOutputObject(MessageMediator messageMediator) { + + CDROutputObject outputObject = + OutputStreamFactory.newCDROutputObject(orb, messageMediator, + messageMediator.getRequestHeader(), + messageMediator.getStreamFormatVersion()); + + messageMediator.setOutputObject(outputObject); + return outputObject; + } + + //////////////////////////////////////////////////// + // + // spi.transport.CorbaContactInfo + // + + public short getAddressingDisposition() { + return addressingDisposition; + } + + public void setAddressingDisposition(short addressingDisposition) { + this.addressingDisposition = addressingDisposition; + } + + // REVISIT - remove this. + public IOR getTargetIOR() { + return contactInfoList.getTargetIOR(); + } + + public IOR getEffectiveTargetIOR() { + return effectiveTargetIOR ; + } + + public IIOPProfile getEffectiveProfile() { + return effectiveTargetIOR.getProfile(); + } + + //////////////////////////////////////////////////// + // + // java.lang.Object + // + + public String toString() { + return "CorbaContactInfoBase[" + "]"; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoImpl.java new file mode 100644 index 000000000..2d3b00f3c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoImpl.java @@ -0,0 +1,202 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.transport.ContactInfoBase; + +/** + * @author Harold Carr + */ +public class ContactInfoImpl + extends ContactInfoBase + implements SocketInfo +{ + protected boolean isHashCodeCached = false; + protected int cachedHashCode; + + protected String socketType; + protected String hostname; + protected int port; + + // XREVISIT + // See SocketOrChannelAcceptorImpl.createMessageMediator + // See SocketFactoryContactInfoImpl.constructor() + // See SocketOrChannelContactInfoImpl.constructor() + protected ContactInfoImpl() + { + } + + protected ContactInfoImpl( + ORB orb, + ContactInfoList contactInfoList) + { + this.orb = orb; + this.contactInfoList = contactInfoList; + } + + public ContactInfoImpl( + ORB orb, + ContactInfoList contactInfoList, + String socketType, + String hostname, + int port) + { + this(orb, contactInfoList); + this.socketType = socketType; + this.hostname = hostname; + this.port = port; + } + + // XREVISIT + public ContactInfoImpl( + ORB orb, + ContactInfoList contactInfoList, + IOR effectiveTargetIOR, + short addressingDisposition, + String socketType, + String hostname, + int port) + { + this(orb, contactInfoList, socketType, hostname, port); + this.effectiveTargetIOR = effectiveTargetIOR; + this.addressingDisposition = addressingDisposition; + } + + public boolean isConnectionBased() + { + return true; + } + + public boolean shouldCacheConnection() + { + return true; + } + + public String getConnectionCacheType() + { + return TransportManager.SOCKET_OR_CHANNEL_CONNECTION_CACHE; + } + + public Connection createConnection() + { + Connection connection = + new ConnectionImpl(orb, this, + socketType, hostname, port); + return connection; + } + + //////////////////////////////////////////////////// + // + // spi.transport.CorbaContactInfo + // + + public String getMonitoringName() + { + return "SocketConnections"; + } + + public String getType() + { + return socketType; + } + + public String getHost() + { + return hostname; + } + + public int getPort() + { + return port; + } + + //////////////////////////////////////////////////// + // + // java.lang.Object + // + + // NOTE: hashCode should only check type/host/port, otherwise + // RMI-IIOP Failover will break. See IIOPPrimaryToContactInfoImpl.java + // in the app server or in the Corba unit tests. + + @Override + public int hashCode() + { + if (! isHashCodeCached) { + cachedHashCode = socketType.hashCode() ^ hostname.hashCode() ^ port; + isHashCodeCached = true; + } + return cachedHashCode; + } + + // NOTE: equals should only check type/host/port, otherwise + // RMI-IIOP Failover will break. See IIOPPrimaryToContactInfoImpl.java + // in the app server or in the Corba unit tests. + + @Override + public boolean equals(Object obj) + { + if (obj == null) { + return false; + } else if (!(obj instanceof ContactInfoImpl)) { + return false; + } + + ContactInfoImpl other = + (ContactInfoImpl) obj; + + if (port != other.port) { + return false; + } + if (!hostname.equals(other.hostname)) { + return false; + } + if (socketType == null) { + if (other.socketType != null) { + return false; + } + } else if (!socketType.equals(other.socketType)) { + return false; + } + return true; + } + + public String toString() + { + return + "SocketOrChannelContactInfoImpl[" + + socketType + " " + + hostname + " " + + port + + "]"; + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + protected void dprint(String msg) + { + ORBUtility.dprint("SocketOrChannelContactInfoImpl", msg); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoListImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoListImpl.java new file mode 100644 index 000000000..bce082b5a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoListImpl.java @@ -0,0 +1,439 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.LinkedList; +import java.util.concurrent.locks.ReentrantReadWriteLock ; +import java.util.concurrent.locks.ReadWriteLock ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.LoadBalancingComponent ; +import com.sun.corba.ee.spi.ior.TaggedProfile ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory; +import com.sun.corba.ee.spi.transport.ContactInfoList ; +import com.sun.corba.ee.spi.transport.SocketInfo; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.protocol.NotLocalLocalCRDImpl; +import com.sun.corba.ee.spi.trace.IsLocal; +import com.sun.corba.ee.spi.trace.Transport; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import org.glassfish.pfl.basic.func.UnaryPredicate; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Transport +@IsLocal +public class ContactInfoListImpl implements ContactInfoList { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + protected ORB orb; + private ReadWriteLock lcrdLock = new ReentrantReadWriteLock() ; + protected LocalClientRequestDispatcher localClientRequestDispatcher; + protected IOR targetIOR; + protected IOR effectiveTargetIOR; + protected List effectiveTargetIORContactInfoList; + protected ContactInfo primaryContactInfo; + private boolean usePerRequestLoadBalancing = false ; + + private int startCount = 0 ; + + private UnaryPredicate testPred = + new UnaryPredicate() { + public boolean evaluate( ContactInfo arg ) { + return !arg.getType().equals( SocketInfo.IIOP_CLEAR_TEXT ) ; + } + } ; + + private List filter( List arg, UnaryPredicate pred ) { + List result = new ArrayList() ; + for (T elem : arg ) { + if (pred.evaluate( elem )) { + result.add( elem ) ; + } + } + + return result ; + } + + private static ThreadLocal skipRotate = new ThreadLocal() { + @Override + protected Boolean initialValue() { + return false ; + } + } ; + + // This is an ugly hack to avoid rotating the iterator when the + // ClientGroupManager decides to update the iterator, which is only + // supposed to happen when the cluster shape changes. Unfortunately it + // is happening on EVERY REQUEST, at least in the Argela test. + public static void setSkipRotate() { + skipRotate.set( true ) ; + } + + @InfoMethod + private void display( String msg, int value ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + // Move the first startCount elements of the list to the end, so that + // the list starts at the startCount'th element and continues + // through all elements. Each time we rotate, increment + // startCount for load balancing. + @Transport + private synchronized List rotate( List arg ) { + if (skipRotate.get()) { + skipRotate.set( false ) ; + return arg ; + } + + if (usePerRequestLoadBalancing) { + display( "startCount", startCount ) ; + LinkedList tempList = null ; + + // This may be the best way to support PRLB for now. + // The GIS will return types like "iiop-listener-1", but we also get + // IIOP_CLEAR_TEXT for some, for both SSL and non-SSL ports. Invoking + // clear on an SSL port leads to bad failures that are not retryable. + tempList = new LinkedList( filter( arg, testPred ) ) ; + + // Really should just be this: + // tempList = new LinkedList( arg ) ; + + if (startCount >= tempList.size()) { + startCount = 0 ; + } + + for (int ctr=0; ctr iterator() + { + createContactInfoList(); + Iterator result = new ContactInfoListIteratorImpl( + orb, this, primaryContactInfo, + rotate( effectiveTargetIORContactInfoList ), + usePerRequestLoadBalancing ); + + /* This doesn't work due to some strange behavior in FOLB: we are getting far + * too many IOR updates. Updates are received even when the cluster shape has not changed. + */ + /* + if (usePerRequestLoadBalancing) { + // Copy the list, otherwise we will get a ConcurrentModificationException as + // soon as next() is called on the iterator. + List newList = new ArrayList( effectiveTargetIORContactInfoList ) ; + CorbaContactInfo head = newList.remove(0) ; + newList.add( head ) ; + effectiveTargetIORContactInfoList = newList ; + } + */ + + return result ; + } + + //////////////////////////////////////////////////// + // + // spi.transport.CorbaContactInfoList + // + + public synchronized void setTargetIOR(IOR targetIOR) + { + this.targetIOR = targetIOR; + setEffectiveTargetIOR(targetIOR); + } + + public synchronized IOR getTargetIOR() + { + return targetIOR; + } + + private IIOPAddress getPrimaryAddress( IOR ior ) { + if (ior != null) { + for (TaggedProfile tprof : ior) { + TaggedProfileTemplate tpt = tprof.getTaggedProfileTemplate() ; + if (tpt instanceof IIOPProfileTemplate) { + IIOPProfileTemplate ipt = (IIOPProfileTemplate)tpt ; + return ipt.getPrimaryAddress() ; + } + } + } + + return null ; + } + + @InfoMethod + private void changingEffectiveAddress( IIOPAddress oldAddr, IIOPAddress newAddr ) { } + + @Transport + public synchronized void setEffectiveTargetIOR(IOR newIOR) + { + if (targetIOR != null) { + final String oldTypeId = targetIOR.getTypeId() ; + final String newTypeId = newIOR.getTypeId() ; + if (!oldTypeId.isEmpty() && !oldTypeId.equals( newTypeId )) { + // Good place for a breakpoint. This is probably always an + // error, but not necessarily in the ORB. + wrapper.changedTypeIdOnSetEffectiveTargetIOR( oldTypeId, + newTypeId ) ; + // temporary? It looks like this happens due to some error + // in IIOP FOLB. + return ; + } + } + + final IIOPAddress oldAddress = getPrimaryAddress( this.effectiveTargetIOR ) ; + final IIOPAddress newAddress = getPrimaryAddress( newIOR ) ; + if ((oldAddress != null) && !oldAddress.equals( newAddress )) { + changingEffectiveAddress( oldAddress, newAddress ) ; + } + + this.effectiveTargetIOR = newIOR; + + effectiveTargetIORContactInfoList = null; + if (primaryContactInfo != null && + orb.getORBData().getIIOPPrimaryToContactInfo() != null) + { + orb.getORBData().getIIOPPrimaryToContactInfo() + .reset(primaryContactInfo); + } + primaryContactInfo = null; + setLocalSubcontract(); + + // Set the per request load balancing flag. + IIOPProfile prof = newIOR.getProfile() ; + TaggedProfileTemplate temp = prof.getTaggedProfileTemplate() ; + Iterator lbcomps = + temp.iteratorById( ORBConstants.TAG_LOAD_BALANCING_ID ) ; + if (lbcomps.hasNext()) { + LoadBalancingComponent lbcomp = null ; + lbcomp = (LoadBalancingComponent)(lbcomps.next()) ; + usePerRequestLoadBalancing = + lbcomp.getLoadBalancingValue() == ORBConstants.PER_REQUEST_LOAD_BALANCING ; + } + } + + public synchronized IOR getEffectiveTargetIOR() + { + return effectiveTargetIOR; + } + + public synchronized LocalClientRequestDispatcher getLocalClientRequestDispatcher() + { + lcrdLock.readLock().lock() ; + try { + return localClientRequestDispatcher; + } finally { + lcrdLock.readLock().unlock() ; + } + } + + //////////////////////////////////////////////////// + // + // org.omg.CORBA.portable.Delegate + // + + // REVISIT - hashCode(org.omg.CORBA.Object self) + + //////////////////////////////////////////////////// + // + // java.lang.Object + // + + @Override + public synchronized int hashCode() + { + return targetIOR.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ContactInfoListImpl other = (ContactInfoListImpl) obj; + if (this.targetIOR != other.targetIOR && + (this.targetIOR == null || !this.targetIOR.equals(other.targetIOR))) { + return false; + } + return true; + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + @Transport + private void createContactInfoList() { + IIOPProfile iiopProfile = effectiveTargetIOR.getProfile(); + final boolean isLocal = iiopProfile.isLocal() ; + + if (effectiveTargetIORContactInfoList == null) { + effectiveTargetIORContactInfoList = + new ArrayList(); + + String hostname = + ((IIOPProfileTemplate)iiopProfile.getTaggedProfileTemplate()) + .getPrimaryAddress().getHost().toLowerCase(); + int port = + ((IIOPProfileTemplate)iiopProfile.getTaggedProfileTemplate()) + .getPrimaryAddress().getPort(); + // For use by "sticky manager" if one is registered. + primaryContactInfo = + createContactInfo(SocketInfo.IIOP_CLEAR_TEXT, hostname, port); + + if (isLocal) { + // NOTE: IMPORTANT: + // Only do local. The APP Server interceptors check + // effectiveTarget.isLocal - which is determined via + // the IOR - so if we added other addresses then + // transactions and interceptors would not execute. + ContactInfo contactInfo = new SharedCDRContactInfoImpl( + orb, this, effectiveTargetIOR, + orb.getORBData().getGIOPAddressDisposition()); + effectiveTargetIORContactInfoList.add(contactInfo); + } else { + addRemoteContactInfos(effectiveTargetIOR, + effectiveTargetIORContactInfoList); + } + display( "First time for iiopProfile", iiopProfile ) ; + } else { + if (!isLocal) { + display( "Subsequent time for iiopProfile", iiopProfile ) ; + // 6152681 - this is so SSL can change its selection on each + // invocation + addRemoteContactInfos(effectiveTargetIOR, + effectiveTargetIORContactInfoList); + } else { + display( "Subsequent time for (colocated) iiopProfile", + iiopProfile ) ; + } + } + + display( "effective list", effectiveTargetIORContactInfoList ) ; + } + + @Transport + private void addRemoteContactInfos( IOR effectiveTargetIOR, + List effectiveTargetIORContactInfoList) { + + ContactInfo contactInfo; + List socketInfos = orb.getORBData() + .getIORToSocketInfo().getSocketInfo( + effectiveTargetIOR, + // 6152681 + effectiveTargetIORContactInfoList); + + if (socketInfos == effectiveTargetIORContactInfoList) { + display( "socketInfos", socketInfos ) ; + return; + } + + for (SocketInfo socketInfo : socketInfos) { + String type = socketInfo.getType(); + String host = socketInfo.getHost().toLowerCase(); + int port = socketInfo.getPort(); + contactInfo = createContactInfo(type, host, port); + effectiveTargetIORContactInfoList.add(contactInfo); + } + } + + protected ContactInfo createContactInfo(String type, String hostname, + int port) { + + return new ContactInfoImpl( + orb, this, + // XREVISIT - See Base Line 62 + effectiveTargetIOR, + orb.getORBData().getGIOPAddressDisposition(), + type, hostname, port); + } + + /** + * setLocalSubcontract sets cached information that is set whenever + * the effectiveTargetIOR changes. + * + * Note: this must be maintained accurately whether or not the ORB + * allows local optimization, because ServantManagers in the POA + * ALWAYS use local optimization ONLY (they do not have a remote case). + */ + @IsLocal + protected void setLocalSubcontract() { + lcrdLock.writeLock().lock() ; + try { + if (!effectiveTargetIOR.getProfile().isLocal()) { + localClientRequestDispatcher = new NotLocalLocalCRDImpl(); + return; + } + + // Note that we have no plan to support multi-profile IORs. + int scid = effectiveTargetIOR.getProfile().getObjectKeyTemplate(). + getSubcontractId() ; + LocalClientRequestDispatcherFactory lcsf = + orb.getRequestDispatcherRegistry(). + getLocalClientRequestDispatcherFactory( scid ) ; + if (lcsf != null) { + localClientRequestDispatcher = lcsf.create( scid, effectiveTargetIOR ) ; + } + } finally { + lcrdLock.writeLock().unlock() ; + } + } + + // For timing test. + public ContactInfo getPrimaryContactInfo() { + return primaryContactInfo; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoListIteratorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoListIteratorImpl.java new file mode 100644 index 000000000..c486d7940 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ContactInfoListIteratorImpl.java @@ -0,0 +1,350 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.Iterator; +import java.util.List; +import java.util.Set ; +import java.util.HashSet ; + +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TRANSIENT; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.transport.TcpTimeouts; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfoListIterator; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.protocol.InvocationInfo; + +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +// REVISIT: create a unit test for this class. + +@Transport +public class ContactInfoListIteratorImpl + implements + ContactInfoListIterator +{ + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + protected ORB orb; + protected ContactInfoList contactInfoList; + protected RuntimeException failureException; + private boolean usePRLB ; + protected TcpTimeouts tcpTimeouts ; + + // ITERATOR state + protected Iterator effectiveTargetIORIterator; + protected ContactInfo previousContactInfo; + protected boolean isAddrDispositionRetry; + protected boolean retryWithPreviousContactInfo; + protected IIOPPrimaryToContactInfo primaryToContactInfo; + protected ContactInfo primaryContactInfo; + protected List listOfContactInfos; + protected TcpTimeouts.Waiter waiter ; + // Set of endpoints that have failed since the last successful communication + // with the IOR. + protected Set failedEndpoints ; + // End ITERATOR state + + public ContactInfoListIteratorImpl( + ORB orb, + ContactInfoList corbaContactInfoList, + ContactInfo primaryContactInfo, + List listOfContactInfos, + boolean usePerRequestLoadBalancing ) + { + this.orb = orb; + this.tcpTimeouts = orb.getORBData().getTransportTcpConnectTimeouts() ; + this.contactInfoList = corbaContactInfoList; + this.primaryContactInfo = primaryContactInfo; + if (listOfContactInfos != null) { + // listOfContactInfos is null when used by the legacy + // socket factory. In that case this iterator is NOT used. + + this.effectiveTargetIORIterator = listOfContactInfos.iterator() ; + } + // List is immutable so no need to synchronize access. + this.listOfContactInfos = listOfContactInfos; + + this.previousContactInfo = null; + this.isAddrDispositionRetry = false; + this.retryWithPreviousContactInfo = false; + + this.failureException = null; + + this.waiter = tcpTimeouts.waiter() ; + this.failedEndpoints = new HashSet() ; + + this.usePRLB = usePerRequestLoadBalancing ; + + if (usePerRequestLoadBalancing) { + // We certainly DON'T want sticky behavior if we are using PRLB. + primaryToContactInfo = null ; + } else { + primaryToContactInfo = orb.getORBData().getIIOPPrimaryToContactInfo(); + } + } + + @InfoMethod + private void display( String msg ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + @InfoMethod + private void display( String msg, long value ) { } + + //////////////////////////////////////////////////// + // + // java.util.Iterator + // + + @Transport + public boolean hasNext() { + boolean result = false; + if (retryWithPreviousContactInfo) { + display("backoff before retry previous"); + + if (waiter.isExpired()) { + display("time to wait for connection exceeded " , + tcpTimeouts.get_max_time_to_wait()); + + // NOTE: Need to indicate the timeout. + // And it needs to break the loop in the delegate. + failureException = wrapper.communicationsRetryTimeout( + failureException, tcpTimeouts.get_max_time_to_wait()); + return false; + } + + waiter.sleepTime() ; + waiter.advance() ; + return true; + } + + if (isAddrDispositionRetry) { + return true; + } + + if (primaryToContactInfo != null) { + result = primaryToContactInfo.hasNext( primaryContactInfo, + previousContactInfo, listOfContactInfos); + } else { + result = effectiveTargetIORIterator.hasNext(); + } + + if (!result && !waiter.isExpired()) { + display("Reached end of ContactInfoList list. Starting at beginning"); + + previousContactInfo = null; + if (primaryToContactInfo != null) { + primaryToContactInfo.reset(primaryContactInfo); + } else { + // Argela: + effectiveTargetIORIterator = listOfContactInfos.iterator() ; + } + + result = hasNext(); + return result; + } + + return result; + } + + @Transport + public ContactInfo next() { + if (retryWithPreviousContactInfo) { + retryWithPreviousContactInfo = false; + return previousContactInfo; + } + + if (isAddrDispositionRetry) { + isAddrDispositionRetry = false; + return previousContactInfo; + } + + // We hold onto the last in case we get an addressing + // disposition retry. Then we use it again. + + // We also hold onto it for the sticky manager. + + if (primaryToContactInfo != null) { + previousContactInfo = (ContactInfo) + primaryToContactInfo.next(primaryContactInfo, + previousContactInfo, + listOfContactInfos); + } else { + previousContactInfo = effectiveTargetIORIterator.next(); + } + + // We must use waiter here regardless of whether or not + // there is a IIOPPrimaryToContactInfo or not. + // Failure to do this resulted in bug 6568174. + if (failedEndpoints.contains(previousContactInfo)) { + failedEndpoints.clear() ; + waiter.sleepTime() ; + waiter.advance() ; + } + + return previousContactInfo; + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + + public ContactInfoList getContactInfoList() + { + return contactInfoList; + } + + @Transport + public void reportSuccess(ContactInfo contactInfo) + { + display( "contactInfo", contactInfo) ; + failedEndpoints.clear() ; + waiter.reset() ; // not strictly necessary + } + + @Transport + public boolean reportException(ContactInfo contactInfo, + RuntimeException ex) { + boolean result = false; + display( "contactInfo", contactInfo) ; + + failedEndpoints.add( contactInfo ) ; + this.failureException = ex; + if (ex instanceof COMM_FAILURE) { + SystemException se = (SystemException) ex; + if (se.minor == ORBUtilSystemException.CONNECTION_REBIND) { + display( "COMM_FAILURE(connection rebind): " + + "retry with previous contact info", ex ) ; + + retryWithPreviousContactInfo = true; + result = true; + return result; + } else { + if (se.completed == CompletionStatus.COMPLETED_NO) { + if (hasNext()) { + display( "COMM_FAILURE(COMPLETED_NO, hasNext true): " + + "retry with next contact info", ex ) ; + result = true; + return result; + } + if (contactInfoList.getEffectiveTargetIOR() != + contactInfoList.getTargetIOR()) { + display( "COMM_FAILURE(COMPLETED_NO, hasNext false, " + + "effective != target): " + + "retry with target", ex ) ; + + // retry from root ior + updateEffectiveTargetIOR(contactInfoList.getTargetIOR()); + result = true; + return result; + } + } + } + } else if (ex instanceof TRANSIENT) { + display( "TRANSIENT: retry with previous contact info", ex ) ; + retryWithPreviousContactInfo = true; + result = true; + return result; + } + result = false; + waiter.reset() ; // not strictly necessary. + return result; + } + + public RuntimeException getFailureException() + { + if (failureException == null) { + return wrapper.invalidContactInfoListIteratorFailureException() ; + } else { + return failureException; + } + } + + //////////////////////////////////////////////////// + // + // spi.CorbaContactInfoListIterator + // + + @Transport + public void reportAddrDispositionRetry(ContactInfo contactInfo, + short disposition) + { + previousContactInfo.setAddressingDisposition(disposition); + isAddrDispositionRetry = true; + waiter.reset() ; // necessary + } + + @Transport + public void reportRedirect(ContactInfo contactInfo, + IOR forwardedIOR) + { + updateEffectiveTargetIOR(forwardedIOR); + waiter.reset() ; // Necessary + } + + //////////////////////////////////////////////////// + // + // Implementation. + // + + // + // REVISIT: + // + // The normal operation for a standard iterator is to throw + // ConcurrentModificationException whenever the underlying collection + // changes. This is implemented by keeping a modification counter (the + // timestamp may fail because the granularity is too coarse). + // Essentially what you need to do is whenever the iterator fails this + // way, go back to ContactInfoList and get a new iterator. + // + // Need to update CorbaClientRequestDispatchImpl to catch and use + // that exception. + // + + public void updateEffectiveTargetIOR(IOR newIOR) + { + contactInfoList.setEffectiveTargetIOR(newIOR); + // If we report the exception in _request (i.e., beginRequest + // we cannot throw RemarshalException to the stub because _request + // does not declare that exception. + // To keep the two-level dispatching (first level chooses ContactInfo, + // second level is specific to that ContactInfo/EPT) we need to + // ensure that the request dispatchers get their iterator from the + // InvocationStack (i.e., ThreadLocal). That way if the list iterator + // needs a complete update it happens right here. + + // Ugly hack for Argela: avoid rotating the iterator in this case, + // or we rotate the iterator twice on every request. + // + // Remove this hack once we figure out why we get all of the + // membership changes when the cluster shape does not change. + ContactInfoListImpl.setSkipRotate() ; + + ((InvocationInfo)orb.getInvocationInfo()) + .setContactInfoListIterator(contactInfoList.iterator()); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/DefaultIORToSocketInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/DefaultIORToSocketInfoImpl.java new file mode 100644 index 000000000..4c3138bd0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/DefaultIORToSocketInfoImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS ; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import com.sun.corba.ee.spi.transport.SocketInfo; + +public class DefaultIORToSocketInfoImpl + implements IORToSocketInfo +{ + public List getSocketInfo(IOR ior, + List previous) { + + // 6152681 + if (! previous.isEmpty()) { + return previous; + } + + SocketInfo socketInfo; + List result = new ArrayList(); + + IIOPProfileTemplate iiopProfileTemplate = (IIOPProfileTemplate) + ior.getProfile().getTaggedProfileTemplate() ; + IIOPAddress primary = iiopProfileTemplate.getPrimaryAddress() ; + String hostname = primary.getHost().toLowerCase(); + int port = 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 = createSocketInfo(hostname, port); + result.add(socketInfo); + + Iterator iterator = iiopProfileTemplate.iteratorById( + TAG_ALTERNATE_IIOP_ADDRESS.value); + + while (iterator.hasNext()) { + AlternateIIOPAddressComponent alternate = + (AlternateIIOPAddressComponent) iterator.next(); + hostname = alternate.getAddress().getHost().toLowerCase(); + port = alternate.getAddress().getPort(); + socketInfo= createSocketInfo(hostname, port); + result.add(socketInfo); + } + return result; + } + + 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; }}; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/DefaultSocketFactoryImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/DefaultSocketFactoryImpl.java new file mode 100644 index 000000000..53b1f687a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/DefaultSocketFactoryImpl.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.net.ServerSocket; +import java.nio.channels.SocketChannel; +import java.nio.channels.ServerSocketChannel; + +import com.sun.corba.ee.spi.transport.Acceptor; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ORBSocketFactory; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class DefaultSocketFactoryImpl + implements ORBSocketFactory +{ + private ORB orb; + + 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 = ORBUtility.openSocketChannel(inetSocketAddress); + socket = socketChannel.socket(); + } else { + socket = new Socket(inetSocketAddress.getHostName(), + inetSocketAddress.getPort()); + } + + // Disable Nagle's algorithm (i.e., always send immediately). + socket.setTcpNoDelay(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); + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/EventHandlerBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/EventHandlerBase.java new file mode 100644 index 000000000..7da00763f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/EventHandlerBase.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import java.nio.channels.SelectionKey; + +import com.sun.corba.ee.spi.transport.EventHandler; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; +import com.sun.corba.ee.spi.threadpool.NoSuchWorkQueueException; +import com.sun.corba.ee.spi.threadpool.Work; + +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Transport +public abstract class EventHandlerBase + implements + EventHandler +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + protected ORB orb; + protected Work work; + protected boolean useWorkerThreadForEvent; + protected boolean useSelectThreadToWait; + protected SelectionKey selectionKey; + + //////////////////////////////////////////////////// + // + // EventHandler methods + // + + public void setUseSelectThreadToWait(boolean x) + { + useSelectThreadToWait = x; + } + + public boolean shouldUseSelectThreadToWait() + { + return useSelectThreadToWait; + } + + public void setSelectionKey(SelectionKey selectionKey) + { + this.selectionKey = selectionKey; + } + + public SelectionKey getSelectionKey() + { + return selectionKey; + } + + @InfoMethod + private void display( String msg ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + /* + * NOTE: + * This is not thread-safe by design. + * Only one thread should call it - a reader/listener/select thread. + * Not stateless: interest ops, registration. + */ + @Transport + public void handleEvent() + { + getSelectionKey().interestOps(getSelectionKey().interestOps() & + (~ getInterestOps())); + if (shouldUseWorkerThreadForEvent()) { + Throwable throwable = null; + try { + display( "add work to pool 0") ; + orb.getThreadPoolManager().getThreadPool(0) + .getWorkQueue(0).addWork(getWork()); + } catch (NoSuchThreadPoolException e) { + throwable = e; + } catch (NoSuchWorkQueueException e) { + throwable = e; + } + // REVISIT: need to close connection. + if (throwable != null) { + display( "unexpected exception", throwable ) ; + throw wrapper.noSuchThreadpoolOrQueue(throwable, 0); + } + } else { + display( "doWork" ) ; + getWork().doWork(); + } + } + + public boolean shouldUseWorkerThreadForEvent() + { + return useWorkerThreadForEvent; + } + + public void setUseWorkerThreadForEvent(boolean x) + { + useWorkerThreadForEvent = x; + } + + public void setWork(Work work) + { + this.work = work; + } + + public Work getWork() + { + return work; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/InboundConnectionCacheImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/InboundConnectionCacheImpl.java new file mode 100644 index 000000000..aef69900e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/InboundConnectionCacheImpl.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.ArrayList; +import java.util.Collection; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.InboundConnectionCache; + +import com.sun.corba.ee.spi.trace.Transport; + +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.AMXMetadata ; +import org.glassfish.gmbal.Description ; + +/** + * @author Harold Carr + */ +@Transport +@ManagedObject +@Description( "Cache of connections accepted by the ORB" ) +@AMXMetadata( type="corba-inbound-connection-cache-mon", group="monitoring" ) +public class InboundConnectionCacheImpl + extends + ConnectionCacheBase + implements + InboundConnectionCache +{ + protected Collection connectionCache; + private InboundConnectionCacheProbeProvider pp = + new InboundConnectionCacheProbeProvider() ; + + public InboundConnectionCacheImpl(ORB orb, Acceptor acceptor) + { + super(orb, acceptor.getConnectionCacheType(), + ((Acceptor)acceptor).getMonitoringName()); + this.connectionCache = new ArrayList(); + } + + public Connection get(Acceptor acceptor) + { + throw wrapper.methodShouldNotBeCalled(); + } + + @Transport + public void put(Acceptor acceptor, Connection connection) + { + synchronized (backingStore()) { + connectionCache.add(connection); + connection.setConnectionCache(this); + cacheStatisticsInfo(); + pp.connectionOpenedEvent( acceptor.toString(), connection.toString() ) ; + } + } + + @Transport + public void remove(Connection connection) + { + synchronized (backingStore()) { + connectionCache.remove(connection); + cacheStatisticsInfo(); + pp.connectionClosedEvent( connection.toString() ) ; + } + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + public Collection values() + { + return connectionCache; + } + + protected Object backingStore() + { + return connectionCache; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/InboundConnectionCacheProbeProvider.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/InboundConnectionCacheProbeProvider.java new file mode 100644 index 000000000..dd0763e6b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/InboundConnectionCacheProbeProvider.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import org.glassfish.external.probe.provider.annotations.Probe ; +import org.glassfish.external.probe.provider.annotations.ProbeProvider ; +import org.glassfish.external.probe.provider.annotations.ProbeParam ; + +/** This simple class is for the GFv3 probe mechanism. As of + * 9/16/09, gfprobes have the unfortunate requirement that ALL + * methods in the class MUST be probe methods (see issue 9536). + * Otherwise I would put these methods in the CorbaInboundConnectionCacheImpl class. + * + * @author Ken Cavanaugh + */ +@ProbeProvider(moduleProviderName="glassfish", moduleName="orb" , probeProviderName="inboundconnection") +public class InboundConnectionCacheProbeProvider { + @Probe(name="inboundConnectionOpened" ) + public void connectionOpenedEvent( + @ProbeParam( "acceptor" ) String acceptor, + @ProbeParam( "connection" ) String connection ) {} + + @Probe(name="inboundConnectionClosed" ) + public void connectionClosedEvent( + @ProbeParam( "connection" ) String connection ) {} +} + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ListenerThreadImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ListenerThreadImpl.java new file mode 100644 index 000000000..e1876d2ed --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ListenerThreadImpl.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + + +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.ListenerThread; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.threadpool.Work; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Transport +public class ListenerThreadImpl + implements + ListenerThread, + Work +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private ORB orb; + private Acceptor acceptor; + private boolean keepRunning; + private long enqueueTime; + + public ListenerThreadImpl(ORB orb, Acceptor acceptor) + { + this.orb = orb; + this.acceptor = acceptor; + keepRunning = true; + } + + //////////////////////////////////////////////////// + // + // ListenerThread methods. + // + + public Acceptor getAcceptor() + { + return acceptor; + } + + @Transport + public synchronized void close() + { + keepRunning = false; + acceptor.close() ; + } + + private synchronized boolean isRunning() { + return keepRunning ; + } + + //////////////////////////////////////////////////// + // + // Work methods. + // + + // REVISIT - this needs alot more from previous ListenerThread + @InfoMethod + private void display( String msg ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + @Transport + public void doWork() + { + while (isRunning()) { + display( "acceptor", acceptor ) ; + try { + display( "Before Accept cycle" ) ; + acceptor.processSocket( acceptor.getAcceptedSocket() ) ; + display( "After Accept cycle" ) ; + } catch (Throwable t) { + wrapper.exceptionInListenerThread( t ) ; + display( "Exception in accept", t ) ; + + orb.getTransportManager().getSelector(0) + .unregisterForEvent(getAcceptor().getEventHandler()); + + try { + if (isRunning()) { + getAcceptor().close(); + } + } catch (Exception exc) { + wrapper.ioExceptionOnClose( exc ) ; + } + } + } + } + + public void setEnqueueTime(long timeInMillis) + { + enqueueTime = timeInMillis; + } + + public long getEnqueueTime() + { + return enqueueTime; + } + + public String getName() { return "ListenerThread"; } + + //////////////////////////////////////////////////// + // + // Implementation. + // +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/MessageTraceManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/MessageTraceManagerImpl.java new file mode 100644 index 000000000..d98dd4753 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/MessageTraceManagerImpl.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.nio.ByteBuffer ; + +import java.util.List ; +import java.util.ArrayList ; + +import com.sun.corba.ee.spi.transport.MessageTraceManager ; + +public class MessageTraceManagerImpl implements MessageTraceManager +{ + // Note: this implementation does not need to be syncronized + // because an instance of this class is only called from a single + // thread. + private List /* */ dataSent ; + private List /* */ dataReceived ; + private boolean enabled ; + private boolean RHRCalled ; // Set to true whenever recordHeaderReceived is called. + private byte[] header ; + + public MessageTraceManagerImpl() + { + init() ; + enabled = false ; + } + + public void clear() + { + init() ; + } + + private void init() + { + dataSent = new ArrayList() ; + dataReceived = new ArrayList() ; + initHeaderRecorder() ; + } + + public boolean isEnabled() + { + return enabled ; + } + + public void enable( boolean flag ) + { + enabled = flag ; + } + + public byte[][] getDataSent() + { + return (byte[][])dataSent.toArray( + new byte[dataSent.size()][] ) ; + } + + public byte[][] getDataReceived() + { + return (byte[][])dataReceived.toArray( + new byte[dataReceived.size()][] ) ; + } + + // Methods that are used internally to record messages + + private void initHeaderRecorder() + { + RHRCalled = false ; + header = null ; + } + + /** Return the contents of the byte buffer. The ByteBuffer + * is not modified. The result is written starting at + * index offset in the byte[]. + */ + public byte[] getBytes( ByteBuffer bb, int offset ) + { + ByteBuffer view = bb.asReadOnlyBuffer() ; + view.flip() ; + int len = view.remaining() ; + byte[] buffer = new byte[ len + offset ] ; + view.get( buffer, offset, len ) ; + + return buffer ; + } + + @Override + public void recordDataSent(ByteBuffer message) + { + byte[] buffer = getBytes( message, 0 ) ; + dataSent.add( buffer ) ; + } + + public void recordHeaderReceived( ByteBuffer message ) + { + if (RHRCalled) { + // Previous call was for header only: no body + dataReceived.add( header ) ; + initHeaderRecorder() ; + } + + RHRCalled = true ; + header = getBytes( message, 0 ) ; + } + + public void recordBodyReceived( ByteBuffer message ) + { + if (!RHRCalled) + // This string is 12 characters long, so the ASCII + // representation should have the same length as a + // GIOP header. + header = "NO HEADER!!!".getBytes() ; + + byte[] buffer = getBytes( message, header.length ) ; + System.arraycopy( header, 0, buffer, header.length, + message.remaining() ) ; + dataReceived.add( buffer ) ; + + initHeaderRecorder() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/NioBufferWriter.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/NioBufferWriter.java new file mode 100644 index 000000000..c68ef6492 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/NioBufferWriter.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.transport.TcpTimeouts; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; + +public class NioBufferWriter { + protected TemporarySelector tmpWriteSelector; + protected final java.lang.Object tmpWriteSelectorLock = new java.lang.Object(); + + private SocketChannel socketChannel; + private TcpTimeouts tcpTimeouts; + + public NioBufferWriter(SocketChannel socketChannel, TcpTimeouts tcpTimeouts) { + this.socketChannel = socketChannel; + this.tcpTimeouts = tcpTimeouts; + } + + void write(ByteBuffer byteBuffer) throws IOException { + int nbytes = socketChannel.write(byteBuffer); + if (byteBuffer.hasRemaining()) { + // Can only occur on non-blocking connections. + // Using long for backoff_factor to avoid floating point + // calculations. + TcpTimeouts.Waiter waiter = tcpTimeouts.waiter() ; + SelectionKey sk = null; + TemporarySelector tmpSelector = null; + try { + tmpSelector = getTemporaryWriteSelector(socketChannel); + sk = tmpSelector.registerChannel(socketChannel, + SelectionKey.OP_WRITE); + while (byteBuffer.hasRemaining() && !waiter.isExpired()) { + int nsel = tmpSelector.select(waiter.getTimeForSleep()); + if (nsel > 0) { + tmpSelector.removeSelectedKey(sk); + do { + // keep writing while bytes can be written + nbytes = socketChannel.write(byteBuffer); + } while (nbytes > 0 && byteBuffer.hasRemaining()); + } + // selector timed out or no bytes have been written + if (nsel == 0 || nbytes == 0) { + waiter.advance() ; + } + } + } catch (IOException ioe) { + ioe.printStackTrace(); + throw ConnectionImpl.wrapper.exceptionWhenWritingWithTemporarySelector(ioe, + byteBuffer.position(), byteBuffer.limit(), + waiter.timeWaiting(), tcpTimeouts.get_max_time_to_wait()); + } finally { + if (tmpSelector != null) { + tmpSelector.cancelAndFlushSelector(sk); + } + } + // if message not fully written, throw exception + if (byteBuffer.hasRemaining() && waiter.isExpired()) { + // failed to write entire message + throw ConnectionImpl.wrapper.transportWriteTimeoutExceeded( + tcpTimeouts.get_max_time_to_wait(), waiter.timeWaiting()); + } + } + } + + void closeTemporaryWriteSelector() throws IOException { + synchronized (tmpWriteSelectorLock) { + if (tmpWriteSelector != null) { + try { + tmpWriteSelector.close(); + } catch (IOException ex) { + throw ex; + } + } + } + } + + TemporarySelector getTemporaryWriteSelector(SocketChannel socketChannel1) throws IOException { + synchronized (tmpWriteSelectorLock) { + if (tmpWriteSelector == null) { + tmpWriteSelector = new TemporarySelector(socketChannel1); + } + } + return tmpWriteSelector; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/OutboundConnectionCacheImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/OutboundConnectionCacheImpl.java new file mode 100644 index 000000000..cb7343aae --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/OutboundConnectionCacheImpl.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.spi.trace.Transport; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.OutboundConnectionCache; + +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.AMXMetadata ; +import org.glassfish.gmbal.Description ; + +/** + * @author Harold Carr + */ +@Transport +@ManagedObject +@Description( "Cache of connections originated by the ORB" ) +@AMXMetadata( type="corba-outbound-connection-cache-mon", group="monitoring" ) +public class OutboundConnectionCacheImpl + extends + ConnectionCacheBase + implements + OutboundConnectionCache +{ + protected Map connectionCache; + private OutboundConnectionCacheProbeProvider pp = + new OutboundConnectionCacheProbeProvider() ; + + public OutboundConnectionCacheImpl(ORB orb, ContactInfo contactInfo) + { + super(orb, contactInfo.getConnectionCacheType(), + ((ContactInfo)contactInfo).getMonitoringName()); + this.connectionCache = new HashMap(); + } + + @Transport + public Connection get(ContactInfo contactInfo) + { + synchronized (backingStore()) { + cacheStatisticsInfo(); + return connectionCache.get(contactInfo); + } + } + + @Transport + public void put(ContactInfo contactInfo, Connection connection) + { + synchronized (backingStore()) { + connectionCache.put(contactInfo, connection); + connection.setConnectionCache(this); + pp.connectionOpenedEvent( contactInfo.toString(), connection.toString() ) ; + cacheStatisticsInfo(); + } + } + + @Transport + public void remove(ContactInfo contactInfo) + { + synchronized (backingStore()) { + if (contactInfo != null) { + Connection connection = connectionCache.remove(contactInfo); + pp.connectionClosedEvent( contactInfo.toString(), connection.toString() ) ; + } + cacheStatisticsInfo(); + } + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + public Collection values() + { + return connectionCache.values(); + } + + protected Object backingStore() + { + return connectionCache; + } + + @Override + public String toString() + { + return "CorbaOutboundConnectionCacheImpl[" + + connectionCache + + "]"; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/OutboundConnectionCacheProbeProvider.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/OutboundConnectionCacheProbeProvider.java new file mode 100644 index 000000000..c0f38710d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/OutboundConnectionCacheProbeProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.glassfish.external.probe.provider.annotations.Probe ; +import org.glassfish.external.probe.provider.annotations.ProbeProvider ; +import org.glassfish.external.probe.provider.annotations.ProbeParam ; + +/** This simple class is for the GFv3 probe mechanism. As of + * 9/16/09, gfprobes have the unfortunate requirement that ALL + * methods in the class MUST be probe methods (see issue 9536). + * Otherwise I would put these methods in the CorbaOutboundConnectionCacheImpl class. + * + * @author Ken Cavanaugh + */ +@ProbeProvider(moduleProviderName="glassfish", moduleName="orb" , probeProviderName="outboundconnection") +public class OutboundConnectionCacheProbeProvider { + @Probe(name="outboundConnectionOpened" ) + public void connectionOpenedEvent( + @ProbeParam( "contactInfo" ) String contactInfo, + @ProbeParam( "connection" ) String connection ) {} + + @Probe(name="outboundConnectionClosed" ) + public void connectionClosedEvent( + @ProbeParam( "contactInfo" ) String contactInfo, + @ProbeParam( "connection" ) String connection ) {} +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ReaderThreadImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ReaderThreadImpl.java new file mode 100644 index 000000000..07d99b89f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ReaderThreadImpl.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ReaderThread; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.threadpool.Work; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Transport +public class ReaderThreadImpl implements ReaderThread, Work { + private ORB orb; + private Connection connection; + private boolean keepRunning; + private long enqueueTime; + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public ReaderThreadImpl(ORB orb, Connection connection) + { + this.orb = orb; + this.connection = connection; + keepRunning = true; + } + + //////////////////////////////////////////////////// + // + // ReaderThread methods. + // + + public Connection getConnection() { + return connection; + } + + @Transport + public synchronized void close() { + keepRunning = false; + + // Note: do not close the connection here, as it may be + // re-used if we are simply closing the ReaderThread + // because it has completed its operation. + // If we are calling close because of transport shutdown, + // the connection will be closed when the connection caches are closed. + } + + private synchronized boolean isRunning() { + return keepRunning ; + } + + //////////////////////////////////////////////////// + // + // Work methods. + // + + @InfoMethod + private void display( String msg ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + + // REVISIT - this needs alot more from previous ReaderThread. + @Transport + public void doWork() + { + while (isRunning()) { + try { + display( "Start readerThread cycle", connection ) ; + + if (connection.read()) { + // REVISIT - put in pool; + return; + } + + display( "End readerThread cycle" ) ; + } catch (Throwable t) { + wrapper.exceptionInReaderThread( t ) ; + display( "Exception in read", t ) ; + + orb.getTransportManager().getSelector(0) + .unregisterForEvent(getConnection().getEventHandler()); + + try { + if (isRunning()) { + getConnection().close(); + } + } catch (Exception exc) { + wrapper.ioExceptionOnClose( exc ) ; + } + } + } + } + + public void setEnqueueTime(long timeInMillis) { + enqueueTime = timeInMillis; + } + + public long getEnqueueTime() { + return enqueueTime; + } + + public String getName() { return "ReaderThread"; } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ResponseWaitingRoomImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ResponseWaitingRoomImpl.java new file mode 100644 index 000000000..4d06c959a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/ResponseWaitingRoomImpl.java @@ -0,0 +1,294 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; + + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ResponseWaitingRoom; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.LocateReplyOrReplyMessage; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Transport +public class ResponseWaitingRoomImpl + implements + ResponseWaitingRoom +{ + final private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + final static class OutCallDesc + { + MessageMediator messageMediator; + SystemException exception; + CDRInputObject inputObject; + ReentrantLock lock = new ReentrantLock(); + Condition condition = lock.newCondition(); + } + + // Maps requestId to an OutCallDesc. + final private Map out_calls; + final private ORB orb; + final private Connection connection; + + + public ResponseWaitingRoomImpl(ORB orb, Connection connection) + { + this.orb = orb; + this.connection = connection; + this.out_calls = + Collections.synchronizedMap(new HashMap()); + } + + @Transport + public void registerWaiter(MessageMediator messageMediator) + { + display( "messageMediator request ID", + messageMediator.getRequestId() ) ; + display( "messageMediator operation name", + messageMediator.getOperationName() ) ; + + Integer requestId = messageMediator.getRequestId(); + + OutCallDesc call = new OutCallDesc(); + call.messageMediator = messageMediator; + OutCallDesc exists = out_calls.put(requestId, call); + if (exists != null) { + wrapper.duplicateRequestIdsInResponseWaitingRoom( + ORBUtility.operationNameAndRequestId( + (MessageMediator)exists.messageMediator), + ORBUtility.operationNameAndRequestId(messageMediator)); + } + } + + @Transport + public void unregisterWaiter(MessageMediator mediator) + { + MessageMediator messageMediator = mediator; + display( "messageMediator request ID", + messageMediator.getRequestId() ) ; + display( "messageMediator operation name", + messageMediator.getOperationName() ) ; + + Integer requestId = messageMediator.getRequestId(); + + out_calls.remove(requestId); + } + + @Transport + public CDRInputObject waitForResponse(MessageMediator messageMediator) { + CDRInputObject returnStream = null; + + display( "messageMediator request ID", + messageMediator.getRequestId() ) ; + display( "messageMediator operation name", + messageMediator.getOperationName() ) ; + + Integer requestId = messageMediator.getRequestId(); + + if (messageMediator.isOneWay()) { + // The waiter is removed in releaseReply in the same + // way as a normal request. + display( "Oneway request: not waiting") ; + return null; + } + + OutCallDesc call = out_calls.get(requestId); + if (call == null) { + throw wrapper.nullOutCall() ; + } + + // Value from ORBData is in milliseconds, will convert it nanoseconds + // to use it with Condition.awaitNanos() + long waitForResponseTimeout = + orb.getORBData().getWaitForResponseTimeout() * 1000 * 1000; + + try { + call.lock.lock(); + while (call.inputObject == null && call.exception == null) { + // Wait for the reply from the server. + // The ReaderThread reads in the reply IIOP message + // and signals us. + try { + display( "Waiting for response..." ) ; + + waitForResponseTimeout = + call.condition.awaitNanos(waitForResponseTimeout); + if (call.inputObject == null && call.exception == null) { + if (waitForResponseTimeout > 0) { + // it's a "spurious wait wakeup", need to + // continue to wait for a response + display( "Spurious wakeup, continuing to wait for ", + waitForResponseTimeout/1000000 ); + } else { + // timed out waiting for data + call.exception = + wrapper.communicationsTimeoutWaitingForResponse( + orb.getORBData().getWaitForResponseTimeout()); + // REVISIT: + // Normally the inputObject or exception is + // created from the response stream. + // Need to fake encoding version since + // it is expected to be popped in endRequest. + ORBUtility.pushEncVersionToThreadLocalState( + ORBConstants.JAVA_ENC_VERSION); + } + } + } catch (InterruptedException ie) {}; + } + if (call.exception != null) { + display( "Exception from call", call.exception ) ; + throw call.exception; + } + + returnStream = call.inputObject; + } finally { + call.lock.unlock(); + } + + // REVISIT -- exceptions from unmarshaling code will + // go up through this client thread! + + if (returnStream != null) { + // On fragmented streams the header MUST be unmarshaled here + // (in the client thread) in case it blocks. + // If the header was already unmarshaled, this won't + // do anything + // REVISIT: cast - need interface method. + ((CDRInputObject)returnStream).unmarshalHeader(); + } + + return returnStream; + } + + @InfoMethod + private void display( String msg ) { } + + @InfoMethod + private void display( String msg, int value ) { } + + @InfoMethod + private void display( String msg, Object value ) { } + + @Transport + public void responseReceived(CDRInputObject is) + { + CDRInputObject inputObject = (CDRInputObject) is; + LocateReplyOrReplyMessage header = (LocateReplyOrReplyMessage) + inputObject.getMessageHeader(); + display( "requestId", header.getRequestId()) ; + display( "header", header ) ; + + OutCallDesc call = out_calls.get(header.getRequestId()); + + // This is an interesting case. It could mean that someone sent us a + // reply message, but we don't know what request it was for. That + // would probably call for an error. However, there's another case + // that's normal and we should think about -- + // + // If the unmarshaling thread does all of its work inbetween the time + // the ReaderThread gives it the last fragment and gets to the + // out_calls.get line, then it will also be null, so just return; + if (call == null) { + display( "No waiter" ) ; + return; + } + + // Set the reply InputObject and signal the client thread + // that the reply has been received. + // The thread signalled will remove outcall descriptor if appropriate. + // Otherwise, it'll be removed when last fragment for it has been put on + // BufferManagerRead's queue. + + try { + call.lock.lock(); + MessageMediator messageMediator = + (MessageMediator)call.messageMediator; + + display( "Notifying waiters") ; + display( "messageMediator request ID", + messageMediator.getRequestId() ) ; + display( "messageMediator operation name", + messageMediator.getOperationName() ) ; + + messageMediator.setReplyHeader(header); + messageMediator.setInputObject(is); + inputObject.setMessageMediator(messageMediator); + call.inputObject = is; + call.condition.signal(); + } finally { + call.lock.unlock(); + } + } + + public int numberRegistered() + { + return out_calls.size(); + } + + ////////////////////////////////////////////////// + // + // CorbaResponseWaitingRoom + // + + @Transport + public void signalExceptionToAllWaiters(SystemException systemException) { + OutCallDesc call; + synchronized (out_calls) { + Iterator itr = out_calls.values().iterator(); + while (itr.hasNext()) { + call = itr.next(); + try { + call.lock.lock(); + ((MessageMediator)call.messageMediator).cancelRequest(); + call.inputObject = null; + call.exception = systemException; + call.condition.signal(); + } finally { + call.lock.unlock(); + } + } + } + } + + public MessageMediator getMessageMediator(int requestId) + { + OutCallDesc call = out_calls.get(requestId); + if (call == null) { + // This can happen when getting early reply fragments for a + // request which has completed (e.g., client marshaling error). + return null; + } + return call.messageMediator; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SelectorImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SelectorImpl.java new file mode 100644 index 000000000..8ded6d54f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SelectorImpl.java @@ -0,0 +1,543 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; +import java.nio.channels.CancelledKeyException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.EventHandler; +import com.sun.corba.ee.spi.transport.ListenerThread; +import com.sun.corba.ee.spi.transport.ReaderThread; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; +import com.sun.corba.ee.spi.threadpool.NoSuchWorkQueueException; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.trace.Transport; + +import java.util.Map; +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +@Transport +@ManagedObject +@Description( "The Selector, which handles incoming requests to the ORB" ) +public class SelectorImpl + extends + Thread + implements + com.sun.corba.ee.spi.transport.Selector +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private ORB orb; + private Timer timer; + private Selector selector; + private long timeout; + private final List deferredRegistrations; + private final List interestOpsList; + private final Map listenerThreads; + private final Map readerThreads; + private boolean selectorStarted; + private volatile boolean closed; + private Map lastActivityTimers = new HashMap(); + + interface Timer { + long getCurrentTime(); + } + + private static final Timer SYSTEM_TIMER = new Timer() { + public long getCurrentTime() { + return System.currentTimeMillis(); + } + }; + + public SelectorImpl(ORB orb) { + this(orb, SYSTEM_TIMER); + } + + SelectorImpl(ORB orb, Timer timer) { + this.orb = orb; + this.timer = timer; + selector = null; + selectorStarted = false; + timeout = 60000; + deferredRegistrations = new ArrayList(); + interestOpsList = new ArrayList(); + listenerThreads = new HashMap(); + readerThreads = new HashMap(); + closed = false; + } + + public void setTimeout(long timeout) + { + this.timeout = timeout; + } + + @ManagedAttribute + @Description( "The selector timeout" ) + public long getTimeout() + { + return timeout; + } + + @InfoMethod + private void display( String msg, Object value ) { } + + @InfoMethod + private void closedEventHandler() { } + + @InfoMethod + private void defaultCaseForEventHandler() { } + + @Transport + public void registerInterestOps(EventHandler eventHandler) { + SelectionKey selectionKey = eventHandler.getSelectionKey(); + if (selectionKey.isValid()) { + int ehOps = eventHandler.getInterestOps(); + SelectionKeyAndOp keyAndOp = new SelectionKeyAndOp(selectionKey, ehOps); + synchronized(interestOpsList) { + interestOpsList.add(keyAndOp); + } + // tell Selector Thread there's an update to a SelectorKey's Ops + selector.wakeup(); + } + else { + wrapper.selectionKeyInvalid(eventHandler.toString()); + display( "EventHandler SelectionKey not valid", eventHandler); + } + } + + @Transport + public void registerForEvent(EventHandler eventHandler) + { + if (isClosed()) { + closedEventHandler(); + return; + } + + if (eventHandler.shouldUseSelectThreadToWait()) { + synchronized (deferredRegistrations) { + deferredRegistrations.add(eventHandler); + } + startSelector(); + selector.wakeup(); + return; + } + + switch (eventHandler.getInterestOps()) { + case SelectionKey.OP_ACCEPT : + createListenerThread(eventHandler); + break; + case SelectionKey.OP_READ : + createReaderThread(eventHandler); + break; + default: + defaultCaseForEventHandler(); + throw new RuntimeException( + "SelectorImpl.registerForEvent: unknown interest ops"); + } + } + + @Transport + public void unregisterForEvent(EventHandler eventHandler) { + if (isClosed()) { + closedEventHandler(); + return; + } + + if (eventHandler.shouldUseSelectThreadToWait()) { + SelectionKey selectionKey = eventHandler.getSelectionKey(); + if (selectionKey != null) { + selectionKey.cancel(); + selector.wakeup(); + } + + return; + } + + switch (eventHandler.getInterestOps()) { + case SelectionKey.OP_ACCEPT : + destroyListenerThread(eventHandler); + break; + case SelectionKey.OP_READ : + destroyReaderThread(eventHandler); + break; + default: + defaultCaseForEventHandler(); + throw new RuntimeException( + "SelectorImpl.uregisterForEvent: unknown interest ops"); + } + } + + @Transport + public void close() { + if (isClosed()) { + closedEventHandler() ; + return; + } + + setClosed(true); + + // Kill listeners. + synchronized (this) { + for (ListenerThread lthread : listenerThreads.values()) { + lthread.close() ; + } + } + + // Kill readers. + synchronized (this) { + for (ReaderThread rthread : readerThreads.values()) { + rthread.close() ; + } + } + + // Selector + try { + if (selector != null) { + // wakeup Selector thread to process close request + selector.wakeup(); + } + } catch (Throwable t) { + display( "Exception in close", t ) ; + } + } + + /////////////////////////////////////////////////// + // + // Thread methods. + // + + @InfoMethod + private void beginSelect() { } + + @InfoMethod + private void endSelect() { } + + @InfoMethod + private void selectorClosed() { } + + @InfoMethod + private void selectResult( boolean hasNext, int count ) { } + + @InfoMethod + private void skippingEventForCancelledKey() { } + + @Transport + @Override + public void run() { + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Object run() { + setName("SelectorThread"); + return null; + } + }); + + while (!closed) { + try { + runSelectionLoopOnce(); + } catch (Throwable t) { + // IMPORTANT: ignore all errors so the select thread keeps running. + // Otherwise a guaranteed hang. + display( "Ignoring exception", t ) ; + } + } + } + + void runSelectionLoopOnce() throws IOException { + beginSelect(); + + int n = 0; + handleDeferredRegistrations(); + enableInterestOps(); + try { + n = selector.select(timeout); + } catch (IOException e) { + display( "Exception in select:", e ) ; + } + if (closed) { + selector.close(); + selectorClosed(); + return; + } + Iterator iterator = + selector.selectedKeys().iterator(); + selectResult(iterator.hasNext(), n); + while (iterator.hasNext()) { + SelectionKey selectionKey = iterator.next(); + iterator.remove(); + + // It is possible that a different thread (other than the + // thread that is executing this code has cancelled the + // SelectionKey as a result of it inititiating a Connection + // close and cleanup of its temporary Selectors. Hence, + // the check for a valid SelectionKey. + // IMPORTANT: Further assuming the thread that has cancelled + // the SelectionKey is releasing other Connection resources + // such as cleaning any temporary Selectors which may be + // been active in addition to closing the Connection. + + if (selectionKey.isValid()) { + EventHandler eventHandler = (EventHandler)selectionKey.attachment(); + try { + eventHandler.handleEvent(); + if (lastActivityTimers.containsKey(eventHandler)) + lastActivityTimers.put(eventHandler, timer.getCurrentTime()); + } catch (Throwable t) { + wrapper.exceptionInSelector( t, eventHandler ) ; + } + } else { + wrapper.canceledSelectionKey( selectionKey ) ; + skippingEventForCancelledKey(); + // skipping event since this EventHandler's + // SelectionKey has been found to be cancelled. + // It will be removed from this Selector on the + // next select() operation. + } + } + long currentTime = timer.getCurrentTime(); + for (EventHandler handler : lastActivityTimers.keySet()) { + long elapsedTime = currentTime - lastActivityTimers.get(handler); + ((Timeoutable) handler).checkForTimeout(elapsedTime); + } + endSelect(); + } + + + ///////////////////////////////////////////////////// + // + // Implementation. + // + + private synchronized boolean isClosed () + { + return closed; + } + + private synchronized void setClosed(boolean closed) + { + this.closed = closed; + } + + @InfoMethod + private void selectorStarted() {} + + @Transport + private synchronized void startSelector() { + // Make sure this is only called once, or setDaemon will + // throw an IllegalStateException since the Selector will already + // be running. Note this must be synchronized to protect against + // concurrent startups of the Selector. + if (!selectorStarted) { + selectorStarted() ; + try { + selector = Selector.open(); + } catch (IOException e) { + throw new RuntimeException( ".startSelector: Selector.open exception", e); + } + setDaemon(true); + start(); + selectorStarted = true; + } + } + + @InfoMethod + private void registeringEventHandler( EventHandler eh ) { } + + @Transport + private void handleDeferredRegistrations() { + synchronized (deferredRegistrations) { + for (EventHandler eventHandler : deferredRegistrations ) { + registeringEventHandler(eventHandler); + SelectableChannel channel = eventHandler.getChannel(); + SelectionKey selectionKey = null; + try { + selectionKey = channel.register(selector, eventHandler.getInterestOps(), eventHandler); + } catch (ClosedChannelException e) { + display( "Exception", e ) ; + } + eventHandler.setSelectionKey(selectionKey); + if (eventHandler instanceof Timeoutable) + lastActivityTimers.put(eventHandler, timer.getCurrentTime()); + } + deferredRegistrations.clear(); + } + } + + @InfoMethod + private void ignoringCancelledKeyException() { } + + @InfoMethod + private void keyAndOpInfo( SelectionKeyAndOp val ) { } + + @Transport + private void enableInterestOps() { + synchronized (interestOpsList) { + for (SelectionKeyAndOp keyAndOp : interestOpsList ) { + SelectionKey selectionKey = keyAndOp.selectionKey; + + // Need to check if the SelectionKey is valid because a + // connection's SelectionKey could be put on the list to + // have its OP enabled and before it's enabled have its + // associated connection reclaimed and/or closed which will + // cancel the SelectionKey. + + // Otherwise, the enabling of the OP will throw an exception + // here and exit this method an potentially not enable all + // registered interest ops. + // + // So, we ignore SelectionKeys that are invalid. They will + // get cleaned up and removed from this Selector's key set + // on the next Selector.select() call. + + if (selectionKey.isValid()) { + keyAndOpInfo(keyAndOp); + int keyOp = keyAndOp.keyOp; + try { + int selectionKeyOps = selectionKey.interestOps(); + selectionKey.interestOps(selectionKeyOps | keyOp); + } catch (CancelledKeyException cke) { + // It is possible that between the time when an + // SelectionKey's interestOp was registered to be + // enabled by Thread 1 that the Connection + // associated with the SelectionKey was closed by + // Thread 2 where Thread 2 will cancel the + // SelectionKey. As a result, we catch and + // ignore this exception condition. + ignoringCancelledKeyException(); + } + } + } + + interestOpsList.clear(); + } + } + + @Transport + private void createListenerThread(EventHandler eventHandler) { + Acceptor acceptor = eventHandler.getAcceptor(); + ListenerThread listenerThread = + new ListenerThreadImpl(orb, acceptor); + synchronized (this) { + listenerThreads.put(eventHandler, listenerThread); + } + Throwable throwable = null; + try { + orb.getThreadPoolManager().getThreadPool(0) + .getWorkQueue(0).addWork((Work)listenerThread); + } catch (NoSuchThreadPoolException e) { + throwable = e; + } catch (NoSuchWorkQueueException e) { + throwable = e; + } + if (throwable != null) { + throw new RuntimeException(throwable); + } + } + + @InfoMethod + private void cannotFindListenerThread() { } + + @Transport + private void destroyListenerThread(EventHandler eventHandler) { + ListenerThread listenerThread ; + synchronized (this) { + listenerThread = listenerThreads.get(eventHandler); + if (listenerThread == null) { + cannotFindListenerThread() ; + return; + } + listenerThreads.remove(eventHandler); + } + + listenerThread.close(); + } + + @Transport + private void createReaderThread(EventHandler eventHandler) { + Connection connection = eventHandler.getConnection(); + ReaderThread readerThread = + new ReaderThreadImpl(orb, connection ); + synchronized (this) { + readerThreads.put(eventHandler, readerThread); + } + Throwable throwable = null; + try { + orb.getThreadPoolManager().getThreadPool(0) + .getWorkQueue(0).addWork((Work)readerThread); + } catch (NoSuchThreadPoolException e) { + throwable = e; + } catch (NoSuchWorkQueueException e) { + throwable = e; + } + if (throwable != null) { + throw new RuntimeException(throwable); + } + } + + @InfoMethod + private void cannotFindReaderThread() { } + + @Transport + private void destroyReaderThread(EventHandler eventHandler) { + ReaderThread readerThread ; + synchronized (this) { + readerThread = readerThreads.get(eventHandler); + if (readerThread == null) { + cannotFindReaderThread(); + return; + } + readerThreads.remove(eventHandler); + } + readerThread.close(); + } + + // Private class to contain a SelectionKey and a SelectionKey op. + // Used only by SelectorImpl to register and enable SelectionKey + // Op. + // REVISIT - Could do away with this class and use the EventHanlder + // directly. + private static class SelectionKeyAndOp + { + // A SelectionKey.[OP_READ|OP_WRITE|OP_ACCEPT|OP_CONNECT] + public int keyOp; + public SelectionKey selectionKey; + + // constructor + public SelectionKeyAndOp(SelectionKey selectionKey, int keyOp) { + this.selectionKey = selectionKey; + this.keyOp = keyOp; + } + } + +// End of file. +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SharedCDRContactInfoImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SharedCDRContactInfoImpl.java new file mode 100644 index 000000000..820992229 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SharedCDRContactInfoImpl.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher; +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.SocketInfo; + +import com.sun.corba.ee.impl.encoding.BufferManagerFactory; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.impl.protocol.MessageMediatorImpl; +import com.sun.corba.ee.impl.protocol.SharedCDRClientRequestDispatcherImpl; + +public class SharedCDRContactInfoImpl + extends + ContactInfoBase +{ + // This is only necessary for the pi.clientrequestinfo test. + // It tests that request ids are different. + // Rather than rewrite the test, just fake it. + private static int requestId = 0; + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public SharedCDRContactInfoImpl( + ORB orb, + ContactInfoList contactInfoList, + IOR effectiveTargetIOR, + short addressingDisposition) + { + this.orb = orb; + this.contactInfoList = contactInfoList; + this.effectiveTargetIOR = effectiveTargetIOR; + this.addressingDisposition = addressingDisposition; + } + + public String getType() + { + throw wrapper.undefinedSocketinfoOperation() ; + } + + public String getHost() + { + throw wrapper.undefinedSocketinfoOperation() ; + } + + public int getPort() + { + throw wrapper.undefinedSocketinfoOperation() ; + } + + public ClientRequestDispatcher getClientRequestDispatcher() + { + // REVISIT - use registry + return new SharedCDRClientRequestDispatcherImpl(); + } + + public boolean isConnectionBased() + { + return false; + } + + public boolean shouldCacheConnection() + { + return false; + } + + public String getConnectionCacheType() + { + throw wrapper.methodShouldNotBeCalled(); + } + + public Connection createConnection() + { + throw wrapper.methodShouldNotBeCalled(); + } + + // Called when client making an invocation. + @Override + public MessageMediator createMessageMediator(ORB broker, + ContactInfo contactInfo, + Connection connection, + String methodName, + boolean isOneWay) + { + if (connection != null) { + throw wrapper.connectionNotNullInCreateMessageMediator( connection ) ; + } + + MessageMediator messageMediator = + new MessageMediatorImpl( + (ORB) broker, + (ContactInfo)contactInfo, + null, // Connection; + GIOPVersion.chooseRequestVersion( (ORB)broker, + effectiveTargetIOR), + effectiveTargetIOR, + requestId++, // Fake RequestId + getAddressingDisposition(), + methodName, + isOneWay); + + return messageMediator; + } + + public CDROutputObject createOutputObject(MessageMediator messageMediator) + { + MessageMediator corbaMessageMediator = (MessageMediator) + messageMediator; + // NOTE: GROW. + CDROutputObject outputObject = + OutputStreamFactory.newCDROutputObject(orb, messageMediator, + corbaMessageMediator.getRequestHeader(), + corbaMessageMediator.getStreamFormatVersion(), + BufferManagerFactory.GROW); + messageMediator.setOutputObject(outputObject); + return outputObject; + } + + //////////////////////////////////////////////////// + // + // spi.transport.CorbaContactInfo + // + + public String getMonitoringName() + { + throw wrapper.methodShouldNotBeCalled(); + } + + //////////////////////////////////////////////////// + // + // java.lang.Object + // + + // NOTE: hashCode and equals are CRITICAL to IIOP failover implementation. + // See SocketOrChannelContactInfoImpl.equals. + + // This calculation must be identical to SocketOrChannelContactInfoImpl. + private int hashCode = + SocketInfo.IIOP_CLEAR_TEXT.hashCode() + "localhost".hashCode() ^ -1; + + public int hashCode() + { + return hashCode; + } + + public boolean equals(Object obj) + { + return obj instanceof SharedCDRContactInfoImpl; + } + + public String toString() + { + return + "SharedCDRContactInfoImpl[" + + "]"; + } + + ////////////////////////////////////////////////// + // + // Implementation + // +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SocketChannelReader.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SocketChannelReader.java new file mode 100644 index 000000000..9a35fcd52 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/SocketChannelReader.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.orb.ORB; + +import java.io.EOFException; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +public class SocketChannelReader { + private ORB orb; + + public SocketChannelReader(ORB orb) { + this.orb = orb; + } + + /** + * Reads all currently available data from the socket channel, appending it to any data left + * from a previous read. + * @param channel the channel from which to read + * @param previouslyReadData the old data to read; note: all data up to the limit is considered valid. + * @param minNeeded the minimum number of bytes that should be present in the buffer before returning + * @return a buffer containing all old data, with all newly available data appended to it. + * @throws IOException if an error occurs while reading from the channel. + */ + public ByteBuffer read(SocketChannel channel, ByteBuffer previouslyReadData, int minNeeded) throws IOException { + ByteBuffer byteBuffer = prepareToAppendTo(previouslyReadData); + + int numBytesRead = channel.read(byteBuffer); + if (numBytesRead < 0) { + throw new EOFException("End of input detected"); + } else if (numBytesRead == 0) { + byteBuffer.flip(); + return null; + } + + while (numBytesRead > 0 && byteBuffer.position() < minNeeded) { + if (haveFilledBuffer(byteBuffer)) + byteBuffer = expandBuffer(byteBuffer); + numBytesRead = channel.read(byteBuffer); + } + + return byteBuffer; + } + + private ByteBuffer expandBuffer(ByteBuffer byteBuffer) { + byteBuffer.flip(); + byteBuffer = reallocateBuffer(byteBuffer); + return byteBuffer; + } + + private boolean haveFilledBuffer(ByteBuffer byteBuffer) { + return byteBuffer.position() == byteBuffer.capacity(); + } + + private ByteBuffer prepareToAppendTo(ByteBuffer byteBuffer) { + if (byteBuffer == null) { + byteBuffer = allocateBuffer(); + } else if (byteBuffer.limit() == byteBuffer.capacity()) { + byteBuffer = reallocateBuffer(byteBuffer); + } else { + byteBuffer.position(byteBuffer.limit()).limit(byteBuffer.capacity()); + } + return byteBuffer; + } + + private ByteBuffer reallocateBuffer(ByteBuffer byteBuffer) { + try { + return orb.getByteBufferPool().reAllocate(byteBuffer, 2*byteBuffer.capacity()); + } finally { + byteBuffer.position(0); // reAllocate call above moves the position; move it back now in case we need it + } + } + + private ByteBuffer allocateBuffer() { + return orb.getByteBufferPool().getByteBuffer(orb.getORBData().getReadByteBufferSize()); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TcpTimeoutsImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TcpTimeoutsImpl.java new file mode 100644 index 000000000..0e842fad8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TcpTimeoutsImpl.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.transport.TcpTimeouts; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +/** + * @author Charlie Hunt + * @author Ken Cavanaugh + */ +public class TcpTimeoutsImpl implements TcpTimeouts +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private final int initial_time_to_wait; + private final int max_time_to_wait; + private int backoff_factor; + private final int max_single_wait_time; + + public TcpTimeoutsImpl( String args ) { + String[] data = args.split( ":" ) ; + if ((data.length < 3) || (data.length > 4)) { + throw wrapper.badTimeoutDataLength(); + } + + initial_time_to_wait = parseArg( "initial_time_to_wait", data[0] ) ; + max_time_to_wait = parseArg( "max_time_to_wait", data[1] ) ; + setBackoffFactor( parseArg( "backoff_factor", data[2] ) ) ; + if (data.length == 4) { + max_single_wait_time = parseArg("max_single_wait_time", data[3]); + } else { + max_single_wait_time = Integer.MAX_VALUE; + } + } + + public TcpTimeoutsImpl( int initial_time, int max_time, + int backoff_percent) { + this( initial_time, max_time, backoff_percent, Integer.MAX_VALUE ) ; + } + + public TcpTimeoutsImpl( int initial_time, int max_time, + int backoff_percent, int max_single_wait_time ) { + this.initial_time_to_wait = initial_time; + this.max_time_to_wait = max_time; + setBackoffFactor( backoff_percent ) ; + this.max_single_wait_time = max_single_wait_time ; + } + + private void setBackoffFactor( int backoff_percent ) { + // Avoiding floating point number. Timeout is obtained by + // dividing by 100 after multiplying by backoff_factor. + this.backoff_factor = 100 + backoff_percent; + } + + private int parseArg( String name, String value ) { + try { + int result = Integer.parseInt( value ) ; + if (result <= 0) { + throw wrapper.badTimeoutStringData(value, name); + } + return result ; + } catch (NumberFormatException exc) { + throw wrapper.badTimeoutStringData( exc, value, name ) ; + } + } + + public int get_initial_time_to_wait() { return initial_time_to_wait; } + + public int get_max_time_to_wait() { return max_time_to_wait; } + + public int get_backoff_factor() { return backoff_factor; } + + public int get_max_single_wait_time() { return max_single_wait_time; } + + public Waiter waiter() { + return new Waiter() { + // Use long so that arithmetic works correctly if + // max_single_wait_time is set to Integer.MAX_VALUE. + private long current_wait = initial_time_to_wait ; + private long total_time = 0 ; + + public void advance() { + if (current_wait != max_single_wait_time) { + current_wait = (current_wait * backoff_factor) / 100 ; + if (current_wait > max_single_wait_time) { + current_wait = max_single_wait_time; + } + } + } + + public void reset() { + current_wait = initial_time_to_wait ; + } + + public int getTime() { + return (int)current_wait ; + } + + public int getTimeForSleep() { + int result = (int)current_wait ; + if (total_time < max_time_to_wait) { + total_time += current_wait; + } + return result ; + } + + public int timeWaiting() { + return (int)total_time ; + } + + public boolean sleepTime() { + if (isExpired()) { + return false; + } + + try { + Thread.sleep( getTimeForSleep() ) ; + return true ; + } catch (InterruptedException exc) { + // this happens so rarely that we will + // ignore it. Just log at FINE level. + wrapper.interruptedExceptionInTimeout() ; + } + + // actually unreachable, but the compiler doesn't know that + return false ; + } + + public boolean isExpired() { + return total_time >= max_time_to_wait ; + } + } ; + } + + @Override + public String toString() { + return "TcpTimeoutsImpl[" + + initial_time_to_wait + ":" + + max_time_to_wait + ":" + + backoff_factor + ":" + + max_single_wait_time + "]" ; + } + + @Override + public boolean equals( Object obj ) { + if (obj == this) { + return true; + } + + if (!(obj instanceof TcpTimeouts)) { + return false; + } + + TcpTimeouts other = (TcpTimeouts)obj ; + + return (initial_time_to_wait == other.get_initial_time_to_wait()) && + (max_time_to_wait == other.get_max_time_to_wait()) && + (backoff_factor == other.get_backoff_factor()) && + (max_single_wait_time == other.get_max_single_wait_time()) ; + } + + @Override + public int hashCode() { + return initial_time_to_wait ^ max_time_to_wait ^ + backoff_factor ^ max_single_wait_time ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelector.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelector.java new file mode 100644 index 000000000..344112e08 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelector.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; + +import com.sun.corba.ee.spi.transport.TemporarySelectorState; + +/** + * + * @author Charlie Hunt + */ + +/** + * + * Encapsulates a temporary Selector and temporary Selector state + */ +public class TemporarySelector { + + private TemporarySelectorState itsState; + private Selector itsSelector; + + /** Creates a new instance of TemporarySelector */ + public TemporarySelector(SelectableChannel theSelectableChannel) throws IOException { + itsSelector = theSelectableChannel.provider().openSelector(); + itsState = new TemporarySelectorStateOpen(); + } + + /** + * NOTE: There is a potential for a situation, (albiet very remote), that + * some other thread may be initiating an explicit "close" of a + * Connection (if someone overrides the implementation of + * SocketOrChannelConnectionImpl and an explicit call to "close" + * the Connection), that call to close the Connection may also + * attempt to close a TemporarySelector. If that TemporarySelector + * is currently in the select(long theTimeout), then the closing + * of that TemporarySelector will not occur until the + * select(long theTimeout) method exits, (i.e. maximum blocking wait + * time for the close will be theTimeout milliseconds which by + * default is 2000 milliseconds). + * This artifact occurs as a result of the TemporarySelector's + * select() and close() operations being atomic operations. + * However, this potential issue does not exist in the current + * implementation of SocketOrChannelConnectionImpl. It may arise + * if someone chooses to extend the implementation of the + * SocketOrChannelConnectionImpl and make explicit calls to + * close the Connection. An example of this potential scenario + * can be found in the "no connection cache" plug-in implementation. + * To avoid this potential scenario, the "no connection + * cache" plug-in disables the read optimization to always + * enter a blocking read. + * See com.sun.corba.ee.impl.plugin.hwlb.NoConnectionCacheImpl.java + * to see how the 'always enter blocking read' optimization is + * disabled. + */ + synchronized public int select(long theTimeout) throws IOException { + return itsState.select(itsSelector, theTimeout); + } + + synchronized public SelectionKey registerChannel(SelectableChannel theSelectableChannel, int theOps) throws IOException { + return itsState.registerChannel(itsSelector, theSelectableChannel, theOps); + } + + /** + * NOTE: There is a potential for a situation, (albiet very remote), that + * some other thread may be in this TemporarySelector's select() + * method while another thread is trying to call this "close" method + * as a result of an explicit close of a Connection (if someone + * overrides the implementation of SocketOrChannelConnectionImpl + * and makes an explicit call to "close" the Connection), that call + * to close the Connection may also attempt to call this close method. + * If that other thread is currently in this TemporarySelector's + * select(long theTimeout) method, then the call to this close method + * will block until the select(long theTimeout) method exits, (i.e. + * maximum blocking wait time for this close will be theTimeout + * milliseconds which by default is 2000 milliseconds). + * This artifact occurs as a result of the TemporarySelector's + * select() and close() operations being atomic operations. + * However, this potential issue does not exist in the current + * implementation of SocketOrChannelConnectionImpl. It may arise + * if someone chooses to extend the implementation of the + * SocketOrChannelConnectionImpl and make explicit calls to + * close the Connection. An example of this potential scenario + * exists in the "no connection cache" plug-in. To avoid this + * scenario, the "no connection cache" plug-in disables the read + * optimization to always enter a blocking read. + * See com.sun.corba.ee.impl.plugin.hwlb.NoConnectionCacheImpl.java + * to see how the 'always enter blocking read' optimization is + * disabled. + */ + synchronized public void close() throws IOException { + itsState = itsState.close(itsSelector); + } + + synchronized public void removeSelectedKey(SelectionKey theSelectionKey) throws IOException { + itsState = itsState.removeSelectedKey(itsSelector, theSelectionKey); + } + + synchronized public void cancelAndFlushSelector(SelectionKey theSelectionKey) throws IOException { + itsState = itsState.cancelKeyAndFlushSelector(itsSelector, theSelectionKey); + } + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorClosedException.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorClosedException.java new file mode 100644 index 000000000..a34efa690 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorClosedException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; + +/** + * + * @author Charlie Hunt + */ + +/** + * + * Thrown when an operation is performed on a TemporarySelector which + * is not allowed as a result of the curent state of a TemporarySelector. + */ +public class TemporarySelectorClosedException extends IOException { + + /** Creates a new instance of TemporarySelectorClosedException */ + public TemporarySelectorClosedException(String theMessage) { + super(theMessage); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorStateClosed.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorStateClosed.java new file mode 100644 index 000000000..4116b249f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorStateClosed.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; + +import com.sun.corba.ee.spi.transport.TemporarySelectorState; + +import com.sun.corba.ee.spi.trace.Transport; + +/** + * + * @author Charlie Hunt + */ + +/** + * + * An class which models a temporary Selector in a closed state. + */ +@Transport +public class TemporarySelectorStateClosed implements TemporarySelectorState { + + /** Creates a new instance of TemporarySelectorStateOpen */ + public TemporarySelectorStateClosed() { + } + + public int select(Selector theSelector, long theTimeout) throws IOException { + String selectorToString = getSelectorToString(theSelector); + throw new TemporarySelectorClosedException("Temporary Selector " + + selectorToString + + " closed"); + } + + public SelectionKey registerChannel(Selector theSelector, + SelectableChannel theSelectableChannel, + int theOps) throws IOException { + String selectorToString = getSelectorToString(theSelector); + throw new TemporarySelectorClosedException("Temporary Selector " + + selectorToString + + " closed"); + } + + public TemporarySelectorState cancelKeyAndFlushSelector(Selector theSelector, + SelectionKey theSelectionKey) throws IOException { + String selectorToString = getSelectorToString(theSelector); + throw new TemporarySelectorClosedException("Temporary Selector " + + selectorToString + + " closed"); + } + + @Transport + public TemporarySelectorState close(Selector theSelector) throws IOException { + if (theSelector != null && theSelector.isOpen()) { + theSelector.close(); + } + return this; + } + + public TemporarySelectorState removeSelectedKey(Selector theSelector, + SelectionKey theSelectionKey) throws IOException { + String selectorToString = getSelectorToString(theSelector); + throw new TemporarySelectorClosedException("Temporary Selector " + + selectorToString + + " closed"); + } + + private String getSelectorToString(Selector theSelector) { + String selectorToString = "(null)"; + if (theSelector != null) { + selectorToString = theSelector.toString(); + } + return selectorToString; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorStateOpen.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorStateOpen.java new file mode 100644 index 000000000..cd31df4bb --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TemporarySelectorStateOpen.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; + +import com.sun.corba.ee.spi.transport.TemporarySelectorState; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.trace.Transport; + +/** + * + * @author Charlie Hunt + */ + +/** + * + * A class which models temporary Selector in an open state. + */ +@Transport +public class TemporarySelectorStateOpen implements TemporarySelectorState { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + /** Creates a new instance of TemporarySelectorStateOpen */ + public TemporarySelectorStateOpen() { + } + + @Transport + public int select(Selector theSelector, long theTimeout) throws IOException { + int result; + if (theSelector.isOpen()) { + if (theTimeout > 0) { + result = theSelector.select(theTimeout); + } else { + throw wrapper.temporarySelectorSelectTimeoutLessThanOne( + theSelector, theTimeout); + } + } else { + throw new TemporarySelectorClosedException( + "Selector " + theSelector.toString() + " is closed."); + } + + return result; + } + + @Transport + public SelectionKey registerChannel(Selector theSelector, + SelectableChannel theSelectableChannel, int theOps) throws IOException { + + SelectionKey key; + if (theSelector.isOpen()) { + key = theSelectableChannel.register(theSelector, theOps); + } else { + throw new TemporarySelectorClosedException("Selector " + + theSelector.toString() + + " is closed."); + } + return key; + } + + @Transport + public TemporarySelectorState cancelKeyAndFlushSelector(Selector theSelector, + SelectionKey theSelectionKey) throws IOException { + + if (theSelectionKey != null) { + theSelectionKey.cancel(); + } + + if (theSelector.isOpen()) { + theSelector.selectNow(); + } else { + throw new TemporarySelectorClosedException( + "Selector " + theSelector.toString() + " is closed."); } + + return this; + } + + @Transport + public TemporarySelectorState close(Selector theSelector) throws IOException { + theSelector.close(); + return new TemporarySelectorStateClosed(); + } + + @Transport + public TemporarySelectorState removeSelectedKey(Selector theSelector, + SelectionKey theSelectionKey) throws IOException { + if (theSelector.isOpen()) { + theSelector.selectedKeys().remove(theSelectionKey); + } else { + throw new TemporarySelectorClosedException("Selector " + + theSelector.toString() + + " is closed."); + } + return this; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/Timeoutable.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/Timeoutable.java new file mode 100644 index 000000000..ed5509e63 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/Timeoutable.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +/** + * Interface for an object that can timeout waiting for activity. + */ +public interface Timeoutable { + + /** + * Checks to see if a timeout has occurred. + * @param timeSinceLastActivity the time in msec since the last activity for this action. + */ + void checkForTimeout(long timeSinceLastActivity); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TransportManagerImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TransportManagerImpl.java new file mode 100644 index 000000000..516d01ab3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/TransportManagerImpl.java @@ -0,0 +1,243 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.sun.corba.ee.spi.transport.Selector; + +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ByteBufferPool; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.transport.MessageTraceManager; + +// REVISIT - impl/poa specific: +import com.sun.corba.ee.impl.oa.poa.Policies; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.spi.trace.Transport; + +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.InboundConnectionCache; +import com.sun.corba.ee.spi.transport.OutboundConnectionCache; + +import org.glassfish.external.probe.provider.StatsProviderManager ; +import org.glassfish.external.probe.provider.PluginPoint ; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** + * @author Harold Carr + */ +// Note that no ObjectKeyName attribute is needed, because there is only +// one CorbaTransportManager per ORB. +@Transport +public class TransportManagerImpl + implements + TransportManager +{ + protected ORB orb; + protected List acceptors; + protected final Map outboundConnectionCaches; + protected final Map inboundConnectionCaches; + protected Selector selector; + + public TransportManagerImpl(ORB orb) + { + this.orb = orb; + acceptors = new ArrayList(); + outboundConnectionCaches = new HashMap(); + inboundConnectionCaches = new HashMap(); + selector = new SelectorImpl(orb); + orb.mom().register( orb, this ) ; + } + + public ByteBufferPool getByteBufferPool(int id) + { + throw new RuntimeException(); + } + + public OutboundConnectionCache getOutboundConnectionCache( + ContactInfo contactInfo) + { + synchronized (contactInfo) { + if (contactInfo.getConnectionCache() == null) { + OutboundConnectionCache connectionCache = null; + synchronized (outboundConnectionCaches) { + connectionCache = outboundConnectionCaches.get( + contactInfo.getConnectionCacheType()); + if (connectionCache == null) { + // REVISIT: Would like to be able to configure + // the connection cache type used. + connectionCache = + new OutboundConnectionCacheImpl(orb, + contactInfo); + + // We need to clean up the multi-cache support: + // this really only works with a single cache. + orb.mom().register( this, connectionCache ) ; + StatsProviderManager.register( "orb", PluginPoint.SERVER, + "orb/transport/connectioncache/outbound", connectionCache ) ; + + outboundConnectionCaches.put( + contactInfo.getConnectionCacheType(), + connectionCache); + } + } + contactInfo.setConnectionCache(connectionCache); + } + return contactInfo.getConnectionCache(); + } + } + + public Collection getOutboundConnectionCaches() + { + return outboundConnectionCaches.values(); + } + + public Collection getInboundConnectionCaches() + { + return inboundConnectionCaches.values(); + } + + public InboundConnectionCache getInboundConnectionCache( + Acceptor acceptor) + { + synchronized (acceptor) { + if (acceptor.getConnectionCache() == null) { + InboundConnectionCache connectionCache = null; + synchronized (inboundConnectionCaches) { + connectionCache = inboundConnectionCaches.get( + acceptor.getConnectionCacheType()); + if (connectionCache == null) { + // REVISIT: Would like to be able to configure + // the connection cache type used. + connectionCache = + new InboundConnectionCacheImpl(orb, + acceptor); + orb.mom().register( this, connectionCache ) ; + StatsProviderManager.register( "orb", PluginPoint.SERVER, + "orb/transport/connectioncache/inbound", connectionCache ) ; + + inboundConnectionCaches.put( + acceptor.getConnectionCacheType(), + connectionCache); + } + } + acceptor.setConnectionCache(connectionCache); + } + return acceptor.getConnectionCache(); + } + } + + public Selector getSelector() { + return selector ; + } + + public Selector getSelector(int id) + { + return selector; + } + + @Transport + public synchronized void registerAcceptor(Acceptor acceptor) { + acceptors.add(acceptor); + } + + @Transport + public synchronized void unregisterAcceptor(Acceptor acceptor) { + acceptors.remove(acceptor); + } + + @Transport + public void close() + { + for (OutboundConnectionCache cc : outboundConnectionCaches.values()) { + StatsProviderManager.unregister( cc ) ; + cc.close() ; + } + for (InboundConnectionCache cc : inboundConnectionCaches.values()) { + StatsProviderManager.unregister( cc ) ; + cc.close() ; + } + getSelector(0).close(); + } + + //////////////////////////////////////////////////// + // + // CorbaTransportManager + // + + public Collection getAcceptors() { + return getAcceptors( null, null ) ; + } + + @InfoMethod + private void display( String msg ) { } + + @Transport + public Collection getAcceptors(String objectAdapterManagerId, + ObjectAdapterId objectAdapterId) + { + // REVISIT - need to filter based on arguments. + + // REVISIT - initialization will be moved to OA. + // Lazy initialization of acceptors. + for (Acceptor acc : acceptors) { + if (acc.initialize()) { + display( "initializing acceptors" ) ; + if (acc.shouldRegisterAcceptEvent()) { + orb.getTransportManager().getSelector(0) + .registerForEvent(acc.getEventHandler()); + } + } + } + return acceptors; + } + + // REVISIT - POA specific policies + @Transport + public void addToIORTemplate(IORTemplate iorTemplate, + Policies policies, + String codebase, + String objectAdapterManagerId, + ObjectAdapterId objectAdapterId) + { + Iterator iterator = + getAcceptors(objectAdapterManagerId, objectAdapterId).iterator(); + while (iterator.hasNext()) { + Acceptor acceptor = (Acceptor) iterator.next(); + acceptor.addToIORTemplate(iorTemplate, policies, codebase); + } + } + + private ThreadLocal currentMessageTraceManager = + new ThreadLocal() { + public Object initialValue() + { + return new MessageTraceManagerImpl( ) ; + } + } ; + + public MessageTraceManager getMessageTraceManager() + { + return (MessageTraceManager)(currentMessageTraceManager.get()) ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueBlockingImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueBlockingImpl.java new file mode 100644 index 000000000..4765c3fcb --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueBlockingImpl.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.concurrent ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue ; + +public class ConcurrentQueueBlockingImpl implements ConcurrentQueue { + // This implementation of ConcurrentQueue uses a single lock, which must be + // acquired to update the list. Every operation on this class updates the + // structure, so read/write locking is probably not useful. + // + // Trying to build a lock-free implementation runs into the usual problems: + // we need to atomically update more than one location at a time in the structure. + // Short of a transactional memory implementation, we would either need a complicated + // implementation implementing recursive fixup, or something like the Ladan-Mozes and + // Shavit algorithm (see "An Optimistic Approach to Lock-Free FIFO Queues" + // at http://people.csail.mit.edu/edya/publications/publicationsAndPatents.htm) + // that delays fixing up one direction in a double linked list. However, that + // algorithm does not consider general deletion, and I don't know whether that + // capability can be easily added or not. + // Any of these approaches are quite complicated, and so we won't go there yet. + // As always, first make it work, then make it fast(er), but only if necessary. + // + // Structure: Head points to a node containing a null value, which is a special marker. + // head.next is the first element, head.prev is the last. The queue is empty if + // head.next == head.prev == head. + final Entry head = new Entry( null, 0 ) ; + final Object lock = new Object() ; + int count = 0 ; + private long ttl ; + + public ConcurrentQueueBlockingImpl( long ttl ) { + head.next = head ; + head.prev = head ; + this.ttl = ttl ; + } + + private final class Entry { + Entry next = null ; + Entry prev = null ; + private HandleImpl handle ; + private long expiration ; + + Entry( V value, long expiration ) { + handle = new HandleImpl( this, value, expiration ) ; + this.expiration = expiration ; + } + + HandleImpl handle() { + return handle ; + } + } + + private final class HandleImpl implements Handle { + private Entry entry ; + private final V value ; + private boolean valid ; + private long expiration ; + + HandleImpl( Entry entry, V value, long expiration ) { + this.entry = entry ; + this.value = value ; + this.valid = true ; + this.expiration = expiration ; + } + + Entry entry() { + return entry ; + } + + public V value() { + return value ; + } + + /** Delete the element corresponding to this handle + * from the queue. Takes constant time. + */ + public boolean remove() { + synchronized (lock) { + if (!valid) { + return false ; + } + + valid = false ; + + entry.next.prev = entry.prev ; + entry.prev.next = entry.next ; + count-- ; + } + + entry.prev = null ; + entry.next = null ; + entry.handle = null ; + entry = null ; + valid = false ; + return true ; + } + + public long expiration() { + return expiration ; + } + } + + public int size() { + synchronized (lock) { + return count ; + } + } + + /** Add a new element to the tail of the queue. + * Returns a handle for the element in the queue. + */ + public Handle offer( V arg ) { + if (arg == null) + throw new IllegalArgumentException( "Argument cannot be null" ) ; + + Entry entry = new Entry( arg, System.currentTimeMillis() + ttl ) ; + + synchronized (lock) { + entry.next = head ; + entry.prev = head.prev ; + head.prev.next = entry ; + head.prev = entry ; + count++ ; + } + + return entry.handle() ; + } + + /** Return an element from the head of the queue. + * The element is removed from the queue. + */ + public Handle poll() { + Entry first = null ; + + synchronized (lock) { + first = head.next ; + if (first == head) + return null ; + else { + final Handle result = first.handle() ; + result.remove() ; + return result ; + } + } + } + + public Handle peek() { + synchronized (lock) { + Entry first = head.next ; + if (first == head) + return null ; + else + return first.handle() ; + } + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueImpl.java new file mode 100644 index 000000000..c20c8bf59 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueImpl.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.concurrent ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue ; + +public class ConcurrentQueueImpl implements ConcurrentQueue { + // This implementation of ConcurrentQueue is unsynchronized, for use in + // other implementations that manage concurrency with locks. + // + // Structure: Head points to a node containing a null value, which is a special marker. + // head.next is the first element, head.prev is the last. The queue is empty if + // head.next == head.prev == head. + final Entry head = new Entry( null, 0 ) ; + int count = 0 ; + private long ttl ; + + public ConcurrentQueueImpl( long ttl ) { + head.next = head ; + head.prev = head ; + this.ttl = ttl ; + } + + private final class Entry { + Entry next = null ; + Entry prev = null ; + private HandleImpl handle ; + private long expiration ; + + Entry( V value, long expiration ) { + handle = new HandleImpl( this, value, expiration ) ; + this.expiration = expiration ; + } + + HandleImpl handle() { + return handle ; + } + } + + private final class HandleImpl implements Handle { + private Entry entry ; + private final V value ; + private boolean valid ; + private long expiration ; + + HandleImpl( Entry entry, V value, long expiration ) { + this.entry = entry ; + this.value = value ; + this.valid = true ; + this.expiration = expiration ; + } + + Entry entry() { + return entry ; + } + + public V value() { + return value ; + } + + /** Delete the element corresponding to this handle + * from the queue. Takes constant time. + */ + public boolean remove() { + if (!valid) { + return false ; + } + + valid = false ; + + entry.next.prev = entry.prev ; + entry.prev.next = entry.next ; + count-- ; + + entry.prev = null ; + entry.next = null ; + entry.handle = null ; + entry = null ; + valid = false ; + return true ; + } + + public long expiration() { + return expiration ; + } + } + + public int size() { + return count ; + } + + /** Add a new element to the tail of the queue. + * Returns a handle for the element in the queue. + */ + public Handle offer( V arg ) { + if (arg == null) + throw new IllegalArgumentException( "Argument cannot be null" ) ; + + Entry entry = new Entry( arg, System.currentTimeMillis() + ttl ) ; + + entry.next = head ; + entry.prev = head.prev ; + head.prev.next = entry ; + head.prev = entry ; + count++ ; + + return entry.handle() ; + } + + /** Return an element from the head of the queue. + * The element is removed from the queue. + */ + public Handle poll() { + Entry first = null ; + + first = head.next ; + if (first == head) { + return null ; + } + + final Handle result = first.handle() ; + result.remove() ; + return result ; + } + + public Handle peek() { + Entry first = head.next ; + if (first == head) + return null ; + else + return first.handle() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueNonBlockingImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueNonBlockingImpl.java new file mode 100644 index 000000000..6154d3fb6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/ConcurrentQueueNonBlockingImpl.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.concurrent ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue ; + +public class ConcurrentQueueNonBlockingImpl implements ConcurrentQueue { + // This implementation of ConcurrentQueue uses a non-blocking algorithm (TBD). + // For now, this is the same as the blocking impl. + // + // Trying to build a lock-free implementation runs into the usual problems: + // we need to atomically update more than one location at a time in the structure. + // Short of a transactional memory implementation, we would either need a complicated + // implementation implementing recursive fixup, or something like the Ladan-Mozes and + // Shavit algorithm (see "An Optimistic Approach to Lock-Free FIFO Queues" + // at http://people.csail.mit.edu/edya/publications/publicationsAndPatents.htm) + // that delays fixing up one direction in a double linked list. However, that + // algorithm does not consider general deletion, and I don't know whether that + // capability can be easily added or not. + // Any of these approaches are quite complicated, and so we won't go there yet. + // As always, first make it work, then make it fast(er), but only if necessary. + // + // Structure: Head points to a node containing a null value, which is a special marker. + // head.next is the first element, head.prev is the last. The queue is empty if + // head.next == head.prev == head. + final Entry head = new Entry( null, 0 ) ; + final Object lock = new Object() ; + int count = 0 ; + private long ttl ; + + public ConcurrentQueueNonBlockingImpl( long ttl ) { + head.next = head ; + head.prev = head ; + this.ttl = ttl ; + } + + private final class Entry { + Entry next = null ; + Entry prev = null ; + private HandleImpl handle ; + private long expiration ; + + Entry( V value, long expiration ) { + handle = new HandleImpl( this, value, expiration ) ; + this.expiration = expiration ; + } + + HandleImpl handle() { + return handle ; + } + } + + private final class HandleImpl implements Handle { + private Entry entry ; + private final V value ; + private boolean valid ; + private long expiration ; + + HandleImpl( Entry entry, V value, long expiration ) { + this.entry = entry ; + this.value = value ; + this.valid = true ; + this.expiration = expiration ; + } + + Entry entry() { + return entry ; + } + + public V value() { + return value ; + } + + /** Delete the element corresponding to this handle + * from the queue. Takes constant time. + */ + public boolean remove() { + synchronized (lock) { + if (!valid) { + return false ; + } + + valid = false ; + + entry.next.prev = entry.prev ; + entry.prev.next = entry.next ; + count-- ; + } + + entry.prev = null ; + entry.next = null ; + entry.handle = null ; + entry = null ; + valid = false ; + return true ; + } + + public long expiration() { + return expiration ; + } + } + + public int size() { + synchronized (lock) { + return count ; + } + } + + /** Add a new element to the tail of the queue. + * Returns a handle for the element in the queue. + */ + public Handle offer( V arg ) { + if (arg == null) + throw new IllegalArgumentException( "Argument cannot be null" ) ; + + Entry entry = new Entry( arg, System.currentTimeMillis() + ttl ) ; + + synchronized (lock) { + entry.next = head ; + entry.prev = head.prev ; + head.prev.next = entry ; + head.prev = entry ; + count++ ; + } + + return entry.handle() ; + } + + /** Return an element from the head of the queue. + * The element is removed from the queue. + */ + public Handle poll() { + Entry first = null ; + + synchronized (lock) { + first = head.next ; + if (first == head) + return null ; + else { + final Handle result = first.handle() ; + result.remove() ; + return result ; + } + } + } + + public Handle peek() { + synchronized (lock) { + Entry first = head.next ; + if (first == head) + return null ; + else + return first.handle() ; + } + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/LMSQueue.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/LMSQueue.java new file mode 100644 index 000000000..7fd71cdef --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/concurrent/LMSQueue.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** Java implementation of the Lock-Free FIFO queue in Ladan-Mozes and Shavit, + * "An Optimistic Approach to Lock-Free FIFO Queues". + */ +package com.sun.corba.ee.impl.transport.concurrent ; + +import java.util.concurrent.atomic.AtomicReference ; + +public class LMSQueue { + static private class Node { + private V value ; + Node next ; + Node prev ; + + public Node( V value ) { + this.value = value ; + } + + public V getValue() { + return value ; + } + } + + private AtomicReference> head ; + private AtomicReference> tail ; + + public final Node dummyNode = new Node( null ) ; + + public void enqueue( V val ) { + if (val == null) + throw new IllegalArgumentException( "Cannot enqueue null value" ) ; + + Node tl ; + Node nd = new Node( val ) ; + while (true) { + tl = tail.get() ; + nd.next = tl ; + if (tail.compareAndSet( tl, nd )) { + tail.get().prev = nd ; + break ; + } + } + } + + public V dequeue() { + Node tl ; + Node hd ; + Node firstNodePrev ; + Node ndDummy ; + V val ; + + while (true) { //D04 + hd = head.get() ; //D05 + tl = tail.get() ; //D06 + firstNodePrev = hd.prev ; //D07 + val = hd.getValue() ; //D08 + if (hd == head.get()) { //D09 + if (val != null) { //D10 + if (tl != hd) { //D11 + if (firstNodePrev == null) { //D12 + fixList( tl, hd ) ; //D13 + continue ; //D14 + } //D15 + } else { //D16,D17 + ndDummy = new Node( null ) ; //D18,D19 + ndDummy.next = tl ; //D20 + if (tail.compareAndSet( tl, ndDummy )) { //D21 + hd.prev = ndDummy ; //D22 + } else { //D23,D24 + ndDummy = null ; //D25 + } //D26 + continue ; //D27 + } //D28 + if (head.compareAndSet( hd, firstNodePrev )) { //D29 + hd = null ; //D30 + return val ; //D31 + } //D32 + } else { //D33,D34 + if (tail == head) { //D35 + return null ; //D36 + } else { //D37,D38 + if (firstNodePrev == null) { //D39 + fixList( tl, hd ) ; //D40 + continue ; //D41 + } //D42 + head.compareAndSet( hd, firstNodePrev ) ; //D43 + } + } + } + } + } + + private void fixList( Node tl, Node hd ) { + Node curNode = tl ; + Node curNodeNext = null ; + Node nextNodePrev = null ; + + while ((hd == head.get()) && (curNode != head.get())) { + curNodeNext = curNode.next ; + if (curNodeNext == null) { + return ; + } + nextNodePrev = curNodeNext.prev ; + if (nextNodePrev != curNode) { + curNodeNext.prev = curNode ; + } + curNode = curNodeNext ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheBase.java new file mode 100644 index 000000000..7e4e4ad41 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheBase.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import com.sun.corba.ee.spi.transport.connection.ConnectionCache ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue ; +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue.Handle; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Transport +public abstract class ConnectionCacheBase + implements ConnectionCache { + + private boolean flag ; + + // A name for this instance, provided for convenience. + private final String cacheType ; + + // Configuration data + // XXX we may want this data to be dynamically re-configurable + private final int highWaterMark ; // Maximum number of + // connections before we start + // closing idle connections + private final int numberToReclaim ; // How many connections to + // reclaim at once + + // MUST be initialized in a subclass + protected ConcurrentQueue reclaimableConnections = null ; + + public final String getCacheType() { + return cacheType ; + } + + public final int numberToReclaim() { + return numberToReclaim ; + } + + public final int highWaterMark() { + return highWaterMark ; + } + + // The name of this class, which is implemented in the subclass. + // I could derive this from this.getClass().getClassName(), but + // this is easier. + protected abstract String thisClassName() ; + + ConnectionCacheBase( final String cacheType, + final int highWaterMark, final int numberToReclaim ) { + + if (cacheType == null) + throw new IllegalArgumentException( + "cacheType must not be null" ) ; + + if (highWaterMark < 0) + throw new IllegalArgumentException( + "highWaterMark must be non-negative" ) ; + + if (numberToReclaim < 1) + throw new IllegalArgumentException( + "numberToReclaim must be at least 1" ) ; + + this.cacheType = cacheType ; + this.highWaterMark = highWaterMark ; + this.numberToReclaim = numberToReclaim ; + } + + @Override + public String toString() { + return thisClassName() + "[" + + getCacheType() + "]"; + } + + @InfoMethod + private void display( String msg, Object value ) {} + + /** Reclaim some idle cached connections. Will never + * close a connection that is busy. + */ + @Transport + protected boolean reclaim() { + int ctr = 0 ; + while (ctr < numberToReclaim()) { + Handle candidate = reclaimableConnections.poll() ; + if (candidate == null) + // If we have closed all idle connections, we must stop + // reclaiming. + break ; + + try { + display("closing connection", candidate) ; + close( candidate.value() ) ; + } catch (RuntimeException exc) { + display( "exception on close", exc ) ; + throw exc ; + } + + ctr++ ; + } + + display( "number of connections reclaimed", ctr ) ; + return ctr > 0 ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheBlockingBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheBlockingBase.java new file mode 100644 index 000000000..e1d7ec5ce --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheBlockingBase.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + + +import com.sun.corba.ee.spi.transport.connection.Connection ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueueFactory; + +abstract class ConnectionCacheBlockingBase + extends ConnectionCacheBase { + + protected int totalBusy ; // Number of busy connections + protected int totalIdle ; // Number of idle connections + + ConnectionCacheBlockingBase( String cacheType, int highWaterMark, + int numberToReclaim, long ttl ) { + + super( cacheType, highWaterMark, numberToReclaim) ; + + this.totalBusy = 0 ; + this.totalIdle = 0 ; + + this.reclaimableConnections = + ConcurrentQueueFactory.makeConcurrentQueue( ttl ) ; + } + + public synchronized long numberOfConnections() { + return totalIdle + totalBusy ; + } + + public synchronized long numberOfIdleConnections() { + return totalIdle ; + } + + public synchronized long numberOfBusyConnections() { + return totalBusy ; + } + + public synchronized long numberOfReclaimableConnections() { + return reclaimableConnections.size() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheNonBlockingBase.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheNonBlockingBase.java new file mode 100644 index 000000000..f442051e2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/ConnectionCacheNonBlockingBase.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + + +import java.util.concurrent.atomic.AtomicInteger ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueueFactory ; + +abstract class ConnectionCacheNonBlockingBase + extends ConnectionCacheBase { + + protected final AtomicInteger totalBusy ; // Number of busy connections + protected final AtomicInteger totalIdle ; // Number of idle connections + + ConnectionCacheNonBlockingBase( String cacheType, int highWaterMark, + int numberToReclaim, long ttl ) { + + super( cacheType, highWaterMark, numberToReclaim) ; + + this.totalBusy = new AtomicInteger() ; + this.totalIdle = new AtomicInteger() ; + + this.reclaimableConnections = + // XXX make this the non-blocking version once we write it. + ConcurrentQueueFactory.makeBlockingConcurrentQueue( ttl ) ; + } + + public long numberOfConnections() { + return totalIdle.get() + totalBusy.get() ; + } + + public long numberOfIdleConnections() { + return totalIdle.get() ; + } + + public long numberOfBusyConnections() { + return totalBusy.get() ; + } + + public long numberOfReclaimableConnections() { + return reclaimableConnections.size() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/InboundConnectionCacheBlockingImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/InboundConnectionCacheBlockingImpl.java new file mode 100644 index 000000000..c46c35064 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/InboundConnectionCacheBlockingImpl.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + +import java.io.IOException ; + +import java.util.logging.Logger ; + +import java.util.Map ; +import java.util.HashMap ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import com.sun.corba.ee.spi.transport.connection.InboundConnectionCache ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** Manage connections that are initiated from another VM. + * + * @author Ken Cavanaugh + */ +@Transport +public final class InboundConnectionCacheBlockingImpl + extends ConnectionCacheBlockingBase + implements InboundConnectionCache { + + private final Map> connectionMap ; + + protected String thisClassName() { + return "InboundConnectionCacheBlockingImpl" ; + } + + private static final class ConnectionState { + final C connection ; // Connection of the + // ConnectionState + int busyCount ; // Number of calls to + // get without release + int expectedResponseCount ; // Number of expected + // responses not yet + // received + + ConcurrentQueue.Handle reclaimableHandle ; // non-null iff connection + // is not in use and has no + // outstanding requests + + ConnectionState( final C conn ) { + this.connection = conn ; + + busyCount = 0 ; + expectedResponseCount = 0 ; + reclaimableHandle = null ; + } + } + + public InboundConnectionCacheBlockingImpl( final String cacheType, + final int highWaterMark, final int numberToReclaim, final long ttl ) { + + super( cacheType, highWaterMark, numberToReclaim, ttl ) ; + + this.connectionMap = new HashMap>() ; + } + + // We do not need to define equals or hashCode for this class. + + @InfoMethod + private void display( String msg, Object value ) {} + + @InfoMethod + private void msg( String msg ) {} + + @Transport + public synchronized void requestReceived( final C conn ) { + ConnectionState cs = getConnectionState( conn ) ; + + final int totalConnections = totalBusy + totalIdle ; + if (totalConnections > highWaterMark()) + reclaim() ; + + ConcurrentQueue.Handle reclaimHandle = cs.reclaimableHandle ; + if (reclaimHandle != null) { + reclaimHandle.remove() ; + display( "removed from reclaimableQueue", conn ) ; + } + + int count = cs.busyCount++ ; + if (count == 0) { + display( "moved from idle to busy", conn ) ; + + totalIdle-- ; + totalBusy++ ; + } + } + + @Transport + public synchronized void requestProcessed( final C conn, + final int numResponsesExpected ) { + final ConnectionState cs = connectionMap.get( conn ) ; + + if (cs == null) { + msg( "connection was closed") ; + return ; + } else { + cs.expectedResponseCount += numResponsesExpected ; + int numResp = cs.expectedResponseCount ; + int numBusy = --cs.busyCount ; + + display( "responses expected", numResp ) ; + display( "connection busy count", numBusy ) ; + + if (numBusy == 0) { + totalBusy-- ; + totalIdle++ ; + + if (numResp == 0) { + display( "queuing reclaimable connection", conn ) ; + + if ((totalBusy+totalIdle) > highWaterMark()) { + close( conn ) ; + } else { + cs.reclaimableHandle = + reclaimableConnections.offer( conn ) ; + } + } + } + } + } + + /** Decrement the number of expected responses. When a connection is idle + * and has no expected responses, it can be reclaimed. + */ + @Transport + public synchronized void responseSent( final C conn ) { + final ConnectionState cs = connectionMap.get( conn ) ; + final int waitCount = --cs.expectedResponseCount ; + if (waitCount == 0) { + display( "reclaimable connection", conn ) ; + + if ((totalBusy+totalIdle) > highWaterMark()) { + close( conn ) ; + } else { + cs.reclaimableHandle = + reclaimableConnections.offer( conn ) ; + } + } else { + display( "wait count", waitCount ) ; + } + } + + /** Close a connection, regardless of whether the connection is busy + * or not. + */ + @Transport + public synchronized void close( final C conn ) { + final ConnectionState cs = connectionMap.remove( conn ) ; + display( "connection state", cs ) ; + + int count = cs.busyCount ; + + if (count == 0) + totalIdle-- ; + else + totalBusy-- ; + + final ConcurrentQueue.Handle rh = cs.reclaimableHandle ; + if (rh != null) { + msg( "connection was reclaimable") ; + rh.remove() ; + } + + try { + conn.close() ; + } catch (IOException exc) { + display( "close threw", exc ) ; + } + } + + // Atomically either get the ConnectionState for conn OR + // create a new one AND put it in the cache + private ConnectionState getConnectionState( C conn ) { + // This should be the only place a CacheEntry is constructed. + ConnectionState result = connectionMap.get( conn ) ; + if (result == null) { + result = new ConnectionState( conn ) ; + connectionMap.put( conn, result ) ; + totalIdle++ ; + } + + return result ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/InboundConnectionCacheImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/InboundConnectionCacheImpl.java new file mode 100644 index 000000000..0a6bdc563 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/InboundConnectionCacheImpl.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + +import java.io.IOException ; + +import java.util.concurrent.ConcurrentMap ; +import java.util.concurrent.ConcurrentHashMap ; + +import java.util.concurrent.atomic.AtomicInteger ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import com.sun.corba.ee.spi.transport.connection.InboundConnectionCache ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +/** Manage connections that are initiated from another VM. + * Connections are reclaimed when + * they are no longer in use and there are too many connections open. + *

    + * A connection basically represents some sort of communication channel, but + * few requirements are placed on the connection. Basically the ability to + * close a connection is required in order for reclamation to work. + *

    + * + * @author Ken Cavanaugh + */ +@Transport +public final class InboundConnectionCacheImpl + extends ConnectionCacheNonBlockingBase + implements InboundConnectionCache { + + private final ConcurrentMap> connectionMap ; + + protected String thisClassName() { + return "InboundConnectionCacheImpl" ; + } + + private static final class ConnectionState { + final C connection ; // Connection of the + // ConnectionState + final AtomicInteger busyCount ; // Number of calls to + // get without release + final AtomicInteger expectedResponseCount ; // Number of expected + // responses not yet + // received + + // At all times, a connection is either on the busy or idle queue in + // its ConnectionEntry, and so only the corresponding handle is + // non-null. If idleHandle is non-null, reclaimableHandle may also + // be non-null if the Connection is also on the + // reclaimableConnections queue. + ConcurrentQueue.Handle reclaimableHandle ; // non-null iff connection + // is not in use and has no + // outstanding requests + + ConnectionState( final C conn ) { + this.connection = conn ; + + busyCount = new AtomicInteger() ; + expectedResponseCount = new AtomicInteger() ; + reclaimableHandle = null ; + } + } + + public InboundConnectionCacheImpl( final String cacheType, + final int highWaterMark, final int numberToReclaim, long ttl ) { + + super( cacheType, highWaterMark, numberToReclaim, ttl ) ; + + this.connectionMap = + new ConcurrentHashMap>() ; + } + + // We do not need to define equals or hashCode for this class. + + public void requestReceived( final C conn ) { + ConnectionState cs = getConnectionState( conn ) ; + + final int totalConnections = totalBusy.get() + totalIdle.get() ; + if (totalConnections > highWaterMark()) + reclaim() ; + + ConcurrentQueue.Handle reclaimHandle = cs.reclaimableHandle ; + if (reclaimHandle != null) + reclaimHandle.remove() ; + + int count = cs.busyCount.getAndIncrement() ; + if (count == 0) { + totalIdle.decrementAndGet() ; + totalBusy.incrementAndGet() ; + } + } + + @InfoMethod + private void msg( String m ) {} + + @InfoMethod + private void display( String m, Object value ) {} + + @Transport + public void requestProcessed( final C conn, + final int numResponsesExpected ) { + + final ConnectionState cs = connectionMap.get( conn ) ; + + if (cs == null) { + msg( "connection was closed"); + return ; + } else { + int numResp = cs.expectedResponseCount.addAndGet( + numResponsesExpected ) ; + int numBusy = cs.busyCount.decrementAndGet() ; + + display( "numResp", numResp ) ; + display( "numBusy", numBusy ) ; + + if (numBusy == 0) { + totalBusy.decrementAndGet() ; + totalIdle.incrementAndGet() ; + + if (numResp == 0) { + display( "queing reclaimalbe connection", conn ) ; + cs.reclaimableHandle = + reclaimableConnections.offer( conn ) ; + } + } + } + } + + /** Decrement the number of expected responses. When a connection is idle + * and has no expected responses, it can be reclaimed. + */ + @Transport + public void responseSent( final C conn ) { + final ConnectionState cs = connectionMap.get( conn ) ; + final int waitCount = cs.expectedResponseCount.decrementAndGet() ; + if (waitCount == 0) { + cs.reclaimableHandle = reclaimableConnections.offer( conn ) ; + } + } + + /** Close a connection, regardless of whether the connection is busy + * or not. + */ + public void close( final C conn ) { + final ConnectionState cs = connectionMap.remove( conn ) ; + int count = cs.busyCount.get() ; + if (count == 0) + totalIdle.decrementAndGet() ; + else + totalBusy.decrementAndGet() ; + + final ConcurrentQueue.Handle rh = cs.reclaimableHandle ; + if (rh != null) + rh.remove() ; + + try { + conn.close() ; + } catch (IOException exc) { + // XXX log this + } + } + + // Atomically either get the ConnectionState for conn OR + // create a new one AND put it in the cache + private ConnectionState getConnectionState( C conn ) { + // This should be the only place a ConnectionState is constructed. + ConnectionState cs = new ConnectionState( conn ) ; + ConnectionState result = connectionMap.putIfAbsent( conn, cs ) ; + if (result != null) { + totalIdle.incrementAndGet() ; + return result ; + } else { + return cs ; + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundCacheEntry.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundCacheEntry.java new file mode 100644 index 000000000..6015ab692 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundCacheEntry.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + +import java.util.Queue ; +import java.util.Collection ; +import java.util.Collections ; + +import java.util.concurrent.LinkedBlockingQueue ; + +import java.util.concurrent.locks.ReentrantLock ; +import java.util.concurrent.locks.Condition ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import java.util.ArrayList; + +// Represents an entry in the outbound connection cache. +// This version handles normal shareable ContactInfo +// (we also need to handle no share). +@ManagedData +public class OutboundCacheEntry { + private ReentrantLock lock ; + private final Condition waitForPendingConnections ; + + public OutboundCacheEntry( ReentrantLock lock ) { + this.lock = lock ; + waitForPendingConnections = lock.newCondition() ; + } + + final Queue idleConnections = new LinkedBlockingQueue() ; + final Collection idleConnectionsView = + Collections.unmodifiableCollection( idleConnections ) ; + + final Queue busyConnections = new LinkedBlockingQueue() ; + final Collection busyConnectionsView = + Collections.unmodifiableCollection( busyConnections ) ; + + private int pendingConnections = 0 ; + + @Override + public String toString() { + lock.lock() ; + try { + return "OutboundCacheEntry[numIdle=" + idleConnections.size() + + ",numBusy=" + busyConnections.size() + + ",numPending=" + pendingConnections + "]" ; + } finally { + lock.unlock(); + } + } + + @ManagedAttribute + @Description( "list of idle connections") + private Collection idleConnections() { + lock.lock() ; + try { + return new ArrayList( idleConnections ) ; + } finally { + lock.unlock() ; + } + } + + @ManagedAttribute + @Description( "list of idle connections") + private Collection busyConnections() { + lock.lock() ; + try { + return new ArrayList( busyConnections ) ; + } finally { + lock.unlock() ; + } + } + + @ManagedAttribute( id="numIdleConnections" ) + @Description( "Number of idle connections" ) + private int numIdleConnectionsAttribute() { + lock.lock() ; + try { + return idleConnections.size() ; + } finally { + lock.unlock() ; + } + } + + @ManagedAttribute( id="numPendingConnections" ) + @Description( "Number of pending connections" ) + private int numPendingConnectionsAttribute() { + lock.lock() ; + try { + return pendingConnections ; + } finally { + lock.unlock() ; + } + } + + @ManagedAttribute( id="numBusyConnections" ) + @Description( "Number of busy connections" ) + private int numBusyConnectionsAttribute() { + lock.lock() ; + try { + return busyConnections.size() ; + } finally { + lock.unlock() ; + } + } + + public int totalConnections() { + return idleConnections.size() + busyConnections.size() + + pendingConnections ; + } + + public void startConnect() { + pendingConnections++ ; + } + + public void finishConnect() { + pendingConnections-- ; + waitForPendingConnections.signal() ; + } + + public void waitForConnection() { + waitForPendingConnections.awaitUninterruptibly() ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionCacheBlockingImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionCacheBlockingImpl.java new file mode 100644 index 000000000..a44062509 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionCacheBlockingImpl.java @@ -0,0 +1,393 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + +import java.io.IOException ; + +import java.util.Map ; +import java.util.HashMap ; + +import java.util.concurrent.locks.ReentrantLock ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import com.sun.corba.ee.spi.transport.connection.ConnectionFinder ; +import com.sun.corba.ee.spi.transport.connection.ContactInfo ; +import com.sun.corba.ee.spi.transport.connection.OutboundConnectionCache ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueueFactory; +import com.sun.corba.ee.spi.trace.Transport; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Transport +@ManagedObject +@Description( "Outbound connection cache for connections opened by the client" ) +public final class OutboundConnectionCacheBlockingImpl + extends ConnectionCacheBlockingBase + implements OutboundConnectionCache { + + private ReentrantLock lock = new ReentrantLock() ; + + // Configuration data + // XXX we may want this data to be dynamically re-configurable + private final int maxParallelConnections ; // Maximum number of + // connections we will open + // to the same endpoint + + @ManagedAttribute + public int maxParallelConnections() { return maxParallelConnections ; } + + private Map,OutboundCacheEntry> entryMap ; + + @ManagedAttribute( id="cacheEntries" ) + private Map,OutboundCacheEntry> entryMap() { + return new HashMap,OutboundCacheEntry>( entryMap ) ; + } + + private Map> connectionMap ; + + @ManagedAttribute( id="connections" ) + private Map> connectionMap() { + return new HashMap>( connectionMap ) ; + } + + protected String thisClassName() { + return "OutboundConnectionCacheBlockingImpl" ; + } + + public OutboundConnectionCacheBlockingImpl( final String cacheType, + final int highWaterMark, final int numberToReclaim, + final int maxParallelConnections, final long ttl ) { + + super( cacheType, highWaterMark, numberToReclaim, ttl ) ; + + if (maxParallelConnections < 1) + throw new IllegalArgumentException( + "maxParallelConnections must be > 0" ) ; + + this.maxParallelConnections = maxParallelConnections ; + + this.entryMap = + new HashMap,OutboundCacheEntry>() ; + this.connectionMap = new HashMap>() ; + this.reclaimableConnections = + ConcurrentQueueFactory.makeConcurrentQueue( ttl ) ; + } + + public boolean canCreateNewConnection( ContactInfo cinfo ) { + lock.lock() ; + try { + OutboundCacheEntry entry = entryMap.get( cinfo ) ; + if (entry == null) + return true ; + + return internalCanCreateNewConnection( entry ) ; + } finally { + lock.unlock() ; + } + } + + private boolean internalCanCreateNewConnection( + final OutboundCacheEntry entry ) { + lock.lock() ; + try { + final boolean createNewConnection = (entry.totalConnections() == 0) || + ((numberOfConnections() < highWaterMark()) && + (entry.totalConnections() < maxParallelConnections)) ; + + return createNewConnection ; + } finally { + lock.unlock() ; + } + } + + public C get( final ContactInfo cinfo) throws IOException { + return get( cinfo, null ) ; + } + + @InfoMethod + private void msg( String m ) {} + + @InfoMethod + private void display( String m, Object value ) {} + + @Transport + public C get( final ContactInfo cinfo, + final ConnectionFinder finder ) throws IOException { + lock.lock() ; + C result = null ; + + try { + while (true) { + final OutboundCacheEntry entry = getEntry( cinfo ) ; + + if (finder != null) { + msg( "calling finder to get a connection" ) ; + + entry.startConnect() ; + // Finder may block, especially on opening a new + // connection, so we can't hold the lock during the + // finder call. + lock.unlock() ; + try { + result = finder.find( cinfo, + entry.idleConnectionsView, + entry.busyConnectionsView ) ; + } finally { + lock.lock() ; + entry.finishConnect() ; + } + + if (result != null) { + display( "finder got connection", result ) ; + } + } + + if (result == null) { + result = entry.idleConnections.poll() ; + } + if (result == null) { + result = tryNewConnection( entry, cinfo ) ; + } + if (result == null) { + result = entry.busyConnections.poll() ; + } + + if (result == null) { + msg( "No connection available: " + + "awaiting a pending connection" ) ; + entry.waitForConnection() ; + continue ; + } else { + OutboundConnectionState cs = getConnectionState( + cinfo, entry, result ) ; + + if (cs.isBusy()) { + // Nothing to do in this case + } else if (cs.isIdle()) { + totalBusy++ ; + decrementTotalIdle() ; + } else { // state is NEW + totalBusy++ ; + } + + cs.acquire() ; + break ; + } + } + } finally { + display( "totalIdle", totalIdle ) ; + display( "totalBusy", totalBusy ) ; + lock.unlock() ; + } + + return result ; + } + + @Transport + private OutboundCacheEntry getEntry( final ContactInfo cinfo + ) throws IOException { + + OutboundCacheEntry result = null ; + // This is the only place a OutboundCacheEntry is constructed. + result = entryMap.get( cinfo ) ; + if (result == null) { + result = new OutboundCacheEntry( lock ) ; + display( "creating new OutboundCacheEntry", result ) ; + entryMap.put( cinfo, result ) ; + } else { + display( "re-using existing OutboundCacheEntry", result ) ; + } + + return result ; + } + + // Note that tryNewConnection will ALWAYS create a new connection if + // no connection currently exists. + @Transport + private C tryNewConnection( final OutboundCacheEntry entry, + final ContactInfo cinfo ) throws IOException { + + C conn = null ; + if (internalCanCreateNewConnection(entry)) { + // If this throws an exception just let it + // propagate: let a higher layer handle a + // connection creation failure. + entry.startConnect() ; + lock.unlock() ; + try { + conn = cinfo.createConnection() ; + } finally { + lock.lock() ; + entry.finishConnect() ; + } + } + + return conn ; + } + + @Transport + private OutboundConnectionState getConnectionState( + ContactInfo cinfo, OutboundCacheEntry entry, C conn ) { + lock.lock() ; + + try { + OutboundConnectionState cs = connectionMap.get( conn ) ; + if (cs == null) { + cs = new OutboundConnectionState( cinfo, entry, conn ) ; + display( "creating new OutboundConnectionState ", cs ) ; + connectionMap.put( conn, cs ) ; + } else { + display( "found OutboundConnectionState ", cs ) ; + } + + return cs ; + } finally { + lock.unlock() ; + } + } + + @Transport + public void release( final C conn, + final int numResponsesExpected ) { + lock.lock() ; + OutboundConnectionState cs = null ; + + try { + cs = connectionMap.get( conn ) ; + if (cs == null) { + msg( "connection was already closed" ) ; + return ; + } else { + int numResp = cs.release( numResponsesExpected ) ; + display( "numResponsesExpected", numResponsesExpected ) ; + + if (!cs.isBusy()) { + boolean connectionClosed = false ; + if (numResp == 0) { + connectionClosed = reclaimOrClose( cs, conn ) ; + } + + decrementTotalBusy() ; + + if (!connectionClosed) { + msg( "idle connection queued" ) ; + totalIdle++ ; + } + } + } + } finally { + display( "cs", cs ) ; + display( "totalIdle", totalIdle ) ; + display( "totalBusy", totalBusy ) ; + lock.unlock() ; + } + } + + /** Decrement the number of expected responses. When a connection is idle + * and has no expected responses, it can be reclaimed. + */ + @Transport + public void responseReceived( final C conn ) { + lock.lock() ; + try { + final OutboundConnectionState cs = connectionMap.get( conn ) ; + if (cs == null) { + msg( "response received on closed connection" ) ; + return ; + } + + if (cs.responseReceived()) { + reclaimOrClose( cs, conn ) ; + } + } finally { + lock.unlock() ; + } + } + + // If overflow, close conn and return true, + // otherwise enqueue on reclaimable queue and return false. + @Transport + private boolean reclaimOrClose( OutboundConnectionState cs, + final C conn ) { + + final boolean isOverflow = numberOfConnections() > + highWaterMark() ; + + if (isOverflow) { + msg( "closing overflow connection" ) ; + close( conn ) ; + } else { + msg( "queuing reclaimable connection" ) ; + cs.setReclaimableHandle( + reclaimableConnections.offer( conn ) ) ; + } + + return isOverflow ; + } + + + /** Close a connection, regardless of whether the connection is busy + * or not. + */ + @Transport + public void close( final C conn ) { + lock.lock() ; + try { + final OutboundConnectionState cs = connectionMap.remove( conn ) ; + if (cs == null) { + msg( "connection was already closed" ) ; + return ; + } + display( "cs", cs ) ; + + if (cs.isBusy()) { + msg( "connection removed from busy connections" ) ; + decrementTotalBusy() ; + } else if (cs.isIdle()) { + msg( "connection removed from idle connections" ) ; + decrementTotalIdle() ; + } + try { + cs.close(); + } catch (IOException ex) { + // ignore this + } + } finally { + lock.unlock() ; + } + } + + @Transport + private void decrementTotalIdle() { + if (totalIdle > 0) { + totalIdle-- ; + } else { + msg( "ERROR: was already 0!" ) ; + } + } + + @Transport + private void decrementTotalBusy() { + if (totalBusy > 0) { + totalBusy-- ; + } else { + msg( "ERROR: count was already 0!" ) ; + } + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionCacheImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionCacheImpl.java new file mode 100644 index 000000000..45450ce7e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionCacheImpl.java @@ -0,0 +1,351 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + +import java.io.IOException ; + +import java.util.concurrent.ConcurrentMap ; +import java.util.concurrent.ConcurrentHashMap ; + +import java.util.concurrent.atomic.AtomicInteger ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import com.sun.corba.ee.spi.transport.connection.ConnectionFinder ; +import com.sun.corba.ee.spi.transport.connection.ContactInfo ; +import com.sun.corba.ee.spi.transport.connection.OutboundConnectionCache ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue; +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueueFactory; + +/** Manage connections that are initiated from this VM. Connections are managed + * by a get/release mechanism and cached by the ContactInfo used to create them. + * For efficiency, multiple connections (referred to as parallel connections) + * may be created using the same ContactInfo. Connections are reclaimed when + * they are no longer in use and there are too many connections open. + *

    + * A connection is obtained through the get method, and released back to the + * cache through the release method. Note that a connection that is released + * may still be expecting a response, in which case the connection is NOT + * eligible for reclamation. If a connection is released to the cache while + * expecting a response, the connection must me made available for reclamation + * by calling responseReceived. + * + * XXX Should a get/release cycle expect at most one response? + * Should it support more than one response? + * Are there cases where we don't know in advance how many responses + * are expected? + *

    + * A connection basically represents some sort of communication channel, but + * few requirements are placed on the connection. Basically the ability to + * close a connection is required in order for reclamation to work. + *

    + * Also we need the ContactInfo as a factory for the Connection. + * + * @author Ken Cavanaugh + */ +public final class OutboundConnectionCacheImpl + extends ConnectionCacheNonBlockingBase + implements OutboundConnectionCache { + + private final int maxParallelConnections ; // Maximum number of connections + // we will open to the same + // endpoint + + private final ConcurrentMap,CacheEntry> entryMap ; + private final ConcurrentMap> connectionMap ; + + public int maxParallelConnections() { + return maxParallelConnections ; + } + + protected String thisClassName() { + return "OutboundConnectionCacheImpl" ; + } + + private static final class ConnectionState { + final ContactInfo cinfo ; // ContactInfo used to + // create this Connection + final C connection ; // Connection of the + // ConnectionState + final CacheEntry entry ; // This Connection's + // CacheEntry + + final AtomicInteger busyCount ; // Number of calls to + // get without release + final AtomicInteger expectedResponseCount ; // Number of expected + // responses not yet + // received + + // At all times, a connection is either on the busy or idle queue in + // its ConnectionEntry, and so only the corresponding handle is + // non-null. If idleHandle is non-null, reclaimableHandle may also + // be non-null if the Connection is also on the + // reclaimableConnections queue. + volatile ConcurrentQueue.Handle reclaimableHandle ; // non-null iff connection + // is not in use and has no + // outstanding requests + volatile ConcurrentQueue.Handle idleHandle ; // non-null iff connection + // is not in use + volatile ConcurrentQueue.Handle busyHandle ; // non-null iff connection + // is in use + + ConnectionState( final ContactInfo cinfo, final CacheEntry entry, + final C conn ) { + + this.cinfo = cinfo ; + this.connection = conn ; + this.entry = entry ; + + busyCount = new AtomicInteger() ; + expectedResponseCount = new AtomicInteger() ; + reclaimableHandle = null ; + idleHandle = null ; + busyHandle = null ; + } + } + + // Represents an entry in the outbound connection cache. + // This version handles normal shareable ContactInfo + // (we also need to handle no share). + private static final class CacheEntry { + final ConcurrentQueue idleConnections = + ConcurrentQueueFactory.makeBlockingConcurrentQueue(0) ; + + final ConcurrentQueue busyConnections = + ConcurrentQueueFactory.makeBlockingConcurrentQueue(0) ; + + public int totalConnections() { + return idleConnections.size() + busyConnections.size() ; + } + } + + public OutboundConnectionCacheImpl( final String cacheType, + final int highWaterMark, final int numberToReclaim, + final int maxParallelConnections, final long ttl ) { + + super( cacheType, highWaterMark, numberToReclaim, ttl ) ; + this.maxParallelConnections = maxParallelConnections ; + + this.entryMap = + new ConcurrentHashMap,CacheEntry>() ; + this.connectionMap = + new ConcurrentHashMap>() ; + this.reclaimableConnections = + ConcurrentQueueFactory.makeBlockingConcurrentQueue( ttl ) ; + } + + // We do not need to define equals or hashCode for this class. + + public C get( final ContactInfo cinfo, + ConnectionFinder finder ) throws IOException { + + return get( cinfo ) ; + } + + public C get( final ContactInfo cinfo ) throws IOException { + final CacheEntry entry = getEntry( cinfo ) ; + C result = null ; + + final int totalConnections = totalBusy.get() + totalIdle.get() ; + if (totalConnections >= highWaterMark()) + reclaim() ; + + do { + result = entry.idleConnections.poll().value() ; + if (result == null) { + if (canCreateNewConnection( entry )) { + // If this throws an exception just let it + // propagate: let a higher layer handle a + // connection creation failure. + result = cinfo.createConnection() ; + + final ConnectionState cs = new ConnectionState( cinfo, + entry, result ) ; + connectionMap.put( result, cs ) ; + + // Make sure this connection is busy: it is + // available to other get calls as soon as + // it is added to the busy queue. For this reason we + // must increment busyCount BEFORE we add the result + // to the entry busy queue. + cs.busyCount.incrementAndGet() ; + entry.busyConnections.offer( result ) ; + totalBusy.incrementAndGet() ; + } else { + // use a busy connection, move to end of busyConnections + // to indicate that the connection has been used recently. + + result = entry.busyConnections.poll().value() ; + if (result != null) { + entry.busyConnections.offer( result ) ; + } + } + } else { // got result from idlConnections; update queues and counts + final ConnectionState cs = connectionMap.get( result ) ; + if (cs == null) { + // Connection was closed, so we can't use it + result = null ; + } else { + final ConcurrentQueue.Handle handle = cs.reclaimableHandle ; + if (handle != null) { + if (handle.remove()) { + totalIdle.decrementAndGet() ; + totalBusy.incrementAndGet() ; + entry.busyConnections.offer( result ) ; + } else { + // another thread closed this connection: try again + result = null ; + } + } + } + } + } while (result == null) ; + + return result ; + } + + public void release( final C conn, final int numResponsesExpected ) { + try { + final ConnectionState cs = connectionMap.get( conn ) ; + + if (cs == null) { + return ; + } else { + int numResp = cs.expectedResponseCount.addAndGet( + numResponsesExpected ) ; + int numBusy = cs.busyCount.decrementAndGet() ; + + if (numBusy == 0) { + final ConcurrentQueue.Handle busyHandle = cs.busyHandle ; + final CacheEntry entry = cs.entry ; + boolean wasOnBusy = false ; + if (busyHandle != null) + wasOnBusy = busyHandle.remove() ; + + if (wasOnBusy) { + // At this point, it is possible that we have removed a + // busy connection from the busy queue, because the + // connection became busy again between the + // decrementAndGet call and the remove call. But, now + // that the entry is NOT on the busy or idle queues + // (because a connection is + // never on both queues at the same time), + // it cannot again change state. + + if (cs.busyCount.get() > 0) { + cs.busyHandle = entry.busyConnections.offer( conn ) ; + } else { + // If the connection does not have waiters, put it on + // the global idle queue. + // + // This is probably unlikely here, because + // release usually requires some response before + // the connection is eligible for reclamation. + if (cs.expectedResponseCount.get() == 0) { + cs.reclaimableHandle = + reclaimableConnections.offer( conn ) ; + totalBusy.decrementAndGet() ; + } + + cs.idleHandle = entry.idleConnections.offer( conn ) ; + } + } + } + } + } finally { + } + } + + /** Decrement the number of expected responses. When a connection is idle + * and has no expected responses, it can be reclaimed. + */ + public void responseReceived( final C conn ) { + final ConnectionState cs = connectionMap.get( conn ) ; + if (cs == null) { + return ; + } + + final ConcurrentQueue.Handle idleHandle = cs.idleHandle ; + final CacheEntry entry = cs.entry ; + final int waitCount = cs.expectedResponseCount.decrementAndGet() ; + if (waitCount == 0) { + boolean wasOnIdle = false ; + if (cs != null) + wasOnIdle = cs.idleHandle.remove() ; + + if (wasOnIdle) + cs.reclaimableHandle = reclaimableConnections.offer( conn ) ; + } + } + + /** Close a connection, regardless of whether the connection is busy + * or not. + */ + public void close( final C conn ) { + final ConnectionState cs = connectionMap.remove( conn ) ; + if (cs == null) { + return ; + } + + final CacheEntry entry = entryMap.remove( cs.cinfo ) ; + + final ConcurrentQueue.Handle rh = cs.reclaimableHandle ; + if (rh != null) + rh.remove() ; + + final ConcurrentQueue.Handle bh = cs.busyHandle ; + if (bh != null) + bh.remove() ; + + final ConcurrentQueue.Handle ih = cs.idleHandle ; + if (ih != null) + ih.remove() ; + + try { + conn.close() ; + } catch (IOException exc) { + // XXX log this + } + } + + // Atomically either get the entry for ContactInfo OR + // create a new one AND put it in the cache + private CacheEntry getEntry( ContactInfo cinfo ) { + // This should be the only place a CacheEntry is constructed. + CacheEntry entry = new CacheEntry() ; + CacheEntry result = entryMap.putIfAbsent( cinfo, entry ) ; + if (result != null) + return result ; + else + return entry ; + } + + // Return true iff the configuration and the current entry support + // creating another connection. Note that it must ALWAYS be + // legal to create a new connection if there is currently no connection. + private boolean canCreateNewConnection( final CacheEntry entry ) { + final int totalConnections = totalBusy.get() + totalIdle.get() ; + final int totalConnectionsInEntry = entry.totalConnections() ; + return (totalConnectionsInEntry == 0) || + ((totalConnections < highWaterMark()) && + (totalConnectionsInEntry < maxParallelConnections)) ; + } + + public boolean canCreateNewConnection( final ContactInfo cinfo ) { + final CacheEntry entry = entryMap.get( cinfo ) ; + if (entry == null) + return true ; + + return canCreateNewConnection( entry ) ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionState.java b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionState.java new file mode 100644 index 000000000..7955530d7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/transport/connection/OutboundConnectionState.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport.connection; + +import java.io.IOException ; + +import com.sun.corba.ee.spi.transport.connection.Connection ; +import com.sun.corba.ee.spi.transport.connection.ContactInfo ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue ; +import com.sun.corba.ee.spi.trace.Transport; +import org.glassfish.gmbal.Description; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; + +@Transport +@ManagedData +public class OutboundConnectionState { +// The real state of the connection + private enum ConnectionStateValue { NEW, BUSY, IDLE } + + private ConnectionStateValue csv ; // Indicates state of connection + + final ContactInfo cinfo ; // ContactInfo used to create this + // Connection + final C connection ; // Connection of the ConnectionState + // + final OutboundCacheEntry entry ; // This Connection's OutboundCacheEntry + + private int busyCount ; // Number of calls to get without release + + int expectedResponseCount ; // Number of expected responses not yet + // received + + // At all times, a connection is either on the busy or idle queue in + // its ConnectionEntry. If the connection is on the idle queue, + // reclaimableHandle may also be non-null if the Connection is also on + // the reclaimableConnections queue. + ConcurrentQueue.Handle reclaimableHandle ; // non-null iff + // connection is not + // in use and has no + // outstanding requests + + public String toString() { + return "OutboundConnectionState[csv=" + csv + + ",cinfo=" + cinfo + + ",connection=" + connection + + ",busyCount=" + busyCount + + ",expectedResponceCount=" + expectedResponseCount + "]" ; + } + +// State exposed as managed attributes + @ManagedAttribute + @Description( "The current state of this connection") + private synchronized ConnectionStateValue state() { return csv ; } + + @ManagedAttribute + @Description( "The contactInfo used to create this connection") + private synchronized ContactInfo contactInfo() { return cinfo ; } + + @ManagedAttribute + @Description( "The underlying connection for this ConnectionState") + private synchronized C connection() { return connection ; } + + @ManagedAttribute + private synchronized OutboundCacheEntry cacheEntry() { return entry ; } + + @ManagedAttribute + private synchronized int busyCount() { return busyCount ; } + + @ManagedAttribute + private synchronized int expectedResponseCount() { + return expectedResponseCount ; + } + + @ManagedAttribute + public synchronized boolean isReclaimable() { + return reclaimableHandle != null ; + } + + public OutboundConnectionState( final ContactInfo cinfo, + final OutboundCacheEntry entry, final C conn ) { + + this.csv = ConnectionStateValue.NEW ; + this.cinfo = cinfo ; + this.connection = conn ; + this.entry = entry ; + + busyCount = 0 ; + expectedResponseCount = 0 ; + reclaimableHandle = null ; + } + +// Methods used in OutboundConnectionCacheBlockingImpl + + public synchronized boolean isBusy() { + return csv == ConnectionStateValue.BUSY ; + } + + public synchronized boolean isIdle() { + return csv == ConnectionStateValue.IDLE ; + } + + // Mark this connection as being busy, and increment + // busyCount. + @Transport + public synchronized void acquire() { + if (busyCount == 0) { + entry.idleConnections.remove( connection ) ; + removeFromReclaim() ; + csv = ConnectionStateValue.BUSY ; + } else { + // Remove from busy queue so we can add it + // back to LRU end later. + entry.busyConnections.remove( connection ) ; + } + + busyCount++ ; + entry.busyConnections.offer( connection ) ; + } + + public synchronized void setReclaimableHandle( + ConcurrentQueue.Handle handle ) { + reclaimableHandle = handle ; + } + + @InfoMethod + private void msg( String m ) {} + + @InfoMethod + private void display( String m, Object value ) {} + + // Decrement busyCount, and move to IDLE if busyCount is 0. + // Returns total number of expected responses + @Transport + public synchronized int release( int numResponsesExpected ) { + expectedResponseCount += numResponsesExpected ; + busyCount-- ; + if (busyCount < 0) { + msg( "ERROR: numBusy is <0!" ) ; + } + + if (busyCount == 0) { + csv = ConnectionStateValue.IDLE ; + boolean wasOnBusy = entry.busyConnections.remove( connection ) ; + if (!wasOnBusy) { + msg( "connection not on busy queue, should have been" ) ; + } + entry.idleConnections.offer( connection ) ; + } + + display( "expectedResponseCount", expectedResponseCount ) ; + display( "busyCount", busyCount ) ; + + return expectedResponseCount ; + } + + // Returns true iff the connection is idle and reclaimable + @Transport + public synchronized boolean responseReceived() { + boolean result = false ; + --expectedResponseCount ; + display( "expectedResponseCount", expectedResponseCount ) ; + + if (expectedResponseCount < 0) { + msg( "ERROR: expectedResponseCount<0!" ) ; + expectedResponseCount = 0 ; + } + + result = (expectedResponseCount == 0) && (busyCount == 0) ; + + return result ; + } + + @Transport + public synchronized void close() throws IOException { + removeFromReclaim() ; + + if (csv == ConnectionStateValue.IDLE) { + entry.idleConnections.remove( connection ) ; + } else if (csv == ConnectionStateValue.BUSY) { + entry.busyConnections.remove( connection ) ; + } + + csv = ConnectionStateValue.NEW ; + busyCount = 0 ; + expectedResponseCount = 0 ; + + connection.close() ; + } + + @Transport + private void removeFromReclaim() { + if (reclaimableHandle != null) { + if (!reclaimableHandle.remove()) { + display( "result was not on reclaimable Q", cinfo ) ; + } + reclaimableHandle = null ; + } + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/txpoa/TSIdentificationImpl.java b/orbmain/src/main/java/com/sun/corba/ee/impl/txpoa/TSIdentificationImpl.java new file mode 100644 index 000000000..253b7b211 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/txpoa/TSIdentificationImpl.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.txpoa; + +import org.omg.CORBA.TSIdentification; + +public class TSIdentificationImpl extends org.omg.CORBA.LocalObject + implements TSIdentification { + + private org.omg.CosTSPortability.Sender sender=null; + private org.omg.CosTSPortability.Receiver receiver=null; + + /** identify_sender is called by the OTS during initialization + to register its Sender callback interface with the ORB. + identify_sender may throw a AlreadyIdentified exception if + the registration has already been done previously. + */ + public void + identify_sender(org.omg.CosTSPortability.Sender senderOTS) + throws org.omg.CORBA.TSIdentificationPackage.NotAvailable, + org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified + { + if ( sender == null ) + sender = senderOTS; + else + throw new org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified(); + } + + + /** identify_receiver is called by the OTS during initialization + to register its Receiver callback interface with the ORB. + identify_receiver may throw a AlreadyIdentified exception if + the registration has already been done previously. + */ + public void + identify_receiver(org.omg.CosTSPortability.Receiver receiverOTS) + throws org.omg.CORBA.TSIdentificationPackage.NotAvailable, + org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified + { + if ( receiver == null ) + receiver = receiverOTS; + else + throw new org.omg.CORBA.TSIdentificationPackage.AlreadyIdentified(); + } + + + /** getSender is not defined in the OTS spec. It is just a convenience + method to allow the ORB to access the Sender subsequent to + initialization. + */ + public org.omg.CosTSPortability.Sender + getSender() + { + return sender; + } + + /** getReceiver is not defined in the OTS spec. It is just a convenience + method to allow the ORB to access the Receiver subsequent to + initialization. + */ + public org.omg.CosTSPortability.Receiver + getReceiver() + { + return receiver; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/JDKBridge.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/JDKBridge.java new file mode 100644 index 000000000..a8f82b8cb --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/JDKBridge.java @@ -0,0 +1,307 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + + +import java.rmi.server.RMIClassLoader; + +import java.security.AccessController; + +import java.net.MalformedURLException; + +import java.util.Map ; +import java.util.HashMap ; +import java.util.WeakHashMap ; +import java.util.logging.Logger; +import java.util.logging.Level; + +import java.lang.ref.SoftReference ; +import java.lang.ref.ReferenceQueue ; + +import com.sun.corba.ee.org.omg.CORBA.GetPropertyAction; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** + * Utility methods for doing various method calls which are used + * by multiple classes + */ +public class JDKBridge { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + private static Logger logger = Logger.getLogger(JDKBridge.class.getName()) ; + + /** + * Get local codebase System property (java.rmi.server.codebase). + * May be null or a space separated array of URLS. + */ + public static String getLocalCodebase () { + return localCodebase; + } + + /** + * Return true if the system property "java.rmi.server.useCodebaseOnly" + * is set, false otherwise. + */ + public static boolean useCodebaseOnly () { + return useCodebaseOnly; + } + + // Building caches for loadClass + // + // There are two cases: + // 1. loader == null + // In this case, we need Maps remoteCodeBase -> className -> SoftReference to Class + // 2. loader != null, + // In this case, we need Maps (weak) loader -> className -> SoftReference to Class + // + // We might also want to cache not found results. This can be represented by: + // 1. Map remoteCodeBase -> Set classname + // 2. Map (weak) loader -> Set classname + // But this is assuming that if a ClassLoader cannot load a class at one time, it also cannot + // load it later! That is not always true, e.g. a new class file is added to a directory. + // Best to avoid this! + // + // We reclaim soft references using a ReferenceQueue. + + private static class LoadClassCache { + private static Map> nullLoaderMap = + new HashMap>() ; + private static Map> nonNullLoaderMap = + new WeakHashMap>() ; + private static ReferenceQueue queue = + new ReferenceQueue() ; + + private static class Entry extends SoftReference { + String codeBase ; + ClassLoader loader ; + + public Entry( Class cls, String codeBase, ClassLoader loader ) { + super( cls, queue ) ; + this.codeBase = codeBase ; + this.loader = loader ; + } + + @Override + public void clear() { + codeBase = null ; + loader = null ; + } + } + + private static void checkQueue() { + while (true) { + Object obj = queue.poll() ; + if (obj == null) { + return ; + } else { + Entry entry = (Entry)obj ; + String className = entry.get().getName() ; + if (entry.loader == null) { + Map mse = nullLoaderMap.get( entry.codeBase ) ; + mse.remove( className ) ; + if (mse.isEmpty()) { + nullLoaderMap.remove( entry.codeBase ) ; + } + } else { + Map mse = nonNullLoaderMap.get( entry.loader ) ; + mse.remove( className ) ; + if (mse.isEmpty()) { + nonNullLoaderMap.remove( entry.loader ) ; + } + } + entry.clear() ; + } + } + } + + /** Returns Class if it is still known to be the resolution of the parameters, + * throws ClassNotFoundException if it is still known that the class + * can NOT be resolved, or return null if nothing is known. + */ + public static synchronized Class get( String className, String remoteCodebase, + ClassLoader loader ) throws ClassNotFoundException { + + checkQueue() ; + + Map scm ; + if (loader == null) { + scm = nullLoaderMap.get( remoteCodebase ) ; + } else { + scm = nonNullLoaderMap.get( loader ) ; + } + + Class cls = null ; + if (scm != null) { + Entry entry = scm.get( className ) ; + if (entry != null) + cls = entry.get() ; + } + + return cls ; + } + + public static synchronized void put( String className, String remoteCodebase, + ClassLoader loader, Class cls ) { + + checkQueue() ; + + Map scm ; + if (loader == null) { + scm = nullLoaderMap.get( remoteCodebase ) ; + if (scm == null) { + scm = new HashMap() ; + nullLoaderMap.put( remoteCodebase, scm ) ; + } + } else { + scm = nonNullLoaderMap.get( loader ) ; + if (scm == null) { + scm = new HashMap() ; + nonNullLoaderMap.put( loader, scm ) ; + } + } + + scm.put( className, new Entry( cls, remoteCodebase, loader ) ) ; + } + } + + /** + * Returns a class instance for the specified class. + * @param className the name of the class + * @param remoteCodebase a space-separated array of urls at which + * the class might be found. May be null. + * @param loader a ClassLoader who may be used to + * load the class if all other methods fail. + * @return the Class object representing the loaded class. + * @exception throws ClassNotFoundException if class cannot be loaded. + */ + public static Class loadClass (String className, + String remoteCodebase, + ClassLoader loader) + throws ClassNotFoundException { + + // XXX GFv3 Disable use of the cache for now: + // + // it is caching different classes incorrectly that have + // the same name, but different ClassLoaders. + Class cls = null ; + // NOCACHE LoadClassCache.get( className, remoteCodebase, loader ) ; + if (cls == null) { + if (loader == null) { + cls = loadClassM(className,remoteCodebase,useCodebaseOnly); + } else { + try { + cls = loadClassM(className,remoteCodebase,useCodebaseOnly); + } catch (ClassNotFoundException e) { + // GLASSFISH-18986 [PERF] Failed ClassLoading consuming too much logging time + // limit the logger calls to finest level only + if (logger.isLoggable(Level.FINE)) { + wrapper.classNotFoundInCodebase( className, remoteCodebase ) ; + } + cls = loader.loadClass(className); + } + } + // NOCACHE LoadClassCache.put( className, remoteCodebase, loader, cls ) ; + } + + return cls ; + } + + /** + * Returns a class instance for the specified class. + * @param className the name of the class + * @param remoteCodebase a space-separated array of urls at which + * the class might be found. May be null. + * @return the Class object representing the loaded class. + * @exception throws ClassNotFoundException if class cannot be loaded. + */ + public static Class loadClass (String className, + String remoteCodebase) + throws ClassNotFoundException { + return loadClass(className,remoteCodebase,null); + } + + /** + * Returns a class instance for the specified class. + * @param className the name of the class + * @return the Class object representing the loaded class. + * @exception throws ClassNotFoundException if class cannot be loaded. + */ + public static Class loadClass (String className) + throws ClassNotFoundException { + return loadClass(className,null,null); + } + + private static final String LOCAL_CODEBASE_KEY = "java.rmi.server.codebase"; + private static final String USE_CODEBASE_ONLY_KEY = "java.rmi.server.useCodebaseOnly"; + private static String localCodebase = null; + private static boolean useCodebaseOnly; + + static { + setCodebaseProperties(); + } + + /** + * Set the codebase and useCodebaseOnly properties. This is public + * only for test code. + */ + public static synchronized void setCodebaseProperties () { + String prop = (String)AccessController.doPrivileged( + new GetPropertyAction(LOCAL_CODEBASE_KEY)); + + if (prop != null && prop.trim().length() > 0) { + localCodebase = prop; + } + + prop = (String)AccessController.doPrivileged( + new GetPropertyAction(USE_CODEBASE_ONLY_KEY)); + + if (prop != null && prop.trim().length() > 0) { + useCodebaseOnly = Boolean.valueOf(prop).booleanValue(); + } + } + + /** + * Set the default code base. This method is here only + * for test code. + */ + public static synchronized void setLocalCodebase(String codebase) { + localCodebase = codebase; + } + + private static Class loadClassM (String className, String remoteCodebase, + boolean useCodebaseOnly) throws ClassNotFoundException { + + try { + return JDKClassLoader.loadClass(null,className); + } catch (ClassNotFoundException e) { + // GLASSFISH-18986 [PERF] Failed ClassLoading consuming too much logging time + // limit the logger calls to finest level only + if (logger.isLoggable(Level.FINE)) { + wrapper.classNotFoundInJDKClassLoader( className, e ) ; + } + } + + try { + if (!useCodebaseOnly && remoteCodebase != null) { + return RMIClassLoader.loadClass(remoteCodebase, + className); + } else { + return RMIClassLoader.loadClass(className); + } + } catch (MalformedURLException e) { + className = className + ": " + e.toString(); + } + + throw new ClassNotFoundException(className); + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/JDKClassLoader.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/JDKClassLoader.java new file mode 100644 index 000000000..7f326626a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/JDKClassLoader.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + +import org.glassfish.pfl.basic.reflection.Bridge; + +import java.util.Map ; +import java.util.WeakHashMap ; +import java.util.Collections ; + +import java.security.AccessController ; +import java.security.PrivilegedAction ; + +/** + * Utility method for crawling call stack to load class + */ +class JDKClassLoader { + + private static final JDKClassLoaderCache classCache + = new JDKClassLoaderCache(); + + private static final Bridge bridge = + (Bridge)AccessController.doPrivileged( + new PrivilegedAction() { + public Object run() { + return Bridge.get() ; + } + } + ) ; + + static Class loadClass(Class aClass, String className) + throws ClassNotFoundException { + + // Maintain the same error semantics as Class.forName() + if (className == null) { + throw new NullPointerException(); + } + if (className.length() == 0) { + throw new ClassNotFoundException(); + } + + // It would be nice to bypass JDKClassLoader's attempts completely + // if it's known that the latest user defined ClassLoader will + // fail. + // + // Otherwise, we end up calling Class.forName here as well as in + // the next step in JDKBridge. That can take a long time depending + // on the length of the classpath. + + // Note: Looking at the only place in JDKBridge where this code + // is invoked, it is clear that aClass will always be null. + ClassLoader loader; + if (aClass != null) { + loader = aClass.getClassLoader(); + } else { + loader = bridge.getLatestUserDefinedLoader(); + } + // See createKey for a description of what's involved + Object key = classCache.createKey(className, loader); + + if (classCache.knownToFail(key)) { + throw new ClassNotFoundException(className); + } else { + try { + // Loading this class with the call stack + // loader isn't known to fail, so try + // to load it. + return Class.forName(className, false, loader); + } catch(ClassNotFoundException cnfe) { + // Record that we failed to find the class + // with this particular loader. This way, we won't + // waste time looking with this loader, again. + classCache.recordFailure(key); + throw cnfe; + } + } + } + + /** + * Private cache implementation specific to JDKClassLoader. + */ + private static class JDKClassLoaderCache + { + // JDKClassLoader couldn't find the class with the located + // ClassLoader. Note this in our cache so JDKClassLoader + // can abort early next time. + public final void recordFailure(Object key) { + cache.put(key, JDKClassLoaderCache.KNOWN_TO_FAIL); + } + + // Factory for a key (CacheKey is an implementation detail + // of JDKClassLoaderCache). + // + // A key currently consists of the class name as well as + // the latest user defined class loader, so it's fairly + // expensive to create. + public final Object createKey(String className, ClassLoader latestLoader) { + return new CacheKey(className, latestLoader); + } + + // Determine whether or not this combination of class name + // and ClassLoader is known to fail. + public final boolean knownToFail(Object key) { + return cache.get(key) == JDKClassLoaderCache.KNOWN_TO_FAIL; + } + + // Synchronized WeakHashMap + private final Map cache + = Collections.synchronizedMap(new WeakHashMap()); + + // Cache result used to mark the caches when there is + // no way JDKClassLoader could succeed with the given + // key + private static final Object KNOWN_TO_FAIL = new Object(); + + // Key consisting of the class name and the latest + // user defined class loader + private static class CacheKey + { + String className; + ClassLoader loader; + + public CacheKey(String className, ClassLoader loader) { + this.className = className; + this.loader = loader; + } + + // Try to incorporate both class name and loader + // into the hashcode + public int hashCode() { + if (loader == null) + return className.hashCode(); + else + return className.hashCode() ^ loader.hashCode(); + } + + public boolean equals(Object obj) { + try { + + // WeakHashMap may compare null keys + if (obj == null) + return false; + + CacheKey other = (CacheKey)obj; + + // I've made a decision to actually compare the + // loader references. I don't want a case when + // two loader instances override their equals + // methods and only compare code base. + // + // This way, at worst, our performance will + // be slower, but we know we'll do the correct + // loading. + return (className.equals(other.className) && + loader == other.loader); + + } catch (ClassCastException cce) { + return false; + } + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/ORBProperties.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/ORBProperties.java new file mode 100644 index 000000000..469f48a96 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/ORBProperties.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintWriter; + +public class ORBProperties { + + public static final String ORB_CLASS = + "org.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl"; + public static final String ORB_SINGLETON_CLASS = + "org.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton"; + + public static void main (String[] args) { + + try { + // Check if orb.properties exists + String javaHome = System.getProperty("java.home"); + File propFile = new File(javaHome + File.separator + + "lib" + File.separator + + "orb.properties"); + + if (propFile.exists()) + return; + + // Write properties to orb.properties + FileOutputStream out = new FileOutputStream(propFile); + PrintWriter pw = new PrintWriter(out); + + try { + pw.println(ORB_CLASS); + pw.println(ORB_SINGLETON_CLASS); + } finally { + pw.close(); + out.close(); + } + + } catch (Exception ex) { } + + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/PackagePrefixChecker.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/PackagePrefixChecker.java new file mode 100644 index 000000000..0c812f2ca --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/PackagePrefixChecker.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + +import java.io.File; + +/** + * PackagePrefixChecker provides static utility methods for getting package prefixes. + * @author M. Mortazavi + */ + +public final class PackagePrefixChecker +{ + private static final String PACKAGE_PREFIX = "org.omg.stub."; + private static final int PACKAGE_PREFIX_LENGTH = PACKAGE_PREFIX.length() ; + + public static String packagePrefix(){ return PACKAGE_PREFIX;} + + public static String correctPackageName (String p) + { + if (isOffendingPackage(p)) + return PACKAGE_PREFIX+p; + else + return p; + } + + public static boolean isOffendingPackage(String p) + { + return p!=null && (p.equals("java") || p.equals("javax")) ; + } + + public static boolean hasOffendingPrefix(String p) + { + return p.startsWith("java.") || p.startsWith("javax.") ; + } + + public static boolean hasBeenPrefixed(String p) + { + return p.startsWith(PACKAGE_PREFIX) ; + } + + public static String withoutPackagePrefix(String p) + { + if (hasBeenPrefixed(p)) + return p.substring(PACKAGE_PREFIX_LENGTH) ; + else + return p; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/RepositoryId.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/RepositoryId.java new file mode 100644 index 000000000..d3bcad1b8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/RepositoryId.java @@ -0,0 +1,1060 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + +import java.util.Map; +import java.util.WeakHashMap; +import java.util.Hashtable; +import java.util.IdentityHashMap; +import java.io.IOException; +import java.lang.reflect.Method; + +// Imports for using codebase URL to load class +import java.net.MalformedURLException; + +import com.sun.corba.ee.impl.io.ObjectStreamClass; + +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +import com.sun.corba.ee.impl.misc.ClassInfoCache ; +import org.glassfish.pfl.basic.concurrent.SoftCache; + +public class RepositoryId { + + // Legal IDL Identifier characters (1 = legal). Note + // that '.' (2E) is marked as legal even though it is + // not legal in IDL. This allows us to treat a fully + // qualified Java name with '.' package separators + // uniformly, and is safe because that is the only + // legal use of '.' in a Java name. + + public static final byte[] IDL_IDENTIFIER_CHARS = { + + // 0 1 2 3 4 5 6 7 8 9 a b c d e f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 00-0f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 10-1f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,1,0, // 20-2f + 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, // 30-3f + 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 40-4f + 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,1, // 50-5f + 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 60-6f + 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0, // 70-7f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 80-8f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 90-9f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // a0-af + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // b0-bf + 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // c0-cf + 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // d0-df + 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // e0-ef + 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // f0-ff + }; + + + private static final long serialVersionUID = 123456789L; + + private static final String defaultServerURL = (String)JDKBridge.getLocalCodebase() ; + private static final boolean useCodebaseOnly = JDKBridge.useCodebaseOnly() ; + + private static final Map classToRepStr = new WeakHashMap(); + private static final Map classIDLToRepStr = new WeakHashMap(); + private static final Map classSeqToRepStr = new WeakHashMap(); + + private static final Map repStrToByteArray = new IdentityHashMap(); + private static final Map repStrToClass = new SoftCache(); + + private String repId = null; + private boolean isSupportedFormat = true; + private String typeString = null; + private String versionString = null; + private boolean isSequence = false; + private boolean isRMIValueType = false; + private boolean isIDLType = false; + private String completeClassName = null; + private String unqualifiedName = null; + private String definedInId = null; + private Class clazz = null; + private String suid = null, actualSuid = null; + private long suidLong = ObjectStreamClass.kDefaultUID, actualSuidLong = + ObjectStreamClass.kDefaultUID; + + // Repository ID fragments + private static final String kSequenceKeyword = "seq"; + private static final String kValuePrefix = "RMI:"; + private static final String kIDLPrefix = "IDL:"; + private static final String kIDLNamePrefix = "omg.org/"; + private static final String kIDLClassnamePrefix = "org.omg."; + private static final String kSequencePrefix = "["; + private static final String kCORBAPrefix = "CORBA/"; + private static final String kArrayPrefix = kValuePrefix + + kSequencePrefix + kCORBAPrefix; + private static final int kValuePrefixLength = kValuePrefix.length(); + private static final int kIDLPrefixLength = kIDLPrefix.length(); + private static final int kSequencePrefixLength = kSequencePrefix.length(); + private static final String kInterfaceHashCode = ":0000000000000000"; + private static final String kInterfaceOnlyHashStr = "0000000000000000"; + private static final String kExternalizableHashStr = "0000000000000001"; + + // Value tag utility methods and constants + public static final int kInitialValueTag= 0x7fffff00; + public static final int kNoTypeInfo = 0; + public static final int kSingleRepTypeInfo = 0x02; + public static final int kPartialListTypeInfo = 0x06; + public static final int kChunkedMask = 0x08; + public static final int kPreComputed_StandardRMIUnchunked = + RepositoryId.computeValueTag(false, + RepositoryId.kSingleRepTypeInfo, false); + public static final int kPreComputed_CodeBaseRMIUnchunked = + RepositoryId.computeValueTag(true, + RepositoryId.kSingleRepTypeInfo, false); + public static final int kPreComputed_StandardRMIChunked = + RepositoryId.computeValueTag(false, + RepositoryId.kSingleRepTypeInfo, true); + public static final int kPreComputed_CodeBaseRMIChunked = + RepositoryId.computeValueTag(true, + RepositoryId.kSingleRepTypeInfo, true); + + public static final int kPreComputed_StandardRMIUnchunked_NoRep = + RepositoryId.computeValueTag(false, RepositoryId.kNoTypeInfo, false); + public static final int kPreComputed_CodeBaseRMIUnchunked_NoRep = + RepositoryId.computeValueTag(true, RepositoryId.kNoTypeInfo, false); + public static final int kPreComputed_StandardRMIChunked_NoRep = + RepositoryId.computeValueTag(false, RepositoryId.kNoTypeInfo, true); + public static final int kPreComputed_CodeBaseRMIChunked_NoRep = + RepositoryId.computeValueTag(true, RepositoryId.kNoTypeInfo, true); + + // Public, well known repository IDs + + // _REVISIT_ : A table structure with a good search routine for all of this + // would be more efficient and easier to maintain... + + // String + public static final String kWStringValueVersion = "1.0"; + public static final String kWStringValueHash = ":"+kWStringValueVersion; + public static final String kWStringStubValue = "WStringValue"; + public static final String kWStringTypeStr = "omg.org/CORBA/" + + kWStringStubValue; + public static final String kWStringValueRepID = kIDLPrefix + + kWStringTypeStr + kWStringValueHash; + + // Any + public static final String kAnyRepID = kIDLPrefix + "omg.org/CORBA/Any"; + + // Class + public static final String kClassDescValueHash = ":" + + Long.toHexString( + ObjectStreamClass.getActualSerialVersionUID( + javax.rmi.CORBA.ClassDesc.class)).toUpperCase() + + ":" + + Long.toHexString( + ObjectStreamClass.getSerialVersionUID( + javax.rmi.CORBA.ClassDesc.class)).toUpperCase(); + public static final String kClassDescStubValue = "ClassDesc"; + public static final String kClassDescTypeStr = + "javax.rmi.CORBA."+kClassDescStubValue; + public static final String kClassDescValueRepID = + kValuePrefix + kClassDescTypeStr + kClassDescValueHash; + + // Object + public static final String kObjectValueHash = ":1.0"; + public static final String kObjectStubValue = "Object"; + + // Sequence + public static final String kSequenceValueHash = ":1.0"; + public static final String kPrimitiveSequenceValueHash = ":0000000000000000"; + + // Serializable + public static final String kSerializableValueHash = ":1.0"; + public static final String kSerializableStubValue = "Serializable"; + + // Externalizable + public static final String kExternalizableValueHash = ":1.0"; + public static final String kExternalizableStubValue = "Externalizable"; + + // Remote (The empty string is used for java.rmi.Remote) + public static final String kRemoteValueHash = ""; + public static final String kRemoteStubValue = ""; + public static final String kRemoteTypeStr = ""; + public static final String kRemoteValueRepID = ""; + + public static final Hashtable kSpecialArrayTypeStrings = new Hashtable(); + + static { + kSpecialArrayTypeStrings.put("CORBA.WStringValue", + new StringBuffer(java.lang.String.class.getName())); + kSpecialArrayTypeStrings.put("javax.rmi.CORBA.ClassDesc", + new StringBuffer(java.lang.Class.class.getName())); + kSpecialArrayTypeStrings.put("CORBA.Object", + new StringBuffer(java.rmi.Remote.class.getName())); + } + + public static final Hashtable kSpecialCasesRepIDs = new Hashtable(); + + static { + kSpecialCasesRepIDs.put(java.lang.String.class, + kWStringValueRepID); + kSpecialCasesRepIDs.put(java.lang.Class.class, + kClassDescValueRepID); + kSpecialCasesRepIDs.put(java.rmi.Remote.class, + kRemoteValueRepID); + } + + public static final Hashtable kSpecialCasesStubValues = new Hashtable(); + + static { + kSpecialCasesStubValues.put(java.lang.String.class, + kWStringStubValue); + kSpecialCasesStubValues.put(java.lang.Class.class, + kClassDescStubValue); + kSpecialCasesStubValues.put(java.lang.Object.class, + kObjectStubValue); + kSpecialCasesStubValues.put(java.io.Serializable.class, + kSerializableStubValue); + kSpecialCasesStubValues.put(java.io.Externalizable.class, + kExternalizableStubValue); + kSpecialCasesStubValues.put(java.rmi.Remote.class, + kRemoteStubValue); + } + + public static final Hashtable kSpecialCasesVersions = new Hashtable(); + + static { + kSpecialCasesVersions.put(java.lang.String.class, + kWStringValueHash); + kSpecialCasesVersions.put(java.lang.Class.class, + kClassDescValueHash); + kSpecialCasesVersions.put(java.lang.Object.class, + kObjectValueHash); + kSpecialCasesVersions.put(java.io.Serializable.class, + kSerializableValueHash); + kSpecialCasesVersions.put(java.io.Externalizable.class, + kExternalizableValueHash); + kSpecialCasesVersions.put(java.rmi.Remote.class, + kRemoteValueHash); + } + + public static final Hashtable kSpecialCasesClasses = new Hashtable(); + + static { + kSpecialCasesClasses.put(kWStringTypeStr, + java.lang.String.class); + kSpecialCasesClasses.put(kClassDescTypeStr, + java.lang.Class.class); + kSpecialCasesClasses.put(kRemoteTypeStr, + java.rmi.Remote.class); + kSpecialCasesClasses.put("org.omg.CORBA.WStringValue", + java.lang.String.class); + kSpecialCasesClasses.put("javax.rmi.CORBA.ClassDesc", + java.lang.Class.class); + + // 6793820: need to handle classes of primitive types! + kSpecialCasesClasses.put( "boolean", boolean.class ) ; + kSpecialCasesClasses.put( "byte", byte.class ) ; + kSpecialCasesClasses.put( "char", char.class ) ; + kSpecialCasesClasses.put( "short", short.class ) ; + kSpecialCasesClasses.put( "int", int.class ) ; + kSpecialCasesClasses.put( "long", long.class ) ; + kSpecialCasesClasses.put( "float", float.class ) ; + kSpecialCasesClasses.put( "double", double.class ) ; + } + + public static final Hashtable kSpecialCasesArrayPrefix = new Hashtable(); + + static { + kSpecialCasesArrayPrefix.put( java.lang.String.class, + kValuePrefix + kSequencePrefix + kCORBAPrefix); + kSpecialCasesArrayPrefix.put( java.lang.Class.class, + kValuePrefix + kSequencePrefix + "javax/rmi/CORBA/"); + kSpecialCasesArrayPrefix.put( java.lang.Object.class, + kValuePrefix + kSequencePrefix + "java/lang/"); + kSpecialCasesArrayPrefix.put( java.io.Serializable.class, + kValuePrefix + kSequencePrefix + "java/io/"); + kSpecialCasesArrayPrefix.put( java.io.Externalizable.class, + kValuePrefix + kSequencePrefix + "java/io/"); + kSpecialCasesArrayPrefix.put( java.rmi.Remote.class, + kValuePrefix + kSequencePrefix + kCORBAPrefix); + } + + public static final Hashtable kSpecialPrimitives = new Hashtable(); + + static { + kSpecialPrimitives.put("int","long"); + kSpecialPrimitives.put("long","longlong"); + kSpecialPrimitives.put("byte","octet"); + } + + /** + * Used to convert ascii to hex. + */ + private static final byte ASCII_HEX[] = { + (byte)'0', + (byte)'1', + (byte)'2', + (byte)'3', + (byte)'4', + (byte)'5', + (byte)'6', + (byte)'7', + (byte)'8', + (byte)'9', + (byte)'A', + (byte)'B', + (byte)'C', + (byte)'D', + (byte)'E', + (byte)'F', + }; + + + // bug fix for 4328952; to eliminate possibility of overriding this + // in a subclass. + public static final RepositoryIdCache cache = new RepositoryIdCache(); + + // Interface Rep ID Strings + public static final String kjava_rmi_Remote = createForAnyType( + java.rmi.Remote.class); + public static final String korg_omg_CORBA_Object = createForAnyType( + org.omg.CORBA.Object.class); + + // To create a RepositoryID, use code similar to the following: + // RepositoryId.cache.getId( id ); + + RepositoryId(){} + + RepositoryId(String aRepId){ + init(aRepId); + } + + RepositoryId init(String aRepId) { + this.repId = aRepId; + + // Special case for remote + if (aRepId.length() == 0) { + clazz = java.rmi.Remote.class; + typeString = ""; + isRMIValueType = true; + suid = kInterfaceOnlyHashStr; + return this; + } else if (aRepId.equals(kWStringValueRepID)) { + clazz = java.lang.String.class; + typeString = kWStringTypeStr; + isIDLType = true; + // fix where Attempting to obtain a FullValueDescription + // for an RMI value type with a String field causes an exception. + completeClassName = "java.lang.String"; + versionString = kWStringValueVersion; + return this; + } else { + String repId = convertFromISOLatin1(aRepId); + + int firstIndex = repId.indexOf(':') ; + if (firstIndex == -1) + throw new IllegalArgumentException( + "RepositoryId must have the form :" ) ; + int secondIndex = repId.indexOf( ':', firstIndex + 1 ) ; + + if (secondIndex == -1) + versionString = "" ; + else + versionString = repId.substring(secondIndex) ; + + if (repId.startsWith(kIDLPrefix)) { + typeString = + repId.substring(kIDLPrefixLength, + repId.indexOf(':', kIDLPrefixLength)); + isIDLType = true; + + if (typeString.startsWith(kIDLNamePrefix)) + completeClassName = kIDLClassnamePrefix + + typeString.substring( + kIDLNamePrefix.length()).replace('/','.'); + else + completeClassName = typeString.replace('/','.'); + + } else if (repId.startsWith(kValuePrefix)) { + typeString = + repId.substring(kValuePrefixLength, + repId.indexOf(':', kValuePrefixLength)); + isRMIValueType = true; + + if (versionString.indexOf('.') == -1) { + actualSuid = versionString.substring(1); + suid = actualSuid; // default if not explicitly specified + + if (actualSuid.indexOf(':') != -1){ + // we have a declared hash also + int pos = actualSuid.indexOf(':')+1; + // actualSuid = suid.substring(pos); + // suid = suid.substring(0, pos-1); + suid = actualSuid.substring(pos); + actualSuid = actualSuid.substring(0, pos-1); + } + } else { + // _REVISIT_ : Special case version failure ? + } + } else { + isSupportedFormat = false; + typeString = "" ; + } + + if (typeString.startsWith(kSequencePrefix)) { + isSequence = true; + } + + return this; + } + } + + public final String getUnqualifiedName() { + if (unqualifiedName == null){ + String className = getClassName(); + int index = className.lastIndexOf('.'); + if (index == -1){ + unqualifiedName = className; + definedInId = "IDL::1.0"; + } + else { + unqualifiedName = className.substring(index); + definedInId = "IDL:" + + className.substring(0, index).replace('.','/') + ":1.0"; + } + } + + return unqualifiedName; + } + + public final String getDefinedInId() { + if (definedInId == null){ + getUnqualifiedName(); + } + + return definedInId; + } + + public final String getTypeString() { + return typeString; + } + + public final String getVersionString() { + return versionString; + } + + public final String getSerialVersionUID() { + return suid; + } + + public final String getActualSerialVersionUID() { + return actualSuid; + } + public final long getSerialVersionUIDAsLong() { + return suidLong; + } + + public final long getActualSerialVersionUIDAsLong() { + return actualSuidLong; + } + + public final boolean isRMIValueType() { + return isRMIValueType; + } + + public final boolean isIDLType() { + return isIDLType; + } + + public final String getRepositoryId() { + return repId; + } + + public static byte[] getByteArray(String repStr) { + synchronized (repStrToByteArray){ + return (byte[]) repStrToByteArray.get(repStr); + } + } + + public static void setByteArray(String repStr, byte[] repStrBytes) { + synchronized (repStrToByteArray){ + repStrToByteArray.put(repStr, repStrBytes); + } + } + + public final boolean isSequence() { + return isSequence; + } + + public final boolean isSupportedFormat() { + return isSupportedFormat; + } + + // This method will return the classname from the typestring OR + // if the classname turns out to be a special class "pseudo" name, + // then the matching real classname is returned. + public final String getClassName() { + + if (isRMIValueType) + return typeString; + else if (isIDLType) + return completeClassName; + else + return null; + } + + // This method calls getClazzFromType() and falls back to the repStrToClass + // cache if no class was found. It's used where any class matching the + // given repid is an acceptable result. + public final Class getAnyClassFromType() throws ClassNotFoundException { + try { + return getClassFromType(); + } catch (ClassNotFoundException cnfe) { + Class clz = (Class)repStrToClass.get(repId); + if (clz != null) + return clz; + else + throw cnfe; + } + } + + public final Class getClassFromType() + throws ClassNotFoundException { + if (clazz != null) + return clazz; + + Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); + + if (specialCase != null) { + clazz = specialCase; + return specialCase; + } else { + try { + return Util.getInstance().loadClass(getClassName(), + null, null); + } catch(ClassNotFoundException cnfe) { + if (defaultServerURL != null) { + try { + return getClassFromType(defaultServerURL); + } catch(MalformedURLException mue){ + throw cnfe; + } + } else { + throw cnfe; + } + } + } + } + + public final Class getClassFromType(Class expectedType, String codebase) + throws ClassNotFoundException { + if (clazz != null) + return clazz; + + Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); + + if (specialCase != null){ + clazz = specialCase; + return specialCase; + } else { + ClassLoader expectedTypeClassLoader = + (expectedType == null ? null : expectedType.getClassLoader()); + return Utility.loadClassOfType(getClassName(), + codebase, + expectedTypeClassLoader, + expectedType, + expectedTypeClassLoader); + } + + } + + public final Class getClassFromType(String url) + throws ClassNotFoundException, MalformedURLException { + + // 6793820: check special cases BEFORE going to ClassLoader. + if (clazz != null) + return clazz; + + Class specialCase = (Class)kSpecialCasesClasses.get(getClassName()); + + if (specialCase != null) { + clazz = specialCase; + return specialCase; + } else { + return Util.getInstance().loadClass(getClassName(), url, null); + } + } + + public final String toString() { + return repId; + } + + public static boolean useFullValueDescription(Class clazz, + String repositoryID) throws IOException{ + + return useFullValueDescription( clazz, ClassInfoCache.get( clazz ), + repositoryID ) ; + } + + /** + * Checks to see if the FullValueDescription should be retrieved. + * @exception IOException if suids do not match or if the repositoryID + * is not an RMIValueType + */ + public static boolean useFullValueDescription(Class clazz, + ClassInfoCache.ClassInfo cinfo, + String repositoryID) throws IOException{ + + String clazzRepIDStr = createForAnyType(clazz, cinfo ); + + if (clazzRepIDStr.equals(repositoryID)) + return false; + + RepositoryId targetRepid; + RepositoryId clazzRepid; + + synchronized(cache) { + // to avoid race condition where multiple threads could be + // accessing this method, and their access to the cache may + // be interleaved giving unexpected results + + targetRepid = cache.getId(repositoryID); + clazzRepid = cache.getId(clazzRepIDStr); + } + + if ((targetRepid.isRMIValueType()) && (clazzRepid.isRMIValueType())){ + if (!targetRepid.getSerialVersionUID() + .equals(clazzRepid.getSerialVersionUID())) { + + String mssg = + "Mismatched serialization UIDs : Source (Rep. ID" + + clazzRepid + ") = " + + clazzRepid.getSerialVersionUID() + + " whereas Target (Rep. ID " + repositoryID + + ") = " + targetRepid.getSerialVersionUID(); + throw new IOException(mssg); + } else { + return true; + } + } else { + throw new IOException( + "The repository ID is not of an RMI value type (Expected ID = " + + clazzRepIDStr + "; Received ID = " + repositoryID +")"); + } + } + + private static String createHashString(java.lang.Class clazz) { + + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( clazz ) ; + if (cinfo.isInterface() || !cinfo.isASerializable(clazz)) + return kInterfaceHashCode; + + long actualLong = ObjectStreamClass.getActualSerialVersionUID(clazz); + String hash = null; + if (actualLong == 0) + hash = kInterfaceOnlyHashStr; + else if (actualLong == 1) + hash = kExternalizableHashStr; + else + hash = Long.toHexString(actualLong).toUpperCase(); + while(hash.length() < 16) { + hash = "0" + hash; + } + + long declaredLong = ObjectStreamClass.getSerialVersionUID(clazz); + String declared = null; + if (declaredLong == 0) + declared = kInterfaceOnlyHashStr; + else if (declaredLong == 1) + declared = kExternalizableHashStr; + else + declared = Long.toHexString(declaredLong).toUpperCase(); + while (declared.length() < 16) { + declared = "0" + declared; + } + hash = hash + ":" + declared; + + return ":" + hash; + } + + /** + * Creates a repository ID for a sequence. This is for expert users only as + * this method assumes the object passed is an array. If passed an object + * that is not an array, it will produce a rep id for a sequence of zero + * length. This would be an error. + * @param ser The Java object to create a repository ID for + **/ + public static String createSequenceRepID(java.lang.Object ser){ + return createSequenceRepID(ser.getClass()); + } + + /** + * Creates a repository ID for a sequence. This is for expert users only as + * this method assumes the object passed is an array. If passed an object + * that is not an array, it will produce a malformed rep id. + * @param clazz The Java class to create a repository ID for + **/ + public static String createSequenceRepID(java.lang.Class clazz){ + synchronized (classSeqToRepStr) { + String repid = (String)classSeqToRepStr.get(clazz); + if (repid != null) + return repid; + + Class originalClazz = clazz; + + Class type = null; + int numOfDims = 0; + + while ((type = clazz.getComponentType()) != null) { + numOfDims++; + clazz = type; + } + + if (clazz.isPrimitive()) { + repid = kValuePrefix + originalClazz.getName() + + kPrimitiveSequenceValueHash; + } else { + StringBuffer buf = new StringBuffer(); + buf.append(kValuePrefix); + while(numOfDims-- > 0) { + buf.append("["); + } + buf.append("L"); + buf.append(convertToISOLatin1(clazz.getName())); + buf.append(";"); + buf.append(createHashString(clazz)); + repid = buf.toString(); + } + classSeqToRepStr.put(originalClazz,repid); + return repid; + } + } + + + public static String createForSpecialCase(java.lang.Class clazz){ + return createForSpecialCase( clazz, ClassInfoCache.get( clazz ) ) ; + } + + public static String createForSpecialCase(java.lang.Class clazz, + ClassInfoCache.ClassInfo cinfo ){ + if (cinfo.isArray()) { + return createSequenceRepID(clazz); + } else { + if (clazz == String.class) + return kWStringValueRepID ; + if (clazz == Class.class) + return kClassDescValueRepID ; + if (clazz == java.rmi.Remote.class) + return kRemoteValueRepID ; + return null ; + } + } + + public static String createForSpecialCase(java.io.Serializable ser){ + Class clazz = ser.getClass(); + if (ClassInfoCache.get(clazz).isArray()) { + return createSequenceRepID(ser); + } else { + return createForSpecialCase(clazz); + } + } + + /** + * Creates a repository ID for a normal Java Type. + * @param ser The Java object to create a repository ID for + * @exception com.sun.corba.ee.impl.io.TypeMismatchException if + * ser implements the org.omg.CORBA.portable.IDLEntity interface + * which indicates it is an IDL Value type. + **/ + public static String createForJavaType(java.io.Serializable ser) + throws com.sun.corba.ee.impl.io.TypeMismatchException + { + synchronized (classToRepStr) { + String repid = createForSpecialCase(ser); + if (repid != null) + return repid; + Class clazz = ser.getClass(); + repid = (String)classToRepStr.get(clazz); + + if (repid != null) + return repid; + + repid = kValuePrefix + convertToISOLatin1(clazz.getName()) + + createHashString(clazz); + + classToRepStr.put(clazz, repid); + repStrToClass.put(repid, clazz); + return repid; + } + } + + public static String createForJavaType(Class clz) + throws com.sun.corba.ee.impl.io.TypeMismatchException + { + return createForJavaType( clz, ClassInfoCache.get( clz ) ) ; + } + + /** + * Creates a repository ID for a normal Java Type. + * @param clz The Java class to create a repository ID for + * @exception com.sun.corba.ee.impl.io.TypeMismatchException if + * ser implements the * org.omg.CORBA.portable.IDLEntity interface + * which indicates it is an IDL Value type. + **/ + public static String createForJavaType(Class clz, ClassInfoCache.ClassInfo cinfo ) + throws com.sun.corba.ee.impl.io.TypeMismatchException + { + synchronized (classToRepStr){ + String repid = createForSpecialCase(clz,cinfo); + if (repid != null) + return repid; + + repid = (String)classToRepStr.get(clz); + if (repid != null) + return repid; + + repid = kValuePrefix + convertToISOLatin1(clz.getName()) + + createHashString(clz); + + classToRepStr.put(clz, repid); + repStrToClass.put(repid, clz); + return repid; + } + } + + /** + * Creates a repository ID for an IDL Java Type. + * @param ser The IDL Value object to create a repository ID for + * @param major The major version number + * @param minor The minor version number + * @exception com.sun.corba.ee.impl.io.TypeMismatchException if ser does not implement the + * org.omg.CORBA.portable.IDLEntity interface which indicates it is an IDL Value type. + **/ + public static String createForIDLType(Class ser, int major, int minor) + throws com.sun.corba.ee.impl.io.TypeMismatchException + { + synchronized (classIDLToRepStr){ + String repid = (String)classIDLToRepStr.get(ser); + if (repid != null) + return repid; + + repid = kIDLPrefix + + convertToISOLatin1(ser.getName()).replace('.','/') + + ":" + major + "." + minor; + classIDLToRepStr.put(ser, repid); + return repid; + } + } + + private static String getIdFromHelper(Class clazz){ + try { + Class helperClazz = + Utility.loadClassForClass(clazz.getName()+"Helper", + null, clazz.getClassLoader(), clazz, clazz.getClassLoader()); + Method idMethod = helperClazz.getDeclaredMethod("id"); + return (String)idMethod.invoke(null); + } catch (java.lang.ClassNotFoundException cnfe) { + throw new org.omg.CORBA.MARSHAL(cnfe.toString()); + } catch (java.lang.NoSuchMethodException nsme) { + throw new org.omg.CORBA.MARSHAL(nsme.toString()); + } catch (java.lang.reflect.InvocationTargetException ite) { + throw new org.omg.CORBA.MARSHAL(ite.toString()); + } catch (java.lang.IllegalAccessException iae) { + throw new org.omg.CORBA.MARSHAL(iae.toString()); + } + } + + public static String createForAnyType(Class type ) { + return createForAnyType( type, ClassInfoCache.get( type ) ) ; + } + + /** + * Createa a repository ID for the type if it is either a java type + * or an IDL type. + * @param type The type to create rep. id for + * @param cinfo The ClassInfo for the type (pre-computed elsewhere to save time) + * @return The rep. id. + **/ + public static String createForAnyType(Class type, ClassInfoCache.ClassInfo cinfo) { + try{ + // We may re-compute the repo id more than once, but that's OK, because + // it's always the same. + String result = cinfo.getRepositoryId() ; + if (result == null) { + if (cinfo.isArray()) { + result = createSequenceRepID(type); + } else if (cinfo.isAIDLEntity(type)) { + try{ + result = getIdFromHelper(type); + } catch(Throwable t) { + return createForIDLType(type, 1, 0); + } + } else + result = createForJavaType(type, cinfo ); + + cinfo.setRepositoryId( result ) ; + } + + return result ; + } catch(com.sun.corba.ee.impl.io.TypeMismatchException e){ + return null; + } + + } + + public static boolean isAbstractBase(Class clazz) { + ClassInfoCache.ClassInfo cinfo = ClassInfoCache.get( clazz ) ; + return cinfo.isInterface() && cinfo.isAIDLEntity(clazz) + && !cinfo.isAValueBase(clazz) && !cinfo.isACORBAObject(clazz) ; + } + + public static boolean isAnyRequired(Class clazz) { + return ((clazz == java.lang.Object.class) || + (clazz == java.io.Serializable.class) || + (clazz == java.io.Externalizable.class)); + } + + public static long fromHex(String hexNumber) { + if (hexNumber.startsWith("0x")) + return Long.valueOf(hexNumber.substring(2), 16).longValue(); + else return Long.valueOf(hexNumber, 16).longValue(); + } + + /** + * Convert strings with illegal IDL identifier characters. + *

    + * Section 5.5.7 of OBV spec. + */ + public static String convertToISOLatin1 (String name) { + + int length = name.length(); + if (length == 0) { + return name; + } + StringBuffer buffer = null; + + for (int i = 0; i < length; i++) { + + char c = name.charAt(i); + + if (c > 255 || IDL_IDENTIFIER_CHARS[c] == 0) { + + // We gotta convert. Have we already started? + + if (buffer == null) { + + // No, so get set up... + + buffer = new StringBuffer(name.substring(0,i)); + } + + // Convert the character into the IDL escape syntax... + buffer.append( + "\\U" + + (char)ASCII_HEX[(c & 0xF000) >>> 12] + + (char)ASCII_HEX[(c & 0x0F00) >>> 8] + + (char)ASCII_HEX[(c & 0x00F0) >>> 4] + + (char)ASCII_HEX[(c & 0x000F)]); + + } else { + if (buffer != null) { + buffer.append(c); + } + } + } + + if (buffer != null) { + name = buffer.toString(); + } + + return name; + } + + /** + * Convert strings with ISO Latin 1 escape sequences back to original + * strings. + *

    + * Section 5.5.7 of OBV spec. + */ + private static String convertFromISOLatin1 (String name) { + + int index = -1; + StringBuffer buf = new StringBuffer(name); + + while ((index = buf.toString().indexOf("\\U")) != -1){ + String str = "0000" + buf.toString().substring(index+2, index+6); + + // Convert Hexadecimal + byte[] buffer = new byte[(str.length() - 4) / 2]; + for (int i=4, j=0; i < str.length(); i +=2, j++) { + buffer[j] = + (byte)((Utility.hexOf(str.charAt(i)) << 4) & 0xF0); + buffer[j] |= + (byte)((Utility.hexOf(str.charAt(i+1)) << 0) & 0x0F); + } + buf = new StringBuffer(delete(buf.toString(), index, index+6)); + buf.insert(index, (char)buffer[1]); + } + + return buf.toString(); + + + } + + private static String delete(String str, int from, int to) + { + return str.substring(0, from) + str.substring(to, str.length()); + } + + private static String replace(String target, String arg, String source) + { + int i = 0; + i = target.indexOf(arg); + + while(i != -1) + { + String left = target.substring(0, i); + String right = target.substring(i+arg.length()); + target = left+source+right; + i = target.indexOf(arg); + } + return target; + } + + public static int computeValueTag(boolean codeBasePresent, int typeInfo, + boolean chunkedEncoding){ + + int value_tag = kInitialValueTag; + + if (codeBasePresent) + value_tag = value_tag | 0x00000001; + + value_tag = value_tag | typeInfo; + + if (chunkedEncoding) + value_tag = value_tag | kChunkedMask; + + return value_tag; + } + + public static boolean isCodeBasePresent(int value_tag){ + return ((value_tag & 0x00000001) == 1); + } + + public static int getTypeInfo(int value_tag){ + return (value_tag & 0x00000006); + } + + public static boolean isChunkedEncoding(int value_tag){ + return ((value_tag & kChunkedMask) != 0); + } + + public static String getServerURL(){ + return defaultServerURL; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/RepositoryIdCache.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/RepositoryIdCache.java new file mode 100644 index 000000000..4ec6005aa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/RepositoryIdCache.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + +import java.util.Stack; +import java.util.Hashtable; +import java.util.EmptyStackException; +import java.util.Enumeration; + +public class RepositoryIdCache extends Hashtable { + public final synchronized RepositoryId getId(String key) { + RepositoryId repId = (RepositoryId)super.get(key); + + if (repId != null) { + return repId; + } else { + repId = new RepositoryId(key); + put(key, repId); + return repId; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/Utility.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/Utility.java new file mode 100644 index 000000000..48193841b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/Utility.java @@ -0,0 +1,1028 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; + +import java.util.List ; +import java.util.ArrayList ; +import java.util.Iterator ; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.BoxedValueHelper; +import org.omg.CORBA.portable.ValueFactory; +import org.omg.CORBA.portable.Delegate; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Tie; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; + +import com.sun.corba.ee.spi.logging.UtilSystemException ; +import com.sun.corba.ee.spi.logging.OMGSystemException ; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util; + +import com.sun.corba.ee.spi.misc.ORBClassLoader ; +import java.util.IdentityHashMap; + + +/** + * Handy class full of static functions. + */ +public final class Utility { + + public static final String STUB_PREFIX = "_"; + public static final String RMI_STUB_SUFFIX = "_Stub"; + public static final String DYNAMIC_STUB_SUFFIX = "_DynamicStub" ; + public static final String IDL_STUB_SUFFIX = "Stub"; + public static final String TIE_SUFIX = "_Tie"; + private static final IdentityHashMap tieCache = new IdentityHashMap(); + private static final IdentityHashMap tieToStubCache = new IdentityHashMap(); + private static final IdentityHashMap stubToTieCache = new IdentityHashMap(); + private static final Object CACHE_MISS = new Object(); + private static final UtilSystemException wrapper = + UtilSystemException.self ; + private static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + /** + * Ensure that stubs, ties, and implementation objects + * are 'connected' to the runtime. Converts implementation + * objects to a type suitable for sending on the wire. + * @param obj the object to connect. + * @param orb the ORB to connect to if obj is exported to IIOP. + * @param convertToStub true if implementation types should be + * converted to Stubs rather than just org.omg.CORBA.Object. + * @return the connected object. + * @exception NoSuchObjectException if obj is an implementation + * which has not been exported. + */ + public static Object autoConnect(Object obj, ORB orb, boolean convertToStub) + { + if (obj == null) { + return obj; + } + + if (StubAdapter.isStub(obj)) { + try { + StubAdapter.getDelegate(obj) ; + } catch (BAD_OPERATION okay) { + try { + StubAdapter.connect( obj, orb ) ; + } catch (RemoteException e) { + // The stub could not be connected because it + // has an invalid IOR... + throw wrapper.objectNotConnected( e, + obj.getClass().getName() ) ; + } + } + + return obj; + } + + if (obj instanceof Remote) { + Remote remoteObj = (Remote)obj; + Tie theTie = Util.getInstance().getTie(remoteObj); + if (theTie != null) { + try { + theTie.orb(); + } catch (SystemException okay) { + theTie.orb(orb); + } + + if (convertToStub) { + Object result = loadStub(theTie,null,null,true); + if (result != null) { + return result; + } else { + throw wrapper.couldNotLoadStub(obj.getClass().getName()); + } + } else { + return StubAdapter.activateTie( theTie ); + } + } else { + // This is an implementation object which has not been + // exported to IIOP OR is a JRMP stub or implementation + // object which cannot be marshalled into an ORB stream... + throw wrapper.objectNotExported( obj.getClass().getName() ) ; + } + } + + // Didn't need to do anything, just return the input... + + return obj; + } + + /* + * Get a new instance of an RMI-IIOP Tie for the + * given server object. + * + * This code is rather confused. tieCache maps impls to Ties, + * but loadTie returns a new Tie instance if the impl is already + * cached. Also this method is useless with dynamic RMI-IIOP, since + * we just call new ReflectiveTie to create a Tie. Even with + * static RMI-IIOP this seems a bit questionable. In the static + * case, I think we want to avoid possibly expensive ClassLoader + * searches. But this is really a mapping from stub class + * to corresponding Tie class. The new stub/tie architecture + * clearly indicates that this responsibility should lie with + * the StubFactoryFactory, and this method should be eliminated. + */ + public static Tie loadTie(Remote obj) { + Tie result = null; + Class objClass = obj.getClass(); + + // Have we tried to find this guy before? + + synchronized (tieCache) { + + Object it = tieCache.get(obj); + + if (it == null) { + + // No, so try it... + + try { + + // First try the classname... + + result = loadTie(objClass); + + // If we don't have a valid tie at this point, + // walk up the parent chain until we either + // load a tie or encounter PortableRemoteObject + // or java.lang.Object... + + while (result == null && + (objClass = objClass.getSuperclass()) != null && + objClass != PortableRemoteObject.class && + objClass != Object.class) { + + result = loadTie(objClass); + } + } catch (Exception ex) { + wrapper.loadTieFailed( ex, objClass.getName() ) ; + } + + // Did we get it? + + if (result == null) { + + // Nope, so cache that fact... + + tieCache.put(obj,CACHE_MISS); + + } else { + + // Yes, so cache it... + + tieCache.put(obj,result); + } + } else { + + // Yes, return a new instance or fail again if + // it was a miss last time... + + if (it != CACHE_MISS) { + try { + result = (Tie) it.getClass().newInstance(); + } catch (Exception e) { + } + } + } + } + + return result; + } + + /* + * Load an RMI-IIOP Tie + */ + private static Tie loadTie(Class theClass) + { + return com.sun.corba.ee.spi.orb.ORB.getStubFactoryFactory(). + getTie( theClass ) ; + } + + /* + * Clear the stub/tie caches. Intended for use by + * test code. + */ + public static void clearCaches() { + synchronized (tieToStubCache) { + tieToStubCache.clear(); + } + synchronized (tieCache) { + tieCache.clear(); + } + synchronized (stubToTieCache) { + stubToTieCache.clear(); + } + } + + /* + * Load a class and check that it is assignable to a given type. + * @param className the class name. + * @param remoteCodebase the codebase to use. May be null. + * @param loader the class loader of last resort. May be null. + * @param expectedType the expected type. May be null. + * @return the loaded class. + */ + static Class loadClassOfType(String className, String remoteCodebase, + ClassLoader loader, Class expectedType, + ClassLoader expectedTypeClassLoader) throws ClassNotFoundException + { + Class loadedClass = null; + + try { + //Sequence finding of the stubs according to spec + try{ + //If-else is put here for speed up of J2EE. + //According to the OMG spec, the if clause is not dead code. + //It can occur if some compiler has allowed generation + //into org.omg.stub hierarchy for non-offending + //classes. This will encourage people to + //produce non-offending class stubs in their own hierarchy. + final String wpp = PackagePrefixChecker.withoutPackagePrefix(className) ; + if (!PackagePrefixChecker.hasOffendingPrefix( wpp )) { + loadedClass = Util.getInstance().loadClass( + wpp, remoteCodebase, loader); + } else { + loadedClass = Util.getInstance().loadClass(className, remoteCodebase, + loader); + } + } catch (ClassNotFoundException cnfe) { + loadedClass = Util.getInstance().loadClass(className, remoteCodebase, + loader); + } + if (expectedType == null) { + return loadedClass; + } + } catch (ClassNotFoundException cnfe) { + if (expectedType == null) { + throw cnfe; + } + } + + // If no class was loaded, or if the loaded class is not of the + // correct type, make a further attempt to load the correct class + // using the classloader of the expected type. + // _REVISIT_ Is this step necessary, or should the Util,loadClass + // algorithm always produce a valid class if the setup is correct? + // Does the OMG standard algorithm need to be changed to include + // this step? + if (loadedClass == null || !expectedType.isAssignableFrom(loadedClass)){ + if (expectedType.getClassLoader() != expectedTypeClassLoader) { + throw new IllegalArgumentException("expectedTypeClassLoader not class loader of " + + "expected Type."); + } + + if (expectedTypeClassLoader != null) { + loadedClass = expectedTypeClassLoader.loadClass(className); + } else { + loadedClass = ORBClassLoader.loadClass(className); + } + } + + return loadedClass; + } + + /* + * Load a class and check that it is compatible with a given type. + * @param className the class name. + * @param remoteCodebase the codebase to use. May be null. + * @param loadingContext the loading context. May be null. + * @param relatedType the related type. May be null. + * @return the loaded class. + */ + public static Class loadClassForClass (String className, + String remoteCodebase, + ClassLoader loader, + Class relatedType, + ClassLoader relatedTypeClassLoader) + throws ClassNotFoundException + { + if (relatedType == null) { + return Util.getInstance().loadClass(className, remoteCodebase, + loader); + } + + Class loadedClass = null; + try { + loadedClass = Util.getInstance().loadClass(className, remoteCodebase, loader); + } catch (ClassNotFoundException cnfe) { + if (relatedType.getClassLoader() == null) { + throw cnfe; + } + } + + // If no class was not loaded, or if the loaded class is not of the + // correct type, make a further attempt to load the correct class + // using the classloader of the related type. + // _REVISIT_ Is this step necessary, or should the Util,loadClass + // algorithm always produce a valid class if the setup is correct? + // Does the OMG standard algorithm need to be changed to include + // this step? + if (loadedClass == null || + (loadedClass.getClassLoader() != null && + loadedClass.getClassLoader().loadClass(relatedType.getName()) != + relatedType)) + { + if (relatedType.getClassLoader() != relatedTypeClassLoader) { + throw new IllegalArgumentException("relatedTypeClassLoader not class loader of relatedType."); + } + + if (relatedTypeClassLoader != null) { + loadedClass = relatedTypeClassLoader.loadClass(className); + } + } + + return loadedClass; + } + + /** + * Get the helper for an IDLValue + * + * Throws MARSHAL exception if no helper found. + */ + public static BoxedValueHelper getHelper(Class clazz, String codebase, + String repId) + { + String className = null; + if (clazz != null) { + className = clazz.getName(); + if (codebase == null) { + codebase = + Util.getInstance().getCodebase(clazz); + } + } else { + if (repId != null) { + className = + RepositoryId.cache.getId(repId).getClassName(); + } + if (className == null) { + throw wrapper.unableLocateValueHelper(); + } + } + + try { + ClassLoader clazzLoader = + (clazz == null ? null : clazz.getClassLoader()); + Class helperClass = + loadClassForClass(className+"Helper", codebase, clazzLoader, + clazz, clazzLoader); + return (BoxedValueHelper)helperClass.newInstance(); + + } catch (ClassNotFoundException cnfe) { + throw wrapper.unableLocateValueHelper( cnfe ); + } catch (IllegalAccessException iae) { + throw wrapper.unableLocateValueHelper( iae ); + } catch (InstantiationException ie) { + throw wrapper.unableLocateValueHelper( ie ); + } catch (ClassCastException cce) { + throw wrapper.unableLocateValueHelper( cce ); + } + } + + /** + * Get the factory for an IDLValue + * + * Throws MARSHAL exception if no factory found. + */ + public static ValueFactory getFactory(Class clazz, String codebase, + ORB orb, String repId) + { + ValueFactory factory = null; + if ((orb != null) && (repId != null)) { + try { + factory = ((org.omg.CORBA_2_3.ORB)orb).lookup_value_factory( + repId); + } catch (org.omg.CORBA.BAD_PARAM ex) { + // Try other way + } + } + + String className = null; + if (clazz != null) { + className = clazz.getName(); + if (codebase == null) { + codebase = + Util.getInstance().getCodebase(clazz); + } + } else { + if (repId != null) { + className = + RepositoryId.cache.getId(repId).getClassName(); + } + if (className == null) { + throw omgWrapper.unableLocateValueFactory(); + } + } + + // if earlier search found a non-default factory, or the same default + // factory that loadClassForClass would return, bale out now... + if (factory != null && + (!factory.getClass().getName().equals(className+"DefaultFactory") || + (clazz == null && codebase == null))) + return factory; + + try { + ClassLoader clazzLoader = + (clazz == null ? null : clazz.getClassLoader()); + Class factoryClass = + loadClassForClass(className+"DefaultFactory", codebase, + clazzLoader, clazz, clazzLoader); + return (ValueFactory)factoryClass.newInstance(); + + } catch (ClassNotFoundException cnfe) { + throw omgWrapper.unableLocateValueFactory( cnfe); + } catch (IllegalAccessException iae) { + throw omgWrapper.unableLocateValueFactory( iae); + } catch (InstantiationException ie) { + throw omgWrapper.unableLocateValueFactory( ie); + } catch (ClassCastException cce) { + throw omgWrapper.unableLocateValueFactory( cce); + } + } + + /* + * Load an RMI-IIOP Stub given a Tie. + * @param tie the tie. + * @param stubClass the stub class. May be null. + * @param remoteCodebase the codebase to use. May be null. + * @param onlyMostDerived if true, will fail if cannot load a stub for the + * first repID in the tie. If false, will walk all repIDs. + * @return the stub or null if not found. + */ + + public static Remote loadStub(Tie tie, + PresentationManager.StubFactory stubFactory, + String remoteCodebase, + boolean onlyMostDerived) + { + StubEntry entry = null; + + // Do we already have it cached? + synchronized (tieToStubCache) { + Object cached = tieToStubCache.get(tie); + if (cached == null) { + // No, so go try to load it... + entry = loadStubAndUpdateCache( + tie, stubFactory, remoteCodebase, onlyMostDerived); + } else { + // Yes, is it a stub? If not, it was a miss last + // time, so return null again... + if (cached != CACHE_MISS) { + // It's a stub. + entry = (StubEntry) cached; + + // Does the cached stub meet the requirements + // of the caller? If the caller does not require + // the most derived stub and does not require + // a specific stub type, we don't have to check + // any further because the cached type is good + // enough... + if (!entry.mostDerived && onlyMostDerived) { + // We must reload because we do not have + // the most derived cached already... + // The stubFactory arg must be null here + // to force onlyMostDerived=true to work + // correctly. + entry = loadStubAndUpdateCache(tie,null, + remoteCodebase,true); + } else if (stubFactory != null && + !StubAdapter.getTypeIds(entry.stub)[0].equals( + stubFactory.getTypeIds()[0]) ) + { + // We do not have exactly the right stub. First, try to + // upgrade the cached stub by forcing it to the most + // derived stub... + entry = loadStubAndUpdateCache(tie,null, + remoteCodebase,true); + + // If that failed, try again with the exact type + // we need... + if (entry == null) { + entry = loadStubAndUpdateCache(tie,stubFactory, + remoteCodebase,onlyMostDerived); + } + } else { + // Use the cached stub. Is the delegate set? + try { + Delegate stubDel = StubAdapter.getDelegate( + entry.stub ) ; + } catch (Exception e2) { + // No, so set it if we can... + try { + Delegate del = StubAdapter.getDelegate( + tie ) ; + StubAdapter.setDelegate( entry.stub, + del ) ; + } catch (Exception e) {} + } + } + } + } + } + + if (entry != null) { + return (Remote)entry.stub; + } else { + return null; + } + } + + /* + * Load an RMI-IIOP Stub given a Tie, but do not look in the cache. + * This method must be called with the lock held for tieToStubCache. + * @param tie the tie. + * @param stubFactory the stub factory. May be null. + * @param remoteCodebase the codebase to use. May be null. + * @param onlyMostDerived if true, will fail if cannot load a stub for the + * first repID in the tie. If false, will walk all repIDs. + * @return the StubEntry or null if not found. + */ + private static StubEntry loadStubAndUpdateCache ( + Tie tie, PresentationManager.StubFactory stubFactory, + String remoteCodebase, boolean onlyMostDerived) + { + org.omg.CORBA.Object stub = null; + StubEntry entry = null; + boolean tieIsStub = StubAdapter.isStub( tie ) ; + + if (stubFactory != null) { + try { + stub = stubFactory.makeStub(); + } catch (Throwable e) { + wrapper.stubFactoryCouldNotMakeStub( e ) ; + if (e instanceof ThreadDeath) { + throw (ThreadDeath) e; + } + } + } else { + String[] ids = null; + if (tieIsStub) { + ids = StubAdapter.getTypeIds( tie ) ; + } else { + // This will throw an exception if the tie + // is not a Servant. + ids = ((org.omg.PortableServer.Servant)tie). + _all_interfaces( null, null ); + } + + if (remoteCodebase == null) { + remoteCodebase = Util.getInstance().getCodebase(tie.getClass()); + } + + if (ids.length == 0) { + stub = new org.omg.stub.java.rmi._Remote_Stub(); + } else { + // Keep track of the errors for reporting after all attempts + List errors = new ArrayList() ; + + // Now walk all the RepIDs till we find a stub or fail... + for (int i = 0; i < ids.length; i++) { + if (ids[i].length() == 0) { + stub = new org.omg.stub.java.rmi._Remote_Stub(); + break; + } + + try { + PresentationManager.StubFactoryFactory stubFactoryFactory = + com.sun.corba.ee.spi.orb.ORB.getStubFactoryFactory(); + RepositoryId rid = RepositoryId.cache.getId( ids[i] ) ; + String className = rid.getClassName() ; + boolean isIDLInterface = rid.isIDLType() ; + stubFactory = stubFactoryFactory.createStubFactory( + className, isIDLInterface, remoteCodebase, null, + // This used to use the Tie's ClassLoader, but + // that is probably wrong for dynamic RMI-IIOP, + // since the Tie is always ReflectiveTie, which + // would always be loaded by the ORB ClassLoader, + // which may not be the application ClassLoader + // in some cases. + ORBClassLoader.getClassLoader() ) ; + stub = stubFactory.makeStub(); + break; + } catch (Exception e) { + // save exception for reporting after all attempts are completed. + errors.add( e ) ; + } + + if (onlyMostDerived) { + break; + } + } + + // Report errors. Errors are logged at FINE level if + // we got a stub (stub != null). Errors are logged + // as WARNINGs if we did not get a stub. + Iterator iter = errors.iterator() ; + if (stub == null ) { + while (iter.hasNext()) { + Exception exc = (Exception)iter.next() ; + wrapper.failureInMakeStubFromRepositoryId( exc ) ; + } + + wrapper.couldNotMakeStubFromRepositoryId() ; + } else { + while (iter.hasNext()) { + Exception exc = (Exception)iter.next() ; + wrapper.errorInMakeStubFromRepositoryId( exc ) ; + } + } + } + } + + if (stub == null) { + // Stub == null, so cache the miss... + tieToStubCache.put(tie,CACHE_MISS); + } else { + if (tieIsStub) { + try { + Delegate del = StubAdapter.getDelegate( tie ) ; + StubAdapter.setDelegate( stub, del ) ; + } catch( Exception e1 ) { + // The tie does not have a delegate set, so stash + // this tie away using the stub as a key so that + // later, when the stub is connected, we can find + // and connect the tie as well... + + synchronized (stubToTieCache) { + stubToTieCache.put(stub,tie); + } + } + } else { + // Tie extends Servant + try { + Delegate delegate = StubAdapter.getDelegate( tie ) ; + StubAdapter.setDelegate( stub, delegate ) ; + } catch( org.omg.CORBA.BAD_INV_ORDER bad) { + synchronized (stubToTieCache) { + stubToTieCache.put(stub,tie); + } + } catch( Exception e ) { + // Exception is caught because of any of the + // following reasons + // 1) POA is not associated with the TIE + // 2) POA Policies for the tie-associated POA + // does not support _this_object() call. + throw wrapper.noPoa( e ) ; + } + } + // Update the cache... + entry = new StubEntry(stub,onlyMostDerived); + tieToStubCache.put(tie,entry); + } + + return entry; + } + + /* + * If we loadStub(Tie,...) stashed away a tie which was + * not connected, remove it from the cache and return + * it. + */ + public static Tie getAndForgetTie (org.omg.CORBA.Object stub) { + synchronized (stubToTieCache) { + return (Tie) stubToTieCache.remove(stub); + } + } + + /* + * Remove any cached Stub for the given tie. + */ + public static void purgeStubForTie (Tie tie) { + StubEntry entry; + synchronized (tieToStubCache) { + entry = (StubEntry)tieToStubCache.remove(tie); + } + if (entry != null) { + synchronized (stubToTieCache) { + stubToTieCache.remove(entry.stub); + } + } + } + + /* + * Remove cached tie/servant pair. + */ + public static void purgeTieAndServant (Tie tie) { + synchronized (tieCache) { + Object target = tie.getTarget(); + if (target != null) { + tieCache.remove(target); + } + } + } + + /* + * Convert a RepId to a stubName... + */ + public static String stubNameFromRepID (String repID) { + + // Convert the typeid to a RepositoryId instance, get + // the className and mangle it as needed... + + RepositoryId id = RepositoryId.cache.getId(repID); + String className = id.getClassName(); + + if (id.isIDLType()) { + className = idlStubName(className); + } else { + className = stubName(className); + } + return className; + } + + + /* + * Load an RMI-IIOP Stub. This is used in PortableRemoteObject.narrow. + */ + public static Remote loadStub (org.omg.CORBA.Object narrowFrom, + Class narrowTo) + { + Remote result = null; + + try { + // Get the codebase from the delegate to use when loading + // the new stub, if possible... + String codebase = null; + Delegate delegate = null ; + try { + // We can't assume that narrowFrom is a CORBA_2_3 stub, yet + // it may have a 2_3 Delegate that provides a codebase. Swallow + // the ClassCastException otherwise. + delegate = StubAdapter.getDelegate( narrowFrom ) ; + codebase = ((org.omg.CORBA_2_3.portable.Delegate)delegate). + get_codebase(narrowFrom); + + } catch (ClassCastException e) { + wrapper.classCastExceptionInLoadStub( e ) ; + } + + // Fix for bug 6344962 + // + // Note that we (currently) only support Dynamic RMI-IIOP + // for our own ORB. Consequently, we need to check here + // whether our own ORB is in use or not. If not, + // we must use the static StubFactoryFactory ONLY. + ORB orb = delegate.orb(narrowFrom) ; + PresentationManager.StubFactoryFactory sff = null ; + if (orb instanceof com.sun.corba.ee.spi.orb.ORB) { + // This can be either static or dynamic + sff = com.sun.corba.ee.spi.orb.ORB.getStubFactoryFactory() ; + } else { + PresentationManager pm = com.sun.corba.ee.spi.orb.ORB.getPresentationManager() ; + sff = pm.getStaticStubFactoryFactory() ; + } + + PresentationManager.StubFactory sf = sff.createStubFactory( + narrowTo.getName(), false, codebase, narrowTo, + narrowTo.getClassLoader() ) ; + result = (Remote)sf.makeStub() ; + StubAdapter.setDelegate( result, + StubAdapter.getDelegate( narrowFrom ) ) ; + } catch (Exception err) { + wrapper.exceptionInLoadStub( err ) ; + } + + return result; + } + + /* + * Load an RMI-IIOP Stub class. This is used in the + * StaticStubFactoryFactory code. + */ + public static Class loadStubClass(String repID, + String remoteCodebase, + Class expectedType) + throws ClassNotFoundException + { + // Get the repID and check for "" special case. + // We should never be called with it (See CDRInputStream + // and the loadStub() method)... + + if (repID.length() == 0) { + throw new ClassNotFoundException(); + } + + // Get the stubname from the repID and load + // the class. If we have a valid 'sender', fall + // back to using its codebase if we need to... + String className = Utility.stubNameFromRepID(repID); + ClassLoader expectedTypeClassLoader = (expectedType == null ? null : + expectedType.getClassLoader()); + + try { + return loadClassOfType(className, + remoteCodebase, + expectedTypeClassLoader, + expectedType, + expectedTypeClassLoader); + } catch (ClassNotFoundException e) { + return loadClassOfType(PackagePrefixChecker.packagePrefix() + className, + remoteCodebase, + expectedTypeClassLoader, + expectedType, + expectedTypeClassLoader); + } + } + + /** + * Create an RMI stub name. + */ + public static String stubName (String className) + { + return stubName( className, false ) ; + } + + public static String dynamicStubName( String className ) + { + return stubName( className, true ) ; + } + + private static String stubName( String className, + boolean isDynamic ) + { + String name = stubNameForCompiler( className, isDynamic ) ; + if (PackagePrefixChecker.hasOffendingPrefix( name )) { + name = + PackagePrefixChecker.packagePrefix() + name; + } + return name ; + } + + public static String stubNameForCompiler (String className) + { + return stubNameForCompiler( className, false ) ; + } + + private static String stubNameForCompiler( String className, + boolean isDynamic ) + { + int index = className.indexOf('$'); + if (index < 0) { + index = className.lastIndexOf('.'); + } + + String suffix = isDynamic ? DYNAMIC_STUB_SUFFIX : + RMI_STUB_SUFFIX ; + + if (index > 0) { + return className.substring(0,index+1) + STUB_PREFIX + + className.substring(index+1) + suffix; + } else { + return STUB_PREFIX + className + suffix; + } + } + + /** + * Create an RMI tie name. + */ + public static String tieName (String className) + { + return + PackagePrefixChecker.hasOffendingPrefix(tieNameForCompiler(className)) ? + PackagePrefixChecker.packagePrefix() + tieNameForCompiler(className) : + tieNameForCompiler(className); + } + + public static String tieNameForCompiler (String className) + { + int index = className.indexOf('$'); + if (index < 0) { + index = className.lastIndexOf('.'); + } + if (index > 0) { + return className.substring(0,index+1) + + STUB_PREFIX + + className.substring(index+1) + + TIE_SUFIX; + } else { + return STUB_PREFIX + + className + + TIE_SUFIX; + } + } + + /** + * Throws the CORBA equivalent of a java.io.NotSerializableException + */ + public static void throwNotSerializableForCorba(String className) { + throw omgWrapper.notSerializable( className ) ; + } + + /** + * Create an IDL stub name. + */ + public static String idlStubName(String className) + { + String result = null; + int index = className.lastIndexOf('.'); + if (index > 0) { + result = className.substring(0,index+1) + + STUB_PREFIX + + className.substring(index+1) + + IDL_STUB_SUFFIX; + } else { + result = STUB_PREFIX + + className + + IDL_STUB_SUFFIX; + } + return result; + } + + public static void printStackTrace() + { + Throwable thr = new Throwable( "Printing stack trace:" ) ; + thr.fillInStackTrace() ; + thr.printStackTrace() ; + } + + /** + * Read an object reference from the input stream and narrow + * it to the desired type. + * @param in the stream to read from. + * @throws ClassCastException if narrowFrom cannot be cast to narrowTo. + */ + public static Object readObjectAndNarrow(InputStream in, + Class narrowTo) + throws ClassCastException + { + Object result = in.read_Object(); + if (result != null) { + return PortableRemoteObject.narrow(result, narrowTo); + } else { + return null; + } + } + + /** + * Read an abstract interface type from the input stream and narrow + * it to the desired type. + * @param in the stream to read from. + * @throws ClassCastException if narrowFrom cannot be cast to narrowTo. + */ + public static Object readAbstractAndNarrow( + org.omg.CORBA_2_3.portable.InputStream in, Class narrowTo) + throws ClassCastException + { + Object result = in.read_abstract_interface(); + if (result != null) { + return PortableRemoteObject.narrow(result, narrowTo); + } else { + return null; + } + } + + + /** Converts an Ascii Character into Hexadecimal digit + */ + static int hexOf( char x ) + { + int val; + + val = x - '0'; + if (val >=0 && val <= 9) { + return val; + } + + val = (x - 'a') + 10; + if (val >= 10 && val <= 15) { + return val; + } + + val = (x - 'A') + 10; + if (val >= 10 && val <= 15) { + return val; + } + + throw wrapper.badHexDigit() ; + } +} + +class StubEntry { + org.omg.CORBA.Object stub; + boolean mostDerived; + + StubEntry(org.omg.CORBA.Object stub, boolean mostDerived) { + this.stub = stub; + this.mostDerived = mostDerived; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/impl/util/Version.java b/orbmain/src/main/java/com/sun/corba/ee/impl/util/Version.java new file mode 100644 index 000000000..b82deb145 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/impl/util/Version.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.util; +import java.util.Date; + +public class Version { + + public static final String PROJECT_NAME = "RMI-IIOP"; + public static final String VERSION = "1.0"; + public static final String BUILD = "0.0"; + public static final String BUILD_TIME = "unknown"; + public static final String FULL = PROJECT_NAME + " " + VERSION + " (" + + BUILD_TIME + ")"; + + public static String asString () { + return FULL; + } + + public static void main (String[] args) { + System.out.println(FULL); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/copyobject/CopierManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/copyobject/CopierManager.java new file mode 100644 index 000000000..9f9762c0b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/copyobject/CopierManager.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.copyobject ; + +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory ; + +/** Manager of ObjectCopier implementations used to support javax.rmi.CORBA.Util.copyObject(s). + * This provides simple methods for registering all supported ObjectCopier factories. + * A default copier is also supported, for use in contexts where no specific copier id + * is available. + */ +public interface CopierManager +{ + /** Set the Id of the copier to use if no other copier has been set. + */ + void setDefaultId( int id ) ; + + /** Return the copier for the default copier id. Throws a BAD_PARAM exception + * if no default copier id has been set. + */ + int getDefaultId() ; + + ObjectCopierFactory getObjectCopierFactory( int id ) ; + + ObjectCopierFactory getDefaultObjectCopierFactory() ; + + /** Register an ObjectCopierFactory under a particular id. This can be retrieved + * later by getObjectCopierFactory. + */ + void registerObjectCopierFactory( ObjectCopierFactory factory, int id ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/copyobject/CopyobjectDefaults.java b/orbmain/src/main/java/com/sun/corba/ee/spi/copyobject/CopyobjectDefaults.java new file mode 100644 index 000000000..3939397d5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/copyobject/CopyobjectDefaults.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.copyobject ; + +import com.sun.corba.ee.spi.orb.ORB ; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopier ; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory ; +import org.glassfish.pfl.dynamic.copyobject.impl.FallbackObjectCopierImpl ; + +import com.sun.corba.ee.impl.copyobject.ReferenceObjectCopierImpl ; +import com.sun.corba.ee.impl.copyobject.ORBStreamObjectCopierImpl ; +import com.sun.corba.ee.impl.copyobject.JavaStreamORBObjectCopierImpl ; +import com.sun.corba.ee.impl.copyobject.OldReflectObjectCopierImpl ; +import com.sun.corba.ee.impl.copyobject.ReflectObjectCopierImpl ; + +public abstract class CopyobjectDefaults +{ + private CopyobjectDefaults() { } + + /** Obtain the ORB stream copier factory. Note that this version behaves differently + * than the others: each ObjectCopier produced by the factory only preserves aliasing + * within a single call to copy. The others copiers all preserve aliasing across + * all calls to copy (on the same ObjectCopier instance). + */ + public static ObjectCopierFactory makeORBStreamObjectCopierFactory( final ORB orb ) + { + return new ObjectCopierFactory() { + public ObjectCopier make( ) + { + return new ORBStreamObjectCopierImpl( orb ) ; + } + } ; + } + + public static ObjectCopierFactory makeJavaStreamObjectCopierFactory( final ORB orb ) + { + return new ObjectCopierFactory() { + public ObjectCopier make( ) + { + return new JavaStreamORBObjectCopierImpl( orb ) ; + } + } ; + } + + private static final ObjectCopier referenceObjectCopier = new ReferenceObjectCopierImpl() ; + + private static ObjectCopierFactory referenceObjectCopierFactory = + new ObjectCopierFactory() { + public ObjectCopier make() + { + return referenceObjectCopier ; + } + } ; + + /** Obtain the reference object "copier". This does no copies: it just + * returns whatever is passed to it. + */ + public static ObjectCopierFactory getReferenceObjectCopierFactory() + { + return referenceObjectCopierFactory ; + } + + /** Create a fallback copier factory from the two ObjectCopierFactory + * arguments. This copier makes an ObjectCopierFactory that creates + * instances of a fallback copier that first tries an ObjectCopier + * created from f1, then tries one created from f2, if the first + * throws a ReflectiveCopyException. + */ + public static ObjectCopierFactory makeFallbackObjectCopierFactory( + final ObjectCopierFactory f1, final ObjectCopierFactory f2 ) + { + return new ObjectCopierFactory() { + public ObjectCopier make() + { + ObjectCopier c1 = f1.make() ; + ObjectCopier c2 = f2.make() ; + return new FallbackObjectCopierImpl( c1, c2 ) ; + } + } ; + } + + /** Obtain the old version of the reflective copier factory. This is provided only + * for benchmarking purposes. + */ + public static ObjectCopierFactory makeOldReflectObjectCopierFactory( final ORB orb ) + { + return new ObjectCopierFactory() { + public ObjectCopier make() + { + return new OldReflectObjectCopierImpl( orb ) ; + } + } ; + } + + /** Obtain the new reflective copier factory. This is 3-4 times faster than the stream + * copier, and about 10% faster than the old reflective copier. It should + * normally be used with a fallback copier, as there are some classes that simply + * cannot be copied reflectively. + */ + public static ObjectCopierFactory makeReflectObjectCopierFactory( final ORB orb ) + { + return new ObjectCopierFactory() { + public ObjectCopier make( ) + { + return new ReflectObjectCopierImpl( orb ) ; + } + } ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/extension/CopyObjectPolicy.java b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/CopyObjectPolicy.java new file mode 100644 index 000000000..8e846423e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/CopyObjectPolicy.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.extension ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.LocalObject ; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** Policy used to specify the copyObject implementation to use. +*/ +public class CopyObjectPolicy extends LocalObject implements Policy +{ + private final int value ; + + public CopyObjectPolicy( int value ) + { + this.value = value ; + } + + public int getValue() + { + return value ; + } + + public int policy_type () + { + return ORBConstants.COPY_OBJECT_POLICY ; + } + + public org.omg.CORBA.Policy copy () + { + return this ; + } + + public void destroy () + { + // NO-OP + } + + public String toString() + { + return "CopyObjectPolicy[" + value + "]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/extension/LoadBalancingPolicy.java b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/LoadBalancingPolicy.java new file mode 100644 index 000000000..2d2f2aca6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/LoadBalancingPolicy.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.extension ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.LocalObject ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** Policy used to support the request partitioning feature and to + * specify the partition to use. +*/ +public class LoadBalancingPolicy extends LocalObject implements Policy +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private final int value; + + public LoadBalancingPolicy( int value ) + { + if (value < ORBConstants.FIRST_LOAD_BALANCING_VALUE || + value > ORBConstants.LAST_LOAD_BALANCING_VALUE) { + throw wrapper.invalidLoadBalancingPolicyValue( + value, ORBConstants.FIRST_LOAD_BALANCING_VALUE, + ORBConstants.LAST_LOAD_BALANCING_VALUE); + } + this.value = value; + } + + public int getValue() + { + return value; + } + + public int policy_type() + { + return ORBConstants.LOAD_BALANCING_POLICY ; + } + + public org.omg.CORBA.Policy copy() + { + return this; + } + + public void destroy() + { + // NO-OP + } + + @Override + public String toString() + { + return "LoadBalancingPolicy[" + value + "]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/extension/RequestPartitioningPolicy.java b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/RequestPartitioningPolicy.java new file mode 100644 index 000000000..2372257b1 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/RequestPartitioningPolicy.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.extension ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.LocalObject ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** Policy used to support the request partitioning feature and to + * specify the partition to use. +*/ +public class RequestPartitioningPolicy extends LocalObject implements Policy +{ + private static ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public final static int DEFAULT_VALUE = 0; + private final int value; + + public RequestPartitioningPolicy( int value ) + { + if (value < ORBConstants.REQUEST_PARTITIONING_MIN_THREAD_POOL_ID || + value > ORBConstants.REQUEST_PARTITIONING_MAX_THREAD_POOL_ID) { + throw wrapper.invalidRequestPartitioningPolicyValue( + value, + ORBConstants.REQUEST_PARTITIONING_MIN_THREAD_POOL_ID, + ORBConstants.REQUEST_PARTITIONING_MAX_THREAD_POOL_ID); + } + this.value = value; + } + + public int getValue() + { + return value; + } + + public int policy_type() + { + return ORBConstants.REQUEST_PARTITIONING_POLICY; + } + + public org.omg.CORBA.Policy copy() + { + return this; + } + + public void destroy() + { + // NO-OP + } + + @Override + public String toString() + { + return "RequestPartitioningPolicy[" + value + "]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/extension/ServantCachingPolicy.java b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/ServantCachingPolicy.java new file mode 100644 index 000000000..a711bec3a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/ServantCachingPolicy.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.extension ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.LocalObject ; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** Policy used to implement servant caching optimization in the POA. +* Creating a POA with an instance pol of this policy where +* pol.getType() > NO_SERVANT_CACHING will cause the servant to be +* looked up in the POA and cached in the LocalClientRequestDispatcher when +* the ClientRequestDispatcher is colocated with the implementation of the +* objref. This greatly speeds up invocations at the cost of violating the +* POA semantics. In particular, every request to a particular objref +* must be handled by the same servant. Note that this is typically the +* case for EJB implementations. +*

    +* If servant caching is used, there are two different additional +* features of the POA that are expensive: +*

      +*
    1. POA current semantics +*
    2. Proper handling of POA destroy. +*
        +* POA current semantics requires maintaining a ThreadLocal stack of +* invocation information that is always available for POACurrent operations. +* Maintaining this stack is expensive on the timescale of optimized co-located +* calls, so the option is provided to turn it off. Similarly, causing +* POA.destroy() calls to wait for all active calls in the POA to complete +* requires careful tracking of the entry and exit of invocations in the POA. +* Again, tracking this is somewhat expensive. +*/ +public class ServantCachingPolicy extends LocalObject implements Policy +{ + /** Do not cache servants in the ClientRequestDispatcher. This will + * always support the full POA semantics, including changing the + * servant that handles requests on a particular objref. + */ + public static final int NO_SERVANT_CACHING = 0 ; + + /** Perform servant caching, preserving POA current and POA destroy semantics. + * We will use this as the new default, as the app server is making heavier use + * now of POA facilities. + */ + public static final int FULL_SEMANTICS = 1 ; + + /** Perform servant caching, preservent only POA current semantics. + * At least this level is required in order to support selection of ObjectCopiers + * for co-located RMI-IIOP calls, as the current copier is stored in + * OAInvocationInfo, which must be present on the stack inside the call. + */ + public static final int INFO_ONLY_SEMANTICS = 2 ; + + /** Perform servant caching, not preserving POA current or POA destroy semantics. + */ + public static final int MINIMAL_SEMANTICS = 3 ; + + private static ServantCachingPolicy policy = null ; + private static ServantCachingPolicy infoOnlyPolicy = null ; + private static ServantCachingPolicy minimalPolicy = null ; + + private int type ; + + public String typeToName() + { + switch (type) { + case FULL_SEMANTICS: + return "FULL" ; + case INFO_ONLY_SEMANTICS: + return "INFO_ONLY" ; + case MINIMAL_SEMANTICS: + return "MINIMAL" ; + default: + return "UNKNOWN(" + type + ")" ; + } + } + + public String toString() + { + return "ServantCachingPolicy[" + typeToName() + "]" ; + } + + private ServantCachingPolicy( int type ) + { + this.type = type ; + } + + public int getType() + { + return type ; + } + + /** Return the default servant caching policy. + */ + public synchronized static ServantCachingPolicy getPolicy() + { + return getFullPolicy() ; + } + + public synchronized static ServantCachingPolicy getFullPolicy() + { + if (policy == null) + policy = new ServantCachingPolicy( FULL_SEMANTICS ) ; + + return policy ; + } + + public synchronized static ServantCachingPolicy getInfoOnlyPolicy() + { + if (infoOnlyPolicy == null) + infoOnlyPolicy = new ServantCachingPolicy( INFO_ONLY_SEMANTICS ) ; + + return infoOnlyPolicy ; + } + + public synchronized static ServantCachingPolicy getMinimalPolicy() + { + if (minimalPolicy == null) + minimalPolicy = new ServantCachingPolicy( MINIMAL_SEMANTICS ) ; + + return minimalPolicy ; + } + + public int policy_type () + { + return ORBConstants.SERVANT_CACHING_POLICY ; + } + + public org.omg.CORBA.Policy copy () + { + return this ; + } + + public void destroy () + { + // NO-OP + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/extension/ZeroPortPolicy.java b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/ZeroPortPolicy.java new file mode 100644 index 000000000..8e93e0e4a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/extension/ZeroPortPolicy.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.extension ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.LocalObject ; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** Policy used to implement zero IIOP port policy in the POA. +*/ +public class ZeroPortPolicy extends LocalObject implements Policy +{ + private static ZeroPortPolicy policy = new ZeroPortPolicy( true ) ; + + private boolean flag = true ; + + private ZeroPortPolicy( boolean type ) + { + this.flag = type ; + } + + public String toString() + { + return "ZeroPortPolicy[" + flag + "]" ; + } + + public boolean forceZeroPort() + { + return flag ; + } + + public synchronized static ZeroPortPolicy getPolicy() + { + return policy ; + } + + public int policy_type () + { + return ORBConstants.ZERO_PORT_POLICY ; + } + + public org.omg.CORBA.Policy copy () + { + return this ; + } + + public void destroy () + { + // NO-OP + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/folb/ClusterInstanceInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/ClusterInstanceInfo.java new file mode 100644 index 000000000..0aac95595 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/ClusterInstanceInfo.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.folb; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import java.io.Serializable ; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +/** + * + * @author ken + */ +public class ClusterInstanceInfo implements Serializable { + private final String name ; + private final int weight ; + private final List endpoints ; + + public ClusterInstanceInfo( InputStream is ) { + name = is.read_string() ; + weight = is.read_long() ; + int size = is.read_long() ; + List elist = new ArrayList( size ) ; + for (int ctr = 0; ctr endpoints) { + + this.name = name; + this.weight = weight; + this.endpoints = Collections.unmodifiableList( endpoints ) ; + } + + public List endpoints() { return endpoints ; } + public String name() { return name; } + public int weight() { return weight; } + + public void write( OutputStream os ) { + os.write_string( name ) ; + os.write_long( weight ); + os.write_long( endpoints.size() ) ; + for (SocketInfo si : endpoints) { + si.write( os ) ; + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "ClusterInstanceInfo[" ) ; + sb.append( "name=" ) ; + sb.append( name ) ; + sb.append( " weight=" ) ; + sb.append( weight ) ; + sb.append( " endpoints=" ) ; + sb.append( endpoints.toString() ) ; + sb.append( "]" ) ; + return sb.toString() ; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final ClusterInstanceInfo other = (ClusterInstanceInfo) obj; + + if ((this.name == null) ? + (other.name() != null) : + !this.name.equals(other.name())) { + + return false; + } + + if (this.weight != other.weight()) { + return false; + } + + if (this.endpoints != other.endpoints() && + (this.endpoints == null || + !this.endpoints.equals(other.endpoints()))) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 79 * hash + (this.name != null ? this.name.hashCode() : 0); + hash = 79 * hash + this.weight; + hash = 79 * hash + (this.endpoints != null ? this.endpoints.hashCode() : 0); + return hash; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/folb/GroupInfoService.java b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/GroupInfoService.java new file mode 100644 index 000000000..11f3a4b6f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/GroupInfoService.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 13 (Mon) 11:04:09 by Harold Carr. +// Last Modified : 2005 Aug 08 (Mon) 17:53:01 by Harold Carr. +// + +package com.sun.corba.ee.spi.folb; + +import java.util.List; + +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; + +/** + * @author Harold Carr + */ +public interface GroupInfoService +{ + /** + * Adds an observer that will receive a + * membershipChange + * invocation whenever the cluster membership changes. + * + * The + * membershipChange + * invocation tells the observer to call + * getClusterInstanceInfo + * to get info. + * + * @return true if the given observer is added. False otherwise. + */ + public boolean addObserver(GroupInfoServiceObserver x); + + /** + * Causes the + * membershipChange + * method to be called on each registered observer. + */ + public void notifyObservers(); + + /** + * This is a separate call + * (rather than info being passed in membershipChange) + * so we can identifier the adapter. + * + * The adapter identification is used in testing. + */ + public List getClusterInstanceInfo( + String[] adapterName); + + /** + * This is a separate call + * (rather than info being passed in membershipChange) + * so we can identifier the adapter. + * + * The adapter identification is used in testing. + */ + public List getClusterInstanceInfo( + String[] adapterName, List endpoints ); + + /** + * This method only used during testing. + */ + public boolean shouldAddAddressesToNonReferenceFactory( + String[] adapterName); + + /** + * This method only used during testing. + */ + public boolean shouldAddMembershipLabel (String[] adapterName); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/folb/GroupInfoServiceObserver.java b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/GroupInfoServiceObserver.java new file mode 100644 index 000000000..0f2662af3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/GroupInfoServiceObserver.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 13 (Mon) 11:04:09 by Harold Carr. +// Last Modified : 2005 Aug 08 (Mon) 17:59:49 by Harold Carr. +// + +package com.sun.corba.ee.spi.folb; + +/** + * @author Harold Carr + */ +public interface GroupInfoServiceObserver +{ + /** + * Called when the GroupInfoService that you register with + * has a change. You should call the GroupInfoService + * getClusterInstanceInfo method to get + * updated info. + */ + public void membershipChange(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/folb/SocketInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/SocketInfo.java new file mode 100644 index 000000000..bd94baa98 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/folb/SocketInfo.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.folb; + +import java.io.Serializable ; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +/** Class representing endpoint info for the ORB. + * + * @author ken + */ +public class SocketInfo implements Serializable { + private final String type ; + private final String host ; + private final int port ; + + public SocketInfo( InputStream is ) { + this.type = is.read_string() ; + this.host = is.read_string() ; + this.port = is.read_long() ; + } + + public SocketInfo( String type, String host, int port ) { + this.type = type ; + this.host = host ; + this.port = port ; + } + + public String type() { return type ; } + public String host() { return host ; } + public int port() { return port ; } + + public void write( OutputStream os ) { + os.write_string( type ) ; + os.write_string( host ) ; + os.write_long(port); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder() ; + sb.append( "SocketInfo[" ) ; + sb.append( "type=" ) ; + sb.append( type ) ; + sb.append( " host=" ) ; + sb.append( host ) ; + sb.append( " port=" ) ; + sb.append( port ) ; + sb.append( ']' ) ; + return sb.toString() ; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final SocketInfo other = (SocketInfo) obj; + + if ((this.type == null) ? (other.type() != null) + : !this.type.equals(other.type())) { + + return false; + } + + if ((this.host == null) ? (other.host() != null) + : !this.host.equals(other.host())) { + + return false; + } + + if (this.port != other.port()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 71 * hash + (this.type != null ? this.type.hashCode() : 0); + hash = 71 * hash + (this.host != null ? this.host.hashCode() : 0); + hash = 71 * hash + this.port; + return hash; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/EncapsulationFactoryBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/EncapsulationFactoryBase.java new file mode 100644 index 000000000..d642385d9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/EncapsulationFactoryBase.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.impl.ior.EncapsulationUtility ; + +public abstract class EncapsulationFactoryBase + implements IdentifiableFactory { + + private int id ; + + public int getId() + { + return id ; + } + + public EncapsulationFactoryBase( int id ) + { + this.id = id ; + } + + public final E create( ORB orb, InputStream in ) + { + InputStream is = EncapsulationUtility.getEncapsulationStream( orb, in ) ; + return readContents( is ) ; + } + + protected abstract E readContents( InputStream is ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IOR.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IOR.java new file mode 100644 index 000000000..88c634e3f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IOR.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import java.util.List ; +import java.util.Iterator ; + +import com.sun.corba.ee.spi.orb.ORBVersion ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.InheritedAttribute ; +import org.glassfish.gmbal.Description ; + +/** An IOR is represented as a list of profiles. +* Only instances of TaggedProfile are contained in the list. +*/ +@ManagedData +@Description( "Interoperable Object Reference: the internal structure of a remote object reference" ) +public interface IOR extends List, Writeable, MakeImmutable +{ + // This is used only for management + @ManagedAttribute + @Description( "The list of profiles in this IOR" ) + Iterator getTaggedProfiles() ; + + ORB getORB() ; + + /** Return the type id string from the IOR. + */ + @ManagedAttribute + @Description( "The repository ID of the IOR" ) + String getTypeId() ; + + /** Return an iterator that iterates over tagged profiles with + * identifier id. It is not possible to modify the list through this + * iterator. + */ + Iterator iteratorById( int id ) ; + + /** Return a representation of this IOR in the standard GIOP stringified + * format that begins with "IOR:". + */ + String stringify() ; + + /** Return a representation of this IOR in the standard GIOP marshalled + * form. + */ + org.omg.IOP.IOR getIOPIOR() ; + + /** Return true if this IOR has no profiles. + */ + boolean isNil() ; + + /** Return true if this IOR is equivalent to ior. Here equivalent means + * that the typeids are the same, they have the same number of profiles, + * and each profile is equivalent to the corresponding profile. + */ + boolean isEquivalent(IOR ior) ; + + /** Return the IORTemplate for this IOR. This is simply a list + * of all TaggedProfileTemplates derived from the TaggedProfiles + * of the IOR. + */ + IORTemplateList getIORTemplates() ; + + /** Return the first IIOPProfile in this IOR. + */ + IIOPProfile getProfile() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORFactories.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORFactories.java new file mode 100644 index 000000000..d359efa8f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORFactories.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import java.io.Serializable ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import org.omg.CORBA.BAD_PARAM ; +import org.omg.CORBA.portable.ValueFactory ; + +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.ObjectReferenceFactory ; + +import com.sun.corba.ee.impl.ior.ObjectIdImpl ; +import com.sun.corba.ee.impl.ior.ObjectKeyImpl ; +import com.sun.corba.ee.impl.ior.IORImpl ; +import com.sun.corba.ee.impl.ior.IORTemplateImpl ; +import com.sun.corba.ee.impl.ior.IORTemplateListImpl ; +import com.sun.corba.ee.impl.ior.ObjectReferenceProducerBase ; +import com.sun.corba.ee.impl.ior.ObjectReferenceFactoryImpl ; +import com.sun.corba.ee.impl.ior.ObjectReferenceTemplateImpl ; +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl ; + +import com.sun.corba.ee.impl.misc.ORBUtility ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** This class provides a number of factory methods for creating + * various IOR SPI classes which are not subclassed for specific protocols. + * The following types must be created using this class: + *
          + *
        • ObjectId
        • + *
        • ObjectKey
        • + *
        • IOR
        • + *
        • IORTemplate
        • + *
        + */ +public class IORFactories { + private IORFactories() {} + + /** Create an ObjectId for the given byte sequence. + */ + public static ObjectId makeObjectId( byte[] id ) + { + return new ObjectIdImpl( id ) ; + } + + /** Create an ObjectKey for the given ObjectKeyTemplate and + * ObjectId. + */ + public static ObjectKey makeObjectKey( ObjectKeyTemplate oktemp, ObjectId oid ) + { + return new ObjectKeyImpl( oktemp, oid ) ; + } + + /** Create an empty IOR for the given orb and typeid. The result is mutable. + */ + public static IOR makeIOR( ORB orb, String typeid ) + { + return new IORImpl( orb, typeid ) ; + } + + /** Create an empty IOR for the given orb with a null typeid. The result is mutable. + */ + public static IOR makeIOR( ORB orb ) + { + return new IORImpl( orb ) ; + } + + /** Read an IOR from an InputStream. ObjectKeys are not shared. + */ + public static IOR makeIOR( ORB orb, InputStream is ) + { + return new IORImpl( orb, is ) ; + } + + /** Create an IORTemplate with the given ObjectKeyTemplate. The result + * is mutable. + */ + public static IORTemplate makeIORTemplate( ObjectKeyTemplate oktemp ) + { + return new IORTemplateImpl( oktemp ) ; + } + + /** Read an IORTemplate from an InputStream. + */ + public static IORTemplate makeIORTemplate( InputStream is ) + { + return new IORTemplateImpl( is ) ; + } + + public static IORTemplateList makeIORTemplateList() + { + return new IORTemplateListImpl() ; + } + + public static IORTemplateList makeIORTemplateList( InputStream is ) + { + return new IORTemplateListImpl( is ) ; + } + + public static IORFactory getIORFactory( ObjectReferenceTemplate ort ) + { + if (ort instanceof ObjectReferenceTemplateImpl) { + ObjectReferenceTemplateImpl orti = + (ObjectReferenceTemplateImpl)ort ; + return orti.getIORFactory() ; + } + + throw new BAD_PARAM() ; + } + + public static IORTemplateList getIORTemplateList( ObjectReferenceFactory orf ) + { + if (orf instanceof ObjectReferenceProducerBase) { + ObjectReferenceProducerBase base = + (ObjectReferenceProducerBase)orf ; + return base.getIORTemplateList() ; + } + + throw new BAD_PARAM() ; + } + + public static ObjectReferenceTemplate makeObjectReferenceTemplate( ORB orb, + IORTemplate iortemp ) + { + return new ObjectReferenceTemplateImpl( orb, iortemp ) ; + } + + public static ObjectReferenceFactory makeObjectReferenceFactory( ORB orb, + IORTemplateList iortemps ) + { + return new ObjectReferenceFactoryImpl( orb, iortemps ) ; + } + + public static ObjectKeyFactory makeObjectKeyFactory( ORB orb ) + { + return new ObjectKeyFactoryImpl( orb ) ; + } + + public static org.omg.CORBA.Object makeObjectReference( IOR ior ) + { + return ORBUtility.makeObjectReference( ior ) ; + } + + /** This method must be called in order to register the value + * factories for the ObjectReferenceTemplate and ObjectReferenceFactory + * value types. + */ + public static void registerValueFactories( ORB orb ) + { + // Create and register the factory for the Object Reference Template + // implementation. + ValueFactory vf = new ValueFactory() { + public Serializable read_value( InputStream is ) + { + return new ObjectReferenceTemplateImpl( is ) ; + } + } ; + + orb.register_value_factory( ObjectReferenceTemplateImpl.repositoryId, vf ) ; + + // Create and register the factory for the Object Reference Factory + // implementation. + vf = new ValueFactory() { + public Serializable read_value( InputStream is ) + { + return new ObjectReferenceFactoryImpl( is ) ; + } + } ; + + orb.register_value_factory( ObjectReferenceFactoryImpl.repositoryId, vf ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORFactory.java new file mode 100644 index 000000000..6e98b7b04 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORFactory.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** An IORFactory provides the capability of creating IORs. It contains + * some collection of TaggedProfileTemplates, which can be iterated over + * for portable interceptors. + */ +public interface IORFactory extends Writeable, MakeImmutable { + /** Construct an IOR containing the given ORB, typeid, and ObjectId. + * The same ObjectId will be used for all TaggedProfileTemplates in + * the IORFactory. + */ + IOR makeIOR( ORB orb, String typeid, ObjectId oid ) ; + + /** Return true iff this.makeIOR(orb,typeid,oid).isEquivalent( + * other.makeIOR(orb,typeid,oid) for all orb, typeid, and oid. + */ + boolean isEquivalent( IORFactory other ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORTemplate.java new file mode 100644 index 000000000..efe616aae --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORTemplate.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import java.util.List ; +import java.util.Iterator ; + +/** An IORTemplate provides all of the data necessary to create an IOR except + * for the typeId and ObjectId. + */ +public interface IORTemplate extends List, + IORFactory, MakeImmutable +{ + /** Iterate over all TaggedProfileTemplates in this IORTemplate + * with the given id. + */ + Iterator iteratorById( int id ) ; + + ObjectKeyTemplate getObjectKeyTemplate() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORTemplateList.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORTemplateList.java new file mode 100644 index 000000000..f7cfb5260 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IORTemplateList.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import java.util.List ; + +/** An IORTemplateList is a list of IORTemplate instances. It can be used to create IORs. + * This is useful for representing IORs made of profiles from different object + * adapters. + * Note that any IORFactory can be added to an IORTemplateList, but it is flattened + * so that the result is just a list of IORTemplate instances. + */ +public interface IORTemplateList extends List, + IORFactory, MakeImmutable +{ +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IOR_classes.html b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IOR_classes.html new file mode 100644 index 000000000..489f44bf2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IOR_classes.html @@ -0,0 +1,399 @@ + + + + + + + IOR classes + + +
          +
        • Implementation hierarchies in the IOR code
        • +
            +
          • Utility classes:
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            impl.ior.ByteBufferclass used to speed up computation of the adapter id
            impl.ior.EncapsulationUtilitymisc. utilities for dealing with CDR encapsulation
            impl.ior.FreezableListspecial list class that can change from mutable to +immutable (one way only)
            impl.ior.MinorCodesminor codes for all IOR errors
            impl.ior.ORTImplwrapper around IORTemplate for ORT
            spi.ior.IORFactoriesfactory for all basic IOR types
            spi.ior.IIOP.IIOPFactories factory for IIOP IOR factory types +(IIOPProfile, IIOPProfileTemplate and all of the supported IIOP tagged +component factories). This needs to provide access to all of the +IdentifiableFactory instances we need for registration. It also needs +to provide factory methods for creating all of these types.
            +
          • +
          • Support for non-registered (unknown) TaggedComponent and +TaggedProfile instances
            +
              +
            • impl.ior.GenericIdEncapsulation
            • +
            • impl.ior.GenericTaggedComponent
            • +
            • impl.ior.GenericTaggedProfile
            • +
            +
          • +
          • Basic common representation for writing, getting ids, inherited +lists:
            +
              +
            • spi.ior.IdentifiableContainerBase
            • +
            • spi.ior.Writeable
            • +
            • spi.ior.Identifiable
            • +
                +
              • spi.ior.IdentifiableBase
              • +
              +
            +
          • +
          • Some basic IOR types and their implementation:
            +
              +
            • spi.ior.IOR (an IOR)
              +
            • +
                +
              • impl.ior.IORImpl
              • +
              +
            • spi.ior.IORTemplate (a template for creating IORs from an +ObjectId)
              +
            • +
            +
              +
                +
              • impl.ior.IORTemplateImpl
              • +
              +
            +
          • +
          • spi.ior.IdentifiableFactory
            +
          • +
          +
        +spi.ior.IdentifiableFactoryFinder (class used to find the factory from +an id) +
          +
            +
              +
            • impl.ior.IdentifiableFactoryFinderBase
            • +
            +
              +
                +
              • impl.ior.TaggedComponentFactoryFinderImpl
              • +
              • impl.ior.TaggedProfileFactoryFinderImpl
              • +
              +
            +
          • spi.ior.ObjectAdapterId (represents the name of an object +adapter on the wire)
          • +
              +
            • impl.ior.ObjectAdapterIdBase
              +
            • +
                +
              • impl.ior.ObjectAdapterIdArray
              • +
              • impl.ior.ObjectAdapterIdNumber
                +
              • +
              +
            +
          • spi.ior.ObjectId (represents the identity of an object +reference in its object adapter)
          • +
              +
            • impl.ior.ObjectIdImpl
            • +
            +
          • spi.ior.ObjectKey (ObjectKeyTemplate+ObjectId=ObjectKey)
            +
          • +
              +
            • impl.ior.ObjectKeyImpl
            • +
            +
          • ObjectKeyTemplate classes:
          • +
              +
            • impl.ior.ObjectKeyFactory
            • +
            • impl.ior.ObjectKeyTemplateFactory (should be in spi)
            • +
            • spi.ior.ObjectKeyTemplate
            • +
                +
              • impl.ior.WireObjectKeyTemplate
              • +
              • impl.ior.ObjectKeyTemplateBase
              • +
                  +
                • impl.ior.OldObjectKeyTemplateBase
                • +
                    +
                  • impl.ior.OldJIDLObjectKeyTemplate
                  • +
                  • impl.ior.OldPOAObjectKeyTemplate
                  • +
                  +
                • impl.ior.NewObjectKeyTemplateBase
                • +
                +
                  + + IOR classes +
                    +
                  • Implementation hierarchies in the IOR code
                  • +
                      +
                    • Utility classes:
                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      impl.ior.ByteBufferclass used to speed up computation of the +adapter id
                      impl.ior.EncapsulationUtilitymisc. utilities for dealing with CDR +encapsulation
                      impl.ior.FreezableListspecial list class that can change from +mutable to +immutable (one way only)
                      impl.ior.MinorCodesminor codes for all IOR errors
                      impl.ior.ORTImplwrapper around IORTemplate for ORT
                      spi.ior.IORFactoriesfactory for all basic IOR types
                      spi.ior.IIOP.IIOPFactories factory for IIOP IOR factory types +(IIOPProfile, IIOPProfileTemplate and all of the supported IIOP tagged +component factories). This needs to provide access to all of the +IdentifiableFactory instances we need for registration. It also needs +to provide factory methods for creating all of these types.
                      +
                    • +
                    • Support for non-registered (unknown) TaggedComponent +and +TaggedProfile instances
                      +
                        +
                      • impl.ior.GenericIdEncapsulation
                      • +
                      • impl.ior.GenericTaggedComponent
                      • +
                      • impl.ior.GenericTaggedProfile
                      • +
                      +
                    • +
                    • Basic common representation for writing, getting ids, +inherited +lists:
                      +
                        +
                      • spi.ior.IdentifiableContainerBase
                      • +
                      • spi.ior.Writeable
                      • +
                      • spi.ior.Identifiable
                      • +
                          +
                        • spi.ior.IdentifiableBase
                        • +
                        +
                      +
                    • +
                    • Some basic IOR types and their implementation:
                      +
                        +
                      • spi.ior.IOR (an IOR)
                        +
                      • +
                          +
                        • impl.ior.IORImpl
                        • +
                        +
                      • spi.ior.IORTemplate (a template for creating IORs +from an +ObjectId)
                        +
                      • +
                      +
                        +
                          +
                        • impl.ior.IORTemplateImpl
                        • +
                        +
                      +
                    • +
                    • spi.ior.IdentifiableFactory
                      +
                    • +
                    +
                  +spi.ior.IdentifiableFactoryFinder (class used to find the factory from +an id) +
                    +
                      +
                        +
                      • impl.ior.IdentifiableFactoryFinderBase
                      • +
                      +
                        +
                          +
                        • impl.ior.TaggedComponentFactoryFinderImpl
                        • +
                        • impl.ior.TaggedProfileFactoryFinderImpl
                        • +
                        +
                      +
                    • spi.ior.ObjectAdapterId (represents the name of an +object +adapter on the wire)
                    • +
                        +
                      • impl.ior.ObjectAdapterIdBase
                        +
                      • +
                          +
                        • impl.ior.ObjectAdapterIdArray
                        • +
                        • impl.ior.ObjectAdapterIdNumber
                          +
                        • +
                        +
                      +
                    • spi.ior.ObjectId (represents the identity of an +object +reference in its object adapter)
                    • +
                        +
                      • impl.ior.ObjectIdImpl
                      • +
                      +
                    • spi.ior.ObjectKey +(ObjectKeyTemplate+ObjectId=ObjectKey)
                      +
                    • +
                        +
                      • impl.ior.ObjectKeyImpl
                      • +
                      +
                    • ObjectKeyTemplate classes:
                    • +
                        +
                      • impl.ior.ObjectKeyFactory
                      • +
                      • impl.ior.ObjectKeyTemplateFactory (should be in spi)
                      • +
                      • spi.ior.ObjectKeyTemplate
                      • +
                          +
                        • impl.ior.WireObjectKeyTemplate
                        • +
                        • impl.ior.ObjectKeyTemplateBase
                        • +
                            +
                          • impl.ior.OldObjectKeyTemplateBase
                          • +
                              +
                            • impl.ior.OldJIDLObjectKeyTemplate
                            • +
                            • impl.ior.OldPOAObjectKeyTemplate
                            • +
                            +
                          • impl.ior.NewObjectKeyTemplateBase
                          • +
                          +
                            +
                          • impl.ior.JIDLObjectKeyTemplate
                          • +
                          • impl.ior.POAObjectKeyTemplate
                          • +
                          +
                        +
                      +
                    +
                      +
                    • IIOP types and their implementations:
                    • +
                        +
                      • spi.ior.TaggedComponent
                      • +
                      +
                        +
                          +
                        • spi.ior.TaggedComponentBase
                        • +
                        +
                      +
                        +
                          +
                            +
                          • impl.ior.iiop.AlternateIIOPAddressComponent
                          • +
                          • impl.ior.iiop.CodeSetsComponent
                          • +
                          • impl.ior.iiop.JavaCodebaseComponent
                          • +
                          • impl.ior.iiop.MaxStreamFormatVersionComponent
                          • +
                          • impl.ior.iiop.ORBTypeComponent
                          • +
                          • impl.ior.iiop.PoliciesComponent
                            +
                          • +
                          +
                        +
                      +
                    • spi.ior.TaggedProfile
                    • +
                        +
                      • spi.ior.iiop.IIOPProfile
                      • +
                      +
                        +
                      • impl.ior.iiop.IIOPProfileImpl
                      • +
                      • spi.ior.TaggedProfileTemplate
                        +spi.ior.iiop.IIOPProfileTemplate
                        +impl.ior.iiop.IIOPProfileTemplateImpl
                        +spi.ior.iiop.IIOPAddress
                        +impl.ior.iiop.IIOPAddressBase
                        +impl.ior.iiop.IIOPAddressFutureImpl
                        +        impl.ior.iiop.IIOPAddressImpl
                        +
                        +
                      • +
                      +
                    +
                  +
                +
              • impl.ior.JIDLObjectKeyTemplate
              • +
              • impl.ior.POAObjectKeyTemplate
              • +
              +
            +
          +
        +
          +
        • IIOP types and their implementations:
        • +
            +
          • spi.ior.TaggedComponent
          • +
          +
            +
              +
            • spi.ior.TaggedComponentBase
            • +
            +
          +
            +
              +
                +
              • impl.ior.iiop.AlternateIIOPAddressComponent
              • +
              • impl.ior.iiop.CodeSetsComponent
              • +
              • impl.ior.iiop.JavaCodebaseComponent
              • +
              • impl.ior.iiop.MaxStreamFormatVersionComponent
              • +
              • impl.ior.iiop.ORBTypeComponent
              • +
              • impl.ior.iiop.PoliciesComponent
                +
              • +
              +
            +
          +
        • spi.ior.TaggedProfile
        • +
            +
          • spi.ior.iiop.IIOPProfile
          • +
          +
            +
          • impl.ior.iiop.IIOPProfileImpl
          • +
          +
        • spi.ior.TaggedProfileTemplate
        • +
            +
          • spi.ior.iiop.IIOPProfileTemplate
          • +
              +
            • impl.ior.iiop.IIOPProfileTemplateImpl
              +
            • +
            +
          +
        • spi.ior.iiop.IIOPAddress
          +impl.ior.iiop.IIOPAddressBase
          +impl.ior.iiop.IIOPAddressFutureImpl
          +        impl.ior.iiop.IIOPAddressImpl
          +
          +
        • +
        + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/Identifiable.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/Identifiable.java new file mode 100644 index 000000000..67b28d601 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/Identifiable.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** This interface represents an entity that can be written to an + * OutputStream and has an identity that is represented by an integer. + * This identity is essentially the type of the entity, and is used in + * order to know how to read the entity back from an InputStream. + * @author Ken Cavanaugh + */ +public interface Identifiable extends Writeable +{ + /** Return the (type) identity of this entity. + * @return int + */ + @ManagedAttribute + @Description( "Id of tagged component or profile" ) + public int getId(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableBase.java new file mode 100644 index 000000000..89b6e01a4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableBase.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.Writeable ; +import com.sun.corba.ee.spi.ior.WriteContents ; +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.impl.ior.EncapsulationUtility ; + +/** Provide support for properly reading and writing Identifiable objects +* that are also encapsulations (tagged profiles and components). +*/ +public abstract class IdentifiableBase implements Identifiable, + WriteContents +{ + /** Write the data for this object as a CDR encapsulation. + * This is used for writing tagged components and profiles. + * These data types must be written out as encapsulations, + * which means that we need to first write the data out to + * an encapsulation stream, then extract the data and write + * it to os as an array of octets. + */ + final public void write( OutputStream os ) + { + EncapsulationUtility.writeEncapsulation( (WriteContents)this, os ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableContainerBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableContainerBase.java new file mode 100644 index 000000000..90db19d78 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableContainerBase.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import java.util.ArrayList; +import java.util.Iterator; + +import com.sun.corba.ee.impl.ior.FreezableList ; + +/** Convenience class for defining objects that contain lists of Identifiables. + * Mainly implements iteratorById. Also note that the constructor creates the + * list, which here is always an ArrayList, as this is much more efficient overall + * for short lists. + * @author Ken Cavanaugh + */ +public class IdentifiableContainerBase + extends FreezableList +{ + /** Create this class with an empty list of identifiables. + * The current implementation uses an ArrayList. + */ + public IdentifiableContainerBase() + { + super( new ArrayList() ) ; + } + + /** Return an iterator which iterates over all contained Identifiables + * with type given by id. + */ + public Iterator iteratorById( final int id) + { + return new Iterator() { + Iterator iter = + IdentifiableContainerBase.this.iterator() ; + E current = advance() ; + + private E advance() + { + while (iter.hasNext()) { + E ide = iter.next() ; + if (ide.getId() == id) + return ide ; + } + + return null ; + } + + public boolean hasNext() + { + return current != null ; + } + + public E next() + { + E result = current ; + current = advance() ; + return result ; + } + + public void remove() + { + iter.remove() ; + } + } ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableFactory.java new file mode 100644 index 000000000..66f1fef80 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableFactory.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.ior.Identifiable ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** Factory interface for creating Identifiables. + */ +public interface IdentifiableFactory { + /** Return the id of this factory, which is the id of the result + * of any create call. + */ + public int getId() ; + + /** Construct the appropriate Identifiable object with the + * given id from the InputStream is. + */ + public E create( ORB orb, InputStream in ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableFactoryFinder.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableFactoryFinder.java new file mode 100644 index 000000000..ec2633d5a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/IdentifiableFactoryFinder.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.InputStream ; + +/** Interface used to manage a group of related IdentifiableFactory instances. + * Factories can be registered, and invoked through a create method, which + * must be implemented to handle the case of no registered factory + * appropriately. + * @author Ken Cavanaugh + */ +public interface IdentifiableFactoryFinder +{ + /** If there is a registered factory for id, use it to + * read an Identifiable from is. Otherwise create an + * appropriate generic container, or throw an error. + * The type of generic container, or error behavior is + * a property of the implementation. + */ + E create(int id, InputStream is); + + /** Register a factory for the given id. + */ + void registerFactory( IdentifiableFactory factory ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/MakeImmutable.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/MakeImmutable.java new file mode 100644 index 000000000..198e2cedf --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/MakeImmutable.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +public interface MakeImmutable { + void makeImmutable() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectAdapterId.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectAdapterId.java new file mode 100644 index 000000000..32ea6aaf7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectAdapterId.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior ; + +import java.util.Iterator ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** This is the object adapter ID for an object adapter. +* Typically this is the path of strings starting from the +* Root POA to get to a POA, but other implementations are possible. +*/ +@ManagedData +@Description( "The identifier for a particular Object adapter in the ORB" ) +public interface ObjectAdapterId extends Iterable, Writeable { + /** Return the number of elements in the adapter ID. + */ + int getNumLevels() ; + + /** Return an iterator that iterates over the components + * of this adapter ID. Each element is returned as a String. + */ + @ManagedAttribute + @Description( "Sequence of strings in the ObjectAdapterId" ) + Iterator iterator() ; + + /** Get the adapter name simply as an array of strings. + */ + String[] getAdapterName() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectId.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectId.java new file mode 100644 index 000000000..a429c8e98 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectId.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * @author Ken Cavanaugh + */ +@ManagedData +@Description( "The ObjectId field within an ObjectKey in an IOR" ) +public interface ObjectId extends Writeable +{ + @ManagedAttribute( id = "Id" ) + @Description( "The actual bytes in the ObjectKey" ) + String getIdString() ; + + public byte[] getId() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKey.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKey.java new file mode 100644 index 000000000..723ded7ed --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKey.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; + +/** The full object key, which is contained in an IIOPProfile. +* The object identifier corresponds to the information passed into +* POA::create_reference_with_id and POA::create_reference +* (in the POA case). The template +* represents the information that is object adapter specific and +* shared across multiple ObjectKey instances. +*/ +public interface ObjectKey extends Writeable +{ + /** Return the object identifier for this Object key. + */ + ObjectId getId() ; + + /** Return the template for this object key. + */ + ObjectKeyTemplate getTemplate() ; + + byte[] getBytes( org.omg.CORBA.ORB orb ) ; + + ServerRequestDispatcher getServerRequestDispatcher() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKeyFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKeyFactory.java new file mode 100644 index 000000000..cb6be8430 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKeyFactory.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; + +/** Construct ObjectKey and ObjectKeyTemplate instances from their + * CDR-marshalled representation. + */ +public interface ObjectKeyFactory +{ + /** Create an ObjectKey from its octet sequence representation. + */ + ObjectKey create( byte[] key ) ; + + /** Create an ObjectKeyTemplate from its representation + * in an InputStream. + */ + ObjectKeyTemplate createTemplate( InputStream is ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKeyTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKeyTemplate.java new file mode 100644 index 000000000..667417e2f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/ObjectKeyTemplate.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** An ObjectKeyTemplate represents the part of an Object Key + * that corresponds to the object adapter used to create an + * object reference. The template is shared between many + * object references. + */ +@ManagedData +@Description( "The template used to represent all IORs created by the same Object adapter" ) +public interface ObjectKeyTemplate extends Writeable +{ + @ManagedAttribute + @Description( "The ORB version that created this template" ) + public ORBVersion getORBVersion() ; + + /** An ID used to determine how to perform operations on this + * ObjectKeyTemplate. This id determines how to process requests + * on this object reference, and what object adapter type to use. + */ + @ManagedAttribute + @Description( "The subcontract ID which identifies a particular type-independent " + + " implementation of an IOR" ) + public int getSubcontractId(); + + /** Return the server ID for this template. + * For CORBA 3.0, this should be a String, but it is currently + * an int in the object key template. + */ + @ManagedAttribute + @Description( "The ID of the server that handles requests to this IOR" ) + public int getServerId() ; + + /** Return the ORB ID for this template. + */ + @ManagedAttribute + @Description( "the ORB ID that created this IOR" ) + public String getORBId() ; + + /** Return the object adapter ID for this template. + */ + @ManagedAttribute + @Description( "The ObjectAdapterId that identifies the ObjectAdapter that created this IOR" ) + public ObjectAdapterId getObjectAdapterId() ; + + /** Compute an adapter ID for this template than includes + * all of the template information. + * This value is cached to avoid the expense of recomputing + * it. + */ + public byte[] getAdapterId() ; + + public void write(ObjectId objectId, OutputStream os); + + public ServerRequestDispatcher getServerRequestDispatcher( ObjectId id ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponent.java new file mode 100644 index 000000000..2c3ca4297 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA.ORB ; + +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent ; +import com.sun.corba.ee.spi.ior.iiop.CodeSetsComponent ; +import com.sun.corba.ee.spi.ior.iiop.JavaCodebaseComponent ; +import com.sun.corba.ee.spi.ior.iiop.MaxStreamFormatVersionComponent ; +import com.sun.corba.ee.spi.ior.iiop.ORBTypeComponent ; +import com.sun.corba.ee.spi.ior.iiop.RequestPartitioningComponent ; + +import com.sun.corba.ee.impl.ior.GenericTaggedComponent ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.IncludeSubclass ; + +/** Generic interface for all tagged components. Users of the ORB may +* create implementations of this class and also corresponding factories +* of type TaggedComponentFactory. The factories can be registered with an +* ORB instance, in which case they will be used to unmarshal IORs containing +* the registered tagged component. +*/ +@ManagedData +@Description( "Base class for all TaggedComponents" ) +@IncludeSubclass( { AlternateIIOPAddressComponent.class, + CodeSetsComponent.class, JavaCodebaseComponent.class, + MaxStreamFormatVersionComponent.class, ORBTypeComponent.class, + RequestPartitioningComponent.class, + GenericTaggedComponent.class } ) +public interface TaggedComponent extends Identifiable +{ + org.omg.IOP.TaggedComponent getIOPComponent( ORB orb ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponentBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponentBase.java new file mode 100644 index 000000000..9fee4e17b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponentBase.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.orb.ORB ; + + +/** Base class to use for implementing TaggedComponents. It implements + * the getIOPComponent method using the TaggedComponent.write() method. + * @author Ken Cavanaugh + */ +public abstract class TaggedComponentBase extends IdentifiableBase + implements TaggedComponent +{ + public org.omg.IOP.TaggedComponent getIOPComponent( + org.omg.CORBA.ORB orb ) + { + EncapsOutputStream os = OutputStreamFactory.newEncapsOutputStream( (ORB)orb ) ; + os.write_ulong( getId() ) ; // Fix for 6158378 + write( os ) ; + InputStream is = (InputStream)(os.create_input_stream() ) ; + return org.omg.IOP.TaggedComponentHelper.read( is ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponentFactoryFinder.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponentFactoryFinder.java new file mode 100644 index 000000000..39fbe9a6e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedComponentFactoryFinder.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +public interface TaggedComponentFactoryFinder + extends IdentifiableFactoryFinder +{ + /** Create a tagged component from a GIOP marshalled representation + * of a tagged component. This is needed for portable interceptors. + */ + TaggedComponent create( org.omg.CORBA.ORB orb, + org.omg.IOP.TaggedComponent comp ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfile.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfile.java new file mode 100644 index 000000000..99ae9966a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfile.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import com.sun.corba.ee.spi.orb.ORB ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.IncludeSubclass ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; + +/** TaggedProfile represents a tagged profile in an IOR. + * A profile contains all of the information necessary for an invocation. + * It contains one or more endpoints that may be used for an invocation. + * A TaggedProfile conceptually has three parts: A TaggedProfileTemplate, + * an ObjectKeyTemplate, and an ObjectId. + */ +@ManagedData +@Description( "A TaggedProfile contained in an IOR" ) +@IncludeSubclass( { com.sun.corba.ee.spi.ior.iiop.IIOPProfile.class } ) +public interface TaggedProfile extends Identifiable, MakeImmutable +{ + @ManagedAttribute + @Description( "Template for this TaggedProfile" ) + TaggedProfileTemplate getTaggedProfileTemplate() ; + + @ManagedAttribute + @Description( "The ObjectId used in the IIOPProfile in this IOR" ) + ObjectId getObjectId() ; + + @ManagedAttribute + @Description( "The template for the ObjectKey in the IIOPProfile in this IOR" ) + ObjectKeyTemplate getObjectKeyTemplate() ; + + ObjectKey getObjectKey() ; + + /** Return true is prof is equivalent to this TaggedProfile. + * This means that this and prof are indistinguishable for + * the purposes of remote invocation. Typically this means that + * the profile data is identical and both profiles contain exactly + * the same components (if components are applicable). + * isEquivalent( prof ) should imply that getObjectId().equals( + * prof.getObjectId() ) is true, and so is + * getObjectKeyTemplate().equals( prof.getObjectKeyTemplate() ). + */ + boolean isEquivalent( TaggedProfile prof ) ; + + /** Return the TaggedProfile as a CDR encapsulation in the standard + * format. This is required for Portable interceptors. + */ + org.omg.IOP.TaggedProfile getIOPProfile(); + + /** Return true if this TaggedProfile was created in orb. + * Caches the result. + */ + boolean isLocal() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfileTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfileTemplate.java new file mode 100644 index 000000000..7130163e3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfileTemplate.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +import java.util.List ; +import java.util.Iterator ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.Writeable ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.WriteContents ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.InheritedAttribute ; +import org.glassfish.gmbal.IncludeSubclass ; + +/** Base template for creating TaggedProfiles. A TaggedProfile will often contain +* tagged components. A template that does not contain components acts like +* an empty immutable list. +* +* @author Ken Cavanaugh +*/ +@ManagedData +@Description( "A template for creating a TaggedProfile" ) +@IncludeSubclass( { com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate.class } ) +public interface TaggedProfileTemplate extends List, + Identifiable, WriteContents, MakeImmutable +{ + @ManagedAttribute + @Description( "The list of TaggedComponents in this TaggedProfileTemplate" ) + public Iterator getTaggedComponents() ; + + /** Return an iterator that iterates over tagged components with + * identifier id. It is not possible to modify the list through this + * iterator. + */ + public Iterator iteratorById( int id ) ; + + public Iterator iteratorById( int id, + Class cls ) ; + + /** Create a TaggedProfile from this template. + */ + TaggedProfile create( ObjectKeyTemplate oktemp, ObjectId id ) ; + + /** Write the profile create( oktemp, id ) to the OutputStream os. + */ + void write( ObjectKeyTemplate oktemp, ObjectId id, OutputStream os) ; + + /** Return true if temp is equivalent to this template. Equivalence + * means that in some sense an invocation on a profile created by this + * template has the same results as an invocation on a profile + * created from temp. Equivalence may be weaker than equality. + */ + boolean isEquivalent( TaggedProfileTemplate temp ); + + /** Return the tagged components in this profile (if any) + * in the GIOP marshalled form, which is required for Portable + * Interceptors. Returns null if either the profile has no + * components, or if this type of profile can never contain + * components. + */ + org.omg.IOP.TaggedComponent[] getIOPComponents( + ORB orb, int id ); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfileTemplateBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfileTemplateBase.java new file mode 100644 index 000000000..65055b1f5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/TaggedProfileTemplateBase.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import java.util.Iterator ; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.impl.ior.EncapsulationUtility ; + +public abstract class TaggedProfileTemplateBase + extends IdentifiableContainerBase + implements TaggedProfileTemplate +{ + public void write( OutputStream os ) + { + EncapsulationUtility.writeEncapsulation( this, os ) ; + } + + public org.omg.IOP.TaggedComponent[] getIOPComponents( ORB orb, int id ) + { + int count = 0 ; + Iterator iter = iteratorById( id ) ; + while (iter.hasNext()) { + iter.next() ; + count++ ; + } + + org.omg.IOP.TaggedComponent[] result = new + org.omg.IOP.TaggedComponent[count] ; + + int index = 0 ; + iter = iteratorById( id ) ; + while (iter.hasNext()) { + TaggedComponent comp = iter.next() ; + result[index++] = comp.getIOPComponent( orb ) ; + } + + return result ; + } + + public Iterator iteratorById( int id, + Class cls ) { + + return (Iterator)iteratorById( id ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/WriteContents.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/WriteContents.java new file mode 100644 index 000000000..ab0c40830 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/WriteContents.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +public interface WriteContents { + void writeContents( OutputStream os ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/Writeable.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/Writeable.java new file mode 100644 index 000000000..700d410cd --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/Writeable.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +/** This interface represents an entity that can be written to an OutputStream. + * @author Ken Cavanaugh + */ +public interface Writeable +{ + /** Write this object directly to the output stream. + */ + void write(OutputStream arg0); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/AlternateIIOPAddressComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/AlternateIIOPAddressComponent.java new file mode 100644 index 000000000..20d0682fe --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/AlternateIIOPAddressComponent.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * @author Ken Cavanaugh + */ +@ManagedData +@Description( "Component containing an alternate IIOP address to use" ) +public interface AlternateIIOPAddressComponent extends TaggedComponent +{ + @ManagedAttribute + @Description( "The Alternate address" ) + public IIOPAddress getAddress() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/ClusterInstanceInfoComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/ClusterInstanceInfoComponent.java new file mode 100644 index 000000000..8baf3901c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/ClusterInstanceInfoComponent.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent; +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; + +public interface ClusterInstanceInfoComponent extends TaggedComponent +{ + public ClusterInstanceInfo getClusterInstanceInfo(); +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/CodeSetsComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/CodeSetsComponent.java new file mode 100644 index 000000000..146a99b35 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/CodeSetsComponent.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent ; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + + +/** + * @author Ken Cavanaugh + */ +@ManagedData +@Description( "The character codesets to be used for encoding " + + "strings sent to the object reference represented by " + + "this IOR" ) +public interface CodeSetsComponent extends TaggedComponent +{ + @ManagedAttribute + @Description( "The codeset component info" ) + // we'll just use toString() to represent this + public CodeSetComponentInfo getCodeSetComponentInfo() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/GIOPVersion.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/GIOPVersion.java new file mode 100644 index 000000000..4f4174a53 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/GIOPVersion.java @@ -0,0 +1,219 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +@ManagedData +@Description( "The maximum GIOP version supported by this IOR" ) +public class GIOPVersion { + + // Static fields + + public static final GIOPVersion V1_0 = new GIOPVersion((byte)1, (byte)0); + public static final GIOPVersion V1_1 = new GIOPVersion((byte)1, (byte)1); + public static final GIOPVersion V1_2 = new GIOPVersion((byte)1, (byte)2); + public static final GIOPVersion V1_3 = new GIOPVersion((byte)1, (byte)3); + + // Major version 13 is used to denote special encodings. + // Minor version 00 is unused. + // Minor version [01-FF] specifies Java serialization encoding version. + public static final GIOPVersion V13_XX = + new GIOPVersion((byte)13, (byte)ORBConstants.JAVA_ENC_VERSION); + + public static final GIOPVersion DEFAULT_VERSION = V1_2; + + public static final int VERSION_1_0 = 0x0100; + public static final int VERSION_1_1 = 0x0101; + public static final int VERSION_1_2 = 0x0102; + public static final int VERSION_1_3 = 0x0103; + public static final int VERSION_13_XX = + (13 << 8) | ORBConstants.JAVA_ENC_VERSION; + + // Instance variables + + private byte major = (byte) 0; + private byte minor = (byte) 0; + + // Constructor + + public GIOPVersion() {} + + public GIOPVersion(byte majorB, byte minorB) { + this.major = majorB; + this.minor = minorB; + } + + public GIOPVersion(int major, int minor) { + this.major = (byte)major; + this.minor = (byte)minor; + } + + // Accessor methods + + @ManagedAttribute + @Description( "The Major GIOP version (almost always 1)" ) + public byte getMajor() { + return this.major; + } + + @ManagedAttribute + @Description( "The Minor GIOP version (almost always 0, 1, or 2." + + " This ORB almost always uses 2" ) + public byte getMinor() { + return this.minor; + } + + // General methods + + public boolean equals(GIOPVersion gv){ + if (gv == null) { + return false ; + } + + return gv.major == this.major && gv.minor == this.minor ; + } + + public boolean equals(Object obj) { + if (obj != null && (obj instanceof GIOPVersion)) + return equals((GIOPVersion)obj); + else + return false; + } + + public int hashCode() + { + return 37*major + minor ; + } + + public boolean lessThan(GIOPVersion gv) { + if (this.major < gv.major) { + return true; + } else if (this.major == gv.major) { + if (this.minor < gv.minor) { + return true; + } + } + + return false; + } + + public int intValue() + { + return (major << 8 | minor); + } + + public String toString() + { + return major + "." + minor; + } + + public static GIOPVersion getInstance(byte major, byte minor) + { + switch(((major << 8) | minor)) { + case VERSION_1_0: + return GIOPVersion.V1_0; + case VERSION_1_1: + return GIOPVersion.V1_1; + case VERSION_1_2: + return GIOPVersion.V1_2; + case VERSION_1_3: + return GIOPVersion.V1_3; + case VERSION_13_XX: + return GIOPVersion.V13_XX; + default: + return new GIOPVersion(major, minor); + } + } + + public static GIOPVersion parseVersion(String s) + { + int dotIdx = s.indexOf('.'); + + if (dotIdx < 1 || dotIdx == s.length() - 1) + throw new NumberFormatException("GIOP major, minor, and decimal point required: " + s); + + int major = Integer.parseInt(s.substring(0, dotIdx)); + int minor = Integer.parseInt(s.substring(dotIdx + 1, s.length())); + + return GIOPVersion.getInstance((byte)major, (byte)minor); + } + + /** + * This chooses the appropriate GIOP version. + * + * @return smallest(profGIOPVersion, orbGIOPVersion). + */ + public static GIOPVersion chooseRequestVersion(ORB orb, IOR ior ) { + + GIOPVersion orbVersion = orb.getORBData().getGIOPVersion(); + IIOPProfile prof = ior.getProfile() ; + GIOPVersion profVersion = prof.getGIOPVersion(); + + // Check if the profile is from a legacy Sun ORB. + + ORBVersion targetOrbVersion = prof.getORBVersion(); + if (!(targetOrbVersion.equals(ORBVersionFactory.getFOREIGN())) && + targetOrbVersion.lessThan(ORBVersionFactory.getNEWER())) { + // we are dealing with a SUN legacy orb which emits 1.1 IORs, + // in spite of being able to handle only GIOP 1.0 messages. + return V1_0; + } + + // Now the target has to be (FOREIGN | NEWER*) + + byte prof_major = profVersion.getMajor(); + byte prof_minor = profVersion.getMinor(); + + byte orb_major = orbVersion.getMajor(); + byte orb_minor = orbVersion.getMinor(); + + if (orb_major < prof_major) { + return orbVersion; + } else if (orb_major > prof_major) { + return profVersion; + } else { // both major version are the same + if (orb_minor <= prof_minor) { + return orbVersion; + } else { + return profVersion; + } + } + } + + public boolean supportsIORIIOPProfileComponents() + { + return getMinor() > 0 || getMajor() > 1; + } + + // IO methods + + public void read(org.omg.CORBA.portable.InputStream istream) { + this.major = istream.read_octet(); + this.minor = istream.read_octet(); + } + + public void write(org.omg.CORBA.portable.OutputStream ostream) { + ostream.write_octet(this.major); + ostream.write_octet(this.minor); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPAddress.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPAddress.java new file mode 100644 index 000000000..85d45ff96 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPAddress.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.Writeable ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** IIOPAddress represents the host and port used to establish a + * TCP connection for an IIOP request. + */ +@ManagedData +@Description( "An IP address for the IIOP protocol" ) +public interface IIOPAddress extends Writeable +{ + @ManagedAttribute + @Description( "The target host (name or IP address)" ) + public String getHost() ; + + @ManagedAttribute + @Description( "The target port (0-65535)" ) + public int getPort() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPFactories.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPFactories.java new file mode 100644 index 000000000..3dc62a1a4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPFactories.java @@ -0,0 +1,270 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop ; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.IdentifiableFactory ; +import com.sun.corba.ee.spi.ior.EncapsulationFactoryBase ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo ; + +import com.sun.corba.ee.impl.encoding.MarshalInputStream ; + +import com.sun.corba.ee.impl.ior.iiop.IIOPAddressImpl ; +import com.sun.corba.ee.impl.ior.iiop.CodeSetsComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.AlternateIIOPAddressComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.JavaCodebaseComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.MaxStreamFormatVersionComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.JavaSerializationComponent; +import com.sun.corba.ee.impl.ior.iiop.ORBTypeComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.IIOPProfileImpl ; +import com.sun.corba.ee.impl.ior.iiop.IIOPProfileTemplateImpl ; +import com.sun.corba.ee.impl.ior.iiop.RequestPartitioningComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.LoadBalancingComponentImpl ; +import com.sun.corba.ee.impl.ior.iiop.ClusterInstanceInfoComponentImpl ; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS ; +import org.omg.IOP.TAG_CODE_SETS ; +import org.omg.IOP.TAG_JAVA_CODEBASE ; +import org.omg.IOP.TAG_RMI_CUSTOM_MAX_STREAM_FORMAT ; +import org.omg.IOP.TAG_ORB_TYPE ; +import org.omg.IOP.TAG_INTERNET_IOP ; + +/** This class provides all of the factories for the IIOP profiles and + * components. This includes direct construction of profiles and templates, + * as well as constructing factories that can be registered with an + * IdentifiableFactoryFinder. + */ +public abstract class IIOPFactories { + private IIOPFactories() {} + + public static IdentifiableFactory makeRequestPartitioningComponentFactory() + { + return new EncapsulationFactoryBase(ORBConstants.TAG_REQUEST_PARTITIONING_ID) { + public Identifiable readContents(InputStream in) + { + int threadPoolToUse = in.read_ulong(); + Identifiable comp = + new RequestPartitioningComponentImpl(threadPoolToUse); + return comp; + } + }; + } + + public static RequestPartitioningComponent makeRequestPartitioningComponent( + int threadPoolToUse) + { + return new RequestPartitioningComponentImpl(threadPoolToUse); + } + + public static IdentifiableFactory makeLoadBalancingComponentFactory() + { + return new EncapsulationFactoryBase(ORBConstants.TAG_LOAD_BALANCING_ID) { + public Identifiable readContents(InputStream in) + { + int loadBalancingValue = in.read_ulong(); + Identifiable comp = + new LoadBalancingComponentImpl(loadBalancingValue); + return comp; + } + }; + } + + public static LoadBalancingComponent makeLoadBalancingComponent( + int loadBalancingValue) + { + return new LoadBalancingComponentImpl(loadBalancingValue); + } + + public static IdentifiableFactory makeClusterInstanceInfoComponentFactory() + { + return new EncapsulationFactoryBase( + ORBConstants.FOLB_MEMBER_ADDRESSES_TAGGED_COMPONENT_ID) { + + public Identifiable readContents(InputStream in) + { + final ClusterInstanceInfo cinfo = new ClusterInstanceInfo( in ) ; + Identifiable comp = + new ClusterInstanceInfoComponentImpl(cinfo); + return comp; + } + }; + } + + public static ClusterInstanceInfoComponent makeClusterInstanceInfoComponent( + ClusterInstanceInfo cinfo) + { + return new ClusterInstanceInfoComponentImpl(cinfo); + } + + public static IdentifiableFactory makeAlternateIIOPAddressComponentFactory() + { + return new EncapsulationFactoryBase(TAG_ALTERNATE_IIOP_ADDRESS.value) { + public Identifiable readContents( InputStream in ) + { + IIOPAddress addr = new IIOPAddressImpl( in ) ; + Identifiable comp = + new AlternateIIOPAddressComponentImpl( addr ) ; + return comp ; + } + } ; + } + + public static AlternateIIOPAddressComponent makeAlternateIIOPAddressComponent( + IIOPAddress addr ) + { + return new AlternateIIOPAddressComponentImpl( addr ) ; + } + + public static IdentifiableFactory makeCodeSetsComponentFactory() + { + return new EncapsulationFactoryBase(TAG_CODE_SETS.value) { + public Identifiable readContents( InputStream in ) + { + return new CodeSetsComponentImpl( in ) ; + } + } ; + } + + public static CodeSetsComponent makeCodeSetsComponent( ORB orb ) + { + return new CodeSetsComponentImpl( orb ) ; + } + + public static IdentifiableFactory makeJavaCodebaseComponentFactory() + { + return new EncapsulationFactoryBase(TAG_JAVA_CODEBASE.value) { + public Identifiable readContents( InputStream in ) + { + String url = in.read_string() ; + Identifiable comp = new JavaCodebaseComponentImpl( url ) ; + return comp ; + } + } ; + } + + public static JavaCodebaseComponent makeJavaCodebaseComponent( + String codebase ) + { + return new JavaCodebaseComponentImpl( codebase ) ; + } + + public static IdentifiableFactory makeORBTypeComponentFactory() + { + return new EncapsulationFactoryBase(TAG_ORB_TYPE.value) { + public Identifiable readContents( InputStream in ) + { + int type = in.read_ulong() ; + Identifiable comp = new ORBTypeComponentImpl( type ) ; + return comp ; + } + } ; + } + + public static ORBTypeComponent makeORBTypeComponent( int type ) + { + return new ORBTypeComponentImpl( type ) ; + } + + public static IdentifiableFactory makeMaxStreamFormatVersionComponentFactory() + { + return new EncapsulationFactoryBase(TAG_RMI_CUSTOM_MAX_STREAM_FORMAT.value) { + public Identifiable readContents(InputStream in) + { + byte version = in.read_octet() ; + Identifiable comp = new MaxStreamFormatVersionComponentImpl(version); + return comp ; + } + }; + } + + public static MaxStreamFormatVersionComponent makeMaxStreamFormatVersionComponent() + { + return new MaxStreamFormatVersionComponentImpl() ; + } + + public static IdentifiableFactory makeJavaSerializationComponentFactory() { + return new EncapsulationFactoryBase( + ORBConstants.TAG_JAVA_SERIALIZATION_ID) { + public Identifiable readContents(InputStream in) { + byte version = in.read_octet(); + Identifiable cmp = new JavaSerializationComponent(version); + return cmp; + } + }; + } + + public static JavaSerializationComponent makeJavaSerializationComponent() { + return JavaSerializationComponent.singleton(); + } + + public static IdentifiableFactory makeIIOPProfileFactory() + { + return new EncapsulationFactoryBase(TAG_INTERNET_IOP.value) { + public Identifiable readContents( InputStream in ) + { + Identifiable result = new IIOPProfileImpl( in ) ; + return result ; + } + } ; + } + + public static IIOPProfile makeIIOPProfile( ORB orb, ObjectKeyTemplate oktemp, + ObjectId oid, IIOPProfileTemplate ptemp ) + { + return new IIOPProfileImpl( orb, oktemp, oid, ptemp ) ; + } + + public static IIOPProfile makeIIOPProfile( ORB orb, + org.omg.IOP.TaggedProfile profile ) + { + return new IIOPProfileImpl( orb, profile ) ; + } + + public static IdentifiableFactory makeIIOPProfileTemplateFactory() + { + return new EncapsulationFactoryBase(TAG_INTERNET_IOP.value) { + public Identifiable readContents( InputStream in ) + { + Identifiable result = new IIOPProfileTemplateImpl( in ) ; + return result ; + } + } ; + } + + public static IIOPProfileTemplate makeIIOPProfileTemplate( ORB orb, + GIOPVersion version, IIOPAddress primary ) + { + return new IIOPProfileTemplateImpl( orb, version, primary ) ; + } + + public static IIOPAddress makeIIOPAddress( String host, int port ) + { + return new IIOPAddressImpl( host, port ) ; + } + + public static IIOPAddress makeIIOPAddress( InputStream is ) + { + return new IIOPAddressImpl( is ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPProfile.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPProfile.java new file mode 100644 index 000000000..cc1cd9772 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPProfile.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedProfile ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; + +/** IIOPProfile represents an IIOP tagged profile. +* It is essentially composed of an object identifier and +* a template. The template contains all of the +* IIOP specific information in the profile. +* Templates are frequently shared between many different profiles, +* while the object identifiy is unique to each profile. +*/ +@ManagedData +@Description( "The IIOPProfile version of a TaggedProfile" ) +public interface IIOPProfile extends TaggedProfile +{ + @ManagedAttribute + @Description( "The ORB version in use" ) + ORBVersion getORBVersion() ; + + /** Return the servant for this profile, if it is local + * AND if the OA that implements this objref supports direct access to servants + * outside of an invocation. + */ + java.lang.Object getServant() ; + + /** Return the GIOPVersion of this profile. Caches the result. + */ + GIOPVersion getGIOPVersion() ; + + /** Return the Codebase of this profile. Caches the result. + */ + String getCodebase() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPProfileTemplate.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPProfileTemplate.java new file mode 100644 index 000000000..4c21a4a47 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/IIOPProfileTemplate.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * IIOPProfileTemplate represents the parts of an IIOPProfile that are independent + * of the object identifier. It is a container of tagged components. + */ +@ManagedData +@Description( "Template for an IIOP profile" ) +public interface IIOPProfileTemplate extends TaggedProfileTemplate +{ + /** Return the GIOP version of this profile. + */ + public GIOPVersion getGIOPVersion() ; + + /** Return the IIOP address from the IIOP profile. This is called the + * primary address here since other addresses may be contained in + * components. + */ + @ManagedAttribute + @Description( "The host and port of the IP address for the primary endpoint of this profile" ) + public IIOPAddress getPrimaryAddress() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/JavaCodebaseComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/JavaCodebaseComponent.java new file mode 100644 index 000000000..78f8dec6c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/JavaCodebaseComponent.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * @author Ken Cavanaugh + */ +@ManagedData +@Description( "Component representing Codebase URLs for downloading code" ) +public interface JavaCodebaseComponent extends TaggedComponent +{ + @ManagedAttribute + @Description( "List of URLs in the codebase" ) + public String getURLs() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/LoadBalancingComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/LoadBalancingComponent.java new file mode 100644 index 000000000..c50095ec0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/LoadBalancingComponent.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent; + +public interface LoadBalancingComponent extends TaggedComponent +{ + public int getLoadBalancingValue(); +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/MaxStreamFormatVersionComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/MaxStreamFormatVersionComponent.java new file mode 100644 index 000000000..00bbb2abe --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/MaxStreamFormatVersionComponent.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +// Java to IDL ptc 02-01-12 1.4.11 +// TAG_RMI_CUSTOM_MAX_STREAM_FORMAT +@ManagedData +@Description( "Component representing the maximum RMI-IIOP stream format " + + "version to be used with this IOR" ) +public interface MaxStreamFormatVersionComponent extends TaggedComponent +{ + @ManagedAttribute + @Description( "The maximum RMI-IIOP stream format version " + + "(usually 2)" ) + public byte getMaxStreamFormatVersion() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/ORBTypeComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/ORBTypeComponent.java new file mode 100644 index 000000000..499a89308 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/ORBTypeComponent.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * @author Ken Cavanaugh + */ +@ManagedData +@Description( "The ORB type" ) +public interface ORBTypeComponent extends TaggedComponent +{ + @ManagedAttribute + @Description( "The ORB type" ) + public int getORBType() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/RequestPartitioningComponent.java b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/RequestPartitioningComponent.java new file mode 100644 index 000000000..c4943e431 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iiop/RequestPartitioningComponent.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.ior.TaggedComponent; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +@ManagedData +@Description( "Component encoding request paritioning ID" ) +public interface RequestPartitioningComponent extends TaggedComponent +{ + @ManagedAttribute + @Description( "Request paritioning id (0-63); commonly 0" ) + public int getRequestPartitioningId(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iornotes.txt b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iornotes.txt new file mode 100644 index 000000000..382ea1b61 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/iornotes.txt @@ -0,0 +1,117 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Implementation hierarchies in the IOR code + +Utility classes: + impl.ior.ByteBuffer class used to speed up computation of the adapter id + impl.ior.EncapsulationUtility misc. utilities for dealing with CDR encapsulation + impl.ior.FreezableList special list class that can change from mutable to immutable (one way only) + impl.ior.MinorCodes minor codes for all IOR errors + impl.ior.ORTImpl wrapper around IORTemplate for ORT + spi.ior.IORFactories factory for all basic IOR types + spi.ior.IIOP.???Factories factory for IIOP IOR factory types (IIOPProfile, IIOPProfileTemplate, + and all of the supported IIOP tagged component factories) + This needs to provide access to all of the IdentifiableFactory instances + we need for registration. It also needs to provide factory methods for + creating all of these types. + impl.ior.iiop.TaggedComponentFactories needs to be absorbed here. + + +Support for non-registered (unknown) TaggedComponent and TaggedProfile instances + impl.ior.GenericIdEncapsulation + impl.ior.GenericTaggedComponent + impl.ior.GenericTaggedProfile + +Basic common representation for writing, getting ids, inherited lists: + spi.ior.IdentifiableContainerBase + spi.ior.Writeable + spi.ior.Identifiable + spi.ior.IdentifiableBase + +Some basic IOR types and their implementation: + spi.ior.IOR + impl.ior.IORImpl + + spi.ior.IORTemplate + impl.ior.IORTemplateImpl + + spi.ior.IdentifiableFactory (the basic factory type, which is never created in the spi.ior package. + All instances of this factory are necessarily protocol dependent, for example IIOP in the + spi.ior.iiop package). + spi.ior.IdentifiableFactoryFinder + impl.ior.IdentifiableFactoryFinderBase + impl.ior.TaggedComponentFactoryFinderImpl + impl.ior.TaggedProfileFactoryFinderImpl + + spi.ior.ObjectAdapterId + impl.ior.ObjectAdapterIdBase + impl.ior.ObjectAdapterIdArray + impl.ior.ObjectAdapterIdNumber + + spi.ior.ObjectId + impl.ior.ObjectIdImpl + + spi.ior.ObjectKey + impl.ior.ObjectKeyImpl + +The ObjectKeyTemplate family, which needs some work for pluggability yet: + impl.ior.ObjectKeyFactory + impl.ior.ObjectKeyTemplateFactory : should this be in the SPI? + spi.ior.ObjectKeyTemplate + impl.ior.WireObjectKeyTemplate + impl.ior.ObjectKeyTemplateBase + impl.ior.OldObjectKeyTemplateBase + impl.ior.OldJIDLObjectKeyTemplate + impl.ior.OldPOAObjectKeyTemplate + impl.ior.NewObjectKeyTemplateBase + impl.ior.JIDLObjectKeyTemplate + impl.ior.POAObjectKeyTemplate + +IIOP types and their implementations: + spi.ior.TaggedComponent + spi.ior.TaggedComponentBase + impl.ior.iiop.AlternateIIOPAddressComponent + impl.ior.iiop.CodeSetsComponent + impl.ior.iiop.JavaCodebaseComponent + impl.ior.iiop.MaxStreamFormatVersionComponent + impl.ior.iiop.ORBTypeComponent + impl.ior.iiop.PoliciesComponent + + spi.ior.TaggedProfile + spi.ior.iiop.IIOPProfile + impl.ior.iiop.IIOPProfileImpl + + spi.ior.TaggedProfileTemplate + spi.ior.iiop.IIOPProfileTemplate + impl.ior.iiop.IIOPProfileTemplateImpl + + spi.ior.iiop.IIOPAddress + impl.ior.iiop.IIOPAddressBase + impl.ior.iiop.IIOPAddressFutureImpl + impl.ior.iiop.IIOPAddressImpl + +Issues: + +1. GIOPVersion.chooseRequestVersion( ORB, IOR ) is not well-defined: it should be + (ORB, IIOPProfile). + Call sites: + Connection.locate: not used + Called from GIOPImpl.locate: not used + CorbaContactInfoImpl.createMessageMediator + This needs a version that looks only at a single profile. + +2. MessageBase.createRequest takes an IOR instead of an IIOPProfile. + +3. CDRInputStream_1_0.read_Object( Class ) calls IOR.getCodebase() in + a call to Utility.loadStubClass, which is + only defined on a profile. What do we do here? + Similar problem in same class internalIORToObject, which call IOR.getServant + and IOR.getCodebase. IOR.getCodeBase is called in loadStub. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/ior/package.html b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/package.html new file mode 100644 index 000000000..3f8cedf21 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/ior/package.html @@ -0,0 +1,49 @@ + + + + + + + +

        +Provides access to the components and profiles in an IOR without the overhead +of CDR encoding. +

        +The abstract model of IORs works as follows: + +

          +
        • An IOR has a type ID string, and contains TaggedProfile instances.
        • +
        • An IIOPProfile isA TaggedProfile.
        • +
        • An IIOPProfile is composed of an IIOPProfileTemplate and an object ID.
        • +
        • An IIOPProfileTemplate has an ObjectKeyTemplate, and contains TaggedComponents.
        • +
        • A TaggedComponent has an ID, and can be written to an OuputStream.
        • +
        • A TaggedComponentFactory reads a TaggedComponent from an InputStream.
        • +
        +

        +In all cases, containment is represented by having the appropriate interface (IOR and +IIOPProfileTemplate above) extend java.util.List. This makes it easy to use all of the +facilities in the Java collections framework with IORs. However, note that all +objects available through these APIs are immutable. Thus all list update operations +through UnsupportedOperationException, and list iterators cannot modify the underlying +list. +

        +Templates are used because the basic object adapter model for object creation is to +establish all properties of an IOR (except for type and object ID) when the object +adapter is created. This has been present for the POA essentially from the beginning, +since policies can only be passed to create_POA, and cannot be changed on an existing +POA. The Portable Interceptors work has also made this clear, since the IOR interceptor +runs only when an object adapter is created, which is the only time that user code +can add tagged components to an IOR. + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/Connection.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/Connection.java new file mode 100644 index 000000000..109c8e6b7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/Connection.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.connection; + +/** + * This interface represents the connection on which a request is made. + */ + +public interface Connection +{ + public java.net.Socket getSocket(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/GetEndPointInfoAgainException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/GetEndPointInfoAgainException.java new file mode 100644 index 000000000..eacbc52dc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/GetEndPointInfoAgainException.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.connection; + +import com.sun.corba.ee.spi.transport.SocketInfo; + +/** + * This exception is raised by ORBSocketFactory.createSocket. + * It informs the ORB that it should call + * ORBSocketFactory.getEndPointInfo again with the + * given socketInfo object as an argument (i.e., a cookie). + * + */ + +public class GetEndPointInfoAgainException + extends Exception +{ + private SocketInfo socketInfo; + + public GetEndPointInfoAgainException(SocketInfo socketInfo) + { + this.socketInfo = socketInfo; + } + + public SocketInfo getEndPointInfo() + { + return socketInfo; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/LegacyServerSocketEndPointInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/LegacyServerSocketEndPointInfo.java new file mode 100644 index 000000000..0d80ff8dc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/LegacyServerSocketEndPointInfo.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.connection; + +/** + * LegacyServerSocketEndPointInfo is an abstraction of a port. + */ +public interface LegacyServerSocketEndPointInfo +{ + /** + * e.g.: "CLEAR_TEXT", "SSL", ... + */ + public String getType(); + + + /** + * Get the host name of this end point. Subcontracts must use this + * instead of InetAddress.getHostName() because this would take + * into account the value of the ORBServerHost property. + */ + public String getHostName(); + + public int getPort(); + + /** + * The ORBD's proxy port of this end point. + * Note: Pre-ORT "port-exchange" model. + */ + public int getLocatorPort(); + public void setLocatorPort(int port); + + // NAME is used while we still have a "port-exchange" ORBD + // to get what used to be called "default" or "bootstrap" endpoints. + + public static final String DEFAULT_ENDPOINT = "DEFAULT_ENDPOINT"; + public static final String BOOT_NAMING = "BOOT_NAMING"; + public static final String NO_NAME = "NO_NAME"; + + public String getName(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/LegacyServerSocketManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/LegacyServerSocketManager.java new file mode 100644 index 000000000..ac3f57a09 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/LegacyServerSocketManager.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.connection; + +/** + * @author Harold Carr + */ +public interface LegacyServerSocketManager +{ + public int legacyGetTransientServerPort(String type); + public int legacyGetPersistentServerPort(String socketType); + public int legacyGetTransientOrPersistentServerPort(String socketType); + + public LegacyServerSocketEndPointInfo legacyGetEndpoint(String name); + + public boolean legacyIsLocalServerPort(int port); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/ORBSocketFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/ORBSocketFactory.java new file mode 100644 index 000000000..005b2fb98 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/ORBSocketFactory.java @@ -0,0 +1,345 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.connection; + +import java.net.ServerSocket; +import java.net.Socket; +import java.io.IOException; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.transport.SocketInfo; + +/** + * + * DEPRECATED. DEPRECATED. DEPRECATED. DEPRECATED.

        + * DEPRECATED. DEPRECATED. DEPRECATED. DEPRECATED.

        + * + * This interface gives one the ability to plug in their own socket + * factory class to an ORB.

        + * + * Usage:

        + * + * One specifies a class which implements this interface via the + * + * ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY + * + * property.

        + * + * Example:

        + + *

        + *   -Dcom.sun.corba.ee.connection.ORBSocketFactoryClass=MySocketFactory
        + * 

        + * + * Typically one would use the same socket factory class on both the + * server side and the client side (but this is not required).

        + * + * A ORBSocketFactory class should have a public default + * constructor which is called once per instantiating ORB.init call. + * That ORB then calls the methods of that ORBSocketFactory + * to obtain client and server sockets.

        + * + * This interface also supports multiple server end points. See the + * documentation on createServerSocket below. + * + */ + +public interface ORBSocketFactory +{ + /** + * DEPRECATED. DEPRECATED. DEPRECATED. DEPRECATED.

        + * + * A server ORB always creates an "IIOP_CLEAR_TEXT" listening port. + * That port is put into IOP profiles of object references exported + * by an ORB.

        + * + * If + * + * createServerSocket(String type, int port) + * + * is passed IIOP_CLEAR_TEXT as a type + * argument it should then call and return + * + * new java.net.ServerSocket(int port)

        + * + * If + * + * createSocket(SocketInfo socketInfo) + * + * is passed IIOP_CLEAR_TEXT in + * socketInfo.getType() it should + * then call and return + * + *

        +     *     new java.net.Socket(socketInfo.getHost(),
        +     *                         socketInfo.getPort())
        +     * 
        + * + */ + public static final String IIOP_CLEAR_TEXT = "IIOP_CLEAR_TEXT"; + + + /** + * DEPRECATED. DEPRECATED. DEPRECATED. DEPRECATED.

        + * + * This method is used by a server side ORB.

        + * + * When an ORB needs to create a listen socket on which connection + * requests are accepted it calls + * + * createServerSocket(String type, int port). + * + * The type argument says which type of socket should be created.

        + * + * The interpretation of the type argument is the responsibility of + * an instance of ORBSocketFactory, except in the case + * of IIOP_CLEAR_TEXT, in which case a standard server + * socket should be created.

        + * + * + * Multiple Server Port API:

        + * + * In addition to the IIOP_CLEAR_TEXT listening port, it is possible + * to specify that an ORB listen on additional port of specific types.

        + * + * This API allows one to specify that an ORB should create an X, + * or an X and a Y listen socket.

        + * + * If X, to the user, means SSL, then one just plugs in an SSL + * socket factory.

        + * + * Or, another example, if X and Y, to the user, means SSL without + * authentication and SSL with authentication respectively, then they + * plug in a factory which will either create an X or a Y socket + * depending on the type given to + * + * createServerSocket(String type, int port).

        + * + * One specifies multiple listening ports (in addition to the + * default IIOP_CLEAR_TEXT port) using the + * + * ORBConstants.LISTEN_SOCKET_PROPERTY + * + * property.

        + * + * Example usage:

        + * + *

        +     *    ... \ 
        +     *    -Dcom.sun.corba.ee.connection.ORBSocketFactoryClass=com.my.MySockFact \
        +     *    -Dcom.sun.corba.ee.connection.ORBListenSocket=SSL:0,foo:1 \
        +     *    ... 
        +     * 
        + * + * The meaning of the "type" (SSL and foo above) is controlled + * by the user.

        + * + * ORBListenSocket is only meaningful for servers.

        + * + * The property value is interpreted as follows. For each + * type/number pair:

        + * + * If number is 0 then use an emphemeral port for the listener of + * the associated type.

        + * + * If number is greater then 0 use that port number.

        + * + * An ORB creates a listener socket for each type + * specified by the user by calling + * + * createServerSocket(String type, int port) + * + * with the type specified by the user.

        + * + * After an ORB is initialized and the RootPOA has been resolved, + * it is then listening on + * all the end points which were specified. It may be necessary + * to add this additional end point information to object references + * exported by this ORB.

        + * + * Each object reference will contain the ORB's default IIOP_CLEAR_TEXT + * end point in its IOP profile. To add additional end point information + * (i.e., an SSL port) to an IOR (i.e., an object reference) one needs + * to intercept IOR creation using + * an PortableInterceptor::IORInterceptor.

        + * + * Using PortableInterceptors (with a non-standard extension):

        + * + * Register an IORInterceptor. Inside its + * establish_components operation: + * + *

        +     *
        +     * com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt ext;
        +     * ext = (com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt)info;
        +     *
        +     * int port = ext.getServerPort("myType");
        +     *
        +     * 
        + * + * Once you have the port you may add information to references + * created by the associated adapter by calling + * + * IORInfo::add_ior_component

        + * + * + * Note: if one is using a POA and the lifespan policy of that + * POA is persistent then the port number returned + * by getServerPort may + * be the corresponding ORBD port, depending on whether the POA/ORBD + * protocol is the present port exchange or if, in the future, + * the protocol is based on object reference template exchange. + * In either + * case, the port returned will be correct for the protocol. + * (In more detail, if the port exchange protocol is used then + * getServerPort will return the ORBD's port since the port + * exchange happens before, at ORB initialization. + * If object reference + * exchange is used then the server's transient port will be returned + * since the templates are exchanged after adding components.)

        + * + * + * Persistent object reference support:

        + * + * When creating persistent object references with alternate + * type/port info, ones needs to configure the ORBD to also support + * this alternate info. This is done as follows:

        + * + * - Give the ORBD the same socket factory you gave to the client + * and server.

        + * + * - specify ORBListenSocket ports of the same types that your + * servers support. You should probably specify explicit port + * numbers for ORBD if you embed these numbers inside IORs.

        + * + * Note: when using the port exchange protocol + * the ORBD and servers will exchange port + * numbers for each given type so they know about each other. + * When using object reference template exchange the server's + * transient ports are contained in the template.

        + * + * + * - specify your BadServerIdHandler (discussed below) + * using the + * + * ORBConstants.BAD_SERVER_ID_HANDLER_CLASS_PROPERTY

        + * + * Example:

        + * + *

        +     *
        +     * -Dcom.sun.corba.ee.POA.ORBBadServerIdHandlerClass=corba.socketPersistent.MyBadServerIdHandler
        +     *
        +     * 
        + * + * The BadServerIdHandler ...

        + * + * See com.sun.corba.ee.impl.activation.ServerManagerImpl.handle + * for example code on writing a bad server id handler. NOTE: This + * is an unsupported internal API. It will not exist in future releases. + *

        + * + * + * Secure connections to other services:

        + * + * If one wants secure connections to other services such as + * Naming then one should configure them with the same + * + * SOCKET_FACTORY_CLASS_PROPERTY and + * LISTEN_SOCKET_PROPERTY + * + * as used by other clients and servers in your distributed system.

        + * + */ + public ServerSocket createServerSocket(String type, int port) + throws + IOException; + + + + /** + * DEPRECATED. DEPRECATED. DEPRECATED. DEPRECATED.

        + * + * This method is used by a client side ORB.

        + * + * Each time a client invokes on an object reference, the reference's + * associated ORB will call + * + *

        +     *    getEndPointInfo(ORB orb, 
        +     *                    IOR ior,
        +     *                    SocketInfo socketInfo)
        +     * 
        + * + * NOTE: The type of the ior argument is an internal + * representation for efficiency. If the ORBSocketFactory + * interface ever becomes standardized then the ior will + * most likely change to a standard type (e.g., a stringified ior, + * an org.omg.IOP.IOR, or ...).

        + * + * Typically, this method will look at tagged components in the + * given ior to determine what type of socket to create.

        + * + * Typically, the ior will contain a tagged component + * specifying an alternate port type and number.

        + * + * This method should return an SocketInfo object + * containing the type/host/port to be used for the connection. + * + * If there are no appropriate tagged components then this method + * should return an SocketInfo object with the type + * IIOP_CLEAR_TEXT and host/port from the ior's IOP + * profile.

        + * + * If the ORB already has an existing connection to the returned + * type/host/port, then that connection is used. Otherwise the ORB calls + * + * createSocket(SocketInfo socketInfo)

        + * + * The orb argument is useful for handling + * the ior argument.

        + * + * The SocketInfo given to getEndPointInfo + * is either null or an object obtained + * from GetEndPointInfoAgainException

        + * + */ + public SocketInfo getEndPointInfo(org.omg.CORBA.ORB orb, + IOR ior, + SocketInfo socketInfo); + + + /** + * DEPRECATED. DEPRECATED. DEPRECATED. DEPRECATED.

        + * + * This method should return a client socket of the given + * type/host/port.

        + * + * Note: the SocketInfo is the same instance as was + * returned by getSocketInfo so extra cookie info may + * be attached.

        + * + * If this method throws GetEndPointInfoAgainException then the + * ORB calls getEndPointInfo again, passing it the + * SocketInfo object contained in the exception.

        + * + */ + public Socket createSocket(SocketInfo socketInfo) + throws + IOException, + GetEndPointInfoAgainException; +} + +// End of file. + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/README.txt b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/README.txt new file mode 100644 index 000000000..21a01c899 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/connection/README.txt @@ -0,0 +1,68 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Summary and suggested reading order: + +============================================================================== +Connection interceptor (called an ORBSocketFactory): + +Summary: + +The server side part of the ORBSocketFactory is told the type to +create as well as a port number. + +The client side part of the ORBSocketFactory is called on every client +request. An ORB first asks the factory for type/host/port information +(given an IOR). If the ORB already has a connection of the +type/host/port it will use the existing connection. Otherwise it will +then ask the factory to create a client socket, giving it that +type/host/port. Finally, the createSocket method may throw an +exception to tell the ORB to ask it for type/host/port info again. +The information passed back and forth between the ORB and factory can +act as a cookie for the factory if desired. + +Interfaces: + + com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory + com.sun.corba.ee.spi.legacy.connection.EndPointInfo + com.sun.corba.ee.spi.legacy.connection.GetEndPointInfoAgainException + +============================================================================== +Access to a request's socket: + +Summary: + +The request's socket is available via ClientRequestInfo and +ServerRequestInfo. We enable this by having them implement the +RequestInfoExt interface. + +Interfaces: + + com.sun.corba.ee.spi.legacy.interceptor.RequestInfoExt + com.sun.corba.ee.spi.legacy.connection.Connection + +============================================================================== +Extending IORInfo to support the multiple server port API: + +Summary: + +We support the multiple server port API in PortableInterceptors by +having IORInfo implement the IORInfoExt interface. The description on +how to use the multiple server port APIs is found in +ORBSocketFactory.java. + +Interfaces: + + com.sun.corba.ee.spi.legacy.interceptor.IORInfoExt + com.sun.corba.ee.spi.legacy.interceptor.UnknownType + +;; End. + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/IORInfoExt.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/IORInfoExt.java new file mode 100644 index 000000000..4c3fab022 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/IORInfoExt.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.interceptor; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; + +public interface IORInfoExt +{ + public int getServerPort(String type) + throws + UnknownType; + + public ObjectAdapter getObjectAdapter(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/ORBInitInfoExt.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/ORBInitInfoExt.java new file mode 100644 index 000000000..210f4d176 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/ORBInitInfoExt.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.interceptor; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** The interface defines an extension to the standard ORBInitInfo + * that gives access to the ORB being initialized. Interceptors run + * as the last stage of initialization of the ORB, so the ORB + * instance returned by getORB is fully initialized. Note that + * this facility eventually shows up post-CORBA 3.0 as a result + * of the resolution of OMG core issue on accessing the ORB from + * local objects. + */ +public interface ORBInitInfoExt +{ + ORB getORB() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/RequestInfoExt.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/RequestInfoExt.java new file mode 100644 index 000000000..4c0012991 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/RequestInfoExt.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.interceptor; + +import com.sun.corba.ee.spi.legacy.connection.Connection; + +/** + * This interface is implemented by our implementation of + * PortableInterceptor.ClientRequestInfo and + * PortableInterceptor.ServerRequestInfo.

        + * + */ + +public interface RequestInfoExt +{ + /** + * @return The connection on which the request is made. + * The return value will be null when a local transport + * is used. + */ + public Connection connection(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/ServerRequestInfoExt.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/ServerRequestInfoExt.java new file mode 100644 index 000000000..57ffd884c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/ServerRequestInfoExt.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.interceptor; + +/** This extension is used to provide information about whether or not + * the object to which the incoming request is dispatched is a name service + * or not. This is added to the implementation of the PortableInterceptor + * ServerRequestInfo interface (see impl.interceptors.ServerRequestInfoImpl) + * to provide this extended functionality). + * + * @author ken + */ +public interface ServerRequestInfoExt { + boolean isNameService() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/UnknownType.java b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/UnknownType.java new file mode 100644 index 000000000..c9cbe58be --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/legacy/interceptor/UnknownType.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.legacy.interceptor; + +public class UnknownType + extends + Exception +{ + public UnknownType() + { + super(); + } + + public UnknownType(String msg) + { + super(msg); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CS.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CS.java new file mode 100644 index 000000000..0b9d19e50 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CS.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logex.corba ; + +/** + * + * @author ken + */ +import java.lang.annotation.Documented ; +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** This annotation is applied to a method to indicate what CompletionStatus to use + * for creating a CORBA exception. It is an error to apply this annotation to a method + * that does not return a subclass of SystemException. + */ +@Documented +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface CS { + /** The CORBA CompletionStatus to be used for this method. + * Can only be used for a method that returns a subclass of SystemException. + */ + CSValue value() default CSValue.NO ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CSValue.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CSValue.java new file mode 100644 index 000000000..f29bf4b62 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CSValue.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logex.corba ; + +import org.omg.CORBA.CompletionStatus ; + +/** Enum corresponding to CompletionStatus that can be used in annotations. + * + * @author ken + */ +public enum CSValue { + YES() { + @Override + public CompletionStatus getCompletionStatus() { + return CompletionStatus.COMPLETED_YES ; + } + }, + + NO { + @Override + public CompletionStatus getCompletionStatus() { + return CompletionStatus.COMPLETED_NO ; + } + }, + + MAYBE { + @Override + public CompletionStatus getCompletionStatus() { + return CompletionStatus.COMPLETED_MAYBE ; + } + } ; + + public abstract CompletionStatus getCompletionStatus() ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CorbaExtension.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CorbaExtension.java new file mode 100644 index 000000000..1efad4a04 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/CorbaExtension.java @@ -0,0 +1,247 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logex.corba ; + +import com.sun.corba.ee.spi.logex.stdcorba.StandardLogger; +import com.sun.corba.ee.org.omg.CORBA.SUNVMCID; +import java.lang.reflect.Constructor; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; + +import org.omg.CORBA.ACTIVITY_COMPLETED; +import org.omg.CORBA.ACTIVITY_REQUIRED; +import org.omg.CORBA.BAD_CONTEXT; +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.BAD_QOS; +import org.omg.CORBA.BAD_TYPECODE; +import org.omg.CORBA.CODESET_INCOMPATIBLE; +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.DATA_CONVERSION; +import org.omg.CORBA.FREE_MEM; +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.INTF_REPOS; +import org.omg.CORBA.INVALID_ACTIVITY; +import org.omg.CORBA.INVALID_TRANSACTION; +import org.omg.CORBA.INV_FLAG; +import org.omg.CORBA.INV_IDENT; +import org.omg.CORBA.INV_OBJREF; +import org.omg.CORBA.INV_POLICY; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.NO_MEMORY; +import org.omg.CORBA.NO_PERMISSION; +import org.omg.CORBA.NO_RESOURCES; +import org.omg.CORBA.NO_RESPONSE; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.OBJ_ADAPTER; +import org.omg.CORBA.OMGVMCID; +import org.omg.CORBA.PERSIST_STORE; +import org.omg.CORBA.REBIND; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TIMEOUT; +import org.omg.CORBA.TRANSACTION_REQUIRED; +import org.omg.CORBA.TRANSACTION_ROLLEDBACK; +import org.omg.CORBA.TRANSACTION_UNAVAILABLE; +import org.omg.CORBA.TRANSIENT; +import org.omg.CORBA.UNKNOWN; + +public class CorbaExtension extends StandardLogger { + public static final CorbaExtension self = new CorbaExtension() ; + + private CorbaExtension() {} + + public static final int ORBUtilGroup = 0 ; + public static final int ActivationGroup = 1 ; + public static final int NamingGroup = 2 ; + public static final int InterceptorsGroup = 3 ; + public static final int POAGroup = 4 ; + public static final int IORGroup = 5 ; + public static final int UtilGroup = 6 ; + + private static final Class[] SYS_EX_CLASSES = { + UNKNOWN.class, BAD_PARAM.class, NO_MEMORY.class, + IMP_LIMIT.class, COMM_FAILURE.class, INV_OBJREF.class, + NO_PERMISSION.class, INTERNAL.class, MARSHAL.class, + INITIALIZE.class, NO_IMPLEMENT.class, BAD_TYPECODE.class, + BAD_OPERATION.class, NO_RESOURCES.class, NO_RESPONSE.class, + PERSIST_STORE.class, BAD_INV_ORDER.class, TRANSIENT.class, + FREE_MEM.class, INV_IDENT.class, INV_FLAG.class, + INTF_REPOS.class, BAD_CONTEXT.class, OBJ_ADAPTER.class, + DATA_CONVERSION.class, OBJECT_NOT_EXIST.class, TRANSACTION_REQUIRED.class, + TRANSACTION_ROLLEDBACK.class, INVALID_TRANSACTION.class, INV_POLICY.class, + CODESET_INCOMPATIBLE.class, REBIND.class, TIMEOUT.class, + TRANSACTION_UNAVAILABLE.class, BAD_QOS.class, INVALID_ACTIVITY.class, + ACTIVITY_COMPLETED.class, ACTIVITY_REQUIRED.class } ; + + @SuppressWarnings("unchecked") + private static final List> SYS_EX_CONSTRUCTORS = + new ArrayList>( + SYS_EX_CLASSES.length) ; + + static { + Class[] ptypes = { String.class, int.class, + CompletionStatus.class } ; + + for (Class cls : SYS_EX_CLASSES) { + try { + @SuppressWarnings("unchecked") + final Constructor cons = + (Constructor)cls.getDeclaredConstructor( + ptypes); + SYS_EX_CONSTRUCTORS.add(cons) ; + } catch (Exception ex) { + throw new RuntimeException( + "Cound not find constructor for " + cls, ex ) ; + } + + + } + } + + private int findClass( Class cls ) { + for (int ctr=0; ctr cls = method.getDeclaringClass() ; + final ORBException orbex = cls.getAnnotation( ORBException.class ) ; + return orbex ; + } + + private Log getLog( Method method ) { + Log log = method.getAnnotation( Log.class ); + if (log == null) { + throw new RuntimeException( + "No Log annotation present on " + method ) ; + } else { + return log ; + } + } + + private int getExceptionId( Method method ) { + final Class rtype = method.getReturnType() ; + final int exceptionId = findClass( rtype ) ; + return exceptionId ; + } + + private int getMinorCode( ORBException orbex, Log log ) { + return 200*orbex.group() + log.id() ; + } + + public int getMinorCode( Method method ) { + final ORBException orbex = getORBException( method ) ; + final Log log = getLog( method ) ; + final int minorCode = getMinorCode( orbex, log ) ; + final int base = orbex.omgException() ? + SUNVMCID.value : + OMGVMCID.value ; + return base + minorCode ; + } + + public int getMinorCode( Class cls, String methodName ) { + Method method = null ; + for (Method m : cls.getDeclaredMethods()) { + if (methodName.equals( m.getName())) { + method = m ; + break ; + } + } + + if (method == null) { + return -1 ; + } else { + return getMinorCode( method ) ; + } + } + + // Format of result: ExceptionId OmgID MinorCode, where + // ExceptionId is the ordinal position of the return type in SYS_EX_Classes, + // padded to 3 places + // OmgId is 0 for OMG exceptions, 1 for Old Sun exceptions + // MinorCode is 200*groupId + id + @Override + public String getLogId( Method method ) { + final ORBException orbex = getORBException( method ) ; + final Log log = getLog( method ) ; + final int minorCode = getMinorCode( orbex, log ) ; + final int exceptionId = getExceptionId( method ) ; + + final int omgId = orbex.omgException() ? 0 : 1 ; + + final String result = String.format( "%03d%1d%04d", + exceptionId, omgId, minorCode ) ; + + return result ; + } + + @Override + public Exception makeException( String msg, Method method ) { + try { + final ORBException orbex = getORBException( method ) ; + final Log log = getLog( method ) ; + final int minorCode = getMinorCode( orbex, log ) ; + final int exceptionId = getExceptionId(method) ; + + final Constructor cons = SYS_EX_CONSTRUCTORS.get(exceptionId) ; + + final CS cs = method.getAnnotation( CS.class ) ; + final CSValue csv = cs == null ? CSValue.NO : cs.value() ; + + final int base = orbex.omgException() ? + SUNVMCID.value : + OMGVMCID.value ; + + SystemException result = cons.newInstance(msg, base + minorCode, + csv.getCompletionStatus()) ; + + return result ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + private static final String CLASS_NAME_SUFFIX = "SystemException" ; + + @Override + public String getLoggerName( Class cls ) { + final ExceptionWrapper ew = cls.getAnnotation( + ExceptionWrapper.class ) ; + + String str = ew.loggerName() ; + if (str.length() == 0) { + str = cls.getSimpleName() ; + if (str.endsWith(CLASS_NAME_SUFFIX)) { + str = str.substring( 0, + str.length() - CLASS_NAME_SUFFIX.length()) ; + } + + return StandardLogger.CORBA_LOGGER_PREFIX + "." + str ; + } + + return str ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/ORBException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/ORBException.java new file mode 100644 index 000000000..7b27cde73 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logex/corba/ORBException.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logex.corba ; + +/** + * + * @author ken + */ +import java.lang.annotation.Documented ; +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; + +/** This annotation is applied to an interface or abstract class that is used + * to define logging and/or constructing CORBA exceptions. + */ +@Documented +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface ORBException { + /** Return true if this is an OMG exception with the OMG VMCID, + * false if it is using the old SUN VMCID. + */ + boolean omgException() default false ; + + /** Return the group ID to be used in computing the message ID. + */ + int group() ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/ActivationSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/ActivationSystemException.java new file mode 100644 index 000000000..d81c5751a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/ActivationSystemException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; + +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.OBJECT_NOT_EXIST; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.ActivationGroup ) +public interface ActivationSystemException { + ActivationSystemException self = WrapperGenerator.makeWrapper( + ActivationSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Cannot read repository datastore" ) + INITIALIZE cannotReadRepositoryDb( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Cannot add initial naming" ) + INITIALIZE cannotAddInitialNaming( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Cannot write repository datastore" ) + INTERNAL cannotWriteRepositoryDb( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Server not expected to register" ) + INTERNAL serverNotExpectedToRegister( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Unable to start server process" ) + INTERNAL unableToStartProcess( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Server is not running" ) + INTERNAL serverNotRunning( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Error in BadServerIdHandler" ) + OBJECT_NOT_EXIST errorInBadServerIdHandler( @Chain Exception exc ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/IORSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/IORSystemException.java new file mode 100644 index 000000000..c141ffb5b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/IORSystemException.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; +import java.io.IOException; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.INV_OBJREF; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.UNKNOWN; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.IORGroup ) +public interface IORSystemException { + IORSystemException self = WrapperGenerator.makeWrapper( + IORSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "ObjectReferenceTemplate is not initialized" ) + INTERNAL ortNotInitialized( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Null POA" ) + INTERNAL nullPoa( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Bad magic number {0} in ObjectKeyTemplate" ) + INTERNAL badMagic( int magic ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Error while stringifying an object reference" ) + INTERNAL stringifyWriteError( @Chain IOException exc ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Could not find a TaggedProfileTemplateFactory for id {0}" ) + INTERNAL taggedProfileTemplateFactoryNotFound( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Found a JDK 1.3.1 patch level indicator with value {0} " + + "less than JDK 1.3.1_01 value of 1" ) + INTERNAL invalidJdk131PatchLevel( int arg0 ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "Exception occurred while looking for ObjectAdapter {0} " + + "in IIOPProfileImpl.getServant" ) + INTERNAL getLocalServantFailure( @Chain Exception exc, + ObjectAdapterId oaid ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Exception occurred while closing an IO stream object" ) + INTERNAL ioexceptionDuringStreamClose( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Adapter ID not available" ) + BAD_OPERATION adapterIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Server ID not available" ) + BAD_OPERATION serverIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "ORB ID not available" ) + BAD_OPERATION orbIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Object adapter ID not available" ) + BAD_OPERATION objectAdapterIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Profiles in IOR do not all have the same Object ID, " + + "so conversion to IORTemplateList is impossible" ) + BAD_PARAM badOidInIorTemplateList( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Error in reading IIOP TaggedProfile" ) + BAD_PARAM invalidTaggedProfile( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Attempt to create IIOPAddress with port {0}, which is out of range" ) + BAD_PARAM badIiopAddressPort( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "IOR must have at least one IIOP profile" ) + INV_OBJREF iorMustHaveIiopProfile( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "MARSHAL error while attempting to create an ObjectKeyTemplate " + + "from an input stream") + UNKNOWN createMarshalError(@Chain MARSHAL mexc); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/InterceptorsSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/InterceptorsSystemException.java new file mode 100644 index 000000000..44d2054d8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/InterceptorsSystemException.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter; +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; +import com.sun.corba.ee.spi.logex.corba.CS; +import com.sun.corba.ee.spi.logex.corba.CSValue; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; +import java.util.List; + +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.UNKNOWN; +import org.omg.PortableInterceptor.ObjectReferenceTemplate; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.InterceptorsGroup ) +public interface InterceptorsSystemException { + InterceptorsSystemException self = WrapperGenerator.makeWrapper( + InterceptorsSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Interceptor type {0} is out of range" ) + BAD_PARAM typeOutOfRange( int type ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Interceptor's name is null: use empty string for " + + "anonymous interceptors" ) + BAD_PARAM nameNull( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "resolve_initial_reference is invalid during pre_init" ) + BAD_INV_ORDER rirInvalidPreInit( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Expected state {0}, but current state is {1}" ) + BAD_INV_ORDER badState1( int arg0, int arg1 ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Expected state {0} or {1}, but current state is {2}" ) + BAD_INV_ORDER badState2( int arg0, int arg1, int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "IOException during cancel request" ) + @CS( CSValue.MAYBE ) + COMM_FAILURE ioexceptionDuringCancelRequest( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Exception was null" ) + INTERNAL exceptionWasNull( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Object has no delegate" ) + INTERNAL objectHasNoDelegate( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Delegate was not a ClientRequestDispatcher" ) + INTERNAL delegateNotClientsub( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Object is not an ObjectImpl" ) + INTERNAL objectNotObjectimpl( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Assertion failed: Interceptor set exception to UserException or " + + "ApplicationException" ) + INTERNAL exceptionInvalid( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Assertion failed: Reply status is initialized but not " + + "SYSTEM_EXCEPTION or LOCATION_FORWARD" ) + INTERNAL replyStatusNotInit( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Exception in arguments" ) + INTERNAL exceptionInArguments( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Exception in exceptions" ) + INTERNAL exceptionInExceptions( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "Exception in contexts" ) + INTERNAL exceptionInContexts( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Another exception was null" ) + INTERNAL exceptionWasNull2( ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Servant invalid" ) + INTERNAL servantInvalid( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Can't pop only PICurrent" ) + INTERNAL cantPopOnlyPicurrent( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Can't pop another PICurrent" ) + INTERNAL cantPopOnlyCurrent2( ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "DSI result is null" ) + INTERNAL piDsiResultIsNull( ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "DII result is null" ) + INTERNAL piDiiResultIsNull( ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Exception is unavailable" ) + INTERNAL exceptionUnavailable( ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Assertion failed: client request info stack is null" ) + INTERNAL clientInfoStackNull( ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "Assertion failed: Server request info stack is null" ) + INTERNAL serverInfoStackNull( ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "Mark and reset failed" ) + INTERNAL markAndResetFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "currentIndex > tableContainer.size(): {0} > {1}" ) + INTERNAL slotTableInvariant( int arg0, int arg1 ) ; + + @Log( level=LogLevel.WARNING, id=21 ) + @Message( "InterceptorList is locked" ) + INTERNAL interceptorListLocked( ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "Invariant: sorted size + unsorted size == total size was violated" ) + INTERNAL sortSizeMismatch( ) ; + + @Log( level=LogLevel.FINE, id=23 ) + @Message( "Ignored exception in establish_components method for " + + "ObjectAdapter {0} (as per specification)" ) + INTERNAL ignoredExceptionInEstablishComponents( @Chain Exception exc, + ObjectAdapter oa ) ; + + @Log( level=LogLevel.FINE, id=24 ) + @Message( "Exception in components_established method for ObjectAdapter {0}" ) + INTERNAL exceptionInComponentsEstablished( @Chain Exception exc, + ObjectAdapter oa ) ; + + @Log( level=LogLevel.FINE, id=25 ) + @Message( "Ignored exception in adapter_manager_state_changed method for " + + "managerId {0} and newState {1} (as per specification)" ) + INTERNAL ignoredExceptionInAdapterManagerStateChanged( @Chain Exception exc, + int managerId, short newState ) ; + + @Log( level=LogLevel.FINE, id=26 ) + @Message( "Ignored exception in adapter_state_changed method for " + + "templates {0} and newState {1} (as per specification)" ) + INTERNAL ignoredExceptionInAdapterStateChanged( @Chain Exception exc, + List templates, short newState ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Policies not implemented" ) + NO_IMPLEMENT piOrbNotPolicyBased( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "ORBInitInfo object is only valid during ORB_init" ) + OBJECT_NOT_EXIST orbinitinfoInvalid( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "Unknown request invocation error" ) + @CS( CSValue.MAYBE ) + UNKNOWN unknownRequestInvoke( ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/NamingSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/NamingSystemException.java new file mode 100644 index 000000000..7702020fc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/NamingSystemException.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; +import com.sun.corba.ee.spi.logex.corba.CS; +import com.sun.corba.ee.spi.logex.corba.CSValue; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; + +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.UNKNOWN; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.NamingGroup ) +public interface NamingSystemException { + NamingSystemException self = WrapperGenerator.makeWrapper( + NamingSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=0 ) + @Message( "Port 0 is not a valid port in the transient name server" ) + BAD_PARAM transientNameServerBadPort( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "A null hostname is not a valid hostname in the " + + "transient name server" ) + BAD_PARAM transientNameServerBadHost( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Object is null" ) + BAD_PARAM objectIsNull() ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Bad host address in -ORBInitDef" ) + BAD_PARAM insBadAddress( ) ; + + @Log( level=LogLevel.WARNING, id=0 ) + @Message( "Updated context failed for bind" ) + UNKNOWN bindUpdateContextFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "bind failure" ) + UNKNOWN bindFailure( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Resolve conversion failed" ) + @CS( CSValue.MAYBE ) + UNKNOWN resolveConversionFailure( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Resolve failure" ) + @CS( CSValue.MAYBE ) + UNKNOWN resolveFailure( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Unbind failure" ) + @CS( CSValue.MAYBE ) + UNKNOWN unbindFailure( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=50 ) + @Message( "SystemException in transient name service while initializing" ) + INITIALIZE transNsCannotCreateInitialNcSys( @Chain SystemException exc ) ; + + @Log( level=LogLevel.WARNING, id=51 ) + @Message( "Java exception in transient name service while initializing" ) + INITIALIZE transNsCannotCreateInitialNc( @Chain Exception exc ) ; + + String namingCtxRebindAlreadyBound = + "Unexpected AlreadyBound exception in rebind" ; + + @Log( level=LogLevel.WARNING, id=0 ) + @Message( namingCtxRebindAlreadyBound ) + INTERNAL namingCtxRebindAlreadyBound( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=0 ) + @Message( namingCtxRebindAlreadyBound ) + INTERNAL namingCtxRebindAlreadyBound() ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Unexpected AlreadyBound exception in rebind_context" ) + INTERNAL namingCtxRebindctxAlreadyBound( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Bad binding type in internal binding implementation" ) + INTERNAL namingCtxBadBindingtype( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Object reference that is not CosNaming::NamingContext " + + "bound as a context" ) + INTERNAL namingCtxResolveCannotNarrowToCtx( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Error in creating POA for BindingIterator" ) + INTERNAL namingCtxBindingIteratorCreate( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=100 ) + @Message( "Bind implementation encountered a previous bind" ) + INTERNAL transNcBindAlreadyBound( ) ; + + @Log( level=LogLevel.WARNING, id=101 ) + @Message( "list operation caught an unexpected Java exception while " + + "creating list iterator" ) + INTERNAL transNcListGotExc( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=102 ) + @Message( "new_context operation caught an unexpected Java exception " + + "creating the NewContext servant" ) + INTERNAL transNcNewctxGotExc( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=103 ) + @Message( "Destroy operation caught a Java exception while " + + "disconnecting from ORB" ) + INTERNAL transNcDestroyGotExc( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=105 ) + @Message( "Stringified object reference with unknown protocol specified" ) + INTERNAL insBadSchemeName( ) ; + + @Log( level=LogLevel.WARNING, id=107 ) + @Message( "Malformed URL in -ORBInitDef" ) + INTERNAL insBadSchemeSpecificPart( ) ; + + @Log( level=LogLevel.WARNING, id=108 ) + @Message( "Malformed URL in -ORBInitDef" ) + INTERNAL insOther( ) ; + + @Log( level=LogLevel.WARNING, id=109 ) + @Message( "Initial port value {0} is not a valid number" ) + INTERNAL badInitialPortValue(String ips, @Chain NumberFormatException e); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/OMGSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/OMGSystemException.java new file mode 100644 index 000000000..a23616772 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/OMGSystemException.java @@ -0,0 +1,667 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; +import com.sun.corba.ee.spi.logex.corba.CS; +import com.sun.corba.ee.spi.logex.corba.CSValue; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; + +import org.omg.CORBA.BAD_CONTEXT; +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.BAD_TYPECODE; +import org.omg.CORBA.DATA_CONVERSION; +import org.omg.CORBA.IMP_LIMIT; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.INTF_REPOS; +import org.omg.CORBA.INV_OBJREF; +import org.omg.CORBA.INV_POLICY; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.NO_RESOURCES; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.OBJ_ADAPTER; +import org.omg.CORBA.TRANSACTION_ROLLEDBACK; +import org.omg.CORBA.TRANSIENT; +import org.omg.CORBA.UNKNOWN; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=true, group=0 ) +public interface OMGSystemException { + OMGSystemException self = WrapperGenerator.makeWrapper( + OMGSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "IDL context not found" ) + BAD_CONTEXT idlContextNotFound( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "No matching IDL context property" ) + BAD_CONTEXT noMatchingIdlContext( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Dependency exists in IFR preventing destruction of this object" ) + BAD_INV_ORDER depPreventDestruction( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Attempt to destroy indestructible objects in IFR" ) + BAD_INV_ORDER destroyIndestructible( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Operation would deadlock" ) + BAD_INV_ORDER shutdownWaitForCompletionDeadlock( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "ORB has shutdown" ) + BAD_INV_ORDER badOperationAfterShutdown( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Attempt to invoke send or invoke operation of the same " + + "Request object more than once " ) + BAD_INV_ORDER badInvoke( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Attempt to set a servant manager after one has already been set" ) + BAD_INV_ORDER badSetServantManager( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "ServerRequest::arguments called more than once or after a call " + + "to ServerRequest::set_exception" ) + BAD_INV_ORDER badArgumentsCall( ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "ServerRequest::ctx called more than once or before " + + "ServerRequest::arguments or after ServerRequest::ctx, " + + "ServerRequest::set_result or ServerRequest::set_exception" ) + BAD_INV_ORDER badCtxCall( ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "ServerRequest::set_result called more than once or before " + + "ServerRequest::arguments or after ServerRequest::set_result or " + + "ServerRequest::set_exception" ) + BAD_INV_ORDER badResultCall( ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Attempt to send a DII request after it was sent previously" ) + BAD_INV_ORDER badSend( ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Attempt to poll a DII request or to retrieve its result " + + "before the request was sent" ) + BAD_INV_ORDER badPollBefore( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Attempt to poll a DII request or to retrieve its result after " + + "the result was retrieved previously" ) + BAD_INV_ORDER badPollAfter( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Attempt to poll a synchronous DII request or to retrieve results " + + "from a synchronous DII request" ) + BAD_INV_ORDER badPollSync( ) ; + + @Log( level=LogLevel.FINE, id=14 ) + @Message( "Invalid call to forward_reference() when reply status is not " + + "LOCATION_FORWARD" ) + BAD_INV_ORDER invalidPiCall1( ) ; + + @Log( level=LogLevel.FINE, id=14 ) + @Message( "Cannot access this attribute or method at this point" ) + BAD_INV_ORDER invalidPiCall2( ) ; + + @Log( level=LogLevel.FINE, id=14 ) + @Message( "Cannot call set_slot from within an ORBInitializer" ) + BAD_INV_ORDER invalidPiCall3( ) ; + + @Log( level=LogLevel.FINE, id=14 ) + @Message( "Cannot call get_slot from within an ORBInitializer" ) + BAD_INV_ORDER invalidPiCall4( ) ; + + @Log( level=LogLevel.FINE, id=15 ) + @Message( "Service context add failed in portable interceptor because " + + "a service context with id {0} already exists" ) + BAD_INV_ORDER serviceContextAddFailed( int id ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Registration of PolicyFactory failed because a factory already " + + "exists for the given PolicyType {0}" ) + BAD_INV_ORDER policyFactoryRegFailed( int type ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "POA cannot create POAs while undergoing destruction" ) + BAD_INV_ORDER createPoaDestroy( ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "Attempt to reassign priority" ) + BAD_INV_ORDER priorityReassign( ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "An OTS/XA integration xa_start() call returned XAER_OUTSIDE" ) + BAD_INV_ORDER xaStartOutsize( ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "An OTS/XA integration xa_ call returned XAER_PROTO" ) + BAD_INV_ORDER xaStartProto( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "ServantManager returned wrong servant type" ) + BAD_OPERATION badServantManagerType( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Operation or attribute not known to target object " ) + BAD_OPERATION operationUnknownToTarget( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Failure to register, unregister or lookup value factory" ) + BAD_PARAM unableRegisterValueFactory( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "RID already defined in IFR" ) + BAD_PARAM ridAlreadyDefined( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Name already used in the context in IFR " ) + BAD_PARAM nameUsedIfr( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Target is not a valid container" ) + BAD_PARAM targetNotContainer( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Name clash in inherited context" ) + BAD_PARAM nameClash( ) ; + + int NOT_SERIALIZABLE = CorbaExtension.self.getMinorCode( + OMGSystemException.class, "notSerializable" ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Class {0} is not Serializable" ) + @CS( CSValue.MAYBE ) + BAD_PARAM notSerializable( String arg0 ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "string_to_object conversion failed due to bad scheme name {0}" ) + BAD_PARAM soBadSchemeName( String arg0 ) ; + + String soBadAddress = "string_to_object conversion failed due to " + + "bad address in name {0}" ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( soBadAddress ) + BAD_PARAM soBadAddress( @Chain Throwable exc, String arg0 ) ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( soBadAddress ) + BAD_PARAM soBadAddress( String arg0 ) ; + + @Log( level=LogLevel.FINE, id=9 ) + @Message( "string_to_object conversion failed due to bad schema specific " + + "part in name {0}" ) + BAD_PARAM soBadSchemaSpecific( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "string_to_object conversion failed due to non specific reason" ) + BAD_PARAM soNonSpecific( ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Attempt to derive abstract interface from non-abstract base " + + "interface in the Interface Repository" ) + BAD_PARAM irDeriveAbsIntBase( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Attempt to let a ValueDef support more than one non-abstract " + + "interface in the Interface Repository" ) + BAD_PARAM irValueSupport( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Attempt to use an incomplete TypeCode as a parameter" ) + BAD_PARAM incompleteTypecode( ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Invalid object id passed to POA::create_reference_by_id " ) + BAD_PARAM invalidObjectId( ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Bad name argument in TypeCode operation" ) + BAD_PARAM typecodeBadName( ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Bad RepositoryId argument in TypeCode operation" ) + BAD_PARAM typecodeBadRepid( ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Invalid member name in TypeCode operation " ) + BAD_PARAM typecodeInvMember( ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "Duplicate label value in create_union_tc " ) + BAD_PARAM tcUnionDupLabel( ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "Incompatible TypeCode of label and discriminator in " + + "create_union_tc " ) + BAD_PARAM tcUnionIncompatible( ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "Supplied discriminator type illegitimate in create_union_tc " ) + BAD_PARAM tcUnionBadDisc( ) ; + + @Log( level=LogLevel.WARNING, id=21 ) + @Message( "Any passed to ServerRequest::set_exception does not contain " + + "an exception " ) + BAD_PARAM setExceptionBadAny( ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "Unlisted user exception passed to ServerRequest::set_exception " ) + BAD_PARAM setExceptionUnlisted( ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "wchar transmission code set not in service context" ) + BAD_PARAM noClientWcharCodesetCtx( ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "Service context is not in OMG-defined range" ) + BAD_PARAM illegalServiceContext( ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "Enum value out of range" ) + BAD_PARAM enumOutOfRange( ) ; + + @Log( level=LogLevel.FINE, id=26 ) + @Message( "Invalid service context Id in portable interceptor" ) + BAD_PARAM invalidServiceContextId( ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "Attempt to call register_initial_reference with a null Object" ) + BAD_PARAM rirWithNullObject( ) ; + + @Log( level=LogLevel.FINE, id=28 ) + @Message( "Invalid component Id {0} in portable interceptor" ) + BAD_PARAM invalidComponentId( int arg0 ) ; + + int INVALID_PROFILE_ID = CorbaExtension.self.getMinorCode( + OMGSystemException.class, "invalidProfileId" ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "Profile ID does not define a known profile or it is impossible " + + "to add components to that profile" ) + BAD_PARAM invalidProfileId( ) ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( "Two or more Policy objects with the same PolicyType value " + + "supplied to Object::set_policy_overrides or " + + "PolicyManager::set_policy_overrides" ) + BAD_PARAM policyTypeDuplicate( ) ; + + @Log( level=LogLevel.WARNING, id=31 ) + @Message( "Attempt to define a oneway operation with non-void result, " + + "out or inout parameters or user exceptions" ) + BAD_PARAM badOnewayDefinition( ) ; + + @Log( level=LogLevel.WARNING, id=32 ) + @Message( "DII asked to create request for an implicit operation" ) + BAD_PARAM diiForImplicitOperation( ) ; + + @Log( level=LogLevel.WARNING, id=33 ) + @Message( "An OTS/XA integration xa_ call returned XAER_INVAL" ) + BAD_PARAM xaCallInval( ) ; + + @Log( level=LogLevel.WARNING, id=34 ) + @Message( "Union branch modifier method called with " + + "bad case label discriminator" ) + BAD_PARAM unionBadDiscriminator( ) ; + + @Log( level=LogLevel.WARNING, id=35 ) + @Message( "Illegal IDL context property name" ) + BAD_PARAM ctxIllegalPropertyName( ) ; + + @Log( level=LogLevel.WARNING, id=36 ) + @Message( "Illegal IDL property search string" ) + BAD_PARAM ctxIllegalSearchString( ) ; + + @Log( level=LogLevel.WARNING, id=37 ) + @Message( "Illegal IDL context name" ) + BAD_PARAM ctxIllegalName( ) ; + + @Log( level=LogLevel.WARNING, id=38 ) + @Message( "Non-empty IDL context" ) + BAD_PARAM ctxNonEmpty( ) ; + + @Log( level=LogLevel.WARNING, id=39 ) + @Message( "Unsupported RMI/IDL custom value type stream format {0}" ) + BAD_PARAM invalidStreamFormatVersion( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=40 ) + @Message( "ORB output stream does not support ValueOutputStream interface" ) + @CS( CSValue.MAYBE ) + BAD_PARAM notAValueoutputstream( ) ; + + @Log( level=LogLevel.WARNING, id=41 ) + @Message( "ORB input stream does not support ValueInputStream interface" ) + BAD_PARAM notAValueinputstream( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Attempt to marshal incomplete TypeCode" ) + BAD_TYPECODE marshallIncompleteTypecode( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Member type code illegitimate in TypeCode operation" ) + BAD_TYPECODE badMemberTypecode( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Illegal parameter type" ) + BAD_TYPECODE illegalParameter( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Character does not map to negotiated transmission code set" ) + DATA_CONVERSION charNotInCodeset( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Failure of PriorityMapping object" ) + DATA_CONVERSION priorityMapFailre( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Unable to use any profile in IOR" ) + IMP_LIMIT noUsableProfile( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Priority range too restricted for ORB" ) + INITIALIZE priorityRangeRestrict( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "wchar Code Set support not specified" ) + INV_OBJREF noServerWcharCodesetCmp( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Codeset component required for type using wchar or wstring data" ) + INV_OBJREF codesetComponentRequired( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Unable to reconcile IOR specified policy with " + + "effective policy override" ) + INV_POLICY iorPolicyReconcileError( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Invalid PolicyType" ) + INV_POLICY policyUnknown( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "No PolicyFactory has been registered for the given PolicyType" ) + INV_POLICY noPolicyFactory( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "An OTS/XA integration xa_ call returned XAER_RMERR" ) + INTERNAL xaRmerr( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "An OTS/XA integration xa_ call returned XAER_RMFAIL" ) + INTERNAL xaRmfail( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Interface Repository not available" ) + INTF_REPOS noIr( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "No entry for requested interface in Interface Repository" ) + INTF_REPOS noInterfaceInIr( ) ; + + String unableLocateValueFactory = "Unable to locate value factory" ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( unableLocateValueFactory ) + @CS( CSValue.MAYBE ) + MARSHAL unableLocateValueFactory( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( unableLocateValueFactory ) + @CS( CSValue.MAYBE ) + MARSHAL unableLocateValueFactory( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "ServerRequest::set_result called before ServerRequest::ctx " + + "when the operation IDL contains a context clause " ) + MARSHAL setResultBeforeCtx( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "NVList passed to ServerRequest::arguments does not describe " + + "all parameters passed by client" ) + MARSHAL badNvlist( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Attempt to marshal Local object" ) + MARSHAL notAnObjectImpl( @Chain BAD_PARAM exception ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "wchar or wstring data erroneously sent by client over " + + "GIOP 1.0 connection " ) + MARSHAL wcharBadGiopVersionSent( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "wchar or wstring data erroneously returned by server over " + + "GIOP 1.0 connection " ) + MARSHAL wcharBadGiopVersionReturned( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Unsupported RMI/IDL custom value type stream format" ) + @CS( CSValue.MAYBE ) + MARSHAL unsupportedFormatVersion( ) ; + + int RMIIIOP_OPTIONAL_DATA_INCOMPATIBLE = + CorbaExtension.self.getMinorCode( OMGSystemException.class, + "rmiiiopOptionalDataIncompatible1" ) ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( "No optional data available" ) + MARSHAL rmiiiopOptionalDataIncompatible1( ) ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( "Not enough space left in current chunk" ) + MARSHAL rmiiiopOptionalDataIncompatible2( ) ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( "Not enough optional data available" ) + MARSHAL rmiiiopOptionalDataIncompatible3( ) ; + + String missingLocalValueImpl = "Missing local value implementation" ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( missingLocalValueImpl ) + @CS( CSValue.MAYBE ) + NO_IMPLEMENT missingLocalValueImpl( @Chain Throwable exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( missingLocalValueImpl ) + @CS( CSValue.MAYBE ) + NO_IMPLEMENT missingLocalValueImpl() ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Incompatible value implementation version" ) + @CS( CSValue.MAYBE ) + NO_IMPLEMENT incompatibleValueImpl( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Unable to use any profile in IOR" ) + NO_IMPLEMENT noUsableProfile2( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Attempt to use DII on Local object" ) + NO_IMPLEMENT diiLocalObject( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Biomolecular Sequence Analysis iterator cannot be reset" ) + NO_IMPLEMENT bioReset( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Biomolecular Sequence Analysis metadata is not available as XML" ) + NO_IMPLEMENT bioMetaNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Genomic Maps iterator cannot be reset" ) + NO_IMPLEMENT bioGenomicNoIterator( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The portable Java bindings do not support arguments()" ) + NO_RESOURCES piOperationNotSupported1( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The portable Java bindings do not support exceptions()" ) + NO_RESOURCES piOperationNotSupported2( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The portable Java bindings do not support contexts()" ) + NO_RESOURCES piOperationNotSupported3( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The portable Java bindings do not support operation_context()" ) + NO_RESOURCES piOperationNotSupported4( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The portable Java bindings do not support result()" ) + NO_RESOURCES piOperationNotSupported5( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The object ID was never set" ) + NO_RESOURCES piOperationNotSupported6( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "The ObjectKeyTemplate was never set" ) + NO_RESOURCES piOperationNotSupported7( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "ServerRequest::arguments() was never called" ) + NO_RESOURCES piOperationNotSupported8( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "No connection for request's priority" ) + NO_RESOURCES noConnectionPriority( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "An OTS/XA integration xa_ call returned XAER_RB" ) + TRANSACTION_ROLLEDBACK xaRb( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "An OTS/XA integration xa_ call returned XAER_NOTA" ) + TRANSACTION_ROLLEDBACK xaNota( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "OTS/XA integration end() was called with success set to TRUE " + + "while transaction rollback was deferred" ) + TRANSACTION_ROLLEDBACK xaEndTrueRollbackDeferred( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Request discarded because of resource exhaustion in POA or " + + "because POA is in DISCARDING state" ) + TRANSIENT poaRequestDiscard( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "No usable profile in IOR" ) + TRANSIENT noUsableProfile3( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Request cancelled" ) + TRANSIENT requestCancelled( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "POA destroyed" ) + TRANSIENT poaDestroyed( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Attempt to pass an unactivated (unregistered) value as an " + + "object reference" ) + OBJECT_NOT_EXIST unregisteredValueAsObjref( ) ; + + String noObjectAdaptor = "Failed to create or locate Object Adaptor" ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( noObjectAdaptor ) + OBJECT_NOT_EXIST noObjectAdaptor( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( noObjectAdaptor ) + OBJECT_NOT_EXIST noObjectAdaptor() ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Biomolecular Sequence Analysis Service is no longer available" ) + OBJECT_NOT_EXIST bioNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Object Adapter Inactive" ) + OBJECT_NOT_EXIST objectAdapterInactive( ) ; + + String adapterActivatorException = "System exception in " + + "POA::unknown_adapter for POA {0} with parent POA {1}" ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( adapterActivatorException ) + OBJ_ADAPTER adapterActivatorException( @Chain Exception exc, String arg0, + ObjectAdapterId arg1 ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( adapterActivatorException ) + OBJ_ADAPTER adapterActivatorException( String arg0, ObjectAdapterId arg1 ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Incorrect servant type returned by servant manager " ) + OBJ_ADAPTER badServantType( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "No default servant available [POA policy]" ) + OBJ_ADAPTER noDefaultServant( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "No servant manager available [POA Policy]" ) + OBJ_ADAPTER noServantManager( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Violation of POA policy by ServantActivator::incarnate" ) + OBJ_ADAPTER badPolicyIncarnate( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Exception in " + + "PortableInterceptor::IORInterceptor.components_established" ) + OBJ_ADAPTER piExcCompEstablished( ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "Null servant returned by servant manager" ) + OBJ_ADAPTER nullServantReturned( ) ; + + String unknownUserException = + "Unlisted user exception received by client " ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( unknownUserException ) + @CS( CSValue.MAYBE ) + UNKNOWN unknownUserException( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( unknownUserException ) + @CS( CSValue.MAYBE ) + UNKNOWN unknownUserException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Non-standard System Exception not supported" ) + UNKNOWN unsupportedSystemException( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "An unknown user exception received by a portable interceptor" ) + UNKNOWN piUnknownUserException( ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/ORBUtilSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/ORBUtilSystemException.java new file mode 100644 index 000000000..c42970e3f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/ORBUtilSystemException.java @@ -0,0 +1,1964 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import com.sun.corba.ee.impl.encoding.OSFCodeSetRegistry; + +import com.sun.corba.ee.impl.ior.iiop.JavaSerializationComponent; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; + +import com.sun.corba.ee.spi.logex.corba.CS; +import com.sun.corba.ee.spi.logex.corba.CSValue; +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; + +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.EventHandler; + +import java.io.IOException; +import java.io.Serializable; + +import java.net.MalformedURLException; + +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.charset.MalformedInputException; + +import java.rmi.RemoteException; + +import java.util.List; +import java.util.NoSuchElementException; + +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.BAD_TYPECODE; +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.DATA_CONVERSION; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.INV_OBJREF; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.OBJ_ADAPTER; +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.CORBA.TIMEOUT; +import org.omg.CORBA.TRANSIENT; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.Bounds; +import org.omg.CORBA.UNKNOWN; + +import org.omg.CORBA.portable.RemarshalException; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.ORBUtilGroup ) +public interface ORBUtilSystemException { + ORBUtilSystemException self = WrapperGenerator.makeWrapper( + ORBUtilSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Adapter ID not available" ) + BAD_OPERATION adapterIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Server ID not available" ) + BAD_OPERATION serverIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "ORB ID not available" ) + BAD_OPERATION orbIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Object adapter ID not available" ) + BAD_OPERATION objectAdapterIdNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Error connecting servant" ) + BAD_OPERATION connectingServant( @Chain RemoteException exc ) ; + + @Log( level=LogLevel.FINE, id=6 ) + @Message( "Expected typecode kind {0} but got typecode kind {1}" ) + BAD_OPERATION extractWrongType( String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Expected typecode kind to be one of {0} but got " + + "typecode kind {1}" ) + BAD_OPERATION extractWrongTypeList( List opList, String tcName ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "String length of {0} exceeds bounded string length of {1}" ) + BAD_OPERATION badStringBounds( int len, int boundedLen ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Tried to insert an object of an incompatible type into an Any " + + "for an object reference" ) + BAD_OPERATION insertObjectIncompatible( ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "insert_Object call failed on an Any" ) + BAD_OPERATION insertObjectFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "extract_Object call failed on an Any" ) + BAD_OPERATION extractObjectIncompatible( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Fixed type does not match typecode" ) + BAD_OPERATION fixedNotMatch( ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Tried to insert Fixed type for non-Fixed typecode" ) + BAD_OPERATION fixedBadTypecode( @Chain BadKind bk ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "set_exception(Any) called with null args for DSI ServerRequest" ) + BAD_OPERATION setExceptionCalledNullArgs( ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "set_exception(Any) called with a bad (non-exception) type" ) + BAD_OPERATION setExceptionCalledBadType( ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "ctx() called out of order for DSI ServerRequest" ) + BAD_OPERATION contextCalledOutOfOrder( ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "ORB configurator class {0} could not be instantiated" ) + BAD_OPERATION badOrbConfigurator( @Chain Exception exc, String name ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "ORB configurator class {0} could not be instantiated" ) + BAD_OPERATION badOrbConfigurator( String name ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "Error in running ORB configurator" ) + BAD_OPERATION orbConfiguratorError( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=28 ) + @Message( "This ORB instance has been destroyed, so no operations can be " + + "performed on it" ) + BAD_OPERATION orbDestroyed( ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "Negative bound for string TypeCode is illegal" ) + BAD_OPERATION negativeBounds( ) ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( "Called typecode extract on an uninitialized typecode" ) + BAD_OPERATION extractNotInitialized( ) ; + + @Log( level=LogLevel.WARNING, id=31 ) + @Message( "extract_Object failed on an uninitialized Any" ) + BAD_OPERATION extractObjectFailed( @Chain Exception exc ) ; + + int METHOD_NOT_FOUND_IN_TIE = CorbaExtension.self.getMinorCode( + ORBUtilSystemException.class, "methodNotFoundInTie" ) ; + + @Log( level=LogLevel.FINE, id=32 ) + @Message( "Could not find method named {0} in class {1} in reflective Tie" ) + BAD_OPERATION methodNotFoundInTie( String arg0, String arg1 ) ; + + @Log( level=LogLevel.FINE, id=33 ) + @Message( "ClassNotFoundException while attempting to load preferred " + + "stub named {0}" ) + @CS( CSValue.MAYBE ) + BAD_OPERATION classNotFound1( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.FINE, id=34 ) + @Message( "ClassNotFoundException while attempting to load alternate " + + "stub named {0}" ) + @CS( CSValue.MAYBE ) + BAD_OPERATION classNotFound2( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.FINE, id=35 ) + @Message( "ClassNotFoundException while attempting to load interface {0}" ) + @CS( CSValue.MAYBE ) + BAD_OPERATION classNotFound3( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=36 ) + @Message( "POA ServantNotActive exception while trying get an " + + "org.omg.CORBA.Portable.Delegate for an org.omg.PortableServer.Servant" ) + BAD_OPERATION getDelegateServantNotActive( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=37 ) + @Message( "POA WrongPolicy exception while trying get an " + + "org.omg.CORBA.Portable.Delegate for an org.omg.PortableServer.Servant" ) + BAD_OPERATION getDelegateWrongPolicy( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=38 ) + @Message( "Call to StubAdapter.setDelegate did not pass a stub" ) + BAD_OPERATION setDelegateRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=39 ) + @Message( "Call to StubAdapter.getDelegate did not pass a stub" ) + BAD_OPERATION getDelegateRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=40 ) + @Message( "Call to StubAdapter.getTypeIds did not pass a stub" ) + BAD_OPERATION getTypeIdsRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=41 ) + @Message( "Call to StubAdapter.getORB did not pass a stub" ) + BAD_OPERATION getOrbRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=42 ) + @Message( "Call to StubAdapter.connect did not pass a stub" ) + BAD_OPERATION connectRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=43 ) + @Message( "Call to StubAdapter.isLocal did not pass a stub" ) + BAD_OPERATION isLocalRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=44 ) + @Message( "Call to StubAdapter.request did not pass a stub" ) + BAD_OPERATION requestRequiresStub( ) ; + + @Log( level=LogLevel.WARNING, id=45 ) + @Message( "Call to StubAdapter.activateTie did not pass a valid Tie" ) + BAD_OPERATION badActivateTieCall( ) ; + + @Log( level=LogLevel.WARNING, id=46 ) + @Message( "Bad operation from _invoke: {0}" ) + BAD_OPERATION badOperationFromInvoke( @Chain Exception exc, String arg0 ) ; + + String couldNotAccessStubDelegate = "Could not access StubDelegateImpl" ; + + @Log( level=LogLevel.WARNING, id=47 ) + @Message( couldNotAccessStubDelegate ) + BAD_OPERATION couldNotAccessStubDelegate( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=47 ) + @Message( couldNotAccessStubDelegate ) + BAD_OPERATION couldNotAccessStubDelegate( ) ; + + @Log( level=LogLevel.WARNING, id=48 ) + @Message( "Could not load interface {0} for creating stub" ) + BAD_OPERATION couldNotLoadInterface( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=49 ) + @Message( "Could not activate POA from foreign ORB due to " + + "AdapterInactive exception in StubAdapter" ) + BAD_OPERATION adapterInactiveInActivateServant( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=50 ) + @Message( "Could not instantiate stub class {0} for dynamic RMI-IIOP" ) + BAD_OPERATION couldNotInstantiateStubClass( @Chain Exception exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=51 ) + @Message( "String expected in OperationFactory.getString()" ) + BAD_OPERATION stringExpectedInOperation( ) ; + + @Log( level=LogLevel.WARNING, id=52 ) + @Message( "Object[] expected" ) + BAD_OPERATION objectArrayExpected( ) ; + + @Log( level=LogLevel.WARNING, id=53 ) + @Message( "Pair expected" ) + BAD_OPERATION pairStringStringExpected( ) ; + + @Log( level=LogLevel.WARNING, id=54 ) + @Message( "Error while attempting to load class {0}" ) + BAD_OPERATION classActionException( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=55 ) + @Message( "Bad URL {0} in URLAction" ) + BAD_OPERATION badUrlInAction( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=56 ) + @Message( "Property value {0} is not in the range {1} to {2}" ) + BAD_OPERATION valueNotInRange( int arg0, int arg1, int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=57 ) + @Message( "Number of token ({0}) and number of actions ({1}) don't match" ) + BAD_OPERATION numTokensActionsDontMatch( int arg0, int arg1 ) ; + + @Log( level=LogLevel.WARNING, id=58 ) + @Message( "Could not find constructor (String) in class {0}" ) + BAD_OPERATION exceptionInConvertActionConstructor( @Chain Exception exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=59 ) + @Message( "Exception in ConvertAction operation" ) + BAD_OPERATION exceptionInConvertAction( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=60 ) + @Message( "Useless exception on call to Closeable.close()" ) + BAD_OPERATION ioExceptionOnClose( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=63 ) + @Message( "Class {0} could not be loaded by bundle {1}" ) + BAD_OPERATION bundleCouldNotLoadClass( @Chain Exception exc, + String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=75 ) + @Message( "Exception while handling event on {0}" ) + BAD_OPERATION exceptionInSelector( @Chain Throwable t, EventHandler arg0 ) ; + + @Log( level=LogLevel.FINE, id=76 ) + @Message( "Ignoring cancelled SelectionKey {0}: key will be removed " + + "from Selector" ) + BAD_OPERATION canceledSelectionKey( SelectionKey arg0 ) ; + + @Log( level=LogLevel.FINE, id=77 ) + @Message( "The OSGi PackageAdmin service is not available" ) + BAD_OPERATION packageAdminServiceNotAvailable( ) ; + + @Log( level=LogLevel.WARNING, id=78 ) + @Message( "The ORBImpl.set_parameters method was called more than once" ) + BAD_OPERATION setParameterCalledAgain( ) ; + + @Log( level=LogLevel.WARNING, id=81 ) + @Message( "Could not make an instance of Class {0}" ) + BAD_OPERATION couldNotMakeInstance( @Chain Exception ex, Class arg0 ) ; + + @Log( level=LogLevel.WARNING, id=82 ) + @Message( "Exception in createCopy`") + BAD_OPERATION exceptionInCreateCopy( @Chain Exception exc); + + @Message( "Exception in reset method in ClientGroupManager") + @Log( level=LogLevel.FINE, id=83 ) + BAD_OPERATION exceptionInReset(@Chain Throwable t); + + @Message( "No IORUpdate service context present in ClientGroupManager") + @Log( level=LogLevel.FINE, id=84 ) + BAD_OPERATION noIORUpdateServicateContext(@Chain BAD_PARAM e); + + @Message( "Exception in next method in ClientGroupManager") + @Log( level=LogLevel.FINE, id=85 ) + BAD_OPERATION exceptionInNext(@Chain Throwable t); + + @Message( "Could not bind initial GIS to name service") + @Log( level=LogLevel.FINE, id=86 ) + BAD_OPERATION bindNameException(@Chain Exception e); + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Null parameter" ) + @CS( CSValue.MAYBE ) + BAD_PARAM nullParam( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Null parameter" ) + @CS( CSValue.NO ) + BAD_PARAM nullParamNoComplete( ) ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( "Unable to find value factory" ) + BAD_PARAM unableFindValueFactory( @Chain MARSHAL exc ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Abstract interface derived from non-abstract interface" ) + BAD_PARAM abstractFromNonAbstract( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Error in reading IIOP TaggedProfile" ) + BAD_PARAM invalidTaggedProfile( ) ; + + @Log( level=LogLevel.FINE, id=5 ) + @Message( "Object reference came from foreign ORB" ) + BAD_PARAM objrefFromForeignOrb( ) ; + + int LOCAL_OBJECT_NOT_ALLOWED = CorbaExtension.self.getMinorCode( + ORBUtilSystemException.class, "localObjectNotAllowed" ) ; + + @Log( level=LogLevel.FINE, id=6 ) + @Message( "Local object not allowed" ) + BAD_PARAM localObjectNotAllowed( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "null object reference" ) + BAD_PARAM nullObjectReference( ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Could not load class {0}" ) + BAD_PARAM couldNotLoadClass( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "Malformed URL {0}" ) + BAD_PARAM badUrl( String arg0 ) ; + + String fieldNotFound = "Field {0} not found in parser data object" ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( fieldNotFound ) + BAD_PARAM fieldNotFound( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( fieldNotFound ) + BAD_PARAM fieldNotFound( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Error in setting field {0} to value {1} in parser data object" ) + BAD_PARAM errorSettingField( @Chain Throwable exc, String arg0, + Object arg1 ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Bounds error occurred in DII request" ) + BAD_PARAM boundsErrorInDiiRequest( @Chain Bounds b ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Initialization error for persistent server" ) + @CS( CSValue.MAYBE) + BAD_PARAM persistentServerInitError( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Could not create array for field {0} with " + + "component type {1} and size {2}" ) + BAD_PARAM couldNotCreateArray( @Chain Throwable exc, String arg0, + Class arg1, int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Could not set array for field {0} at index {1} " + + "with component type {2} and size {3} to value {4}" ) + BAD_PARAM couldNotSetArray( @Chain Throwable thr, String arg0, int arg1, + Class arg2, int arg3, Object arg4 ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Illegal bootstrap operation {0}" ) + BAD_PARAM illegalBootstrapOperation( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Runtime Exception during bootstrap operation" ) + BAD_PARAM bootstrapRuntimeException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "Exception during bootstrap operation" ) + BAD_PARAM bootstrapException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "Expected a string, but argument was not of String type" ) + BAD_PARAM stringExpected( ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "{0} does not represent a valid kind of typecode" ) + BAD_PARAM invalidTypecodeKind( @Chain Throwable t, int kind ) ; + + @Log( level=LogLevel.WARNING, id=21 ) + @Message( "cannot have a SocketFactory and a ContactInfoList at the " + + "same time" ) + BAD_PARAM socketFactoryAndContactInfoListAtSameTime( ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "cannot have Acceptors and a legacy SocketFactory at the " + + "same time" ) + BAD_PARAM acceptorsAndLegacySocketFactoryAtSameTime( ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "Reflective POA Servant requires an instance of " + + "org.omg.CORBA_2_3.ORB" ) + BAD_PARAM badOrbForServant( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "Request partitioning value specified, {0}, " + + "is outside supported range, {1} - {2}" ) + BAD_PARAM invalidRequestPartitioningPolicyValue( int arg0, int arg1, + int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "Could not set request partitioning component value to {0}, " + + "valid values are {1} - {2}" ) + BAD_PARAM invalidRequestPartitioningComponentValue( int arg0, + int arg1, int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "Invalid request partitioning id {0}, " + + "valid values are {1} - {2}" ) + BAD_PARAM invalidRequestPartitioningId( int arg0, int arg1, int arg2 ) ; + + @Log( level=LogLevel.FINE, id=27 ) + @Message( "ORBDynamicStubFactoryFactoryClass property had value {0}, " + + "which could not be loaded by the ORB ClassLoader" ) + BAD_PARAM errorInSettingDynamicStubFactoryFactory( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=28 ) + @Message( "An attempt was made to register a ServiceContext.Factory with an " + + "ID that is already registered" ) + BAD_PARAM registerDuplicateServiceContext( ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "CORBA object is not an ObjectImpl in ORB.getIOR" ) + BAD_PARAM notAnObjectImpl( ) ; + + String badTimeoutStringData = "{0} is not a valid positive decimal " + + "integer for {1}" ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( badTimeoutStringData ) + BAD_PARAM badTimeoutStringData( @Chain Exception exc, String arg0, + String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( badTimeoutStringData ) + BAD_PARAM badTimeoutStringData( String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=31 ) + @Message( "Timeout data must be 3 or 4 positive decimal " + + "integers separated by :" ) + BAD_PARAM badTimeoutDataLength( ) ; + + @Log( level=LogLevel.WARNING, id=32 ) + @Message( "Load balancing value specified, {0}, is outside " + + "supported range, {1} - {2}" ) + BAD_PARAM invalidLoadBalancingPolicyValue( int arg0, int arg1, int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=33 ) + @Message( "Could not set load balancing component value to {0}, " + + "valid values are {1} - {2}" ) + BAD_PARAM invalidLoadBalancingComponentValue( int arg0, int arg1, int arg2 ) ; + + @Log( level=LogLevel.WARNING, id=34 ) + @Message( "Invalid request partitioning id {0}, valid values are {1} - {2}" ) + BAD_PARAM invalidLoadBalancingId( String arg0, String arg1, String arg2 ) ; + + @Log( level=LogLevel.FINE, id=35 ) + @Message( "CodeBase unavailable on connection {0}" ) + BAD_PARAM codeBaseUnavailable( Connection conn ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "DSI method not called" ) + @CS( CSValue.MAYBE ) + BAD_INV_ORDER dsimethodNotcalled( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "arguments(NVList) called more than once for DSI ServerRequest" ) + BAD_INV_ORDER argumentsCalledMultiple( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "arguments(NVList) called after exceptions set for " + + "DSI ServerRequest" ) + BAD_INV_ORDER argumentsCalledAfterException( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "arguments(NVList) called with null args for DSI ServerRequest" ) + BAD_INV_ORDER argumentsCalledNullArgs( ) ; + + @Log( level=LogLevel.FINE, id=5 ) + @Message( "arguments(NVList) not called for DSI ServerRequest" ) + BAD_INV_ORDER argumentsNotCalled( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "set_result(Any) called more than once for DSI ServerRequest" ) + BAD_INV_ORDER setResultCalledMultiple( ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "set_result(Any) called exception was set for DSI ServerRequest" ) + BAD_INV_ORDER setResultAfterException( ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "set_result(Any) called with null args for DSI ServerRequest" ) + BAD_INV_ORDER setResultCalledNullArgs( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Foreign to native typecode conversion constructor should not be " + + "called with native typecode" ) + BAD_TYPECODE badRemoteTypecode( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Invoked operation on unresolved recursive TypeCode" ) + BAD_TYPECODE unresolvedRecursiveTypecode( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "Connection failure: socketType: {0}; hostname: {1}; port: {2}" ) + COMM_FAILURE connectFailure( @Chain Throwable t, String arg0, + String arg1, String arg2 ) ; + + String writeErrorSend = "Write error sent" ; + + @Log( level=LogLevel.FINE, id=3 ) + @Message( writeErrorSend ) + @CS( CSValue.MAYBE ) + COMM_FAILURE writeErrorSend( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=3 ) + @Message( writeErrorSend ) + COMM_FAILURE writeErrorSend() ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Get properties error" ) + COMM_FAILURE getPropertiesError( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Bootstrap server is not available" ) + COMM_FAILURE bootstrapServerNotAvail( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Invocation error" ) + COMM_FAILURE invokeError( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "DefaultSocketFactory.createServerSocket only handles " + + "IIOP_CLEAR_TEXT, given {0}" ) + COMM_FAILURE defaultCreateServerSocketGivenNonIiopClearText( String arg0 ) ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( "Connection abort" ) + COMM_FAILURE connectionAbort( @Chain Throwable thr ) ; + + int CONNECTION_REBIND = CorbaExtension.self.getMinorCode( + ORBUtilSystemException.class, "connectionRebind" ) ; + + String connectionRebind = "Connection rebind" ; + + @Log( level=LogLevel.FINE, id=9 ) + @Message( "Connection rebind" ) + COMM_FAILURE connectionRebind( @Chain Throwable thr ) ; + + @Log( level=LogLevel.FINE, id=9 ) + @Message( "Connection rebind" ) + @CS( CSValue.MAYBE ) + COMM_FAILURE connectionRebindMaybe( @Chain Throwable thr ) ; + + @Log( level=LogLevel.FINE, id=9 ) + @Message( "Connection rebind" ) + COMM_FAILURE connectionRebind( ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Received a GIOP MessageError, indicating header corruption or " + + "version mismatch" ) + COMM_FAILURE recvMsgError( ) ; + + @Log( level=LogLevel.FINE, id=11 ) + @Message( "IOException received when reading from connection {0}" ) + COMM_FAILURE ioexceptionWhenReadingConnection( @Chain Exception exc, + Connection arg0 ) ; + + @Log( level=LogLevel.FINE, id=12 ) + @Message( "SelectionKey invalid on channel, {0}" ) + COMM_FAILURE selectionKeyInvalid( String arg0 ) ; + + @Log( level=LogLevel.FINE, id=13 ) + @Message( "Unexpected {0} in accept" ) + COMM_FAILURE exceptionInAccept( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.FINE, id=14 ) + @Message( "Unexpected exception, has permissions {0}" ) + COMM_FAILURE securityExceptionInAccept( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Read of full message failed : bytes requested = {0} " + + "bytes read = {1} max wait time = {2} total time spent waiting = {3}" ) + COMM_FAILURE transportReadTimeoutExceeded( int arg0, int arg1, + int arg2, int arg3 ) ; + + @Log( level=LogLevel.SEVERE, id=16 ) + @Message( "Unable to create IIOP listener on the specified " + + "host {0} and port {1}" ) + COMM_FAILURE createListenerFailed( @Chain Throwable thr, String host, int port ) ; + + @Log( level=LogLevel.FINE, id=17 ) + @Message( "Throwable received in ReadBits" ) + COMM_FAILURE throwableInReadBits( @Chain Throwable exc ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "IOException in accept" ) + COMM_FAILURE oexceptionInAccept( ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "Communications timeout waiting for response. " + + "Exceeded {0} milliseconds" ) + @CS( CSValue.MAYBE ) + COMM_FAILURE communicationsTimeoutWaitingForResponse( long arg0 ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "Communications retry timeout. Exceeded {0} milliseconds" ) + COMM_FAILURE communicationsRetryTimeout( @Chain Exception exc, long arg0 ) ; + + @Log( level=LogLevel.FINE, id=21 ) + @Message( "Ignoring exception while waiting for retry" ) + COMM_FAILURE ignoringExceptionWhileWaitingForRetry( ) ; + + @Log( level=LogLevel.SEVERE, id=22 ) + @Message( "Invalid request for a temporary write selector object for use " + + "on a blocking connection: {0}." ) + COMM_FAILURE temporaryWriteSelectorWithBlockingConnection( + Connection arg0 ) ; + + @Log( level=LogLevel.SEVERE, id=23 ) + @Message( "Invalid request for a temporary read selector object for use " + + "on a blocking connection: {0}." ) + COMM_FAILURE temporaryReadSelectorWithBlockingConnection( + Connection arg0 ) ; + + @Log( level=LogLevel.SEVERE, id=24 ) + @Message( "TemporarySelector's Selector, {0} .select(timeout) must called " + + "with timeout value greater than 0, " + + "called with a timeout value of, {1}." ) + COMM_FAILURE temporarySelectorSelectTimeoutLessThanOne( Selector arg0, + long arg1 ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "Write of message exceeded TCP timeout : max wait time = {0} ms, " + + "total time spent blocked, waiting to write = {1} ms." ) + COMM_FAILURE transportWriteTimeoutExceeded( int arg0, int arg1 ) ; + + @Log( level=LogLevel.SEVERE, id=26 ) + @Message( "Unexpected exception when reading with a temporary selector: " + + "bytes read = {0}, bytes requested = {1}, " + + "time spent waiting = {2} ms, max time to wait = {3}." ) + COMM_FAILURE exceptionWhenReadingWithTemporarySelector( @Chain Exception exc, + int arg0, int arg1, int arg2, int arg3 ) ; + + @Log( level=LogLevel.SEVERE, id=27 ) + @Message( "Unexpected exception when writing with a temporary selector: " + + "bytes written = {0}, total bytes requested to write = {1}, " + + "time spent waiting = {2} ms, max time to wait = {3}." ) + COMM_FAILURE exceptionWhenWritingWithTemporarySelector( @Chain Exception exc, + int arg0, int arg1, int arg2, int arg3 ) ; + + @Log( level=LogLevel.FINE, id=28 ) + @Message( "Throwable received in doOptimizedReadStrategy" ) + COMM_FAILURE throwableInDoOptimizedReadStrategy( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "Blocking read failed, expected to read additional bytes: " + + "max wait time = {0}ms total time spent waiting = {1}ms" ) + COMM_FAILURE blockingReadTimeout( long arg0, long arg1 ) ; + + @Log( level=LogLevel.FINE, id=30 ) + @Message( "Exception in a blocking read on connection {0} with a " + + "temporary selector" ) + COMM_FAILURE exceptionBlockingReadWithTemporarySelector( @Chain Exception exc, + Connection arg0 ) ; + + @Log( level=LogLevel.SEVERE, id=31 ) + @Message( "Invalid operation, attempting a non-blocking read on blocking " + + "connection, {0}" ) + COMM_FAILURE nonBlockingReadOnBlockingSocketChannel( Connection arg0 ) ; + + @Log( level=LogLevel.FINE, id=32 ) + @Message( "Unexpected exception when canceling SelectionKey and " + + "flushing temporary Selector" ) + COMM_FAILURE unexpectedExceptionCancelAndFlushTempSelector( + @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=33 ) + @Message( "Ignoring request to read a message which exceeds read size " + + "threshold of {0} bytes, requested size was {1}. " + + "Use ORB property -D{2}=<# of bytes> to set threshold higher." ) + COMM_FAILURE maximumReadByteBufferSizeExceeded( int arg0, + int arg1, String arg2 ) ; + + @Log( level=LogLevel.FINE, id=34 ) + @Message( "Received {0}, in a blocking read on connection, {1}, " + + "because an 'end of stream' was detected" ) + COMM_FAILURE blockingReadEndOfStream( @Chain Exception exc, String arg0, + String arg1 ) ; + + @Log( level=LogLevel.FINE, id=35 ) + @Message( "Received {0}, in a non-blocking read on connection, {1}, " + + "because an 'end of stream' was detected" ) + COMM_FAILURE nonblockingReadEndOfStream( String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=36 ) + @Message( "IOException in accept" ) + COMM_FAILURE ioexceptionInAccept( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=36 ) + @Message( "IOException in accept" ) + COMM_FAILURE ioexceptionInAcceptFine( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=37 ) + @Message( "Timeout while reading data in buffer manager" ) + COMM_FAILURE bufferReadManagerTimeout( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "A character did not map to the transmission code set" ) + DATA_CONVERSION badStringifiedIorLen( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Bad stringified IOR" ) + DATA_CONVERSION badStringifiedIor( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Unable to perform resolve_initial_references due to bad host or " + + "port configuration" ) + DATA_CONVERSION badModifier( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Codesets incompatible" ) + DATA_CONVERSION codesetIncompatible( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Illegal hexadecimal digit" ) + DATA_CONVERSION badHexDigit( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Invalid unicode pair detected during code set conversion" ) + DATA_CONVERSION badUnicodePair( @Chain MalformedInputException exc ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Tried to convert bytes to a single java char, " + + "but conversion yielded more than one Java char (Surrogate pair?)" ) + DATA_CONVERSION btcResultMoreThanOneChar( ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Client sent code set service context that we do not support" ) + DATA_CONVERSION badCodesetsFromClient( ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "Char to byte conversion for a CORBA char resulted in more than " + + "one byte" ) + @CS( CSValue.MAYBE ) + DATA_CONVERSION invalidSingleCharCtb( ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Character to byte conversion did not exactly double number of " + + "chars (GIOP 1.1 only)" ) + @CS( CSValue.MAYBE ) + DATA_CONVERSION badGiop11Ctb( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Tried to insert a sequence of length {0} into a " + + "bounded sequence of maximum length {1} in an Any" ) + DATA_CONVERSION badSequenceBounds( int len, int maxLen ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Class {0} is not a subtype of ORBSocketFactory" ) + DATA_CONVERSION illegalSocketFactoryType( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "{0} is not a valid custom socket factory" ) + DATA_CONVERSION badCustomSocketFactory( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Fragment size {0} is too small: it must be at least {1}" ) + DATA_CONVERSION fragmentSizeMinimum( int arg0, int arg1 ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Illegal value for fragment size ({0}): must be divisible by {1}" ) + DATA_CONVERSION fragmentSizeDiv( int arg0, int arg1 ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Could not instantiate ORBInitializer {0}" ) + DATA_CONVERSION orbInitializerFailure( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "orb initializer class {0} is not a subtype of ORBInitializer" ) + DATA_CONVERSION orbInitializerType( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "Bad syntax for ORBInitialReference" ) + DATA_CONVERSION orbInitialreferenceSyntax( ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "Could not instantiate Acceptor {0}" ) + DATA_CONVERSION acceptorInstantiationFailure( @Chain Exception exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=21 ) + @Message( "Acceptor class {0} is not a subtype of Acceptor" ) + DATA_CONVERSION acceptorInstantiationTypeFailure( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "Class {0} is not a subtype of CorbaContactInfoListFactory" ) + DATA_CONVERSION illegalContactInfoListFactoryType( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "{0} is not a valid CorbaContactInfoListFactory" ) + DATA_CONVERSION badContactInfoListFactory( @Chain Exception exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "Class {0} is not a subtype of IORToSocketInfo" ) + DATA_CONVERSION illegalIorToSocketInfoType( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "{0} is not a valid custom IORToSocketInfo" ) + DATA_CONVERSION badCustomIorToSocketInfo( @Chain Exception exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "Class {0} is not a subtype of IIOPPrimaryToContactInfo" ) + DATA_CONVERSION illegalIiopPrimaryToContactInfoType( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "{0} is not a valid custom IIOPPrimaryToContactInfo" ) + DATA_CONVERSION badCustomIiopPrimaryToContactInfo( @Chain Exception exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Bad corbaloc: URL" ) + INV_OBJREF badCorbalocString( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "No profile in IOR" ) + INV_OBJREF noProfilePresent( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Cannot create ORB ID datastore" ) + INITIALIZE cannotCreateOrbidDb( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Cannot read ORB ID datastore" ) + INITIALIZE cannotReadOrbidDb( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Cannot write ORB ID datastore" ) + INITIALIZE cannotWriteOrbidDb( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "legacyGetServerPort called before endpoints initialized" ) + INITIALIZE getServerPortCalledBeforeEndpointsInitialized( ) ; + + @Log( level=LogLevel.FINE, id=5 ) + @Message( "Persistent server port is not set" ) + @CS( CSValue.MAYBE ) + INITIALIZE persistentServerportNotSet( ) ; + + @Log( level=LogLevel.FINE, id=6 ) + @Message( "Persistent server ID is not set" ) + @CS( CSValue.MAYBE ) + INITIALIZE persistentServeridNotSet( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Exception occurred while running a user configurator" ) + INITIALIZE userConfiguratorException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Non-existent ORB ID" ) + INTERNAL nonExistentOrbid( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "No server request dispatcher" ) + INTERNAL noServerSubcontract( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "server request dispatcher template size error" ) + INTERNAL serverScTempSize( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "No client request dispatcher class" ) + INTERNAL noClientScClass( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "No IIOP profile in server request dispatcher" ) + INTERNAL serverScNoIiopProfile( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "getSystemException returned null" ) + INTERNAL getSystemExReturnedNull( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "The repository ID of a user exception had a bad length" ) + INTERNAL peekstringFailed( ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Unable to determine local hostname from " + + "InetAddress.getLocalHost().getHostName()" ) + INTERNAL getLocalHostFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Bad locate request status in IIOP locate reply" ) + INTERNAL badLocateRequestStatus( ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Error while stringifying an object reference" ) + INTERNAL stringifyWriteError( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "IIOP message with bad GIOP 1.0 message type" ) + INTERNAL badGiopRequestType( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Error in unmarshalling user exception" ) + INTERNAL errorUnmarshalingUserexc( ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Overflow in RequestDispatcherRegistry" ) + INTERNAL requestdispatcherregistryError( ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Error in processing a LocationForward" ) + INTERNAL locationforwardError( ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Wrong client request dispatcher" ) + INTERNAL wrongClientsc( ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Bad servant in read_Object" ) + INTERNAL badServantReadObject( ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "multiple IIOP profiles not supported" ) + INTERNAL multIiopProfNotSupported( ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "Error in GIOP magic" ) + @CS( CSValue.MAYBE ) + INTERNAL giopMagicError( ) ; + + @Log( level=LogLevel.WARNING, id=21 ) + @Message( "Error in GIOP version" ) + @CS( CSValue.MAYBE ) + INTERNAL giopVersionError( ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "Illegal reply status in GIOP reply message" ) + @CS( CSValue.MAYBE ) + INTERNAL illegalReplyStatus( ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "Illegal GIOP message type" ) + INTERNAL illegalGiopMsgType( ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "Fragmentation not allowed for this message type" ) + @CS( CSValue.MAYBE ) + INTERNAL fragmentationDisallowed( ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "Bad status in the IIOP reply message" ) + INTERNAL badReplystatus( ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "character to byte converter failure" ) + INTERNAL ctbConverterFailure( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "byte to character converter failure" ) + INTERNAL btcConverterFailure( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=28 ) + @Message( "Unsupported wchar encoding: ORB only supports fixed width " + + "UTF-16 encoding" ) + INTERNAL wcharArrayUnsupportedEncoding( ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "Illegal target address disposition value" ) + @CS( CSValue.MAYBE ) + INTERNAL illegalTargetAddressDisposition( ) ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( "No reply while attempting to get addressing disposition" ) + INTERNAL nullReplyInGetAddrDisposition( ) ; + + @Log( level=LogLevel.WARNING, id=31 ) + @Message( "Invalid GIOP target addressing preference" ) + INTERNAL orbTargetAddrPreferenceInExtractObjectkeyInvalid( ) ; + + @Log( level=LogLevel.WARNING, id=32 ) + @Message( "Invalid isStreamed TCKind {0}" ) + @CS( CSValue.MAYBE ) + INTERNAL invalidIsstreamedTckind( int kind ) ; + + @Log( level=LogLevel.WARNING, id=33 ) + @Message( "Found a JDK 1.3.1 patch level indicator with value less than " + + "JDK 1.3.1_01 value of 1" ) + INTERNAL invalidJdk131PatchLevel( ) ; + + @Log( level=LogLevel.WARNING, id=34 ) + @Message( "Error unmarshalling service context data" ) + @CS( CSValue.MAYBE ) + INTERNAL svcctxUnmarshalError( ) ; + + @Log( level=LogLevel.WARNING, id=35 ) + @Message( "null IOR" ) + INTERNAL nullIor( ) ; + + @Log( level=LogLevel.WARNING, id=36 ) + @Message( "Unsupported GIOP version {0}" ) + INTERNAL unsupportedGiopVersion( GIOPVersion arg0 ) ; + + @Log( level=LogLevel.WARNING, id=37 ) + @Message( "Application exception in special method: should not happen" ) + INTERNAL applicationExceptionInSpecialMethod( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=38 ) + @Message( "Assertion failed: statement not reachable (1)" ) + INTERNAL statementNotReachable1( ) ; + + @Log( level=LogLevel.WARNING, id=39 ) + @Message( "Assertion failed: statement not reachable (2)" ) + INTERNAL statementNotReachable2( ) ; + + @Log( level=LogLevel.WARNING, id=40 ) + @Message( "Assertion failed: statement not reachable (3)" ) + INTERNAL statementNotReachable3( ) ; + + @Log( level=LogLevel.FINE, id=41 ) + @Message( "Assertion failed: statement not reachable (4)" ) + INTERNAL statementNotReachable4( ) ; + + @Log( level=LogLevel.WARNING, id=42 ) + @Message( "Assertion failed: statement not reachable (5)" ) + INTERNAL statementNotReachable5( ) ; + + @Log( level=LogLevel.WARNING, id=43 ) + @Message( "Assertion failed: statement not reachable (6)" ) + INTERNAL statementNotReachable6( ) ; + + @Log( level=LogLevel.WARNING, id=44 ) + @Message( "Unexpected exception while unmarshalling DII user exception" ) + INTERNAL unexpectedDiiException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=45 ) + @Message( "This method should never be called" ) + INTERNAL methodShouldNotBeCalled( ) ; + + @Log( level=LogLevel.WARNING, id=46 ) + @Message( "We do not support cancel request for GIOP 1.1" ) + INTERNAL cancelNotSupported( ) ; + + @Log( level=LogLevel.WARNING, id=47 ) + @Message( "Empty stack exception while calling runServantPostInvoke" ) + INTERNAL emptyStackRunServantPostInvoke( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=48 ) + @Message( "Bad exception typecode" ) + INTERNAL problemWithExceptionTypecode( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=49 ) + @Message( "Illegal Subcontract id {0}" ) + INTERNAL illegalSubcontractId( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=50 ) + @Message( "Bad system exception in locate reply" ) + INTERNAL badSystemExceptionInLocateReply( ) ; + + @Log( level=LogLevel.WARNING, id=51 ) + @Message( "Bad system exception in reply" ) + @CS( CSValue.MAYBE ) + INTERNAL badSystemExceptionInReply( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=52 ) + @Message( "Bad CompletionStatus {0} in locate reply" ) + @CS( CSValue.MAYBE ) + INTERNAL badCompletionStatusInLocateReply( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=53 ) + @Message( "Bad CompletionStatus {0} in reply" ) + @CS( CSValue.MAYBE ) + INTERNAL badCompletionStatusInReply( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=54 ) + @Message( "The BadKind exception should never occur here" ) + INTERNAL badkindCannotOccur( @Chain BadKind bk ) ; + + @Log( level=LogLevel.WARNING, id=54 ) + @Message( "The BadKind exception should never occur here" ) + INTERNAL badkindCannotOccur( ) ; + + @Log( level=LogLevel.WARNING, id=55 ) + @Message( "Could not resolve alias typecode" ) + INTERNAL errorResolvingAlias( ) ; + + @Log( level=LogLevel.WARNING, id=56 ) + @Message( "The long double type is not supported in Java" ) + INTERNAL tkLongDoubleNotSupported( ) ; + + @Log( level=LogLevel.WARNING, id=57 ) + @Message( "Illegal typecode kind" ) + INTERNAL typecodeNotSupported( ) ; + + String boundsCannotOccur = + "Bounds exception cannot occur in this context" ; + + @Log( level=LogLevel.WARNING, id=59 ) + @Message( boundsCannotOccur ) + INTERNAL boundsCannotOccur( @Chain Bounds bd ) ; + + @Log( level=LogLevel.WARNING, id=59 ) + @Message( boundsCannotOccur ) + INTERNAL boundsCannotOccur( @Chain org.omg.CORBA.TypeCodePackage.Bounds bd ) ; + + @Log( level=LogLevel.WARNING, id=61 ) + @Message( "Number of invocations is already zero, but another invocation " + + "has completed" ) + @CS( CSValue.YES ) + INTERNAL numInvocationsAlreadyZero( ) ; + + @Log( level=LogLevel.WARNING, id=62 ) + @Message( "Error in constructing instance of bad server ID handler" ) + INTERNAL errorInitBadserveridhandler( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=63 ) + @Message( "No TOAFactory is available" ) + INTERNAL noToa( ) ; + + @Log( level=LogLevel.WARNING, id=64 ) + @Message( "No POAFactory is available" ) + INTERNAL noPoa( ) ; + + @Log( level=LogLevel.WARNING, id=65 ) + @Message( "Invocation info stack is unexpectedly empty" ) + INTERNAL invocationInfoStackEmpty( ) ; + + @Log( level=LogLevel.WARNING, id=66 ) + @Message( "Empty or null code set string" ) + INTERNAL badCodeSetString( ) ; + + @Log( level=LogLevel.WARNING, id=67 ) + @Message( "Unknown native codeset: {0}" ) + INTERNAL unknownNativeCodeset( int codeset ) ; + + @Log( level=LogLevel.WARNING, id=68 ) + @Message( "Unknown conversion codeset: {0}" ) + INTERNAL unknownConversionCodeSet( int codeset ) ; + + @Log( level=LogLevel.WARNING, id=69 ) + @Message( "Invalid codeset number" ) + INTERNAL invalidCodeSetNumber( @Chain NumberFormatException exc ) ; + + @Log( level=LogLevel.WARNING, id=70 ) + @Message( "Invalid codeset string {0}" ) + INTERNAL invalidCodeSetString( @Chain NoSuchElementException exc, + String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=71 ) + @Message( "Invalid CTB converter {0}" ) + INTERNAL invalidCtbConverterName( Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=72 ) + @Message( "Invalid BTC converter {0}" ) + INTERNAL invalidBtcConverterName( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=73 ) + @Message( "Could not duplicate CDRInputStream" ) + INTERNAL couldNotDuplicateCdrInputStream( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=74 ) + @Message( "BootstrapResolver caught an unexpected ApplicationException" ) + INTERNAL bootstrapApplicationException( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=75 ) + @Message( "Old entry in serialization indirection table has a " + + "different value than the value being added with the same key" ) + INTERNAL duplicateIndirectionOffset( ) ; + + @Log( level=LogLevel.WARNING, id=76 ) + @Message( "GIOP Cancel request contained a bad request ID: the request " + + "ID did not match the request that was to be cancelled" ) + INTERNAL badMessageTypeForCancel( ) ; + + @Log( level=LogLevel.WARNING, id=77 ) + @Message( "Duplicate ExceptionDetailMessage" ) + INTERNAL duplicateExceptionDetailMessage( ) ; + + @Log( level=LogLevel.WARNING, id=78 ) + @Message( "Bad ExceptionDetailMessage ServiceContext type" ) + INTERNAL badExceptionDetailMessageServiceContextType( ) ; + + @Log( level=LogLevel.WARNING, id=79 ) + @Message( "unexpected direct ByteBuffer with non-channel socket" ) + INTERNAL unexpectedDirectByteBufferWithNonChannelSocket( ) ; + + @Log( level=LogLevel.WARNING, id=80 ) + @Message( "unexpected non-direct ByteBuffer with channel socket" ) + INTERNAL unexpectedNonDirectByteBufferWithChannelSocket( ) ; + + @Log( level=LogLevel.WARNING, id=82 ) + @Message( "There should be at least one CorbaContactInfo to try (and fail) " + + "so this error should not be seen." ) + INTERNAL invalidContactInfoListIteratorFailureException( ) ; + + @Log( level=LogLevel.WARNING, id=83 ) + @Message( "Remarshal with nowhere to go" ) + INTERNAL remarshalWithNowhereToGo( ) ; + + @Log( level=LogLevel.WARNING, id=84 ) + @Message( "Exception when sending close connection" ) + INTERNAL exceptionWhenSendingCloseConnection( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=85 ) + @Message( "A reflective tie got an error while invoking method {0} on " + + "class {1}" ) + INTERNAL invocationErrorInReflectiveTie( @Chain Exception exc, + String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=86 ) + @Message( "Could not find or invoke write method on exception " + + "Helper class {0}" ) + INTERNAL badHelperWriteMethod( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=87 ) + @Message( "Could not find or invoke read method on exception " + + "Helper class {0}" ) + INTERNAL badHelperReadMethod( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=88 ) + @Message( "Could not find or invoke id method on exception " + + "Helper class {0}" ) + INTERNAL badHelperIdMethod( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=89 ) + @Message( "Tried to write exception of type {0} that was not declared on " + + "method" ) + INTERNAL writeUndeclaredException( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=90 ) + @Message( "Tried to read undeclared exception with ID {0}" ) + INTERNAL readUndeclaredException( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=91 ) + @Message( "Unable to setSocketFactoryORB" ) + INTERNAL unableToSetSocketFactoryOrb( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=92 ) + @Message( "Unexpected exception occurred where no exception should occur" ) + INTERNAL unexpectedException( @Chain Throwable exc ) ; + + @Log( level=LogLevel.WARNING, id=93 ) + @Message( "No invocation handler available for {0}" ) + INTERNAL noInvocationHandler( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=94 ) + @Message( "{0}: invalid buffer manager strategy for Java serialization" ) + INTERNAL invalidBuffMgrStrategy( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=95 ) + @Message( "Java stream initialization failed" ) + INTERNAL javaStreamInitFailed( ) ; + + @Log( level=LogLevel.WARNING, id=96 ) + @Message( "An ORBVersionServiceContext was already in the " + + "service context list" ) + INTERNAL duplicateOrbVersionServiceContext( ) ; + + @Log( level=LogLevel.WARNING, id=97 ) + @Message( "A SendingContextServiceContext was already in the " + + "service context list" ) + INTERNAL duplicateSendingContextServiceContext( ) ; + + @Log( level=LogLevel.WARNING, id=98 ) + @Message( "No such threadpool or queue {0}" ) + INTERNAL noSuchThreadpoolOrQueue( @Chain Throwable thr, int arg0 ) ; + + @Log( level=LogLevel.FINE, id=99 ) + @Message( "Successfully created IIOP listener on the specified host/port: " + + "{0}/{1}" ) + INTERNAL infoCreateListenerSucceeded( String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=100 ) + @Message( "Exception occurred while closing an IO stream object" ) + INTERNAL ioexceptionDuringStreamClose( @Chain Exception exc ) ; + + @Log( level=LogLevel.SEVERE, id=101 ) + @Message( "Invalid Java serialization version {0}" ) + INTERNAL invalidJavaSerializationVersion( JavaSerializationComponent arg0 ) ; + + @Log( level=LogLevel.WARNING, id=102 ) + @Message( "Object in ServiceContext map was not of the correct type" ) + INTERNAL errorInServiceContextMap( ) ; + + @Log( level=LogLevel.WARNING, id=103 ) + @Message( "The ContactInfoList in a CorbaClientDelegate is NOT a " + + "CorbaContactInfoList" ) + INTERNAL badTypeInDelegate( ) ; + + @Log( level=LogLevel.WARNING, id=117 ) + @Message( "Ignoring parsed fragment message because there is no " + + "fragment queue found for request id {0}." ) + INTERNAL noFragmentQueueForRequestId( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=118 ) + @Message( "Ignoring unexpected InterruptedException while waiting for " + + "next fragment in " + + "CorbaMessageMediatorImpl.resumeOptimizedReadProcessing." ) + INTERNAL resumeOptimizedReadThreadInterrupted( @Chain Exception exc ) ; + + @Log( level=LogLevel.SEVERE, id=119 ) + @Message( "Not allowed to get the integer value for an undefined " + + "CorbaRequestId." ) + INTERNAL undefinedCorbaRequestIdNotAllowed( ) ; + + @Log( level=LogLevel.WARNING, id=120 ) + @Message( "Illegal call to getKey in CacheTable: this instance has no " + + "reverse map" ) + INTERNAL getKeyInvalidInCacheTable( ) ; + + @Log( level=LogLevel.WARNING, id=121 ) + @Message( "TimerManager not initialized: error in constructing TypeCodeImpl" ) + INTERNAL timerManagerNotInitialized( ) ; + + @Log( level=LogLevel.WARNING, id=122 ) + @Message( "TimingPoints instance is null in TypeCodeImpl constructor" ) + INTERNAL timingPointsAreNull( ) ; + + @Log( level=LogLevel.SEVERE, id=123 ) + @Message( "Error in connection event handler caused event loss: may result " + + "in client-side deadlock" ) + INTERNAL lostConnectionEvent( ) ; + + @Log( level=LogLevel.WARNING, id=124 ) + @Message( "SharedCDRContactInfoImpl does not support SocketInfo calls" ) + INTERNAL undefinedSocketinfoOperation( ) ; + + @Log( level=LogLevel.WARNING, id=125 ) + @Message( "Duplicate request ids in response waiting room: " + + "over wrote old one: {0}, with new one: {1}" ) + INTERNAL duplicateRequestIdsInResponseWaitingRoom( String arg0, String arg1 ) ; + + @Log( level=LogLevel.FINE, id=132 ) + @Message( "Exception occurred in reader thread" ) + INTERNAL exceptionInReaderThread( @Chain Throwable thr ) ; + + @Log( level=LogLevel.FINE, id=133 ) + @Message( "Exception occurred in listener thread" ) + INTERNAL exceptionInListenerThread( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=134 ) + @Message( "Exception occurred in handleRequest for a Request message" ) + INTERNAL exceptionInHandleRequestForRequest( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=135 ) + @Message( "Exception occurred in handleRequest for a LocateRequest message" ) + INTERNAL exceptionInHandleRequestForLocateRequest( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=136 ) + @Message( "Could not set ORBData.orbInitializers") + INTERNAL couldNotSetOrbInitializer(@Chain Exception exc); + + @Log( id=137 ) + @Message( "Connection {0} not null in createMessageMediator" ) + INTERNAL connectionNotNullInCreateMessageMediator( + Connection connection); + + @Log( level=LogLevel.FINE, id=138 ) + @Message( "Old typeId {0} is not the same as the new typeId {1} in " + + "setEffectiveTargetIOR" ) + INTERNAL changedTypeIdOnSetEffectiveTargetIOR( String oldTypeId, + String newTypeId ); + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Data read past end of chunk without closing the chunk" ) + MARSHAL chunkOverflow( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Grow buffer strategy called underflow handler" ) + MARSHAL unexpectedEof( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Error in reading marshalled object" ) + MARSHAL readObjectException( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Character not IOS Latin-1 compliant in marshalling" ) + MARSHAL characterOutofrange( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Exception thrown during result() on ServerRequest" ) + @CS( CSValue.MAYBE ) + MARSHAL dsiResultException( Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "grow() called on IIOPInputStream" ) + MARSHAL iiopinputstreamGrow( ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "Underflow in BufferManagerReadStream after last fragment in " + + "message" ) + MARSHAL endOfStream( ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Invalid ObjectKey in request header" ) + MARSHAL invalidObjectKey() ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Invalid ObjectKey in request header" ) + MARSHAL invalidObjectKey( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "Unable to locate value class for repository ID {0} " + + "because codebase URL {1} is malformed" ) + @CS( CSValue.MAYBE ) + MARSHAL malformedUrl( @Chain MalformedURLException exc, + String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "Error from readValue on ValueHandler in CDRInputStream" ) + @CS( CSValue.MAYBE ) + MARSHAL valuehandlerReadError( @Chain Error err ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Exception from readValue on ValueHandler in CDRInputStream" ) + @CS( CSValue.MAYBE ) + MARSHAL valuehandlerReadException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Bad kind in isCustomType in CDRInputStream" ) + MARSHAL badKind( BadKind bk ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Could not find class {0} in CDRInputStream.readClass" ) + @CS( CSValue.MAYBE ) + MARSHAL cnfeReadClass( @Chain ClassNotFoundException exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Bad repository ID indirection at index {0}" ) + @CS( CSValue.MAYBE ) + MARSHAL badRepIdIndirection( int index ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Bad codebase string indirection at index {0}" ) + @CS( CSValue.MAYBE ) + MARSHAL badCodebaseIndirection( int index ) ; + + String unknownCodeSet = "Unknown code set {0} specified by client ORB as a " + + "negotiated code set" ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( unknownCodeSet ) + MARSHAL unknownCodeset( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( unknownCodeSet ) + MARSHAL unknownCodeset( OSFCodeSetRegistry.Entry arg0 ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Attempt to marshal wide character or string data in GIOP 1.0" ) + @CS( CSValue.MAYBE ) + MARSHAL wcharDataInGiop10( ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "String or wstring with a negative length {0}" ) + @CS( CSValue.MAYBE ) + MARSHAL negativeStringLength( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "CDRInputStream.read_value(null) called, but no repository ID " + + "information on the wire" ) + @CS( CSValue.MAYBE ) + MARSHAL expectedTypeNullAndNoRepId( ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "CDRInputStream.read_value() called, but no repository ID " + + "information on the wire" ) + MARSHAL readValueAndNoRepId( ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "Received end tag {0}, which is less than the expected value {1}" ) + @CS( CSValue.MAYBE ) + MARSHAL unexpectedEnclosingValuetype( int endTag, int expected ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "Read non-negative end tag {0} at offset {1} (end tags should " + + "always be negative)" ) + @CS( CSValue.MAYBE ) + MARSHAL positiveEndTag( int endTag, int offset ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "Out call descriptor is missing" ) + @CS( CSValue.MAYBE ) + MARSHAL nullOutCall( ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "write_Object called with a local object" ) + @CS( CSValue.MAYBE ) + MARSHAL writeLocalObject( ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "Tried to insert non-ObjectImpl {0} into an Any via insert_Object" ) + @CS( CSValue.MAYBE ) + MARSHAL badInsertobjParam( String name ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "Codebase present in RMI-IIOP stream format version 1 optional " + + "data valuetype header" ) + @CS( CSValue.MAYBE ) + MARSHAL customWrapperWithCodebase( ) ; + + @Log( level=LogLevel.WARNING, id=28 ) + @Message( "Indirection present in RMI-IIOP stream format version 2 optional " + + "data valuetype header" ) + @CS( CSValue.MAYBE ) + MARSHAL customWrapperIndirection( ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "0 or more than one repository ID found reading the optional data " + + "valuetype header" ) + @CS( CSValue.MAYBE ) + MARSHAL customWrapperNotSingleRepid( ) ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( "Bad valuetag {0} found while reading repository IDs" ) + @CS( CSValue.MAYBE ) + MARSHAL badValueTag( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=31 ) + @Message( "Bad typecode found for custom valuetype" ) + @CS( CSValue.MAYBE ) + MARSHAL badTypecodeForCustomValue( @Chain BadKind bk ) ; + + @Log( level=LogLevel.WARNING, id=32 ) + @Message( "An error occurred using reflection to invoke IDL Helper " + + "write method" ) + @CS( CSValue.MAYBE ) + MARSHAL errorInvokingHelperWrite( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=33 ) + @Message( "A bad digit was found while marshalling an IDL fixed type" ) + @CS( CSValue.MAYBE ) + MARSHAL badDigitInFixed( ) ; + + @Log( level=LogLevel.WARNING, id=34 ) + @Message( "Referenced type of indirect type not marshaled" ) + @CS( CSValue.MAYBE ) + MARSHAL refTypeIndirType( ) ; + + @Log( level=LogLevel.WARNING, id=35 ) + @Message( "Request message reserved bytes has invalid length" ) + @CS(CSValue.MAYBE) + MARSHAL badReservedLength( ) ; + + @Log( level=LogLevel.WARNING, id=36 ) + @Message( "A null object is not allowed here" ) + MARSHAL nullNotAllowed( ) ; + + @Log( level=LogLevel.WARNING, id=38 ) + @Message( "Error in typecode union discriminator" ) + MARSHAL unionDiscriminatorError( ) ; + + @Log( level=LogLevel.WARNING, id=39 ) + @Message( "Cannot marshal a native TypeCode" ) + MARSHAL cannotMarshalNative( ) ; + + @Log( level=LogLevel.WARNING, id=40 ) + @Message( "Cannot marshal an invalid TypeCode kind" ) + MARSHAL cannotMarshalBadTckind( ) ; + + @Log( level=LogLevel.WARNING, id=41 ) + @Message( "Invalid indirection value {0} (>-4): probable stream corruption" ) + MARSHAL invalidIndirection( int arg0 ) ; + + @Log( level=LogLevel.FINE, id=42 ) + @Message( "No type found at indirection {0}: probably stream corruption" ) + MARSHAL indirectionNotFound( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=43 ) + @Message( "Recursive TypeCode not supported by InputStream subtype" ) + MARSHAL recursiveTypecodeError( ) ; + + @Log( level=LogLevel.WARNING, id=44 ) + @Message( "TypeCode is of wrong kind to be simple" ) + MARSHAL invalidSimpleTypecode( ) ; + + @Log( level=LogLevel.WARNING, id=45 ) + @Message( "TypeCode is of wrong kind to be complex" ) + MARSHAL invalidComplexTypecode( ) ; + + @Log( level=LogLevel.WARNING, id=46 ) + @Message( "Cannot marshal typecode of invalid kind" ) + MARSHAL invalidTypecodeKindMarshal( ) ; + + @Log( level=LogLevel.WARNING, id=47 ) + @Message( "Default union branch not expected" ) + MARSHAL unexpectedUnionDefault( ) ; + + @Log( level=LogLevel.WARNING, id=48 ) + @Message( "Illegal discriminator type in union" ) + MARSHAL illegalUnionDiscriminatorType( ) ; + + @Log( level=LogLevel.WARNING, id=49 ) + @Message( "Could not skip over {0} bytes at offset {1}" ) + @CS( CSValue.MAYBE ) + MARSHAL couldNotSkipBytes( int len, int offset ) ; + + @Log( level=LogLevel.WARNING, id=50 ) + @Message( "Incorrect chunk length {0} at offset {1}" ) + MARSHAL badChunkLength( int len, int offset ) ; + + @Log( level=LogLevel.WARNING, id=51 ) + @Message( "Unable to locate array of repository IDs from indirection {0}" ) + MARSHAL unableToLocateRepIdArray( int indir ) ; + + @Log( level=LogLevel.WARNING, id=52 ) + @Message( "Fixed of length {0} in buffer of length {1}" ) + MARSHAL badFixed( short flen, int blen ) ; + + @Log( level=LogLevel.WARNING, id=53 ) + @Message( "Failed to load stub for {0} with class {1}" ) + MARSHAL readObjectLoadClassFailure( String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=54 ) + @Message( "Could not instantiate Helper class {0}" ) + MARSHAL couldNotInstantiateHelper( @Chain InstantiationException exc, + Class arg0 ) ; + + @Log( level=LogLevel.WARNING, id=55 ) + @Message( "Bad ObjectAdapterId for TOA" ) + MARSHAL badToaOaid( ) ; + + @Log( level=LogLevel.WARNING, id=56 ) + @Message( "Could not invoke helper read method for helper {0}" ) + MARSHAL couldNotInvokeHelperReadMethod( @Chain Exception exc, + Class arg0 ) ; + + @Log( level=LogLevel.WARNING, id=57 ) + @Message( "Could not load class {0}" ) + @CS( CSValue.MAYBE ) + MARSHAL couldNotFindClass( String clasName ) ; + + @Log( level=LogLevel.FINE, id=58 ) + @Message( "Error in arguments(NVList) for DSI ServerRequest" ) + MARSHAL badArgumentsNvlist( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=59 ) + @Message( "Could not create stub" ) + MARSHAL stubCreateError( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=60 ) + @Message( "Java serialization exception during {0} operation" ) + MARSHAL javaSerializationException( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=61 ) + @Message( "Could not read exception from UEInfoServiceContext" ) + @CS( CSValue.MAYBE ) + MARSHAL couldNotReadInfo( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=62 ) + @Message( "Could not find enum class {0} while reading an enum" ) + MARSHAL enumClassNotFound( @Chain ClassNotFoundException ex, + String arg0 ) ; + + String proxyClassNotFound = "Could not find Proxy class for " + + "interfaces {0} while reading a proxy" ; + + @Log( level=LogLevel.WARNING, id=63 ) + @Message( proxyClassNotFound ) + MARSHAL proxyClassNotFound( @Chain ClassNotFoundException exc, + List interfaceNames ) ; + + @Log( level=LogLevel.WARNING, id=63 ) + @Message( proxyClassNotFound ) + MARSHAL proxyClassNotFound( @Chain ClassNotFoundException exc, + String interfaceNames ) ; + + @Log( level=LogLevel.WARNING, id=64 ) + @Message( "Unable to load proxy class for interfaces {0} because " + + "codebase URL {1} is malformed" ) + MARSHAL malformedProxyUrl( @Chain MalformedURLException exc, + List interfaceNames, String url ) ; + + @Log( level=LogLevel.WARNING, id=65 ) + @Message( "Unable to create proxy instance because the interface list " + + "specified is empty" ) + MARSHAL emptyProxyInterfaceList( @Chain NullPointerException exc ) ; + + @Log( level=LogLevel.WARNING, id=66 ) + @Message( "Unable to create proxy instance because " + + "Proxy.getProxyClass(..) called with violated restrictions." ) + MARSHAL proxyWithIllegalArgs( @Chain IllegalArgumentException exc ) ; + + @Log( level=LogLevel.WARNING, id=67 ) + @Message( "An instance of class {0} could not be marshalled: the class is " + + "not an instance of java.io.Serializable" ) + MARSHAL objectNotSerializable( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=68 ) + @Message( "Could not unmarshal enum with cls {0}, value {1} using EnumDesc" ) + MARSHAL couldNotUnmarshalEnum( String cls, Serializable value ) ; + + @Log( level=LogLevel.WARNING, id=69 ) + @Message( "Expected String value for enum class {0}, but got value {1}" ) + MARSHAL enumValueNotString( Class cls, Serializable value ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "feature not implemented" ) + NO_IMPLEMENT genericNoImpl( ) ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( "IDL request context is not implemented" ) + NO_IMPLEMENT contextNotImplemented( ) ; + + @Log( level=LogLevel.FINE, id=3 ) + @Message( "getInterface() is not implemented" ) + NO_IMPLEMENT getinterfaceNotImplemented( ) ; + + @Log( level=LogLevel.FINE, id=4 ) + @Message( "send deferred is not implemented" ) + NO_IMPLEMENT sendDeferredNotimplemented( ) ; + + @Log( level=LogLevel.FINE, id=5 ) + @Message( "IDL type long double is not supported in Java" ) + @CS( CSValue.MAYBE ) + NO_IMPLEMENT longDoubleNotImplemented( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "getAcceptedSocket is not supported for a CorbaAcceptorLazyImpl" ) + NO_IMPLEMENT notSupportedOnLazyAcceptor( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "No server request dispatcher found when dispatching request " + + "to object adapter" ) + OBJ_ADAPTER noServerScInDispatch( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Error in connecting servant to ORB" ) + OBJ_ADAPTER orbConnectError( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=3 ) + @Message( "StubAdapter.getDelegate failed to activate a Servant" ) + OBJ_ADAPTER adapterInactiveInActivation( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Locate response indicated that the object was unknown" ) + OBJECT_NOT_EXIST locateUnknownObject( ) ; + + int BAD_SERVER_ID = CorbaExtension.self.getMinorCode( + ORBUtilSystemException.class, "badServerId" ) ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( "The server ID in the target object key does not match the " + + "server key expected by the server" ) + OBJECT_NOT_EXIST badServerId( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "No skeleton found in the server that matches the target " + + "object key" ) + OBJECT_NOT_EXIST badSkeleton( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Servant not found" ) + OBJECT_NOT_EXIST servantNotFound( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "No object adapter factory" ) + OBJECT_NOT_EXIST noObjectAdapterFactory( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Bad adapter ID" ) + OBJECT_NOT_EXIST badAdapterId( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Dynamic Any was destroyed: all operations are invalid" ) + OBJECT_NOT_EXIST dynAnyDestroyed( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "Sleep was interrupted in TCP timeouts" ) + TIMEOUT interruptedExceptionInTimeout( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "Request cancelled by exception" ) + TRANSIENT requestCanceled( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Unknown user exception while unmarshalling" ) + @CS( CSValue.MAYBE ) + UNKNOWN unknownCorbaExc( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Unknown user exception thrown by the server - " + + "exception: {0}; message: {1}" ) + @CS( CSValue.MAYBE ) + UNKNOWN runtimeexception( @Chain Throwable exc, String arg0, String arg1 ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Error while marshalling SystemException after DSI-based " + + "invocation" ) + @CS(CSValue.MAYBE) + UNKNOWN unknownDsiSysex( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Error while unmarshalling SystemException" ) + @CS(CSValue.MAYBE) + UNKNOWN unknownSysex( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "InterfaceDef object of wrong type returned by server" ) + @CS(CSValue.MAYBE) + UNKNOWN wrongInterfaceDef( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "org.omg.CORBA._InterfaceDefStub class not available" ) + UNKNOWN noInterfaceDefStub( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "UnknownException in dispatch" ) + @CS( CSValue.MAYBE ) + UNKNOWN unknownExceptionInDispatch( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=8 ) + @Message( "MARSHAL exception while trying to get value factory") + UNKNOWN marshalErrorInReadIDLValue(@Chain MARSHAL marshal); + + @Message( "Exception in post_init in VirtualAddressAgentImpl") + @Log( level=LogLevel.FINE, id=9 ) + UNKNOWN vaaErrorInPostInit( @Chain Exception exc); + + @Message( "Could not set tcpNoDelay on socket") + @Log( level=LogLevel.FINE, id=10 ) + UNKNOWN couldNotSetTcpNoDelay(@Chain Exception e); + + @Message( "Exception in purgeCalls") + @Log( level=LogLevel.FINE, id=11 ) + UNKNOWN exceptionInPurgeCalls(@Chain Exception ex); + + @Message( "Exception while closing socket") + @Log( level=LogLevel.FINE, id=12 ) + UNKNOWN exceptionOnClose(IOException e); + + @Message( "Interrupted while waiting in writeLock on OPENING state") + @Log( level=LogLevel.FINE, id=13 ) + UNKNOWN openingWaitInterrupted(InterruptedException ie); + + @Message( "Interrupted while waiting in writeLock on ESTABLISHED state") + @Log( level=LogLevel.FINE, id=14 ) + UNKNOWN establishedWaitInterrupted(InterruptedException ie); + + @Message( "Exception while creating Typecode from native representation") + @Log( level=LogLevel.FINE, id=15 ) + UNKNOWN exceptionOnCreatingTypecode(@Chain Exception e); + + @Message( "Exception in Typecode equals") + @Log( level=LogLevel.FINE, id=16 ) + UNKNOWN exceptionInTypecodeEquals(@Chain Exception e); + + @Message( "Remarshal exception in bootstrap resolver") + @Log( level=LogLevel.FINE, id=17 ) + UNKNOWN bootstrapRemarshalException(@Chain RemarshalException e); + + @Message( "Could not initialize initial GIS") + @Log( level=LogLevel.FINE, id=18 ) + UNKNOWN couldNotInitializeInitialGIS(@Chain Exception exc); + + @Log( level=LogLevel.FINE, id=19 ) + @Message( "No CSIv2TaggedComponentHandler available from initial references") + UNKNOWN noCSIV2Handler(@Chain InvalidName e); + + @Log( level=LogLevel.FINE, id=20 ) + @Message( "Error in ServerGroupManager") + UNKNOWN serverGroupManagerException(@Chain Exception e); + + @Log( level=LogLevel.FINE, id=21 ) + @Message( "ThreadStateValidator {0} threw an exception") + UNKNOWN threadStateValidatorException(Runnable run, @Chain Throwable thr); + + @Log( level=LogLevel.FINE, id=22 ) + @Message( "Bad GIOP 1.1 cancel request received") + UNKNOWN bad1_1CancelRequestReceived(); + + @Log( level=LogLevel.FINE, id=23 ) + @Message( "Cancel request with id 0 received") + UNKNOWN cancelRequestWithId0(); + + @Log( level=LogLevel.FINE, id=24 ) + @Message( "Bad cancel request received") + UNKNOWN badCancelRequest(); + + @Log( level=LogLevel.FINE, id=25 ) + @Message( "Class {0} not found in remote codebase {1}") + UNKNOWN classNotFoundInCodebase(String className, String remoteCodebase); + + @Log( level=LogLevel.FINE, id=26 ) + @Message( "Class {0} not found in JDKClassLoader") + UNKNOWN classNotFoundInJDKClassLoader(String className, + @Chain ClassNotFoundException e); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/POASystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/POASystemException.java new file mode 100644 index 000000000..645c4280d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/POASystemException.java @@ -0,0 +1,430 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; +import com.sun.corba.ee.spi.logex.corba.CS; +import com.sun.corba.ee.spi.logex.corba.CSValue; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; + +import org.omg.CORBA.BAD_INV_ORDER; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.INITIALIZE; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.NO_IMPLEMENT; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.CORBA.OBJ_ADAPTER; +import org.omg.CORBA.TRANSIENT; +import org.omg.CORBA.UNKNOWN; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.POAGroup ) +public interface POASystemException { + POASystemException self = WrapperGenerator.makeWrapper( + POASystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Servant Manager already set" ) + BAD_INV_ORDER servantManagerAlreadySet( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Request to wait for POA destruction while servicing request " + + "would deadlock" ) + BAD_INV_ORDER destroyDeadlock( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Bad operation on servant ORB???" ) + BAD_OPERATION servantOrb( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Bad Servant???" ) + BAD_OPERATION badServant( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Illegal Forward Request???" ) + BAD_OPERATION illegalForwardRequest( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "setDaemon() failed in creating destroy thread" ) + BAD_OPERATION couldNotSetDaemon( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Bad transaction context" ) + BAD_PARAM badTransactionContext( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Bad repository id" ) + BAD_PARAM badRepositoryId( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Null repository id" ) + BAD_PARAM nullRepositoryId( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "invoke setup???" ) + INTERNAL invokesetup( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "bad local reply status???" ) + INTERNAL badLocalreplystatus( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "persistent serverport error???" ) + INTERNAL persistentServerportError() ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "servant dispatch???" ) + INTERNAL servantDispatch( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "wrong client request dispatcher???" ) + INTERNAL wrongClientsc( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "can't clone template???" ) + INTERNAL cantCloneTemplate( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "POACurrent stack is unbalanced" ) + INTERNAL poacurrentUnbalancedStack( @Chain Exception ex ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Null field in POACurrent" ) + @CS( CSValue.MAYBE ) + INTERNAL poacurrentNullField( ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "POA internalGetServant error" ) + INTERNAL poaInternalGetServantError( ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "First Object Adapter name is {0}, should be RootPOA" ) + INTERNAL makeFactoryNotPoa( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "Duplicate ORB version service context" ) + INTERNAL duplicateOrbVersionSc( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "preinvoke clone error" ) + INTERNAL preinvokeCloneError( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "preinvoke POA destroyed" ) + INTERNAL preinvokePoaDestroyed( ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Bad dispatch policy for RETAIN policy in " + + "POAPolicyMediatorFactory" ) + INTERNAL pmfCreateRetain( ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Bad dispatch policy for NON_RETAIN policy in " + + "POAPolicyMediatorFactory" ) + INTERNAL pmfCreateNonRetain( ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Inconsistent policy in PolicyMediator" ) + INTERNAL policyMediatorBadPolicyInFactory( ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "ObjectAlreadyActive in servantToId" ) + INTERNAL servantToIdOaa( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "ServantAlreadyActive in servantToId" ) + INTERNAL servantToIdSaa(@Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "WrongPolicy in servantToId" ) + INTERNAL servantToIdWp( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "Can't resolve root POA" ) + INTERNAL cantResolveRootPoa( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=21 ) + @Message( "Call made to local client request dispatcher with non-local " + + "servant" ) + INTERNAL servantMustBeLocal( ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "IOR does not have any profiles" ) + INTERNAL noProfilesInIor( ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "Tried to decrement AOMEntry counter that is already 0" ) + INTERNAL aomEntryDecZero( ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "Tried to add a POA to an inactive POAManager" ) + @CS( CSValue.MAYBE ) + INTERNAL addPoaInactive( ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "POA tried to make an illegal state transition" ) + INTERNAL illegalPoaStateTrans( ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "Unexpected exception in POA {0}" ) + INTERNAL unexpectedException( @Chain Throwable thr, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "Exception occurred in RMORBInitializer.post_init" ) + INTERNAL rfmPostInitException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=28 ) + @Message( "Exception occurred in ReferenceManagerConfigurator.configure" ) + INTERNAL rfmConfigureException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "RFM was inactive on state change" ) + INTERNAL rfmManagerInactive( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=30 ) + @Message( "Suspend condition wait was unexpectedly interrupted" ) + INTERNAL rfmSuspendConditionWaitInterrupted( ) ; + + @Log( level=LogLevel.SEVERE, id=31) + @Message( "Some locks not released in find_POA: " + + "readLocked={0}, writeLocked={1}, childReadLocked={2}") + INTERNAL findPOALocksNotReleased(boolean readLocked, boolean writeLocked, + boolean childReadLocked); + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Single thread policy is not supported" ) + NO_IMPLEMENT singleThreadNotSupported( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "This method is not implemented" ) + NO_IMPLEMENT methodNotImplemented( ) ; + + String poaLookupError = "Error in find_POA" ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( poaLookupError ) + OBJ_ADAPTER poaLookupError( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( poaLookupError ) + OBJ_ADAPTER poaLookupError() ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( "POA is inactive" ) + OBJ_ADAPTER poaInactive( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "POA has no servant manager" ) + OBJ_ADAPTER poaNoServantManager( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "POA has no default servant" ) + OBJ_ADAPTER poaNoDefaultServant( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "POA servant is not unique" ) + OBJ_ADAPTER poaServantNotUnique( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Bad policy in POA" ) + OBJ_ADAPTER poaWrongPolicy( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Another error in find_POA" ) + OBJ_ADAPTER findpoaError( ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "POA ServantActivator lookup failed" ) + OBJ_ADAPTER poaServantActivatorLookupFailed( @Chain Throwable exc ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "POA has bad servant manager" ) + OBJ_ADAPTER poaBadServantManager( ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "POA ServantLocator lookup failed" ) + OBJ_ADAPTER poaServantLocatorLookupFailed( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Unknown policy passed to POA" ) + OBJ_ADAPTER poaUnknownPolicy( ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "POA not found" ) + OBJ_ADAPTER poaNotFound( ) ; + + @Log( level=LogLevel.WARNING, id=14 ) + @Message( "Error in servant lookup" ) + OBJ_ADAPTER servantLookup( ) ; + + @Log( level=LogLevel.WARNING, id=15 ) + @Message( "Error in local servant lookup" ) + OBJ_ADAPTER localServantLookup( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "Bad type for servant manager" ) + OBJ_ADAPTER servantManagerBadType( ) ; + + @Log( level=LogLevel.WARNING, id=17 ) + @Message( "Servant's _default_POA must be an instance of POAImpl" ) + OBJ_ADAPTER defaultPoaNotPoaimpl( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=18 ) + @Message( "Wrong POA policies for _this_object called outside of an " + + "invocation context" ) + OBJ_ADAPTER wrongPoliciesForThisObject( ) ; + + @Log( level=LogLevel.WARNING, id=19 ) + @Message( "ServantNotActive exception in _this_object" ) + OBJ_ADAPTER thisObjectServantNotActive( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=20 ) + @Message( "WrongPolicy exception in _this_object" ) + OBJ_ADAPTER thisObjectWrongPolicy( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=21 ) + @Message( "Operation called outside of invocation context" ) + OBJ_ADAPTER noContext( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=22 ) + @Message( "ServantActivator.incarnate() returned a null Servant" ) + OBJ_ADAPTER incarnateReturnedNull( ) ; + + @Log( level=LogLevel.WARNING, id=23 ) + @Message( "ReferenceFactoryManager caught exception in " + + "AdapterActivator.unknown_adaptor" ) + OBJ_ADAPTER rfmAdapterActivatorFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=24 ) + @Message( "ReferenceFactoryManager is not active" ) + OBJ_ADAPTER rfmNotActive( ) ; + + @Log( level=LogLevel.WARNING, id=25 ) + @Message( "ReferenceFactoryManager is already active" ) + OBJ_ADAPTER rfmAlreadyActive( ) ; + + @Log( level=LogLevel.WARNING, id=26 ) + @Message( "ReferenceFactoryManager activate method failed" ) + OBJ_ADAPTER rfmActivateFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=27 ) + @Message( "ReferenceFactoryManager restart called with a null argument" ) + OBJ_ADAPTER rfmNullArgRestart( ) ; + + @Log( level=LogLevel.WARNING, id=28 ) + @Message( "ReferenceFactoryManager restart failed" ) + OBJ_ADAPTER rfmRestartFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=29 ) + @Message( "ReferenceFactoryManager createReference failed" ) + OBJ_ADAPTER rfmCreateReferenceFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=30 ) + @Message( "ReferenceFactoryManager destroy failed" ) + OBJ_ADAPTER rfmDestroyFailed( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=31 ) + @Message( "Illegal use of ReferenceFactoryManager parent POA detected" ) + OBJ_ADAPTER rfmIllegalParentPoaUsage( ) ; + + @Log( level=LogLevel.WARNING, id=32 ) + @Message( "Illegal use of ReferenceFactoryManager parent POA detected" ) + OBJ_ADAPTER rfmIllegalPoaManagerUsage( ) ; + + @Log( level=LogLevel.WARNING, id=33 ) + @Message( "Method {0} can only be called when RFM is suspended" ) + OBJ_ADAPTER rfmMethodRequiresSuspendedState( String arg0 ) ; + + int JTS_INIT_ERROR = CorbaExtension.self.getMinorCode( + POASystemException.class, "jtsInitError" ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "JTS initialization error" ) + INITIALIZE jtsInitError( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Persistent server ID is not set" ) + INITIALIZE persistentServeridNotSet( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Persistent server port is not set" ) + INITIALIZE persistentServerportNotSet( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Error in ORBD" ) + INITIALIZE orbdError( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Error in bootstrap" ) + INITIALIZE bootstrapError( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "POAManager is in discarding state" ) + TRANSIENT poaDiscarding( ) ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( "Thread is active in another POAManager: holding on a different " + + "POAManager might cause a deadlock" ) + TRANSIENT poaManagerMightDeadlock( ) ; + + @Log( level=LogLevel.FINE, id=3 ) + @Message( "Thread is active in a POAManager: cannot perform operation in " + + "RFM without risking a deadlock" ) + TRANSIENT rfmMightDeadlock( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Error in OTS hook" ) + UNKNOWN otshookexception( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Unknown server exception" ) + UNKNOWN unknownServerException( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Unknown server application exception" ) + UNKNOWN unknownServerappException( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Unknown local invocation error" ) + UNKNOWN unknownLocalinvocationError( ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "AdapterActivator does not exist" ) + OBJECT_NOT_EXIST adapterActivatorNonexistent( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "AdapterActivator failed" ) + OBJECT_NOT_EXIST adapterActivatorFailed( ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Bad skeleton" ) + OBJECT_NOT_EXIST badSkeleton( ) ; + + @Log( level=LogLevel.FINE, id=4 ) + @Message( "Null servant" ) + OBJECT_NOT_EXIST nullServant( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "POA has been destroyed" ) + OBJECT_NOT_EXIST adapterDestroyed( ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "waitGuard was interrupted" ) + UNKNOWN waitGuardInterrupted(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/logging/UtilSystemException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/UtilSystemException.java new file mode 100644 index 000000000..eaa450c38 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/logging/UtilSystemException.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.logging ; + +import org.glassfish.pfl.basic.logex.Chain; +import org.glassfish.pfl.basic.logex.ExceptionWrapper; +import org.glassfish.pfl.basic.logex.Log; +import org.glassfish.pfl.basic.logex.LogLevel; +import org.glassfish.pfl.basic.logex.Message; +import org.glassfish.pfl.basic.logex.WrapperGenerator; +import com.sun.corba.ee.spi.logex.corba.CS; +import com.sun.corba.ee.spi.logex.corba.CSValue; + +import com.sun.corba.ee.spi.logex.corba.ORBException ; +import com.sun.corba.ee.spi.logex.corba.CorbaExtension ; +import java.io.IOException; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.DATA_CONVERSION; +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.INV_OBJREF; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.UNKNOWN; + +@ExceptionWrapper( idPrefix="IOP" ) +@ORBException( omgException=false, group=CorbaExtension.UtilGroup ) +public interface UtilSystemException { + UtilSystemException self = WrapperGenerator.makeWrapper( + UtilSystemException.class, CorbaExtension.self ) ; + + @Log( level=LogLevel.FINE, id=1 ) + @Message( "StubFactory failed on makeStub call" ) + BAD_OPERATION stubFactoryCouldNotMakeStub( @Chain Throwable exc ) ; + + @Log( level=LogLevel.FINE, id=2 ) + @Message( "Error in making stub given RepositoryId" ) + BAD_OPERATION errorInMakeStubFromRepositoryId( @Chain Throwable thr ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Failure in making stub given RepositoryId" ) + BAD_OPERATION failureInMakeStubFromRepositoryId( @Chain Throwable thr ) ; + + @Log( level=LogLevel.FINE, id=4 ) + @Message( "ClassCastException in loadStub" ) + BAD_OPERATION classCastExceptionInLoadStub( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Exception in loadStub" ) + BAD_OPERATION exceptionInLoadStub( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Unable to make stub from any of the repository IDs of the " + + "interface" ) + BAD_OPERATION couldNotMakeStubFromRepositoryId( ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "An IOException occurred while creating an IIOPOutputStream" ) + BAD_OPERATION exceptionInCreateIiopOutputStream( @Chain IOException exc ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "An IOException occurred while creating an IIOPInputStream" ) + BAD_OPERATION exceptionInCreateIiopInputStream( @Chain IOException exc ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "Only one call to the Util constructor is allowed; " + + "normally Util.getInstance should be called" ) + BAD_OPERATION onlyOneCallToConstructorAllowed( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Error in loadStubAndUpdateCache caused by _this_object" ) + BAD_PARAM noPoa( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=3 ) + @Message( "Tried to connect already connected Stub Delegate to a " + + "different ORB" ) + BAD_PARAM connectWrongOrb( ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Tried to connect unconnected Stub Delegate but no Tie was found" ) + BAD_PARAM connectNoTie( ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Tried to connect unconnected stub with Tie in a different ORB" ) + BAD_PARAM connectTieWrongOrb( ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Tried to connect unconnected stub to unconnected Tie" ) + BAD_PARAM connectTieNoServant( ) ; + + @Log( level=LogLevel.FINE, id=7 ) + @Message( "Failed to load Tie of class {0}" ) + BAD_PARAM loadTieFailed( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Bad hex digit in string_to_object" ) + DATA_CONVERSION badHexDigit( ) ; + + String unableLocateValueHelper = "Could not locate value helper" ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( unableLocateValueHelper ) + @CS( CSValue.MAYBE ) + MARSHAL unableLocateValueHelper( ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( unableLocateValueHelper ) + @CS( CSValue.MAYBE ) + MARSHAL unableLocateValueHelper( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Invalid indirection {0}" ) + MARSHAL invalidIndirection( @Chain IOException exc, int indir ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "{0} did not originate from a connected object" ) + INV_OBJREF objectNotConnected( @Chain Exception exc, String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Could not load stub for class {0}" ) + INV_OBJREF couldNotLoadStub( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Class {0} not exported, or else is actually a JRMP stub" ) + INV_OBJREF objectNotExported( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Error in setting object field {0} in {1} to {2}" ) + INTERNAL errorSetObjectField( @Chain Exception exc, + String fname, Object obj, Object value ) ; + + @Log( level=LogLevel.WARNING, id=2 ) + @Message( "Error in setting boolean field {0} in {1} to {2}" ) + INTERNAL errorSetBooleanField( @Chain Exception exc, + String fname, Object obj, boolean value ) ; + + @Log( level=LogLevel.WARNING, id=3 ) + @Message( "Error in setting byte field {0} in {1} to {2}" ) + INTERNAL errorSetByteField( @Chain Exception exc, + String fname, Object obj, byte value ) ; + + @Log( level=LogLevel.WARNING, id=4 ) + @Message( "Error in setting char field {0} in {1} to {2}" ) + INTERNAL errorSetCharField( @Chain Exception exc, + String fname, Object obj, char value ) ; + + @Log( level=LogLevel.WARNING, id=5 ) + @Message( "Error in setting short field {0} in {1} to {2}" ) + INTERNAL errorSetShortField( @Chain Exception exc, + String fname, Object obj, short value ) ; + + @Log( level=LogLevel.WARNING, id=6 ) + @Message( "Error in setting int field {0} in {1} to {2}" ) + INTERNAL errorSetIntField( @Chain Exception exc, + String fname, Object obj, int value ) ; + + @Log( level=LogLevel.WARNING, id=7 ) + @Message( "Error in setting long field {0} in {1} to {2}" ) + INTERNAL errorSetLongField( @Chain Exception exc, + String fname, Object obj, long value ) ; + + @Log( level=LogLevel.WARNING, id=8 ) + @Message( "Error in setting float field {0} in {1} to {2}" ) + INTERNAL errorSetFloatField( @Chain Exception exc, + String fname, Object obj, float value ) ; + + @Log( level=LogLevel.WARNING, id=9 ) + @Message( "Error in setting double field {0} in {1} to {2}" ) + INTERNAL errorSetDoubleField( @Chain Exception exc, + String arg0, Object obj, double value ) ; + + @Log( level=LogLevel.WARNING, id=10 ) + @Message( "IllegalAccessException while trying to write to field {0}" ) + INTERNAL illegalFieldAccess( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=11 ) + @Message( "State should be saved and reset first" ) + INTERNAL badBeginUnmarshalCustomValue( ) ; + + @Log( level=LogLevel.WARNING, id=12 ) + @Message( "Failure while loading specific Java remote exception class: {0}" ) + INTERNAL classNotFound( String arg0 ) ; + + @Log( level=LogLevel.WARNING, id=13 ) + @Message( "Could not find the expected Value Handler implementation " + + "in the JDK: Wrong JDK Version?" ) + INTERNAL couldNotFindJdkValueHandler( @Chain Exception exc ) ; + + @Log( level=LogLevel.FINE, id=14 ) + @Message( " Bad Operation or Bad Invocation Order : The Servant has not " + + "been associated with an ORB instance" ) + INTERNAL handleSystemException( @Chain SystemException exc ) ; + + @Log( level=LogLevel.INFO, id=15 ) + @Message( "This is a test exception with number {0}" ) + INTERNAL testException( int arg0 ) ; + + @Log( level=LogLevel.WARNING, id=16 ) + @Message( "This is another test exception with no parameters" ) + @CS( CSValue.MAYBE ) + INTERNAL simpleTestException( @Chain Exception exc ) ; + + @Log( level=LogLevel.WARNING, id=1 ) + @Message( "Unknown System Exception" ) + UNKNOWN unknownSysex( ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/misc/ORBClassLoader.java b/orbmain/src/main/java/com/sun/corba/ee/spi/misc/ORBClassLoader.java new file mode 100644 index 000000000..33777b815 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/misc/ORBClassLoader.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.misc ; + +/** + * Based on feedback from bug report 4452016, all class loading + * in the ORB is isolated here. It is acceptable to use + * Class.forName only when one is certain that the desired class + * should come from the core JDK. + *

        + * Note that this class must not depend on generated log wrappers! + */ +public class ORBClassLoader +{ + public static Class loadClass(String className) + throws ClassNotFoundException + { + return getClassLoader().loadClass(className); + } + + public static ClassLoader getClassLoader() + { + ClassLoader ccl = Thread.currentThread().getContextClassLoader() ; + if (ccl != null) + return ccl; + else + return ClassLoader.getSystemClassLoader(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/misc/ORBConstants.java b/orbmain/src/main/java/com/sun/corba/ee/spi/misc/ORBConstants.java new file mode 100644 index 000000000..b6dbe89ba --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/misc/ORBConstants.java @@ -0,0 +1,612 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.misc; + +import com.sun.corba.ee.org.omg.CORBA.SUNVMCID ; + +public class ORBConstants { + private ORBConstants() {} + + public static final String STRINGIFY_PREFIX = "IOR:" ; + + /* TAGS + tag-request@omg.org + FAQ on tags and tag allocation: http://doc.omg.org/ptc/99-02-01. + http://doc.omg.org/standard-tags + http://doc.omg.org/vendor-tags + + Last update: 19th August 2003 (ptc/03-08-14) + + // Legacy + 1 profile tag 0x4f4e4300 ("ONC\x00") + 1 profile tag 0x4e454f00 ("NEO\x00") + 1 profile tag 0x434f4f4c ("COOL") + 16 service tags 0x4e454f00 - 0x4e454f0f ("NEO\x00" - "NEO\x0f") + + // Current + 16 VMCID 0x5355xxxx ("SU\x00\x00" - "SU\xff\xff") + 16 profile tags 0x53554e00 - 0x53554e0f ("SUN\x00" - "SUN\x0f") + 16 ORB Type IDs 0x53554e00 - 0x53554e0f ("SUN\x00" - "SUN\x0f") + 64 service tags 0x53554e00 - 0x53554e3f ("SUN\x00" - "SUN\x3f") + 64 component tags 0x53554e00 - 0x53554e3f ("SUN\x00" - "SUN\x3f") + */ + + // All NEO service contexts must be in the range + // NEO_FIRST_SERVICE_CONTEXT to + // NEO_FIRST_SERVICE_CONTEXT + NUM_NEO_SERVICE_CONTEXTS - 1 + public static final int NEO_FIRST_SERVICE_CONTEXT = 0x4e454f00 ; + public static final int NUM_NEO_SERVICE_CONTEXTS = 15 ; + public static final int TAG_ORB_VERSION = NEO_FIRST_SERVICE_CONTEXT ; + + public static final int SUN_TAGGED_COMPONENT_ID_BASE = 0x53554e00; + public static final int SUN_SERVICE_CONTEXT_ID_BASE = 0x53554e00; + + //////////////////////////////////////////////////// + // + // Tagged Components Ids + // + + // Used by AS 7 for IIOP failover. + public static final int TAG_CONTAINER_ID = + SUN_TAGGED_COMPONENT_ID_BASE + 0; + // Used by AS 8.1 for Request Partioning + public static final int TAG_REQUEST_PARTITIONING_ID = + SUN_TAGGED_COMPONENT_ID_BASE + 1; + // TaggedComponentId for Java serialization tagged component. + public static final int TAG_JAVA_SERIALIZATION_ID = + SUN_TAGGED_COMPONENT_ID_BASE + 2; + + // Introduced in AS 9.0 + public static final int FOLB_MEMBER_ADDRESSES_TAGGED_COMPONENT_ID = + SUN_TAGGED_COMPONENT_ID_BASE + 3; + // Introduced in AS 9.0 + public static final int FOLB_MEMBERSHIP_LABEL_TAGGED_COMPONENT_ID = + SUN_TAGGED_COMPONENT_ID_BASE + 4; + // Introduced in GFv2.1 + public static final int TAG_LOAD_BALANCING_ID = + SUN_TAGGED_COMPONENT_ID_BASE + 5; + + //////////////////////////////////////////////////// + // + // Service Context Ids + // + + // Used by AS 7 for IIOP failover. + public static final int CONTAINER_ID_SERVICE_CONTEXT = + SUN_SERVICE_CONTEXT_ID_BASE + 0; + + // Introduced in AS 9. + public static final int FOLB_MEMBERSHIP_LABEL_SERVICE_CONTEXT_ID = + SUN_SERVICE_CONTEXT_ID_BASE + 1; + // Introduced in AS 9. + public static final int FOLB_IOR_UPDATE_SERVICE_CONTEXT_ID = + SUN_SERVICE_CONTEXT_ID_BASE + 2; + + + //////////////////////////////////////////////////// + // + // All Sun policies are allocated using the SUNVMCID, which is also + // used for minor codes. This allows 12 bits of offset, so + // the largest legal Sun policy is SUNVMCID.value + 4095. + public static final int SERVANT_CACHING_POLICY = SUNVMCID.value + 0 ; + public static final int ZERO_PORT_POLICY = SUNVMCID.value + 1 ; + public static final int COPY_OBJECT_POLICY = SUNVMCID.value + 2 ; + public static final int REQUEST_PARTITIONING_POLICY = SUNVMCID.value + 3 ; + public static final int REFERENCE_MANAGER_POLICY = SUNVMCID.value + 4 ; + public static final int LOAD_BALANCING_POLICY = SUNVMCID.value + 5 ; + + // These are the subcontract IDs for various qualities of + // service/implementation. + // Persistent SCIDs have the second bit as 1. + // SCIDs less than FIRST_POA_SCID are JavaIDL SCIDs. + public static final int TOA_SCID = 2 ; + + public static final int DEFAULT_SCID = TOA_SCID ; + + public static final int FIRST_POA_SCID = 32; + public static final int MAX_POA_SCID = 63; + public static final int TRANSIENT_SCID = FIRST_POA_SCID ; + public static final int PERSISTENT_SCID = makePersistent( TRANSIENT_SCID ) ; + public static final int SC_TRANSIENT_SCID = FIRST_POA_SCID + 4 ; + public static final int SC_PERSISTENT_SCID = makePersistent( SC_TRANSIENT_SCID ) ; + public static final int IISC_TRANSIENT_SCID = FIRST_POA_SCID + 8 ; + public static final int IISC_PERSISTENT_SCID = makePersistent( IISC_TRANSIENT_SCID ) ; + public static final int MINSC_TRANSIENT_SCID = FIRST_POA_SCID + 12 ; + public static final int MINSC_PERSISTENT_SCID = makePersistent( MINSC_TRANSIENT_SCID ) ; + + public static boolean isTransient( int scid ) + { + return (scid & 2) == 0 ; + } + + public static int makePersistent( int scid ) + { + return scid | 2 ; + } + + // Constants for ORB properties ************************************************************** + + // All ORB properties must follow the following rules: + // 1. Property names must start with either + // CORBA_PREFIX or SUN_PREFIX. + // 2. Property names must have unique suffixes after the last ".". + // 3. Property names must have "ORB" as the first 3 letters + // in their suffix. + // 4. proprietary property names should have a subsystem + // where appropriate after the prefix. + + // org.omg.CORBA properties must be defined by OMG standards + // The well known org.omg.CORBA.ORBClass and + // org.omg.CORBA.ORBSingletonClass are not included here + // since they occur in org.omg.CORBA.ORB. + + public static final String CORBA_PREFIX = "org.omg.CORBA." ; + + public static final String INITIAL_HOST_PROPERTY = + CORBA_PREFIX + "ORBInitialHost" ; + public static final String INITIAL_PORT_PROPERTY = + CORBA_PREFIX + "ORBInitialPort" ; + public static final String INITIAL_SERVICES_PROPERTY = + CORBA_PREFIX + "ORBInitialServices" ; + public static final String DEFAULT_INIT_REF_PROPERTY = + CORBA_PREFIX + "ORBDefaultInitRef" ; + public static final String ORB_INIT_REF_PROPERTY = + CORBA_PREFIX + "ORBInitRef" ; + + // All of our proprietary properties must start with com.sun.corba.ee + public static final String SUN_PREFIX = "com.sun.corba.ee." ; + + // special property (system only) for enabling OSGIListener debug + public static final String DEBUG_OSGI_LISTENER = SUN_PREFIX + "ORBDebugOSGIListener" ; + + // general properties + public static final String ALLOW_LOCAL_OPTIMIZATION = SUN_PREFIX + "ORBAllowLocalOptimization" ; + public static final String SERVER_PORT_PROPERTY = SUN_PREFIX + "ORBServerPort" ; + public static final String SERVER_HOST_PROPERTY = SUN_PREFIX + "ORBServerHost" ; + public static final String ORB_ID_PROPERTY = CORBA_PREFIX + "ORBId" ; + // This property is provided for backward compatibility reasons + public static final String OLD_ORB_ID_PROPERTY = SUN_PREFIX + "ORBid" ; + public static final String ORB_SERVER_ID_PROPERTY = CORBA_PREFIX + "ORBServerId" ; + public static final String DEBUG_PROPERTY = SUN_PREFIX + "ORBDebug" ; + public static final String INIT_DEBUG_PROPERTY = SUN_PREFIX + "ORBInitDebug" ; + // Property for setting use of repository Ids during serialization. + public static final String USE_REP_ID = SUN_PREFIX + "ORBUseRepId"; + + // giop related properties - default settings in decimal form + public static final String GIOP_VERSION = SUN_PREFIX + "giop.ORBGIOPVersion" ; + public static final String GIOP_FRAGMENT_SIZE = SUN_PREFIX + "giop.ORBFragmentSize" ; + public static final String GIOP_BUFFER_SIZE = SUN_PREFIX + "giop.ORBBufferSize" ; + public static final String GIOP_11_BUFFMGR = SUN_PREFIX + "giop.ORBGIOP11BuffMgr"; + public static final String GIOP_12_BUFFMGR = SUN_PREFIX + "giop.ORBGIOP12BuffMgr"; + public static final String GIOP_TARGET_ADDRESSING = SUN_PREFIX + "giop.ORBTargetAddressing"; + public static final int GIOP_DEFAULT_FRAGMENT_SIZE = 4096; + public static final int GIOP_DEFAULT_BUFFER_SIZE = 4096; + public static final int DEFAULT_GIOP_11_BUFFMGR = 0; //Growing + public static final int DEFAULT_GIOP_12_BUFFMGR = 2; //Streaming + public static final short ADDR_DISP_OBJKEY = 0; // object key used for target addressing + public static final short ADDR_DISP_PROFILE = 1; // iop profile used for target addressing + public static final short ADDR_DISP_IOR = 2; // ior used for target addressing + public static final short ADDR_DISP_HANDLE_ALL = 3; // accept all target addressing dispositions (default) + + // CORBA formal 00-11-03 sections 15.4.2.2, 15.4.3.2, 15.4.6.2 + // state that the GIOP 1.2 RequestMessage, ReplyMessage, and + // LocateReply message bodies must begin on 8 byte boundaries. + public static final int GIOP_12_MSG_BODY_ALIGNMENT = 8; + + // The GIOP 1.2 fragments must be divisible by 8. We generalize this + // to GIOP 1.1 fragments, as well. + public static final int GIOP_FRAGMENT_DIVISOR = 8; + public static final int GIOP_FRAGMENT_MINIMUM_SIZE = 32; + + public static final String ENV_IS_SERVER_PROPERTY = + SUN_PREFIX + "ORBEnvironmentIsGlassFishServer" ; + + // connection management properties + public static final String HIGH_WATER_MARK_PROPERTY = + SUN_PREFIX + "connection.ORBHighWaterMark" ; + public static final String LOW_WATER_MARK_PROPERTY = + SUN_PREFIX + "connection.ORBLowWaterMark" ; + public static final String NUMBER_TO_RECLAIM_PROPERTY = + SUN_PREFIX + "connection.ORBNumberToReclaim" ; + + public static final String ACCEPTOR_CLASS_PREFIX_PROPERTY = + SUN_PREFIX + "transport.ORBAcceptor"; + + public static final String CONTACT_INFO_LIST_FACTORY_CLASS_PROPERTY = + SUN_PREFIX + "transport.ORBContactInfoList"; + + // Legacy: + public static final String LEGACY_SOCKET_FACTORY_CLASS_PROPERTY = + SUN_PREFIX + "legacy.connection.ORBSocketFactoryClass" ; + + + public static final String SOCKET_FACTORY_CLASS_PROPERTY = + SUN_PREFIX + "transport.ORBSocketFactoryClass" ; + public static final String LISTEN_SOCKET_PROPERTY = + SUN_PREFIX + "transport.ORBListenSocket"; + public static final String IOR_TO_SOCKET_INFO_CLASS_PROPERTY = + SUN_PREFIX + "transport.ORBIORToSocketInfoClass"; + public static final String IIOP_PRIMARY_TO_CONTACT_INFO_CLASS_PROPERTY = + SUN_PREFIX + "transport.ORBIIOPPrimaryToContactInfoClass"; + + // Request partitioning maximum and minimum thread pool id constants. + public static final int REQUEST_PARTITIONING_MIN_THREAD_POOL_ID = 0; + public static final int REQUEST_PARTITIONING_MAX_THREAD_POOL_ID = 63; + + // Load balancing polices: integer to avoid issues with Enum encoding + public static final int FIRST_LOAD_BALANCING_VALUE = 0 ; + public static final int NO_LOAD_BALANCING = FIRST_LOAD_BALANCING_VALUE + 0 ; + public static final int PER_REQUEST_LOAD_BALANCING = FIRST_LOAD_BALANCING_VALUE + 1 ; + public static final int LAST_LOAD_BALANCING_VALUE = PER_REQUEST_LOAD_BALANCING ; + + // transport read tcp timeout property, colon separated property + // with syntax + // where the last parameter is optional and defaults to INTEGER.MAX_VALUE. + public static final String TRANSPORT_TCP_TIMEOUTS_PROPERTY = + SUN_PREFIX + "transport.ORBTCPTimeouts"; + + // Same syntax as TRANSPORT_TCP_TIMEOUTS_PROPERTY + public static final String TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY = + SUN_PREFIX + "transport.ORBTCPConnectTimeouts" ; + + // initial time to wait in milliseconds in a temporary + // Selector.select(long wait) if a transport tcp read + // or write returns 0 bytes + public static final int TRANSPORT_TCP_INITIAL_TIME_TO_WAIT = 2000; + + // max time to spend in cumulative waits in milliseconds + // if a transport tcp read or write returns 0 bytes + public static final int TRANSPORT_TCP_MAX_TIME_TO_WAIT = 6000; + + // A backoff percentage used to compute the next amount of time to + // wait on a subsequent transport tcp read or write of 0 bytes. + // It multiplies each wait time by 1.2. + public static final int TRANSPORT_TCP_BACKOFF_FACTOR = 20; + + // initial time to wait in milliseconds after an attempt to connect + // fails. + public static final int TRANSPORT_TCP_CONNECT_INITIAL_TIME_TO_WAIT = 250 ; + + // max time to spend in cumulative waits in milliseconds + // if a transport tcp read or write returns 0 bytes + public static final int TRANSPORT_TCP_CONNECT_MAX_TIME_TO_WAIT = 60000; + + // A backoff percentage used to compute the next amount of time to + // wait on a subsequent transport tcp read or write of 0 bytes. + // It multiplies each wait time by 1.2. + public static final int TRANSPORT_TCP_CONNECT_BACKOFF_FACTOR = 100; + + // Maximum time to wait before retrying to connect. + public static final int TRANSPORT_TCP_CONNECT_MAX_SINGLE_WAIT = 5000 ; + + public static final String USE_NIO_SELECT_TO_WAIT_PROPERTY = + SUN_PREFIX + "transport.ORBUseNIOSelectToWait"; + + // "Socket" | "SocketChannel" + // Note: Connections accepted by SocketChannel will be SocketChannel. + public static final String ACCEPTOR_SOCKET_TYPE_PROPERTY = + SUN_PREFIX + "transport.ORBAcceptorSocketType"; + + // Applicable if using SocketChannel and using select thread. + public static final String ACCEPTOR_SOCKET_USE_WORKER_THREAD_FOR_EVENT_PROPERTY = + SUN_PREFIX + "transport.ORBAcceptorSocketUseWorkerThreadForEvent"; + + // Applicable on client-side. "Socket" | "SocketChannel" + public static final String CONNECTION_SOCKET_TYPE_PROPERTY = + SUN_PREFIX + "transport.ORBConnectionSocketType"; + + // Applicable if using SocketChannel and using select thread + public static final String CONNECTION_SOCKET_USE_WORKER_THREAD_FOR_EVENT_PROPERTY = + SUN_PREFIX + "transport.ORBConnectionSocketUseWorkerThreadForEvent"; + + // Used to disable the use of direct byte buffers. This enables much easier + // debugging, because the contents of a direct byte buffer cannot be + // viewed in most (all?) debuggers. + public static final String DISABLE_DIRECT_BYTE_BUFFER_USE_PROPERTY = + SUN_PREFIX + "transport.ORBDisableDirectByteBufferUse" ; + + // The default ByteBuffer size used to read data into when using the + // optimized read strategy which is used when USE_NIO_SELECT_TO_WAIT_PROPERTY + // is true, (default). + public static final int DEFAULT_READ_BYTE_BUFFER_SIZE = 64000; + + // Property name to change the DEFAULT_READ_BYTE_BUFFER_SIZE value. + public static final String READ_BYTE_BUFFER_SIZE_PROPERTY = + SUN_PREFIX + "transport.ORBReadByteBufferSize"; + + // The default pooled DirectByteBuffer slab size. + public static final int DEFAULT_POOLED_DIRECT_BYTE_BUFFER_SLAB_SIZE = + 4000000; // 4 megabytes + + // The property name to set the size of the pooled DirectByteBuffer + // slab size. + public static final String POOLED_DIRECT_BYTE_BUFFER_SLAB_SIZE_PROPERTY = + SUN_PREFIX + "transport.ORBPooledDirectByteBufferSlabSize"; + + // Maximum read ByteBuffer size threshhold for which a single message will + // be read. + public static final int MAX_READ_BYTE_BUFFER_SIZE_THRESHOLD = 256000; // 256 kbytes + + // Property to override the default MAX_READ_BYTE_BUFFER_SIZE_THRESHOLD + public static final String MAX_READ_BYTE_BUFFER_SIZE_THRESHOLD_PROPERTY = + SUN_PREFIX + "transport.ORBMaximumReadByteBufferSize"; + + // A property that can tell the optimized read implementation to always + // enter a blocking read before returning control the Selector Thread. + public static final String ALWAYS_ENTER_BLOCKING_READ_PROPERTY = + SUN_PREFIX + "transport.ORBOptimizedReadAlwaysEnterBlockingRead"; + + // A property that can tell the optimized read implementation to read + // until zero bytes are read by the non-blocking read. + public static final String NON_BLOCKING_READ_CHECK_MESSAGE_PARSER_PROPERTY = + SUN_PREFIX + "transport.ORBNonBlockingReadCheckMessageParser"; + + // A property that can tell the optimized read implementation to be more + // patient about expecting additional data to arrive. + public static final String BLOCKING_READ_CHECK_MESSAGE_PARSER_PROPERTY = + SUN_PREFIX + "transport.ORBBlockingReadCheckMessageParser"; + + public static final String SOCKET = "Socket"; + public static final String SOCKETCHANNEL = "SocketChannel"; + + public static final String WAIT_FOR_RESPONSE_TIMEOUT = + SUN_PREFIX + "transport.ORBWaitForResponseTimeout"; + + public static final String NO_DEFAULT_ACCEPTORS = + SUN_PREFIX + "transport.ORBNoDefaultAcceptors" ; + + public static final String REGISTER_MBEANS = + SUN_PREFIX + "ORBRegisterMBeans" ; + + public static final int DEFAULT_FRAGMENT_READ_TIMEOUT = 18000 ; + + public static final String FRAGMENT_READ_TIMEOUT = + SUN_PREFIX + "ORBFragmentReadTimeout" ; + + // POA related policies + public static final String PERSISTENT_SERVER_PORT_PROPERTY = + SUN_PREFIX + "POA.ORBPersistentServerPort" ; + public static final String BAD_SERVER_ID_HANDLER_CLASS_PROPERTY = + SUN_PREFIX + "POA.ORBBadServerIdHandlerClass" ; + public static final String ACTIVATED_PROPERTY = + SUN_PREFIX + "POA.ORBActivated" ; + public static final String SERVER_NAME_PROPERTY = + SUN_PREFIX + "POA.ORBServerName" ; + + // Server Properties; e.g. when properties passed to ORB activated + // servers + + public static final String SERVER_DEF_VERIFY_PROPERTY = + SUN_PREFIX + "activation.ORBServerVerify" ; + + public static final String JTS_CLASS_PROPERTY = + SUN_PREFIX + "CosTransactions.ORBJTSClass" ; + + // Property for enabling ORB's use of Java serialization. + public static final String ENABLE_JAVA_SERIALIZATION_PROPERTY = + SUN_PREFIX + "encoding.ORBEnableJavaSerialization"; + + // Constants for ORB prefixes ************************************************************** + + public static final String PI_ORB_INITIALIZER_CLASS_PREFIX = + "org.omg.PortableInterceptor.ORBInitializerClass."; + + public static final String USER_CONFIGURATOR_PREFIX = + SUN_PREFIX + "ORBUserConfigurators." ; + + public static final String RFM_PROPERTY = USER_CONFIGURATOR_PREFIX + + "com.sun.corba.ee.impl.oa.rfm.ReferenceManagerConfigurator" ; + + public static final String USE_DYNAMIC_STUB_PROPERTY = + SUN_PREFIX + "ORBUseDynamicStub" ; + + public static final String DEBUG_DYNAMIC_STUB = + SUN_PREFIX + "ORBDebugStubGeneration" ; + + // Not available through ORBData: used only in test.Test + // and in the optional ClassCopierOrdinaryImpl class. + public static final String USE_CODEGEN_REFLECTIVE_COPYOBJECT = + SUN_PREFIX + "ORBUseCodegenReflectiveCopyobject" ; + + public static final String DYNAMIC_STUB_FACTORY_FACTORY_CLASS = + SUN_PREFIX + "ORBDynamicStubFactoryFactoryClass" ; + + // Constants for NameService properties ************************************ + + public static final int DEFAULT_INITIAL_PORT = 900; + + public static final String DEFAULT_INS_HOST = "localhost"; + + public static final int DEFAULT_INS_PORT = 2809; + + public static final int DEFAULT_INS_GIOP_MAJOR_VERSION = 1; + + // http://www.omg.org/cgi-bin/doc?ptc/00-08-07 [ Section 13.6.7.3 ] + // defines the default GIOP minor version to be 0. + public static final int DEFAULT_INS_GIOP_MINOR_VERSION = 0; + + + // Constants for INS properties ******************************************** + + // GIOP Version number for validation of INS URL format addresses + public static final int MAJORNUMBER_SUPPORTED = 1; + public static final int MINORNUMBERMAX = 2; + + // Subcontract's differentiation using the TRANSIENT and PERSISTENT + // Name Service Property. + public static final int TRANSIENT = 1; + public static final int PERSISTENT = 2; + + // Constants for ORBD properties **************************************************************** + + // Used to disable ORBD, which is the normal case when the ORBFactory is used to create an ORB. + public static final String DISABLE_ORBD_INIT_PROPERTY = SUN_PREFIX + "activation.ORBDisableORBD" ; + + // These properties are never passed on ORB init: they are only passed to ORBD. + + public static final String DB_DIR_PROPERTY = SUN_PREFIX + "activation.DbDir" ; + public static final String DB_PROPERTY = SUN_PREFIX + "activation.db" ; + public static final String ORBD_PORT_PROPERTY = SUN_PREFIX + "activation.Port" ; + public static final String SERVER_POLLING_TIME = SUN_PREFIX + "activation.ServerPollingTime"; + public static final String SERVER_STARTUP_DELAY = SUN_PREFIX + "activation.ServerStartupDelay"; + + public static final int DEFAULT_ACTIVATION_PORT = 1049 ; + + // If RI is starting the NameService then they would indicate that by + // passing the RI flag. That would start a Persistent Port to listen to + // INS request. + public static final int RI_NAMESERVICE_PORT = 1050; + + public static final int DEFAULT_SERVER_POLLING_TIME = 1000; + + public static final int DEFAULT_SERVER_STARTUP_DELAY = 1000; + + + //***************** Constants for Logging **************** + + public static final String LOG_LEVEL_PROPERTY = SUN_PREFIX + "ORBLogLevel"; + + public static final String LOG_RESOURCE_FILE = + "com.sun.corba.ee.impl.logging.LogStrings"; + + public static final String SHOW_INFO_MESSAGES + = SUN_PREFIX + "ORBShowInfoMessages"; + + public static final String GET_SERVICE_CONTEXT_RETURNS_NULL + = SUN_PREFIX + "ORBGetServiceContextReturnsNull"; + + // Constants for initial references ************************************************************* + + public static final String TRANSIENT_NAME_SERVICE_NAME = "TNameService" ; + public static final String PERSISTENT_NAME_SERVICE_NAME = "NameService" ; + + // A large Number to make sure that other ServerIds doesn't collide + // with NameServer Persistent Server Id + public static final String NAME_SERVICE_SERVER_ID = "1000000" ; + + public static final String ROOT_POA_NAME = "RootPOA" ; + public static final String POA_CURRENT_NAME = "POACurrent" ; + public static final String SERVER_ACTIVATOR_NAME = "ServerActivator" ; + public static final String SERVER_LOCATOR_NAME = "ServerLocator" ; + public static final String SERVER_REPOSITORY_NAME = "ServerRepository" ; + public static final String INITIAL_NAME_SERVICE_NAME= "InitialNameService" ; + public static final String TRANSACTION_CURRENT_NAME = "TransactionCurrent" ; + public static final String DYN_ANY_FACTORY_NAME = "DynAnyFactory" ; + public static final String REFERENCE_FACTORY_MANAGER= "ReferenceFactoryManager" ; + + // New for Portable Interceptors + public static final String PI_CURRENT_NAME = "PICurrent" ; + public static final String CODEC_FACTORY_NAME = "CodecFactory" ; + + public static final String FOLB_CLIENT_GROUP_INFO_SERVICE = + "FolbClientGroupInfoService"; + + public static final String FOLB_SERVER_GROUP_INFO_SERVICE = + "FolbServerGroupInfoService"; + + public static final String CSI_V2_SSL_TAGGED_COMPONENT_HANDLER = + "CSIv2SSLTaggedComponentHandler"; + + + // Constants for ORBD DB *********************************************************************** + + public static final String DEFAULT_DB_DIR = "orb.db" ; + public static final String DEFAULT_DB_NAME = "db" ; + public static final String INITIAL_ORB_DB = "initial.db" ; + public static final String SERVER_LOG_DIR = "logs" ; + public static final String ORBID_DIR_BASE = "orbids" ; + public static final String ORBID_DB_FILE_NAME = "orbids.db" ; + + // Constants for minor code bases ************************************************************** + // This is the value that pre-Merlin Sun ORBs incorrectly used. We preserve this + // here for backwards compatibility, but note that the current ORB must never + // create a BAD_PARAM system exception with this minor code. + public static final int LEGACY_SUN_NOT_SERIALIZABLE = SUNVMCID.value + 1 ; + + // Code Set related ******************************************************* + + // If we don't always send the code set context, there's a possibility + // of failure when fragments of a smaller request are interleved with + // those of a first request with other large service contexts. + // + public static final boolean DEFAULT_ALWAYS_SEND_CODESET_CTX = true; + public static final String ALWAYS_SEND_CODESET_CTX_PROPERTY + = SUN_PREFIX + "codeset.AlwaysSendCodeSetCtx"; + + // Use byte order markers in streams when applicable? This won't apply to + // GIOP 1.1 due to limitations in the CDR encoding. + public static final boolean DEFAULT_USE_BYTE_ORDER_MARKERS = true; + public static final String USE_BOMS = SUN_PREFIX + "codeset.UseByteOrderMarkers"; + + // Use byte order markers in encapsulations when applicable? + public static final boolean DEFAULT_USE_BYTE_ORDER_MARKERS_IN_ENCAPS = false; + public static final String USE_BOMS_IN_ENCAPS = SUN_PREFIX + "codeset.UseByteOrderMarkersInEncaps"; + + // The CHAR_CODESETS and WCHAR_CODESETS allow the user to override the default + // connection code sets. The value should be a comma separated list of OSF + // registry numbers. The first number in the list will be the native code + // set. + // + // Number can be specified as hex if preceded by 0x, otherwise they are + // interpreted as decimal. + // + // Code sets that we accept currently (see core/OSFCodeSetRegistry): + // + // char/string: + // + // ISO8859-1 (Latin-1) 0x00010001 + // ISO646 (ASCII) 0x00010020 + // UTF-8 0x05010001 + // + // wchar/string: + // + // UTF-16 0x00010109 + // UCS-2 0x00010100 + // UTF-8 0x05010001 + // + // Note: The ORB will let you assign any of the above values to + // either of the following properties, but the above assignments + // are the only ones that won't get you into trouble. + public static final String CHAR_CODESETS = SUN_PREFIX + "codeset.charsets"; + public static final String WCHAR_CODESETS = SUN_PREFIX + "codeset.wcharsets"; + + // Constants to make stream format version code easier to read + public static final byte STREAM_FORMAT_VERSION_1 = (byte)1; + public static final byte STREAM_FORMAT_VERSION_2 = (byte)2; + + // Constants used for denoting different serialization encodings. + public static final byte CDR_ENC_VERSION = (byte) 0; + public static final byte JAVA_ENC_VERSION = (byte) 1; + + // property to check if the current ORB was created from within the app server + public static final String APPSERVER_MODE = SUN_PREFIX + "ORBAppServerMode"; + + // name for looking up the remote object for getting initial clister instance info + public static final String INITIAL_GROUP_INFO_SERVICE = "INITIAL_GIS" ; + + // Enable the use of internal timing points. This slows the ORB down slightly, + // even if none of the individual timing points are themselves enabled. + public static final String TIMING_POINTS_ENABLED = SUN_PREFIX + + "ORBEnableTimingPoints" ; + + // Enable the use of the EnumDesc class for marshaling enums. Really only + // present for testing. + public static final String USE_ENUM_DESC = SUN_PREFIX + + "ORBUseEnumDesc" ; + + // Specify an AMXv3-compliant ObjectName (as a string) for the parent of the + // ORB's gmbal root. + public static final String GMBAL_ROOT_PARENT_NAME = SUN_PREFIX + + "ORBGmbalRootParentName" ; +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/NullServant.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/NullServant.java new file mode 100644 index 000000000..4292f669e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/NullServant.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa ; + +import org.omg.CORBA.SystemException ; + +/** NullServant is used to represent a null servant returned + * OAInvocationInfo after a + * ObjectAdapter.getInvocationServant( OAInvocationInfo ) call. + * If the getInvocationServant call could not locate a servant + * for the ObjectId in the OAInvocationInfo, getServantContainer + * will contain a NullServant. Later stages of the request + * dispatch may choose either to throw the exception or perform + * some other action in response to the NullServant result. + */ +public interface NullServant +{ + /** Obtain the exception that is associated with this + * NullServant instance. + */ + SystemException getException() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OADefault.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OADefault.java new file mode 100644 index 000000000..fa3bc7c10 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OADefault.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa ; + +import com.sun.corba.ee.impl.oa.poa.POAFactory ; +import com.sun.corba.ee.impl.oa.toa.TOAFactory ; +import com.sun.corba.ee.spi.orb.ORB ; + +/** OADefault provides methods to create the standard ObjectAdapterFactory + * instances for this version of the ORB. These methods are generally + * used in ORBConfigurator instances to construct an ORB instance. + */ +public class OADefault { + public static ObjectAdapterFactory makePOAFactory( ORB orb ) + { + ObjectAdapterFactory oaf = new POAFactory() ; + oaf.init( orb ) ; + return oaf ; + } + + public static ObjectAdapterFactory makeTOAFactory( ORB orb ) + { + ObjectAdapterFactory oaf = new TOAFactory() ; + oaf.init( orb ) ; + return oaf ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OADestroyed.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OADestroyed.java new file mode 100644 index 000000000..45c07aa33 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OADestroyed.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa; + +/** This exception is thrown when an operation on an ObjectAdapter + * fails because the ObjectAdapter was destroyed during the operation. + */ +public class OADestroyed extends java.lang.Exception { +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OAInvocationInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OAInvocationInfo.java new file mode 100644 index 000000000..dbcd50eb3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/OAInvocationInfo.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa; + +import javax.rmi.CORBA.Tie ; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; +import org.omg.CORBA.portable.ServantObject; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; + + +/** This class is a holder for the information required to implement POACurrent. +* It is also used for the ServantObject that is returned by _servant_preinvoke calls. +* This allows us to avoid allocating an extra object on each collocated invocation. +*/ +public class OAInvocationInfo extends ServantObject { + // This is the container object for the servant. + // In the RMI-IIOP case, it is the RMI-IIOP Tie, and the servant is the + // target of the Tie. + // In all other cases, it is the same as the Servant. + private java.lang.Object servantContainer ; + + // These fields are to support standard OMG APIs. + private ObjectAdapter oa; + private byte[] oid; + + // These fields are to support the Object adapter implementation. + private CookieHolder cookieHolder; + private String operation; + + // This is the copier to be used by javax.rmi.CORBA.Util.copyObject(s) + // For the current request. + private ObjectCopierFactory factory ; + + public OAInvocationInfo(ObjectAdapter oa, byte[] id ) + { + this.oa = oa; + this.oid = id; + } + + // Copy constructor of sorts; used in local optimization path + public OAInvocationInfo( OAInvocationInfo info, String operation ) + { + this.servant = info.servant ; + this.servantContainer = info.servantContainer ; + this.cookieHolder = info.cookieHolder ; + this.oa = info.oa; + this.oid = info.oid; + this.factory = info.factory ; + + this.operation = operation; + } + + //getters + public ObjectAdapter oa() { return oa ; } + public byte[] id() { return oid ; } + public Object getServantContainer() { return servantContainer ; } + + // Create CookieHolder on demand. This is only called by a single + // thread, so no synchronization is needed. + public CookieHolder getCookieHolder() + { + if (cookieHolder == null) + cookieHolder = new CookieHolder() ; + + return cookieHolder; + } + + public String getOperation() { return operation; } + public ObjectCopierFactory getCopierFactory() { return factory; } + + //setters + public void setOperation( String operation ) { this.operation = operation ; } + public void setCopierFactory( ObjectCopierFactory factory ) { this.factory = factory ; } + + public void setServant(Object servant) + { + servantContainer = servant ; + if (servant instanceof Tie) + this.servant = ((Tie)servant).getTarget() ; + else + this.servant = servant; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapter.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapter.java new file mode 100644 index 000000000..1b2b2bf19 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapter.java @@ -0,0 +1,249 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa ; + +import org.omg.CORBA.Policy ; + +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.ObjectReferenceFactory ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.IORTemplate ; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.gmbal.ManagedObject; + +// REVISIT: What should the order be? enter/push...pop/exit? + +/** ObjectAdapter represents the abstract model of an object +* adapter that was introduced by ORT. This means that all +* object adapters must: +*

          +*
        • Have an ORB
        • +*
        • Have a name
        • +*
        • Have an adapter manager (represented by an ID)
        • +*
        • Have an adapter template
        • +*
        • Support getting and setting their ObjectReferenceFactory
        • +*
        • Provide access to their current state
        • +*
        • Support adding components to their profiles expressed in the adapter template
        • +*
        +* Other requirements: +*
          +*
        • All object adapters must invoke ORB.AdapterCreated when they are created. +*
        • +*
        • All adapter managers must invoke ORB.AdapterManagerStateChanged when +* their state changes, mapping the internal state to an ORT state.
        • +*
        • AdapterStateChanged must be invoked (from somewhere) whenever +* an adapter state changes that is not due to an adapter manager state change.
        • +*
        +*

        +* Object adapters must also provide mechanisms for: +*

          +*
        • Managing object reference lifecycle
        • +*
        • Controlling how servants are associated with object references
        • +*
        • Manage the state of the adapter, if the adapter desires to implement such mechanisms
        • +*
        +* Such mechanisms are all object adapter specific, and so we do not attempt to +* create general APIs for these functions here. The object adapter itself +* must provide these APIs directly to the user, and they do not affect the rest of the +* ORB. This interface basically makes it possible to plug any object adapter into the +* ORB and have the OA work propertly with portable interceptors, and also have requests +* dispatched properly to the object adapter. +*

        +* The basic function of an ObjectAdapter is to map object IDs to servants and to support +* the dispatch operation of the subcontract, which dispatches requests to servants. +* This is the purpose of the getInvocationServant method. In addition, ObjectAdapters must be +* able to change state gracefully in the presence of executing methods. This +* requires the use of the enter/exit methods. Finally, ObjectAdapters often +* require access to information about requests. This is accomodated through the +* OAInvocationInfo class and the thread local stack maintained by push/pop/peekInvocationInfo +* on the ORB. +*

        +* To be useful, this dispatch cycle must be extremely efficient. There are several +* scenarios that matter: +*

          +*
        1. A remote invocation, where the dispatch is handled in the server subcontract.
        2. +*
        3. A local invocation, where the dispatch is handled in the client subcontract.
        4. +*
        5. A cached local invocation, where the servant is cached when the IOR is established +* for the client subcontract, and the dispatch is handled in the client subcontract +* to the cached subcontract.
        6. +*
        +*

        +* Each of these 3 cases is handled a bit differently. On each request, assume as known +* ObjectId and ObjectAdapterId, which can be obtained from the object key. +* The ObjectAdaptorFactory is available in the subcontract registry, where it is +* registered under the subcontract ID. The Subcontract ID is also available in the +* object key. +*

          +*
        1. The remote pattern: +*
            +*
          1. oa = oaf.find( oaid )
          2. +*
          3. oa.enter()
          4. +*
          5. info = oa.makeInvocationInfo( oid )
          6. +*
          7. info.setOperation( operation )
          8. +*
          9. push info
          10. +*
          11. oa.getInvocationServant( info )
          12. +*
          13. sreq.setExecuteReturnServantInResponseConstructor( true )
          14. +*
          15. dispatch to servant
          16. +*
          17. oa.returnServant()
          18. +*
          19. oa.exit()
          20. +*
          21. pop info
          22. +*
              +* +* REVISIT: Is this the required order for exit/pop? Can they be nested instead? +* Note that getInvocationServant and returnServant may throw exceptions. In such cases, +* returnServant, exit, and pop must be called in the correct order. +*
            1. The local pattern: +*
                +*
              1. oa = oaf.find( oaid )
              2. +*
              3. oa.enter()
              4. +*
              5. info = oa.makeInvocationInfo( oid )
              6. +*
              7. info.setOperation( operation )
              8. +*
              9. push info
              10. +*
              11. oa.getInvocationServant( info )
              12. +*
              13. dispatch to servant
              14. +*
              15. oa.returnServant()
              16. +*
              17. oa.exit()
              18. +*
              19. pop info
              20. +*
                  +* +* This is the same as the remote case, except that setExecuteReturnServantInResponseConstructor +* is not needed (or possible, since there is no server request). +*
                1. The fast local pattern: When delegate is constructed, +* first extract ObjectKey from IOR in delegate, +* then get ObjectId, ObjectAdapterId, and ObjectAdapterFactory (oaf). Then: +*
                    +*
                  1. oa = oaf.find( oaid )
                  2. +*
                  3. info = oa.makeInvocationInfo( oid ) (note: no operation!)
                  4. +*
                  5. push info (needed for the correct functioning of getInvocationServant)
                  6. +*
                  7. oa.getInvocationServant( info )
                  8. +*
                  9. pop info +*
                  +* The info instance (which includes the Servant) is cached in the client subcontract. +*

                  Then, on each invocation:

                  +*
                    +*
                  1. newinfo = copy of info (clone)
                  2. +*
                  3. info.setOperation( operation )
                  4. +*
                  5. push newinfo
                  6. +*
                  7. oa.enter()
                  8. +*
                  9. dispatch to servant
                  10. +*
                  11. oa.returnServant()
                  12. +*
                  13. oa.exit()
                  14. +*
                  15. pop info
                  16. +*
                  +*
                2. +*
                +*/ +@ManagedObject +@Description( "ObjectAdapter used to dispatch requests and manage servants") +public interface ObjectAdapter +{ + //////////////////////////////////////////////////////////////////////////// + // Basic methods for supporting interceptors + //////////////////////////////////////////////////////////////////////////// + + /** Returns the ORB associated with this adapter. + */ + ORB getORB() ; + + Policy getEffectivePolicy( int type ) ; + + /** Returns the IOR template of this adapter. The profiles + * in this template may be updated only during the AdapterCreated call. + * After that call completes, the IOR template must be made immutable. + * Note that the server ID, ORB ID, and adapter name are all available + * from the IOR template. + */ + @ManagedAttribute + @Description( "The IORTemplate used to create Object References") + IORTemplate getIORTemplate() ; + + //////////////////////////////////////////////////////////////////////////// + // Methods needed to support ORT. + //////////////////////////////////////////////////////////////////////////// + + /** Return the ID of the AdapterManager for this object adapter. + */ + @ManagedAttribute + @Description( "The identifier for the AdapterManager that manages this ObjectAdapter") + int getManagerId() ; + + /** Return the current state of this object adapter (see + * org.omg.PortableInterceptors for states. + */ + short getState() ; + + @ManagedAttribute + @Description( "The adapter template" ) + ObjectReferenceTemplate getAdapterTemplate() ; + + @ManagedAttribute + @Description( "The current object reference factory" ) + ObjectReferenceFactory getCurrentFactory() ; + + /** Change the current factory. This may only be called during the + * AdapterCreated call. + */ + void setCurrentFactory( ObjectReferenceFactory factory ) ; + + //////////////////////////////////////////////////////////////////////////// + // Methods required for dispatching to servants + //////////////////////////////////////////////////////////////////////////// + + /** Get the servant corresponding to the given objectId, if this is supported. + * This method is only used for models where the servant is an ObjectImpl, + * which allows the servant to be used directly as the stub. This allows an object + * reference to be replaced by its servant when it is unmarshalled locally. + * Such objects are not ORB mediated. + */ + org.omg.CORBA.Object getLocalServant( byte[] objectId ) ; + + /** Get the servant for the request given by the parameters. + * info must contain a valid objectId in this call. + * The servant is set in the InvocationInfo argument that is passed into + * this call. + * @param info is the InvocationInfo object for the object reference + * @exception ForwardException (a runtime exception) is thrown if the request + * is to be handled by a different object reference. + */ + void getInvocationServant( OAInvocationInfo info ) ; + + /** enter must be called before each request is invoked on a servant. + * @exception OADestroyed is thrown when an OA has been destroyed, which + * requires a retry in the case where an AdapterActivator is present. + */ + void enter( ) throws OADestroyed ; + + /** exit must be called after each request has been completed. If enter + * is called and completes normally, there must always be a corresponding exit. + * If enter throw OADestroyed, exit must NOT be called. + */ + void exit( ) ; + + /** Must be called every time getInvocationServant is called after + * the request has completed. + */ + public void returnServant() ; + + /** Create an instance of InvocationInfo that is appropriate for this + * Object adapter. + */ + OAInvocationInfo makeInvocationInfo( byte[] objectId ) ; + + /** Return the most derived interface for the given servant and objectId. + */ + String[] getInterfaces( Object servant, byte[] objectId ) ; + + public boolean isNameService(); + + public void setNameService( boolean flag ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapterBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapterBase.java new file mode 100644 index 000000000..b517c576e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapterBase.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa ; + +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.ObjectReferenceFactory ; + +import org.omg.CORBA.Policy ; + +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.PIHandler ; + +import com.sun.corba.ee.spi.logging.POASystemException ; +import com.sun.corba.ee.impl.oa.poa.Policies; +import org.glassfish.gmbal.Description; +import org.glassfish.gmbal.ManagedAttribute; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; +import org.omg.PortableInterceptor.ACTIVE; +import org.omg.PortableInterceptor.DISCARDING; +import org.omg.PortableInterceptor.HOLDING; +import org.omg.PortableInterceptor.INACTIVE; +import org.omg.PortableInterceptor.NON_EXISTENT; + +abstract public class ObjectAdapterBase extends org.omg.CORBA.LocalObject + implements ObjectAdapter +{ + protected static final POASystemException wrapper = + POASystemException.self ; + + private ORB orb; + + // Data related to the construction of object references and + // supporting the Object Reference Template. + private IORTemplate iortemp; + private byte[] adapterId ; + private ObjectReferenceTemplate adapterTemplate ; + private ObjectReferenceFactory currentFactory ; + private boolean isNameService = false ; + + public ObjectAdapterBase( ORB orb ) { + this.orb = orb ; + } + + public final POASystemException wrapper() { + return wrapper ; + } + + /* + * This creates the complete template. + * When it is done, reference creation can proceed. + */ + final public void initializeTemplate( ObjectKeyTemplate oktemp, + boolean notifyORB, Policies policies, String codebase, + String objectAdapterManagerId, ObjectAdapterId objectAdapterId) + { + adapterId = oktemp.getAdapterId() ; + + iortemp = IORFactories.makeIORTemplate(oktemp) ; + + // This calls acceptors which create profiles and may + // add tagged components to those profiles. + orb.getCorbaTransportManager().addToIORTemplate( + iortemp, policies, + codebase, objectAdapterManagerId, objectAdapterId); + + adapterTemplate = IORFactories.makeObjectReferenceTemplate( orb, + iortemp ) ; + currentFactory = adapterTemplate ; + + if (notifyORB) { + PIHandler pih = orb.getPIHandler() ; + if (pih != null) { + pih.objectAdapterCreated(this); + } + } + + iortemp.makeImmutable() ; + } + + final public org.omg.CORBA.Object makeObject( String repId, byte[] oid ) + { + if (repId == null) { + throw wrapper.nullRepositoryId(); + } + return currentFactory.make_object( repId, oid ) ; + } + + final public byte[] getAdapterId() + { + return adapterId ; + } + + final public ORB getORB() + { + return orb ; + } + + abstract public Policy getEffectivePolicy( int type ) ; + + final public IORTemplate getIORTemplate() + { + return iortemp ; + } + + abstract public int getManagerId() ; + + abstract public short getState() ; + + @ManagedAttribute( id="State" ) + @Description( "The current Adapter state") + private String getDisplayState( ) { + final short state = getState() ; + switch (state) { + case HOLDING.value : return "HOLDING" ; + case ACTIVE.value : return "ACTIVE" ; + case DISCARDING.value : return "DISCARDING" ; + case INACTIVE.value : return "INACTIVE" ; + case NON_EXISTENT.value : return "NON_EXISTENT" ; + default : return "" ; + } + } + + final public ObjectReferenceTemplate getAdapterTemplate() + { + return adapterTemplate ; + } + + final public ObjectReferenceFactory getCurrentFactory() + { + return currentFactory ; + } + + final public void setCurrentFactory( ObjectReferenceFactory factory ) + { + currentFactory = factory ; + } + + abstract public org.omg.CORBA.Object getLocalServant( byte[] objectId ) ; + + abstract public void getInvocationServant( OAInvocationInfo info ) ; + + abstract public void returnServant() ; + + abstract public void enter() throws OADestroyed ; + + abstract public void exit() ; + + abstract protected ObjectCopierFactory getObjectCopierFactory() ; + + // Note that all current subclasses share the same implementation of this method, + // but overriding it would make sense for OAs that use a different InvocationInfo. + public OAInvocationInfo makeInvocationInfo( byte[] objectId ) + { + OAInvocationInfo info = new OAInvocationInfo( this, objectId ) ; + info.setCopierFactory( getObjectCopierFactory() ) ; + return info ; + } + + abstract public String[] getInterfaces( Object servant, byte[] objectId ) ; + + public boolean isNameService() { + return isNameService ; + } + + public void setNameService( boolean flag ) { + isNameService = flag ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapterFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapterFactory.java new file mode 100644 index 000000000..5e8d50c78 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/ObjectAdapterFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; + +public interface ObjectAdapterFactory { + /** Initialize this object adapter factory instance. + */ + void init( ORB orb ) ; + + /** Shutdown all object adapters and other state associated + * with this factory. + */ + void shutdown( boolean waitForCompletion ) ; + + /** Find the ObjectAdapter instance that corresponds to the + * given ObjectAdapterId. + */ + ObjectAdapter find( ObjectAdapterId oaid ) ; + + ORB getORB() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/rfm/ReferenceFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/rfm/ReferenceFactory.java new file mode 100644 index 000000000..10caf9050 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/rfm/ReferenceFactory.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa.rfm ; + +public interface ReferenceFactory extends org.omg.CORBA.Object, + org.omg.CORBA.portable.IDLEntity +{ + /** Create an object reference with the given key and + * repository ID. + */ + org.omg.CORBA.Object createReference( byte[] key ) ; + + /** Destroy this ReferenceFactory. + */ + void destroy() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/oa/rfm/ReferenceFactoryManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/rfm/ReferenceFactoryManager.java new file mode 100644 index 000000000..1fd5413b5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/oa/rfm/ReferenceFactoryManager.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.oa.rfm ; + +import java.util.Map ; +import java.util.List ; +import org.glassfish.pfl.basic.contain.Pair; + +import org.omg.CORBA.Policy ; + +import org.omg.PortableServer.ServantLocator ; + +/** ReferenceFactoryManager uses the ORB POA to create + * a specialized reference factory. This is done primarily + * so that all POAs managed here can be restarted in order + * to be updated when parts of the ORB configuration are + * changed. For example, this is used in AS 9 to support + * dynamic fail over, which requires re-configuring the + * App server POAs whenever an instance joins or leaves + * a cluster. + *

                + * An instance of this interface can be obtained + * from an ORB by calling resolve_initial_references( "ReferenceFactoryManager" ). + * The ORB will have an instance of this available if it is started with the + * property ORBConstants.USER_CONFIGURATOR_PREFIX + + * "com.sun.corba.ee.impl.oa.rfm.ReferenceManagerConfigurator" set to a value + * (usually we use "1" as the value, but that does not matter). + * This will cause the configurator to set up the ORB so that the + * ReferenceFactoryManager is available, so long as the configurator class + * is available. Since this code is in the optional package, this just + * means that the optional ORB package contents must be in the classpath. + *

                + * Note that this interface is a simulated IDL local interface, but there + * is no actual IDL for this interface. + *

                + * Note that the suspend and resume methods must be called from the + * same thread in order for the thread synchronization to be handled + * correctly. Calling either of the restart() methods guarantees this, + * but disallows more complex ORB configuration changes. + */ +public interface ReferenceFactoryManager extends org.omg.CORBA.Object, + org.omg.CORBA.portable.IDLEntity +{ + public enum RFMState { READY, SUSPENDED } + + /** The state of the ReferenceFactoryManager. + */ + public RFMState getState(); + + /** Must be called before any other operation. + * Used to activate the ORB reference creation function. + */ + public void activate() ; + + /** Suspend all CORBA request processing on all references created + * by ReferenceFactory instances that were created by this + * ReferenceFactoryManager. This call does not return until + * after all currently executing calls have completed. + */ + public void suspend() ; + + /** Resume all CORBA request processing on all references created + * by ReferenceFactory instances that were created by this + * ReferenceFactoryManager. + */ + public void resume() ; + + /** Create a new reference factory with the given policies. + * All such reference factories will be persistent. The + * ServantLocator is solely responsible for creating + * servants: no internal caching will be performed. + * The following policies are always applied here: + *

                  + *
                • Servant retention policy NON_RETAIN + *
                • Request processing policy USE_SERVANT_MANAGER + *
                • Lifespan policy PERSISTENT + *
                + * These policies are required because all are essential to + * the correct functioning of this class in handling restarts. + * It is an error for the policies list to contain any value + * of the above 3 policies. + * All other policies must be given explicitly in the list. + * @param name is the name of this ReferenceFactory. This is a + * simple flat name, not a hierarchical name. + * @param repositoryId is the repoid to be used when this reference factory + * creates a new CORBA Object reference. + * @param policies are the policies to be used to create the underlying POA. + */ + public ReferenceFactory create( String name, String repositoryId, List policies, + ServantLocator manager ) ; + + /** Get the ReferenceFactory name from a String[] adapterName, if + * adapterName is the name of a ReferenceFactory. If not, return null. + */ + public ReferenceFactory find( String[] adapterName ) ; + + /** Find the ReferenceFactory with the given name. + * If no such ReferenceFactory exists, return null. + */ + public ReferenceFactory find( String name ) ; + + /** Restart all ReferenceFactories. + * @param updates is a map giving the updated policies for + * some or all of the ReferenceFactory instances in this ReferenceFactoryManager. + * This parameter must not be null. + */ + public void restartFactories( Map>> updates ) ; + + /** Restart all ReferenceFactories. + * Equivalent to calling restartFactories( new Map() ). + */ + public void restartFactories() ; + + /** Restart all ReferenceFactories. This is done safely, so that + * any request against object references created from these factories + * complete correctly. Restart does not return until all restart + * activity completes. This method is equivalent to: + *
                +     * suspend() ;
                +     * try {
                +     *     restartFactories( updates ) ;
                +     * } finally {
                +     *     resume() ;
                +     * }
                +     * 
                + * @param updates is a map giving the updated policies for + * some or all of the ReferenceFactory instances in this ReferenceFactoryManager. + * This parameter must not be null. + */ + public void restart( Map>> updates ) ; + + /** Restart all ReferenceFactories. This is done safely, so that + * any request against object references created from these factories + * complete correctly. Restart does not return until all restart + * activity completes. Equivalent to calling restart( new Map() ). + */ + public void restart() ; + + public boolean isRfmName( String[] adapterName ) ; + +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ClassCodeBaseHandler.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ClassCodeBaseHandler.java new file mode 100644 index 000000000..0cb744290 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ClassCodeBaseHandler.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb; + +public interface ClassCodeBaseHandler { + /** Returns some sort of codebase for the given class, or null. + * It is expected that, if str is the result of getCodeBase( cls ), + * then loadClass( str, cls.getClassName() ) will return cls. + * A codebase to use with this handler, or null if this handler + * does not apply to this class. + * @param cls Class for which we need a codebase + * @return Codebase string + */ + String getCodeBase( Class cls ) ; + + /** load a class given the classname and a codebase. + * The className will always satisfy cls.getClassName().equals( className ) + * if the call succeeds and returns a Class. + * codebase A string that somehow describes which ClassLoader to use. + * For example, the string could be an ordinary URL that a URL ClassLoader can use, + * or something more specialized, such as a description of an OSGi bundles and version. + * className The name of the class to load. + * The loaded class, or null if the class could not be loaded. + * @param codebase The codebase to use for finding the ClassLoader + * @param className The name of the class to load + * @return The loaded class + */ + Class loadClass( String codebase, String className ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/DataCollector.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/DataCollector.java new file mode 100644 index 000000000..3bc1d28f0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/DataCollector.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import java.applet.Applet ; +import java.util.Properties ; +import java.util.Vector ; + +/** Interface for collecting all sources of ORB configuration properties + * into a single properties object. A PropertyParser is needed so that + * the set of property names of interest is known. + */ +public interface DataCollector { + /** Return true iff this DataCollector was created from + * applet data. + */ + boolean isApplet() ; + + /** Return true iff the local host and ORB initial host are the same. + * This is provided to avoid exposing the local host in insecure + * contexts. + */ + boolean initialHostIsLocal() ; + + /** Set the parser which is used to obtain property names. + * This must be called before getProperties + * may be called. It may be called multiple times if different + * sets of properties are needed for the same data sources. + */ + void setParser( PropertyParser parser ) ; + + /** Return the consolidated property information to be used + * for ORB configuration. Note that -ORBInitRef arguments are + * handled specially: all -ORBInitRef name=value arguments are + * converted into ( org.omg.CORBA.ORBInitRef.name, value ) + * mappings in the resulting properties. Also, -ORBInitialServices + * is handled specially in applet mode: they are converted from + * relative to absolute URLs. + * @throws IllegalStateException if setPropertyNames has not + * been called. + */ + Properties getProperties() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORB.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORB.java new file mode 100644 index 000000000..b26936755 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORB.java @@ -0,0 +1,841 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb; + +import com.sun.corba.ee.impl.corba.TypeCodeFactory; +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.impl.ior.WireObjectKeyTemplate; +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler; +import com.sun.corba.ee.impl.transport.ByteBufferPoolImpl; +import com.sun.corba.ee.spi.copyobject.CopierManager; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.IORFactories; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.ObjectKeyFactory; +import com.sun.corba.ee.spi.ior.TaggedComponentFactoryFinder; +import com.sun.corba.ee.spi.ior.TaggedProfile; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.legacy.connection.LegacyServerSocketManager; +import com.sun.corba.ee.spi.logging.OMGSystemException; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import com.sun.corba.ee.spi.misc.ORBClassLoader; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.presentation.rmi.InvocationInterceptor; +import com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.protocol.ClientDelegateFactory; +import com.sun.corba.ee.spi.protocol.ClientInvocationInfo; +import com.sun.corba.ee.spi.protocol.PIHandler; +import com.sun.corba.ee.spi.protocol.RequestDispatcherRegistry; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.resolver.LocalResolver; +import com.sun.corba.ee.spi.resolver.Resolver; +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry; +import com.sun.corba.ee.spi.servicecontext.ServiceContextsCache; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.corba.ee.spi.trace.*; +import com.sun.corba.ee.spi.trace.Shutdown; +import com.sun.corba.ee.spi.transport.ByteBufferPool; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory; +import com.sun.corba.ee.spi.transport.TransportManager; +import org.glassfish.gmbal.*; +import org.glassfish.pfl.basic.func.UnaryFunction; +import org.glassfish.pfl.tf.spi.MethodMonitorFactoryDefaults; +import org.glassfish.pfl.tf.spi.MethodMonitorRegistry; +import org.glassfish.pfl.tf.spi.annotation.InfoMethod; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.PortableServer.Servant; + +import javax.management.ObjectName; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Logger; + +@OrbLifeCycle +@ManagedObject +@Description( "The Main ORB Implementation object" ) +@AMXMetadata( type="ORB-Root" ) +public abstract class ORB extends com.sun.corba.ee.org.omg.CORBA.ORB + implements TypeCodeFactory +{ + static { + MethodMonitorFactoryDefaults.addPrefix( "com.sun.corba.ee", "ORB" ) ; + } + + // As much as possible, this class should be stateless. However, + // there are a few reasons why it is not: + // + // 1. The ORB debug flags are defined here because they are accessed + // frequently, and we do not want a cast to the impl just for that. + // 2. typeCodeMap and primitiveTypeCodeConstants are here because they + // are needed in both ORBImpl and ORBSingleton. + // 3. Logging support is here so that we can avoid problems with + // incompletely initialized ORBs that need to perform logging. + + // This is not one of the xxxDebugFlags because it is used to debug the mechanism + // that sets the xxxDebugFlags! + public static final boolean orbInitDebug = AccessController.doPrivileged( + new PrivilegedAction() { + public Boolean run() { + return Boolean.getBoolean( ORBConstants.INIT_DEBUG_PROPERTY ); + } + } + ) ; + + // Currently defined debug flags. Any additions must be called xxxDebugFlag. + // All debug flags must be public boolean types. + // These are set by passing the flag -ORBDebug x,y,z in the ORB init args. + // Note that x,y,z must not contain spaces. + // + // The annotations (when present) connect the ORB debug flags to the tracing + // system. Whenever a flag is set, the corresponding tracing annotation + // is also set in the MethodMonitorRegistry to a standard tracing + // MethodMonitorFactory. A few cases still make direct access to this + // flags, and the flags are much faster to test than the state of the + // MethodMonitorRegistry. + + @Transport + public boolean transportDebugFlag = false ; + + @Subcontract + public boolean subcontractDebugFlag = false ; + + @Osgi + public boolean osgiDebugFlag = false ; + + @Poa + public boolean poaDebugFlag = false ; + + @PoaFSM + public boolean poaFSMDebugFlag = false ; + + @Orbd + public boolean orbdDebugFlag = false ; + + @Naming + public boolean namingDebugFlag = false ; + + @TraceServiceContext + public boolean serviceContextDebugFlag = false ; + + @TransientObjectManager + public boolean transientObjectManagerDebugFlag = false ; + + @Shutdown + public boolean shutdownDebugFlag = false; + + @Giop + public boolean giopDebugFlag = false; + + public boolean giopSizeDebugFlag = false; + public boolean giopReadDebugFlag = false; + + @TraceInterceptor + public boolean interceptorDebugFlag = false ; + + @Folb + public boolean folbDebugFlag = false ; + + public boolean cdrCacheDebugFlag = false ; + + @Cdr + public boolean cdrDebugFlag = false ; + + @StreamFormatVersion + public boolean streamFormatVersionDebugFlag = false ; + + @TraceValueHandler + public boolean valueHandlerDebugFlag = false ; + + public boolean mbeanDebugFlag = false ; + public boolean mbeanFineDebugFlag = false ; + public boolean mbeanRuntimeDebugFlag = false ; + + @OrbLifeCycle + public boolean orbLifecycleDebugFlag = false ; + + public boolean operationTraceDebugFlag = false ; + + @DynamicType + public boolean dynamicTypeDebugFlag = false ; + + @IsLocal + public boolean isLocalDebugFlag = false ; + + @ManagedAttribute + @Description( "The current settings of the ORB debug flags" ) + private Map getDebugFlags() { + Map result = new HashMap() ; + for (Field fld : this.getClass().getFields()) { + if (fld.getName().endsWith("DebugFlag")) { + Boolean value = false ; + try { + value = fld.getBoolean( this ); + result.put( fld.getName(), value ) ; + } catch (Exception exc) { + } + } + } + + return result ; + } + + @InfoMethod + private void mbeanRegistrationSuspended(String oRBId) { } + + public enum DebugFlagResult { OK, BAD_NAME } + + @ManagedOperation + @Description( "Enable debugging for several ORB debug flags") + public DebugFlagResult setDebugFlags( String... names ) { + return setDebugFlags( true, names ) ; + } + + @ManagedOperation + @Description( "Enable debugging for a particular ORB debug flag") + public DebugFlagResult setDebugFlag( String name ) { + return setDebugFlag( name, true ) ; + } + + @ManagedOperation + @Description( "Disable debugging for several ORB debug flags") + public DebugFlagResult clearDebugFlags( String... names ) { + return setDebugFlags( false, names ) ; + } + + @ManagedOperation + @Description( "Disable debugging for a particular ORB debug flag") + public DebugFlagResult clearDebugFlag( String name ) { + return setDebugFlag( name, false ) ; + } + + private DebugFlagResult setDebugFlags( boolean flag, String... names ) { + DebugFlagResult res = DebugFlagResult.OK ; + for (String name : names) { + DebugFlagResult lres = setDebugFlag( name, flag ) ; + if (lres == DebugFlagResult.BAD_NAME) { + res = DebugFlagResult.BAD_NAME ; + } + } + return res ; + } + + private DebugFlagResult setDebugFlag( String name, boolean value ) { + try { + Field fld = this.getClass().getField( name + "DebugFlag" ) ; + fld.set( this, value ) ; + + Annotation[] annots = fld.getAnnotations() ; + for (Annotation anno : annots) { + Class annoClass = anno.annotationType() ; + + if (annoClass.isAnnotationPresent( + MethodMonitorGroup.class )) { + if (value) { + MethodMonitorRegistry.register( annoClass, + MethodMonitorFactoryDefaults.dprint() ); + } else { + MethodMonitorRegistry.clear( annoClass ) ; + } + } + } + + return DebugFlagResult.OK ; + } catch (Exception exc) { + return DebugFlagResult.BAD_NAME ; + } + } + + // mom MUST be initialized in a subclass by calling createManagedObjectManager. + // In ORBSingleton, this happens in the constructor. It ORBImpl, it cannot + // happen in the constructor: instead, it must be called in post_init. + protected ManagedObjectManager mom ; + + // SystemException log wrappers. Protected so that they can be used in + // subclasses. + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + protected static final OMGSystemException omgWrapper = + OMGSystemException.self ; + + // This map is needed for resolving recursive type code placeholders + // based on the unique repository id. + private Map typeCodeMap ; + + private TypeCodeImpl[] primitiveTypeCodeConstants ; + + // ByteBufferPool - needed by both ORBImpl and ORBSingleton + ByteBufferPool byteBufferPool; + + // Cached WireObjectKeyTemplate singleton. + WireObjectKeyTemplate wireObjectKeyTemplate; + + // Local testing + public abstract boolean isLocalHost( String hostName ) ; + public abstract boolean isLocalServerId( int subcontractId, int serverId ) ; + + // Invocation stack manipulation + public abstract OAInvocationInfo peekInvocationInfo() ; + public abstract void pushInvocationInfo( OAInvocationInfo info ) ; + public abstract OAInvocationInfo popInvocationInfo() ; + + @ManagedAttribute + @Description( "The ORB's transport manager" ) + public abstract TransportManager getCorbaTransportManager(); + + public abstract LegacyServerSocketManager getLegacyServerSocketManager(); + + private static PresentationManager presentationManager = PresentationDefaults.makeOrbPresentationManager(); + + private UnaryFunction> classNameResolver = defaultClassNameResolver ; + private ClassCodeBaseHandler ccbHandler = null ; + + @Override + public synchronized void destroy() { + typeCodeMap = null ; + primitiveTypeCodeConstants = null ; + byteBufferPool = null ; + wireObjectKeyTemplate = null ; + } + + /** + * Returns the Presentation Manager for the current thread group, using the ThreadGroup-specific + * AppContext to hold it. Creates and records one if needed. + * @return The PresentationManager. + */ + @ManagedAttribute + @Description( "The presentation manager, which handles stub creation" ) + public static PresentationManager getPresentationManager() + { + /**/ + return presentationManager; + /*/ + AppContext ac = AppContext.getAppContext(); + PresentationManager pm = (PresentationManager) ac.get(PresentationManager.class); + if (pm == null) { + pm = PresentationDefaults.makeOrbPresentationManager() ; + ac.put(PresentationManager.class, pm); + } + + return pm; + /**/ + } + + /** Get the appropriate StubFactoryFactory. This + * will be dynamic or static depending on whether + * com.sun.corba.ee.ORBUseDynamicStub is true or false. + * @return The stub factory factory. + */ + public static PresentationManager.StubFactoryFactory + getStubFactoryFactory() + { + PresentationManager gPM = getPresentationManager(); + boolean useDynamicStubs = gPM.useDynamicStubs() ; + return useDynamicStubs ? gPM.getDynamicStubFactoryFactory() : gPM.getStaticStubFactoryFactory(); + } + + /** Obtain the InvocationInterceptor for this ORB instance. + * By default this does nothing. + * @return The InvocationInterceptor. + */ + public abstract InvocationInterceptor getInvocationInterceptor() ; + + /** Set the InvocationInterceptor for this ORB instance. + * This will be used around all dynamic RMI-IIOP calls that + * are mediated by this ORB instance. + * @param interceptor The InvocationInterceptor to add. + */ + public abstract void setInvocationInterceptor( + InvocationInterceptor interceptor ) ; + + protected ORB() + { + + typeCodeMap = new HashMap(); + + wireObjectKeyTemplate = new WireObjectKeyTemplate(this); + } + + protected void initializePrimitiveTypeCodeConstants() { + primitiveTypeCodeConstants = new TypeCodeImpl[] { + new TypeCodeImpl(this, TCKind._tk_null), + new TypeCodeImpl(this, TCKind._tk_void), + new TypeCodeImpl(this, TCKind._tk_short), + new TypeCodeImpl(this, TCKind._tk_long), + new TypeCodeImpl(this, TCKind._tk_ushort), + new TypeCodeImpl(this, TCKind._tk_ulong), + new TypeCodeImpl(this, TCKind._tk_float), + new TypeCodeImpl(this, TCKind._tk_double), + new TypeCodeImpl(this, TCKind._tk_boolean), + new TypeCodeImpl(this, TCKind._tk_char), + new TypeCodeImpl(this, TCKind._tk_octet), + new TypeCodeImpl(this, TCKind._tk_any), + new TypeCodeImpl(this, TCKind._tk_TypeCode), + new TypeCodeImpl(this, TCKind._tk_Principal), + new TypeCodeImpl(this, TCKind._tk_objref), + null, // tk_struct + null, // tk_union + null, // tk_enum + new TypeCodeImpl(this, TCKind._tk_string), + null, // tk_sequence + null, // tk_array + null, // tk_alias + null, // tk_except + new TypeCodeImpl(this, TCKind._tk_longlong), + new TypeCodeImpl(this, TCKind._tk_ulonglong), + new TypeCodeImpl(this, TCKind._tk_longdouble), + new TypeCodeImpl(this, TCKind._tk_wchar), + new TypeCodeImpl(this, TCKind._tk_wstring), + new TypeCodeImpl(this, TCKind._tk_fixed), + new TypeCodeImpl(this, TCKind._tk_value), + new TypeCodeImpl(this, TCKind._tk_value_box), + new TypeCodeImpl(this, TCKind._tk_native), + new TypeCodeImpl(this, TCKind._tk_abstract_interface) + } ; + } + + // Typecode support: needed in both ORBImpl and ORBSingleton + public TypeCodeImpl get_primitive_tc(int kind) + { + try { + return primitiveTypeCodeConstants[kind] ; + } catch (Throwable t) { + throw wrapper.invalidTypecodeKind( t, kind ) ; + } + } + + public synchronized void setTypeCode(String id, TypeCodeImpl code) + { + typeCodeMap.put(id, code); + } + + public synchronized TypeCodeImpl getTypeCode(String id) + { + return typeCodeMap.get(id); + } + + // Special non-standard set_parameters method for + // creating a precisely controlled ORB instance. + // An ORB created by this call is affected only by + // those properties passes explicitly in props, not by + // the system properties and orb.properties files as + // with the standard ORB.init methods. + public abstract void set_parameters( Properties props ) ; + + // Added to provide an API for creating an ORB that avoids the org.omg.CORBA.ORB API + // to get around an OSGi problem. + public abstract void setParameters( String[] args, Properties props ) ; + + // ORB versioning + @ManagedAttribute + @Description( "The implementation version of the ORB" ) + public abstract ORBVersion getORBVersion() ; + + public abstract void setORBVersion( ORBVersion version ) ; + + @ManagedAttribute + @Description( "The IOR used for the Full Value Description" ) + public abstract IOR getFVDCodeBaseIOR() ; + + /** + * Handle a bad server id for the given object key. This should + * always through an exception: either a ForwardException to + * allow another server to handle the request, or else an error + * indication. + * @param okey The ObjectKey to check for a valid server id. + */ + public abstract void handleBadServerId( ObjectKey okey ) ; + public abstract void setBadServerIdHandler( BadServerIdHandler handler ) ; + public abstract void initBadServerIdHandler() ; + + public abstract void notifyORB() ; + + @ManagedAttribute + @Description( "The PortableInterceptor Handler" ) + public abstract PIHandler getPIHandler() ; + + public abstract void createPIHandler() ; + + // Dispatch support: in the ORB because it is needed for shutdown. + // This is used by the first level server side subcontract. + public abstract boolean isDuringDispatch() ; + public abstract void startingDispatch(); + public abstract void finishedDispatch(); + + /** Return this ORB's transient server ID. This is needed for + * initializing object adapters. + * @return The transient server id. + */ + @ManagedAttribute + @Description( "The transient ServerId of this ORB instance" ) + public abstract int getTransientServerId(); + + @ManagedAttribute + @Description( "The registry for all ServerContext factories" ) + public abstract ServiceContextFactoryRegistry getServiceContextFactoryRegistry() ; + + @ManagedAttribute + @Description( "The cache used to opimize marshaling of ServiceContexts" ) + public abstract ServiceContextsCache getServiceContextsCache(); + + @ManagedAttribute + @Description( "The RequestDispatcher registry, which contains the request handling code" ) + public abstract RequestDispatcherRegistry getRequestDispatcherRegistry(); + + @ManagedAttribute + @Description( "The ORB configuration data" ) + public abstract ORBData getORBData() ; + + public abstract void setClientDelegateFactory( ClientDelegateFactory factory ) ; + + @ManagedAttribute + @Description( "The ClientDelegateFactory, which is used to create the ClientDelegate that represents an IOR" ) + public abstract ClientDelegateFactory getClientDelegateFactory() ; + + public abstract void setCorbaContactInfoListFactory( ContactInfoListFactory factory ) ; + + @ManagedAttribute + @Description( "The CorbaContactInfoListFactory, which creates the contact info list that represents " + + "possible endpoints in an IOR" ) + public abstract ContactInfoListFactory getCorbaContactInfoListFactory() ; + + /** Set the resolver used in this ORB. This resolver will be used for list_initial_services + * and resolve_initial_references. + */ + public abstract void setResolver( Resolver resolver ) ; + + /** Get the resolver used in this ORB. This resolver will be used for list_initial_services + * and resolve_initial_references. + */ + @ManagedAttribute + @Description( "ORB Name resolver" ) + public abstract Resolver getResolver() ; + + /** Set the LocalResolver used in this ORB. This LocalResolver is used for + * register_initial_reference only. + */ + public abstract void setLocalResolver( LocalResolver resolver ) ; + + /** Get the LocalResolver used in this ORB. This LocalResolver is used for + * register_initial_reference only. + */ + @ManagedAttribute + @Description( "ORB Local Name resolver" ) + public abstract LocalResolver getLocalResolver() ; + + /** Set the operation used in string_to_object calls. The Operation must expect a + * String and return an org.omg.CORBA.Object. + */ + public abstract void setURLOperation( Operation stringToObject ) ; + + /** Get the operation used in string_to_object calls. The Operation must expect a + * String and return an org.omg.CORBA.Object. + */ + public abstract Operation getURLOperation() ; + + /** Set the ServerRequestDispatcher that should be used for handling INS requests. + */ + public abstract void setINSDelegate( ServerRequestDispatcher insDelegate ) ; + + /** Factory finders for the various parts of the IOR: tagged components, tagged + * profiles, and tagged profile templates. + */ + @ManagedAttribute + @Description( "Finder of Factories for TaggedComponents of IORs" ) + public abstract TaggedComponentFactoryFinder getTaggedComponentFactoryFinder() ; + + @ManagedAttribute + @Description( "Finder of Factories for TaggedProfiles of IORs" ) + public abstract IdentifiableFactoryFinder + getTaggedProfileFactoryFinder() ; + + @ManagedAttribute + @Description( "Finder of Factories for TaggedProfileTemplates of IORs" ) + public abstract IdentifiableFactoryFinder + getTaggedProfileTemplateFactoryFinder() ; + + @ManagedAttribute + @Description( "Factory for creating ObjectKeys" ) + public abstract ObjectKeyFactory getObjectKeyFactory() ; + + public abstract void setObjectKeyFactory( ObjectKeyFactory factory ) ; + + // Logging SPI + + public static Logger getLogger( String name ) + { + return Logger.getLogger( name, ORBConstants.LOG_RESOURCE_FILE ) ; + } + + // get a reference to a ByteBufferPool, a pool of NIO ByteBuffers + // NOTE: ByteBuffer pool must be unique per ORB, not per process. + // There can be more than one ORB per process. + // This method must also be inherited by both ORB and ORBSingleton. + @ManagedAttribute + @Description( "The ByteBuffer pool used in the ORB" ) + public ByteBufferPool getByteBufferPool() + { + if (byteBufferPool == null) + byteBufferPool = new ByteBufferPoolImpl(this); + + return byteBufferPool; + } + + public WireObjectKeyTemplate getWireObjectKeyTemplate() { + return wireObjectKeyTemplate; + } + + public abstract void setThreadPoolManager(ThreadPoolManager mgr); + + @ManagedAttribute + @Description( "The ORB's threadpool manager" ) + public abstract ThreadPoolManager getThreadPoolManager(); + + @ManagedAttribute + @Description( "The ORB's object copier manager" ) + public abstract CopierManager getCopierManager() ; + + /** Returns a name for this ORB that is based on the ORB id (if any) + * and guaranteed to be unique within the ClassLoader that loaded the + * ORB class. This is the default implementation inherited by the + * ORBSingleton. + */ + @NameValue + public String getUniqueOrbId() { + return "###DEFAULT_UNIQUE_ORB_ID###" ; + } + + // Interfaces used only to define InheritedAttributes for other classes + // If we register a class that has Servant in its inheritance, it will + // pick up these InheritedAttributes. + @ManagedData + @Description( "A servant, which implements a remote object in the server" ) + @InheritedAttributes( { + @InheritedAttribute( methodName="_get_delegate", id="delegate", + description="Delegate that implements this servant" ), + @InheritedAttribute( methodName="_orb", id="orb", + description="The ORB for this Servant" ), + @InheritedAttribute( methodName="toString", id="representation", + description="Representation of this Servant" ), + @InheritedAttribute( methodName="_all_interfaces", id="typeIds", + description="The types implemented by this Servant" ) } + ) + public interface DummyServant{} + + // DummyDelegate + // DummyORB + // DummyPOA + + private ObjectName rootParentObjectName = null ; + + public void setRootParentObjectName( ObjectName oname ) { + rootParentObjectName = oname ; + } + + @OrbLifeCycle + public void createORBManagedObjectManager() { + if (rootParentObjectName == null) { + mom = ManagedObjectManagerFactory.createStandalone( "com.sun.corba" ) ; + } else { + mom = ManagedObjectManagerFactory.createFederated( rootParentObjectName ) ; + } + + if (mbeanFineDebugFlag) { + mom.setRegistrationDebug( ManagedObjectManager.RegistrationDebugLevel.FINE ) ; + } else if (mbeanDebugFlag) { + mom.setRegistrationDebug( ManagedObjectManager.RegistrationDebugLevel.NORMAL ) ; + } else { + mom.setRegistrationDebug( ManagedObjectManager.RegistrationDebugLevel.NONE ) ; + } + + mom.addAnnotation( Servant.class, DummyServant.class.getAnnotation( ManagedData.class ) ) ; + mom.addAnnotation( Servant.class, DummyServant.class.getAnnotation( Description.class ) ) ; + mom.addAnnotation( Servant.class, DummyServant.class.getAnnotation( InheritedAttributes.class ) ) ; + + mom.setRuntimeDebug( mbeanRuntimeDebugFlag ) ; + + mom.stripPrefix( "com.sun.corba.ee", "com.sun.corba.ee.spi", "com.sun.corba.ee.spi.orb", + "com.sun.corba.ee.impl" ) ; + + mom.suspendJMXRegistration() ; + + mbeanRegistrationSuspended( getORBData().getORBId() ) ; + + mom.createRoot( this, getUniqueOrbId() ) ; + } + + /** Return the ORB's TimerManager. + */ + // public abstract TimerManager getTimerManager() ; + + // This method obtains an IOR from a CORBA object reference. + // The result is never null. + // Throws BAD_OPERATION (from oi._get_delegate) if obj is a + // normal objref, but does not have a delegate set. + // Throws BAD_PARAM if obj is a local object + protected IOR getIOR( org.omg.CORBA.Object obj ) + { + if (obj == null) + throw wrapper.nullObjectReference() ; + + IOR ior = null ; + if (StubAdapter.isStub(obj)) { + org.omg.CORBA.portable.Delegate del = StubAdapter.getDelegate( + obj ) ; + + if (del instanceof ClientDelegate) { + ClientDelegate cdel = (ClientDelegate)del ; + ContactInfoList ccil = cdel.getContactInfoList() ; + ior = ccil.getTargetIOR() ; + if (ior == null) + throw wrapper.nullIor() ; + + return ior ; + } + + if (obj instanceof ObjectImpl) { + // Get the ORB instance of obj so we can use that ORB + // to marshal the object. + ObjectImpl oi = ObjectImpl.class.cast( obj ) ; + org.omg.CORBA.ORB oiorb = oi._orb() ; + + // obj is implemented by a foreign ORB, because the Delegate is not a + // CorbaClientDelegate. Here we need to marshal obj to an output stream, + // then read the IOR back in. Note that the output stream MUST be + // created by the ORB to which obj is attached, otherwise we get an + // infinite recursion between this code and + // CDROutputStream_1_0.write_Object. + org.omg.CORBA.portable.OutputStream os = oiorb.create_output_stream() ; + os.write_Object( obj ) ; + org.omg.CORBA.portable.InputStream is = os.create_input_stream() ; + ior = IORFactories.makeIOR( this, + org.omg.CORBA_2_3.portable.InputStream.class.cast( is ) ) ; + return ior ; + } else { + throw wrapper.notAnObjectImpl() ; + } + } else + throw wrapper.localObjectNotAllowed() ; + } + + + /** Get the IOR for the CORBA object. If the object is an RMI-IIOP object that + * is not connected, and connectIfNecessary is true, connect to this ORB. + * This method will obtain an IOR for any non-local CORBA object, regardless of + * what ORB implementation created it. It may be more efficient for objrefs + * that were created by this ORB implementation. + * + * @exception SystemException (nullObjectReference) if obj is null + * @exception SystemException (localObjectNotAllowed) of obj is a local CORBA object. + */ + public IOR getIOR( org.omg.CORBA.Object obj, boolean connectIfNecessary ) { + // Note: this version ignores connectIfNecessary, since an objref can only + // be connected to an ORBImpl, not an ORBSingleton. + return getIOR( obj ) ; + } + + /** The singleton ORB does not need the cache, so just return null here. + */ + public ObjectKeyCacheEntry extractObjectKeyCacheEntry(byte[] objKey) { + return null ; + } + + /** Return whether or not the ORB is shutdown. A shutdown ORB cannot process + * incoming requests. + */ + public boolean orbIsShutdown() { + return true ; + } + + private static UnaryFunction> defaultClassNameResolver = + new UnaryFunction>() { + public Class evaluate( String name ) { + try { + return ORBClassLoader.getClassLoader().loadClass( name ) ; + } catch (ClassNotFoundException exc) { + throw new RuntimeException( exc ) ; + } + } + + @Override + public String toString() { + return "ORBClassNameResolver" ; + } + } ; + + public static UnaryFunction> defaultClassNameResolver() { + return defaultClassNameResolver ; + } + + public UnaryFunction> makeCompositeClassNameResolver( + final UnaryFunction> first, + final UnaryFunction> second ) { + + return new UnaryFunction>() { + public Class evaluate( String className ) { + Class result = first.evaluate( className ) ; + if (result == null) { + return second.evaluate( className ) ; + } else { + return result ; + } + } + + @Override + public String toString() { + return "CompositeClassNameResolver[" + first + "," + second + "]" ; + } + } ; + } + + public UnaryFunction> classNameResolver() { + return classNameResolver ; + } + + public void classNameResolver( UnaryFunction> arg ) { + classNameResolver = arg ; + } + + public ManagedObjectManager mom() { + return mom ; + } + + public ClassCodeBaseHandler classCodeBaseHandler() { + return ccbHandler ; + } + + public void classCodeBaseHandler( ClassCodeBaseHandler ccbh ) { + ccbHandler = ccbh ; + } + + public abstract ClientInvocationInfo createOrIncrementInvocationInfo() ; + public abstract ClientInvocationInfo getInvocationInfo(); + public abstract void releaseOrDecrementInvocationInfo(); + + public abstract TransportManager getTransportManager(); + + +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBConfigurator.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBConfigurator.java new file mode 100644 index 000000000..25df6a3f8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBConfigurator.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +/** Interface used to configure an ORB instance. The DataCollector dc has all + * available config info available. The configure method may constructor a + * parser, call dc.setParser( parser ), get the consolidated properties from dc, + * and parse this information. The configure method may also register ORB + * components with the ORB and perform other parts of ORB initialization. + * Implementations of this interface must have a public no-args constructor. + */ +public interface ORBConfigurator { + void configure( DataCollector dc, ORB orb ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBData.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBData.java new file mode 100644 index 000000000..4d8583c85 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBData.java @@ -0,0 +1,386 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import org.omg.PortableInterceptor.ORBInitializer ; + +import com.sun.corba.ee.spi.transport.Acceptor; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; +import com.sun.corba.ee.spi.transport.ContactInfoListFactory; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; +import com.sun.corba.ee.spi.transport.TcpTimeouts; + +import com.sun.corba.ee.impl.legacy.connection.USLPort; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; + +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.AMXMetadata ; + +import org.glassfish.pfl.basic.contain.Pair ; + +// Which attributes should become setters? NOT everything, but only +// those that we think might actually be useful to set. This may change +// over time. On the other hande, essentially everything should be readable. + +@ManagedObject +@Description( "ORB Configuration data" ) +@AMXMetadata( isSingleton=true ) +public interface ORBData { + @ManagedAttribute + @Description( "Value of ORBInitialHost, the host name of the remote name service" ) + public String getORBInitialHost() ; + // XXX add setter? + + @ManagedAttribute + @Description( "Value of ORBInitialPort, the port number of the remote name service" ) + public int getORBInitialPort() ; + // XXX add setter? + + @ManagedAttribute + @Description( "DESC" ) + public String getORBServerHost() ; + // XXX add setter? + + @ManagedAttribute + @Description( "DESC" ) + public int getORBServerPort() ; + // XXX add setter? + + @ManagedAttribute + @Description( "If true, the ORB listens at its ports on all IP interfaces on the host" ) + public boolean getListenOnAllInterfaces(); + // XXX add setter? + + @ManagedAttribute + @Description( "The implementation of the legacy ORBSocketFactory interface in use (if any)" ) + public com.sun.corba.ee.spi.legacy.connection.ORBSocketFactory getLegacySocketFactory () ; + + @ManagedAttribute + @Description( "The implementation of the ORBSocketFactory interface in use (if any)" ) + public com.sun.corba.ee.spi.transport.ORBSocketFactory getSocketFactory(); + + @ManagedAttribute + @Description( "Return the user-specified listen ports, on which the ORB listens for incoming requests" ) + public USLPort[] getUserSpecifiedListenPorts () ; + // XXX This is legacy: can we remove it? + + @ManagedAttribute + @Description( "Return the instance of the IORToSocketInfo interface, " + + "which is used to get SocketInfo from IORs" ) + public IORToSocketInfo getIORToSocketInfo(); + + // XXX Make the setter visible to JMX? + public void setIORToSocketInfo(IORToSocketInfo x); + + @ManagedAttribute + @Description( "Return the instance of the IIOPPrimaryToContactInfo interface" ) + public IIOPPrimaryToContactInfo getIIOPPrimaryToContactInfo(); + + // XXX Make the setter visible to JMX? + public void setIIOPPrimaryToContactInfo( + IIOPPrimaryToContactInfo x); + + @ManagedAttribute + @Description( "Return the configured ORB ID" ) + public String getORBId() ; + + @ManagedAttribute + @Description( "Returns true if the RMI-IIOP local optimization " + + "(caching servant in local subcontract) is allowed." ) + public boolean isLocalOptimizationAllowed() ; + + @ManagedAttribute + @Description( "Return the GIOP version that will be prefered for sending requests" ) + public GIOPVersion getGIOPVersion() ; + + @ManagedAttribute + @Description( "Return the high water mark for the connection cache" ) + public int getHighWaterMark() ; + // XXX add setter? + + @ManagedAttribute + @Description( "Return the number of connections to attempt to reclaim " + + "when the total number of connections exceeds the high water mark" ) + public int getNumberToReclaim() ; + // XXX add setter? + + @ManagedAttribute + @Description( "Return the " ) + public int getGIOPFragmentSize() ; + // XXX add setter? + + // Probably don't really want to expose this + // @ManagedAttribute + // @Description( "Buffer size to use for Java serialization encoding (NOT SUPPORTED)" ) + public int getGIOPBufferSize() ; + // XXX add setter? + + // Can't have an argument: what is the correct action here? + // @ManagedAttribute + // @Description( "Int describing GIOP buffer management strategy: " + // + "0:grow, 1:collect, 2:stream (the default)") + public int getGIOPBuffMgrStrategy(GIOPVersion gv) ; + + /** + * @return the GIOP Target Addressing preference of the ORB. + * This ORB by default supports all addressing dispositions unless specified + * otherwise via a java system property ORBConstants.GIOP_TARGET_ADDRESSING + */ + @ManagedAttribute + @Description( "The ORB required target addressing mode: " + + "0:ObjectKey, 1:TaggedProfile, 2:EntireIOR, 3:Accept All (default)" ) + public short getGIOPTargetAddressPreference() ; + + @ManagedAttribute + @Description( "The ORB required target addressing mode: " + + "0:ObjectKey, 1:TaggedProfile, 2:EntireIOR, 3:Accept All (default)" ) + public short getGIOPAddressDisposition() ; + + @ManagedAttribute + @Description( "DESC" ) + public boolean useByteOrderMarkers() ; + + @ManagedAttribute + @Description( "DESC" ) + public boolean useByteOrderMarkersInEncapsulations() ; + + @ManagedAttribute + @Description( "DESC" ) + public boolean alwaysSendCodeSetServiceContext() ; + + @ManagedAttribute + @Description( "DESC" ) + public boolean getPersistentPortInitialized() ; + + @ManagedAttribute + @Description( "DESC" ) + public int getPersistentServerPort(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean getPersistentServerIdInitialized() ; + + /** Return the persistent-server-id of this server. This id is the same + * across multiple activations of this server. + * The user/environment is required to supply the + * persistent-server-id every time this server is started, in + * the ORBServerId parameter, System properties, or other means. + * The user is also required to ensure that no two persistent servers + * on the same host have the same server-id. + */ + @ManagedAttribute + @Description( "DESC" ) + public int getPersistentServerId(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean getServerIsORBActivated() ; + + @ManagedAttribute + @Description( "DESC" ) + public Class getBadServerIdHandler(); + + /** + * Get the prefered code sets for connections. Should the client send the + * code set service context on every request? + */ + @ManagedAttribute + @Description( "DESC" ) + public CodeSetComponentInfo getCodeSetComponentInfo() ; + + @ManagedAttribute + @Description( "DESC" ) + public ORBInitializer[] getORBInitializers(); + + /** Added to allow user configurators to add ORBInitializers + * for PI. This makes it possible to add interceptors from + * an ORBConfigurator. + * XXX Should this be an operation, or a set only attribute? + * Should it even be exposed in the MBean? + */ + // @ManagedAttribute + // @Description( "DESC" ) + public void addORBInitializer( ORBInitializer init ) ; + + @ManagedAttribute + @Description( "Pair of (name, CORBA URL) used to initialize resolve_initial_references" ) + public Pair[] getORBInitialReferences(); + + public String getORBDefaultInitialReference() ; + + @ManagedAttribute + @Description( "DESC" ) + public String[] getORBDebugFlags(); + // Add operation to set flags + + @ManagedAttribute + @Description( "DESC" ) + public Acceptor[] getAcceptors(); + + @ManagedAttribute + @Description( "DESC" ) + public ContactInfoListFactory getCorbaContactInfoListFactory(); + + @ManagedAttribute + @Description( "DESC" ) + public String acceptorSocketType(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean acceptorSocketUseSelectThreadToWait(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean acceptorSocketUseWorkerThreadForEvent(); + + @ManagedAttribute + @Description( "DESC" ) + public String connectionSocketType(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean connectionSocketUseSelectThreadToWait(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean connectionSocketUseWorkerThreadForEvent(); + + @ManagedAttribute + @Description( "DESC" ) + public long getCommunicationsRetryTimeout(); + // XXX add setter + + @ManagedAttribute + @Description( "DESC" ) + public long getWaitForResponseTimeout(); + // XXX add setter + + @ManagedAttribute + @Description( "DESC" ) + public TcpTimeouts getTransportTcpTimeouts(); + // XXX add setter + + @ManagedAttribute + @Description( "DESC" ) + public TcpTimeouts getTransportTcpConnectTimeouts(); + // XXX add setter + + @ManagedAttribute + @Description( "DESC" ) + public boolean disableDirectByteBufferUse() ; + + @ManagedAttribute + @Description( "DESC" ) + public boolean isJavaSerializationEnabled(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean useRepId(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean showInfoMessages(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean getServiceContextReturnsNull() ; + + // this method tells whether the current ORB was created from within the app server + // This helps in performance improvement (for certain computations that donot need to be + //performed again and again. For e.g. getMaxStreamFormatVersion()) + @ManagedAttribute + @Description( "DESC" ) + public boolean isAppServerMode() ; + + // Get the ByteBuffer size to use when reading from a SocketChannel, + // i.e optimized read strategy + @ManagedAttribute + @Description( "DESC" ) + public int getReadByteBufferSize(); + + // Get maximum read ByteBuffer size to re-allocate + @ManagedAttribute + @Description( "DESC" ) + public int getMaxReadByteBufferSizeThreshold(); + + // Get the pooled DirectByteBuffer slab size + @ManagedAttribute + @Description( "DESC" ) + public int getPooledDirectByteBufferSlabSize(); + + // Should a blocking read always be done when using the optimized read + // strategy ? + @ManagedAttribute + @Description( "DESC" ) + public boolean alwaysEnterBlockingRead(); + + // Set whether the read optimization should always enter a blocking read + // after doing a non-blocking read + @ManagedAttribute + @Description( "DESC" ) + public void alwaysEnterBlockingRead(boolean b); + + // Should the optimized non-blocking read include in its while loop the + // condition to check the MessageParser if it is expecting more data? + @ManagedAttribute + @Description( "DESC" ) + public boolean nonBlockingReadCheckMessageParser(); + + // Should the optimized blocking read include in its while loop the + // condition to check the MessageParser if it is expecting more data? + @ManagedAttribute + @Description( "DESC" ) + public boolean blockingReadCheckMessageParser(); + + @ManagedAttribute + @Description( "DESC" ) + public boolean timingPointsEnabled() ; + // XXX add setter + + @ManagedAttribute + @Description( "DESC" ) + // Should marshaling of enums be done with EnumDesc, or by simply + // marshaling as a value type with receiver-make-right? Use EnumDesc + // if this returns true. The default is false, but the ORB will do + // the right thing if it receives an EnumDesc in any case. + public boolean useEnumDesc() ; + + @ManagedAttribute + @Description( "Returns true if ORB is running inside the GFv3 application server" ) + boolean environmentIsGFServer() ; + + @ManagedAttribute + @Description( "If true, do not start any acceptors in the transport by default" ) + public boolean noDefaultAcceptors() ; + + // No reason to make this an attribute: if false, we won't see MBeans! + public boolean registerMBeans() ; + + @ManagedAttribute + @Description( "The time that a CDRInputStream will wait for more data before throwing an exception" ) + public int fragmentReadTimeout() ; + + public void setOrbInitArgs( String[] args ) ; + + @ManagedAttribute + @Description( "The String[] args that were passed to the ORB init call (used for interceptor initialization)" ) + public String[] getOrbInitArgs() ; + + @ManagedAttribute + @Description( "True if ORBD should not be used in this ORB instance") + public boolean disableORBD() ; +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBVersion.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBVersion.java new file mode 100644 index 000000000..1dcde68f7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBVersion.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import org.omg.CORBA.portable.OutputStream ; + +import org.glassfish.gmbal.ManagedData ; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; + +@ManagedData +@Description( "The version of the ORB" ) +public interface ORBVersion extends Comparable +{ + byte FOREIGN = 0 ; // ORB from another vendor + byte OLD = 1 ; // JDK 1.3.0 or earlier + byte NEW = 2 ; // JDK 1.3.1 FCS + byte JDK1_3_1_01 = 3; // JDK1_3_1_01 patch + byte NEWER = 10 ; // JDK 1.4.x + byte PEORB = 20 ; // PEORB in JDK 1.5, S1AS 8, J2EE 1.4 + + @ManagedAttribute + @Description( "ORB version (0=FOREIGN,1=OLD,2=NEW,3=JDK1_3_1_01,10=NEWER,20=PEORB)" ) + byte getORBType() ; + + void write( OutputStream os ) ; + + public boolean lessThan( ORBVersion version ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBVersionFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBVersionFactory.java new file mode 100644 index 000000000..65b60c20f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ORBVersionFactory.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.impl.orb.ORBVersionImpl ; +import org.omg.CORBA.portable.InputStream ; +import org.omg.CORBA.INTERNAL ; + +public class ORBVersionFactory { + private ORBVersionFactory() {} ; + + public static ORBVersion getFOREIGN() + { + return ORBVersionImpl.FOREIGN ; + } + + public static ORBVersion getOLD() + { + return ORBVersionImpl.OLD ; + } + + public static ORBVersion getNEW() + { + return ORBVersionImpl.NEW ; + } + + public static ORBVersion getJDK1_3_1_01() + { + return ORBVersionImpl.JDK1_3_1_01 ; + } + + public static ORBVersion getNEWER() + { + return ORBVersionImpl.NEWER ; + } + + public static ORBVersion getPEORB() + { + return ORBVersionImpl.PEORB ; + } + + /** Return the current version of this ORB + */ + public static ORBVersion getORBVersion() + { + return ORBVersionImpl.PEORB ; + } + + public static ORBVersion create( InputStream is ) + { + byte value = is.read_octet() ; + return byteToVersion( value ) ; + } + + private static ORBVersion byteToVersion( byte value ) + { + /* Throwing an exception here would cause this version to be + * incompatible with future versions of the ORB, to the point + * that this version could + * not even unmarshal objrefs from a newer version that uses + * extended versioning. Therefore, we will simply treat all + * unknown versions as the latest version. + if (value < 0) + throw new INTERNAL() ; + */ + + /** + * Update: If we treat all unknown versions as the latest version + * then when we send an IOR with a PEORB version to an ORB that + * doesn't know the PEORB version it will treat it as whatever + * its idea of the latest version is. Then, if that IOR is + * sent back to the server and compared with the original + * the equality check will fail because the versions will be + * different. + * + * Instead, just capture the version bytes. + */ + + switch (value) { + case ORBVersion.FOREIGN : return ORBVersionImpl.FOREIGN ; + case ORBVersion.OLD : return ORBVersionImpl.OLD ; + case ORBVersion.NEW : return ORBVersionImpl.NEW ; + case ORBVersion.JDK1_3_1_01: return ORBVersionImpl.JDK1_3_1_01 ; + case ORBVersion.NEWER : return ORBVersionImpl.NEWER ; + case ORBVersion.PEORB : return ORBVersionImpl.PEORB ; + default : return new ORBVersionImpl(value); + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ObjectKeyCacheEntry.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ObjectKeyCacheEntry.java new file mode 100644 index 000000000..ad0999eb5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ObjectKeyCacheEntry.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import com.sun.corba.ee.spi.ior.ObjectKey ; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +/** Interface used to represent information cached for a particular byte[] that + * represent a GIOP marshalled ObjectKey. + */ +public interface ObjectKeyCacheEntry { + ObjectKey getObjectKey() ; + + ObjectAdapter getObjectAdapter() ; + + void clearObjectAdapter() ; + + void setObjectAdapter( ObjectAdapter oa ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/Operation.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/Operation.java new file mode 100644 index 000000000..6c79bcaa4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/Operation.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +/** A generic class representing a function that takes a value and returns + * a value. This is a building block for property parsing. + */ +public interface Operation{ + /** Apply some function to a value and return the result. + */ + Object operate( Object value ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/OperationFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/OperationFactory.java new file mode 100644 index 000000000..c17b1b85a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/OperationFactory.java @@ -0,0 +1,582 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; +import java.util.StringTokenizer ; + +import java.lang.reflect.Array ; + +import java.net.URL ; +import java.net.MalformedURLException ; +import org.glassfish.pfl.basic.algorithm.ObjectUtility; +import org.glassfish.pfl.basic.contain.Pair; +import org.glassfish.pfl.basic.func.UnaryFunction; + +/** This is a static factory class for commonly used operations +* for property parsing. The following operations are supported: +*
                  +*
                • maskErrorAction( Operation op ) executes op and returns the result. If op throws an +* exception, the result is null. +*
                • indexAction( int arg ) returns the [arg] element of value, which must be an Object[]
                • +*
                • identityAction() return the value
                • +*
                • booleanAction() return a Boolean representing true or false values of the String value
                • +*
                • integerAction() returns an Integer for the String value, which must be a decimal integer
                • +*
                • stringAction() returns the String value
                • +*
                • classAction() returns a class for the String value, as loaded by the ORB classloader
                • +*
                • setFlagAction() always return Boolean.TRUE
                • +*
                • URLAction() returns a java.net.URL for the String value, which must be a valid URL
                • +*
                • integerRangeAction( int min, int max ) returns an Integer for the String value, which must be a +* decimal integer in the range min to max inclusive
                • +*
                • listAction( String sep, Operation ) tokenizes the String value with sep as separator, then +* applies the Operation to each token, and returns an array of the result
                • +*
                • sequenceAction( String, Operation[] ) tokenizes the String value with sep as separator, then +* applies each Operation in the Operation array to successive tokens, and returns an array of the results
                • +*
                • compose( Operation op1, Operation op2 ) is the operation that applies op2 to the result of applying +* op1 to the value
                • +*
                • mapAction( Operation ) applies the Operation to each element of an array of objects, and returns +* an array of the results
                • +*
                • mapSequenceAction( Operation[] ) applies the corresponding element of the Operation array to an +* element of the Object[] value, and returns an array of the results
                • +*
                • convertIntegerToShort coerces an Integer into a Short.
                • +*
                +* Other operations can be directly defined, and combined using these basic operations. +*

                +* This class also provides a simple ArgumentParser that can be used to parse +* simple String[] data using the Operations framework. +*/ +public abstract class OperationFactory { + // I18N for errors through log wrappers: bug 5051545 + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private OperationFactory() {} + + private static String getString( Object obj ) + { + if (obj instanceof String) { + return (String) obj; + } else { + throw wrapper.stringExpectedInOperation(); + } + } + + private static Object[] getObjectArray( Object obj ) + { + if (obj instanceof Object[]) { + return (Object[]) obj; + } else { + throw wrapper.objectArrayExpected(); + } + } + + private static Pair getStringPair( Object obj ) + { + if (obj instanceof Pair) { + return (Pair) obj; + } else { + throw wrapper.pairStringStringExpected(); + } + } + + private static abstract class OperationBase implements Operation{ + @Override + public boolean equals( Object obj ) + { + if (this==obj) { + return true; + } + + if (!(obj instanceof OperationBase)) { + return false; + } + + OperationBase other = (OperationBase)obj ; + + return toString().equals( other.toString() ) ; + } + + @Override + public int hashCode() + { + return toString().hashCode() ; + } + } + + private static class MaskErrorAction extends OperationBase + { + private Operation op ; + + public MaskErrorAction( Operation op ) + { + this.op = op ; + } + + public Object operate( Object arg ) + { + try { + return op.operate( arg ) ; + } catch (java.lang.Exception exc) { + return null ; + } + } + + @Override + public String toString() + { + return "maskErrorAction(" + op + ")" ; + } + } + + public static Operation maskErrorAction( Operation op ) + { + return new MaskErrorAction( op ) ; + } + + private static class IndexAction extends OperationBase + { + private int index ; + + public IndexAction( int index ) + { + this.index = index ; + } + + public Object operate( Object value ) + { + return getObjectArray( value )[ index ] ; + } + + @Override + public String toString() + { + return "indexAction(" + index + ")" ; + } + } + + public static Operation indexAction( int index ) + { + return new IndexAction( index ) ; + } + + private static class SuffixAction extends OperationBase + { + public Object operate( Object value ) + { + return getStringPair( value ).first() ; + } + + @Override + public String toString() { return "suffixAction" ; } + } + + private static Operation suffixActionImpl = new SuffixAction() ; + + private static class ValueAction extends OperationBase + { + public Object operate( Object value ) + { + return getStringPair( value ).second() ; + } + + @Override + public String toString() { return "valueAction" ; } + } + + private static Operation valueActionImpl = new ValueAction() ; + + private static class IdentityAction extends OperationBase + { + public Object operate( Object value ) + { + return value ; + } + + @Override + public String toString() { return "identityAction" ; } + } + + private static Operation identityActionImpl = new IdentityAction() ; + + private static class BooleanAction extends OperationBase + { + public Object operate( Object value ) + { + return Boolean.valueOf( getString( value ) ) ; + } + + @Override + public String toString() { return "booleanAction" ; } + } + + private static Operation booleanActionImpl = new BooleanAction() ; + + private static class IntegerAction extends OperationBase + { + public Object operate( Object value ) + { + return Integer.valueOf( getString( value ) ) ; + } + + @Override + public String toString() { return "integerAction" ; } + } + + private static Operation integerActionImpl = new IntegerAction() ; + + private static class StringAction extends OperationBase + { + public Object operate( Object value ) + { + return value ; + } + + @Override + public String toString() { return "stringAction" ; } + } + + private static Operation stringActionImpl = new StringAction() ; + + private static class ClassAction extends OperationBase + { + private UnaryFunction> resolver ; + + public ClassAction( UnaryFunction> resolver ) { + this.resolver = resolver ; + } + + public Object operate( Object value ) + { + String className = getString( value ) ; + + try { + Class result = resolver.evaluate( className ) ; + return result ; + } catch (Exception exc) { + throw wrapper.classActionException( exc, className ) ; + } + } + + @Override + public String toString() { return "classAction[" + resolver + "]" ; } + } + + private static class SetFlagAction extends OperationBase + { + public Object operate( Object value ) + { + return Boolean.TRUE ; + } + + @Override + public String toString() { return "setFlagAction" ; } + } + + private static Operation setFlagActionImpl = new SetFlagAction() ; + + private static class URLAction extends OperationBase + { + public Object operate( Object value ) + { + String val = (String)value ; + try { + return new URL( val ) ; + } catch (MalformedURLException exc) { + throw wrapper.badUrlInAction( exc, val ) ; + } + } + + @Override + public String toString() { return "URLAction" ; } + } + + private static Operation URLActionImpl = new URLAction() ; + + public static Operation identityAction() + { + return identityActionImpl ; + } + + public static Operation suffixAction() + { + return suffixActionImpl ; + } + + public static Operation valueAction() + { + return valueActionImpl ; + } + + public static Operation booleanAction() + { + return booleanActionImpl ; + } + + public static Operation integerAction() + { + return integerActionImpl ; + } + + public static Operation stringAction() + { + return stringActionImpl ; + } + + public static Operation classAction( + final UnaryFunction> resolver ) + { + return new ClassAction( resolver ) ; + } + + public static Operation setFlagAction() + { + return setFlagActionImpl ; + } + + public static Operation URLAction() + { + return URLActionImpl ; + } + + private static class IntegerRangeAction extends OperationBase + { + private int min ; + private int max ; + + IntegerRangeAction( int min, int max ) + { + this.min = min ; + this.max = max ; + } + + public Object operate( Object value ) + { + int result = Integer.parseInt( getString( value ) ) ; + if ((result >= min) && (result <= max)) { + return Integer.valueOf(result); + } else { + throw wrapper.valueNotInRange(result, min, max); + } + } + + @Override + public String toString() { + return "integerRangeAction(" + min + "," + max + ")" ; + } + } + + public static Operation integerRangeAction( int min, int max ) + { + return new IntegerRangeAction( min, max ) ; + } + + private static class ListAction extends OperationBase { + private String sep ; + private Operation act ; + + ListAction( String sep, Operation act ) + { + this.sep = sep ; + this.act = act ; + } + + // Note that this method carefully constructs an array of the type + // of the first result, rather than just using Object[], which is + // not convertible into the correct type. Also note that no tokens + // results in a null result. + public Object operate( Object value ) + { + StringTokenizer st = new StringTokenizer( getString( value ), + sep ) ; + int length = st.countTokens() ; + Object result = null ; + int ctr = 0 ; + while (st.hasMoreTokens()) { + String next = st.nextToken() ; + Object val = act.operate( next ) ; + if (result == null) { + result = + Array.newInstance(val.getClass(), length); + } + Array.set( result, ctr++, val ) ; + } + + return result ; + } + + @Override + public String toString() { + return "listAction(separator=\"" + sep + + "\",action=" + act + ")" ; + } + } + + public static Operation listAction( String sep, Operation act ) + { + return new ListAction( sep, act ) ; + } + + private static class SequenceAction extends OperationBase + { + private String sep ; + private Operation[] actions ; + + SequenceAction( String sep, Operation[] actions ) + { + this.sep = sep ; + this.actions = actions ; + } + + public Object operate( Object value ) + { + StringTokenizer st = new StringTokenizer( getString( value ), + sep ) ; + + int numTokens = st.countTokens() ; + if (numTokens != actions.length) { + throw wrapper.numTokensActionsDontMatch(numTokens, + actions.length); + } + + int ctr = 0 ; + Object[] result = new Object[ numTokens ] ; + while (st.hasMoreTokens()) { + Operation act = actions[ctr] ; + String next = st.nextToken() ; + result[ctr++] = act.operate( next ) ; + } + + return result ; + } + + @Override + public String toString() { + return "sequenceAction(separator=\"" + sep + + "\",actions=" + + ObjectUtility.compactObjectToString(actions) + ")" ; + } + } + + public static Operation sequenceAction( String sep, + Operation[] actions ) + { + return new SequenceAction( sep, actions ) ; + } + + private static class ComposeAction extends OperationBase + { + private Operation op1 ; + private Operation op2 ; + + ComposeAction( Operation op1, Operation op2 ) + { + this.op1 = op1 ; + this.op2 = op2 ; + } + + public Object operate( Object value ) + { + return op2.operate( op1.operate( value ) ) ; + } + + @Override + public String toString() { + return "composition(" + op1 + "," + op2 + ")" ; + } + } + + public static Operation compose( Operation op1, Operation op2 ) + { + return new ComposeAction( op1, op2 ) ; + } + + private static class MapAction extends OperationBase + { + private Operation op ; + + MapAction( Operation op ) + { + this.op = op ; + } + + public Object operate( Object value ) + { + Object[] values = (Object[])value ; + Object[] result = new Object[ values.length ] ; + for (int ctr=0; ctr + * This is split off here to avoid problems with the build depending on the + * version of OperationFactory that is in Java SE 5.0. + */ +public class OperationFactoryExt { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private OperationFactoryExt() {} + + private static class ConvertAction implements Operation { + private Class cls ; + private Constructor cons ; + + public ConvertAction( Class cls ) { + this.cls = cls ; + try { + cons = cls.getConstructor( String.class ) ; + } catch (Exception exc) { + throw wrapper.exceptionInConvertActionConstructor( exc, + cls.getName() ) ; + } + } + + public Object operate( Object value ) + { + try { + return cons.newInstance( value ) ; + } catch (Exception exc) { + throw wrapper.exceptionInConvertAction( exc ) ; + } + } + + @Override + public String toString() { + return "ConvertAction[" + cls.getName() + "]" ; + } + + @Override + public boolean equals( Object obj ) + { + if (this==obj) { + return true; + } + + if (!(obj instanceof ConvertAction)) { + return false; + } + + ConvertAction other = (ConvertAction)obj ; + + return toString().equals( other.toString() ) ; + } + + @Override + public int hashCode() + { + return toString().hashCode() ; + } + } + + public static Operation convertAction( Class cls ) { + return new ConvertAction( cls ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserData.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserData.java new file mode 100644 index 000000000..99500abb3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserData.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import java.util.Properties ; + +public interface ParserData { + public String getPropertyName() ; + + public Operation getOperation() ; + + public String getFieldName() ; + + public Object getDefaultValue() ; + + public Object getTestValue() ; + + public void addToParser( PropertyParser parser ) ; + + public void addToProperties( Properties props ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserDataFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserDataFactory.java new file mode 100644 index 000000000..853a3c265 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserDataFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import com.sun.corba.ee.impl.orb.NormalParserData ; +import com.sun.corba.ee.impl.orb.PrefixParserData ; +import org.glassfish.pfl.basic.contain.Pair; + +public class ParserDataFactory { + public static ParserData make( String propertyName, + Operation operation, String fieldName, Object defaultValue, + Object testValue, String testData ) + { + return new NormalParserData( propertyName, operation, fieldName, + defaultValue, testValue, testData ) ; + } + + public static ParserData make( String propertyName, + Operation operation, String fieldName, Object defaultValue, + Object testValue, Pair[] testData, Class componentType ) + { + return new PrefixParserData( propertyName, operation, fieldName, + defaultValue, testValue, testData, componentType ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserImplBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserImplBase.java new file mode 100644 index 000000000..08b504986 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserImplBase.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import java.util.Map ; +import java.util.Set ; +import java.util.Iterator ; +import java.util.Properties ; + +import java.security.PrivilegedExceptionAction ; +import java.security.PrivilegedActionException ; +import java.security.AccessController ; + +import java.lang.reflect.Field ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +public abstract class ParserImplBase { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + protected abstract PropertyParser makeParser() ; + + /** Override this method if there is some needed initialization + * that takes place after argument parsing. + */ + protected void complete() + { + } + + public ParserImplBase() + { + } + + public void init( DataCollector coll ) + { + PropertyParser parser = makeParser() ; + coll.setParser( parser ) ; + Properties props = coll.getProperties() ; + Map map = parser.parse( props ) ; + setFields( map ) ; + + // Make sure that any extra initialization takes place after all the + // fields are set from the map. + complete() ; + } + + private Field getAnyField( String name ) + { + Field result = null ; + + try { + Class cls = this.getClass() ; + result = cls.getDeclaredField( name ) ; + while (result == null) { + cls = cls.getSuperclass() ; + if (cls == null) { + break; + } + + result = cls.getDeclaredField( name ) ; + } + } catch (Exception exc) { + throw wrapper.fieldNotFound( exc, name ) ; + } + + if (result == null) { + throw wrapper.fieldNotFound(name); + } + + return result ; + } + + protected void setFields( Map map ) + { + Set entries = map.entrySet() ; + Iterator iter = entries.iterator() ; + while (iter.hasNext()) { + java.util.Map.Entry entry = (java.util.Map.Entry)(iter.next()) ; + final String name = (String)(entry.getKey()) ; + final Object value = entry.getValue() ; + + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Object run() throws IllegalAccessException, + IllegalArgumentException + { + Field field = getAnyField( name ) ; + field.setAccessible( true ) ; + field.set( ParserImplBase.this, value ) ; + return null ; + } + } + ) ; + } catch (PrivilegedActionException exc) { + // Since exc wraps the actual exception, use exc.getCause() + // instead of exc. + throw wrapper.errorSettingField( exc.getCause(), name, value ) ; + } + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserImplTableBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserImplTableBase.java new file mode 100644 index 000000000..9ebd414ad --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/orb/ParserImplTableBase.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.orb ; + +import java.util.Map ; +import java.util.AbstractMap ; +import java.util.Set ; +import java.util.AbstractSet ; +import java.util.Iterator ; +import java.util.Properties ; + +import java.lang.reflect.Field ; + +import org.omg.CORBA.INTERNAL ; + +public abstract class ParserImplTableBase extends ParserImplBase { + private final ParserData[] entries ; + + public ParserImplTableBase( ParserData[] entries ) + { + this.entries = entries ; + setDefaultValues() ; + } + + protected PropertyParser makeParser() + { + PropertyParser result = new PropertyParser() ; + for (int ctr=0; ctr actions ; + + public PropertyParser( ) + { + actions = new LinkedList() ; + } + + public PropertyParser add( String propName, + Operation action, String fieldName ) + { + actions.add( ParserActionFactory.makeNormalAction( propName, + action, fieldName ) ) ; + return this ; + } + + public PropertyParser addPrefix( String propName, + Operation action, String fieldName, Class componentType ) + { + actions.add( ParserActionFactory.makePrefixAction( propName, + action, fieldName, componentType ) ) ; + return this ; + } + + /** Return a map from field name to value. + */ + public Map parse( Properties props ) + { + Map map = new HashMap() ; + Iterator iter = actions.iterator() ; + while (iter.hasNext()) { + ParserAction act = iter.next() ; + Object result = act.apply( props ) ; + + // A null result means that the property was not set for + // this action, so do not override the default value in this case. + if (result != null) { + map.put(act.getFieldName(), result); + } + } + + return map ; + } + + public Iterator iterator() + { + return actions.iterator() ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/osgi/ORBFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/osgi/ORBFactory.java new file mode 100644 index 000000000..1defbe18d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/osgi/ORBFactory.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.osgi; + +import java.util.Properties ; + +import org.glassfish.external.amx.AMXGlassfish ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ClassCodeBaseHandler ; + +import com.sun.corba.ee.impl.orb.ORBImpl ; + +import com.sun.corba.ee.impl.osgi.loader.OSGIListener; +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** A simple factory for creating our ORB that avoids the ClassLoader + * problems with org.omg.CORBA.ORB.init, which must load the ORB impl class. + * The usual OSGi configuration prevents this, so we just directly use a + * static factory method here. Note that this also assumes that the created + * ORB should be suitable for running inside GlassFish v3. + */ +public class ORBFactory { + private ORBFactory() {} + + public static ORB create( String[] args, Properties props, boolean useOSGi ) { + ORB result = create() ; + initialize( result, args, props, useOSGi ) ; + return result ; + } + + /** Create but do not initialize an ORB instance. + * @return The newly created uninitialized ORB. + */ + public static ORB create() { + ORB result = new ORBImpl() ; + return result ; + } + + /** Complete the initialization of the ORB. + * useOSGi if true will cause an ORB initialization + * suitable for use in GlassFish v3. + * @param orb The orb to initialize. + * @param args Usual args passed to an ORB.init() call. + * @param props Usual props passed to an ORB.init() call. + * @param useOSGi true if the ORB is running in GFv3 or later (generally means an OSGI environment). + */ + @SuppressWarnings("static-access") + public static void initialize( ORB orb, String[] args, Properties props, boolean useOSGi ) { + // Always disable ORBD if coming through the ORBFactory. + // Anyone that wants ORBD must use ORB.init as usual. + // Actually we assume that we are running in GFv3 if this method is called, + // regardless of whether OSGi is used or not. + props.setProperty( ORBConstants.DISABLE_ORBD_INIT_PROPERTY, "true" ) ; + + if (useOSGi) { + orb.classNameResolver( + orb.makeCompositeClassNameResolver( + OSGIListener.classNameResolver(), + orb.defaultClassNameResolver() + ) ); + + ClassCodeBaseHandler ccbh = OSGIListener.classCodeBaseHandler() ; + orb.classCodeBaseHandler( ccbh ) ; + } + + orb.setRootParentObjectName( AMXGlassfish.DEFAULT.serverMonForDAS() ) ; + + orb.setParameters( args, props ) ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/DynamicMethodMarshaller.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/DynamicMethodMarshaller.java new file mode 100644 index 000000000..f6b3ac39f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/DynamicMethodMarshaller.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +import org.omg.CORBA.ORB ; +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA.portable.ApplicationException ; + +import java.lang.reflect.Method ; + +import java.rmi.RemoteException ; + +/** Used to read and write arguments and results for a particular method. +* +*/ +public interface DynamicMethodMarshaller +{ + /** Returns the method used to create this DynamicMethodMarshaller. + */ + Method getMethod() ; + + /** Copy the arguments as needed for this particular method. + * Can be optimized so that as little copying as possible is + * performed. + */ + Object[] copyArguments( Object[] args, ORB orb ) throws RemoteException ; + + /** Read the arguments for this method from the InputStream. + * Returns null if there are no arguments. + */ + Object[] readArguments( InputStream is ) ; + + /** Write arguments for this method to the OutputStream. + * Does nothing if there are no arguments. + */ + void writeArguments( OutputStream os, Object[] args ) ; + + /** Copy the result as needed for this particular method. + * Can be optimized so that as little copying as possible is + * performed. + */ + Object copyResult( Object result, ORB orb ) throws RemoteException ; + + /** Read the result from the InputStream. Returns null + * if the result type is null. + */ + Object readResult( InputStream is ) ; + + /** Write the result to the OutputStream. Does nothing if + * the result type is null. + */ + void writeResult( OutputStream os, Object result ) ; + + /** Returns true iff thr's class is a declared exception (or a subclass of + * a declared exception) for this DynamicMethodMarshaller's method. + */ + boolean isDeclaredException( Throwable thr ) ; + + /** Write the repository ID of the exception and the value of the + * exception to the OutputStream. ex should be a declared exception + * for this DynamicMethodMarshaller's method. + */ + void writeException( OutputStream os, Exception ex ) ; + + /** Reads an exception ID and the corresponding exception from + * the input stream. This should be an exception declared in + * this method. + */ + Exception readException( ApplicationException ae ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/DynamicStub.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/DynamicStub.java new file mode 100644 index 000000000..c035cf9e9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/DynamicStub.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +import java.rmi.RemoteException ; + +import org.omg.CORBA.portable.Delegate ; +import org.omg.CORBA.portable.OutputStream ; + +import org.omg.CORBA.ORB ; + +/** Interface used to support dynamically generated stubs. + * This supplies some methods that are found in + * org.omg.CORBA.portable.ObjectImpl that are not available + * in org.omg.CORBA.Object. + */ +public interface DynamicStub extends org.omg.CORBA.Object +{ + /** Similar to ObjectImpl._set_delegate + */ + void setDelegate( Delegate delegate ) ; + + /** Similar to ObjectImpl._get_delegate + */ + Delegate getDelegate() ; + + /** Similar to ObjectImpl._orb() + */ + ORB getORB() ; + + /** Similar to ObjectImpl._ids + */ + String[] getTypeIds() ; + + /** Connect this dynamic stub to an ORB. + * Just as in standard RMI-IIOP, this is required after + * a dynamic stub is deserialized from an ObjectInputStream. + * It is not needed when unmarshalling from a + * org.omg.CORBA.portable.InputStream. + */ + void connect( ORB orb ) throws RemoteException ; + + boolean isLocal() ; + + OutputStream request( String operation, boolean responseExpected ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/IDLNameTranslator.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/IDLNameTranslator.java new file mode 100644 index 000000000..2e49a16e8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/IDLNameTranslator.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +import java.lang.reflect.Method ; + +/** Translates between methods on an interface and RMI-IIOP encodings + * of those methods as names. + */ +public interface IDLNameTranslator +{ + /** Get the interfaces that this IDLNameTranslator describes. + */ + Class[] getInterfaces() ; + + /** Get all methods for this remote interface. + * The methods are returned in a canonical order, that is, + * they are always in the same order for a particular interface. + */ + Method[] getMethods() ; + + /** Get the method from this IDLNameTranslator's interfaces that + * corresponds to the mangled name idlName. Returns null + * if there is no matching method. + */ + Method getMethod( String idlName ) ; + + /** Get the mangled name that corresponds to the given method + * on this IDLNameTranslator's interface. Returns null + * if there is no matching name. + */ + String getIDLName( Method method ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/InvocationInterceptor.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/InvocationInterceptor.java new file mode 100644 index 000000000..77a91e220 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/InvocationInterceptor.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +/** Represents an interceptor that is invoked around a + * RMI-IIOP method invocation when dynamic RMI-IIOP is used. + * This facility is not available either in IDL-based + * calls, or in static RMI-IIOP. + */ +public interface InvocationInterceptor { + /** Called just before a dynamic RMI-IIOP stub is called. + * Any exceptions thrown by this method are ignored. + */ + void preInvoke() ; + + /** Called just before a dynamic RMI-IIOP stub returns control + * to the caller. Any exceptions thrown by this method are + * ignored. + */ + void postInvoke() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/PresentationDefaults.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/PresentationDefaults.java new file mode 100644 index 000000000..2b2c28a45 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/PresentationDefaults.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi; + +import com.sun.corba.ee.impl.presentation.rmi.PresentationManagerImpl; +import com.sun.corba.ee.impl.presentation.rmi.StubFactoryFactoryStaticImpl; +import com.sun.corba.ee.impl.presentation.rmi.StubFactoryStaticImpl; +import com.sun.corba.ee.impl.presentation.rmi.codegen.StubFactoryFactoryCodegenImpl; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +public abstract class PresentationDefaults +{ + private static PresentationManager.StubFactoryFactory staticImpl = null; + private static PresentationManager.StubFactoryFactory dynamicImpl = null; + + private PresentationDefaults() {} + + synchronized static PresentationManager.StubFactoryFactory getDynamicStubFactoryFactory() { + if (dynamicImpl == null) dynamicImpl = new StubFactoryFactoryCodegenImpl(); + + return dynamicImpl ; + } + + public synchronized static PresentationManager.StubFactoryFactory getStaticStubFactoryFactory() { + if (staticImpl == null) staticImpl = new StubFactoryFactoryStaticImpl(); + + return staticImpl; + } + + public static PresentationManager.StubFactory makeStaticStubFactory( + final Class stubClass ) + { + return new StubFactoryStaticImpl( stubClass ) ; + } + + private static InvocationInterceptor nullInvocationInterceptor = + new InvocationInterceptor() { + public void preInvoke() {} + public void postInvoke() {} + } ; + + public static InvocationInterceptor getNullInvocationInterceptor() + { + return nullInvocationInterceptor ; + } + + public static boolean inAppServer() { + final String thisClassRenamed = + "com.sun.corba.ee.spi.presentation.rmi.PresentationDefaults" ; + final boolean inAppServer = + PresentationDefaults.class.getName().equals( thisClassRenamed ) ; + return inAppServer ; + } + + private static boolean getBooleanPropertyValue( final String propName, + final boolean def ) { + + final String defs = Boolean.toString( def ) ; + final String value = AccessController.doPrivileged( + new PrivilegedAction() { + public String run() { + return System.getProperty( propName, defs ) ; + } + } + ) ; + + return Boolean.valueOf( value ) ; + } + + public static PresentationManagerImpl makeOrbPresentationManager() { + final boolean useDynamicStub = getBooleanPropertyValue( + ORBConstants.USE_DYNAMIC_STUB_PROPERTY, inAppServer() ) ; + + final boolean debug = getBooleanPropertyValue( + ORBConstants.DEBUG_DYNAMIC_STUB, false ) ; + + final PresentationManagerImpl result = new PresentationManagerImpl( useDynamicStub ) ; + result.setStaticStubFactoryFactory(PresentationDefaults.getStaticStubFactoryFactory()); + result.setDynamicStubFactoryFactory(PresentationDefaults.getDynamicStubFactoryFactory()); + if (debug) { + result.enableDebug( System.out ) ; + } + + return result ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/PresentationManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/PresentationManager.java new file mode 100644 index 000000000..0d013949a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/PresentationManager.java @@ -0,0 +1,207 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +import java.io.PrintStream ; + +import java.util.Map ; + +import java.lang.reflect.Method ; + +import javax.rmi.CORBA.Tie ; +import org.glassfish.pfl.basic.proxy.InvocationHandlerFactory; + +/** Provides access to RMI-IIOP stubs and ties. + * Any style of stub and tie generation may be used. + * This includes compiler generated stubs and runtime generated stubs + * as well as compiled and reflective ties. There is normally + * only one instance of this interface per VM. The instance + * is obtained from the static method + * com.sun.corba.ee.spi.orb.ORB.getPresentationManager. + *

                + * Note that + * the getClassData and getDynamicMethodMarshaller methods + * maintain caches to avoid redundant computation. + */ +public interface PresentationManager +{ + /** Creates StubFactory and Tie instances. + */ + public interface StubFactoryFactory + { + /** Return the standard name of a stub (according to the RMI-IIOP specification + * and rmic). This is needed so that the name of a stub is known for + * standalone clients of the app server. + * + * @param className name of the class + * @return the stub name + */ + String getStubName( String className ) ; + + /** Create a stub factory for stubs for the interface whose type is given by + * className. className may identify either an IDL interface or an RMI-IIOP + * interface. + * @param className The name of the remote interface as a Java class name. + * @param isIDLStub True if className identifies an IDL stub, else false. + * @param remoteCodeBase The CodeBase to use for loading Stub classes, if + * necessary (may be null or unused). + * @param expectedClass The expected stub type (may be null or unused). + * @param classLoader The classLoader to use (may be null). + * @return The stub factory + */ + PresentationManager.StubFactory createStubFactory( String className, + boolean isIDLStub, String remoteCodeBase, Class expectedClass, + ClassLoader classLoader); + + /** Return a Tie for the given class. + * + * @param cls class + * @return The tie corresponding to cls + */ + Tie getTie( Class cls ) ; + + /** Return whether or not this StubFactoryFactory creates StubFactory + * instances that create dynamic stubs and ties. At the top level, + * true indicates that rmic -iiop is not needed for generating stubs + * or ties. + * + * @return true iff we are using dynamic stubs + */ + boolean createsDynamicStubs() ; + } + + /** Creates the actual stub needed for RMI-IIOP remote + * references. + */ + public interface StubFactory + { + /** Create a new dynamic stub. It has the type that was + * used to create this factory. + * + * @return The dynamic stub + */ + org.omg.CORBA.Object makeStub() ; + + /** Return the repository ID information for all Stubs + * created by this stub factory. + * + * @return Array of type ids, most derived type first. + */ + String[] getTypeIds() ; + } + + public interface ClassData + { + /** Get the class used to create this ClassData instance + * + * @return Class of this ClassData. + */ + Class getMyClass() ; + + /** Get the IDLNameTranslator for the class used to create + * this ClassData instance. + * + * @return IDLNameTranslator for the class of this ClassData + */ + IDLNameTranslator getIDLNameTranslator() ; + + /** Return the array of repository IDs for all of the remote + * interfaces implemented by this class. + * + * @return The typeids, most derived first. + */ + String[] getTypeIds() ; + + /** Get the InvocationHandlerFactory that is used to create + * an InvocationHandler for dynamic stubs of the type of the + * ClassData. + * + * @return InvocationHandlerFactory. + */ + InvocationHandlerFactory getInvocationHandlerFactory() ; + + /** Get the dictionary for this ClassData instance. + * This is used to hold class-specific information for a Class + * in the class data. This avoids the need to create other + * caches for accessing the information. + * + * @return the dictionary. + */ + Map getDictionary() ; + } + + /** Get the ClassData for a particular class. + * This class may be an implementation class, in which + * case the IDLNameTranslator handles all Remote interfaces implemented by + * the class. If the class implements more than one remote interface, and not + * all of the remote interfaces are related by inheritance, then the type + * IDs have the implementation class as element 0. + * @param cls iClass fro which we need ClassData. + * @return The ClassData. + */ + ClassData getClassData( Class cls ) ; + + /** Given a particular method, return a DynamicMethodMarshaller + * for that method. This is used for dynamic stubs and ties. + * @param method Method for which we need a DynamicMethodMarshaller. + * @return The DynamicMethodMarshaller. + */ + DynamicMethodMarshaller getDynamicMethodMarshaller( Method method ) ; + + /** Return the registered StubFactoryFactory. + * @param isDynamic true iff we want the dynamic stub factory + * @return static or dynamic stub factory. + * @deprecated use {@link #getDynamicStubFactoryFactory()} or {@link #getStaticStubFactoryFactory()} + */ + StubFactoryFactory getStubFactoryFactory( boolean isDynamic ) ; + + /** Return the registered static StubFactoryFactory. + * @return static stub factory. + */ + StubFactoryFactory getStaticStubFactoryFactory(); + + /** Return the registered dynamic StubFactoryFactory. + * @return dynamic stub factory. + */ + StubFactoryFactory getDynamicStubFactoryFactory(); + + /** Equivalent to getStubFactoryFactory( true ).getTie( null ). + * Provided for compatibility with earlier versions of PresentationManager + * as used in the app server. The class argument is ignored in + * the dynamic case, so this is safe. + * @return The static tie. + */ + Tie getTie() ; + + /** Get the correct repository ID for the given implementation + * instance. This is useful when using dynamic RMI with the POA. + * @param impl implementation + * @return repository ID string + */ + String getRepositoryId( java.rmi.Remote impl ) ; + + /** Returns the value of the com.sun.corba.ee.ORBUseDynamicStub + * property. + * @return whether to use dynamic stubs. + */ + boolean useDynamicStubs() ; + + /** Remove all internal references to Class cls from the + * PresentationManager. This allows ClassLoaders to + * be garbage collected when they are no longer needed. + * @param cls Class to flush + */ + void flushClass( Class cls ) ; + + boolean getDebug() ; + + PrintStream getPrintStream() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/StubAdapter.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/StubAdapter.java new file mode 100644 index 000000000..5492ad1c5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/StubAdapter.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +import javax.rmi.CORBA.Tie ; + +import org.omg.CORBA.portable.Delegate ; +import org.omg.CORBA.portable.ObjectImpl ; +import org.omg.CORBA.portable.OutputStream ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.POAManager ; +import org.omg.PortableServer.POAManagerPackage.State ; +import org.omg.PortableServer.Servant ; + +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.ServantNotActive ; +import org.omg.PortableServer.POAManagerPackage.AdapterInactive ; + +import org.omg.CORBA.ORB ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.impl.oa.poa.POAManagerImpl ; + +/** Provide access to stub delegate and type id information + * independent of the stub type. This class exists because + * ObjectImpl does not have an interface for the 3 delegate and + * type id methods, so a DynamicStub has a different type. + * We cannot simply change ObjectImpl as it is a standard API. + * We also cannot change the code generation of Stubs, as that + * is also standard. Hence I am left with this ugly class. + */ +public abstract class StubAdapter +{ + private StubAdapter() {} + + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public static boolean isStubClass( Class cls ) + { + return (ObjectImpl.class.isAssignableFrom( cls )) || + (DynamicStub.class.isAssignableFrom( cls )) ; + } + + public static boolean isStub( Object stub ) + { + return (stub instanceof DynamicStub) || + (stub instanceof ObjectImpl) ; + } + + public static void setDelegate( Object stub, Delegate delegate ) + { + if (stub instanceof DynamicStub) { + ((DynamicStub) stub).setDelegate(delegate); + } else if (stub instanceof ObjectImpl) { + ((ObjectImpl) stub)._set_delegate(delegate); + } else { + throw wrapper.setDelegateRequiresStub(); + } + } + + /** Use implicit activation to get an object reference for the servant. + */ + public static org.omg.CORBA.Object activateServant( Servant servant ) + { + POA poa = servant._default_POA() ; + org.omg.CORBA.Object ref = null ; + + try { + ref = poa.servant_to_reference( servant ) ; + } catch (ServantNotActive sna) { + throw wrapper.getDelegateServantNotActive( sna ) ; + } catch (WrongPolicy wp) { + throw wrapper.getDelegateWrongPolicy( wp ) ; + } + + // Make sure that the POAManager is activated if no other + // POAManager state management has taken place. + POAManager mgr = poa.the_POAManager() ; + if (mgr instanceof POAManagerImpl) { + // This servant is managed by one of our POAs, + // so only activate it if there has not been + // an explicit state change, that is, if the POA + // has never changed state from the initial + // HOLDING state. + POAManagerImpl mgrImpl = (POAManagerImpl)mgr ; + mgrImpl.implicitActivation() ; + } else { + // This servant is not managed by one of our POAs, + // so activate it if the state is HOLDING, which is the + // initial state. Note that this may NOT be exactly + // what the user intended! + if (mgr.get_state().value() == State._HOLDING) { + try { + mgr.activate() ; + } catch (AdapterInactive ai) { + throw wrapper.adapterInactiveInActivateServant( ai ) ; + } + } + } + + return ref ; + } + + /** Given any Tie, return the corresponding object refernce, activating + * the Servant if necessary. + */ + public static org.omg.CORBA.Object activateTie( Tie tie ) + { + /** Any implementation of Tie should be either a Servant or an ObjectImpl, + * depending on which style of code generation is used. rmic -iiop by + * default results in an ObjectImpl-based Tie, while rmic -iiop -poa + * results in a Servant-based Tie. Dynamic RMI-IIOP also uses Servant-based + * Ties (see impl.presentation.rmi.ReflectiveTie). + */ + if (tie instanceof ObjectImpl) { + return tie.thisObject() ; + } else if (tie instanceof Servant) { + Servant servant = (Servant)tie ; + return activateServant( servant ) ; + } else { + throw wrapper.badActivateTieCall() ; + } + } + + + /** This also gets the delegate from a Servant by + * using Servant._this_object() + */ + public static Delegate getDelegate( Object stub ) + { + if (stub instanceof DynamicStub) { + return ((DynamicStub) stub).getDelegate(); + } else if (stub instanceof ObjectImpl) { + return ((ObjectImpl) stub)._get_delegate(); + } else if (stub instanceof Tie) { + Tie tie = (Tie)stub ; + org.omg.CORBA.Object ref = activateTie( tie ) ; + return getDelegate( ref ) ; + } else { + throw wrapper.getDelegateRequiresStub(); + } + } + + public static ORB getORB( Object stub ) + { + if (stub instanceof DynamicStub) { + return ((DynamicStub)stub).getORB() ; + } else if (stub instanceof ObjectImpl) { + return ((ObjectImpl) stub)._orb() ; + } else { + throw wrapper.getOrbRequiresStub() ; + } + } + + public static String[] getTypeIds( Object stub ) + { + if (stub instanceof DynamicStub) { + return ((DynamicStub)stub).getTypeIds() ; + } else if (stub instanceof ObjectImpl) { + return ((ObjectImpl)stub)._ids() ; + } else { + throw wrapper.getTypeIdsRequiresStub() ; + } + } + + public static void connect( Object stub, + ORB orb ) throws java.rmi.RemoteException + { + if (stub instanceof DynamicStub) { + ((DynamicStub)stub).connect( + (com.sun.corba.ee.spi.orb.ORB)orb ) ; + } else if (stub instanceof javax.rmi.CORBA.Stub) { + ((javax.rmi.CORBA.Stub)stub).connect( orb ) ; + } else if (stub instanceof ObjectImpl) { + orb.connect( (org.omg.CORBA.Object)stub ) ; + } else { + throw wrapper.connectRequiresStub() ; + } + } + + public static boolean isLocal( Object stub ) + { + if (stub instanceof DynamicStub) { + return ((DynamicStub)stub).isLocal() ; + } else if (stub instanceof ObjectImpl) { + return ((ObjectImpl)stub)._is_local() ; + } else { + throw wrapper.isLocalRequiresStub() ; + } + } + + public static OutputStream request( Object stub, + String operation, boolean responseExpected ) + { + if (stub instanceof DynamicStub) { + return ((DynamicStub)stub).request( operation, + responseExpected ) ; + } else if (stub instanceof ObjectImpl) { + return ((ObjectImpl)stub)._request( operation, + responseExpected ) ; + } else { + throw wrapper.requestRequiresStub() ; + } + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/StubWrapper.java b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/StubWrapper.java new file mode 100644 index 000000000..9321584a0 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/presentation/rmi/StubWrapper.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi ; + +import java.rmi.RemoteException ; + +import org.omg.CORBA.portable.Delegate ; +import org.omg.CORBA.ORB ; +import org.omg.CORBA.Request ; +import org.omg.CORBA.Context ; +import org.omg.CORBA.NamedValue ; +import org.omg.CORBA.NVList ; +import org.omg.CORBA.ContextList ; +import org.omg.CORBA.ExceptionList ; +import org.omg.CORBA.Policy ; +import org.omg.CORBA.DomainManager ; +import org.omg.CORBA.SetOverrideType ; + +import org.omg.CORBA.portable.OutputStream ; + +/** Wrapper that can take any stub (object x such that StubAdapter.isStub(x)) + * and treat it as a DynamicStub. + */ +public class StubWrapper implements DynamicStub +{ + private org.omg.CORBA.Object object ; + + public StubWrapper( org.omg.CORBA.Object object ) + { + if (!(StubAdapter.isStub(object))) + throw new IllegalStateException() ; + + this.object = object ; + } + + public void setDelegate( Delegate delegate ) + { + StubAdapter.setDelegate( object, delegate ) ; + } + + public Delegate getDelegate() + { + return StubAdapter.getDelegate( object ) ; + } + + public ORB getORB() + { + return StubAdapter.getORB( object ) ; + } + + public String[] getTypeIds() + { + return StubAdapter.getTypeIds( object ) ; + } + + public void connect( ORB orb ) throws RemoteException + { + StubAdapter.connect( object, (com.sun.corba.ee.spi.orb.ORB)orb ) ; + } + + public boolean isLocal() + { + return StubAdapter.isLocal( object ) ; + } + + public OutputStream request( String operation, boolean responseExpected ) + { + return StubAdapter.request( object, operation, responseExpected ) ; + } + + public boolean _is_a(String repositoryIdentifier) + { + return object._is_a( repositoryIdentifier ) ; + } + + public boolean _is_equivalent(org.omg.CORBA.Object other) + { + return object._is_equivalent( other ) ; + } + + public boolean _non_existent() + { + return object._non_existent() ; + } + + public int _hash(int maximum) + { + return object._hash( maximum ) ; + } + + public org.omg.CORBA.Object _duplicate() + { + return object._duplicate() ; + } + + public void _release() + { + object._release() ; + } + + public org.omg.CORBA.Object _get_interface_def() + { + return object._get_interface_def() ; + } + + public Request _request(String operation) + { + return object._request( operation ) ; + } + + public Request _create_request( Context ctx, String operation, NVList arg_list, + NamedValue result) + { + return object._create_request( ctx, operation, arg_list, result ) ; + } + + public Request _create_request( Context ctx, String operation, NVList arg_list, + NamedValue result, ExceptionList exclist, ContextList ctxlist) + { + return object._create_request( ctx, operation, arg_list, result, + exclist, ctxlist ) ; + } + + public Policy _get_policy(int policy_type) + { + return object._get_policy( policy_type ) ; + } + + public DomainManager[] _get_domain_managers() + { + return object._get_domain_managers() ; + } + + public org.omg.CORBA.Object _set_policy_override( Policy[] policies, + SetOverrideType set_add) + { + return object._set_policy_override( policies, set_add ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientDelegate.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientDelegate.java new file mode 100644 index 000000000..aacf9466e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientDelegate.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfoList; + +public abstract class ClientDelegate + extends org.omg.CORBA_2_3.portable.Delegate +{ + /** + * The ORB associated * with an invocation. + * + * @return ORB + */ + public abstract ORB getBroker(); + + /** + * Get the CorbaContactInfoList which represents they encoding/protocol/transport + * combinations that may be used to contact the service. + * + * @return CorbaContactInfoList + */ + public abstract ContactInfoList getContactInfoList(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientDelegateFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientDelegateFactory.java new file mode 100644 index 000000000..fb70fb637 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientDelegateFactory.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol ; + +import com.sun.corba.ee.spi.transport.ContactInfoList ; + +import com.sun.corba.ee.spi.protocol.ClientDelegate ; + +/** Interface used to create a ClientDelegate from a ContactInfoList. + */ +public interface ClientDelegateFactory { + ClientDelegate create( ContactInfoList list ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientInvocationInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientInvocationInfo.java new file mode 100644 index 000000000..720789ba3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientInvocationInfo.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import java.util.Iterator; + +/** + * @author Harold Carr + */ +public interface ClientInvocationInfo +{ + public Iterator getContactInfoListIterator(); + + public void setContactInfoListIterator(Iterator contactInfoListIterator); + + public boolean isRetryInvocation(); + + public void setIsRetryInvocation(boolean isRetryInvocation); + + public int getEntryCount(); + + public void incrementEntryCount(); + + public void decrementEntryCount(); + + public void setClientRequestDispatcher(ClientRequestDispatcher clientRequestDispatcher); + + public ClientRequestDispatcher getClientRequestDispatcher(); + + public void setMessageMediator(MessageMediator messageMediator); + + public MessageMediator getMessageMediator(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientRequestDispatcher.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientRequestDispatcher.java new file mode 100644 index 000000000..e3e875959 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ClientRequestDispatcher.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.ContactInfo; + +/** + * ClientRequestDispatcher coordinates the request (and possible + * response) processing for a specific protocol. + * + * @author Harold Carr + */ +public interface ClientRequestDispatcher +{ + /** + * At the beginning of a request the presentation block uses this + * to obtain an OutputObject to set data to be sent on a message. + * + * @param self - + * @param methodName - the remote method name + * @param isOneWay - true if the message is asynchronous + * @param contactInfo - the CorbaContactInfo + * which which created/chose this ClientRequestDispatcher + * + * @return OutputObject + */ + public CDROutputObject beginRequest(Object self, + String methodName, + boolean isOneWay, + ContactInfo contactInfo); + + /** + * After the presentation block has set data on the CDROutputObject + * it signals the PEPt runtime to send the encoded data by calling this + * method. + * + * @param self - + * @param outputObject + * + * @return CDRInputObject if the message is synchronous. + * + * @throws + * {@link org.omg.CORBA.portable.ApplicationException ApplicationException} + * if the remote side raises an exception declared in the remote interface. + * + * @throws + * {@link org.omg.CORBA.portable.RemarshalException RemarshalException} + * if the PEPt runtime would like the presentation block to start over. + */ + public CDRInputObject marshalingComplete(java.lang.Object self, + CDROutputObject outputObject) + // REVISIT EXCEPTIONS + throws + org.omg.CORBA.portable.ApplicationException, + org.omg.CORBA.portable.RemarshalException; + + /** + * After the presentation block completes a request it signals + * the PEPt runtime by calling this method. + * + * This method may release resources. In some cases it may cause + * control or error messages to be sent. + * + * @param broker - + * @param inputObject - + */ + public void endRequest(ORB broker, + java.lang.Object self, + CDRInputObject inputObject); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ForwardException.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ForwardException.java new file mode 100644 index 000000000..337bd8489 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ForwardException.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import org.omg.CORBA.BAD_PARAM ; + +import com.sun.corba.ee.impl.misc.ORBUtility ; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.orb.ORB ; + +/** + * Thrown to signal an OBJECT_FORWARD or LOCATION_FORWARD + */ +public class ForwardException extends RuntimeException { + private ORB orb ; + private org.omg.CORBA.Object obj; + private IOR ior ; + + public ForwardException( ORB orb, IOR ior ) { + super(); + + this.orb = orb ; + this.obj = null ; + this.ior = ior ; + } + + public ForwardException( ORB orb, org.omg.CORBA.Object obj) { + super(); + + // This check is done early so that no attempt + // may be made to do a location forward to a local + // object. Doing this lazily would allow + // forwarding to locals in some restricted cases. + if (obj instanceof org.omg.CORBA.LocalObject) + throw new BAD_PARAM() ; + + this.orb = orb ; + this.obj = obj ; + this.ior = null ; + } + + public synchronized org.omg.CORBA.Object getObject() + { + if (obj == null) { + obj = ORBUtility.makeObjectReference( ior ) ; + } + + return obj ; + } + + public synchronized IOR getIOR() + { + if (ior == null) { + ior = orb.getIOR( obj, false ) ; + } + + return ior ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/InitialServerRequestDispatcher.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/InitialServerRequestDispatcher.java new file mode 100644 index 000000000..5ab400060 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/InitialServerRequestDispatcher.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import com.sun.corba.ee.spi.resolver.Resolver ; + +/** InitialServerRequestDispatcher is a specialized version of a ServerRequestDispatcher + * that provides an initialization method. This delegate is used + * to implement bootstrapping of initial object references. + */ +public interface InitialServerRequestDispatcher + extends ServerRequestDispatcher +{ + /** Plug in the resolver that this InitialServerRequestDispatcher should + * use in order to lookup or list initial name to object reference + * bindings. + */ + void init( Resolver resolver ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/LocalClientRequestDispatcher.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/LocalClientRequestDispatcher.java new file mode 100644 index 000000000..db2726823 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/LocalClientRequestDispatcher.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import org.omg.CORBA.portable.ServantObject; + +/** + * @author Harold Carr + */ + +public interface LocalClientRequestDispatcher +{ + public boolean useLocalInvocation(org.omg.CORBA.Object self); + + public boolean is_local(org.omg.CORBA.Object self); + + /** + * Returns a Java reference to the servant which should be used for this + * request. servant_preinvoke() is invoked by a local stub. + * If a ServantObject object is returned, then its servant field + * has been set to an object of the expected type (Note: the object may + * or may not be the actual servant instance). The local stub may cast + * the servant field to the expected type, and then invoke the operation + * directly. + * + * @param self The object reference which delegated to this delegate. + * + * @param operation a string containing the operation name. + * The operation name corresponds to the operation name as it would be + * encoded in a GIOP request. + * + * @param expectedType a Class object representing the expected type of the servant. + * The expected type is the Class object associated with the operations + * class of the stub's interface (e.g. A stub for an interface Foo, + * would pass the Class object for the FooOperations interface). + * + * @return a ServantObject object. + * The method may return a null value if it does not wish to support + * this optimization (e.g. due to security, transactions, etc). + * The method must return null if the servant is not of the expected type. + */ + public ServantObject servant_preinvoke(org.omg.CORBA.Object self, + String operation, + Class expectedType); + + public void servant_postinvoke(org.omg.CORBA.Object self, + ServantObject servant); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/LocalClientRequestDispatcherFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/LocalClientRequestDispatcherFactory.java new file mode 100644 index 000000000..82c53df5b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/LocalClientRequestDispatcherFactory.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import com.sun.corba.ee.spi.ior.IOR ; + +public interface LocalClientRequestDispatcherFactory { + public LocalClientRequestDispatcher create( int id, IOR ior ) ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/MessageMediator.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/MessageMediator.java new file mode 100644 index 000000000..d7534d363 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/MessageMediator.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.transport.Connection; +import java.nio.ByteBuffer; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA_2_3.portable.InputStream; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.spi.transport.ContactInfo; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.LocateReplyMessage; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.LocateReplyOrReplyMessage; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage; + +/** + * @author Harold Carr + */ +public abstract interface MessageMediator + extends + ResponseHandler +{ + RequestId getRequestIdFromRawBytes(); + public void setReplyHeader(LocateReplyOrReplyMessage header); + public LocateReplyMessage getLocateReplyHeader(); + public ReplyMessage getReplyHeader(); + public void setReplyExceptionDetailMessage(String message); + public RequestMessage getRequestHeader(); + public GIOPVersion getGIOPVersion(); + public byte getEncodingVersion(); + public int getRequestId(); + public boolean isOneWay(); + public String getOperationName(); + public ServiceContexts getRequestServiceContexts(); + public void setRequestServiceContexts(ServiceContexts sc); + public ServiceContexts getReplyServiceContexts(); + public Message getDispatchHeader(); + public int getThreadPoolToUse(); + public boolean dispatch(); + public byte getStreamFormatVersion(); // REVIST name ForRequest? + public byte getStreamFormatVersionForReply(); + + // REVISIT - not sure if the final fragment and DII stuff should + // go here. + + public void sendCancelRequestIfFinalFragmentNotSent(); + + public void setDIIInfo(org.omg.CORBA.Request request); + public boolean isDIIRequest(); + public Exception unmarshalDIIUserException(String repoId, + InputStream inputStream); + public void setDIIException(Exception exception); + public void handleDIIReply(InputStream inputStream); + + public boolean isSystemExceptionReply(); + public boolean isUserExceptionReply(); + public boolean isLocationForwardReply(); + public boolean isDifferentAddrDispositionRequestedReply(); + public short getAddrDispositionReply(); + public IOR getForwardedIOR(); + public SystemException getSystemExceptionReply(); + public void cancelRequest(); + + //////////////////////////////////////////////////// + // + // Server side + // + + public ObjectKeyCacheEntry getObjectKeyCacheEntry(); + public ProtocolHandler getProtocolHandler(); + + //////////////////////////////////////////////////// + // + // ResponseHandler + // + + public org.omg.CORBA.portable.OutputStream createReply(); + public org.omg.CORBA.portable.OutputStream createExceptionReply(); + + //////////////////////////////////////////////////// + // + // from core.ServerRequest + // + + public boolean executeReturnServantInResponseConstructor(); + + public void setExecuteReturnServantInResponseConstructor(boolean b); + + public boolean executeRemoveThreadInfoInResponseConstructor(); + + public void setExecuteRemoveThreadInfoInResponseConstructor(boolean b); + + public boolean executePIInResponseConstructor(); + + public void setExecutePIInResponseConstructor( boolean b ); + + public ORB getBroker(); + + public ContactInfo getContactInfo(); + + public Connection getConnection(); + + /** + * Used to initialize message headers. + * + * Note: this should be moved to a RequestDispatcher. + */ + public void initializeMessage(); + + /** + * Used to send the message (or its last fragment). + * + * Note: this should be moved to a RequestDispatcher. + */ + public void finishSendingRequest(); + + public CDRInputObject waitForResponse(); + + public void setOutputObject(CDROutputObject outputObject); + + public CDROutputObject getOutputObject(); + + public void setInputObject(CDRInputObject inputObject); + + public CDRInputObject getInputObject(); +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/MessageParser.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/MessageParser.java new file mode 100644 index 000000000..eef4b3f18 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/MessageParser.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import java.nio.ByteBuffer; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.trace.Transport; +import com.sun.corba.ee.spi.transport.Connection; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; + + +/** + * + * An interface that knows how to parse bytes into a protocol data unit. + */ +public interface MessageParser { + + @Transport + ByteBuffer getNewBufferAndCopyOld(ByteBuffer byteBuffer); + + /** + * Is this MessageParser expecting more data ? + * + * This method is typically called after a call to parseBytes() + * to determine if the ByteBuffer which has been parsed + * contains a partial Message. + * + * @return - true if more bytes are needed to construct a + * Message. false, if no + * additional bytes remain to be parsed into a Message. + */ + boolean isExpectingMoreData(); + + /** + * If there are sufficient bytes in the ByteBuffer to compose a + * Message, then return a newly initialized Message. + * Otherwise, return null. + * + * When this method is first called, it is assumed that + * ByteBuffer.position() points to the location in the + * ByteBuffer where the beginning of the first + * Message begins. + * + * If there is no partial Message remaining in the + * ByteBuffer when this method exits, this method will e + * this.expectingMoreData to false. + * Otherwise, it will be set to true. + * + * Callees of this method may check isExpectingMoreData() + * subsequently to determine if this MessageParser is expecting + * more data to complete a protocol data unit. Callees may also + * subsequently check hasMoreBytesToParse() to determine if this + * MessageParser has more data to parse in the given + * ByteBuffer. + * + * @return Message if one is found in the ByteBuffer. + * Otherwise, returns null. + */ + // REVISIT - This interface should be declared without a CorbaConnection. + // As a result, this interface will likely be deprecated in a + // future release in favor of Message parseBytes(ByteBuffer byteBuffer) + Message parseBytes(ByteBuffer byteBuffer, Connection connection); + + /** + * Are there more bytes to be parsed in the ByteBuffer given + * to this MessageParser's parseBytes ? + * + * This method is typically called after a call to parseBytes() + * to determine if the ByteBuffer has more bytes which need to + * parsed into a Message. + * + * @return true if there are more bytes to be parsed. + * Otherwise false. + */ + boolean hasMoreBytesToParse(); + + /** + * Set the starting position where the next message in the + * ByteBuffer given to parseBytes() begins. + */ + void setNextMessageStartPosition(int position); + + /** + * Get the starting position where the next message in the + * ByteBuffer given to parseBytes() begins. + */ + int getNextMessageStartPosition(); + + /** + * Return the suggested number of bytes needed to hold the next message + * to be parsed. + */ + int getSizeNeeded(); + + /** + * Returns the byte buffer (if any) associated with the last message returned. + */ + ByteBuffer getMsgByteBuffer(); + + /** + * Offers an input buffer to the parser. Position must be set to 0, and the buffer must contain at least the start + * of a GIOP message. The parser will consume what it can and make the remainder available in {@link #getRemainderBuffer} + * @param buffer a buffer containing at least the start of a GIOP message. + */ + void offerBuffer(ByteBuffer buffer); + + /** + * Returns a buffer containing whatever is left after processing the buffer provided in {@link #offerBuffer(ByteBuffer)}, + * which could be the same buffer. The buffer could also be null if all data has been consumed. + * @return a byte buffer representing data which still needs to be processed. + */ + ByteBuffer getRemainderBuffer(); + + /** + * Returns the full message constructed by the last call to {@link #offerBuffer(ByteBuffer)}. Will be null if + * the last such call did not complete a message. + * @return a complete message, wrapped in a message mediator. + */ + MessageMediator getMessageMediator(); + + /** + * Checks for a stalled or rogue client. If in the middle of receiving a message and the time exceeds the limit, + * will throw a communications failure exception. + * @param timeSinceLastInput the number of milliseconds since the last input was received. + */ + void checkTimeout(long timeSinceLastInput); + + boolean isExpectingFragments(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/PIHandler.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/PIHandler.java new file mode 100644 index 000000000..f21ecea5e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/PIHandler.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import java.io.Closeable ; + +import org.omg.PortableInterceptor.ObjectReferenceTemplate ; +import org.omg.PortableInterceptor.Interceptor ; +import org.omg.PortableInterceptor.Current ; +import org.omg.PortableInterceptor.PolicyFactory ; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName ; + +import org.omg.CORBA.NVList ; +import org.omg.CORBA.Any ; +import org.omg.CORBA.Policy ; +import org.omg.CORBA.PolicyError ; + +import org.omg.CORBA.portable.RemarshalException; + +import com.sun.corba.ee.spi.oa.ObjectAdapter ; + +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; + +import com.sun.corba.ee.impl.corba.RequestImpl ; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage ; + +/** This interface defines the PI interface that is used to interface the rest of the + * ORB to the PI implementation. + */ +public interface PIHandler extends Closeable { + /** Complete the initialization of the PIHandler. This will execute the methods + * on the ORBInitializers, if any are defined. This must be done here so that + * the ORB can obtain the PIHandler BEFORE the ORBInitializers run, since they + * will need access to the PIHandler through the ORB. + */ + public void initialize() ; + + public void destroyInterceptors() ; + + /* + **************************** + * IOR interceptor PI hooks + ****************************/ + + /** + * Called when a new object adapter is created. + * + * @param oa The adapter associated with the interceptors to be + * invoked. + */ + void objectAdapterCreated( ObjectAdapter oa ) ; + + /** + * Called whenever a state change occurs in an adapter manager. + * + * @param managerId managerId The adapter manager id + * @param newState newState The new state of the adapter manager, + * and by implication of all object adapters managed by this manager. + */ + void adapterManagerStateChanged( int managerId, + short newState ) ; + + /** Called whenever a state change occurs in an object adapter that + * was not caused by an adapter manager state change. + * + * @param templates The templates that are changing state. + * @param newState The new state of the adapters identified by the + * templates. + */ + void adapterStateChanged( ObjectReferenceTemplate[] templates, + short newState ) ; + + /* + ***************** + * Client PI hooks + *****************/ + + /** + * Called for pseudo-ops to temporarily disable portable interceptor + * hooks for calls on this thread. Keeps track of the number of + * times this is called and increments the disabledCount. + */ + void disableInterceptorsThisThread() ; + + /** + * Called for pseudo-ops to re-enable portable interceptor + * hooks for calls on this thread. Decrements the disabledCount. + * If disabledCount is 0, interceptors are re-enabled. + */ + void enableInterceptorsThisThread() ; + + /** + * Called when the send_request or send_poll portable interception point + * is to be invoked for all appropriate client-side request interceptors. + * + * @exception RemarhsalException - Thrown when this request needs to + * be retried. + */ + void invokeClientPIStartingPoint() + throws RemarshalException ; + + /** + * Called when the appropriate client ending interception point is + * to be invoked for all apporpriate client-side request interceptors. + * + * @param replyStatus One of the constants in iiop.messages.ReplyMessage + * indicating which reply status to set. + * @param exception The exception before ending interception points have + * been invoked, or null if no exception at the moment. + * @return The exception to be thrown, after having gone through + * all ending points, or null if there is no exception to be + * thrown. Note that this exception can be either the same or + * different from the exception set using setClientPIException. + * There are four possible return types: null (no exception), + * SystemException, UserException, or RemarshalException. + */ + Exception invokeClientPIEndingPoint( + int replyStatus, Exception exception ) ; + + /** + * Called when a retry is needed after initiateClientPIRequest but + * before invokeClientPIRequest. In this case, we need to properly + * balance initiateClientPIRequest/cleanupClientPIRequest calls, + * but WITHOUT extraneous calls to invokeClientPIEndingPoint + * (see bug 6763340). + * + * @param replyStatus One of the constants in iiop.messages.ReplyMessage + * indicating which reply status to set. + * @param exception The exception before ending interception points have + * been invoked, or null if no exception at the moment. + * @return The exception to be thrown, after having gone through + * all ending points, or null if there is no exception to be + * thrown. Note that this exception can be either the same or + * different from the exception set using setClientPIException. + * There are four possible return types: null (no exception), + * SystemException, UserException, or RemarshalException. + */ + Exception makeCompletedClientRequest( + int replyStatus, Exception exception ) ; + + /** + * Invoked when a request is about to be created. Must be called before + * any of the setClientPI* methods so that a new info object can be + * prepared for information collection. + * + * @param diiRequest True if this is to be a DII request, or false if it + * is a "normal" request. In the DII case, initiateClientPIRequest + * is called twice and we need to ignore the second one. + */ + void initiateClientPIRequest( boolean diiRequest ) ; + + /** + * Invoked when a request is about to be cleaned up. Must be called + * after ending points are called so that the info object on the stack + * can be deinitialized and popped from the stack at the appropriate + * time. + */ + void cleanupClientPIRequest() ; + + /** + * Notifies PI of additional information for client-side interceptors. + * PI will use this information as a source of information for the + * ClientRequestInfo object. + */ + void setClientPIInfo( RequestImpl requestImpl ) ; + + /** + * Notify PI of the MessageMediator for the request. + */ + void setClientPIInfo(MessageMediator messageMediator) ; + + /* + ***************** + * Server PI hooks + *****************/ + + /** + * Called when the appropriate server starting interception point is + * to be invoked for all appropriate server-side request interceptors. + * + * @throws ForwardException Thrown if an interceptor raises + * ForwardRequest. This is an unchecked exception so that we need + * not modify the entire execution path to declare throwing + * ForwardException. + */ + void invokeServerPIStartingPoint() ; + + /** + * Called when the appropriate server intermediate interception point is + * to be invoked for all appropriate server-side request interceptors. + * + * @throws ForwardException Thrown if an interceptor raises + * ForwardRequest. This is an unchecked exception so that we need + * not modify the entire execution path to declare throwing + * ForwardException. + */ + void invokeServerPIIntermediatePoint() ; + + /** + * Called when the appropriate server ending interception point is + * to be invoked for all appropriate server-side request interceptors. + * + * @param replyMessage The iiop.messages.ReplyMessage containing the + * reply status. + * @throws ForwardException Thrown if an interceptor raises + * ForwardRequest. This is an unchecked exception so that we need + * not modify the entire execution path to declare throwing + * ForwardException. + */ + void invokeServerPIEndingPoint( ReplyMessage replyMessage ) ; + + /** + * Notifies PI to start a new server request and set initial + * information for server-side interceptors. + * PI will use this information as a source of information for the + * ServerRequestInfo object. poaimpl is declared as an Object so that + * we need not introduce a dependency on the POA package. + */ + void initializeServerPIInfo( MessageMediator request, + ObjectAdapter oa, byte[] objectId, ObjectKeyTemplate oktemp ) ; + + /** + * Notifies PI of additional information reqired for ServerRequestInfo. + * + * @param servant The servant. This is java.lang.Object because in the + * POA case, this will be a org.omg.PortableServer.Servant whereas + * in the ServerRequestDispatcher case this will be an ObjectImpl. + * @param targetMostDerivedInterface The most derived interface. This + * is passed in instead of calculated when needed because it requires + * extra information in the POA case that we didn't want to bother + * creating extra methods for to pass in. + */ + void setServerPIInfo( java.lang.Object servant, + String targetMostDerivedInterface ) ; + + /** + * Notifies PI of additional information required for ServerRequestInfo. + */ + void setServerPIInfo( Exception exception ) ; + + /** + * Notifies PI of additional information for server-side interceptors. + * PI will use this information as a source of information for the + * ServerRequestInfo object. These are the arguments for a DSI request. + */ + void setServerPIInfo( NVList arguments ) ; + + /** + * Notifies PI of additional information for server-side interceptors. + * PI will use this information as a source of information for the + * ServerRequestInfo object. This is the exception of a DSI request. + */ + void setServerPIExceptionInfo( Any exception ) ; + + /** + * Notifies PI of additional information for server-side interceptors. + * PI will use this information as a source of information for the + * ServerRequestInfo object. This is the result of a DSI request. + */ + void setServerPIInfo( Any result ) ; + + /** + * Invoked when a request is about to be cleaned up. Must be called + * after ending points are called so that the info object on the stack + * can be deinitialized and popped from the stack at the appropriate + * time. + */ + void cleanupServerPIRequest() ; + + Policy create_policy( int type, Any val ) throws PolicyError ; + + void register_interceptor( Interceptor interceptor, int type ) + throws DuplicateName ; + + Current getPICurrent() ; + + void registerPolicyFactory( int type, PolicyFactory factory ) ; + + int allocateServerRequestId() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ProtocolHandler.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ProtocolHandler.java new file mode 100644 index 000000000..a2a2327f4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ProtocolHandler.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.UnknownException; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.LocateRequestMessage; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage; + +/** + * @author Harold Carr + */ +public abstract interface ProtocolHandler +{ + public void handleRequest(RequestMessage header, + MessageMediator messageMediator); + + public void handleRequest(LocateRequestMessage header, + MessageMediator messageMediator); + + public MessageMediator createResponse( + MessageMediator messageMediator, + ServiceContexts svc); + public MessageMediator createUserExceptionResponse( + MessageMediator messageMediator, + ServiceContexts svc); + public MessageMediator createUnknownExceptionResponse( + MessageMediator messageMediator, + UnknownException ex); + public MessageMediator createSystemExceptionResponse( + MessageMediator messageMediator, + SystemException ex, + ServiceContexts svc); + public MessageMediator createLocationForward( + MessageMediator messageMediator, + IOR ior, + ServiceContexts svc); + + public void handleThrowableDuringServerDispatch( + MessageMediator request, + Throwable exception, + CompletionStatus completionStatus); + + public boolean handleRequest(MessageMediator messageMediator); + +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestDispatcherDefault.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestDispatcherDefault.java new file mode 100644 index 000000000..7bd6e599e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestDispatcherDefault.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol ; + + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory ; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; + +import com.sun.corba.ee.spi.orb.ORB ; + +// Used only in the implementation: no client of this class ever needs these +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.impl.protocol.ClientRequestDispatcherImpl ; +import com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl ; +import com.sun.corba.ee.impl.protocol.MinimalServantCacheLocalCRDImpl ; +import com.sun.corba.ee.impl.protocol.InfoOnlyServantCacheLocalCRDImpl ; +import com.sun.corba.ee.impl.protocol.FullServantCacheLocalCRDImpl ; +import com.sun.corba.ee.impl.protocol.JIDLLocalCRDImpl ; +import com.sun.corba.ee.impl.protocol.POALocalCRDImpl ; +import com.sun.corba.ee.impl.protocol.INSServerRequestDispatcher ; +import com.sun.corba.ee.impl.protocol.BootstrapServerRequestDispatcher ; + +public final class RequestDispatcherDefault { + private RequestDispatcherDefault() {} + + public static ClientRequestDispatcher makeClientRequestDispatcher() + { + return new ClientRequestDispatcherImpl() ; + } + + public static ServerRequestDispatcher makeServerRequestDispatcher( ORB orb ) + { + return new ServerRequestDispatcherImpl( (com.sun.corba.ee.spi.orb.ORB)orb ) ; + } + + public static ServerRequestDispatcher makeBootstrapServerRequestDispatcher( ORB orb ) + { + return new BootstrapServerRequestDispatcher( orb ) ; + } + + public static ServerRequestDispatcher makeINSServerRequestDispatcher( ORB orb ) + { + return new INSServerRequestDispatcher( orb ) ; + } + + public static LocalClientRequestDispatcherFactory makeMinimalServantCacheLocalClientRequestDispatcherFactory( final ORB orb ) + { + return new LocalClientRequestDispatcherFactory() { + public LocalClientRequestDispatcher create( int id, IOR ior ) { + return new MinimalServantCacheLocalCRDImpl( orb, id, ior ) ; + } + } ; + } + + public static LocalClientRequestDispatcherFactory makeInfoOnlyServantCacheLocalClientRequestDispatcherFactory( final ORB orb ) + { + return new LocalClientRequestDispatcherFactory() { + public LocalClientRequestDispatcher create( int id, IOR ior ) { + return new InfoOnlyServantCacheLocalCRDImpl( orb, id, ior ) ; + } + } ; + } + + public static LocalClientRequestDispatcherFactory makeFullServantCacheLocalClientRequestDispatcherFactory( final ORB orb ) + { + return new LocalClientRequestDispatcherFactory() { + public LocalClientRequestDispatcher create( int id, IOR ior ) { + return new FullServantCacheLocalCRDImpl( orb, id, ior ) ; + } + } ; + } + + public static LocalClientRequestDispatcherFactory makeJIDLLocalClientRequestDispatcherFactory( final ORB orb ) + { + return new LocalClientRequestDispatcherFactory() { + public LocalClientRequestDispatcher create( int id, IOR ior ) { + return new JIDLLocalCRDImpl( orb, id, ior ) ; + } + } ; + } + + public static LocalClientRequestDispatcherFactory makePOALocalClientRequestDispatcherFactory( final ORB orb ) + { + return new LocalClientRequestDispatcherFactory() { + public LocalClientRequestDispatcher create( int id, IOR ior ) { + return new POALocalCRDImpl( orb, id, ior ) ; + } + } ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestDispatcherRegistry.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestDispatcherRegistry.java new file mode 100644 index 000000000..51ef6f435 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestDispatcherRegistry.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +import java.util.Set; + +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher ; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcherFactory ; + +import com.sun.corba.ee.spi.oa.ObjectAdapterFactory ; + +/** + * This is a registry of all subcontract ID dependent objects. This includes: + * LocalClientRequestDispatcherFactory, ClientRequestDispatcher, ServerRequestDispatcher, and + * ObjectAdapterFactory. + */ +public interface RequestDispatcherRegistry { + + /** Register a ClientRequestDispatcher for a particular subcontract ID. + * The subcontract ID appears in the ObjectKey of an object reference, and is used + * to control how a remote method invocation is processed by the ORB for a + * particular kind of object reference. + */ + void registerClientRequestDispatcher( ClientRequestDispatcher csc, int scid) ; + + /** Get the ClientRequestDispatcher for subcontract ID scid. + */ + ClientRequestDispatcher getClientRequestDispatcher( int scid ) ; + + /** Register a LocalClientRequestDispatcher for a particular subcontract ID. + * The subcontract ID appears in the ObjectKey of an object reference, and is used + * to control how a particular kind of colocated request is processed. + */ + void registerLocalClientRequestDispatcherFactory( LocalClientRequestDispatcherFactory csc, int scid) ; + + /** Get the LocalClientRequestDispatcher for subcontract ID scid. + */ + LocalClientRequestDispatcherFactory getLocalClientRequestDispatcherFactory( int scid ) ; + + /** Register a CorbaServerRequestDispatcher for a particular subcontract ID. + * The subcontract ID appears in the ObjectKey of an object reference, and is used + * to control how a particular kind of request is processed when received by the ORB. + */ + void registerServerRequestDispatcher( ServerRequestDispatcher ssc, int scid) ; + + /** Get the CorbaServerRequestDispatcher for subcontract ID scid. + */ + ServerRequestDispatcher getServerRequestDispatcher(int scid) ; + + /** Register a CorbaServerRequestDispatcher for handling an explicit object key name. + * This is used for non-standard invocations such as INS and the bootstrap name service. + */ + void registerServerRequestDispatcher( ServerRequestDispatcher ssc, String name ) ; + + /** Get the CorbaServerRequestDispatcher for a particular object key. + */ + ServerRequestDispatcher getServerRequestDispatcher( String name ) ; + + /** Register an ObjectAdapterFactory for a particular subcontract ID. + * This controls how Object references are created and managed. + */ + void registerObjectAdapterFactory( ObjectAdapterFactory oaf, int scid) ; + + /** Get the ObjectAdapterFactory for a particular subcontract ID scid. + */ + ObjectAdapterFactory getObjectAdapterFactory( int scid ) ; + + /** Return the set of all ObjectAdapterFactory instances that are registered. + */ + Set getObjectAdapterFactories() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestId.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestId.java new file mode 100644 index 000000000..069841bcc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RequestId.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + +/** + * Represents a Corba protocol request id. + * + * @author Charlie Hunt + */ +public interface RequestId { + /** + * return its value + */ + int getValue(); + + /** + * Is there a numeric value for this CorbaRequestId ? + */ + boolean isDefined(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RetryType.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RetryType.java new file mode 100644 index 000000000..7066406e5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/RetryType.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol ; + +// Introduce more information about WHY we are re-trying a request +// so we can properly handle the two cases: +// - BEFORE_RESPONSE means that the retry is caused by +// something that happened BEFORE the message was sent: either +// an exception from the SocketFactory, or one from the +// Client side send_request interceptor point. +// - AFTER_RESPONSE means that the retry is a result either of the +// request sent to the server (from the response), or from the +// Client side receive_xxx interceptor point. +public enum RetryType { + NONE( false ), + BEFORE_RESPONSE( true ), + AFTER_RESPONSE( true ) ; + + private final boolean isRetry ; + + RetryType( boolean isRetry ) { + this.isRetry = isRetry ; + } + + public boolean isRetry() { + return this.isRetry ; + } +} ; + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ServerRequestDispatcher.java b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ServerRequestDispatcher.java new file mode 100644 index 000000000..60151a302 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/ServerRequestDispatcher.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.protocol; + + +import com.sun.corba.ee.spi.ior.ObjectKey; + +import com.sun.corba.ee.spi.ior.IOR ; + +/** + * Server delegate adds behavior on the server-side -- specifically + * on the dispatch path. A single server delegate instance serves + * many server objects. This is the second level of the dispatch + * on the server side: Acceptor to ServerSubcontract to ServerRequestDispatcher to + * ObjectAdapter to Servant, although this may be short-circuited. + * Instances of this class are registered in the subcontract Registry. + */ +public abstract interface ServerRequestDispatcher +{ + /** + * Handle a locate request. + */ + public IOR locate(ObjectKey key); + + public void dispatch(MessageMediator messageMediator); +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/protocol.zargo b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/protocol.zargo new file mode 100644 index 000000000..8b4ca554c Binary files /dev/null and b/orbmain/src/main/java/com/sun/corba/ee/spi/protocol/protocol.zargo differ diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/LocalResolver.java b/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/LocalResolver.java new file mode 100644 index 000000000..006e54987 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/LocalResolver.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.resolver ; + +import org.glassfish.pfl.basic.func.NullaryFunction; + +/** A LocalResolver is a Resolver that allows registration of (name, CORBA object) + * bindings. + */ +public interface LocalResolver extends Resolver { + /** Register the Closure with the given name. + */ + void register( String name, NullaryFunction closure ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/Resolver.java b/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/Resolver.java new file mode 100644 index 000000000..1f3fa773b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/Resolver.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.resolver ; + +/** Resolver defines the operations needed to support ORB operations for + * resolve_initial_references and list_initial_services. + */ +public interface Resolver { + /** Look up the name using this resolver and return the CORBA object + * reference bound to this name, if any. Returns null if no object + * is bound to the name. + */ + org.omg.CORBA.Object resolve( String name ) ; + + /** Return the entire collection of names that are currently bound + * by this resolver. Resulting collection contains only strings for + * which resolve does not return null. Some resolvers may not support + * this method, in which case they return an empty set. + */ + java.util.Set list() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/ResolverDefault.java b/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/ResolverDefault.java new file mode 100644 index 000000000..38557dfff --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/resolver/ResolverDefault.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.resolver ; + +import java.io.File ; + +import com.sun.corba.ee.impl.resolver.LocalResolverImpl ; +import com.sun.corba.ee.impl.resolver.ORBInitRefResolverImpl ; +import com.sun.corba.ee.impl.resolver.ORBDefaultInitRefResolverImpl ; +import com.sun.corba.ee.impl.resolver.BootstrapResolverImpl ; +import com.sun.corba.ee.impl.resolver.CompositeResolverImpl ; +import com.sun.corba.ee.impl.resolver.INSURLOperationImpl ; +import com.sun.corba.ee.impl.resolver.SplitLocalResolverImpl ; +import com.sun.corba.ee.impl.resolver.FileResolverImpl ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.Operation ; +import org.glassfish.pfl.basic.contain.Pair; + +/** Utility class that provides factory methods for all of the + * standard resolvers that we provide. + */ +public class ResolverDefault { + /** Return a local resolver that simply stores bindings in a map. + */ + public static LocalResolver makeLocalResolver( ) + { + return new LocalResolverImpl() ; + } + + /** Return a resolver that relies on configured values of ORBInitRef for data. + */ + public static Resolver makeORBInitRefResolver( Operation urlOperation, + Pair[] initRefs ) + { + return new ORBInitRefResolverImpl( urlOperation, initRefs ) ; + } + + public static Resolver makeORBDefaultInitRefResolver( Operation urlOperation, + String defaultInitRef ) + { + return new ORBDefaultInitRefResolverImpl( urlOperation, + defaultInitRef ) ; + } + + /** Return a resolver that uses the proprietary bootstrap protocol + * to implement a resolver. Obtains the necessary host and port + * information from the ORB. + */ + public static Resolver makeBootstrapResolver( ORB orb, String host, int port ) + { + return new BootstrapResolverImpl( orb, host, port ) ; + } + + /** Return a resolver composed of the two given resolvers. result.list() is the + * union of first.list() and second.list(). result.resolve( name ) returns + * first.resolve( name ) if that is not null, otherwise returns the result of + * second.resolve( name ). + */ + public static Resolver makeCompositeResolver( Resolver first, Resolver second ) + { + return new CompositeResolverImpl( first, second ) ; + } + + public static Operation makeINSURLOperation( ORB orb ) + { + return new INSURLOperationImpl( orb ) ; + } + + public static LocalResolver makeSplitLocalResolver( Resolver resolver, + LocalResolver localResolver ) + { + return new SplitLocalResolverImpl( resolver, localResolver ) ; + } + + public static Resolver makeFileResolver( ORB orb, File file ) + { + return new FileResolverImpl( orb, file ) ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/CodeSetServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/CodeSetServiceContext.java new file mode 100644 index 000000000..e17991bc4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/CodeSetServiceContext.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; + +public interface CodeSetServiceContext extends ServiceContext { + int SERVICE_CONTEXT_ID = 1 ; + + CodeSetComponentInfo.CodeSetContext getCodeSetContext() ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/MaxStreamFormatVersionServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/MaxStreamFormatVersionServiceContext.java new file mode 100644 index 000000000..234c0771b --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/MaxStreamFormatVersionServiceContext.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import org.omg.IOP.RMICustomMaxStreamFormat; + +public interface MaxStreamFormatVersionServiceContext extends ServiceContext { + int SERVICE_CONTEXT_ID = RMICustomMaxStreamFormat.value ; + + byte getMaximumStreamFormatVersion() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ORBVersionServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ORBVersionServiceContext.java new file mode 100644 index 000000000..42883eadd --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ORBVersionServiceContext.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import com.sun.corba.ee.spi.orb.ORBVersion ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +public interface ORBVersionServiceContext extends ServiceContext { + int SERVICE_CONTEXT_ID = ORBConstants.TAG_ORB_VERSION ; + + ORBVersion getVersion() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/SendingContextServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/SendingContextServiceContext.java new file mode 100644 index 000000000..5e125cfcc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/SendingContextServiceContext.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; + +public interface SendingContextServiceContext extends ServiceContext +{ + int SERVICE_CONTEXT_ID = 6 ; + + IOR getIOR() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContext.java new file mode 100644 index 000000000..06a53b366 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContext.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +/** Base class for all ServiceContext classes. +* There is a derived ServiceContext class for each service context that +* the ORB supports. Each subclass encapsulates the representation of +* the service context and provides any needed methods for manipulating +* the service context. +*

                +* The subclass can be constructed either directly from the service context +* representation, or by reading the representation from an input stream. +* These cases are needed when the service context is created and written to +* the request or reply, and when the service context is read from the +* received request or reply. +*/ +public interface ServiceContext { + public interface Factory { + int getId() ; + + ServiceContext create( InputStream s, GIOPVersion gv ) ; + } + + int getId() ; + + void write(OutputStream s, GIOPVersion gv ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextBase.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextBase.java new file mode 100644 index 000000000..338606d3a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextBase.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; +import com.sun.corba.ee.impl.encoding.OutputStreamFactory; +import com.sun.corba.ee.spi.logging.ORBUtilSystemException; + +/** Base class for all ServiceContext classes. +* There is a derived ServiceContext class for each service context that +* the ORB supports. Each subclass encapsulates the representation of +* the service context and provides any needed methods for manipulating +* the service context. Each subclass must provide the following +* members: +*

                +*

                  +* a public static final int SERVICE_CONTEXT_ID that gives the OMG +* (or other) defined id for the service context. This is needed for the +* registration mechanism defined in ServiceContexts. OMG defined +* service context ids are taken from section 13.6.7 of ptc/98-12-04. +*
                • a public constructor that takes an InputStream as its argument.
                • +*
                • Appropriate definitions of getId() and writeData(). getId() must +* return SERVICE_CONTEXT_ID.
                • +*
                +*

                +* The subclass can be constructed either directly from the service context +* representation, or by reading the representation from an input stream. +* These cases are needed when the service context is created and written to +* the request or reply, and when the service context is read from the +* received request or reply. +*/ +public abstract class ServiceContextBase { + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + /** Simple default constructor used when subclass is constructed + * from its representation. + */ + + private byte[] data; + + protected ServiceContextBase() { } + + /** Stream constructor used when subclass is constructed from an + * InputStream. This constructor must be called by super( stream ) + * in the subclass. After this constructor completes, the service + * context representation can be read from in. + * Note that the service context id has been consumed from the input + * stream before this object is constructed. + */ + protected ServiceContextBase(InputStream s) + { + in = s; + } + + /** Returns Service context id. Must be overloaded in subclass. + */ + public abstract int getId() ; + + /** Write the service context to an output stream. This method + * must be used for writing the service context to a request or reply + * header. + */ + public synchronized void write(OutputStream s, GIOPVersion gv) throws SystemException { + if (data == null) { + EncapsOutputStream os = OutputStreamFactory.newEncapsOutputStream((ORB)(s.orb()), gv); + try { + os.putEndian(); + writeData(os); + data = os.toByteArray(); + } finally { + try { + os.close(); + } catch (java.io.IOException e) { + wrapper.ioexceptionDuringStreamClose(e); + } + } + } + s.write_long(getId()); + s.write_long(data.length); + s.write_octet_array(data, 0, data.length); + } + + /** Writes the data used to represent the subclasses service context + * into an encapsulation stream. Must be overloaded in subclass. + */ + protected abstract void writeData( OutputStream os ) ; + + /** in is the stream containing the service context representation. + * It is constructed by the stream constructor, and available for use + * in the subclass stream constructor. + */ + protected InputStream in = null ; + + @Override + public String toString() + { + return "ServiceContext[ id=" + getId() + " ]" ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextDefaults.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextDefaults.java new file mode 100644 index 000000000..b35554eaa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextDefaults.java @@ -0,0 +1,197 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.orb.ORBVersion ; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; + +import com.sun.corba.ee.spi.servicecontext.ServiceContexts ; +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; +import com.sun.corba.ee.spi.servicecontext.ServiceContextFactoryRegistry ; +import com.sun.corba.ee.spi.servicecontext.CodeSetServiceContext ; +import com.sun.corba.ee.spi.servicecontext.ORBVersionServiceContext ; +import com.sun.corba.ee.spi.servicecontext.MaxStreamFormatVersionServiceContext ; +import com.sun.corba.ee.spi.servicecontext.UEInfoServiceContext ; +import com.sun.corba.ee.spi.servicecontext.UnknownServiceContext ; + +import com.sun.corba.ee.impl.servicecontext.ServiceContextsImpl ; +import com.sun.corba.ee.impl.servicecontext.ServiceContextFactoryRegistryImpl ; +import com.sun.corba.ee.impl.servicecontext.CodeSetServiceContextImpl ; +import com.sun.corba.ee.impl.servicecontext.ORBVersionServiceContextImpl ; +import com.sun.corba.ee.impl.servicecontext.MaxStreamFormatVersionServiceContextImpl ; +import com.sun.corba.ee.impl.servicecontext.UEInfoServiceContextImpl ; +import com.sun.corba.ee.impl.servicecontext.UnknownServiceContextImpl ; +import com.sun.corba.ee.impl.servicecontext.SendingContextServiceContextImpl ; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo ; + +import com.sun.corba.ee.spi.orb.ORBVersionFactory; + + +public abstract class ServiceContextDefaults { + + private static ORBVersion orbVersion = ORBVersionFactory.getORBVersion(); + private static ORBVersionServiceContext orbVersionContext = + new ORBVersionServiceContextImpl( orbVersion ); + + private ServiceContextDefaults() {} + + public static ServiceContexts makeServiceContexts( ORB orb ) + { + return new ServiceContextsImpl( orb ) ; + } + + public static ServiceContexts makeServiceContexts( InputStream is ) + { + return new ServiceContextsImpl( is ) ; + } + + public static ServiceContextFactoryRegistry makeServiceContextFactoryRegistry( + ORB orb ) + { + return new ServiceContextFactoryRegistryImpl( orb ) ; + } + + public static CodeSetServiceContext makeCodeSetServiceContext( + CodeSetComponentInfo.CodeSetContext csc ) + { + return new CodeSetServiceContextImpl( csc ) ; + } + + public static ServiceContext.Factory makeCodeSetServiceContextFactory() + { + return new ServiceContext.Factory() { + public int getId() + { + return CodeSetServiceContext.SERVICE_CONTEXT_ID ; + } + + public ServiceContext create( InputStream s, GIOPVersion gv ) + { + return new CodeSetServiceContextImpl( s, gv ) ; + } + } ; + } + + public static ServiceContext.Factory + makeMaxStreamFormatVersionServiceContextFactory() + { + return new ServiceContext.Factory() { + public int getId() + { + return MaxStreamFormatVersionServiceContext.SERVICE_CONTEXT_ID ; + } + + public ServiceContext create( InputStream s, GIOPVersion gv ) + { + return new MaxStreamFormatVersionServiceContextImpl( s, gv ) ; + } + } ; + } + + public static MaxStreamFormatVersionServiceContext + getMaxStreamFormatVersionServiceContext() + { + return MaxStreamFormatVersionServiceContextImpl.singleton ; + } + + public static MaxStreamFormatVersionServiceContext + makeMaxStreamFormatVersionServiceContext( byte version ) + { + return new MaxStreamFormatVersionServiceContextImpl( version ) ; + } + + public static ServiceContext.Factory makeORBVersionServiceContextFactory() + { + return new ServiceContext.Factory() { + public int getId() + { + return ORBVersionServiceContext.SERVICE_CONTEXT_ID ; + } + + public ServiceContext create( InputStream s, GIOPVersion gv ) + { + return new ORBVersionServiceContextImpl( s, gv ) ; + } + } ; + } + + public static ORBVersionServiceContext getORBVersionServiceContext() + { + return ORBVersionServiceContextImpl.singleton ; + } + + public static ORBVersionServiceContext makeORBVersionServiceContext() + { + return orbVersionContext ; + } + + public static ServiceContext.Factory makeSendingContextServiceContextFactory() + { + return new ServiceContext.Factory() { + public int getId() + { + return SendingContextServiceContext.SERVICE_CONTEXT_ID ; + } + + public ServiceContext create( InputStream s, GIOPVersion gv ) + { + return new SendingContextServiceContextImpl( s, gv ) ; + } + } ; + } + + public static SendingContextServiceContext + makeSendingContextServiceContext( IOR ior ) + { + return new SendingContextServiceContextImpl( ior ) ; + } + + public static ServiceContext.Factory makeUEInfoServiceContextFactory() + { + return new ServiceContext.Factory() { + public int getId() + { + return UEInfoServiceContext.SERVICE_CONTEXT_ID ; + } + + public ServiceContext create( InputStream s, GIOPVersion gv ) + { + return new UEInfoServiceContextImpl( s, gv ) ; + } + } ; + } + + public static UEInfoServiceContext + makeUEInfoServiceContext( Throwable thr ) + { + return new UEInfoServiceContextImpl( thr ) ; + } + + public static UnknownServiceContext + makeUnknownServiceContext( int id, byte[] data ) + { + return new UnknownServiceContextImpl( id, data ) ; + } + + public static UnknownServiceContext + makeUnknownServiceContext( int id, InputStream str ) + { + return new UnknownServiceContextImpl( id, str ) ; + } +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextFactoryRegistry.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextFactoryRegistry.java new file mode 100644 index 000000000..63bfa9df9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextFactoryRegistry.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; + +public interface ServiceContextFactoryRegistry { + + public void register( ServiceContext.Factory factory ) ; + + public ServiceContext.Factory find( int scId ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContexts.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContexts.java new file mode 100644 index 000000000..35605e3f5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContexts.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; + +/** The collection of ServiceContext instances used in a particular + * request. + */ +public interface ServiceContexts { + /** Write the service contexts to the output stream. + * If an UnknownExceptionInfo service context is present, + * it is written out last, so that it follows any + * SendingContext service context. This is required so that + * the codebase is available to handle value types if + * necessary. + * + * We should really do this as SendingContext goes first, so + * that we can guarantee correct marshalling of non-standard + * service contexts. + */ + void write( OutputStream os, GIOPVersion gv ) ; + + /** Add a service context. Silently replaces an existing + * service context with the same id. + */ + public void put( ServiceContext sc ) ; + + /** Remove the service context with the id, if any. + */ + public void delete( int scId ) ; + + /** Return the service context with scId, or null if not + * found. + */ + public ServiceContext get( int scId) ; + + public ServiceContexts copy() ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextsCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextsCache.java new file mode 100644 index 000000000..e921c3662 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/ServiceContextsCache.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import java.util.EnumMap; +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo; +import com.sun.corba.ee.spi.orb.ORB; + +public class ServiceContextsCache { + + public static enum CASE { + CLIENT_INITIAL, + CLIENT_SUBSEQUENT, + SERVER_INITIAL, + SERVER_SUBSEQUENT}; + + private EnumMap data; + private ORB orb; + + public ServiceContextsCache (com.sun.corba.ee.spi.orb.ORB orb) { + + data = new EnumMap(CASE.class); + this.orb = orb; + + } + + public synchronized ServiceContexts get(CASE c) { + + if (data.size() == 0) { + + //CLIENT_INITIAL + ServiceContexts scContainer = ServiceContextDefaults.makeServiceContexts(orb); + scContainer.put(ServiceContextDefaults.getMaxStreamFormatVersionServiceContext()); + scContainer.put(ServiceContextDefaults.getORBVersionServiceContext()); + scContainer.put(ServiceContextDefaults.makeSendingContextServiceContext(orb.getFVDCodeBaseIOR())); + + data.put(CASE.CLIENT_INITIAL, scContainer); + + //CLIENT_SUBSEQUENT + scContainer = ServiceContextDefaults.makeServiceContexts(orb); + scContainer.put(ServiceContextDefaults.getMaxStreamFormatVersionServiceContext()); + scContainer.put(ServiceContextDefaults.getORBVersionServiceContext()); + + data.put(CASE.CLIENT_SUBSEQUENT, scContainer); + + //SERVER_INITIAL + scContainer = ServiceContextDefaults.makeServiceContexts(orb); + scContainer.put(ServiceContextDefaults.getORBVersionServiceContext()); + scContainer.put(ServiceContextDefaults.makeSendingContextServiceContext(orb.getFVDCodeBaseIOR())); + + data.put(CASE.SERVER_INITIAL, scContainer); + + //SERVER_SUBSEQUENT + scContainer = ServiceContextDefaults.makeServiceContexts(orb); + scContainer.put(ServiceContextDefaults.getORBVersionServiceContext()); + + data.put(CASE.SERVER_SUBSEQUENT, scContainer); + + } + + return (data.get(c)).copy(); + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/UEInfoServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/UEInfoServiceContext.java new file mode 100644 index 000000000..bf178e3de --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/UEInfoServiceContext.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; + +public interface UEInfoServiceContext extends ServiceContext +{ + int SERVICE_CONTEXT_ID = 9 ; + + Throwable getUE() ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/UnknownServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/UnknownServiceContext.java new file mode 100644 index 000000000..23c4f4330 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/servicecontext/UnknownServiceContext.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.servicecontext; + +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.servicecontext.ServiceContext ; + +public interface UnknownServiceContext extends ServiceContext +{ + public byte[] getData() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Cdr.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Cdr.java new file mode 100644 index 000000000..ab3f540df --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Cdr.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup({ CdrRead.class, CdrWrite.class }) +public @interface Cdr { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/CdrRead.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/CdrRead.java new file mode 100644 index 000000000..63fde185d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/CdrRead.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR unmarshaling + * implementation in the ORB. + */ +@MethodMonitorGroup +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface CdrRead { +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/CdrWrite.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/CdrWrite.java new file mode 100644 index 000000000..718c121c4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/CdrWrite.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR unmarshaling + * implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface CdrWrite { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/DynamicType.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/DynamicType.java new file mode 100644 index 000000000..95aeb51b6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/DynamicType.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its traced methods are classified as part of the + * TypeCode/Any implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface DynamicType { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Folb.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Folb.java new file mode 100644 index 000000000..bafd2c461 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Folb.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Folb { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Giop.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Giop.java new file mode 100644 index 000000000..e7b0e516e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Giop.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Giop { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/IsLocal.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/IsLocal.java new file mode 100644 index 000000000..b2eaf182e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/IsLocal.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the code that determines whether + * or not an invocation is a local invocation. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface IsLocal { +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/MonitorRead.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/MonitorRead.java new file mode 100644 index 000000000..8661a724a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/MonitorRead.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class to indicate + * that its methods are classified as methods used to read primitive values. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface MonitorRead { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/MonitorWrite.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/MonitorWrite.java new file mode 100644 index 000000000..0dd21475e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/MonitorWrite.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class to indicate + * that its methods are classified as methods used to write primitive values. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface MonitorWrite { +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Naming.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Naming.java new file mode 100644 index 000000000..d405a4db8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Naming.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Naming { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/OrbLifeCycle.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/OrbLifeCycle.java new file mode 100644 index 000000000..978978e35 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/OrbLifeCycle.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface OrbLifeCycle { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Orbd.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Orbd.java new file mode 100644 index 000000000..2e348d2c5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Orbd.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Orbd { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Osgi.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Osgi.java new file mode 100644 index 000000000..4a8511e3a --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Osgi.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Osgi { +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Poa.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Poa.java new file mode 100644 index 000000000..39c705e04 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Poa.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Poa { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PoaFSM.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PoaFSM.java new file mode 100644 index 000000000..93c1d82b8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PoaFSM.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface PoaFSM { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PrimitiveRead.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PrimitiveRead.java new file mode 100644 index 000000000..81414eb3d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PrimitiveRead.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class to indicate + * that its methods are classified as methods used to read primitive values. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface PrimitiveRead { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PrimitiveWrite.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PrimitiveWrite.java new file mode 100644 index 000000000..e12862768 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/PrimitiveWrite.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class to indicate + * that its methods are classified as methods used to write primitive values. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface PrimitiveWrite { +} + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Shutdown.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Shutdown.java new file mode 100644 index 000000000..7a99c0eae --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Shutdown.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Shutdown { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/StreamFormatVersion.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/StreamFormatVersion.java new file mode 100644 index 000000000..0adc446dc --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/StreamFormatVersion.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface StreamFormatVersion { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Subcontract.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Subcontract.java new file mode 100644 index 000000000..cceb40e0d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Subcontract.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Subcontract { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceInterceptor.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceInterceptor.java new file mode 100644 index 000000000..9f1fa753e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceInterceptor.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface TraceInterceptor { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceServiceContext.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceServiceContext.java new file mode 100644 index 000000000..c5f56a2af --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceServiceContext.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface TraceServiceContext { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceValueHandler.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceValueHandler.java new file mode 100644 index 000000000..783dc22c5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TraceValueHandler.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the ValueHandler implementation + * in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup({ ValueHandlerRead.class, ValueHandlerWrite.class }) +public @interface TraceValueHandler { +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TransientObjectManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TransientObjectManager.java new file mode 100644 index 000000000..0539e562f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/TransientObjectManager.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface TransientObjectManager { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Transport.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Transport.java new file mode 100644 index 000000000..4c2f5b4ca --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/Transport.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the CDR implementation in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface Transport { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/ValueHandlerRead.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/ValueHandlerRead.java new file mode 100644 index 000000000..61b20cd00 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/ValueHandlerRead.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the ValueHandler implementation + * that is used for reading value types in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface ValueHandlerRead { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/trace/ValueHandlerWrite.java b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/ValueHandlerWrite.java new file mode 100644 index 000000000..1856d8c63 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/trace/ValueHandlerWrite.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.trace ; + +import java.lang.annotation.Target ; +import java.lang.annotation.ElementType ; +import java.lang.annotation.Retention ; +import java.lang.annotation.RetentionPolicy ; +import org.glassfish.pfl.tf.spi.annotation.MethodMonitorGroup; + +/** This annotation is applied to a class or interface to indicate + * that its methods are classified as part of the ValueHandler implementation + * that is used for writing value types in the ORB. + */ +@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@MethodMonitorGroup +public @interface ValueHandlerWrite { +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Acceptor.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Acceptor.java new file mode 100644 index 000000000..6798f512e --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Acceptor.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.ior.IORTemplate; + +// REVISIT - impl/poa specific: +import com.sun.corba.ee.impl.oa.poa.Policies; +import com.sun.corba.ee.spi.orb.ORB; +import java.net.ServerSocket; +import java.net.Socket; + +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.Description ; + +/** + * @author Harold Carr + */ +@ManagedObject +@Description( "An Acceptor represents an endpoint on which the ORB handles incoming connections" ) +public abstract interface Acceptor +{ + @ManagedAttribute + @Description( "The TCP port of this Acceptor" ) + int getPort() ; + + @ManagedAttribute + @Description( "The name of the IP interface for this Acceptor" ) + String getInterfaceName() ; + + @ManagedAttribute + @Description( "The type of requests that this Acceptor handles" ) + String getType() ; + + @ManagedAttribute + @Description( "True if this acceptor is used to lazily start the ORB" ) + boolean isLazy() ; + + void addToIORTemplate(IORTemplate iorTemplate, Policies policies, + String codebase); + String getMonitoringName(); + + /** + * Used to initialize an Acceptor. + * + * For example, initialization may mean to create a + * {@link java.nio.channels.ServerSocketChannel ServerSocketChannel}. + * + * Note: this must be prepared to be be called multiple times. + * + * @return true when it performs initializatin + * actions (typically the first call. + */ + boolean initialize(); + + /** + * Used to determine if an Acceptor has been initialized. + * + * @return trueAcceptor has been + * initialized. + */ + boolean initialized(); + + String getConnectionCacheType(); + + void setConnectionCache(InboundConnectionCache connectionCache); + + InboundConnectionCache getConnectionCache(); + + /** + * Used to determine if the Acceptor should register + * with a Selector to handle accept events. + * + * For example, this may be false in the case of Solaris Doors + * which do not actively listen. + * + * @return true if the Acceptor should be + * registered with a Selector. + */ + boolean shouldRegisterAcceptEvent(); + + /** Blocks until a new Socket is available on the acceptor's port. + */ + Socket getAcceptedSocket() ; + + /** Handle a newly accepted Socket. + */ + void processSocket( Socket channel ) ; + + /** + * Close the Acceptor. + */ + void close(); + + EventHandler getEventHandler(); + + CDROutputObject createOutputObject(ORB broker, MessageMediator messageMediator); + + ServerSocket getServerSocket(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ByteBufferPool.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ByteBufferPool.java new file mode 100644 index 000000000..d4e0f8962 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ByteBufferPool.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.nio.ByteBuffer; + +/** + * @author Charlie Hunt + */ +public interface ByteBufferPool +{ + public ByteBuffer getByteBuffer(int theSize); + public void releaseByteBuffer(ByteBuffer thebb); + public int activeCount(); + /** + * Return a new ByteBuffer of at least minimumSize + * and copy any bytes in the oldByteBuffer starting at + * oldByteBuffer.position() up to oldByteBuffer.limit() + * into the returned ByteBuffer. + */ + public ByteBuffer reAllocate(ByteBuffer oldByteBuffer, int minimumSize); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Connection.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Connection.java new file mode 100644 index 000000000..29e5642aa --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Connection.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.Queue; + +import org.omg.CORBA.SystemException; + +import com.sun.org.omg.SendingContext.CodeBase; + + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.RequestId; + +import com.sun.corba.ee.impl.encoding.CodeSetComponentInfo; +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; + +/** + * @author Harold Carr + */ +public interface Connection + extends + com.sun.corba.ee.spi.legacy.connection.Connection +{ + /** + * Used to determine if the Connection should register + * with the CorbaTransportManager Selector + * to handle read events. + * + * For example, an HTTP transport would not register since the requesting + * thread would just block on read when waiting for the reply. + * + * @return true if it should be registered. + */ + public boolean shouldRegisterReadEvent(); + + /** + * Used to determine if the Connection should register + * with the + * CorbaTransportManager Selector + * to handle read events. + * + * For example, an HTTP transport would not register since the requesting + * thread would just block on read when waiting for the reply. + * + * @return true if it should be registered. + */ + public boolean shouldRegisterServerReadEvent(); // REVISIT - why special? + + /** + * Called to read incoming messages. + * + * @return true if the thread calling read can be released. + */ + public boolean read(); + + public void close(); + + // REVISIT: replace next two with PlugInFactory (implemented by ContactInfo + // and Acceptor). + + public Acceptor getAcceptor(); + + public ContactInfo getContactInfo(); + + public EventHandler getEventHandler(); + + /** + * Indicates whether a CorbaContactInfo or CorbaAcceptor + * created the + * Connection. + * + * @return true if a CorbaAcceptor + * created the Connection. + */ + public boolean isServer(); + + /** + * Indicates if the Connection is closed. + * + * @return true if the Connection is closed. + */ + public boolean isClosed(); + + /** + * Indicates if the Connection is in the process of + * sending or receiving a message. + * + * @return true if the Connection is busy. + */ + public boolean isBusy(); + + /** + * Timestamps are used for connection management, in particular, for + * reclaiming idle Connections. + * + * @return the "time" the Connection was last used. + */ + public long getTimeStamp(); + + /** + * Timestamps are used for connection management, in particular, for + * reclaiming idle Connections. + * + * @param time - the "time" the Connection was last used. + */ + public void setTimeStamp(long time); + + /** + * The "state" of the Connection. + * + * param state + */ + public void setState(String state); + + /** + * Grab a write lock on the Connection. + * + * If another thread already has a write lock then the calling + * thread will block until the lock is released. The calling + * thread must call + * {@link #writeUnlock} + * when it is done. + */ + public void writeLock(); + + /** + * Release a write lock on the Connection. + */ + public void writeUnlock(); + + /* + * Send the data encoded in + * {@link com.sun.corba.ee.impl.encoding.CDROutputObject CDROutputObject} + * on the Connection. + * + * @param outputObject + */ + public void sendWithoutLock(CDROutputObject outputObject); + + /** + * Register an invocation's CorbaMessageMediator + * with the Connection. + * + * This is useful in protocols which support fragmentation. + * + * @param messageMediator + */ + public void registerWaiter(MessageMediator messageMediator); + + /** + * If a message expect's a response then this method is called. + * + * This method might block on a read (e.g., HTTP), put the calling + * thread to sleep while another thread read's the response (e.g., GIOP), + * or it may use the calling thread to perform the server-side work + * (e.g., Solaris Doors). + * + * @param messageMediator + */ + public CDRInputObject waitForResponse(MessageMediator messageMediator); + + /** + * Unregister an invocation's * CorbaMessageMediator + * with the Connection. + * + * @param messageMediator + */ + public void unregisterWaiter(MessageMediator messageMediator); + + public void setConnectionCache(ConnectionCache connectionCache); + + public ConnectionCache getConnectionCache(); + public boolean hasSocketChannel(); + + public void write(ByteBuffer byteBuffer) + throws IOException; + + public int getNextRequestId(); + public ORB getBroker(); + public CodeSetComponentInfo.CodeSetContext getCodeSetContext(); + public void setCodeSetContext(CodeSetComponentInfo.CodeSetContext csc); + + // Facade to ResponseWaitingRoom. + public MessageMediator clientRequestMapGet(int requestId); + + public void clientReply_1_1_Put(MessageMediator x); + public MessageMediator clientReply_1_1_Get(); + public void clientReply_1_1_Remove(); + + public void serverRequest_1_1_Put(MessageMediator x); + public MessageMediator serverRequest_1_1_Get(); + public void serverRequest_1_1_Remove(); + + public boolean isPostInitialContexts(); + + // Can never be unset... + public void setPostInitialContexts(); + + public void purgeCalls(SystemException systemException, + boolean die, boolean lockHeld); + + // + // Connection status + // + public static final int OPENING = 1; + public static final int ESTABLISHED = 2; + public static final int CLOSE_SENT = 3; + public static final int CLOSE_RECVD = 4; + public static final int ABORT = 5; + + // Begin Code Base methods --------------------------------------- + // + // Set this connection's code base IOR. The IOR comes from the + // SendingContext. This is an optional service context, but all + // JavaSoft ORBs send it. + // + // The set and get methods don't need to be synchronized since the + // first possible get would occur during reading a valuetype, and + // that would be after the set. + + // Sets this connection's code base IOR. This is done after + // getting the IOR out of the SendingContext service context. + // Our ORBs always send this, but it's optional in CORBA. + + void setCodeBaseIOR(IOR ior); + + IOR getCodeBaseIOR(); + + // Get a CodeBase stub to use in unmarshaling. The CachedCodeBase + // won't connect to the remote codebase unless it's necessary. + CodeBase getCodeBase(); + + // End Code Base methods ----------------------------------------- + + public void sendCloseConnection(GIOPVersion giopVersion) + throws IOException; + + public void sendMessageError(GIOPVersion giopVersion) + throws IOException; + + public void sendCancelRequest(GIOPVersion giopVersion, int requestId) + throws + IOException; + + // NOTE: This method can throw a connection rebind SystemException. + public void sendCancelRequestWithLock(GIOPVersion giopVersion, + int requestId) + throws + IOException; + + public ResponseWaitingRoom getResponseWaitingRoom(); + + public void serverRequestMapPut(int requestId, + MessageMediator messageMediator); + public MessageMediator serverRequestMapGet(int requestId); + public void serverRequestMapRemove(int requestId); + + public Queue getFragmentList(RequestId corbaRequestId); + public void removeFragmentList(RequestId corbaRequestId); + + // REVISIT: WRONG: should not expose sockets here. + public SocketChannel getSocketChannel(); + + // REVISIT - CorbaMessageMediator parameter? + public void serverRequestProcessingBegins(); + public void serverRequestProcessingEnds(); + + /** Clean up all connection resources. Used when shutting down an ORB. + */ + public void closeConnectionResources() ; +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ConnectionCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ConnectionCache.java new file mode 100644 index 000000000..8e6e8c676 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ConnectionCache.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import org.glassfish.external.statistics.CountStatistic ; + +/** + * @author Harold Carr + */ +public interface ConnectionCache +{ + public String getMonitoringName(); + + public String getCacheType(); + + public void stampTime(Connection connection); + + public long numberOfConnections(); + + public long numberOfIdleConnections(); + + public long numberOfBusyConnections(); + + public boolean reclaim(); + + /** Close all connections in the connection cache. + * This is used as a final cleanup, and will result + * in abrupt termination of any pending communications. + */ + public void close() ; +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfo.java new file mode 100644 index 000000000..3900e4bf2 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfo.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import com.sun.corba.ee.spi.protocol.ClientRequestDispatcher; +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.protocol.MessageMediator; + +/** + * @author Harold Carr + */ +public abstract interface ContactInfo extends SocketInfo +{ + public ContactInfoList getContactInfoList() ; + public IOR getTargetIOR(); + public IOR getEffectiveTargetIOR(); + public IIOPProfile getEffectiveProfile(); // REVISIT - type + public void setAddressingDisposition(short addressingDisposition); + public short getAddressingDisposition(); + public String getMonitoringName(); + + public ORB getBroker(); + + public ClientRequestDispatcher getClientRequestDispatcher(); + + /** + * Used to determine if a CorbaConnection + * will be present in an invocation. + * + * For example, it may be + * false in the case of shared-memory + * Input/OutputObjects. + * + * @return true if a CorbaConnection + * will be used for an invocation. + */ + public boolean isConnectionBased(); + + /** + * Used to determine if the CorbaConnection + * used for a request should be cached. + * + * If true then the ORB will attempt to reuse an existing + * CorbaConnection. If + * one is not found it will create a new one and cache it for future use. + * + * + * @return true if a CorbaConnection + * created by this ContactInfo should be cached. + */ + public boolean shouldCacheConnection(); + + public String getConnectionCacheType(); + + public void setConnectionCache(OutboundConnectionCache connectionCache); + + public OutboundConnectionCache getConnectionCache(); + + public Connection createConnection(); + + public MessageMediator createMessageMediator(ORB broker, + ContactInfo contactInfo, Connection connection, + String methodName, boolean isOneWay); + + public CDROutputObject createOutputObject(MessageMediator messageMediator); + + /** + * Used to lookup artifacts associated with this ContactInfo. + * + * @return the hash value. + */ + public int hashCode(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoList.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoList.java new file mode 100644 index 000000000..3b212378c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoList.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.util.Iterator ; + +import com.sun.corba.ee.spi.ior.IOR ; + +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher ; + + +/** + * @author Harold Carr + */ +public abstract interface ContactInfoList +{ + public Iterator iterator() ; // covariant override + public void setTargetIOR(IOR ior); + public IOR getTargetIOR(); + + public void setEffectiveTargetIOR(IOR locatedIor); + public IOR getEffectiveTargetIOR(); + + public LocalClientRequestDispatcher getLocalClientRequestDispatcher(); + + public int hashCode(); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoListFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoListFactory.java new file mode 100644 index 000000000..8c25c1e35 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoListFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport ; + + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.orb.ORB; + +/** Interface used to create a ContactInfoList from an IOR, as required + * for supporting CORBA semantics using the DCS framework. This is a + * natural correspondence since an IOR contains the information for + * contacting one or more communication endpoints that can be used to + * invoke a method on an object, along with the necessary information + * on particular transports, encodings, and protocols to use. + * Note that the actual implementation may support more than one + * IOR in the case of GIOP with Location Forward messages. + */ +public interface ContactInfoListFactory { + /** + * This will be called after the no-arg constructor before + * create is called. + */ + public void setORB(ORB orb); + + public ContactInfoList create( IOR ior ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoListIterator.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoListIterator.java new file mode 100644 index 000000000..9b76d7b8c --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ContactInfoListIterator.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport ; + + +import com.sun.corba.ee.spi.ior.IOR; +import java.util.Iterator; + +public abstract interface ContactInfoListIterator + extends Iterator { + + public void reportAddrDispositionRetry(ContactInfo contactInfo, + short disposition); + + public void reportRedirect(ContactInfo contactInfo, + IOR forwardedIOR); + + public ContactInfoList getContactInfoList(); + + public void reportSuccess(ContactInfo contactInfo); + + public boolean reportException(ContactInfo contactInfo, RuntimeException exception); + + public RuntimeException getFailureException(); + +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/EventHandler.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/EventHandler.java new file mode 100644 index 000000000..c0d6320f5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/EventHandler.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; + +import com.sun.corba.ee.spi.threadpool.Work; + +/** + * @author Harold Carr + * + * This should only be registered with ONE selector. + */ +public interface EventHandler +{ + public void setUseSelectThreadToWait(boolean x); + public boolean shouldUseSelectThreadToWait(); + + public SelectableChannel getChannel(); + + public int getInterestOps(); + + public void setSelectionKey(SelectionKey selectionKey); + public SelectionKey getSelectionKey(); + + public void handleEvent(); + + // NOTE: if there is more than one interest op this does not + // allow discrimination between different ops and how threading + // is handled. + public void setUseWorkerThreadForEvent(boolean x); + public boolean shouldUseWorkerThreadForEvent(); + + public void setWork(Work work); + public Work getWork(); + + // REVISIT: need base class with two derived. + public Acceptor getAcceptor(); + public Connection getConnection(); + +} + +// End of file. + + + + + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IIOPPrimaryToContactInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IIOPPrimaryToContactInfo.java new file mode 100644 index 000000000..7ea5c7657 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IIOPPrimaryToContactInfo.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.util.List; + +import com.sun.corba.ee.spi.transport.ContactInfo; + +/** + * This interface is the "sticky manager" for IIOP failover. The default + * ORB does NOT contain a sticky manager. One is registered by supplying + * a class via the com.sun.corba.ee.transport.ORBIIOPPrimaryToContactInfoClass. + * + * It uses the IIOP primary host/port (with a SocketInfo.IIOP_CLEAR_TEXT type) + * as a key to map to the last ContactInfo that resulted in successful' + * communication. + * + * It mainly prevents "fallback" - if a previously failed replica comes + * back up we do NOT want to switch back to using it - particularly in the + * case of statefull session beans. + * + * Note: This assumes static lists of replicas (e.g., AS 8.1 EE). + * This does NOT work well with LOCATION_FORWARD. + * + * @author Harold Carr + */ +public interface IIOPPrimaryToContactInfo +{ + /** + * @param primary - clear any state relating to primary. + */ + public void reset(ContactInfo primary); + + /** + * @param primary - the key. + * @param previous - if null return true. Otherwise, find previous in + * contactInfos and if another ContactInfo + * follows it in the list then return true. Otherwise false. + * @param contactInfos - the list of replicas associated with the + * primary. + */ + public boolean hasNext(ContactInfo primary, + ContactInfo previous, + List contactInfos); + + /** + * @param primary - the key. + * @param previous - if null then map primary to failover. If failover is + * empty then map primary to first ContactInfo in contactInfos and mapped entry. + * If failover is + * non-empty then return failover. If previous is non-null that + * indicates that the previous failed. Therefore, find previous in + * contactInfos. Map the ContactInfo following + * previous to primary and return that ContactInfo. + */ + public ContactInfo next(ContactInfo primary, + ContactInfo previous, + List contactInfos); + +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IORToSocketInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IORToSocketInfo.java new file mode 100644 index 000000000..08421924f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IORToSocketInfo.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.util.List; + +import com.sun.corba.ee.spi.ior.IOR; + +public interface IORToSocketInfo +{ + /** Used to extract socket address information from an IOR. + * @param ior The ior from which the socket info is extracted. + * @param previous The previous list, which may be reused if not null. + * @return a list of SocketInfo. + */ + public List getSocketInfo(IOR ior, + List previous); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IORTransformer.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IORTransformer.java new file mode 100644 index 000000000..61121a109 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/IORTransformer.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.impl.encoding.CDRInputObject ; +import com.sun.corba.ee.impl.encoding.CDROutputObject ; + +/** Interface that provides operations to transorm an IOR + * between its programmatic representation and a representation + * in an Input or Output object. + */ +public interface IORTransformer { + IOR unmarshal( CDRInputObject io ) ; + + void marshal( CDROutputObject oo, IOR ior ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/InboundConnectionCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/InboundConnectionCache.java new file mode 100644 index 000000000..7b95a5778 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/InboundConnectionCache.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + + +/** + * @author Harold Carr + */ +public interface InboundConnectionCache extends ConnectionCache +{ + public Connection get(Acceptor acceptor); // REVISIT + + public void put(Acceptor acceptor, Connection connection); + + public void remove( Connection connection ) ; +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ListenerThread.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ListenerThread.java new file mode 100644 index 000000000..3017bed96 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ListenerThread.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +/** + * @author Harold Carr + */ +public interface ListenerThread +{ + public Acceptor getAcceptor(); + public void close(); +} + +// End of file. + + + + + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/MessageData.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/MessageData.java new file mode 100644 index 000000000..92b45cf2d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/MessageData.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message ; +import com.sun.corba.ee.impl.encoding.CDRInputObject; + +public interface MessageData { + /** An array of GIOP messages. The messages will + * satisfy: + *

                  + *
                1. If there is more than one message, the first message is + * a request or a reply. + *
                2. If there is more than one message, all messages after the first + * will be fragment messages. + *
                3. If there is more than one message, all messages will share the + * same request ID (for GIOP 1.2). + *
                4. The more fragments bit will be set on all messages except the + * last message. + *
                + */ + Message[] getMessages() ; + + /** A fully initialized input stream for the message data, positioned + * at the first element of the body. + */ + CDRInputObject getStream() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/MessageTraceManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/MessageTraceManager.java new file mode 100644 index 000000000..68221b7ad --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/MessageTraceManager.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.nio.ByteBuffer; + +/** Interface that supports capturing the GIOP messages for the + * last non-co-located invocation in the current thread. + * This enables easy capture of the GIOP messages for testing + * purposes. + */ +public interface MessageTraceManager { + /** Discard all messages accumulated since the last call to + * clear. + */ + void clear() ; + + /** Returns true if messages are to be captured on this thread, otherwise + * false. + */ + boolean isEnabled() ; + + /** Called with flag=true to enable capture of messages. + */ + void enable( boolean flag ) ; + + /** Return an array of messages (represented as byte[]) for the + * message(s) sent on this thread since the last call to clear(). + * If there is a Location Forward in this invocation, the + * the data returned will include all requests sent starting + * with the first request. + */ + byte[][] getDataSent() ; + + /** Return an array of messages (represented as byte[]) for the + * message(s) received since the last call to clear(). + */ + byte[][] getDataReceived() ; + + void recordDataSent(ByteBuffer message); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ORBSocketFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ORBSocketFactory.java new file mode 100644 index 000000000..c3e8586d8 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ORBSocketFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; +import java.net.ServerSocket; + +import com.sun.corba.ee.spi.orb.ORB; + +/** + * @author Harold Carr + */ +public interface ORBSocketFactory +{ + public void setORB(ORB orb); + + public ServerSocket createServerSocket(String type, + InetSocketAddress inetSocketAddress) + throws IOException; + + public Socket createSocket(String type, + InetSocketAddress inetSocketAddress) + throws IOException; + + public void setAcceptedSocketOptions(Acceptor acceptor, + ServerSocket serverSocket, + Socket socket) + throws SocketException; + +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/OutboundConnectionCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/OutboundConnectionCache.java new file mode 100644 index 000000000..8f04b69e3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/OutboundConnectionCache.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + + +/** + * @author Harold Carr + */ +public interface OutboundConnectionCache extends ConnectionCache +{ + public Connection get(ContactInfo contactInfo); + + public void put(ContactInfo contactInfo, Connection connection); + + public void remove( ContactInfo contactInfo ) ; +} + +// End of file. + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ReaderThread.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ReaderThread.java new file mode 100644 index 000000000..6ec5130f6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ReaderThread.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +/** + * @author Harold Carr + */ +public interface ReaderThread { + public Connection getConnection(); + public void close(); +} + +// End of file. + + + + + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ResponseWaitingRoom.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ResponseWaitingRoom.java new file mode 100644 index 000000000..1938fcac9 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/ResponseWaitingRoom.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import org.omg.CORBA.SystemException; + +/** + * @author Harold Carr + */ +public interface ResponseWaitingRoom{ + public void registerWaiter(MessageMediator messageMediator); + + // REVISIT: maybe return void (or MessageMediator). + public CDRInputObject waitForResponse(MessageMediator messageMediator); + + public void responseReceived(CDRInputObject inputObject); + + public void unregisterWaiter(MessageMediator messageMediator); + + public int numberRegistered(); + + public void signalExceptionToAllWaiters(SystemException systemException); + + public MessageMediator getMessageMediator(int requestId); +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Selector.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Selector.java new file mode 100644 index 000000000..6a35dc98f --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/Selector.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +/** + * @author Harold Carr + */ +public interface Selector +{ + public void setTimeout(long timeout); + public long getTimeout(); + public void registerInterestOps(EventHandler eventHandler); + public void registerForEvent(EventHandler eventHander); + public void unregisterForEvent(EventHandler eventHandler); + public void close(); +} + +// End of file. + + + + + + + + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/SocketInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/SocketInfo.java new file mode 100644 index 000000000..770d40c8d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/SocketInfo.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +public interface SocketInfo +{ + // Endpoint types known in advance. + // If you change the value of this constant then update + // activation.idl accordingly. It has a duplicate definition + // to avoid a compilation dependency. + + String IIOP_CLEAR_TEXT = "IIOP_CLEAR_TEXT"; + String SSL_PREFIX = "SSL" ; + + String getType(); + + String getHost(); + + int getPort(); +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TcpTimeouts.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TcpTimeouts.java new file mode 100644 index 000000000..ae1aa0089 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TcpTimeouts.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import com.sun.corba.ee.impl.transport.TcpTimeoutsImpl ; + +/** This interface defines the ability to wait for a configurable time, + * applying an exponential backoff to increase the time. The maximum + * single wait time can be bounded, as well as the maximum total wait time. + */ +public interface TcpTimeouts { + /** Return the initial time to wait on the first getTime or sleepTime + * call on a new Waiter instance. + */ + int get_initial_time_to_wait(); + + /** Get the maximum total time a Waiter can exist before isExpired returns + * true. -1 if not used for this TcpTimeouts instances. + */ + int get_max_time_to_wait(); + + /** Get the maximum time a single sleepTime or getTime can taoke or return + * in an instance of Waiter. -1 if not used. + */ + int get_max_single_wait_time() ; + + /** Return the backoff factor, which is the percentage multiplier used + * to compute the next timeout in the Waiter.advance method. + */ + int get_backoff_factor(); + + /** Interface used to represent a series of timeout values using + * exponential backoff. Supports both a maximum total wait time + * and a maximum single wait time. + *

                + * The total wait time starts at + * 0 and is incremented by each call to getTimeForSleep or sleepTime. + * Once the total wait time exceeds the maximum total wait time, + * isExpired returns true. + *

                + * The timer also has a current wait time, which is returned by getTime + * and is the interval for which sleep waits. The initial value + * of the current wait time is get_initial_time_to_wait(). + * Each subsequent call to advance increases the current wait time by + * a factor of (previous*get_backoff_factor())/100, unless + * get_max_single_wait_time is configured and + * the current wait time exceeds get_max_single_wait_time(). + * If get_max_single_wait_time() is not used, the current time + * increases without bound (until it overflows). Once + * get_max_single_wait_time() is reached, + * every subsequent call to next() returnes get_max_single_wait_time(), + * and advance has no effect. + */ + public interface Waiter { + /** Advance to the next timeout value. + */ + void advance() ; + + /** Set the current timeout back to the initial + * value. Accumulated time is not affected. + */ + void reset() ; + + /** Return the current timeout value. + * Also increments total time. + */ + int getTimeForSleep() ; + + /** Return the current timeout value, + * but do not increment total wait time. + */ + int getTime() ; + + /** Return the accumulated wait time. + */ + int timeWaiting() ; + + /** Sleep for the current timeout value. + * Returns true if sleep happened, otherwise false, + * in the case where the Waiter has expired. + */ + boolean sleepTime() ; + + /** Returns true if the waiter has expired. It expires + * once the total wait time exceeds get_max_wait_time. + */ + boolean isExpired() ; + } + + /** Return a Waiter that can be used for computing a series + * of timeouts. + */ + Waiter waiter() ; + + /** Factory used to create TcpTimeouts instances. + */ + public interface Factory { + /** Create TcpTimeouts assuming that max_single_wait is + * unbounded. + */ + TcpTimeouts create( int initial_time_to_wait, + int max_time_to_wait, int backoff_value ) ; + + /** Create TcpTimeouts using all configuration parameters, + * including a bound on the maximum single wait time. + */ + TcpTimeouts create( int initial_time_to_wait, + int max_time_to_wait, int backoff_value, int max_single_wait ) ; + + /** Create TcpTimeouts from a configuration string. args must + * be a : separated string, with 3 or 4 args, all of which are + * positive decimal integers. The integers are in the same + * order as the arguments to the other create methods. + */ + TcpTimeouts create( String args ) ; + } + + Factory factory = new Factory() { + public TcpTimeouts create( int initial_time_to_wait, + int max_time_to_wait, int backoff_value ) { + + return new TcpTimeoutsImpl( initial_time_to_wait, + max_time_to_wait, backoff_value ) ; + } + + public TcpTimeouts create( int initial_time_to_wait, + int max_time_to_wait, int backoff_value, int max_single_wait ) { + + return new TcpTimeoutsImpl( initial_time_to_wait, + max_time_to_wait, backoff_value, max_single_wait ) ; + } + + public TcpTimeouts create( String args ) { + return new TcpTimeoutsImpl( args ) ; + } + } ; +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TemporarySelectorState.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TemporarySelectorState.java new file mode 100644 index 000000000..d2b6a8500 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TemporarySelectorState.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; + +/** + * + * @author Charlie Hunt + */ + +/** + * + * An interface which models the state and transitions of a temporary Selector. + * + */ +public interface TemporarySelectorState { + /** + * Selects a set of keys whose corresponding SelectableChannel is ready for + * I/O operations. + * + *

                This method performs a blocking selection + * operation on theSelector. It returns only after the + * SelectableChannel is selected, theSelector's wakeup + * method is invoked, the current thread is interrupted, or the given + * timeout period expires, whichever comes first. + * + *

                This method does not offer real-time guarantees: It schedules + * theTimeout as if by invoking the {@link Object#wait(long)} method.

                + * + * @param theTimeout If positive, block for up to theTimeout + * milliseconds, more or less, while waiting for a + * SelectableChannel to become ready; must be greater + * than 0 in value + * + * @throws IOException + * If an I/O error occurs + * + * @throws ClosedSelectorException + * If this theSelector is closed + * + * @throws IllegalArgumentException + * If the value of the theTimeout argument is not greater than 0 + * + * @return The number of keys, possibly zero, whose ready-operation sets + * was updated. + */ + public int select(Selector theSelector, long theTimeout) throws IOException; + + /** + * Registers theSelectableChannel with theSelector, setting theSelection to + * the key returned by the registeration. + * + * @param theSelector + * The selector with which this channel is to be registered + * + * @param theSelectableChannel + * The SelectableChannel to register theSelector with. + * + * @param theOps + * The interest set for the resulting key + * + * @throws ClosedChannelException + * If theSelectableChannel is closed + * + * @throws IllegalBlockingModeException + * If theSelectableChannel is in blocking mode + * + * @throws IllegalSelectorException + * If thSelectableChannel was not created by the same provider + * as theSelector + * + * @throws CancelledKeyException + * If theSelectableChannel is currently registered with theSelector + * but the corresponding key has already been cancelled + * + * @throws IllegalArgumentException + * If a bit in theOps does not correspond to an operation + * that is supported by theSelectableChannel, that is, if set & + * ~theSeletableChannel.validOps() != 0 + * + * @return A key representing the registration of theSelectableChannel with + * theSelector. + */ + public SelectionKey registerChannel(Selector theSelector, + SelectableChannel theSelectableChannel, + int theOps) throws IOException; + + /** + * Requests that the registration of a SelectableChannel with theSelector, + * theSelectionKey be cancelled and flushed from theSelector. Upon return + * theSelectionKey will be invalid and will have been flushed from + * theSelector's key sets. + * + *

                If theSelectionKey has already been cancelled and it has been flushed + * from theSelector, then invoking this method has no effect. Once + * theSelectionKey is cancelled and flushed, theSelectionKey remains forever + * invalid.

                + * + *

                This method may be invoked at any time. It synchronizes on the + * theSelector's cancelled-key set, and therefore may block briefly if + * invoked concurrently with a cancellation or selection operation + * involving the same selector.

                + * + * @param theSelector + * The selector with which this channel is to be registered + * + * @param theSelectionKey + * A key representing the registration of theSelectableChannel with + * theSelector + * + * @return TemporarySelectorState, the state of the TemporarySelector after + * invoking this method. + */ + public TemporarySelectorState cancelKeyAndFlushSelector(Selector theSelector, + SelectionKey theSelectionKey) + throws IOException; + + /** + * Closes theSelector. + * + *

                If a thread is currently blocked in one of theSelector's selection + * methods then it is interrupted as if by invoking theSelector's + * wakeup method. + * + *

                Any uncancelled keys still associated with theSelector are + * invalidated, their SelectableChannels are deregistered, and any other + * resources associated with this selector are released. + * + *

                If theSelector is already closed then invoking this method has no + * effect. + * + *

                After theSelector is closed, any further attempt to use it, except by + * invoking this method, will cause a ClosedSelectorException to be + * thrown.

                + * + * @param theSelector + * The selector with which this channel is to be registered + * @throws IOException + * If an I/O error occurs + * + * @return TemporarySelectorState, the state of the TemporarySelector after + * invoking this method. + */ + public TemporarySelectorState close(Selector theSelector) throws IOException; + + /** + * Remove theSelectionKey from the theSelector's selected key set. + * + * @param theSelector + * The selector whose selected key set should have theSelectionKey + * removed. + * + * @param theSelectionKey + * A key representing the registration of theSelectableChannel with + * theSelector and the key should be removed key removed from the + * selected key set. + * + * @return TemporarySelectorState, the state of the TemporarySelector after + * invoking this method. + * + * @throws IOException + * If this selector is closed + */ + public TemporarySelectorState removeSelectedKey(Selector theSelector, + SelectionKey theSelectionKey) + throws IOException; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TransportDefault.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TransportDefault.java new file mode 100644 index 000000000..2bd798310 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TransportDefault.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport ; + +import com.sun.corba.ee.spi.protocol.ClientDelegate ; +import com.sun.corba.ee.spi.protocol.ClientDelegateFactory ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.ior.IOR ; + +// Internal imports, not used in the interface to this package +import com.sun.corba.ee.impl.protocol.ClientDelegateImpl ; +import com.sun.corba.ee.impl.transport.AcceptorAcceptOnlyImpl; +import com.sun.corba.ee.impl.transport.ContactInfoListImpl; +import com.sun.corba.ee.impl.transport.AcceptorImpl ; +import com.sun.corba.ee.impl.transport.AcceptorLazyImpl ; +import java.net.Socket; +import org.glassfish.pfl.basic.func.UnaryVoidFunction; + +/** This class provices standard building blocks for the ORB, as do all Default classes + * in the various packages. + */ +public abstract class TransportDefault { + private TransportDefault() {} + + public static ContactInfoListFactory makeCorbaContactInfoListFactory( + final ORB broker ) + { + return new ContactInfoListFactory() { + public void setORB(ORB orb) { } + public ContactInfoList create( IOR ior ) { + return new ContactInfoListImpl( + (com.sun.corba.ee.spi.orb.ORB)broker, ior ) ; + } + }; + } + + public static ClientDelegateFactory makeClientDelegateFactory( + final ORB broker ) + { + return new ClientDelegateFactory() { + public ClientDelegate create( ContactInfoList info ) { + return new ClientDelegateImpl( + (com.sun.corba.ee.spi.orb.ORB)broker, info ) ; + } + }; + } + + public static IORTransformer makeIORTransformer( + final ORB broker ) + { + return null ; + } + + public static Acceptor makeStandardCorbaAcceptor( + ORB orb, int port, String name, String type ) { + + return new AcceptorImpl( orb, port, name, type ) ; + } + + public static Acceptor makeLazyCorbaAcceptor( + ORB orb, int port, String name, String type ) { + + return new AcceptorLazyImpl( orb, port, name, type ) ; + } + + public static Acceptor makeAcceptOnlyCorbaAcceptor( + ORB orb, int port, String name, String type, + UnaryVoidFunction operation ) { + + return new AcceptorAcceptOnlyImpl( orb, port, name, type, + operation ) ; + } +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TransportManager.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TransportManager.java new file mode 100644 index 000000000..799eaca52 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/TransportManager.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport; + +import java.util.Collection; + +import com.sun.corba.ee.spi.ior.IORTemplate; +import com.sun.corba.ee.spi.ior.ObjectAdapterId; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message ; +// +// REVISIT - impl/poa specific: +import com.sun.corba.ee.impl.oa.poa.Policies; + +import com.sun.corba.ee.spi.orb.ORB; +import org.glassfish.gmbal.Description ; +import org.glassfish.gmbal.ManagedAttribute ; +import org.glassfish.gmbal.ManagedObject ; +import org.glassfish.gmbal.AMXMetadata ; + +/** + * @author Harold Carr + */ +@ManagedObject +@Description( "The Transport Manager for the ORB" ) +@AMXMetadata( isSingleton=true ) +public interface TransportManager { + + public ByteBufferPool getByteBufferPool(int id); + + @ManagedAttribute + @Description( "The Selector, which listens for all I/O events" ) + public Selector getSelector(); + + public Selector getSelector(int id); + + public void close(); + + public static final String SOCKET_OR_CHANNEL_CONNECTION_CACHE = + "SocketOrChannelConnectionCache"; + + @ManagedAttribute + @Description( "List of all Acceptors in this ORB" ) + public Collection getAcceptors() ; + + public Collection getAcceptors(String objectAdapterManagerId, + ObjectAdapterId objectAdapterId); + + // REVISIT - POA specific policies + public void addToIORTemplate(IORTemplate iorTemplate, + Policies policies, + String codebase, + String objectAdapterManagerId, + ObjectAdapterId objectAdapterId); + + // Methods for GIOP debugging support + + /** Return a MessageTraceManager for the current thread. + * Each thread that calls getMessageTraceManager gets its own + * independent copy. + */ + MessageTraceManager getMessageTraceManager() ; + + public OutboundConnectionCache getOutboundConnectionCache( + ContactInfo contactInfo); + + @ManagedAttribute + @Description( "Outbound Connection Cache (client initiated connections)" ) + public Collection getOutboundConnectionCaches(); + + public InboundConnectionCache getInboundConnectionCache(Acceptor acceptor); + + // Only used for MBeans + @ManagedAttribute + @Description( "Inbound Connection Cache (server accepted connections)" ) + public Collection getInboundConnectionCaches(); + + public void registerAcceptor(Acceptor acceptor); + + public void unregisterAcceptor(Acceptor acceptor); + +} + +// End of file. diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/concurrent/ConcurrentQueue.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/concurrent/ConcurrentQueue.java new file mode 100644 index 000000000..48d34fe1d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/concurrent/ConcurrentQueue.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.concurrent ; + +/** A class that provides a very simply unbounded queue. + * The main requirement here is that the class support constant time (very fast) + * deletion of arbitrary elements. An instance of this class must be thread safe, + * either by locking or by using a wait-free algorithm (preferred). + * The interface is made as simple is possible to make it easier to produce + * a wait-free implementation. + */ +public interface ConcurrentQueue { + /** A Handle provides the capability to delete an element of a ConcurrentQueue + * very quickly. Typically, the handle is stored in the element, so that an + * element located from another data structure can be quickly deleted from + * a ConcurrentQueue. + */ + public interface Handle { + /** Return the value that corresponds to this handle. + */ + V value() ; + + /** Delete the element corresponding to this handle + * from the queue. Takes constant time. Returns + * true if the removal succeeded, or false if it failed. + * which can occur if another thread has already called + * poll or remove on this element. + */ + boolean remove() ; + + /** Time at which the element will expire + * + * @return time in milliseconds since 1/1/70 when this item expires. + */ + long expiration() ; + } + + /** Return the number of elements in the queue. + */ + int size() ; + + /** Add a new element to the tail of the queue. + * Returns a handle for the element in the queue. + */ + Handle offer( V arg ) ; + + /** Return the handle for the head of the queue. + * The element is removed from the queue. + */ + Handle poll() ; + + /** Return the handle for the head of the queue. + * The element is not removed from the queue. + */ + Handle peek() ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/concurrent/ConcurrentQueueFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/concurrent/ConcurrentQueueFactory.java new file mode 100644 index 000000000..3a1a8dae7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/concurrent/ConcurrentQueueFactory.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.concurrent ; + +import com.sun.corba.ee.impl.transport.concurrent.ConcurrentQueueBlockingImpl ; +import com.sun.corba.ee.impl.transport.concurrent.ConcurrentQueueNonBlockingImpl ; +import com.sun.corba.ee.impl.transport.concurrent.ConcurrentQueueImpl ; + +/** A factory class for creating instances of ConcurrentQueue. + * Note that a rather unusual syntax is needed for calling these methods: + * + * ConcurrentQueueFactory.makeXXXConcurrentQueue() + * + * This is required because the type variable V is not used in the + * parameters of the factory method, so the correct type + * cannot be inferred by the compiler. + */ +public final class ConcurrentQueueFactory { + private ConcurrentQueueFactory() {} + + /** Create a ConcurrentQueue whose implementation never blocks. + * Currently not fully implemented: the NonBlocking and Blocking + * impls are basically the same. + */ + public static ConcurrentQueue makeNonBlockingConcurrentQueue(final long ttl ) { + return new ConcurrentQueueNonBlockingImpl( ttl ) ; + } + + /** Create a ConcurrentQueue whose implementation uses conventional + * locking to protect the data structure. + */ + public static ConcurrentQueue makeBlockingConcurrentQueue(final long ttl ) { + return new ConcurrentQueueBlockingImpl( ttl ) ; + } + + /** Create a ConcurrentQueue that does no locking at all. + * For use in data structures that manage their own locking. + */ + public static ConcurrentQueue makeConcurrentQueue(final long ttl ) { + return new ConcurrentQueueImpl( ttl ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/Connection.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/Connection.java new file mode 100644 index 000000000..12028d8da --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/Connection.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + +import java.io.IOException ; + +/** A Connection represents some kind of channel to a (possibly different) process. + * Here we only need the capability of closing the connection. Any connection + * must also define hashCode and equals properly so that it can be used in a map. + * It is also recommended that toString() be defined to return a useful summary + * of the connection (e.g. address information). + */ +public interface Connection { + void close() throws IOException ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionCache.java new file mode 100644 index 000000000..0878b4ed6 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionCache.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + +/** A connection cache manages a group of connections which may be re-used + * for sending and receiving messages. + */ +public interface ConnectionCache { + /** User-provided indentifier for an instance of the + * OutboundConnectionCache. + */ + String getCacheType() ; + + /** Total number of connections currently managed by the cache. + */ + long numberOfConnections() ; + + /** Number of idle connections; that is, connections for which the number of + * get/release or responseReceived/responseProcessed calls are equal. + */ + long numberOfIdleConnections() ; + + /** Number of non-idle connections. Normally, busy+idle==total, but this + * may not be strictly true due to concurrent updates to the connection + * cache. + */ + long numberOfBusyConnections() ; + + /** Number of idle connections that are reclaimable. Such connections + * are not in use, and are not waiting to handle any responses. + */ + long numberOfReclaimableConnections() ; + + /** Threshold at which connection reclamation begins. + */ + int highWaterMark() ; + + /** Number of connections to reclaim each time reclamation starts. + */ + int numberToReclaim() ; + + /** Close a connection, regardless of its state. This may cause requests + * to fail to be sent, and responses to be lost. Intended for + * handling serious errors, such as loss of framing on a TCP stream, + * that require closing the connection. + */ + void close( final C conn ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionCacheFactory.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionCacheFactory.java new file mode 100644 index 000000000..83e5de799 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionCacheFactory.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + + +import com.sun.corba.ee.impl.transport.connection.OutboundConnectionCacheBlockingImpl ; +import com.sun.corba.ee.impl.transport.connection.OutboundConnectionCacheImpl ; +import com.sun.corba.ee.impl.transport.connection.InboundConnectionCacheBlockingImpl ; +import com.sun.corba.ee.impl.transport.connection.InboundConnectionCacheImpl ; + +/** A factory class for creating connections caches. + * Note that a rather unusual syntax is needed for calling these methods: + * + * ConnectionCacheFactory.makeXXXCache() + * + * This is required because the type variable V is not used in the + * parameters of the factory method (there are no parameters). + */ +public final class ConnectionCacheFactory { + private ConnectionCacheFactory() {} + + public static OutboundConnectionCache + makeBlockingOutboundConnectionCache( String cacheType, int highWaterMark, + int numberToReclaim, int maxParallelConnections, int ttl ) { + + return new OutboundConnectionCacheBlockingImpl( cacheType, highWaterMark, + numberToReclaim, maxParallelConnections, ttl ) ; + } + + public static OutboundConnectionCache + makeNonBlockingOutboundConnectionCache( String cacheType, int highWaterMark, + int numberToReclaim, int maxParallelConnections, int ttl ) { + + return new OutboundConnectionCacheImpl( cacheType, highWaterMark, + numberToReclaim, maxParallelConnections, ttl ) ; + } + + public static InboundConnectionCache + makeBlockingInboundConnectionCache( String cacheType, int highWaterMark, + int numberToReclaim, int ttl ) { + return new InboundConnectionCacheBlockingImpl( cacheType, + highWaterMark, numberToReclaim, ttl ) ; + } + + public static InboundConnectionCache + makeNonBlockingInboundConnectionCache( String cacheType, int highWaterMark, + int numberToReclaim, int ttl ) { + return new InboundConnectionCacheImpl( cacheType, + highWaterMark, numberToReclaim, ttl ) ; + } +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionFinder.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionFinder.java new file mode 100644 index 000000000..bd5b711ab --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ConnectionFinder.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + +import java.util.Collection ; + +import java.io.IOException ; + +/** An instance of a ConnectionFinder may be supplied to the + * OutboundConnectionCache.get method. + */ +public interface ConnectionFinder { + /** Method that searches idleConnections and busyConnections for + * the best connection. May return null if no best connection + * exists. May create a new connection and return it. + */ + C find( ContactInfo cinfo, Collection idleConnections, + Collection busyConnections ) throws IOException ; +} + diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ContactInfo.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ContactInfo.java new file mode 100644 index 000000000..441c14d68 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/ContactInfo.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + +import java.io.IOException ; + +/** The ContactInfo represents the information needed to establish a connection + * to a (possibly different) process. This is a subset of the PEPt 2.0 connection. + * Any implemetnation of this interface must define hashCode and equals properly so that + * it may be used in a Map. + * It is also recommended that toString() be defined to return a useful summary + * of the contact info (e.g. address information). + */ +public interface ContactInfo { + /** Create a new Connection from this ContactInfo. + * Throws an IOException if Connection creation fails. + */ + C createConnection() throws IOException ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/InboundConnectionCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/InboundConnectionCache.java new file mode 100644 index 000000000..25390693d --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/InboundConnectionCache.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + +/** A concurrent connection cache for passively created connections (e.g. + * from an acceptor). Here a Connection is an + * abstraction of a Socket or SocketChannel: basically some sort of resource + * that is expensive to acquire, and can be re-used freely. + * The cache maintains a loose + * upper bound on the number of cached connections, and reclaims connections as + * needed. + *

                + * This cache places minimal requirements on the Connections that it contains: + *

                  + *
                1. A Connection must implement a close() method. This is called when idle + * connections are reclaimed. + *
                2. A Connection must be usable as a HashMap key. + *
                + *

                + * Some simple methods are provided for monitoring the state of the cache: + * numbers of busy and idle connections, and the total number of + * connections in the cache. + *

                + * Access is also provided to the cache configuration: maxParallelConnections, + * highWaterMark, and numberToReclaim. Currently these can only be set when + * the cache is created. + * + * XXX We may wish to make the cache configuration dynamically configurable. + */ +public interface InboundConnectionCache extends ConnectionCache { + /** Mark a connection as busy because a request is being processed + * on the connection. The connection may or may not be previously + * known to the cache when this method is called. + * Busy connections cannot be reclaimed. + * This provides an early indication that a Connection is in use, + * before we know how many responses still need to be sent on + * the Connection for this request. This reduces the likelyhood + * of reclaiming a connection on which we are processing a request. + *

                + * Note that this problem is inherent in a distributed system. + * We could in any case reclaim a connection AFTER a client + * has sent a request but BEFORE the request is received. + * Note that AFTER and BEFORE refer to global time which does + * not really exist in a distributed system (or at least we + * want to pretend it is not available). + * + * XXX Should we age out connections? + * This would require actual time stamps, rather than just an LRU queue. + */ + void requestReceived( C conn ) ; + + /** Indicate that request processing has been completed for a request + * received on conn. This indicates that a Connection that received + * a request as indicated in a previous call to requestReceived has + * completed request processing for that request. Responses may still + * need to be sent. Some number of + * responses (usually 0 or 1) may be expected ON THE SAME CONNECTION + * even for an idle connection. We maintain a count of the number of + * outstanding responses we expect for protocols that return the response + * on the same connection on which the request was received. This is + * necessary to prevent reclamation of a Connection that is idle, but + * still needed to send responses to old requests. + */ + void requestProcessed( C conn, int numResponseExpected ) ; + + /** Inform the cache that a response has been sent on a particular + * connection. + *

                + * When a Connection is idle, and has no pending responses, it is + * eligible for reclamation. + */ + void responseSent( C conn ) ; +} diff --git a/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/OutboundConnectionCache.java b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/OutboundConnectionCache.java new file mode 100644 index 000000000..2867e1e96 --- /dev/null +++ b/orbmain/src/main/java/com/sun/corba/ee/spi/transport/connection/OutboundConnectionCache.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.transport.connection; + +import java.io.IOException ; + +/** A concurrent mostly non-blocking connection cache. Here a Connection is an + * abstraction of a Socket or SocketChannel: basically some sort of resource + * that is expensive to acquire, and can be re-used freely. The cache + * maintains a loose upper bound on the number of cached connections, and + * reclaims connections as needed. + *

                + * This cache places minimal requirements on the Connections that it contains: + *

                  + *
                1. A Connection must implement a close() method. This is called when idle + * connections are reclaimed. + *
                2. A Connection must be usable as a HashMap key. + *
                3. There must be a ContactInfo class that is used to create Connection + * instances. The ContactInfo class must support a create() method that + * returns a Connection. + *
                4. The ContactInfo must be usable as a HashMap key. + *
                5. All instances created from a ContactInfo are equal; that is, any request + * sent to a particular ContactInfo can used an instance created from that + * ContactInfo. For example, in the CORBA case, IP host and port is not always + * sufficient: we may also need the Codeset type that indicates how Strings are + * encoded. Basically, protocols (like GIOP) that bind session state to a + * Connection may need more than transport information in the ContactInfo. + *
                + *

                + * Some simple methods are provided for monitoring the state of the cache: + * numbers of busy and idle connections, and the total number of connections in + * the cache. + */ +public interface OutboundConnectionCache + extends ConnectionCache { + /** Configured maximum number of connections supported per ContactInfo. + */ + int maxParallelConnections() ; + + /** Determine whether a new connection could be created by the + * ConnectionCache or not. + */ + boolean canCreateNewConnection( ContactInfo cinfo ) ; + + /** Return a Connection corresponding to the given ContactInfo. + * This works as follows: + *

                  + *
                • Call the finder. If it returns non-null, use that connection; + * (Note that this may be a new connection, created in the finder). + * The finder SHOULD NOT create a new connection if canCreateNewConnection + * returns false, but this is advisory. + *
                • otherwise, Use an idle connection, if one is available; + *
                • otherwise, create a new connection, if not too many connections are + * open; + *
                • otherwise, use a busy connection. + *
                + * Note that creating a new connection requires EITHER: + *
                  + *
                • there is no existing connection for the ContactInfo + *
                • OR the total number of connections in the cache is less than the + * HighWaterMark and the number of connections for this ContactInfo + * is less than MaxParallelConnections. + *
                + * We will always return a + * Connection for a get call UNLESS we have no existing connection and + * an attempt to create a new connection fails. In this case, the + * IOException thrown by ContactInfo.create is propagated out of this + * method. + *

                + * It is possible that the cache contains connections that no longer connect + * to their destination. In this case, it is the responsibility of the + * client of the cache to close the broken connection as they are detected. + * Connection reclamation may also handle the cleanup, but note that a + * broken connection with pending responses will never be reclaimed. + *

                + * Note that the idle and busy connection collections that are + * passed to the finder are unmodifiable collections. They have iterators + * that return connections in LRU order, with the least recently used + * connection first. This is done to aid a finder that wishes to consider + * load balancing in its determination of an appropriate connection. + *

                + */ + C get( ContactInfo cinfo, ConnectionFinder finder + ) throws IOException ; + + /** Behaves the same as get( ContactInfo, ConnectionFinder ) + * except that no connection finder is provided, so that step is + * ignored. + */ + C get( ContactInfo cinfo ) throws IOException ; + + /** Release a Connection previously obtained from get. Connections that + * have been released as many times as they have been returned by + * get are idle; otherwise a Connection is busy. Some number of + * responses (usually 0 or 1) may be expected ON THE SAME CONNECTION + * even for an idle connection. We maintain a count of the number of + * outstanding responses we expect for protocols that return the response + * on the same connection on which the request was received. This is + * necessary to prevent reclamation of a Connection that is idle, but + * still needed to send responses to old requests. + */ + void release( C conn, int numResponseExpected ) ; + + /** Inform the cache that a response has been received on a particular + * connection. This must also be called in the event that no response + * is received, but the client times out waiting for a response, and + * decides to abandon the request. + *

                + * When a Connection is idle, and has no pending responses, it is + * eligible for reclamation. + */ + void responseReceived( C conn ) ; +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/AttrDescriptionSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttrDescriptionSeqHelper.java new file mode 100644 index 000000000..5e3f3e489 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttrDescriptionSeqHelper.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/AttrDescriptionSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class AttrDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttrDescriptionSeq:1.0"; + + public AttrDescriptionSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.AttributeDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.AttributeDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.AttributeDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.AttrDescriptionSeqHelper.id (), "AttrDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.AttributeDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.AttributeDescription value[] = null; + int _len0 = istream.read_long (); + value = new com.sun.org.omg.CORBA.AttributeDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.AttributeDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.AttributeDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.AttributeDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeDescription.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeDescription.java new file mode 100644 index 000000000..c4d2ab92f --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeDescription.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/AttributeDescription.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class AttributeDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + public com.sun.org.omg.CORBA.AttributeMode mode = null; + + public AttributeDescription () + { + } // ctor + + public AttributeDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type, com.sun.org.omg.CORBA.AttributeMode _mode) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + mode = _mode; + } // ctor + +} // class AttributeDescription diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeDescriptionHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeDescriptionHelper.java new file mode 100644 index 000000000..9fe98b339 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeDescriptionHelper.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/AttributeDescriptionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class AttributeDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttributeDescription:1.0"; + + public AttributeDescriptionHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.AttributeDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.AttributeDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [6]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.AttributeModeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "mode", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.AttributeDescriptionHelper.id (), "AttributeDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.AttributeDescription read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.AttributeDescription value = new com.sun.org.omg.CORBA.AttributeDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + value.mode = com.sun.org.omg.CORBA.AttributeModeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.AttributeDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + com.sun.org.omg.CORBA.AttributeModeHelper.write (ostream, value.mode); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeMode.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeMode.java new file mode 100644 index 000000000..0a14b1150 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeMode.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/AttributeMode.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public class AttributeMode implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 2; + private static com.sun.org.omg.CORBA.AttributeMode[] __array = new com.sun.org.omg.CORBA.AttributeMode [__size]; + + public static final int _ATTR_NORMAL = 0; + public static final com.sun.org.omg.CORBA.AttributeMode ATTR_NORMAL = new com.sun.org.omg.CORBA.AttributeMode(_ATTR_NORMAL); + public static final int _ATTR_READONLY = 1; + public static final com.sun.org.omg.CORBA.AttributeMode ATTR_READONLY = new com.sun.org.omg.CORBA.AttributeMode(_ATTR_READONLY); + + public int value () + { + return __value; + } + + public static com.sun.org.omg.CORBA.AttributeMode from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected AttributeMode (int value) + { + __value = value; + __array[__value] = this; + } +} // class AttributeMode diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeModeHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeModeHelper.java new file mode 100644 index 000000000..4f450bb0e --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/AttributeModeHelper.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/AttributeModeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class AttributeModeHelper +{ + private static String _id = "IDL:omg.org/CORBA/AttributeMode:1.0"; + + public AttributeModeHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.AttributeMode that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.AttributeMode extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (com.sun.org.omg.CORBA.AttributeModeHelper.id (), "AttributeMode", new String[] { "ATTR_NORMAL", "ATTR_READONLY"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.AttributeMode read (org.omg.CORBA.portable.InputStream istream) + { + return com.sun.org.omg.CORBA.AttributeMode.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.AttributeMode value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ContextIdSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ContextIdSeqHelper.java new file mode 100644 index 000000000..ac46130ae --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ContextIdSeqHelper.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ContextIdSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class ContextIdSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ContextIdSeq:1.0"; + + public ContextIdSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ContextIdentifierHelper.id (), "ContextIdentifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ContextIdSeqHelper.id (), "ContextIdSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[] read (org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long (); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.ContextIdentifierHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.ContextIdentifierHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ContextIdentifierHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ContextIdentifierHelper.java new file mode 100644 index 000000000..80a1d3ce5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ContextIdentifierHelper.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ContextIdentifierHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class ContextIdentifierHelper +{ + private static String _id = "IDL:omg.org/CORBA/ContextIdentifier:1.0"; + + public ContextIdentifierHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ContextIdentifierHelper.id (), "ContextIdentifier", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/DefinitionKindHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/DefinitionKindHelper.java new file mode 100644 index 000000000..de161558c --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/DefinitionKindHelper.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/DefinitionKindHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:43 AM PDT +*/ + +// This file has been manually _CHANGED_ + +public final class DefinitionKindHelper +{ + private static String _id = "IDL:omg.org/CORBA/DefinitionKind:1.0"; + + public DefinitionKindHelper() + { + } + + // _CHANGED_ + //public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.DefinitionKind that) + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.DefinitionKind that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.DefinitionKind extract (org.omg.CORBA.Any a) + public static org.omg.CORBA.DefinitionKind extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (com.sun.org.omg.CORBA.DefinitionKindHelper.id (), "DefinitionKind", new String[] { "dk_none", "dk_all", "dk_Attribute", "dk_Constant", "dk_Exception", "dk_Interface", "dk_Module", "dk_Operation", "dk_Typedef", "dk_Alias", "dk_Struct", "dk_Union", "dk_Enum", "dk_Primitive", "dk_String", "dk_Sequence", "dk_Array", "dk_Repository", "dk_Wstring", "dk_Fixed", "dk_Value", "dk_ValueBox", "dk_ValueMember", "dk_Native"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.DefinitionKind read (org.omg.CORBA.portable.InputStream istream) + public static org.omg.CORBA.DefinitionKind read (org.omg.CORBA.portable.InputStream istream) + { + // _CHANGED_ + //return com.sun.org.omg.CORBA.DefinitionKind.from_int (istream.read_long ()); + return org.omg.CORBA.DefinitionKind.from_int (istream.read_long ()); + } + + // _CHANGED_ + //public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.DefinitionKind value) + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.DefinitionKind value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ExcDescriptionSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ExcDescriptionSeqHelper.java new file mode 100644 index 000000000..7fc9005a5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ExcDescriptionSeqHelper.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ExcDescriptionSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class ExcDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ExcDescriptionSeq:1.0"; + + public ExcDescriptionSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ExceptionDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ExceptionDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.ExceptionDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ExcDescriptionSeqHelper.id (), "ExcDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ExceptionDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.ExceptionDescription value[] = null; + int _len0 = istream.read_long (); + value = new com.sun.org.omg.CORBA.ExceptionDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.ExceptionDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ExceptionDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.ExceptionDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ExceptionDescription.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ExceptionDescription.java new file mode 100644 index 000000000..811c9096f --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ExceptionDescription.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ExceptionDescription.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class ExceptionDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode type = null; + + public ExceptionDescription () + { + } // ctor + + public ExceptionDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _type) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + type = _type; + } // ctor + +} // class ExceptionDescription diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ExceptionDescriptionHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ExceptionDescriptionHelper.java new file mode 100644 index 000000000..40c8a4fe5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ExceptionDescriptionHelper.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ExceptionDescriptionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class ExceptionDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ExceptionDescription:1.0"; + + public ExceptionDescriptionHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ExceptionDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ExceptionDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [5]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.ExceptionDescriptionHelper.id (), "ExceptionDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ExceptionDescription read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.ExceptionDescription value = new com.sun.org.omg.CORBA.ExceptionDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ExceptionDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/IDLTypeHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/IDLTypeHelper.java new file mode 100644 index 000000000..c33fbbab5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/IDLTypeHelper.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/IDLTypeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:45 AM PDT +*/ + +// This file has been _CHANGED_ + +public final class IDLTypeHelper +{ + private static String _id = "IDL:omg.org/CORBA/IDLType:1.0"; + + public IDLTypeHelper() + { + } + + // _CHANGED_ + //public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.IDLType that) + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.IDLType that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.IDLType extract (org.omg.CORBA.Any a) + public static org.omg.CORBA.IDLType extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (com.sun.org.omg.CORBA.IDLTypeHelper.id (), "IDLType"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.IDLType read (org.omg.CORBA.portable.InputStream istream) + public static org.omg.CORBA.IDLType read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (org.glassfish.corba.org.omg.CORBA._IDLTypeStub.class)); + } + + // _CHANGED_ + //public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.IDLType value) + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.IDLType value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.IDLType narrow (org.omg.CORBA.Object obj) + public static org.omg.CORBA.IDLType narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + // _CHANGED_ + //else if (obj instanceof com.sun.org.omg.CORBA.IDLType) + else if (obj instanceof org.omg.CORBA.IDLType) + // _CHANGED_ + //return (com.sun.org.omg.CORBA.IDLType)obj; + return (org.omg.CORBA.IDLType)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + return new org.glassfish.corba.org.omg.CORBA._IDLTypeStub(delegate); + } + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/IDLTypeOperations.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/IDLTypeOperations.java new file mode 100644 index 000000000..263d38fc3 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/IDLTypeOperations.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/IDLTypeOperations.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:45 AM PDT +*/ + +public interface IDLTypeOperations extends com.sun.org.omg.CORBA.IRObjectOperations +{ + org.omg.CORBA.TypeCode type (); +} // interface IDLTypeOperations diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/IRObjectOperations.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/IRObjectOperations.java new file mode 100644 index 000000000..f95b3832e --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/IRObjectOperations.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/IRObjectOperations.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:43 AM PDT +*/ + +// This file has been manually _CHANGED_ + +public interface IRObjectOperations +{ + + // read interface + + // _CHANGED_ + //com.sun.org.omg.CORBA.DefinitionKind def_kind (); + org.omg.CORBA.DefinitionKind def_kind (); + + // write interface + void destroy (); +} // interface IRObjectOperations diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/IdentifierHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/IdentifierHelper.java new file mode 100644 index 000000000..4dc22eaae --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/IdentifierHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/IdentifierHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:42 AM PDT +*/ + +public final class IdentifierHelper +{ + private static String _id = "IDL:omg.org/CORBA/Identifier:1.0"; + + public IdentifierHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/Initializer.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/Initializer.java new file mode 100644 index 000000000..9f18f8661 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/Initializer.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/Initializer.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +// This file has been _CHANGED_ + +public final class Initializer implements org.omg.CORBA.portable.IDLEntity +{ + // _CHANGED_ + //public com.sun.org.omg.CORBA.StructMember members[] = null; + public org.omg.CORBA.StructMember members[] = null; + public String name = null; + + public Initializer () + { + } // ctor + + // _CHANGED_ + //public Initializer (com.sun.org.omg.CORBA.StructMember[] _members, String _name) + public Initializer (org.omg.CORBA.StructMember[] _members, String _name) + { + members = _members; + name = _name; + } // ctor + +} // class Initializer diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/InitializerHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/InitializerHelper.java new file mode 100644 index 000000000..2474204ce --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/InitializerHelper.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/InitializerHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +public final class InitializerHelper +{ + private static String _id = "IDL:omg.org/CORBA/Initializer:1.0"; + + public InitializerHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.Initializer that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.Initializer extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = com.sun.org.omg.CORBA.StructMemberHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.StructMemberSeqHelper.id (), "StructMemberSeq", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "members", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.InitializerHelper.id (), "Initializer", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.Initializer read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.Initializer value = new com.sun.org.omg.CORBA.Initializer (); + value.members = com.sun.org.omg.CORBA.StructMemberSeqHelper.read (istream); + value.name = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.Initializer value) + { + com.sun.org.omg.CORBA.StructMemberSeqHelper.write (ostream, value.members); + ostream.write_string (value.name); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/InitializerSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/InitializerSeqHelper.java new file mode 100644 index 000000000..d986b7e00 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/InitializerSeqHelper.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/InitializerSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +public final class InitializerSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/InitializerSeq:1.0"; + + public InitializerSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.Initializer[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.Initializer[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.InitializerHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.InitializerSeqHelper.id (), "InitializerSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.Initializer[] read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.Initializer value[] = null; + int _len0 = istream.read_long (); + value = new com.sun.org.omg.CORBA.Initializer[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.InitializerHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.Initializer[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.InitializerHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/OpDescriptionSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/OpDescriptionSeqHelper.java new file mode 100644 index 000000000..0a3db0832 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/OpDescriptionSeqHelper.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/OpDescriptionSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class OpDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/OpDescriptionSeq:1.0"; + + public OpDescriptionSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.OperationDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.OperationDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.OperationDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.OpDescriptionSeqHelper.id (), "OpDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.OperationDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.OperationDescription value[] = null; + int _len0 = istream.read_long (); + value = new com.sun.org.omg.CORBA.OperationDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.OperationDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.OperationDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.OperationDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationDescription.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationDescription.java new file mode 100644 index 000000000..679ddad35 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationDescription.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/OperationDescription.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class OperationDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public String defined_in = null; + public String version = null; + public org.omg.CORBA.TypeCode result = null; + public com.sun.org.omg.CORBA.OperationMode mode = null; + public String contexts[] = null; + public com.sun.org.omg.CORBA.ParameterDescription parameters[] = null; + public com.sun.org.omg.CORBA.ExceptionDescription exceptions[] = null; + + public OperationDescription () + { + } // ctor + + public OperationDescription (String _name, String _id, String _defined_in, String _version, org.omg.CORBA.TypeCode _result, com.sun.org.omg.CORBA.OperationMode _mode, String[] _contexts, com.sun.org.omg.CORBA.ParameterDescription[] _parameters, com.sun.org.omg.CORBA.ExceptionDescription[] _exceptions) + { + name = _name; + id = _id; + defined_in = _defined_in; + version = _version; + result = _result; + mode = _mode; + contexts = _contexts; + parameters = _parameters; + exceptions = _exceptions; + } // ctor + +} // class OperationDescription diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationDescriptionHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationDescriptionHelper.java new file mode 100644 index 000000000..3bca08018 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationDescriptionHelper.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/OperationDescriptionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class OperationDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/OperationDescription:1.0"; + + public OperationDescriptionHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.OperationDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.OperationDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [9]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "result", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.OperationModeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "mode", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ContextIdentifierHelper.id (), "ContextIdentifier", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ContextIdSeqHelper.id (), "ContextIdSeq", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "contexts", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.ParameterDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ParDescriptionSeqHelper.id (), "ParDescriptionSeq", _tcOf_members0); + _members0[7] = new org.omg.CORBA.StructMember ( + "parameters", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.ExceptionDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ExcDescriptionSeqHelper.id (), "ExcDescriptionSeq", _tcOf_members0); + _members0[8] = new org.omg.CORBA.StructMember ( + "exceptions", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.OperationDescriptionHelper.id (), "OperationDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.OperationDescription read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.OperationDescription value = new com.sun.org.omg.CORBA.OperationDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.result = istream.read_TypeCode (); + value.mode = com.sun.org.omg.CORBA.OperationModeHelper.read (istream); + value.contexts = com.sun.org.omg.CORBA.ContextIdSeqHelper.read (istream); + value.parameters = com.sun.org.omg.CORBA.ParDescriptionSeqHelper.read (istream); + value.exceptions = com.sun.org.omg.CORBA.ExcDescriptionSeqHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.OperationDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.result); + com.sun.org.omg.CORBA.OperationModeHelper.write (ostream, value.mode); + com.sun.org.omg.CORBA.ContextIdSeqHelper.write (ostream, value.contexts); + com.sun.org.omg.CORBA.ParDescriptionSeqHelper.write (ostream, value.parameters); + com.sun.org.omg.CORBA.ExcDescriptionSeqHelper.write (ostream, value.exceptions); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationMode.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationMode.java new file mode 100644 index 000000000..a15b6833e --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationMode.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/OperationMode.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public class OperationMode implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 2; + private static com.sun.org.omg.CORBA.OperationMode[] __array = new com.sun.org.omg.CORBA.OperationMode [__size]; + + public static final int _OP_NORMAL = 0; + public static final com.sun.org.omg.CORBA.OperationMode OP_NORMAL = new com.sun.org.omg.CORBA.OperationMode(_OP_NORMAL); + public static final int _OP_ONEWAY = 1; + public static final com.sun.org.omg.CORBA.OperationMode OP_ONEWAY = new com.sun.org.omg.CORBA.OperationMode(_OP_ONEWAY); + + public int value () + { + return __value; + } + + public static com.sun.org.omg.CORBA.OperationMode from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected OperationMode (int value) + { + __value = value; + __array[__value] = this; + } +} // class OperationMode diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationModeHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationModeHelper.java new file mode 100644 index 000000000..2b99efb9c --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/OperationModeHelper.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/OperationModeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class OperationModeHelper +{ + private static String _id = "IDL:omg.org/CORBA/OperationMode:1.0"; + + public OperationModeHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.OperationMode that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.OperationMode extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (com.sun.org.omg.CORBA.OperationModeHelper.id (), "OperationMode", new String[] { "OP_NORMAL", "OP_ONEWAY"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.OperationMode read (org.omg.CORBA.portable.InputStream istream) + { + return com.sun.org.omg.CORBA.OperationMode.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.OperationMode value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ParDescriptionSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParDescriptionSeqHelper.java new file mode 100644 index 000000000..5593de7e5 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParDescriptionSeqHelper.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ParDescriptionSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class ParDescriptionSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ParDescriptionSeq:1.0"; + + public ParDescriptionSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ParameterDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ParameterDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.ParameterDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ParDescriptionSeqHelper.id (), "ParDescriptionSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ParameterDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.ParameterDescription value[] = null; + int _len0 = istream.read_long (); + value = new com.sun.org.omg.CORBA.ParameterDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.ParameterDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ParameterDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.ParameterDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterDescription.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterDescription.java new file mode 100644 index 000000000..28f957672 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterDescription.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ParameterDescription.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +// This file has been _CHANGED_ + +public final class ParameterDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public org.omg.CORBA.TypeCode type = null; + // _CHANGED_ + //public com.sun.org.omg.CORBA.IDLType type_def = null; + public org.omg.CORBA.IDLType type_def = null; + public com.sun.org.omg.CORBA.ParameterMode mode = null; + + public ParameterDescription () + { + } // ctor + + // _CHANGED_ + //public ParameterDescription (String _name, org.omg.CORBA.TypeCode _type, com.sun.org.omg.CORBA.IDLType _type_def, com.sun.org.omg.CORBA.ParameterMode _mode) + public ParameterDescription (String _name, org.omg.CORBA.TypeCode _type, org.omg.CORBA.IDLType _type_def, com.sun.org.omg.CORBA.ParameterMode _mode) + { + name = _name; + type = _type; + type_def = _type_def; + mode = _mode; + } // ctor + +} // class ParameterDescription diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterDescriptionHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterDescriptionHelper.java new file mode 100644 index 000000000..a51829f45 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterDescriptionHelper.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ParameterDescriptionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class ParameterDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ParameterDescription:1.0"; + + public ParameterDescriptionHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ParameterDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ParameterDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [4]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[1] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.IDLTypeHelper.type (); + _members0[2] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.ParameterModeHelper.type (); + _members0[3] = new org.omg.CORBA.StructMember ( + "mode", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.ParameterDescriptionHelper.id (), "ParameterDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ParameterDescription read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.ParameterDescription value = new com.sun.org.omg.CORBA.ParameterDescription (); + value.name = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = com.sun.org.omg.CORBA.IDLTypeHelper.read (istream); + value.mode = com.sun.org.omg.CORBA.ParameterModeHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ParameterDescription value) + { + ostream.write_string (value.name); + ostream.write_TypeCode (value.type); + com.sun.org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + com.sun.org.omg.CORBA.ParameterModeHelper.write (ostream, value.mode); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterMode.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterMode.java new file mode 100644 index 000000000..aa8c56116 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterMode.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ParameterMode.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public class ParameterMode implements org.omg.CORBA.portable.IDLEntity +{ + private int __value; + private static int __size = 3; + private static com.sun.org.omg.CORBA.ParameterMode[] __array = new com.sun.org.omg.CORBA.ParameterMode [__size]; + + public static final int _PARAM_IN = 0; + public static final com.sun.org.omg.CORBA.ParameterMode PARAM_IN = new com.sun.org.omg.CORBA.ParameterMode(_PARAM_IN); + public static final int _PARAM_OUT = 1; + public static final com.sun.org.omg.CORBA.ParameterMode PARAM_OUT = new com.sun.org.omg.CORBA.ParameterMode(_PARAM_OUT); + public static final int _PARAM_INOUT = 2; + public static final com.sun.org.omg.CORBA.ParameterMode PARAM_INOUT = new com.sun.org.omg.CORBA.ParameterMode(_PARAM_INOUT); + + public int value () + { + return __value; + } + + public static com.sun.org.omg.CORBA.ParameterMode from_int (int value) + { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM (); + } + + protected ParameterMode (int value) + { + __value = value; + __array[__value] = this; + } +} // class ParameterMode diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterModeHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterModeHelper.java new file mode 100644 index 000000000..7c102a687 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ParameterModeHelper.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ParameterModeHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:50 AM PDT +*/ + +public final class ParameterModeHelper +{ + private static String _id = "IDL:omg.org/CORBA/ParameterMode:1.0"; + + public ParameterModeHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ParameterMode that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ParameterMode extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_enum_tc (com.sun.org.omg.CORBA.ParameterModeHelper.id (), "ParameterMode", new String[] { "PARAM_IN", "PARAM_OUT", "PARAM_INOUT"} ); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ParameterMode read (org.omg.CORBA.portable.InputStream istream) + { + return com.sun.org.omg.CORBA.ParameterMode.from_int (istream.read_long ()); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ParameterMode value) + { + ostream.write_long (value.value ()); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/Repository.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/Repository.java new file mode 100644 index 000000000..587042006 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/Repository.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + +public interface Repository extends org.omg.CORBA.IRObject, org.omg.CORBA.portable.IDLEntity +{ +} // interface Repository diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryHelper.java new file mode 100644 index 000000000..684a5797f --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryHelper.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + +public final class RepositoryHelper +{ + private static String _id = "IDL:com.sun.omg.org/CORBA/Repository:3.0"; + + public RepositoryHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, Repository that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static Repository extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryHelper.id (), "Repository", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static Repository read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return null; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, Repository value) + { + ostream.write_string (null); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryIdHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryIdHelper.java new file mode 100644 index 000000000..bb0e148bf --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryIdHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/RepositoryIdHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:43 AM PDT +*/ + +public final class RepositoryIdHelper +{ + private static String _id = "IDL:omg.org/CORBA/RepositoryId:1.0"; + + public RepositoryIdHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryIdSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryIdSeqHelper.java new file mode 100644 index 000000000..ee1516574 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/RepositoryIdSeqHelper.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/RepositoryIdSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:51 AM PDT +*/ + +public final class RepositoryIdSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/RepositoryIdSeq:1.0"; + + public RepositoryIdSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[] read (org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long (); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.RepositoryIdHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.RepositoryIdHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/StructMemberHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/StructMemberHelper.java new file mode 100644 index 000000000..38c6a923d --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/StructMemberHelper.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/StructMemberHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +// This file has been manually _CHANGED_ + +public final class StructMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/StructMember:1.0"; + + public StructMemberHelper() + { + } + + // _CHANGED_ + //public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.StructMember that) + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StructMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.StructMember extract (org.omg.CORBA.Any a) + public static org.omg.CORBA.StructMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [3]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[1] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.IDLTypeHelper.type (); + _members0[2] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.StructMemberHelper.id (), "StructMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.StructMember read (org.omg.CORBA.portable.InputStream istream) + public static org.omg.CORBA.StructMember read (org.omg.CORBA.portable.InputStream istream) + { + // _CHANGED_ + //com.sun.org.omg.CORBA.StructMember value = new com.sun.org.omg.CORBA.StructMember (); + org.omg.CORBA.StructMember value = new org.omg.CORBA.StructMember (); + value.name = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = com.sun.org.omg.CORBA.IDLTypeHelper.read (istream); + return value; + } + + // _CHANGED_ + //public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.StructMember value) + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StructMember value) + { + ostream.write_string (value.name); + ostream.write_TypeCode (value.type); + com.sun.org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/StructMemberSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/StructMemberSeqHelper.java new file mode 100644 index 000000000..81fa456d4 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/StructMemberSeqHelper.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/StructMemberSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +// This file has been _CHANGED_ + +public final class StructMemberSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/StructMemberSeq:1.0"; + + public StructMemberSeqHelper() + { + } + + // _CHANGED_ + //public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.StructMember[] that) + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.StructMember[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.StructMember[] extract (org.omg.CORBA.Any a) + public static org.omg.CORBA.StructMember[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.StructMemberHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.StructMemberSeqHelper.id (), "StructMemberSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.StructMember[] read (org.omg.CORBA.portable.InputStream istream) + public static org.omg.CORBA.StructMember[] read (org.omg.CORBA.portable.InputStream istream) + { + // _CHANGED_ + //com.sun.org.omg.CORBA.StructMember value[] = null; + org.omg.CORBA.StructMember value[] = null; + int _len0 = istream.read_long (); + // _CHANGED_ + //value = new com.sun.org.omg.CORBA.StructMember[_len0]; + value = new org.omg.CORBA.StructMember[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.StructMemberHelper.read (istream); + return value; + } + + // _CHANGED_ + //public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.StructMember[] value) + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.StructMember[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.StructMemberHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescription.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescription.java new file mode 100644 index 000000000..f94372c83 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescription.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA.ValueDefPackage; + + +/** +* com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescription.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:52 AM PDT +*/ + +// This file has been manually _CHANGED_ + +public final class FullValueDescription implements org.omg.CORBA.portable.IDLEntity +{ + public String name = null; + public String id = null; + public boolean is_abstract = false; + public boolean is_custom = false; + public String defined_in = null; + public String version = null; + public com.sun.org.omg.CORBA.OperationDescription operations[] = null; + public com.sun.org.omg.CORBA.AttributeDescription attributes[] = null; + + // _CHANGED_ + //public com.sun.org.omg.CORBA.ValueMember members[] = null; + public org.omg.CORBA.ValueMember members[] = null; + + public com.sun.org.omg.CORBA.Initializer initializers[] = null; + public String supported_interfaces[] = null; + public String abstract_base_values[] = null; + public boolean is_truncatable = false; + public String base_value = null; + public org.omg.CORBA.TypeCode type = null; + + public FullValueDescription () + { + } // ctor + + // _CHANGED_ + //public FullValueDescription (String _name, String _id, boolean _is_abstract, boolean _is_custom, String _defined_in, String _version, com.sun.org.omg.CORBA.OperationDescription[] _operations, com.sun.org.omg.CORBA.AttributeDescription[] _attributes, com.sun.org.omg.CORBA.ValueMember[] _members, com.sun.org.omg.CORBA.Initializer[] _initializers, String[] _supported_interfaces, String[] _abstract_base_values, boolean _is_truncatable, String _base_value, org.omg.CORBA.TypeCode _type) + public FullValueDescription (String _name, String _id, boolean _is_abstract, boolean _is_custom, String _defined_in, String _version, com.sun.org.omg.CORBA.OperationDescription[] _operations, com.sun.org.omg.CORBA.AttributeDescription[] _attributes, org.omg.CORBA.ValueMember[] _members, com.sun.org.omg.CORBA.Initializer[] _initializers, String[] _supported_interfaces, String[] _abstract_base_values, boolean _is_truncatable, String _base_value, org.omg.CORBA.TypeCode _type) + { + name = _name; + id = _id; + is_abstract = _is_abstract; + is_custom = _is_custom; + defined_in = _defined_in; + version = _version; + operations = _operations; + attributes = _attributes; + members = _members; + initializers = _initializers; + supported_interfaces = _supported_interfaces; + abstract_base_values = _abstract_base_values; + is_truncatable = _is_truncatable; + base_value = _base_value; + type = _type; + } // ctor + +} // class FullValueDescription diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java new file mode 100644 index 000000000..a74c3c302 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA.ValueDefPackage; + + +/** +* com/sun/org/omg/CORBA/ValueDefPackage/FullValueDescriptionHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:52 AM PDT +*/ + +public final class FullValueDescriptionHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueDef/FullValueDescription:1.0"; + + public FullValueDescriptionHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [15]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[2] = new org.omg.CORBA.StructMember ( + "is_abstract", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[3] = new org.omg.CORBA.StructMember ( + "is_custom", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[4] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[5] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.OperationDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.OpDescriptionSeqHelper.id (), "OpDescriptionSeq", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "operations", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.AttributeDescriptionHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.AttrDescriptionSeqHelper.id (), "AttrDescriptionSeq", _tcOf_members0); + _members0[7] = new org.omg.CORBA.StructMember ( + "attributes", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.ValueMemberHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ValueMemberSeqHelper.id (), "ValueMemberSeq", _tcOf_members0); + _members0[8] = new org.omg.CORBA.StructMember ( + "members", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.InitializerHelper.type (); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.InitializerSeqHelper.id (), "InitializerSeq", _tcOf_members0); + _members0[9] = new org.omg.CORBA.StructMember ( + "initializers", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[10] = new org.omg.CORBA.StructMember ( + "supported_interfaces", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_sequence_tc (0, _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdSeqHelper.id (), "RepositoryIdSeq", _tcOf_members0); + _members0[11] = new org.omg.CORBA.StructMember ( + "abstract_base_values", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[12] = new org.omg.CORBA.StructMember ( + "is_truncatable", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[13] = new org.omg.CORBA.StructMember ( + "base_value", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[14] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.id (), "FullValueDescription", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription value = new com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.is_abstract = istream.read_boolean (); + value.is_custom = istream.read_boolean (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.operations = com.sun.org.omg.CORBA.OpDescriptionSeqHelper.read (istream); + value.attributes = com.sun.org.omg.CORBA.AttrDescriptionSeqHelper.read (istream); + value.members = com.sun.org.omg.CORBA.ValueMemberSeqHelper.read (istream); + value.initializers = com.sun.org.omg.CORBA.InitializerSeqHelper.read (istream); + value.supported_interfaces = com.sun.org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.abstract_base_values = com.sun.org.omg.CORBA.RepositoryIdSeqHelper.read (istream); + value.is_truncatable = istream.read_boolean (); + value.base_value = istream.read_string (); + value.type = istream.read_TypeCode (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_boolean (value.is_abstract); + ostream.write_boolean (value.is_custom); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + com.sun.org.omg.CORBA.OpDescriptionSeqHelper.write (ostream, value.operations); + com.sun.org.omg.CORBA.AttrDescriptionSeqHelper.write (ostream, value.attributes); + com.sun.org.omg.CORBA.ValueMemberSeqHelper.write (ostream, value.members); + com.sun.org.omg.CORBA.InitializerSeqHelper.write (ostream, value.initializers); + com.sun.org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.supported_interfaces); + com.sun.org.omg.CORBA.RepositoryIdSeqHelper.write (ostream, value.abstract_base_values); + ostream.write_boolean (value.is_truncatable); + ostream.write_string (value.base_value); + ostream.write_TypeCode (value.type); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueMemberHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueMemberHelper.java new file mode 100644 index 000000000..32fc44f23 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueMemberHelper.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ValueMemberHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +// This file has been _CHANGED_ + +public final class ValueMemberHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueMember:1.0"; + + public ValueMemberHelper() + { + } + + // _CHANGED_ + //public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ValueMember that) + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueMember that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.ValueMember extract (org.omg.CORBA.Any a) + public static org.omg.CORBA.ValueMember extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [7]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.IdentifierHelper.id (), "Identifier", _tcOf_members0); + _members0[0] = new org.omg.CORBA.StructMember ( + "name", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[1] = new org.omg.CORBA.StructMember ( + "id", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember ( + "defined_in", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember ( + "version", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_TypeCode); + _members0[4] = new org.omg.CORBA.StructMember ( + "type", + _tcOf_members0, + null); + _tcOf_members0 = com.sun.org.omg.CORBA.IDLTypeHelper.type (); + _members0[5] = new org.omg.CORBA.StructMember ( + "type_def", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VisibilityHelper.id (), "Visibility", _tcOf_members0); + _members0[6] = new org.omg.CORBA.StructMember ( + "access", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (com.sun.org.omg.CORBA.ValueMemberHelper.id (), "ValueMember", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.ValueMember read (org.omg.CORBA.portable.InputStream istream) + public static org.omg.CORBA.ValueMember read (org.omg.CORBA.portable.InputStream istream) + { + // _CHANGED_ + //com.sun.org.omg.CORBA.ValueMember value = new com.sun.org.omg.CORBA.ValueMember (); + org.omg.CORBA.ValueMember value = new org.omg.CORBA.ValueMember (); + value.name = istream.read_string (); + value.id = istream.read_string (); + value.defined_in = istream.read_string (); + value.version = istream.read_string (); + value.type = istream.read_TypeCode (); + value.type_def = com.sun.org.omg.CORBA.IDLTypeHelper.read (istream); + value.access = istream.read_short (); + return value; + } + + // _CHANGED_ + //public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ValueMember value) + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueMember value) + { + ostream.write_string (value.name); + ostream.write_string (value.id); + ostream.write_string (value.defined_in); + ostream.write_string (value.version); + ostream.write_TypeCode (value.type); + com.sun.org.omg.CORBA.IDLTypeHelper.write (ostream, value.type_def); + ostream.write_short (value.access); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueMemberSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueMemberSeqHelper.java new file mode 100644 index 000000000..d6ef2fa32 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/ValueMemberSeqHelper.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/ValueMemberSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + +// This file has been _CHANGED_ + +public final class ValueMemberSeqHelper +{ + private static String _id = "IDL:omg.org/CORBA/ValueMemberSeq:1.0"; + + public ValueMemberSeqHelper() + { + } + + // _CHANGED_ + //public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ValueMember[] that) + public static void insert (org.omg.CORBA.Any a, org.omg.CORBA.ValueMember[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.ValueMember[] extract (org.omg.CORBA.Any a) + public static org.omg.CORBA.ValueMember[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.ValueMemberHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.ValueMemberSeqHelper.id (), "ValueMemberSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + // _CHANGED_ + //public static com.sun.org.omg.CORBA.ValueMember[] read (org.omg.CORBA.portable.InputStream istream) + public static org.omg.CORBA.ValueMember[] read (org.omg.CORBA.portable.InputStream istream) + { + // _CHANGED_ + //com.sun.org.omg.CORBA.ValueMember value[] = null; + org.omg.CORBA.ValueMember value[] = null; + int _len0 = istream.read_long (); + // _CHANGED_ + //value = new com.sun.org.omg.CORBA.ValueMember[_len0]; + value = new org.omg.CORBA.ValueMember[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.ValueMemberHelper.read (istream); + return value; + } + + // _CHANGED_ + //public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ValueMember[] value) + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CORBA.ValueMember[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.ValueMemberHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/VersionSpecHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/VersionSpecHelper.java new file mode 100644 index 000000000..8cc056e67 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/VersionSpecHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/VersionSpecHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:43 AM PDT +*/ + +public final class VersionSpecHelper +{ + private static String _id = "IDL:omg.org/CORBA/VersionSpec:1.0"; + + public VersionSpecHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VersionSpecHelper.id (), "VersionSpec", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/VisibilityHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/VisibilityHelper.java new file mode 100644 index 000000000..5ff63cc8c --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/VisibilityHelper.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/VisibilityHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:44 AM PDT +*/ + + +// orbos 98-01-18: Objects By Value -- begin +public final class VisibilityHelper +{ + private static String _id = "IDL:omg.org/CORBA/Visibility:1.0"; + + public VisibilityHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, short that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static short extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_short); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.CORBA.VisibilityHelper.id (), "Visibility", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static short read (org.omg.CORBA.portable.InputStream istream) + { + short value = (short)0; + value = istream.read_short (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, short value) + { + ostream.write_short (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/CORBA/portable/ValueHelper.java b/orbmain/src/main/java/com/sun/org/omg/CORBA/portable/ValueHelper.java new file mode 100644 index 000000000..a957ffd55 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/CORBA/portable/ValueHelper.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.CORBA.portable; + +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.portable.BoxedValueHelper; + +/** + * An interface that is implemented by valuetype helper classes. + * This interface appeared in CORBA 2.3 drafts but was removed from + * the published CORBA 2.3 specification. + *

                + * @deprecated Deprecated by CORBA 2.3. + */ +@Deprecated +public interface ValueHelper extends BoxedValueHelper { + Class get_class(); + String[] get_truncatable_base_ids(); + TypeCode get_type(); +} + diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBase.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBase.java new file mode 100644 index 000000000..be04bf919 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBase.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext; + + +/** +* com/sun/org/omg/SendingContext/CodeBase.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +// Edited to leave RunTime in org.omg.CORBA + +public interface CodeBase extends CodeBaseOperations, org.omg.SendingContext.RunTime, org.omg.CORBA.portable.IDLEntity +{ +} // interface CodeBase diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBaseHelper.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBaseHelper.java new file mode 100644 index 000000000..b3f8eb442 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBaseHelper.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext; + + +/** +* com/sun/org/omg/SendingContext/CodeBaseHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +public final class CodeBaseHelper +{ + private static String _id = "IDL:omg.org/SendingContext/CodeBase:1.0"; + + public CodeBaseHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.SendingContext.CodeBase that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.SendingContext.CodeBase extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (com.sun.org.omg.SendingContext.CodeBaseHelper.id (), "CodeBase"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.SendingContext.CodeBase read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_CodeBaseStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.SendingContext.CodeBase value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static com.sun.org.omg.SendingContext.CodeBase narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof com.sun.org.omg.SendingContext.CodeBase) + return (com.sun.org.omg.SendingContext.CodeBase)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + return new com.sun.org.omg.SendingContext._CodeBaseStub (delegate); + } + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBaseOperations.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBaseOperations.java new file mode 100644 index 000000000..c5d7a2b7d --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBaseOperations.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext; + + +/** +* com/sun/org/omg/SendingContext/CodeBaseOperations.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +// Edited to leave RunTime in org.omg.CORBA + +public interface CodeBaseOperations extends org.omg.SendingContext.RunTimeOperations +{ + + // Operation to obtain the IR from the sending context + com.sun.org.omg.CORBA.Repository get_ir (); + + // Operations to obtain a URL to the implementation code + String implementation (String x); + String[] implementations (String[] x); + + // the same information + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription meta (String x); + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[] metas (String[] x); + + // information + String[] bases (String x); +} // interface CodeBaseOperations diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/URLHelper.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/URLHelper.java new file mode 100644 index 000000000..519d91e24 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/URLHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext.CodeBasePackage; + + +/** +* com/sun/org/omg/SendingContext/CodeBasePackage/URLHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +public final class URLHelper +{ + private static String _id = "IDL:omg.org/SendingContext/CodeBase/URL:1.0"; + + public URLHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.SendingContext.CodeBasePackage.URLHelper.id (), "URL", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/URLSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/URLSeqHelper.java new file mode 100644 index 000000000..707d0e790 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/URLSeqHelper.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext.CodeBasePackage; + + +/** +* com/sun/org/omg/SendingContext/CodeBasePackage/URLSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +public final class URLSeqHelper +{ + private static String _id = "IDL:omg.org/SendingContext/CodeBase/URLSeq:1.0"; + + public URLSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, String[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.SendingContext.CodeBasePackage.URLHelper.id (), "URL", __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.SendingContext.CodeBasePackage.URLSeqHelper.id (), "URLSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[] read (org.omg.CORBA.portable.InputStream istream) + { + String value[] = null; + int _len0 = istream.read_long (); + value = new String[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.SendingContext.CodeBasePackage.URLHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.SendingContext.CodeBasePackage.URLHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/ValueDescSeqHelper.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/ValueDescSeqHelper.java new file mode 100644 index 000000000..cc52d5bce --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/CodeBasePackage/ValueDescSeqHelper.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext.CodeBasePackage; + + +/** +* com/sun/org/omg/SendingContext/CodeBasePackage/ValueDescSeqHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +public final class ValueDescSeqHelper +{ + private static String _id = "IDL:omg.org/SendingContext/CodeBase/ValueDescSeq:1.0"; + + public ValueDescSeqHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.type (); + __typeCode = org.omg.CORBA.ORB.init ().create_sequence_tc (0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (com.sun.org.omg.SendingContext.CodeBasePackage.ValueDescSeqHelper.id (), "ValueDescSeq", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[] read (org.omg.CORBA.portable.InputStream istream) + { + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription value[] = null; + int _len0 = istream.read_long (); + value = new com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[_len0]; + for (int _o1 = 0;_o1 < value.length; ++_o1) + value[_o1] = com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.read (istream); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[] value) + { + ostream.write_long (value.length); + for (int _i0 = 0;_i0 < value.length; ++_i0) + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.write (ostream, value[_i0]); + } + +} diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/_CodeBaseImplBase.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/_CodeBaseImplBase.java new file mode 100644 index 000000000..aebd03e50 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/_CodeBaseImplBase.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext; + + +/** +* com/sun/org/omg/SendingContext/_CodeBaseImplBase.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +public abstract class _CodeBaseImplBase extends org.omg.CORBA.portable.ObjectImpl + implements com.sun.org.omg.SendingContext.CodeBase, org.omg.CORBA.portable.InvokeHandler +{ + + // Constructors + public _CodeBaseImplBase () + { + } + + private static java.util.Map _methods = + new java.util.HashMap (); + + static + { + _methods.put ("get_ir", 0); + _methods.put ("implementation", 1 ) ; + _methods.put ("implementations", 2 ) ; + _methods.put ("meta", 3 ) ; + _methods.put ("metas", 4 ) ; + _methods.put ("bases", 5 ) ; + } + + public org.omg.CORBA.portable.OutputStream _invoke (String method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler rh) + { + org.omg.CORBA.portable.OutputStream out = rh.createReply(); + java.lang.Integer __method = _methods.get (method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue ()) + { + + // Operation to obtain the IR from the sending context + case 0: // SendingContext/CodeBase/get_ir + { + com.sun.org.omg.CORBA.Repository __result = null; + __result = this.get_ir (); + com.sun.org.omg.CORBA.RepositoryHelper.write (out, __result); + break; + } + + + // Operations to obtain a URL to the implementation code + case 1: // SendingContext/CodeBase/implementation + { + String x = com.sun.org.omg.CORBA.RepositoryIdHelper.read (in); + String __result = null; + __result = this.implementation (x); + out.write_string (__result); + break; + } + + case 2: // SendingContext/CodeBase/implementations + { + String x[] = com.sun.org.omg.CORBA.RepositoryIdSeqHelper.read (in); + String __result[] = null; + __result = this.implementations (x); + com.sun.org.omg.SendingContext.CodeBasePackage.URLSeqHelper.write (out, __result); + break; + } + + + // the same information + case 3: // SendingContext/CodeBase/meta + { + String x = com.sun.org.omg.CORBA.RepositoryIdHelper.read (in); + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription __result = null; + __result = this.meta (x); + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.write (out, __result); + break; + } + + case 4: // SendingContext/CodeBase/metas + { + String x[] = com.sun.org.omg.CORBA.RepositoryIdSeqHelper.read (in); + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription __result[] = null; + __result = this.metas (x); + com.sun.org.omg.SendingContext.CodeBasePackage.ValueDescSeqHelper.write (out, __result); + break; + } + + + // information + case 5: // SendingContext/CodeBase/bases + { + String x = com.sun.org.omg.CORBA.RepositoryIdHelper.read (in); + String __result[] = null; + __result = this.bases (x); + com.sun.org.omg.CORBA.RepositoryIdSeqHelper.write (out, __result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private final static String[] __ids = { + "IDL:omg.org/SendingContext/CodeBase:1.0", + "IDL:omg.org/SendingContext/RunTime:1.0"}; + + public String[] _ids () + { + return __ids.clone(); + } + + +} // class _CodeBaseImplBase diff --git a/orbmain/src/main/java/com/sun/org/omg/SendingContext/_CodeBaseStub.java b/orbmain/src/main/java/com/sun/org/omg/SendingContext/_CodeBaseStub.java new file mode 100644 index 000000000..828133aa7 --- /dev/null +++ b/orbmain/src/main/java/com/sun/org/omg/SendingContext/_CodeBaseStub.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.org.omg.SendingContext; + + +/** +* com/sun/org/omg/SendingContext/_CodeBaseStub.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from rt.idl +* Thursday, May 6, 1999 1:52:08 AM PDT +*/ + +public class _CodeBaseStub extends org.omg.CORBA.portable.ObjectImpl implements com.sun.org.omg.SendingContext.CodeBase +{ + // Constructors + // NOTE: If the default constructor is used, the + // object is useless until _set_delegate (...) + // is called. + public _CodeBaseStub () + { + super (); + } + + public _CodeBaseStub (org.omg.CORBA.portable.Delegate delegate) + { + super (); + _set_delegate (delegate); + } + + + // Operation to obtain the IR from the sending context + public com.sun.org.omg.CORBA.Repository get_ir () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("get_ir", true); + _in = _invoke (_out); + com.sun.org.omg.CORBA.Repository __result = com.sun.org.omg.CORBA.RepositoryHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return get_ir (); + } finally { + _releaseReply (_in); + } + } // get_ir + + + // Operations to obtain a URL to the implementation code + public String implementation (String x) + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("implementation", true); + com.sun.org.omg.CORBA.RepositoryIdHelper.write (_out, x); + _in = _invoke (_out); + String __result = com.sun.org.omg.SendingContext.CodeBasePackage.URLHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return implementation (x); + } finally { + _releaseReply (_in); + } + } // implementation + + public String[] implementations (String[] x) + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("implementations", true); + com.sun.org.omg.CORBA.RepositoryIdSeqHelper.write (_out, x); + _in = _invoke (_out); + String __result[] = com.sun.org.omg.SendingContext.CodeBasePackage.URLSeqHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return implementations (x); + } finally { + _releaseReply (_in); + } + } // implementations + + + // the same information + public com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription meta (String x) + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("meta", true); + com.sun.org.omg.CORBA.RepositoryIdHelper.write (_out, x); + _in = _invoke (_out); + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription __result = com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescriptionHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return meta (x); + } finally { + _releaseReply (_in); + } + } // meta + + public com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription[] metas (String[] x) + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("metas", true); + com.sun.org.omg.CORBA.RepositoryIdSeqHelper.write (_out, x); + _in = _invoke (_out); + com.sun.org.omg.CORBA.ValueDefPackage.FullValueDescription __result[] = com.sun.org.omg.SendingContext.CodeBasePackage.ValueDescSeqHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return metas (x); + } finally { + _releaseReply (_in); + } + } // metas + + + // information + public String[] bases (String x) + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("bases", true); + com.sun.org.omg.CORBA.RepositoryIdHelper.write (_out, x); + _in = _invoke (_out); + String __result[] = com.sun.org.omg.CORBA.RepositoryIdSeqHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return bases (x); + } finally { + _releaseReply (_in); + } + } // bases + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/SendingContext/CodeBase:1.0", + "IDL:omg.org/SendingContext/RunTime:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) + { + try + { + String str = s.readUTF (); + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init ().string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } catch (java.io.IOException e) {} + } + + private void writeObject (java.io.ObjectOutputStream s) + { + try + { + String str = org.omg.CORBA.ORB.init ().object_to_string (this); + s.writeUTF (str); + } catch (java.io.IOException e) {} + } +} // class _CodeBaseStub diff --git a/orbmain/src/main/java/org/glassfish/corba/Bridge.java b/orbmain/src/main/java/org/glassfish/corba/Bridge.java new file mode 100644 index 000000000..9f296330c --- /dev/null +++ b/orbmain/src/main/java/org/glassfish/corba/Bridge.java @@ -0,0 +1,334 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba; + +import java.lang.reflect.Field ; +import java.lang.reflect.Method ; +import java.lang.reflect.Constructor ; +import java.lang.reflect.InvocationTargetException ; + +import java.io.ObjectInputStream ; + +import java.security.AccessController; +import java.security.Permission; +import java.security.PrivilegedAction; + +import sun.misc.Unsafe ; +import sun.reflect.ReflectionFactory ; + +/** This class provides the methods for fundamental JVM operations + * needed in the ORB that are not part of the public Java API. This includes: + *

                  + *
                • throwException, which can throw undeclared checked exceptions. + * This is needed to handle throwing arbitrary exceptions across a standardized OMG interface that (incorrectly) does not specify appropriate exceptions.
                • + *
                • putXXX/getXXX methods that allow unchecked access to fields of objects. + * This is used for setting uninitialzed non-static final fields (which is + * impossible with reflection) and for speed.
                • + *
                • objectFieldOffset to obtain the field offsets for use in the putXXX/getXXX methods
                • + *
                • newConstructorForSerialization to get the special constructor required for a + * Serializable class
                • + *
                • latestUserDefinedLoader to get the latest user defined class loader from + * the call stack as required by the RMI-IIOP specification (really from the + * JDK 1.1 days)
                • + *
                + * The code that calls Bridge.get() must have the following Permissions: + *
                  + *
                • RuntimePermission "reflectionFactoryAccess"
                • + *
                • BridgePermission "getBridge"
                • + *
                • ReflectPermission "suppressAccessChecks"
                • + *
                + *

                + * All of these permissions are required to obtain and correctly initialize + * the instance of Bridge. No security checks are performed on calls + * made to Bridge instance methods, so access to the Bridge instance + * must be protected. + *

                + * This class is a singleton (per ClassLoader of course). Access to the + * instance is obtained through the Bridge.get() method. + */ +public final class Bridge +{ + private static final Permission getBridgePermission = + new BridgePermission( "getBridge" ) ; + private static Bridge bridge = null ; + + // latestUserDefinedLoader() is a private static method + // in ObjectInputStream in JDK 1.3 through 1.5. + // We use reflection in a doPrivileged block to get a + // Method reference and make it accessible. + private final Method latestUserDefinedLoaderMethod ; + private final Unsafe unsafe ; + private final ReflectionFactory reflectionFactory ; + + private Method getLatestUserDefinedLoaderMethod() { + return AccessController.doPrivileged( + new PrivilegedAction() { + @SuppressWarnings("unchecked") + public Method run() { + Method result = null; + + try { + Class io = ObjectInputStream.class; + result = io.getDeclaredMethod( + "latestUserDefinedLoader"); + result.setAccessible(true); + } catch (NoSuchMethodException nsme) { + throw new Error("java.io.ObjectInputStream" + + " latestUserDefinedLoader " + nsme, nsme) ; + } + + return result; + } + } + ); + } + + private Unsafe getUnsafe() { + Field fld = AccessController.doPrivileged( + new PrivilegedAction() { + public Field run() { + try { + Class unsafeClass = sun.misc.Unsafe.class ; + Field fld = unsafeClass.getDeclaredField( "theUnsafe" ) ; + fld.setAccessible( true ) ; + return fld ; + } catch (NoSuchFieldException exc) { + throw new Error("Could not access Unsafe", exc) ; + } + } + } + ) ; + + Unsafe theUnsafe = null; + + try { + theUnsafe = Unsafe.class.cast( fld.get( null ) ) ; + } catch (Throwable t) { + throw new Error("Could not access Unsafe", t) ; + } + + return theUnsafe ; + } + + + @SuppressWarnings("unchecked") + private Bridge() { + latestUserDefinedLoaderMethod = getLatestUserDefinedLoaderMethod(); + unsafe = getUnsafe() ; + reflectionFactory = ReflectionFactory.getReflectionFactory(); + } + + /** Fetch the Bridge singleton. This requires the following + * permissions: + *

                  + *
                • RuntimePermission "reflectionFactoryAccess"
                • + *
                • BridgePermission "getBridge"
                • + *
                • ReflectPermission "suppressAccessChecks"
                • + *
                + * @return The singleton instance of the Bridge class + * @throws SecurityException if the caller does not have the + * required permissions and the caller has a non-null security manager. + */ + public static synchronized Bridge get() + { + SecurityManager sman = System.getSecurityManager() ; + if (sman != null) { + sman.checkPermission(getBridgePermission); + } + + if (bridge == null) { + bridge = new Bridge() ; + } + + return bridge ; + } + + /** Obtain the latest user defined ClassLoader from the call stack. + * This is required by the RMI-IIOP specification. + */ + public final ClassLoader getLatestUserDefinedLoader() + { + try { + // Invoke the ObjectInputStream.latestUserDefinedLoader method + return (ClassLoader)latestUserDefinedLoaderMethod.invoke(null); + } catch (InvocationTargetException ite) { + throw new Error("sun.corba.Bridge.latestUserDefinedLoader: " + ite, + ite) ; + } catch (IllegalAccessException iae) { + throw new Error("sun.corba.Bridge.latestUserDefinedLoader: " + iae, + iae) ; + } + } + + /** + * Fetches a field element within the given + * object o at the given offset. + * The result is undefined unless the offset was obtained from + * {@link #objectFieldOffset} on the {@link java.lang.reflect.Field} + * of some Java field and the object referred to by o + * is of a class compatible with that field's class. + * @param o Java heap object in which the field from which the offset + * was obtained resides + * @param offset indication of where the field resides in a Java heap + * object + * @return the value fetched from the indicated Java field + * @throws RuntimeException No defined exceptions are thrown, not even + * {@link NullPointerException} + */ + public final int getInt(Object o, long offset) + { + return unsafe.getInt( o, offset ) ; + } + + /** + * Stores a value into a given Java field. + *

                + * The first two parameters are interpreted exactly as with + * {@link #getInt(Object, long)} to refer to a specific + * Java field. The given value is stored into that field. + *

                + * The field must be of the same type as the method + * parameter x. + * + * @param o Java heap object in which the field resides, if any, else + * null + * @param offset indication of where the field resides in a Java heap + * object. + * @param x the value to store into the indicated Java field + * @throws RuntimeException No defined exceptions are thrown, not even + * {@link NullPointerException} + */ + public final void putInt(Object o, long offset, int x) + { + unsafe.putInt( o, offset, x ) ; + } + + /** + * @see #getInt(Object, long) + */ + public final Object getObject(Object o, long offset) + { + return unsafe.getObject( o, offset ) ; + } + + /** + * @see #putInt(Object, long, int) + */ + public final void putObject(Object o, long offset, Object x) + { + unsafe.putObject( o, offset, x ) ; + } + + /** @see #getInt(Object, long) */ + public final boolean getBoolean(Object o, long offset) + { + return unsafe.getBoolean( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putBoolean(Object o, long offset, boolean x) + { + unsafe.putBoolean( o, offset, x ) ; + } + /** @see #getInt(Object, long) */ + public final byte getByte(Object o, long offset) + { + return unsafe.getByte( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putByte(Object o, long offset, byte x) + { + unsafe.putByte( o, offset, x ) ; + } + /** @see #getInt(Object, long) */ + public final short getShort(Object o, long offset) + { + return unsafe.getShort( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putShort(Object o, long offset, short x) + { + unsafe.putShort( o, offset, x ) ; + } + /** @see #getInt(Object, long) */ + public final char getChar(Object o, long offset) + { + return unsafe.getChar( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putChar(Object o, long offset, char x) + { + unsafe.putChar( o, offset, x ) ; + } + /** @see #getInt(Object, long) */ + public final long getLong(Object o, long offset) + { + return unsafe.getLong( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putLong(Object o, long offset, long x) + { + unsafe.putLong( o, offset, x ) ; + } + /** @see #getInt(Object, long) */ + public final float getFloat(Object o, long offset) + { + return unsafe.getFloat( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putFloat(Object o, long offset, float x) + { + unsafe.putFloat( o, offset, x ) ; + } + /** @see #getInt(Object, long) */ + public final double getDouble(Object o, long offset) + { + return unsafe.getDouble( o, offset ) ; + } + /** @see #putInt(Object, long, int) */ + public final void putDouble(Object o, long offset, double x) + { + unsafe.putDouble( o, offset, x ) ; + } + + /** + * This constant differs from all results that will ever be returned from + * {@link #objectFieldOffset}. + */ + public static final long INVALID_FIELD_OFFSET = -1; + + /** + * Returns the offset of a non-static field. + */ + public final long objectFieldOffset(Field f) + { + return unsafe.objectFieldOffset( f ) ; + } + + /** Throw the exception. + * The exception may be an undeclared checked exception. + */ + public final void throwException(Throwable ee) + { + unsafe.throwException( ee ) ; + } + + /** Obtain a constructor for Class cl using constructor cons which + * may be the constructor defined in a superclass of cl. This is + * used to create a constructor for Serializable classes that + * constructs an instance of the Serializable class using the + * no args constructor of the first non-Serializable superclass + * of the Serializable class. + */ + @SuppressWarnings("unchecked") + public final Constructor newConstructorForSerialization(Class cl, Constructor cons) { + return (Constructor) reflectionFactory.newConstructorForSerialization( cl, cons ) ; + } +} diff --git a/orbmain/src/main/java/org/glassfish/corba/BridgePermission.java b/orbmain/src/main/java/org/glassfish/corba/BridgePermission.java new file mode 100644 index 000000000..ba54bd9cd --- /dev/null +++ b/orbmain/src/main/java/org/glassfish/corba/BridgePermission.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba; + +import java.security.BasicPermission ; + +/** Permission class used to protect access to the sun.corba.Bridge + * object. The only name valid here is "getBridge". The + * BridgePermission("getBridge") permission must be held by the + * caller of sun.corba.Bridge.get(). + */ +public final class BridgePermission extends BasicPermission +{ + /** + * Creates a new BridgePermission with the specified name. + * The name is the symbolic name of the BridgePermission. + * The only valid name here is "getBridge". + * + * @param name the name of the BridgePermission. + */ + public BridgePermission(String name) + { + super(name); + } + + /** + * Creates a new BridgePermission object with the specified name. + * The name is the symbolic name of the BridgePermission, and the + * actions String is currently unused and should be null. + * The only valid name here is "getBridge". + * + * @param name the name of the BridgePermission. + * @param actions should be null. + */ + + public BridgePermission(String name, String actions) + { + super(name, actions); + } +} diff --git a/orbmain/src/main/java/org/glassfish/corba/org/omg/CORBA/_IDLTypeStub.java b/orbmain/src/main/java/org/glassfish/corba/org/omg/CORBA/_IDLTypeStub.java new file mode 100644 index 000000000..b4e0c6b6f --- /dev/null +++ b/orbmain/src/main/java/org/glassfish/corba/org/omg/CORBA/_IDLTypeStub.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba.org.omg.CORBA; + + +/** +* com/sun/org/omg/CORBA/_IDLTypeStub.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* Thursday, May 6, 1999 1:51:45 AM PDT +*/ + +// This file has been manually _CHANGED_ + +// _CHANGED_ +//public class _IDLTypeStub extends org.omg.CORBA.portable.ObjectImpl implements com.sun.org.omg.CORBA.IDLType +public class _IDLTypeStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.CORBA.IDLType +{ + // Constructors + // NOTE: If the default constructor is used, the + // object is useless until _set_delegate (...) + // is called. + public _IDLTypeStub () + { + super (); + } + + public _IDLTypeStub (org.omg.CORBA.portable.Delegate delegate) + { + super (); + _set_delegate (delegate); + } + + public org.omg.CORBA.TypeCode type () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("_get_type", true); + _in = _invoke (_out); + org.omg.CORBA.TypeCode __result = _in.read_TypeCode (); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return type (); + } finally { + _releaseReply (_in); + } + } // type + + + // read interface + // _CHANGED_ + //public com.sun.org.omg.CORBA.DefinitionKind def_kind () + public org.omg.CORBA.DefinitionKind def_kind () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("_get_def_kind", true); + _in = _invoke (_out); + // _CHANGED_ + //com.sun.org.omg.CORBA.DefinitionKind __result = com.sun.org.omg.CORBA.DefinitionKindHelper.read (_in); + org.omg.CORBA.DefinitionKind __result = com.sun.org.omg.CORBA.DefinitionKindHelper.read (_in); + return __result; + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + return def_kind (); + } finally { + _releaseReply (_in); + } + } // def_kind + + + // write interface + public void destroy () + { + org.omg.CORBA.portable.InputStream _in = null; + try { + org.omg.CORBA.portable.OutputStream _out = _request ("destroy", true); + _in = _invoke (_out); + } catch (org.omg.CORBA.portable.ApplicationException _ex) { + _in = _ex.getInputStream (); + String _id = _ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException _rm) { + destroy (); + } finally { + _releaseReply (_in); + } + } // destroy + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:omg.org/CORBA/IDLType:1.0", + "IDL:omg.org/CORBA/IRObject:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) + { + try + { + String str = s.readUTF (); + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init ().string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } catch (java.io.IOException e) {} + } + + private void writeObject (java.io.ObjectOutputStream s) + { + try + { + String str = org.omg.CORBA.ORB.init ().object_to_string (this); + s.writeUTF (str); + } catch (java.io.IOException e) {} + } +} // class _IDLTypeStub diff --git a/orbmain/src/main/java/org/glassfish/corba/package.html b/orbmain/src/main/java/org/glassfish/corba/package.html new file mode 100644 index 000000000..cece2bd01 --- /dev/null +++ b/orbmain/src/main/java/org/glassfish/corba/package.html @@ -0,0 +1,22 @@ + + + + + + package + + +Provides an internal API that the Sun ORB implementation uses to +access JVM functions that have no standard APIs. + + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb.properties new file mode 100644 index 000000000..e9d42f4e9 --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb.properties @@ -0,0 +1,178 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=Usage: {0} \ +\n\ +\nwhere includes:\ +\n -port Activation Port where the ORBD should be started, default 1049 (optional)\ +\n -defaultdb Directory for ORBD files, default "./orb.db" (optional)\ +\n -serverid Server Id for ORBD, default 1 (optional)\ +\n -ORBInitialPort Initial Port (required)\ +\n -ORBInitialHost Initial HostName (required)\ +\n\ + + +servertool.usage=Usage: {0} \ +\n\ +\nwhere includes:\ +\n -ORBInitialPort Initial Port (required)\ +\n -ORBInitialHost Initial HostName (required)\ +\n\ + +servertool.banner=\ +\n\ +\nWelcome to the Java IDL Server Tool \ +\nplease enter commands at the prompt \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\tAvailable Commands: \ +\n\t------------------- \ +\n\ + +servertool.baddef=Bad server definition: {0} +servertool.nosuchserver=\tno such server found. +servertool.helddown=\tserver is held down. +servertool.nosuchorb=\tinvalid ORB. +servertool.serverup=\tserver is already up. +servertool.appname=\tapplicationName - {0} +servertool.name=\tname - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targs - {0} +servertool.vmargs=\tvmargs - {0} +servertool.serverid=\tserver id - {0} +servertool.servernotrunning=\tserver is not running. +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=register an activatable server +servertool.register2=\tserver registered (serverid = {0}). +servertool.register3=\tserver registerd but held down (serverid = {0}). +servertool.register4=\tserver already registered (serverid = {0}). + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=unregister a registered server +servertool.unregister2=\tserver unregistered. + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=locate ports of specific type for a registered server +servertool.locate2=\ +\n\ +\n\tHost Name {0} \ +\n\ +\n\t\tPort\t\tPort Type\t\tORB Id\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=locate ports for a specific orb of registered server +servertool.locateorb2=\ +\n\ +\n\tHost Name {0} \ +\n\ +\n\t\tPort\t\tPortType\t\tORB Id\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=return the server id for an applicationName +servertool.getserverid2=\tServer ID for applicationName {0} is {1} + +servertool.list=\n\tlist\ +\n\ + +servertool.list1=list all registered servers +servertool.list2=\ +\n\tServer Id\tServer Class Name\t\tServer Application\ +\n\t---------\t-----------------\t\t------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=list currently active servers +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=list applicationNames currently defined +servertool.listappnames2=Currently defined server applicationNames: + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=shutdown a registered server +servertool.shutdown2=\tserver sucessfully shutdown. +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=start a registered server +servertool.startserver2=\tserver sucessfully started up. + +servertool.quit=\n\tquit\n +servertool.quit1=quit this tool + +servertool.help=\thelp\ +\n\tOR\ +\n\thelp \ +\n\ + +servertool.help1=get help + +servertool.orbidmap=\tUsage: orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=list of orb names and their mapping +servertool.orbidmap2=\ +\n\tORB Id\t\tORB Name\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=Persistent NameServer Started Successfully + + +bootstrap.usage=Usage: {0} \ +\n\ +\nwhere includes:\ +\n -ORBInitialPort Initial Port (required)\ +\n -InitialServicesFile File containing list of initial services (required)\ +\n\ + +bootstrap.success=setting port to {0} and reading services from {1} +bootstrap.filenotreadable=the file {0} is not readable +bootstrap.filenotfound=the file {0} not found +bootstrap.exception=caught exception while saving Properties to file {0}: Exception {1} + +tnameserv.exception=caught an exception while starting the bootstrap service on port {0} +tnameserv.usage=try using a different port with commandline arguments -ORBInitialPort +tnameserv.invalidhostoption=ORBInitialHost is not a valid option for NameService +tnameserv.orbinitialport0=ORBInitialPort 0 is not valid option for NameService +tnameserv.hs1=Initial Naming Context:\n{0} +tnameserv.hs2=TransientNameServer: setting port for initial object references to: {0} +tnameserv.hs3=Ready. + +orbd.commfailure=\nFailed to start ORBD because ORBinitialPort is already in use +orbd.internalexception=\nFailed to start ORBD because of an Internal Exception. \nPossible Causes: \n1. Specified ORBInitialPort or ORBActivationPort is already in use \n2. No Write Permission to write orb.db + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_de.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_de.properties new file mode 100644 index 000000000..7de634d22 --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_de.properties @@ -0,0 +1,177 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=Syntax: {0} \ +\n\ +\nwobei folgende m\u00f6glich sind:\ +\n -port Aktivierungsport, an dem der ORBD gestartet werden sollte, Standardvorgabe 1049 (optional)\ +\n -defaultdb Verzeichnis f\u00fcr ORBD-Dateien, Standardvorgabe "./orb.db" (optional)\ +\n -serverid Server-ID f\u00fcr ORBD, Standardvorgabe 1 (optional)\ +\n -ORBInitialPort Anfangsport (erforderlich)\ +\n -ORBInitialHost Anf\u00e4nglicher Rechnername (erforderlich)\ +\n\ + + +servertool.usage=Syntax: {0} \ +\n\ +\nwobei folgende m\u00f6glich sind:\ +\n -ORBInitialPort Anfangsport (erforderlich)\ +\n -ORBInitialHost Anf\u00e4nglicher Rechnername (erforderlich)\ +\n\ + +servertool.banner=\ +\n\ +\nWillkommen beim Java IDL-Server-Tool \ +\nBitte geben Sie an der Eingabeaufforderung Befehle ein. \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\tVerf\u00fcgbare Befehle: \ +\n\t------------------- \ +\n\ + +servertool.baddef=Fehlerhafte Serverdefinition: {0} +servertool.nosuchserver=\tDer Server wurde nicht gefunden. +servertool.helddown=\tServer ist au\u00dfer Betrieb. +servertool.nosuchorb=\tUng\u00fcltige ORB +servertool.serverup=\tServer ist bereits in Betrieb. +servertool.appname=\tAnwendungsname - {0} +servertool.name=\tName - {0} +servertool.classpath=\tKlassenpfad - {0} +servertool.args=\tArgs - {0} +servertool.vmargs=\tVmargs - {0} +servertool.serverid=\tServer-ID - {0} +servertool.servernotrunning=\tServer l\u00e4uft nicht. +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=aktivierbaren Server registrieren +servertool.register2=\tServer registriert (serverid = {0}) +servertool.register3=\tServer registriert, aber au\u00dfer Betrieb (serverid = {0}) +servertool.register4=\tServer bereits registriert (serverid = {0}) + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=Registrierung eines registrierten Servers l\u00f6schen +servertool.unregister2=\tServer-Registrierung gel\u00f6scht + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=Finden von Ports eines speziellen Typs bei einem registrierten Server +servertool.locate2=\ +\n\ +\n\tHostname {0} \ +\n\ +\n\t\tPort\t\tPorttyp\t\tORB-ID\ +\n\t\t----\t\t-------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=Finden von Ports eines speziellen ORBs bei einem registrierten Server +servertool.locateorb2=\ +\n\ +\n\tHostname {0} \ +\n\ +\n\t\tPort\t\tPorttyp\t\tORB-ID\ +\n\t\t----\t\t-------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=\u00dcbergeben der Server-ID f\u00fcr einen Anwendungsnamen +servertool.getserverid2=\tServer-ID f\u00fcr Anwendungsname {0} ist {1}. + +servertool.list=\n\tlist\ +\n\ + +servertool.list1=Auflisten aller registrierten Server +servertool.list2=\ +\n\tServer-ID\tServer-Klassenname\t\tServer-Anwendung\ +\n\t---------\t------------------\t\t----------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=Auflisten der gegenw\u00e4rtig aktiven Server +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=Auflisten der gegenw\u00e4rtig definierten Anwendungsnamen +servertool.listappnames2=Gegenw\u00e4rtig definierte Serveranwendungsnamen: + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=Herunterfahren eines registrierten Servers +servertool.shutdown2=\tServer erfolgreich heruntergefahren +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=Hochfahren eines registrierten Servers +servertool.startserver2=\tServer erfolgreich hochgefahren + +servertool.quit=\n\tquit\n +servertool.quit1=Dieses Tool beenden + +servertool.help=\thelp\ +\n\tOR\ +\n\thelp \ +\n\ + +servertool.help1=Hilfe anfordern + +servertool.orbidmap=\tSyntax: orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=Liste von ORB-Namen und ihren Zuordnungen +servertool.orbidmap2=\ +\n\tORB-ID\t\tORB-Name\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=St\u00e4ndiger Namensserver erfolgreich hochgefahren + + +bootstrap.usage=Syntax: {0} \ +\n\ +\nwobei folgende m\u00f6glich sind:\ +\n -ORBInitialPort Erster Port (erforderlich)\ +\n -InitialServicesFile Datei mit Liste von Anfangsdiensten (erforderlich)\ +\n\ + +bootstrap.success=Ein Port wird auf {0} eingestellt, und Dienste werden von {1} gelesen +bootstrap.filenotreadable=Die Datei {0} kann nicht gelesen werden. +bootstrap.filenotfound=Die Datei {0} wurde nicht gefunden. +bootstrap.exception=Beim Speichern von Eigenschaften in Datei {0} wurde eine Ausnahme aufgefangen: Ausnahme {1}. + +tnameserv.exception=Beim Hochfahren des Bootstrap-Dienstes auf Port {0} wurde eine Ausnahme aufgefangen. +tnameserv.usage=Versuchen Sie, einen anderen Port mit den Befehlszeilenargumenten -ORBInitialPort zu verwenden. +tnameserv.invalidhostoption=ORBInitialHost ist keine g\u00fcltige Option f\u00fcr NameService +tnameserv.orbinitialport0=ORBInitialPort 0 ist keine g\u00fcltige Option f\u00fcr NameService +tnameserv.hs1=Anf\u00e4nglicher Namenskontext:\n{0} +tnameserv.hs2=\u00dcbergangsnamensserver: Port f\u00fcr anf\u00e4ngliche Objektreferenzen wird eingestellt auf: {0} +tnameserv.hs3=Bereit + + + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_es.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_es.properties new file mode 100644 index 000000000..2497f3247 --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_es.properties @@ -0,0 +1,177 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=Sintaxis: {0} \ +\n\ +\ndonde incluye:\ +\n -port Puerto de activaci\u00f3n en el que se debe iniciar el ORBD, el predeterminado es el 1049 (opcional)\ +\n -defaultdb Directorio para los archivos de ORBD, el predeterminado es "./orb.db" (opcional)\ +\n -serverid Identificador de servidor para ORBD, el predeterminado es 1 (opcional)\ +\n -ORBInitialPort Puerto inicial (necesario)\ +\n -ORBInitialHost Nombre de sistema inicial (necesario)\ +\n\ + + +servertool.usage=Sintaxis: {0} \ +\n\ +\ndonde incluye:\ +\n -ORBInitialPort Puerto inicial (necesario)\ +\n -ORBInitialHost Nombre de sistema inicial (necesario)\ +\n\ + +servertool.banner=\ +\n\ +\nBienvenido Java IDL Server Tool \ +\nescriba los comandos en el indicador \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\tComandos disponibles: \ +\n\t------------------- \ +\n\ + +servertool.baddef=Definici\u00f3n de servidor incorrecta: {0} +servertool.nosuchserver=\tno se ha encontrado el servidor. +servertool.helddown=\tel servidor se mantiene desconectado. +servertool.nosuchorb=\tORB no v\u00e1lido. +servertool.serverup=\tel servidor ya est\u00e1 conectado. +servertool.appname=\tnombre de aplicaci\u00f3n - {0} +servertool.name=\tnombre - {0} +servertool.classpath=\truta de clase - {0} +servertool.args=\targumentos - {0} +servertool.vmargs=\targumentos de MV - {0} +servertool.serverid=\tidentificador de servidor - {0} +servertool.servernotrunning=\tel servidor no se est\u00e1 ejecutando. +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=registrar un servidor que se pueda activar +servertool.register2=\tservidor registrado (identificador de servidor = {0}). +servertool.register3=\tservidor registrado pero desconectado (identificador de servidor = {0}). +servertool.register4=\tservidor ya registrado (identificador de servidor = {0}). + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=anular el registro de un servidor registrado +servertool.unregister2=\tanulado el registro del servidor. + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=localizar puertos de un tipo espec\u00edfico para un servidor registrado +servertool.locate2=\ +\n\ +\n\tNombre de sistema {0} \ +\n\ +\n\t\tPuerto\t\tTipo de puerto\t\tIdentificador ORB\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=localizar puertos para un ORB espec\u00edfico del servidor registrado +servertool.locateorb2=\ +\n\ +\n\tNombre de sistema {0} \ +\n\ +\n\t\tPuerto\t\tTipo de puerto\t\tIdentificador de ORB\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=devolver el identificador de servidor para un nombre de aplicaci\u00f3n +servertool.getserverid2=\tIdentificador de servidor para el nombre de aplicaci\u00f3n {0} es {1} + +servertool.list=\n\tlista\ +\n\ + +servertool.list1=enumerar todos los servidores registrados +servertool.list2=\ +\n\tIdentificador de servidor\tNombre de clase del servidor\t\tAplicaci\u00f3n de servidor\ +\n\t-------------------------\t----------------------------\t\t----------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=enumerar los servidores actualmente activos +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=enumerar los nombres de aplicaci\u00f3n actualmente definidos +servertool.listappnames2=Nombres de aplicaci\u00f3n de servidor actualmente definidos: + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=apagar un servidor registrado +servertool.shutdown2=\tservidor apagado satisfactoriamente. +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=iniciar un servidor registrado +servertool.startserver2=\tservidor iniciado satisfactoriamente. + +servertool.quit=\n\tsalir\n +servertool.quit1=salir de esta herramienta + +servertool.help=\thelp\ +\n\tO\ +\n\thelp \ +\n\ + +servertool.help1=obtener ayuda + +servertool.orbidmap=\tSintaxis: orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=lista de nombres de ORB y su reasignaci\u00f3n +servertool.orbidmap2=\ +\n\tIdentificador de ORB\t\tNombre de ORB\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=Servidor de nombres constante iniciado satisfactoriamente + + +bootstrap.usage=Sintaxis: {0} \ +\n\ +\ndonde incluye:\ +\n -ORBInitialPort Puerto inicial (necesario)\ +\n -InitialServicesFile Archivo que contiene una lista de los servicios iniciales (necesario)\ +\n\ + +bootstrap.success=estableciendo puerto en {0} y leyendo servicios de {1} +bootstrap.filenotreadable=el archivo {0} no se puede leer +bootstrap.filenotfound=no se ha encontrado el archivo {0} +bootstrap.exception=se ha interceptado una excepci\u00f3n al guardar las propiedades en el archivo {0}: Excepci\u00f3n {1} + +tnameserv.exception=se ha interceptado una excepci\u00f3n al iniciar el servicio de rutina de carga en el puerto {0} +tnameserv.usage=intente utilizar un puerto distinto con argumentos de l\u00ednea de comandos -ORBInitialPort +tnameserv.invalidhostoption=ORBInitialHost no es una opci\u00f3n v\u00e1lida para NameService +tnameserv.orbinitialport0=ORBInitialPort 0 no es una opci\u00f3n v\u00e1lida para NameService +tnameserv.hs1=Contexto de asignaci\u00f3n de nombres inicial:\n{0} +tnameserv.hs2=TransientNameServer: estableciendo puerto para referencias a objeto iniciales en: {0} +tnameserv.hs3=Listo. + + + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_fr.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_fr.properties new file mode 100644 index 000000000..44c1b845c --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_fr.properties @@ -0,0 +1,174 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=Syntaxe : {0} \ +\n\ +\no\u00f9 comprend :\ +\n -port Port d''activation o\u00f9 le ORBD doit \u00eatre d\u00e9marr\u00e9, 1049 par d\u00e9faut (facultatif)\ +\n -defaultdb R\u00e9pertoire des fichiers ORBD, par d\u00e9faut "./orb.db" (facultatif)\ +\n -serverid ID de serveur pour ORBD, 1 (facultatif)\ +\n -ORBInitialPort Port initial (requis)\ +\n -ORBInitialHost Nom d''h\u00f4te initial (requis)\ +\n\ + + +servertool.usage=Syntaxe : {0} \ +\n\ +\no\u00f9 comprend :\ +\n -ORBInitialPort Port initial (requis)\ +\n -ORBInitialHost Nom d''h\u00f4te initial (requis)\ +\n\ + +servertool.banner=\ +\n\ +\nBienvenue dans l'outil Java IDL Server Tool \ +\nSp\u00e9cifiez des commandes \u00e0 l'invite \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\tCommandes disponibles : \ +\n\t------------------- \ +\n\ + +servertool.baddef=D\u00e9finition de serveur non valide : {0} +servertool.nosuchserver=\tce serveur est introuvable. +servertool.helddown=\tserveur interrompu. +servertool.nosuchorb=\tORB non valide. +servertool.serverup=\tle serveur fonctionne d\u00e9j\u00e0. +servertool.appname=\tNom d''application - {0} +servertool.name=\tnom - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targs - {0} +servertool.vmargs=\tvmargs - {0} +servertool.serverid=\tserver id - {0} +servertool.servernotrunning=\tLe serveur ne fonctionne pas. +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=inscrire un serveur activable +servertool.register2=\tserveur inscrit (ID serveur = {0}). +servertool.register3=\tserveur inscrit mais interrompu (ID serveur = {0}). +servertool.register4=\tserveur d\u00e9j\u00e0 inscrit (ID serveur = {0}). + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=d\u00e9sinscrire un serveur inscrit +servertool.unregister2=\tserveur d\u00e9sinscrit. + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=rep\u00e9rer des ports de type sp\u00e9cifique d'un serveur inscrit +servertool.locate2=\ +\n\ +\n\tNom d''h\u00f4te {0} \ +\n\ +\n\t\tPort\t\tType de port\t\tID ORB\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=rep\u00e9rer les ports d'un ORB sp\u00e9cifique de serveurs inscrits +servertool.locateorb2=\ +\n\ +\n\tNom d''h\u00f4te {0} \ +\n\ +\n\t\tPort\t\tType de port\t\tID ORB\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=renvoyer l'ID serveur pour un applicationName +servertool.getserverid2=\tL''ID serveur de applicationName {0} est {1} + +servertool.list=\n\tlist +\n\ + +servertool.list1=lister tous les serveurs inscrits +servertool.list2=\ +\n\tID serveur\tNom de classe serveur\t\tApplication serveur\ +\n\t---------\t-----------------\t\t------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=lister les serveurs actifs +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=lister les noms d'application d\u00e9finis +servertool.listappnames2=noms d'application du serveur d\u00e9finis : + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=arr\u00eater un serveur inscrit +servertool.shutdown2=\tserveur arr\u00eat\u00e9. +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=d\u00e9marrer un serveur inscrit +servertool.startserver2=\tserveur d\u00e9marr\u00e9. + +servertool.quit=\n\tquit\n +servertool.quit1=fermer cet outil + +servertool.help=\thelp\ +\n\tOR\ +\n\thelp \ +\n\ + +servertool.help1=afficher l'aide + +servertool.orbidmap=\tSyntaxe : orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=liste des noms orb et de leur mappage +servertool.orbidmap2=\ +\n\tID ORB\t\tNom ORB\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=NameServer persistant d\u00e9marr\u00e9 + + +bootstrap.usage=Syntaxe : {0} \ +\n\ +\no\u00f9 comprend :\ +\n -ORBInitialPort Port initial (requis)\ +\n -InitialServicesFile Fichier contenant la liste des services initiaux (requis)\ +\n\ + +bootstrap.success=configuration du port sur {0} et lecture des services de {1} +bootstrap.filenotreadable=le fichier {0} n''est pas lisible +bootstrap.filenotfound=fichier {0} introuvable +bootstrap.exception=erreur d\u00e9tect\u00e9e pendant l''enregistrement des propri\u00e9t\u00e9s dans le fichier {0} : Erreur {1} + +tnameserv.exception=Erreur d\u00e9tect\u00e9e pendant le d\u00e9marrage du service d''amor\u00e7age sur le port {0} +tnameserv.usage=essayez un autre port avec les arguments de ligne de commande -ORBInitialPort +tnameserv.invalidhostoption=ORBInitialHost n'est pas une option valide pour NameService +tnameserv.orbinitialport0=ORBInitialPort 0 n'est pas une option valide pour NameService +tnameserv.hs1=Contexte d''appellation initial :\n{0} +tnameserv.hs2=TransientNameServer : configuration du port pour des r\u00e9f\u00e9rences d''objet initial \u00e0 : {0} +tnameserv.hs3=Pr\u00eat. diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_it.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_it.properties new file mode 100644 index 000000000..0b00af16b --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_it.properties @@ -0,0 +1,178 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=Utilizzo: {0} \ +\n\ +\ndove comprende:\ +\n -port Porta di attivazione da cui avviare ORBD, default 1049 (opzionale)\ +\n -defaultdb Directory per i file ORBD, default "./orb.db" (opzionale)\ +\n -serverid Id server per ORBD, default 1 (opzionale)\ +\n -ORBInitialPort Porta iniziale (richiesta)\ +\n -ORBInitialHost Nome host iniziale (richiesto)\ +\n\ + + +servertool.usage=Utilizzo: {0} \ +\n\ +\ndove comprende:\ +\n -ORBInitialPort Porta iniziale (richiesta)\ +\n -ORBInitialHost Nome host iniziale (richiesto)\ +\n\ + +servertool.banner=\ +\n\ +\nBenvenuti a Java IDL Server Tool \ +\nimmettere i comandi quando richiesto \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\tComandi disponibili:\ +\n\t-------------------- \ +\n\ + +servertool.baddef=Definizione server errata: {0} +servertool.nosuchserver=\timpossibile trovare il server indicato. +servertool.helddown=\til server \u00e8 mantenuto inattivo. +servertool.nosuchorb=\tORB non valido. +servertool.serverup=\til server \u00e8 gi\u00e0 attivo. +servertool.appname=\tNomeApplicazione - {0} +servertool.name=\tnome - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targom - {0} +servertool.vmargs=\targomvm - {0} +servertool.serverid=\tid server - {0} +servertool.servernotrunning=\til server non \u00e8 in funzione. +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=registra un server attivabile +servertool.register2=\tserver registrato (idserver = {0}). +servertool.register3=\tserver registrato ma mantenuto inattivo (idserver = {0}). +servertool.register4=\tserver gi\u00e0 registrato (idserver = {0}). + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=rimuovi un server registrato. +servertool.unregister2=\tserver rimosso dal registro. + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=individua le porte di un tipo specifico per un server registrato +servertool.locate2=\ +\n\ +\n\tNome host {0} \ +\n\ +\n\t\tPorta\t\tTipo porta\t\tId ORB\ +\n\t\t-----\t\t----------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=individua le porte per un orb specifico di un server registrato +servertool.locateorb2=\ +\n\ +\n\tNome host {0} \ +\n\ +\n\t\tPorta\t\tTipoPorta\t\tId ORB\ +\n\t\t-----\t\t---------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=restituisce l'id server per un applicationName +servertool.getserverid2=\tL''ID server per applicationName {0} \u00e8 {1} + +servertool.list=\n\tlist\ +\n\ + +servertool.list1=elenca tutti i server registrati +servertool.list2=\ +\n\tID server\tNome classe server\t\tApplicazione server\ +\n\t---------\t------------------\t\t-------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=elenca i server attualmente attivi +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=elenca gli applicationName attualmente definiti +servertool.listappnames2=applicationName del server attualmente definiti: + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=arresta un server registrato +servertool.shutdown2=\tserver arrestato correttamente +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=avvia un server registrato +servertool.startserver2=\tserver avviato correttamente. + +servertool.quit=\n\tquit\n +servertool.quit1=esci dall'applicazione corrente + +servertool.help=\thelp\ +\n\tOR\ +\n\thelp \ +\n\ + +servertool.help1=get help + +servertool.orbidmap=\tUtilizzo: orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=elenco dei nomi orb e relativa mappatura +servertool.orbidmap2=\ +\n\tId ORB\t\tNome ORB\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=NameServer persistente avviato correttamente + + +bootstrap.usage=Utilizzo: {0} \ +\n\ +\ndove comprende:\ +\n -ORBInitialPort Porta iniziale (richiesta)\ +\n -InitialServicesFile File contenente l''elenco dei servizi iniziali (richiesto)\ +\n\ + +bootstrap.success=impostazione porta su {0} e lettura servizi da {1} in corso +bootstrap.filenotreadable=il file {0} non \u00e8 leggibile +bootstrap.filenotfound=impossibile trovare il file {0} +bootstrap.exception=rilevata un''eccezione durante il salvataggio delle propriet\u00e0 nel file {0}: eccezione {1} + + +tnameserv.exception=rilevata un''eccezione durante l''avvio del servizio di bootstrap sulla porta {0} +tnameserv.usage=utilizzare un'altra porta con gli argomenti di riga di comando -ORBInitialPort +tnameserv.invalidhostoption=ORBInitialHost non \u00e8 un'opzione valida per NameService +tnameserv.orbinitialport0=ORBInitialPort 0 non \u00e8 un'opzione valida per NameService +tnameserv.hs1=Contesto di denominazione iniziale:\n{0} +tnameserv.hs2=TransientNameServer: impostazione della porta per i riferimenti degli oggetti iniziali a: {0} +tnameserv.hs3=Pronto. + + + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_ja.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_ja.properties new file mode 100644 index 000000000..5f607eff8 --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_ja.properties @@ -0,0 +1,175 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=\u4f7f\u3044\u65b9: {0} \ +\n\ +\n \u306b\u306f\u6b21\u306e\u3082\u306e\u304c\u3042\u308a\u307e\u3059\u3002\ +\n -port ORBD \u306e\u8d77\u52d5\u30dd\u30fc\u30c8\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u306f 1049 (\u30aa\u30d7\u30b7\u30e7\u30f3)\ +\n -defaultdb ORBD \u30d5\u30a1\u30a4\u30eb\u306e\u30c7\u30a3\u30ec\u30af\u30c8\u30ea\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u306f "./orb.db" (\u30aa\u30d7\u30b7\u30e7\u30f3)\ +\n -serverid ORBD \u306e\u30b5\u30fc\u30d0 Id\u3002\u30c7\u30d5\u30a9\u30eb\u30c8\u306f 1 (\u30aa\u30d7\u30b7\u30e7\u30f3)\ +\n -ORBInitialPort \u521d\u671f\u30dd\u30fc\u30c8 (\u5fc5\u9808)\ +\n -ORBInitialHost \u521d\u671f\u30db\u30b9\u30c8\u540d (\u5fc5\u9808)\ +\n\ + + +servertool.usage=\u4f7f\u3044\u65b9: {0} \ +\n\ +\n \u306b\u306f\u6b21\u306e\u3082\u306e\u304c\u3042\u308a\u307e\u3059\u3002\ +\n -ORBInitialPort \u521d\u671f\u30dd\u30fc\u30c8 (\u5fc5\u9808)\ +\n -ORBInitialHost \u521d\u671f\u30db\u30b9\u30c8\u540d (\u5fc5\u9808)\ +\n\ + +servertool.banner=\ +\n\ +\nJava IDL Server Tool \u3078\u3088\u3046\u3053\u305d\ +\n\u30d7\u30ed\u30f3\u30d7\u30c8\u306b\u30b3\u30de\u30f3\u30c9\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044 \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\t\u4f7f\u7528\u53ef\u80fd\u306a\u30b3\u30de\u30f3\u30c9: \ +\n\t------------------- \ +\n\ + +servertool.baddef=\u4e0d\u6b63\u306a\u30b5\u30fc\u30d0\u5b9a\u7fa9: {0} +servertool.nosuchserver=\t\u6307\u5b9a\u3055\u308c\u305f\u30b5\u30fc\u30d0\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3002 +servertool.helddown=\t\u30b5\u30fc\u30d0\u306f\u505c\u6b62\u3057\u3066\u3044\u307e\u3059\u3002 +servertool.nosuchorb=\tORB \u304c\u7121\u52b9\u3067\u3059\u3002 +servertool.serverup=\t\u30b5\u30fc\u30d0\u306f\u8d77\u52d5\u3057\u3066\u3044\u307e\u3059\u3002 +servertool.appname=\tapplicationName - {0} +servertool.name=\tname - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targs - {0} +servertool.vmargs=\tvmargs - {0} +servertool.serverid=\tserver id - {0} +servertool.servernotrunning=\t\u30b5\u30fc\u30d0\u306f\u7a3c\u52d5\u3057\u3066\u3044\u307e\u305b\u3093\u3002 +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=\u8d77\u52d5\u53ef\u80fd\u306a\u30b5\u30fc\u30d0\u3092\u767b\u9332\u3057\u307e\u3059\u3002 +servertool.register2=\t\u767b\u9332\u3055\u308c\u305f\u30b5\u30fc\u30d0 (serverid = {0})\u3002 +servertool.register3=\t\u767b\u9332\u3055\u308c\u3066\u3044\u308b\u304c\u8d77\u52d5\u3057\u3066\u3044\u306a\u3044\u30b5\u30fc\u30d0 (serverid = {0})\u3002 +servertool.register4=\t\u767b\u9332\u6e08\u307f\u306e\u30b5\u30fc\u30d0 (serverid = {0})\u3002 + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=\u767b\u9332\u3055\u308c\u305f\u30b5\u30fc\u30d0\u306e\u767b\u9332\u3092\u89e3\u9664\u3057\u307e\u3059 +servertool.unregister2=\t\u30b5\u30fc\u30d0\u306e\u767b\u9332\u304c\u89e3\u9664\u3055\u308c\u307e\u3057\u305f\u3002 + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=\u767b\u9332\u3055\u308c\u305f\u30b5\u30fc\u30d0\u306e\u7279\u5b9a\u30bf\u30a4\u30d7\u306e\u30dd\u30fc\u30c8\u3092\u691c\u51fa\u3057\u307e\u3059\u3002 +servertool.locate2=\ +\n\ +\n\t\u30db\u30b9\u30c8\u540d {0} \ +\n\ +\n\t\t\u30dd\u30fc\u30c8\t\t\u30dd\u30fc\u30c8\u30bf\u30a4\u30d7\t\tORB ID\ +\n\t\t------\t\t------------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=\u767b\u9332\u3055\u308c\u305f\u30b5\u30fc\u30d0\u306e\u7279\u5b9a ORB \u306e\u30dd\u30fc\u30c8\u3092\u691c\u51fa\u3057\u307e\u3059\u3002 +servertool.locateorb2=\ +\n\ +\n\t\u30db\u30b9\u30c8\u540d {0} \ +\n\ +\n\t\t\u30dd\u30fc\u30c8\t\t\u30dd\u30fc\u30c8\u30bf\u30a4\u30d7\t\tORB ID\ +\n\t\t------\t\t------------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=applicationName \u306e\u30b5\u30fc\u30d0 ID \u3092\u8fd4\u3057\u307e\u3059\u3002 +servertool.getserverid2=\tapplicationName {0} \u306e\u30b5\u30fc\u30d0 ID \u306f {1} \u3067\u3059\u3002 + +servertool.list=\n\t\u30ea\u30b9\u30c8\u3092\u8868\u793a\u3057\u307e\u3059\u3002\ +\n\ + +servertool.list1=\u767b\u9332\u3055\u308c\u305f\u3059\u3079\u3066\u306e\u30b5\u30fc\u30d0\u306e\u30ea\u30b9\u30c8\u3092\u8868\u793a\u3057\u307e\u3059\u3002 +servertool.list2=\ +\n\t\u30b5\u30fc\u30d0 Id\t\u30b5\u30fc\u30d0\u306e\u30af\u30e9\u30b9\u540d\t\t\u30b5\u30fc\u30d0\u30a2\u30d7\u30ea\u30b1\u30fc\u30b7\u30e7\u30f3\ +\n\t---------\t----------------\t\t----------------------\ +\n\ + +servertool.listactive=\n\t\u30a2\u30af\u30c6\u30a3\u30d6\u306a\u30b5\u30fc\u30d0\u306e\u30ea\u30b9\u30c8\u3092\u8868\u793a\u3057\u307e\u3059\u3002 +servertool.listactive1=\u73fe\u5728\u30a2\u30af\u30c6\u30a3\u30d6\u306a\u30b5\u30fc\u30d0\u306e\u30ea\u30b9\u30c8\u3092\u8868\u793a\u3057\u307e\u3059\u3002 +servertool.listappnames=\tapplicationNames \u306e\u30ea\u30b9\u30c8\u3092\u8868\u793a\u3057\u307e\u3059\u3002\n +servertool.listappnames1=\u73fe\u5728\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b applicationNames \u306e\u30ea\u30b9\u30c8\u3092\u8868\u793a\u3057\u307e\u3059\u3002 +servertool.listappnames2=\u73fe\u5728\u5b9a\u7fa9\u3055\u308c\u3066\u3044\u308b\u30b5\u30fc\u30d0 applicationNames: + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=\u767b\u9332\u3055\u308c\u305f\u30b5\u30fc\u30d0\u3092\u505c\u6b62\u3057\u307e\u3059\u3002 +servertool.shutdown2=\t\u30b5\u30fc\u30d0\u306e\u505c\u6b62\u306b\u6210\u529f\u3057\u307e\u3057\u305f\u3002 +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=\u767b\u9332\u3055\u308c\u305f\u30b5\u30fc\u30d0\u3092\u8d77\u52d5\u3057\u307e\u3059\u3002 +servertool.startserver2=\t\u30b5\u30fc\u30d0\u306e\u8d77\u52d5\u306b\u6210\u529f\u3057\u307e\u3057\u305f\u3002 + +servertool.quit=\n\tquit\n +servertool.quit1=\u3053\u306e\u30c4\u30fc\u30eb\u3092\u7d42\u4e86\u3057\u307e\u3059\u3002 + +servertool.help=\thelp\ +\n\t\u307e\u305f\u306f\ +\n\thelp \ +\n\ + +servertool.help1=\u30d8\u30eb\u30d7\u3092\u8868\u793a\u3057\u307e\u3059\u3002 + +servertool.orbidmap=\t\u4f7f\u3044\u65b9: orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=ORB \u540d\u304a\u3088\u3073\u305d\u306e\u30de\u30c3\u30d4\u30f3\u30b0\u306e\u30ea\u30b9\u30c8 +servertool.orbidmap2=\ +\n\tORB Id\t\tORB \u540d\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=\u6301\u7d9a NameServer \u306e\u8d77\u52d5\u306b\u6210\u529f\u3057\u307e\u3057\u305f\u3002 + + +bootstrap.usage=\u4f7f\u3044\u65b9: {0} \ +\n\ +\n \u306b\u306f\u6b21\u306e\u3082\u306e\u304c\u3042\u308a\u307e\u3059\u3002\ +\n -ORBInitialPort \u521d\u671f\u30dd\u30fc\u30c8 (\u5fc5\u9808)\ +\n -InitialServicesFile \u521d\u671f\u30b5\u30fc\u30d3\u30b9\u30ea\u30b9\u30c8\u3092\u542b\u3080\u30d5\u30a1\u30a4\u30eb (\u5fc5\u9808)\ +\n\ + +bootstrap.success=\u30dd\u30fc\u30c8\u3092 {0} \u306b\u8a2d\u5b9a\u3057\u3001{1} \u304b\u3089\u30b5\u30fc\u30d3\u30b9\u3092\u8aad\u307f\u8fbc\u307f\u307e\u3059\u3002 +bootstrap.filenotreadable=\u30d5\u30a1\u30a4\u30eb {0} \u3092\u8aad\u307f\u8fbc\u3081\u307e\u305b\u3093\u3002 +bootstrap.filenotfound=\u30d5\u30a1\u30a4\u30eb {0} \u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3002 +bootstrap.exception=\u30d7\u30ed\u30d1\u30c6\u30a3\u3092\u30d5\u30a1\u30a4\u30eb {0} \u306b\u4fdd\u5b58\u4e2d\u306b\u4f8b\u5916\u3092\u30ad\u30e3\u30c3\u30c1\u3057\u307e\u3057\u305f: \u4f8b\u5916 {1} + +tnameserv.exception=\u30dd\u30fc\u30c8 {0} \u3067\u30d6\u30fc\u30c8\u30b9\u30c8\u30e9\u30c3\u30d7\u30b5\u30fc\u30d3\u30b9\u3092\u8d77\u52d5\u4e2d\u306b\u4f8b\u5916\u3092\u30ad\u30e3\u30c3\u30c1\u3057\u307e\u3057\u305f\u3002 +tnameserv.usage=\u30b3\u30de\u30f3\u30c9\u884c\u5f15\u6570 -ORBInitialPort \u3092\u4f7f\u3063\u3066\u5225\u306e\u30dd\u30fc\u30c8\u3092\u4f7f\u7528\u3057\u3066\u304f\u3060\u3055\u3044\u3002 +tnameserv.invalidhostoption=ORBInitialHost \u306f NameService \u306b\u6709\u52b9\u306a\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u306f\u3042\u308a\u307e\u305b\u3093\u3002 +tnameserv.orbinitialport0=ORBInitialPort 0 \u306f NameService \u306b\u6709\u52b9\u306a\u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u306f\u3042\u308a\u307e\u305b\u3093\u3002 +tnameserv.hs1=\u521d\u671f\u30cd\u30fc\u30df\u30f3\u30b0\u30b3\u30f3\u30c6\u30ad\u30b9\u30c8:\n{0} +tnameserv.hs2=TransientNameServer: \u521d\u671f\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\u53c2\u7167\u306e\u30dd\u30fc\u30c8\u3092 {0} \u306b\u8a2d\u5b9a\u3057\u307e\u3059\u3002 +tnameserv.hs3=\u6e96\u5099\u304c\u5b8c\u4e86\u3057\u307e\u3057\u305f\u3002 + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_ko.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_ko.properties new file mode 100644 index 000000000..4ddc8f93d --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_ko.properties @@ -0,0 +1,176 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=\uc0ac\uc6a9\ubc95: {0} <\uc635\uc158> \ +\n\ +\n<\uc635\uc158>\uc5d0 \ub4e4\uc5b4\uac00\ub294 \ud56d\ubaa9\uc740 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4.\ +\n -port ORBD\uac00 \uc2dc\uc791\ub418\uc5b4\uc57c \ud558\ub294 \ud65c\uc131 \ud3ec\ud2b8\ub85c \uae30\ubcf8\uac12\uc740 1049\uc785\ub2c8\ub2e4(\uc120\ud0dd \uc0ac\ud56d).\ +\n -defaultdb ORBD \ud30c\uc77c\uc758 \ub514\ub809\ud1a0\ub9ac. \uae30\ubcf8\uac12\uc740 "./orb.db"\uc785\ub2c8\ub2e4(\uc120\ud0dd \uc0ac\ud56d).\ +\n -serverid ORBD\uc758 \uc11c\ubc84 ID. \uae30\ubcf8\uac12\uc740 1 \uc785\ub2c8\ub2e4(\uc120\ud0dd \uc0ac\ud56d).\ +\n -ORBInitialPort \ucd08\uae30 \ud3ec\ud2b8(\ud544\uc218)\ +\n -ORBInitialHost \ucd08\uae30 \ud638\uc2a4\ud2b8\uba85(\ud544\uc218)\ +\n\ + + +servertool.usage=\uc0ac\uc6a9\ubc95: {0} <\uc635\uc158> \ +\n\ +\n<\uc635\uc158>\uc5d0 \ub4e4\uc5b4\uac00\ub294 \ud56d\ubaa9\uc740 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4.\ +\n -ORBInitialPort \ucd08\uae30 \ud3ec\ud2b8(\ud544\uc218)\ +\n -ORBInitialHost \ucd08\uae30 \ud638\uc2a4\ud2b8\uba85(\ud544\uc218)\ +\n\ + +servertool.banner=\ +\n\ +\nJava IDL \uc11c\ubc84 \ub3c4\uad6c\uc785\ub2c8\ub2e4\ +\n\ud504\ub86c\ud504\ud2b8\uc5d0 \uba85\ub839\uc5b4\ub97c \uc785\ub825\ud558\uc2ed\uc2dc\uc624\ +\n\ + +servertool.shorthelp=\ +\n\ +\n\t\uc0ac\uc6a9 \uac00\ub2a5\ud55c \uba85\ub839\uc5b4: \ +\n\t------------------- \ +\n\ + +servertool.baddef=\uc798\ubabb\ub41c \uc11c\ubc84 \uc815\uc758: {0} +servertool.nosuchserver=\t\ud574\ub2f9 \uc11c\ubc84\uac00 \uc5c6\uc2b5\ub2c8\ub2e4. +servertool.helddown=\t\uc11c\ubc84\uac00 \ub2e4\uc6b4\ub418\uc5c8\uc2b5\ub2c8\ub2e4. +servertool.nosuchorb=\t\uc798\ubabb\ub41c ORB. +servertool.serverup=\t\uc11c\ubc84\uac00 \uc774\ubbf8 \uac00\ub3d9\ub418\uc5c8\uc2b5\ub2c8\ub2e4. +servertool.appname=\t\uc751\uc6a9\ud504\ub85c\uadf8\ub7a8 \uc774\ub984 - {0} +servertool.name=\t\uc774\ub984 - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targs - {0} +servertool.vmargs=\tvmargs - {0} +servertool.serverid=\t\uc11c\ubc84 ID - {0} +servertool.servernotrunning=\t\uc11c\ubc84\uac00 \uc2e4\ud589 \uc911\uc774 \uc544\ub2d9\ub2c8\ub2e4. +servertool.register=\ +\n\ +\n\tregister -server <\uc11c\ubc84 \ud074\ub798\uc2a4 \uc774\ub984> \ +\n\t -applicationName <\ub300\uccb4 \uc11c\ubc84 \uc774\ub984> \ +\n\t -classpath <\uc11c\ubc84\uc758 classpath> \ +\n\t -args <\uc11c\ubc84 \uc778\uc790> \ +\n\t -vmargs <\uc11c\ubc84 Java VM \uc778\uc790>\ +\n\ + +servertool.register1=\ud65c\uc131 \uac00\ub2a5 \uc11c\ubc84 \ub4f1\ub85d +servertool.register2=\t\uc11c\ubc84\uac00 \ub4f1\ub85d\ub418\uc5c8\uc2b5\ub2c8\ub2e4(serverid = {0}). +servertool.register3=\t\uc11c\ubc84\uac00 \ub4f1\ub85d\ub418\uc5c8\uc9c0\ub9cc \ub2e4\uc6b4\ub418\uc5c8\uc2b5\ub2c8\ub2e4(serverid = {0}). +servertool.register4=\t\uc11c\ubc84\uac00 \uc774\ubbf8 \ub4f1\ub85d\ub418\uc5c8\uc2b5\ub2c8\ub2e4(serverid = {0}). + +servertool.unregister=\ +\n\tunregister [ -serverid <\uc11c\ubc84 ID> | -applicationName <\uc774\ub984> ] \ +\n\ + +servertool.unregister1=\ub4f1\ub85d\ub41c \uc11c\ubc84\uc758 \ub4f1\ub85d\uc744 \ucde8\uc18c\ud569\ub2c8\ub2e4 +servertool.unregister2=\t\uc11c\ubc84\uac00 \ub4f1\ub85d \ucde8\uc18c\ub418\uc5c8\uc2b5\ub2c8\ub2e4. + +servertool.locate=\ +\n\tlocate [ -serverid <\uc11c\ubc84 ID> | -applicationName <\uc774\ub984> ] [ <-endpointType ] \ +\n\ + +servertool.locate1=\ub4f1\ub85d\ub41c \uc11c\ubc84\uc5d0 \ub300\ud55c \ud2b9\uc815 \uc885\ub958\uc758 \ud3ec\ud2b8\ub97c \ucc3e\uc2b5\ub2c8\ub2e4 +servertool.locate2=\ +\n\ +\n\t\ud638\uc2a4\ud2b8 \uc774\ub984 {0} \ +\n\ +\n\t\t\ud3ec\ud2b8\t\t\ud3ec\ud2b8 \uc885\ub958\t\tORB ID\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid <\uc11c\ubc84 ID> | -applicationName <\uc774\ub984> ] [ -orbid ]\ +\n\ + +servertool.locateorb1=\ub4f1\ub85d\ub41c \uc11c\ubc84\uc758 \ud2b9\uc815 ORB\uc5d0 \ub300\ud55c \ud3ec\ud2b8\ub97c \ucc3e\uc2b5\ub2c8\ub2e4 +servertool.locateorb2=\ +\n\ +\n\t\ud638\uc2a4\ud2b8 \uc774\ub984 {0} \ +\n\ +\n\t\t\ud3ec\ud2b8\t\t\ud3ec\ud2b8 \uc885\ub958\t\tORB ID\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName <\uc774\ub984> ] \ +\n\ + +servertool.getserverid1=\uc9c0\uc815\ud55c \uc751\uc6a9\ud504\ub85c\uadf8\ub7a8 \uc774\ub984\uc5d0 \ub300\ud55c \uc11c\ubc84 ID\ub97c \ubc18\ud658\ud569\ub2c8\ub2e4. +servertool.getserverid2=\t\uc751\uc6a9\ud504\ub85c\uadf8\ub7a8 \uc774\ub984 {0}\uc5d0 \ub300\ud55c \uc11c\ubc84 ID\ub294 {1}\uc785\ub2c8\ub2e4. + +servertool.list=\n\t\ubaa9\ub85d\ +\n\ + +servertool.list1=\ub4f1\ub85d\ub41c \uc11c\ubc84\ub97c \ubaa8\ub450 \ub098\uc5f4\ud569\ub2c8\ub2e4. +servertool.list2=\ +\n\t\uc11c\ubc84 ID\t\uc11c\ubc84 \ud074\ub798\uc2a4 \uc774\ub984\t\t\uc11c\ubc84 \uc751\uc6a9 \ud504\ub85c\uadf8\ub7a8\ +\n\t---------\t-----------------\t\t------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=\ud604\uc7ac\uc758 \ud65c\uc131 \uc11c\ubc84\ub97c \ub098\uc5f4\ud569\ub2c8\ub2e4. +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=\ud604\uc7ac \uc815\uc758\ub41c \uc751\uc6a9\ud504\ub85c\uadf8\ub7a8 \uc774\ub984\uc744 \ub098\uc5f4\ud569\ub2c8\ub2e4. +servertool.listappnames2=\ud604\uc7ac \uc815\uc758\ub41c \uc11c\ubc84 \uc751\uc6a9\ud504\ub85c\uadf8\ub7a8 \uc774\ub984: + +servertool.shutdown=\ +\n\tshutdown [ -serverid <\uc11c\ubc84 ID> | -applicationName <\uc774\ub984> ]\ +\n\ + +servertool.shutdown1=\ub4f1\ub85d\ub41c \uc11c\ubc84\ub97c \uc885\ub8cc\ud569\ub2c8\ub2e4. +servertool.shutdown2=\t\uc11c\ubc84\uac00 \uc131\uacf5\uc801\uc73c\ub85c \uc885\ub8cc\ub418\uc5c8\uc2b5\ub2c8\ub2e4. +servertool.startserver=\ +\n\tstartup [ -serverid <\uc11c\ubc84 ID> | -applicationName <\uc774\ub984> ]\ +\n\ + +servertool.startserver1=\ub4f1\ub85d\ub41c \uc11c\ubc84\ub97c \uc2dc\uc791\ud569\ub2c8\ub2e4. +servertool.startserver2=\t\uc11c\ubc84\uac00 \uc131\uacf5\uc801\uc73c\ub85c \uc2dc\uc791\ub418\uc5c8\uc2b5\ub2c8\ub2e4. + +servertool.quit=\n\tquit\n +servertool.quit1=\uc774 \ub3c4\uad6c\ub97c \uc885\ub8cc\ud569\ub2c8\ub2e4. + +servertool.help=\thelp\ +\n\t\ub610\ub294\ +\n\thelp <\uba85\ub839\uc5b4 \uc774\ub984>\ +\n\ + +servertool.help1=\ub3c4\uc6c0\ub9d0\uc744 \ud45c\uc2dc\ud569\ub2c8\ub2e4. + +servertool.orbidmap=\tUsage:orblist [ -serverid <\uc11c\ubc84 ID> | -applicationName <\uc774\ub984> ]\ +\n\ + +servertool.orbidmap1=ORB \uc774\ub984\uacfc \ud574\ub2f9 \ub9e4\ud551\uc744 \ub098\uc5f4\ud569\ub2c8\ub2e4 +servertool.orbidmap2=\ +\n\tORB ID\t\tORB \uc774\ub984\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=\uc9c0\uc18d \uc774\ub984 \uc11c\ubc84\uac00 \uc131\uacf5\uc801\uc73c\ub85c \uc2dc\uc791\ub418\uc5c8\uc2b5\ub2c8\ub2e4 + + +bootstrap.usage=\uc0ac\uc6a9\ubc95: {0} <\uc635\uc158> \ +\n\ +\n<\uc635\uc158>\uc5d0 \ub4e4\uc5b4\uac00\ub294 \ud56d\ubaa9\uc740 \ub2e4\uc74c\uacfc \uac19\uc2b5\ub2c8\ub2e4.\ +\n -ORBInitialPort \ucd08\uae30 \ud3ec\ud2b8(\ud544\uc218)\ +\n -InitialServicesFile \ucd08\uae30 \uc11c\ube44\uc2a4 \ubaa9\ub85d\uc774 \ub4e4\uc5b4 \uc788\ub294 \ud30c\uc77c(\ud544\uc218)\ +\n\ + +bootstrap.success=\ud3ec\ud2b8\ub97c {0}(\uc73c)\ub85c \uc124\uc815\ud558\uace0 {1}\uc5d0\uc11c \uc11c\ube44\uc2a4\ub97c \uc77d\uc2b5\ub2c8\ub2e4 +bootstrap.filenotreadable={0} \ud30c\uc77c\uc744 \uc77d\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4 +bootstrap.filenotfound={0} \ud30c\uc77c\uc744 \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4 +bootstrap.exception={0} \ud30c\uc77c\uc5d0 \ub4f1\ub85d \uc815\ubcf4\ub97c \uc800\uc7a5\ud558\ub294 \ub3d9\uc548 \uc608\uc678\uac00 \ubc1c\uc0dd\ud588\uc2b5\ub2c8\ub2e4.\uc608\uc678 {1} + +tnameserv.exception={0} \ud3ec\ud2b8\uc5d0\uc11c \ubd80\ud2b8\uc2a4\ud2b8\ub7a9 \uc11c\ube44\uc2a4\ub97c \uc2dc\uc791\ud558\ub294 \ub3d9\uc548 \uc624\ub958\uac00 \ubc1c\uc0dd\ud588\uc2b5\ub2c8\ub2e4 +tnameserv.usage=ORBInitialPort <\ud3ec\ud2b8 \ubc88\ud638> \uba85\ub839\uc904 \uc778\uc790\ub85c \ub2e4\ub978 \ud3ec\ud2b8 \uc0ac\uc6a9\uc744 \uc2dc\ub3c4\ud569\ub2c8\ub2e4 +tnameserv.invalidhostoption=ORBInitialHost\ub294 NameService\uc758 \uc720\ud6a8\ud55c \uc635\uc158\uc774 \uc544\ub2d9\ub2c8\ub2e4. +tnameserv.orbinitialport0=ORBInitialPort 0\uc740 NameService\uc758 \uc720\ud6a8\ud55c \uc635\uc158\uc774 \uc544\ub2d9\ub2c8\ub2e4 +tnameserv.hs1=\ucd08\uae30 \uba85\ub839 \ucee8\ud14d\uc2a4\ud2b8:\n{0} +tnameserv.hs2=TransientNameServer:\ucd08\uae30 \uac1d\uccb4 \ucc38\uc870\ub97c \uc704\ud55c \ud3ec\ud2b8 \uc124\uc815: {0} {0} +tnameserv.hs3=\uc900\ube44\ub418\uc5c8\uc2b5\ub2c8\ub2e4. + + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_sv.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_sv.properties new file mode 100644 index 000000000..3ee9a0efa --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_sv.properties @@ -0,0 +1,177 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=G\u00f6r s\u00e5 h\u00e4r: {0} \ +\n\ +\nd\u00e4r omfattar:\ +\n -port Aktiveringsport d\u00e4r ORBD ska startas, standard 1049 (valfritt)\ +\n -defaultdb Katalog f\u00f6r ORBD-filer, standard "./orb.db" (valfritt)\ +\n -serverid Server-ID f\u00f6r ORBD, standard 1 (valfritt)\ +\n -ORBInitialPort Initialport (obligatoriskt)\ +\n -ORBInitialHost Initialt v\u00e4rdnamn (obligatoriskt)\ +\n\ + + +servertool.usage=G\u00f6r s\u00e5 h\u00e4r: {0} \ +\n\ +\nd\u00e4r omfattar:\ +\n -ORBInitialPort Initialport (obligatoriskt)\ +\n -ORBInitialHost Initialt v\u00e4rdnamn (obligatoriskt)\ +\n\ + +servertool.banner=\ +\n\ +\nV\u00e4lkommen till Java IDL Server Tool \ +\nskriv kommandona vid prompten \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\tTillg\u00e4ngliga kommandon: \ +\n\t------------------- \ +\n\ + +servertool.baddef=D\u00e5lig serverdefinition: {0} +servertool.nosuchserver=\tn\u00e5gon s\u00e5dan server kan inte hittas. +servertool.helddown=\tserver h\u00e5lls nere. +servertool.nosuchorb=\togiltig ORB. +servertool.serverup=\tserver \u00e4r redan uppe. +servertool.appname=\tapplicationName - {0} +servertool.name=\tnamn - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targs - {0} +servertool.vmargs=\tvmargs - {0} +servertool.serverid=\tserver id - {0} +servertool.servernotrunning=\tserver k\u00f6rs inte. +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=registrera en aktiverbar server +servertool.register2=\tserver registrerad (serverid = {0}). +servertool.register3=\tserver registrerad men h\u00e5lls nere (serverid = {0}). +servertool.register4=\tserver har redan registrerats (serverid = {0}). + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=avregistrera en registrerad server +servertool.unregister2=\tserver oregistrerad. + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=lokaliserar portar av en viss typ f\u00f6r en registrerad server +servertool.locate2=\ +\n\ +\n\tV\u00e4rdnamn {0} \ +\n\ +\n\t\tPort\t\tPorttyp\t\tORB-ID\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=lokaliserar portar f\u00f6r en viss ORB f\u00f6r en registrerad server +servertool.locateorb2=\ +\n\ +\n\tV\u00e4rdnamn {0} \ +\n\ +\n\t\tPort\t\tPorttyp\t\tORB-ID\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=returnerar server-id f\u00f6r ett applicationName +servertool.getserverid2=\tServer-ID f\u00f6r applicationName {0} \u00e4r {1} + +servertool.list=\n\tlist_\ +\n\ + +servertool.list1=listar alla registrerade servrar +servertool.list2=\ +\n\tServer Id\tServer Class Name\t\tServer Application\ +\n\t---------\t-----------------\t\t------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=listar alla f\u00f6r tillf\u00e4llet aktiva servrar +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=listar de applicationNames som f\u00f6r tillf\u00e4llet \u00e4r definierade +servertool.listappnames2=Aktuella definierade server-applicationNames: + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=st\u00e4nger en registrerad server +servertool.shutdown2=\tserver har st\u00e4ngts av. +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=startar en registrerad server +servertool.startserver2=\tserver har startats. + +servertool.quit=\n\tquit\n +servertool.quit1=avsluta det h\u00e4r verktyget + +servertool.help=\thelp\ +\n\tOR\ +\n\thelp \ +\n\ + +servertool.help1=get help + +servertool.orbidmap=\tG\u00f6r s\u00e5 h\u00e4r: orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=lista \u00f6ver ORB-namn och deras mappning +servertool.orbidmap2=\ +\n\tORB-ID\t\tORB-namn\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=Namnservern har startats utan problem + + +bootstrap.usage=G\u00f6r s\u00e5 h\u00e4r: {0} \ +\n\ +\nd\u00e4r omfattar:\ +\n -ORBInitialPort Initialport (obligatoriskt)\ +\n -InitialServicesFile En fil som inneh\u00e5ller en lista \u00f6ver initiala tj\u00e4nster (obligatoriskt)\ +\n\ + +bootstrap.success=s\u00e4tter porten till {0} och l\u00e4ser tj\u00e4nster fr\u00e5n {1} +bootstrap.filenotreadable=filen {0} g\u00e5r inte att l\u00e4sa +bootstrap.filenotfound=filen {0} g\u00e5r inte att hitta +bootstrap.exception=p\u00e5tr\u00e4ffade undantag medan egenskaper sparades i filen {0}: Undantag {1} + +tnameserv.exception=p\u00e5tr\u00e4ffade ett undantagsfel n\u00e4r starttj\u00e4nsten startades vid porten {0} +tnameserv.usage=f\u00f6rs\u00f6k att anv\u00e4nda en annan port med kommandoradsargument -ORBInitialPort +tnameserv.invalidhostoption=ORBInitialHost \u00e4r inte ett giltigt alternativ f\u00f6r NameService +tnameserv.orbinitialport0=ORBInitialPort 0 \u00e4r inte ett giltigt alternativ f\u00f6r NameService +tnameserv.hs1=Initial namngivningskontext:\n{0} +tnameserv.hs2=TransientNameServer: anger port f\u00f6r initiala objektreferenser till: {0} +tnameserv.hs3=Klar. + + + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_zh_CN.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_zh_CN.properties new file mode 100644 index 000000000..fa1d8d1ac --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_zh_CN.properties @@ -0,0 +1,175 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=\u7528\u6cd5\uff1a{0} <\u9009\u9879> \ +\n\ +\n\u5176\u4e2d\uff0c<\u9009\u9879> \u5305\u62ec\uff1a\ +\n -port \u542f\u52a8 ORBD \u7684\u6fc0\u6d3b\u7aef\u53e3\uff0c\u7f3a\u7701\u503c\u4e3a 1049 (\u53ef\u9009)\ +\n -defaultdb ORBD \u6587\u4ef6\u7684\u76ee\u5f55\uff0c\u7f3a\u7701\u503c\u4e3a "./orb.db" (\u53ef\u9009)\ +\n -serverid ORBD \u7684\u670d\u52a1\u5668\u6807\u8bc6\u7b26\uff0c\u7f3a\u7701\u503c\u4e3a 1 (\u53ef\u9009)\ +\n -ORBInitialPort \u521d\u59cb\u7aef\u53e3\uff08\u5fc5\u9700\uff09\ +\n -ORBInitialHost \u521d\u59cb\u4e3b\u673a\u540d\u79f0\uff08\u5fc5\u9700\uff09\ +\n\ + + +servertool.usage=\u7528\u6cd5\uff1a {0} <\u9009\u9879> \ +\n\ +\n\u5176\u4e2d\uff0c<\u9009\u9879> \u5305\u62ec\uff1a\ +\n -ORBInitialPort \u521d\u59cb\u7aef\u53e3\uff08\u5fc5\u9700\uff09\ +\n -ORBInitialHost \u521d\u59cb\u4e3b\u673a\u540d\u79f0\uff08\u5fc5\u9700\uff09\ +\n\ + +servertool.banner=\ +\n\ +\n\u6b22\u8fce\u4f7f\u7528 Java IDL \u670d\u52a1\u5668\u5de5\u5177 \ +\n\u8bf7\u5728\u63d0\u793a\u5904\u8f93\u5165\u547d\u4ee4 \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\t\u53ef\u7528\u547d\u4ee4\uff1a\ +\n\t------------------- \ +\n\ + +servertool.baddef=\u9519\u8bef\u7684\u670d\u52a1\u5668\u5b9a\u4e49\uff1a {0} +servertool.nosuchserver=\t\u627e\u4e0d\u5230\u8fd9\u79cd\u670d\u52a1\u5668\u3002 +servertool.helddown=\t\u670d\u52a1\u5668\u5df2\u88ab\u5173\u95ed\u3002 +servertool.nosuchorb=\t\u65e0\u6548\u7684\u5bf9\u8c61\u8bf7\u6c42\u4ee3\u7406\u7a0b\u5e8f (ORB)\u3002 +servertool.serverup=\t\u670d\u52a1\u5668\u5df2\u5f00\u542f\u3002 +servertool.appname=\t\u5e94\u7528\u7a0b\u5e8f\u540d\u79f0 - {0} +servertool.name=\t\u540d\u79f0 - {0} +servertool.classpath=\t\u7c7b\u8def\u5f84 - {0} +servertool.args=\t\u53c2\u6570 - {0} +servertool.vmargs=\tvm\u53c2\u6570 - {0} +servertool.serverid=\t\u670d\u52a1\u5668\u6807\u8bc6\u7b26 - {0} +servertool.servernotrunning=\t\u670d\u52a1\u5668\u6ca1\u6709\u8fd0\u884c\u3002 +servertool.register=\ +\n\ +\n\tregister -server<\u670d\u52a1\u5668\u7c7b\u540d\u79f0> \ +\n\t -applicationName <\u5907\u7528\u670d\u52a1\u5668\u540d\u79f0> \ +\n\t -classpath <\u5230\u670d\u52a1\u5668\u7684\u7c7b\u8def\u5f84> \ +\n\t -args <\u670d\u52a1\u5668\u7684\u53c2\u6570> \ +\n\t -vmargs <\u670d\u52a1\u5668 Java VM \u7684\u53c2\u6570>\ +\n\ + +servertool.register1=\u6ce8\u518c\u4e00\u4e2a\u53ef\u6fc0\u6d3b\u7684\u670d\u52a1\u5668 +servertool.register2=\t\u5df2\u6ce8\u518c\u670d\u52a1\u5668 (serverid = {0})\u3002 +servertool.register3=\t\u5df2\u6ce8\u518c\u670d\u52a1\u5668\uff0c\u4f46\u5df2\u88ab\u5173\u95ed (serverid = {0})\u3002 +servertool.register4=\t\u670d\u52a1\u5668\u5df2\u6ce8\u518c (serverid = {0})\u3002 + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=\u53d6\u6d88\u670d\u52a1\u5668\u6ce8\u518c +servertool.unregister2=\t\u670d\u52a1\u5668\u672a\u6ce8\u518c\u3002 + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=\u5c06\u5df2\u6ce8\u518c\u670d\u52a1\u5668\u5b9a\u4f4d\u5728\u7279\u5b9a\u7c7b\u578b\u7684\u7aef\u53e3 +servertool.locate2=\ +\n\ +\n\t\u4e3b\u673a\u540d\u79f0 {0} \ +\n\ +\n\t\t\u7aef\u53e3\t\t\u7aef\u53e3\u7c7b\u578b\t\tORB \u6807\u8bc6\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=\u4e3a\u5df2\u6ce8\u518c\u670d\u52a1\u5668\u7684\u7279\u5b9a\u5bf9\u8c61\u8bf7\u6c42\u4ee3\u7406\u7a0b\u5e8f\u5b9a\u4f4d\u7aef\u53e3\u3002 +servertool.locateorb2=\ +\n\ +\n\t\u4e3b\u673a\u540d\u79f0 {0} \ +\n\ +\n\t\t\u7aef\u53e3\t\t\u7aef\u53e3\u7c7b\u578b\t\tORB \u6807\u8bc6\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1= \u8fd4\u56de\u5e94\u7528\u7a0b\u5e8f\u540d\u79f0\u7684\u670d\u52a1\u5668\u6807\u8bc6\u7b26 +servertool.getserverid2=\t\u5e94\u7528\u7a0b\u5e8f\u540d\u79f0\u7684\u670d\u52a1\u5668\u6807\u8bc6\u7b26 {0} is {1} + +servertool.list=\n\t\u5217\u8868\ +\n\ + +servertool.list1=\u5217\u4e3e\u6240\u6709\u5df2\u6ce8\u518c\u670d\u52a1\u5668 +servertool.list2=\ +\n\t\u670d\u52a1\u5668\u6807\u8bc6\u7b26\t\u670d\u52a1\u5668\u7c7b\u540d\u79f0\t\t\u670d\u52a1\u5668\u5e94\u7528\u7a0b\u5e8f\ +\n\t---------\t-----------------\t\t------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=\u5217\u4e3e\u5f53\u524d\u6d3b\u52a8\u7684\u670d\u52a1\u5668 +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=\u5217\u4e3e\u5f53\u524d\u5b9a\u4e49\u7684\u5e94\u7528\u7a0b\u5e8f\u540d\u79f0 +servertool.listappnames2=\u5f53\u524d\u5b9a\u4e49\u7684\u670d\u52a1\u5668\u5e94\u7528\u7a0b\u5e8f\u540d\u79f0\uff1a + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=\u5173\u95ed\u4e00\u4e2a\u5df2\u6ce8\u518c\u670d\u52a1\u5668 +servertool.shutdown2=\t\u670d\u52a1\u5668\u6210\u529f\u5173\u95ed\u3002 +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=\u542f\u52a8\u4e00\u4e2a\u5df2\u6ce8\u518c\u670d\u52a1\u5668 +servertool.startserver2=\t\u670d\u52a1\u5668\u6210\u529f\u542f\u52a8\u3002 + +servertool.quit=\n\t\u9000\u51fa\n +servertool.quit1=\u9000\u51fa\u6b64\u5de5\u5177 + +servertool.help=\t\u5e2e\u52a9\ +\n\t\u6216\ +\n\thelp \ +\n\ + +servertool.help1=\u53d6\u5f97\u5e2e\u52a9 + +servertool.orbidmap=\t\u7528\u6cd5\uff1aorblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=\u5bf9\u8c61\u8bf7\u6c42\u4ee3\u7406\u7a0b\u5e8f (orb) \u540d\u79f0\u53ca\u5176\u6620\u5c04\u5217\u8868 +servertool.orbidmap2=\ +\n\tORB \u6807\u8bc6\t\tORB \u540d\u79f0\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=\u6301\u4e45\u6027\u540d\u79f0\u670d\u52a1\u5668\u6210\u529f\u542f\u52a8 + + +bootstrap.usage=\u7528\u6cd5\uff1a{0} <\u9009\u9879> \ +\n\ +\n\u5176\u4e2d\uff0c<\u9009\u9879> \u5305\u62ec\uff1a\ +\n -ORBInitialPort \u521d\u59cb\u7aef\u53e3\uff08\u5fc5\u9700\uff09\ +\n -InitialServicesFile \u5305\u542b\u521d\u59cb\u670d\u52a1\u5217\u8868\u7684\u6587\u4ef6\uff08\u5fc5\u9700\uff09\ +\n\ + +bootstrap.success=\u5c06\u7aef\u53e3\u8bbe\u7f6e\u4e3a{0}\u5e76\u4ece{1}\u8bfb\u53d6\u670d\u52a1 +bootstrap.filenotreadable=\u4e0d\u53ef\u8bfb\u53d6\u6587\u4ef6 {0} +bootstrap.filenotfound=\u6ca1\u6709\u627e\u5230\u6587\u4ef6{0} +bootstrap.exception=\u5c06\u5c5e\u6027\u4fdd\u5b58\u5230\u6587\u4ef6{0}\u65f6\u53d1\u751f\u5f02\u5e38\uff1a\u5f02\u5e38 {1} + +tnameserv.exception=\u542f\u52a8{0}\u7aef\u53e3\u4e0a\u7684\u81ea\u5f15\u5bfc\u7a0b\u5e8f\u670d\u52a1\u65f6\u53d1\u751f\u5f02\u5e38 +tnameserv.usage=\u5c1d\u8bd5\u5229\u7528\u547d\u4ee4\u884c\u53c2\u6570\u4f7f\u7528\u4e0d\u540c\u7684\u7aef\u53e3 -ORBInnitialPort +tnameserv.invalidhostoption=ORBInitialHost \u4e0d\u662f\u540d\u79f0\u670d\u52a1\u5668\u7684\u6709\u6548\u9009\u9879 +tnameserv.orbinitialport0=ORBInitialPort 0 \u4e0d\u662f\u540d\u79f0\u670d\u52a1\u5668\u7684\u6709\u6548\u9009\u9879 +tnameserv.hs1=\u521d\u59cb\u7684\u547d\u540d\u8303\u56f4\uff1a\n{0} +tnameserv.hs2=TransientNameServer: \u5c06\u521d\u59cb\u5bf9\u8c61\u5f15\u7528\u7aef\u53e3\u8bbe\u7f6e\u4e3a\uff1a{0} +tnameserv.hs3=\u51c6\u5907\u5c31\u7eea\u3002 + diff --git a/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_zh_TW.properties b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_zh_TW.properties new file mode 100644 index 000000000..6b743831a --- /dev/null +++ b/orbmain/src/main/resources/com/sun/corba/ee/impl/resources/sunorb_zh_TW.properties @@ -0,0 +1,175 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +orbd.usage=\u7528\u6cd5\uff1a{0} \ +\n\ +\n\u5176\u4e2d \u5305\u62ec\uff1a\ +\n -port ORBD \u61c9\u88ab\u555f\u52d5\u7684\u555f\u52d5\u57e0\u6240\u5728\uff0c\u9810\u8a2d\u70ba 1049 (\u53ef\u9078)\ +\n -defaultdb ORBD \u6a94\u6848\u7684\u76ee\u9304\uff0c\u9810\u8a2d "./orb.db" (\u53ef\u9078)\ +\n -serverid ORBD \u4f3a\u670d\u5668 Id\uff0c\u9810\u8a2d\u70ba 1 (\u53ef\u9078)\ +\n -ORBInitialPort \u8d77\u59cb\u57e0\uff08\u5fc5\u8981\uff09\ +\n -ORBInitialHost \u8d77\u59cb\u4e3b\u6a5f\u540d\u7a31\uff08\u5fc5\u8981\uff09\ +\n\ + + +servertool.usage=\u7528\u6cd5\uff1a {0} \ +\n\ +\nwhere \u5305\u62ec\uff1a\ +\n -ORBInitialPort \u8d77\u59cb\u57e0\uff08\u5fc5\u8981\uff09\ +\n -ORBInitialHost \u8d77\u59cb\u4e3b\u6a5f\u540d\u7a31\uff08\u5fc5\u8981\uff09\ +\n\ + +servertool.banner=\ +\n\ +\n\u6b61\u8fce\u4f86\u5230 Java IDL \u4f3a\u670d\u5668\u5de5\u5177 \ +\n\u8acb\u5728\u63d0\u793a\u8655\u8f38\u5165\u6307\u4ee4 \ +\n\ + +servertool.shorthelp=\ +\n\ +\n\t\u73fe\u6709\u7684\u6307\u4ee4\uff1a\ +\n\t------------------- \ +\n\ + +servertool.baddef=\u932f\u8aa4\u7684\u4f3a\u670d\u5668\u5b9a\u7fa9\uff1a {0} +servertool.nosuchserver=\t\u627e\u4e0d\u5230\u9019\u500b\u4f3a\u670d\u5668\u3002 +servertool.helddown=\t\u4f3a\u670d\u5668\u4e0d\u5728\u5de5\u4f5c\u72c0\u614b\u3002 +servertool.nosuchorb=\t\u7121\u6548\u7684 ORB. +servertool.serverup=\t\u4f3a\u670d\u5668\u5df2\u5728\u5de5\u4f5c\u72c0\u614b\u3002 +servertool.appname=\tapplicationName - {0} +servertool.name=\t\u540d\u7a31 - {0} +servertool.classpath=\tclasspath - {0} +servertool.args=\targs - {0} +servertool.vmargs=\tvmargs - {0} +servertool.serverid=\t\u4f3a\u670d\u5668 id - {0} +servertool.servernotrunning=\t\u4f3a\u670d\u5668\u672a\u904b\u4f5c\u3002 +servertool.register=\ +\n\ +\n\tregister -server \ +\n\t -applicationName \ +\n\t -classpath \ +\n\t -args \ +\n\t -vmargs \ +\n\ + +servertool.register1=\u8a3b\u518a\u4e00\u500b\u53ef\u555f\u52d5\u7684\u4f3a\u670d\u5668 +servertool.register2=\t\u5df2\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668 (serverid = {0})\u3002 +servertool.register3=\t\u5df2\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668\uff0c\u4f46\u4e0d\u5728\u5de5\u4f5c\u72c0\u614b (serverid = {0})\u3002 +servertool.register4=\t\u4f3a\u670d\u5668\u5df2\u8a3b\u518a (serverid = {0})\u3002 + +servertool.unregister=\ +\n\tunregister [ -serverid | -applicationName ] \ +\n\ + +servertool.unregister1=\u672a\u8a3b\u518a\u4e00\u500b\u5df2\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668 +servertool.unregister2=\t\u4f3a\u670d\u5668\u672a\u8a3b\u518a\u3002 + +servertool.locate=\ +\n\tlocate [ -serverid | -applicationName ] [ <-endpointType ] \ +\n\ + +servertool.locate1=\u91dd\u5c0d\u4e00\u500b\u5df2\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668\u5c0b\u627e\u7279\u5b9a\u985e\u578b\u7684\u9023\u63a5\u57e0 +servertool.locate2=\ +\n\ +\n\t\u4e3b\u6a5f\u540d\u7a31 {0} \ +\n\ +\n\t\tPort\t\tPort Type\t\tORB Id\ +\n\t\t----\t\t---------\t\t------\ +\n\ + +servertool.locateorb=\ +\n\tlocateperorb [ -serverid | -applicationName ] [ -orbid ]\ +\n\ + +servertool.locateorb1=\u91dd\u5c0d\u5df2\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668\u7684\u7279\u5b9a orb \u5c0b\u627e\u9023\u63a5\u57e0\u3002 +servertool.locateorb2=\ +\n\ +\n\t\u4e3b\u6a5f\u540d\u7a31 {0} \ +\n\ +\n\t\tPort\t\tPortType\t\tORB Id\ +\n\t\t----\t\t--------\t\t------\ +\n\ + +servertool.getserverid=\n\tgetserverid [ -applicationName ] \ +\n\ + +servertool.getserverid1=\u91dd\u5c0d\u4e00\u500b applicationName \u50b3\u56de\u4f3a\u670d\u5668\u8b58\u5225\u78bc +servertool.getserverid2=\tapplicationName \u7684\u4f3a\u670d\u5668\u8b58\u5225\u78bc {0} \u70ba {1} + +servertool.list=\n\t\u6e05\u55ae\ +\n\ + +servertool.list1=\u5217\u51fa\u6240\u6709\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668 +servertool.list2=\ +\n\t\u4f3a\u670d\u5668\u8b58\u5225\u78bc\t\u4f3a\u670d\u5668\u985e\u5225\u540d\u7a31\t\t\u4f3a\u670d\u5668\u61c9\u7528\u7a0b\u5f0f\ +\n\t---------\t-----------------\t\t------------------\ +\n\ + +servertool.listactive=\n\tlistactive +servertool.listactive1=\u5217\u51fa\u73fe\u5728\u555f\u52d5\u7684\u4f3a\u670d\u5668 +servertool.listappnames=\tlistappnames\n +servertool.listappnames1=\u5217\u51fa\u73fe\u5728\u88ab\u5b9a\u7fa9\u7684 applicationNames +servertool.listappnames2=\u73fe\u5728\u5b9a\u7fa9\u7684\u4f3a\u670d\u5668 applicationNames\uff1a + +servertool.shutdown=\ +\n\tshutdown [ -serverid | -applicationName ]\ +\n\ + +servertool.shutdown1=\u95dc\u9589\u4e00\u500b\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668 +servertool.shutdown2=\t\u4f3a\u670d\u5668\u95dc\u9589\u6210\u529f\u3002 +servertool.startserver=\ +\n\tstartup [ -serverid | -applicationName ]\ +\n\ + +servertool.startserver1=\u958b\u555f\u4e00\u500b\u8a3b\u518a\u904e\u7684\u4f3a\u670d\u5668 +servertool.startserver2=\t\u4f3a\u670d\u5668\u958b\u555f\u6210\u529f\u3002 + +servertool.quit=\n\t\u96e2\u958b\n +servertool.quit1=\u96e2\u958b\u9019\u500b\u5de5\u5177 + +servertool.help=\t\u5e6b\u52a9\ +\n\tOR\ +\n\thelp \ +\n\ + +servertool.help1=\u53d6\u5f97\u5e6b\u52a9 + +servertool.orbidmap=\t\u7528\u6cd5\uff1a orblist [ -serverid | -applicationName ]\ +\n\ + +servertool.orbidmap1=orb \u540d\u7a31\u53ca\u5176\u5c0d\u6620\u6e05\u55ae +servertool.orbidmap2=\ +\n\tORB Id\t\tORB \u540d\u7a31\ +\n\t------\t\t--------\ +\n\ + +pnameserv.success=\u6c38\u4e45\u6027 NameServer \u958b\u555f\u6210\u529f + + +bootstrap.usage=\u7528\u6cd5\uff1a {0} \ +\n\ +\n\u5176\u4e2d \u5305\u62ec\uff1a\ +\n -ORBInitialPort \u8d77\u59cb\u57e0\uff08\u5fc5\u8981\uff09\ +\n -InitialServicesFile \u542b\u6709\u8d77\u555f\u670d\u52d9\u6e05\u55ae\u7684\u6a94\u6848\uff08\u5fc5\u8981\uff09\ +\n\ + +bootstrap.success=\u8a2d\u5b9a\u9023\u63a5\u57e0\u81f3 {0} \u4e26\u5f9e {1} \u8b80\u53d6\u670d\u52d9 +bootstrap.filenotreadable=\u6a94\u6848 {0} \u7121\u6cd5\u8b80\u53d6 +bootstrap.filenotfound=\u6a94\u6848 {0} \u672a\u627e\u5230 +bootstrap.exception=\u5c07\u5c6c\u6027\u5132\u5b58\u81f3\u6a94\u6848 {0} \u6642\u767c\u751f\u7570\u5e38\uff1a\u7570\u5e38 {1} + +tnameserv.exception=\u958b\u555f {0} \u9023\u63a5\u57e0\u4e0a\u7684\u555f\u52d5\u7a0b\u5f0f\u670d\u52d9\u6642\uff0c\u767c\u751f\u7570\u5e38 +tnameserv.usage=\u8a66\u8457\u5229\u7528\u542b\u6709\u6307\u4ee4\u884c\u5f15\u6578\u7684\u4e0d\u540c\u9023\u63a5\u57e0 -ORBInitialPort +tnameserv.invalidhostoption=ORBInitialHost \u4e0d\u662f NameService \u7684\u6709\u6548\u9078\u9805 +tnameserv.orbinitialport0=ORBInitialPort 0 \u4e0d\u662f NameService \u7684\u6709\u6548\u9078\u9805 +tnameserv.hs1=\u8d77\u59cb\u547d\u540d\u5167\u6587\uff1a\n{0} +tnameserv.hs2=TransientNameServer: \u91dd\u5c0d\u8d77\u59cb\u7269\u4ef6\u53c3\u7167\uff0c\u8a2d\u5b9a\u9023\u63a5\u57e0\u81f3\uff1a{0} +tnameserv.hs3=\u5c31\u7dd2\u3002 + diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/corba/AnyEqualityTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/AnyEqualityTest.java new file mode 100644 index 000000000..164dbba2d --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/AnyEqualityTest.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import com.meterware.simplestub.Memento; +import com.meterware.simplestub.SystemPropertySupport; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; +import org.omg.CORBA.TypeCode; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class AnyEqualityTest { + List mementos = new ArrayList<>(); + + private Any any; + private Any any1; + private Any any2; + + @Before + public void setUp() throws Exception { + mementos.add(SystemPropertySupport.install("org.omg.CORBA.ORBClass", "com.sun.corba.ee.impl.orb.ORBImpl")); + ORB orb = ORB.init(new String[0], null); + any = orb.create_any(); + any1 = orb.create_any(); + any2 = orb.create_any(); + } + + @After + public void tearDown() throws Exception { + for (Memento memento : mementos) memento.revert(); + } + + @Test + public void nullAnys_areEqual() throws Exception { + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameShort_areEqual() throws Exception { + short shortData = Short.MAX_VALUE; + any1.insert_short(shortData); + any2.insert_short(shortData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameUnsignedShort_areEqual() throws Exception { + short uShortData = -1; + any1.insert_ushort(uShortData); + any2.insert_ushort(uShortData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameLong_areEqual() throws Exception { + int longData = Integer.MAX_VALUE; + any1.insert_long(longData); + any2.insert_long(longData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameUnsignedLong_areEqual() throws Exception { + int ulongData = -1; + any1.insert_ulong(ulongData); + any2.insert_ulong(ulongData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameLongLong_areEqual() throws Exception { + long longlongData = Long.MAX_VALUE; + any1.insert_longlong(longlongData); + any2.insert_longlong(longlongData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameUnsignedLongLong_areEqual() throws Exception { + long ulonglongData = -1L; + any1.insert_ulonglong(ulonglongData); + any2.insert_ulonglong(ulonglongData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameFloat_areEqual() throws Exception { + float floatData = Float.MAX_VALUE; + any1.insert_float(floatData); + any2.insert_float(floatData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameDouble_areEqual() throws Exception { + double doubleData = Double.MAX_VALUE; + any1.insert_double(doubleData); + any2.insert_double(doubleData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameChar_areEqual() throws Exception { + char charData = Character.MAX_VALUE; + any1.insert_char(charData); + any2.insert_char(charData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameOctet_areEqual() throws Exception { + byte octetData = Byte.MAX_VALUE; + any1.insert_octet(octetData); + any2.insert_octet(octetData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameAny_areEqual() throws Exception { + byte octetData = Byte.MAX_VALUE; + any.insert_octet(octetData); + + any1.insert_any(any); + any2.insert_any(any); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameTypecode_areEqual() throws Exception { + byte octetData = Byte.MAX_VALUE; + any.insert_octet(octetData); + TypeCode typeCodeData = any.type(); + + any1.insert_TypeCode(typeCodeData); + any2.insert_TypeCode(typeCodeData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameString_areEqual() throws Exception { + String stringData = "stringData"; + any1.insert_string(stringData); + any2.insert_string(stringData); + + assertTrue(any1.equal(any2)); + } + + @Test + public void twoAnysContainingTheSameEnum_areEqual() throws Exception { + Enum1 enumData = Enum1.zeroth; + Enum1Helper.insert(any1, enumData); + Enum1Helper.insert(any2, enumData); + + assertTrue(any1.equal(any2)); + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/corba/AnyImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/AnyImplTest.java new file mode 100644 index 000000000..88210cb31 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/AnyImplTest.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +import com.sun.corba.ee.spi.orb.ORB; +import org.junit.Before; +import org.junit.Test; +import org.omg.CORBA.Any; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.TCKind; + +import java.io.Serializable; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.*; + +public class AnyImplTest { + + private ORBFake orb = createStrictStub(ORBFake.class); + private Any any; + + @Before + public void setUp() throws Exception { + any = new AnyImpl(orb); + } + + @Test + public void whenAnyCreated_typeIsNull() { + assertEquals(TCKind.tk_null, any.type().kind()); + } + + @Test(expected = BAD_OPERATION.class) + public void whenReadingUninitializedAny_throwException() { + any.extract_octet(); + } + + @Test(expected = BAD_OPERATION.class) + public void whenTryingToReadWrongType_throwException() { + any.insert_octet((byte) 3); + assertThat(any.extract_double(), equalTo(3.0)); + } + + @Test + public void whenOctetInserted_canReadBackValue() { + any.insert_octet((byte) 3); + assertEquals(TCKind.tk_octet, any.type().kind()); + assertEquals(3, any.extract_octet()); + } + + @Test + public void whenShortInserted_canReadBackValue() { + any.insert_short((short) -15); + assertEquals(TCKind.tk_short, any.type().kind()); + assertEquals(-15, any.extract_short()); + } + + @Test + public void whenUnsignedShortInserted_canReadBackValue() { + any.insert_ushort((short) 127); + assertEquals(TCKind.tk_ushort, any.type().kind()); + assertEquals(127, any.extract_ushort()); + } + + @Test + public void whenLongInserted_canReadBackValue() { + any.insert_long(17); + assertEquals(TCKind.tk_long, any.type().kind()); + assertEquals(17, any.extract_long()); + } + + @Test + public void whenUnsignedLongInserted_canReadBackValue() { + any.insert_ulong(170); + assertEquals(TCKind.tk_ulong, any.type().kind()); + assertEquals(170, any.extract_ulong()); + } + + @Test + public void whenLongLongInserted_canReadBackValue() { + any.insert_longlong(Integer.MAX_VALUE); + assertEquals(TCKind.tk_longlong, any.type().kind()); + assertEquals(Integer.MAX_VALUE, any.extract_longlong()); + } + + @Test + public void whenUnsignedLongLongInserted_canReadBackValue() { + any.insert_ulonglong(Integer.MAX_VALUE); + assertEquals(TCKind.tk_ulonglong, any.type().kind()); + assertEquals(Integer.MAX_VALUE, any.extract_ulonglong()); + } + + @Test + public void whenBooleanTrueInserted_canReadBackValue() { + any.insert_boolean(true); + assertEquals(TCKind.tk_boolean, any.type().kind()); + assertTrue(any.extract_boolean()); + } + + @Test + public void whenBooleanFalseInserted_canReadBackValue() { + any.insert_boolean(false); + assertFalse(any.extract_boolean()); + } + + @Test + public void whenFloatInserted_canReadBackValue() { + any.insert_float((float) 21.3); + assertEquals(TCKind.tk_float, any.type().kind()); + assertEquals(21.3, any.extract_float(), 0.01); + } + + @Test + public void whenDoubleInserted_canReadBackValue() { + any.insert_double(-12.56); + assertEquals(TCKind.tk_double, any.type().kind()); + assertEquals(-12.56, any.extract_double(), 0.01); + } + + @Test + public void whenCharInserted_canReadBackValue() { + any.insert_char('x'); + assertEquals(TCKind.tk_char, any.type().kind()); + assertEquals('x', any.extract_char()); + } + + @Test + public void whenWideCharInserted_canReadBackValue() { + any.insert_wchar('\u0123'); + assertEquals(TCKind.tk_wchar, any.type().kind()); + assertEquals('\u0123', any.extract_wchar()); + } + + @Test + public void whenStringInserted_canReadBackValue() { + any.insert_string("This is a test"); + assertEquals(TCKind.tk_string, any.type().kind()); + assertEquals("This is a test", any.extract_string()); + } + + @Test + public void whenStringInsertedAsValue_canReadBackValue() throws Exception { + any.insert_Value("This is another test"); + + assertThat(any.type().kind(), is(TCKind.tk_value_box)); + assertThat(any.extract_Value(), equalTo((Serializable) "This is another test")); + } + + abstract static class ORBFake extends ORB { + protected ORBFake() { + initializePrimitiveTypeCodeConstants(); + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/corba/Enum1.java b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/Enum1.java new file mode 100644 index 000000000..9da7f6553 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/Enum1.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +public final class Enum1 implements org.omg.CORBA.portable.IDLEntity { + public static final int _zeroth = 0, + _first = 1, + _second = 2, + _third = 3; + public static final Enum1 zeroth = new Enum1(_zeroth); + public static final Enum1 first = new Enum1(_first); + public static final Enum1 second = new Enum1(_second); + public static final Enum1 third = new Enum1(_third); + public int value() { + return _value; + } + public static final Enum1 from_int(int i) throws org.omg.CORBA.BAD_PARAM { + switch (i) { + case _zeroth: + return zeroth; + case _first: + return first; + case _second: + return second; + case _third: + return third; + default: + throw new org.omg.CORBA.BAD_PARAM(); + } + } + private Enum1(int _value){ + this._value = _value; + } + private int _value; +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/corba/Enum1Helper.java b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/Enum1Helper.java new file mode 100644 index 000000000..b5298577e --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/corba/Enum1Helper.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.corba; + +public class Enum1Helper { + // It is useless to have instances of this class + private Enum1Helper() { } + + public static void write(org.omg.CORBA.portable.OutputStream out, Enum1 that) { + out.write_long(that.value()); + } + public static Enum1 read(org.omg.CORBA.portable.InputStream in) { + return Enum1.from_int(in.read_long()); + } + public static Enum1 extract(org.omg.CORBA.Any a) { + org.omg.CORBA.portable.InputStream in = a.create_input_stream(); + return read(in); + } + public static void insert(org.omg.CORBA.Any a, Enum1 that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + private static org.omg.CORBA.TypeCode _tc; + private static final int _memberCount = 4; + private static String[] _members = { + "zeroth", + "first", + "second", + "third" + }; + synchronized public static org.omg.CORBA.TypeCode type() { + if (_tc == null) + _tc = org.omg.CORBA.ORB.init().create_enum_tc(id(), "enum1", _members); + return _tc; + } + public static String id() { + return "IDL:anytest/enum1:1.0"; + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRInputTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRInputTest.java new file mode 100644 index 000000000..b1d60f6f9 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRInputTest.java @@ -0,0 +1,622 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.protocol.RequestCanceledException; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import org.junit.Test; +import org.omg.CORBA.*; +import org.omg.CORBA.TypeCodePackage.BadKind; + +import java.io.IOException; +import java.util.Arrays; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class CDRInputTest extends EncodingTestBase { + + @Test + public void reportMarkNotSupported() { + assertFalse(new CDRInputStream_1_0().markSupported()); + assertFalse(new CDRInputStream_1_1().markSupported()); + assertFalse(new CDRInputStream_1_2().markSupported()); + } + + @Test(expected = NO_IMPLEMENT.class) + public void reportReadNotImplented() throws IOException { + new CDRInputStream_1_0().read(); + } + + @Test(expected = NO_IMPLEMENT.class) + public void reportReadContextImplented() throws IOException { + setMessageBody(); + getInputObject().read_Context(); + } + + @Test + public void whenCDRInputObjectCreated_canReadBoolean() throws IOException { + setMessageBody(0, 1); + assertFalse(getInputObject().read_boolean()); + assertTrue(getInputObject().read_boolean()); + } + + @Test + public void whenCDRInputObjectCreated_canReadLatin1Char() throws IOException { + setCharEncoding(ISO_8859_1); + setMessageBody('x'); + assertEquals('x', getInputObject().read_char()); + } + + @Test + public void whenCDRInputObjectCreated_canReadUTF8Char() throws IOException { + setCharEncoding(UTF_8); + setMessageBody('{'); + assertEquals('{', getInputObject().read_char()); + } + + @Test(expected = MARSHAL.class) + public void whenCDRInputObjectCreated_cannotReadUTF16CharIn_1_0() throws IOException { + useV1_0(); + setWCharEncoding(UTF_16); + setMessageBody(0x04, FE, FF, 0x34, 0x56); + assertEquals('\u3456', getInputObject().read_wchar()); + } + + @Test + public void whenCDRInputObjectCreated_canReadUTF16CharIn_1_0WithLegacyORB() throws IOException { + useV1_0(); + setOrbVersion(ORBVersionFactory.getOLD()); + setWCharEncoding(UTF_16); + setMessageBody(0x34, 0x56); + assertEquals('\u3456', getInputObject().read_wchar()); + } + + @Test + public void whenCDRInputObjectCreated_canReadLittleEndianUTF16CharIn_1_0WithLegacyORB() throws IOException { + useV1_0(); + useLittleEndian(); + setOrbVersion(ORBVersionFactory.getOLD()); + setWCharEncoding(UTF_16); + setMessageBody(0x34, 0x56); + assertEquals('\u5634', getInputObject().read_wchar()); + } + + @Test + public void whenCDRInputObjectCreated_canReadUTF16CharIn_1_1() throws IOException { + useV1_1(); + setWCharEncoding(UTF_16); + setMessageBody(0x34, 0x56); + assertEquals('\u3456', getInputObject().read_wchar()); + } + + @Test + public void whenCDRInputObjectCreated_canReadUTF16CharIn_1_2() throws IOException { + useV1_2(); + setWCharEncoding(UTF_16); + setMessageBody(0x04, FE, FF, 0x34, 0x56); + assertEquals('\u3456', getInputObject().read_wchar()); + } + + @Test + public void whenCDRInputObjectCreated_canReadOctet() throws IOException { + setMessageBody(25); + CDRInputObject inputObject = getInputObject(); + assertEquals(25, inputObject.read_octet()); + } + + @Test + public void can_read_integers() { + setMessageBody(0x04, pad(), /* short*/ FF, (byte) 0xf2, + /* short */ 0x00, 0x03, + pad(), pad(), + /* long1 */ 0, 1, 2, (byte) 0x83, + /* long2 */ FF, FF, (byte) 0xfd, 0x71, + pad(), pad(), pad(), pad(), + /* long long */ 0, 0, 1, 0, 0, (byte) 0x80, 1, 7, + /* long long */ 0, 0, 1, 0, 0, 0, 1, 2); + + assertEquals("Octet value", 4, getInputObject().read_octet()); + assertEquals("Signed short value", -14, getInputObject().read_short()); + assertEquals("Standard unsigned short value", 3, getInputObject().read_ushort()); + assertEquals("Unsigned long value", 66179, getInputObject().read_ulong()); + assertEquals("Long value", -655, getInputObject().read_long()); + assertEquals("Long long value", 1099520016647L, getInputObject().read_longlong()); + assertEquals("Unsigned long long value", 1099511628034L, getInputObject().read_ulonglong()); + } + + @Test + public void can_read_little_endian_integers() { + setMessageBody(0x04, pad(), + /* short*/ 0xf2, FF, + /* ushort */ 0x03, 0x00, + /* for long */ pad(), pad(), + /* long */ 0x83, 2, 1, 0, + /* ulong */ 0x71, 0xfd, FF, FF, + /* for long_long */ pad(), pad(), pad(), pad(), + /* long long */ 7, 1, 0x80, 0, 0, 1, 0, 0); + useLittleEndian(); + + assertEquals("Octet value", 4, getInputObject().read_octet()); + assertEquals("Signed short value", -14, getInputObject().read_short()); + assertEquals("Standard unsigned short value", 3, getInputObject().read_ushort()); + assertEquals("Unsigned long value", 66179, getInputObject().read_ulong()); + assertEquals("Long value", -655, getInputObject().read_long()); + assertEquals("Long long value", 1099520016647L, getInputObject().read_longlong()); + } + + @Test + public void can_read_floats() { + setMessageBody(0x3f, 0x80, 0, 0, + 0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55); + + assertEquals("Float", 1, getInputObject().read_float(), 0.001); + assertEquals("Double", 0.33333, getInputObject().read_double(), 0.001); + } + + @Test + public void can_read_float_arrays() { + setMessageBody(0x3f, 0x80, 0, 0, + 0x46, 0x40, 0xE4, 0x7E); + float[] actual = new float[2]; + getInputObject().read_float_array(actual, 0, 2); + + assertEquals("Float 1", 1, actual[0], 0.001); + assertEquals("Float 2", 12345.12346f, actual[1], 0.001); + } + + @Test + public void can_read_double_arrays() { + setMessageBody(pad(), pad(), pad(), pad(), + 0x3f, 0xd5, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x40, 0, 0, 0, 0, 0, 0, 0); + double[] actual = new double[2]; + getInputObject().read_double_array(actual, 0, 2); + + assertEquals("Double 1", 0.33333, actual[0], 0.001); + assertEquals("Double 2", 2, actual[1], 0.001); + } + + @Test + public void whenUsingV1_0_canReadCharString() { + useV1_0(); + setMessageBody(0, 0, 0, 11, 't', 'h', 'i', 's', ' ', 'w', 'o', 'r', 'k', 's', 0); + + assertEquals("String value", "this works", getInputObject().read_string()); + } + + @Test + public void canReadNullStringFromOldOrb() { + setOrbVersion(ORBVersionFactory.getOLD()); + setMessageBody(0, 0, 0, 0); + assertEquals("", getInputObject().read_string()); + } + + @Test + public void canReadStringFromOldOrb() { + setOrbVersion(ORBVersionFactory.getOLD()); + setMessageBody(0, 0, 0, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 0); + assertEquals("abcdefgh", getInputObject().read_string()); + } + + @Test + public void canReadStringFromOldOrbAcrossFragment() { + useV1_1(); + setOrbVersion(ORBVersionFactory.getOLD()); + setMessageBody(0, 0, 0, 9, 'a', 'b', 'c', 'd'); + addFragment('e', 'f', 'g', 'h', 0); + assertEquals("abcdefgh", getInputObject().read_string()); + } + + @Test + public void canReadStringFromOldOrbWithTerminatorInNextFragment() { + useV1_1(); + setOrbVersion(ORBVersionFactory.getOLD()); + setMessageBody(0, 0, 0, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ); + addFragment(0, 'x'); + assertEquals("abcdefgh", getInputObject().read_string()); + assertEquals('x', getInputObject().read_char()); + } + + @Test(expected = MARSHAL.class) + public void whenUsingV1_0_cannotReadWCharString() { + useV1_0(); + int[] data = {0, 0, 0, 22, FE, FF, + 0, 'T', 0, 'h', 0, 'i', 0, 's', 0, ',', 0, ' ', 0, 't', 0, 'o', 0, 'o', 0, '!'}; + setMessageBody(data); + assertEquals("Wide string value", "This, too!", getInputObject().read_wstring()); + } + + @Test + public void whenUsingV1_1_canReadCharAndWCharStrings() { + useV1_1(); + int[] data = {0, 0, 0, 11, 't', 'h', 'i', 's', ' ', 'w', 'o', 'r', 'k', 's', 0, + pad(), + 0, 0, 0, 11, + 0, 'T', 0, 'h', 0, 'i', 0, 's', 0, ',', 0, ' ', 0, 't', 0, 'o', 0, 'o', 0, '!', + 0, 0, + pad(), pad(), 0, 0, 0, 0}; + setMessageBody(data); + + assertEquals("String value", "this works", getInputObject().read_string()); + assertEquals("Wide string value", "This, too!", getInputObject().read_wstring()); + assertEquals("position before reading empty string", 54, getInputObject().getPosition()); + assertEquals("Empty string value", "", getInputObject().read_wstring()); + } + + @Test + public void whenUsingV1_2_canReadCharAndWCharStrings() { + useV1_2(); + int[] data = {0, 0, 0, 11, 't', 'h', 'i', 's', ' ', 'w', 'o', 'r', 'k', 's', 0, + pad(), + 0, 0, 0, 22, FE, FF, + 0, 'T', 0, 'h', 0, 'i', 0, 's', 0, ',', 0, ' ', 0, 't', 0, 'o', 0, 'o', 0, '!', + pad(), pad(), 0, 0, 0, 0}; + setMessageBody(data); + + assertEquals("String value", "this works", getInputObject().read_string()); + assertEquals("Wide string value", "This, too!", getInputObject().read_wstring()); + assertEquals("Empty string value", "", getInputObject().read_wstring()); + } + + @Test + public void can_read_boolean_array() throws Exception { + final int[] data = {1, FF, 0, 7, 0}; + final boolean[] expected = {true, true, false, true, false}; + setMessageBody(data); + readAndVerifyBooleanArray(expected); + } + + private void readAndVerifyBooleanArray(boolean[] expected) { + boolean[] actual = new boolean[expected.length]; + + getInputObject().read_boolean_array(actual, 0, expected.length); + + if (!Arrays.equals(expected, actual)) { + fail("Expected " + Arrays.toString(expected) + " but found " + Arrays.toString(actual)); + } + } + + @Test + public void can_read_octet_array() throws Exception { + final int[] data = {0, 1, 2, 3, -1, -1}; + final byte[] expected = {0, 1, 2, 3, -1, -1}; + setMessageBody(data); + readAndVerifyOctetArray(expected); + } + + @Test + public void can_read_octet_array_acrossFragments() throws Exception { + useV1_2(); + final int[] data = {0, 1, 2, 3}; + final byte[] expected = {0, 1, 2, 3, -1, -1}; + setMessageBody(data); + addFragment(-1, -1); + readAndVerifyOctetArray(expected); + } + + private void readAndVerifyOctetArray(byte[] expected) { + byte[] actual = new byte[expected.length]; + + getInputObject().read_octet_array(actual, 0, expected.length); + assertArrayEquals("Octet array", expected, actual); + } + + + @Test + public void can_read_short_array() throws Exception { + final int[] data = {0, 1, 2, 3, -1, -1}; + final short[] expected = {1, 515, -1}; + setMessageBody(data); + readAndVerifyShortArray(expected); + } + + private void readAndVerifyShortArray(short[] expected) { + short[] actual = new short[expected.length]; + + getInputObject().read_short_array(actual, 0, expected.length); + assertArrayEquals(expected, actual); + } + + + @Test + public void can_read_ushort_array() throws Exception { + final int[] data = {0, 1, 2, 3}; + final short[] expected = {1, 515}; + setMessageBody(data); + readAndVerifyUshortArray(expected); + } + + private void readAndVerifyUshortArray(short[] expected) { + short[] actual = new short[expected.length]; + + getInputObject().read_ushort_array(actual, 0, expected.length); + assertArrayEquals(expected, actual); + } + + + @Test + public void can_read_long_array() throws Exception { + final int[] data = {0, 1, 2, 3, -1, -1, -3, 30}; + final int[] expected = {66051, -738}; + setMessageBody(data); + readAndVerifyLongArray(expected); + } + + private void readAndVerifyLongArray(int[] expected) { + int[] actual = new int[expected.length]; + + getInputObject().read_long_array(actual, 0, expected.length); + assertArrayEquals(expected, actual); + } + + + @Test + public void can_read_ulong_array() throws Exception { + final int[] data = {0, 1, 2, 3, -1, -1, -3, 30}; + final int[] expected = {66051, -738}; + setMessageBody(data); + readAndVerifyULongArray(expected); + } + + private void readAndVerifyULongArray(int[] expected) { + int[] actual = new int[expected.length]; + + getInputObject().read_ulong_array(actual, 0, expected.length); + + assertArrayEquals(expected, actual); + } + + @Test + public void can_read_longlong_array() throws Exception { + final int[] data = {pad(), pad(), pad(), pad(), 0, 0, 1, 0, 0, 0, 1, 7, -1, -1, -1, -1, -1, -1, -3, -20}; + final long[] expected = {1099511628039L, -532}; + setMessageBody(data); + + readAndVerifyLongLongArray(expected); + } + + private void readAndVerifyLongLongArray(long[] expected) { + long[] actual = new long[expected.length]; + + getInputObject().read_longlong_array(actual, 0, expected.length); + + assertArrayEquals(expected, actual); + } + + @Test + public void can_read_ulonglong_array() throws Exception { + final int[] data = {pad(), pad(), pad(), pad(), 0, 0, 1, 0, 0, 0, 1, 7, FF, FF, FF, FF, FF, FF, -3, -20}; + final long[] expected = {1099511628039L, -532}; + setMessageBody(data); + readAndVerifyULongLongArray(expected); + } + + private void readAndVerifyULongLongArray(long[] expected) { + long[] actual = new long[expected.length]; + + getInputObject().read_ulonglong_array(actual, 0, expected.length); + + if (!Arrays.equals(expected, actual)) { + fail("Expected " + Arrays.toString(expected) + " but found " + Arrays.toString(actual)); + } + } + + @Test + public void can_read_char_array() throws Exception { + final int[] data = {'b', 'u', 'c', 'k', 'l', 'e', 'u', 'p'}; + final char[] expected = {'b', 'u', 'c', 'k', 'l', 'e', 'u', 'p'}; + setMessageBody(data); + readAndVerifyCharArray(expected); + } + + private void readAndVerifyCharArray(char[] expected) { + char[] actual = new char[expected.length]; + + getInputObject().read_char_array(actual, 0, expected.length); + + assertArrayEquals(expected, actual); + } + + @Test + public void can_read_wchar_array() throws Exception { + useV1_2(); + final int[] data = {4, FE, FF, 0, 'b', 4, FE, FF, 0, 'u', 4, FF, FE, 't', 0}; + final char[] expected = {'b', 'u', 't'}; + setMessageBody(data); + readAndVerifyWCharArray(expected); + } + + private void readAndVerifyWCharArray(char[] expected) { + char[] actual = new char[expected.length]; + + getInputObject().read_wchar_array(actual, 0, expected.length); + + assertArrayEquals(expected, actual); + } + + @Test(expected = MARSHAL.class) + public void whenUsingV1_0_throwExceptionOnUnexpectedEndOfData() { + useV1_0(); + setMessageBody(0, 0); + getInputObject().read_long(); + } + + @Test + public void whenUsingV1_2_headerPaddingForces8ByteAlignmentOnce() { + useV1_2(); + setMessageBody(pad(), pad(), pad(), pad(), + 0, 0, 1, 0, + FF, FF, FF, FF); + + getInputObject().setHeaderPadding(true); + assertEquals(256, getInputObject().read_long()); + assertEquals(-1, getInputObject().read_long()); + } + + @Test + public void whenMarkIsSetInV1_0_restoreAllowsReread() { + useV1_0(); + setMessageBody(0, 0, 1, 23, 'x'); + getInputObject().mark(0); + assertEquals(0, getInputObject().read_short()); + getInputObject().reset(); + assertEquals(279, getInputObject().read_long()); + } + + @Test + public void whenMarkIsSetInV1_2_restoreAllowsReread() { + useV1_2(); + setMessageBody(0, 0, 1, 23, 'x'); + getInputObject().mark(0); + assertEquals(0, getInputObject().read_short()); + getInputObject().reset(); + assertEquals(279, getInputObject().read_long()); + } + + @Test + public void whenUsingV1_2_continueReadingOnToFragment() { + useV1_2(); + setMessageBody(0, 0, 1, 23); + addFragment(0, 7); + getInputObject().read_long(); + assertEquals(7, getInputObject().read_short()); + } + + @Test + public void whenUsingV1_2_skipPaddingBeforeReadingNextFragment() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + addFragment(0, 0, 0, 7); + getInputObject().read_short(); + assertEquals(7, getInputObject().read_long()); + } + + @Test + public void whenUsingV1_1_skipOptionalPaddingBeforeReadingNextFragment() { + useV1_1(); + setMessageBody(0, 23, pad(), pad()); + addFragment(0, 0, 0, 7); + getInputObject().read_short(); + assertEquals(7, getInputObject().read_long()); + } + + @Test + public void whenUsingV1_1_alignToStartOfNextFragment() { + useV1_1(); + setMessageBody(0, 23); + addFragment(0, 0, 0, 7); + getInputObject().read_short(); + assertEquals(7, getInputObject().read_long()); + } + + @Test(expected = RequestCanceledException.class) + public void whenUsingV1_2_throwExceptionIfCanceled() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + getInputObject().read_short(); + getInputObject().cancelProcessing(0); + getInputObject().read_long(); + } + + @Test(expected = MARSHAL.class) + public void whenUsingV1_2_throwExceptionOnReadPastEnd() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test(expected = COMM_FAILURE.class) + public void whenUsingV1_2_throwExceptionOnTimeout() { + useV1_2(); + expectMoreFragments(); + setMessageBody(0, 23, pad(), pad()); + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test + public void whenUsingV1_2_interruptedThreadDoesNotCauseTimeout() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + expectMoreFragments(); + + whileWaitingForFragmentsDo(new AsynchronousAction() { + int iteration = 0; + public void exec() { + if (iteration++ == 0) + Thread.currentThread().interrupt(); + else + addFragment(0, 0, 0, 7); + } + }); + + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test(expected = RequestCanceledException.class) + public void whenUsingV1_2_throwExceptionWhenCanceledDuringWait() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + expectMoreFragments(); + + whileWaitingForFragmentsDo(new AsynchronousAction() { + public void exec() { + addFragment(0, 0, 0, 7); + getInputObject().cancelProcessing(0); + } + }); + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test + public void whenTypeCodeHasNoBody_readKindOnly() { + setMessageBody( 0, 0, 0, 6); + TypeCode typeCode = getInputObject().read_TypeCode(); + assertEquals(TCKind.tk_float, typeCode.kind()); + } + + @Test + public void whenTypeCodeIsString_readLength() throws BadKind { + setMessageBody( 0, 0, 0, 18, 0, 0, 1, 0); + TypeCode typeCode = getInputObject().read_TypeCode(); + assertEquals(TCKind.tk_string, typeCode.kind()); + assertEquals(256, typeCode.length()); + } + + @Test + public void whenTypeCodeIsFixed_readDigitsAndScale() throws BadKind { + setMessageBody( 0, 0, 0, 28, 0, 10, 0, 6); + TypeCode typeCode = getInputObject().read_TypeCode(); + assertEquals(TCKind.tk_fixed, typeCode.kind()); + assertEquals(10, typeCode.fixed_digits()); + assertEquals(6, typeCode.fixed_scale()); + } + + @Test + public void whenValueIsZero_returnNull() { + setMessageBody(0, 0, 0, 0); + assertNull(getInputObject().read_value()); + } + + @Test + public void whenCloneEncapsInputStream_readFromClone() { + setMessageBody(); + EncapsInputStream inputStream1 = createEncapsulatedInputStream(0, 0, 1, 5); + EncapsInputStream inputStream2 = new EncapsInputStream(inputStream1); + assertEquals(261, inputStream2.read_long()); + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRInputValueTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRInputValueTest.java new file mode 100644 index 000000000..cd456d8d1 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRInputValueTest.java @@ -0,0 +1,425 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import org.junit.Test; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.portable.IndirectionException; + +import java.io.IOException; +import java.io.Serializable; +import java.net.InetAddress; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.sameInstance; +import static org.junit.Assert.*; + +public class CDRInputValueTest extends ValueTestBase { + + + @Test + public void canReadStringValue() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(RepositoryId.kWStringValueRepID); + writeStringValue_1_2("This, too!"); + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue( object instanceof String); + assertEquals("This, too!", object); + } + + @Test + public void canReadStringValueInAChunk() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(RepositoryId.kWStringValueRepID); + + startChunk(); + writeStringValue_1_2("This, too!"); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof String); + assertEquals("This, too!", object); + } + + @Test(expected = MARSHAL.class) + public void whenRepIdNotRecognized_throwException() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId("RMI:com.sun.corba.ee.impl.encoding.NoSuchValue:3E1F37A79F0D0984:F72C4A0542764A7B"); + + writeWchar_1_2('x'); + writeInt(3); + + setMessageBody( getGeneratedBody() ); + + getInputObject().read_value(); + } +/* + + static final String VALUE1_REPID2 = "RMI:com.sun.corba.ee.impl.encoding.Value1:3E1F37A79F0B1235:F72C4A0542764A7B"; + + @Test + public void canReadSerializedValueWithMismatchedRepID() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(VALUE1_REPID2); + + writeWchar_1_2('x'); + writeInt(7); + writeInt(3); + + setMessageBody(getGeneratedBody()); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals(3, value1.anInt); + } +*/ + + @Test + public void canReadSerializedValue() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_2('x'); + writeInt(3); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals(3, value1.anInt); + } + + @Test + public void canReadSerializedEnum() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(Enum1.REPID); + + writeString(Enum1.strange.toString()); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertEquals( Enum1.strange, object); + } + + @Test + public void canReadIDLEntity() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(IDLValue.REPID); + + int aByte = 0x45; + writeByte(aByte); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof IDLValue); + IDLValue value = (IDLValue) object; + assertEquals(0x45, value.aByte); + assertEquals(0x450, value.anInt); + } + + @Test + public void canReadSerializedValueWithIndirection() throws IOException { + int location = getCurrentLocation(); + writeValueTag(ONE_REPID_ID | USE_CODEBASE); + writeCodebase("ignore this"); + writeRepId(Value1.REPID); + + writeWchar_1_2('x'); + writeInt(3); + writeIndirectionTo(location); + + setMessageBody( getGeneratedBody() ); + + Object object1 = getInputObject().read_value(); + Object object2 = getInputObject().read_value(); + assertSame(object1, object2); + } + + @Test + public void canReadSerializedValueWithIndirection_in1_1() throws IOException { + useV1_1(); + int location = getCurrentLocation(); + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_1('x'); + writeInt(3); + writeIndirectionTo(location); + + setMessageBody( getGeneratedBody() ); + + Object object1 = getInputObject().read_value(); + Object object2 = getInputObject().read_value(); + assertSame(object1, object2); + assertEquals('x', ((Value1) object1).aChar); + } + + @Test + public void canReadSerializedValueWithIndirection_in1_0() throws IOException { + useV1_0(); + setOrbVersion(ORBVersionFactory.getOLD()); + int location = getCurrentLocation(); + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_1('x'); + writeInt(3); + writeIndirectionTo(location); + + setMessageBody( getGeneratedBody() ); + + Object object1 = getInputObject().read_value(); + Object object2 = getInputObject().read_value(); + assertSame(object1, object2); + assertEquals( 'x', ((Value1) object1).aChar); + } + + @Test + public void canReadSerializedValueInChunk() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals(3, value1.anInt); + } + + @Test + public void canReadSerializedValueWithContinuationChunk() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + + startChunk(); + writeWchar_1_2('x'); + endChunk(); + + startChunk(); + writeInt(3); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals(3, value1.anInt); + } + + @Test + public void canReadSerializedValueWithNestedValue() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value2.REPID); + + startChunk(); + writeLong(750); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value2); + Value2 value2 = (Value2) object; + assertEquals(750,value2.aLong); + assertEquals('x', value2.aValue.aChar); + assertEquals(3, value2.aValue.anInt); + } + + @Test(expected = MARSHAL.class) + public void whenEndTagTooSmall_throwException() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value2.REPID); + + startChunk(); + writeLong(750); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-3); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + getInputObject().read_value(); + } + + @Test + public void whenTalkingtoLegacyORBAndEndTagTooSmall_ignoreIt() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value2.REPID); + + startChunk(); + writeLong(750); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value2); + Value2 value2 = (Value2) object; + assertEquals(750,value2.aLong); + assertEquals('x', value2.aValue.aChar); + assertEquals(3, value2.aValue.anInt); + } + + @Test + public void canReadSerializedValueUsingDefaultFactory() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CODEBASE); + writeCodebase("http://localhost/myClasses"); + writeRepId(Value1.REPID); + + writeWchar_1_2('x'); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(Value1.REPID); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals('x', value1.anInt); + } + + @Test + public void canReadNullValueUsingDefaultFactory() throws IOException { + writeNull(); + setMessageBody( getGeneratedBody() ); + + assertNull(getInputObject().read_value(Value1.REPID)); + } + + @Test(expected = IndirectionException.class) + public void whenIndirectionHasNoAntecedent_throwExceptionWhenUsingRepId() throws IOException { + writeIndirectionTo(0); + setMessageBody( getGeneratedBody() ); + getInputObject().read_value(Value1.REPID); + } + + @Test + public void canReadSerializedValueUsingDefaultFactoryAndIndirection() throws IOException { + int location = getCurrentLocation(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + startChunk(); + writeWchar_1_2('x'); + endChunk(); + writeEndTag(-1); + + writeIndirectionTo(location); + + setMessageBody( getGeneratedBody() ); + + Object object1 = getInputObject().read_value(Value1.REPID); + Object object2 = getInputObject().read_value(Value1.REPID); + assertSame(object1, object2); + } + + + @Test + public void whenObjectImplementsReadResolve_resultingValueMatchesOriginal() throws Exception { + writeValueTag(ONE_REPID_ID); + writeRepId(Gender.REPID); + writeInt(0); // the serialized form of the MALE constant, produced by writeReplace + setMessageBody(getGeneratedBody()); + + assertThat(getInputObject().read_value(), sameInstance((Serializable) Gender.MALE)); + } + + @Test + public void whenInaccessibleObjectImplementsReadResolve_resultingValueEqualToOriginal() throws Exception { + String InetAddressRepId = "RMI:java.net.InetAddress:C156A93A2ABC4FAF:2D9B57AF9FE3EBDB"; + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); // custom marshalling requires a chunk + writeRepId(InetAddressRepId); + + startChunk(); + writeInt(0x01010000); + writeInt(0x7F000001); // 127.0.0.1 + writeInt(0x00000002); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); // custom marshalling requires a chunk + writeRepId("IDL:omg.org/CORBA/WStringValue:1.0"); + startChunk(); + writeStringValue_1_2("localhost"); + endChunk(); + writeEndTag(-1); + + setMessageBody(getGeneratedBody()); + + assertThat(getInputObject().read_value(), equalTo((Serializable) InetAddress.getLoopbackAddress())); + } + + @Test + public void whenObjectExternalizable_callReadExternal() throws Exception { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); // custom marshalling requires a chunk + writeRepId(Profession.REPID); + + startChunk(); + writeByte(1); // serial format version + writeInt(5); + endChunk(); + writeEndTag(-1); + + setMessageBody(getGeneratedBody()); + Serializable value = getInputObject().read_value(); + + assertThat(value, instanceOf(Profession.class)); + Profession profession = (Profession) value; + assertThat(profession.getProfession(), equalTo("Lawyer")); + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRMemoryManagementTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRMemoryManagementTest.java new file mode 100644 index 000000000..f0e4b981f --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDRMemoryManagementTest.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class CDRMemoryManagementTest extends EncodingTestBase { + + @Test + public void whenFinishReadingFragment_dontReleaseIt() { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + + getInputObject().read_long(); + + assertEquals(0, getNumBuffersReleased()); + } + + @Test + public void whenStartReadingNextFragment_releasePreviousFragment() { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + + getInputObject().read_long(); + getInputObject().read_long(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void whenStartReadingNextFragmentWhileMarkActive_dontReleasePreviousFragment() { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + + getInputObject().read_long(); + getInputObject().mark(0); + getInputObject().read_long(); + + assertEquals(0, getNumBuffersReleased()); + } + + @Test + public void whenStartReadingNextFragmentWhileMarkActive_releasePreviousFragmentOnResetAndNewRead() { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + + getInputObject().read_long(); + getInputObject().mark(0); + getInputObject().read_long(); + getInputObject().reset(); + getInputObject().read_long(); + + assertEquals(1, getNumBuffersReleased()); + } + + + @Test + public void whenFragmentAddedAfterMarkActive_releaseSubsequentFragmentOnClose() throws IOException { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + + getInputObject().read_long(); + getInputObject().mark(0); + getInputObject().read_long(); + getInputObject().close(); + + assertEquals(2, getNumBuffersReleased()); + } + + @Test + public void whenInputObjectClosed_releaseAllFragments() throws IOException { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + addFragment(0, 0, 0, 3); + + getInputObject().read_short(); + getInputObject().close(); + + assertEquals(3, getNumBuffersReleased()); + } + + @Test + public void whenInputObjectClosedWhileMarkActive_releaseAllFragments() throws IOException { + setMessageBody(0, 0, 0, 1); + addFragment(0, 0, 0, 2); + + getInputObject().read_short(); + getInputObject().mark(0); + getInputObject().close(); + + assertEquals(2, getNumBuffersReleased()); + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDROutputTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDROutputTest.java new file mode 100644 index 000000000..46347b36c --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDROutputTest.java @@ -0,0 +1,607 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.corba.AnyImpl; +import com.sun.corba.ee.impl.corba.TypeCodeImpl; +import com.sun.corba.ee.impl.io.ValueUtility; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import org.junit.Test; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA_2_3.portable.InputStream; + +import java.io.IOException; +import java.io.Serializable; + +import static org.junit.Assert.assertEquals; + +public class CDROutputTest extends EncodingTestBase { + + + @Test + public void whenCDROutputObjectCreated_canWriteBoolean() throws IOException { + getOutputObject().write_boolean(false); + getOutputObject().write_boolean(true); + + expectByteArray(new byte[]{0, 1}); + } + + @Test + public void canWriteLatin1Char() throws IOException { + setCharEncoding(ISO_8859_1); + getOutputObject().write_char('x'); + + expectByteArray('x'); + } + + @Test + public void caWriteUTF8Char() throws IOException { + setCharEncoding(UTF_8); + getOutputObject().write_char('x'); + + expectByteArray('x'); + } + + @Test(expected = MARSHAL.class) + public void whenCDROutputObjectCreated_cannotWriteUTF16CharIn_1_0() throws IOException { + useV1_0(); + setWCharEncoding(UTF_16); + + getOutputObject().write_wchar('\u3456'); + } + + @Test + public void canWriteUTF16CharIn_1_0WithLegacyORB() throws IOException { + useV1_0(); + setOrbVersion(ORBVersionFactory.getOLD()); + setWCharEncoding(UTF_16); + + getOutputObject().write_wchar('\u3456'); + expectByteArray(0x34, 0x56); + } + + @Test + public void canWriteUTF16CharIn_1_1() throws IOException { + useV1_1(); + setWCharEncoding(UTF_16); + + getOutputObject().write_wchar('\u3456'); + expectByteArray(0x34, 0x56); + } + + @Test + public void canWriteUTF16CharIn_1_2() throws IOException { + useV1_2(); + setWCharEncoding(UTF_16); + + getOutputObject().write_wchar('\u3456'); + expectByteArray(0x04, FE, FF, 0x34, 0x56); + } + + @Test + public void canWriteIntegers() { + getOutputObject().write_octet((byte) 4); + getOutputObject().write_short((short) -14); + getOutputObject().write_ushort((short) 3); + getOutputObject().write_ulong(66179); + getOutputObject().write_long(-655); + getOutputObject().write_longlong(1099520016647L); + getOutputObject().write_ulonglong(1099511628034L); + + expectByteArray(0x04, PAD, FF, (byte) 0xf2, + 0x00, 0x03, // short + PAD, PAD, + 0, 1, 2, (byte) 0x83, // long1 + FF, FF, (byte) 0xfd, 0x71, // long2 + PAD, PAD, PAD, PAD, + 0, 0, 1, 0, 0, (byte) 0x80, 1, 7, // longlong1 + 0, 0, 1, 0, 0, 0, 1, 2); // ulonglong2 + } + + @Test + public void canWritefloats() { + getOutputObject().write_float(1); + getOutputObject().write_double(0.25); + expectByteArray(0x3f, 0x80, 0, 0, + 0x3f, 0xd0, 0, 0, 0, 0, 0, 0); + } + + @Test + public void can_write_float_arrays() { + getOutputObject().write_float_array(new float[]{1, .0625f}, 0, 2); + + expectByteArray(0x3f, 0x80, 0, 0, + 0x3d, 0x80, 0, 0); + } + + @Test + public void can_write_double_arrays() { + getOutputObject().write_double_array(new double[]{0.25, 2}, 0, 2); + + expectByteArray(PAD, PAD, PAD, PAD, + 0x3f, 0xd0, 0, 0, 0, 0, 0, 0, + 0x40, 0, 0, 0, 0, 0, 0, 0); + } + + @Test + public void whenUsingV1_0_canWriteCharString() { + useV1_0(); + getOutputObject().write_string("this works"); + + expectByteArray(0, 0, 0, 11, 't', 'h', 'i', 's', ' ', 'w', 'o', 'r', 'k', 's', 0); + } + + @Test(expected = BAD_PARAM.class) + public void whenNullStringWritten_throwException() { + getOutputObject().write_string(null); + } + + @Test(expected = BAD_PARAM.class) + public void whenNullWStringWritten_throwExceptionIn1_0() { + useV1_0(); + getOutputObject().write_wstring(null); + } + + @Test(expected = BAD_PARAM.class) + public void whenNullWStringWritten_throwExceptionIn1_1() { + useV1_1(); + getOutputObject().write_wstring(null); + } + + @Test(expected = BAD_PARAM.class) + public void whenNullWStringWritten_throwExceptionIn1_2() { + useV1_2(); + getOutputObject().write_wstring(null); + } + + @Test(expected = MARSHAL.class) + public void whenWriteWStringToForeignOrb_throwException() { + useV1_0(); + getOutputObject().write_wstring("This should fail"); + } + + @Test + public void whenUsingV1_0WithLegacyOrb_canReadWCharString() { + useV1_0(); + setOrbVersion(ORBVersionFactory.getOLD()); + getOutputObject().write_wstring("This works"); + + expectByteArray(0, 0, 0, 11, + 0, 'T', 0, 'h', 0, 'i', 0, 's', 0, ' ', 0, 'w', 0, 'o', 0, 'r', 0, 'k', 0, 's', 0, 0); + } + + @Test + public void whenUsingV1_1_canWriteCharAndWCharStrings() { + useV1_1(); + getOutputObject().write_string("this works"); + getOutputObject().write_wstring("This, too!"); + expectByteArray(0, 0, 0, 11, 't', 'h', 'i', 's', ' ', 'w', 'o', 'r', 'k', 's', 0, + PAD, + 0, 0, 0, 11, + 0, 'T', 0, 'h', 0, 'i', 0, 's', 0, ',', 0, ' ', 0, 't', 0, 'o', 0, 'o', 0, '!', + 0, 0); + } + + @Test + public void whenUsingV1_2_canWriteCharAndWCharStrings() { + useV1_2(); + getOutputObject().write_string("this works"); + getOutputObject().write_wstring("This, too!"); + expectByteArray(0, 0, 0, 11, 't', 'h', 'i', 's', ' ', 'w', 'o', 'r', 'k', 's', 0, + PAD, + 0, 0, 0, 22, FE, FF, + 0, 'T', 0, 'h', 0, 'i', 0, 's', 0, ',', 0, ' ', 0, 't', 0, 'o', 0, 'o', 0, '!'); + } + + @Test + public void canWriteBooleanArray() { + getOutputObject().write_boolean_array(new boolean[]{true, true, false, true, false}, 0, 4); + + expectByteArray(1, 1, 0, 1); + } + + @Test + public void canWriteOctetArray() { + getOutputObject().write_octet_array(new byte[]{2, -3, 6, 2}, 0, 4); + + expectByteArray(2, -3, 6, 2); + } + + @Test + public void writingEmptyOctetArray_doesNotDoEightByteAlign() { + getOutputObject().setHeaderPadding(true); + getOutputObject().write_octet_array(new byte[]{}, 0, 0); + + expectByteArray( new byte[0] ); + } + + @Test(expected = BAD_PARAM.class) + public void whenWritingNullArray_anExceptionIsThrown() { + getOutputObject().write_octet_array(null, 0, 4); + } + + @Test + public void canWriteShortArray() { + getOutputObject().write_short_array(new short[]{-3, 1, 515, -1}, 1, 3); + + expectByteArray(0, 1, 2, 3, -1, -1); + } + + @Test + public void canWriteUShortArray() { + getOutputObject().write_short_array(new short[] {-3, 1, 515, -1}, 0, 2); + + expectByteArray(FF, 0xfd, 0, 1); + } + + @Test + public void canWriteLongArray() { + getOutputObject().write_long_array(new int[]{66051, -738}, 0, 2); + + expectByteArray(0, 1, 2, 3, -1, -1, -3, 30); + } + + @Test + public void canWriteULongArray() { + getOutputObject().write_ulong_array(new int[]{66051, -738}, 0, 2); + + expectByteArray(0, 1, 2, 3, -1, -1, -3, 30); + } + + @Test + public void canWriteLongLongArray() { + getOutputObject().write_longlong_array(new long[]{1099511628039L, -532}, 0, 2); + + expectByteArray(PAD, PAD, PAD, PAD, 0, 0, 1, 0, 0, 0, 1, 7, -1, -1, -1, -1, -1, -1, -3, -20); + } + + @Test + public void canWriteULongLongArray() { + getOutputObject().write_ulonglong_array(new long[]{1099511628039L, -532}, 0, 2); + + expectByteArray(PAD, PAD, PAD, PAD, 0, 0, 1, 0, 0, 0, 1, 7, -1, -1, -1, -1, -1, -1, -3, -20); + } + + @Test + public void canWriteCharArray() { + getOutputObject().write_char_array(new char[]{'b', 'u', 'c', 'k', 'l', 'e', 'u', 'p'}, 0, 8); + + expectByteArray('b', 'u', 'c', 'k', 'l', 'e', 'u', 'p'); + } + + @Test + public void canWriteWCharArray() { + getOutputObject().write_wchar_array(new char[]{'b', 'u', 't'}, 0, 3); + + expectByteArray(4, FE, FF, 0, 'b', 4, FE, FF, 0, 'u', 4, FE, FF, 0, 't'); + } + + @Test + public void canWriteTypeCode_withNoBody() { + getOutputObject().write_TypeCode(new TypeCodeImpl((ORB) getOutputObject().orb(), TCKind._tk_float)); + + expectByteArray(0, 0, 0, 6); + } + + @Test + public void canWriteStringTypeCode() { + getOutputObject().write_TypeCode(new TypeCodeImpl((ORB) getOutputObject().orb(), TCKind._tk_string, 256)); + + expectByteArray(0, 0, 0, 18, 0, 0, 1, 0); + } + + @Test + public void canWriteSerializableTypeCode() { + String KNOWN_TYPE_CODE = "0000001D000000CE0000000000000067524D493A636F6D2E73756E2E636F7262612E65652E696D706C" + + "2E656E636F64696E672E4344524F7574707574546573745C553030323453657269616C697A65644461" + + "74613A323837394346383133394444433741463A393031343243313746444330444632410000000000" + + "3C636F6D2E73756E2E636F7262612E65652E696D706C2E656E636F64696E672E4344524F7574707574" + + "546573742453657269616C697A65644461746100000000000000000000000001000000066142797465" + + "0000000000000A0000"; + TypeCode typeCode = AnyImpl.createTypeCodeForClass(SerializedData.class, getOrb()); + getOutputObject().write_TypeCode(typeCode); + + expectByteArray(hexStringToByteArray(KNOWN_TYPE_CODE)); + } + + static class SerializedData implements Serializable { + byte aByte; + } + + private byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len/2]; + for (int i = 0; i < len; i+=2) { + data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i+1), 16)); + } + return data; + } + + @Test + public void canWriteObjRefTypeCode() { + getOutputObject().write_TypeCode(new TypeCodeImpl((ORB) getOutputObject().orb(), TCKind._tk_objref, "aa", "bb")); + + expectByteArray(0,0,0,14, 0,0,0,19, 0,0,0,0, 0,0,0,3, 'a','a',0,0, 0,0,0,3, 'b','b',0 ); + } + + @Test + public void WhenOutputStreamClosed_releaseBuffer() throws IOException { + getOutputObject().write_ulong(123); + getOutputObject().close(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void WhenOutputStreamClosedFirst_sharedBuffersAreOnlyReleasedOnce() throws IOException { + getOutputObject().write_ulong(123); + CDRInputObject inputObject = getOutputObject().createInputObject(getOrb()); + getOutputObject().getMessageMediator().setInputObject(inputObject); + inputObject.setMessageMediator(getOutputObject().getMessageMediator()); + assertEquals(123, inputObject.read_ulong()); + getOutputObject().close(); + inputObject.close(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void WhenInputStreamClosedFirst_sharedBuffersAreOnlyReleasedOnce() throws IOException { + getOutputObject().write_ulong(123); + CDRInputObject inputObject = getOutputObject().createInputObject(getOrb()); + getOutputObject().getMessageMediator().setInputObject(inputObject); + inputObject.setMessageMediator(getOutputObject().getMessageMediator()); + getOutputObject().getMessageMediator().setOutputObject(getOutputObject()); + assertEquals(123, inputObject.read_ulong()); + inputObject.close(); + getOutputObject().close(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void WhenEncapsOutputStreamClosedFirst_sharedBuffersAreOnlyReleasedOnce() throws IOException { + EncapsOutputStream os = new EncapsOutputStream( getOrb() ); + os.write_ulong(123); + InputStream is = (InputStream)(os.create_input_stream() ); + assertEquals(123, is.read_ulong()); + os.close(); + is.close(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void WhenEncapsInputStreamClosedFirst_sharedBuffersAreOnlyReleasedOnce() throws IOException { + EncapsOutputStream os = new EncapsOutputStream( getOrb() ); + os.write_ulong(123); + InputStream is = (InputStream)(os.create_input_stream() ); + assertEquals(123, is.read_ulong()); + is.close(); + os.close(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void WhenTypeCodeOutputStreamClosedFirst_sharedBuffersAreOnlyReleasedOnce() throws IOException { + TypeCodeOutputStream os = new TypeCodeOutputStream( getOrb() ); + os.write_ulong(123); + InputStream is = (InputStream)(os.create_input_stream() ); + assertEquals(123, is.read_ulong()); + os.close(); + is.close(); + + assertEquals(1, getNumBuffersReleased()); + } + + @Test + public void WhenTypeCodeInputStreamClosedFirst_sharedBuffersAreOnlyReleasedOnce() throws IOException { + TypeCodeOutputStream os = new TypeCodeOutputStream( getOrb() ); + os.write_ulong(123); + InputStream is = (InputStream)(os.create_input_stream() ); + assertEquals(123, is.read_ulong()); + is.close(); + os.close(); + + assertEquals(1, getNumBuffersReleased()); + } + + /* + + @Test(expected = MARSHAL.class) + public void whenUsingV1_0_throwExceptionOnUnexpectedEndOfData() { + useV1_0(); + setMessageBody(0, 0); + getInputObject().read_long(); + } + + @Test + public void whenUsingV1_2_headerPaddingForces8ByteAlignmentOnce() { + useV1_2(); + setMessageBody(pad(), pad(), pad(), pad(), + 0, 0, 1, 0, + FF, FF, FF, FF); + + getInputObject().setHeaderPadding(true); + assertEquals(256, getInputObject().read_long()); + assertEquals(-1, getInputObject().read_long()); + } + + @Test + public void whenMarkIsSetInV1_0_restoreAllowsReread() { + useV1_0(); + setMessageBody(0, 0, 1, 23, 'x'); + getInputObject().mark(0); + assertEquals(0, getInputObject().read_short()); + getInputObject().reset(); + assertEquals(279, getInputObject().read_long()); + } + + @Test + public void whenMarkIsSetInV1_2_restoreAllowsReread() { + useV1_2(); + setMessageBody(0, 0, 1, 23, 'x'); + getInputObject().mark(0); + assertEquals(0, getInputObject().read_short()); + getInputObject().reset(); + assertEquals(279, getInputObject().read_long()); + } + + @Test + public void whenUsingV1_2_continueReadingOnToFragment() { + useV1_2(); + setMessageBody(0, 0, 1, 23); + addFragment(0, 7); + getInputObject().read_long(); + assertEquals(7, getInputObject().read_short()); + } + + @Test + public void whenUsingV1_2_skipPaddingBeforeReadingNextFragment() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + addFragment(0, 0, 0, 7); + getInputObject().read_short(); + assertEquals(7, getInputObject().read_long()); + } + + @Test + public void whenUsingV1_1_skipOptionalPaddingBeforeReadingNextFragment() { + useV1_1(); + setMessageBody(0, 23, pad(), pad()); + addFragment(0, 0, 0, 7); + getInputObject().read_short(); + assertEquals(7, getInputObject().read_long()); + } + + @Test + public void whenUsingV1_1_alignToStartOfNextFragment() { + useV1_1(); + setMessageBody(0, 23); + addFragment(0, 0, 0, 7); + getInputObject().read_short(); + assertEquals(7, getInputObject().read_long()); + } + + @Test(expected = RequestCanceledException.class) + public void whenUsingV1_2_throwExceptionIfCanceled() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + getInputObject().read_short(); + getInputObject().cancelProcessing(0); + getInputObject().read_long(); + } + + @Test(expected = MARSHAL.class) + public void whenUsingV1_2_throwExceptionOnReadPastEnd() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test(expected = COMM_FAILURE.class) + public void whenUsingV1_2_throwExceptionOnTimeout() { + useV1_2(); + expectMoreFragments(); + setMessageBody(0, 23, pad(), pad()); + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test(expected = RequestCanceledException.class) + public void whenUsingV1_2_throwExceptionWhenCanceledDuringWait() { + useV1_2(); + setMessageBody(0, 23, pad(), pad()); + expectMoreFragments(); + + whileWaitingForFragmentsDo(new AsynchronousAction() { + public void exec() { + addFragment(0, 0, 0, 7); + getInputObject().cancelProcessing(0); + } + }); + getInputObject().read_short(); + getInputObject().read_long(); + } + + @Test + public void whenValueIsZero_returnNull() { + setMessageBody(0, 0, 0, 0); + assertNull(getInputObject().read_value()); + } + + @Test + public void whenCloneEncapsInputStream_readFromClone() { + setMessageBody(); + EncapsInputStream inputStream1 = createEncapsulatedInputStream(0, 0, 1, 5); + EncapsInputStream inputStream2 = new EncapsInputStream(inputStream1); + assertEquals(261, inputStream2.read_long()); + } + + @Test + public void canWriteLittleEndianUTF16CharIn_1_0WithLegacyORB() throws IOException { + useV1_0(); + useLittleEndian(); + setOrbVersion(ORBVersionFactory.getOLD()); + setWCharEncoding(UTF_16); + + getOutputObject().write_wchar('\u5634'); + expectByteArray(0x34, 0x56); + } + + @Test + public void can_read_little_endian_integers() { + setMessageBody(0x04, pad(), + 0xf2, FF,// short + 0x03, 0x00,// ushort + pad(), pad(),// for long + 0x83, 2, 1, 0,// long + 0x71, 0xfd, FF, FF,// ulong + pad(), pad(), pad(), pad(),// for long_long + 7, 1, 0x80, 0, 0, 1, 0, 0);// long long + useLittleEndian(); + + assertEquals("Octet value", 4, getInputObject().read_octet()); + assertEquals("Signed short value", -14, getInputObject().read_short()); + assertEquals("Standard unsigned short value", 3, getInputObject().read_ushort()); + assertEquals("Unsigned long value", 66179, getInputObject().read_ulong()); + assertEquals("Long value", -655, getInputObject().read_long()); + assertEquals("Long long value", 1099520016647L, getInputObject().read_longlong()); + } + + @Test + public void canReadStringFromOldOrbAcrossFragment() { + useV1_1(); + setOrbVersion(ORBVersionFactory.getOLD()); + setMessageBody(0, 0, 0, 9, 'a', 'b', 'c', 'd'); + addFragment('e', 'f', 'g', 'h', 0); + assertEquals("abcdefgh", getInputObject().read_string()); + } + + @Test + public void can_read_octet_array_acrossFragments() throws Exception { + useV1_2(); + final int[] data = {0, 1, 2, 3}; + final byte[] expected = {0, 1, 2, 3, -1, -1}; + setMessageBody(data); + addFragment(-1, -1); + readAndVerifyOctetArray(expected); + } + + /**/ +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDROutputValueTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDROutputValueTest.java new file mode 100644 index 000000000..bc4726ae6 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/CDROutputValueTest.java @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.util.RepositoryId; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import org.junit.Test; +import org.omg.CORBA.VM_TRUNCATABLE; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.ArrayList; + +import static com.meterware.simplestub.Stub.createStrictStub; + +public class CDROutputValueTest extends ValueTestBase { + + static final String ARRAY_LIST_REPID = "RMI:java.util.ArrayList:F655154F32815380:7881D21D99C7619D"; + + Value1Helper value1Helper = createStrictStub(Value1Helper.class); + + @Test + public void canWriteStringValue() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(RepositoryId.kWStringValueRepID); + writeStringValue_1_2("This, too!"); + + getOutputObject().write_value("This, too!"); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteSerializedValue() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_2('x'); + writeInt(3); + + Value1 value1 = new Value1('x', 3); + getOutputObject().write_value(value1); + + setMessageBody(getGeneratedBody()); + expectByteArray(getGeneratedBody()); + } + + /** + * ArrayLists always use chunking because they have custom marshalling. The Value1 type does not, normally. + * When a Value1 instance is contained in an ArrayList, it must use chunking to comply with the CORBA spec. + * @throws IOException + */ + @Test + public void valuesNestedUnderChunkedValuesAreChunked() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(ARRAY_LIST_REPID); + + startChunk(); + writeByte(1); // array header + writeByte(1); // true: overriding write object + writeInt(1); + writeInt(1); // size of array list + writeByte(0); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + ArrayList value = new ArrayList(1); + value.add(new Value1('x', 3)); + getOutputObject().write_value(value); + + setMessageBody(getGeneratedBody()); + expectByteArray(getGeneratedBody()); + } + + /** + * A ComplexValue does not need chunking; however, it contains an ArrayList which does. The next field is a Value1, + * which should not use chunking. + * @throws IOException + */ + @Test + public void valuesFollowingChunkedValuesNeedNotBeChunked() throws IOException { + setFragmentSize(500); + writeValueTag(ONE_REPID_ID); + writeRepId(ComplexValue.REPID); + writeInt(3); // anInt + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(ARRAY_LIST_REPID); + + startChunk(); + writeByte(1); // array header + writeByte(1); + writeInt(1); + writeInt(1); // ArrayList size + writeByte(0); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + int valueRepIdLocation = getCurrentLocation(); + writeRepId(Value1.REPID); + + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + writeValueTag(ONE_REPID_ID); + writeIndirectionTo(valueRepIdLocation); + + writeWchar_1_2('X'); + writeInt(4); + + ComplexValue value = new ComplexValue('x', 3); + getOutputObject().write_value(value); + + setMessageBody(getGeneratedBody()); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteSerializedValueInChunk() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + value1Helper.setModifier(VM_TRUNCATABLE.value); + useRepId(); + getOutputObject().write_value(new Value1('x', 3), value1Helper); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteSerializedEnum() throws IOException { + writeValueTag(ONE_REPID_ID); + writeRepId(Enum1.REPID); + + writeString(Enum1.strange.toString()); + + getOutputObject().write_value(Enum1.strange); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteIDLEntity() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(IDLValue.REPID); + + byte aByte = 0x45; + + startChunk(); + writeByte(aByte); + endChunk(); + writeEndTag(-1); + + IDLValue value = new IDLValue(aByte); + getOutputObject().write_value(value); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteSerializedValueWithIndirection() throws IOException { + int location = getCurrentLocation(); + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_2('x'); + writeInt(3); + writeIndirectionTo(location); + + Value1 value = new Value1('x', 3); + getOutputObject().write_value(value); + getOutputObject().write_value(value); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteSerializedValueWithIndirection_in1_1() throws IOException { + useV1_1(); + int location = getCurrentLocation(); + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_1('x'); + writeInt(3); + writeIndirectionTo(location); + + Value1 value = new Value1('x', 3); + getOutputObject().write_value(value); + getOutputObject().write_value(value); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteSerializedValueWithIndirection_in1_0() throws IOException { + useV1_0(); + setOrbVersion(ORBVersionFactory.getOLD()); + int location = getCurrentLocation(); + writeValueTag(ONE_REPID_ID); + writeRepId(Value1.REPID); + + writeWchar_1_1('x'); + writeInt(3); + writeIndirectionTo(location); + + Value1 value = new Value1('x', 3); + getOutputObject().write_value(value); + getOutputObject().write_value(value); + expectByteArray(getGeneratedBody()); + } + + @Test + public void canWriteCustomValueInChunk_withCompactedEndTags() throws IOException { + getOutputObject().start_value("ID1"); + getOutputObject().write_long(73); + getOutputObject().start_value("ID2"); + getOutputObject().write_long(37); + getOutputObject().end_value(); + getOutputObject().end_value(); + + expectByteArrays(new byte[] {0x7F,FF,FF,0x0A, 0,0,0,4, 'I','D','1',0, 0,0,0,4, 0,0,0,73, + 0x7F,FF,FF,0x0A, 0,0,0,4, 'I','D','2',0, 0,0,0,4, 0,0,0,37, FF,FF,FF,FF }); + } + + @Test + public void whenBufferFull_sendFragment() { + setFragmentSize(Message.GIOPMessageHeaderLength + 8); + getOutputObject().write_long(1); + getOutputObject().write_short((short) 2); + getOutputObject().write_long(3); + + expectByteArrays(new byte[] {0,0,0,1, 0,2, 0,0}, new byte[] {0,0,0,3}); + } + + @Test + public void whenBufferFullInV1_1_sendFragment() { + useV1_1(); + setFragmentSize(Message.GIOPMessageHeaderLength + 8); + getOutputObject().write_long(1); + getOutputObject().write_short((short) 2); + getOutputObject().write_long(3); + + expectByteArrays(new byte[] {0,0,0,1, 0,2}, new byte[] {0,0,0,3}); + } + + @Test + public void whenBufferFullInV1_0_expandIt() { + useV1_0(); + setBufferSize(Message.GIOPMessageHeaderLength + 8); + getOutputObject().write_long(1); + getOutputObject().write_short((short) 2); + getOutputObject().write_long(3); + + expectByteArray(0,0,0,1, 0,2, 0,0, 0,0,0,3); + } + + @Test + public void whenBufferFullWhileWritingPrimitive_generateContinuationAfterFirstPrimitiveInNewFragment() { + setFragmentSize(Message.GIOPMessageHeaderLength + 16); + getOutputObject().start_block(); + getOutputObject().write_long(1); + getOutputObject().write_long(2); + getOutputObject().write_long(3); + getOutputObject().write_long(5); + getOutputObject().write_long(6); + getOutputObject().write_long(9); + getOutputObject().end_block(); + + expectByteArrays(new byte[] {0,0,0,16, 0,0,0,1, 0,0,0,2, 0,0,0,3}, new byte[] {0,0,0,5, 0,0,0,8, 0,0,0,6, 0,0,0,9}); + } + + @Test + public void whenBufferFullWhileMidChunkAndWritingArray_generateContinuationAfterArray() { + setFragmentSize(Message.GIOPMessageHeaderLength + 16); + getOutputObject().start_block(); + getOutputObject().write_long_array(new int[] {1, 2, 3, 5, 6}, 0, 5); + getOutputObject().write_long(9); + getOutputObject().end_block(); + + expectByteArrays(new byte[] {0,0,0,20, 0,0,0,1, 0,0,0,2, 0,0,0,3}, new byte[] {0,0,0,5, 0,0,0,6, 0,0,0,4, 0,0,0,9}); + } + + @Test + public void whenObjectImplementsWriteReplace_outputStreamContainsReplacementValue() throws Exception { + writeValueTag(ONE_REPID_ID); + writeRepId(Gender.REPID); + + writeInt(0); // the serialized form of the MALE constant, produced by writeReplace + + getOutputObject().write_value(Gender.MALE); + + setMessageBody(getGeneratedBody()); + expectByteArray(getGeneratedBody()); + } + + @Test + public void whenInaccessibleObjectImplementsWriteReplace_outputStreamContainsReplacementValue() throws Exception { + String InetAddressRepId = "RMI:java.net.InetAddress:C156A93A2ABC4FAF:2D9B57AF9FE3EBDB"; + + InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); + writeValueTag(ONE_REPID_ID | USE_CHUNKING); // custom marshalling requires a chunk + writeRepId(InetAddressRepId); + + startChunk(); + writeInt(0x01010000); + writeInt(0x7F000001); // 127.0.0.1 + writeInt(0x00000002); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); // custom marshalling requires a chunk + writeRepId("IDL:omg.org/CORBA/WStringValue:1.0"); + startChunk(); + writeStringValue_1_2("localhost"); + endChunk(); + writeEndTag(-1); + + getOutputObject().write_value(loopbackAddress); + + setMessageBody(getGeneratedBody()); + expectByteArray(getGeneratedBody()); + } + + @Test + public void whenExternalizableObjectWritten_invokeWriteExternalMethod() throws Exception { + Profession profession = Profession.DOCTOR; + getOutputObject().write_value(profession); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); // custom marshalling requires a chunk + writeRepId(Profession.REPID); + + startChunk(); + writeByte(1); // serial format version + writeInt(4); + endChunk(); + writeEndTag(-1); + + setMessageBody(getGeneratedBody()); + expectByteArray(getGeneratedBody()); + } +/* + +// write codebase + + @Test + public void canReadSerializedValueWithContinuationChunk() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + + startChunk(); + writeWchar_1_2('x'); + endChunk(); + + startChunk(); + writeInt(3); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals(3, value1.anInt); + } + + @Test + public void canReadSerializedValueWithNestedValue() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value2.REPID); + + startChunk(); + writeLong(750); + endChunk(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + startChunk(); + writeWchar_1_2('x'); + writeInt(3); + endChunk(); + writeEndTag(-1); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(); + assertTrue(object instanceof Value2); + Value2 value2 = (Value2) object; + assertEquals(750,value2.aLong); + assertEquals('x', value2.aValue.aChar); + assertEquals(3, value2.aValue.anInt); + } + + @Test + public void canReadSerializedValueUsingDefaultFactory() throws IOException { + writeValueTag(ONE_REPID_ID | USE_CODEBASE); + writeCodebase("http://localhost/myClasses"); + writeRepId(Value1.REPID); + + writeWchar_1_2('x'); + + setMessageBody( getGeneratedBody() ); + + Object object = getInputObject().read_value(Value1.REPID); + assertTrue(object instanceof Value1); + Value1 value1 = (Value1) object; + assertEquals('x', value1.aChar); + assertEquals('x', value1.anInt); + } + + @Test + public void canReadNullValueUsingDefaultFactory() throws IOException { + writeNull(); + setMessageBody( getGeneratedBody() ); + + assertNull(getInputObject().read_value(Value1.REPID)); + } + + @Test(expected = IndirectionException.class) + public void whenIndirectionHasNoAntecedent_throwExceptionWhenUsingRepId() throws IOException { + writeIndirectionTo(0); + setMessageBody( getGeneratedBody() ); + getInputObject().read_value(Value1.REPID); + } + + @Test + public void canReadSerializedValueUsingDefaultFactoryAndIndirection() throws IOException { + int location = getCurrentLocation(); + + writeValueTag(ONE_REPID_ID | USE_CHUNKING); + writeRepId(Value1.REPID); + startChunk(); + writeWchar_1_2('x'); + endChunk(); + writeEndTag(-1); + + writeIndirectionTo(location); + + setMessageBody( getGeneratedBody() ); + + Object object1 = getInputObject().read_value(Value1.REPID); + Object object2 = getInputObject().read_value(Value1.REPID); + assertSame(object1, object2); + } + +*/ +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/ComplexValue.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/ComplexValue.java new file mode 100644 index 000000000..e97373f0a --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/ComplexValue.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class ComplexValue implements Serializable { + static final String REPID = "RMI:com.sun.corba.ee.impl.encoding.ComplexValue:526A075F52D4A68C:31E83A657AE82D48"; + int anInt; + List arrayList = new ArrayList(1); + Value1 value; + + ComplexValue(char aChar, int anInt) { + this.anInt = anInt; + arrayList.add(new Value1(aChar, anInt)); + char nextChar = Character.toUpperCase(aChar); + value = new Value1(nextChar, anInt+1); + } + + ComplexValue() { + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/EncodingTestBase.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/EncodingTestBase.java new file mode 100644 index 000000000..03c9d0eac --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/EncodingTestBase.java @@ -0,0 +1,608 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.meterware.simplestub.Stub; +import com.sun.corba.ee.impl.orb.ORBImpl; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.FragmentMessage; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.transport.MessageTraceManagerImpl; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ORBVersionFactory; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.transport.ByteBufferPool; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.MessageTraceManager; +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.org.omg.SendingContext.CodeBase; +import org.glassfish.corba.testutils.HexBuffer; +import org.junit.Before; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ValueFactory; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.List; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static com.sun.corba.ee.impl.encoding.EncodingTestBase.Endian.big_endian; +import static com.sun.corba.ee.impl.encoding.EncodingTestBase.Endian.little_endian; +import static com.sun.corba.ee.impl.encoding.EncodingTestBase.Fragments.more_fragments; +import static com.sun.corba.ee.impl.encoding.EncodingTestBase.Fragments.no_more_fragments; +import static com.sun.corba.ee.spi.ior.iiop.GIOPVersion.*; +import static org.junit.Assert.*; + +public class EncodingTestBase { + protected static final byte REQUEST = 0; + protected static final int ISO_8859_1 = OSFCodeSetRegistry.ISO_8859_1.getNumber(); + protected static final int UTF_8 = OSFCodeSetRegistry.UTF_8.getNumber(); + protected static final int UTF_16 = OSFCodeSetRegistry.UTF_16.getNumber(); + protected static final byte FE = -2; + protected static final byte FF = -1; + protected static final int PAD = 0; // use for output tests only, to make comparison possible + + private ORBDataFake orbData = createStrictStub(ORBDataFake.class); + private ORBFake orb = createStrictStub(ORBFake.class); + private ConnectionFake connection = createStrictStub(ConnectionFake.class); + private MessageFake message = createStrictStub(MessageFake.class); + private MessageFake fragment = createStrictStub(MessageFake.class); + private ByteBufferPoolFake pool = createStrictStub(ByteBufferPoolFake.class); + private MessageMediatorFake mediator = createStrictStub(MessageMediatorFake.class); + private TransportManagerFake transportManager = createStrictStub(TransportManagerFake.class); + + private CDRInputObject inputObject; + private CDROutputObject outputObject; + private byte formatVersion = ORBConstants.STREAM_FORMAT_VERSION_1; + + private List fragments = new ArrayList(); + + static byte flags(Endian endian, Fragments fragments) { + byte result = 0; + if (endian == little_endian) result |= 0x01; + if (fragments == more_fragments) result |= 0x02; + return result; + } + + /** Returns a random value to ensure that the test never reads it. **/ + static byte pad() { + return (byte) ((int) (Math.random() * 256)); + } + + @Before + public void setUp() throws Exception { + orb.setORBData(orbData); + orb.setByteBufferPool(pool); + orb.transportManager = transportManager; + mediator.setConnection(connection); + connection.fragments = fragments; + } + + protected final ORB getOrb() { + return orb; + } + + protected final void useRepId() { + orbData.useRepId = true; + } + + protected final void useEnumDesc() { + orbData.useEnumDesc = true; + } + + protected final void setBufferSize(int size) { + orbData.giopBufferSize = size; + } + + protected final void setFragmentSize(int size) { + orbData.giopFragmentSize = size; + } + + protected final void useStreamFormatVersion1() { + formatVersion = ORBConstants.STREAM_FORMAT_VERSION_1; + } + + protected final void useStreamFormatVersion2() { + formatVersion = ORBConstants.STREAM_FORMAT_VERSION_2; + } + + protected final void setCharEncoding(int encoding) { + connection.setCharEncoding(encoding); + } + + protected final void setWCharEncoding(int encoding) { + connection.setWCharEncoding(encoding); + } + + protected final EncapsInputStream createEncapsulatedInputStream(int... contents) { + byte[] bytes = new byte[contents.length]; + for (int i = 0; i < contents.length; i++) + bytes[i] = (byte) contents[i]; + return new EncapsInputStream(orb, bytes, bytes.length, getByteOrder(), message.giopVersion); + } + + private ByteOrder getByteOrder() { + return isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; + } + + protected final CDRInputObject getInputObject() { + if (inputObject == null) + inputObject = createInputObject(); + return inputObject; + } + + private CDRInputObject createInputObject() { + CDRInputObject inputObject = new CDRInputObject(orb, connection, getByteBuffer(), message); + inputObject.performORBVersionSpecificInit(); + return inputObject; + } + + protected final void useV1_0() { + message.giopVersion = V1_0; + } + + protected final void useV1_1() { + message.giopVersion = V1_1; + } + + protected final void useV1_2() { + message.giopVersion = V1_2; + } + + protected final void useLittleEndian() { + message.endian = little_endian; + } + + private boolean isLittleEndian() { + return message.endian == little_endian; + } + + protected final void setOrbVersion(ORBVersion version) { + orb.setORBVersion(version); + } + + protected final void addFragment(int... values) { + fragment.body = new byte[values.length]; + for (int i = 0; i < values.length; i++) + fragment.body[i] = (byte) (values[i]); + getInputObject().addFragment(fragment, ByteBuffer.wrap(fragment.getMessageData())); + } + + /** + * Sets the message 'more fragments coming' flag. + */ + protected final void expectMoreFragments() { + message.fragments = more_fragments; + } + + protected final void whileWaitingForFragmentsDo(AsynchronousAction asynchronousAction) { + orbData.asynchronousAction = asynchronousAction; + } + + private ByteBuffer getByteBuffer() { + return ByteBuffer.wrap(message.getMessageData()); + } + + protected final void setMessageBody(int... values) { + message.body = new byte[values.length]; + for (int i = 0; i < values.length; i++) + message.body[i] = (byte) values[i]; + } + + protected final void setMessageBody(byte[] values) { + message.body = values.clone(); + } + + protected final int getNumBuffersReleased() { + return pool.getNumBuffersReleased(); + } + + // Note: the tests assume that the buffer contents start after the header. For the output logic, the object is created + // positioned after the header, so the comparison must skip that. + + protected final CDROutputObject getOutputObject() { + if (outputObject == null) + outputObject = createOutputObject(); + return outputObject; + } + + private CDROutputObject createOutputObject() { + CDROutputObject outputObject = new CDROutputObject(orb, mediator, message.giopVersion, connection, message, formatVersion); + outputObject.setIndex(Message.GIOPMessageHeaderLength); + return outputObject; + } + + protected final void expectByteArray(byte... expected) { + getOutputObject().finishSendingMessage(); + assertEquals(1, fragments.size()); + expectFragment(0, expected); + } + + protected final void dumpActual() { + getOutputObject().finishSendingMessage(); + HexBuffer.dumpBuffers(fragments); + } + + private void expectFragment(int index, byte[] expected) { + byte[] actual = subBuffer(fragments.get(index), Message.GIOPMessageHeaderLength); + try { + assertArrayEquals(expected, actual); + } catch (AssertionError e) { + System.out.println("buffer" + index + " expected:"); + HexBuffer.dumpBuffer(expected); + System.out.println("actual:"); + HexBuffer.dumpBuffer(actual); + throw e; + } + } + + protected final void expectByteArrays(byte[]... expected) { + getOutputObject().getBufferManager().sendMessage(); + assertEquals(expected.length, fragments.size()); + for (int i = 0; i < expected.length; i++) + expectFragment(i, expected[i]); + } + + private byte[] subBuffer(byte[] input, int start) { + byte[] result = new byte[input.length-start]; + System.arraycopy(input, start, result, 0, result.length); + return result; + } + + + protected final void expectByteArray(int... expected) { + byte[] bytes = new byte[expected.length]; + for (int i = 0; i < expected.length; i++) + bytes[i] = (byte) (expected[i]); + expectByteArray(bytes); + } + + enum Endian {big_endian, little_endian} + + enum Fragments {no_more_fragments, more_fragments} + + interface AsynchronousAction { + void exec(); + } + + + //--------------------------------- fake implementation of a TransportManager -------------------------------------- + + static abstract class TransportManagerFake implements TransportManager { + @Override + public MessageTraceManager getMessageTraceManager() { + return new MessageTraceManagerImpl(); + } + } + + //-------------------------------------- fake implementation of an ORBData ----------------------------------------- + + static abstract class ORBDataFake implements ORBData { + private AsynchronousAction asynchronousAction; + private int giopBufferSize = 250; + private boolean useRepId; + private boolean useEnumDesc; + private int giopFragmentSize = 250; + + @Override + public int fragmentReadTimeout() { + if (asynchronousAction != null) asynchronousAction.exec(); + return 1; + } + + @Override + public int getGIOPBuffMgrStrategy(GIOPVersion gv) { + return gv.equals(GIOPVersion.V1_0) ? BufferManagerFactory.GROW : BufferManagerFactory.STREAM; + } + + @Override + public int getGIOPBufferSize() { + return giopBufferSize; + } + + @Override + public boolean useByteOrderMarkers() { + return true; + } + + @Override + public boolean useRepId() { + return useRepId; + } + + @Override + public boolean useEnumDesc() { + return useEnumDesc; + } + + @Override + public int getGIOPFragmentSize() { + return giopFragmentSize; + } + } + + //----------------------------------- fake implementation of a ByteBufferPool -------------------------------------- + + static abstract class ByteBufferPoolFake implements ByteBufferPool { + private List buffers = new ArrayList(); + + protected int getNumBuffersReleased() { + return buffers.size(); + } + + @Override + public void releaseByteBuffer(ByteBuffer buffer) { + buffers.add(buffer); + } + + @Override + public ByteBuffer getByteBuffer(int theSize) { + return ByteBuffer.allocate(theSize); + } + } + + //---------------------------------------- fake implementation of the ORB ------------------------------------------ + + static abstract class ORBFake extends ORBImpl { + private ORBDataFake orbData; + private ORBVersion version = ORBVersionFactory.getFOREIGN(); + private ByteBufferPool pool; + private TransportManager transportManager = null; + + protected ORBFake() { + initializePrimitiveTypeCodeConstants(); + } + + void setORBData(ORBDataFake orbData) { + this.orbData = orbData; + } + + public void setORBVersion(ORBVersion version) { + this.version = version; + } + + @Override + public ORBVersion getORBVersion() { + return version; + } + + @Override + public ORBData getORBData() { + return orbData; + } + + @Override + public ByteBufferPool getByteBufferPool() { + return pool; + } + + @Override + public ValueFactory lookup_value_factory(String repID) { + return null; + } + + public void setByteBufferPool(ByteBufferPool pool) { + this.pool = pool; + } + + @Override + public TransportManager getTransportManager() { + return transportManager; + } + } + + //-------------------------------------- fake implementation of a Codebase ----------------------------------------- + + static abstract class CodeBaseFake implements CodeBase { + @Override + public String implementation(String s) { + return null; + } + } + + //------------------------------------- fake implementation of a Connection ---------------------------------------- + + static abstract class ConnectionFake implements Connection { + int char_encoding = ISO_8859_1; + int wchar_encoding = UTF_16; + boolean locked; + private CodeSetComponentInfo.CodeSetContext codeSets; + List fragments; + CodeBase codeBase = createStrictStub(CodeBaseFake.class); + + void setCharEncoding(int char_encoding) { + this.char_encoding = char_encoding; + codeSets = new CodeSetComponentInfo.CodeSetContext(char_encoding, wchar_encoding); + } + + void setWCharEncoding(int wchar_encoding) { + this.wchar_encoding = wchar_encoding; + codeSets = new CodeSetComponentInfo.CodeSetContext(char_encoding, wchar_encoding); + } + + @Override + public CodeSetComponentInfo.CodeSetContext getCodeSetContext() { + if (codeSets == null) + codeSets = new CodeSetComponentInfo.CodeSetContext(char_encoding, wchar_encoding); + return codeSets; + } + + @Override + public CodeBase getCodeBase() { + return codeBase; + } + + @Override + public boolean hasSocketChannel() { + return true; + } + + @Override + public void writeLock() { + locked = true; + } + + @Override + public void writeUnlock() { + locked = false; + } + + @Override + public void sendWithoutLock(CDROutputObject outputObject) { + try { + if (!locked) fail("sendWithoutLock called while connection is not locked"); + outputObject.writeTo(this); + } catch (IOException e) { + fail("Connection reported: " + e); + } + } + + @Override + public void write(ByteBuffer byteBuffer) throws IOException { + byte[] buf = new byte[byteBuffer.remaining()]; + byteBuffer.get(buf); + fragments.add(buf); + } + } + + //---------------------------------- fake implementation of a Message Mediator ------------------------------------- + + static abstract class MessageMediatorFake implements MessageMediator { + + private Connection connection; + private CDRInputObject inputObject; + private CDROutputObject outputObject; + + public void setConnection(Connection connection) { + this.connection = connection; + } + + @Override + public Connection getConnection() { + return connection; + } + + @Override + public void setInputObject(CDRInputObject inputObject) { + this.inputObject = inputObject; + } + + @Override + public CDRInputObject getInputObject() { + return inputObject; + } + + @Override + public void setOutputObject(CDROutputObject outputObject) { + this.outputObject = outputObject; + } + + @Override + public CDROutputObject getOutputObject() { + return outputObject; + } + } + + //--------------------------------------- fake implementation of a Message ----------------------------------------- + + static abstract class MessageFake implements FragmentMessage { + Endian endian = big_endian; + Fragments fragments = no_more_fragments; + private GIOPVersion giopVersion = V1_2; + private byte messageType = REQUEST; + byte[] body; + byte[] data; + int headerIndex = 0; + int sizeInHeader = -1; + private boolean startedNewMessage; + + byte[] getMessageData() { + if (data != null) return data; + + if (body == null) throw new RuntimeException("No message body defined"); + data = new byte[body.length + getHeaderLength()]; + System.arraycopy(body, 0, data, getHeaderLength(), body.length); + copyToHeader((byte) 'G', (byte) 'I', (byte) 'O', (byte) 'P'); + copyToHeader(giopVersion.getMajor(), giopVersion.getMinor()); + copyToHeader(flags(endian, fragments), messageType); + copyToHeader(body.length); + return data; + } + + private void copyToHeader(int value) { + data[headerIndex++] = (byte) (0xFF & value >> 24); + data[headerIndex++] = (byte) (0xFF & value >> 16); + data[headerIndex++] = (byte) (0xFF & value >> 8); + data[headerIndex++] = (byte) (0xFF & value); + } + + private void copyToHeader(byte... bytes) { + for (byte aByte : bytes) { + data[headerIndex++] = aByte; + } + } + + public int getHeaderLength() { + return Message.GIOPMessageHeaderLength; + } + + @Override + public int getSize() { + return sizeInHeader >=0 ? sizeInHeader : getMessageData().length; + } + + @Override + public boolean isLittleEndian() { + return endian == little_endian; + } + + @Override + public GIOPVersion getGIOPVersion() { + return giopVersion; + } + + @Override + public byte getEncodingVersion() { + return 0; // not actually used + } + + @Override + public boolean moreFragmentsToFollow() { + return fragments == more_fragments; + } + + @Override + public void setSize(ByteBuffer byteBuffer, int size) { + sizeInHeader = size; + } + + @Override + public FragmentMessage createFragmentMessage() { + return Stub.createStrictStub(MessageFake.class); + } + + public int getSizeInHeader() { + return sizeInHeader; + } + + @Override + public void write(OutputStream ostream) { + startedNewMessage = true; + for (int i = 0; i < GIOPMessageHeaderLength; i++) + ostream.write_octet((byte) 0); + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Enum1.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Enum1.java new file mode 100644 index 000000000..d10fe4c21 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Enum1.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +enum Enum1 { + + up, down, strange, charm, truth, beauty; + + static final String REPID = "RMI:com.sun.corba.ee.impl.encoding.Enum1:64D47C1D01980B5E:0000000000000000"; + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Gender.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Gender.java new file mode 100644 index 000000000..145ad46d0 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Gender.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +/** + * A class which uses writeReplace and readResolve to place a custom version into the object stream. + */ +class Gender implements Serializable { + private static final long serialVersionUID = 0x34789521D52D7FF2L; + + final static String REPID = "RMI:com.sun.corba.ee.impl.encoding.Gender\\U0024SerializedForm:F85634868214EB9C:34789521D52D7FF2"; + final static Gender MALE = new Gender("Male"); + final static Gender FEMALE = new Gender("Female"); + + private String name; + + private Gender(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Gender{" + + "name='" + name + '\'' + + '}'; + } + + private Object writeReplace() throws ObjectStreamException { + if (this.equals(MALE)) { + return SerializedForm.MALE_FORM; + } else { + return SerializedForm.FEMALE_FORM; + } + } + + private static class SerializedForm implements Serializable { + + final static SerializedForm MALE_FORM = new SerializedForm(0); + final static SerializedForm FEMALE_FORM = new SerializedForm(1); + + private int value; + + SerializedForm(int value) { + this.value = value; + } + + private Object readResolve() throws ObjectStreamException { + if (value == MALE_FORM.value) { + return Gender.MALE; + } else { + return Gender.FEMALE; + } + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/IDLValue.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/IDLValue.java new file mode 100644 index 000000000..b2e89d0d1 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/IDLValue.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import org.omg.CORBA.portable.IDLEntity; + +public class IDLValue implements IDLEntity { + static final String REPID = "RMI:com.sun.corba.ee.impl.encoding.IDLValue:BB212B05444A560F:000000000ABCDEF0"; + static final long serialVersionUID = 0xABCDEF0; + + byte aByte; + int anInt; + + public IDLValue() { + } + + public IDLValue(byte aByte) { + this.aByte = aByte; + this.anInt = 0x10 * aByte; + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/IDLValueHelper.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/IDLValueHelper.java new file mode 100644 index 000000000..cd08386ff --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/IDLValueHelper.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +import java.io.Serializable; + +public class IDLValueHelper { + public static Serializable read(InputStream is) { + byte b = is.read_octet(); + return new IDLValue(b); + } + + public static void write(OutputStream os, IDLValue value) { + os.write_octet(value.aByte); + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Profession.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Profession.java new file mode 100644 index 000000000..5d020413d --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Profession.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; + +/** + * A class which uses externalization to serialize values into the stream. + */ +public class Profession implements Externalizable { + private static final long serialVersionUID = 0x7123456789ABCDEFL; + public static final String REPID = "RMI:" + Profession.class.getName() + ":0000000000000001:" + Long.toHexString(serialVersionUID).toUpperCase(); + + private static final String STRINGS[] = {"Rich Man", "Poor Man", "Beggar Man", "Thief", "Doctor", "Lawyer", "Indian Chief"}; + + static final Profession DOCTOR = new Profession("Doctor"); + private static final int NOT_FOUND = -1; + + private String profession; + + public Profession() { + } + + private Profession(String profession) { + this.profession = profession; + } + + String getProfession() { + return profession; + } + + @Override + public void writeExternal(ObjectOutput out) throws IOException { + int i = getProfessionIndex(); + out.writeInt(i); + if (i == NOT_FOUND) out.writeObject(profession); + } + + private int getProfessionIndex() { + for (int i = 0; i < STRINGS.length; i++) + if (STRINGS[i].equalsIgnoreCase(profession)) return i; + + return NOT_FOUND; + } + + @Override + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + int index = in.readInt(); + if (index == NOT_FOUND) + profession = (String) in.readObject(); + else + profession = STRINGS[index]; + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1.java new file mode 100644 index 000000000..32be0b496 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.Serializable; + +class Value1 implements Serializable { + static final String REPID = "RMI:com.sun.corba.ee.impl.encoding.Value1:3E1F37A79F0D0984:F72C4A0542764A7B"; + char aChar; + int anInt; + + Value1(char aChar, int anInt) { + this.aChar = aChar; + this.anInt = anInt; + } + + Value1() { + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1DefaultFactory.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1DefaultFactory.java new file mode 100644 index 000000000..2ad4c4084 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1DefaultFactory.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import org.omg.CORBA.portable.ValueFactory; +import org.omg.CORBA_2_3.portable.InputStream; + +import java.io.Serializable; + +public class Value1DefaultFactory implements ValueFactory { + @Override + public Serializable read_value(InputStream is) { + char c = is.read_wchar(); + return new Value1(c, c); + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1Helper.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1Helper.java new file mode 100644 index 000000000..29292643b --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value1Helper.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.org.omg.CORBA.portable.ValueHelper; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.TypeCodePackage.BadKind; +import org.omg.CORBA.portable.OutputStream; + +import java.io.Serializable; + +import static com.meterware.simplestub.Stub.createStrictStub; + +abstract class Value1Helper implements ValueHelper { + Value1Type typeCode = createStrictStub(Value1Type.class); + + void setModifier(short modifier) { + typeCode.modifier = modifier; + } + + @Override + public TypeCode get_type() { + return typeCode; + } + + @Override + public void write_value(OutputStream os, Serializable value) { + Value1 value1 = (Value1) value; + os.write_wchar(value1.aChar); + os.write_long(value1.anInt); + } + + @Override + public String get_id() { + return Value1.REPID; + } +} + + +abstract class Value1Type extends TypeCode { + short modifier; + + @Override + public short type_modifier() throws BadKind { + return modifier; + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value2.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value2.java new file mode 100644 index 000000000..bf081f02c --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/Value2.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import java.io.Serializable; + +class Value2 implements Serializable { + static final String REPID = "RMI:com.sun.corba.ee.impl.encoding.Value2:512583A866C00892:E19C2D95C723A741"; + long aLong; + Value1 aValue; +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/ValueTestBase.java b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/ValueTestBase.java new file mode 100644 index 000000000..c54b22e81 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/encoding/ValueTestBase.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.encoding; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import org.glassfish.corba.testutils.HexBuffer; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Stack; + +public class ValueTestBase extends EncodingTestBase { + protected static final int USE_CODEBASE = 0x01; + protected static final int ONE_REPID_ID = 0x02; + protected static final int USE_CHUNKING = 0x08; + private static final int BASE_VALUE_TAG = 0x7fffff00; + + private DataByteOutputStream out = new DataByteOutputStream(); + private final Stack chunkStack = new Stack(); + + protected void writeValueTag(int flags) throws IOException { + writeInt(BASE_VALUE_TAG | flags); + } + + protected byte[] getGeneratedBody() { + return out.toByteArray(); + } + + protected void writeByte(int aByte) throws IOException { + out.write(aByte); + } + + protected int getCurrentLocation() { + return out.pos(); + } + + protected void writeCodebase(String location) throws IOException { + writeString(location); + } + + protected void writeNull() throws IOException { + writeInt(0); + } + + protected void dumpBuffer() { + HexBuffer.dumpBuffer(getGeneratedBody()); + } + + protected void writeWchar_1_1(char aChar) throws IOException { + out.write((aChar >> 8)); + out.write(aChar); + } + + protected void writeWchar_1_2(char aChar) throws IOException { + out.write(4); + writeBigEndianMarker(); + out.write((aChar >> 8)); + out.write(aChar); + } + + protected void writeEndTag(int chunkLevel) throws IOException { + writeInt(chunkLevel); + } + + /** When starting a new chunk, align and reserve space for the chunk length. **/ + protected void startChunk() throws IOException { + align(4); + chunkStack.push(out); + out = new DataByteOutputStream(out.pos() + 4); + } + + protected void endChunk() throws IOException { + byte[] chunkData = out.toByteArray(); + out = chunkStack.pop(); + writeInt(chunkData.length); + out.write(chunkData); + } + + protected void writeStringValue_1_2(String value) throws IOException { + writeInt(2 + 2*value.length()); + writeBigEndianMarker(); + for (char aChar : value.toCharArray()) { + out.write(0); + out.write(aChar); + } + } + + private void writeBigEndianMarker() throws IOException { + out.write(FE); + out.write(FF); + } + + protected void writeRepId(String id) throws IOException { + writeString(id); + } + + protected void writeString(String string) throws IOException { + writeInt(string.length() + 1); + for (char aChar : string.toCharArray()) + out.write(aChar); + out.write(0); + } + + protected void writeInt(int value) throws IOException { + align(4); + out.writeInt(value); + } + + protected void writeLong(long value) throws IOException { + align(8); + out.writeLong(value); + } + + private void align(int size) throws IOException { + while ((out.pos() % size) != 0) + out.write(0); + } + + protected void writeIndirectionTo(int location) throws IOException { + writeInt(-1); + writeInt(location - out.pos()); + } + + static class DataByteOutputStream extends DataOutputStream { + private int streamStart; + + DataByteOutputStream() { + this(Message.GIOPMessageHeaderLength); + } + + DataByteOutputStream(int streamStart) { + super(new ByteArrayOutputStream()); + this.streamStart = streamStart; + } + + private byte[] toByteArray() { + return ((ByteArrayOutputStream) out).toByteArray(); + } + + private int pos() { + return streamStart + size(); + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/folb/GroupManagerServiceInterceptorsTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/folb/GroupManagerServiceInterceptorsTest.java new file mode 100644 index 000000000..e99a6787a --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/folb/GroupManagerServiceInterceptorsTest.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.folb; + +import com.sun.corba.ee.impl.interceptors.CodecFactoryImpl; +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.IIOPPrimaryToContactInfo; +import com.sun.corba.ee.spi.transport.IORToSocketInfo; +import org.glassfish.corba.testutils.StubCorbaObject; +import org.junit.Before; +import org.junit.Test; +import org.omg.CORBA.ORBPackage.InvalidName; +import org.omg.CORBA.Object; +import org.omg.IOP.CodecFactoryPackage.UnknownEncoding; +import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; +import org.omg.IOP.ServiceContext; +import org.omg.IOP.TaggedComponent; +import org.omg.PortableInterceptor.ClientRequestInfo; +import org.omg.PortableInterceptor.ClientRequestInterceptor; +import org.omg.PortableInterceptor.ForwardRequest; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; +import org.omg.PortableInterceptor.ORBInitializer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static org.junit.Assert.*; + +public class GroupManagerServiceInterceptorsTest implements GroupInfoServiceObserver { + + private final TestClientGroupManager clientGroupManager = new TestClientGroupManager(); + private final TestORB orb = createStrictStub(TestORB.class); + private final TestORBData orbData = createStrictStub(TestORBData.class); + private final TestORBInitInfo orbInitInfo = createStrictStub(TestORBInitInfo.class); + private final TestClientRequestInfo clientRequestInfo = createStrictStub(TestClientRequestInfo.class); + private final TestContactInfo contactInfo = createStrictStub(TestContactInfo.class); + + private static final byte[] COMPONENT_DATA_1 = new byte[]{0, 1, 2, 5, 6}; + private static final byte[] COMPONENT_DATA_2 = new byte[]{9, 3, 3}; + + private int numMembershipChanges; + private IOR locatedIOR; + + public void membershipChange() { + numMembershipChanges++; + } + + @Before + public void setUp() throws InvalidName, UnknownEncoding { + orb.setORBData(orbData); + clientGroupManager.configure(null, orb); + clientGroupManager.addObserver(this); + CodecFactoryImpl codecFactory = new CodecFactoryImpl(orb); + orb.register_initial_reference(ORBConstants.CODEC_FACTORY_NAME, codecFactory); + preInitInitializers(); + postInitInitializers(); + clientGroupManager.reset(contactInfo); + } + + private void preInitInitializers() { + for (ORBInitializer initializer : orbData.getORBInitializers()) + initializer.pre_init(orbInitInfo); + } + + private void postInitInitializers() { + for (ORBInitializer initializer : orbData.getORBInitializers()) + initializer.post_init(orbInitInfo); + } + + @Test + public void whenClientGroupManagerInitialized_registerForCallbacks() { + assertEquals(clientGroupManager, orbData.getIIOPPrimaryToContactInfo()); + assertEquals(clientGroupManager, orbData.getIORToSocketInfo()); + } + + @Test + public void whenRequestIORContainsNoFolbMembershipComponent_doNothing() throws ForwardRequest { + defineFolbMembershipTaggedComponents(); // No components defined + + sendRequest(); + + assertNull(getFolbMembershipServiceContext()); + } + + @Test + public void whenRequestIORContainsOneFolbMembershipComponent_createCorrespondingServiceContext() throws ForwardRequest { + defineFolbMembershipTaggedComponents(COMPONENT_DATA_1); + + sendRequest(); + + assertEqualData(COMPONENT_DATA_1, getFolbMembershipServiceContext().context_data); + } + + @Test + public void whenRequestIORContainsMultipleFolbMembershipComponents_useFirstForServiceContext() throws ForwardRequest { + defineFolbMembershipTaggedComponents(COMPONENT_DATA_1, COMPONENT_DATA_2); + + sendRequest(); + + assertEqualData(COMPONENT_DATA_1, getFolbMembershipServiceContext().context_data); + } + + @Test + public void whenReceiveReplyWithNoFolbServiceContext_doNoCallbacks() throws ForwardRequest { + receiveReply(); + + assertEquals(0, numMembershipChanges); + } + + @Test + public void whenReceiveExceptionWithNoFolbServiceContext_doNoCallbacks() throws ForwardRequest { + receiveException(); + + assertEquals(0, numMembershipChanges); + } + + @Test + public void whenReceiveReplyWithFolbServiceContext_issueCallback() throws ForwardRequest, InvalidTypeForEncoding { + TestIOR ior = createIORWithFolbMembershipTaggedComponents(); + setFolbIorUpdateContext(ior); + + receiveReply(); + + assertEquals(1, numMembershipChanges); + assertEquals(ior,locatedIOR); + } + + private void setFolbIorUpdateContext(TestIOR ior) { + byte[] encodedIOR = {1,1,1,1}; + clientGroupManager.setIORWithEncoding(ior,encodedIOR); + clientRequestInfo.setReplyServiceContext(new ServiceContext(ORBConstants.FOLB_IOR_UPDATE_SERVICE_CONTEXT_ID, encodedIOR)); + } + + + public void clientInterceptorOnReceive_addsNewIORForListeners() { + // when we receive a reply, if it has a service context of type ORBConstants.FOLB_IOR_UPDATE_SERVICE_CONTEXT_ID, + // extract a forwarding IOR and notify any listeners. + // (need this for receive_request, receive_exception, and receive_other) + } + + private void assertEqualData( byte[] expected, byte[] actual) { + if (!Arrays.equals(expected, actual)) + fail( "expected " + Arrays.toString(expected) + " but was " + Arrays.toString(actual)); + } + + private ServiceContext getFolbMembershipServiceContext() { + return clientRequestInfo.getRequestServiceContext(ORBConstants.FOLB_MEMBERSHIP_LABEL_SERVICE_CONTEXT_ID); + } + + private void sendRequest() throws ForwardRequest { + for (ClientRequestInterceptor interceptor : orbInitInfo.clientRequestInterceptors) + interceptor.send_request(clientRequestInfo); + } + + private void receiveReply() throws ForwardRequest { + for (ClientRequestInterceptor interceptor : orbInitInfo.clientRequestInterceptors) + interceptor.receive_reply(clientRequestInfo); + } + + private void receiveException() throws ForwardRequest { + for (ClientRequestInterceptor interceptor : orbInitInfo.clientRequestInterceptors) + interceptor.receive_exception(clientRequestInfo); + } + + private void defineOperation(String operationName) { + clientRequestInfo.setOperation(operationName); + } + + private void defineFolbMembershipTaggedComponents(byte[]... componentData) { + clientRequestInfo.setEffectiveTarget(createObjectWithFolbMembershipTaggedComponents(componentData)); + } + + private Object createObjectWithFolbMembershipTaggedComponents(byte[]... componentData) { + TestIOR ior = createIORWithFolbMembershipTaggedComponents(componentData); + return StubObject.createObjectWithIOR(ior); + } + + private static TestIOR createIORWithFolbMembershipTaggedComponents(byte[]... componentData) { + TaggedComponent[] taggedComponents = new TaggedComponent[componentData.length]; + for (int i = 0; i < taggedComponents.length; i++) + taggedComponents[i] = new TaggedComponent(ORBConstants.FOLB_MEMBERSHIP_LABEL_TAGGED_COMPONENT_ID, componentData[i]); + + return TestIOR.createIORWithTaggedComponents(ORBConstants.FOLB_MEMBERSHIP_LABEL_TAGGED_COMPONENT_ID, taggedComponents); + } + + + abstract static class TestORBInitInfo extends StubCorbaObject implements ORBInitInfo { + List clientRequestInterceptors = new ArrayList(); + + public void add_client_request_interceptor(ClientRequestInterceptor interceptor) throws DuplicateName { + clientRequestInterceptors.add(interceptor); + } + + } + + class TestClientGroupManager extends ClientGroupManager { + + + private TestIOR ior; + private byte[] encodedIOR; + + @Override + protected IOR extractIOR(byte[] data) { + assertEqualData(encodedIOR,data); + return ior; + } + + @Override + protected void reportLocatedIOR(ClientRequestInfo ri, IOR ior) { + locatedIOR = ior; + } + + void setIORWithEncoding(TestIOR ior, byte[] encodedIOR) { + this.ior = ior; + this.encodedIOR = encodedIOR; + } + } + + abstract static class TestORBData implements ORBData { + private IORToSocketInfo IORToSocketInfo; + private IIOPPrimaryToContactInfo IIOPPrimaryToContactInfo; + private List orbInitializers = new ArrayList(); + + public IORToSocketInfo getIORToSocketInfo() { + return IORToSocketInfo; + } + + public void setIORToSocketInfo(IORToSocketInfo IORToSocketInfo) { + this.IORToSocketInfo = IORToSocketInfo; + } + + public ORBInitializer[] getORBInitializers() { + return orbInitializers.toArray(new ORBInitializer[orbInitializers.size()]); + } + + public void addORBInitializer(ORBInitializer orbInitializer) { + orbInitializers.add(orbInitializer); + } + + public IIOPPrimaryToContactInfo getIIOPPrimaryToContactInfo() { + return IIOPPrimaryToContactInfo; + } + + public void setIIOPPrimaryToContactInfo(IIOPPrimaryToContactInfo IIOPPrimaryToContactInfo) { + this.IIOPPrimaryToContactInfo = IIOPPrimaryToContactInfo; + } + } + + + abstract static class TestORB extends ORB { + private ORBData ORBData; + private Map initialReferences = new HashMap(); + + public void setORBData(ORBData orbData) { + this.ORBData = orbData; + } + + public ORBData getORBData() { + return ORBData; + } + + public void register_initial_reference(String id, Object obj) throws org.omg.CORBA.ORBPackage.InvalidName { + initialReferences.put(id, obj); + } + + public Object resolve_initial_references(String id) throws InvalidName { + return initialReferences.get(id); + } + } + + + abstract static public class TestClientRequestInfo implements ClientRequestInfo { + private Object effectiveTarget; + private String operation = ""; + private Map requestServiceContexts = new HashMap(); + private Map replyServiceContexts = new HashMap(); + + public Object effective_target() { + return effectiveTarget; + } + + public String operation() { + return operation; + } + + public void add_request_service_context(ServiceContext serviceContext, boolean replace) { + requestServiceContexts.put(serviceContext.context_id, serviceContext); + } + + public ServiceContext get_reply_service_context(int id) { + return replyServiceContexts.get(id); + } + + public void setEffectiveTarget(Object effectiveTarget) { + this.effectiveTarget = effectiveTarget; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public ServiceContext getRequestServiceContext(int id) { + return requestServiceContexts.get(id); + } + + public void setReplyServiceContext(ServiceContext serviceContext) { + replyServiceContexts.put(serviceContext.context_id, serviceContext); + } + } + + abstract static class TestContactInfo implements ContactInfo { + public int getPort() { + return 1000; + } + } + + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/folb/StubObject.java b/orbmain/src/test/java/com/sun/corba/ee/impl/folb/StubObject.java new file mode 100644 index 000000000..d9ba4ea7c --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/folb/StubObject.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.folb; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import org.omg.CORBA.portable.ObjectImpl; + +import static com.meterware.simplestub.Stub.createStrictStub; + +public class StubObject extends ObjectImpl { + static org.omg.CORBA.Object createObjectWithIOR(IOR ior) { + StubObject result = new StubObject(); + result._set_delegate(createDelegateWithIOR(ior)); + return result; + } + + private static TestClientDelegate createDelegateWithIOR(IOR ior) { + TestClientDelegate delegate = createStrictStub(TestClientDelegate.class); + delegate.setContactInfoList(createInfoListWithIOR(ior)); + return delegate; + } + + private static TestContactInfoList createInfoListWithIOR(IOR ior) { + TestContactInfoList infoList = createStrictStub(TestContactInfoList.class); + infoList.setTargetIOR(ior); + return infoList; + } + + public String[] _ids() { + return new String[0]; + } + + abstract static class TestClientDelegate extends ClientDelegate { + private ContactInfoList contactInfoList; + + public void setContactInfoList(ContactInfoList contactInfoList) { + this.contactInfoList = contactInfoList; + } + + public ContactInfoList getContactInfoList() { + return contactInfoList; + } + } + + abstract static class TestContactInfoList implements ContactInfoList { + private IOR ior; + + public void setTargetIOR(IOR ior) { + this.ior = ior; + } + + public IOR getTargetIOR() { + return ior; + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/folb/TestIOR.java b/orbmain/src/test/java/com/sun/corba/ee/impl/folb/TestIOR.java new file mode 100644 index 000000000..ce0b9639f --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/folb/TestIOR.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.folb; + +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.TaggedComponent; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import org.omg.CORBA.ORB; +import org.omg.CORBA_2_3.portable.OutputStream; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static com.meterware.simplestub.Stub.createStrictStub; + +abstract class TestIOR implements IOR { + + static TestIOR createIORWithTaggedComponents(int id, org.omg.IOP.TaggedComponent... components) { + TestIOR ior = createStrictStub(TestIOR.class); + ior.setProfile(createIIOPProfileWithTaggedComponents(id, components)); + return ior; + } + + private IIOPProfile profile; + + public IIOPProfile getProfile() { + return profile; + } + + public void setProfile(IIOPProfile profile) { + this.profile = profile; + } + + static TestIIOPProfile createIIOPProfileWithTaggedComponents(int id, org.omg.IOP.TaggedComponent... components) { + TestIIOPProfile profile = createStrictStub(TestIIOPProfile.class); + profile.setProfileTemplate(createIIOPProfileTemplateWithTaggedComponents(id, components)); + return profile; + } + + abstract static class TestIIOPProfile implements IIOPProfile { + + private TaggedProfileTemplate profileTemplate; + + public TaggedProfileTemplate getTaggedProfileTemplate() { + return profileTemplate; + } + + public void setProfileTemplate(TaggedProfileTemplate profileTemplate) { + this.profileTemplate = profileTemplate; + } + + } + + static TestIIOPProfileTemplate createIIOPProfileTemplateWithTaggedComponents(int id, org.omg.IOP.TaggedComponent... components) { + TestIIOPProfileTemplate template = createStrictStub(TestIIOPProfileTemplate.class); + for (org.omg.IOP.TaggedComponent component : components) + template.addTaggedComponent(id, component); + return template; + } + + abstract static class TestIIOPProfileTemplate implements IIOPProfileTemplate { + private Map> taggedComponents = new HashMap>(); + + public void addTaggedComponent(int id, org.omg.IOP.TaggedComponent component) { + getTaggedComponentList(id).add(new TestTaggedComponent(id,component)); + } + + public Iterator iteratorById(int id) { + return getTaggedComponentList(id).iterator(); + } + + private List getTaggedComponentList(int id) { + List componentList = taggedComponents.get(id); + if (componentList == null) { + componentList = new ArrayList(); + taggedComponents.put(id, componentList); + } + return componentList; + } + } + + static class TestTaggedComponent implements TaggedComponent { + + private int id; + private org.omg.IOP.TaggedComponent iopComponent; + + TestTaggedComponent(int id, org.omg.IOP.TaggedComponent iopComponent) { + this.id = id; + this.iopComponent = iopComponent; + } + + public org.omg.IOP.TaggedComponent getIOPComponent(ORB orb) { + return iopComponent; + } + + public int getId() { + return id; + } + + public void write(OutputStream outputStream) { + } + } +} + + diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/io/ValueHandlerTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/io/ValueHandlerTest.java new file mode 100644 index 000000000..921250ac4 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/io/ValueHandlerTest.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.io; + +import java.lang.reflect.Modifier; + +import org.junit.Assert; +import org.junit.Test; + +public class ValueHandlerTest { + /** + * Ensures that value handler impl is final + */ + @Test + public void testValueHandlerImplIsFinal() { + int mods = ValueHandlerImpl.class.getModifiers(); + + Assert.assertTrue(Modifier.isFinal(mods)); + } + + /** + * Ensures the SharedSecrets class works + */ + @Test + public void testSharedSecrets() { + Assert.assertNotNull(SharedSecrets.getJavaCorbaAccess()); + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/ior/IORImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/ior/IORImplTest.java new file mode 100644 index 000000000..c9f6a0c23 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/ior/IORImplTest.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior; + +import com.sun.corba.ee.impl.encoding.EncodingTestBase; +import com.sun.corba.ee.spi.ior.IOR; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class IORImplTest extends EncodingTestBase { + + @Test + public void stringifyIncludesTypeId() { + IOR ior = new IORImpl(getOrb(), "TestType"); + assertEquals("IOR:" + "00000000" + "00000009" + "54657374" + "54797065" +"0000000000000000", ior.stringify()); + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileImplTest.java new file mode 100644 index 000000000..d5631ff06 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/ior/iiop/IIOPProfileImplTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.ior.iiop; + +import com.sun.corba.ee.impl.orb.ORBVersionImpl; +import com.sun.corba.ee.spi.ior.ObjectId; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion; +import org.junit.Test; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +public class IIOPProfileImplTest { + private ORB orb = createStrictStub(ORB.class); + private ObjectId oid = createStrictStub(ObjectId.class); + private IIOPProfileTemplate profileTemplate = createStrictStub(IIOPProfileTemplate.class); + private ObjectKeyTemplateStub objectKeyTemplate = createStrictStub(ObjectKeyTemplateStub.class); + + private IIOPProfileImpl iiopProfile = new IIOPProfileImpl(orb, objectKeyTemplate, oid, profileTemplate); + + @Test + public void whenForeignProfileOrbVersion_isLocalReturnsFalse() throws Exception { + setOrbVersion(ORBVersionImpl.FOREIGN); + + assertThat(iiopProfile.isLocal(), is(false)); + } + + private void setOrbVersion(ORBVersion orbVersion) { + objectKeyTemplate.setOrbVersion(orbVersion); + } + + abstract static class ObjectKeyTemplateStub implements ObjectKeyTemplate { + + private ORBVersion orbVersion = ORBVersionImpl.NEW; + + public void setOrbVersion(ORBVersion orbVersion) { + this.orbVersion = orbVersion; + } + + @Override + public ORBVersion getORBVersion() { + return orbVersion; + } + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/JNDIStateFactoryImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/JNDIStateFactoryImplTest.java new file mode 100644 index 000000000..958ee4908 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/JNDIStateFactoryImplTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import com.meterware.simplestub.Memento; +import com.meterware.simplestub.StaticStubSupport; +import com.meterware.simplestub.Stub; +import com.sun.corba.ee.spi.orb.ORB; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.omg.CosNaming.NamingContext; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.rmi.CORBA.PortableRemoteObjectDelegate; +import javax.rmi.PortableRemoteObject; +import java.rmi.NoSuchObjectException; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public class JNDIStateFactoryImplTest { + + private JNDIStateFactoryImpl impl = new JNDIStateFactoryImpl(); + private final Remote remote = createStrictStub(Remote.class); + private Hashtable env = new Hashtable<>(); + private ORB orb = createStrictStub(JndiOrb.class); + + private List mementos = new ArrayList<>(); + private Context context; + private CorbaStub corbaStub; + + @After + public void tearDown() throws Exception { + for (Memento memento : mementos) memento.revert(); + } + + @Before + public void setUp() throws Exception { + context = createContextWithOrb(); + corbaStub = createStrictStub(CorbaStub.class); + } + + abstract static class OrbContext implements Context { + private ORB _orb; + + OrbContext(ORB _orb) { + this._orb = _orb; + } + } + + private Context createContextWithOrb() throws NamingException { + return Stub.createStrictStub(OrbContext.class, orb); + } + + @Test + public void whenObjectIsCorbaObject_returnIt() throws Exception { + Object testObject = createStrictStub(org.omg.CORBA.Object.class); + + assertThat(impl.getStateToBind(testObject, null, null, env), sameInstance(testObject)); + } + + @Test + public void whenObjectIsNotRemote_returnNull() throws Exception { + assertThat(impl.getStateToBind(new Object(), null, null, env), nullValue()); + } + + @Test + public void whenCannotGetOrbFromContext_returnNull() throws Exception { + assertThat(impl.getStateToBind(remote, null, createStrictStub(Context.class), env), nullValue()); + } + + @Test + public void whenObjectIsNotAStub_returnNull() throws Exception { + installDelegate(createStrictStub(NoStubDelegate.class)); + + assertThat(impl.getStateToBind(remote, null, context, env), nullValue()); + } + + private void installDelegate(PortableRemoteObjectDelegate delegate) throws NoSuchFieldException { + mementos.add(StaticStubSupport.install(PortableRemoteObject.class, "proDelegate", delegate)); + } + + abstract static class NoStubDelegate implements PortableRemoteObjectDelegate { + @Override + public Remote toStub(Remote obj) throws NoSuchObjectException { + return null; + } + } + + @Test + public void whenObjectIsAStub_returnIt() throws Exception { + installDelegateForStub(corbaStub); + + Object state = impl.getStateToBind(remote, null, context, env); + assertThat(state, sameInstance(corbaStub)); + } + + private void installDelegateForStub(CorbaStub stub) throws NoSuchFieldException { + installDelegate(createStrictStub(StubPRODelegate.class, stub)); + } + + @Test + public void whenObjectIsAStub_connectIt() throws Exception { + installDelegateForStub(corbaStub); + + impl.getStateToBind(remote, null, context, env); + assertThat(corbaStub.connected, is(true)); + } + + abstract static class StubPRODelegate implements PortableRemoteObjectDelegate { + Remote stub; + + public StubPRODelegate(Remote stub) { + this.stub = stub; + } + + @Override + public Remote toStub(Remote obj) throws NoSuchObjectException { + return stub; + } + } + + abstract static class CorbaStub extends javax.rmi.CORBA.Stub implements Remote { + private boolean connected = false; + + @Override + public void connect(org.omg.CORBA.ORB orb) throws RemoteException { + connected = true; + } + } + + abstract static class JndiOrb extends ORB { + @Override + public org.omg.CORBA.Object string_to_object(String str) { + return createStrictStub(NamingContext.class); + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/StubInvocationHandlerImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/StubInvocationHandlerImplTest.java new file mode 100644 index 000000000..626f40301 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/StubInvocationHandlerImplTest.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import com.sun.corba.ee.spi.copyobject.CopyobjectDefaults; +import com.sun.corba.ee.spi.oa.OAInvocationInfo; +import com.sun.corba.ee.spi.presentation.rmi.DynamicMethodMarshaller; +import com.sun.corba.ee.spi.presentation.rmi.IDLNameTranslator; +import com.sun.corba.ee.spi.presentation.rmi.InvocationInterceptor; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager; +import com.sun.corba.ee.spi.protocol.ClientDelegate; +import com.sun.corba.ee.spi.protocol.LocalClientRequestDispatcher; +import com.sun.corba.ee.spi.transport.ContactInfoList; +import org.junit.Before; +import org.junit.Test; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CORBA.portable.Delegate; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.ServantObject; + +import java.lang.reflect.Method; +import java.rmi.RemoteException; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static com.meterware.simplestub.Stub.createStub; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.emptyArray; +import static org.hamcrest.Matchers.not; + +public class StubInvocationHandlerImplTest { + + private PresentationManagerFake presentationManager = createStrictStub(PresentationManagerFake.class); + private ClassDataFake classData = createStrictStub(ClassDataFake.class); + + private CalledObject calledObject = new CalledObject(); + private Method throwExceptionMethod; + + private StubInvocationHandlerImpl handler = new StubInvocationHandlerImpl(presentationManager, classData, new CalledObject()); + + @Before + public void setUp() throws Exception { + throwExceptionMethod = CalledObject.class.getMethod("throwException"); + } + + @Test + public void whenColocatedCallThrowsException_exceptionHasStackTrace() throws Throwable { + try { + handler.invoke(calledObject, throwExceptionMethod, new Object[0]); + } catch (TestException exception) { + assertThat(exception.getStackTrace(), not(emptyArray())); + } + } + + static class CalledObject extends ObjectImpl { + private Delegate delegate = createStrictStub(ClientDelegateFake.class, this); + + @SuppressWarnings({"WeakerAccess", "unused"}) + public void throwException() throws Exception { + throw new TestException("thrown in test"); + } + + @Override + public String[] _ids() { + return new String[0]; + } + + @Override + public Delegate _get_delegate() { + return delegate; + } + } + + static class TestException extends RuntimeException { + public TestException(String message) { + super(message); + } + } + + static abstract class PresentationManagerFake implements PresentationManager { + @Override + public DynamicMethodMarshaller getDynamicMethodMarshaller(Method method) { + return createStrictStub(DynamicMethodMarshallerFake.class); + } + } + + static abstract class DynamicMethodMarshallerFake implements DynamicMethodMarshaller { + @Override + public java.lang.Object[] copyArguments(java.lang.Object[] args, ORB orb) throws RemoteException { + return args; + } + + @Override + public boolean isDeclaredException(Throwable thr) { + return true; + } + } + + static abstract class ClassDataFake implements PresentationManager.ClassData { + @Override + public IDLNameTranslator getIDLNameTranslator() { + return createStrictStub(IDLNameTranslatorFake.class); + } + } + + static abstract class IDLNameTranslatorFake implements IDLNameTranslator { + @Override + public String getIDLName(Method method) { + return "methodName"; + } + } + + static abstract class ClientDelegateFake extends ClientDelegate { + private Object servant; + + ClientDelegateFake(Object servant) { + this.servant = servant; + } + + @Override + public ContactInfoList getContactInfoList() { + return createStrictStub(ContactInfoListFake.class); + } + + @Override + public ORB orb(Object obj) { + return createStrictStub(ORBFake.class); + } + + @Override + public ServantObject servant_preinvoke(Object self, String operation, Class expectedType) { + ServantObject servantObject = new ServantObject(); + servantObject.servant = servant; + return servantObject; + } + } + + static abstract class ORBFake extends com.sun.corba.ee.spi.orb.ORB { + private OAInvocationInfo invocationInfo = new OAInvocationInfo(null, new byte[0]); + + public ORBFake() { + invocationInfo.setCopierFactory( + CopyobjectDefaults.makeFallbackObjectCopierFactory( + CopyobjectDefaults.makeReflectObjectCopierFactory(this), + CopyobjectDefaults.makeORBStreamObjectCopierFactory(this))); + } + + @Override + public InvocationInterceptor getInvocationInterceptor() { + return createStub(InvocationInterceptor.class); + } + + @Override + public OAInvocationInfo peekInvocationInfo() { + return invocationInfo; + } + } + + static abstract class ContactInfoListFake implements ContactInfoList { + @Override + public LocalClientRequestDispatcher getLocalClientRequestDispatcher() { + return createStrictStub(LocalClientRequestDispatcherFake.class); + } + } + + static abstract class LocalClientRequestDispatcherFake implements LocalClientRequestDispatcher { + private boolean useLocalInvocation; + + @SuppressWarnings("unused") + public LocalClientRequestDispatcherFake() { + this(true); + } + + LocalClientRequestDispatcherFake(boolean useLocalInvocation) { + this.useLocalInvocation = useLocalInvocation; + } + + @Override + public boolean useLocalInvocation(Object self) { + return useLocalInvocation; + } + } + + +} + diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/TestIDLNameTranslator.java b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/TestIDLNameTranslator.java new file mode 100644 index 000000000..0e83b4ea5 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/TestIDLNameTranslator.java @@ -0,0 +1,301 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import com.sun.corba.ee.spi.presentation.rmi.IDLNameTranslator; +import corba.dynamicrmiiiop.testclasses.*; +import junit.framework.TestCase; + +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.util.SortedSet; +import java.util.TreeSet; + +public class TestIDLNameTranslator extends TestCase { + + private static final Class[] nonRemoteInterfaces = { + InvalidRemotes.InvalidRemote1.class, + InvalidRemotes.InvalidRemote2.class, + InvalidRemotes.InvalidRemote3.class, + InvalidRemotes.InvalidRemote4.class, + InvalidRemotes.InvalidRemote5.class, + // InvalidRemote6 has a method that declares an unchecked exception. + // Although bad practice, this is not an error. + // InvalidRemotes.InvalidRemote6.class, + // InvalidRemotes.InvalidRemote7.class, + // InvalidRemotes.InvalidRemote8.class, + InvalidRemotes.InvalidRemote9.class, + InvalidRemotes.InvalidRemote10.class, + InvalidRemotes.InvalidRemote11.class, + // The following test for interfaces that inherit the + // same method from multiple super-interfaces. This is supposed + // to be illegal, but rmic allows it, so we will also allow it here. + //InvalidRemotes.InvalidRemote12.class, + //InvalidRemotes.InvalidRemote13.class, + //InvalidRemotes.InvalidRemote14.class, + //InvalidRemotes.InvalidRemote15.class, + InvalidRemotes.InvalidRemote16.class, + InvalidRemotes.InvalidRemote17.class, + InvalidRemotes.InvalidRemote18.class, + InvalidRemotes.InvalidRemote19.class + }; + + protected void setUp() {} + + protected void tearDown() {} + + public void testMultipleInterfaces() + { + doIDLNameTranslationTest( IDLMultipleInterfaceTest.class, + new Class[] { + IDLMultipleInterfaceTest.first.class, + IDLMultipleInterfaceTest.second.class + } + ) ; + } + + public void testIDLProperties() + { + doIDLNameTranslationTest(IDLPropertiesTest.class, + IDLPropertiesTest.IDLProperties.class); + } + + public void testOverloadedMethods() + { + doIDLNameTranslationTest(IDLOverloadedTest.class, + IDLOverloadedTest.IDLOverloaded.class); + } + + public void testContainerClash() + { + + + doIDLNameTranslationTest(new String[] { "ContainerClash1_" }, + ContainerClash1.class); + + doIDLNameTranslationTest(new String[] { "ContainerCLASH2_" }, + ContainerClash2.class); + + doIDLNameTranslationTest(new String[] { "J_ContainerClash3_" }, + _ContainerClash3.class); + + doIDLNameTranslationTest(new String[] { "J_ContainerCLASH4_" }, + _ContainerClash4.class); + } + + public void testLeadingUnderscores() + { + doIDLNameTranslationTest(IDLLeadingUnderscoresTest.class, + IDLLeadingUnderscoresTest.IDLLeadingUnderscores.class); + } + + public void testIDLCaseSensitivity() + { + doIDLNameTranslationTest(IDLCaseSensitivityTest.class, + IDLCaseSensitivityTest.IDLCaseSensitivity.class); + } + + public void testIDLKeywords() + { + doIDLNameTranslationTest(IDLKeywordsTest.class, + IDLKeywordsTest.IDLKeywords.class); + } + + public void testDefaultPackageClasses() + { + Class testClass = null; + Class testInterface = null; + try { + testClass = Class.forName("corba.dynamicrmiiiop.testclasses.IDLDefaultTest"); + testInterface = Class.forName("corba.dynamicrmiiiop.testclasses.IDLDefaultTest$IDLDefault"); + } catch(Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + doIDLNameTranslationTest(testClass, testInterface); + } + + public void testInvalidInterfaces() + { + for(int i = 0; i < nonRemoteInterfaces.length; i++) { + Class nonRemote = nonRemoteInterfaces[i]; + String msg = "Unexpected success for class " + nonRemote.getName() + + " at index " + i ; + + try { + IDLNameTranslator translator = + IDLNameTranslatorImpl.get(nonRemote); + assertTrue(msg, false); + } catch(IllegalStateException ise) { + // System.out.println(ise.getMessage()); + } + + // Also ensure that IDLNameTranslator rejects these interfaces. + } + } + + public void testIDLIdentifiers() + { + doIDLNameTranslationTest(IDLIdentifiersTest.class, + IDLIdentifiersTest.IDLIdentifiers.class); + } + + public void testIDLCombo1() { + doIDLNameTranslationTest(IDLComboTest1.class, + IDLComboTest1.IDLCombo.class); + } + + private String[] getExpectedIdlNames( Class cls ) + { + String[] expectedIdlNames = new String[0]; + try { + Method idlNamesMethod = cls.getMethod("getIDLNames", + new Class[] {}); + expectedIdlNames = (String[]) + idlNamesMethod.invoke(null, new Object[] {}); + } catch(Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + + return expectedIdlNames ; + } + + private void doIDLNameTranslationTest(Class testClass, + Class[] testInterfaces) + { + String[] expectedIdlNames = getExpectedIdlNames( testClass ) ; + IDLNameTranslator nameTranslator = + IDLNameTranslatorImpl.get(testInterfaces); + Method[] sortedMethods = getSortedMethods( testInterfaces ); + + doIDLNameTranslationTest(expectedIdlNames, nameTranslator, + sortedMethods ); + } + + private void doIDLNameTranslationTest(Class testClass, + Class testInterface) + { + String[] expectedIdlNames = getExpectedIdlNames( testClass ) ; + doIDLNameTranslationTest( expectedIdlNames, testInterface ) ; + } + + private void doIDLNameTranslationTest(String[] expectedIdlNames, + Class testInterface) + { + IDLNameTranslator nameTranslator = + IDLNameTranslatorImpl.get(testInterface); + Method[] sortedMethods = getSortedMethods( + new Class[] { testInterface } ); + + doIDLNameTranslationTest(expectedIdlNames, nameTranslator, + sortedMethods ); + } + + private void doIDLNameTranslationTest( + String[] expectedIdlNames, IDLNameTranslator nameTranslator, + Method[] sortedMethods ) + { + for(int i = 0; i < sortedMethods.length; i++) { + Method m = (Method) sortedMethods[i]; + String expected = expectedIdlNames[i]; + String translatedName = nameTranslator.getIDLName(m); + String msg = "expected '" + expected + "'" + + " got '" + translatedName + "' " + ":" + m; + + assertEquals(msg, expected, translatedName); + assertEquals(msg, m, + nameTranslator.getMethod(expected)); + } + } + + public void testUnicodeTranslation() + { + IDLNameTranslatorImpl nameTranslator = + (IDLNameTranslatorImpl)IDLNameTranslatorImpl.get( + java.rmi.Remote.class); + + for( int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; i++ ) { + char c = (char) i; + String unicode = IDLNameTranslatorImpl.charToUnicodeRepresentation( + c); + String msg = i + ":" + Character.toString(c) + ":" + unicode; + + // Make sure result is 5 characters long : 1 character for + // the "U", plus four for the hex representation. + assertEquals(msg, 5, unicode.length()); + + BigInteger bigInt = new BigInteger(unicode.substring(1), 16); + int hexValue = bigInt.intValue(); + msg = msg + ":" + hexValue; + // Convert the hex back into a value and compare with original. + assertEquals(msg, i, hexValue); + } + + } + + private Method[] getSortedMethods(Class[] classes) + { + SortedSet sortedMethods = new TreeSet(new MethodComparator()); + + for(int classCtr = 0; classCtr < classes.length; classCtr++ ) { + Method[] methods = classes[classCtr].getMethods(); + + for(int methodCtr = 0; methodCtr < methods.length; methodCtr++) { + Method next = methods[methodCtr]; + sortedMethods.add(next); + } + } + + Method[] sortedMethodArray = new Method[sortedMethods.size()]; + + sortedMethods.toArray(sortedMethodArray); + + /** Uncomment to print method order. Useful when + debugging interfaces with multiple methods that have + complex signatures + + System.out.println(sortedMethodArray.length + " sorted methods : "); + for(int i = 0; i < sortedMethodArray.length; i++) { + System.out.println(sortedMethodArray[i]); + } + */ + + return sortedMethodArray; + } + + // + // Alphabetically sorted interface methods. + // Method strings are composed of method name, + // (case sensitive), followed by comma-separated list of the value + // of Class.getName() for each parameter type. + // + // + private static class MethodComparator implements java.util.Comparator { + public int compare(Object o1, Object o2) { + String m1 = getMethodString((Method)o1); + String m2 = getMethodString((Method)o2); + return m1.compareTo(m2); + } + + private String getMethodString(Method m) { + StringBuffer methodStr = new StringBuffer(m.getName()); + Class[] params = m.getParameterTypes(); + for(int i = 0; i < params.length; i++) { + Class next = params[i]; + methodStr.append("|"); + methodStr.append(next.getName()); + } + return methodStr.toString(); + } + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/TestRMIIDLTypes.java b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/TestRMIIDLTypes.java new file mode 100644 index 000000000..713e48a2f --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/presentation/rmi/TestRMIIDLTypes.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.presentation.rmi; + +import corba.dynamicrmiiiop.testclasses.InvalidEntities; +import corba.dynamicrmiiiop.testclasses.InvalidExceptions; +import corba.dynamicrmiiiop.testclasses.InvalidObjRefs; +import corba.dynamicrmiiiop.testclasses.InvalidValues; +import corba.dynamicrmiiiop.testclasses.ValidEntities; +import corba.dynamicrmiiiop.testclasses.ValidExceptions; +import corba.dynamicrmiiiop.testclasses.ValidObjRefs; +import corba.dynamicrmiiiop.testclasses.ValidRemotes; +import corba.dynamicrmiiiop.testclasses.ValidValues; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class TestRMIIDLTypes extends TestCase { + + private IDLTypesUtil idlTypesUtil; + + public static Test suite() + { + return new TestSuite(TestRMIIDLTypes.class); + } + + protected void setUp() + { + idlTypesUtil = new IDLTypesUtil(); + } + + protected void tearDown() + { + } + + public void testPrimitiveTypes() + { + Class[] primitives = { + Void.TYPE, Boolean.TYPE, Byte.TYPE, Character.TYPE, + Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE + }; + + for(int i = 0; i < primitives.length; i++) { + Class primitive = primitives[i]; + String msg = primitive.getName(); + assertTrue(msg, idlTypesUtil.isPrimitive(primitive)); + assertFalse(msg,idlTypesUtil.isRemoteInterface(primitive)); + assertFalse(msg,idlTypesUtil.isValue(primitive)); + assertFalse(msg,idlTypesUtil.isArray(primitive)); + assertFalse(msg,idlTypesUtil.isException(primitive)); + assertFalse(msg,idlTypesUtil.isObjectReference(primitive)); + assertFalse(msg,idlTypesUtil.isEntity(primitive)); + } + + Class[] nonPrimitives = { + Byte.class, Short.class, Integer.class, Long.class, Float.class, + Double.class, String.class, java.util.Date.class, Object.class + }; + + for(int i = 0; i < nonPrimitives.length; i++) { + Class nonPrimitive = nonPrimitives[i]; + String msg = nonPrimitive.getName(); + assertFalse(msg, idlTypesUtil.isPrimitive(nonPrimitive)); + } + + } + + public void testRemoteInterfaceTypes() + { + + Class[] remoteInterfaces = ValidRemotes.CLASSES; + + for(int i = 0; i < remoteInterfaces.length; i++) { + Class remoteIntf = remoteInterfaces[i]; + String msg = remoteIntf.getName(); + + assertTrue(msg, idlTypesUtil.isRemoteInterface(remoteIntf)); + + assertFalse(msg,idlTypesUtil.isPrimitive(remoteIntf)); + assertFalse(msg,idlTypesUtil.isValue(remoteIntf)); + assertFalse(msg,idlTypesUtil.isArray(remoteIntf)); + assertFalse(msg,idlTypesUtil.isException(remoteIntf)); + assertFalse(msg,idlTypesUtil.isObjectReference(remoteIntf)); + assertFalse(msg,idlTypesUtil.isEntity(remoteIntf)); + } + + // NOTE invalid remote interfaces are tested in TestIDLNameTranslator + } + + public void testValueTypes() + { + + Class[] values = ValidValues.CLASSES; + + for(int i = 0; i < values.length; i++) { + Class value = values[i]; + String msg = value.getName(); + + assertTrue(msg,idlTypesUtil.isValue(value)); + + assertFalse(msg, idlTypesUtil.isPrimitive(value)); + assertFalse(msg,idlTypesUtil.isRemoteInterface(value)); + assertFalse(msg,idlTypesUtil.isArray(value)); + assertFalse(msg,idlTypesUtil.isException(value)); + assertFalse(msg,idlTypesUtil.isObjectReference(value)); + assertFalse(msg,idlTypesUtil.isEntity(value)); + } + + Class[] nonValues = InvalidValues.CLASSES; + + for(int i = 0; i < nonValues.length; i++) { + Class nonValue = nonValues[i]; + String msg = nonValue.getName(); + assertFalse(msg, idlTypesUtil.isValue(nonValue)); + } + + } + + public void testExceptionTypes() + { + + Class[] exceptions = ValidExceptions.CLASSES; + + for(int i = 0; i < exceptions.length; i++) { + Class excep = exceptions[i]; + String msg = excep.getName(); + + assertTrue(msg,idlTypesUtil.isException(excep)); + // a valid exception is always a valid value type ! + assertTrue(msg,idlTypesUtil.isValue(excep)); + + assertFalse(msg, idlTypesUtil.isPrimitive(excep)); + assertFalse(msg,idlTypesUtil.isRemoteInterface(excep)); + assertFalse(msg,idlTypesUtil.isArray(excep)); + assertFalse(msg,idlTypesUtil.isObjectReference(excep)); + assertFalse(msg,idlTypesUtil.isEntity(excep)); + } + + Class[] nonExceptions = InvalidExceptions.CLASSES; + + for(int i = 0; i < nonExceptions.length; i++) { + Class nonException = nonExceptions[i]; + String msg = nonException.getName(); + assertFalse(msg, idlTypesUtil.isException(nonException)); + } + } + + public void testObjRefs() + { + + Class[] objRefs = ValidObjRefs.CLASSES; + + for(int i = 0; i < objRefs.length; i++) { + Class objRef = objRefs[i]; + String msg = objRef.getName(); + + assertTrue(msg,idlTypesUtil.isObjectReference(objRef)); + + assertFalse(msg, idlTypesUtil.isPrimitive(objRef)); + assertFalse(msg,idlTypesUtil.isRemoteInterface(objRef)); + assertFalse(msg,idlTypesUtil.isValue(objRef)); + assertFalse(msg,idlTypesUtil.isArray(objRef)); + assertFalse(msg,idlTypesUtil.isException(objRef)); + assertFalse(msg,idlTypesUtil.isEntity(objRef)); + } + + Class[] nonObjRefs = InvalidObjRefs.CLASSES; + + for(int i = 0; i < nonObjRefs.length; i++) { + Class nonObjRef = nonObjRefs[i]; + String msg = nonObjRef.getName(); + assertFalse(msg, idlTypesUtil.isObjectReference(nonObjRef)); + } + + } + + public void testEntities() + { + + Class[] entities = ValidEntities.CLASSES; + + for(int i = 0; i < entities.length; i++) { + Class entity = entities[i]; + String msg = entity.getName(); + + assertTrue(msg,idlTypesUtil.isEntity(entity)); + // An entity type is always a value type + assertTrue(msg,idlTypesUtil.isValue(entity)); + + assertFalse(msg, idlTypesUtil.isPrimitive(entity)); + assertFalse(msg,idlTypesUtil.isRemoteInterface(entity)); + assertFalse(msg,idlTypesUtil.isArray(entity)); + assertFalse(msg,idlTypesUtil.isException(entity)); + assertFalse(msg,idlTypesUtil.isObjectReference(entity)); + + } + + Class[] nonEntities = InvalidEntities.CLASSES; + + for(int i = 0; i < nonEntities.length; i++) { + Class nonEntity = nonEntities[i]; + String msg = nonEntity.getName(); + assertFalse(msg, idlTypesUtil.isEntity(nonEntity)); + } + + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/protocol/ClientRequestDispatcherImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/protocol/ClientRequestDispatcherImplTest.java new file mode 100644 index 000000000..df12908c1 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/protocol/ClientRequestDispatcherImplTest.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.impl.encoding.BufferManagerFactory; +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.protocol.ClientInvocationInfo; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.PIHandler; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.ContactInfo; +import com.sun.corba.ee.spi.transport.ContactInfoListIterator; +import org.junit.Test; +import org.omg.CORBA.portable.RemarshalException; + +import java.util.Iterator; + +import static com.meterware.simplestub.Stub.createStrictStub; + +public class ClientRequestDispatcherImplTest { + + static final int BUFFER_SIZE = 128; + private final ORBFake orb = createStrictStub(ORBFake.class); + private final MessageMediatorFake mediator = createStrictStub(MessageMediatorFake.class, orb); + private final MessageFake message = createStrictStub(MessageFake.class); + private final byte streamFormatVersion = 1; + + private ClientRequestDispatcherImpl impl = new ClientRequestDispatcherImpl(); + private CDROutputObject outputObject = new CDROutputObject(orb, mediator, message, streamFormatVersion); + + @Test(expected = RemarshalException.class) + public void whenPIHandleReturnsRemarshalException_throwIt() throws Exception { + orb.setPiEndingPointException(new RemarshalException()); + + impl.marshalingComplete(null, outputObject); + } + + abstract static class ORBFake extends ORB { + private ClientInvocationInfoFake invocationInfo = createStrictStub(ClientInvocationInfoFake.class); + private ORBDataFake orbData = createStrictStub(ORBDataFake.class); + private Exception piEndingPointException; + + void setPiEndingPointException(Exception piEndingPointException) { + this.piEndingPointException = piEndingPointException; + } + + @Override + public ClientInvocationInfo getInvocationInfo() { + return invocationInfo; + } + + @Override + public ORBData getORBData() { + return orbData; + } + + @Override + public PIHandler getPIHandler() { + return createStrictStub(PIHandlerFake.class, this); + } + } + + abstract static class ClientInvocationInfoFake implements ClientInvocationInfo { + @Override + public Iterator getContactInfoListIterator() { + return createStrictStub(ContactInfoListIteratorFake.class); + } + } + + abstract static class ContactInfoListIteratorFake implements ContactInfoListIterator { + @Override + public boolean reportException(ContactInfo contactInfo, RuntimeException exception) { + return false; + } + } + + abstract static class ORBDataFake implements ORBData { + @Override + public int getGIOPBufferSize() { + return BUFFER_SIZE; + } + + @Override + public int getGIOPBuffMgrStrategy(GIOPVersion gv) { + return BufferManagerFactory.GROW; + } + } + + abstract static class PIHandlerFake implements PIHandler { + private ORBFake orb; + + public PIHandlerFake(ORBFake orb) { + this.orb = orb; + } + + @Override + public Exception invokeClientPIEndingPoint(int replyStatus, Exception exception) { + return orb.piEndingPointException == null ? exception : orb.piEndingPointException; + } + } + + abstract static class MessageMediatorFake implements MessageMediator { + private ORB orb; + private RuntimeException exception = new RuntimeException("test"); + + public MessageMediatorFake(ORB orb) { + this.orb = orb; + } + + @Override + public void finishSendingRequest() { + + } + + @Override + public ORB getBroker() { + return orb; + } + + @Override + public Connection getConnection() { + return null; + } + + @Override + public ContactInfo getContactInfo() { + return null; + } + + @Override + public GIOPVersion getGIOPVersion() { + return GIOPVersion.DEFAULT_VERSION; + } + + @Override + public String getOperationName() { + return "test"; + } + + @Override + public int getRequestId() { + return 0; + } + + @Override + public boolean isOneWay() { + return false; + } + + @Override + public CDRInputObject waitForResponse() { + if (exception != null) throw exception; + return null; + } + } + + abstract static class MessageFake implements Message { + @Override + public byte getEncodingVersion() { + return ORBConstants.CDR_ENC_VERSION; + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/protocol/MessageParserTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/protocol/MessageParserTest.java new file mode 100644 index 000000000..9cb4ae01d --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/protocol/MessageParserTest.java @@ -0,0 +1,415 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.protocol; + +import com.sun.corba.ee.impl.protocol.giopmsgheaders.FragmentMessage_1_2; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.LocateRequestMessage_1_2; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage_1_1; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage_1_2; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_0; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2; +import com.sun.corba.ee.impl.transport.MessageTraceManagerImpl; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.MessageParser; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.MessageTraceManager; +import com.sun.corba.ee.spi.transport.TransportManager; +import org.junit.Before; +import org.junit.Test; +import org.omg.CORBA.COMM_FAILURE; + +import java.nio.ByteBuffer; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static org.junit.Assert.*; + +public class MessageParserTest { + + private static final int BUFFER_SIZE = 1357; // pick a bizarre number that should not occur randomly + + private ORBDataFake orbData = createStrictStub(ORBDataFake.class); + private ORBFake orb = createStrictStub(ORBFake.class); + private ConnectionFake connection = createStrictStub(ConnectionFake.class); + private TransportManagerFake transportManager = createStrictStub(TransportManagerFake.class); + + private MessageParser parser; + + @Before + public void setUp() throws Exception { + orb.orbData = orbData; + orb.transportManager = transportManager; + parser = new MessageParserImpl(orb, connection); + } + + @Test + public void oldwhenBufferDoesNotContainEntireHeader_requestMore() { + byte[] header = {'G', 'I', 'O', 'P', 1, 0}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + Message message = parser.parseBytes(buffer, connection); + + assertFalse(parser.hasMoreBytesToParse()); + assertTrue(parser.isExpectingMoreData()); + assertEquals(BUFFER_SIZE, parser.getSizeNeeded()); + assertEquals(0, parser.getNextMessageStartPosition()); + assertNull(message); + assertSame(buffer, parser.getRemainderBuffer()); + } + + @Test + public void whenBufferDoesNotContainEntireHeader_requestMoreAndDoNotCreateMediator() { + byte[] header = {'G', 'I', 'O', 'P', 1, 0}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + + assertSame(buffer, parser.getRemainderBuffer()); + assertNull(parser.getMessageMediator()); + assertEquals(0, buffer.position()); + } + + @Test + public void oldwhenBufferContainsHeaderOnly_requestMore() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPCancelRequest, 0, 0, 0, 6, 1, 2}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + Message message = parser.parseBytes(buffer, connection); + + assertFalse(parser.hasMoreBytesToParse()); + assertTrue(parser.isExpectingMoreData()); + assertEquals(18, parser.getSizeNeeded()); + assertEquals(0, parser.getNextMessageStartPosition()); + assertNull(message); + assertSame(buffer, parser.getRemainderBuffer()); + } + + @Test + public void whenBufferContainsHeaderOnly_requestMoreAndDoNotCreateMediator() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPCancelRequest, 0, 0, 0, 6, 1, 2}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + + assertSame(buffer, parser.getRemainderBuffer()); + assertNull(parser.getMessageMediator()); + assertEquals(0, buffer.position()); + } + + @Test + public void whenBufferIsLittleEndianAndContainsHeaderOnly_requestMoreAndDoNotCreateMediator() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.LITTLE_ENDIAN_BIT, Message.GIOPCancelRequest, 6, 0, 0, 0, 1, 2}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + + assertSame(buffer, parser.getRemainderBuffer()); + assertNull(parser.getMessageMediator()); + assertEquals(0, buffer.position()); + } + + @Test + public void old_whenBufferContainsWholeMessage_consumeEntireBuffer() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + Message message = parser.parseBytes(buffer, connection); + + assertFalse(parser.hasMoreBytesToParse()); + assertFalse(parser.isExpectingMoreData()); + assertEquals(true, message instanceof ReplyMessage_1_2); + assertEquals(header.length, parser.getMsgByteBuffer().limit()); + assertEquals(0, parser.getRemainderBuffer().remaining()); + } + + @Test + public void whenBufferContainsWholeMessage_consumeEntireBuffer() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + assertNull(parser.getRemainderBuffer()); + MessageMediator mediator = parser.getMessageMediator(); + assertNotNull(mediator); + assertTrue(mediator.getDispatchHeader() instanceof ReplyMessage_1_2); + } + + @Test + public void afterConsumingEntireBuffer_offerOfNullBufferClearsMessageMediator() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + parser.offerBuffer(null); + assertNull(parser.getMessageMediator()); + } + + @Test + public void whenIsLittleEndianAndBufferContainsWholeMessage_consumeEntireBuffer() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.LITTLE_ENDIAN_BIT, Message.GIOPReply, 6, 0, 0, 0, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + assertNull(parser.getRemainderBuffer()); + MessageMediator mediator = parser.getMessageMediator(); + assertNotNull(mediator); + assertTrue(mediator.getDispatchHeader() instanceof ReplyMessage_1_2); + } + + @Test + public void oldwhenBufferContainsRestOfMessage_consumeEntireBuffer() { + byte[] partMessage = {'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPRequest, 0, 0, 0, 6, 1}; + byte[] wholeMessage = {'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(partMessage); + parser.parseBytes(buffer, connection); + + buffer = ByteBuffer.wrap(wholeMessage); + Message message = parser.parseBytes(buffer, connection); + + assertFalse(parser.hasMoreBytesToParse()); + assertFalse(parser.isExpectingMoreData()); + assertEquals(true, message instanceof RequestMessage_1_0); + assertEquals(wholeMessage.length, parser.getMsgByteBuffer().limit()); + assertEquals(0, parser.getRemainderBuffer().remaining()); + } + + @Test + public void whenBufferContainsRestOfMessage_consumeEntireBuffer() { + byte[] partMessage = {'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPRequest, 0, 0, 0, 6, 1}; + byte[] wholeMessage = {'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + parser.offerBuffer(ByteBuffer.wrap(partMessage)); + + parser.offerBuffer(ByteBuffer.wrap(wholeMessage)); + assertNull(parser.getRemainderBuffer()); + MessageMediator mediator = parser.getMessageMediator(); + assertNotNull(mediator); + assertTrue(mediator.getDispatchHeader() instanceof RequestMessage_1_0); + } + + @Test + public void oldwhenBufferContainsWholeMessagePlusMore_consumeMessageAndLeaveMore() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6, 'G'}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + Message message = parser.parseBytes(buffer, connection); + + assertTrue(parser.hasMoreBytesToParse()); + assertFalse(parser.isExpectingMoreData()); + assertTrue(message instanceof ReplyMessage_1_1); + assertEquals(18, parser.getMsgByteBuffer().limit()); + assertEquals(1, parser.getRemainderBuffer().remaining()); + } + + @Test + public void whenBufferContainsWholeMessageAndMore_consumeMessageBytesAndLeaveRemainder() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, + 1, 2, 3, 4, 5, 6, + 'R', 'M', 'I'}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + assertNotNull(parser.getRemainderBuffer()); + assertEquals(3, parser.getRemainderBuffer().remaining()); + assertEquals('R', parser.getRemainderBuffer().get(0)); + MessageMediator mediator = parser.getMessageMediator(); + assertNotNull(mediator); + assertTrue(mediator.getDispatchHeader() instanceof ReplyMessage_1_1); + } + + @Test + public void afterConsumingMessage_offerOfPartialBufferClearsMessageMediator() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, + 1, 2, 3, 4, 5, 6, + 'R', 'M', 'I'}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + parser.offerBuffer(parser.getRemainderBuffer()); + assertNull(parser.getMessageMediator()); + } + + @Test + public void oldwhenBufferContainsWholeMessageNeedingFragments_consumeEntireBufferAndExpectMore() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.MORE_FRAGMENTS_BIT, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + Message message = parser.parseBytes(buffer, connection); + + assertFalse(parser.hasMoreBytesToParse()); + assertTrue(parser.isExpectingMoreData()); + assertTrue(message instanceof ReplyMessage_1_1); + assertEquals(header.length, parser.getMsgByteBuffer().limit()); + } + + @Test + public void whenBufferContainsWholeMessageNeedingFragments_consumeEntireBuffer() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.MORE_FRAGMENTS_BIT, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + MessageMediator messageMediator = parser.getMessageMediator(); + + assertNull(parser.getRemainderBuffer()); + assertTrue(messageMediator.getDispatchHeader() instanceof ReplyMessage_1_1); + assertTrue(parser.isExpectingFragments()); + } + + @Test + public void oldwhenBufferContainsFinalFragment_consumeBuffer() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, Message.GIOPRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6, + 'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, 0, 0, 0, 4, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + Message message1 = parser.parseBytes(buffer, connection); + Message message2 = parser.parseBytes(buffer, connection); + + assertTrue(parser.hasMoreBytesToParse()); + assertFalse(parser.isExpectingMoreData()); + assertEquals(34, parser.getNextMessageStartPosition()); + assertTrue(message1 instanceof RequestMessage_1_2); + assertTrue(message2 instanceof FragmentMessage_1_2); + } + + @Test + public void whenBufferContainsFinalFragment_consumeBuffer() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, Message.GIOPRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6, + 'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, 0, 0, 0, 4, 1, 2, 3, 4}; + ByteBuffer buffer = ByteBuffer.wrap(header); + parser.offerBuffer(buffer); + MessageMediator messageMediator1 = parser.getMessageMediator(); + parser.offerBuffer(parser.getRemainderBuffer()); + MessageMediator messageMediator2 = parser.getMessageMediator(); + + assertNull(parser.getRemainderBuffer()); + assertTrue(messageMediator1.getDispatchHeader() instanceof RequestMessage_1_2); + assertTrue(messageMediator2.getDispatchHeader() instanceof FragmentMessage_1_2); + } + + @Test + public void oldwhenStartPositionNonZero_startReadingFromPosition() { + byte[] header = {0, 0, 'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPLocateRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6, 'G'}; + ByteBuffer buffer = ByteBuffer.wrap(header); + buffer.position(2); + parser.setNextMessageStartPosition(2); + + Message message = parser.parseBytes(buffer, connection); + + assertTrue(parser.hasMoreBytesToParse()); + assertEquals(20, parser.getNextMessageStartPosition()); + assertFalse(parser.isExpectingMoreData()); + assertTrue(message instanceof LocateRequestMessage_1_2); + assertEquals(18, parser.getMsgByteBuffer().limit()); + } + + + @Test + public void whenTimedOutBetweenMessages_doNothing() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + parser.offerBuffer(null); + + parser.checkTimeout(Integer.MAX_VALUE); + } + + @Test + public void whenMidBodyButNotTimedOut_doNothing() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + parser.offerBuffer(null); + + parser.checkTimeout(10); + } + + @Test(expected = COMM_FAILURE.class) + public void whenTimedOutMidHeader_throwAnException() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + + parser.checkTimeout(Integer.MAX_VALUE); + } + + @Test(expected = COMM_FAILURE.class) + public void whenTimedOutMidBody_throwAnException() { + byte[] header = {'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPReply, 0, 0, 0, 6, 1}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + parser.offerBuffer(null); + + parser.checkTimeout(Integer.MAX_VALUE); + } + + @Test(expected = COMM_FAILURE.class) + public void whenTimedOutWhileWaitingForFragment_throwAnException() { + byte[] header = {'G', 'I', 'O', 'P', 1, 1, Message.MORE_FRAGMENTS_BIT, Message.GIOPReply, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}; + ByteBuffer buffer = ByteBuffer.wrap(header); + + parser.offerBuffer(buffer); + parser.offerBuffer(null); + + parser.checkTimeout(Integer.MAX_VALUE); + } + + @Test + public void whenToStringInvoked_stateIsReported() { + assertTrue(parser.toString().contains("expectingMoreData=false")); + } + + static abstract class ORBDataFake implements ORBData { + private GIOPVersion giopVersion = GIOPVersion.V1_2; + + @Override + public int getReadByteBufferSize() { + return BUFFER_SIZE; + } + + @Override + public GIOPVersion getGIOPVersion() { + return giopVersion; + } + } + + static abstract class ORBFake extends ORB { + private ORBData orbData; + private TransportManager transportManager; + + @Override + public ORBData getORBData() { + return orbData; + } + + @Override + public TransportManager getTransportManager() { + return transportManager; + } + } + + static abstract class ConnectionFake implements Connection { + } + + static abstract class TransportManagerFake implements TransportManager { + private MessageTraceManager mtm = new MessageTraceManagerImpl(); + + @Override + public MessageTraceManager getMessageTraceManager() { + return mtm; + } + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/transport/ConnectionImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/ConnectionImplTest.java new file mode 100644 index 000000000..85b14f514 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/ConnectionImplTest.java @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.protocol.RequestIdImpl; +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.threadpool.Work; +import org.junit.After; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; + +import static org.junit.Assert.*; + +public class ConnectionImplTest extends TransportTestBase { + + private static final byte[] BYTE_DATA = {0,1,2,3,4,5,6,7,8,9,10}; + + @After + public void tearDown() { + if (getConnection() != null) + assertNull(getConnection().getDiscardedThrowable()); + } + + @Test + public void whenRequest1_0_receivedFromSocket_dispatchRequest() throws IOException { // REG + final List params = new ArrayList(); + defineRequestDispatcher( new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromSocketWithoutChannelAndDispatch(new byte[]{'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPRequest, /* size */ 0, 0, 0, 38, /* no service contexts */ 0, 0, 0, 0, + /* request ID */ 0, 0, 0, 2, /* response expected */ 1, /* padding */ 0, 0, 0, + /* object key */ 0, 0, 0, 4, 0, 0, 0, 6, /* operation */ 0, 0, 0, 5, 'd', 'o', 'I', 't', 0, + 0, 0, 0, /* principal */ 0, 0, 0, 0, /* short param */ 1, 1}); + getConnection().doWork(); + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("doIt", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + @Test + public void whenRequest1_0_receivedFromNio_dispatchRequest() throws IOException { + final List params = new ArrayList(); + defineRequestDispatcher( new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromNio(new byte[]{'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPRequest, /* size */ 0, 0, 0, 38, /* no service contexts */ 0, 0, 0, 0, + /* request ID */ 0, 0, 0, 2, /* response expected */ 1, /* padding */ 0, 0, 0, + /* object key */ 0, 0, 0, 4, 0, 0, 0, 6, /* operation */ 0, 0, 0, 5, 'd', 'o', 'I', 't', 0, + 0, 0, 0, /* principal */ 0, 0, 0, 0, /* short param */ 1, 1}); + getConnection().doWork(); + processQueuedWork(); + + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("doIt", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + @Test + public void whenRequest1_1_receivedFromNio_dispatchRequest() throws IOException { + final List params = new ArrayList(); + defineRequestDispatcher( new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromNio(new byte[]{'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPRequest, /* size */ 0, 0, 0, 38, /* no service contexts */ 0, 0, 0, 0, + /* request ID */ 0, 0, 0, 2, /* response expected */ 1, /* padding */ 0,0,0, + /* object key */ 0, 0, 0, 4, 0, 0, 0, 6, /* operation */ 0, 0, 0, 5, 'd', 'o', 'I', 't', 0, + 0, 0, 0, /* principal */ 0, 0, 0, 0, /* short param */ 1, 1}); + getConnection().doWork(); + processQueuedWork(); + + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("doIt", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + @Test + public void whenLittleEndianRequest1_2_receivedFromNio_dispatchRequest() throws IOException { + final List params = new ArrayList(); + defineRequestDispatcher( new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromNio(new byte[]{'G', 'I', 'O', 'P', 1, 2, Message.LITTLE_ENDIAN_BIT, + Message.GIOPRequest, /* size */ 38, 0, 0, 0, + /* request ID */ 2, 0, 0, 0, /* response expected */ 1, /* request reserved */ 0, 0, 0, + /* use key */ 0, 0, /* padding */ 0, 0, /* object key */ 4, 0, 0, 0, 0, 0, 0, 6, + /* operation */ 5, 0, 0, 0, 'd', 'o', 'I', 't', 0, + /* padding */ 0, 0, 0, /* no service contexts */ 0, 0, 0, 0, /* short param */ 1, 1}); + getConnection().doWork(); + processQueuedWork(); + + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("doIt", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + @Test + public void whenRequest1_1_receivedFromSocketWithFragments_dispatchRequest() throws IOException, InterruptedException { // REG + final List params = new ArrayList(); + defineRequestDispatcher( new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromSocketWithoutChannelAndDispatch(new byte[]{'G', 'I', 'O', 'P', 1, 1, Message.MORE_FRAGMENTS_BIT, + Message.GIOPRequest, /* size */ 0, 0, 0, 36, /* no service contexts */ 0, 0, 0, 0, + /* request ID */ 0, 0, 0, 2, /* response expected */ 1, /* reserved */ 0, 0, 0, + /* object key */ 0, 0, 0, 4, 0, 0, 0, 6, /* operation */ 0, 0, 0, 5, 'd', 'o', 'I', 't', 0, + /* padding */ 0, 0, 0, /* principal */ 0, 0, 0, 0, + + 'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, + /* size */ 0, 0, 0, 2, /* short param */ 1, 1}); + processSocketMessageWithFragments(1); + + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("doIt", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + private void processSocketMessageWithFragments(int numFragments) throws InterruptedException { + BackgroundProcessor backgroundProcessor = new BackgroundProcessor(numFragments); + getConnection().doWork(); + backgroundProcessor.waitUntilDone(); + } + + @Test + public void whenRequest1_1ReceivedFromNioWithFragments_dispatchRequest() throws IOException, InterruptedException { + final List params = new ArrayList(); + defineRequestDispatcher(new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromNio(new byte[]{'G', 'I', 'O', 'P', 1, 1, Message.MORE_FRAGMENTS_BIT, + Message.GIOPRequest, /* size */ 0, 0, 0, 36, /* no service contexts */ 0, 0, 0, 0, + /* request ID */ 0, 0, 0, 2, /* response expected */ 1, /* reserved */ 0, 0, 0, + /* object key */ 0, 0, 0, 4, 0, 0, 0, 6, /* operation */ 0, 0, 0, 5, 'd', 'o', 'I', 't', 0, + /* padding */ 0, 0, 0, /* principal */ 0, 0, 0, 0, + + 'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, + /* size */ 0, 0, 0, 2, /* short param */ 1, 1}); + processNioMessageWithFragments(1); + + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("doIt", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + @Test + public void whenRequest1_2ReceivedFromNioWithFragments_dispatchRequest() throws IOException, InterruptedException { + final List params = new ArrayList(); + defineRequestDispatcher(new RequestDispatcher() { + public void readParameters(CDRInputObject input) { + params.add(input.read_short()); + } + }); + readFromNio(new byte[]{'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, + Message.GIOPRequest, /* size */ 0, 0, 0, 36, + /* request ID */ 0, 0, 0, 2, /* response expected */ 1, /* reserved */ 0, 0, 0, + /* use key */ 0, 0, /* padding */ 0, 0, /* object key */ 0, 0, 0, 4, 0, 0, 0, 6, + /* operation */ 0, 0, 0, 8, 'g', 'o', 'A', 'g', 'a', 'i', 'n', 0, + /* no service contexts */ 0, 0, 0, 0, + + 'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, + /* size */ 0, 0, 0, 6, /* request id */ 0, 0, 0, 2, /* short param */ 1, 1}); + processNioMessageWithFragments(1); + + assertEquals(1, getMediators().size()); + MessageMediator mediator = getMediators().remove(0); + assertEquals("goAgain", mediator.getOperationName()); + assertEquals(2, mediator.getRequestId()); + assertFalse(mediator.isOneWay()); + assertEquals(257, (short) params.get(0)); + } + + private void processNioMessageWithFragments(int numFragments) throws InterruptedException { + getConnection().doWork(); + Work work = getWorkQueue().remove(); + BackgroundProcessor backgroundProcessor = new BackgroundProcessor(numFragments); + work.doWork(); + backgroundProcessor.waitUntilDone(); + } + + @Test + public void whenCloseConnectionReceivedFromSocket_shutdownConnection() { + readFromSocketWithoutChannelAndDispatch(new byte[]{'G', 'I', 'O', 'P', 1, 1, Message.FLAG_NO_FRAG_BIG_ENDIAN, + Message.GIOPCloseConnection, /* size */ 0, 0, 0, 0}); + getConnection().doWork(); + assertEquals(1, getNumConnectionsRemoved()); + getConnection().clearDiscardedThrowable(); + } + + @Test(expected = RuntimeException.class) + public void whenNioConfigureBlockingFails_throwException() throws IOException { + SocketChannelFake socketChannel = getSocketChannel(); + socketChannel.setFailToConfigureBlocking(); + useNio(); + } + + @Test + public void whenNioFullBufferWritable_allDataIsWritten() throws IOException { + useNio(); + getConnection().write(ByteBuffer.wrap(BYTE_DATA)); + + assertArrayEquals(BYTE_DATA, getSocketChannel().getDataWritten()); + } + + + @Test + public void whenNioChannelMomentarilyBusy_allDataIsWritten() throws IOException { + useNio(); + getSocketChannel().setNumBytesToWrite(0); + getConnection().write(ByteBuffer.wrap(BYTE_DATA)); + + assertArrayEquals(BYTE_DATA, getSocketChannel().getDataWritten()); + } + + @Test + public void whenNioWholeMessageReceived_queueSingleEntry() throws IOException { + useNio(); + getSocketChannel().enqueData(new byte[]{'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}); + getConnection().doWork(); + assertEquals(1, getWorkQueue().size()); + assertTrue(getWorkQueue().remove() instanceof MessageMediator); + } + + @Test + public void whenNioMessageReceivedInTwoReads_queueSingleEntryAfterSecond() throws IOException { + useNio(); + getSocketChannel().enqueData(new byte[]{'G', 'I', 'O', 'P', 1, 0, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPRequest, 0, 0, 0, 6, 1, 2, 3, 4, 5, 6}); + getSocketChannel().setNumBytesToRead(8, 0); + getConnection().doWork(); + getConnection().doWork(); + assertEquals(1, getWorkQueue().size()); + assertTrue(getWorkQueue().remove() instanceof MessageMediator); + } + + @Test + public void whenNioFragmentsIncluded_queueFirstMessageAndAddFragmentsToFragmentList() throws IOException { + useNio(); + byte[] messages = {'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, Message.GIOPRequest, 0, 0, 0, 6, 0, 0, 0, 3, 5, 6, + 'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, Message.GIOPFragment, 0, 0, 0, 6, 0, 0, 0, 3, 5, 6, + 'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, 0, 0, 0, 4, 0, 0, 0, 3}; + getSocketChannel().enqueData(messages); + getConnection().doWork(); + assertEquals(1, getWorkQueue().size()); + Work workItem = getWorkQueue().remove(); + assertTrue(workItem instanceof MessageMediator); + Queue fragmentList = getConnection().getFragmentList(new RequestIdImpl(3)); + assertEquals(2, fragmentList.size()); + } + + @Test + public void whenMessageWithFragmentsReceivedFromSocket_dispatchEachPart() throws IOException { + byte[] messages = {'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, Message.GIOPRequest, 0, 0, 0, 6, 0, 0, 0, 3, 5, 6, + 'G', 'I', 'O', 'P', 1, 2, Message.MORE_FRAGMENTS_BIT, Message.GIOPFragment, 0, 0, 0, 6, 0, 0, 0, 3, 5, 6, + 'G', 'I', 'O', 'P', 1, 2, Message.FLAG_NO_FRAG_BIG_ENDIAN, Message.GIOPFragment, 0, 0, 0, 4, 0, 0, 0, 3}; + readFromSocketWithoutChannelAndDispatch(messages); + collectMediatorsAsDispatched(); + getConnection().doWork(); + assertEquals(1, getMediators().size()); + getConnection().doWork(); + getConnection().doWork(); + assertEquals(3, getMediators().size()); + } + + + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/transport/SelectorImplTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/SelectorImplTest.java new file mode 100644 index 000000000..e11c1c1f5 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/SelectorImplTest.java @@ -0,0 +1,347 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.Connection; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static com.meterware.simplestub.Stub.createStub; +import static org.junit.Assert.*; + +public class SelectorImplTest extends TransportTestBase { + + private TimerFake timer = new TimerFake(); + private SelectorImpl selector = new SelectorImpl(getOrb(), timer); + private EventHandlerFake eventHandler = new EventHandlerFake(); + private NioSelectorFake selectorStub = createStub(NioSelectorFake.class); + private SelectableChannelFake channel = createStub(SelectableChannelFake.class); + + @Before + public void setUpTest() throws Exception { + simulateStartSelectorCall(); + eventHandler.channel = channel; + } + + private void simulateStartSelectorCall() { + setPrivateFieldValue(selector, "selector", selectorStub); + setPrivateFieldValue(selector, "selectorStarted", Boolean.TRUE); + } + + @Test + public void whenRegisteringAcceptEventWithoutSelectThread_listenerThreadIsCreated() { + eventHandler.setUseSelectThreadToWait(false); + eventHandler.setInterestOps(SelectionKey.OP_ACCEPT); + selector.registerForEvent(eventHandler); + assertTrue(getWorkQueue().remove() instanceof ListenerThreadImpl); + } + + @Test + public void whenRegisteringReadEventWithoutSelectThread_readerThreadIsCreated() { + eventHandler.setUseSelectThreadToWait(false); + eventHandler.setInterestOps(SelectionKey.OP_READ); + selector.registerForEvent(eventHandler); + assertTrue(getWorkQueue().remove() instanceof ReaderThreadImpl); + } + + @Test + public void whenSelectorClosed_nioSelectorClosedAndLoopEnds() throws IOException { + selector.close(); + + selector.runSelectionLoopOnce(); + assertFalse(selectorStub.isOpen()); + } + + @Test + public void whenRegisteringEventWithSelectThread_wakeUpSelector() throws IOException { + registerEventHandler(); + + assertTrue(selectorStub.wakeupCalled); + } + + @Test + public void afterRegisteringEventWithSelectThread_runRegistersChannel() throws IOException { + registerEventHandler(); + + assertFalse(selectorStub.keys.isEmpty()); + SelectionKey selectionKey = selectorStub.keys.get(0); + assertEquals(eventHandler.getChannel(), selectionKey.channel()); + assertEquals(0, eventHandler.numInvocations); + } + + private void registerEventHandler() throws IOException { + eventHandler.setUseSelectThreadToWait(true); + eventHandler.setInterestOps(SelectionKey.OP_READ); + selector.registerForEvent(eventHandler); + selector.runSelectionLoopOnce(); + } + + @Test + public void whenIoAvailable_dispatchToEventHandler() throws IOException { + registerEventHandler(); + + selectorStub.setReady(channel, SelectionKey.OP_READ); + selector.runSelectionLoopOnce(); + assertEquals(1, eventHandler.numInvocations); + } + + @Test + public void whenEventTimesOut_reportTimeout() throws IOException { + registerEventHandler(); + + timer.setCurrentTime(1000); + selector.runSelectionLoopOnce(); + assertTrue(eventHandler.timeout); + } + + @Test + public void whenEventHappens_resetTheTimer() throws IOException { + registerEventHandler(); + + timer.setCurrentTime(1000); + selectorStub.setReady(channel, SelectionKey.OP_READ); + selector.runSelectionLoopOnce(); + assertFalse(eventHandler.timeout); + } + + + protected void setPrivateFieldValue(Object obj, String fieldName, Object value) { + try { + Class theClass = obj.getClass(); + setPrivateFieldValue(obj, theClass, fieldName, value); + } catch (NoSuchFieldException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + private void setPrivateFieldValue(Object obj, Class theClass, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { + try { + Field field = theClass.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(obj, value); + } catch (NoSuchFieldException e) { + if (theClass.equals(Object.class)) + throw e; + else + setPrivateFieldValue(obj, theClass.getSuperclass(), fieldName, value); + } + } + + static class EventHandlerFake extends EventHandlerBase implements Timeoutable, Work { + private int interestOps; + private SelectableChannelFake channel; + public int numInvocations; + private boolean timeout; + + public void setInterestOps(int interestOps) { + this.interestOps = interestOps; + } + + @Override + public int getInterestOps() { + return interestOps; + } + + @Override + public Acceptor getAcceptor() { + return null; + } + + @Override + public Connection getConnection() { + return null; + } + + @Override + public SelectableChannel getChannel() { + return channel; + } + + @Override + public Work getWork() { + return this; + } + + @Override + public void doWork() { + numInvocations++; + channel.clearReadyOps(); + } + + @Override + public void setEnqueueTime(long timeInMillis) { + } + + @Override + public long getEnqueueTime() { + return 0; + } + + @Override + public String getName() { + return null; + } + + @Override + public void checkForTimeout(long timeSinceLastActivity) { + timeout = timeSinceLastActivity > 100; + } + } + + static abstract class NioSelectorFake extends Selector { + boolean wakeupCalled; + boolean open; + List keys = new ArrayList(); + + Set selectedKeys = new HashSet(); + Set activeKeys = new HashSet(); + + public void addKey(SelectionKeyFake selectionKey) { + keys.add(selectionKey); + } + + public void setReady(SelectableChannel channel, int op) { + for (SelectionKey key : keys) { + if (key.channel().equals(channel)) { + activeKeys.add(key); + ((SelectionKeyFake) key).setReady(op); + } + } + } + + @Override + public Selector wakeup() { + wakeupCalled = true; + return this; + } + + @Override + public int select(long timeout) throws IOException { + selectedKeys.addAll(activeKeys); + activeKeys.clear(); + return selectedKeys.size(); + } + + @Override + public Set selectedKeys() { + return selectedKeys; + } + + @Override + public boolean isOpen() { + return open; + } + + @Override + public void close() throws IOException { + open = false; + } + } + + static abstract class SelectableChannelFake extends SelectableChannel { + private Set keys = new HashSet(); + + @Override + public SelectionKey register(Selector sel, int ops, Object attachment) throws ClosedChannelException { + SelectionKeyFake selectionKey = new SelectionKeyFake(this, ops, sel); + selectionKey.attach(attachment); + ((NioSelectorFake) sel).addKey(selectionKey); + keys.add(selectionKey); + return selectionKey; + } + + + public void clearReadyOps() { + for (SelectionKeyFake key : keys) + key.readyOps = 0; + } + } + + static class SelectionKeyFake extends SelectionKey { + private SelectableChannel channel; + private int interestOps; + private Selector selector; + private int readyOps; + + SelectionKeyFake(SelectableChannel channel, int interestOps, Selector selector) { + this.channel = channel; + this.interestOps = interestOps; + this.selector = selector; + } + + public SelectableChannel channel() { + return channel; + } + + @Override + public Selector selector() { + return selector; + } + + @Override + public boolean isValid() { + return true; + } + + @Override + public void cancel() { + } + + @Override + public int interestOps() { + return interestOps; + } + + @Override + public SelectionKey interestOps(int ops) { + interestOps = ops; + return this; + } + + @Override + public int readyOps() { + return readyOps; + } + + void setReady(int op) { + readyOps |= op; + } + } + + static class TimerFake implements SelectorImpl.Timer { + private long currentTime; + + @Override + public long getCurrentTime() { + return currentTime; + } + + public void setCurrentTime(long currentTime) { + this.currentTime = currentTime; + } + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/transport/SocketChannelReaderTest.java b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/SocketChannelReaderTest.java new file mode 100644 index 000000000..feb90e3ef --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/SocketChannelReaderTest.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import org.junit.Before; +import org.junit.Test; + +import java.io.EOFException; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.Arrays; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +public class SocketChannelReaderTest extends TransportTestBase { + + private static final byte[] DATA_TO_BE_READ = new byte[]{0, 1, 2, 3, 4, 5, 6}; + private SocketChannelReader reader; + + @Before + public void setUpReaderTest() { + reader = new SocketChannelReader(getOrb()); + } + + @Test + public void whenCurrentBufferNull_allocateBufferAndRead() throws IOException { + enqueData(DATA_TO_BE_READ); + ByteBuffer buffer = reader.read(getSocketChannel(), null, 0); + assertBufferContents(buffer, DATA_TO_BE_READ); + } + + private void enqueData(byte[] dataToBeRead) { + getSocketChannel().enqueData(dataToBeRead); + } + + @Test + public void whenCurrentBufferHasPartialData_readToAppendData() throws IOException { + ByteBuffer oldBuffer = ByteBuffer.allocate(100); + populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, 3); + enqueData(DATA_TO_BE_READ, 3, DATA_TO_BE_READ.length - 3); + ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 0); + assertBufferContents(buffer, DATA_TO_BE_READ); + } + + private void populateBuffer(ByteBuffer buffer, byte[] bytes, int offset, int length) { + buffer.put(bytes, offset, length); + buffer.flip(); + } + + private void enqueData(byte[] dataToBeRead, int offset, int length) { + enqueData(getSubarray(dataToBeRead, offset, length)); + } + + private byte[] getSubarray(byte[] dataToBeRead, int offset, int length) { + byte[] data = new byte[Math.min(length, dataToBeRead.length-offset)]; + System.arraycopy(dataToBeRead, offset, data, 0, data.length); + return data; + } + + private void assertBufferContents(ByteBuffer buffer, byte... bytes) { + buffer.flip(); + assertPopulatedBufferContents(buffer, bytes); + } + + private void assertPopulatedBufferContents(ByteBuffer buffer, byte[] bytes) { + byte[] actual = new byte[buffer.limit()]; + buffer.get(actual); + assertEqualData(bytes, actual); + } + + private void assertEqualData( byte[] expected, byte[] actual) { + if (!Arrays.equals(expected, actual)) + fail( "expected " + Arrays.toString(expected) + " but was " + Arrays.toString(actual)); + } + + @Test + public void whenCurrentBufferIsFull_readToAppendData() throws IOException { + ByteBuffer oldBuffer = ByteBuffer.allocate(3); + populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, 3); + enqueData(DATA_TO_BE_READ, 3, DATA_TO_BE_READ.length - 3); + ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 0); + assertBufferContents(buffer, DATA_TO_BE_READ); + } + + @Test + public void whenCurrentBufferTooSmallForIncomingData_reallocateAndAppend() throws IOException { + ByteBuffer oldBuffer = ByteBuffer.allocate(5); + populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, 3); + enqueData(DATA_TO_BE_READ, 3, DATA_TO_BE_READ.length - 3); + ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, DATA_TO_BE_READ.length); + assertBufferContents(buffer, DATA_TO_BE_READ); + } + + @Test + public void whenMoreDataAvailableThanNeeded_ignoreIt() throws IOException { + ByteBuffer oldBuffer = ByteBuffer.allocate(10); + oldBuffer.flip(); + enqueData(DATA_TO_BE_READ); + getSocketChannel().setNumBytesToRead(3, 3); + ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 2); + assertBufferContents(buffer, getSubarray(DATA_TO_BE_READ, 0, 3)); + } + + @Test(expected = EOFException.class) + public void whenEOFDetectedThrowException() throws IOException { + getSocketChannel().setEndOfInput(); + ByteBuffer oldBuffer = ByteBuffer.allocate(5); + reader.read(getSocketChannel(), oldBuffer, 0); + } + + @Test + public void whenNoDataRemains_returnNull() throws IOException { + ByteBuffer oldBuffer = ByteBuffer.allocate(10); + populateBuffer(oldBuffer, DATA_TO_BE_READ, 0, DATA_TO_BE_READ.length); + ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 10); + assertNull(buffer); + assertPopulatedBufferContents(oldBuffer, DATA_TO_BE_READ); + } + + @Test + public void whenAtCapacityAndNoDataRemains_returnNullAndPreserveOldBuffer() throws IOException { + ByteBuffer oldBuffer = ByteBuffer.wrap(DATA_TO_BE_READ); + ByteBuffer buffer = reader.read(getSocketChannel(), oldBuffer, 10); + assertNull(buffer); + assertPopulatedBufferContents(oldBuffer, DATA_TO_BE_READ); + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/impl/transport/TransportTestBase.java b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/TransportTestBase.java new file mode 100644 index 000000000..7b5c528cf --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/impl/transport/TransportTestBase.java @@ -0,0 +1,585 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.transport; + +import com.sun.corba.ee.impl.encoding.CDRInputObject; +import com.sun.corba.ee.impl.orb.ORBVersionImpl; +import com.sun.corba.ee.impl.orb.ObjectKeyCacheEntryImpl; +import com.sun.corba.ee.spi.ior.IOR; +import com.sun.corba.ee.spi.ior.ObjectKey; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBData; +import com.sun.corba.ee.spi.orb.ORBVersion; +import com.sun.corba.ee.spi.orb.ObjectKeyCacheEntry; +import com.sun.corba.ee.spi.protocol.MessageMediator; +import com.sun.corba.ee.spi.protocol.ServerRequestDispatcher; +import com.sun.corba.ee.spi.threadpool.NoSuchThreadPoolException; +import com.sun.corba.ee.spi.threadpool.NoSuchWorkQueueException; +import com.sun.corba.ee.spi.threadpool.ThreadPool; +import com.sun.corba.ee.spi.threadpool.ThreadPoolManager; +import com.sun.corba.ee.spi.threadpool.Work; +import com.sun.corba.ee.spi.threadpool.WorkQueue; +import com.sun.corba.ee.spi.transport.Connection; +import com.sun.corba.ee.spi.transport.EventHandler; +import com.sun.corba.ee.spi.transport.InboundConnectionCache; +import com.sun.corba.ee.spi.transport.MessageTraceManager; +import com.sun.corba.ee.spi.transport.Selector; +import com.sun.corba.ee.spi.transport.TcpTimeouts; +import com.sun.corba.ee.spi.transport.TransportManager; +import org.junit.Before; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.AbstractSelectionKey; +import java.nio.channels.spi.AbstractSelector; +import java.nio.channels.spi.SelectorProvider; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Queue; +import java.util.Set; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static com.meterware.simplestub.Stub.createStub; + +public class TransportTestBase { + private OrbFake orb = createStrictStub(OrbFake.class); + private ORBDataFake orbData = createStrictStub(ORBDataFake.class); + private SelectorProviderFake selectorProvider = createStrictStub(SelectorProviderFake.class); + private SocketChannelFake socketChannel = createStrictStub(SocketChannelFake.class, selectorProvider); + private ConnectionCacheFake connectionCache = createStrictStub(ConnectionCacheFake.class); + private WorkQueueFake workQueue = createStrictStub(WorkQueueFake.class); + private AcceptorFake acceptor; + private ConnectionImpl connection; + private SocketFake socket = new SocketFake(); + private List mediators = new ArrayList(); + private TcpTimeoutsFake tcpTimeouts = createStrictStub(TcpTimeoutsFake.class); + private WaiterFake waiter = createStrictStub(WaiterFake.class); + private TransportManagerFake transportManager = createStrictStub(TransportManagerFake.class); + private TransportSelectorFake selector = createStrictStub(TransportSelectorFake.class); + private ThreadPoolManagerFake threadPoolManager = createStrictStub(ThreadPoolManagerFake.class); + private ThreadPoolFake threadPool = createStrictStub(ThreadPoolFake.class); + + final protected ORB getOrb() { + return orb; + } + + protected void defineRequestDispatcher(RequestDispatcher requestDispatcher) { + ObjectKeyFake.requestDispatcher = requestDispatcher; + } + + protected void processQueuedWork() { + while (!workQueue.items.isEmpty()) { + workQueue.items.remove().doWork(); + } + } + + protected int getNumConnectionsRemoved() { + return connectionCache.numRemoveCalls; + } + + class BackgroundProcessor extends Thread { + int numToProcess; + + BackgroundProcessor(int numToProcess) { + this.numToProcess = numToProcess; + start(); + + } + + protected void waitUntilDone() throws InterruptedException { + join(200); + } + + @Override + public void run() { + while (numToProcess > 0) { + if (workQueue.items.isEmpty()) + Thread.yield(); + else { + numToProcess--; + Work work = workQueue.items.remove(); + work.doWork(); + } + } + + } + } + + @Before + public void setUp() throws IOException { + orb.data = orbData; + orbData.transportTcpTimeouts = tcpTimeouts; + orb.transportManager = transportManager; + orb.threadPoolManager = threadPoolManager; + threadPoolManager.threadPool = threadPool; + threadPool.workQueue = workQueue; + transportManager.selector = selector; + selector.workQueue = workQueue; + tcpTimeouts.waiter = waiter; + socketChannel.socket = socket; + acceptor = createStub(AcceptorFake.class, orb, 0, "name", "type"); + } + + protected void readFromNio(byte[] data) throws IOException { + useNio(); + socketChannel.enqueData(data); + } + + protected void useNio() throws IOException { + orbData.useSelectThread = true; + connection = new ConnectionImpl(orb, acceptor, socket); + connection.setConnectionCache(connectionCache); + } + + protected void collectMediatorsAsDispatched() { + connection.dispatcher = new ConnectionImpl.Dispatcher() { + @Override + public boolean dispatch(MessageMediator messageMediator) { + mediators.add( messageMediator ); + return false; + } + }; + } + + protected void readFromSocketWithoutChannelAndDispatch(byte[] bytes) { + socketChannel = null; + orbData.useSelectThread = false; + socket.inputStream = new ByteArrayInputStream( bytes ); + connection = new ConnectionImpl(orb, acceptor, socket); + connection.setConnectionCache(connectionCache); + } + + protected SocketChannelFake getSocketChannel() { + return socketChannel; + } + + protected Queue getWorkQueue() { + return workQueue.items; + } + + public ConnectionImpl getConnection() { + return connection; + } + + protected List getMediators() { + return mediators; + } + + static abstract class ORBDataFake implements ORBData { + private TcpTimeouts transportTcpTimeouts; + private boolean useSelectThread = true; + + @Override + public TcpTimeouts getTransportTcpTimeouts() { + return transportTcpTimeouts; + } + + @Override + public boolean disableDirectByteBufferUse() { + return true; + } + + @Override + public int getReadByteBufferSize() { + return 100; + } + + @Override + public GIOPVersion getGIOPVersion() { + return GIOPVersion.V1_2; + } + + @Override + public boolean nonBlockingReadCheckMessageParser() { + return true; + } + + @Override + public boolean alwaysEnterBlockingRead() { + return false; + } + + @Override + public boolean connectionSocketUseSelectThreadToWait() { + return useSelectThread; + } + + @Override + public boolean connectionSocketUseWorkerThreadForEvent() { + return true; + } + + @Override + public String getORBServerHost() { + return "localhost"; + } + + @Override + public short getGIOPTargetAddressPreference() { + return 3; // allow all types + } + + @Override + public int fragmentReadTimeout() { + return 1000; + } + + @Override + public int getMaxReadByteBufferSizeThreshold() { + return 500; + } + } + + static abstract class OrbFake extends ORB { + + private ORBDataFake data; + private TransportManagerFake transportManager; + private ThreadPoolManager threadPoolManager; + + @Override + public ORBData getORBData() { + return data; + } + + @Override + public TransportManager getTransportManager() { + return transportManager; + } + + @Override + public ThreadPoolManager getThreadPoolManager() { + return threadPoolManager; + } + + @Override + public ORBVersion getORBVersion() { + return ORBVersionImpl.PEORB; + } + + @Override + public boolean orbIsShutdown() { + return false; + } + + @Override + public ObjectKeyCacheEntry extractObjectKeyCacheEntry(byte[] objKey) { + return new ObjectKeyCacheEntryImpl(createStub(ObjectKeyFake.class)); + } + + @Override + public void startingDispatch() { + } + + @Override + public void finishedDispatch() { + } + } + + static abstract class ObjectKeyFake implements ObjectKey { + private static RequestDispatcher requestDispatcher; + + @Override + public ServerRequestDispatcher getServerRequestDispatcher() { + return requestDispatcher; + } + } + + static abstract class SelectorFake extends AbstractSelector { + private Set selectedKeys = new HashSet(); + + public SelectorFake(SelectorProvider provider) { + super(provider); + } + + @Override + public int selectNow() throws IOException { + return 0; + } + + @Override + protected SelectionKey register(AbstractSelectableChannel ch, int ops, Object att) { + SelectionKeyFake selectionKey = createStrictStub(SelectionKeyFake.class, this); + selectedKeys.add(selectionKey); + return selectionKey; + } + + @Override + public int select(long timeout) throws IOException { + return 1; + } + + @Override + public Set selectedKeys() { + return selectedKeys; + } + + @Override + protected void implCloseSelector() throws IOException { + } + } + + static abstract class SelectorProviderFake extends SelectorProvider { + @Override + public AbstractSelector openSelector() throws IOException { + return createStrictStub(SelectorFake.class, this); + } + } + + static abstract class SocketChannelFake extends SocketChannel { + private byte[] dataWritten = new byte[0]; + private byte[] readableData; + private int readPos; + private ArrayList numBytesToWrite = new ArrayList(); + private ArrayList numBytesToRead = new ArrayList(); + private Socket socket; + private boolean failConfigureBlocking; + private boolean endOfInput; + + protected void setFailToConfigureBlocking() { + failConfigureBlocking = true; + } + + private int getNumBytesToWrite() { + return numBytesToWrite.isEmpty() ? Integer.MAX_VALUE : numBytesToWrite.remove(0); + } + + private int getNumBytesToRead() { + return numBytesToRead.isEmpty() ? Integer.MAX_VALUE : numBytesToRead.remove(0); + } + + protected void setNumBytesToWrite(int... numBytesToWrite) { + for (int i : numBytesToWrite) + this.numBytesToWrite.add(i); + } + + public void setNumBytesToRead(int... numBytesToRead) { + for (int i : numBytesToRead) + this.numBytesToRead.add(i); + } + + protected void enqueData(byte... dataToBeRead) { + readableData = new byte[dataToBeRead.length]; + System.arraycopy(dataToBeRead, 0, readableData, 0, dataToBeRead.length); + } + + protected SocketChannelFake(SelectorProvider provider) { + super(provider); + } + + @Override + public Socket socket() { + return socket; + } + + @Override + public int write(ByteBuffer src) throws IOException { + int numBytesAvailable = src.limit() - src.position(); + int numToWrite = Math.min(numBytesAvailable, getNumBytesToWrite()); + byte[] bytesToWrite = new byte[numToWrite]; + src.get(bytesToWrite); + byte[] written = new byte[dataWritten.length + numToWrite]; + System.arraycopy(dataWritten, 0, written, 0, dataWritten.length); + System.arraycopy(bytesToWrite, 0, written, dataWritten.length, written.length); + dataWritten = written; + return numToWrite; + } + + @Override + protected void implConfigureBlocking(boolean block) throws IOException { + if (failConfigureBlocking) + throw new IOException("Test failure to configure blocking"); + } + + @Override + public int read(ByteBuffer dst) throws IOException { + if (endOfInput) return -1; + int numBytesToRead = Math.min(getNumBytesToRead(), Math.min(dataSize(), bufferCapacity(dst))); + if (numBytesToRead == 0) return 0; + + dst.put(readableData, readPos, numBytesToRead); + readPos += numBytesToRead; + return numBytesToRead; + } + + private int bufferCapacity(ByteBuffer dst) { + return dst.limit() - dst.position(); + } + + private int dataSize() { + return this.readableData == null ? 0 : this.readableData.length - readPos; + } + + protected byte[] getDataWritten() { + return dataWritten; + } + + + public void setEndOfInput() { + endOfInput = true; + } + } + + static abstract class TcpTimeoutsFake implements TcpTimeouts { + private Waiter waiter; + + @Override + public Waiter waiter() { + return waiter; + } + } + + static abstract class ConnectionCacheFake implements InboundConnectionCache { + private int numRemoveCalls; + + @Override + public void stampTime(Connection connection) { + } + + @Override + public void remove(Connection connection) { + numRemoveCalls++; + } + } + + static abstract class WaiterFake implements TcpTimeouts.Waiter { + @Override + public boolean isExpired() { + return false; + } + + @Override + public int getTimeForSleep() { + return 1; + } + + @Override + public void advance() { + } + } + + static abstract class SelectionKeyFake extends AbstractSelectionKey { + private SelectorFake selector; + + protected SelectionKeyFake(SelectorFake selector) { + this.selector = selector; + } + + public SelectorFake selector() { + return selector; + } + } + + static abstract class WorkQueueFake implements WorkQueue { + private Queue items = new ArrayDeque(); + + @Override + public void addWork(Work aWorkItem) { + items.offer(aWorkItem); + } + } + + static abstract class TransportManagerFake implements TransportManager { + private MessageTraceManager mtm = new MessageTraceManagerImpl(); + public TransportSelectorFake selector; + + @Override + public MessageTraceManager getMessageTraceManager() { + return mtm; + } + + @Override + public Selector getSelector(int i) { + return selector; + } + } + + static abstract class TransportSelectorFake implements Selector { + public WorkQueueFake workQueue; + + @Override + public void unregisterForEvent(EventHandler eventHandler) { + } + + @Override + public void registerForEvent(EventHandler eventHandler) { + if (eventHandler instanceof Work) + workQueue.addWork((Work) eventHandler); + } + + @Override + public void registerInterestOps(EventHandler eventHandler) { + } + } + + static abstract class ThreadPoolManagerFake implements ThreadPoolManager { + private ThreadPool threadPool; + + @Override + public ThreadPool getThreadPool(int numericIdForThreadpool) throws NoSuchThreadPoolException { + return threadPool; + } + } + + static abstract class ThreadPoolFake implements ThreadPool { + private WorkQueue workQueue; + + @Override + public WorkQueue getWorkQueue(int queueId) throws NoSuchWorkQueueException { + return workQueue; + } + } + + static abstract class AcceptorFake extends AcceptorBase { + protected AcceptorFake(ORB orb, int port, String name, String type) { + super(orb, port, name, type); + } + } + + private class SocketFake extends Socket { + private InputStream inputStream = null; + private OutputStream outputStream = null; + + public SocketChannel getChannel() { + return socketChannel; + } + public InputStream getInputStream() throws IOException { + return inputStream; + } + public OutputStream getOutputStream() throws IOException { + return outputStream; + } + } + + protected class RequestDispatcher implements ServerRequestDispatcher { + @Override + public IOR locate(ObjectKey key) { + return null; + } + + @Override + public void dispatch(MessageMediator messageMediator) { + mediators.add(messageMediator); + readParameters(messageMediator.getInputObject()); + } + + public void readParameters( CDRInputObject input ) {} + } +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/spi/ior/iiop/IIOPFactoriesTest.java b/orbmain/src/test/java/com/sun/corba/ee/spi/ior/iiop/IIOPFactoriesTest.java new file mode 100644 index 000000000..f2e652143 --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/spi/ior/iiop/IIOPFactoriesTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.ior.iiop; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBData; +import org.junit.Test; +import org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS; + +import static com.meterware.simplestub.Stub.createStrictStub; +import static com.meterware.simplestub.Stub.createStub; +import static org.junit.Assert.assertEquals; + +public class IIOPFactoriesTest { + + @Test + public void canCreateAlternateIIOPAddressComponent() { + IIOPAddress addr = IIOPFactories.makeIIOPAddress("localhost", 2345); + AlternateIIOPAddressComponent comp = IIOPFactories.makeAlternateIIOPAddressComponent(addr); + org.omg.IOP.TaggedComponent tcomp = comp.getIOPComponent(createStub(ORBFake.class)); + assertEquals(tcomp.tag, TAG_ALTERNATE_IIOP_ADDRESS.value); + } + + abstract static public class ORBDataFake implements ORBData { + @Override + public int getGIOPBufferSize() { + return 100; + } + } + + abstract static public class ORBFake extends ORB { + + private ORBData data = createStrictStub(ORBDataFake.class); + + @Override + public ORBData getORBData() { + return data; + } + } + +} diff --git a/orbmain/src/test/java/com/sun/corba/ee/spi/presentation/rmi/PresentationDefaultsTest.java b/orbmain/src/test/java/com/sun/corba/ee/spi/presentation/rmi/PresentationDefaultsTest.java new file mode 100644 index 000000000..d148c587f --- /dev/null +++ b/orbmain/src/test/java/com/sun/corba/ee/spi/presentation/rmi/PresentationDefaultsTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.spi.presentation.rmi; + +import com.meterware.simplestub.Memento; +import com.meterware.simplestub.SystemPropertySupport; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +public class PresentationDefaultsTest { + + private List mementos = new ArrayList<>(); + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + for (Memento memento : mementos) memento.revert(); + } + + @Test + public void dynamicStubFactory_createsDynamicStubs() throws Exception { + assertThat(PresentationDefaults.getDynamicStubFactoryFactory().createsDynamicStubs(), is(true)); + } + + @Test + public void staticStubFactory_doesNotCreateDynamicStubs() throws Exception { + assertThat(PresentationDefaults.getStaticStubFactoryFactory().createsDynamicStubs(), is(false)); + } + + @Test + public void defaultOrbPresentationManager_createsDynamicStubs() throws Exception { + assertThat(PresentationDefaults.makeOrbPresentationManager().useDynamicStubs(), is(true)); + } + + @Test + public void whenSystemPropertyFalse_presentationManagerCreatesStaticStubs() throws Exception { + mementos.add(SystemPropertySupport.install(ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "false")); + + assertThat(PresentationDefaults.makeOrbPresentationManager().useDynamicStubs(), is(false)); + } +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ContainerClash1.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ContainerClash1.java new file mode 100644 index 000000000..41772a9b5 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ContainerClash1.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public interface ContainerClash1 extends java.rmi.Remote { + + void ContainerClash1() throws java.rmi.RemoteException; + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ContainerClash2.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ContainerClash2.java new file mode 100644 index 000000000..4de8212f5 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ContainerClash2.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public interface ContainerClash2 extends java.rmi.Remote { + + void ContainerCLASH2() throws java.rmi.RemoteException; + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/Default.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/Default.java new file mode 100644 index 000000000..f8431db44 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/Default.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Class defined in default package that also clashes with IDL keyword. + */ +public class Default { + + public class Inner {} + + public class _Inner {} + + public class _Default {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLCaseSensitivityTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLCaseSensitivityTest.java new file mode 100644 index 000000000..35b1da137 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLCaseSensitivityTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLCaseSensitivityTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + public static final String[] IDL_NAMES = { + "ABCDEFGHIJKLmNOPQRSTUVWXYzA_0_1_2_3_4_5_6_7_8_9_10_11_13_14_15_16_17_18_19_20_21_22_23_24_26", + "B_0", + "JACK_0_1_2_3", + "JACKY", + "Jack_0", + "a", + "abcdefghijklMnopqrstuvwxyza_12", + "abcdefghijklmnopqrstuvwxyzA_26", + "b_", + "b__", + "jAcK_1_3", + "jack_" + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLCaseSensitivity extends java.rmi.Remote { + String ABCDEFGHIJKLmNOPQRSTUVWXYzA(int a) + throws java.rmi.RemoteException; + + void B() throws java.rmi.RemoteException; + + boolean JACK() throws java.rmi.RemoteException; + void JACKY() throws java.rmi.RemoteException; + void Jack() throws java.rmi.RemoteException; + + void a() throws java.rmi.RemoteException; + + void abcdefghijklMnopqrstuvwxyza() throws java.rmi.RemoteException; + void abcdefghijklmnopqrstuvwxyzA() throws java.rmi.RemoteException; + + void b() throws java.rmi.RemoteException; + + void b__() throws java.rmi.RemoteException; + + + int jAcK() throws java.rmi.RemoteException; + void jack() throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLComboTest1.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLComboTest1.java new file mode 100644 index 000000000..461c183cc --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLComboTest1.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLComboTest1 { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + static final String[] IDL_NAMES = { + + "ABCDEF_0_1_2_3_4_5", + "CCDcxU04E3U05E90123_0_1_2", + "CCdCxU04E3U05E90123_0_1_3", + "ONEWay_0_1_2_3", + + "PLANT__corba_dynamicrmiiiop_testclasses_Raises", + "PLANT__corba_dynamicrmiiiop_testclasses_Raises__Union", + // "PLANT__corba_dynamicrmiiiop_testclasses_Raises__UniU8001code", + "PLANT__corba_dynamicrmiiiop_testclasses_Raises___Foo", + "PLANT__corba_dynamicrmiiiop_testclasses_Raises___Union", + + "QQQQQ__", + "QQQQQ__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Raises__long", + "RRRRR__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Raises__Union", + "RRRRR__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Raises__Union__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Raises___Foo__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Raises___Union", + + "SSSSS__corba_dynamicrmiiiop_testclasses_J_Raises", + "SSSSS__corba_dynamicrmiiiop_testclasses_J_Raises__Union", + "SSSSS__corba_dynamicrmiiiop_testclasses_J_Raises___Foo", + "SSSSS__corba_dynamicrmiiiop_testclasses_J_Raises___Union", + + "SSSTT__corba_dynamicrmiiiop_testclasses_J_upackage_Foo", + // "SSSTT__corba_dynamicrmiiiop_testclasses_dolU0024lar_Foo", + "SSSTT__corba_dynamicrmiiiop_testclasses_typedef_Foo", + + "TTTTT__", + "TTTTT__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Raises__long", + + + "TTTUU__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_J_upackage_seq1_Foo", + // "TTTUU__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_dolU0024lar_seq1_Foo", + "TTTUU__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_typedef_seq1_Foo", + + "UUUUU__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Raises__Union", + + "UUUUU__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Raises__Union__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Raises___Foo__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Raises___Union", + + "J_BU8001U0024", + "J_CCMcxU04E3U05E90123_1_2_3", + "J_CCmCxU04E3U05E90123_1_2_4", + "abcdef___", + "abcdef___long", + "_get_octet", + "_get_ZWepT_0_1_4", + "onewAy_4", + "_set_octet", + "zWePt_1_3" + + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + /** + * RMI Interface with a set of methods that involve multiple mangling + * rules from the Java2IDL spec. + */ + public interface IDLCombo extends java.rmi.Remote { + + // Differs in case with a() + void ABCDEF() throws java.rmi.RemoteException; + + // methods that Differ in case and have illegal IDL chars + void CCDcx\u04e3\u05E90123() throws java.rmi.RemoteException; + void CCdCx\u04e3\u05E90123() throws java.rmi.RemoteException; + + // Clashes with IDL keyword and differs only in case with onewAy + void ONEWay() throws java.rmi.RemoteException; + + // class name that clashes with idl keyword + overloading + void PLANT(Raises r) throws java.rmi.RemoteException; + + // inner class name that clashes with idl keyword, whose enclosing + // class also clashes with idl keyword + overloading + void PLANT(Raises.Union r) throws java.rmi.RemoteException; + + // inner class with unicode chars that need to be mangled + // void PLANT(Raises.Uni\u8001code f) throws java.rmi.RemoteException; + + // inner class beginning with underscore, whose enclosing class + // clashes with idl keyword + overloading + void PLANT(Raises._Foo r) throws java.rmi.RemoteException; + + // inner class beginning with underscore, where the remainder is + // an IDL keyword, whose enclosing class clashes with idl keyword + // + overloading + void PLANT(Raises._Union r) throws java.rmi.RemoteException; + + // overloading + class names that clash with keywords + void QQQQQ() throws java.rmi.RemoteException; + void QQQQQ(Raises[] r, int q) throws java.rmi.RemoteException; + + void RRRRR(Raises.Union[] r) throws java.rmi.RemoteException; + void RRRRR(Raises.Union[] r, Raises._Foo[] s, Raises._Union[] t) throws java.rmi.RemoteException; + + // class name that starts with underscore, where remainder + // clashes with idl keyword + void SSSSS(_Raises r) throws java.rmi.RemoteException; + + // inner class that clashes with idl keyword, whose enclosing class + // is underscore + keyword + void SSSSS(_Raises.Union r) throws java.rmi.RemoteException; + + void SSSSS(_Raises._Foo r) throws java.rmi.RemoteException; + void SSSSS(_Raises._Union r) throws java.rmi.RemoteException; + + + // intermeidate package starting with an underscore + void SSSTT(corba.dynamicrmiiiop.testclasses._upackage.Foo r) + throws java.rmi.RemoteException; + + // subpackage name with illegal idl char + // void SSSTT(corba.dynamicrmiiiop.testclasses.dol$lar.Foo r) + // throws java.rmi.RemoteException; + + // intermediate package name(typedef) that clashes with idl keyword + void SSSTT(corba.dynamicrmiiiop.testclasses.typedef.Foo r) + throws java.rmi.RemoteException; + + void TTTTT() throws java.rmi.RemoteException; + void TTTTT(_Raises[] r, int q) throws java.rmi.RemoteException; + + // intermediate package starting with an underscore + void TTTUU(corba.dynamicrmiiiop.testclasses._upackage.Foo[] f) throws java.rmi.RemoteException; + + // subpackage name with illegal idl char + // void TTTUU(corba.dynamicrmiiiop.testclasses.dol$lar.Foo[] r) + // throws java.rmi.RemoteException; + + // intermediate package name(typedef) that clashes with idl keyword + void TTTUU(corba.dynamicrmiiiop.testclasses.typedef.Foo[] f) throws java.rmi.RemoteException; + + void UUUUU(_Raises.Union[] r) throws java.rmi.RemoteException; + void UUUUU(_Raises.Union[] r, _Raises._Foo[] s, _Raises._Union[] t) throws java.rmi.RemoteException; + + // Combo of leading underscore + illegal IDL chars + void _B\u8001$() throws java.rmi.RemoteException; + + // methods that Differ in case and have illegal IDL chars and + // start with underscore + void _CCMcx\u04e3\u05E90123() throws java.rmi.RemoteException; + void _CCmCx\u04e3\u05E90123() throws java.rmi.RemoteException; + + // Differs in case with ABCDEF() and is also overloaded + void abcdef() throws java.rmi.RemoteException; + void abcdef(int a) throws java.rmi.RemoteException; + + // property with attribute name that is the same as an IDL keyword. + // rmic does not mangle these. + int getOctet() throws java.rmi.RemoteException; + + // property that differs only in case with a method name + int getZWepT() throws java.rmi.RemoteException; + + // Clashes with IDL keyword and differs only in case with ONEWay + void onewAy() throws java.rmi.RemoteException; + + // property with attribute name that is the same as an IDL keyword. + // rmic does not mangle these. + void setOctet(int i) throws java.rmi.RemoteException; + + // method that differs only in case with a attribute name + void zWePt() throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLDefaultTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLDefaultTest.java new file mode 100644 index 000000000..a9a6472e6 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLDefaultTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLDefaultTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + static final String[] IDL_NAMES = { + + "AAA__corba_dynamicrmiiiop_testclasses_Default", + "AAA__corba_dynamicrmiiiop_testclasses_J_Default", + "BBB__corba_dynamicrmiiiop_testclasses_Default__corba_dynamicrmiiiop_testclasses_Default__Inner__corba_dynamicrmiiiop_testclasses_Default___Inner__corba_dynamicrmiiiop_testclasses_Default___Default", + "BBB__corba_dynamicrmiiiop_testclasses_J_Default__corba_dynamicrmiiiop_testclasses_J_Default__Inner__corba_dynamicrmiiiop_testclasses_J_Default___Inner__corba_dynamicrmiiiop_testclasses_J_Default__Default", + "CCC__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Default", + "CCC__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Default", + + "DDD__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Default__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Default__Inner__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Default___Inner__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_Default___Default", + "DDD__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Default__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Default__Inner__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Default___Inner__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_J_Default__Default" + + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLDefault extends java.rmi.Remote { + + void AAA(Default d) throws java.rmi.RemoteException; + void AAA(_Default d) throws java.rmi.RemoteException; + + void BBB(Default d, Default.Inner e, Default._Inner f, + Default._Default g) throws java.rmi.RemoteException; + void BBB(_Default d, _Default.Inner e, _Default._Inner f, + _Default.Default g) throws java.rmi.RemoteException; + + + void CCC(Default[] d) throws java.rmi.RemoteException; + void CCC(_Default[] d) throws java.rmi.RemoteException; + + void DDD(Default[] d, Default.Inner[] e, Default._Inner[] f, + Default._Default[] g) throws java.rmi.RemoteException; + void DDD(_Default[] d, _Default.Inner[] e, _Default._Inner[] f, + _Default.Default[] g) throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLIdentifiersTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLIdentifiersTest.java new file mode 100644 index 000000000..f38d04f74 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLIdentifiersTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLIdentifiersTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + static final String[] IDL_NAMES = { + + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0", + "aU0024U0024U0024U0024", + "a0123456789", + "a_", + "a_0", + "abcdefghijklmnopqrstuvwxyz", + + "\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C6\u00C7\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D0\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D8\u00D9\u00DA\u00DB\u00DC\u00DD\u00DE\u00DF", + "\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5\u00E6\u00E7\u00E8\u00E9\u00EA\u00EB\u00EC\u00ED\u00EE\u00EF\u00F0\u00F1\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8\u00F9\u00FA\u00FB\u00FC\u00FD\u00FE\u00FF", + + "U0100U0101U0170\u00FF\u00FEU0024", + "U0393U0394U0398U03B6", + "U0393U0394U0398U03B6_abc", + "U04E3U04F3U04D5U04E6", + "U05E9U05EAU05F0U05E5U05DE", + "U13E0U13F0U13F2U13F4", + "U50AFU50BFU50EF______", + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLIdentifiers extends java.rmi.Remote { + + void ABCDEFGHIJKLMNOPQRSTUVWXYZ0() throws java.rmi.RemoteException; + + void a$$$$() throws java.rmi.RemoteException; + void a0123456789() throws java.rmi.RemoteException; + void a_() throws java.rmi.RemoteException; + void a_0() throws java.rmi.RemoteException; + void abcdefghijklmnopqrstuvwxyz() throws java.rmi.RemoteException; + + // note : no 00D7 (x) + void \u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C6\u00C7\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D0\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D8\u00D9\u00DA\u00DB\u00DC\u00DD\u00DE\u00DF() throws java.rmi.RemoteException; + + // note : no 00F7 (/) + void \u00E0\u00E1\u00E2\u00E3\u00E4\u00E5\u00E6\u00E7\u00E8\u00E9\u00EA\u00EB\u00EC\u00ED\u00EE\u00EF\u00F0\u00F1\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8\u00F9\u00FA\u00FB\u00FC\u00FD\u00FE\u00FF() throws java.rmi.RemoteException; + + // latin extended-A, right outside the IDL range + void \u0100\u0101\u0170\u00FF\u00FE\u0024() throws java.rmi.RemoteException; + + // some greek letters + void \u0393\u0394\u0398\u03B6() throws java.rmi.RemoteException; + void \u0393\u0394\u0398\u03B6_abc() throws java.rmi.RemoteException; + + // some Cyrillic letters + void \u04e3\u04f3\u04D5\u04E6() throws java.rmi.RemoteException; + + // some hebrew letters + void \u05E9\u05EA\u05f0\u05E5\u05DE() throws java.rmi.RemoteException; + + // some Cherokee letters + void \u13E0\u13F0\u13f2\u13F4() throws java.rmi.RemoteException; + + // some CJK Unified Ideographs + void \u50AF\u50bF\u50Ef______() throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLKeywordsTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLKeywordsTest.java new file mode 100644 index 000000000..5c9e97829 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLKeywordsTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLKeywordsTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + // List doesn't contain the following + // IDL Keywords : boolean, case, char, const, default, double, float, + // interface, long, Object, short, switch, void, num + // since they are also Java keywords + // + static final String[] IDL_NAMES = { + "_Any", "_EXCEPTION", "_RaiseS", "_TRUE", "_attribute", "_context", + "_falsE", "_in", "_inout", "_module", "_octet", + "_oneway", "_out", "_readonly", "_sequence", + "_string", "_struct", "_typedef", "_union", "_unsigNED" + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLKeywords extends java.rmi.Remote { + + // Comparison to IDL keywords is case-insensitive. + + void Any() throws java.rmi.RemoteException; + void EXCEPTION() throws java.rmi.RemoteException; + void RaiseS() throws java.rmi.RemoteException; + void TRUE() throws java.rmi.RemoteException; + + void attribute() throws java.rmi.RemoteException; + void context() throws java.rmi.RemoteException; + void falsE() throws java.rmi.RemoteException; + + void in() throws java.rmi.RemoteException; + void inout() throws java.rmi.RemoteException; + void module() throws java.rmi.RemoteException; + void octet() throws java.rmi.RemoteException; + void oneway() throws java.rmi.RemoteException; + void out() throws java.rmi.RemoteException; + + void readonly() throws java.rmi.RemoteException; + void sequence() throws java.rmi.RemoteException; + void string() throws java.rmi.RemoteException; + void struct() throws java.rmi.RemoteException; + void typedef() throws java.rmi.RemoteException; + void union() throws java.rmi.RemoteException; + void unsigNED() throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLLeadingUnderscoresTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLLeadingUnderscoresTest.java new file mode 100644 index 000000000..89f6e0d7d --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLLeadingUnderscoresTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLLeadingUnderscoresTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + static final String[] IDL_NAMES = { + + "J_", + "J_0", + "J_J_", + "J__", + "J______________________________Z", + "J__a", + "J_a", + "J_jj" + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLLeadingUnderscores extends java.rmi.Remote { + + void _() throws java.rmi.RemoteException; + + void _0() throws java.rmi.RemoteException; + + void _J_() throws java.rmi.RemoteException; + + void __() throws java.rmi.RemoteException; + + void ______________________________Z() throws java.rmi.RemoteException; + + void __a() throws java.rmi.RemoteException; + + void _a() throws java.rmi.RemoteException; + + void _jj() throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLMultipleInterfaceTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLMultipleInterfaceTest.java new file mode 100644 index 000000000..11bb71d04 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLMultipleInterfaceTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +import java.rmi.RemoteException ; + +public class IDLMultipleInterfaceTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + public static final String[] IDL_NAMES = { + "A1", + "CB", + "CC", + "CD" + } ; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface first extends java.rmi.Remote { + void A1() throws RemoteException ; + void CC( int a ) throws RemoteException ; + } + + public interface second extends java.rmi.Remote { + void CB( int a ) throws RemoteException ; + void CD( int a ) throws RemoteException ; + } +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLOverloadedTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLOverloadedTest.java new file mode 100644 index 000000000..4727c116f --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLOverloadedTest.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLOverloadedTest { + + public class Inner\u0300 { + + public class Extra\u0301Inner {} + } + + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + public static final String[] IDL_NAMES = { + + "A__", + "A__org_omg_boxedRMI_seq1_octet", + "A__org_omg_boxedRMI_seq1_wchar", + "A__org_omg_boxedRMI_seq1_double", + "A__org_omg_boxedRMI_seq1_float", + "A__org_omg_boxedRMI_seq1_long", + "A__org_omg_boxedRMI_seq1_long_long", + + "A__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_IDLOverloadedTest__InnerU0300__ExtraU0301Inner", + "A__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq1_IDLOverloadedTest__InnerU0300", + + "A__org_omg_boxedRMI_java_io_seq1_Externalizable", + "A__org_omg_boxedRMI_java_io_seq1_Serializable", + "A__org_omg_boxedRMI_java_lang_seq1_Boolean", + "A__org_omg_boxedRMI_java_lang_seq1_Byte", + "A__org_omg_boxedRMI_java_lang_seq1_Character", + "A__org_omg_boxedRMI_javax_rmi_CORBA_seq1_ClassDesc", + "A__org_omg_boxedRMI_java_lang_seq1_Double", + "A__org_omg_boxedRMI_java_lang_seq1_Float", + "A__org_omg_boxedRMI_java_lang_seq1_Integer", + "A__org_omg_boxedRMI_java_lang_seq1_Long", + "A__org_omg_boxedRMI_java_lang_seq1_Object", + + "A__org_omg_boxedRMI_java_lang_seq1_Short", + "A__org_omg_boxedRMI_CORBA_seq1_WStringValue", + "A__org_omg_boxedRMI_java_rmi_seq1_Remote", + "A__org_omg_boxedRMI_javax_swing_seq1_UIDefaults__ActiveValue", + "A__org_omg_boxedRMI_seq1_Object", + + "A__org_omg_boxedRMI_seq1_short", + "A__org_omg_boxedRMI_seq1_boolean", + "A__org_omg_boxedRMI_seq2_boolean", + "A__org_omg_boxedRMI_corba_dynamicrmiiiop_testclasses_seq4_IDLOverloadedTest__InnerU0300__ExtraU0301Inner__org_omg_boxedRMI_CORBA_seq2_WStringValue__long", + "A__org_omg_boxedRMI_seq16_boolean", + "A__boolean", + "A__octet", + "A__wchar", + "A__corba_dynamicrmiiiop_testclasses_IDLOverloadedTest__InnerU0300", + "A__corba_dynamicrmiiiop_testclasses_IDLOverloadedTest__InnerU0300__ExtraU0301Inner", + "A__org_omg_boxedIDL_corba_dynamicrmiiiop_testclasses_TestStruct", + "A__double", + "A__float", + "A__long", + "A__long__float__double__wchar__octet__boolean__java_io_Serializable__CORBA_WStringValue", + + "A__java_io_Externalizable", + "A__java_io_Serializable", + "A__java_lang_Boolean", + "A__java_lang_Byte", + "A__java_lang_Character", + "A__javax_rmi_CORBA_ClassDesc", + "A__java_lang_Double", + "A__java_lang_Float", + "A__java_lang_Integer", + "A__java_lang_Long", + "A__java_lang_Object", + "A__java_lang_Short", + "A__CORBA_WStringValue", + "A__java_rmi_Remote", + "A__javax_swing_UIDefaults__ActiveValue", + + "A__long_long", + "A__Object", + "A__short" + + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLOverloaded extends java.rmi.Remote { + + void A() throws java.rmi.RemoteException; + + void A(byte[] b) throws java.rmi.RemoteException; + void A(char[] c) throws java.rmi.RemoteException; + void A(double[] d) throws java.rmi.RemoteException; + void A(float[] f) throws java.rmi.RemoteException; + void A(int[] a) throws java.rmi.RemoteException; + void A(long[] a) throws java.rmi.RemoteException; + + void A(corba.dynamicrmiiiop.testclasses.IDLOverloadedTest.Inner\u0300.Extra\u0301Inner[] b) throws java.rmi.RemoteException; + void A(corba.dynamicrmiiiop.testclasses.IDLOverloadedTest.Inner\u0300[] a) + throws java.rmi.RemoteException; + + void A(java.io.Externalizable[] e) throws java.rmi.RemoteException; + void A(java.io.Serializable[] s) throws java.rmi.RemoteException; + void A(java.lang.Boolean[] b) throws java.rmi.RemoteException; + void A(java.lang.Byte[] b) throws java.rmi.RemoteException; + void A(java.lang.Character[] b) throws java.rmi.RemoteException; + void A(java.lang.Class[] c) throws java.rmi.RemoteException; + void A(java.lang.Double[] d) throws java.rmi.RemoteException; + void A(java.lang.Float[] f) throws java.rmi.RemoteException; + void A(java.lang.Integer[] i) throws java.rmi.RemoteException; + void A(java.lang.Long[] l) throws java.rmi.RemoteException; + void A(java.lang.Object[] o) throws java.rmi.RemoteException; + + void A(java.lang.Short[] s) throws java.rmi.RemoteException; + void A(java.lang.String[] s) throws java.rmi.RemoteException; + void A(java.rmi.Remote[] r) throws java.rmi.RemoteException; + + void A(javax.swing.UIDefaults.ActiveValue[] s) throws java.rmi.RemoteException; + void A(org.omg.CORBA.Object[] o) throws java.rmi.RemoteException; + + void A(short[] s) throws java.rmi.RemoteException; + void A(boolean[] b) throws java.rmi.RemoteException; + void A(boolean[][] b) throws java.rmi.RemoteException; + void A(corba.dynamicrmiiiop.testclasses.IDLOverloadedTest.Inner\u0300.Extra\u0301Inner[][][][] a, java.lang.String[][] b, int c) throws java.rmi.RemoteException; + void A(boolean[][][][][][][][][][][][][][][][] b) throws java.rmi.RemoteException; + + void A(boolean z) throws java.rmi.RemoteException; + void A(byte b) throws java.rmi.RemoteException; + void A(char c) throws java.rmi.RemoteException; + void A(corba.dynamicrmiiiop.testclasses.IDLOverloadedTest.Inner\u0300 d) throws java.rmi.RemoteException; + void A(corba.dynamicrmiiiop.testclasses.IDLOverloadedTest.Inner\u0300.Extra\u0301Inner e) throws java.rmi.RemoteException; + void A(double d) throws java.rmi.RemoteException; + void A(float f) throws java.rmi.RemoteException; + void A(int i) throws java.rmi.RemoteException; + void A(int i, float f, double d, char c, byte b, boolean z, + java.io.Serializable s, java.lang.String t) throws java.rmi.RemoteException; + + void A(java.io.Externalizable e) throws java.rmi.RemoteException; + void A(java.io.Serializable s) throws java.rmi.RemoteException; + void A(java.lang.Boolean b) throws java.rmi.RemoteException; + void A(java.lang.Byte b) throws java.rmi.RemoteException; + void A(java.lang.Character b) throws java.rmi.RemoteException; + void A(java.lang.Class c) throws java.rmi.RemoteException; + void A(java.lang.Double d) throws java.rmi.RemoteException; + void A(java.lang.Float f) throws java.rmi.RemoteException; + void A(java.lang.Integer i) throws java.rmi.RemoteException; + void A(java.lang.Long l) throws java.rmi.RemoteException; + void A(java.lang.Object o) throws java.rmi.RemoteException; + void A(java.lang.Short s) throws java.rmi.RemoteException; + void A(java.lang.String s) throws java.rmi.RemoteException; + void A(java.rmi.Remote r) throws java.rmi.RemoteException; + void A(javax.swing.UIDefaults.ActiveValue s) throws java.rmi.RemoteException; + + void A(long j) throws java.rmi.RemoteException; + + void A(org.omg.CORBA.Object o) throws java.rmi.RemoteException; + void A(short s) throws java.rmi.RemoteException; + + void A(TestStruct t) throws java.rmi.RemoteException; + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLPropertiesTest.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLPropertiesTest.java new file mode 100644 index 000000000..13df64b01 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/IDLPropertiesTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class IDLPropertiesTest { + + // + // Set of idl names corresponding to alphabetically sorted set of + // interface methods. See TestIDLNameTranslator for sorting details. + // + static final String[] IDL_NAMES = { + "a", + "get", + "_get_a__", + "_get_ABc", + "_get_b", + "_get_CDE", + "getDAB", + "getDCD", + "getDzzz", + "getEfg", + "_get_zde", + "is", + "isA", + "isBCD", + "_get_c", + "_get_CCCCCe", + "isCZ", + "_get_cf", + "set", + "_set_a__", + "_set_b", + "setCDE", + "setEfg", + "_set_zde" + }; + + public static String[] getIDLNames() { + return IDL_NAMES; + } + + public interface IDLProperties extends java.rmi.Remote { + + // should force a __ to be added to getter attribute + void a() throws java.rmi.RemoteException; + + // not a property since there is no portion + int get() throws java.rmi.RemoteException; + + // valid getter + int getA() throws java.rmi.RemoteException; + + // valid getter + int getABc() throws java.rmi.RemoteException; + + // valid getter + int getB() throws java.rmi.RemoteException; + + // getter + int getCDE() throws java.rmi.RemoteException; + + // not a getter. can't have void return type. + void getDAB() throws java.rmi.RemoteException; + + // not a getter. can't have void return type. + void getDCD(int a) throws java.rmi.RemoteException; + + // not a getter. can't have any parameters. + int getDzzz(int a) throws java.rmi.RemoteException; + + // valid getter + boolean getZde() throws java.rmi.RemoteException; + + // not a getter. throws at least one checked exception in addition to + // java.rmi.RemoteException(or one of its subclasses) + int getEfg() throws java.rmi.RemoteException, java.lang.Exception; + + // not a property since there is no portion + boolean is() throws java.rmi.RemoteException; + + // not a property since "is" only applies to boolean + int isA() throws java.rmi.RemoteException; + + // not valid. must be boolean primitive + Boolean isBCD() throws java.rmi.RemoteException; + + // valid boolean property + boolean isC() throws java.rmi.RemoteException; + + // valid boolean property + boolean isCCCCCe() throws java.rmi.RemoteException; + + // not boolean property. must have 0 args + boolean isCZ(int a) throws java.rmi.RemoteException; + + // valid boolean property + boolean isCf() throws java.rmi.RemoteException; + + // not a property since there is no portion + int set() throws java.rmi.RemoteException; + + void setA(int c) throws java.rmi.RemoteException; + + // valid setter + void setB(int b) throws java.rmi.RemoteException; + + // not a setter. no corresponding getter with correct type. + void setCDE(Integer i) throws java.rmi.RemoteException; + + // not a setter. no corresponding getter. + void setEfg(int a) throws java.rmi.RemoteException; + + // valid setter + void setZde(boolean a) throws java.rmi.RemoteException; + + } + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidEntities.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidEntities.java new file mode 100644 index 000000000..0dfbd9a33 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidEntities.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Invalid IDL Entity Types + */ +public class InvalidEntities { + + public static final Class[] CLASSES = { + InvalidEntity1.class, + InvalidEntity2.class, + InvalidEntity3.class, + InvalidEntity4.class, + InvalidEntity5.class, + InvalidEntity6.class + }; + + // must be a class that is a subtype of org.omg.CORBA.portable.IDLEntity + public class InvalidEntity1 {} + + // must be a class that is a subtype of org.omg.CORBA.portable.IDLEntity + public class InvalidEntity2 extends InvalidEntity1 {} + + // must be a class + public interface InvalidEntity3 {} + + public interface InvalidEntity4 extends InvalidEntity3 {} + + public interface InvalidEntity5 extends org.omg.CORBA.portable.IDLEntity {} + + public interface InvalidEntity6 extends InvalidEntity5 {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidExceptions.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidExceptions.java new file mode 100644 index 000000000..7f3e66414 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidExceptions.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Invalid RMI/IDL Exception Types + */ +public class InvalidExceptions { + + public static final Class[] CLASSES = { + InvalidException1.class, + InvalidException2.class, + InvalidException3.class, + InvalidException4.class, + InvalidException5.class, + InvalidException6.class, + InvalidException7.class, + InvalidException8.class, + InvalidException9.class, + InvalidException10.class + }; + + // must be a checked exception + public class InvalidException1 {} + + // must be a checked exception + public class InvalidException2 extends InvalidException1 {} + + // must be a checked exception + public class InvalidException3 extends Error {} + + // must be a checked exception + public class InvalidException4 extends InvalidException3 {} + + // must be a checked exception + public class InvalidException5 extends RuntimeException {} + + // must be a checked exception + public class InvalidException6 extends InvalidException5 {} + + // must be a checked exception + public interface InvalidException7 {} + + // must be a checked exception + public interface InvalidException8 extends java.io.Serializable {} + + public class InvalidException9 extends Exception + implements java.rmi.Remote {} + + public class InvalidException10 extends InvalidException9 {} + + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidObjRefs.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidObjRefs.java new file mode 100644 index 000000000..e80578be2 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidObjRefs.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Invalid RMI/IDL CORBA Object Reference Types + */ +public class InvalidObjRefs { + + public static final Class[] CLASSES = { + InvalidObjRef1.class, + InvalidObjRef2.class, + InvalidObjRef3.class, + InvalidObjRef4.class, + InvalidObjRef5.class, + InvalidObjRef6.class, + InvalidObjRef7.class, + InvalidObjRef8.class + }; + + // must be subtype of org.omg.CORBA.Object + public interface InvalidObjRef1 {} + + // must be subtype of org.omg.CORBA.Object + public interface InvalidObjRef2 extends InvalidObjRef1 {} + + // must be subtype of org.omg.CORBA.Object + public class InvalidObjRef3 {} + + // must be subtype of org.omg.CORBA.Object + public class InvalidObjRef4 extends InvalidObjRef3 {} + + // must be an interface + public abstract class InvalidObjRef5 + extends org.omg.CORBA.portable.ObjectImpl {} + + // must be an interface + public abstract class InvalidObjRef6 extends InvalidObjRef5 {} + + // must be an interface + public abstract class InvalidObjRef7 implements org.omg.CORBA.Object {} + + // must be an interface + public abstract class InvalidObjRef8 extends InvalidObjRef7 {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidRemotes.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidRemotes.java new file mode 100644 index 000000000..fdaa610ec --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidRemotes.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Invalid RMI/IDL Remote Interface Types + */ +public class InvalidRemotes { + + // should extend java.rmi.Remote, either directly or indirectly + public interface InvalidRemote1 {} + + // should extend java.rmi.Remote, either directly or indirectly + public interface InvalidRemote2 extends InvalidRemote1 {} + + // RMI/IDL Exceptions should not extend java.rmi.Remote, either directly + // or indirectly + public class InvalidException1 extends java.lang.Exception + implements java.rmi.Remote {} + + // RMI/IDL Exceptions should not extend java.rmi.Remote, either directly + // or indirectly + public class InvalidException2 extends InvalidException1 {} + + // contains method with invalid exception type + public interface InvalidRemote3 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, InvalidException1; + } + + // contains method with invalid exception type + public interface InvalidRemote4 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, InvalidException2; + } + + // Each remote method should throw java.rmi.RemoteException or one of its + // super-class exception types. + public interface InvalidRemote5 extends java.rmi.Remote { + public void foo1(); + } + + // contains method with invalid exception type + public interface InvalidRemote6 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, java.lang.Error; + } + + // contains method with invalid exception type + public interface InvalidRemote7 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, + java.lang.RuntimeException; + } + + private class InvalidException3 extends java.lang.RuntimeException {} + // contains method with invalid exception type + public interface InvalidRemote8 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, + InvalidException3; + } + + // has a field other than primitive or String + public interface InvalidRemote9 extends java.rmi.Remote { + Object o = null; + } + + private interface A { + void foo() throws java.rmi.RemoteException; + } + + private interface B { + void foo() throws java.rmi.RemoteException; + } + + // can't directly inherit from multiple base interfaces which define a + // method with the same name + public interface InvalidRemote10 extends java.rmi.Remote, A, B {} + + private interface C extends A {} + private interface D extends B {} + + // can't directly inherit from multiple base interfaces which define a + // method with the same name. + public interface InvalidRemote11 extends java.rmi.Remote, C, D {} + + private interface E { + void foo() throws java.rmi.RemoteException; + } + + private interface F { + void foo(int a) throws java.rmi.RemoteException; + } + + // can't directly inherit from multiple base interfaces which define a + // method with the same name + public interface InvalidRemote12 extends java.rmi.Remote, E, F {} + + private interface G extends E {} + private interface H extends F {} + + // can't directly inherit from multiple base interfaces which define a + // method with the same name + public interface InvalidRemote13 extends java.rmi.Remote, G, H {} + + // can't directly inherit from multiple base interfaces which define a + // method with the same name + public interface InvalidRemote14 extends G, java.rmi.Remote, H {} + + + // can't directly inherit from multiple base interfaces which define a + // method with the same name. doesn't matter if a method with the same + // name is defined in the most derived interface + public interface InvalidRemote15 extends G, java.rmi.Remote, H { + void foo() throws java.rmi.RemoteException; + } + + // must be an interface + public class InvalidRemote16 {} + + // illegal constant type. must be primitive or String + public interface InvalidRemote17 extends java.rmi.Remote { + int[] FOO = { 1, 2, 3 }; + } + + // applying mangling rules results in clash + public interface InvalidRemote18 extends java.rmi.Remote { + void J_foo() throws java.rmi.RemoteException; + void _foo() throws java.rmi.RemoteException; + } + + // applying mangling rules results in clash + public interface InvalidRemote19 extends java.rmi.Remote { + void foo() throws java.rmi.RemoteException; + void foo(int a) throws java.rmi.RemoteException; + void foo__long() throws java.rmi.RemoteException; + } + + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidValues.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidValues.java new file mode 100644 index 000000000..7fee1dafb --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/InvalidValues.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Invalid RMI/IDL Value Types + */ +public class InvalidValues { + + public static final Class[] CLASSES = { + InvalidValue1.class, InvalidValue2.class, + InvalidValue3.class, InvalidValue4.class, + InvalidValue5.class, InvalidValue6.class, + InvalidValue7.class + }; + + // must be a subtype of Serializable + public class InvalidValue1 {} + + // must be a subtype of Serializable + public class InvalidValue2 extends InvalidValue1 {} + + // must be a class + public interface InvalidValue3 {} + + // must be a class + public interface InvalidValue4 extends java.io.Serializable {} + + // can't implement Remote + public class InvalidValue5 implements java.rmi.Remote {} + + // can't implement Remote + public class InvalidValue6 implements java.io.Serializable, + java.rmi.Remote {} + + // can't implement Remote, directly or indirectly + public class InvalidValue7 extends InvalidValue5 {} + + + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/Raises.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/Raises.java new file mode 100644 index 000000000..f1f1da2d2 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/Raises.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Java class whose name clashes with an IDL keyword. + */ +public class Raises { + + // Inner class with name that clashes with an IDL keyword. + public static class Union {} + + // Inner class whose name has a leading underscore. + public static class _Foo {} + + // Inner class with chars that need to be mangled. + // public static class Uni\u8001code {} + + // Inner class with name that has leading underscore plus IDL keyword + public static class _Union {} + + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/TestStruct.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/TestStruct.java new file mode 100644 index 000000000..4e2080873 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/TestStruct.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public final class TestStruct implements org.omg.CORBA.portable.IDLEntity +{ + public short x = (short)0; + + public TestStruct () + { + } + + public TestStruct (short _x) + { + x = _x; + } +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidEntities.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidEntities.java new file mode 100644 index 000000000..211505b64 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidEntities.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Valid IDL Entity Types + */ +public class ValidEntities { + + public static final Class[] CLASSES = { + ValidEntity1.class, ValidEntity2.class + }; + + public class ValidEntity1 implements org.omg.CORBA.portable.IDLEntity {} + + public class ValidEntity2 extends ValidEntity1 {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidExceptions.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidExceptions.java new file mode 100644 index 000000000..5de0de405 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidExceptions.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Valid RMI/IDL Exception Types + */ +public class ValidExceptions { + + public static final Class[] CLASSES = { + ValidException1.class, + ValidException2.class, + ValidException3.class, + ValidException4.class, + ValidException5.class, + ValidException6.class + }; + + public class ValidException1 extends java.lang.Exception {} + + public class ValidException2 extends ValidException1 {} + + public class ValidException3 extends Throwable {} + + public class ValidException4 extends ValidException3 {} + + public class ValidException5 extends java.io.IOException {} + + public class ValidException6 extends ValidException5 {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidObjRefs.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidObjRefs.java new file mode 100644 index 000000000..583a8fb64 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidObjRefs.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Valid RMI/IDL CORBA Object Reference Types + */ +public class ValidObjRefs { + + public static final Class[] CLASSES = { + org.omg.CORBA.Object.class, + ValidObjRef1.class, ValidObjRef2.class + }; + + public interface ValidObjRef1 extends org.omg.CORBA.Object {} + + public interface ValidObjRef2 extends ValidObjRef1 {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidRemotes.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidRemotes.java new file mode 100644 index 000000000..7191b1459 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidRemotes.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Valid RMI/IDL Remote Interface Types + */ +public class ValidRemotes { + + public static final Class[] CLASSES = { + java.rmi.Remote.class, + ValidRemote0.class, ValidRemote1.class, + ValidRemote2.class, ValidRemote3.class, + ValidRemote4.class, ValidRemote5.class, + ValidRemote6.class, ValidRemote7.class, + ValidRemote8.class, ValidRemote9.class, + ValidRemote10.class + }; + + public interface ValidRemote0 extends java.rmi.Remote {} + + public interface ValidRemote1 extends ValidRemote0 {} + + public interface ValidRemote2 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, + java.io.IOException, java.lang.Exception, java.lang.Throwable; + } + + public interface ValidRemote3 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException; + public void foo2() throws java.io.IOException; + public void foo3() throws java.lang.Exception; + public void foo4() throws java.lang.Throwable; + } + + public interface ValidRemote4 extends ValidRemote3 {} + + public interface ValidRemote5 extends java.rmi.Remote { + boolean a = true; + boolean b = false; + byte c = 0; + char d = 'd'; + short e = 2; + int f = 3; + long g = 4; + float h = 5.0f; + double i = 6.0; + String j = "foo"; + } + + public interface ValidRemote6 extends java.rmi.Remote { + public void foo1() throws java.rmi.RemoteException, + java.lang.Exception; + + public void foo2() + throws java.rmi.RemoteException, Exception1; + + } + + public static class Exception1 extends java.lang.Exception {} + + public interface ValidRemote7 extends java.rmi.Remote { + void foo() throws java.rmi.RemoteException; + void foo(int a) throws java.rmi.RemoteException; + void foo(String[] b) throws java.rmi.RemoteException; + } + + public interface ValidRemote8 extends + ValidRemote2, ValidRemote5, ValidRemote7 {} + + public interface ValidRemote9 extends ValidRemote8 { + void foo(int a) throws java.rmi.RemoteException; + } + + public interface ValidRemote10 extends java.rmi.Remote, ValidRemote9 {} +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidValues.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidValues.java new file mode 100644 index 000000000..d30d5f5ad --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/ValidValues.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Valid RMI/IDL Value Types + */ +public class ValidValues { + + public static final Class[] CLASSES = { + ValidValue1.class, ValidValue2.class, + java.util.Date.class, java.lang.Integer.class, java.lang.String.class + }; + + public class ValidValue1 implements java.io.Serializable {} + + public class ValidValue2 extends ValidValue1 {} + + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_ContainerClash3.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_ContainerClash3.java new file mode 100644 index 000000000..15375c2c9 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_ContainerClash3.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public interface _ContainerClash3 extends java.rmi.Remote { + + void _ContainerClash3() throws java.rmi.RemoteException; + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_ContainerClash4.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_ContainerClash4.java new file mode 100644 index 000000000..722f38a79 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_ContainerClash4.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public interface _ContainerClash4 extends java.rmi.Remote { + + void _ContainerCLASH4() throws java.rmi.RemoteException; + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_Default.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_Default.java new file mode 100644 index 000000000..a01c6c656 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_Default.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public class _Default { + + public class Inner {} + + public class _Inner {} + + public class Default {} + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_Raises.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_Raises.java new file mode 100644 index 000000000..8dbdeec8d --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_Raises.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +/** + * Java class whose name is an IDL keyword prepended with an underscore. + */ +public class _Raises { + + // Inner class with name that clashes with an IDL keyword. + public static class Union {} + + // Inner class whose name has a leading underscore. + public static class _Foo {} + + // Inner class with name that has leading underscore plus IDL keyword + public static class _Union {} + + +} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_upackage/Foo.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_upackage/Foo.java new file mode 100644 index 000000000..84b23d70a --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/_upackage/Foo.java @@ -0,0 +1,13 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses._upackage; + +public class Foo {} diff --git a/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/typedef/Foo.java b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/typedef/Foo.java new file mode 100644 index 000000000..3b2da8e59 --- /dev/null +++ b/orbmain/src/test/java/corba/dynamicrmiiiop/testclasses/typedef/Foo.java @@ -0,0 +1,13 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses.typedef; + +public class Foo {} diff --git a/orbmain/src/test/java/org/glassfish/corba/testutils/HexBuffer.java b/orbmain/src/test/java/org/glassfish/corba/testutils/HexBuffer.java new file mode 100644 index 000000000..dc963ae00 --- /dev/null +++ b/orbmain/src/test/java/org/glassfish/corba/testutils/HexBuffer.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba.testutils; + +import java.util.List; + +public class HexBuffer { + public static final int BYTES_PER_LINE = 32; + public static final int SPACES_PER_LINE = 2*BYTES_PER_LINE + BYTES_PER_LINE/4; + + public static void dumpBuffer(byte[] bytes) { + for (int i = 0; i < bytes.length; i+= BYTES_PER_LINE) + dumpLine( i, subBuffer(bytes, i, i + BYTES_PER_LINE) ); + } + + private static void dumpLine(int start, byte[] bytes) { + StringBuilder sb = new StringBuilder(String.format("%4d: ", start)); + int width = 0; + for (int i = 0; i < bytes.length;) { + sb.append(String.format("%02X", bytes[i])); + width += 2; + if ((++i % 4) == 0) { + sb.append(' '); + width++; + } + } + while (width++ < SPACES_PER_LINE) + sb.append(' '); + sb.append(' '); + for (byte aByte : bytes) { + sb.append(aByte < ' ' ? ' ' : (char)aByte); + } + System.out.println(sb.toString()); + } + + private static byte[] subBuffer(byte[] input, int start, int limit) { + int end = Math.min(limit, input.length); + byte[] result = new byte[end-start]; + System.arraycopy(input, start, result, 0, result.length); + return result; + } + + public static void dumpBuffers(List list) { + for (byte[] buffer : list) { + dumpBuffer(buffer); + System.out.println(); + } + } +} diff --git a/orbmain/src/test/java/org/glassfish/corba/testutils/StubCorbaObject.java b/orbmain/src/test/java/org/glassfish/corba/testutils/StubCorbaObject.java new file mode 100644 index 000000000..7a23aa3ae --- /dev/null +++ b/orbmain/src/test/java/org/glassfish/corba/testutils/StubCorbaObject.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.corba.testutils; + +import org.omg.CORBA.*; +import org.omg.CORBA.Object; + +public class StubCorbaObject implements org.omg.CORBA.Object { + public boolean _is_a(String s) { + return false; + } + + public boolean _is_equivalent(org.omg.CORBA.Object object) { + return false; + } + + public boolean _non_existent() { + return false; + } + + public int _hash(int i) { + return 0; + } + + public Object _duplicate() { + return null; + } + + public void _release() { + } + + public Object _get_interface_def() { + return null; + } + + public Request _request(String s) { + return null; + } + + public Request _create_request(Context context, String s, NVList nvList, NamedValue namedValue) { + return null; + } + + public Request _create_request(Context context, String s, NVList nvList, NamedValue namedValue, ExceptionList exceptionList, ContextList contextList) { + return null; + } + + public Policy _get_policy(int i) { + return null; + } + + public DomainManager[] _get_domain_managers() { + return new DomainManager[0]; + } + + public Object _set_policy_override(Policy[] policies, SetOverrideType setOverrideType) { + return null; + } +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000..242e97b4a --- /dev/null +++ b/pom.xml @@ -0,0 +1,374 @@ + + + + 4.0.0 + + org.eclipse.ee4j + project + 1.0.1 + + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + ORB Implementation + pom + A CORBA ORB for Glassfish + + https://projects.eclipse.org/proposals/eclipse-orb + + + github + https://github.com/eclipse-ee4j/orb/issues + + + + + EDL 1.0 + https://www.eclipse.org/org/documents/edl-v10.php + repo + + + + + + ORB mailing list + orb-dev@eclipse.org + https://dev.eclipse.org/mailman/listinfo/orb-dev + https://dev.eclipse.org/mailman/listinfo/orb-dev + https://dev.eclipse.org/mhonarc/lists/orb-dev + + + + + scm:git:https://github.com/eclipse-ee4j/orb.git + scm:git:ssh://git@github.com/eclipse-ee4j/orb.git + https://github.com/eclipse-ee4j/orb + HEAD + + + + + github + scm:git:https://github.com/eclipse-ee4j/orb.git + + + + + + Russell Gold + russell.gold@oracle.com + russgold + + + Harshad Vilekar + + + + + idlj + rmic + omgapi + csiv2-idl + exception-annotation-processor + orbmain + internal-api + functional-tests + + + + 1.8 + ${jdkVersion} + ${jdkVersion} + UTF-8 + false + 4.0.1-b003 + 4.0.0-b002 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + + com.meterware.simplestub + simplestub + 1.2.12 + test + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.20 + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + + Oracle Corporation + Oracle + + + + + + + + maven-site-plugin + 3.3 + + + stage-for-scm-publish + post-site + + stage + + + + default-deploy + none + + + + + + + maven-scm-publish-plugin + 1.1 + + gh-pages + scm:git:https://github.com/javaee/glassfish-corba.git + + + + + + + + org.apache.felix + maven-bundle-plugin + 3.3.0 + true + + + org.codehaus.mojo + idlj-maven-plugin + 1.2.2 + + + + generate + + + + + + + false + + + CORBA3 + + + + -corba + 3.0 + + + + + + + + org.codehaus.mojo + rmic-maven-plugin + 1.3 + + + + test-rmic + + + + + + org.glassfish.corba + rmic + 4.0.2-b007 + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.6 + + + ant + ant-junit + 1.6.5 + + + junit + junit + 4.4 + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.9 + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.2 + + + org.apache.maven.scm + maven-scm-provider-gitexe + 1.8.1 + + + + + + + + + org.apache.maven.wagon + wagon-webdav-jackrabbit + 2.4 + + + + + + + + + + + + + + + + disable-java8-doclint + + [1.8,) + + + -Xdoclint:none + + + + + + jvnet-release + + + + org.apache.maven.plugins + maven-toolchains-plugin + 1.1 + + + + toolchain + + + + + + + ${jdkVersion} + oracle + + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 1.4.1 + + + enforce-jdk-versions + + enforce + + + + + (,1.9) + functional-tests will not build with Java 9 or higher + + + + + + + + + + + + diff --git a/rmic/README b/rmic/README new file mode 100644 index 000000000..d02afac86 --- /dev/null +++ b/rmic/README @@ -0,0 +1,6 @@ +By default, rmic now uses an ASM-based classfile parser. New Java code versions can be supported simply by changing +the dependent ASM version. It is also possible to fall back to the legacy binary classfile parser in +JDK versions 1.8 and 9 by setting the system property org.glassfish.rmic.UseLegacyClassParsing to "true". + +Note that if no version of ASM is in the classpath, rmic will attempt to fallback to the legacy parser in the earlier +JDK versions. \ No newline at end of file diff --git a/rmic/pom.xml b/rmic/pom.xml new file mode 100644 index 000000000..db4e6d15f --- /dev/null +++ b/rmic/pom.xml @@ -0,0 +1,74 @@ + + + + 4.0.0 + + org.glassfish.corba + glassfish-corba + 4.2.0-b005-SNAPSHOT + + + rmic + RMIC compiler + + + + ${project.groupId} + glassfish-corba-orb + ${project.version} + + + org.ow2.asm + asm + 6.0 + + + org.hamcrest + hamcrest-all + 1.3 + test + + + junit + junit + 4.12 + test + + + com.meterware.simplestub + simplestub + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + + org.glassfish.rmic.Main + + + ${project.version} + + + + + + + + diff --git a/rmic/src/main/java/org/glassfish/rmic/BatchEnvironment.java b/rmic/src/main/java/org/glassfish/rmic/BatchEnvironment.java new file mode 100644 index 000000000..ad0c7fafe --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/BatchEnvironment.java @@ -0,0 +1,407 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.ClassPath; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.StringTokenizer; +import java.util.Vector; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +/** + * BatchEnvironment for rmic extends javac's version in four ways: + * 1. It overrides errorString() to handle looking for rmic-specific + * error messages in rmic's resource bundle + * 2. It provides a mechanism for recording intermediate generated + * files so that they can be deleted later. + * 3. It holds a reference to the Main instance so that generators + * can refer to it. + * 4. It provides access to the ClassPath passed to the constructor. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ + +@SuppressWarnings("deprecation") +public class BatchEnvironment extends org.glassfish.rmic.tools.javac.BatchEnvironment { + + /** The directory to which class files are being written. */ + private File destinationDir; + + /** + * Create a ClassPath object for rmic from the relevant command line + * options for class path and boot class path. + */ + public static ClassPath createClassPath(String classPathString, String sysClassPathString) { + /* + * Previously, this method delegated to the + * org.glassfish.rmic.tools.javac.BatchEnvironment.classPaths method in order + * to supply default values for paths not specified on the + * command line, expand extensions directories into specific + * JAR files, and construct the ClassPath object-- but as part + * of the fix for 6473331, which adds support for Class-Path + * manifest entries in JAR files, those steps are now handled + * here directly, with the help of a Path utility class copied + * from the new javac implementation (see below). + */ + Path path = new Path(); + + if (sysClassPathString == null) { + sysClassPathString = System.getProperty("sun.boot.class.path"); + } + if (sysClassPathString != null) { + path.addFiles(sysClassPathString); + } + + /* + * Class-Path manifest entries are supported for JAR files + * everywhere except in the boot class path. + */ + path.expandJarClassPaths(true); + + /* + * In the application class path, an empty element means + * the current working directory. + */ + path.emptyPathDefault("."); + + if (classPathString == null) { + // The env.class.path property is the user's CLASSPATH + // environment variable, and it set by the wrapper (ie, + // javac.exe). + classPathString = System.getProperty("env.class.path"); + if (classPathString == null) { + classPathString = "."; + } + } + path.addFiles(classPathString); + + return new ClassPath(path.toArray(new String[path.size()])); + } + + /** + * Create a BatchEnvironment for rmic with the given class path, + * stream for messages and destination directory. + */ + public BatchEnvironment(OutputStream out, ClassPath path, File destinationDir) { + super(out, path); + this.destinationDir = destinationDir; + } + + /** + * Returns the directory to which generated classes will be written. + * @return the destination directory specified by the "-d" flag + */ + public File getDestinationDir() { + return destinationDir; + } + + /** + * Get the ClassPath. + */ + public ClassPath getClassPath() { + return binaryPath; + } + + /** list of generated source files created in this environment */ + private Vector generatedFiles = new Vector<>(); + + /** + * Remember a generated source file generated so that it + * can be removed later, if appropriate. + */ + public void addGeneratedFile(File file) { + generatedFiles.addElement(file); + } + + /** + * Delete all the generated source files made during the execution + * of this environment (those that have been registered with the + * "addGeneratedFile" method). + */ + void deleteGeneratedFiles() { + synchronized(generatedFiles) { + Enumeration enumeration = generatedFiles.elements(); + while (enumeration.hasMoreElements()) { + File file = enumeration.nextElement(); + file.delete(); + } + generatedFiles.removeAllElements(); + } + } + + /** + * Release resources, if any. + */ + public void shutdown() { + generatedFiles = null; + super.shutdown(); + } + + /** + * Return the formatted, localized string for a named error message + * and supplied arguments. For rmic error messages, with names that + * being with "rmic.", look up the error message in rmic's resource + * bundle; otherwise, defer to java's superclass method. + */ + public String errorString(String err, + Object arg0, Object arg1, Object arg2) + { + if (err.startsWith("rmic.") || err.startsWith("warn.rmic.")) { + String result = Main.getText(err, + (arg0 != null ? arg0.toString() : null), + (arg1 != null ? arg1.toString() : null), + (arg2 != null ? arg2.toString() : null)); + + if (err.startsWith("warn.")) { + result = "warning: " + result; + } + return result; + } else { + return super.errorString(err, arg0, arg1, arg2); + } + } + public void reset() { + } + + /** + * Utility for building paths of directories and JAR files. This + * class was copied from com.org.glassfish.rmic.tools.javac.util.Paths as part of + * the fix for 6473331, which adds support for Class-Path manifest + * entries in JAR files. Diagnostic code is simply commented out + * because rmic silently ignored these conditions historically. + */ + private static class Path extends LinkedHashSet { + private static final long serialVersionUID = 0; + private static final boolean warn = false; + + private static class PathIterator implements Collection { + private int pos = 0; + private final String path; + private final String emptyPathDefault; + + public PathIterator(String path, String emptyPathDefault) { + this.path = path; + this.emptyPathDefault = emptyPathDefault; + } + public PathIterator(String path) { this(path, null); } + public Iterator iterator() { + return new Iterator() { + public boolean hasNext() { + return pos <= path.length(); + } + public String next() { + int beg = pos; + int end = path.indexOf(File.pathSeparator, beg); + if (end == -1) + end = path.length(); + pos = end + 1; + + if (beg == end && emptyPathDefault != null) + return emptyPathDefault; + else + return path.substring(beg, end); + } + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + // required for Collection. + public int size() { + throw new UnsupportedOperationException(); + } + public boolean isEmpty() { + throw new UnsupportedOperationException(); + } + public boolean contains(Object o) { + throw new UnsupportedOperationException(); + } + public Object[] toArray() { + throw new UnsupportedOperationException(); + } + public T[] toArray(T[] a) { + throw new UnsupportedOperationException(); + } + public boolean add(String o) { + throw new UnsupportedOperationException(); + } + public boolean remove(Object o) { + throw new UnsupportedOperationException(); + } + public boolean containsAll(Collection c) { + throw new UnsupportedOperationException(); + } + public boolean addAll(Collection c) { + throw new UnsupportedOperationException(); + } + public boolean removeAll(Collection c) { + throw new UnsupportedOperationException(); + } + public boolean retainAll(Collection c) { + throw new UnsupportedOperationException(); + } + public void clear() { + throw new UnsupportedOperationException(); + } + public boolean equals(Object o) { + throw new UnsupportedOperationException(); + } + public int hashCode() { + throw new UnsupportedOperationException(); + } + } + + /** Is this the name of a zip file? */ + private static boolean isZip(String name) { + return new File(name).isFile(); + } + + private boolean expandJarClassPaths = false; + + public Path expandJarClassPaths(boolean x) { + expandJarClassPaths = x; + return this; + } + + /** What to use when path element is the empty string */ + private String emptyPathDefault = null; + + public Path emptyPathDefault(String x) { + emptyPathDefault = x; + return this; + } + + public Path() { super(); } + + public Path addDirectories(String dirs, boolean warn) { + if (dirs != null) + for (String dir : new PathIterator(dirs)) + addDirectory(dir, warn); + return this; + } + + public Path addDirectories(String dirs) { + return addDirectories(dirs, warn); + } + + private void addDirectory(String dir, boolean warn) { + if (! new File(dir).isDirectory()) { +// if (warn) +// log.warning(Position.NOPOS, +// "dir.path.element.not.found", dir); + return; + } + + for (String direntry : new File(dir).list()) { + String canonicalized = direntry.toLowerCase(); + if (canonicalized.endsWith(".jar") || + canonicalized.endsWith(".zip")) + addFile(dir + File.separator + direntry, warn); + } + } + + public Path addFiles(String files, boolean warn) { + if (files != null) + for (String file : new PathIterator(files, emptyPathDefault)) + addFile(file, warn); + return this; + } + + public Path addFiles(String files) { + return addFiles(files, warn); + } + + private void addFile(String file, boolean warn) { + if (contains(file)) { + /* Discard duplicates and avoid infinite recursion */ + return; + } + + File ele = new File(file); + if (! ele.exists()) { + /* No such file or directory exist */ + if (warn) +// log.warning(Position.NOPOS, +// "path.element.not.found", file); + return; + } + + if (ele.isFile()) { + /* File is an ordinay file */ + String arcname = file.toLowerCase(); + if (! (arcname.endsWith(".zip") || + arcname.endsWith(".jar"))) { + /* File name don't have right extension */ +// if (warn) +// log.warning(Position.NOPOS, +// "invalid.archive.file", file); + return; + } + } + + /* Now what we have left is either a directory or a file name + confirming to archive naming convention */ + + super.add(file); + if (expandJarClassPaths && isZip(file)) + addJarClassPath(file, warn); + } + + // Adds referenced classpath elements from a jar's Class-Path + // Manifest entry. In some future release, we may want to + // update this code to recognize URLs rather than simple + // filenames, but if we do, we should redo all path-related code. + private void addJarClassPath(String jarFileName, boolean warn) { + try { + String jarParent = new File(jarFileName).getParent(); + JarFile jar = new JarFile(jarFileName); + + try { + Manifest man = jar.getManifest(); + if (man == null) return; + + Attributes attr = man.getMainAttributes(); + if (attr == null) return; + + String path = attr.getValue(Attributes.Name.CLASS_PATH); + if (path == null) return; + + for (StringTokenizer st = new StringTokenizer(path); + st.hasMoreTokens();) { + String elt = st.nextToken(); + if (jarParent != null) + elt = new File(jarParent, elt).getCanonicalPath(); + addFile(elt, warn); + } + } finally { + jar.close(); + } + } catch (IOException e) { +// log.error(Position.NOPOS, +// "error.reading.file", jarFileName, +// e.getLocalizedMessage()); + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/BatchEnvironmentError.java b/rmic/src/main/java/org/glassfish/rmic/BatchEnvironmentError.java new file mode 100644 index 000000000..a014f5c56 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/BatchEnvironmentError.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +public class BatchEnvironmentError extends Error { + public BatchEnvironmentError(String message) { + super(message); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/Constants.java b/rmic/src/main/java/org/glassfish/rmic/Constants.java new file mode 100644 index 000000000..5789745c5 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/Constants.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.Identifier; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public interface Constants extends org.glassfish.rmic.tools.java.Constants { + + /* + * Identifiers potentially useful for all Generators + */ + public static final Identifier idRemote = + Identifier.lookup("java.rmi.Remote"); + public static final Identifier idRemoteException = + Identifier.lookup("java.rmi.RemoteException"); +} diff --git a/rmic/src/main/java/org/glassfish/rmic/Generator.java b/rmic/src/main/java/org/glassfish/rmic/Generator.java new file mode 100644 index 000000000..c8760408f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/Generator.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import java.io.File; +import org.glassfish.rmic.tools.java.ClassDefinition; + +/** + * Generator defines the protocol for back-end implementations to be added + * to rmic. See the rmic.properties file for a description of the format for + * adding new Generators to rmic. + *

                + * Classes implementing this interface must have a public default constructor + * which should set any required arguments to their defaults. When Main + * encounters a command line argument which maps to a specific Generator + * subclass, it will instantiate one and call parseArgs(...). At some later + * point, Main will invoke the generate(...) method once for _each_ class passed + * on the command line. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Bryan Atsatt + */ +public interface Generator { + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param main Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main); + + /** + * Generate output. Any source files created which need compilation should + * be added to the compiler environment using the addGeneratedFile(File) + * method. + * @param env The compiler environment + * @param destDir The directory for the root of the package hierarchy + * @param cdef The definition for the implementation class or interface from + * which to generate output + */ + public void generate(BatchEnvironment env, File destDir, ClassDefinition cdef); +} diff --git a/rmic/src/main/java/org/glassfish/rmic/IndentingWriter.java b/rmic/src/main/java/org/glassfish/rmic/IndentingWriter.java new file mode 100644 index 000000000..1488a04a8 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/IndentingWriter.java @@ -0,0 +1,278 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import java.io.Writer; +import java.io.BufferedWriter; +import java.io.IOException; + +/** + * IndentingWriter is a BufferedWriter subclass that supports automatic + * indentation of lines of text written to the underlying Writer. + * + * Methods are provided for compact, convenient indenting, writing text, + * and writing lines in various combinations. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public class IndentingWriter extends BufferedWriter { + + /** true if the next character written is the first on a line */ + private boolean beginningOfLine = true; + + /** current number of spaces to prepend to lines */ + private int currentIndent = 0; + + /** number of spaces to change indent when indenting in or out */ + private int indentStep = 4; + + /** number of spaces to convert into tabs. Use MAX_VALUE to disable */ + private int tabSize = 8; + + /** + * Create a new IndentingWriter that writes indented text to the + * given Writer. Use the default indent step of four spaces. + */ + public IndentingWriter(Writer out) { + super(out); + } + + /** + * Create a new IndentingWriter that writes indented text to the + * given Writer and uses the supplied indent step. + */ + public IndentingWriter(Writer out, int step) { + this(out); + + if (indentStep < 0) + throw new IllegalArgumentException("negative indent step"); + + indentStep = step; + } + + /** + * Create a new IndentingWriter that writes indented text to the + * given Writer and uses the supplied indent step and tab size. + */ + public IndentingWriter(Writer out, int step, int tabSize) { + this(out); + + if (indentStep < 0) + throw new IllegalArgumentException("negative indent step"); + + indentStep = step; + this.tabSize = tabSize; + } + + /** + * Write a single character. + */ + public void write(int c) throws IOException { + checkWrite(); + super.write(c); + } + + /** + * Write a portion of an array of characters. + */ + public void write(char[] cbuf, int off, int len) throws IOException { + if (len > 0) { + checkWrite(); + } + super.write(cbuf, off, len); + } + + /** + * Write a portion of a String. + */ + public void write(String s, int off, int len) throws IOException { + if (len > 0) { + checkWrite(); + } + super.write(s, off, len); + } + + /** + * Write a line separator. The next character written will be + * preceded by an indent. + */ + public void newLine() throws IOException { + super.newLine(); + beginningOfLine = true; + } + + /** + * Check if an indent needs to be written before writing the next + * character. + * + * The indent generation is optimized (and made consistent with + * certain coding conventions) by condensing groups of eight spaces + * into tab characters. + */ + protected void checkWrite() throws IOException { + if (beginningOfLine) { + beginningOfLine = false; + int i = currentIndent; + while (i >= tabSize) { + super.write('\t'); + i -= tabSize; + } + while (i > 0) { + super.write(' '); + -- i; + } + } + } + + /** + * Increase the current indent by the indent step. + */ + protected void indentIn() { + currentIndent += indentStep; + } + + /** + * Decrease the current indent by the indent step. + */ + protected void indentOut() { + currentIndent -= indentStep; + if (currentIndent < 0) + currentIndent = 0; + } + + /** + * Indent in. + */ + public void pI() { + indentIn(); + } + + /** + * Indent out. + */ + public void pO() { + indentOut(); + } + + /** + * Write string. + */ + public void p(String s) throws IOException { + write(s); + } + + /** + * End current line. + */ + public void pln() throws IOException { + newLine(); + } + + /** + * Write string; end current line. + */ + public void pln(String s) throws IOException { + p(s); + pln(); + } + + /** + * Write string; end current line; indent in. + */ + public void plnI(String s) throws IOException { + p(s); + pln(); + pI(); + } + + /** + * Indent out; write string. + */ + public void pO(String s) throws IOException { + pO(); + p(s); + } + + /** + * Indent out; write string; end current line. + */ + public void pOln(String s) throws IOException { + pO(s); + pln(); + } + + /** + * Indent out; write string; end current line; indent in. + * + * This method is useful for generating lines of code that both + * end and begin nested blocks, like "} else {". + */ + public void pOlnI(String s) throws IOException { + pO(s); + pln(); + pI(); + } + + /** + * Write Object. + */ + public void p(Object o) throws IOException { + write(o.toString()); + } + /** + * Write Object; end current line. + */ + public void pln(Object o) throws IOException { + p(o.toString()); + pln(); + } + + /** + * Write Object; end current line; indent in. + */ + public void plnI(Object o) throws IOException { + p(o.toString()); + pln(); + pI(); + } + + /** + * Indent out; write Object. + */ + public void pO(Object o) throws IOException { + pO(); + p(o.toString()); + } + + /** + * Indent out; write Object; end current line. + */ + public void pOln(Object o) throws IOException { + pO(o.toString()); + pln(); + } + + /** + * Indent out; write Object; end current line; indent in. + * + * This method is useful for generating lines of code that both + * end and begin nested blocks, like "} else {". + */ + public void pOlnI(Object o) throws IOException { + pO(o.toString()); + pln(); + pI(); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/Main.java b/rmic/src/main/java/org/glassfish/rmic/Main.java new file mode 100644 index 000000000..60f0e9821 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/Main.java @@ -0,0 +1,832 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassFile; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.ClassPath; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.javac.SourceClass; +import org.glassfish.rmic.tools.util.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + * Main "rmic" program. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public class Main implements org.glassfish.rmic.Constants { + String sourcePathArg; + String sysClassPathArg; + String classPathString; + File destDir; + int flags; + long tm; + Vector classes; + boolean nowrite; + boolean nocompile; + boolean keepGenerated; + boolean status; + String[] generatorArgs; + Vector generators; + Class environmentClass = + BatchEnvironment.class; + boolean iiopGeneration = false; + + /** + * Name of the program. + */ + String program; + + /** + * The stream where error message are printed. + */ + OutputStream out; + + /** + * Constructor. + */ + public Main(OutputStream out, String program) { + this.out = out; + this.program = program; + } + + /** + * Output a message. + */ + public void output(String msg) { + PrintStream out = this.out instanceof PrintStream ? (PrintStream) this.out : new PrintStream(this.out, true); + out.println(msg); + } + + /** + * Top level error message. This method is called when the + * environment could not be set up yet. + */ + public void error(String msg) { + output(getText(msg)); + } + + public void error(String msg, String arg1) { + output(getText(msg, arg1)); + } + + public void error(String msg, String arg1, String arg2) { + output(getText(msg, arg1, arg2)); + } + + /** + * Usage + */ + public void usage() { + error("rmic.usage", program); + } + + /** + * Run the compiler + */ + public synchronized boolean compile(String argv[]) { + + if (!parseArgs(argv)) { + return false; + } + + if (classes.size() == 0) { + usage(); + return false; + } + + return doCompile(); + } + + /** + * Get the destination directory. + */ + public File getDestinationDir() { + return destDir; + } + + /** + * Parse the arguments for compile. + */ + public boolean parseArgs(String... argv) { + sourcePathArg = null; + sysClassPathArg = null; + + classPathString = null; + destDir = null; + flags = F_WARNINGS; + tm = System.currentTimeMillis(); + classes = new Vector<>(); + nowrite = false; + nocompile = false; + keepGenerated = false; + generatorArgs = getArray("generator.args",true); + if (generatorArgs == null) { + return false; + } + generators = new Vector<>(); + + // Pre-process command line for @file arguments + try { + argv = CommandLine.parse(argv); + } catch (FileNotFoundException e) { + error("rmic.cant.read", e.getMessage()); + return false; + } catch (IOException e) { + e.printStackTrace(out instanceof PrintStream ? + (PrintStream) out : + new PrintStream(out, true)); + return false; + } + + // Parse arguments + for (int i = 0 ; i < argv.length ; i++) { + if (argv[i] != null) { + if (argv[i].equals("-g")) { + flags &= ~F_OPT; + flags |= F_DEBUG_LINES | F_DEBUG_VARS; + argv[i] = null; + } else if (argv[i].equals("-O")) { + flags &= ~F_DEBUG_LINES; + flags &= ~F_DEBUG_VARS; + flags |= F_OPT | F_DEPENDENCIES; + argv[i] = null; + } else if (argv[i].equals("-nowarn")) { + flags &= ~F_WARNINGS; + argv[i] = null; + } else if (argv[i].equals("-debug")) { + flags |= F_DUMP; + argv[i] = null; + } else if (argv[i].equals("-depend")) { + flags |= F_DEPENDENCIES; + argv[i] = null; + } else if (argv[i].equals("-verbose")) { + flags |= F_VERBOSE; + argv[i] = null; + } else if (argv[i].equals("-nowrite")) { + nowrite = true; + argv[i] = null; + } else if (argv[i].equals("-Xnocompile")) { + nocompile = true; + keepGenerated = true; + argv[i] = null; + } else if (argv[i].equals("-keep") || + argv[i].equals("-keepgenerated")) { + keepGenerated = true; + argv[i] = null; + } else if (argv[i].equals("-show")) { + error("rmic.option.unsupported", "-show"); + usage(); + return false; + } else if (argv[i].equals("-classpath")) { + if ((i + 1) < argv.length) { + if (classPathString != null) { + error("rmic.option.already.seen", "-classpath"); + usage(); + return false; + } + argv[i] = null; + classPathString = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-classpath"); + usage(); + return false; + } + } else if (argv[i].equals("-sourcepath")) { + if ((i + 1) < argv.length) { + if (sourcePathArg != null) { + error("rmic.option.already.seen", "-sourcepath"); + usage(); + return false; + } + argv[i] = null; + sourcePathArg = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-sourcepath"); + usage(); + return false; + } + } else if (argv[i].equals("-bootclasspath")) { + if ((i + 1) < argv.length) { + if (sysClassPathArg != null) { + error("rmic.option.already.seen", "-bootclasspath"); + usage(); + return false; + } + argv[i] = null; + sysClassPathArg = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-bootclasspath"); + usage(); + return false; + } + } else if (argv[i].equals("-d")) { + if ((i + 1) < argv.length) { + if (destDir != null) { + error("rmic.option.already.seen", "-d"); + usage(); + return false; + } + argv[i] = null; + destDir = new File(argv[++i]); + argv[i] = null; + if (!destDir.exists()) { + error("rmic.no.such.directory", destDir.getPath()); + usage(); + return false; + } + } else { + error("rmic.option.requires.argument", "-d"); + usage(); + return false; + } + } else { + if (!checkGeneratorArg(argv,i)) { + usage(); + return false; + } + } + } + } + + + // Now that all generators have had a chance at the args, + // scan what's left for classes and illegal args... + + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + if (argv[i].startsWith("-")) { + error("rmic.no.such.option", argv[i]); + usage(); + return false; + } else { + classes.addElement(argv[i]); + } + } + } + + + // If the generators vector is empty, add the default generator... + + if (generators.size() == 0) { + addGenerator("default"); + } + + return true; + } + + /** + * If this argument is for a generator, instantiate it, call + * parseArgs(...) and add generator to generators vector. + * Returns false on error. + */ + protected boolean checkGeneratorArg(String[] argv, int currentIndex) { + boolean result = true; + if (argv[currentIndex].startsWith("-")) { + String arg = argv[currentIndex].substring(1).toLowerCase(); // Remove '-' + for (int i = 0; i < generatorArgs.length; i++) { + if (arg.equalsIgnoreCase(generatorArgs[i])) { + // Got a match, add Generator and call parseArgs... + Generator gen = addGenerator(arg); + if (gen == null) { + return false; + } + result = gen.parseArgs(argv,this); + break; + } + } + } + return result; + } + + /** + * Instantiate and add a generator to the generators array. + */ + protected Generator addGenerator(String arg) { + + Generator gen; + + // Create an instance of the generator and add it to + // the array... + + String className = getString("generator.class." + arg); + if (className == null) { + error("rmic.missing.property",arg); + return null; + } + + try { + gen = (Generator) Class.forName(className).newInstance(); + } catch (Exception e) { + error("rmic.cannot.instantiate",className); + return null; + } + + generators.addElement(gen); + + // Get the environment required by this generator... + + Class envClass = BatchEnvironment.class; + String env = getString("generator.env." + arg); + if (env != null) { + try { + envClass = Class.forName(env); + + // Is the new class a subclass of the current one? + + if (environmentClass.isAssignableFrom(envClass)) { + + // Yes, so switch to the new one... + + environmentClass = envClass.asSubclass(BatchEnvironment.class); + + } else { + + // No. Is the current class a subclass of the + // new one? + + if (!envClass.isAssignableFrom(environmentClass)) { + + // No, so it's a conflict... + + error("rmic.cannot.use.both",environmentClass.getName(),envClass.getName()); + return null; + } + } + } catch (ClassNotFoundException e) { + error("rmic.class.not.found",env); + return null; + } + } + + // If this is the iiop stub generator, cache + // that fact for the jrmp generator... + + if (arg.equals("iiop")) { + iiopGeneration = true; + } + return gen; + } + + /** + * Grab a resource string and parse it into an array of strings. Assumes + * comma separated list. + * @param name The resource name. + * @param mustExist If true, throws error if resource does not exist. If + * false and resource does not exist, returns zero element array. + */ + protected String[] getArray(String name, boolean mustExist) { + String[] result = null; + String value = getString(name); + if (value == null) { + if (mustExist) { + error("rmic.resource.not.found",name); + return null; + } else { + return new String[0]; + } + } + + StringTokenizer parser = new StringTokenizer(value,", \t\n\r", false); + int count = parser.countTokens(); + result = new String[count]; + for (int i = 0; i < count; i++) { + result[i] = parser.nextToken(); + } + + return result; + } + + /** + * Get the correct type of BatchEnvironment + */ + public BatchEnvironment getEnv() { + + ClassPath classPath = + BatchEnvironment.createClassPath(classPathString, + sysClassPathArg); + BatchEnvironment result = null; + try { + Class[] ctorArgTypes = {OutputStream.class,ClassPath.class,File.class}; + Object[] ctorArgs = {out,classPath,getDestinationDir()}; + Constructor constructor = + environmentClass.getConstructor(ctorArgTypes); + result = constructor.newInstance(ctorArgs); + result.reset(); + } + catch (Exception e) { + error("rmic.cannot.instantiate",environmentClass.getName()); + } + return result; + } + + + /** + * Do the compile with the switches and files already supplied + */ + private boolean doCompile() { + // Create batch environment + BatchEnvironment env = getEnv(); + env.flags |= flags; + + // Set the classfile version numbers + // Compat and 1.1 stubs must retain the old version number. + env.majorVersion = 45; + env.minorVersion = 3; + + // Preload the "out of memory" error string just in case we run + // out of memory during the compile. + String noMemoryErrorString = getText("rmic.no.memory"); + String stackOverflowErrorString = getText("rmic.stack.overflow"); + + try { + generateClasses(env); + if (!nocompile) { // compile all classes that need compilation + compileAllClasses(env); + } + } catch (OutOfMemoryError ee) { + // The compiler has run out of memory. Use the error string + // which we preloaded. + env.output(noMemoryErrorString); + return false; + } catch (StackOverflowError ee) { + env.output(stackOverflowErrorString); + return false; + } catch (Error ee) { + // We allow the compiler to take an exception silently if a program + // error has previously been detected. Presumably, this makes the + // compiler more robust in the face of bad error recovery. + if (env.nerrors == 0 || env.dump()) { + env.error(0, "fatal.error"); + ee.printStackTrace(out instanceof PrintStream ? + (PrintStream) out : + new PrintStream(out, true)); + } + } catch (Exception ee) { + if (env.nerrors == 0 || env.dump()) { + env.error(0, "fatal.exception"); + ee.printStackTrace(out instanceof PrintStream ? + (PrintStream) out : + new PrintStream(out, true)); + } + } + + env.flushErrors(); + + boolean status = displayErrors(env); + + // last step is to delete generated source files + if (!keepGenerated) { + env.deleteGeneratedFiles(); + } + + // We're done + if (env.verbose()) { + tm = System.currentTimeMillis() - tm; + output(getText("rmic.done_in", Long.toString(tm))); + } + + // Shutdown the environment object and release our resources. + // Note that while this is unneccessary when rmic is invoked + // the command line, there are environments in which rmic + // from is invoked within a server process, so resource + // reclamation is important... + + env.shutdown(); + + sourcePathArg = null; + sysClassPathArg = null; + classPathString = null; + destDir = null; + classes = null; + generatorArgs = null; + generators = null; + environmentClass = null; + program = null; + out = null; + + return status; + } + + private void generateClasses(BatchEnvironment env) { + for (String className : classes) + generateClass(env, getClassIdentifier(env, className)); + } + + void generateClass(BatchEnvironment env, Identifier implClassName) { + ClassDeclaration decl = env.getClassDeclaration(implClassName); + try { + for (Generator gen : generators) + gen.generate(env, destDir, decl.getClassDefinition(env)); + } catch (ClassNotFound ex) { + env.error(0, "rmic.class.not.found", implClassName); + } + } + + boolean displayErrors(BatchEnvironment env) { + List summary = new ArrayList<>(); + + if (env.nerrors > 0) summary.add(getErrorSummary(env)); + if (env.nwarnings > 0) summary.add(getWarningSummary(env)); + if (!summary.isEmpty()) output(String.join(", ", summary)); + + return env.nerrors == 0; + } + + private String getErrorSummary(BatchEnvironment env) { + return env.nerrors == 1 ? getText("rmic.1error") : getText("rmic.errors", env.nerrors); + } + + private String getWarningSummary(BatchEnvironment env) { + return env.nwarnings == 1 ? getText("rmic.1warning") : getText("rmic.warnings", env.nwarnings); + } + + static Identifier getClassIdentifier(BatchEnvironment env, String className) { + Identifier implClassName = Identifier.lookup(className); + + /* + * Fix bugid 4049354: support using '.' as an inner class + * qualifier on the command line (previously, only mangled + * inner class names were understood, like "pkg.Outer$Inner"). + * + * The following method, also used by "javap", resolves the + * given unmangled inner class name to the appropriate + * internal identifier. For example, it translates + * "pkg.Outer.Inner" to "pkg.Outer. Inner". + */ + implClassName = env.resolvePackageQualifiedName(implClassName); + /* + * But if we use such an internal inner class name identifier + * to load the class definition, the Java compiler will notice + * if the impl class is a "private" inner class and then deny + * skeletons (needed unless "-v1.2" is used) the ability to + * cast to it. To work around this problem, we mangle inner + * class name identifiers to their binary "outer" class name: + * "pkg.Outer. Inner" becomes "pkg.Outer$Inner". + */ + implClassName = Names.mangleClass(implClassName); + return implClassName; + } + + /* + * Compile all classes that need to be compiled. + */ + public void compileAllClasses (BatchEnvironment env) + throws ClassNotFound, + IOException, + InterruptedException { + ByteArrayOutputStream buf = new ByteArrayOutputStream(4096); + boolean done; + + do { + done = true; + for (Enumeration e = env.getClasses() ; e.hasMoreElements() ; ) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + done = compileClass(c,buf,env); + } + } while (!done); + } + + /* + * Compile a single class. + * Fallthrough is intentional + */ + @SuppressWarnings({"fallthrough", "deprecation"}) + public boolean compileClass (ClassDeclaration c, + ByteArrayOutputStream buf, + BatchEnvironment env) + throws ClassNotFound, + IOException, + InterruptedException { + boolean done = true; + env.flushErrors(); + SourceClass src; + + switch (c.getStatus()) { + case CS_UNDEFINED: + { + if (!env.dependencies()) { + break; + } + // fall through + } + + case CS_SOURCE: + { + done = false; + env.loadDefinition(c); + if (c.getStatus() != CS_PARSED) { + break; + } + // fall through + } + + case CS_PARSED: + { + if (c.getClassDefinition().isInsideLocal()) { + break; + } + // If we get to here, then compilation is going + // to occur. If the -Xnocompile switch is set + // then fail. Note that this check is required + // here because this method is called from + // generators, not just from within this class... + + if (nocompile) { + throw new IOException("Compilation required, but -Xnocompile option in effect"); + } + + done = false; + + src = (SourceClass)c.getClassDefinition(env); + src.check(env); + c.setDefinition(src, CS_CHECKED); + // fall through + } + + case CS_CHECKED: + { + src = (SourceClass)c.getClassDefinition(env); + // bail out if there were any errors + if (src.getError()) { + c.setDefinition(src, CS_COMPILED); + break; + } + done = false; + buf.reset(); + src.compile(buf); + c.setDefinition(src, CS_COMPILED); + src.cleanup(env); + + if (src.getError() || nowrite) { + break; + } + + String pkgName = c.getName().getQualifier().toString().replace('.', File.separatorChar); + String className = c.getName().getFlatName().toString().replace('.', SIGC_INNERCLASS) + ".class"; + + File file; + if (destDir != null) { + if (pkgName.length() > 0) { + file = new File(destDir, pkgName); + if (!file.exists()) { + file.mkdirs(); + } + file = new File(file, className); + } else { + file = new File(destDir, className); + } + } else { + ClassFile classfile = (ClassFile)src.getSource(); + if (classfile.isZipped()) { + env.error(0, "cant.write", classfile.getPath()); + break; + } + file = new File(classfile.getPath()); + file = new File(file.getParent(), className); + } + + // Create the file + try { + FileOutputStream out = new FileOutputStream(file.getPath()); + buf.writeTo(out); + out.close(); + if (env.verbose()) { + output(getText("rmic.wrote", file.getPath())); + } + } catch (IOException ee) { + env.error(0, "cant.write", file.getPath()); + } + } + } + return done; + } + + /** + * Main program + */ + public static void main(String argv[]) { + Main compiler = new Main(System.out, "rmic"); + System.exit(compiler.compile(argv) ? 0 : 1); + } + + /** + * Return the string value of a named resource in the rmic.properties + * resource bundle. If the resource is not found, null is returned. + */ + public static String getString(String key) { + if (!resourcesInitialized) { + initResources(); + } + + // To enable extensions, search the 'resourcesExt' + // bundle first, followed by the 'resources' bundle... + + if (resourcesExt != null) { + try { + return resourcesExt.getString(key); + } catch (MissingResourceException e) {} + } + + try { + return resources.getString(key); + } catch (MissingResourceException ignore) { + } + return null; + } + + private static boolean resourcesInitialized = false; + private static ResourceBundle resources; + private static ResourceBundle resourcesExt = null; + + private static void initResources() { + try { + resources = + ResourceBundle.getBundle("org.glassfish.rmic.resources.rmic"); + resourcesInitialized = true; + try { + resourcesExt = + ResourceBundle.getBundle("org.glassfish.rmic.resources.rmicext"); + } catch (MissingResourceException e) {} + } catch (MissingResourceException e) { + throw new Error("fatal: missing resource bundle: " + + e.getClassName()); + } + } + + public static String getText(String key) { + String message = getString(key); + if (message == null) { + message = "no text found: \"" + key + "\""; + } + return message; + } + + public static String getText(String key, int num) { + return getText(key, Integer.toString(num), null, null); + } + + public static String getText(String key, String arg0) { + return getText(key, arg0, null, null); + } + + public static String getText(String key, String arg0, String arg1) { + return getText(key, arg0, arg1, null); + } + + public static String getText(String key, + String arg0, String arg1, String arg2) + { + String format = getString(key); + if (format == null) { + format = "no text found: key = \"" + key + "\", " + "arguments = \"{0}\", \"{1}\", \"{2}\""; + } + + String[] args = new String[3]; + args[0] = (arg0 != null ? arg0 : "null"); + args[1] = (arg1 != null ? arg1 : "null"); + args[2] = (arg2 != null ? arg2 : "null"); + + return java.text.MessageFormat.format(format, (Object[]) args); + } + + String[] getGeneratedClassNames(BatchEnvironment environment) { + List result = new ArrayList<>(); + for (ClassDeclaration declaration : environment.getGeneratedClasses()) { + result.add(declaration.getName().toString()); + } + + return result.toArray(new String[result.size()]); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/Names.java b/rmic/src/main/java/org/glassfish/rmic/Names.java new file mode 100644 index 000000000..17eb2fa4b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/Names.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.Identifier; + +/** + * Names provides static utility methods used by other rmic classes + * for dealing with identifiers. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public class Names { + + /** + * Return stub class name for impl class name. + */ + static final public Identifier stubFor(Identifier name) { + return Identifier.lookup(name + "_Stub"); + } + + /** + * Return skeleton class name for impl class name. + */ + static final public Identifier skeletonFor(Identifier name) { + return Identifier.lookup(name + "_Skel"); + } + + /** + * If necessary, convert a class name to its mangled form, i.e. the + * non-inner class name used in the binary representation of + * inner classes. This is necessary to be able to name inner + * classes in the generated source code in places where the language + * does not permit it, such as when synthetically defining an inner + * class outside of its outer class, and for generating file names + * corresponding to inner classes. + * + * Currently this mangling involves modifying the internal names of + * inner classes by converting occurrences of ". " into "$". + * + * This code is taken from the "mangleInnerType" method of + * the "org.glassfish.rmic.tools.java.Type" class; this method cannot be accessed + * itself because it is package protected. + */ + static final public Identifier mangleClass(Identifier className) { + if (!className.isInner()) + return className; + + /* + * Get '.' qualified inner class name (with outer class + * qualification and no package qualification) and replace + * each '.' with '$'. + */ + Identifier mangled = Identifier.lookup( + className.getFlatName().toString() + .replace('.', org.glassfish.rmic.tools.java.Constants.SIGC_INNERCLASS)); + if (mangled.isInner()) + throw new Error("failed to mangle inner class name"); + + // prepend package qualifier back for returned identifier + return Identifier.lookup(className.getQualifier(), mangled); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/RMIConstants.java b/rmic/src/main/java/org/glassfish/rmic/RMIConstants.java new file mode 100644 index 000000000..3157ec7f7 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/RMIConstants.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.Identifier; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public interface RMIConstants extends org.glassfish.rmic.Constants { + + /* + * identifiers for RMI classes referenced by rmic + */ + public static final Identifier idRemoteObject = + Identifier.lookup("java.rmi.server.RemoteObject"); + public static final Identifier idRemoteStub = + Identifier.lookup("java.rmi.server.RemoteStub"); + public static final Identifier idRemoteRef = + Identifier.lookup("java.rmi.server.RemoteRef"); + public static final Identifier idOperation = + Identifier.lookup("java.rmi.server.Operation"); + public static final Identifier idSkeleton = + Identifier.lookup("java.rmi.server.Skeleton"); + public static final Identifier idSkeletonMismatchException = + Identifier.lookup("java.rmi.server.SkeletonMismatchException"); + public static final Identifier idRemoteCall = + Identifier.lookup("java.rmi.server.RemoteCall"); + public static final Identifier idMarshalException = + Identifier.lookup("java.rmi.MarshalException"); + public static final Identifier idUnmarshalException = + Identifier.lookup("java.rmi.UnmarshalException"); + public static final Identifier idUnexpectedException = + Identifier.lookup("java.rmi.UnexpectedException"); + + /* + * stub protocol versions + */ + public static final int STUB_VERSION_1_1 = 1; + public static final int STUB_VERSION_FAT = 2; + public static final int STUB_VERSION_1_2 = 3; + + /** serialVersionUID for all stubs that can use 1.2 protocol */ + public static final long STUB_SERIAL_VERSION_UID = 2; + + /** version number used to seed interface hash computation */ + public static final int INTERFACE_HASH_STUB_VERSION = 1; +} diff --git a/rmic/src/main/java/org/glassfish/rmic/RMIGenerator.java b/rmic/src/main/java/org/glassfish/rmic/RMIGenerator.java new file mode 100644 index 000000000..25df9c628 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/RMIGenerator.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.ClassDefinition; + +import java.io.File; + +/** + * A placeholder to handle the no-longer supported JRMP flags. Any attempt to use them will now result in an error. + * + * @author Peter Jones, Bryan Atsatt + */ +public class RMIGenerator implements RMIConstants, Generator { + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param main Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + main.error("rmic.jrmp.not.supported", main.program); + return false; + } + + /** + * Generate the source files for the stub and/or skeleton classes + * needed by RMI for the given remote implementation class. + * @param env compiler environment + * @param destDir directory for the root of the package hierarchy + * @param cdef definition of remote implementation class + * to generate stubs and/or skeletons for + */ + public void generate(BatchEnvironment env, File destDir, ClassDefinition cdef) { + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/RemoteClass.java b/rmic/src/main/java/org/glassfish/rmic/RemoteClass.java new file mode 100644 index 000000000..f1193130c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/RemoteClass.java @@ -0,0 +1,862 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.MemberDefinition; +import org.glassfish.rmic.tools.java.Type; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +/** + * A RemoteClass object encapsulates RMI-specific information about + * a remote implementation class, i.e. a class that implements + * one or more remote interfaces. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Peter Jones + */ +public class RemoteClass implements org.glassfish.rmic.RMIConstants { + + /** + * Create a RemoteClass object representing the remote meta-information + * of the given class. + * + * Returns true if successful. If the class is not a properly formed + * remote implementation class or if some other error occurs, the + * return value will be null, and errors will have been reported to + * the supplied BatchEnvironment. + */ + public static RemoteClass forClass(BatchEnvironment env, + ClassDefinition implClassDef) + { + RemoteClass rc = new RemoteClass(env, implClassDef); + if (rc.initialize()) { + return rc; + } else { + return null; + } + } + + /** + * Return the ClassDefinition for this class. + */ + public ClassDefinition getClassDefinition() { + return implClassDef; + } + + /** + * Return the name of the class represented by this object. + */ + public Identifier getName() { + return implClassDef.getName(); + } + + /** + * Return an array of ClassDefinitions representing all of the remote + * interfaces implemented by this class. + * + * A remote interface is any interface that extends Remote, + * directly or indirectly. The remote interfaces of a class + * are the interfaces directly listed in either the class's + * "implements" clause, or the "implements" clause of any + * of its superclasses, that are remote interfaces. + * + * The order of the array returned is arbitrary, and some elements + * may be superfluous (i.e., superinterfaces of other interfaces + * in the array). + */ + public ClassDefinition[] getRemoteInterfaces() { + return remoteInterfaces.clone(); + } + + /** + * Return an array of RemoteClass.Method objects representing all of + * the remote methods implemented by this class, i.e. all of the + * methods in the class's remote interfaces. + * + * The methods in the array are ordered according to the comparison + * of the strings consisting of their method name followed by their + * type signature, so each method's index in the array corresponds + * to its "operation number" in the JDK 1.1 version of the + * stub/skeleton protocol. + */ + public Method[] getRemoteMethods() { + return remoteMethods.clone(); + } + + /** + * Return the "interface hash" used to match a stub/skeleton pair for + * this class in the JDK 1.1 version of the stub/skeleton protocol. + */ + public long getInterfaceHash() { + return interfaceHash; + } + + /** + * Return string representation of this object, consisting of + * the string "remote class " followed by the class name. + */ + public String toString() { + return "remote class " + implClassDef.getName().toString(); + } + + /** rmic environment for this object */ + private BatchEnvironment env; + + /** the remote implementation class this object corresponds to */ + private ClassDefinition implClassDef; + + /** remote interfaces implemented by this class */ + private ClassDefinition[] remoteInterfaces; + + /** all the remote methods of this class */ + private Method[] remoteMethods; + + /** stub/skeleton "interface hash" for this class */ + private long interfaceHash; + + /** cached definition for certain classes used in this environment */ + private ClassDefinition defRemote; + private ClassDefinition defException; + private ClassDefinition defRemoteException; + + /** + * Create a RemoteClass instance for the given class. The resulting + * object is not yet initialized. + */ + private RemoteClass(BatchEnvironment env, ClassDefinition implClassDef) { + this.env = env; + this.implClassDef = implClassDef; + } + + /** + * Validate that the remote implementation class is properly formed + * and fill in the data structures required by the public interface. + */ + private boolean initialize() { + /* + * Verify that the "impl" is really a class, not an interface. + */ + if (implClassDef.isInterface()) { + env.error(0, "rmic.cant.make.stubs.for.interface", + implClassDef.getName()); + return false; + } + + /* + * Initialize cached definitions for the Remote interface and + * the RemoteException class. + */ + try { + defRemote = + env.getClassDeclaration(idRemote).getClassDefinition(env); + defException = + env.getClassDeclaration(idJavaLangException). + getClassDefinition(env); + defRemoteException = + env.getClassDeclaration(idRemoteException). + getClassDefinition(env); + } catch (ClassNotFound e) { + env.error(0, "rmic.class.not.found", e.name); + return false; + } + + /* + * Here we find all of the remote interfaces of our remote + * implementation class. For each class up the superclass + * chain, add each directly-implemented interface that + * somehow extends Remote to a list. + */ + Vector remotesImplemented = // list of remote interfaces found + new Vector(); + for (ClassDefinition classDef = implClassDef; + classDef != null;) + { + try { + ClassDeclaration[] interfaces = classDef.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + ClassDefinition interfaceDef = + interfaces[i].getClassDefinition(env); + /* + * Add interface to the list if it extends Remote and + * it is not already there. + */ + if (!remotesImplemented.contains(interfaceDef) && + defRemote.implementedBy(env, interfaces[i])) + { + remotesImplemented.addElement(interfaceDef); + /***** */ + if (env.verbose()) { + System.out.println("[found remote interface: " + + interfaceDef.getName() + "]"); + /***** */ + } + } + } + + /* + * Verify that the candidate remote implementation class + * implements at least one remote interface directly. + */ + if (classDef == implClassDef && remotesImplemented.isEmpty()) { + if (defRemote.implementedBy(env, + implClassDef.getClassDeclaration())) + { + /* + * This error message is used if the class does + * implement a remote interface through one of + * its superclasses, but not directly. + */ + env.error(0, "rmic.must.implement.remote.directly", + implClassDef.getName()); + } else { + /* + * This error message is used if the class never + * implements a remote interface. + */ + env.error(0, "rmic.must.implement.remote", + implClassDef.getName()); + } + return false; + } + + /* + * Get definition for next superclass. + */ + classDef = (classDef.getSuperClass() != null ? + classDef.getSuperClass().getClassDefinition(env) : + null); + + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, classDef.getName()); + return false; + } + } + + /* + * The "remotesImplemented" vector now contains all of the remote + * interfaces directly implemented by the remote class or by any + * of its superclasses. + * + * At this point, we could optimize the list by removing superfluous + * entries, i.e. any interfaces that are implemented by some other + * interface in the list anyway. + * + * This should be correct; would it be worthwhile? + * + * for (int i = 0; i < remotesImplemented.size();) { + * ClassDefinition interfaceDef = + * (ClassDefinition) remotesImplemented.elementAt(i); + * boolean isOtherwiseImplemented = false; + * for (int j = 0; j < remotesImplemented.size; j++) { + * if (j != i && + * interfaceDef.implementedBy(env, (ClassDefinition) + * remotesImplemented.elementAt(j). + * getClassDeclaration())) + * { + * isOtherwiseImplemented = true; + * break; + * } + * } + * if (isOtherwiseImplemented) { + * remotesImplemented.removeElementAt(i); + * } else { + * ++i; + * } + * } + */ + + /* + * Now we collect the methods from all of the remote interfaces + * into a hashtable. + */ + Hashtable methods = new Hashtable(); + boolean errors = false; + for (Enumeration enumeration + = remotesImplemented.elements(); + enumeration.hasMoreElements();) + { + ClassDefinition interfaceDef = enumeration.nextElement(); + if (!collectRemoteMethods(interfaceDef, methods)) + errors = true; + } + if (errors) + return false; + + /* + * Convert vector of remote interfaces to an array + * (order is not important for this array). + */ + remoteInterfaces = new ClassDefinition[remotesImplemented.size()]; + remotesImplemented.copyInto(remoteInterfaces); + + /* + * Sort table of remote methods into an array. The elements are + * sorted in ascending order of the string of the method's name + * and type signature, so that each elements index is equal to + * its operation number of the JDK 1.1 version of the stub/skeleton + * protocol. + */ + String[] orderedKeys = new String[methods.size()]; + int count = 0; + for (Enumeration enumeration = methods.elements(); + enumeration.hasMoreElements();) + { + Method m = enumeration.nextElement(); + String key = m.getNameAndDescriptor(); + int i; + for (i = count; i > 0; --i) { + if (key.compareTo(orderedKeys[i - 1]) >= 0) { + break; + } + orderedKeys[i] = orderedKeys[i - 1]; + } + orderedKeys[i] = key; + ++count; + } + remoteMethods = new Method[methods.size()]; + for (int i = 0; i < remoteMethods.length; i++) { + remoteMethods[i] = methods.get(orderedKeys[i]); + /***** */ + if (env.verbose()) { + System.out.print("[found remote method <" + i + ">: " + + remoteMethods[i].getOperationString()); + ClassDeclaration[] exceptions = + remoteMethods[i].getExceptions(); + if (exceptions.length > 0) + System.out.print(" throws "); + for (int j = 0; j < exceptions.length; j++) { + if (j > 0) + System.out.print(", "); + System.out.print(exceptions[j].getName()); + } + System.out.println("]"); + } + /***** */ + } + + /** + * Finally, pre-compute the interface hash to be used by + * stubs/skeletons for this remote class. + */ + interfaceHash = computeInterfaceHash(); + + return true; + } + + /** + * Collect and validate all methods from given interface and all of + * its superinterfaces as remote methods. Remote methods are added + * to the supplied hashtable. Returns true if successful, + * or false if an error occurred. + */ + private boolean collectRemoteMethods(ClassDefinition interfaceDef, + Hashtable table) + { + if (!interfaceDef.isInterface()) { + throw new Error( + "expected interface, not class: " + interfaceDef.getName()); + } + + /* + * rmic used to enforce that a remote interface could not extend + * a non-remote interface, i.e. an interface that did not itself + * extend from Remote. The current version of rmic does not have + * this restriction, so the following code is now commented out. + * + * Verify that this interface extends Remote, since all interfaces + * extended by a remote interface must implement Remote. + * + * try { + * if (!defRemote.implementedBy(env, + * interfaceDef.getClassDeclaration())) + * { + * env.error(0, "rmic.can.mix.remote.nonremote", + * interfaceDef.getName()); + * return false; + * } + * } catch (ClassNotFound e) { + * env.error(0, "class.not.found", e.name, + * interfaceDef.getName()); + * return false; + * } + */ + + boolean errors = false; + + /* + * Search interface's members for methods. + */ + nextMember: + for (MemberDefinition member = interfaceDef.getFirstMember(); + member != null; + member = member.getNextMember()) + { + if (member.isMethod() && + !member.isConstructor() && !member.isInitializer()) + { + /* + * Verify that each method throws RemoteException. + */ + ClassDeclaration[] exceptions = member.getExceptions(env); + boolean hasRemoteException = false; + for (int i = 0; i < exceptions.length; i++) { + /* + * rmic used to enforce that a remote method had to + * explicitly list RemoteException in its "throws" + * clause; i.e., just throwing Exception was not + * acceptable. The current version of rmic does not + * have this restriction, so the following code is + * now commented out. Instead, the method is + * considered valid if RemoteException is a subclass + * of any of the methods declared exceptions. + * + * if (exceptions[i].getName().equals( + * idRemoteException)) + * { + * hasRemoteException = true; + * break; + * } + */ + try { + if (defRemoteException.subClassOf( + env, exceptions[i])) + { + hasRemoteException = true; + break; + } + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + interfaceDef.getName()); + continue nextMember; + } + } + /* + * If this method did not throw RemoteException as required, + * generate the error but continue, so that multiple such + * errors can be reported. + */ + if (!hasRemoteException) { + env.error(0, "rmic.must.throw.remoteexception", + interfaceDef.getName(), member.toString()); + errors = true; + continue nextMember; + } + + /* + * Verify that the implementation of this method throws only + * java.lang.Exception or its subclasses (fix bugid 4092486). + * JRMP does not support remote methods throwing + * java.lang.Throwable or other subclasses. + */ + try { + MemberDefinition implMethod = implClassDef.findMethod( + env, member.getName(), member.getType()); + if (implMethod != null) { // should not be null + exceptions = implMethod.getExceptions(env); + for (int i = 0; i < exceptions.length; i++) { + if (!defException.superClassOf( + env, exceptions[i])) + { + env.error(0, "rmic.must.only.throw.exception", + implMethod.toString(), + exceptions[i].getName()); + errors = true; + continue nextMember; + } + } + } + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + implClassDef.getName()); + continue nextMember; + } + + /* + * Create RemoteClass.Method object to represent this method + * found in a remote interface. + */ + Method newMethod = new Method(member); + /* + * Store remote method's representation in the table of + * remote methods found, keyed by its name and parameter + * signature. + * + * If the table already contains an entry with the same + * method name and parameter signature, then we must + * replace the old entry with a Method object that + * represents a legal combination of the old and the new + * methods; specifically, the combined method must have + * a throws list that contains (only) all of the checked + * exceptions that can be thrown by both the old or + * the new method (see bugid 4070653). + */ + String key = newMethod.getNameAndDescriptor(); + Method oldMethod = table.get(key); + if (oldMethod != null) { + newMethod = newMethod.mergeWith(oldMethod); + if (newMethod == null) { + errors = true; + continue nextMember; + } + } + table.put(key, newMethod); + } + } + + /* + * Recursively collect methods for all superinterfaces. + */ + try { + ClassDeclaration[] superDefs = interfaceDef.getInterfaces(); + for (int i = 0; i < superDefs.length; i++) { + ClassDefinition superDef = + superDefs[i].getClassDefinition(env); + if (!collectRemoteMethods(superDef, table)) + errors = true; + } + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, interfaceDef.getName()); + return false; + } + + return !errors; + } + + /** + * Compute the "interface hash" of the stub/skeleton pair for this + * remote implementation class. This is the 64-bit value used to + * enforce compatibility between a stub and a skeleton using the + * JDK 1.1 version of the stub/skeleton protocol. + * + * It is calculated using the first 64 bits of a SHA digest. The + * digest is from a stream consisting of the following data: + * (int) stub version number, always 1 + * for each remote method, in order of operation number: + * (UTF) method name + * (UTF) method type signature + * for each declared exception, in alphabetical name order: + * (UTF) name of exception class + * + */ + private long computeInterfaceHash() { + long hash = 0; + ByteArrayOutputStream sink = new ByteArrayOutputStream(512); + try { + MessageDigest md = MessageDigest.getInstance("SHA"); + DataOutputStream out = new DataOutputStream( + new DigestOutputStream(sink, md)); + + out.writeInt(INTERFACE_HASH_STUB_VERSION); + for (int i = 0; i < remoteMethods.length; i++) { + MemberDefinition m = remoteMethods[i].getMemberDefinition(); + Identifier name = m.getName(); + Type type = m.getType(); + + out.writeUTF(name.toString()); + // type signatures already use mangled class names + out.writeUTF(type.getTypeSignature()); + + ClassDeclaration exceptions[] = m.getExceptions(env); + sortClassDeclarations(exceptions); + for (int j = 0; j < exceptions.length; j++) { + out.writeUTF(Names.mangleClass( + exceptions[j].getName()).toString()); + } + } + out.flush(); + + // use only the first 64 bits of the digest for the hash + byte hashArray[] = md.digest(); + for (int i = 0; i < Math.min(8, hashArray.length); i++) { + hash += ((long) (hashArray[i] & 0xFF)) << (i * 8); + } + } catch (IOException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } catch (NoSuchAlgorithmException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } + + return hash; + } + + /** + * Sort array of class declarations alphabetically by their mangled + * fully-qualified class name. This is used to feed a method's exceptions + * in a canonical order into the digest stream for the interface hash + * computation. + */ + private void sortClassDeclarations(ClassDeclaration[] decl) { + for (int i = 1; i < decl.length; i++) { + ClassDeclaration curr = decl[i]; + String name = Names.mangleClass(curr.getName()).toString(); + int j; + for (j = i; j > 0; j--) { + if (name.compareTo( + Names.mangleClass(decl[j - 1].getName()).toString()) >= 0) + { + break; + } + decl[j] = decl[j - 1]; + } + decl[j] = curr; + } + } + + + /** + * A RemoteClass.Method object encapsulates RMI-specific information + * about a particular remote method in the remote implementation class + * represented by the outer instance. + */ + public class Method implements Cloneable { + + /** + * Return the definition of the actual class member corresponing + * to this method of a remote interface. + * + * REMIND: Can this method be removed? + */ + public MemberDefinition getMemberDefinition() { + return memberDef; + } + + /** + * Return the name of this method. + */ + public Identifier getName() { + return memberDef.getName(); + } + + /** + * Return the type of this method. + */ + public Type getType() { + return memberDef.getType(); + } + + /** + * Return an array of the exception classes declared to be + * thrown by this remote method. + * + * For methods with the same name and type signature inherited + * from multiple remote interfaces, the array will contain + * the set of exceptions declared in all of the interfaces' + * methods that can be legally thrown in each of them. + */ + public ClassDeclaration[] getExceptions() { + return exceptions.clone(); + } + + /** + * Return the "method hash" used to identify this remote method + * in the JDK 1.2 version of the stub protocol. + */ + public long getMethodHash() { + return methodHash; + } + + /** + * Return the string representation of this method. + */ + public String toString() { + return memberDef.toString(); + } + + /** + * Return the string representation of this method appropriate + * for the construction of a java.rmi.server.Operation object. + */ + public String getOperationString() { + return memberDef.toString(); + } + + /** + * Return a string consisting of this method's name followed by + * its method descriptor, using the Java VM's notation for + * method descriptors (see section 4.3.3 of The Java Virtual + * Machine Specification). + */ + public String getNameAndDescriptor() { + return memberDef.getName().toString() + + memberDef.getType().getTypeSignature(); + } + + /** + * Member definition for this method, from one of the remote + * interfaces that this method was found in. + * + * Note that this member definition may be only one of several + * member defintions that correspond to this remote method object, + * if several of this class's remote interfaces contain methods + * with the same name and type signature. Therefore, this member + * definition may declare more exceptions thrown that this remote + * method does. + */ + private MemberDefinition memberDef; + + /** stub "method hash" to identify this method */ + private long methodHash; + + /** + * Exceptions declared to be thrown by this remote method. + * + * This list can include superfluous entries, such as + * unchecked exceptions and subclasses of other entries. + */ + private ClassDeclaration[] exceptions; + + /** + * Create a new Method object corresponding to the given + * method definition. + */ + /* + * Temporarily comment out the private modifier until + * the VM allows outer class to access inner class's + * private constructor + */ + /* private */ Method(MemberDefinition memberDef) { + this.memberDef = memberDef; + exceptions = memberDef.getExceptions(env); + methodHash = computeMethodHash(); + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + + /** + * Return a new Method object that is a legal combination of + * this method object and another one. + * + * This requires determining the exceptions declared by the + * combined method, which must be (only) all of the exceptions + * declared in both old Methods that may thrown in either of + * them. + */ + private Method mergeWith(Method other) { + if (!getName().equals(other.getName()) || + !getType().equals(other.getType())) + { + throw new Error("attempt to merge method \"" + + other.getNameAndDescriptor() + "\" with \"" + + getNameAndDescriptor()); + } + + Vector legalExceptions + = new Vector(); + try { + collectCompatibleExceptions( + other.exceptions, exceptions, legalExceptions); + collectCompatibleExceptions( + exceptions, other.exceptions, legalExceptions); + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + getClassDefinition().getName()); + return null; + } + + Method merged = (Method) clone(); + merged.exceptions = new ClassDeclaration[legalExceptions.size()]; + legalExceptions.copyInto(merged.exceptions); + + return merged; + } + + /** + * Add to the supplied list all exceptions in the "from" array + * that are subclasses of an exception in the "with" array. + */ + private void collectCompatibleExceptions(ClassDeclaration[] from, + ClassDeclaration[] with, + Vector list) + throws ClassNotFound + { + for (int i = 0; i < from.length; i++) { + ClassDefinition exceptionDef = from[i].getClassDefinition(env); + if (!list.contains(from[i])) { + for (int j = 0; j < with.length; j++) { + if (exceptionDef.subClassOf(env, with[j])) { + list.addElement(from[i]); + break; + } + } + } + } + } + + /** + * Compute the "method hash" of this remote method. The method + * hash is a long containing the first 64 bits of the SHA digest + * from the UTF encoded string of the method name and descriptor. + * + * REMIND: Should this method share implementation code with + * the outer class's computeInterfaceHash() method? + */ + private long computeMethodHash() { + long hash = 0; + ByteArrayOutputStream sink = new ByteArrayOutputStream(512); + try { + MessageDigest md = MessageDigest.getInstance("SHA"); + DataOutputStream out = new DataOutputStream( + new DigestOutputStream(sink, md)); + + String methodString = getNameAndDescriptor(); + /***** */ + if (env.verbose()) { + System.out.println("[string used for method hash: \"" + + methodString + "\"]"); + } + /***** */ + out.writeUTF(methodString); + + // use only the first 64 bits of the digest for the hash + out.flush(); + byte hashArray[] = md.digest(); + for (int i = 0; i < Math.min(8, hashArray.length); i++) { + hash += ((long) (hashArray[i] & 0xFF)) << (i * 8); + } + } catch (IOException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } catch (NoSuchAlgorithmException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } + + return hash; + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/TypeCode.java b/rmic/src/main/java/org/glassfish/rmic/TypeCode.java new file mode 100644 index 000000000..f7acdad90 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/TypeCode.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import static org.glassfish.rmic.tools.java.Constants.*; + +public enum TypeCode { + BOOLEAN(TC_BOOLEAN) { + @Override + public String format(String s) { + return Boolean.toString(s.equals("1")); + } + }, + BYTE(TC_BYTE), + CHAR(TC_CHAR) { + @Override + public String toValueString(Object value) { + return value == null ? null : "L'" + asCharacter(value) + "'"; + } + + private String asCharacter(Object value) { + return String.valueOf((char) ((Number) value).intValue()); + } + }, + SHORT(TC_SHORT), + INT(TC_INT), + LONG(TC_LONG) { + @Override + public String format(String s) { + return s + "L"; + } + }, + FLOAT(TC_FLOAT) { + @Override + public String format(String s) { + return s + "F"; + } + }, + DOUBLE(TC_DOUBLE) { + @Override + public String format(String s) { + return s + "D"; + } + }, + NULL(TC_NULL), + ARRAY(TC_ARRAY), + CLASS(TC_CLASS), + VOID(TC_VOID), + METHOD(TC_METHOD), + ERROR(TC_ERROR); + + private int tcCode; + + public int tcCode() { + return tcCode; + } + + TypeCode(int tcCode) { + this.tcCode = tcCode; + } + + String format(String s) { + return s; + } + + public String toValueString(Object value) { + return value == null ? null : format(value.toString()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/Util.java b/rmic/src/main/java/org/glassfish/rmic/Util.java new file mode 100644 index 000000000..319ca7c0c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/Util.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +/** + * Util provides static utility methods used by other rmic classes. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Bryan Atsatt + */ + +public class Util implements org.glassfish.rmic.Constants { + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/asm/AsmClass.java b/rmic/src/main/java/org/glassfish/rmic/asm/AsmClass.java new file mode 100644 index 000000000..d53ee9d15 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/asm/AsmClass.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.asm; + +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.Environment; +import org.glassfish.rmic.tools.java.Identifier; + +/** + * This represents a class for RMIC to process. It is built from a class file using ASM. + */ +class AsmClass extends ClassDefinition { + + private final AsmClassFactory factory; + + AsmClass(AsmClassFactory factory, String name, int modifiers, ClassDeclaration declaration, ClassDeclaration superClassDeclaration, ClassDeclaration[] interfaceDeclarations) { + super(name, 0, declaration, modifiers, null, null); + this.factory = factory; + superClass = superClassDeclaration; + interfaces = interfaceDeclarations; + } + + @Override + public void loadNested(Environment env) { + try { + Identifier outerClass = factory.getOuterClassName(getName()); + if (outerClass != null) + this.outerClass = env.getClassDefinition(outerClass); + } catch (ClassNotFound ignore) { + } + } + + private boolean basicCheckDone = false; + private boolean basicChecking = false; + + // This code is copied from BinaryClass.java which ensures that inherited method + // information is gathered. Consider promoting this to the super class. + protected void basicCheck(Environment env) throws ClassNotFound { + if (tracing) env.dtEnter("AsmClass.basicCheck: " + getName()); + + if (basicChecking || basicCheckDone) { + if (tracing) env.dtExit("AsmClass.basicCheck: OK " + getName()); + return; + } + + if (tracing) env.dtEvent("AsmClass.basicCheck: CHECKING " + getName()); + basicChecking = true; + + super.basicCheck(env); + + // Collect inheritance information. + if (doInheritanceChecks) { + collectInheritedMethods(env); + } + + basicCheckDone = true; + basicChecking = false; + if (tracing) env.dtExit("AsmClass.basicCheck: " + getName()); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/asm/AsmClassFactory.java b/rmic/src/main/java/org/glassfish/rmic/asm/AsmClassFactory.java new file mode 100644 index 000000000..fcb40607d --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/asm/AsmClassFactory.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.asm; + +import org.glassfish.rmic.Names; +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassDefinitionFactory; +import org.glassfish.rmic.tools.java.Environment; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.MemberDefinition; +import org.glassfish.rmic.tools.java.Type; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +/** + * A factory for a class definition produced via ASM. + */ +public class AsmClassFactory implements ClassDefinitionFactory { + // This field exists to allow unit testing of the case when ASM is not in the classpath. + @SuppressWarnings("unused") + private static final Boolean simulateMissingASM = false; + + private Map outerClasses = new HashMap<>(); + + public AsmClassFactory() { + if (simulateMissingASM) throw new NoClassDefFoundError(); + } + + /** + * Returns the latest API supported by the active version of ASM. + * @return an integer value + */ + static int getLatestVersion() { + try { + int latest = 0; + for (Field field : Opcodes.class.getDeclaredFields()) { + if (field.getName().startsWith("ASM") && field.getType().equals(int.class)) { + latest = Math.max(latest, field.getInt(Opcodes.class)); + } + } + return latest; + } catch (IllegalAccessException e) { + return Opcodes.ASM6; + } + } + + Identifier getOuterClassName(Identifier className) { + if (isResolvedInnerClassName(className)) + className = Names.mangleClass(className); + return outerClasses.get(className); + } + + // This is needed to compensate for the hack described in Main.getClassIdentifier() + private boolean isResolvedInnerClassName(Identifier className) { + return className.toString().contains(". "); + } + + @Override + public ClassDefinition loadDefinition(InputStream is, Environment env) throws IOException { + ClassDefinitionVisitor visitor = new ClassDefinitionVisitor(env); + ClassReader classReader = new ClassReader(is); + classReader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG); + return visitor.getDefinition(); + } + + class ClassDefinitionVisitor extends ClassVisitor { + private Environment env; + private AsmClass asmClass; + + ClassDefinitionVisitor(Environment env) { + super(getLatestVersion()); + this.env = env; + } + + ClassDefinition getDefinition() { + return asmClass; + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + asmClass = new AsmClass(AsmClassFactory.this, toSourceFileName(name), access, toClassDeclaration(name), + toClassDeclaration(superName), toClassDeclarations(interfaces)); + } + + private String toSourceFileName(String name) { + String className = toClassName(name); + if (className.contains("$")) + className = className.substring(0, className.indexOf("$")); + return className + ".java"; + } + + private String toClassName(String name) { + return name.substring(name.lastIndexOf('/') + 1); + } + + private ClassDeclaration[] toClassDeclarations(String... names) { + ClassDeclaration[] result = new ClassDeclaration[names.length]; + for (int i = 0; i < names.length; i++) + result[i] = new ClassDeclaration(getIdentifier(names[i])); + return result; + } + + private ClassDeclaration toClassDeclaration(String name) { + return name == null ? null : new ClassDeclaration(getIdentifier(name)); + } + + private Identifier getIdentifier(String name) { + return Identifier.lookup(name.replace('/', '.')); + } + + @Override + public void visitInnerClass(String name, String outerName, String innerName, int access) { + if (outerName != null) + outerClasses.put(getIdentifier(name), getIdentifier(outerName)); + } + + @Override + public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { + MemberDefinition definition = new AsmMemberDefinition(0, asmClass, access, TypeFactory.createType(desc), getIdentifier(name), value); + asmClass.addMember(env, definition); + return null; + } + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + MemberDefinition definition = new AsmMemberDefinition(0, asmClass, access, createType(desc), getIdentifier(name), exceptions); + asmClass.addMember(env, definition); + return null; + } + + private Type createType(String desc) { + return TypeFactory.createMethodType(desc); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/asm/AsmMemberDefinition.java b/rmic/src/main/java/org/glassfish/rmic/asm/AsmMemberDefinition.java new file mode 100644 index 000000000..80c077e89 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/asm/AsmMemberDefinition.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.asm; + +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.Environment; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.MemberDefinition; +import org.glassfish.rmic.tools.java.Type; + +import java.util.Vector; + +public class AsmMemberDefinition extends MemberDefinition { + private final ClassDeclaration[] exceptions; + private final String memberValueString; + + /** + * Constructor for a method definition + * @param where the location of the definition relative to the class + * @param clazz the containing class + * @param modifiers the access modifiers + * @param type the constructed type + * @param name the name of the method + * @param exceptions the checked exceptions throwable by the method + */ + AsmMemberDefinition(long where, ClassDefinition clazz, int modifiers, Type type, Identifier name, String[] exceptions) { + super(where, clazz, modifiers, type, name, null, null); + + this.memberValueString = null; + this.exceptions = toClassDeclarations(exceptions); + } + + /** + * Constructor for a field definition + * @param where the location of the definition relative to the class + * @param clazz the containing class + * @param modifiers the access modifiers + * @param type the constructed type + * @param name the name of the method + * @param value the default value for the field + */ + AsmMemberDefinition(long where, ClassDefinition clazz, int modifiers, Type type, Identifier name, Object value) { + super(where, clazz, modifiers, type, name, null, null); + + memberValueString = type.toStringValue(value); + exceptions = null; + } + + private ClassDeclaration[] toClassDeclarations(String[] classNames) { + if (classNames == null) return new ClassDeclaration[0]; + + ClassDeclaration[] result = new ClassDeclaration[classNames.length]; + for (int i = 0; i < classNames.length; i++) + result[i] = new ClassDeclaration(Identifier.lookup(classNames[i].replace('/','.'))); + return result; + + } + + @Override + public String getMemberValueString(Environment env) throws ClassNotFound { + return memberValueString; + } + + @Override + public ClassDeclaration[] getExceptions(Environment env) { + return exceptions; + } + + @Override + public Vector getArguments() { + return null; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/asm/TypeFactory.java b/rmic/src/main/java/org/glassfish/rmic/asm/TypeFactory.java new file mode 100644 index 000000000..81056cefb --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/asm/TypeFactory.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.asm; + +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.Type; + +/** + * A Factory to create MethodType objects from ASM method descriptors. + */ +class TypeFactory { + static Type createType(String descriptor) { + return toRmicType(org.objectweb.asm.Type.getType(descriptor)); + } + + static Type createMethodType(String descriptor) { + org.objectweb.asm.Type returnType = org.objectweb.asm.Type.getReturnType(descriptor); + return Type.tMethod(toRmicType(returnType), toTypeArray(org.objectweb.asm.Type.getArgumentTypes(descriptor))); + } + + private static Type[] toTypeArray(org.objectweb.asm.Type[] argumentTypes) { + Type[] result = new Type[argumentTypes.length]; + for (int i = 0; i < result.length; i++) + result[i] = toRmicType(argumentTypes[i]); + return result; + } + + private static Type toRmicType(org.objectweb.asm.Type asmType) { + switch (asmType.getSort()) { + case org.objectweb.asm.Type.VOID: + return Type.tVoid; + case org.objectweb.asm.Type.BOOLEAN: + return Type.tBoolean; + case org.objectweb.asm.Type.BYTE: + return Type.tByte; + case org.objectweb.asm.Type.SHORT: + return Type.tShort; + case org.objectweb.asm.Type.INT: + return Type.tInt; + case org.objectweb.asm.Type.LONG: + return Type.tLong; + case org.objectweb.asm.Type.FLOAT: + return Type.tFloat; + case org.objectweb.asm.Type.DOUBLE: + return Type.tDouble; + case org.objectweb.asm.Type.CHAR: + return Type.tChar; + case org.objectweb.asm.Type.ARRAY: + return toArrayType(asmType); + default: + return Type.tClass(Identifier.lookup(asmType.getClassName())); + } + } + + private static Type toArrayType(org.objectweb.asm.Type asmType) { + Type type = toRmicType(asmType.getElementType()); + for (int i = 0; i < asmType.getDimensions(); i++) + type = Type.tArray(type); + return type; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/AbstractType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/AbstractType.java new file mode 100644 index 000000000..5d62dd6bf --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/AbstractType.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; + +import java.util.Vector; + +/** + * AbstractType represents any non-special interface which does not + * inherit from java.rmi.Remote, for which all methods throw RemoteException. + *

                + * The static forAbstract(...) method must be used to obtain an instance, and will + * return null if the ClassDefinition is non-conforming. + * @author Bryan Atsatt + */ +public class AbstractType extends RemoteType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an AbstractType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static AbstractType forAbstract(ClassDefinition classDef, + ContextStack stack, + boolean quiet) + { + boolean doPop = false; + AbstractType result = null; + + try { + + // Do we already have it? + + org.glassfish.rmic.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof AbstractType)) return null; // False hit. + + // Yep, so return it... + + return (AbstractType) existing; + + } + + // Could this be an abstract? + + if (couldBeAbstract(stack,classDef,quiet)) { + + // Yes, so try it... + + AbstractType it = new AbstractType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(quiet,stack)) { + stack.pop(true); + result = it; + } else { + removeType(theType,stack); + stack.pop(false); + } + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + } + + return result; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Abstract interface"; + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a AbstractType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private AbstractType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_ABSTRACT | TM_INTERFACE | TM_COMPOUND); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + + private static boolean couldBeAbstract(ContextStack stack, ClassDefinition classDef, + boolean quiet) { + + // Return true if interface and not remote... + + boolean result = false; + + if (classDef.isInterface()) { + BatchEnvironment env = stack.getEnv(); + + try { + result = ! env.defRemote.implementedBy(env, classDef.getClassDeclaration()); + if (!result) failedConstraint(15,quiet,stack,classDef.getName()); + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } else { + failedConstraint(14,quiet,stack,classDef.getName()); + } + + + return result; + } + + + /** + * Initialize this instance. + */ + private boolean initialize (boolean quiet,ContextStack stack) { + + boolean result = false; + ClassDefinition self = getClassDefinition(); + + try { + + // Get methods... + + Vector directMethods = new Vector(); + + if (addAllMethods(self,directMethods,true,quiet,stack) != null) { + + // Do we have any methods? + + boolean validMethods = true; + + if (directMethods.size() > 0) { + + // Yes. Walk 'em, ensuring each is a valid remote method... + + for (int i = 0; i < directMethods.size(); i++) { + + if (! isConformingRemoteMethod((Method) directMethods.elementAt(i),true)) { + validMethods = false; + } + } + } + + if (validMethods) { + + // We're ok, so pass 'em up... + + result = initialize(null,directMethods,null,stack,quiet); + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ArrayType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ArrayType.java new file mode 100644 index 000000000..b7eeec717 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ArrayType.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import java.lang.reflect.Array; +import java.util.HashSet; +import java.util.Vector; + +/** + * ArrayType is a wrapper for any of the other types. The getElementType() + * method can be used to get the array element type. The getArrayDimension() + * method can be used to get the array dimension. + * + * @author Bryan Atsatt + */ +public class ArrayType extends Type { + + private Type type; + private int arrayDimension; + private String brackets; + private String bracketsSig; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an ArrayType object for the given type. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static ArrayType forArray( org.glassfish.rmic.tools.java.Type theType, + ContextStack stack) { + + + ArrayType result = null; + org.glassfish.rmic.tools.java.Type arrayType = theType; + + if (arrayType.getTypeCode() == TC_ARRAY) { + + // Find real type... + + while (arrayType.getTypeCode() == TC_ARRAY) { + arrayType = arrayType.getElementType(); + } + + // Do we already have it? + + Type existing = getType(theType,stack); + if (existing != null) { + + if (!(existing instanceof ArrayType)) return null; // False hit. + + // Yep, so return it... + + return (ArrayType) existing; + } + + // Now try to make a Type from it... + + Type temp = CompoundType.makeType(arrayType,null,stack); + + if (temp != null) { + + // Got a valid one. Make an array type... + + result = new ArrayType(stack,temp,theType.getArrayDimension()); + + // Add it... + + putType(theType,result,stack); + + // Do the stack thing in case tracing on... + + stack.push(result); + stack.pop(true); + } + } + + return result; + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public String getSignature() { + return bracketsSig + type.getSignature(); + } + + /** + * Get element type. Returns null if not an array. + */ + public Type getElementType () { + return type; + } + + /** + * Get array dimension. Returns zero if not an array. + */ + public int getArrayDimension () { + return arrayDimension; + } + + /** + * Get brackets string. Returns "" if not an array. + */ + public String getArrayBrackets () { + return brackets; + } + + /** + * Return a string representation of this type. + */ + public String toString () { + return getQualifiedName() + brackets; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Array of " + type.getTypeDescription(); + } + + + /** + * Return the name of this type. For arrays, will include "[]" if useIDLNames == false. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public String getTypeName ( boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) { + if (useIDLNames) { + return super.getTypeName(useQualifiedNames,useIDLNames,globalIDLNames); + } else { + return super.getTypeName(useQualifiedNames,useIDLNames,globalIDLNames) + brackets; + } + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + if (type.getStatus() != STATUS_VALID) { + type = getValidType(type); + } + } + + /* + * Add matching types to list. Return true if this type has not + * been previously checked, false otherwise. + */ + protected boolean addTypes (int typeCodeFilter, + HashSet checked, + Vector matching) { + + // Check self. + + boolean result = super.addTypes(typeCodeFilter,checked,matching); + + // Have we been checked before? + + if (result) { + + // No, so add element type... + + getElementType().addTypes(typeCodeFilter,checked,matching); + } + + return result; + } + + /** + * Create an ArrayType instance for the given type. The resulting + * object is not yet completely initialized. + */ + private ArrayType(ContextStack stack, Type type, int arrayDimension) { + super(stack,TYPE_ARRAY); + this.type = type; + this.arrayDimension = arrayDimension; + + // Create our brackets string... + + brackets = ""; + bracketsSig = ""; + for (int i = 0; i < arrayDimension; i ++) { + brackets += "[]"; + bracketsSig += "["; + } + + // Now set our names... + + String idlName = IDLNames.getArrayName(type,arrayDimension); + String[] module = IDLNames.getArrayModuleNames(type); + setNames(type.getIdentifier(),module,idlName); + + // Set our repositoryID... + + setRepositoryID(); + } + + + /* + * Load a Class instance. Return null if fail. + */ + protected Class loadClass() { + Class result = null; + Class elementClass = type.getClassInstance(); + if (elementClass != null) { + result = Array.newInstance(elementClass, new int[arrayDimension]).getClass(); + } + return result; + } + + /** + * Release all resources + */ + protected void destroy () { + super.destroy(); + if (type != null) { + type.destroy(); + type = null; + } + brackets = null; + bracketsSig = null; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/BatchEnvironment.java b/rmic/src/main/java/org/glassfish/rmic/iiop/BatchEnvironment.java new file mode 100644 index 000000000..6bf9fa12c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/BatchEnvironment.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.ClassPath; + +import java.io.File; +import java.io.OutputStream; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Iterator; + +/** + * BatchEnvironment for iiop extends rmic's version to add + * parse state. + */ +public class BatchEnvironment extends org.glassfish.rmic.BatchEnvironment implements Constants { + + /* + * If the following flag is true, then the IDL generator can map + * the methods and constants of non-conforming types. However, + * this is very expensive, so the default should be false. + */ + private boolean parseNonConforming = false; + + /** + * This flag indicates that the stubs and ties need to be generated without + * the package prefix (org.omg.stub). + */ + private boolean standardPackage; + + /* Common objects used within package */ + + HashSet alreadyChecked = new HashSet(); + Hashtable allTypes = new Hashtable(3001, 0.5f); + Hashtable invalidTypes = new Hashtable(256, 0.5f); + DirectoryLoader loader = null; + ClassPathLoader classPathLoader = null; + Hashtable nameContexts = null; + Hashtable namesCache = new Hashtable(); + NameContext modulesContext = new NameContext(false); + + ClassDefinition defRemote = null; + ClassDefinition defError = null; + ClassDefinition defException = null; + ClassDefinition defRemoteException = null; + ClassDefinition defCorbaObject = null; + ClassDefinition defSerializable = null; + ClassDefinition defExternalizable = null; + ClassDefinition defThrowable = null; + ClassDefinition defRuntimeException = null; + ClassDefinition defIDLEntity = null; + ClassDefinition defValueBase = null; + + org.glassfish.rmic.tools.java.Type typeRemoteException = null; + org.glassfish.rmic.tools.java.Type typeIOException = null; + org.glassfish.rmic.tools.java.Type typeException = null; + org.glassfish.rmic.tools.java.Type typeThrowable = null; + + ContextStack contextStack = null; + + /** + * Create a BatchEnvironment for rmic with the given class path, + * stream for messages and the destination directory. + */ + public BatchEnvironment(OutputStream out, ClassPath path, File destinationDir) { + + super(out, path, destinationDir); + + // Make sure we have our definitions... + + try { + defRemote = + getClassDeclaration(idRemote).getClassDefinition(this); + defError = + getClassDeclaration(idJavaLangError).getClassDefinition(this); + defException = + getClassDeclaration(idJavaLangException).getClassDefinition(this); + defRemoteException = + getClassDeclaration(idRemoteException).getClassDefinition(this); + defCorbaObject = + getClassDeclaration(idCorbaObject).getClassDefinition(this); + defSerializable = + getClassDeclaration(idJavaIoSerializable).getClassDefinition(this); + defRuntimeException = + getClassDeclaration(idJavaLangRuntimeException).getClassDefinition(this); + defExternalizable = + getClassDeclaration(idJavaIoExternalizable).getClassDefinition(this); + defThrowable= + getClassDeclaration(idJavaLangThrowable).getClassDefinition(this); + defIDLEntity= + getClassDeclaration(idIDLEntity).getClassDefinition(this); + defValueBase= + getClassDeclaration(idValueBase).getClassDefinition(this); + typeRemoteException = defRemoteException.getClassDeclaration().getType(); + typeException = defException.getClassDeclaration().getType(); + typeIOException = getClassDeclaration(idJavaIoIOException).getType(); + typeThrowable = getClassDeclaration(idJavaLangThrowable).getType(); + + classPathLoader = new ClassPathLoader(path); + + } catch (ClassNotFound e) { + error(0, "rmic.class.not.found", e.name); + throw new Error(); + } + } + + /** + * Return whether or not to parse non-conforming types. + */ + public boolean getParseNonConforming () { + return parseNonConforming; + } + + /** + * Set whether or not to parse non-conforming types. + */ + public void setParseNonConforming (boolean parseEm) { + + // If we are transitioning from not parsing to + // parsing, we need to throw out any previously + // parsed types... + + if (parseEm && !parseNonConforming) { + reset(); + } + + parseNonConforming = parseEm; + } + + void setStandardPackage(boolean standardPackage) { + this.standardPackage = standardPackage; + } + + boolean getStandardPackage() { + return standardPackage; + } + + /** + * Clear out any data from previous executions. + */ + public void reset () { + + // First, find all Type instances and call destroy() + // on them... + + for (Enumeration e = allTypes.elements() ; e.hasMoreElements() ;) { + Type type = (Type) e.nextElement(); + type.destroy(); + } + + for (Enumeration e = invalidTypes.keys() ; e.hasMoreElements() ;) { + Type type = (Type) e.nextElement(); + type.destroy(); + } + + for (Iterator e = alreadyChecked.iterator() ; e.hasNext() ;) { + Type type = (Type) e.next(); + type.destroy(); + } + + if (contextStack != null) contextStack.clear(); + + // Remove and clear all NameContexts in the + // nameContexts cache... + + if (nameContexts != null) { + for (Enumeration e = nameContexts.elements() ; e.hasMoreElements() ;) { + NameContext context = (NameContext) e.nextElement(); + context.clear(); + } + nameContexts.clear(); + } + + // Now remove all table entries... + + allTypes.clear(); + invalidTypes.clear(); + alreadyChecked.clear(); + namesCache.clear(); + modulesContext.clear(); + + // Clean up remaining... + loader = null; + parseNonConforming = false; + + // REVISIT - can't clean up classPathLoader here + } + + /** + * Release resources, if any. + */ + public void shutdown() { + if (alreadyChecked != null) { + //System.out.println(); + //System.out.println("allTypes.size() = "+ allTypes.size()); + //System.out.println(" InstanceCount before reset = "+Type.instanceCount); + reset(); + //System.out.println(" InstanceCount AFTER reset = "+Type.instanceCount); + + alreadyChecked = null; + allTypes = null; + invalidTypes = null; + nameContexts = null; + namesCache = null; + modulesContext = null; + defRemote = null; + defError = null; + defException = null; + defRemoteException = null; + defCorbaObject = null; + defSerializable = null; + defExternalizable = null; + defThrowable = null; + defRuntimeException = null; + defIDLEntity = null; + defValueBase = null; + typeRemoteException = null; + typeIOException = null; + typeException = null; + typeThrowable = null; + + super.shutdown(); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ClassPathLoader.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ClassPathLoader.java new file mode 100644 index 000000000..37ed3a3de --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ClassPathLoader.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2000, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassFile; +import org.glassfish.rmic.tools.java.ClassPath; + +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; + +/** + * A ClassLoader that will ultimately use a given org.glassfish.rmic.tools.java.ClassPath to + * find the desired file. This works for any JAR files specified in the given + * ClassPath as well -- reusing all of that wonderful org.glassfish.rmic.tools.java code. + * + *@author Everett Anderson + */ +public class ClassPathLoader extends ClassLoader +{ + private ClassPath classPath; + + public ClassPathLoader(ClassPath classPath) { + this.classPath = classPath; + } + + // Called by the super class + protected Class findClass(String name) throws ClassNotFoundException + { + byte[] b = loadClassData(name); + return defineClass(name, b, 0, b.length); + } + + /** + * Load the class with the given fully qualified name from the ClassPath. + */ + private byte[] loadClassData(String className) + throws ClassNotFoundException + { + // Build the file name and subdirectory from the + // class name + String filename = className.replace('.', File.separatorChar) + + ".class"; + + // Have ClassPath find the file for us, and wrap it in a + // ClassFile. Note: This is where it looks inside jar files that + // are specified in the path. + ClassFile classFile = classPath.getFile(filename); + + if (classFile != null) { + + // Provide the most specific reason for failure in addition + // to ClassNotFound + Exception reportedError = null; + byte data[] = null; + + try { + // ClassFile is beautiful because it shields us from + // knowing if it's a separate file or an entry in a + // jar file. + DataInputStream input + = new DataInputStream(classFile.getInputStream()); + + // Can't rely on input available() since it will be + // something unusual if it's a jar file! May need + // to worry about a possible problem if someone + // makes a jar file entry with a size greater than + // max int. + data = new byte[(int)classFile.length()]; + + try { + input.readFully(data); + } catch (IOException ex) { + // Something actually went wrong reading the file. This + // is a real error so save it to report it. + data = null; + reportedError = ex; + } finally { + // Just don't care if there's an exception on close! + // I hate that close can throw an IOException! + try { input.close(); } catch (IOException ex) {} + } + } catch (IOException ex) { + // Couldn't get the input stream for the file. This is + // probably also a real error. + reportedError = ex; + } + + if (data == null) + throw new ClassNotFoundException(className, reportedError); + + return data; + } + + // Couldn't find the file in the class path. + throw new ClassNotFoundException(className); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ClassType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ClassType.java new file mode 100644 index 000000000..bb2e5fb41 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ClassType.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.IndentingWriter; +import java.io.IOException; + +/** + * ClassType is an abstract base representing any non-special class + * type. + * + * @author Bryan Atsatt + */ +public abstract class ClassType extends CompoundType { + + private ClassType parent; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Return the parent class of this type. Returns null if this + * type is an interface or if there is no parent. + */ + public ClassType getSuperclass() { + return parent; + } + + + /** + * Print this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + if (isInner()) { + writer.p("// " + getTypeDescription() + " (INNER)"); + } else { + writer.p("// " + getTypeDescription()); + } + writer.pln(" (" + getRepositoryID() + ")\n"); + + printPackageOpen(writer,useIDLNames); + + if (!useIDLNames) { + writer.p("public "); + } + + String prefix = ""; + writer.p("class " + getTypeName(false,useIDLNames,false)); + if (printExtends(writer,useQualifiedNames,useIDLNames,globalIDLNames)) { + prefix = ","; + } + printImplements(writer,prefix,useQualifiedNames,useIDLNames,globalIDLNames); + writer.plnI(" {"); + printMembers(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + printMethods(writer,useQualifiedNames,useIDLNames,globalIDLNames); + + if (useIDLNames) { + writer.pOln("};"); + } else { + writer.pOln("}"); + } + + printPackageClose(writer,useIDLNames); + } + + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + protected void destroy () { + if (!destroyed) { + super.destroy(); + if (parent != null) { + parent.destroy(); + parent = null; + } + } + } + + /** + * Create a ClassType instance for the given class. NOTE: This constructor + * is ONLY for SpecialClassType. + */ + protected ClassType(ContextStack stack, int typeCode, ClassDefinition classDef) { + super(stack,typeCode,classDef); // Call special parent constructor. + if ((typeCode & TM_CLASS) == 0 && classDef.isInterface()) { + throw new CompilerError("Not a class"); + } + parent = null; + } + + /** + * Create a ClassType instance for the given class. NOTE: This constructor + * is ONLY for ImplementationType. It does not walk the parent chain. + */ + protected ClassType(int typeCode, ClassDefinition classDef,ContextStack stack) { + super(stack,classDef,typeCode); + + if ((typeCode & TM_CLASS) == 0 && classDef.isInterface()) { + throw new CompilerError("Not a class"); + } + parent = null; + } + + /** + * Create an ClassType instance for the given class. The resulting + * object is not yet completely initialized. Subclasses must call + * initialize(directInterfaces,directInterfaces,directConstants); + */ + protected ClassType(ContextStack stack, + ClassDefinition classDef, + int typeCode) { + super(stack,classDef,typeCode); + if ((typeCode & TM_CLASS) == 0 && classDef.isInterface()) { + throw new CompilerError("Not a class"); + } + parent = null; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + super.swapInvalidTypes(); + if (parent != null && parent.getStatus() != STATUS_VALID) { + parent = (ClassType) getValidType(parent); + } + } + + /** + * Modify the type description with exception info. + */ + public String addExceptionDescription (String typeDesc) { + if (isException) { + if (isCheckedException) { + typeDesc = typeDesc + " - Checked Exception"; + } else { + typeDesc = typeDesc + " - Unchecked Exception"; + } + } + return typeDesc; + } + + + protected boolean initParents(ContextStack stack) { + + stack.setNewContextCode(ContextStack.EXTENDS); + BatchEnvironment env = stack.getEnv(); + + // Init parent... + + boolean result = true; + + try { + ClassDeclaration parentDecl = getClassDefinition().getSuperClass(env); + if (parentDecl != null) { + ClassDefinition parentDef = parentDecl.getClassDefinition(env); + parent = (ClassType) makeType(parentDef.getType(),parentDef,stack); + if (parent == null) { + result = false; + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + throw new CompilerError("ClassType constructor"); + } + + return result; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/CompoundType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/CompoundType.java new file mode 100644 index 000000000..9411b16e3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/CompoundType.java @@ -0,0 +1,2644 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.MemberDefinition; +import org.glassfish.rmic.tools.tree.LocalMember; +import org.glassfish.rmic.tools.tree.Node; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Vector; + +/** + * A CompoundType is an abstract base class for all IIOP class and + * interface types. + * + * @author Bryan Atsatt + */ +public abstract class CompoundType extends Type { + + protected Method[] methods; + protected InterfaceType[] interfaces; + protected Member[] members; + protected ClassDefinition classDef; + protected ClassDeclaration classDecl; + + protected boolean isCORBAObject = false; + protected boolean isIDLEntity = false; + protected boolean isAbstractBase = false; + protected boolean isValueBase = false; + protected boolean isCORBAUserException = false; + protected boolean isException = false; + protected boolean isCheckedException = false; + protected boolean isRemoteExceptionOrSubclass = false; + protected String idlExceptionName; + protected String qualifiedIDLExceptionName; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Return true if this type implements + * org.omg.CORBA.Object. + */ + public boolean isCORBAObject () { + return isCORBAObject; + } + + /** + * Return true if this type implements + * org.omg.CORBA.portable.IDLEntity. + */ + public boolean isIDLEntity () { + return isIDLEntity; + } + + /** + * Return true if this type implements + * org.omg.CORBA.portable.ValueBase. + */ + public boolean isValueBase () { + return isValueBase; + } + + /** + * Return true if this type is a CORBA + * abstract interface. + */ + public boolean isAbstractBase () { + return isAbstractBase; + } + + /** + * Return true if this type is an exception. + */ + public boolean isException () { + return isException; + } + + /** + * Return true if this type is a "checked" exception. + * Result if valid iff isException() returns true. + */ + public boolean isCheckedException () { + return isCheckedException; + } + + /** + * Return true if this type is a java.rmi.RemoteException + * or one of its subclasses. Result if valid iff isException() + * returns true. + */ + public boolean isRemoteExceptionOrSubclass () { + return isRemoteExceptionOrSubclass; + } + + /** + * Return true if this type is exactly + * org.omg.CORBA.UserException. + */ + public boolean isCORBAUserException () { + return isCORBAUserException; + } + + /** + * Return true if this type implements + * {@code isIDLEntity() && isException()}. + */ + public boolean isIDLEntityException () { + return isIDLEntity() && isException(); + } + /** + * Return true if {@code isIDLEntity() && !isValueBase() + * && !isAbstractBase() && !isCORBAObject() + * && !isIDLEntityException()}. + */ + public boolean isBoxed () { + return (isIDLEntity() && !isValueBase() && + !isAbstractBase() && !isCORBAObject() && + !isIDLEntityException()); + } + + /** + * If this type represents an exception, return the + * IDL name including the "Ex" mangling, otherwise + * return null. + */ + public String getIDLExceptionName () { + return idlExceptionName; + } + + /** + * If this type represents an exception, return the + * qualified IDL name including the "Ex" mangling, + * otherwise return null. + * @param global If true, prepends "::". + */ + public String getQualifiedIDLExceptionName (boolean global) { + if (qualifiedIDLExceptionName != null && + global && + getIDLModuleNames().length > 0) { + return IDL_NAME_SEPARATOR + qualifiedIDLExceptionName; + } else { + return qualifiedIDLExceptionName; + } + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public String getSignature() { + String sig = classDecl.getType().getTypeSignature(); + if (sig.endsWith(";")) { + sig = sig.substring(0,sig.length()-1); + } + return sig; + } + + /** + * Return the ClassDeclaration for this type. + */ + public ClassDeclaration getClassDeclaration() { + return classDecl; + } + + /** + * Return the ClassDefinition for this type. + */ + public ClassDefinition getClassDefinition() { + return classDef; + } + + /** + * Return the parent class of this type. Returns null if this + * type is an interface or if there is no parent. + */ + public ClassType getSuperclass() { + return null; + } + + /** + * Return an array of interfaces directly implemented by this type. + *

                + * The order of the array returned is arbitrary. + */ + public InterfaceType[] getInterfaces() { + if( interfaces != null ) { + return (InterfaceType[]) interfaces.clone(); + } + return null; + } + + /** + * Return an array of Type.Method objects representing all + * of the methods implemented directly by this type. + */ + public Method[] getMethods() { + if( methods != null ) { + return (Method[]) methods.clone(); + } + return null; + } + + /** + * Return an array of Type.Member objects representing all of + * the data members directly implemented by this interface. + */ + public Member[] getMembers() { + if( members != null ) { + return (Member[]) members.clone(); + } + return null; + } + + /** + * Create a CompoundType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + static CompoundType forCompound(ClassDefinition classDef, + ContextStack stack) { + CompoundType result = null; + + try { + result = (CompoundType) makeType(classDef.getType(),classDef,stack); + } catch (ClassCastException ignored) {} + + return result; + } + + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Release all resources. + */ + protected void destroy () { + if (!destroyed) { + super.destroy(); + + if (methods != null) { + for (int i = 0; i < methods.length; i++) { + if (methods[i] != null) methods[i].destroy(); + } + methods = null; + } + + if (interfaces != null) { + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i] != null) interfaces[i].destroy(); + } + interfaces = null; + } + + if (members != null) { + for (int i = 0; i < members.length; i++) { + if (members[i] != null) members[i].destroy(); + } + members = null; + } + + classDef = null; + classDecl = null; + } + } + + /* + * Load a Class instance. Return null if fail. + */ + protected Class loadClass() { + + Class ourClass = null; + + // Now try to get the Class... + // The outer try block is there for people who might want to use + // the compiler at run-time of their AS. + // They could set and use their own context class loader for loading + // classes directly. + try { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + ourClass = cl.loadClass(getQualifiedName()); + } catch(ClassNotFoundException cfe) { + + try { + ourClass = env.classPathLoader.loadClass(getQualifiedName()); + } catch (NullPointerException e) { + // This should never happen + } catch (ClassNotFoundException e) { + // Fall through to the next case (which is to look in the + // output directory for generated files) + } + } + + /* This piece of code used to cause the compiler to ignore jar files + on its classpath + try { + ourClass = Util.loadClass(getQualifiedName(),null,null); + } catch (ClassNotFoundException e) { + } catch (LinkageError e) { + } + */ + + if (ourClass == null) { + + // Try one last thing. If the class was compiled into + // a directory that's not in the classpath, the load + // will fail. Let's get the bits off the disk and load + // it directly... + + if (env.loader == null) { + File destDir = env.getDestinationDir(); + if (destDir == null) { + destDir = new File("."); + } + env.loader = new DirectoryLoader(destDir); + } + + try { + ourClass = env.loader.loadClass(getQualifiedName()); + } catch (Exception e) {} + } + + return ourClass; + } + + // Print "extends XX" + + protected boolean printExtends (IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + ClassType parent = getSuperclass(); + + if (parent != null && (!useIDLNames || + (!parent.isType(TYPE_ANY) && !parent.isType(TYPE_CORBA_OBJECT)))) { + writer.p(" extends "); + parent.printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + return true; + } + return false; + } + + // Print "implements XX, YY" + + protected void printImplements (IndentingWriter writer, + String prefix, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + InterfaceType[] interfaces = getInterfaces(); + + String adjective = " implements"; + + if (isInterface()) { + adjective = " extends"; + } + + if (useIDLNames) { + adjective = ":"; + } + + for (int i = 0; i < interfaces.length; i++) { + if (!useIDLNames || (!interfaces[i].isType(TYPE_ANY) && !interfaces[i].isType(TYPE_CORBA_OBJECT))) { + if (i == 0) { + writer.p(prefix + adjective + " "); + } else { + writer.p(", "); + } + interfaces[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + } + + // Print members + + protected void printMembers ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + CompoundType.Member[] members = getMembers(); + + for (int i = 0; i < members.length; i++) { + if (!members[i].isInnerClassDeclaration()) { + Type it = members[i].getType(); + String visibility = members[i].getVisibility(); + String name; + + if (useIDLNames) { + name = members[i].getIDLName(); + } else { + name = members[i].getName(); + } + + String value = members[i].getValue(); + + writer.p(visibility); + if (visibility.length() > 0) { + writer.p(" "); + } + it.printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.p(" " + name); + + if (value != null) { + writer.pln(" = " + value + ";"); + } else { + writer.pln(";"); + } + } + } + } + + // Print methods + + protected void printMethods ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + CompoundType.Method[] methods = getMethods(); + + for (int m = 0; m < methods.length; m++) { + CompoundType.Method theMethod = methods[m]; + printMethod(theMethod,writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + + // Print a method... + + protected void printMethod (CompoundType.Method it, + IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + + // Write visibility... + + String visibility = it.getVisibility(); + + writer.p(visibility); + if (visibility.length() > 0) { + writer.p(" "); + } + + // Write return type... + + it.getReturnType().printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + + // Write method name... + + if (useIDLNames) { + writer.p(" " + it.getIDLName()); + } else { + writer.p(" " + it.getName()); + } + + // Write arguments... + + writer.p(" ("); + Type[] args = it.getArguments(); + String[] argNames = it.getArgumentNames(); + + for (int i = 0; i < args.length; i++) { + if (i > 0) { + writer.p(", "); + } + + if (useIDLNames) { + writer.p("in "); + } + + args[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.p(" " + argNames[i]); + } + writer.p(")"); + + // Write exceptions... + + ClassType[] exceptions; + + if (isType(TYPE_IMPLEMENTATION)) { + exceptions = it.getImplExceptions(); + } else { + exceptions = it.getExceptions(); + } + + for (int i = 0; i < exceptions.length; i++) { + if (i == 0) { + if (useIDLNames) { + writer.p(" raises ("); + } else { + writer.p(" throws "); + } + } else { + writer.p(", "); + } + + if (useIDLNames) { + if (useQualifiedNames) { + writer.p(exceptions[i].getQualifiedIDLExceptionName(globalIDLNames)); + } else { + writer.p(exceptions[i].getIDLExceptionName()); + } + writer.p(" [a.k.a. "); + exceptions[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.p("]"); + } else { + exceptions[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + + if (useIDLNames && exceptions.length > 0) { + writer.p(")"); + } + + if (it.isInherited()) { + writer.p(" // Inherited from "); + writer.p(it.getDeclaredBy()); + } + + writer.pln(";"); + } + + /** + * Create a CompoundType instance for the given class. NOTE: This constructor + * is ONLY for SpecialClassType and SpecialInterfaceType. + */ + protected CompoundType(ContextStack stack, int typeCode, ClassDefinition classDef) { + super(stack,typeCode); + this.classDef = classDef; + classDecl = classDef.getClassDeclaration(); + interfaces = new InterfaceType[0]; + methods = new Method[0]; + members = new Member[0]; + + // If we are an inner class/interface, reset the type codes... + + if (classDef.isInnerClass()) { + setTypeCode(typeCode | TM_INNER); + } + + // Set special flags... + + setFlags(); + } + + private void setFlags() { + + try { + + // Set our special interface flags... + + isCORBAObject = env.defCorbaObject.implementedBy(env,classDecl); + isIDLEntity = env.defIDLEntity.implementedBy(env,classDecl); + isValueBase = env.defValueBase.implementedBy(env,classDecl); + isAbstractBase = isInterface() && // Interface, not a class. + isIDLEntity && // Implements IDLEntity. + !isValueBase && // Does not implement ValueBase. + !isCORBAObject; // Does not implement org.omg.CORBA.Object; + isCORBAUserException = (classDecl.getName() == idCorbaUserException); + + // Is this an exception? + + if (env.defThrowable.implementedBy(env, classDecl)) { + + // Yes... + + isException = true; + + // Is it a checked exception? + + if (env.defRuntimeException.implementedBy(env,classDecl) || + env.defError.implementedBy(env,classDecl)) { + isCheckedException = false; + } else { + isCheckedException = true; + } + + // Is it java.rmi.RemoteException or a subclass? + + if (env.defRemoteException.implementedBy(env,classDecl)) { + isRemoteExceptionOrSubclass = true; + } else { + isRemoteExceptionOrSubclass = false; + } + } else { + isException = false; + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } + + /** + * Create a CompoundType instance for the given class. The resulting + * object is not yet completely initialized. + */ + protected CompoundType(ContextStack stack, ClassDefinition classDef, + int typeCode) { + super(stack,typeCode); + this.classDef = classDef; + classDecl = classDef.getClassDeclaration(); + + // If we are an inner class/interface, reset the type codes... + + if (classDef.isInnerClass()) { + setTypeCode(typeCode | TM_INNER); + } + + // Set special flags... + + setFlags(); + + // Set names... + + Identifier id = classDef.getName(); + String idlName; + String[] idlModuleNames; + + try { + + // These can fail if we get case-sensitive name matches... + + idlName = IDLNames.getClassOrInterfaceName(id,env); + idlModuleNames = IDLNames.getModuleNames(id,isBoxed(),env); + + setNames(id,idlModuleNames,idlName); + + // Is this an exception? + + if (isException()) { + + // Yes, so set our mangled exception names... + + isException = true; + idlExceptionName = IDLNames.getExceptionName(getIDLName()); + qualifiedIDLExceptionName = + IDLNames.getQualifiedName(getIDLModuleNames(),idlExceptionName); + } + + // Set interfaces, methods and members... + + interfaces = null; // set in initialize() + methods = null; // set in initialize() + members = null; // set in initialize() + + } catch (Exception e) { + failedConstraint(7,false,stack,id.toString(),e.getMessage()); + throw new CompilerError(""); + } + } + + /** + * Initialize this instance. + */ + protected boolean initialize ( Vector directInterfaces, + Vector directMethods, + Vector directMembers, + ContextStack stack, + boolean quiet) { + + boolean result = true; + + // Initialize our arrays... + + if (directInterfaces != null && directInterfaces.size() > 0) { + interfaces = new InterfaceType[directInterfaces.size()]; + directInterfaces.copyInto(interfaces); + } else { + interfaces = new InterfaceType[0]; + } + + if (directMethods != null && directMethods.size() > 0) { + methods = new Method[directMethods.size()]; + directMethods.copyInto(methods); + + // Now set the idl names for each... + + try { + IDLNames.setMethodNames(this, methods,env); + } catch (Exception e) { + failedConstraint(13,quiet,stack,getQualifiedName(),e.getMessage()); + result = false; + } + + } else { + methods = new Method[0]; + } + + if (directMembers != null && directMembers.size() > 0) { + members = new Member[directMembers.size()]; + directMembers.copyInto(members); + + // If we have any un-initialized inner classes, now is the time + // to init them... + + for (int i = 0; i < members.length; i++) { + if (members[i].isInnerClassDeclaration()) { + try { + members[i].init(stack,this); + } catch (CompilerError e) { + return false; + } + } + } + + // Now set the idl names for each... + + try { + IDLNames.setMemberNames(this, members,methods,env); + } catch (Exception e) { + int constraint = classDef.isInterface() ? 19 : 20; + failedConstraint(constraint,quiet,stack,getQualifiedName(),e.getMessage()); + result = false; + } + + } else { + members = new Member[0]; + } + + // Set our repositoryID... + + if (result) { + result = setRepositoryID(); + } + + return result; + } + + /* + * Return Type or null if error. classDef may be null. + */ + protected static Type makeType (org.glassfish.rmic.tools.java.Type theType, + ClassDefinition classDef, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + // See if we can find this type in the cache. If so, return it... + + String key = theType.toString(); + + Type result = getType(key,stack); + + if (result != null) { + return result; + } + + // Gotta try with context... + + result = getType(key + stack.getContextCodeString(),stack); + + if (result != null) { + return result; + } + + // Gotta map it... + + BatchEnvironment env = stack.getEnv(); + int typeCode = theType.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + case TC_LONG: + case TC_FLOAT: + case TC_DOUBLE: + { + // Primitive... + + result = PrimitiveType.forPrimitive(theType,stack); + break; + } + + case TC_ARRAY: + { + // Array. + + result = ArrayType.forArray(theType,stack); + break; + } + + case TC_CLASS: + { + try { + // First, make sure we have the class definition... + + ClassDefinition theClass = classDef; + + if (theClass == null) { + theClass = env.getClassDeclaration(theType).getClassDefinition(env); + } + + // Is it an interface or a class? + + if (theClass.isInterface()) { + + // An interface. Is it a special case? + + result = SpecialInterfaceType.forSpecial(theClass,stack); + + if (result == null) { + + // No, does it implement java.rmi.Remote? + + if (env.defRemote.implementedBy(env,theClass.getClassDeclaration())) { + + // Yep, so just see if we can create an instance of RemoteType + // from it... + + boolean parentIsValue = stack.isParentAValue(); + result = RemoteType.forRemote(theClass,stack,parentIsValue); + + // If we did not succeed AND we are in a value context, then + // go ahead and make an NC type out of it... + + if (result == null && parentIsValue) { + result = NCInterfaceType.forNCInterface(theClass,stack); + } + } else { + + // Nope, is it an AbstractType? + + result = AbstractType.forAbstract(theClass,stack,true); + + if (result == null) { + + // No, so treat it as a non-conforming interface type... + + result = NCInterfaceType.forNCInterface(theClass,stack); + } + } + } + } else { + + // A class. Is it a special case? + + result = SpecialClassType.forSpecial(theClass,stack); + + if (result == null) { + + ClassDeclaration classDecl = theClass.getClassDeclaration(); + + // Nope, does it implement java.rmi.Remote? + + if (env.defRemote.implementedBy(env,classDecl)) { + + // Yep, so just see if we can create an instance of + // ImplementationType from it... + + boolean parentIsValue = stack.isParentAValue(); + result = ImplementationType.forImplementation(theClass,stack,parentIsValue); + + // If we did not succeed AND inValue is true, then + // go ahead and make an NC type out of it... + + if (result == null && parentIsValue) { + result = NCClassType.forNCClass(theClass,stack); + } + } else { + + // No, does it implement Serializable? + + if (env.defSerializable.implementedBy(env,classDecl)) { + + // Yep, so just see if we can create an instance of ValueType + // from it... + + result = ValueType.forValue(theClass,stack,true); + } + + if (result == null) { + + // Treat it as a non-conforming class type... + + result = NCClassType.forNCClass(theClass,stack); + } + } + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + break; + } + + default: throw new CompilerError("Unknown typecode (" + typeCode + ") for " + theType.getTypeSignature()); + } + + return result; + } + + /* + * Check if exception is RemoteException or one of its parents. + */ + public static boolean isRemoteException (ClassType ex, + BatchEnvironment env) { + org.glassfish.rmic.tools.java.Type exceptionType = ex.getClassDeclaration().getType(); + + if (exceptionType.equals(env.typeRemoteException) || + exceptionType.equals(env.typeIOException) || + exceptionType.equals(env.typeException) || + exceptionType.equals(env.typeThrowable)) { + + return true; + } + return false; + } + + /* + * Check if method is conforming. + */ + protected boolean isConformingRemoteMethod (Method method, boolean quiet) + throws ClassNotFound { + + // Do we have one exception that is RemoteException or + // a superclass of RemoteException? + + boolean haveRemote = false; + ClassType[] exceptions = method.getExceptions(); + + for (int i = 0; i < exceptions.length; i++) { + + // Is it a conforming exception? + + if (isRemoteException(exceptions[i],env)) { + + // Got it. + + haveRemote = true; + break; + } + } + + // Do we have our exception? + + if (!haveRemote) { + + // No, so report failure... + + failedConstraint(5,quiet,stack,method.getEnclosing(), method.toString()); + } + + // Are any of the arguments exceptions which implement IDLEntity? + // If so, report failure... + + boolean noIDLEntity = !isIDLEntityException(method.getReturnType(),method,quiet); + if (noIDLEntity) { + Type[] args = method.getArguments(); + for (int i = 0; i < args.length; i++) { + if (isIDLEntityException(args[i],method,quiet)) { + noIDLEntity = false; + break; + } + } + } + + return (haveRemote && noIDLEntity); + } + + protected boolean isIDLEntityException(Type type, CompoundType.Method method,boolean quiet) + throws ClassNotFound { + if (type.isArray()) { + type = type.getElementType(); + } + if (type.isCompound()){ + if (((CompoundType)type).isIDLEntityException()) { + failedConstraint(18,quiet,stack,method.getEnclosing(), method.toString()); + return true; + } + } + return false; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + + // Walk all interfaces and check them... + + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i].getStatus() != STATUS_VALID) { + interfaces[i] = (InterfaceType)getValidType(interfaces[i]); + } + } + + // Update methods... + + for (int i = 0; i < methods.length; i++) { + methods[i].swapInvalidTypes(); + } + + // Update members... + + for (int i = 0; i < members.length; i++) { + members[i].swapInvalidTypes(); + } + } + + /* + * Add matching types to list. Return true if this type has not + * been previously checked, false otherwise. + */ + protected boolean addTypes (int typeCodeFilter, + HashSet checked, + Vector matching) { + + // Check self. + + boolean result = super.addTypes(typeCodeFilter,checked,matching); + + // Have we been checked before? + + if (result) { + + // Nope, so walk parent(s) and check them... + + ClassType parent = getSuperclass(); + + if (parent != null) { + parent.addTypes(typeCodeFilter,checked,matching); + } + + // Walk all interfaces and check them... + + //if (interfaces == null) System.out.println("NULL for " +getQualifiedName() + " interfaces"); + for (int i = 0; interfaces != null && i < interfaces.length; i++) { + + // Now recurse and add it and any referenced types... + + //if (interfaces[i] == null) System.out.println("NULL for " +getQualifiedName() + " interfaces[" + i + "]"); + interfaces[i].addTypes(typeCodeFilter,checked,matching); + } + + // Walk all methods and check arguments... + + //if (methods == null) System.out.println("NULL for " +getQualifiedName() + " methods"); + for (int i = 0; methods != null && i < methods.length; i++) { + + // Add return type... + //if (methods[i] == null) System.out.println("NULL for " +getQualifiedName() + " methods[" + i + "]"); + //if (methods[i].getReturnType() == null) System.out.println("NULL for " +getQualifiedName() + methods[i]); + methods[i].getReturnType().addTypes(typeCodeFilter,checked,matching); + + // Add args... + + Type[] args = methods[i].getArguments(); + //if (args == null) System.out.println("NULL for " + getQualifiedName() + " args"); + + for (int j = 0; j < args.length; j++) { + + Type arg = args[j]; + //if (arg == null) System.out.println("NULL for " + getQualifiedName() + " arg[" +j+"]"); + + // Add argument... + + arg.addTypes(typeCodeFilter,checked,matching); + } + + // Add exceptions... + + ClassType[] exceptions = methods[i].getExceptions(); + //if (exceptions == null) System.out.println("NULL for " + getQualifiedName() + " exceptions"); + + for (int j = 0; exceptions != null && j < exceptions.length; j++) { + + ClassType ex = exceptions[j]; + + // Add argument... + + ex.addTypes(typeCodeFilter,checked,matching); + } + } + + // Walk all members and add em... + + //if (members == null) System.out.println("NULL for " +getQualifiedName() + " members"); + for (int i = 0; members != null && i < members.length; i++) { + //if (members[i] == null) System.out.println("NULL for " +getQualifiedName() + " members[" + i + "]"); + Type cType = members[i].getType(); + //if (cType == null) System.out.println("NULL for " + getQualifiedName() + " cType"); + + // Add it... + + cType.addTypes(typeCodeFilter,checked,matching); + } + } + + return result; + } + + /* + * Return true if theType is a conforming constant type. + */ + private boolean isConformingConstantType (MemberDefinition member) { + return isConformingConstantType(member.getType(),member); + } + + /* + * Return true if theType is a conforming constant type. + */ + private boolean isConformingConstantType (org.glassfish.rmic.tools.java.Type theType,MemberDefinition member) { + + // Constraint 3: Constants must be either primitives or String. + + boolean result = true; + int typeCode = theType.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + case TC_LONG: + case TC_FLOAT: + case TC_DOUBLE: // Primitive, so OK... + { + break; + } + + case TC_CLASS: // Must be java.lang.String + { + if (theType.getClassName() != idJavaLangString) { + failedConstraint(3,false,stack,member.getClassDefinition(),member.getName()); + result = false; + } + break; + } + + case TC_ARRAY: // Array constants are not allowed. + { + failedConstraint(3,false,stack,member.getClassDefinition(),member.getName()); + result = false; + break; + } + + default: + throw new Error("unexpected type code: " + typeCode); + } + + return result; + } + + + /* + * Update any method from 'currentMethods' which is defined in a + * parent class so that it's 'declaredBy' field specifies the + * parent. + * @param current The class or interface to gather methods from. + * @param currentMethods The list into which to put the methods. + * for contraint 6. + * @param quiet true if silent errors. + * @param stack the context stack. + * @return currentMethods or null if failed a constraint check. + */ + protected Vector updateParentClassMethods(ClassDefinition current, + Vector currentMethods, + boolean quiet, + ContextStack stack) + throws ClassNotFound { + + ClassDeclaration parentDecl = current.getSuperClass(env); + + while (parentDecl != null) { + + ClassDefinition parentDef = parentDecl.getClassDefinition(env); + Identifier currentID = parentDecl.getName(); + + if ( currentID == idJavaLangObject ) break; + + // Walk all members of this class and update any that + // already exist in currentMethods... + + for (MemberDefinition member = parentDef.getFirstMember(); + member != null; + member = member.getNextMember()) { + + if (member.isMethod() && + !member.isInitializer() && + !member.isConstructor() && + !member.isPrivate()) { + + // It's a method. Is it valid? + + Method method; + try { + method = new Method((CompoundType)this,member,quiet,stack); + } catch (Exception e) { + // Don't report anything here, it's already been reported... + return null; + } + + // Have we already seen it? + + int index = currentMethods.indexOf(method); + if (index >= 0) { + + // Yes, so update it... + + Method currentMethod = (Method)currentMethods.elementAt(index); + currentMethod.setDeclaredBy(currentID); + } + else currentMethods.addElement(method); + } + } + + // Update parent and keep walking up the chain... + + parentDecl = parentDef.getSuperClass(env); + } + + return currentMethods; + } + + /* + * Add all of the public and protected methods defined in + * current (other than initializers) to allMethods. If a sub-interface + * re-declares an inherited method, it will not be added. + * @param current The class or interface to gather methods from. + * @param directMethods The list into which to put the methods. + * @param noMultiInheritedMethods A flag to enable/disable checking + * for contraint 6. + * @param quiet true if silent errors. + * @param stack the context stack. + * @return directMethods or null if failed a constraint check. + */ + protected Vector addAllMethods (ClassDefinition current, Vector directMethods, + boolean noMultiInheritedMethods, + boolean quiet, + ContextStack stack) + throws ClassNotFound { + + // Constraint 6: Multiple inherited interfaces may not + // declare the same method. + + ClassDeclaration[] interfaces = current.getInterfaces(); + + // We want to add members starting at the _least_ derived + // interfaces. To do so, recurse until we have no more + // interfaces... + + for (int i = 0; i < interfaces.length; i++) { + + Vector result = addAllMethods(interfaces[i].getClassDefinition(env), + directMethods, + noMultiInheritedMethods,quiet,stack); + if (result == null) { + return null; + } + } + + // Walk all members of this interface, adding any unique methods + // other than initializers and private methods... + + for (MemberDefinition member = current.getFirstMember(); + member != null; + member = member.getNextMember()) + { + if (member.isMethod() && + !member.isInitializer() && + !member.isPrivate()) { + + // It's a method. Is it valid? + + Method method; + try { + method = new Method((CompoundType)this,member,quiet,stack); + } catch (Exception e) { + // Don't report anything here, it's already been reported... + return null; + } + + // Have we already seen it? + + if (!directMethods.contains(method)) { + + // Nope, so add it... + + directMethods.addElement(method); + + } else { + + // Yes. This is an error unless we are looking at the + // target interface (or this is a ValueType). Are we? + + if (noMultiInheritedMethods && current != classDef && + !stack.isParentAValue() && !stack.getContext().isValue()) { + + // Nope. Say so and signal error by returning null.. + + Method existingMethod = (Method) directMethods.elementAt(directMethods.indexOf(method)); + ClassDefinition existingMemberClassDef = existingMethod.getMemberDefinition().getClassDefinition(); + + // There are more legal cases to consider here. + // If the two methods belong to interfaces that inherit from each other + // then it is just a redefinition which is legal. + if ( current != existingMemberClassDef && + ! inheritsFrom(stack, current, existingMemberClassDef) && + ! inheritsFrom(stack, existingMemberClassDef, current)) + { + //Identifier int1 = existingMethod.getEnclosing().getIdentifier(); + //Identifier int2 = current.getName(); + //String message = int1.toString() + " and " + int2.toString(); + String message = existingMemberClassDef.getName() + " and " + current.getName(); + failedConstraint(6,quiet,stack,classDef,message,method); + return null; + } + } + + // Bug fix 5014329 + + // find a matching method. + int index = directMethods.indexOf(method); + Method other = (Method) directMethods.get(index); + + // merge the two methods, such that the new method + // will contain only those exception that can be thrown + // by both these methods, not just one of them. + Method newMethod = method.mergeWith(other); + + // replace the old method with the new. + directMethods.set(index, newMethod); + } + } + } + + return directMethods; + } + + // This should really be a method on ClassDefinition, but it takes too long to change the shared source. + // Works for both, classes and interfaces. + protected boolean inheritsFrom(ContextStack stack, ClassDefinition def, ClassDefinition otherDef) throws ClassNotFound { + if (def == otherDef) + return true; + + ClassDefinition superDef; + if (def.getSuperClass() != null) { + superDef = def.getSuperClass().getClassDefinition(stack.getEnv()); + if (inheritsFrom(stack, superDef, otherDef)) + return true; + } + + ClassDeclaration[] interfaces = def.getInterfaces(); + for (int i=0; i 0) { + int offset = 0; + ValueType[] temp = new ValueType[exceptions.length - dupCount]; + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i] != null) { + temp[offset++] = exceptions[i]; + } + } + exceptions = temp; + } + + return exceptions; + } + + + protected static String getVisibilityString (MemberDefinition member) { + String vis = ""; + String prefix = ""; + + if (member.isPublic()) { + vis += "public"; + prefix = " "; + } else if (member.isProtected()) { + vis += "protected"; + prefix = " "; + } else if (member.isPrivate()) { + vis += "private"; + prefix = " "; + } + + if (member.isStatic()) { + vis += prefix; + vis += "static"; + prefix = " "; + } + + if (member.isFinal()) { + vis += prefix; + vis += "final"; + prefix = " "; + } + + return vis; + } + + protected boolean assertNotImpl(Type type, + boolean quiet, + ContextStack stack, + CompoundType enclosing, + boolean dataMember) { + + if (type.isType(TYPE_IMPLEMENTATION)) { + int constraint = dataMember ? 28 : 21; + failedConstraint(constraint,quiet,stack,type,enclosing.getName()); + return false; + } + return true; + } + + //_____________________________________________________________________ + // Inner Class "Method" + //_____________________________________________________________________ + + /** + * A CompoundType.Method object encapsulates IIOP-specific information + * about a particular method in the interface represented by the outer + * instance. + */ + public class Method implements ContextElement, Cloneable { + + /** + * Is this method inherited? + */ + public boolean isInherited () { + return declaredBy != enclosing.getIdentifier(); + } + + /** + * Is this method an attribute? + * Return true if getAttributeKind != ATTRIBUTE_NONE. + */ + public boolean isAttribute () { + return attributeKind != ATTRIBUTE_NONE; + } + + /** + * Is this method a read-write attribute? + */ + public boolean isReadWriteAttribute () { + return attributeKind == ATTRIBUTE_IS_RW || + attributeKind == ATTRIBUTE_GET_RW; + } + + /** + * Return the attribute kind. + */ + public int getAttributeKind() { + return attributeKind; + } + + /** + * Return the attribute name. Will be null if + * attribute kind == ATTRIBUTE_NONE. + */ + public String getAttributeName() { + return attributeName; + } + + /** + * For kinds ATTRIBUTE_GET_RW or ATTRIBUTE_IS_RW, return + * the index of the matching ATTRIBUTE_SET method, and + * vice-versa. For all other cases, return -1. + */ + public int getAttributePairIndex() { + return attributePairIndex; + } + + /** + * Return context element name. + */ + public String getElementName() { + return memberDef.toString(); + } + + /** + * Equality check based on method signature. + */ + public boolean equals(Object obj) { + Method other = (Method) obj; + + if (getName().equals(other.getName()) && + arguments.length == other.arguments.length) { + + for (int i = 0; i < arguments.length; i++) { + if (! arguments[i].equals(other.arguments[i])) { + return false; + } + } + return true; + } + return false; + } + + public int hashCode() { + return getName().hashCode() ^ Arrays.hashCode(arguments); + } + + /** + * Return a new Method object that is a legal combination of + * this method object and another one. + * + * This requires determining the exceptions declared by the + * combined method, which must be only those exceptions + * that may thrown by both of the old methods. + */ + public Method mergeWith(Method other) { + if (!equals(other)) { + env.error(0, "attempt to merge method failed:", getName(), + enclosing.getClassDefinition().getName()); + } + + Vector legalExceptions = new Vector(); + try { + collectCompatibleExceptions( + other.exceptions, exceptions, legalExceptions); + collectCompatibleExceptions( + exceptions, other.exceptions, legalExceptions); + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + enclosing.getClassDefinition().getName()); + return null; + } + + Method merged = (Method) clone(); + merged.exceptions = new ValueType[legalExceptions.size()]; + legalExceptions.copyInto(merged.exceptions); + merged.implExceptions = merged.exceptions; + + return merged; + } + + /** + * Add to the supplied list all exceptions in the "from" array + * that are subclasses of an exception in the "with" array. + */ + private void collectCompatibleExceptions( + ValueType[] from, ValueType[] with, Vector list) + throws ClassNotFound { + + for (int i = 0; i < from.length; i++) { + ClassDefinition exceptionDef = from[i].getClassDefinition(); + if (!list.contains(from[i])) { + for (int j = 0; j < with.length; j++) { + if (exceptionDef.subClassOf( + enclosing.getEnv(), + with[j].getClassDeclaration())) { + list.addElement(from[i]); + break; + } + } + } + } + } + + /** + * Return the compound type which contains this method. + */ + public CompoundType getEnclosing() { + return enclosing; + } + + /** + * Return the identifier for the class or interface which + * declares this method. + */ + public Identifier getDeclaredBy() { + return declaredBy; + } + + /** + * Return the visibility (e.g. "public final") of this member. + */ + public String getVisibility() { + return vis; + } + + /** + * Methods to check various attributes. + */ + public boolean isPublic() { + return memberDef.isPublic(); + } + + public boolean isProtected() { + return memberDef.isPrivate(); + } + + public boolean isPrivate() { + return memberDef.isPrivate(); + } + + public boolean isStatic() { + return memberDef.isStatic(); + } + + /** + * Return the name of this method. + */ + public String getName() { + return name; + } + + /** + * IDL_Naming + * Return the IDL name of this method. + */ + public String getIDLName() { + return idlName; + } + + /** + * Return the type of this method. + */ + public org.glassfish.rmic.tools.java.Type getType() { + return memberDef.getType(); + } + + /** + * Return true if this is a constructor. + */ + public boolean isConstructor () { + return memberDef.isConstructor(); + } + + /** + * Return true if this is NOT a constructor {@code &&} is not + * an attribute. + */ + public boolean isNormalMethod () { + return (!memberDef.isConstructor()) && attributeKind == ATTRIBUTE_NONE; + } + + /** + * Get the return type of this method. May be null. + */ + public Type getReturnType() { + return returnType; + } + + /** + * Return the argument types of this method. + */ + public Type[] getArguments() { + return (Type[]) arguments.clone(); + } + + /** + * Return the names of the argument types of this method. + */ + public String[] getArgumentNames() { + return argumentNames; + } + + /** + * Return the MemberDefinition from which this method was created. + */ + public MemberDefinition getMemberDefinition() { + return memberDef; + } + + /** + * Return an array of the exception classes declared to be + * thrown by this remote method. + * + * For methods with the same name and type signature inherited + * from multiple remote interfaces, the array will contain + * the set of exceptions declared in all of the interfaces' + * methods that can be legally thrown in each of them. + */ + public ValueType[] getExceptions() { + return (ValueType[]) exceptions.clone(); + } + + /** + * Same as getExceptions(), except when method is in an + * ImplementationType and the exceptions list is narrower. + */ + public ValueType[] getImplExceptions() { + return (ValueType[]) implExceptions.clone(); + } + + /** + * Return an array containing only those exceptions which + * need to be caught. Removes java.rmi.RemoteException, + * java.lang.RuntimeException, java.lang.Error, and their + * subclasses, then removes any exceptions which are more + * derived than another in the list. Returns null if no + * exceptions need to be caught. + */ + public ValueType[] getUniqueCatchList(ValueType[] list) { + ValueType[] result = list; + int newSize = list.length; + + try { + + // First, remove RemoteException, RuntimeException, Error, and their subclasses... + for (int i = 0; i < list.length; i++) { + ClassDeclaration decl = list[i].getClassDeclaration(); + if (env.defRemoteException.superClassOf(env, decl) || + env.defRuntimeException.superClassOf(env, decl) || + env.defError.superClassOf(env, decl)) { + list[i] = null; + newSize--; + } + } + + // Now remove derived types... + for (int i = 0; i < list.length; i++) { + if (list[i] != null) { + ClassDefinition current = list[i].getClassDefinition(); + for (int j = 0; j < list.length; j++) { + if (j != i && list[i] != null && list[j] != null && + current.superClassOf(env, list[j].getClassDeclaration())) { + list[j] = null; + newSize--; + } + } + } + } + + } catch (ClassNotFound e) { + classNotFound(stack,e); // Report error but do not stop. + } + + // Create new list if we removed anything... + + if (newSize < list.length) { + ValueType[] temp = new ValueType[newSize]; + int offset = 0; + for (int i = 0; i < list.length; i++) { + if (list[i] != null) { + temp[offset++] = list[i]; + } + } + list = temp; + } + + if (list.length == 0) { + return null; + } else { + return list; + } + } + + /** + * Return an array containing only those exceptions which need to be + * handled explicitly by the stub. Removes java.lang.RuntimeException, + * java.lang.Error, and their subclasses, since these are all passed + * back as CORBA system exceptions. Also removes subclasses of + * java.rmi.RemoteException but not java.rmi.RemoteException itself, + * since this may need to be thrown by the stub. + */ + public ValueType[] getFilteredStubExceptions(ValueType[] list) { + ValueType[] result = list; + int newSize = list.length; + + try { + + for (int i = 0; i < list.length; i++) { + ClassDeclaration decl = list[i].getClassDeclaration(); + if ((env.defRemoteException.superClassOf(env, decl) && + !env.defRemoteException.getClassDeclaration().equals(decl)) || + env.defRuntimeException.superClassOf(env, decl) || + env.defError.superClassOf(env, decl)) { + list[i] = null; + newSize--; + } + } + + } catch (ClassNotFound e) { + classNotFound(stack,e); // Report error but do not stop. + } + + // Create new list if we removed anything... + + if (newSize < list.length) { + ValueType[] temp = new ValueType[newSize]; + int offset = 0; + for (int i = 0; i < list.length; i++) { + if (list[i] != null) { + temp[offset++] = list[i]; + } + } + list = temp; + } + + return list; + } + + /** + * Return the string representation of this method. + */ + public String toString() { + + if (stringRep == null) { + + StringBuffer result = new StringBuffer(returnType.toString()); + + // Add name... + + result.append(" "); + result.append(getName()); + result.append(" ("); + + // Add arguments... + + for (int i = 0; i < arguments.length; i++) { + if (i > 0) { + result.append(", "); + } + result.append(arguments[i]); + result.append(" "); + result.append(argumentNames[i]); + } + + result.append(")"); + + // Add exceptions... + + for (int i = 0; i < exceptions.length; i++) { + if (i == 0) { + result.append(" throws "); + } else { + result.append(", "); + } + result.append(exceptions[i]); + } + + result.append(";"); + + stringRep = result.toString(); + } + + return stringRep; + } + + + /** + * Set attribute kind. May only be called during initialization. + */ + public void setAttributeKind(int kind) { + attributeKind = kind; + } + + /** + * Set pair index. May only be called during initialization. + */ + public void setAttributePairIndex(int index) { + attributePairIndex = index; + } + + /** + * Set attribute name. May only be called during initialization. + */ + public void setAttributeName(String name) { + attributeName = name; + } + + /** + * Set the idl name. May only be called during initialization. + */ + public void setIDLName (String idlName) { + this.idlName=idlName; + } + + /** + * Set the implExceptions array. May only be called during initialization. + */ + public void setImplExceptions (ValueType[] exceptions) { + implExceptions = exceptions; + } + + /** + * Set the declaredBy Identifier. May only be called during initialization. + */ + public void setDeclaredBy (Identifier by) { + declaredBy = by; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + + // Check return type... + + if (returnType.getStatus() != STATUS_VALID) { + returnType = getValidType(returnType); + } + + // Check args... + + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].getStatus() != STATUS_VALID) { + arguments[i] = getValidType(arguments[i]); + } + } + + // Check exceptions... + + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getStatus() != STATUS_VALID) { + exceptions[i] = (ValueType)getValidType(exceptions[i]); + } + } + + // Check implExceptions... + + for (int i = 0; i < implExceptions.length; i++) { + if (implExceptions[i].getStatus() != STATUS_VALID) { + implExceptions[i] = (ValueType)getValidType(implExceptions[i]); + } + } + } + + /** + * Release all resources. + */ + public void destroy () { + if (memberDef != null) { + memberDef = null; + enclosing = null; + if (exceptions != null) { + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i] != null) exceptions[i].destroy(); + exceptions[i] = null; + } + exceptions = null; + } + + if (implExceptions != null) { + for (int i = 0; i < implExceptions.length; i++) { + if (implExceptions[i] != null) implExceptions[i].destroy(); + implExceptions[i] = null; + } + implExceptions = null; + } + + if (returnType != null) returnType.destroy(); + returnType = null; + + if (arguments != null) { + for (int i = 0; i < arguments.length; i++) { + if (arguments[i] != null) arguments[i].destroy(); + arguments[i] = null; + } + arguments = null; + } + + if (argumentNames != null) { + for (int i = 0; i < argumentNames.length; i++) { + argumentNames[i] = null; + } + argumentNames = null; + } + + vis = null; + name = null; + idlName = null; + stringRep = null; + attributeName = null; + declaredBy = null; + } + } + + private MemberDefinition memberDef; + private CompoundType enclosing; + private ValueType[] exceptions; + private ValueType[] implExceptions; + private Type returnType; + private Type[] arguments; + private String[] argumentNames; + private String vis; + private String name; + private String idlName; + private String stringRep = null; + private int attributeKind = ATTRIBUTE_NONE; + private String attributeName = null; + private int attributePairIndex = -1; + private Identifier declaredBy = null; + + /** + * Make up an argument name for the given type. + */ + private String makeArgName (int argNum, Type type) { + return "arg" + argNum; + } + + /** + * Create a new Method object corresponding to the given + * method definition. + */ + public Method (CompoundType enclosing, + MemberDefinition memberDef, + boolean quiet, + ContextStack stack) throws Exception { + + this.enclosing = enclosing; + this.memberDef = memberDef; + vis = getVisibilityString(memberDef); + idlName = null; // See setIDLName() + boolean valid = true; + declaredBy = memberDef.getClassDeclaration().getName(); + + // Set name... + + name = memberDef.getName().toString(); + + // Update the context... + + stack.setNewContextCode(ContextStack.METHOD); + stack.push(this); + + // Set return type... + + stack.setNewContextCode(ContextStack.METHOD_RETURN); + org.glassfish.rmic.tools.java.Type methodType = memberDef.getType(); + org.glassfish.rmic.tools.java.Type rtnType = methodType.getReturnType(); + + if (rtnType == org.glassfish.rmic.tools.java.Type.tVoid) { + returnType = PrimitiveType.forPrimitive(rtnType,stack); + } else { + returnType = makeType(rtnType,null,stack); + if (returnType == null || + !assertNotImpl(returnType,quiet,stack,enclosing,false)) { + valid = false; + failedConstraint(24,quiet,stack,enclosing.getName()); + } + } + + // Set arguments and argument names... + + stack.setNewContextCode(ContextStack.METHOD_ARGUMENT); + org.glassfish.rmic.tools.java.Type[] args = memberDef.getType().getArgumentTypes(); + arguments = new Type[args.length]; + argumentNames = new String[args.length]; + Vector origArgNames = memberDef.getArguments(); + + for (int i = 0; i < args.length; i++) { + Type type = null; + try { + type = makeType(args[i],null,stack); + } catch (Exception e) { + } + + if (type != null) { + if (!assertNotImpl(type,quiet,stack,enclosing,false)) { + valid = false; + } else { + arguments[i] = type; + if (origArgNames != null) { + LocalMember local = (LocalMember)origArgNames.elementAt(i+1); + argumentNames[i] = local.getName().toString(); + } else { + argumentNames[i] = makeArgName(i,type); + } + } + } else { + valid = false; + failedConstraint(25,false,stack,enclosing.getQualifiedName(),name); + } + } + + if (!valid) { + stack.pop(false); + throw new Exception(); + } + + // Set exceptions... + + try { + exceptions = enclosing.getMethodExceptions(memberDef,quiet,stack); + implExceptions = exceptions; + stack.pop(true); + } catch (Exception e) { + stack.pop(false); + throw new Exception(); + } + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + } + + //_____________________________________________________________________ + // Inner Class "Member" + //_____________________________________________________________________ + + /** + * An CompoundType.Member object wraps a Type and a value representing + * a data member, including constants. + */ + public class Member implements ContextElement, Cloneable { + + /** + * Return context element name. + */ + public String getElementName() { + return "\"" + getName() + "\""; + } + + /** + * Return the type of this member. + */ + public Type getType() { + return type; + } + + /** + * Return the name of this member. + */ + public String getName() { + return name; + } + + /** + * IDL_Naming + * Return the IDL name of this member. + */ + public String getIDLName() { + return idlName; + } + + /** + * Return the visibility (e.g. "public final") of this member. + */ + public String getVisibility() { + return vis; + } + + /** + * Methods to check various attributes. + */ + public boolean isPublic() { + return member.isPublic(); + } + + public boolean isPrivate() { + return member.isPrivate(); + } + + public boolean isStatic() { + return member.isStatic(); + } + + public boolean isFinal() { + return member.isFinal(); + } + + public boolean isTransient() { + if (forceTransient) return true; + return member.isTransient(); + } + + /** + * Return the value of this member. May be null. + */ + public String getValue() { + return value; + } + + /** + * Return true if this member represents an inner class declaration, + * false otherwise. + */ + public boolean isInnerClassDeclaration() { + return innerClassDecl; + } + + /** + * Return true if this member represents a constant. + */ + public boolean isConstant () { + return constant; + } + + /** + * Return the string representation of this constant. + */ + public String toString() { + + String result = type.toString(); + + if (value != null) { + result += (" = " + value); + } + + return result; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + if (type.getStatus() != STATUS_VALID) { + type = getValidType(type); + } + } + + protected void setTransient() { + if (! isTransient()) { + forceTransient = true; + if (vis.length() > 0) { + vis = vis + " transient"; + } else { + vis = "transient"; + } + } + } + + protected MemberDefinition getMemberDefinition() { + return member; + } + + /** + * Release all resources. + */ + public void destroy () { + if (type != null) { + type.destroy(); + type = null; + vis = null; + value = null; + name = null; + idlName = null; + member = null; + } + } + + private Type type; + private String vis; + private String value; + private String name; + private String idlName; + private boolean innerClassDecl; + private boolean constant; + private MemberDefinition member; + private boolean forceTransient; + + /** + * Create a new Member object. + */ + public Member(MemberDefinition member, + String value, + ContextStack stack, + CompoundType enclosing) { + this.member = member; + this.value = value; + forceTransient = false; + innerClassDecl = member.getInnerClass() != null; + + // If we are not an inner class, finish initializing now. + // Otherwise, wait until outer class is finished, then + // call init to avoid potential recursion problems... + + if (!innerClassDecl) { + init (stack,enclosing); + } + } + + public void init (ContextStack stack, CompoundType enclosing) { + + constant = false; + name = member.getName().toString(); + vis = getVisibilityString(member); + idlName = null; + + // Add self to stack... + + int contextCode = ContextStack.MEMBER; + stack.setNewContextCode(contextCode); + + // Check for special contextCodes... + + if (member.isVariable()) { + if (value != null && member.isConstant()) { + contextCode = ContextStack.MEMBER_CONSTANT; + this.constant = true; + } else if (member.isStatic()) { + contextCode = ContextStack.MEMBER_STATIC; + } else if (member.isTransient()) { + contextCode = ContextStack.MEMBER_TRANSIENT; + } + } + + stack.setNewContextCode(contextCode); + stack.push(this); + + type = makeType(member.getType(),null,stack); + + if (type == null || + (!innerClassDecl && + !member.isStatic() && + !member.isTransient() && + !assertNotImpl(type,false,stack,enclosing,true))) { + stack.pop(false); + throw new CompilerError(""); + } + + // Clean up primitive constant values... + + if (constant && type.isPrimitive()) { + if (type.isType(TYPE_LONG) || type.isType(TYPE_FLOAT) || type.isType(TYPE_DOUBLE)) { + int length = value.length(); + char lastChar = value.charAt(length-1); + if (!Character.isDigit(lastChar)) { + this.value = value.substring(0,length-1); + } + } else if (type.isType(TYPE_BOOLEAN)) { + value = value.toUpperCase(); + } + } + if (constant && type.isType(TYPE_STRING)) { + value = "L" + value; + } + stack.pop(true); + } + + public void setIDLName (String name) { + this.idlName = name; + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/Constants.java b/rmic/src/main/java/org/glassfish/rmic/iiop/Constants.java new file mode 100644 index 000000000..dd5e9a7e4 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/Constants.java @@ -0,0 +1,276 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.Identifier; + +public interface Constants extends org.glassfish.rmic.Constants { + + // Identifiers for referenced classes: + + public static final Identifier idReplyHandler = + Identifier.lookup("org.omg.CORBA.portable.ResponseHandler"); + public static final Identifier idStubBase = + Identifier.lookup("javax.rmi.CORBA.Stub"); + public static final Identifier idTieBase = + Identifier.lookup("org.omg.CORBA.portable.ObjectImpl"); + public static final Identifier idTieInterface = + Identifier.lookup("javax.rmi.CORBA.Tie"); + public static final Identifier idPOAServantType = + Identifier.lookup( "org.omg.PortableServer.Servant" ) ; + public static final Identifier idDelegate = + Identifier.lookup("org.omg.CORBA.portable.Delegate"); + public static final Identifier idOutputStream = + Identifier.lookup("org.omg.CORBA.portable.OutputStream"); + public static final Identifier idExtOutputStream = + Identifier.lookup("org.omg.CORBA_2_3.portable.OutputStream"); + public static final Identifier idInputStream = + Identifier.lookup("org.omg.CORBA.portable.InputStream"); + public static final Identifier idExtInputStream = + Identifier.lookup("org.omg.CORBA_2_3.portable.InputStream"); + public static final Identifier idSystemException = + Identifier.lookup("org.omg.CORBA.SystemException"); + public static final Identifier idBadMethodException = + Identifier.lookup("org.omg.CORBA.BAD_OPERATION"); + public static final Identifier idPortableUnknownException = + Identifier.lookup("org.omg.CORBA.portable.UnknownException"); + public static final Identifier idApplicationException = + Identifier.lookup("org.omg.CORBA.portable.ApplicationException"); + public static final Identifier idRemarshalException = + Identifier.lookup("org.omg.CORBA.portable.RemarshalException"); + public static final Identifier idJavaIoExternalizable = + Identifier.lookup("java.io.Externalizable"); + public static final Identifier idCorbaObject = + Identifier.lookup("org.omg.CORBA.Object"); + public static final Identifier idCorbaORB = + Identifier.lookup("org.omg.CORBA.ORB"); + public static final Identifier idClassDesc = + Identifier.lookup("javax.rmi.CORBA.ClassDesc"); + public static final Identifier idJavaIoIOException = + Identifier.lookup("java.io.IOException"); + public static final Identifier idIDLEntity = + Identifier.lookup("org.omg.CORBA.portable.IDLEntity"); + public static final Identifier idValueBase = + Identifier.lookup("org.omg.CORBA.portable.ValueBase"); + public static final Identifier idBoxedRMI = + Identifier.lookup("org.omg.boxedRMI"); + public static final Identifier idBoxedIDL = + Identifier.lookup("org.omg.boxedIDL"); + public static final Identifier idCorbaUserException = + Identifier.lookup("org.omg.CORBA.UserException"); + + + // Identifiers for primitive types: + + public static final Identifier idBoolean = + Identifier.lookup("boolean"); + public static final Identifier idByte = + Identifier.lookup("byte"); + public static final Identifier idChar = + Identifier.lookup("char"); + public static final Identifier idShort = + Identifier.lookup("short"); + public static final Identifier idInt = + Identifier.lookup("int"); + public static final Identifier idLong = + Identifier.lookup("long"); + public static final Identifier idFloat = + Identifier.lookup("float"); + public static final Identifier idDouble = + Identifier.lookup("double"); + public static final Identifier idVoid = + Identifier.lookup("void"); + + // IndentingWriter constructor args: + + public static final int INDENT_STEP = 4; + public static final int TAB_SIZE = Integer.MAX_VALUE; // No tabs. + + // Type status codes: + + public static final int STATUS_PENDING = 0; + public static final int STATUS_VALID = 1; + public static final int STATUS_INVALID = 2; + + // Java Names: + + public static final String NAME_SEPARATOR = "."; + public static final String SERIAL_VERSION_UID = "serialVersionUID"; + + // IDL Names: + + public static final String[] IDL_KEYWORDS = { + "abstract", + "any", + "attribute", + "boolean", + "case", + "char", + "const", + "context", + "custom", + "default", + "double", + "enum", + "exception", + "factory", + "FALSE", + "fixed", + "float", + "in", + "inout", + "interface", + "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", + }; + + + public static final String EXCEPTION_SUFFIX = "Exception"; + public static final String ERROR_SUFFIX = "Error"; + public static final String EX_SUFFIX = "Ex"; + + public static final String IDL_REPOSITORY_ID_PREFIX = "IDL:"; + public static final String IDL_REPOSITORY_ID_VERSION = ":1.0"; + + public static final String[] IDL_CORBA_MODULE = {"CORBA"}; + public static final String[] IDL_SEQUENCE_MODULE = {"org","omg","boxedRMI"}; + public static final String[] IDL_BOXEDIDL_MODULE = {"org","omg","boxedIDL"}; + + public static final String IDL_CLASS = "ClassDesc"; + public static final String[] IDL_CLASS_MODULE = {"javax","rmi","CORBA"}; + + public static final String IDL_IDLENTITY = "IDLEntity"; + public static final String IDL_SERIALIZABLE = "Serializable"; + public static final String IDL_EXTERNALIZABLE = "Externalizable"; + public static final String[] IDL_JAVA_IO_MODULE = {"java","io"}; + public static final String[] IDL_ORG_OMG_CORBA_MODULE = {"org","omg","CORBA"}; + public static final String[] IDL_ORG_OMG_CORBA_PORTABLE_MODULE = {"org","omg","CORBA","portable"}; + + public static final String IDL_JAVA_LANG_OBJECT = "_Object"; + public static final String[] IDL_JAVA_LANG_MODULE = {"java","lang"}; + + public static final String IDL_JAVA_RMI_REMOTE = "Remote"; + public static final String[] IDL_JAVA_RMI_MODULE = {"java","rmi"}; + + public static final String IDL_SEQUENCE = "seq"; + + public static final String IDL_CONSTRUCTOR = "create"; + + public static final String IDL_NAME_SEPARATOR = "::"; + public static final String IDL_BOOLEAN = "boolean"; + public static final String IDL_BYTE = "octet"; + public static final String IDL_CHAR = "wchar"; + public static final String IDL_SHORT = "short"; + public static final String IDL_INT = "long"; + public static final String IDL_LONG = "long long"; + public static final String IDL_FLOAT = "float"; + public static final String IDL_DOUBLE = "double"; + public static final String IDL_VOID = "void"; + + public static final String IDL_STRING = "WStringValue"; + public static final String IDL_CONSTANT_STRING = "wstring"; + public static final String IDL_CORBA_OBJECT = "Object"; + public static final String IDL_ANY = "any"; + + // File names: + + public static final String SOURCE_FILE_EXTENSION = ".java"; + public static final String IDL_FILE_EXTENSION = ".idl"; + + // Type Codes: + + public static final int TYPE_VOID = 0x00000001; // In PrimitiveType + public static final int TYPE_BOOLEAN = 0x00000002; // In PrimitiveType + public static final int TYPE_BYTE = 0x00000004; // In PrimitiveType + public static final int TYPE_CHAR = 0x00000008; // In PrimitiveType + public static final int TYPE_SHORT = 0x00000010; // In PrimitiveType + public static final int TYPE_INT = 0x00000020; // In PrimitiveType + public static final int TYPE_LONG = 0x00000040; // In PrimitiveType + public static final int TYPE_FLOAT = 0x00000080; // In PrimitiveType + public static final int TYPE_DOUBLE = 0x00000100; // In PrimitiveType + + public static final int TYPE_STRING = 0x00000200; // In SpecialClassType (String) + public static final int TYPE_ANY = 0x00000400; // In SpecialInterfaceType (Serializable,Externalizable) + public static final int TYPE_CORBA_OBJECT = 0x00000800; // In SpecialInterfaceType (CORBA.Object,Remote) + + public static final int TYPE_REMOTE = 0x00001000; // In RemoteType + public static final int TYPE_ABSTRACT = 0x00002000; // In AbstractType + public static final int TYPE_NC_INTERFACE = 0x00004000; // In NCInterfaceType + + public static final int TYPE_VALUE = 0x00008000; // In ValueType + public static final int TYPE_IMPLEMENTATION = 0x00010000; // In ImplementationType + public static final int TYPE_NC_CLASS = 0x00020000; // In NCClassType + + public static final int TYPE_ARRAY = 0x00040000; // In ArrayType + public static final int TYPE_JAVA_RMI_REMOTE = 0x00080000; // In SpecialInterfaceType + + // Type code masks: + + public static final int TYPE_NONE = 0x00000000; + public static final int TYPE_ALL = 0xFFFFFFFF; + public static final int TYPE_MASK = 0x00FFFFFF; + public static final int TM_MASK = 0xFF000000; + + // Type code modifiers: + + public static final int TM_PRIMITIVE = 0x01000000; + public static final int TM_COMPOUND = 0x02000000; + public static final int TM_CLASS = 0x04000000; + public static final int TM_INTERFACE = 0x08000000; + public static final int TM_SPECIAL_CLASS = 0x10000000; + public static final int TM_SPECIAL_INTERFACE= 0x20000000; + public static final int TM_NON_CONFORMING = 0x40000000; + public static final int TM_INNER = 0x80000000; + + // Attribute kinds... + + public static final int ATTRIBUTE_NONE = 0; // Not an attribute. + public static final int ATTRIBUTE_IS = 1; // read-only, had "is" prefix. + public static final int ATTRIBUTE_GET = 2; // read-only, had "get" prefix. + public static final int ATTRIBUTE_IS_RW = 3; // read-write, had "is" prefix. + public static final int ATTRIBUTE_GET_RW = 4; // read-write, had "get" prefix. + public static final int ATTRIBUTE_SET = 5; // had "set" prefix. + + public static final String[] ATTRIBUTE_WIRE_PREFIX = { + "", + "_get_", + "_get_", + "_get_", + "_get_", + "_set_", + }; +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ContextElement.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ContextElement.java new file mode 100644 index 000000000..c31f0a109 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ContextElement.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +/** + * ContextElement provides a common interface for elements of a ContextStack. + * @author Bryan Atsatt + */ +public interface ContextElement { + public String getElementName(); +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ContextStack.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ContextStack.java new file mode 100644 index 000000000..8940334be --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ContextStack.java @@ -0,0 +1,426 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.CompilerError; + +/** + * ContextStack provides a mechanism to record parsing state. + * + * @author Bryan Atsatt + */ +public class ContextStack { + + // Context codes. + + public static final int TOP = 1; + + public static final int METHOD = 2; + public static final int METHOD_RETURN = 3; + public static final int METHOD_ARGUMENT = 4; + public static final int METHOD_EXCEPTION = 5; + + public static final int MEMBER = 6; + public static final int MEMBER_CONSTANT = 7; + public static final int MEMBER_STATIC = 8; + public static final int MEMBER_TRANSIENT = 9; + + public static final int IMPLEMENTS = 10; + public static final int EXTENDS = 11; + + // String versions of context codes. + + private static final String[] CODE_NAMES = { + "UNKNOWN ", + "Top level type ", + "Method ", + "Return parameter ", + "Parameter ", + "Exception ", + "Member ", + "Constant member ", + "Static member ", + "Transient member ", + "Implements ", + "Extends ", + }; + // Member data. + + private int currentIndex = -1; + private int maxIndex = 100; + private TypeContext[] stack = new TypeContext[maxIndex]; + private int newCode = TOP; + private BatchEnvironment env = null; + private boolean trace = false; + private TypeContext tempContext = new TypeContext(); + + private static final String TRACE_INDENT = " "; + + /** + * Constructor. + */ + public ContextStack (BatchEnvironment env) { + this.env = env; + env.contextStack = this; + } + + /** + * Return true if {@code env.nerrors > 0}. + */ + public boolean anyErrors () { + return env.nerrors > 0; + } + + /** + * Enable/disable tracing. + */ + public void setTrace(boolean trace) { + this.trace = trace; + } + + /** + * Check trace flag. + */ + public boolean isTraceOn() { + return trace; + } + + /** + * Get the environment. + */ + public BatchEnvironment getEnv() { + return env; + } + + /** + * Set the new context. + */ + public void setNewContextCode(int code) { + newCode = code; + } + + /** + * Get the current context code. + */ + public int getCurrentContextCode() { + return newCode; + } + + + /** + * If tracing on, write the current call stack (not the context stack) to + * System.out. + */ + final void traceCallStack () { + if (trace) dumpCallStack(); + } + + public final static void dumpCallStack() { + new Error().printStackTrace(System.out); + } + + /** + * Print a line indented by stack depth. + */ + final private void tracePrint (String text, boolean line) { + int length = text.length() + (currentIndex * TRACE_INDENT.length()); + StringBuffer buffer = new StringBuffer(length); + for (int i = 0; i < currentIndex; i++) { + buffer.append(TRACE_INDENT); + } + buffer.append(text); + if (line) { + buffer.append("\n"); + } + System.out.print(buffer.toString()); + } + + /** + * If tracing on, print a line. + */ + final void trace (String text) { + if (trace) { + tracePrint(text,false); + } + } + + /** + * If tracing on, print a line followed by a '\n'. + */ + final void traceln (String text) { + if (trace) { + tracePrint(text,true); + } + } + + /** + * If tracing on, print a pre-mapped ContextElement. + */ + final void traceExistingType (Type type) { + if (trace) { + tempContext.set(newCode,type); + traceln(toResultString(tempContext,true,true)); + } + } + + /** + * Push a new element on the stack. + * @return the new element. + */ + public TypeContext push (ContextElement element) { + + currentIndex++; + + // Grow array if need to... + + if (currentIndex == maxIndex) { + int newMax = maxIndex * 2; + TypeContext[] newStack = new TypeContext[newMax]; + System.arraycopy(stack,0,newStack,0,maxIndex); + maxIndex = newMax; + stack = newStack; + } + + // Make sure we have a context object to use at this position... + + TypeContext it = stack[currentIndex]; + + if (it == null) { + it = new TypeContext(); + stack[currentIndex] = it; + } + + // Set the context object... + + it.set(newCode,element); + + // Trace... + + traceln(toTrialString(it)); + + // Return... + + return it; + } + + /** + * Pop an element from the stack. + * @return the new current element or null if top. + */ + public TypeContext pop (boolean wasValid) { + + if (currentIndex < 0) { + throw new CompilerError("Nothing on stack!"); + } + + newCode = stack[currentIndex].getCode(); + traceln(toResultString(stack[currentIndex],wasValid,false)); + + Type last = stack[currentIndex].getCandidateType(); + if (last != null) { + + // Set status... + + if (wasValid) { + last.setStatus(Constants.STATUS_VALID); + } else { + last.setStatus(Constants.STATUS_INVALID); + } + } + + currentIndex--; + + if (currentIndex < 0) { + + // Done parsing, so update the invalid types + // if this type was valid... + + if (wasValid) { + Type.updateAllInvalidTypes(this); + } + return null; + } else { + return stack[currentIndex]; + } + } + + /** + * Get the current size. + */ + public int size () { + return currentIndex + 1; + } + + /** + * Get a specific context. + */ + public TypeContext getContext (int index) { + + if (currentIndex < index) { + throw new Error("Index out of range"); + } + return stack[index]; + } + + /** + * Get the current top context. + */ + public TypeContext getContext () { + + if (currentIndex < 0) { + throw new Error("Nothing on stack!"); + } + return stack[currentIndex]; + } + + /** + * Is parent context a value type? + */ + public boolean isParentAValue () { + + if (currentIndex > 0) { + return stack[currentIndex - 1].isValue(); + } else { + return false; + } + } + + /** + * Get parent context. Null if none. + */ + public TypeContext getParentContext () { + + if (currentIndex > 0) { + return stack[currentIndex - 1]; + } else { + return null; + } + } + + /** + * Get a string for the context name... + */ + public String getContextCodeString () { + + if (currentIndex >= 0) { + return CODE_NAMES[newCode]; + } else { + return CODE_NAMES[0]; + } + } + + /** + * Get a string for the given context code... + */ + public static String getContextCodeString (int contextCode) { + return CODE_NAMES[contextCode]; + } + + private String toTrialString(TypeContext it) { + int code = it.getCode(); + if (code != METHOD && code != MEMBER) { + return it.toString() + " (trying " + it.getTypeDescription() + ")"; + } else { + return it.toString(); + } + } + + private String toResultString (TypeContext it, boolean result, boolean preExisting) { + int code = it.getCode(); + if (code != METHOD && code != MEMBER) { + if (result) { + String str = it.toString() + " --> " + it.getTypeDescription(); + if (preExisting) { + return str + " [Previously mapped]"; + } else { + return str; + } + } + } else { + if (result) { + return it.toString() + " --> [Mapped]"; + } + } + return it.toString() + " [Did not map]"; + } + + public void clear () { + for (int i = 0; i < stack.length; i++) { + if (stack[i] != null) stack[i].destroy(); + } + } +} + + +class TypeContext { + + public void set(int code, ContextElement element) { + this.code = code; + this.element = element; + if (element instanceof ValueType) { + isValue = true; + } else { + isValue = false; + } + } + + public int getCode() { + return code; + } + + public String getName() { + return element.getElementName(); + } + + public Type getCandidateType() { + if (element instanceof Type) { + return (Type) element; + } else { + return null; + } +} + +public String getTypeDescription() { + if (element instanceof Type) { + return ((Type) element).getTypeDescription(); + } else { + return "[unknown type]"; + } +} + +public String toString () { + if (element != null) { + return ContextStack.getContextCodeString(code) + element.getElementName(); + } else { + return ContextStack.getContextCodeString(code) + "null"; + } +} + +public boolean isValue () { + return isValue; +} + + public boolean isConstant () { + return code == ContextStack.MEMBER_CONSTANT; + } + + public void destroy() { + if (element instanceof Type) { + ((Type)element).destroy(); + } + element = null; + } + + private int code = 0; + private ContextElement element = null; + private boolean isValue = false; +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/DirectoryLoader.java b/rmic/src/main/java/org/glassfish/rmic/iiop/DirectoryLoader.java new file mode 100644 index 000000000..f0baffd9e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/DirectoryLoader.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import java.util.Hashtable; +import java.io.File; +import java.io.FileInputStream; + +/** + * DirectoryLoader is a simple ClassLoader which loads from a specified + * file system directory. + * @author Bryan Atsatt + */ + +public class DirectoryLoader extends ClassLoader { + + private Hashtable cache; + private File root; + + /** + * Constructor. + */ + public DirectoryLoader (File rootDir) { + cache = new Hashtable(); + if (rootDir == null || !rootDir.isDirectory()) { + throw new IllegalArgumentException(); + } + root = rootDir; + } + + private DirectoryLoader () {} + + /** + * Convenience version of loadClass which sets 'resolve' == true. + */ + public Class loadClass(String className) throws ClassNotFoundException { + return loadClass(className, true); + } + + /** + * This is the required version of loadClass which is called + * both from loadClass above and from the internal function + * FindClassFromClass. + */ + public synchronized Class loadClass(String className, boolean resolve) + throws ClassNotFoundException { + Class result; + byte classData[]; + + // Do we already have it in the cache? + + result = (Class) cache.get(className); + + if (result == null) { + + // Nope, can we get if from the system class loader? + + try { + + result = super.findSystemClass(className); + + } catch (ClassNotFoundException e) { + + // No, so try loading it... + + classData = getClassFileData(className); + + if (classData == null) { + throw new ClassNotFoundException(); + } + + // Parse the class file data... + + result = defineClass(classData, 0, classData.length); + + if (result == null) { + throw new ClassFormatError(); + } + + // Resolve it... + + if (resolve) resolveClass(result); + + // Add to cache... + + cache.put(className, result); + } + } + + return result; + } + + /** + * Reurn a byte array containing the contents of the class file. Returns null + * if an exception occurs. + */ + private byte[] getClassFileData (String className) { + + byte result[] = null; + FileInputStream stream = null; + + // Get the file... + + File classFile = new File(root,className.replace('.',File.separatorChar) + ".class"); + + // Now get the bits... + + try { + stream = new FileInputStream(classFile); + result = new byte[stream.available()]; + stream.read(result); + } catch(ThreadDeath death) { + throw death; + } catch (Throwable e) { + } + + finally { + if (stream != null) { + try { + stream.close(); + } catch(ThreadDeath death) { + throw death; + } catch (Throwable e) { + } + } + } + + return result; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/Generator.java b/rmic/src/main/java/org/glassfish/rmic/iiop/Generator.java new file mode 100644 index 000000000..deaa71d82 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/Generator.java @@ -0,0 +1,371 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.Main; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassFile; +import org.glassfish.rmic.tools.java.ClassPath; +import org.glassfish.rmic.tools.java.Identifier; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.HashSet; + +/** + * Generator provides a small framework from which IIOP-specific + * generators can inherit. Common logic is implemented here which uses + * both abstract methods as well as concrete methods which subclasses may + * want to override. The following methods must be present in any subclass: + *

                + *      Default constructor
                + *              CompoundType getTopType(BatchEnvironment env, ClassDefinition cdef);
                + *      int parseArgs(String argv[], int currentIndex);
                + *      boolean requireNewInstance();
                + *              OutputType[] getOutputTypesFor(CompoundType topType,
                + *                                     HashSet alreadyChecked);
                + *              String getFileNameExtensionFor(OutputType outputType);
                + *              void writeOutputFor (   OutputType outputType,
                + *                              HashSet alreadyChecked,
                + *                                                              IndentingWriter writer) throws IOException;
                + * 
                + * @author Bryan Atsatt + */ +public abstract class Generator implements org.glassfish.rmic.Generator, + org.glassfish.rmic.iiop.Constants { + + private boolean alwaysGenerate = false; + private BatchEnvironment env = null; + private boolean trace = false; + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param main Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + if (argv[i].equalsIgnoreCase("-always") || + argv[i].equalsIgnoreCase("-alwaysGenerate")) { + alwaysGenerate = true; + argv[i] = null; + } else if (argv[i].equalsIgnoreCase("-xtrace")) { + trace = true; + argv[i] = null; + } + } + } + return true; + } + + /** + * Return true if non-conforming types should be parsed. + * @param stack The context stack. + */ + protected abstract boolean parseNonConforming(ContextStack stack); + + /** + * Create and return a top-level type. + * @param cdef The top-level class definition. + * @param stack The context stack. + * @return The compound type or null if is non-conforming. + */ + protected abstract CompoundType getTopType(ClassDefinition cdef, ContextStack stack); + + /** + * Return an array containing all the file names and types that need to be + * generated for the given top-level type. The file names must NOT have an + * extension (e.g. ".java"). + * @param topType The type returned by getTopType(). + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + */ + protected abstract OutputType[] getOutputTypesFor(CompoundType topType, + HashSet alreadyChecked); + + /** + * Return the file name extension for the given file name (e.g. ".java"). + * All files generated with the ".java" extension will be compiled. To + * change this behavior for ".java" files, override the compileJavaSourceFile + * method to return false. + * @param outputType One of the items returned by getOutputTypesFor(...) + */ + protected abstract String getFileNameExtensionFor(OutputType outputType); + + /** + * Write the output for the given OutputFileName into the output stream. + * @param outputType One of the items returned by getOutputTypesFor(...) + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + * @param writer The output stream. + */ + protected abstract void writeOutputFor(OutputType outputType, + HashSet alreadyChecked, + IndentingWriter writer) throws IOException; + + /** + * Return true if a new instance should be created for each + * class on the command line. Subclasses which return true + * should override newInstance() to return an appropriately + * constructed instance. + */ + protected abstract boolean requireNewInstance(); + + /** + * Return true if the specified file needs generation. + */ + private boolean requiresGeneration(File target, Type theType) { + + boolean result = alwaysGenerate; + + if (!result) { + + // Get a ClassFile instance for base source or class + // file. We use ClassFile so that if the base is in + // a zip file, we can still get at it's mod time... + + ClassFile baseFile; + ClassPath path = env.getClassPath(); + String className = theType.getQualifiedName().replace('.',File.separatorChar); + + // First try the source file... + + baseFile = path.getFile(className + ".source"); + + if (baseFile == null) { + + // Then try class file... + + baseFile = path.getFile(className + ".class"); + } + + // Do we have a baseFile? + + if (baseFile != null) { + + // Yes, grab baseFile's mod time... + + long baseFileMod = baseFile.lastModified(); + + // Get a File instance for the target. If it is a source + // file, create a class file instead since the source file + // will frequently be deleted... + + String targetName = IDLNames.replace(target.getName(),".java",".class"); + String parentPath = target.getParent(); + File targetFile = new File(parentPath,targetName); + + // Does the target file exist? + + if (targetFile.exists()) { + + // Yes, so grab it's mod time... + + long targetFileMod = targetFile.lastModified(); + + // Set result... + + result = targetFileMod < baseFileMod; + + } else { + + // No, so we must generate... + + result = true; + } + } else { + + // No, so we must generate... + + result = true; + } + } + + return result; + } + + /** + * Create and return a new instance of self. Subclasses + * which need to do something other than default construction + * must override this method. + */ + private Generator newInstance() { + Generator result = null; + try { + result = getClass().newInstance(); + } + catch (Exception ignored){} // Should ALWAYS work! + + return result; + } + + /** + * Default constructor for subclasses to use. + */ + Generator() { + } + + /** + * Generate output. Any source files created which need compilation should + * be added to the compiler environment using the addGeneratedFile(File) + * method. + * @param env The compiler environment + * @param destDir The directory for the root of the package hierarchy + * @param cdef The definition for the implementation class or interface from + * which to generate output + */ + public void generate(org.glassfish.rmic.BatchEnvironment env, File destDir, ClassDefinition cdef) { + + this.env = (BatchEnvironment) env; + ContextStack contextStack = new ContextStack(this.env); + contextStack.setTrace(trace); + + // Make sure the environment knows whether or not to parse + // non-conforming types. This will clear out any previously + // parsed types if necessary... + + this.env.setParseNonConforming(parseNonConforming(contextStack)); + + // Get our top level type... + + CompoundType topType = getTopType(cdef, contextStack); + if (topType != null) { + + Generator generator = this; + + // Do we need to make a new instance? + + if (requireNewInstance()) { + + // Yes, so make one. 'this' instance is the one instantiated by Main + // and which knows any needed command line args... + + generator = newInstance(); + } + + // Now generate all output files... + + generator.generateOutputFiles(topType, this.env, destDir); + } + } + + /** + * Create and return a new instance of self. Subclasses + * which need to do something other than default construction + * must override this method. + */ + private void generateOutputFiles(CompoundType topType, + BatchEnvironment env, + File destDir) { + + // Grab the 'alreadyChecked' HashSet from the environment... + + HashSet alreadyChecked = env.alreadyChecked; + + // Ask subclass for a list of output types... + + OutputType[] types = getOutputTypesFor(topType,alreadyChecked); + + // Process each file... + + for (OutputType type : types) { + File file = getFileFor(type, destDir); + + if (!requiresGeneration(file, type.getType())) { + if (env.verbose()) env.output(Main.getText("rmic.previously.generated", file.getPath())); + } else { + // Now create an output stream and ask subclass to fill it up... + + try { + IndentingWriter out = new IndentingWriter( + new OutputStreamWriter(new FileOutputStream(file)), INDENT_STEP, TAB_SIZE); + + long startTime = !env.verbose() ? 0 : System.currentTimeMillis(); + writeOutputFor(type, alreadyChecked, out); + out.close(); + + if (env.verbose()) { + long duration = System.currentTimeMillis() - startTime; + env.output(Main.getText("rmic.generated", file.getPath(), Long.toString(duration))); + } + postProcessFile(env, file); + } catch (IOException e) { + env.error(0, "cant.write", file.toString()); + return; + } + } + } + } + + protected void postProcessFile(BatchEnvironment env, File file) throws FileNotFoundException {} + + /** + * Return the File object that should be used as the output file + * for the given OutputType. + * @param outputType The type to create a file for. + * @param destinationDir The directory to use as the root of the + * package heirarchy. May be null, in which case the current + * classpath is searched to find the directory in which to create + * the output file. If that search fails (most likely because the + * package directory lives in a zip or jar file rather than the + * file system), the current user directory is used. + */ + private File getFileFor(OutputType outputType, File destinationDir) { + // Calling this method does some crucial initialization + // in a subclass implementation. Don't skip it. + Identifier id = getOutputId(outputType); + File packageDir = getOutputDirectory(destinationDir, id, env); + String classFileName = outputType.getName() + getFileNameExtensionFor(outputType); + return new File(packageDir, classFileName); + } + + protected abstract File getOutputDirectory(File destinationDir, Identifier id, BatchEnvironment environment); + + + /** + * Return an identifier to use for output. + * @param outputType the type for which output is to be generated. + * @return the new identifier. This implementation returns the input parameter. + */ + protected Identifier getOutputId (OutputType outputType) { + return outputType.getType().getIdentifier(); + } + + //_____________________________________________________________________ + // OutputType is a simple wrapper for a name and a Type + //_____________________________________________________________________ + + public class OutputType { + private String name; + private Type type; + + OutputType(String name, Type type) { + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public Type getType() { + return type; + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/IDLGenerator.java b/rmic/src/main/java/org/glassfish/rmic/iiop/IDLGenerator.java new file mode 100644 index 000000000..25552c89a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/IDLGenerator.java @@ -0,0 +1,2069 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.Main; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Identifier; + +import java.io.File; +import java.io.IOException; +import java.text.DateFormat; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Locale; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + * An IDL generator for rmic. + * + * @author Steve Newberry, Bryan Atsatt + */ +public class IDLGenerator extends org.glassfish.rmic.iiop.Generator { + + private boolean valueMethods = true; + private boolean factory = true; //init==!factory + private Hashtable ifHash = new Hashtable(); //IDL file Hashtable + private Hashtable imHash = new Hashtable(); //IDL module Hashtable + + private boolean isThrown = true; //flag for writeInclude + private boolean isException = true; //flag for writeBanner, writeIfndef + private boolean isForward = true; //flag for writeIfndef + private boolean forValuetype = true; //flag for writeInherits + + /** + * Default constructor for Main to use. + */ + public IDLGenerator() { + } + + @Override + protected File getOutputDirectory(File destinationDir, Identifier id, BatchEnvironment environment) { + return Util.getOutputDirectoryForIDL(id, destinationDir, environment); + } + + + /** + * Return true if a new instance should be created for each + * class on the command line. Subclasses which return true + * should override newInstance() to return an appropriately + * constructed instance. + */ + protected boolean requireNewInstance() { + return false; + } + + /** + * Return true if non-conforming types should be parsed. + * @param stack The context stack. + */ + protected boolean parseNonConforming(ContextStack stack) { + return valueMethods; + } + + /** + * Create and return a top-level type. + * @param cdef The top-level class definition. + * @param stack The context stack. + * @return An RemoteType or null if is non-conforming. + */ + protected org.glassfish.rmic.iiop.CompoundType getTopType(ClassDefinition cdef, + ContextStack stack) { + return CompoundType.forCompound(cdef,stack); + } + + + /** + * Return an Identifier which contains the fully-qualified IDL filename + * for the given OutputType. + * The OutputType contains a filename string (not directory) and Type. + * @param ot the OutputType for which directory nesting is to be defined. + * @return the new identifier. + */ + protected Identifier getOutputId ( + OutputType ot ) { + Identifier id = super.getOutputId( ot ); + + Type t = ot.getType(); + String fName = ot.getName(); + + if ( id == idJavaLangClass ) //java.lang.Class and array of + if ( t.isArray() ) + return Identifier.lookup( + "org.omg.boxedRMI.javax.rmi.CORBA." + fName ); + else return idClassDesc; + + if ( id == idJavaLangString && //array of java.lang.String + t.isArray() ) + return Identifier.lookup( "org.omg.boxedRMI.CORBA." + fName ); + + if ( "org.omg.CORBA.Object".equals( t.getQualifiedName() ) && + t.isArray() ) //array of org.omg.CORBA.Object + return Identifier.lookup( "org.omg.boxedRMI." + fName ); + + if ( t.isArray()) { //array + ArrayType at = (ArrayType)t; + Type et = at.getElementType(); + if ( et.isCompound() ) { + CompoundType ct = (CompoundType)et; + String qName = ct.getQualifiedName(); + if ( ct.isIDLEntity() ) + return Identifier.lookup( getQualifiedName( at ) ); + } + return Identifier.lookup( idBoxedRMI,id ); + } + + if ( t.isCompound() ) { //boxed IDLEntity + CompoundType ct = (CompoundType)t; + String qName = ct.getQualifiedName(); + if ( ct.isBoxed() ) + return Identifier.lookup( getQualifiedName( ct ) ); + } + + return id; + } + + + + /** + * Return the file name extension for the given file name (e.g. ".java"). + * All files generated with the ".java" extension will be compiled. To + * change this behavior for ".java" files, override the compileJavaSourceFile + * method to return false. + * @param outputType One of the items returned by getOutputTypesFor(...) + */ + protected String getFileNameExtensionFor(OutputType outputType) { + return IDL_FILE_EXTENSION; + } + + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param main Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + boolean result = super.parseArgs(argv,main); + String idlFrom; + String idlTo; + if (result) { + nextArg: + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + if (argv[i].equalsIgnoreCase("-idl")) { + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-valueMethods" ) ) { + valueMethods = true; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-noValueMethods" ) ) { + valueMethods = false; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-init" ) ) { + factory = false; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-factory" ) ) { + factory = true; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-idlfile" ) ) { + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlFrom = argv[i]; + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlTo = argv[i]; + argv[i] = null; + ifHash.put( idlFrom,idlTo ); + continue nextArg; + } + } + main.error("rmic.option.requires.argument", "-idlfile"); + result = false; + } + else if ( argv[i].equalsIgnoreCase( "-idlmodule" ) ) { + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlFrom = argv[i]; + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlTo = argv[i]; + argv[i] = null; + imHash.put( idlFrom,idlTo ); + continue nextArg; + } + } + main.error("rmic.option.requires.argument", "-idlmodule"); + result = false; + } + + + } + } + } + return result; + } + + + + /** + * Return an array of OutputTypes for the IDL files that need to be + * generated for the given top-level type. + * OutputTypes contain filename string (not directory) and Type. + * @param topType The type returned by getTopType(). + * @param alreadyChecked A set of Types which have already been checked. + * @return Array of OutputTypes to generate + */ + protected OutputType[] getOutputTypesFor( + CompoundType topType, + HashSet alreadyChecked ) { + Vector refVec = getAllReferencesFor( topType ); + Vector outVec = new Vector(); + for ( int i1 = 0; i1 < refVec.size(); i1++ ) { //forall references + Type t = (Type)refVec.elementAt( i1 ); + if ( t.isArray() ) { + ArrayType at = (ArrayType)t; + int dim = at.getArrayDimension(); + Type et = at.getElementType(); + String fName = unEsc( et.getIDLName() ).replace( ' ','_' ); + for ( int i2 = 0; i2 < dim; i2++ ) { //foreach dimension + String fileName = "seq" + ( i2 + 1 ) + "_" + fName; + outVec.addElement( new OutputType( fileName,at ) ); + } + } + else if ( t.isCompound() ) { + String fName = unEsc( t.getIDLName() ); + outVec.addElement( new OutputType( fName.replace( ' ','_' ),t ) ); + if ( t.isClass() ) { + ClassType ct = (ClassType)t; + if ( ct.isException() ) { //exception file + fName = unEsc( ct.getIDLExceptionName() ); + outVec.addElement( new OutputType( fName.replace( ' ','_' ),t ) ); + } + } + } + } + OutputType[] outArr = new OutputType[outVec.size()]; + outVec.copyInto( outArr ); + return outArr; + } + + /** + * Get all referenced types of a given tyoe for which an IDL file needs + * to be generated. + * @param ct The given type. + * @return Vector of Types for which IDL must be generated. + */ + protected Vector getAllReferencesFor( + CompoundType ct ) { + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + int refSize; + refHash.put( ct.getQualifiedName(),ct ); //put the given type + accumulateReferences( refHash,spcHash,arrHash ); + do { + refSize = refHash.size(); + accumulateReferences( refHash,spcHash,arrHash ); + } + while ( refSize < refHash.size() ); //till hashtable stays same size + + Vector outVec = new Vector(); + Enumeration e = refHash.elements(); //ordinary references + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + outVec.addElement( t ); + } + e = spcHash.elements(); //special references + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + outVec.addElement( t ); + } + e = arrHash.elements(); //array references + nextSequence: + while ( e.hasMoreElements() ) { + ArrayType at = (ArrayType)e.nextElement(); + int dim = at.getArrayDimension(); + Type et = at.getElementType(); + Enumeration e2 = arrHash.elements(); + while ( e2.hasMoreElements() ) { //eliminate duplicates + ArrayType at2 = (ArrayType)e2.nextElement(); + if ( et == at2.getElementType() && //same element type & + dim < at2.getArrayDimension() ) //smaller dimension? + continue nextSequence; //ignore this one + } + outVec.addElement( at ); + } + return outVec; + } + + + /** + * Accumulate and filter all those types that are referenced by the given + * referenced types. + * Keep only those for which IDL is to be generated. + * @param refHash Hashtable containing the given types + * @param spcHash Hashtable containing referenced specials (IDL typedefs) + * @param arrHash Hashtable containing referenced arrays (dimensioned) + */ + protected void accumulateReferences( + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash ) { + Enumeration e = refHash.elements(); + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + Vector datVec = getData( t ); //collect and sort data + Vector mthVec = getMethods( t ); //collect and filter methods + getInterfaces( t,refHash ); //collect interfaces + getInheritance( t,refHash ); //add inheritance + getMethodReferences( mthVec,refHash,spcHash,arrHash,refHash ); + getMemberReferences( datVec,refHash,spcHash,arrHash ); + } + e = arrHash.elements(); //add array element references + while ( e.hasMoreElements() ) { + ArrayType at = (ArrayType)e.nextElement(); + Type et = at.getElementType(); + addReference( et,refHash,spcHash,arrHash ); + } + e = refHash.elements(); + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + if ( !isIDLGeneratedFor( t ) ) //remove if no IDL generation + refHash.remove( t.getQualifiedName() ); + } + } + + + + /** + * Determine if IDL should be generated for a referenced type. + * Do not generate IDL for a CORBA Object reference. It gets mapped + * to the original IDL or to Object (if exactly org.omg.CORBA.Object) + * Generate (boxed) IDL for an IDL Entity unless it is an IDL user + * exception, a ValueBase, an AbstractBase (or a CORBA Object). + * Do not generate IDL for Implementation classes..unless they inherit + * from multiple distinct remote interfaces + * @param t The type to check. + * @return true or false + */ + protected boolean isIDLGeneratedFor( + CompoundType t ) { + if ( t.isCORBAObject() ) return false; + if ( t.isIDLEntity() ) + if ( t.isBoxed() ) return true; + else if ( "org.omg.CORBA.portable.IDLEntity" + .equals( t.getQualifiedName() ) ) return true; + else if ( t.isCORBAUserException() ) return true; + else return false; + Hashtable inhHash = new Hashtable(); + getInterfaces( t,inhHash ); + if ( t.getTypeCode() == TYPE_IMPLEMENTATION ) + if ( inhHash.size() < 2 ) return false; //no multiple inheritance + else return true; + return true; //generate IDL for this type + } + + + /** + * Write the output for the given OutputFileName into the output stream. + * (The IDL mapping for java.lang.Class is generated from + * javax.rmi.CORBA.ClassDesc in the tools workspace) + * @param ot One of the items returned by getOutputTypesFor(...) + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + * @param p The output stream. + */ + protected void writeOutputFor( + OutputType ot, + HashSet alreadyChecked, + IndentingWriter p ) + throws IOException { + Type t = ot.getType(); + if ( t.isArray() ) { //specialcase: sequence + writeSequence( ot,p ); + return; + } + if ( isSpecialReference( t ) ) { //specialcase: IDL typecode + writeSpecial( t,p ); + return; + } + if ( t.isCompound() ) { //specialcase: boxed IDL + CompoundType ct = (CompoundType)t; + if ( ct.isIDLEntity() && ct.isBoxed() ) { + writeBoxedIDL( ct,p ); + return; + } + } + if ( t.isClass() ) { //specialcase: exception + ClassType ct = (ClassType)t; + if ( ct.isException() ) { + String eName = unEsc( ct.getIDLExceptionName() ); + String fName = ot.getName(); + if ( fName.equals( eName.replace( ' ','_' ) ) ) { + writeException( ct,p ); + return; + } + } + } + switch ( t.getTypeCode() ) { //general case + case TYPE_IMPLEMENTATION: + writeImplementation( (ImplementationType)t,p ); + break; + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: + writeNCType( (CompoundType)t,p ); + break; + case TYPE_ABSTRACT: //AbstractType is a RemoteType + case TYPE_REMOTE: + writeRemote( (RemoteType)t,p ); + break; + case TYPE_VALUE: + writeValue( (ValueType)t,p ); + break; + default: + throw new CompilerError( + "IDLGenerator got unexpected type code: " + + t.getTypeCode()); + } + } + + + /** + * Write an IDL interface definition for a Java implementation class + * @param t The current ImplementationType + * @param p The output stream. + */ + protected void writeImplementation( + ImplementationType t, + IndentingWriter p ) + throws IOException { + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + + writeBanner( t,0,!isException,p ); + writeInheritedIncludes( inhHash,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeIncOrb( p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.p( "interface " + t.getIDLName() ); + writeInherits( inhHash,!forValuetype,p ); + + p.pln( " {" ); + p.pln( "};" ); + + p.pO();p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write an IDL valuetype definition for + * 1) a nonconforming Java class + * 2) a nonconforming Java interface (that is not an AbstractType) + * @param t The current NC Type (NCClassType or NCInterfaceType) + * @param p The output stream. + */ + protected void writeNCType( + CompoundType t, + IndentingWriter p ) + throws IOException { + Vector conVec = getConstants( t ); //collect constants + Vector mthVec = getMethods( t ); //collect methods + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + Hashtable excHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + getInheritance( t,inhHash ); //add inheritance + getMethodReferences( mthVec,refHash,spcHash,arrHash,excHash ); + + writeProlog( t,refHash,spcHash,arrHash,excHash,inhHash,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.p( "abstract valuetype " + t.getIDLName() ); + writeInherits( inhHash,!forValuetype,p ); + + p.pln( " {" ); + if ( conVec.size() + mthVec.size() > 0 ) { //any content? + p.pln();p.pI(); + for ( int i1 = 0; i1 < conVec.size(); i1++ ) //write constants + writeConstant( (CompoundType.Member)conVec.elementAt( i1 ),p ); + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) //write methods + writeMethod( (CompoundType.Method)mthVec.elementAt( i1 ),p ); + p.pO();p.pln(); + } + p.pln( "};" ); + + p.pO();p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write an IDL interface definition for either: + * 1) a conforming Java remote interface (RemoteType)..or + * 2) a non-conforming Java interface whose methods all throw + * java.rmi.RemoteException (AbstractType) + * @param t The current RemoteType + * @param p The output stream. + */ + protected void writeRemote( + RemoteType t, + IndentingWriter p ) + throws IOException { + Vector conVec = getConstants( t ); //collect constants + Vector mthVec = getMethods( t ); //collect methods + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + Hashtable excHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + getMethodReferences( mthVec,refHash,spcHash,arrHash,excHash ); + + writeProlog( t,refHash,spcHash,arrHash,excHash,inhHash,p ); + writeModule1( t,p ); + p.pln();p.pI(); + if ( t.getTypeCode() == TYPE_ABSTRACT ) p.p( "abstract " ); + p.p( "interface " + t.getIDLName() ); + writeInherits( inhHash,!forValuetype,p ); + + p.pln( " {" ); + if ( conVec.size() + mthVec.size() > 0 ) { //any constants or methods? + p.pln();p.pI(); + for ( int i1 = 0; i1 < conVec.size(); i1++ ) //constants + writeConstant( (CompoundType.Member)conVec.elementAt( i1 ),p ); + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) //methods, attributes + writeMethod( (CompoundType.Method)mthVec.elementAt( i1 ),p ); + p.pO();p.pln(); + } + p.pln( "};" ); + + p.pO();p.pln(); + writeRepositoryID ( t,p ); + p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write an IDL valuetype definition for a conforming Java class. + * Methods and constructors are optional..controlled by -valueMethods flag + * @param t The current ValueType + * @param p The output stream. + */ + protected void writeValue( + ValueType t, + IndentingWriter p ) + throws IOException { + Vector datVec = getData( t ); //collect and sort data + Vector conVec = getConstants( t ); //collect constants + Vector mthVec = getMethods( t ); //collect and filter methods + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + Hashtable excHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + getInheritance( t,inhHash ); //add inheritance + getMethodReferences( mthVec,refHash,spcHash,arrHash,excHash ); + getMemberReferences( datVec,refHash,spcHash,arrHash ); + + writeProlog( t,refHash,spcHash,arrHash,excHash,inhHash,p ); + writeModule1( t,p ); + p.pln();p.pI(); + if ( t.isCustom() ) p.p( "custom " ); + p.p( "valuetype " + t.getIDLName() ); + writeInherits( inhHash,forValuetype,p ); + + p.pln( " {" ); + if ( conVec.size() + datVec.size() + mthVec.size() > 0 ) { //any content? + p.pln();p.pI(); + for ( int i1 = 0; i1 < conVec.size(); i1++ ) //write constants + writeConstant( (CompoundType.Member)conVec.elementAt( i1 ),p ); + for ( int i1 = 0; i1 < datVec.size(); i1++ ) { + CompoundType.Member mem = (CompoundType.Member)datVec.elementAt( i1 ); + if ( mem.getType().isPrimitive() ) + writeData( mem,p ); //write primitive data + } + for ( int i1 = 0; i1 < datVec.size(); i1++ ) { + CompoundType.Member mem = (CompoundType.Member)datVec.elementAt( i1 ); + if ( !mem.getType().isPrimitive() ) + writeData( mem,p ); //write non-primitive data + } + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) //write methods + writeMethod( (CompoundType.Method)mthVec.elementAt( i1 ),p ); + p.pO();p.pln(); + } + p.pln( "};" ); + + p.pO();p.pln(); + writeRepositoryID ( t,p ); + p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write IDL prolog for a CompoundType. + * @param t The CompoundType. + * @param refHash Hashtable loaded with type references. + * @param spcHash Hashtable loaded with special type references. + * @param arrHash Hashtable loaded with array references. + * @param excHash Hashtable loaded with exceptions thrown. + * @param inhHash Hashtable loaded with inherited types. + * @param p The output stream. + */ + protected void writeProlog( + CompoundType t, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash, + Hashtable excHash, + Hashtable inhHash, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeForwardReferences( refHash,p ); + writeIncludes( excHash,isThrown,p ); //#includes for exceptions thrown + writeInheritedIncludes( inhHash,p ); + writeIncludes( spcHash,!isThrown,p ); //#includes for special types + writeBoxedRMIIncludes( arrHash,p ); + writeIDLEntityIncludes( refHash,p ); + writeIncOrb( p ); + writeIfndef( t,0,!isException,!isForward,p ); + } + + + /** + * Write IDL epilog for a CompoundType. + * @param t The CompoundType. + * @param refHash Hashtable loaded with type references. + * @param p The output stream. + */ + protected void writeEpilog( + CompoundType t, + Hashtable refHash, + IndentingWriter p ) + throws IOException { + writeIncludes( refHash,!isThrown,p ); //#includes for forward dcl types + writeEndif( p ); + } + + + + /** + * Write special typedef + * @param t A special Type. + * @param p The output stream. + */ + protected void writeSpecial( + Type t, + IndentingWriter p ) + throws IOException { + String spcName = t.getQualifiedName(); + if ( "java.io.Serializable".equals( spcName ) ) + writeJavaIoSerializable( t,p ); + else if ( "java.io.Externalizable".equals( spcName ) ) + writeJavaIoExternalizable( t,p ); + else if ( "java.lang.Object".equals( spcName) ) + writeJavaLangObject( t,p ); + else if ( "java.rmi.Remote".equals( spcName) ) + writeJavaRmiRemote( t,p ); + else if ( "org.omg.CORBA.portable.IDLEntity".equals( spcName) ) + writeIDLEntity( t,p ); + } + + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.io.Serializable. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaIoSerializable( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any Serializable;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.io.Externalizable. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaIoExternalizable( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any Externalizable;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.lang.Object. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaLangObject( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any _Object;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.rmi.Remote. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaRmiRemote( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef Object Remote;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + + /** + * Write a hard-coded IDL typedef definition for the special case + * org.omg.CORBA.portable.IDLEntity + * @param t The current Type + * @param p The output stream. + */ + protected void writeIDLEntity( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any IDLEntity;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Filter and collect non-duplicate inherited interfaces for a type + * @param ct The current CompoundType + * @param inhHash Hashtable containing the inherited interfaces + */ + protected void getInterfaces( + CompoundType ct, + Hashtable inhHash ) { + InterfaceType[] infs = ct.getInterfaces(); + nextInterface: + for ( int i1 = 0; i1 < infs.length; i1++ ) { //forall inherited interfaces + String inhName = infs[i1].getQualifiedName(); + switch ( ct.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_VALUE: //filter for classes + if ( "java.io.Externalizable".equals( inhName ) || + "java.io.Serializable".equals( inhName ) || + "org.omg.CORBA.portable.IDLEntity".equals( inhName ) ) + continue nextInterface; + break; + default: //filter for all others + if ( "java.rmi.Remote".equals( inhName ) ) + continue nextInterface; + break; + } + inhHash.put( inhName,infs[i1] ); //add this one + } + } + + + /** + * Filter and add base class inheritance for a class type + * @param ct The current CompoundType + * @param inhHash Hashtable containing inherited types + */ + protected void getInheritance( + CompoundType ct, + Hashtable inhHash ) { + ClassType par = ct.getSuperclass(); //get parent + if ( par == null ) return; + String parName = par.getQualifiedName(); + switch ( ct.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_VALUE: + if ( "java.lang.Object".equals( parName ) ) //this is implicit + return; + break; + default: return; //ignore other types + } + inhHash.put( parName,par ); //add valid base class + } + + + /** + * Collect and filter type and array references from methods + * @param mthVec Given Vector of methods + * @param refHash Hashtable for type references + * @param spcHash Hashtable for special type references + * @param arrHash Hashtable for array references + * @param excHash Hashtable for exceptions thrown + */ + protected void getMethodReferences( + Vector mthVec, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash, + Hashtable excHash ) { + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) { //forall methods + CompoundType.Method mth = (CompoundType.Method)mthVec.elementAt( i1 ); + Type[] args = mth.getArguments(); + Type ret = mth.getReturnType(); + getExceptions( mth,excHash ); //collect exceptions thrown + for ( int i2 = 0; i2 < args.length; i2++ ) //forall arguments + addReference( args[i2],refHash,spcHash,arrHash ); + addReference( ret,refHash,spcHash,arrHash ); + } + } + + + /** + * Collect and filter type and array references from data members + * @param datVec Given Vector of data members + * @param refHash Hashtable for type references + * @param spcHash Hashtable for special type references + * @param arrHash Hashtable for array references + */ + protected void getMemberReferences( + Vector datVec, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash ) { + for ( int i1 = 0; i1 < datVec.size(); i1++ ) { //forall datamembers + CompoundType.Member mem = (CompoundType.Member)datVec.elementAt( i1 ); + Type dat = mem.getType(); + addReference( dat,refHash,spcHash,arrHash ); + } + } + + + /** + * Add reference for given type avoiding duplication. + * Sort into specials, arrays and regular references. + * Filter out types which are not required. + * @param ref Given Type + * @param refHash Hashtable for type references + * @param spcHash Hashtable for special type references + * @param arrHash Hashtable for array references + */ + protected void addReference( + Type ref, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash ) { + String rName = ref.getQualifiedName(); + switch ( ref.getTypeCode() ) { + case TYPE_ABSTRACT: + case TYPE_REMOTE: + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: + case TYPE_VALUE: + refHash.put( rName,ref ); + return; + case TYPE_CORBA_OBJECT: + if ( "org.omg.CORBA.Object".equals( rName ) ) return; //don't want + refHash.put( rName,ref ); + return; + case TYPE_ARRAY: //array? + arrHash.put( rName + ref.getArrayDimension(),ref ); + return; + default: + if ( isSpecialReference( ref ) ) //special IDL typedef? + spcHash.put( rName,ref ); + } + } + + + + /** + * Determine whether given Type is a special reference. + * Special cases are: java.io.Serializable, java.io.Externalizable, + * java.lang.Object, java.rmi.Remote and org.omg.CORBA.portable.IDLEntity + * They are special because they have a hard-coded typedef defined in the + * spec. + * @param ref A referenced Type + * @return boolean indicating whether it's a special reference + */ + protected boolean isSpecialReference( + Type ref ) { + String rName = ref.getQualifiedName(); + if ( "java.io.Serializable".equals( rName ) ) return true; + if ( "java.io.Externalizable".equals( rName ) ) return true; + if ( "java.lang.Object".equals( rName) ) return true; + if ( "java.rmi.Remote".equals( rName) ) return true; + if ( "org.omg.CORBA.portable.IDLEntity".equals( rName) ) return true; + return false; + } + + + /** + * Collect and filter thrown exceptions for a given pre-filtered method. + * Keep only 'checked' exception classes minus java.rmi.RemoteException + * and its subclasses + * @param mth The current method + * @param excHash Hashtable containing non-duplicate thrown exceptions + */ + protected void getExceptions( + CompoundType.Method mth, + Hashtable excHash ) { + ClassType[] excs = mth.getExceptions(); + for ( int i1 = 0; i1 < excs.length; i1++ ) { //forall exceptions + ClassType exc = excs[i1]; + if ( exc.isCheckedException() && + !exc.isRemoteExceptionOrSubclass() ) { + excHash.put( exc.getQualifiedName(),exc ); + } + } + } + + + /** + * Collect and filter methods for a type. + * Remove any private or inherited methods. + * @param ct The current CompoundType + * @return Vector containing the methods + */ + protected Vector getMethods( + CompoundType ct ) { + Vector vec = new Vector(); + int ctType = ct.getTypeCode(); + switch ( ctType ) { + case TYPE_ABSTRACT: + case TYPE_REMOTE: break; + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: + case TYPE_VALUE: if ( valueMethods ) break; + default: return vec; + } + Identifier ctId = ct.getIdentifier(); + CompoundType.Method[] mths = ct.getMethods(); + nextMethod: + for ( int i1 = 0; i1 < mths.length; i1++ ) { //forall methods + if ( mths[i1].isPrivate() || //private method? + mths[i1].isInherited() ) //inherited method? + continue nextMethod; //yes..ignore it + if ( ctType == TYPE_VALUE ) { + String mthName = mths[i1].getName(); + if ( "readObject" .equals( mthName ) || + "writeObject" .equals( mthName ) || + "readExternal".equals( mthName ) || + "writeExternal".equals( mthName ) ) + continue nextMethod; //ignore this one + } + if ( ( ctType == TYPE_NC_CLASS || + ctType == TYPE_NC_INTERFACE ) && + mths[i1].isConstructor() ) //init not valid for abstract valuetype + continue nextMethod; //ignore this one + vec.addElement( mths[i1] ); //add this one + } + return vec; + } + + + /** + * Collect constants for a type. + * A valid constant is a "public final static" field with a compile-time + * constant value for a primitive type or String + * @param ct The current CompoundType + * @return Vector containing the constants + */ + protected Vector getConstants( + CompoundType ct ) { + Vector vec = new Vector(); + CompoundType.Member[] mems = ct.getMembers(); + for ( int i1 = 0; i1 < mems.length; i1++ ) { //forall members + Type memType = mems[i1].getType(); + String memValue = mems[i1].getValue(); + if ( mems[i1].isPublic() && + mems[i1].isFinal() && + mems[i1].isStatic() && + ( memType.isPrimitive() || "String".equals( memType.getName() ) ) && + memValue != null ) + vec.addElement( mems[i1] ); //add this one + } + return vec; + } + + + /** + * Collect and sort data fields for a ValueType. + * Sort in Java (not IDL) Unicode name string lexicographic increasing + * order. + * Non-static, non-transient fields are mapped. + * If the type is a custom valuetype, only public fields are mapped. + * @param t The current CompoundType + * @return Vector containing the data fields + */ + protected Vector getData( + CompoundType t ) { + Vector vec = new Vector(); + if ( t.getTypeCode() != TYPE_VALUE ) return vec; + ValueType vt = (ValueType)t; + CompoundType.Member[] mems = vt.getMembers(); + boolean notCust = !vt.isCustom(); + for ( int i1 = 0; i1 < mems.length; i1++ ) { //forall members + if ( !mems[i1].isStatic() && + !mems[i1].isTransient() && + ( mems[i1].isPublic() || notCust ) ) { + int i2; + String memName = mems[i1].getName(); + for ( i2 = 0; i2 < vec.size(); i2++ ) { //insert in java lex order + CompoundType.Member aMem = (CompoundType.Member)vec.elementAt( i2 ); + if ( memName.compareTo( aMem.getName() ) < 0 ) break; + } + vec.insertElementAt( mems[i1],i2 ); //insert this one + } + } + return vec; + } + + + /** + * Write forward references for referenced interfaces and valuetypes + * ...but not if the reference is to a boxed IDLEntity, + * @param refHash Hashtable loaded with referenced types + * @param p The output stream. + */ + protected void writeForwardReferences( + Hashtable refHash, + IndentingWriter p ) + throws IOException { + Enumeration refEnum = refHash.elements(); + nextReference: + while ( refEnum.hasMoreElements() ) { + Type t = (Type)refEnum.nextElement(); + if ( t.isCompound() ) { + CompoundType ct = (CompoundType)t; + if ( ct.isIDLEntity() ) + continue nextReference; //ignore IDLEntity reference + } + writeForwardReference( t,p ); + } + } + + + /** + * Write forward reference for given type + * @param t Given type + * @param p The output stream. + */ + protected void writeForwardReference( + Type t, + IndentingWriter p ) + throws IOException { + String qName = t.getQualifiedName(); + if ( "java.lang.String".equals( qName ) ) ; + else if ( "org.omg.CORBA.Object".equals( qName ) ) return ; //no fwd dcl + + writeIfndef( t,0,!isException,isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + switch ( t.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: p.p( "abstract valuetype " ); break; + case TYPE_ABSTRACT: p.p( "abstract interface " ); break; + case TYPE_VALUE: p.p( "valuetype " ); break; + case TYPE_REMOTE: + case TYPE_CORBA_OBJECT: p.p( "interface " ); break; + default: ; //all other types were filtered + } + p.pln( t.getIDLName() + ";" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write forward reference for boxed valuetype for single dimension of IDL + * sequence. + * If the dimension is {@literal < 1} and the element is a CompoundType, write a + * forward declare for the element + * @param at ArrayType for forward declare + * @param dim The dimension to write + * @param p The output stream. + */ + protected void writeForwardReference( + ArrayType at, + int dim, + IndentingWriter p) + throws IOException { + Type et = at.getElementType(); + if ( dim < 1 ) { + if ( et.isCompound() ) { + CompoundType ct = (CompoundType)et; + writeForwardReference( et,p); + } + return; + } + String fName = unEsc( et.getIDLName() ).replace( ' ','_' ); + + writeIfndef( at,dim,!isException,isForward,p ); + writeModule1( at,p ); + p.pln();p.pI(); + switch ( et.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: p.p( "abstract valuetype " ); break; + case TYPE_ABSTRACT: p.p( "abstract interface " ); break; + case TYPE_VALUE: p.p( "valuetype " ); break; + case TYPE_REMOTE: + case TYPE_CORBA_OBJECT: p.p( "interface " ); break; + default: ; //all other types were filtered + } + p.pln( "seq" + dim + "_" + fName + ";" ); + p.pO();p.pln(); + writeModule2( at,p ); + writeEndif( p ); + } + + + /** + * Write #includes for boxed IDLEntity references. + * @param refHash Hashtable loaded with referenced types + * @param p The output stream. + */ + protected void writeIDLEntityIncludes( + Hashtable refHash, + IndentingWriter p ) + throws IOException { + Enumeration refEnum = refHash.elements(); + while ( refEnum.hasMoreElements() ) { + Type t = (Type)refEnum.nextElement(); + if ( t.isCompound() ) { + CompoundType ct = (CompoundType)t; + if ( ct.isIDLEntity() ) { //select IDLEntities + writeInclude( ct,0,!isThrown,p ); + refHash.remove( ct.getQualifiedName() ); //avoid another #include + } + } + } + } + + + /** + * Write #includes + * @param incHash Hashtable loaded with Types to include + * @param isThrown true if Types are thrown exceptions + * @param p The output stream. + */ + protected void writeIncludes( + Hashtable incHash, + boolean isThrown, + IndentingWriter p ) + throws IOException { + Enumeration incEnum = incHash.elements(); + while ( incEnum.hasMoreElements() ) { + CompoundType t = (CompoundType)incEnum.nextElement(); + writeInclude( t,0,isThrown,p ); + } + } + + + /** + * Write includes for boxedRMI valuetypes for IDL sequences. + * Write only the maximum dimension found for an ArrayType. + * @param arrHash Hashtable loaded with array types + * @param p The output stream. + */ + protected void writeBoxedRMIIncludes( + Hashtable arrHash, + IndentingWriter p) + throws IOException { + Enumeration e1 = arrHash.elements(); + nextSequence: + while ( e1.hasMoreElements() ) { + ArrayType at = (ArrayType)e1.nextElement(); + int dim = at.getArrayDimension(); + Type et = at.getElementType(); + + Enumeration e2 = arrHash.elements(); + while ( e2.hasMoreElements() ) { //eliminate duplicates + ArrayType at2 = (ArrayType)e2.nextElement(); + if ( et == at2.getElementType() && //same element type & + dim < at2.getArrayDimension() ) //smaller dimension? + continue nextSequence; //ignore this one + } + writeInclude( at,dim,!isThrown,p ); + } + } + + + /** + * Write #includes + * @param inhHash Hashtable loaded with Types to include + * @param p The output stream. + */ + protected void writeInheritedIncludes( + Hashtable inhHash, + IndentingWriter p ) + throws IOException { + Enumeration inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { + CompoundType t = (CompoundType)inhEnum.nextElement(); + writeInclude( t,0,!isThrown,p ); + } + } + + + /** + * Write a #include. + * @param t Type to include + * @param dim The dimension to write if t is an array. + * @param isThrown boolean indicating if include is for thrown exception. + * @param p The output stream. + */ + protected void writeInclude( + Type t, + int dim, + boolean isThrown, + IndentingWriter p) + throws IOException { + CompoundType ct; + String tName; + String[] modNames; + if ( t.isCompound() ) { + ct = (CompoundType)t; + String qName = ct.getQualifiedName(); + if ( "java.lang.String".equals( qName ) ) { + writeIncOrb( p ); //#include orb.idl for String + return; + } + if ( "org.omg.CORBA.Object".equals( qName ) ) + return; //Object treated like primitive + modNames = getIDLModuleNames( ct ); //module name array + tName = unEsc( ct.getIDLName() ); //file name default + + if ( ct.isException() ) + if ( ct.isIDLEntityException() ) + if ( ct.isCORBAUserException() ) + if ( isThrown ) tName = unEsc( ct.getIDLExceptionName() ); + else ; + else tName = ct.getName(); //use original IDL name + else if ( isThrown ) + tName = unEsc( ct.getIDLExceptionName() ); + } + else if ( t.isArray() ) { + Type et = t.getElementType(); //file name for sequence + if ( dim > 0 ) { + modNames = getIDLModuleNames( t ); //module name array + tName = "seq" + dim + "_" + unEsc( et.getIDLName().replace( ' ','_' ) ); + } + else{ //#include element + if ( !et.isCompound() ) return; //no include needed for primitive + ct = (CompoundType) et; + modNames = getIDLModuleNames( ct ); //no boxedRMI for element + tName = unEsc( ct.getIDLName() ); + writeInclude( ct,modNames,tName,p ); + return; + } + } + else return; //no include needed for primitive + writeInclude( t,modNames,tName,p ); + } + + + /** + * Write a #include doing user specified -idlFile translation (if any) for + * IDLEntities. + * @param t Type to include. + * @param modNames Preprocessed module names (default). + * @param tName Preprocessed Type name (default). + * @param p The output stream. + */ + protected void writeInclude( + Type t, + String[] modNames, + String tName, + IndentingWriter p) + throws IOException { + if ( t.isCompound() ) { + CompoundType it = (CompoundType)t; + + if ( ifHash.size() > 0 && //any -idlFile translation to apply + it.isIDLEntity() ) { //..for this IDLEntity? + String qName = t.getQualifiedName(); //fully qualified orig Java name + + Enumeration k = ifHash.keys(); + while ( k.hasMoreElements() ) { //loop thro user-defined -idlFiles + String from = (String)k.nextElement(); + if ( qName.startsWith( from ) ) { //found a match? + String to = (String)ifHash.get( from ); + p.pln( "#include \"" + to + "\"" ); //user-specified idl filename + return; //don't look for any more + } + } + } + } + else if ( t.isArray() ) ; //no -idlFile translation needed for array + else return; //no #include needed for primitive + + p.p( "#include \"" ); //no -idlFile translation required + for ( int i1 = 0; i1 < modNames.length; i1++ ) p.p( modNames[i1] + "/" ); + p.p( tName + ".idl\"" ); + p.pln(); + } + + + /** + * Return the fully qualified Java Name for a Type. + * IDLEntity preprocessing done by getIDLModuleNames(t) + * @param t Given Type + * @return Array containing the original module nesting. + */ + protected String getQualifiedName( + Type t ) { + String[] modNames = getIDLModuleNames( t ); + int len = modNames.length; + StringBuffer buf = new StringBuffer(); + for ( int i1 = 0; i1 < len; i1++ ) + buf.append( modNames[i1] + "." ); + buf.append( t.getIDLName() ); + return buf.toString(); + } + + + /** + * Return the global fully qualified IDL Name for a Type. + * IDLEntity preprocessing done by getIDLModuleNames(t) + * @param t Given Type + * @return Array containing the original module nesting. + */ + protected String getQualifiedIDLName(Type t) { + if ( t.isPrimitive() ) + return t.getIDLName(); + if ( !t.isArray() && + "org.omg.CORBA.Object".equals( t.getQualifiedName() ) ) + return t.getIDLName(); + + String[] modNames = getIDLModuleNames( t ); + int len = modNames.length; + if (len > 0) { + StringBuffer buf = new StringBuffer(); + for ( int i1 = 0; i1 < len; i1++ ) + buf.append( IDL_NAME_SEPARATOR + modNames[i1] ); + buf.append( IDL_NAME_SEPARATOR + t.getIDLName() ); + return buf.toString(); + } else { + return t.getIDLName(); + } + } + + + /** + * Return the IDL module nesting of the given Type. + * For IDLEntity CompoundTypes (or their arrays) apply any user specified + * -idlModule translation or, if none applicable, strip any package + * prefix. + * Add boxedIDL or boxedRMI modules if required. + * @param t Given Type + * @return Array containing the original module nesting. + */ + protected String[] getIDLModuleNames(Type t) { + String[] modNames = t.getIDLModuleNames(); //default module name array + CompoundType ct; + if ( t.isCompound() ) { + ct = (CompoundType)t; + if ( !ct.isIDLEntity ) return modNames; //normal (non-IDLEntity) case + if ( "org.omg.CORBA.portable.IDLEntity" + .equals( t.getQualifiedName() ) ) + return modNames; + } + else if ( t.isArray() ) { + Type et = t.getElementType(); + if ( et.isCompound() ) { + ct = (CompoundType)et; + if ( !ct.isIDLEntity ) return modNames; //normal (non-IDLEntity) case + if ( "org.omg.CORBA.portable.IDLEntity" + .equals( t.getQualifiedName() ) ) + return modNames; + } + else return modNames; + } + else return modNames; //no preprocessing needed for primitives + + //it's an IDLEntity or an array of... + Vector mVec = new Vector(); + if ( !translateJavaPackage( ct,mVec ) ) //apply -idlModule translation + stripJavaPackage( ct,mVec ); //..or strip prefixes (not both) + + if ( ct.isBoxed() ) { //add boxedIDL if required + mVec.insertElementAt( "org",0 ); + mVec.insertElementAt( "omg",1 ); + mVec.insertElementAt( "boxedIDL",2 ); + } + if ( t.isArray() ) { //add boxedRMI if required + mVec.insertElementAt( "org",0 ); + mVec.insertElementAt( "omg",1 ); + mVec.insertElementAt( "boxedRMI",2 ); + } + String[] outArr = new String[mVec.size()]; + mVec.copyInto( outArr ); + return outArr; + } + + + /** + * Apply user specified -idlModule translation to package names of given + * IDLEntity ct. Example: + * -idlModule foo.bar real::mod::nesting + * @param ct CompoundType containing given IDLEntity. + * @param vec Returned Vector of translated IDL module names. + * @return boolean true if any translation was done. + */ + protected boolean translateJavaPackage( + CompoundType ct, + Vector vec ) { + vec.removeAllElements(); + boolean ret = false; + String fc = null; + if ( ! ct.isIDLEntity() ) return ret; + + String pName = ct.getPackageName(); //start from Java package names + if ( pName == null ) return ret; + StringTokenizer pt = new StringTokenizer( pName,"." ); + while ( pt.hasMoreTokens() ) vec.addElement( pt.nextToken() ); + + if ( imHash.size() > 0 ) { //any -idlModule translation to apply? + Enumeration k = imHash.keys(); + + nextModule: + while ( k.hasMoreElements() ) { //loop thro user-defined -idlModules + String from = (String)k.nextElement(); //from String.. + StringTokenizer ft = new StringTokenizer( from,"." ); + int vecLen = vec.size(); + int ifr; + for ( ifr = 0; ifr < vecLen && ft.hasMoreTokens(); ifr++ ) + if ( ! vec.elementAt(ifr).equals( ft.nextToken() ) ) + continue nextModule; //..no match + + if ( ft.hasMoreTokens() ) { //matched so far.. + fc = ft.nextToken(); //a 'from' token remains + if ( ! ct.getName().equals( fc ) || //matches class name? + ft.hasMoreTokens() ) + continue nextModule; //..no match + } + + ret = true; //found a match + for ( int i4 = 0; i4 < ifr; i4++ ) + vec.removeElementAt( 0 ); //remove 'from' package + + String to = (String)imHash.get( from ); //..to String + StringTokenizer tt = new StringTokenizer( to,IDL_NAME_SEPARATOR ); + + int itoco = tt.countTokens(); + int ito = 0; + if ( fc != null ) itoco--; //user may have given IDL type + for ( ito = 0; ito < itoco; ito++ ) + vec.insertElementAt( tt.nextToken(),ito ); //insert 'to' modules + if ( fc != null ) { + String tc = tt.nextToken(); + if ( ! ct.getName().equals( tc ) ) //not the IDL type, so.. + vec.insertElementAt( tc,ito ); //insert final 'to' module + } + } + } + return ret; + } + + + /** + * Strip Java #pragma prefix and/or -pkgPrefix prefix package names from + * given IDLEntity ct. + * Strip any package prefix which may have been added by comparing with + * repository id. For example in Java package fake.omega: + * repid = IDL:phoney.pfix/omega/Juliet:1.0 gives { "omega" } + * @param ct CompoundType containing given IDLEntity. + * @param vec Returned Vector of stripped IDL module names. + */ + protected void stripJavaPackage( + CompoundType ct, + Vector vec ) { + vec.removeAllElements(); + if ( ! ct.isIDLEntity() ) return; + + String repID = ct.getRepositoryID().substring( 4 ); + StringTokenizer rept = new StringTokenizer( repID,"/" ); + if ( rept.countTokens() < 2 ) return; + + while ( rept.hasMoreTokens() ) + vec.addElement( rept.nextToken() ); + vec.removeElementAt( vec.size() - 1 ); + + String pName = ct.getPackageName(); //start from Java package names + if ( pName == null ) return; + Vector pVec = new Vector(); + StringTokenizer pt = new StringTokenizer( pName,"." ); + while ( pt.hasMoreTokens() ) pVec.addElement( pt.nextToken() ); + + int i1 = vec.size() - 1; + int i2 = pVec.size() - 1; + while ( i1 >= 0 && i2 >= 0 ) { //go R->L till mismatch + String rep = (String)( vec.elementAt( i1 ) ); + String pkg = (String)( pVec.elementAt( i2 ) ); + if ( ! pkg.equals( rep ) ) break; + i1--; i2--; + } + for ( int i3 = 0; i3 <= i1; i3++ ) + vec.removeElementAt( 0 ); //strip prefix + } + + + + /** + * Write boxedRMI valuetype for a single dimension of an IDL sequence + * indicated by the given OutputType. + * The filename for the OutputType is of the form "seqn_elemName" where n + * is the dimension required. + * @param ot Given OutputType. + * @param p The output stream. + */ + protected void writeSequence( + OutputType ot, + IndentingWriter p) + throws IOException { + ArrayType at = (ArrayType)ot.getType(); + Type et = at.getElementType(); + String fName = ot.getName(); + int dim = Integer.parseInt( fName.substring( 3,fName.indexOf( "_" ) ) ); + String idlName = unEsc( et.getIDLName() ).replace( ' ','_' ); + String qIdlName = getQualifiedIDLName( et ); + String qName = et.getQualifiedName(); + + String repID = at.getRepositoryID(); + int rix1 = repID.indexOf( '[' ); //edit repository id + int rix2 = repID.lastIndexOf( '[' ) + 1; + StringBuffer rid = new StringBuffer( + repID.substring( 0,rix1 ) + + repID.substring( rix2 ) ); + for ( int i1 = 0; i1 < dim; i1++ ) rid.insert( rix1,'[' ); + + String vtName = "seq" + dim + "_" + idlName; + boolean isFromIDL = false; + if ( et.isCompound() ) { + CompoundType ct = (CompoundType)et; + isFromIDL = ct.isIDLEntity() || ct.isCORBAObject(); + } + boolean isForwardInclude = + et.isCompound() && + !isSpecialReference( et ) && + dim == 1 && + !isFromIDL && + !"org.omg.CORBA.Object".equals(qName) && + !"java.lang.String".equals(qName); + + writeBanner( at,dim,!isException,p ); + if ( dim == 1 && "java.lang.String".equals(qName) ) //special case + writeIncOrb( p ); + if ( dim == 1 && "org.omg.CORBA.Object".equals(qName) ) ; + else if ( isSpecialReference( et ) || dim > 1 || isFromIDL ) + writeInclude( at,dim-1,!isThrown,p ); //"trivial" include + writeIfndef( at,dim,!isException,!isForward,p ); + if ( isForwardInclude ) + writeForwardReference( at,dim-1,p ); //forward declare + writeModule1( at,p ); + p.pln();p.pI(); + p.p( "valuetype " + vtName ); + p.p( " sequence<" ); + if ( dim == 1 ) p.p( qIdlName ); + else { + p.p( "seq" + ( dim - 1 ) + "_" ); + p.p( idlName ); + } + p.pln( ">;" ); + p.pO();p.pln(); + p.pln( "#pragma ID " + vtName + " \"" + rid + "\"" ); + p.pln(); + writeModule2( at,p ); + if ( isForwardInclude ) + writeInclude( at,dim-1,!isThrown,p ); //#include for forward declare + writeEndif( p ); + } + + + /** + * Write valuetype for a boxed IDLEntity. + * @param t Given CompoundType representing the IDLEntity. + * @param p The output stream. + */ + protected void writeBoxedIDL( + CompoundType t, + IndentingWriter p) + throws IOException { + String[] boxNames = getIDLModuleNames( t ); + int len = boxNames.length; + String[] modNames = new String[len - 3]; //remove box modules + for ( int i1 = 0; i1 < len - 3; i1++ ) modNames[i1] = boxNames[i1 + 3]; + String tName = unEsc( t.getIDLName() ); + + writeBanner( t,0,!isException,p ); + writeInclude( t,modNames,tName,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + + p.p( "valuetype " + tName + " " ); + for ( int i1 = 0; i1 < modNames.length; i1++ ) + p.p( IDL_NAME_SEPARATOR + modNames[i1] ); + p.pln( IDL_NAME_SEPARATOR + tName + ";" ); + + p.pO();p.pln(); + writeRepositoryID( t,p ); + p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write an exception. + * @param t Given ClassType representing the exception. + * @param p The output stream. + */ + protected void writeException( + ClassType t, + IndentingWriter p) + throws IOException { + writeBanner( t,0,isException,p ); + writeIfndef( t,0,isException,!isForward,p ); + writeForwardReference( t,p ); + writeModule1( t,p ); + p.pln();p.pI(); + + p.pln( "exception " + t.getIDLExceptionName() + " {" ); + p.pln();p.pI(); + p.pln( t.getIDLName() + " value;" ); + p.pO();p.pln(); + p.pln( "};" ); + + p.pO();p.pln(); + writeModule2( t,p ); + writeInclude( t,0,!isThrown,p ); //include valuetype idl file + writeEndif( p ); + } + + + /** + * Write #pragma to identify the repository ID of the given type + * @param t The given Type. + * @param p The output stream. + */ + protected void writeRepositoryID( + Type t, + IndentingWriter p ) + throws IOException { + String repid = t.getRepositoryID(); + if ( t.isCompound() ) { + CompoundType ct = (CompoundType)t; + if ( ct.isBoxed() ) + repid = ct.getBoxedRepositoryID(); + } + + p.pln( "#pragma ID " + t.getIDLName() + " \"" + + repid + "\"" ); + } + + /** + * Write inheritance for an IDL interface or valuetype. Any class + * inheritance precedes any interface inheritance. + * For a valutype any inheritance from abstract interfaces then + * follows the "supports" keyword. + * @param inhHash Hashtable loaded with inherited Types + * @param forValuetype true if writing inheritance for a valuetype + * @param p The output stream. + */ + protected void writeInherits( + Hashtable inhHash, + boolean forValuetype, + IndentingWriter p ) + throws IOException { + int itot = inhHash.size(); + int iinh = 0; + int isup = 0; + if ( itot < 1 ) return; //any inheritance to write? + Enumeration inhEnum = inhHash.elements(); + CompoundType ct; + if ( forValuetype ) + while ( inhEnum.hasMoreElements() ) { + ct = (CompoundType)inhEnum.nextElement(); + if ( ct.getTypeCode() == TYPE_ABSTRACT ) isup++; + } + iinh = itot - isup; + + if ( iinh > 0 ) { + p.p( ": " ); + inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { //write any class inheritance + ct = (CompoundType)inhEnum.nextElement(); + if ( ct.isClass() ) { + p.p( getQualifiedIDLName( ct ) ); + if ( iinh > 1 ) p.p( ", " ); //delimit them with commas + else if ( itot > 1 ) p.p( " " ); + break; //only one parent + } + } + int i = 0; + inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { //write any interface inheritance + ct = (CompoundType)inhEnum.nextElement(); + if ( !ct.isClass() && + !( ct.getTypeCode() == TYPE_ABSTRACT ) ) { + if ( i++ > 0 ) p.p( ", " ); //delimit with commas + p.p( getQualifiedIDLName( ct ) ); + } + } + } + if ( isup > 0 ) { //write abstract interface inheritance + p.p( " supports " ); + int i = 0; + inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { + ct = (CompoundType)inhEnum.nextElement(); + if ( ct.getTypeCode() == TYPE_ABSTRACT ) { + if ( i++ > 0 ) p.p( ", " ); //delimit with commas + p.p( getQualifiedIDLName( ct ) ); + } + } + } + } + + + /** + * Write an IDL constant + * @param constant The current CompoundType.Member constant + * @param p The output stream. + */ + protected void writeConstant( + CompoundType.Member constant, + IndentingWriter p ) + throws IOException { + Type t = constant.getType(); + p.p( "const " ); + p.p( getQualifiedIDLName( t ) ); + p.p( " " + constant.getIDLName() + " = " + constant.getValue() ); + p.pln( ";" ); + } + + + + /** + * Write an IDL data member + * @param data The current CompoundType.Member data member + * @param p The output stream. + */ + protected void writeData( + CompoundType.Member data, + IndentingWriter p ) + throws IOException { + if ( data.isInnerClassDeclaration() ) return; //ignore + Type t = data.getType(); + if ( data.isPublic() ) + p.p( "public " ); + else p.p( "private " ); + p.pln( getQualifiedIDLName( t ) + " " + + data.getIDLName() + ";" ); + } + + + + /** + * Write an IDL Attribute + * @param attr The current CompoundType.Method attribute + * @param p The output stream. + */ + protected void writeAttribute( + CompoundType.Method attr, + IndentingWriter p ) + throws IOException { + if ( attr.getAttributeKind() == ATTRIBUTE_SET ) return; //use getters only + Type t = attr.getReturnType(); + if ( !attr.isReadWriteAttribute() ) p.p( "readonly " ); + p.p( "attribute " + getQualifiedIDLName( t ) + " " ); + p.pln( attr.getAttributeName() + ";" ); + } + + + + /** + * Write an IDL method + * @param method The current CompoundType.Method + * @param p The output stream. + */ + protected void writeMethod( + CompoundType.Method method, + IndentingWriter p ) + throws IOException { + if ( method.isAttribute() ) { + writeAttribute( method,p ); + return; + } + Type[] pts = method.getArguments(); + String[] paramNames = method.getArgumentNames(); + Type rt = method.getReturnType(); + Hashtable excHash = new Hashtable(); + getExceptions( method,excHash ); + + if ( method.isConstructor() ) + if ( factory ) p.p( "factory " + method.getIDLName() + "(" ); + else p.p( "init(" ); //IDL initializer + else { + p.p( getQualifiedIDLName( rt ) ); + p.p( " " + method.getIDLName() + "(" ); + } + p.pI(); + + for ( int i=0; i < pts.length; i++ ) { + if ( i > 0 ) p.pln( "," ); //delimit with comma and newline + else p.pln(); + p.p( "in " ); + p.p( getQualifiedIDLName( pts[i] ) ); + p.p( " " + paramNames[i] ); + } + p.pO(); + p.p( " )" ); + + if ( excHash.size() > 0 ) { //any exceptions to write? + p.pln( " raises (" ); + p.pI(); + int i = 0; + Enumeration excEnum = excHash.elements(); + while ( excEnum.hasMoreElements() ) { + ValueType exc = (ValueType)excEnum.nextElement(); + if ( i > 0 ) p.pln( "," ); //delimit them with commas + if ( exc.isIDLEntityException() ) + if ( exc.isCORBAUserException() ) + p.p( "::org::omg::CORBA::UserEx" ); + else { + String[] modNames = getIDLModuleNames( exc ); + for ( int i2 = 0; i2 < modNames.length; i2++ ) + p.p( IDL_NAME_SEPARATOR + modNames[i2] ); + p.p( IDL_NAME_SEPARATOR + exc.getName() ); + } + else p.p( exc.getQualifiedIDLExceptionName( true ) ); + i++; + } + p.pO(); + p.p( " )" ); + } + + p.pln( ";" ); + } + + + /** + * Remove escape character ("_"), if any, from given String + * @param name Given String + * @return String with any escape character removed + */ + protected String unEsc( + String name ) { + if ( name.startsWith( "_" ) ) return name.substring( 1 ); + else return name; + } + + + /** + * Write IDL banner into the output stream for a given Type + * @param t The given Type. + * @param dim The dimension required if t is an ArrayType. + * @param isException true if writing an exception. + * @param p The output stream. + */ + protected void writeBanner( + Type t, + int dim, + boolean isException, + IndentingWriter p ) + throws IOException { + String[] modNames = getIDLModuleNames( t ); //module name array + String fName = unEsc( t.getIDLName() ); //file name default + if ( isException && t.isClass() ) { + ClassType ct = (ClassType)t; //file name for Exception + fName = unEsc( ct.getIDLExceptionName() ); + } + if ( dim > 0 && t.isArray() ) { + Type et = t.getElementType(); //file name for sequence + fName = "seq" + dim + "_" + unEsc( et.getIDLName().replace( ' ','_' ) ); + } + + p.pln( "/**" ); + p.p( " * " ); + for ( int i1 = 0; i1 < modNames.length; i1++ ) + p.p( modNames[i1] + "/" ); + p.pln( fName + ".idl" ); + p.pln( " * Generated by rmic -idl. Do not edit" ); + String d = DateFormat.getDateTimeInstance( + DateFormat.FULL,DateFormat.FULL,Locale.getDefault() ) + .format( new Date() ); + String ocStr = "o'clock"; + int ocx = d.indexOf( ocStr ); //remove unwanted o'clock, if any + p.p ( " * " ); + if ( ocx > -1 ) + p.pln( d.substring( 0,ocx ) + d.substring( ocx + ocStr.length() ) ); + else p.pln( d ); + p.pln( " */" ); + p.pln(); + } + + + /** + * Write #include for orb.idl + * @param p The output stream. + */ + protected void writeIncOrb( + IndentingWriter p ) + throws IOException { + p.pln( "#include \"orb.idl\"" ); + } + + + /** + * Write #ifndef guard into the output stream for a given Type + * @param t The given Type. + * @param dim The dimension required if t is an ArrayType. + * @param isException true if writing an exception. + * @param isForward No #define needed if it's a forward declare + * @param p The output stream. + */ + protected void writeIfndef( + Type t, + int dim, + boolean isException, + boolean isForward, + IndentingWriter p ) + throws IOException { + String[] modNames = getIDLModuleNames( t ); //module name array + String fName = unEsc( t.getIDLName() ); //file name default + if ( isException && t.isClass() ) { + ClassType ct = (ClassType)t; //file name for Exception + fName = unEsc( ct.getIDLExceptionName() ); + } + if ( dim > 0 && t.isArray() ) { + Type et = t.getElementType(); //file name for sequence + fName = "seq" + dim + "_" + unEsc( et.getIDLName().replace( ' ','_' ) ); + } + p.pln(); + p.p( "#ifndef __" ); + for ( int i = 0; i < modNames.length; i++ ) p.p( modNames[i] + "_" ); + p.pln( fName + "__" ); + if ( !isForward ) { + p.p( "#define __" ); + for ( int i = 0; i < modNames.length; i++ ) p.p( modNames[i] + "_" ); + p.pln( fName + "__" ); + p.pln(); + } + } + + + /** + * Write #endif bracket into the output stream + * @param p The output stream. + */ + protected void writeEndif( + IndentingWriter p ) + throws IOException { + p.pln("#endif"); + p.pln(); + } + + /** + * Write Module start bracketing for the given type into the output stream + * @param t The given Type + * @param p The output stream. + */ + protected void writeModule1( + Type t, + IndentingWriter p ) + throws IOException { + + String[] modNames = getIDLModuleNames( t ); + p.pln(); + for ( int i = 0; i < modNames.length; i++ ) + p.pln( "module " + modNames[i] + " {" ); + } + + /** + * Write Module end bracketing for the given type into the output stream + * @param t The given Type + * @param p The output stream. + */ + protected void writeModule2( + Type t, + IndentingWriter p ) + throws IOException { + String[] modNames = getIDLModuleNames( t ); + for ( int i=0; i < modNames.length; i++ ) p.pln( "};" ); + p.pln(); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/IDLNames.java b/rmic/src/main/java/org/glassfish/rmic/iiop/IDLNames.java new file mode 100644 index 000000000..8c0b8a87f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/IDLNames.java @@ -0,0 +1,1208 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.Identifier; + +/** + * IDLNames provides static utility methods to perform the IDL + * name mappings specified in Chapter 5 of the Java Language + * to IDL specification. + * + * @author Bryan Atsatt + */ +public class IDLNames implements org.glassfish.rmic.iiop.Constants { + + /** + * Used to convert ascii to hex. + */ + public static final byte ASCII_HEX[] = { + (byte)'0', + (byte)'1', + (byte)'2', + (byte)'3', + (byte)'4', + (byte)'5', + (byte)'6', + (byte)'7', + (byte)'8', + (byte)'9', + (byte)'A', + (byte)'B', + (byte)'C', + (byte)'D', + (byte)'E', + (byte)'F', + }; + + // Legal IDL Identifier characters (1 = legal). Note + // that '.' (2E) is marked as legal even though it is + // not legal in IDL. This allows us to treat a fully + // qualified Java name with '.' package separators + // uniformly, and is safe because that is the only + // legal use of '.' in a Java name. + + private static final byte[] IDL_IDENTIFIER_CHARS = { + + // 0 1 2 3 4 5 6 7 8 9 a b c d e f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 00-0f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 10-1f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,1,0, // 20-2f + 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0, // 30-3f + 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 40-4f + 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,1, // 50-5f + 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // 60-6f + 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0, // 70-7f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 80-8f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // 90-9f + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // a0-af + 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // b0-bf + 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // c0-cf + 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // d0-df + 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, // e0-ef + 0,1,1,1, 1,1,1,0, 1,1,1,1, 1,0,0,1, // f0-ff + }; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Convert a name. The nameContext argument MUST be pre-filled with + * all names from the appropriate context (e.g. all the method names + * in a given class). The names must not have had any IDL conversions + * applied. + *

                + * Section 28.3.2.2 + * Section 28.3.2.3 + * Section 28.3.2.4 + * Section 28.3.2.7 (member and method names only) + */ + public static String getMemberOrMethodName (NameContext nameContext, + String name, + BatchEnvironment env) { + + // Check namesCache... + + String result = (String) env.namesCache.get(name); + + if (result == null) { + + // 28.3.2.7 Case sensitive member names. + + // Note: This must be done before any of + // the other conversions! + + result = nameContext.get(name); + + // 28.3.2.3 Leading underscores... + + result = convertLeadingUnderscores(result); + + // 28.3.2.2 IDL keywords (NOTE: must be done + // after leading underscore conversion because + // the mangling for IDL keywords creates a + // leading underscore!)... + + result = convertIDLKeywords(result); + + // 28.3.2.4 Illegal IDL identifier characters... + + result = convertToISOLatin1(result); + + // Add to namesCache... + + env.namesCache.put(name,result); + } + + return result; + } + + /** + * Convert names with illegal IDL identifier characters. + *

                + * Section 28.3.2.4 + */ + public static String convertToISOLatin1 (String name) { + + // First, replace any escape sequences... + + String result = replace(name,"x\\u","U"); + result = replace(result,"x\\U","U"); + + // Now see if we have any remaining illegal characters (see + // IDL_IDENTIFIER_CHARS array)... + + int length = result.length(); + StringBuffer buffer = null; + + for (int i = 0; i < length; i++) { + + char c = result.charAt(i); + + if (c > 255 || IDL_IDENTIFIER_CHARS[c] == 0) { + + // We gotta convert. Have we already started? + + if (buffer == null) { + + // No, so get set up... + + buffer = new StringBuffer(result.substring(0,i)); + } + + // Convert the character into the IDL escape syntax... + + buffer.append("U"); + buffer.append((char)ASCII_HEX[(c & 0xF000) >>> 12]); + buffer.append((char)ASCII_HEX[(c & 0x0F00) >>> 8]); + buffer.append((char)ASCII_HEX[(c & 0x00F0) >>> 4]); + buffer.append((char)ASCII_HEX[(c & 0x000F)]); + + } else { + if (buffer != null) { + buffer.append(c); + } + } + } + + if (buffer != null) { + result = buffer.toString(); + } + + return result; + } + + /** + * Convert names which collide with IDL keywords. + *

                + * Section 28.3.2.5 + */ + public static String convertIDLKeywords (String name) { + + for (int i = 0; i < IDL_KEYWORDS.length; i++) { + if (name.equalsIgnoreCase(IDL_KEYWORDS[i])) { + return "_" + name; + } + } + + return name; + } + + /** + * Convert names which have leading underscores + *

                + * Section 28.3.2.3 + */ + public static String convertLeadingUnderscores (String name) { + + if (name.startsWith("_")) { + return "J" + name; + } + + return name; + } + + /** + * Convert a type name. + *

                + * Section 28.3.2.5 + * Section 28.3.2.7 (class or interface names only) + * Throws exception if fails 28.3.2.7. + */ + public static String getClassOrInterfaceName (Identifier id, + BatchEnvironment env) throws Exception { + + // Get the type and package name... + + String typeName = id.getName().toString(); + String packageName = null; + + if (id.isQualified()) { + packageName = id.getQualifier().toString(); + } + + // Check namesCache... + + String result = (String) env.namesCache.get(typeName); + + if (result == null) { + + // 28.3.2.5 Inner classes... + + result = toInnerClassName(typeName); + + // 28.3.2.4 Illegal identifier characters... + + result = convertToISOLatin1(result); + + // 28.3.2.7 Case sensitive class or interface names... + + NameContext context = NameContext.forName(packageName,false,env); + context.assertPut(result); + + // Run it through the name checks... + + result = getTypeOrModuleName(result); + + // Add it to the namesCache... + + env.namesCache.put(typeName,result); + } + + return result; + } + + private static String toInnerClassName(String typeName) { + if (typeName.contains(". ")) + return replace(typeName,". ","__"); + else + return replace(typeName,"$","__"); + } + + /** + * Convert an Exception name. + *

                + * Section 28.3.7.2 (see ValueType) + */ + public static String getExceptionName (String idlName) { + + String result = idlName; +// d.11315 Incorrectly mangled exception names + if (idlName.endsWith(EXCEPTION_SUFFIX)) { + + // Remove "Exception" and append "Ex". Strip leading underscore + // in case the idlName is exactly "_Exception"... + + result = stripLeadingUnderscore(idlName.substring(0,idlName.lastIndexOf(EXCEPTION_SUFFIX)) + EX_SUFFIX); + } else { + result = idlName + EX_SUFFIX; + } + + return result; + } + + /** + * Convert a qualified Identifier into an array of IDL names. + *

                + * Section 28.3.2.1 (see CompoundType) + * Throws exception if fails 28.3.2.7. + */ + public static String[] getModuleNames (Identifier theID, + boolean boxIt, + BatchEnvironment env) throws Exception { + + String[] result = null; + + if (theID.isQualified()) { + + // Extract the qualifier... + + Identifier id = theID.getQualifier(); + + // 28.3.2.7 Case sensitive module names. + + env.modulesContext.assertPut(id.toString()); + + // Count them... + + int count = 1; + Identifier current = id; + while (current.isQualified()) { + current = current.getQualifier(); + count++; + } + + result = new String[count]; + int index = count-1; + current = id; + + // Now walk them and fill our array (backwards)... + + for (int i = 0; i < count; i++) { + + String item = current.getName().toString(); + + // Check namesCache... + + String cachedItem = (String) env.namesCache.get(item); + + if (cachedItem == null) { + + // 28.3.2.4 Illegal identifier characters... + + cachedItem = convertToISOLatin1(item); + + // Run it through the name checks... + + cachedItem = getTypeOrModuleName(cachedItem); + + // Add it to the namesCache... + + env.namesCache.put(item,cachedItem); + } + + result[index--] = cachedItem; + current = current.getQualifier(); + } + } + + + // If it is supposed to be "boxed", prepend + // IDL_BOXEDIDL_MODULE... + + if (boxIt) { + if (result == null) { + result = IDL_BOXEDIDL_MODULE; + } else { + String[] boxed = new String[result.length+IDL_BOXEDIDL_MODULE.length]; + System.arraycopy(IDL_BOXEDIDL_MODULE,0,boxed,0,IDL_BOXEDIDL_MODULE.length); + System.arraycopy(result,0,boxed,IDL_BOXEDIDL_MODULE.length,result.length); + result = boxed; + } + } + + return result; + } + + /** + * Get an array name with the specified dimensions. + *

                + * Section 28.3.6 (see ArrayType) + */ + public static String getArrayName (Type theType, int arrayDimension) { + + StringBuffer idlName = new StringBuffer(64); + + // Prefix with seq_... + + idlName.append(IDL_SEQUENCE); + idlName.append(Integer.toString(arrayDimension)); + idlName.append("_"); + + // Add the type name. We need to map any spaces in the + // name to "_"... + + idlName.append(replace(stripLeadingUnderscore(theType.getIDLName())," ","_")); + + // And we're done... + + return idlName.toString(); + } + + /** + * Get an array module names. + */ + public static String[] getArrayModuleNames (Type theType) { + + String[] moduleName; + String[] typeModule = theType.getIDLModuleNames(); + int typeModuleLength = typeModule.length; + + // Does the type have a module? + + if (typeModuleLength == 0) { + + // Nope, so just use the sequence module... + + moduleName = IDL_SEQUENCE_MODULE; + } else { + + // Yes, so gotta concatenate... + + moduleName = new String[typeModuleLength + IDL_SEQUENCE_MODULE.length]; + System.arraycopy(IDL_SEQUENCE_MODULE,0,moduleName,0,IDL_SEQUENCE_MODULE.length); + System.arraycopy(typeModule,0,moduleName,IDL_SEQUENCE_MODULE.length,typeModuleLength); + } + + return moduleName; + } + + private static int getInitialAttributeKind (CompoundType.Method method, + BatchEnvironment env) throws ClassNotFound { + + int result = ATTRIBUTE_NONE; + + // First make sure it is not a constructor... + + if (!method.isConstructor()) { + + // Now check exceptions. It may not throw any checked + // exception other than RemoteException or one of its + // subclasses... + + boolean validExceptions = true; + ClassType[] exceptions = method.getExceptions(); + + if (exceptions.length > 0) { + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i].isCheckedException() && + !exceptions[i].isRemoteExceptionOrSubclass()) { + validExceptions = false; + break; + } + } + } else { + + // If this is a ValueType, it is ok to not have any exceptions, + // otherwise this method does not qualify... + + validExceptions = method.getEnclosing().isType(TYPE_VALUE); + } + + if (validExceptions) { + String name = method.getName(); + int nameLength = name.length(); + int argCount = method.getArguments().length; + Type returnType = method.getReturnType(); + boolean voidReturn = returnType.isType(TYPE_VOID); + boolean booleanReturn = returnType.isType(TYPE_BOOLEAN); + + // It's a getter if name starts with "get" and it has no arguments + // and a return type that is not void... + + if (name.startsWith("get") && nameLength > 3 && argCount == 0 && !voidReturn) { + result = ATTRIBUTE_GET; + } else { + + // It's a getter if name starts with "is" and it has no arguments + // and a boolean return type... + + if (name.startsWith("is") && nameLength > 2 && argCount == 0 && booleanReturn) { + result = ATTRIBUTE_IS; + } else { + + // It's a setter if name starts with "set" and it has 1 argument + // and a void return type... + + if (name.startsWith("set") && nameLength > 3 && argCount == 1 && voidReturn) { + result = ATTRIBUTE_SET; + } + } + } + } + } + + return result; + } + + private static void setAttributeKinds (CompoundType.Method[] methods, + int[] kinds, + String[] names) { + + int count = methods.length; + + // Strip the prefixes off of the attribute names... + + for (int i = 0; i < count; i++) { + switch (kinds[i]) { + case ATTRIBUTE_GET: names[i] = names[i].substring(3); break; + case ATTRIBUTE_IS: names[i] = names[i].substring(2); break; + case ATTRIBUTE_SET: names[i] = names[i].substring(3); break; + } + } + + // Now, we need to look at all the IS attributes to see + // if there is a corresponding getter or setter which has + // a different return type. If so, mark it as not an + // attribute. Do this before checking for invalid setters... + + for (int i = 0; i < count; i++) { + if (kinds[i] == ATTRIBUTE_IS) { + for (int j = 0; j < count; j++) { + if (j != i && + (kinds[j] == ATTRIBUTE_GET || kinds[j] == ATTRIBUTE_SET) && + names[i].equals(names[j])) { + + // We have matching getter or setter. Do the types match? + + Type isType = methods[i].getReturnType(); + Type targetType; + + if (kinds[j] == ATTRIBUTE_GET) { + targetType = methods[j].getReturnType(); + } else { + targetType = methods[j].getArguments()[0]; + } + + if (!isType.equals(targetType)) { + + // No, so forget this guy as an attribute... + + kinds[i] = ATTRIBUTE_NONE; + names[i] = methods[i].getName(); + break; + } + } + } + } + } + + // Now, we need to look at all the setters to see if there + // is a corresponding getter. If not, it is not a setter. + // If there is, change the getter type to _RW and set the + // pair index... + + for (int i = 0; i < count; i++) { + if (kinds[i] == ATTRIBUTE_SET) { + int getterIndex = -1; + int isGetterIndex = -1; + // First look for is-getters, then for getters. + // This is preferred for boolean attributes. + for (int j = 0; j < count; j++) { + if (j != i && names[i].equals(names[j])) { + // Yep, is the return type of the getter the same + // as the argument type of the setter? + + Type getterReturn = methods[j].getReturnType(); + Type setterArg = methods[i].getArguments()[0]; + + if (getterReturn.equals(setterArg)) { + if (kinds[j] == ATTRIBUTE_IS) { + isGetterIndex = j; + // continue looking for another getter + } else if (kinds[j] == ATTRIBUTE_GET) { + getterIndex = j; + // continue looking for an is-getter + } + } + } + } + + if (getterIndex > -1) { + if (isGetterIndex > -1) { + // We have both, a boolean is-getter and a boolean getter. + // Use the is-getter and drop the getter. + + // We have a matching getter. Change it to a read-write type... + kinds[isGetterIndex] = ATTRIBUTE_IS_RW; + + // Now set the pair index for both the getter and the setter... + methods[isGetterIndex].setAttributePairIndex(i); + methods[i].setAttributePairIndex(isGetterIndex); + + // We found a better matching is-getter. + // Forget this other getter as an attribute. + kinds[getterIndex] = ATTRIBUTE_NONE; + names[getterIndex] = methods[getterIndex].getName(); + } else { + // We only have one getter. + + // We have a matching getter. Change it to a read-write type... + kinds[getterIndex] = ATTRIBUTE_GET_RW; + + // Now set the pair index for both the getter and the setter... + methods[getterIndex].setAttributePairIndex(i); + methods[i].setAttributePairIndex(getterIndex); + } + } else { + if (isGetterIndex > -1) { + // We only have one is-getter. + + // We have a matching getter. Change it to a read-write type... + kinds[isGetterIndex] = ATTRIBUTE_IS_RW; + + // Now set the pair index for both the getter and the setter... + methods[isGetterIndex].setAttributePairIndex(i); + methods[i].setAttributePairIndex(isGetterIndex); + } else { + // We did not find a matching getter. + // Forget this setter as an attribute. + kinds[i] = ATTRIBUTE_NONE; + names[i] = methods[i].getName(); + } + } + } + } + + // Finally, do the case conversion and set the + // attribute kinds for each method... + + for (int i = 0; i < count; i++) { + + if (kinds[i] != ATTRIBUTE_NONE) { + + String name = names[i]; + + // Is the first character upper case? + + if (Character.isUpperCase(name.charAt(0))) { + + // Yes, is the second? + + if (name.length() == 1 || Character.isLowerCase(name.charAt(1))) { + + // No, so convert the first character to lower case... + + StringBuffer buffer = new StringBuffer(name); + buffer.setCharAt(0,Character.toLowerCase(name.charAt(0))); + names[i] = buffer.toString(); + } + } + } + + methods[i].setAttributeKind(kinds[i]); + } + } + + /** + * Set all the method names in a given class. + *

                + * Section 28.3.2.7 (see CompoundType) + * Section 28.3.2.7 + * Section 28.3.4.3 (RemoteType/AbstractType only). + */ + public static void setMethodNames (CompoundType container, + CompoundType.Method[] allMethods, + BatchEnvironment env) + throws Exception { + + // This method implements the following name mangling sequence: + // + // 1. If methods belong to a Remote interface, identify + // those which qualify as an attribute under 28.3.4.3. + // Those that do are referred to as 'attributes' below; + // those that do not are referred to as 'methods'. + // + // 2. Apply the 28.3.4.3 manglings, except "__", to all + // attribute names. + // + // 3. Apply all 28.3 manglings, except 28.3.2.7, to all names. + // + // 4. Apply 28.3.2.7 manglings to all method names. + // + // 5. Compare each attribute name to each method name. For + // any which compare equal, append "__" to the attribute + // name. + // + // 6. Compare each name (attribute and method) to all others. + // If any compare equal, throw an Exception with the + // conflicting name as the message. + + int count = allMethods.length; + + if (count == 0) return; + + // Make an array of all the method names... + + String[] names = new String[count]; + for (int i = 0; i < count; i++) { + names[i] = allMethods[i].getName(); + } + + // Are we dealing with a RemoteType, AbstractType, or ValueType? + + CompoundType enclosing = allMethods[0].getEnclosing(); + if (enclosing.isType(TYPE_REMOTE) || + enclosing.isType(TYPE_ABSTRACT) || + enclosing.isType(TYPE_VALUE)) { + + // Yes, so we must do the 28.3.4.3 attribute mapping. First, get + // the initial attribute kind of each method... + + int[] kinds = new int[count]; + + for (int i = 0; i < count; i++) { + kinds[i] = getInitialAttributeKind(allMethods[i],env); + } + + // Now set the attribute kind for each method and do the + // 28.3.4.3 name mangling... + + setAttributeKinds(allMethods,kinds,names); + } + + // Make and populate a new context from our names array... + + NameContext context = new NameContext(true); + + for (int i = 0; i < count; i++) { + context.put(names[i]); + } + + // Apply the appropriate 28.3 manglings to all the names... + + boolean haveConstructor = false; + for (int i = 0; i < count; i++) { + if (!allMethods[i].isConstructor()) { + names[i] = getMemberOrMethodName(context,names[i],env); + } else { + names[i] = IDL_CONSTRUCTOR; + haveConstructor = true; + } + } + + // Now do the 28.3.2.7 mangling for method name collisions... + // Do this in two passes so that we don't change one during + // the detection of collisions and then miss a real one... + + boolean overloaded[] = new boolean[count]; + for (int i = 0; i < count; i++) { + overloaded[i] = (!allMethods[i].isAttribute() && + !allMethods[i].isConstructor() && + doesMethodCollide(names[i],allMethods[i],allMethods,names,true)); + } + convertOverloadedMethods(allMethods,names,overloaded); + + // Now do the same mangling for constructor name collisions... + + for (int i = 0; i < count; i++) { + overloaded[i] = (!allMethods[i].isAttribute() && + allMethods[i].isConstructor() && + doesConstructorCollide(names[i],allMethods[i],allMethods,names,true)); + } + convertOverloadedMethods(allMethods,names,overloaded); + + // Now do the 28.3.4.3 mangling for attribute name collisions... + + for (int i = 0; i < count; i++) { + + CompoundType.Method method = allMethods[i]; + + // If this is an attribute name, does it collide with a method? + + if (method.isAttribute() && + doesMethodCollide(names[i],method,allMethods,names,true)) { + + // Yes, so add double underscore... + + names[i] += "__"; + } + } + + // Do the same mangling for any constructors which collide with + // methods... + + if (haveConstructor) { + for (int i = 0; i < count; i++) { + CompoundType.Method method = allMethods[i]; + + // Is this a constructor which collides with a method? + + if (method.isConstructor() && + doesConstructorCollide(names[i],method,allMethods,names,false)) { + + // Yes, so add double underscore... + + names[i] += "__"; + } + } + } + + // Now see if we have a collision with the container name (28.3.2.9). + + String containerName = container.getIDLName(); + for (int i = 0; i < count; i++) { + if (names[i].equalsIgnoreCase(containerName)) { + // Do not add underscore to attributes. + // Otherwise getFoo will turn into _get_foo_. + if (! allMethods[i].isAttribute()) { + names[i] += "_"; + } + } + } + + // Now see if we have any collisions (28.3.2.9). If we do, + // it's an error. Note: a get/set pair does not collide. + + for (int i = 0; i < count; i++) { + + // Does it collide with any other name? + + if (doesMethodCollide(names[i],allMethods[i],allMethods,names,false)) { + + // Yes, so bail... + + throw new Exception(allMethods[i].toString()); + } + } + + // Ok. We have unique names. Create the appropriate 'wire' name + // for each and set as the 'idl' name. If it is an attribute, also + // set the attribute name... + + for (int i = 0; i < count; i++) { + + CompoundType.Method method = allMethods[i]; + String wireName = names[i]; + + if (method.isAttribute()) { + wireName = ATTRIBUTE_WIRE_PREFIX[method.getAttributeKind()] + + stripLeadingUnderscore(wireName); + String attributeName = names[i]; + method.setAttributeName(attributeName); + } + method.setIDLName(wireName); + } + } + + private static String stripLeadingUnderscore (String name) { + if (name != null && name.length() > 1 + && name.charAt(0) == '_') + { + return name.substring(1); + } + return name; + } + + + private static String stripTrailingUnderscore (String name) { + if (name != null && name.length() > 1 && + name.charAt(name.length() - 1) == '_') + { + return name.substring(0, name.length() - 1); + } + return name; + } + + + private static void convertOverloadedMethods(CompoundType.Method[] allMethods, + String[] names, + boolean[] overloaded) { + + for (int i = 0; i < names.length; i++) { + + // Do we need to mangle it? + + if (overloaded[i]) { + + // Yes, so add arguments... + + CompoundType.Method method = allMethods[i]; + Type[] args = method.getArguments(); + + for (int k = 0; k < args.length; k++) { + + // Add the separator... + + names[i] += "__"; + + // Get the fully qualified IDL name, without the "::" + // prefix... + + String argIDLName = args[k].getQualifiedIDLName(false); + + // Replace any occurances of "::_" with "_" to + // undo any IDL keyword mangling and do next step + // at the same time... + + argIDLName = replace(argIDLName,"::_","_"); + + // Replace any occurances of "::" with "_"... + + argIDLName = replace(argIDLName,"::","_"); + + // Replace any occurances of " " with "_"... + + argIDLName = replace(argIDLName," ","_"); + + // Add the argument type name... + + names[i] += argIDLName; + } + + if (args.length == 0) { + names[i] += "__"; + } + + // Remove any IDL keyword mangling... + + names[i] = stripLeadingUnderscore(names[i]); + } + } + } + + private static boolean doesMethodCollide (String name, + CompoundType.Method method, + CompoundType.Method[] allMethods, + String[] allNames, + boolean ignoreAttributes) { + + // Scan all methods looking for a match... + + for (int i = 0; i < allMethods.length; i++) { + + CompoundType.Method target = allMethods[i]; + + if (method != target && // Not same instance + !target.isConstructor() && // Not a constructor + (!ignoreAttributes || !target.isAttribute()) && // Correct kind + name.equals(allNames[i])) { // Same names + + // Are we looking at a get/set pair? + + int kind1 = method.getAttributeKind(); + int kind2 = target.getAttributeKind(); + + if ((kind1 != ATTRIBUTE_NONE && kind2 != ATTRIBUTE_NONE) && + ((kind1 == ATTRIBUTE_SET && kind2 != ATTRIBUTE_SET) || + (kind1 != ATTRIBUTE_SET && kind2 == ATTRIBUTE_SET) || + // one is a is-getter/setter pair and the other is just a getter + (kind1 == ATTRIBUTE_IS_RW && kind2 == ATTRIBUTE_GET) || + (kind1 == ATTRIBUTE_GET && kind2 == ATTRIBUTE_IS_RW))) { + + // Yes, so ignore it... + + } else { + + // No, so we have a collision... + + return true; + } + } + } + + return false; + } + + private static boolean doesConstructorCollide (String name, + CompoundType.Method method, + CompoundType.Method[] allMethods, + String[] allNames, + boolean compareConstructors) { + + // Scan all methods looking for a match... + + for (int i = 0; i < allMethods.length; i++) { + + CompoundType.Method target = allMethods[i]; + + if (method != target && // Not same instance + (target.isConstructor() == compareConstructors) && // Correct kind + name.equals(allNames[i])) { // Same names + + // We have a collision... + + return true; + } + } + + return false; + } + + + /** + * Set all the member names in a given class. + *

                + * Section 28.3.2.7 (see CompoundType) + * Section 28.3.2.7 + */ + public static void setMemberNames (CompoundType container, + CompoundType.Member[] allMembers, + CompoundType.Method[] allMethods, + BatchEnvironment env) + throws Exception { + + // Make and populate a new context... + + NameContext context = new NameContext(true); + + for (int i = 0; i < allMembers.length; i++) { + context.put(allMembers[i].getName()); + } + + // Now set all the idl names... + + for (int i = 0; i < allMembers.length; i++) { + + CompoundType.Member member = allMembers[i]; + String idlName = getMemberOrMethodName(context,member.getName(),env); + member.setIDLName(idlName); + } + + // First see if we have a collision with the container name (28.3.2.9). + + String containerName = container.getIDLName(); + for (int i = 0; i < allMembers.length; i++) { + String name = allMembers[i].getIDLName(); + if (name.equalsIgnoreCase(containerName)) { + // REVISIT - How is this different than line 788 + allMembers[i].setIDLName(name+"_"); + } + } + + // Check for collisions between member names... + + for (int i = 0; i < allMembers.length; i++) { + String name = allMembers[i].getIDLName(); + for (int j = 0; j < allMembers.length; j++) { + if (i != j && allMembers[j].getIDLName().equals(name)) { + + // Collision... + + throw new Exception(name); + } + } + } + + // Now check for collisions between member names and + // method names... + + boolean changed; + do { + changed = false; + for (int i = 0; i < allMembers.length; i++) { + String name = allMembers[i].getIDLName(); + for (int j = 0; j < allMethods.length; j++) { + if (allMethods[j].getIDLName().equals(name)) { + + // Collision, so append "_" to member name... + + allMembers[i].setIDLName(name+"_"); + changed = true; + break; + } + } + } + } while (changed); + } + + /** + * Get the name for the specified type code. + *

                + * Section 28.3..3 (see PrimitiveType) + * Section 28.3.5.10 (see SpecialClassType) + * Section 28.3.4.1 (see SpecialInterfaceType) + * Section 28.3.10.1 (see SpecialInterfaceType) + * Section 28.3.10.2 (see SpecialClassType) + */ + public static String getTypeName(int typeCode, boolean isConstant) { + + String idlName = null; + + switch (typeCode) { + case TYPE_VOID: idlName = IDL_VOID; break; + case TYPE_BOOLEAN: idlName = IDL_BOOLEAN; break; + case TYPE_BYTE: idlName = IDL_BYTE; break; + case TYPE_CHAR: idlName = IDL_CHAR; break; + case TYPE_SHORT: idlName = IDL_SHORT; break; + case TYPE_INT: idlName = IDL_INT; break; + case TYPE_LONG: idlName = IDL_LONG; break; + case TYPE_FLOAT: idlName = IDL_FLOAT; break; + case TYPE_DOUBLE: idlName = IDL_DOUBLE; break; + case TYPE_ANY: idlName = IDL_ANY; break; + case TYPE_CORBA_OBJECT: idlName = IDL_CORBA_OBJECT; break; + case TYPE_STRING: + { + if (isConstant) { + idlName = IDL_CONSTANT_STRING; + } else { + idlName = IDL_STRING; + } + + break; + } + } + + return idlName; + } + + /** + * Create a qualified name. + */ + public static String getQualifiedName (String[] idlModuleNames, String idlName) { + String result = null; + if (idlModuleNames != null && idlModuleNames.length > 0) { + for (int i = 0; i < idlModuleNames.length;i++) { + if (i == 0) { + result = idlModuleNames[0]; + } else { + result += IDL_NAME_SEPARATOR; + result += idlModuleNames[i]; + } + } + result += IDL_NAME_SEPARATOR; + result += idlName; + } else { + result = idlName; + } + return result; + } + + /** + * Replace substrings + * @param source The source string. + * @param match The string to search for within the source string. + * @param replace The replacement for any matching components. + * @return + */ + public static String replace (String source, String match, String replace) { + + int index = source.indexOf(match,0); + + if (index >=0) { + + // We have at least one match, so gotta do the + // work... + + StringBuffer result = new StringBuffer(source.length() + 16); + int matchLength = match.length(); + int startIndex = 0; + + while (index >= 0) { + result.append(source.substring(startIndex,index)); + result.append(replace); + startIndex = index + matchLength; + index = source.indexOf(match,startIndex); + } + + // Grab the last piece, if any... + + if (startIndex < source.length()) { + result.append(source.substring(startIndex)); + } + + return result.toString(); + + } else { + + // No matches, just return the source... + + return source; + } + } + + /** + * Get an IDL style repository id for + */ + public static String getIDLRepositoryID (String idlName) { + return IDL_REPOSITORY_ID_PREFIX + + replace(idlName,"::", "/") + + IDL_REPOSITORY_ID_VERSION; + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + + /** + * Convert a type or module name. + *

                + * Section 28.3.2.2 + * Section 28.3.2.3 + */ + private static String getTypeOrModuleName (String name) { + + // 28.3.2.3 Leading underscores... + + String result = convertLeadingUnderscores(name); + + // 28.3.2.2 IDL keywords (NOTE: must be done + // after leading underscore conversion because + // the mangling for IDL keywords creates a + // leading underscore!)... + + return convertIDLKeywords(result); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ImplementationType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ImplementationType.java new file mode 100644 index 000000000..5350e5f5e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ImplementationType.java @@ -0,0 +1,272 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.MemberDefinition; + +import java.util.Vector; + +/** + * ImplementationType represents any non-special class which implements + * one or more interfaces which inherit from java.rmi.Remote. + *

                + * The static forImplementation(...) method must be used to obtain an instance, + * and will return null if the ClassDefinition is non-conforming. + * + * @author Bryan Atsatt + */ +public class ImplementationType extends ClassType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an ImplementationType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static ImplementationType forImplementation(ClassDefinition classDef, + ContextStack stack, + boolean quiet) { + if (stack.anyErrors()) return null; + + boolean doPop = false; + ImplementationType result = null; + + try { + // Do we already have it? + + org.glassfish.rmic.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof ImplementationType)) return null; // False hit. + + // Yep, so return it... + + return (ImplementationType) existing; + + } + + // Could this be an implementation? + + if (couldBeImplementation(quiet,stack,classDef)) { + + // Yes, so check it... + + ImplementationType it = new ImplementationType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(stack,quiet)) { + stack.pop(true); + result = it; + } else { + removeType(theType,stack); + stack.pop(false); + } + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + } + + return result; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Implementation"; + } + + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Create a ImplementationType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private ImplementationType(ContextStack stack, ClassDefinition classDef) { + super(TYPE_IMPLEMENTATION | TM_CLASS | TM_COMPOUND,classDef,stack); // Use special constructor. + } + + + private static boolean couldBeImplementation(boolean quiet, ContextStack stack, + ClassDefinition classDef) { + boolean result = false; + BatchEnvironment env = stack.getEnv(); + + try { + if (!classDef.isClass()) { + failedConstraint(17,quiet,stack,classDef.getName()); + } else { + result = env.defRemote.implementedBy(env, classDef.getClassDeclaration()); + if (!result) failedConstraint(8,quiet,stack,classDef.getName()); + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } + + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack, boolean quiet) { + + boolean result = false; + ClassDefinition theClass = getClassDefinition(); + + if (initParents(stack)) { + + // Make up our collections... + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + + // Check interfaces... + + try { + if (addRemoteInterfaces(directInterfaces,true,stack) != null) { + + boolean haveRemote = false; + + // Get methods from all interfaces... + + for (int i = 0; i < directInterfaces.size(); i++) { + InterfaceType theInt = (InterfaceType) directInterfaces.elementAt(i); + if (theInt.isType(TYPE_REMOTE) || + theInt.isType(TYPE_JAVA_RMI_REMOTE)) { + haveRemote = true; + } + + copyRemoteMethods(theInt,directMethods); + } + + // Make sure we have at least one remote interface... + + if (!haveRemote) { + failedConstraint(8,quiet,stack,getQualifiedName()); + return false; + } + + // Now check the methods to ensure we have the + // correct throws clauses... + + if (checkMethods(theClass,directMethods,stack,quiet)) { + + // We're ok, so pass 'em up... + + result = initialize(directInterfaces,directMethods,null,stack,quiet); + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } + + return result; + } + + private static void copyRemoteMethods(InterfaceType type, Vector list) { + + if (type.isType(TYPE_REMOTE)) { + + // Copy all the unique methods from type... + + Method[] allMethods = type.getMethods(); + + for (int i = 0; i < allMethods.length; i++) { + Method theMethod = allMethods[i]; + + if (!list.contains(theMethod)) { + list.addElement(theMethod); + } + } + + // Now recurse thru all inherited interfaces... + + InterfaceType[] allInterfaces = type.getInterfaces(); + + for (int i = 0; i < allInterfaces.length; i++) { + copyRemoteMethods(allInterfaces[i],list); + } + } + } + + // Walk all methods of the class, and for each that is already in + // the list, call setImplExceptions()... + + private boolean checkMethods(ClassDefinition theClass, Vector list, + ContextStack stack, boolean quiet) { + + // Convert vector to array... + + Method[] methods = new Method[list.size()]; + list.copyInto(methods); + + for (MemberDefinition member = theClass.getFirstMember(); + member != null; + member = member.getNextMember()) { + + if (member.isMethod() && !member.isConstructor() + && !member.isInitializer()) { + + // It's a method... + + if (!updateExceptions(member,methods,stack,quiet)) { + return false; + } + } + } + return true; + } + + private boolean updateExceptions (MemberDefinition implMethod, Method[] list, + ContextStack stack, boolean quiet) { + int length = list.length; + String implMethodSig = implMethod.toString(); + + for (int i = 0; i < length; i++) { + Method existingMethod = list[i]; + MemberDefinition existing = existingMethod.getMemberDefinition(); + + // Do we have a matching method? + + if (implMethodSig.equals(existing.toString())) { + + // Yes, so create exception list... + + try { + ValueType[] implExcept = getMethodExceptions(implMethod,quiet,stack); + existingMethod.setImplExceptions(implExcept); + } catch (Exception e) { + return false; + } + } + } + return true; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/InterfaceType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/InterfaceType.java new file mode 100644 index 000000000..6e2c80a63 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/InterfaceType.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.CompilerError; + +import java.io.IOException; + +/** + * InterfaceType is an abstract base representing any non-special + * interface type. + * + * @author Bryan Atsatt + */ +public abstract class InterfaceType extends CompoundType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Print this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + if (isInner()) { + writer.p("// " + getTypeDescription() + " (INNER)"); + } else { + writer.p("// " + getTypeDescription() + ""); + } + writer.pln(" (" + getRepositoryID() + ")\n"); + printPackageOpen(writer,useIDLNames); + + if (!useIDLNames) { + writer.p("public "); + } + + writer.p("interface " + getTypeName(false,useIDLNames,false)); + printImplements(writer,"",useQualifiedNames,useIDLNames,globalIDLNames); + writer.plnI(" {"); + printMembers(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + printMethods(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + + if (useIDLNames) { + writer.pOln("};"); + } else { + writer.pOln("}"); + } + printPackageClose(writer,useIDLNames); + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create a InterfaceType instance for the given class. NOTE: This constructor + * is ONLY for SpecialInterfaceType. + */ + protected InterfaceType(ContextStack stack, int typeCode, ClassDefinition classDef) { + super(stack,typeCode,classDef); // Call special parent constructor. + + if ((typeCode & TM_INTERFACE) == 0 || ! classDef.isInterface()) { + throw new CompilerError("Not an interface"); + } + } + + /** + * Create a InterfaceType instance for the given class. The resulting + * object is not yet completely initialized. Subclasses must call + * initialize(directInterfaces,directInterfaces,directConstants); + */ + protected InterfaceType(ContextStack stack, + ClassDefinition classDef, + int typeCode) { + super(stack,classDef,typeCode); + + if ((typeCode & TM_INTERFACE) == 0 || ! classDef.isInterface()) { + throw new CompilerError("Not an interface"); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/NCClassType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/NCClassType.java new file mode 100644 index 000000000..12add7d69 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/NCClassType.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; + +import java.util.Vector; + +/** + * NCClassType represents any non-special class which does not + * extends one or more interfaces which inherit from java.rmi.Remote. + *

                + * The static forImplementation(...) method must be used to obtain an instance, + * and will return null if the ClassDefinition is non-conforming. + * + * @author Bryan Atsatt + */ +public class NCClassType extends ClassType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an NCClassType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static NCClassType forNCClass(ClassDefinition classDef, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + boolean doPop = false; + try { + // Do we already have it? + + org.glassfish.rmic.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof NCClassType)) return null; // False hit. + + // Yep, so return it... + + return (NCClassType) existing; + + } + + NCClassType it = new NCClassType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(stack)) { + stack.pop(true); + return it; + } else { + removeType(theType,stack); + stack.pop(false); + return null; + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return addExceptionDescription("Non-conforming class"); + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a NCClassType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private NCClassType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_NC_CLASS | TM_CLASS | TM_COMPOUND); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack) { + if (!initParents(stack)) { + return false; + } + + if (stack.getEnv().getParseNonConforming()) { + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directMembers = new Vector(); + + try { + + // Get methods... + + if (addAllMethods(getClassDefinition(),directMethods,false,false,stack) != null) { + + // Update parent class methods... + + if (updateParentClassMethods(getClassDefinition(),directMethods,false,stack) != null) { + + // Get conforming constants... + + if (addConformingConstants(directMembers,false,stack)) { + + // We're ok, so pass 'em up... + + if (!initialize(directInterfaces,directMethods,directMembers,stack,false)) { + return false; + } + } + } + } + return true; + + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + return false; + } else { + return initialize(null,null,null,stack,false); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/NCInterfaceType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/NCInterfaceType.java new file mode 100644 index 000000000..3ec867937 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/NCInterfaceType.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; + +import java.util.Vector; + +/** + * NCInterfaceType represents any non-special, non-conforming interface. + *

                + * The static forNCInterface(...) method must be used to obtain an instance. + * @author Bryan Atsatt + */ +public class NCInterfaceType extends InterfaceType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an NCInterfaceType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static NCInterfaceType forNCInterface( ClassDefinition classDef, + ContextStack stack) { + if (stack.anyErrors()) return null; + + boolean doPop = false; + try { + // Do we already have it? + + org.glassfish.rmic.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof NCInterfaceType)) return null; // False hit. + + // Yep, so return it... + + return (NCInterfaceType) existing; + } + + NCInterfaceType it = new NCInterfaceType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(stack)) { + stack.pop(true); + return it; + } else { + removeType(theType,stack); + stack.pop(false); + return null; + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Non-conforming interface"; + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a NCInterfaceType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private NCInterfaceType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_NC_INTERFACE | TM_INTERFACE | TM_COMPOUND); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack) { + + if (stack.getEnv().getParseNonConforming()) { + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directMembers = new Vector(); + + try { + + // need to include parent interfaces in IDL generation... + addNonRemoteInterfaces( directInterfaces,stack ); + + // Get methods... + + if (addAllMethods(getClassDefinition(),directMethods,false,false,stack) != null) { + + // Get conforming constants... + + if (addConformingConstants(directMembers,false,stack)) { + + // We're ok, so pass 'em up... + + if (!initialize(directInterfaces,directMethods,directMembers,stack,false)) { + return false; + } + } + } + return true; + + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + return false; + } else { + return initialize(null,null,null,stack,false); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/NameContext.java b/rmic/src/main/java/org/glassfish/rmic/iiop/NameContext.java new file mode 100644 index 000000000..2d26e1481 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/NameContext.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import java.util.Hashtable; + +/** + * A NameContext enables detection of strings which differ only + * in case. + * + * @author Bryan Atsatt + */ +class NameContext { + + private Hashtable table; + private boolean allowCollisions; + + /** + * Get a context for the given name. Name may be null, in + * which case this method will return the default context. + */ + public static synchronized NameContext forName (String name, + boolean allowCollisions, + BatchEnvironment env) { + + NameContext result = null; + + // Do we need to use the default context? + + if (name == null) { + + // Yes. + + name = "null"; + } + + // Have we initialized our hashtable? + + if (env.nameContexts == null) { + + // Nope, so do it... + + env.nameContexts = new Hashtable(); + + } else { + + // Yes, see if we already have the requested + // context... + + result = (NameContext) env.nameContexts.get(name); + } + + // Do we have the requested context? + + if (result == null) { + + // Nope, so create and add it... + + result = new NameContext(allowCollisions); + + env.nameContexts.put(name,result); + } + + return result; + } + + /** + * Construct a context. + * @param allowCollisions true if case-sensitive name collisions + * are allowed, false if not. + */ + public NameContext (boolean allowCollisions) { + this.allowCollisions = allowCollisions; + table = new Hashtable(); + } + + /** + * Add a name to this context. If constructed with allowCollisions + * false and a collision occurs, this method will throw an exception + * in which the message contains the string: "name" and "collision". + */ + public void assertPut (String name) throws Exception { + + String message = add(name); + + if (message != null) { + throw new Exception(message); + } + } + + /** + * Add a name to this context.. + */ + public void put (String name) { + + if (allowCollisions == false) { + throw new Error("Must use assertPut(name)"); + } + + add(name); + } + + /** + * Add a name to this context. If constructed with allowCollisions + * false and a collision occurs, this method will return a message + * string, otherwise returns null. + */ + private String add (String name) { + + // First, create a key by converting name to lowercase... + + String key = name.toLowerCase(); + + // Does this key exist in the context? + + Name value = (Name) table.get(key); + + if (value != null) { + + // Yes, so they match if we ignore case. Do they match if + // we don't ignore case? + + if (!name.equals(value.name)) { + + // No, so this is a case-sensitive match. Are we + // supposed to allow this? + + if (allowCollisions) { + + // Yes, make sure it knows that it collides... + + value.collisions = true; + + } else { + + // No, so return a message string... + + return new String("\"" + name + "\" and \"" + value.name + "\""); + } + } + } else { + + // No, so add it... + + table.put(key,new Name(name,false)); + } + + return null; + } + + /** + * Get a name from the context. If it has collisions, the name + * will be converted as specified in section 5.2.7. + */ + public String get (String name) { + + Name it = (Name) table.get(name.toLowerCase()); + String result = name; + + // Do we need to mangle it? + + if (it.collisions) { + + // Yep, so do it... + + int length = name.length(); + boolean allLower = true; + + for (int i = 0; i < length; i++) { + + if (Character.isUpperCase(name.charAt(i))) { + result += "_"; + result += i; + allLower = false; + } + } + + if (allLower) { + result += "_"; + } + } + + return result; + } + + /** + * Remove all entries. + */ + public void clear () { + table.clear(); + } + + public class Name { + public String name; + public boolean collisions; + + public Name (String name, boolean collisions) { + this.name = name; + this.collisions = collisions; + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/PrimitiveType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/PrimitiveType.java new file mode 100644 index 000000000..aa402c67f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/PrimitiveType.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Identifier; + +/** + * PrimitiveType wraps primitive types and void. + *

                + * The static forPrimitive(...) method must be used to obtain an instance, and + * will return null if the type is non-conforming. + * + * @author Bryan Atsatt + */ +public class PrimitiveType extends Type { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create a PrimitiveType object for the given type. + * + * If the type is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static PrimitiveType forPrimitive(org.glassfish.rmic.tools.java.Type type, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + // Do we already have it? + + Type existing = getType(type,stack); + + if (existing != null) { + + if (!(existing instanceof PrimitiveType)) return null; // False hit. + + // Yep, so return it... + + return (PrimitiveType) existing; + } + + int typeCode; + + switch (type.getTypeCode()) { + case TC_VOID: typeCode = TYPE_VOID; break; + case TC_BOOLEAN: typeCode = TYPE_BOOLEAN; break; + case TC_BYTE: typeCode = TYPE_BYTE; break; + case TC_CHAR: typeCode = TYPE_CHAR; break; + case TC_SHORT: typeCode = TYPE_SHORT; break; + case TC_INT: typeCode = TYPE_INT; break; + case TC_LONG: typeCode = TYPE_LONG; break; + case TC_FLOAT: typeCode = TYPE_FLOAT; break; + case TC_DOUBLE: typeCode = TYPE_DOUBLE; break; + default: return null; + } + + PrimitiveType it = new PrimitiveType(stack,typeCode); + + // Add it... + + putType(type,it,stack); + + // Do the stack thing in case tracing on... + + stack.push(it); + stack.pop(true); + + return it; + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public String getSignature() { + switch (getTypeCode()) { + case TYPE_VOID: return SIG_VOID; + case TYPE_BOOLEAN: return SIG_BOOLEAN; + case TYPE_BYTE: return SIG_BYTE; + case TYPE_CHAR: return SIG_CHAR; + case TYPE_SHORT: return SIG_SHORT; + case TYPE_INT: return SIG_INT; + case TYPE_LONG: return SIG_LONG; + case TYPE_FLOAT: return SIG_FLOAT; + case TYPE_DOUBLE: return SIG_DOUBLE; + default: return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Primitive"; + } + + /** + * IDL_Naming + * Return the fully qualified IDL name for this type (e.g. com.acme.Dynamite would + * return "com::acme::Dynamite"). + * @param global If true, prepends "::". + */ + public String getQualifiedIDLName(boolean global) { + return super.getQualifiedIDLName(false); + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /* + * Load a Class instance. Return null if fail. + */ + protected Class loadClass() { + switch (getTypeCode()) { + case TYPE_VOID: return Null.class; + case TYPE_BOOLEAN: return boolean.class; + case TYPE_BYTE: return byte.class; + case TYPE_CHAR: return char.class; + case TYPE_SHORT: return short.class; + case TYPE_INT: return int.class; + case TYPE_LONG: return long.class; + case TYPE_FLOAT: return float.class; + case TYPE_DOUBLE: return double.class; + default: throw new CompilerError("Not a primitive type"); + } + } + + /** + * IDL_Naming + * Create an PrimitiveType instance for the given class. + */ + private PrimitiveType(ContextStack stack, int typeCode) { + super(stack,typeCode | TM_PRIMITIVE); + + // Validate type and set names... + + String idlName = IDLNames.getTypeName(typeCode,false); + Identifier id = null; + + switch (typeCode) { + case TYPE_VOID: id = idVoid; break; + case TYPE_BOOLEAN: id = idBoolean; break; + case TYPE_BYTE: id = idByte; break; + case TYPE_CHAR: id = idChar; break; + case TYPE_SHORT: id = idShort; break; + case TYPE_INT: id = idInt; break; + case TYPE_LONG: id = idLong; break; + case TYPE_FLOAT: id = idFloat; break; + case TYPE_DOUBLE: id = idDouble; break; + default: throw new CompilerError("Not a primitive type"); + } + + setNames(id,null,idlName); + setRepositoryID(); + } +} + +class Null {} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/PrintGenerator.java b/rmic/src/main/java/org/glassfish/rmic/iiop/PrintGenerator.java new file mode 100644 index 000000000..cf0ad41e2 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/PrintGenerator.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStreamWriter; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.Main; + +/** + * An IDL generator for rmic. + * + * @author Bryan Atsatt + */ +public class PrintGenerator implements org.glassfish.rmic.Generator, + org.glassfish.rmic.iiop.Constants { + + private static final int JAVA = 0; + private static final int IDL = 1; + private static final int BOTH = 2; + + private int whatToPrint; // Initialized in parseArgs. + private boolean global = false; + private boolean qualified = false; + private boolean trace = false; + private boolean valueMethods = false; + + private IndentingWriter out; + + /** + * Default constructor for Main to use. + */ + public PrintGenerator() { + OutputStreamWriter writer = new OutputStreamWriter(System.out); + out = new IndentingWriter (writer); + } + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * @param error Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + String arg = argv[i].toLowerCase(); + if (arg.equals("-xprint")) { + whatToPrint = JAVA; + argv[i] = null; + if (i+1 < argv.length) { + if (argv[i+1].equalsIgnoreCase("idl")) { + argv[++i] = null; + whatToPrint = IDL; + } else if (argv[i+1].equalsIgnoreCase("both")) { + argv[++i] = null; + whatToPrint = BOTH; + } + } + } else if (arg.equals("-xglobal")) { + global = true; + argv[i] = null; + } else if (arg.equals("-xqualified")) { + qualified = true; + argv[i] = null; + } else if (arg.equals("-xtrace")) { + trace = true; + argv[i] = null; + } else if (arg.equals("-xvaluemethods")) { + valueMethods = true; + argv[i] = null; + } + } + } + return true; + } + + /** + * Generate output. Any source files created which need compilation should + * be added to the compiler environment using the addGeneratedFile(File) + * method. + * @param env The compiler environment + * @param destDir The directory for the root of the package hierarchy + * @param cdef The definition for the implementation class or interface from + * which to generate output + */ + public void generate(org.glassfish.rmic.BatchEnvironment env, File destDir, ClassDefinition cdef) { + + BatchEnvironment ourEnv = (BatchEnvironment) env; + ContextStack stack = new ContextStack(ourEnv); + stack.setTrace(trace); + + if (valueMethods) { + ourEnv.setParseNonConforming(true); + } + + // Get our top level type... + + CompoundType topType = CompoundType.forCompound(cdef,stack); + + if (topType != null) { + + try { + + // Collect up all the compound types... + + Type[] theTypes = topType.collectMatching(TM_COMPOUND); + + for (int i = 0; i < theTypes.length; i++) { + + out.pln("\n-----------------------------------------------------------\n"); + + Type theType = theTypes[i]; + + switch (whatToPrint) { + case JAVA: theType.println(out,qualified,false,false); + break; + + case IDL: theType.println(out,qualified,true,global); + break; + + case BOTH: theType.println(out,qualified,false,false); + theType.println(out,qualified,true,global); + break; + + default: throw new CompilerError("Unknown type!"); + } + } + + out.flush(); + + } catch (IOException e) { + throw new CompilerError("PrintGenerator caught " + e); + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/RemoteType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/RemoteType.java new file mode 100644 index 000000000..8374b9280 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/RemoteType.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; + +import java.util.Vector; + +/** + * RemoteType represents any non-special interface which inherits + * from java.rmi.Remote. + *

                + * The static forRemote(...) method must be used to obtain an instance, and will + * return null if the ClassDefinition is non-conforming. + * @author Bryan Atsatt + */ +public class RemoteType extends InterfaceType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an RemoteType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static RemoteType forRemote(ClassDefinition classDef, + ContextStack stack, + boolean quiet) { + + if (stack.anyErrors()) return null; + + boolean doPop = false; + RemoteType result = null; + + try { + // Do we already have it? + + org.glassfish.rmic.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof RemoteType)) return null; // False hit. + + // Yep, so return it... + + return (RemoteType) existing; + } + + // Could this be a remote type? + + if (couldBeRemote(quiet,stack,classDef)) { + + // Yes, so check it... + + RemoteType it = new RemoteType(stack,classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(quiet,stack)) { + stack.pop(true); + result = it; + } else { + removeType(theType,stack); + stack.pop(false); + } + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + } + + return result; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Remote interface"; + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a RemoteType instance for the given class. The resulting + * object is not yet completely initialized. + */ + protected RemoteType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_REMOTE | TM_INTERFACE | TM_COMPOUND); + } + + /** + * Create a RemoteType instance for the given class. The resulting + * object is not yet completely initialized. + */ + protected RemoteType(ContextStack stack, ClassDefinition classDef, int typeCode) { + super(stack,classDef,typeCode); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + + private static boolean couldBeRemote (boolean quiet, ContextStack stack, + ClassDefinition classDef) { + + boolean result = false; + BatchEnvironment env = stack.getEnv(); + + try { + if (!classDef.isInterface()) { + failedConstraint(16,quiet,stack,classDef.getName()); + } else { + result = env.defRemote.implementedBy(env,classDef.getClassDeclaration()); + if (!result) failedConstraint(1,quiet,stack,classDef.getName()); + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } + + + /** + * Initialize this instance. + */ + private boolean initialize (boolean quiet,ContextStack stack) { + + boolean result = false; + + // Go check it out and gather up the info we need... + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directConstants = new Vector(); + + if (isConformingRemoteInterface(directInterfaces, + directMethods, + directConstants, + quiet, + stack)){ + + // We're ok, so pass 'em up... + + result = initialize(directInterfaces,directMethods,directConstants,stack,quiet); + } + + return result; + } + + /** + * Check to ensure that the interface and all it's methods and arguments + * conforms to the RMI/IDL java subset for remote interfaces as defined + * by the "Java to IDL Mapping" specification, section 4. + * @param directInterfaces All directly implmented interfaces will be + * added to this list. + * @param directMethods All directly implemented methods (other than + * constructors and initializers) will be added to this list. + * @param directConstants All constants defined by theInterface will be + * added to this list. + * @param quiet True if should not report constraint failures. + * @return true if constraints satisfied, false otherwise. + */ + private boolean isConformingRemoteInterface ( Vector directInterfaces, + Vector directMethods, + Vector directConstants, + boolean quiet, + ContextStack stack) { + + ClassDefinition theInterface = getClassDefinition(); + + try { + + // Get all remote interfaces... + + if (addRemoteInterfaces(directInterfaces,false,stack) == null ) { + return false; + } + + // Make sure all constants are conforming... + + if (!addAllMembers(directConstants,true,quiet,stack)) { + return false; + } + + // Now, collect up all methods... + + if (addAllMethods(theInterface,directMethods,true,quiet,stack) == null) { + // Failed a constraint check... + return false; + } + + // Now walk 'em, ensuring each is a valid remote method... + + boolean methodsConform = true; + for (int i = 0; i < directMethods.size(); i++) { + if (! isConformingRemoteMethod((Method) directMethods.elementAt(i),quiet)) { + methodsConform = false; + } + } + if (!methodsConform) { + return false; + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + return false; + } + + return true; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/SpecialClassType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/SpecialClassType.java new file mode 100644 index 000000000..fefe9b8ab --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/SpecialClassType.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Identifier; + +/** + * SpecialClassType represents any one of the following types: + *

                + *    java.lang.Object
                + *    java.lang.String
                + * 
                + * all of which are treated as special cases. + *

                + * The static forSpecial(...) method must be used to obtain an instance, and + * will return null if the type is non-conforming. + * + * @author Bryan Atsatt + */ +public class SpecialClassType extends ClassType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create a SpecialClassType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static SpecialClassType forSpecial (ClassDefinition theClass, + ContextStack stack) { + if (stack.anyErrors()) return null; + + org.glassfish.rmic.tools.java.Type type = theClass.getType(); + + // Do we already have it? + + String typeKey = type.toString() + stack.getContextCodeString(); + + Type existing = getType(typeKey,stack); + + if (existing != null) { + + if (!(existing instanceof SpecialClassType)) return null; // False hit. + + // Yep, so return it... + + return (SpecialClassType) existing; + } + + // Is it a special type? + + int typeCode = getTypeCode(type,theClass,stack); + + if (typeCode != TYPE_NONE) { + + // Yes... + + SpecialClassType result = new SpecialClassType(stack,typeCode,theClass); + putType(typeKey,result,stack); + stack.push(result); + stack.pop(true); + return result; + + } else { + + return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Special class"; + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create an SpecialClassType instance for the given class. + */ + private SpecialClassType(ContextStack stack, int typeCode, + ClassDefinition theClass) { + super(stack,typeCode | TM_SPECIAL_CLASS | TM_CLASS | TM_COMPOUND, theClass); + Identifier id = theClass.getName(); + String idlName = null; + String[] idlModuleName = null; + boolean constant = stack.size() > 0 && stack.getContext().isConstant(); + + // Set names... + + switch (typeCode) { + case TYPE_STRING: { + idlName = IDLNames.getTypeName(typeCode,constant); + if (!constant) { + idlModuleName = IDL_CORBA_MODULE; + } + break; + } + + case TYPE_ANY: { + idlName = IDL_JAVA_LANG_OBJECT; + idlModuleName = IDL_JAVA_LANG_MODULE; + break; + } + } + + setNames(id,idlModuleName,idlName); + + // Init parents... + + if (!initParents(stack)) { + + // Should not be possible! + + throw new CompilerError("SpecialClassType found invalid parent."); + } + + // Initialize CompoundType... + + initialize(null,null,null,stack,false); + } + + private static int getTypeCode(org.glassfish.rmic.tools.java.Type type, ClassDefinition theClass, ContextStack stack) { + if (type.isType(TC_CLASS)) { + Identifier id = type.getClassName(); + if (id == idJavaLangString) return TYPE_STRING; + if (id == idJavaLangObject) return TYPE_ANY; + } + return TYPE_NONE; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/SpecialInterfaceType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/SpecialInterfaceType.java new file mode 100644 index 000000000..2c034cde3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/SpecialInterfaceType.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Identifier; + +/** + * SpecialInterfaceType represents any one of the following types: + *

                + *    java.rmi.Remote
                + *    java.io.Serializable
                + *    java.io.Externalizable
                + *    org.omg.CORBA.Object
                + *    org.omg.CORBA.portable.IDLEntity
                + * 
                + * all of which are treated as special cases. For all but CORBA.Object, + * the type must match exactly. For CORBA.Object, the type must either be + * CORBA.Object or inherit from it. + *

                + * The static forSpecial(...) method must be used to obtain an instance, and + * will return null if the type is non-conforming. + * + * @author Bryan Atsatt + */ +public class SpecialInterfaceType extends InterfaceType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create a SpecialInterfaceType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static SpecialInterfaceType forSpecial ( ClassDefinition theClass, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + // Do we already have it? + + org.glassfish.rmic.tools.java.Type type = theClass.getType(); + Type existing = getType(type,stack); + + if (existing != null) { + + if (!(existing instanceof SpecialInterfaceType)) return null; // False hit. + + // Yep, so return it... + + return (SpecialInterfaceType) existing; + } + + // Is it special? + + if (isSpecial(type,theClass,stack)) { + + // Yes... + + SpecialInterfaceType result = new SpecialInterfaceType(stack,0,theClass); + putType(type,result,stack); + stack.push(result); + + if (result.initialize(type,stack)) { + stack.pop(true); + return result; + } else { + removeType(type,stack); + stack.pop(false); + return null; + } + } + return null; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Special interface"; + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create an SpecialInterfaceType instance for the given class. + */ + private SpecialInterfaceType(ContextStack stack, int typeCode, + ClassDefinition theClass) { + super(stack,typeCode | TM_SPECIAL_INTERFACE | TM_INTERFACE | TM_COMPOUND, theClass); + setNames(theClass.getName(),null,null); // Fixed in initialize. + } + + private static boolean isSpecial(org.glassfish.rmic.tools.java.Type type, + ClassDefinition theClass, + ContextStack stack) { + if (type.isType(TC_CLASS)) { + Identifier id = type.getClassName(); + + if (id.equals(idRemote)) return true; + if (id == idJavaIoSerializable) return true; + if (id == idJavaIoExternalizable) return true; + if (id == idCorbaObject) return true; + if (id == idIDLEntity) return true; + BatchEnvironment env = stack.getEnv(); + try { + if (env.defCorbaObject.implementedBy(env,theClass.getClassDeclaration())) return true; + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } + return false; + } + + private boolean initialize(org.glassfish.rmic.tools.java.Type type, ContextStack stack) { + + int typeCode = TYPE_NONE; + Identifier id = null; + String idlName = null; + String[] idlModuleName = null; + boolean constant = stack.size() > 0 && stack.getContext().isConstant(); + + if (type.isType(TC_CLASS)) { + id = type.getClassName(); + + if (id.equals(idRemote)) { + typeCode = TYPE_JAVA_RMI_REMOTE; + idlName = IDL_JAVA_RMI_REMOTE; + idlModuleName = IDL_JAVA_RMI_MODULE; + } else if (id == idJavaIoSerializable) { + typeCode = TYPE_ANY; + idlName = IDL_SERIALIZABLE; + idlModuleName = IDL_JAVA_IO_MODULE; + } else if (id == idJavaIoExternalizable) { + typeCode = TYPE_ANY; + idlName = IDL_EXTERNALIZABLE; + idlModuleName = IDL_JAVA_IO_MODULE; + } else if (id == idIDLEntity) { + typeCode = TYPE_ANY; + idlName = IDL_IDLENTITY; + idlModuleName = IDL_ORG_OMG_CORBA_PORTABLE_MODULE; + } else { + + typeCode = TYPE_CORBA_OBJECT; + + // Is it exactly org.omg.CORBA.Object? + + if (id == idCorbaObject) { + + // Yes, so special case... + + idlName = IDLNames.getTypeName(typeCode,constant); + idlModuleName = null; + + } else { + + // No, so get the correct names... + + try { + + // These can fail if we get case-sensitive name matches... + + idlName = IDLNames.getClassOrInterfaceName(id,env); + idlModuleName = IDLNames.getModuleNames(id,isBoxed(),env); + + } catch (Exception e) { + failedConstraint(7,false,stack,id.toString(),e.getMessage()); + throw new CompilerError(""); + } + } + } + } + + if (typeCode == TYPE_NONE) { + return false; + } + + // Reset type code... + + setTypeCode(typeCode | TM_SPECIAL_INTERFACE | TM_INTERFACE | TM_COMPOUND); + + // Set names + + if (idlName == null) { + throw new CompilerError("Not a special type"); + } + + setNames(id,idlModuleName,idlName); + + // Initialize CompoundType... + + return initialize(null,null,null,stack,false); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/StaticStringsHash.java b/rmic/src/main/java/org/glassfish/rmic/iiop/StaticStringsHash.java new file mode 100644 index 000000000..9b368ff14 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/StaticStringsHash.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +/** + * StaticStringsHash takes an array of constant strings and + * uses several different hash methods to try to find the + * 'best' one for that set. The set of methods is currently + * fixed, but with a little work could be made extensible thru + * subclassing. + *

                + * The current set of methods is: + *

                  + *
                1. length() - works well when all strings are different length.
                2. + *
                3. charAt(n) - works well when one offset into all strings is different.
                4. + *
                5. hashCode() - works well with larger arrays.
                6. + *
                + * After constructing an instance over the set of strings, the + * getKey(String) method can be used to use the selected hash + * method to produce a key. The method string will contain + * "length()", "charAt(n)", or "hashCode()", and is intended for use by + * code generators. + *

                + * The keys array will contain the full set of unique keys. + *

                + * The buckets array will contain a set of arrays, one for + * each key in the keys, where buckets[x][y] + * is an index into the strings array. + * @author Bryan Atsatt + */ +public class StaticStringsHash { + + /** The set of strings upon which the hash info is created */ + public String[] strings = null; + + /** Unique hash keys */ + public int[] keys = null; + + /** Buckets for each key, where buckets[x][y] is an index + * into the strings[] array. */ + public int[][] buckets = null; + + /** The method to invoke on String to produce the hash key */ + public String method = null; + + /** Get a key for the given string using the + * selected hash method. + * @param str the string to return a key for. + * @return the key. + */ + public int getKey(String str) { + switch (keyKind) { + case LENGTH: return str.length(); + case CHAR_AT: return str.charAt(charAt); + case HASH_CODE: return str.hashCode(); + } + throw new Error("Bad keyKind"); + } + + /** Constructor + * @param strings the set of strings upon which to + * find an optimal hash method. Must not contain + * duplicates. + */ + public StaticStringsHash(String[] strings) { + this.strings = strings; + length = strings.length; + tempKeys = new int[length]; + bucketSizes = new int[length]; + setMinStringLength(); + + // Decide on the best algorithm based on + // which one has the smallest maximum + // bucket depth. First, try length()... + + int currentMaxDepth = getKeys(LENGTH); + int useCharAt = -1; + boolean useHashCode = false; + + if (currentMaxDepth > 1) { + + // At least one bucket had more than one + // entry, so try charAt(i). If there + // are a lot of strings in the array, + // and minStringLength is large, limit + // the search to a smaller number of + // characters to avoid spending a lot + // of time here that is most likely to + // be pointless... + + int minLength = minStringLength; + if (length > CHAR_AT_MAX_LINES && + length * minLength > CHAR_AT_MAX_CHARS) { + minLength = length/CHAR_AT_MAX_CHARS; + } + + charAt = 0; + for (int i = 0; i < minLength; i++) { + int charAtDepth = getKeys(CHAR_AT); + if (charAtDepth < currentMaxDepth) { + currentMaxDepth = charAtDepth; + useCharAt = i; + if (currentMaxDepth == 1) { + break; + } + } + charAt++; + } + charAt = useCharAt; + + + if (currentMaxDepth > 1) { + + // At least one bucket had more than one + // entry, try hashCode(). + // + // Since the cost of computing a full hashCode + // (for the runtime target string) is much higher + // than the previous methods, use it only if it is + // substantially better. The definition of 'substantial' + // here is not very well founded, and could be improved + // with some further analysis ;^) + + int hashCodeDepth = getKeys(HASH_CODE); + if (hashCodeDepth < currentMaxDepth-3) { + + // Using the full hashCode results in at least + // 3 fewer entries in the worst bucket, so will + // therefore avoid at least 3 calls to equals() + // in the worst case. + // + // Note that using a number smaller than 3 could + // result in using a hashCode when there are only + // 2 strings in the array, and that would surely + // be a poor performance choice. + + useHashCode = true; + } + } + + // Reset keys if needed... + + if (!useHashCode) { + if (useCharAt >= 0) { + + // Use the charAt(i) method... + + getKeys(CHAR_AT); + + } else { + + // Use length method... + + getKeys(LENGTH); + } + } + } + + // Now allocate and fill our real hashKeys array... + + keys = new int[bucketCount]; + System.arraycopy(tempKeys,0,keys,0,bucketCount); + + // Sort keys and bucketSizes arrays... + + boolean didSwap; + do { + didSwap = false; + for (int i = 0; i < bucketCount - 1; i++) { + if (keys[i] > keys[i+1]) { + int temp = keys[i]; + keys[i] = keys[i+1]; + keys[i+1] = temp; + temp = bucketSizes[i]; + bucketSizes[i] = bucketSizes[i+1]; + bucketSizes[i+1] = temp; + didSwap = true; + } + } + } + while (didSwap == true); + + // Allocate our buckets array. Fill the string + // index slot with an unused key so we can + // determine which are free... + + int unused = findUnusedKey(); + buckets = new int[bucketCount][]; + for (int i = 0; i < bucketCount; i++) { + buckets[i] = new int[bucketSizes[i]]; + for (int j = 0; j < bucketSizes[i]; j++) { + buckets[i][j] = unused; + } + } + + // And fill it in... + + for(int i = 0; i < strings.length; i++) { + int key = getKey(strings[i]); + for (int j = 0; j < bucketCount; j++) { + if (keys[j] == key) { + int k = 0; + while (buckets[j][k] != unused) { + k++; + } + buckets[j][k] = i; + break; + } + } + } + } + + /** Print an optimized 'contains' method for the + * argument strings + */ + public static void main (String[] args) { + StaticStringsHash hash = new StaticStringsHash(args); + System.out.println(); + System.out.println(" public boolean contains(String key) {"); + System.out.println(" switch (key."+hash.method+") {"); + for (int i = 0; i < hash.buckets.length; i++) { + System.out.println(" case "+hash.keys[i]+": "); + for (int j = 0; j < hash.buckets[i].length; j++) { + if (j > 0) { + System.out.print(" } else "); + } else { + System.out.print(" "); + } + System.out.println("if (key.equals(\""+ hash.strings[hash.buckets[i][j]] +"\")) {"); + System.out.println(" return true;"); + } + System.out.println(" }"); + } + System.out.println(" }"); + System.out.println(" return false;"); + System.out.println(" }"); + } + + private int length; + private int[] tempKeys; + private int[] bucketSizes; + private int bucketCount; + private int maxDepth; + private int minStringLength = Integer.MAX_VALUE; + private int keyKind; + private int charAt; + + private static final int LENGTH = 0; + private static final int CHAR_AT = 1; + private static final int HASH_CODE = 2; + + /* Determines the maximum number of charAt(i) + * tests that will be done. The search is + * limited because if the number of characters + * is large enough, the likelyhood of finding + * a good hash key based on this method is + * low. The CHAR_AT_MAX_CHARS limit only + * applies f there are more strings than + * CHAR_AT_MAX_LINES. + */ + private static final int CHAR_AT_MAX_LINES = 50; + private static final int CHAR_AT_MAX_CHARS = 1000; + + private void resetKeys(int keyKind) { + this.keyKind = keyKind; + switch (keyKind) { + case LENGTH: method = "length()"; break; + case CHAR_AT: method = "charAt("+charAt+")"; break; + case HASH_CODE: method = "hashCode()"; break; + } + maxDepth = 1; + bucketCount = 0; + for (int i = 0; i < length; i++) { + tempKeys[i] = 0; + bucketSizes[i] = 0; + } + } + + private void setMinStringLength() { + for (int i = 0; i < length; i++) { + if (strings[i].length() < minStringLength) { + minStringLength = strings[i].length(); + } + } + } + + private int findUnusedKey() { + int unused = 0; + int keysLength = keys.length; + + // Note that we just assume that resource + // exhaustion will occur rather than an + // infinite loop here if the set of keys + // is very large. + + while (true) { + boolean match = false; + for (int i = 0; i < keysLength; i++) { + if (keys[i] == unused) { + match = true; + break; + } + } + if (match) { + unused--; + } else { + break; + } + } + return unused; + } + + private int getKeys(int methodKind) { + resetKeys(methodKind); + for(int i = 0; i < strings.length; i++) { + addKey(getKey(strings[i])); + } + return maxDepth; + } + + private void addKey(int key) { + + // Have we seen this one before? + + boolean addIt = true; + for (int j = 0; j < bucketCount; j++) { + if (tempKeys[j] == key) { + addIt = false; + bucketSizes[j]++; + if (bucketSizes[j] > maxDepth) { + maxDepth = bucketSizes[j]; + } + break; + } + } + + if (addIt) { + tempKeys[bucketCount] = key; + bucketSizes[bucketCount] = 1; + bucketCount++; + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/StubGenerator.java b/rmic/src/main/java/org/glassfish/rmic/iiop/StubGenerator.java new file mode 100644 index 000000000..f3a289902 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/StubGenerator.java @@ -0,0 +1,2352 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import com.sun.corba.ee.impl.util.PackagePrefixChecker; +import com.sun.corba.ee.impl.util.Utility; +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.Main; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassFile; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Identifier; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Vector; + + +/** + * An IIOP stub/tie generator for rmic. + * + * @author Bryan Atsatt + * @author Anil Vijendran + * @author M. Mortazavi + */ + +public class StubGenerator extends org.glassfish.rmic.iiop.Generator { + + private static final String DEFAULT_STUB_CLASS = "javax.rmi.CORBA.Stub"; + private static final String DEFAULT_TIE_CLASS = "org.omg.CORBA_2_3.portable.ObjectImpl"; + private static final String DEFAULT_POA_TIE_CLASS = "org.omg.PortableServer.Servant"; + + private boolean reverseIDs = false; + private boolean localStubs = true; + private boolean standardPackage = false; + private boolean useHash = true; + private String stubBaseClass = DEFAULT_STUB_CLASS; + private String tieBaseClass = DEFAULT_TIE_CLASS; + private HashSet namesInUse = new HashSet(); + private Hashtable classesInUse = new Hashtable(); + private Hashtable imports = new Hashtable(); + private int importCount = 0; + private String currentPackage = null; + private String currentClass = null; + private boolean castArray = false; + private Hashtable transactionalObjects = new Hashtable() ; + private boolean POATie = false ; + private boolean emitPermissionCheck = false; + + /** + * Default constructor for Main to use. + */ + public StubGenerator() { + } + + /** + * Overridden in order to set the standardPackage flag. + */ + public void generate(org.glassfish.rmic.BatchEnvironment env, File destDir, ClassDefinition cdef) { + ((BatchEnvironment)env).setStandardPackage(standardPackage); + super.generate(env, destDir, cdef); + } + + /** + * Return true if a new instance should be created for each + * class on the command line. Subclasses which return true + * should override newInstance() to return an appropriately + * constructed instance. + */ + protected boolean requireNewInstance() { + return false; + } + + /** + * Return true if non-conforming types should be parsed. + * @param stack The context stack. + */ + protected boolean parseNonConforming(ContextStack stack) { + + // We let the environment setting decide so that + // another generator (e.g. IDLGenerator) can change + // it and we will just go with the flow... + + return stack.getEnv().getParseNonConforming(); + } + + /** + * Create and return a top-level type. + * @param cdef The top-level class definition. + * @param stack The context stack. + * @return The compound type or null if is non-conforming. + */ + protected CompoundType getTopType(ClassDefinition cdef, ContextStack stack) { + + CompoundType result; + + // Do we have an interface? + + if (cdef.isInterface()) { + + // Yes, so first try Abstract... + + result = AbstractType.forAbstract(cdef,stack,true); + + if (result == null) { + + // Then try Remote... + + result = RemoteType.forRemote(cdef,stack,false); + } + } else { + + // Not an interface, so try Implementation... + + result = ImplementationType.forImplementation(cdef,stack,false); + } + + return result; + } + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param main Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + Object marker = new Object() ; + + // Reset any cached options... + + reverseIDs = false; + localStubs = true; + useHash = true; + stubBaseClass = DEFAULT_STUB_CLASS; + // tieBaseClass = DEFAULT_TIE_CLASS; + transactionalObjects = new Hashtable() ; + + // Parse options... + + boolean result = super.parseArgs(argv,main); + if (result) { + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + String arg = argv[i].toLowerCase(); + if (arg.equals("-iiop")) { + argv[i] = null; + } else if (arg.equals("-xreverseids")) { + reverseIDs = true; + argv[i] = null; + } else if (arg.equals("-nolocalstubs")) { + localStubs = false; + argv[i] = null; + } else if (arg.equals("-xnohash")) { + useHash = false; + argv[i] = null; + } else if (argv[i].equals("-standardPackage")) { + standardPackage = true; + argv[i] = null; + } else if (argv[i].equals("-emitPermissionCheck")) { + emitPermissionCheck = true; + argv[i] = null; + } else if (arg.equals("-xstubbase")) { + argv[i] = null; + if (++i < argv.length && argv[i] != null && !argv[i].startsWith("-")) { + stubBaseClass = argv[i]; + argv[i] = null; + } else { + main.error("rmic.option.requires.argument", "-Xstubbase"); + result = false; + } + } else if (arg.equals("-xtiebase")) { + argv[i] = null; + if (++i < argv.length && argv[i] != null && !argv[i].startsWith("-")) { + tieBaseClass = argv[i]; + argv[i] = null; + } else { + main.error("rmic.option.requires.argument", "-Xtiebase"); + result = false; + } + } else if (arg.equals("-transactional" )) { + // Scan for the next non-flag argument. + // Assume that it is a class name and add it + // to the list of transactional classes. + for ( int ctr=i+1; ctr list = new Vector<>(count+5); + BatchEnvironment theEnv = topType.getEnv(); + + // Now walk all types... + + for (int i = 0; i < genTypes.length; i++) { + + Type type = genTypes[i]; + String typeName = type.getName(); + boolean createStub = true; + + // Is it an implementation type? + + if (type instanceof ImplementationType) { + + // Yes, so add a tie for it... + + list.addElement(new OutputType(Utility.tieNameForCompiler(typeName), type)); + + // Does it have more than 1 remote interface? If so, we + // want to create a stub for it... + + int remoteInterfaceCount = 0; + InterfaceType[] interfaces = ((CompoundType)type).getInterfaces(); + for (InterfaceType anInterface : interfaces) { + if (anInterface.isType(TYPE_REMOTE) && !anInterface.isType(TYPE_ABSTRACT)) { + remoteInterfaceCount++; + } + } + + if (remoteInterfaceCount <= 1) { + + // No, so do not create a stub for this type... + + createStub = false; + } + } + + // Is it an abstract interface type? + + if (type instanceof AbstractType) { + + // Do not create a stub for this type... + + createStub = false; // d11141 + } + + if (createStub) { + + // Add a stub for the type... + + list.addElement(new OutputType(Utility.stubNameForCompiler(typeName), type)); + } + } + + // Copy list into array.. + + OutputType[] outputTypes = new OutputType[list.size()]; + list.copyInto(outputTypes); + return outputTypes; + } + + /** + * Return the file name extension for the given file name (e.g. ".java"). + * All files generated with the ".java" extension will be compiled. To + * change this behavior for ".java" files, override the compileJavaSourceFile + * method to return false. + * @param outputType One of the items returned by getOutputTypesFor(...) + */ + protected String getFileNameExtensionFor(OutputType outputType) { + return SOURCE_FILE_EXTENSION; + } + + /** + * Write the output for the given OutputFileName into the output stream. + * @param outputType One of the items returned by getOutputTypesFor(...) + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + * @param writer The output stream. + */ + protected void writeOutputFor( OutputType outputType, + HashSet alreadyChecked, + IndentingWriter writer) throws IOException { + + if (isStubType(outputType)) { + writeStub(outputType,writer); + } else { + writeTie(outputType,writer); + } + } + + private boolean isStubType(OutputType outputType) { + return outputType.getName().endsWith(Utility.RMI_STUB_SUFFIX); + } + + /** + * Write a stub for the specified type. + */ + private void writeStub(OutputType outputType, + IndentingWriter p) throws IOException { + + CompoundType theType = (CompoundType) outputType.getType(); + RemoteType[] remoteInterfaces = getDirectRemoteInterfaces(theType); + + // Write comment. + + p.pln("// Stub class generated by rmic, do not edit."); + p.pln("// Contents subject to change without notice."); + p.pln(); + + // Set our standard classes... + + setStandardClassesInUse(theType,true); + + // Add classes for this type... + + addClassesInUse(theType,remoteInterfaces); + + // Write package and import statements... + + writePackageAndImports(p); + + if (emitPermissionCheck) { + p.pln("import java.security.AccessController;"); + p.pln("import java.security.PrivilegedAction;"); + p.pln("import java.io.SerializablePermission;"); + p.pln(); + p.pln(); + } + + // Declare the stub class; implement all remote interfaces. + + p.p("public class " + currentClass); + + p.p(" extends " + getName(stubBaseClass)); + p.p(" implements "); + if (remoteInterfaces.length > 0) { + for(int i = 0; i < remoteInterfaces.length; i++) { + if (i > 0) { + p.pln(","); + } + String objName = testUtil(getName(remoteInterfaces[i]), theType); + p.p(objName); + } + } + + // Add java.rmi.Remote if this type does not implement it. + // This allows stubs for Abstract interfaces to be treated + // uniformly... + + if (!implementsRemote(theType)) { + p.pln(","); + p.p(getName("java.rmi.Remote")); + } + + p.plnI(" {"); + p.pln(); + + // Write the ids... + + writeIds( p, theType, false ); + p.pln(); + + if (emitPermissionCheck) { + + // produce the following generated code for example + // + // private transient boolean _instantiated = false; + // + // private static Void checkPermission() { + // SecurityManager sm = System.getSecurityManager(); + // if (sm != null) { + // sm.checkPermission(new SerializablePermission( + // "enableSubclassImplementation")); // testing + // } + // return null; + // } + // + // private _XXXXX_Stub(Void ignore) { + // } + // + // public _XXXXX_Stub() { + // this(checkPermission()); + // _instantiated = true; + // } + // + // private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { + // checkPermission(); + // s.defaultReadObject(); + // _instantiated = true; + // } + // + // where XXXXX is the name of the remote interface + + p.pln(); + p.plnI("private transient boolean _instantiated = false;"); + p.pln(); + p.pO(); + p.plnI("private static Void checkPermission() {"); + p.plnI("SecurityManager sm = System.getSecurityManager();"); + p.pln("if (sm != null) {"); + p.pI(); + p.plnI("sm.checkPermission(new SerializablePermission("); + p.plnI("\"enableSubclassImplementation\"));"); + p.pO(); + p.pO(); + p.pOln("}"); + p.pln("return null;"); + p.pO(); + p.pOln("}"); + p.pln(); + p.pO(); + + p.pI(); + p.plnI("private " + currentClass + "(Void ignore) { }"); + p.pln(); + p.pO(); + + p.plnI("public " + currentClass + "() { "); + p.pln("this(checkPermission());"); + p.pln("_instantiated = true;"); + p.pOln("}"); + p.pln(); + p.plnI("private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {"); + p.plnI("checkPermission();"); + p.pO(); + p.pln("s.defaultReadObject();"); + p.pln("_instantiated = true;"); + p.pOln("}"); + p.pln(); + //p.pO(); + } + + if (!emitPermissionCheck) { + p.pI(); + } + + // Write the _ids() method... + + p.plnI("public String[] _ids() { "); + p.pln("return (String[]) _type_ids.clone();"); + p.pOln("}"); + + // Get all the methods and write each stub method... + + CompoundType.Method[] remoteMethods = theType.getMethods(); + int methodCount = remoteMethods.length; + if (methodCount > 0) { + boolean writeHeader = true; + for(int i = 0; i < methodCount; i++) { + if (!remoteMethods[i].isConstructor()) { + if (writeHeader) { + writeHeader = false; + } + p.pln(); + writeStubMethod(p, remoteMethods[i], theType); + } + } + } + + // Write the cast array hack... + + writeCastArray(p); + + p.pOln("}"); // end stub class + } + + private void addClassInUse(String qualifiedName) { + String unqualifiedName = qualifiedName; + String packageName = null; + int index = qualifiedName.lastIndexOf('.'); + if (index > 0) { + unqualifiedName = qualifiedName.substring(index+1); + packageName = qualifiedName.substring(0,index); + } + addClassInUse(unqualifiedName,qualifiedName,packageName); + } + + private void addClassInUse(Type type) { + if (!type.isPrimitive()) { + Identifier id = type.getIdentifier(); + String name = IDLNames.replace(id.getName().toString(),". ","."); + String packageName = type.getPackageName(); + String qualifiedName; + if (packageName != null) { + qualifiedName = packageName+"."+name; + } else { + qualifiedName = name; + } + addClassInUse(name,qualifiedName,packageName); + } + } + + private void addClassInUse(Type[] types) { + for (Type type : types) { + addClassInUse(type); + } + } + + private void addStubInUse(Type type) { + if (type.getIdentifier() != idCorbaObject && type.isType(TYPE_CORBA_OBJECT)) { + String stubName = getStubNameFor(type,false); + String packageName = type.getPackageName(); + String fullName; + if (packageName == null) { + fullName = stubName; + } else { + fullName = packageName + "." + stubName; + } + addClassInUse(stubName,fullName,packageName); + } + if (type.isType(TYPE_REMOTE) || + type.isType(TYPE_JAVA_RMI_REMOTE)) { + addClassInUse("javax.rmi.PortableRemoteObject"); + } + } + + private String getStubNameFor(Type type, boolean qualified) { + String stubName; + String className; + if (qualified) { + className = type.getQualifiedName(); + } else { + className = type.getName(); + } + if (((CompoundType)type).isCORBAObject()) { + stubName = Utility.idlStubName(className); + } else { + stubName = Utility.stubNameForCompiler(className); + } + return stubName; + } + + private void addStubInUse(Type[] types) { + for (Type type : types) { + addStubInUse(type); + } + } + + private static final String NO_IMPORT = new String(); + + void addClassInUse(String unqualifiedName, String qualifiedName, String packageName) { + + // Have we already got an entry for this qualifiedName? + + String currentName = (String)classesInUse.get(qualifiedName); + + if (currentName == null) { + + // No, never seen it before. Grab any existing import + // name and then decide what to do... + + String importName = (String) imports.get(unqualifiedName); + String nameToUse = null; + + if (packageName == null) { + + // Default package, so doesn't matter which name to use... + + nameToUse = unqualifiedName; + + } else if (packageName.equals("java.lang")) { + + // java.lang.*, so use unqualified name... + + nameToUse = unqualifiedName; + + // unless you want to be able to import things from the right place :--) + + if(nameToUse.endsWith("_Stub")) nameToUse = Util.packagePrefix()+qualifiedName; + + } else if (currentPackage != null && packageName.equals(currentPackage)) { + + // Class in currentPackage, so use unqualified name... + + nameToUse = unqualifiedName; + + // Do we already have a previous import under this + // unqualified name? + + if (importName != null) { + + // Yes, so we use qualifiedName... + + nameToUse = qualifiedName; + + } + + } else if (importName != null) { + + // It is in some package for which we normally + // would import, but we have a previous import + // under this unqualified name. We must use + // the qualified name... + + nameToUse = qualifiedName; + + /* + // Is the currentPackage the default package? + + if (currentPackage == null) { + + // Yes, so undo the import so that all + // uses for this name will be qualified... + + String old = (String)imports.remove(unqualifiedName); + classesInUse.put(old,old); + importCount--; + + // Note that this name is in use but should + // not be imported... + + imports.put(nameToUse,NO_IMPORT); + } + */ + } else if (qualifiedName.equals("org.omg.CORBA.Object")) { + + // Always qualify this quy to avoid confusion... + + nameToUse = qualifiedName; + + } else { + + // Default to using unqualified name, and add + // this guy to the imports... + + // Check for nested class in which case we use + // the fully qualified name instead of imports + if (unqualifiedName.indexOf('.') != -1) { + nameToUse = qualifiedName; + } else { + nameToUse = unqualifiedName; + imports.put(unqualifiedName,qualifiedName); + importCount++; + } + } + + // Now add the name... + + classesInUse.put(qualifiedName,nameToUse); + } + } + + String getName(Type type) { + if (type.isPrimitive()) { + return type.getName() + type.getArrayBrackets(); + } + Identifier id = type.getIdentifier(); + String name = IDLNames.replace(id.toString(),". ","."); + return getName(name) + type.getArrayBrackets(); + } + + // Added for Bug 4818753 + String getExceptionName(Type type) { + Identifier id = type.getIdentifier(); + return IDLNames.replace(id.toString(),". ","."); + } + + String getName(String qualifiedName) { + return (String)classesInUse.get(qualifiedName); + } + + String getName(Identifier id) { + return getName(id.toString()); + } + + String getStubName(Type type) { + String stubName = getStubNameFor(type,true); + return getName(stubName); + } + + void setStandardClassesInUse(CompoundType type, + boolean stub) throws IOException { + + // Reset our state... + + currentPackage = type.getPackageName(); + imports.clear(); + classesInUse.clear(); + namesInUse.clear(); + importCount = 0; + castArray = false; + + // Add the top-level type... + + addClassInUse(type); + + // Set current class name... + + if (stub) { + currentClass = Utility.stubNameForCompiler(type.getName()); + } else { + currentClass = Utility.tieNameForCompiler(type.getName()); + } + + // Add current class... + + if (currentPackage == null) { + addClassInUse(currentClass,currentClass,currentPackage); + } else { + addClassInUse(currentClass,(currentPackage+"."+currentClass),currentPackage); + } + + // Add standard classes... + + addClassInUse("javax.rmi.CORBA.Util"); + addClassInUse(idRemote.toString()); + addClassInUse(idRemoteException.toString()); + addClassInUse(idOutputStream.toString()); + addClassInUse(idInputStream.toString()); + addClassInUse(idSystemException.toString()); + addClassInUse(idJavaIoSerializable.toString()); + addClassInUse(idCorbaORB.toString()); + addClassInUse(idReplyHandler.toString()); + + // Add stub/tie specific imports... + + if (stub) { + addClassInUse(stubBaseClass); + addClassInUse("java.rmi.UnexpectedException"); + addClassInUse(idRemarshalException.toString()); + addClassInUse(idApplicationException.toString()); + if (localStubs) { + addClassInUse("org.omg.CORBA.portable.ServantObject"); + } + } else { + addClassInUse(type); + addClassInUse(tieBaseClass); + addClassInUse(idTieInterface.toString()); + addClassInUse(idBadMethodException.toString()); + addClassInUse(idPortableUnknownException.toString()); + addClassInUse(idJavaLangThrowable.toString()); + } + } + + void addClassesInUse(CompoundType type, RemoteType[] interfaces) { + + // Walk all methods and add types in use... + + CompoundType.Method[] methods = type.getMethods(); + for (int i = 0; i < methods.length; i++) { + addClassInUse(methods[i].getReturnType()); + addStubInUse(methods[i].getReturnType()); + addClassInUse(methods[i].getArguments()); + addStubInUse(methods[i].getArguments()); + addClassInUse(methods[i].getExceptions()); + // bug 4473859: Also include narrower subtypes for use + addClassInUse(methods[i].getImplExceptions()); + } + + // If this is a stub, add all interfaces... + + if (interfaces != null) { + addClassInUse(interfaces); + } + } + + private void writePackageAndImports(IndentingWriter p) throws IOException { + + // Write package declaration... + + if (currentPackage != null) { + p.pln("package " + + Util.correctPackageName( + currentPackage, false, standardPackage) + + ";"); + p.pln(); + } + + // Get imports into an array and sort them... + + String[] names = new String[importCount]; + int index = 0; + for (Enumeration e = imports.elements() ; e.hasMoreElements() ;) { + String it = (String) e.nextElement(); + if (it != NO_IMPORT) { + names[index++] = it; + } + } + + Arrays.sort(names,new StringComparator()); + + // Now dump them out... + + for (int i = 0; i < importCount; i++) { + if( + Util.isOffendingPackage(names[i]) + && names[i].endsWith("_Stub") + && String.valueOf(names[i].charAt(names[i].lastIndexOf(".")+1)).equals("_") + ){ + p.pln("import " + PackagePrefixChecker.packagePrefix()+names[i]+";"); + } else{ + p.pln("import " + names[i] + ";"); + } + } + p.pln(); + + // Include offending packages . . . + if ( currentPackage!=null && Util.isOffendingPackage(currentPackage) ){ + p.pln("import " + currentPackage +".* ;"); + } + p.pln(); + + } + + private boolean implementsRemote(CompoundType theType) { + boolean result = theType.isType(TYPE_REMOTE) && !theType.isType(TYPE_ABSTRACT); + + // If theType is not remote, look at all the interfaces + // until we find one that is... + + if (!result) { + InterfaceType[] interfaces = theType.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + result = implementsRemote(interfaces[i]); + if (result) { + break; + } + } + } + + return result; + } + + private void writeStubMethod(IndentingWriter p, + CompoundType.Method method, + CompoundType theType) throws IOException { + + // Wtite the method declaration and opening brace... + String methodName = method.getName(); + String methodIDLName = method.getIDLName(); + + Type paramTypes[] = method.getArguments(); + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getStubExceptions(method,false); + boolean hasIOException = false; + + addNamesInUse(method); + addNameInUse("_type_ids"); + + String objName = testUtil(getName(returnType), returnType); + p.p("public " + objName + " " + methodName + "("); + for(int i = 0; i < paramTypes.length; i++) { + if (i > 0) + p.p(", "); + p.p(getName(paramTypes[i]) + " " + paramNames[i]); + } + + p.p(")"); + if (exceptions.length > 0) { + p.p(" throws "); + for(int i = 0; i < exceptions.length; i++) { + if (i > 0) { + p.p(", "); + } + // Added for Bug 4818753 + p.p(getExceptionName(exceptions[i])); + } + } + + p.plnI(" {"); + + // Now create the method body... + if (emitPermissionCheck) { + p.pln("if ((System.getSecurityManager() != null) && (!_instantiated)) {"); + p.plnI(" throw new java.io.IOError(new java.io.IOException(\"InvalidObject \"));"); + p.pOln("}"); + p.pln(); + } + + + if (localStubs) { + writeLocalStubMethodBody(p,method,theType); + } else { + writeNonLocalStubMethodBody(p,method,theType); + } + + // Close out the method... + + p.pOln("}"); + } + + + void writeLocalStubMethodBody (IndentingWriter p, + CompoundType.Method method, + CompoundType theType) throws IOException { + + String objName; + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getStubExceptions(method,false); + String methodName = method.getName(); + String methodIDLName = method.getIDLName(); + + p.plnI("if (!Util.isLocal(this)) {"); + writeNonLocalStubMethodBody(p,method,theType); + p.pOlnI("} else {"); + String so = getVariableName("so"); + + p.pln("ServantObject "+so+" = _servant_preinvoke(\""+methodIDLName+"\","+getName(theType)+".class);"); + p.plnI("if ("+so+" == null) {"); + if (!returnType.isType(TYPE_VOID)) { + p.p("return "); + } + p.p(methodName+"("); + for (int i = 0; i < paramNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(paramNames[i]); + } + p.pln(");"); + if (returnType.isType(TYPE_VOID)) { + p.pln( "return ;" ) ; + } + + p.pOln("}"); + p.plnI("try {"); + + // Generate code to copy required arguments, and + // get back the names by which all arguments are known... + + String[] argNames = writeCopyArguments(method,p); + + // Now write the method... + + boolean copyReturn = mustCopy(returnType); + String resultName = null; + if (!returnType.isType(TYPE_VOID)) { + if (copyReturn) { + resultName = getVariableName("result"); + objName = testUtil(getName(returnType), returnType); + p.p(objName+" "+resultName + " = "); + } else { + p.p("return "); + } + } + objName = testUtil(getName(theType), theType); + p.p("(("+objName+")"+so+".servant)."+methodName+"("); + + for (int i = 0; i < argNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(argNames[i]); + } + + if (copyReturn) { + p.pln(");"); + objName = testUtil(getName(returnType), returnType); + p.pln("return ("+objName+")Util.copyObject("+resultName+",_orb());"); + } else { + p.pln(");"); + } + + String e1 = getVariableName("ex"); + String e2 = getVariableName("exCopy"); + p.pOlnI("} catch (Throwable "+e1+") {"); + + p.pln("Throwable "+e2+" = (Throwable)Util.copyObject("+e1+",_orb());"); + for(int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getIdentifier() != idRemoteException && + exceptions[i].isType(TYPE_VALUE)) { + // Added for Bug 4818753 + p.plnI("if ("+e2+" instanceof "+getExceptionName(exceptions[i])+") {"); + p.pln("throw ("+getExceptionName(exceptions[i])+")"+e2+";"); + p.pOln("}"); + } + } + + p.pln("throw Util.wrapException("+e2+");"); + p.pOlnI("} finally {"); + p.pln("_servant_postinvoke("+so+");"); + p.pOln("}"); + p.pOln("}"); + } + + + void writeNonLocalStubMethodBody ( IndentingWriter p, + CompoundType.Method method, + CompoundType theType) throws IOException { + + String methodName = method.getName(); + String methodIDLName = method.getIDLName(); + + Type paramTypes[] = method.getArguments(); + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getStubExceptions(method,true); + + String in = getVariableName("in"); + String out = getVariableName("out"); + String ex = getVariableName("ex"); + + // Decide if we need to use the new streams for + // any of the read calls... + + boolean needNewReadStreamClass = false; + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getIdentifier() != idRemoteException && + exceptions[i].isType(TYPE_VALUE) && + needNewReadStreamClass(exceptions[i])) { + needNewReadStreamClass = true; + break; + } + } + if (!needNewReadStreamClass) { + for (int i = 0; i < paramTypes.length; i++) { + if (needNewReadStreamClass(paramTypes[i])) { + needNewReadStreamClass = true; + break; + } + } + } + if (!needNewReadStreamClass) { + needNewReadStreamClass = needNewReadStreamClass(returnType); + } + + // Decide if we need to use the new streams for + // any of the write calls... + + boolean needNewWriteStreamClass = false; + for (int i = 0; i < paramTypes.length; i++) { + if (needNewWriteStreamClass(paramTypes[i])) { + needNewWriteStreamClass = true; + break; + } + } + + // Now write the method, inserting casts where needed... + + p.plnI("try {"); + if (needNewReadStreamClass) { + p.pln(idExtInputStream + " "+in+" = null;"); + } else { + p.pln(idInputStream + " "+in+" = null;"); + } + p.plnI("try {"); + + String argStream = "null"; + + if (needNewWriteStreamClass) { + p.plnI(idExtOutputStream + " "+out+" = "); + p.pln("(" + idExtOutputStream + ")"); + p.pln("_request(\"" + methodIDLName + "\", true);"); + p.pO(); + } else { + p.pln("OutputStream "+out+" = _request(\"" + methodIDLName + "\", true);"); + } + + if (paramTypes.length > 0) { + writeMarshalArguments(p, out, paramTypes, paramNames); + p.pln(); + } + argStream = out; + + if (returnType.isType(TYPE_VOID)) { + p.pln("_invoke(" + argStream + ");" ); + } else { + if (needNewReadStreamClass) { + p.plnI(in+" = (" + idExtInputStream + ")_invoke(" + argStream + ");"); + p.pO(); + } else { + p.pln(in+" = _invoke(" + argStream + ");"); + } + p.p("return "); + writeUnmarshalArgument(p, in, returnType, null); + p.pln(); + } + + // Handle ApplicationException... + + p.pOlnI("} catch ("+getName(idApplicationException)+" "+ex+") {"); + if (needNewReadStreamClass) { + p.pln(in + " = (" + idExtInputStream + ") "+ex+".getInputStream();"); + } else { + p.pln(in + " = "+ex+".getInputStream();"); + } + + boolean idRead = false; + boolean idAllocated = false; + for(int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getIdentifier() != idRemoteException) { + + // Is this our special-case IDLEntity exception? + + if (exceptions[i].isIDLEntityException() && !exceptions[i].isCORBAUserException()) { + + // Yes. + + if (!idAllocated && !idRead) { + p.pln("String $_id = "+ex+".getId();"); + idAllocated = true; + } + + String helperName = IDLNames.replace(exceptions[i].getQualifiedIDLName(false),"::","."); + helperName += "Helper"; + p.plnI("if ($_id.equals("+helperName+".id())) {"); + p.pln("throw "+helperName+".read("+in+");"); + + } else { + + // No. + + if (!idAllocated && !idRead) { + p.pln("String $_id = "+in+".read_string();"); + idAllocated = true; + idRead = true; + } else if (idAllocated && !idRead) { + p.pln("$_id = "+in+".read_string();"); + idRead = true; + } + p.plnI("if ($_id.equals(\""+getExceptionRepositoryID(exceptions[i])+"\")) {"); + // Added for Bug 4818753 + p.pln("throw ("+getExceptionName(exceptions[i])+") "+in+".read_value(" + getExceptionName(exceptions[i]) + ".class);"); + } + p.pOln("}"); + } + } + if (!idAllocated && !idRead) { + p.pln("String $_id = "+in+".read_string();"); + idAllocated = true; + idRead = true; + } else if (idAllocated && !idRead) { + p.pln("$_id = "+in+".read_string();"); + idRead = true; + } + p.pln("throw new UnexpectedException($_id);"); + + // Handle RemarshalException... + + p.pOlnI("} catch ("+getName(idRemarshalException)+" "+ex+") {"); + if (!returnType.isType(TYPE_VOID)) { + p.p("return "); + } + p.p(methodName + "("); + for(int i = 0; i < paramTypes.length; i++) { + if (i > 0) { + p.p(","); + } + p.p(paramNames[i]); + } + p.pln(");"); + + // Ensure that we release the reply... + + p.pOlnI("} finally {"); + p.pln("_releaseReply("+in+");"); + + p.pOln("}"); + + // Handle SystemException... + + p.pOlnI("} catch (SystemException "+ex+") {"); + p.pln("throw Util.mapSystemException("+ex+");"); + p.pOln("}"); + + // returnResult(p,returnType); + } + + void allocateResult (IndentingWriter p, + Type returnType) throws IOException { + if (!returnType.isType(TYPE_VOID)) { + String objName = testUtil(getName(returnType), returnType); + p.p(objName + " result = "); + } + } + + int getTypeCode(Type type) { + + int typeCode = type.getTypeCode(); + + // Handle late-breaking special case for + // abstract IDL entities... + + if ((type instanceof CompoundType) && + ((CompoundType)type).isAbstractBase()) { + typeCode = TYPE_ABSTRACT; + } + + return typeCode; + } + + + /** + * Write a snippet of Java code to marshal a value named "name" of + * type "type" to the java.io.ObjectOutput stream named "stream". + */ + void writeMarshalArgument(IndentingWriter p, + String streamName, + Type type, String name) throws IOException { + + int typeCode = getTypeCode(type); + + switch (typeCode) { + case TYPE_BOOLEAN: + p.p(streamName + ".write_boolean(" + name + ");"); + break; + case TYPE_BYTE: + p.p(streamName + ".write_octet(" + name + ");"); + break; + case TYPE_CHAR: + p.p(streamName + ".write_wchar(" + name + ");"); + break; + case TYPE_SHORT: + p.p(streamName + ".write_short(" + name + ");"); + break; + case TYPE_INT: + p.p(streamName + ".write_long(" + name + ");"); + break; + case TYPE_LONG: + p.p(streamName + ".write_longlong(" + name + ");"); + break; + case TYPE_FLOAT: + p.p(streamName + ".write_float(" + name + ");"); + break; + case TYPE_DOUBLE: + p.p(streamName + ".write_double(" + name + ");"); + break; + case TYPE_STRING: + p.p(streamName + ".write_value(" + name + "," + getName(type) + ".class);"); + break; + case TYPE_ANY: + p.p("Util.writeAny("+ streamName + "," + name + ");"); + break; + case TYPE_CORBA_OBJECT: + p.p(streamName + ".write_Object(" + name + ");"); + break; + case TYPE_REMOTE: + p.p("Util.writeRemoteObject("+ streamName + "," + name + ");"); + break; + case TYPE_ABSTRACT: + p.p("Util.writeAbstractObject("+ streamName + "," + name + ");"); + break; + case TYPE_NC_INTERFACE: + p.p(streamName + ".write_value((Serializable)" + name + "," + getName(type) + ".class);"); + break; + case TYPE_VALUE: + p.p(streamName + ".write_value(" + name + "," + getName(type) + ".class);"); + break; + case TYPE_IMPLEMENTATION: + p.p(streamName + ".write_value((Serializable)" + name + "," + getName(type) + ".class);"); + break; + case TYPE_NC_CLASS: + p.p(streamName + ".write_value((Serializable)" + name + "," + getName(type) + ".class);"); + break; + case TYPE_ARRAY: + castArray = true; + p.p(streamName + ".write_value(cast_array(" + name + ")," + getName(type) + ".class);"); + break; + case TYPE_JAVA_RMI_REMOTE: + p.p("Util.writeRemoteObject("+ streamName + "," + name + ");"); + break; + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Write a snippet of Java code to unmarshal a value of type "type" + * from the java.io.ObjectInput stream named "stream" into a variable + * named "name" (if "name" is null, the value in unmarshalled and + * discarded). + */ + void writeUnmarshalArgument(IndentingWriter p, + String streamName, + Type type, + String name) throws IOException { + + int typeCode = getTypeCode(type); + + if (name != null) { + p.p(name + " = "); + } + + switch (typeCode) { + case TYPE_BOOLEAN: + p.p(streamName + ".read_boolean();"); + break; + case TYPE_BYTE: + p.p(streamName + ".read_octet();"); + break; + case TYPE_CHAR: + p.p(streamName + ".read_wchar();"); + break; + case TYPE_SHORT: + p.p(streamName + ".read_short();"); + break; + case TYPE_INT: + p.p(streamName + ".read_long();"); + break; + case TYPE_LONG: + p.p(streamName + ".read_longlong();"); + break; + case TYPE_FLOAT: + p.p(streamName + ".read_float();"); + break; + case TYPE_DOUBLE: + p.p(streamName + ".read_double();"); + break; + case TYPE_STRING: + p.p("(String) " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_ANY: + if (type.getIdentifier() != idJavaLangObject) { + p.p("(" + getName(type) + ") "); + } + p.p("Util.readAny(" + streamName + ");"); + break; + case TYPE_CORBA_OBJECT: + if (type.getIdentifier() == idCorbaObject) { + p.p("(" + getName(type) + ") " + streamName + ".read_Object();"); + } else { + p.p("(" + getName(type) + ") " + streamName + ".read_Object(" + getStubName(type) + ".class);"); + } + break; + case TYPE_REMOTE: + String objName = testUtil(getName(type), type); + p.p("(" + objName + ") " + + "PortableRemoteObject.narrow(" + streamName + ".read_Object(), " + objName + ".class);"); + break; + case TYPE_ABSTRACT: + p.p("(" + getName(type) + ") " + streamName + ".read_abstract_interface();"); + break; + case TYPE_NC_INTERFACE: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_VALUE: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_IMPLEMENTATION: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_NC_CLASS: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_ARRAY: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_JAVA_RMI_REMOTE: + p.p("(" + getName(type) + ") " + + "PortableRemoteObject.narrow(" + streamName + ".read_Object(), " + getName(type) + ".class);"); + // p.p("(" + getName(type) + ") " + streamName + ".read_Object(" + getStubName(type) + ".class);"); + break; + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Get a list of all the RepositoryIDs for interfaces + * implemented directly or indirectly by theType. In the + * case of an ImplementationType which implements 2 or + * more remote interfaces, this list will begin with the + * Identifier for the implementation (see section 5.9 in + * the Java -> IDL mapping). Ensures that the most derived + * type is first in the list because the IOR is generated + * using that entry in the _ids array. + */ + String[] getAllRemoteRepIDs (CompoundType theType) { + + String[] result; + + // Collect up all the (inherited) remote interfaces + // (ignores all the 'special' interfaces: Remote, + // Serializable, Externalizable)... + + Type[] types = collectAllRemoteInterfaces(theType); + + int length = types.length; + boolean haveImpl = theType instanceof ImplementationType; + InterfaceType[] interfaces = theType.getInterfaces(); + int remoteCount = countRemote(interfaces,false); + int offset = 0; + + // Do we have an implementation type that implements + // more than one remote interface? + + if (haveImpl && remoteCount > 1) { + + // Yes, so we need to insert it at the beginning... + + result = new String[length + 1]; + result[0] = getRepositoryID(theType); + offset = 1; + + } else { + + // No. + + result = new String[length]; + + // Here we need to ensure that the most derived + // interface ends up being first in the list. If + // there is only one, we're done. + + if (length > 1) { + + // First, decide what the most derived type is... + + String mostDerived = null; + + if (haveImpl) { + + // If we get here, we know that there is only one + // direct remote interface, so just find it... + + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i].isType(TYPE_REMOTE)) { + mostDerived = interfaces[i].getRepositoryID(); + break; + } + } + } else { + + // If we get here we know that theType is a RemoteType + // so just use its id... + + mostDerived = theType.getRepositoryID(); + } + + // Now search types list and make sure mostDerived is + // at index zero... + + for (int i = 0; i < length; i++) { + if (types[i].getRepositoryID() == mostDerived) { + + // Found it. Swap it if we need to... + + if (i > 0) { + Type temp = types[0]; + types[0] = types[i]; + types[i] = temp; + } + + break; + } + } + } + } + + // Now copy contents of the types array... + + for (int i = 0; i < types.length; i++) { + result[offset++] = getRepositoryID(types[i]); + } + + // If we're supposed to, reverse the array. This + // is only done when the -testReverseIDs flag is + // passed, and that should ONLY be done for test + // cases. This is an undocumented feature. + + if (reverseIDs) { + int start = 0; + int end = result.length -1; + while (start < end) { + String temp = result[start]; + result[start++] = result[end]; + result[end--] = temp; + } + } + + return result; + } + + /** + * Collect all the inherited remote interfaces. + */ + Type[] collectAllRemoteInterfaces (CompoundType theType) { + Vector list = new Vector(); + + // Collect up all the Remote interfaces, and get an instance + // for java.rmi.Remote... + + addRemoteInterfaces(list,theType); + + // Create and return our results... + + Type[] result = new Type[list.size()]; + list.copyInto(result); + + return result; + } + + /** + * Add all the inherited remote interfaces to list. + */ + void addRemoteInterfaces(Vector list, CompoundType theType) { + + if (theType != null) { + if (theType.isInterface() && !list.contains(theType)) { + list.addElement(theType); + } + + InterfaceType[] interfaces = theType.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + + if (interfaces[i].isType(TYPE_REMOTE)) { + addRemoteInterfaces(list,interfaces[i]); + } + } + + addRemoteInterfaces(list,theType.getSuperclass()); + } + } + + /** + * Get a list of all the remote interfaces which this stub + * should declare. + */ + RemoteType[] getDirectRemoteInterfaces (CompoundType theType) { + + RemoteType[] result; + InterfaceType[] interfaces = theType.getInterfaces(); + + // First, get a list of all the interfaces... + + InterfaceType[] list; + + // Because we can be passed either an ImplementationType + // (which has interfaces) or a RemoteType (which is an + // interface and may have interfaces) we must handle each + // separately... + + // Do we have an implementation type? + + if (theType instanceof ImplementationType) { + + // Yes, so list is exactly what this type + // implements and is correct already. + + list = interfaces; + + } else { + + // No, so list is just theType... + + list = new InterfaceType[1]; + list[0] = (InterfaceType) theType; + } + + // Ok, now count up the remote interfaces, allocate + // our result and fill it in... + + int remoteCount = countRemote(list,false); + + if (remoteCount == 0) { + throw new CompilerError("iiop.StubGenerator: No remote interfaces!"); + } + + result = new RemoteType[remoteCount]; + int offset = 0; + for (int i = 0; i < list.length; i++) { + if (list[i].isType(TYPE_REMOTE)) { + result[offset++] = (RemoteType)list[i]; + } + } + + return result; + } + + int countRemote (Type[] list, boolean includeAbstract) { + int remoteCount = 0; + for (int i = 0; i < list.length; i++) { + if (list[i].isType(TYPE_REMOTE) && + (includeAbstract || !list[i].isType(TYPE_ABSTRACT))) { + remoteCount++; + } + } + + return remoteCount; + } + + void writeCastArray(IndentingWriter p) throws IOException { + if (castArray) { + p.pln(); + p.pln("// This method is required as a work-around for"); + p.pln("// a bug in the JDK 1.1.6 verifier."); + p.pln(); + p.plnI("private "+getName(idJavaIoSerializable)+" cast_array(Object obj) {"); + p.pln("return ("+getName(idJavaIoSerializable)+")obj;"); + p.pOln("}"); + } + } + void writeIds(IndentingWriter p, CompoundType theType, boolean isTie + ) throws IOException { + p.plnI("private static final String[] _type_ids = {"); + + String[] ids = getAllRemoteRepIDs(theType); + + if (ids.length >0 ) { + for(int i = 0; i < ids.length; i++) { + if (i > 0) + p.pln(", "); + p.p("\"" + ids[i] + "\""); + } + } else { + // Must be an implementation which only implements Remote... + p.pln("\"\""); + } + String qname = theType.getQualifiedName() ; + boolean isTransactional = isTie && transactionalObjects.containsKey( qname ) ; + // Add TransactionalObject if needed. + if (isTransactional) { + // Have already written an id. + p.pln( ", " ) ; + p.pln( "\"IDL:omg.org/CosTransactions/TransactionalObject:1.0\"" ) ; + } else if (ids.length > 0) { + p.pln(); + } + p.pOln("};"); + } + + + /** + * Write the Tie for the remote class to a stream. + */ + protected void writeTie(OutputType outputType, + IndentingWriter p) throws IOException + { + CompoundType theType = (CompoundType) outputType.getType(); + RemoteType[] remoteInterfaces = null; + + // Write comment... + p.pln("// Tie class generated by rmic, do not edit."); + p.pln("// Contents subject to change without notice."); + p.pln(); + + // Set our standard classes... + setStandardClassesInUse(theType,false); + + // Add classes for this type... + addClassesInUse(theType,remoteInterfaces); + + // Write package and import statements... + writePackageAndImports(p); + + // Declare the tie class. + p.p("public class " + currentClass + " extends " + + getName(tieBaseClass) + " implements Tie"); + + // Add java.rmi.Remote if this type does not implement it. + // This allows stubs for Abstract interfaces to be treated + // uniformly... + if (!implementsRemote(theType)) { + p.pln(","); + p.p(getName("java.rmi.Remote")); + } + + p.plnI(" {"); + + // Write data members... + p.pln(); + p.pln("volatile private " + getName(theType) + " target = null;"); + p.pln(); + + // Write the ids... + writeIds( p, theType, true ) ; + + // Write setTarget method... + p.pln(); + p.plnI("public void setTarget(Remote target) {"); + p.pln("this.target = (" + getName(theType) + ") target;"); + p.pOln("}"); + + // Write getTarget method... + p.pln(); + p.plnI("public Remote getTarget() {"); + p.pln("return target;"); + p.pOln("}"); + + // Write thisObject method... + p.pln(); + write_tie_thisObject_method(p,idCorbaObject); + + // Write deactivate method... + p.pln(); + write_tie_deactivate_method(p); + + // Write get orb method... + p.pln(); + p.plnI("public ORB orb() {"); + p.pln("return _orb();"); + p.pOln("}"); + + // Write set orb method... + p.pln(); + write_tie_orb_method(p); + + // Write the _ids() method... + p.pln(); + write_tie__ids_method(p); + + // Get all the methods... + CompoundType.Method[] remoteMethods = theType.getMethods(); + + // Register all the argument names used, plus our + // data member names... + + addNamesInUse(remoteMethods); + addNameInUse("target"); + addNameInUse("_type_ids"); + + // Write the _invoke method... + p.pln(); + + String in = getVariableName("in"); + String _in = getVariableName("_in"); + String ex = getVariableName("ex"); + String method = getVariableName("method"); + String reply = getVariableName("reply"); + + p.plnI("public OutputStream _invoke(String "+method+", InputStream "+_in+", " + + "ResponseHandler "+reply+") throws SystemException {"); + + if (remoteMethods.length > 0) { + p.plnI("try {"); + p.pln(getName(theType) + " target = this.target;"); + p.plnI("if (target == null) {"); + p.pln("throw new java.io.IOException();"); + p.pOln("}"); + p.plnI(idExtInputStream + " "+in+" = "); + p.pln("(" + idExtInputStream + ") "+_in+";"); + p.pO(); + + // See if we should use a hash table style + // comparison... + + StaticStringsHash hash = getStringsHash(remoteMethods); + + if (hash != null) { + p.plnI("switch ("+method+"."+hash.method+") {"); + for (int i = 0; i < hash.buckets.length; i++) { + p.plnI("case "+hash.keys[i]+": "); + for (int j = 0; j < hash.buckets[i].length; j++) { + CompoundType.Method current = remoteMethods[hash.buckets[i][j]]; + if (j > 0) { + p.pO("} else "); + } + p.plnI("if ("+method+".equals(\""+ current.getIDLName() +"\")) {"); + writeTieMethod(p, theType,current); + } + p.pOln("}"); + p.pO(); + } + } else { + for(int i = 0; i < remoteMethods.length; i++) { + CompoundType.Method current = remoteMethods[i]; + if (i > 0) { + p.pO("} else "); + } + + p.plnI("if ("+method+".equals(\""+ current.getIDLName() +"\")) {"); + writeTieMethod(p, theType, current); + } + } + + if (hash != null) { + p.pI(); + // p.plnI("default:"); + } else { + // p.pOlnI("} else {"); + } + // p.pln("throw new "+getName(idBadMethodException)+"();"); + + if (hash != null) { + p.pO(); + } + p.pOln("}"); + p.pln("throw new "+getName(idBadMethodException)+"();"); + + p.pOlnI("} catch ("+getName(idSystemException)+" "+ex+") {"); + p.pln("throw "+ex+";"); + + p.pOlnI("} catch ("+getName(idJavaLangThrowable)+" "+ex+") {"); + p.pln("throw new " + getName(idPortableUnknownException) + "("+ex+");"); + p.pOln("}"); + } else { + // No methods... + + p.pln("throw new " + getName(idBadMethodException) + "();"); + } + + p.pOln("}"); // end invoke + + // Write the cast array hack... + + writeCastArray(p); + + // End tie class... + p.pOln("}"); + } + public void catchWrongPolicy(IndentingWriter p) throws IOException { + p.pln(""); + } + public void catchServantNotActive(IndentingWriter p) throws IOException { + p.pln(""); + } + public void catchObjectNotActive(IndentingWriter p) throws IOException { + p.pln(""); + } + + public void write_tie_thisObject_method(IndentingWriter p, + Identifier idCorbaObject) + throws IOException + { + if(POATie){ + p.plnI("public " + idCorbaObject + " thisObject() {"); + /* + p.pln("org.omg.CORBA.Object objref = null;"); + p.pln("try{"); + p.pln("objref = _poa().servant_to_reference(this);"); + p.pln("}catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){"); + catchWrongPolicy(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){"); + catchServantNotActive(p); + p.pln("}"); + p.pln("return objref;"); + */ + p.pln("return _this_object();"); + p.pOln("}"); + } else { + p.plnI("public " + idCorbaObject + " thisObject() {"); + p.pln("return this;"); + p.pOln("}"); + } + } + + public void write_tie_deactivate_method(IndentingWriter p) + throws IOException + { + if(POATie){ + p.plnI("public void deactivate() {"); + p.pln("try{"); + p.pln("_poa().deactivate_object(_poa().servant_to_id(this));"); + p.pln("}catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){"); + catchWrongPolicy(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){"); + catchObjectNotActive(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){"); + catchServantNotActive(p); + p.pln("}"); + p.pOln("}"); + } else { + p.plnI("public void deactivate() {"); + p.pln("_orb().disconnect(this);"); + p.pln("_set_delegate(null);"); + p.pln("target = null;"); + p.pOln("}"); + } + } + + public void write_tie_orb_method(IndentingWriter p) + throws IOException + { + if(POATie){ + p.plnI("public void orb(ORB orb) {"); + /* + p.pln("try{"); + p.pln("orb.connect(_poa().servant_to_reference(this));"); + p.pln("}catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){"); + catchWrongPolicy(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){"); + catchServantNotActive(p); + p.pln("}"); + */ + p.pln("try {"); + p.pln(" ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this);"); + p.pln("}"); + p.pln("catch(ClassCastException e) {"); + p.pln(" throw new org.omg.CORBA.BAD_PARAM"); + p.pln(" (\"POA Servant requires an instance of org.omg.CORBA_2_3.ORB\");"); + p.pln("}"); + p.pOln("}"); + } else { + p.plnI("public void orb(ORB orb) {"); + p.pln("orb.connect(this);"); + p.pOln("}"); + } + } + + public void write_tie__ids_method(IndentingWriter p) + throws IOException + { + if(POATie){ + p.plnI("public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){"); + p.pln("return (String[]) _type_ids.clone();"); + p.pOln("}"); + } else { + p.plnI("public String[] _ids() { "); + p.pln("return (String[]) _type_ids.clone();"); + p.pOln("}"); + } + } + + + StaticStringsHash getStringsHash (CompoundType.Method[] methods) { + if (useHash && methods.length > 1) { + String[] methodNames = new String[methods.length]; + for (int i = 0; i < methodNames.length; i++) { + methodNames[i] = methods[i].getIDLName(); + } + return new StaticStringsHash(methodNames); + } + return null; + } + + static boolean needNewReadStreamClass(Type type) { + if (type.isType(TYPE_ABSTRACT)) { + return true; + } + // Handle late-breaking special case for + // abstract IDL entities... + if ((type instanceof CompoundType) && + ((CompoundType)type).isAbstractBase()) { + return true; + } + return needNewWriteStreamClass(type); + } + + static boolean needNewWriteStreamClass(Type type) { + switch (type.getTypeCode()) { + case TYPE_VOID: + case TYPE_BOOLEAN: + case TYPE_BYTE: + case TYPE_CHAR: + case TYPE_SHORT: + case TYPE_INT: + case TYPE_LONG: + case TYPE_FLOAT: + case TYPE_DOUBLE: return false; + + case TYPE_STRING: return true; + case TYPE_ANY: return false; + case TYPE_CORBA_OBJECT: return false; + case TYPE_REMOTE: return false; + case TYPE_ABSTRACT: return false; + case TYPE_NC_INTERFACE: return true; + case TYPE_VALUE: return true; + case TYPE_IMPLEMENTATION: return true; + case TYPE_NC_CLASS: return true; + case TYPE_ARRAY: return true; + case TYPE_JAVA_RMI_REMOTE: return false; + + default: throw new Error("unexpected type code: " + type.getTypeCode()); + } + } + + /* + * Decide which arguments need to be copied and write + * the copy code. Returns an array of argument names to + * use to refer to either the copy or the original. + */ + String[] writeCopyArguments(CompoundType.Method method, + IndentingWriter p) throws IOException { + + Type[] args = method.getArguments(); + String[] origNames = method.getArgumentNames(); + + // Copy the current parameter names to a result array... + + String[] result = new String[origNames.length]; + for (int i = 0; i < result.length; i++) { + result[i] = origNames[i]; + } + + // Decide which arguments must be copied, if any. If + // any of the arguments are types for which a 'real' copy + // will be done, rather than just an autoConnect, set + // realCopy = true. Note that abstract types may only + // need autoConnect, but we cannot know that at compile + // time... + + boolean realCopy = false; + boolean[] copyArg = new boolean[args.length]; + int copyCount = 0; + int firstCopiedArg = 0; // Only used in single copy case. It is only the first arg that + // needs copying IF copyCount == 1. + + for (int i = 0; i < args.length; i++) { + if (mustCopy(args[i])) { + copyArg[i] = true; + copyCount++; + firstCopiedArg = i; + if (args[i].getTypeCode() != TYPE_REMOTE && + args[i].getTypeCode() != TYPE_IMPLEMENTATION) { + realCopy = true; + } + } else { + copyArg[i] = false; + } + } + + // Do we have any types which must be copied? + if (copyCount > 0) { + // Yes. Are we only doing the copy to ensure + // that autoConnect occurs? + if (realCopy) { + // Nope. We need to go back thru the list and + // mark any strings so that they will be copied + // to preserve any shared references... + for (int i = 0; i < args.length; i++) { + if (args[i].getTypeCode() == TYPE_STRING) { + copyArg[i] = true; + copyCount++; + } + } + } + + // We're ready to generate code. Do we have more than + // one to copy? + if (copyCount > 1) { + // Generate a call to copyObjects... + String arrayName = getVariableName("copies"); + p.p("Object[] " + arrayName + " = Util.copyObjects(new Object[]{"); + boolean first = true; + for (int i = 0; i < args.length; i++) { + if (copyArg[i]) { + if (!first) { + p.p(","); + } + first = false; + p.p(origNames[i]); + } + } + p.pln("},_orb());"); + + // For each of the types which was copied, create + // a local temporary for it, updating the result + // array with the new local parameter name... + int copyIndex = 0 ; + for (int i = 0; i < args.length; i++) { + if (copyArg[i]) { + result[i] = getVariableName(result[i]+"Copy"); + p.pln( getName(args[i]) + " " + result[i] + " = (" + getName(args[i]) + ") " + + arrayName + "[" + copyIndex++ +"];"); + } + } + } else { + // Generate a call to copyObject, updating the result + // with the new local parameter name... + result[firstCopiedArg] = getVariableName(result[firstCopiedArg]+"Copy"); + p.pln( getName(args[firstCopiedArg]) + " " + result[firstCopiedArg] + " = (" + + getName(args[firstCopiedArg]) + ") Util.copyObject(" + + origNames[firstCopiedArg] + ",_orb());"); + } + } + + return result; + } + + static final String SINGLE_SLASH = "\\"; + static final String DOUBLE_SLASH = SINGLE_SLASH + SINGLE_SLASH; + + String getRepositoryID(Type type) { + return IDLNames.replace(type.getRepositoryID(), SINGLE_SLASH, DOUBLE_SLASH); + } + + String getExceptionRepositoryID(Type type) { + ClassType theType = (ClassType) type; + return IDLNames.getIDLRepositoryID(theType.getQualifiedIDLExceptionName(false)); + } + + String getVariableName(String proposed) { + while (namesInUse.contains(proposed)) { + proposed = "$" + proposed; + } + + return proposed; + } + + void addNamesInUse(CompoundType.Method[] methods) { + for (int i = 0; i < methods.length; i++) { + addNamesInUse(methods[i]); + } + } + + void addNamesInUse(CompoundType.Method method) { + String paramNames[] = method.getArgumentNames(); + for (int i = 0; i < paramNames.length; i++) { + addNameInUse(paramNames[i]); + } + } + + void addNameInUse(String name) { + namesInUse.add(name); + } + + static boolean mustCopy(Type type) { + switch (type.getTypeCode()) { + case TYPE_VOID: + case TYPE_BOOLEAN: + case TYPE_BYTE: + case TYPE_CHAR: + case TYPE_SHORT: + case TYPE_INT: + case TYPE_LONG: + case TYPE_FLOAT: + case TYPE_DOUBLE: + case TYPE_STRING: return false; + + case TYPE_ANY: return true; + + case TYPE_CORBA_OBJECT: return false; + + case TYPE_REMOTE: + case TYPE_ABSTRACT: + case TYPE_NC_INTERFACE: + case TYPE_VALUE: + case TYPE_IMPLEMENTATION: + case TYPE_NC_CLASS: + case TYPE_ARRAY: + case TYPE_JAVA_RMI_REMOTE: return true; + + default: throw new Error("unexpected type code: " + type.getTypeCode()); + } + } + + ValueType[] getStubExceptions (CompoundType.Method method, boolean sort) { + + ValueType[] list = method.getFilteredStubExceptions(method.getExceptions()); + + // Sort the list so that all org.omg.CORBA.UserException + // subtypes are at the beginning of the list. This ensures + // that the stub will not call read_string() before calling + // XXHelper.read(). + + if (sort) { + Arrays.sort(list,new UserExceptionComparator()); + } + + return list; + } + + ValueType[] getTieExceptions (CompoundType.Method method) { + return method.getUniqueCatchList(method.getImplExceptions()); + } + + void writeTieMethod(IndentingWriter p, CompoundType type, + CompoundType.Method method) throws IOException { + String methodName = method.getName(); + Type paramTypes[] = method.getArguments(); + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getTieExceptions(method); + String in = getVariableName("in"); + String ex = getVariableName("ex"); + String out = getVariableName("out"); + String reply = getVariableName("reply"); + + for (int i = 0; i < paramTypes.length; i++) { + p.p(getName(paramTypes[i])+" "+paramNames[i]+" = "); + writeUnmarshalArgument(p, in, paramTypes[i], null); + p.pln(); + } + + boolean handleExceptions = exceptions != null; + boolean doReturn = !returnType.isType(TYPE_VOID); + + if (handleExceptions && doReturn) { + String objName = testUtil(getName(returnType), returnType); + p.pln(objName+" result;"); + } + + if (handleExceptions) + p.plnI("try {"); + + if (doReturn) { + if (handleExceptions) { + p.p("result = "); + } else { + p.p(getName(returnType)+" result = "); + } + } + + p.p("target."+methodName+"("); + for(int i = 0; i < paramNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(paramNames[i]); + } + p.pln(");"); + + if (handleExceptions) { + for(int i = 0; i < exceptions.length; i++) { + p.pOlnI("} catch ("+getName(exceptions[i])+" "+ex+") {"); + + // Is this our IDLEntity Exception special case? + + if (exceptions[i].isIDLEntityException() && !exceptions[i].isCORBAUserException()) { + + // Yes... + + String helperName = IDLNames.replace(exceptions[i].getQualifiedIDLName(false),"::","."); + helperName += "Helper"; + p.pln(idOutputStream+" "+out +" = "+reply+".createExceptionReply();"); + p.pln(helperName+".write("+out+","+ex+");"); + + } else { + + // No... + + p.pln("String id = \"" + getExceptionRepositoryID(exceptions[i]) + "\";"); + p.plnI(idExtOutputStream + " "+out+" = "); + p.pln("(" + idExtOutputStream + ") "+reply+".createExceptionReply();"); + p.pOln(out+".write_string(id);"); + p.pln(out+".write_value("+ex+"," + getName(exceptions[i]) + ".class);"); + } + + p.pln("return "+out+";"); + } + p.pOln("}"); + } + + if (needNewWriteStreamClass(returnType)) { + p.plnI(idExtOutputStream + " "+out+" = "); + p.pln("(" + idExtOutputStream + ") "+reply+".createReply();"); + p.pO(); + } else { + p.pln("OutputStream "+out+" = "+reply+".createReply();"); + } + + if (doReturn) { + writeMarshalArgument(p, out, returnType, "result"); + p.pln(); + } + + p.pln("return "+out+";"); + } + + + /** + * Write Java statements to marshal a series of values in order as + * named in the "names" array, with types as specified in the "types" + * array", to the java.io.ObjectOutput stream named "stream". + */ + void writeMarshalArguments(IndentingWriter p, + String streamName, + Type[] types, String[] names) + throws IOException + { + if (types.length != names.length) { + throw new Error("paramter type and name arrays different sizes"); + } + + for (int i = 0; i < types.length; i++) { + writeMarshalArgument(p, streamName, types[i], names[i]); + if (i != types.length -1) { + p.pln(); + } + } + } + + /** + * Added for IASRI 4987274. Remote classes named "Util" were + * getting confused with javax.rmi.CORBA.Util and the + * unqualifiedName "Util". + */ + String testUtil(String objectName, Type ttype) { + if (objectName.equals("Util")) { + String correctedName = (String)ttype.getPackageName() + "." + objectName; + return correctedName; + } else { + return objectName; + } + } + + @Override + protected File getOutputDirectory(File destinationDir, Identifier id, BatchEnvironment environment) { + return Util.getOutputDirectoryForStub(id,destinationDir,environment); + } + + @Override + protected void postProcessFile(BatchEnvironment env, File file) throws FileNotFoundException { + env.addGeneratedFile(file); + env.parseFile(ClassFile.newClassFile(file)); + } + +} + +class StringComparator implements java.util.Comparator { + public int compare(Object o1, Object o2) { + String s1 = (String)o1; + String s2 = (String)o2; + return s1.compareTo(s2); + } +} + + +class UserExceptionComparator implements java.util.Comparator { + public int compare(Object o1, Object o2) { + ValueType v1 = (ValueType)o1; + ValueType v2 = (ValueType)o2; + int result = 0; + if (isUserException(v1)) { + if (!isUserException(v2)) { + result = -1; + } + } else if (isUserException(v2)) { + if (!isUserException(v1)) { + result = 1; + } + } + return result; + } + + final boolean isUserException(ValueType it) { + return it.isIDLEntityException() && !it.isCORBAUserException(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/Type.java b/rmic/src/main/java/org/glassfish/rmic/iiop/Type.java new file mode 100644 index 000000000..15b0f18f1 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/Type.java @@ -0,0 +1,985 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import com.sun.corba.ee.impl.util.RepositoryId; +import org.glassfish.rmic.IndentingWriter; +import org.glassfish.rmic.Names; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.Identifier; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Vector; + +/** + * Type is an abstract base class for a family of types which provide + * conformance checking and name mapping as defined in the "Java to IDL + * Mapping" OMG specification. The family is composed of the following + * fixed set of types: + *

                {@literal
                + *
                + *                                              +- RemoteType <-- AbstractType
                + *                                              |
                + *                           +- InterfaceType <-+- SpecialInterfaceType
                + *         +- PrimitiveType  |                  |
                + *         |                 |                  +- NCInterfaceType
                + *  Type <-+- CompoundType <-|
                + *         |                 |                  +- ValueType
                + *         +- ArrayType      |                  |
                + *                           +- ClassType <-----+- ImplementationType
                + *                                              |
                + *                                              +- SpecialClassType
                + *                                              |
                + *                                              +- NCClassType
                + *
                + * }
                + * PrimitiveType represents a primitive or a void type. + *

                + * CompoundType is an abstract base representing any non-special class + * or interface type. + *

                + * InterfaceType is an abstract base representing any non-special + * interface type. + *

                + * RemoteType represents any non-special interface which inherits + * from java.rmi.Remote. + *

                + * AbstractType represents any non-special interface which does not + * inherit from java.rmi.Remote, for which all methods throw RemoteException. + *

                + * SpecialInterfaceType represents any one of the following types: + *

                + *    java.rmi.Remote
                + *    java.io.Serializable
                + *    java.io.Externalizable
                + * 
                + * all of which are treated as special cases. + *

                + * NCInterfaceType represents any non-special, non-conforming interface. + *

                + * ClassType is an abstract base representing any non-special class + * type. + *

                + * ValueType represents any non-special class which does inherit from + * java.io.Serializable and does not inherit from java.rmi.Remote. + *

                + * ImplementationType represents any non-special class which implements + * one or more interfaces which inherit from java.rmi.Remote. + *

                + * SpecialClassType represents any one of the following types: + *

                + *    java.lang.Object
                + *    java.lang.String
                + *    org.omg.CORBA.Object
                + * 
                + * all of which are treated as special cases. For all but CORBA.Object, + * the type must match exactly. For CORBA.Object, the type must either be + * CORBA.Object or inherit from it. + *

                + * NCClassType represents any non-special, non-conforming class. + *

                + * ArrayType is a wrapper for any of the other types. The getElementType() + * method can be used to get the array element type. The getArrayDimension() + * method can be used to get the array dimension. + *

                + * NOTE: None of these types is multi-thread-safe + * @author Bryan Atsatt + */ +public abstract class Type implements org.glassfish.rmic.iiop.Constants, ContextElement, Cloneable { + + private int typeCode; + private int fullTypeCode; + private Identifier id; + + private String name; + private String packageName; + private String qualifiedName; + + private String idlName; + private String[] idlModuleNames; + private String qualifiedIDLName; + + private String repositoryID; + private Class ourClass; + + private int status = STATUS_PENDING; + + protected BatchEnvironment env; // Easy access for subclasses. + protected ContextStack stack; // Easy access for subclasses. + + protected boolean destroyed = false; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Return the unqualified name for this type (e.g. com.acme.Dynamite would + * return "Dynamite"). + */ + public String getName() { + return name; + } + + /** + * Return the package of this type (e.g. com.acme.Dynamite would + * return "com.acme"). Will return null if default package or + * if this type is a primitive. + */ + public String getPackageName() { + return packageName; + } + + /** + * Return the fully qualified name of this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite") + */ + public String getQualifiedName() { + return qualifiedName; + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public abstract String getSignature(); + + /** + * IDL_Naming + * Return the unqualified IDL name of this type (e.g. com.acme.Dynamite would + * return "Dynamite"). + */ + public String getIDLName() { + return idlName; + } + + /** + * IDL_Naming + * Return the IDL module name for this type (e.g. com.acme.Dynamite would return + * a three element array of {"com","acme"). May be a zero length array if + * there is no module name. + */ + public String[] getIDLModuleNames() { + return idlModuleNames; + } + + /** + * IDL_Naming + * Return the fully qualified IDL name for this type (e.g. com.acme.Dynamite would + * return "com::acme::Dynamite"). + * @param global If true, prepends "::". + */ + public String getQualifiedIDLName(boolean global) { + if (global && getIDLModuleNames().length > 0) { + return IDL_NAME_SEPARATOR + qualifiedIDLName; + } else { + return qualifiedIDLName; + } + } + + /** + * Return the identifier for this type. May be qualified. + */ + public Identifier getIdentifier() { + return id; + } + + /** + * Return the repository ID for this type. + */ + public String getRepositoryID() { + return repositoryID; + } + + /** + * Return the repository ID for this "boxed" type. + */ + public String getBoxedRepositoryID() { + return RepositoryId.createForJavaType(ourClass); + } + + /** + * Return the Class for this type. + */ + public Class getClassInstance() { + if (ourClass == null) { + initClass(); + } + return ourClass; + } + + /** + * Return the status of this type. + */ + public int getStatus() { + return status; + } + + /** + * Set the status of this type. + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * Return the compiler environment for this type. + */ + public BatchEnvironment getEnv() { + return env; + } + + /** + * Get type code, without modifiers. Type codes are defined in org.glassfish.rmic.iiop.Constants. + */ + public int getTypeCode() { + return typeCode; + } + + /** + * Get type code, with modifiers. Type codes are defined in org.glassfish.rmic.iiop.Constants. + */ + public int getFullTypeCode() { + return fullTypeCode; + } + + /** + * Get type code modifiers. Type codes are defined in org.glassfish.rmic.iiop.Constants. + */ + public int getTypeCodeModifiers() { + return fullTypeCode & TM_MASK; + } + + /** + * Check for a certain type. Type codes are defined in org.glassfish.rmic.iiop.Constants. + * Returns true if all of the bits in typeCodeMask are present in the full type code + * of this object. + */ + public boolean isType(int typeCodeMask) { + return (fullTypeCode & typeCodeMask) == typeCodeMask; + } + + /** + * Like isType(), but returns true if any of the bits in typeCodeMask are + * present in the full type code of this object. + */ + public boolean typeMatches(int typeCodeMask) { + return (fullTypeCode & typeCodeMask) > 0; + } + + + /** + * Return the fullTypeCode. If an array, returns the + * type code from the element type. + */ + public int getRootTypeCode() { + if (isArray()) { + return getElementType().getFullTypeCode(); + } else { + return fullTypeCode; + } + } + + /** + * Return true if this type is-a InterfaceType. + */ + public boolean isInterface() { + return (fullTypeCode & TM_INTERFACE) == TM_INTERFACE; + } + + /** + * Return true if this type is-a ClassType. + */ + public boolean isClass() { + return (fullTypeCode & TM_CLASS) == TM_CLASS; + } + + /** + * Return true if this type is-a inner class or interface. + */ + public boolean isInner() { + return (fullTypeCode & TM_INNER) == TM_INNER; + } + + + /** + * Return true if this type is-a SpecialInterfaceType. + */ + public boolean isSpecialInterface() { + return (fullTypeCode & TM_SPECIAL_INTERFACE) == TM_SPECIAL_INTERFACE; + } + + /** + * Return true if this type is-a SpecialClassType. + */ + public boolean isSpecialClass() { + return (fullTypeCode & TM_SPECIAL_CLASS) == TM_SPECIAL_CLASS; + } + + /** + * Return true if this type is-a CompoundType. + */ + public boolean isCompound() { + return (fullTypeCode & TM_COMPOUND) == TM_COMPOUND; + } + + /** + * Return true if this type is-a PrimitiveType. + */ + public boolean isPrimitive() { + return (fullTypeCode & TM_PRIMITIVE) == TM_PRIMITIVE; + } + + /** + * Return true if this type is-a ArrayType. + */ + public boolean isArray() { + return (fullTypeCode & TYPE_ARRAY) == TYPE_ARRAY; + } + + /** + * Return true if this type is a conforming type. + */ + public boolean isConforming() { + return (fullTypeCode & TM_NON_CONFORMING) == TM_NON_CONFORMING; + } + + /** + * Return a string representation of this type. + */ + public String toString () { + return getQualifiedName(); + } + + /** + * Get element type. Returns null if not an array. + */ + public Type getElementType () { + return null; + } + + /** + * Get array dimension. Returns zero if not an array. + */ + public int getArrayDimension () { + return 0; + } + + /** + * Get brackets string. Returns "" if not an array. + */ + public String getArrayBrackets () { + return ""; + } + + /** + * Equality check based on the string representation. + */ + public boolean equals(Object obj) { + + String us = toString(); + String them = ((Type)obj).toString(); + return us.equals(them); + } + + /** + * Collect all the matching types referenced directly or indirectly + * by this type, including itself. + * @param typeCodeFilter The typeCode to use as a filter. + */ + public Type[] collectMatching (int typeCodeFilter) { + return collectMatching(typeCodeFilter,new HashSet(env.allTypes.size())); + } + + /** + * Collect all the matching types referenced directly or indirectly + * by this type, including itself. + * @param typeCodeFilter The typeCode to use as a filter. + * @param alreadyChecked Contains types which have previously been checked + * and will be ignored. Updated during collection. + */ + public Type[] collectMatching (int typeCodeFilter, HashSet alreadyChecked) { + Vector matching = new Vector(); + + // Fill up the list... + + addTypes(typeCodeFilter,alreadyChecked,matching); + + // Copy vector contents to array and return it... + + Type[] result = new Type[matching.size()]; + matching.copyInto(result); + + return result; + } + + /** + * Return a string describing this type. + */ + public abstract String getTypeDescription (); + + /** + * Return the name of this type. For arrays, will include "[]" if useIDLNames == false. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public String getTypeName ( boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) { + if (useIDLNames) { + if (useQualifiedNames) { + return getQualifiedIDLName(globalIDLNames); + } else { + return getIDLName(); + } + } else { + if (useQualifiedNames) { + return getQualifiedName(); + } else { + return getName(); + } + } + } + + /** + * Print all types referenced directly or indirectly by this type which + * match the filter. + * @param writer The stream to print to. + * @param typeCodeFilter The type codes to print. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + int typeCodeFilter, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + Type[] theTypes = collectMatching(typeCodeFilter); + print(writer,theTypes,useQualifiedNames,useIDLNames,globalIDLNames); + } + + /** + * Print an array of types. + * @param writer The stream to print to. + * @param theTypes The types to print. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public static void print ( IndentingWriter writer, + Type[] theTypes, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + for (int i = 0; i < theTypes.length; i++) { + theTypes[i].println(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + + + /** + * Print this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + + /** + * Print this type, followed by a newline. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void println ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + print(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + } + + + + /** + * Print the name of this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void printTypeName ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + writer.p(getTypeName(useQualifiedNames,useIDLNames,globalIDLNames)); + } + + /** + * Return context element name. + */ + public String getElementName() { + return getQualifiedName(); + } + + //_____________________________________________________________________ + // Subclass Interfaces + //_____________________________________________________________________ + + /** + * Print the "opening" of the package or module of this type. + * @param writer The stream to print to. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + */ + protected void printPackageOpen ( IndentingWriter writer, + boolean useIDLNames) throws IOException { + + if (useIDLNames) { + String[] moduleNames = getIDLModuleNames(); + for (int i = 0; i < moduleNames.length; i++ ) { + writer.plnI("module " + moduleNames[i] + " {"); + } + } else { + String packageName = getPackageName(); + if (packageName != null) { + writer.pln("package " + packageName + ";"); + } + } + } + + /** + * Get a type out of the table. + */ + protected static Type getType (org.glassfish.rmic.tools.java.Type key, ContextStack stack) { + return getType(key.toString(),stack); + } + + /** + * Get a type out of the table. + */ + protected static Type getType (String key, ContextStack stack) { + Type result = (Type) stack.getEnv().allTypes.get(key); + + if (result != null) { + stack.traceExistingType(result); + } + + return result; + } + + /** + * Remove a type from the table. + */ + protected static void removeType (String key, ContextStack stack) { + Type value = (Type) stack.getEnv().allTypes.remove(key); + stack.getEnv().invalidTypes.put(value,key); + } + + /** + * Remove a type from the table. + */ + protected static void removeType (org.glassfish.rmic.tools.java.Type key, ContextStack stack) { + String theKey = key.toString(); + Type old = (Type) stack.getEnv().allTypes.remove(theKey); + putInvalidType(old,theKey,stack); + } + + /** + * Put a type into the table. + */ + protected static void putType (org.glassfish.rmic.tools.java.Type key, Type value, ContextStack stack) { + stack.getEnv().allTypes.put(key.toString(),value); + } + + /** + * Put a type into the table. + */ + protected static void putType (String key, Type value, ContextStack stack) { + stack.getEnv().allTypes.put(key,value); + } + + /** + * Put an invalid type into the. + */ + protected static void putInvalidType (Type key, String value, ContextStack stack) { + stack.getEnv().invalidTypes.put(key,value); + } + + + /** + * Remove all invalid types... + */ + public void removeInvalidTypes () { + if (env.invalidTypes.size() > 0) { + env.invalidTypes.clear(); + } + } + + /** + * Walk all types and tell them to update invalid types... + */ + protected static void updateAllInvalidTypes (ContextStack stack) { + BatchEnvironment env = stack.getEnv(); + if (env.invalidTypes.size() > 0) { + + // Walk all types and swap invalid... + + for (Enumeration e = env.allTypes.elements() ; e.hasMoreElements() ;) { + Type it = (Type) e.nextElement(); + it.swapInvalidTypes(); + } + + // Delete all invalidTypes... + + env.invalidTypes.clear(); + } + } + + /** + * Return count of previously parsed types. + */ + protected int countTypes () { + return env.allTypes.size(); + } + + /** + * Reset types removes all previously parsed types. + */ + void resetTypes () { + env.reset(); + } + + /** + * Release all resources. + */ + protected void destroy () { + if (!destroyed) { + id = null; + name = null; + packageName = null; + qualifiedName = null; + idlName = null; + idlModuleNames = null; + qualifiedIDLName = null; + repositoryID = null; + ourClass = null; + env = null; + stack = null; + destroyed = true; + } + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + } + + /** + * Convert an invalid type to a valid one. + */ + protected Type getValidType (Type invalidType) { + if (invalidType.getStatus() == STATUS_VALID) { + return invalidType; + } + + String key = (String)env.invalidTypes.get(invalidType); + Type result = null; + if (key != null) { + result = (Type) env.allTypes.get(key); + } + + if (result == null) { + throw new Error("Failed to find valid type to swap for " + invalidType + " mis-identified as " + invalidType.getTypeDescription()); + } + //System.out.println("Swapped " + result + " from " + invalidType.getTypeDescription() + // + " to " + result.getTypeDescription()); + //ContextStack.dumpCallStack(); + return result; + } + + /** + * Print the "closing" of the package or module of this type. + * @param writer The stream to print to. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + */ + protected void printPackageClose ( IndentingWriter writer, + boolean useIDLNames) throws IOException { + if (useIDLNames) { + String[] moduleNames = getIDLModuleNames(); + for (int i = 0; i < moduleNames.length; i++ ) { + writer.pOln("};"); + } + } + } + + /** + * Create a Type instance for the given type. Requires that + * setName(Identifier) be called afterward. + */ + protected Type(ContextStack stack, int fullTypeCode) { + this.env = stack.getEnv(); + this.stack = stack; + this.fullTypeCode = fullTypeCode; + typeCode = fullTypeCode & TYPE_MASK; + } + + /** + * Set type codes. May only be called during initialization. + */ + protected void setTypeCode(int fullTypeCode) { + this.fullTypeCode = fullTypeCode; + typeCode = fullTypeCode & TYPE_MASK; + } + + /** + * Set name and package. May only be called during initialization. + */ + protected void setNames(Identifier id, String[] idlModuleNames, String idlName) { + + this.id = id; + name = Names.mangleClass(id).getName().toString(); + packageName = null; + + if (id.isQualified()) { + packageName = id.getQualifier().toString(); + qualifiedName = packageName + NAME_SEPARATOR + name; + } else { + qualifiedName = name; + } + + setIDLNames(idlModuleNames,idlName); + } + + + /** + * Set IDL name. May only be called during initialization. + */ + protected void setIDLNames(String[] idlModuleNames, String idlName) { + this.idlName = idlName; + + if (idlModuleNames != null) { + this.idlModuleNames = idlModuleNames; + } else { + this.idlModuleNames = new String[0]; + } + qualifiedIDLName = IDLNames.getQualifiedName(idlModuleNames,idlName); + } + + /** + * Report a ClassNotFoundException thru the compiler environment. + */ + protected static void classNotFound(ContextStack stack, + ClassNotFound e) { + classNotFound(false,stack,e); + } + + /** + * Report a ClassNotFoundException thru the compiler environment. + */ + protected static void classNotFound(boolean quiet, + ContextStack stack, + ClassNotFound e) { + if (!quiet) stack.getEnv().error(0, "rmic.class.not.found", e.name); + stack.traceCallStack(); + } + + /** + * Report a constraint failure thru the compiler environment. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param arg0 An object to substitute for {0} in the message. + * @param arg1 An object to substitute for {1} in the message. + * @param arg2 An object to substitute for {2} in the message. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack, + Object arg0, Object arg1, Object arg2) { + String message = "rmic.iiop.constraint." + constraintNum; + + if (!quiet) { + stack.getEnv().error(0,message, + (arg0 != null ? arg0.toString() : null), + (arg1 != null ? arg1.toString() : null), + (arg2 != null ? arg2.toString() : null)); + } else { + String error = stack.getEnv().errorString(message,arg0,arg1,arg2); + stack.traceln(error); + } + + return false; + } + + /** + * Report a constraint failure thru the compiler environment. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param arg0 An object to substitute for {0} in the message. + * @param arg1 An object to substitute for {1} in the message. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack, + Object arg0, Object arg1) { + return failedConstraint(constraintNum,quiet,stack,arg0,arg1,null); + } + + + /** + * Report a constraint failure thru the compiler environment. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param arg0 An object to substitute for {0} in the message. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack, + Object arg0) { + return failedConstraint(constraintNum,quiet,stack,arg0,null,null); + } + + /** + * Report a constraint failure thru the compiler environment. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack) { + return failedConstraint(constraintNum,quiet,stack,null,null,null); + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + + /* + * Add matching types to list. Return true if this type has not + * been previously checked, false otherwise. + */ + protected boolean addTypes (int typeCodeFilter, + HashSet checked, + Vector matching) { + + boolean result; + + // Have we already checked this type? + + if (checked.contains(this)) { + + // Yes, so return false. + + result = false; + + } else { + + // Nope, so add it... + + checked.add(this); + + // Do we match the filter? + + if (typeMatches(typeCodeFilter)) { + + // Yep. so add it and set result to true... + + matching.addElement(this); + } + + // Return true. + + result = true; + } + + return result; + } + + /* + * Load a Class instance. Return null if fail. + */ + protected abstract Class loadClass(); + + private boolean initClass() { + if (ourClass == null) { + ourClass = loadClass(); + if (ourClass == null) { + failedConstraint(27,false,stack,getQualifiedName()); + return false; + } + } + return true; + } + + /* + * Set the clz and repositoryID fields. Reports error + * and returns false if fails, returns true if succeeds. + */ + protected boolean setRepositoryID() { + + // First, load the class... + + if (!initClass()) { + return false; + } + + // Now make the repositoryID and return success... + + repositoryID = RepositoryId.createForAnyType(ourClass); + return true; + } + + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + private Type () {} // Disallowed. +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/Util.java b/rmic/src/main/java/org/glassfish/rmic/iiop/Util.java new file mode 100644 index 000000000..db19b9f91 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/Util.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1999, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import com.sun.corba.ee.impl.util.PackagePrefixChecker; +import org.glassfish.rmic.tools.java.Identifier; + +import java.io.File; + +/** + * Util provides static utility methods used by other rmic classes. + * @author Bryan Atsatt + */ + +public final class Util implements org.glassfish.rmic.Constants { + + + public static String packagePrefix(){ return PackagePrefixChecker.packagePrefix();} + + + /** + * Return the directory that should be used for output for a given + * class. + * @param theClass The fully qualified name of the class. + * @param rootDir The directory to use as the root of the + * package heirarchy. May be null, in which case the current + * working directory is used as the root. + */ + private static File getOutputDirectoryFor(Identifier theClass, + File rootDir, + BatchEnvironment env, + boolean idl ) { + File outputDir = null; + String className = theClass.getFlatName().toString().replace('.', SIGC_INNERCLASS); + String qualifiedClassName = className; + String packagePath = null; + String packageName = theClass.getQualifier().toString(); + //Shift package names for stubs generated for interfaces. + /*if(type.isInterface())*/ + packageName = correctPackageName(packageName, idl, env.getStandardPackage()); + //Done. + if (packageName.length() > 0) { + qualifiedClassName = packageName + "." + className; + packagePath = packageName.replace('.', File.separatorChar); + } + + // Do we have a root directory? + + if (rootDir != null) { + + // Yes, do we have a package name? + + if (packagePath != null) { + + // Yes, so use it as the root. Open the directory... + + outputDir = new File(rootDir, packagePath); + + // Make sure the directory exists... + + ensureDirectory(outputDir,env); + + } else { + + // Default package, so use root as output dir... + + outputDir = rootDir; + } + } else { + + // No root directory. Get the current working directory... + + String workingDirPath = System.getProperty("user.dir"); + File workingDir = new File(workingDirPath); + + // Do we have a package name? + + if (packagePath == null) { + + // No, so use working directory... + + outputDir = workingDir; + + } else { + + // Yes, so use working directory as the root... + + outputDir = new File(workingDir, packagePath); + + // Make sure the directory exists... + + ensureDirectory(outputDir,env); + } + } + + // Finally, return the directory... + + return outputDir; + } + + public static File getOutputDirectoryForIDL(Identifier theClass, + File rootDir, + BatchEnvironment env) { + return getOutputDirectoryFor(theClass, rootDir, env, true); + } + + public static File getOutputDirectoryForStub(Identifier theClass, + File rootDir, + BatchEnvironment env) { + return getOutputDirectoryFor(theClass, rootDir, env, false); + } + + private static void ensureDirectory (File dir, BatchEnvironment env) { + if (!dir.exists()) { + dir.mkdirs(); + if (!dir.exists()) { + env.error(0,"rmic.cannot.create.dir",dir.getAbsolutePath()); + throw new InternalError(); + } + } + } + + public static String correctPackageName( + String p, boolean idl, boolean standardPackage){ + if (idl){ + return p; + } else { + if (standardPackage) { + return p; + } else { + return PackagePrefixChecker.correctPackageName(p); + } + } + } + + public static boolean isOffendingPackage(String p){ + return PackagePrefixChecker.isOffendingPackage(p); + } + + public static boolean hasOffendingPrefix(String p){ + return PackagePrefixChecker.hasOffendingPrefix(p); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/iiop/ValueType.java b/rmic/src/main/java/org/glassfish/rmic/iiop/ValueType.java new file mode 100644 index 000000000..9e5b9951d --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/iiop/ValueType.java @@ -0,0 +1,469 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.iiop; + +import org.glassfish.rmic.tools.java.ClassDeclaration; +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.ClassNotFound; +import org.glassfish.rmic.tools.java.MemberDefinition; + +import java.io.ObjectStreamClass; +import java.io.ObjectStreamField; +import java.util.Hashtable; +import java.util.Vector; + + +/** + * ValueType represents any non-special class which does inherit from + * java.io.Serializable and does not inherit from java.rmi.Remote. + *

                + * The static forValue(...) method must be used to obtain an instance, and + * will return null if the ClassDefinition is non-conforming. + * + * @author Bryan Atsatt + */ +public class ValueType extends ClassType { + + private boolean isCustom; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an ValueType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static ValueType forValue(ClassDefinition classDef, + ContextStack stack, + boolean quiet) { + + if (stack.anyErrors()) return null; + + // Do we already have it? + + org.glassfish.rmic.tools.java.Type theType = classDef.getType(); + String typeKey = theType.toString(); + Type existing = getType(typeKey,stack); + + if (existing != null) { + + if (!(existing instanceof ValueType)) return null; // False hit. + + // Yep, so return it... + + return (ValueType) existing; + } + + // Is this java.lang.Class? + + boolean javaLangClass = false; + + if (classDef.getClassDeclaration().getName() == idJavaLangClass) { + + // Yes, so replace classDef with one for + // javax.rmi.CORBA.ClassDesc... + + javaLangClass = true; + BatchEnvironment env = stack.getEnv(); + ClassDeclaration decl = env.getClassDeclaration(idClassDesc); + ClassDefinition def = null; + + try { + def = decl.getClassDefinition(env); + } catch (ClassNotFound ex) { + classNotFound(stack,ex); + return null; + } + + classDef = def; + } + + // Could this be a value? + + if (couldBeValue(stack,classDef)) { + + // Yes, so check it... + + ValueType it = new ValueType(classDef,stack,javaLangClass); + putType(typeKey,it,stack); + stack.push(it); + + if (it.initialize(stack,quiet)) { + stack.pop(true); + return it; + } else { + removeType(typeKey,stack); + stack.pop(false); + return null; + } + } else { + return null; + } + } + + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + String result = addExceptionDescription("Value"); + if (isCustom) { + result = "Custom " + result; + } + if (isIDLEntity) { + result = result + " [IDLEntity]"; + } + return result; + } + + /** + * Return true if this type is a "custom" type (i.e. + * it implements java.io.Externalizable or has a + * method with the following signature: + * + * private void writeObject(java.io.ObjectOutputStream out); + * + */ + public boolean isCustom () { + return isCustom; + } + + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create a ValueType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private ValueType(ClassDefinition classDef, + ContextStack stack, + boolean isMappedJavaLangClass) { + super(stack,classDef,TYPE_VALUE | TM_CLASS | TM_COMPOUND); + isCustom = false; + + // If this is the mapped version of java.lang.Class, + // set the non-IDL names back to java.lang.Class... + + if (isMappedJavaLangClass) { + setNames(idJavaLangClass,IDL_CLASS_MODULE,IDL_CLASS); + } + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Initialize this instance. + */ + + private static boolean couldBeValue(ContextStack stack, ClassDefinition classDef) { + + boolean result = false; + ClassDeclaration classDecl = classDef.getClassDeclaration(); + BatchEnvironment env = stack.getEnv(); + + try { + // Make sure it's not remote... + + if (env.defRemote.implementedBy(env, classDecl)) { + failedConstraint(10,false,stack,classDef.getName()); + } else { + + // Make sure it's Serializable... + + if (!env.defSerializable.implementedBy(env, classDecl)) { + failedConstraint(11,false,stack,classDef.getName()); + } else { + result = true; + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack, boolean quiet) { + + ClassDefinition ourDef = getClassDefinition(); + ClassDeclaration ourDecl = getClassDeclaration(); + + try { + + // Make sure our parentage is ok... + + if (!initParents(stack)) { + failedConstraint(12,quiet,stack,getQualifiedName()); + return false; + } + + + // We're ok, so make up our collections... + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directMembers = new Vector(); + + // Get interfaces... + + if (addNonRemoteInterfaces(directInterfaces,stack) != null) { + + // Get methods... + + if (addAllMethods(ourDef,directMethods,false,false,stack) != null) { + + // Update parent class methods + if (updateParentClassMethods(ourDef,directMethods,false,stack) != null) { + + // Get constants and members... + + if (addAllMembers(directMembers,false,false,stack)) { + + // We're ok, so pass 'em up... + + if (!initialize(directInterfaces,directMethods,directMembers,stack,quiet)) { + return false; + } + + // Is this class Externalizable? + + boolean externalizable = false; + if (!env.defExternalizable.implementedBy(env, ourDecl)) { + + // No, so check to see if we have a serialPersistentField + // that will modify the members. + + if (!checkPersistentFields(getClassInstance(),quiet)) { + return false; + } + } else { + + // Yes. + + externalizable = true; + } + + // Should this class be considered "custom"? It is if + // it is Externalizable OR if it has a method with the + // following signature: + // + // private void writeObject(java.io.ObjectOutputStream out); + // + + if (externalizable) { + isCustom = true; + } else { + for (MemberDefinition member = ourDef.getFirstMember(); + member != null; + member = member.getNextMember()) { + + if (member.isMethod() && + !member.isInitializer() && + member.isPrivate() && + member.getName().toString().equals("writeObject")) { + + // Check return type, arguments and exceptions... + + org.glassfish.rmic.tools.java.Type methodType = member.getType(); + org.glassfish.rmic.tools.java.Type rtnType = methodType.getReturnType(); + + if (rtnType == org.glassfish.rmic.tools.java.Type.tVoid) { + + // Return type is correct. How about arguments? + + org.glassfish.rmic.tools.java.Type[] args = methodType.getArgumentTypes(); + if (args.length == 1 && + args[0].getTypeSignature().equals("Ljava/io/ObjectOutputStream;")) { + + // Arguments are correct, so it is a custom + // value type... + + isCustom = true; + } + } + } + } + } + } + + return true; + } + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return false; + } + + + private boolean checkPersistentFields (Class clz, boolean quiet) { + + // Do we have a writeObject method? + + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals("writeObject") && + methods[i].getArguments().length == 1) { + + Type returnType = methods[i].getReturnType(); + Type arg = methods[i].getArguments()[0]; + String id = arg.getQualifiedName(); + + if (returnType.isType(TYPE_VOID) && + id.equals("java.io.ObjectOutputStream")) { + + // Got one, so there's nothing to do... + + return true; + } + } + } + + // Do we have a valid serialPersistentField array? + + MemberDefinition spfDef = null; + + for (int i = 0; i < members.length; i++) { + if (members[i].getName().equals("serialPersistentFields")) { + + Member member = members[i]; + Type type = member.getType(); + Type elementType = type.getElementType(); + + // We have a member with the correct name. Make sure + // we have the correct signature... + + if (elementType != null && + elementType.getQualifiedName().equals( + "java.io.ObjectStreamField") + ) { + + if (member.isStatic() && + member.isFinal() && + member.isPrivate()) { + + // We have the correct signature + + spfDef = member.getMemberDefinition(); + + } else { + + // Bad signature... + + failedConstraint(4,quiet,stack,getQualifiedName()); + return false; + } + } + } + } + + // If we do not have a serialPersistentField, + // there's nothing to do, so return with no error... + + if (spfDef == null) { + return true; + } + + // Ok, now we must examine the contents of the array - + // then validate them... + + Hashtable fields = getPersistentFields(clz); + boolean result = true; + + for (int i = 0; i < members.length; i++) { + String fieldName = members[i].getName(); + String fieldType = members[i].getType().getSignature(); + + // Is this field present in the array? + + String type = (String) fields.get(fieldName); + + if (type == null) { + + // No, so mark it transient... + + members[i].setTransient(); + + } else { + + // Yes, does the type match? + + if (type.equals(fieldType)) { + + // Yes, so remove it from the fields table... + + fields.remove(fieldName); + + } else { + + // No, so error... + + result = false; + failedConstraint(2,quiet,stack,fieldName,getQualifiedName()); + } + } + } + + // Ok, we've checked all of our fields. Are there any left in the "array"? + // If so, it's an error... + + if (result && fields.size() > 0) { + + result = false; + failedConstraint(9,quiet,stack,getQualifiedName()); + } + + // Return result... + + return result; + } + + /** + * Get the names and types of all the persistent fields of a Class. + */ + private Hashtable getPersistentFields (Class clz) { + Hashtable result = new Hashtable(); + ObjectStreamClass osc = ObjectStreamClass.lookup(clz); + if (osc != null) { + ObjectStreamField[] fields = osc.getFields(); + for (int i = 0; i < fields.length; i++) { + String typeSig; + String typePrefix = String.valueOf(fields[i].getTypeCode()); + if (fields[i].isPrimitive()) { + typeSig = typePrefix; + } else { + if (fields[i].getTypeCode() == '[') { + typePrefix = ""; + } + typeSig = typePrefix + fields[i].getType().getName().replace('.','/'); + if (typeSig.endsWith(";")) { + typeSig = typeSig.substring(0,typeSig.length()-1); + } + } + result.put(fields[i].getName(),typeSig); + } + } + return result; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/asm/ArrayData.java b/rmic/src/main/java/org/glassfish/rmic/tools/asm/ArrayData.java new file mode 100644 index 000000000..9d9bf2cdd --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/asm/ArrayData.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1995, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.asm; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public final +class ArrayData { + Type type; + int nargs; + + public ArrayData(Type type, int nargs) { + this.type = type; + this.nargs = nargs; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/asm/Assembler.java b/rmic/src/main/java/org/glassfish/rmic/tools/asm/Assembler.java new file mode 100644 index 000000000..da20da7ba --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/asm/Assembler.java @@ -0,0 +1,954 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.asm; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.CompilerError; +import org.glassfish.rmic.tools.java.Constants; +import org.glassfish.rmic.tools.java.Environment; +import org.glassfish.rmic.tools.java.MemberDefinition; +import org.glassfish.rmic.tools.java.Type; +import org.glassfish.rmic.tools.javac.SourceClass; + +import java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Enumeration; +import java.util.Vector; + +// JCOV +// end JCOV + +/** + * This class is used to assemble the bytecode instructions for a method. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ +public final +class Assembler implements Constants { + static final int NOTREACHED = 0; + static final int REACHED = 1; + static final int NEEDED = 2; + + Label first = new Label(); + Instruction last = first; + int maxdepth; + int maxvar; + int maxpc; + + /** + * Add an instruction + */ + public void add(Instruction inst) { + if (inst != null) { + last.next = inst; + last = inst; + } + } + public void add(long where, int opc) { + add(new Instruction(where, opc, null)); + } + public void add(long where, int opc, Object obj) { + add(new Instruction(where, opc, obj)); + } +// JCOV + public void add(long where, int opc, Object obj, boolean flagCondInverted) { + add(new Instruction(where, opc, obj, flagCondInverted)); + } + + public void add(boolean flagNoCovered, long where, int opc, Object obj) { + add(new Instruction(flagNoCovered, where, opc, obj)); + } + + public void add(long where, int opc, boolean flagNoCovered) { + add(new Instruction(where, opc, flagNoCovered)); + } + + static Vector SourceClassList = new Vector<>(); + + static Vector TmpCovTable = new Vector<>(); + + static int[] JcovClassCountArray = new int[CT_LAST_KIND + 1]; + + static String JcovMagicLine = "JCOV-DATA-FILE-VERSION: 2.0"; + static String JcovClassLine = "CLASS: "; + static String JcovSrcfileLine = "SRCFILE: "; + static String JcovTimestampLine = "TIMESTAMP: "; + static String JcovDataLine = "DATA: "; + static String JcovHeadingLine = "#kind\tcount"; + + static int[] arrayModifiers = + {M_PUBLIC, M_PRIVATE, M_PROTECTED, M_ABSTRACT, M_FINAL, M_INTERFACE}; + static int[] arrayModifiersOpc = + {PUBLIC, PRIVATE, PROTECTED, ABSTRACT, FINAL, INTERFACE}; +//end JCOV + + /** + * Optimize instructions and mark those that can be reached + */ + void optimize(Environment env, Label lbl) { + lbl.pc = REACHED; + + for (Instruction inst = lbl.next ; inst != null ; inst = inst.next) { + switch (inst.pc) { + case NOTREACHED: + inst.optimize(env); + inst.pc = REACHED; + break; + case REACHED: + return; + case NEEDED: + break; + } + + switch (inst.opc) { + case opc_label: + case opc_dead: + if (inst.pc == REACHED) { + inst.pc = NOTREACHED; + } + break; + + case opc_ifeq: + case opc_ifne: + case opc_ifgt: + case opc_ifge: + case opc_iflt: + case opc_ifle: + case opc_if_icmpeq: + case opc_if_icmpne: + case opc_if_icmpgt: + case opc_if_icmpge: + case opc_if_icmplt: + case opc_if_icmple: + case opc_if_acmpeq: + case opc_if_acmpne: + case opc_ifnull: + case opc_ifnonnull: + optimize(env, (Label)inst.value); + break; + + case opc_goto: + optimize(env, (Label)inst.value); + return; + + case opc_jsr: + optimize(env, (Label)inst.value); + break; + + case opc_ret: + case opc_return: + case opc_ireturn: + case opc_lreturn: + case opc_freturn: + case opc_dreturn: + case opc_areturn: + case opc_athrow: + return; + + case opc_tableswitch: + case opc_lookupswitch: { + SwitchData sw = (SwitchData)inst.value; + optimize(env, sw.defaultLabel); + for (Enumeration

                Collect all methods defined in this class or inherited from + * any of our superclasses or interfaces. Look for any + * incompatible definitions. + * + *

                This function is also responsible for collecting the + * Miranda methods for a class. For a definition of + * Miranda methods, see the comment in addMirandaMethods() + * below. + */ + protected void collectInheritedMethods(Environment env) { + // The methods defined in this class. + MethodSet myMethods; + MethodSet mirandaMethods; + + //System.out.println("Called collectInheritedMethods() for " + + // this); + + if (allMethods != null) { + if (allMethods.isFrozen()) { + // We have already done the collection. No need to + // do it again. + return; + } else { + // We have run into a circular need to collect our methods. + // This should not happen at this stage. + throw new CompilerError("collectInheritedMethods()"); + } + } + + myMethods = new MethodSet(); + allMethods = new MethodSet(); + + // For testing, do not generate miranda methods. + if (env.version12()) { + mirandaMethods = null; + } else { + mirandaMethods = new MethodSet(); + } + + // Any methods defined in the current class get added + // to both the myMethods and the allMethods MethodSets. + + for (MemberDefinition member = getFirstMember(); + member != null; + member = member.nextMember) { + + // We only collect methods. Initializers are not relevant. + if (member.isMethod() && + !member.isInitializer()) { + + //System.out.println("Declared in " + this + ", " + member); + + //////////////////////////////////////////////////////////// + // PCJ 2003-07-30 modified the following code because with + // the covariant return type feature of the 1.5 compiler, + // there might be multiple methods with the same signature + // but different return types, and MethodSet doesn't + // support that. We use a new utility method that attempts + // to ensure that the appropriate method winds up in the + // MethodSet. See 4892308. + //////////////////////////////////////////////////////////// + // myMethods.add(member); + // allMethods.add(member); + //////////////////////////////////////////////////////////// + methodSetAdd(env, myMethods, member); + methodSetAdd(env, allMethods, member); + //////////////////////////////////////////////////////////// + } + } + + // We're ready to start adding inherited methods. First add + // the methods from our superclass. + + //System.out.println("About to start superclasses for " + this); + + ClassDeclaration scDecl = getSuperClass(env); + if (scDecl != null) { + collectOneClass(env, scDecl, + myMethods, allMethods, mirandaMethods); + + // Make sure that we add all unimplementable methods from our + // superclass to our list of unimplementable methods. + ClassDefinition sc = scDecl.getClassDefinition(); + Iterator supIter = sc.getPermanentlyAbstractMethods(); + while (supIter.hasNext()) { + permanentlyAbstractMethods.add(supIter.next()); + } + } + + // Now we inherit all of the methods from our interfaces. + + //System.out.println("About to start interfaces for " + this); + + for (int i = 0; i < interfaces.length; i++) { + collectOneClass(env, interfaces[i], + myMethods, allMethods, mirandaMethods); + } + allMethods.freeze(); + + // Now we have collected all of our methods from our superclasses + // and interfaces into our `allMethods' member. Good. As a last + // task, we add our collected miranda methods to this class. + // + // If we do not add the mirandas to the class explicitly, there + // will be no code generated for them. + if (mirandaMethods != null && mirandaMethods.size() > 0) { + addMirandaMethods(env, mirandaMethods.iterator()); + } + } + + //////////////////////////////////////////////////////////// + // PCJ 2003-07-30 added this utility method to insulate + // MethodSet additions from the covariant return type + // feature of the 1.5 compiler. When there are multiple + // methods with the same signature and different return + // types to be added, we try to ensure that the one with + // the most specific return type winds up in the MethodSet. + // This logic was not put into MethodSet itself because it + // requires access to an Environment for type relationship + // checking. No error checking is performed here, but that + // should be OK because this code is only still used by + // rmic. See 4892308. + //////////////////////////////////////////////////////////// + private static void methodSetAdd(Environment env, + MethodSet methodSet, + MemberDefinition newMethod) + { + MemberDefinition oldMethod = methodSet.lookupSig(newMethod.getName(), + newMethod.getType()); + if (oldMethod != null) { + Type oldReturnType = oldMethod.getType().getReturnType(); + Type newReturnType = newMethod.getType().getReturnType(); + try { + if (env.isMoreSpecific(newReturnType, oldReturnType)) { + methodSet.replace(newMethod); + } + } catch (ClassNotFound ignore) { + } + } else { + methodSet.add(newMethod); + } + } + //////////////////////////////////////////////////////////// + + /** + * Get an Iterator of all methods which could be accessed in an + * instance of this class. + */ + protected Iterator getMethods(Environment env) { + if (allMethods == null) { + collectInheritedMethods(env); + } + return getMethods(); + } + + /** + * Get an Iterator of all methods which could be accessed in an + * instance of this class. Throw a compiler error if we haven't + * generated this information yet. + */ + public Iterator getMethods() { + if (allMethods == null) { + throw new CompilerError("getMethods: too early"); + } + return allMethods.iterator(); + } + + // In early VM's there was a bug -- the VM didn't walk the interfaces + // of a class looking for a method, they only walked the superclass + // chain. This meant that abstract methods defined only in interfaces + // were not being found. To fix this bug, a counter-bug was introduced + // in the compiler -- the so-called Miranda methods. If a class + // does not provide a definition for an abstract method in one of + // its interfaces then the compiler inserts one in the class artificially. + // That way the VM didn't have to bother looking at the interfaces. + // + // This is a problem. Miranda methods are not part of the specification. + // But they continue to be inserted so that old VM's can run new code. + // Someday, when the old VM's are gone, perhaps classes can be compiled + // without Miranda methods. Towards this end, the compiler has a + // flag, -nomiranda, which can turn off the creation of these methods. + // Eventually that behavior should become the default. + // + // Why are they called Miranda methods? Well the sentence "If the + // class is not able to provide a method, then one will be provided + // by the compiler" is very similar to the sentence "If you cannot + // afford an attorney, one will be provided by the court," -- one + // of the so-called "Miranda" rights in the United States. + + /** + * Add a list of methods to this class as miranda methods. This + * gets overridden with a meaningful implementation in SourceClass. + * BinaryClass should not need to do anything -- it should already + * have its miranda methods and, if it doesn't, then that doesn't + * affect our compilation. + */ + protected void addMirandaMethods(Environment env, + Iterator mirandas) { + // do nothing. + } + + //--------------------------------------------------------------- + + public void inlineLocalClass(Environment env) { + } + + /** + * We create a stub for this. Source classes do more work. + * Some calls from 'SourceClass.checkSupers' execute this method. + * @see org.glassfish.rmic.tools.javac.SourceClass#resolveTypeStructure + */ + + public void resolveTypeStructure(Environment env) { + } + + /** + * Look up an inner class name, from somewhere inside this class. + * Since supers and outers are in scope, search them too. + *

                + * If no inner class is found, env.resolveName() is then called, + * to interpret the ambient package and import directives. + *

                + * This routine operates on a "best-efforts" basis. If + * at some point a class is not found, the partially-resolved + * identifier is returned. Eventually, someone else has to + * try to get the ClassDefinition and diagnose the ClassNotFound. + *

                + * resolveName() looks at surrounding scopes, and hence + * pulling in both inherited and uplevel types. By contrast, + * resolveInnerClass() is intended only for interpreting + * explicitly qualified names, and so look only at inherited + * types. Also, resolveName() looks for package prefixes, + * which appear similar to "very uplevel" outer classes. + *

                + * A similar (but more complex) name-lookup process happens + * when field and identifier expressions denoting qualified names + * are type-checked. The added complexity comes from the fact + * that variables may occur in such names, and take precedence + * over class and package names. + *

                + * In the expression type-checker, resolveInnerClass() is paralleled + * by code in FieldExpression.checkAmbigName(), which also calls + * ClassDefinition.getInnerClass() to interpret names of the form + * "OuterClass.Inner" (and also outerObject.Inner). The checking + * of an identifier expression that fails to be a variable is referred + * directly to resolveName(). + */ + public Identifier resolveName(Environment env, Identifier name) { + if (tracing) env.dtEvent("ClassDefinition.resolveName: " + name); + // This logic is pretty much exactly parallel to that of + // Environment.resolveName(). + if (name.isQualified()) { + // Try to resolve the first identifier component, + // because inner class names take precedence over + // package prefixes. (Cf. Environment.resolveName.) + Identifier rhead = resolveName(env, name.getHead()); + + if (rhead.hasAmbigPrefix()) { + // The first identifier component refers to an + // ambiguous class. Limp on. We throw away the + // rest of the classname as it is irrelevant. + // (part of solution for 4059855). + return rhead; + } + + if (!env.classExists(rhead)) { + return env.resolvePackageQualifiedName(name); + } + try { + return env.getClassDefinition(rhead). + resolveInnerClass(env, name.getTail()); + } catch (ClassNotFound ee) { + // return partially-resolved name someone else can fail on + return Identifier.lookupInner(rhead, name.getTail()); + } + } + + // This method used to fail to look for local classes, thus a + // reference to a local class within, e.g., the type of a member + // declaration, would fail to resolve if the immediately enclosing + // context was an inner class. The code added below is ugly, but + // it works, and is lifted from existing code in 'Context.resolveName' + // and 'Context.getClassCommon'. See the comments there about the design. + // Fixes 4095716. + + int ls = -2; + LocalMember lf = null; + if (classContext != null) { + lf = classContext.getLocalClass(name); + if (lf != null) { + ls = lf.getScopeNumber(); + } + } + + // Look for an unqualified name in enclosing scopes. + for (ClassDefinition c = this; c != null; c = c.outerClass) { + try { + MemberDefinition f = c.getInnerClass(env, name); + if (f != null && + (lf == null || classContext.getScopeNumber(c) > ls)) { + // An uplevel member was found, and was nested more deeply than + // any enclosing local of the same name. + return f.getInnerClass().getName(); + } + } catch (ClassNotFound ee) { + // a missing superclass, or something catastrophic + } + } + + // No uplevel member found, so use the enclosing local if one was found. + if (lf != null) { + return lf.getInnerClass().getName(); + } + + // look in imports, etc. + return env.resolveName(name); + } + + /** + * Interpret a qualified class name, which may have further subcomponents.. + * Follow inheritance links, as in: + * class C { class N { } } class D extends C { } ... new D.N() ... + * Ignore outer scopes and packages. + */ + public Identifier resolveInnerClass(Environment env, Identifier nm) { + if (nm.isInner()) throw new CompilerError("inner"); + if (nm.isQualified()) { + Identifier rhead = resolveInnerClass(env, nm.getHead()); + try { + return env.getClassDefinition(rhead). + resolveInnerClass(env, nm.getTail()); + } catch (ClassNotFound ee) { + // return partially-resolved name someone else can fail on + return Identifier.lookupInner(rhead, nm.getTail()); + } + } else { + try { + MemberDefinition f = getInnerClass(env, nm); + if (f != null) { + return f.getInnerClass().getName(); + } + } catch (ClassNotFound ee) { + // a missing superclass, or something catastrophic + } + // Fake a good name for a diagnostic. + return Identifier.lookupInner(this.getName(), nm); + } + } + + /** + * While resolving import directives, the question has arisen: + * does a given inner class exist? If the top-level class exists, + * we ask it about an inner class via this method. + * This method looks only at the literal name of the class, + * and does not attempt to follow inheritance links. + * This is necessary, since at the time imports are being + * processed, inheritance links have not been resolved yet. + * (Thus, an import directive must always spell a class + * name exactly.) + */ + boolean innerClassExists(Identifier nm) { + for (MemberDefinition field = getFirstMatch(nm.getHead()) ; field != null ; field = field.getNextMatch()) { + if (field.isInnerClass()) { + if (field.getInnerClass().isLocal()) { + continue; // ignore this name; it is internally generated + } + return !nm.isQualified() || + field.getInnerClass().innerClassExists(nm.getTail()); + } + } + return false; + } + + /** + * Find any method with a given name. + */ + public MemberDefinition findAnyMethod(Environment env, Identifier nm) throws ClassNotFound { + MemberDefinition f; + for (f = getFirstMatch(nm) ; f != null ; f = f.getNextMatch()) { + if (f.isMethod()) { + return f; + } + } + + // look in the super class + ClassDeclaration sup = getSuperClass(); + if (sup == null) + return null; + return sup.getClassDefinition(env).findAnyMethod(env, nm); + } + + /** + * Given the fact that this class has no method "nm" matching "argTypes", + * find out if the mismatch can be blamed on a particular actual argument + * which disagrees with all of the overloadings. + * If so, return the code (i<<2)+(castOK<<1)+ambig, where + * "i" is the number of the offending argument, and + * "castOK" is 1 if a cast could fix the problem. + * The target type for the argument is returned in margTypeResult[0]. + * If not all methods agree on this type, "ambig" is 1. + * If there is more than one method, the choice of target type is + * arbitrary.

                + * Return -1 if every argument is acceptable to at least one method. + * Return -2 if there are no methods of the required arity. + * The value "start" gives the index of the first argument to begin + * checking. + */ + public int diagnoseMismatch(Environment env, Identifier nm, Type argTypes[], + int start, Type margTypeResult[]) throws ClassNotFound { + int haveMatch[] = new int[argTypes.length]; + Type margType[] = new Type[argTypes.length]; + if (!diagnoseMismatch(env, nm, argTypes, start, haveMatch, margType)) + return -2; + for (int i = start; i < argTypes.length; i++) { + if (haveMatch[i] < 4) { + margTypeResult[0] = margType[i]; + return (i<<2) | haveMatch[i]; + } + } + return -1; + } + + private boolean diagnoseMismatch(Environment env, Identifier nm, Type argTypes[], int start, + int haveMatch[], Type margType[]) throws ClassNotFound { + // look in the current class + boolean haveOne = false; + MemberDefinition f; + for (f = getFirstMatch(nm) ; f != null ; f = f.getNextMatch()) { + if (!f.isMethod()) { + continue; + } + Type fArgTypes[] = f.getType().getArgumentTypes(); + if (fArgTypes.length == argTypes.length) { + haveOne = true; + for (int i = start; i < argTypes.length; i++) { + Type at = argTypes[i]; + Type ft = fArgTypes[i]; + if (env.implicitCast(at, ft)) { + haveMatch[i] = 4; + continue; + } else if (haveMatch[i] <= 2 && env.explicitCast(at, ft)) { + if (haveMatch[i] < 2) margType[i] = null; + haveMatch[i] = 2; + } else if (haveMatch[i] > 0) { + continue; + } + if (margType[i] == null) + margType[i] = ft; + else if (margType[i] != ft) + haveMatch[i] |= 1; + } + } + } + + // constructors are not inherited + if (nm.equals(idInit)) { + return haveOne; + } + + // look in the super class + ClassDeclaration sup = getSuperClass(); + if (sup != null) { + if (sup.getClassDefinition(env).diagnoseMismatch(env, nm, argTypes, start, + haveMatch, margType)) + haveOne = true; + } + return haveOne; + } + + /** + * Add a field (no checks) + */ + protected void addMember(MemberDefinition field) { + //System.out.println("ADD = " + field); + if (firstMember == null) { + firstMember = lastMember = field; + } else if (field.isSynthetic() && field.isFinal() + && field.isVariable()) { + // insert this at the front, because of initialization order + field.nextMember = firstMember; + firstMember = field; + field.nextMatch = fieldHash.get(field.name); + } else { + lastMember.nextMember = field; + lastMember = field; + field.nextMatch = fieldHash.get(field.name); + } + fieldHash.put(field.name, field); + } + + /** + * Add a field (subclasses make checks) + */ + public void addMember(Environment env, MemberDefinition field) { + addMember(field); + if (resolved) { + // a late addition + field.resolveTypeStructure(env); + } + } + + /** + * Find or create an uplevel reference for the given target. + */ + public UplevelReference getReference(LocalMember target) { + for (UplevelReference r = references; r != null; r = r.getNext()) { + if (r.getTarget() == target) { + return r; + } + } + return addReference(target); + } + + private UplevelReference addReference(LocalMember target) { + if (target.getClassDefinition() == this) { + throw new CompilerError("addReference "+target); + } + referencesMustNotBeFrozen(); + UplevelReference r = new UplevelReference(this, target); + references = r.insertInto(references); + return r; + } + + /** + * Return the list of all uplevel references. + */ + public UplevelReference getReferences() { + return references; + } + + /** + * Return the same value as getReferences. + * Also, mark the set of references frozen. + * After that, it is an error to add new references. + */ + public UplevelReference getReferencesFrozen() { + referencesFrozen = true; + return references; + } + + /** + * assertion check + */ + public final void referencesMustNotBeFrozen() { + if (referencesFrozen) { + throw new CompilerError("referencesMustNotBeFrozen "+this); + } + } + + /** + * Get helper method for class literal lookup. + */ + public MemberDefinition getClassLiteralLookup(long fwhere) { + throw new CompilerError("binary class"); + } + + public void loadNested(Environment env) { + throw new CompilerError("loadNested"); + } + + public Iterator getDependencies() { + throw new CompilerError("getDependencies"); + } + + /** + * Add a dependency + */ + public void addDependency(ClassDeclaration c) { + throw new CompilerError("addDependency"); + } + + /** + * Maintain a hash table of local and anonymous classes + * whose internal names are prefixed by the current class. + * The key is the simple internal name, less the prefix. + */ + + public ClassDefinition getLocalClass(String name) { + if (localClasses == null) { + return null; + } else { + return localClasses.get(name); + } + } + + public void addLocalClass(ClassDefinition c, String name) { + if (localClasses == null) { + localClasses = new Hashtable<>(LOCAL_CLASSES_SIZE); + } + localClasses.put(name, c); + } + + + /** + * Print for debugging + */ + public void print(PrintStream out) { + if (isPublic()) { + out.print("public "); + } + if (isInterface()) { + out.print("interface "); + } else { + out.print("class "); + } + out.print(getName() + " "); + if (getSuperClass() != null) { + out.print("extends " + getSuperClass().getName() + " "); + } + if (interfaces.length > 0) { + out.print("implements "); + for (int i = 0 ; i < interfaces.length ; i++) { + if (i > 0) { + out.print(", "); + } + out.print(interfaces[i].getName()); + out.print(" "); + } + } + out.println("{"); + + for (MemberDefinition f = getFirstMember() ; f != null ; f = f.getNextMember()) { + out.print(" "); + f.print(out); + } + + out.println("}"); + } + + /** + * Convert to String + */ + public String toString() { + return getClassDeclaration().toString(); + } + + /** + * After the class has been written to disk, try to free up + * some storage. + */ + public void cleanup(Environment env) { + if (env.dump()) { + env.output("[cleanup " + getName() + "]"); + } + for (MemberDefinition f = getFirstMember() ; f != null ; f = f.getNextMember()) { + f.cleanup(env); + } + // keep "references" around, for the sake of local subclasses + documentation = null; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassDefinitionFactory.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassDefinitionFactory.java new file mode 100644 index 000000000..746688dad --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassDefinitionFactory.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.IOException; +import java.io.InputStream; + +public interface ClassDefinitionFactory { + ClassDefinition loadDefinition(InputStream is, Environment env) throws IOException; +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassFile.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassFile.java new file mode 100644 index 000000000..0f8684a68 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassFile.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1995, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * Abstract class to represent a class file. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +abstract class ClassFile { + /** + * Factory method to create a ClassFile backed by a File. + * + * @param file a File object + * @return a new ClassFile + */ + public static ClassFile newClassFile(File file) { + return new FileClassFile(file); + } + + /** + * Factory method to create a ClassFile backed by a ZipEntry. + * + * @param zf a ZipFile + * @param ze a ZipEntry within the zip file + * @return a new ClassFile + */ + public static ClassFile newClassFile(ZipFile zf, ZipEntry ze) { + return new ZipClassFile(zf, ze); + } + + /** + * Factory method to create a ClassFile backed by a nio Path. + * + * @param path nio Path object + * @return a new ClassFile + */ + public static ClassFile newClassFile(Path path) { + return Files.exists(path)? new PathClassFile(path) : null; + } + + /** + * Returns true if this is zip file entry + */ + public abstract boolean isZipped(); + + /** + * Returns input stream to either regular file or zip file entry + */ + public abstract InputStream getInputStream() throws IOException; + + /** + * Returns true if file exists. + */ + public abstract boolean exists(); + + /** + * Returns true if this is a directory. + */ + public abstract boolean isDirectory(); + + /** + * Return last modification time + */ + public abstract long lastModified(); + + /** + * Get file path. The path for a zip file entry will also include + * the zip file name. + */ + public abstract String getPath(); + + /** + * Get name of file entry excluding directory name + */ + public abstract String getName(); + + /** + * Get absolute name of file entry + */ + public abstract String getAbsoluteName(); + + /** + * Get length of file + */ + public abstract long length(); +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassNotFound.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassNotFound.java new file mode 100644 index 000000000..ed4e6c3ef --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassNotFound.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +/** + * This exception is thrown when a class definition is needed + * and the class can't be found. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@SuppressWarnings("serial") // JDK implementation class +public +class ClassNotFound extends Exception { + /** + * The class that was not found + */ + public Identifier name; + + /** + * Create a ClassNotFound exception + */ + public ClassNotFound(Identifier nm) { + super(nm.toString()); + name = nm; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassPath.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassPath.java new file mode 100644 index 000000000..71084ea7d --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassPath.java @@ -0,0 +1,450 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.DirectoryStream; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.ProviderNotFoundException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * This class is used to represent a class path, which can contain both + * directories and zip files. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ClassPath { + private FileSystem getJrtFileSystem() { + return FileSystems.getFileSystem(URI.create("jrt:/")); + } + + private static final char dirSeparator = File.pathSeparatorChar; + + /** + * The original class path string + */ + private String pathstr; + + /** + * List of class path entries + */ + private ClassPathEntry[] path; + + /** + * Build a class path from the specified path string + */ + ClassPath(String pathstr) { + init(pathstr); + } + + /** + * Build a class path from the specified array of class path + * element strings. This constructor, and the corresponding + * "init" method, were added as part of the fix for 6473331, which + * adds support for Class-Path manifest entries in JAR files to + * rmic. It is conceivable that the value of a Class-Path + * manifest entry will contain a path separator, which would cause + * incorrect behavior if the expanded path were passed to the + * previous constructor as a single path-separator-delimited + * string; use of this constructor avoids that problem. + */ + public ClassPath(String... patharray) { + init(patharray); + } + + private void init(String pathstr) { + int i, j, n; + // Save original class path string + this.pathstr = pathstr; + + if (pathstr.length() == 0) { + this.path = new ClassPathEntry[0]; + } + + // Count the number of path separators + i = n = 0; + while ((i = pathstr.indexOf(dirSeparator, i)) != -1) { + n++; i++; + } + // Build the class path + ClassPathEntry[] path = new ClassPathEntry[n+1]; + + int len = pathstr.length(); + for (i = n = 0; i < len; i = j + 1) { + if ((j = pathstr.indexOf(dirSeparator, i)) == -1) { + j = len; + } + if (i == j) { + path[n++] = new DirClassPathEntry(new File(".")); + } else { + String filename = pathstr.substring(i, j); + File file = new File(filename); + if (file.isFile()) { + try { + ZipFile zip = new ZipFile(file); + path[n++] = new ZipClassPathEntry(zip); + } catch (IOException ignored) { + } + } else { + path[n++] = new DirClassPathEntry(file); + } + } + } + + // add jrt file system at the end + try { + FileSystem fs = getJrtFileSystem(); + path[n++] = new JrtClassPathEntry(fs); + } catch (ProviderNotFoundException ignored) { + // this could happen during jdk build with earlier JDK as bootstrap + } + + // Trim class path to exact size + this.path = new ClassPathEntry[n]; + System.arraycopy(path, 0, this.path, 0, n); + } + + private void init(String[] patharray) { + // Save original class path string + if (patharray.length == 0) { + this.pathstr = ""; + } else { + StringBuilder sb = new StringBuilder(patharray[0]); + for (int i = 1; i < patharray.length; i++) { + sb.append(File.pathSeparatorChar); + sb.append(patharray[i]); + } + this.pathstr = sb.toString(); + } + + // Build the class path + ClassPathEntry[] path = new ClassPathEntry[patharray.length + 1]; + int n = 0; + for (String name : patharray) { + File file = new File(name); + if (file.isFile()) { + try { + ZipFile zip = new ZipFile(file); + path[n++] = new ZipClassPathEntry(zip); + } catch (IOException ignored) { + // Ignore exceptions, at least for now... + } + } else { + path[n++] = new DirClassPathEntry(file); + } + } + + // add jrt file system at the end + try { + FileSystem fs = getJrtFileSystem(); + path[n++] = new JrtClassPathEntry(fs); + } catch (ProviderNotFoundException ignored) { + // this could happen with earlier version of JDK used as bootstrap + } + + // Trim class path to exact size + this.path = new ClassPathEntry[n]; + System.arraycopy(path, 0, this.path, 0, n); + } + + /** + * Find the specified directory in the class path + */ + ClassFile getDirectory(String name) { + return getFile(name, true); + } + + /** + * Load the specified file from the class path + */ + public ClassFile getFile(String name) { + return getFile(name, false); + } + + private final String fileSeparatorChar = "" + File.separatorChar; + + private ClassFile getFile(String name, boolean isDirectory) { + String subdir = name; + String basename = ""; + if (!isDirectory) { + int i = name.lastIndexOf(File.separatorChar); + subdir = name.substring(0, i + 1); + basename = name.substring(i + 1); + } else if (!subdir.equals("") + && !subdir.endsWith(fileSeparatorChar)) { + // zip files are picky about "foo" vs. "foo/". + // also, the getFiles caches are keyed with a trailing / + subdir = subdir + File.separatorChar; + name = subdir; // Note: isDirectory==true & basename=="" + } + for (int i = 0; i < path.length; i++) { + ClassFile cf = path[i].getFile(name, subdir, basename, isDirectory); + if (cf != null) { + return cf; + } + } + return null; + } + + /** + * Returns list of files given a package name and extension. + */ + Enumeration getFiles(String pkg, String ext) { + Hashtable files = new Hashtable<>(); + for (int i = path.length; --i >= 0; ) { + path[i].fillFiles(pkg, ext, files); + } + return files.elements(); + } + + /** + * Release resources. + */ + public void close() throws IOException { + for (int i = path.length; --i >= 0; ) { + path[i].close(); + } + } + + /** + * Returns original class path string + */ + public String toString() { + return pathstr; + } +} + +/** + * A class path entry, which can either be a directory or an open zip file or an open jimage filesystem. + */ +abstract class ClassPathEntry { + abstract ClassFile getFile(String name, String subdir, String basename, boolean isDirectory); + abstract void fillFiles(String pkg, String ext, Hashtable files); + abstract void close() throws IOException; +} + +// a ClassPathEntry that represents a directory +final class DirClassPathEntry extends ClassPathEntry { + private final File dir; + + DirClassPathEntry(File dir) { + this.dir = dir; + } + + private final Hashtable subdirs = new Hashtable<>(29); // cache of sub-directory listings: + private String[] getFiles(String subdir) { + String files[] = subdirs.get(subdir); + if (files == null) { + files = computeFiles(subdir); + subdirs.put(subdir, files); + } + return files; + } + + private String[] computeFiles(String subdir) { + File sd = new File(dir.getPath(), subdir); + String[] files; + if (sd.isDirectory()) { + files = sd.list(); + if (files == null) { + // should not happen, but just in case, fail silently + files = new String[0]; + } + if (files.length == 0) { + String nonEmpty[] = { "" }; + files = nonEmpty; + } + } else { + files = new String[0]; + } + return files; + } + + ClassFile getFile(String name, String subdir, String basename, boolean isDirectory) { + File file = new File(dir.getPath(), name); + String list[] = getFiles(subdir); + if (isDirectory) { + if (list.length > 0) { + return ClassFile.newClassFile(file); + } + } else { + for (int j = 0; j < list.length; j++) { + if (basename.equals(list[j])) { + // Don't bother checking !file.isDir, + // since we only look for names which + // cannot already be packages (foo.java, etc). + return ClassFile.newClassFile(file); + } + } + } + return null; + } + + void fillFiles(String pkg, String ext, Hashtable files) { + String[] list = getFiles(pkg); + for (int j = 0; j < list.length; j++) { + String name = list[j]; + if (name.endsWith(ext)) { + name = pkg + File.separatorChar + name; + File file = new File(dir.getPath(), name); + files.put(name, ClassFile.newClassFile(file)); + } + } + } + + void close() throws IOException { + } +} + +// a ClassPathEntry that represents a .zip or a .jar file +final class ZipClassPathEntry extends ClassPathEntry { + private final ZipFile zip; + + ZipClassPathEntry(ZipFile zip) { + this.zip = zip; + } + + void close() throws IOException { + zip.close(); + } + + ClassFile getFile(String name, String subdir, String basename, boolean isDirectory) { + String newname = name.replace(File.separatorChar, '/'); + ZipEntry entry = zip.getEntry(newname); + return entry != null? ClassFile.newClassFile(zip, entry) : null; + } + + void fillFiles(String pkg, String ext, Hashtable files) { + Enumeration e = zip.entries(); + while (e.hasMoreElements()) { + ZipEntry entry = (ZipEntry)e.nextElement(); + String name = entry.getName(); + name = name.replace('/', File.separatorChar); + if (name.startsWith(pkg) && name.endsWith(ext)) { + files.put(name, ClassFile.newClassFile(zip, entry)); + } + } + } +} + +// a ClassPathEntry that represents jrt file system +final class JrtClassPathEntry extends ClassPathEntry { + private final FileSystem fs; + // package name to package directory path mapping (lazily filled) + private final Map pkgDirs; + + JrtClassPathEntry(FileSystem fs) { + this.fs = fs; + this.pkgDirs = new HashMap<>(); + } + + void close() throws IOException { + } + + // from pkgName (internal separator '/') to it's Path in jrtfs + synchronized Path getPackagePath(String pkgName) throws IOException { + // check the cache first + if (pkgDirs.containsKey(pkgName)) { + return pkgDirs.get(pkgName); + } + + Path pkgLink = fs.getPath("/packages/" + pkgName.replace('/', '.')); + // check if /packages/$PACKAGE directory exists + if (Files.isDirectory(pkgLink)) { + try (DirectoryStream stream = Files.newDirectoryStream(pkgLink)) { + for (Path p : stream) { + // find first symbolic link to module directory + if (Files.isSymbolicLink(p)) { + Path modDir = Files.readSymbolicLink(p); + if (Files.isDirectory(modDir)) { + // get package subdirectory under /modules/$MODULE/ + Path pkgDir = fs.getPath(modDir.toString() + "/" + pkgName); + if (Files.isDirectory(pkgDir)) { + // it is a package directory only if contains + // at least one .class file + try (DirectoryStream pstream = + Files.newDirectoryStream(pkgDir)) { + for (Path f : pstream) { + if (Files.isRegularFile(f) + && f.toString().endsWith(".class")) { + pkgDirs.put(pkgName, pkgDir); + return pkgDir; + } + } + } + } + } + } + } + } + } + + return null; + } + + // fully qualified (internal) class name to it's Path in jrtfs + Path getClassPath(String clsName) throws IOException { + int index = clsName.lastIndexOf('/'); + if (index == -1) { + return null; + } + Path pkgPath = getPackagePath(clsName.substring(0, index)); + return pkgPath == null? null : fs.getPath(pkgPath + "/" + clsName.substring(index + 1)); + } + + ClassFile getFile(String name, String subdir, String basename, boolean isDirectory) { + try { + name = name.replace(File.separatorChar, '/'); + Path cp = getClassPath(name); + return cp == null? null : ClassFile.newClassFile(cp); + } catch (IOException ioExp) { + throw new RmicUncheckedIOException(ioExp); + } + } + + void fillFiles(String pkg, String ext, Hashtable files) { + Path dir; + try { + dir = getPackagePath(pkg); + if (dir == null) { + return; + } + } catch (IOException ioExp) { + throw new RmicUncheckedIOException(ioExp); + } + + try (DirectoryStream stream = Files.newDirectoryStream(dir)) { + for (Path p : stream) { + String name = p.toString(); + name = name.replace('/', File.separatorChar); + if (name.startsWith(pkg) && name.endsWith(ext)) { + files.put(name, ClassFile.newClassFile(p)); + } + } + } catch (IOException ioExp) { + throw new RmicUncheckedIOException(ioExp); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassType.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassType.java new file mode 100644 index 000000000..e36dc844b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ClassType.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import org.glassfish.rmic.TypeCode; + +/** + * This class represents an Java class type. + * It overrides the relevant methods in class Type. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ +public final +class ClassType extends Type { + private static final char QUOTE = '"'; + /** + * The fully qualified class name. + */ + Identifier className; + + /** + * Construct a class type. Use Type.tClass to create + * a new class type. + */ + ClassType(String typeSig, Identifier className) { + super(TypeCode.CLASS, typeSig); + this.className = className; + } + + public Identifier getClassName() { + return className; + } + + public String typeString(String id, boolean abbrev, boolean ret) { + String s = (abbrev ? getClassName().getFlatName() : + Identifier.lookup(getClassName().getQualifier(), + getClassName().getFlatName())).toString(); + return (id.length() > 0) ? s + " " + id : s; + } + + @Override + public String toStringValue(Object value) { + if (value == null || isStringType()) { + return null; + } else { + return QUOTE + value.toString() + QUOTE; + } + } + + private boolean isStringType() { + return !className.toString().equals(String.class.getName()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/CompilerError.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/CompilerError.java new file mode 100644 index 000000000..e4ff2214f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/CompilerError.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +/** + * This exception is thrown when an internal compiler error occurs + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@SuppressWarnings("serial") // JDK implementation class +public +class CompilerError extends Error { + Throwable e; + + /** + * Constructor + */ + public CompilerError(String msg) { + super(msg); + this.e = this; + } + + /** + * Create an exception given another exception. + */ + public CompilerError(Exception e) { + super(e.getMessage()); + this.e = e; + } + + public void printStackTrace() { + if (e == this) + super.printStackTrace(); + else + e.printStackTrace(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Constants.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Constants.java new file mode 100644 index 000000000..fb5afcb5b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Constants.java @@ -0,0 +1,575 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +/** + * This interface defines constant that are used + * throughout the compiler. It inherits from RuntimeConstants, + * which is an autogenerated class that contains contstants + * defined in the interpreter. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ + +public +interface Constants extends RuntimeConstants { + + /* + * Enable/disable inclusion of certain debug tracing code in the + * compiler. When included, the tracing code may be selectively + * enabled at runtime, otherwise we save the space/time overhead. + * Should normally be 'false' for a release version. + */ + public static final boolean tracing = true; + + /* + * Frequently used identifiers + */ + Identifier idAppend = Identifier.lookup("append"); + Identifier idClassInit = Identifier.lookup(""); + Identifier idCode = Identifier.lookup("Code"); + Identifier idInit = Identifier.lookup(""); + Identifier idLength = Identifier.lookup("length"); + Identifier idNull = Identifier.lookup(""); + Identifier idStar = Identifier.lookup("*"); + Identifier idSuper = Identifier.lookup("super"); + Identifier idThis = Identifier.lookup("this"); + Identifier idClass = Identifier.lookup("class"); + Identifier idToString = Identifier.lookup("toString"); + Identifier idValueOf = Identifier.lookup("valueOf"); + Identifier idNew = Identifier.lookup("new"); + Identifier idGetClass = Identifier.lookup("getClass"); + Identifier idTYPE = Identifier.lookup("TYPE"); + Identifier idFinallyReturnValue = Identifier.lookup(""); + + Identifier idJavaLang = Identifier.lookup("java.lang"); + + Identifier idJavaLangCloneable = Identifier.lookup("java.lang.Cloneable"); + + Identifier idJavaLangError = Identifier.lookup("java.lang.Error"); + Identifier idJavaLangException = Identifier.lookup("java.lang.Exception"); + Identifier idJavaLangObject = Identifier.lookup("java.lang.Object"); + Identifier idJavaLangClass = Identifier.lookup("java.lang.Class"); + Identifier idJavaLangRuntimeException = + Identifier.lookup("java.lang.RuntimeException"); + Identifier idJavaLangString = Identifier.lookup("java.lang.String"); + Identifier idJavaLangStringBuffer = + Identifier.lookup("java.lang.StringBuffer"); + Identifier idJavaLangThrowable = Identifier.lookup("java.lang.Throwable"); + + Identifier idJavaIoSerializable = Identifier.lookup("java.io.Serializable"); + + + Identifier idConstantValue = Identifier.lookup("ConstantValue"); + Identifier idLocalVariableTable = Identifier.lookup("LocalVariableTable"); + Identifier idLineNumberTable = Identifier.lookup("LineNumberTable"); +// JCOV + Identifier idCoverageTable = Identifier.lookup("CoverageTable"); +// end JCOV + Identifier idSourceFile = Identifier.lookup("SourceFile"); + Identifier idDocumentation = Identifier.lookup("Documentation"); + Identifier idDeprecated = Identifier.lookup("Deprecated"); + Identifier idSynthetic = Identifier.lookup("Synthetic"); + Identifier idExceptions = Identifier.lookup("Exceptions"); + Identifier idInnerClasses = Identifier.lookup("InnerClasses"); + + /* methods we need to know about */ + Identifier idClone = Identifier.lookup("clone"); + + + /* This is not a real signature marker, since it is also + * an identifier constituent character. + */ + char SIGC_INNERCLASS = '$'; + String SIG_INNERCLASS = "$"; + + String prefixThis = "this$"; + String prefixVal = "val$"; + String prefixLoc = "loc$"; + String prefixAccess = "access$"; + String prefixClass = "class$"; + String prefixArray = "array$"; + + /* + * Flags + */ + int F_VERBOSE = 1 << 0; + int F_DUMP = 1 << 1; + int F_WARNINGS = 1 << 2; + + // The meaning of -g has changed, so F_DEBUG flag is removed. + // public static final int F_DEBUG = 1 << 3; + int F_DEBUG_LINES = 1 << 12; + int F_DEBUG_VARS = 1 << 13; + int F_DEBUG_SOURCE = 1 << 18; + + // The meaning of -O has changed, so F_OPTIMIZE flag is removed. + // public static final int F_OPTIMIZE = 1 << 4; + int F_OPT = 1 << 14; + int F_OPT_INTERCLASS = 1 << 15; + + int F_DEPENDENCIES = 1 << 5; + +// JCOV + int F_COVERAGE = 1 << 6; + int F_COVDATA = 1 << 7; +// end JCOV + + int F_DEPRECATION = 1 << 9; + int F_PRINT_DEPENDENCIES = 1 << 10; + int F_VERSION12 = 1 << 11; + + + int F_ERRORSREPORTED = 1 << 16; + + int F_STRICTDEFAULT = 1 << 17; + + /* + * Modifiers. + * + * There has been much confusion regarding modifiers. There + * are a number of distinct usages: + * + * - in classfiles to annotate classes, as per JVM pg. 102. + * - in classfiles to annotate methods, as per JVM pg. 104. + * - in classfiles to annotate InnerClass attributes, as per + * http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses + * - in the compiler to record java source level modifiers, + * as per JLS pg. 157 et al., plus misc. info such as whether + * a method is deprecated + * - in the JVM to record misc. info, such as whether a method has + * has been compiled + * + * To make matters worse, the terms "access flags" and "modifiers" + * are often used interchangably, and some information that might + * make sense as a flag is expressed using attributes (ie. Synthetic). + * + * The constants defined herein have been divided by whether they + * make sense only within the compiler (M_* and MM_*) or whether + * they only make sense to the JVM (ACC_* and ACCM_*). At an earlier + * time these were all lumped together. Future maintenance should + * strive to keep the distinction clear. + * + * Note that modifier M_STRICTFP is not in general recoverable from + * the ACC_STRICT bit in classfiles. + * + * Note also that the modifiers M_LOCAL and M_ANONYMOUS do not appear + * in the InnerClass attribute, as they are above the first 16 bits. + */ + + // Modifiers meaningful to both Java source and the JVM. These + // have been kept the same bit in the M_* and ACC_* forms + // to avoid destabilizing the compiler. + int M_PUBLIC = ACC_PUBLIC; + int M_PRIVATE = ACC_PRIVATE; + int M_PROTECTED = ACC_PROTECTED; + int M_STATIC = ACC_STATIC; + int M_TRANSIENT = ACC_TRANSIENT; + int M_SYNCHRONIZED = ACC_SYNCHRONIZED; // collides with ACC_SUPER + int M_ABSTRACT = ACC_ABSTRACT; + int M_NATIVE = ACC_NATIVE; + int M_FINAL = ACC_FINAL; + int M_VOLATILE = ACC_VOLATILE; + int M_INTERFACE = ACC_INTERFACE; + + // Modifiers not meaningful to the JVM. The JVM only allows 16 bits + // for modifiers, so keeping these in the unusable bits after the first + // 16 is a good idea. + int M_ANONYMOUS = 0x00010000; + int M_LOCAL = 0x00020000; + int M_DEPRECATED = 0x00040000; + int M_SYNTHETIC = 0x00080000; + int M_INLINEABLE = 0x00100000; + + int M_STRICTFP = 0x00200000; + + String paraDeprecated = "@deprecated"; + + // Masks for modifiers that apply to Java source code + int MM_CLASS = M_PUBLIC + | M_INTERFACE + | M_FINAL + | M_ABSTRACT + | M_STRICTFP; + int MM_MEMBER = M_PUBLIC + | M_PRIVATE + | M_PROTECTED + | M_FINAL + | M_STATIC; + int MM_FIELD = MM_MEMBER + | M_TRANSIENT + | M_VOLATILE; + int MM_METHOD = MM_MEMBER + | M_SYNCHRONIZED + | M_ABSTRACT + | M_NATIVE + | M_STRICTFP; + + // Masks for modifiers that apply to class files. + // Note that the M_SYNTHETIC modifier is never written out to a class file. + // Synthetic members are indicated using the "Synthetic" attribute. + int ACCM_CLASS = ACC_PUBLIC + | ACC_INTERFACE + | ACC_FINAL + | ACC_ABSTRACT + | ACC_SUPER + | ACC_STRICT; + int ACCM_MEMBER = ACC_PUBLIC + | ACC_PRIVATE + | ACC_PROTECTED + | ACC_FINAL + | ACC_STATIC; + // The M_ANONYMOUS and M_LOCAL modifiers are not mentioned in the + // inner classes specification and are never written to classfiles. + // Also note that ACC_SUPER should never be set in an InnerClass + // attribute. + int ACCM_INNERCLASS = ACC_PUBLIC + | ACC_PRIVATE + | ACC_PROTECTED + | ACC_STATIC + | ACC_ABSTRACT + | ACC_FINAL + | ACC_INTERFACE + | ACC_STRICT; + int ACCM_FIELD = ACCM_MEMBER + | ACC_TRANSIENT + | ACC_VOLATILE; + int ACCM_METHOD = ACCM_MEMBER + | ACC_SYNCHRONIZED + | ACC_ABSTRACT + | ACC_NATIVE + | ACC_STRICT; + + /* + * Type codes + */ + int TC_BOOLEAN = 0; + int TC_BYTE = 1; + int TC_CHAR = 2; + int TC_SHORT = 3; + int TC_INT = 4; + int TC_LONG = 5; + int TC_FLOAT = 6; + int TC_DOUBLE = 7; + int TC_NULL = 8; + int TC_ARRAY = 9; + int TC_CLASS = 10; + int TC_VOID = 11; + int TC_METHOD = 12; + int TC_ERROR = 13; + +// JCOV + /* + * Cover's types + */ + int CT_FIRST_KIND = 1; + int CT_METHOD = 1; + int CT_FIKT_METHOD = 2; + int CT_BLOCK = 3; + int CT_FIKT_RET = 4; + int CT_CASE = 5; + int CT_SWITH_WO_DEF = 6; + int CT_BRANCH_TRUE = 7; + int CT_BRANCH_FALSE = 8; + int CT_LAST_KIND = 8; +// end JCOV + + /* + * Type Masks + */ + int TM_NULL = 1 << TC_NULL; + int TM_VOID = 1 << TC_VOID; + int TM_BOOLEAN = 1 << TC_BOOLEAN; + int TM_BYTE = 1 << TC_BYTE; + int TM_CHAR = 1 << TC_CHAR; + int TM_SHORT = 1 << TC_SHORT; + int TM_INT = 1 << TC_INT; + int TM_LONG = 1 << TC_LONG; + int TM_FLOAT = 1 << TC_FLOAT; + int TM_DOUBLE = 1 << TC_DOUBLE; + int TM_ARRAY = 1 << TC_ARRAY; + int TM_CLASS = 1 << TC_CLASS; + int TM_METHOD = 1 << TC_METHOD; + int TM_ERROR = 1 << TC_ERROR; + + int TM_INT32 = TM_BYTE | TM_SHORT | TM_CHAR | TM_INT; + int TM_NUM32 = TM_INT32 | TM_FLOAT; + int TM_NUM64 = TM_LONG | TM_DOUBLE; + int TM_INTEGER = TM_INT32 | TM_LONG; + int TM_REAL = TM_FLOAT | TM_DOUBLE; + int TM_NUMBER = TM_INTEGER | TM_REAL; + int TM_REFERENCE = TM_ARRAY | TM_CLASS | TM_NULL; + + /* + * Class status + */ + int CS_UNDEFINED = 0; + int CS_UNDECIDED = 1; + int CS_BINARY = 2; + int CS_SOURCE = 3; + int CS_PARSED = 4; + int CS_CHECKED = 5; + int CS_COMPILED = 6; + int CS_NOTFOUND = 7; + + + /* + * Attributes + */ + int ATT_ALL = 0xFFFFFFFF; + int ATT_CODE = 1 << 1; + int ATT_ALLCLASSES = 1 << 2; + + /* + * Number of bits used in file offsets. The line number and + * file offset are concatenated into a long, with enough room + * for other information to be added later if desired (such as + * token lengths). For the moment explicit bit manipulations + * are used to modify the fields. This makes sense for efficiency + * but at some point these ought to be better encapsulated. + */ + int WHEREOFFSETBITS = 32; + long MAXFILESIZE = (1L << WHEREOFFSETBITS) - 1; + long MAXLINENUMBER = (1L << (64 - WHEREOFFSETBITS)) - 1; + + /* + * Operators + */ + int COMMA = 0; + int ASSIGN = 1; + + int ASGMUL = 2; + int ASGDIV = 3; + int ASGREM = 4; + int ASGADD = 5; + int ASGSUB = 6; + int ASGLSHIFT = 7; + int ASGRSHIFT = 8; + int ASGURSHIFT = 9; + int ASGBITAND = 10; + int ASGBITOR = 11; + int ASGBITXOR = 12; + + int COND = 13; + int OR = 14; + int AND = 15; + int BITOR = 16; + int BITXOR = 17; + int BITAND = 18; + int NE = 19; + int EQ = 20; + int GE = 21; + int GT = 22; + int LE = 23; + int LT = 24; + int INSTANCEOF = 25; + int LSHIFT = 26; + int RSHIFT = 27; + int URSHIFT = 28; + int ADD = 29; + int SUB = 30; + int DIV = 31; + int REM = 32; + int MUL = 33; + int CAST = 34; // (x)y + int POS = 35; // +x + int NEG = 36; // -x + int NOT = 37; + int BITNOT = 38; + int PREINC = 39; // ++x + int PREDEC = 40; // --x + int NEWARRAY = 41; + int NEWINSTANCE = 42; + int NEWFROMNAME = 43; + int POSTINC = 44; // x++ + int POSTDEC = 45; // x-- + int FIELD = 46; + int METHOD = 47; // x(y) + int ARRAYACCESS = 48; // x[y] + int NEW = 49; + int INC = 50; + int DEC = 51; + + int CONVERT = 55; // implicit conversion + int EXPR = 56; // (x) + int ARRAY = 57; // {x, y, ...} + int GOTO = 58; + + /* + * Value tokens + */ + int IDENT = 60; + int BOOLEANVAL = 61; + int BYTEVAL = 62; + int CHARVAL = 63; + int SHORTVAL = 64; + int INTVAL = 65; + int LONGVAL = 66; + int FLOATVAL = 67; + int DOUBLEVAL = 68; + int STRINGVAL = 69; + + /* + * Type keywords + */ + int BYTE = 70; + int CHAR = 71; + int SHORT = 72; + int INT = 73; + int LONG = 74; + int FLOAT = 75; + int DOUBLE = 76; + int VOID = 77; + int BOOLEAN = 78; + + /* + * Expression keywords + */ + int TRUE = 80; + int FALSE = 81; + int THIS = 82; + int SUPER = 83; + int NULL = 84; + + /* + * Statement keywords + */ + int IF = 90; + int ELSE = 91; + int FOR = 92; + int WHILE = 93; + int DO = 94; + int SWITCH = 95; + int CASE = 96; + int DEFAULT = 97; + int BREAK = 98; + int CONTINUE = 99; + int RETURN = 100; + int TRY = 101; + int CATCH = 102; + int FINALLY = 103; + int THROW = 104; + int STAT = 105; + int EXPRESSION = 106; + int DECLARATION = 107; + int VARDECLARATION = 108; + + /* + * Declaration keywords + */ + int IMPORT = 110; + int CLASS = 111; + int EXTENDS = 112; + int IMPLEMENTS = 113; + int INTERFACE = 114; + int PACKAGE = 115; + + /* + * Modifier keywords + */ + int PRIVATE = 120; + int PUBLIC = 121; + int PROTECTED = 122; + int CONST = 123; + int STATIC = 124; + int TRANSIENT = 125; + int SYNCHRONIZED = 126; + int NATIVE = 127; + int FINAL = 128; + int VOLATILE = 129; + int ABSTRACT = 130; + int STRICTFP = 131; + + /* + * Punctuation + */ + int SEMICOLON = 135; + int COLON = 136; + int QUESTIONMARK = 137; + int LBRACE = 138; + int RBRACE = 139; + int LPAREN = 140; + int RPAREN = 141; + int LSQBRACKET = 142; + int RSQBRACKET = 143; + int THROWS = 144; + + /* + * Special tokens + */ + int ERROR = 145; // an error + int COMMENT = 146; // not used anymore. + int TYPE = 147; + int LENGTH = 148; + int INLINERETURN = 149; + int INLINEMETHOD = 150; + int INLINENEWINSTANCE = 151; + + /* + * Operator precedence + */ + int opPrecedence[] = { + 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 12, 13, 14, 15, 16, 17, 18, + 18, 19, 19, 19, 19, 19, 20, 20, 20, 21, + 21, 22, 22, 22, 23, 24, 24, 24, 24, 24, + 24, 25, 25, 26, 26, 26, 26, 26, 26 + }; + + /* + * Operator names + */ + String opNames[] = { + ",", "=", "*=", "/=", "%=", + "+=", "-=", "<<=", ">>=", ">>>=", + "&=", "|=", "^=", "?:", "||", + "&&", "|", "^", "&", "!=", + "==", ">=", ">", "<=", "<", + "instanceof", "<<", ">>", ">>>", "+", + "-", "/", "%", "*", "cast", + "+", "-", "!", "~", "++", + "--", "new", "new", "new", "++", + "--", "field","method","[]", "new", + "++", "--", null, null, null, + + "convert", "expr", "array", "goto", null, + + "Identifier", "boolean", "byte", "char", "short", + "int", "long", "float", "double", "string", + + "byte", "char", "short", "int", "long", + "float", "double", "void", "boolean", null, + + "true", "false", "this", "super", "null", + null, null, null, null, null, + + "if", "else", "for", "while","do", + "switch", "case", "default", "break", "continue", + "return", "try", "catch", "finally", "throw", + "stat", "expression", "declaration", "declaration", null, + + "import", "class", "extends", "implements", "interface", + "package", null, null, null, null, + + "private", "public", "protected", "const", "static", + "transient", "synchronized", "native", "final", "volatile", + "abstract", "strictfp", null, null, null, + + ";", ":", "?", "{", "}", + "(", ")", "[", "]", "throws", + "error", "comment", "type", "length", "inline-return", + "inline-method", "inline-new" + }; +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Environment.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Environment.java new file mode 100644 index 000000000..129c58eb1 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Environment.java @@ -0,0 +1,983 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.File; +import java.io.IOException; + +//JCOV +//end JCOV + +/** + * This class defines the environment for a compilation. + * It is used to load classes, resolve class names and + * report errors. It is an abstract class, a subclass + * must define implementations for some of the functions.

                + * + * An environment has a source object associated with it. + * This is the thing against which errors are reported, it + * is usually a file name, a field or a class.

                + * + * Environments can be nested to change the source object.

                + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ + +public class Environment implements Constants { + /** + * The actual environment to which everything is forwarded. + */ + Environment env; + + /** + * External character encoding name + */ + String encoding; + + /** + * The object that is currently being parsed/compiled. + * It is either a file name (String) or a field (MemberDefinition) + * or a class (ClassDeclaration or ClassDefinition). + */ + Object source; + + public Environment(Environment env, Object source) { + if (env != null && env.env != null && env.getClass() == this.getClass()) + env = env.env; // a small optimization + this.env = env; + this.source = source; + } + public Environment() { + this(null, null); + } + + /** + * Tells whether an Identifier refers to a package which should be + * exempt from the "exists" check in Imports#resolve(). + */ + public boolean isExemptPackage(Identifier id) { + return env.isExemptPackage(id); + } + + /** + * Return a class declaration given a fully qualified class name. + */ + public ClassDeclaration getClassDeclaration(Identifier nm) { + return env.getClassDeclaration(nm); + } + + /** + * Return a class definition given a fully qualified class name. + *

                + * Should be called only with 'internal' class names, i.e., the result + * of a call to 'resolveName' or a synthetic class name. + */ + public final ClassDefinition getClassDefinition(Identifier nm) throws ClassNotFound { + if (nm.isInner()) { + ClassDefinition c = getClassDefinition(nm.getTopName()); + Identifier tail = nm.getFlatName(); + walkTail: + while (tail.isQualified()) { + tail = tail.getTail(); + Identifier head = tail.getHead(); + //System.out.println("CLASS: " + c + " HEAD: " + head + " TAIL: " + tail); + String hname = head.toString(); + // If the name is of the form 'ClassName.N$localName', where N is + // a number, the field 'N$localName' may not necessarily be a member + // of the class named by 'ClassName', but might be a member of some + // inaccessible class contained within it. We use 'getLocalClass' + // to do the lookup in this case. This is part of a fix for bugid + // 4054523 and 4030421. See also 'BatchEnvironment.makeClassDefinition'. + // This should also work for anonymous class names of the form + // 'ClassName.N'. Note that the '.' qualifications get converted to + // '$' characters when determining the external name of the class and + // the name of the class file. + if (hname.length() > 0 + && Character.isDigit(hname.charAt(0))) { + ClassDefinition localClass = c.getLocalClass(hname); + if (localClass != null) { + c = localClass; + continue walkTail; + } + } else { + for (MemberDefinition f = c.getFirstMatch(head); + f != null; f = f.getNextMatch()) { + if (f.isInnerClass()) { + c = f.getInnerClass(); + continue walkTail; + } + } + } + throw new ClassNotFound(Identifier.lookupInner(c.getName(), head)); + } + //System.out.println("FOUND " + c + " FOR " + nm); + return c; + } + return getClassDeclaration(nm).getClassDefinition(this); + } + + + /** + * Return a class declaration given a type. Only works for + * class types. + */ + public ClassDeclaration getClassDeclaration(Type t) { + return getClassDeclaration(t.getClassName()); + } + + /** + * Return a class definition given a type. Only works for + * class types. + */ + public final ClassDefinition getClassDefinition(Type t) throws ClassNotFound { + return getClassDefinition(t.getClassName()); + } + + /** + * Check if a class exists (without actually loading it). + * (Since inner classes cannot in general be examined without + * loading source, this method does not accept inner names.) + */ + public boolean classExists(Identifier nm) { + return env.classExists(nm); + } + + public final boolean classExists(Type t) { + return !t.isType(TC_CLASS) || classExists(t.getClassName()); + } + + /** + * Get the package path for a package + */ + public Package getPackage(Identifier pkg) throws IOException { + return env.getPackage(pkg); + } + + /** + * Load the definition of a class. + */ + public void loadDefinition(ClassDeclaration c) { + env.loadDefinition(c); + } + + /** + * Return the source of the environment (ie: the thing being compiled/parsed). + */ + public final Object getSource() { + return source; + } + + /** + * Resolve a type. Make sure that all the classes referred to by + * the type have a definition. Report errors. Return true if + * the type is well-formed. Presently used for types appearing + * in member declarations, which represent named types internally as + * qualified identifiers. Type names appearing in local variable + * declarations and within expressions are represented as identifier + * or field expressions, and are resolved by 'toType', which delegates + * handling of the non-inner portion of the name to this method. + *

                + * In 'toType', the various stages of qualification are represented by + * separate AST nodes. Here, we are given a single identifier which + * contains the entire qualification structure. It is not possible in + * general to set the error location to the exact position of a component + * that is in error, so an error message must refer to the entire qualified + * name. An attempt to keep track of the string length of the components of + * the name and to offset the location accordingly fails because the initial + * prefix of the name may have been rewritten by an earlier call to + * 'resolveName'. See 'SourceMember.resolveTypeStructure'. The situation + * is actually even worse than this, because only a single location is + * passed in for an entire declaration, which may contain many type names. + * All error messages are thus poorly localized. These checks should be + * done while traversing the parse tree for the type, not the type descriptor. + *

                + * DESIGN NOTE: + * As far as I can tell, the two-stage resolution of names represented in + * string form is an artifact of the late implementation of inner classes + * and the use of mangled names internally within the compiler. All + * qualified names should have their hiearchical structure made explicit + * in the parse tree at the phase at which they are presented for static + * semantic checking. This would affect class names appearing in 'extends', + * 'implements', and 'throws' clauses, as well as in member declarations. + */ + public boolean resolve(long where, ClassDefinition c, Type t) { + switch (t.getTypeCode()) { + case TC_CLASS: { + ClassDefinition def; + try { + Identifier nm = t.getClassName(); + if (!nm.isQualified() && !nm.isInner() && !classExists(nm)) { + resolve(nm); // elicit complaints about ambiguity + } + def = getQualifiedClassDefinition(where, nm, c, false); + if (!c.canAccess(this, def.getClassDeclaration())) { + // Reported error location may be imprecise + // if the name is qualified. + error(where, "cant.access.class", def); + return true; // return false later + } + def.noteUsedBy(c, where, env); + } catch (AmbiguousClass ee) { + error(where, "ambig.class", ee.name1, ee.name2); + return false; + } catch (ClassNotFound e) { + // For now, report "class.and.package" only when the code + // is going to fail anyway. + try { + if (e.name.isInner() && + getPackage(e.name.getTopName()).exists()) { + env.error(where, "class.and.package", + e.name.getTopName()); + } + } catch (IOException ee) { + env.error(where, "io.exception", "package check"); + } + // This error message is also emitted for 'new' expressions. + // error(where, "class.not.found", e.name, "declaration"); + error(where, "class.not.found.no.context", e.name); + return false; + } + return true; + } + + case TC_ARRAY: + return resolve(where, c, t.getElementType()); + + case TC_METHOD: + boolean ok = resolve(where, c, t.getReturnType()); + Type args[] = t.getArgumentTypes(); + for (int i = args.length ; i-- > 0 ; ) { + ok &= resolve(where, c, args[i]); + } + return ok; + } + return true; + } + + /** + * Given its fully-qualified name, verify that a class is defined and accessible. + * Used to check components of qualified names in contexts where a class is expected. + * Like 'resolve', but is given a single type name, not a type descriptor. + */ + public boolean resolveByName(long where, ClassDefinition c, Identifier nm) { + return resolveByName(where, c, nm, false); + } + + public boolean resolveExtendsByName(long where, ClassDefinition c, Identifier nm) { + return resolveByName(where, c, nm, true); + } + + private boolean resolveByName(long where, ClassDefinition c, + Identifier nm, boolean isExtends) { + ClassDefinition def; + try { + if (!nm.isQualified() && !nm.isInner() && !classExists(nm)) { + resolve(nm); // elicit complaints about ambiguity + } + def = getQualifiedClassDefinition(where, nm, c, isExtends); + ClassDeclaration decl = def.getClassDeclaration(); + if (!((!isExtends && c.canAccess(this, decl)) + || + (isExtends && c.extendsCanAccess(this, decl)))) { + error(where, "cant.access.class", def); + return true; // return false later + } + } catch (AmbiguousClass ee) { + error(where, "ambig.class", ee.name1, ee.name2); + return false; + } catch (ClassNotFound e) { + // For now, report "class.and.package" only when the code + // is going to fail anyway. + try { + if (e.name.isInner() && + getPackage(e.name.getTopName()).exists()) { + env.error(where, "class.and.package", + e.name.getTopName()); + } + } catch (IOException ee) { + env.error(where, "io.exception", "package check"); + } + error(where, "class.not.found", e.name, "type name"); + return false; + } + return true; + } + + /** + * Like 'getClassDefinition(env)', but check access on each component. + * Currently called only by 'resolve' above. It is doubtful that calls + * to 'getClassDefinition(env)' are appropriate now. + */ + public final ClassDefinition + getQualifiedClassDefinition(long where, + Identifier nm, + ClassDefinition ctxClass, + boolean isExtends) throws ClassNotFound { + if (nm.isInner()) { + ClassDefinition c = getClassDefinition(nm.getTopName()); + Identifier tail = nm.getFlatName(); + walkTail: + while (tail.isQualified()) { + tail = tail.getTail(); + Identifier head = tail.getHead(); + // System.out.println("CLASS: " + c + " HEAD: " + head + " TAIL: " + tail); + String hname = head.toString(); + // Handle synthesized names of local and anonymous classes. + // See 'getClassDefinition(env)' above. + if (hname.length() > 0 + && Character.isDigit(hname.charAt(0))) { + ClassDefinition localClass = c.getLocalClass(hname); + if (localClass != null) { + c = localClass; + continue walkTail; + } + } else { + for (MemberDefinition f = c.getFirstMatch(head); + f != null; f = f.getNextMatch()) { + if (f.isInnerClass()) { + ClassDeclaration rdecl = c.getClassDeclaration(); + c = f.getInnerClass(); + ClassDeclaration fdecl = c.getClassDeclaration(); + // This check is presumably applicable even if the + // original source-code name (expanded by 'resolveNames') + // was a simple, unqualified name. Hopefully, JLS 2e + // will clarify the matter. + if ((!isExtends + && !ctxClass.canAccess(env, fdecl)) + || + (isExtends + && !ctxClass.extendsCanAccess(env, fdecl))) { + // Reported error location is imprecise. + env.error(where, "no.type.access", head, rdecl, ctxClass); + } + // The JLS 6.6.2 restrictions on access to protected members + // depend in an essential way upon the syntactic form of the name. + // Since the compiler has previously expanded the class names + // here into fully-qualified form ('resolveNames'), this check + // cannot be performed here. Unfortunately, the original names + // are clobbered during 'basicCheck', which is also the phase that + // resolves the inheritance structure, required to implement the + // access restrictions. Pending a large-scale revision of the + // name-resolution machinery, we forgo this check, with the result + // that the JLS 6.6.2 restrictions are not enforced for some cases + // of qualified access to inner classes. Some qualified names are + // resolved elsewhere via a different mechanism, and will be + // treated correctly -- see 'FieldExpression.checkCommon'. + /*---------------------------------------* + if (f.isProtected()) { + Type rty = Type.tClass(rdecl.getName()); // hack + if (!ctxClass.protectedAccess(env, f, rty)) { + // Reported error location is imprecise. + env.error(where, "invalid.protected.type.use", + head, ctxClass, rty); + } + } + *---------------------------------------*/ + continue walkTail; + } + } + } + throw new ClassNotFound(Identifier.lookupInner(c.getName(), head)); + } + //System.out.println("FOUND " + c + " FOR " + nm); + return c; + } + return getClassDeclaration(nm).getClassDefinition(this); + } + + /** + * Resolve the names within a type, returning the adjusted type. + * Adjust class names to reflect scoping. + * Do not report errors. + *

                + * NOTE: It would be convenient to check for errors here, such as + * verifying that each component of a qualified name exists and is + * accessible. Why must this be done in a separate phase? + *

                + * If the 'synth' argument is true, indicating that the member whose + * type is being resolved is synthetic, names are resolved with respect + * to the package scope. (Fix for 4097882) + */ + public Type resolveNames(ClassDefinition c, Type t, boolean synth) { + if (tracing) dtEvent("Environment.resolveNames: " + c + ", " + t); + switch (t.getTypeCode()) { + case TC_CLASS: { + Identifier name = t.getClassName(); + Identifier rname; + if (synth) { + rname = resolvePackageQualifiedName(name); + } else { + rname = c.resolveName(this, name); + } + if (name != rname) { + t = Type.tClass(rname); + } + break; + } + + case TC_ARRAY: + t = Type.tArray(resolveNames(c, t.getElementType(), synth)); + break; + + case TC_METHOD: { + Type ret = t.getReturnType(); + Type rret = resolveNames(c, ret, synth); + Type args[] = t.getArgumentTypes(); + Type rargs[] = new Type[args.length]; + boolean changed = (ret != rret); + for (int i = args.length ; i-- > 0 ; ) { + Type arg = args[i]; + Type rarg = resolveNames(c, arg, synth); + rargs[i] = rarg; + if (arg != rarg) { + changed = true; + } + } + if (changed) { + t = Type.tMethod(rret, rargs); + } + break; + } + } + return t; + } + + /** + * Resolve a class name, using only package and import directives. + * Report no errors. + *

                + */ + public Identifier resolveName(Identifier name) { + // This logic is pretty exactly parallel to that of + // ClassDefinition.resolveName(). + if (name.isQualified()) { + // Try to resolve the first identifier component, + // because inner class names take precedence over + // package prefixes. (Cf. ClassDefinition.resolveName.) + Identifier rhead = resolveName(name.getHead()); + + if (rhead.hasAmbigPrefix()) { + // The first identifier component refers to an + // ambiguous class. Limp on. We throw away the + // rest of the classname as it is irrelevant. + // (part of solution for 4059855). + return rhead; + } + + if (!this.classExists(rhead)) { + return this.resolvePackageQualifiedName(name); + } + try { + return this.getClassDefinition(rhead). + resolveInnerClass(this, name.getTail()); + } catch (ClassNotFound ee) { + // return partially-resolved name someone else can fail on + return Identifier.lookupInner(rhead, name.getTail()); + } + } + try { + return resolve(name); + } catch (AmbiguousClass ee) { + // Don't force a resolution of the name if it is ambiguous. + // Forcing the resolution would tack the current package + // name onto the front of the class, which would be wrong. + // Instead, mark the name as ambiguous and let a later stage + // find the error by calling env.resolve(name). + // (part of solution for 4059855). + + if (name.hasAmbigPrefix()) { + return name; + } else { + return name.addAmbigPrefix(); + } + } catch (ClassNotFound ee) { + // last chance to make something halfway sensible + Imports imports = getImports(); + if (imports != null) + return imports.forceResolve(this, name); + } + return name; + } + + /** + * Discover if name consists of a package prefix, followed by the + * name of a class (that actually exists), followed possibly by + * some inner class names. If we can't find a class that exists, + * return the name unchanged. + *

                + * This routine is used after a class name fails to + * be resolved by means of imports or inner classes. + * However, import processing uses this routine directly, + * since import names must be exactly qualified to start with. + */ + public final Identifier resolvePackageQualifiedName(Identifier name) { + Identifier tail = null; + for (;;) { + if (classExists(name)) { + break; + } + if (!name.isQualified()) { + name = (tail == null) ? name : Identifier.lookup(name, tail); + tail = null; + break; + } + Identifier nm = name.getName(); + tail = (tail == null)? nm: Identifier.lookup(nm, tail); + name = name.getQualifier(); + } + if (tail != null) + name = Identifier.lookupInner(name, tail); + return name; + } + + /** + * Resolve a class name, using only package and import directives. + */ + public Identifier resolve(Identifier nm) throws ClassNotFound { + if (env == null) return nm; // a pretty useless no-op + return env.resolve(nm); + } + + /** + * Get the imports used to resolve class names. + */ + public Imports getImports() { + if (env == null) return null; // lame default + return env.getImports(); + } + + /** + * Create a new class. + */ + public ClassDefinition makeClassDefinition(Environment origEnv, long where, + IdentifierToken name, + String doc, int modifiers, + IdentifierToken superClass, + IdentifierToken interfaces[], + ClassDefinition outerClass) { + if (env == null) return null; // lame default + return env.makeClassDefinition(origEnv, where, name, + doc, modifiers, + superClass, interfaces, outerClass); + } + + /** + * Create a new field. + */ + public MemberDefinition makeMemberDefinition(Environment origEnv, long where, + ClassDefinition clazz, + String doc, int modifiers, + Type type, Identifier name, + IdentifierToken argNames[], + IdentifierToken expIds[], + Object value) { + if (env == null) return null; // lame default + return env.makeMemberDefinition(origEnv, where, clazz, doc, modifiers, + type, name, argNames, expIds, value); + } + + /** + * Returns true if the given method is applicable to the given arguments + */ + + public boolean isApplicable(MemberDefinition m, Type args[]) throws ClassNotFound { + Type mType = m.getType(); + if (!mType.isType(TC_METHOD)) + return false; + Type mArgs[] = mType.getArgumentTypes(); + if (args.length != mArgs.length) + return false; + for (int i = args.length ; --i >= 0 ;) + if (!isMoreSpecific(args[i], mArgs[i])) + return false; + return true; + } + + + /** + * Returns true if "best" is in every argument at least as good as "other" + */ + public boolean isMoreSpecific(MemberDefinition best, MemberDefinition other) + throws ClassNotFound { + Type bestType = best.getClassDeclaration().getType(); + Type otherType = other.getClassDeclaration().getType(); + boolean result = isMoreSpecific(bestType, otherType) + && isApplicable(other, best.getType().getArgumentTypes()); + // System.out.println("isMoreSpecific: " + best + "/" + other + // + " => " + result); + return result; + } + + /** + * Returns true if "from" is a more specific type than "to" + */ + + public boolean isMoreSpecific(Type from, Type to) throws ClassNotFound { + return implicitCast(from, to); + } + + /** + * Return true if an implicit cast from this type to + * the given type is allowed. + */ + @SuppressWarnings("fallthrough") + public boolean implicitCast(Type from, Type to) throws ClassNotFound { + if (from == to) + return true; + + int toTypeCode = to.getTypeCode(); + + switch(from.getTypeCode()) { + case TC_BYTE: + if (toTypeCode == TC_SHORT) + return true; + case TC_SHORT: + case TC_CHAR: + if (toTypeCode == TC_INT) return true; + case TC_INT: + if (toTypeCode == TC_LONG) return true; + case TC_LONG: + if (toTypeCode == TC_FLOAT) return true; + case TC_FLOAT: + if (toTypeCode == TC_DOUBLE) return true; + case TC_DOUBLE: + default: + return false; + + case TC_NULL: + return to.inMask(TM_REFERENCE); + + case TC_ARRAY: + if (!to.isType(TC_ARRAY)) { + return (to == Type.tObject || to == Type.tCloneable + || to == Type.tSerializable); + } else { + // both are arrays. recurse down both until one isn't an array + do { + from = from.getElementType(); + to = to.getElementType(); + } while (from.isType(TC_ARRAY) && to.isType(TC_ARRAY)); + if ( from.inMask(TM_ARRAY|TM_CLASS) + && to.inMask(TM_ARRAY|TM_CLASS)) { + return isMoreSpecific(from, to); + } else { + return (from.getTypeCode() == to.getTypeCode()); + } + } + + case TC_CLASS: + if (toTypeCode == TC_CLASS) { + ClassDefinition fromDef = getClassDefinition(from); + ClassDefinition toDef = getClassDefinition(to); + return toDef.implementedBy(this, + fromDef.getClassDeclaration()); + } else { + return false; + } + } + } + + + /** + * Return true if an explicit cast from this type to + * the given type is allowed. + */ + public boolean explicitCast(Type from, Type to) throws ClassNotFound { + if (implicitCast(from, to)) { + return true; + } + if (from.inMask(TM_NUMBER)) { + return to.inMask(TM_NUMBER); + } + if (from.isType(TC_CLASS) && to.isType(TC_CLASS)) { + ClassDefinition fromClass = getClassDefinition(from); + ClassDefinition toClass = getClassDefinition(to); + if (toClass.isFinal()) { + return fromClass.implementedBy(this, + toClass.getClassDeclaration()); + } + if (fromClass.isFinal()) { + return toClass.implementedBy(this, + fromClass.getClassDeclaration()); + } + + // The code here used to omit this case. If both types + // involved in a cast are interfaces, then JLS 5.5 requires + // that we do a simple test -- make sure none of the methods + // in toClass and fromClass have the same signature but + // different return types. (bug number 4028359) + if (toClass.isInterface() && fromClass.isInterface()) { + return toClass.couldImplement(fromClass); + } + + return toClass.isInterface() || + fromClass.isInterface() || + fromClass.superClassOf(this, toClass.getClassDeclaration()); + } + if (to.isType(TC_ARRAY)) { + if (from.isType(TC_ARRAY)) { + Type t1 = from.getElementType(); + Type t2 = to.getElementType(); + while ((t1.getTypeCode() == TC_ARRAY) + && (t2.getTypeCode() == TC_ARRAY)) { + t1 = t1.getElementType(); + t2 = t2.getElementType(); + } + if (t1.inMask(TM_ARRAY|TM_CLASS) && + t2.inMask(TM_ARRAY|TM_CLASS)) { + return explicitCast(t1, t2); + } + } else if (from == Type.tObject || from == Type.tCloneable + || from == Type.tSerializable) + return true; + } + return false; + } + + /** + * Flags. + */ + public int getFlags() { + return env.getFlags(); + } + + /** + * Debugging flags. There used to be a method debug() + * that has been replaced because -g has changed meaning + * (it now cooperates with -O and line number, variable + * range and source file info can be toggled separately). + */ + public final boolean debug_lines() { + return (getFlags() & F_DEBUG_LINES) != 0; + } + public final boolean debug_vars() { + return (getFlags() & F_DEBUG_VARS) != 0; + } + public final boolean debug_source() { + return (getFlags() & F_DEBUG_SOURCE) != 0; + } + + /** + * Optimization flags. There used to be a method optimize() + * that has been replaced because -O has changed meaning in + * javac to be replaced with -O and -O:interclass. + */ + public final boolean opt() { + return (getFlags() & F_OPT) != 0; + } + public final boolean opt_interclass() { + return (getFlags() & F_OPT_INTERCLASS) != 0; + } + + /** + * Verbose + */ + public final boolean verbose() { + return (getFlags() & F_VERBOSE) != 0; + } + + /** + * Dump debugging stuff + */ + public final boolean dump() { + return (getFlags() & F_DUMP) != 0; + } + + /** + * Verbose + */ + public final boolean warnings() { + return (getFlags() & F_WARNINGS) != 0; + } + + /** + * Dependencies + */ + public final boolean dependencies() { + return (getFlags() & F_DEPENDENCIES) != 0; + } + + /** + * Print Dependencies to stdout + */ + public final boolean print_dependencies() { + return (getFlags() & F_PRINT_DEPENDENCIES) != 0; + } + + /** + * Deprecation warnings are enabled. + */ + public final boolean deprecation() { + return (getFlags() & F_DEPRECATION) != 0; + } + + /** + * Do not support virtual machines before version 1.2. + * This option is not supported and is only here for testing purposes. + */ + public final boolean version12() { + return (getFlags() & F_VERSION12) != 0; + } + + /** + * Floating point is strict by default + */ + public final boolean strictdefault() { + return (getFlags() & F_STRICTDEFAULT) != 0; + } + + /** + * Release resources, if any. + */ + public void shutdown() { + if (env != null) { + env.shutdown(); + } + } + + /** + * Issue an error. + * source - the input source, usually a file name string + * offset - the offset in the source of the error + * err - the error number (as defined in this interface) + * arg1 - an optional argument to the error (null if not applicable) + * arg2 - a second optional argument to the error (null if not applicable) + * arg3 - a third optional argument to the error (null if not applicable) + */ + public void error(Object source, long where, String err, Object arg1, Object arg2, Object arg3) { + env.error(source, where, err, arg1, arg2, arg3); + } + public final void error(long where, String err, Object arg1, Object arg2, Object arg3) { + error(source, where, err, arg1, arg2, arg3); + } + public final void error(long where, String err, Object arg1, Object arg2) { + error(source, where, err, arg1, arg2, null); + } + public final void error(long where, String err, Object arg1) { + error(source, where, err, arg1, null, null); + } + public final void error(long where, String err) { + error(source, where, err, null, null, null); + } + + /** + * Output a string. This can either be an error message or something + * for debugging. This should be used instead of println. + */ + public void output(String msg) { + env.output(msg); + } + + private static boolean debugging = (System.getProperty("javac.debug") != null); + + public static void debugOutput(Object msg) { + if (Environment.debugging) + System.out.println(msg.toString()); + } + + /** + * set character encoding name + */ + public void setCharacterEncoding(String encoding) { + this.encoding = encoding; + } + + /** + * Return character encoding name + */ + public String getCharacterEncoding() { + return encoding; + } + + /** + * Return major version to use in generated class files. + */ + public short getMajorVersion() { + if (env==null) return JAVA_DEFAULT_VERSION; // needed for javah + return env.getMajorVersion(); + } + + /** + * Return minor version to use in generated class files. + */ + public short getMinorVersion() { + if (env==null) return JAVA_DEFAULT_MINOR_VERSION; // needed for javah + return env.getMinorVersion(); + } + +// JCOV + /** + * get coverage flag + */ + public final boolean coverage() { + return (getFlags() & F_COVERAGE) != 0; + } + + /** + * get flag of generation the coverage data file + */ + public final boolean covdata() { + return (getFlags() & F_COVDATA) != 0; + } + + /** + * Return the coverage data file + */ + public File getcovFile() { + return env.getcovFile(); + } + +// end JCOV + + /** + * Debug tracing. + * Currently, this code is used only for tracing the loading and + * checking of classes, particularly the demand-driven aspects. + * This code should probably be integrated with 'debugOutput' above, + * but we need to give more thought to the issue of classifying debugging + * messages and allowing those only those of interest to be enabled. + * + * Calls to these methods are generally conditioned on the final variable + * 'Constants.tracing', which allows the calls to be completely omitted + * in a production release to avoid space and time overhead. + */ + + private static boolean dependtrace = + (System.getProperty("javac.trace.depend") != null); + + public void dtEnter(String s) { + if (dependtrace) System.out.println(">>> " + s); + } + + public void dtExit(String s) { + if (dependtrace) System.out.println("<<< " + s); + } + + public void dtEvent(String s) { + if (dependtrace) System.out.println(s); + } + + /** + * Enable diagnostic dump of class modifier bits, including those + * in InnerClasses attributes, as they are written to the classfile. + * In the future, may also enable dumping field and method modifiers. + */ + + private static boolean dumpmodifiers = + (System.getProperty("javac.dump.modifiers") != null); + + public boolean dumpModifiers() { return dumpmodifiers; } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/FileClassFile.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/FileClassFile.java new file mode 100644 index 000000000..d895c728c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/FileClassFile.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.File; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.IOException; + +/** + * This class is used to represent a file loaded from the class path, and + * is a regular file. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +final +class FileClassFile extends ClassFile { + private final File file; + + /** + * Constructor for instance representing a regular file + */ + public FileClassFile(File file) { + this.file = file; + } + + @Override + public boolean isZipped() { + return false; + } + + @Override + public InputStream getInputStream() throws IOException { + return new FileInputStream(file); + } + + @Override + public boolean exists() { + return file.exists(); + } + + @Override + public boolean isDirectory() { + return file.isDirectory(); + } + + @Override + public long lastModified() { + return file.lastModified(); + } + + @Override + public String getPath() { + return file.getPath(); + } + + @Override + public String getName() { + return file.getName(); + } + +//JCOV + @Override + public String getAbsoluteName() { + String absoluteName; + try { + absoluteName = file.getCanonicalPath(); + } catch (IOException e) { + absoluteName = file.getAbsolutePath(); + } + return absoluteName; + } +// end JCOV + + @Override + public long length() { + return file.length(); + } + + @Override + public String toString() { + return file.toString(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Identifier.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Identifier.java new file mode 100644 index 000000000..39a229d86 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Identifier.java @@ -0,0 +1,314 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.util.Hashtable; +import java.io.PrintStream; +import java.util.Enumeration; + +/** + * A class to represent identifiers.

                + * + * An identifier instance is very similar to a String. The difference + * is that identifier can't be instanciated directly, instead they are + * looked up in a hash table. This means that identifiers with the same + * name map to the same identifier object. This makes comparisons of + * identifiers much faster.

                + * + * A lot of identifiers are qualified, that is they have '.'s in them. + * Each qualified identifier is chopped up into the qualifier and the + * name. The qualifier is cached in the value field.

                + * + * Unqualified identifiers can have a type. This type is an integer that + * can be used by a scanner as a token value. This value has to be set + * using the setType method.

                + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ + +public final +class Identifier implements Constants { + /** + * The hashtable of identifiers + */ + static Hashtable hash = new Hashtable<>(3001, 0.5f); + + /** + * The name of the identifier + */ + String name; + + /** + * The value of the identifier, for keywords this is an + * instance of class Integer, for qualified names this is + * another identifier (the qualifier). + */ + Object value; + + /** + * The Type which corresponds to this Identifier. This is used as + * cache for Type.tClass() and shouldn't be used outside of that + * context. + */ + Type typeObject = null; + + /** + * The index of INNERCLASS_PREFIX in the name, or -1 if none. + */ + private int ipos; + + /** + * Construct an identifier. Don't call this directly, + * use lookup instead. + * @see Identifier.lookup + */ + private Identifier(String name) { + this.name = name; + this.ipos = name.indexOf(INNERCLASS_PREFIX); + } + + /** + * Get the type of the identifier. + */ + int getType() { + return ((value != null) && (value instanceof Integer)) ? + ((Integer)value).intValue() : IDENT; + } + + /** + * Set the type of the identifier. + */ + void setType(int t) { + value = t; + //System.out.println("type(" + this + ")=" + t); + } + + /** + * Lookup an identifier. + */ + public static synchronized Identifier lookup(String s) { + //System.out.println("lookup(" + s + ")"); + Identifier id = hash.get(s); + if (id == null) { + hash.put(s, id = new Identifier(s)); + } + return id; + } + + /** + * Lookup a qualified identifier. + */ + public static Identifier lookup(Identifier q, Identifier n) { + // lookup("", x) => x + if (q == idNull) return n; + // lookup(lookupInner(c, ""), n) => lookupInner(c, lookup("", n)) + if (q.name.charAt(q.name.length()-1) == INNERCLASS_PREFIX) + return lookup(q.name+n.name); + Identifier id = lookup(q + "." + n); + if (!n.isQualified() && !q.isInner()) + id.value = q; + return id; + } + + /** + * Lookup an inner identifier. + * (Note: n can be idNull.) + */ + public static Identifier lookupInner(Identifier c, Identifier n) { + Identifier id; + if (c.isInner()) { + if (c.name.charAt(c.name.length()-1) == INNERCLASS_PREFIX) + id = lookup(c.name+n); + else + id = lookup(c, n); + } else { + id = lookup(c + "." + INNERCLASS_PREFIX + n); + } + id.value = c.value; + return id; + } + + /** + * Convert to a string. + */ + public String toString() { + return name; + } + + /** + * Check if the name is qualified (ie: it contains a '.'). + */ + public boolean isQualified() { + if (value == null) { + int idot = ipos; + if (idot <= 0) + idot = name.length(); + else + idot -= 1; // back up over previous dot + int index = name.lastIndexOf('.', idot-1); + value = (index < 0) ? idNull : Identifier.lookup(name.substring(0, index)); + } + return (value instanceof Identifier) && (value != idNull); + } + + /** + * Return the qualifier. The null identifier is returned if + * the name was not qualified. The qualifier does not include + * any inner part of the name. + */ + public Identifier getQualifier() { + return isQualified() ? (Identifier)value : idNull; + } + + /** + * Return the unqualified name. + * In the case of an inner name, the unqualified name + * will itself contain components. + */ + public Identifier getName() { + return isQualified() ? + Identifier.lookup(name.substring(((Identifier)value).name.length() + 1)) : this; + } + + /** A space character, which precedes the first inner class + * name in a qualified name, and thus marks the qualification + * as involving inner classes, instead of merely packages.

                + * Ex: {@code java.util.Vector. Enumerator}. + */ + public static final char INNERCLASS_PREFIX = ' '; + + /* Explanation: + * Since much of the compiler's low-level name resolution code + * operates in terms of Identifier objects. This includes the + * code which walks around the file system and reports what + * classes are where. It is important to get nesting information + * right as early as possible, since it affects the spelling of + * signatures. Thus, the low-level import and resolve code must + * be able Identifier type must be able to report the nesting + * of types, which implied that that information must be carried + * by Identifiers--or that the low-level interfaces be significantly + * changed. + */ + + /** + * Check if the name is inner (ie: it contains a ' '). + */ + public boolean isInner() { + return (ipos > 0); + } + + /** + * Return the class name, without its qualifier, + * and with any nesting flattened into a new qualfication structure. + * If the original identifier is inner, + * the result will be qualified, and can be further + * decomposed by means of {@code getQualifier} and {@code getName}. + *

                + * For example: + *

                +     * Identifier id = Identifier.lookup("pkg.Foo. Bar");
                +     * id.getName().name      =>  "Foo. Bar"
                +     * id.getFlatName().name  =>  "Foo.Bar"
                +     * 
                + */ + public Identifier getFlatName() { + if (isQualified()) { + return getName().getFlatName(); + } + if (ipos > 0 && name.charAt(ipos-1) == '.') { + if (ipos+1 == name.length()) { + // last component is idNull + return Identifier.lookup(name.substring(0,ipos-1)); + } + String n = name.substring(ipos+1); + String t = name.substring(0,ipos); + return Identifier.lookup(t+n); + } + // Not inner. Just return the same as getName() + return this; + } + + public Identifier getTopName() { + if (!isInner()) return this; + return Identifier.lookup(getQualifier(), getFlatName().getHead()); + } + + /** + * Yet another way to slice qualified identifiers: + * The head of an identifier is its first qualifier component, + * and the tail is the rest of them. + */ + public Identifier getHead() { + Identifier id = this; + while (id.isQualified()) + id = id.getQualifier(); + return id; + } + + /** + * @see getHead + */ + public Identifier getTail() { + Identifier id = getHead(); + if (id == this) + return idNull; + else + return Identifier.lookup(name.substring(id.name.length() + 1)); + } + + // Unfortunately, the current structure of the compiler requires + // that the resolveName() family of methods (which appear in + // Environment.java, Context.java, and ClassDefinition.java) raise + // no exceptions and emit no errors. When we are in resolveName() + // and we find a method that is ambiguous, we need to + // unambiguously mark it as such, so that later stages of the + // compiler realize that they should give an ambig.class rather than + // a class.not.found error. To mark it we add a special prefix + // which cannot occur in the program source. The routines below + // are used to check, add, and remove this prefix. + // (part of solution for 4059855). + + /** + * A special prefix to add to ambiguous names. + */ + private static final String ambigPrefix = "<>"; + + /** + * Determine whether an Identifier has been marked as ambiguous. + */ + public boolean hasAmbigPrefix() { + return (name.startsWith(ambigPrefix)); + } + + /** + * Add ambigPrefix to `this' to make a new Identifier marked as + * ambiguous. It is important that this new Identifier not refer + * to an existing class. + */ + public Identifier addAmbigPrefix() { + return Identifier.lookup(ambigPrefix + name); + } + + /** + * Remove the ambigPrefix from `this' to get the original identifier. + */ + public Identifier removeAmbigPrefix() { + if (hasAmbigPrefix()) { + return Identifier.lookup(name.substring(ambigPrefix.length())); + } else { + return this; + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/IdentifierToken.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/IdentifierToken.java new file mode 100644 index 000000000..c6a6060a0 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/IdentifierToken.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +/** + * Information about the occurrence of an identifier. + * The parser produces these to represent name which cannot yet be + * bound to field definitions. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @see + */ + +public +class IdentifierToken { + long where; + int modifiers; + Identifier id; + + public IdentifierToken(long where, Identifier id) { + this.where = where; + this.id = id; + } + + /** Use this constructor when the identifier is synthesized. + * The location will be 0. + */ + public IdentifierToken(Identifier id) { + this.where = 0; + this.id = id; + } + + public IdentifierToken(long where, Identifier id, int modifiers) { + this.where = where; + this.id = id; + this.modifiers = modifiers; + } + + /** The source location of this identifier occurrence. */ + public long getWhere() { + return where; + } + + /** The identifier itself (possibly qualified). */ + public Identifier getName() { + return id; + } + + /** The modifiers associated with the occurrence, if any. */ + public int getModifiers() { + return modifiers; + } + + public String toString() { + return id.toString(); + } + + /** + * Return defaultWhere if id is null or id.where is missing (0). + * Otherwise, return id.where. + */ + public static long getWhere(IdentifierToken id, long defaultWhere) { + return (id != null && id.where != 0) ? id.where : defaultWhere; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Imports.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Imports.java new file mode 100644 index 000000000..b37777765 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Imports.java @@ -0,0 +1,488 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.util.Hashtable; +import java.util.Vector; +import java.util.Enumeration; +import java.util.List; +import java.util.Collections; +import java.io.IOException; + +/** + * This class describes the classes and packages imported + * from a source file. A Hashtable called bindings is maintained + * to quickly map symbol names to classes. This table is flushed + * everytime a new import is added. + * + * A class name is resolved as follows: + * - if it is a qualified name then return the corresponding class + * - if the name corresponds to an individually imported class then return that class + * - check if the class is defined in any of the imported packages, + * if it is then return it, make sure it is defined in only one package + * - assume that the class is defined in the current package + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ + +public +class Imports implements Constants { + /** + * The current package, which is implicitly imported, + * and has precedence over other imported packages. + */ + Identifier currentPackage = idNull; + + /** + * A location for the current package declaration. Used to + * report errors against the current package. + */ + long currentPackageWhere = 0; + + /** + * The imported classes, including memoized imports from packages. + */ + Hashtable classes = new Hashtable<>(); + + /** + * The imported package identifiers. This will not contain duplicate + * imports for the same package. It will also not contain the + * current package. + */ + Vector packages = new Vector<>(); + + /** + * The (originally) imported classes. + * A vector of IdentifierToken. + */ + Vector singles = new Vector<>(); + + /** + * Are the import names checked yet? + */ + protected int checked; + + /** + * Constructor, always import java.lang. + */ + public Imports(Environment env) { + addPackage(idJavaLang); + } + + /** + * Check the names of the imports. + */ + public synchronized void resolve(Environment env) { + if (checked != 0) { + return; + } + checked = -1; + + // After all class information has been read, now we can + // safely inspect import information for errors. + // If we did this before all parsing was finished, + // we could get vicious circularities, since files can + // import each others' classes. + + // A note: the resolution of the package java.lang takes place + // in the org.glassfish.rmic.tools.javac.BatchEnvironment#setExemptPackages(). + + // Make sure that the current package's name does not collide + // with the name of an existing class. (bug 4101529) + // + // This change has been backed out because, on WIN32, it + // failed to distinguish between java.awt.event and + // java.awt.Event when looking for a directory. We will + // add this back in later. + // + // if (currentPackage != idNull) { + // Identifier resolvedName = + // env.resolvePackageQualifiedName(currentPackage); + // + // Identifier className = resolvedName.getTopName(); + // + // if (importable(className, env)) { + // // The name of the current package is also the name + // // of a class. + // env.error(currentPackageWhere, "package.class.conflict", + // currentPackage, className); + // } + // } + + Vector resolvedPackages = new Vector<>(); + for (Enumeration e = packages.elements() ; e.hasMoreElements() ;) { + IdentifierToken t = e.nextElement(); + Identifier nm = t.getName(); + long where = t.getWhere(); + + // Check to see if this package is exempt from the "exists" + // check. See the note in + // org.glassfish.rmic.tools.javac.BatchEnvironment#setExemptPackages() + // for more information. + if (env.isExemptPackage(nm)) { + resolvedPackages.addElement(t); + continue; + } + + // (Note: This code is moved from BatchParser.importPackage().) + try { + Identifier rnm = env.resolvePackageQualifiedName(nm); + if (importable(rnm, env)) { + // This name is a real class; better not be a package too. + if (env.getPackage(rnm.getTopName()).exists()) { + env.error(where, "class.and.package", + rnm.getTopName()); + } + // Pass an "inner" name to the imports. + if (!rnm.isInner()) + rnm = Identifier.lookupInner(rnm, idNull); + nm = rnm; + } else if (!env.getPackage(nm).exists()) { + env.error(where, "package.not.found", nm, "import"); + } else if (rnm.isInner()) { + // nm exists, and rnm.getTopName() is a parent package + env.error(where, "class.and.package", rnm.getTopName()); + } + resolvedPackages.addElement(new IdentifierToken(where, nm)); + } catch (IOException ee) { + env.error(where, "io.exception", "import"); + } + } + packages = resolvedPackages; + + for (Enumeration e = singles.elements() ; e.hasMoreElements() ;) { + IdentifierToken t = e.nextElement(); + Identifier nm = t.getName(); + long where = t.getWhere(); + Identifier pkg = nm.getQualifier(); + + // (Note: This code is moved from BatchParser.importClass().) + nm = env.resolvePackageQualifiedName(nm); + if (!env.classExists(nm.getTopName())) { + env.error(where, "class.not.found", nm, "import"); + } + + // (Note: This code is moved from Imports.addClass().) + Identifier snm = nm.getFlatName().getName(); + + // make sure it isn't already imported explicitly + Identifier className = classes.get(snm); + if (className != null) { + Identifier f1 = Identifier.lookup(className.getQualifier(), + className.getFlatName()); + Identifier f2 = Identifier.lookup(nm.getQualifier(), + nm.getFlatName()); + if (!f1.equals(f2)) { + env.error(where, "ambig.class", nm, className); + } + } + classes.put(snm, nm); + + + // The code here needs to check to see, if we + // are importing an inner class, that all of its + // enclosing classes are visible to us. To check this, + // we need to construct a definition for the class. + // The code here used to call... + // + // ClassDefinition def = env.getClassDefinition(nm); + // + // ...but that interfered with the basicCheck()'ing of + // interfaces in certain cases (bug no. 4086139). Never + // fear. Instead we load the class with a call to the + // new getClassDefinitionNoCheck() which does no basicCheck() and + // lets us answer the questions we are interested in w/o + // interfering with the demand-driven nature of basicCheck(). + + try { + // Get a declaration + ClassDeclaration decl = env.getClassDeclaration(nm); + + // Get the definition (no env argument) + ClassDefinition def = decl.getClassDefinitionNoCheck(env); + + // Get the true name of the package containing this class. + // `pkg' from above is insufficient. It includes the + // names of our enclosing classes. Fix for 4086815. + Identifier importedPackage = def.getName().getQualifier(); + + // Walk out the outerClass chain, ensuring that each level + // is visible from our perspective. + for (; def != null; def = def.getOuterClass()) { + if (def.isPrivate() + || !(def.isPublic() + || importedPackage.equals(currentPackage))) { + env.error(where, "cant.access.class", def); + break; + } + } + } catch (AmbiguousClass ee) { + env.error(where, "ambig.class", ee.name1, ee.name2); + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, "import"); + } + } + checked = 1; + } + + /** + * Lookup a class, given the current set of imports, + * AmbiguousClass exception is thrown if the name can be + * resolved in more than one way. A ClassNotFound exception + * is thrown if the class is not found in the imported classes + * and packages. + */ + public synchronized Identifier resolve(Environment env, Identifier nm) throws ClassNotFound { + if (tracing) env.dtEnter("Imports.resolve: " + nm); + + // If the class has the special ambiguous prefix, then we will + // get the original AmbiguousClass exception by removing the + // prefix and proceeding in the normal fashion. + // (part of solution for 4059855) + if (nm.hasAmbigPrefix()) { + nm = nm.removeAmbigPrefix(); + } + + if (nm.isQualified()) { + // Don't bother it is already qualified + if (tracing) env.dtExit("Imports.resolve: QUALIFIED " + nm); + return nm; + } + + if (checked <= 0) { + checked = 0; + resolve(env); + } + + // Check if it was imported before + Identifier className = classes.get(nm); + if (className != null) { + if (tracing) env.dtExit("Imports.resolve: PREVIOUSLY IMPORTED " + nm); + return className; + } + + // Note: the section below has changed a bit during the fix + // for bug 4093217. The current package is no longer grouped + // with the rest of the import-on-demands; it is now checked + // separately. Also, the list of import-on-demands is now + // guarranteed to be duplicate-free, so the code below can afford + // to be a bit simpler. + + // First we look in the current package. The current package + // is given precedence over the rest of the import-on-demands, + // which means, among other things, that a class in the current + // package cannot be ambiguous. + Identifier id = Identifier.lookup(currentPackage, nm); + if (importable(id, env)) { + className = id; + } else { + // If it isn't in the current package, try to find it in + // our import-on-demands. + Enumeration e = packages.elements(); + while (e.hasMoreElements()) { + IdentifierToken t = e.nextElement(); + id = Identifier.lookup(t.getName(), nm); + + if (importable(id, env)) { + if (className == null) { + // We haven't found any other matching classes yet. + // Set className to what we've found and continue + // looking for an ambiguity. + className = id; + } else { + if (tracing) + env.dtExit("Imports.resolve: AMBIGUOUS " + nm); + + // We've found an ambiguity. + throw new AmbiguousClass(className, id); + } + } + } + } + + // Make sure a class was found + if (className == null) { + if (tracing) env.dtExit("Imports.resolve: NOT FOUND " + nm); + throw new ClassNotFound(nm); + } + + // Remember the binding + classes.put(nm, className); + if (tracing) env.dtExit("Imports.resolve: FIRST IMPORT " + nm); + return className; + } + + /** + * Check to see if 'id' names an importable class in `env'. + * This method was made public and static for utility. + */ + static public boolean importable(Identifier id, Environment env) { + if (!id.isInner()) { + return env.classExists(id); + } else if (!env.classExists(id.getTopName())) { + return false; + } else { + // load the top class and look inside it + try { + // There used to be a call to... + // env.getClassDeclaration(id.getTopName()); + // ...here. It has been replaced with the + // two statements below. These should be functionally + // the same except for the fact that + // getClassDefinitionNoCheck() does not call + // basicCheck(). This allows us to avoid a circular + // need to do basicChecking that can arise with + // certain patterns of importing and inheritance. + // This is a fix for a variant of bug 4086139. + // + // Note: the special case code in env.getClassDefinition() + // which handles inner class names is not replicated below. + // This should be okay, as we are looking up id.getTopName(), + // not id. + ClassDeclaration decl = + env.getClassDeclaration(id.getTopName()); + ClassDefinition c = + decl.getClassDefinitionNoCheck(env); + + return c.innerClassExists(id.getFlatName().getTail()); + } catch (ClassNotFound ee) { + return false; + } + } + } + + /** + * Suppose a resolve() call has failed. + * This routine can be used silently to give a reasonable + * default qualification (the current package) to the identifier. + * This decision is recorded for future reference. + */ + public synchronized Identifier forceResolve(Environment env, Identifier nm) { + if (nm.isQualified()) + return nm; + + Identifier className = classes.get(nm); + if (className != null) { + return className; + } + + className = Identifier.lookup(currentPackage, nm); + + classes.put(nm, className); + return className; + } + + /** + * Add a class import + */ + public synchronized void addClass(IdentifierToken t) { + singles.addElement(t); + } + // for compatibility + public void addClass(Identifier nm) throws AmbiguousClass { + addClass(new IdentifierToken(nm)); + } + + /** + * Add a package import, or perhaps an inner class scope. + * Ignore any duplicate imports. + */ + public synchronized void addPackage(IdentifierToken t) { + final Identifier name = t.getName(); + + // If this is a duplicate import for the current package, + // ignore it. + if (name == currentPackage) { + return; + } + + // If this is a duplicate of a package which has already been + // added to the list, ignore it. + final int size = packages.size(); + for (int i = 0; i < size; i++) { + if (name == (packages.elementAt(i)).getName()) { + return; + } + } + + // Add the package to the list. + packages.addElement(t); + } + // for compatibility + public void addPackage(Identifier id) { + addPackage(new IdentifierToken(id)); + } + + /** + * Specify the current package with an IdentifierToken. + */ + public synchronized void setCurrentPackage(IdentifierToken t) { + currentPackage = t.getName(); + currentPackageWhere = t.getWhere(); + } + + /** + * Specify the current package + */ + public synchronized void setCurrentPackage(Identifier id) { + currentPackage = id; + } + + /** + * Report the current package + */ + public Identifier getCurrentPackage() { + return currentPackage; + } + + /** + * Return an unmodifiable list of IdentifierToken representing + * packages specified as imports. + */ + public List getImportedPackages() { + return Collections.unmodifiableList(packages); + } + + /** + * Return an unmodifiable list of IdentifierToken representing + * classes specified as imports. + */ + public List getImportedClasses() { + return Collections.unmodifiableList(singles); + } + + /** + * Extend an environment with my resolve() method. + */ + public Environment newEnvironment(Environment env) { + return new ImportEnvironment(env, this); + } +} + +final +class ImportEnvironment extends Environment { + Imports imports; + + ImportEnvironment(Environment env, Imports imports) { + super(env, env.getSource()); + this.imports = imports; + } + + public Identifier resolve(Identifier nm) throws ClassNotFound { + return imports.resolve(this, nm); + } + + public Imports getImports() { + return imports; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/MemberDefinition.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/MemberDefinition.java new file mode 100644 index 000000000..e5d11779f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/MemberDefinition.java @@ -0,0 +1,998 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.tree.Context; +import org.glassfish.rmic.tools.tree.Expression; +import org.glassfish.rmic.tools.tree.Node; +import org.glassfish.rmic.tools.tree.Statement; +import org.glassfish.rmic.tools.tree.Vset; + +import java.io.PrintStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Vector; + +/** + * This class defines a member of a Java class: + * a variable, a method, or an inner class. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@SuppressWarnings("deprecation") +public +class MemberDefinition implements Constants { + protected long where; + protected int modifiers; + protected Type type; + protected String documentation; + protected IdentifierToken expIds[]; + protected ClassDeclaration exp[]; + protected Node value; + protected ClassDefinition clazz; + protected Identifier name; + protected ClassDefinition innerClass; + protected MemberDefinition nextMember; + protected MemberDefinition nextMatch; + protected MemberDefinition accessPeer; + protected boolean superAccessMethod; + + /** + * Constructor + */ + public MemberDefinition(long where, ClassDefinition clazz, int modifiers, + Type type, Identifier name, + IdentifierToken expIds[], Node value) { + if (expIds == null) { + expIds = new IdentifierToken[0]; + } + this.where = where; + this.clazz = clazz; + this.modifiers = modifiers; + this.type = type; + this.name = name; + this.expIds = expIds; + this.value = value; + } + + /** + * Constructor for an inner class. + * Inner classes are represented as fields right along with + * variables and methods for simplicity of data structure, + * and to reflect properly the textual declaration order. + *

                + * This constructor calls the generic constructor for this + * class, extracting all necessary values from the innerClass. + */ + public MemberDefinition(ClassDefinition innerClass) { + this(innerClass.getWhere(), + innerClass.getOuterClass(), + innerClass.getModifiers(), + innerClass.getType(), + innerClass.getName().getFlatName().getName(), + null, null); + this.innerClass = innerClass; + } + + /** + * A cache of previously created proxy members. Used to ensure + * uniqueness of proxy objects. See the makeProxyMember method + * defined below. + */ + static private Map proxyCache; + + /** + * Create a member which is externally the same as `field' but + * is defined in class `classDef'. This is used by code + * in org.glassfish.rmic.tools.tree.(MethodExpression,FieldExpression) as + * part of the fix for bug 4135692. + * + * Proxy members should not be added, ala addMember(), to classes. + * They are merely "stand-ins" to produce modified MethodRef + * constant pool entries during code generation. + * + * We keep a cache of previously created proxy members not to + * save time or space, but to ensure uniqueness of the proxy + * member for any (field,classDef) pair. If these are not made + * unique then we can end up generating duplicate MethodRef + * constant pool entries during code generation. + */ + public static MemberDefinition makeProxyMember(MemberDefinition field, + ClassDefinition classDef, + Environment env) { + + if (proxyCache == null) { + proxyCache = new HashMap<>(); + } + + String key = field.toString() + "@" + classDef.toString(); + // System.out.println("Key is : " + key); + MemberDefinition proxy = proxyCache.get(key); + + if (proxy != null) + return proxy; + + proxy = new MemberDefinition(field.getWhere(), classDef, + field.getModifiers(), field.getType(), + field.getName(), field.getExceptionIds(), + null); + proxy.exp = field.getExceptions(env); + proxyCache.put(key, proxy); + + return proxy; + } + + public String getMemberValueString(Environment env) throws ClassNotFound { + return null; + } + + /** + * Get the position in the input + */ + public final long getWhere() { + return where; + } + + /** + * Get the class declaration + */ + public final ClassDeclaration getClassDeclaration() { + return clazz.getClassDeclaration(); + } + + /** + * A stub. Subclasses can do more checking. + */ + public void resolveTypeStructure(Environment env) { + } + + /** + * Get the class declaration in which the field is actually defined + */ + public ClassDeclaration getDefiningClassDeclaration() { + return getClassDeclaration(); + } + + /** + * Get the class definition + */ + public final ClassDefinition getClassDefinition() { + return clazz; + } + + /** + * Get the field's top-level enclosing class + */ + public final ClassDefinition getTopClass() { + return clazz.getTopClass(); + } + + /** + * Get the field's modifiers + */ + public final int getModifiers() { + return modifiers; + } + public final void subModifiers(int mod) { + modifiers &= ~mod; + } + public final void addModifiers(int mod) { + modifiers |= mod; + } + + /** + * Get the field's type + */ + public final Type getType() { + return type; + } + + /** + * Get the field's name + */ + public final Identifier getName() { + return name; + } + + /** + * Get arguments (a vector of LocalMember) + */ + public Vector getArguments() { + return isMethod() ? new Vector() : null; + } + + /** + * Get the exceptions that are thrown by this method. + */ + public ClassDeclaration[] getExceptions(Environment env) { + if (expIds != null && exp == null) { + if (expIds.length == 0) + exp = new ClassDeclaration[0]; + else + // we should have translated this already! + throw new CompilerError("getExceptions "+this); + } + return exp; + } + + public final IdentifierToken[] getExceptionIds() { + return expIds; + } + + /** + * Get an inner class. + */ + public ClassDefinition getInnerClass() { + return innerClass; + } + + /** + * Is this a synthetic field which holds a copy of, + * or reference to, a local variable or enclosing instance? + */ + public boolean isUplevelValue() { + if (!isSynthetic() || !isVariable() || isStatic()) { + return false; + } + String name = this.name.toString(); + return name.startsWith(prefixVal) + || name.startsWith(prefixLoc) + || name.startsWith(prefixThis); + } + + public boolean isAccessMethod() { + // This no longer works, because access methods + // for constructors do not use the standard naming + // scheme. + // return isSynthetic() && isMethod() + // && name.toString().startsWith(prefixAccess); + // Assume that a method is an access method if it has + // an access peer. NOTE: An access method will not be + // recognized as such until 'setAccessMethodTarget' has + // been called on it. + return isSynthetic() && isMethod() && (accessPeer != null); + } + + /** + * Is this a synthetic method which provides access to a + * visible private member? + */ + public MemberDefinition getAccessMethodTarget() { + if (isAccessMethod()) { + for (MemberDefinition f = accessPeer; f != null; f = f.accessPeer) { + // perhaps skip over another access for the same field + if (!f.isAccessMethod()) { + return f; + } + } + } + return null; + } + + + public void setAccessMethodTarget(MemberDefinition target) { + if (getAccessMethodTarget() != target) { + /*-------------------* + if (!isAccessMethod() || accessPeer != null || + target.accessPeer != null) { + throw new CompilerError("accessPeer"); + } + *-------------------*/ + if (accessPeer != null || target.accessPeer != null) { + throw new CompilerError("accessPeer"); + } + accessPeer = target; + } + } + + /** + * If this method is a getter for a private field, return the setter. + */ + public MemberDefinition getAccessUpdateMember() { + if (isAccessMethod()) { + for (MemberDefinition f = accessPeer; f != null; f = f.accessPeer) { + if (f.isAccessMethod()) { + return f; + } + } + } + return null; + } + + public void setAccessUpdateMember(MemberDefinition updater) { + if (getAccessUpdateMember() != updater) { + if (!isAccessMethod() || + updater.getAccessMethodTarget() != getAccessMethodTarget()) { + throw new CompilerError("accessPeer"); + } + updater.accessPeer = accessPeer; + accessPeer = updater; + } + } + + /** + * Is this an access method for a field selection or method call + * of the form '...super.foo' or '...super.foo()'? + */ + public final boolean isSuperAccessMethod() { + return superAccessMethod; + } + + /** + * Mark this member as an access method for a field selection + * or method call via the 'super' keyword. + */ + public final void setIsSuperAccessMethod(boolean b) { + superAccessMethod = b; + } + + /** + * Tell if this is a final variable without an initializer. + * Such variables are subject to definite single assignment. + */ + public final boolean isBlankFinal() { + return isFinal() && !isSynthetic() && getValue() == null; + } + + public boolean isNeverNull() { + if (isUplevelValue()) { + // loc$x and this$C are never null + return !name.toString().startsWith(prefixVal); + } + return false; + } + + /** + * Get the field's final value (may return null) + */ + public Node getValue(Environment env) throws ClassNotFound { + return value; + } + public final Node getValue() { + return value; + } + public final void setValue(Node value) { + this.value = value; + } + public Object getInitialValue() { + return null; + } + + /** + * Get the next field or the next match + */ + public final MemberDefinition getNextMember() { + return nextMember; + } + public final MemberDefinition getNextMatch() { + return nextMatch; + } + + /** + * Get the field's documentation + */ + public String getDocumentation() { + return documentation; + } + + /** + * Request a check of the field definition. + */ + public void check(Environment env) throws ClassNotFound { + } + + /** + * Really check the field definition. + */ + public Vset check(Environment env, Context ctx, Vset vset) throws ClassNotFound { + return vset; + } + + /** + * Generate code + */ + public void code(Environment env, Assembler asm) throws ClassNotFound { + throw new CompilerError("code"); + } + public void codeInit(Environment env, Context ctx, Assembler asm) throws ClassNotFound { + throw new CompilerError("codeInit"); + } + + /** + * Tells whether to report a deprecation error for this field. + */ + public boolean reportDeprecated(Environment env) { + return (isDeprecated() || clazz.reportDeprecated(env)); + } + + /** + * Check if a field can reach another field (only considers + * forward references, not the access modifiers). + */ + public final boolean canReach(Environment env, MemberDefinition f) { + if (f.isLocal() || !f.isVariable() || !(isVariable() || isInitializer())) + return true; + if ((getClassDeclaration().equals(f.getClassDeclaration())) && + (isStatic() == f.isStatic())) { + // They are located in the same class, and are either both + // static or both non-static. Check the initialization order. + while (((f = f.getNextMember()) != null) && (f != this)); + return f != null; + } + return true; + } + + //----------------------------------------------------------------- + // The code in this section is intended to test certain kinds of + // compatibility between methods. There are two kinds of compatibility + // that the compiler may need to test. The first is whether one + // method can legally override another. The second is whether two + // method definitions can legally coexist. We use the word `meet' + // to mean the intersection of two legally coexisting methods. + // For more information on these kinds of compatibility, see the + // comments/code for checkOverride() and checkMeet() below. + + /** + * Constants used by getAccessLevel() to represent the access + * modifiers as numbers. + */ + static final int PUBLIC_ACCESS = 1; + static final int PROTECTED_ACCESS = 2; + static final int PACKAGE_ACCESS = 3; + static final int PRIVATE_ACCESS = 4; + + /** + * Return the access modifier of this member as a number. The idea + * is that this number may be used to check properties like "the + * access modifier of x is more restrictive than the access + * modifier of y" with a simple inequality test: + * "x.getAccessLevel() > y.getAccessLevel. + * + * This is an internal utility method. + */ + private int getAccessLevel() { + // Could just compute this once instead of recomputing. + // Check to see if this is worth it. + if (isPublic()) { + return PUBLIC_ACCESS; + } else if (isProtected()) { + return PROTECTED_ACCESS; + } else if (isPackagePrivate()) { + return PACKAGE_ACCESS; + } else if (isPrivate()) { + return PRIVATE_ACCESS; + } else { + throw new CompilerError("getAccessLevel()"); + } + } + + /** + * Munge our error message to report whether the override conflict + * came from an inherited method or a declared method. + */ + private void reportError(Environment env, String errorString, + ClassDeclaration clazz, + MemberDefinition method) { + + if (clazz == null) { + // For example: + // "Instance method BLAH inherited from CLASSBLAH1 cannot be + // overridden by the static method declared in CLASSBLAH2." + env.error(getWhere(), errorString, + this, getClassDeclaration(), + method.getClassDeclaration()); + } else { + // For example: + // "In CLASSBLAH1, instance method BLAH inherited from CLASSBLAH2 + // cannot be overridden by the static method inherited from + // CLASSBLAH3." + env.error(clazz.getClassDefinition().getWhere(), + //"inherit." + errorString, + errorString, + //clazz, + this, getClassDeclaration(), + method.getClassDeclaration()); + } + } + + /** + * Convenience method to see if two methods return the same type + */ + public boolean sameReturnType(MemberDefinition method) { + // Make sure both are methods. + if (!isMethod() || !method.isMethod()) { + throw new CompilerError("sameReturnType: not method"); + } + + Type myReturnType = getType().getReturnType(); + Type yourReturnType = method.getType().getReturnType(); + + return (myReturnType == yourReturnType); + } + + /** + * Check to see if `this' can override/hide `method'. Caller is + * responsible for verifying that `method' has the same signature + * as `this'. Caller is also responsible for verifying that + * `method' is visible to the class where this override is occurring. + * This method is called for the case when class B extends A and both + * A and B define some method. + *

                +     *       A - void foo() throws e1
                +     *       |
                +     *       |
                +     *       B - void foo() throws e2
                +     * 
                + */ + public boolean checkOverride(Environment env, MemberDefinition method) { + return checkOverride(env, method, null); + } + + /** + * Checks whether `this' can override `method'. It `clazz' is + * null, it reports the errors in the class where `this' is + * declared. If `clazz' is not null, it reports the error in `clazz'. + */ + private boolean checkOverride(Environment env, + MemberDefinition method, + ClassDeclaration clazz) { + // This section of code is largely based on section 8.4.6.3 + // of the JLS. + + boolean success = true; + + // Sanity + if (!isMethod()) { + throw new CompilerError("checkOverride(), expected method"); + } + + // Suppress checks for synthetic methods, as the compiler presumably + // knows what it is doing, e.g., access methods. + if (isSynthetic()) { + // Sanity check: We generally do not intend for one synthetic + // method to override another, though hiding of static members + // is expected. This check may need to be changed if new uses + // of synthetic methods are devised. + // + // Query: this code was copied from elsewhere. What + // exactly is the role of the !isStatic() in the test? + if (method.isFinal() || + (!method.isConstructor() && + !method.isStatic() && !isStatic())) { + //////////////////////////////////////////////////////////// + // NMG 2003-01-28 removed the following test because it is + // invalidated by bridge methods inserted by the "generic" + // (1.5) Java compiler. In 1.5, this code is used, + // indirectly, by rmic + //////////////////////////////////////////////////////////// + // throw new CompilerError("checkOverride() synthetic"); + //////////////////////////////////////////////////////////// + } + + // We trust the compiler. (Ha!) We're done checking. + return true; + } + + // Our caller should have verified that the method had the + // same signature. + if (getName() != method.getName() || + !getType().equalArguments(method.getType())) { + + throw new CompilerError("checkOverride(), signature mismatch"); + } + + // It is forbidden to `override' a static method with an instance + // method. + if (method.isStatic() && !isStatic()) { + reportError(env, "override.static.with.instance", clazz, method); + success = false; + } + + // It is forbidden to `hide' an instance method with a static + // method. + if (!method.isStatic() && isStatic()) { + reportError(env, "hide.instance.with.static", clazz, method); + success = false; + } + + // We cannot override a final method. + if (method.isFinal()) { + reportError(env, "override.final.method", clazz, method); + success = false; + } + + // Give a warning when we override a deprecated method with + // a non-deprecated one. + // + // We bend over backwards to suppress this warning if + // the `method' has not been already compiled or + // `this' has been already compiled. + if (method.reportDeprecated(env) && !isDeprecated() + && this instanceof org.glassfish.rmic.tools.javac.SourceMember) { + reportError(env, "warn.override.is.deprecated", + clazz, method); + } + + // Visibility may not be more restrictive + if (getAccessLevel() > method.getAccessLevel()) { + reportError(env, "override.more.restrictive", clazz, method); + success = false; + } + + // Return type equality + if (!sameReturnType(method)) { + //////////////////////////////////////////////////////////// + // PCJ 2003-07-30 removed the following error because it is + // invalidated by the covariant return type feature of the + // 1.5 compiler. The resulting check is now much looser + // than the actual 1.5 language spec, but that should be OK + // because this code is only still used by rmic. See 4892308. + //////////////////////////////////////////////////////////// + // reportError(env, "override.different.return", clazz, method); + // success = false; + //////////////////////////////////////////////////////////// + } + + // Exception agreeement + if (!exceptionsFit(env, method)) { + reportError(env, "override.incompatible.exceptions", + clazz, method); + success = false; + } + + return success; + } + + /** + * Check to see if two method definitions are compatible, that is + * do they have a `meet'. The meet of two methods is essentially + * and `intersection' of + * two methods. This method is called when some class C inherits + * declarations for some method foo from two parents (superclass, + * interfaces) but it does not, itself, have a declaration of foo. + * Caller is responsible for making sure that both methods are + * indeed visible in clazz. + *
                +     *     A - void foo() throws e1
                +     *      \
                +     *       \     B void foo() throws e2
                +     *        \   /
                +     *         \ /
                +     *          C
                +     * 
                + */ + public boolean checkMeet(Environment env, + MemberDefinition method, + ClassDeclaration clazz) { + // This section of code is largely based on Section 8.4.6 + // and 9.4.1 of the JLS. + + // Sanity + if (!isMethod()) { + throw new CompilerError("checkMeet(), expected method"); + } + + // Check for both non-abstract. + if (!isAbstract() && !method.isAbstract()) { + throw new CompilerError("checkMeet(), no abstract method"); + } + + // If either method is non-abstract, then we need to check that + // the abstract method can be properly overridden. We call + // the checkOverride method to check this and generate any errors. + // This test must follow the previous test. + else if (!isAbstract()) { + return checkOverride(env, method, clazz); + } else if (!method.isAbstract()) { + return method.checkOverride(env, this, clazz); + } + + // Both methods are abstract. + + // Our caller should have verified that the method has the + // same signature. + if (getName() != method.getName() || + !getType().equalArguments(method.getType())) { + + throw new CompilerError("checkMeet(), signature mismatch"); + } + + // Check for return type equality + if (!sameReturnType(method)) { + // More args? + env.error(clazz.getClassDefinition().getWhere(), + "meet.different.return", + this, this.getClassDeclaration(), + method.getClassDeclaration()); + return false; + } + + // We don't have to check visibility -- there always + // potentially exists a meet. Similarly with exceptions. + + // There does exist a meet. + return true; + } + + /** + * This method is meant to be used to determine if one of two inherited + * methods could override the other. Unlike checkOverride(), failure + * is not an error. This method is only meant to be called after + * checkMeet() has succeeded on the two methods. + * + * If you call couldOverride() without doing a checkMeet() first, then + * you are on your own. + */ + public boolean couldOverride(Environment env, + MemberDefinition method) { + + // Sanity + if (!isMethod()) { + throw new CompilerError("coulcOverride(), expected method"); + } + + // couldOverride() is only called with `this' and `method' both + // being inherited methods. Neither of them is defined in the + // class which we are currently working on. Even though an + // abstract method defined *in* a class can override a non-abstract + // method defined in a superclass, an abstract method inherited + // from an interface *never* can override a non-abstract method. + // This comment may sound odd, but that's the way inheritance is. + // The following check makes sure we aren't trying to override + // an inherited non-abstract definition with an abstract definition + // from an interface. + if (!method.isAbstract()) { + return false; + } + + // Visibility should be less restrictive + if (getAccessLevel() > method.getAccessLevel()) { + return false; + } + + // Exceptions + if (!exceptionsFit(env, method)) { + return false; + } + + // Potentially some deprecation warnings could be given here + // when we merge two abstract methods, one of which is deprecated. + // This is not currently reported. + + return true; + } + + /** + * Check to see if the exceptions of `this' fit within the + * exceptions of `method'. + */ + private boolean exceptionsFit(Environment env, + MemberDefinition method) { + ClassDeclaration e1[] = getExceptions(env); // my exceptions + ClassDeclaration e2[] = method.getExceptions(env); // parent's + + // This code is taken nearly verbatim from the old implementation + // of checkOverride() in SourceClass. + outer: + for (int i = 0 ; i < e1.length ; i++) { + try { + ClassDefinition c1 = e1[i].getClassDefinition(env); + for (int j = 0 ; j < e2.length ; j++) { + if (c1.subClassOf(env, e2[j])) { + continue outer; + } + } + if (c1.subClassOf(env, + env.getClassDeclaration(idJavaLangError))) + continue outer; + if (c1.subClassOf(env, + env.getClassDeclaration(idJavaLangRuntimeException))) + continue outer; + + // the throws was neither something declared by a parent, + // nor one of the ignorables. + return false; + + } catch (ClassNotFound ee) { + // We were unable to find one of the exceptions. + env.error(getWhere(), "class.not.found", + ee.name, method.getClassDeclaration()); + } + } + + // All of the exceptions `fit'. + return true; + } + + //----------------------------------------------------------------- + + /** + * Checks + */ + public final boolean isPublic() { + return (modifiers & M_PUBLIC) != 0; + } + public final boolean isPrivate() { + return (modifiers & M_PRIVATE) != 0; + } + public final boolean isProtected() { + return (modifiers & M_PROTECTED) != 0; + } + public final boolean isPackagePrivate() { + return (modifiers & (M_PUBLIC | M_PRIVATE | M_PROTECTED)) == 0; + } + public final boolean isFinal() { + return (modifiers & M_FINAL) != 0; + } + public final boolean isStatic() { + return (modifiers & M_STATIC) != 0; + } + public final boolean isSynchronized() { + return (modifiers & M_SYNCHRONIZED) != 0; + } + public final boolean isAbstract() { + return (modifiers & M_ABSTRACT) != 0; + } + public final boolean isNative() { + return (modifiers & M_NATIVE) != 0; + } + public final boolean isVolatile() { + return (modifiers & M_VOLATILE) != 0; + } + public final boolean isTransient() { + return (modifiers & M_TRANSIENT) != 0; + } + public final boolean isMethod() { + return type.isType(TC_METHOD); + } + public final boolean isVariable() { + return !type.isType(TC_METHOD) && innerClass == null; + } + public final boolean isSynthetic() { + return (modifiers & M_SYNTHETIC) != 0; + } + public final boolean isDeprecated() { + return (modifiers & M_DEPRECATED) != 0; + } + public final boolean isStrict() { + return (modifiers & M_STRICTFP) != 0; + } + public final boolean isInnerClass() { + return innerClass != null; + } + public final boolean isInitializer() { + return getName().equals(idClassInit); + } + public final boolean isConstructor() { + return getName().equals(idInit); + } + public boolean isLocal() { + return false; + } + public boolean isInlineable(Environment env, boolean fromFinal) throws ClassNotFound { + return (isStatic() || isPrivate() || isFinal() || isConstructor() || fromFinal) && + !(isSynchronized() || isNative()); + } + + /** + * Check if constant: Will it inline away to a constant? + */ + public boolean isConstant() { + if (isFinal() && isVariable() && value != null) { + try { + // If an infinite regress requeries this name, + // deny that it is a constant. + modifiers &= ~M_FINAL; + return ((Expression)value).isConstant(); + } finally { + modifiers |= M_FINAL; + } + } + return false; + } + + /** + * toString + */ + public String toString() { + Identifier name = getClassDefinition().getName(); + if (isInitializer()) { + return isStatic() ? "static {}" : "instance {}"; + } else if (isConstructor()) { + StringBuilder sb = new StringBuilder(); + sb.append(name); + sb.append('('); + Type argTypes[] = getType().getArgumentTypes(); + for (int i = 0 ; i < argTypes.length ; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(argTypes[i].toString()); + } + sb.append(')'); + return sb.toString(); + } else if (isInnerClass()) { + return getInnerClass().toString(); + } + return type.typeString(getName().toString()); + } + + /** + * Print for debugging + */ + public void print(PrintStream out) { + if (isPublic()) { + out.print("public "); + } + if (isPrivate()) { + out.print("private "); + } + if (isProtected()) { + out.print("protected "); + } + if (isFinal()) { + out.print("final "); + } + if (isStatic()) { + out.print("static "); + } + if (isSynchronized()) { + out.print("synchronized "); + } + if (isAbstract()) { + out.print("abstract "); + } + if (isNative()) { + out.print("native "); + } + if (isVolatile()) { + out.print("volatile "); + } + if (isTransient()) { + out.print("transient "); + } + out.println(toString() + ";"); + } + + public void cleanup(Environment env) { + documentation = null; + if (isMethod() && value != null) { + int cost = 0; + if (isPrivate() || isInitializer()) { + value = Statement.empty; + } else if ((cost = + ((Statement)value) + .costInline(Statement.MAXINLINECOST, null, null)) + >= Statement.MAXINLINECOST) { + // will never be inlined + value = Statement.empty; + } else { + try { + if (!isInlineable(null, true)) { + value = Statement.empty; + } + } + catch (ClassNotFound ee) { } + } + if (value != Statement.empty && env.dump()) { + env.output("[after cleanup of " + getName() + ", " + + cost + " expression cost units remain]"); + } + } else if (isVariable()) { + if (isPrivate() || !isFinal() || type.isType(TC_ARRAY)) { + value = null; + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/MethodSet.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/MethodSet.java new file mode 100644 index 000000000..59c389bea --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/MethodSet.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.util.*; + +/** + * The MethodSet structure is used to store methods for a class. + * It maintains the invariant that it never stores two methods + * with the same signature. MethodSets are able to lookup + * all methods with a given name and the unique method with a given + * signature (name, args). + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ + +public +class MethodSet { + + /** + * A Map containing Lists of MemberDefinitions. The Lists + * contain methods which share the same name. + */ + private final Map> lookupMap; + + /** + * The number of methods stored in the MethodSet. + */ + private int count; + + /** + * Is this MethodSet currently frozen? See freeze() for more details. + */ + private boolean frozen; + + /** + * Creates a brand new MethodSet + */ + public MethodSet() { + frozen = false; + lookupMap = new HashMap<>(); + count = 0; + } + + /** + * Returns the number of distinct methods stored in the MethodSet. + */ + public int size() { + return count; + } + + /** + * Adds `method' to the MethodSet. No method of the same signature + * should be already defined. + */ + public void add(MemberDefinition method) { + // Check for late additions. + if (frozen) { + throw new CompilerError("add()"); + } + + // todo: Check for method?? + + Identifier name = method.getName(); + + // Get a List containing all methods of this name. + List methodList = lookupMap.get(name); + + if (methodList == null) { + // There is no method with this name already. + // Create a List, and insert it into the hash. + methodList = new ArrayList<>(); + lookupMap.put(name, methodList); + } + + // Make sure that no method with the same signature has already + // been added to the MethodSet. + int size = methodList.size(); + for (int i = 0; i < size; i++) { + if ((methodList.get(i)) + .getType().equalArguments(method.getType())) { + throw new CompilerError("duplicate addition"); + } + } + + // We add the method to the appropriate list. + methodList.add(method); + count++; + } + + /** + * Adds `method' to the MethodSet, replacing any previous definition + * with the same signature. + */ + public void replace(MemberDefinition method) { + // Check for late additions. + if (frozen) { + throw new CompilerError("replace()"); + } + + // todo: Check for method?? + + Identifier name = method.getName(); + + // Get a List containing all methods of this name. + List methodList = lookupMap.get(name); + + if (methodList == null) { + // There is no method with this name already. + // Create a List, and insert it into the hash. + methodList = new ArrayList<>(); + lookupMap.put(name, methodList); + } + + // Replace the element which has the same signature as + // `method'. + int size = methodList.size(); + for (int i = 0; i < size; i++) { + if ((methodList.get(i)) + .getType().equalArguments(method.getType())) { + methodList.set(i, method); + return; + } + } + + // We add the method to the appropriate list. + methodList.add(method); + count++; + } + + /** + * If the MethodSet contains a method with the same signature + * then lookup() returns it. Otherwise, this method returns null. + */ + public MemberDefinition lookupSig(Identifier name, Type type) { + // Go through all methods of the same name and see if any + // have the right signature. + Iterator matches = lookupName(name); + MemberDefinition candidate; + + while (matches.hasNext()) { + candidate = matches.next(); + if (candidate.getType().equalArguments(type)) { + return candidate; + } + } + + // No match. + return null; + } + + /** + * Returns an Iterator of all methods contained in the + * MethodSet which have a given name. + */ + public Iterator lookupName(Identifier name) { + // Find the List containing all methods of this name, and + // return that List's Iterator. + List methodList = lookupMap.get(name); + if (methodList == null) { + // If there is no method of this name, return a bogus, empty + // Iterator. + return Collections.emptyIterator(); + } + return methodList.iterator(); + } + + /** + * Returns an Iterator of all methods in the MethodSet + */ + public Iterator iterator() { + + //---------------------------------------------------------- + // The inner class MethodIterator is used to create our + // Iterator of all methods in the MethodSet. + class MethodIterator implements Iterator { + Iterator> hashIter = lookupMap.values().iterator(); + Iterator listIter = Collections.emptyIterator(); + + public boolean hasNext() { + if (listIter.hasNext()) { + return true; + } else { + if (hashIter.hasNext()) { + listIter = hashIter.next().iterator(); + + // The following should be always true. + if (listIter.hasNext()) { + return true; + } else { + throw new + CompilerError("iterator() in MethodSet"); + } + } + } + + // We've run out of Lists. + return false; + } + + public MemberDefinition next() { + return listIter.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + } + // end MethodIterator + //---------------------------------------------------------- + + // A one-liner. + return new MethodIterator(); + } + + /** + * After freeze() is called, the MethodSet becomes (mostly) + * immutable. Any calls to add() or addMeet() lead to + * CompilerErrors. Note that the entries themselves are still + * (unfortunately) open for mischievous and wanton modification. + */ + public void freeze() { + frozen = true; + } + + /** + * Tells whether freeze() has been called on this MethodSet. + */ + public boolean isFrozen() { + return frozen; + } + + /** + * Returns a (big) string representation of this MethodSet + */ + public String toString() { + int len = size(); + StringBuilder sb = new StringBuilder(); + Iterator all = iterator(); + sb.append("{"); + + while (all.hasNext()) { + sb.append(all.next().toString()); + len--; + if (len > 0) { + sb.append(", "); + } + } + sb.append("}"); + return sb.toString(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/MethodType.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/MethodType.java new file mode 100644 index 000000000..d75f7ee24 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/MethodType.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import org.glassfish.rmic.TypeCode; + +/** + * This class represents an Java method type. + * It overrides the relevant methods in class Type. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ +public final +class MethodType extends Type { + /** + * The return type. + */ + Type returnType; + + /** + * The argument types. + */ + Type argTypes[]; + + /** + * Construct a method type. Use Type.tMethod to create + * a new method type. + * @see Type.tMethod + */ + MethodType(String typeSig, Type returnType, Type argTypes[]) { + super(TypeCode.METHOD, typeSig); + this.returnType = returnType; + this.argTypes = argTypes; + } + + public Type getReturnType() { + return returnType; + } + + public Type getArgumentTypes()[] { + return argTypes; + } + + public boolean equalArguments(Type t) { + if (t.getTypeCode() != TC_METHOD) { + return false; + } + MethodType m = (MethodType)t; + if (argTypes.length != m.argTypes.length) { + return false; + } + for (int i = argTypes.length - 1 ; i >= 0 ; i--) { + if (argTypes[i] != m.argTypes[i]) { + return false; + } + } + return true; + } + + public int stackSize() { + int n = 0; + for (int i = 0 ; i < argTypes.length ; i++) { + n += argTypes[i].stackSize(); + } + return n; + } + + public String typeString(String id, boolean abbrev, boolean ret) { + StringBuilder sb = new StringBuilder(); + sb.append(id); + sb.append('('); + for (int i = 0 ; i < argTypes.length ; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(argTypes[i].typeString("", abbrev, ret)); + } + sb.append(')'); + + return ret ? getReturnType().typeString(sb.toString(), abbrev, ret) : sb.toString(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Package.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Package.java new file mode 100644 index 000000000..2324a19da --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Package.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1995, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.File; + +/** + * This class is used to represent the classes in a package. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class Package { + /** + * The path which we use to locate source files. + */ + private final ClassPath sourcePath = new ClassPath(""); + + /** + * The path which we use to locate class (binary) files. + */ + private ClassPath binaryPath; + + /** + * The path name of the package. + */ + private String pkg; + + /** + * Create a package given a source path, binary path, and package + * name. + */ + public Package(ClassPath binaryPath, Identifier pkg) { + if (pkg.isInner()) + pkg = Identifier.lookup(pkg.getQualifier(), pkg.getFlatName()); + this.binaryPath = binaryPath; + this.pkg = pkg.toString().replace('.', File.separatorChar); + } + + /** + * Check if a class is defined in this package. + * (If it is an inner class name, it is assumed to exist + * only if its binary file exists. This is somewhat pessimistic.) + */ + public boolean classExists(Identifier className) { + return getBinaryFile(className) != null || + !className.isInner() && + getSourceFile(className) != null; + } + + /** + * Check if the package exists + */ + public boolean exists() { + // Look for the directory on our binary path. + ClassFile dir = binaryPath.getDirectory(pkg); + if (dir != null && dir.isDirectory()) { + return true; + } + + /* Accommodate ZIP files without CEN entries for directories + * (packages): look on class path for at least one binary + * file or one source file with the right package prefix + */ + String prefix = pkg + File.separator; + + return binaryPath.getFiles(prefix, ".class").hasMoreElements(); + } + + private String makeName(String fileName) { + return pkg.equals("") ? fileName : pkg + File.separator + fileName; + } + + /** + * Get the .class file of a class + */ + public ClassFile getBinaryFile(Identifier className) { + className = Type.mangleInnerType(className); + String fileName = className.toString() + ".class"; + return binaryPath.getFile(makeName(fileName)); + } + + /** + * Get the .java file of a class + */ + public ClassFile getSourceFile(Identifier className) { + // The source file of an inner class is that of its outer class. + className = className.getTopName(); + String fileName = className.toString() + ".java"; + return sourcePath.getFile(makeName(fileName)); + } + + public ClassFile getSourceFile(String fileName) { + if (fileName.endsWith(".java")) { + return sourcePath.getFile(makeName(fileName)); + } + return null; + } + + public String toString() { + if (pkg.equals("")) { + return "unnamed package"; + } + return "package " + pkg; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Parser.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Parser.java new file mode 100644 index 000000000..09cea609a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Parser.java @@ -0,0 +1,2115 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import org.glassfish.rmic.tools.tree.*; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Vector; + +/** + * This class is used to parse Java statements and expressions. + * The result is a parse tree.

                + * + * This class implements an operator precedence parser. Errors are + * reported to the Environment object, if the error can't be + * resolved immediately, a SyntaxError exception is thrown.

                + * + * Error recovery is implemented by catching SyntaxError exceptions + * and discarding input tokens until an input token is reached that + * is possibly a legal continuation.

                + * + * The parse tree that is constructed represents the input + * exactly (no rewrites to simpler forms). This is important + * if the resulting tree is to be used for code formatting in + * a programming environment. Currently only documentation comments + * are retained.

                + * + * The parsing algorithm does NOT use any type information. Changes + * in the type system do not affect the structure of the parse tree. + * This restriction does introduce an ambiguity an expression of the + * form: (e1) e2 is assumed to be a cast if e2 does not start with + * an operator. That means that (a) - b is interpreted as subtract + * b from a and not cast negative b to type a. However, if a is a + * simple type (byte, int, ...) then it is assumed to be a cast.

                + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ + +public +class Parser extends Scanner implements ParserActions, Constants { + /** + * Create a parser + */ + protected Parser(Environment env, InputStream in) throws IOException { + super(env, in); + this.scanner = this; + this.actions = this; + } + + /** + * Create a parser, given a scanner. + */ + protected Parser(Scanner scanner) throws IOException { + super(scanner.env); + this.scanner = scanner; + ((Scanner)this).env = scanner.env; + ((Scanner)this).token = scanner.token; + ((Scanner)this).pos = scanner.pos; + this.actions = this; + } + + /** + * Create a parser, given a scanner and the semantic callback. + */ + public Parser(Scanner scanner, ParserActions actions) throws IOException { + this(scanner); + this.actions = actions; + } + + /** + * Usually this.actions == (ParserActions)this. + * However, a delegate scanner can produce tokens for this parser, + * in which case (Scanner)this is unused, + * except for this.token and this.pos + * instance variables which are filled from the real scanner + * by this.scan() and the constructor. + */ + ParserActions actions; + + // Note: The duplication of methods allows pre-1.1 classes to + // be binary compatible with the new version of the parser, + // which now passes IdentifierTokens to the semantics phase, + // rather than just Identifiers. This change is necessary, + // since the parser is no longer responsible for managing the + // resolution of type names. (That caused the "Vector" bug.) + // + // In a future release, the old "plain-Identifier" methods will + // go away, and the corresponding "IdentifierToken" methods + // may become abstract. + + /** + * package declaration + * @deprecated + */ + @Deprecated + public void packageDeclaration(long off, IdentifierToken nm) { + // By default, call the deprecated version. + // Any application must override one of the packageDeclaration methods. + packageDeclaration(off, nm.id); + } + /** + * @deprecated + */ + @Deprecated + protected void packageDeclaration(long off, Identifier nm) { + throw new RuntimeException("beginClass method is abstract"); + } + + /** + * import class + * @deprecated + */ + @Deprecated + public void importClass(long off, IdentifierToken nm) { + // By default, call the deprecated version. + // Any application must override one of the packageDeclaration methods. + importClass(off, nm.id); + } + /** + * @deprecated Use the version with the IdentifierToken arguments. + */ + @Deprecated + protected void importClass(long off, Identifier nm) { + throw new RuntimeException("importClass method is abstract"); + } + + /** + * import package + * @deprecated + */ + @Deprecated + public void importPackage(long off, IdentifierToken nm) { + // By default, call the deprecated version. + // Any application must override one of the importPackage methods. + importPackage(off, nm.id); + } + /** + * @deprecated Use the version with the IdentifierToken arguments. + */ + @Deprecated + protected void importPackage(long off, Identifier nm) { + throw new RuntimeException("importPackage method is abstract"); + } + + /** + * Define class + * @deprecated + */ + @Deprecated + public ClassDefinition beginClass(long off, String doc, + int mod, IdentifierToken nm, + IdentifierToken sup, + IdentifierToken impl[]) { + // By default, call the deprecated version. + // Any application must override one of the beginClass methods. + Identifier supId = (sup == null) ? null : sup.id; + Identifier implIds[] = null; + if (impl != null) { + implIds = new Identifier[impl.length]; + for (int i = 0; i < impl.length; i++) { + implIds[i] = impl[i].id; + } + } + beginClass(off, doc, mod, nm.id, supId, implIds); + return getCurrentClass(); + } + /** + * @deprecated Use the version with the IdentifierToken arguments. + */ + @Deprecated + protected void beginClass(long off, String doc, int mod, Identifier nm, + Identifier sup, Identifier impl[]) { + throw new RuntimeException("beginClass method is abstract"); + } + + /** + * Report the current class under construction. + * By default, it's a no-op which returns null. + * It may only be called before the corresponding endClass(). + */ + protected ClassDefinition getCurrentClass() { + return null; + } + + /** + * End class + * @deprecated + */ + @Deprecated + public void endClass(long off, ClassDefinition c) { + // By default, call the deprecated version. + // Any application must override one of the beginClass methods. + endClass(off, c.getName().getFlatName().getName()); + } + /** + * @deprecated Use the version with the IdentifierToken arguments. + */ + @Deprecated + protected void endClass(long off, Identifier nm) { + throw new RuntimeException("endClass method is abstract"); + } + + /** + * Define a field + * @deprecated + */ + @Deprecated + public void defineField(long where, ClassDefinition c, + String doc, int mod, Type t, + IdentifierToken nm, IdentifierToken args[], + IdentifierToken exp[], Node val) { + // By default, call the deprecated version. + // Any application must override one of the defineField methods. + Identifier argIds[] = null; + Identifier expIds[] = null; + if (args != null) { + argIds = new Identifier[args.length]; + for (int i = 0; i < args.length; i++) { + argIds[i] = args[i].id; + } + } + if (exp != null) { + expIds = new Identifier[exp.length]; + for (int i = 0; i < exp.length; i++) { + expIds[i] = exp[i].id; + } + } + defineField(where, doc, mod, t, nm.id, argIds, expIds, val); + } + + /** + * @deprecated Use the version with the IdentifierToken arguments. + */ + @Deprecated + protected void defineField(long where, String doc, int mod, Type t, + Identifier nm, Identifier args[], + Identifier exp[], Node val) { + throw new RuntimeException("defineField method is abstract"); + } + + /* + * A growable array of nodes. It is used as a growable + * buffer to hold argument lists and expression lists. + * I'm not using Vector to make it more efficient. + */ + private Node args[] = new Node[32]; + protected int argIndex = 0; + + protected final void addArgument(Node n) { + if (argIndex == args.length) { + Node newArgs[] = new Node[args.length * 2]; + System.arraycopy(args, 0, newArgs, 0, args.length); + args = newArgs; + } + args[argIndex++] = n; + } + protected final Expression exprArgs(int index)[] { + Expression e[] = new Expression[argIndex - index]; + System.arraycopy(args, index, e, 0, argIndex - index); + argIndex = index; + return e; + } + protected final Statement statArgs(int index)[] { + Statement s[] = new Statement[argIndex - index]; + System.arraycopy(args, index, s, 0, argIndex - index); + argIndex = index; + return s; + } + + /** + * Expect a token, return its value, scan the next token or + * throw an exception. + */ + protected void expect(int t) throws SyntaxError, IOException { + if (token != t) { + switch (t) { + case IDENT: + env.error(scanner.prevPos, "identifier.expected"); + break; + default: + env.error(scanner.prevPos, "token.expected", opNames[t]); + break; + } + throw new SyntaxError(); + } + scan(); + } + + /** + * Parse a type expression. Does not parse the []'s. + */ + protected Expression parseTypeExpression() throws SyntaxError, IOException { + switch (token) { + case VOID: + return new TypeExpression(scan(), Type.tVoid); + case BOOLEAN: + return new TypeExpression(scan(), Type.tBoolean); + case BYTE: + return new TypeExpression(scan(), Type.tByte); + case CHAR: + return new TypeExpression(scan(), Type.tChar); + case SHORT: + return new TypeExpression(scan(), Type.tShort); + case INT: + return new TypeExpression(scan(), Type.tInt); + case LONG: + return new TypeExpression(scan(), Type.tLong); + case FLOAT: + return new TypeExpression(scan(), Type.tFloat); + case DOUBLE: + return new TypeExpression(scan(), Type.tDouble); + case IDENT: + Expression e = new IdentifierExpression(pos, scanner.idValue); + scan(); + while (token == FIELD) { + e = new FieldExpression(scan(), e, scanner.idValue); + expect(IDENT); + } + return e; + } + + env.error(pos, "type.expected"); + throw new SyntaxError(); + } + + /** + * Parse a method invocation. Should be called when the current + * then is the '(' of the argument list. + */ + protected Expression parseMethodExpression(Expression e, Identifier id) throws SyntaxError, IOException { + long p = scan(); + int i = argIndex; + if (token != RPAREN) { + addArgument(parseExpression()); + while (token == COMMA) { + scan(); + addArgument(parseExpression()); + } + } + expect(RPAREN); + return new MethodExpression(p, e, id, exprArgs(i)); + } + + /** + * Parse a new instance expression. Should be called when the current + * token is the '(' of the argument list. + */ + protected Expression parseNewInstanceExpression(long p, Expression outerArg, Expression type) throws SyntaxError, IOException { + int i = argIndex; + expect(LPAREN); + if (token != RPAREN) { + addArgument(parseExpression()); + while (token == COMMA) { + scan(); + addArgument(parseExpression()); + } + } + expect(RPAREN); + ClassDefinition body = null; + if (token == LBRACE && !(type instanceof TypeExpression)) { + long tp = pos; + // x = new Type(arg) { subclass body ... } + Identifier superName = FieldExpression.toIdentifier(type); + if (superName == null) { + env.error(type.getWhere(), "type.expected"); + } + Vector ext = new Vector<>(1); + Vector impl = new Vector<>(0); + ext.addElement(new IdentifierToken(idNull)); + if (token == IMPLEMENTS || token == EXTENDS) { + env.error(pos, "anonymous.extends"); + parseInheritance(ext, impl); // error recovery + } + body = parseClassBody(new IdentifierToken(tp, idNull), + M_ANONYMOUS | M_LOCAL, EXPR, null, + ext, impl, type.getWhere()); + } + if (outerArg == null && body == null) { + return new NewInstanceExpression(p, type, exprArgs(i)); + } + return new NewInstanceExpression(p, type, exprArgs(i), outerArg, body); + } + + /** + * Parse a primary expression. + */ + protected Expression parseTerm() throws SyntaxError, IOException { + switch (token) { + case CHARVAL: { + char v = scanner.charValue; + return new CharExpression(scan(), v); + } + case INTVAL: { + int v = scanner.intValue; + long q = scan(); + if (v < 0 && radix == 10) env.error(q, "overflow.int.dec"); + return new IntExpression(q, v); + } + case LONGVAL: { + long v = scanner.longValue; + long q = scan(); + if (v < 0 && radix == 10) env.error(q, "overflow.long.dec"); + return new LongExpression(q, v); + } + case FLOATVAL: { + float v = scanner.floatValue; + return new FloatExpression(scan(), v); + } + case DOUBLEVAL: { + double v = scanner.doubleValue; + return new DoubleExpression(scan(), v); + } + case STRINGVAL: { + String v = scanner.stringValue; + return new StringExpression(scan(), v); + } + case IDENT: { + Identifier v = scanner.idValue; + long p = scan(); + return (token == LPAREN) ? + parseMethodExpression(null, v) : new IdentifierExpression(p, v); + } + + case TRUE: + return new BooleanExpression(scan(), true); + case FALSE: + return new BooleanExpression(scan(), false); + case NULL: + return new NullExpression(scan()); + + case THIS: { + Expression e = new ThisExpression(scan()); + return (token == LPAREN) ? parseMethodExpression(e, idInit) : e; + } + case SUPER: { + Expression e = new SuperExpression(scan()); + return (token == LPAREN) ? parseMethodExpression(e, idInit) : e; + } + + case VOID: + case BOOLEAN: + case BYTE: + case CHAR: + case SHORT: + case INT: + case LONG: + case FLOAT: + case DOUBLE: + return parseTypeExpression(); + + case ADD: { + long p = scan(); + switch (token) { + case INTVAL: { + int v = scanner.intValue; + long q = scan(); + if (v < 0 && radix == 10) env.error(q, "overflow.int.dec"); + return new IntExpression(q, v); + } + case LONGVAL: { + long v = scanner.longValue; + long q = scan(); + if (v < 0 && radix == 10) env.error(q, "overflow.long.dec"); + return new LongExpression(q, v); + } + case FLOATVAL: { + float v = scanner.floatValue; + return new FloatExpression(scan(), v); + } + case DOUBLEVAL: { + double v = scanner.doubleValue; + return new DoubleExpression(scan(), v); + } + } + return new PositiveExpression(p, parseTerm()); + } + case SUB: { + long p = scan(); + switch (token) { + case INTVAL: { + int v = -scanner.intValue; + return new IntExpression(scan(), v); + } + case LONGVAL: { + long v = -scanner.longValue; + return new LongExpression(scan(), v); + } + case FLOATVAL: { + float v = -scanner.floatValue; + return new FloatExpression(scan(), v); + } + case DOUBLEVAL: { + double v = -scanner.doubleValue; + return new DoubleExpression(scan(), v); + } + } + return new NegativeExpression(p, parseTerm()); + } + case NOT: + return new NotExpression(scan(), parseTerm()); + case BITNOT: + return new BitNotExpression(scan(), parseTerm()); + case INC: + return new PreIncExpression(scan(), parseTerm()); + case DEC: + return new PreDecExpression(scan(), parseTerm()); + + case LPAREN: { + // bracketed-expr: (expr) + long p = scan(); + Expression e = parseExpression(); + expect(RPAREN); + + if (e.getOp() == TYPE) { + // cast-expr: (simple-type) expr + return new CastExpression(p, e, parseTerm()); + } + + switch (token) { + + // We handle INC and DEC specially. + // See the discussion in JLS section 15.14.1. + // (Part of fix for 4044502.) + + case INC: + // We know this must be a postfix increment. + return new PostIncExpression(scan(), e); + + case DEC: + // We know this must be a postfix decrement. + return new PostDecExpression(scan(), e); + + case LPAREN: + case CHARVAL: + case INTVAL: + case LONGVAL: + case FLOATVAL: + case DOUBLEVAL: + case STRINGVAL: + case IDENT: + case TRUE: + case FALSE: + case NOT: + case BITNOT: + case THIS: + case SUPER: + case NULL: + case NEW: + // cast-expr: (expr) expr + return new CastExpression(p, e, parseTerm()); + } + return new ExprExpression(p, e); + } + + case LBRACE: { + // array initializer: {expr1, expr2, ... exprn} + long p = scan(); + int i = argIndex; + if (token != RBRACE) { + addArgument(parseExpression()); + while (token == COMMA) { + scan(); + if (token == RBRACE) { + break; + } + addArgument(parseExpression()); + } + } + expect(RBRACE); + return new ArrayExpression(p, exprArgs(i)); + } + + case NEW: { + long p = scan(); + int i = argIndex; + + if (token == LPAREN) { + scan(); + Expression e = parseExpression(); + expect(RPAREN); + env.error(p, "not.supported", "new(...)"); + return new NullExpression(p); + } + + Expression e = parseTypeExpression(); + + if (token == LSQBRACKET) { + while (token == LSQBRACKET) { + scan(); + addArgument((token != RSQBRACKET) ? parseExpression() : null); + expect(RSQBRACKET); + } + Expression[] dims = exprArgs(i); + if (token == LBRACE) { + return new NewArrayExpression(p, e, dims, parseTerm()); + } + return new NewArrayExpression(p, e, dims); + } else { + return parseNewInstanceExpression(p, null, e); + } + } + } + + // System.err.println("NEAR: " + opNames[token]); + env.error(scanner.prevPos, "missing.term"); + return new IntExpression(pos, 0); + } + + /** + * Parse an expression. + */ + protected Expression parseExpression() throws SyntaxError, IOException { + for (Expression e = parseTerm() ; e != null ; e = e.order()) { + Expression more = parseBinaryExpression(e); + if (more == null) + return e; + e = more; + } + // this return is bogus + return null; + } + + /** + * Given a left-hand term, parse an operator and right-hand term. + */ + protected Expression parseBinaryExpression(Expression e) throws SyntaxError, IOException { + if (e != null) { + switch (token) { + case LSQBRACKET: { + // index: expr1[expr2] + long p = scan(); + Expression index = (token != RSQBRACKET) ? parseExpression() : null; + expect(RSQBRACKET); + e = new ArrayAccessExpression(p, e, index); + break; + } + + case INC: + e = new PostIncExpression(scan(), e); + break; + case DEC: + e = new PostDecExpression(scan(), e); + break; + case FIELD: { + long p = scan(); + if (token == THIS) { + // class C { class N { ... C.this ... } } + // class C { class N { N(C c){ ... c.this() ... } } } + long q = scan(); + if (token == LPAREN) { + e = new ThisExpression(q, e); + e = parseMethodExpression(e, idInit); + } else { + e = new FieldExpression(p, e, idThis); + } + break; + } + if (token == SUPER) { + // class D extends C.N { D(C.N n) { n.super(); } } + // Also, 'C.super', as in: + // class C extends CS { class N { ... C.super.foo ... } } + // class C extends CS { class N { ... C.super.foo() ... } } + long q = scan(); + if (token == LPAREN) { + e = new SuperExpression(q, e); + e = parseMethodExpression(e, idInit); + } else { + // We must check elsewhere that this expression + // does not stand alone, but qualifies a member name. + e = new FieldExpression(p, e, idSuper); + } + break; + } + if (token == NEW) { + // new C().new N() + scan(); + if (token != IDENT) + expect(IDENT); + e = parseNewInstanceExpression(p, e, parseTypeExpression()); + break; + } + if (token == CLASS) { + // just class literals, really + // Class c = C.class; + scan(); + e = new FieldExpression(p, e, idClass); + break; + } + Identifier id = scanner.idValue; + expect(IDENT); + if (token == LPAREN) { + e = parseMethodExpression(e, id); + } else { + e = new FieldExpression(p, e, id); + } + break; + } + case INSTANCEOF: + e = new InstanceOfExpression(scan(), e, parseTerm()); + break; + case ADD: + e = new AddExpression(scan(), e, parseTerm()); + break; + case SUB: + e = new SubtractExpression(scan(), e, parseTerm()); + break; + case MUL: + e = new MultiplyExpression(scan(), e, parseTerm()); + break; + case DIV: + e = new DivideExpression(scan(), e, parseTerm()); + break; + case REM: + e = new RemainderExpression(scan(), e, parseTerm()); + break; + case LSHIFT: + e = new ShiftLeftExpression(scan(), e, parseTerm()); + break; + case RSHIFT: + e = new ShiftRightExpression(scan(), e, parseTerm()); + break; + case URSHIFT: + e = new UnsignedShiftRightExpression(scan(), e, parseTerm()); + break; + case LT: + e = new LessExpression(scan(), e, parseTerm()); + break; + case LE: + e = new LessOrEqualExpression(scan(), e, parseTerm()); + break; + case GT: + e = new GreaterExpression(scan(), e, parseTerm()); + break; + case GE: + e = new GreaterOrEqualExpression(scan(), e, parseTerm()); + break; + case EQ: + e = new EqualExpression(scan(), e, parseTerm()); + break; + case NE: + e = new NotEqualExpression(scan(), e, parseTerm()); + break; + case BITAND: + e = new BitAndExpression(scan(), e, parseTerm()); + break; + case BITXOR: + e = new BitXorExpression(scan(), e, parseTerm()); + break; + case BITOR: + e = new BitOrExpression(scan(), e, parseTerm()); + break; + case AND: + e = new AndExpression(scan(), e, parseTerm()); + break; + case OR: + e = new OrExpression(scan(), e, parseTerm()); + break; + case ASSIGN: + e = new AssignExpression(scan(), e, parseTerm()); + break; + case ASGMUL: + e = new AssignMultiplyExpression(scan(), e, parseTerm()); + break; + case ASGDIV: + e = new AssignDivideExpression(scan(), e, parseTerm()); + break; + case ASGREM: + e = new AssignRemainderExpression(scan(), e, parseTerm()); + break; + case ASGADD: + e = new AssignAddExpression(scan(), e, parseTerm()); + break; + case ASGSUB: + e = new AssignSubtractExpression(scan(), e, parseTerm()); + break; + case ASGLSHIFT: + e = new AssignShiftLeftExpression(scan(), e, parseTerm()); + break; + case ASGRSHIFT: + e = new AssignShiftRightExpression(scan(), e, parseTerm()); + break; + case ASGURSHIFT: + e = new AssignUnsignedShiftRightExpression(scan(), e, parseTerm()); + break; + case ASGBITAND: + e = new AssignBitAndExpression(scan(), e, parseTerm()); + break; + case ASGBITOR: + e = new AssignBitOrExpression(scan(), e, parseTerm()); + break; + case ASGBITXOR: + e = new AssignBitXorExpression(scan(), e, parseTerm()); + break; + case QUESTIONMARK: { + long p = scan(); + Expression second = parseExpression(); + expect(COLON); + Expression third = parseExpression(); + + // The grammar in the JLS does not allow assignment + // expressions as the third part of a ?: expression. + // Even though javac has no trouble parsing this, + // check for this case and signal an error. + // (fix for bug 4092958) + if (third instanceof AssignExpression + || third instanceof AssignOpExpression) { + env.error(third.getWhere(), "assign.in.conditionalexpr"); + } + + e = new ConditionalExpression(p, e, second, third); + break; + } + + default: + return null; // mark end of binary expressions + } + } + return e; // return more binary expression stuff + } + + /** + * Recover after a syntax error in a statement. This involves + * discarding tokens until EOF or a possible continuation is + * encountered. + */ + protected boolean recoverStatement() throws SyntaxError, IOException { + while (true) { + switch (token) { + case EOF: + case RBRACE: + case LBRACE: + case IF: + case FOR: + case WHILE: + case DO: + case TRY: + case CATCH: + case FINALLY: + case BREAK: + case CONTINUE: + case RETURN: + // begin of a statement, return + return true; + + case VOID: + case STATIC: + case PUBLIC: + case PRIVATE: + case SYNCHRONIZED: + case INTERFACE: + case CLASS: + case TRANSIENT: + // begin of something outside a statement, panic some more + expect(RBRACE); + return false; + + case LPAREN: + match(LPAREN, RPAREN); + scan(); + break; + + case LSQBRACKET: + match(LSQBRACKET, RSQBRACKET); + scan(); + break; + + default: + // don't know what to do, skip + scan(); + break; + } + } + } + + /** + * Parse declaration, called after the type expression + * has been parsed and the current token is IDENT. + */ + protected Statement parseDeclaration(long p, int mod, Expression type) throws SyntaxError, IOException { + int i = argIndex; + if (token == IDENT) { + addArgument(new VarDeclarationStatement(pos, parseExpression())); + while (token == COMMA) { + scan(); + addArgument(new VarDeclarationStatement(pos, parseExpression())); + } + } + return new DeclarationStatement(p, mod, type, statArgs(i)); + } + + /** + * Check if an expression is a legal toplevel expression. + * Only method, inc, dec, and new expression are allowed. + */ + protected void topLevelExpression(Expression e) { + switch (e.getOp()) { + case ASSIGN: + case ASGMUL: + case ASGDIV: + case ASGREM: + case ASGADD: + case ASGSUB: + case ASGLSHIFT: + case ASGRSHIFT: + case ASGURSHIFT: + case ASGBITAND: + case ASGBITOR: + case ASGBITXOR: + case PREINC: + case PREDEC: + case POSTINC: + case POSTDEC: + case METHOD: + case NEWINSTANCE: + return; + } + env.error(e.getWhere(), "invalid.expr"); + } + + /** + * Parse a statement. + */ + protected Statement parseStatement() throws SyntaxError, IOException { + switch (token) { + case SEMICOLON: + return new CompoundStatement(scan(), new Statement[0]); + + case LBRACE: + return parseBlockStatement(); + + case IF: { + // if-statement: if (expr) stat + // if-statement: if (expr) stat else stat + long p = scan(); + + expect(LPAREN); + Expression c = parseExpression(); + expect(RPAREN); + Statement t = parseStatement(); + if (token == ELSE) { + scan(); + return new IfStatement(p, c, t, parseStatement()); + } else { + return new IfStatement(p, c, t, null); + } + } + + case ELSE: { + // else-statement: else stat + env.error(scan(), "else.without.if"); + return parseStatement(); + } + + case FOR: { + // for-statement: for (decl-expr? ; expr? ; expr?) stat + long p = scan(); + Statement init = null; + Expression cond = null, inc = null; + + expect(LPAREN); + if (token != SEMICOLON) { + long p2 = pos; + int mod = parseModifiers(M_FINAL); + Expression e = parseExpression(); + + if (token == IDENT) { + init = parseDeclaration(p2, mod, e); + } else { + if (mod != 0) { + expect(IDENT); // should have been a declaration + } + topLevelExpression(e); + while (token == COMMA) { + long p3 = scan(); + Expression e2 = parseExpression(); + topLevelExpression(e2); + e = new CommaExpression(p3, e, e2); + } + init = new ExpressionStatement(p2, e); + } + } + expect(SEMICOLON); + if (token != SEMICOLON) { + cond = parseExpression(); + } + expect(SEMICOLON); + if (token != RPAREN) { + inc = parseExpression(); + topLevelExpression(inc); + while (token == COMMA) { + long p2 = scan(); + Expression e2 = parseExpression(); + topLevelExpression(e2); + inc = new CommaExpression(p2, inc, e2); + } + } + expect(RPAREN); + return new ForStatement(p, init, cond, inc, parseStatement()); + } + + case WHILE: { + // while-statement: while (expr) stat + long p = scan(); + + expect(LPAREN); + Expression cond = parseExpression(); + expect(RPAREN); + return new WhileStatement(p, cond, parseStatement()); + } + + case DO: { + // do-statement: do stat while (expr) + long p = scan(); + + Statement body = parseStatement(); + expect(WHILE); + expect(LPAREN); + Expression cond = parseExpression(); + expect(RPAREN); + expect(SEMICOLON); + return new DoStatement(p, body, cond); + } + + case BREAK: { + // break-statement: break ; + long p = scan(); + Identifier label = null; + + if (token == IDENT) { + label = scanner.idValue; + scan(); + } + expect(SEMICOLON); + return new BreakStatement(p, label); + } + + case CONTINUE: { + // continue-statement: continue ; + long p = scan(); + Identifier label = null; + + if (token == IDENT) { + label = scanner.idValue; + scan(); + } + expect(SEMICOLON); + return new ContinueStatement(p, label); + } + + case RETURN: { + // return-statement: return ; + // return-statement: return expr ; + long p = scan(); + Expression e = null; + + if (token != SEMICOLON) { + e = parseExpression(); + } + expect(SEMICOLON); + return new ReturnStatement(p, e); + } + + case SWITCH: { + // switch statement: switch ( expr ) stat + long p = scan(); + int i = argIndex; + + expect(LPAREN); + Expression e = parseExpression(); + expect(RPAREN); + expect(LBRACE); + + while ((token != EOF) && (token != RBRACE)) { + int j = argIndex; + try { + switch (token) { + case CASE: + // case-statement: case expr: + addArgument(new CaseStatement(scan(), parseExpression())); + expect(COLON); + break; + + case DEFAULT: + // default-statement: default: + addArgument(new CaseStatement(scan(), null)); + expect(COLON); + break; + + default: + addArgument(parseStatement()); + break; + } + } catch (SyntaxError ee) { + argIndex = j; + if (!recoverStatement()) { + throw ee; + } + } + } + expect(RBRACE); + return new SwitchStatement(p, e, statArgs(i)); + } + + case CASE: { + // case-statement: case expr : stat + env.error(pos, "case.without.switch"); + while (token == CASE) { + scan(); + parseExpression(); + expect(COLON); + } + return parseStatement(); + } + + case DEFAULT: { + // default-statement: default : stat + env.error(pos, "default.without.switch"); + scan(); + expect(COLON); + return parseStatement(); + } + + case TRY: { + // try-statement: try stat catch (type-expr ident) stat finally stat + long p = scan(); + Statement init = null; // try-object specification + int i = argIndex; + boolean catches = false; + + if (false && token == LPAREN) { + expect(LPAREN); + long p2 = pos; + int mod = parseModifiers(M_FINAL); + Expression e = parseExpression(); + + if (token == IDENT) { + init = parseDeclaration(p2, mod, e); + // leave check for try (T x, y) for semantic phase + } else { + if (mod != 0) { + expect(IDENT); // should have been a declaration + } + init = new ExpressionStatement(p2, e); + } + expect(RPAREN); + } + + Statement s = parseBlockStatement(); + + if (init != null) { + // s = new FinallyStatement(p, init, s, 0); + } + + while (token == CATCH) { + long pp = pos; + expect(CATCH); + expect(LPAREN); + int mod = parseModifiers(M_FINAL); + Expression t = parseExpression(); + IdentifierToken id = scanner.getIdToken(); + expect(IDENT); + id.modifiers = mod; + // We only catch Throwable's, so this is no longer required + // while (token == LSQBRACKET) { + // t = new ArrayAccessExpression(scan(), t, null); + // expect(RSQBRACKET); + // } + expect(RPAREN); + addArgument(new CatchStatement(pp, t, id, parseBlockStatement())); + catches = true; + } + + if (catches) + s = new TryStatement(p, s, statArgs(i)); + + if (token == FINALLY) { + scan(); + return new FinallyStatement(p, s, parseBlockStatement()); + } else if (catches || init != null) { + return s; + } else { + env.error(pos, "try.without.catch.finally"); + return new TryStatement(p, s, null); + } + } + + case CATCH: { + // catch-statement: catch (expr ident) stat finally stat + env.error(pos, "catch.without.try"); + + Statement s; + do { + scan(); + expect(LPAREN); + parseModifiers(M_FINAL); + parseExpression(); + expect(IDENT); + expect(RPAREN); + s = parseBlockStatement(); + } while (token == CATCH); + + if (token == FINALLY) { + scan(); + s = parseBlockStatement(); + } + return s; + } + + case FINALLY: { + // finally-statement: finally stat + env.error(pos, "finally.without.try"); + scan(); + return parseBlockStatement(); + } + + case THROW: { + // throw-statement: throw expr; + long p = scan(); + Expression e = parseExpression(); + expect(SEMICOLON); + return new ThrowStatement(p, e); + } + + case GOTO: { + long p = scan(); + expect(IDENT); + expect(SEMICOLON); + env.error(p, "not.supported", "goto"); + return new CompoundStatement(p, new Statement[0]); + } + + case SYNCHRONIZED: { + // synchronized-statement: synchronized (expr) stat + long p = scan(); + expect(LPAREN); + Expression e = parseExpression(); + expect(RPAREN); + return new SynchronizedStatement(p, e, parseBlockStatement()); + } + + case INTERFACE: + case CLASS: + // Inner class. + return parseLocalClass(0); + + case CONST: + case ABSTRACT: + case FINAL: + case STRICTFP: { + // a declaration of some sort + long p = pos; + + // A class which is local to a block is not a member, and so + // cannot be public, private, protected, or static. It is in + // effect private to the block, since it cannot be used outside + // its scope. + // + // However, any class (if it has a name) can be declared final, + // abstract, or strictfp. + int mod = parseModifiers(M_FINAL | M_ABSTRACT + | M_STRICTFP ); + + switch (token) { + case INTERFACE: + case CLASS: + return parseLocalClass(mod); + + case BOOLEAN: + case BYTE: + case CHAR: + case SHORT: + case INT: + case LONG: + case FLOAT: + case DOUBLE: + case IDENT: { + if ((mod & (M_ABSTRACT | M_STRICTFP )) != 0) { + mod &= ~ (M_ABSTRACT | M_STRICTFP ); + expect(CLASS); + } + Expression e = parseExpression(); + if (token != IDENT) { + expect(IDENT); + } + // declaration: final expr expr + Statement s = parseDeclaration(p, mod, e); + expect(SEMICOLON); + return s; + } + + default: + env.error(pos, "type.expected"); + throw new SyntaxError(); + } + } + + case VOID: + case STATIC: + case PUBLIC: + case PRIVATE: + case TRANSIENT: + // This is the start of something outside a statement + env.error(pos, "statement.expected"); + throw new SyntaxError(); + } + + long p = pos; + Expression e = parseExpression(); + + if (token == IDENT) { + // declaration: expr expr + Statement s = parseDeclaration(p, 0, e); + expect(SEMICOLON); + return s; + } + if (token == COLON) { + // label: id: stat + scan(); + Statement s = parseStatement(); + s.setLabel(env, e); + return s; + } + + // it was just an expression... + topLevelExpression(e); + expect(SEMICOLON); + return new ExpressionStatement(p, e); + } + + protected Statement parseBlockStatement() throws SyntaxError, IOException { + // compound statement: { stat1 stat2 ... statn } + if (token != LBRACE) { + // We're expecting a block statement. But we'll probably do the + // least damage if we try to parse a normal statement instead. + env.error(scanner.prevPos, "token.expected", opNames[LBRACE]); + return parseStatement(); + } + long p = scan(); + int i = argIndex; + while ((token != EOF) && (token != RBRACE)) { + int j = argIndex; + try { + addArgument(parseStatement()); + } catch (SyntaxError e) { + argIndex = j; + if (!recoverStatement()) { + throw e; + } + } + } + + expect(RBRACE); + return new CompoundStatement(p, statArgs(i)); + } + + + /** + * Parse an identifier. ie: a.b.c returns "a.b.c" + * If star is true then "a.b.*" is allowed. + * The return value encodes both the identifier and its location. + */ + protected IdentifierToken parseName(boolean star) throws SyntaxError, IOException { + IdentifierToken res = scanner.getIdToken(); + expect(IDENT); + + if (token != FIELD) { + return res; + } + + StringBuilder sb = new StringBuilder(res.id.toString()); + + while (token == FIELD) { + scan(); + if ((token == MUL) && star) { + scan(); + sb.append(".*"); + break; + } + + sb.append('.'); + if (token == IDENT) { + sb.append(scanner.idValue); + } + expect(IDENT); + } + + res.id = Identifier.lookup(sb.toString()); + return res; + } + /** + * @deprecated + * @see #parseName + */ + @Deprecated + protected Identifier parseIdentifier(boolean star) throws SyntaxError, IOException { + return parseName(star).id; + } + + /** + * Parse a type expression, this results in a Type. + * The parse includes trailing array brackets. + */ + protected Type parseType() throws SyntaxError, IOException { + Type t; + + switch (token) { + case IDENT: + t = Type.tClass(parseName(false).id); + break; + case VOID: + scan(); + t = Type.tVoid; + break; + case BOOLEAN: + scan(); + t = Type.tBoolean; + break; + case BYTE: + scan(); + t = Type.tByte; + break; + case CHAR: + scan(); + t = Type.tChar; + break; + case SHORT: + scan(); + t = Type.tShort; + break; + case INT: + scan(); + t = Type.tInt; + break; + case FLOAT: + scan(); + t = Type.tFloat; + break; + case LONG: + scan(); + t = Type.tLong; + break; + case DOUBLE: + scan(); + t = Type.tDouble; + break; + default: + env.error(pos, "type.expected"); + throw new SyntaxError(); + } + return parseArrayBrackets(t); + } + + /** + * Parse the tail of a type expression, which might be array brackets. + * Return the given type, as possibly modified by the suffix. + */ + protected Type parseArrayBrackets(Type t) throws SyntaxError, IOException { + + // Parse []'s + while (token == LSQBRACKET) { + scan(); + if (token != RSQBRACKET) { + env.error(pos, "array.dim.in.decl"); + parseExpression(); + } + expect(RSQBRACKET); + t = Type.tArray(t); + } + return t; + } + + /* + * Dealing with argument lists, I'm not using + * Vector for efficiency. + */ + + private int aCount = 0; + private Type aTypes[] = new Type[8]; + private IdentifierToken aNames[] = new IdentifierToken[aTypes.length]; + + private void addArgument(int mod, Type t, IdentifierToken nm) { + nm.modifiers = mod; + if (aCount >= aTypes.length) { + Type newATypes[] = new Type[aCount * 2]; + System.arraycopy(aTypes, 0, newATypes, 0, aCount); + aTypes = newATypes; + IdentifierToken newANames[] = new IdentifierToken[aCount * 2]; + System.arraycopy(aNames, 0, newANames, 0, aCount); + aNames = newANames; + } + aTypes[aCount] = t; + aNames[aCount++] = nm; + } + + /** + * Parse a possibly-empty sequence of modifier keywords. + * Return the resulting bitmask. + * Diagnose repeated modifiers, but make no other checks. + * Only modifiers mentioned in the given bitmask are scanned; + * an unmatched modifier must be handled by the caller. + */ + protected int parseModifiers(int mask) throws IOException { + int mod = 0; + while (true) { + if (token==CONST) { + // const isn't in java, but handle a common C++ usage gently + env.error(pos, "not.supported", "const"); + scan(); + } + int nextmod = 0; + switch (token) { + case PRIVATE: nextmod = M_PRIVATE; break; + case PUBLIC: nextmod = M_PUBLIC; break; + case PROTECTED: nextmod = M_PROTECTED; break; + case STATIC: nextmod = M_STATIC; break; + case TRANSIENT: nextmod = M_TRANSIENT; break; + case FINAL: nextmod = M_FINAL; break; + case ABSTRACT: nextmod = M_ABSTRACT; break; + case NATIVE: nextmod = M_NATIVE; break; + case VOLATILE: nextmod = M_VOLATILE; break; + case SYNCHRONIZED: nextmod = M_SYNCHRONIZED; break; + case STRICTFP: nextmod = M_STRICTFP; break; + } + if ((nextmod & mask) == 0) { + break; + } + if ((nextmod & mod) != 0) { + env.error(pos, "repeated.modifier"); + } + mod |= nextmod; + scan(); + } + return mod; + } + + private ClassDefinition curClass; + + /** + * Parse a field. + */ + protected void parseField() throws SyntaxError, IOException { + + // Empty fields are not allowed by the JLS but are accepted by + // the compiler, and much code has come to rely on this. It has + // been decided that the language will be extended to legitimize them. + if (token == SEMICOLON) { + // empty field + scan(); + return; + } + + // Optional doc comment + String doc = scanner.docComment; + + // The start of the field + long p = pos; + + // Parse the modifiers + int mod = parseModifiers(MM_FIELD | MM_METHOD); + + // Check for static initializer + // ie: static { ... } + // or an instance initializer (w/o the static). + if ((mod == (mod & M_STATIC)) && (token == LBRACE)) { + // static initializer + actions.defineField(p, curClass, doc, mod, + Type.tMethod(Type.tVoid), + new IdentifierToken(idClassInit), null, null, + parseStatement()); + return; + } + + // Check for inner class + if (token == CLASS || token == INTERFACE) { + parseNamedClass(mod, CLASS, doc); + return; + } + + // Parse the type + p = pos; + Type t = parseType(); + IdentifierToken id = null; + + // Check that the type is followed by an Identifier + // (the name of the method or the first variable), + // otherwise it is a constructor. + switch (token) { + case IDENT: + id = scanner.getIdToken(); + p = scan(); + break; + + case LPAREN: + // It is a constructor + id = new IdentifierToken(idInit); + if ((mod & M_STRICTFP) != 0) + env.error(pos, "bad.constructor.modifier"); + break; + + default: + expect(IDENT); + } + + // If the next token is a left-bracket then we + // are dealing with a method or constructor, otherwise it is + // a list of variables + if (token == LPAREN) { + // It is a method or constructor declaration + scan(); + aCount = 0; + + if (token != RPAREN) { + // Parse argument type and identifier + // (arguments (like locals) are allowed to be final) + int am = parseModifiers(M_FINAL); + Type at = parseType(); + IdentifierToken an = scanner.getIdToken(); + expect(IDENT); + + // Parse optional array specifier, ie: a[][] + at = parseArrayBrackets(at); + addArgument(am, at, an); + + // If the next token is a comma then there are + // more arguments + while (token == COMMA) { + // Parse argument type and identifier + scan(); + am = parseModifiers(M_FINAL); + at = parseType(); + an = scanner.getIdToken(); + expect(IDENT); + + // Parse optional array specifier, ie: a[][] + at = parseArrayBrackets(at); + addArgument(am, at, an); + } + } + expect(RPAREN); + + // Parse optional array sepecifier, ie: foo()[][] + t = parseArrayBrackets(t); + + // copy arguments + Type atypes[] = new Type[aCount]; + System.arraycopy(aTypes, 0, atypes, 0, aCount); + + IdentifierToken anames[] = new IdentifierToken[aCount]; + System.arraycopy(aNames, 0, anames, 0, aCount); + + // Construct the type signature + t = Type.tMethod(t, atypes); + + // Parse and ignore throws clause + IdentifierToken exp[] = null; + if (token == THROWS) { + Vector v = new Vector<>(); + scan(); + v.addElement(parseName(false)); + while (token == COMMA) { + scan(); + v.addElement(parseName(false)); + } + + exp = new IdentifierToken[v.size()]; + v.copyInto(exp); + } + + // Check if it is a method definition or a method declaration + // ie: foo() {...} or foo(); + switch (token) { + case LBRACE: // It's a method definition + + // Set the state of FP strictness for the body of the method + int oldFPstate = FPstate; + if ((mod & M_STRICTFP)!=0) { + FPstate = M_STRICTFP; + } else { + mod |= FPstate & M_STRICTFP; + } + + actions.defineField(p, curClass, doc, mod, t, id, + anames, exp, parseStatement()); + + FPstate = oldFPstate; + + break; + + case SEMICOLON: + scan(); + actions.defineField(p, curClass, doc, mod, t, id, + anames, exp, null); + break; + + default: + // really expected a statement body here + if ((mod & (M_NATIVE | M_ABSTRACT)) == 0) { + expect(LBRACE); + } else { + expect(SEMICOLON); + } + } + return; + } + + // It is a list of instance variables + while (true) { + p = pos; // get the current position + // parse the array brackets (if any) + // ie: var[][][] + Type vt = parseArrayBrackets(t); + + // Parse the optional initializer + Node init = null; + if (token == ASSIGN) { + scan(); + init = parseExpression(); + } + + // Define the variable + actions.defineField(p, curClass, doc, mod, vt, id, + null, null, init); + + // If the next token is a comma, then there is more + if (token != COMMA) { + expect(SEMICOLON); + return; + } + scan(); + + // The next token must be an identifier + id = scanner.getIdToken(); + expect(IDENT); + } + } + + /** + * Recover after a syntax error in a field. This involves + * discarding tokens until an EOF or a possible legal + * continuation is encountered. + */ + protected void recoverField(ClassDefinition newClass) throws SyntaxError, IOException { + while (true) { + switch (token) { + case EOF: + case STATIC: + case FINAL: + case PUBLIC: + case PRIVATE: + case SYNCHRONIZED: + case TRANSIENT: + + case VOID: + case BOOLEAN: + case BYTE: + case CHAR: + case SHORT: + case INT: + case FLOAT: + case LONG: + case DOUBLE: + // possible begin of a field, continue + return; + + case LBRACE: + match(LBRACE, RBRACE); + scan(); + break; + + case LPAREN: + match(LPAREN, RPAREN); + scan(); + break; + + case LSQBRACKET: + match(LSQBRACKET, RSQBRACKET); + scan(); + break; + + case RBRACE: + case INTERFACE: + case CLASS: + case IMPORT: + case PACKAGE: + // begin of something outside a class, panic more + actions.endClass(pos, newClass); + throw new SyntaxError(); + + default: + // don't know what to do, skip + scan(); + break; + } + } + } + + /** + * Parse a top-level class or interface declaration. + */ + protected void parseClass() throws SyntaxError, IOException { + String doc = scanner.docComment; + + // Parse the modifiers. + int mod = parseModifiers(MM_CLASS | MM_MEMBER); + + parseNamedClass(mod, PACKAGE, doc); + } + + // Current strict/default state of floating point. This is + // set and reset with a stack discipline around methods and named + // classes. Only M_STRICTFP may be set in this word. try... + // finally is not needed to protect setting and resetting because + // there are no error messages based on FPstate. + private int FPstate = 0; + + /** + * Parse a block-local class or interface declaration. + */ + protected Statement parseLocalClass(int mod) throws SyntaxError, IOException { + long p = pos; + ClassDefinition body = parseNamedClass(M_LOCAL | mod, STAT, null); + Statement ds[] = { + new VarDeclarationStatement(p, new LocalMember(body), null) + }; + Expression type = new TypeExpression(p, body.getType()); + return new DeclarationStatement(p, 0, type, ds); + } + + /** + * Parse a named class or interface declaration, + * starting at "class" or "interface". + * @arg ctx Syntactic context of the class, one of {PACKAGE CLASS STAT EXPR}. + */ + protected ClassDefinition parseNamedClass(int mod, int ctx, String doc) throws SyntaxError, IOException { + // Parse class/interface + switch (token) { + case INTERFACE: + scan(); + mod |= M_INTERFACE; + break; + + case CLASS: + scan(); + break; + + default: + env.error(pos, "class.expected"); + break; + } + + int oldFPstate = FPstate; + if ((mod & M_STRICTFP)!=0) { + FPstate = M_STRICTFP; + } else { + // The & (...) isn't really necessary here because we do maintain + // the invariant that FPstate has no extra bits set. + mod |= FPstate & M_STRICTFP; + } + + // Parse the class name + IdentifierToken nm = scanner.getIdToken(); + long p = pos; + expect(IDENT); + + Vector ext = new Vector<>(); + Vector impl = new Vector<>(); + parseInheritance(ext, impl); + + ClassDefinition tmp = parseClassBody(nm, mod, ctx, doc, ext, impl, p); + + FPstate = oldFPstate; + + return tmp; + } + + protected void parseInheritance(Vector ext, Vector impl) throws SyntaxError, IOException { + // Parse extends clause + if (token == EXTENDS) { + scan(); + ext.addElement(parseName(false)); + while (token == COMMA) { + scan(); + ext.addElement(parseName(false)); + } + } + + // Parse implements clause + if (token == IMPLEMENTS) { + scan(); + impl.addElement(parseName(false)); + while (token == COMMA) { + scan(); + impl.addElement(parseName(false)); + } + } + } + + /** + * Parse the body of a class or interface declaration, + * starting at the left brace. + */ + protected ClassDefinition parseClassBody(IdentifierToken nm, int mod, + int ctx, String doc, + Vector ext, Vector impl, long p + ) throws SyntaxError, IOException { + // Decide which is the super class + IdentifierToken sup = null; + if ((mod & M_INTERFACE) != 0) { + if (impl.size() > 0) { + env.error(impl.elementAt(0).getWhere(), + "intf.impl.intf"); + } + impl = ext; + } else { + if (ext.size() > 0) { + if (ext.size() > 1) { + env.error(ext.elementAt(1).getWhere(), + "multiple.inherit"); + } + sup = ext.elementAt(0); + } + } + + ClassDefinition oldClass = curClass; + + // Begin a new class + IdentifierToken implids[] = new IdentifierToken[impl.size()]; + impl.copyInto(implids); + ClassDefinition newClass = + actions.beginClass(p, doc, mod, nm, sup, implids); + + // Parse fields + expect(LBRACE); + while ((token != EOF) && (token != RBRACE)) { + try { + curClass = newClass; + parseField(); + } catch (SyntaxError e) { + recoverField(newClass); + } finally { + curClass = oldClass; + } + } + expect(RBRACE); + + // End the class + actions.endClass(scanner.prevPos, newClass); + return newClass; + } + + /** + * Recover after a syntax error in the file. + * This involves discarding tokens until an EOF + * or a possible legal continuation is encountered. + */ + protected void recoverFile() throws IOException { + while (true) { + switch (token) { + case CLASS: + case INTERFACE: + // Start of a new source file statement, continue + return; + + case LBRACE: + match(LBRACE, RBRACE); + scan(); + break; + + case LPAREN: + match(LPAREN, RPAREN); + scan(); + break; + + case LSQBRACKET: + match(LSQBRACKET, RSQBRACKET); + scan(); + break; + + case EOF: + return; + + default: + // Don't know what to do, skip + scan(); + break; + } + } + } + + /** + * Parse an Java file. + */ + public void parseFile() { + try { + try { + if (token == PACKAGE) { + // Package statement + long p = scan(); + IdentifierToken id = parseName(false); + expect(SEMICOLON); + actions.packageDeclaration(p, id); + } + } catch (SyntaxError e) { + recoverFile(); + } + while (token == IMPORT) { + try{ + // Import statement + long p = scan(); + IdentifierToken id = parseName(true); + expect(SEMICOLON); + if (id.id.getName().equals(idStar)) { + id.id = id.id.getQualifier(); + actions.importPackage(p, id); + } else { + actions.importClass(p, id); + } + } catch (SyntaxError e) { + recoverFile(); + } + } + + while (token != EOF) { + try { + switch (token) { + case FINAL: + case PUBLIC: + case PRIVATE: + case ABSTRACT: + case CLASS: + case INTERFACE: + case STRICTFP: + // Start of a class + parseClass(); + break; + + case SEMICOLON: + // Bogus semicolon. + // According to the JLS (7.6,19.6), a TypeDeclaration + // may consist of a single semicolon, however, this + // usage is discouraged (JLS 7.6). In contrast, + // a FieldDeclaration may not be empty, and is flagged + // as an error. See parseField above. + scan(); + break; + + case EOF: + // The end + return; + + default: + // Oops + env.error(pos, "toplevel.expected"); + throw new SyntaxError(); + } + } catch (SyntaxError e) { + recoverFile(); + } + } + } catch (IOException e) { + env.error(pos, "io.exception", env.getSource()); + return; + } + } + + /** + * Usually this.scanner == (Scanner)this. + * However, a delegate scanner can produce tokens for this parser, + * in which case (Scanner)this is unused, + * except for this.token and this.pos + * instance variables which are filled from the real scanner + * by this.scan() and the constructor. + */ + protected Scanner scanner; + + // Design Note: We ought to disinherit Parser from Scanner. + // We also should split out the interface ParserActions from + // Parser, and make BatchParser implement ParserActions, + // not extend Parser. This would split scanning, parsing, + // and class building into distinct responsibility areas. + // (Perhaps tree building could be virtualized too.) + + public long scan() throws IOException { + if (scanner != this && scanner != null) { + long result = scanner.scan(); + ((Scanner)this).token = scanner.token; + ((Scanner)this).pos = scanner.pos; + return result; + } + return super.scan(); + } + + public void match(int open, int close) throws IOException { + if (scanner != this) { + scanner.match(open, close); + ((Scanner)this).token = scanner.token; + ((Scanner)this).pos = scanner.pos; + return; + } + super.match(open, close); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ParserActions.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ParserActions.java new file mode 100644 index 000000000..3788a7e60 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ParserActions.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import org.glassfish.rmic.tools.tree.*; + +/** + * This is the protocol by which a Parser makes callbacks + * to the later phases of the compiler. + *

                + * (As a backwards compatibility trick, Parser implements + * this protocol, so that an instance of a Parser subclass + * can handle its own actions. The preferred way to use a + * Parser, however, is to instantiate it directly with a + * reference to your own ParserActions implementation.) + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author John R. Rose + */ +public interface ParserActions { + /** + * package declaration + */ + void packageDeclaration(long off, IdentifierToken nm); + + /** + * import class + */ + void importClass(long off, IdentifierToken nm); + + /** + * import package + */ + void importPackage(long off, IdentifierToken nm); + + /** + * Define class + * @return a cookie for the class + * This cookie is used by the parser when calling defineField + * and endClass, and is not examined otherwise. + */ + ClassDefinition beginClass(long off, String doc, + int mod, IdentifierToken nm, + IdentifierToken sup, IdentifierToken impl[]); + + + /** + * End class + * @param c a cookie returned by the corresponding beginClass call + */ + void endClass(long off, ClassDefinition c); + + /** + * Define a field + * @param c a cookie returned by the corresponding beginClass call + */ + void defineField(long where, ClassDefinition c, + String doc, int mod, Type t, + IdentifierToken nm, IdentifierToken args[], + IdentifierToken exp[], Node val); +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/PathClassFile.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/PathClassFile.java new file mode 100644 index 000000000..6191a2011 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/PathClassFile.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; + +/** + * This class is used to represent a file loaded from the class path, and + * is represented by nio Path. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +final +class PathClassFile extends ClassFile { + private final Path path; + private final BasicFileAttributes attrs; + + /** + * Constructor for instance representing a Path + */ + public PathClassFile(Path path) { + this.path = path; + try { + this.attrs = Files.readAttributes(path, BasicFileAttributes.class); + } catch (IOException ioExp) { + throw new RmicUncheckedIOException(ioExp); + } + } + + @Override + public boolean isZipped() { + return false; + } + + @Override + public InputStream getInputStream() throws IOException { + return Files.newInputStream(path); + } + + @Override + public boolean exists() { + return true; + } + + @Override + public boolean isDirectory() { + return attrs.isDirectory(); + } + + @Override + public long lastModified() { + return attrs.lastModifiedTime().toMillis(); + } + + @Override + public String getPath() { + return path.toUri().toString(); + } + + @Override + public String getName() { + return path.getFileName().toString(); + } + +//JCOV + @Override + public String getAbsoluteName() { + return path.toAbsolutePath().toUri().toString(); + } +// end JCOV + + @Override + public long length() { + return attrs.size(); + } + + @Override + public String toString() { + return path.toString(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/RmicUncheckedIOException.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/RmicUncheckedIOException.java new file mode 100644 index 000000000..925e6bce7 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/RmicUncheckedIOException.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.IOException; +import java.io.InvalidObjectException; +import java.io.ObjectInputStream; +import java.util.Objects; + +/** + * Wraps an {@link IOException} with an unchecked exception. Copied from the JDK's UncheckedIOException, as it was only + * added in JDK 8. Once the orb switches to JDK8 as a minimum, this can be replaced with the JDK class. + */ +public class RmicUncheckedIOException extends RuntimeException { + private static final long serialVersionUID = -8134305061645241065L; + + /** + * Constructs an instance of this class. + * + * @param message + * the detail message, can be null + * @param cause + * the {@code IOException} + * + * @throws NullPointerException + * if the cause is {@code null} + */ + public RmicUncheckedIOException(String message, IOException cause) { + super(message, Objects.requireNonNull(cause)); + } + + /** + * Constructs an instance of this class. + * + * @param cause + * the {@code IOException} + * + * @throws NullPointerException + * if the cause is {@code null} + */ + public RmicUncheckedIOException(IOException cause) { + super(Objects.requireNonNull(cause)); + } + + /** + * Returns the cause of this exception. + * + * @return the {@code IOException} which is the cause of this exception. + */ + @Override + public IOException getCause() { + return (IOException) super.getCause(); + } + + /** + * Called to read the object from a stream. + * + * @throws InvalidObjectException + * if the object is invalid or has a cause that is not + * an {@code IOException} + */ + private void readObject(ObjectInputStream s) + throws IOException, ClassNotFoundException + { + s.defaultReadObject(); + Throwable cause = super.getCause(); + if (!(cause instanceof IOException)) + throw new InvalidObjectException("Cause must be an IOException"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/RuntimeConstants.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/RuntimeConstants.java new file mode 100644 index 000000000..249fcecbb --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/RuntimeConstants.java @@ -0,0 +1,727 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public interface RuntimeConstants { + + /* Signature Characters */ + char SIGC_VOID = 'V'; + String SIG_VOID = "V"; + char SIGC_BOOLEAN = 'Z'; + String SIG_BOOLEAN = "Z"; + char SIGC_BYTE = 'B'; + String SIG_BYTE = "B"; + char SIGC_CHAR = 'C'; + String SIG_CHAR = "C"; + char SIGC_SHORT = 'S'; + String SIG_SHORT = "S"; + char SIGC_INT = 'I'; + String SIG_INT = "I"; + char SIGC_LONG = 'J'; + String SIG_LONG = "J"; + char SIGC_FLOAT = 'F'; + String SIG_FLOAT = "F"; + char SIGC_DOUBLE = 'D'; + String SIG_DOUBLE = "D"; + char SIGC_ARRAY = '['; + String SIG_ARRAY = "["; + char SIGC_CLASS = 'L'; + String SIG_CLASS = "L"; + char SIGC_METHOD = '('; + String SIG_METHOD = "("; + char SIGC_ENDCLASS = ';'; + String SIG_ENDCLASS = ";"; + char SIGC_ENDMETHOD = ')'; + String SIG_ENDMETHOD = ")"; + char SIGC_PACKAGE = '/'; + String SIG_PACKAGE = "/"; + + /* Class File Constants */ + int JAVA_MAGIC = 0xcafebabe; + int JAVA_MIN_SUPPORTED_VERSION = 45; + int JAVA_MAX_SUPPORTED_VERSION = 53; + int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0; + + /* Generate class file version for 1.1 by default */ + int JAVA_DEFAULT_VERSION = 45; + int JAVA_DEFAULT_MINOR_VERSION = 3; + + /* Constant table */ + int CONSTANT_UTF8 = 1; + int CONSTANT_UNICODE = 2; + int CONSTANT_INTEGER = 3; + int CONSTANT_FLOAT = 4; + int CONSTANT_LONG = 5; + int CONSTANT_DOUBLE = 6; + int CONSTANT_CLASS = 7; + int CONSTANT_STRING = 8; + int CONSTANT_FIELD = 9; + int CONSTANT_METHOD = 10; + int CONSTANT_INTERFACEMETHOD = 11; + int CONSTANT_NAMEANDTYPE = 12; + int CONSTANT_METHODHANDLE = 15; + int CONSTANT_METHODTYPE = 16; + int CONSTANT_INVOKEDYNAMIC = 18; + + /* Access and modifier flags */ + int ACC_PUBLIC = 0x00000001; + int ACC_PRIVATE = 0x00000002; + int ACC_PROTECTED = 0x00000004; + int ACC_STATIC = 0x00000008; + int ACC_FINAL = 0x00000010; + int ACC_SYNCHRONIZED = 0x00000020; + int ACC_VOLATILE = 0x00000040; + int ACC_TRANSIENT = 0x00000080; + int ACC_NATIVE = 0x00000100; + int ACC_INTERFACE = 0x00000200; + int ACC_ABSTRACT = 0x00000400; + int ACC_SUPER = 0x00000020; + int ACC_STRICT = 0x00000800; + + /* Type codes */ + int T_CLASS = 0x00000002; + int T_BOOLEAN = 0x00000004; + int T_CHAR = 0x00000005; + int T_FLOAT = 0x00000006; + int T_DOUBLE = 0x00000007; + int T_BYTE = 0x00000008; + int T_SHORT = 0x00000009; + int T_INT = 0x0000000a; + int T_LONG = 0x0000000b; + + /* Opcodes */ + int opc_try = -3; + int opc_dead = -2; + int opc_label = -1; + int opc_nop = 0; + int opc_aconst_null = 1; + int opc_iconst_m1 = 2; + int opc_iconst_0 = 3; + int opc_iconst_1 = 4; + int opc_iconst_2 = 5; + int opc_iconst_3 = 6; + int opc_iconst_4 = 7; + int opc_iconst_5 = 8; + int opc_lconst_0 = 9; + int opc_lconst_1 = 10; + int opc_fconst_0 = 11; + int opc_fconst_1 = 12; + int opc_fconst_2 = 13; + int opc_dconst_0 = 14; + int opc_dconst_1 = 15; + int opc_bipush = 16; + int opc_sipush = 17; + int opc_ldc = 18; + int opc_ldc_w = 19; + int opc_ldc2_w = 20; + int opc_iload = 21; + int opc_lload = 22; + int opc_fload = 23; + int opc_dload = 24; + int opc_aload = 25; + int opc_iload_0 = 26; + int opc_iload_1 = 27; + int opc_iload_2 = 28; + int opc_iload_3 = 29; + int opc_lload_0 = 30; + int opc_lload_1 = 31; + int opc_lload_2 = 32; + int opc_lload_3 = 33; + int opc_fload_0 = 34; + int opc_fload_1 = 35; + int opc_fload_2 = 36; + int opc_fload_3 = 37; + int opc_dload_0 = 38; + int opc_dload_1 = 39; + int opc_dload_2 = 40; + int opc_dload_3 = 41; + int opc_aload_0 = 42; + int opc_aload_1 = 43; + int opc_aload_2 = 44; + int opc_aload_3 = 45; + int opc_iaload = 46; + int opc_laload = 47; + int opc_faload = 48; + int opc_daload = 49; + int opc_aaload = 50; + int opc_baload = 51; + int opc_caload = 52; + int opc_saload = 53; + int opc_istore = 54; + int opc_lstore = 55; + int opc_fstore = 56; + int opc_dstore = 57; + int opc_astore = 58; + int opc_istore_0 = 59; + int opc_istore_1 = 60; + int opc_istore_2 = 61; + int opc_istore_3 = 62; + int opc_lstore_0 = 63; + int opc_lstore_1 = 64; + int opc_lstore_2 = 65; + int opc_lstore_3 = 66; + int opc_fstore_0 = 67; + int opc_fstore_1 = 68; + int opc_fstore_2 = 69; + int opc_fstore_3 = 70; + int opc_dstore_0 = 71; + int opc_dstore_1 = 72; + int opc_dstore_2 = 73; + int opc_dstore_3 = 74; + int opc_astore_0 = 75; + int opc_astore_1 = 76; + int opc_astore_2 = 77; + int opc_astore_3 = 78; + int opc_iastore = 79; + int opc_lastore = 80; + int opc_fastore = 81; + int opc_dastore = 82; + int opc_aastore = 83; + int opc_bastore = 84; + int opc_castore = 85; + int opc_sastore = 86; + int opc_pop = 87; + int opc_pop2 = 88; + int opc_dup = 89; + int opc_dup_x1 = 90; + int opc_dup_x2 = 91; + int opc_dup2 = 92; + int opc_dup2_x1 = 93; + int opc_dup2_x2 = 94; + int opc_swap = 95; + int opc_iadd = 96; + int opc_ladd = 97; + int opc_fadd = 98; + int opc_dadd = 99; + int opc_isub = 100; + int opc_lsub = 101; + int opc_fsub = 102; + int opc_dsub = 103; + int opc_imul = 104; + int opc_lmul = 105; + int opc_fmul = 106; + int opc_dmul = 107; + int opc_idiv = 108; + int opc_ldiv = 109; + int opc_fdiv = 110; + int opc_ddiv = 111; + int opc_irem = 112; + int opc_lrem = 113; + int opc_frem = 114; + int opc_drem = 115; + int opc_ineg = 116; + int opc_lneg = 117; + int opc_fneg = 118; + int opc_dneg = 119; + int opc_ishl = 120; + int opc_lshl = 121; + int opc_ishr = 122; + int opc_lshr = 123; + int opc_iushr = 124; + int opc_lushr = 125; + int opc_iand = 126; + int opc_land = 127; + int opc_ior = 128; + int opc_lor = 129; + int opc_ixor = 130; + int opc_lxor = 131; + int opc_iinc = 132; + int opc_i2l = 133; + int opc_i2f = 134; + int opc_i2d = 135; + int opc_l2i = 136; + int opc_l2f = 137; + int opc_l2d = 138; + int opc_f2i = 139; + int opc_f2l = 140; + int opc_f2d = 141; + int opc_d2i = 142; + int opc_d2l = 143; + int opc_d2f = 144; + int opc_i2b = 145; + int opc_i2c = 146; + int opc_i2s = 147; + int opc_lcmp = 148; + int opc_fcmpl = 149; + int opc_fcmpg = 150; + int opc_dcmpl = 151; + int opc_dcmpg = 152; + int opc_ifeq = 153; + int opc_ifne = 154; + int opc_iflt = 155; + int opc_ifge = 156; + int opc_ifgt = 157; + int opc_ifle = 158; + int opc_if_icmpeq = 159; + int opc_if_icmpne = 160; + int opc_if_icmplt = 161; + int opc_if_icmpge = 162; + int opc_if_icmpgt = 163; + int opc_if_icmple = 164; + int opc_if_acmpeq = 165; + int opc_if_acmpne = 166; + int opc_goto = 167; + int opc_jsr = 168; + int opc_ret = 169; + int opc_tableswitch = 170; + int opc_lookupswitch = 171; + int opc_ireturn = 172; + int opc_lreturn = 173; + int opc_freturn = 174; + int opc_dreturn = 175; + int opc_areturn = 176; + int opc_return = 177; + int opc_getstatic = 178; + int opc_putstatic = 179; + int opc_getfield = 180; + int opc_putfield = 181; + int opc_invokevirtual = 182; + int opc_invokespecial = 183; + int opc_invokestatic = 184; + int opc_invokeinterface = 185; + int opc_invokedynamic = 186; + int opc_new = 187; + int opc_newarray = 188; + int opc_anewarray = 189; + int opc_arraylength = 190; + int opc_athrow = 191; + int opc_checkcast = 192; + int opc_instanceof = 193; + int opc_monitorenter = 194; + int opc_monitorexit = 195; + int opc_wide = 196; + int opc_multianewarray = 197; + int opc_ifnull = 198; + int opc_ifnonnull = 199; + int opc_goto_w = 200; + int opc_jsr_w = 201; + int opc_breakpoint = 202; + + /* Opcode Names */ + String opcNames[] = { + "nop", + "aconst_null", + "iconst_m1", + "iconst_0", + "iconst_1", + "iconst_2", + "iconst_3", + "iconst_4", + "iconst_5", + "lconst_0", + "lconst_1", + "fconst_0", + "fconst_1", + "fconst_2", + "dconst_0", + "dconst_1", + "bipush", + "sipush", + "ldc", + "ldc_w", + "ldc2_w", + "iload", + "lload", + "fload", + "dload", + "aload", + "iload_0", + "iload_1", + "iload_2", + "iload_3", + "lload_0", + "lload_1", + "lload_2", + "lload_3", + "fload_0", + "fload_1", + "fload_2", + "fload_3", + "dload_0", + "dload_1", + "dload_2", + "dload_3", + "aload_0", + "aload_1", + "aload_2", + "aload_3", + "iaload", + "laload", + "faload", + "daload", + "aaload", + "baload", + "caload", + "saload", + "istore", + "lstore", + "fstore", + "dstore", + "astore", + "istore_0", + "istore_1", + "istore_2", + "istore_3", + "lstore_0", + "lstore_1", + "lstore_2", + "lstore_3", + "fstore_0", + "fstore_1", + "fstore_2", + "fstore_3", + "dstore_0", + "dstore_1", + "dstore_2", + "dstore_3", + "astore_0", + "astore_1", + "astore_2", + "astore_3", + "iastore", + "lastore", + "fastore", + "dastore", + "aastore", + "bastore", + "castore", + "sastore", + "pop", + "pop2", + "dup", + "dup_x1", + "dup_x2", + "dup2", + "dup2_x1", + "dup2_x2", + "swap", + "iadd", + "ladd", + "fadd", + "dadd", + "isub", + "lsub", + "fsub", + "dsub", + "imul", + "lmul", + "fmul", + "dmul", + "idiv", + "ldiv", + "fdiv", + "ddiv", + "irem", + "lrem", + "frem", + "drem", + "ineg", + "lneg", + "fneg", + "dneg", + "ishl", + "lshl", + "ishr", + "lshr", + "iushr", + "lushr", + "iand", + "land", + "ior", + "lor", + "ixor", + "lxor", + "iinc", + "i2l", + "i2f", + "i2d", + "l2i", + "l2f", + "l2d", + "f2i", + "f2l", + "f2d", + "d2i", + "d2l", + "d2f", + "i2b", + "i2c", + "i2s", + "lcmp", + "fcmpl", + "fcmpg", + "dcmpl", + "dcmpg", + "ifeq", + "ifne", + "iflt", + "ifge", + "ifgt", + "ifle", + "if_icmpeq", + "if_icmpne", + "if_icmplt", + "if_icmpge", + "if_icmpgt", + "if_icmple", + "if_acmpeq", + "if_acmpne", + "goto", + "jsr", + "ret", + "tableswitch", + "lookupswitch", + "ireturn", + "lreturn", + "freturn", + "dreturn", + "areturn", + "return", + "getstatic", + "putstatic", + "getfield", + "putfield", + "invokevirtual", + "invokespecial", + "invokestatic", + "invokeinterface", + "invokedynamic", + "new", + "newarray", + "anewarray", + "arraylength", + "athrow", + "checkcast", + "instanceof", + "monitorenter", + "monitorexit", + "wide", + "multianewarray", + "ifnull", + "ifnonnull", + "goto_w", + "jsr_w", + "breakpoint" + }; + + /* Opcode Lengths */ + int opcLengths[] = { + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 3, + 2, + 3, + 3, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 3, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 2, + 99, + 99, + 1, + 1, + 1, + 1, + 1, + 1, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 5, + 5, + 3, + 2, + 3, + 1, + 1, + 3, + 3, + 1, + 1, + 0, + 4, + 3, + 3, + 5, + 5, + 1 + }; + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Scanner.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Scanner.java new file mode 100644 index 000000000..2fbe2724d --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Scanner.java @@ -0,0 +1,1331 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.IOException; +import java.io.InputStream; + +/** + * A Scanner for Java tokens. Errors are reported + * to the environment object.

                + * + * The scanner keeps track of the current token, + * the value of the current token (if any), and the start + * position of the current token.

                + * + * The scan() method advances the scanner to the next + * token in the input.

                + * + * The match() method is used to quickly match opening + * brackets (ie: '(', '{', or '[') with their closing + * counter part. This is useful during error recovery.

                + * + * An position consists of: ((linenr << WHEREOFFSETBITS) | offset) + * this means that both the line number and the exact offset into + * the file are encoded in each position value.

                + * + * The compiler treats either "\n", "\r" or "\r\n" as the + * end of a line.

                + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ + +@SuppressWarnings("deprecation") +public +class Scanner implements Constants { + /** + * The increment for each character. + */ + public static final long OFFSETINC = 1; + + /** + * The increment for each line. + */ + public static final long LINEINC = 1L << WHEREOFFSETBITS; + + /** + * End of input + */ + public static final int EOF = -1; + + /** + * Where errors are reported + */ + public Environment env; + + /** + * Input reader + */ + protected ScannerInputReader in; + + /** + * If true, present all comments as tokens. + * Contents are not saved, but positions are recorded accurately, + * so the comment can be recovered from the text. + * Line terminations are also returned as comment tokens, + * and may be distinguished by their start and end positions, + * which are equal (meaning, these tokens contain no chars). + */ + public boolean scanComments = false; + + /** + * Current token + */ + public int token; + + /** + * The position of the current token + */ + public long pos; + + /** + * The position of the previous token + */ + public long prevPos; + + /** + * The current character + */ + protected int ch; + + /* + * Token values. + */ + public char charValue; + public int intValue; + public long longValue; + public float floatValue; + public double doubleValue; + public String stringValue; + public Identifier idValue; + public int radix; // Radix, when reading int or long + + /* + * A doc comment preceding the most recent token + */ + public String docComment; + + /* + * A growable character buffer. + */ + private int count; + private char buffer[] = new char[1024]; + private void growBuffer() { + char newBuffer[] = new char[buffer.length * 2]; + System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); + buffer = newBuffer; + } + + // The following two methods have been hand-inlined in + // scanDocComment. If you make changes here, you should + // check to see if scanDocComment also needs modification. + private void putc(int ch) { + if (count == buffer.length) { + growBuffer(); + } + buffer[count++] = (char)ch; + } + + private String bufferString() { + return new String(buffer, 0, count); + } + + /** + * Create a scanner to scan an input stream. + */ + public Scanner(Environment env, InputStream in) throws IOException { + this.env = env; + useInputStream(in); + } + + /** + * Setup input from the given input stream, + * and scan the first token from it. + */ + protected void useInputStream(InputStream in) throws IOException { + try { + this.in = new ScannerInputReader(env, in); + } catch (Exception e) { + env.setCharacterEncoding(null); + this.in = new ScannerInputReader(env, in); + } + + ch = this.in.read(); + prevPos = this.in.pos; + + scan(); + } + + /** + * Create a scanner to scan an input stream. + */ + protected Scanner(Environment env) { + this.env = env; + // Expect the subclass to call useInputStream at the right time. + } + + /** + * Define a keyword. + */ + private static void defineKeyword(int val) { + Identifier.lookup(opNames[val]).setType(val); + } + + /** + * Initialized keyword and token Hashtables + */ + static { + // Statement keywords + defineKeyword(FOR); + defineKeyword(IF); + defineKeyword(ELSE); + defineKeyword(WHILE); + defineKeyword(DO); + defineKeyword(SWITCH); + defineKeyword(CASE); + defineKeyword(DEFAULT); + defineKeyword(BREAK); + defineKeyword(CONTINUE); + defineKeyword(RETURN); + defineKeyword(TRY); + defineKeyword(CATCH); + defineKeyword(FINALLY); + defineKeyword(THROW); + + // Type defineKeywords + defineKeyword(BYTE); + defineKeyword(CHAR); + defineKeyword(SHORT); + defineKeyword(INT); + defineKeyword(LONG); + defineKeyword(FLOAT); + defineKeyword(DOUBLE); + defineKeyword(VOID); + defineKeyword(BOOLEAN); + + // Expression keywords + defineKeyword(INSTANCEOF); + defineKeyword(TRUE); + defineKeyword(FALSE); + defineKeyword(NEW); + defineKeyword(THIS); + defineKeyword(SUPER); + defineKeyword(NULL); + + // Declaration keywords + defineKeyword(IMPORT); + defineKeyword(CLASS); + defineKeyword(EXTENDS); + defineKeyword(IMPLEMENTS); + defineKeyword(INTERFACE); + defineKeyword(PACKAGE); + defineKeyword(THROWS); + + // Modifier keywords + defineKeyword(PRIVATE); + defineKeyword(PUBLIC); + defineKeyword(PROTECTED); + defineKeyword(STATIC); + defineKeyword(TRANSIENT); + defineKeyword(SYNCHRONIZED); + defineKeyword(NATIVE); + defineKeyword(ABSTRACT); + defineKeyword(VOLATILE); + defineKeyword(FINAL); + defineKeyword(STRICTFP); + + // reserved keywords + defineKeyword(CONST); + defineKeyword(GOTO); + } + + /** + * Scan a comment. This method should be + * called once the initial /, * and the next + * character have been read. + */ + private void skipComment() throws IOException { + while (true) { + switch (ch) { + case EOF: + env.error(pos, "eof.in.comment"); + return; + + case '*': + if ((ch = in.read()) == '/') { + ch = in.read(); + return; + } + break; + + default: + ch = in.read(); + break; + } + } + } + + /** + * Scan a doc comment. This method should be called + * once the initial /, * and * have been read. It gathers + * the content of the comment (witout leading spaces and '*'s) + * in the string buffer. + */ + private String scanDocComment() throws IOException { + // Note: this method has been hand-optimized to yield + // better performance. This was done after it was noted + // that javadoc spent a great deal of its time here. + // This should also help the performance of the compiler + // as well -- it scans the doc comments to find + // @deprecated tags. + // + // The logic of the method has been completely rewritten + // to avoid the use of flags that need to be looked at + // for every character read. Members that are accessed + // more than once have been stored in local variables. + // The methods putc() and bufferString() have been + // inlined by hand. Extra cases have been added to + // switch statements to trick the compiler into generating + // a tableswitch instead of a lookupswitch. + // + // This implementation aims to preserve the previous + // behavior of this method. + + int c; + + // Put `in' in a local variable. + final ScannerInputReader in = this.in; + + // We maintain the buffer locally rather than calling putc(). + char[] buffer = this.buffer; + int count = 0; + + // We are called pointing at the second star of the doc + // comment: + // + // Input: /** the rest of the comment ... */ + // ^ + // + // We rely on this in the code below. + + // Consume any number of stars. + while ((c = in.read()) == '*') + ; + + // Is the comment of the form /**/, /***/, /****/, etc.? + if (c == '/') { + // Set ch and return + ch = in.read(); + return ""; + } + + // Skip a newline on the first line of the comment. + if (c == '\n') { + c = in.read(); + } + + outerLoop: + // The outerLoop processes the doc comment, looping once + // for each line. For each line, it first strips off + // whitespace, then it consumes any stars, then it + // puts the rest of the line into our buffer. + while (true) { + + // The wsLoop consumes whitespace from the beginning + // of each line. + wsLoop: + while (true) { + switch (c) { + case ' ': + case '\t': + // We could check for other forms of whitespace + // as well, but this is left as is for minimum + // disturbance of functionality. + // + // Just skip whitespace. + c = in.read(); + break; + + // We have added extra cases here to trick the + // compiler into using a tableswitch instead of + // a lookupswitch. They can be removed without + // a change in meaning. + case 10: case 11: case 12: case 13: case 14: case 15: + case 16: case 17: case 18: case 19: case 20: case 21: + case 22: case 23: case 24: case 25: case 26: case 27: + case 28: case 29: case 30: case 31: + default: + // We've seen something that isn't whitespace, + // jump out. + break wsLoop; + } + } // end wsLoop. + + // Are there stars here? If so, consume them all + // and check for the end of comment. + if (c == '*') { + // Skip all of the stars... + do { + c = in.read(); + } while (c == '*'); + + // ...then check for the closing slash. + if (c == '/') { + // We're done with the doc comment. + // Set ch and break out. + ch = in.read(); + break outerLoop; + } + } + + // The textLoop processes the rest of the characters + // on the line, adding them to our buffer. + textLoop: + while (true) { + switch (c) { + case EOF: + // We've seen a premature EOF. Break out + // of the loop. + env.error(pos, "eof.in.comment"); + ch = EOF; + break outerLoop; + + case '*': + // Is this just a star? Or is this the + // end of a comment? + c = in.read(); + if (c == '/') { + // This is the end of the comment, + // set ch and return our buffer. + ch = in.read(); + break outerLoop; + } + // This is just an ordinary star. Add it to + // the buffer. + if (count == buffer.length) { + growBuffer(); + buffer = this.buffer; + } + buffer[count++] = '*'; + break; + + case '\n': + // We've seen a newline. Add it to our + // buffer and break out of this loop, + // starting fresh on a new line. + if (count == buffer.length) { + growBuffer(); + buffer = this.buffer; + } + buffer[count++] = '\n'; + c = in.read(); + break textLoop; + + // Again, the extra cases here are a trick + // to get the compiler to generate a tableswitch. + case 0: case 1: case 2: case 3: case 4: case 5: + case 6: case 7: case 8: case 11: case 12: case 13: + case 14: case 15: case 16: case 17: case 18: case 19: + case 20: case 21: case 22: case 23: case 24: case 25: + case 26: case 27: case 28: case 29: case 30: case 31: + case 32: case 33: case 34: case 35: case 36: case 37: + case 38: case 39: case 40: + default: + // Add the character to our buffer. + if (count == buffer.length) { + growBuffer(); + buffer = this.buffer; + } + buffer[count++] = (char)c; + c = in.read(); + break; + } + } // end textLoop + } // end outerLoop + + // We have scanned our doc comment. It is stored in + // buffer. The previous implementation of scanDocComment + // stripped off all trailing spaces and stars from the comment. + // We will do this as well, so as to cause a minimum of + // disturbance. Is this what we want? + if (count > 0) { + int i = count - 1; + trailLoop: + while (i > -1) { + switch (buffer[i]) { + case ' ': + case '\t': + case '*': + i--; + break; + // And again, the extra cases here are a trick + // to get the compiler to generate a tableswitch. + case 0: case 1: case 2: case 3: case 4: case 5: + case 6: case 7: case 8: case 10: case 11: case 12: + case 13: case 14: case 15: case 16: case 17: case 18: + case 19: case 20: case 21: case 22: case 23: case 24: + case 25: case 26: case 27: case 28: case 29: case 30: + case 31: case 33: case 34: case 35: case 36: case 37: + case 38: case 39: case 40: + default: + break trailLoop; + } + } + count = i + 1; + + // Return the text of the doc comment. + return new String(buffer, 0, count); + } else { + return ""; + } + } + + /** + * Scan a number. The first digit of the number should be the current + * character. We may be scanning hex, decimal, or octal at this point + */ + @SuppressWarnings("fallthrough") + private void scanNumber() throws IOException { + boolean seenNonOctal = false; + boolean overflow = false; + boolean seenDigit = false; // used to detect invalid hex number 0xL + radix = (ch == '0' ? 8 : 10); + long value = ch - '0'; + count = 0; + putc(ch); // save character in buffer + numberLoop: + for (;;) { + switch (ch = in.read()) { + case '.': + if (radix == 16) + break numberLoop; // an illegal character + scanReal(); + return; + + case '8': case '9': + // We can't yet throw an error if reading an octal. We might + // discover we're really reading a real. + seenNonOctal = true; + // Fall through + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + seenDigit = true; + putc(ch); + if (radix == 10) { + overflow = overflow || (value * 10)/10 != value; + value = (value * 10) + (ch - '0'); + overflow = overflow || (value - 1 < -1); + } else if (radix == 8) { + overflow = overflow || (value >>> 61) != 0; + value = (value << 3) + (ch - '0'); + } else { + overflow = overflow || (value >>> 60) != 0; + value = (value << 4) + (ch - '0'); + } + break; + + case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': + if (radix != 16) { + scanReal(); + return; + } + // fall through + case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': + seenDigit = true; + putc(ch); + if (radix != 16) + break numberLoop; // an illegal character + overflow = overflow || (value >>> 60) != 0; + value = (value << 4) + 10 + + Character.toLowerCase((char)ch) - 'a'; + break; + + case 'l': case 'L': + ch = in.read(); // skip over 'l' + longValue = value; + token = LONGVAL; + break numberLoop; + + case 'x': case 'X': + // if the first character is a '0' and this is the second + // letter, then read in a hexadecimal number. Otherwise, error. + if (count == 1 && radix == 8) { + radix = 16; + seenDigit = false; + break; + } else { + // we'll get an illegal character error + break numberLoop; + } + + default: + intValue = (int)value; + token = INTVAL; + break numberLoop; + } + } // while true + + // We have just finished reading the number. The next thing better + // not be a letter or digit. + // Note: There will be deprecation warnings against these uses + // of Character.isJavaLetterOrDigit and Character.isJavaLetter. + // Do not fix them yet; allow the compiler to run on pre-JDK1.1 VMs. + if (Character.isJavaLetterOrDigit((char)ch) || ch == '.') { + env.error(in.pos, "invalid.number"); + do { ch = in.read(); } + while (Character.isJavaLetterOrDigit((char)ch) || ch == '.'); + intValue = 0; + token = INTVAL; + } else if (radix == 8 && seenNonOctal) { + // A bogus octal literal. + intValue = 0; + token = INTVAL; + env.error(pos, "invalid.octal.number"); + } else if (radix == 16 && seenDigit == false) { + // A hex literal with no digits, 0xL, for example. + intValue = 0; + token = INTVAL; + env.error(pos, "invalid.hex.number"); + } else { + if (token == INTVAL) { + // Check for overflow. Note that base 10 literals + // have different rules than base 8 and 16. + overflow = overflow || + (value & 0xFFFFFFFF00000000L) != 0 || + (radix == 10 && value > 2147483648L); + + if (overflow) { + intValue = 0; + + // Give a specific error message which tells + // the user the range. + switch (radix) { + case 8: + env.error(pos, "overflow.int.oct"); + break; + case 10: + env.error(pos, "overflow.int.dec"); + break; + case 16: + env.error(pos, "overflow.int.hex"); + break; + default: + throw new CompilerError("invalid radix"); + } + } + } else { + if (overflow) { + longValue = 0; + + // Give a specific error message which tells + // the user the range. + switch (radix) { + case 8: + env.error(pos, "overflow.long.oct"); + break; + case 10: + env.error(pos, "overflow.long.dec"); + break; + case 16: + env.error(pos, "overflow.long.hex"); + break; + default: + throw new CompilerError("invalid radix"); + } + } + } + } + } + + /** + * Scan a float. We are either looking at the decimal, or we have already + * seen it and put it into the buffer. We haven't seen an exponent. + * Scan a float. Should be called with the current character is either + * the 'e', 'E' or '.' + */ + @SuppressWarnings("fallthrough") + private void scanReal() throws IOException { + boolean seenExponent = false; + boolean isSingleFloat = false; + char lastChar; + if (ch == '.') { + putc(ch); + ch = in.read(); + } + + numberLoop: + for ( ; ; ch = in.read()) { + switch (ch) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + putc(ch); + break; + + case 'e': case 'E': + if (seenExponent) + break numberLoop; // we'll get a format error + putc(ch); + seenExponent = true; + break; + + case '+': case '-': + lastChar = buffer[count - 1]; + if (lastChar != 'e' && lastChar != 'E') + break numberLoop; // this isn't an error, though! + putc(ch); + break; + + case 'f': case 'F': + ch = in.read(); // skip over 'f' + isSingleFloat = true; + break numberLoop; + + case 'd': case 'D': + ch = in.read(); // skip over 'd' + // fall through + default: + break numberLoop; + } // sswitch + } // loop + + // we have just finished reading the number. The next thing better + // not be a letter or digit. + if (Character.isJavaLetterOrDigit((char)ch) || ch == '.') { + env.error(in.pos, "invalid.number"); + do { ch = in.read(); } + while (Character.isJavaLetterOrDigit((char)ch) || ch == '.'); + doubleValue = 0; + token = DOUBLEVAL; + } else { + token = isSingleFloat ? FLOATVAL : DOUBLEVAL; + try { + lastChar = buffer[count - 1]; + if (lastChar == 'e' || lastChar == 'E' + || lastChar == '+' || lastChar == '-') { + env.error(in.pos -1, "float.format"); + } else if (isSingleFloat) { + String string = bufferString(); + floatValue = Float.valueOf(string).floatValue(); + if (Float.isInfinite(floatValue)) { + env.error(pos, "overflow.float"); + } else if (floatValue == 0 && !looksLikeZero(string)) { + env.error(pos, "underflow.float"); + } + } else { + String string = bufferString(); + doubleValue = Double.valueOf(string).doubleValue(); + if (Double.isInfinite(doubleValue)) { + env.error(pos, "overflow.double"); + } else if (doubleValue == 0 && !looksLikeZero(string)) { + env.error(pos, "underflow.double"); + } + } + } catch (NumberFormatException ee) { + env.error(pos, "float.format"); + doubleValue = 0; + floatValue = 0; + } + } + return; + } + + // We have a token that parses as a number. Is this token possibly zero? + // i.e. does it have a non-zero value in the mantissa? + private static boolean looksLikeZero(String token) { + int length = token.length(); + for (int i = 0; i < length; i++) { + switch (token.charAt(i)) { + case 0: case '.': + continue; + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': + return false; + case 'e': case 'E': case 'f': case 'F': + return true; + } + } + return true; + } + + /** + * Scan an escape character. + * @return the character or -1 if it escaped an + * end-of-line. + */ + private int scanEscapeChar() throws IOException { + long p = in.pos; + + switch (ch = in.read()) { + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': { + int n = ch - '0'; + for (int i = 2 ; i > 0 ; i--) { + switch (ch = in.read()) { + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + n = (n << 3) + ch - '0'; + break; + + default: + if (n > 0xFF) { + env.error(p, "invalid.escape.char"); + } + return n; + } + } + ch = in.read(); + if (n > 0xFF) { + env.error(p, "invalid.escape.char"); + } + return n; + } + + case 'r': ch = in.read(); return '\r'; + case 'n': ch = in.read(); return '\n'; + case 'f': ch = in.read(); return '\f'; + case 'b': ch = in.read(); return '\b'; + case 't': ch = in.read(); return '\t'; + case '\\': ch = in.read(); return '\\'; + case '\"': ch = in.read(); return '\"'; + case '\'': ch = in.read(); return '\''; + } + + env.error(p, "invalid.escape.char"); + ch = in.read(); + return -1; + } + + /** + * Scan a string. The current character + * should be the opening " of the string. + */ + private void scanString() throws IOException { + token = STRINGVAL; + count = 0; + ch = in.read(); + + // Scan a String + while (true) { + switch (ch) { + case EOF: + env.error(pos, "eof.in.string"); + stringValue = bufferString(); + return; + + case '\r': + case '\n': + ch = in.read(); + env.error(pos, "newline.in.string"); + stringValue = bufferString(); + return; + + case '"': + ch = in.read(); + stringValue = bufferString(); + return; + + case '\\': { + int c = scanEscapeChar(); + if (c >= 0) { + putc((char)c); + } + break; + } + + default: + putc(ch); + ch = in.read(); + break; + } + } + } + + /** + * Scan a character. The current character should be + * the opening ' of the character constant. + */ + private void scanCharacter() throws IOException { + token = CHARVAL; + + switch (ch = in.read()) { + case '\\': + int c = scanEscapeChar(); + charValue = (char)((c >= 0) ? c : 0); + break; + + case '\'': + // There are two standard problems this case deals with. One + // is the malformed single quote constant (i.e. the programmer + // uses ''' instead of '\'') and the other is the empty + // character constant (i.e. ''). Just consume any number of + // single quotes and emit an error message. + charValue = 0; + env.error(pos, "invalid.char.constant"); + ch = in.read(); + while (ch == '\'') { + ch = in.read(); + } + return; + + case '\r': + case '\n': + charValue = 0; + env.error(pos, "invalid.char.constant"); + return; + + default: + charValue = (char)ch; + ch = in.read(); + break; + } + + if (ch == '\'') { + ch = in.read(); + } else { + env.error(pos, "invalid.char.constant"); + while (true) { + switch (ch) { + case '\'': + ch = in.read(); + return; + case ';': + case '\n': + case EOF: + return; + default: + ch = in.read(); + } + } + } + } + + /** + * Scan an Identifier. The current character should + * be the first character of the identifier. + */ + private void scanIdentifier() throws IOException { + count = 0; + + while (true) { + putc(ch); + switch (ch = in.read()) { + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': + case 'z': + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': + case 'Z': + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case '$': case '_': + break; + + default: + if (!Character.isJavaLetterOrDigit((char)ch)) { + idValue = Identifier.lookup(bufferString()); + token = idValue.getType(); + return; + } + } + } + } + + /** + * The ending position of the current token + */ + // Note: This should be part of the pos itself. + public long getEndPos() { + return in.pos; + } + + /** + * If the current token is IDENT, return the identifier occurrence. + * It will be freshly allocated. + */ + public IdentifierToken getIdToken() { + return (token != IDENT) ? null : new IdentifierToken(pos, idValue); + } + + /** + * Scan the next token. + * @return the position of the previous token. + */ + public long scan() throws IOException { + return xscan(); + } + + @SuppressWarnings("fallthrough") + protected long xscan() throws IOException { + final ScannerInputReader in = this.in; + long retPos = pos; + prevPos = in.pos; + docComment = null; + while (true) { + pos = in.pos; + + switch (ch) { + case EOF: + token = EOF; + return retPos; + + case '\n': + if (scanComments) { + ch = ' '; + // Avoid this path the next time around. + // Do not just call in.read; we want to present + // a null token (and also avoid read-ahead). + token = COMMENT; + return retPos; + } + // Fall through + case ' ': + case '\t': + case '\f': + ch = in.read(); + break; + + case '/': + switch (ch = in.read()) { + case '/': + // Parse a // comment + while (((ch = in.read()) != EOF) && (ch != '\n')); + if (scanComments) { + token = COMMENT; + return retPos; + } + break; + + case '*': + ch = in.read(); + if (ch == '*') { + docComment = scanDocComment(); + } else { + skipComment(); + } + if (scanComments) { + return retPos; + } + break; + + case '=': + ch = in.read(); + token = ASGDIV; + return retPos; + + default: + token = DIV; + return retPos; + } + break; + + case '"': + scanString(); + return retPos; + + case '\'': + scanCharacter(); + return retPos; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + scanNumber(); + return retPos; + + case '.': + switch (ch = in.read()) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + count = 0; + putc('.'); + scanReal(); + break; + default: + token = FIELD; + } + return retPos; + + case '{': + ch = in.read(); + token = LBRACE; + return retPos; + + case '}': + ch = in.read(); + token = RBRACE; + return retPos; + + case '(': + ch = in.read(); + token = LPAREN; + return retPos; + + case ')': + ch = in.read(); + token = RPAREN; + return retPos; + + case '[': + ch = in.read(); + token = LSQBRACKET; + return retPos; + + case ']': + ch = in.read(); + token = RSQBRACKET; + return retPos; + + case ',': + ch = in.read(); + token = COMMA; + return retPos; + + case ';': + ch = in.read(); + token = SEMICOLON; + return retPos; + + case '?': + ch = in.read(); + token = QUESTIONMARK; + return retPos; + + case '~': + ch = in.read(); + token = BITNOT; + return retPos; + + case ':': + ch = in.read(); + token = COLON; + return retPos; + + case '-': + switch (ch = in.read()) { + case '-': + ch = in.read(); + token = DEC; + return retPos; + + case '=': + ch = in.read(); + token = ASGSUB; + return retPos; + } + token = SUB; + return retPos; + + case '+': + switch (ch = in.read()) { + case '+': + ch = in.read(); + token = INC; + return retPos; + + case '=': + ch = in.read(); + token = ASGADD; + return retPos; + } + token = ADD; + return retPos; + + case '<': + switch (ch = in.read()) { + case '<': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = ASGLSHIFT; + return retPos; + } + token = LSHIFT; + return retPos; + + case '=': + ch = in.read(); + token = LE; + return retPos; + } + token = LT; + return retPos; + + case '>': + switch (ch = in.read()) { + case '>': + switch (ch = in.read()) { + case '=': + ch = in.read(); + token = ASGRSHIFT; + return retPos; + + case '>': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = ASGURSHIFT; + return retPos; + } + token = URSHIFT; + return retPos; + } + token = RSHIFT; + return retPos; + + case '=': + ch = in.read(); + token = GE; + return retPos; + } + token = GT; + return retPos; + + case '|': + switch (ch = in.read()) { + case '|': + ch = in.read(); + token = OR; + return retPos; + + case '=': + ch = in.read(); + token = ASGBITOR; + return retPos; + } + token = BITOR; + return retPos; + + case '&': + switch (ch = in.read()) { + case '&': + ch = in.read(); + token = AND; + return retPos; + + case '=': + ch = in.read(); + token = ASGBITAND; + return retPos; + } + token = BITAND; + return retPos; + + case '=': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = EQ; + return retPos; + } + token = ASSIGN; + return retPos; + + case '%': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = ASGREM; + return retPos; + } + token = REM; + return retPos; + + case '^': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = ASGBITXOR; + return retPos; + } + token = BITXOR; + return retPos; + + case '!': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = NE; + return retPos; + } + token = NOT; + return retPos; + + case '*': + if ((ch = in.read()) == '=') { + ch = in.read(); + token = ASGMUL; + return retPos; + } + token = MUL; + return retPos; + + case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': + case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': + case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': + case 's': case 't': case 'u': case 'v': case 'w': case 'x': + case 'y': case 'z': + case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': + case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': + case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': + case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': + case 'Y': case 'Z': + case '$': case '_': + scanIdentifier(); + return retPos; + + case '\u001a': + // Our one concession to DOS. + if ((ch = in.read()) == EOF) { + token = EOF; + return retPos; + } + env.error(pos, "funny.char"); + ch = in.read(); + break; + + + default: + if (Character.isJavaLetter((char)ch)) { + scanIdentifier(); + return retPos; + } + env.error(pos, "funny.char"); + ch = in.read(); + break; + } + } + } + + /** + * Scan to a matching '}', ']' or ')'. The current token must be + * a '{', '[' or '('; + */ + public void match(int open, int close) throws IOException { + int depth = 1; + + while (true) { + scan(); + if (token == open) { + depth++; + } else if (token == close) { + if (--depth == 0) { + return; + } + } else if (token == EOF) { + env.error(pos, "unbalanced.paren"); + return; + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ScannerInputReader.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ScannerInputReader.java new file mode 100644 index 000000000..fa4c2b5ad --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ScannerInputReader.java @@ -0,0 +1,226 @@ +/* + * Copyright (c) 1995, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.FilterReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; + +/** + * An input stream for java programs. The stream treats either "\n", "\r" + * or "\r\n" as the end of a line, it always returns \n. It also parses + * UNICODE characters expressed as \uffff. However, if it sees "\\", the + * second slash cannot begin a unicode sequence. It keeps track of the current + * position in the input stream. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @author Arthur van Hoff + */ + +public +class ScannerInputReader extends FilterReader implements Constants { + // A note. This class does not really properly subclass FilterReader. + // Since this class only overrides the single character read method, + // and not the multi-character read method, any use of the latter + // will not work properly. Any attempt to use this code outside of + // the compiler should take that into account. + // + // For efficiency, it might be worth moving this code to Scanner and + // getting rid of this class. + + Environment env; + long pos; + + private long chpos; + private int pushBack = -1; + + public ScannerInputReader(Environment env, InputStream in) + throws UnsupportedEncodingException + { + // ScannerInputStream has been modified to no longer use + // BufferedReader. It now does its own buffering for + // performance. + super(env.getCharacterEncoding() != null ? + new InputStreamReader(in, env.getCharacterEncoding()) : + new InputStreamReader(in)); + + // Start out the buffer empty. + currentIndex = 0; + numChars = 0; + + this.env = env; + chpos = Scanner.LINEINC; + } + + //------------------------------------------------------------ + // Buffering code. + + // The size of our buffer. + private static final int BUFFERLEN = 10 * 1024; + + // A character buffer. + private final char[] buffer = new char[BUFFERLEN]; + + // The index of the next character to be "read" from the buffer. + private int currentIndex; + + // The number of characters in the buffer. -1 if EOF is reached. + private int numChars; + + /** + * Get the next character from our buffer. + * Note: this method has been inlined by hand in the `read' method + * below. Any changes made to this method should be equally applied + * to that code. + */ + private int getNextChar() throws IOException { + // Check to see if we have either run out of characters in our + // buffer or gotten to EOF on a previous call. + if (currentIndex >= numChars) { + numChars = in.read(buffer); + if (numChars == -1) { + // We have reached EOF. + return -1; + } + + // No EOF. currentIndex points to first char in buffer. + currentIndex = 0; + } + + return buffer[currentIndex++]; + } + + //------------------------------------------------------------ + + public int read(char[] buffer, int off, int len) { + throw new CompilerError( + "ScannerInputReader is not a fully implemented reader."); + } + + public int read() throws IOException { + pos = chpos; + chpos += Scanner.OFFSETINC; + + int c = pushBack; + if (c == -1) { + getchar: try { + // Here the call... + // c = getNextChar(); + // has been inlined by hand for performance. + + if (currentIndex >= numChars) { + numChars = in.read(buffer); + if (numChars == -1) { + // We have reached EOF. + c = -1; + break getchar; + } + + // No EOF. currentIndex points to first char in buffer. + currentIndex = 0; + } + c = buffer[currentIndex++]; + + } catch (java.io.CharConversionException e) { + env.error(pos, "invalid.encoding.char"); + // this is fatal error + return -1; + } + } else { + pushBack = -1; + } + + // parse special characters + switch (c) { + case -2: + // -2 is a special code indicating a pushback of a backslash that + // definitely isn't the start of a unicode sequence. + return '\\'; + + case '\\': + if ((c = getNextChar()) != 'u') { + pushBack = (c == '\\' ? -2 : c); + return '\\'; + } + // we have a unicode sequence + chpos += Scanner.OFFSETINC; + while ((c = getNextChar()) == 'u') { + chpos += Scanner.OFFSETINC; + } + + // unicode escape sequence + int d = 0; + for (int i = 0 ; i < 4 ; i++, chpos += Scanner.OFFSETINC, c = getNextChar()) { + switch (c) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + d = (d << 4) + c - '0'; + break; + + case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': + d = (d << 4) + 10 + c - 'a'; + break; + + case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': + d = (d << 4) + 10 + c - 'A'; + break; + + default: + env.error(pos, "invalid.escape.char"); + pushBack = c; + return d; + } + } + pushBack = c; + + // To read the following line, switch \ and /... + // Handle /u000a, /u000A, /u000d, /u000D properly as + // line terminators as per JLS 3.4, even though they are encoded + // (this properly respects the order given in JLS 3.2). + switch (d) { + case '\n': + chpos += Scanner.LINEINC; + return '\n'; + case '\r': + if ((c = getNextChar()) != '\n') { + pushBack = c; + } else { + chpos += Scanner.OFFSETINC; + } + chpos += Scanner.LINEINC; + return '\n'; + default: + return d; + } + + case '\n': + chpos += Scanner.LINEINC; + return '\n'; + + case '\r': + if ((c = getNextChar()) != '\n') { + pushBack = c; + } else { + chpos += Scanner.OFFSETINC; + } + chpos += Scanner.LINEINC; + return '\n'; + + default: + return c; + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/SyntaxError.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/SyntaxError.java new file mode 100644 index 000000000..729abdd8f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/SyntaxError.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +/** + * Syntax errors, should always be caught inside the + * parser for error recovery. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@SuppressWarnings("serial") // JDK implementation class +public +class SyntaxError extends Exception { +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/Type.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/Type.java new file mode 100644 index 000000000..cd5a2fb4c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/Type.java @@ -0,0 +1,444 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import org.glassfish.rmic.TypeCode; + +import java.util.Hashtable; + +/** + * This class represents an Java Type.

                + * + * It encapsulates an Java type signature and it provides + * quick access to the components of the type. Note that + * all types are hashed into a hashtable (typeHash), that + * means that each distinct type is only allocated once, + * saving space and making equality checks cheap.

                + * + * For simple types use the constants defined in this class. + * (Type.tInt, Type.tShort, ...). To create complex types use + * the static methods Type.tArray, Type.tMethod or Type.tClass. + * + * For classes, arrays and method types a sub class of class + * type is created which defines the extra type components. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @see ArrayType + * @see ClassType + * @see MethodType + * @author Arthur van Hoff + */ +public +class Type implements Constants { + /** + * This hashtable is used to cache types + */ + private static final Hashtable typeHash = new Hashtable<>(231); + + /** + * The TypeCode of this type. + */ + private TypeCode typeCode; + + /** + * The TypeSignature of this type. This type signature is + * equivalent to the runtime type signatures used by the + * interpreter. + */ + protected String typeSig; + + /* + * Predefined types. + */ + public static final Type noArgs[] = new Type[0]; + public static final Type tError = new Type(TypeCode.ERROR, "?"); + public static final Type tPackage = new Type(TypeCode.ERROR, "."); + public static final Type tNull = new Type(TypeCode.NULL, "*"); + public static final Type tVoid = new Type(TypeCode.VOID, SIG_VOID); + public static final Type tBoolean = new Type(TypeCode.BOOLEAN, SIG_BOOLEAN); + public static final Type tByte = new Type(TypeCode.BYTE, SIG_BYTE); + public static final Type tChar = new Type(TypeCode.CHAR, SIG_CHAR); + public static final Type tShort = new Type(TypeCode.SHORT, SIG_SHORT); + public static final Type tInt = new Type(TypeCode.INT, SIG_INT); + public static final Type tFloat = new Type(TypeCode.FLOAT, SIG_FLOAT); + public static final Type tLong = new Type(TypeCode.LONG, SIG_LONG); + public static final Type tDouble = new Type(TypeCode.DOUBLE, SIG_DOUBLE); + public static final Type tObject = Type.tClass(idJavaLangObject); + public static final Type tClassDesc = Type.tClass(idJavaLangClass); + public static final Type tString = Type.tClass(idJavaLangString); + public static final Type tCloneable = Type.tClass(idJavaLangCloneable); + public static final Type tSerializable = Type.tClass(idJavaIoSerializable); + + /** + * Create a type given a typecode and a type signature. + */ + protected Type(TypeCode tc, String typeSig) { + this.typeCode = tc; + this.typeSig = typeSig; + typeHash.put(typeSig, this); + } + + /** + * Return the Java type signature. + */ + public final String getTypeSignature() { + return typeSig; + } + + /** + * Return the type code. + */ + public final int getTypeCode() { + return typeCode.tcCode(); + } + + /** + * Return the type mask. The bits in this mask correspond + * to the TM_* constants defined in Constants. Only one bit + * is set at a type. + * @see Constants + */ + public final int getTypeMask() { + return 1 << typeCode.tcCode(); + } + + /** + * Check for a certain type. + */ + public final boolean isType(int tc) { + return typeCode.tcCode() == tc; + } + + /** + * Check to see if this is the bogus type "array of void" + * + * Although this highly degenerate "type" is not constructable from + * the grammar, the Parser accepts it. Rather than monkey with the + * Parser, we check for the bogus type at specific points and give + * a nice error. + */ + public boolean isVoidArray() { + // a void type is not a void array. + if (!isType(TC_ARRAY)) { + return false; + } + // If this is an array, find out what its element type is. + Type type = this; + while (type.isType(TC_ARRAY)) + type = type.getElementType(); + + return type.isType(TC_VOID); + } + + + /** + * Check for a certain set of types. + */ + public final boolean inMask(int tm) { + return ((1 << typeCode.tcCode()) & tm) != 0; + } + + /** + * Create an array type. + */ + public static synchronized Type tArray(Type elem) { + String sig = SIG_ARRAY + elem.getTypeSignature(); + Type t = typeHash.get(sig); + if (t == null) { + t = new ArrayType(sig, elem); + } + return t; + } + + /** + * Return the element type of an array type. Only works + * for array types. + */ + public Type getElementType() { + throw new CompilerError("getElementType"); + } + + /** + * Return the array dimension. Only works for + * array types. + */ + public int getArrayDimension() { + return 0; + } + + /** + * Create a class type. + * @arg className the fully qualified class name + */ + public static synchronized Type tClass(Identifier className) { + if (className.isInner()) { + Type t = tClass(mangleInnerType(className)); + if (t.getClassName() != className) + // Somebody got here first with a mangled name. + // (Perhaps it came from a binary.) + changeClassName(t.getClassName(), className); + return t; + } + // see if we've cached the object in the Identifier + if (className.typeObject != null) { + return className.typeObject; + } + String sig = + SIG_CLASS + + className.toString().replace('.', SIGC_PACKAGE) + + SIG_ENDCLASS; + Type t = typeHash.get(sig); + if (t == null) { + t = new ClassType(sig, className); + } + + className.typeObject = t; // cache the Type object in the Identifier + return t; + } + + /** + * Return the ClassName. Only works on class types. + */ + public Identifier getClassName() { + throw new CompilerError("getClassName:" + this); + } + + /** + * Given an inner identifier, return the non-inner, mangled + * representation used to manage signatures. + * + * Note: It is changed to 'public' for Jcov file generation. + * (see Assembler.java) + */ + + public static Identifier mangleInnerType(Identifier className) { + // Map "pkg.Foo. Bar" to "pkg.Foo$Bar". + if (!className.isInner()) return className; + Identifier mname = Identifier.lookup( + className.getFlatName().toString(). + replace('.', SIGC_INNERCLASS) ); + if (mname.isInner()) throw new CompilerError("mangle "+mname); + return Identifier.lookup(className.getQualifier(), mname); + } + + /** + * We have learned that a signature means something other + * that what we thought it meant. Live with it: Change all + * affected data structures to reflect the new name of the old type. + *

                + * (This is necessary because of an ambiguity between the + * low-level signatures of inner types and their manglings. + * Note that the latter are also valid class names.) + */ + private static void changeClassName(Identifier oldName, Identifier newName) { + // Note: If we are upgrading "pkg.Foo$Bar" to "pkg.Foo. Bar", + // we assume someone else will come along and deal with any types + // inner within Bar. So, there's only one change to make. + ((ClassType)Type.tClass(oldName)).className = newName; + } + + /** + * Create a method type with no arguments. + */ + public static synchronized Type tMethod(Type ret) { + return tMethod(ret, noArgs); + } + + /** + * Create a method type with arguments. + */ + public static synchronized Type tMethod(Type returnType, Type argTypes[]) { + StringBuilder sb = new StringBuilder(); + sb.append(SIG_METHOD); + for (Type argType : argTypes) { + sb.append(argType.getTypeSignature()); + } + sb.append(SIG_ENDMETHOD); + sb.append(returnType.getTypeSignature()); + + String sig = sb.toString(); + Type t = typeHash.get(sig); + if (t == null) { + t = new MethodType(sig, returnType, argTypes); + } + return t; + } + + /** + * Return the return type. Only works for method types. + */ + public Type getReturnType() { + throw new CompilerError("getReturnType"); + } + + /** + * Return the argument types. Only works for method types. + */ + public Type getArgumentTypes()[] { + throw new CompilerError("getArgumentTypes"); + } + + /** + * Create a Type from an Java type signature. + * @exception CompilerError invalid type signature. + */ + public static synchronized Type tType(String sig) { + Type t = typeHash.get(sig); + if (t != null) { + return t; + } + + switch (sig.charAt(0)) { + case SIGC_ARRAY: + return Type.tArray(tType(sig.substring(1))); + + case SIGC_CLASS: + return Type.tClass(Identifier.lookup(sig.substring(1, sig.length() - 1).replace(SIGC_PACKAGE, '.'))); + + case SIGC_METHOD: { + Type argv[] = new Type[8]; + int argc = 0; + int i, j; + + for (i = 1 ; sig.charAt(i) != SIGC_ENDMETHOD ; i = j) { + for (j = i ; sig.charAt(j) == SIGC_ARRAY ; j++); + if (sig.charAt(j++) == SIGC_CLASS) { + while (sig.charAt(j++) != SIGC_ENDCLASS); + } + if (argc == argv.length) { + Type newargv[] = new Type[argc * 2]; + System.arraycopy(argv, 0, newargv, 0, argc); + argv = newargv; + } + argv[argc++] = tType(sig.substring(i, j)); + } + + Type argtypes[] = new Type[argc]; + System.arraycopy(argv, 0, argtypes, 0, argc); + return Type.tMethod(tType(sig.substring(i + 1)), argtypes); + } + } + + throw new CompilerError("invalid TypeSignature:" + sig); + } + + /** + * Check if the type arguments are the same. + * @return true if both types are method types and the + * argument types are identical. + */ + public boolean equalArguments(Type t) { + return false; + } + + /** + * Return the amount of space this type takes up on the + * Java operand stack. For a method this is equal to the + * total space taken up by the arguments. + */ + public int stackSize() { + switch (typeCode.tcCode()) { + case TC_ERROR: + case TC_VOID: + return 0; + case TC_BOOLEAN: + case TC_BYTE: + case TC_SHORT: + case TC_CHAR: + case TC_INT: + case TC_FLOAT: + case TC_ARRAY: + case TC_CLASS: + return 1; + case TC_LONG: + case TC_DOUBLE: + return 2; + } + throw new CompilerError("stackSize " + toString()); + } + + /** + * Return the type code offset. This offset can be added to + * an opcode to get the right opcode type. Most opcodes + * are ordered: int, long, float, double, array. For + * example: iload, lload fload, dload, aload. So the + * appropriate opcode is iadd + type.getTypeCodeOffset(). + */ + public int getTypeCodeOffset() { + switch (typeCode.tcCode()) { + case TC_BOOLEAN: + case TC_BYTE: + case TC_SHORT: + case TC_CHAR: + case TC_INT: + return 0; + case TC_LONG: + return 1; + case TC_FLOAT: + return 2; + case TC_DOUBLE: + return 3; + case TC_NULL: + case TC_ARRAY: + case TC_CLASS: + return 4; + } + throw new CompilerError("invalid typecode: " + typeCode); + } + + /** + * Convert a Type to a string, if abbrev is true class names are + * not fully qualified, if ret is true the return type is included. + */ + public String typeString(String id, boolean abbrev, boolean ret) { + String s = null; + + switch (typeCode.tcCode()) { + case TC_NULL: s = "null"; break; + case TC_VOID: s = "void"; break; + case TC_BOOLEAN: s = "boolean"; break; + case TC_BYTE: s = "byte"; break; + case TC_CHAR: s = "char"; break; + case TC_SHORT: s = "short"; break; + case TC_INT: s = "int"; break; + case TC_LONG: s = "long"; break; + case TC_FLOAT: s = "float"; break; + case TC_DOUBLE: s = "double"; break; + case TC_ERROR: s = ""; + if (this==tPackage) s = ""; + break; + default: s = "unknown"; + } + + return (id.length() > 0) ? s + " " + id : s; + } + + /** + * Create a type string, given an identifier. + */ + public String typeString(String id) { + return typeString(id, false, true); + } + + /** + * Convert to a String + */ + public String toString() { + return typeString("", false, true); + } + + public String toStringValue(Object value) { + return typeCode.toValueString(value); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/java/ZipClassFile.java b/rmic/src/main/java/org/glassfish/rmic/tools/java/ZipClassFile.java new file mode 100644 index 000000000..089690aab --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/java/ZipClassFile.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; + +/** + * This class is used to represent a file loaded from the class path, and + * is a zip file entry. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +final +class ZipClassFile extends ClassFile { + private final ZipFile zipFile; + private final ZipEntry zipEntry; + + /** + * Constructor for instance representing a zip file entry + */ + public ZipClassFile(ZipFile zf, ZipEntry ze) { + this.zipFile = zf; + this.zipEntry = ze; + } + + @Override + public boolean isZipped() { + return true; + } + + @Override + public InputStream getInputStream() throws IOException { + try { + return zipFile.getInputStream(zipEntry); + } catch (ZipException e) { + throw new IOException(e.getMessage()); + } + } + + @Override + public boolean exists() { + return true; + } + + @Override + public boolean isDirectory() { + return zipEntry.getName().endsWith("/"); + } + + @Override + public long lastModified() { + return zipEntry.getTime(); + } + + @Override + public String getPath() { + return zipFile.getName() + "(" + zipEntry.getName() + ")"; + } + + @Override + public String getName() { + return zipEntry.getName(); + } + +//JCOV + @Override + public String getAbsoluteName() { + return zipFile.getName() + "(" + zipEntry.getName() + ")"; + } +// end JCOV + + @Override + public long length() { + return zipEntry.getSize(); + } + + @Override + public String toString() { + return zipEntry.toString(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/BatchEnvironment.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/BatchEnvironment.java new file mode 100644 index 000000000..c79d23c60 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/BatchEnvironment.java @@ -0,0 +1,1232 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import org.glassfish.rmic.BatchEnvironmentError; +import org.glassfish.rmic.asm.AsmClassFactory; +import org.glassfish.rmic.tools.binaryclass.BinaryClassFactory; +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.java.Package; +import org.glassfish.rmic.tools.tree.Node; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Set; +import java.util.Vector; +import java.util.stream.Collectors; + +import static java.lang.Character.isDigit; + +/** + * Main environment of the batch version of the Java compiler, + * this needs more work. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +public +class BatchEnvironment extends Environment implements ErrorConsumer { + private static final String USE_LEGACY_PARSING_PROPERTY = "org.glassfish.rmic.UseLegacyClassParsing"; + private static final String JAVA_VERSION_PROPERTY = "java.version"; + private static final int ASM_ONLY_JAVA_VERSION = 10; + private static final ClassDefinitionFactory classDefinitionFactory = createClassDefinitionFactory(); + + static ClassDefinitionFactory createClassDefinitionFactory() { + try { + return useBinaryClassFactory() ? new BinaryClassFactory() : new AsmClassFactory(); + } catch (NoClassDefFoundError e) { + if (!mayUseBinaryClassFactory()) + throw new BatchEnvironmentError("RMIC is unable to parse class files at this JDK level without an appropriate version of ASM in its class path"); + + return new BinaryClassFactory(); + } + } + + private static boolean useBinaryClassFactory() { + return Boolean.getBoolean(USE_LEGACY_PARSING_PROPERTY) && mayUseBinaryClassFactory(); + } + + private static boolean mayUseBinaryClassFactory() { + return isBinaryClassCompatibleJavaVersion(System.getProperty(JAVA_VERSION_PROPERTY)); + } + + private static boolean isBinaryClassCompatibleJavaVersion(String property) { + return property.startsWith("1.") || getVersionPortion(property) < ASM_ONLY_JAVA_VERSION; + } + + private static int getVersionPortion(String versionString) { + for (int i = 0; i < versionString.length(); i++) + if (!isDigit(versionString.charAt(i))) + return Integer.parseInt(versionString.substring(0, i)); + + return Integer.parseInt(versionString); + } + + /** + * The stream where error message are printed. + */ + private OutputStream out; + + /** + * The path we use for finding class (binary) files. + */ + protected ClassPath binaryPath; + + /** + * A hashtable of resource contexts. + */ + private Hashtable packages = new Hashtable<>(31); + + /** + * The classes, in order of appearance. + */ + private Vector classesOrdered = new Vector<>(); + + /** + * The classes, keyed by ClassDeclaration. + */ + private Hashtable classes = new Hashtable<>(351); + + /** + * flags + */ + public int flags; + + /** + * Major and minor versions to use for generated class files. + * Environments that extend BatchEnvironment (such as javadoc's + * Env class) get the default values below. + * + * javac itself may override these versions with values determined + * from the command line "-target" option. + */ + public short majorVersion = JAVA_DEFAULT_VERSION; + public short minorVersion = JAVA_DEFAULT_MINOR_VERSION; + +// JCOV + /** + * coverage data file + */ + private File covFile; +// end JCOV + + /** + * The number of errors and warnings + */ + public int nerrors; + public int nwarnings; + private int ndeprecations; + + /** + * A list of files containing deprecation warnings. + */ + private Vector deprecationFiles = new Vector<>(); + + /** + * writes out error messages + */ + + private ErrorConsumer errorConsumer; + + public BatchEnvironment(OutputStream out, + ClassPath binaryPath) { + this(out, binaryPath, null); + } + + public BatchEnvironment(OutputStream out, + ClassPath binaryPath, + ErrorConsumer errorConsumer) { + this.out = out; + this.binaryPath = binaryPath; + this.errorConsumer = (errorConsumer == null) ? this : errorConsumer; + } + + /** + * Return flags + */ + public int getFlags() { + return flags; + } + + /** + * Return major version to use for generated class files + */ + public short getMajorVersion() { + return majorVersion; + } + + /** + * Return minor version to use for generated class files + */ + public short getMinorVersion() { + return minorVersion; + } + +// JCOV + /** + * Return coverage data file + */ + public File getcovFile() { + return covFile; + } +// end JCOV + + /** + * Return an enumeration of all the currently defined classes + * in order of appearance to getClassDeclaration(). + */ + public Enumeration getClasses() { + return classesOrdered.elements(); + } + + /** + * Return the declarations for all generated classes. These can be recognized + * as having the 'parsed' status + */ + public Iterable getGeneratedClasses() { + return classesOrdered.stream() + .filter(p -> p.getStatus() == Constants.CS_PARSED) + .collect(Collectors.toList()); + } + + /** + * A set of Identifiers for all packages exempt from the "exists" + * check in Imports#resolve(). These are the current packages for + * all classes being compiled as of the first call to isExemptPackage. + */ + private Set exemptPackages; + + /** + * Tells whether an Identifier refers to a package which should be + * exempt from the "exists" check in Imports#resolve(). + */ + public boolean isExemptPackage(Identifier id) { + if (exemptPackages == null) { + // Collect a list of the packages of all classes currently + // being compiled. + setExemptPackages(); + } + + return exemptPackages.contains(id); + } + + /** + * Set the set of packages which are exempt from the exists check + * in Imports#resolve(). + */ + private void setExemptPackages() { + // The JLS gives us the freedom to define "accessibility" of + // a package in whatever manner we wish. After the evaluation + // of bug 4093217, we have decided to consider a package P + // accessible if either: + // + // 1. The directory corresponding to P exists on the classpath. + // 2. For any class C currently being compiled, C belongs to + // package P. + // 3. For any class C currently being compiled, C belongs to + // package Q and Q is a subpackage of P. + // + // In order to implement this, we collect the current packages + // (and prefixes) of all packages we have found so far. These + // will be exempt from the "exists" check in + // org.glassfish.rmic.tools.java.Imports#resolve(). + + exemptPackages = new HashSet<>(101); + + // Add all of the current packages and their prefixes to our set. + for (ClassDeclaration c : getGeneratedClasses()) { + SourceClass def = (SourceClass) c.getClassDefinition(); + if (def.isLocal()) + continue; + + Identifier pkg = def.getImports().getCurrentPackage(); + + // Add the name of this package and all of its prefixes + // to our set. + while (pkg != idNull && exemptPackages.add(pkg)) { + pkg = pkg.getQualifier(); + } + } + + // Before we go any further, we make sure java.lang is + // accessible and that it is not ambiguous. These checks + // are performed for "ordinary" packages in + // org.glassfish.rmic.tools.java.Imports#resolve(). The reason we perform + // them specially for java.lang is that we want to report + // the error once, and outside of any particular file. + + // Check to see if java.lang is accessible. + if (!exemptPackages.contains(idJavaLang)) { + // Add java.lang to the set of exempt packages. + exemptPackages.add(idJavaLang); + + if (!getPackage(idJavaLang).exists()) { + // java.lang doesn't exist. + error(0, "package.not.found.strong", idJavaLang); + } + } + + // Next we ensure that java.lang is not both a class and + // a package. (Fix for 4101529) + // + // This change has been backed out because, on WIN32, it + // failed to take character case into account. It will + // be put back in later. + // + // Identifier resolvedName = + // resolvePackageQualifiedName(idJavaLang); + // Identifier topClassName = resolvedName.getTopName(); + // //if (Imports.importable(topClassName, env)) { + // if (Imports.importable(topClassName, this)) { + // // It is a package and a class. Emit the error. + // error(0, "package.class.conflict.strong", + // idJavaLang, topClassName); + // return; + // } + } + + /** + * Get a class, given the fully qualified class name + */ + public ClassDeclaration getClassDeclaration(Identifier nm) { + return getClassDeclaration(Type.tClass(nm)); + } + + public ClassDeclaration getClassDeclaration(Type t) { + ClassDeclaration c = classes.get(t); + if (c == null) { + classes.put(t, c = new ClassDeclaration(t.getClassName())); + classesOrdered.addElement(c); + } + return c; + } + + /** + * Check if a class exists + * Applies only to package members (non-nested classes). + */ + public boolean classExists(Identifier nm) { + if (nm.isInner()) { + nm = nm.getTopName(); // just in case + } + Type t = Type.tClass(nm); + ClassDeclaration c = classes.get(t); + return (c != null) ? c.getName().equals(nm) : getPackage(nm.getQualifier()).classExists(nm.getName()); + } + + /** + * Get the package path for a package + */ + public Package getPackage(Identifier pkg) { + Package p = packages.get(pkg); + if (p == null) { + packages.put(pkg, p = new Package(binaryPath, pkg)); + } + return p; + } + + /** + * Parse a source file + */ + public void parseFile(ClassFile file) throws FileNotFoundException { + long tm = System.currentTimeMillis(); + InputStream input; + BatchParser p; + + if (tracing) dtEnter("parseFile: PARSING SOURCE " + file); + + Environment env = new Environment(this, file); + + try { + input = file.getInputStream(); + env.setCharacterEncoding(getCharacterEncoding()); + // p = new BatchParser(e, new BufferedInputStream(input)); + p = new BatchParser(env, input); + } catch(IOException ex) { + if (tracing) dtEvent("parseFile: IO EXCEPTION " + file); + throw new FileNotFoundException(); + } + + try { + p.parseFile(); + } catch(Exception e) { + throw new CompilerError(e); + } + + try { + input.close(); + } catch (IOException ex) { + // We're turn with the input, so ignore this. + } + + if (verbose()) { + tm = System.currentTimeMillis() - tm; + output(Main.getText("benv.parsed_in", file.getPath(), + Long.toString(tm))); + } + + if (p.classes.size() == 0) { + // The JLS allows a file to contain no compilation units -- + // that is, it allows a file to contain no classes or interfaces. + // In this case, we are still responsible for checking that the + // imports resolve properly. The way the compiler is organized, + // this is the last point at which we still have enough information + // to do so. (Fix for 4041851). + p.imports.resolve(env); + } else { + // In an attempt to see that classes which come from the + // same source file are all recompiled when any one of them + // would be recompiled (when using the -depend option) we + // introduce artificial dependencies between these classes. + // We do this by calling the addDependency() method, which + // adds a (potentially unused) class reference to the constant + // pool of the class. + // + // Previously, we added a dependency from every class in the + // file, to every class in the file. This introduced, in + // total, a quadratic number of potentially bogus constant + // pool entries. This was bad. Now we add our artificial + // dependencies in such a way that the classes are connected + // in a circle. While single links is probably sufficient, the + // code below adds double links just to be diligent. + // (Fix for 4108286). + // + // Note that we don't chain in inner classes. The links + // between them and their outerclass should be sufficient + // here. + // (Fix for 4107960). + // + // The dependency code was previously in BatchParser.java. + Enumeration e = p.classes.elements(); + + // first will not be an inner class. + ClassDefinition first = e.nextElement(); + if (first.isInnerClass()) { + throw new CompilerError("BatchEnvironment, first is inner"); + } + + ClassDefinition current = first; + ClassDefinition next; + while (e.hasMoreElements()) { + next = e.nextElement(); + // Don't chain in inner classes. + if (next.isInnerClass()) { + continue; + } + current.addDependency(next.getClassDeclaration()); + next.addDependency(current.getClassDeclaration()); + current = next; + } + // Make a circle. Don't bother to add a dependency if there + // is only one class in the file. + if (current != first) { + current.addDependency(first.getClassDeclaration()); + first.addDependency(current.getClassDeclaration()); + } + } + + if (tracing) dtExit("parseFile: SOURCE PARSED " + file); + } + + /** + * Load a binary file + */ + private ClassDefinition loadFile(ClassFile file) throws IOException { + long tm = System.currentTimeMillis(); + InputStream input = file.getInputStream(); + ClassDefinition c; + + if (tracing) dtEnter("loadFile: LOADING CLASSFILE " + file); + + try { + c = classDefinitionFactory.loadDefinition(input, new Environment(this, file)); + } catch (ClassFormatError e) { + error(0, "class.format", file.getPath(), e.getMessage()); + if (tracing) dtExit("loadFile: CLASS FORMAT ERROR " + file); + return null; + } catch (java.io.EOFException e) { + // If we get an EOF while processing a class file, then + // it has been truncated. We let other I/O errors pass + // through. Fix for 4088443. + error(0, "truncated.class", file.getPath()); + return null; + } + + input.close(); + if (verbose()) { + tm = System.currentTimeMillis() - tm; + output(Main.getText("benv.loaded_in", file.getPath(), + Long.toString(tm))); + } + + if (tracing) dtExit("loadFile: CLASSFILE LOADED " + file); + + return c; + } + + /** + * Load a binary class + */ + private boolean needsCompilation(Hashtable check, ClassDeclaration c) { + switch (c.getStatus()) { + + case CS_UNDEFINED: + if (tracing) dtEnter("needsCompilation: UNDEFINED " + c.getName()); + loadDefinition(c); + return needsCompilation(check, c); + + case CS_UNDECIDED: + if (tracing) dtEnter("needsCompilation: UNDECIDED " + c.getName()); + if (check.get(c) == null) { + check.put(c, c); + + ClassDefinition def = c.getClassDefinition(); + for (Iterator e = def.getDependencies(); e.hasNext() ;) { + ClassDeclaration dep = e.next(); + if (needsCompilation(check, dep)) { + // It must be source, dependencies need compilation + c.setDefinition(def, CS_SOURCE); + if (tracing) dtExit("needsCompilation: YES (source) " + c.getName()); + return true; + } + } + } + if (tracing) dtExit("needsCompilation: NO (undecided) " + c.getName()); + return false; + + case CS_BINARY: + if (tracing) { + dtEnter("needsCompilation: BINARY " + c.getName()); + dtExit("needsCompilation: NO (binary) " + c.getName()); + } + return false; + + } + + if (tracing) dtExit("needsCompilation: YES " + c.getName()); + return true; + } + + /** + * Load the definition of a class + * or at least determine how to load it. + * The caller must repeat calls to this method + * until it the state converges to CS_BINARY, CS_PARSED, or the like.. + * @see ClassDeclaration#getClassDefinition + */ + public void loadDefinition(ClassDeclaration c) { + if (tracing) dtEnter("loadDefinition: ENTER " + + c.getName() + ", status " + c.getStatus()); + switch (c.getStatus()) { + case CS_UNDEFINED: { + if (tracing) + dtEvent("loadDefinition: STATUS IS UNDEFINED"); + Identifier nm = c.getName(); + Package pkg; + pkg = getPackage(nm.getQualifier()); + ClassFile binfile = pkg.getBinaryFile(nm.getName()); + if (binfile == null) { + // must be source, there is no binary + c.setDefinition(null, CS_SOURCE); + if (tracing) + dtExit("loadDefinition: MUST BE SOURCE (no binary) " + + c.getName()); + return; + } + + ClassFile srcfile = pkg.getSourceFile(nm.getName()); + if (srcfile == null) { + if (tracing) + dtEvent("loadDefinition: NO SOURCE " + c.getName()); + ClassDefinition cDef; + try { + cDef = loadFile(binfile); + } catch (IOException e) { + // If we can't access the binary, set the class to + // be not found. (bug id 4030497) + c.setDefinition(null, CS_NOTFOUND); + + error(0, "io.exception", binfile); + if (tracing) + dtExit("loadDefinition: IO EXCEPTION (binary)"); + return; + } + if ((cDef != null) && !cDef.getName().equals(nm)) { + error(0, "wrong.class", binfile.getPath(), c, cDef); + cDef = null; + if (tracing) + dtEvent("loadDefinition: WRONG CLASS (binary)"); + } + if (cDef == null) { + // no source nor binary found + c.setDefinition(null, CS_NOTFOUND); + if (tracing) + dtExit("loadDefinition: NOT FOUND (source or binary)"); + return; + } + + // Couldn't find the source, try the one mentioned in the binary + if (cDef.getSource() != null) { + srcfile = ClassFile.newClassFile(new File((String)cDef.getSource())); + // Look for the source file + srcfile = pkg.getSourceFile(srcfile.getName()); + if ((srcfile != null) && srcfile.exists()) { + if (tracing) + dtEvent("loadDefinition: FILENAME IN BINARY " + + srcfile); + if (srcfile.lastModified() > binfile.lastModified()) { + // must be source, it is newer than the binary + c.setDefinition(cDef, CS_SOURCE); + if (tracing) + dtEvent("loadDefinition: SOURCE IS NEWER " + + srcfile); + cDef.loadNested(this); + if (tracing) + dtExit("loadDefinition: MUST BE SOURCE " + + c.getName()); + return; + } + if (dependencies()) { + c.setDefinition(cDef, CS_UNDECIDED); + if (tracing) + dtEvent("loadDefinition: UNDECIDED " + + c.getName()); + } else { + c.setDefinition(cDef, CS_BINARY); + if (tracing) + dtEvent("loadDefinition: MUST BE BINARY " + + c.getName()); + } + cDef.loadNested(this); + if (tracing) + dtExit("loadDefinition: EXIT " + + c.getName() + ", status " + c.getStatus()); + return; + } + } + + // It must be binary, there is no source + c.setDefinition(cDef, CS_BINARY); + if (tracing) + dtEvent("loadDefinition: MUST BE BINARY (no source) " + + c.getName()); + cDef.loadNested(this); + if (tracing) + dtExit("loadDefinition: EXIT " + + c.getName() + ", status " + c.getStatus()); + return; + } + ClassDefinition cDef = null; + try { + if (srcfile.lastModified() > binfile.lastModified()) { + // must be source, it is newer than the binary + c.setDefinition(null, CS_SOURCE); + if (tracing) + dtEvent("loadDefinition: MUST BE SOURCE (younger than binary) " + + c.getName()); + return; + } + cDef = loadFile(binfile); + } catch (IOException e) { + error(0, "io.exception", binfile); + if (tracing) + dtEvent("loadDefinition: IO EXCEPTION (binary)"); + } + if ((cDef != null) && !cDef.getName().equals(nm)) { + error(0, "wrong.class", binfile.getPath(), c, cDef); + cDef = null; + if (tracing) + dtEvent("loadDefinition: WRONG CLASS (binary)"); + } + if (cDef != null) { + Identifier name = cDef.getName(); + if (name.equals(c.getName())) { + if (dependencies()) { + c.setDefinition(cDef, CS_UNDECIDED); + if (tracing) + dtEvent("loadDefinition: UNDECIDED " + name); + } else { + c.setDefinition(cDef, CS_BINARY); + if (tracing) + dtEvent("loadDefinition: MUST BE BINARY " + name); + } + } else { + c.setDefinition(null, CS_NOTFOUND); + if (tracing) + dtEvent("loadDefinition: NOT FOUND (source or binary)"); + if (dependencies()) { + getClassDeclaration(name).setDefinition(cDef, CS_UNDECIDED); + if (tracing) + dtEvent("loadDefinition: UNDECIDED " + name); + } else { + getClassDeclaration(name).setDefinition(cDef, CS_BINARY); + if (tracing) + dtEvent("loadDefinition: MUST BE BINARY " + name); + } + } + } else { + c.setDefinition(null, CS_NOTFOUND); + if (tracing) + dtEvent("loadDefinition: NOT FOUND (source or binary)"); + } + if (cDef != null && cDef == c.getClassDefinition()) + cDef.loadNested(this); + if (tracing) dtExit("loadDefinition: EXIT " + + c.getName() + ", status " + c.getStatus()); + return; + } + + case CS_UNDECIDED: { + if (tracing) dtEvent("loadDefinition: STATUS IS UNDECIDED"); + Hashtable tab = new Hashtable<>(); + if (!needsCompilation(tab, c)) { + // All undecided classes that this class depends on must be binary + for (Enumeration e = tab.keys() ; e.hasMoreElements() ; ) { + ClassDeclaration dep = e.nextElement(); + if (dep.getStatus() == CS_UNDECIDED) { + // must be binary, dependencies need compilation + dep.setDefinition(dep.getClassDefinition(), CS_BINARY); + if (tracing) + dtEvent("loadDefinition: MUST BE BINARY " + dep); + } + } + } + if (tracing) dtExit("loadDefinition: EXIT " + + c.getName() + ", status " + c.getStatus()); + return; + } + + case CS_SOURCE: { + if (tracing) dtEvent("loadDefinition: STATUS IS SOURCE"); + ClassFile srcfile; + Package pkg; + if (c.getClassDefinition() != null) { + // Use the source file name from the binary class file + pkg = getPackage(c.getName().getQualifier()); + srcfile = pkg.getSourceFile((String)c.getClassDefinition().getSource()); + if (srcfile == null) { + String fn = (String)c.getClassDefinition().getSource(); + srcfile = ClassFile.newClassFile(new File(fn)); + } + } else { + // Get a source file name from the package + Identifier nm = c.getName(); + pkg = getPackage(nm.getQualifier()); + srcfile = pkg.getSourceFile(nm.getName()); + if (srcfile == null) { + // not found, there is no source + c.setDefinition(null, CS_NOTFOUND); + if (tracing) + dtExit("loadDefinition: SOURCE NOT FOUND " + + c.getName() + ", status " + c.getStatus()); + return; + } + } + try { + parseFile(srcfile); + } catch (FileNotFoundException e) { + error(0, "io.exception", srcfile); + if (tracing) dtEvent("loadDefinition: IO EXCEPTION (source)"); + } + if ((c.getClassDefinition() == null) || (c.getStatus() == CS_SOURCE)) { + // not found after parsing the file + error(0, "wrong.source", srcfile.getPath(), c, pkg); + c.setDefinition(null, CS_NOTFOUND); + if (tracing) + dtEvent("loadDefinition: WRONG CLASS (source) " + + c.getName()); + } + if (tracing) dtExit("loadDefinition: EXIT " + + c.getName() + ", status " + c.getStatus()); + return; + } + } + if (tracing) dtExit("loadDefinition: EXIT " + + c.getName() + ", status " + c.getStatus()); + } + + /** + * Create a new class. + */ + public ClassDefinition makeClassDefinition(Environment toplevelEnv, + long where, + IdentifierToken name, + String doc, int modifiers, + IdentifierToken superClass, + IdentifierToken interfaces[], + ClassDefinition outerClass) { + + Identifier nm = name.getName(); + long nmpos = name.getWhere(); + + Identifier pkgNm; + String mangledName = null; + ClassDefinition localContextClass = null; + + // Provide name for a local class. This used to be set after + // the class was created, but it is needed for checking within + // the class constructor. + // NOTE: It seems that we could always provide the simple name, + // and thereby avoid the test in 'ClassDefinition.getLocalName()' + // for the definedness of the local name. There, if the local + // name is not set, a simple name is extracted from the result of + // 'getName()'. That name can potentially change, however, as + // it is ultimately derived from 'ClassType.className', which is + // set by 'Type.changeClassName'. Better leave this alone... + Identifier localName = null; + + if (nm.isQualified() || nm.isInner()) { + pkgNm = nm; + } else if ((modifiers & (M_LOCAL | M_ANONYMOUS)) != 0) { + // Inaccessible class. Create a name of the form + // 'PackageMember.N$localName' or 'PackageMember.N'. + // Note that the '.' will be converted later to a '$'. + // pkgNm = generateName(outerClass, nm); + localContextClass = outerClass.getTopClass(); + // Always use the smallest number in generating the name that + // renders the complete name unique within the top-level class. + // This is required to make the names more predictable, as part + // of a serialization-related workaround, and satisfies an obscure + // requirement that the name of a local class be of the form + // 'PackageMember$1$localName' when this name is unique. + for (int i = 1 ; ; i++) { + mangledName = i + (nm.equals(idNull) ? "" : SIG_INNERCLASS + nm); + if (localContextClass.getLocalClass(mangledName) == null) { + break; + } + } + Identifier outerNm = localContextClass.getName(); + pkgNm = Identifier.lookupInner(outerNm, Identifier.lookup(mangledName)); + //System.out.println("LOCAL CLASS: " + pkgNm + " IN " + localContextClass); + if ((modifiers & M_ANONYMOUS) != 0) { + localName = idNull; + } else { + // Local class has a locally-scoped name which is independent of pkgNm. + localName = nm; + } + } else if (outerClass != null) { + // Accessible inner class. Qualify name with surrounding class name. + pkgNm = Identifier.lookupInner(outerClass.getName(), nm); + } else { + pkgNm = nm; + } + + // Find the class + ClassDeclaration c = toplevelEnv.getClassDeclaration(pkgNm); + + // Make sure this is the first definition + if (c.isDefined()) { + toplevelEnv.error(nmpos, "class.multidef", + c.getName(), c.getClassDefinition().getSource()); + // Don't mess with the existing class declarations with same name + c = new ClassDeclaration (pkgNm); + } + + if (superClass == null && !pkgNm.equals(idJavaLangObject)) { + superClass = new IdentifierToken(idJavaLangObject); + } + + ClassDefinition sourceClass = + new SourceClass(toplevelEnv, where, c, doc, + modifiers, superClass, interfaces, + (SourceClass) outerClass, localName); + + if (outerClass != null) { + // It is a member of its enclosing class. + outerClass.addMember(toplevelEnv, new SourceMember(sourceClass)); + // Record local (or anonymous) class in the class whose name will + // serve as the prefix of the local class name. This is necessary + // so that the class may be retrieved from its name, which does not + // fully represent the class nesting structure. + // See 'ClassDefinition.getClassDefinition'. + // This is part of a fix for bugid 4054523 and 4030421. + if ((modifiers & (M_LOCAL | M_ANONYMOUS)) != 0) { + localContextClass.addLocalClass(sourceClass, mangledName); + } + } + + // The local name of an anonymous or local class used to be set here + // with a call to 'setLocalName'. This has been moved to the constructor + // for 'SourceClass', which now takes a 'localName' argument. + + return sourceClass; + } + + /* + * makeMemberDefinition method is left with rawtypes and with lint messages suppressed. + * The addition of Generics to com.org.glassfish.rmic.tools.* has uncovered an inconsistency + * in usage though tools still work correctly as long as this function is allowed to + * function as is. + */ + + /** + * Create a new field. + */ + @SuppressWarnings({"rawtypes","unchecked"}) + public MemberDefinition makeMemberDefinition(Environment origEnv, long where, + ClassDefinition clazz, + String doc, int modifiers, + Type type, Identifier name, + IdentifierToken argNames[], + IdentifierToken expIds[], + Object value) { + if (tracing) dtEvent("makeMemberDefinition: " + name + " IN " + clazz); + Vector v = null; + if (argNames != null) { + v = new Vector(argNames.length); + for (IdentifierToken argName : argNames) { + v.addElement(argName); + } + } + SourceMember f = new SourceMember(where, clazz, doc, modifiers, + type, name, v, expIds, (Node)value); + clazz.addMember(origEnv, f); + return f; + } + + /** + * Release resources in classpath. + */ + public void shutdown() { + try { + if (binaryPath != null) { + binaryPath.close(); + } + } catch (IOException ee) { + output(Main.getText("benv.failed_to_close_class_path", + ee.toString())); + } + binaryPath = null; + + super.shutdown(); + } + + /** + * Error String + */ + public + String errorString(String err, Object arg1, Object arg2, Object arg3) { + String key; + + if(err.startsWith("warn.")) + key = "javac.err." + err.substring(5); + else + key = "javac.err." + err; + + return Main.getText(key, + arg1 != null ? arg1.toString() : null, + arg2 != null ? arg2.toString() : null, + arg3 != null ? arg3.toString() : null); + } + + /** + * The filename where the last errors have occurred + */ + private String errorFileName; + + /** + * List of outstanding error messages + */ + private ErrorMessage errors; + + /** + * Insert an error message in the list of outstanding error messages. + * The list is sorted on input position and contains no duplicates. + * The return value indicates whether or not the message was + * actually inserted. + * + * The method flushErrors() used to check for duplicate error messages. + * It would only detect duplicates if they were contiguous. Removing + * non-contiguous duplicate error messages is slightly less complicated + * at insertion time, so the functionality was moved here. This also + * saves a miniscule number of allocations. + */ + private boolean insertError(long where, String message) { + //output("ERR = " + message); + + if (errors == null + || errors.where > where) { + // If the list is empty, or the error comes before any other + // errors, insert it at the beginning of the list. + ErrorMessage newMsg = new ErrorMessage(where, message); + newMsg.next = errors; + errors = newMsg; + + } else if (errors.where == where + && errors.message.equals(message)) { + // The new message is an exact duplicate of the first message + // in the list. Don't insert it. + return false; + + } else { + // Okay, we know that the error doesn't come first. Walk + // the list until we find the right position for insertion. + ErrorMessage current = errors; + ErrorMessage next; + + while ((next = current.next) != null + && next.where < where) { + current = next; + } + + // Now walk over any errors with the same location, looking + // for duplicates. If we find a duplicate, don't insert the + // error. + while ((next = current.next) != null + && next.where == where) { + if (next.message.equals(message)) { + // We have found an exact duplicate. Don't bother to + // insert the error. + return false; + } + current = next; + } + + // Now insert after current. + ErrorMessage newMsg = new ErrorMessage(where, message); + newMsg.next = current.next; + current.next = newMsg; + } + + // Indicate that the insertion occurred. + return true; + } + + private int errorsPushed; + + /** + * Maximum number of errors to print. + */ + private int errorLimit = 100; + + private boolean hitErrorLimit; + + /** + * Flush outstanding errors + */ + + public void pushError(String errorFileName, int line, String message, + String referenceText, String referenceTextPointer) { + int limit = errorLimit + nwarnings; + if (++errorsPushed >= limit && errorLimit >= 0) { + if (!hitErrorLimit) { + hitErrorLimit = true; + output(errorString("too.many.errors", + errorLimit,null,null)); + } + return; + } + if (errorFileName.endsWith(".java")) { + output(errorFileName + ":" + line + ": " + message); + output(referenceText); + output(referenceTextPointer); + } else { + // It wasn't really a source file (probably an error or + // warning because of a malformed or badly versioned + // class file. + output(errorFileName + ": " + message); + } + } + + public void flushErrors() { + if (errors == null) { + return; + } + + boolean inputAvail = false; + // Read the file + char data[] = null; + int dataLength = 0; + // A malformed file encoding could cause a CharConversionException. + // If something bad happens while trying to find the source file, + // don't bother trying to show lines. + try { + FileInputStream in = new FileInputStream(errorFileName); + data = new char[in.available()]; + InputStreamReader reader = + (getCharacterEncoding() != null ? + new InputStreamReader(in, getCharacterEncoding()) : + new InputStreamReader(in)); + dataLength = reader.read(data); + reader.close(); + inputAvail = true; + } catch(IOException e) { + // inputAvail will not be set + } + + // Report the errors + for (ErrorMessage msg = errors ; msg != null ; msg = msg.next) { + // There used to be code here which checked + // for duplicate error messages. This functionality + // has been moved to the method insertError(). See + // the comments on that method for more information. + + int ln = (int) (msg.where >>> WHEREOFFSETBITS); + int off = (int) (msg.where & ((1L << WHEREOFFSETBITS) - 1)); + if (off > dataLength) off = dataLength; + + String referenceString = ""; + String markerString = ""; + if(inputAvail) { + int i, j; + for (i = off ; (i > 0) && (data[i - 1] != '\n') && (data[i - 1] != '\r') ; i--); + for (j = off ; (j < dataLength) && (data[j] != '\n') && (data[j] != '\r') ; j++); + referenceString = new String(data, i, j - i); + + char strdata[] = new char[(off - i) + 1]; + for (j = i ; j < off ; j++) { + strdata[j-i] = (data[j] == '\t') ? '\t' : ' '; + } + strdata[off-i] = '^'; + markerString = new String(strdata); + } + + errorConsumer.pushError(errorFileName, ln, msg.message, + referenceString, markerString); + } + errors = null; + } + + /** + * Report error + */ + private void reportError(Object src, long where, String err, String msg) { + if (src == null) { + if (errorFileName != null) { + flushErrors(); + errorFileName = null; + } + if (err.startsWith("warn.")) { + if (warnings()) { + nwarnings++; + output(msg); + } + return; + } + output("error: " + msg); + nerrors++; + flags |= F_ERRORSREPORTED; + + } else if (src instanceof String) { + String fileName = (String)src; + + // Flush errors if we've moved on to a new file. + if (!fileName.equals(errorFileName)) { + flushErrors(); + errorFileName = fileName; + } + + // Classify `err' as a warning, deprecation warning, or + // error message. Proceed accordingly. + if (err.startsWith("warn.")) { + if (err.contains("is.deprecated")) { + // This is a deprecation warning. Add `src' to the + // list of files with deprecation warnings. + if (!deprecationFiles.contains(src)) { + deprecationFiles.addElement(src); + } + + // If we are reporting deprecations, try to add it + // to our list. Otherwise, just increment the + // deprecation count. + if (deprecation()) { + if (insertError(where, msg)) { + ndeprecations++; + } + } else { + ndeprecations++; + } + } else { + // This is a regular warning. If we are reporting + // warnings, try to add it to the list. Otherwise, just + // increment the warning count. + if (warnings()) { + if (insertError(where, msg)) { + nwarnings++; + } + } else { + nwarnings++; + } + } + } else { + // This is an error. Try to add it to the list of errors. + // If it isn't a duplicate, increment our error count. + if (insertError(where, msg)) { + nerrors++; + flags |= F_ERRORSREPORTED; + } + } + } else if (src instanceof ClassFile) { + reportError(((ClassFile)src).getPath(), where, err, msg); + + } else if (src instanceof Identifier) { + reportError(src.toString(), where, err, msg); + + } else if (src instanceof ClassDeclaration) { + try { + reportError(((ClassDeclaration)src).getClassDefinition(this), where, err, msg); + } catch (ClassNotFound e) { + reportError(((ClassDeclaration)src).getName(), where, err, msg); + } + } else if (src instanceof ClassDefinition) { + ClassDefinition c = (ClassDefinition)src; + if (!err.startsWith("warn.")) { + c.setError(); + } + reportError(c.getSource(), where, err, msg); + + } else if (src instanceof MemberDefinition) { + reportError(((MemberDefinition)src).getClassDeclaration(), where, err, msg); + + } else { + output(src + ":error=" + err + ":" + msg); + } + } + + /** + * Issue an error + */ + public void error(Object source, long where, String err, Object arg1, Object arg2, Object arg3) { + if (errorsPushed >= errorLimit + nwarnings) { + // Don't bother to queue any more errors if they won't get printed. + return; + } + if (System.getProperty("javac.dump.stack") != null) { + output("javac.err."+err+": "+errorString(err, arg1, arg2, arg3)); + new Exception("Stack trace").printStackTrace(new PrintStream(out)); + } + reportError(source, where, err, errorString(err, arg1, arg2, arg3)); + } + + /** + * Output a string. This can either be an error message or something + * for debugging. + */ + public void output(String msg) { + PrintStream out = + this.out instanceof PrintStream ? (PrintStream)this.out + : new PrintStream(this.out, true); + out.println(msg); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/BatchParser.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/BatchParser.java new file mode 100644 index 000000000..d7205c188 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/BatchParser.java @@ -0,0 +1,304 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import org.glassfish.rmic.tools.java.ClassDefinition; +import org.glassfish.rmic.tools.java.Environment; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.IdentifierToken; +import org.glassfish.rmic.tools.java.Imports; +import org.glassfish.rmic.tools.java.MemberDefinition; +import org.glassfish.rmic.tools.java.Parser; +import org.glassfish.rmic.tools.java.Type; +import org.glassfish.rmic.tools.tree.Node; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Vector; + +/** + * Batch file parser, this needs more work. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +public +class BatchParser extends Parser { + /** + * The current package + */ + protected Identifier pkg; + + /** + * The current imports + */ + protected Imports imports; + + /** + * The classes defined in this file + */ + protected Vector classes; + + + /** + * The current class + */ + protected SourceClass sourceClass; + + /** + * The toplevel environment + */ + protected Environment toplevelEnv; + + /** + * Create a batch file parser + */ + public BatchParser(Environment env, InputStream in) throws IOException { + super(env, in); + + imports = new Imports(env); + classes = new Vector<>(); + toplevelEnv = imports.newEnvironment(env); + } + + /** + * Package declaration + */ + public void packageDeclaration(long where, IdentifierToken t) { + Identifier nm = t.getName(); + //System.out.println("package " + nm); + if (pkg == null) { + // This code has been changed to pass an IdentifierToken, + // rather than an Identifier, to setCurrentPackage(). Imports + // now needs the location of the token. + pkg = t.getName(); + imports.setCurrentPackage(t); + } else { + env.error(where, "package.repeated"); + } + } + + /** + * Import class + */ + public void importClass(long pos, IdentifierToken t) { + //System.out.println("import class " + t); + imports.addClass(t); + } + + /** + * Import package + */ + public void importPackage(long pos, IdentifierToken t) { + //System.out.println("import package " + t); + imports.addPackage(t); + } + + /** + * Define class + */ + public ClassDefinition beginClass(long where, String doc, int mod, + IdentifierToken t, + IdentifierToken sup, + IdentifierToken interfaces[]) { + + // If this class is nested, the modifier bits set here will + // be copied into the 'SourceMember' object for the inner class + // created during the call to 'makeClassDefinition' below. + // When writing the class file, we will look there for the + // 'untransformed' modifiers. The modifiers in the ClassDefinition + // object will end up as the 'transformed' modifiers. Note that + // there are some bits set here that are not legal class modifiers + // according to the JVMS, e.g., M_PRIVATE and M_STATIC. These are + // masked off while writing the class file, but are preserved in + // the InnerClasses attributes. + + if (tracing) toplevelEnv.dtEnter("beginClass: " + sourceClass); + + SourceClass outerClass = sourceClass; + + if (outerClass == null && pkg != null) { + t = new IdentifierToken(t.getWhere(), + Identifier.lookup(pkg, t.getName())); + } + + // The defaults for anonymous and local classes should be documented! + + if ((mod & M_ANONYMOUS) != 0) { + mod |= (M_FINAL | M_PRIVATE); + } + if ((mod & M_LOCAL) != 0) { + mod |= M_PRIVATE; + } + + // Certain modifiers are implied as follows: + // + // 1. Any interface (nested or not) is implicitly deemed to be abstract, + // whether it is explicitly marked so or not. (Java 1.0.) + // 2. A interface which is a member of a type is implicitly deemed to + // be static, whether it is explicitly marked so or not. (InnerClasses) + // 3a. A type which is a member of an interface is implicitly deemed + // to be public, whether it is explicitly marked so or not. (InnerClasses) + // 3b. A type which is a member of an interface is implicitly deemed + // to be static, whether it is explicitly marked so or not. (InnerClasses) + + if ((mod & M_INTERFACE) != 0) { + // Rule 1. + mod |= M_ABSTRACT; + if (outerClass != null) { + // Rule 2. + mod |= M_STATIC; + } + } + + if (outerClass != null && outerClass.isInterface()) { + // Rule 3a. + // For interface members, neither 'private' nor 'protected' + // are legal modifiers. We avoid setting M_PUBLIC in some + // cases in order to avoid interfering with error detection + // and reporting. This is patched up, after reporting an + // error, by 'SourceClass.addMember'. + if ((mod & (M_PRIVATE | M_PROTECTED)) == 0) + mod |= M_PUBLIC; + // Rule 3b. + mod |= M_STATIC; + } + + // For nested classes, we must transform 'protected' to 'public' + // and 'private' to package scope. This must be done later, + // because any modifiers set here will be copied into the + // 'MemberDefinition' for the nested class, which must represent + // the original untransformed modifiers. Also, compile-time + // checks should be performed against the actual, untransformed + // modifiers. This is in contrast to transformations that implement + // implicit modifiers, such as M_STATIC and M_FINAL for fields + // of interfaces. + + sourceClass = (SourceClass) + toplevelEnv.makeClassDefinition(toplevelEnv, where, t, + doc, mod, sup, + interfaces, outerClass); + + sourceClass.getClassDeclaration().setDefinition(sourceClass, CS_PARSED); + env = new Environment(toplevelEnv, sourceClass); + + if (tracing) toplevelEnv.dtEvent("beginClass: SETTING UP DEPENDENCIES"); + + // The code which adds artificial dependencies between + // classes in the same source file has been moved to + // BatchEnvironment#parseFile(). + + if (tracing) toplevelEnv.dtEvent("beginClass: ADDING TO CLASS LIST"); + + classes.addElement(sourceClass); + + if (tracing) toplevelEnv.dtExit("beginClass: " + sourceClass); + + return sourceClass; + } + + /** + * Report the current class under construction. + */ + public ClassDefinition getCurrentClass() { + return sourceClass; + } + + /** + * End class + */ + public void endClass(long where, ClassDefinition c) { + + if (tracing) toplevelEnv.dtEnter("endClass: " + sourceClass); + + // c == sourceClass; don't bother to check + sourceClass.setEndPosition(where); + SourceClass outerClass = (SourceClass) sourceClass.getOuterClass(); + sourceClass = outerClass; + env = toplevelEnv; + if (sourceClass != null) + env = new Environment(env, sourceClass); + + if (tracing) toplevelEnv.dtExit("endClass: " + sourceClass); + } + + /** + * Define a method + */ + public void defineField(long where, ClassDefinition c, + String doc, int mod, Type t, + IdentifierToken name, IdentifierToken args[], + IdentifierToken exp[], Node val) { + // c == sourceClass; don't bother to check + Identifier nm = name.getName(); + // Members that are nested classes are not created with 'defineField', + // so these transformations do not apply to them. See 'beginClass' above. + if (sourceClass.isInterface()) { + // Members of interfaces are implicitly public. + if ((mod & (M_PRIVATE | M_PROTECTED)) == 0) + // For interface members, neither 'private' nor 'protected' + // are legal modifiers. Avoid setting M_PUBLIC in some cases + // to avoid interfering with later error detection. This will + // be fixed up after the error is reported. + mod |= M_PUBLIC; + // Methods of interfaces are implicitly abstract. + // Fields of interfaces are implicitly static and final. + if (t.isType(TC_METHOD)) { + mod |= M_ABSTRACT; + } else { + mod |= M_STATIC | M_FINAL; + } + } + if (nm.equals(idInit)) { + // The parser reports "idInit" when in reality it has found + // that there is no method name at all present. + // So, decide if it's really a constructor, or a syntax error. + Type rt = t.getReturnType(); + Identifier retname = !rt.isType(TC_CLASS) ? idStar /*no match*/ + : rt.getClassName(); + Identifier clsname = sourceClass.getLocalName(); + if (clsname.equals(retname)) { + t = Type.tMethod(Type.tVoid, t.getArgumentTypes()); + } else if (clsname.equals(retname.getFlatName().getName())) { + // It appears to be a constructor with spurious qualification. + t = Type.tMethod(Type.tVoid, t.getArgumentTypes()); + env.error(where, "invalid.method.decl.qual"); + } else if (retname.isQualified() || retname.equals(idStar)) { + // It appears to be a type name with no method name. + env.error(where, "invalid.method.decl.name"); + return; + } else { + // We assume the type name is missing, even though the + // simple name that's present might have been intended + // to be a type: "String (){}" vs. "toString(){}". + env.error(where, "invalid.method.decl"); + return; + } + } + + if (args == null && t.isType(TC_METHOD)) { + args = new IdentifierToken[0]; + } + + if (exp == null && t.isType(TC_METHOD)) { + exp = new IdentifierToken[0]; + } + + MemberDefinition f = env.makeMemberDefinition(env, where, sourceClass, + doc, mod, t, nm, + args, exp, val); + if (env.dump()) { + f.print(System.out); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/CompilerMember.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/CompilerMember.java new file mode 100644 index 000000000..58115f9d3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/CompilerMember.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * This class is used to represents fields while they are + * being compiled + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +final +class CompilerMember implements Comparable { + MemberDefinition field; + Assembler asm; + Object value; + String name; + String sig; + String key; + + CompilerMember(MemberDefinition field, Assembler asm) { + this.field = field; + this.asm = asm; + name = field.getName().toString(); + sig = field.getType().getTypeSignature(); + } + + public int compareTo(Object o) { + CompilerMember cm = (CompilerMember) o; + return getKey().compareTo(cm.getKey()); + } + + String getKey() { + if (key==null) + key = name+sig; + return key; + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/ErrorConsumer.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/ErrorConsumer.java new file mode 100644 index 000000000..f093eaa2f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/ErrorConsumer.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +/** + * Allows for easier parsing of errors and warnings from the compiler + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +public +interface ErrorConsumer { + public void pushError(String errorFileName, + int line, + String message, + String referenceText, String referenceTextPointer); +}; diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/ErrorMessage.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/ErrorMessage.java new file mode 100644 index 000000000..fd48482a4 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/ErrorMessage.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +/** + * A sorted list of error messages + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +final +class ErrorMessage { + long where; + String message; + ErrorMessage next; + + /** + * Constructor + */ + ErrorMessage(long where, String message) { + this.where = where; + this.message = message; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/Main.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/Main.java new file mode 100644 index 000000000..48ccb3076 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/Main.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import org.glassfish.rmic.tools.java.*; +// JCOV +// end JCOV + +import java.util.*; +import java.text.MessageFormat; + +/** + * Main program of the Java compiler + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @deprecated As of J2SE 1.3, the preferred way to compile Java + * language sources is by using the new compiler, + * com.org.glassfish.rmic.tools.javac.Main. + */ +@Deprecated +public +class Main implements Constants { + + private static ResourceBundle messageRB; + + /** + * Initialize ResourceBundle + */ + private static void initResource() { + try { + messageRB = + ResourceBundle.getBundle("org.glassfish.rmic.tools.javac.resources.javac"); + } catch (MissingResourceException e) { + throw new Error("Fatal: Resource for javac is missing"); + } + } + + public static String getText(String key, String fixed) { + return getText(key, fixed, null); + } + + static String getText(String key, String fixed1, String fixed2) { + return getText(key, fixed1, fixed2, null); + } + + static String getText(String key, String fixed1, + String fixed2, String fixed3) { + if (messageRB == null) { + initResource(); + } + try { + String message = messageRB.getString(key); + return MessageFormat.format(message, fixed1, fixed2, fixed3); + } catch (MissingResourceException e) { + if (fixed1 == null) fixed1 = "null"; + if (fixed2 == null) fixed2 = "null"; + if (fixed3 == null) fixed3 = "null"; + String message = "JAVAC MESSAGE FILE IS BROKEN: key={0}, arguments={1}, {2}, {3}"; + return MessageFormat.format(message, key, fixed1, fixed2, fixed3); + } + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/SourceClass.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/SourceClass.java new file mode 100644 index 000000000..8fc7c2624 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/SourceClass.java @@ -0,0 +1,2658 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.tree.*; +import org.glassfish.rmic.tools.tree.CompoundStatement; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.ConstantPool; +import java.util.Vector; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Iterator; +import java.io.IOException; +import java.io.OutputStream; +import java.io.DataOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; + +/** + * This class represents an Java class as it is read from + * an Java source file. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +public +class SourceClass extends ClassDefinition { + + /** + * The toplevel environment, shared with the parser + */ + Environment toplevelEnv; + + /** + * The default constructor + */ + SourceMember defConstructor; + + /** + * The constant pool + */ + ConstantPool tab = new ConstantPool(); + + /** + * The list of class dependencies + */ + Hashtable deps = new Hashtable<>(11); + + /** + * The field used to represent "this" in all of my code. + */ + LocalMember thisArg; + + /** + * Last token of class, as reported by parser. + */ + long endPosition; + + /** + * Access methods for constructors are distinguished from + * the constructors themselves by a dummy first argument. + * A unique type used for this purpose and shared by all + * constructor access methods within a package-member class is + * maintained here. + *

                + * This field is null except in an outermost class containing + * one or more classes needing such an access method. + */ + private Type dummyArgumentType = null; + + /** + * Constructor + */ + public SourceClass(Environment env, long where, + ClassDeclaration declaration, String documentation, + int modifiers, IdentifierToken superClass, + IdentifierToken interfaces[], + SourceClass outerClass, Identifier localName) { + super(env.getSource(), where, + declaration, modifiers, superClass, interfaces); + setOuterClass(outerClass); + + this.toplevelEnv = env; + this.documentation = documentation; + + if (ClassDefinition.containsDeprecated(documentation)) { + this.modifiers |= M_DEPRECATED; + } + + // Check for a package level class which is declared static. + if (isStatic() && outerClass == null) { + env.error(where, "static.class", this); + this.modifiers &=~ M_STATIC; + } + + // Inner classes cannot be static, nor can they be interfaces + // (which are implicitly static). Static classes and interfaces + // can only occur as top-level entities. + // + // Note that we do not have to check for local classes declared + // to be static (this is currently caught by the parser) but + // we check anyway in case the parser is modified to allow this. + if (isLocal() || (outerClass != null && !outerClass.isTopLevel())) { + if (isInterface()) { + env.error(where, "inner.interface"); + } else if (isStatic()) { + env.error(where, "static.inner.class", this); + this.modifiers &=~ M_STATIC; + if (innerClassMember != null) { + innerClassMember.subModifiers(M_STATIC); + } + } + } + + if (isPrivate() && outerClass == null) { + env.error(where, "private.class", this); + this.modifiers &=~ M_PRIVATE; + } + if (isProtected() && outerClass == null) { + env.error(where, "protected.class", this); + this.modifiers &=~ M_PROTECTED; + } + /*----* + if ((isPublic() || isProtected()) && isInsideLocal()) { + env.error(where, "warn.public.local.class", this); + } + *----*/ + + // maybe define an uplevel "A.this" current instance field + if (!isTopLevel() && !isLocal()) { + LocalMember outerArg = outerClass.getThisArgument(); + UplevelReference r = getReference(outerArg); + setOuterMember(r.getLocalField(env)); + } + + // Set simple, unmangled local name for a local or anonymous class. + // NOTE: It would be OK to do this unconditionally, as null is the + // correct value for a member (non-local) class. + if (localName != null) + setLocalName(localName); + + // Check for inner class with same simple name as one of + // its enclosing classes. Note that 'getLocalName' returns + // the simple, unmangled source-level name of any class. + // The previous version of this code was not careful to avoid + // mangled local class names. This version fixes 4047746. + Identifier thisName = getLocalName(); + if (thisName != idNull) { + // Test above suppresses error for nested anonymous classes, + // which have an internal "name", but are not named in source code. + for (ClassDefinition scope = outerClass; scope != null; + scope = scope.getOuterClass()) { + Identifier outerName = scope.getLocalName(); + if (thisName.equals(outerName)) + env.error(where, "inner.redefined", thisName); + } + } + } + + /** + * Return last position in this class. + * @see #getWhere + */ + public long getEndPosition() { + return endPosition; + } + + public void setEndPosition(long endPosition) { + this.endPosition = endPosition; + } + + +// JCOV + /** + * Return absolute name of source file + */ + public String getAbsoluteName() { + String AbsName = ((ClassFile)getSource()).getAbsoluteName(); + + return AbsName; + } +//end JCOV + + /** + * Return imports + */ + public Imports getImports() { + return toplevelEnv.getImports(); + } + + /** + * Find or create my "this" argument, which is used for all methods. + */ + public LocalMember getThisArgument() { + if (thisArg == null) { + thisArg = new LocalMember(where, this, 0, getType(), idThis); + } + return thisArg; + } + + /** + * Add a dependency + */ + public void addDependency(ClassDeclaration c) { + if (tab != null) { + tab.put(c); + } + // If doing -xdepend option, save away list of class dependencies + // making sure to NOT include duplicates or the class we are in + // (Hashtable's put() makes sure we don't have duplicates) + if ( toplevelEnv.print_dependencies() && c != getClassDeclaration() ) { + deps.put(c,c); + } + } + + /** + * Add a field (check it first) + */ + public void addMember(Environment env, MemberDefinition f) { + // Make sure the access permissions are self-consistent: + switch (f.getModifiers() & (M_PUBLIC | M_PRIVATE | M_PROTECTED)) { + case M_PUBLIC: + case M_PRIVATE: + case M_PROTECTED: + case 0: + break; + default: + env.error(f.getWhere(), "inconsistent.modifier", f); + // Cut out the more restrictive modifier(s): + if (f.isPublic()) { + f.subModifiers(M_PRIVATE | M_PROTECTED); + } else { + f.subModifiers(M_PRIVATE); + } + break; + } + + // Note exemption for synthetic members below. + if (f.isStatic() && !isTopLevel() && !f.isSynthetic()) { + if (f.isMethod()) { + env.error(f.getWhere(), "static.inner.method", f, this); + f.subModifiers(M_STATIC); + } else if (f.isVariable()) { + if (!f.isFinal() || f.isBlankFinal()) { + env.error(f.getWhere(), "static.inner.field", f.getName(), this); + f.subModifiers(M_STATIC); + } + // Even if a static passes this test, there is still another + // check in 'SourceMember.check'. The check is delayed so + // that the initializer may be inspected more closely, using + // 'isConstant()'. Part of fix for 4095568. + } else { + // Static inner classes are diagnosed in 'SourceClass.'. + f.subModifiers(M_STATIC); + } + } + + if (f.isMethod()) { + if (f.isConstructor()) { + if (f.getClassDefinition().isInterface()) { + env.error(f.getWhere(), "intf.constructor"); + return; + } + if (f.isNative() || f.isAbstract() || + f.isStatic() || f.isSynchronized() || f.isFinal()) { + env.error(f.getWhere(), "constr.modifier", f); + f.subModifiers(M_NATIVE | M_ABSTRACT | + M_STATIC | M_SYNCHRONIZED | M_FINAL); + } + } else if (f.isInitializer()) { + if (f.getClassDefinition().isInterface()) { + env.error(f.getWhere(), "intf.initializer"); + return; + } + } + + // f is not allowed to return an array of void + if ((f.getType().getReturnType()).isVoidArray()) { + env.error(f.getWhere(), "void.array"); + } + + if (f.getClassDefinition().isInterface() && + (f.isStatic() || f.isSynchronized() || f.isNative() + || f.isFinal() || f.isPrivate() || f.isProtected())) { + env.error(f.getWhere(), "intf.modifier.method", f); + f.subModifiers(M_STATIC | M_SYNCHRONIZED | M_NATIVE | + M_FINAL | M_PRIVATE); + } + if (f.isTransient()) { + env.error(f.getWhere(), "transient.meth", f); + f.subModifiers(M_TRANSIENT); + } + if (f.isVolatile()) { + env.error(f.getWhere(), "volatile.meth", f); + f.subModifiers(M_VOLATILE); + } + if (f.isAbstract()) { + if (f.isPrivate()) { + env.error(f.getWhere(), "abstract.private.modifier", f); + f.subModifiers(M_PRIVATE); + } + if (f.isStatic()) { + env.error(f.getWhere(), "abstract.static.modifier", f); + f.subModifiers(M_STATIC); + } + if (f.isFinal()) { + env.error(f.getWhere(), "abstract.final.modifier", f); + f.subModifiers(M_FINAL); + } + if (f.isNative()) { + env.error(f.getWhere(), "abstract.native.modifier", f); + f.subModifiers(M_NATIVE); + } + if (f.isSynchronized()) { + env.error(f.getWhere(),"abstract.synchronized.modifier",f); + f.subModifiers(M_SYNCHRONIZED); + } + } + if (f.isAbstract() || f.isNative()) { + if (f.getValue() != null) { + env.error(f.getWhere(), "invalid.meth.body", f); + f.setValue(null); + } + } else { + if (f.getValue() == null) { + if (f.isConstructor()) { + env.error(f.getWhere(), "no.constructor.body", f); + } else { + env.error(f.getWhere(), "no.meth.body", f); + } + f.addModifiers(M_ABSTRACT); + } + } + Vector arguments = f.getArguments(); + if (arguments != null) { + // arguments can be null if this is an implicit abstract method + int argumentLength = arguments.size(); + Type argTypes[] = f.getType().getArgumentTypes(); + for (int i = 0; i < argTypes.length; i++) { + Object arg = arguments.elementAt(i); + long where = f.getWhere(); + if (arg instanceof MemberDefinition) { + where = ((MemberDefinition)arg).getWhere(); + arg = ((MemberDefinition)arg).getName(); + } + // (arg should be an Identifier now) + if (argTypes[i].isType(TC_VOID) + || argTypes[i].isVoidArray()) { + env.error(where, "void.argument", arg); + } + } + } + } else if (f.isInnerClass()) { + if (f.isVolatile() || + f.isTransient() || f.isNative() || f.isSynchronized()) { + env.error(f.getWhere(), "inner.modifier", f); + f.subModifiers(M_VOLATILE | M_TRANSIENT | + M_NATIVE | M_SYNCHRONIZED); + } + // same check as for fields, below: + if (f.getClassDefinition().isInterface() && + (f.isPrivate() || f.isProtected())) { + env.error(f.getWhere(), "intf.modifier.field", f); + f.subModifiers(M_PRIVATE | M_PROTECTED); + f.addModifiers(M_PUBLIC); + // Fix up the class itself to agree with + // the inner-class member. + ClassDefinition c = f.getInnerClass(); + c.subModifiers(M_PRIVATE | M_PROTECTED); + c.addModifiers(M_PUBLIC); + } + } else { + if (f.getType().isType(TC_VOID) || f.getType().isVoidArray()) { + env.error(f.getWhere(), "void.inst.var", f.getName()); + // REMIND: set type to error + return; + } + + if (f.isSynchronized() || f.isAbstract() || f.isNative()) { + env.error(f.getWhere(), "var.modifier", f); + f.subModifiers(M_SYNCHRONIZED | M_ABSTRACT | M_NATIVE); + } + if (f.isStrict()) { + env.error(f.getWhere(), "var.floatmodifier", f); + f.subModifiers(M_STRICTFP); + } + if (f.isTransient() && isInterface()) { + env.error(f.getWhere(), "transient.modifier", f); + f.subModifiers(M_TRANSIENT); + } + if (f.isVolatile() && (isInterface() || f.isFinal())) { + env.error(f.getWhere(), "volatile.modifier", f); + f.subModifiers(M_VOLATILE); + } + if (f.isFinal() && (f.getValue() == null) && isInterface()) { + env.error(f.getWhere(), "initializer.needed", f); + f.subModifiers(M_FINAL); + } + + if (f.getClassDefinition().isInterface() && + (f.isPrivate() || f.isProtected())) { + env.error(f.getWhere(), "intf.modifier.field", f); + f.subModifiers(M_PRIVATE | M_PROTECTED); + f.addModifiers(M_PUBLIC); + } + } + // Do not check for repeated methods here: Types are not yet resolved. + if (!f.isInitializer()) { + for (MemberDefinition f2 = getFirstMatch(f.getName()); + f2 != null; f2 = f2.getNextMatch()) { + if (f.isVariable() && f2.isVariable()) { + env.error(f.getWhere(), "var.multidef", f, f2); + return; + } else if (f.isInnerClass() && f2.isInnerClass() && + !f.getInnerClass().isLocal() && + !f2.getInnerClass().isLocal()) { + // Found a duplicate inner-class member. + // Duplicate local classes are detected in + // 'VarDeclarationStatement.checkDeclaration'. + env.error(f.getWhere(), "inner.class.multidef", f); + return; + } + } + } + + super.addMember(env, f); + } + + /** + * Create an environment suitable for checking this class. + * Make sure the source and imports are set right. + * Make sure the environment contains no context information. + * (Actually, throw away env altogether and use toplevelEnv instead.) + */ + public Environment setupEnv(Environment env) { + // In some cases, we go to some trouble to create the 'env' argument + // that is discarded. We should remove the 'env' argument entirely + // as well as the vestigial code that supports it. See comments on + // 'newEnvironment' in 'checkInternal' below. + return new Environment(toplevelEnv, this); + } + + /** + * A source class never reports deprecation, since the compiler + * allows access to deprecated features that are being compiled + * in the same job. + */ + public boolean reportDeprecated(Environment env) { + return false; + } + + /** + * See if the source file of this class is right. + * @see ClassDefinition#noteUsedBy + */ + public void noteUsedBy(ClassDefinition ref, long where, Environment env) { + // If this class is not public, watch for cross-file references. + super.noteUsedBy(ref, where, env); + ClassDefinition def = this; + while (def.isInnerClass()) { + def = def.getOuterClass(); + } + if (def.isPublic()) { + return; // already checked + } + while (ref.isInnerClass()) { + ref = ref.getOuterClass(); + } + if (def.getSource().equals(ref.getSource())) { + return; // intra-file reference + } + ((SourceClass)def).checkSourceFile(env, where); + } + + /** + * Check this class and all its fields. + */ + public void check(Environment env) throws ClassNotFound { + if (tracing) env.dtEnter("SourceClass.check: " + getName()); + if (isInsideLocal()) { + // An inaccessible class gets checked when the surrounding + // block is checked. + // QUERY: Should this case ever occur? + // What would invoke checking of a local class aside from + // checking the surrounding method body? + if (tracing) env.dtEvent("SourceClass.check: INSIDE LOCAL " + + getOuterClass().getName()); + getOuterClass().check(env); + } else { + if (isInnerClass()) { + if (tracing) env.dtEvent("SourceClass.check: INNER CLASS " + + getOuterClass().getName()); + // Make sure the outer is checked first. + ((SourceClass)getOuterClass()).maybeCheck(env); + } + Vset vset = new Vset(); + Context ctx = null; + if (tracing) + env.dtEvent("SourceClass.check: CHECK INTERNAL " + getName()); + vset = checkInternal(setupEnv(env), ctx, vset); + // drop vset here + } + if (tracing) env.dtExit("SourceClass.check: " + getName()); + } + + private void maybeCheck(Environment env) throws ClassNotFound { + if (tracing) env.dtEvent("SourceClass.maybeCheck: " + getName()); + // Check this class now, if it has not yet been checked. + // Cf. Main.compile(). Perhaps this code belongs there somehow. + ClassDeclaration c = getClassDeclaration(); + if (c.getStatus() == CS_PARSED) { + // Set it first to avoid vicious circularity: + c.setDefinition(this, CS_CHECKED); + check(env); + } + } + + private Vset checkInternal(Environment env, Context ctx, Vset vset) + throws ClassNotFound { + Identifier nm = getClassDeclaration().getName(); + if (env.verbose()) { + env.output("[checking class " + nm + "]"); + } + + // Save context enclosing class for later access + // by 'ClassDefinition.resolveName.' + classContext = ctx; + + // At present, the call to 'newEnvironment' is not needed. + // The incoming environment to 'basicCheck' is always passed to + // 'setupEnv', which discards it completely. This is also the + // only call to 'newEnvironment', which is now apparently dead code. + basicCheck(Context.newEnvironment(env, ctx)); + + // Validate access for all inner-class components + // of a qualified name, not just the last one, which + // is checked below. Yes, this is a dirty hack... + // Much of this code was cribbed from 'checkSupers'. + // Part of fix for 4094658. + ClassDeclaration sup = getSuperClass(); + if (sup != null) { + long where = getWhere(); + where = IdentifierToken.getWhere(superClassId, where); + env.resolveExtendsByName(where, this, sup.getName()); + } + for (int i = 0 ; i < interfaces.length ; i++) { + ClassDeclaration intf = interfaces[i]; + long where = getWhere(); + // Error localization fails here if interfaces were + // elided during error recovery from an invalid one. + if (interfaceIds != null + && interfaceIds.length == interfaces.length) { + where = IdentifierToken.getWhere(interfaceIds[i], where); + } + env.resolveExtendsByName(where, this, intf.getName()); + } + + // Does the name already exist in an imported package? + // See JLS 8.1 for the precise rules. + if (!isInnerClass() && !isInsideLocal()) { + // Discard package qualification for the import checks. + Identifier simpleName = nm.getName(); + try { + // We want this to throw a ClassNotFound exception + Imports imports = toplevelEnv.getImports(); + Identifier ID = imports.resolve(env, simpleName); + if (ID != getName()) + env.error(where, "class.multidef.import", simpleName, ID); + } catch (AmbiguousClass e) { + // At least one of e.name1 and e.name2 must be different + Identifier ID = (e.name1 != getName()) ? e.name1 : e.name2; + env.error(where, "class.multidef.import", simpleName, ID); + } catch (ClassNotFound e) { + // we want this to happen + } + + // Make sure that no package with the same fully qualified + // name exists. This is required by JLS 7.1. We only need + // to perform this check for top level classes -- it isn't + // necessary for inner classes. (bug 4101529) + // + // This change has been backed out because, on WIN32, it + // failed to distinguish between java.awt.event and + // java.awt.Event when looking for a directory. We will + // add this back in later. + // + // try { + // if (env.getPackage(nm).exists()) { + // env.error(where, "class.package.conflict", nm); + // } + // } catch (java.io.IOException ee) { + // env.error(where, "io.exception.package", nm); + // } + + // Make sure it was defined in the right file + if (isPublic()) { + checkSourceFile(env, getWhere()); + } + } + + vset = checkMembers(env, ctx, vset); + return vset; + } + + private boolean sourceFileChecked = false; + + /** + * See if the source file of this class is of the right name. + */ + public void checkSourceFile(Environment env, long where) { + // one error per offending class is sufficient + if (sourceFileChecked) return; + sourceFileChecked = true; + + String fname = getName().getName() + ".java"; + String src = ((ClassFile)getSource()).getName(); + if (!src.equals(fname)) { + if (isPublic()) { + env.error(where, "public.class.file", this, fname); + } else { + env.error(where, "warn.package.class.file", this, src, fname); + } + } + } + + // Set true if superclass (but not necessarily superinterfaces) have + // been checked. If the superclass is still unresolved, then an error + // message should have been issued, and we assume that no further + // resolution is possible. + private boolean supersChecked = false; + + /** + * Overrides 'ClassDefinition.getSuperClass'. + */ + + public ClassDeclaration getSuperClass(Environment env) { + if (tracing) env.dtEnter("SourceClass.getSuperClass: " + this); + // Superclass may fail to be set because of error recovery, + // so resolve types here only if 'checkSupers' has not yet + // completed its checks on the superclass. + // QUERY: Can we eliminate the need to resolve superclasses on demand? + // See comments in 'checkSupers' and in 'ClassDefinition.getInnerClass'. + if (superClass == null && superClassId != null && !supersChecked) { + resolveTypeStructure(env); + // We used to report an error here if the superclass was not + // resolved. Having moved the call to 'checkSupers' from 'basicCheck' + // into 'resolveTypeStructure', the errors reported here should have + // already been reported. Furthermore, error recovery can null out + // the superclass, which would cause a spurious error from the test here. + } + if (tracing) env.dtExit("SourceClass.getSuperClass: " + this); + return superClass; + } + + /** + * Check that all superclasses and superinterfaces are defined and + * well formed. Among other checks, verify that the inheritance + * graph is acyclic. Called from 'resolveTypeStructure'. + */ + + private void checkSupers(Environment env) throws ClassNotFound { + + // *** DEBUG *** + supersCheckStarted = true; + + if (tracing) env.dtEnter("SourceClass.checkSupers: " + this); + + if (isInterface()) { + if (isFinal()) { + Identifier nm = getClassDeclaration().getName(); + env.error(getWhere(), "final.intf", nm); + // Interfaces have no superclass. Superinterfaces + // are checked below, in code shared with the class case. + } + } else { + // Check superclass. + // Call to 'getSuperClass(env)' (note argument) attempts + // 'resolveTypeStructure' if superclass has not successfully + // been resolved. Since we have just now called 'resolveSupers' + // (see our call in 'resolveTypeStructure'), it is not clear + // that this can do any good. Why not 'getSuperClass()' here? + if (getSuperClass(env) != null) { + long where = getWhere(); + where = IdentifierToken.getWhere(superClassId, where); + try { + ClassDefinition def = + getSuperClass().getClassDefinition(env); + // Resolve superclass and its ancestors. + def.resolveTypeStructure(env); + // Access to the superclass should be checked relative + // to the surrounding context, not as if the reference + // appeared within the class body. Changed 'canAccess' + // to 'extendsCanAccess' to fix 4087314. + if (!extendsCanAccess(env, getSuperClass())) { + env.error(where, "cant.access.class", getSuperClass()); + // Might it be a better recovery to let the access go through? + superClass = null; + } else if (def.isFinal()) { + env.error(where, "super.is.final", getSuperClass()); + // Might it be a better recovery to let the access go through? + superClass = null; + } else if (def.isInterface()) { + env.error(where, "super.is.intf", getSuperClass()); + superClass = null; + } else if (superClassOf(env, getSuperClass())) { + env.error(where, "cyclic.super"); + superClass = null; + } else { + def.noteUsedBy(this, where, env); + } + if (superClass == null) { + def = null; + } else { + // If we have a valid superclass, check its + // supers as well, and so on up to root class. + // Call to 'enclosingClassOf' will raise + // 'NullPointerException' if 'def' is null, + // so omit this check as error recovery. + ClassDefinition sup = def; + for (;;) { + if (enclosingClassOf(sup)) { + // Do we need a similar test for + // interfaces? See bugid 4038529. + env.error(where, "super.is.inner"); + superClass = null; + break; + } + // Since we resolved the superclass and its + // ancestors above, we should not discover + // any unresolved classes on the superclass + // chain. It should thus be sufficient to + // call 'getSuperClass()' (no argument) here. + ClassDeclaration s = sup.getSuperClass(env); + if (s == null) { + // Superclass not resolved due to error. + break; + } + sup = s.getClassDefinition(env); + } + } + } catch (ClassNotFound e) { + // Error is detected in call to 'getClassDefinition'. + // The class may actually exist but be ambiguous. + // Call env.resolve(e.name) to see if it is. + // env.resolve(name) will definitely tell us if the + // class is ambiguous, but may not necessarily tell + // us if the class is not found. + // (part of solution for 4059855) + reportError: { + try { + env.resolve(e.name); + } catch (AmbiguousClass ee) { + env.error(where, + "ambig.class", ee.name1, ee.name2); + superClass = null; + break reportError; + } catch (ClassNotFound ee) { + // fall through + } + env.error(where, "super.not.found", e.name, this); + superClass = null; + } // The break exits this block + } + + } else { + // Superclass was null on entry, after call to + // 'resolveSupers'. This should normally not happen, + // as 'resolveSupers' sets 'superClass' to a non-null + // value for all named classes, except for one special + // case: 'java.lang.Object', which has no superclass. + if (isAnonymous()) { + // checker should have filled it in first + throw new CompilerError("anonymous super"); + } else if (!getName().equals(idJavaLangObject)) { + throw new CompilerError("unresolved super"); + } + } + } + + // At this point, if 'superClass' is null due to an error + // in the user program, a message should have been issued. + supersChecked = true; + + // Check interfaces + for (int i = 0 ; i < interfaces.length ; i++) { + ClassDeclaration intf = interfaces[i]; + long where = getWhere(); + if (interfaceIds != null + && interfaceIds.length == interfaces.length) { + where = IdentifierToken.getWhere(interfaceIds[i], where); + } + try { + ClassDefinition def = intf.getClassDefinition(env); + // Resolve superinterface and its ancestors. + def.resolveTypeStructure(env); + // Check superinterface access in the correct context. + // Changed 'canAccess' to 'extendsCanAccess' to fix 4087314. + if (!extendsCanAccess(env, intf)) { + env.error(where, "cant.access.class", intf); + } else if (!intf.getClassDefinition(env).isInterface()) { + env.error(where, "not.intf", intf); + } else if (isInterface() && implementedBy(env, intf)) { + env.error(where, "cyclic.intf", intf); + } else { + def.noteUsedBy(this, where, env); + // Interface is OK, leave it in the interface list. + continue; + } + } catch (ClassNotFound e) { + // The interface may actually exist but be ambiguous. + // Call env.resolve(e.name) to see if it is. + // env.resolve(name) will definitely tell us if the + // interface is ambiguous, but may not necessarily tell + // us if the interface is not found. + // (part of solution for 4059855) + reportError2: { + try { + env.resolve(e.name); + } catch (AmbiguousClass ee) { + env.error(where, + "ambig.class", ee.name1, ee.name2); + superClass = null; + break reportError2; + } catch (ClassNotFound ee) { + // fall through + } + env.error(where, "intf.not.found", e.name, this); + superClass = null; + } // The break exits this block + } + // Remove this interface from the list of interfaces + // as recovery from an error. + ClassDeclaration newInterfaces[] = + new ClassDeclaration[interfaces.length - 1]; + System.arraycopy(interfaces, 0, newInterfaces, 0, i); + System.arraycopy(interfaces, i + 1, newInterfaces, i, + newInterfaces.length - i); + interfaces = newInterfaces; + --i; + } + if (tracing) env.dtExit("SourceClass.checkSupers: " + this); + } + + /** + * Check all of the members of this class. + *

                + * Inner classes are checked in the following way. Any class which + * is immediately contained in a block (anonymous and local classes) + * is checked along with its containing method; see the + * SourceMember.check() method for more information. Member classes + * of this class are checked immediately after this class, unless this + * class is insideLocal(), in which case, they are checked with the + * rest of the members. + */ + private Vset checkMembers(Environment env, Context ctx, Vset vset) + throws ClassNotFound { + + // bail out if there were any errors + if (getError()) { + return vset; + } + + // Make sure that all of our member classes have been + // basicCheck'ed before we check the rest of our members. + // If our member classes haven't been basicCheck'ed, then they + // may not have methods. It is important that they + // have methods so we can process NewInstanceExpressions + // correctly. This problem didn't occur before 1.2beta1. + // This is a fix for bug 4082816. + for (MemberDefinition f = getFirstMember(); + f != null; f = f.getNextMember()) { + if (f.isInnerClass()) { + // System.out.println("Considering " + f + " in " + this); + SourceClass cdef = (SourceClass) f.getInnerClass(); + if (cdef.isMember()) { + cdef.basicCheck(env); + } + } + } + + if (isFinal() && isAbstract()) { + env.error(where, "final.abstract", this.getName().getName()); + } + + // This class should be abstract if there are any abstract methods + // in our parent classes and interfaces which we do not override. + // There are odd cases when, even though we cannot access some + // abstract method from our superclass, that abstract method can + // still force this class to be abstract. See the discussion in + // bug id 1240831. + if (!isInterface() && !isAbstract() && mustBeAbstract(env)) { + // Set the class abstract. + modifiers |= M_ABSTRACT; + + // Tell the user which methods force this class to be abstract. + + // First list all of the "unimplementable" abstract methods. + Iterator iter = getPermanentlyAbstractMethods(); + while (iter.hasNext()) { + MemberDefinition method = iter.next(); + // We couldn't override this method even if we + // wanted to. Try to make the error message + // as non-confusing as possible. + env.error(where, "abstract.class.cannot.override", + getClassDeclaration(), method, + method.getDefiningClassDeclaration()); + } + + // Now list all of the traditional abstract methods. + iter = getMethods(env); + while (iter.hasNext()) { + // For each method, check if it is abstract. If it is, + // output an appropriate error message. + MemberDefinition method = iter.next(); + if (method.isAbstract()) { + env.error(where, "abstract.class", + getClassDeclaration(), method, + method.getDefiningClassDeclaration()); + } + } + } + + // Check the instance variables in a pre-pass before any constructors. + // This lets constructors "in-line" any initializers directly. + // It also lets us do some definite assignment checks on variables. + Context ctxInit = new Context(ctx); + Vset vsInst = vset.copy(); + Vset vsClass = vset.copy(); + + // Do definite assignment checking on blank finals. + // Other variables do not need such checks. The simple textual + // ordering constraints implemented by MemberDefinition.canReach() + // are necessary and sufficient for the other variables. + // Note that within non-static code, all statics are always + // definitely assigned, and vice-versa. + for (MemberDefinition f = getFirstMember(); + f != null; f = f.getNextMember()) { + if (f.isVariable() && f.isBlankFinal()) { + // The following allocates a LocalMember object as a proxy + // to represent the field. + int number = ctxInit.declareFieldNumber(f); + if (f.isStatic()) { + vsClass = vsClass.addVarUnassigned(number); + vsInst = vsInst.addVar(number); + } else { + vsInst = vsInst.addVarUnassigned(number); + vsClass = vsClass.addVar(number); + } + } + } + + // For instance variable checks, use a context with a "this" parameter. + Context ctxInst = new Context(ctxInit, this); + LocalMember thisArg = getThisArgument(); + int thisNumber = ctxInst.declare(env, thisArg); + vsInst = vsInst.addVar(thisNumber); + + // Do all the initializers in order, checking the definite + // assignment of blank finals. Separate static from non-static. + for (MemberDefinition f = getFirstMember(); + f != null; f = f.getNextMember()) { + try { + if (f.isVariable() || f.isInitializer()) { + if (f.isStatic()) { + vsClass = f.check(env, ctxInit, vsClass); + } else { + vsInst = f.check(env, ctxInst, vsInst); + } + } + } catch (ClassNotFound ee) { + env.error(f.getWhere(), "class.not.found", ee.name, this); + } + } + + checkBlankFinals(env, ctxInit, vsClass, true); + + // Check the rest of the field definitions. + // (Note: Re-checking a field is a no-op.) + for (MemberDefinition f = getFirstMember(); + f != null; f = f.getNextMember()) { + try { + if (f.isConstructor()) { + // When checking a constructor, an explicit call to + // 'this(...)' makes all blank finals definitely assigned. + // See 'MethodExpression.checkValue'. + Vset vsCon = f.check(env, ctxInit, vsInst.copy()); + // May issue multiple messages for the same variable!! + checkBlankFinals(env, ctxInit, vsCon, false); + // (drop vsCon here) + } else { + Vset vsFld = f.check(env, ctx, vset.copy()); + // (drop vsFld here) + } + } catch (ClassNotFound ee) { + env.error(f.getWhere(), "class.not.found", ee.name, this); + } + } + + // Must mark class as checked before visiting inner classes, + // as they may in turn request checking of the current class + // as an outer class. Fix for bug id 4056774. + getClassDeclaration().setDefinition(this, CS_CHECKED); + + // Also check other classes in the same nest. + // All checking of this nest must be finished before any + // of its classes emit bytecode. + // Otherwise, the inner classes might not have a chance to + // add access or class literal fields to the outer class. + for (MemberDefinition f = getFirstMember(); + f != null; f = f.getNextMember()) { + if (f.isInnerClass()) { + SourceClass cdef = (SourceClass) f.getInnerClass(); + if (!cdef.isInsideLocal()) { + cdef.maybeCheck(env); + } + } + } + + // Note: Since inner classes cannot set up-level variables, + // the returned vset is always equal to the passed-in vset. + // Still, we'll return it for the sake of regularity. + return vset; + } + + /** Make sure all my blank finals exist now. */ + + private void checkBlankFinals(Environment env, Context ctxInit, Vset vset, + boolean isStatic) { + for (int i = 0; i < ctxInit.getVarNumber(); i++) { + if (!vset.testVar(i)) { + MemberDefinition ff = ctxInit.getElement(i); + if (ff != null && ff.isBlankFinal() + && ff.isStatic() == isStatic + && ff.getClassDefinition() == this) { + env.error(ff.getWhere(), + "final.var.not.initialized", ff.getName()); + } + } + } + } + + /** + * Check this class has its superclass and its interfaces. Also + * force it to have an method (if it doesn't already have one) + * and to have all the abstract methods of its parents. + */ + private boolean basicChecking = false; + private boolean basicCheckDone = false; + protected void basicCheck(Environment env) throws ClassNotFound { + + if (tracing) env.dtEnter("SourceClass.basicCheck: " + getName()); + + super.basicCheck(env); + + if (basicChecking || basicCheckDone) { + if (tracing) env.dtExit("SourceClass.basicCheck: OK " + getName()); + return; + } + + if (tracing) env.dtEvent("SourceClass.basicCheck: CHECKING " + getName()); + + basicChecking = true; + + env = setupEnv(env); + + Imports imports = env.getImports(); + if (imports != null) { + imports.resolve(env); + } + + resolveTypeStructure(env); + + // Check the existence of the superclass and all interfaces. + // Also responsible for breaking inheritance cycles. This call + // has been moved to 'resolveTypeStructure', just after the call + // to 'resolveSupers', as inheritance cycles must be broken before + // resolving types within the members. Fixes 4073739. + // checkSupers(env); + + if (!isInterface()) { + + // Add implicit method, if necessary. + // QUERY: What keeps us from adding an implicit constructor + // when the user explicitly declares one? Is it truly guaranteed + // that the declaration for such an explicit constructor will have + // been processed by the time we arrive here? In general, 'basicCheck' + // is called very early, prior to the normal member checking phase. + if (!hasConstructor()) { + Node code = new CompoundStatement(getWhere(), new Statement[0]); + Type t = Type.tMethod(Type.tVoid); + + // Default constructors inherit the access modifiers of their + // class. For non-inner classes, this follows from JLS 8.6.7, + // as the only possible modifier is 'public'. For the sake of + // robustness in the presence of errors, we ignore any other + // modifiers. For inner classes, the rule needs to be extended + // in some way to account for the possibility of private and + // protected classes. We make the 'obvious' extension, however, + // the inner classes spec is silent on this issue, and a definitive + // resolution is needed. See bugid 4087421. + // WORKAROUND: A private constructor might need an access method, + // but it is not possible to create one due to a restriction in + // the verifier. (This is a known problem -- see 4015397.) + // We therefore do not inherit the 'private' modifier from the class, + // allowing the default constructor to be package private. This + // workaround can be observed via reflection, but is otherwise + // undetectable, as the constructor is always accessible within + // the class in which its containing (private) class appears. + int accessModifiers = getModifiers() & + (isInnerClass() ? (M_PUBLIC | M_PROTECTED) : M_PUBLIC); + env.makeMemberDefinition(env, getWhere(), this, null, + accessModifiers, + t, idInit, null, null, code); + } + } + + // Only do the inheritance/override checks if they are turned on. + // The idea here is that they will be done in javac, but not + // in javadoc. See the comment for turnOffChecks(), above. + if (doInheritanceChecks) { + + // Verify the compatibility of all inherited method definitions + // by collecting all of our inheritable methods. + collectInheritedMethods(env); + } + + basicChecking = false; + basicCheckDone = true; + if (tracing) env.dtExit("SourceClass.basicCheck: " + getName()); + } + + /** + * Add a group of methods to this class as miranda methods. + * + * For a definition of Miranda methods, see the comment above the + * method addMirandaMethods() in the file + * org/glassfish/rmic/tools/java/ClassDeclaration.java + */ + protected void addMirandaMethods(Environment env, + Iterator mirandas) { + + while(mirandas.hasNext()) { + MemberDefinition method = mirandas.next(); + + addMember(method); + + //System.out.println("adding miranda method " + newMethod + + // " to " + this); + } + } + + /** + * After parsing is complete, resolve all names + * except those inside method bodies or initializers. + * In particular, this is the point at which we find out what + * kinds of variables and methods there are in the classes, + * and therefore what is each class's interface to the world. + *

                + * Also perform certain other transformations, such as inserting + * "this$C" arguments into constructors, and reorganizing structure + * to flatten qualified member names. + *

                + * Do not perform type-based or name-based consistency checks + * or normalizations (such as default nullary constructors), + * and do not attempt to compile code against this class, + * until after this phase. + */ + + private boolean resolving = false; + + public void resolveTypeStructure(Environment env) { + + if (tracing) + env.dtEnter("SourceClass.resolveTypeStructure: " + getName()); + + // Resolve immediately enclosing type, which in turn + // forces resolution of all enclosing type declarations. + ClassDefinition oc = getOuterClass(); + if (oc != null && oc instanceof SourceClass + && !((SourceClass)oc).resolved) { + // Do the outer class first, always. + ((SourceClass)oc).resolveTypeStructure(env); + // (Note: this.resolved is probably true at this point.) + } + + // Punt if we've already resolved this class, or are currently + // in the process of doing so. + if (resolved || resolving) { + if (tracing) + env.dtExit("SourceClass.resolveTypeStructure: OK " + getName()); + return; + } + + // Previously, 'resolved' was set here, and served to prevent + // duplicate resolutions here as well as its function in + // 'ClassDefinition.addMember'. Now, 'resolving' serves the + // former purpose, distinct from that of 'resolved'. + resolving = true; + + if (tracing) + env.dtEvent("SourceClass.resolveTypeStructure: RESOLVING " + getName()); + + env = setupEnv(env); + + // Resolve superclass names to class declarations + // for the immediate superclass and superinterfaces. + resolveSupers(env); + + // Check all ancestor superclasses for various + // errors, verifying definition of all superclasses + // and superinterfaces. Also breaks inheritance cycles. + // Calls 'resolveTypeStructure' recursively for ancestors + // This call used to appear in 'basicCheck', but was not + // performed early enough. Most of the compiler will barf + // on inheritance cycles! + try { + checkSupers(env); + } catch (ClassNotFound ee) { + // Undefined classes should be reported by 'checkSupers'. + env.error(where, "class.not.found", ee.name, this); + } + + for (MemberDefinition + f = getFirstMember() ; f != null ; f = f.getNextMember()) { + if (f instanceof SourceMember) + ((SourceMember)f).resolveTypeStructure(env); + } + + resolving = false; + + // Mark class as resolved. If new members are subsequently + // added to the class, they will be resolved at that time. + // See 'ClassDefinition.addMember'. Previously, this variable was + // set prior to the calls to 'checkSupers' and 'resolveTypeStructure' + // (which may engender further calls to 'checkSupers'). This could + // lead to duplicate resolution of implicit constructors, as the call to + // 'basicCheck' from 'checkSupers' could add the constructor while + // its class is marked resolved, and thus would resolve the constructor, + // believing it to be a "late addition". It would then be resolved + // redundantly during the normal traversal of the members, which + // immediately follows in the code above. + resolved = true; + + // Now we have enough information to detect method repeats. + for (MemberDefinition + f = getFirstMember() ; f != null ; f = f.getNextMember()) { + if (f.isInitializer()) continue; + if (!f.isMethod()) continue; + for (MemberDefinition f2 = f; (f2 = f2.getNextMatch()) != null; ) { + if (!f2.isMethod()) continue; + if (f.getType().equals(f2.getType())) { + env.error(f.getWhere(), "meth.multidef", f); + continue; + } + if (f.getType().equalArguments(f2.getType())) { + env.error(f.getWhere(), "meth.redef.rettype", f, f2); + continue; + } + } + } + if (tracing) + env.dtExit("SourceClass.resolveTypeStructure: " + getName()); + } + + protected void resolveSupers(Environment env) { + if (tracing) + env.dtEnter("SourceClass.resolveSupers: " + this); + // Find the super class + if (superClassId != null && superClass == null) { + superClass = resolveSuper(env, superClassId); + // Special-case java.lang.Object here (not in the parser). + // In all other cases, if we have a valid 'superClassId', + // we return with a valid and non-null 'superClass' value. + if (superClass == getClassDeclaration() + && getName().equals(idJavaLangObject)) { + superClass = null; + superClassId = null; + } + } + // Find interfaces + if (interfaceIds != null && interfaces == null) { + interfaces = new ClassDeclaration[interfaceIds.length]; + for (int i = 0 ; i < interfaces.length ; i++) { + interfaces[i] = resolveSuper(env, interfaceIds[i]); + for (int j = 0; j < i; j++) { + if (interfaces[i] == interfaces[j]) { + Identifier id = interfaceIds[i].getName(); + long where = interfaceIds[j].getWhere(); + env.error(where, "intf.repeated", id); + } + } + } + } + if (tracing) + env.dtExit("SourceClass.resolveSupers: " + this); + } + + private ClassDeclaration resolveSuper(Environment env, IdentifierToken t) { + Identifier name = t.getName(); + if (tracing) + env.dtEnter("SourceClass.resolveSuper: " + name); + if (isInnerClass()) + name = outerClass.resolveName(env, name); + else + name = env.resolveName(name); + ClassDeclaration result = env.getClassDeclaration(name); + // Result is never null, as a new 'ClassDeclaration' is + // created if one with the given name does not exist. + if (tracing) env.dtExit("SourceClass.resolveSuper: " + name); + return result; + } + + /** + * During the type-checking of an outer method body or initializer, + * this routine is called to check a local class body + * in the proper context. + * @param sup the named super class or interface (if anonymous) + * @param args the actual arguments (if anonymous) + */ + public Vset checkLocalClass(Environment env, Context ctx, Vset vset, + ClassDefinition sup, + Expression args[], Type argTypes[] + ) throws ClassNotFound { + env = setupEnv(env); + + if ((sup != null) != isAnonymous()) { + throw new CompilerError("resolveAnonymousStructure"); + } + if (isAnonymous()) { + resolveAnonymousStructure(env, sup, args, argTypes); + } + + // Run the checks in the lexical context from the outer class. + vset = checkInternal(env, ctx, vset); + + // This is now done by 'checkInternal' via its call to 'checkMembers'. + // getClassDeclaration().setDefinition(this, CS_CHECKED); + + return vset; + } + + /** + * As with checkLocalClass, run the inline phase for a local class. + */ + public void inlineLocalClass(Environment env) { + for (MemberDefinition + f = getFirstMember(); f != null; f = f.getNextMember()) { + if ((f.isVariable() || f.isInitializer()) && !f.isStatic()) { + continue; // inlined inside of constructors only + } + try { + ((SourceMember)f).inline(env); + } catch (ClassNotFound ee) { + env.error(f.getWhere(), "class.not.found", ee.name, this); + } + } + if (getReferencesFrozen() != null && !inlinedLocalClass) { + inlinedLocalClass = true; + // add more constructor arguments for uplevel references + for (MemberDefinition + f = getFirstMember(); f != null; f = f.getNextMember()) { + if (f.isConstructor()) { + //((SourceMember)f).addUplevelArguments(false); + ((SourceMember)f).addUplevelArguments(); + } + } + } + } + private boolean inlinedLocalClass = false; + + /** + * Check a class which is inside a local class, but is not itself local. + */ + public Vset checkInsideClass(Environment env, Context ctx, Vset vset) + throws ClassNotFound { + if (!isInsideLocal() || isLocal()) { + throw new CompilerError("checkInsideClass"); + } + return checkInternal(env, ctx, vset); + } + + /** + * Just before checking an anonymous class, decide its true + * inheritance, and build its (sole, implicit) constructor. + */ + private void resolveAnonymousStructure(Environment env, + ClassDefinition sup, + Expression args[], Type argTypes[] + ) throws ClassNotFound { + + if (tracing) env.dtEvent("SourceClass.resolveAnonymousStructure: " + + this + ", super " + sup); + + // Decide now on the superclass. + + // This check has been removed as part of the fix for 4055017. + // In the anonymous class created to hold the 'class$' method + // of an interface, 'superClassId' refers to 'java.lang.Object'. + /*---------------------* + if (!(superClass == null && superClassId.getName() == idNull)) { + throw new CompilerError("superclass "+superClass); + } + *---------------------*/ + + if (sup.isInterface()) { + // allow an interface in the "super class" position + int ni = (interfaces == null) ? 0 : interfaces.length; + ClassDeclaration i1[] = new ClassDeclaration[1+ni]; + if (ni > 0) { + System.arraycopy(interfaces, 0, i1, 1, ni); + if (interfaceIds != null && interfaceIds.length == ni) { + IdentifierToken id1[] = new IdentifierToken[1+ni]; + System.arraycopy(interfaceIds, 0, id1, 1, ni); + id1[0] = new IdentifierToken(sup.getName()); + } + } + i1[0] = sup.getClassDeclaration(); + interfaces = i1; + + sup = toplevelEnv.getClassDefinition(idJavaLangObject); + } + superClass = sup.getClassDeclaration(); + + if (hasConstructor()) { + throw new CompilerError("anonymous constructor"); + } + + // Synthesize an appropriate constructor. + Type t = Type.tMethod(Type.tVoid, argTypes); + IdentifierToken names[] = new IdentifierToken[argTypes.length]; + for (int i = 0; i < names.length; i++) { + names[i] = new IdentifierToken(args[i].getWhere(), + Identifier.lookup("$"+i)); + } + int outerArg = (sup.isTopLevel() || sup.isLocal()) ? 0 : 1; + Expression superArgs[] = new Expression[-outerArg + args.length]; + for (int i = outerArg ; i < args.length ; i++) { + superArgs[-outerArg + i] = new IdentifierExpression(names[i]); + } + long where = getWhere(); + Expression superExp; + if (outerArg == 0) { + superExp = new SuperExpression(where); + } else { + superExp = new SuperExpression(where, + new IdentifierExpression(names[0])); + } + Expression superCall = new MethodExpression(where, + superExp, idInit, + superArgs); + Statement body[] = { new ExpressionStatement(where, superCall) }; + Node code = new CompoundStatement(where, body); + int mod = M_SYNTHETIC; // ISSUE: make M_PRIVATE, with wrapper? + env.makeMemberDefinition(env, where, this, null, + mod, t, idInit, names, null, code); + } + + /** + * Convert class modifiers to a string for diagnostic purposes. + * Accepts modifiers applicable to inner classes and that appear + * in the InnerClasses attribute only, as well as those that may + * appear in the class modifier proper. + */ + + private static int classModifierBits[] = + { ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, + ACC_INTERFACE, ACC_ABSTRACT, ACC_SUPER, M_ANONYMOUS, M_LOCAL, + M_STRICTFP, ACC_STRICT}; + + private static String classModifierNames[] = + { "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "FINAL", + "INTERFACE", "ABSTRACT", "SUPER", "ANONYMOUS", "LOCAL", + "STRICTFP", "STRICT"}; + + static String classModifierString(int mods) { + String s = ""; + for (int i = 0; i < classModifierBits.length; i++) { + if ((mods & classModifierBits[i]) != 0) { + s = s + " " + classModifierNames[i]; + mods &= ~classModifierBits[i]; + } + } + if (mods != 0) { + s = s + " ILLEGAL:" + Integer.toHexString(mods); + } + return s; + } + + /** + * Find or create an access method for a private member, + * or return null if this is not possible. + */ + public MemberDefinition getAccessMember(Environment env, Context ctx, + MemberDefinition field, boolean isSuper) { + return getAccessMember(env, ctx, field, false, isSuper); + } + + public MemberDefinition getUpdateMember(Environment env, Context ctx, + MemberDefinition field, boolean isSuper) { + if (!field.isVariable()) { + throw new CompilerError("method"); + } + return getAccessMember(env, ctx, field, true, isSuper); + } + + private MemberDefinition getAccessMember(Environment env, Context ctx, + MemberDefinition field, + boolean isUpdate, + boolean isSuper) { + + // The 'isSuper' argument is really only meaningful when the + // target member is a method, in which case an 'invokespecial' + // is needed. For fields, 'getfield' and 'putfield' instructions + // are generated in either case, and 'isSuper' currently plays + // no essential role. Nonetheless, we maintain the distinction + // consistently for the time being. + + boolean isStatic = field.isStatic(); + boolean isMethod = field.isMethod(); + + // Find pre-existing access method. + // In the case of a field access method, we only look for the getter. + // A getter is always created whenever a setter is. + // QUERY: Why doesn't the 'MemberDefinition' object for the field + // itself just have fields for its getter and setter? + MemberDefinition af; + for (af = getFirstMember(); af != null; af = af.getNextMember()) { + if (af.getAccessMethodTarget() == field) { + if (isMethod && af.isSuperAccessMethod() == isSuper) { + break; + } + // Distinguish the getter and the setter by the number of + // arguments. + int nargs = af.getType().getArgumentTypes().length; + // This was (nargs == (isStatic ? 0 : 1) + (isUpdate ? 1 : 0)) + // in order to find a setter as well as a getter. This caused + // allocation of multiple getters. + if (nargs == (isStatic ? 0 : 1)) { + break; + } + } + } + + if (af != null) { + if (!isUpdate) { + return af; + } else { + MemberDefinition uf = af.getAccessUpdateMember(); + if (uf != null) { + return uf; + } + } + } else if (isUpdate) { + // must find or create the getter before creating the setter + af = getAccessMember(env, ctx, field, false, isSuper); + } + + // If we arrive here, we are creating a new access member. + + Identifier anm; + Type dummyType = null; + + if (field.isConstructor()) { + // For a constructor, we use the same name as for all + // constructors (""), but add a distinguishing + // argument of an otherwise unused "dummy" type. + anm = idInit; + // Get the dummy class, creating it if necessary. + SourceClass outerMostClass = (SourceClass)getTopClass(); + dummyType = outerMostClass.dummyArgumentType; + if (dummyType == null) { + // Create dummy class. + IdentifierToken sup = + new IdentifierToken(0, idJavaLangObject); + IdentifierToken interfaces[] = {}; + IdentifierToken t = new IdentifierToken(0, idNull); + int mod = M_ANONYMOUS | M_STATIC | M_SYNTHETIC; + // If an interface has a public inner class, the dummy class for + // the constructor must always be accessible. Fix for 4221648. + if (outerMostClass.isInterface()) { + mod |= M_PUBLIC; + } + ClassDefinition dummyClass = + toplevelEnv.makeClassDefinition(toplevelEnv, + 0, t, null, mod, + sup, interfaces, + outerMostClass); + // Check the class. + // It is likely that a full check is not really necessary, + // but it is essential that the class be marked as parsed. + dummyClass.getClassDeclaration().setDefinition(dummyClass, CS_PARSED); + Expression argsX[] = {}; + Type argTypesX[] = {}; + try { + ClassDefinition supcls = + toplevelEnv.getClassDefinition(idJavaLangObject); + dummyClass.checkLocalClass(toplevelEnv, null, + new Vset(), supcls, argsX, argTypesX); + } catch (ClassNotFound ee) {}; + // Get class type. + dummyType = dummyClass.getType(); + outerMostClass.dummyArgumentType = dummyType; + } + } else { + // Otherwise, we use the name "access$N", for the + // smallest value of N >= 0 yielding an unused name. + for (int i = 0; ; i++) { + anm = Identifier.lookup(prefixAccess + i); + if (getFirstMatch(anm) == null) { + break; + } + } + } + + Type argTypes[]; + Type t = field.getType(); + + if (isStatic) { + if (!isMethod) { + if (!isUpdate) { + Type at[] = { }; + argTypes = at; + t = Type.tMethod(t); // nullary getter + } else { + Type at[] = { t }; + argTypes = at; + t = Type.tMethod(Type.tVoid, argTypes); // unary setter + } + } else { + // Since constructors are never static, we don't + // have to worry about a dummy argument here. + argTypes = t.getArgumentTypes(); + } + } else { + // All access methods for non-static members get an explicit + // 'this' pointer as an extra argument, as the access methods + // themselves must be static. EXCEPTION: Access methods for + // constructors are non-static. + Type classType = this.getType(); + if (!isMethod) { + if (!isUpdate) { + Type at[] = { classType }; + argTypes = at; + t = Type.tMethod(t, argTypes); // nullary getter + } else { + Type at[] = { classType, t }; + argTypes = at; + t = Type.tMethod(Type.tVoid, argTypes); // unary setter + } + } else { + // Target is a method, possibly a constructor. + Type at[] = t.getArgumentTypes(); + int nargs = at.length; + if (field.isConstructor()) { + // Access method is a constructor. + // Requires a dummy argument. + MemberDefinition outerThisArg = + ((SourceMember)field).getOuterThisArg(); + if (outerThisArg != null) { + // Outer instance link must be the first argument. + // The following is a sanity check that will catch + // most cases in which in this requirement is violated. + if (at[0] != outerThisArg.getType()) { + throw new CompilerError("misplaced outer this"); + } + // Strip outer 'this' argument. + // It will be added back when the access method is checked. + argTypes = new Type[nargs]; + argTypes[0] = dummyType; + for (int i = 1; i < nargs; i++) { + argTypes[i] = at[i]; + } + } else { + // There is no outer instance. + argTypes = new Type[nargs+1]; + argTypes[0] = dummyType; + for (int i = 0; i < nargs; i++) { + argTypes[i+1] = at[i]; + } + } + } else { + // Access method is static. + // Requires an explicit 'this' argument. + argTypes = new Type[nargs+1]; + argTypes[0] = classType; + for (int i = 0; i < nargs; i++) { + argTypes[i+1] = at[i]; + } + } + t = Type.tMethod(t.getReturnType(), argTypes); + } + } + + int nlen = argTypes.length; + long where = field.getWhere(); + IdentifierToken names[] = new IdentifierToken[nlen]; + for (int i = 0; i < nlen; i++) { + names[i] = new IdentifierToken(where, Identifier.lookup("$"+i)); + } + + Expression access = null; + Expression thisArg = null; + Expression args[] = null; + + if (isStatic) { + args = new Expression[nlen]; + for (int i = 0 ; i < nlen ; i++) { + args[i] = new IdentifierExpression(names[i]); + } + } else { + if (field.isConstructor()) { + // Constructor access method is non-static, so + // 'this' works normally. + thisArg = new ThisExpression(where); + // Remove dummy argument, as it is not + // passed to the target method. + args = new Expression[nlen-1]; + for (int i = 1 ; i < nlen ; i++) { + args[i-1] = new IdentifierExpression(names[i]); + } + } else { + // Non-constructor access method is static, so + // we use the first argument as 'this'. + thisArg = new IdentifierExpression(names[0]); + // Remove first argument. + args = new Expression[nlen-1]; + for (int i = 1 ; i < nlen ; i++) { + args[i-1] = new IdentifierExpression(names[i]); + } + } + access = thisArg; + } + + if (!isMethod) { + access = new FieldExpression(where, access, field); + if (isUpdate) { + access = new AssignExpression(where, access, args[0]); + } + } else { + // If true, 'isSuper' forces a non-virtual call. + access = new MethodExpression(where, access, field, args, isSuper); + } + + Statement code; + if (t.getReturnType().isType(TC_VOID)) { + code = new ExpressionStatement(where, access); + } else { + code = new ReturnStatement(where, access); + } + Statement body[] = { code }; + code = new CompoundStatement(where, body); + + // Access methods are now static (constructors excepted), and no longer final. + // This change was mandated by the interaction of the access method + // naming conventions and the restriction against overriding final + // methods. + int mod = M_SYNTHETIC; + if (!field.isConstructor()) { + mod |= M_STATIC; + } + + // Create the synthetic method within the class in which the referenced + // private member appears. The 'env' argument to 'makeMemberDefinition' + // is suspect because it represents the environment at the point at + // which a reference takes place, while it should represent the + // environment in which the definition of the synthetic method appears. + // We get away with this because 'env' is used only to access globals + // such as 'Environment.error', and also as an argument to + // 'resolveTypeStructure', which immediately discards it using + // 'setupEnv'. Apparently, the current definition of 'setupEnv' + // represents a design change that has not been thoroughly propagated. + // An access method is declared with same list of exceptions as its + // target. As the exceptions are simply listed by name, the correctness + // of this approach requires that the access method be checked + // (name-resolved) in the same context as its target method This + // should always be the case. + SourceMember newf = (SourceMember) + env.makeMemberDefinition(env, where, this, + null, mod, t, anm, names, + field.getExceptionIds(), code); + // Just to be safe, copy over the name-resolved exceptions from the + // target so that the context in which the access method is checked + // doesn't matter. + newf.setExceptions(field.getExceptions(env)); + + newf.setAccessMethodTarget(field); + if (isUpdate) { + af.setAccessUpdateMember(newf); + } + newf.setIsSuperAccessMethod(isSuper); + + // The call to 'check' is not needed, as the access method will be + // checked by the containing class after it is added. This is the + // idiom followed in the implementation of class literals. (See + // 'FieldExpression.java'.) In any case, the context is wrong in the + // call below. The access method must be checked in the context in + // which it is declared, i.e., the class containing the referenced + // private member, not the (inner) class in which the original member + // reference occurs. + // + // try { + // newf.check(env, ctx, new Vset()); + // } catch (ClassNotFound ee) { + // env.error(where, "class.not.found", ee.name, this); + // } + + // The comment above is inaccurate. While it is often the case + // that the containing class will check the access method, this is + // by no means guaranteed. In fact, an access method may be added + // after the checking of its class is complete. In this case, however, + // the context in which the class was checked will have been saved in + // the class definition object (by the fix for 4095716), allowing us + // to check the field now, and in the correct context. + // This fixes bug 4098093. + + Context checkContext = newf.getClassDefinition().getClassContext(); + if (checkContext != null) { + //System.out.println("checking late addition: " + this); + try { + newf.check(env, checkContext, new Vset()); + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, this); + } + } + + + //System.out.println("[Access member '" + + // newf + "' created for field '" + + // field +"' in class '" + this + "']"); + + return newf; + } + + /** + * Find an inner class of 'this', chosen arbitrarily. + * Result is always an actual class, never an interface. + * Returns null if none found. + */ + SourceClass findLookupContext() { + // Look for an immediate inner class. + for (MemberDefinition f = getFirstMember(); + f != null; + f = f.getNextMember()) { + if (f.isInnerClass()) { + SourceClass ic = (SourceClass)f.getInnerClass(); + if (!ic.isInterface()) { + return ic; + } + } + } + // Look for a class nested within an immediate inner interface. + // At this point, we have given up on finding a minimally-nested + // class (which would require a breadth-first traversal). It doesn't + // really matter which inner class we find. + for (MemberDefinition f = getFirstMember(); + f != null; + f = f.getNextMember()) { + if (f.isInnerClass()) { + SourceClass lc = + ((SourceClass)f.getInnerClass()).findLookupContext(); + if (lc != null) { + return lc; + } + } + } + // No inner classes. + return null; + } + + private MemberDefinition lookup = null; + + /** + * Get helper method for class literal lookup. + */ + public MemberDefinition getClassLiteralLookup(long fwhere) { + + // If we have already created a lookup method, reuse it. + if (lookup != null) { + return lookup; + } + + // If the current class is a nested class, make sure we put the + // lookup method in the outermost class. Set 'lookup' for the + // intervening inner classes so we won't have to do the search + // again. + if (outerClass != null) { + lookup = outerClass.getClassLiteralLookup(fwhere); + return lookup; + } + + // If we arrive here, there was no existing 'class$' method. + + ClassDefinition c = this; + boolean needNewClass = false; + + if (isInterface()) { + // The top-level type is an interface. Try to find an existing + // inner class in which to create the helper method. Any will do. + c = findLookupContext(); + if (c == null) { + // The interface has no inner classes. Create an anonymous + // inner class to hold the helper method, as an interface must + // not have any methods. The tests above for prior creation + // of a 'class$' method assure that only one such class is + // allocated for each outermost class containing a class + // literal embedded somewhere within. Part of fix for 4055017. + needNewClass = true; + IdentifierToken sup = + new IdentifierToken(fwhere, idJavaLangObject); + IdentifierToken interfaces[] = {}; + IdentifierToken t = new IdentifierToken(fwhere, idNull); + int mod = M_PUBLIC | M_ANONYMOUS | M_STATIC | M_SYNTHETIC; + c = (SourceClass) + toplevelEnv.makeClassDefinition(toplevelEnv, + fwhere, t, null, mod, + sup, interfaces, this); + } + } + + + // The name of the class-getter stub is "class$" + Identifier idDClass = Identifier.lookup(prefixClass); + Type strarg[] = { Type.tString }; + + // Some sanity checks of questionable value. + // + // This check became useless after matchMethod() was modified + // to not return synthetic methods. + // + //try { + // lookup = c.matchMethod(toplevelEnv, c, idDClass, strarg); + //} catch (ClassNotFound ee) { + // throw new CompilerError("unexpected missing class"); + //} catch (AmbiguousMember ee) { + // throw new CompilerError("synthetic name clash"); + //} + //if (lookup != null && lookup.getClassDefinition() == c) { + // // Error if method found was not inherited. + // throw new CompilerError("unexpected duplicate"); + //} + // Some sanity checks of questionable value. + + /* // The helper function looks like this. + * // It simply maps a checked exception to an unchecked one. + * static Class class$(String class$) { + * try { return Class.forName(class$); } + * catch (ClassNotFoundException forName) { + * throw new NoClassDefFoundError(forName.getMessage()); + * } + * } + */ + long w = c.getWhere(); + IdentifierToken arg = new IdentifierToken(w, idDClass); + Expression e = new IdentifierExpression(arg); + Expression a1[] = { e }; + Identifier idForName = Identifier.lookup("forName"); + e = new MethodExpression(w, new TypeExpression(w, Type.tClassDesc), + idForName, a1); + Statement body = new ReturnStatement(w, e); + // map the exceptions + Identifier idClassNotFound = + Identifier.lookup("java.lang.ClassNotFoundException"); + Identifier idNoClassDefFound = + Identifier.lookup("java.lang.NoClassDefFoundError"); + Type ctyp = Type.tClass(idClassNotFound); + Type exptyp = Type.tClass(idNoClassDefFound); + Identifier idGetMessage = Identifier.lookup("getMessage"); + e = new IdentifierExpression(w, idForName); + e = new MethodExpression(w, e, idGetMessage, new Expression[0]); + Expression a2[] = { e }; + e = new NewInstanceExpression(w, new TypeExpression(w, exptyp), a2); + Statement handler = new CatchStatement(w, new TypeExpression(w, ctyp), + new IdentifierToken(idForName), + new ThrowStatement(w, e)); + Statement handlers[] = { handler }; + body = new TryStatement(w, body, handlers); + + Type mtype = Type.tMethod(Type.tClassDesc, strarg); + IdentifierToken args[] = { arg }; + + // Use default (package) access. If private, an access method would + // be needed in the event that the class literal belonged to an interface. + // Also, making it private tickles bug 4098316. + lookup = toplevelEnv.makeMemberDefinition(toplevelEnv, w, + c, null, + M_STATIC | M_SYNTHETIC, + mtype, idDClass, + args, null, body); + + // If a new class was created to contain the helper method, + // check it now. + if (needNewClass) { + if (c.getClassDeclaration().getStatus() == CS_CHECKED) { + throw new CompilerError("duplicate check"); + } + c.getClassDeclaration().setDefinition(c, CS_PARSED); + Expression argsX[] = {}; + Type argTypesX[] = {}; + try { + ClassDefinition sup = + toplevelEnv.getClassDefinition(idJavaLangObject); + c.checkLocalClass(toplevelEnv, null, + new Vset(), sup, argsX, argTypesX); + } catch (ClassNotFound ee) {}; + } + + return lookup; + } + + + /** + * A list of active ongoing compilations. This list + * is used to stop two compilations from saving the + * same class. + */ + private static Vector active = new Vector<>(); + + /** + * Compile this class + */ + public void compile(OutputStream out) + throws InterruptedException, IOException { + Environment env = toplevelEnv; + synchronized (active) { + while (active.contains(getName())) { + active.wait(); + } + active.addElement(getName()); + } + + try { + compileClass(env, out); + } catch (ClassNotFound e) { + throw new CompilerError(e); + } finally { + synchronized (active) { + active.removeElement(getName()); + active.notifyAll(); + } + } + } + + /** + * Verify that the modifier bits included in 'required' are + * all present in 'mods', otherwise signal an internal error. + * Note that errors in the source program may corrupt the modifiers, + * thus we rely on the fact that 'CompilerError' exceptions are + * silently ignored after an error message has been issued. + */ + private static void assertModifiers(int mods, int required) { + if ((mods & required) != required) { + throw new CompilerError("illegal class modifiers"); + } + } + + protected void compileClass(Environment env, OutputStream out) + throws IOException, ClassNotFound { + Vector variables = new Vector<>(); + Vector methods = new Vector<>(); + Vector innerClasses = new Vector<>(); + CompilerMember init = new CompilerMember(new MemberDefinition(getWhere(), this, M_STATIC, Type.tMethod(Type.tVoid), idClassInit, null, null), new Assembler()); + Context ctx = new Context((Context)null, init.field); + + for (ClassDefinition def = this; def.isInnerClass(); def = def.getOuterClass()) { + innerClasses.addElement(def); + } + // Reverse the order, so that outer levels come first: + int ncsize = innerClasses.size(); + for (int i = ncsize; --i >= 0; ) + innerClasses.addElement(innerClasses.elementAt(i)); + for (int i = ncsize; --i >= 0; ) + innerClasses.removeElementAt(i); + + // System.out.println("compile class " + getName()); + + boolean haveDeprecated = this.isDeprecated(); + boolean haveSynthetic = this.isSynthetic(); + boolean haveConstantValue = false; + boolean haveExceptions = false; + + // Generate code for all fields + for (SourceMember field = (SourceMember)getFirstMember(); + field != null; + field = (SourceMember)field.getNextMember()) { + + //System.out.println("compile field " + field.getName()); + + haveDeprecated |= field.isDeprecated(); + haveSynthetic |= field.isSynthetic(); + + try { + if (field.isMethod()) { + haveExceptions |= + (field.getExceptions(env).length > 0); + + if (field.isInitializer()) { + if (field.isStatic()) { + field.code(env, init.asm); + } + } else { + CompilerMember f = + new CompilerMember(field, new Assembler()); + field.code(env, f.asm); + methods.addElement(f); + } + } else if (field.isInnerClass()) { + innerClasses.addElement(field.getInnerClass()); + } else if (field.isVariable()) { + field.inline(env); + CompilerMember f = new CompilerMember(field, null); + variables.addElement(f); + if (field.isStatic()) { + field.codeInit(env, ctx, init.asm); + + } + haveConstantValue |= + (field.getInitialValue() != null); + } + } catch (CompilerError ee) { + ee.printStackTrace(); + env.error(field, 0, "generic", + field.getClassDeclaration() + ":" + field + + "@" + ee.toString(), null, null); + } + } + if (!init.asm.empty()) { + init.asm.add(getWhere(), opc_return, true); + methods.addElement(init); + } + + // bail out if there were any errors + if (getNestError()) { + return; + } + + int nClassAttrs = 0; + + // Insert constants + if (methods.size() > 0) { + tab.put("Code"); + } + if (haveConstantValue) { + tab.put("ConstantValue"); + } + + String sourceFile = null; + if (env.debug_source()) { + sourceFile = ((ClassFile)getSource()).getName(); + tab.put("SourceFile"); + tab.put(sourceFile); + nClassAttrs += 1; + } + + if (haveExceptions) { + tab.put("Exceptions"); + } + + if (env.debug_lines()) { + tab.put("LineNumberTable"); + } + if (haveDeprecated) { + tab.put("Deprecated"); + if (this.isDeprecated()) { + nClassAttrs += 1; + } + } + if (haveSynthetic) { + tab.put("Synthetic"); + if (this.isSynthetic()) { + nClassAttrs += 1; + } + } +// JCOV + if (env.coverage()) { + nClassAttrs += 2; // AbsoluteSourcePath, TimeStamp + tab.put("AbsoluteSourcePath"); + tab.put("TimeStamp"); + tab.put("CoverageTable"); + } +// end JCOV + if (env.debug_vars()) { + tab.put("LocalVariableTable"); + } + if (innerClasses.size() > 0) { + tab.put("InnerClasses"); + nClassAttrs += 1; // InnerClasses + } + +// JCOV + String absoluteSourcePath = ""; + long timeStamp = 0; + + if (env.coverage()) { + absoluteSourcePath = getAbsoluteName(); + timeStamp = System.currentTimeMillis(); + tab.put(absoluteSourcePath); + } +// end JCOV + tab.put(getClassDeclaration()); + if (getSuperClass() != null) { + tab.put(getSuperClass()); + } + for (int i = 0 ; i < interfaces.length ; i++) { + tab.put(interfaces[i]); + } + + // Sort the methods in order to make sure both constant pool + // entries and methods are in a deterministic order from run + // to run (this allows comparing class files for a fixed point + // to validate the compiler) + CompilerMember[] ordered_methods = + new CompilerMember[methods.size()]; + methods.copyInto(ordered_methods); + java.util.Arrays.sort(ordered_methods); + for (int i=0; i e = methods.elements() ; e.hasMoreElements() ; ) { + CompilerMember f = e.nextElement(); + try { + f.asm.optimize(env); + f.asm.collect(env, f.field, tab); + tab.put(f.name); + tab.put(f.sig); + ClassDeclaration exp[] = f.field.getExceptions(env); + for (int i = 0 ; i < exp.length ; i++) { + tab.put(exp[i]); + } + } catch (Exception ee) { + ee.printStackTrace(); + env.error(f.field, -1, "generic", f.field.getName() + "@" + ee.toString(), null, null); + f.asm.listing(System.out); + } + } + + // Collect field constants + for (Enumeration e = variables.elements() ; e.hasMoreElements() ; ) { + CompilerMember f = e.nextElement(); + tab.put(f.name); + tab.put(f.sig); + + Object val = f.field.getInitialValue(); + if (val != null) { + tab.put((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val); + } + } + + // Collect inner class constants + for (Enumeration e = innerClasses.elements(); + e.hasMoreElements() ; ) { + ClassDefinition inner = e.nextElement(); + tab.put(inner.getClassDeclaration()); + + // If the inner class is local, we do not need to add its + // outer class here -- the outer_class_info_index is zero. + if (!inner.isLocal()) { + ClassDefinition outer = inner.getOuterClass(); + tab.put(outer.getClassDeclaration()); + } + + // If the local name of the class is idNull, don't bother to + // add it to the constant pool. We won't need it. + Identifier inner_local_name = inner.getLocalName(); + if (inner_local_name != idNull) { + tab.put(inner_local_name.toString()); + } + } + + // Write header + DataOutputStream data = new DataOutputStream(out); + data.writeInt(JAVA_MAGIC); + data.writeShort(toplevelEnv.getMinorVersion()); + data.writeShort(toplevelEnv.getMajorVersion()); + tab.write(env, data); + + // Write class information + int cmods = getModifiers() & MM_CLASS; + + // Certain modifiers are implied: + // 1. Any interface (nested or not) is implicitly deemed to be abstract, + // whether it is explicitly marked so or not. (Java 1.0.) + // 2. A interface which is a member of a type is implicitly deemed to + // be static, whether it is explicitly marked so or not. + // 3a. A type which is a member of an interface is implicitly deemed + // to be public, whether it is explicitly marked so or not. + // 3b. A type which is a member of an interface is implicitly deemed + // to be static, whether it is explicitly marked so or not. + // All of these rules are implemented in 'BatchParser.beginClass', + // but the results are verified here. + + if (isInterface()) { + // Rule 1. + // The VM spec states that ACC_ABSTRACT must be set when + // ACC_INTERFACE is; this was not done by javac prior to 1.2, + // and the runtime compensates by setting it. Making sure + // it is set here will allow the runtime hack to eventually + // be removed. Rule 2 doesn't apply to transformed modifiers. + assertModifiers(cmods, ACC_ABSTRACT); + } else { + // Contrary to the JVM spec, we only set ACC_SUPER for classes, + // not interfaces. This is a workaround for a bug in IE3.0, + // which refuses interfaces with ACC_SUPER on. + cmods |= ACC_SUPER; + } + + // If this is a nested class, transform access modifiers. + if (outerClass != null) { + // If private, transform to default (package) access. + // If protected, transform to public. + // M_PRIVATE and M_PROTECTED are already masked off by MM_CLASS above. + // cmods &= ~(M_PRIVATE | M_PROTECTED); + if (isProtected()) cmods |= M_PUBLIC; + // Rule 3a. Note that Rule 3b doesn't apply to transformed modifiers. + if (outerClass.isInterface()) { + assertModifiers(cmods, M_PUBLIC); + } + } + + data.writeShort(cmods); + + if (env.dumpModifiers()) { + Identifier cn = getName(); + Identifier nm = + Identifier.lookup(cn.getQualifier(), cn.getFlatName()); + System.out.println(); + System.out.println("CLASSFILE " + nm); + System.out.println("---" + classModifierString(cmods)); + } + + data.writeShort(tab.index(getClassDeclaration())); + data.writeShort((getSuperClass() != null) ? tab.index(getSuperClass()) : 0); + data.writeShort(interfaces.length); + for (int i = 0 ; i < interfaces.length ; i++) { + data.writeShort(tab.index(interfaces[i])); + } + + // write variables + ByteArrayOutputStream buf = new ByteArrayOutputStream(256); + ByteArrayOutputStream attbuf = new ByteArrayOutputStream(256); + DataOutputStream databuf = new DataOutputStream(buf); + + data.writeShort(variables.size()); + for (Enumeration e = variables.elements() ; e.hasMoreElements() ; ) { + CompilerMember f = e.nextElement(); + Object val = f.field.getInitialValue(); + + data.writeShort(f.field.getModifiers() & MM_FIELD); + data.writeShort(tab.index(f.name)); + data.writeShort(tab.index(f.sig)); + + int fieldAtts = (val != null ? 1 : 0); + boolean dep = f.field.isDeprecated(); + boolean syn = f.field.isSynthetic(); + fieldAtts += (dep ? 1 : 0) + (syn ? 1 : 0); + + data.writeShort(fieldAtts); + if (val != null) { + data.writeShort(tab.index("ConstantValue")); + data.writeInt(2); + data.writeShort(tab.index((val instanceof String) ? new StringExpression(f.field.getWhere(), (String)val) : val)); + } + if (dep) { + data.writeShort(tab.index("Deprecated")); + data.writeInt(0); + } + if (syn) { + data.writeShort(tab.index("Synthetic")); + data.writeInt(0); + } + } + + // write methods + + data.writeShort(methods.size()); + for (Enumeration e = methods.elements() ; e.hasMoreElements() ; ) { + CompilerMember f = e.nextElement(); + + int xmods = f.field.getModifiers() & MM_METHOD; + // Transform floating point modifiers. M_STRICTFP + // of member + status of enclosing class turn into + // ACC_STRICT bit. + if (((xmods & M_STRICTFP)!=0) || ((cmods & M_STRICTFP)!=0)) { + xmods |= ACC_STRICT; + } else { + // Use the default + if (env.strictdefault()) { + xmods |= ACC_STRICT; + } + } + data.writeShort(xmods); + + data.writeShort(tab.index(f.name)); + data.writeShort(tab.index(f.sig)); + ClassDeclaration exp[] = f.field.getExceptions(env); + int methodAtts = ((exp.length > 0) ? 1 : 0); + boolean dep = f.field.isDeprecated(); + boolean syn = f.field.isSynthetic(); + methodAtts += (dep ? 1 : 0) + (syn ? 1 : 0); + + if (!f.asm.empty()) { + data.writeShort(methodAtts+1); + f.asm.write(env, databuf, f.field, tab); + int natts = 0; + if (env.debug_lines()) { + natts++; + } +// JCOV + if (env.coverage()) { + natts++; + } +// end JCOV + if (env.debug_vars()) { + natts++; + } + databuf.writeShort(natts); + + if (env.debug_lines()) { + f.asm.writeLineNumberTable(env, new DataOutputStream(attbuf), tab); + databuf.writeShort(tab.index("LineNumberTable")); + databuf.writeInt(attbuf.size()); + attbuf.writeTo(buf); + attbuf.reset(); + } + +//JCOV + if (env.coverage()) { + f.asm.writeCoverageTable(env, (ClassDefinition)this, new DataOutputStream(attbuf), tab, f.field.getWhere()); + databuf.writeShort(tab.index("CoverageTable")); + databuf.writeInt(attbuf.size()); + attbuf.writeTo(buf); + attbuf.reset(); + } +// end JCOV + if (env.debug_vars()) { + f.asm.writeLocalVariableTable(env, f.field, new DataOutputStream(attbuf), tab); + databuf.writeShort(tab.index("LocalVariableTable")); + databuf.writeInt(attbuf.size()); + attbuf.writeTo(buf); + attbuf.reset(); + } + + data.writeShort(tab.index("Code")); + data.writeInt(buf.size()); + buf.writeTo(data); + buf.reset(); + } else { +//JCOV + if ((env.coverage()) && ((f.field.getModifiers() & M_NATIVE) > 0)) + f.asm.addNativeToJcovTab(env, (ClassDefinition)this); +// end JCOV + data.writeShort(methodAtts); + } + + if (exp.length > 0) { + data.writeShort(tab.index("Exceptions")); + data.writeInt(2 + exp.length * 2); + data.writeShort(exp.length); + for (int i = 0 ; i < exp.length ; i++) { + data.writeShort(tab.index(exp[i])); + } + } + if (dep) { + data.writeShort(tab.index("Deprecated")); + data.writeInt(0); + } + if (syn) { + data.writeShort(tab.index("Synthetic")); + data.writeInt(0); + } + } + + // class attributes + data.writeShort(nClassAttrs); + + if (env.debug_source()) { + data.writeShort(tab.index("SourceFile")); + data.writeInt(2); + data.writeShort(tab.index(sourceFile)); + } + + if (this.isDeprecated()) { + data.writeShort(tab.index("Deprecated")); + data.writeInt(0); + } + if (this.isSynthetic()) { + data.writeShort(tab.index("Synthetic")); + data.writeInt(0); + } + +// JCOV + if (env.coverage()) { + data.writeShort(tab.index("AbsoluteSourcePath")); + data.writeInt(2); + data.writeShort(tab.index(absoluteSourcePath)); + data.writeShort(tab.index("TimeStamp")); + data.writeInt(8); + data.writeLong(timeStamp); + } +// end JCOV + + if (innerClasses.size() > 0) { + data.writeShort(tab.index("InnerClasses")); + data.writeInt(2 + 2*4*innerClasses.size()); + data.writeShort(innerClasses.size()); + for (Enumeration e = innerClasses.elements() ; + e.hasMoreElements() ; ) { + // For each inner class name transformation, we have a record + // with the following fields: + // + // u2 inner_class_info_index; // CONSTANT_Class_info index + // u2 outer_class_info_index; // CONSTANT_Class_info index + // u2 inner_name_index; // CONSTANT_Utf8_info index + // u2 inner_class_access_flags; // access_flags bitmask + // + // The spec states that outer_class_info_index is 0 iff + // the inner class is not a member of its enclosing class (i.e. + // it is a local or anonymous class). The spec also states + // that if a class is anonymous then inner_name_index should + // be 0. + // + // See also the initInnerClasses() method in BinaryClass.java. + + // Generate inner_class_info_index. + ClassDefinition inner = e.nextElement(); + data.writeShort(tab.index(inner.getClassDeclaration())); + + // Generate outer_class_info_index. + // + // Checking isLocal() should probably be enough here, + // but the check for isAnonymous is added for good + // measure. + if (inner.isLocal() || inner.isAnonymous()) { + data.writeShort(0); + } else { + // Query: what about if inner.isInsideLocal()? + // For now we continue to generate a nonzero + // outer_class_info_index. + ClassDefinition outer = inner.getOuterClass(); + data.writeShort(tab.index(outer.getClassDeclaration())); + } + + // Generate inner_name_index. + Identifier inner_name = inner.getLocalName(); + if (inner_name == idNull) { + if (!inner.isAnonymous()) { + throw new CompilerError("compileClass(), anonymous"); + } + data.writeShort(0); + } else { + data.writeShort(tab.index(inner_name.toString())); + } + + // Generate inner_class_access_flags. + int imods = inner.getInnerClassMember().getModifiers() + & ACCM_INNERCLASS; + + // Certain modifiers are implied for nested types. + // See rules 1, 2, 3a, and 3b enumerated above. + // All of these rules are implemented in 'BatchParser.beginClass', + // but are verified here. + + if (inner.isInterface()) { + // Rules 1 and 2. + assertModifiers(imods, M_ABSTRACT | M_STATIC); + } + if (inner.getOuterClass().isInterface()) { + // Rules 3a and 3b. + imods &= ~(M_PRIVATE | M_PROTECTED); // error recovery + assertModifiers(imods, M_PUBLIC | M_STATIC); + } + + data.writeShort(imods); + + if (env.dumpModifiers()) { + Identifier fn = inner.getInnerClassMember().getName(); + Identifier nm = + Identifier.lookup(fn.getQualifier(), fn.getFlatName()); + System.out.println("INNERCLASS " + nm); + System.out.println("---" + classModifierString(imods)); + } + + } + } + + // Cleanup + data.flush(); + tab = null; + +// JCOV + // generate coverage data + if (env.covdata()) { + Assembler CovAsm = new Assembler(); + CovAsm.GenVecJCov(env, (ClassDefinition)this, timeStamp); + } +// end JCOV + } + + /** + * Print out the dependencies for this class (-xdepend) option + */ + + public void printClassDependencies(Environment env) { + + // Only do this if the -xdepend flag is on + if ( toplevelEnv.print_dependencies() ) { + + // Name of java source file this class was in (full path) + // e.g. /home/ohair/Test.java + String src = ((ClassFile)getSource()).getAbsoluteName(); + + // Class name, fully qualified + // e.g. "java.lang.Object" or "FooBar" or "org.glassfish.rmic.tools.javac.Main" + // Inner class names must be mangled, as ordinary '.' qualification + // is used internally where the spec requires '$' separators. + // String className = getName().toString(); + String className = Type.mangleInnerType(getName()).toString(); + + // Line number where class starts in the src file + long startLine = getWhere() >> WHEREOFFSETBITS; + + // Line number where class ends in the src file (not used yet) + long endLine = getEndPosition() >> WHEREOFFSETBITS; + + // First line looks like: + // CLASS:src,startLine,endLine,className + System.out.println( "CLASS:" + + src + "," + + startLine + "," + + endLine + "," + + className); + + // For each class this class is dependent on: + // CLDEP:className1,className2 + // where className1 is the name of the class we are in, and + // classname2 is the name of the class className1 + // is dependent on. + for(Enumeration e = deps.elements(); e.hasMoreElements(); ) { + ClassDeclaration data = e.nextElement(); + // Mangle name of class dependend on. + String depName = + Type.mangleInnerType(data.getName()).toString(); + env.output("CLDEP:" + className + "," + depName); + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/javac/SourceMember.java b/rmic/src/main/java/org/glassfish/rmic/tools/javac/SourceMember.java new file mode 100644 index 000000000..d9e75e22a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/javac/SourceMember.java @@ -0,0 +1,892 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.tree.*; +import org.glassfish.rmic.tools.asm.*; +import java.util.Vector; +import java.util.Enumeration; +import java.util.Hashtable; +import java.io.PrintStream; + +/** + * A Source Member + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +@Deprecated +public +class SourceMember extends MemberDefinition implements Constants { + /** + * The argument names (if it is a method) + */ + Vector args; + + // set to the MemberDefinition in the interface if we have this field because + // it has been forced on us + MemberDefinition abstractSource; + + /** + * The status of the field + */ + int status; + + static final int PARSED = 0; + static final int CHECKING = 1; + static final int CHECKED = 2; + static final int INLINING = 3; + static final int INLINED = 4; + static final int ERROR = 5; + + public Vector getArguments() { + return args; + } + + /** + * Constructor + * @param argNames a vector of IdentifierToken + */ + public SourceMember(long where, ClassDefinition clazz, + String doc, int modifiers, Type type, + Identifier name, Vector argNames, + IdentifierToken exp[], Node value) { + super(where, clazz, modifiers, type, name, exp, value); + this.documentation = doc; + this.args = argNames; // for the moment + // not until type names are resolved: createArgumentFields(argNames); + + if (ClassDefinition.containsDeprecated(documentation)) { + this.modifiers |= M_DEPRECATED; + } + } + + void createArgumentFields(Vector argNames) { + // Create a list of arguments + if (isMethod()) { + args = new Vector<>(); + + if (isConstructor() || !(isStatic() || isInitializer())) { + args.addElement(((SourceClass)clazz).getThisArgument()); + } + + if (argNames != null) { + Enumeration e = argNames.elements(); + Type argTypes[] = getType().getArgumentTypes(); + for (int i = 0 ; i < argTypes.length ; i++) { + Object x = e.nextElement(); + if (x instanceof LocalMember) { + // This should not happen, but it does + // in cases of vicious cyclic inheritance. + args = argNames; + return; + } + Identifier id; + int mod; + long where; + if (x instanceof Identifier) { + // allow argNames to be simple Identifiers (deprecated!) + id = (Identifier)x; + mod = 0; + where = getWhere(); + } else { + IdentifierToken token = (IdentifierToken)x; + id = token.getName(); + mod = token.getModifiers(); + where = token.getWhere(); + } + args.addElement(new LocalMember(where, clazz, mod, + argTypes[i], id)); + } + } + } + } + + // The methods addOuterThis() and addUplevelArguments() were + // both originally part of a single method called addUplevelArguments() + // which took a single boolean parameter describing which of the + // two behaviors it wanted. + // + // The original addUplevelArguments() claimed to keep the arguments in + // the following order: + // + // (1) + // + // (By I am referring to the clientOuterField added + // to some constructors when they are created. If an outer this is + // added later, on demand, then this is mixed in with the rest of the + // uplevel arguments and is added by addUplevelArguments.) + // + // In reality, the `args' Vector was generated in this order, but the + // Type array `argTypes' was generated as: + // + // (2) + // + // This didn't make a difference in the common case -- that is, when + // a class had an or but not both. + // Both can happen in the case that a member class is declared inside + // of a local class. It seems that the calling sequences, generated + // in places like NewInstanceExpression.codeCommon(), use order (2), + // so I have changed the code below to stick with that order. Since + // the only time this happens is in classes which are insideLocal, no + // one should be able to tell the difference between these orders. + // (bug number 4085633) + + LocalMember outerThisArg = null; + + /** + * Get outer instance link, or null if none. + */ + + public LocalMember getOuterThisArg() { + return outerThisArg; + } + + /** + * Add the outer.this argument to the list of arguments for this + * constructor. This is called from resolveTypeStructure. Any + * additional uplevel arguments get added later by addUplevelArguments(). + */ + + void addOuterThis() { + UplevelReference refs = clazz.getReferences(); + + // See if we have a client outer field. + while (refs != null && + !refs.isClientOuterField()) { + refs = refs.getNext(); + } + + // There is no outer this argument. Quit. + if (refs == null) { + return; + } + + // Get the old arg types. + Type oldArgTypes[] = type.getArgumentTypes(); + + // And make an array for the new ones with space for one more. + Type argTypes[] = new Type[oldArgTypes.length + 1]; + + LocalMember arg = refs.getLocalArgument(); + outerThisArg = arg; + + // args is our list of arguments. It contains a `this', so + // we insert at position 1. The list of types does not have a + // this, so we insert at position 0. + args.insertElementAt(arg, 1); + argTypes[0] = arg.getType(); + + // Add on the rest of the constructor arguments. + for (int i = 0; i < oldArgTypes.length; i++) { + argTypes[i + 1] = oldArgTypes[i]; + } + + type = Type.tMethod(type.getReturnType(), argTypes); + } + + /** + * Prepend argument names and argument types for local variable references. + * This information is never seen by the type-check phase, + * but it affects code generation, which is the earliest moment + * we have comprehensive information on uplevel references. + * The code() methods tweaks the constructor calls, prepending + * the proper values to the argument list. + */ + void addUplevelArguments() { + UplevelReference refs = clazz.getReferences(); + clazz.getReferencesFrozen(); + + // Count how many uplevels we have to add. + int count = 0; + for (UplevelReference r = refs; r != null; r = r.getNext()) { + if (!r.isClientOuterField()) { + count += 1; + } + } + + if (count == 0) { + // None to add, quit. + return; + } + + // Get the old argument types. + Type oldArgTypes[] = type.getArgumentTypes(); + + // Make an array with enough room for the new. + Type argTypes[] = new Type[oldArgTypes.length + count]; + + // Add all of the late uplevel references to args and argTypes. + // Note that they are `off-by-one' because of the `this'. + int ins = 0; + for (UplevelReference r = refs; r != null; r = r.getNext()) { + if (!r.isClientOuterField()) { + LocalMember arg = r.getLocalArgument(); + + args.insertElementAt(arg, 1 + ins); + argTypes[ins] = arg.getType(); + + ins++; + } + } + + // Add the rest of the old arguments. + for (int i = 0; i < oldArgTypes.length; i++) { + argTypes[ins + i] = oldArgTypes[i]; + } + + type = Type.tMethod(type.getReturnType(), argTypes); + } + + /** + * Constructor for an inner class. + */ + public SourceMember(ClassDefinition innerClass) { + super(innerClass); + } + + /** + * Constructor. + * Used only to generate an abstract copy of a method that a class + * inherits from an interface + */ + public SourceMember(MemberDefinition f, ClassDefinition c, Environment env) { + this(f.getWhere(), c, f.getDocumentation(), + f.getModifiers() | M_ABSTRACT, f.getType(), f.getName(), null, + f.getExceptionIds(), null); + this.args = f.getArguments(); + this.abstractSource = f; + this.exp = f.getExceptions(env); + } + + /** + * Get exceptions + */ + public ClassDeclaration[] getExceptions(Environment env) { + if ((!isMethod()) || (exp != null)) { + return exp; + } + if (expIds == null) { + // (should not happen) + exp = new ClassDeclaration[0]; + return exp; + } + // be sure to get the imports right: + env = ((SourceClass)getClassDefinition()).setupEnv(env); + exp = new ClassDeclaration[expIds.length]; + for (int i = 0; i < exp.length; i++) { + Identifier e = expIds[i].getName(); + Identifier rexp = getClassDefinition().resolveName(env, e); + exp[i] = env.getClassDeclaration(rexp); + } + return exp; + } + + /** + * Set array of name-resolved exceptions directly, e.g., for access methods. + */ + public void setExceptions(ClassDeclaration[] exp) { + this.exp = exp; + } + + /** + * Resolve types in a field, after parsing. + * @see ClassDefinition.resolveTypeStructure + */ + + public boolean resolved = false; + + public void resolveTypeStructure(Environment env) { + if (tracing) env.dtEnter("SourceMember.resolveTypeStructure: " + this); + + // A member should only be resolved once. For a constructor, it is imperative + // that 'addOuterThis' be called only once, else the outer instance argument may + // be inserted into the argument list multiple times. + + if (resolved) { + if (tracing) env.dtEvent("SourceMember.resolveTypeStructure: OK " + this); + // This case shouldn't be happening. It is the responsibility + // of our callers to avoid attempting multiple resolutions of a member. + // *** REMOVE FOR SHIPMENT? *** + throw new CompilerError("multiple member type resolution"); + //return; + } else { + if (tracing) env.dtEvent("SourceMember.resolveTypeStructure: RESOLVING " + this); + resolved = true; + } + + super.resolveTypeStructure(env); + if (isInnerClass()) { + ClassDefinition nc = getInnerClass(); + if (nc instanceof SourceClass && !nc.isLocal()) { + ((SourceClass)nc).resolveTypeStructure(env); + } + type = innerClass.getType(); + } else { + // Expand all class names in 'type', including those that are not + // fully-qualified or refer to inner classes, into fully-qualified + // names. Local and anonymous classes get synthesized names here, + // corresponding to the class files that will be generated. This is + // currently the only place where 'resolveNames' is used. + type = env.resolveNames(getClassDefinition(), type, isSynthetic()); + + // do the throws also: + getExceptions(env); + + if (isMethod()) { + Vector argNames = args; args = null; + createArgumentFields(argNames); + // Add outer instance argument for constructors. + if (isConstructor()) { + addOuterThis(); + } + } + } + if (tracing) env.dtExit("SourceMember.resolveTypeStructure: " + this); + } + + /** + * Get the class declaration in which the field is actually defined + */ + public ClassDeclaration getDefiningClassDeclaration() { + if (abstractSource == null) + return super.getDefiningClassDeclaration(); + else + return abstractSource.getDefiningClassDeclaration(); + } + + /** + * A source field never reports deprecation, since the compiler + * allows access to deprecated features that are being compiled + * in the same job. + */ + public boolean reportDeprecated(Environment env) { + return false; + } + + /** + * Check this field. + *

                + * This is the method which requests checking. + * The real work is done by + * {@code Vset check(Environment, Context, Vset)}. + */ + public void check(Environment env) throws ClassNotFound { + if (tracing) env.dtEnter("SourceMember.check: " + + getName() + ", status = " + status); + // rely on the class to check all fields in the proper order + if (status == PARSED) { + if (isSynthetic() && getValue() == null) { + // break a big cycle for small synthetic variables + status = CHECKED; + if (tracing) + env.dtExit("SourceMember.check: BREAKING CYCLE"); + return; + } + if (tracing) env.dtEvent("SourceMember.check: CHECKING CLASS"); + clazz.check(env); + if (status == PARSED) { + if (getClassDefinition().getError()) { + status = ERROR; + } else { + if (tracing) + env.dtExit("SourceMember.check: CHECK FAILED"); + throw new CompilerError("check failed"); + } + } + } + if (tracing) env.dtExit("SourceMember.check: DONE " + + getName() + ", status = " + status); + } + + /** + * Check a field. + * @param vset tells which uplevel variables are definitely assigned + * The vset is also used to track the initialization of blank finals + * by whichever fields which are relevant to them. + */ + public Vset check(Environment env, Context ctx, Vset vset) throws ClassNotFound { + if (tracing) env.dtEvent("SourceMember.check: MEMBER " + + getName() + ", status = " + status); + if (status == PARSED) { + if (isInnerClass()) { + // some classes are checked separately + ClassDefinition nc = getInnerClass(); + if (nc instanceof SourceClass && !nc.isLocal() + && nc.isInsideLocal()) { + status = CHECKING; + vset = ((SourceClass)nc).checkInsideClass(env, ctx, vset); + } + status = CHECKED; + return vset; + } + if (env.dump()) { + System.out.println("[check field " + getClassDeclaration().getName() + "." + getName() + "]"); + if (getValue() != null) { + getValue().print(System.out); + System.out.println(); + } + } + env = new Environment(env, this); + + // This is where all checking of names appearing within the type + // of the member is done. Includes return type and argument types. + // Since only one location ('where') for error messages is provided, + // localization of errors is poor. Throws clauses are handled below. + env.resolve(where, getClassDefinition(), getType()); + + // Make sure that all the classes that we claim to throw really + // are subclasses of Throwable, and are classes that we can reach + if (isMethod()) { + ClassDeclaration throwable = + env.getClassDeclaration(idJavaLangThrowable); + ClassDeclaration exp[] = getExceptions(env); + for (int i = 0 ; i < exp.length ; i++) { + ClassDefinition def; + long where = getWhere(); + if (expIds != null && i < expIds.length) { + where = IdentifierToken.getWhere(expIds[i], where); + } + try { + def = exp[i].getClassDefinition(env); + + // Validate access for all inner-class components + // of a qualified name, not just the last one, which + // is checked below. Yes, this is a dirty hack... + // Part of fix for 4094658. + env.resolveByName(where, getClassDefinition(), def.getName()); + + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, "throws"); + break; + } + def.noteUsedBy(getClassDefinition(), where, env); + if (!getClassDefinition(). + canAccess(env, def.getClassDeclaration())) { + env.error(where, "cant.access.class", def); + } else if (!def.subClassOf(env, throwable)) { + env.error(where, "throws.not.throwable", def); + } + } + } + + status = CHECKING; + + if (isMethod() && args != null) { + int length = args.size(); + outer_loop: + for (int i = 0; i < length; i++) { + LocalMember lf = (LocalMember)(args.elementAt(i)); + Identifier name_i = lf.getName(); + for (int j = i + 1; j < length; j++) { + LocalMember lf2 = (LocalMember)(args.elementAt(j)); + Identifier name_j = lf2.getName(); + if (name_i.equals(name_j)) { + env.error(lf2.getWhere(), "duplicate.argument", + name_i); + break outer_loop; + } + } + } + } + + if (getValue() != null) { + ctx = new Context(ctx, this); + + if (isMethod()) { + Statement s = (Statement)getValue(); + // initialize vset, indication that each of the arguments + // to the function has a value + + for (Enumeration e = args.elements(); e.hasMoreElements();){ + LocalMember f = (LocalMember)e.nextElement(); + vset.addVar(ctx.declare(env, f)); + } + + if (isConstructor()) { + // Undefine "this" in some constructors, until after + // the super constructor has been called. + vset.clearVar(ctx.getThisNumber()); + + // If the first thing in the definition isn't a call + // to either super() or this(), then insert one. + Expression supCall = s.firstConstructor(); + if ((supCall == null) + && (getClassDefinition().getSuperClass() != null)) { + supCall = getDefaultSuperCall(env); + Statement scs = new ExpressionStatement(where, + supCall); + s = Statement.insertStatement(scs, s); + setValue(s); + } + } + + //System.out.println("VSET = " + vset); + ClassDeclaration exp[] = getExceptions(env); + int htsize = (exp.length > 3) ? 17 : 7; + Hashtable thrown = new Hashtable<>(htsize); + + vset = s.checkMethod(env, ctx, vset, thrown); + + ClassDeclaration ignore1 = + env.getClassDeclaration(idJavaLangError); + ClassDeclaration ignore2 = + env.getClassDeclaration(idJavaLangRuntimeException); + + for (Enumeration e = thrown.keys(); e.hasMoreElements();) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + ClassDefinition def = c.getClassDefinition(env); + if (def.subClassOf(env, ignore1) + || def.subClassOf(env, ignore2)) { + continue; + } + + boolean ok = false; + if (!isInitializer()) { + for (int i = 0 ; i < exp.length ; i++) { + if (def.subClassOf(env, exp[i])) { + ok = true; + } + } + } + if (!ok) { + Node n = (Node)thrown.get(c); + long where = n.getWhere(); + String errorMsg; + + if (isConstructor()) { + if (where == + getClassDefinition().getWhere()) { + + // If this message is being generated for + // a default constructor, we should give + // a different error message. Currently + // we check for this by seeing if the + // constructor has the same "where" as + // its class. This is a bit kludgy, but + // works. (bug id 4034836) + errorMsg = "def.constructor.exception"; + } else { + // Constructor with uncaught exception. + errorMsg = "constructor.exception"; + } + } else if (isInitializer()) { + // Initializer with uncaught exception. + errorMsg = "initializer.exception"; + } else { + // Method with uncaught exception. + errorMsg = "uncaught.exception"; + } + env.error(where, errorMsg, c.getName()); + } + } + } else { + Hashtable thrown = new Hashtable<>(3); // small & throw-away + Expression val = (Expression)getValue(); + + vset = val.checkInitializer(env, ctx, vset, + getType(), thrown); + setValue(val.convert(env, ctx, getType(), val)); + + // Complain about static final members of inner classes that + // do not have an initializer that is a constant expression. + // In general, static members are not permitted for inner + // classes, but an exception is made for named constants. + // Other cases of static members, including non-final ones, + // are handled in 'SourceClass'. Part of fix for 4095568. + if (isStatic() && isFinal() && !clazz.isTopLevel()) { + if (!((Expression)getValue()).isConstant()) { + env.error(where, "static.inner.field", getName(), this); + setValue(null); + } + } + + + // Both RuntimeExceptions and Errors should be + // allowed in initializers. Fix for bug 4102541. + ClassDeclaration except = + env.getClassDeclaration(idJavaLangThrowable); + ClassDeclaration ignore1 = + env.getClassDeclaration(idJavaLangError); + ClassDeclaration ignore2 = + env.getClassDeclaration(idJavaLangRuntimeException); + + for (Enumeration e = thrown.keys(); e.hasMoreElements(); ) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + ClassDefinition def = c.getClassDefinition(env); + + if (!def.subClassOf(env, ignore1) + && !def.subClassOf(env, ignore2) + && def.subClassOf(env, except)) { + Node n = (Node)thrown.get(c); + env.error(n.getWhere(), + "initializer.exception", c.getName()); + } + } + } + if (env.dump()) { + getValue().print(System.out); + System.out.println(); + } + } + status = getClassDefinition().getError() ? ERROR : CHECKED; + } + + + // Initializers (static and instance) must be able to complete normally. + if (isInitializer() && vset.isDeadEnd()) { + env.error(where, "init.no.normal.completion"); + vset = vset.clearDeadEnd(); + } + + return vset; + } + + // helper to check(): synthesize a missing super() call + private Expression getDefaultSuperCall(Environment env) { + Expression se = null; + ClassDefinition sclass = getClassDefinition().getSuperClass().getClassDefinition(); + // does the superclass constructor require an enclosing instance? + ClassDefinition reqc = (sclass == null) ? null + : sclass.isTopLevel() ? null + : sclass.getOuterClass(); + ClassDefinition thisc = getClassDefinition(); + if (reqc != null && !Context.outerLinkExists(env, reqc, thisc)) { + se = new SuperExpression(where, new NullExpression(where)); + env.error(where, "no.default.outer.arg", reqc, getClassDefinition()); + } + if (se == null) { + se = new SuperExpression(where); + } + return new MethodExpression(where, se, idInit, new Expression[0]); + } + + /** + * Inline the field + */ + void inline(Environment env) throws ClassNotFound { + switch (status) { + case PARSED: + check(env); + inline(env); + break; + + case CHECKED: + if (env.dump()) { + System.out.println("[inline field " + getClassDeclaration().getName() + "." + getName() + "]"); + } + status = INLINING; + env = new Environment(env, this); + + if (isMethod()) { + if ((!isNative()) && (!isAbstract())) { + Statement s = (Statement)getValue(); + Context ctx = new Context((Context)null, this); + for (Enumeration e = args.elements() ; e.hasMoreElements() ;) { + LocalMember local = (LocalMember)e.nextElement(); + ctx.declare(env, local); + } + setValue(s.inline(env, ctx)); + } + } else if (isInnerClass()) { + // some classes are checked and inlined separately + ClassDefinition nc = getInnerClass(); + if (nc instanceof SourceClass && !nc.isLocal() + && nc.isInsideLocal()) { + status = INLINING; + ((SourceClass)nc).inlineLocalClass(env); + } + status = INLINED; + break; + } else { + if (getValue() != null) { + Context ctx = new Context((Context)null, this); + if (!isStatic()) { + // Cf. "thisArg" in SourceClass.checkMembers(). + Context ctxInst = new Context(ctx, this); + LocalMember thisArg = + ((SourceClass)clazz).getThisArgument(); + ctxInst.declare(env, thisArg); + setValue(((Expression)getValue()) + .inlineValue(env, ctxInst)); + } else { + setValue(((Expression)getValue()) + .inlineValue(env, ctx)); + } + } + } + if (env.dump()) { + System.out.println("[inlined field " + getClassDeclaration().getName() + "." + getName() + "]"); + if (getValue() != null) { + getValue().print(System.out); + System.out.println(); + } else { + System.out.println(""); + } + } + status = INLINED; + break; + } + } + + /** + * Get the value of the field (or null if the value can't be determined) + */ + public Node getValue(Environment env) throws ClassNotFound { + Node value = getValue(); + if (value != null && status != INLINED) { + // be sure to get the imports right: + env = ((SourceClass)clazz).setupEnv(env); + inline(env); + value = (status == INLINED) ? getValue() : null; + } + return value; + } + + public boolean isInlineable(Environment env, boolean fromFinal) throws ClassNotFound { + if (super.isInlineable(env, fromFinal)) { + getValue(env); + return (status == INLINED) && !getClassDefinition().getError(); + } + return false; + } + + + /** + * Get the initial value of the field + */ + public Object getInitialValue() { + if (isMethod() || (getValue() == null) || (!isFinal()) || (status != INLINED)) { + return null; + } + return ((Expression)getValue()).getValue(); + } + + /** + * Generate code + */ + public void code(Environment env, Assembler asm) throws ClassNotFound { + switch (status) { + case PARSED: + check(env); + code(env, asm); + return; + + case CHECKED: + inline(env); + code(env, asm); + return; + + case INLINED: + // Actually generate code + if (env.dump()) { + System.out.println("[code field " + getClassDeclaration().getName() + "." + getName() + "]"); + } + if (isMethod() && (!isNative()) && (!isAbstract())) { + env = new Environment(env, this); + Context ctx = new Context((Context)null, this); + Statement s = (Statement)getValue(); + + for (Enumeration e = args.elements() ; e.hasMoreElements() ; ) { + LocalMember f = (LocalMember)e.nextElement(); + ctx.declare(env, f); + //ctx.declare(env, (LocalMember)e.nextElement()); + } + + /* + if (isConstructor() && ((s == null) || (s.firstConstructor() == null))) { + ClassDeclaration c = getClassDefinition().getSuperClass(); + if (c != null) { + MemberDefinition field = c.getClassDefinition(env).matchMethod(env, getClassDefinition(), idInit); + asm.add(getWhere(), opc_aload, new Integer(0)); + asm.add(getWhere(), opc_invokespecial, field); + asm.add(getWhere(), opc_pop); + } + + // Output initialization code + for (MemberDefinition f = getClassDefinition().getFirstMember() ; f != null ; f = f.getNextMember()) { + if (!f.isStatic()) { + f.codeInit(env, ctx, asm); + } + } + } + */ + if (s != null) { + s.code(env, ctx, asm); + } + if (getType().getReturnType().isType(TC_VOID) && !isInitializer()) { + asm.add(getWhere(), opc_return, true); + } + } + return; + } + } + + public void codeInit(Environment env, Context ctx, Assembler asm) throws ClassNotFound { + if (isMethod()) { + return; + } + switch (status) { + case PARSED: + check(env); + codeInit(env, ctx, asm); + return; + + case CHECKED: + inline(env); + codeInit(env, ctx, asm); + return; + + case INLINED: + // Actually generate code + if (env.dump()) { + System.out.println("[code initializer " + getClassDeclaration().getName() + "." + getName() + "]"); + } + if (getValue() != null) { + Expression e = (Expression)getValue(); + // The JLS Section 8.5 specifies that static (non-final) + // initializers should be executed in textual order. Eliding + // initializations to default values can interfere with this, + // so the tests for !e.equalsDefault() have been eliminated, + // below. + if (isStatic()) { + if (getInitialValue() == null) { + // removed: && !e.equalsDefault()) { + e.codeValue(env, ctx, asm); + asm.add(getWhere(), opc_putstatic, this); + } + } else { // removed: if (!e.equalsDefault()) { + // This code doesn't appear to be reached for + // instance initializers. Code for these is generated + // in the makeVarInits() method of the class + // MethodExpression. + asm.add(getWhere(), opc_aload, 0); + e.codeValue(env, ctx, asm); + asm.add(getWhere(), opc_putfield, this); + } + } + return; + } + } + + /** + * Print for debugging + */ + public void print(PrintStream out) { + super.print(out); + if (getValue() != null) { + getValue().print(out); + out.println(); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AddExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AddExpression.java new file mode 100644 index 000000000..7aaace1dc --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AddExpression.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AddExpression extends BinaryArithmeticExpression { + /** + * constructor + */ + public AddExpression(long where, Expression left, Expression right) { + super(ADD, where, left, right); + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + if ((left.type == Type.tString) && !right.type.isType(TC_VOID)) { + type = Type.tString; + return; + } else if ((right.type == Type.tString) && !left.type.isType(TC_VOID)) { + type = Type.tString; + return; + } + super.selectType(env, ctx, tm); + } + + public boolean isNonNull() { + // an addition expression cannot yield a null reference as a result + return true; + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a + b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a + b); + } + Expression eval(float a, float b) { + return new FloatExpression(where, a + b); + } + Expression eval(double a, double b) { + return new DoubleExpression(where, a + b); + } + Expression eval(String a, String b) { + return new StringExpression(where, a + b); + } + + /** + * Inline the value of an AddExpression. If this AddExpression + * represents a concatenation of compile-time constant strings, + * dispatch to the special method inlineValueSB, which handles + * the inlining more efficiently. + */ + public Expression inlineValue(Environment env, Context ctx) { + if (type == Type.tString && isConstant()) { + StringBuffer buffer = inlineValueSB(env, ctx, new StringBuffer()); + if (buffer != null) { + // We were able to evaluate the String concatenation. + return new StringExpression(where, buffer.toString()); + } + } + // For some reason inlinValueSB() failed to produce a value. + // Use the older, less efficient, inlining mechanism. + return super.inlineValue(env, ctx); + } + + /** + * Attempt to evaluate this expression. If this expression + * yields a value, append it to the StringBuffer `buffer'. + * If this expression cannot be evaluated at this time (for + * example if it contains a division by zero, a non-constant + * subexpression, or a subexpression which "refuses" to evaluate) + * then return `null' to indicate failure. + * + * It is anticipated that this method will be called to evaluate + * concatenations of compile-time constant strings. The call + * originates from AddExpression#inlineValue(). + * + * This method does not use associativity to good effect in + * folding string concatenations. This is room for improvement. + * + * ------------- + * + * A bit of history: this method was added because an + * expression like... + * + * "a" + "b" + "c" + "d" + * + * ...was evaluated at compile-time as... + * + * (new StringBuffer((new StringBuffer("a")).append("b").toString())). + * append((new StringBuffer("c")).append("d").toString()).toString() + * + * Alex Garthwaite, in profiling the memory allocation of the + * compiler, noticed this and suggested that the method inlineValueSB() + * be added to evaluate constant string concatenations in a more + * efficient manner. The compiler now builds the string in a + * top-down fashion, by accumulating the result in a StringBuffer + * which is allocated once and passed in as a parameter. The new + * evaluation scheme is equivalent to... + * + * (new StringBuffer("a")).append("b").append("c").append("d") + * .toString() + * + * ...which is more efficient. Since then, the code has been modified + * to fix certain problems. Now, for example, it can return `null' + * when it encounters a concatenation which it is not able to + * evaluate. + * + * See also Expression#inlineValueSB() and ExprExpression#inlineValueSB(). + */ + protected StringBuffer inlineValueSB(Environment env, + Context ctx, + StringBuffer buffer) { + if (type != Type.tString) { + // This isn't a concatenation. It is actually an addition + // of some sort. Call the generic inlineValueSB() + return super.inlineValueSB(env, ctx, buffer); + } + + buffer = left.inlineValueSB(env, ctx, buffer); + if (buffer != null) { + buffer = right.inlineValueSB(env, ctx, buffer); + } + return buffer; + } + + /** + * Simplify + */ + Expression simplify() { + if (!type.isType(TC_CLASS)) { + // Can't simplify floating point add because of -0.0 strangeness + if (type.inMask(TM_INTEGER)) { + if (left.equals(0)) { + return right; + } + if (right.equals(0)) { + return left; + } + } + } else if (right.type.isType(TC_NULL)) { + right = new StringExpression(right.where, "null"); + } else if (left.type.isType(TC_NULL)) { + left = new StringExpression(left.where, "null"); + } + return this; + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + return (type.isType(TC_CLASS) ? 12 : 1) + + left.costInline(thresh, env, ctx) + + right.costInline(thresh, env, ctx); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iadd + type.getTypeCodeOffset()); + } + + /** + * Convert this expression to a string and append it to the string + * buffer on the top of the stack. + * If the needBuffer argument is true, the string buffer needs to be + * created, initialized, and pushed on the stack, first. + */ + void codeAppend(Environment env, Context ctx, Assembler asm, + ClassDeclaration sbClass, boolean needBuffer) + throws ClassNotFound, AmbiguousMember { + if (type.isType(TC_CLASS)) { + left.codeAppend(env, ctx, asm, sbClass, needBuffer); + right.codeAppend(env, ctx, asm, sbClass, false); + } else { + super.codeAppend(env, ctx, asm, sbClass, needBuffer); + } + } + + public void codeValue(Environment env, Context ctx, Assembler asm) { + if (type.isType(TC_CLASS)) { + try { + // optimize (""+foo) or (foo+"") to String.valueOf(foo) + if (left.equals("")) { + right.codeValue(env, ctx, asm); + right.ensureString(env, ctx, asm); + return; + } + if (right.equals("")) { + left.codeValue(env, ctx, asm); + left.ensureString(env, ctx, asm); + return; + } + + ClassDeclaration sbClass = + env.getClassDeclaration(idJavaLangStringBuffer); + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + // Create the string buffer and append to it. + codeAppend(env, ctx, asm, sbClass, true); + // Convert the string buffer to a string + MemberDefinition f = + sbClass.getClassDefinition(env).matchMethod(env, + sourceClass, + idToString); + asm.add(where, opc_invokevirtual, f); + } catch (ClassNotFound e) { + throw new CompilerError(e); + } catch (AmbiguousMember e) { + throw new CompilerError(e); + } + } else { + super.codeValue(env, ctx, asm); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AndExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AndExpression.java new file mode 100644 index 000000000..ca87f42f4 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AndExpression.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AndExpression extends BinaryLogicalExpression { + /** + * constructor + */ + public AndExpression(long where, Expression left, Expression right) { + super(AND, where, left, right); + } + + /* + * Check an "and" expression. + * + * cvars is modified so that + * cvar.vsTrue indicates variables with a known value if + * both the left and right hand side are true + * cvars.vsFalse indicates variables with a known value + * either the left or right hand side is false + */ + public void checkCondition(Environment env, Context ctx, Vset vset, + Hashtable exp, ConditionVars cvars) { + // Find out when the left side is true/false + left.checkCondition(env, ctx, vset, exp, cvars); + left = convert(env, ctx, Type.tBoolean, left); + Vset vsTrue = cvars.vsTrue.copy(); + Vset vsFalse = cvars.vsFalse.copy(); + + // Only look at the right side if the left side is true + right.checkCondition(env, ctx, vsTrue, exp, cvars); + right = convert(env, ctx, Type.tBoolean, right); + + // cvars.vsTrue already reports when both returned true + // cvars.vsFalse must be set to either the left or right side + // returning false + cvars.vsFalse = cvars.vsFalse.join(vsFalse); + } + + /** + * Evaluate + */ + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a && b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.equals(true)) { + return right; + } + if (right.equals(false)) { + // Preserve effects of left argument. + return new CommaExpression(where, left, right).simplify(); + } + if (right.equals(true)) { + return left; + } + if (left.equals(false)) { + return left; + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + if (whenTrue) { + Label lbl2 = new Label(); + left.codeBranch(env, ctx, asm, lbl2, false); + right.codeBranch(env, ctx, asm, lbl, true); + asm.add(lbl2); + } else { + left.codeBranch(env, ctx, asm, lbl, false); + right.codeBranch(env, ctx, asm, lbl, false); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ArrayAccessExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ArrayAccessExpression.java new file mode 100644 index 000000000..797e946cf --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ArrayAccessExpression.java @@ -0,0 +1,256 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ArrayAccessExpression extends UnaryExpression { + + /** + * The index expression for the array access. Note that + * ArrayAccessExpression also `moonlights' as a structure for + * storing array types (like Object[]) which are used as part + * of cast expressions. For properly formed array types, the + * value of index is null. We need to be on the lookout for + * null indices in true array accesses, and non-null indices + * in array types. We also need to make sure general purpose + * methods (like copyInline(), which is called for both) are + * prepared to handle either null or non-null indices. + */ + Expression index; + + /** + * constructor + */ + public ArrayAccessExpression(long where, Expression right, Expression index) { + super(ARRAYACCESS, where, Type.tError, right); + this.index = index; + } + + /** + * Check expression type + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = right.checkValue(env, ctx, vset, exp); + if (index == null) { + env.error(where, "array.index.required"); + return vset; + } + vset = index.checkValue(env, ctx, vset, exp); + index = convert(env, ctx, Type.tInt, index); + + if (!right.type.isType(TC_ARRAY)) { + if (!right.type.isType(TC_ERROR)) { + env.error(where, "not.array", right.type); + } + return vset; + } + + type = right.type.getElementType(); + return vset; + } + + public Vset checkAmbigName(Environment env, Context ctx, + Vset vset, Hashtable exp, + UnaryExpression loc) { + if (index == null) { + vset = right.checkAmbigName(env, ctx, vset, exp, this); + if (right.type == Type.tPackage) { + FieldExpression.reportFailedPackagePrefix(env, right); + return vset; + } + + // Nope. Is this field expression a type? + if (right instanceof TypeExpression) { + Type atype = Type.tArray(right.type); + loc.right = new TypeExpression(where, atype); + return vset; + } + + env.error(where, "array.index.required"); + return vset; + } + return super.checkAmbigName(env, ctx, vset, exp, loc); + } + + /* + * Check the array if it appears on the LHS of an assignment + */ + public Vset checkLHS(Environment env, Context ctx, + Vset vset, Hashtable exp) { + return checkValue(env, ctx, vset, exp); + } + + /* + * Check the array if it appears on the LHS of an op= expression + */ + public Vset checkAssignOp(Environment env, Context ctx, + Vset vset, Hashtable exp, Expression outside) { + return checkValue(env, ctx, vset, exp); + } + + /** + * An array access expression never requires the use of an access method to perform + * an assignment to an array element, though an access method may be required to + * fetch the array object itself. + */ + public FieldUpdater getAssigner(Environment env, Context ctx) { + return null; + } + + /** + * An array access expression never requires a field updater. + */ + public FieldUpdater getUpdater(Environment env, Context ctx) { + return null; + } + + /** + * Convert to a type + */ + Type toType(Environment env, Context ctx) { + return toType(env, right.toType(env, ctx)); + } + Type toType(Environment env, Type t) { + if (index != null) { + env.error(index.where, "array.dim.in.type"); + } + return Type.tArray(t); + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + // It isn't possible to simply replace an array access + // with a CommaExpression as happens with many binary + // operators, because array accesses may have side effects + // such as NullPointerException or IndexOutOfBoundsException. + right = right.inlineValue(env, ctx); + index = index.inlineValue(env, ctx); + return this; + } + public Expression inlineValue(Environment env, Context ctx) { + // inlineValue() should not end up being called when the index is + // null. If it is null, we let this method fail with a + // NullPointerException. + + right = right.inlineValue(env, ctx); + index = index.inlineValue(env, ctx); + return this; + } + public Expression inlineLHS(Environment env, Context ctx) { + return inlineValue(env, ctx); + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + ArrayAccessExpression e = (ArrayAccessExpression)clone(); + e.right = right.copyInline(ctx); + if (index == null) { + // The index can be null when this node is being used to + // represent a type (e.g. Object[]) used in a cast expression. + // We need to copy such structures without complaint. + e.index = null; + } else { + e.index = index.copyInline(ctx); + } + return e; + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + // costInline() should not end up being called when the index is + // null. If it is null, we let this method fail with a + // NullPointerException. + + return 1 + right.costInline(thresh, env, ctx) + + index.costInline(thresh, env, ctx); + } + + /** + * Code + */ + int codeLValue(Environment env, Context ctx, Assembler asm) { + // codeLValue() should not end up being called when the index is + // null. If it is null, we let this method fail with a + // NullPointerException. + + right.codeValue(env, ctx, asm); + index.codeValue(env, ctx, asm); + return 2; + } + void codeLoad(Environment env, Context ctx, Assembler asm) { + switch (type.getTypeCode()) { + case TC_BOOLEAN: + case TC_BYTE: + asm.add(where, opc_baload); + break; + case TC_CHAR: + asm.add(where, opc_caload); + break; + case TC_SHORT: + asm.add(where, opc_saload); + break; + default: + asm.add(where, opc_iaload + type.getTypeCodeOffset()); + } + } + void codeStore(Environment env, Context ctx, Assembler asm) { + switch (type.getTypeCode()) { + case TC_BOOLEAN: + case TC_BYTE: + asm.add(where, opc_bastore); + break; + case TC_CHAR: + asm.add(where, opc_castore); + break; + case TC_SHORT: + asm.add(where, opc_sastore); + break; + default: + asm.add(where, opc_iastore + type.getTypeCodeOffset()); + } + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeLValue(env, ctx, asm); + codeLoad(env, ctx, asm); + } + + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + right.print(out); + out.print(" "); + if (index != null) { + index.print(out); + } else { + out.print(""); + } + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ArrayExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ArrayExpression.java new file mode 100644 index 000000000..fb914c0c9 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ArrayExpression.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.*; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ArrayExpression extends NaryExpression { + /** + * Constructor + */ + public ArrayExpression(long where, Expression args[]) { + super(ARRAY, where, Type.tError, null, args); + } + + /** + * Check expression type + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + env.error(where, "invalid.array.expr"); + return vset; + } + public Vset checkInitializer(Environment env, Context ctx, Vset vset, Type t, Hashtable exp) { + if (!t.isType(TC_ARRAY)) { + if (!t.isType(TC_ERROR)) { + env.error(where, "invalid.array.init", t); + } + return vset; + } + type = t; + t = t.getElementType(); + for (int i = 0 ; i < args.length ; i++) { + vset = args[i].checkInitializer(env, ctx, vset, t, exp); + args[i] = convert(env, ctx, t, args[i]); + } + return vset; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + Expression e = null; + for (int i = 0 ; i < args.length ; i++) { + args[i] = args[i].inline(env, ctx); + if (args[i] != null) { + e = (e == null) ? args[i] : new CommaExpression(where, e, args[i]); + } + } + return e; + } + public Expression inlineValue(Environment env, Context ctx) { + for (int i = 0 ; i < args.length ; i++) { + args[i] = args[i].inlineValue(env, ctx); + } + return this; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + int t = 0; + asm.add(where, opc_ldc, args.length); + switch (type.getElementType().getTypeCode()) { + case TC_BOOLEAN: asm.add(where, opc_newarray, T_BOOLEAN); break; + case TC_BYTE: asm.add(where, opc_newarray, T_BYTE); break; + case TC_SHORT: asm.add(where, opc_newarray, T_SHORT); break; + case TC_CHAR: asm.add(where, opc_newarray, T_CHAR); break; + case TC_INT: asm.add(where, opc_newarray, T_INT); break; + case TC_LONG: asm.add(where, opc_newarray, T_LONG); break; + case TC_FLOAT: asm.add(where, opc_newarray, T_FLOAT); break; + case TC_DOUBLE: asm.add(where, opc_newarray, T_DOUBLE); break; + + case TC_ARRAY: + asm.add(where, opc_anewarray, type.getElementType()); + break; + + case TC_CLASS: + asm.add(where, opc_anewarray, env.getClassDeclaration(type.getElementType())); + break; + + default: + throw new CompilerError("codeValue"); + } + + for (int i = 0 ; i < args.length ; i++) { + + // If the array element is the default initial value, + // then don't bother generating code for this element. + if (args[i].equalsDefault()) continue; + + asm.add(where, opc_dup); + asm.add(where, opc_ldc, i); + args[i].codeValue(env, ctx, asm); + switch (type.getElementType().getTypeCode()) { + case TC_BOOLEAN: + case TC_BYTE: + asm.add(where, opc_bastore); + break; + case TC_CHAR: + asm.add(where, opc_castore); + break; + case TC_SHORT: + asm.add(where, opc_sastore); + break; + default: + asm.add(where, opc_iastore + type.getElementType().getTypeCodeOffset()); + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignAddExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignAddExpression.java new file mode 100644 index 000000000..e6aa91d9e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignAddExpression.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignAddExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignAddExpression(long where, Expression left, Expression right) { + super(ASGADD, where, left, right); + } + + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return type.isType(TC_CLASS) ? 25 : super.costInline(thresh, env, ctx); + } + + /** + * Code + */ + void code(Environment env, Context ctx, Assembler asm, boolean valNeeded) { + if (itype.isType(TC_CLASS)) { + // Create code for String += + try { + // Create new string buffer. + Type argTypes[] = {Type.tString}; + ClassDeclaration c = + env.getClassDeclaration(idJavaLangStringBuffer); + + if (updater == null) { + + // No access method is needed. + + asm.add(where, opc_new, c); + asm.add(where, opc_dup); + // stack: ... + int depth = left.codeLValue(env, ctx, asm); + codeDup(env, ctx, asm, depth, 2); // copy past 2 string buffers + // stack: ...[][] + // where isn't yet initialized, and the + // has length depth and is whatever is needed to get/set the + // value + left.codeLoad(env, ctx, asm); + left.ensureString(env, ctx, asm); // Why is this needed? + // stack: ...[] + // call .(String) + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + MemberDefinition f = c.getClassDefinition(env) + .matchMethod(env, sourceClass, + idInit, argTypes); + asm.add(where, opc_invokespecial, f); + // stack: ...[] + // .append(value).toString() + right.codeAppend(env, ctx, asm, c, false); + f = c.getClassDefinition(env) + .matchMethod(env, sourceClass, idToString); + asm.add(where, opc_invokevirtual, f); + // stack: ...[] + // dup the string past the , if necessary. + if (valNeeded) { + codeDup(env, ctx, asm, Type.tString.stackSize(), depth); + // stack: ...[] + } + // store + left.codeStore(env, ctx, asm); + + } else { + + // Access method is required. + // (Handling this case fixes 4102566.) + + updater.startUpdate(env, ctx, asm, false); + // stack: ...[] + left.ensureString(env, ctx, asm); // Why is this needed? + asm.add(where, opc_new, c); + // stack: ...[] + asm.add(where, opc_dup_x1); + // stack: ...[] + asm.add(where, opc_swap); + // stack: ...[] + // call .(String) + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + MemberDefinition f = c.getClassDefinition(env) + .matchMethod(env, sourceClass, + idInit, argTypes); + asm.add(where, opc_invokespecial, f); + // stack: ...[] + // .append(value).toString() + right.codeAppend(env, ctx, asm, c, false); + f = c.getClassDefinition(env) + .matchMethod(env, sourceClass, idToString); + asm.add(where, opc_invokevirtual, f); + // stack: .. [] + updater.finishUpdate(env, ctx, asm, valNeeded); + + } + + } catch (ClassNotFound e) { + throw new CompilerError(e); + } catch (AmbiguousMember e) { + throw new CompilerError(e); + } + } else { + super.code(env, ctx, asm, valNeeded); + } + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iadd + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitAndExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitAndExpression.java new file mode 100644 index 000000000..6b737aa64 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitAndExpression.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignBitAndExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignBitAndExpression(long where, Expression left, Expression right) { + super(ASGBITAND, where, left, right); + } + + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iand + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitOrExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitOrExpression.java new file mode 100644 index 000000000..2da8baa0b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitOrExpression.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignBitOrExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignBitOrExpression(long where, Expression left, Expression right) { + super(ASGBITOR, where, left, right); + } + + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ior + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitXorExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitXorExpression.java new file mode 100644 index 000000000..4062b135d --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignBitXorExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignBitXorExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignBitXorExpression(long where, Expression left, Expression right) { + super(ASGBITXOR, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ixor + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignDivideExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignDivideExpression.java new file mode 100644 index 000000000..9998715e3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignDivideExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignDivideExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignDivideExpression(long where, Expression left, Expression right) { + super(ASGDIV, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_idiv + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignExpression.java new file mode 100644 index 000000000..5633408b5 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignExpression.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignExpression extends BinaryAssignExpression { + + private FieldUpdater updater = null; + + /** + * Constructor + */ + public AssignExpression(long where, Expression left, Expression right) { + super(ASSIGN, where, left, right); + } + + /** + * Check an assignment expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + if (left instanceof IdentifierExpression) { + // we don't want to mark an identifier as having a value + // until having evaluated the right-hand side + vset = right.checkValue(env, ctx, vset, exp); + vset = left.checkLHS(env, ctx, vset, exp); + } else { + // normally left to right evaluation. + vset = left.checkLHS(env, ctx, vset, exp); + vset = right.checkValue(env, ctx, vset, exp); + } + type = left.type; + right = convert(env, ctx, type, right); + + // Get field updater (access method) if needed, else null. + updater = left.getAssigner(env, ctx); + + return vset; + } + + /** + * Inline + */ + public Expression inlineValue(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineValue(env, ctx); + // Must be 'inlineLHS' here. But compare with similar case in + // 'AssignOpExpression' and 'IncDecExpression', which needs 'inlineValue'. + left = left.inlineLHS(env, ctx); + right = right.inlineValue(env, ctx); + if (updater != null) { + updater = updater.inline(env, ctx); + } + return this; + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + if (implementation != null) + return implementation.copyInline(ctx); + AssignExpression e = (AssignExpression)clone(); + e.left = left.copyInline(ctx); + e.right = right.copyInline(ctx); + if (updater != null) { + e.updater = updater.copyInline(ctx); + } + return e; + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + /*----------* + return 2 + super.costInline(thresh, env, ctx); + *----------*/ + return (updater != null) + // Cost of rhs expression + cost of access method call. + // Access method call cost includes lhs cost. + ? right.costInline(thresh, env, ctx) + + updater.costInline(thresh, env, ctx, false) + // Cost of rhs expression + cost of lhs expression + + // cost of store instruction. + : right.costInline(thresh, env, ctx) + + left.costInline(thresh, env, ctx) + 2; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + if (updater == null) { + // Field is directly accessible. + int depth = left.codeLValue(env, ctx, asm); + right.codeValue(env, ctx, asm); + codeDup(env, ctx, asm, right.type.stackSize(), depth); + left.codeStore(env, ctx, asm); + } else { + // Must use access method. + // Left operand is always a 'FieldExpression', or + // is rewritten as one via 'implementation'. + updater.startAssign(env, ctx, asm); + right.codeValue(env, ctx, asm); + updater.finishAssign(env, ctx, asm, true); + } + } + + public void code(Environment env, Context ctx, Assembler asm) { + if (updater == null) { + // Field is directly accessible. + left.codeLValue(env, ctx, asm); + right.codeValue(env, ctx, asm); + left.codeStore(env, ctx, asm); + } else { + // Must use access method. + // Left operand is always a 'FieldExpression', or + // is rewritten as one via 'implementation'. + updater.startAssign(env, ctx, asm); + right.codeValue(env, ctx, asm); + updater.finishAssign(env, ctx, asm, false); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignMultiplyExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignMultiplyExpression.java new file mode 100644 index 000000000..78579ea60 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignMultiplyExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignMultiplyExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignMultiplyExpression(long where, Expression left, Expression right) { + super(ASGMUL, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_imul + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignOpExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignOpExpression.java new file mode 100644 index 000000000..139180450 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignOpExpression.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public abstract +class AssignOpExpression extends BinaryAssignExpression { + protected Type itype; // Type of intermediate result, before assigning + final int NOINC = Integer.MAX_VALUE; + + protected FieldUpdater updater = null; // Used also in 'AssignAddExpression'. + + /** + * Constructor + */ + public AssignOpExpression(int op, long where, Expression left, Expression right) { + super(op, where, left, right); + } + + /** + * Select the type + * + */ + @SuppressWarnings("fallthrough") + final void selectType(Environment env, Context ctx, int tm) { + Type rtype = null; // special conversion type for RHS + switch(op) { + case ASGADD: + if (left.type == Type.tString) { + if (right.type == Type.tVoid) { + // The type of the right hand side can be + // anything except void. Fix for 4119864. + env.error(where, "incompatible.type", + opNames[op], Type.tVoid, Type.tString); + type = Type.tError; + } else { + type = itype = Type.tString; + } + return; + } + /* Fall through */ + case ASGDIV: case ASGMUL: case ASGSUB: case ASGREM: + if ((tm & TM_DOUBLE) != 0) { + itype = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + itype = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + itype = Type.tLong; + } else { + itype = Type.tInt; + } + break; + + case ASGBITAND: case ASGBITOR: case ASGBITXOR: + if ((tm & TM_BOOLEAN) != 0) { + itype = Type.tBoolean; + } else if ((tm & TM_LONG) != 0) { + itype = Type.tLong; + } else { + itype = Type.tInt; + } + break; + + case ASGLSHIFT: case ASGRSHIFT: case ASGURSHIFT: + rtype = Type.tInt; + + // Fix for bug 4134459. + // We allow any integral type (even long) to + // be the right hand side of a shift operation. + if (right.type.inMask(TM_INTEGER)) { + right = new ConvertExpression(where, Type.tInt, right); + } + // The intermediate type of the expression is the + // type of the left hand side after undergoing + // unary (not binary) type promotion. We ignore + // tm -- it contains information about both left + // and right hand sides -- and we compute the + // type only from the type of the lhs. + if (left.type == Type.tLong) { + itype = Type.tLong; + } else { + itype = Type.tInt; + } + + break; + + default: + throw new CompilerError("Bad assignOp type: " + op); + } + if (rtype == null) { + rtype = itype; + } + right = convert(env, ctx, rtype, right); + // The result is always the type of the left operand. + + type = left.type; + } + + + /** + * Get the increment, return NOINC if an increment is not possible + */ + int getIncrement() { + if ((left.op == IDENT) && type.isType(TC_INT) && (right.op == INTVAL)) + if ((op == ASGADD) || (op == ASGSUB)) + if (((IdentifierExpression)left).field.isLocal()) { + int val = ((IntExpression)right).value; + if (op == ASGSUB) + val = -val; + if (val == (short)val) + return val; + } + return NOINC; + } + + + /** + * Check an assignment expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = left.checkAssignOp(env, ctx, vset, exp, this); + vset = right.checkValue(env, ctx, vset, exp); + int tm = left.type.getTypeMask() | right.type.getTypeMask(); + if ((tm & TM_ERROR) != 0) { + return vset; + } + selectType(env, ctx, tm); + if (!type.isType(TC_ERROR)) { + convert(env, ctx, itype, left); + } + updater = left.getUpdater(env, ctx); // Must be called after 'checkAssignOp'. + return vset; + } + + /** + * Inline + */ + public Expression inlineValue(Environment env, Context ctx) { + // Why not inlineLHS? But that does not work. + left = left.inlineValue(env, ctx); + right = right.inlineValue(env, ctx); + if (updater != null) { + updater = updater.inline(env, ctx); + } + return this; + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + AssignOpExpression e = (AssignOpExpression)clone(); + e.left = left.copyInline(ctx); + e.right = right.copyInline(ctx); + if (updater != null) { + e.updater = updater.copyInline(ctx); + } + return e; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + /*----------* + return (getIncrement() != NOINC) + ? 2 + : (3 + super.costInline(thresh, env, ctx)); + *----------*/ + if (updater == null) { + return (getIncrement() != NOINC) + // Increment variable in place. Count 3 bytes for 'iinc'. + ? 3 + // Cost of rhs expression + cost of lhs expression + cost + // of load/op/store instructions. E.g.: iload = 1 or 2, + // istore = 1 or 2, iadd = 1. Cost could be higher if + // getfield/putfield or conversions needed, lower if rhs is + // a small constant. Costs are highly approximate. + : right.costInline(thresh, env, ctx) + + left.costInline(thresh, env, ctx) + 4; + } else { + // Cost of rhs expression + (2 * cost of access method call) + + // cost of operator. Does not account for cost of conversions, + // or duplications in value-needed context. + return right.costInline(thresh, env, ctx) + + updater.costInline(thresh, env, ctx, true) + 1; + } + } + + /** + * Code + */ + void code(Environment env, Context ctx, Assembler asm, boolean valNeeded) { + + // Handle cases in which a '+=' or '-=' operator can be optimized using + // the 'iinc' instruction. See also 'IncDecExpression.codeIncDec'. + // The 'iinc' instruction cannot be used if an access method call is required. + int val = getIncrement(); + if (val != NOINC && updater == null) { + int v = ((LocalMember)((IdentifierExpression)left).field).number; + int[] operands = { v, val }; + asm.add(where, opc_iinc, operands); + if (valNeeded) { + left.codeValue(env, ctx, asm); + } + return; + } + + if (updater == null) { + // Field is directly accessible. + int depth = left.codeLValue(env, ctx, asm); + codeDup(env, ctx, asm, depth, 0); + left.codeLoad(env, ctx, asm); + codeConversion(env, ctx, asm, left.type, itype); + right.codeValue(env, ctx, asm); + codeOperation(env, ctx, asm); + codeConversion(env, ctx, asm, itype, type); + if (valNeeded) { + codeDup(env, ctx, asm, type.stackSize(), depth); + } + left.codeStore(env, ctx, asm); + } else { + // Must use access methods. + updater.startUpdate(env, ctx, asm, false); + codeConversion(env, ctx, asm, left.type, itype); + right.codeValue(env, ctx, asm); + codeOperation(env, ctx, asm); + codeConversion(env, ctx, asm, itype, type); + updater.finishUpdate(env, ctx, asm, valNeeded); + } + } + + public void codeValue(Environment env, Context ctx, Assembler asm) { + code(env, ctx, asm, true); + } + public void code(Environment env, Context ctx, Assembler asm) { + code(env, ctx, asm, false); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + left.print(out); + out.print(" "); + right.print(out); + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignRemainderExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignRemainderExpression.java new file mode 100644 index 000000000..eede6e7d0 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignRemainderExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignRemainderExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignRemainderExpression(long where, Expression left, Expression right) { + super(ASGREM, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_irem + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignShiftLeftExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignShiftLeftExpression.java new file mode 100644 index 000000000..de8093cb7 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignShiftLeftExpression.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignShiftLeftExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignShiftLeftExpression(long where, Expression left, Expression right) { + super(ASGLSHIFT, where, left, right); + } + + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ishl + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignShiftRightExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignShiftRightExpression.java new file mode 100644 index 000000000..534aa70c0 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignShiftRightExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignShiftRightExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignShiftRightExpression(long where, Expression left, Expression right) { + super(ASGRSHIFT, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ishr + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignSubtractExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignSubtractExpression.java new file mode 100644 index 000000000..cda708d76 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignSubtractExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignSubtractExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignSubtractExpression(long where, Expression left, Expression right) { + super(ASGSUB, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_isub + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignUnsignedShiftRightExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignUnsignedShiftRightExpression.java new file mode 100644 index 000000000..6d97817ad --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/AssignUnsignedShiftRightExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class AssignUnsignedShiftRightExpression extends AssignOpExpression { + /** + * Constructor + */ + public AssignUnsignedShiftRightExpression(long where, Expression left, Expression right) { + super(ASGURSHIFT, where, left, right); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iushr + itype.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryArithmeticExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryArithmeticExpression.java new file mode 100644 index 000000000..19e5c85e9 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryArithmeticExpression.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BinaryArithmeticExpression extends BinaryExpression { + /** + * constructor + */ + public BinaryArithmeticExpression(int op, long where, Expression left, Expression right) { + super(op, where, left.type, left, right); + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + if ((tm & TM_DOUBLE) != 0) { + type = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + type = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + type = Type.tLong; + } else { + type = Type.tInt; + } + left = convert(env, ctx, type, left); + right = convert(env, ctx, type, right); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryAssignExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryAssignExpression.java new file mode 100644 index 000000000..f146edd69 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryAssignExpression.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BinaryAssignExpression extends BinaryExpression { + Expression implementation; + + /** + * Constructor + */ + BinaryAssignExpression(int op, long where, Expression left, Expression right) { + super(op, where, left.type, left, right); + } + + public Expression getImplementation() { + if (implementation != null) + return implementation; + return this; + } + + /** + * Order the expression based on precedence + */ + public Expression order() { + if (precedence() >= left.precedence()) { + UnaryExpression e = (UnaryExpression)left; + left = e.right; + e.right = order(); + return e; + } + return this; + } + + /** + * Check void expression + */ + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + return checkValue(env, ctx, vset, exp); + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + if (implementation != null) + return implementation.inline(env, ctx); + return inlineValue(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineValue(env, ctx); + left = left.inlineLHS(env, ctx); + right = right.inlineValue(env, ctx); + return this; + } + + public Expression copyInline(Context ctx) { + if (implementation != null) + return implementation.copyInline(ctx); + return super.copyInline(ctx); + } + + public int costInline(int thresh, Environment env, Context ctx) { + if (implementation != null) + return implementation.costInline(thresh, env, ctx); + return super.costInline(thresh, env, ctx); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryBitExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryBitExpression.java new file mode 100644 index 000000000..fdd6e5ede --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryBitExpression.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +abstract public +class BinaryBitExpression extends BinaryExpression { + /** + * constructor + */ + public BinaryBitExpression(int op, long where, Expression left, Expression right) { + super(op, where, left.type, left, right); + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + if ((tm & TM_BOOLEAN) != 0) { + type = Type.tBoolean; + } else if ((tm & TM_LONG) != 0) { + type = Type.tLong; + } else { + type = Type.tInt; + } + left = convert(env, ctx, type, left); + right = convert(env, ctx, type, right); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + left.codeValue(env, ctx, asm); + right.codeValue(env, ctx, asm); + codeOperation(env, ctx, asm); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryCompareExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryCompareExpression.java new file mode 100644 index 000000000..4fbdbd0ba --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryCompareExpression.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BinaryCompareExpression extends BinaryExpression { + /** + * constructor + */ + public BinaryCompareExpression(int op, long where, Expression left, Expression right) { + super(op, where, Type.tBoolean, left, right); + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + Type t = Type.tInt; + if ((tm & TM_DOUBLE) != 0) { + t = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + t = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + t = Type.tLong; + } + left = convert(env, ctx, t, left); + right = convert(env, ctx, t, right); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryEqualityExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryEqualityExpression.java new file mode 100644 index 000000000..331b136b2 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryEqualityExpression.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BinaryEqualityExpression extends BinaryExpression { + /** + * constructor + */ + public BinaryEqualityExpression(int op, long where, Expression left, Expression right) { + super(op, where, Type.tBoolean, left, right); + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + Type t; + if ((tm & TM_ERROR) != 0) { + // who cares. One of them is an error. + return; + } else if ((tm & (TM_CLASS | TM_ARRAY | TM_NULL)) != 0) { + try { + if (env.explicitCast(left.type, right.type) || + env.explicitCast(right.type, left.type)) { + return; + } + env.error(where, "incompatible.type", + left.type, left.type, right.type); + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, opNames[op]); + } + return; + } else if ((tm & TM_DOUBLE) != 0) { + t = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + t = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + t = Type.tLong; + } else if ((tm & TM_BOOLEAN) != 0) { + t = Type.tBoolean; + } else { + t = Type.tInt; + } + left = convert(env, ctx, t, left); + right = convert(env, ctx, t, right); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryExpression.java new file mode 100644 index 000000000..cc7921e0b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryExpression.java @@ -0,0 +1,230 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BinaryExpression extends UnaryExpression { + Expression left; + + /** + * Constructor + */ + BinaryExpression(int op, long where, Type type, Expression left, Expression right) { + super(op, where, type, right); + this.left = left; + } + + /** + * Order the expression based on precedence + */ + public Expression order() { + if (precedence() > left.precedence()) { + UnaryExpression e = (UnaryExpression)left; + left = e.right; + e.right = order(); + return e; + } + return this; + } + + /** + * Check a binary expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = left.checkValue(env, ctx, vset, exp); + vset = right.checkValue(env, ctx, vset, exp); + + int tm = left.type.getTypeMask() | right.type.getTypeMask(); + if ((tm & TM_ERROR) != 0) { + return vset; + } + selectType(env, ctx, tm); + + if (type.isType(TC_ERROR)) { + env.error(where, "invalid.args", opNames[op]); + } + return vset; + } + + /** + * Check if constant + */ + public boolean isConstant() { + switch (op) { + case MUL: + case DIV: + case REM: + case ADD: + case SUB: + case LSHIFT: + case RSHIFT: + case URSHIFT: + case LT: + case LE: + case GT: + case GE: + case EQ: + case NE: + case BITAND: + case BITXOR: + case BITOR: + case AND: + case OR: + return left.isConstant() && right.isConstant(); + } + return false; + } + /** + * Evaluate + */ + Expression eval(int a, int b) { + return this; + } + Expression eval(long a, long b) { + return this; + } + Expression eval(float a, float b) { + return this; + } + Expression eval(double a, double b) { + return this; + } + Expression eval(boolean a, boolean b) { + return this; + } + Expression eval(String a, String b) { + return this; + } + Expression eval() { + // See also the eval() code in BinaryShiftExpression.java. + if (left.op == right.op) { + switch (left.op) { + case BYTEVAL: + case CHARVAL: + case SHORTVAL: + case INTVAL: + return eval(((IntegerExpression)left).value, ((IntegerExpression)right).value); + case LONGVAL: + return eval(((LongExpression)left).value, ((LongExpression)right).value); + case FLOATVAL: + return eval(((FloatExpression)left).value, ((FloatExpression)right).value); + case DOUBLEVAL: + return eval(((DoubleExpression)left).value, ((DoubleExpression)right).value); + case BOOLEANVAL: + return eval(((BooleanExpression)left).value, ((BooleanExpression)right).value); + case STRINGVAL: + return eval(((StringExpression)left).value, ((StringExpression)right).value); + } + } + return this; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + left = left.inline(env, ctx); + right = right.inline(env, ctx); + return (left == null) ? right : new CommaExpression(where, left, right); + } + public Expression inlineValue(Environment env, Context ctx) { + left = left.inlineValue(env, ctx); + right = right.inlineValue(env, ctx); + try { + return eval().simplify(); + } catch (ArithmeticException e) { + // Got rid of this error message. It isn't illegal to + // have a program which does a constant division by + // zero. We return `this' to make the compiler to + // generate code here. + // (bugs 4019304, 4089107). + // + // env.error(where, "arithmetic.exception"); + return this; + } + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + BinaryExpression e = (BinaryExpression)clone(); + if (left != null) { + e.left = left.copyInline(ctx); + } + if (right != null) { + e.right = right.copyInline(ctx); + } + return e; + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + ((left != null) ? left.costInline(thresh, env, ctx) : 0) + + ((right != null) ? right.costInline(thresh, env, ctx) : 0); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + throw new CompilerError("codeOperation: " + opNames[op]); + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + if (type.isType(TC_BOOLEAN)) { + Label l1 = new Label(); + Label l2 = new Label(); + + codeBranch(env, ctx, asm, l1, true); + asm.add(true, where, opc_ldc, 0); + asm.add(true, where, opc_goto, l2); + asm.add(l1); + asm.add(true, where, opc_ldc, 1); + asm.add(l2); + } else { + left.codeValue(env, ctx, asm); + right.codeValue(env, ctx, asm); + codeOperation(env, ctx, asm); + } + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + if (left != null) { + left.print(out); + } else { + out.print(""); + } + out.print(" "); + if (right != null) { + right.print(out); + } else { + out.print(""); + } + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryLogicalExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryLogicalExpression.java new file mode 100644 index 000000000..d31deb7ca --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryLogicalExpression.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +abstract public +class BinaryLogicalExpression extends BinaryExpression { + /** + * constructor + */ + public BinaryLogicalExpression(int op, long where, Expression left, Expression right) { + super(op, where, Type.tBoolean, left, right); + } + + /** + * Check a binary expression + */ + public Vset checkValue(Environment env, Context ctx, + Vset vset, Hashtable exp) { + ConditionVars cvars = new ConditionVars(); + // evaluate the logical expression, determining which variables are + // set if the resulting value is true or false + checkCondition(env, ctx, vset, exp, cvars); + // return the intersection. + return cvars.vsTrue.join(cvars.vsFalse); + } + + /* + * Every subclass of this class must define a genuine implementation + * of this method. It cannot inherit the method of Expression. + */ + abstract + public void checkCondition(Environment env, Context ctx, Vset vset, + Hashtable exp, ConditionVars cvars); + + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + left = left.inlineValue(env, ctx); + right = right.inlineValue(env, ctx); + return this; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryShiftExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryShiftExpression.java new file mode 100644 index 000000000..beeedf416 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BinaryShiftExpression.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BinaryShiftExpression extends BinaryExpression { + /** + * constructor + */ + public BinaryShiftExpression(int op, long where, Expression left, Expression right) { + super(op, where, left.type, left, right); + } + + /** + * Evaluate the expression + */ + Expression eval() { + // The eval code in BinaryExpression.java only works correctly + // for arithmetic expressions. For shift expressions, we get cases + // where the left and right operand may legitimately be of mixed + // types (long and int). This is a fix for 4082814. + if (left.op == LONGVAL && right.op == INTVAL) { + return eval(((LongExpression)left).value, + ((IntExpression)right).value); + } + + // Delegate the rest of the cases to our parent, so as to minimize + // impact on existing behavior. + return super.eval(); + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + if (left.type == Type.tLong) { + type = Type.tLong; + } else if (left.type.inMask(TM_INTEGER)) { + type = Type.tInt; + left = convert(env, ctx, type, left); + } else { + type = Type.tError; + } + if (right.type.inMask(TM_INTEGER)) { + right = new ConvertExpression(where, Type.tInt, right); + } else { + right = convert(env, ctx, Type.tInt, right); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitAndExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitAndExpression.java new file mode 100644 index 000000000..9f176814a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitAndExpression.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BitAndExpression extends BinaryBitExpression { + /** + * constructor + */ + public BitAndExpression(long where, Expression left, Expression right) { + super(BITAND, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a & b); + } + Expression eval(int a, int b) { + return new IntExpression(where, a & b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a & b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.equals(true)) + return right; + if (right.equals(true)) + return left; + if (left.equals(false) || left.equals(0)) + return new CommaExpression(where, right, left).simplify(); + if (right.equals(false) || right.equals(0)) + return new CommaExpression(where, left, right).simplify(); + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iand + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitNotExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitNotExpression.java new file mode 100644 index 000000000..b36fcbc36 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitNotExpression.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BitNotExpression extends UnaryExpression { + /** + * Constructor + */ + public BitNotExpression(long where, Expression right) { + super(BITNOT, where, right.type, right); + } + + /** + * Select the type of the expression + */ + void selectType(Environment env, Context ctx, int tm) { + if ((tm & TM_LONG) != 0) { + type = Type.tLong; + } else { + type = Type.tInt; + } + right = convert(env, ctx, type, right); + } + + /** + * Evaluate + */ + Expression eval(int a) { + return new IntExpression(where, ~a); + } + Expression eval(long a) { + return new LongExpression(where, ~a); + } + + /** + * Simplify + */ + Expression simplify() { + if (right.op == BITNOT) { + return ((BitNotExpression)right).right; + } + return this; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + right.codeValue(env, ctx, asm); + if (type.isType(TC_INT)) { + asm.add(where, opc_ldc, -1); + asm.add(where, opc_ixor); + } else { + asm.add(where, opc_ldc2_w, -1L); + asm.add(where, opc_lxor); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitOrExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitOrExpression.java new file mode 100644 index 000000000..fa7718e78 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitOrExpression.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BitOrExpression extends BinaryBitExpression { + /** + * constructor + */ + public BitOrExpression(long where, Expression left, Expression right) { + super(BITOR, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a | b); + } + Expression eval(int a, int b) { + return new IntExpression(where, a | b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a | b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.equals(false) || left.equals(0)) + return right; + if (right.equals(false) || right.equals(0)) + return left; + if (left.equals(true)) + return new CommaExpression(where, right, left).simplify(); + if (right.equals(true)) + return new CommaExpression(where, left, right).simplify(); + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ior + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitXorExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitXorExpression.java new file mode 100644 index 000000000..9cef8ddf6 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BitXorExpression.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BitXorExpression extends BinaryBitExpression { + /** + * constructor + */ + public BitXorExpression(long where, Expression left, Expression right) { + super(BITXOR, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a ^ b); + } + Expression eval(int a, int b) { + return new IntExpression(where, a ^ b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a ^ b); + } + + + /** + * Simplify + */ + Expression simplify() { + if (left.equals(true)) { + return new NotExpression(where, right); + } + if (right.equals(true)) { + return new NotExpression(where, left); + } + if (left.equals(false) || left.equals(0)) { + return right; + } + if (right.equals(false) || right.equals(0)) { + return left; + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ixor + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BooleanExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BooleanExpression.java new file mode 100644 index 000000000..6bea38d5e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BooleanExpression.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BooleanExpression extends ConstantExpression { + boolean value; + + /** + * Constructor + */ + public BooleanExpression(long where, boolean value) { + super(BOOLEANVAL, where, Type.tBoolean); + this.value = value; + } + + /** + * Get the value + */ + public Object getValue() { + return value ? 1 : 0; + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(boolean b) { + return value == b; + } + + + /** + * Check if the expression is equal to its default static value + */ + public boolean equalsDefault() { + return !value; + } + + + /* + * Check a "not" expression. + * + * cvars is modified so that + * cvar.vsTrue indicates variables with a known value if + * the expression is true. + * cvars.vsFalse indicates variables with a known value if + * the expression is false + * + * For constant expressions, set the side that corresponds to our + * already known value to vset. Set the side that corresponds to the + * other way to "impossible" + */ + + public void checkCondition(Environment env, Context ctx, + Vset vset, Hashtable exp, ConditionVars cvars) { + if (value) { + cvars.vsFalse = Vset.DEAD_END; + cvars.vsTrue = vset; + } else { + cvars.vsFalse = vset; + cvars.vsTrue = Vset.DEAD_END; + } + } + + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + if (value == whenTrue) { + asm.add(where, opc_goto, lbl); + } + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ldc, value ? 1 : 0); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value ? "true" : "false"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/BreakStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BreakStatement.java new file mode 100644 index 000000000..4b468a279 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/BreakStatement.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class BreakStatement extends Statement { + Identifier lbl; + + /** + * Constructor + */ + public BreakStatement(long where, Identifier lbl) { + super(BREAK, where); + this.lbl = lbl; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + reach(env, vset); + checkLabel(env, ctx); + CheckContext destctx = (CheckContext)new CheckContext(ctx, this).getBreakContext(lbl); + if (destctx != null) { + if (destctx.frameNumber != ctx.frameNumber) { + env.error(where, "branch.to.uplevel", lbl); + } + destctx.vsBreak = destctx.vsBreak.join(vset); + } else { + if (lbl != null) { + env.error(where, "label.not.found", lbl); + } else { + env.error(where, "invalid.break"); + } + } + CheckContext exitctx = ctx.getTryExitContext(); + if (exitctx != null) { + exitctx.vsTryExit = exitctx.vsTryExit.join(vset); + } + return DEAD_END; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + CodeContext destctx = (CodeContext)newctx.getBreakContext(lbl); + codeFinally(env, ctx, asm, destctx, null); + asm.add(where, opc_goto, destctx.breakLabel); + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("break"); + if (lbl != null) { + out.print(" " + lbl); + } + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ByteExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ByteExpression.java new file mode 100644 index 000000000..12ea6a19c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ByteExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ByteExpression extends IntegerExpression { + /** + * Constructor + */ + public ByteExpression(long where, byte value) { + super(BYTEVAL, where, Type.tByte, value); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value + "b"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CaseStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CaseStatement.java new file mode 100644 index 000000000..0fb4b67d6 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CaseStatement.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CaseStatement extends Statement { + Expression expr; + + /** + * Constructor + */ + public CaseStatement(long where, Expression expr) { + super(CASE, where); + this.expr = expr; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + if (expr != null) { + expr.checkValue(env, ctx, vset, exp); + expr = convert(env, ctx, Type.tInt, expr); + expr = expr.inlineValue(env, ctx); + } + return vset.clearDeadEnd(); + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 6; + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + if (expr == null) { + out.print("default"); + } else { + out.print("case "); + expr.print(out); + } + out.print(":"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CastExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CastExpression.java new file mode 100644 index 000000000..a3da72549 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CastExpression.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CastExpression extends BinaryExpression { + /** + * constructor + */ + public CastExpression(long where, Expression left, Expression right) { + super(CAST, where, left.type, left, right); + } + + /** + * Check the expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + type = left.toType(env, ctx); + vset = right.checkValue(env, ctx, vset, exp); + + if (type.isType(TC_ERROR) || right.type.isType(TC_ERROR)) { + // An error was already reported + return vset; + } + + if (type.equals(right.type)) { + // The types are already the same + return vset; + } + + try { + if (env.explicitCast(right.type, type)) { + right = new ConvertExpression(where, type, right); + return vset; + } + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, opNames[op]); + } + + // The cast is not allowed + env.error(where, "invalid.cast", right.type, type); + return vset; + } + + /** + * Check if constant + */ + public boolean isConstant() { + if (type.inMask(TM_REFERENCE) && !type.equals(Type.tString)) { + // must be a primitive type, or String + return false; + } + return right.isConstant(); + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + return right.inline(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + return right.inlineValue(env, ctx); + } + + + public int costInline(int thresh, Environment env, Context ctx) { + if (ctx == null) { + return 1 + right.costInline(thresh, env, ctx); + } + // sourceClass is the current class trying to inline this method + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + try { + // We only allow the inlining if the current class can access + // the casting class + if (left.type.isType(TC_ARRAY) || + sourceClass.permitInlinedAccess(env, + env.getClassDeclaration(left.type))) + return 1 + right.costInline(thresh, env, ctx); + } catch (ClassNotFound e) { + } + return thresh; + } + + + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + if (type.isType(TC_ERROR)) { + left.print(out); + } else { + out.print(type); + } + out.print(" "); + right.print(out); + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CatchStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CatchStatement.java new file mode 100644 index 000000000..637daf5da --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CatchStatement.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.LocalVariable; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CatchStatement extends Statement { + int mod; + Expression texpr; + Identifier id; + Statement body; + LocalMember field; + + /** + * Constructor + */ + public CatchStatement(long where, Expression texpr, IdentifierToken id, Statement body) { + super(CATCH, where); + this.mod = id.getModifiers(); + this.texpr = texpr; + this.id = id.getName(); + this.body = body; + } + /** @deprecated */ + @Deprecated + public CatchStatement(long where, Expression texpr, Identifier id, Statement body) { + super(CATCH, where); + this.texpr = texpr; + this.id = id; + this.body = body; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = reach(env, vset); + ctx = new Context(ctx, this); + Type type = texpr.toType(env, ctx); + + try { + if (ctx.getLocalField(id) != null) { + env.error(where, "local.redefined", id); + } + + if (type.isType(TC_ERROR)) { + // error message printed out elsewhere + } else if (!type.isType(TC_CLASS)) { + env.error(where, "catch.not.throwable", type); + } else { + ClassDefinition def = env.getClassDefinition(type); + if (!def.subClassOf(env, + env.getClassDeclaration(idJavaLangThrowable))) { + env.error(where, "catch.not.throwable", def); + } + } + + field = new LocalMember(where, ctx.field.getClassDefinition(), mod, type, id); + ctx.declare(env, field); + vset.addVar(field.number); + + return body.check(env, ctx, vset, exp); + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, opNames[op]); + return vset; + } + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + if (field.isUsed()) { + ctx.declare(env, field); + } + if (body != null) { + body = body.inline(env, ctx); + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + CatchStatement s = (CatchStatement)clone(); + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + if (field != null) { + s.field = field.copyInline(ctx); + } + return s; + } + + /** + * Compute cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx){ + int cost = 1; + if (body != null) { + cost += body.costInline(thresh, env,ctx); + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + if (field.isUsed()) { + newctx.declare(env, field); + asm.add(where, opc_astore, new LocalVariable(field, field.number)); + } else { + asm.add(where, opc_pop); + } + if (body != null) { + body.code(env, newctx, asm); + } + //asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("catch ("); + texpr.print(out); + out.print(" " + id + ") "); + if (body != null) { + body.print(out, indent); + } else { + out.print(""); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CharExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CharExpression.java new file mode 100644 index 000000000..763588385 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CharExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CharExpression extends IntegerExpression { + /** + * Constructor + */ + public CharExpression(long where, char value) { + super(CHARVAL, where, Type.tChar, value); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value + "c"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CheckContext.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CheckContext.java new file mode 100644 index 000000000..9254b0e89 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CheckContext.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CheckContext extends Context { + public Vset vsBreak = Vset.DEAD_END; + public Vset vsContinue = Vset.DEAD_END; + + // Accumulate (join) all DA/DU state prior to + // any abnormal exit from a try-statement. + // This field is ignored unless this + // context is associated with a try-statement. + public Vset vsTryExit = Vset.DEAD_END; + + /** + * Create a new nested context, for a block statement + */ + CheckContext(Context ctx, Statement stat) { + super(ctx, stat); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CodeContext.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CodeContext.java new file mode 100644 index 000000000..d197b79af --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CodeContext.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +class CodeContext extends Context { + Label breakLabel; + Label contLabel; + + /** + * Create a new nested context, for a block statement + */ + CodeContext(Context ctx, Node node) { + super(ctx, node); + switch (node.op) { + case DO: + case WHILE: + case FOR: + case FINALLY: + case SYNCHRONIZED: + this.breakLabel = new Label(); + this.contLabel = new Label(); + break; + case SWITCH: + case TRY: + case INLINEMETHOD: + case INLINENEWINSTANCE: + this.breakLabel = new Label(); + break; + default: + if ((node instanceof Statement) && (((Statement)node).labels != null)) { + this.breakLabel = new Label(); + } + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CommaExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CommaExpression.java new file mode 100644 index 000000000..763c6d179 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CommaExpression.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CommaExpression extends BinaryExpression { + /** + * constructor + */ + public CommaExpression(long where, Expression left, Expression right) { + super(COMMA, where, (right != null) ? right.type : Type.tVoid, left, right); + } + + /** + * Check void expression + */ + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = left.check(env, ctx, vset, exp); + vset = right.check(env, ctx, vset, exp); + return vset; + } + + /** + * Select the type + */ + void selectType(Environment env, Context ctx, int tm) { + type = right.type; + } + + /** + * Simplify + */ + Expression simplify() { + if (left == null) { + return right; + } + if (right == null) { + return left; + } + return this; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + if (left != null) { + left = left.inline(env, ctx); + } + if (right != null) { + right = right.inline(env, ctx); + } + return simplify(); + } + public Expression inlineValue(Environment env, Context ctx) { + if (left != null) { + left = left.inline(env, ctx); + } + if (right != null) { + right = right.inlineValue(env, ctx); + } + return simplify(); + } + + /** + * Code + */ + int codeLValue(Environment env, Context ctx, Assembler asm) { + if (right == null) { + // throw an appropriate error + return super.codeLValue(env, ctx, asm); + } else { + // Fully code the left-hand side. Do the LValue part of the + // right-hand side now. The remainder will be done by codeLoad or + // codeStore + if (left != null) { + left.code(env, ctx, asm); + } + return right.codeLValue(env, ctx, asm); + } + } + + void codeLoad(Environment env, Context ctx, Assembler asm) { + // The left-hand part has already been handled by codeLValue. + + if (right == null) { + // throw an appropriate error + super.codeLoad(env, ctx, asm); + } else { + right.codeLoad(env, ctx, asm); + } + } + + void codeStore(Environment env, Context ctx, Assembler asm) { + // The left-hand part has already been handled by codeLValue. + if (right == null) { + // throw an appropriate error + super.codeStore(env, ctx, asm); + } else { + right.codeStore(env, ctx, asm); + } + } + + public void codeValue(Environment env, Context ctx, Assembler asm) { + if (left != null) { + left.code(env, ctx, asm); + } + right.codeValue(env, ctx, asm); + } + public void code(Environment env, Context ctx, Assembler asm) { + if (left != null) { + left.code(env, ctx, asm); + } + if (right != null) { + right.code(env, ctx, asm); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/CompoundStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CompoundStatement.java new file mode 100644 index 000000000..c388fe71c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/CompoundStatement.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class CompoundStatement extends Statement { + Statement args[]; + + /** + * Constructor + */ + public CompoundStatement(long where, Statement args[]) { + super(STAT, where); + this.args = args; + // To avoid the need for subsequent null checks: + for (int i = 0 ; i < args.length ; i++) { + if (args[i] == null) { + args[i] = new CompoundStatement(where, new Statement[0]); + } + } + } + + /** + * Insert a new statement at the front. + * This is used to introduce an implicit super-class constructor call. + */ + public void insertStatement(Statement s) { + Statement newargs[] = new Statement[1+args.length]; + newargs[0] = s; + for (int i = 0 ; i < args.length ; i++) { + newargs[i+1] = args[i]; + } + this.args = newargs; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + if (args.length > 0) { + vset = reach(env, vset); + CheckContext newctx = new CheckContext(ctx, this); + // In this environment, 'resolveName' will look for local classes. + Environment newenv = Context.newEnvironment(env, newctx); + for (int i = 0 ; i < args.length ; i++) { + vset = args[i].checkBlockStatement(newenv, newctx, vset, exp); + } + vset = vset.join(newctx.vsBreak); + } + return ctx.removeAdditionalVars(vset); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + boolean expand = false; + int count = 0; + for (int i = 0 ; i < args.length ; i++) { + Statement s = args[i]; + if (s != null) { + if ((s = s.inline(env, ctx)) != null) { + if ((s.op == STAT) && (s.labels == null)) { + count += ((CompoundStatement)s).args.length; + } else { + count++; + } + expand = true; + } + args[i] = s; + } + } + switch (count) { + case 0: + return null; + + case 1: + for (int i = args.length ; i-- > 0 ;) { + if (args[i] != null) { + return eliminate(env, args[i]); + } + } + break; + } + if (expand || (count != args.length)) { + Statement newArgs[] = new Statement[count]; + for (int i = args.length ; i-- > 0 ;) { + Statement s = args[i]; + if (s != null) { + if ((s.op == STAT) && (s.labels == null)) { + Statement a[] = ((CompoundStatement)s).args; + for (int j = a.length ; j-- > 0 ; ) { + newArgs[--count] = a[j]; + } + } else { + newArgs[--count] = s; + } + } + } + args = newArgs; + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + CompoundStatement s = (CompoundStatement)clone(); + s.args = new Statement[args.length]; + for (int i = 0 ; i < args.length ; i++) { + s.args[i] = args[i].copyInline(ctx, valNeeded); + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + int cost = 0; + for (int i = 0 ; (i < args.length) && (cost < thresh) ; i++) { + cost += args[i].costInline(thresh, env, ctx); + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + for (int i = 0 ; i < args.length ; i++) { + args[i].code(env, newctx, asm); + } + asm.add(newctx.breakLabel); + } + + /** + * Check if the first thing is a constructor invocation + */ + public Expression firstConstructor() { + return (args.length > 0) ? args[0].firstConstructor() : null; + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("{\n"); + for (int i = 0 ; i < args.length ; i++) { + printIndent(out, indent+1); + if (args[i] != null) { + args[i].print(out, indent + 1); + } else { + out.print(""); + } + out.print("\n"); + } + printIndent(out, indent); + out.print("}"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConditionVars.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConditionVars.java new file mode 100644 index 000000000..4955b2918 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConditionVars.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +/** + * This class is used to hold two sets of variables, + * one for the true branch, one for the false branch. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +class ConditionVars { + Vset vsTrue; + Vset vsFalse; +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConditionalExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConditionalExpression.java new file mode 100644 index 000000000..d1d14ec48 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConditionalExpression.java @@ -0,0 +1,220 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ConditionalExpression extends BinaryExpression { + Expression cond; + + /** + * Constructor + */ + public ConditionalExpression(long where, Expression cond, Expression left, Expression right) { + super(COND, where, Type.tError, left, right); + this.cond = cond; + } + + /** + * Order the expression based on precedence + */ + public Expression order() { + if (precedence() > cond.precedence()) { + UnaryExpression e = (UnaryExpression)cond; + cond = e.right; + e.right = order(); + return e; + } + return this; + } + + /** + * Check the expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + ConditionVars cvars = cond.checkCondition(env, ctx, vset, exp); + vset = left.checkValue(env, ctx, cvars.vsTrue, exp).join( + right.checkValue(env, ctx, cvars.vsFalse, exp) ); + cond = convert(env, ctx, Type.tBoolean, cond); + + int tm = left.type.getTypeMask() | right.type.getTypeMask(); + if ((tm & TM_ERROR) != 0) { + type = Type.tError; + return vset; + } + if (left.type.equals(right.type)) { + type = left.type; + } else if ((tm & TM_DOUBLE) != 0) { + type = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + type = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + type = Type.tLong; + } else if ((tm & TM_REFERENCE) != 0) { + try { + // This is wrong. We should be using their most common + // ancestor, instead. + type = env.implicitCast(right.type, left.type) + ? left.type : right.type; + } catch (ClassNotFound e) { + type = Type.tError; + } + } else if (((tm & TM_CHAR) != 0) && left.fitsType(env, ctx, Type.tChar) && right.fitsType(env, ctx, Type.tChar)) { + type = Type.tChar; + } else if (((tm & TM_SHORT) != 0) && left.fitsType(env, ctx, Type.tShort) && right.fitsType(env, ctx, Type.tShort)) { + type = Type.tShort; + } else if (((tm & TM_BYTE) != 0) && left.fitsType(env, ctx, Type.tByte) && right.fitsType(env, ctx, Type.tByte)) { + type = Type.tByte; + } else { + type = Type.tInt; + } + + left = convert(env, ctx, type, left); + right = convert(env, ctx, type, right); + return vset; + } + + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = cond.checkValue(env, ctx, vset, exp); + cond = convert(env, ctx, Type.tBoolean, cond); + return left.check(env, ctx, vset.copy(), exp).join(right.check(env, ctx, vset, exp)); + } + + /** + * Check if constant + */ + public boolean isConstant() { + return cond.isConstant() && left.isConstant() && right.isConstant(); + } + + /** + * Simplify + */ + Expression simplify() { + if (cond.equals(true)) { + return left; + } + if (cond.equals(false)) { + return right; + } + return this; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + left = left.inline(env, ctx); + right = right.inline(env, ctx); + if ((left == null) && (right == null)) { + return cond.inline(env, ctx); + } + if (left == null) { + left = right; + right = null; + cond = new NotExpression(where, cond); + } + cond = cond.inlineValue(env, ctx); + return simplify(); + } + + public Expression inlineValue(Environment env, Context ctx) { + cond = cond.inlineValue(env, ctx); + left = left.inlineValue(env, ctx); + right = right.inlineValue(env, ctx); + return simplify(); + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + // We need to check if right is null in case costInline() + // is called after this expression has been inlined. + // This call can happen, for example, in MemberDefinition#cleanup(). + // (Fix for 4069861). + return 1 + + cond.costInline(thresh, env, ctx) + + left.costInline(thresh, env, ctx) + + ((right == null) ? 0 : right.costInline(thresh, env, ctx)); + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + ConditionalExpression e = (ConditionalExpression)clone(); + e.cond = cond.copyInline(ctx); + e.left = left.copyInline(ctx); + + // If copyInline() is called after inlining is complete, + // right could be null. + e.right = (right == null) ? null : right.copyInline(ctx); + + return e; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + Label l1 = new Label(); + Label l2 = new Label(); + + cond.codeBranch(env, ctx, asm, l1, false); + left.codeValue(env, ctx, asm); + asm.add(where, opc_goto, l2); + asm.add(l1); + right.codeValue(env, ctx, asm); + asm.add(l2); + } + public void code(Environment env, Context ctx, Assembler asm) { + Label l1 = new Label(); + cond.codeBranch(env, ctx, asm, l1, false); + left.code(env, ctx, asm); + if (right != null) { + Label l2 = new Label(); + asm.add(where, opc_goto, l2); + asm.add(l1); + right.code(env, ctx, asm); + asm.add(l2); + } else { + asm.add(l1); + } + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + cond.print(out); + out.print(" "); + left.print(out); + out.print(" "); + if (right != null) { + right.print(out); + } else { + out.print(""); + } + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConstantExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConstantExpression.java new file mode 100644 index 000000000..a545bf5d3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConstantExpression.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +class ConstantExpression extends Expression { + /** + * Constructor + */ + public ConstantExpression(int op, long where, Type type) { + super(op, where, type); + } + + /** + * Return true if constant + */ + public boolean isConstant() { + return true; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/Context.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Context.java new file mode 100644 index 000000000..2621b07ca --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Context.java @@ -0,0 +1,846 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class Context implements Constants { + Context prev; + Node node; + int varNumber; + LocalMember locals; + LocalMember classes; + MemberDefinition field; + int scopeNumber; + int frameNumber; + + /** + * Create the initial context for a method + * The incoming context is inherited from + */ + public Context(Context ctx, MemberDefinition field) { + this.field = field; + if (ctx == null) { + this.frameNumber = 1; + this.scopeNumber = 2; + this.varNumber = 0; + } else { + this.prev = ctx; + this.locals = ctx.locals; + this.classes = ctx.classes; + if (field != null && + (field.isVariable() || field.isInitializer())) { + // Variables and initializers are inlined into a constructor. + // Model this by inheriting the frame number of the parent, + // which will contain a "this" parameter. + this.frameNumber = ctx.frameNumber; + this.scopeNumber = ctx.scopeNumber + 1; + } else { + this.frameNumber = ctx.scopeNumber + 1; + this.scopeNumber = this.frameNumber + 1; + } + this.varNumber = ctx.varNumber; + } + } + + /** + * Create a new context, for initializing a class. + */ + public Context(Context ctx, ClassDefinition c) { + this(ctx, (MemberDefinition)null); + } + + /** + * Create a new nested context, for a block statement + */ + Context(Context ctx, Node node) { + if (ctx == null) { + this.frameNumber = 1; + this.scopeNumber = 2; + this.varNumber = 0; + } else { + this.prev = ctx; + this.locals = ctx.locals; + // Inherit local classes from surrounding block, + // just as for local variables. Fixes 4074421. + this.classes = ctx.classes; + this.varNumber = ctx.varNumber; + this.field = ctx.field; + this.frameNumber = ctx.frameNumber; + this.scopeNumber = ctx.scopeNumber + 1; + this.node = node; + } + } + + public Context(Context ctx) { + this(ctx, (Node)null); + } + + /** + * Declare local + */ + public int declare(Environment env, LocalMember local) { + //System.out.println( "DECLARE= " + local.getName() + "=" + varNumber + ", read=" + local.readcount + ", write=" + local.writecount + ", hash=" + local.hashCode()); + local.scopeNumber = scopeNumber; + if (this.field == null && idThis.equals(local.getName())) { + local.scopeNumber += 1; // Anticipate variable or initializer. + } + if (local.isInnerClass()) { + local.prev = classes; + classes = local; + return 0; + } + + // Originally the statement: + // + // local.subModifiers(M_INLINEABLE); + // + // was here with the comment: + // + // // prevent inlining across call sites + // + // This statement prevented constant local variables from + // inlining. It didn't seem to do anything useful. + // + // The statement has been removed and an assertion has been + // added which mandates that the only members which are marked + // with M_INLINEABLE are the ones for which isConstant() is true. + // (Fix for 4106244.) + // + // Addition to the above comment: they might also be + // final variables initialized with 'this', 'super', or other + // final identifiers. See VarDeclarationStatement.inline(). + // So I've removed the assertion. The original subModifiers + // call appears to have been there to fix nested class translation + // breakage, which has been fixed in VarDeclarationStatement + // now instead. (Fix for 4073244.) + + local.prev = locals; + locals = local; + local.number = varNumber; + varNumber += local.getType().stackSize(); + return local.number; + } + + /** + * Get a local variable by name + */ + public + LocalMember getLocalField(Identifier name) { + for (LocalMember f = locals ; f != null ; f = f.prev) { + if (name.equals(f.getName())) { + return f; + } + } + return null; + } + + /** + * Get the scope number for a reference to a member of this class + * (Larger scope numbers are more deeply nested.) + * @see LocalMember#scopeNumber + */ + public + int getScopeNumber(ClassDefinition c) { + for (Context ctx = this; ctx != null; ctx = ctx.prev) { + if (ctx.field == null) continue; + if (ctx.field.getClassDefinition() == c) { + return ctx.frameNumber; + } + } + return -1; + } + + private + MemberDefinition getFieldCommon(Environment env, Identifier name, + boolean apparentOnly) throws AmbiguousMember, ClassNotFound { + // Note: This is structured as a pair of parallel lookups. + // If we were to redesign Context, we might prefer to walk + // along a single chain of scopes. + + LocalMember lf = getLocalField(name); + int ls = (lf == null) ? -2 : lf.scopeNumber; + + ClassDefinition thisClass = field.getClassDefinition(); + + // Also look for a class member in a shallower scope. + for (ClassDefinition c = thisClass; + c != null; + c = c.getOuterClass()) { + MemberDefinition f = c.getVariable(env, name, thisClass); + if (f != null && getScopeNumber(c) > ls) { + if (apparentOnly && f.getClassDefinition() != c) { + continue; + } + return f; + } + } + + return lf; + } + + /** + * Assign a number to a class field. + * (This is used to track definite assignment of some blank finals.) + */ + public int declareFieldNumber(MemberDefinition field) { + return declare(null, new LocalMember(field)); + } + + /** + * Retrieve a number previously assigned by declareMember(). + * Return -1 if there was no such assignment in this context. + */ + public int getFieldNumber(MemberDefinition field) { + for (LocalMember f = locals ; f != null ; f = f.prev) { + if (f.getMember() == field) { + return f.number; + } + } + return -1; + } + + /** + * Return the local field or member field corresponding to a number. + * Return null if there is no such field. + */ + public MemberDefinition getElement(int number) { + for (LocalMember f = locals ; f != null ; f = f.prev) { + if (f.number == number) { + MemberDefinition field = f.getMember(); + return (field != null) ? field : f; + } + } + return null; + } + + /** + * Get a local class by name + */ + public + LocalMember getLocalClass(Identifier name) { + for (LocalMember f = classes ; f != null ; f = f.prev) { + if (name.equals(f.getName())) { + return f; + } + } + return null; + } + + private + MemberDefinition getClassCommon(Environment env, Identifier name, + boolean apparentOnly) throws ClassNotFound { + LocalMember lf = getLocalClass(name); + int ls = (lf == null) ? -2 : lf.scopeNumber; + + // Also look for a class member in a shallower scope. + for (ClassDefinition c = field.getClassDefinition(); + c != null; + c = c.getOuterClass()) { + // QUERY: We may need to get the inner class from a + // superclass of 'c'. This call is prepared to + // resolve the superclass if necessary. Can we arrange + // to assure that it is always previously resolved? + // This is one of a small number of problematic calls that + // requires 'getSuperClass' to resolve superclasses on demand. + // See 'ClassDefinition.getInnerClass(env, nm)'. + MemberDefinition f = c.getInnerClass(env, name); + if (f != null && getScopeNumber(c) > ls) { + if (apparentOnly && f.getClassDefinition() != c) { + continue; + } + return f; + } + } + + return lf; + } + + /** + * Get either a local variable, or a field in a current class + */ + public final + MemberDefinition getField(Environment env, Identifier name) throws AmbiguousMember, ClassNotFound { + return getFieldCommon(env, name, false); + } + + /** + * Like getField, except that it skips over inherited fields. + * Used for error checking. + */ + public final + MemberDefinition getApparentField(Environment env, Identifier name) throws AmbiguousMember, ClassNotFound { + return getFieldCommon(env, name, true); + } + + /** + * Check if the given field is active in this context. + */ + public boolean isInScope(LocalMember field) { + for (LocalMember f = locals ; f != null ; f = f.prev) { + if (field == f) { + return true; + } + } + return false; + } + + /** + * Notice a reference (usually an uplevel one). + * Update the references list of every enclosing class + * which is enclosed by the scope of the target. + * Update decisions about which uplevels to make into fields. + * Return the uplevel reference descriptor, or null if it's local. + *

                + * The target must be in scope in this context. + * So, call this method only from the check phase. + * (In other phases, the context may be less complete.) + *

                + * This can and should be called both before and after classes are frozen. + * It should be a no-op, and will raise a compiler error if not. + */ + public UplevelReference noteReference(Environment env, LocalMember target) { + int targetScopeNumber = !isInScope(target) ? -1 : target.scopeNumber; + + // Walk outward visiting each scope. + // Note each distinct frame (i.e., enclosing method). + // For each frame in which the variable is uplevel, + // record the event in the references list of the enclosing class. + UplevelReference res = null; + int currentFrameNumber = -1; + for (Context refctx = this; refctx != null; refctx = refctx.prev) { + if (currentFrameNumber == refctx.frameNumber) { + continue; // we're processing frames, not contexts + } + currentFrameNumber = refctx.frameNumber; + if (targetScopeNumber >= currentFrameNumber) { + break; // the target is native to this frame + } + + // process a frame which is using this variable as an uplevel + ClassDefinition refc = refctx.field.getClassDefinition(); + UplevelReference r = refc.getReference(target); + r.noteReference(env, refctx); + + // remember the reference pertaining to the innermost frame + if (res == null) { + res = r; + } + } + return res; + } + + /** + * Implement a reference (usually an uplevel one). + * Call noteReference() first, to make sure the reference + * lists are up to date. + *

                + * The resulting expression tree does not need checking; + * it can be code-generated right away. + * If the reference is not uplevel, the result is an IDENT or THIS. + */ + public Expression makeReference(Environment env, LocalMember target) { + UplevelReference r = noteReference(env, target); + + // Now create a referencing expression. + if (r != null) { + return r.makeLocalReference(env, this); + } else if (idThis.equals(target.getName())) { + return new ThisExpression(0, target); + } else { + return new IdentifierExpression(0, target); + } + } + + /** + * Return a local expression which can serve as the base reference + * for the given field. If the field is a constructor, return an + * expression for the implicit enclosing instance argument. + *

                + * Return null if there is no need for such an argument, + * or if there was an error. + */ + public Expression findOuterLink(Environment env, long where, + MemberDefinition f) { + // reqc is the base pointer type required to use f + ClassDefinition fc = f.getClassDefinition(); + ClassDefinition reqc = f.isStatic() ? null + : !f.isConstructor() ? fc + : fc.isTopLevel() ? null + : fc.getOuterClass(); + if (reqc == null) { + return null; + } + return findOuterLink(env, where, reqc, f, false); + } + + private static boolean match(Environment env, + ClassDefinition thisc, ClassDefinition reqc) { + try { + return thisc == reqc + || reqc.implementedBy(env, thisc.getClassDeclaration()); + } catch (ClassNotFound ee) { + return false; + } + } + + public Expression findOuterLink(Environment env, long where, + ClassDefinition reqc, + MemberDefinition f, + boolean needExactMatch) { + if (field.isStatic()) { + if (f == null) { + // say something like: undefined variable A.this + Identifier nm = reqc.getName().getFlatName().getName(); + env.error(where, "undef.var", Identifier.lookup(nm,idThis)); + } else if (f.isConstructor()) { + env.error(where, "no.outer.arg", reqc, f.getClassDeclaration()); + } else if (f.isMethod()) { + env.error(where, "no.static.meth.access", + f, f.getClassDeclaration()); + } else { + env.error(where, "no.static.field.access", f.getName(), + f.getClassDeclaration()); + } + // This is an attempt at error recovery. + // Unfortunately, the constructor may throw + // a null pointer exception after failing to resolve + // 'idThis'. Since an error message has already been + // issued previously, this exception is caught and + // silently ignored. Ideally, we should avoid throwing + // the exception. + Expression e = new ThisExpression(where, this); + e.type = reqc.getType(); + return e; + } + + // use lp to scan for current instances (locals named "this") + LocalMember lp = locals; + + // thise is a link expression being built up + Expression thise = null; + + // root is the local variable (idThis) at the far left of thise + LocalMember root = null; + + // thisc is the class of the link expression thise + ClassDefinition thisc = null; + + // conCls is the class of the "this", in a constructor + ClassDefinition conCls = null; + if (field.isConstructor()) { + conCls = field.getClassDefinition(); + } + + if (!field.isMethod()) { + thisc = field.getClassDefinition(); + thise = new ThisExpression(where, this); + } + + while (true) { + if (thise == null) { + // start fresh from lp + while (lp != null && !idThis.equals(lp.getName())) { + lp = lp.prev; + } + if (lp == null) { + break; + } + thise = new ThisExpression(where, lp); + thisc = lp.getClassDefinition(); + root = lp; + lp = lp.prev; + } + + // Require exact class identity when called with + // 'needExactMatch' true. This is done when checking + // the '.this' syntax. Fixes 4102393 and 4133457. + if (thisc == reqc || + (!needExactMatch && match(env, thisc, reqc))) { + break; + } + + // move out one step, if the current instance has an outer link + + MemberDefinition outerMember = thisc.findOuterMember(); + if (outerMember == null) { + thise = null; + continue; // try to find more help in lp + } + ClassDefinition prevc = thisc; + thisc = prevc.getOuterClass(); + + if (prevc == conCls) { + // Must pick up "this$C" from the constructor argument, + // not from "this.this$C", since the latter may not be + // initialized properly. (This way is cheaper too.) + Identifier nm = outerMember.getName(); + IdentifierExpression arg = new IdentifierExpression(where, nm); + arg.bind(env, this); + thise = arg; + } else { + thise = new FieldExpression(where, thise, outerMember); + } + } + if (thise != null) { + // mark crossed scopes + // ????? + //ensureAvailable(root); + return thise; + } + + if (f == null) { + // say something like: undefined variable A.this + Identifier nm = reqc.getName().getFlatName().getName(); + env.error(where, "undef.var", Identifier.lookup(nm,idThis)); + } else if (f.isConstructor()) { + env.error(where, "no.outer.arg", reqc, f.getClassDefinition()); + } else { + env.error(where, "no.static.field.access", f, field); + } + + // avoid floodgating: + Expression e = new ThisExpression(where, this); + e.type = reqc.getType(); + return e; + } + + /** + * Is there a "this" of type reqc in scope? + */ + public static boolean outerLinkExists(Environment env, + ClassDefinition reqc, + ClassDefinition thisc) { + while (!match(env, thisc, reqc)) { + if (thisc.isTopLevel()) { + return false; + } + thisc = thisc.getOuterClass(); + } + return true; + } + + /** + * From which enclosing class do members of this type come? + */ + public ClassDefinition findScope(Environment env, ClassDefinition reqc) { + ClassDefinition thisc = field.getClassDefinition(); + while (thisc != null && !match(env, thisc, reqc)) { + thisc = thisc.getOuterClass(); + } + return thisc; + } + + /** + * Resolve a type name from within a local scope. + * @see Environment#resolveName + */ + Identifier resolveName(Environment env, Identifier name) { + // This logic is pretty much exactly parallel to that of + // Environment.resolveName(). + if (name.isQualified()) { + // Try to resolve the first identifier component, + // because inner class names take precedence over + // package prefixes. (Cf. Environment.resolveName.) + Identifier rhead = resolveName(env, name.getHead()); + + if (rhead.hasAmbigPrefix()) { + // The first identifier component refers to an + // ambiguous class. Limp on. We throw away the + // rest of the classname as it is irrelevant. + // (part of solution for 4059855). + return rhead; + } + + if (!env.classExists(rhead)) { + return env.resolvePackageQualifiedName(name); + } + try { + return env.getClassDefinition(rhead). + resolveInnerClass(env, name.getTail()); + } catch (ClassNotFound ee) { + // return partially-resolved name someone else can fail on + return Identifier.lookupInner(rhead, name.getTail()); + } + } + + // Look for an unqualified name in enclosing scopes. + try { + MemberDefinition f = getClassCommon(env, name, false); + if (f != null) { + return f.getInnerClass().getName(); + } + } catch (ClassNotFound ee) { + // a missing superclass, or something catastrophic + } + + // look in imports, etc. + return env.resolveName(name); + } + + /** + * Return the name of a lexically apparent type, + * skipping inherited members, and ignoring + * the current pacakge and imports. + * This is used for error checking. + */ + public + Identifier getApparentClassName(Environment env, Identifier name) { + if (name.isQualified()) { + // Try to resolve the first identifier component, + // because inner class names take precedence over + // package prefixes. (Cf. Environment.resolveName.) + Identifier rhead = getApparentClassName(env, name.getHead()); + return (rhead == null) ? idNull + : Identifier.lookup(rhead, + name.getTail()); + } + + // Look for an unqualified name in enclosing scopes. + try { + MemberDefinition f = getClassCommon(env, name, true); + if (f != null) { + return f.getInnerClass().getName(); + } + } catch (ClassNotFound ee) { + // a missing superclass, or something catastrophic + } + + // the enclosing class name is the only apparent package member: + Identifier topnm = field.getClassDefinition().getTopClass().getName(); + if (topnm.getName().equals(name)) { + return topnm; + } + return idNull; + } + + /** + * Raise an error if a blank final was definitely unassigned + * on entry to a loop, but has possibly been assigned on the + * back-branch. If this is the case, the loop may be assigning + * it multiple times. + */ + public void checkBackBranch(Environment env, Statement loop, + Vset vsEntry, Vset vsBack) { + for (LocalMember f = locals ; f != null ; f = f.prev) { + if (f.isBlankFinal() + && vsEntry.testVarUnassigned(f.number) + && !vsBack.testVarUnassigned(f.number)) { + env.error(loop.where, "assign.to.blank.final.in.loop", + f.getName()); + } + } + } + + /** + * Check if a field can reach another field (only considers + * forward references, not the access modifiers). + */ + public boolean canReach(Environment env, MemberDefinition f) { + return field.canReach(env, f); + } + + /** + * Get the context that corresponds to a label, return null if + * not found. + */ + public + Context getLabelContext(Identifier lbl) { + for (Context ctx = this ; ctx != null ; ctx = ctx.prev) { + if ((ctx.node != null) && (ctx.node instanceof Statement)) { + if (((Statement)(ctx.node)).hasLabel(lbl)) + return ctx; + } + } + return null; + } + + /** + * Get the destination context of a break + */ + public + Context getBreakContext(Identifier lbl) { + if (lbl != null) { + return getLabelContext(lbl); + } + for (Context ctx = this ; ctx != null ; ctx = ctx.prev) { + if (ctx.node != null) { + switch (ctx.node.op) { + case SWITCH: + case FOR: + case DO: + case WHILE: + return ctx; + } + } + } + return null; + } + + /** + * Get the destination context of a continue + */ + public + Context getContinueContext(Identifier lbl) { + if (lbl != null) { + return getLabelContext(lbl); + } + for (Context ctx = this ; ctx != null ; ctx = ctx.prev) { + if (ctx.node != null) { + switch (ctx.node.op) { + case FOR: + case DO: + case WHILE: + return ctx; + } + } + } + return null; + } + + /** + * Get the destination context of a return (the method body) + */ + public + CheckContext getReturnContext() { + for (Context ctx = this ; ctx != null ; ctx = ctx.prev) { + // The METHOD node is set up by Statement.checkMethod(). + if (ctx.node != null && ctx.node.op == METHOD) { + return (CheckContext)ctx; + } + } + return null; + } + + /** + * Get the context of the innermost surrounding try-block. + * Consider only try-blocks contained within the same method. + * (There could be others when searching from within a method + * of a local class, but they are irrelevant to our purpose.) + * This is used for recording DA/DU information preceding + * all abnormal transfers of control: break, continue, return, + * and throw. + */ + public + CheckContext getTryExitContext() { + for (Context ctx = this; + ctx != null && ctx.node != null && ctx.node.op != METHOD; + ctx = ctx.prev) { + if (ctx.node.op == TRY) { + return (CheckContext)ctx; + } + } + return null; + } + + /** + * Get the nearest inlined context + */ + Context getInlineContext() { + for (Context ctx = this ; ctx != null ; ctx = ctx.prev) { + if (ctx.node != null) { + switch (ctx.node.op) { + case INLINEMETHOD: + case INLINENEWINSTANCE: + return ctx; + } + } + } + return null; + } + + /** + * Get the context of a field that is being inlined + */ + Context getInlineMemberContext(MemberDefinition field) { + for (Context ctx = this ; ctx != null ; ctx = ctx.prev) { + if (ctx.node != null) { + switch (ctx.node.op) { + case INLINEMETHOD: + if (((InlineMethodExpression)ctx.node).field.equals(field)) { + return ctx; + } + break; + case INLINENEWINSTANCE: + if (((InlineNewInstanceExpression)ctx.node).field.equals(field)) { + return ctx; + } + } + } + } + return null; + } + + /** + * Remove variables from the vset set that are no longer part of + * this context. + */ + public final Vset removeAdditionalVars(Vset vset) { + return vset.removeAdditionalVars(varNumber); + } + + public final int getVarNumber() { + return varNumber; + } + + /** + * Return the number of the innermost current instance reference. + */ + public int getThisNumber() { + LocalMember thisf = getLocalField(idThis); + if (thisf != null + && thisf.getClassDefinition() == field.getClassDefinition()) { + return thisf.number; + } + // this is a variable; there is no "this" (should not happen) + return varNumber; + } + + /** + * Return the field containing the present context. + */ + public final MemberDefinition getField() { + return field; + } + + /** + * Extend an environment with the given context. + * The resulting environment behaves the same as + * the given one, except that resolveName() takes + * into account local class names in this context. + */ + public static Environment newEnvironment(Environment env, Context ctx) { + return new ContextEnvironment(env, ctx); + } +} + +final +class ContextEnvironment extends Environment { + Context ctx; + Environment innerEnv; + + ContextEnvironment(Environment env, Context ctx) { + super(env, env.getSource()); + this.ctx = ctx; + this.innerEnv = env; + } + + public Identifier resolveName(Identifier name) { + return ctx.resolveName(innerEnv, name); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ContinueStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ContinueStatement.java new file mode 100644 index 000000000..6732092bf --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ContinueStatement.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ContinueStatement extends Statement { + Identifier lbl; + + /** + * Constructor + */ + public ContinueStatement(long where, Identifier lbl) { + super(CONTINUE, where); + this.lbl = lbl; + } + + /** + * Check statement + */ + + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + reach(env, vset); + // A new context is established here because the 'continue' statement + // itself may be labelled, however erroneously. A 'CheckContext' must + // be used here, as 'getContinueContext' is expected to return one. + CheckContext destctx = (CheckContext)new CheckContext(ctx, this).getContinueContext(lbl); + if (destctx != null) { + switch (destctx.node.op) { + case FOR: + case DO: + case WHILE: + if (destctx.frameNumber != ctx.frameNumber) { + env.error(where, "branch.to.uplevel", lbl); + } + destctx.vsContinue = destctx.vsContinue.join(vset); + break; + default: + env.error(where, "invalid.continue"); + } + } else { + if (lbl != null) { + env.error(where, "label.not.found", lbl); + } else { + env.error(where, "invalid.continue"); + } + } + CheckContext exitctx = ctx.getTryExitContext(); + if (exitctx != null) { + exitctx.vsTryExit = exitctx.vsTryExit.join(vset); + } + return DEAD_END; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext destctx = (CodeContext)ctx.getContinueContext(lbl); + codeFinally(env, ctx, asm, destctx, null); + asm.add(where, opc_goto, destctx.contLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("continue"); + if (lbl != null) { + out.print(" " + lbl); + } + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConvertExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConvertExpression.java new file mode 100644 index 000000000..cea53abf7 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ConvertExpression.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ConvertExpression extends UnaryExpression { + /** + * Constructor + */ + public ConvertExpression(long where, Type type, Expression right) { + super(CONVERT, where, type, right); + } + + /** + * Check the value + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + return right.checkValue(env, ctx, vset, exp); + } + + /** + * Simplify + */ + Expression simplify() { + switch (right.op) { + case BYTEVAL: + case CHARVAL: + case SHORTVAL: + case INTVAL: { + int value = ((IntegerExpression)right).value; + switch (type.getTypeCode()) { + case TC_BYTE: return new ByteExpression(right.where, (byte)value); + case TC_CHAR: return new CharExpression(right.where, (char)value); + case TC_SHORT: return new ShortExpression(right.where, (short)value); + case TC_INT: return new IntExpression(right.where, value); + case TC_LONG: return new LongExpression(right.where, (long)value); + case TC_FLOAT: return new FloatExpression(right.where, (float)value); + case TC_DOUBLE: return new DoubleExpression(right.where, (double)value); + } + break; + } + case LONGVAL: { + long value = ((LongExpression)right).value; + switch (type.getTypeCode()) { + case TC_BYTE: return new ByteExpression(right.where, (byte)value); + case TC_CHAR: return new CharExpression(right.where, (char)value); + case TC_SHORT: return new ShortExpression(right.where, (short)value); + case TC_INT: return new IntExpression(right.where, (int)value); + case TC_FLOAT: return new FloatExpression(right.where, (float)value); + case TC_DOUBLE: return new DoubleExpression(right.where, (double)value); + } + break; + } + case FLOATVAL: { + float value = ((FloatExpression)right).value; + switch (type.getTypeCode()) { + case TC_BYTE: return new ByteExpression(right.where, (byte)value); + case TC_CHAR: return new CharExpression(right.where, (char)value); + case TC_SHORT: return new ShortExpression(right.where, (short)value); + case TC_INT: return new IntExpression(right.where, (int)value); + case TC_LONG: return new LongExpression(right.where, (long)value); + case TC_DOUBLE: return new DoubleExpression(right.where, (double)value); + } + break; + } + case DOUBLEVAL: { + double value = ((DoubleExpression)right).value; + switch (type.getTypeCode()) { + case TC_BYTE: return new ByteExpression(right.where, (byte)value); + case TC_CHAR: return new CharExpression(right.where, (char)value); + case TC_SHORT: return new ShortExpression(right.where, (short)value); + case TC_INT: return new IntExpression(right.where, (int)value); + case TC_LONG: return new LongExpression(right.where, (long)value); + case TC_FLOAT: return new FloatExpression(right.where, (float)value); + } + break; + } + } + return this; + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(int i) { + return right.equals(i); + } + public boolean equals(boolean b) { + return right.equals(b); + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + // super.inline throws away the op. + // This is sometimes incorrect, since casts can have side effects. + if (right.type.inMask(TM_REFERENCE) && type.inMask(TM_REFERENCE)) { + try { + if (!env.implicitCast(right.type, type)) + return inlineValue(env, ctx); + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + } + return super.inline(env, ctx); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + right.codeValue(env, ctx, asm); + codeConversion(env, ctx, asm, right.type, type); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " " + type.toString() + " "); + right.print(out); + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/DeclarationStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DeclarationStatement.java new file mode 100644 index 000000000..a88a931c6 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DeclarationStatement.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class DeclarationStatement extends Statement { + int mod; + Expression type; + Statement args[]; + + /** + * Constructor + */ + public DeclarationStatement(long where, int mod, Expression type, Statement args[]) { + super(DECLARATION, where); + this.mod = mod; + this.type = type; + this.args = args; + } + + /** + * Check statement + * Report an error unless the call is checkBlockStatement. + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + env.error(where, "invalid.decl"); + return checkBlockStatement(env, ctx, vset, exp); + } + Vset checkBlockStatement(Environment env, Context ctx, Vset vset, Hashtable exp) { + if (labels != null) { + env.error(where, "declaration.with.label", labels[0]); + } + vset = reach(env, vset); + Type t = type.toType(env, ctx); + + for (int i = 0 ; i < args.length ; i++) { + vset = args[i].checkDeclaration(env, ctx, vset, mod, t, exp); + } + + return vset; + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + int n = 0; + for (int i = 0 ; i < args.length ; i++) { + if ((args[i] = args[i].inline(env, ctx)) != null) { + n++; + } + } + return (n == 0) ? null : this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + DeclarationStatement s = (DeclarationStatement)clone(); + if (type != null) { + s.type = type.copyInline(ctx); + } + s.args = new Statement[args.length]; + for (int i = 0; i < args.length; i++){ + if (args[i] != null){ + s.args[i] = args[i].copyInline(ctx, valNeeded); + } + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + int cost = 1; + for (int i = 0; i < args.length; i++){ + if (args[i] != null){ + cost += args[i].costInline(thresh, env, ctx); + } + } + return cost; + } + + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + args[i].code(env, ctx, asm); + } + } + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + out.print("declare "); + super.print(out, indent); + type.print(out); + out.print(" "); + for (int i = 0 ; i < args.length ; i++) { + if (i > 0) { + out.print(", "); + } + if (args[i] != null) { + args[i].print(out); + } else { + out.print(""); + } + } + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/DivRemExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DivRemExpression.java new file mode 100644 index 000000000..896e3f30a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DivRemExpression.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1995, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +abstract public +class DivRemExpression extends BinaryArithmeticExpression { + /** + * constructor + */ + public DivRemExpression(int op, long where, Expression left, Expression right) { + super(op, where, left, right); + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + // Do not toss out integer divisions or remainders since they + // can cause a division by zero. + if (type.inMask(TM_INTEGER)) { + right = right.inlineValue(env, ctx); + if (right.isConstant() && !right.equals(0)) { + // We know the division can be elided + left = left.inline(env, ctx); + return left; + } else { + left = left.inlineValue(env, ctx); + try { + return eval().simplify(); + } catch (ArithmeticException e) { + env.error(where, "arithmetic.exception"); + return this; + } + } + } else { + // float & double divisions don't cause arithmetic errors + return super.inline(env, ctx); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/DivideExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DivideExpression.java new file mode 100644 index 000000000..a0acf96e9 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DivideExpression.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class DivideExpression extends DivRemExpression { + /** + * constructor + */ + public DivideExpression(long where, Expression left, Expression right) { + super(DIV, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a / b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a / b); + } + Expression eval(float a, float b) { + return new FloatExpression(where, a / b); + } + Expression eval(double a, double b) { + return new DoubleExpression(where, a / b); + } + + /** + * Simplify + */ + Expression simplify() { + // This code here was wrong. What if the expression is a float? + // In any case, if the expression throws an exception, we + // should just throw the exception at run-time. Throwing + // it at compile-time is not correct. + // (Fix for 4019300) + // + // if (right.equals(0)) { + // throw new ArithmeticException("/ by zero"); + // } + if (right.equals(1)) { + return left; + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_idiv + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/DoStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DoStatement.java new file mode 100644 index 000000000..152f9df5f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DoStatement.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class DoStatement extends Statement { + Statement body; + Expression cond; + + /** + * Constructor + */ + public DoStatement(long where, Statement body, Expression cond) { + super(DO, where); + this.body = body; + this.cond = cond; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env,ctx); + CheckContext newctx = new CheckContext(ctx, this); + // remember what was unassigned on entry + Vset vsEntry = vset.copy(); + vset = body.check(env, newctx, reach(env, vset), exp); + vset = vset.join(newctx.vsContinue); + // get to the test either by falling through the body, or through + // a "continue" statement. + ConditionVars cvars = + cond.checkCondition(env, newctx, vset, exp); + cond = convert(env, newctx, Type.tBoolean, cond); + // make sure the back-branch fits the entry of the loop + ctx.checkBackBranch(env, this, vsEntry, cvars.vsTrue); + // exit the loop through the test returning false, or a "break" + vset = newctx.vsBreak.join(cvars.vsFalse); + return ctx.removeAdditionalVars(vset); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + if (body != null) { + body = body.inline(env, ctx); + } + cond = cond.inlineValue(env, ctx); + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + DoStatement s = (DoStatement)clone(); + s.cond = cond.copyInline(ctx); + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + cond.costInline(thresh, env, ctx) + + ((body != null) ? body.costInline(thresh, env, ctx) : 0); + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + Label l1 = new Label(); + asm.add(l1); + + CodeContext newctx = new CodeContext(ctx, this); + + if (body != null) { + body.code(env, newctx, asm); + } + asm.add(newctx.contLabel); + cond.codeBranch(env, newctx, asm, l1, true); + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("do "); + body.print(out, indent); + out.print(" while "); + cond.print(out); + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/DoubleExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DoubleExpression.java new file mode 100644 index 000000000..3d96041ab --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/DoubleExpression.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class DoubleExpression extends ConstantExpression { + double value; + + /** + * Constructor + */ + public DoubleExpression(long where, double value) { + super(DOUBLEVAL, where, Type.tDouble); + this.value = value; + } + + /** + * Get the value + */ + public Object getValue() { + return new Double(value); + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(int i) { + return value == i; + } + + /** + * Check if the expression is equal to its default static value + */ + public boolean equalsDefault() { + // don't allow -0.0 + return (Double.doubleToLongBits(value) == 0); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ldc2_w, new Double(value)); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value + "D"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/EqualExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/EqualExpression.java new file mode 100644 index 000000000..82a7cc172 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/EqualExpression.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class EqualExpression extends BinaryEqualityExpression { + /** + * constructor + */ + public EqualExpression(long where, Expression left, Expression right) { + super(EQ, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new BooleanExpression(where, a == b); + } + Expression eval(long a, long b) { + return new BooleanExpression(where, a == b); + } + Expression eval(float a, float b) { + return new BooleanExpression(where, a == b); + } + Expression eval(double a, double b) { + return new BooleanExpression(where, a == b); + } + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a == b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.isConstant() && !right.isConstant()) { + return new EqualExpression(where, right, left); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + left.codeValue(env, ctx, asm); + switch (left.type.getTypeCode()) { + case TC_BOOLEAN: + case TC_INT: + if (!right.equals(0)) { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_icmpeq : opc_if_icmpne, lbl, whenTrue); + return; + } + break; + case TC_LONG: + right.codeValue(env, ctx, asm); + asm.add(where, opc_lcmp); + break; + case TC_FLOAT: + right.codeValue(env, ctx, asm); + asm.add(where, opc_fcmpl); + break; + case TC_DOUBLE: + right.codeValue(env, ctx, asm); + asm.add(where, opc_dcmpl); + break; + case TC_ARRAY: + case TC_CLASS: + case TC_NULL: + if (right.equals(0)) { + asm.add(where, whenTrue ? opc_ifnull : opc_ifnonnull, lbl, whenTrue); + } else { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_acmpeq : opc_if_acmpne, lbl, whenTrue); + } + return; + + default: + throw new CompilerError("Unexpected Type"); + } + asm.add(where, whenTrue ? opc_ifeq : opc_ifne, lbl, whenTrue); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ExprExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ExprExpression.java new file mode 100644 index 000000000..b92d98024 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ExprExpression.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.util.Hashtable; + +/** + * Parenthesized expressions. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ + +public +class ExprExpression extends UnaryExpression { + /** + * Constructor + */ + public ExprExpression(long where, Expression right) { + super(EXPR, where, right.type, right); + } + + /** + * Check a condition. We must pass it on to our unparenthesised form. + */ + public void checkCondition(Environment env, Context ctx, Vset vset, + Hashtable exp, ConditionVars cvars) { + right.checkCondition(env, ctx, vset, exp, cvars); + type = right.type; + } + + /** + * Check the expression if it appears as an lvalue. + * We just pass it on to our unparenthesized subexpression. + * (Part of fix for 4090372) + */ + public Vset checkAssignOp(Environment env, Context ctx, + Vset vset, Hashtable exp, Expression outside) { + vset = right.checkAssignOp(env, ctx, vset, exp, outside); + type = right.type; + return vset; + } + + /** + * Delegate to our subexpression. + * (Part of fix for 4090372) + */ + public FieldUpdater getUpdater(Environment env, Context ctx) { + return right.getUpdater(env, ctx); + } + + // Allow (x) = 9; + // + // I will hold off on this until I'm sure about it. Nobody's + // going to clammer for this one. + // + // public Vset checkLHS(Environment env, Context ctx, + // Vset vset, Hashtable exp) { + // vset = right.check(env, ctx, vset, exp); + // type = right.type; + // return vset; + // } + + public boolean isNull() { + return right.isNull(); + } + + public boolean isNonNull() { + return right.isNonNull(); + } + + // Probably not necessary + public Object getValue() { + return right.getValue(); + } + + /** + * Delegate to our subexpression. + * See the comment in AddExpression#inlineValueSB() for + * information about this method. + */ + protected StringBuffer inlineValueSB(Environment env, + Context ctx, + StringBuffer buffer) { + return right.inlineValueSB(env, ctx, buffer); + } + + /** + * Select the type of the expression + */ + void selectType(Environment env, Context ctx, int tm) { + type = right.type; + } + + /** + * Simplify + */ + Expression simplify() { + return right; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/Expression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Expression.java new file mode 100644 index 000000000..71645b96e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Expression.java @@ -0,0 +1,760 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class Expression extends Node { + Type type; + + /** + * Constructor + */ + Expression(int op, long where, Type type) { + super(op, where); + this.type = type; + } + + /** + * Type checking may assign a more complex implementation + * to an innocuous-looking expression (like an identifier). + * Return that implementation, or the original expression itself + * if there is no special implementation. + *

                + * This appears at present to be dead code, and is not called + * from within javac. Access to the implementation generally + * occurs within the same class, and thus uses the underlying + * field directly. + */ + public Expression getImplementation() { + return this; + } + + public Type getType() { + return type; + } + + /** + * Return the precedence of the operator + */ + int precedence() { + return (op < opPrecedence.length) ? opPrecedence[op] : 100; + } + + /** + * Order the expression based on precedence + */ + public Expression order() { + return this; + } + + /** + * Return true if constant, according to JLS 15.27. + * A constant expression must inline away to a literal constant. + */ + public boolean isConstant() { + return false; + } + + /** + * Return the constant value. + */ + public Object getValue() { + return null; + } + + /** + * Check if the expression is known to be equal to a given value. + * Returns false for any expression other than a literal constant, + * thus should be called only after simplification (inlining) has + * been performed. + */ + public boolean equals(int i) { + return false; + } + public boolean equals(boolean b) { + return false; + } + public boolean equals(Identifier id) { + return false; + } + public boolean equals(String s) { + return false; + } + + /** + * Check if the expression must be a null reference. + */ + public boolean isNull() { + return false; + } + + /** + * Check if the expression cannot be a null reference. + */ + public boolean isNonNull() { + return false; + } + + /** + * Check if the expression is equal to its default static value + */ + public boolean equalsDefault() { + return false; + } + + + /** + * Convert an expresion to a type + */ + Type toType(Environment env, Context ctx) { + env.error(where, "invalid.type.expr"); + return Type.tError; + } + + /** + * Convert an expresion to a type in a context where a qualified + * type name is expected, e.g., in the prefix of a qualified type + * name. + */ + /*-----------------------------------------------------* + Type toQualifiedType(Environment env, Context ctx) { + env.error(where, "invalid.type.expr"); + return Type.tError; + } + *-----------------------------------------------------*/ + + /** + * See if this expression fits in the given type. + * This is useful because some larger numbers fit into + * smaller types. + *

                + * If it is an "int" constant expression, inline it, if necessary, + * to examine its numerical value. See JLS 5.2 and 15.24. + */ + public boolean fitsType(Environment env, Context ctx, Type t) { + try { + if (env.isMoreSpecific(this.type, t)) { + return true; + } + if (this.type.isType(TC_INT) && this.isConstant() && ctx != null) { + // Tentative inlining is harmless for constant expressions. + Expression n = this.inlineValue(env, ctx); + if (n != this && n instanceof ConstantExpression) { + return n.fitsType(env, ctx, t); + } + } + return false; + } catch (ClassNotFound e) { + return false; + } + } + + /** @deprecated (for backward compatibility) */ + @Deprecated + public boolean fitsType(Environment env, Type t) { + return fitsType(env, (Context) null, t); + } + + /** + * Check an expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + return vset; + } + public Vset checkInitializer(Environment env, Context ctx, Vset vset, Type t, Hashtable exp) { + return checkValue(env, ctx, vset, exp); + } + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + throw new CompilerError("check failed"); + } + + public Vset checkLHS(Environment env, Context ctx, + Vset vset, Hashtable exp) { + env.error(where, "invalid.lhs.assignment"); + type = Type.tError; + return vset; + } + + /** + * Return a {@code FieldUpdater} object to be used in updating the + * value of the location denoted by {@code this}, which must be an + * expression suitable for the left-hand side of an assignment. + * This is used for implementing assignments to private fields for which + * an access method is required. Returns null if no access method is + * needed, in which case the assignment is handled in the usual way, by + * direct access. Only simple assignment expressions are handled here + * Assignment operators and pre/post increment/decrement operators are + * are handled by 'getUpdater' below. + *

                + * Called during the checking phase. + */ + + public FieldUpdater getAssigner(Environment env, Context ctx) { + throw new CompilerError("getAssigner lhs"); + } + + /** + * Return a {@code FieldUpdater} object to be used in updating the value of the + * location denoted by {@code this}, which must be an expression suitable for the + * left-hand side of an assignment. This is used for implementing the assignment + * operators and the increment/decrement operators on private fields that require an + * access method, e.g., uplevel from an inner class. Returns null if no access method + * is needed. + *

                + * Called during the checking phase. + */ + + public FieldUpdater getUpdater(Environment env, Context ctx) { + throw new CompilerError("getUpdater lhs"); + } + + public Vset checkAssignOp(Environment env, Context ctx, + Vset vset, Hashtable exp, Expression outside) { + if (outside instanceof IncDecExpression) + env.error(where, "invalid.arg", opNames[outside.op]); + else + env.error(where, "invalid.lhs.assignment"); + type = Type.tError; + return vset; + } + + /** + * Check something that might be an AmbiguousName (refman 6.5.2). + * A string of dot-separated identifiers might be, in order of preference: + * + *

              21. a variable name followed by fields or types + *
              22. a type name followed by fields or types + *
              23. a package name followed a type and then fields or types + * + * If a type name is found, it rewrites itself as a {@code TypeExpression}. + * If a node decides it can only be a package prefix, it sets its + * type to {@code Type.tPackage}. The caller must detect this + * and act appropriately to verify the full package name. + * @arg loc the expression containing the ambiguous expression + */ + public Vset checkAmbigName(Environment env, Context ctx, Vset vset, Hashtable exp, + UnaryExpression loc) { + return checkValue(env, ctx, vset, exp); + } + + /** + * Check a condition. Return a ConditionVars(), which indicates when + * which variables are set if the condition is true, and which are set if + * the condition is false. + */ + public ConditionVars checkCondition(Environment env, Context ctx, + Vset vset, Hashtable exp) { + ConditionVars cvars = new ConditionVars(); + checkCondition(env, ctx, vset, exp, cvars); + return cvars; + } + + /* + * Check a condition. + * + * cvars is modified so that + * cvar.vsTrue indicates variables with a known value if result = true + * cvars.vsFalse indicates variables with a known value if !result + * + * The default action is to simply call checkValue on the expression, and + * to see both vsTrue and vsFalse to the result. + */ + + public void checkCondition(Environment env, Context ctx, + Vset vset, Hashtable exp, ConditionVars cvars) { + cvars.vsTrue = cvars.vsFalse = checkValue(env, ctx, vset, exp); + // unshare side effects: + cvars.vsFalse = cvars.vsFalse.copy(); + } + + /** + * Evaluate. + * + * Attempt to compute the value of an expression node. If all operands are + * literal constants of the same kind (e.g., IntegerExpression nodes), a + * new constant node of the proper type is returned representing the value + * as computed at compile-time. Otherwise, the original node 'this' is + * returned. + */ + Expression eval() { + return this; + } + + /** + * Simplify. + * + * Attempt to simplify an expression node by returning a semantically- + * equivalent expression that is presumably less costly to execute. There + * is some overlap with the intent of 'eval', as compile-time evaluation of + * conditional expressions and the short-circuit boolean operators is + * performed here. Other simplifications include logical identities + * involving logical negation and comparisons. If no simplification is + * possible, the original node 'this' is returned. It is assumed that the + * children of the node have previously been recursively simplified and + * evaluated. A result of 'null' indicates that the expression may be + * elided entirely. + */ + Expression simplify() { + return this; + } + + /** + * Inline. + * + * Recursively simplify each child of an expression node, destructively + * replacing the child with the simplified result. Also attempts to + * simplify the current node 'this', and returns the simplified result. + * + * The name 'inline' is somthing of a misnomer, as these methods are + * responsible for compile-time expression simplification in general. + * The 'eval' and 'simplify' methods apply to a single expression node + * only -- it is 'inline' and 'inlineValue' that drive the simplification + * of entire expressions. + */ + public Expression inline(Environment env, Context ctx) { + return null; + } + public Expression inlineValue(Environment env, Context ctx) { + return this; + } + + /** + * Attempt to evaluate this expression. If this expression + * yields a value, append it to the StringBuffer `buffer'. + * If this expression cannot be evaluated at this time (for + * example if it contains a division by zero, a non-constant + * subexpression, or a subexpression which "refuses" to evaluate) + * then return `null' to indicate failure. + * + * It is anticipated that this method will be called to evaluate + * concatenations of compile-time constant strings. The call + * originates from AddExpression#inlineValue(). + * + * See AddExpression#inlineValueSB() for detailed comments. + */ + protected StringBuffer inlineValueSB(Environment env, + Context ctx, + StringBuffer buffer) { + Expression inlined = inlineValue(env, ctx); + Object val = inlined.getValue(); + + if (val == null && !inlined.isNull()){ + // This (supposedly constant) expression refuses to yield + // a value. This can happen, in particular, when we are + // trying to evaluate a division by zero. It can also + // happen in cases where isConstant() is able to classify + // expressions as constant that the compiler's inlining + // mechanisms aren't able to evaluate; this is rare, + // and all such cases that we have found so far + // (e.g. 4082814, 4106244) have been plugged up. + // + // We return a null to indicate that we have failed to + // evaluate the concatenation. + return null; + } + + // For boolean and character expressions, getValue() returns + // an Integer. We need to take care, when appending the result + // of getValue(), that we preserve the type. + // Fix for 4103959, 4102672. + if (type == Type.tChar) { + buffer.append((char)((Integer)val).intValue()); + } else if (type == Type.tBoolean) { + buffer.append(((Integer)val).intValue() != 0); + } else { + buffer.append(val); + } + + return buffer; + } + + public Expression inlineLHS(Environment env, Context ctx) { + return null; + } + + /** + * The cost of inlining this expression. + * This cost controls the inlining of methods, and does not determine + * the compile-time simplifications performed by 'inline' and friends. + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + if (type.isType(TC_BOOLEAN)) { + codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_ifne : opc_ifeq, lbl, whenTrue); + } else { + throw new CompilerError("codeBranch " + opNames[op]); + } + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + if (type.isType(TC_BOOLEAN)) { + Label l1 = new Label(); + Label l2 = new Label(); + + codeBranch(env, ctx, asm, l1, true); + asm.add(true, where, opc_ldc, 0); + asm.add(true, where, opc_goto, l2); + asm.add(l1); + asm.add(true, where, opc_ldc, 1); + asm.add(l2); + } else { + throw new CompilerError("codeValue"); + } + } + public void code(Environment env, Context ctx, Assembler asm) { + codeValue(env, ctx, asm); + + switch (type.getTypeCode()) { + case TC_VOID: + break; + + case TC_DOUBLE: + case TC_LONG: + asm.add(where, opc_pop2); + break; + + default: + asm.add(where, opc_pop); + break; + } + } + int codeLValue(Environment env, Context ctx, Assembler asm) { + print(System.out); + throw new CompilerError("invalid lhs"); + } + void codeLoad(Environment env, Context ctx, Assembler asm) { + print(System.out); + throw new CompilerError("invalid load"); + } + void codeStore(Environment env, Context ctx, Assembler asm) { + print(System.out); + throw new CompilerError("invalid store"); + } + + /** + * Convert this expression to a string. + */ + void ensureString(Environment env, Context ctx, Assembler asm) + throws ClassNotFound, AmbiguousMember + { + if (type == Type.tString && isNonNull()) { + return; + } + // Make sure it's a non-null string. + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + ClassDeclaration stClass = env.getClassDeclaration(Type.tString); + ClassDefinition stClsDef = stClass.getClassDefinition(env); + // FIX FOR 4071548 + // We use 'String.valueOf' to do the conversion, in order to + // correctly handle null references and efficiently handle + // primitive types. For reference types, we force the argument + // to be interpreted as of 'Object' type, thus avoiding the + // the special-case overloading of 'valueOf' for character arrays. + // This special treatment would conflict with JLS 15.17.1.1. + if (type.inMask(TM_REFERENCE)) { + // Reference type + if (type != Type.tString) { + // Convert non-string object to string. If object is + // a string, we don't need to convert it, except in the + // case that it is null, which is handled below. + Type argType1[] = {Type.tObject}; + MemberDefinition f1 = + stClsDef.matchMethod(env, sourceClass, idValueOf, argType1); + asm.add(where, opc_invokestatic, f1); + } + // FIX FOR 4030173 + // If the argument was null, then value is "null", but if the + // argument was not null, 'toString' was called and could have + // returned null. We call 'valueOf' again to make sure that + // the result is a non-null string. See JLS 15.17.1.1. The + // approach taken here minimizes code size -- open code would + // be faster. The 'toString' method for an array class cannot + // be overridden, thus we know that it will never return null. + if (!type.inMask(TM_ARRAY|TM_NULL)) { + Type argType2[] = {Type.tString}; + MemberDefinition f2 = + stClsDef.matchMethod(env, sourceClass, idValueOf, argType2); + asm.add(where, opc_invokestatic, f2); + } + } else { + // Primitive type + Type argType[] = {type}; + MemberDefinition f = + stClsDef.matchMethod(env, sourceClass, idValueOf, argType); + asm.add(where, opc_invokestatic, f); + } + } + + /** + * Convert this expression to a string and append it to the string + * buffer on the top of the stack. + * If the needBuffer argument is true, the string buffer needs to be + * created, initialized, and pushed on the stack, first. + */ + void codeAppend(Environment env, Context ctx, Assembler asm, + ClassDeclaration sbClass, boolean needBuffer) + throws ClassNotFound, AmbiguousMember + { + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + ClassDefinition sbClsDef = sbClass.getClassDefinition(env); + MemberDefinition f; + if (needBuffer) { + // need to create the string buffer + asm.add(where, opc_new, sbClass); // create the class + asm.add(where, opc_dup); + if (equals("")) { + // make an empty string buffer + f = sbClsDef.matchMethod(env, sourceClass, idInit); + } else { + // optimize by initializing the buffer with the string + codeValue(env, ctx, asm); + ensureString(env, ctx, asm); + Type argType[] = {Type.tString}; + f = sbClsDef.matchMethod(env, sourceClass, idInit, argType); + } + asm.add(where, opc_invokespecial, f); + } else { + // append this item to the string buffer + codeValue(env, ctx, asm); + // FIX FOR 4071548 + // 'StringBuffer.append' converts its argument as if by + // 'valueOf', treating character arrays specially. This + // violates JLS 15.17.1.1, which requires that concatenation + // convert non-primitive arguments using 'toString'. We force + // the treatment of all reference types as type 'Object', thus + // invoking an overloading of 'append' that has the required + // semantics. + Type argType[] = + { (type.inMask(TM_REFERENCE) && type != Type.tString) + ? Type.tObject + : type }; + f = sbClsDef.matchMethod(env, sourceClass, idAppend, argType); + asm.add(where, opc_invokevirtual, f); + } + } + + /** + * Code + */ + void codeDup(Environment env, Context ctx, Assembler asm, int items, int depth) { + switch (items) { + case 0: + return; + + case 1: + switch (depth) { + case 0: + asm.add(where, opc_dup); + return; + case 1: + asm.add(where, opc_dup_x1); + return; + case 2: + asm.add(where, opc_dup_x2); + return; + + } + break; + case 2: + switch (depth) { + case 0: + asm.add(where, opc_dup2); + return; + case 1: + asm.add(where, opc_dup2_x1); + return; + case 2: + asm.add(where, opc_dup2_x2); + return; + + } + break; + } + throw new CompilerError("can't dup: " + items + ", " + depth); + } + + void codeConversion(Environment env, Context ctx, Assembler asm, Type f, Type t) { + int from = f.getTypeCode(); + int to = t.getTypeCode(); + + switch (to) { + case TC_BOOLEAN: + if (from != TC_BOOLEAN) { + break; + } + return; + case TC_BYTE: + if (from != TC_BYTE) { + codeConversion(env, ctx, asm, f, Type.tInt); + asm.add(where, opc_i2b); + } + return; + case TC_CHAR: + if (from != TC_CHAR) { + codeConversion(env, ctx, asm, f, Type.tInt); + asm.add(where, opc_i2c); + } + return; + case TC_SHORT: + if (from != TC_SHORT) { + codeConversion(env, ctx, asm, f, Type.tInt); + asm.add(where, opc_i2s); + } + return; + case TC_INT: + switch (from) { + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + return; + case TC_LONG: + asm.add(where, opc_l2i); + return; + case TC_FLOAT: + asm.add(where, opc_f2i); + return; + case TC_DOUBLE: + asm.add(where, opc_d2i); + return; + } + break; + case TC_LONG: + switch (from) { + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + asm.add(where, opc_i2l); + return; + case TC_LONG: + return; + case TC_FLOAT: + asm.add(where, opc_f2l); + return; + case TC_DOUBLE: + asm.add(where, opc_d2l); + return; + } + break; + case TC_FLOAT: + switch (from) { + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + asm.add(where, opc_i2f); + return; + case TC_LONG: + asm.add(where, opc_l2f); + return; + case TC_FLOAT: + return; + case TC_DOUBLE: + asm.add(where, opc_d2f); + return; + } + break; + case TC_DOUBLE: + switch (from) { + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + asm.add(where, opc_i2d); + return; + case TC_LONG: + asm.add(where, opc_l2d); + return; + case TC_FLOAT: + asm.add(where, opc_f2d); + return; + case TC_DOUBLE: + return; + } + break; + + case TC_CLASS: + switch (from) { + case TC_NULL: + return; + case TC_CLASS: + case TC_ARRAY: + try { + if (!env.implicitCast(f, t)) { + asm.add(where, opc_checkcast, env.getClassDeclaration(t)); + } + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + return; + } + + break; + + case TC_ARRAY: + switch (from) { + case TC_NULL: + return; + case TC_CLASS: + case TC_ARRAY: + try { + if (!env.implicitCast(f, t)) { + asm.add(where, opc_checkcast, t); + } + return; + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + } + break; + } + throw new CompilerError("codeConversion: " + from + ", " + to); + } + + /** + * Check if the first thing is a constructor invocation + */ + public Expression firstConstructor() { + return null; + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + return (Expression)clone(); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(opNames[op]); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ExpressionStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ExpressionStatement.java new file mode 100644 index 000000000..ab2196f15 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ExpressionStatement.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ExpressionStatement extends Statement { + Expression expr; + + /** + * Constructor + */ + public ExpressionStatement(long where, Expression expr) { + super(EXPRESSION, where); + this.expr = expr; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + return expr.check(env, ctx, reach(env, vset), exp); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (expr != null) { + expr = expr.inline(env, ctx); + return (expr == null) ? null : this; + } + return null; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + ExpressionStatement s = (ExpressionStatement)clone(); + s.expr = expr.copyInline(ctx); + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return expr.costInline(thresh, env, ctx); + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + expr.code(env, ctx, asm); + } + + /** + * Check if the first thing is a constructor invocation + */ + public Expression firstConstructor() { + return expr.firstConstructor(); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + if (expr != null) { + expr.print(out); + } else { + out.print(""); + } + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/FieldExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FieldExpression.java new file mode 100644 index 000000000..ce7aa38e4 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FieldExpression.java @@ -0,0 +1,1267 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.*; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class FieldExpression extends UnaryExpression { + Identifier id; + MemberDefinition field; + Expression implementation; + + // The class from which the field is select ed. + ClassDefinition clazz; + + // For an expression of the form '.super', then + // this is , else null. + private ClassDefinition superBase; + + /** + * constructor + */ + public FieldExpression(long where, Expression right, Identifier id) { + super(FIELD, where, Type.tError, right); + this.id = id; + } + public FieldExpression(long where, Expression right, MemberDefinition field) { + super(FIELD, where, field.getType(), right); + this.id = field.getName(); + this.field = field; + } + + public Expression getImplementation() { + if (implementation != null) + return implementation; + return this; + } + + /** + * Return true if the field is being selected from + * a qualified 'super'. + */ + private boolean isQualSuper() { + return superBase != null; + } + + /** + * Convert an '.' expression to a qualified identifier + */ + static public Identifier toIdentifier(Expression e) { + StringBuilder sb = new StringBuilder(); + while (e.op == FIELD) { + FieldExpression fe = (FieldExpression)e; + if (fe.id == idThis || fe.id == idClass) { + return null; + } + sb.insert(0, fe.id); + sb.insert(0, '.'); + e = fe.right; + } + if (e.op != IDENT) { + return null; + } + sb.insert(0, ((IdentifierExpression) e).id); + return Identifier.lookup(sb.toString()); + } + + /** + * Convert a qualified name into a type. + * Performs a careful check of each inner-class component, + * including the JLS 6.6.1 access checks that were omitted + * in 'FieldExpression.toType'. + *

                + * This code is similar to 'checkCommon', which could be cleaned + * up a bit long the lines we have done here. + */ + /*-------------------------------------------------------* + Type toQualifiedType(Environment env, Context ctx) { + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + Type rty = right.toQualifiedType(env, ctx); + if (rty == Type.tPackage) { + // Is this field expression a non-inner type? + Identifier nm = toIdentifier(this); + if ((nm != null) && env.classExists(nm)) { + Type t = Type.tClass(nm); + if (env.resolve(where, ctxClass, t)) { + return t; + } else { + return null; + } + } + // Not a type. Must be a package prefix. + return Type.tPackage; + } + if (rty == null) { + // An error was already reported, so quit. + return null; + } + + // Check inner-class qualification while unwinding from recursion. + try { + ClassDefinition rightClass = env.getClassDefinition(rty); + + // Local variables, which cannot be inner classes, + // are ignored here, and thus will not hide inner + // classes. Is this correct? + MemberDefinition field = rightClass.getInnerClass(env, id); + if (field == null) { + env.error(where, "inner.class.expected", id, rightClass); + return Type.tError; + } + + ClassDefinition innerClass = field.getInnerClass(); + Type t = innerClass.getType(); + + if (!ctxClass.canAccess(env, field)) { + env.error(where, "no.type.access", id, rightClass, ctxClass); + return t; + } + if (field.isProtected() + && !ctxClass.protectedAccess(env, field, rty)) { + env.error(where, "invalid.protected.type.use", id, ctxClass, rty); + return t; + } + + // These were omitted earlier in calls to 'toType', but I can't + // see any reason for that. I think it was an oversight. See + // 'checkCommon' and 'checkInnerClass'. + innerClass.noteUsedBy(ctxClass, where, env); + ctxClass.addDependency(field.getClassDeclaration()); + + return t; + + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, ctx.field); + } + + // Class not found. + return null; + } + *-------------------------------------------------------*/ + + /** + * Convert an '.' expression to a type + */ + + // This is a rewrite to treat qualified names in a + // context in which a type name is expected in the + // same way that they are handled for an ambiguous + // or expression-expected context in 'checkCommon' + // below. The new code is cleaner and allows better + // localization of errors. Unfortunately, most + // qualified names appearing in types are actually + // handled by 'Environment.resolve'. There isn't + // much point, then, in breaking out 'toType' as a + // special case until the other cases can be cleaned + // up as well. For the time being, we will leave this + // code disabled, thus reducing the testing requirements. + /*-------------------------------------------------------* + Type toType(Environment env, Context ctx) { + Type t = toQualifiedType(env, ctx); + if (t == null) { + return Type.tError; + } + if (t == Type.tPackage) { + FieldExpression.reportFailedPackagePrefix(env, right, true); + return Type.tError; + } + return t; + } + *-------------------------------------------------------*/ + + Type toType(Environment env, Context ctx) { + Identifier id = toIdentifier(this); + if (id == null) { + env.error(where, "invalid.type.expr"); + return Type.tError; + } + Type t = Type.tClass(ctx.resolveName(env, id)); + if (env.resolve(where, ctx.field.getClassDefinition(), t)) { + return t; + } + return Type.tError; + } + + /** + * Check if the present name is part of a scoping prefix. + */ + + public Vset checkAmbigName(Environment env, Context ctx, + Vset vset, Hashtable exp, + UnaryExpression loc) { + if (id == idThis || id == idClass) { + loc = null; // this cannot be a type or package + } + return checkCommon(env, ctx, vset, exp, loc, false); + } + + /** + * Check the expression + */ + + public Vset checkValue(Environment env, Context ctx, + Vset vset, Hashtable exp) { + vset = checkCommon(env, ctx, vset, exp, null, false); + if (id == idSuper && type != Type.tError) { + // "super" is not allowed in this context. + // It must always qualify another name. + env.error(where, "undef.var.super", idSuper); + } + return vset; + } + + /** + * If 'checkAmbiguousName' returns 'Package.tPackage', then it was + * unable to resolve any prefix of the qualified name. This method + * attempts to diagnose the problem. + */ + + static void reportFailedPackagePrefix(Environment env, Expression right) { + reportFailedPackagePrefix(env, right, false); + } + + static void reportFailedPackagePrefix(Environment env, + Expression right, + boolean mustBeType) { + // Find the leftmost component, and put the blame on it. + Expression idp = right; + while (idp instanceof UnaryExpression) + idp = ((UnaryExpression)idp).right; + IdentifierExpression ie = (IdentifierExpression)idp; + + // It may be that 'ie' refers to an ambiguous class. Check this + // with a call to env.resolve(). Part of solution for 4059855. + try { + env.resolve(ie.id); + } catch (AmbiguousClass e) { + env.error(right.where, "ambig.class", e.name1, e.name2); + return; + } catch (ClassNotFound e) { + } + + if (idp == right) { + if (mustBeType) { + env.error(ie.where, "undef.class", ie.id); + } else { + env.error(ie.where, "undef.var.or.class", ie.id); + } + } else { + if (mustBeType) { + env.error(ie.where, "undef.class.or.package", ie.id); + } else { + env.error(ie.where, "undef.var.class.or.package", ie.id); + } + } + } + + /** + * Rewrite accesses to private fields of another class. + */ + + private Expression + implementFieldAccess(Environment env, Context ctx, Expression base, boolean isLHS) { + ClassDefinition abase = accessBase(env, ctx); + if (abase != null) { + + // If the field is final and its initializer is a constant expression, + // then just rewrite to the constant expression. This is not just an + // optimization, but is required for correctness. If an expression is + // rewritten to use an access method, then its status as a constant + // expression is lost. This was the cause of bug 4098737. Note that + // a call to 'getValue(env)' below would not be correct, as it attempts + // to simplify the initial value expression, which must not occur until + // after the checking phase, for example, after definite assignment checks. + if (field.isFinal()) { + Expression e = (Expression)field.getValue(); + // Must not be LHS here. Test as a precaution, + // as we may not be careful to avoid this when + // compiling an erroneous program. + if ((e != null) && e.isConstant() && !isLHS) { + return e.copyInline(ctx); + } + } + + //System.out.println("Finding access method for " + field); + MemberDefinition af = abase.getAccessMember(env, ctx, field, isQualSuper()); + //System.out.println("Using access method " + af); + + if (!isLHS) { + //System.out.println("Reading " + field + + // " via access method " + af); + // If referencing the value of the field, then replace + // with a call to the access method. If assigning to + // the field, a call to the update method will be + // generated later. It is important that + // 'implementation' not be set to non-null if the + // expression is a valid assignment target. + // (See 'checkLHS'.) + if (field.isStatic()) { + Expression args[] = { }; + Expression call = + new MethodExpression(where, null, af, args); + return new CommaExpression(where, base, call); + } else { + Expression args[] = { base }; + return new MethodExpression(where, null, af, args); + } + } + } + + return null; + } + + /** + * Determine if an access method is required, and, if so, return + * the class in which it should appear, else return null. + */ + private ClassDefinition accessBase(Environment env, Context ctx) { + if (field.isPrivate()) { + ClassDefinition cdef = field.getClassDefinition(); + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + if (cdef == ctxClass){ + // If access from same class as field, then no access + // method is needed. + return null; + } + // An access method is needed in the class containing the field. + return cdef; + } else if (field.isProtected()) { + if (superBase == null) { + // If access is not via qualified super, then it is either + // OK without an access method, or it is an illegal access + // for which an error message should have been issued. + // Legal accesses include unqualified 'super.foo'. + return null; + } + ClassDefinition cdef = field.getClassDefinition(); + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + if (cdef.inSamePackage(ctxClass)) { + // Access to protected member in same package always allowed. + return null; + } + // Access via qualified super. + // An access method is needed in the qualifying class, an + // immediate subclass of the class containing the selected + // field. NOTE: The fact that the returned class is 'superBase' + // carries the additional bit of information (that a special + // superclass access method is being created) which is provided + // to 'getAccessMember' via its 'isSuper' argument. + return superBase; + } else { + // No access method needed. + return null; + } + } + + /** + * Determine if a type is accessible from a given class. + */ + static boolean isTypeAccessible(long where, + Environment env, + Type t, + ClassDefinition c) { + switch (t.getTypeCode()) { + case TC_CLASS: + try { + Identifier nm = t.getClassName(); + // Why not just use 'Environment.getClassDeclaration' here? + // But 'Environment.getClassDeclation' has special treatment + // for local classes that is probably necessary. This code + // was adapted from 'Environment.resolve'. + ClassDefinition def = env.getClassDefinition(t); + return c.canAccess(env, def.getClassDeclaration()); + } catch (ClassNotFound e) {} // Ignore -- reported elsewhere. + return true; + case TC_ARRAY: + return isTypeAccessible(where, env, t.getElementType(), c); + default: + return true; + } + } + + /** + * Common code for checkValue and checkAmbigName + */ + + private Vset checkCommon(Environment env, Context ctx, + Vset vset, Hashtable exp, + UnaryExpression loc, boolean isLHS) { + + // Handle class literal, e.g., 'x.class'. + if (id == idClass) { + + // In 'x.class', 'x' must be a type name, possibly qualified. + Type t = right.toType(env, ctx); + + if (!t.isType(TC_CLASS) && !t.isType(TC_ARRAY)) { + if (t.isType(TC_ERROR)) { + type = Type.tClassDesc; + return vset; + } + String wrc = null; + switch (t.getTypeCode()) { + case TC_VOID: wrc = "Void"; break; + case TC_BOOLEAN: wrc = "Boolean"; break; + case TC_BYTE: wrc = "Byte"; break; + case TC_CHAR: wrc = "Character"; break; + case TC_SHORT: wrc = "Short"; break; + case TC_INT: wrc = "Integer"; break; + case TC_FLOAT: wrc = "Float"; break; + case TC_LONG: wrc = "Long"; break; + case TC_DOUBLE: wrc = "Double"; break; + default: + env.error(right.where, "invalid.type.expr"); + return vset; + } + Identifier wid = Identifier.lookup(idJavaLang+"."+wrc); + Expression wcls = new TypeExpression(where, Type.tClass(wid)); + implementation = new FieldExpression(where, wcls, idTYPE); + vset = implementation.checkValue(env, ctx, vset, exp); + type = implementation.type; // java.lang.Class + return vset; + } + + // Check for the bogus type `array of void' + if (t.isVoidArray()) { + type = Type.tClassDesc; + env.error(right.where, "void.array"); + return vset; + } + + // it is a class or array + long fwhere = ctx.field.getWhere(); + ClassDefinition fcls = ctx.field.getClassDefinition(); + MemberDefinition lookup = fcls.getClassLiteralLookup(fwhere); + + String sig = t.getTypeSignature(); + String className; + if (t.isType(TC_CLASS)) { + // sig is like "Lfoo/bar;", name is like "foo.bar". + // We assume SIG_CLASS and SIG_ENDCLASS are 1 char each. + className = sig.substring(1, sig.length()-1) + .replace(SIGC_PACKAGE, '.'); + } else { + // sig is like "[Lfoo/bar;" or "[I"; + // name is like "[Lfoo.bar" or (again) "[I". + className = sig.replace(SIGC_PACKAGE, '.'); + } + + if (fcls.isInterface()) { + // The immediately-enclosing type is an interface. + // The class literal can only appear in an initialization + // expression, so don't bother caching it. (This could + // lose if many initializations use the same class literal, + // but saves time and code space otherwise.) + implementation = + makeClassLiteralInlineRef(env, ctx, lookup, className); + } else { + // Cache the call to the helper, as it may be executed + // many times (e.g., if the class literal is inside a loop). + ClassDefinition inClass = lookup.getClassDefinition(); + MemberDefinition cfld = + getClassLiteralCache(env, ctx, className, inClass); + implementation = + makeClassLiteralCacheRef(env, ctx, lookup, cfld, className); + } + + vset = implementation.checkValue(env, ctx, vset, exp); + type = implementation.type; // java.lang.Class + return vset; + } + + // Arrive here if not a class literal. + + if (field != null) { + + // The field as been pre-set, e.g., as the result of transforming + // an 'IdentifierExpression'. Most error-checking has already been + // performed at this point. + // QUERY: Why don't we further unify checking of identifier + // expressions and field expressions that denote instance and + // class variables? + + implementation = implementFieldAccess(env, ctx, right, isLHS); + return (right == null) ? + vset : right.checkAmbigName(env, ctx, vset, exp, this); + } + + // Does the qualifier have a meaning of its own? + vset = right.checkAmbigName(env, ctx, vset, exp, this); + if (right.type == Type.tPackage) { + // Are we out of options? + if (loc == null) { + FieldExpression.reportFailedPackagePrefix(env, right); + return vset; + } + + // ASSERT(loc.right == this) + + // Nope. Is this field expression a type? + Identifier nm = toIdentifier(this); + if ((nm != null) && env.classExists(nm)) { + loc.right = new TypeExpression(where, Type.tClass(nm)); + // Check access. (Cf. IdentifierExpression.toResolvedType.) + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + env.resolve(where, ctxClass, loc.right.type); + return vset; + } + + // Let the caller make sense of it, then. + type = Type.tPackage; + return vset; + } + + // Good; we have a well-defined qualifier type. + + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + boolean staticRef = (right instanceof TypeExpression); + + try { + + // Handle array 'length' field, e.g., 'x.length'. + + if (!right.type.isType(TC_CLASS)) { + if (right.type.isType(TC_ARRAY) && id.equals(idLength)) { + // Verify that the type of the base expression is accessible. + // Required by JLS 6.6.1. Fixes 4094658. + if (!FieldExpression.isTypeAccessible(where, env, right.type, ctxClass)) { + ClassDeclaration cdecl = ctxClass.getClassDeclaration(); + if (staticRef) { + env.error(where, "no.type.access", + id, right.type.toString(), cdecl); + } else { + env.error(where, "cant.access.member.type", + id, right.type.toString(), cdecl); + } + } + type = Type.tInt; + implementation = new LengthExpression(where, right); + return vset; + } + if (!right.type.isType(TC_ERROR)) { + env.error(where, "invalid.field.reference", id, right.type); + } + return vset; + } + + // At this point, we know that 'right.type' is a class type. + + // Note that '.super(...)' and '.this(...)' cases never + // reach here. Instead, '' is stored as the 'outerArg' field + // of a 'SuperExpression' or 'ThisExpression' node. + + // If our prefix is of the form '.super', then we are + // about to do a field selection '.super.'. + // Save the qualifying class in 'superBase', which is non-null + // only if the current FieldExpression is a qualified 'super' form. + // Also, set 'sourceClass' to the "effective accessing class" relative + // to which access checks will be performed. Normally, this is the + // immediately enclosing class. For '.this' and '.super', + // however, we use . + + ClassDefinition sourceClass = ctxClass; + if (right instanceof FieldExpression) { + Identifier id = ((FieldExpression)right).id; + if (id == idThis) { + sourceClass = ((FieldExpression)right).clazz; + } else if (id == idSuper) { + sourceClass = ((FieldExpression)right).clazz; + superBase = sourceClass; + } + } + + // Handle 'class.this' and 'class.super'. + // + // Suppose 'super.name' appears within a class C with immediate + // superclass S. According to JLS 15.10.2, 'super.name' in this + // case is equivalent to '((S)this).name'. Analogously, we interpret + // 'class.super.name' as '((S)(class.this)).name', where S is the + // immediate superclass of (enclosing) class 'class'. + // Note that 'super' may not stand alone as an expression, but must + // occur as the qualifying expression of a field access or a method + // invocation. This is enforced in 'SuperExpression.checkValue' and + // 'FieldExpression.checkValue', and need not concern us here. + + //ClassDefinition clazz = env.getClassDefinition(right.type); + clazz = env.getClassDefinition(right.type); + if (id == idThis || id == idSuper) { + if (!staticRef) { + env.error(right.where, "invalid.type.expr"); + } + + // We used to check that 'right.type' is accessible here, + // per JLS 6.6.1. As a result of the fix for 4102393, however, + // the qualifying class name must exactly match an enclosing + // outer class, which is necessarily accessible. + + /*** Temporary assertion check ***/ + if (ctx.field.isSynthetic()) + throw new CompilerError("synthetic qualified this"); + /*********************************/ + + // A.this means we're inside an A and we want its self ptr. + // C.this is always the same as this when C is innermost. + // Another A.this means we skip out to get a "hidden" this, + // just as ASuper.foo skips out to get a hidden variable. + // Last argument 'true' means we want an exact class match, + // not a subclass of the specified class ('clazz'). + implementation = ctx.findOuterLink(env, where, clazz, null, true); + vset = implementation.checkValue(env, ctx, vset, exp); + if (id == idSuper) { + type = clazz.getSuperClass().getType(); + } else { + type = clazz.getType(); + } + return vset; + } + + // Field should be an instance variable or class variable. + field = clazz.getVariable(env, id, sourceClass); + + if (field == null && staticRef && loc != null) { + // Is this field expression an inner type? + // Search the class and its supers (but not its outers). + // QUERY: We may need to get the inner class from a + // superclass of 'clazz'. This call is prepared to + // resolve the superclass if necessary. Can we arrange + // to assure that it is always previously resolved? + // This is one of a small number of problematic calls that + // requires 'getSuperClass' to resolve superclasses on demand. + // See 'ClassDefinition.getInnerClass(env, nm)'. + field = clazz.getInnerClass(env, id); + if (field != null) { + return checkInnerClass(env, ctx, vset, exp, loc); + } + } + + // If not a variable reference, diagnose error if name is + // that of a method. + + if (field == null) { + if ((field = clazz.findAnyMethod(env, id)) != null) { + env.error(where, "invalid.field", + id, field.getClassDeclaration()); + } else { + env.error(where, "no.such.field", id, clazz); + } + return vset; + } + + // At this point, we have identified a valid field. + + // Required by JLS 6.6.1. Fixes 4094658. + if (!FieldExpression.isTypeAccessible(where, env, right.type, sourceClass)) { + ClassDeclaration cdecl = sourceClass.getClassDeclaration(); + if (staticRef) { + env.error(where, "no.type.access", + id, right.type.toString(), cdecl); + } else { + env.error(where, "cant.access.member.type", + id, right.type.toString(), cdecl); + } + } + + type = field.getType(); + + if (!sourceClass.canAccess(env, field)) { + env.error(where, "no.field.access", + id, clazz, sourceClass.getClassDeclaration()); + return vset; + } + + if (staticRef && !field.isStatic()) { + // 'Class.field' is not legal when field is not static; + // see JLS 15.13.1. This case was permitted by javac + // prior to 1.2; static refs were silently changed to + // be dynamic access of the form 'this.field'. + env.error(where, "no.static.field.access", id, clazz); + return vset; + } else { + // Rewrite access to use an access method if necessary. + implementation = implementFieldAccess(env, ctx, right, isLHS); + } + + // Check for invalid access to protected field. + if (field.isProtected() + && !(right instanceof SuperExpression + // Extension of JLS 6.6.2 for qualified 'super'. + || (right instanceof FieldExpression && + ((FieldExpression)right).id == idSuper)) + && !sourceClass.protectedAccess(env, field, right.type)) { + env.error(where, "invalid.protected.field.use", + field.getName(), field.getClassDeclaration(), + right.type); + return vset; + } + + if ((!field.isStatic()) && + (right.op == THIS) && !vset.testVar(ctx.getThisNumber())) { + env.error(where, "access.inst.before.super", id); + } + + if (field.reportDeprecated(env)) { + env.error(where, "warn."+"field.is.deprecated", + id, field.getClassDefinition()); + } + + // When a package-private class defines public or protected + // members, those members may sometimes be accessed from + // outside of the package in public subclasses. In these + // cases, we need to massage the getField to refer to + // to an accessible subclass rather than the package-private + // parent class. Part of fix for 4135692. + + // Find out if the class which contains this field + // reference has access to the class which declares the + // public or protected field. + if (sourceClass == ctxClass) { + ClassDefinition declarer = field.getClassDefinition(); + if (declarer.isPackagePrivate() && + !declarer.getName().getQualifier() + .equals(sourceClass.getName().getQualifier())) { + + //System.out.println("The access of member " + + // field + " declared in class " + + // declarer + + // " is not allowed by the VM from class " + + // ctxClass + + // ". Replacing with an access of class " + + // clazz); + + // We cannot make this access at the VM level. + // Construct a member which will stand for this + // field in ctxClass and set `field' to refer to it. + field = + MemberDefinition.makeProxyMember(field, clazz, env); + } + } + + sourceClass.addDependency(field.getClassDeclaration()); + + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, ctx.field); + + } catch (AmbiguousMember e) { + env.error(where, "ambig.field", + id, e.field1.getClassDeclaration(), e.field2.getClassDeclaration()); + } + return vset; + } + + /** + * Return a FieldUpdater object to be used in updating the + * value of the location denoted by this, which must be an + * expression suitable for the left-hand side of an assignment. + * This is used for implementing assignments to private fields for which + * an access method is required. Returns null if no access method is + * needed, in which case the assignment is handled in the usual way, by + * direct access. Only simple assignment expressions are handled here + * Assignment operators and pre/post increment/decrement operators are + * are handled by 'getUpdater' below. + *

                + * Must be called after 'checkValue', else 'right' will be invalid. + */ + + + public FieldUpdater getAssigner(Environment env, Context ctx) { + if (field == null) { + // Field can legitimately be null if the field name was + // undefined, in which case an error was reported, but + // no value for 'field' is available. + // throw new CompilerError("getAssigner"); + return null; + } + ClassDefinition abase = accessBase(env, ctx); + if (abase != null) { + MemberDefinition setter = abase.getUpdateMember(env, ctx, field, isQualSuper()); + // It may not be necessary to copy 'right' here. + Expression base = (right == null) ? null : right.copyInline(ctx); + // Created 'FieldUpdater' has no getter method. + return new FieldUpdater(where, field, base, null, setter); + } + return null; + } + + /** + * Return a FieldUpdater object to be used in updating the + * value of the location denoted by this, which must be an + * expression suitable for the left-hand side of an assignment. This is + * used for implementing the assignment operators and the increment and + * decrement operators on private fields that are accessed from another + * class, e.g, uplevel from an inner class. Returns null if no access + * method is needed. + *

                + * Must be called after 'checkValue', else 'right' will be invalid. + */ + + public FieldUpdater getUpdater(Environment env, Context ctx) { + if (field == null) { + // Field can legitimately be null if the field name was + // undefined, in which case an error was reported, but + // no value for 'field' is available. + // throw new CompilerError("getUpdater"); + return null; + } + ClassDefinition abase = accessBase(env, ctx); + if (abase != null) { + MemberDefinition getter = abase.getAccessMember(env, ctx, field, isQualSuper()); + MemberDefinition setter = abase.getUpdateMember(env, ctx, field, isQualSuper()); + // It may not be necessary to copy 'right' here. + Expression base = (right == null) ? null : right.copyInline(ctx); + return new FieldUpdater(where, field, base, getter, setter); + } + return null; + } + + /** + * This field expression is an inner class reference. + * Finish checking it. + */ + private Vset checkInnerClass(Environment env, Context ctx, + Vset vset, Hashtable exp, + UnaryExpression loc) { + ClassDefinition inner = field.getInnerClass(); + type = inner.getType(); + + if (!inner.isTopLevel()) { + env.error(where, "inner.static.ref", inner.getName()); + } + + Expression te = new TypeExpression(where, type); + + // check access + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + try { + if (!ctxClass.canAccess(env, field)) { + ClassDefinition clazz = env.getClassDefinition(right.type); + //env.error(where, "no.type.access", + // id, clazz, ctx.field.getClassDeclaration()); + env.error(where, "no.type.access", + id, clazz, ctxClass.getClassDeclaration()); + return vset; + } + + if (field.isProtected() + && !(right instanceof SuperExpression + // Extension of JLS 6.6.2 for qualified 'super'. + || (right instanceof FieldExpression && + ((FieldExpression)right).id == idSuper)) + && !ctxClass.protectedAccess(env, field, right.type)){ + env.error(where, "invalid.protected.field.use", + field.getName(), field.getClassDeclaration(), + right.type); + return vset; + } + + inner.noteUsedBy(ctxClass, where, env); + + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, ctx.field); + } + + ctxClass.addDependency(field.getClassDeclaration()); + if (loc == null) + // Complain about a free-floating type name. + return te.checkValue(env, ctx, vset, exp); + loc.right = te; + return vset; + } + + /** + * Check the expression if it appears on the LHS of an assignment + */ + public Vset checkLHS(Environment env, Context ctx, + Vset vset, Hashtable exp) { + boolean hadField = (field != null); + + //checkValue(env, ctx, vset, exp); + checkCommon(env, ctx, vset, exp, null, true); + + // If 'implementation' is set to a non-null value, then the + // field expression does not denote an assignable location, + // e.g., the 'length' field of an array. + if (implementation != null) { + // This just reports an error and recovers. + return super.checkLHS(env, ctx, vset, exp); + } + + if (field != null && field.isFinal() && !hadField) { + if (field.isBlankFinal()) { + if (field.isStatic()) { + if (right != null) { + env.error(where, "qualified.static.final.assign"); + } + // Continue with checking anyhow. + // In fact, it would be easy to allow this case. + } else { + if ((right != null) && (right.op != THIS)) { + env.error(where, "bad.qualified.final.assign", field.getName()); + // The actual instance could be anywhere, so don't + // continue with checking the definite assignment status. + return vset; + } + } + vset = checkFinalAssign(env, ctx, vset, where, field); + } else { + env.error(where, "assign.to.final", id); + } + } + return vset; + } + + /** + * Check the expression if it appears on the LHS of an op= expression + */ + public Vset checkAssignOp(Environment env, Context ctx, + Vset vset, Hashtable exp, Expression outside) { + + //checkValue(env, ctx, vset, exp); + checkCommon(env, ctx, vset, exp, null, true); + + // If 'implementation' is set to a non-null value, then the + // field expression does not denote an assignable location, + // e.g., the 'length' field of an array. + if (implementation != null) { + return super.checkLHS(env, ctx, vset, exp); + } + if (field != null && field.isFinal()) { + env.error(where, "assign.to.final", id); + } + return vset; + } + + /** + * There is a simple assignment being made to the given final field. + * The field was named either by a simple name or by an almost-simple + * expression of the form "this.v". + * Check if this is a legal assignment. + *

                + * Blank final variables can be set in initializers or constructor + * bodies. In all cases there must be definite single assignment. + * (All instance and instance variable initializers and each + * constructor body are treated as if concatenated for the purposes + * of this check. Assignment to "this.x" is treated as a definite + * assignment to the simple name "x" which names the instance variable.) + */ + + public static Vset checkFinalAssign(Environment env, Context ctx, + Vset vset, long where, + MemberDefinition field) { + if (field.isBlankFinal() + && field.getClassDefinition() == ctx.field.getClassDefinition()) { + int number = ctx.getFieldNumber(field); + if (number >= 0 && vset.testVarUnassigned(number)) { + // definite single assignment + vset = vset.addVar(number); + } else { + // it is a blank final in this class, but not assignable + Identifier id = field.getName(); + env.error(where, "assign.to.blank.final", id); + } + } else { + // give the generic error message + Identifier id = field.getName(); + env.error(where, "assign.to.final", id); + } + return vset; + } + + private static MemberDefinition getClassLiteralCache(Environment env, + Context ctx, + String className, + ClassDefinition c) { + // Given a class name, look for a static field to cache it. + // className lname + // pkg.Foo class$pkg$Foo + // [Lpkg.Foo; array$Lpkg$Foo + // [[Lpkg.Foo; array$$Lpkg$Foo + // [I array$I + // [[I array$$I + String lname; + if (!className.startsWith(SIG_ARRAY)) { + lname = prefixClass + className.replace('.', '$'); + } else { + lname = prefixArray + className.substring(1); + lname = lname.replace(SIGC_ARRAY, '$'); // [[[I => array$$$I + if (className.endsWith(SIG_ENDCLASS)) { + // [Lpkg.Foo; => array$Lpkg$Foo + lname = lname.substring(0, lname.length() - 1); + lname = lname.replace('.', '$'); + } + // else [I => array$I or some such; lname is already OK + } + Identifier fname = Identifier.lookup(lname); + + // The class to put the cache in is now given as an argument. + // + // ClassDefinition c = ctx.field.getClassDefinition(); + // while (c.isInnerClass()) { + // c = c.getOuterClass(); + + MemberDefinition cfld; + try { + cfld = c.getVariable(env, fname, c); + } catch (ClassNotFound ee) { + return null; + } catch (AmbiguousMember ee) { + return null; + } + + // Ignore inherited field. Each top-level class + // containing a given class literal must have its own copy, + // both for reasons of binary compatibility and to prevent + // access violations should the superclass be in another + // package. Part of fix 4106051. + if (cfld != null && cfld.getClassDefinition() == c) { + return cfld; + } + + // Since each class now has its own copy, we might as well + // tighten up the access to private (previously default). + // Part of fix for 4106051. + // ** Temporarily retract this, as it tickles 4098316. + return env.makeMemberDefinition(env, c.getWhere(), + c, null, + M_STATIC | M_SYNTHETIC, // M_PRIVATE, + Type.tClassDesc, fname, + null, null, null); + } + + private Expression makeClassLiteralCacheRef(Environment env, Context ctx, + MemberDefinition lookup, + MemberDefinition cfld, + String className) { + Expression ccls = new TypeExpression(where, + cfld.getClassDefinition() + .getType()); + Expression cache = new FieldExpression(where, ccls, cfld); + Expression cacheOK = + new NotEqualExpression(where, cache.copyInline(ctx), + new NullExpression(where)); + Expression lcls = + new TypeExpression(where, lookup.getClassDefinition() .getType()); + Expression name = new StringExpression(where, className); + Expression namearg[] = { name }; + Expression setCache = new MethodExpression(where, lcls, + lookup, namearg); + setCache = new AssignExpression(where, cache.copyInline(ctx), + setCache); + return new ConditionalExpression(where, cacheOK, cache, setCache); + } + + private Expression makeClassLiteralInlineRef(Environment env, Context ctx, + MemberDefinition lookup, + String className) { + Expression lcls = + new TypeExpression(where, lookup.getClassDefinition().getType()); + Expression name = new StringExpression(where, className); + Expression namearg[] = { name }; + Expression getClass = new MethodExpression(where, lcls, + lookup, namearg); + return getClass; + } + + + /** + * Check if constant: Will it inline away? + */ + public boolean isConstant() { + if (implementation != null) + return implementation.isConstant(); + if ((field != null) + && (right == null || right instanceof TypeExpression + || (right.op == THIS && right.where == where))) { + return field.isConstant(); + } + return false; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + if (implementation != null) + return implementation.inline(env, ctx); + // A field expression may have the side effect of causing + // a NullPointerException, so evaluate it even though + // the value is not needed. Similarly, static field dereferences + // may cause class initialization, so they mustn't be omitted + // either. + // + // However, NullPointerException can't happen and initialization must + // already have occurred if you are dotting into 'this'. So + // allow fields of 'this' to be eliminated as a special case. + Expression e = inlineValue(env, ctx); + if (e instanceof FieldExpression) { + FieldExpression fe = (FieldExpression) e; + if ((fe.right != null) && (fe.right.op==THIS)) + return null; + // It should be possible to split this into two checks: one using + // isNonNull() for non-statics and a different check for statics. + // That would make the inlining slightly less conservative by + // allowing, for example, dotting into String constants. + } + return e; + } + public Expression inlineValue(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineValue(env, ctx); + try { + if (field == null) { + return this; + } + + if (field.isFinal()) { + Expression e = (Expression)field.getValue(env); + if ((e != null) && e.isConstant()) { + // remove bogus line-number info + e = e.copyInline(ctx); + e.where = where; + return new CommaExpression(where, right, e).inlineValue(env, ctx); + } + } + + if (right != null) { + if (field.isStatic()) { + Expression e = right.inline(env, ctx); + right = null; + if (e != null) { + return new CommaExpression(where, e, this); + } + } else { + right = right.inlineValue(env, ctx); + } + } + return this; + + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + } + public Expression inlineLHS(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineLHS(env, ctx); + if (right != null) { + if (field.isStatic()) { + Expression e = right.inline(env, ctx); + right = null; + if (e != null) { + return new CommaExpression(where, e, this); + } + } else { + right = right.inlineValue(env, ctx); + } + } + return this; + } + + public Expression copyInline(Context ctx) { + if (implementation != null) + return implementation.copyInline(ctx); + return super.copyInline(ctx); + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + if (implementation != null) + return implementation.costInline(thresh, env, ctx); + if (ctx == null) { + return 3 + ((right == null) ? 0 + : right.costInline(thresh, env, ctx)); + } + // ctxClass is the current class trying to inline this method + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + try { + // We only allow the inlining if the current class can access + // the field, the field's class, and right's declared type. + if ( ctxClass.permitInlinedAccess(env, field.getClassDeclaration()) + && ctxClass.permitInlinedAccess(env, field)) { + if (right == null) { + return 3; + } else { + ClassDeclaration rt = env.getClassDeclaration(right.type); + if (ctxClass.permitInlinedAccess(env, rt)) { + return 3 + right.costInline(thresh, env, ctx); + } + } + } + } catch (ClassNotFound e) { + } + return thresh; + } + + /** + * Code + */ + int codeLValue(Environment env, Context ctx, Assembler asm) { + if (implementation != null) + throw new CompilerError("codeLValue"); + if (field.isStatic()) { + if (right != null) { + right.code(env, ctx, asm); + return 1; + } + return 0; + } + right.codeValue(env, ctx, asm); + return 1; + } + void codeLoad(Environment env, Context ctx, Assembler asm) { + if (field == null) { + throw new CompilerError("should not be null"); + } + if (field.isStatic()) { + asm.add(where, opc_getstatic, field); + } else { + asm.add(where, opc_getfield, field); + } + } + void codeStore(Environment env, Context ctx, Assembler asm) { + if (field.isStatic()) { + asm.add(where, opc_putstatic, field); + } else { + asm.add(where, opc_putfield, field); + } + } + + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeLValue(env, ctx, asm); + codeLoad(env, ctx, asm); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("("); + if (right != null) { + right.print(out); + } else { + out.print(""); + } + out.print("." + id + ")"); + if (implementation != null) { + out.print("/IMPL="); + implementation.print(out); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/FieldUpdater.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FieldUpdater.java new file mode 100644 index 000000000..ace4c0fb3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FieldUpdater.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * This class encapsulates the information required to generate an update to a private + * field referenced from another class, e.g., an inner class. An expression denoting a + * reference to the object to which the field belongs is associated with getter and + * setter methods. + *

                + * We use this class only for assignment, increment, and decrement operators, in which + * the old value is first retrieved and then a new value is computed and stored. + * Simple assignment expressions in which a value is copied without modification are + * handled by another mechanism. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ + +class FieldUpdater implements Constants { + + // Location for reporting errors. + // Errors will always indicate compiler failure, but these will be easier to diagnose + // if the bogus error is localized to the offending assignment. + private long where; + + // The field to which this updater applies. + // It would be easy to eliminate the need to store the field here, but we retain it for + // diagnostic purposes. + private MemberDefinition field; + + // Expression denoting the object to which the getter and setter are applied. + // If the field is static, 'base' may be null, but need not be, as a static field + // may be selected from an object reference. Even though the value of the object + // reference will be ignored, it may have side-effects. + private Expression base; + + // The getter and setter methods, generated by 'getAccessMember' and 'getUpdateMember'. + private MemberDefinition getter; + private MemberDefinition setter; + + // The number of words occupied on the stack by the object reference. + // For static fields, this is zero. + private int depth; + + /** + * Constructor. + */ + + public FieldUpdater(long where, MemberDefinition field, + Expression base, MemberDefinition getter, MemberDefinition setter) { + this.where = where; + this.field = field; + this.base = base; + this.getter = getter; + this.setter = setter; + } + + + /** + * Since the object reference expression may be captured before it has been inlined, + * we must inline it later. A FieldUpdater is inlined essentially as if + * it were a child of the assignment node to which it belongs. + */ + + public FieldUpdater inline(Environment env, Context ctx) { + if (base != null) { + if (field.isStatic()) { + base = base.inline(env, ctx); + } else { + base = base.inlineValue(env, ctx); + } + } + return this; + } + + public FieldUpdater copyInline(Context ctx) { + return new FieldUpdater(where, field, base.copyInline(ctx), getter, setter); + } + + public int costInline(int thresh, Environment env, Context ctx, boolean needGet) { + // Size of 'invokestatic' call for access method is 3 bytes. + int cost = needGet ? 7 : 3; // getter needs extra invokestatic + dup + // Size of expression to compute 'this' arg if needed. + if (!field.isStatic() && base != null) { + cost += base.costInline(thresh, env, ctx); + } + // We ignore the cost of duplicating value in value-needed context. + return cost; + } + + /** + * Duplicate items words from the top of the stack, locating them + * below the topmost depth words on the stack. + */ + + // This code was cribbed from 'Expression.java'. We cannot reuse that code here, + // because we do not inherit from class 'Expression'. + + private void codeDup(Assembler asm, int items, int depth) { + switch (items) { + case 0: + return; + case 1: + switch (depth) { + case 0: + asm.add(where, opc_dup); + return; + case 1: + asm.add(where, opc_dup_x1); + return; + case 2: + asm.add(where, opc_dup_x2); + return; + + } + break; + case 2: + switch (depth) { + case 0: + asm.add(where, opc_dup2); + return; + case 1: + asm.add(where, opc_dup2_x1); + return; + case 2: + asm.add(where, opc_dup2_x2); + return; + + } + break; + } + throw new CompilerError("can't dup: " + items + ", " + depth); + } + + /** + * Begin a field update by an assignment, increment, or decrement operator. + * The current value of the field is left at the top of the stack. + * If valNeeded is true, we arrange for the initial value to remain + * on the stack after the update. + */ + + public void startUpdate(Environment env, Context ctx, Assembler asm, boolean valNeeded) { + if (!(getter.isStatic() && setter.isStatic())) { + throw new CompilerError("startUpdate isStatic"); + } + if (!field.isStatic()) { + // Provide explicit 'this' argument. + base.codeValue(env, ctx, asm); + depth = 1; + } else { + // May need to evaluate 'base' for effect. + // If 'base' was a type expression, it should have previously been inlined away. + if (base != null) { + base.code(env, ctx, asm); + } + depth = 0; + } + codeDup(asm, depth, 0); + asm.add(where, opc_invokestatic, getter); + if (valNeeded) { + codeDup(asm, field.getType().stackSize(), depth); + } + } + + /** + * Complete a field update by an assignment, increment, or decrement operator. + * The original value of the field left on the stack by startUpdate + * must have been replaced with the updated value, with no other stack alterations. + * If valNeeded is true, we arrange for the updated value to remain + * on the stack after the update. The valNeeded argument must not be + * true in both startUpdate and finishUpdate. + */ + + public void finishUpdate(Environment env, Context ctx, Assembler asm, boolean valNeeded) { + if (valNeeded) { + codeDup(asm, field.getType().stackSize(), depth); + } + asm.add(where, opc_invokestatic, setter); + } + + /** + * Like above, but used when assigning a new value independent of the + * old, as in a simple assignment expression. After 'startAssign', + * code must be emitted to leave one additional value on the stack without + * altering any others, followed by 'finishAssign'. + */ + + public void startAssign(Environment env, Context ctx, Assembler asm) { + if (!setter.isStatic()) { + throw new CompilerError("startAssign isStatic"); + } + if (!field.isStatic()) { + // Provide explicit 'this' argument. + base.codeValue(env, ctx, asm); + depth = 1; + } else { + // May need to evaluate 'base' for effect. + // If 'base' was a type expression, it should have previously been inlined away. + if (base != null) { + base.code(env, ctx, asm); + } + depth = 0; + } + } + + public void finishAssign(Environment env, Context ctx, Assembler asm, boolean valNeeded) { + if (valNeeded) { + codeDup(asm, field.getType().stackSize(), depth); + } + asm.add(where, opc_invokestatic, setter); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/FinallyStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FinallyStatement.java new file mode 100644 index 000000000..c45e3eecf --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FinallyStatement.java @@ -0,0 +1,345 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.TryData; +import org.glassfish.rmic.tools.asm.CatchData; +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Enumeration; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class FinallyStatement extends Statement { + Statement body; + Statement finalbody; + boolean finallyCanFinish; // does finalBody never return? + boolean needReturnSlot; // set by inner return statement + Statement init; // try object expression or declaration from parser + LocalMember tryTemp; // temp holding the try object, if any + + /** + * Constructor + */ + public FinallyStatement(long where, Statement body, Statement finalbody) { + super(FINALLY, where); + this.body = body; + this.finalbody = finalbody; + } + +// /** +// * Constructor for try (init) {body} +// */ +// public FinallyStatement(long where, Statement init, Statement body, int junk) { +// this(where, body, null); +// this.init = init; +// } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = reach(env, vset); + Hashtable newexp = new Hashtable<>(); + + // Handle the proposed 'try (init) { stmts } finally { stmts }' syntax. + // This feature has not been adopted, and support is presently disabled. + /*-----------------------------------------------------------* + if (init != null) { + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + Expression tryExpr = null; + DeclarationStatement tryDecl = null; + long where = init.getWhere(); + // find out whether init is a simple expression or a declaration + if (init.getOp() == EXPRESSION) { + tryExpr = ((ExpressionStatement)init).expr; + init = null; // restore it below + vset = tryExpr.checkValue(env, ctx, vset, exp); + } else if (init.getOp() == DECLARATION) { + tryDecl = (DeclarationStatement) init; + init = null; // restore it below + vset = tryDecl.checkBlockStatement(env, ctx, vset, exp); + if (tryDecl.args.length != 1) { + env.error(where, "invalid.decl"); + } else { + LocalMember field = + ((VarDeclarationStatement) tryDecl.args[0]).field; + tryExpr = new IdentifierExpression(where, field); + tryExpr.type = field.getType(); + } + } else { + env.error(where, "invalid.expr"); + vset = init.check(env, ctx, vset, exp); + } + Type type = (tryExpr == null) ? Type.tError : tryExpr.getType(); + + MemberDefinition tryEnter = null; + MemberDefinition tryExit = null; + if (!type.isType(TC_CLASS)) { + if (!type.isType(TC_ERROR)) { + env.error(where, "invalid.method.invoke", type); + } + } else { + Identifier idTryEnter = Identifier.lookup("tryEnter"); + Identifier idTryExit = Identifier.lookup("tryExit"); + Type tTryMethod = Type.tMethod(Type.tVoid); + try { + ClassDefinition tryClass = env.getClassDefinition(type); + tryEnter = tryClass.matchMethod(env, sourceClass, idTryEnter); + tryExit = tryClass.matchMethod(env, sourceClass, idTryExit); + if (tryEnter != null && !tryEnter.getType().equals(tTryMethod)) { + tryEnter = null; + } + if (tryExit != null && !tryExit.getType().equals(tTryMethod)) { + tryExit = null; + } + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, ctx.field); + } catch (AmbiguousMember ee) { + Identifier id = ee.field1.getName(); + env.error(where, "ambig.field", id, ee.field1, ee.field2); + } + } + if (tryEnter == null || tryExit == null) { + // Make a better (more didactic) error here! + env.error(where, "invalid.method.invoke", type); + } else { + tryTemp = new LocalMember(where, sourceClass, 0, + type, Identifier.lookup("")); + ctx = new Context(ctx, this); + ctx.declare(env, tryTemp); + + Expression e; + e = new IdentifierExpression(where, tryTemp); + e = new AssignExpression(where, e, tryExpr); + e = new MethodExpression(where, e, tryEnter, new Expression[0]); + e.type = Type.tVoid; + Statement enterCall = new ExpressionStatement(where, e); + // store it on the init, for code generation + if (tryDecl != null) { + Statement args2[] = { tryDecl.args[0], enterCall }; + tryDecl.args = args2; + init = tryDecl; + } else { + init = enterCall; + } + e = new IdentifierExpression(where, tryTemp); + e = new MethodExpression(where, e, tryExit, new Expression[0]); + e.type = Type.tVoid; + Statement exitCall = new ExpressionStatement(where, e); + finalbody = exitCall; + } + } + *-----------------------------------------------------------*/ + + // Check the try part. We reach the end of the try part either by + // finishing normally, or doing a break to the label of the try/finally. + // NOTE: I don't think newctx1.vsBreak is ever used -- see TryStatement. + CheckContext newctx1 = new CheckContext(ctx, this); + Vset vset1 = body.check(env, newctx1, vset.copy(), newexp) + .join(newctx1.vsBreak); + // Check the finally part. + CheckContext newctx2 = new CheckContext(ctx, this); + // Should never access this field. The null indicates the finally part. + newctx2.vsContinue = null; + Vset vset2 = finalbody.check(env, newctx2, vset, exp); + finallyCanFinish = !vset2.isDeadEnd(); + vset2 = vset2.join(newctx2.vsBreak); + // If !finallyCanFinish, then the only possible exceptions that can + // occur at this point are the ones preceding the try/finally, or + // the ones generated by the finally. Anything in the try is + // irrelevant. Otherwise, we have to merge in all the exceptions + // generated by the body into exp. + if (finallyCanFinish) { + // Add newexp's back into exp; cf. ThrowStatement.check(). + for (Enumeration e = newexp.keys() ; e.hasMoreElements() ; ) { + Object def = e.nextElement(); + exp.put(def, newexp.get(def)); + } + } + return ctx.removeAdditionalVars(vset1.addDAandJoinDU(vset2)); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (tryTemp != null) { + ctx = new Context(ctx, this); + ctx.declare(env, tryTemp); + } + if (init != null) { + init = init.inline(env, ctx); + } + if (body != null) { + body = body.inline(env, ctx); + } + if (finalbody != null) { + finalbody = finalbody.inline(env, ctx); + } + if (body == null) { + return eliminate(env, finalbody); + } + if (finalbody == null) { + return eliminate(env, body); + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + FinallyStatement s = (FinallyStatement)clone(); + if (tryTemp != null) { + s.tryTemp = tryTemp.copyInline(ctx); + } + if (init != null) { + s.init = init.copyInline(ctx, valNeeded); + } + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + if (finalbody != null) { + s.finalbody = finalbody.copyInline(ctx, valNeeded); + } + return s; + } + + /** + * Compute cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx){ + int cost = 4; + if (init != null) { + cost += init.costInline(thresh, env,ctx); + if (cost >= thresh) return cost; + } + if (body != null) { + cost += body.costInline(thresh, env,ctx); + if (cost >= thresh) return cost; + } + if (finalbody != null) { + cost += finalbody.costInline(thresh, env,ctx); + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + ctx = new Context(ctx); + Integer num1 = null, num2 = null; + Label endLabel = new Label(); + + if (tryTemp != null) { + ctx.declare(env, tryTemp); + } + if (init != null) { + CodeContext exprctx = new CodeContext(ctx, this); + init.code(env, exprctx, asm); + } + + if (finallyCanFinish) { + LocalMember f1, f2; + ClassDefinition thisClass = ctx.field.getClassDefinition(); + + if (needReturnSlot) { + Type returnType = ctx.field.getType().getReturnType(); + LocalMember localfield = new LocalMember(0, thisClass, 0, + returnType, + idFinallyReturnValue); + ctx.declare(env, localfield); + Environment.debugOutput("Assigning return slot to " + localfield.number); + } + + // allocate space for the exception and return address + f1 = new LocalMember(where, thisClass, 0, Type.tObject, null); + f2 = new LocalMember(where, thisClass, 0, Type.tInt, null); + num1 = ctx.declare(env, f1); + num2 = ctx.declare(env, f2); + } + + TryData td = new TryData(); + td.add(null); + + // Main body + CodeContext bodyctx = new CodeContext(ctx, this); + asm.add(where, opc_try, td); // start of protected code + body.code(env, bodyctx, asm); + asm.add(bodyctx.breakLabel); + asm.add(td.getEndLabel()); // end of protected code + + // Cleanup afer body + if (finallyCanFinish) { + asm.add(where, opc_jsr, bodyctx.contLabel); + asm.add(where, opc_goto, endLabel); + } else { + // just goto the cleanup code. It will never return. + asm.add(where, opc_goto, bodyctx.contLabel); + } + + // Catch code + CatchData cd = td.getCatch(0); + asm.add(cd.getLabel()); + if (finallyCanFinish) { + asm.add(where, opc_astore, num1); // store exception + asm.add(where, opc_jsr, bodyctx.contLabel); + asm.add(where, opc_aload, num1); // rethrow exception + asm.add(where, opc_athrow); + } else { + // pop exception off stack. Fall through to finally code + asm.add(where, opc_pop); + } + + // The finally part, which is marked by the contLabel. Update + // breakLabel: since break's in the finally are different + // contLabel: to null to indicate no longer in the protected code. + asm.add(bodyctx.contLabel); + bodyctx.contLabel = null; + bodyctx.breakLabel = endLabel; + if (finallyCanFinish) { + asm.add(where, opc_astore, num2); // save the return address + finalbody.code(env, bodyctx, asm); // execute the cleanup code + asm.add(where, opc_ret, num2); // return + } else { + finalbody.code(env, bodyctx, asm); // execute the cleanup code + } + asm.add(endLabel); // breaks come here + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("try "); + if (body != null) { + body.print(out, indent); + } else { + out.print(""); + } + out.print(" finally "); + if (finalbody != null) { + finalbody.print(out, indent); + } else { + out.print(""); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/FloatExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FloatExpression.java new file mode 100644 index 000000000..915dc7601 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/FloatExpression.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class FloatExpression extends ConstantExpression { + float value; + + /** + * Constructor + */ + public FloatExpression(long where, float value) { + super(FLOATVAL, where, Type.tFloat); + this.value = value; + } + + /** + * Get the value + */ + public Object getValue() { + return new Float(value); + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(int i) { + return value == i; + } + + /** + * Check if the expression is equal to its default static value + */ + public boolean equalsDefault() { + // don't allow -0.0 + return (Float.floatToIntBits(value) == 0); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ldc, new Float(value)); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value +"F"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ForStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ForStatement.java new file mode 100644 index 000000000..6e47f1595 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ForStatement.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ForStatement extends Statement { + Statement init; + Expression cond; + Expression inc; + Statement body; + + /** + * Constructor + */ + public ForStatement(long where, Statement init, Expression cond, Expression inc, Statement body) { + super(FOR, where); + this.init = init; + this.cond = cond; + this.inc = inc; + this.body = body; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + vset = reach(env, vset); + Context initctx = new Context(ctx, this); + if (init != null) { + vset = init.checkBlockStatement(env, initctx, vset, exp); + } + CheckContext newctx = new CheckContext(initctx, this); + // remember what was unassigned on entry + Vset vsEntry = vset.copy(); + ConditionVars cvars; + if (cond != null) { + cvars = cond.checkCondition(env, newctx, vset, exp); + cond = convert(env, newctx, Type.tBoolean, cond); + } else { + // a missing test is equivalent to "true" + cvars = new ConditionVars(); + cvars.vsFalse = Vset.DEAD_END; + cvars.vsTrue = vset; + } + vset = body.check(env, newctx, cvars.vsTrue, exp); + vset = vset.join(newctx.vsContinue); + if (inc != null) { + vset = inc.check(env, newctx, vset, exp); + } + // Make sure the back-branch fits the entry of the loop. + // Must include variables declared in the for-init part in the + // set of variables visible upon loop entry that must be checked. + initctx.checkBackBranch(env, this, vsEntry, vset); + // exit by testing false or executing a break; + vset = newctx.vsBreak.join(cvars.vsFalse); + return ctx.removeAdditionalVars(vset); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + if (init != null) { + Statement body[] = {init, this}; + init = null; + return new CompoundStatement(where, body).inline(env, ctx); + } + if (cond != null) { + cond = cond.inlineValue(env, ctx); + } + if (body != null) { + body = body.inline(env, ctx); + } + if (inc != null) { + inc = inc.inline(env, ctx); + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + ForStatement s = (ForStatement)clone(); + if (init != null) { + s.init = init.copyInline(ctx, valNeeded); + } + if (cond != null) { + s.cond = cond.copyInline(ctx); + } + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + if (inc != null) { + s.inc = inc.copyInline(ctx); + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + int cost = 2; + if (init != null) { + cost += init.costInline(thresh, env, ctx); + } + if (cond != null) { + cost += cond.costInline(thresh, env, ctx); + } + if (body != null) { + cost += body.costInline(thresh, env, ctx); + } + if (inc != null) { + cost += inc.costInline(thresh, env, ctx); + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + if (init != null) { + init.code(env, newctx, asm); + } + + Label l1 = new Label(); + Label l2 = new Label(); + + asm.add(where, opc_goto, l2); + + asm.add(l1); + if (body != null) { + body.code(env, newctx, asm); + } + + asm.add(newctx.contLabel); + if (inc != null) { + inc.code(env, newctx, asm); + } + + asm.add(l2); + if (cond != null) { + cond.codeBranch(env, newctx, asm, l1, true); + } else { + asm.add(where, opc_goto, l1); + } + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("for ("); + if (init != null) { + init.print(out, indent); + out.print(" "); + } else { + out.print("; "); + } + if (cond != null) { + cond.print(out); + out.print(" "); + } + out.print("; "); + if (inc != null) { + inc.print(out); + } + out.print(") "); + if (body != null) { + body.print(out, indent); + } else { + out.print(";"); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/GreaterExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/GreaterExpression.java new file mode 100644 index 000000000..e0283302b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/GreaterExpression.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class GreaterExpression extends BinaryCompareExpression { + /** + * constructor + */ + public GreaterExpression(long where, Expression left, Expression right) { + super(GT, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new BooleanExpression(where, a > b); + } + Expression eval(long a, long b) { + return new BooleanExpression(where, a > b); + } + Expression eval(float a, float b) { + return new BooleanExpression(where, a > b); + } + Expression eval(double a, double b) { + return new BooleanExpression(where, a > b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.isConstant() && !right.isConstant()) { + return new LessExpression(where, right, left); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + left.codeValue(env, ctx, asm); + switch (left.type.getTypeCode()) { + case TC_INT: + if (!right.equals(0)) { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_icmpgt : opc_if_icmple, lbl, whenTrue); + return; + } + break; + case TC_LONG: + right.codeValue(env, ctx, asm); + asm.add(where, opc_lcmp); + break; + case TC_FLOAT: + right.codeValue(env, ctx, asm); + asm.add(where, opc_fcmpl); + break; + case TC_DOUBLE: + right.codeValue(env, ctx, asm); + asm.add(where, opc_dcmpl); + break; + default: + throw new CompilerError("Unexpected Type"); + } + asm.add(where, whenTrue ? opc_ifgt : opc_ifle, lbl, whenTrue); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/GreaterOrEqualExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/GreaterOrEqualExpression.java new file mode 100644 index 000000000..0f6a88393 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/GreaterOrEqualExpression.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class GreaterOrEqualExpression extends BinaryCompareExpression { + /** + * constructor + */ + public GreaterOrEqualExpression(long where, Expression left, Expression right) { + super(GE, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new BooleanExpression(where, a >= b); + } + Expression eval(long a, long b) { + return new BooleanExpression(where, a >= b); + } + Expression eval(float a, float b) { + return new BooleanExpression(where, a >= b); + } + Expression eval(double a, double b) { + return new BooleanExpression(where, a >= b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.isConstant() && !right.isConstant()) { + return new LessOrEqualExpression(where, right, left); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + left.codeValue(env, ctx, asm); + switch (left.type.getTypeCode()) { + case TC_INT: + if (!right.equals(0)) { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_icmpge : opc_if_icmplt, lbl, whenTrue); + return; + } + break; + case TC_LONG: + right.codeValue(env, ctx, asm); + asm.add(where, opc_lcmp); + break; + case TC_FLOAT: + right.codeValue(env, ctx, asm); + asm.add(where, opc_fcmpl); + break; + case TC_DOUBLE: + right.codeValue(env, ctx, asm); + asm.add(where, opc_dcmpl); + break; + default: + throw new CompilerError("Unexpected Type"); + } + asm.add(where, whenTrue ? opc_ifge : opc_iflt, lbl, whenTrue); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/IdentifierExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IdentifierExpression.java new file mode 100644 index 000000000..64e57619f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IdentifierExpression.java @@ -0,0 +1,462 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.LocalVariable; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class IdentifierExpression extends Expression { + Identifier id; + MemberDefinition field; + Expression implementation; + + /** + * Constructor + */ + public IdentifierExpression(long where, Identifier id) { + super(IDENT, where, Type.tError); + this.id = id; + } + public IdentifierExpression(IdentifierToken id) { + this(id.getWhere(), id.getName()); + } + public IdentifierExpression(long where, MemberDefinition field) { + super(IDENT, where, field.getType()); + this.id = field.getName(); + this.field = field; + } + + public Expression getImplementation() { + if (implementation != null) + return implementation; + return this; + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(Identifier id) { + return this.id.equals(id); + } + + + /** + * Assign a value to this identifier. [It must already be "bound"] + */ + private Vset assign(Environment env, Context ctx, Vset vset) { + if (field.isLocal()) { + LocalMember local = (LocalMember)field; + if (local.scopeNumber < ctx.frameNumber) { + env.error(where, "assign.to.uplevel", id); + } + if (local.isFinal()) { + // allow definite single assignment of blank finals + if (!local.isBlankFinal()) { + env.error(where, "assign.to.final", id); + } else if (!vset.testVarUnassigned(local.number)) { + env.error(where, "assign.to.blank.final", id); + } + } + vset.addVar(local.number); + local.writecount++; + } else if (field.isFinal()) { + vset = FieldExpression.checkFinalAssign(env, ctx, vset, + where, field); + } + return vset; + } + + /** + * Get the value of this identifier. [ It must already be "bound"] + */ + private Vset get(Environment env, Context ctx, Vset vset) { + if (field.isLocal()) { + LocalMember local = (LocalMember)field; + if (local.scopeNumber < ctx.frameNumber && !local.isFinal()) { + env.error(where, "invalid.uplevel", id); + } + if (!vset.testVar(local.number)) { + env.error(where, "var.not.initialized", id); + vset.addVar(local.number); + } + local.readcount++; + } else { + if (!field.isStatic()) { + if (!vset.testVar(ctx.getThisNumber())) { + env.error(where, "access.inst.before.super", id); + implementation = null; + } + } + if (field.isBlankFinal()) { + int number = ctx.getFieldNumber(field); + if (number >= 0 && !vset.testVar(number)) { + env.error(where, "var.not.initialized", id); + } + } + } + return vset; + } + + /** + * Bind to a field + */ + boolean bind(Environment env, Context ctx) { + try { + field = ctx.getField(env, id); + if (field == null) { + for (ClassDefinition cdef = ctx.field.getClassDefinition(); + cdef != null; cdef = cdef.getOuterClass()) { + if (cdef.findAnyMethod(env, id) != null) { + env.error(where, "invalid.var", id, + ctx.field.getClassDeclaration()); + return false; + } + } + env.error(where, "undef.var", id); + return false; + } + + type = field.getType(); + + // Check access permission + if (!ctx.field.getClassDefinition().canAccess(env, field)) { + env.error(where, "no.field.access", + id, field.getClassDeclaration(), + ctx.field.getClassDeclaration()); + return false; + } + + // Find out how to access this variable. + if (field.isLocal()) { + LocalMember local = (LocalMember)field; + if (local.scopeNumber < ctx.frameNumber) { + // get a "val$x" copy via the current object + implementation = ctx.makeReference(env, local); + } + } else { + MemberDefinition f = field; + + if (f.reportDeprecated(env)) { + env.error(where, "warn.field.is.deprecated", + id, f.getClassDefinition()); + } + + ClassDefinition fclass = f.getClassDefinition(); + if (fclass != ctx.field.getClassDefinition()) { + // Maybe an inherited field hides an apparent variable. + MemberDefinition f2 = ctx.getApparentField(env, id); + if (f2 != null && f2 != f) { + ClassDefinition c = ctx.findScope(env, fclass); + if (c == null) c = f.getClassDefinition(); + if (f2.isLocal()) { + env.error(where, "inherited.hides.local", + id, c.getClassDeclaration()); + } else { + env.error(where, "inherited.hides.field", + id, c.getClassDeclaration(), + f2.getClassDeclaration()); + } + } + } + + // Rewrite as a FieldExpression. + // Access methods for private fields, if needed, will be added + // during subsequent processing of the FieldExpression. See + // method 'FieldExpression.checkCommon'. This division of labor + // is somewhat awkward, as most further processing of a + // FieldExpression during the checking phase is suppressed when + // the referenced field is pre-set as it is here. + + if (f.isStatic()) { + Expression base = new TypeExpression(where, + f.getClassDeclaration().getType()); + implementation = new FieldExpression(where, null, f); + } else { + Expression base = ctx.findOuterLink(env, where, f); + if (base != null) { + implementation = new FieldExpression(where, base, f); + } + } + } + + // Check forward reference + if (!ctx.canReach(env, field)) { + env.error(where, "forward.ref", + id, field.getClassDeclaration()); + return false; + } + return true; + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, ctx.field); + } catch (AmbiguousMember e) { + env.error(where, "ambig.field", id, + e.field1.getClassDeclaration(), + e.field2.getClassDeclaration()); + } + return false; + } + + /** + * Check expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + if (field != null) { + // An internally pre-set field, such as an argument copying + // an uplevel value. Do not re-check it. + return vset; + } + if (bind(env, ctx)) { + vset = get(env, ctx, vset); + ctx.field.getClassDefinition().addDependency(field.getClassDeclaration()); + if (implementation != null) + vset = implementation.checkValue(env, ctx, vset, exp); + } + return vset; + } + + /** + * Check the expression if it appears on the LHS of an assignment + */ + public Vset checkLHS(Environment env, Context ctx, + Vset vset, Hashtable exp) { + if (!bind(env, ctx)) + return vset; + vset = assign(env, ctx, vset); + if (implementation != null) + vset = implementation.checkValue(env, ctx, vset, exp); + return vset; + } + + /** + * Check the expression if it appears on the LHS of an op= expression + */ + public Vset checkAssignOp(Environment env, Context ctx, + Vset vset, Hashtable exp, Expression outside) { + if (!bind(env, ctx)) + return vset; + vset = assign(env, ctx, get(env, ctx, vset)); + if (implementation != null) + vset = implementation.checkValue(env, ctx, vset, exp); + return vset; + } + + /** + * Return an accessor if one is needed for assignments to this expression. + */ + public FieldUpdater getAssigner(Environment env, Context ctx) { + if (implementation != null) + return implementation.getAssigner(env, ctx); + return null; + } + + /** + * Return an updater if one is needed for assignments to this expression. + */ + public FieldUpdater getUpdater(Environment env, Context ctx) { + if (implementation != null) + return implementation.getUpdater(env, ctx); + return null; + } + + /** + * Check if the present name is part of a scoping prefix. + */ + public Vset checkAmbigName(Environment env, Context ctx, Vset vset, Hashtable exp, + UnaryExpression loc) { + try { + if (ctx.getField(env, id) != null) { + // if this is a local field, there's nothing more to do. + return checkValue(env, ctx, vset, exp); + } + } catch (ClassNotFound ee) { + } catch (AmbiguousMember ee) { + } + // Can this be interpreted as a type? + ClassDefinition c = toResolvedType(env, ctx, true); + // Is it a real type?? + if (c != null) { + loc.right = new TypeExpression(where, c.getType()); + return vset; + } + // We hope it is a package prefix. Let the caller decide. + type = Type.tPackage; + return vset; + } + + /** + * Convert an identifier to a known type, or null. + */ + private ClassDefinition toResolvedType(Environment env, Context ctx, + boolean pkgOK) { + Identifier rid = ctx.resolveName(env, id); + Type t = Type.tClass(rid); + if (pkgOK && !env.classExists(t)) { + return null; + } + if (env.resolve(where, ctx.field.getClassDefinition(), t)) { + try { + ClassDefinition c = env.getClassDefinition(t); + + // Maybe an inherited class hides an apparent class. + if (c.isMember()) { + ClassDefinition sc = ctx.findScope(env, c.getOuterClass()); + if (sc != c.getOuterClass()) { + Identifier rid2 = ctx.getApparentClassName(env, id); + if (!rid2.equals(idNull) && !rid2.equals(rid)) { + env.error(where, "inherited.hides.type", + id, sc.getClassDeclaration()); + } + } + } + + if (!c.getLocalName().equals(id.getFlatName().getName())) { + env.error(where, "illegal.mangled.name", id, c); + } + + return c; + } catch (ClassNotFound ee) { + } + } + return null; + } + + /** + * Convert an identifier to a type. + * If one is not known, use the current package as a qualifier. + */ + Type toType(Environment env, Context ctx) { + ClassDefinition c = toResolvedType(env, ctx, false); + if (c != null) { + return c.getType(); + } + return Type.tError; + } + + /** + * Convert an expresion to a type in a context where a qualified + * type name is expected, e.g., in the prefix of a qualified type + * name. We do not necessarily know where the package prefix ends, + * so we operate similarly to 'checkAmbiguousName'. This is the + * base case -- the first component of the qualified name. + */ + /*-------------------------------------------------------* + Type toQualifiedType(Environment env, Context ctx) { + // We do not look for non-type fields. Is this correct? + ClassDefinition c = toResolvedType(env, ctx, true); + // Is it a real type? + if (c != null) { + return c.getType(); + } + // We hope it is a package prefix. Let the caller decide. + return Type.tPackage; + } + *-------------------------------------------------------*/ + + /** + * Check if constant: Will it inline away? + */ + public boolean isConstant() { + if (implementation != null) + return implementation.isConstant(); + if (field != null) { + return field.isConstant(); + } + return false; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + return null; + } + public Expression inlineValue(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineValue(env, ctx); + if (field == null) { + return this; + } + try { + if (field.isLocal()) { + if (field.isInlineable(env, false)) { + Expression e = (Expression)field.getValue(env); + return (e == null) ? this : e.inlineValue(env, ctx); + } + return this; + } + return this; + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + } + public Expression inlineLHS(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineLHS(env, ctx); + return this; + } + + public Expression copyInline(Context ctx) { + if (implementation != null) + return implementation.copyInline(ctx); + IdentifierExpression e = + (IdentifierExpression)super.copyInline(ctx); + if (field != null && field.isLocal()) { + e.field = ((LocalMember)field).getCurrentInlineCopy(ctx); + } + return e; + } + + public int costInline(int thresh, Environment env, Context ctx) { + if (implementation != null) + return implementation.costInline(thresh, env, ctx); + return super.costInline(thresh, env, ctx); + } + + /** + * Code local vars (object fields have been inlined away) + */ + int codeLValue(Environment env, Context ctx, Assembler asm) { + return 0; + } + void codeLoad(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iload + type.getTypeCodeOffset(), + ((LocalMember)field).number); + } + void codeStore(Environment env, Context ctx, Assembler asm) { + LocalMember local = (LocalMember)field; + asm.add(where, opc_istore + type.getTypeCodeOffset(), + new LocalVariable(local, local.number)); + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeLValue(env, ctx, asm); + codeLoad(env, ctx, asm); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(id + "#" + ((field != null) ? field.hashCode() : 0)); + if (implementation != null) { + out.print("/IMPL="); + implementation.print(out); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/IfStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IfStatement.java new file mode 100644 index 000000000..b1cd99dba --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IfStatement.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class IfStatement extends Statement { + Expression cond; + Statement ifTrue; + Statement ifFalse; + + /** + * Constructor + */ + public IfStatement(long where, Expression cond, Statement ifTrue, Statement ifFalse) { + super(IF, where); + this.cond = cond; + this.ifTrue = ifTrue; + this.ifFalse = ifFalse; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + CheckContext newctx = new CheckContext(ctx, this); + // Vset vsExtra = vset.copy(); // See comment below. + ConditionVars cvars = + cond.checkCondition(env, newctx, reach(env, vset), exp); + cond = convert(env, newctx, Type.tBoolean, cond); + // The following code, now deleted, was apparently an erroneous attempt + // at providing better error diagnostics. The comment read: 'If either + // the true clause or the false clause is unreachable, do a reasonable + // check on the child anyway.' + // Vset vsTrue = cvars.vsTrue.isDeadEnd() ? vsExtra : cvars.vsTrue; + // Vset vsFalse = cvars.vsFalse.isDeadEnd() ? vsExtra : cvars.vsFalse; + // Unfortunately, this violates the rules laid out in the JLS, and leads to + // blatantly incorrect results. For example, 'i' will not be recognized + // as definitely assigned following the statement 'if (true) i = 1;'. + // It is best to slavishly follow the JLS here. A cleverer approach could + // only correctly issue warnings, as JLS 16.2.6 is quite explicit, and it + // is OK for a dead branch of an if-statement to omit an assignment that + // would be required in the other branch. A complication: This code also + // had the effect of implementing the special-case rules for 'if-then' and + // 'if-then-else' in JLS 14.19, "Unreachable Statements". We now use + // 'Vset.clearDeadEnd' to remove the dead-end status of unreachable branches + // without affecting the definite-assignment status of the variables, thus + // maintaining a correct implementation of JLS 16.2.6. Fixes 4094353. + // Note that the code below will not consider the branches unreachable if + // the entire statement is unreachable. This is consistent with the error + // recovery policy that reports the only the first unreachable statement + // along an acyclic execution path. + Vset vsTrue = cvars.vsTrue.clearDeadEnd(); + Vset vsFalse = cvars.vsFalse.clearDeadEnd(); + vsTrue = ifTrue.check(env, newctx, vsTrue, exp); + if (ifFalse != null) + vsFalse = ifFalse.check(env, newctx, vsFalse, exp); + vset = vsTrue.join(vsFalse.join(newctx.vsBreak)); + return ctx.removeAdditionalVars(vset); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + cond = cond.inlineValue(env, ctx); + + // The compiler currently needs to perform inlining on both + // branches of the if statement -- even if `cond' is a constant + // true or false. Why? The compiler will later try to compile + // all classes that it has seen; this includes classes that + // appear in dead code. If we don't inline the dead branch here + // then the compiler will never perform inlining on any local + // classes appearing on the dead code. When the compiler tries + // to compile an un-inlined local class with uplevel references, + // it dies. (bug 4059492) + // + // A better solution to this would be to walk the dead branch and + // mark any local classes appearing therein as unneeded. Then the + // compilation phase could skip these classes. + if (ifTrue != null) { + ifTrue = ifTrue.inline(env, ctx); + } + if (ifFalse != null) { + ifFalse = ifFalse.inline(env, ctx); + } + if (cond.equals(true)) { + return eliminate(env, ifTrue); + } + if (cond.equals(false)) { + return eliminate(env, ifFalse); + } + if ((ifTrue == null) && (ifFalse == null)) { + return eliminate(env, new ExpressionStatement(where, cond).inline(env, ctx)); + } + if (ifTrue == null) { + cond = new NotExpression(cond.where, cond).inlineValue(env, ctx); + return eliminate(env, new IfStatement(where, cond, ifFalse, null)); + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + IfStatement s = (IfStatement)clone(); + s.cond = cond.copyInline(ctx); + if (ifTrue != null) { + s.ifTrue = ifTrue.copyInline(ctx, valNeeded); + } + if (ifFalse != null) { + s.ifFalse = ifFalse.copyInline(ctx, valNeeded); + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + int cost = 1 + cond.costInline(thresh, env, ctx); + if (ifTrue != null) { + cost += ifTrue.costInline(thresh, env, ctx); + } + if (ifFalse != null) { + cost += ifFalse.costInline(thresh, env, ctx); + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + + Label l1 = new Label(); + cond.codeBranch(env, newctx, asm, l1, false); + ifTrue.code(env, newctx, asm); + if (ifFalse != null) { + Label l2 = new Label(); + asm.add(true, where, opc_goto, l2); + asm.add(l1); + ifFalse.code(env, newctx, asm); + asm.add(l2); + } else { + asm.add(l1); + } + + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("if "); + cond.print(out); + out.print(" "); + ifTrue.print(out, indent); + if (ifFalse != null) { + out.print(" else "); + ifFalse.print(out, indent); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/IncDecExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IncDecExpression.java new file mode 100644 index 000000000..0614516bf --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IncDecExpression.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class IncDecExpression extends UnaryExpression { + + private FieldUpdater updater = null; + + /** + * Constructor + */ + public IncDecExpression(int op, long where, Expression right) { + super(op, where, right.type, right); + } + + /** + * Check an increment or decrement expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = right.checkAssignOp(env, ctx, vset, exp, this); + if (right.type.inMask(TM_NUMBER)) { + type = right.type; + } else { + if (!right.type.isType(TC_ERROR)) { + env.error(where, "invalid.arg.type", right.type, opNames[op]); + } + type = Type.tError; + } + updater = right.getUpdater(env, ctx); // Must be called after 'checkAssignOp'. + return vset; + } + + /** + * Check void expression + */ + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + return checkValue(env, ctx, vset, exp); + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + return inlineValue(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + // Why not inlineLHS? But that does not work. + right = right.inlineValue(env, ctx); + if (updater != null) { + updater = updater.inline(env, ctx); + } + return this; + } + + public int costInline(int thresh, Environment env, Context ctx) { + if (updater == null) { + if ((right.op == IDENT) && type.isType(TC_INT) && + (((IdentifierExpression)right).field.isLocal())) { + // Increment variable in place. Count 3 bytes for 'iinc'. + return 3; + } + // Cost to load lhs reference, fetch local, increment, and store. + // Load/store cost will be higher if variable is a field. Note that + // costs are highly approximate. See 'AssignOpExpression.costInline' + // Does not account for cost of conversions,or duplications in + // value-needed context.. + return right.costInline(thresh, env, ctx) + 4; + } else { + // Cost of two access method calls (get/set) + cost of increment. + return updater.costInline(thresh, env, ctx, true) + 1; + } + } + + + /** + * Code + */ + + private void codeIncDecOp(Assembler asm, boolean inc) { + switch (type.getTypeCode()) { + case TC_BYTE: + asm.add(where, opc_ldc, 1); + asm.add(where, inc ? opc_iadd : opc_isub); + asm.add(where, opc_i2b); + break; + case TC_SHORT: + asm.add(where, opc_ldc, 1); + asm.add(where, inc ? opc_iadd : opc_isub); + asm.add(where, opc_i2s); + break; + case TC_CHAR: + asm.add(where, opc_ldc, 1); + asm.add(where, inc ? opc_iadd : opc_isub); + asm.add(where, opc_i2c); + break; + case TC_INT: + asm.add(where, opc_ldc, 1); + asm.add(where, inc ? opc_iadd : opc_isub); + break; + case TC_LONG: + asm.add(where, opc_ldc2_w, 1L); + asm.add(where, inc ? opc_ladd : opc_lsub); + break; + case TC_FLOAT: + asm.add(where, opc_ldc, new Float(1)); + asm.add(where, inc ? opc_fadd : opc_fsub); + break; + case TC_DOUBLE: + asm.add(where, opc_ldc2_w, new Double(1)); + asm.add(where, inc ? opc_dadd : opc_dsub); + break; + default: + throw new CompilerError("invalid type"); + } + } + + void codeIncDec(Environment env, Context ctx, Assembler asm, boolean inc, boolean prefix, boolean valNeeded) { + + // The 'iinc' instruction cannot be used if an access method call is required. + if ((right.op == IDENT) && type.isType(TC_INT) && + (((IdentifierExpression)right).field.isLocal()) && updater == null) { + if (valNeeded && !prefix) { + right.codeLoad(env, ctx, asm); + } + int v = ((LocalMember)((IdentifierExpression)right).field).number; + int[] operands = { v, inc ? 1 : -1 }; + asm.add(where, opc_iinc, operands); + if (valNeeded && prefix) { + right.codeLoad(env, ctx, asm); + } + return; + + } + + if (updater == null) { + // Field is directly accessible. + int depth = right.codeLValue(env, ctx, asm); + codeDup(env, ctx, asm, depth, 0); + right.codeLoad(env, ctx, asm); + if (valNeeded && !prefix) { + codeDup(env, ctx, asm, type.stackSize(), depth); + } + codeIncDecOp(asm, inc); + if (valNeeded && prefix) { + codeDup(env, ctx, asm, type.stackSize(), depth); + } + right.codeStore(env, ctx, asm); + } else { + // Must use access methods. + updater.startUpdate(env, ctx, asm, (valNeeded && !prefix)); + codeIncDecOp(asm, inc); + updater.finishUpdate(env, ctx, asm, (valNeeded && prefix)); + } + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineMethodExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineMethodExpression.java new file mode 100644 index 000000000..790a93d18 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineMethodExpression.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class InlineMethodExpression extends Expression { + MemberDefinition field; + Statement body; + + /** + * Constructor + */ + InlineMethodExpression(long where, Type type, MemberDefinition field, Statement body) { + super(INLINEMETHOD, where, type); + this.field = field; + this.body = body; + } + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + body = body.inline(env, new Context(ctx, this)); + if (body == null) { + return null; + } else if (body.op == INLINERETURN) { + Expression expr = ((InlineReturnStatement)body).expr; + if (expr != null && type.isType(TC_VOID)) { + throw new CompilerError("value on inline-void return"); + } + return expr; + } else { + return this; + } + } + public Expression inlineValue(Environment env, Context ctx) { + // When this node was constructed, "copyInline" walked the body + // with a "valNeeded" flag which made all returns either void + // or value-bearing. The type of this node reflects that + // earlier choice. The present inline/inlineValue distinction + // is ignored. + return inline(env, ctx); + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + InlineMethodExpression e = (InlineMethodExpression)clone(); + if (body != null) { + e.body = body.copyInline(ctx, true); + } + return e; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + // pop the result if there is any (usually, type is already void) + super.code(env, ctx, asm); + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + body.code(env, newctx, asm); + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + "\n"); + body.print(out, 1); + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineNewInstanceExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineNewInstanceExpression.java new file mode 100644 index 000000000..8c52bded3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineNewInstanceExpression.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Vector; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class InlineNewInstanceExpression extends Expression { + MemberDefinition field; + Statement body; + + /** + * Constructor + */ + InlineNewInstanceExpression(long where, Type type, MemberDefinition field, Statement body) { + super(INLINENEWINSTANCE, where, type); + this.field = field; + this.body = body; + } + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + return inlineValue(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + if (body != null) { + LocalMember v = (LocalMember)field.getArguments().elementAt(0); + Context newctx = new Context(ctx, this); + newctx.declare(env, v); + body = body.inline(env, newctx); + } + if ((body != null) && (body.op == INLINERETURN)) { + body = null; + } + return this; + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + InlineNewInstanceExpression e = (InlineNewInstanceExpression)clone(); + e.body = body.copyInline(ctx, true); + return e; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + codeCommon(env, ctx, asm, false); + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeCommon(env, ctx, asm, true); + } + private void codeCommon(Environment env, Context ctx, Assembler asm, + boolean forValue) { + asm.add(where, opc_new, field.getClassDeclaration()); + if (body != null) { + LocalMember v = (LocalMember)field.getArguments().elementAt(0); + CodeContext newctx = new CodeContext(ctx, this); + newctx.declare(env, v); + asm.add(where, opc_astore, v.number); + body.code(env, newctx, asm); + asm.add(newctx.breakLabel); + if (forValue) { + asm.add(where, opc_aload, v.number); + } + } + } + + /** + * Print + */ + public void print(PrintStream out) { + LocalMember v = (LocalMember)field.getArguments().elementAt(0); + out.println("(" + opNames[op] + "#" + v.hashCode() + "=" + field.hashCode()); + if (body != null) { + body.print(out, 1); + } else { + out.print(""); + } + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineReturnStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineReturnStatement.java new file mode 100644 index 000000000..88b9846dc --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InlineReturnStatement.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class InlineReturnStatement extends Statement { + Expression expr; + + /** + * Constructor + */ + public InlineReturnStatement(long where, Expression expr) { + super(INLINERETURN, where); + this.expr = expr; + } + + /** + * Get the destination context of a break + */ + Context getDestination(Context ctx) { + for (; ctx != null ; ctx = ctx.prev) { + if ((ctx.node != null) && ((ctx.node.op == INLINEMETHOD) || (ctx.node.op == INLINENEWINSTANCE))) { + return ctx; + } + } + return null; + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (expr != null) { + expr = expr.inlineValue(env, ctx); + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + InlineReturnStatement s = (InlineReturnStatement)clone(); + if (expr != null) { + s.expr = expr.copyInline(ctx); + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + ((expr != null) ? expr.costInline(thresh, env, ctx) : 0); + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + if (expr != null) { + expr.codeValue(env, ctx, asm); + } + CodeContext destctx = (CodeContext)getDestination(ctx); + asm.add(where, opc_goto, destctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("inline-return"); + if (expr != null) { + out.print(" "); + expr.print(out); + } + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/InstanceOfExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InstanceOfExpression.java new file mode 100644 index 000000000..3c2001890 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/InstanceOfExpression.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class InstanceOfExpression extends BinaryExpression { + /** + * constructor + */ + public InstanceOfExpression(long where, Expression left, Expression right) { + super(INSTANCEOF, where, Type.tBoolean, left, right); + } + + /** + * Check the expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = left.checkValue(env, ctx, vset, exp); + right = new TypeExpression(right.where, right.toType(env, ctx)); + + if (right.type.isType(TC_ERROR) || left.type.isType(TC_ERROR)) { + // An error was already reported + return vset; + } + + if (!right.type.inMask(TM_CLASS|TM_ARRAY)) { + env.error(right.where, "invalid.arg.type", right.type, opNames[op]); + return vset; + } + try { + if (!env.explicitCast(left.type, right.type)) { + env.error(where, "invalid.instanceof", left.type, right.type); + } + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, opNames[op]); + } + return vset; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + return left.inline(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + left = left.inlineValue(env, ctx); + return this; + } + + public int costInline(int thresh, Environment env, Context ctx) { + if (ctx == null) { + return 1 + left.costInline(thresh, env, ctx); + } + // sourceClass is the current class trying to inline this method + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + try { + // We only allow the inlining if the current class can access + // the "instance of" class + if (right.type.isType(TC_ARRAY) || + sourceClass.permitInlinedAccess(env, env.getClassDeclaration(right.type))) + return 1 + left.costInline(thresh, env, ctx); + } catch (ClassNotFound e) { + } + return thresh; + } + + + + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + left.codeValue(env, ctx, asm); + if (right.type.isType(TC_CLASS)) { + asm.add(where, opc_instanceof, env.getClassDeclaration(right.type)); + } else { + asm.add(where, opc_instanceof, right.type); + } + } + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_ifne : opc_ifeq, lbl, whenTrue); + } + public void code(Environment env, Context ctx, Assembler asm) { + left.code(env, ctx, asm); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + left.print(out); + out.print(" "); + if (right.op == TYPE) { + out.print(right.type.toString()); + } else { + right.print(out); + } + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/IntExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IntExpression.java new file mode 100644 index 000000000..3ca631db5 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IntExpression.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class IntExpression extends IntegerExpression { + /** + * Constructor + */ + public IntExpression(long where, int value) { + super(INTVAL, where, Type.tInt, value); + } + + /** + * Equality, this is needed so that switch statements + * can put IntExpressions in a hashtable + */ + public boolean equals(Object obj) { + if ((obj != null) && (obj instanceof IntExpression)) { + return value == ((IntExpression)obj).value; + } + return false; + } + + /** + * Hashcode, this is needed so that switch statements + * can put IntExpressions in a hashtable + */ + public int hashCode() { + return value; + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/IntegerExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IntegerExpression.java new file mode 100644 index 000000000..c858f62a3 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/IntegerExpression.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class IntegerExpression extends ConstantExpression { + int value; + + /** + * Constructor + */ + IntegerExpression(int op, long where, Type type, int value) { + super(op, where, type); + this.value = value; + } + + /** + * See if this number fits in the given type. + */ + public boolean fitsType(Environment env, Context ctx, Type t) { + if (this.type.isType(TC_CHAR)) { + // A char constant is not really an int constant, + // so do not report that 'a' fits in a byte or short, + // even if its value is in fact 7-bit ascii. See JLS 5.2. + return super.fitsType(env, ctx, t); + } + switch (t.getTypeCode()) { + case TC_BYTE: + return value == (byte)value; + case TC_SHORT: + return value == (short)value; + case TC_CHAR: + return value == (char)value; + } + return super.fitsType(env, ctx, t); + } + + /** + * Get the value + */ + public Object getValue() { + return value; + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(int i) { + return value == i; + } + + /** + * Check if the expression is equal to its default static value + */ + public boolean equalsDefault() { + return value == 0; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ldc, value); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/LengthExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LengthExpression.java new file mode 100644 index 000000000..5c000806b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LengthExpression.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class LengthExpression extends UnaryExpression { + /** + * Constructor + */ + public LengthExpression(long where, Expression right) { + super(LENGTH, where, Type.tInt, right); + } + + /** + * Select the type of the expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = right.checkValue(env, ctx, vset, exp); + if (!right.type.isType(TC_ARRAY)) { + env.error(where, "invalid.length", right.type); + } + return vset; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + right.codeValue(env, ctx, asm); + asm.add(where, opc_arraylength); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/LessExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LessExpression.java new file mode 100644 index 000000000..7cb3eafc5 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LessExpression.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class LessExpression extends BinaryCompareExpression { + /** + * constructor + */ + public LessExpression(long where, Expression left, Expression right) { + super(LT, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new BooleanExpression(where, a < b); + } + Expression eval(long a, long b) { + return new BooleanExpression(where, a < b); + } + Expression eval(float a, float b) { + return new BooleanExpression(where, a < b); + } + Expression eval(double a, double b) { + return new BooleanExpression(where, a < b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.isConstant() && !right.isConstant()) { + return new GreaterExpression(where, right, left); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + left.codeValue(env, ctx, asm); + switch (left.type.getTypeCode()) { + case TC_INT: + if (!right.equals(0)) { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_icmplt : opc_if_icmpge, lbl, whenTrue); + return; + } + break; + case TC_LONG: + right.codeValue(env, ctx, asm); + asm.add(where, opc_lcmp); + break; + case TC_FLOAT: + right.codeValue(env, ctx, asm); + asm.add(where, opc_fcmpg); + break; + case TC_DOUBLE: + right.codeValue(env, ctx, asm); + asm.add(where, opc_dcmpg); + break; + default: + throw new CompilerError("Unexpected Type"); + } + asm.add(where, whenTrue ? opc_iflt : opc_ifge, lbl, whenTrue); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/LessOrEqualExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LessOrEqualExpression.java new file mode 100644 index 000000000..cc00ad48b --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LessOrEqualExpression.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class LessOrEqualExpression extends BinaryCompareExpression { + /** + * constructor + */ + public LessOrEqualExpression(long where, Expression left, Expression right) { + super(LE, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new BooleanExpression(where, a <= b); + } + Expression eval(long a, long b) { + return new BooleanExpression(where, a <= b); + } + Expression eval(float a, float b) { + return new BooleanExpression(where, a <= b); + } + Expression eval(double a, double b) { + return new BooleanExpression(where, a <= b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.isConstant() && !right.isConstant()) { + return new GreaterOrEqualExpression(where, right, left); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + left.codeValue(env, ctx, asm); + switch (left.type.getTypeCode()) { + case TC_INT: + if (!right.equals(0)) { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_icmple : opc_if_icmpgt, lbl, whenTrue); + return; + } + break; + case TC_LONG: + right.codeValue(env, ctx, asm); + asm.add(where, opc_lcmp); + break; + case TC_FLOAT: + right.codeValue(env, ctx, asm); + asm.add(where, opc_fcmpg); + break; + case TC_DOUBLE: + right.codeValue(env, ctx, asm); + asm.add(where, opc_dcmpg); + break; + default: + throw new CompilerError("Unexpected Type"); + } + asm.add(where, whenTrue ? opc_ifle : opc_ifgt, lbl, whenTrue); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/LocalMember.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LocalMember.java new file mode 100644 index 000000000..6f2be9597 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LocalMember.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.tree.*; +import java.util.Vector; + +/** + * A local Field + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ + +public +class LocalMember extends MemberDefinition { + /** + * The number of the variable + */ + int number = -1; + + /** + * Some statistics + */ + int readcount; + int writecount; + + /** + * An indication of which block the variable comes from. + * Helps identify uplevel references. + */ + int scopeNumber; + + /** + * Return current nesting level, i.e., the value of 'scopeNumber'. + * Made public for the benefit of 'ClassDefinition.resolveName'. + */ + public int getScopeNumber() { + return scopeNumber; + } + + /** + * Used by copyInline to record the original of this copy. + */ + LocalMember originalOfCopy; + + /** + * The previous local variable, this list is used to build a nested + * context of local variables. + */ + LocalMember prev; + + /** + * Constructor + */ + public LocalMember(long where, ClassDefinition clazz, int modifiers, Type type, + Identifier name) { + super(where, clazz, modifiers, type, name, null, null); + } + + /** + * Constructor for a block-inner class. + */ + public LocalMember(ClassDefinition innerClass) { + super(innerClass); + + // The class's "real" name is something like "foo$1$bar", but locally: + name = innerClass.getLocalName(); + } + + /** + * Constructor for a proxy to an instance or class variable. + */ + LocalMember(MemberDefinition field) { + this(0, null, 0, field.getType(), idClass); + // use this random slot to store the info: + accessPeer = field; + } + + /** + * Is this a proxy for the given field? + */ + final MemberDefinition getMember() { + return (name == idClass) ? accessPeer : null; + } + + /** + * Special checks + */ + public boolean isLocal() { + return true; + } + + /** + * Make a copy of this field, which is an argument to a method + * or constructor. Arrange so that when occurrences of the field + * are encountered in an immediately following copyInline() operation, + * the expression nodes will replace the original argument by the + * fresh copy. + */ + public LocalMember copyInline(Context ctx) { + LocalMember copy = new LocalMember(where, clazz, modifiers, type, name); + copy.readcount = this.readcount; + copy.writecount = this.writecount; + + copy.originalOfCopy = this; + + // Make a temporary link from the original. + // It only stays valid through the next call to copyInline(). + // (This means that recursive inlining won't work.) + // To stay honest, we mark these inline copies: + copy.addModifiers(M_LOCAL); + if (this.accessPeer != null + && (this.accessPeer.getModifiers() & M_LOCAL) == 0) { + throw new CompilerError("local copyInline"); + } + this.accessPeer = copy; + + return copy; + } + + /** + * Returns the previous result of copyInline(ctx). + * Must be called in the course of an Expression.copyInline() + * operation that immediately follows the LocalMember.copyInline(). + * Return "this" if there is no such copy. + */ + public LocalMember getCurrentInlineCopy(Context ctx) { + MemberDefinition accessPeer = this.accessPeer; + if (accessPeer != null && (accessPeer.getModifiers() & M_LOCAL) != 0) { + LocalMember copy = (LocalMember)accessPeer; + return copy; + } + return this; + } + + /** + * May inline copies of all the arguments of the given method. + */ + static public LocalMember[] copyArguments(Context ctx, MemberDefinition field) { + Vector v = field.getArguments(); + LocalMember res[] = new LocalMember[v.size()]; + v.copyInto(res); + for (int i = 0; i < res.length; i++) { + res[i] = res[i].copyInline(ctx); + } + return res; + } + + /** + * Call this when finished with the result of a copyArguments() call. + */ + static public void doneWithArguments(Context ctx, LocalMember res[]) { + for (int i = 0; i < res.length; i++) { + if (res[i].originalOfCopy.accessPeer == res[i]) { + res[i].originalOfCopy.accessPeer = null; + } + } + } + + /** + * Is this local variable's value stable and simple enough to be directly + * substituted for occurrences of the variable itself? + * (This decision is made by VarDeclarationStatement.inline().) + */ + public boolean isInlineable(Environment env, boolean fromFinal) { + return (getModifiers() & M_INLINEABLE) != 0; + } + + /** + * Check if used + */ + public boolean isUsed() { + return (readcount != 0) || (writecount != 0); + } + + // Used by class Context, only on members of MemberDefinition.available: + LocalMember getAccessVar() { + return (LocalMember)accessPeer; + } + void setAccessVar(LocalMember f) { + accessPeer = f; + } + // Used by class Context, only on "AccessVar" constructor args + MemberDefinition getAccessVarMember() { + return accessPeer; + } + void setAccessVarMember(MemberDefinition f) { + accessPeer = f; + } + + + /** + * Return value + */ + public Node getValue(Environment env) { + return (Expression)getValue(); + } + + /** + * Value number for vsets, or -1 if none. + */ + public int getNumber(Context ctx) { + return number; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/LongExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LongExpression.java new file mode 100644 index 000000000..3fce3d940 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/LongExpression.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class LongExpression extends ConstantExpression { + long value; + + /** + * Constructor + */ + public LongExpression(long where, long value) { + super(LONGVAL, where, Type.tLong); + this.value = value; + } + + /** + * Get the value + */ + public Object getValue() { + return value; + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(int i) { + return value == i; + } + + /** + * Check if the expression is equal to its default static value + */ + public boolean equalsDefault() { + return value == 0; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ldc2_w, value); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value + "L"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/MethodExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/MethodExpression.java new file mode 100644 index 000000000..0c1c4fe0f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/MethodExpression.java @@ -0,0 +1,934 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class MethodExpression extends NaryExpression { + Identifier id; + ClassDefinition clazz; // The class in which the called method is defined + MemberDefinition field; + Expression implementation; + + private boolean isSuper; // Set if qualified by 'super' or '.super'. + + /** + * constructor + */ + public MethodExpression(long where, Expression right, Identifier id, Expression args[]) { + super(METHOD, where, Type.tError, right, args); + this.id = id; + } + public MethodExpression(long where, Expression right, MemberDefinition field, Expression args[]) { + super(METHOD, where, field.getType().getReturnType(), right, args); + this.id = field.getName(); + this.field = field; + this.clazz = field.getClassDefinition(); + } + + // This is a hack used only within certain access methods generated by + // 'SourceClass.getAccessMember'. It allows an 'invokespecial' instruction + // to be forced even though 'super' does not appear within the call. + // Such access methods are needed for access to protected methods when using + // the qualified '.super.(...)' notation. + public MethodExpression(long where, Expression right, + MemberDefinition field, Expression args[], boolean forceSuper) { + this(where, right, field, args); + this.isSuper = forceSuper; + } + + public Expression getImplementation() { + if (implementation != null) + return implementation; + return this; + } + + /** + * Check expression type + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + ClassDeclaration c = null; + boolean isArray = false; + boolean staticRef = false; + + // Access method to use if required. + MemberDefinition implMethod = null; + + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + + // When calling a constructor, we may need to add an + // additional argument to transmit the outer instance link. + Expression args[] = this.args; + if (id.equals(idInit)){ + ClassDefinition conCls = ctxClass; + try { + Expression conOuter = null; + if (right instanceof SuperExpression) { + // outer.super(...) + conCls = conCls.getSuperClass().getClassDefinition(env); + conOuter = ((SuperExpression)right).outerArg; + } else if (right instanceof ThisExpression) { + // outer.this(...) + conOuter = ((ThisExpression)right).outerArg; + } + args = NewInstanceExpression. + insertOuterLink(env, ctx, where, conCls, conOuter, args); + } catch (ClassNotFound ee) { + // the same error is handled elsewhere + } + } + + Type argTypes[] = new Type[args.length]; + + // The effective accessing class, for access checking. + // This is normally the immediately enclosing class. + ClassDefinition sourceClass = ctxClass; + + try { + if (right == null) { + staticRef = ctx.field.isStatic(); + // Find the first outer scope that mentions the method. + ClassDefinition cdef = ctxClass; + MemberDefinition m = null; + for (; cdef != null; cdef = cdef.getOuterClass()) { + m = cdef.findAnyMethod(env, id); + if (m != null) { + break; + } + } + if (m == null) { + // this is the scope for error diagnosis + c = ctx.field.getClassDeclaration(); + } else { + // found the innermost scope in which m occurs + c = cdef.getClassDeclaration(); + + // Maybe an inherited method hides an apparent method. + // Keep looking at enclosing scopes to find out. + if (m.getClassDefinition() != cdef) { + ClassDefinition cdef2 = cdef; + while ((cdef2 = cdef2.getOuterClass()) != null) { + MemberDefinition m2 = cdef2.findAnyMethod(env, id); + if (m2 != null && m2.getClassDefinition() == cdef2) { + env.error(where, "inherited.hides.method", + id, cdef.getClassDeclaration(), + cdef2.getClassDeclaration()); + break; + } + } + } + } + } else { + if (id.equals(idInit)) { + int thisN = ctx.getThisNumber(); + if (!ctx.field.isConstructor()) { + env.error(where, "invalid.constr.invoke"); + return vset.addVar(thisN); + } + // As a consequence of the DA/DU rules in the JLS (draft of + // forthcoming 2e), all variables are both definitely assigned + // and definitely unassigned in unreachable code. Normally, this + // correctly suppresses DA/DU-related errors in such code. + // The use of the DA status of the 'this' variable for the extra + // check below on correct constructor usage, however, does not quite + // fit into this DA/DU scheme. The current representation of + // Vsets for unreachable dead-ends, does not allow 'clearVar' + // to work, as the DA/DU bits (all on) are implicitly represented + // by the fact that the Vset is a dead-end. The DA/DU status + // of the 'this' variable is supposed to be temporarily + // cleared at the beginning of a constructor and during the + // checking of constructor arguments (see below in this method). + // Since 'clearVar' has no effect on dead-ends, we may + // find the 'this' variable in an erroneously definitely-assigned state. + // As a workaround, we suppress the following error message when + // the Vset is a dead-end, i.e., when we are in unreachable code. + // Unfortunately, the special-case treatment of reachability for + // if-then and if-then-else allows unreachable code in some circumstances, + // thus it is possible that no error message will be emitted at all. + // While this behavior is strictly incorrect (thus we call this a + // workaround), the problematic code is indeed unreachable and will + // not be executed. In fact, it will be entirely omitted from the + // translated program, and can cause no harm at runtime. A correct + // solution would require modifying the representation of the DA/DU + // analysis to use finite Vsets only, restricting the universe + // of variables about which assertions are made (even in unreachable + // code) to variables that are actually in scope. Alternatively, the + // Vset extension and the dead-end marker (currently a reserved value + // of the extension) could be represented orthogonally. In either case, + // 'clearVar' could then be made to work on (non-canonical) dead ends. + // See file 'Vset.java'. + if (!vset.isReallyDeadEnd() && vset.testVar(thisN)) { + env.error(where, "constr.invoke.not.first"); + return vset; + } + vset = vset.addVar(thisN); + if (right instanceof SuperExpression) { + // supers require this specific kind of checking + vset = right.checkAmbigName(env, ctx, vset, exp, this); + } else { + vset = right.checkValue(env, ctx, vset, exp); + } + } else { + vset = right.checkAmbigName(env, ctx, vset, exp, this); + if (right.type == Type.tPackage) { + FieldExpression.reportFailedPackagePrefix(env, right); + return vset; + } + if (right instanceof TypeExpression) { + staticRef = true; + } + } + if (right.type.isType(TC_CLASS)) { + c = env.getClassDeclaration(right.type); + } else if (right.type.isType(TC_ARRAY)) { + isArray = true; + c = env.getClassDeclaration(Type.tObject); + } else { + if (!right.type.isType(TC_ERROR)) { + env.error(where, "invalid.method.invoke", right.type); + } + return vset; + } + + // Normally, the effective accessing class is the innermost + // class surrounding the current method call, but, for calls + // of the form '.super.(...)', it is . + // This allows access to protected members of a superclass + // from within a class nested within one of its subclasses. + // Otherwise, for example, the call below to 'matchMethod' + // may fail due to the rules for visibility of inaccessible + // members. For consistency, we treat qualified 'this' in + // the same manner, as error diagnostics will be affected. + // QUERY: Are there subtle unexplored language issues here? + if (right instanceof FieldExpression) { + Identifier id = ((FieldExpression)right).id; + if (id == idThis) { + sourceClass = ((FieldExpression)right).clazz; + } else if (id == idSuper) { + isSuper = true; + sourceClass = ((FieldExpression)right).clazz; + } + } else if (right instanceof SuperExpression) { + isSuper = true; + } + + // Fix for 4158650. When we extend a protected inner + // class in a different package, we may not have access + // to the type of our superclass. Allow the call to + // the superclass constructor from within our constructor + // Note that this check does not apply to constructor + // calls in new instance expressions -- those are part + // of NewInstanceExpression#check(). + if (id != idInit) { + // Required by JLS 6.6.1. Fixes 4143715. + // (See also 4094658.) + if (!FieldExpression.isTypeAccessible(where, env, + right.type, + sourceClass)) { + ClassDeclaration cdecl = + sourceClass.getClassDeclaration(); + if (staticRef) { + env.error(where, "no.type.access", + id, right.type.toString(), cdecl); + } else { + env.error(where, "cant.access.member.type", + id, right.type.toString(), cdecl); + } + } + } + } + + // Compose a list of argument types + boolean hasErrors = false; + + // "this" is not defined during argument checking + if (id.equals(idInit)) { + vset = vset.clearVar(ctx.getThisNumber()); + } + + for (int i = 0 ; i < args.length ; i++) { + vset = args[i].checkValue(env, ctx, vset, exp); + argTypes[i] = args[i].type; + hasErrors = hasErrors || argTypes[i].isType(TC_ERROR); + } + + // "this" is defined after the constructor invocation + if (id.equals(idInit)) { + vset = vset.addVar(ctx.getThisNumber()); + } + + // Check if there are any type errors in the arguments + if (hasErrors) { + return vset; + } + + // Get the method field, given the argument types + clazz = c.getClassDefinition(env); + + if (field == null) { + + field = clazz.matchMethod(env, sourceClass, id, argTypes); + + if (field == null) { + if (id.equals(idInit)) { + if (diagnoseMismatch(env, args, argTypes)) + return vset; + String sig = clazz.getName().getName().toString(); + sig = Type.tMethod(Type.tError, argTypes).typeString(sig, false, false); + env.error(where, "unmatched.constr", sig, c); + return vset; + } + String sig = id.toString(); + sig = Type.tMethod(Type.tError, argTypes).typeString(sig, false, false); + if (clazz.findAnyMethod(env, id) == null) { + if (ctx.getField(env, id) != null) { + env.error(where, "invalid.method", id, c); + } else { + env.error(where, "undef.meth", sig, c); + } + } else if (diagnoseMismatch(env, args, argTypes)) { + } else { + env.error(where, "unmatched.meth", sig, c); + } + return vset; + } + + } + + type = field.getType().getReturnType(); + + // Make sure that static references are allowed + if (staticRef && !field.isStatic()) { + env.error(where, "no.static.meth.access", + field, field.getClassDeclaration()); + return vset; + } + + if (field.isProtected() + && !(right == null) + && !(right instanceof SuperExpression + // Extension of JLS 6.6.2 for qualified 'super'. + || (right instanceof FieldExpression && + ((FieldExpression)right).id == idSuper)) + && !sourceClass.protectedAccess(env, field, right.type)) { + env.error(where, "invalid.protected.method.use", + field.getName(), field.getClassDeclaration(), + right.type); + return vset; + } + + // In .super.(), we cannot simply evaluate + // .super to an object reference (as we would for + // .super.) and then perform an 'invokespecial'. + // An 'invokespecial' must be performed from within (a subclass of) + // the class in which the target method is located. + if (right instanceof FieldExpression && + ((FieldExpression)right).id == idSuper) { + if (!field.isPrivate()) { + // The private case is handled below. + // Use an access method unless the effective accessing class + // (the class qualifying the 'super') is the same as the + // immediately enclosing class, i.e., the qualification was + // unnecessary. + if (sourceClass != ctxClass) { + implMethod = sourceClass.getAccessMember(env, ctx, field, true); + } + } + } + + // Access method for private field if not in the same class. + if (implMethod == null && field.isPrivate()) { + ClassDefinition cdef = field.getClassDefinition(); + if (cdef != ctxClass) { + implMethod = cdef.getAccessMember(env, ctx, field, false); + } + } + + // Make sure that we are not invoking an abstract method + if (field.isAbstract() && (right != null) && (right.op == SUPER)) { + env.error(where, "invoke.abstract", field, field.getClassDeclaration()); + return vset; + } + + if (field.reportDeprecated(env)) { + if (field.isConstructor()) { + env.error(where, "warn.constr.is.deprecated", field); + } else { + env.error(where, "warn.meth.is.deprecated", + field, field.getClassDefinition()); + } + } + + // Check for recursive constructor + if (field.isConstructor() && ctx.field.equals(field)) { + env.error(where, "recursive.constr", field); + } + + // When a package-private class defines public or protected + // members, those members may sometimes be accessed from + // outside of the package in public subclasses. In these + // cases, we need to massage the method call to refer to + // to an accessible subclass rather than the package-private + // parent class. Part of fix for 4135692. + + // Find out if the class which contains this method + // call has access to the class which declares the + // public or protected method referent. + // We don't perform this translation on constructor calls. + if (sourceClass == ctxClass) { + ClassDefinition declarer = field.getClassDefinition(); + if (!field.isConstructor() && + declarer.isPackagePrivate() && + !declarer.getName().getQualifier() + .equals(sourceClass.getName().getQualifier())) { + + //System.out.println("The access of member " + + // field + " declared in class " + + // declarer + + // " is not allowed by the VM from class " + + // accessor + + // ". Replacing with an access of class " + + // clazz); + + // We cannot make this access at the VM level. + // Construct a member which will stand for this + // method in clazz and set `field' to refer to it. + field = + MemberDefinition.makeProxyMember(field, clazz, env); + } + } + + sourceClass.addDependency(field.getClassDeclaration()); + if (sourceClass != ctxClass) { + ctxClass.addDependency(field.getClassDeclaration()); + } + + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, ctx.field); + return vset; + + } catch (AmbiguousMember ee) { + env.error(where, "ambig.field", id, ee.field1, ee.field2); + return vset; + } + + // Make sure it is qualified + if ((right == null) && !field.isStatic()) { + right = ctx.findOuterLink(env, where, field); + vset = right.checkValue(env, ctx, vset, exp); + } + + // Cast arguments + argTypes = field.getType().getArgumentTypes(); + for (int i = 0 ; i < args.length ; i++) { + args[i] = convert(env, ctx, argTypes[i], args[i]); + } + + if (field.isConstructor()) { + MemberDefinition m = field; + if (implMethod != null) { + m = implMethod; + } + int nargs = args.length; + Expression[] newargs = args; + if (nargs > this.args.length) { + // Argument was added above. + // Maintain the model for hidden outer args in outer.super(...): + Expression rightI; + if (right instanceof SuperExpression) { + rightI = new SuperExpression(right.where, ctx); + ((SuperExpression)right).outerArg = args[0]; + } else if (right instanceof ThisExpression) { + rightI = new ThisExpression(right.where, ctx); + } else { + throw new CompilerError("this.init"); + } + if (implMethod != null) { + // Need dummy argument for access method. + // Dummy argument follows outer instance link. + // Leave 'this.args' equal to 'newargs' but + // without the outer instance link. + newargs = new Expression[nargs+1]; + this.args = new Expression[nargs]; + newargs[0] = args[0]; // outer instance + this.args[0] = newargs[1] = new NullExpression(where); // dummy argument + for (int i = 1 ; i < nargs ; i++) { + this.args[i] = newargs[i+1] = args[i]; + } + } else { + // Strip outer instance link from 'this.args'. + // ASSERT(this.arg.length == nargs-1); + for (int i = 1 ; i < nargs ; i++) { + this.args[i-1] = args[i]; + } + } + implementation = new MethodExpression(where, rightI, m, newargs); + implementation.type = type; // Is this needed? + } else { + // No argument was added. + if (implMethod != null) { + // Need dummy argument for access method. + // Dummy argument is first, as there is no outer instance link. + newargs = new Expression[nargs+1]; + newargs[0] = new NullExpression(where); + for (int i = 0 ; i < nargs ; i++) { + newargs[i+1] = args[i]; + } + } + implementation = new MethodExpression(where, right, m, newargs); + } + } else { + // Have ordinary method. + // Argument should have been added only for a constructor. + if (args.length > this.args.length) { + throw new CompilerError("method arg"); + } + if (implMethod != null) { + //System.out.println("Calling " + field + " via " + implMethod); + Expression oldargs[] = this.args; + if (field.isStatic()) { + Expression call = new MethodExpression(where, null, implMethod, oldargs); + implementation = new CommaExpression(where, right, call); + } else { + // Access method needs an explicit 'this' pointer. + int nargs = oldargs.length; + Expression newargs[] = new Expression[nargs+1]; + newargs[0] = right; + for (int i = 0; i < nargs; i++) { + newargs[i+1] = oldargs[i]; + } + implementation = new MethodExpression(where, null, implMethod, newargs); + } + } + } + + // Follow super() by variable initializations + if (ctx.field.isConstructor() && + field.isConstructor() && (right != null) && (right.op == SUPER)) { + Expression e = makeVarInits(env, ctx); + if (e != null) { + if (implementation == null) + implementation = (Expression)this.clone(); + implementation = new CommaExpression(where, implementation, e); + } + } + + // Throw the declared exceptions. + ClassDeclaration exceptions[] = field.getExceptions(env); + if (isArray && (field.getName() == idClone) && + (field.getType().getArgumentTypes().length == 0)) { + /* Arrays pretend that they have "public Object clone()" that doesn't + * throw anything, according to the language spec. + */ + exceptions = new ClassDeclaration[0]; + /* See if there's a bogus catch for it, to issue a warning. */ + for (Context p = ctx; p != null; p = p.prev) { + if (p.node != null && p.node.op == TRY) { + ((TryStatement) p.node).arrayCloneWhere = where; + } + } + } + for (int i = 0 ; i < exceptions.length ; i++) { + if (exp.get(exceptions[i]) == null) { + exp.put(exceptions[i], this); + } + } + + // Mark all blank finals as definitely assigned following 'this(...)'. + // Correctness follows inductively from the requirement that all blank finals + // be definitely assigned at the completion of every constructor. + if (ctx.field.isConstructor() && + field.isConstructor() && (right != null) && (right.op == THIS)) { + ClassDefinition cls = field.getClassDefinition(); + for (MemberDefinition f = cls.getFirstMember() ; f != null ; f = f.getNextMember()) { + if (f.isVariable() && f.isBlankFinal() && !f.isStatic()) { + // Static variables should also be considered defined as well, but this + // is handled in 'SourceClass.checkMembers', and we should not interfere. + vset = vset.addVar(ctx.getFieldNumber(f)); + } + } + } + + return vset; + } + + /** + * Check void expression + */ + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + return checkValue(env, ctx, vset, exp); + } + + /** + * We're about to report a "unmatched method" error. + * Try to issue a better diagnostic by comparing the actual argument types + * with the method (or methods) available. + * In particular, if there is an argument which fails to match any + * method, we report a type mismatch error against that particular argument. + * The diagnostic will report a target type taken from one of the methods. + *

                + * Return false if we couldn't think of anything smart to say. + */ + boolean diagnoseMismatch(Environment env, Expression args[], + Type argTypes[]) throws ClassNotFound { + Type margType[] = new Type[1]; + boolean saidSomething = false; + int start = 0; + while (start < argTypes.length) { + int code = clazz.diagnoseMismatch(env, id, argTypes, start, margType); + String opName = (id.equals(idInit)) ? "constructor" : opNames[op]; + if (code == -2) { + env.error(where, "wrong.number.args", opName); + saidSomething = true; + } + if (code < 0) break; + int i = code >> 2; + boolean castOK = (code & 2) != 0; + boolean ambig = (code & 1) != 0; + Type targetType = margType[0]; + + // At least one argument is offensive to all overloadings. + // targetType is one of the argument types it does not match. + String ttype = ""+targetType; + + // The message might be slightly misleading, if there are other + // argument types that also would match. Hint at this: + //if (ambig) ttype = "{"+ttype+";...}"; + + if (castOK) + env.error(args[i].where, "explicit.cast.needed", opName, argTypes[i], ttype); + else + env.error(args[i].where, "incompatible.type", opName, argTypes[i], ttype); + saidSomething = true; + start = i+1; // look for other bad arguments, too + } + return saidSomething; + } + + /** + * Inline + */ + static final int MAXINLINECOST = Statement.MAXINLINECOST; + + private + Expression inlineMethod(Environment env, Context ctx, Statement s, boolean valNeeded) { + if (env.dump()) { + System.out.println("INLINE METHOD " + field + " in " + ctx.field); + } + LocalMember v[] = LocalMember.copyArguments(ctx, field); + Statement body[] = new Statement[v.length + 2]; + + int n = 0; + if (field.isStatic()) { + body[0] = new ExpressionStatement(where, right); + } else { + if ((right != null) && (right.op == SUPER)) { + right = new ThisExpression(right.where, ctx); + } + body[0] = new VarDeclarationStatement(where, v[n++], right); + } + for (int i = 0 ; i < args.length ; i++) { + body[i + 1] = new VarDeclarationStatement(where, v[n++], args[i]); + } + //System.out.print("BEFORE:"); s.print(System.out); System.out.println(); + // Note: If !valNeeded, then all returns in the body of the method + // change to void returns. + body[body.length - 1] = (s != null) ? s.copyInline(ctx, valNeeded) : null; + //System.out.print("COPY:"); body[body.length - 1].print(System.out); System.out.println(); + LocalMember.doneWithArguments(ctx, v); + + // Make sure the type matches what the return statements are returning. + Type type = valNeeded ? this.type : Type.tVoid; + Expression e = new InlineMethodExpression(where, type, field, new CompoundStatement(where, body)); + return valNeeded ? e.inlineValue(env, ctx) : e.inline(env, ctx); + } + + public Expression inline(Environment env, Context ctx) { + if (implementation != null) + return implementation.inline(env, ctx); + try { + if (right != null) { + right = field.isStatic() ? right.inline(env, ctx) : right.inlineValue(env, ctx); + } + for (int i = 0 ; i < args.length ; i++) { + args[i] = args[i].inlineValue(env, ctx); + } + + // ctxClass is the current class trying to inline this method + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + + Expression e = this; + if (env.opt() && field.isInlineable(env, clazz.isFinal()) && + + // Don't inline if a qualified non-static method: the call + // itself might throw NullPointerException as a side effect + ((right == null) || (right.op==THIS) || field.isStatic()) && + + // We only allow the inlining if the current class can access + // the field, the field's class, and right's declared type. + ctxClass.permitInlinedAccess(env, + field.getClassDeclaration()) && + ctxClass.permitInlinedAccess(env, field) && + (right==null || ctxClass.permitInlinedAccess(env, + env.getClassDeclaration(right.type))) && + + ((id == null) || !id.equals(idInit)) && + (!ctx.field.isInitializer()) && ctx.field.isMethod() && + (ctx.getInlineMemberContext(field) == null)) { + Statement s = (Statement)field.getValue(env); + if ((s == null) || + (s.costInline(MAXINLINECOST, env, ctx) < MAXINLINECOST)) { + e = inlineMethod(env, ctx, s, false); + } + } + return e; + + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + } + + public Expression inlineValue(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineValue(env, ctx); + try { + if (right != null) { + right = field.isStatic() ? right.inline(env, ctx) : right.inlineValue(env, ctx); + } + if (field.getName().equals(idInit)) { + ClassDefinition refc = field.getClassDefinition(); + UplevelReference r = refc.getReferencesFrozen(); + if (r != null) { + r.willCodeArguments(env, ctx); + } + } + for (int i = 0 ; i < args.length ; i++) { + args[i] = args[i].inlineValue(env, ctx); + } + + // ctxClass is the current class trying to inline this method + ClassDefinition ctxClass = ctx.field.getClassDefinition(); + + if (env.opt() && field.isInlineable(env, clazz.isFinal()) && + + // Don't inline if a qualified non-static method: the call + // itself might throw NullPointerException as a side effect + ((right == null) || (right.op==THIS) || field.isStatic()) && + + // We only allow the inlining if the current class can access + // the field, the field's class, and right's declared type. + ctxClass.permitInlinedAccess(env, + field.getClassDeclaration()) && + ctxClass.permitInlinedAccess(env, field) && + (right==null || ctxClass.permitInlinedAccess(env, + env.getClassDeclaration(right.type))) && + + (!ctx.field.isInitializer()) && ctx.field.isMethod() && + (ctx.getInlineMemberContext(field) == null)) { + Statement s = (Statement)field.getValue(env); + if ((s == null) || + (s.costInline(MAXINLINECOST, env, ctx) < MAXINLINECOST)) { + return inlineMethod(env, ctx, s, true); + } + } + return this; + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + } + + public Expression copyInline(Context ctx) { + if (implementation != null) + return implementation.copyInline(ctx); + return super.copyInline(ctx); + } + + public int costInline(int thresh, Environment env, Context ctx) { + if (implementation != null) + return implementation.costInline(thresh, env, ctx); + + // for now, don't allow calls to super() to be inlined. We may fix + // this later + if ((right != null) && (right.op == SUPER)) { + return thresh; + } + return super.costInline(thresh, env, ctx); + } + + /* + * Grab all instance initializer code from the class definition, + * and return as one bolus. Note that we are assuming the + * the relevant fields have already been checked. + * (See the pre-pass in SourceClass.checkMembers which ensures this.) + */ + private Expression makeVarInits(Environment env, Context ctx) { + // insert instance initializers + ClassDefinition clazz = ctx.field.getClassDefinition(); + Expression e = null; + for (MemberDefinition f = clazz.getFirstMember() ; f != null ; f = f.getNextMember()) { + if ((f.isVariable() || f.isInitializer()) && !f.isStatic()) { + try { + f.check(env); + } catch (ClassNotFound ee) { + env.error(f.getWhere(), "class.not.found", ee.name, + f.getClassDefinition()); + } + Expression val = null; + if (f.isUplevelValue()) { + if (f != clazz.findOuterMember()) { + // it's too early to accumulate these + continue; + } + IdentifierExpression arg = + new IdentifierExpression(where, f.getName()); + if (!arg.bind(env, ctx)) { + throw new CompilerError("bind "+arg.id); + } + val = arg; + } else if (f.isInitializer()) { + Statement s = (Statement)f.getValue(); + val = new InlineMethodExpression(where, Type.tVoid, f, s); + } else { + val = (Expression)f.getValue(); + } + // append all initializers to "e": + // This section used to check for variables which were + // initialized to their default values and elide such + // initialization. This is specifically disallowed by + // JLS 12.5 numeral 4, which requires a textual ordering + // on the execution of initializers. + if ((val != null)) { // && !val.equals(0)) { + long p = f.getWhere(); + val = val.copyInline(ctx); + Expression init = val; + if (f.isVariable()) { + Expression v = new ThisExpression(p, ctx); + v = new FieldExpression(p, v, f); + init = new AssignExpression(p, v, val); + } + e = (e == null) ? init : new CommaExpression(p, e, init); + } + } + } + return e; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + if (implementation != null) + throw new CompilerError("codeValue"); + int i = 0; // argument index + if (field.isStatic()) { + if (right != null) { + right.code(env, ctx, asm); + } + } else if (right == null) { + asm.add(where, opc_aload, 0); + } else if (right.op == SUPER) { + // 'super.(...)', 'super(...)', or '.super(...)' + /***** + isSuper = true; + *****/ + right.codeValue(env, ctx, asm); + if (idInit.equals(id)) { + // 'super(...)' or '.super(...)' only + ClassDefinition refc = field.getClassDefinition(); + UplevelReference r = refc.getReferencesFrozen(); + if (r != null) { + // When calling a constructor for a class with + // embedded uplevel references, add extra arguments. + if (r.isClientOuterField()) { + // the extra arguments are inserted after this one + args[i++].codeValue(env, ctx, asm); + } + r.codeArguments(env, ctx, asm, where, field); + } + } + } else { + right.codeValue(env, ctx, asm); + /***** + if (right.op == FIELD && + ((FieldExpression)right).id == idSuper) { + // '.super.(...)' + isSuper = true; + } + *****/ + } + + for ( ; i < args.length ; i++) { + args[i].codeValue(env, ctx, asm); + } + + if (field.isStatic()) { + asm.add(where, opc_invokestatic, field); + } else if (field.isConstructor() || field.isPrivate() || isSuper) { + asm.add(where, opc_invokespecial, field); + } else if (field.getClassDefinition().isInterface()) { + asm.add(where, opc_invokeinterface, field); + } else { + asm.add(where, opc_invokevirtual, field); + } + + if (right != null && right.op == SUPER && idInit.equals(id)) { + // 'super(...)' or '.super(...)' + ClassDefinition refc = ctx.field.getClassDefinition(); + UplevelReference r = refc.getReferencesFrozen(); + if (r != null) { + // After calling a superclass constructor in a class with + // embedded uplevel references, initialize uplevel fields. + r.codeInitialization(env, ctx, asm, where, field); + } + } + } + + /** + * Check if the first thing is a constructor invocation + */ + public Expression firstConstructor() { + return id.equals(idInit) ? this : null; + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op]); + if (right != null) { + out.print(" "); + right.print(out); + } + out.print(" " + ((id == null) ? idInit : id)); + for (int i = 0 ; i < args.length ; i++) { + out.print(" "); + if (args[i] != null) { + args[i].print(out); + } else { + out.print(""); + } + } + out.print(")"); + if (implementation != null) { + out.print("/IMPL="); + implementation.print(out); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/MultiplyExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/MultiplyExpression.java new file mode 100644 index 000000000..6515e5190 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/MultiplyExpression.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class MultiplyExpression extends BinaryArithmeticExpression { + /** + * constructor + */ + public MultiplyExpression(long where, Expression left, Expression right) { + super(MUL, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a * b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a * b); + } + Expression eval(float a, float b) { + return new FloatExpression(where, a * b); + } + Expression eval(double a, double b) { + return new DoubleExpression(where, a * b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.equals(1)) { + return right; + } + if (right.equals(1)) { + return left; + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_imul + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NaryExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NaryExpression.java new file mode 100644 index 000000000..d310cd05c --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NaryExpression.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NaryExpression extends UnaryExpression { + Expression args[]; + + /** + * Constructor + */ + NaryExpression(int op, long where, Type type, Expression right, Expression args[]) { + super(op, where, type, right); + this.args = args; + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + NaryExpression e = (NaryExpression)clone(); + if (right != null) { + e.right = right.copyInline(ctx); + } + e.args = new Expression[args.length]; + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + e.args[i] = args[i].copyInline(ctx); + } + } + return e; + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + int cost = 3; + if (right != null) + cost += right.costInline(thresh, env, ctx); + for (int i = 0 ; (i < args.length) && (cost < thresh) ; i++) { + if (args[i] != null) { + cost += args[i].costInline(thresh, env, ctx); + } + } + return cost; + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + "#" + hashCode()); + if (right != null) { + out.print(" "); + right.print(out); + } + for (int i = 0 ; i < args.length ; i++) { + out.print(" "); + if (args[i] != null) { + args[i].print(out); + } else { + out.print(""); + } + } + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NegativeExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NegativeExpression.java new file mode 100644 index 000000000..d865c9a5d --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NegativeExpression.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NegativeExpression extends UnaryExpression { + /** + * Constructor + */ + public NegativeExpression(long where, Expression right) { + super(NEG, where, right.type, right); + } + + /** + * Select the type of the expression + */ + void selectType(Environment env, Context ctx, int tm) { + if ((tm & TM_DOUBLE) != 0) { + type = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + type = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + type = Type.tLong; + } else { + type = Type.tInt; + } + right = convert(env, ctx, type, right); + } + + /** + * Evaluate + */ + Expression eval(int a) { + return new IntExpression(where, -a); + } + Expression eval(long a) { + return new LongExpression(where, -a); + } + Expression eval(float a) { + return new FloatExpression(where, -a); + } + Expression eval(double a) { + return new DoubleExpression(where, -a); + } + + /** + * Simplify + */ + Expression simplify() { + if (right.op == NEG) { + return ((NegativeExpression)right).right; + } + return this; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + right.codeValue(env, ctx, asm); + asm.add(where, opc_ineg + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NewArrayExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NewArrayExpression.java new file mode 100644 index 000000000..8c5c71452 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NewArrayExpression.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.ArrayData; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NewArrayExpression extends NaryExpression { + Expression init; + + /** + * Constructor + */ + public NewArrayExpression(long where, Expression right, Expression args[]) { + super(NEWARRAY, where, Type.tError, right, args); + } + + public NewArrayExpression(long where, Expression right, Expression args[], Expression init) { + this(where, right, args); + this.init = init; + } + + /** + * Check + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + type = right.toType(env, ctx); + + boolean flag = (init != null); // flag says that dims are forbidden + for (int i = 0 ; i < args.length ; i++) { + Expression dim = args[i]; + if (dim == null) { + if (i == 0 && !flag) { + env.error(where, "array.dim.missing"); + } + flag = true; + } else { + if (flag) { + env.error(dim.where, "invalid.array.dim"); + } + vset = dim.checkValue(env, ctx, vset, exp); + args[i] = convert(env, ctx, Type.tInt, dim); + } + type = Type.tArray(type); + } + if (init != null) { + vset = init.checkInitializer(env, ctx, vset, type, exp); + init = convert(env, ctx, type, init); + } + return vset; + } + + public Expression copyInline(Context ctx) { + NewArrayExpression e = (NewArrayExpression)super.copyInline(ctx); + if (init != null) { + e.init = init.copyInline(ctx); + } + return e; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + Expression e = null; + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + e = (e != null) ? new CommaExpression(where, e, args[i]) : args[i]; + } + } + if (init != null) + e = (e != null) ? new CommaExpression(where, e, init) : init; + return (e != null) ? e.inline(env, ctx) : null; + } + public Expression inlineValue(Environment env, Context ctx) { + if (init != null) + return init.inlineValue(env, ctx); // args are all null + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + args[i] = args[i].inlineValue(env, ctx); + } + } + return this; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + int t = 0; + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + args[i].codeValue(env, ctx, asm); + t++; + } + } + if (args.length > 1) { + asm.add(where, opc_multianewarray, new ArrayData(type, t)); + return; + } + + switch (type.getElementType().getTypeCode()) { + case TC_BOOLEAN: + asm.add(where, opc_newarray, T_BOOLEAN); break; + case TC_BYTE: + asm.add(where, opc_newarray, T_BYTE); break; + case TC_SHORT: + asm.add(where, opc_newarray, T_SHORT); break; + case TC_CHAR: + asm.add(where, opc_newarray, T_CHAR); break; + case TC_INT: + asm.add(where, opc_newarray, T_INT); break; + case TC_LONG: + asm.add(where, opc_newarray, T_LONG); break; + case TC_FLOAT: + asm.add(where, opc_newarray, T_FLOAT); break; + case TC_DOUBLE: + asm.add(where, opc_newarray, T_DOUBLE); break; + case TC_ARRAY: + asm.add(where, opc_anewarray, type.getElementType()); break; + case TC_CLASS: + asm.add(where, opc_anewarray, + env.getClassDeclaration(type.getElementType())); + break; + default: + throw new CompilerError("codeValue"); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NewInstanceExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NewInstanceExpression.java new file mode 100644 index 000000000..a5ab8f814 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NewInstanceExpression.java @@ -0,0 +1,531 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NewInstanceExpression extends NaryExpression { + MemberDefinition field; + Expression outerArg; + ClassDefinition body; + + // Access method for constructor, if needed. + MemberDefinition implMethod = null; + + /** + * Constructor + */ + public NewInstanceExpression(long where, Expression right, Expression args[]) { + super(NEWINSTANCE, where, Type.tError, right, args); + } + public NewInstanceExpression(long where, Expression right, + Expression args[], + Expression outerArg, ClassDefinition body) { + this(where, right, args); + this.outerArg = outerArg; + this.body = body; + } + + /** + * From the "new" in an expression of the form outer.new InnerCls(...), + * return the "outer" expression, or null if there is none. + */ + public Expression getOuterArg() { + return outerArg; + } + + int precedence() { + return 100; + } + + public Expression order() { + // act like a method or field reference expression: + if (outerArg != null && opPrecedence[FIELD] > outerArg.precedence()) { + UnaryExpression e = (UnaryExpression)outerArg; + outerArg = e.right; + e.right = order(); + return e; + } + return this; + } + + /** + * Check expression type + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + // What type? + ClassDefinition def = null; + + Expression alreadyChecked = null; + + try { + if (outerArg != null) { + vset = outerArg.checkValue(env, ctx, vset, exp); + + // Remember the expression that we already checked + // so that we don't attempt to check it again when + // it appears as an argument to the constructor. + // Fix for 4030426. + alreadyChecked = outerArg; + + // Check outerArg and the type name together. + Identifier typeName = FieldExpression.toIdentifier(right); + + // According to the inner classes spec, the type name in a + // qualified 'new' expression must be a single identifier. + if (typeName != null && typeName.isQualified()) { + env.error(where, "unqualified.name.required", typeName); + } + + if (typeName == null || !outerArg.type.isType(TC_CLASS)) { + if (!outerArg.type.isType(TC_ERROR)) { + env.error(where, "invalid.field.reference", + idNew, outerArg.type); + } + outerArg = null; + } else { + // Don't perform checks on components of qualified name + // ('getQualifiedClassDefinition'), because a qualified + // name is illegal in this context, and will have previously + // been reported as an error. + ClassDefinition oc = env.getClassDefinition(outerArg.type); + Identifier nm = oc.resolveInnerClass(env, typeName); + right = new TypeExpression(right.where, Type.tClass(nm)); + // Check access directly, since we're not calling toType(). + env.resolve(right.where, ctx.field.getClassDefinition(), + right.type); + // and fall through to env.getClassDefinition() below + } + } + + if (!(right instanceof TypeExpression)) { + // The call to 'toType' should perform component access checks. + right = new TypeExpression(right.where, right.toType(env, ctx)); + } + + if (right.type.isType(TC_CLASS)) + def = env.getClassDefinition(right.type); + } catch (AmbiguousClass ee) { + env.error(where, "ambig.class", ee.name1, ee.name2); + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, ctx.field); + } + + Type t = right.type; + boolean hasErrors = t.isType(TC_ERROR); + + if (!t.isType(TC_CLASS)) { + if (!hasErrors) { + env.error(where, "invalid.arg.type", t, opNames[op]); + hasErrors = true; + } + } + + // If we failed to find a class or a class was ambiguous, def + // may be null. Bail out. This allows us to report multiple + // unfound or ambiguous classes rather than tripping over an + // internal compiler error. + if (def == null) { + type = Type.tError; + return vset; + } + + // Add an extra argument, maybe. + Expression args[] = this.args; + args = NewInstanceExpression. + insertOuterLink(env, ctx, where, def, outerArg, args); + if (args.length > this.args.length) + outerArg = args[0]; // recopy the checked arg + else if (outerArg != null) + // else set it to void (maybe it has a side-effect) + outerArg = new CommaExpression(outerArg.where, outerArg, null); + + // Compose a list of argument types + Type argTypes[] = new Type[args.length]; + + for (int i = 0 ; i < args.length ; i++) { + // Don't check 'outerArg' again. Fix for 4030426. + if (args[i] != alreadyChecked) { + vset = args[i].checkValue(env, ctx, vset, exp); + } + argTypes[i] = args[i].type; + hasErrors = hasErrors || argTypes[i].isType(TC_ERROR); + } + + try { + // Check if there are any type errors in the arguments + if (hasErrors) { + type = Type.tError; + return vset; + } + + + // Get the source class that this declaration appears in. + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + + ClassDeclaration c = env.getClassDeclaration(t); + + // If this is an anonymous class, handle it specially now. + if (body != null) { + // The current package. + Identifier packageName = sourceClass.getName().getQualifier(); + + // This is an anonymous class. + ClassDefinition superDef = null; + if (def.isInterface()) { + // For interfaces, our superclass is java.lang.Object. + // We could just assume that java.lang.Object has + // one constructor with no arguments in the code + // that follows, but we don't. This way, if Object + // grows a new constructor (unlikely) then the + // compiler should handle it. + superDef = env.getClassDefinition(idJavaLangObject); + } else { + // Otherwise, def is actually our superclass. + superDef = def; + } + // Try to find a matching constructor in our superclass. + MemberDefinition constructor = + superDef.matchAnonConstructor(env, packageName, argTypes); + if (constructor != null) { + // We've found one. Process the body. + // + // Note that we are passing in the constructors' argument + // types, rather than the argument types of the actual + // expressions, to checkLocalClass(). Previously, + // the expression types were passed in. This could + // lead to trouble when one of the argument types was + // the special internal type tNull. (bug 4054689). + if (tracing) + env.dtEvent( + "NewInstanceExpression.checkValue: ANON CLASS " + + body + " SUPER " + def); + vset = body.checkLocalClass(env, ctx, vset, + def, args, + constructor.getType() + .getArgumentTypes()); + + // Set t to be the true type of this expression. + // (bug 4102056). + t = body.getClassDeclaration().getType(); + + def = body; + } + } else { + // Check if it is an interface + if (def.isInterface()) { + env.error(where, "new.intf", c); + return vset; + } + + // Check for abstract class + if (def.mustBeAbstract(env)) { + env.error(where, "new.abstract", c); + return vset; + } + } + + // Get the constructor that the "new" expression should call. + field = def.matchMethod(env, sourceClass, idInit, argTypes); + + // Report an error if there is no matching constructor. + if (field == null) { + MemberDefinition anyInit = def.findAnyMethod(env, idInit); + if (anyInit != null && + new MethodExpression(where, right, anyInit, args) + .diagnoseMismatch(env, args, argTypes)) + return vset; + String sig = c.getName().getName().toString(); + sig = Type.tMethod(Type.tError, argTypes).typeString(sig, false, false); + env.error(where, "unmatched.constr", sig, c); + return vset; + } + + if (field.isPrivate()) { + ClassDefinition cdef = field.getClassDefinition(); + if (cdef != sourceClass) { + // Use access method. + implMethod = cdef.getAccessMember(env, ctx, field, false); + } + } + + // Check for abstract anonymous class + if (def.mustBeAbstract(env)) { + env.error(where, "new.abstract", c); + return vset; + } + + if (field.reportDeprecated(env)) { + env.error(where, "warn.constr.is.deprecated", + field, field.getClassDefinition()); + } + + // According to JLS 6.6.2, a protected constructor may be accessed + // by a class instance creation expression only from within the + // package in which it is defined. + if (field.isProtected() && + !(sourceClass.getName().getQualifier().equals( + field.getClassDeclaration().getName().getQualifier()))) { + env.error(where, "invalid.protected.constructor.use", + sourceClass); + } + + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, opNames[op]); + return vset; + + } catch (AmbiguousMember ee) { + env.error(where, "ambig.constr", ee.field1, ee.field2); + return vset; + } + + // Cast arguments + argTypes = field.getType().getArgumentTypes(); + for (int i = 0 ; i < args.length ; i++) { + args[i] = convert(env, ctx, argTypes[i], args[i]); + } + if (args.length > this.args.length) { + outerArg = args[0]; // recopy the checked arg + // maintain an accurate tree + for (int i = 1 ; i < args.length ; i++) { + this.args[i-1] = args[i]; + } + } + + // Throw the declared exceptions. + ClassDeclaration exceptions[] = field.getExceptions(env); + for (int i = 0 ; i < exceptions.length ; i++) { + if (exp.get(exceptions[i]) == null) { + exp.put(exceptions[i], this); + } + } + + type = t; + + return vset; + } + + /** + * Given a list of arguments for a constructor, + * return a possibly modified list which includes the hidden + * argument which initializes the uplevel self pointer. + * @arg def the class which perhaps contains an outer link. + * @arg outerArg if non-null, an explicit location in which to construct. + */ + public static Expression[] insertOuterLink(Environment env, Context ctx, + long where, ClassDefinition def, + Expression outerArg, + Expression args[]) { + if (!def.isTopLevel() && !def.isLocal()) { + Expression args2[] = new Expression[1+args.length]; + System.arraycopy(args, 0, args2, 1, args.length); + try { + if (outerArg == null) + outerArg = ctx.findOuterLink(env, where, + def.findAnyMethod(env, idInit)); + } catch (ClassNotFound e) { + // die somewhere else + } + args2[0] = outerArg; + args = args2; + } + return args; + } + + /** + * Check void expression + */ + public Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + return checkValue(env, ctx, vset, exp); + } + + /** + * Inline + */ + final int MAXINLINECOST = Statement.MAXINLINECOST; + + public Expression copyInline(Context ctx) { + NewInstanceExpression e = (NewInstanceExpression)super.copyInline(ctx); + if (outerArg != null) { + e.outerArg = outerArg.copyInline(ctx); + } + return e; + } + + Expression inlineNewInstance(Environment env, Context ctx, Statement s) { + if (env.dump()) { + System.out.println("INLINE NEW INSTANCE " + field + " in " + ctx.field); + } + LocalMember v[] = LocalMember.copyArguments(ctx, field); + Statement body[] = new Statement[v.length + 2]; + + int o = 1; + if (outerArg != null && !outerArg.type.isType(TC_VOID)) { + o = 2; + body[1] = new VarDeclarationStatement(where, v[1], outerArg); + } else if (outerArg != null) { + body[0] = new ExpressionStatement(where, outerArg); + } + for (int i = 0 ; i < args.length ; i++) { + body[i+o] = new VarDeclarationStatement(where, v[i+o], args[i]); + } + //System.out.print("BEFORE:"); s.print(System.out); System.out.println(); + body[body.length - 1] = (s != null) ? s.copyInline(ctx, false) : null; + //System.out.print("COPY:"); body[body.length - 1].print(System.out); System.out.println(); + //System.out.print("AFTER:"); s.print(System.out); System.out.println(); + LocalMember.doneWithArguments(ctx, v); + + return new InlineNewInstanceExpression(where, type, field, new CompoundStatement(where, body)).inline(env, ctx); + } + + public Expression inline(Environment env, Context ctx) { + return inlineValue(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + if (body != null) { + body.inlineLocalClass(env); + } + ClassDefinition refc = field.getClassDefinition(); + UplevelReference r = refc.getReferencesFrozen(); + if (r != null) { + r.willCodeArguments(env, ctx); + } + //right = right.inlineValue(env, ctx); + + try { + if (outerArg != null) { + if (outerArg.type.isType(TC_VOID)) + outerArg = outerArg.inline(env, ctx); + else + outerArg = outerArg.inlineValue(env, ctx); + } + for (int i = 0 ; i < args.length ; i++) { + args[i] = args[i].inlineValue(env, ctx); + } + // This 'false' that fy put in is inexplicable to me + // the decision to not inline new instance expressions + // should be revisited. - dps + if (false && env.opt() && field.isInlineable(env, false) && + (!ctx.field.isInitializer()) && ctx.field.isMethod() && + (ctx.getInlineMemberContext(field) == null)) { + Statement s = (Statement)field.getValue(env); + if ((s == null) + || (s.costInline(MAXINLINECOST, env, ctx) < MAXINLINECOST)) { + return inlineNewInstance(env, ctx, s); + } + } + } catch (ClassNotFound e) { + throw new CompilerError(e); + } + if (outerArg != null && outerArg.type.isType(TC_VOID)) { + Expression e = outerArg; + outerArg = null; + return new CommaExpression(where, e, this); + } + return this; + } + + public int costInline(int thresh, Environment env, Context ctx) { + if (body != null) { + return thresh; // don't copy classes... + } + if (ctx == null) { + return 2 + super.costInline(thresh, env, ctx); + } + // sourceClass is the current class trying to inline this method + ClassDefinition sourceClass = ctx.field.getClassDefinition(); + try { + // We only allow the inlining if the current class can access + // the field and the field's class; + if ( sourceClass.permitInlinedAccess(env, field.getClassDeclaration()) + && sourceClass.permitInlinedAccess(env, field)) { + return 2 + super.costInline(thresh, env, ctx); + } + } catch (ClassNotFound e) { + } + return thresh; + } + + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + codeCommon(env, ctx, asm, false); + } + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeCommon(env, ctx, asm, true); + } + @SuppressWarnings("fallthrough") + private void codeCommon(Environment env, Context ctx, Assembler asm, + boolean forValue) { + asm.add(where, opc_new, field.getClassDeclaration()); + if (forValue) { + asm.add(where, opc_dup); + } + + ClassDefinition refc = field.getClassDefinition(); + UplevelReference r = refc.getReferencesFrozen(); + + if (r != null) { + r.codeArguments(env, ctx, asm, where, field); + } + + if (outerArg != null) { + outerArg.codeValue(env, ctx, asm); + switch (outerArg.op) { + case THIS: + case SUPER: + case NEW: + // guaranteed non-null + break; + case FIELD: { + MemberDefinition f = ((FieldExpression)outerArg).field; + if (f != null && f.isNeverNull()) { + break; + } + // else fall through: + } + default: + // Test for nullity by invoking some trivial operation + // that can throw a NullPointerException. + try { + ClassDefinition c = env.getClassDefinition(idJavaLangObject); + MemberDefinition getc = c.getFirstMatch(idGetClass); + asm.add(where, opc_dup); + asm.add(where, opc_invokevirtual, getc); + asm.add(where, opc_pop); + } catch (ClassNotFound e) { + } + } + } + + if (implMethod != null) { + // Constructor call will be via an access method. + // Pass 'null' as the value of the dummy argument. + asm.add(where, opc_aconst_null); + } + + for (int i = 0 ; i < args.length ; i++) { + args[i].codeValue(env, ctx, asm); + } + asm.add(where, opc_invokespecial, + ((implMethod != null) ? implMethod : field)); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/Node.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Node.java new file mode 100644 index 000000000..f9c2fad00 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Node.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; +import java.io.ByteArrayOutputStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class Node implements Constants, Cloneable { + int op; + long where; + + /** + * Constructor + */ + Node(int op, long where) { + this.op = op; + this.where = where; + } + + /** + * Get the operator + */ + public int getOp() { + return op; + } + + /** + * Get where + */ + public long getWhere() { + return where; + } + + /** + * Implicit conversions + */ + public Expression convert(Environment env, Context ctx, Type t, Expression e) { + if (e.type.isType(TC_ERROR) || t.isType(TC_ERROR)) { + // An error was already reported + return e; + } + + if (e.type.equals(t)) { + // The types are already the same + return e; + } + + try { + if (e.fitsType(env, ctx, t)) { + return new ConvertExpression(where, t, e); + } + + if (env.explicitCast(e.type, t)) { + env.error(where, "explicit.cast.needed", opNames[op], e.type, t); + return new ConvertExpression(where, t, e); + } + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, opNames[op]); + } + + // The cast is not allowed + env.error(where, "incompatible.type", opNames[op], e.type, t); + return new ConvertExpression(where, Type.tError, e); + } + + /** + * Print + */ + public void print(PrintStream out) { + throw new CompilerError("print"); + } + + /** + * Clone this object. + */ + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw (InternalError) new InternalError().initCause(e); + } + } + + /* + * Useful for simple debugging + */ + public String toString() { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + print(new PrintStream(bos)); + return bos.toString(); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NotEqualExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NotEqualExpression.java new file mode 100644 index 000000000..2e22161fe --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NotEqualExpression.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NotEqualExpression extends BinaryEqualityExpression { + /** + * constructor + */ + public NotEqualExpression(long where, Expression left, Expression right) { + super(NE, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new BooleanExpression(where, a != b); + } + Expression eval(long a, long b) { + return new BooleanExpression(where, a != b); + } + Expression eval(float a, float b) { + return new BooleanExpression(where, a != b); + } + Expression eval(double a, double b) { + return new BooleanExpression(where, a != b); + } + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a != b); + } + + /** + * Simplify + */ + Expression simplify() { + if (left.isConstant() && !right.isConstant()) { + return new NotEqualExpression(where, right, left); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + left.codeValue(env, ctx, asm); + switch (left.type.getTypeCode()) { + case TC_BOOLEAN: + case TC_INT: + if (!right.equals(0)) { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_icmpne : opc_if_icmpeq, lbl, whenTrue); + return; + } + break; + case TC_LONG: + right.codeValue(env, ctx, asm); + asm.add(where, opc_lcmp); + break; + case TC_FLOAT: + right.codeValue(env, ctx, asm); + asm.add(where, opc_fcmpl); + break; + case TC_DOUBLE: + right.codeValue(env, ctx, asm); + asm.add(where, opc_dcmpl); + break; + case TC_ARRAY: + case TC_CLASS: + case TC_NULL: + if (right.equals(0)) { + asm.add(where, whenTrue ? opc_ifnonnull : opc_ifnull, lbl, whenTrue); + } else { + right.codeValue(env, ctx, asm); + asm.add(where, whenTrue ? opc_if_acmpne : opc_if_acmpeq, lbl, whenTrue); + } + return; + default: + throw new CompilerError("Unexpected Type"); + } + asm.add(where, whenTrue ? opc_ifne : opc_ifeq, lbl, whenTrue); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NotExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NotExpression.java new file mode 100644 index 000000000..2bfeabaed --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NotExpression.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NotExpression extends UnaryExpression { + /** + * Constructor + */ + public NotExpression(long where, Expression right) { + super(NOT, where, Type.tBoolean, right); + } + + /** + * Select the type of the expression + */ + void selectType(Environment env, Context ctx, int tm) { + right = convert(env, ctx, Type.tBoolean, right); + } + + /* + * Check a "not" expression. + * + * cvars is modified so that + * cvar.vsTrue indicates variables with a known value if + * the expression is true. + * cvars.vsFalse indicates variables with a known value if + * the expression is false + * + * For "not" expressions, we look at the inside expression, and then + * swap true and false. + */ + + public void checkCondition(Environment env, Context ctx, Vset vset, + Hashtable exp, ConditionVars cvars) { + right.checkCondition(env, ctx, vset, exp, cvars); + right = convert(env, ctx, Type.tBoolean, right); + // swap true and false + Vset temp = cvars.vsFalse; + cvars.vsFalse = cvars.vsTrue; + cvars.vsTrue = temp; + } + + /** + * Evaluate + */ + Expression eval(boolean a) { + return new BooleanExpression(where, !a); + } + + /** + * Simplify + */ + Expression simplify() { + // Check if the expression can be optimized + switch (right.op) { + case NOT: + return ((NotExpression)right).right; + + case EQ: + case NE: + case LT: + case LE: + case GT: + case GE: + break; + + default: + return this; + } + + // Can't negate real comparisons + BinaryExpression bin = (BinaryExpression)right; + if (bin.left.type.inMask(TM_REAL)) { + return this; + } + + // Negate comparison + switch (right.op) { + case EQ: + return new NotEqualExpression(where, bin.left, bin.right); + case NE: + return new EqualExpression(where, bin.left, bin.right); + case LT: + return new GreaterOrEqualExpression(where, bin.left, bin.right); + case LE: + return new GreaterExpression(where, bin.left, bin.right); + case GT: + return new LessOrEqualExpression(where, bin.left, bin.right); + case GE: + return new LessExpression(where, bin.left, bin.right); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + right.codeBranch(env, ctx, asm, lbl, !whenTrue); + } + + /** + * Instead of relying on the default code generation which uses + * conditional branching, generate a simpler stream using XOR. + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + right.codeValue(env, ctx, asm); + asm.add(where, opc_ldc, 1); + asm.add(where, opc_ixor); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/NullExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NullExpression.java new file mode 100644 index 000000000..74ff48214 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/NullExpression.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class NullExpression extends ConstantExpression { + /** + * Constructor + */ + public NullExpression(long where) { + super(NULL, where, Type.tNull); + } + + /** + * Check if the expression is equal to a value + */ + public boolean equals(int i) { + return i == 0; + } + + public boolean isNull() { + return true; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_aconst_null); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("null"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/OrExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/OrExpression.java new file mode 100644 index 000000000..12bd20631 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/OrExpression.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class OrExpression extends BinaryLogicalExpression { + /** + * constructor + */ + public OrExpression(long where, Expression left, Expression right) { + super(OR, where, left, right); + } + + /* + * Check an "or" expression. + * + * cvars is modified so that + * cvar.vsTrue indicates variables with a known value if + * either the left and right hand side isn true + * cvars.vsFalse indicates variables with a known value if + * both the left or right hand side are false + */ + public void checkCondition(Environment env, Context ctx, Vset vset, + Hashtable exp, ConditionVars cvars) { + // Find out when the left side is true/false + left.checkCondition(env, ctx, vset, exp, cvars); + left = convert(env, ctx, Type.tBoolean, left); + Vset vsTrue = cvars.vsTrue.copy(); + Vset vsFalse = cvars.vsFalse.copy(); + + // Only look at the right side if the left side is false + right.checkCondition(env, ctx, vsFalse, exp, cvars); + right = convert(env, ctx, Type.tBoolean, right); + + // cvars.vsFalse actually reports that both returned false + // cvars.vsTrue must be set back to either left side or the right + // side returning false; + cvars.vsTrue = cvars.vsTrue.join(vsTrue); + } + + /** + * Evaluate + */ + Expression eval(boolean a, boolean b) { + return new BooleanExpression(where, a || b); + } + + /** + * Simplify + */ + Expression simplify() { + if (right.equals(false)) { + return left; + } + if (left.equals(true)) { + return left; + } + if (left.equals(false)) { + return right; + } + if (right.equals(true)) { + // Preserve effects of left argument. + return new CommaExpression(where, left, right).simplify(); + } + return this; + } + + /** + * Code + */ + void codeBranch(Environment env, Context ctx, Assembler asm, Label lbl, boolean whenTrue) { + if (whenTrue) { + left.codeBranch(env, ctx, asm, lbl, true); + right.codeBranch(env, ctx, asm, lbl, true); + } else { + Label lbl2 = new Label(); + left.codeBranch(env, ctx, asm, lbl2, true); + right.codeBranch(env, ctx, asm, lbl, false); + asm.add(lbl2); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/PositiveExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PositiveExpression.java new file mode 100644 index 000000000..05d997d19 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PositiveExpression.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class PositiveExpression extends UnaryExpression { + /** + * Constructor + */ + public PositiveExpression(long where, Expression right) { + super(POS, where, right.type, right); + } + + /** + * Select the type of the expression + */ + void selectType(Environment env, Context ctx, int tm) { + if ((tm & TM_DOUBLE) != 0) { + type = Type.tDouble; + } else if ((tm & TM_FLOAT) != 0) { + type = Type.tFloat; + } else if ((tm & TM_LONG) != 0) { + type = Type.tLong; + } else { + type = Type.tInt; + } + right = convert(env, ctx, type, right); + } + + /** + * Simplify + */ + Expression simplify() { + return right; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/PostDecExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PostDecExpression.java new file mode 100644 index 000000000..d8436fcdc --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PostDecExpression.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class PostDecExpression extends IncDecExpression { + /** + * Constructor + */ + public PostDecExpression(long where, Expression right) { + super(POSTDEC, where, right); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, false, false, true); + } + public void code(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, false, false, false); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/PostIncExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PostIncExpression.java new file mode 100644 index 000000000..25194f7a9 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PostIncExpression.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class PostIncExpression extends IncDecExpression { + /** + * Constructor + */ + public PostIncExpression(long where, Expression right) { + super(POSTINC, where, right); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, true, false, true); + } + public void code(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, true, false, false); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/PreDecExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PreDecExpression.java new file mode 100644 index 000000000..462d6160f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PreDecExpression.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class PreDecExpression extends IncDecExpression { + /** + * Constructor + */ + public PreDecExpression(long where, Expression right) { + super(PREDEC, where, right); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, false, true, true); + } + public void code(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, false, true, false); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/PreIncExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PreIncExpression.java new file mode 100644 index 000000000..abe0ebec9 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/PreIncExpression.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class PreIncExpression extends IncDecExpression { + /** + * Constructor + */ + public PreIncExpression(long where, Expression right) { + super(PREINC, where, right); + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, true, true, true); + } + public void code(Environment env, Context ctx, Assembler asm) { + codeIncDec(env, ctx, asm, true, true, false); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/RemainderExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/RemainderExpression.java new file mode 100644 index 000000000..d73b1b2ba --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/RemainderExpression.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class RemainderExpression extends DivRemExpression { + /** + * constructor + */ + public RemainderExpression(long where, Expression left, Expression right) { + super(REM, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a % b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a % b); + } + Expression eval(float a, float b) { + return new FloatExpression(where, a % b); + } + Expression eval(double a, double b) { + return new DoubleExpression(where, a % b); + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_irem + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ReturnStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ReturnStatement.java new file mode 100644 index 000000000..6e27a947e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ReturnStatement.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ReturnStatement extends Statement { + Expression expr; + + /** + * Constructor + */ + public ReturnStatement(long where, Expression expr) { + super(RETURN, where); + this.expr = expr; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + vset = reach(env, vset); + if (expr != null) { + vset = expr.checkValue(env, ctx, vset, exp); + } + + // Make sure the return isn't inside a static initializer + if (ctx.field.isInitializer()) { + env.error(where, "return.inside.static.initializer"); + return DEAD_END; + } + // Check return type + if (ctx.field.getType().getReturnType().isType(TC_VOID)) { + if (expr != null) { + if (ctx.field.isConstructor()) { + env.error(where, "return.with.value.constr", ctx.field); + } else { + env.error(where, "return.with.value", ctx.field); + } + expr = null; + } + } else { + if (expr == null) { + env.error(where, "return.without.value", ctx.field); + } else { + expr = convert(env, ctx, ctx.field.getType().getReturnType(), expr); + } + } + CheckContext mctx = ctx.getReturnContext(); + if (mctx != null) { + mctx.vsBreak = mctx.vsBreak.join(vset); + } + CheckContext exitctx = ctx.getTryExitContext(); + if (exitctx != null) { + exitctx.vsTryExit = exitctx.vsTryExit.join(vset); + } + if (expr != null) { + // see if we are returning a value out of a try or synchronized + // statement. If so, find the outermost one. . . . + Node outerFinallyNode = null; + for (Context c = ctx; c != null; c = c.prev) { + if (c.node == null) { + continue; + } + if (c.node.op == METHOD) { + // Don't search outside current method. Fixes 4084230. + break; + } + if (c.node.op == SYNCHRONIZED) { + outerFinallyNode = c.node; + break; + } else if (c.node.op == FINALLY + && ((CheckContext)c).vsContinue != null) { + outerFinallyNode = c.node; + } + } + if (outerFinallyNode != null) { + if (outerFinallyNode.op == FINALLY) { + ((FinallyStatement)outerFinallyNode).needReturnSlot = true; + } else { + ((SynchronizedStatement)outerFinallyNode).needReturnSlot = true; + } + } + } + return DEAD_END; + } + + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (expr != null) { + expr = expr.inlineValue(env, ctx); + } + return this; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + ((expr != null) ? expr.costInline(thresh, env, ctx) : 0); + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + Expression e = (expr != null) ? expr.copyInline(ctx) : null; + if ((!valNeeded) && (e != null)) { + Statement body[] = { + new ExpressionStatement(where, e), + new InlineReturnStatement(where, null) + }; + return new CompoundStatement(where, body); + } + return new InlineReturnStatement(where, e); + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + if (expr == null) { + codeFinally(env, ctx, asm, null, null); + asm.add(where, opc_return); + } else { + expr.codeValue(env, ctx, asm); + codeFinally(env, ctx, asm, null, expr.type); + asm.add(where, opc_ireturn + expr.type.getTypeCodeOffset()); + } + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("return"); + if (expr != null) { + out.print(" "); + expr.print(out); + } + out.print(";"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShiftLeftExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShiftLeftExpression.java new file mode 100644 index 000000000..741882c7e --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShiftLeftExpression.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ShiftLeftExpression extends BinaryShiftExpression { + /** + * constructor + */ + public ShiftLeftExpression(long where, Expression left, Expression right) { + super(LSHIFT, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a << b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a << b); + } + + /** + * Simplify + */ + Expression simplify() { + if (right.equals(0)) { + return left; + } + if (left.equals(0)) { + return new CommaExpression(where, right, left).simplify(); + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ishl + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShiftRightExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShiftRightExpression.java new file mode 100644 index 000000000..6e4cae75a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShiftRightExpression.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ShiftRightExpression extends BinaryShiftExpression { + /** + * constructor + */ + public ShiftRightExpression(long where, Expression left, Expression right) { + super(RSHIFT, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a >> b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a >> b); + } + + /** + * Simplify + */ + Expression simplify() { + if (right.equals(0)) { + return left; + } + if (left.equals(0)) { + return new CommaExpression(where, right, left).simplify(); + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ishr + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShortExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShortExpression.java new file mode 100644 index 000000000..06fa398d2 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ShortExpression.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ShortExpression extends IntegerExpression { + /** + * Constructor + */ + public ShortExpression(long where, short value) { + super(SHORTVAL, where, Type.tShort, value); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(value + "s"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/Statement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Statement.java new file mode 100644 index 000000000..ea5632909 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Statement.java @@ -0,0 +1,327 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class Statement extends Node { + public static final Vset DEAD_END = Vset.DEAD_END; + Identifier labels[] = null; + + /** + * Constructor + */ + Statement(int op, long where) { + super(op, where); + } + + /** + * An empty statement. Its costInline is infinite. + */ + public static final Statement empty = new Statement(STAT, 0); + + /** + * The largest possible interesting inline cost value. + */ + public static final int MAXINLINECOST = + Integer.getInteger("javac.maxinlinecost", + 30).intValue(); + + /** + * Insert a bit of code at the front of a statement. + * Side-effect s2, if it is a CompoundStatement. + */ + public static Statement insertStatement(Statement s1, Statement s2) { + if (s2 == null) { + s2 = s1; + } else if (s2 instanceof CompoundStatement) { + // Do not add another level of block nesting. + ((CompoundStatement)s2).insertStatement(s1); + } else { + Statement body[] = { s1, s2 }; + s2 = new CompoundStatement(s1.getWhere(), body); + } + return s2; + } + + /** + * Set the label of a statement + */ + public void setLabel(Environment env, Expression e) { + if (e.op == IDENT) { + if (labels == null) { + labels = new Identifier[1]; + } else { + // this should almost never happen. Multiple labels on + // the same statement. But handle it gracefully. + Identifier newLabels[] = new Identifier[labels.length + 1]; + System.arraycopy(labels, 0, newLabels, 1, labels.length); + labels = newLabels; + } + labels[0] = ((IdentifierExpression)e).id; + } else { + env.error(e.where, "invalid.label"); + } + } + + /** + * Check a statement + */ + public Vset checkMethod(Environment env, Context ctx, Vset vset, Hashtable exp) { + // Set up ctx.getReturnContext() for the sake of ReturnStatement.check(). + CheckContext mctx = new CheckContext(ctx, new Statement(METHOD, 0)); + ctx = mctx; + + vset = check(env, ctx, vset, exp); + + // Check for return + if (!ctx.field.getType().getReturnType().isType(TC_VOID)) { + // In general, we suppress further error messages due to + // unreachable statements after reporting the first error + // along a flow path (using 'clearDeadEnd'). Here, we + // report an error anyway, because the end of the method + // should be unreachable despite the earlier error. The + // difference in treatment is due to the fact that, in this + // case, the error is reachability, not unreachability. + // NOTE: In addition to this subtle difference in the quality + // of the error diagnostics, this treatment is essential to + // preserve the correctness of using 'clearDeadEnd' to implement + // the special-case reachability rules for if-then and if-then-else. + if (!vset.isDeadEnd()) { + env.error(ctx.field.getWhere(), "return.required.at.end", ctx.field); + } + } + + // Simulate a return at the end. + vset = vset.join(mctx.vsBreak); + + return vset; + } + Vset checkDeclaration(Environment env, Context ctx, Vset vset, int mod, Type t, Hashtable exp) { + throw new CompilerError("checkDeclaration"); + } + + /** + * Make sure the labels on this statement do not duplicate the + * labels on any enclosing statement. Provided as a convenience + * for subclasses. + */ + protected void checkLabel(Environment env, Context ctx) { + if (labels != null) { + loop: for (int i = 0; i < labels.length; i++) { + // Make sure there is not a double label on this statement. + for (int j = i+1; j < labels.length; j++) { + if (labels[i] == labels[j]) { + env.error(where, "nested.duplicate.label", labels[i]); + continue loop; + } + } + + // Make sure no enclosing statement has the same label. + CheckContext destCtx = + (CheckContext) ctx.getLabelContext(labels[i]); + + if (destCtx != null) { + // Check to make sure the label is in not uplevel. + if (destCtx.frameNumber == ctx.frameNumber) { + env.error(where, "nested.duplicate.label", labels[i]); + } + } + } // end loop + } + } + + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + throw new CompilerError("check"); + } + + /** This is called in contexts where declarations are valid. */ + Vset checkBlockStatement(Environment env, Context ctx, Vset vset, Hashtable exp) { + return check(env, ctx, vset, exp); + } + + Vset reach(Environment env, Vset vset) { + if (vset.isDeadEnd()) { + env.error(where, "stat.not.reached"); + vset = vset.clearDeadEnd(); + } + return vset; + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + return this; + } + + /** + * Eliminate this statement, which is only possible if it has no label. + */ + public Statement eliminate(Environment env, Statement s) { + if ((s != null) && (labels != null)) { + Statement args[] = {s}; + s = new CompoundStatement(where, args); + s.labels = labels; + } + return s; + } + + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + throw new CompilerError("code"); + } + + /** + * Generate the code to call all finally's for a break, continue, or + * return statement. We must call "jsr" on all the cleanup code between + * the current context "ctx", and the destination context "stopctx". + * If 'save' isn't null, there is also a value on the top of the stack + */ + void codeFinally(Environment env, Context ctx, Assembler asm, + Context stopctx, Type save) { + Integer num = null; + boolean haveCleanup = false; // there is a finally or synchronize; + boolean haveNonLocalFinally = false; // some finally doesn't return; + + for (Context c = ctx; (c != null) && (c != stopctx); c = c.prev) { + if (c.node == null) + continue; + if (c.node.op == SYNCHRONIZED) { + haveCleanup = true; + } else if (c.node.op == FINALLY + && ((CodeContext)c).contLabel != null) { + // c.contLabel == null indicates we're in the "finally" part + haveCleanup = true; + FinallyStatement st = ((FinallyStatement)(c.node)); + if (!st.finallyCanFinish) { + haveNonLocalFinally = true; + // after hitting a non-local finally, no need generating + // further code, because it won't get executed. + break; + } + } + } + if (!haveCleanup) { + // there is no cleanup that needs to be done. Just quit. + return; + } + if (save != null) { + // This statement has a return value on the stack. + ClassDefinition def = ctx.field.getClassDefinition(); + if (!haveNonLocalFinally) { + // Save the return value in the register which should have + // been reserved. + LocalMember lf = ctx.getLocalField(idFinallyReturnValue); + num = lf.number; + asm.add(where, opc_istore + save.getTypeCodeOffset(), num); + } else { + // Pop the return value. + switch(ctx.field.getType().getReturnType().getTypeCode()) { + case TC_VOID: + break; + case TC_DOUBLE: case TC_LONG: + asm.add(where, opc_pop2); break; + default: + asm.add(where, opc_pop); break; + } + } + } + // Call each of the cleanup functions, as necessary. + for (Context c = ctx ; (c != null) && (c != stopctx) ; c = c.prev) { + if (c.node == null) + continue; + if (c.node.op == SYNCHRONIZED) { + asm.add(where, opc_jsr, ((CodeContext)c).contLabel); + } else if (c.node.op == FINALLY + && ((CodeContext)c).contLabel != null) { + FinallyStatement st = ((FinallyStatement)(c.node)); + Label label = ((CodeContext)c).contLabel; + if (st.finallyCanFinish) { + asm.add(where, opc_jsr, label); + } else { + // the code never returns, so we're done. + asm.add(where, opc_goto, label); + break; + } + } + } + // Move the return value from the register back to the stack. + if (num != null) { + asm.add(where, opc_iload + save.getTypeCodeOffset(), num); + } + } + + /* + * Return true if the statement has the given label + */ + public boolean hasLabel (Identifier lbl) { + Identifier labels[] = this.labels; + if (labels != null) { + for (int i = labels.length; --i >= 0; ) { + if (labels[i].equals(lbl)) { + return true; + } + } + } + return false; + } + + /** + * Check if the first thing is a constructor invocation + */ + public Expression firstConstructor() { + return null; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + return (Statement)clone(); + } + + public int costInline(int thresh, Environment env, Context ctx) { + return thresh; + } + + + /** + * Print + */ + void printIndent(PrintStream out, int indent) { + for (int i = 0 ; i < indent ; i++) { + out.print(" "); + } + } + public void print(PrintStream out, int indent) { + if (labels != null) { + for (int i = labels.length; --i >= 0; ) + out.print(labels[i] + ": "); + } + } + public void print(PrintStream out) { + print(out, 0); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/StringExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/StringExpression.java new file mode 100644 index 000000000..dcd31fdeb --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/StringExpression.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class StringExpression extends ConstantExpression { + String value; + + /** + * Constructor + */ + public StringExpression(long where, String value) { + super(STRINGVAL, where, Type.tString); + this.value = value; + } + + public boolean equals(String s) { + return value.equals(s); + } + public boolean isNonNull() { + return true; // string literal is never null + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_ldc, this); + } + + /** + * Get the value + */ + public Object getValue() { + return value; + } + + /** + * Hashcode + */ + public int hashCode() { + return value.hashCode() ^ 3213; + } + + /** + * Equality + */ + public boolean equals(Object obj) { + if ((obj != null) && (obj instanceof StringExpression)) { + return value.equals(((StringExpression)obj).value); + } + return false; + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("\"" + value + "\""); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/SubtractExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SubtractExpression.java new file mode 100644 index 000000000..06a484ab5 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SubtractExpression.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class SubtractExpression extends BinaryArithmeticExpression { + /** + * constructor + */ + public SubtractExpression(long where, Expression left, Expression right) { + super(SUB, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a - b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a - b); + } + Expression eval(float a, float b) { + return new FloatExpression(where, a - b); + } + Expression eval(double a, double b) { + return new DoubleExpression(where, a - b); + } + + /** + * Simplify + */ + Expression simplify() { + // Can't simplify floating point subtract because of -0.0 strangeness + if (type.inMask(TM_INTEGER)) { + if (left.equals(0)) { + return new NegativeExpression(where, right); + } + if (right.equals(0)) { + return left; + } + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_isub + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/SuperExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SuperExpression.java new file mode 100644 index 000000000..6185ec312 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SuperExpression.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class SuperExpression extends ThisExpression { + + /** + * Constructor + */ + public SuperExpression(long where) { + super(SUPER, where); + } + + /** + * Constructor for "outer.super()" + */ + public SuperExpression(long where, Expression outerArg) { + super(where, outerArg); + op = SUPER; + } + + public SuperExpression(long where, Context ctx) { + super(where, ctx); + op = SUPER; + } + + /** + * Check expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = checkCommon(env, ctx, vset, exp); + if (type != Type.tError) { + // "super" is not allowed in this context: + env.error(where, "undef.var.super", idSuper); + } + return vset; + } + + /** + * Check if the present name is part of a scoping prefix. + */ + public Vset checkAmbigName(Environment env, Context ctx, + Vset vset, Hashtable exp, + UnaryExpression loc) { + return checkCommon(env, ctx, vset, exp); + } + + /** Common code for checkValue and checkAmbigName */ + private Vset checkCommon(Environment env, Context ctx, Vset vset, Hashtable exp) { + ClassDeclaration superClass = ctx.field.getClassDefinition().getSuperClass(); + if (superClass == null) { + env.error(where, "undef.var", idSuper); + type = Type.tError; + return vset; + } + vset = super.checkValue(env, ctx, vset, exp); + type = superClass.getType(); + return vset; + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/SwitchStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SwitchStatement.java new file mode 100644 index 000000000..030c7aa00 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SwitchStatement.java @@ -0,0 +1,249 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.SwitchData; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class SwitchStatement extends Statement { + Expression expr; + Statement args[]; + + /** + * Constructor + */ + public SwitchStatement(long where, Expression expr, Statement args[]) { + super(SWITCH, where); + this.expr = expr; + this.args = args; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + CheckContext newctx = new CheckContext(ctx, this); + vset = expr.checkValue(env, newctx, reach(env, vset), exp); + Type switchType = expr.type; + + expr = convert(env, newctx, Type.tInt, expr); + + Hashtable tab = new Hashtable<>(); + boolean hasDefault = false; + // Note that vs is reset to vset.copy() on every case label. + // If the first substatement is not a case label, it is unreached. + Vset vs = DEAD_END; + + for (int i = 0 ; i < args.length ; i++) { + Statement s = args[i]; + + if (s.op == CASE) { + + vs = s.check(env, newctx, vs.join(vset.copy()), exp); + + Expression lbl = ((CaseStatement)s).expr; + if (lbl != null) { + if (lbl instanceof IntegerExpression) { + Integer Ivalue = + (Integer)(((IntegerExpression)lbl).getValue()); + int ivalue = Ivalue.intValue(); + if (tab.get(lbl) != null) { + env.error(s.where, "duplicate.label", Ivalue); + } else { + tab.put(lbl, s); + boolean overflow; + switch (switchType.getTypeCode()) { + case TC_BYTE: + overflow = (ivalue != (byte)ivalue); break; + case TC_SHORT: + overflow = (ivalue != (short)ivalue); break; + case TC_CHAR: + overflow = (ivalue != (char)ivalue); break; + default: + overflow = false; + } + if (overflow) { + env.error(s.where, "switch.overflow", + Ivalue, switchType); + } + } + } else { + // Suppose a class got an error early on during + // checking. It will set all of its members to + // have the status "ERROR". Now suppose that a + // case label refers to one of this class's + // fields. When we check the case label, the + // compiler will try to inline the FieldExpression. + // Since the expression has ERROR status, it doesn't + // inline. This means that instead of the case + // label being an IntegerExpression, it will still + // be a FieldExpression, and we will end up in this + // else block. So, before we just assume that + // the expression isn't constant, do a check to + // see if it was constant but unable to inline. + // This eliminates some spurious error messages. + // (Bug id 4067498). + if (!lbl.isConstant() || + lbl.getType() != Type.tInt) { + env.error(s.where, "const.expr.required"); + } + } + } else { + if (hasDefault) { + env.error(s.where, "duplicate.default"); + } + hasDefault = true; + } + } else { + vs = s.checkBlockStatement(env, newctx, vs, exp); + } + } + if (!vs.isDeadEnd()) { + newctx.vsBreak = newctx.vsBreak.join(vs); + } + if (hasDefault) + vset = newctx.vsBreak; + return ctx.removeAdditionalVars(vset); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + expr = expr.inlineValue(env, ctx); + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + args[i] = args[i].inline(env, ctx); + } + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + SwitchStatement s = (SwitchStatement)clone(); + s.expr = expr.copyInline(ctx); + s.args = new Statement[args.length]; + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + s.args[i] = args[i].copyInline(ctx, valNeeded); + } + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + int cost = expr.costInline(thresh, env, ctx); + for (int i = 0 ; (i < args.length) && (cost < thresh) ; i++) { + if (args[i] != null) { + cost += args[i].costInline(thresh, env, ctx); + } + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + + expr.codeValue(env, newctx, asm); + + SwitchData sw = new SwitchData(); + boolean hasDefault = false; + + for (int i = 0 ; i < args.length ; i++) { + Statement s = args[i]; + if ((s != null) && (s.op == CASE)) { + Expression e = ((CaseStatement)s).expr; + if (e != null) { + sw.add(((IntegerExpression)e).value, new Label()); + } +// JCOV + else { + hasDefault = true; + } +// end JCOV + } + } + +// JCOV + if (env.coverage()) + sw.initTableCase(); +// end JCOV + asm.add(where, opc_tableswitch, sw); + + for (int i = 0 ; i < args.length ; i++) { + Statement s = args[i]; + if (s != null) { + if (s.op == CASE) { + Expression e = ((CaseStatement)s).expr; + if (e != null) { + asm.add(sw.get(((IntegerExpression)e).value)); +// JCOV + sw.addTableCase(((IntegerExpression)e).value, s.where); +// end JCOV + } else { + asm.add(sw.getDefaultLabel()); +// JCOV + sw.addTableDefault(s.where); +// end JCOV +/* JCOV hasDefault = true; end JCOV */ + } + } else { + s.code(env, newctx, asm); + } + } + } + + if (!hasDefault) { + asm.add(sw.getDefaultLabel()); + } + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("switch ("); + expr.print(out); + out.print(") {\n"); + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + printIndent(out, indent + 1); + args[i].print(out, indent + 1); + out.print("\n"); + } + } + printIndent(out, indent); + out.print("}"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/SynchronizedStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SynchronizedStatement.java new file mode 100644 index 000000000..8152c63fa --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/SynchronizedStatement.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.TryData; +import org.glassfish.rmic.tools.asm.CatchData; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class SynchronizedStatement extends Statement { + Expression expr; + Statement body; + boolean needReturnSlot; // set by inner return statement + + /** + * Constructor + */ + public SynchronizedStatement(long where, Expression expr, Statement body) { + super(SYNCHRONIZED, where); + this.expr = expr; + this.body = body; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + CheckContext newctx = new CheckContext(ctx, this); + vset = reach(env, vset); + vset = expr.checkValue(env, newctx, vset, exp); + if (expr.type.equals(Type.tNull)) { + env.error(expr.where, "synchronized.null"); + } + expr = convert(env, newctx, Type.tClass(idJavaLangObject), expr); + vset = body.check(env, newctx, vset, exp); + return ctx.removeAdditionalVars(vset.join(newctx.vsBreak)); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (body != null) { + body = body.inline(env, ctx); + } + expr = expr.inlineValue(env, ctx); + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + SynchronizedStatement s = (SynchronizedStatement)clone(); + s.expr = expr.copyInline(ctx); + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + return s; + } + + /** + * Compute cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx){ + int cost = 1; + if (expr != null) { + cost += expr.costInline(thresh, env,ctx); + if (cost >= thresh) return cost; + } + if (body != null) { + cost += body.costInline(thresh, env,ctx); + } + return cost; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + ClassDefinition clazz = ctx.field.getClassDefinition(); + expr.codeValue(env, ctx, asm); + ctx = new Context(ctx); + + if (needReturnSlot) { + Type returnType = ctx.field.getType().getReturnType(); + LocalMember localfield = new LocalMember(0, clazz, 0, returnType, + idFinallyReturnValue); + ctx.declare(env, localfield); + Environment.debugOutput("Assigning return slot to " + localfield.number); + } + + LocalMember f1 = new LocalMember(where, clazz, 0, Type.tObject, null); + LocalMember f2 = new LocalMember(where, clazz, 0, Type.tInt, null); + Integer num1 = ctx.declare(env, f1); + Integer num2 = ctx.declare(env, f2); + + Label endLabel = new Label(); + + TryData td = new TryData(); + td.add(null); + + // lock the object + asm.add(where, opc_astore, num1); + asm.add(where, opc_aload, num1); + asm.add(where, opc_monitorenter); + + // Main body + CodeContext bodyctx = new CodeContext(ctx, this); + asm.add(where, opc_try, td); + if (body != null) { + body.code(env, bodyctx, asm); + } else { + asm.add(where, opc_nop); + } + asm.add(bodyctx.breakLabel); + asm.add(td.getEndLabel()); + + // Cleanup afer body + asm.add(where, opc_aload, num1); + asm.add(where, opc_monitorexit); + asm.add(where, opc_goto, endLabel); + + // Catch code + CatchData cd = td.getCatch(0); + asm.add(cd.getLabel()); + asm.add(where, opc_aload, num1); + asm.add(where, opc_monitorexit); + asm.add(where, opc_athrow); + + // Final body + asm.add(bodyctx.contLabel); + asm.add(where, opc_astore, num2); + asm.add(where, opc_aload, num1); + asm.add(where, opc_monitorexit); + asm.add(where, opc_ret, num2); + + asm.add(endLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("synchronized "); + expr.print(out); + out.print(" "); + if (body != null) { + body.print(out, indent); + } else { + out.print("{}"); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ThisExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ThisExpression.java new file mode 100644 index 000000000..f55849879 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ThisExpression.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ThisExpression extends Expression { + LocalMember field; + Expression implementation; + Expression outerArg; + + /** + * Constructor + */ + public ThisExpression(long where) { + super(THIS, where, Type.tObject); + } + protected ThisExpression(int op, long where) { + super(op, where, Type.tObject); + } + public ThisExpression(long where, LocalMember field) { + super(THIS, where, Type.tObject); + this.field = field; + field.readcount++; + } + public ThisExpression(long where, Context ctx) { + super(THIS, where, Type.tObject); + field = ctx.getLocalField(idThis); + field.readcount++; + } + + /** + * Constructor for "x.this()" + */ + public ThisExpression(long where, Expression outerArg) { + this(where); + this.outerArg = outerArg; + } + + public Expression getImplementation() { + if (implementation != null) + return implementation; + return this; + } + + /** + * From the 'this' in an expression of the form outer.this(...), + * or the 'super' in an expression of the form outer.super(...), + * return the "outer" expression, or null if there is none. + */ + public Expression getOuterArg() { + return outerArg; + } + + /** + * Check expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + if (ctx.field.isStatic()) { + env.error(where, "undef.var", opNames[op]); + type = Type.tError; + return vset; + } + if (field == null) { + field = ctx.getLocalField(idThis); + field.readcount++; + } + if (field.scopeNumber < ctx.frameNumber) { + // get a "this$C" copy via the current object + implementation = ctx.makeReference(env, field); + } + if (!vset.testVar(field.number)) { + env.error(where, "access.inst.before.super", opNames[op]); + } + if (field == null) { + type = ctx.field.getClassDeclaration().getType(); + } else { + type = field.getType(); + } + return vset; + } + + public boolean isNonNull() { + return true; + } + + // A 'ThisExpression' node can never appear on the LHS of an assignment in a correct + // program, but handle this case anyhow to provide a safe error recovery. + + public FieldUpdater getAssigner(Environment env, Context ctx) { + return null; + } + + public FieldUpdater getUpdater(Environment env, Context ctx) { + return null; + } + + /** + * Inline + */ + public Expression inlineValue(Environment env, Context ctx) { + if (implementation != null) + return implementation.inlineValue(env, ctx); + if (field != null && field.isInlineable(env, false)) { + Expression e = (Expression)field.getValue(env); + //System.out.println("INLINE = "+ e + ", THIS"); + if (e != null) { + e = e.copyInline(ctx); + e.type = type; // in case op==SUPER + return e; + } + } + return this; + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + if (implementation != null) + return implementation.copyInline(ctx); + ThisExpression e = (ThisExpression)clone(); + if (field == null) { + // The expression is copied into the context of a method + e.field = ctx.getLocalField(idThis); + e.field.readcount++; + } else { + e.field = field.getCurrentInlineCopy(ctx); + } + if (outerArg != null) { + e.outerArg = outerArg.copyInline(ctx); + } + return e; + } + + /** + * Code + */ + public void codeValue(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_aload, field.number); + } + + /** + * Print + */ + public void print(PrintStream out) { + if (outerArg != null) { + out.print("(outer="); + outerArg.print(out); + out.print(" "); + } + String pfx = (field == null) ? "" + : field.getClassDefinition().getName().getFlatName().getName()+"."; + pfx += opNames[op]; + out.print(pfx + "#" + ((field != null) ? field.hashCode() : 0)); + if (outerArg != null) + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/ThrowStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ThrowStatement.java new file mode 100644 index 000000000..d8b4ce7c7 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/ThrowStatement.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class ThrowStatement extends Statement { + Expression expr; + + /** + * Constructor + */ + public ThrowStatement(long where, Expression expr) { + super(THROW, where); + this.expr = expr; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + try { + vset = reach(env, vset); + expr.checkValue(env, ctx, vset, exp); + if (expr.type.isType(TC_CLASS)) { + ClassDeclaration c = env.getClassDeclaration(expr.type); + if (exp.get(c) == null) { + exp.put(c, this); + } + ClassDefinition def = c.getClassDefinition(env); + ClassDeclaration throwable = + env.getClassDeclaration(idJavaLangThrowable); + if (!def.subClassOf(env, throwable)) { + env.error(where, "throw.not.throwable", def); + } + expr = convert(env, ctx, Type.tObject, expr); + } else if (!expr.type.isType(TC_ERROR)) { + env.error(expr.where, "throw.not.throwable", expr.type); + } + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, opNames[op]); + } + CheckContext exitctx = ctx.getTryExitContext(); + if (exitctx != null) { + exitctx.vsTryExit = exitctx.vsTryExit.join(vset); + } + return DEAD_END; + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + expr = expr.inlineValue(env, ctx); + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + ThrowStatement s = (ThrowStatement)clone(); + s.expr = expr.copyInline(ctx); + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + expr.costInline(thresh, env, ctx); + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + expr.codeValue(env, ctx, asm); + asm.add(where, opc_athrow); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("throw "); + expr.print(out); + out.print(":"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/TryStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/TryStatement.java new file mode 100644 index 000000000..a9be2f950 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/TryStatement.java @@ -0,0 +1,302 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import org.glassfish.rmic.tools.asm.TryData; +import org.glassfish.rmic.tools.asm.CatchData; +import java.io.PrintStream; +import java.util.Enumeration; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class TryStatement extends Statement { + Statement body; + Statement args[]; + long arrayCloneWhere; // private note posted from MethodExpression + + /** + * Constructor + */ + public TryStatement(long where, Statement body, Statement args[]) { + super(TRY, where); + this.body = body; + this.args = args; + } + + /** + * Check statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + try { + vset = reach(env, vset); + Hashtable newexp = new Hashtable<>(); + CheckContext newctx = new CheckContext(ctx, this); + + // Check 'try' block. A variable is DA (DU) before the try + // block if it is DA (DU) before the try statement. + Vset vs = body.check(env, newctx, vset.copy(), newexp); + + // A variable is DA before a catch block if it is DA before the + // try statement. A variable is DU before a catch block if it + // is DU after the try block and before any 'break', 'continue', + // 'throw', or 'return' contained therein. That is, the variable + // is DU upon entry to the try-statement and is not assigned to + // anywhere within the try block. + Vset cvs = Vset.firstDAandSecondDU(vset, vs.copy().join(newctx.vsTryExit)); + + for (int i = 0 ; i < args.length ; i++) { + // A variable is DA (DU) after a try statement if + // it is DA (DU) after every catch block. + vs = vs.join(args[i].check(env, newctx, cvs.copy(), exp)); + } + + // Check that catch statements are actually reached + for (int i = 1 ; i < args.length ; i++) { + CatchStatement cs = (CatchStatement)args[i]; + if (cs.field == null) { + continue; + } + Type type = cs.field.getType(); + ClassDefinition def = env.getClassDefinition(type); + + for (int j = 0 ; j < i ; j++) { + CatchStatement cs2 = (CatchStatement)args[j]; + if (cs2.field == null) { + continue; + } + Type t = cs2.field.getType(); + ClassDeclaration c = env.getClassDeclaration(t); + if (def.subClassOf(env, c)) { + env.error(args[i].where, "catch.not.reached"); + break; + } + } + } + + ClassDeclaration ignore1 = env.getClassDeclaration(idJavaLangError); + ClassDeclaration ignore2 = env.getClassDeclaration(idJavaLangRuntimeException); + + // Make sure the exception is actually throw in that part of the code + for (int i = 0 ; i < args.length ; i++) { + CatchStatement cs = (CatchStatement)args[i]; + if (cs.field == null) { + continue; + } + Type type = cs.field.getType(); + if (!type.isType(TC_CLASS)) { + // CatchStatement.checkValue() will have already printed + // an error message + continue; + } + + ClassDefinition def = env.getClassDefinition(type); + + // Anyone can throw these! + if (def.subClassOf(env, ignore1) || def.superClassOf(env, ignore1) || + def.subClassOf(env, ignore2) || def.superClassOf(env, ignore2)) { + continue; + } + + // Make sure the exception is actually throw in that part of the code + boolean ok = false; + for (Enumeration e = newexp.keys() ; e.hasMoreElements() ; ) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + if (def.superClassOf(env, c) || def.subClassOf(env, c)) { + ok = true; + break; + } + } + if (!ok && arrayCloneWhere != 0 + && def.getName().toString().equals("java.lang.CloneNotSupportedException")) { + env.error(arrayCloneWhere, "warn.array.clone.supported", def.getName()); + } + + if (!ok) { + env.error(cs.where, "catch.not.thrown", def.getName()); + } + } + + // Only carry over exceptions that are not caught + for (Enumeration e = newexp.keys() ; e.hasMoreElements() ; ) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + ClassDefinition def = c.getClassDefinition(env); + boolean add = true; + for (int i = 0 ; i < args.length ; i++) { + CatchStatement cs = (CatchStatement)args[i]; + if (cs.field == null) { + continue; + } + Type type = cs.field.getType(); + if (type.isType(TC_ERROR)) + continue; + if (def.subClassOf(env, env.getClassDeclaration(type))) { + add = false; + break; + } + } + if (add) { + exp.put(c, newexp.get(c)); + } + } + // A variable is DA (DU) after a try statement if it is DA (DU) + // after the try block and after every catch block. These variables + // are represented by 'vs'. If the try statement is labelled, we + // may also exit from it (including from within a catch block) via + // a break statement. + // If there is a finally block, the Vset returned here is further + // adjusted. Note that this 'TryStatement' node will be a child of + // a 'FinallyStatement' node in that case. + return ctx.removeAdditionalVars(vs.join(newctx.vsBreak)); + } catch (ClassNotFound e) { + env.error(where, "class.not.found", e.name, opNames[op]); + return vset; + } + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (body != null) { + body = body.inline(env, new Context(ctx, this)); + } + if (body == null) { + return null; + } + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + args[i] = args[i].inline(env, new Context(ctx, this)); + } + } + return (args.length == 0) ? eliminate(env, body) : this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + TryStatement s = (TryStatement)clone(); + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + s.args = new Statement[args.length]; + for (int i = 0 ; i < args.length ; i++) { + if (args[i] != null) { + s.args[i] = args[i].copyInline(ctx, valNeeded); + } + } + return s; + } + + /** + * Compute cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx){ + + // Don't inline methods containing try statements. + // If the try statement is being inlined in order to + // inline a method that returns a value which is + // a subexpression of an expression involving the + // operand stack, then the early operands may get lost. + // This shows up as a verifier error. For example, + // in the following: + // + // public static int test() { + // try { return 2; } catch (Exception e) { return 0; } + // } + // + // System.out.println(test()); + // + // an inlined call to test() might look like this: + // + // 0 getstatic + // 3 iconst_2 + // 4 goto 9 + // 7 pop + // 8 iconst_0 + // 9 invokevirtual + // 12 return + // Exception table: + // from to target type + // 3 7 7 + // + // This fails to verify because the operand stored + // for System.out gets axed at an exception, leading to + // an inconsistent stack depth at pc=7. + // + // Note that although all code must be able to be inlined + // to implement initializers, this problem doesn't come up, + // as try statements themselves can never be expressions. + // It suffices here to make sure they are never inlined as part + // of optimization. + + return thresh; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + + TryData td = new TryData(); + for (int i = 0 ; i < args.length ; i++) { + Type t = ((CatchStatement)args[i]).field.getType(); + if (t.isType(TC_CLASS)) { + td.add(env.getClassDeclaration(t)); + } else { + td.add(t); + } + } + asm.add(where, opc_try, td); + if (body != null) { + body.code(env, newctx, asm); + } + + asm.add(td.getEndLabel()); + asm.add(where, opc_goto, newctx.breakLabel); + + for (int i = 0 ; i < args.length ; i++) { + CatchData cd = td.getCatch(i); + asm.add(cd.getLabel()); + args[i].code(env, newctx, asm); + asm.add(where, opc_goto, newctx.breakLabel); + } + + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("try "); + if (body != null) { + body.print(out, indent); + } else { + out.print(""); + } + for (int i = 0 ; i < args.length ; i++) { + out.print(" "); + args[i].print(out, indent); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/TypeExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/TypeExpression.java new file mode 100644 index 000000000..6bf9f7d6f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/TypeExpression.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class TypeExpression extends Expression { + /** + * Constructor + */ + public TypeExpression(long where, Type type) { + super(TYPE, where, type); + } + + /** + * Convert to a type + */ + Type toType(Environment env, Context ctx) { + return type; + } + + /** + * Check an expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + env.error(where, "invalid.term"); + type = Type.tError; + return vset; + } + + public Vset checkAmbigName(Environment env, Context ctx, Vset vset, Hashtable exp, + UnaryExpression loc) { + return vset; + } + + public Expression inline(Environment env, Context ctx) { + return null; + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print(type.toString()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/UnaryExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/UnaryExpression.java new file mode 100644 index 000000000..d54980b3f --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/UnaryExpression.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class UnaryExpression extends Expression { + Expression right; + + /** + * Constructor + */ + UnaryExpression(int op, long where, Type type, Expression right) { + super(op, where, type); + this.right = right; + } + + /** + * Order the expression based on precedence + */ + public Expression order() { + if (precedence() > right.precedence()) { + UnaryExpression e = (UnaryExpression)right; + right = e.right; + e.right = order(); + return e; + } + return this; + } + + /** + * Select the type of the expression + */ + void selectType(Environment env, Context ctx, int tm) { + throw new CompilerError("selectType: " + opNames[op]); + } + + /** + * Check a unary expression + */ + public Vset checkValue(Environment env, Context ctx, Vset vset, Hashtable exp) { + vset = right.checkValue(env, ctx, vset, exp); + + int tm = right.type.getTypeMask(); + selectType(env, ctx, tm); + if (((tm & TM_ERROR) == 0) && type.isType(TC_ERROR)) { + env.error(where, "invalid.arg", opNames[op]); + } + return vset; + } + + /** + * Check if constant + */ + public boolean isConstant() { + switch (op) { + case POS: + case NEG: + case BITNOT: + case NOT: + case EXPR: + case CONVERT: // generated inside of CastExpression + return right.isConstant(); + } + return false; + } + + /** + * Evaluate + */ + Expression eval(int a) { + return this; + } + Expression eval(long a) { + return this; + } + Expression eval(float a) { + return this; + } + Expression eval(double a) { + return this; + } + Expression eval(boolean a) { + return this; + } + Expression eval(String a) { + return this; + } + Expression eval() { + switch (right.op) { + case BYTEVAL: + case CHARVAL: + case SHORTVAL: + case INTVAL: + return eval(((IntegerExpression)right).value); + case LONGVAL: + return eval(((LongExpression)right).value); + case FLOATVAL: + return eval(((FloatExpression)right).value); + case DOUBLEVAL: + return eval(((DoubleExpression)right).value); + case BOOLEANVAL: + return eval(((BooleanExpression)right).value); + case STRINGVAL: + return eval(((StringExpression)right).value); + } + return this; + } + + /** + * Inline + */ + public Expression inline(Environment env, Context ctx) { + return right.inline(env, ctx); + } + public Expression inlineValue(Environment env, Context ctx) { + right = right.inlineValue(env, ctx); + try { + return eval().simplify(); + } catch (ArithmeticException e) { + // Got rid of this error message. It isn't illegal to + // have a program which does a constant division by + // zero. We return `this' to make the compiler to + // generate code here. + // (bugs 4019304, 4089107). + // + // I am not positive that this catch is ever reached. + // + // env.error(where, "arithmetic.exception"); + return this; + } + } + + /** + * Create a copy of the expression for method inlining + */ + public Expression copyInline(Context ctx) { + UnaryExpression e = (UnaryExpression)clone(); + if (right != null) { + e.right = right.copyInline(ctx); + } + return e; + } + + /** + * The cost of inlining this expression + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + right.costInline(thresh, env, ctx); + } + + /** + * Print + */ + public void print(PrintStream out) { + out.print("(" + opNames[op] + " "); + right.print(out); + out.print(")"); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/UnsignedShiftRightExpression.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/UnsignedShiftRightExpression.java new file mode 100644 index 000000000..5e2fc5610 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/UnsignedShiftRightExpression.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class UnsignedShiftRightExpression extends BinaryShiftExpression { + /** + * constructor + */ + public UnsignedShiftRightExpression(long where, Expression left, Expression right) { + super(URSHIFT, where, left, right); + } + + /** + * Evaluate + */ + Expression eval(int a, int b) { + return new IntExpression(where, a >>> b); + } + Expression eval(long a, long b) { + return new LongExpression(where, a >>> b); + } + + /** + * Simplify + */ + Expression simplify() { + if (right.equals(0)) { + return left; + } + if (left.equals(0)) { + return new CommaExpression(where, right, left).simplify(); + } + return this; + } + + /** + * Code + */ + void codeOperation(Environment env, Context ctx, Assembler asm) { + asm.add(where, opc_iushr + type.getTypeCodeOffset()); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/UplevelReference.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/UplevelReference.java new file mode 100644 index 000000000..a9e5ca5d9 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/UplevelReference.java @@ -0,0 +1,386 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.tree.*; +import org.glassfish.rmic.tools.asm.Assembler; + +/** + * A reference from one scope to another. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + */ + +public +class UplevelReference implements Constants { + /** + * The class in which the reference occurs. + */ + ClassDefinition client; + + /** + * The field being referenced. + * It is always a final argument or a final local variable. + * (An uplevel reference to a field of a class C is fetched + * through an implicit uplevel reference to C.this, which is + * an argument.) + */ + LocalMember target; + + /** + * The local variable which bears a copy of the target's value, + * for all methods of the client class. + * Its name is "this$C" for this.C or + * "val$x" for other target variables x. + *

                + * This local variable is always a constructor argument, + * and is therefore usable only in the constructor and in initializers. + * All other methods use the local field. + * @see #localField + */ + LocalMember localArgument; + + /** + * A private synthetic field of the client class which + * bears a copy of the target's value. + * The compiler tries to avoid creating it if possible. + * The field has the same name and type as the localArgument. + * @see #localArgument + */ + MemberDefinition localField; + + /** + * The next item on the references list of the client. + */ + UplevelReference next; + + /** + * constructor + */ + public UplevelReference(ClassDefinition client, LocalMember target) { + this.client = client; + this.target = target; + + // Choose a name and build a variable declaration node. + Identifier valName; + if (target.getName().equals(idThis)) { + ClassDefinition tc = target.getClassDefinition(); + // It should always be true that tc.enclosingClassOf(client). + // If it were false, the numbering scheme would fail + // to produce unique names, since we'd be trying + // to number classes which were not in the sequence + // of enclosing scopes. The next paragraph of this + // code robustly deals with that possibility, however, + // by detecting name collisions and perturbing the names. + int depth = 0; + for (ClassDefinition pd = tc; !pd.isTopLevel(); pd = pd.getOuterClass()) { + // The inner classes specification states that the name of + // a private field containing a reference to the outermost + // enclosing instance is named "this$0". That outermost + // enclosing instance is always the innermost toplevel class. + depth += 1; + } + // In this example, T1,T2,T3 are all top-level (static), + // while I4,I5,I6,I7 are all inner. Each of the inner classes + // will have a single up-level "this$N" reference to the next + // class out. Only the outermost "this$0" will refer to a + // top-level class, T3. + // + // class T1 { + // static class T2 { + // static class T3 { + // class I4 { + // class I5 { + // class I6 { + // // at this point we have these fields in various places: + // // I4 this$0; I5 this$1; I6 this$2; + // } + // } + // class I7 { + // // I4 this$0; I7 this$1; + // } + // } + // } + // } + // } + valName = Identifier.lookup(prefixThis + depth); + } else { + valName = Identifier.lookup(prefixVal + target.getName()); + } + + // Make reasonably certain that valName is unique to this client. + // (This check can be fooled by malicious naming of explicit + // constructor arguments, or of inherited fields.) + Identifier base = valName; + int tick = 0; + while (true) { + boolean failed = (client.getFirstMatch(valName) != null); + for (UplevelReference r = client.getReferences(); + r != null; r = r.next) { + if (r.target.getName().equals(valName)) { + failed = true; + } + } + if (!failed) { + break; + } + // try another name + valName = Identifier.lookup(base + "$" + (++tick)); + } + + // Build the constructor argument. + // Like "this", it wil be shared equally by all constructors of client. + localArgument = new LocalMember(target.getWhere(), + client, + M_FINAL | M_SYNTHETIC, + target.getType(), + valName); + } + + /** + * Insert self into a list of references. + * Maintain "isEarlierThan" as an invariant of the list. + * This is important (a) to maximize stability of signatures, + * and (b) to allow uplevel "this" parameters to come at the + * front of every argument list they appear in. + */ + public UplevelReference insertInto(UplevelReference references) { + if (references == null || isEarlierThan(references)) { + next = references; + return this; + } else { + UplevelReference prev = references; + while (!(prev.next == null || isEarlierThan(prev.next))) { + prev = prev.next; + } + next = prev.next; + prev.next = this; + return references; + } + } + + /** + * Tells if self precedes the other in the canonical ordering. + */ + public final boolean isEarlierThan(UplevelReference other) { + // Outer fields always come first. + if (isClientOuterField()) { + return true; + } else if (other.isClientOuterField()) { + return false; + } + + // Now it doesn't matter what the order is; use string comparison. + LocalMember target2 = other.target; + Identifier name = target.getName(); + Identifier name2 = target2.getName(); + int cmp = name.toString().compareTo(name2.toString()); + if (cmp != 0) { + return cmp < 0; + } + Identifier cname = target.getClassDefinition().getName(); + Identifier cname2 = target2.getClassDefinition().getName(); + int ccmp = cname.toString().compareTo(cname2.toString()); + return ccmp < 0; + } + + /** + * the target of this reference + */ + public final LocalMember getTarget() { + return target; + } + + /** + * the local argument for this reference + */ + public final LocalMember getLocalArgument() { + return localArgument; + } + + /** + * the field allocated in the client for this reference + */ + public final MemberDefinition getLocalField() { + return localField; + } + + /** + * Get the local field, creating one if necessary. + * The client class must not be frozen. + */ + public final MemberDefinition getLocalField(Environment env) { + if (localField == null) { + makeLocalField(env); + } + return localField; + } + + /** + * the client class + */ + public final ClassDefinition getClient() { + return client; + } + + /** + * the next reference in the client's list + */ + public final UplevelReference getNext() { + return next; + } + + /** + * Tell if this uplevel reference is the up-level "this" pointer + * of an inner class. Such references are treated differently + * than others, because they affect constructor calls across + * compilation units. + */ + public boolean isClientOuterField() { + MemberDefinition outerf = client.findOuterMember(); + return (outerf != null) && (localField == outerf); + } + + /** + * Tell if my local argument is directly available in this context. + * If not, the uplevel reference will have to be via a class field. + *

                + * This must be called in a context which is local + * to the client of the uplevel reference. + */ + public boolean localArgumentAvailable(Environment env, Context ctx) { + MemberDefinition reff = ctx.field; + if (reff.getClassDefinition() != client) { + throw new CompilerError("localArgumentAvailable"); + } + return ( reff.isConstructor() + || reff.isVariable() + || reff.isInitializer() ); + } + + /** + * Process an uplevel reference. + * The only decision to make at this point is whether + * to build a "localField" instance variable, which + * is done (lazily) when localArgumentAvailable() proves false. + */ + public void noteReference(Environment env, Context ctx) { + if (localField == null && !localArgumentAvailable(env, ctx)) { + // We need an instance variable unless client is a constructor. + makeLocalField(env); + } + } + + private void makeLocalField(Environment env) { + // Cannot alter decisions like this one at a late date. + client.referencesMustNotBeFrozen(); + int mod = M_PRIVATE | M_FINAL | M_SYNTHETIC; + localField = env.makeMemberDefinition(env, + localArgument.getWhere(), + client, null, + mod, + localArgument.getType(), + localArgument.getName(), + null, null, null); + } + + /** + * Assuming noteReference() is all taken care of, + * build an uplevel reference. + *

                + * This must be called in a context which is local + * to the client of the uplevel reference. + */ + public Expression makeLocalReference(Environment env, Context ctx) { + if (ctx.field.getClassDefinition() != client) { + throw new CompilerError("makeLocalReference"); + } + if (localArgumentAvailable(env, ctx)) { + return new IdentifierExpression(0, localArgument); + } else { + return makeFieldReference(env, ctx); + } + } + + /** + * As with makeLocalReference(), build a locally-usable reference. + * Ignore the availability of local arguments; always use a class field. + */ + public Expression makeFieldReference(Environment env, Context ctx) { + Expression e = ctx.findOuterLink(env, 0, localField); + return new FieldExpression(0, e, localField); + } + + /** + * During the inline phase, call this on a list of references + * for which the code phase will later emit arguments. + * It will make sure that any "double-uplevel" values + * needed by the callee are also present at the call site. + *

                + * If any reference is a "ClientOuterField", it is skipped + * by this method (and by willCodeArguments). This is because + */ + public void willCodeArguments(Environment env, Context ctx) { + if (!isClientOuterField()) { + ctx.noteReference(env, target); + } + + if (next != null) { + next.willCodeArguments(env, ctx); + } + } + + /** + * Code is being generated for a call to a constructor of + * the client class. Push an argument for the constructor. + */ + public void codeArguments(Environment env, Context ctx, Assembler asm, + long where, MemberDefinition conField) { + if (!isClientOuterField()) { + Expression e = ctx.makeReference(env, target); + e.codeValue(env, ctx, asm); + } + + if (next != null) { + next.codeArguments(env, ctx, asm, where, conField); + } + } + + /** + * Code is being generated for a constructor of the client class. + * Emit code which initializes the instance. + */ + public void codeInitialization(Environment env, Context ctx, Assembler asm, + long where, MemberDefinition conField) { + // If the reference is a clientOuterField, then the initialization + // code is generated in MethodExpression.makeVarInits(). + // (Fix for bug 4075063.) + if (localField != null && !isClientOuterField()) { + Expression e = ctx.makeReference(env, target); + Expression f = makeFieldReference(env, ctx); + e = new AssignExpression(e.getWhere(), f, e); + e.type = localField.getType(); + e.code(env, ctx, asm); + } + + if (next != null) { + next.codeInitialization(env, ctx, asm, where, conField); + } + } + + public String toString() { + return "[" + localArgument + " in " + client + "]"; + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/VarDeclarationStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/VarDeclarationStatement.java new file mode 100644 index 000000000..6947890ea --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/VarDeclarationStatement.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.LocalVariable; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class VarDeclarationStatement extends Statement { + LocalMember field; + Expression expr; + + /** + * Constructor + */ + public VarDeclarationStatement(long where, Expression expr) { + super(VARDECLARATION, where); + this.expr = expr; + } + public VarDeclarationStatement(long where, LocalMember field, Expression expr) { + super(VARDECLARATION, where); + this.field = field; + this.expr = expr; + } + + /** + * Check statement + */ + Vset checkDeclaration(Environment env, Context ctx, Vset vset, int mod, Type t, Hashtable exp) { + if (labels != null) { + env.error(where, "declaration.with.label", labels[0]); + } + if (field != null) { + if (ctx.getLocalClass(field.getName()) != null + && field.isInnerClass()) { + env.error(where, "local.class.redefined", field.getName()); + } + + ctx.declare(env, field); + if (field.isInnerClass()) { + ClassDefinition body = field.getInnerClass(); + try { + vset = body.checkLocalClass(env, ctx, vset, + null, null, null); + } catch (ClassNotFound ee) { + env.error(where, "class.not.found", ee.name, opNames[op]); + } + return vset; + } + vset.addVar(field.number); + return (expr != null) ? expr.checkValue(env, ctx, vset, exp) : vset; + } + + // Argument 'expr' is either an IdentifierExpression for a declaration of + // the form 'type x' or an AssignmentExpression for a declaration of the + // form 'type x = initvalue'. Note that these expressions are treated + // specially in this context, and don't have much connection to their ordinary + // meaning. + + Expression e = expr; + + if (e.op == ASSIGN) { + expr = ((AssignExpression)e).right; + e = ((AssignExpression)e).left; + } else { + expr = null; + } + + boolean declError = t.isType(TC_ERROR); + while (e.op == ARRAYACCESS) { + ArrayAccessExpression array = (ArrayAccessExpression)e; + if (array.index != null) { + env.error(array.index.where, "array.dim.in.type"); + declError = true; + } + e = array.right; + t = Type.tArray(t); + } + if (e.op == IDENT) { + Identifier id = ((IdentifierExpression)e).id; + if (ctx.getLocalField(id) != null) { + env.error(where, "local.redefined", id); + } + + field = new LocalMember(e.where, ctx.field.getClassDefinition(), mod, t, id); + ctx.declare(env, field); + + if (expr != null) { + vset = expr.checkInitializer(env, ctx, vset, t, exp); + expr = convert(env, ctx, t, expr); + field.setValue(expr); // for the sake of non-blank finals + if (field.isConstant()) { + // Keep in mind that isConstant() only means expressions + // that are constant according to the JLS. They might + // not be either constants or evaluable (eg. 1/0). + field.addModifiers(M_INLINEABLE); + } + vset.addVar(field.number); + } else if (declError) { + vset.addVar(field.number); + } else { + vset.addVarUnassigned(field.number); + } + return vset; + } + env.error(e.where, "invalid.decl"); + return vset; + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + if (field.isInnerClass()) { + ClassDefinition body = field.getInnerClass(); + body.inlineLocalClass(env); + return null; + } + + // Don't generate code for variable if unused and + // optimization is on, whether or not debugging is on + if (env.opt() && !field.isUsed()) { + return new ExpressionStatement(where, expr).inline(env, ctx); + } + + ctx.declare(env, field); + + if (expr != null) { + expr = expr.inlineValue(env, ctx); + field.setValue(expr); // for the sake of non-blank finals + if (env.opt() && (field.writecount == 0)) { + if (expr.op == IDENT) { + + // This code looks like it tests whether a final variable + // is being initialized by an identifier expression. + // Then if the identifier is a local of the same method + // it makes the final variable eligible to be inlined. + // BUT: why isn't the local also checked to make sure + // it is itself final? Unknown. + + IdentifierExpression e = (IdentifierExpression)expr; + if (e.field.isLocal() && ((ctx = ctx.getInlineContext()) != null) && + (((LocalMember)e.field).number < ctx.varNumber)) { + //System.out.println("FINAL IDENT = " + field + " in " + ctx.field); + field.setValue(expr); + field.addModifiers(M_INLINEABLE); + + // The two lines below used to elide the declaration + // of inlineable variables, on the theory that there + // wouldn't be any references. But this breaks the + // translation of nested classes, which might refer to + // the variable. + + //expr = null; + //return null; + } + } + if (expr.isConstant() || (expr.op == THIS) || (expr.op == SUPER)) { + //System.out.println("FINAL = " + field + " in " + ctx.field); + field.setValue(expr); + field.addModifiers(M_INLINEABLE); + + // The two lines below used to elide the declaration + // of inlineable variables, on the theory that there + // wouldn't be any references. But this breaks the + // translation of nested classes, which might refer to + // the variable. Fix for 4073244. + + //expr = null; + //return null; + } + } + } + return this; + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + VarDeclarationStatement s = (VarDeclarationStatement)clone(); + if (expr != null) { + s.expr = expr.copyInline(ctx); + } + return s; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + if (field != null && field.isInnerClass()) { + return thresh; // don't copy classes... + } + return (expr != null) ? expr.costInline(thresh, env, ctx) : 0; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + if (expr != null && !expr.type.isType(TC_VOID)) { + // The two lines of code directly following this comment used + // to be in the opposite order. They were switched so that + // lines like the following: + // + // int j = (j = 4); + // + // will compile correctly. (Constructions like the above are + // legal. JLS 14.3.2 says that the scope of a local variable + // includes its own initializer.) It is important that we + // declare `field' before we code `expr', because otherwise + // situations can arise where `field' thinks it is assigned + // a local variable slot that is, in actuality, assigned to + // an entirely different variable. (Bug id 4076729) + ctx.declare(env, field); + expr.codeValue(env, ctx, asm); + + asm.add(where, opc_istore + field.getType().getTypeCodeOffset(), + new LocalVariable(field, field.number)); + } else { + ctx.declare(env, field); + if (expr != null) { + // an initial side effect, rather than an initial value + expr.code(env, ctx, asm); + } + } + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + out.print("local "); + if (field != null) { + out.print(field + "#" + field.hashCode()); + if (expr != null) { + out.print(" = "); + expr.print(out); + } + } else { + expr.print(out); + out.print(";"); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/Vset.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Vset.java new file mode 100644 index 000000000..aae01c99a --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/Vset.java @@ -0,0 +1,503 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public final +class Vset implements Constants { + long vset; // DA bits for first 64 variables + long uset; // DU bits for first 64 variables + + // The extension array is interleaved, consisting of alternating + // blocks of 64 DA bits followed by 64 DU bits followed by 64 DA + // bits, and so on. + + long x[]; // extension array for more bits + + // An infinite vector of zeroes or an infinite vector of ones is + // represented by a special value of the extension array. + // + // IMPORTANT: The condition 'this.x == fullX' is used as a marker for + // unreachable code, i.e., for a dead-end. We maintain the invariant + // that (this.x != fullX || (this.vset == -1 && this.uset == -1)). + // A dead-end has the peculiar property that all variables are both + // definitely assigned and definitely unassigned. We always force this + // condition to hold, even when the normal bitvector operations performed + // during DA/DU analysis would produce a different result. This supresses + // reporting of DA/DU errors in unreachable code. + + static final long emptyX[] = new long[0]; // all zeroes + static final long fullX[] = new long[0]; // all ones + + // For more thorough testing of long vset support, it is helpful to + // temporarily redefine this value to a smaller number, such as 1 or 2. + + static final int VBITS = 64; // number of bits in vset (uset) + + /** + * This is the Vset which reports all vars assigned and unassigned. + * This impossibility is degenerately true exactly when + * control flow cannot reach this point. + */ + + // We distinguish a canonical dead-end value generated initially for + // statements that do not complete normally, making the next one unreachable. + // Once an unreachable statement is reported, a non-canonical dead-end value + // is used for subsequent statements in order to suppress redundant error + // messages. + + static final Vset DEAD_END = new Vset(-1, -1, fullX); + + /** + * Create an empty Vset. + */ + public Vset() { + this.x = emptyX; + } + + private Vset(long vset, long uset, long x[]) { + this.vset = vset; + this.uset = uset; + this.x = x; + } + + /** + * Create an copy of the given Vset. + * (However, DEAD_END simply returns itself.) + */ + public Vset copy() { + if (this == DEAD_END) { + return this; + } + Vset vs = new Vset(vset, uset, x); + if (x.length > 0) { + vs.growX(x.length); // recopy the extension vector + } + return vs; + } + + private void growX(int length) { + long newX[] = new long[length]; + long oldX[] = x; + for (int i = 0; i < oldX.length; i++) { + newX[i] = oldX[i]; + } + x = newX; + } + + /** + * Ask if this is a vset for a dead end. + * Answer true only for the canonical dead-end, DEAD_END. + * A canonical dead-end is produced only as a result of + * a statement that cannot complete normally, as specified + * by the JLS. Due to the special-case rules for if-then + * and if-then-else, this may fail to detect actual unreachable + * code that could easily be identified. + */ + + public boolean isDeadEnd() { + return (this == DEAD_END); + } + + /** + * Ask if this is a vset for a dead end. + * Answer true for any dead-end. + * Since 'clearDeadEnd' has no effect on this predicate, + * if-then and if-then-else are handled in the more 'obvious' + * and precise way. This predicate is to be preferred for + * dead code elimination purposes. + * (Presently used in workaround for bug 4173473 in MethodExpression.java) + */ + public boolean isReallyDeadEnd() { + return (x == fullX); + } + + /** + * Replace canonical DEAD_END with a distinct but + * equivalent Vset. The bits are unaltered, but + * the result does not answer true to 'isDeadEnd'. + *

                + * Used mostly for error recovery, but see + * 'IfStatement.check', where it is used to + * implement the special-case treatment of + * statement reachability for such statements. + */ + public Vset clearDeadEnd() { + if (this == DEAD_END) { + return new Vset(-1, -1, fullX); + } + return this; + } + + /** + * Ask if a var is definitely assigned. + */ + public boolean testVar(int varNumber) { + long bit = (1L << varNumber); + if (varNumber >= VBITS) { + int i = (varNumber / VBITS - 1) * 2; + if (i >= x.length) { + return (x == fullX); + } + return (x[i] & bit) != 0; + } else { + return (vset & bit) != 0; + } + } + + /** + * Ask if a var is definitely un-assigned. + * (This is not just the negation of testVar: + * It's possible for neither to be true.) + */ + public boolean testVarUnassigned(int varNumber) { + long bit = (1L << varNumber); + if (varNumber >= VBITS) { + // index "uset" extension + int i = ((varNumber / VBITS - 1) * 2) + 1; + if (i >= x.length) { + return (x == fullX); + } + return (x[i] & bit) != 0; + } else { + return (uset & bit) != 0; + } + } + + /** + * Note that a var is definitely assigned. + * (Side-effecting.) + */ + public Vset addVar(int varNumber) { + if (x == fullX) { + return this; + } + + // gen DA, kill DU + + long bit = (1L << varNumber); + if (varNumber >= VBITS) { + int i = (varNumber / VBITS - 1) * 2; + if (i >= x.length) { + growX(i+1); + } + x[i] |= bit; + if (i+1 < x.length) { + x[i+1] &=~ bit; + } + } else { + vset |= bit; + uset &=~ bit; + } + return this; + } + + /** + * Note that a var is definitely un-assigned. + * (Side-effecting.) + */ + public Vset addVarUnassigned(int varNumber) { + if (x == fullX) { + return this; + } + + // gen DU, kill DA + + long bit = (1L << varNumber); + if (varNumber >= VBITS) { + // index "uset" extension + int i = ((varNumber / VBITS - 1) * 2) + 1; + if (i >= x.length) { + growX(i+1); + } + x[i] |= bit; + x[i-1] &=~ bit; + } else { + uset |= bit; + vset &=~ bit; + } + return this; + } + + /** + * Retract any assertion about the var. + * This operation is ineffective on a dead-end. + * (Side-effecting.) + */ + public Vset clearVar(int varNumber) { + if (x == fullX) { + return this; + } + long bit = (1L << varNumber); + if (varNumber >= VBITS) { + int i = (varNumber / VBITS - 1) * 2; + if (i >= x.length) { + return this; + } + x[i] &=~ bit; + if (i+1 < x.length) { + x[i+1] &=~ bit; + } + } else { + vset &=~ bit; + uset &=~ bit; + } + return this; + } + + /** + * Join with another vset. This is set intersection. + * (Side-effecting.) + */ + public Vset join(Vset other) { + + // Return a dead-end if both vsets are dead-ends. + // Return the canonical DEAD_END only if both vsets + // are the canonical DEAD_END. Otherwise, an incoming + // dead-end vset has already produced an error message, + // and is now assumed to be reachable. + if (this == DEAD_END) { + return other.copy(); + } + if (other == DEAD_END) { + return this; + } + if (x == fullX) { + return other.copy(); + } + if (other.x == fullX) { + return this; + } + + // DA = DA intersection DA + // DU = DU intersection DU + + vset &= other.vset; + uset &= other.uset; + + if (other.x == emptyX) { + x = emptyX; + } else { + // ASSERT(otherX.length > 0); + long otherX[] = other.x; + int selfLength = x.length; + int limit = (otherX.length < selfLength) ? otherX.length : selfLength; + for (int i = 0; i < limit; i++) { + x[i] &= otherX[i]; + } + // If self is longer than other, all remaining + // bits are implicitly 0. In the result, then, + // the remaining DA and DU bits are cleared. + for (int i = limit; i < selfLength; i++) { + x[i] = 0; + } + } + return this; + } + + /** + * Add in the definite assignment bits of another vset, + * but join the definite unassignment bits. This unusual + * operation is used only for 'finally' blocks. The + * original vset 'this' is destroyed by this operation. + * (Part of fix for 4068688.) + */ + + public Vset addDAandJoinDU(Vset other) { + + // Return a dead-end if either vset is a dead end. + // If either vset is the canonical DEAD_END, the + // result is also the canonical DEAD_END. + if (this == DEAD_END) { + return this; + } + if (other == DEAD_END) { + return other; + } + if (x == fullX) { + return this; + } + if (other.x == fullX) { + return other.copy(); + } + + // DA = DA union DA' + // DU = (DU intersection DU') - DA' + + vset = vset | other.vset; + uset = (uset & other.uset) & ~other.vset; + + int selfLength = x.length; + long otherX[] = other.x; + int otherLength = otherX.length; + + if (otherX != emptyX) { + // ASSERT(otherX.length > 0); + if (otherLength > selfLength) { + growX(otherLength); + } + int i = 0; + while (i < otherLength) { + x[i] |= otherX[i]; + i++; + if (i == otherLength) break; + x[i] = ((x[i] & otherX[i]) & ~otherX[i-1]); + i++; + } + } + // If self is longer than other, all remaining + // bits are implicitly 0. In the result, then, + // the remaining DA bits are left unchanged, and + // the DU bits are all cleared. First, align + // index to the next block of DU bits (odd index). + for (int i = (otherLength | 1); i < selfLength; i += 2) { + x[i] = 0; + } + return this; + } + + + /** + * Construct a vset consisting of the DA bits of the first argument + * and the DU bits of the second argument. This is a higly unusual + * operation, as it implies a case where the flowgraph for DA analysis + * differs from that for DU analysis. It is only needed for analysing + * 'try' blocks. The result is a dead-end iff the first argument is + * dead-end. (Part of fix for 4068688.) + */ + + public static Vset firstDAandSecondDU(Vset sourceDA, Vset sourceDU) { + + // Note that reachability status is received via 'sourceDA' only! + // This is a consequence of the fact that reachability and DA + // analysis are performed on an identical flow graph, whereas the + // flowgraph for DU analysis differs in the case of a 'try' statement. + if (sourceDA.x == fullX) { + return sourceDA.copy(); + } + + long sourceDAx[] = sourceDA.x; + int lenDA = sourceDAx.length; + long sourceDUx[] = sourceDU.x; + int lenDU = sourceDUx.length; + int limit = (lenDA > lenDU) ? lenDA : lenDU; + long x[] = emptyX; + + if (limit > 0) { + x = new long[limit]; + for (int i = 0; i < lenDA; i += 2) { + x[i] = sourceDAx[i]; + } + for (int i = 1; i < lenDU; i += 2) { + x[i] = sourceDUx[i]; + } + } + + return new Vset(sourceDA.vset, sourceDU.uset, x); + } + + /** + * Remove variables from the vset that are no longer part of + * a context. Zeroes are stored past varNumber. + * (Side-effecting.)

                + * However, if this is a dead end, keep it so. + * That is, leave an infinite tail of bits set. + */ + public Vset removeAdditionalVars(int varNumber) { + if (x == fullX) { + return this; + } + long bit = (1L << varNumber); + if (varNumber >= VBITS) { + int i = (varNumber / VBITS - 1) * 2; + if (i < x.length) { + x[i] &= (bit - 1); + if (++i < x.length) { + x[i] &= (bit - 1); // do the "uset" extension also + } + while (++i < x.length) { + x[i] = 0; + } + } + } else { + if (x.length > 0) { + x = emptyX; + } + vset &= (bit - 1); + uset &= (bit - 1); + } + return this; + } + + /** + * Return one larger than the highest bit set. + */ + public int varLimit() { + long vset; + int result; + scan: { + for (int i = (x.length / 2) * 2; i >= 0; i -= 2) { + if (i == x.length) continue; // oops + vset = x[i]; + if (i+1 < x.length) { + vset |= x[i+1]; // check the "uset" also + } + if (vset != 0) { + result = (i/2 + 1) * VBITS; + break scan; + } + } + vset = this.vset; + vset |= this.uset; // check the "uset" also + if (vset != 0) { + result = 0; + break scan; + } else { + return 0; + } + } + while (vset != 0) { + result += 1; + vset >>>= 1; + } + return result; + } + + public String toString() { + if (this == DEAD_END) + return "{DEAD_END}"; + StringBuilder sb = new StringBuilder("{"); + int maxVar = VBITS * (1 + (x.length+1)/2); + for (int i = 0; i < maxVar; i++) { + if (!testVarUnassigned(i)) { + if (sb.length() > 1) { + sb.append(' '); + } + sb.append(i); + if (!testVar(i)) { + sb.append('?'); // not definitely unassigned + } + } + } + if (x == fullX) { + sb.append("...DEAD_END"); + } + sb.append('}'); + return sb.toString(); + } + +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/tree/WhileStatement.java b/rmic/src/main/java/org/glassfish/rmic/tools/tree/WhileStatement.java new file mode 100644 index 000000000..a07728c40 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/tree/WhileStatement.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 1994, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.tree; + +import org.glassfish.rmic.tools.java.*; +import org.glassfish.rmic.tools.asm.Assembler; +import org.glassfish.rmic.tools.asm.Label; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public +class WhileStatement extends Statement { + Expression cond; + Statement body; + + /** + * Constructor + */ + public WhileStatement(long where, Expression cond, Statement body) { + super(WHILE, where); + this.cond = cond; + this.body = body; + } + + /** + * Check a while statement + */ + Vset check(Environment env, Context ctx, Vset vset, Hashtable exp) { + checkLabel(env, ctx); + CheckContext newctx = new CheckContext(ctx, this); + // remember what was unassigned on entry + Vset vsEntry = vset.copy(); + // check the condition. Determine which variables have values if + // it returns true or false. + ConditionVars cvars = + cond.checkCondition(env, newctx, reach(env, vset), exp); + cond = convert(env, newctx, Type.tBoolean, cond); + // check the body, given that the condition returned true. + vset = body.check(env, newctx, cvars.vsTrue, exp); + vset = vset.join(newctx.vsContinue); + // make sure the back-branch fits the entry of the loop + ctx.checkBackBranch(env, this, vsEntry, vset); + // Exit the while loop by testing false or getting a break statement + vset = newctx.vsBreak.join(cvars.vsFalse); + return ctx.removeAdditionalVars(vset); + } + + /** + * Inline + */ + public Statement inline(Environment env, Context ctx) { + ctx = new Context(ctx, this); + cond = cond.inlineValue(env, ctx); + if (body != null) { + body = body.inline(env, ctx); + } + return this; + } + + /** + * The cost of inlining this statement + */ + public int costInline(int thresh, Environment env, Context ctx) { + return 1 + cond.costInline(thresh, env, ctx) + + ((body != null) ? body.costInline(thresh, env, ctx) : 0); + } + + /** + * Create a copy of the statement for method inlining + */ + public Statement copyInline(Context ctx, boolean valNeeded) { + WhileStatement s = (WhileStatement)clone(); + s.cond = cond.copyInline(ctx); + if (body != null) { + s.body = body.copyInline(ctx, valNeeded); + } + return s; + } + + /** + * Code + */ + public void code(Environment env, Context ctx, Assembler asm) { + CodeContext newctx = new CodeContext(ctx, this); + + asm.add(where, opc_goto, newctx.contLabel); + + Label l1 = new Label(); + asm.add(l1); + + if (body != null) { + body.code(env, newctx, asm); + } + + asm.add(newctx.contLabel); + cond.codeBranch(env, newctx, asm, l1, true); + asm.add(newctx.breakLabel); + } + + /** + * Print + */ + public void print(PrintStream out, int indent) { + super.print(out, indent); + out.print("while "); + cond.print(out); + if (body != null) { + out.print(" "); + body.print(out, indent); + } else { + out.print(";"); + } + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/util/CommandLine.java b/rmic/src/main/java/org/glassfish/rmic/tools/util/CommandLine.java new file mode 100644 index 000000000..5f331b6e4 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/util/CommandLine.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.util; + +import java.io.IOException; +import java.io.Reader; +import java.io.FileReader; +import java.io.BufferedReader; +import java.io.StreamTokenizer; +import java.util.List; +import java.util.ArrayList; + +/** + * Various utility methods for processing Java tool command line arguments. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + */ +public class CommandLine { + /** + * Process Win32-style command files for the specified command line + * arguments and return the resulting arguments. A command file argument + * is of the form '@file' where 'file' is the name of the file whose + * contents are to be parsed for additional arguments. The contents of + * the command file are parsed using StreamTokenizer and the original + * '@file' argument replaced with the resulting tokens. Recursive command + * files are not supported. The '@' character itself can be quoted with + * the sequence '@@'. + */ + public static String[] parse(String[] args) + throws IOException + { + ArrayList newArgs = new ArrayList<>(args.length); + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + if (arg.length() > 1 && arg.charAt(0) == '@') { + arg = arg.substring(1); + if (arg.charAt(0) == '@') { + newArgs.add(arg); + } else { + loadCmdFile(arg, newArgs); + } + } else { + newArgs.add(arg); + } + } + return newArgs.toArray(new String[newArgs.size()]); + } + + private static void loadCmdFile(String name, List args) + throws IOException + { + Reader r = new BufferedReader(new FileReader(name)); + StreamTokenizer st = new StreamTokenizer(r); + st.resetSyntax(); + st.wordChars(' ', 255); + st.whitespaceChars(0, ' '); + st.commentChar('#'); + st.quoteChar('"'); + st.quoteChar('\''); + while (st.nextToken() != StreamTokenizer.TT_EOF) { + args.add(st.sval); + } + r.close(); + } +} diff --git a/rmic/src/main/java/org/glassfish/rmic/tools/util/ModifierFilter.java b/rmic/src/main/java/org/glassfish/rmic/tools/util/ModifierFilter.java new file mode 100644 index 000000000..46d353587 --- /dev/null +++ b/rmic/src/main/java/org/glassfish/rmic/tools/util/ModifierFilter.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.util; + +import org.glassfish.rmic.tools.java.*; + + +/** + * A class whose instances are filters over Modifier bits. + * Filtering is done by returning boolean values. + * Classes, methods and fields can be filtered, or filtering + * can be done directly on modifier bits. + * + * WARNING: The contents of this source file are not part of any + * supported API. Code that depends on them does so at its own risk: + * they are subject to change or removal without notice. + * + * @see java.lang.reflect.Modifier + * @author Robert Field + */ + +public +class ModifierFilter extends java.lang.reflect.Modifier { + + /** + * Package private access. + * A "pseudo-" modifier bit that can be used in the + * constructors of this class to specify package private + * access. This is needed since there is no Modifier.PACKAGE. + */ + public static final long PACKAGE = 0x8000000000000000L; + + /** + * All access modifiers. + * A short-hand set of modifier bits that can be used in the + * constructors of this class to specify all access modifiers, + * Same as PRIVATE | PROTECTED | PUBLIC | PACKAGE. + */ + public static final long ALL_ACCESS = + PRIVATE | PROTECTED | PUBLIC | PACKAGE; + + private long oneOf; + private long must; + private long cannot; + + private static final int ACCESS_BITS = PRIVATE | PROTECTED | PUBLIC; + + /** + * Constructor - Specify a filter. + * + * @param oneOf If zero, everything passes the filter. + * If non-zero, at least one of the specified + * bits must be on in the modifier bits to + * pass the filter. + */ + public + ModifierFilter(long oneOf) { + this(oneOf, 0, 0); + } + + /** + * Constructor - Specify a filter. + * For example, the filter below will only pass synchronized + * methods that are private or package private access and are + * not native or static. + *

                +     * ModifierFilter(  Modifier.PRIVATE | ModifierFilter.PACKAGE,
                +     *                  Modifier.SYNCHRONIZED,
                +     *                  Modifier.NATIVE | Modifier.STATIC)
                +     * 

                + * Each of the three arguments must either be + * zero or the or'ed combination of the bits specified in the + * class Modifier or this class. During filtering, these values + * are compared against the modifier bits as follows: + * + * @param oneOf If zero, ignore this argument. + * If non-zero, at least one of the bits must be on. + * @param must All bits specified must be on. + * @param cannot None of the bits specified can be on. + */ + public + ModifierFilter(long oneOf, long must, long cannot) { + this.oneOf = oneOf; + this.must = must; + this.cannot = cannot; + } + + /** + * Filter on modifier bits. + * + * @param modifierBits Bits as specified in the Modifier class + * + * @return Whether the modifierBits pass this filter. + */ + public boolean checkModifier(int modifierBits) { + // Add in the "pseudo-" modifier bit PACKAGE, if needed + long fmod = ((modifierBits & ACCESS_BITS) == 0) ? + modifierBits | PACKAGE : + modifierBits; + return ((oneOf == 0) || ((oneOf & fmod) != 0)) && + ((must & fmod) == must) && + ((cannot & fmod) == 0); + } + + /** + * Filter a MemberDefinition. + * + * @param field A MemberDefinition + * + * @return Whether the modifier of the field + * passes this filter. + * + * @see org.glassfish.rmic.tools.MemberDefinition + */ + public boolean checkMember(MemberDefinition field) { + return checkModifier(field.getModifiers()); + } + + /** + * Filter a ClassDefinition. + * + * @param cdef A ClassDefinition + * + * @return Whether the modifier of the class + * passes this filter. + * + * @see org.glassfish.rmic.tools.ClassDefinition + */ + public boolean checkClass(ClassDefinition cdef) { + return checkModifier(cdef.getModifiers()); + } + +} // end ModifierFilter diff --git a/rmic/src/main/java/sun/rmi/rmic/Main.java b/rmic/src/main/java/sun/rmi/rmic/Main.java new file mode 100644 index 000000000..58211a20b --- /dev/null +++ b/rmic/src/main/java/sun/rmi/rmic/Main.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.io.OutputStream; + +/** + * Legacy main class for "rmic" program, allowing the old class name to be used to run it. + */ +public class Main extends org.glassfish.rmic.Main { + + /** + * Constructor. + */ + public Main(OutputStream out, String program) { + super(out, program); + } + + /** + * Main program + */ + public static void main(String argv[]) { + Main compiler = new Main(System.out, "rmic"); + System.exit(compiler.compile(argv) ? 0 : 1); + } +} diff --git a/rmic/src/main/resources/org/glassfish/rmic/resources/rmic.properties b/rmic/src/main/resources/org/glassfish/rmic/resources/rmic.properties new file mode 100644 index 000000000..9909084e6 --- /dev/null +++ b/rmic/src/main/resources/org/glassfish/rmic/resources/rmic.properties @@ -0,0 +1,196 @@ +# +# Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1998 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# To add a generator org.glassfish.rmic.Foo which is invoked via the -foo option: +# +# 1. Add "foo" to generator.args list. +# 2. Add line: generator.class.foo=org.glassfish.rmic.Foo +# 3. Update rmic.usage string to include new arguments. + +# For each available generator, list the command line argument used +# to invoke it. The value can be a single item or a comma separated +# list. + +generator.args=iiop,idl,xprint + +# For each generator, specify the class to invoke, using the following +# syntax: +# +# generator.class.{arg}=fullClassName +# +# The 'default' entry is required and will be used if none of the args +# specified in generator.args is passed. Note that {arg} is compared +# using String.equalsIgnoreCase(). + +generator.class.default=org.glassfish.rmic.RMIGenerator + +generator.class.iiop=org.glassfish.rmic.iiop.StubGenerator +generator.class.idl=org.glassfish.rmic.iiop.IDLGenerator +generator.class.xprint=org.glassfish.rmic.iiop.PrintGenerator + +# If a generator needs a BatchEnvironment other than +# org.glassfish.rmic.BatchEnvironment, specify it as follows: +# +# generator.env.{arg}=fullClassName + +generator.env.iiop=org.glassfish.rmic.iiop.BatchEnvironment +generator.env.idl=org.glassfish.rmic.iiop.BatchEnvironment +generator.env.xprint=org.glassfish.rmic.iiop.BatchEnvironment + +rmic.usage=Usage: {0} \ +\n\ +\nwhere includes:\ +\n -keep Do not delete intermediate generated source files\ +\n -keepgenerated (same as "-keep")\ +\n -iiop Create stubs for IIOP. When present, also includes:\ +\n\ +\n -always Create stubs even when they appear current\ +\n -alwaysgenerate (same as "-always")\ +\n -nolocalstubs Do not create stubs optimized for same process\ +\n\ +\n -idl Create IDL. When present, also includes:\ +\n\ +\n -noValueMethods Do not generate methods for valuetypes \ +\n -always Create IDL even when it appears current\ +\n -alwaysgenerate (same as "-always")\ +\n\ +\n -g Generate debugging info\ +\n -nowarn Generate no warnings\ +\n -nowrite Do not write compiled classes to the file system\ +\n -verbose Output messages about what the compiler is doing\ +\n -classpath Specify where to find input class files\ +\n -bootclasspath Override location of bootstrap class files\ +\n -d Specify where to place generated class files\ +\n -J Pass argument to the java interpreter\ +\n + +# +# Generic Messages +# + +rmic.cant.read=Can''t read: {0} +rmic.cant.write=Can''t write: {0} +rmic.option.unsupported=The {0} option is no longer supported. +rmic.option.unimplemented=The {0} option is not yet implemented. +rmic.option.already.seen=The {0} option may be specified no more than once. +rmic.option.requires.argument=The {0} option requires an argument. +rmic.no.such.directory=The {0} directory does not exist. +rmic.no.such.option={0} is an invalid option or argument. +rmic.wrote=[wrote {0}] +rmic.errors={0} errors +rmic.1error=1 error +rmic.warnings={0} warnings +rmic.1warning=1 warning +rmic.done_in=[done in {0} ms] +rmic.no.memory=\ + The compiler has run out of memory. Consider using the "-J-Xmx" command line option to increase the maximum heap size. +rmic.stack.overflow=\ + The compiler has run out of stack space. Consider using the "-J-Xss" command line option to increase the memory allocated for the Java stack. +rmic.class.not.found=\ + Class {0} not found. +rmic.missing.property=Missing property generator.class.{0} +rmic.cannot.instantiate=Cannot instantiate class {0} +rmic.cannot.use.both=Cannot use both {0} and {1} +rmic.resource.not.found={0} not found. +rmic.no.output.dir=\ + Cannot find suitable output directory for {0}. Use the -d option to specify a root directory. +rmic.cannot.create.dir=\ + Cannot create output directory {0}. + +# +# JRMP Messages +# + +rmic.cant.make.stubs.for.interface=\ + {0} is an interface; stubs are needed only for remote object classes. +rmic.must.implement.remote=\ + Class {0} does not implement an interface that extends java.rmi.Remote; only remote objects need stubs and skeletons. +rmic.must.implement.remote.directly=\ + Stubs are only needed for classes that directly implement an interface that extends java.rmi.Remote; class {0} does not directly implement a remote interface. +rmic.must.throw.remoteexception=\ + {0} is not a valid remote interface: method {1} must throw java.rmi.RemoteException. +rmic.must.only.throw.exception=\ + Method {0} is not a valid remote method implementation because it throws {1}; implementations of remote methods may only throw java.lang.Exception or its subclasses. +warn.rmic.tie.found=\ + An IIOP "tie" exists for class {0}:\ + \n {1}\ + \nIf you use PortableRemoteObject.exportObject, you should remove this file; otherwise, your server object will be exported to IIOP rather than to JRMP. +rmic.jrmp.not.supported=\ + Warning: generation and use of skeletons and static stubs for JRMP\ + \nis no longer supported by this tool. Skeletons are unnecessary, and static stubs have\ + \nbeen superseded by dynamically generated stubs. Use the built-in rmic tool in JDK 1.8 or earlier\ + \nif you have not yet migrated. + +# +# RMI-IIOP Messages +# + +rmic.generated=[generated {0} in {1} ms] +rmic.previously.generated=[previously generated file {0} is current] +warn.rmic.member.not.mapped=\ + Data member {0} of class {1} was not mapped to IDL. + +rmic.iiop.constraint.1=\ + {0} is not a valid interface: does not inherit from java.rmi.Remote. +rmic.iiop.constraint.2=\ + serialPersistentFields array of class {0} is invalid: references non-existent members. +rmic.iiop.constraint.3=\ + {0} is not a valid remote interface: {1} is not a valid primitive or String constant. +rmic.iiop.constraint.4=\ + {0} is not a valid value: serialPersistentFields must be private static final. +rmic.iiop.constraint.5=\ + {0} is not a valid remote interface: method {1} must throw RemoteException or a superclass of RemoteException. +rmic.iiop.constraint.6=\ + {0} is not a valid remote interface: inherited interfaces {1} both declare method {2}. +rmic.iiop.constraint.7=\ + {0} is not a valid type: {1} differ only in case. +rmic.iiop.constraint.8=\ + {0} is not a valid remote implementation: has no remote interfaces. +rmic.iiop.constraint.9=\ + serialPersistentFields array member {0} of class {1} is invalid: type does not match declared member. +rmic.iiop.constraint.10=\ + {0} is not a valid value: implements java.rmi.Remote. +rmic.iiop.constraint.11=\ + {0} is not a valid value: does not implement java.io.Serializable. +rmic.iiop.constraint.12=\ + {0} is not a valid value: invalid parent. +rmic.iiop.constraint.13=\ + {0} is not a valid interface: the idl name for method {1} conflicts with another method. +rmic.iiop.constraint.14=\ + {0} is not a valid abstract interface: not an interface. +rmic.iiop.constraint.15=\ + {0} is not a valid abstract interface: implements java.rmi.Remote. +rmic.iiop.constraint.16=\ + {0} is not a valid remote interface: not an interface. +rmic.iiop.constraint.17=\ + {0} is not a valid remote implementation: not a class. +rmic.iiop.constraint.18=\ + {0} is not a valid interface: method {1} may not pass an exception which implements org.omg.CORBA.portable.IDLEntity. +rmic.iiop.constraint.19=\ + {0} is not a valid interface: the idl name for constant {1} conflicts with another constant. +rmic.iiop.constraint.20=\ + {0} is not a valid class: the idl name for member {1} conflicts with another member. +rmic.iiop.constraint.21=\ + {0} is a remote implementation class and cannot be used as a method argument or return type in {1}. +rmic.iiop.constraint.22=\ + Internal failure: (Method) exception {0} not a class type. +rmic.iiop.constraint.23=\ + Internal failure: (Method) caught null pointer exception for {0}. +rmic.iiop.constraint.24=\ + Class {0} contains an invalid return type. +rmic.iiop.constraint.25=\ + Class {0} contains an invalid argument type in method {1}. +rmic.iiop.constraint.26=\ + Could not compile {0}. +rmic.iiop.constraint.27=\ + Could not load class {0}. +rmic.iiop.constraint.28=\ + {0} is a remote implementation class and cannot be used as a data member in {1}. diff --git a/rmic/src/main/resources/org/glassfish/rmic/resources/rmic_ja.properties b/rmic/src/main/resources/org/glassfish/rmic/resources/rmic_ja.properties new file mode 100644 index 000000000..b21b71815 --- /dev/null +++ b/rmic/src/main/resources/org/glassfish/rmic/resources/rmic_ja.properties @@ -0,0 +1,128 @@ +# +# Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1998 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# To add a generator org.glassfish.rmic.Foo which is invoked via the -foo option: +# +# 1. Add "foo" to generator.args list. +# 2. Add line: generator.class.foo=org.glassfish.rmic.Foo +# 3. Update rmic.usage string to include new arguments. + +# For each available generator, list the command line argument used +# to invoke it. The value can be a single item or a comma separated +# list. + +generator.args=v1.1,vcompat,v1.2,iiop,idl,xprint + +# For each generator, specify the class to invoke, using the following +# syntax: +# +# generator.class.{arg}=fullClassName +# +# The 'default' entry is required and will be used if none of the args +# specified in generator.args is passed. Note that {arg} is compared +# using String.equalsIgnoreCase(). + +generator.class.default=org.glassfish.rmic.RMIGenerator + +generator.class.v1.1=org.glassfish.rmic.RMIGenerator +generator.class.vcompat=org.glassfish.rmic.RMIGenerator +generator.class.v1.2=org.glassfish.rmic.RMIGenerator +generator.class.iiop=org.glassfish.rmic.iiop.StubGenerator +generator.class.idl=org.glassfish.rmic.iiop.IDLGenerator +generator.class.xprint=org.glassfish.rmic.iiop.PrintGenerator + +# If a generator needs a BatchEnvironment other than +# org.glassfish.rmic.BatchEnvironment, specify it as follows: +# +# generator.env.{arg}=fullClassName + +generator.env.iiop=org.glassfish.rmic.iiop.BatchEnvironment +generator.env.idl=org.glassfish.rmic.iiop.BatchEnvironment +generator.env.xprint=org.glassfish.rmic.iiop.BatchEnvironment + +rmic.usage=\u4F7F\u7528\u65B9\u6CD5: {0} \n\n\u306B\u306F\u6B21\u306E\u3082\u306E\u304C\u3042\u308A\u307E\u3059\u3002\n -keep \u4E2D\u9593\u751F\u6210\u3055\u308C\u305F\u30BD\u30FC\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u524A\u9664\u3057\u306A\u3044\n -keepgenerated("-keep"\u3068\u540C\u3058)\n -v1.1 1.1\u30B9\u30BF\u30D6\u30FB\u30D7\u30ED\u30C8\u30B3\u30EB\u7248\u7528\u306E\u30B9\u30BF\u30D6/\u30B9\u30B1\u30EB\u30C8\u30F3\u3092\u4F5C\u6210\u3059\u308B(\u975E\u63A8\u5968)\n -vcompat 1.1\u30681.2\u306E\u30B9\u30BF\u30D6\u30FB\u30D7\u30ED\u30C8\u30B3\u30EB\u7248\u3068\n \u4E92\u63DB\u6027\u306E\u3042\u308B\u30B9\u30BF\u30D6/\u30B9\u30B1\u30EB\u30C8\u30F3\u3092\u4F5C\u6210\u3059\u308B(\u975E\u63A8\u5968)\n -v1.2 (\u30C7\u30D5\u30A9\u30EB\u30C8)1.2\u30B9\u30BF\u30D6\u30FB\u30D7\u30ED\u30C8\u30B3\u30EB\u7248\u5C02\u7528\u306E\u30B9\u30BF\u30D6\u3092\u4F5C\u6210\u3059\u308B(\u975E\u63A8\u5968)\n -iiop IIOP\u7528\u306E\u30B9\u30BF\u30D6\u3092\u4F5C\u6210\u3059\u308B\u3002\u6307\u5B9A\u3059\u308B\u3068\u306B\u306F\u6B21\u306E\u3082\u306E\u3082\u542B\u307E\u308C\u307E\u3059\u3002\n\n -always \u6700\u65B0\u306E\u5834\u5408\u3067\u3082\u30B9\u30BF\u30D6\u3092\u4F5C\u6210\u3059\u308B\n -alwaysgenerate ("-always"\u3068\u540C\u3058)\n -nolocalstubs \u540C\u3058\u30D7\u30ED\u30BB\u30B9\u306B\u3064\u3044\u3066\u6700\u9069\u5316\u3055\u308C\u305F\u30B9\u30BF\u30D6\u306F\u4F5C\u6210\u3057\u306A\u3044\n\n -idl IDL\u3092\u4F5C\u6210\u3059\u308B\u3002\u6307\u5B9A\u3059\u308B\u3068\u306B\u306F\u6B21\u306E\u3082\u306E\u3082\u542B\u307E\u308C\u307E\u3059\u3002\n\n -noValueMethods valuetypes\u306B\u5BFE\u3057\u3066\u30E1\u30BD\u30C3\u30C9\u3092\u751F\u6210\u3057\u306A\u3044\n -always \u6700\u65B0\u306E\u5834\u5408\u3067\u3082IDL\u3092\u751F\u6210\u3059\u308B\n -alwaysgenerate ("-always"\u3068\u540C\u3058)\n\n -g \u30C7\u30D0\u30C3\u30B0\u60C5\u5831\u3092\u751F\u6210\u3059\u308B\n -nowarn \u8B66\u544A\u3092\u751F\u6210\u3057\u306A\u3044\n -nowrite \u30B3\u30F3\u30D1\u30A4\u30EB\u3057\u305F\u30AF\u30E9\u30B9\u3092\u30D5\u30A1\u30A4\u30EB\u30FB\u30B7\u30B9\u30C6\u30E0\u306B\u66F8\u304D\u8FBC\u307E\u306A\u3044\n -verbose \u30B3\u30F3\u30D1\u30A4\u30E9\u306E\u52D5\u4F5C\u306B\u95A2\u3059\u308B\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u51FA\u529B\u3059\u308B\n -classpath \u5165\u529B\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u691C\u7D22\u3059\u308B\u5834\u6240\u3092\u6307\u5B9A\u3059\u308B\n -bootclasspath \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u30FB\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u306E\u5834\u6240\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\n -d \u751F\u6210\u3055\u308C\u305F\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u683C\u7D0D\u3059\u308B\u5834\u6240\u3092\u6307\u5B9A\u3059\u308B\n -J java\u30A4\u30F3\u30BF\u30D7\u30EA\u30BF\u306B\u5F15\u6570\u3092\u6E21\u3059\n + +# +# Generic Messages +# + +rmic.cant.read={0}\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093 +rmic.cant.write={0}\u304C\u66F8\u304D\u8FBC\u3081\u307E\u305B\u3093 +rmic.option.unsupported=\u30AA\u30D7\u30B7\u30E7\u30F3{0}\u306F\u73FE\u5728\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +rmic.option.unimplemented=\u30AA\u30D7\u30B7\u30E7\u30F3{0}\u306F\u307E\u3060\u5B9F\u88C5\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +rmic.option.already.seen={0}\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u8907\u6570\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +rmic.option.requires.argument={0}\u30AA\u30D7\u30B7\u30E7\u30F3\u306B\u306F\u5F15\u6570\u304C\u5FC5\u8981\u3067\u3059\u3002 +rmic.no.such.directory=\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA{0}\u306F\u5B58\u5728\u3057\u307E\u305B\u3093\u3002 +rmic.no.such.option={0}\u306F\u7121\u52B9\u306A\u30AA\u30D7\u30B7\u30E7\u30F3\u307E\u305F\u306F\u5F15\u6570\u3067\u3059\u3002 +rmic.wrote=[{0}\u3092\u66F8\u8FBC\u307F\u5B8C\u4E86] +rmic.errors=\u30A8\u30E9\u30FC{0}\u500B +rmic.1error=\u30A8\u30E9\u30FC1\u500B +rmic.warnings=\u8B66\u544A{0}\u500B +rmic.1warning=\u8B66\u544A1\u500B +rmic.done_in=[{0}\u30DF\u30EA\u79D2\u3067\u5B8C\u4E86] +rmic.no.memory=\u30B3\u30F3\u30D1\u30A4\u30E9\u306B\u30E1\u30E2\u30EA\u30FC\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002"-J-Xmx"\u30B3\u30DE\u30F3\u30C9\u30E9\u30A4\u30F3\u30FB\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u3001\u6700\u5927\u30D2\u30FC\u30D7\u30FB\u30B5\u30A4\u30BA\u3092\u5897\u3084\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +rmic.stack.overflow=\u30B3\u30F3\u30D1\u30A4\u30E9\u306B\u30B9\u30BF\u30C3\u30AF\u7A7A\u9593\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002"-J-Xss"\u30B3\u30DE\u30F3\u30C9\u30E9\u30A4\u30F3\u30FB\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u3001Java\u30B9\u30BF\u30C3\u30AF\u306B\u5272\u308A\u5F53\u3066\u308B\u30E1\u30E2\u30EA\u30FC\u3092\u5897\u3084\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +rmic.class.not.found=\u30AF\u30E9\u30B9{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +rmic.missing.property=\u30D7\u30ED\u30D1\u30C6\u30A3generator.class.{0}\u304C\u3042\u308A\u307E\u305B\u3093 +rmic.cannot.instantiate=\u30AF\u30E9\u30B9{0}\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093 +rmic.cannot.use.both={0}\u3068{1}\u306E\u4E21\u65B9\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002 +rmic.resource.not.found={0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +rmic.no.output.dir={0}\u306B\u9069\u5207\u306A\u51FA\u529B\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002-d\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u30EB\u30FC\u30C8\u30FB\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +rmic.cannot.create.dir=\u51FA\u529B\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA{0}\u3092\u4F5C\u6210\u3067\u304D\u307E\u305B\u3093\u3002 + +# +# JRMP Messages +# + +rmic.cant.make.stubs.for.interface={0}\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30B9\u30BF\u30D6\u306F\u30EA\u30E2\u30FC\u30C8\u30FB\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u30FB\u30AF\u30E9\u30B9\u306B\u306E\u307F\u5FC5\u8981\u3067\u3059\u3002 +rmic.must.implement.remote=\u30AF\u30E9\u30B9{0}\u306Fjava.rmi.Remote\u3092\u62E1\u5F35\u3059\u308B\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3092\u5B9F\u88C5\u3057\u307E\u305B\u3093\u3002\u30B9\u30BF\u30D6\u3068\u30B9\u30B1\u30EB\u30C8\u30F3\u3092\u5FC5\u8981\u3068\u3059\u308B\u306E\u306F\u30EA\u30E2\u30FC\u30C8\u30FB\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u306E\u307F\u3067\u3059\u3002 +rmic.must.implement.remote.directly=\u30B9\u30BF\u30D6\u3092\u5FC5\u8981\u3068\u3059\u308B\u306E\u306Fjava.rmi.Remote\u3092\u62E1\u5F35\u3059\u308B\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3092\u76F4\u63A5\u5B9F\u88C5\u3059\u308B\u30AF\u30E9\u30B9\u306E\u307F\u3067\u3059\u3002\u30AF\u30E9\u30B9{0}\u306F\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3092\u76F4\u63A5\u306B\u306F\u5B9F\u88C5\u3057\u307E\u305B\u3093\u3002 +rmic.must.throw.remoteexception={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30E1\u30BD\u30C3\u30C9{1}\u306Fjava.rmi.RemoteException\u3092\u30B9\u30ED\u30FC\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +rmic.must.only.throw.exception=\u30E1\u30BD\u30C3\u30C9{0}\u306F{1}\u3092\u30B9\u30ED\u30FC\u3059\u308B\u306E\u3067\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u30FB\u30E1\u30BD\u30C3\u30C9\u5B9F\u88C5\u3067\u3059\u3002\u30EA\u30E2\u30FC\u30C8\u30FB\u30E1\u30BD\u30C3\u30C9\u306E\u5B9F\u88C5\u304C\u30B9\u30ED\u30FC\u3059\u308B\u306E\u306Fjava.lang.Exception\u304B\u305D\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u306E\u307F\u3067\u3059\u3002 +warn.rmic.tie.found=IIOP "tie"\u306F\u30AF\u30E9\u30B9{0}\u306E\u305F\u3081\u306B\u3042\u308A\u307E\u3059\u3002\n {1}\nPortableRemoteObject.exportObject\u3092\u4F7F\u7528\u3059\u308B\u5834\u5408\u306F\u3053\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u524A\u9664\u3057\u307E\u3059\u3002\u524A\u9664\u3057\u306A\u3044\u3068\u3001\u30B5\u30FC\u30D0\u30FC\u30FB\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u306FJRMP\u3067\u306A\u304FIIOP\u306B\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3055\u308C\u307E\u3059\u3002 +rmic.jrmp.not.supported=\u8B66\u544A: JRMP\u306E\u30B9\u30B1\u30EB\u30C8\u30F3\u3068static\u30B9\u30BF\u30D6\u306E\u751F\u6210\u3068\u4F7F\u7528\u306F\n\u975E\u63A8\u5968\u3067\u3059\u3002\u30B9\u30B1\u30EB\u30C8\u30F3\u306F\u4E0D\u8981\u3067\u3001static\u30B9\u30BF\u30D6\u306F\n\u52D5\u7684\u306B\u751F\u6210\u3055\u308C\u308B\u30B9\u30BF\u30D6\u306B\u5DEE\u3057\u66FF\u3048\u3089\u308C\u307E\u3057\u305F\u3002\u30E6\u30FC\u30B6\u30FC\u306F\n\u30B9\u30B1\u30EB\u30C8\u30F3\u3068static\u30B9\u30BF\u30D6\u3092\u751F\u6210\u3059\u308B\u305F\u3081\u306B{0}\u3092\u4F7F\u7528\u305B\u305A\u306B\u79FB\u884C\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002\njava.rmi.server.UnicastRemoteObject\u306B\u95A2\u3059\u308B\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002 + +# +# RMI-IIOP Messages +# + +rmic.generated=[{1}\u30DF\u30EA\u79D2\u3067{0}\u3092\u751F\u6210] +rmic.previously.generated=[\u4EE5\u524D\u306B\u751F\u6210\u3055\u308C\u305F\u30D5\u30A1\u30A4\u30EB{0}\u306F\u6700\u65B0\u3067\u3059] +warn.rmic.member.not.mapped=\u30AF\u30E9\u30B9{1}\u306E\u30C7\u30FC\u30BF\u30FB\u30E1\u30F3\u30D0\u30FC{0}\u306FIDL\u306B\u30DE\u30C3\u30D7\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002 + +rmic.iiop.constraint.1={0}\u306F\u4E0D\u6B63\u306A\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002java.rmi.Remote\u304B\u3089\u306F\u7D99\u627F\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.2=\u30AF\u30E9\u30B9{0}\u306EserialPersistentFields\u914D\u5217\u306F\u4E0D\u6B63\u3067\u3059\u3002\u5B58\u5728\u3057\u306A\u3044\u30E1\u30F3\u30D0\u30FC\u3092\u53C2\u7167\u3057\u3066\u3044\u307E\u3059\u3002 +rmic.iiop.constraint.3={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002{1}\u306F\u6B63\u3057\u3044\u30D7\u30EA\u30DF\u30C6\u30A3\u30D6\u307E\u305F\u306FString\u5B9A\u6570\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.4={0}\u306F\u4E0D\u6B63\u306A\u5024\u3067\u3059\u3002serialPersistentFields\u306Fprivate static final\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +rmic.iiop.constraint.5={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30E1\u30BD\u30C3\u30C9{1}\u306FRemoteException\u307E\u305F\u306FRemoteException\u306E\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9\u3092\u30B9\u30ED\u30FC\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +rmic.iiop.constraint.6={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u7D99\u627F\u3055\u308C\u305F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9{1}\u3082\u4E21\u65B9\u30E1\u30BD\u30C3\u30C9{2}\u3092\u5BA3\u8A00\u3057\u3066\u3044\u307E\u3059\u3002 +rmic.iiop.constraint.7={0}\u306F\u4E0D\u6B63\u306A\u578B\u3067\u3059\u3002{1}\u306F\u7279\u5225\u306A\u5834\u5408\u306B\u306E\u307F\u7570\u306A\u308A\u307E\u3059\u3002 +rmic.iiop.constraint.8={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u5B9F\u88C5\u3067\u3059\u3002\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3092\u6301\u3063\u3066\u3044\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.9=\u30AF\u30E9\u30B9{1}\u306EserialPersistentFields\u914D\u5217\u30E1\u30F3\u30D0\u30FC{0}\u306F\u4E0D\u6B63\u3067\u3059\u3002\u578B\u304C\u5BA3\u8A00\u3055\u308C\u305F\u30E1\u30F3\u30D0\u30FC\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.10={0}\u306F\u4E0D\u6B63\u306A\u5024\u3067\u3059\u3002java.rmi.Remote\u3092\u5B9F\u88C5\u3057\u307E\u3059\u3002 +rmic.iiop.constraint.11={0}\u306F\u4E0D\u6B63\u306A\u5024\u3067\u3059\u3002java.io.Serializable\u3092\u5B9F\u88C5\u3057\u3066\u3044\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.12={0}\u306F\u4E0D\u6B63\u306A\u5024\u3067\u3059\u3002\u4E0D\u6B63\u306A\u89AA\u3067\u3059\u3002 +rmic.iiop.constraint.13={0}\u306F\u4E0D\u6B63\u306A\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30E1\u30BD\u30C3\u30C9{1}\u306Eidl\u540D\u304C\u4ED6\u306E\u30E1\u30BD\u30C3\u30C9\u3068\u7AF6\u5408\u3057\u307E\u3059\u3002 +rmic.iiop.constraint.14={0}\u306F\u4E0D\u6B63\u306Aabstract\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.15={0}\u306F\u4E0D\u6B63\u306Aabstract\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002java.rmi.Remote\u3092\u5B9F\u88C5\u3057\u3066\u3044\u307E\u3059\u3002 +rmic.iiop.constraint.16={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3001\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.17={0}\u306F\u4E0D\u6B63\u306A\u30EA\u30E2\u30FC\u30C8\u5B9F\u88C5\u3067\u3059\u3002\u30AF\u30E9\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.18={0}\u306F\u4E0D\u6B63\u306A\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30E1\u30BD\u30C3\u30C9{1}\u306Forg.omg.CORBA.portable.IDLEntity\u3092\u5B9F\u88C5\u3059\u308B\u4F8B\u5916\u3092\u6E21\u3057\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.19={0}\u306F\u4E0D\u6B63\u306A\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u5B9A\u6570{1}\u306Eidl\u540D\u304C\u4ED6\u306E\u5B9A\u6570\u3068\u7AF6\u5408\u3057\u307E\u3059\u3002 +rmic.iiop.constraint.20={0}\u306F\u4E0D\u6B63\u306A\u30AF\u30E9\u30B9\u3067\u3059\u3002\u30E1\u30F3\u30D0\u30FC{1}\u306Eidl\u540D\u304C\u4ED6\u306E\u30E1\u30F3\u30D0\u30FC\u3068\u7AF6\u5408\u3057\u307E\u3059\u3002 +rmic.iiop.constraint.21={0}\u306F\u30EA\u30E2\u30FC\u30C8\u5B9F\u88C5\u30AF\u30E9\u30B9\u3067\u3042\u308A\u3001{1}\u306E\u30E1\u30BD\u30C3\u30C9\u5F15\u6570\u307E\u305F\u306F\u623B\u308A\u5024\u306E\u578B\u3068\u3057\u3066\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.22=\u5185\u90E8\u969C\u5BB3: (\u30E1\u30BD\u30C3\u30C9)\u4F8B\u5916{0}\u306F\u30AF\u30E9\u30B9\u578B\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.23=\u5185\u90E8\u969C\u5BB3: (\u30E1\u30BD\u30C3\u30C9)\u306F{0}\u306Enull\u30DD\u30A4\u30F3\u30BF\u4F8B\u5916\u3092\u6355\u6349\u3057\u307E\u3057\u305F\u3002 +rmic.iiop.constraint.24=\u30AF\u30E9\u30B9{0}\u306F\u4E0D\u6B63\u306A\u623B\u308A\u5024\u306E\u578B\u3092\u542B\u3093\u3067\u3044\u307E\u3059\u3002 +rmic.iiop.constraint.25=\u30AF\u30E9\u30B9{0}\u306F\u30E1\u30BD\u30C3\u30C9{1}\u306B\u4E0D\u6B63\u306A\u5F15\u6570\u578B\u3092\u542B\u3093\u3067\u3044\u307E\u3059\u3002 +rmic.iiop.constraint.26={0}\u3092\u30B3\u30F3\u30D1\u30A4\u30EB\u3067\u304D\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.27=\u30AF\u30E9\u30B9{0}\u3092\u30ED\u30FC\u30C9\u3067\u304D\u307E\u305B\u3093\u3002 +rmic.iiop.constraint.28={0}\u306F\u30EA\u30E2\u30FC\u30C8\u5B9F\u88C5\u30AF\u30E9\u30B9\u3067\u3042\u308A\u3001{1}\u306E\u30C7\u30FC\u30BF\u30FB\u30E1\u30F3\u30D0\u30FC\u3068\u3057\u3066\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002 diff --git a/rmic/src/main/resources/org/glassfish/rmic/resources/rmic_zh_CN.properties b/rmic/src/main/resources/org/glassfish/rmic/resources/rmic_zh_CN.properties new file mode 100644 index 000000000..389f52262 --- /dev/null +++ b/rmic/src/main/resources/org/glassfish/rmic/resources/rmic_zh_CN.properties @@ -0,0 +1,128 @@ +# +# Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1998 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# To add a generator org.glassfish.rmic.Foo which is invoked via the -foo option: +# +# 1. Add "foo" to generator.args list. +# 2. Add line: generator.class.foo=org.glassfish.rmic.Foo +# 3. Update rmic.usage string to include new arguments. + +# For each available generator, list the command line argument used +# to invoke it. The value can be a single item or a comma separated +# list. + +generator.args=v1.1,vcompat,v1.2,iiop,idl,xprint + +# For each generator, specify the class to invoke, using the following +# syntax: +# +# generator.class.{arg}=fullClassName +# +# The 'default' entry is required and will be used if none of the args +# specified in generator.args is passed. Note that {arg} is compared +# using String.equalsIgnoreCase(). + +generator.class.default=org.glassfish.rmic.RMIGenerator + +generator.class.v1.1=org.glassfish.rmic.RMIGenerator +generator.class.vcompat=org.glassfish.rmic.RMIGenerator +generator.class.v1.2=org.glassfish.rmic.RMIGenerator +generator.class.iiop=org.glassfish.rmic.iiop.StubGenerator +generator.class.idl=org.glassfish.rmic.iiop.IDLGenerator +generator.class.xprint=org.glassfish.rmic.iiop.PrintGenerator + +# If a generator needs a BatchEnvironment other than +# org.glassfish.rmic.BatchEnvironment, specify it as follows: +# +# generator.env.{arg}=fullClassName + +generator.env.iiop=org.glassfish.rmic.iiop.BatchEnvironment +generator.env.idl=org.glassfish.rmic.iiop.BatchEnvironment +generator.env.xprint=org.glassfish.rmic.iiop.BatchEnvironment + +rmic.usage=\u7528\u6CD5: {0} \n\n\u5176\u4E2D \u5305\u62EC:\n -keep \u4E0D\u5220\u9664\u4E34\u65F6\u751F\u6210\u7684\u6E90\u6587\u4EF6\n -keepgenerated (\u4E0E "-keep" \u76F8\u540C)\n -v1.1 \u521B\u5EFA 1.1 \u5B58\u6839\u534F\u8BAE\u7248\u672C\u7684\u5B58\u6839/\u9AA8\u67B6 (\u5DF2\u8FC7\u65F6)\n -vcompat \u521B\u5EFA\u4E0E 1.1 \u548C 1.2 \u5B58\u6839\u534F\u8BAE\u7248\u672C\n \u90FD\u517C\u5BB9\u7684\u5B58\u6839/\u9AA8\u67B6 (\u5DF2\u8FC7\u65F6)\n -v1.2 (\u9ED8\u8BA4\u503C) \u4EC5\u521B\u5EFA 1.2 \u5B58\u6839\u534F\u8BAE\u7248\u672C\u7684\u5B58\u6839 (\u5DF2\u8FC7\u65F6)\n -iiop \u521B\u5EFA IIOP \u7684\u5B58\u6839\u3002\u5982\u679C\u63D0\u4F9B, \u8FD8\u5305\u62EC:\n\n -always \u521B\u5EFA\u5B58\u6839 (\u5373\u4F7F\u5F53\u524D\u663E\u793A)\n -alwaysgenerate (\u4E0E "-always" \u76F8\u540C)\n -nolocalstubs \u4E0D\u521B\u5EFA\u5BF9\u76F8\u540C\u8FDB\u7A0B\u4F18\u5316\u7684\u5B58\u6839\n\n -idl \u521B\u5EFA IDL\u3002\u5982\u679C\u63D0\u4F9B, \u8FD8\u5305\u62EC:\n\n -noValueMethods \u4E0D\u4E3A\u503C\u7C7B\u578B\u751F\u6210\u65B9\u6CD5\n -always \u521B\u5EFA IDL (\u5373\u4F7F\u5F53\u524D\u663E\u793A)\n -alwaysgenerate (\u4E0E "-always" \u76F8\u540C)\n\n -g \u751F\u6210\u8C03\u8BD5\u4FE1\u606F\n -nowarn \u4E0D\u751F\u6210\u4EFB\u4F55\u8B66\u544A\n -nowrite \u4E0D\u5C06\u7F16\u8BD1\u7684\u7C7B\u5199\u5165\u6587\u4EF6\u7CFB\u7EDF\n -verbose \u8F93\u51FA\u6709\u5173\u7F16\u8BD1\u5668\u6B63\u5728\u6267\u884C\u7684\u64CD\u4F5C\u7684\u6D88\u606F\n -classpath \u6307\u5B9A\u67E5\u627E\u8F93\u5165\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n -bootclasspath \u8986\u76D6\u5F15\u5BFC\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n -d \u6307\u5B9A\u653E\u7F6E\u751F\u6210\u7684\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n -J \u5C06\u53C2\u6570\u4F20\u9012\u7ED9 java \u89E3\u91CA\u5668\n + +# +# Generic Messages +# + +rmic.cant.read=\u65E0\u6CD5\u8BFB\u53D6: {0} +rmic.cant.write=\u65E0\u6CD5\u5199\u5165: {0} +rmic.option.unsupported=\u4E0D\u518D\u652F\u6301{0}\u9009\u9879\u3002 +rmic.option.unimplemented=\u5C1A\u672A\u5B9E\u73B0{0}\u9009\u9879\u3002 +rmic.option.already.seen={0}\u9009\u9879\u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\u3002 +rmic.option.requires.argument=\u9009\u9879{0}\u9700\u8981\u53C2\u6570\u3002 +rmic.no.such.directory={0} \u76EE\u5F55\u4E0D\u5B58\u5728\u3002 +rmic.no.such.option={0}\u662F\u65E0\u6548\u9009\u9879\u6216\u53C2\u6570\u3002 +rmic.wrote=[\u5DF2\u5199\u5165{0}] +rmic.errors={0} \u4E2A\u9519\u8BEF +rmic.1error=1 \u4E2A\u9519\u8BEF +rmic.warnings={0} \u4E2A\u8B66\u544A +rmic.1warning=1 \u4E2A\u8B66\u544A +rmic.done_in=[\u5728 {0} \u6BEB\u79D2\u5185\u5B8C\u6210] +rmic.no.memory=\u7F16\u8BD1\u5668\u6240\u7528\u5185\u5B58\u4E0D\u8DB3\u3002\u8BF7\u8003\u8651\u4F7F\u7528 "-J-Xmx" \u547D\u4EE4\u884C\u9009\u9879\u6765\u589E\u52A0\u5806\u5927\u5C0F\u7684\u6700\u5927\u503C\u3002 +rmic.stack.overflow=\u7F16\u8BD1\u5668\u6240\u7528\u5806\u6808\u7A7A\u95F4\u4E0D\u8DB3\u3002\u8BF7\u8003\u8651\u4F7F\u7528 "-J-Xss" \u547D\u4EE4\u884C\u9009\u9879\u6765\u589E\u52A0\u5206\u914D\u7ED9 Java \u5806\u6808\u7684\u5185\u5B58\u5927\u5C0F\u3002 +rmic.class.not.found=\u627E\u4E0D\u5230\u7C7B{0}\u3002 +rmic.missing.property=\u7F3A\u5C11\u5C5E\u6027 generator.class.{0} +rmic.cannot.instantiate=\u65E0\u6CD5\u5B9E\u4F8B\u5316\u7C7B{0} +rmic.cannot.use.both=\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528{0}\u548C{1} +rmic.resource.not.found=\u627E\u4E0D\u5230{0}\u3002 +rmic.no.output.dir=\u65E0\u6CD5\u627E\u5230\u9002\u7528\u4E8E{0}\u7684\u8F93\u51FA\u76EE\u5F55\u3002\u8BF7\u4F7F\u7528 -d \u9009\u9879\u6765\u6307\u5B9A\u6839\u76EE\u5F55\u3002 +rmic.cannot.create.dir=\u65E0\u6CD5\u521B\u5EFA\u8F93\u51FA\u76EE\u5F55 {0}\u3002 + +# +# JRMP Messages +# + +rmic.cant.make.stubs.for.interface={0}\u662F\u63A5\u53E3; \u4EC5\u8FDC\u7A0B\u5BF9\u8C61\u7C7B\u9700\u8981\u5B58\u6839\u3002 +rmic.must.implement.remote=\u7C7B{0}\u4E0D\u5B9E\u73B0\u6269\u5C55 java.rmi.Remote \u7684\u63A5\u53E3; \u4EC5\u8FDC\u7A0B\u5BF9\u8C61\u9700\u8981\u5B58\u6839\u548C\u6846\u67B6\u3002 +rmic.must.implement.remote.directly=\u4EC5\u76F4\u63A5\u5B9E\u73B0\u6269\u5C55 java.rmi.Remote \u7684\u63A5\u53E3\u7684\u7C7B\u9700\u8981\u5B58\u6839; \u7C7B{0}\u4E0D\u76F4\u63A5\u5B9E\u73B0\u8FDC\u7A0B\u63A5\u53E3\u3002 +rmic.must.throw.remoteexception={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u63A5\u53E3: \u65B9\u6CD5{1}\u5FC5\u987B\u629B\u51FA java.rmi.RemoteException\u3002 +rmic.must.only.throw.exception=\u65B9\u6CD5{0}\u4E0D\u662F\u6709\u6548\u7684\u8FDC\u7A0B\u65B9\u6CD5\u5B9E\u73B0, \u56E0\u4E3A\u5B83\u629B\u51FA\u4E86{1}; \u8FDC\u7A0B\u65B9\u6CD5\u5B9E\u73B0\u53EA\u53EF\u80FD\u629B\u51FA java.lang.Exception \u6216\u5176\u5B50\u7C7B\u3002 +warn.rmic.tie.found=\u5BF9\u4E8E\u7C7B{0}, \u5B58\u5728 IIOP "tie":\n {1}\n\u5982\u679C\u4F7F\u7528 PortableRemoteObject.exportObject, \u5219\u5E94\u8BE5\u5220\u9664\u6B64\u6587\u4EF6, \u5426\u5219, \u60A8\u7684\u670D\u52A1\u5668\u5BF9\u8C61\u5C06\u4F1A\u5BFC\u51FA\u5230 IIOP \u800C\u975E JRMP\u3002 +rmic.jrmp.not.supported=\u8B66\u544A: \u4E3A JRMP \u751F\u6210\u548C\u4F7F\u7528\u9AA8\u67B6\u53CA\u9759\u6001\u5B58\u6839\n\u5DF2\u8FC7\u65F6\u3002\u9AA8\u67B6\u4E0D\u518D\u5FC5\u8981, \u800C\u9759\u6001\u5B58\u6839\n\u5DF2\u7531\u52A8\u6001\u751F\u6210\u7684\u5B58\u6839\u53D6\u4EE3\u3002\u5EFA\u8BAE\u7528\u6237\n\u4E0D\u518D\u4F7F\u7528{0}\u6765\u751F\u6210\u9AA8\u67B6\u548C\u9759\u6001\u5B58\u6839\u3002\n\u8BF7\u53C2\u9605 java.rmi.server.UnicastRemoteObject \u7684\u6587\u6863\u3002 + +# +# RMI-IIOP Messages +# + +rmic.generated=[\u5728 {1} \u6BEB\u79D2\u5185\u751F\u6210{0}] +rmic.previously.generated=[\u4EE5\u524D\u751F\u6210\u7684\u6587\u4EF6{0}\u4E3A\u5F53\u524D\u6587\u4EF6] +warn.rmic.member.not.mapped=\u7C7B{1}\u7684\u6570\u636E\u6210\u5458{0}\u672A\u6620\u5C04\u5230 IDL\u3002 + +rmic.iiop.constraint.1={0}\u4E0D\u662F\u6709\u6548\u63A5\u53E3: \u6CA1\u6709\u4ECE java.rmi.Remote \u7EE7\u627F\u3002 +rmic.iiop.constraint.2=\u7C7B{0}\u7684 serialPersistentFields \u6570\u7EC4\u65E0\u6548: \u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u6210\u5458\u3002 +rmic.iiop.constraint.3={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u63A5\u53E3: {1}\u4E0D\u662F\u6709\u6548\u7684\u57FA\u5143\u6216\u5B57\u7B26\u4E32\u5E38\u91CF\u3002 +rmic.iiop.constraint.4={0}\u4E0D\u662F\u6709\u6548\u503C: serialPersistentFields \u5FC5\u987B\u4E3A\u4E13\u7528\u9759\u6001\u6700\u7EC8\u7C7B\u578B\u3002 +rmic.iiop.constraint.5={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u63A5\u53E3: \u65B9\u6CD5{1}\u5FC5\u987B\u629B\u51FA RemoteException \u6216 RemoteException \u7684\u8D85\u7C7B\u3002 +rmic.iiop.constraint.6={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u63A5\u53E3: \u7EE7\u627F\u7684\u63A5\u53E3{1}\u5747\u58F0\u660E\u4E86\u65B9\u6CD5{2}\u3002 +rmic.iiop.constraint.7={0}\u4E0D\u662F\u6709\u6548\u7C7B\u578B: {1}\u4EC5\u5728\u5927\u5C0F\u5199\u4E0A\u4E0D\u540C\u3002 +rmic.iiop.constraint.8={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u5B9E\u73B0: \u4E0D\u5177\u6709\u8FDC\u7A0B\u63A5\u53E3\u3002 +rmic.iiop.constraint.9=\u7C7B{1}\u7684 serialPersistentFields \u6570\u7EC4\u6210\u5458{0}\u65E0\u6548: \u7C7B\u578B\u4E0E\u58F0\u660E\u7684\u6210\u5458\u4E0D\u5339\u914D\u3002 +rmic.iiop.constraint.10={0}\u4E0D\u662F\u6709\u6548\u503C: \u5B9E\u73B0 java.rmi.Remote\u3002 +rmic.iiop.constraint.11={0}\u4E0D\u662F\u6709\u6548\u503C: \u4E0D\u5B9E\u73B0 java.io.Serializable\u3002 +rmic.iiop.constraint.12={0}\u4E0D\u662F\u6709\u6548\u503C: \u7236\u7EA7\u65E0\u6548\u3002 +rmic.iiop.constraint.13={0}\u4E0D\u662F\u6709\u6548\u63A5\u53E3: \u65B9\u6CD5{1}\u7684 idl \u540D\u79F0\u4E0E\u5176\u4ED6\u65B9\u6CD5\u51B2\u7A81\u3002 +rmic.iiop.constraint.14={0}\u4E0D\u662F\u6709\u6548\u62BD\u8C61\u63A5\u53E3: \u4E0D\u662F\u63A5\u53E3\u3002 +rmic.iiop.constraint.15={0}\u4E0D\u662F\u6709\u6548\u62BD\u8C61\u63A5\u53E3: \u5B9E\u73B0 java.rmi.Remote\u3002 +rmic.iiop.constraint.16={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u63A5\u53E3: \u4E0D\u662F\u63A5\u53E3\u3002 +rmic.iiop.constraint.17={0}\u4E0D\u662F\u6709\u6548\u8FDC\u7A0B\u5B9E\u73B0: \u4E0D\u662F\u7C7B\u3002 +rmic.iiop.constraint.18={0}\u4E0D\u662F\u6709\u6548\u63A5\u53E3: \u65B9\u6CD5{1}\u4E0D\u80FD\u4F20\u9012\u5B9E\u73B0 org.omg.CORBA.portable.IDLEntity \u7684\u5F02\u5E38\u9519\u8BEF\u3002 +rmic.iiop.constraint.19={0}\u4E0D\u662F\u6709\u6548\u63A5\u53E3: \u5E38\u91CF{1}\u7684 idl \u540D\u79F0\u4E0E\u5176\u4ED6\u5E38\u91CF\u51B2\u7A81\u3002 +rmic.iiop.constraint.20={0}\u4E0D\u662F\u6709\u6548\u7C7B: \u6210\u5458{1}\u7684 idl \u540D\u79F0\u4E0E\u5176\u4ED6\u6210\u5458\u51B2\u7A81\u3002 +rmic.iiop.constraint.21={0}\u662F\u8FDC\u7A0B\u5B9E\u73B0\u7C7B\u5E76\u4E14\u4E0D\u80FD\u7528\u4F5C{1}\u4E2D\u7684\u65B9\u6CD5\u53C2\u6570\u6216\u8FD4\u56DE\u7C7B\u578B\u3002 +rmic.iiop.constraint.22=\u5185\u90E8\u5931\u8D25: (\u65B9\u6CD5) \u5F02\u5E38\u9519\u8BEF{0}\u4E0D\u662F\u7C7B\u7C7B\u578B\u3002 +rmic.iiop.constraint.23=\u5185\u90E8\u5931\u8D25: (\u65B9\u6CD5) \u6355\u83B7\u5230{0}\u7684\u7A7A\u503C\u6307\u9488\u5F02\u5E38\u9519\u8BEF\u3002 +rmic.iiop.constraint.24=\u7C7B{0}\u5305\u542B\u65E0\u6548\u8FD4\u56DE\u7C7B\u578B\u3002 +rmic.iiop.constraint.25=\u7C7B{0}\u5305\u542B\u65B9\u6CD5{1}\u4E2D\u7684\u65E0\u6548\u53C2\u6570\u7C7B\u578B\u3002 +rmic.iiop.constraint.26=\u65E0\u6CD5\u7F16\u8BD1{0}\u3002 +rmic.iiop.constraint.27=\u65E0\u6CD5\u52A0\u8F7D\u7C7B{0}\u3002 +rmic.iiop.constraint.28={0}\u662F\u8FDC\u7A0B\u5B9E\u73B0\u7C7B\u5E76\u4E14\u65E0\u6CD5\u7528\u4F5C{1}\u4E2D\u7684\u6570\u636E\u6210\u5458\u3002 diff --git a/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac.properties b/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac.properties new file mode 100644 index 000000000..cc02db42e --- /dev/null +++ b/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac.properties @@ -0,0 +1,622 @@ +# +# Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +javac.err.internal=\ + Internal error. +javac.err.eof.in.comment=\ + Comment not terminated at end of input. +javac.err.eof.in.string=\ + String not terminated at end of input. +javac.err.newline.in.string=\ + String not terminated at end of line. +javac.err.invalid.char.constant=\ + Invalid character constant. +javac.err.unbalanced.paren=\ + Unbalanced parentheses. +javac.err.invalid.escape.char=\ + Invalid escape character. +javac.err.invalid.hex.number=\ + Hexadecimal numbers must contain at least one hexadecimal digit. +javac.err.invalid.octal.number=\ + Invalid character in octal number. +javac.err.invalid.number=\ + Invalid character in number. +javac.err.funny.char=\ + Invalid character in input. +javac.err.float.format=\ + Invalid floating point format. +javac.err.overflow.int.oct=\ + Integer literal out of range. Octal int literals must be in \ + the range 00 to 037777777777. +javac.err.overflow.int.dec=\ + Integer literal out of range. Decimal int literals must be in \ + the range -2147483648 to 2147483647. +javac.err.overflow.int.hex=\ + Integer literal out of range. Hexadecimal int literals must be in \ + the range 0x0 to 0xffffffff. +javac.err.overflow.long.oct=\ + Integer literal out of range. Octal long literals must be in \ + the range 00L to 01777777777777777777777L. +javac.err.overflow.long.dec=\ + Integer literal out of range. Decimal long literals must be in \ + the range -9223372036854775808L to 9223372036854775807L. +javac.err.overflow.long.hex=\ + Integer literal out of range. Hexadecimal long literals must be in \ + the range 0x0L to 0xffffffffffffffffL. +javac.err.overflow.float=\ + Numeric overflow: float literal too large. +javac.err.overflow.double=\ + Numeric overflow: double literal too large. +javac.err.underflow.float=\ + Numeric underflow: float literal too small. +javac.err.underflow.double=\ + Numeric underflow: double literal too small. +javac.err.token.expected=\ + ''{0}'' expected. +javac.err.statement.expected=\ + Statement expected. +javac.err.type.expected=\ + Type expected. +javac.err.identifier.expected=\ + Identifier expected. +javac.err.class.expected=\ + ''class'' or ''interface'' keyword expected. +javac.err.toplevel.expected=\ + Class or interface declaration expected. +javac.err.missing.term=\ + Missing term. +javac.err.assign.in.conditionalexpr=\ + Assignment expressions are not permitted as the third subexpression \ + of a conditional expression (that is, a ? : expression). \ + Try parenthesizing this assignment expression. +javac.err.else.without.if=\ + ''else'' without ''if''. +javac.err.catch.without.try=\ + ''catch'' without ''try''. +javac.err.finally.without.try=\ + ''finally'' without ''try''. +javac.err.try.without.catch.finally=\ + ''try'' without ''catch'' or ''finally''. +javac.err.case.without.switch=\ + ''case'' outside switch statement. +javac.err.default.without.switch=\ + ''default'' outside switch statement. +javac.err.io.exception=\ + I/O error in {0}. +javac.err.io.exception.package=\ + I/O error while checking for existence of package {0}. +javac.err.malformed.attribute=\ + The class file containing {0} has a malformed ''{1}'' attribute. +javac.err.array.index.required=\ + Array index required. +javac.err.not.array=\ + [] can only be applied to arrays. It can''t be applied to {0}. +javac.err.array.dim.in.decl=\ + Can''t specify array dimension in a declaration. +javac.err.array.dim.in.type=\ + Can''t specify array dimension in a type expression. +javac.err.invalid.array.expr=\ + Array constants can only be used in initializers. +javac.err.invalid.array.init=\ + Invalid initializer for type {0}. +javac.err.invalid.lhs.assignment=\ + Invalid left hand side of assignment. +javac.err.invalid.args=\ + Invalid arguments to {0}. +javac.err.invalid.cast=\ + Invalid cast from {0} to {1}. +javac.err.invalid.instanceof=\ + Impossible for {0} to be instance of {1}. +javac.err.invalid.type.expr=\ + Invalid type expression. +javac.err.anonymous.extends=\ + Only named classes can have ''extends'' or ''implements'' clauses. +javac.err.invalid.field.reference=\ + Attempt to reference field {0} in a {1}. +javac.err.no.such.field=\ + No variable {0} defined in {1}. +javac.err.no.field.access=\ + Variable {0} in {1} not accessible from {2}. +javac.err.no.type.access=\ + Inner type {0} in {1} not accessible from {2}. +javac.err.cant.access.member.type=\ + The type {1} to which the member {0} belongs is not accessible from {2}. +javac.err.inner.class.expected=\ + No inner class {0} found in {1}. +javac.err.no.static.field.access=\ + Can''t make a static reference to nonstatic variable {0} in {1}. +javac.err.inner.static.ref=\ + Can''t make a static reference to inner class {0}. +javac.err.ambig.field=\ + Reference to {0} is ambiguous. It is defined in {1} and {2}. +javac.err.invalid.field=\ + Attempt to reference method {0} in {1} as an instance variable. +javac.err.assign.to.final=\ + Can''t assign a value to a final variable: {0} +javac.err.assign.to.blank.final=\ + Can''t assign a second value to a blank final variable: {0} +javac.err.qualified.static.final.assign=\ + The variable in an assignment to a static blank final must be a simple name (it may not follow a dot ''.''). +javac.err.bad.qualified.final.assign=\ + The variable in an assignment to a blank final must be a simple name or a simple name qualified by ''this'': ''{0}'' or ''this.{0}''. +javac.err.assign.to.blank.final.in.loop=\ + Attempt to assign a blank final variable {0} in a loop. The initialization must occur exactly once. +javac.err.assign.to.uplevel=\ + Attempt to assign to a variable {0} in a different method. From enclosing blocks, only final local variables are available. +javac.err.invalid.uplevel=\ + Attempt to use a non-final variable {0} from a different method. From enclosing blocks, only final local variables are available. +javac.err.undef.var=\ + Undefined variable: {0} +javac.err.undef.var.super=\ + Undefined variable: {0}. The "super" keyword may only be used for member access and constructor invocation. +javac.err.undef.var.or.package=\ + Undefined variable or package name: {0} +javac.err.undef.class.or.package=\ + Undefined class or package name: {0} +javac.err.undef.var.class.or.package=\ + Undefined variable, class, or package name: {0} +javac.err.undef.class=\ + Undefined class name: {0} +javac.err.undef.var.or.class=\ + Undefined variable or class name: {0} +javac.err.var.not.initialized=\ + Variable {0} may not have been initialized. +javac.err.final.var.not.initialized=\ + Blank final variable ''{0}'' may not have been initialized. It must be assigned a value in an initializer, or in every constructor. +javac.err.access.inst.before.super=\ + Can''t reference {0} before the superclass constructor has been called. +javac.err.ambig.class=\ + Ambiguous class: {0} and {1} +javac.err.invalid.arg=\ + Invalid argument to {0}. +javac.err.invalid.arg.type=\ + Invalid argument type {0} for {1}. +javac.err.invalid.length=\ + ''length'' applied to {0}, which is not an array. +javac.err.invalid.constr.invoke=\ + Only constructors can invoke constructors. +javac.err.constr.invoke.not.first=\ + Constructor invocation must be the first thing in a method. +javac.err.invalid.method.invoke=\ + Can''t invoke a method on a {0}. +javac.err.undef.meth=\ + Method {0} not found in {1}. +javac.err.no.meth.access=\ + Method {0} in {1} is not accessible from {2}. +#warning: +javac.err.no.override.access=\ + Note: Method {0} in {1} does not override the corresponding method in {2}. If you are trying to override this method, you cannot do so because it is private to a different package. +javac.err.no.static.meth.access=\ + Can''t make static reference to method {0} in {1}. +javac.err.invalid.protected.method.use=\ + Can''t access protected method {0} in {1}. {2} is not a subclass of the current class. +javac.err.invalid.protected.field.use=\ + Can''t access protected field {0} in {1}. {2} is not a subclass of the current class. +javac.err.invalid.protected.type.use=\ + Can''t access protected inner type {0} in {1}. {2} is not a subclass of the current class. +javac.err.invalid.protected.constructor.use=\ + Can''t access protected constructor of {0}. Instance creation is permitted only within the package in which the constructor is defined. +javac.err.invalid.method=\ + Reference to variable {0} in {1} as if it were a method. +javac.err.invalid.var=\ + Reference to method {0} in {1} as if it were a variable. +javac.err.synchronized.null=\ + The null literal is not a legal argument for the synchronized statement. +#all messages related to deprecation are warnings: +javac.err.class.is.deprecated=\ + Note: {0} has been deprecated. +javac.err.meth.is.deprecated=\ + Note: The method {0} in {1} has been deprecated. +javac.err.constr.is.deprecated=\ + Note: The constructor {0} has been deprecated. +javac.err.field.is.deprecated=\ + Note: The variable {0} in {1} has been deprecated. +javac.err.note.deprecations=\ + Note: {0} files use or override a deprecated API. Please consult the documentation for a better alternative in each case. +javac.err.note.1deprecation=\ + Note: {0} uses or overrides a deprecated API. Please consult the documentation for a better alternative. +javac.err.note.deprecations.silent=\ + Note: {0} files use or override a deprecated API. Recompile with "-deprecation" for details. +javac.err.note.1deprecation.silent=\ + Note: {0} uses or overrides a deprecated API. Recompile with "-deprecation" for details. +javac.err.invalid.array.dim=\ + Invalid array dimension. +javac.err.ambig.constr=\ + Constructor is ambiguous: {0}, {1} +javac.err.explicit.cast.needed=\ + Incompatible type for {0}. Explicit cast needed to convert {1} to {2}. +javac.err.incompatible.type=\ + Incompatible type for {0}. Can''t convert {1} to {2}. +javac.err.invalid.term=\ + Invalid term. +javac.err.abstract.class=\ + {0} must be declared abstract. It does not define {1} from {2}. +javac.err.abstract.class.cannot.override=\ + {0} must be declared abstract. The package-private abstract method {1} in superclass {2} is inaccessible and cannot be overridden. +javac.err.new.intf=\ + {0} is an interface. It can''t be instantiated. +javac.err.invoke.abstract=\ + Can''t directly invoke abstract method {0} in {1}. +javac.err.unmatched.meth=\ + No method matching {0} found in {1}. +javac.err.unmatched.constr=\ + No constructor matching {0} found in {1}. +javac.err.wrong.number.args=\ + Wrong number of arguments in {0}. +javac.err.wrong.number.args=\ + Wrong number of arguments in {0}. +javac.err.forward.ref=\ + Can''t make forward reference to {0} in {1}. +javac.err.array.dim.missing=\ + Array dimension missing. +javac.err.new.abstract=\ + {0} is an abstract class. It can''t be instantiated. +javac.err.label.not.found=\ + No label definition found for {0}. +javac.err.invalid.break=\ + ''break'' must be in loop or switch. +javac.err.invalid.continue=\ + ''continue'' must be in loop. +javac.err.branch.to.uplevel=\ + a ''break'' or ''continue'' must transfer control within the same method. +javac.err.invalid.decl=\ + Invalid declaration. +javac.err.return.with.value=\ + ''return'' with value from {0}. +javac.err.return.without.value=\ + ''return'' without value from {0}. +javac.err.return.inside.static.initializer=\ + ''return'' inside static initializer. +javac.err.invalid.label=\ + Invalid label. +javac.err.return.required.at.end=\ + Return required at end of {0}. +javac.err.duplicate.label=\ + Duplicate case label: {0} +javac.err.switch.overflow=\ + Case label {0} too large for ''switch'' on {1} +javac.err.nested.duplicate.label=\ + A statement cannot be labeled with the same identifier as one of its enclosing statements: {0} +javac.err.declaration.with.label=\ + A declaration cannot be labeled: {0} +javac.err.const.expr.required=\ + Constant expression required. +javac.err.duplicate.default=\ + Duplicate ''default'' label. +javac.err.not.supported=\ + ''{0}'' not supported. +javac.err.return.with.value.constr=\ + ''return'' with value from constructor: {0} +javac.err.package.repeated=\ + Only one package declaration allowed. +javac.err.class.multidef=\ + Class {0} already defined in {1}. +javac.err.class.multidef.import=\ + Class name {0} clashes with imported class {1}. +javac.err.intf.constructor=\ + Interfaces can''t have constructors. +javac.err.constr.modifier=\ + Constructors can''t be native, abstract, static, synchronized, or final: {0} +javac.err.intf.initializer=\ + Interfaces can''t have static initializers. +javac.err.intf.modifier.method=\ + Interface methods can''t be native, static, synchronized, final, private, or protected : {0} +javac.err.intf.modifier.field=\ + Interface fields can''t be private or protected: {0} +javac.err.transient.meth=\ + Method {0} can''t be transient. Only variables can be transient. +javac.err.volatile.meth=\ + Method {0} can''t be volatile. Only variables can be volatile. +javac.err.abstract.private.modifier=\ + Abstract methods can''t be private: {0} +javac.err.abstract.static.modifier=\ + Abstract methods can''t be static: {0} +javac.err.abstract.final.modifier=\ + Abstract methods can''t be final: {0} +javac.err.abstract.native.modifier=\ + Abstract methods can''t be native: {0} +javac.err.abstract.synchronized.modifier=\ + Abstract methods can''t be synchronized: {0} +javac.err.invalid.meth.body=\ + Abstract and native methods can''t have a body: {0} +javac.err.var.modifier=\ + Variables can''t be synchronized, abstract or native: {0} +javac.err.var.floatmodifier=\ + Variables can''t be declared strict: {0} +javac.err.inner.modifier=\ + Inner classes can''t be volatile, transient, native, or synchronized: {0} +javac.err.transient.modifier=\ + Transient variables can''t be members of interfaces: {0} +javac.err.volatile.modifier=\ + Volatile variables can''t be final or members of interfaces: {0} +javac.err.initializer.needed=\ + This final variable must be initialized: {0} +javac.err.meth.multidef=\ + Duplicate method declaration: {0} +javac.err.meth.redef.rettype=\ + Methods can''t be redefined with a different return type: {0} was {1} +javac.err.var.multidef=\ + Duplicate variable declaration: {0} was {1} +javac.err.inner.class.multidef=\ + Duplicate inner class declaration: {0} is already defined in this scope. +javac.err.intf.super.class=\ + Superclass of {0} can''t be an interface: {1} +javac.err.cant.access.class=\ + Can''t access {0}. Class or interface must be public, in same package, or an accessible member class. +javac.err.unqualified.name.required=\ + The type name in a qualified 'new' expression must be an unqualified identifier. +javac.err.repeated.modifier=\ + Repeated modifier. +javac.err.inconsistent.modifier=\ + Inconsistent member declaration. At most one of public, private, or protected may be specified. +javac.err.super.is.final=\ + Can''t subclass final classes: {0} +javac.err.super.is.intf=\ + Can''t subclass interfaces: {0} +javac.err.cyclic.super=\ + Cyclic class inheritance. +javac.err.super.is.inner=\ + Cyclic class inheritance: A subclass cannot enclose a superclass. +javac.err.cyclic.intf=\ + Cyclic interface inheritance. +javac.err.cyclic.scoping=\ + Cyclic class inheritance or scoping. +javac.err.not.intf=\ + {0} must be an interface. +javac.err.final.intf=\ + Interfaces can''t be final: {0} +javac.err.intf.impl.intf=\ + An interface can''t implement anything; it can only extend other interfaces. +javac.err.multiple.inherit=\ + Multiple inheritance is not supported. +javac.err.intf.repeated=\ + Interface {0} repeated. +javac.err.class.format=\ + Invalid class file format in {0}. {1} +javac.err.truncated.class=\ + Unexpected end of file encountered while reading the class file {0}. +javac.err.no.meth.body=\ + Method {0} requires a method body. Otherwise declare it as abstract. +javac.err.no.constructor.body=\ + Constructor {0} requires a method body. +javac.err.bad.constructor.modifier=\ + Constructors may not be modified by strictfp. +javac.err.void.inst.var=\ + Instance variables can''t be void: {0} +javac.err.invalid.method.decl=\ + Invalid method declaration; return type required. +javac.err.invalid.method.decl.name=\ + Invalid method declaration; method name required. +javac.err.invalid.method.decl.qual=\ + Invalid qualified constructor name. +javac.err.super.not.found=\ + Superclass {0} of {1} not found. +javac.err.intf.not.found=\ + Interface {0} of {1} not found. +javac.err.final.abstract=\ + Class {0} can''t be declared both abstract and final. +javac.err.void.array=\ + Array of void is not a valid type. +javac.err.void.argument=\ + Argument can''t have type void: {0} +javac.err.invalid.expr=\ + Invalid expression statement. +javac.err.catch.not.reached=\ + catch not reached. +javac.err.stat.not.reached=\ + Statement not reached. +javac.err.init.no.normal.completion=\ + Initializer must be able to complete normally. +javac.err.arithmetic.exception=\ + Arithmetic exception. +javac.err.generic=\ + {0} +javac.err.public.class.file=\ + Public {0} must be defined in a file called "{1}". +javac.err.package.class.file=\ + {0} is defined in {1}. Because it is used outside of its source file, it should be defined in a file called "{2}". +javac.err.lose.precision=\ + Possible loss of precision. Use an explicit cast to convert {0} to {1}. +javac.err.duplicate.argument=\ + Variable ''{0}'' is used twice in the argument list of this method. +javac.err.local.redefined=\ + Variable ''{0}'' is already defined in this method. +javac.err.local.class.redefined=\ + Local class ''{0}'' is already defined in this method. +javac.err.inner.redefined=\ + The class name ''{0}'' is already defined in this scope. An inner class may not have the same simple name as any of its enclosing classes. +javac.err.inherited.hides.field=\ + Variable ''{0}'' is inherited in {1}, and hides a variable of the same name in {2}. An explicit ''this'' qualifier must be used to select the desired instance. +javac.err.inherited.hides.local=\ + Variable ''{0}'' is inherited in {1}, and hides a local variable of the same name. An explicit ''this'' qualifier must be used to select the variable, or the local must be renamed. +javac.err.inherited.hides.method=\ + Method ''{0}'' is inherited in {1}, and hides a method of the same name in {2}. An explicit ''this'' qualifier must be used to select the desired instance. +javac.err.inherited.hides.type=\ + Type ''{0}'' is inherited in {1}, and hides a type of the same name in an enclosing scope. An explicit qualifier prefix must be used to name this type. +javac.err.private.class=\ + The type {0} can''t be private. Package members are always accessible within the current package. +javac.err.static.class=\ + The type {0} can''t be declared static. It is already top-level, since it is a member of a package. +javac.err.protected.class=\ + The type {0} can''t be made protected. Package members can either be public or local to the current package. +javac.err.recursive.constr=\ + Recursive constructor invocation: {0}. +javac.err.wrong.class=\ + File {0} does not contain {1} as expected, but {2}. Please remove the file, or make sure it appears in the correct subdirectory of the class path. +javac.err.wrong.source=\ + File {0} does not contain {1} as expected. Please adjust the class path so that the file does not appear in the {2}. +javac.err.class.not.found=\ + Class {0} not found in {1}. +javac.err.class.not.found.no.context=\ + Class {0} not found. +javac.err.package.not.found=\ + Package {0} not found in {1}. +javac.err.package.not.found.strong=\ + Package {0} not found. Please adjust the classpath so that package {0} is accessible. +javac.err.class.package.conflict=\ + A type and a package cannot have the same name. The name {0} cannot be used to name a class while the package {0} is accessible. +javac.err.package.class.conflict=\ + A type and a package cannot have the same name. The name {0} cannot be used to name a package while the class {1} is accessible. +javac.err.package.class.conflict.strong=\ + The name {0} must refer to a package. It is illegal for there to be an accessible class named {1} because types and packages cannot have the same name. The class {1} should be renamed or taken off the classpath. +javac.err.illegal.mangled.name=\ + Invalid name {0} for {1}. +javac.err.class.and.package=\ + Ambiguous name: {0} is both a class and a package. +javac.err.throws.not.throwable=\ + {0} in throws clause must be a subclass of class java.lang.Throwable. +javac.err.throw.not.throwable=\ + Can''t throw {0}; it must be a subclass of class java.lang.Throwable. +javac.err.catch.not.throwable=\ + Can''t catch {0}; it must be a subclass of class java.lang.Throwable. +javac.err.initializer.exception=\ + Exception {0} can''t be thrown in initializer. +javac.err.cant.read=\ + Can''t read: {0} +javac.err.cant.write=\ + Can''t write: {0} +javac.err.fatal.error=\ + An error has occurred in the compiler; please file a bug report (http://bugreport.java.com/bugreport/). +javac.err.fatal.exception=\ + An exception has occurred in the compiler; please file a bug report (http://bugreport.java.com/bugreport/). +javac.err.no.inner.classes=\ + Support for inner classes has been disabled. +javac.err.uncaught.exception=\ + Exception {0} must be caught, or it must be declared in the throws clause of this method. +javac.err.constructor.exception=\ + Exception {0} must be caught, or it must be declared in the throws clause of this constructor. +javac.err.def.constructor.exception=\ + A default constructor cannot be created for this class because the constructor of its superclass throws the exception {0}. Define the constructor for this class explicitly. +javac.err.catch.not.thrown=\ + Exception {0} is never thrown in the body of the corresponding try statement. +#warning: +javac.err.array.clone.supported=\ + Note: The cloning of an array does not throw any checked exceptions, and therefore does not require any catch clauses. Please remove unused catch clauses, or if you wish to retain compatibility with older compilers, you may insert an artificial throw as follows: if (false) throw new CloneNotSupportedException(); +javac.err.no.outer.arg=\ + No enclosing instance of {0} is in scope; \ + an explicit one must be provided when creating {1}, \ + as in "outer. new Inner()" or "outer. super()". +javac.err.no.default.outer.arg=\ + No enclosing instance of {0} is in scope; \ + cannot create a default constructor for {1}. +javac.err.no.outer.base=\ + No enclosing instance of {0} is in scope; \ + an explicit one must be provided when accessing {1}, \ + as in "outer.member". +javac.err.inner.interface=\ + Member interfaces can only occur in interfaces and top-level classes. +javac.err.static.inner.class=\ + The type {0} can''t be static. Static members can only occur in interfaces and top-level classes. +javac.err.static.inner.field=\ + Variable {0} can''t be static in {1}. Only members of interfaces and top-level classes can be static. +javac.err.static.inner.method=\ + Method {0} can''t be static in {1}. Only members of interfaces and top-level classes can be static. +javac.err.too.many.errors=\ + Too many errors. (The limit on reported errors is {0}.) +javac.err.override.static.with.instance=\ + The instance method {0} declared in {1} cannot override the static \ + method of the same signature declared in {2}. It is illegal to \ + override a static method. +javac.err.hide.instance.with.static=\ + The static method {0} declared in {1} cannot hide the instance \ + method of the same signature declared in {2}. It is illegal to \ + hide an instance method. +javac.err.override.final.method=\ + The method {0} declared in {1} cannot override the final method of \ + the same signature declared in {2}. Final methods cannot be \ + overridden. +javac.err.override.is.deprecated=\ + The method {0} declared in {1} is not deprecated, but \ + overrides a deprecated method of the \ + same signature declared in {2}. +javac.err.override.more.restrictive=\ + The method {0} declared in {1} cannot override the method of the \ + same signature declared in {2}. The access modifier is made more \ + restrictive. +javac.err.override.different.return=\ + The method {0} declared in {1} cannot override the method of the \ + same signature declared in {2}. They must have the same return \ + type. +javac.err.override.incompatible.exceptions=\ + The method {0} declared in {1} cannot override the method of the \ + same signature declared in {2}. Their throws clauses are \ + incompatible. +javac.err.meet.different.return=\ + The method {0} inherited from {1} is incompatible with the method of \ + the same signature inherited from {2}. They must have the same \ + return type. +javac.err.nontrivial.meet=\ + The definitions of method {0} inherited from {1} and {2} are \ + compatible, but the combination of them is nontrivial and has not \ + been implemented. As a workaround, declare {0} explicitly in this \ + class. +javac.err.method.too.long=\ + This code requires generating a method with more than \ + 64K bytes. Virtual machines may refuse the resulting class file. +# +javac.err.version.too.old=\ + The major version ''{0}'' is too old for this tool to understand. +javac.err.version.too.recent=\ + The major.minor version ''{0}'' is too recent for this tool \ + to understand. +# +benv.parsed_in=[parsed {0} in {1} ms] +benv.loaded_in=[loaded {0} in {1} ms] +benv.failed_to_close_class_path=failed to close class path: {0} +# +main.usage=\ +Usage: {0} \n\ +\n\ +where includes:\n\ +\ \ -g Generate all debugging info\n\ +\ \ -g:none Generate no debugging info\n\ +\ \ -g:'{'lines,vars,source'}' Generate only some debugging info\n\ +\ \ -O Optimize; may hinder debugging or enlarge class files\n\ +\ \ -nowarn Generate no warnings\n\ +\ \ -verbose Output messages about what the compiler is doing\n\ +\ \ -deprecation Output source locations where deprecated APIs are used\n\ +\ \ -classpath Specify where to find user class files\n\ +\ \ -sourcepath Specify where to find input source files\n\ +\ \ -bootclasspath Override location of bootstrap class files\n\ +\ \ -extdirs Override location of installed extensions\n\ +\ \ -d Specify where to place generated class files\n\ +\ \ -encoding Specify character encoding used by source files\n\ +\ \ -target Generate class files for specific VM version +# +main.unsupported.usage=\ +\ \ -Xdepend Recursively search for more recent source files to recompile\n\ +\ \ -Xstdout Send messages to System.out\n\ +\ \ -Xverbosepath Describe how paths and standard extensions were searched\n\ +\ \ -J Pass argument to the java interpreter\n\ +\n\ +The -X and -J options are non-standard and subject to change without notice. +# +main.conflicting.options=The options {0} and {1} may not be used at the same time. +main.option.already.seen=The {0} option may be specified no more than once. +main.option.requires.argument=The {0} option requires an argument. +main.bad.debug.option=The {0} option is not well formed. Only specify "lines", "vars", and "source" separated by commas. +main.no.such.directory=The {0} directory does not exist. +main.no.such.option={0} is an invalid option or argument. +main.unknown.release=The release ''{0}'' is unknown to this compiler. +main.wrote=[wrote {0}] +main.errors={0} errors +main.1error=1 error +main.warnings={0} warnings +main.1warning=1 warning +main.done_in=[done in {0} ms] +main.no.memory=\ + The compiler has run out of memory. Consider using the "-J-mx" command line option to increase the maximum heap size. +main.stack.overflow=\ + The compiler has run out of stack space. Consider using the "-J-oss" command line option to increase the memory allocated for the Java stack. +main.path.msg=\ + [The source classpath is "{0}"]\n\ + [The library classpath is "{1}"] +javac.err.invalid.encoding.char=\ + The source file encoding may be different with this platform encoding. Please use -encoding option to adjust file encoding, or make sure source file converted to ASCII encoding. diff --git a/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac_ja.properties b/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac_ja.properties new file mode 100644 index 000000000..27c6a5f6c --- /dev/null +++ b/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac_ja.properties @@ -0,0 +1,300 @@ +# +# Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +javac.err.internal=\u5185\u90E8\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002 +javac.err.eof.in.comment=\u30B3\u30E1\u30F3\u30C8\u304C\u5165\u529B\u306E\u6700\u5F8C\u3067\u7D42\u4E86\u3057\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.eof.in.string=\u6587\u5B57\u5217\u304C\u5165\u529B\u306E\u6700\u5F8C\u3067\u7D42\u4E86\u3057\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.newline.in.string=\u6587\u5B57\u5217\u304C\u884C\u306E\u6700\u5F8C\u3067\u7D42\u4E86\u3057\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.invalid.char.constant=\u7121\u52B9\u306A\u6587\u5B57\u5B9A\u6570\u3067\u3059\u3002 +javac.err.unbalanced.paren=\u30AB\u30C3\u30B3\u304C\u4E00\u81F4\u3057\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.invalid.escape.char=\u30A8\u30B9\u30B1\u30FC\u30D7\u6587\u5B57\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.hex.number=16\u9032\u6570\u5B57\u306F\u5C11\u306A\u304F\u3068\u30821\u6841\u306E16\u9032\u6570\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.invalid.octal.number=8\u9032\u6570\u5B57\u5185\u306B\u7121\u52B9\u306A\u6587\u5B57\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.invalid.number=\u6570\u5B57\u5185\u306B\u7121\u52B9\u306A\u6587\u5B57\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.funny.char=\u5165\u529B\u5185\u306B\u7121\u52B9\u306A\u6587\u5B57\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.float.format=\u6D6E\u52D5\u5C0F\u6570\u70B9\u306E\u5F62\u5F0F\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.overflow.int.oct=\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u304C\u7BC4\u56F2\u5916\u3067\u3059\u30028\u9032\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u306F00\u304B\u3089037777777777\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.overflow.int.dec=\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u304C\u7BC4\u56F2\u5916\u3067\u3059\u300210\u9032\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u306F -2147483648\u304B\u30892147483647\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.overflow.int.hex=\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u304C\u7BC4\u56F2\u5916\u3067\u3059\u300216\u9032\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u306F0x0\u304B\u30890xffffffff\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.overflow.long.oct=\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u304C\u7BC4\u56F2\u5916\u3067\u3059\u30028\u9032\u30ED\u30F3\u30B0\u30FB\u30EA\u30C6\u30E9\u30EB\u306F00L\u304B\u308901777777777777777777777L\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.overflow.long.dec=\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u304C\u7BC4\u56F2\u5916\u3067\u3059\u300210\u9032\u30ED\u30F3\u30B0\u30FB\u30EA\u30C6\u30E9\u30EB\u306F -9223372036854775808L\u304B\u30899223372036854775807L\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.overflow.long.hex=\u6574\u6570\u30EA\u30C6\u30E9\u30EB\u304C\u7BC4\u56F2\u5916\u3067\u3059\u300216\u9032\u30ED\u30F3\u30B0\u30FB\u30EA\u30C6\u30E9\u30EB\u306F0x0L\u304B\u30890xffffffffffffffffL\u306E\u7BC4\u56F2\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.overflow.float=\u6570\u5024\u304C\u30AA\u30FC\u30D0\u30FC\u30D5\u30ED\u30FC\u3057\u307E\u3057\u305F: \u6D6E\u52D5\u30EA\u30C6\u30E9\u30EB\u304C\u5927\u304D\u3059\u304E\u307E\u3059\u3002 +javac.err.overflow.double=\u6570\u5024\u304C\u30AA\u30FC\u30D0\u30FC\u30D5\u30ED\u30FC\u3057\u307E\u3057\u305F: \u500D\u7CBE\u5EA6\u30EA\u30C6\u30E9\u30EB\u304C\u5927\u304D\u3059\u304E\u307E\u3059\u3002 +javac.err.underflow.float=\u6570\u5024\u304C\u30A2\u30F3\u30C0\u30FC\u30D5\u30ED\u30FC\u3057\u307E\u3057\u305F: \u6D6E\u52D5\u30EA\u30C6\u30E9\u30EB\u304C\u5C0F\u3055\u3059\u304E\u307E\u3059\u3002 +javac.err.underflow.double=\u6570\u5024\u304C\u30A2\u30F3\u30C0\u30FC\u30D5\u30ED\u30FC\u3057\u307E\u3057\u305F: \u500D\u7CBE\u5EA6\u30EA\u30C6\u30E9\u30EB\u304C\u5C0F\u3055\u3059\u304E\u307E\u3059\u3002 +javac.err.token.expected=''{0}''\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.statement.expected=\u6587\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.type.expected=\u578B\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.identifier.expected=\u8B58\u5225\u5B50\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.class.expected=\u30AD\u30FC\u30EF\u30FC\u30C9''class''\u307E\u305F\u306F''interface''\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.toplevel.expected=\u30AF\u30E9\u30B9\u307E\u305F\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u5BA3\u8A00\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.missing.term=\u9805\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.assign.in.conditionalexpr=\u4EE3\u5165\u5F0F\u306F\u6761\u4EF6\u5F0F(\u3064\u307E\u308A\u3001? : \u5F0F)\u306E3\u756A\u76EE\u306E\u90E8\u5206\u5F0F\u3068\u3057\u3066\u306F\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u3053\u306E\u4EE3\u5165\u5F0F\u3092\u30AB\u30C3\u30B3\u3067\u56F2\u3093\u3067\u5165\u529B\u3057\u3066\u307F\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.else.without.if=''else''\u3078\u306E''if''\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.catch.without.try=''catch''\u3078\u306E''try''\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.finally.without.try=''finally''\u3078\u306E''try''\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.try.without.catch.finally=''try''\u3078\u306E''catch''\u307E\u305F\u306F''finally''\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.case.without.switch=switch\u6587\u306E\u5916\u306B''case''\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.default.without.switch=switch\u6587\u306E\u5916\u306B''default''\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.io.exception={0}\u3067\u5165\u51FA\u529B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002 +javac.err.io.exception.package=\u30D1\u30C3\u30B1\u30FC\u30B8{0}\u306E\u6709\u7121\u3092\u78BA\u8A8D\u4E2D\u306B\u5165\u51FA\u529B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002 +javac.err.malformed.attribute={0}\u3092\u542B\u3080\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u306B\u66F8\u5F0F\u304C\u4E0D\u6B63\u306A\u5C5E\u6027''{1}''\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.array.index.required=\u914D\u5217\u306E\u6DFB\u3048\u5B57\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.not.array=[]\u306F\u914D\u5217\u306B\u306E\u307F\u9069\u7528\u3067\u304D\u307E\u3059\u3002{0}\u306B\u306F\u9069\u7528\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.array.dim.in.decl=\u5BA3\u8A00\u4E2D\u3067\u306F\u914D\u5217\u306E\u6B21\u5143\u3092\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.array.dim.in.type=\u578B\u8868\u73FE\u4E2D\u3067\u306F\u914D\u5217\u306E\u6B21\u5143\u3092\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.invalid.array.expr=\u914D\u5217\u5B9A\u6570\u306F\u521D\u671F\u5316\u5B50\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002 +javac.err.invalid.array.init={0}\u578B\u3078\u306E\u521D\u671F\u5316\u5B50\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.lhs.assignment=\u4EE3\u5165\u306E\u5DE6\u8FBA\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.args={0}\u3078\u306E\u5F15\u6570\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.cast={0}\u304B\u3089{1}\u3078\u306E\u30AD\u30E3\u30B9\u30C8\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.instanceof={0}\u306F{1}\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u306B\u306F\u306A\u308A\u307E\u305B\u3093\u3002 +javac.err.invalid.type.expr=\u578B\u5F0F\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.anonymous.extends=\u540D\u524D\u306E\u306A\u3044\u30AF\u30E9\u30B9\u304C''extends''\u7BC0\u307E\u305F\u306F''implements''\u7BC0\u3092\u6301\u3064\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.invalid.field.reference={1}\u304B\u3089\u30D5\u30A3\u30FC\u30EB\u30C9{0}\u3092\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002 +javac.err.no.such.field={1}\u306B\u306F\u5909\u6570{0}\u306F\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.no.field.access={1}\u5185\u306E\u5909\u6570{0}\u306F{2}\u304B\u3089\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.no.type.access={1}\u5185\u306E\u5185\u90E8\u578B{0}\u306F{2}\u304B\u3089\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.cant.access.member.type=\u30E1\u30F3\u30D0\u30FC{0}\u3092\u6301\u3064\u578B{1}\u306F{2}\u304B\u3089\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.inner.class.expected=\u5185\u90E8\u30AF\u30E9\u30B9{0}\u304C{1}\u306B\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.no.static.field.access={1}\u5185\u306Estatic\u3067\u306A\u3044\u5909\u6570{0}\u3092static\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.inner.static.ref=\u5185\u90E8\u30AF\u30E9\u30B9{0}\u3092static\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.ambig.field={0}\u3078\u306E\u53C2\u7167\u304C\u3042\u3044\u307E\u3044\u3067\u3059\u3002{1}\u3068{2}\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.invalid.field={1}\u5185\u306E\u30E1\u30BD\u30C3\u30C9{0}\u3092\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u5909\u6570\u3068\u3057\u3066\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002 +javac.err.assign.to.final=final\u5909\u6570{0}\u306B\u5024\u3092\u4EE3\u5165\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.assign.to.blank.final=\u30D6\u30E9\u30F3\u30AFfinal\u5909\u6570{0}\u306B2\u56DE\u4EE5\u4E0A\u5024\u3092\u4EE3\u5165\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.qualified.static.final.assign=static\u30D6\u30E9\u30F3\u30AFfinal\u3078\u306E\u4EE3\u5165\u306B\u4F7F\u7528\u3059\u308B\u5909\u6570\u306F\u5358\u7D14\u540D\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059(\u30C9\u30C3\u30C8''.''\u3092\u4ED8\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093)\u3002 +javac.err.bad.qualified.final.assign=\u30D6\u30E9\u30F3\u30AFfinal\u3078\u306E\u4EE3\u5165\u306B\u4F7F\u7528\u3059\u308B\u5909\u6570\u306F\u5358\u7D14\u306A\u540D\u524D\u3001\u307E\u305F\u306F''this''\u3067\u4FEE\u98FE\u3055\u308C\u305F\u5358\u7D14\u306A\u540D\u524D\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059: ''{0}''\u307E\u305F\u306F''this.{0}'' +javac.err.assign.to.blank.final.in.loop=\u30D6\u30E9\u30F3\u30AFfinal\u5909\u6570{0}\u306B\u30EB\u30FC\u30D7\u4E2D\u3067\u4EE3\u5165\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002\u521D\u671F\u5316\u306F\u5FC5\u305A1\u56DE\u9650\u308A\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.assign.to.uplevel=\u5909\u6570{0}\u306B\u7570\u306A\u308B\u30E1\u30BD\u30C3\u30C9\u304B\u3089\u4EE3\u5165\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002\u30AF\u30E9\u30B9\u5B9A\u7FA9\u3092\u56F2\u3080\u30D6\u30ED\u30C3\u30AF\u304B\u3089\u306F\u3001\u5185\u5074\u306E\u30AF\u30E9\u30B9\u3067\u306F\u30D6\u30ED\u30C3\u30AF\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u308B\u5909\u6570\u306E\u3046\u3061\u5C40\u6240\u7684\u306Afinal\u5909\u6570\u306E\u307F\u304C\u6709\u52B9\u3067\u3059\u3002 +javac.err.invalid.uplevel=final\u3067\u306A\u3044\u5909\u6570{0}\u306B\u7570\u306A\u308B\u30E1\u30BD\u30C3\u30C9\u4E2D\u304B\u3089\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002\u30AF\u30E9\u30B9\u5B9A\u7FA9\u3092\u56F2\u3080\u30D6\u30ED\u30C3\u30AF\u304B\u3089\u306F\u3001\u5185\u5074\u306E\u30AF\u30E9\u30B9\u3067\u306F\u30D6\u30ED\u30C3\u30AF\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u308B\u5909\u6570\u306E\u3046\u3061\u5C40\u6240\u7684\u306Afinal\u5909\u6570\u306E\u307F\u304C\u6709\u52B9\u3067\u3059\u3002 +javac.err.undef.var={0}\u306F\u672A\u5B9A\u7FA9\u306E\u5909\u6570\u3067\u3059 +javac.err.undef.var.super={0}\u306F\u672A\u5B9A\u7FA9\u306E\u5909\u6570\u3067\u3059\u3002\u30AD\u30FC\u30EF\u30FC\u30C9"super"\u306F\u3001\u30E1\u30F3\u30D0\u30FC\u306E\u30A2\u30AF\u30BB\u30B9\u307E\u305F\u306F\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u306E\u547C\u51FA\u3057\u306B\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002 +javac.err.undef.var.or.package={0}\u306F\u672A\u5B9A\u7FA9\u306E\u5909\u6570\u307E\u305F\u306F\u30D1\u30C3\u30B1\u30FC\u30B8\u540D\u3067\u3059 +javac.err.undef.class.or.package={0}\u306F\u672A\u5B9A\u7FA9\u306E\u30AF\u30E9\u30B9\u307E\u305F\u306F\u30D1\u30C3\u30B1\u30FC\u30B8\u540D\u3067\u3059 +javac.err.undef.var.class.or.package={0}\u306F\u672A\u5B9A\u7FA9\u306E\u5909\u6570\u3001\u30AF\u30E9\u30B9\u307E\u305F\u306F\u30D1\u30C3\u30B1\u30FC\u30B8\u540D\u3067\u3059 +javac.err.undef.class={0}\u306F\u672A\u5B9A\u7FA9\u306E\u30AF\u30E9\u30B9\u540D\u3067\u3059 +javac.err.undef.var.or.class={0}\u306F\u672A\u5B9A\u7FA9\u306E\u5909\u6570\u307E\u305F\u306F\u30AF\u30E9\u30B9\u540D\u3067\u3059 +javac.err.var.not.initialized=\u5909\u6570{0}\u306F\u521D\u671F\u5316\u3055\u308C\u3066\u3044\u306A\u3044\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.final.var.not.initialized=\u30D6\u30E9\u30F3\u30AFfinal\u5909\u6570''{0}''\u306F\u521D\u671F\u5316\u3055\u308C\u3066\u3044\u306A\u3044\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002\u30D6\u30E9\u30F3\u30AFfinal\u5909\u6570\u306B\u306F\u521D\u671F\u5316\u5B50\u307E\u305F\u306F\u5404\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3067\u5024\u304C\u4EE3\u5165\u3055\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.access.inst.before.super=\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9\u306E\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u304C\u547C\u3073\u51FA\u3055\u308C\u308B\u524D\u306B{0}\u3092\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.ambig.class={0}\u304A\u3088\u3073{1}\u306E\u30AF\u30E9\u30B9\u5B9A\u7FA9\u304C\u3042\u3044\u307E\u3044\u3067\u3059 +javac.err.invalid.arg={0}\u3078\u306E\u5F15\u6570\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.arg.type={1}\u306B\u5BFE\u3059\u308B\u5F15\u6570\u306E\u578B{0}\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.invalid.length=\u578B{0}\u306B''length''\u3092\u9069\u7528\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u304C\u3001\u3053\u308C\u306F\u914D\u5217\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.invalid.constr.invoke=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u4EE5\u5916\u304B\u3089\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3092\u547C\u3073\u51FA\u3059\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.constr.invoke.not.first=\u30E1\u30BD\u30C3\u30C9\u5185\u3067\u306F\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3092\u6700\u521D\u306B\u547C\u3073\u51FA\u3059\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.invalid.method.invoke={0}\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u547C\u3073\u51FA\u3059\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.undef.meth=\u30E1\u30BD\u30C3\u30C9{0}\u306F{1}\u3067\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.no.meth.access={1}\u306E\u30E1\u30BD\u30C3\u30C9{0}\u306F{2}\u304B\u3089\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002 +#warning: +javac.err.no.override.access=\u6CE8\u610F: {1}\u306E\u30E1\u30BD\u30C3\u30C9{0}\u306F{2}\u306E\u5BFE\u5FDC\u3059\u308B\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002\u7570\u306A\u308B\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u5BFE\u3057\u3066\u306Fprivate\u3067\u3042\u308B\u305F\u3081\u3001\u3053\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.no.static.meth.access={1}\u306E\u30E1\u30BD\u30C3\u30C9{0}\u306Bstatic\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.invalid.protected.method.use={1}\u306Eprotected\u30E1\u30BD\u30C3\u30C9{0}\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002{2}\u306F\u73FE\u5728\u306E\u30AF\u30E9\u30B9\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.invalid.protected.field.use={1}\u306Eprotected\u30D5\u30A3\u30FC\u30EB\u30C9{0}\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002{2}\u306F\u73FE\u5728\u306E\u30AF\u30E9\u30B9\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.invalid.protected.type.use={1}\u306Eprotected\u5185\u90E8\u578B{0}\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002{2}\u306F\u73FE\u5728\u306E\u30AF\u30E9\u30B9\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.invalid.protected.constructor.use={0}\u306Eprotected\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u306E\u751F\u6210\u306F\u3001\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u304C\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u308B\u30D1\u30C3\u30B1\u30FC\u30B8\u5185\u3067\u306E\u307F\u8A31\u53EF\u3055\u308C\u307E\u3059\u3002 +javac.err.invalid.method={1}\u306E\u5909\u6570{0}\u3092\u30E1\u30BD\u30C3\u30C9\u3068\u3057\u3066\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002 +javac.err.invalid.var={1}\u306E\u30E1\u30BD\u30C3\u30C9{0}\u3092\u5909\u6570\u3068\u3057\u3066\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002 +javac.err.synchronized.null=null\u306E\u30EA\u30C6\u30E9\u30EB\u306F\u3001synchronized\u69CB\u6587\u3067\u306F\u6B63\u3057\u3044\u5F15\u6570\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +#all messages related to deprecation are warnings: +javac.err.class.is.deprecated=\u6CE8\u610F: {0}\u306F\u63A8\u5968\u3055\u308C\u307E\u305B\u3093\u3002 +javac.err.meth.is.deprecated=\u6CE8\u610F: {1}\u306E\u30E1\u30BD\u30C3\u30C9{0}\u306F\u63A8\u5968\u3055\u308C\u307E\u305B\u3093\u3002 +javac.err.constr.is.deprecated=\u6CE8\u610F: \u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF{0}\u306F\u63A8\u5968\u3055\u308C\u307E\u305B\u3093\u3002 +javac.err.field.is.deprecated=\u6CE8\u610F: {1}\u306E\u5909\u6570{0}\u306F\u63A8\u5968\u3055\u308C\u307E\u305B\u3093\u3002 +javac.err.note.deprecations=\u6CE8\u610F: \u63A8\u5968\u3055\u308C\u306A\u3044API\u3092\u4F7F\u7528\u307E\u305F\u306F\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3057\u3066\u3044\u308B\u30D5\u30A1\u30A4\u30EB\u304C{0}\u500B\u3042\u308A\u307E\u3059\u3002\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167\u3057\u3066\u4ED6\u306E\u65B9\u6CD5\u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.note.1deprecation=\u6CE8\u610F: {0}\u306F\u63A8\u5968\u3055\u308C\u306A\u3044API\u3092\u4F7F\u7528\u307E\u305F\u306F\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3057\u3066\u3044\u307E\u3059\u3002\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167\u3057\u3066\u4ED6\u306E\u65B9\u6CD5\u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.note.deprecations.silent=\u6CE8\u610F: \u63A8\u5968\u3055\u308C\u306A\u3044API\u3092\u4F7F\u7528\u307E\u305F\u306F\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3057\u3066\u3044\u308B\u30D5\u30A1\u30A4\u30EB\u304C{0}\u500B\u3042\u308A\u307E\u3059\u3002\u8A73\u7D30\u306F\u3001"-deprecation"\u3092\u6307\u5B9A\u3057\u3066\u518D\u30B3\u30F3\u30D1\u30A4\u30EB\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.note.1deprecation.silent=\u6CE8\u610F: {0}\u306F\u63A8\u5968\u3055\u308C\u306A\u3044API\u3092\u4F7F\u7528\u307E\u305F\u306F\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3057\u3066\u3044\u307E\u3059\u3002\u8A73\u7D30\u306F\u3001"-deprecation"\u3092\u6307\u5B9A\u3057\u3066\u518D\u30B3\u30F3\u30D1\u30A4\u30EB\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.invalid.array.dim=\u914D\u5217\u306E\u5927\u304D\u3055\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.ambig.constr=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF{0},{1}\u306F\u3042\u3044\u307E\u3044\u3067\u3059\u3002 +javac.err.explicit.cast.needed=\u3053\u306E\u578B\u306F{0}\u306B\u306F\u4E0D\u9069\u5408\u3067\u3059\u3002{1}\u304B\u3089{2}\u3078\u306E\u5909\u63DB\u306B\u306F\u660E\u793A\u7684\u306A\u30AD\u30E3\u30B9\u30C8\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.incompatible.type=\u3053\u306E\u578B\u306F{0}\u306B\u306F\u4E0D\u9069\u5408\u3067\u3059\u3002{1}\u304B\u3089{2}\u306B\u306F\u5909\u63DB\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.invalid.term=\u7121\u52B9\u306A\u9805\u3067\u3059\u3002 +javac.err.abstract.class={0}\u306Fabstract\u30AF\u30E9\u30B9\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\u3053\u306E\u30AF\u30E9\u30B9\u3067\u306F\u3001{2}\u304B\u3089\u6D3E\u751F\u3059\u308B{1}\u3092\u5B9A\u7FA9\u3057\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.abstract.class.cannot.override={0}\u306Fabstract\u3068\u3057\u3066\u5BA3\u8A00\u3055\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9{2}\u306E\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u5BFE\u3057\u3066private\u3067\u3042\u308Babstract\u30E1\u30BD\u30C3\u30C9{1}\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u305A\u3001\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.new.intf={0}\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3059\u3002\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u751F\u6210\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.invoke.abstract={1}\u306E\u30E1\u30BD\u30C3\u30C9{0}\u306Fabstract\u3067\u3042\u308A\u3001\u76F4\u63A5\u547C\u3073\u51FA\u3059\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.unmatched.meth={0}\u306B\u9069\u5408\u3059\u308B\u30E1\u30BD\u30C3\u30C9\u304C{1}\u306B\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.unmatched.constr={0}\u306B\u9069\u5408\u3059\u308B\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u304C{1}\u306B\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.wrong.number.args={0}\u306E\u5F15\u6570\u306E\u6570\u304C\u4E0D\u6B63\u3067\u3059\u3002 +javac.err.wrong.number.args={0}\u306E\u5F15\u6570\u306E\u6570\u304C\u4E0D\u6B63\u3067\u3059\u3002 +javac.err.forward.ref={1}\u3067\u306F{0}\u306B\u524D\u65B9\u53C2\u7167\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.array.dim.missing=\u914D\u5217\u306E\u5927\u304D\u3055\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.new.abstract={0}\u306Fabstract\u30AF\u30E9\u30B9\u3067\u3059\u3002\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u751F\u6210\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.label.not.found={0}\u306E\u30E9\u30D9\u30EB\u5B9A\u7FA9\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.invalid.break=''break''\u306F\u30EB\u30FC\u30D7\u5185\u304Bswitch\u6587\u5185\u306B\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.invalid.continue=''continue''\u306F\u30EB\u30FC\u30D7\u5185\u306B\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.branch.to.uplevel=''break''\u6587\u304A\u3088\u3073''continue''\u6587\u306F\u540C\u4E00\u30E1\u30BD\u30C3\u30C9\u5185\u306B\u306E\u307F\u5206\u5C90\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.invalid.decl=\u7121\u52B9\u306A\u5BA3\u8A00\u3067\u3059\u3002 +javac.err.return.with.value=\u30E1\u30BD\u30C3\u30C9{0}\u3067\u5024\u4ED8\u304D\u306E''return''\u3092\u5B9F\u884C\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002 +javac.err.return.without.value=\u30E1\u30BD\u30C3\u30C9{0}\u3067\u5024\u306A\u3057\u306E''return''\u3092\u5B9F\u884C\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002 +javac.err.return.inside.static.initializer=static\u521D\u671F\u5316\u5B50\u306E\u4E2D\u306B''return''\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.invalid.label=\u7121\u52B9\u306A\u30E9\u30D9\u30EB\u3067\u3059\u3002 +javac.err.return.required.at.end=\u30E1\u30BD\u30C3\u30C9{0}\u306E\u7D42\u308F\u308A\u306Breturn\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.duplicate.label=case\u30E9\u30D9\u30EB{0}\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059 +javac.err.switch.overflow=case\u30E9\u30D9\u30EB{0}\u306F{1}\u306Eswitch\u6587\u306E\u7BC4\u56F2\u3092\u8D85\u3048\u3066\u3044\u307E\u3059 +javac.err.nested.duplicate.label=\u6587\u306B\u306F\u3001\u305D\u308C\u3092\u56F2\u3080\u6587\u3068\u540C\u3058\u8B58\u5225\u5B50{0}\u3067\u30E9\u30D9\u30EB\u3092\u4ED8\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.declaration.with.label=\u5BA3\u8A00\u306B\u306F\u30E9\u30D9\u30EB{0}\u3092\u4ED8\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.const.expr.required=\u5B9A\u6570\u5F0F\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.duplicate.default=''default''\u30E9\u30D9\u30EB\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059\u3002 +javac.err.not.supported=''{0}''\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.return.with.value.constr=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF{0}\u3067\u5024\u4ED8\u304D\u306E''return''\u3092\u5B9F\u884C\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F +javac.err.package.repeated=\u30D1\u30C3\u30B1\u30FC\u30B8\u5BA3\u8A00\u306F1\u56DE\u306E\u307F\u53EF\u80FD\u3067\u3059\u3002 +javac.err.class.multidef=\u30AF\u30E9\u30B9{0}\u306F\u3059\u3067\u306B{1}\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.class.multidef.import=\u30AF\u30E9\u30B9\u540D{0}\u306F\u30A4\u30F3\u30DD\u30FC\u30C8\u3055\u308C\u305F\u30AF\u30E9\u30B9{1}\u3068\u7AF6\u5408\u3057\u307E\u3059\u3002 +javac.err.intf.constructor=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306F\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3092\u6301\u3064\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.constr.modifier=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF{0}\u3092native\u3001abstract\u3001static\u3001synchronized\u307E\u305F\u306Ffinal\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.intf.initializer=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306Fstatic\u521D\u671F\u5316\u5B50\u3092\u6301\u3064\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.intf.modifier.method=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306E\u30E1\u30BD\u30C3\u30C9{0}\u3092native\u3001static\u3001synchronized\u3001final\u3001private\u307E\u305F\u306Fprotected\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.intf.modifier.field=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306E\u30D5\u30A3\u30FC\u30EB\u30C9{0}\u3092private\u307E\u305F\u306Fprotected\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.transient.meth=\u30E1\u30BD\u30C3\u30C9{0}\u3092transient\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002transient\u306F\u5909\u6570\u306B\u306E\u307F\u9069\u7528\u3055\u308C\u307E\u3059\u3002 +javac.err.volatile.meth=\u30E1\u30BD\u30C3\u30C9{0}\u3092volatile\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002volatile\u306F\u5909\u6570\u306B\u306E\u307F\u9069\u7528\u3055\u308C\u307E\u3059\u3002 +javac.err.abstract.private.modifier=abstract\u30E1\u30BD\u30C3\u30C9{0}\u3092private\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.abstract.static.modifier=abstract\u30E1\u30BD\u30C3\u30C9{0}\u3092static\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.abstract.final.modifier=abstract\u30E1\u30BD\u30C3\u30C9{0}\u3092final\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.abstract.native.modifier=abstract\u30E1\u30BD\u30C3\u30C9{0}\u3092native\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.abstract.synchronized.modifier=abstract\u30E1\u30BD\u30C3\u30C9{0}\u3092synchronized\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.invalid.meth.body={0}\u306Fabstract\u30E1\u30BD\u30C3\u30C9\u304Bnative\u30E1\u30BD\u30C3\u30C9\u306A\u306E\u3067\u3001\u672C\u4F53\u3092\u6301\u3064\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.var.modifier=\u5909\u6570{0}\u3092synchronized\u3001abstract\u307E\u305F\u306Fnative\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.var.floatmodifier=\u5909\u6570{0}\u3092strict\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.inner.modifier=\u5185\u90E8\u30AF\u30E9\u30B9{0}\u3092volatile\u3001transient\u3001native\u307E\u305F\u306Fsynchronized\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.transient.modifier=transient\u5909\u6570{0}\u3092\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u30FB\u30E1\u30F3\u30D0\u30FC\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.volatile.modifier=volatile\u5909\u6570{0}\u3092final\u307E\u305F\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u30FB\u30E1\u30F3\u30D0\u30FC\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.initializer.needed=final\u5909\u6570{0}\u306F\u521D\u671F\u5316\u3055\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059 +javac.err.meth.multidef=\u30E1\u30BD\u30C3\u30C9\u5BA3\u8A00{0}\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059 +javac.err.meth.redef.rettype=\u540C\u3058\u5F15\u6570\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u7570\u306A\u308B\u623B\u308A\u5024\u306E\u578B\u3067\u518D\u5B9A\u7FA9\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002{0}\u306F\u4EE5\u524D{1}\u3068\u5BA3\u8A00\u3055\u308C\u3066\u3044\u307E\u3057\u305F +javac.err.var.multidef=\u5909\u6570\u5BA3\u8A00\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059\u3002{0}\u306F\u4EE5\u524D{1}\u3068\u5BA3\u8A00\u3055\u308C\u3066\u3044\u307E\u3057\u305F +javac.err.inner.class.multidef=\u5185\u90E8\u30AF\u30E9\u30B9\u5BA3\u8A00\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059\u3002{0}\u306F\u3053\u306E\u30B9\u30B3\u30FC\u30D7\u3067\u3059\u3067\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.intf.super.class={0}\u306E\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9{1}\u3092\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.cant.access.class={0}\u306B\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093\u3002\u30AF\u30E9\u30B9\u307E\u305F\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306F\u3001\u540C\u3058\u30D1\u30C3\u30B1\u30FC\u30B8\u307E\u305F\u306F\u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u306A\u30E1\u30F3\u30D0\u30FC\u30FB\u30AF\u30E9\u30B9\u3067\u306Fpublic\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.unqualified.name.required=\u4FEE\u98FE\u3055\u308C\u305Fnew\u5F0F\u306B\u304A\u3051\u308B\u578B\u540D\u306F\u3001\u4FEE\u98FE\u3055\u308C\u3066\u3044\u306A\u3044\u8B58\u5225\u5B50\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.repeated.modifier=\u4FEE\u98FE\u5B50\u304C\u7E70\u308A\u8FD4\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.inconsistent.modifier=\u30E1\u30F3\u30D0\u30FC\u5BA3\u8A00\u306B\u4E00\u8CAB\u6027\u304C\u3042\u308A\u307E\u305B\u3093\u3002public\u3001private\u307E\u305F\u306Fprotected\u306E\u3046\u3061\u306E1\u3064\u306E\u307F\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002 +javac.err.super.is.final=final\u30AF\u30E9\u30B9{0}\u304B\u3089\u30B5\u30D6\u30AF\u30E9\u30B9\u3092\u751F\u6210\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.super.is.intf=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9{0}\u304B\u3089\u30B5\u30D6\u30AF\u30E9\u30B9\u3092\u751F\u6210\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.cyclic.super=\u30AF\u30E9\u30B9\u7D99\u627F\u304C\u30EB\u30FC\u30D7\u3057\u3066\u3044\u307E\u3059\u3002 +javac.err.super.is.inner=\u30AF\u30E9\u30B9\u7D99\u627F\u304C\u30EB\u30FC\u30D7\u3057\u3066\u3044\u307E\u3059\u3002\u30B5\u30D6\u30AF\u30E9\u30B9\u306F\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9\u3092\u56F2\u3080\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.cyclic.intf=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u7D99\u627F\u304C\u30EB\u30FC\u30D7\u3057\u3066\u3044\u307E\u3059\u3002 +javac.err.cyclic.scoping=\u30AF\u30E9\u30B9\u7D99\u627F\u307E\u305F\u306F\u30B9\u30B3\u30FC\u30D7\u304C\u30EB\u30FC\u30D7\u3057\u3066\u3044\u307E\u3059\u3002 +javac.err.not.intf={0}\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.final.intf=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9{0}\u3092final\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.intf.impl.intf=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306Fimplements\u7BC0\u3092\u542B\u3080\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002extends\u7BC0\u306B\u3088\u308A\u4ED6\u306E\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u3092\u62E1\u5F35\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u3059\u3002 +javac.err.multiple.inherit=\u591A\u91CD\u7D99\u627F\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002 +javac.err.intf.repeated=\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9{0}\u304C\u7E70\u308A\u8FD4\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.class.format={0}\u306E\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB{1}\u306E\u5F62\u5F0F\u304C\u7121\u52B9\u3067\u3059 +javac.err.truncated.class=\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB{0}\u306E\u8AAD\u8FBC\u307F\u4E2D\u306B\u4E88\u671F\u3057\u306A\u3044\u30D5\u30A1\u30A4\u30EB\u306E\u7D42\u308F\u308A\u304C\u691C\u51FA\u3055\u308C\u307E\u3057\u305F\u3002 +javac.err.no.meth.body=\u30E1\u30BD\u30C3\u30C9{0}\u306B\u306F\u672C\u4F53\u304C\u5FC5\u8981\u3067\u3059\u3002\u3042\u308B\u3044\u306Fabstract\u3068\u3057\u3066\u5BA3\u8A00\u3057\u307E\u3059\u3002 +javac.err.no.constructor.body=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF{0}\u306B\u306F\u30E1\u30BD\u30C3\u30C9\u672C\u4F53\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.bad.constructor.modifier=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u306Fstrictfp\u3067\u4FEE\u98FE\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.void.inst.var=\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u5909\u6570{0}\u3092void\u578B\u306B\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.invalid.method.decl=\u7121\u52B9\u306A\u30E1\u30BD\u30C3\u30C9\u5BA3\u8A00\u3067\u3059\u3002\u623B\u308A\u5024\u306E\u578B\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.invalid.method.decl.name=\u7121\u52B9\u306A\u30E1\u30BD\u30C3\u30C9\u5BA3\u8A00\u3067\u3059\u3002\u30E1\u30BD\u30C3\u30C9\u540D\u304C\u5FC5\u8981\u3067\u3059\u3002 +javac.err.invalid.method.decl.qual=\u4FEE\u98FE\u3055\u308C\u305F\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u540D\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.super.not.found={1}\u306E\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.intf.not.found={1}\u306E\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.final.abstract=\u30AF\u30E9\u30B9{0}\u3092abstract\u3068final\u306E\u4E21\u65B9\u306B\u5BA3\u8A00\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.void.array=void\u306E\u914D\u5217\u306E\u578B\u304C\u7121\u52B9\u3067\u3059\u3002 +javac.err.void.argument=\u5F15\u6570{0}\u3092void\u578B\u306B\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 +javac.err.invalid.expr=\u7121\u52B9\u306A\u5F0F\u6587\u3067\u3059\u3002 +javac.err.catch.not.reached=\u3053\u306Ecatch\u7BC0\u306B\u5236\u5FA1\u304C\u79FB\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.stat.not.reached=\u3053\u306E\u6587\u306B\u5236\u5FA1\u304C\u79FB\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.init.no.normal.completion=\u521D\u671F\u5316\u5B50\u306F\u6B63\u5E38\u306B\u5B8C\u4E86\u3067\u304D\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.arithmetic.exception=\u6F14\u7B97\u4E0A\u306E\u4F8B\u5916\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002 +javac.err.generic={0} +javac.err.public.class.file=public\u306A\u30AF\u30E9\u30B9{0}\u306F\u3001\u30D5\u30A1\u30A4\u30EB"{1}"\u3067\u5B9A\u7FA9\u3055\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.package.class.file={0}\u306F{1}\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u3053\u306E\u30BD\u30FC\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u5916\u3067\u5229\u7528\u3055\u308C\u3066\u3044\u308B\u306E\u3067\u3001\u30D5\u30A1\u30A4\u30EB"{2}"\u3067\u5B9A\u7FA9\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.lose.precision=\u7CBE\u5EA6\u304C\u843D\u3061\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002{0}\u304B\u3089{1}\u3078\u306E\u5909\u63DB\u306B\u306F\u3001\u660E\u793A\u7684\u306A\u30AD\u30E3\u30B9\u30C8\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002 +javac.err.duplicate.argument=\u5909\u6570\u540D''{0}''\u304C\u30E1\u30BD\u30C3\u30C9\u5F15\u6570\u30672\u56DE\u4EE5\u4E0A\u4F7F\u7528\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.local.redefined=\u5909\u6570''{0}''\u306F\u3059\u3067\u306B\u3053\u306E\u30E1\u30BD\u30C3\u30C9\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.local.class.redefined=\u5C40\u6240\u30AF\u30E9\u30B9''{0}''\u306F\u3059\u3067\u306B\u3053\u306E\u30E1\u30BD\u30C3\u30C9\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.inner.redefined=\u30AF\u30E9\u30B9\u540D''{0}''\u306F\u3059\u3067\u306B\u3053\u306E\u30B9\u30B3\u30FC\u30D7\u5185\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002\u5185\u90E8\u30AF\u30E9\u30B9\u306F\u305D\u308C\u3092\u56F2\u3080\u30AF\u30E9\u30B9\u3068\u540C\u3058\u5358\u7D14\u540D\u3092\u6301\u3064\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.inherited.hides.field=\u5909\u6570''{0}''\u306F{1}\u3067\u7D99\u627F\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001{2}\u306E\u540C\u540D\u306E\u5909\u6570\u3092\u8986\u3044\u96A0\u3057\u3066\u3044\u307E\u3059\u3002\u660E\u793A\u7684\u306B''this''\u4FEE\u98FE\u5B50\u3092\u4F7F\u7528\u3057\u3066\u76EE\u7684\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.inherited.hides.local=\u5909\u6570''{0}''\u306F{1}\u3067\u7D99\u627F\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u540C\u540D\u306E\u5C40\u6240\u5909\u6570\u3092\u8986\u3044\u96A0\u3057\u3066\u3044\u307E\u3059\u3002\u660E\u793A\u7684\u306B''this''\u4FEE\u98FE\u5B50\u3092\u4F7F\u7528\u3057\u3066\u3069\u3061\u3089\u306E\u5909\u6570\u3067\u3042\u308B\u304B\u3092\u6307\u5B9A\u3059\u308B\u304B\u3001\u3042\u308B\u3044\u306F\u5C40\u6240\u5909\u6570\u306E\u540D\u524D\u3092\u5909\u66F4\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.inherited.hides.method=\u30E1\u30BD\u30C3\u30C9''{0}''\u306F{1}\u3067\u7D99\u627F\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001{2}\u306E\u540C\u540D\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u8986\u3044\u96A0\u3057\u3066\u3044\u307E\u3059\u3002\u660E\u793A\u7684\u306B''this''\u4FEE\u98FE\u5B50\u3092\u4F7F\u7528\u3057\u3066\u3069\u3061\u3089\u306E\u30E1\u30BD\u30C3\u30C9\u3067\u3042\u308B\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.inherited.hides.type=\u578B''{0}''\u306F{1}\u3067\u7D99\u627F\u3055\u308C\u3066\u3044\u307E\u3059\u304C\u3001\u30AF\u30E9\u30B9\u5B9A\u7FA9\u3092\u56F2\u3080\u30B9\u30B3\u30FC\u30D7\u306B\u3042\u308B\u540C\u540D\u306E\u578B\u3092\u8986\u3044\u96A0\u3057\u3066\u3044\u307E\u3059\u3002\u660E\u793A\u7684\u306B\u524D\u7F6E\u4FEE\u98FE\u5B50\u3092\u4F7F\u7528\u3057\u3066\u3069\u3061\u3089\u306E\u578B\u3067\u3042\u308B\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.private.class=\u578B{0}\u3092private\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002\u30D1\u30C3\u30B1\u30FC\u30B8\u306E\u30E1\u30F3\u30D0\u30FC\u306F\u5E38\u306B\u305D\u306E\u30D1\u30C3\u30B1\u30FC\u30B8\u5185\u304B\u3089\u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u3067\u3059\u3002 +javac.err.static.class=\u578B{0}\u3092static\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002\u3053\u306E\u578B\u306F\u30D1\u30C3\u30B1\u30FC\u30B8\u306E\u30E1\u30F3\u30D0\u30FC\u306A\u306E\u3067\u3001\u3059\u3067\u306B\u30C8\u30C3\u30D7\u30FB\u30EC\u30D9\u30EB\u306B\u3042\u308A\u307E\u3059\u3002 +javac.err.protected.class=\u578B{0}\u3092protected\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002\u30D1\u30C3\u30B1\u30FC\u30B8\u306E\u30E1\u30F3\u30D0\u30FC\u306F\u3001public\u3067\u3042\u308B\u304B\u3001\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u5C40\u6240\u7684\u3067\u3042\u308B\u304B\u306E\u3069\u3061\u3089\u304B\u3067\u3059\u3002 +javac.err.recursive.constr=\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u306E\u547C\u51FA\u3057\u304C\u518D\u5E30\u7684\u3067\u3059: {0}\u3002 +javac.err.wrong.class=\u30D5\u30A1\u30A4\u30EB{0}\u306B\u306F{1}\u304C\u542B\u307E\u308C\u308B\u3068\u307F\u306A\u3055\u308C\u3066\u3044\u307E\u3057\u305F\u304C\u3001\u542B\u307E\u308C\u3066\u3044\u305F\u306E\u306F{2}\u3067\u3057\u305F\u3002\u30D5\u30A1\u30A4\u30EB\u3092\u30AF\u30EA\u30A2\u3059\u308B\u304B\u3001\u30AF\u30E9\u30B9\u30D1\u30B9\u306B\u542B\u307E\u308C\u308B\u9069\u5207\u306A\u30B5\u30D6\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306B\u79FB\u52D5\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.wrong.source=\u30D5\u30A1\u30A4\u30EB{0}\u306B\u306F{1}\u306F\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u30AF\u30E9\u30B9\u30D1\u30B9\u3092\u5909\u66F4\u3057\u3066\u3001\u30D5\u30A1\u30A4\u30EB\u304C{2}\u306B\u306A\u3044\u3088\u3046\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.class.not.found=\u30AF\u30E9\u30B9{0}\u304C{1}\u306B\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.class.not.found.no.context=\u30AF\u30E9\u30B9{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.package.not.found=\u30D1\u30C3\u30B1\u30FC\u30B8{0}\u304C{1}\u306B\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002 +javac.err.package.not.found.strong=\u30D1\u30C3\u30B1\u30FC\u30B8{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002\u30D1\u30C3\u30B1\u30FC\u30B8{0}\u304C\u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u306B\u306A\u308B\u3088\u3046\u306B\u30AF\u30E9\u30B9\u30D1\u30B9\u3092\u8ABF\u6574\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.class.package.conflict=\u578B\u3068\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u540C\u3058\u540D\u524D\u3092\u4ED8\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002\u30D1\u30C3\u30B1\u30FC\u30B8{0}\u306F\u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u3067\u3059\u304C\u3001\u30AF\u30E9\u30B9\u540D\u306B{0}\u3092\u4F7F\u7528\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.package.class.conflict=\u578B\u3068\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u540C\u3058\u540D\u524D\u3092\u4ED8\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002\u30AF\u30E9\u30B9{1}\u306F\u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u3067\u3059\u304C\u3001\u30D1\u30C3\u30B1\u30FC\u30B8\u540D\u306B{0}\u3092\u4F7F\u7528\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.package.class.conflict.strong=\u540D\u524D{0}\u306F\u30D1\u30C3\u30B1\u30FC\u30B8\u3092\u53C2\u7167\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\u578B\u3068\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u306F\u540C\u3058\u540D\u524D\u3092\u4ED8\u3051\u308B\u3053\u3068\u306F\u3067\u304D\u306A\u3044\u305F\u3081\u3001{1}\u3068\u3044\u3046\u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u306A\u30AF\u30E9\u30B9\u306E\u540D\u524D\u306F\u7121\u52B9\u3067\u3059\u3002\u30AF\u30E9\u30B9{1}\u306E\u540D\u524D\u3092\u5909\u66F4\u3059\u308B\u304B\u3001\u30AF\u30E9\u30B9\u30D1\u30B9\u304B\u3089\u524A\u9664\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.illegal.mangled.name={1}\u306B\u5BFE\u3057\u3066\u540D\u524D{0}\u306F\u4E0D\u6B63\u3067\u3059\u3002 +javac.err.class.and.package={0}\u306F\u30AF\u30E9\u30B9\u304B\u30D1\u30C3\u30B1\u30FC\u30B8\u304B\u306E\u533A\u5225\u304C\u3064\u304D\u307E\u305B\u3093\u3002 +javac.err.throws.not.throwable=throws\u7BC0\u306E\u4F8B\u5916{0}\u306F\u30AF\u30E9\u30B9java.lang.Throwable\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.throw.not.throwable=\u4F8B\u5916{0}\u306F\u30B9\u30ED\u30FC\u3067\u304D\u307E\u305B\u3093\u3002\u4F8B\u5916\u306F\u30AF\u30E9\u30B9java.lang.Throwable\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.catch.not.throwable=\u4F8B\u5916{0}\u306F\u6355\u6349\u3067\u304D\u307E\u305B\u3093\u3002\u4F8B\u5916\u306F\u30AF\u30E9\u30B9java.lang.Throwable\u306E\u30B5\u30D6\u30AF\u30E9\u30B9\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.initializer.exception=\u521D\u671F\u5316\u5B50\u5185\u3067\u306F\u4F8B\u5916{0}\u3092\u30B9\u30ED\u30FC\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.cant.read={0}\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093 +javac.err.cant.write={0}\u304C\u66F8\u304D\u8FBC\u3081\u307E\u305B\u3093 +javac.err.fatal.error=\u30B3\u30F3\u30D1\u30A4\u30E9\u5185\u90E8\u3067\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002http://bugreport.java.com/bugreport/\u3067\u30D0\u30B0\u5831\u544A\u3092\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.fatal.exception=\u30B3\u30F3\u30D1\u30A4\u30E9\u5185\u90E8\u3067\u4F8B\u5916\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002http://bugreport.java.com/bugreport/\u3067\u30D0\u30B0\u5831\u544A\u3092\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.no.inner.classes=\u5185\u90E8\u30AF\u30E9\u30B9\u306E\u30B5\u30DD\u30FC\u30C8\u306F\u4E2D\u6B62\u3055\u308C\u307E\u3057\u305F\u3002 +javac.err.uncaught.exception=\u4F8B\u5916{0}\u306F\u6355\u6349\u3055\u308C\u308B\u304B\u3001\u3042\u308B\u3044\u306F\u3053\u306E\u30E1\u30BD\u30C3\u30C9\u306Ethrows\u7BC0\u3067\u5BA3\u8A00\u3055\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.constructor.exception=\u4F8B\u5916{0}\u306F\u6355\u6349\u3055\u308C\u308B\u304B\u3001\u307E\u305F\u306F\u3053\u306E\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u306Ethrows\u7BC0\u3067\u5BA3\u8A00\u3055\u308C\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.def.constructor.exception=\u30B9\u30FC\u30D1\u30FC\u30AF\u30E9\u30B9\u306E\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u304C\u4F8B\u5916{0}\u3092\u30B9\u30ED\u30FC\u3059\u308B\u305F\u3081\u3001\u30C7\u30D5\u30A9\u30EB\u30C8\u306E\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3092\u3053\u306E\u30AF\u30E9\u30B9\u7528\u306B\u751F\u6210\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093\u3002\u3053\u306E\u30AF\u30E9\u30B9\u306E\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3092\u660E\u793A\u7684\u306B\u5B9A\u7FA9\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.catch.not.thrown=\u4F8B\u5916{0}\u306F\u5BFE\u5FDC\u3059\u308Btry\u6587\u306E\u672C\u4F53\u3067\u30B9\u30ED\u30FC\u3055\u308C\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002 +#warning: +javac.err.array.clone.supported=\u6CE8\u610F: \u914D\u5217\u306E\u8907\u88FD\u306F\u78BA\u8A8D\u6E08\u4F8B\u5916\u3092\u30B9\u30ED\u30FC\u3059\u308B\u3053\u3068\u306F\u306A\u3044\u306E\u3067\u3001catch\u7BC0\u306F\u4E0D\u8981\u3067\u3059\u3002\u4E0D\u8981\u306Acatch\u7BC0\u3092\u524A\u9664\u3059\u308B\u304B\u3001\u3042\u308B\u3044\u306F\u4EE5\u524D\u306E\u30B3\u30F3\u30D1\u30A4\u30E9\u3068\u306E\u4E92\u63DB\u6027\u3092\u4FDD\u3061\u305F\u3044\u5834\u5408\u306F\u3001\u6B21\u306E\u3088\u3046\u306A\u64EC\u4F3C\u7684\u306Athrow\u6587\u3092\u633F\u5165\u3057\u3066\u304F\u3060\u3055\u3044: if(false)throw new CloneNotSupportedException()\u3002 +javac.err.no.outer.arg=\u5185\u90E8\u30AF\u30E9\u30B9\u3092\u56F2\u3080{0}\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u304C\u30B9\u30B3\u30FC\u30D7\u5185\u306B\u3042\u308A\u307E\u305B\u3093\u3002\u5185\u90E8\u30AF\u30E9\u30B9\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093\u3002{1}\u3092\u751F\u6210\u3059\u308B\u5834\u5408\u306B\u306F\u3001"outer. new Inner()"\u307E\u305F\u306F"outer. super()"\u306E\u3088\u3046\u306B\u660E\u793A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.no.default.outer.arg=\u5185\u90E8\u30AF\u30E9\u30B9\u3092\u56F2\u3080{0}\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u304C\u30B9\u30B3\u30FC\u30D7\u5185\u306B\u3042\u308A\u307E\u305B\u3093\u3002{1}\u306B\u3064\u3044\u3066\u306F\u30C7\u30D5\u30A9\u30EB\u30C8\u306E\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.no.outer.base=\u5185\u90E8\u30AF\u30E9\u30B9\u3092\u56F2\u3080{0}\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u304C\u30B9\u30B3\u30FC\u30D7\u5185\u306B\u3042\u308A\u307E\u305B\u3093\u3002{1}\u306B\u30A2\u30AF\u30BB\u30B9\u3059\u308B\u5834\u5408\u306F\u3001"outer.member"\u306A\u3069\u306E\u3088\u3046\u306B\u660E\u793A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.inner.interface=\u30E1\u30F3\u30D0\u30FC\u30FB\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u304B\u30C8\u30C3\u30D7\u30FB\u30EC\u30D9\u30EB\u30FB\u30AF\u30E9\u30B9\u306B\u306E\u307F\u8A31\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.static.inner.class=\u578B{0}\u3092static\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002static\u30E1\u30F3\u30D0\u30FC\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u304B\u30C8\u30C3\u30D7\u30FB\u30EC\u30D9\u30EB\u30FB\u30AF\u30E9\u30B9\u306B\u306E\u307F\u8A31\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.static.inner.field=\u5909\u6570{0}\u306F{1}\u3067static\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002static\u30E1\u30F3\u30D0\u30FC\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u304B\u30C8\u30C3\u30D7\u30FB\u30EC\u30D9\u30EB\u30FB\u30AF\u30E9\u30B9\u306B\u306E\u307F\u8A31\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.static.inner.method=\u30E1\u30BD\u30C3\u30C9{0}\u306F{1}\u3067static\u3068\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093\u3002static\u30E1\u30F3\u30D0\u30FC\u306F\u30A4\u30F3\u30BF\u30D5\u30A7\u30FC\u30B9\u304B\u30C8\u30C3\u30D7\u30FB\u30EC\u30D9\u30EB\u30FB\u30AF\u30E9\u30B9\u306B\u306E\u307F\u8A31\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +javac.err.too.many.errors=\u30A8\u30E9\u30FC\u6570\u304C\u4E0A\u9650\u3092\u8D85\u3048\u307E\u3057\u305F\u3002(\u5831\u544A\u3059\u308B\u30A8\u30E9\u30FC\u306E\u4E0A\u9650\u306F{0}\u3067\u3059\u3002) +javac.err.override.static.with.instance={1}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u30FB\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306Estatic\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002static\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\u306E\u306F\u7121\u52B9\u3067\u3059\u3002 +javac.err.hide.instance.with.static={1}\u3067\u5BA3\u8A00\u3055\u308C\u305Fstatic\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306Estatic\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002static\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u30FB\u30E1\u30BD\u30C3\u30C9\u3092\u8986\u3044\u96A0\u3059\u306E\u306F\u7121\u52B9\u3067\u3059\u3002 +javac.err.override.final.method={1}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306Efinal\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002final\u30E1\u30BD\u30C3\u30C9\u306F\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.override.is.deprecated={1}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306F\u63A8\u5968\u3055\u308C\u306A\u3044\u3082\u306E\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u304C\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306E\u63A8\u5968\u3055\u308C\u306A\u3044\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3057\u307E\u3059\u3002 +javac.err.override.more.restrictive={1}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002\u30A2\u30AF\u30BB\u30B9\u4FEE\u98FE\u5B50\u306F\u3055\u3089\u306B\u5236\u9650\u3055\u308C\u3066\u4F5C\u6210\u3055\u308C\u307E\u3059\u3002 +javac.err.override.different.return={1}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002\u540C\u3058\u578B\u306E\u623B\u308A\u5024\u3092\u6301\u3064\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\t +javac.err.override.incompatible.exceptions={1}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u3067\u5BA3\u8A00\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306E\u30E1\u30BD\u30C3\u30C9\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u305B\u3093\u3002\u305D\u308C\u3089\u306Ethrows\u7BC0\u306B\u306F\u4E92\u63DB\u6027\u304C\u3042\u308A\u307E\u305B\u3093\u3002 +javac.err.meet.different.return={1}\u304B\u3089\u7D99\u627F\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306F\u3001{2}\u304B\u3089\u7D99\u627F\u3055\u308C\u305F\u540C\u3058\u30B7\u30B0\u30CB\u30C1\u30E3\u306E\u30E1\u30BD\u30C3\u30C9\u3068\u4E92\u63DB\u6027\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u540C\u3058\u578B\u306E\u623B\u308A\u5024\u3092\u6301\u3064\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002 +javac.err.nontrivial.meet={1}\u3068{2}\u304B\u3089\u7D99\u627F\u3055\u308C\u305F\u30E1\u30BD\u30C3\u30C9{0}\u306E\u5B9A\u7FA9\u306F\u4E92\u63DB\u6027\u304C\u3042\u308A\u307E\u3059\u304C\u3001\u305D\u308C\u3089\u306E\u7D44\u5408\u305B\u306F\u5F71\u97FF\u304C\u5927\u304D\u3044\u305F\u3081\u5B9F\u88C5\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u56DE\u907F\u65B9\u6CD5\u3068\u3057\u3066\u306F\u3001\u3053\u306E\u30AF\u30E9\u30B9\u3067\u660E\u793A\u7684\u306B{0}\u3092\u5BA3\u8A00\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +javac.err.method.too.long=\u3053\u306E\u30B3\u30FC\u30C9\u306F64KB\u3092\u8D85\u3048\u308B\u30B5\u30A4\u30BA\u306E\u30E1\u30BD\u30C3\u30C9\u306E\u751F\u6210\u3092\u5FC5\u8981\u3068\u3057\u307E\u3059\u3002Virtual Machine\u306F\u751F\u6210\u3055\u308C\u308B\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u62D2\u5426\u3057\u307E\u3059\u3002 +# +javac.err.version.too.old=\u30E1\u30B8\u30E3\u30FC\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3''{0}''\u306F\u53E4\u3044\u305F\u3081\u3001\u3053\u306E\u30C4\u30FC\u30EB\u3067\u306F\u8A8D\u8B58\u3067\u304D\u307E\u305B\u3093\u3002 +javac.err.version.too.recent=\u30E1\u30B8\u30E3\u30FC.\u30DE\u30A4\u30CA\u30FC\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3''{0}''\u306F\u65B0\u3057\u3044\u305F\u3081\u3001\u3053\u306E\u30C4\u30FC\u30EB\u3067\u306F\u8A8D\u8B58\u3067\u304D\u307E\u305B\u3093\u3002 +# +benv.parsed_in=[{0}\u3092{1}\u30DF\u30EA\u79D2\u3067\u69CB\u6587\u89E3\u6790\u3057\u307E\u3057\u305F] +benv.loaded_in=[{0}\u3092{1}\u30DF\u30EA\u79D2\u3067\u8AAD\u307F\u8FBC\u307F\u307E\u3057\u305F] +benv.failed_to_close_class_path=\u30AF\u30E9\u30B9\u30D1\u30B9: {0}\u3092\u9589\u3058\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F +# +main.usage=\u4F7F\u7528\u65B9\u6CD5: {0} \n\n\u306B\u306F\u6B21\u306E\u3082\u306E\u304C\u3042\u308A\u307E\u3059\u3002\n\\ -g \u3059\u3079\u3066\u306E\u30C7\u30D0\u30C3\u30B0\u60C5\u5831\u3092\u751F\u6210\u3059\u308B\n\\ -g:none \u30C7\u30D0\u30C3\u30B0\u60C5\u5831\u3092\u751F\u6210\u3057\u306A\u3044\n\\ -g:'{'lines,vars,source'}'\u3044\u304F\u3064\u304B\u306E\u30C7\u30D0\u30C3\u30B0\u60C5\u5831\u306E\u307F\u3092\u751F\u6210\u3059\u308B\n\\ -O \u6700\u9069\u5316;\u30C7\u30D0\u30C3\u30B0\u3092\u6291\u5236\u3057\u3001\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u5927\u304D\u304F\u3059\u308B\n\\ -nowarn \u8B66\u544A\u3092\u767A\u751F\u3055\u305B\u306A\u3044\n\\ -verbose \u30B3\u30F3\u30D1\u30A4\u30E9\u306E\u52D5\u4F5C\u306B\u3064\u3044\u3066\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u51FA\u529B\u3059\u308B\n\\ -deprecation \u63A8\u5968\u3055\u308C\u306A\u3044API\u304C\u4F7F\u7528\u3055\u308C\u3066\u3044\u308B\u30BD\u30FC\u30B9\u306E\u4F4D\u7F6E\u3092\u51FA\u529B\u3059\u308B\n\\ -classpath \u30E6\u30FC\u30B6\u30FC\u30FB\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u306E\u3042\u308B\u5834\u6240\u3092\u6307\u5B9A\u3059\u308B\n\\ -sourcepath \u5165\u529B\u30BD\u30FC\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u306E\u3042\u308B\u5834\u6240\u3092\u6307\u5B9A\u3059\u308B\n\\ -bootclasspath \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u30FB\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u306E\u4F4D\u7F6E\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\n\\ -extdirs \u62E1\u5F35\u6A5F\u80FD\u304C\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3055\u308C\u305F\u4F4D\u7F6E\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\n\\ -d \u751F\u6210\u3055\u308C\u305F\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u683C\u7D0D\u3059\u308B\u5834\u6240\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\n\\ -encoding \u30BD\u30FC\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u304C\u4F7F\u7528\u3059\u308B\u6587\u5B57\u30A8\u30F3\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0\u3092\u6307\u5B9A\u3059\u308B\n\\ -target \u7279\u5B9A\u306EVM\u30D0\u30FC\u30B8\u30E7\u30F3\u7528\u306E\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u751F\u6210\u3059\u308B +# +main.unsupported.usage=\ -Xdepend \u518D\u30B3\u30F3\u30D1\u30A4\u30EB\u306E\u305F\u3081\u306E\u3055\u3089\u306B\u65B0\u3057\u3044\u30D5\u30A1\u30A4\u30EB\u3092\u518D\u5E30\u7684\u306B\u691C\u7D22\u3059\u308B\n\\ -Xstdout \u30E1\u30C3\u30BB\u30FC\u30B8\u3092System.out\u306B\u9001\u308B\n\\ -Xverbosepath \u30D1\u30B9\u3068\u6A19\u6E96\u62E1\u5F35\u6A5F\u80FD\u306E\u691C\u7D22\u65B9\u6CD5\u3092\u8A18\u8FF0\u3059\u308B\n\\ -J \u5F15\u6570\u3092Java\u30A4\u30F3\u30BF\u30FC\u30D7\u30EA\u30BF\u306B\u6E21\u3059\n\n-X\u304A\u3088\u3073-J\u30AA\u30D7\u30B7\u30E7\u30F3\u306F\u6A19\u6E96\u3067\u306F\u306A\u304F\u3001\u4E88\u544A\u306A\u3057\u306B\u5909\u66F4\u3055\u308C\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002 +# +main.conflicting.options=\u30AA\u30D7\u30B7\u30E7\u30F3{0}\u3068{1}\u306F\u540C\u6642\u306B\u306F\u4F7F\u7528\u3057\u307E\u305B\u3093\u3002 +main.option.already.seen={0}\u30AA\u30D7\u30B7\u30E7\u30F3\u304C\u8907\u6570\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\u3002 +main.option.requires.argument={0}\u30AA\u30D7\u30B7\u30E7\u30F3\u306B\u306F\u5F15\u6570\u304C\u5FC5\u8981\u3067\u3059\u3002 +main.bad.debug.option={0}\u30AA\u30D7\u30B7\u30E7\u30F3\u306E\u5F62\u5F0F\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093\u3002\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F"lines"\u3001"vars"\u3001"source"\u306E\u307F\u3067\u3001\u30AB\u30F3\u30DE\u3067\u533A\u5207\u308A\u307E\u3059\u3002 +main.no.such.directory=\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA{0}\u306F\u5B58\u5728\u3057\u307E\u305B\u3093\u3002 +main.no.such.option={0}\u306F\u7121\u52B9\u306A\u30AA\u30D7\u30B7\u30E7\u30F3\u307E\u305F\u306F\u5F15\u6570\u3067\u3059\u3002 +main.unknown.release=\u30EA\u30EA\u30FC\u30B9''{0}''\u306F\u3053\u306E\u30B3\u30F3\u30D1\u30A4\u30E9\u3067\u306F\u8A8D\u8B58\u3055\u308C\u307E\u305B\u3093\u3002 +main.wrote=[{0}\u3092\u66F8\u8FBC\u307F\u5B8C\u4E86] +main.errors=\u30A8\u30E9\u30FC{0}\u500B +main.1error=\u30A8\u30E9\u30FC1\u500B +main.warnings=\u8B66\u544A{0}\u500B +main.1warning=\u8B66\u544A1\u500B +main.done_in=[{0}\u30DF\u30EA\u79D2\u3067\u5B8C\u4E86] +main.no.memory=\u30B3\u30F3\u30D1\u30A4\u30E9\u306B\u30E1\u30E2\u30EA\u30FC\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002"-J-mx"\u30B3\u30DE\u30F3\u30C9\u30E9\u30A4\u30F3\u30FB\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u3001\u6700\u5927\u30D2\u30FC\u30D7\u30FB\u30B5\u30A4\u30BA\u3092\u5897\u3084\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +main.stack.overflow=\u30B3\u30F3\u30D1\u30A4\u30E9\u306B\u30B9\u30BF\u30C3\u30AF\u7A7A\u9593\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059\u3002"-J-oss"\u30B3\u30DE\u30F3\u30C9\u30E9\u30A4\u30F3\u30FB\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u3066\u3001Java\u30B9\u30BF\u30C3\u30AF\u306B\u5272\u308A\u5F53\u3066\u308B\u30E1\u30E2\u30EA\u30FC\u3092\u5897\u3084\u3057\u3066\u304F\u3060\u3055\u3044\u3002 +main.path.msg=[\u30BD\u30FC\u30B9\u30FB\u30AF\u30E9\u30B9\u30D1\u30B9\u306F"{0}"\u3067\u3059]\n[\u30E9\u30A4\u30D6\u30E9\u30EA\u30FB\u30AF\u30E9\u30B9\u30D1\u30B9\u306F "{1}"\u3067\u3059] +javac.err.invalid.encoding.char=\u3053\u306E\u30BD\u30FC\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u306E\u30A8\u30F3\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0\u304C\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0\u306E\u3082\u306E\u3068\u7570\u306A\u3063\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002-encoding\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u6307\u5B9A\u3057\u3066\u30D5\u30A1\u30A4\u30EB\u306E\u30A8\u30F3\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0\u3092\u5909\u66F4\u3059\u308B\u304B\u3001\u307E\u305F\u306F\u30D5\u30A1\u30A4\u30EB\u306F\u5FC5\u305AASCII\u30A8\u30F3\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0\u306B\u5909\u63DB\u3057\u3066\u304F\u3060\u3055\u3044\u3002 diff --git a/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac_zh_CN.properties b/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac_zh_CN.properties new file mode 100644 index 000000000..ab1a5c317 --- /dev/null +++ b/rmic/src/main/resources/org/glassfish/rmic/tools/javac/resources/javac_zh_CN.properties @@ -0,0 +1,300 @@ +# +# Copyright (c) 1996, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +javac.err.internal=\u5185\u90E8\u9519\u8BEF\u3002 +javac.err.eof.in.comment=\u8F93\u5165\u7ED3\u5C3E\u5904\u672A\u4EE5\u6CE8\u91CA\u7EC8\u6B62\u3002 +javac.err.eof.in.string=\u8F93\u5165\u7ED3\u5C3E\u5904\u672A\u4EE5\u5B57\u7B26\u4E32\u7EC8\u6B62\u3002 +javac.err.newline.in.string=\u884C\u7ED3\u5C3E\u5904\u672A\u4EE5\u5B57\u7B26\u4E32\u7EC8\u6B62\u3002 +javac.err.invalid.char.constant=\u5B57\u7B26\u5E38\u91CF\u65E0\u6548\u3002 +javac.err.unbalanced.paren=\u62EC\u53F7\u4E0D\u914D\u5BF9\u3002 +javac.err.invalid.escape.char=\u8F6C\u4E49\u7B26\u65E0\u6548\u3002 +javac.err.invalid.hex.number=\u5341\u516D\u8FDB\u5236\u6570\u5B57\u5FC5\u987B\u5305\u542B\u81F3\u5C11\u4E00\u4F4D\u5341\u516D\u8FDB\u5236\u6570\u5B57\u3002 +javac.err.invalid.octal.number=\u4EE5\u516B\u8FDB\u5236\u6570\u5B57\u8868\u793A\u7684\u5B57\u7B26\u65E0\u6548\u3002 +javac.err.invalid.number=\u4EE5\u6570\u5B57\u8868\u793A\u7684\u5B57\u7B26\u65E0\u6548\u3002 +javac.err.funny.char=\u8F93\u5165\u7684\u5B57\u7B26\u65E0\u6548\u3002 +javac.err.float.format=\u6D6E\u70B9\u6570\u683C\u5F0F\u65E0\u6548\u3002 +javac.err.overflow.int.oct=\u6574\u578B\u6587\u5B57\u8D85\u51FA\u8303\u56F4\u3002\u516B\u8FDB\u5236\u6574\u578B\u6587\u5B57\u5FC5\u987B\u5728 00 \u81F3 037777777777 \u8303\u56F4\u4E4B\u95F4\u3002 +javac.err.overflow.int.dec=\u6574\u578B\u6587\u5B57\u8D85\u51FA\u8303\u56F4\u3002\u5341\u8FDB\u5236\u6574\u578B\u6587\u5B57\u5FC5\u987B\u5728 -2147483648 \u81F3 2147483647 \u8303\u56F4\u4E4B\u95F4\u3002 +javac.err.overflow.int.hex=\u6574\u578B\u6587\u5B57\u8D85\u51FA\u8303\u56F4\u3002\u5341\u516D\u8FDB\u5236\u6574\u578B\u6587\u5B57\u5FC5\u987B\u5728 0x0 \u81F3 0xffffffff \u8303\u56F4\u4E4B\u95F4\u3002 +javac.err.overflow.long.oct=\u6574\u578B\u6587\u5B57\u8D85\u51FA\u8303\u56F4\u3002\u516B\u8FDB\u5236\u957F\u6574\u578B\u6587\u5B57\u5FC5\u987B\u5728 00L \u81F3 01777777777777777777777L \u8303\u56F4\u4E4B\u95F4\u3002 +javac.err.overflow.long.dec=\u6574\u578B\u6587\u5B57\u8D85\u51FA\u8303\u56F4\u3002\u5341\u8FDB\u5236\u957F\u6574\u578B\u6587\u5B57\u5FC5\u987B\u5728 -9223372036854775808L \u81F3 9223372036854775807L \u8303\u56F4\u4E4B\u95F4\u3002 +javac.err.overflow.long.hex=\u6574\u578B\u6587\u5B57\u8D85\u51FA\u8303\u56F4\u3002\u5341\u516D\u8FDB\u5236\u957F\u6574\u578B\u6587\u5B57\u5FC5\u987B\u5728 0x0L \u81F3 0xffffffffffffffffL \u8303\u56F4\u4E4B\u95F4\u3002 +javac.err.overflow.float=\u6570\u5B57\u6EA2\u51FA: \u6D6E\u70B9\u6587\u5B57\u8FC7\u5927\u3002 +javac.err.overflow.double=\u6570\u5B57\u6EA2\u51FA: \u53CC\u7CBE\u5EA6\u578B\u6587\u5B57\u8FC7\u5927\u3002 +javac.err.underflow.float=\u6570\u5B57\u4E0B\u6EA2: \u6D6E\u70B9\u6587\u5B57\u8FC7\u5C0F\u3002 +javac.err.underflow.double=\u6570\u5B57\u4E0B\u6EA2: \u53CC\u7CBE\u5EA6\u578B\u6587\u5B57\u8FC7\u5C0F\u3002 +javac.err.token.expected=\u9700\u8981 ''{0}''\u3002 +javac.err.statement.expected=\u9700\u8981\u8BED\u53E5\u3002 +javac.err.type.expected=\u9700\u8981\u7C7B\u578B\u3002 +javac.err.identifier.expected=\u9700\u8981\u6807\u8BC6\u7B26\u3002 +javac.err.class.expected=\u9700\u8981 ''class'' \u6216 ''interface'' \u5173\u952E\u5B57\u3002 +javac.err.toplevel.expected=\u9700\u8981\u7C7B\u58F0\u660E\u6216\u63A5\u53E3\u58F0\u660E\u3002 +javac.err.missing.term=\u7F3A\u5C11\u6761\u4EF6\u3002 +javac.err.assign.in.conditionalexpr=\u4E0D\u5141\u8BB8\u5C06\u8D4B\u503C\u8868\u8FBE\u5F0F\u7528\u4F5C\u6761\u4EF6\u8868\u8FBE\u5F0F\u7684\u7B2C\u4E09\u4E2A\u5B50\u8868\u8FBE\u5F0F (\u5373 ?: \u8868\u8FBE\u5F0F)\u3002\u8BF7\u5C1D\u8BD5\u5BF9\u6B64\u8D4B\u503C\u8868\u8FBE\u5F0F\u52A0\u62EC\u53F7\u3002 +javac.err.else.without.if=\u6709 ''if'', \u4F46\u662F\u6CA1\u6709 ''else''\u3002 +javac.err.catch.without.try=\u6709 ''catch'', \u4F46\u662F\u6CA1\u6709 ''try''\u3002 +javac.err.finally.without.try=\u6709 ''finally'', \u4F46\u662F\u6CA1\u6709 ''try''\u3002 +javac.err.try.without.catch.finally=\u6709 ''try'', \u4F46\u662F\u6CA1\u6709 ''catch'' \u6216 ''finally''\u3002 +javac.err.case.without.switch=''case'' \u4E0D\u5728 switch \u8BED\u53E5\u4E2D\u3002 +javac.err.default.without.switch=''default'' \u4E0D\u5728 switch \u8BED\u53E5\u4E2D\u3002 +javac.err.io.exception={0}\u4E2D\u51FA\u73B0 I/O \u9519\u8BEF\u3002 +javac.err.io.exception.package=\u68C0\u67E5\u7A0B\u5E8F\u5305{0}\u662F\u5426\u5B58\u5728\u65F6\u51FA\u73B0 I/O \u9519\u8BEF\u3002 +javac.err.malformed.attribute=\u5305\u542B{0}\u7684\u7C7B\u6587\u4EF6\u5177\u6709\u683C\u5F0F\u9519\u8BEF\u7684 ''{1}'' \u5C5E\u6027\u3002 +javac.err.array.index.required=\u9700\u8981\u6570\u7EC4\u7D22\u5F15\u3002 +javac.err.not.array=[] \u53EA\u80FD\u5E94\u7528\u4E8E\u6570\u7EC4, \u800C\u4E0D\u80FD\u5E94\u7528\u4E8E{0}\u3002 +javac.err.array.dim.in.decl=\u65E0\u6CD5\u5728\u58F0\u660E\u4E2D\u6307\u5B9A\u6570\u7EC4\u7EF4\u3002 +javac.err.array.dim.in.type=\u65E0\u6CD5\u5728\u7C7B\u578B\u8868\u8FBE\u5F0F\u4E2D\u6307\u5B9A\u6570\u7EC4\u7EF4\u3002 +javac.err.invalid.array.expr=\u6570\u7EC4\u5E38\u91CF\u53EA\u80FD\u7528\u4E8E\u521D\u59CB\u5316\u7A0B\u5E8F\u4E2D\u3002 +javac.err.invalid.array.init=\u7C7B\u578B{0}\u7684\u521D\u59CB\u5316\u7A0B\u5E8F\u65E0\u6548\u3002 +javac.err.invalid.lhs.assignment=\u8D4B\u503C\u8868\u8FBE\u5F0F\u7684\u5DE6\u4FA7\u65E0\u6548\u3002 +javac.err.invalid.args={0}\u7684\u53C2\u6570\u65E0\u6548\u3002 +javac.err.invalid.cast=\u4ECE{0}\u5230{1}\u7684\u8F6C\u6362\u65E0\u6548\u3002 +javac.err.invalid.instanceof={0}\u65E0\u6CD5\u6210\u4E3A{1}\u7684\u5B9E\u4F8B\u3002 +javac.err.invalid.type.expr=\u7C7B\u578B\u8868\u8FBE\u5F0F\u65E0\u6548\u3002 +javac.err.anonymous.extends=\u53EA\u6709\u5DF2\u547D\u540D\u7684\u7C7B\u624D\u80FD\u6709 ''extends'' \u6216 ''implements'' \u5B50\u53E5\u3002 +javac.err.invalid.field.reference=\u5C1D\u8BD5\u5728{1}\u4E2D\u5F15\u7528\u5B57\u6BB5{0}\u3002 +javac.err.no.such.field={1}\u4E2D\u672A\u5B9A\u4E49\u53D8\u91CF{0}\u3002 +javac.err.no.field.access=\u65E0\u6CD5\u4ECE{2}\u8BBF\u95EE{1}\u4E2D\u7684\u53D8\u91CF{0}\u3002 +javac.err.no.type.access=\u65E0\u6CD5\u4ECE{2}\u8BBF\u95EE{1}\u4E2D\u7684\u5185\u90E8\u7C7B\u578B {0}\u3002 +javac.err.cant.access.member.type=\u65E0\u6CD5\u4ECE{2}\u8BBF\u95EE\u6210\u5458{0}\u6240\u5C5E\u7684\u7C7B\u578B {1}\u3002 +javac.err.inner.class.expected=\u5728{1}\u4E2D\u627E\u4E0D\u5230\u5185\u90E8\u7C7B{0}\u3002 +javac.err.no.static.field.access=\u65E0\u6CD5\u9759\u6001\u5F15\u7528{1}\u4E2D\u7684\u975E\u9759\u6001\u53D8\u91CF{0}\u3002 +javac.err.inner.static.ref=\u65E0\u6CD5\u9759\u6001\u5F15\u7528\u5185\u90E8\u7C7B{0}\u3002 +javac.err.ambig.field=\u5BF9{0}\u7684\u5F15\u7528\u4E0D\u660E\u786E\u3002\u5728{1}\u548C{2}\u4E2D\u90FD\u5BF9\u5176\u8FDB\u884C\u4E86\u5B9A\u4E49\u3002 +javac.err.invalid.field=\u5C1D\u8BD5\u5C06{1}\u4E2D\u7684\u65B9\u6CD5{0}\u4F5C\u4E3A\u5B9E\u4F8B\u53D8\u91CF\u8FDB\u884C\u5F15\u7528\u3002 +javac.err.assign.to.final=\u65E0\u6CD5\u4E3A\u6700\u7EC8\u53D8\u91CF\u5206\u914D\u503C: {0} +javac.err.assign.to.blank.final=\u65E0\u6CD5\u4E3A\u7A7A\u6700\u7EC8\u53D8\u91CF\u5206\u914D\u7B2C\u4E8C\u4E2A\u503C: {0} +javac.err.qualified.static.final.assign=\u4E3A\u7A7A\u9759\u6001\u6700\u7EC8\u53D8\u91CF\u5206\u914D\u7684\u53D8\u91CF\u5FC5\u987B\u4E3A\u7B80\u540D (\u540E\u9762\u4E0D\u80FD\u52A0\u70B9 ''.'')\u3002 +javac.err.bad.qualified.final.assign=\u4E3A\u7A7A\u6700\u7EC8\u53D8\u91CF\u5206\u914D\u7684\u53D8\u91CF\u5FC5\u987B\u4E3A\u7B80\u540D\u6216\u7531 ''this'' \u9650\u5B9A\u7684\u7B80\u540D: ''{0}'' \u6216 ''this.{0}''\u3002 +javac.err.assign.to.blank.final.in.loop=\u5C1D\u8BD5\u5728 loop \u4E2D\u5206\u914D\u7A7A\u6700\u7EC8\u53D8\u91CF{0}\u3002\u53EA\u80FD\u8FDB\u884C\u4E00\u6B21\u521D\u59CB\u5316\u3002 +javac.err.assign.to.uplevel=\u5C1D\u8BD5\u4EE5\u5176\u4ED6\u65B9\u6CD5\u5C06\u503C\u5206\u914D\u7ED9\u53D8\u91CF{0}\u3002\u5C01\u95ED\u5757\u4E2D\u53EA\u6709\u6700\u7EC8\u672C\u5730\u53D8\u91CF\u53EF\u7528\u3002 +javac.err.invalid.uplevel=\u5C1D\u8BD5\u4EE5\u5176\u4ED6\u65B9\u6CD5\u4F7F\u7528\u975E\u6700\u7EC8\u53D8\u91CF{0}\u3002\u5C01\u95ED\u5757\u4E2D\u53EA\u6709\u6700\u7EC8\u672C\u5730\u53D8\u91CF\u53EF\u7528\u3002 +javac.err.undef.var=\u672A\u5B9A\u4E49\u7684\u53D8\u91CF: {0} +javac.err.undef.var.super=\u672A\u5B9A\u4E49\u7684\u53D8\u91CF: {0}\u3002 "super" \u5173\u952E\u5B57\u53EA\u80FD\u7528\u4E8E\u6210\u5458\u8BBF\u95EE\u548C\u6784\u9020\u5668\u8C03\u7528\u3002 +javac.err.undef.var.or.package=\u672A\u5B9A\u4E49\u7684\u53D8\u91CF\u6216\u7A0B\u5E8F\u5305\u540D\u79F0: {0} +javac.err.undef.class.or.package=\u672A\u5B9A\u4E49\u7684\u7C7B\u6216\u7A0B\u5E8F\u5305\u540D\u79F0: {0} +javac.err.undef.var.class.or.package=\u672A\u5B9A\u4E49\u7684\u53D8\u91CF, \u7C7B\u6216\u7A0B\u5E8F\u5305\u540D\u79F0: {0} +javac.err.undef.class=\u672A\u5B9A\u4E49\u7684\u7C7B\u540D: {0} +javac.err.undef.var.or.class=\u672A\u5B9A\u4E49\u7684\u53D8\u91CF\u6216\u7C7B\u540D: {0} +javac.err.var.not.initialized=\u53EF\u80FD\u5C1A\u672A\u521D\u59CB\u5316\u53D8\u91CF{0}\u3002 +javac.err.final.var.not.initialized=\u53EF\u80FD\u5C1A\u672A\u521D\u59CB\u5316\u7A7A\u6700\u7EC8\u53D8\u91CF ''{0}''\u3002\u5FC5\u987B\u5728\u521D\u59CB\u5316\u7A0B\u5E8F\u6216\u5728\u6BCF\u4E2A\u6784\u9020\u5668\u4E2D\u5206\u914D\u503C\u3002 +javac.err.access.inst.before.super=\u65E0\u6CD5\u5728\u8C03\u7528\u8D85\u7C7B\u6784\u9020\u5668\u4E4B\u524D\u5F15\u7528{0}\u3002 +javac.err.ambig.class=\u4E0D\u660E\u786E\u7684\u7C7B: {0}\u548C{1} +javac.err.invalid.arg={0}\u7684\u53C2\u6570\u65E0\u6548\u3002 +javac.err.invalid.arg.type={1}\u7684\u53C2\u6570\u7C7B\u578B{0}\u65E0\u6548\u3002 +javac.err.invalid.length=''length'' \u5E94\u7528\u5230\u4E0D\u662F\u6570\u7EC4\u7684{0}\u3002 +javac.err.invalid.constr.invoke=\u53EA\u6709\u6784\u9020\u5668\u624D\u80FD\u8C03\u7528\u6784\u9020\u5668\u3002 +javac.err.constr.invoke.not.first=\u5728\u65B9\u6CD5\u4E2D\u5FC5\u987B\u9996\u5148\u8C03\u7528\u6784\u9020\u5668\u3002 +javac.err.invalid.method.invoke=\u65E0\u6CD5\u5728{0}\u4E0A\u8C03\u7528\u65B9\u6CD5\u3002 +javac.err.undef.meth=\u5728{1}\u4E2D\u627E\u4E0D\u5230\u65B9\u6CD5{0}\u3002 +javac.err.no.meth.access=\u65E0\u6CD5\u4ECE{2}\u8BBF\u95EE{1}\u4E2D\u7684\u65B9\u6CD5{0}\u3002 +#warning: +javac.err.no.override.access=\u6CE8: {1}\u4E2D\u7684\u65B9\u6CD5{0}\u4E0D\u4F1A\u8986\u76D6{2}\u4E2D\u76F8\u5BF9\u5E94\u7684\u65B9\u6CD5\u3002\u5982\u679C\u6B63\u5C1D\u8BD5\u8986\u76D6\u6B64\u65B9\u6CD5, \u5219\u65E0\u6CD5\u8FBE\u5230\u76EE\u7684, \u56E0\u4E3A\u8BE5\u65B9\u6CD5\u662F\u5176\u4ED6\u7A0B\u5E8F\u5305\u7684\u4E13\u7528\u65B9\u6CD5\u3002 +javac.err.no.static.meth.access=\u65E0\u6CD5\u9759\u6001\u5F15\u7528{1}\u4E2D\u7684\u65B9\u6CD5{0}\u3002 +javac.err.invalid.protected.method.use=\u65E0\u6CD5\u8BBF\u95EE{1}\u4E2D\u7684\u53D7\u4FDD\u62A4\u65B9\u6CD5{0}\u3002{2}\u4E0D\u662F\u5F53\u524D\u7C7B\u7684\u5B50\u7C7B\u3002 +javac.err.invalid.protected.field.use=\u65E0\u6CD5\u8BBF\u95EE{1}\u4E2D\u7684\u53D7\u4FDD\u62A4\u5B57\u6BB5{0}\u3002{2}\u4E0D\u662F\u5F53\u524D\u7C7B\u7684\u5B50\u7C7B\u3002 +javac.err.invalid.protected.type.use=\u65E0\u6CD5\u8BBF\u95EE{1}\u4E2D\u7684\u53D7\u4FDD\u62A4\u5185\u90E8\u7C7B\u578B {0}\u3002{2}\u4E0D\u662F\u5F53\u524D\u7C7B\u7684\u5B50\u7C7B\u3002 +javac.err.invalid.protected.constructor.use=\u65E0\u6CD5\u8BBF\u95EE{0}\u7684\u53D7\u4FDD\u62A4\u6784\u9020\u5668\u3002\u53EA\u5141\u8BB8\u5728\u5B9A\u4E49\u4E86\u6784\u9020\u5668\u7684\u7A0B\u5E8F\u5305\u5185\u521B\u5EFA\u5B9E\u4F8B\u3002 +javac.err.invalid.method=\u5728{1}\u4E2D\u5C06\u53D8\u91CF{0}\u4F5C\u4E3A\u4E00\u4E2A\u65B9\u6CD5\u8FDB\u884C\u5F15\u7528\u3002 +javac.err.invalid.var=\u5728{1}\u4E2D\u5C06\u65B9\u6CD5{0}\u4F5C\u4E3A\u4E00\u4E2A\u53D8\u91CF\u8FDB\u884C\u5F15\u7528\u3002 +javac.err.synchronized.null=\u7A7A\u503C\u6587\u5B57\u4E0D\u662F\u540C\u6B65\u8BED\u53E5\u7684\u5408\u6CD5\u53C2\u6570\u3002 +#all messages related to deprecation are warnings: +javac.err.class.is.deprecated=\u6CE8: {0}\u5DF2\u8FC7\u65F6\u3002 +javac.err.meth.is.deprecated=\u6CE8: {1}\u4E2D\u7684\u65B9\u6CD5{0}\u5DF2\u8FC7\u65F6\u3002 +javac.err.constr.is.deprecated=\u6CE8: \u6784\u9020\u5668{0}\u5DF2\u8FC7\u65F6\u3002 +javac.err.field.is.deprecated=\u6CE8: {1}\u4E2D\u7684\u53D8\u91CF{0}\u5DF2\u8FC7\u65F6\u3002 +javac.err.note.deprecations=\u6CE8: {0}\u6587\u4EF6\u4F7F\u7528\u6216\u8986\u76D6\u4E86\u5DF2\u8FC7\u65F6\u7684 API\u3002\u8BF7\u53C2\u9605\u6587\u6863\u4EE5\u83B7\u5F97\u9488\u5BF9\u6BCF\u79CD\u60C5\u51B5\u7684\u66F4\u597D\u7684\u66FF\u4EE3\u65B9\u6CD5\u3002 +javac.err.note.1deprecation=\u6CE8: {0}\u4F7F\u7528\u6216\u8986\u76D6\u4E86\u5DF2\u8FC7\u65F6\u7684 API\u3002\u8BF7\u53C2\u9605\u6587\u6863\u4EE5\u83B7\u5F97\u66F4\u597D\u7684\u66FF\u4EE3\u65B9\u6CD5\u3002 +javac.err.note.deprecations.silent=\u6CE8: {0}\u6587\u4EF6\u4F7F\u7528\u6216\u8986\u76D6\u4E86\u5DF2\u8FC7\u65F6\u7684 API\u3002\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F, \u8BF7\u4F7F\u7528 "-deprecation" \u91CD\u65B0\u7F16\u8BD1\u3002 +javac.err.note.1deprecation.silent=\u6CE8: {0}\u4F7F\u7528\u6216\u8986\u76D6\u4E86\u5DF2\u8FC7\u65F6\u7684 API\u3002\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F, \u8BF7\u4F7F\u7528 "-deprecation" \u91CD\u65B0\u7F16\u8BD1\u3002 +javac.err.invalid.array.dim=\u6570\u7EC4\u7EF4\u65E0\u6548\u3002 +javac.err.ambig.constr=\u6784\u9020\u5668\u4E0D\u660E\u786E: {0}, {1} +javac.err.explicit.cast.needed={0}\u7684\u4E0D\u517C\u5BB9\u7C7B\u578B\u3002\u9700\u8981\u4F7F\u7528\u663E\u5F0F\u8F6C\u6362\u5C06{1}\u8F6C\u6362\u4E3A{2}\u3002 +javac.err.incompatible.type={0}\u7684\u4E0D\u517C\u5BB9\u7C7B\u578B\u3002\u65E0\u6CD5\u5C06{1}\u8F6C\u6362\u4E3A{2}\u3002 +javac.err.invalid.term=\u6761\u4EF6\u65E0\u6548\u3002 +javac.err.abstract.class=\u5FC5\u987B\u5C06{0}\u58F0\u660E\u4E3A\u62BD\u8C61\u3002\u5B83\u672A\u4ECE{2}\u5B9A\u4E49{1}\u3002 +javac.err.abstract.class.cannot.override=\u5FC5\u987B\u5C06{0}\u58F0\u660E\u4E3A\u62BD\u8C61\u3002\u65E0\u6CD5\u8BBF\u95EE\u4E14\u65E0\u6CD5\u8986\u76D6\u8D85\u7C7B{2}\u4E2D\u7684\u7A0B\u5E8F\u5305\u4E13\u7528\u62BD\u8C61\u65B9\u6CD5{1}\u3002 +javac.err.new.intf={0}\u662F\u63A5\u53E3\u3002\u65E0\u6CD5\u5B9E\u4F8B\u5316\u3002 +javac.err.invoke.abstract=\u65E0\u6CD5\u5728{1}\u4E2D\u76F4\u63A5\u8C03\u7528\u62BD\u8C61\u65B9\u6CD5{0}\u3002 +javac.err.unmatched.meth=\u5728{1}\u4E2D\u627E\u4E0D\u5230\u4E0E{0}\u5339\u914D\u7684\u65B9\u6CD5\u3002 +javac.err.unmatched.constr=\u5728{1}\u4E2D\u627E\u4E0D\u5230\u4E0E{0}\u5339\u914D\u7684\u6784\u9020\u5668\u3002 +javac.err.wrong.number.args={0}\u4E2D\u7684\u53C2\u6570\u6570\u76EE\u9519\u8BEF\u3002 +javac.err.wrong.number.args={0}\u4E2D\u7684\u53C2\u6570\u6570\u76EE\u9519\u8BEF\u3002 +javac.err.forward.ref=\u65E0\u6CD5\u524D\u5411\u5F15\u7528{1}\u4E2D\u7684{0}\u3002 +javac.err.array.dim.missing=\u7F3A\u5C11\u6570\u7EC4\u7EF4\u3002 +javac.err.new.abstract={0}\u662F\u62BD\u8C61\u7C7B\u3002\u65E0\u6CD5\u5B9E\u4F8B\u5316\u3002 +javac.err.label.not.found=\u627E\u4E0D\u5230{0}\u7684\u6807\u7B7E\u5B9A\u4E49\u3002 +javac.err.invalid.break=loop \u6216 switch \u4E2D\u5FC5\u987B\u6709 ''break''\u3002 +javac.err.invalid.continue=loop \u4E2D\u5FC5\u987B\u6709 ''continue''\u3002 +javac.err.branch.to.uplevel=''break'' \u6216 ''continue'' \u5FC5\u987B\u5728\u540C\u4E00\u65B9\u6CD5\u5185\u8F6C\u79FB\u63A7\u5236\u3002 +javac.err.invalid.decl=\u58F0\u660E\u65E0\u6548\u3002 +javac.err.return.with.value=\u5BF9\u4E8E{0}\u4F7F\u7528 ''return'' \u8FD4\u56DE\u503C\u3002 +javac.err.return.without.value=\u5BF9\u4E8E{0}\u4F7F\u7528 ''return'' \u672A\u8FD4\u56DE\u503C\u3002 +javac.err.return.inside.static.initializer=\u9759\u6001\u521D\u59CB\u5316\u7A0B\u5E8F\u5185\u90E8\u7684 ''return''\u3002 +javac.err.invalid.label=\u6807\u7B7E\u65E0\u6548\u3002 +javac.err.return.required.at.end=\u5728{0}\u7684\u7ED3\u5C3E\u5904\u8FD4\u56DE\u6240\u9700\u5185\u5BB9\u3002 +javac.err.duplicate.label=case \u6807\u7B7E\u91CD\u590D: {0} +javac.err.switch.overflow=\u5728{1}\u4E0A\u7528\u4E8E ''switch'' \u7684 case \u6807\u7B7E{0}\u8FC7\u5927 +javac.err.nested.duplicate.label=\u8BED\u53E5\u4E0D\u80FD\u4E0E\u5176\u5C01\u95ED\u8BED\u53E5\u4E4B\u4E00\u4F7F\u7528\u540C\u4E00\u6807\u8BC6\u7B26\u6807\u8BB0: {0} +javac.err.declaration.with.label=\u65E0\u6CD5\u6807\u8BB0\u58F0\u660E: {0} +javac.err.const.expr.required=\u9700\u8981\u5E38\u91CF\u8868\u8FBE\u5F0F\u3002 +javac.err.duplicate.default=''default'' \u6807\u7B7E\u91CD\u590D\u3002 +javac.err.not.supported=\u4E0D\u652F\u6301 ''{0}''\u3002 +javac.err.return.with.value.constr=\u5BF9\u4E8E\u6784\u9020\u5668\u4F7F\u7528 ''return'' \u8FD4\u56DE\u503C: {0} +javac.err.package.repeated=\u4EC5\u5141\u8BB8\u4E00\u4E2A\u7A0B\u5E8F\u5305\u58F0\u660E\u3002 +javac.err.class.multidef=\u5DF2\u5728{1}\u4E2D\u5B9A\u4E49\u7C7B{0}\u3002 +javac.err.class.multidef.import=\u7C7B\u540D{0}\u4E0E\u5BFC\u5165\u7C7B{1}\u51B2\u7A81\u3002 +javac.err.intf.constructor=\u63A5\u53E3\u4E0D\u80FD\u6709\u6784\u9020\u5668\u3002 +javac.err.constr.modifier=\u6784\u9020\u5668\u7684\u7C7B\u578B\u4E0D\u80FD\u4E3A\u672C\u673A, \u62BD\u8C61, \u9759\u6001, \u540C\u6B65\u6216\u6700\u7EC8: {0} +javac.err.intf.initializer=\u63A5\u53E3\u4E0D\u80FD\u6709\u9759\u6001\u521D\u59CB\u5316\u7A0B\u5E8F\u3002 +javac.err.intf.modifier.method=\u63A5\u53E3\u65B9\u6CD5\u7C7B\u578B\u4E0D\u80FD\u4E3A\u672C\u673A, \u9759\u6001, \u540C\u6B65, \u6700\u7EC8, \u4E13\u7528\u6216\u53D7\u4FDD\u62A4: {0} +javac.err.intf.modifier.field=\u63A5\u53E3\u5B57\u6BB5\u7C7B\u578B\u4E0D\u80FD\u4E3A\u4E13\u7528\u6216\u53D7\u4FDD\u62A4: {0} +javac.err.transient.meth=\u65B9\u6CD5{0}\u4E0D\u80FD\u4E3A\u77AC\u6001\u65B9\u6CD5\u3002\u53EA\u6709\u53D8\u91CF\u624D\u80FD\u662F\u77AC\u6001\u7684\u3002 +javac.err.volatile.meth=\u65B9\u6CD5{0}\u4E0D\u80FD\u4E3A\u6613\u5931\u65B9\u6CD5\u3002\u53EA\u6709\u53D8\u91CF\u624D\u80FD\u662F\u6613\u5931\u7684\u3002 +javac.err.abstract.private.modifier=\u62BD\u8C61\u65B9\u6CD5\u4E0D\u80FD\u4E3A\u4E13\u7528\u65B9\u6CD5: {0} +javac.err.abstract.static.modifier=\u62BD\u8C61\u65B9\u6CD5\u4E0D\u80FD\u4E3A\u9759\u6001\u65B9\u6CD5: {0} +javac.err.abstract.final.modifier=\u62BD\u8C61\u65B9\u6CD5\u4E0D\u80FD\u4E3A\u6700\u7EC8\u65B9\u6CD5: {0} +javac.err.abstract.native.modifier=\u62BD\u8C61\u65B9\u6CD5\u4E0D\u80FD\u4E3A\u672C\u673A\u65B9\u6CD5: {0} +javac.err.abstract.synchronized.modifier=\u62BD\u8C61\u65B9\u6CD5\u4E0D\u80FD\u4E3A\u540C\u6B65\u65B9\u6CD5: {0} +javac.err.invalid.meth.body=\u62BD\u8C61\u65B9\u6CD5\u548C\u672C\u673A\u65B9\u6CD5\u4E0D\u80FD\u5E26\u6709\u4E3B\u4F53: {0} +javac.err.var.modifier=\u53D8\u91CF\u7C7B\u578B\u4E0D\u80FD\u4E3A\u540C\u6B65, \u62BD\u8C61\u6216\u672C\u673A: {0} +javac.err.var.floatmodifier=\u4E0D\u80FD\u4E25\u683C\u58F0\u660E\u53D8\u91CF: {0} +javac.err.inner.modifier=\u5185\u90E8\u7C7B\u4E0D\u80FD\u4E3A\u6613\u5931, \u77AC\u6001, \u672C\u673A\u6216\u540C\u6B65\u7C7B: {0} +javac.err.transient.modifier=\u77AC\u6001\u53D8\u91CF\u4E0D\u80FD\u4E3A\u63A5\u53E3\u7684\u6210\u5458: {0} +javac.err.volatile.modifier=\u6613\u5931\u53D8\u91CF\u4E0D\u80FD\u4E3A\u6700\u7EC8\u53D8\u91CF\u6216\u63A5\u53E3\u7684\u6210\u5458: {0} +javac.err.initializer.needed=\u5FC5\u987B\u521D\u59CB\u5316\u6B64\u6700\u7EC8\u53D8\u91CF: {0} +javac.err.meth.multidef=\u65B9\u6CD5\u58F0\u660E\u91CD\u590D: {0} +javac.err.meth.redef.rettype=\u4E0D\u80FD\u4F7F\u7528\u5176\u4ED6\u8FD4\u56DE\u7C7B\u578B\u91CD\u65B0\u5B9A\u4E49\u65B9\u6CD5: {0}\u662F{1} +javac.err.var.multidef=\u53D8\u91CF\u58F0\u660E\u91CD\u590D: {0}\u662F{1} +javac.err.inner.class.multidef=\u5185\u90E8\u7C7B\u58F0\u660E\u91CD\u590D: \u5DF2\u5728\u6B64\u8303\u56F4\u5185\u5B9A\u4E49\u4E86{0}\u3002 +javac.err.intf.super.class={0}\u7684\u8D85\u7C7B\u4E0D\u80FD\u662F\u63A5\u53E3: {1} +javac.err.cant.access.class=\u65E0\u6CD5\u8BBF\u95EE{0}\u3002\u7C7B\u6216\u63A5\u53E3\u5FC5\u987B\u662F\u516C\u5171\u7684, \u5728\u540C\u4E00\u7A0B\u5E8F\u5305\u4E2D\u6216\u4E3A\u53EF\u8BBF\u95EE\u6210\u5458\u7C7B\u3002 +javac.err.unqualified.name.required=\u9650\u5B9A\u7684 'new' \u8868\u8FBE\u5F0F\u4E2D\u7684\u7C7B\u578B\u540D\u79F0\u5FC5\u987B\u4E3A\u975E\u9650\u5B9A\u6807\u8BC6\u7B26\u3002 +javac.err.repeated.modifier=\u4FEE\u9970\u7B26\u91CD\u590D\u3002 +javac.err.inconsistent.modifier=\u6210\u5458\u58F0\u660E\u4E0D\u4E00\u81F4\u3002\u6700\u591A\u53EA\u80FD\u6307\u5B9A\u4E00\u4E2A\u516C\u5171\u7684, \u4E13\u7528\u7684\u6216\u53D7\u4FDD\u62A4\u7684\u6210\u5458\u3002 +javac.err.super.is.final=\u4E0D\u80FD\u5C06\u6700\u7EC8\u7C7B\u7528\u4F5C\u5B50\u7C7B: {0} +javac.err.super.is.intf=\u4E0D\u80FD\u5C06\u63A5\u53E3\u7528\u4F5C\u5B50\u7C7B: {0} +javac.err.cyclic.super=\u5FAA\u73AF\u7C7B\u7EE7\u627F\u3002 +javac.err.super.is.inner=\u5FAA\u73AF\u7C7B\u7EE7\u627F: \u5B50\u7C7B\u4E0D\u80FD\u5C01\u95ED\u8D85\u7C7B\u3002 +javac.err.cyclic.intf=\u5FAA\u73AF\u63A5\u53E3\u7EE7\u627F\u3002 +javac.err.cyclic.scoping=\u5FAA\u73AF\u7C7B\u7EE7\u627F\u6216\u786E\u5B9A\u4F5C\u7528\u57DF\u3002 +javac.err.not.intf={0}\u5FC5\u987B\u4E3A\u63A5\u53E3\u3002 +javac.err.final.intf=\u63A5\u53E3\u4E0D\u80FD\u4E3A\u6700\u7EC8\u63A5\u53E3: {0} +javac.err.intf.impl.intf=\u63A5\u53E3\u4E0D\u80FD\u5B9E\u73B0\u4EFB\u4F55\u65B9\u6CD5, \u5B83\u53EA\u80FD\u6269\u5C55\u5176\u4ED6\u63A5\u53E3\u3002 +javac.err.multiple.inherit=\u4E0D\u652F\u6301\u591A\u91CD\u7EE7\u627F\u3002 +javac.err.intf.repeated=\u63A5\u53E3{0}\u91CD\u590D\u3002 +javac.err.class.format={0}\u4E2D\u7684\u7C7B\u6587\u4EF6\u683C\u5F0F\u65E0\u6548\u3002{1} +javac.err.truncated.class=\u8BFB\u53D6\u7C7B\u6587\u4EF6{0}\u65F6\u9047\u5230\u610F\u5916\u7684\u6587\u4EF6\u7ED3\u5C3E\u3002 +javac.err.no.meth.body=\u65B9\u6CD5{0}\u9700\u8981\u65B9\u6CD5\u4E3B\u4F53\u3002\u5426\u5219\u5C06\u5176\u58F0\u660E\u4E3A\u62BD\u8C61\u65B9\u6CD5\u3002 +javac.err.no.constructor.body=\u6784\u9020\u5668{0}\u9700\u8981\u65B9\u6CD5\u4E3B\u4F53\u3002 +javac.err.bad.constructor.modifier=\u6784\u9020\u5668\u4E0D\u80FD\u7531 strictfp \u6765\u4FEE\u6539\u3002 +javac.err.void.inst.var=\u5B9E\u4F8B\u53D8\u91CF\u4E0D\u80FD\u4E3A\u7A7A: {0} +javac.err.invalid.method.decl=\u65B9\u6CD5\u58F0\u660E\u65E0\u6548; \u9700\u8981\u8FD4\u56DE\u7C7B\u578B\u3002 +javac.err.invalid.method.decl.name=\u65B9\u6CD5\u58F0\u660E\u65E0\u6548; \u9700\u8981\u65B9\u6CD5\u540D\u79F0\u3002 +javac.err.invalid.method.decl.qual=\u5168\u9650\u5B9A\u6784\u9020\u5668\u540D\u79F0\u65E0\u6548\u3002 +javac.err.super.not.found=\u627E\u4E0D\u5230{1}\u7684\u8D85\u7C7B{0}\u3002 +javac.err.intf.not.found=\u627E\u4E0D\u5230{1}\u7684\u63A5\u53E3{0}\u3002 +javac.err.final.abstract=\u4E0D\u80FD\u5C06\u7C7B{0}\u540C\u65F6\u58F0\u660E\u4E3A\u62BD\u8C61\u7C7B\u548C\u6700\u7EC8\u7C7B\u3002 +javac.err.void.array=\u7A7A\u6570\u7EC4\u4E3A\u65E0\u6548\u7C7B\u578B\u3002 +javac.err.void.argument=\u53C2\u6570\u7684\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A: {0} +javac.err.invalid.expr=\u8868\u8FBE\u5F0F\u8BED\u53E5\u65E0\u6548\u3002 +javac.err.catch.not.reached=\u65E0\u6CD5\u8BBF\u95EE catch\u3002 +javac.err.stat.not.reached=\u65E0\u6CD5\u8BBF\u95EE\u8BED\u53E5\u3002 +javac.err.init.no.normal.completion=\u521D\u59CB\u5316\u7A0B\u5E8F\u5FC5\u987B\u80FD\u591F\u6B63\u5E38\u5B8C\u6210\u3002 +javac.err.arithmetic.exception=\u7B97\u6CD5\u5F02\u5E38\u9519\u8BEF\u3002 +javac.err.generic={0} +javac.err.public.class.file=\u5FC5\u987B\u5728\u540D\u4E3A "{1}" \u7684\u6587\u4EF6\u4E2D\u5B9A\u4E49\u516C\u5171{0}\u3002 +javac.err.package.class.file={0}\u5728{1}\u4E2D\u5B9A\u4E49\u3002\u7531\u4E8E\u5B83\u662F\u5728\u5176\u6E90\u6587\u4EF6\u4E4B\u5916\u4F7F\u7528\u7684, \u56E0\u6B64\u5E94\u5728\u540D\u4E3A "{2}" \u7684\u6587\u4EF6\u4E2D\u5BF9\u5176\u8FDB\u884C\u5B9A\u4E49\u3002 +javac.err.lose.precision=\u53EF\u80FD\u635F\u5931\u7CBE\u5EA6\u3002\u4F7F\u7528\u663E\u5F0F\u8F6C\u6362\u5C06{0}\u8F6C\u6362\u4E3A{1}\u3002 +javac.err.duplicate.argument=\u5728\u6B64\u65B9\u6CD5\u7684\u53C2\u6570\u5217\u8868\u4E2D\u4E24\u6B21\u4F7F\u7528\u53D8\u91CF ''{0}''\u3002 +javac.err.local.redefined=\u5DF2\u5728\u6B64\u65B9\u6CD5\u4E2D\u5B9A\u4E49\u4E86\u53D8\u91CF ''{0}''\u3002 +javac.err.local.class.redefined=\u5DF2\u5728\u6B64\u65B9\u6CD5\u4E2D\u5B9A\u4E49\u4E86\u672C\u5730\u7C7B ''{0}''\u3002 +javac.err.inner.redefined=\u5DF2\u5728\u6B64\u8303\u56F4\u5185\u5B9A\u4E49\u4E86\u7C7B\u540D ''{0}''\u3002\u5185\u90E8\u7C7B\u4E0D\u80FD\u4E0E\u5176\u4EFB\u4E00\u5C01\u95ED\u7C7B\u5177\u6709\u76F8\u540C\u7684\u7B80\u540D\u3002 +javac.err.inherited.hides.field=\u53D8\u91CF ''{0}'' \u662F\u5728{1}\u4E2D\u7EE7\u627F\u7684, \u5E76\u5728{2}\u4E2D\u9690\u85CF\u4E86\u4E00\u4E2A\u540C\u540D\u53D8\u91CF\u3002\u5FC5\u987B\u4F7F\u7528\u663E\u5F0F ''this'' \u9650\u5B9A\u7B26\u9009\u62E9\u6240\u9700\u5B9E\u4F8B\u3002 +javac.err.inherited.hides.local=\u53D8\u91CF ''{0}'' \u662F\u5728{1}\u4E2D\u7EE7\u627F\u7684, \u5E76\u4E14\u9690\u85CF\u4E86\u4E00\u4E2A\u540C\u540D\u672C\u5730\u53D8\u91CF\u3002\u5FC5\u987B\u4F7F\u7528\u663E\u5F0F ''this'' \u9650\u5B9A\u7B26\u9009\u62E9\u53D8\u91CF, \u5426\u5219\u5FC5\u987B\u91CD\u547D\u540D\u672C\u5730\u53D8\u91CF\u3002 +javac.err.inherited.hides.method=\u65B9\u6CD5 ''{0}'' \u662F\u5728{1}\u4E2D\u7EE7\u627F\u7684, \u5E76\u5728{2}\u4E2D\u9690\u85CF\u4E86\u4E00\u4E2A\u540C\u540D\u65B9\u6CD5\u3002\u5FC5\u987B\u4F7F\u7528\u663E\u5F0F ''this'' \u9650\u5B9A\u7B26\u9009\u62E9\u6240\u9700\u5B9E\u4F8B\u3002 +javac.err.inherited.hides.type=\u7C7B\u578B ''{0}'' \u662F\u5728{1}\u4E2D\u7EE7\u627F\u7684, \u5E76\u5728\u5C01\u95ED\u8303\u56F4\u5185\u9690\u85CF\u4E86\u4E00\u4E2A\u540C\u540D\u7C7B\u578B\u3002\u5FC5\u987B\u4F7F\u7528\u663E\u5F0F\u9650\u5B9A\u7B26\u524D\u7F00\u547D\u540D\u6B64\u7C7B\u578B\u3002 +javac.err.private.class=\u7C7B\u578B{0}\u4E0D\u80FD\u4E3A\u4E13\u7528\u7C7B\u578B\u3002\u5728\u5F53\u524D\u7A0B\u5E8F\u5305\u4E2D\u59CB\u7EC8\u53EF\u4EE5\u8BBF\u95EE\u7A0B\u5E8F\u5305\u6210\u5458\u3002 +javac.err.static.class=\u7C7B\u578B{0}\u4E0D\u80FD\u58F0\u660E\u4E3A\u9759\u6001\u7C7B\u578B\u3002\u7531\u4E8E\u5B83\u662F\u7A0B\u5E8F\u5305\u6210\u5458, \u56E0\u6B64\u5B83\u5DF2\u81F3\u9876\u5C42\u3002 +javac.err.protected.class=\u7C7B\u578B{0}\u4E0D\u80FD\u4E3A\u53D7\u4FDD\u62A4\u7C7B\u578B\u3002\u7A0B\u5E8F\u5305\u6210\u5458\u53EF\u4EE5\u662F\u5F53\u524D\u7A0B\u5E8F\u5305\u7684\u516C\u5171\u7A0B\u5E8F\u5305\u6210\u5458\u6216\u672C\u5730\u7A0B\u5E8F\u5305\u6210\u5458\u3002 +javac.err.recursive.constr=\u9012\u5F52\u6784\u9020\u5668\u8C03\u7528: {0}\u3002 +javac.err.wrong.class=\u6587\u4EF6{0}\u672A\u6309\u9884\u671F\u5305\u542B{1}\u800C\u662F\u5305\u542B\u4E86{2}\u3002\u8BF7\u5220\u9664\u8BE5\u6587\u4EF6\u6216\u786E\u4FDD\u8BE5\u6587\u4EF6\u4F4D\u4E8E\u6B63\u786E\u7684\u7C7B\u8DEF\u5F84\u5B50\u76EE\u5F55\u4E2D\u3002 +javac.err.wrong.source=\u6587\u4EF6{0}\u672A\u6309\u9884\u671F\u5305\u542B{1}\u3002\u8BF7\u8C03\u6574\u7C7B\u8DEF\u5F84, \u4EE5\u4F7F\u8BE5\u6587\u4EF6\u4E0D\u51FA\u73B0\u5728{2}\u4E2D\u3002 +javac.err.class.not.found=\u5728{1}\u4E2D\u627E\u4E0D\u5230\u7C7B{0}\u3002 +javac.err.class.not.found.no.context=\u627E\u4E0D\u5230\u7C7B{0}\u3002 +javac.err.package.not.found=\u5728{1}\u4E2D\u627E\u4E0D\u5230\u7A0B\u5E8F\u5305{0}\u3002 +javac.err.package.not.found.strong=\u627E\u4E0D\u5230\u7A0B\u5E8F\u5305{0}\u3002\u8BF7\u8C03\u6574\u7C7B\u8DEF\u5F84, \u4EE5\u4FBF\u53EF\u4EE5\u8BBF\u95EE\u7A0B\u5E8F\u5305{0}\u3002 +javac.err.class.package.conflict=\u7C7B\u578B\u548C\u7A0B\u5E8F\u5305\u4E0D\u80FD\u540C\u540D\u3002\u53EF\u4EE5\u8BBF\u95EE\u7A0B\u5E8F\u5305{0}\u65F6, \u4E0D\u80FD\u4F7F\u7528\u540D\u79F0{0}\u6765\u547D\u540D\u7C7B\u3002 +javac.err.package.class.conflict=\u7C7B\u578B\u548C\u7A0B\u5E8F\u5305\u4E0D\u80FD\u540C\u540D\u3002\u53EF\u4EE5\u8BBF\u95EE\u7C7B{1}\u65F6, \u4E0D\u80FD\u4F7F\u7528\u540D\u79F0{0}\u6765\u547D\u540D\u7A0B\u5E8F\u5305\u3002 +javac.err.package.class.conflict.strong=\u540D\u79F0{0}\u5FC5\u987B\u53C2\u8003\u7A0B\u5E8F\u5305\u3002\u7531\u4E8E\u7C7B\u578B\u548C\u7A0B\u5E8F\u5305\u4E0D\u80FD\u540C\u540D, \u5982\u679C\u53EF\u8BBF\u95EE\u7C7B\u540D\u4E3A{1}\u5219\u4E3A\u975E\u6CD5\u3002\u5E94\u91CD\u547D\u540D\u7C7B{1}\u6216\u5C06\u5176\u4ECE\u7C7B\u8DEF\u5F84\u4E2D\u5220\u9664\u3002 +javac.err.illegal.mangled.name={1}\u7684\u540D\u79F0{0}\u65E0\u6548\u3002 +javac.err.class.and.package=\u4E0D\u660E\u786E\u7684\u540D\u79F0: {0}\u65E2\u662F\u7C7B\u53C8\u662F\u7A0B\u5E8F\u5305\u3002 +javac.err.throws.not.throwable=throws \u5B50\u53E5\u4E2D\u7684{0}\u5FC5\u987B\u662F\u7C7B java.lang.Throwable \u7684\u5B50\u7C7B\u3002 +javac.err.throw.not.throwable=\u65E0\u6CD5\u629B\u51FA{0}; \u5B83\u5FC5\u987B\u4E3A\u7C7B java.lang.Throwable \u7684\u5B50\u7C7B\u3002 +javac.err.catch.not.throwable=\u65E0\u6CD5\u6355\u83B7{0}; \u5B83\u5FC5\u987B\u4E3A\u7C7B java.lang.Throwable \u7684\u5B50\u7C7B\u3002 +javac.err.initializer.exception=\u4E0D\u80FD\u5728\u521D\u59CB\u5316\u7A0B\u5E8F\u4E2D\u629B\u51FA\u5F02\u5E38\u9519\u8BEF{0}\u3002 +javac.err.cant.read=\u65E0\u6CD5\u8BFB\u53D6: {0} +javac.err.cant.write=\u65E0\u6CD5\u5199\u5165: {0} +javac.err.fatal.error=\u7F16\u8BD1\u5668\u51FA\u9519; \u8BF7\u5EFA\u7ACB Bug \u62A5\u544A (http://bugreport.java.com/bugreport/)\u3002 +javac.err.fatal.exception=\u7F16\u8BD1\u5668\u51FA\u73B0\u5F02\u5E38\u9519\u8BEF; \u8BF7\u5EFA\u7ACB Bug \u62A5\u544A (http://bugreport.java.com/bugreport/)\u3002 +javac.err.no.inner.classes=\u5DF2\u7981\u7528\u5BF9\u5185\u90E8\u7C7B\u7684\u652F\u6301\u3002 +javac.err.uncaught.exception=\u5FC5\u987B\u6355\u83B7\u5F02\u5E38\u9519\u8BEF{0}, \u5426\u5219\u5FC5\u987B\u5728\u6B64\u65B9\u6CD5\u7684 throws \u5B50\u53E5\u4E2D\u5BF9\u5176\u8FDB\u884C\u58F0\u660E\u3002 +javac.err.constructor.exception=\u5FC5\u987B\u6355\u83B7\u5F02\u5E38\u9519\u8BEF{0}, \u5426\u5219\u5FC5\u987B\u5728\u6B64\u6784\u9020\u5668\u7684 throws \u5B50\u53E5\u4E2D\u5BF9\u5176\u8FDB\u884C\u58F0\u660E\u3002 +javac.err.def.constructor.exception=\u7531\u4E8E\u7C7B\u7684\u8D85\u7C7B\u7684\u6784\u9020\u5668\u629B\u51FA\u5F02\u5E38\u9519\u8BEF{0}, \u56E0\u6B64\u65E0\u6CD5\u4E3A\u6B64\u7C7B\u521B\u5EFA\u9ED8\u8BA4\u6784\u9020\u5668\u3002\u4E3A\u6B64\u7C7B\u663E\u5F0F\u5B9A\u4E49\u6784\u9020\u5668\u3002 +javac.err.catch.not.thrown=\u4ECE\u672A\u5728\u76F8\u5E94\u7684 try \u8BED\u53E5\u4E3B\u4F53\u4E2D\u629B\u51FA\u5F02\u5E38\u9519\u8BEF{0}\u3002 +#warning: +javac.err.array.clone.supported=\u6CE8: \u6570\u7EC4\u7684\u514B\u9686\u4E0D\u4F1A\u629B\u51FA\u4EFB\u4F55\u53D7\u63A7\u5F02\u5E38\u9519\u8BEF, \u56E0\u6B64\u4E0D\u9700\u8981\u4F7F\u7528\u4EFB\u4F55 catch \u5B50\u53E5\u3002\u8BF7\u5220\u9664\u672A\u4F7F\u7528\u7684 catch \u5B50\u53E5, \u6216\u8005\u5982\u679C\u8981\u4FDD\u6301\u4E0E\u65E7\u7248\u7F16\u8BD1\u5668\u7684\u517C\u5BB9\u6027, \u53EF\u4EE5\u6309\u5982\u4E0B\u6240\u793A\u63D2\u5165\u4EBA\u5DE5\u629B\u51FA: if (false) throw new CloneNotSupportedException(); +javac.err.no.outer.arg=\u8303\u56F4\u5185\u6CA1\u6709{0}\u7684\u5C01\u95ED\u5B9E\u4F8B; \u521B\u5EFA{1}\u65F6\u5FC5\u987B\u63D0\u4F9B\u4E00\u4E2A\u663E\u5F0F\u5C01\u95ED\u5B9E\u4F8B, \u4F8B\u5982 "outer. new Inner()" \u6216 "outer. super()" \u4E2D\u6240\u793A\u3002 +javac.err.no.default.outer.arg=\u8303\u56F4\u5185\u6CA1\u6709{0}\u7684\u5C01\u95ED\u5B9E\u4F8B; \u65E0\u6CD5\u4E3A{1}\u521B\u5EFA\u9ED8\u8BA4\u6784\u9020\u5668\u3002 +javac.err.no.outer.base=\u8303\u56F4\u5185\u6CA1\u6709{0}\u7684\u5C01\u95ED\u5B9E\u4F8B; \u8BBF\u95EE{1}\u65F6\u5FC5\u987B\u63D0\u4F9B\u4E00\u4E2A\u663E\u5F0F\u5C01\u95ED\u5B9E\u4F8B, \u5982 "outer.member" \u4E2D\u6240\u793A\u3002 +javac.err.inner.interface=\u6210\u5458\u63A5\u53E3\u53EA\u80FD\u51FA\u73B0\u5728\u63A5\u53E3\u548C\u9876\u5C42\u7C7B\u4E2D\u3002 +javac.err.static.inner.class=\u7C7B\u578B{0}\u4E0D\u80FD\u4E3A\u9759\u6001\u7C7B\u578B\u3002\u9759\u6001\u6210\u5458\u53EA\u80FD\u51FA\u73B0\u5728\u63A5\u53E3\u548C\u9876\u5C42\u7C7B\u4E2D\u3002 +javac.err.static.inner.field=\u53D8\u91CF{0}\u5728{1}\u4E2D\u4E0D\u80FD\u4E3A\u9759\u6001\u53D8\u91CF\u3002\u53EA\u6709\u63A5\u53E3\u548C\u9876\u5C42\u7C7B\u7684\u6210\u5458\u624D\u80FD\u4E3A\u9759\u6001\u53D8\u91CF\u3002 +javac.err.static.inner.method=\u65B9\u6CD5{0}\u5728{1}\u4E2D\u4E0D\u80FD\u4E3A\u9759\u6001\u65B9\u6CD5\u3002\u53EA\u6709\u63A5\u53E3\u548C\u9876\u5C42\u7C7B\u7684\u6210\u5458\u624D\u80FD\u4E3A\u9759\u6001\u65B9\u6CD5\u3002 +javac.err.too.many.errors=\u9519\u8BEF\u592A\u591A\u3002(\u5BF9\u62A5\u544A\u7684\u9519\u8BEF\u7684\u9650\u5236\u503C\u4E3A {0}\u3002) +javac.err.override.static.with.instance=\u5728{1}\u4E2D\u58F0\u660E\u7684\u5B9E\u4F8B\u65B9\u6CD5{0}\u4E0D\u80FD\u8986\u76D6\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u9759\u6001\u65B9\u6CD5\u3002\u8986\u76D6\u9759\u6001\u65B9\u6CD5\u662F\u975E\u6CD5\u7684\u3002 +javac.err.hide.instance.with.static=\u5728{1}\u4E2D\u58F0\u660E\u7684\u9759\u6001\u65B9\u6CD5{0}\u4E0D\u80FD\u9690\u85CF\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u5B9E\u4F8B\u65B9\u6CD5\u3002\u9690\u85CF\u5B9E\u4F8B\u65B9\u6CD5\u662F\u975E\u6CD5\u7684\u3002 +javac.err.override.final.method=\u5728{1}\u4E2D\u58F0\u660E\u7684\u65B9\u6CD5{0}\u4E0D\u80FD\u8986\u76D6\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u6700\u7EC8\u65B9\u6CD5\u3002\u4E0D\u80FD\u8986\u76D6\u6700\u7EC8\u65B9\u6CD5\u3002 +javac.err.override.is.deprecated=\u5728{1}\u4E2D\u58F0\u660E\u7684\u65B9\u6CD5{0}\u672A\u8FC7\u65F6, \u4F46\u662F\u5C06\u8986\u76D6\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u5DF2\u8FC7\u65F6\u65B9\u6CD5\u3002 +javac.err.override.more.restrictive=\u5728{1}\u4E2D\u58F0\u660E\u7684\u65B9\u6CD5{0}\u4E0D\u80FD\u8986\u76D6\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u65B9\u6CD5\u3002\u5DF2\u5BF9\u8BBF\u95EE\u4FEE\u9970\u7B26\u8FDB\u884C\u4E86\u66F4\u591A\u9650\u5236\u3002 +javac.err.override.different.return=\u5728{1}\u4E2D\u58F0\u660E\u7684\u65B9\u6CD5{0}\u4E0D\u80FD\u8986\u76D6\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u65B9\u6CD5\u3002\u5B83\u4EEC\u7684\u8FD4\u56DE\u7C7B\u578B\u5FC5\u987B\u76F8\u540C\u3002\t +javac.err.override.incompatible.exceptions=\u5728{1}\u4E2D\u58F0\u660E\u7684\u65B9\u6CD5{0}\u4E0D\u80FD\u8986\u76D6\u5728{2}\u4E2D\u58F0\u660E\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u65B9\u6CD5\u3002\u5B83\u4EEC\u7684 throws \u5B50\u53E5\u4E0D\u517C\u5BB9\u3002 +javac.err.meet.different.return=\u4ECE{1}\u7EE7\u627F\u7684\u65B9\u6CD5{0}\u4E0E\u4ECE{2}\u7EE7\u627F\u7684\u5177\u6709\u76F8\u540C\u7B7E\u540D\u7684\u65B9\u6CD5\u4E0D\u517C\u5BB9\u3002\u5B83\u4EEC\u7684\u8FD4\u56DE\u7C7B\u578B\u5FC5\u987B\u76F8\u540C\u3002 +javac.err.nontrivial.meet=\u4ECE{1}\u548C{2}\u7EE7\u627F\u7684\u65B9\u6CD5{0}\u7684\u5B9A\u4E49\u662F\u517C\u5BB9\u7684, \u4F46\u4E24\u8005\u7684\u7EC4\u5408\u662F\u975E\u51E1\u7684\u5E76\u4E14\u5C1A\u672A\u5B9E\u73B0\u3002\u89E3\u51B3\u65B9\u6CD5\u662F: \u5728\u6B64\u7C7B\u4E2D\u663E\u5F0F\u58F0\u660E{0}\u3002 +javac.err.method.too.long=\u6B64\u4EE3\u7801\u8981\u6C42\u751F\u6210\u5927\u4E8E 64K \u5B57\u8282\u7684\u65B9\u6CD5\u3002\u865A\u62DF\u673A\u53EF\u80FD\u4F1A\u62D2\u7EDD\u7ED3\u679C\u7C7B\u6587\u4EF6\u3002 +# +javac.err.version.too.old=\u4E3B\u7248\u672C ''{0}'' \u592A\u65E7, \u6B64\u5DE5\u5177\u65E0\u6CD5\u8BC6\u522B\u3002 +javac.err.version.too.recent=major.minor \u7248\u672C ''{0}'' \u592A\u65B0, \u6B64\u5DE5\u5177\u65E0\u6CD5\u8BC6\u522B\u3002 +# +benv.parsed_in=[\u5DF2\u5728 {1} \u6BEB\u79D2\u5185\u5BF9{0}\u8FDB\u884C\u8BED\u6CD5\u5206\u6790] +benv.loaded_in=[\u5DF2\u5728 {1} \u6BEB\u79D2\u5185\u52A0\u8F7D{0}] +benv.failed_to_close_class_path=\u65E0\u6CD5\u5173\u95ED\u7C7B\u8DEF\u5F84: {0} +# +main.usage=\u7528\u6CD5: {0} \n\n\u5176\u4E2D \u5305\u62EC:\n -g \u751F\u6210\u6240\u6709\u8C03\u8BD5\u4FE1\u606F\n -g:none \u4E0D\u751F\u6210\u4EFB\u4F55\u8C03\u8BD5\u4FE1\u606F\n -g:'{'lines,vars,source'}' \u53EA\u751F\u6210\u67D0\u4E9B\u8C03\u8BD5\u4FE1\u606F\n -O \u4F18\u5316; \u53EF\u4EE5\u963B\u788D\u8C03\u8BD5\u6216\u6269\u5927\u7C7B\u6587\u4EF6\n -nowarn \u4E0D\u751F\u6210\u4EFB\u4F55\u8B66\u544A\n -verbose \u8F93\u51FA\u6709\u5173\u7F16\u8BD1\u5668\u6B63\u5728\u6267\u884C\u7684\u64CD\u4F5C\u7684\u6D88\u606F\n -deprecation \u8F93\u51FA\u4F7F\u7528\u5DF2\u8FC7\u65F6\u7684 API \u7684\u6E90\u4F4D\u7F6E\n -classpath \u6307\u5B9A\u67E5\u627E\u7528\u6237\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n -sourcepath \u6307\u5B9A\u67E5\u627E\u8F93\u5165\u6E90\u6587\u4EF6\u7684\u4F4D\u7F6E\n -bootclasspath \u8986\u76D6\u5F15\u5BFC\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n -extdirs \u8986\u76D6\u6240\u5B89\u88C5\u6269\u5C55\u7684\u4F4D\u7F6E\n -d \u6307\u5B9A\u653E\u7F6E\u751F\u6210\u7684\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n -encoding \u6307\u5B9A\u6E90\u6587\u4EF6\u4F7F\u7528\u7684\u5B57\u7B26\u7F16\u7801\n -target \u751F\u6210\u7279\u5B9A VM \u7248\u672C\u7684\u7C7B\u6587\u4EF6 +# +main.unsupported.usage=\ -Xdepend \u9012\u5F52\u641C\u7D22\u6700\u65B0\u6E90\u6587\u4EF6\u4EE5\u8FDB\u884C\u91CD\u65B0\u7F16\u8BD1\n -Xstdout \u5C06\u6D88\u606F\u53D1\u9001\u5230 System.out\n -Xverbosepath \u8BF4\u660E\u641C\u7D22\u8DEF\u5F84\u548C\u6807\u51C6\u6269\u5C55\u7684\u65B9\u6CD5\n -J<\u8FD0\u884C\u65F6\u6807\u8BB0> \u5411 java \u89E3\u91CA\u5668\u4F20\u9012\u53C2\u6570\n\n-X \u548C -J \u9009\u9879\u90FD\u662F\u975E\u6807\u51C6\u9009\u9879, \u5982\u6709\u66F4\u6539, \u6055\u4E0D\u53E6\u884C\u901A\u77E5\u3002 +# +main.conflicting.options=\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\u9009\u9879{0}\u548C{1}\u3002 +main.option.already.seen={0}\u9009\u9879\u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\u3002 +main.option.requires.argument=\u9009\u9879{0}\u9700\u8981\u53C2\u6570\u3002 +main.bad.debug.option={0}\u9009\u9879\u7684\u683C\u5F0F\u4E0D\u5BF9\u3002\u53EA\u80FD\u4EE5\u9017\u53F7\u5206\u9694\u7684\u5F62\u5F0F\u6307\u5B9A "lines", "vars" \u548C "source"\u3002 +main.no.such.directory={0} \u76EE\u5F55\u4E0D\u5B58\u5728\u3002 +main.no.such.option={0}\u662F\u65E0\u6548\u9009\u9879\u6216\u53C2\u6570\u3002 +main.unknown.release=\u6B64\u7F16\u8BD1\u5668\u4E0D\u8BC6\u522B\u53D1\u884C\u7248 ''{0}''\u3002 +main.wrote=[\u5DF2\u5199\u5165{0}] +main.errors={0} \u4E2A\u9519\u8BEF +main.1error=1 \u4E2A\u9519\u8BEF +main.warnings={0} \u4E2A\u8B66\u544A +main.1warning=1 \u4E2A\u8B66\u544A +main.done_in=[\u5728 {0} \u6BEB\u79D2\u5185\u5B8C\u6210] +main.no.memory=\u7F16\u8BD1\u5668\u6240\u7528\u5185\u5B58\u4E0D\u8DB3\u3002\u8BF7\u8003\u8651\u4F7F\u7528 "-J-mx<\u6570\u5B57>" \u547D\u4EE4\u884C\u9009\u9879\u6765\u63D0\u9AD8\u5806\u5927\u5C0F\u7684\u6700\u5927\u503C\u3002 +main.stack.overflow=\u7F16\u8BD1\u5668\u6240\u7528\u5806\u6808\u7A7A\u95F4\u4E0D\u8DB3\u3002\u8BF7\u8003\u8651\u4F7F\u7528 "-J-oss<\u6570\u5B57>" \u547D\u4EE4\u884C\u9009\u9879\u6765\u63D0\u9AD8\u5206\u914D\u7ED9 Java \u5806\u6808\u7684\u5185\u5B58\u5927\u5C0F\u3002 +main.path.msg=[\u6E90\u7C7B\u8DEF\u5F84\u4E3A "{0}"]\n[\u5E93\u7C7B\u8DEF\u5F84\u4E3A "{1}"] +javac.err.invalid.encoding.char=\u6E90\u6587\u4EF6\u7F16\u7801\u4E0E\u6B64\u5E73\u53F0\u7F16\u7801\u4E0D\u540C\u3002\u8BF7\u4F7F\u7528 -encoding \u9009\u9879\u6765\u8C03\u6574\u6587\u4EF6\u7F16\u7801, \u6216\u786E\u4FDD\u6E90\u6587\u4EF6\u8F6C\u6362\u4E3A ASCII \u7F16\u7801\u3002 diff --git a/rmic/src/test/README b/rmic/src/test/README new file mode 100644 index 000000000..4f7d25603 --- /dev/null +++ b/rmic/src/test/README @@ -0,0 +1,53 @@ +The files in this directory were generated by the JDK 8 rmic tool from classes compiled for the functional tests: + +[DEBUG] rmic arguments: +[DEBUG] -classpath +[DEBUG] /Users/rgold/projects/glassfish/glassfish-corba/functional-tests/target/test-classes:/Users/rgold/projects/glassfish/glassfish-corba/functional-tests/target/classes:/Users/rgold/.m2/repository/org/glassfish/gmbal/gmbal-api-only/3.1.0-b001/gmbal-api-only-3.1.0-b001.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-csiv2-idl/4.1.1-b002-SNAPSHOT/glassfish-corba-csiv2-idl-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-omgapi/4.1.1-b002-SNAPSHOT/glassfish-corba-omgapi-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-orb/4.1.1-b002-SNAPSHOT/glassfish-corba-orb-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-internal-api/4.1.1-b002-SNAPSHOT/glassfish-corba-internal-api-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/exception-annotation-processor/4.1.1-b002-SNAPSHOT/exception-annotation-processor-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/apache/felix/org.osgi.core/1.2.0/org.osgi.core-1.2.0.jar:/Users/rgold/.m2/repository/org/glassfish/grizzly/grizzly-framework/2.2.10/grizzly-framework-2.2.10.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-basic/4.0.0-b008/pfl-basic-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-basic-tools/4.0.0-b008/pfl-basic-tools-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-dynamic/4.0.0-b008/pfl-dynamic-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-asm/4.0.0-b008/pfl-asm-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/gmbal/gmbal/3.1.0-b001/gmbal-3.1.0-b001.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-tf/4.0.0-b008/pfl-tf-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-tf-tools/4.0.0-b008/pfl-tf-tools-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-test/4.0.0-b008/pfl-test-4.0.0-b008.jar:/Users/rgold/.m2/repository/junit/junit/4.7/junit-4.7.jar:/Users/rgold/.m2/repository/org/glassfish/external/management-api/3.1.0-b001/management-api-3.1.0-b001.jar:/Users/rgold/.m2/repository/org/testng/testng/6.1.1/testng-6.1.1.jar:/Users/rgold/.m2/repository/org/beanshell/bsh/2.0b4/bsh-2.0b4.jar:/Users/rgold/.m2/repository/com/beust/jcommander/1.12/jcommander-1.12.jar:/Users/rgold/.m2/repository/org/yaml/snakeyaml/1.6/snakeyaml-1.6.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home/jre/../lib/tools.jar +[DEBUG] -d +[DEBUG] /Users/rgold/projects/glassfish/glassfish-corba/functional-tests/target/test-classes +[DEBUG] -iiop +[DEBUG] -poa +[DEBUG] -keep +[DEBUG] -verbose +[DEBUG] corba.preinvokepostinvoke.MyServant +[DEBUG] corba.systemexceptions.rmiiIServantPOA +[DEBUG] corba.hcks.rmiiIServantPOA +[DEBUG] corba.giopheaderpadding.rmiiIServantPOA +[DEBUG] corba.islocal.rmiiIServantPOA +[DEBUG] corba.exceptiondetailsc.rmiiIServantPOA +[DEBUG] corba.rmipoacounter.counterImpl + + +--- +[DEBUG] rmic arguments: +[DEBUG] -classpath +[DEBUG] /Users/rgold/projects/glassfish/glassfish-corba/functional-tests/target/test-classes:/Users/rgold/projects/glassfish/glassfish-corba/functional-tests/target/classes:/Users/rgold/.m2/repository/org/glassfish/gmbal/gmbal-api-only/3.1.0-b001/gmbal-api-only-3.1.0-b001.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-csiv2-idl/4.1.1-b002-SNAPSHOT/glassfish-corba-csiv2-idl-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-omgapi/4.1.1-b002-SNAPSHOT/glassfish-corba-omgapi-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-orb/4.1.1-b002-SNAPSHOT/glassfish-corba-orb-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/glassfish-corba-internal-api/4.1.1-b002-SNAPSHOT/glassfish-corba-internal-api-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/glassfish/corba/exception-annotation-processor/4.1.1-b002-SNAPSHOT/exception-annotation-processor-4.1.1-b002-SNAPSHOT.jar:/Users/rgold/.m2/repository/org/apache/felix/org.osgi.core/1.2.0/org.osgi.core-1.2.0.jar:/Users/rgold/.m2/repository/org/glassfish/grizzly/grizzly-framework/2.2.10/grizzly-framework-2.2.10.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-basic/4.0.0-b008/pfl-basic-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-basic-tools/4.0.0-b008/pfl-basic-tools-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-dynamic/4.0.0-b008/pfl-dynamic-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-asm/4.0.0-b008/pfl-asm-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/gmbal/gmbal/3.1.0-b001/gmbal-3.1.0-b001.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-tf/4.0.0-b008/pfl-tf-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-tf-tools/4.0.0-b008/pfl-tf-tools-4.0.0-b008.jar:/Users/rgold/.m2/repository/org/glassfish/pfl/pfl-test/4.0.0-b008/pfl-test-4.0.0-b008.jar:/Users/rgold/.m2/repository/junit/junit/4.7/junit-4.7.jar:/Users/rgold/.m2/repository/org/glassfish/external/management-api/3.1.0-b001/management-api-3.1.0-b001.jar:/Users/rgold/.m2/repository/org/testng/testng/6.1.1/testng-6.1.1.jar:/Users/rgold/.m2/repository/org/beanshell/bsh/2.0b4/bsh-2.0b4.jar:/Users/rgold/.m2/repository/com/beust/jcommander/1.12/jcommander-1.12.jar:/Users/rgold/.m2/repository/org/yaml/snakeyaml/1.6/snakeyaml-1.6.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home/jre/../lib/tools.jar +[DEBUG] -d +[DEBUG] /Users/rgold/projects/glassfish/glassfish-corba/functional-tests/target/test-classes +[DEBUG] -iiop +[DEBUG] -keep +[DEBUG] -verbose +[DEBUG] corba.hcks.rmiiIServant + + + +---- generated files ---- + +functional-tests/target//test-classes/corba/systemexceptions/_rmiiI_Stub.java +functional-tests/target//test-classes/corba/systemexceptions/_rmiiIServantPOA_Tie.java +functional-tests/target//test-classes/corba/preinvokepostinvoke/_Interface_Stub.java +functional-tests/target//test-classes/corba/preinvokepostinvoke/_MyServant_Tie.java +functional-tests/target//test-classes/corba/islocal/_rmiiI_Stub.java +functional-tests/target//test-classes/corba/islocal/_rmiiIServantPOA_Tie.java +functional-tests/target//test-classes/corba/hcks/_rmiiI_Stub.java +functional-tests/target//test-classes/corba/hcks/_rmiiIServantPOA_Tie.java +functional-tests/target//test-classes/corba/hcks/_rmiiIServant_Tie.java +functional-tests/target//test-classes/corba/rmipoacounter/_counterIF_Stub.java +functional-tests/target//test-classes/corba/rmipoacounter/_counterImpl_Tie.java +functional-tests/target//test-classes/corba/giopheaderpadding/_rmiiI_Stub.java +functional-tests/target//test-classes/corba/giopheaderpadding/_rmiiIServantPOA_Tie.java +functional-tests/target//test-classes/corba/exceptiondetailsc/_rmiiI_Stub.java +functional-tests/target//test-classes/corba/exceptiondetailsc/_rmiiIServantPOA_Tie.java + + + diff --git a/rmic/src/test/java/TopLevelClass.java b/rmic/src/test/java/TopLevelClass.java new file mode 100644 index 000000000..6326c03a8 --- /dev/null +++ b/rmic/src/test/java/TopLevelClass.java @@ -0,0 +1,12 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +public class TopLevelClass { +} diff --git a/rmic/src/test/java/org/glassfish/rmic/BatchEnvironmentTest.java b/rmic/src/test/java/org/glassfish/rmic/BatchEnvironmentTest.java new file mode 100644 index 000000000..eea1b0327 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/BatchEnvironmentTest.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.junit.Test; + +import java.io.File; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.arrayWithSize; + +public class BatchEnvironmentTest { + + @Test + public void createdClassPathString_usesPathSeparator() throws Exception { + String systemPath = "./jdk/jre/lib/rt.jar"; + String classPath = "./user.jar" + File.pathSeparator + "./user2.jar" + File.pathSeparator + "./user3.jar"; + + assertThat(BatchEnvironment.createClassPath(classPath, systemPath).toString().split(File.pathSeparator), arrayWithSize(4)); + } + } diff --git a/rmic/src/test/java/org/glassfish/rmic/MainTest.java b/rmic/src/test/java/org/glassfish/rmic/MainTest.java new file mode 100644 index 000000000..020fd5b69 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/MainTest.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.classes.hcks.RmiIIServant; +import org.glassfish.rmic.tools.java.ClassPath; +import org.glassfish.rmic.tools.java.Identifier; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import static org.glassfish.rmic.tools.java.Constants.F_WARNINGS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public class MainTest { + + private ClassPath classPath = new ClassPath(); + private ByteArrayOutputStream out = new ByteArrayOutputStream(); + private BatchEnvironment environment; + private Main main = new Main(out, "rmic"); + private File destDir; + + @Before + public void setUp() throws Exception { + destDir = Files.createTempDirectory("rmic").toFile(); + environment = new BatchEnvironment(out, classPath, destDir); + environment.flags = F_WARNINGS; + } + + @Test + public void whenNoErrorsOrWarnings_displayErrorsReturnsTrue() throws Exception { + assertThat(main.displayErrors(environment), is(true)); + } + + @Test + public void afterOneError_displayErrorsReturnsFalse() throws Exception { + environment.error(0, "error"); + + assertThat(main.displayErrors(environment), is(false)); + } + + @Test + public void whenNoErrorsOrWarnings_outputIsEmpty() throws Exception { + main.displayErrors(environment); + + assertThat(getOutput(), isEmptyString()); + } + + private String getOutput() throws IOException { + out.close(); + return out.toString(); + } + + @Test + public void afterOneError_outputReportsOneError() throws Exception { + reportError(); + + main.displayErrors(environment); + + assertThat(getOutput(), containsString("1 error")); + } + + private void reportError() { + environment.error(0, "rmic.wrote", "something bad"); + } + + @Test + public void afterThreeErrors_outputReportsNumberOfErrors() throws Exception { + reportError(); + reportError(); + reportError(); + + main.displayErrors(environment); + + assertThat(getOutput(), containsString("3 errors")); + } + + @Test + public void afterOneWarning_outputReportsOneWarning() throws Exception { + reportWarning(); + + main.displayErrors(environment); + + assertThat(getOutput(), containsString("1 warning")); + } + + private void reportWarning() { + environment.error(0, "warn.rmic.member.not.mapped", "foo", "bar"); + } + + @Test + public void afterThreeWarningss_outputReportsNumberOfErrors() throws Exception { + reportWarning(); + reportWarning(); + reportWarning(); + + main.displayErrors(environment); + + assertThat(getOutput(), containsString("3 warnings")); + } + + @Test + public void afterOneErrorAndTwoWarnings_outputReportsNumbersOfBoth() throws Exception { + reportError(); + reportWarning(); + reportWarning(); + + main.displayErrors(environment); + + assertThat(getOutput(), containsString("1 error, 2 warnings")); + } + + @Test + public void afterTwoErrorsAndOneWarnings_outputReportsNumbersOfBoth() throws Exception { + reportError(); + reportError(); + reportWarning(); + + main.displayErrors(environment); + + assertThat(getOutput(), containsString("2 errors, 1 warning")); + } + + @Test + public void afterGenerateStubs_getGeneratedClassNames() throws Exception { + main.parseArgs("-iiop", "-classpath", TestUtils.getClassPathString(), "-d", destDir.getAbsolutePath()); + environment = main.getEnv(); + Identifier identifier = Main.getClassIdentifier(environment, RmiIIServant.class.getName()); + main.generateClass(environment, identifier); + + assertThat(main.getGeneratedClassNames(environment), + arrayContainingInAnyOrder("org.glassfish.rmic.classes.hcks._RmiII_Stub", "org.glassfish.rmic.classes.hcks._RmiIIServant_Tie")); + } + +} diff --git a/rmic/src/test/java/org/glassfish/rmic/RmicGenerationTest.java b/rmic/src/test/java/org/glassfish/rmic/RmicGenerationTest.java new file mode 100644 index 000000000..30cf65e6e --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/RmicGenerationTest.java @@ -0,0 +1,404 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import org.glassfish.rmic.classes.covariantReturn.DogFinder; +import org.glassfish.rmic.classes.errorClasses.InterfaceWithNonRemoteMethod; +import org.glassfish.rmic.classes.errorClasses.NotRemoteClass; +import org.glassfish.rmic.classes.exceptiondetailsc.ExceptionSourceServantPOA; +import org.glassfish.rmic.classes.giopheaderpadding.FooServantPOA; +import org.glassfish.rmic.classes.hcks.RmiII; +import org.glassfish.rmic.classes.hcks.RmiIIServant; +import org.glassfish.rmic.classes.hcks.RmiIIServantPOA; +import org.glassfish.rmic.classes.inneraccess.Rainbow; +import org.glassfish.rmic.classes.islocal.MessageBuilderServantPOA; +import org.glassfish.rmic.classes.preinvokepostinvoke.MyServant; +import org.glassfish.rmic.classes.primitives.InterfaceWithConstantArray; +import org.glassfish.rmic.classes.primitives.InterfaceWithNonPrimitiveConstant; +import org.glassfish.rmic.classes.primitives.RmiTestRemoteImpl; +import org.glassfish.rmic.classes.rmipoacounter.CounterImpl; +import org.glassfish.rmic.classes.systemexceptions.ServerInvokerServantPOA; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; + +/** + * Tests RMIC by comparing the kept generated source files against the expected files. + */ +public class RmicGenerationTest { + + private static int testNum = 0; + private static File rootDir; + private static final boolean COMPILE_GENERATED = true; // set false to check generated files without compiling + private static final String USE_LEGACY_PARSING_PROPERTY = "org.glassfish.rmic.UseLegacyClassParsing"; + + @SuppressWarnings("ResultOfMethodCallIgnored") + @BeforeClass + public static void clearRootDir() throws IOException { + rootDir = Files.createTempDirectory("rmic").toFile(); + } + + @Test + public void whenDefaultGeneratorSpecified_reportJRMPNoLongerSupported() throws Exception { + GenerationControl generator = new GenerationControl(FooServantPOA.class); + + try { + generator.generate(); + fail("Should have reported JRMP no longer supported"); + } catch (AssertionError e) { + assertThat(e.getMessage(), containsString("no longer supported")); + } + } + + @Test + public void generateIiopStubsWithoutPoa() throws Exception { + GenerationControl generator = new GenerationControl(RmiIIServant.class); + generator.addArgs("-iiop", "-keep"); + + generator.generate(); + + checkGeneratedFiles(generator, "without_poas", ".java"); + } + + @Test + public void whenKeepNotSpecified_deleteGeneratedJavaFiles() throws Exception { + assumeTrue(COMPILE_GENERATED); + GenerationControl generator = new GenerationControl(RmiIIServant.class); + generator.addArgs("-iiop"); + + generator.generate(); + + checkGeneratedFilesDeleted(generator); + } + + @Test + public void afterProcessing_classFilesArePresent() throws Exception { + assumeTrue(COMPILE_GENERATED); + GenerationControl generator = new GenerationControl(RmiIIServant.class); + generator.addArgs("-iiop"); + + generator.generate(); + + checkClassFilesPresent(generator, "without_poas"); + } + + + @Test + public void generateIiopStubsFromInterface() throws Exception { + GenerationControl generator = new GenerationControl(RmiII.class); + generator.addArgs("-iiop", "-keep"); + + generator.generate(); + + checkGeneratedFiles(generator, "stub_from_interface", ".java"); + } + + @Test + public void generateIiopStubsWithPoa() throws Exception { + GenerationControl generator = new GenerationControl( + ExceptionSourceServantPOA.class, MyServant.class, MessageBuilderServantPOA.class, CounterImpl.class, + ServerInvokerServantPOA.class, RmiIIServantPOA.class, FooServantPOA.class); + generator.addArgs("-iiop", "-keep", "-poa"); + generator.generate(); + + checkGeneratedFiles(generator, "with_poas", ".java"); + } + + @Test + public void generateIiopStubsWithConstant() throws Exception { + GenerationControl generator = new GenerationControl(RmiTestRemoteImpl.class); + generator.addArgs("-iiop","-always", "-keep"); + generator.generate(); + + checkGeneratedFiles(generator, "primitives", ".java"); + } + + @Test(expected = AssertionError.class) + public void dontGenerateIiopStubsWithConstantArray() throws Exception { + GenerationControl generator = new GenerationControl(InterfaceWithConstantArray.class); + generator.addArgs("-iiop","-always", "-keep"); + generator.generate(); + } + + @Test(expected = AssertionError.class) + public void dontGenerateIiopStubsWithConstantException() throws Exception { + GenerationControl generator = new GenerationControl(InterfaceWithNonPrimitiveConstant.class); + generator.addArgs("-iiop","-always", "-keep"); + generator.generate(); + } + + @Test + public void generateIdlForInnerClass() throws Exception { + GenerationControl generator = new GenerationControl(Rainbow.getInterfaceCheckerClass()); + generator.addArgs("-idl", "-keep"); + generator.generate(); + + checkGeneratedFiles(generator, "idl", ".idl"); + } + + @Test + public void whenKeepFlagNotSpecified_dontDeleteGeneratedIdlFiles() throws Exception { + GenerationControl generator = new GenerationControl(Rainbow.getInterfaceCheckerClass()); + generator.addArgs("-idl"); + generator.generate(); + + checkGeneratedFiles(generator, "idl", ".idl"); + } + + @Test + public void generateIdlForInnerClassUsingDotNotation() throws Exception { + GenerationControl generator = new GenerationControl(Rainbow.getQualifiedCheckerClassName()); + generator.addArgs("-idl", "-keep"); + generator.generate(); + + checkGeneratedFiles(generator, "idl", ".idl"); + } + + // NOTE: The test case from which this was based (http://hg.openjdk.java.net/jdk/jdk/file/9a29aa153c20/test/jdk/sun/rmi/rmic/covariantReturns) + // doesn't actually seem to test the feature. This one verifies that we can generate the stubs, but they appear to me to be incorrect, + // in that the generated derived type is actually returning the same type as its parent rather than the specified covariant type. + // More testing will be needed to see if it matters. + @Test + public void canHandleCovariantReturns() throws Exception { + GenerationControl generator = new GenerationControl(DogFinder.class); + generator.addArgs("-iiop", "-keep"); + generator.generate(); + } + + @Test + public void whenBinaryIsMissing_dontCompileSources() throws Exception { + File generatedFile = new File(TestUtils.getClassPathString() + "Interface.java"); + BufferedWriter writer = new BufferedWriter(new FileWriter(generatedFile)); + writer.write("public class Interface implements java.rmi.Remote { }"); + writer.close(); + + GenerationControl generator = new GenerationControl("Interface"); + generator.addArgs("-iiop"); + + try { + generator.generate(); + fail("Should not have succeeded in generating a stub"); + } catch (AssertionError e) { + assertThat(e.getMessage(), containsString("Class Interface not found")); + } + } + + @Test(expected = AssertionError.class) + public void whenClassDoesNotImplementRemote_cannotGenerate() throws Exception { + GenerationControl generator = new GenerationControl(NotRemoteClass.class); + generator.addArgs("-iiop"); + generator.generate(); + } + + @Test(expected = AssertionError.class) + public void whenInterfaceHasNonRemoteMethod_cannotGenerate() throws Exception { + GenerationControl generator = new GenerationControl(InterfaceWithNonRemoteMethod.class); + generator.addArgs("-iiop"); + generator.generate(); + } + + @Test + public void canGenerateNonPublicClass() throws Exception { + GenerationControl generator = new GenerationControl("org.glassfish.rmic.classes.errorClasses.PackageInterface"); + generator.addArgs("-iiop"); + generator.generate(); + } + + // Confirms that the generated files match those in the specified directory of master files + private void checkGeneratedFiles(GenerationControl generator, String mastersSubDir, String suffix) throws IOException { + File masterDir = new File(getModuleRoot(), "src/test/masters/" + mastersSubDir); + + String[] generatedFilePaths = getFilePaths(generator.getDestDir(), suffix); + String[] expectedFilePaths = getFilePaths(masterDir, suffix); + + assertThat("In " + generator.getDestDir(), generatedFilePaths, arrayContaining(expectedFilePaths)); + compareGeneratedFiles(masterDir, generator.getDestDir(), expectedFilePaths); + } + + private File getModuleRoot() { + String classPathString = TestUtils.getClassPathString(); + return new File(classPathString.substring(0, classPathString.lastIndexOf("/target/"))); + } + + // Verifies that the generated files were deleted + private void checkGeneratedFilesDeleted(GenerationControl generator) throws IOException { + String[] generatedFilePaths = getFilePaths(generator.getDestDir(), ".java"); + + assertThat("In " + generator.getDestDir(), generatedFilePaths, emptyArray()); + } + + // Confirms that the generated files match those in the specified directory of master files + @SuppressWarnings("SameParameterValue") + private void checkClassFilesPresent(GenerationControl generator, String mastersSubDir) throws IOException { + File masterDir = new File(getModuleRoot(), "src/test/masters/" + mastersSubDir); + + String[] generatedFilePaths = getFilePaths(generator.getDestDir(), ".class"); + String[] expectedFilePaths = toClassFilePaths(getFilePaths(masterDir, ".java")); + + assertThat("In " + generator.getDestDir(), generatedFilePaths, arrayContaining(expectedFilePaths)); + } + + private String[] toClassFilePaths(String[] sourceFilePaths) { + String[] result = new String[sourceFilePaths.length]; + for (int i = 0; i < sourceFilePaths.length; i++) + result[i] = sourceFilePaths[i].replace(".java", ".class"); + return result; + } + + // Returns a sorted array of paths to files with the specified suffix under the specified directory, relative to that directory + private String[] getFilePaths(File rootDir, String suffix) { + ArrayList files = new ArrayList<>(); + appendFiles(files, rootDir, rootDir.getAbsolutePath().length() + 1, suffix); + Collections.sort(files); + return files.toArray(new String[files.size()]); + } + + @SuppressWarnings("ConstantConditions") + private void appendFiles(ArrayList files, File currentDir, int rootDirLength, String suffix) { + for (File file : currentDir.listFiles()) + if (file.isDirectory()) + appendFiles(files, file, rootDirLength, suffix); + else if (file.getName().endsWith(suffix)) + files.add(getRelativePath(file, rootDirLength)); + } + + private String getRelativePath(File file, int rootDirLength) { + return file.getAbsolutePath().substring(rootDirLength); + } + + private void compareGeneratedFiles(File expectedDir, File actualDir, String... generatedFileNames) throws IOException { + for (String filePath : generatedFileNames) + compareFiles(filePath, expectedDir, actualDir); + } + + private void compareFiles(String filePath, File masterDirectory, File generationDirectory) throws IOException { + File expectedFile = new File(masterDirectory, filePath); + File actualFile = new File(generationDirectory, filePath); + + compareFiles(expectedFile, actualFile); + } + + private void compareFiles(File expectedFile, File actualFile) throws IOException { + LineNumberReader expected = new LineNumberReader(new FileReader(expectedFile)); + LineNumberReader actual = new LineNumberReader(new FileReader(actualFile)); + + String expectedLine = ""; + String actualLine = ""; + while (expectedLine != null && actualLine != null && linesMatch(expectedLine, actualLine)) { + expectedLine = expected.readLine(); + actualLine = actual.readLine(); + } + + if (expectedLine == null && actualLine == null) return; + + if (expectedLine == null) + fail("Unexpected line in generated file at " + actual.getLineNumber() + ": " + actualLine); + else if (actualLine == null) + fail("Actual file ends unexpectedly at line " + expected.getLineNumber()); + else + fail("Generated file mismatch at line " + actual.getLineNumber() + + "\nshould be <" + expectedLine + "> " + + "\nbut found <" + actualLine + ">"); + + } + + private boolean linesMatch(String expectedLine, String actualLine) { + return expectedLine.equals(actualLine) || expectedLine.trim().startsWith("* "); + } + + + private class GenerationControl { + private ArrayList argList = new ArrayList<>(); + private String[] classNames; + private File destDir; + private String warning; + + @SuppressWarnings("ResultOfMethodCallIgnored") + GenerationControl(String... classNames) { + this.classNames = classNames; + + String classPath = TestUtils.getClassPathString(); + destDir = new File(rootDir + "/" + (++testNum)); + destDir.mkdirs(); + addArgs("-classpath", classPath, "-d", destDir.getAbsolutePath()); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + private GenerationControl(Class... classes) { + this(toNameList(classes)); + } + + private void addArgs(String... args) { + argList.addAll(Arrays.asList(args)); + } + + File getDestDir() { + return destDir; + } + + String getWarning() { + return warning; + } + + private void generate() throws IOException { + if (argList.contains("-iiop") && !COMPILE_GENERATED) addArgs("-Xnocompile"); + for (String name : classNames) + addArgs(name); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Main compiler = new Main(out, "rmic"); + String[] argv = argList.toArray(new String[argList.size()]); + if (!compiler.compile(argv)) + throw createException(out); + else + warning = toMessage(out); + } + + private AssertionError createException(ByteArrayOutputStream out) throws IOException { + String message = toMessage(out); + if (message == null) message = "No error message reported"; + return new AssertionError(message); + } + + private String toMessage(ByteArrayOutputStream out) throws IOException { + out.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray()); + BufferedReader reader = new BufferedReader(new InputStreamReader(bais)); + + StringBuilder sb; + String line = reader.readLine(); + if (line == null) + return null; + else { + sb = new StringBuilder(line); + while ((line = reader.readLine()) != null && !line.startsWith("Usage:")) + sb.append("/n").append(line); + return sb.toString(); + } + } + } + + private static String[] toNameList(Class[] classes) { + String[] nameList = new String[classes.length]; + for (int i = 0; i < classes.length; i++) + nameList[i] = classes[i].getName(); + return nameList; + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/TestUtils.java b/rmic/src/test/java/org/glassfish/rmic/TestUtils.java new file mode 100644 index 000000000..f42dc6980 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/TestUtils.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic; + +import java.io.File; + +public class TestUtils { + @SuppressWarnings("ConstantConditions") + public static String getClassPathString() { + String classFileName = toPath(TestUtils.class.getName()); + String filePath = TestUtils.class.getClassLoader().getResource(classFileName).getPath(); + return filePath.substring(0, filePath.indexOf(classFileName)); + } + + private static String toPath(String className) { + return className.replace('.', File.separatorChar) + ".class"; + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/asm/AsmClassFactoryTest.java b/rmic/src/test/java/org/glassfish/rmic/asm/AsmClassFactoryTest.java new file mode 100644 index 000000000..d83734389 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/asm/AsmClassFactoryTest.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.asm; + +import org.glassfish.rmic.tools.java.ClassDefinitionFactoryTest; +import org.junit.Test; +import org.objectweb.asm.Opcodes; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +public class AsmClassFactoryTest extends ClassDefinitionFactoryTest { + + public AsmClassFactoryTest() { + super(new AsmClassFactory()); + } + + @Test + public void canRetrieveLatestAsmVersion() { + assertThat(AsmClassFactory.getLatestVersion(), equalTo(Opcodes.ASM6)); + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/asm/TypeFactoryTest.java b/rmic/src/test/java/org/glassfish/rmic/asm/TypeFactoryTest.java new file mode 100644 index 000000000..654b82eb2 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/asm/TypeFactoryTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.asm; + +import org.glassfish.rmic.classes.nestedClasses.TwoLevelNested; +import org.glassfish.rmic.tools.java.Identifier; +import org.glassfish.rmic.tools.java.Type; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.emptyArray; +import static org.hamcrest.Matchers.equalTo; + +public class TypeFactoryTest { + private TypeFactory factory = new TypeFactory(); + + @Test + public void constructNoArgVoidMethodType() throws Exception { + Type methodType = TypeFactory.createMethodType("()V"); + + assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); + assertThat(methodType.getArgumentTypes(), emptyArray()); + } + + @Test + public void constructByteArrayToIntType() throws Exception { + Type methodType = TypeFactory.createMethodType("([B)I"); + + assertThat(methodType.getReturnType(), equalTo(Type.tInt)); + assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tArray(Type.tByte))); + } + + @Test + public void constructAllNumericArgsToBooleanMethod() throws Exception { + Type methodType = TypeFactory.createMethodType("(SIJFD)Z"); + + assertThat(methodType.getReturnType(), equalTo(Type.tBoolean)); + assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tShort, Type.tInt, Type.tLong, Type.tFloat, Type.tDouble)); + } + + @Test + public void constructAllObjectArguments() throws Exception { + Type methodType = TypeFactory.createMethodType("(Ljava/lang/String;Lorg/glassfish/rmic/classes/nestedClasses/TwoLevelNested$Level1;)V"); + + assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); + assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tString, Type.tClass(Identifier.lookup(TwoLevelNested.Level1.class.getName())))); + } + + @Test + public void constructObjectArrayArgument() throws Exception { + Type methodType = TypeFactory.createMethodType("([Ljava/lang/Object;)V"); + + assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); + assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tArray(Type.tObject))); + } + + @Test + public void constructCharArrayArgument() throws Exception { + Type methodType = TypeFactory.createMethodType("([C)V"); + + assertThat(methodType.getReturnType(), equalTo(Type.tVoid)); + assertThat(methodType.getArgumentTypes(), arrayContaining(Type.tArray(Type.tChar))); + } + + @Test + public void constructMultiDimensionalArrayType() throws Exception { + assertThat(TypeFactory.createType("[[I"), equalTo(Type.tArray(Type.tArray(Type.tInt)))); + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/Animal.java b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/Animal.java new file mode 100644 index 000000000..5edf00cff --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/Animal.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.covariantReturn; + +import java.io.Serializable; + +public interface Animal extends Serializable { + String getName(); + + String speak(); +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/AnimalFinder.java b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/AnimalFinder.java new file mode 100644 index 000000000..f8108130d --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/AnimalFinder.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.covariantReturn; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface AnimalFinder extends Remote { + Animal getAnimalWithName(String name) throws RemoteException; + + Animal[][] getZooCages(int[][] sizes) throws RemoteException; + + double getValues(short a, long b, float c, double d) throws RemoteException; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/Dog.java b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/Dog.java new file mode 100644 index 000000000..e1c5fac4a --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/Dog.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.covariantReturn; + +public class Dog implements Animal { + private String name; + + public Dog(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public String speak() { + return "woof"; + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/DogFinder.java b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/DogFinder.java new file mode 100644 index 000000000..4a4e5d269 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/covariantReturn/DogFinder.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.covariantReturn; + +import java.rmi.RemoteException; + +public interface DogFinder extends AnimalFinder { + + @Override + Dog getAnimalWithName(String name) throws RemoteException; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/InterfaceWithNonRemoteMethod.java b/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/InterfaceWithNonRemoteMethod.java new file mode 100644 index 000000000..07aeeabb0 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/InterfaceWithNonRemoteMethod.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.errorClasses; + +public interface InterfaceWithNonRemoteMethod { + void doItHere(); +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/NotRemoteClass.java b/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/NotRemoteClass.java new file mode 100644 index 000000000..f07fe58e9 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/NotRemoteClass.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.errorClasses; + +import java.rmi.RemoteException; + +public class NotRemoteClass { + public void doIt() throws RemoteException {} +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/PackageInterface.java b/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/PackageInterface.java new file mode 100644 index 000000000..3ce15d9b2 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/errorClasses/PackageInterface.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.errorClasses; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +class PackageInterface implements Remote { + + void doItThere() throws RemoteException {} + +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/ExceptionSource.java b/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/ExceptionSource.java new file mode 100644 index 000000000..a44a90c07 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/ExceptionSource.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.exceptiondetailsc; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface ExceptionSource extends Remote { + void raiseSystemException(String x) throws RemoteException; + + void raiseUserException(String x) throws RemoteException, RmiIException; + + void raiseRuntimeException(String x) throws RemoteException; +} + + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/ExceptionSourceServantPOA.java b/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/ExceptionSourceServantPOA.java new file mode 100644 index 000000000..dd8b86b03 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/ExceptionSourceServantPOA.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.exceptiondetailsc; + +import org.omg.CORBA.FREE_MEM; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class ExceptionSourceServantPOA extends PortableRemoteObject implements ExceptionSource { + public static final String baseMsg = ExceptionSourceServantPOA.class.getName(); + + public ExceptionSourceServantPOA() throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + } + + public void raiseSystemException(String x) throws RemoteException { + throw new FREE_MEM(x); + } + + public void raiseUserException(String x) throws RemoteException, RmiIException { + throw new RmiIException(x); + } + + public void raiseRuntimeException(String x) throws RemoteException { + throw new RuntimeException(x); + } +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/RmiIException.java b/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/RmiIException.java new file mode 100644 index 000000000..73b81a25e --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/exceptiondetailsc/RmiIException.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.exceptiondetailsc; + +public class RmiIException extends Exception { + RmiIException(String x) + { + super(x); + } +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/giopheaderpadding/Foo.java b/rmic/src/test/java/org/glassfish/rmic/classes/giopheaderpadding/Foo.java new file mode 100644 index 000000000..de341c7a2 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/giopheaderpadding/Foo.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.giopheaderpadding; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface Foo extends Remote { + byte fooA(byte x) throws RemoteException; + void fooB() throws RemoteException; +} + +// End of file. + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/giopheaderpadding/FooServantPOA.java b/rmic/src/test/java/org/glassfish/rmic/classes/giopheaderpadding/FooServantPOA.java new file mode 100644 index 000000000..0707bf32d --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/giopheaderpadding/FooServantPOA.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.giopheaderpadding; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class FooServantPOA extends PortableRemoteObject implements Foo { + + public FooServantPOA() throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + } + + public byte fooA(byte x) { + System.out.println(x + ""); + return x; + } + + public void fooB() { + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiII.java b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiII.java new file mode 100644 index 000000000..79290ad30 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiII.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.hcks; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface RmiII extends Remote { + String sayHello() throws RemoteException; + + int sendBytes(byte[] x) throws RemoteException; + + Object sendOneObject(Object x) throws RemoteException, RmiIMyException; + + Object sendTwoObjects(Object x, Object y) throws RemoteException; + + String makeColocatedCallFromServant() throws RemoteException; + + String colocatedCallFromServant(String a) throws RemoteException, Exception; + + String throwThreadDeathInServant(String a) throws RemoteException, ThreadDeath; + + Object returnObjectFromServer(boolean isSerializable) throws RemoteException; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIIServant.java b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIIServant.java new file mode 100644 index 000000000..70b26e24e --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIIServant.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.hcks; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class RmiIIServant extends PortableRemoteObject implements RmiII { + + public RmiIIServant() throws RemoteException { + super(); + } + + public String sayHello() { + return "Hello, World!"; + } + + public int sendBytes (byte[] x) + { + if (x == null) + return -1; + return x.length; + } + + public Object sendOneObject(Object x) throws RmiIMyException { + return x; + } + + public Object sendTwoObjects (Object x, Object y) + { + return x; + } + + public String makeColocatedCallFromServant() throws RemoteException { + return ""; + } + + public String colocatedCallFromServant (String a) throws RemoteException { + return "B" + a; + } + + public String throwThreadDeathInServant (String a) throws RemoteException, ThreadDeath { + throw new ThreadDeath(); + } + + public Object returnObjectFromServer (boolean isSerializable) throws RemoteException { + return isSerializable ? "" : new RmiIIServant(); + } + +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIIServantPOA.java b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIIServantPOA.java new file mode 100644 index 000000000..7171d7332 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIIServantPOA.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 11 (Sat) 10:45:48 by Harold Carr. +// Last Modified : 2001 May 10 (Thu) 15:45:53 by Harold Carr. +// + +package org.glassfish.rmic.classes.hcks; + +import org.omg.CORBA.ORB; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +@SuppressWarnings({"WeakerAccess", "unused"}) +public class RmiIIServantPOA extends PortableRemoteObject implements RmiII { + public static final String baseMsg = RmiIIServantPOA.class.getName(); + + public String name; + + RmiIIServantPOA(ORB orb, String name) throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + this.name = name; + } + + public String sayHello() { + return "Hello, World!"; + } + + public int sendBytes(byte[] x) { + if (x == null) return -1; + return x.length; + } + + public Object sendOneObject(Object x) throws RmiIMyException { + return x; + } + + public Object sendTwoObjects(Object x, Object y) { + return x; + } + + public String makeColocatedCallFromServant() throws RemoteException { + return ""; + } + + private String doCall(RmiII rrmiiI, String resultSoFar) throws Exception { + String result = rrmiiI.colocatedCallFromServant(resultSoFar); + String op = "op"; + return op + " " + result; + } + + public String colocatedCallFromServant(String a) throws RemoteException { + String op = "op"; + return op + " " + a; + } + + public String throwThreadDeathInServant(String a) throws RemoteException, ThreadDeath { + throw new ThreadDeath(); + } + + public Object returnObjectFromServer(boolean isSerializable) throws RemoteException { + return isSerializable ? "" : new RmiIIServantPOA(null, ""); + } +} + +// End of file. diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIMyException.java b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIMyException.java new file mode 100644 index 000000000..4c672dea9 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/hcks/RmiIMyException.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.hcks; + +class RmiIMyException extends Exception { +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/inneraccess/ColorChecker.java b/rmic/src/test/java/org/glassfish/rmic/classes/inneraccess/ColorChecker.java new file mode 100644 index 000000000..31c1b5f67 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/inneraccess/ColorChecker.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.inneraccess; + +import java.rmi.RemoteException; + +public interface ColorChecker { + String getPreferredColor() throws RemoteException; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/inneraccess/Rainbow.java b/rmic/src/test/java/org/glassfish/rmic/classes/inneraccess/Rainbow.java new file mode 100644 index 000000000..28761b200 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/inneraccess/Rainbow.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.inneraccess; + +import java.rmi.RemoteException; + +public class Rainbow { + + class CheckerImpl implements ColorChecker { + @Override + public String getPreferredColor() throws RemoteException { + return "blue"; + } + } + + public static String getQualifiedCheckerClassName() { + return Rainbow.class.getName() + ".CheckerImpl"; + } + + public static Class getInterfaceCheckerClass() { + return CheckerImpl.class; + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/islocal/MessageBuilder.java b/rmic/src/test/java/org/glassfish/rmic/classes/islocal/MessageBuilder.java new file mode 100644 index 000000000..85f2ab41c --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/islocal/MessageBuilder.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.islocal; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface MessageBuilder extends Remote { + String m(String x) throws RemoteException; +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/islocal/MessageBuilderServantPOA.java b/rmic/src/test/java/org/glassfish/rmic/classes/islocal/MessageBuilderServantPOA.java new file mode 100644 index 000000000..073d93db4 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/islocal/MessageBuilderServantPOA.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.islocal; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class MessageBuilderServantPOA extends PortableRemoteObject implements MessageBuilder { + private static final String baseMsg = MessageBuilderServantPOA.class.getName(); + + public MessageBuilderServantPOA() throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + } + + public String m(String x) { + String result = x + baseMsg; + System.out.println(baseMsg); + return result; + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/nestedClasses/TwoLevelNested.java b/rmic/src/test/java/org/glassfish/rmic/classes/nestedClasses/TwoLevelNested.java new file mode 100644 index 000000000..9ed919f4b --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/nestedClasses/TwoLevelNested.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.nestedClasses; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public class TwoLevelNested { + + public class Level1 { + + public class Level2 implements Remote, Cloneable { + public void level2Execute() throws RemoteException { + System.out.println("Level2.level2Execute executed"); + } + } + } +/* + + void tryThis() { + new Runnable() { + @Override + public void run() { + System.out.println("Called inner class"); + } + }; + } +*/ +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/preinvokepostinvoke/Interface.java b/rmic/src/test/java/org/glassfish/rmic/classes/preinvokepostinvoke/Interface.java new file mode 100644 index 000000000..f9f4b7129 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/preinvokepostinvoke/Interface.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.preinvokepostinvoke; + +import java.rmi.RemoteException; + +public interface Interface extends java.rmi.Remote { + public String o1(String x) throws RemoteException; + public String o2(String x) throws RemoteException; +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/preinvokepostinvoke/MyServant.java b/rmic/src/test/java/org/glassfish/rmic/classes/preinvokepostinvoke/MyServant.java new file mode 100644 index 000000000..339b302c3 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/preinvokepostinvoke/MyServant.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.preinvokepostinvoke; + +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class MyServant extends PortableRemoteObject implements Interface +{ + private org.omg.CORBA.ORB orb; + public MyServant( org.omg.CORBA.ORB orb) throws RemoteException + { + this.orb = orb; + } + + public String o1(String arg) + { + System.out.println( "Interface.o1 called with " + arg ); + System.out.flush( ); + try { + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); + objRef = ncRef.resolve_str( "Instance2" ); + Interface i2 = + (Interface) PortableRemoteObject.narrow( objRef, Interface.class ); + i2.o2( "Invoking from Interface.o1..." ); + } catch( Throwable e ) { + System.err.println( " Exception ..." + e ); + e.printStackTrace( ); + System.exit( 1 ); + } + return "return value for interface.o1"; + } + + public String o2( String arg ) + { + System.out.println( "Interface.o2 called with " + arg ); + System.out.flush( ); + return "return value for interface.o2"; + } +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/primitives/InterfaceWithConstantArray.java b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/InterfaceWithConstantArray.java new file mode 100644 index 000000000..4c9612c3e --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/InterfaceWithConstantArray.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.primitives; + +import java.rmi.Remote; + +public interface InterfaceWithConstantArray extends Remote { + public static final int[] VALUES = {1,2,3}; + +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/primitives/InterfaceWithNonPrimitiveConstant.java b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/InterfaceWithNonPrimitiveConstant.java new file mode 100644 index 000000000..37e30a88b --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/InterfaceWithNonPrimitiveConstant.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.primitives; + +import java.io.EOFException; +import java.rmi.Remote; + +public interface InterfaceWithNonPrimitiveConstant extends Remote { + public static final Exception TO_THROW = new EOFException(); +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/primitives/NonFinalInterface.java b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/NonFinalInterface.java new file mode 100644 index 000000000..43a74e6dc --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/NonFinalInterface.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.primitives; + +public class NonFinalInterface { + public static String JNDI_NAME = "IIOP_RmiTestRemote"; + public static boolean A_BOOLEAN = true; + public static char A_CHAR = 'x'; + public static byte A_BYTE = 0x34; + public static short A_SHORT = 12; + public static int AN_INT = 17; + public static long A_LONG = 1234567; + public static float A_FLOAT = 123.5f; + public static double A_DOUBLE = 123.567; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/primitives/RmiTestRemote.java b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/RmiTestRemote.java new file mode 100644 index 000000000..6a1e070fa --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/RmiTestRemote.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.primitives; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface RmiTestRemote extends Remote { + public static final String JNDI_NAME = "IIOP_RmiTestRemote"; + public static final boolean A_BOOLEAN = true; + public static final char A_CHAR = 'x'; + public static final byte A_BYTE = 0x34; + public static final short A_SHORT = 12; + public static final int AN_INT = 17; + public static final long A_LONG = 1234567; + public static final float A_FLOAT = 123.5f; + public static final double A_DOUBLE = 123.567; + + void test_ping() throws RemoteException; + + int test_int(int x) throws RemoteException; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/primitives/RmiTestRemoteImpl.java b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/RmiTestRemoteImpl.java new file mode 100644 index 000000000..9d72aabb2 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/primitives/RmiTestRemoteImpl.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.primitives; + +import java.rmi.RemoteException; + +public class RmiTestRemoteImpl implements RmiTestRemote { + @Override + public void test_ping() throws RemoteException { + System.out.println("ping"); + } + + @Override + public int test_int(int x) throws RemoteException { + return 0; + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/rmipoacounter/CounterIF.java b/rmic/src/test/java/org/glassfish/rmic/classes/rmipoacounter/CounterIF.java new file mode 100644 index 000000000..3f9f06af8 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/rmipoacounter/CounterIF.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.rmipoacounter; + +public interface CounterIF extends java.rmi.Remote { + long increment( long invalue ) throws java.rmi.RemoteException ; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/rmipoacounter/CounterImpl.java b/rmic/src/test/java/org/glassfish/rmic/classes/rmipoacounter/CounterImpl.java new file mode 100644 index 000000000..6ef163b3a --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/rmipoacounter/CounterImpl.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1998, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.rmipoacounter; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; + +import javax.rmi.PortableRemoteObject; +import java.io.File; +import java.io.RandomAccessFile; +import java.rmi.RemoteException; + +public class CounterImpl extends PortableRemoteObject implements CounterIF +{ + // Temporary hack to get this test to work and keep the output + // directory clean + private static final String outputDirOffset + = "/org/glassfish/rmic/classes/rmipoacounter/".replace('/', File.separatorChar); + + private String name; + private int value; + private ORB orb; + private int myid; + private static int SERVANT_ID=1; + private boolean debug ; + + public CounterImpl(ORB orb, boolean debug) throws RemoteException + { + this.myid = SERVANT_ID++; + this.orb = orb; + this.debug = debug ; + + name = System.getProperty("output.dir") + + outputDirOffset + + "counterValue"; + + try { + File f = new File(name); + if ( !f.exists() ) { + RandomAccessFile file = new RandomAccessFile(f, "rw"); + value = 0; + file.writeBytes(String.valueOf(value)); + file.close(); + } + } catch ( Exception ex ) { + ex.printStackTrace(); + System.exit(1); + } + } + + public synchronized long increment(long invalue) throws RemoteException + { + if ( debug ) + System.out.println( "\nIn counterServant " + myid + + " increment(), invalue = " + invalue + " Server thread is " + + Thread.currentThread()); + + try { + // Test Current operations + org.omg.PortableServer.Current current = + (org.omg.PortableServer.Current)orb.resolve_initial_references( + "POACurrent"); + POA poa = current.get_POA(); + byte[] oid = current.get_object_id(); + + if ( debug ) + System.out.println( "POA = " + poa.the_name() + " objectid = " + oid); + + // Increment counter and save state + RandomAccessFile file = new RandomAccessFile(new File(name), "rw"); + String svalue = file.readLine(); + value = Integer.parseInt(svalue); + file.seek(0); + value += (int)invalue; + file.writeBytes(String.valueOf(value)); + file.close(); + + System.out.println("\nIn counterServant read "+svalue+" wrote "+value); + } catch ( Exception ex ) { + System.err.println("ERROR in counterServant !"); + ex.printStackTrace(); + System.exit(1); + } + + return value; + } +} + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/Server.java b/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/Server.java new file mode 100644 index 000000000..5613ad5fa --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/Server.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.systemexceptions; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class Server { + static void invoke(int excType) { + System.out.println("Invoked with " + excType); + } +} + + diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/ServerInvoker.java b/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/ServerInvoker.java new file mode 100644 index 000000000..6df0d3ddf --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/ServerInvoker.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.systemexceptions; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface ServerInvoker extends Remote { + void invoke(int excType) throws RemoteException; +} diff --git a/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/ServerInvokerServantPOA.java b/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/ServerInvokerServantPOA.java new file mode 100644 index 000000000..301b70525 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/classes/systemexceptions/ServerInvokerServantPOA.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.classes.systemexceptions; + +import javax.rmi.PortableRemoteObject; +import java.rmi.RemoteException; + +public class ServerInvokerServantPOA extends PortableRemoteObject implements ServerInvoker { + + ServerInvokerServantPOA() throws RemoteException { + // DO NOT CALL SUPER - that would connect the object. + } + + public void invoke(int excType) { + Server.invoke(excType); + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/tools/binaryclass/BinaryClassTest.java b/rmic/src/test/java/org/glassfish/rmic/tools/binaryclass/BinaryClassTest.java new file mode 100644 index 000000000..221a88e4b --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/tools/binaryclass/BinaryClassTest.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.binaryclass; + +import org.glassfish.rmic.tools.java.ClassDefinitionFactoryTest; + +public class BinaryClassTest extends ClassDefinitionFactoryTest { + + public BinaryClassTest() { + super(new BinaryClassFactory()); + } + + +} diff --git a/rmic/src/test/java/org/glassfish/rmic/tools/java/ClassDefinitionFactoryTest.java b/rmic/src/test/java/org/glassfish/rmic/tools/java/ClassDefinitionFactoryTest.java new file mode 100644 index 000000000..2253ec8f2 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/tools/java/ClassDefinitionFactoryTest.java @@ -0,0 +1,408 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.java; + +import com.meterware.simplestub.Memento; +import com.meterware.simplestub.StaticStubSupport; +import org.glassfish.rmic.BatchEnvironment; +import org.glassfish.rmic.Names; +import org.glassfish.rmic.TestUtils; +import org.glassfish.rmic.classes.covariantReturn.AnimalFinder; +import org.glassfish.rmic.classes.exceptiondetailsc.ExceptionSource; +import org.glassfish.rmic.classes.exceptiondetailsc.ExceptionSourceServantPOA; +import org.glassfish.rmic.classes.exceptiondetailsc.RmiIException; +import org.glassfish.rmic.classes.hcks.RmiII; +import org.glassfish.rmic.classes.hcks.RmiIIServantPOA; +import org.glassfish.rmic.classes.inneraccess.Rainbow; +import org.glassfish.rmic.classes.nestedClasses.TwoLevelNested; +import org.glassfish.rmic.classes.primitives.NonFinalInterface; +import org.glassfish.rmic.classes.primitives.RmiTestRemote; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeDiagnosingMatcher; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.rmi.PortableRemoteObject; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.List; + +import static org.glassfish.rmic.tools.java.ClassDefinitionFactoryTest.ClassDeclarationMatcher.declarationFor; +import static org.glassfish.rmic.tools.java.ClassDefinitionFactoryTest.MemberDefinitionMatcher.isDefinitionFor; +import static org.glassfish.rmic.tools.java.Constants.*; +import static org.glassfish.rmic.tools.java.RuntimeConstants.ACC_SUPER; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +public abstract class ClassDefinitionFactoryTest { + private ByteArrayOutputStream messagesOut = new ByteArrayOutputStream(); + private Environment environment = new BatchEnvironment(messagesOut, createTestClassPath(), null); + private ClassDefinitionFactory factory; + private Memento memento; + + @Before + public void setUp() throws Exception { + memento = StaticStubSupport.install(BatchEnvironment.class, "classDefinitionFactory", factory); + environment = new BatchEnvironment(messagesOut, createTestClassPath(), null); + } + + @After + public void tearDown() throws Exception { + memento.revert(); + } + + protected ClassDefinitionFactoryTest(ClassDefinitionFactory factory) { + this.factory = factory; + } + + private ClassPath createTestClassPath() { + return BatchEnvironment.createClassPath(TestUtils.getClassPathString(), null); + } + + private ClassDefinition definitionFor(Class aClass) throws IOException { + InputStream classFileInputStream = getClass().getClassLoader().getResourceAsStream(toPath(aClass)); + return factory.loadDefinition(classFileInputStream, environment); + } + + private String toPath(Class aClass) { + return aClass.getName().replace('.', File.separatorChar) + ".class"; + } + + private void loadNested(ClassDefinition classDefinition) { + classDefinition.loadNested(environment); + } + + // Name mangling is required to convert an internal class name identifier to an actual class name. + private String getClassName(ClassDeclaration classDeclaration) { + return Names.mangleClass(classDeclaration.getName()).toString(); + } + + @Test + public void loadJavaLangObject() throws Exception { + definitionFor(Object.class); + } + + @Test + public void classDefinition_hasDeclarationWithClassName() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiII.class); + + assertThat(getClassName(classDefinition.getClassDeclaration()), equalTo(RmiII.class.getName())); + } + + @Test + public void classDefinitionForInnerClass_hasDeclarationWithClassName() throws Exception { + ClassDefinition classDefinition = definitionFor(Rainbow.getInterfaceCheckerClass()); + + assertThat(getClassName(classDefinition.getClassDeclaration()), equalTo(Rainbow.getInterfaceCheckerClass().getName())); + } + + @Test + public void classDefinition_hasSuperclass() throws Exception { + ClassDefinition classDefinition = definitionFor(ExceptionSourceServantPOA.class); + + assertThat(getClassName(classDefinition.getSuperClass()), equalTo(PortableRemoteObject.class.getName())); + } + + @Test + public void classDefinition_hasInterfaces() throws Exception { + ClassDefinition classDefinition = definitionFor(TwoLevelNested.Level1.Level2.class); + + assertThat(getClassNames(classDefinition.getInterfaces()), + arrayContainingInAnyOrder(Remote.class.getName(), Cloneable.class.getName())); + } + + private String[] getClassNames(ClassDeclaration[] declarations) { + String[] result = new String[declarations.length]; + for (int i = 0; i < declarations.length; i++) + result[i] = getClassName(declarations[i]); + return result; + } + + @Test + public void classDefinitionForCompiledClass_hasSourceName() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiII.class); + + assertThat(classDefinition.getSource(), equalTo("RmiII.java")); + } + + @Test + public void classDefinitionForTopLevelClass_hasSourceName() throws Exception { + ClassDefinition classDefinition = definitionFor(Class.forName("TopLevelClass")); + + assertThat(classDefinition.getSource(), equalTo("TopLevelClass.java")); + } + + @Test + public void classDefinitionForInnerClass_hasSourceName() throws Exception { + ClassDefinition classDefinition = definitionFor(TwoLevelNested.Level1.Level2.class); + + assertThat(classDefinition.getSource(), equalTo("TwoLevelNested.java")); + } + + @Test + public void classDefinitionForCompiledClass_hasNoError() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiII.class); + + assertThat(classDefinition.getError(), is(false)); + } + + @Test + public void classDefinitionForCompiledClass_hasZeroWhereValue() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiII.class); + + assertThat(classDefinition.getWhere(), equalTo(0L)); + } + + @Test + public void classDefinitionForRmiII_hasExpectedModifiers() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiII.class); + + assertThat(classDefinition.getModifiers(), equalTo(M_ABSTRACT | M_INTERFACE | M_PUBLIC)); + } + + @Test + public void classDefinitionForRmiIIServantPOA_hasExpectedModifiers() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiIIServantPOA.class); + + assertThat(classDefinition.getModifiers(), equalTo(ACC_SUPER | M_PUBLIC)); + } + + @Test + public void afterLoadNested_topClassOfInnerClassMatchesOuterClass() throws Exception { + ClassDefinition inner = definitionFor(Rainbow.getInterfaceCheckerClass()); + loadNested(inner); + + assertThat(inner.getTopClass().getName(), equalTo(definitionFor(Rainbow.class).getName())); + } + + @Test + public void afterLoadNested_topClassOfInner2LevelNestedClassMatchesOuterClass() throws Exception { + ClassDefinition inner = definitionFor(TwoLevelNested.Level1.Level2.class); + loadNested(inner); + + assertThat(inner.getTopClass().getName(), equalTo(definitionFor(TwoLevelNested.class).getName())); + } + + @Test + public void classDefinitionForRmiIIServantPOA_hasExpectedMemberDefinitions() throws Exception { + ClassDefinition classDefinition = definitionFor(RmiIIServantPOA.class); + + List memberDefinitions = new ArrayList<>(); + for (MemberDefinition member = classDefinition.getFirstMember(); member != null; member = member.getNextMember()) + if (!isStaticInitializer(member)) memberDefinitions.add(member); + + assertThat(memberDefinitions, containsInAnyOrder(allMembers(RmiIIServantPOA.class))); + } + + private boolean isStaticInitializer(MemberDefinition member) { + return member.getName().toString().equals(""); + } + + @Test + public void classDefinitionForAnimalFinder_hasExpectedMemberDefinitions() throws Exception { + ClassDefinition classDefinition = definitionFor(AnimalFinder.class); + + List memberDefinitions = new ArrayList<>(); + for (MemberDefinition member = classDefinition.getFirstMember(); member != null; member = member.getNextMember()) + if (!isStaticInitializer(member)) memberDefinitions.add(member); + + assertThat(memberDefinitions, containsInAnyOrder(allMembers(AnimalFinder.class))); + } + + @Test + public void methodDefinition_hasThrownExceptions() throws Exception { + ClassDefinition classDefinition = definitionFor(ExceptionSource.class); + + MemberDefinition method = classDefinition.findAnyMethod(environment, Identifier.lookup("raiseUserException")); + assertThat(method.getExceptions(environment), arrayContainingInAnyOrder(declarationFor(RemoteException.class), declarationFor(RmiIException.class))); + } + + // It appears that only the static initializer is allowed to return an empty array for this. + @Test + public void methodDefinitionGetArguments_returnsNull() throws Exception { + ClassDefinition classDefinition = definitionFor(ExceptionSource.class); + + MemberDefinition method = classDefinition.findAnyMethod(environment, Identifier.lookup("raiseUserException")); + assertThat(method.getArguments(), nullValue()); + } + + @SuppressWarnings("unchecked") + private Matcher[] allMembers(Class aClass) { + List> matchers = new ArrayList<>(); + for (Method method : aClass.getDeclaredMethods()) + matchers.add(isDefinitionFor(method)); + for (Field field : aClass.getDeclaredFields()) + matchers.add(isDefinitionFor(field)); + for (Constructor constructor : aClass.getDeclaredConstructors()) + matchers.add(isDefinitionFor(constructor)); + return matchers.toArray(new Matcher[matchers.size()]); + } + + @Test + public void verifyFinalMemberDefs() throws Exception { +// Assume.assumeTrue(factory instanceof BinaryClassFactory); + ClassDefinition classDefinition = definitionFor(RmiTestRemote.class); + assertThat(getMember(classDefinition, "A_DOUBLE").getMemberValueString(environment), equalTo("123.567D")); + assertThat(getMember(classDefinition, "A_FLOAT").getMemberValueString(environment), equalTo("123.5F")); + assertThat(getMember(classDefinition, "A_LONG").getMemberValueString(environment), equalTo("1234567L")); + assertThat(getMember(classDefinition, "AN_INT").getMemberValueString(environment), equalTo("17")); + assertThat(getMember(classDefinition, "A_SHORT").getMemberValueString(environment), equalTo("12")); + assertThat(getMember(classDefinition, "A_BYTE").getMemberValueString(environment), equalTo("52")); + assertThat(getMember(classDefinition, "A_CHAR").getMemberValueString(environment), equalTo("L'x'")); + assertThat(getMember(classDefinition, "A_BOOLEAN").getMemberValueString(environment), equalTo("true")); + assertThat(getMember(classDefinition, "JNDI_NAME").getMemberValueString(environment), equalTo("\"IIOP_RmiTestRemote\"")); + } + + private MemberDefinition getMember(ClassDefinition classDefinition, String name) { + for (MemberDefinition def = classDefinition.getFirstMember(); def != null; def = def.getNextMember()) { + if (name.equals(def.getName().toString())) return def; + } + + throw new AssertionError("No member named " + name + " found in class " + classDefinition.getName()); + } + + @Test + public void verifyNonFinalMemberDefs() throws Exception { + ClassDefinition classDefinition = definitionFor(NonFinalInterface.class); + assertThat(getMember(classDefinition, "A_DOUBLE").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "A_FLOAT").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "A_LONG").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "AN_INT").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "A_SHORT").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "A_BYTE").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "A_CHAR").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "A_BOOLEAN").getMemberValueString(environment), nullValue()); + assertThat(getMember(classDefinition, "JNDI_NAME").getMemberValueString(environment), nullValue()); + } + + static class MemberDefinitionMatcher extends TypeSafeDiagnosingMatcher { + private AccessibleObject member; + + private MemberDefinitionMatcher(AccessibleObject member) { + this.member = member; + } + + static MemberDefinitionMatcher isDefinitionFor(AccessibleObject member) { + return new MemberDefinitionMatcher(member); + } + + @Override + protected boolean matchesSafely(MemberDefinition memberDefinition, Description description) { + if (!matches(memberDefinition)) { + description.appendValue(memberDefinition.getName()); + return false; + } + return true; + } + + private boolean matches(MemberDefinition memberDefinition) { + if (member instanceof Constructor) + return parameterTypesMatch(((Constructor) member).getParameterTypes(), memberDefinition.getType().getArgumentTypes()); + else if (member instanceof Method) + return isSameMethod(memberDefinition, (Method) this.member); + else + return getName(member).equals(memberDefinition.getName().toString()); + } + + private boolean isSameMethod(MemberDefinition memberDefinition, Method method) { + return method.getName().equals(memberDefinition.getName().toString()) && + parameterTypeMatch(method.getReturnType(), memberDefinition.getType().getReturnType()) && + parameterTypesMatch(method.getParameterTypes(), memberDefinition.getType().getArgumentTypes()); + } + + private boolean parameterTypesMatch(Class[] parameterTypes, Type[] memberDefinition) { + if (parameterTypes.length != memberDefinition.length) return false; + + for (int i = 0; i < parameterTypes.length; i++) + if (!parameterTypeMatch(parameterTypes[i], memberDefinition[i])) return false; + return true; + } + + private boolean parameterTypeMatch(Class parameterType, Type type) { + return parameterType.getTypeName().equals(type.toString()); + } + + private String getName(AccessibleObject member) { + if (member instanceof Method) + return getMethodName((Method) member); + else if (member instanceof Field) + return ((Field) member).getName(); + else if (member instanceof Constructor) + return getConstructorName((Constructor) member); + else + return "??"; + } + + private String getMethodName(Method member) { + return toDisplayType(member.getReturnType()) + " " + member.getName() + toParameterString(member.getParameterTypes()); + } + + private String getConstructorName(Constructor member) { + return toDisplayType(member.getDeclaringClass()) + toParameterString(member.getParameterTypes()); + } + + private String toParameterString(Class[] parameterTypes) { + return "(" + String.join(", ", toStringList(parameterTypes)) + ")"; + } + + private List toStringList(Class[] parameterTypes) { + List list = new ArrayList<>(); + for (Class parameterType : parameterTypes) + list.add(toDisplayType(parameterType)); + return list; + } + + private String toDisplayType(Class parameterType) { + return parameterType.getTypeName(); + } + + @Override + public void describeTo(Description description) { + description.appendValue(getName(member)); + } + } + + static class ClassDeclarationMatcher extends TypeSafeDiagnosingMatcher { + private Class classToMatch; + + private ClassDeclarationMatcher(Class classToMatch) { + this.classToMatch = classToMatch; + } + + static ClassDeclarationMatcher declarationFor(Class classToMatch) { + return new ClassDeclarationMatcher(classToMatch); + } + + @Override + protected boolean matchesSafely(ClassDeclaration item, Description mismatchDescription) { + if (item.getName().toString().equals(classToMatch.getName())) return true; + + mismatchDescription.appendText("declaration for ").appendValue(item.getName()); + return false; + } + + @Override + public void describeTo(Description description) { + description.appendText("declaration for ").appendValue(classToMatch.getName()); + } + } +} diff --git a/rmic/src/test/java/org/glassfish/rmic/tools/javac/BatchEnvironmentTest.java b/rmic/src/test/java/org/glassfish/rmic/tools/javac/BatchEnvironmentTest.java new file mode 100644 index 000000000..3d79f24d7 --- /dev/null +++ b/rmic/src/test/java/org/glassfish/rmic/tools/javac/BatchEnvironmentTest.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.glassfish.rmic.tools.javac; + +import com.meterware.simplestub.Memento; +import com.meterware.simplestub.StaticStubSupport; +import com.meterware.simplestub.SystemPropertySupport; +import org.glassfish.rmic.BatchEnvironmentError; +import org.glassfish.rmic.asm.AsmClassFactory; +import org.glassfish.rmic.tools.binaryclass.BinaryClassFactory; +import org.glassfish.rmic.tools.java.ClassDefinitionFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; + +@SuppressWarnings("deprecation") +public class BatchEnvironmentTest { + private static final String USE_LEGACY_PARSING_PROPERTY = "org.glassfish.rmic.UseLegacyClassParsing"; + private static final String JAVA_VERSION_PROPERTY = "java.version"; + private List mementos = new ArrayList<>(); + + @Before + public void setUp() throws Exception { + mementos.add(SystemPropertySupport.preserve(USE_LEGACY_PARSING_PROPERTY)); + mementos.add(SystemPropertySupport.preserve(JAVA_VERSION_PROPERTY)); + System.clearProperty(USE_LEGACY_PARSING_PROPERTY); + } + + @After + public void tearDown() throws Exception { + for (Memento memento : mementos) memento.revert(); + } + + @Test + public void whenPropertyNotSet_chooseAsmParser() throws Exception { + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(AsmClassFactory.class)); + } + + @Test + public void whenAsmClassesMissingOnJdk8_chooseBinaryParser() throws Exception { + simulateAsmClassesMissing(); + simulateJdkVersion("1.8"); + + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(BinaryClassFactory.class)); + } + + private void simulateAsmClassesMissing() throws NoSuchFieldException { + mementos.add(StaticStubSupport.install(AsmClassFactory.class, "simulateMissingASM", true)); + } + + private void simulateJdkVersion(String jdkVersion) { + System.setProperty(JAVA_VERSION_PROPERTY, jdkVersion); + } + + @Test(expected = BatchEnvironmentError.class) + public void whenAsmClassesMissingOnJdk10_reportError() throws Exception { + simulateAsmClassesMissing(); + simulateJdkVersion("10"); + + BatchEnvironment.createClassDefinitionFactory(); + } + + @Test + public void whenLegacyParserRequestedOnJdk8_chooseBinaryParser() throws Exception { + preferLegacyParser(); + simulateJdkVersion("1.8"); + + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(BinaryClassFactory.class)); + } + + private void preferLegacyParser() { + System.setProperty(USE_LEGACY_PARSING_PROPERTY, "true"); + } + + @Test + public void whenLegacyParserRequestedOnJdk9_chooseBinaryParser() throws Exception { + preferLegacyParser(); + simulateJdkVersion("9"); + + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(BinaryClassFactory.class)); + } + + @Test + public void whenLegacyParserRequestedOnJdk10_chooseAsmParser() throws Exception { + preferLegacyParser(); + simulateJdkVersion("10"); + + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(AsmClassFactory.class)); + } + + @Test + public void whenLegacyParserRequestedOnJdk10EarlyAccess_chooseAsmParser() throws Exception { + preferLegacyParser(); + simulateJdkVersion("10-ea"); + + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(AsmClassFactory.class)); + } + + @Test + public void whenLegacyParserRequestedOnJdk11_chooseAsmParser() throws Exception { + preferLegacyParser(); + simulateJdkVersion("11"); + + ClassDefinitionFactory factory = BatchEnvironment.createClassDefinitionFactory(); + + assertThat(factory, instanceOf(AsmClassFactory.class)); + } + +} diff --git a/rmic/src/test/masters/README b/rmic/src/test/masters/README new file mode 100644 index 000000000..77f2ce22c --- /dev/null +++ b/rmic/src/test/masters/README @@ -0,0 +1,12 @@ +The files in this directory were generated by the JDK version of RMIC, run against the follow classes, + built under the functional-tests module: + +corba.preinvokepostinvoke.MyServant +corba.systemexceptions.rmiiIServantPOA +corba.hcks.rmiiIServantPOA +corba.giopheaderpadding.rmiiIServantPOA +corba.islocal.rmiiIServantPOA +corba.exceptiondetailsc.rmiiIServantPOA +corba.rmipoacounter.counterImpl + +The resulting source files are used as 'golden masters' to verify that the Glassfish version produces what is expected. diff --git a/rmic/src/test/masters/idl/org/glassfish/rmic/classes/inneraccess/Rainbow__CheckerImpl.idl b/rmic/src/test/masters/idl/org/glassfish/rmic/classes/inneraccess/Rainbow__CheckerImpl.idl new file mode 100644 index 000000000..d99142d30 --- /dev/null +++ b/rmic/src/test/masters/idl/org/glassfish/rmic/classes/inneraccess/Rainbow__CheckerImpl.idl @@ -0,0 +1,32 @@ +/** + * org/glassfish/rmic/classes/inneraccess/Rainbow__CheckerImpl.idl + * Generated by rmic -idl. Do not edit + * IGNORE date line changes with every generation + */ + +#include "orb.idl" + +#ifndef __org_glassfish_rmic_classes_inneraccess_Rainbow__CheckerImpl__ +#define __org_glassfish_rmic_classes_inneraccess_Rainbow__CheckerImpl__ + + +module org { +module glassfish { +module rmic { +module classes { +module inneraccess { + + abstract valuetype Rainbow__CheckerImpl { + + ::CORBA::WStringValue getPreferredColor( ); + + }; + +}; +}; +}; +}; +}; + +#endif + diff --git a/rmic/src/test/masters/primitives/org/glassfish/rmic/classes/primitives/_RmiTestRemoteImpl_Tie.java b/rmic/src/test/masters/primitives/org/glassfish/rmic/classes/primitives/_RmiTestRemoteImpl_Tie.java new file mode 100644 index 000000000..55c4d29fc --- /dev/null +++ b/rmic/src/test/masters/primitives/org/glassfish/rmic/classes/primitives/_RmiTestRemoteImpl_Tie.java @@ -0,0 +1,90 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.primitives; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + + +public class _RmiTestRemoteImpl_Tie extends ObjectImpl implements Tie { + + volatile private RmiTestRemoteImpl target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.primitives.RmiTestRemote:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (RmiTestRemoteImpl) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + RmiTestRemoteImpl target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.length()) { + case 8: + if (method.equals("test_int")) { + int arg0 = in.read_long(); + int result = target.test_int(arg0); + OutputStream out = reply.createReply(); + out.write_long(result); + return out; + } + case 9: + if (method.equals("test_ping")) { + target.test_ping(); + OutputStream out = reply.createReply(); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/primitives/org/glassfish/rmic/classes/primitives/_RmiTestRemote_Stub.java b/rmic/src/test/masters/primitives/org/glassfish/rmic/classes/primitives/_RmiTestRemote_Stub.java new file mode 100644 index 000000000..0482ec1c2 --- /dev/null +++ b/rmic/src/test/masters/primitives/org/glassfish/rmic/classes/primitives/_RmiTestRemote_Stub.java @@ -0,0 +1,104 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.primitives; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _RmiTestRemote_Stub extends Stub implements RmiTestRemote { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.primitives.RmiTestRemote:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public void test_ping() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("test_ping", true); + _invoke(out); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + test_ping(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("test_ping",RmiTestRemote.class); + if (so == null) { + test_ping(); + return ; + } + try { + ((RmiTestRemote)so.servant).test_ping(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public int test_int(int arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("test_int", true); + out.write_long(arg0); + in = _invoke(out); + return in.read_long(); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return test_int(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("test_int",RmiTestRemote.class); + if (so == null) { + return test_int(arg0); + } + try { + return ((RmiTestRemote)so.servant).test_int(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/stub_from_interface/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java b/rmic/src/test/masters/stub_from_interface/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java new file mode 100644 index 000000000..ddfd7f7b7 --- /dev/null +++ b/rmic/src/test/masters/stub_from_interface/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java @@ -0,0 +1,359 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.hcks; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _RmiII_Stub extends Stub implements RmiII { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.hcks.RmiII:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public String sayHello() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("sayHello", true); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHello(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHello",RmiII.class); + if (so == null) { + return sayHello(); + } + try { + return ((RmiII)so.servant).sayHello(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public int sendBytes(byte[] arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sendBytes", true); + out.write_value(cast_array(arg0),byte[].class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return in.read_long(); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendBytes(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendBytes",RmiII.class); + if (so == null) { + return sendBytes(arg0); + } + try { + byte[] arg0Copy = (byte[]) Util.copyObject(arg0,_orb()); + return ((RmiII)so.servant).sendBytes(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object sendOneObject(Object arg0) throws java.rmi.RemoteException, org.glassfish.rmic.classes.hcks.RmiIMyException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("sendOneObject", true); + Util.writeAny(out,arg0); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:org/glassfish/rmic/classes/hcks/RmiIMyEx:1.0")) { + throw (org.glassfish.rmic.classes.hcks.RmiIMyException) in.read_value(org.glassfish.rmic.classes.hcks.RmiIMyException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendOneObject(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendOneObject",RmiII.class); + if (so == null) { + return sendOneObject(arg0); + } + try { + Object arg0Copy = (Object) Util.copyObject(arg0,_orb()); + Object result = ((RmiII)so.servant).sendOneObject(arg0Copy); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof org.glassfish.rmic.classes.hcks.RmiIMyException) { + throw (org.glassfish.rmic.classes.hcks.RmiIMyException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object sendTwoObjects(Object arg0, Object arg1) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("sendTwoObjects", true); + Util.writeAny(out,arg0); + Util.writeAny(out,arg1); + in = _invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendTwoObjects(arg0,arg1); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendTwoObjects",RmiII.class); + if (so == null) { + return sendTwoObjects(arg0, arg1); + } + try { + Object[] copies = Util.copyObjects(new Object[]{arg0,arg1},_orb()); + Object arg0Copy = (Object) copies[0]; + Object arg1Copy = (Object) copies[1]; + Object result = ((RmiII)so.servant).sendTwoObjects(arg0Copy, arg1Copy); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String makeColocatedCallFromServant() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("makeColocatedCallFromServant", true); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return makeColocatedCallFromServant(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("makeColocatedCallFromServant",RmiII.class); + if (so == null) { + return makeColocatedCallFromServant(); + } + try { + return ((RmiII)so.servant).makeColocatedCallFromServant(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String colocatedCallFromServant(String arg0) throws java.rmi.RemoteException, java.lang.Exception { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("colocatedCallFromServant", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:java/lang/Ex:1.0")) { + throw (java.lang.Exception) in.read_value(java.lang.Exception.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return colocatedCallFromServant(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("colocatedCallFromServant",RmiII.class); + if (so == null) { + return colocatedCallFromServant(arg0); + } + try { + return ((RmiII)so.servant).colocatedCallFromServant(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof java.lang.Exception) { + throw (java.lang.Exception)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String throwThreadDeathInServant(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("throwThreadDeathInServant", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return throwThreadDeathInServant(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("throwThreadDeathInServant",RmiII.class); + if (so == null) { + return throwThreadDeathInServant(arg0); + } + try { + return ((RmiII)so.servant).throwThreadDeathInServant(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object returnObjectFromServer(boolean arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("returnObjectFromServer", true); + out.write_boolean(arg0); + in = _invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return returnObjectFromServer(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("returnObjectFromServer",RmiII.class); + if (so == null) { + return returnObjectFromServer(arg0); + } + try { + Object result = ((RmiII)so.servant).returnObjectFromServer(arg0); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + // This method is required as a work-around for + // a bug in the JDK 1.1.6 verifier. + + private Serializable cast_array(Object obj) { + return (Serializable)obj; + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/exceptiondetailsc/_ExceptionSourceServantPOA_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/exceptiondetailsc/_ExceptionSourceServantPOA_Tie.java new file mode 100644 index 000000000..0af9b8535 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/exceptiondetailsc/_ExceptionSourceServantPOA_Tie.java @@ -0,0 +1,118 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.exceptiondetailsc; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _ExceptionSourceServantPOA_Tie extends Servant implements Tie { + + volatile private ExceptionSourceServantPOA target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.exceptiondetailsc.ExceptionSource:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (ExceptionSourceServantPOA) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + ExceptionSourceServantPOA target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.length()) { + case 18: + if (method.equals("raiseUserException")) { + String arg0 = (String) in.read_value(String.class); + try { + target.raiseUserException(arg0); + } catch (RmiIException ex) { + String id = "IDL:org/glassfish/rmic/classes/exceptiondetailsc/RmiIEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,RmiIException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 20: + if (method.equals("raiseSystemException")) { + String arg0 = (String) in.read_value(String.class); + target.raiseSystemException(arg0); + OutputStream out = reply.createReply(); + return out; + } + case 21: + if (method.equals("raiseRuntimeException")) { + String arg0 = (String) in.read_value(String.class); + target.raiseRuntimeException(arg0); + OutputStream out = reply.createReply(); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/exceptiondetailsc/_ExceptionSource_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/exceptiondetailsc/_ExceptionSource_Stub.java new file mode 100644 index 000000000..4007b83e3 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/exceptiondetailsc/_ExceptionSource_Stub.java @@ -0,0 +1,154 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.exceptiondetailsc; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _ExceptionSource_Stub extends Stub implements ExceptionSource { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.exceptiondetailsc.ExceptionSource:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public void raiseSystemException(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("raiseSystemException", true); + out.write_value(arg0,String.class); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + raiseSystemException(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("raiseSystemException",ExceptionSource.class); + if (so == null) { + raiseSystemException(arg0); + return ; + } + try { + ((ExceptionSource)so.servant).raiseSystemException(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void raiseUserException(String arg0) throws java.rmi.RemoteException, org.glassfish.rmic.classes.exceptiondetailsc.RmiIException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("raiseUserException", true); + out.write_value(arg0,String.class); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:org/glassfish/rmic/classes/exceptiondetailsc/RmiIEx:1.0")) { + throw (org.glassfish.rmic.classes.exceptiondetailsc.RmiIException) in.read_value(org.glassfish.rmic.classes.exceptiondetailsc.RmiIException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + raiseUserException(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("raiseUserException",ExceptionSource.class); + if (so == null) { + raiseUserException(arg0); + return ; + } + try { + ((ExceptionSource)so.servant).raiseUserException(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof org.glassfish.rmic.classes.exceptiondetailsc.RmiIException) { + throw (org.glassfish.rmic.classes.exceptiondetailsc.RmiIException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void raiseRuntimeException(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("raiseRuntimeException", true); + out.write_value(arg0,String.class); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + raiseRuntimeException(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("raiseRuntimeException",ExceptionSource.class); + if (so == null) { + raiseRuntimeException(arg0); + return ; + } + try { + ((ExceptionSource)so.servant).raiseRuntimeException(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/giopheaderpadding/_FooServantPOA_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/giopheaderpadding/_FooServantPOA_Tie.java new file mode 100644 index 000000000..20629ccf1 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/giopheaderpadding/_FooServantPOA_Tie.java @@ -0,0 +1,102 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.giopheaderpadding; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _FooServantPOA_Tie extends Servant implements Tie { + + volatile private FooServantPOA target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.giopheaderpadding.Foo:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (FooServantPOA) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + FooServantPOA target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.charAt(3)) { + case 65: + if (method.equals("fooA")) { + byte arg0 = in.read_octet(); + byte result = target.fooA(arg0); + OutputStream out = reply.createReply(); + out.write_octet(result); + return out; + } + case 66: + if (method.equals("fooB")) { + target.fooB(); + OutputStream out = reply.createReply(); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/giopheaderpadding/_Foo_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/giopheaderpadding/_Foo_Stub.java new file mode 100644 index 000000000..c1dd8daf8 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/giopheaderpadding/_Foo_Stub.java @@ -0,0 +1,104 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.giopheaderpadding; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _Foo_Stub extends Stub implements Foo { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.giopheaderpadding.Foo:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public byte fooA(byte arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("fooA", true); + out.write_octet(arg0); + in = _invoke(out); + return in.read_octet(); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return fooA(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("fooA",Foo.class); + if (so == null) { + return fooA(arg0); + } + try { + return ((Foo)so.servant).fooA(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void fooB() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("fooB", true); + _invoke(out); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + fooB(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("fooB",Foo.class); + if (so == null) { + fooB(); + return ; + } + try { + ((Foo)so.servant).fooB(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/hcks/_RmiIIServantPOA_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/hcks/_RmiIIServantPOA_Tie.java new file mode 100644 index 000000000..a93ad0f42 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/hcks/_RmiIIServantPOA_Tie.java @@ -0,0 +1,165 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.hcks; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _RmiIIServantPOA_Tie extends Servant implements Tie { + + volatile private RmiIIServantPOA target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.hcks.RmiII:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (RmiIIServantPOA) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + RmiIIServantPOA target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.length()) { + case 8: + if (method.equals("sayHello")) { + String result = target.sayHello(); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 9: + if (method.equals("sendBytes")) { + byte[] arg0 = (byte[]) in.read_value(byte[].class); + int result = target.sendBytes(arg0); + OutputStream out = reply.createReply(); + out.write_long(result); + return out; + } + case 13: + if (method.equals("sendOneObject")) { + Object arg0 = Util.readAny(in); + Object result; + try { + result = target.sendOneObject(arg0); + } catch (RmiIMyException ex) { + String id = "IDL:org/glassfish/rmic/classes/hcks/RmiIMyEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,RmiIMyException.class); + return out; + } + OutputStream out = reply.createReply(); + Util.writeAny(out,result); + return out; + } + case 14: + if (method.equals("sendTwoObjects")) { + Object arg0 = Util.readAny(in); + Object arg1 = Util.readAny(in); + Object result = target.sendTwoObjects(arg0, arg1); + OutputStream out = reply.createReply(); + Util.writeAny(out,result); + return out; + } + case 22: + if (method.equals("returnObjectFromServer")) { + boolean arg0 = in.read_boolean(); + Object result = target.returnObjectFromServer(arg0); + OutputStream out = reply.createReply(); + Util.writeAny(out,result); + return out; + } + case 24: + if (method.equals("colocatedCallFromServant")) { + String arg0 = (String) in.read_value(String.class); + String result = target.colocatedCallFromServant(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 25: + if (method.equals("throwThreadDeathInServant")) { + String arg0 = (String) in.read_value(String.class); + String result = target.throwThreadDeathInServant(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 28: + if (method.equals("makeColocatedCallFromServant")) { + String result = target.makeColocatedCallFromServant(); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java new file mode 100644 index 000000000..ddfd7f7b7 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java @@ -0,0 +1,359 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.hcks; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _RmiII_Stub extends Stub implements RmiII { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.hcks.RmiII:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public String sayHello() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("sayHello", true); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHello(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHello",RmiII.class); + if (so == null) { + return sayHello(); + } + try { + return ((RmiII)so.servant).sayHello(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public int sendBytes(byte[] arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sendBytes", true); + out.write_value(cast_array(arg0),byte[].class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return in.read_long(); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendBytes(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendBytes",RmiII.class); + if (so == null) { + return sendBytes(arg0); + } + try { + byte[] arg0Copy = (byte[]) Util.copyObject(arg0,_orb()); + return ((RmiII)so.servant).sendBytes(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object sendOneObject(Object arg0) throws java.rmi.RemoteException, org.glassfish.rmic.classes.hcks.RmiIMyException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("sendOneObject", true); + Util.writeAny(out,arg0); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:org/glassfish/rmic/classes/hcks/RmiIMyEx:1.0")) { + throw (org.glassfish.rmic.classes.hcks.RmiIMyException) in.read_value(org.glassfish.rmic.classes.hcks.RmiIMyException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendOneObject(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendOneObject",RmiII.class); + if (so == null) { + return sendOneObject(arg0); + } + try { + Object arg0Copy = (Object) Util.copyObject(arg0,_orb()); + Object result = ((RmiII)so.servant).sendOneObject(arg0Copy); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof org.glassfish.rmic.classes.hcks.RmiIMyException) { + throw (org.glassfish.rmic.classes.hcks.RmiIMyException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object sendTwoObjects(Object arg0, Object arg1) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("sendTwoObjects", true); + Util.writeAny(out,arg0); + Util.writeAny(out,arg1); + in = _invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendTwoObjects(arg0,arg1); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendTwoObjects",RmiII.class); + if (so == null) { + return sendTwoObjects(arg0, arg1); + } + try { + Object[] copies = Util.copyObjects(new Object[]{arg0,arg1},_orb()); + Object arg0Copy = (Object) copies[0]; + Object arg1Copy = (Object) copies[1]; + Object result = ((RmiII)so.servant).sendTwoObjects(arg0Copy, arg1Copy); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String makeColocatedCallFromServant() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("makeColocatedCallFromServant", true); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return makeColocatedCallFromServant(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("makeColocatedCallFromServant",RmiII.class); + if (so == null) { + return makeColocatedCallFromServant(); + } + try { + return ((RmiII)so.servant).makeColocatedCallFromServant(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String colocatedCallFromServant(String arg0) throws java.rmi.RemoteException, java.lang.Exception { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("colocatedCallFromServant", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:java/lang/Ex:1.0")) { + throw (java.lang.Exception) in.read_value(java.lang.Exception.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return colocatedCallFromServant(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("colocatedCallFromServant",RmiII.class); + if (so == null) { + return colocatedCallFromServant(arg0); + } + try { + return ((RmiII)so.servant).colocatedCallFromServant(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof java.lang.Exception) { + throw (java.lang.Exception)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String throwThreadDeathInServant(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("throwThreadDeathInServant", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return throwThreadDeathInServant(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("throwThreadDeathInServant",RmiII.class); + if (so == null) { + return throwThreadDeathInServant(arg0); + } + try { + return ((RmiII)so.servant).throwThreadDeathInServant(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object returnObjectFromServer(boolean arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("returnObjectFromServer", true); + out.write_boolean(arg0); + in = _invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return returnObjectFromServer(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("returnObjectFromServer",RmiII.class); + if (so == null) { + return returnObjectFromServer(arg0); + } + try { + Object result = ((RmiII)so.servant).returnObjectFromServer(arg0); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + // This method is required as a work-around for + // a bug in the JDK 1.1.6 verifier. + + private Serializable cast_array(Object obj) { + return (Serializable)obj; + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/islocal/_MessageBuilderServantPOA_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/islocal/_MessageBuilderServantPOA_Tie.java new file mode 100644 index 000000000..1631a719f --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/islocal/_MessageBuilderServantPOA_Tie.java @@ -0,0 +1,94 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.islocal; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _MessageBuilderServantPOA_Tie extends Servant implements Tie { + + volatile private MessageBuilderServantPOA target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.islocal.MessageBuilder:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (MessageBuilderServantPOA) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + MessageBuilderServantPOA target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + if (method.equals("m")) { + String arg0 = (String) in.read_value(String.class); + String result = target.m(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/islocal/_MessageBuilder_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/islocal/_MessageBuilder_Stub.java new file mode 100644 index 000000000..b4b336263 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/islocal/_MessageBuilder_Stub.java @@ -0,0 +1,70 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.islocal; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _MessageBuilder_Stub extends Stub implements MessageBuilder { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.islocal.MessageBuilder:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public String m(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("m", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return m(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("m",MessageBuilder.class); + if (so == null) { + return m(arg0); + } + try { + return ((MessageBuilder)so.servant).m(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/preinvokepostinvoke/_Interface_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/preinvokepostinvoke/_Interface_Stub.java new file mode 100644 index 000000000..aa3b32e57 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/preinvokepostinvoke/_Interface_Stub.java @@ -0,0 +1,109 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.preinvokepostinvoke; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _Interface_Stub extends Stub implements Interface { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.preinvokepostinvoke.Interface:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public String o1(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("o1", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return o1(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("o1",Interface.class); + if (so == null) { + return o1(arg0); + } + try { + return ((Interface)so.servant).o1(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String o2(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("o2", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return o2(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("o2",Interface.class); + if (so == null) { + return o2(arg0); + } + try { + return ((Interface)so.servant).o2(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/preinvokepostinvoke/_MyServant_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/preinvokepostinvoke/_MyServant_Tie.java new file mode 100644 index 000000000..daedb7dba --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/preinvokepostinvoke/_MyServant_Tie.java @@ -0,0 +1,106 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.preinvokepostinvoke; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _MyServant_Tie extends Servant implements Tie { + + volatile private MyServant target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.preinvokepostinvoke.Interface:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (MyServant) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + MyServant target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.charAt(1)) { + case 49: + if (method.equals("o1")) { + String arg0 = (String) in.read_value(String.class); + String result = target.o1(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 50: + if (method.equals("o2")) { + String arg0 = (String) in.read_value(String.class); + String result = target.o2(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/rmipoacounter/_CounterIF_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/rmipoacounter/_CounterIF_Stub.java new file mode 100644 index 000000000..860ae74b8 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/rmipoacounter/_CounterIF_Stub.java @@ -0,0 +1,68 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.rmipoacounter; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _CounterIF_Stub extends Stub implements CounterIF { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.rmipoacounter.CounterIF:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public long increment(long arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("increment", true); + out.write_longlong(arg0); + in = _invoke(out); + return in.read_longlong(); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return increment(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("increment",CounterIF.class); + if (so == null) { + return increment(arg0); + } + try { + return ((CounterIF)so.servant).increment(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/rmipoacounter/_CounterImpl_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/rmipoacounter/_CounterImpl_Tie.java new file mode 100644 index 000000000..14ed2259c --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/rmipoacounter/_CounterImpl_Tie.java @@ -0,0 +1,93 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.rmipoacounter; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _CounterImpl_Tie extends Servant implements Tie { + + volatile private CounterImpl target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.rmipoacounter.CounterIF:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (CounterImpl) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + CounterImpl target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + if (method.equals("increment")) { + long arg0 = in.read_longlong(); + long result = target.increment(arg0); + OutputStream out = reply.createReply(); + out.write_longlong(result); + return out; + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/systemexceptions/_ServerInvokerServantPOA_Tie.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/systemexceptions/_ServerInvokerServantPOA_Tie.java new file mode 100644 index 000000000..7e82883d1 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/systemexceptions/_ServerInvokerServantPOA_Tie.java @@ -0,0 +1,92 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.systemexceptions; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + + +public class _ServerInvokerServantPOA_Tie extends Servant implements Tie { + + volatile private ServerInvokerServantPOA target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.systemexceptions.ServerInvoker:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (ServerInvokerServantPOA) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return _this_object(); + } + + public void deactivate() { + try{ + _poa().deactivate_object(_poa().servant_to_id(this)); + }catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){ + + }catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){ + + }catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){ + + } + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw new org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + } + + public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){ + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + ServerInvokerServantPOA target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + if (method.equals("invoke")) { + int arg0 = in.read_long(); + target.invoke(arg0); + OutputStream out = reply.createReply(); + return out; + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/systemexceptions/_ServerInvoker_Stub.java b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/systemexceptions/_ServerInvoker_Stub.java new file mode 100644 index 000000000..2d5d6e975 --- /dev/null +++ b/rmic/src/test/masters/with_poas/org/glassfish/rmic/classes/systemexceptions/_ServerInvoker_Stub.java @@ -0,0 +1,68 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.systemexceptions; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _ServerInvoker_Stub extends Stub implements ServerInvoker { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.systemexceptions.ServerInvoker:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public void invoke(int arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("invoke", true); + out.write_long(arg0); + _invoke(out); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + invoke(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("invoke",ServerInvoker.class); + if (so == null) { + invoke(arg0); + return ; + } + try { + ((ServerInvoker)so.servant).invoke(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + } diff --git a/rmic/src/test/masters/without_poas/org/glassfish/rmic/classes/hcks/_RmiIIServant_Tie.java b/rmic/src/test/masters/without_poas/org/glassfish/rmic/classes/hcks/_RmiIIServant_Tie.java new file mode 100644 index 000000000..78693f878 --- /dev/null +++ b/rmic/src/test/masters/without_poas/org/glassfish/rmic/classes/hcks/_RmiIIServant_Tie.java @@ -0,0 +1,153 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.hcks; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + + +public class _RmiIIServant_Tie extends ObjectImpl implements Tie { + + volatile private RmiIIServant target = null; + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.hcks.RmiII:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (RmiIIServant) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + RmiIIServant target = this.target; + if (target == null) { + throw new java.io.IOException(); + } + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.length()) { + case 8: + if (method.equals("sayHello")) { + String result = target.sayHello(); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 9: + if (method.equals("sendBytes")) { + byte[] arg0 = (byte[]) in.read_value(byte[].class); + int result = target.sendBytes(arg0); + OutputStream out = reply.createReply(); + out.write_long(result); + return out; + } + case 13: + if (method.equals("sendOneObject")) { + Object arg0 = Util.readAny(in); + Object result; + try { + result = target.sendOneObject(arg0); + } catch (RmiIMyException ex) { + String id = "IDL:org/glassfish/rmic/classes/hcks/RmiIMyEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,RmiIMyException.class); + return out; + } + OutputStream out = reply.createReply(); + Util.writeAny(out,result); + return out; + } + case 14: + if (method.equals("sendTwoObjects")) { + Object arg0 = Util.readAny(in); + Object arg1 = Util.readAny(in); + Object result = target.sendTwoObjects(arg0, arg1); + OutputStream out = reply.createReply(); + Util.writeAny(out,result); + return out; + } + case 22: + if (method.equals("returnObjectFromServer")) { + boolean arg0 = in.read_boolean(); + Object result = target.returnObjectFromServer(arg0); + OutputStream out = reply.createReply(); + Util.writeAny(out,result); + return out; + } + case 24: + if (method.equals("colocatedCallFromServant")) { + String arg0 = (String) in.read_value(String.class); + String result = target.colocatedCallFromServant(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 25: + if (method.equals("throwThreadDeathInServant")) { + String arg0 = (String) in.read_value(String.class); + String result = target.throwThreadDeathInServant(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 28: + if (method.equals("makeColocatedCallFromServant")) { + String result = target.makeColocatedCallFromServant(); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/rmic/src/test/masters/without_poas/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java b/rmic/src/test/masters/without_poas/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java new file mode 100644 index 000000000..ddfd7f7b7 --- /dev/null +++ b/rmic/src/test/masters/without_poas/org/glassfish/rmic/classes/hcks/_RmiII_Stub.java @@ -0,0 +1,359 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package org.glassfish.rmic.classes.hcks; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _RmiII_Stub extends Stub implements RmiII { + + private static final String[] _type_ids = { + "RMI:org.glassfish.rmic.classes.hcks.RmiII:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public String sayHello() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("sayHello", true); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHello(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHello",RmiII.class); + if (so == null) { + return sayHello(); + } + try { + return ((RmiII)so.servant).sayHello(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public int sendBytes(byte[] arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sendBytes", true); + out.write_value(cast_array(arg0),byte[].class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return in.read_long(); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendBytes(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendBytes",RmiII.class); + if (so == null) { + return sendBytes(arg0); + } + try { + byte[] arg0Copy = (byte[]) Util.copyObject(arg0,_orb()); + return ((RmiII)so.servant).sendBytes(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object sendOneObject(Object arg0) throws java.rmi.RemoteException, org.glassfish.rmic.classes.hcks.RmiIMyException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("sendOneObject", true); + Util.writeAny(out,arg0); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:org/glassfish/rmic/classes/hcks/RmiIMyEx:1.0")) { + throw (org.glassfish.rmic.classes.hcks.RmiIMyException) in.read_value(org.glassfish.rmic.classes.hcks.RmiIMyException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendOneObject(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendOneObject",RmiII.class); + if (so == null) { + return sendOneObject(arg0); + } + try { + Object arg0Copy = (Object) Util.copyObject(arg0,_orb()); + Object result = ((RmiII)so.servant).sendOneObject(arg0Copy); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof org.glassfish.rmic.classes.hcks.RmiIMyException) { + throw (org.glassfish.rmic.classes.hcks.RmiIMyException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object sendTwoObjects(Object arg0, Object arg1) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("sendTwoObjects", true); + Util.writeAny(out,arg0); + Util.writeAny(out,arg1); + in = _invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sendTwoObjects(arg0,arg1); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sendTwoObjects",RmiII.class); + if (so == null) { + return sendTwoObjects(arg0, arg1); + } + try { + Object[] copies = Util.copyObjects(new Object[]{arg0,arg1},_orb()); + Object arg0Copy = (Object) copies[0]; + Object arg1Copy = (Object) copies[1]; + Object result = ((RmiII)so.servant).sendTwoObjects(arg0Copy, arg1Copy); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String makeColocatedCallFromServant() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("makeColocatedCallFromServant", true); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return makeColocatedCallFromServant(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("makeColocatedCallFromServant",RmiII.class); + if (so == null) { + return makeColocatedCallFromServant(); + } + try { + return ((RmiII)so.servant).makeColocatedCallFromServant(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String colocatedCallFromServant(String arg0) throws java.rmi.RemoteException, java.lang.Exception { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("colocatedCallFromServant", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:java/lang/Ex:1.0")) { + throw (java.lang.Exception) in.read_value(java.lang.Exception.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return colocatedCallFromServant(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("colocatedCallFromServant",RmiII.class); + if (so == null) { + return colocatedCallFromServant(arg0); + } + try { + return ((RmiII)so.servant).colocatedCallFromServant(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof java.lang.Exception) { + throw (java.lang.Exception)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String throwThreadDeathInServant(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("throwThreadDeathInServant", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return throwThreadDeathInServant(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("throwThreadDeathInServant",RmiII.class); + if (so == null) { + return throwThreadDeathInServant(arg0); + } + try { + return ((RmiII)so.servant).throwThreadDeathInServant(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public Object returnObjectFromServer(boolean arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("returnObjectFromServer", true); + out.write_boolean(arg0); + in = _invoke(out); + return Util.readAny(in); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return returnObjectFromServer(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("returnObjectFromServer",RmiII.class); + if (so == null) { + return returnObjectFromServer(arg0); + } + try { + Object result = ((RmiII)so.servant).returnObjectFromServer(arg0); + return (Object)Util.copyObject(result,_orb()); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + // This method is required as a work-around for + // a bug in the JDK 1.1.6 verifier. + + private Serializable cast_array(Object obj) { + return (Serializable)obj; + } + } diff --git a/src/share/classes/com/sun/corba/ee/GiopIDL/GIOP.idl b/src/share/classes/com/sun/corba/ee/GiopIDL/GIOP.idl new file mode 100644 index 000000000..5ffd912e7 --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/GiopIDL/GIOP.idl @@ -0,0 +1,214 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @(#)GIOP.idl 1.0 00/05/21 + * + */ + +#include "IOP.idl" + +module GIOP { // IDL extended for version 1.1 and 1.2 + + struct Version { + octet major; + octet minor; + }; + + + // GIOP 1.0 + + struct MessageHeader_1_0 { // Renamed from MessageHeader + char magic [4]; + Version GIOP_version; + boolean byte_order; + octet message_type; + unsigned long message_size; + }; + + // GIOP 1.1 + + struct MessageHeader_1_1 { + char magic [4]; + Version GIOP_version; + octet flags; // GIOP 1.1 change + octet message_type; + unsigned long message_size; + }; + + // GIOP 1.2 + // Same Header contents for 1.1 and 1.2 + typedef MessageHeader_1_1 MessageHeader_1_2; + + + // GIOP 1.0 + struct RequestHeader_1_0 { // Renamed from RequestHeader + IOP::ServiceContextList service_context; + unsigned long request_id; + boolean response_expected; + sequence object_key; + string operation; + sequence requesting_principal; + }; + + // GIOP 1.1 + struct RequestHeader_1_1 { + IOP::ServiceContextList service_context; + unsigned long request_id; + boolean response_expected; + octet reserved[3]; // Added in GIOP 1.1 + sequence object_key; + string operation; + sequence requesting_principal; + }; + + // GIOP 1.2 + typedef short AddressingDisposition; + const short KeyAddr = 0; + const short ProfileAddr = 1; + const short ReferenceAddr = 2; + struct IORAddressingInfo { + unsigned long selected_profile_index; + IOP::IOR ior; + }; + union TargetAddress switch (AddressingDisposition) { + case KeyAddr: sequence object_key; + case ProfileAddr: IOP::TaggedProfile profile; + case ReferenceAddr: IORAddressingInfo ior; + }; + struct RequestHeader_1_2 { + unsigned long request_id; + octet response_flags; + octet reserved[3]; + TargetAddress target; + string operation; + IOP::ServiceContextList service_context; + // Principal not in GIOP 1.2 + }; + + + #ifndef GIOP_1_2 //We're supporting all versions + + // GIOP 1.0 and 1.1 + enum ReplyStatusType_1_0 { // Renamed from ReplyStatusType + NO_EXCEPTION, + USER_EXCEPTION, + SYSTEM_EXCEPTION, + LOCATION_FORWARD + }; + + // GIOP 1.0 + struct ReplyHeader_1_0 { // Renamed from ReplyHeader + IOP::ServiceContextList service_context; + unsigned long request_id; + ReplyStatusType_1_0 reply_status; + }; + + // GIOP 1.1 + // Same Header contents for 1.0 and 1.1 + typedef ReplyHeader_1_0 ReplyHeader_1_1; + + #else + + // GIOP 1.2 + enum ReplyStatusType_1_2 { + NO_EXCEPTION, + USER_EXCEPTION, + SYSTEM_EXCEPTION, + LOCATION_FORWARD, + LOCATION_FORWARD_PERM,// new value for 1.2 + NEEDS_ADDRESSING_MODE // new value for 1.2 + }; + + struct ReplyHeader_1_2 { + unsigned long request_id; + ReplyStatusType_1_2 reply_status; + IOP::ServiceContextList service_context; + }; + + #endif // GIOP_1_2 + + + struct SystemExceptionReplyBody { + string exception_id; + unsigned long minor_code_value; + unsigned long completion_status; + }; + + + + struct CancelRequestHeader { + unsigned long request_id; + }; + + + + // GIOP 1.0 + struct LocateRequestHeader_1_0 { // Renamed LocationRequestHeader + unsigned long request_id; + sequence object_key; + }; + + // GIOP 1.1 + // Same Header contents for 1.0 and 1.1 + typedef LocateRequestHeader_1_0 LocateRequestHeader_1_1; + + // GIOP 1.2 + struct LocateRequestHeader_1_2 { + unsigned long request_id; + TargetAddress target; + }; + + + #ifndef GIOP_1_2 // We're supporting all versions + + // GIOP 1.0 and 1.1 + enum LocateStatusType_1_0 { // Renamed from LocateStatusType + UNKNOWN_OBJECT, + OBJECT_HERE, + OBJECT_FORWARD + }; + + + // GIOP 1.0 + struct LocateReplyHeader_1_0 { // Renamed from LocateReplyHeader + unsigned long request_id; + LocateStatusType_1_0 locate_status; + }; + + // GIOP 1.1 + // same Header contents for 1.0 and 1.1 + typedef LocateReplyHeader_1_0 LocateReplyHeader_1_1; + + #else + + // GIOP 1.2 + enum LocateStatusType_1_2 { + UNKNOWN_OBJECT, + OBJECT_HERE, + OBJECT_FORWARD, + OBJECT_FORWARD_PERM, // new value for GIOP 1.2 + LOC_SYSTEM_EXCEPTION, // new value for GIOP 1.2 + LOC_NEEDS_ADDRESSING_MODE // new value for GIOP 1.2 + }; + + struct LocateReplyHeader_1_2 { + unsigned long request_id; + LocateStatusType_1_2 locate_status; + }; + + #endif // GIOP_1_2 + + + // GIOP 1.2 + struct FragmentHeader_1_2 { + unsigned long request_id; + }; +}; diff --git a/src/share/classes/com/sun/corba/ee/GiopIDL/messages.idl b/src/share/classes/com/sun/corba/ee/GiopIDL/messages.idl new file mode 100644 index 000000000..853c187e6 --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/GiopIDL/messages.idl @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @(#)GIOP.idl 1.0 00/05/21 + * + */ + +#include "IOP.idl" + +module messages { + + typedef short AddressingDisposition; + const short KeyAddr = 0; + const short ProfileAddr = 1; + const short ReferenceAddr = 2; + struct IORAddressingInfo { + unsigned long selected_profile_index; + IOP::IOR ior; + }; + union TargetAddress switch (AddressingDisposition) { + case KeyAddr: sequence object_key; + case ProfileAddr: IOP::TaggedProfile profile; + case ReferenceAddr: IORAddressingInfo ior; + }; +}; diff --git a/src/share/classes/com/sun/corba/ee/impl/osgi/main/ORBFactoryTest.java b/src/share/classes/com/sun/corba/ee/impl/osgi/main/ORBFactoryTest.java new file mode 100644 index 000000000..f8bacd3ad --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/impl/osgi/main/ORBFactoryTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.impl.osgi.main ; + +import org.osgi.framework.Bundle ; +import org.osgi.framework.BundleActivator ; +import org.osgi.framework.BundleEvent ; +import org.osgi.framework.BundleContext ; +import org.osgi.framework.SynchronousBundleListener ; +import org.osgi.framework.ServiceReference ; + +import org.osgi.service.packageadmin.PackageAdmin ; +import org.osgi.service.packageadmin.ExportedPackage ; + +import java.util.Properties ; + +import com.sun.corba.ee.spi.osgi.ORBFactory ; +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager ; + +public class ORBFactoryTest implements BundleActivator, SynchronousBundleListener { + private static PackageAdmin pkgAdmin ; + + private static String getBundleEventType( int type ) { + if (type == BundleEvent.INSTALLED) + return "INSTALLED" ; + else if (type == BundleEvent.LAZY_ACTIVATION) + return "LAZY_ACTIVATION" ; + else if (type == BundleEvent.RESOLVED) + return "RESOLVED" ; + else if (type == BundleEvent.STARTED) + return "STARTED" ; + else if (type == BundleEvent.STARTING) + return "STARTING" ; + else if (type == BundleEvent.STOPPED) + return "STOPPED" ; + else if (type == BundleEvent.STOPPING) + return "STOPPING" ; + else if (type == BundleEvent.UNINSTALLED) + return "UNINSTALLED" ; + else if (type == BundleEvent.UNRESOLVED) + return "UNRESOLVED" ; + else if (type == BundleEvent.UPDATED) + return "UPDATED" ; + else + return "ILLEGAL-EVENT-TYPE" ; + } + + private static void msg( String arg ) { + System.out.println( "ORBFactoryTest: " + arg ) ; + } + + private ORB orb = null ; + + public void start( BundleContext context ) { + msg( "Starting ORBFactoryTest" ) ; + context.addBundleListener( this ) ; + + try { + ServiceReference sref = context.getServiceReference( "org.osgi.service.packageadmin.PackageAdmin" ) ; + pkgAdmin = (PackageAdmin)context.getService( sref ) ; + + dumpInfo( context, pkgAdmin ) ; + } catch (Exception exc) { + msg( "Exception in getting PackageAdmin: " + exc ) ; + } + } + + private void dumpInfo( BundleContext context, PackageAdmin pkgAdmin ) { + msg( "Dumping bundle information" ) ; + for (Bundle bundle : context.getBundles()) { + msg( "\tBundle: " + bundle.getSymbolicName() ) ; + for (ExportedPackage ep : pkgAdmin.getExportedPackages( bundle ) ) { + msg( "\t\tExport: " + ep.getName() ) ; + } + } + } + + public void stop( BundleContext context ) { + msg( "Stopping ORBFactoryTest" ) ; + context.removeBundleListener( this ) ; + } + + public void bundleChanged(BundleEvent event) { + int type = event.getType() ; + String name = event.getBundle().getSymbolicName() ; + + msg( "Received event type " + + getBundleEventType( type ) + " for bundle " + name ) ; + + // Only want to know when this bundle changes state, not the others. + if (!name.equals( "glassfish-corba-osgi-test" )) { + return ; + } + + if ((type & (BundleEvent.STARTED | BundleEvent.STARTING)) != 0) { + try { + String[] args = {} ; + Properties props = new Properties() ; + props.setProperty( ORBConstants.RFM_PROPERTY, "dummy" ) ; + orb = ORBFactory.create() ; + ORBFactory.initialize( orb, args, props, true ) ; + ReferenceFactoryManager rfm = + (ReferenceFactoryManager)orb.resolve_initial_references( + ORBConstants.REFERENCE_FACTORY_MANAGER ) ; + msg( "ORB successfully created" ) ; + } catch (Exception exc) { + exc.printStackTrace() ; + } + } else if ((type & (BundleEvent.STOPPED | BundleEvent.STOPPING)) != 0) { + if (orb != null) { + orb.destroy() ; + } + msg( "ORB destroyed" ) ; + } + } +} diff --git a/src/share/classes/com/sun/corba/ee/internal/io/IIOPInputStream.java b/src/share/classes/com/sun/corba/ee/internal/io/IIOPInputStream.java new file mode 100644 index 000000000..d5235bd7a --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/internal/io/IIOPInputStream.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.io; + +public class IIOPInputStream { + private static native Object allocateNewObject(Class aclass, + Class initclass) + throws InstantiationException, IllegalAccessException; + /* Create a pending exception. This is needed to get around + * the fact that the *Delegate methods do not explicitly + * declare that they throw exceptions. + * + * This native methods creates an exception of the given type with + * the given message string and posts it to the pending queue. + */ + private static native void throwExceptionType(Class c, String message); + + /* The following native methods of the form set*Field are used + * to set private, protected, and package private fields + * of an Object. + */ + private static native void setObjectField(Object o, Class c, String fieldName, String fieldSig, Object v); + private static native void setBooleanField(Object o, Class c, String fieldName, String fieldSig, boolean v); + private static native void setByteField(Object o, Class c, String fieldName, String fieldSig, byte v); + private static native void setCharField(Object o, Class c, String fieldName, String fieldSig, char v); + private static native void setShortField(Object o, Class c, String fieldName, String fieldSig, short v); + private static native void setIntField(Object o, Class c, String fieldName, String fieldSig, int v); + private static native void setLongField(Object o, Class c, String fieldName, String fieldSig, long v); + private static native void setFloatField(Object o, Class c, String fieldName, String fieldSig, float v); + private static native void setDoubleField(Object o, Class c, String fieldName, String fieldSig, double v); + private static native void readObject(Object obj, Class asClass, Object ois); + + private static native void setObjectFieldOpt(Object o, long fieldID, Object v); + private static native void setBooleanFieldOpt(Object o, long fieldID, boolean v); + private static native void setByteFieldOpt(Object o, long fieldID, byte v); + private static native void setCharFieldOpt(Object o, long fieldID, char v); + private static native void setShortFieldOpt(Object o, long fieldID, short v); + private static native void setIntFieldOpt(Object o, long fieldID, int v); + private static native void setLongFieldOpt(Object o, long fieldID, long v); + + private static native void setFloatFieldOpt(Object o, long fieldID, float v); + private static native void setDoubleFieldOpt(Object o, long fieldID, double v); +} diff --git a/src/share/classes/com/sun/corba/ee/internal/io/IIOPOutputStream.java b/src/share/classes/com/sun/corba/ee/internal/io/IIOPOutputStream.java new file mode 100644 index 000000000..c182d0c47 --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/internal/io/IIOPOutputStream.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.io; + + +public class IIOPOutputStream { + + /* Create a pending exception. This is needed to get around + * the fact that the *Delegate methods do not explicitly + * declare that they throw exceptions. + * + * This native method creates an exception of the given type with + * the given message string and posts it to the pending queue. + */ + private static native void throwExceptionType(Class c, String message); + + private static native Object getObjectFieldOpt(Object o, long fieldID); + private static native boolean getBooleanFieldOpt(Object o, long fieldID); + private static native byte getByteFieldOpt(Object o, long fieldID); + private static native char getCharFieldOpt(Object o, long fieldID); + private static native short getShortFieldOpt(Object o, long fieldID); + private static native int getIntFieldOpt(Object o, long fieldID); + private static native long getLongFieldOpt(Object o, long fieldID); + private static native float getFloatFieldOpt(Object o, long fieldID); + private static native double getDoubleFieldOpt(Object o, long fieldID); + + private static native void writeObject(Object obj, Class asClass, Object oos) throws IllegalAccessException; +} diff --git a/src/share/classes/com/sun/corba/ee/internal/io/LibraryManager.java b/src/share/classes/com/sun/corba/ee/internal/io/LibraryManager.java new file mode 100644 index 000000000..d1570e7b4 --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/internal/io/LibraryManager.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.io; + +public class LibraryManager +{ + native private static int getMajorVersion(); + + native private static int getMinorVersion(); + + private static native boolean setEnableOverride(Class targetClass, Object instance); +} diff --git a/src/share/classes/com/sun/corba/ee/internal/io/ObjectStreamClass.java b/src/share/classes/com/sun/corba/ee/internal/io/ObjectStreamClass.java new file mode 100644 index 000000000..9ee956d8f --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/internal/io/ObjectStreamClass.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.internal.io; + +public class ObjectStreamClass { + + /* Find out if the class has a static class initializer */ + private static native boolean hasStaticInitializer(Class cl); + +} diff --git a/src/share/classes/com/sun/corba/ee/pept/package.html b/src/share/classes/com/sun/corba/ee/pept/package.html new file mode 100644 index 000000000..d87549198 --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/pept/package.html @@ -0,0 +1,346 @@ + + + + + + + + +

                This package is the top-level package for the PEPt Remoting +Architecture. PEPt enables remoting (i.e., RPC and Messaging) +systems to dynamically use alternate encodings, protocols and +transports.

                + +

                Related Documentation

                + +

                +For papers, slides and examples of the PEPt architecture, please see: +

                +

                + +

                PEPt Architecture

                + +

                +PEPt stands for: +

                  + +
                • Presentation: the data types that may be passed and the +APIs used to interact with the remoting system.
                • + +
                • Encoding: the process of transforming those programming +language data types into an underlying "wire" representation (and the +wire representation itself).
                • + +
                • Protocol: The metadata which accompanies a message and the +use of that metadata.
                • + +
                • transport: The mechanism used to move the encoded data and +metadata from one location to another.
                • + +
                +

                + +

                Key PEPt Interfaces

                +
                  + +
                • {@link com.sun.corba.ee.pept.transport.ContactInfoList ContactInfoList} + - Client-side address selection mechanism and factory for + alternate encodings, protocols and transports (EPT).
                • + +
                • {@link com.sun.corba.ee.pept.transport.Acceptor Acceptor} + - Server-side endpoint, addressing and factory for alternate EPTs.
                • + +
                +

                + +

                PEPt Client-side Interfaces

                +
                  +
                • Protocol +
                    + +
                  • {@link com.sun.corba.ee.pept.protocol.ClientDelegate ClientDelegate} + - The presentation block interacts with ClientDelegate + to initiate and complete a message send (and a possible + response). ClientDelegate is a "portability" interface, + to allow different vendors to plug in their implementation into a + standard presentation block.
                  • + +
                  • {@link com.sun.corba.ee.pept.protocol.ClientRequestDispatcher + ClientRequestDispatcher} - This interface controls the client-side + dispatch for a given EPT.
                  • + +
                  +
                • +
                • Transport +
                    + +
                  • {@link com.sun.corba.ee.pept.protocol.ContactInfoList + ContactInfoList} - A list of ContactInfo associated + with a ClientDelegate
                  • . + +
                  • {@link com.sun.corba.ee.pept.protocol.ContactInfoListIterator + ContactInfoListIterator} - An iterator which chooses the "next" + EPT-specific ContactInfo.
                  • + +
                  • {@link com.sun.corba.ee.pept.protocol.ContactInfoList + ContactInfo} - The key PEPt client-side interface. The + presentation block uses a ClientDelegate to select an + EPT-specific ContactInfo. That ContactInfo + serves as a factory for EPT-specifc + ClientRequestDispatcher, + Input/OutputObjects and Connection.
                  • + +
                  +
                • +
                +

                + +

                PEPt Server-side Interfaces

                +
                  +
                • Protocol +
                    + +
                  • {@link com.sun.corba.ee.pept.protocol.ServerRequestDispatcher + ServerRequestDispatcher} - This interface controls the server-side + dispatch for a given EPT.
                  • + +
                  +
                • +
                • Transport +
                    + +
                  • {@link com.sun.corba.ee.pept.protocol.Acceptor Acceptor} + - The key PEPt server-side interface. Aceptor + serves as a factory for EPT-specifc + ServerRequestDispatcher, + Input/OutputObjects and Connection.
                  • + +
                  +
                • +
                +

                + +

                PEPt Client and Server Interfaces

                +
                  +
                • Presentation +
                    + +
                  • PEPt, at this time, does not provide interfaces for the + presentation level. PEPt is the architecture underlying Sun's CORBA + implementation. In that implementation the CORBA system provides + stubs, ties, DII and DSI presentation artifacts that interact with + the underlying PEPt interfaces.
                  • + +
                  +
                • +
                • Encoding +
                    + +
                  • {@link com.sun.corba.ee.pept.encoding.InputObject InputObject} + - The presentation block uses an InputObject to + retrieve programming language typed data from encoded data sent in a + message.
                  • + +
                  • {@link com.sun.corba.ee.pept.encoding.OutputObject OutputObject} + - The presentation block uses an OutputObject to + post programming language typed data to be encoded and sent in a + message.
                  • + +
                  +
                • +
                • Protocol +
                    + +
                  • {@link com.sun.corba.ee.pept.protocol.MessageMediator MessageMediator} + - A "repository" of data associated with a message to be sent or one + received. It is the main object used as an argument for methods of + the interfaces of the PEPt architecture.
                  • + +
                  • {@link com.sun.corba.ee.pept.protocol.ProtocolHandler ProtocolHandler} + - Used to determine an incoming message and dispatch it + appropriately.
                  • + +
                  +
                • +
                • transport +
                    + +
                  • {@link com.sun.corba.ee.pept.protocol.Connection Connection} + - The top-level abstraction of a "connection" between two PEPt + peers. Concreate instances may be TCP/IP sockets, Solaris Doors, + Shared Memory, ATM, etc.
                  • + +
                  +
                • +
                +

                + +

                High-level view of PEPt Operation

                + +

                PEPt Client-side Operation

                + +
                  +
                1. Presentation asks ClientDelegate for an +OutputObject.
                2. +
                    +
                  1. ClientDelegate gets an EPT-specific + ContactInfo.
                  2. +
                  3. ClientDelegate uses the chosen + ContactInfo as a factory to get an EPT-specific + ClientRequestDispatcher.
                  4. +
                  5. ClientDelegate transfers control to the + EPT-specific ClientRequestDispatcher.beginRequest. +
                      +
                    1. ClientRequestDispatcher.beginRequest uses + ContactInfo as a factory to get EPT-specific + OutputObject, MessageMediator and + Connection.
                    2. +
                    3. ClientRequestDispatcher.beginRequest may marshal + or set header information on the OutputObject and it + may execute interceptors (which may add additional header + information) before returning the OutputObject to the + presentation block.
                    4. +
                    +
                  +
                3. Presentation block sets data objects to be sent by calling +OutputObject methods.
                4. +
                5. Presentation block signals the PEPt architecture to send the +message by calling +ClientRequestDispatcher.marshalingComplete.
                6. +
                7. ClientRequestDispatcher.marshalingComplete sends the +headers and data encoded in OutputObject on the +Connection.
                8. +
                9. Depending on the EPT, +ClientRequestDispatcher.marshalingComplete may return +immediately (i.e., an asynchronous message send with no +acknowledgment), may wait to get an indication that the message send +was successfully (i.e., an acknowledged asynchronous send) or wait for +a response (a synchronous message send). The following steps assume +waiting for a response.
                10. +
                11. ClientRequestDispatcher.marshalingComplete waits for a +response. This may mean blocking on a read of the +Connection (e.g., SOAP/HTTP), or putting the client +thread to sleep while another thread demultiplexes replies (e.g., +RMI-IIOP), or using the client thread itself to perform the +server-side operation (e.g., colocation optimization).
                12. +
                13. When a response arrives on the Connection it gives +the raw bits of the response to ContactInfo which creates +an EPT-specific InputObject and calls +ProtocolHandler.handleRequest to determine the message +type.
                14. +
                    +
                  1. ProtocolHandler.handleRequest determines the + message type (e.g., Request, Response, Error, Cancel, Close, ...).
                  2. +
                  3. Suppose it is a response to an RMI-IIOP request. In that case + it would find the thread and MessageMediator which + originated the request and wake it up, after having passed it the + response InputObject.
                  4. +
                  +
                15. ClientRequestDispatcher.marshalingComplete may run +interceptors and use reply header metadata befor returning control to +the presentation block.
                16. +
                17. The presentation block call to +ClientRequestDispatcher.marshalingComplete would return +the response InputObject.
                18. +
                19. The presentation block would get response data objects from the +InputObject.
                20. +
                21. The presentation block would signal the PEPt architecture that +the invocation is complete by calling +ClientRequestDispatcher.endRequest.
                22. +
                23. ClientRequestDispatcher.endRequest may clean up +resources used in the invocation.
                24. +
                + +

                PEPt Server-side Operation

                + +

                Suppose a server support several EPTs.

                + +
                  +
                1. For each EPT, register an Acceptor.
                2. +
                3. If the system supports the concept of an "object reference" then +the Acceptor is responsible for adding its EPT +information (e.g., address information) to the object reference.
                4. +
                5. The Acceptor acts as a "listener" for client +connection requests.
                6. +
                7. When the Acceptor receives a connection request it +creates an EPT-specific Connection on which to receive +messages.
                8. +
                9. When Connection receives a message, it gives the raw +bits of the message to Acceptor which creates an +EPT-specific InputObject and calls +ProtocolHandler.handleRequest to determine the message +type.
                10. +
                    +
                  1. ProtocolHandler.handleRequest determines the + message type.
                  2. +
                  3. Suppose it is a request. In that case it would read enough + header information to give to Acceptor to get an + EPT-specific InputObject, + ServerRequestDispatcher and MessageMediator.
                  4. +
                  5. Control would then transfer to + ServerRequestDispatcher.dispatch.
                  6. +
                      +
                    1. ServerRequestDispatcher.dispatch uses header + information to obtain appropriate presentation block artifacts + (e.g., Ties, DSI handlers).
                    2. +
                    3. As an example, a Tie would be given the InputObject.
                    4. +
                        +
                      1. The Tie would get the request data from the + InputObject and make it available to user + code.
                      2. +
                      3. In the case of a synchronous message, the Tie would ask the + ServerRequestDispatcher for an + OutputObject.
                      4. +
                          +
                        1. The ServerRequestDispatcher would use the + Acceptor as a factory to create the EPT-specific + OutputObject.
                        2. +
                        +
                      5. The Tie would set the response data (normal or error) on + the OutputObject.
                      6. +
                      +
                    5. ServerRequestDispatcher.dispatch would send the + header and response data encoded in OutputObject on + the Connection.
                    6. +
                    +
                  7. ServerRequestDispatcher.dispatch may clean up + any resources used in the invocation.
                  8. +
                  +
                + + +

                Initial ContactInfo and Acceptor Creation

                + +

                ContactInfo and Acceptor are the +factories for all other objects involved in a message for a particular +EPT. The question naturally arises, how are these created?

                + +
                  +
                • From a tool reading service descriptions (e.g., WSDL).
                • +
                • By reading the contents of an object reference (e.g., CORBA IOR).
                • +
                • From a configuration file.
                • +
                + +

                Other PEPt Interfaces

                + +
                  +
                • {@link com.sun.corba.ee.pept.broker.Broker Broker} - A repository +of resources such as transport managers, thread pools, thread local +data structures, etc.
                • +
                + + + diff --git a/src/share/classes/com/sun/corba/ee/tool/IORDump.java b/src/share/classes/com/sun/corba/ee/tool/IORDump.java new file mode 100644 index 000000000..1c42db2ac --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/tool/IORDump.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.tool ; + +import org.omg.CORBA.portable.ObjectImpl ; + +import com.sun.corba.ee.spi.orb.ORB ; +import com.sun.corba.ee.spi.protocol.ClientDelegate ; +import com.sun.corba.ee.spi.transport.ContactInfoList ; + +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.impl.ior.GenericIdentifiable ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; +import com.sun.corba.ee.spi.ior.TaggedProfile ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import org.glassfish.pfl.basic.algorithm.Printer; + +public class IORDump { + private static Printer pr = new Printer( System.out ) ; + + private static final String[] STANDARD_TAGGED_COMPONENT_NAMES = new String[]{ + "ORB_TYPE", // 0 + "CODE_SETS", + "POLICIES", + "ALTERNATE_IIOP_ADDRESS", + null, + "COMPLETE_OBJECT_KEY", + "ENDPOINT_ID_POSITION", + null, + null, + null, + null, // 10 + null, + "LOCATION_POLICY", + "ASSOCIATION_OPTIONS", + "SEC_NAME", + "SPKM_1_SEC_MECH", + "SPKM_2_SEC_MECH", + "KergerosV5_SEC_MECH", + "CSI_ECMA_Secret_SEC_MECH", + "CSI_ECMA_Hybrid_SEC_MECH", + "SSL_SEC_TRANS", // 20 + "CSI_ECMA_Public_SEC_MECH", + "GENERIC_SEC_MECH", + "FIREWALL_TRANS", + "SCCP_CONTACT_INFO", + "JAVA_CODEBASE", + "TRANSACTION_POLICY", + "FT_GROUP", + "FT_PRIMARY", + "FT_HEARTBEAT_ENABLED", + "MESSAGE_ROUTERS", // 30 + "OTS_POLICY", + "INV_POLICY", + "CSI_SEC_MECH_LIST", + "NULL_TAG", + "SECIOP_SEC_TRANS", + "TLS_SEC_TRANS", + "ACTIVITY_POLICY", + "RMI_CUSTOM_MAX_STREAM_FORMAT", + null, + null, // 40 + null, null, null, null, null, + null, null, null, null, null, // 50 + null, null, null, null, null, + null, null, null, null, null, // 60 + null, null, null, null, null, + null, null, null, null, null, // 70 + null, null, null, null, null, + null, null, null, null, null, // 80 + null, null, null, null, null, + null, null, null, null, null, // 90 + null, null, null, null, null, + null, null, null, null, + "DCE_STRING_BINDING", // 100 + "DCE_BINDING_NAME", + "DCE_NO_PIPES", + "DCE_SEC_MECH", + null, null, + null, null, null, null, null, // 110 + null, null, null, null, null, + null, null, null, null, null, // 120 + null, null, + "INET_SEC_TRANS" + } ; + + private static String getTaggedComponentName( int id ) { + String entry = null ; + if ((id >= 0) && (id < STANDARD_TAGGED_COMPONENT_NAMES.length)) + entry = STANDARD_TAGGED_COMPONENT_NAMES[id] ; + + if (entry == null) + entry = "UNASSIGNED_" + id ; + + return entry ; + } + + public static void main( String[] args ) { + if (args.length != 1) { + System.out.println( "Syntax: iordump " ) ; + } else { + try { + String iorString = args[0] ; + String[] initArgs = null ; + ORB orb = (ORB)ORB.init( initArgs, null ) ; + org.omg.CORBA.Object obj = orb.string_to_object( iorString ) ; + ObjectImpl oimpl = (ObjectImpl)obj ; + ClientDelegate delegate = (ClientDelegate)(oimpl._get_delegate()) ; + ContactInfoList cilist = (ContactInfoList)(delegate.getContactInfoList()) ; + IOR ior = cilist.getTargetIOR() ; + dumpIOR( ior ) ; + } catch (Exception exc) { + System.out.println( "Caught exception: " + exc ) ; + exc.printStackTrace() ; + } + } + } + + public static void dumpIOR( IOR ior ) { + pr.nl().p( "Dump of IOR:" ).in() ; + pr.nl().p( "typeId = " + ior.getTypeId() ) ; + pr.nl().p( "tagged profiles:" ).in() ; + for (TaggedProfile tprof : ior) { + dumpTaggedProfile( tprof ) ; + } + pr.out().out().nl() ; + } + + public static void dumpTaggedProfile( TaggedProfile tprof ) { + pr.nl().p( "Id = ", tprof.getId(), ":" ).in() ; + + TaggedProfileTemplate tpt = tprof.getTaggedProfileTemplate() ; + if (tpt instanceof IIOPProfileTemplate) { + IIOPProfileTemplate iptemp = (IIOPProfileTemplate)tpt ; + pr.nl().p( "GIOPVersion = ", iptemp.getGIOPVersion() ) ; + pr.nl().p( "PrimaryAddress = ", iptemp.getPrimaryAddress() ) ; + } + + pr.nl().p( "ObjectId:" ).in() ; + pr.printBuffer( tprof.getObjectId().getId() ).out() ; + + pr.nl().p( "ObjectKeyTemplate:" ).in() ; + dumpObjectKeyTemplate( tprof.getObjectKeyTemplate() ) ; + pr.out() ; + + pr.nl().p( "Tagged components:" ).in() ; + for (TaggedComponent tcomp : tpt ) { + int id = tcomp.getId() ; + pr.nl().p( "id = ", tcomp.getId(), + " (", getTaggedComponentName( id ), ")" ).in() ; + if (tcomp instanceof GenericIdentifiable) { + GenericIdentifiable gid = (GenericIdentifiable)tcomp ; + pr.printBuffer( gid.getData() ) ; + } else { + pr.nl().p( tcomp ) ; + } + pr.out() ; + } + pr.out() ; + + pr.out() ; + } + + public static void dumpObjectKeyTemplate( ObjectKeyTemplate oktemp ) { + pr.nl().p( "ORBVersion = " ).p( oktemp.getORBVersion() ) ; + pr.nl().p( "SubcontractId = " ).p( oktemp.getSubcontractId() ) ; + pr.nl().p( "ServerId = " ).p( oktemp.getServerId() ) ; + pr.nl().p( "ORBId = " ).p( oktemp.getORBId() ) ; + pr.nl().p( "ObjectAdapterId = " ).p( oktemp.getObjectAdapterId() ) ; + } +} diff --git a/src/share/classes/com/sun/corba/ee/tool/OrbPing.java b/src/share/classes/com/sun/corba/ee/tool/OrbPing.java new file mode 100644 index 000000000..dd491d064 --- /dev/null +++ b/src/share/classes/com/sun/corba/ee/tool/OrbPing.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package com.sun.corba.ee.tool; + +import org.glassfish.pfl.basic.tools.argparser.ArgParser; +import org.glassfish.pfl.basic.tools.argparser.DefaultValue; +import org.glassfish.pfl.basic.tools.argparser.Help; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +/** This tool checks to see if an ORB is listening at the given host and port. + * It can print out the round trip time, and do a series of pings, or a single ping. + *

                + * A ping consists of constructing a corbaname URL for the NameService, and + * narrowing the corresponding object reference to the name service. + * + * @author ken + */ +public class OrbPing { + public static class IntervalTimer { + long lastTime ; + + public void start() { + lastTime = System.nanoTime() ; + } + + /** Returns interval since last start() or interval() call in + * microseconds. + * @return Elapsed time in microseconds + */ + public long interval() { + final long current = System.nanoTime() ; + final long diff = current - lastTime ; + start() ; + return diff/1000 ; + } + } + + private interface Args { + @DefaultValue( "1" ) + @Help( "The number of times to repeat the ORB ping") + int count() ; + + @DefaultValue( "localhost" ) + @Help( "The host running the ORB") + String host() ; + + @DefaultValue( "3037") + @Help( "The port on which the ORB listens for clear text requests") + int port() ; + + @DefaultValue( "false" ) + @Help( "Display extra information, including timing information" ) + boolean verbose() ; + } + + private static Args args ; + private static ORB orb ; + private static IntervalTimer timer = new IntervalTimer() ; + + private static void ping( String host, int port ) { + final String url = String.format( "corbaname:iiop:1.2@%s:%d/NameService", + host, port ) ; + + org.omg.CORBA.Object cobject = null ; + try { + timer.start() ; + cobject = orb.string_to_object( url ) ; + } catch (Exception exc) { + msg( "Exception in string_to_object call: %s\n", exc ) ; + } finally { + if (args.verbose()) { + msg( "string_to_object call took %d microseconds\n", + timer.interval() ) ; + } + } + + NamingContext nctx ; + + try { + timer.start() ; + nctx = NamingContextHelper.narrow(cobject); + } catch (Exception exc) { + msg( "Exception in naming narrow call: %s\n", exc ) ; + } finally { + if (args.verbose()) { + msg( "naming narrow call took %d microseconds\n", + timer.interval() ) ; + } + } + } + + private static void msg( String str, Object... args ) { + System.out.printf( str, args ) ; + } + + public static void main( String[] params ) { + args = (new ArgParser( Args.class )).parse( params, Args.class ) ; + + try { + timer.start() ; + orb = ORB.init( params, null ) ; + } catch (Exception exc) { + msg( "Exception in ORB.init: %s\n", exc ) ; + } finally { + if (args.verbose()) { + msg( "ORB.init call took %d microseconds\n", timer.interval() ) ; + } + } + + for (int ctr=0; ctr + + + + + + + + + + + + + + + + + + diff --git a/src/share/classes/com/sun/tools/corba/se/timer/timing.xml b/src/share/classes/com/sun/tools/corba/se/timer/timing.xml new file mode 100644 index 000000000..f55f5d503 --- /dev/null +++ b/src/share/classes/com/sun/tools/corba/se/timer/timing.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/classes/javax/transaction/InvalidTransactionException.java b/src/share/classes/javax/transaction/InvalidTransactionException.java new file mode 100644 index 000000000..4d9d94700 --- /dev/null +++ b/src/share/classes/javax/transaction/InvalidTransactionException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.transaction; + +/** + * This exception indicates that the request carried an invalid transaction + * context. For example, this exception could be raised if an error + * occured when trying to register a resource. + */ +public class InvalidTransactionException extends java.rmi.RemoteException +{ + public InvalidTransactionException() + { + super(); + } + + public InvalidTransactionException(String msg) + { + super(msg); + } +} + diff --git a/src/share/classes/javax/transaction/TransactionRequiredException.java b/src/share/classes/javax/transaction/TransactionRequiredException.java new file mode 100644 index 000000000..6c15c2e64 --- /dev/null +++ b/src/share/classes/javax/transaction/TransactionRequiredException.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.transaction; + +/** + * This exception indicates that a request carried a null transaction context, + * but the target object requires an activate transaction. + */ +public class TransactionRequiredException extends java.rmi.RemoteException +{ + public TransactionRequiredException() + { + super(); + } + + public TransactionRequiredException(String msg) + { + super(msg); + } +} + diff --git a/src/share/classes/javax/transaction/TransactionRolledbackException.java b/src/share/classes/javax/transaction/TransactionRolledbackException.java new file mode 100644 index 000000000..4f685c2ed --- /dev/null +++ b/src/share/classes/javax/transaction/TransactionRolledbackException.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.transaction; + +/** + * This exception indicates that the transaction associated with processing + * of the request has been rolled back, or marked to roll back. Thus the + * requested operation either could not be performed or was not performed + * because further computation on behalf of the transaction would be + * fruitless + */ +public class TransactionRolledbackException extends java.rmi.RemoteException +{ + public TransactionRolledbackException() + { + super(); + } + + public TransactionRolledbackException(String msg) + { + super(msg); + } +} + diff --git a/src/share/classes/javax/transaction/package.html b/src/share/classes/javax/transaction/package.html new file mode 100644 index 000000000..1ba5ffd61 --- /dev/null +++ b/src/share/classes/javax/transaction/package.html @@ -0,0 +1,23 @@ + + + + + + + + +Contains three exceptions thrown by the ORB machinery during unmarshalling. +

                +@since 1.3 + + diff --git a/src/share/classes/org/omg/CORBA/OctetSeqHelper.java b/src/share/classes/org/omg/CORBA/OctetSeqHelper.java new file mode 100644 index 000000000..9dfe4114a --- /dev/null +++ b/src/share/classes/org/omg/CORBA/OctetSeqHelper.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** + * The Helper for OctetSeq. For more information on + * Helper files, see + * "Generated Files: Helper Files".

                + * org/omg/CORBA/OctetSeqHelper.java + * Generated by the IDL-to-Java compiler (portable), version "3.0" + * from streams.idl + * 13 May 1999 22:41:36 o'clock GMT+00:00 + *

                + * The class definition has been modified to conform to the following + * OMG specifications : + *

                  + *
                • ORB core as defined by CORBA 2.3.1 + * (formal/99-10-07) + *
                • + *

                  + *

                • IDL/Java Language Mapping as defined in + * ptc/00-01-08 + *
                • + *
                + */ + +public abstract class OctetSeqHelper { + private static String _id = "IDL:omg.org/CORBA/OctetSeq:1.0"; + + public static void insert(org.omg.CORBA.Any a, byte[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static byte[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_octet); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = org.omg.CORBA.ORB.init().create_alias_tc(org.omg.CORBA.OctetSeqHelper.id(), "OctetSeq", __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static byte[] read(org.omg.CORBA.portable.InputStream istream) { + byte value[] = null; + int _len0 = istream.read_long(); + value = new byte[_len0]; + istream.read_octet_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, byte[] value) { + ostream.write_long(value.length); + ostream.write_octet_array(value, 0, value.length); + } + +} diff --git a/src/share/classes/org/omg/CORBA/OctetSeqHolder.java b/src/share/classes/org/omg/CORBA/OctetSeqHolder.java new file mode 100644 index 000000000..05ead55cc --- /dev/null +++ b/src/share/classes/org/omg/CORBA/OctetSeqHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Holder for OctetSeq. For more information on +* Holder files, see +* "Generated Files: Holder Files".

                +* org/omg/CORBA/OctetSeqHolder.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from streams.idl +* 13 May 1999 22:41:36 o'clock GMT+00:00 +*/ + +public final class OctetSeqHolder implements org.omg.CORBA.portable.Streamable +{ + public byte value[] = null; + + public OctetSeqHolder () + { + } + + public OctetSeqHolder (byte[] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.omg.CORBA.OctetSeqHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.omg.CORBA.OctetSeqHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.omg.CORBA.OctetSeqHelper.type (); + } + +} diff --git a/src/share/classes/org/omg/CORBA/PolicyError.java b/src/share/classes/org/omg/CORBA/PolicyError.java new file mode 100644 index 000000000..98b62047f --- /dev/null +++ b/src/share/classes/org/omg/CORBA/PolicyError.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + +/** +* A user exception thrown when a policy error occurs. A PolicyError +* exception may include one of the following policy error reason codes +* defined in the org.omg.CORBA package: BAD_POLICY, BAD_POLICY_TYPE, +* BAD_POLICY_VALUE, UNSUPPORTED_POLICY, UNSUPPORTED_POLICY_VALUE. +*/ + +// @SuppressWarnings({"serial"}) +public final class PolicyError extends org.omg.CORBA.UserException { + + /** + * The reason for the PolicyError exception being thrown. + * @serial + */ + public short reason; + + /** + * Constructs a default PolicyError user exception + * with no reason code and an empty reason detail message. + */ + public PolicyError() { + super(); + } + + /** + * Constructs a PolicyError user exception + * initialized with the given reason code and an empty reason detail message. + * @param __reason the reason code. + */ + public PolicyError(short __reason) { + super(); + reason = __reason; + } + + /** + * Constructs a PolicyError user exception + * initialized with the given reason detail message and reason code. + * @param reason_string the reason detail message. + * @param __reason the reason code. + */ + public PolicyError(String reason_string, short __reason) { + super(reason_string); + reason = __reason; + } +} diff --git a/src/share/classes/org/omg/CORBA/RepositoryIdHelper.java b/src/share/classes/org/omg/CORBA/RepositoryIdHelper.java new file mode 100644 index 000000000..9184fa9d7 --- /dev/null +++ b/src/share/classes/org/omg/CORBA/RepositoryIdHelper.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CORBA; + + +/** +* The Helper for RepositoryId. For more information on +* Helper files, see +* "Generated Files: Helper Files".

                + +* org/omg/CORBA/RepositoryIdHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from ir.idl +* 03 June 1999 11:33:43 o'clock GMT+00:00 +*/ + +abstract public class RepositoryIdHelper +{ + private static String _id = "IDL:omg.org/CORBA/RepositoryId:1.0"; + + public static void insert (org.omg.CORBA.Any a, String that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.omg.CORBA.RepositoryIdHelper.id (), "RepositoryId", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String read (org.omg.CORBA.portable.InputStream istream) + { + String value = null; + value = istream.read_string (); + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String value) + { + ostream.write_string (value); + } + +} diff --git a/src/share/classes/org/omg/CosNaming/_BindingIteratorImplBase.java b/src/share/classes/org/omg/CosNaming/_BindingIteratorImplBase.java new file mode 100644 index 000000000..69229fbf8 --- /dev/null +++ b/src/share/classes/org/omg/CosNaming/_BindingIteratorImplBase.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CosNaming/_BindingIteratorImplBase.java + * From: nameservice.idl + * Date: Tue Aug 11 03:12:09 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + * @deprecated Deprecated in JDK 1.4. + */ + +package org.omg.CosNaming; + +@SuppressWarnings({"deprecation"}) +public abstract class _BindingIteratorImplBase + extends org.omg.CORBA.DynamicImplementation + implements org.omg.CosNaming.BindingIterator { + + // Constructor + public _BindingIteratorImplBase() { + super(); + } + + // Type strings for this class and its superclases + private static final String _type_ids[] = { + "IDL:omg.org/CosNaming/BindingIterator:1.0" + }; + + public String[] _ids() { return (String[]) _type_ids.clone(); } + + private static java.util.Dictionary _methods = new java.util.Hashtable(); + static { + _methods.put("next_one", new java.lang.Integer(0)); + _methods.put("next_n", new java.lang.Integer(1)); + _methods.put("destroy", new java.lang.Integer(2)); + } + // DSI Dispatch call + public void invoke(org.omg.CORBA.ServerRequest r) { + switch (((java.lang.Integer) _methods.get(r.op_name())).intValue()) { + case 0: // org.omg.CosNaming.BindingIterator.next_one + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _b = _orb().create_any(); + _b.type(org.omg.CosNaming.BindingHelper.type()); + _list.add_value("b", _b, org.omg.CORBA.ARG_OUT.value); + r.params(_list); + org.omg.CosNaming.BindingHolder b; + b = new org.omg.CosNaming.BindingHolder(); + boolean ___result; + ___result = this.next_one(b); + org.omg.CosNaming.BindingHelper.insert(_b, b.value); + org.omg.CORBA.Any __result = _orb().create_any(); + __result.insert_boolean(___result); + r.result(__result); + } + break; + case 1: // org.omg.CosNaming.BindingIterator.next_n + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _how_many = _orb().create_any(); + _how_many.type(org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ulong)); + _list.add_value("how_many", _how_many, org.omg.CORBA.ARG_IN.value); + org.omg.CORBA.Any _bl = _orb().create_any(); + _bl.type(org.omg.CosNaming.BindingListHelper.type()); + _list.add_value("bl", _bl, org.omg.CORBA.ARG_OUT.value); + r.params(_list); + int how_many; + how_many = _how_many.extract_ulong(); + org.omg.CosNaming.BindingListHolder bl; + bl = new org.omg.CosNaming.BindingListHolder(); + boolean ___result; + ___result = this.next_n(how_many, bl); + org.omg.CosNaming.BindingListHelper.insert(_bl, bl.value); + org.omg.CORBA.Any __result = _orb().create_any(); + __result.insert_boolean(___result); + r.result(__result); + } + break; + case 2: // org.omg.CosNaming.BindingIterator.destroy + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + r.params(_list); + this.destroy(); + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + } +} diff --git a/src/share/classes/org/omg/CosNaming/_NamingContextImplBase.java b/src/share/classes/org/omg/CosNaming/_NamingContextImplBase.java new file mode 100644 index 000000000..25ba64c81 --- /dev/null +++ b/src/share/classes/org/omg/CosNaming/_NamingContextImplBase.java @@ -0,0 +1,399 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * File: ./org/omg/CosNaming/_NamingContextImplBase.java + * From: nameservice.idl + * Date: Tue Aug 11 03:12:09 1998 + * By: idltojava Java IDL 1.2 Aug 11 1998 02:00:18 + * @deprecated Deprecated in JDK 1.4. + */ + +package org.omg.CosNaming; + +@SuppressWarnings({"deprecation"}) +public abstract class _NamingContextImplBase + extends org.omg.CORBA.DynamicImplementation + implements org.omg.CosNaming.NamingContext { + + // Constructor + public _NamingContextImplBase() { + super(); + } + + // Type strings for this class and its superclases + private static final String _type_ids[] = { + "IDL:omg.org/CosNaming/NamingContext:1.0" + }; + + public String[] _ids() { return (String[]) _type_ids.clone(); } + + private static java.util.Dictionary _methods = new java.util.Hashtable(); + static { + _methods.put("bind", new java.lang.Integer(0)); + _methods.put("bind_context", new java.lang.Integer(1)); + _methods.put("rebind", new java.lang.Integer(2)); + _methods.put("rebind_context", new java.lang.Integer(3)); + _methods.put("resolve", new java.lang.Integer(4)); + _methods.put("unbind", new java.lang.Integer(5)); + _methods.put("list", new java.lang.Integer(6)); + _methods.put("new_context", new java.lang.Integer(7)); + _methods.put("bind_new_context", new java.lang.Integer(8)); + _methods.put("destroy", new java.lang.Integer(9)); + } + // DSI Dispatch call + public void invoke(org.omg.CORBA.ServerRequest r) { + switch (((java.lang.Integer) _methods.get(r.op_name())).intValue()) { + case 0: // org.omg.CosNaming.NamingContext.bind + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + org.omg.CORBA.Any _obj = _orb().create_any(); + _obj.type(org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_objref)); + _list.add_value("obj", _obj, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + org.omg.CORBA.Object obj; + obj = _obj.extract_Object(); + try { + this.bind(n, obj); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e2); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound e3) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.insert(_except, e3); + r.except(_except); + return; + } + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + case 1: // org.omg.CosNaming.NamingContext.bind_context + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + org.omg.CORBA.Any _nc = _orb().create_any(); + _nc.type(org.omg.CosNaming.NamingContextHelper.type()); + _list.add_value("nc", _nc, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + org.omg.CosNaming.NamingContext nc; + nc = org.omg.CosNaming.NamingContextHelper.extract(_nc); + try { + this.bind_context(n, nc); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e2); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound e3) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.insert(_except, e3); + r.except(_except); + return; + } + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + case 2: // org.omg.CosNaming.NamingContext.rebind + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + org.omg.CORBA.Any _obj = _orb().create_any(); + _obj.type(org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_objref)); + _list.add_value("obj", _obj, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + org.omg.CORBA.Object obj; + obj = _obj.extract_Object(); + try { + this.rebind(n, obj); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e2); + r.except(_except); + return; + } + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + case 3: // org.omg.CosNaming.NamingContext.rebind_context + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + org.omg.CORBA.Any _nc = _orb().create_any(); + _nc.type(org.omg.CosNaming.NamingContextHelper.type()); + _list.add_value("nc", _nc, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + org.omg.CosNaming.NamingContext nc; + nc = org.omg.CosNaming.NamingContextHelper.extract(_nc); + try { + this.rebind_context(n, nc); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e2); + r.except(_except); + return; + } + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + case 4: // org.omg.CosNaming.NamingContext.resolve + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + org.omg.CORBA.Object ___result; + try { + ___result = this.resolve(n); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e2); + r.except(_except); + return; + } + org.omg.CORBA.Any __result = _orb().create_any(); + __result.insert_Object(___result); + r.result(__result); + } + break; + case 5: // org.omg.CosNaming.NamingContext.unbind + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + try { + this.unbind(n); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e2); + r.except(_except); + return; + } + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + case 6: // org.omg.CosNaming.NamingContext.list + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _how_many = _orb().create_any(); + _how_many.type(org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ulong)); + _list.add_value("how_many", _how_many, org.omg.CORBA.ARG_IN.value); + org.omg.CORBA.Any _bl = _orb().create_any(); + _bl.type(org.omg.CosNaming.BindingListHelper.type()); + _list.add_value("bl", _bl, org.omg.CORBA.ARG_OUT.value); + org.omg.CORBA.Any _bi = _orb().create_any(); + _bi.type(org.omg.CosNaming.BindingIteratorHelper.type()); + _list.add_value("bi", _bi, org.omg.CORBA.ARG_OUT.value); + r.params(_list); + int how_many; + how_many = _how_many.extract_ulong(); + org.omg.CosNaming.BindingListHolder bl; + bl = new org.omg.CosNaming.BindingListHolder(); + org.omg.CosNaming.BindingIteratorHolder bi; + bi = new org.omg.CosNaming.BindingIteratorHolder(); + this.list(how_many, bl, bi); + org.omg.CosNaming.BindingListHelper.insert(_bl, bl.value); + org.omg.CosNaming.BindingIteratorHelper.insert(_bi, bi.value); + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + case 7: // org.omg.CosNaming.NamingContext.new_context + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + r.params(_list); + org.omg.CosNaming.NamingContext ___result; + ___result = this.new_context(); + org.omg.CORBA.Any __result = _orb().create_any(); + org.omg.CosNaming.NamingContextHelper.insert(__result, ___result); + r.result(__result); + } + break; + case 8: // org.omg.CosNaming.NamingContext.bind_new_context + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + org.omg.CORBA.Any _n = _orb().create_any(); + _n.type(org.omg.CosNaming.NameHelper.type()); + _list.add_value("n", _n, org.omg.CORBA.ARG_IN.value); + r.params(_list); + org.omg.CosNaming.NameComponent[] n; + n = org.omg.CosNaming.NameHelper.extract(_n); + org.omg.CosNaming.NamingContext ___result; + try { + ___result = this.bind_new_context(n); + } + catch (org.omg.CosNaming.NamingContextPackage.NotFound e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotFoundHelper.insert(_except, e0); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound e1) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.insert(_except, e1); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e2) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.insert(_except, e2); + r.except(_except); + return; + } + catch (org.omg.CosNaming.NamingContextPackage.InvalidName e3) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.insert(_except, e3); + r.except(_except); + return; + } + org.omg.CORBA.Any __result = _orb().create_any(); + org.omg.CosNaming.NamingContextHelper.insert(__result, ___result); + r.result(__result); + } + break; + case 9: // org.omg.CosNaming.NamingContext.destroy + { + org.omg.CORBA.NVList _list = _orb().create_list(0); + r.params(_list); + try { + this.destroy(); + } + catch (org.omg.CosNaming.NamingContextPackage.NotEmpty e0) { + org.omg.CORBA.Any _except = _orb().create_any(); + org.omg.CosNaming.NamingContextPackage.NotEmptyHelper.insert(_except, e0); + r.except(_except); + return; + } + org.omg.CORBA.Any __return = _orb().create_any(); + __return.type(_orb().get_primitive_tc(org.omg.CORBA.TCKind.tk_void)); + r.result(__return); + } + break; + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + } +} diff --git a/src/share/classes/org/omg/CosNaming/package.html b/src/share/classes/org/omg/CosNaming/package.html new file mode 100644 index 000000000..d55799dd3 --- /dev/null +++ b/src/share/classes/org/omg/CosNaming/package.html @@ -0,0 +1,332 @@ + + + + + + + + + Provides the naming service for Java IDL. +

                + The package and all its classes and interfaces + were generated by running the tool idltojava on the file + nameservice.idl, which is a module written in OMG IDL. +

                +

                Interfaces

                + The package org.omg.CosNaming contains two public interfaces + and several auxiliary classes. +

                + The interfaces are: +

                  +
                • NamingContext +
                • BindingIterator +
                +

                + These two interfaces provide the means to bind/unbind names and object + references, to retrieve bound object references, and + to iterate through a list of bindings. The NamingContext + interface supplies the main functionality for the naming service, and + BindingIterator provides a means of iterating through a list + of name/object reference bindings. +

                +

                Auxiliary Classes

                + In order to map an OMG IDL interface to the Java programming language, + the idltojava compiler creates Java classes that can be thought of + as auxiliary classes. + Comments for the generated auxiliary classes + used by the interfaces NamingContext and + BindingIterator are included here. +

                +

                Classes Used by NamingContext and + BindingIterator

                + The following are classes used by + the naming service. (Helper and holder classes, which are + generated for each of the classes listed here, are discussed below.) + +
                  +
                • public final class NameComponent -- + a building block for names. (Names are bound to object references + in a naming context.) +

                  A name is an array of one or more NameComponent objects. + A name with a single NameComponent is called + a simple name; a name with multiple NameComponent + objects is called a compound name. +

                  + A NameComponent object consists of two fields: +

                    +
                  1. id -- a String used as an identifier +
                  2. kind -- a String that can be used for any + descriptive purpose. Its importance is that it + can be used to describe an object without affecting syntax. + The C programming language, for example, uses the the syntactic convention + of appending the extension ".c" to a file name to indicate that it is + a source code file. In a NameComponent object, + the kind field can be used to describe the type of object + rather than a file extension or some other syntactic convention. + Examples of the value of the kind field include the strings + "c_source", "object_code", + "executable", + "postscript", and "". It is not unusual + for the kind field to be the empty string. +
                  +

                  + In a name, each NameComponent object except the last denotes + a NamingContext object; the last NameComponent + object denotes the bound object reference. + This is similar to a path name, in which the last name is the + file name, and all names before it are directory names.

                  +

                  + +

                • public final class Binding -- + an object that associates a name with an object reference or a + naming context. + A Binding object has two fields: +
                    +
                  1. binding_name - an array of one or more + NameComponent objects that represents the bound name +
                  2. binding_type - a BindingType object + indicating whether the binding is between a name and an object + reference or between a name and a naming context +
                  +

                  + The interface NamingContext has methods for + binding/unbinding names with object references or naming contexts, + for listing bindings, + and for resolving bindings (given a name, the method + resolve returns the object reference bound to it). + +

                  +

                • public final class BindingType -- + an object that specifies whether the given Binding + object is a binding between a name and an object reference (that is, + not a naming context) or between a name and a naming context. +

                  + The classBindingType consists of two methods and + four constants. Two of these constants are + BindingType objects, and two are ints. +

                  + The BindingType objects + can be passed to the constructor for the class + Binding or used as parameters or return values. These + BindingType objects are: +

                    +
                  • public static final BindingType nobject -- + to indicate that the binding is with an object reference +
                  • public static final BindingType ncontext -- + to indicate that the binding is with a naming context +
                  +

                  + The int constants can be supplied to the method + from_int to create BindingType objects, + or they can be return values for the method value. + These constants are: +

                    +
                  • public static final int _nobject +
                  • public static final int _ncontext +
                  + If the method from_int is supplied with anything other + than _nobject + or _ncontext, it will throw + the exception org.omg.CORBA.BAD_PARAM. +

                  Usage is as follows: +

                  +       BindingType btObject = from_int(_nobject);
                  +       BindingType btContext = from_int(_ncontext);
                  +    
                  + The variable btObject refers to a BindingType + object initialized to represent a binding with an object reference. + The variable btContext refers to a BindingType + object initialized to represent a binding with a + NamingContex object. +

                  + The method value returns either + _nobject or _ncontext, so + in the following line of code, the variable bt + will contain _nobject or _ncontext: +

                  +       int bt = BindingType.value();
                  +    
                  +
                + +

                Holder Classes

                + + OMG IDL uses OUT and INOUT parameters for returning values from operations. + The mapping to the Java programming language, which does not have OUT + and INOUT parameters, creates a special class for each type, called + a holder class. + An instance of a holder class can be passed to a + Java method as a parameter, and + a value can be assigned to its value field. This allows + it to perform the function of an OUT or INOUT parameter. +

                The following holder classes are generated for the package + org.omg.CosNaming: +

                  +
                • NamingContextHolder +
                • BindingIteratorHolder +
                • BindingHolder +
                • BindingListHolder +
                • BindingTypeHolder +
                • NameComponentHolder +
                • NameHolder +
                +

                + Note that in the org.omg.CORBA package, + there is a holder class for each of the basic Java types: + IntHolder, ShortHolder, + StringHolder, and so on. +

                + Note also that there is a NameHolder class even though + there is no Name class; similarly, there is a + BindingListHolder class even though there is no + BindingList class. This is true because in the OMG IDL + interface, Name and BindingList are + typedefs. There is no mapping from an IDL + typedef to a Java construct, but holder classes + are generated if the typedef is for a sequence or + an array. As mapped to the + Java programming language, Name is an array of + NameComponent objects, and a BindingList + is an array of Binding objects. + + All holder classes have at least two constructors and one field: +

                  +
                • value field -- an instance of the type being used as + an OUT or INOUT parameter. For example, the value field of a + NamingContextHolder will be a NamingContext + object. +
                • default constructor -- a constructor that creates a new holder object + initialized with the default value for the type. For example, a new + BindingHolder object created with the default constructor + will have its value field set to null because + that is the default value for an object. Other defaults are + false for boolean, + 0 for numeric and char types, and + null for object references. +
                • constructor from an instance -- a constructor that creates a new + holder object whose value field is + initialized with the instance supplied +
                +

                + A holder class for a user-defined type (a Java class) has three more + methods, but application developers do not use them directly. + +

                Helper Classes

                + Helper classes, which are generated for all user-defined types + in an OMG IDL interface, supply static methods needed to manipulate + those types. +

                + There is only one method in a helper class that an + application programmer uses: the + method narrow. Only Java interfaces mapped from IDL + interfaces will have a helper class that includes a narrow + method, so in the CosNaming package, only the classes + NamingContextHelper and BindingIteratorHelper + have a narrow method. +

                  +
                • public static NamingContext + narrow(org.omg.CORBA.Object obj) -- converts the given + CORBA object to a NamingContext object +
                • public static BindingIterator + narrow(org.omg.CORBA.Object obj) -- converts the given + CORBA object to a BindingIterator object +
                +

                Package org.omg.CosNaming.NamingContextPackage

                +This package supplies Helper and Holder classes for the exceptions used +in the package org.omg.CosNaming and also for the class +NotFoundReason, which supplies a reason for the exception +NotFound. +

                +There are Helper and Holder classes for the following exceptions: +

                  +
                • AlreadyBound +
                • CannotProceed +
                • InvalidName +
                • NotEmpty +
                • NotFound +
                + +

                Naming Service Compatibility

                + +Sun's implementation of the CosNaming package complies +with the OMG COSNaming specification. In other words, +the APIs in Sun's naming service are implemented according to the +guidelines for a naming service provided by OMG. Therefore, if a +third-party vendor has implemented a naming service that is OMG +compliant, it is possible to switch between Sun's implementation of +CosNaming and the third-party vendor's implementation. +However, it is important to understand that there can be minor +variations in the way different vendors implement the naming service, +such as differences in the exception strings. + +

                Instructions for Using a Third Party's Naming Service

                +Although we encourage using an ORB and ORB services that are both +from one vendor, it is possible to plug in a third party's +COSNaming implementation with Sun's RMI-IIOP ORB. +Here are the steps to follow: +
                  +
                1. Create a properties file for the Bootstrap server and give it + two entries. For example, you could call this properties file + /tmp/services and put the following in it: + NameService, <Stringified IOR of the Root Naming Context>. +

                  + This associates NameService with the Root Naming + Context of the CosNaming implementation that you + want to use. +

                  +

                2. Start the standalone Bootstrap server using the following command: +
                  +      
                  +      java -classpath $(CLASSPATH)
                  +      com.sun.corba.ee.internal.CosNaming.BootstrapServer -InitialServicesFile
                  +      "/tmp/services" [-ORBInitialPort port]
                  +      
                  +  
                  +

                  + Note that the square brackets at the end of the command indicate that + specifying a port number is optional. +

                +

                +Now when an application calls the method +org.omg.CORBA.ORB.resolve_initial_references, CORBA +processes will contact the Bootstrap Server to get the Root Naming +Context. + +

                Package Specification

                + + + +

                Related Documentation

                + +For an overview and examples of how to use the +CosNaming API, please see: + +

                +For an overview of Java IDL, please see: +

                + +@since JDK1.3 +@serial exclude + + + diff --git a/src/share/classes/org/omg/CosTSPortability/CosTSPortability.idl b/src/share/classes/org/omg/CosTSPortability/CosTSPortability.idl new file mode 100644 index 000000000..69c66e80a --- /dev/null +++ b/src/share/classes/org/omg/CosTSPortability/CosTSPortability.idl @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// PIDL for CosTSPortability Module, p 10-74 +// CORBAservices, Transaction Service V1.1 +// NOTE: This should not be sent thru the idltojava compiler since +// it is a pseudo-object. + +#include "CORBA.idl" +#include "CosTransactions.idl" + +#pragma prefix "omg.org" +#pragma javaPackage "org.omg" + +module CosTSPortability { // PIDL + typedef long ReqId; + + interface Sender { + void sending_request(in ReqId id, + out CosTransactions::PropagationContext ctx); + void received_reply(in ReqId id, + in CosTransactions::PropagationContext ctx, + in CORBA::Environment env) raises (WrongTransaction); + }; + + interface Receiver { + void received_request(in ReqId id, + in CosTransactions::PropagationContext ctx); + void sending_reply(in ReqId id, + out CosTransactions::PropagationContext ctx); + }; +}; + diff --git a/src/share/classes/org/omg/CosTransactions/CORBAX.idl b/src/share/classes/org/omg/CosTransactions/CORBAX.idl new file mode 100644 index 000000000..08fbaa36d --- /dev/null +++ b/src/share/classes/org/omg/CosTransactions/CORBAX.idl @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "CosTSPortability.idl" + +// PIDL for TSIdentification interface to be implemented by ORB +// NOTE: This should not be sent thru the idltojava compiler since +// it is a pseudo-object. + +#pragma prefix "omg.org" +#pragma javaPackage org.omg + +module CORBA { +interface TSIdentification { // PIDL + exception NotAvailable{}; + exception AlreadyIdentified{}; + void identify_sender(in CosTSPortability::Sender sender) + raises (NotAvailable, AlreadyIdentified); + void identify_receiver(in CosTSPortability::Receiver receiver) + raises (NotAvailable, AlreadyIdentified); +}; +}; diff --git a/src/share/classes/org/omg/CosTransactions/CurrentHelper.java b/src/share/classes/org/omg/CosTransactions/CurrentHelper.java new file mode 100644 index 000000000..4bdf465ef --- /dev/null +++ b/src/share/classes/org/omg/CosTransactions/CurrentHelper.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CosTransactions; + +public class CurrentHelper { + // It is useless to have instances of this class + private CurrentHelper() { } + + public static void write(org.omg.CORBA.portable.OutputStream out, org.omg.CosTransactions.Current that) { + throw new org.omg.CORBA.MARSHAL("Current cannot be marshaled"); + } + public static org.omg.CosTransactions.Current read(org.omg.CORBA.portable.InputStream in) { + throw new org.omg.CORBA.MARSHAL("Current cannot be unmarshaled"); + } + public static org.omg.CosTransactions.Current extract(org.omg.CORBA.Any a) { + org.omg.CORBA.portable.InputStream in = a.create_input_stream(); + return read(in); + } + public static void insert(org.omg.CORBA.Any a, org.omg.CosTransactions.Current that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + private static org.omg.CORBA.TypeCode _tc; + synchronized public static org.omg.CORBA.TypeCode type() { + if (_tc == null) + _tc = org.omg.CORBA.ORB.init().create_interface_tc(id(), "Current"); + return _tc; + } + public static String id() { + return "IDL:omg.org/CosTransactions/Current:1.0"; + } + public static org.omg.CosTransactions.Current narrow(org.omg.CORBA.Object that) + throws org.omg.CORBA.BAD_PARAM { + if (that == null) + return null; + if (that instanceof org.omg.CosTransactions.Current) + return (org.omg.CosTransactions.Current) that; + else + throw new org.omg.CORBA.BAD_PARAM(); + } +} diff --git a/src/share/classes/org/omg/CosTransactions/CurrentHolder.java b/src/share/classes/org/omg/CosTransactions/CurrentHolder.java new file mode 100644 index 000000000..a833cac7c --- /dev/null +++ b/src/share/classes/org/omg/CosTransactions/CurrentHolder.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.CosTransactions; + +/** CurrentHolder is the holder for Current objects. + * Current is a pseudo object, hence it will never be transmitted + * over the wire. + */ +public final class CurrentHolder implements org.omg.CORBA.portable.Streamable +{ + // instance variable + public org.omg.CosTransactions.Current value; + // constructors + public CurrentHolder() { + this(null); + } + public CurrentHolder(org.omg.CosTransactions.Current __arg) { + value = __arg; + } + + public void _write(org.omg.CORBA.portable.OutputStream out) { + org.omg.CosTransactions.CurrentHelper.write(out, value); + } + + public void _read(org.omg.CORBA.portable.InputStream in) { + value = org.omg.CosTransactions.CurrentHelper.read(in); + } + + public org.omg.CORBA.TypeCode _type() { + return org.omg.CosTransactions.CurrentHelper.type(); + } +} diff --git a/src/share/classes/org/omg/DynamicAny/DynAnyFactoryPackage/package.html b/src/share/classes/org/omg/DynamicAny/DynAnyFactoryPackage/package.html new file mode 100644 index 000000000..45c589ae4 --- /dev/null +++ b/src/share/classes/org/omg/DynamicAny/DynAnyFactoryPackage/package.html @@ -0,0 +1,40 @@ + + + + + + + +

                + +This package contains classes and exceptions from the DynAnyFactory +interface of the +DynamicAny module +specified in the OMG The Common Object Request Broker: Architecture and +Specification, + +http://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 9.2.2. Please +refer to that OMG specification for further details. + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/DynamicAny/DynAnyPackage/package.html b/src/share/classes/org/omg/DynamicAny/DynAnyPackage/package.html new file mode 100644 index 000000000..e5576691a --- /dev/null +++ b/src/share/classes/org/omg/DynamicAny/DynAnyPackage/package.html @@ -0,0 +1,39 @@ + + + + + + + +

                This package contains classes and exceptions from the DynAny + interface of the DynamicAny module +specified in the OMG The Common Object Request Broker: Architecture and +Specification, + +http://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 9.2. Please +refer to that OMG specification for further details. + + + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/DynamicAny/package.html b/src/share/classes/org/omg/DynamicAny/package.html new file mode 100644 index 000000000..2f28fe843 --- /dev/null +++ b/src/share/classes/org/omg/DynamicAny/package.html @@ -0,0 +1,205 @@ + + + + + + + +

                Provides classes and interfaces that enable traversal of the data value + associated with an any at +runtime, and extraction of the primitive constituents of the data value. + + +

                An any can be passed to a program that doesn't have any static information +for the type of the any (code generated for the type by an IDL compiler has not +been compiled with the object implementation). As a result, the object receiving the +any does not have a portable method of using it. + +

                DynAnys enable traversal of the data value associated with an +any at runtime, and extraction of the primitive constituents of the data value. +This is especially helpful for writing powerful generic servers (bridges, event channels +supporting filtering). Similarly, this facility enables the construction of an +any at runtime, without having static knowledge of its type. This is especially +helpful for writing generic clients (bridges, browsers, debuggers, user interface tools). + +

                Any values can be dynamically interpreted (traversed) and constructed through +DynAny objects. A DynAny object is associated with a data +value which corresponds to a copy of the value inserted into an Any. A +DynAny object may be viewed as an ordered collection of component +DynAnys. For DynAnys representing a basic type, such as long, +or a type without components, such as an empty exception, the ordered collection of +components is empty. + +

                Each DynAny object maintains the notion of a current position into its collection +of component DynAnys. The current position is identified by an index value that runs +from 0 to n-1, where n is the number of components. The special index value -1 +indicates a current position that points nowhere. + For values that cannot have a current position (such as an empty exception), + the index value is fixed at -1. + If a DynAny is initialized with a value that has components, the index is +initialized to 0. + After creation of an uninitialized DynAny (that is, a DynAny that +has no value but a TypeCode + that permits components), the current position depends on the type of value represented by + the DynAny. (The current position is set to 0 or -1, depending on whether the +new DynAny + gets default values for its components.) + + +

                The iteration operations rewind, seek, and next +can be used to change the current position + and the current_component operation returns the component at the current +position. + The component_count operation returns the number of components of a +DynAny. + Collectively, these operations enable iteration over the components of a +DynAny, for example, + to (recursively) examine its contents. + + +

                A constructed DynAny object is a DynAny object associated with +a constructed type. + There is a different interface, inheriting from the DynAny interface, +associated with + each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, + exception, and value type). A constructed DynAny object exports operations +that enable the creation of new DynAny objects, + each of them associated with a component of the constructed data value. + As an example, a DynStruct is associated with a struct value. This +means that the DynStruct + may be seen as owning an ordered collection of components, one for each structure member. + The DynStruct object exports operations that enable the creation of new +DynAny objects, + each of them associated with a member of the struct. + + +

                If a DynAny object has been obtained from another (constructed) +DynAny object, + such as a DynAny representing a structure member that was created from a +DynStruct, + the member DynAny is logically contained in the DynStruct. + Calling an insert or get operation leaves the current position +unchanged. + Destroying a top-level DynAny object (one that was not obtained as a component +of another DynAny) + also destroys any component DynAny objects obtained from it. + Destroying a non-top level DynAny object does nothing. + Invoking operations on a destroyed top-level DynAny or any of its descendants +raises OBJECT_NOT_EXIST. + If the programmer wants to destroy a DynAny object but still wants to +manipulate some component + of the data value associated with it, then he or she should first create a +DynAny for the component + and, after that, make a copy of the created DynAny object. + + +

                The behavior of DynAny objects has been defined in order to enable efficient +implementations + in terms of allocated memory space and speed of access. DynAny objects are +intended to be used + for traversing values extracted from anys or constructing values of +anys at runtime. + Their use for other purposes is not recommended. + + + +

                Handling DynAny objects

                + +

                Insert and get operations are necessary to handle basic +DynAny objects + but are also helpful to handle constructed DynAny objects. + Inserting a basic data type value into a constructed DynAny object + implies initializing the current component of the constructed data value + associated with the DynAny object. For example, invoking +insert_boolean on a + DynStruct implies inserting a boolean data value at the current +position + of the associated struct data value. + A type is consistent for inserting or extracting a value if its TypeCode is +equivalent to + the TypeCode contained in the DynAny or, if the +DynAny has components, is equivalent to the TypeCode + of the DynAny at the current position. + +

                Basic operations include: +

                +

                  +
                • insert_boolean, get_boolean +
                • insert_char, get_char +
                • insert_short, get_short +
                • insert_ushort, get_ushort +
                • insert_long, get_long +
                • insert_ulong, get_ulong +
                • insert_double, get_double +
                • insert_string, get_string +
                • insert_reference, get_reference +
                • insert_typecode, get_typecode +
                • insert_longlong, get_longlong +
                • insert_ulonglong, get_ulonglong +
                • insert_longdouble, get_longdouble +
                • insert_wchar, get_wchar +
                • insert_wstring, get_wstring +
                • insert_any, get_any +
                • insert_dyn_any, get_dyn_any +
                • insert_val, get_val +
                • insert_octet, get_octet +
                • insert_float, get_float +
                • get_value +
                • get_as_string +
                • get_as_ulong +
                • get_members +
                • get_members_as_dyn_any +
                • get_discriminator +
                • get_length +
                • get_elements +
                • get_elements_as_dyn_any +
                • get_boxed_value +
                • get_boxed_value_as_dyn_any +
                + + +

                DynAny and DynAnyFactory objects are intended to be local to +the process in which they are + created and used. This means that references to DynAny and +DynAnyFactory objects cannot be exported + to other processes, or externalized with ORB.object_to_string(). + If any attempt is made to do so, the offending operation will raise a MARSHAL system +exception. + Since their interfaces are specified in IDL, DynAny objects export operations +defined in the standard + org.omg.CORBA.Object interface. However, any attempt to invoke operations +exported through the Object + interface may raise the standard NO_IMPLEMENT exception. + An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT +exception. + + + + + + +

                + + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableInterceptor/ORBInitInfoPackage/package.html b/src/share/classes/org/omg/PortableInterceptor/ORBInitInfoPackage/package.html new file mode 100644 index 000000000..e81da57ee --- /dev/null +++ b/src/share/classes/org/omg/PortableInterceptor/ORBInitInfoPackage/package.html @@ -0,0 +1,37 @@ + + + + + + + +

                This package contains the exceptions and typedefs from the ORBInitInfo +local interface of the PortableInterceptor module specified in the OMG +Portable Interceptor specification, + +http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06, section 21.7.2. Please +refer to that OMG specification for further details. + + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableInterceptor/package.html b/src/share/classes/org/omg/PortableInterceptor/package.html new file mode 100644 index 000000000..faa32fcb6 --- /dev/null +++ b/src/share/classes/org/omg/PortableInterceptor/package.html @@ -0,0 +1,90 @@ + + + + + + + + +Provides a mechanism to register ORB hooks through which ORB services +can intercept the normal flow of execution of the ORB. + +

                Interceptor Types

                +There are currently three types of interceptors that can be registered: +
                  +
                • {@link org.omg.PortableInterceptor.IORInterceptor IORInterceptor} - + Used to establish tagged components in the profiles within an IOR.
                • +
                • {@link org.omg.PortableInterceptor.ClientRequestInterceptor +ClientRequestInterceptor} - + Intercepts the flow of a request/reply sequence through the ORB on + the client side.
                • +
                • {@link org.omg.PortableInterceptor.ServerRequestInterceptor +ServerRequestInterceptor} - + Intercepts the flow of a request/reply sequence through the ORB on + the server side.
                • +
                +See the javadocs for class +{@link org.omg.PortableInterceptor.ORBInitializer ORBInitializer} +for how to go about registering interceptors. + + +

                Known limitations / unimplemented methods in package +org.omg.PortableInterceptor

                + + +
                  +
                • + RequestInfo +
                    +
                  • sync_scope(): Always returns SYNC_WITH_TRANSPORT
                  • +
                  • arguments(): Only supported for DII/DSI calls
                  • +
                  • exceptions(): Only supported for DII calls on client side. + Not supported on server-side.
                  • +
                  • contexts(): Only supported for DII calls on client side. + Not supported on server-side since our ORB does not send contexts. +
                  • +
                  • operation_context(): Only supported for DII calls + on client side. Not supported on server-side since ORB + does not send contexts.
                  • +
                  • result(): Only supported for DII/DSI calls
                  • +
                  +
                • +
                • + ClientRequestInfo +
                    +
                  • received_exception_id(): Always returns null in the + DII case
                  • +
                  • get_request_policy(int type): Not implemented.
                  • +
                  +
                • +
                • + ServerRequestInfo +
                    +
                  • sending_exception(): Does not support user exceptions on + the server side in non-DSI case.
                  • +
                  +
                • +
                +
                + +

                Package Specification

                +

                For a precise list of supported sections of official OMG specifications with which +the Java[tm] Platform, Standard Edition 6, complies, see Official Specifications for CORBA +support in Java[tm] SE 6. + +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableServer/CurrentHelper.java b/src/share/classes/org/omg/PortableServer/CurrentHelper.java new file mode 100644 index 000000000..51c629f21 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/CurrentHelper.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + + +/** +* org/omg/PortableServer/CurrentHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.1" +* from ../../../../src/share/classes/org/omg/PortableServer/poa.idl +* Tuesday, October 23, 2001 1:17:01 PM PDT +*/ + + +/** + * The PortableServer::Current interface, derived from + * CORBA::Current, provides method implementations with + * access to the identity of the object on which the + * method was invoked. The Current interface is provided + * to support servants that implement multiple objects, + * but can be used within the context of POA-dispatched + * method invocations on any servant. To provide location + * transparency, ORBs are required to support use of + * Current in the context of both locally and remotely + * invoked operations. An instance of Current can be + * obtained by the application by issuing the + * CORBA::ORB::resolve_initial_references("POACurrent") + * operation. Thereafter, it can be used within the + * context of a method dispatched by the POA to obtain + * the POA and ObjectId that identify the object on + * which that operation was invoked. + */ +abstract public class CurrentHelper +{ + private static String _id = "IDL:omg.org/PortableServer/Current:2.3"; + + public static void insert (org.omg.CORBA.Any a, + org.omg.PortableServer.Current that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.PortableServer.Current extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc ( + org.omg.PortableServer.CurrentHelper.id (), "Current"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.PortableServer.Current read ( + org.omg.CORBA.portable.InputStream istream) + { + throw new org.omg.CORBA.MARSHAL (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, + org.omg.PortableServer.Current value) + { + throw new org.omg.CORBA.MARSHAL (); + } + + public static org.omg.PortableServer.Current narrow ( + org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.PortableServer.Current) + return (org.omg.PortableServer.Current)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + return null; + } + +} diff --git a/src/share/classes/org/omg/PortableServer/CurrentPackage/package.html b/src/share/classes/org/omg/PortableServer/CurrentPackage/package.html new file mode 100644 index 000000000..d68debf0e --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/CurrentPackage/package.html @@ -0,0 +1,45 @@ + + + + + + + +

                Provides method implementations with + access to the identity of the object on which the + method was invoked. The Current package + supports servants that implement multiple objects, + but can be used within the context of POA-dispatched + method invocations on any servant. To provide location + transparency, ORBs are required to support use of + Current in the context of both locally and remotely + invoked operations. An instance of Current can be + obtained by the application by issuing the + CORBA::ORB::resolve_initial_references("POACurrent") + operation. Thereafter, it can be used within the + context of a method dispatched by the POA to obtain + the POA and ObjectId that identify the object on + which that operation was invoked. + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableServer/DynamicImplementation.java b/src/share/classes/org/omg/PortableServer/DynamicImplementation.java new file mode 100644 index 000000000..4eb7adc46 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/DynamicImplementation.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + +/** + * Allows dynamic handling of object invocations. POA-based DSI + * servants inherit from the + * standard DynamicImplementation class, this class inherits + * from the Servant class. Based on IDL to Java spec. + * CORBA V 2.3.1 ptc/00-01-08.pdf. + */ +abstract public class DynamicImplementation extends Servant { + +/** + * Receives requests issued to any CORBA object + * incarnated by the DSI servant and performs the processing + * necessary to execute the request. + * @param request the request issued to the CORBA object. + */ + abstract public void invoke(org.omg.CORBA.ServerRequest request); +} diff --git a/src/share/classes/org/omg/PortableServer/POAHelper.java b/src/share/classes/org/omg/PortableServer/POAHelper.java new file mode 100644 index 000000000..bfbbe49d3 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/POAHelper.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + +/** +* org/omg/PortableServer/POAHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.1" +* from ../../../../src/share/classes/org/omg/PortableServer/poa.idl +* Tuesday, October 23, 2001 1:16:58 PM PDT +*/ + + +/** + * A POA object manages the implementation of a + * collection of objects. The POA supports a name space + * for the objects, which are identified by Object Ids. + * A POA also provides a name space for POAs. A POA is + * created as a child of an existing POA, which forms a + * hierarchy starting with the root POA. A POA object + * must not be exported to other processes, or + * externalized with ORB::object_to_string. + */ +abstract public class POAHelper +{ + private static String _id = "IDL:omg.org/PortableServer/POA:2.3"; + + public static void insert (org.omg.CORBA.Any a, + org.omg.PortableServer.POA that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.omg.PortableServer.POA extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.omg.PortableServer.POAHelper.id (), "POA"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.omg.PortableServer.POA read ( + org.omg.CORBA.portable.InputStream istream) + { + throw new org.omg.CORBA.MARSHAL (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, + org.omg.PortableServer.POA value) + { + throw new org.omg.CORBA.MARSHAL (); + } + + public static org.omg.PortableServer.POA narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.omg.PortableServer.POA) + return (org.omg.PortableServer.POA)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + return null; + } +} + diff --git a/src/share/classes/org/omg/PortableServer/POAManagerPackage/package.html b/src/share/classes/org/omg/PortableServer/POAManagerPackage/package.html new file mode 100644 index 000000000..8998fc0cd --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/POAManagerPackage/package.html @@ -0,0 +1,35 @@ + + + + + + + +

                +Encapsulates the processing + state of the POAs it is associated with. Each POA object has an associated POAManager object. A POA manager may be associated with one or more + POA objects. + + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, ORB complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableServer/POAPackage/package.html b/src/share/classes/org/omg/PortableServer/POAPackage/package.html new file mode 100644 index 000000000..a195e5a69 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/POAPackage/package.html @@ -0,0 +1,58 @@ + + + + + + + + +

                Allows programmers to construct object implementations that are portable +between different ORB products. + +

                The Portable Object Adaptor (POA) is designed to meet the following goals: +

                +

                  +
                • Allow programmers to construct object implementations that are portable between different ORB products. +
                • Provide support for objects with persistent identities. +
                • Provide support for transparent activation of objects. +
                • Allow a single servant to support multiple object identities simultaneously. +
                + + + +

                Given an interface My defined in My.idl, the file MyPOA.java is generated by the idlj compiler. You must provide the implementation for My and it must inherit from MyPOA. + +

                MyPOA.java is a stream-based skeleton that extends org.omg.PortableServer.Servant and implements the InvokeHandler interface and the operations interface associated with the IDL interface the skeleton implements. + +

                The PortableServer module for the Portable Object Adapter (POA) defines the native Servant type. In the Java programming language, the Servant type is mapped to the Java org.omg.PortableServer.Servant class. It serves as the base class for all POA servant implementations and provides a number of methods that may +be invoked by the application programmer, as well as methods which are invoked by the POA itself and may be overridden by the user to control aspects of servant behavior. + + + +

                All Mapping corresponds to the Chapter 11 of + CORBA V2.3.1 specified by OMG document formal/99-10-07.pdf. + The exception to this is the id attribute, which is added in ptc/00-08-06, + section 11.3.8.26. + +

                Package Specification

                + +

                For a precise list of supported sections of official specifications with which +the Java[tm] Platform, Standard Edition 6, complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableServer/Servant.java b/src/share/classes/org/omg/PortableServer/Servant.java new file mode 100644 index 000000000..72ff07517 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/Servant.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.portable.Delegate; + +/** + * Defines the native Servant type. In Java, the + * Servant type is mapped to the Java + * org.omg.PortableServer.Servant class. + * It serves as the base class for all POA servant + * implementations and provides a number of methods that may + * be invoked by the application programmer, as well as methods + * which are invoked by the POA itself and may be overridden by + * the user to control aspects of servant behavior. + * Based on IDL to Java spec. (CORBA V2.3.1) ptc/00-01-08.pdf. + */ + +abstract public class Servant { + + private transient Delegate _delegate = null; + /** + * Gets the ORB vendor-specific implementation of + * PortableServer::Servant. + * @return _delegate the ORB vendor-specific + * implementation of PortableServer::Servant. + */ + final public Delegate _get_delegate() { + if (_delegate == null) { + throw + new + org.omg.CORBA.BAD_INV_ORDER + ("The Servant has not been associated with an ORB instance"); + } + return _delegate; + } + + /** + * Supports the Java ORB portability + * interfaces by providing a method for classes that support + * ORB portability through delegation to set their delegate. + * @param delegate ORB vendor-specific implementation of + * the PortableServer::Servant. + */ + final public void _set_delegate(Delegate delegate) { + _delegate = delegate; + } + + /** + * Allows the servant to obtain the object reference for + * the target CORBA object it is incarnating for that request. + * @return this_object Object reference + * associated with the request. + */ + final public org.omg.CORBA.Object _this_object() { + return _get_delegate().this_object(this); + } + + /** + * Allows the servant to obtain the object reference for + * the target CORBA Object it is incarnating for that request. + * @param orb ORB with which the servant is associated. + * @return _this_object reference associated with the request. + */ + final public org.omg.CORBA.Object _this_object(ORB orb) { + try { + ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this); + } + catch(ClassCastException e) { + throw + new + org.omg.CORBA.BAD_PARAM + ("POA Servant requires an instance of org.omg.CORBA_2_3.ORB"); + } + return _this_object(); + } + + /** + * Returns the instance of the ORB + * currently associated with the Servant (convenience method). + * @return orb the instance of the ORB currently + * associated with the Servant. + */ + final public ORB _orb() { + return _get_delegate().orb(this); + } + + /** + * Allows easy execution of common methods, equivalent to + * PortableServer::Current:get_POA. + * @return poa POA associated with the servant. + */ + final public POA _poa() { + return _get_delegate().poa(this); + } + + /** + * Allows easy execution of + * common methods, equivalent + * to calling PortableServer::Current::get_object_id. + * @return object_id the Object ID associated + * with this servant. + */ + final public byte[] _object_id() { + return _get_delegate().object_id(this); + } + + /** + * Returns the + * root POA from the ORB instance associated with the servant. + * Subclasses may override this method to return a different POA. + * @return default_POA the POA associated with the + * Servant. + */ + public POA _default_POA() { + return _get_delegate().default_POA(this); + } + + /** + * Checks to see if the specified repository_id is present + * on the list returned by _all_interfaces() or is the + * repository_id for the generic CORBA Object. + * @param repository_id the repository_id + * to be checked in the repository list or against the id + * of generic CORBA objects. + * @return is_a boolean indicating whether the specified + * repository_id is + * in the repository list or is same as a generic CORBA + * object. + */ + public boolean _is_a(String repository_id) { + return _get_delegate().is_a(this, repository_id); + } + + /** + * Checks for the existence of an + * Object. + * The Servant provides a default implementation of + * _non_existent() that can be overridden by derived servants. + * @return non_existent true if that object does + * not exist, false otherwise. + */ + public boolean _non_existent() { + return _get_delegate().non_existent(this); + } + + // Ken and Simon will ask about editorial changes + // needed in IDL to Java mapping to the following + // signature. + /** + * Returns an object in the Interface Repository + * which provides type information that may be useful to a program. + * Servant provides a default implementation of + * _get_interface() + * that can be overridden by derived servants if the default + * behavior is not adequate. + * @return get_interface type information that corresponds to this servant. + */ + /* + public org.omg.CORBA.Object _get_interface() { + return _get_delegate().get_interface(this); + } + */ + + // _get_interface_def() replaces the _get_interface() method + + /** + * Returns an InterfaceDef object as a + * CORBA::Object that defines the runtime type of the + * CORBA::Object implemented by the Servant. + * The invoker of _get_interface_def + * must narrow the result to an InterfaceDef in order + * to use it. + *

                This default implementation of _get_interface_def() + * can be overridden + * by derived servants if the default behavior is not adequate. + * As defined in the CORBA 2.3.1 specification, section 11.3.1, the + * default behavior of _get_interface_def() is to use + * the most derived + * interface of a static servant or the most derived interface retrieved + * from a dynamic servant to obtain the InterfaceDef. + * This behavior must + * be supported by the Delegate that implements the + * Servant. + * @return get_interface_def an InterfaceDef + * object as a + * CORBA::Object that defines the runtime type of the + * CORBA::Object implemented by the Servant. + */ + public org.omg.CORBA.Object _get_interface_def() + { + // First try to call the delegate implementation class's + // "Object get_interface_def(..)" method (will work for ORBs + // whose delegates implement this method). + // Else call the delegate implementation class's + // "InterfaceDef get_interface(..)" method using reflection + // (will work for ORBs that were built using an older version + // of the Delegate interface with a get_interface method + // but not a get_interface_def method). + + org.omg.PortableServer.portable.Delegate delegate = _get_delegate(); + try { + // If the ORB's delegate class does not implement + // "Object get_interface_def(..)", this will throw + // an AbstractMethodError. + return delegate.get_interface_def(this); + } catch( AbstractMethodError aex ) { + // Call "InterfaceDef get_interface(..)" method using reflection. + try { + Class[] argc = { org.omg.PortableServer.Servant.class }; + java.lang.reflect.Method meth = + delegate.getClass().getMethod("get_interface", argc); + Object[] argx = { this }; + return (org.omg.CORBA.Object)meth.invoke(delegate, argx); + } catch( java.lang.reflect.InvocationTargetException exs ) { + Throwable t = exs.getTargetException(); + if (t instanceof Error) { + throw (Error) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } catch( RuntimeException rex ) { + throw rex; + } catch( Exception exr ) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + } + } + + // methods for which the user must provide an + // implementation + /** + * Used by the ORB to obtain complete type + * information from the servant. + * @param poa POA with which the servant is associated. + * @param objectId is the id corresponding to the object + * associated with this servant. + * @return list of type information for the object. + */ + abstract public String[] _all_interfaces( POA poa, byte[] objectId); +} diff --git a/src/share/classes/org/omg/PortableServer/ServantLocatorPackage/CookieHolder.java b/src/share/classes/org/omg/PortableServer/ServantLocatorPackage/CookieHolder.java new file mode 100644 index 000000000..b3b6006fa --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/ServantLocatorPackage/CookieHolder.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer.ServantLocatorPackage; + +/** + * The native type PortableServer::ServantLocator::Cookie is mapped + * to java.lang.Object. A CookieHolder class is provided for passing + * the Cookie type as an out parameter. The CookieHolder class + * follows exactly the same pattern as the other holder classes + * for basic types. + */ + +final public class CookieHolder implements org.omg.CORBA.portable.Streamable +{ + public java.lang.Object value; + + public CookieHolder() { } + + public CookieHolder(java.lang.Object initial) { + value = initial; + } + + public void _read( org.omg.CORBA.portable.InputStream is) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + public void _write( org.omg.CORBA.portable.OutputStream os) { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } + + public org.omg.CORBA.TypeCode _type() { + throw new org.omg.CORBA.NO_IMPLEMENT(); + } +} diff --git a/src/share/classes/org/omg/PortableServer/ServantLocatorPackage/package.html b/src/share/classes/org/omg/PortableServer/ServantLocatorPackage/package.html new file mode 100644 index 000000000..cd95e25b2 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/ServantLocatorPackage/package.html @@ -0,0 +1,42 @@ + + + + + + + +Provides classes and interfaces for locating the servant. + +

                This package supplies a CookieHolder class for passing +the Cookie type as an out parameter. The CookieHolder class +follows exactly the same pattern as the other holder classes for basic types. + +

                Package Specification

                + +

                For a precise list of supported sections of official OMG specifications with which +the Java[tm] Platform, Standard Edition 6, complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                + + + + + + + +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableServer/package.html b/src/share/classes/org/omg/PortableServer/package.html new file mode 100644 index 000000000..e218839f3 --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/package.html @@ -0,0 +1,203 @@ + + + + + + + +Provides classes and interfaces for making the server side of your applications +portable across multivendor ORBs. + +

                In Java, Portable Object Adaptor (POA)-based Dynamic Skeleton Interface (DSI) +servants inherit from the standard DynamicImplementation class, which +inherits from the Servant class. The native Servant type is +defined by the PortableServer module for the POA. In Java, the + Servant type is mapped to the Java + org.omg.PortableServer.Servant class. + It serves as the base class for all POA servant + implementations and provides a number of methods that may + be invoked by the application programmer, as well as methods + which are invoked by the POA itself and may be overridden by + the user to control aspects of servant behavior. + +

                Package Specification

                + +

                For a precise list of supported sections of official OMG specifications with which +the Java[tm] Platform, Standard Edition 6, complies, see Official Specifications for CORBA +support in Java[tm] SE 6. +

                + +

                POA-related Interfaces

                + +

                The PortableServer module defines the following POA-related interfaces: +

                +

                  +
                • POA +
                • POAManager +
                • ServantManager +
                • ServantActivator +
                • ServantLocator +
                • AdapterActivator +
                • ThreadPolicy +
                • LifespanPolicy +
                • IdUniquenessPolicy +
                • IdAssignmentPolicy +
                • ImplicitActivationPolicy +
                • ServantRetentionPolicy +
                • RequestProcessingPolicy +
                • Current +
                + +

                In addition, the POA defines the Servant native type. + +

                Operations classes

                + +

                Each of the interfaces listed above has an associated Operations interface. The Operations interface is generated by the idlj compiler and contains the method signatures for methods defined in its associated interface. The Operations interface can be accessed by both the client and the server, while its associated interface can only be called by the client. + +

                Value Classes

                + +Classes ending in the suffix PolicyValue provide the values used for the create_POA call, which sets the policy for the POA. See the sample code below for a demonstration. PolicyValue files include the following: +

                +

                  +
                • IdAssignmentPolicyValue +
                • IdUniquenessPolicyValue +
                • ImplicitActivationPolicyValue +
                • LifespanPolicyValue +
                • RequestProcessingPolicyValue +
                • ServantRetentionPolicyValue +
                • ThreadPolicyValue +
                + +

                Helper Classes

                + +

                Helper classes, which are generated for all user-defined types in an OMG IDL +interface, supply static methods needed to manipulate those types. There is only one method in a helper class that an application programmer uses: the narrow method. Only Java interfaces mapped from IDL interfaces will have a helper class that includes a narrow method, so in the PortableServer package, only the following classes have a narrow method: +

                +

                  +
                • ForwardRequestHelper +
                • ServantActivatorHelper +
                • ServantLocatorHelper +
                + +

                POA Classes

                + +

                POA classes are used to implement the ServantActivator or ServantLocator. + +

                Exceptions

                + +

                The ForwardRequest exception indicates to the ORB +that it is responsible for delivering the current request and subsequent ForwardRequest requests to the object denoted in the + forward_reference member of the exception. + +

                Interfaces Implemented by the Application Programmer

                + +

                Most of what PortableServer does is transparent to the user. The result is that programmers will use only a few of the interfaces mentioned above. The remaining interfaces will be provided by the ORB implementation. The interfaces of interest to application programmers are the following: +

                +

                  +
                • AdapterActivator +

                  Adapter activators are associated with POAs. An adapter activator supplies a POA with the ability to create child POAs on demand, as a side-effect of receiving a request that names the child POA (or one of its children), or when find_POA is called with an activate parameter value of TRUE. An application server that creates all its needed POAs at the beginning of execution does not need to use or provide an adapter activator; it is necessary only for the case in which POAs need to be created during request processing. +

                  +

                • ServantLocator +

                  When the POA has the NON_RETAIN policy, it uses servant managers that are ServantLocators. +

                  +

                • ServantActivator +

                  When the POA has the RETAIN policy, it uses servant managers that are ServantActivators. +

                + + +

                Package org.omg.PortableServer.ServantLocatorPackage

                + +

                This package supplies a CookieHolder class for passing +the Cookie type as an out parameter. The CookieHolder class +follows exactly the same pattern as the other holder classes for basic types. + +

                Related Documentation

                + +

                For an overview of Java IDL, please see: +

                +

              24. Java IDL home page. + +

                Example Code

                + +

                Example Server Code

                +

                +

                +import javax.naming.InitialContext;
                +import javax.naming.Context;
                +import javax.rmi.PortableRemoteObject ;
                +import com.sun.corba.ee.impl.poa.POAORB;
                +import org.omg.PortableServer.*;
                +import java.util.*;
                +import org.omg.CORBA.*;
                +import javax.rmi.CORBA.Stub;
                +import javax.rmi.CORBA.Util;
                +
                +
                +
                +public class HelloServer {
                +    public HelloServer(String[] args) {
                +        try {
                +            Properties p = System.getProperties();
                +         //   p.put("org.omg.CORBA.ORBClass", "com.sun.corba.ee.internal.POA.POAORB");
                +            ORB orb = ORB.init( args, p );
                +
                +            POA rootPOA = (POA)orb.resolve_initial_references("RootPOA");
                +
                +            Policy[] tpolicy = new Policy[3];
                +            tpolicy[0] = rootPOA.create_lifespan_policy(
                +                LifespanPolicyValue.TRANSIENT );
                +            tpolicy[1] = rootPOA.create_request_processing_policy(
                +                RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY );
                +            tpolicy[2] = rootPOA.create_servant_retention_policy(
                +                ServantRetentionPolicyValue.RETAIN);
                +            POA tpoa = rootPOA.create_POA("MyTransientPOA", null, tpolicy);
                +
                +
                +            String  ObjectId = "MyObjectId";
                +            byte[] oid = ObjectId.getBytes();
                +
                +            org.omg.CORBA.Object obj = tpoa.create_reference_with_id(oid,
                +                new _HelloImpl_Tie()._all_interfaces(tpoa, oid)[0]);
                +            HelloInterface helloRef = (HelloInterface)PortableRemoteObject.narrow(
                +                obj, HelloInterface.class );
                +
                +            Context initialNamingContext = new InitialContext();
                +            initialNamingContext.rebind("HelloService", helloRef);
                +            System.out.println("Hello Server: Ready...");
                +            orb.run();
                +         } catch (Exception e) {
                +            System.out.println("Trouble: " + e);
                +            e.printStackTrace();
                +         } 
                +     }
                +
                +
                +     public static void main(String args[]) {
                +         new HelloServer( args );
                +     }
                +}
                +
                +
                +
                + + + +

                + + +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/org/omg/PortableServer/portable/Delegate.java b/src/share/classes/org/omg/PortableServer/portable/Delegate.java new file mode 100644 index 000000000..2e4fa816f --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/portable/Delegate.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package org.omg.PortableServer.portable; + +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.POA; + +/** + * The portability package contains interfaces and classes + * that are designed for and intended to be used by ORB + * implementor. It exposes the publicly defined APIs that + * are used to connect stubs and skeletons to the ORB. + * The Delegate interface provides the ORB vendor specific + * implementation of PortableServer::Servant. + * Conformant to spec CORBA V2.3.1, ptc/00-01-08.pdf + */ +public interface Delegate { +/** + * Convenience method that returns the instance of the ORB + * currently associated with the Servant. + * @param Self the servant. + * @return ORB associated with the Servant. + */ + org.omg.CORBA.ORB orb(Servant Self); + +/** + * This allows the servant to obtain the object reference for + * the target CORBA Object it is incarnating for that request. + * @param Self the servant. + * @return Object reference associated with the request. + */ + org.omg.CORBA.Object this_object(Servant Self); + +/** + * The method _poa() is equivalent to + * calling PortableServer::Current:get_POA. + * @param Self the servant. + * @return POA associated with the servant. + */ + POA poa(Servant Self); + +/** + * The method _object_id() is equivalent + * to calling PortableServer::Current::get_object_id. + * @param Self the servant. + * @return ObjectId associated with this servant. + */ + byte[] object_id(Servant Self); + +/** + * The default behavior of this function is to return the + * root POA from the ORB instance associated with the servant. + * @param Self the servant. + * @return POA associated with the servant class. + */ + POA default_POA(Servant Self); + +/** + * This method checks to see if the specified repid is present + * on the list returned by _all_interfaces() or is the + * repository id for the generic CORBA Object. + * @param Self the servant. + * @param Repository_Id the repository_id to be checked in the + * repository list or against the id of generic CORBA + * object. + * @return boolean indicating whether the specified repid is + * in the list or is same as that got generic CORBA + * object. + */ + boolean is_a(Servant Self, String Repository_Id); + +/** + * This operation is used to check for the existence of the + * Object. + * @param Self the servant. + * @return boolean true to indicate that object does not exist, + * and false otherwise. + */ + boolean non_existent(Servant Self); + //Simon And Ken Will Ask About Editorial Changes + //In Idl To Java For The Following Signature. + +/** + * This operation returns an object in the Interface Repository + * which provides type information that may be useful to a program. + * @param Self the servant. + * @return type information corresponding to the object. + */ + // The get_interface() method has been replaced by get_interface_def() + //org.omg.CORBA.Object get_interface(Servant Self); + + org.omg.CORBA.Object get_interface_def(Servant self); +} + diff --git a/src/share/classes/org/omg/PortableServer/portable/package.html b/src/share/classes/org/omg/PortableServer/portable/package.html new file mode 100644 index 000000000..9fd7f7a7d --- /dev/null +++ b/src/share/classes/org/omg/PortableServer/portable/package.html @@ -0,0 +1,33 @@ + + + + + + + +Provides classes and interfaces for making the server side of your applications +portable across multivendor ORBs. + +

                The portable package contains interfaces and classes + that are designed for and intended to be used by an ORB +implementor. It exposes the publicly defined APIs that + are used to connect stubs and skeletons to the ORB. + The Delegate interface provides the ORB-vendor-specific + implementation of PortableServer::Servant. + This package conforms CORBA Specification V2.3.1, ptc/00-01-08. + +@since 1.4 +
                +@serial exclude + + diff --git a/src/share/classes/sun/rmi/rmic/BatchEnvironment.java b/src/share/classes/sun/rmi/rmic/BatchEnvironment.java new file mode 100644 index 000000000..5b494c89e --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/BatchEnvironment.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.io.File; +import java.io.OutputStream; +import java.util.Enumeration; +import java.util.Vector; +import sun.tools.java.ClassPath; + +/** + * BatchEnvironment for rmic extends javac's version in four ways: + * 1. It overrides errorString() to handle looking for rmic-specific + * error messages in rmic's resource bundle + * 2. It provides a mechanism for recording intermediate generated + * files so that they can be deleted later. + * 3. It holds a reference to the Main instance so that generators + * can refer to it. + * 4. It provides access to the ClassPath passed to the constructor. + */ + +@SuppressWarnings({"deprecation"}) +public class BatchEnvironment extends sun.tools.javac.BatchEnvironment { + + /** instance of Main which created this environment */ + private Main main; + + /** + * Create a ClassPath object for rmic from a class path string. + */ + public static ClassPath createClassPath(String classPathString) { + ClassPath[] paths = classPaths(null, classPathString, null, null); + return paths[1]; + } + + /** + * Create a ClassPath object for rmic from the relevant command line + * options for class path, boot class path, and extension directories. + */ + public static ClassPath createClassPath(String classPathString, + String sysClassPathString, + String extDirsString) + { + ClassPath[] paths = classPaths(null, + classPathString, + sysClassPathString, + extDirsString); + return paths[1]; + } + + /** + * Create a BatchEnvironment for rmic with the given class path, + * stream for messages and Main. + */ + public BatchEnvironment(OutputStream out, ClassPath path, Main main) { + super(out, path); + this.main = main; + } + + /** + * Get the instance of Main which created this environment. + */ + public Main getMain() { + return main; + } + + /** + * Get the ClassPath. + */ + public ClassPath getClassPath() { + return sourcePath; + } + + /** list of generated source files created in this environment */ + private Vector generatedFiles = new Vector(); + + /** + * Remember a generated source file generated so that it + * can be removed later, if appropriate. + */ + public void addGeneratedFile(File file) { + generatedFiles.addElement(file); + } + + /** + * Delete all the generated source files made during the execution + * of this environment (those that have been registered with the + * "addGeneratedFile" method). + */ + public void deleteGeneratedFiles() { + synchronized(generatedFiles) { + Enumeration enumeration = generatedFiles.elements(); + while (enumeration.hasMoreElements()) { + File file = (File) enumeration.nextElement(); + file.delete(); + } + generatedFiles.removeAllElements(); + } + } + + /** + * Release resources, if any. + */ + public void shutdown() { + main = null; + generatedFiles = null; + super.shutdown(); + } + + /** + * Return the formatted, localized string for a named error message + * and supplied arguments. For rmic error messages, with names that + * being with "rmic.", look up the error message in rmic's resource + * bundle; otherwise, defer to java's superclass method. + */ + public String errorString(String err, + Object arg0, Object arg1, Object arg2) + { + if (err.startsWith("rmic.") || err.startsWith("warn.rmic.")) { + String result = Main.getText(err, + (arg0 != null ? arg0.toString() : null), + (arg1 != null ? arg1.toString() : null), + (arg2 != null ? arg2.toString() : null)); + + if (err.startsWith("warn.")) { + result = "warning: " + result; + } + return result; + } else { + return super.errorString(err, arg0, arg1, arg2); + } + } + public void reset() { + } +} diff --git a/src/share/classes/sun/rmi/rmic/Constants.java b/src/share/classes/sun/rmi/rmic/Constants.java new file mode 100644 index 000000000..74f649c49 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/Constants.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import sun.tools.java.Identifier; + +public interface Constants extends sun.tools.java.Constants { + + /* + * Identifiers potentially useful for all Generators + */ + public static final Identifier idRemote = + Identifier.lookup("java.rmi.Remote"); + public static final Identifier idRemoteException = + Identifier.lookup("java.rmi.RemoteException"); +} diff --git a/src/share/classes/sun/rmi/rmic/Generator.java b/src/share/classes/sun/rmi/rmic/Generator.java new file mode 100644 index 000000000..6d59a639b --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/Generator.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.io.File; +import sun.tools.java.ClassDefinition; + +/** + * Generator defines the protocol for back-end implementations to be added + * to rmic. See the rmic.properties file for a description of the format for + * adding new Generators to rmic. + *

                + * Classes implementing this interface must have a public default constructor + * which should set any required arguments to their defaults. When Main + * encounters a command line argument which maps to a specific Generator + * subclass, it will instantiate one and call parseArgs(...). At some later + * point, Main will invoke the generate(...) method once for _each_ class passed + * on the command line. + * + * @version 1.0, 2/23/98 + * @author Bryan Atsatt + */ +public interface Generator { + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param main Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main); + + /** + * Generate output. Any source files created which need compilation should + * be added to the compiler environment using the addGeneratedFile(File) + * method. + * + * @param env The compiler environment + * @param cdef The definition for the implementation class or interface from + * which to generate output + * @param destDir The directory for the root of the package hierarchy + * for generated files. May be null. + */ + public void generate(BatchEnvironment env, ClassDefinition cdef, File destDir); +} diff --git a/src/share/classes/sun/rmi/rmic/IndentingWriter.java b/src/share/classes/sun/rmi/rmic/IndentingWriter.java new file mode 100644 index 000000000..1e650bb94 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/IndentingWriter.java @@ -0,0 +1,274 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.io.Writer; +import java.io.BufferedWriter; +import java.io.IOException; + +/** + * IndentingWriter is a BufferedWriter subclass that supports automatic + * indentation of lines of text written to the underlying Writer. + * + * Methods are provided for compact, convenient indenting, writing text, + * and writing lines in various combinations. + */ +public class IndentingWriter extends BufferedWriter { + + /** true if the next character written is the first on a line */ + private boolean beginningOfLine = true; + + /** current number of spaces to prepend to lines */ + private int currentIndent = 0; + + /** number of spaces to change indent when indenting in or out */ + private int indentStep = 4; + + /** number of spaces to convert into tabs. Use MAX_VALUE to disable */ + private int tabSize = 8; + + /** + * Create a new IndentingWriter that writes indented text to the + * given Writer. Use the default indent step of four spaces. + */ + public IndentingWriter(Writer out) { + super(out); + } + + /** + * Create a new IndentingWriter that writes indented text to the + * given Writer and uses the supplied indent step. + */ + public IndentingWriter(Writer out, int step) { + this(out); + + if (indentStep < 0) + throw new IllegalArgumentException("negative indent step"); + + indentStep = step; + } + + /** + * Create a new IndentingWriter that writes indented text to the + * given Writer and uses the supplied indent step and tab size. + */ + public IndentingWriter(Writer out, int step, int tabSize) { + this(out); + + if (indentStep < 0) + throw new IllegalArgumentException("negative indent step"); + + indentStep = step; + this.tabSize = tabSize; + } + + /** + * Write a single character. + */ + public void write(int c) throws IOException { + checkWrite(); + super.write(c); + } + + /** + * Write a portion of an array of characters. + */ + public void write(char[] cbuf, int off, int len) throws IOException { + if (len > 0) { + checkWrite(); + } + super.write(cbuf, off, len); + } + + /** + * Write a portion of a String. + */ + public void write(String s, int off, int len) throws IOException { + if (len > 0) { + checkWrite(); + } + super.write(s, off, len); + } + + /** + * Write a line separator. The next character written will be + * preceded by an indent. + */ + public void newLine() throws IOException { + super.newLine(); + beginningOfLine = true; + } + + /** + * Check if an indent needs to be written before writing the next + * character. + * + * The indent generation is optimized (and made consistent with + * certain coding conventions) by condensing groups of eight spaces + * into tab characters. + */ + protected void checkWrite() throws IOException { + if (beginningOfLine) { + beginningOfLine = false; + int i = currentIndent; + while (i >= tabSize) { + super.write('\t'); + i -= tabSize; + } + while (i > 0) { + super.write(' '); + -- i; + } + } + } + + /** + * Increase the current indent by the indent step. + */ + protected void indentIn() { + currentIndent += indentStep; + } + + /** + * Decrease the current indent by the indent step. + */ + protected void indentOut() { + currentIndent -= indentStep; + if (currentIndent < 0) + currentIndent = 0; + } + + /** + * Indent in. + */ + public void pI() { + indentIn(); + } + + /** + * Indent out. + */ + public void pO() { + indentOut(); + } + + /** + * Write string. + */ + public void p(String s) throws IOException { + write(s); + } + + /** + * End current line. + */ + public void pln() throws IOException { + newLine(); + } + + /** + * Write string; end current line. + */ + public void pln(String s) throws IOException { + p(s); + pln(); + } + + /** + * Write string; end current line; indent in. + */ + public void plnI(String s) throws IOException { + p(s); + pln(); + pI(); + } + + /** + * Indent out; write string. + */ + public void pO(String s) throws IOException { + pO(); + p(s); + } + + /** + * Indent out; write string; end current line. + */ + public void pOln(String s) throws IOException { + pO(s); + pln(); + } + + /** + * Indent out; write string; end current line; indent in. + * + * This method is useful for generating lines of code that both + * end and begin nested blocks, like "} else {". + */ + public void pOlnI(String s) throws IOException { + pO(s); + pln(); + pI(); + } + + /** + * Write Object. + */ + public void p(Object o) throws IOException { + write(o.toString()); + } + /** + * Write Object; end current line. + */ + public void pln(Object o) throws IOException { + p(o.toString()); + pln(); + } + + /** + * Write Object; end current line; indent in. + */ + public void plnI(Object o) throws IOException { + p(o.toString()); + pln(); + pI(); + } + + /** + * Indent out; write Object. + */ + public void pO(Object o) throws IOException { + pO(); + p(o.toString()); + } + + /** + * Indent out; write Object; end current line. + */ + public void pOln(Object o) throws IOException { + pO(o.toString()); + pln(); + } + + /** + * Indent out; write Object; end current line; indent in. + * + * This method is useful for generating lines of code that both + * end and begin nested blocks, like "} else {". + */ + public void pOlnI(Object o) throws IOException { + pO(o.toString()); + pln(); + pI(); + } + +} diff --git a/src/share/classes/sun/rmi/rmic/Main.java b/src/share/classes/sun/rmi/rmic/Main.java new file mode 100644 index 000000000..a57746d90 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/Main.java @@ -0,0 +1,819 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.util.Vector; +import java.util.Enumeration; +import java.util.ResourceBundle; +import java.util.StringTokenizer; +import java.util.MissingResourceException; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.IOException; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.ByteArrayOutputStream; + +import sun.tools.java.ClassFile; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.ClassNotFound; +import sun.tools.java.Identifier; +import sun.tools.java.ClassPath; + +import sun.tools.util.CommandLine; +import java.lang.reflect.Constructor; +import java.util.Properties; + +/** + * Main "rmic" program. + */ +@SuppressWarnings({"deprecation"}) +public class Main implements sun.rmi.rmic.Constants { + String sourcePathArg; + String sysClassPathArg; + String extDirsArg; + String classPathString; + File destDir; + int flags; + long tm; + Vector classes; + boolean nowrite; + boolean nocompile; + boolean keepGenerated; + boolean status; + String[] generatorArgs; + Vector generators; + Class environmentClass = BatchEnvironment.class; + boolean iiopGeneration = false; + + /** + * Name of the program. + */ + String program; + + /** + * The stream where error message are printed. + */ + OutputStream out; + + /** + * Constructor. + */ + public Main(OutputStream out, String program) { + this.out = out; + this.program = program; + } + + /** + * Output a message. + */ + public void output(String msg) { + PrintStream out = + this.out instanceof PrintStream ? (PrintStream)this.out + : new PrintStream(this.out, true); + out.println(msg); + } + + /** + * Top level error message. This method is called when the + * environment could not be set up yet. + */ + public void error(String msg, Object... args) { + output(getText(msg, args)); + } + + /** + * Usage + */ + public void usage() { + error("rmic.usage", program); + } + + /** + * Run the compiler + */ + public synchronized boolean compile(String argv[]) { + if (!parseArgs(argv)) { + return false; + } + + if (classes.size() == 0) { + usage(); + return false; + } + + return doCompile(); + } + + /** + * Get the destination directory. + */ + public File getDestinationDir() { + return destDir; + } + + /** + * Parse the arguments for compile. + */ + public boolean parseArgs(String argv[]) { + sourcePathArg = null; + sysClassPathArg = null; + extDirsArg = null; + + classPathString = null; + destDir = null; + flags = F_WARNINGS; + tm = System.currentTimeMillis(); + classes = new Vector(); + nowrite = false; + nocompile = false; + keepGenerated = false; + generatorArgs = getArray("generator.args",true); + if (generatorArgs == null) { + return false; + } + generators = new Vector(); + + // Pre-process command line for @file arguments + try { + argv = CommandLine.parse(argv); + } catch (FileNotFoundException e) { + error("rmic.cant.read", e.getMessage()); + return false; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + // Parse arguments + for (int i = 0 ; i < argv.length ; i++) { + if (argv[i] != null) { + if (argv[i].equals("-g")) { + flags &= ~F_OPT; + flags |= F_DEBUG_LINES | F_DEBUG_VARS; + argv[i] = null; + } else if (argv[i].equals("-O")) { + flags &= ~F_DEBUG_LINES; + flags &= ~F_DEBUG_VARS; + flags |= F_OPT | F_DEPENDENCIES; + argv[i] = null; + } else if (argv[i].equals("-nowarn")) { + flags &= ~F_WARNINGS; + argv[i] = null; + } else if (argv[i].equals("-debug")) { + flags |= F_DUMP; + argv[i] = null; + } else if (argv[i].equals("-depend")) { + flags |= F_DEPENDENCIES; + argv[i] = null; + } else if (argv[i].equals("-verbose")) { + flags |= F_VERBOSE; + argv[i] = null; + } else if (argv[i].equals("-nowrite")) { + nowrite = true; + argv[i] = null; + } else if (argv[i].equals("-Xnocompile")) { + nocompile = true; + keepGenerated = true; + argv[i] = null; + } else if (argv[i].equals("-keep") || + argv[i].equals("-keepgenerated")) { + keepGenerated = true; + argv[i] = null; + } else if (argv[i].equals("-show")) { + error("rmic.option.unsupported", "-show"); + usage(); + return false; + } else if (argv[i].equals("-classpath")) { + if ((i + 1) < argv.length) { + if (classPathString != null) { + error("rmic.option.already.seen", "-classpath"); + usage(); + return false; + } + argv[i] = null; + classPathString = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-classpath"); + usage(); + return false; + } + } else if (argv[i].equals("-sourcepath")) { + if ((i + 1) < argv.length) { + if (sourcePathArg != null) { + error("rmic.option.already.seen", "-sourcepath"); + usage(); + return false; + } + argv[i] = null; + sourcePathArg = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-sourcepath"); + usage(); + return false; + } + } else if (argv[i].equals("-bootclasspath")) { + if ((i + 1) < argv.length) { + if (sysClassPathArg != null) { + error("rmic.option.already.seen", "-bootclasspath"); + usage(); + return false; + } + argv[i] = null; + sysClassPathArg = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-bootclasspath"); + usage(); + return false; + } + } else if (argv[i].equals("-extdirs")) { + if ((i + 1) < argv.length) { + if (extDirsArg != null) { + error("rmic.option.already.seen", "-extdirs"); + usage(); + return false; + } + argv[i] = null; + extDirsArg = argv[++i]; + argv[i] = null; + } else { + error("rmic.option.requires.argument", "-extdirs"); + usage(); + return false; + } + } else if (argv[i].equals("-d")) { + if ((i + 1) < argv.length) { + if (destDir != null) { + error("rmic.option.already.seen", "-d"); + usage(); + return false; + } + argv[i] = null; + destDir = new File(argv[++i]); + argv[i] = null; + if (!destDir.exists()) { + error("rmic.no.such.directory", destDir.getPath()); + usage(); + return false; + } + } else { + error("rmic.option.requires.argument", "-d"); + usage(); + return false; + } + } else { + if (!checkGeneratorArg(argv,i)) { + usage(); + return false; + } + } + } + } + + + // Now that all generators have had a chance at the args, + // scan what's left for classes and illegal args... + + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + if (argv[i].startsWith("-")) { + error("rmic.no.such.option", argv[i]); + usage(); + return false; + } else { + classes.addElement(argv[i]); + } + } + } + + + // If the generators vector is empty, add the default generator... + + if (generators.size() == 0) { + addGenerator("default"); + } + + return true; + } + + /** + * If this argument is for a generator, instantiate it, call + * parseArgs(...) and add generator to generators vector. + * Returns false on error. + */ + protected boolean checkGeneratorArg(String[] argv, int currentIndex) { + boolean result = true; + if (argv[currentIndex].startsWith("-")) { + String arg = argv[currentIndex].substring(1).toLowerCase(); // Remove '-' + for (int i = 0; i < generatorArgs.length; i++) { + if (arg.equalsIgnoreCase(generatorArgs[i])) { + // Got a match, add Generator and call parseArgs... + Generator gen = addGenerator(arg); + if (gen == null) { + return false; + } + result = gen.parseArgs(argv,this); + break; + } + } + } + return result; + } + + /** + * Instantiate and add a generator to the generators array. + */ + protected Generator addGenerator(String arg) { + + Generator gen; + + // Create an instance of the generator and add it to + // the array... + + String className = getString("generator.class." + arg); + if (className == null) { + error("rmic.missing.property",arg); + return null; + } + + try { + gen = (Generator) Class.forName(className).newInstance(); + } catch (Exception e) { + error("rmic.cannot.instantiate",className); + return null; + } + + generators.addElement(gen); + + // Get the environment required by this generator... + + Class envClass = BatchEnvironment.class; + String env = getString("generator.env." + arg); + if (env != null) { + try { + envClass = Class.forName(env); + + // Is the new class a subclass of the current one? + + if (environmentClass.isAssignableFrom(envClass)) { + + // Yes, so switch to the new one... + + environmentClass = envClass; + + } else { + + // No. Is the current class a subclass of the + // new one? + + if (!envClass.isAssignableFrom(environmentClass)) { + + // No, so it's a conflict... + + error("rmic.cannot.use.both",environmentClass.getName(),envClass.getName()); + return null; + } + } + } catch (ClassNotFoundException e) { + error("rmic.class.not.found",env); + return null; + } + } + + // If this is the iiop stub generator, cache + // that fact for the jrmp generator... + + if (arg.equals("iiop")) { + iiopGeneration = true; + } + return gen; + } + + /** + * Grab a resource string and parse it into an array of strings. Assumes + * comma separated list. + * @param name The resource name. + * @param mustExist If true, throws error if resource does not exist. If + * false and resource does not exist, returns zero element array. + */ + protected String[] getArray(String name, boolean mustExist) { + String[] result = null; + String value = getString(name); + if (value == null) { + if (mustExist) { + error("rmic.resource.not.found",name); + return null; + } else { + return new String[0]; + } + } + + StringTokenizer parser = new StringTokenizer(value,", \t\n\r", false); + int count = parser.countTokens(); + result = new String[count]; + for (int i = 0; i < count; i++) { + result[i] = parser.nextToken(); + } + + return result; + } + + /** + * Get the correct type of BatchEnvironment + */ + public BatchEnvironment getEnv() { + + ClassPath classPath = + BatchEnvironment.createClassPath(classPathString, + sysClassPathArg, + extDirsArg); + BatchEnvironment result = null; + try { + Class[] ctorArgTypes = {OutputStream.class,ClassPath.class,Main.class}; + Object[] ctorArgs = {out,classPath,this}; + Constructor constructor = environmentClass.getConstructor(ctorArgTypes); + result = (BatchEnvironment) constructor.newInstance(ctorArgs); + result.reset(); + } + catch (Exception e) { + error("rmic.cannot.instantiate",environmentClass.getName()); + } + return result; + } + + + /** + * Do the compile with the switches and files already supplied + */ + public boolean doCompile() { + // Create batch environment + BatchEnvironment env = getEnv(); + env.flags |= flags; + + // Set the classfile version numbers + // Compat and 1.1 stubs must retain the old version number. + env.majorVersion = 45; + env.minorVersion = 3; + + // Preload the "out of memory" error string just in case we run + // out of memory during the compile. + String noMemoryErrorString = getText("rmic.no.memory"); + String stackOverflowErrorString = getText("rmic.stack.overflow"); + + try { + /** Load the classes on the command line + * Replace the entries in classes with the ClassDefinition for the class + */ + for (int i = classes.size()-1; i >= 0; i-- ) { + Identifier implClassName = + Identifier.lookup((String)classes.elementAt(i)); + + /* + * Fix bugid 4049354: support using '.' as an inner class + * qualifier on the command line (previously, only mangled + * inner class names were understood, like "pkg.Outer$Inner"). + * + * The following method, also used by "javap", resolves the + * given unmangled inner class name to the appropriate + * internal identifier. For example, it translates + * "pkg.Outer.Inner" to "pkg.Outer. Inner". + */ + implClassName = env.resolvePackageQualifiedName(implClassName); + /* + * But if we use such an internal inner class name identifier + * to load the class definition, the Java compiler will notice + * if the impl class is a "private" inner class and then deny + * skeletons (needed unless "-v1.2" is used) the ability to + * cast to it. To work around this problem, we mangle inner + * class name identifiers to their binary "outer" class name: + * "pkg.Outer. Inner" becomes "pkg.Outer$Inner". + */ + implClassName = Names.mangleClass(implClassName); + + ClassDeclaration decl = env.getClassDeclaration(implClassName); + try { + ClassDefinition def = decl.getClassDefinition(env); + for (int j = 0; j < generators.size(); j++) { + Generator gen = (Generator)generators.elementAt(j); + gen.generate(env, def, destDir); + } + } catch (ClassNotFound ex) { + env.error(0, "rmic.class.not.found", implClassName); + } + + } + + // compile all classes that need compilation + if (!nocompile) { + compileAllClasses(env); + } + } catch (OutOfMemoryError ee) { + // The compiler has run out of memory. Use the error string + // which we preloaded. + env.output(noMemoryErrorString); + return false; + } catch (StackOverflowError ee) { + env.output(stackOverflowErrorString); + return false; + } catch (Error ee) { + // We allow the compiler to take an exception silently if a program + // error has previously been detected. Presumably, this makes the + // compiler more robust in the face of bad error recovery. + if (env.nerrors == 0 || env.dump()) { + ee.printStackTrace(); + env.error(0, "fatal.error"); + } + } catch (Exception ee) { + if (env.nerrors == 0 || env.dump()) { + ee.printStackTrace(); + env.error(0, "fatal.exception"); + } + } + + env.flushErrors(); + + boolean status = true; + if (env.nerrors > 0) { + String msg = ""; + if (env.nerrors > 1) { + msg = getText("rmic.errors", env.nerrors); + } else { + msg = getText("rmic.1error"); + } + if (env.nwarnings > 0) { + if (env.nwarnings > 1) { + msg += ", " + getText("rmic.warnings", env.nwarnings); + } else { + msg += ", " + getText("rmic.1warning"); + } + } + output(msg); + status = false; + } else { + if (env.nwarnings > 0) { + if (env.nwarnings > 1) { + output(getText("rmic.warnings", env.nwarnings)); + } else { + output(getText("rmic.1warning")); + } + } + } + + // last step is to delete generated source files + if (!keepGenerated) { + env.deleteGeneratedFiles(); + } + + // We're done + if (env.verbose()) { + tm = System.currentTimeMillis() - tm; + output(getText("rmic.done_in", Long.toString(tm))); + } + + // Shutdown the environment object and release our resources. + // Note that while this is unneccessary when rmic is invoked + // the command line, there are environments in which rmic + // from is invoked within a server process, so resource + // reclamation is important... + + env.shutdown(); + + sourcePathArg = null; + sysClassPathArg = null; + extDirsArg = null; + classPathString = null; + destDir = null; + classes = null; + generatorArgs = null; + generators = null; + environmentClass = null; + program = null; + out = null; + + return status; + } + + /* + * Compile all classes that need to be compiled. + */ + public void compileAllClasses (BatchEnvironment env) + throws ClassNotFound, + IOException, + InterruptedException { + ByteArrayOutputStream buf = new ByteArrayOutputStream(4096); + boolean done; + + do { + done = true; + for (Enumeration e = env.getClasses() ; e.hasMoreElements() ; ) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + done = compileClass(c,buf,env); + } + } while (!done); + } + + /* + * Compile a single class. + */ + public boolean compileClass (ClassDeclaration c, + ByteArrayOutputStream buf, + BatchEnvironment env) + throws ClassNotFound, + IOException, + InterruptedException { + boolean done = true; + env.flushErrors(); + sun.tools.javac.SourceClass src; + + switch (c.getStatus()) { + case CS_UNDEFINED: + { + if (!env.dependencies()) { + break; + } + // fall through + } + + case CS_SOURCE: + { + done = false; + env.loadDefinition(c); + if (c.getStatus() != CS_PARSED) { + break; + } + // fall through + } + + case CS_PARSED: + { + if (c.getClassDefinition().isInsideLocal()) { + break; + } + // If we get to here, then compilation is going + // to occur. If the -Xnocompile switch is set + // then fail. Note that this check is required + // here because this method is called from + // generators, not just from within this class... + + if (nocompile) { + throw new IOException("Compilation required, but -Xnocompile option in effect"); + } + + done = false; + + src = (sun.tools.javac.SourceClass)c.getClassDefinition(env); + src.check(env); + c.setDefinition(src, CS_CHECKED); + // fall through + } + + case CS_CHECKED: + { + src = (sun.tools.javac.SourceClass)c.getClassDefinition(env); + // bail out if there were any errors + if (src.getError()) { + c.setDefinition(src, CS_COMPILED); + break; + } + done = false; + buf.reset(); + src.compile(buf); + c.setDefinition(src, CS_COMPILED); + src.cleanup(env); + + if (src.getError() || nowrite) { + break; + } + + String pkgName = c.getName().getQualifier().toString().replace('.', File.separatorChar); + String className = c.getName().getFlatName().toString().replace('.', SIGC_INNERCLASS) + ".class"; + + File file; + if (destDir != null) { + if (pkgName.length() > 0) { + file = new File(destDir, pkgName); + if (!file.exists()) { + file.mkdirs(); + } + file = new File(file, className); + } else { + file = new File(destDir, className); + } + } else { + ClassFile classfile = (ClassFile)src.getSource(); + if (classfile.isZipped()) { + env.error(0, "cant.write", classfile.getPath()); + break; + } + file = new File(classfile.getPath()); + file = new File(file.getParent(), className); + } + + // Create the file + try { + FileOutputStream out = new FileOutputStream(file.getPath()); + buf.writeTo(out); + out.close(); + if (env.verbose()) { + output(getText("rmic.wrote", file.getPath())); + } + } catch (IOException ee) { + env.error(0, "cant.write", file.getPath()); + } + } + } + return done; + } + + /** + * Main program + */ + public static void main(String argv[]) { + Main compiler = new Main(System.out, "rmic"); + System.exit(compiler.compile(argv) ? 0 : 1); + } + + /** + * Return the string value of a named resource in the rmic.properties + * resource bundle. If the resource is not found, null is returned. + */ + public static String getString(String key) { + if (!resourcesInitialized) { + initResources(); + } + + // To enable extensions, search the 'resourcesExt' + // bundle first, followed by the 'resources' bundle... + + if (resourcesExt != null) { + try { + return resourcesExt.getString(key); + } catch (MissingResourceException e) {} + } + + try { + return resources.getString(key); + } catch (MissingResourceException ignore) { + } + return null; + } + + private static boolean resourcesInitialized = false; + private static ResourceBundle resources; + private static ResourceBundle resourcesExt = null; + + private static void initResources() { + try { + resources = + ResourceBundle.getBundle("sun.rmi.rmic.resources.rmic"); + resourcesInitialized = true; + try { + resourcesExt = + ResourceBundle.getBundle("sun.rmi.rmic.resources.rmicext"); + } catch (MissingResourceException e) {} + } catch (MissingResourceException e) { + throw new Error("fatal: missing resource bundle: " + + e.getClassName()); + } + } + + public static String getText(String key) { + String message = getString(key); + if (message == null) { + message = "no text found: \"" + key + "\""; + } + return message; + } + + public static String getText(String key, Object... args ) + { + String format = getString(key); + if (format == null) { + format = "no text found: key = \"" + key + "\", " + + "arguments = " ; + + for (int ctr=0; ctr 0) { + p.p("implements "); + for (int i = 0; i < remoteInterfaces.length; i++) { + if (i > 0) + p.p(", "); + p.p(remoteInterfaces[i].getName().toString()); + } + p.pln(); + } + p.pOlnI("{"); + + if (version == STUB_VERSION_1_1 || + version == STUB_VERSION_FAT) + { + writeOperationsArray(p); + p.pln(); + writeInterfaceHash(p); + p.pln(); + } + + if (version == STUB_VERSION_FAT || + version == STUB_VERSION_1_2) + { + p.pln("private static final long serialVersionUID = " + + STUB_SERIAL_VERSION_UID + ";"); + p.pln(); + + /* + * We only need to declare and initialize the static fields of + * Method objects for each remote method if there are any remote + * methods; otherwise, skip this code entirely, to avoid generating + * a try/catch block for a checked exception that cannot occur + * (see bugid 4125181). + */ + if (methodFieldNames.length > 0) { + if (version == STUB_VERSION_FAT) { + p.pln("private static boolean useNewInvoke;"); + } + writeMethodFieldDeclarations(p); + p.pln(); + + /* + * Initialize java.lang.reflect.Method fields for each remote + * method in a static initializer. + */ + p.plnI("static {"); + p.plnI("try {"); + if (version == STUB_VERSION_FAT) { + /* + * Fat stubs must determine whether the API required for + * the JDK 1.2 stub protocol is supported in the current + * runtime, so that it can use it if supported. This is + * determined by using the Reflection API to test if the + * new invoke method on RemoteRef exists, and setting the + * static boolean "useNewInvoke" to true if it does, or + * to false if a NoSuchMethodException is thrown. + */ + p.plnI(idRemoteRef + ".class.getMethod(\"invoke\","); + p.plnI("new java.lang.Class[] {"); + p.pln(idRemote + ".class,"); + p.pln("java.lang.reflect.Method.class,"); + p.pln("java.lang.Object[].class,"); + p.pln("long.class"); + p.pOln("});"); + p.pO(); + p.pln("useNewInvoke = true;"); + } + writeMethodFieldInitializers(p); + p.pOlnI("} catch (java.lang.NoSuchMethodException e) {"); + if (version == STUB_VERSION_FAT) { + p.pln("useNewInvoke = false;"); + } else { + /* + * REMIND: By throwing an Error here, the application will + * get the NoSuchMethodError directly when the stub class + * is initialized. If we throw a RuntimeException + * instead, the application would get an + * ExceptionInInitializerError. Would that be more + * appropriate, and if so, which RuntimeException should + * be thrown? + */ + p.plnI("throw new java.lang.NoSuchMethodError("); + p.pln("\"stub class initialization failed\");"); + p.pO(); + } + p.pOln("}"); // end try/catch block + p.pOln("}"); // end static initializer + p.pln(); + } + } + + writeStubConstructors(p); + p.pln(); + + /* + * Write each stub method. + */ + if (remoteMethods.length > 0) { + p.pln("// methods from remote interfaces"); + for (int i = 0; i < remoteMethods.length; ++i) { + p.pln(); + writeStubMethod(p, i); + } + } + + p.pOln("}"); // end stub class + } + + /** + * Write the constructors for the stub class. + */ + private void writeStubConstructors(IndentingWriter p) + throws IOException + { + p.pln("// constructors"); + + /* + * Only stubs compatible with the JDK 1.1 stub protocol need + * a no-arg constructor; later versions use reflection to find + * the constructor that directly takes a RemoteRef argument. + */ + if (version == STUB_VERSION_1_1 || + version == STUB_VERSION_FAT) + { + p.plnI("public " + Names.mangleClass(stubClassName.getName()) + + "() {"); + p.pln("super();"); + p.pOln("}"); + } + + p.plnI("public " + Names.mangleClass(stubClassName.getName()) + + "(" + idRemoteRef + " ref) {"); + p.pln("super(ref);"); + p.pOln("}"); + } + + /** + * Write the stub method for the remote method with the given "opnum". + */ + private void writeStubMethod(IndentingWriter p, int opnum) + throws IOException + { + RemoteClass.Method method = remoteMethods[opnum]; + Identifier methodName = method.getName(); + Type methodType = method.getType(); + Type paramTypes[] = methodType.getArgumentTypes(); + String paramNames[] = nameParameters(paramTypes); + Type returnType = methodType.getReturnType(); + ClassDeclaration[] exceptions = method.getExceptions(); + + /* + * Declare stub method; throw exceptions declared in remote + * interface(s). + */ + p.pln("// implementation of " + + methodType.typeString(methodName.toString(), true, false)); + p.p("public " + returnType + " " + methodName + "("); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) + p.p(", "); + p.p(paramTypes[i] + " " + paramNames[i]); + } + p.plnI(")"); + if (exceptions.length > 0) { + p.p("throws "); + for (int i = 0; i < exceptions.length; i++) { + if (i > 0) + p.p(", "); + p.p(exceptions[i].getName().toString()); + } + p.pln(); + } + p.pOlnI("{"); + + /* + * The RemoteRef.invoke methods throw Exception, but unless this + * stub method throws Exception as well, we must catch Exceptions + * thrown from the invocation. So we must catch Exception and + * rethrow something we can throw: UnexpectedException, which is a + * subclass of RemoteException. But for any subclasses of Exception + * that we can throw, like RemoteException, RuntimeException, and + * any of the exceptions declared by this stub method, we want them + * to pass through unharmed, so first we must catch any such + * exceptions and rethrow it directly. + * + * We have to be careful generating the rethrowing catch blocks + * here, because javac will flag an error if there are any + * unreachable catch blocks, i.e. if the catch of an exception class + * follows a previous catch of it or of one of its superclasses. + * The following method invocation takes care of these details. + */ + Vector catchList = computeUniqueCatchList(exceptions); + + /* + * If we need to catch any particular exceptions (i.e. this method + * does not declare java.lang.Exception), put the entire stub + * method in a try block. + */ + if (catchList.size() > 0) { + p.plnI("try {"); + } + + if (version == STUB_VERSION_FAT) { + p.plnI("if (useNewInvoke) {"); + } + if (version == STUB_VERSION_FAT || + version == STUB_VERSION_1_2) + { + if (!returnType.isType(TC_VOID)) { + p.p("Object $result = "); // REMIND: why $? + } + p.p("ref.invoke(this, " + methodFieldNames[opnum] + ", "); + if (paramTypes.length > 0) { + p.p("new java.lang.Object[] {"); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) + p.p(", "); + p.p(wrapArgumentCode(paramTypes[i], paramNames[i])); + } + p.p("}"); + } else { + p.p("null"); + } + p.pln(", " + method.getMethodHash() + "L);"); + if (!returnType.isType(TC_VOID)) { + p.pln("return " + + unwrapArgumentCode(returnType, "$result") + ";"); + } + } + if (version == STUB_VERSION_FAT) { + p.pOlnI("} else {"); + } + if (version == STUB_VERSION_1_1 || + version == STUB_VERSION_FAT) + { + p.pln(idRemoteCall + " call = ref.newCall((" + idRemoteObject + + ") this, operations, " + opnum + ", interfaceHash);"); + + if (paramTypes.length > 0) { + p.plnI("try {"); + p.pln("java.io.ObjectOutput out = call.getOutputStream();"); + writeMarshalArguments(p, "out", paramTypes, paramNames); + p.pOlnI("} catch (java.io.IOException e) {"); + p.pln("throw new " + idMarshalException + + "(\"error marshalling arguments\", e);"); + p.pOln("}"); + } + + p.pln("ref.invoke(call);"); + + if (returnType.isType(TC_VOID)) { + p.pln("ref.done(call);"); + } else { + p.pln(returnType + " $result;"); // REMIND: why $? + p.plnI("try {"); + p.pln("java.io.ObjectInput in = call.getInputStream();"); + boolean objectRead = + writeUnmarshalArgument(p, "in", returnType, "$result"); + p.pln(";"); + p.pOlnI("} catch (java.io.IOException e) {"); + p.pln("throw new " + idUnmarshalException + + "(\"error unmarshalling return\", e);"); + /* + * If any only if readObject has been invoked, we must catch + * ClassNotFoundException as well as IOException. + */ + if (objectRead) { + p.pOlnI("} catch (java.lang.ClassNotFoundException e) {"); + p.pln("throw new " + idUnmarshalException + + "(\"error unmarshalling return\", e);"); + } + p.pOlnI("} finally {"); + p.pln("ref.done(call);"); + p.pOln("}"); + p.pln("return $result;"); + } + } + if (version == STUB_VERSION_FAT) { + p.pOln("}"); // end if/else (useNewInvoke) block + } + + /* + * If we need to catch any particular exceptions, finally write + * the catch blocks for them, rethrow any other Exceptions with an + * UnexpectedException, and end the try block. + */ + if (catchList.size() > 0) { + for (Enumeration enumeration = catchList.elements(); + enumeration.hasMoreElements();) + { + ClassDefinition def = (ClassDefinition) enumeration.nextElement(); + p.pOlnI("} catch (" + def.getName() + " e) {"); + p.pln("throw e;"); + } + p.pOlnI("} catch (java.lang.Exception e) {"); + p.pln("throw new " + idUnexpectedException + + "(\"undeclared checked exception\", e);"); + p.pOln("}"); // end try/catch block + } + + p.pOln("}"); // end stub method + } + + /** + * Compute the exceptions which need to be caught and rethrown in a + * stub method before wrapping Exceptions in UnexpectedExceptions, + * given the exceptions declared in the throws clause of the method. + * Returns a Vector containing ClassDefinition objects for each + * exception to catch. Each exception is guaranteed to be unique, + * i.e. not a subclass of any of the other exceptions in the Vector, + * so the catch blocks for these exceptions may be generated in any + * order relative to each other. + * + * RemoteException and RuntimeException are each automatically placed + * in the returned Vector (if none of their superclasses are already + * present), since those exceptions should always be directly rethrown + * by a stub method. + * + * The returned Vector will be empty if java.lang.Exception or one + * of its superclasses is in the throws clause of the method, indicating + * that no exceptions need to be caught. + */ + private Vector computeUniqueCatchList(ClassDeclaration[] exceptions) { + Vector uniqueList = new Vector(); // unique exceptions to catch + + uniqueList.addElement(defRuntimeException); + uniqueList.addElement(defRemoteException); + + /* For each exception declared by the stub method's throws clause: */ + nextException: + for (int i = 0; i < exceptions.length; i++) { + ClassDeclaration decl = exceptions[i]; + try { + if (defException.subClassOf(env, decl)) { + /* + * (If java.lang.Exception (or a superclass) was declared + * in the throws clause of this stub method, then we don't + * have to bother catching anything; clear the list and + * return.) + */ + uniqueList.clear(); + break; + } else if (!defException.superClassOf(env, decl)) { + /* + * Ignore other Throwables that do not extend Exception, + * since they do not need to be caught anyway. + */ + continue; + } + /* + * Compare this exception against the current list of + * exceptions that need to be caught: + */ + for (int j = 0; j < uniqueList.size();) { + ClassDefinition def = + (ClassDefinition) uniqueList.elementAt(j); + if (def.superClassOf(env, decl)) { + /* + * If a superclass of this exception is already on + * the list to catch, then ignore and continue; + */ + continue nextException; + } else if (def.subClassOf(env, decl)) { + /* + * If a subclass of this exception is on the list + * to catch, then remove it. + */ + uniqueList.removeElementAt(j); + } else { + j++; // else continue comparing + } + } + /* This exception is unique: add it to the list to catch. */ + uniqueList.addElement(decl.getClassDefinition(env)); + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, decl.getName()); + /* + * REMIND: We do not exit from this exceptional condition, + * generating questionable code and likely letting the + * compiler report a resulting error later. + */ + } + } + return uniqueList; + } + + /** + * Write the skeleton for the remote class to a stream. + */ + private void writeSkeleton(IndentingWriter p) throws IOException { + if (version == STUB_VERSION_1_2) { + throw new Error("should not generate skeleton for version"); + } + + /* + * Write boiler plate comment. + */ + p.pln("// Skeleton class generated by rmic, do not edit."); + p.pln("// Contents subject to change without notice."); + p.pln(); + + /* + * If remote implementation class was in a particular package, + * declare the skeleton class to be in the same package. + */ + if (remoteClassName.isQualified()) { + p.pln("package " + remoteClassName.getQualifier() + ";"); + p.pln(); + } + + /* + * Declare the skeleton class. + */ + p.plnI("public final class " + + Names.mangleClass(skeletonClassName.getName())); + p.pln("implements " + idSkeleton); + p.pOlnI("{"); + + writeOperationsArray(p); + p.pln(); + + writeInterfaceHash(p); + p.pln(); + + /* + * Define the getOperations() method. + */ + p.plnI("public " + idOperation + "[] getOperations() {"); + p.pln("return (" + idOperation + "[]) operations.clone();"); + p.pOln("}"); + p.pln(); + + /* + * Define the dispatch() method. + */ + p.plnI("public void dispatch(" + idRemote + " obj, " + + idRemoteCall + " call, int opnum, long hash)"); + p.pln("throws java.lang.Exception"); + p.pOlnI("{"); + + if (version == STUB_VERSION_FAT) { + p.plnI("if (opnum < 0) {"); + if (remoteMethods.length > 0) { + for (int opnum = 0; opnum < remoteMethods.length; opnum++) { + if (opnum > 0) + p.pO("} else "); + p.plnI("if (hash == " + + remoteMethods[opnum].getMethodHash() + "L) {"); + p.pln("opnum = " + opnum + ";"); + } + p.pOlnI("} else {"); + } + /* + * Skeleton throws UnmarshalException if it does not recognize + * the method hash; this is what UnicastServerRef.dispatch() + * would do. + */ + p.pln("throw new " + + idUnmarshalException + "(\"invalid method hash\");"); + if (remoteMethods.length > 0) { + p.pOln("}"); + } + /* + * Ignore the validation of the interface hash if the + * operation number was negative, since it is really a + * method hash instead. + */ + p.pOlnI("} else {"); + } + + p.plnI("if (hash != interfaceHash)"); + p.pln("throw new " + + idSkeletonMismatchException + "(\"interface hash mismatch\");"); + p.pO(); + + if (version == STUB_VERSION_FAT) { + p.pOln("}"); // end if/else (opnum < 0) block + } + p.pln(); + + /* + * Cast remote object instance to our specific implementation class. + */ + p.pln(remoteClassName + " server = (" + remoteClassName + ") obj;"); + + /* + * Process call according to the operation number. + */ + p.plnI("switch (opnum) {"); + for (int opnum = 0; opnum < remoteMethods.length; opnum++) { + writeSkeletonDispatchCase(p, opnum); + } + p.pOlnI("default:"); + /* + * Skeleton throws UnmarshalException if it does not recognize + * the operation number; this is consistent with the case of an + * unrecognized method hash. + */ + p.pln("throw new " + idUnmarshalException + + "(\"invalid method number\");"); + p.pOln("}"); // end switch statement + + p.pOln("}"); // end dispatch() method + + p.pOln("}"); // end skeleton class + } + + /** + * Write the case block for the skeleton's dispatch method for + * the remote method with the given "opnum". + */ + private void writeSkeletonDispatchCase(IndentingWriter p, int opnum) + throws IOException + { + RemoteClass.Method method = remoteMethods[opnum]; + Identifier methodName = method.getName(); + Type methodType = method.getType(); + Type paramTypes[] = methodType.getArgumentTypes(); + String paramNames[] = nameParameters(paramTypes); + Type returnType = methodType.getReturnType(); + + p.pOlnI("case " + opnum + ": // " + + methodType.typeString(methodName.toString(), true, false)); + /* + * Use nested block statement inside case to provide an independent + * namespace for local variables used to unmarshal parameters for + * this remote method. + */ + p.pOlnI("{"); + + if (paramTypes.length > 0) { + /* + * Declare local variables to hold arguments. + */ + for (int i = 0; i < paramTypes.length; i++) { + p.pln(paramTypes[i] + " " + paramNames[i] + ";"); + } + + /* + * Unmarshal arguments from call stream. + */ + p.plnI("try {"); + p.pln("java.io.ObjectInput in = call.getInputStream();"); + boolean objectsRead = writeUnmarshalArguments(p, "in", + paramTypes, paramNames); + p.pOlnI("} catch (java.io.IOException e) {"); + p.pln("throw new " + idUnmarshalException + + "(\"error unmarshalling arguments\", e);"); + /* + * If any only if readObject has been invoked, we must catch + * ClassNotFoundException as well as IOException. + */ + if (objectsRead) { + p.pOlnI("} catch (java.lang.ClassNotFoundException e) {"); + p.pln("throw new " + idUnmarshalException + + "(\"error unmarshalling arguments\", e);"); + } + p.pOlnI("} finally {"); + p.pln("call.releaseInputStream();"); + p.pOln("}"); + } else { + p.pln("call.releaseInputStream();"); + } + + if (!returnType.isType(TC_VOID)) { + /* + * Declare variable to hold return type, if not void. + */ + p.p(returnType + " $result = "); // REMIND: why $? + } + + /* + * Invoke the method on the server object. + */ + p.p("server." + methodName + "("); + for (int i = 0; i < paramNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(paramNames[i]); + } + p.pln(");"); + + /* + * Always invoke getResultStream(true) on the call object to send + * the indication of a successful invocation to the caller. If + * the return type is not void, keep the result stream and marshal + * the return value. + */ + p.plnI("try {"); + if (!returnType.isType(TC_VOID)) { + p.p("java.io.ObjectOutput out = "); + } + p.pln("call.getResultStream(true);"); + if (!returnType.isType(TC_VOID)) { + writeMarshalArgument(p, "out", returnType, "$result"); + p.pln(";"); + } + p.pOlnI("} catch (java.io.IOException e) {"); + p.pln("throw new " + + idMarshalException + "(\"error marshalling return\", e);"); + p.pOln("}"); + + p.pln("break;"); // break from switch statement + + p.pOlnI("}"); // end nested block statement + p.pln(); + } + + /** + * Write declaration and initializer for "operations" static array. + */ + private void writeOperationsArray(IndentingWriter p) + throws IOException + { + p.plnI("private static final " + idOperation + "[] operations = {"); + for (int i = 0; i < remoteMethods.length; i++) { + if (i > 0) + p.pln(","); + p.p("new " + idOperation + "(\"" + + remoteMethods[i].getOperationString() + "\")"); + } + p.pln(); + p.pOln("};"); + } + + /** + * Write declaration and initializer for "interfaceHash" static field. + */ + private void writeInterfaceHash(IndentingWriter p) + throws IOException + { + p.pln("private static final long interfaceHash = " + + remoteClass.getInterfaceHash() + "L;"); + } + + /** + * Write declaration for java.lang.reflect.Method static fields + * corresponding to each remote method in a stub. + */ + private void writeMethodFieldDeclarations(IndentingWriter p) + throws IOException + { + for (int i = 0; i < methodFieldNames.length; i++) { + p.pln("private static java.lang.reflect.Method " + + methodFieldNames[i] + ";"); + } + } + + /** + * Write code to initialize the static fields for each method + * using the Java Reflection API. + */ + private void writeMethodFieldInitializers(IndentingWriter p) + throws IOException + { + for (int i = 0; i < methodFieldNames.length; i++) { + p.p(methodFieldNames[i] + " = "); + /* + * Here we look up the Method object in the arbitrary interface + * that we find in the RemoteClass.Method object. + * REMIND: Is this arbitrary choice OK? + * REMIND: Should this access be part of RemoteClass.Method's + * abstraction? + */ + RemoteClass.Method method = remoteMethods[i]; + MemberDefinition def = method.getMemberDefinition(); + Identifier methodName = method.getName(); + Type methodType = method.getType(); + Type paramTypes[] = methodType.getArgumentTypes(); + + p.p(def.getClassDefinition().getName() + ".class.getMethod(\"" + + methodName + "\", new java.lang.Class[] {"); + for (int j = 0; j < paramTypes.length; j++) { + if (j > 0) + p.p(", "); + p.p(paramTypes[j] + ".class"); + } + p.pln("});"); + } + } + + + /* + * Following are a series of static utility methods useful during + * the code generation process: + */ + + /** + * Generate an array of names for fields that correspond to the given + * array of remote methods. Each name in the returned array is + * guaranteed to be unique. + * + * The name of a method is included in its corresponding field name + * to enhance readability of the generated code. + */ + private static String[] nameMethodFields(RemoteClass.Method[] methods) { + String[] names = new String[methods.length]; + for (int i = 0; i < names.length; i++) { + names[i] = "$method_" + methods[i].getName() + "_" + i; + } + return names; + } + + /** + * Generate an array of names for parameters corresponding to the + * given array of types for the parameters. Each name in the returned + * array is guaranteed to be unique. + * + * A representation of the type of a parameter is included in its + * corresponding field name to enhance the readability of the generated + * code. + */ + private static String[] nameParameters(Type[] types) { + String[] names = new String[types.length]; + for (int i = 0; i < names.length; i++) { + names[i] = "$param_" + + generateNameFromType(types[i]) + "_" + (i + 1); + } + return names; + } + + /** + * Generate a readable string representing the given type suitable + * for embedding within a Java identifier. + */ + private static String generateNameFromType(Type type) { + int typeCode = type.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + case TC_LONG: + case TC_FLOAT: + case TC_DOUBLE: + return type.toString(); + case TC_ARRAY: + return "arrayOf_" + generateNameFromType(type.getElementType()); + case TC_CLASS: + return Names.mangleClass(type.getClassName().getName()).toString(); + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Write a snippet of Java code to marshal a value named "name" of + * type "type" to the java.io.ObjectOutput stream named "stream". + * + * Primitive types are marshalled with their corresponding methods + * in the java.io.DataOutput interface, and objects (including arrays) + * are marshalled using the writeObject method. + */ + private static void writeMarshalArgument(IndentingWriter p, + String streamName, + Type type, String name) + throws IOException + { + int typeCode = type.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + p.p(streamName + ".writeBoolean(" + name + ")"); + break; + case TC_BYTE: + p.p(streamName + ".writeByte(" + name + ")"); + break; + case TC_CHAR: + p.p(streamName + ".writeChar(" + name + ")"); + break; + case TC_SHORT: + p.p(streamName + ".writeShort(" + name + ")"); + break; + case TC_INT: + p.p(streamName + ".writeInt(" + name + ")"); + break; + case TC_LONG: + p.p(streamName + ".writeLong(" + name + ")"); + break; + case TC_FLOAT: + p.p(streamName + ".writeFloat(" + name + ")"); + break; + case TC_DOUBLE: + p.p(streamName + ".writeDouble(" + name + ")"); + break; + case TC_ARRAY: + case TC_CLASS: + p.p(streamName + ".writeObject(" + name + ")"); + break; + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Write Java statements to marshal a series of values in order as + * named in the "names" array, with types as specified in the "types" + * array", to the java.io.ObjectOutput stream named "stream". + */ + private static void writeMarshalArguments(IndentingWriter p, + String streamName, + Type[] types, String[] names) + throws IOException + { + if (types.length != names.length) { + throw new Error("paramter type and name arrays different sizes"); + } + + for (int i = 0; i < types.length; i++) { + writeMarshalArgument(p, streamName, types[i], names[i]); + p.pln(";"); + } + } + + /** + * Write a snippet of Java code to unmarshal a value of type "type" + * from the java.io.ObjectInput stream named "stream" into a variable + * named "name" (if "name" is null, the value in unmarshalled and + * discarded). + * + * Primitive types are unmarshalled with their corresponding methods + * in the java.io.DataInput interface, and objects (including arrays) + * are unmarshalled using the readObject method. + */ + private static boolean writeUnmarshalArgument(IndentingWriter p, + String streamName, + Type type, String name) + throws IOException + { + boolean readObject = false; + + if (name != null) { + p.p(name + " = "); + } + + int typeCode = type.getTypeCode(); + switch (type.getTypeCode()) { + case TC_BOOLEAN: + p.p(streamName + ".readBoolean()"); + break; + case TC_BYTE: + p.p(streamName + ".readByte()"); + break; + case TC_CHAR: + p.p(streamName + ".readChar()"); + break; + case TC_SHORT: + p.p(streamName + ".readShort()"); + break; + case TC_INT: + p.p(streamName + ".readInt()"); + break; + case TC_LONG: + p.p(streamName + ".readLong()"); + break; + case TC_FLOAT: + p.p(streamName + ".readFloat()"); + break; + case TC_DOUBLE: + p.p(streamName + ".readDouble()"); + break; + case TC_ARRAY: + case TC_CLASS: + p.p("(" + type + ") " + streamName + ".readObject()"); + readObject = true; + break; + default: + throw new Error("unexpected type code: " + typeCode); + } + return readObject; + } + + /** + * Write Java statements to unmarshal a series of values in order of + * types as in the "types" array from the java.io.ObjectInput stream + * named "stream" into variables as named in "names" (for any element + * of "names" that is null, the corresponding value is unmarshalled + * and discarded). + */ + private static boolean writeUnmarshalArguments(IndentingWriter p, + String streamName, + Type[] types, + String[] names) + throws IOException + { + if (types.length != names.length) { + throw new Error("paramter type and name arrays different sizes"); + } + + boolean readObject = false; + for (int i = 0; i < types.length; i++) { + if (writeUnmarshalArgument(p, streamName, types[i], names[i])) { + readObject = true; + } + p.pln(";"); + } + return readObject; + } + + /** + * Return a snippet of Java code to wrap a value named "name" of + * type "type" into an object as appropriate for use by the + * Java Reflection API. + * + * For primitive types, an appropriate wrapper class instantiated + * with the primitive value. For object types (including arrays), + * no wrapping is necessary, so the value is named directly. + */ + private static String wrapArgumentCode(Type type, String name) { + int typeCode = type.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + return "new java.lang.Boolean(" + name + ")"; + case TC_BYTE: + return "new java.lang.Byte(" + name + ")"; + case TC_CHAR: + return "new java.lang.Character(" + name + ")"; + case TC_SHORT: + return "new java.lang.Short(" + name + ")"; + case TC_INT: + return "new java.lang.Integer(" + name + ")"; + case TC_LONG: + return "new java.lang.Long(" + name + ")"; + case TC_FLOAT: + return "new java.lang.Float(" + name + ")"; + case TC_DOUBLE: + return "new java.lang.Double(" + name + ")"; + case TC_ARRAY: + case TC_CLASS: + return name; + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Return a snippet of Java code to unwrap a value named "name" into + * a value of type "type", as appropriate for the Java Reflection API. + * + * For primitive types, the value is assumed to be of the corresponding + * wrapper type, and a method is called on the wrapper type to retrieve + * the primitive value. For object types (include arrays), no + * unwrapping is necessary; the value is simply cast to the expected + * real object type. + */ + private static String unwrapArgumentCode(Type type, String name) { + int typeCode = type.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + return "((java.lang.Boolean) " + name + ").booleanValue()"; + case TC_BYTE: + return "((java.lang.Byte) " + name + ").byteValue()"; + case TC_CHAR: + return "((java.lang.Character) " + name + ").charValue()"; + case TC_SHORT: + return "((java.lang.Short) " + name + ").shortValue()"; + case TC_INT: + return "((java.lang.Integer) " + name + ").intValue()"; + case TC_LONG: + return "((java.lang.Long) " + name + ").longValue()"; + case TC_FLOAT: + return "((java.lang.Float) " + name + ").floatValue()"; + case TC_DOUBLE: + return "((java.lang.Double) " + name + ").doubleValue()"; + case TC_ARRAY: + case TC_CLASS: + return "((" + type + ") " + name + ")"; + default: + throw new Error("unexpected type code: " + typeCode); + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/RemoteClass.java b/src/share/classes/sun/rmi/rmic/RemoteClass.java new file mode 100644 index 000000000..b49ee6c7b --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/RemoteClass.java @@ -0,0 +1,857 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.util.Vector; +import java.util.Hashtable; +import java.util.Enumeration; +import java.io.IOException; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.security.MessageDigest; +import java.security.DigestOutputStream; +import java.security.NoSuchAlgorithmException; +import sun.tools.java.Type; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.MemberDefinition; +import sun.tools.java.Identifier; +import sun.tools.java.ClassNotFound; + +/** + * A RemoteClass object encapsulates RMI-specific information about + * a remote implementation class, i.e. a class that implements + * one or more remote interfaces. + * + * @version 1.21, 07/27/07 + * @author Peter Jones + */ +public class RemoteClass implements sun.rmi.rmic.RMIConstants { + + /** + * Create a RemoteClass object representing the remote meta-information + * of the given class. + * + * Returns true if successful. If the class is not a properly formed + * remote implementation class or if some other error occurs, the + * return value will be null, and errors will have been reported to + * the supplied BatchEnvironment. + */ + public static RemoteClass forClass(BatchEnvironment env, + ClassDefinition implClassDef) + { + RemoteClass rc = new RemoteClass(env, implClassDef); + if (rc.initialize()) { + return rc; + } else { + return null; + } + } + + /** + * Return the ClassDefinition for this class. + */ + public ClassDefinition getClassDefinition() { + return implClassDef; + } + + /** + * Return the name of the class represented by this object. + */ + public Identifier getName() { + return implClassDef.getName(); + } + + /** + * Return an array of ClassDefinitions representing all of the remote + * interfaces implemented by this class. + * + * A remote interface is any interface that extends Remote, + * directly or indirectly. The remote interfaces of a class + * are the interfaces directly listed in either the class's + * "implements" clause, or the "implements" clause of any + * of its superclasses, that are remote interfaces. + * + * The order of the array returned is arbitrary, and some elements + * may be superfluous (i.e., superinterfaces of other interfaces + * in the array). + */ + public ClassDefinition[] getRemoteInterfaces() { + return (ClassDefinition[]) remoteInterfaces.clone(); + } + + /** + * Return an array of RemoteClass.Method objects representing all of + * the remote methods implemented by this class, i.e. all of the + * methods in the class's remote interfaces. + * + * The methods in the array are ordered according to the comparision + * of the strings consisting of their method name followed by their + * type signature, so each method's index in the array corresponds + * to its "operation number" in the JDK 1.1 version of the + * stub/skeleton protocol. + */ + public Method[] getRemoteMethods() { + return (Method[]) remoteMethods.clone(); + } + + /** + * Return the "interface hash" used to match a stub/skeleton pair for + * this class in the JDK 1.1 version of the stub/skeleton protocol. + */ + public long getInterfaceHash() { + return interfaceHash; + } + + /** + * Return string representation of this object, consisting of + * the string "remote class " followed by the class name. + */ + public String toString() { + return "remote class " + implClassDef.getName().toString(); + } + + /** rmic environment for this object */ + private BatchEnvironment env; + + /** the remote implementation class this object corresponds to */ + private ClassDefinition implClassDef; + + /** remote interfaces implemented by this class */ + private ClassDefinition[] remoteInterfaces; + + /** all the remote methods of this class */ + private Method[] remoteMethods; + + /** stub/skeleton "interface hash" for this class */ + private long interfaceHash; + + /** cached definition for certain classes used in this environment */ + private ClassDefinition defRemote; + private ClassDefinition defException; + private ClassDefinition defRemoteException; + + /** + * Create a RemoteClass instance for the given class. The resulting + * object is not yet initialized. + */ + private RemoteClass(BatchEnvironment env, ClassDefinition implClassDef) { + this.env = env; + this.implClassDef = implClassDef; + } + + /** + * Validate that the remote implementation class is properly formed + * and fill in the data structures required by the public interface. + */ + private boolean initialize() { + /* + * Verify that the "impl" is really a class, not an interface. + */ + if (implClassDef.isInterface()) { + env.error(0, "rmic.cant.make.stubs.for.interface", + implClassDef.getName()); + return false; + } + + /* + * Initialize cached definitions for the Remote interface and + * the RemoteException class. + */ + try { + defRemote = + env.getClassDeclaration(idRemote).getClassDefinition(env); + defException = + env.getClassDeclaration(idJavaLangException). + getClassDefinition(env); + defRemoteException = + env.getClassDeclaration(idRemoteException). + getClassDefinition(env); + } catch (ClassNotFound e) { + env.error(0, "rmic.class.not.found", e.name); + return false; + } + + /* + * Here we find all of the remote interfaces of our remote + * implementation class. For each class up the superclass + * chain, add each directly-implemented interface that + * somehow extends Remote to a list. + */ + Vector remotesImplemented = // list of remote interfaces found + new Vector(); + for (ClassDefinition classDef = implClassDef; + classDef != null;) + { + try { + ClassDeclaration[] interfaces = classDef.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + ClassDefinition interfaceDef = + interfaces[i].getClassDefinition(env); + /* + * Add interface to the list if it extends Remote and + * it is not already there. + */ + if (!remotesImplemented.contains(interfaceDef) && + defRemote.implementedBy(env, interfaces[i])) + { + remotesImplemented.addElement(interfaceDef); + /***** */ + if (env.verbose()) { + System.out.println("[found remote interface: " + + interfaceDef.getName() + "]"); + /***** */ + } + } + } + + /* + * Verify that the candidate remote implementation class + * implements at least one remote interface directly. + */ + if (classDef == implClassDef && remotesImplemented.isEmpty()) { + if (defRemote.implementedBy(env, + implClassDef.getClassDeclaration())) + { + /* + * This error message is used if the class does + * implement a remote interface through one of + * its superclasses, but not directly. + */ + env.error(0, "rmic.must.implement.remote.directly", + implClassDef.getName()); + } else { + /* + * This error message is used if the class never + * implements a remote interface. + */ + env.error(0, "rmic.must.implement.remote", + implClassDef.getName()); + } + return false; + } + + /* + * Get definition for next superclass. + */ + classDef = (classDef.getSuperClass() != null ? + classDef.getSuperClass().getClassDefinition(env) : + null); + + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, classDef.getName()); + return false; + } + } + + /* + * The "remotesImplemented" vector now contains all of the remote + * interfaces directly implemented by the remote class or by any + * of its superclasses. + * + * At this point, we could optimize the list by removing superfluous + * entries, i.e. any interfaces that are implemented by some other + * interface in the list anyway. + * + * This should be correct; would it be worthwhile? + * + * for (int i = 0; i < remotesImplemented.size();) { + * ClassDefinition interfaceDef = + * (ClassDefinition) remotesImplemented.elementAt(i); + * boolean isOtherwiseImplemented = false; + * for (int j = 0; j < remotesImplemented.size; j++) { + * if (j != i && + * interfaceDef.implementedBy(env, (ClassDefinition) + * remotesImplemented.elementAt(j). + * getClassDeclaration())) + * { + * isOtherwiseImplemented = true; + * break; + * } + * } + * if (isOtherwiseImplemented) { + * remotesImplemented.removeElementAt(i); + * } else { + * ++i; + * } + * } + */ + + /* + * Now we collect the methods from all of the remote interfaces + * into a hashtable. + */ + Hashtable methods = new Hashtable(); + boolean errors = false; + for (Enumeration enumeration = remotesImplemented.elements(); + enumeration.hasMoreElements();) + { + ClassDefinition interfaceDef = + (ClassDefinition) enumeration.nextElement(); + if (!collectRemoteMethods(interfaceDef, methods)) + errors = true; + } + if (errors) + return false; + + /* + * Convert vector of remote interfaces to an array + * (order is not important for this array). + */ + remoteInterfaces = new ClassDefinition[remotesImplemented.size()]; + remotesImplemented.copyInto(remoteInterfaces); + + /* + * Sort table of remote methods into an array. The elements are + * sorted in ascending order of the string of the method's name + * and type signature, so that each elements index is equal to + * its operation number of the JDK 1.1 version of the stub/skeleton + * protocol. + */ + String[] orderedKeys = new String[methods.size()]; + int count = 0; + for (Enumeration enumeration = methods.elements(); + enumeration.hasMoreElements();) + { + Method m = (Method) enumeration.nextElement(); + String key = m.getNameAndDescriptor(); + int i; + for (i = count; i > 0; --i) { + if (key.compareTo(orderedKeys[i - 1]) >= 0) { + break; + } + orderedKeys[i] = orderedKeys[i - 1]; + } + orderedKeys[i] = key; + ++count; + } + remoteMethods = new Method[methods.size()]; + for (int i = 0; i < remoteMethods.length; i++) { + remoteMethods[i] = (Method) methods.get(orderedKeys[i]); + /***** */ + if (env.verbose()) { + System.out.print("[found remote method <" + i + ">: " + + remoteMethods[i].getOperationString()); + ClassDeclaration[] exceptions = + remoteMethods[i].getExceptions(); + if (exceptions.length > 0) + System.out.print(" throws "); + for (int j = 0; j < exceptions.length; j++) { + if (j > 0) + System.out.print(", "); + System.out.print(exceptions[j].getName()); + } + System.out.println("]"); + } + /***** */ + } + + /** + * Finally, pre-compute the interface hash to be used by + * stubs/skeletons for this remote class. + */ + interfaceHash = computeInterfaceHash(); + + return true; + } + + /** + * Collect and validate all methods from given interface and all of + * its superinterfaces as remote methods. Remote methods are added + * to the supplied hashtable. Returns true if successful, + * or false if an error occurred. + */ + private boolean collectRemoteMethods(ClassDefinition interfaceDef, + Hashtable table) + { + if (!interfaceDef.isInterface()) { + throw new Error( + "expected interface, not class: " + interfaceDef.getName()); + } + + /* + * rmic used to enforce that a remote interface could not extend + * a non-remote interface, i.e. an interface that did not itself + * extend from Remote. The current version of rmic does not have + * this restriction, so the following code is now commented out. + * + * Verify that this interface extends Remote, since all interfaces + * extended by a remote interface must implement Remote. + * + * try { + * if (!defRemote.implementedBy(env, + * interfaceDef.getClassDeclaration())) + * { + * env.error(0, "rmic.can.mix.remote.nonremote", + * interfaceDef.getName()); + * return false; + * } + * } catch (ClassNotFound e) { + * env.error(0, "class.not.found", e.name, + * interfaceDef.getName()); + * return false; + * } + */ + + boolean errors = false; + + /* + * Search interface's members for methods. + */ + nextMember: + for (MemberDefinition member = interfaceDef.getFirstMember(); + member != null; + member = member.getNextMember()) + { + if (member.isMethod() && + !member.isConstructor() && !member.isInitializer()) + { + /* + * Verify that each method throws RemoteException. + */ + ClassDeclaration[] exceptions = member.getExceptions(env); + boolean hasRemoteException = false; + for (int i = 0; i < exceptions.length; i++) { + /* + * rmic used to enforce that a remote method had to + * explicitly list RemoteException in its "throws" + * clause; i.e., just throwing Exception was not + * acceptable. The current version of rmic does not + * have this restriction, so the following code is + * now commented out. Instead, the method is + * considered valid if RemoteException is a subclass + * of any of the methods declared exceptions. + * + * if (exceptions[i].getName().equals( + * idRemoteException)) + * { + * hasRemoteException = true; + * break; + * } + */ + try { + if (defRemoteException.subClassOf( + env, exceptions[i])) + { + hasRemoteException = true; + break; + } + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + interfaceDef.getName()); + continue nextMember; + } + } + /* + * If this method did not throw RemoteException as required, + * generate the error but continue, so that multiple such + * errors can be reported. + */ + if (!hasRemoteException) { + env.error(0, "rmic.must.throw.remoteexception", + interfaceDef.getName(), member.toString()); + errors = true; + continue nextMember; + } + + /* + * Verify that the implementation of this method throws only + * java.lang.Exception or its subclasses (fix bugid 4092486). + * JRMP does not support remote methods throwing + * java.lang.Throwable or other subclasses. + */ + try { + MemberDefinition implMethod = implClassDef.findMethod( + env, member.getName(), member.getType()); + if (implMethod != null) { // should not be null + exceptions = implMethod.getExceptions(env); + for (int i = 0; i < exceptions.length; i++) { + if (!defException.superClassOf( + env, exceptions[i])) + { + env.error(0, "rmic.must.only.throw.exception", + implMethod.toString(), + exceptions[i].getName()); + errors = true; + continue nextMember; + } + } + } + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + implClassDef.getName()); + continue nextMember; + } + + /* + * Create RemoteClass.Method object to represent this method + * found in a remote interface. + */ + Method newMethod = new Method(member); + /* + * Store remote method's representation in the table of + * remote methods found, keyed by its name and parameter + * signature. + * + * If the table already contains an entry with the same + * method name and parameter signature, then we must + * replace the old entry with a Method object that + * represents a legal combination of the old and the new + * methods; specifically, the combined method must have + * a throws list that contains (only) all of the checked + * exceptions that can be thrown by both the old or + * the new method (see bugid 4070653). + */ + String key = newMethod.getNameAndDescriptor(); + Method oldMethod = (Method) table.get(key); + if (oldMethod != null) { + newMethod = newMethod.mergeWith(oldMethod); + if (newMethod == null) { + errors = true; + continue nextMember; + } + } + table.put(key, newMethod); + } + } + + /* + * Recursively collect methods for all superinterfaces. + */ + try { + ClassDeclaration[] superDefs = interfaceDef.getInterfaces(); + for (int i = 0; i < superDefs.length; i++) { + ClassDefinition superDef = + superDefs[i].getClassDefinition(env); + if (!collectRemoteMethods(superDef, table)) + errors = true; + } + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, interfaceDef.getName()); + return false; + } + + return !errors; + } + + /** + * Compute the "interface hash" of the stub/skeleton pair for this + * remote implementation class. This is the 64-bit value used to + * enforce compatibility between a stub and a skeleton using the + * JDK 1.1 version of the stub/skeleton protocol. + * + * It is calculated using the first 64 bits of a SHA digest. The + * digest is from a stream consisting of the following data: + * (int) stub version number, always 1 + * for each remote method, in order of operation number: + * (UTF) method name + * (UTF) method type signature + * for each declared exception, in alphabetical name order: + * (UTF) name of exception class + * + */ + private long computeInterfaceHash() { + long hash = 0; + ByteArrayOutputStream sink = new ByteArrayOutputStream(512); + try { + MessageDigest md = MessageDigest.getInstance("SHA"); + DataOutputStream out = new DataOutputStream( + new DigestOutputStream(sink, md)); + + out.writeInt(INTERFACE_HASH_STUB_VERSION); + for (int i = 0; i < remoteMethods.length; i++) { + MemberDefinition m = remoteMethods[i].getMemberDefinition(); + Identifier name = m.getName(); + Type type = m.getType(); + + out.writeUTF(name.toString()); + // type signatures already use mangled class names + out.writeUTF(type.getTypeSignature()); + + ClassDeclaration exceptions[] = m.getExceptions(env); + sortClassDeclarations(exceptions); + for (int j = 0; j < exceptions.length; j++) { + out.writeUTF(Names.mangleClass( + exceptions[j].getName()).toString()); + } + } + out.flush(); + + // use only the first 64 bits of the digest for the hash + byte hashArray[] = md.digest(); + for (int i = 0; i < Math.min(8, hashArray.length); i++) { + hash += ((long) (hashArray[i] & 0xFF)) << (i * 8); + } + } catch (IOException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } catch (NoSuchAlgorithmException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } + + return hash; + } + + /** + * Sort array of class declarations alphabetically by their mangled + * fully-qualfied class name. This is used to feed a method's exceptions + * in a canonical order into the digest stream for the interface hash + * computation. + */ + private void sortClassDeclarations(ClassDeclaration[] decl) { + for (int i = 1; i < decl.length; i++) { + ClassDeclaration curr = decl[i]; + String name = Names.mangleClass(curr.getName()).toString(); + int j; + for (j = i; j > 0; j--) { + if (name.compareTo( + Names.mangleClass(decl[j - 1].getName()).toString()) >= 0) + { + break; + } + decl[j] = decl[j - 1]; + } + decl[j] = curr; + } + } + + + /** + * A RemoteClass.Method object encapsulates RMI-specific information + * about a particular remote method in the remote implementation class + * represented by the outer instance. + */ + public class Method implements Cloneable { + + /** + * Return the definition of the actual class member corresponing + * to this method of a remote interface. + * + * REMIND: Can this method be removed? + */ + public MemberDefinition getMemberDefinition() { + return memberDef; + } + + /** + * Return the name of this method. + */ + public Identifier getName() { + return memberDef.getName(); + } + + /** + * Return the type of this method. + */ + public Type getType() { + return memberDef.getType(); + } + + /** + * Return an array of the exception classes declared to be + * thrown by this remote method. + * + * For methods with the same name and type signature inherited + * from multiple remote interfaces, the array will contain + * the set of exceptions declared in all of the interfaces' + * methods that can be legally thrown in each of them. + */ + public ClassDeclaration[] getExceptions() { + return (ClassDeclaration[]) exceptions.clone(); + } + + /** + * Return the "method hash" used to identify this remote method + * in the JDK 1.2 version of the stub protocol. + */ + public long getMethodHash() { + return methodHash; + } + + /** + * Return the string representation of this method. + */ + public String toString() { + return memberDef.toString(); + } + + /** + * Return the string representation of this method appropriate + * for the construction of a java.rmi.server.Operation object. + */ + public String getOperationString() { + return memberDef.toString(); + } + + /** + * Return a string consisting of this method's name followed by + * its method descriptor, using the Java VM's notation for + * method descriptors (see section 4.3.3 of The Java Virtual + * Machine Specification). + */ + public String getNameAndDescriptor() { + return memberDef.getName().toString() + + memberDef.getType().getTypeSignature(); + } + + /** + * Member definition for this method, from one of the remote + * interfaces that this method was found in. + * + * Note that this member definition may be only one of several + * member defintions that correspond to this remote method object, + * if several of this class's remote interfaces contain methods + * with the same name and type signature. Therefore, this member + * definition may declare more exceptions thrown that this remote + * method does. + */ + private MemberDefinition memberDef; + + /** stub "method hash" to identify this method */ + private long methodHash; + + /** + * Exceptions declared to be thrown by this remote method. + * + * This list can include superfluous entries, such as + * unchecked exceptions and subclasses of other entries. + */ + private ClassDeclaration[] exceptions; + + /** + * Create a new Method object corresponding to the given + * method definition. + */ + /* + * Temporarily comment out the private modifier until + * the VM allows outer class to access inner class's + * private constructor + */ + /* private */ Method(MemberDefinition memberDef) { + this.memberDef = memberDef; + exceptions = memberDef.getExceptions(env); + methodHash = computeMethodHash(); + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + + /** + * Return a new Method object that is a legal combination of + * this method object and another one. + * + * This requires determining the exceptions declared by the + * combined method, which must be (only) all of the exceptions + * declared in both old Methods that may thrown in either of + * them. + */ + private Method mergeWith(Method other) { + if (!getName().equals(other.getName()) || + !getType().equals(other.getType())) + { + throw new Error("attempt to merge method \"" + + other.getNameAndDescriptor() + "\" with \"" + + getNameAndDescriptor()); + } + + Vector legalExceptions = new Vector(); + try { + collectCompatibleExceptions( + other.exceptions, exceptions, legalExceptions); + collectCompatibleExceptions( + exceptions, other.exceptions, legalExceptions); + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + getClassDefinition().getName()); + return null; + } + + Method merged = (Method) clone(); + merged.exceptions = new ClassDeclaration[legalExceptions.size()]; + legalExceptions.copyInto(merged.exceptions); + + return merged; + } + + /** + * Add to the supplied list all exceptions in the "from" array + * that are subclasses of an exception in the "with" array. + */ + private void collectCompatibleExceptions(ClassDeclaration[] from, + ClassDeclaration[] with, + Vector list) + throws ClassNotFound + { + for (int i = 0; i < from.length; i++) { + ClassDefinition exceptionDef = from[i].getClassDefinition(env); + if (!list.contains(from[i])) { + for (int j = 0; j < with.length; j++) { + if (exceptionDef.subClassOf(env, with[j])) { + list.addElement(from[i]); + break; + } + } + } + } + } + + /** + * Compute the "method hash" of this remote method. The method + * hash is a long containing the first 64 bits of the SHA digest + * from the UTF encoded string of the method name and descriptor. + * + * REMIND: Should this method share implementation code with + * the outer class's computeInterfaceHash() method? + */ + private long computeMethodHash() { + long hash = 0; + ByteArrayOutputStream sink = new ByteArrayOutputStream(512); + try { + MessageDigest md = MessageDigest.getInstance("SHA"); + DataOutputStream out = new DataOutputStream( + new DigestOutputStream(sink, md)); + + String methodString = getNameAndDescriptor(); + /***** */ + if (env.verbose()) { + System.out.println("[string used for method hash: \"" + + methodString + "\"]"); + } + /***** */ + out.writeUTF(methodString); + + // use only the first 64 bits of the digest for the hash + out.flush(); + byte hashArray[] = md.digest(); + for (int i = 0; i < Math.min(8, hashArray.length); i++) { + hash += ((long) (hashArray[i] & 0xFF)) << (i * 8); + } + } catch (IOException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } catch (NoSuchAlgorithmException e) { + throw new Error( + "unexpected exception computing intetrface hash: " + e); + } + + return hash; + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/Util.java b/src/share/classes/sun/rmi/rmic/Util.java new file mode 100644 index 000000000..2f064077a --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/Util.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic; + +import java.io.File; +import sun.tools.java.Identifier; + +/** + * Util provides static utility methods used by other rmic classes. + * @author Bryan Atsatt + */ + +public class Util implements sun.rmi.rmic.Constants { + + /** + * Return the directory that should be used for output for a given + * class. + * @param theClass The fully qualified name of the class. + * @param rootDir The directory to use as the root of the + * package heirarchy. May be null, in which case the current + * working directory is used as the root. + */ + public static File getOutputDirectoryFor(Identifier theClass, + File rootDir, + BatchEnvironment env) { + + File outputDir = null; + String className = theClass.getFlatName().toString().replace('.', SIGC_INNERCLASS); + String qualifiedClassName = className; + String packagePath = null; + String packageName = theClass.getQualifier().toString(); + + if (packageName.length() > 0) { + qualifiedClassName = packageName + "." + className; + packagePath = packageName.replace('.', File.separatorChar); + } + + // Do we have a root directory? + + if (rootDir != null) { + + // Yes, do we have a package name? + + if (packagePath != null) { + + // Yes, so use it as the root. Open the directory... + + outputDir = new File(rootDir, packagePath); + + // Make sure the directory exists... + + ensureDirectory(outputDir,env); + + } else { + + // Default package, so use root as output dir... + + outputDir = rootDir; + } + } else { + + // No root directory. Get the current working directory... + + String workingDirPath = System.getProperty("user.dir"); + File workingDir = new File(workingDirPath); + + // Do we have a package name? + + if (packagePath == null) { + + // No, so use working directory... + + outputDir = workingDir; + + } else { + + // Yes, so use working directory as the root... + + outputDir = new File(workingDir, packagePath); + + // Make sure the directory exists... + + ensureDirectory(outputDir,env); + } + } + + // Finally, return the directory... + + return outputDir; + } + + private static void ensureDirectory (File dir, BatchEnvironment env) { + if (!dir.exists()) { + dir.mkdirs(); + if (!dir.exists()) { + env.error(0,"rmic.cannot.create.dir",dir.getAbsolutePath()); + throw new InternalError(); + } + } + } +} + diff --git a/src/share/classes/sun/rmi/rmic/iiop/AbstractType.java b/src/share/classes/sun/rmi/rmic/iiop/AbstractType.java new file mode 100644 index 000000000..9ec117ecc --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/AbstractType.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; + +/** + * AbstractType represents any non-special interface which does not + * inherit from java.rmi.Remote, for which all methods throw RemoteException. + *

                + * The static forAbstract(...) method must be used to obtain an instance, and will + * return null if the ClassDefinition is non-conforming. + * @version 1.0, 2/25/98 + * @author Bryan Atsatt + */ +public class AbstractType extends RemoteType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an AbstractType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static AbstractType forAbstract(ClassDefinition classDef, + ContextStack stack, + boolean quiet) + { + boolean doPop = false; + AbstractType result = null; + + try { + + // Do we already have it? + + sun.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof AbstractType)) return null; // False hit. + + // Yep, so return it... + + return (AbstractType) existing; + + } + + // Could this be an abstract? + + if (couldBeAbstract(stack,classDef,quiet)) { + + // Yes, so try it... + + AbstractType it = new AbstractType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(quiet,stack)) { + stack.pop(true); + result = it; + } else { + removeType(theType,stack); + stack.pop(false); + } + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + } + + return result; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Abstract interface"; + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a AbstractType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private AbstractType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_ABSTRACT | TM_INTERFACE | TM_COMPOUND); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + + private static boolean couldBeAbstract(ContextStack stack, ClassDefinition classDef, + boolean quiet) { + + // Return true if interface and not remote... + + boolean result = false; + + if (classDef.isInterface()) { + BatchEnvironment env = stack.getEnv(); + + try { + result = ! env.defRemote.implementedBy(env, classDef.getClassDeclaration()); + if (!result) failedConstraint(15,quiet,stack,classDef.getName()); + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } else { + failedConstraint(14,quiet,stack,classDef.getName()); + } + + + return result; + } + + + /** + * Initialize this instance. + */ + private boolean initialize (boolean quiet,ContextStack stack) { + + boolean result = false; + ClassDefinition self = getClassDefinition(); + + try { + + // Get methods... + + Vector directMethods = new Vector(); + + if (addAllMethods(self,directMethods,true,quiet,stack) != null) { + + // Do we have any methods? + + boolean validMethods = true; + + if (directMethods.size() > 0) { + + // Yes. Walk 'em, ensuring each is a valid remote method... + + for (int i = 0; i < directMethods.size(); i++) { + + if (! isConformingRemoteMethod((Method) directMethods.elementAt(i),true)) { + validMethods = false; + } + } + } + + if (validMethods) { + + // We're ok, so pass 'em up... + + result = initialize(null,directMethods,null,stack,quiet); + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/ArrayType.java b/src/share/classes/sun/rmi/rmic/iiop/ArrayType.java new file mode 100644 index 000000000..535580bab --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ArrayType.java @@ -0,0 +1,250 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import java.util.HashSet; +import sun.tools.java.CompilerError; +import sun.tools.java.Identifier; +import sun.tools.java.ClassDefinition; +import java.lang.reflect.Array; + +/** + * ArrayType is a wrapper for any of the other types. The getElementType() + * method can be used to get the array element type. The getArrayDimension() + * method can be used to get the array dimension. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public class ArrayType extends Type { + + private Type type; + private int arrayDimension; + private String brackets; + private String bracketsSig; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an ArrayType object for the given type. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static ArrayType forArray( sun.tools.java.Type theType, + ContextStack stack) { + + + ArrayType result = null; + sun.tools.java.Type arrayType = theType; + + if (arrayType.getTypeCode() == TC_ARRAY) { + + // Find real type... + + while (arrayType.getTypeCode() == TC_ARRAY) { + arrayType = arrayType.getElementType(); + } + + // Do we already have it? + + Type existing = getType(theType,stack); + if (existing != null) { + + if (!(existing instanceof ArrayType)) return null; // False hit. + + // Yep, so return it... + + return (ArrayType) existing; + } + + // Now try to make a Type from it... + + Type temp = CompoundType.makeType(arrayType,null,stack); + + if (temp != null) { + + // Got a valid one. Make an array type... + + result = new ArrayType(stack,temp,theType.getArrayDimension()); + + // Add it... + + putType(theType,result,stack); + + // Do the stack thing in case tracing on... + + stack.push(result); + stack.pop(true); + } + } + + return result; + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public String getSignature() { + return bracketsSig + type.getSignature(); + } + + /** + * Get element type. Returns null if not an array. + */ + public Type getElementType () { + return type; + } + + /** + * Get array dimension. Returns zero if not an array. + */ + public int getArrayDimension () { + return arrayDimension; + } + + /** + * Get brackets string. Returns "" if not an array. + */ + public String getArrayBrackets () { + return brackets; + } + + /** + * Return a string representation of this type. + */ + public String toString () { + return getQualifiedName() + brackets; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Array of " + type.getTypeDescription(); + } + + + /** + * Return the name of this type. For arrays, will include "[]" if useIDLNames == false. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public String getTypeName ( boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) { + if (useIDLNames) { + return super.getTypeName(useQualifiedNames,useIDLNames,globalIDLNames); + } else { + return super.getTypeName(useQualifiedNames,useIDLNames,globalIDLNames) + brackets; + } + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + if (type.getStatus() != STATUS_VALID) { + type = getValidType(type); + } + } + + /* + * Add matching types to list. Return true if this type has not + * been previously checked, false otherwise. + */ + protected boolean addTypes (int typeCodeFilter, + HashSet checked, + Vector matching) { + + // Check self. + + boolean result = super.addTypes(typeCodeFilter,checked,matching); + + // Have we been checked before? + + if (result) { + + // No, so add element type... + + getElementType().addTypes(typeCodeFilter,checked,matching); + } + + return result; + } + + /** + * Create an ArrayType instance for the given type. The resulting + * object is not yet completely initialized. + */ + private ArrayType(ContextStack stack, Type type, int arrayDimension) { + super(stack,TYPE_ARRAY); + this.type = type; + this.arrayDimension = arrayDimension; + + // Create our brackets string... + + brackets = ""; + bracketsSig = ""; + for (int i = 0; i < arrayDimension; i ++) { + brackets += "[]"; + bracketsSig += "["; + } + + // Now set our names... + + String idlName = IDLNames.getArrayName(type,arrayDimension); + String[] module = IDLNames.getArrayModuleNames(type); + setNames(type.getIdentifier(),module,idlName); + + // Set our repositoryID... + + setRepositoryID(); + } + + + /* + * Load a Class instance. Return null if fail. + */ + protected Class loadClass() { + Class result = null; + Class elementClass = type.getClassInstance(); + if (elementClass != null) { + result = Array.newInstance(elementClass, new int[arrayDimension]).getClass(); + } + return result; + } + + /** + * Release all resources + */ + protected void destroy () { + super.destroy(); + if (type != null) { + type.destroy(); + type = null; + } + brackets = null; + bracketsSig = null; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/BatchEnvironment.java b/src/share/classes/sun/rmi/rmic/iiop/BatchEnvironment.java new file mode 100644 index 000000000..6cb025562 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/BatchEnvironment.java @@ -0,0 +1,239 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.rmi.rmic.Main; +import sun.tools.java.ClassPath; +import java.io.OutputStream; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.Identifier; +import sun.tools.java.ClassNotFound; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Enumeration; +import java.util.Iterator; + +/** + * BatchEnvironment for iiop extends rmic's version to add + * parse state. + */ +public class BatchEnvironment extends sun.rmi.rmic.BatchEnvironment implements Constants { + + /* + * If the following flag is true, then the IDL generator can map + * the methods and constants of non-conforming types. However, + * this is very expensive, so the default should be false. + */ + private boolean parseNonConforming = false; + + /** + * This flag indicates that the stubs and ties need to be generated without + * the package prefix (org.omg.stub). + */ + private boolean standardPackage; + + /* Common objects used within package */ + + HashSet alreadyChecked = new HashSet(); + Hashtable allTypes = new Hashtable(3001, 0.5f); + Hashtable invalidTypes = new Hashtable(256, 0.5f); + DirectoryLoader loader = null; + ClassPathLoader classPathLoader = null; + Hashtable nameContexts = null; + Hashtable namesCache = new Hashtable(); + NameContext modulesContext = new NameContext(false); + + ClassDefinition defRemote = null; + ClassDefinition defError = null; + ClassDefinition defException = null; + ClassDefinition defRemoteException = null; + ClassDefinition defCorbaObject = null; + ClassDefinition defSerializable = null; + ClassDefinition defExternalizable = null; + ClassDefinition defThrowable = null; + ClassDefinition defRuntimeException = null; + ClassDefinition defIDLEntity = null; + ClassDefinition defValueBase = null; + + sun.tools.java.Type typeRemoteException = null; + sun.tools.java.Type typeIOException = null; + sun.tools.java.Type typeException = null; + sun.tools.java.Type typeThrowable = null; + + ContextStack contextStack = null; + + /** + * Create a BatchEnvironment for rmic with the given class path, + * stream for messages and Main. + */ + public BatchEnvironment(OutputStream out, ClassPath path, Main main) { + + super(out,path,main); + + // Make sure we have our definitions... + + try { + defRemote = + getClassDeclaration(idRemote).getClassDefinition(this); + defError = + getClassDeclaration(idJavaLangError).getClassDefinition(this); + defException = + getClassDeclaration(idJavaLangException).getClassDefinition(this); + defRemoteException = + getClassDeclaration(idRemoteException).getClassDefinition(this); + defCorbaObject = + getClassDeclaration(idCorbaObject).getClassDefinition(this); + defSerializable = + getClassDeclaration(idJavaIoSerializable).getClassDefinition(this); + defRuntimeException = + getClassDeclaration(idJavaLangRuntimeException).getClassDefinition(this); + defExternalizable = + getClassDeclaration(idJavaIoExternalizable).getClassDefinition(this); + defThrowable= + getClassDeclaration(idJavaLangThrowable).getClassDefinition(this); + defIDLEntity= + getClassDeclaration(idIDLEntity).getClassDefinition(this); + defValueBase= + getClassDeclaration(idValueBase).getClassDefinition(this); + typeRemoteException = defRemoteException.getClassDeclaration().getType(); + typeException = defException.getClassDeclaration().getType(); + typeIOException = getClassDeclaration(idJavaIoIOException).getType(); + typeThrowable = getClassDeclaration(idJavaLangThrowable).getType(); + + classPathLoader = new ClassPathLoader(path); + + } catch (ClassNotFound e) { + error(0, "rmic.class.not.found", e.name); + throw new Error(); + } + } + + /** + * Return whether or not to parse non-conforming types. + */ + public boolean getParseNonConforming () { + return parseNonConforming; + } + + /** + * Set whether or not to parse non-conforming types. + */ + public void setParseNonConforming (boolean parseEm) { + + // If we are transitioning from not parsing to + // parsing, we need to throw out any previously + // parsed types... + + if (parseEm && !parseNonConforming) { + reset(); + } + + parseNonConforming = parseEm; + } + + void setStandardPackage(boolean standardPackage) { + this.standardPackage = standardPackage; + } + + boolean getStandardPackage() { + return standardPackage; + } + + /** + * Clear out any data from previous executions. + */ + public void reset () { + + // First, find all Type instances and call destroy() + // on them... + + for (Enumeration e = allTypes.elements() ; e.hasMoreElements() ;) { + Type type = (Type) e.nextElement(); + type.destroy(); + } + + for (Enumeration e = invalidTypes.keys() ; e.hasMoreElements() ;) { + Type type = (Type) e.nextElement(); + type.destroy(); + } + + for (Iterator e = alreadyChecked.iterator() ; e.hasNext() ;) { + Type type = (Type) e.next(); + type.destroy(); + } + + if (contextStack != null) contextStack.clear(); + + // Remove and clear all NameContexts in the + // nameContexts cache... + + if (nameContexts != null) { + for (Enumeration e = nameContexts.elements() ; e.hasMoreElements() ;) { + NameContext context = (NameContext) e.nextElement(); + context.clear(); + } + nameContexts.clear(); + } + + // Now remove all table entries... + + allTypes.clear(); + invalidTypes.clear(); + alreadyChecked.clear(); + namesCache.clear(); + modulesContext.clear(); + + // Clean up remaining... + loader = null; + parseNonConforming = false; + + // REVISIT - can't clean up classPathLoader here + } + + /** + * Release resources, if any. + */ + public void shutdown() { + if (alreadyChecked != null) { + //System.out.println(); + //System.out.println("allTypes.size() = "+ allTypes.size()); + //System.out.println(" InstanceCount before reset = "+Type.instanceCount); + reset(); + //System.out.println(" InstanceCount AFTER reset = "+Type.instanceCount); + + alreadyChecked = null; + allTypes = null; + invalidTypes = null; + nameContexts = null; + namesCache = null; + modulesContext = null; + defRemote = null; + defError = null; + defException = null; + defRemoteException = null; + defCorbaObject = null; + defSerializable = null; + defExternalizable = null; + defThrowable = null; + defRuntimeException = null; + defIDLEntity = null; + defValueBase = null; + typeRemoteException = null; + typeIOException = null; + typeException = null; + typeThrowable = null; + + super.shutdown(); + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/ClassPathLoader.java b/src/share/classes/sun/rmi/rmic/iiop/ClassPathLoader.java new file mode 100644 index 000000000..c281e67f6 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ClassPathLoader.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.*; +import sun.tools.java.ClassPath ; +import sun.tools.java.ClassFile ; + +/** + * A ClassLoader that will ultimately use a given sun.tools.java.ClassPath to + * find the desired file. This works for any JAR files specified in the given + * ClassPath as well -- reusing all of that wonderful sun.tools.java code. + * + *@author Everett Anderson + */ +public class ClassPathLoader extends ClassLoader +{ + private ClassPath classPath; + + public ClassPathLoader(ClassPath classPath) { + this.classPath = classPath; + } + + // Called by the super class + protected Class findClass(String name) throws ClassNotFoundException + { + byte[] b = loadClassData(name); + return defineClass(name, b, 0, b.length); + } + + /** + * Load the class with the given fully qualified name from the ClassPath. + */ + private byte[] loadClassData(String className) + throws ClassNotFoundException + { + // Build the file name and subdirectory from the + // class name + String filename = className.replace('.', File.separatorChar) + + ".class"; + + // Have ClassPath find the file for us, and wrap it in a + // ClassFile. Note: This is where it looks inside jar files that + // are specified in the path. + ClassFile classFile = classPath.getFile(filename); + + if (classFile != null) { + + // Provide the most specific reason for failure in addition + // to ClassNotFound + Exception reportedError = null; + byte data[] = null; + + try { + // ClassFile is beautiful because it shields us from + // knowing if it's a separate file or an entry in a + // jar file. + DataInputStream input + = new DataInputStream(classFile.getInputStream()); + + // Can't rely on input available() since it will be + // something unusual if it's a jar file! May need + // to worry about a possible problem if someone + // makes a jar file entry with a size greater than + // max int. + data = new byte[(int)classFile.length()]; + + try { + input.readFully(data); + } catch (IOException ex) { + // Something actually went wrong reading the file. This + // is a real error so save it to report it. + data = null; + reportedError = ex; + } finally { + // Just don't care if there's an exception on close! + // I hate that close can throw an IOException! + try { input.close(); } catch (IOException ex) {} + } + } catch (IOException ex) { + // Couldn't get the input stream for the file. This is + // probably also a real error. + reportedError = ex; + } + + if (data == null) + throw new ClassNotFoundException(className, reportedError); + + return data; + } + + // Couldn't find the file in the class path. + throw new ClassNotFoundException(className); + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/ClassType.java b/src/share/classes/sun/rmi/rmic/iiop/ClassType.java new file mode 100644 index 000000000..45d442d63 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ClassType.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.tools.java.CompilerError; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.ClassDefinition; +import sun.rmi.rmic.IndentingWriter; +import java.io.IOException; + +/** + * ClassType is an abstract base representing any non-special class + * type. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public abstract class ClassType extends CompoundType { + + private ClassType parent; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Return the parent class of this type. Returns null if this + * type is an interface or if there is no parent. + */ + public ClassType getSuperclass() { + return parent; + } + + + /** + * Print this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + if (isInner()) { + writer.p("// " + getTypeDescription() + " (INNER)"); + } else { + writer.p("// " + getTypeDescription()); + } + writer.pln(" (" + getRepositoryID() + ")\n"); + + printPackageOpen(writer,useIDLNames); + + if (!useIDLNames) { + writer.p("public "); + } + + String prefix = ""; + writer.p("class " + getTypeName(false,useIDLNames,false)); + if (printExtends(writer,useQualifiedNames,useIDLNames,globalIDLNames)) { + prefix = ","; + } + printImplements(writer,prefix,useQualifiedNames,useIDLNames,globalIDLNames); + writer.plnI(" {"); + printMembers(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + printMethods(writer,useQualifiedNames,useIDLNames,globalIDLNames); + + if (useIDLNames) { + writer.pOln("};"); + } else { + writer.pOln("}"); + } + + printPackageClose(writer,useIDLNames); + } + + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + protected void destroy () { + if (!destroyed) { + super.destroy(); + if (parent != null) { + parent.destroy(); + parent = null; + } + } + } + + /** + * Create a ClassType instance for the given class. NOTE: This constructor + * is ONLY for SpecialClassType. + */ + protected ClassType(ContextStack stack, int typeCode, ClassDefinition classDef) { + super(stack,typeCode,classDef); // Call special parent constructor. + if ((typeCode & TM_CLASS) == 0 && classDef.isInterface()) { + throw new CompilerError("Not a class"); + } + parent = null; + } + + /** + * Create a ClassType instance for the given class. NOTE: This constructor + * is ONLY for ImplementationType. It does not walk the parent chain. + */ + protected ClassType(int typeCode, ClassDefinition classDef,ContextStack stack) { + super(stack,classDef,typeCode); + + if ((typeCode & TM_CLASS) == 0 && classDef.isInterface()) { + throw new CompilerError("Not a class"); + } + parent = null; + } + + /** + * Create an ClassType instance for the given class. The resulting + * object is not yet completely initialized. Subclasses must call + * initialize(directInterfaces,directInterfaces,directConstants); + */ + protected ClassType(ContextStack stack, + ClassDefinition classDef, + int typeCode) { + super(stack,classDef,typeCode); + if ((typeCode & TM_CLASS) == 0 && classDef.isInterface()) { + throw new CompilerError("Not a class"); + } + parent = null; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + super.swapInvalidTypes(); + if (parent != null && parent.getStatus() != STATUS_VALID) { + parent = (ClassType) getValidType(parent); + } + } + + /** + * Modify the type description with exception info. + */ + public String addExceptionDescription (String typeDesc) { + if (isException) { + if (isCheckedException) { + typeDesc = typeDesc + " - Checked Exception"; + } else { + typeDesc = typeDesc + " - Unchecked Exception"; + } + } + return typeDesc; + } + + + protected boolean initParents(ContextStack stack) { + + stack.setNewContextCode(ContextStack.EXTENDS); + BatchEnvironment env = stack.getEnv(); + + // Init parent... + + boolean result = true; + + try { + ClassDeclaration parentDecl = getClassDefinition().getSuperClass(env); + if (parentDecl != null) { + ClassDefinition parentDef = parentDecl.getClassDefinition(env); + parent = (ClassType) makeType(parentDef.getType(),parentDef,stack); + if (parent == null) { + result = false; + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + throw new CompilerError("ClassType constructor"); + } + + return result; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/CompoundType.java b/src/share/classes/sun/rmi/rmic/iiop/CompoundType.java new file mode 100644 index 000000000..044161c94 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/CompoundType.java @@ -0,0 +1,2678 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.Identifier; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.MemberDefinition; +import sun.tools.java.CompilerError; +import sun.tools.tree.Node; +import sun.tools.tree.LocalMember; +import sun.tools.tree.CharExpression; +import sun.tools.tree.IntegerExpression; +import sun.rmi.rmic.IndentingWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Enumeration; +import java.io.File; + +/** + * A CompoundType is an abstract base class for all IIOP class and + * interface types. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public abstract class CompoundType extends Type { + + protected Method[] methods; + protected InterfaceType[] interfaces; + protected Member[] members; + protected ClassDefinition classDef; + protected ClassDeclaration classDecl; + + protected boolean isCORBAObject = false; + protected boolean isIDLEntity = false; + protected boolean isAbstractBase = false; + protected boolean isValueBase = false; + protected boolean isCORBAUserException = false; + protected boolean isException = false; + protected boolean isCheckedException = false; + protected boolean isRemoteExceptionOrSubclass = false; + protected String idlExceptionName; + protected String qualifiedIDLExceptionName; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Return true if this type implements + * org.omg.CORBA.Object. + */ + public boolean isCORBAObject () { + return isCORBAObject; + } + + /** + * Return true if this type implements + * org.omg.CORBA.portable.IDLEntity. + */ + public boolean isIDLEntity () { + return isIDLEntity; + } + + /** + * Return true if this type implements + * org.omg.CORBA.portable.ValueBase. + */ + public boolean isValueBase () { + return isValueBase; + } + + /** + * Return true if this type is a CORBA + * abstract interface. + */ + public boolean isAbstractBase () { + return isAbstractBase; + } + + /** + * Return true if this type is an exception. + */ + public boolean isException () { + return isException; + } + + /** + * Return true if this type is a "checked" exception. + * Result if valid iff isException() returns true. + */ + public boolean isCheckedException () { + return isCheckedException; + } + + /** + * Return true if this type is a java.rmi.RemoteException + * or one of its subclasses. Result if valid iff isException() + * returns true. + */ + public boolean isRemoteExceptionOrSubclass () { + return isRemoteExceptionOrSubclass; + } + + /** + * Return true if this type is exactly + * org.omg.CORBA.UserException. + */ + public boolean isCORBAUserException () { + return isCORBAUserException; + } + + /** + * Return true if this type implements + * isIDLEntity() && isException(). + */ + public boolean isIDLEntityException () { + return isIDLEntity() && isException(); + } + /** + * Return true if isIDLEntity() && !isValueBase() + * && !isAbstractBase() && !isCORBAObject() + * && !isIDLEntityException(). + */ + public boolean isBoxed () { + return (isIDLEntity() && !isValueBase() && + !isAbstractBase() && !isCORBAObject() && + !isIDLEntityException()); + } + + /** + * If this type represents an exception, return the + * IDL name including the "Ex" mangling, otherwise + * return null. + */ + public String getIDLExceptionName () { + return idlExceptionName; + } + + /** + * If this type represents an exception, return the + * qualified IDL name including the "Ex" mangling, + * otherwise return null. + * @param global If true, prepends "::". + */ + public String getQualifiedIDLExceptionName (boolean global) { + if (qualifiedIDLExceptionName != null && + global && + getIDLModuleNames().length > 0) { + return IDL_NAME_SEPARATOR + qualifiedIDLExceptionName; + } else { + return qualifiedIDLExceptionName; + } + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public String getSignature() { + String sig = classDecl.getType().getTypeSignature(); + if (sig.endsWith(";")) { + sig = sig.substring(0,sig.length()-1); + } + return sig; + } + + /** + * Return the ClassDeclaration for this type. + */ + public ClassDeclaration getClassDeclaration() { + return classDecl; + } + + /** + * Return the ClassDefinition for this type. + */ + public ClassDefinition getClassDefinition() { + return classDef; + } + + /** + * Return the parent class of this type. Returns null if this + * type is an interface or if there is no parent. + */ + public ClassType getSuperclass() { + return null; + } + + /** + * Return an array of interfaces directly implemented by this type. + *

                + * The order of the array returned is arbitrary. + */ + public InterfaceType[] getInterfaces() { + if( interfaces != null ) { + return (InterfaceType[]) interfaces.clone(); + } + return null; + } + + /** + * Return an array of Type.Method objects representing all + * of the methods implemented directly by this type. + */ + public Method[] getMethods() { + if( methods != null ) { + return (Method[]) methods.clone(); + } + return null; + } + + /** + * Return an array of Type.Member objects representing all of + * the data members directly implemented by this interface. + */ + public Member[] getMembers() { + if( members != null ) { + return (Member[]) members.clone(); + } + return null; + } + + /** + * Create a CompoundType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static CompoundType forCompound (ClassDefinition classDef, + ContextStack stack) { + CompoundType result = null; + + try { + result = (CompoundType) makeType(classDef.getType(),classDef,stack); + } catch (ClassCastException e) {} + + return result; + } + + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Release all resources. + */ + protected void destroy () { + if (!destroyed) { + super.destroy(); + + if (methods != null) { + for (int i = 0; i < methods.length; i++) { + if (methods[i] != null) methods[i].destroy(); + } + methods = null; + } + + if (interfaces != null) { + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i] != null) interfaces[i].destroy(); + } + interfaces = null; + } + + if (members != null) { + for (int i = 0; i < members.length; i++) { + if (members[i] != null) members[i].destroy(); + } + members = null; + } + + classDef = null; + classDecl = null; + } + } + + /* + * Load a Class instance. Return null if fail. + */ + protected Class loadClass() { + + Class ourClass = null; + + // To avoid getting out-of-date Class instances, and + // to ensure that there is an instance, we must compile + // any classes that we've seen and which are not yet + // compiled. We can't just compile this class, 'cuz it + // may have dependencies on classes which have not been + // compiled... + + try { + env.getMain().compileAllClasses(env); + } catch (Exception e1) { + for (Enumeration e = env.getClasses() ; e.hasMoreElements() ; ) { + ClassDeclaration c = (ClassDeclaration)e.nextElement(); + } + failedConstraint(26,false,stack,"required classes"); + env.flushErrors(); + } + + // Now try to get the Class... + // The outer try block is there for people who might want to use + // the compiler at run-time of their AS. + // They could set and use their own context class loader for loading + // classes directly. + try { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + ourClass = cl.loadClass(getQualifiedName()); + } catch(ClassNotFoundException cfe) { + + try { + ourClass = env.classPathLoader.loadClass(getQualifiedName()); + } catch (NullPointerException e) { + // This should never happen + } catch (ClassNotFoundException e) { + // Fall through to the next case (which is to look in the + // output directory for generated files) + } + } + + /* This piece of code used to cause the compiler to ignore jar files + on its classpath + try { + ourClass = Util.loadClass(getQualifiedName(),null,null); + } catch (ClassNotFoundException e) { + } catch (LinkageError e) { + } + */ + + if (ourClass == null) { + + // Try one last thing. If the class was compiled into + // a directory that's not in the classpath, the load + // will fail. Let's get the bits off the disk and load + // it directly... + + if (env.loader == null) { + File destDir = env.getMain().getDestinationDir(); + if (destDir == null) { + destDir = new File("."); + } + env.loader = new DirectoryLoader(destDir); + } + + try { + ourClass = env.loader.loadClass(getQualifiedName()); + } catch (Exception e) {} + } + + return ourClass; + } + + // Print "extends XX" + + protected boolean printExtends (IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + ClassType parent = getSuperclass(); + + if (parent != null && (!useIDLNames || + (!parent.isType(TYPE_ANY) && !parent.isType(TYPE_CORBA_OBJECT)))) { + writer.p(" extends "); + parent.printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + return true; + } + return false; + } + + // Print "implements XX, YY" + + protected void printImplements (IndentingWriter writer, + String prefix, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + InterfaceType[] interfaces = getInterfaces(); + + String adjective = " implements"; + + if (isInterface()) { + adjective = " extends"; + } + + if (useIDLNames) { + adjective = ":"; + } + + for (int i = 0; i < interfaces.length; i++) { + if (!useIDLNames || (!interfaces[i].isType(TYPE_ANY) && !interfaces[i].isType(TYPE_CORBA_OBJECT))) { + if (i == 0) { + writer.p(prefix + adjective + " "); + } else { + writer.p(", "); + } + interfaces[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + } + + // Print members + + protected void printMembers ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + CompoundType.Member[] members = getMembers(); + + for (int i = 0; i < members.length; i++) { + if (!members[i].isInnerClassDeclaration()) { + Type it = members[i].getType(); + String visibility = members[i].getVisibility(); + String name; + + if (useIDLNames) { + name = members[i].getIDLName(); + } else { + name = members[i].getName(); + } + + String value = members[i].getValue(); + + writer.p(visibility); + if (visibility.length() > 0) { + writer.p(" "); + } + it.printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.p(" " + name); + + if (value != null) { + writer.pln(" = " + value + ";"); + } else { + writer.pln(";"); + } + } + } + } + + // Print methods + + protected void printMethods ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + CompoundType.Method[] methods = getMethods(); + + for (int m = 0; m < methods.length; m++) { + CompoundType.Method theMethod = methods[m]; + printMethod(theMethod,writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + + // Print a method... + + protected void printMethod (CompoundType.Method it, + IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + + // Write visibility... + + String visibility = it.getVisibility(); + + writer.p(visibility); + if (visibility.length() > 0) { + writer.p(" "); + } + + // Write return type... + + it.getReturnType().printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + + // Write method name... + + if (useIDLNames) { + writer.p(" " + it.getIDLName()); + } else { + writer.p(" " + it.getName()); + } + + // Write arguments... + + writer.p(" ("); + Type[] args = it.getArguments(); + String[] argNames = it.getArgumentNames(); + + for (int i = 0; i < args.length; i++) { + if (i > 0) { + writer.p(", "); + } + + if (useIDLNames) { + writer.p("in "); + } + + args[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.p(" " + argNames[i]); + } + writer.p(")"); + + // Write exceptions... + + ClassType[] exceptions; + + if (isType(TYPE_IMPLEMENTATION)) { + exceptions = it.getImplExceptions(); + } else { + exceptions = it.getExceptions(); + } + + for (int i = 0; i < exceptions.length; i++) { + if (i == 0) { + if (useIDLNames) { + writer.p(" raises ("); + } else { + writer.p(" throws "); + } + } else { + writer.p(", "); + } + + if (useIDLNames) { + if (useQualifiedNames) { + writer.p(exceptions[i].getQualifiedIDLExceptionName(globalIDLNames)); + } else { + writer.p(exceptions[i].getIDLExceptionName()); + } + writer.p(" [a.k.a. "); + exceptions[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.p("]"); + } else { + exceptions[i].printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + + if (useIDLNames && exceptions.length > 0) { + writer.p(")"); + } + + if (it.isInherited()) { + writer.p(" // Inherited from "); + writer.p(it.getDeclaredBy()); + } + + writer.pln(";"); + } + + /** + * Create a CompoundType instance for the given class. NOTE: This constructor + * is ONLY for SpecialClassType and SpecialInterfaceType. + */ + protected CompoundType(ContextStack stack, int typeCode, ClassDefinition classDef) { + super(stack,typeCode); + this.classDef = classDef; + classDecl = classDef.getClassDeclaration(); + interfaces = new InterfaceType[0]; + methods = new Method[0]; + members = new Member[0]; + + // If we are an inner class/interface, reset the type codes... + + if (classDef.isInnerClass()) { + setTypeCode(typeCode | TM_INNER); + } + + // Set special flags... + + setFlags(); + } + + private void setFlags() { + + try { + + // Set our special interface flags... + + isCORBAObject = env.defCorbaObject.implementedBy(env,classDecl); + isIDLEntity = env.defIDLEntity.implementedBy(env,classDecl); + isValueBase = env.defValueBase.implementedBy(env,classDecl); + isAbstractBase = isInterface() && // Interface, not a class. + isIDLEntity && // Implements IDLEntity. + !isValueBase && // Does not implement ValueBase. + !isCORBAObject; // Does not implement org.omg.CORBA.Object; + isCORBAUserException = (classDecl.getName() == idCorbaUserException); + + // Is this an exception? + + if (env.defThrowable.implementedBy(env, classDecl)) { + + // Yes... + + isException = true; + + // Is it a checked exception? + + if (env.defRuntimeException.implementedBy(env,classDecl) || + env.defError.implementedBy(env,classDecl)) { + isCheckedException = false; + } else { + isCheckedException = true; + } + + // Is it java.rmi.RemoteException or a subclass? + + if (env.defRemoteException.implementedBy(env,classDecl)) { + isRemoteExceptionOrSubclass = true; + } else { + isRemoteExceptionOrSubclass = false; + } + } else { + isException = false; + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } + + /** + * Create a CompoundType instance for the given class. The resulting + * object is not yet completely initialized. + */ + protected CompoundType(ContextStack stack, ClassDefinition classDef, + int typeCode) { + super(stack,typeCode); + this.classDef = classDef; + classDecl = classDef.getClassDeclaration(); + + // If we are an inner class/interface, reset the type codes... + + if (classDef.isInnerClass()) { + setTypeCode(typeCode | TM_INNER); + } + + // Set special flags... + + setFlags(); + + // Set names... + + Identifier id = classDef.getName(); + String idlName; + String[] idlModuleNames; + + try { + + // These can fail if we get case-sensitive name matches... + + idlName = IDLNames.getClassOrInterfaceName(id,env); + idlModuleNames = IDLNames.getModuleNames(id,isBoxed(),env); + + setNames(id,idlModuleNames,idlName); + + // Is this an exception? + + if (isException()) { + + // Yes, so set our mangled exception names... + + isException = true; + idlExceptionName = IDLNames.getExceptionName(getIDLName()); + qualifiedIDLExceptionName = + IDLNames.getQualifiedName(getIDLModuleNames(),idlExceptionName); + } + + // Set interfaces, methods and members... + + interfaces = null; // set in initialize() + methods = null; // set in initialize() + members = null; // set in initialize() + + } catch (Exception e) { + failedConstraint(7,false,stack,id.toString(),e.getMessage()); + throw new CompilerError(""); + } + } + + /** + * Initialize this instance. + */ + protected boolean initialize ( Vector directInterfaces, + Vector directMethods, + Vector directMembers, + ContextStack stack, + boolean quiet) { + + boolean result = true; + + // Initialize our arrays... + + if (directInterfaces != null && directInterfaces.size() > 0) { + interfaces = new InterfaceType[directInterfaces.size()]; + directInterfaces.copyInto(interfaces); + } else { + interfaces = new InterfaceType[0]; + } + + if (directMethods != null && directMethods.size() > 0) { + methods = new Method[directMethods.size()]; + directMethods.copyInto(methods); + + // Now set the idl names for each... + + try { + IDLNames.setMethodNames(this, methods,env); + } catch (Exception e) { + failedConstraint(13,quiet,stack,getQualifiedName(),e.getMessage()); + result = false; + } + + } else { + methods = new Method[0]; + } + + if (directMembers != null && directMembers.size() > 0) { + members = new Member[directMembers.size()]; + directMembers.copyInto(members); + + // If we have any un-initialized inner classes, now is the time + // to init them... + + for (int i = 0; i < members.length; i++) { + if (members[i].isInnerClassDeclaration()) { + try { + members[i].init(stack,this); + } catch (CompilerError e) { + return false; + } + } + } + + // Now set the idl names for each... + + try { + IDLNames.setMemberNames(this, members,methods,env); + } catch (Exception e) { + int constraint = classDef.isInterface() ? 19 : 20; + failedConstraint(constraint,quiet,stack,getQualifiedName(),e.getMessage()); + result = false; + } + + } else { + members = new Member[0]; + } + + // Set our repositoryID... + + if (result) { + result = setRepositoryID(); + } + + return result; + } + + /* + * Return Type or null if error. classDef may be null. + */ + protected static Type makeType (sun.tools.java.Type theType, + ClassDefinition classDef, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + // See if we can find this type in the cache. If so, return it... + + String key = theType.toString(); + + Type result = getType(key,stack); + + if (result != null) { + return result; + } + + // Gotta try with context... + + result = getType(key + stack.getContextCodeString(),stack); + + if (result != null) { + return result; + } + + // Gotta map it... + + BatchEnvironment env = stack.getEnv(); + int typeCode = theType.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + case TC_LONG: + case TC_FLOAT: + case TC_DOUBLE: + { + // Primitive... + + result = PrimitiveType.forPrimitive(theType,stack); + break; + } + + case TC_ARRAY: + { + // Array. + + result = ArrayType.forArray(theType,stack); + break; + } + + case TC_CLASS: + { + try { + // First, make sure we have the class definition... + + ClassDefinition theClass = classDef; + + if (theClass == null) { + theClass = env.getClassDeclaration(theType).getClassDefinition(env); + } + + // Is it an interface or a class? + + if (theClass.isInterface()) { + + // An interface. Is it a special case? + + result = SpecialInterfaceType.forSpecial(theClass,stack); + + if (result == null) { + + // No, does it implement java.rmi.Remote? + + if (env.defRemote.implementedBy(env,theClass.getClassDeclaration())) { + + // Yep, so just see if we can create an instance of RemoteType + // from it... + + boolean parentIsValue = stack.isParentAValue(); + result = RemoteType.forRemote(theClass,stack,parentIsValue); + + // If we did not succeed AND we are in a value context, then + // go ahead and make an NC type out of it... + + if (result == null && parentIsValue) { + result = NCInterfaceType.forNCInterface(theClass,stack); + } + } else { + + // Nope, is it an AbstractType? + + result = AbstractType.forAbstract(theClass,stack,true); + + if (result == null) { + + // No, so treat it as a non-conforming interface type... + + result = NCInterfaceType.forNCInterface(theClass,stack); + } + } + } + } else { + + // A class. Is it a special case? + + result = SpecialClassType.forSpecial(theClass,stack); + + if (result == null) { + + ClassDeclaration classDecl = theClass.getClassDeclaration(); + + // Nope, does it implement java.rmi.Remote? + + if (env.defRemote.implementedBy(env,classDecl)) { + + // Yep, so just see if we can create an instance of + // ImplementationType from it... + + boolean parentIsValue = stack.isParentAValue(); + result = ImplementationType.forImplementation(theClass,stack,parentIsValue); + + // If we did not succeed AND inValue is true, then + // go ahead and make an NC type out of it... + + if (result == null && parentIsValue) { + result = NCClassType.forNCClass(theClass,stack); + } + } else { + + // No, does it implement Serializable? + + if (env.defSerializable.implementedBy(env,classDecl)) { + + // Yep, so just see if we can create an instance of ValueType + // from it... + + result = ValueType.forValue(theClass,stack,true); + } + + if (result == null) { + + // Treat it as a non-conforming class type... + + result = NCClassType.forNCClass(theClass,stack); + } + } + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + break; + } + + default: throw new CompilerError("Unknown typecode (" + typeCode + ") for " + theType.getTypeSignature()); + } + + return result; + } + + /* + * Check if exception is RemoteException or one of its parents. + */ + public static boolean isRemoteException (ClassType ex, + BatchEnvironment env) { + sun.tools.java.Type exceptionType = ex.getClassDeclaration().getType(); + + if (exceptionType.equals(env.typeRemoteException) || + exceptionType.equals(env.typeIOException) || + exceptionType.equals(env.typeException) || + exceptionType.equals(env.typeThrowable)) { + + return true; + } + return false; + } + + /* + * Check if method is conforming. + */ + protected boolean isConformingRemoteMethod (Method method, boolean quiet) + throws ClassNotFound { + + // Do we have one exception that is RemoteException or + // a superclass of RemoteException? + + boolean haveRemote = false; + ClassType[] exceptions = method.getExceptions(); + + for (int i = 0; i < exceptions.length; i++) { + + // Is it a conforming exception? + + if (isRemoteException(exceptions[i],env)) { + + // Got it. + + haveRemote = true; + break; + } + } + + // Do we have our exception? + + if (!haveRemote) { + + // No, so report failure... + + failedConstraint(5,quiet,stack,method.getEnclosing(), method.toString()); + } + + // Are any of the arguments exceptions which implement IDLEntity? + // If so, report failure... + + boolean noIDLEntity = !isIDLEntityException(method.getReturnType(),method,quiet); + if (noIDLEntity) { + Type[] args = method.getArguments(); + for (int i = 0; i < args.length; i++) { + if (isIDLEntityException(args[i],method,quiet)) { + noIDLEntity = false; + break; + } + } + } + + return (haveRemote && noIDLEntity); + } + + protected boolean isIDLEntityException(Type type, CompoundType.Method method,boolean quiet) + throws ClassNotFound { + if (type.isArray()) { + type = type.getElementType(); + } + if (type.isCompound()){ + if (((CompoundType)type).isIDLEntityException()) { + failedConstraint(18,quiet,stack,method.getEnclosing(), method.toString()); + return true; + } + } + return false; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + + // Walk all interfaces and check them... + + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i].getStatus() != STATUS_VALID) { + interfaces[i] = (InterfaceType)getValidType(interfaces[i]); + } + } + + // Update methods... + + for (int i = 0; i < methods.length; i++) { + methods[i].swapInvalidTypes(); + } + + // Update members... + + for (int i = 0; i < members.length; i++) { + members[i].swapInvalidTypes(); + } + } + + /* + * Add matching types to list. Return true if this type has not + * been previously checked, false otherwise. + */ + protected boolean addTypes (int typeCodeFilter, + HashSet checked, + Vector matching) { + + // Check self. + + boolean result = super.addTypes(typeCodeFilter,checked,matching); + + // Have we been checked before? + + if (result) { + + // Nope, so walk parent(s) and check them... + + ClassType parent = getSuperclass(); + + if (parent != null) { + parent.addTypes(typeCodeFilter,checked,matching); + } + + // Walk all interfaces and check them... + + //if (interfaces == null) System.out.println("NULL for " +getQualifiedName() + " interfaces"); + for (int i = 0; i < interfaces.length; i++) { + + // Now recurse and add it and any referenced types... + + //if (interfaces[i] == null) System.out.println("NULL for " +getQualifiedName() + " interfaces[" + i + "]"); + interfaces[i].addTypes(typeCodeFilter,checked,matching); + } + + // Walk all methods and check arguments... + + //if (methods == null) System.out.println("NULL for " +getQualifiedName() + " methods"); + for (int i = 0; i < methods.length; i++) { + + // Add return type... + //if (methods[i] == null) System.out.println("NULL for " +getQualifiedName() + " methods[" + i + "]"); + //if (methods[i].getReturnType() == null) System.out.println("NULL for " +getQualifiedName() + methods[i]); + methods[i].getReturnType().addTypes(typeCodeFilter,checked,matching); + + // Add args... + + Type[] args = methods[i].getArguments(); + //if (args == null) System.out.println("NULL for " + getQualifiedName() + " args"); + + for (int j = 0; j < args.length; j++) { + + Type arg = args[j]; + //if (arg == null) System.out.println("NULL for " + getQualifiedName() + " arg[" +j+"]"); + + // Add argument... + + arg.addTypes(typeCodeFilter,checked,matching); + } + + // Add exceptions... + + ClassType[] exceptions = methods[i].getExceptions(); + //if (exceptions == null) System.out.println("NULL for " + getQualifiedName() + " exceptions"); + + for (int j = 0; j < exceptions.length; j++) { + + ClassType ex = exceptions[j]; + + // Add argument... + + ex.addTypes(typeCodeFilter,checked,matching); + } + } + + // Walk all members and add em... + + //if (members == null) System.out.println("NULL for " +getQualifiedName() + " members"); + for (int i = 0; i < members.length; i++) { + //if (members[i] == null) System.out.println("NULL for " +getQualifiedName() + " members[" + i + "]"); + Type cType = members[i].getType(); + //if (cType == null) System.out.println("NULL for " + getQualifiedName() + " cType"); + + // Add it... + + cType.addTypes(typeCodeFilter,checked,matching); + } + } + + return result; + } + + /* + * Return true if theType is a conforming constant type. + */ + private boolean isConformingConstantType (MemberDefinition member) { + return isConformingConstantType(member.getType(),member); + } + + /* + * Return true if theType is a conforming constant type. + */ + private boolean isConformingConstantType (sun.tools.java.Type theType,MemberDefinition member) { + + // Constraint 3: Constants must be either primitives or String. + + boolean result = true; + int typeCode = theType.getTypeCode(); + switch (typeCode) { + case TC_BOOLEAN: + case TC_BYTE: + case TC_CHAR: + case TC_SHORT: + case TC_INT: + case TC_LONG: + case TC_FLOAT: + case TC_DOUBLE: // Primitive, so OK... + { + break; + } + + case TC_CLASS: // Must be java.lang.String + { + if (theType.getClassName() != idJavaLangString) { + failedConstraint(3,false,stack,member.getClassDefinition(),member.getName()); + result = false; + } + break; + } + + case TC_ARRAY: // Array constants are not allowed. + { + failedConstraint(3,false,stack,member.getClassDefinition(),member.getName()); + result = false; + break; + } + + default: + throw new Error("unexpected type code: " + typeCode); + } + + return result; + } + + + /* + * Update any method from 'currentMethods' which is defined in a + * parent class so that it's 'declaredBy' field specifies the + * parent. + * @param current The class or interface to gather methods from. + * @param currentMethods The list into which to put the methods. + * for contraint 6. + * @param quiet true if silent errors. + * @param stack the context stack. + * @return currentMethods or null if failed a constraint check. + */ + protected Vector updateParentClassMethods(ClassDefinition current, + Vector currentMethods, + boolean quiet, + ContextStack stack) + throws ClassNotFound { + + ClassDeclaration parentDecl = current.getSuperClass(env); + + while (parentDecl != null) { + + ClassDefinition parentDef = parentDecl.getClassDefinition(env); + Identifier currentID = parentDecl.getName(); + + if ( currentID == idJavaLangObject ) break; + + // Walk all members of this class and update any that + // already exist in currentMethods... + + for (MemberDefinition member = parentDef.getFirstMember(); + member != null; + member = member.getNextMember()) { + + if (member.isMethod() && + !member.isInitializer() && + !member.isConstructor() && + !member.isPrivate()) { + + // It's a method. Is it valid? + + Method method; + try { + method = new Method((CompoundType)this,member,quiet,stack); + } catch (Exception e) { + // Don't report anything here, it's already been reported... + return null; + } + + // Have we already seen it? + + int index = currentMethods.indexOf(method); + if (index >= 0) { + + // Yes, so update it... + + Method currentMethod = (Method)currentMethods.elementAt(index); + currentMethod.setDeclaredBy(currentID); + } + else currentMethods.addElement(method); + } + } + + // Update parent and keep walking up the chain... + + parentDecl = parentDef.getSuperClass(env); + } + + return currentMethods; + } + + /* + * Add all of the public and protected methods defined in + * current (other than initializers) to allMethods. If a sub-interface + * re-declares an inherited method, it will not be added. + * @param current The class or interface to gather methods from. + * @param directMethods The list into which to put the methods. + * @param noMultiInheritedMethods A flag to enable/disable checking + * for contraint 6. + * @param quiet true if silent errors. + * @param stack the context stack. + * @return directMethods or null if failed a constraint check. + */ + protected Vector addAllMethods (ClassDefinition current, Vector directMethods, + boolean noMultiInheritedMethods, + boolean quiet, + ContextStack stack) + throws ClassNotFound { + + // Constraint 6: Multiple inherited interfaces may not + // declare the same method. + + ClassDeclaration[] interfaces = current.getInterfaces(); + + // We want to add members starting at the _least_ derived + // interfaces. To do so, recurse until we have no more + // interfaces... + + for (int i = 0; i < interfaces.length; i++) { + + Vector result = addAllMethods(interfaces[i].getClassDefinition(env), + directMethods, + noMultiInheritedMethods,quiet,stack); + if (result == null) { + return null; + } + } + + // Walk all members of this interface, adding any unique methods + // other than initializers and private methods... + + for (MemberDefinition member = current.getFirstMember(); + member != null; + member = member.getNextMember()) + { + if (member.isMethod() && + !member.isInitializer() && + !member.isPrivate()) { + + // It's a method. Is it valid? + + Method method; + try { + method = new Method((CompoundType)this,member,quiet,stack); + } catch (Exception e) { + // Don't report anything here, it's already been reported... + return null; + } + + // Have we already seen it? + + if (!directMethods.contains(method)) { + + // Nope, so add it... + + directMethods.addElement(method); + + } else { + + // Yes. This is an error unless we are looking at the + // target interface (or this is a ValueType). Are we? + + if (noMultiInheritedMethods && current != classDef && + !stack.isParentAValue() && !stack.getContext().isValue()) { + + // Nope. Say so and signal error by returning null.. + + Method existingMethod = (Method) directMethods.elementAt(directMethods.indexOf(method)); + ClassDefinition existingMemberClassDef = existingMethod.getMemberDefinition().getClassDefinition(); + + // There are more legal cases to consider here. + // If the two methods belong to interfaces that inherit from each other + // then it is just a redefinition which is legal. + if ( current != existingMemberClassDef && + ! inheritsFrom(current, existingMemberClassDef) && + ! inheritsFrom(existingMemberClassDef, current)) + { + //Identifier int1 = existingMethod.getEnclosing().getIdentifier(); + //Identifier int2 = current.getName(); + //String message = int1.toString() + " and " + int2.toString(); + String message = existingMemberClassDef.getName() + " and " + current.getName(); + failedConstraint(6,quiet,stack,classDef,message,method); + return null; + } + } + + // Bug fix 5014329 + + // find a matching method. + int index = directMethods.indexOf(method); + Method other = (Method) directMethods.get(index); + + // merge the two methods, such that the new method + // will contain only those exception that can be thrown + // by both these methods, not just one of them. + Method newMethod = method.mergeWith(other); + + // replace the old method with the new. + directMethods.set(index, newMethod); + } + } + } + + return directMethods; + } + + // This should really be a method on ClassDefinition, but it takes too long to change the shared source. + // Works for both, classes and interfaces. + protected boolean inheritsFrom(ClassDefinition def, ClassDefinition otherDef) { + if (def == otherDef) + return true; + + ClassDefinition superDef; + if (def.getSuperClass() != null) { + superDef = def.getSuperClass().getClassDefinition(); + if (inheritsFrom(superDef, otherDef)) + return true; + } + + ClassDeclaration[] interfaces = def.getInterfaces(); + for (int i=0; i 0) { + int offset = 0; + ValueType[] temp = new ValueType[exceptions.length - dupCount]; + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i] != null) { + temp[offset++] = exceptions[i]; + } + } + exceptions = temp; + } + + return exceptions; + } + + + protected static String getVisibilityString (MemberDefinition member) { + String vis = ""; + String prefix = ""; + + if (member.isPublic()) { + vis += "public"; + prefix = " "; + } else if (member.isProtected()) { + vis += "protected"; + prefix = " "; + } else if (member.isPrivate()) { + vis += "private"; + prefix = " "; + } + + if (member.isStatic()) { + vis += prefix; + vis += "static"; + prefix = " "; + } + + if (member.isFinal()) { + vis += prefix; + vis += "final"; + prefix = " "; + } + + return vis; + } + + protected boolean assertNotImpl(Type type, + boolean quiet, + ContextStack stack, + CompoundType enclosing, + boolean dataMember) { + + if (type.isType(TYPE_IMPLEMENTATION)) { + int constraint = dataMember ? 28 : 21; + failedConstraint(constraint,quiet,stack,type,enclosing.getName()); + return false; + } + return true; + } + + //_____________________________________________________________________ + // Inner Class "Method" + //_____________________________________________________________________ + + /** + * A CompoundType.Method object encapsulates IIOP-specific information + * about a particular method in the interface represented by the outer + * instance. + */ + public class Method implements ContextElement, Cloneable { + + /** + * Is this method inherited? + */ + public boolean isInherited () { + return declaredBy != enclosing.getIdentifier(); + } + + /** + * Is this method an attribute? + * Return true if getAttributeKind != ATTRIBUTE_NONE. + */ + public boolean isAttribute () { + return attributeKind != ATTRIBUTE_NONE; + } + + /** + * Is this method a read-write attribute? + */ + public boolean isReadWriteAttribute () { + return attributeKind == ATTRIBUTE_IS_RW || + attributeKind == ATTRIBUTE_GET_RW; + } + + /** + * Return the attribute kind. + */ + public int getAttributeKind() { + return attributeKind; + } + + /** + * Return the attribute name. Will be null if + * attribute kind == ATTRIBUTE_NONE. + */ + public String getAttributeName() { + return attributeName; + } + + /** + * For kinds ATTRIBUTE_GET_RW or ATTRIBUTE_IS_RW, return + * the index of the matching ATTRIBUTE_SET method, and + * vice-versa. For all other cases, return -1. + */ + public int getAttributePairIndex() { + return attributePairIndex; + } + + /** + * Return context element name. + */ + public String getElementName() { + return memberDef.toString(); + } + + /** + * Equality check based on method signature. + */ + public boolean equals(Object obj) { + Method other = (Method) obj; + + if (getName().equals(other.getName()) && + arguments.length == other.arguments.length) { + + for (int i = 0; i < arguments.length; i++) { + if (! arguments[i].equals(other.arguments[i])) { + return false; + } + } + return true; + } + return false; + } + + /** + * Return a new Method object that is a legal combination of + * this method object and another one. + * + * This requires determining the exceptions declared by the + * combined method, which must be only those exceptions + * that may thrown by both of the old methods. + */ + public Method mergeWith(Method other) { + if (!equals(other)) { + env.error(0, "attempt to merge method failed:", getName(), + enclosing.getClassDefinition().getName()); + } + + Vector legalExceptions = new Vector(); + try { + collectCompatibleExceptions( + other.exceptions, exceptions, legalExceptions); + collectCompatibleExceptions( + exceptions, other.exceptions, legalExceptions); + } catch (ClassNotFound e) { + env.error(0, "class.not.found", e.name, + enclosing.getClassDefinition().getName()); + return null; + } + + Method merged = (Method) clone(); + merged.exceptions = new ValueType[legalExceptions.size()]; + legalExceptions.copyInto(merged.exceptions); + merged.implExceptions = merged.exceptions; + + return merged; + } + + /** + * Add to the supplied list all exceptions in the "from" array + * that are subclasses of an exception in the "with" array. + */ + private void collectCompatibleExceptions( + ValueType[] from, ValueType[] with, Vector list) + throws ClassNotFound { + + for (int i = 0; i < from.length; i++) { + ClassDefinition exceptionDef = from[i].getClassDefinition(); + if (!list.contains(from[i])) { + for (int j = 0; j < with.length; j++) { + if (exceptionDef.subClassOf( + enclosing.getEnv(), + with[j].getClassDeclaration())) { + list.addElement(from[i]); + break; + } + } + } + } + } + + /** + * Return the compound type which contains this method. + */ + public CompoundType getEnclosing() { + return enclosing; + } + + /** + * Return the identifier for the class or interface which + * declares this method. + */ + public Identifier getDeclaredBy() { + return declaredBy; + } + + /** + * Return the visibility (e.g. "public final") of this member. + */ + public String getVisibility() { + return vis; + } + + /** + * Methods to check various attributes. + */ + public boolean isPublic() { + return memberDef.isPublic(); + } + + public boolean isProtected() { + return memberDef.isPrivate(); + } + + public boolean isPrivate() { + return memberDef.isPrivate(); + } + + public boolean isStatic() { + return memberDef.isStatic(); + } + + /** + * Return the name of this method. + */ + public String getName() { + return name; + } + + /** + * IDL_Naming + * Return the IDL name of this method. + */ + public String getIDLName() { + return idlName; + } + + /** + * Return the type of this method. + */ + public sun.tools.java.Type getType() { + return memberDef.getType(); + } + + /** + * Return true if this is a constructor. + */ + public boolean isConstructor () { + return memberDef.isConstructor(); + } + + /** + * Return true if this is NOT a constructor && is not + * an attribute. + */ + public boolean isNormalMethod () { + return (!memberDef.isConstructor()) && attributeKind == ATTRIBUTE_NONE; + } + + /** + * Get the return type of this method. May be null. + */ + public Type getReturnType() { + return returnType; + } + + /** + * Return the argument types of this method. + */ + public Type[] getArguments() { + return (Type[]) arguments.clone(); + } + + /** + * Return the names of the argument types of this method. + */ + public String[] getArgumentNames() { + return argumentNames; + } + + /** + * Return the MemberDefinition from which this method was created. + */ + public MemberDefinition getMemberDefinition() { + return memberDef; + } + + /** + * Return an array of the exception classes declared to be + * thrown by this remote method. + * + * For methods with the same name and type signature inherited + * from multiple remote interfaces, the array will contain + * the set of exceptions declared in all of the interfaces' + * methods that can be legally thrown in each of them. + */ + public ValueType[] getExceptions() { + return (ValueType[]) exceptions.clone(); + } + + /** + * Same as getExceptions(), except when method is in an + * ImplementationType and the exceptions list is narrower. + */ + public ValueType[] getImplExceptions() { + return (ValueType[]) implExceptions.clone(); + } + + /** + * Return an array containing only those exceptions which + * need to be caught. Removes java.rmi.RemoteException, + * java.lang.RuntimeException, java.lang.Error, and their + * subclasses, then removes any exceptions which are more + * derived than another in the list. Returns null if no + * exceptions need to be caught. + */ + public ValueType[] getUniqueCatchList(ValueType[] list) { + ValueType[] result = list; + int newSize = list.length; + + try { + + // First, remove RemoteException, RuntimeException, Error, and their subclasses... + for (int i = 0; i < list.length; i++) { + ClassDeclaration decl = list[i].getClassDeclaration(); + if (env.defRemoteException.superClassOf(env, decl) || + env.defRuntimeException.superClassOf(env, decl) || + env.defError.superClassOf(env, decl)) { + list[i] = null; + newSize--; + } + } + + // Now remove derived types... + for (int i = 0; i < list.length; i++) { + if (list[i] != null) { + ClassDefinition current = list[i].getClassDefinition(); + for (int j = 0; j < list.length; j++) { + if (j != i && list[i] != null && list[j] != null && + current.superClassOf(env, list[j].getClassDeclaration())) { + list[j] = null; + newSize--; + } + } + } + } + + } catch (ClassNotFound e) { + classNotFound(stack,e); // Report error but do not stop. + } + + // Create new list if we removed anything... + + if (newSize < list.length) { + ValueType[] temp = new ValueType[newSize]; + int offset = 0; + for (int i = 0; i < list.length; i++) { + if (list[i] != null) { + temp[offset++] = list[i]; + } + } + list = temp; + } + + if (list.length == 0) { + return null; + } else { + return list; + } + } + + /** + * Return an array containing only those exceptions which need to be + * handled explicitly by the stub. Removes java.lang.RuntimeException, + * java.lang.Error, and their subclasses, since these are all passed + * back as CORBA system exceptions. Also removes subclasses of + * java.rmi.RemoteException but not java.rmi.RemoteException itself, + * since this may need to be thrown by the stub. + */ + public ValueType[] getFilteredStubExceptions(ValueType[] list) { + ValueType[] result = list; + int newSize = list.length; + + try { + + for (int i = 0; i < list.length; i++) { + ClassDeclaration decl = list[i].getClassDeclaration(); + if ((env.defRemoteException.superClassOf(env, decl) && + !env.defRemoteException.getClassDeclaration().equals(decl)) || + env.defRuntimeException.superClassOf(env, decl) || + env.defError.superClassOf(env, decl)) { + list[i] = null; + newSize--; + } + } + + } catch (ClassNotFound e) { + classNotFound(stack,e); // Report error but do not stop. + } + + // Create new list if we removed anything... + + if (newSize < list.length) { + ValueType[] temp = new ValueType[newSize]; + int offset = 0; + for (int i = 0; i < list.length; i++) { + if (list[i] != null) { + temp[offset++] = list[i]; + } + } + list = temp; + } + + return list; + } + + /** + * Return the string representation of this method. + */ + public String toString() { + + if (stringRep == null) { + + StringBuffer result = new StringBuffer(returnType.toString()); + + // Add name... + + result.append(" "); + result.append(getName()); + result.append(" ("); + + // Add arguments... + + for (int i = 0; i < arguments.length; i++) { + if (i > 0) { + result.append(", "); + } + result.append(arguments[i]); + result.append(" "); + result.append(argumentNames[i]); + } + + result.append(")"); + + // Add exceptions... + + for (int i = 0; i < exceptions.length; i++) { + if (i == 0) { + result.append(" throws "); + } else { + result.append(", "); + } + result.append(exceptions[i]); + } + + result.append(";"); + + stringRep = result.toString(); + } + + return stringRep; + } + + + /** + * Set attribute kind. May only be called during initialization. + */ + public void setAttributeKind(int kind) { + attributeKind = kind; + } + + /** + * Set pair index. May only be called during initialization. + */ + public void setAttributePairIndex(int index) { + attributePairIndex = index; + } + + /** + * Set attribute name. May only be called during initialization. + */ + public void setAttributeName(String name) { + attributeName = name; + } + + /** + * Set the idl name. May only be called during initialization. + */ + public void setIDLName (String idlName) { + this.idlName=idlName; + } + + /** + * Set the implExceptions array. May only be called during initialization. + */ + public void setImplExceptions (ValueType[] exceptions) { + implExceptions = exceptions; + } + + /** + * Set the declaredBy Identifier. May only be called during initialization. + */ + public void setDeclaredBy (Identifier by) { + declaredBy = by; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + + // Check return type... + + if (returnType.getStatus() != STATUS_VALID) { + returnType = getValidType(returnType); + } + + // Check args... + + for (int i = 0; i < arguments.length; i++) { + if (arguments[i].getStatus() != STATUS_VALID) { + arguments[i] = getValidType(arguments[i]); + } + } + + // Check exceptions... + + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getStatus() != STATUS_VALID) { + exceptions[i] = (ValueType)getValidType(exceptions[i]); + } + } + + // Check implExceptions... + + for (int i = 0; i < implExceptions.length; i++) { + if (implExceptions[i].getStatus() != STATUS_VALID) { + implExceptions[i] = (ValueType)getValidType(implExceptions[i]); + } + } + } + + /** + * Release all resources. + */ + public void destroy () { + if (memberDef != null) { + memberDef = null; + enclosing = null; + if (exceptions != null) { + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i] != null) exceptions[i].destroy(); + exceptions[i] = null; + } + exceptions = null; + } + + if (implExceptions != null) { + for (int i = 0; i < implExceptions.length; i++) { + if (implExceptions[i] != null) implExceptions[i].destroy(); + implExceptions[i] = null; + } + implExceptions = null; + } + + if (returnType != null) returnType.destroy(); + returnType = null; + + if (arguments != null) { + for (int i = 0; i < arguments.length; i++) { + if (arguments[i] != null) arguments[i].destroy(); + arguments[i] = null; + } + arguments = null; + } + + if (argumentNames != null) { + for (int i = 0; i < argumentNames.length; i++) { + argumentNames[i] = null; + } + argumentNames = null; + } + + vis = null; + name = null; + idlName = null; + stringRep = null; + attributeName = null; + declaredBy = null; + } + } + + private MemberDefinition memberDef; + private CompoundType enclosing; + private ValueType[] exceptions; + private ValueType[] implExceptions; + private Type returnType; + private Type[] arguments; + private String[] argumentNames; + private String vis; + private String name; + private String idlName; + private String stringRep = null; + private int attributeKind = ATTRIBUTE_NONE; + private String attributeName = null; + private int attributePairIndex = -1; + private Identifier declaredBy = null; + + /** + * Make up an argument name for the given type. + */ + private String makeArgName (int argNum, Type type) { + return "arg" + argNum; + } + + /** + * Create a new Method object corresponding to the given + * method definition. + */ + public Method (CompoundType enclosing, + MemberDefinition memberDef, + boolean quiet, + ContextStack stack) throws Exception { + + this.enclosing = enclosing; + this.memberDef = memberDef; + vis = getVisibilityString(memberDef); + idlName = null; // See setIDLName() + boolean valid = true; + declaredBy = memberDef.getClassDeclaration().getName(); + + // Set name... + + name = memberDef.getName().toString(); + + // Update the context... + + stack.setNewContextCode(ContextStack.METHOD); + stack.push(this); + + // Set return type... + + stack.setNewContextCode(ContextStack.METHOD_RETURN); + sun.tools.java.Type methodType = memberDef.getType(); + sun.tools.java.Type rtnType = methodType.getReturnType(); + + if (rtnType == sun.tools.java.Type.tVoid) { + returnType = PrimitiveType.forPrimitive(rtnType,stack); + } else { + returnType = makeType(rtnType,null,stack); + if (returnType == null || + !assertNotImpl(returnType,quiet,stack,enclosing,false)) { + valid = false; + failedConstraint(24,quiet,stack,enclosing.getName()); + } + } + + // Set arguments and argument names... + + stack.setNewContextCode(ContextStack.METHOD_ARGUMENT); + sun.tools.java.Type[] args = memberDef.getType().getArgumentTypes(); + arguments = new Type[args.length]; + argumentNames = new String[args.length]; + Vector origArgNames = memberDef.getArguments(); + + for (int i = 0; i < args.length; i++) { + Type type = null; + try { + type = makeType(args[i],null,stack); + } catch (Exception e) { + } + + if (type != null) { + if (!assertNotImpl(type,quiet,stack,enclosing,false)) { + valid = false; + } else { + arguments[i] = type; + if (origArgNames != null) { + LocalMember local = (LocalMember)origArgNames.elementAt(i+1); + argumentNames[i] = local.getName().toString(); + } else { + argumentNames[i] = makeArgName(i,type); + } + } + } else { + valid = false; + failedConstraint(25,false,stack,enclosing.getQualifiedName(),name); + } + } + + if (!valid) { + stack.pop(false); + throw new Exception(); + } + + // Set exceptions... + + try { + exceptions = enclosing.getMethodExceptions(memberDef,quiet,stack); + implExceptions = exceptions; + stack.pop(true); + } catch (Exception e) { + stack.pop(false); + throw new Exception(); + } + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + } + + //_____________________________________________________________________ + // Inner Class "Member" + //_____________________________________________________________________ + + /** + * An CompoundType.Member object wraps a Type and a value representing + * a data member, including constants. + */ + public class Member implements ContextElement, Cloneable { + + /** + * Return context element name. + */ + public String getElementName() { + return "\"" + getName() + "\""; + } + + /** + * Return the type of this member. + */ + public Type getType() { + return type; + } + + /** + * Return the name of this member. + */ + public String getName() { + return name; + } + + /** + * IDL_Naming + * Return the IDL name of this member. + */ + public String getIDLName() { + return idlName; + } + + /** + * Return the visibility (e.g. "public final") of this member. + */ + public String getVisibility() { + return vis; + } + + /** + * Methods to check various attributes. + */ + public boolean isPublic() { + return member.isPublic(); + } + + public boolean isPrivate() { + return member.isPrivate(); + } + + public boolean isStatic() { + return member.isStatic(); + } + + public boolean isFinal() { + return member.isFinal(); + } + + public boolean isTransient() { + if (forceTransient) return true; + return member.isTransient(); + } + + /** + * Return the value of this member. May be null. + */ + public String getValue() { + return value; + } + + /** + * Return true if this member represents an inner class declaration, + * false otherwise. + */ + public boolean isInnerClassDeclaration() { + return innerClassDecl; + } + + /** + * Return true if this member represents a constant. + */ + public boolean isConstant () { + return constant; + } + + /** + * Return the string representation of this constant. + */ + public String toString() { + + String result = type.toString(); + + if (value != null) { + result += (" = " + value); + } + + return result; + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + if (type.getStatus() != STATUS_VALID) { + type = getValidType(type); + } + } + + protected void setTransient() { + if (! isTransient()) { + forceTransient = true; + if (vis.length() > 0) { + vis = vis + " transient"; + } else { + vis = "transient"; + } + } + } + + protected MemberDefinition getMemberDefinition() { + return member; + } + + /** + * Release all resources. + */ + public void destroy () { + if (type != null) { + type.destroy(); + type = null; + vis = null; + value = null; + name = null; + idlName = null; + member = null; + } + } + + private Type type; + private String vis; + private String value; + private String name; + private String idlName; + private boolean innerClassDecl; + private boolean constant; + private MemberDefinition member; + private boolean forceTransient; + + /** + * Create a new Member object. + */ + public Member(MemberDefinition member, + String value, + ContextStack stack, + CompoundType enclosing) { + this.member = member; + this.value = value; + forceTransient = false; + innerClassDecl = member.getInnerClass() != null; + + // If we are not an inner class, finish initializing now. + // Otherwise, wait until outer class is finished, then + // call init to avoid potential recursion problems... + + if (!innerClassDecl) { + init (stack,enclosing); + } + } + + public void init (ContextStack stack, CompoundType enclosing) { + + constant = false; + name = member.getName().toString(); + vis = getVisibilityString(member); + idlName = null; + + // Add self to stack... + + int contextCode = ContextStack.MEMBER; + stack.setNewContextCode(contextCode); + + // Check for special contextCodes... + + if (member.isVariable()) { + if (value != null && member.isConstant()) { + contextCode = ContextStack.MEMBER_CONSTANT; + this.constant = true; + } else if (member.isStatic()) { + contextCode = ContextStack.MEMBER_STATIC; + } else if (member.isTransient()) { + contextCode = ContextStack.MEMBER_TRANSIENT; + } + } + + stack.setNewContextCode(contextCode); + stack.push(this); + + type = makeType(member.getType(),null,stack); + + if (type == null || + (!innerClassDecl && + !member.isStatic() && + !member.isTransient() && + !assertNotImpl(type,false,stack,enclosing,true))) { + stack.pop(false); + throw new CompilerError(""); + } + + // Clean up primitive constant values... + + if (constant && type.isPrimitive()) { + if (type.isType(TYPE_LONG) || type.isType(TYPE_FLOAT) || type.isType(TYPE_DOUBLE)) { + int length = value.length(); + char lastChar = value.charAt(length-1); + if (!Character.isDigit(lastChar)) { + this.value = value.substring(0,length-1); + } + } else if (type.isType(TYPE_BOOLEAN)) { + value = value.toUpperCase(); + } + } + if (constant && type.isType(TYPE_STRING)) { + value = "L" + value; + } + stack.pop(true); + } + + public void setIDLName (String name) { + this.idlName = name; + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/Constants.java b/src/share/classes/sun/rmi/rmic/iiop/Constants.java new file mode 100644 index 000000000..2f24d87c2 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/Constants.java @@ -0,0 +1,276 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.tools.java.Identifier; + +public interface Constants extends sun.rmi.rmic.Constants { + + // Identifiers for referenced classes: + + public static final Identifier idReplyHandler = + Identifier.lookup("org.omg.CORBA.portable.ResponseHandler"); + public static final Identifier idStubBase = + Identifier.lookup("javax.rmi.CORBA.Stub"); + public static final Identifier idTieBase = + Identifier.lookup("org.omg.CORBA.portable.ObjectImpl"); + public static final Identifier idTieInterface = + Identifier.lookup("javax.rmi.CORBA.Tie"); + public static final Identifier idPOAServantType = + Identifier.lookup( "org.omg.PortableServer.Servant" ) ; + public static final Identifier idDelegate = + Identifier.lookup("org.omg.CORBA.portable.Delegate"); + public static final Identifier idOutputStream = + Identifier.lookup("org.omg.CORBA.portable.OutputStream"); + public static final Identifier idExtOutputStream = + Identifier.lookup("org.omg.CORBA_2_3.portable.OutputStream"); + public static final Identifier idInputStream = + Identifier.lookup("org.omg.CORBA.portable.InputStream"); + public static final Identifier idExtInputStream = + Identifier.lookup("org.omg.CORBA_2_3.portable.InputStream"); + public static final Identifier idSystemException = + Identifier.lookup("org.omg.CORBA.SystemException"); + public static final Identifier idBadMethodException = + Identifier.lookup("org.omg.CORBA.BAD_OPERATION"); + public static final Identifier idPortableUnknownException = + Identifier.lookup("org.omg.CORBA.portable.UnknownException"); + public static final Identifier idApplicationException = + Identifier.lookup("org.omg.CORBA.portable.ApplicationException"); + public static final Identifier idRemarshalException = + Identifier.lookup("org.omg.CORBA.portable.RemarshalException"); + public static final Identifier idJavaIoExternalizable = + Identifier.lookup("java.io.Externalizable"); + public static final Identifier idCorbaObject = + Identifier.lookup("org.omg.CORBA.Object"); + public static final Identifier idCorbaORB = + Identifier.lookup("org.omg.CORBA.ORB"); + public static final Identifier idClassDesc = + Identifier.lookup("javax.rmi.CORBA.ClassDesc"); + public static final Identifier idJavaIoIOException = + Identifier.lookup("java.io.IOException"); + public static final Identifier idIDLEntity = + Identifier.lookup("org.omg.CORBA.portable.IDLEntity"); + public static final Identifier idValueBase = + Identifier.lookup("org.omg.CORBA.portable.ValueBase"); + public static final Identifier idBoxedRMI = + Identifier.lookup("org.omg.boxedRMI"); + public static final Identifier idBoxedIDL = + Identifier.lookup("org.omg.boxedIDL"); + public static final Identifier idCorbaUserException = + Identifier.lookup("org.omg.CORBA.UserException"); + + + // Identifiers for primitive types: + + public static final Identifier idBoolean = + Identifier.lookup("boolean"); + public static final Identifier idByte = + Identifier.lookup("byte"); + public static final Identifier idChar = + Identifier.lookup("char"); + public static final Identifier idShort = + Identifier.lookup("short"); + public static final Identifier idInt = + Identifier.lookup("int"); + public static final Identifier idLong = + Identifier.lookup("long"); + public static final Identifier idFloat = + Identifier.lookup("float"); + public static final Identifier idDouble = + Identifier.lookup("double"); + public static final Identifier idVoid = + Identifier.lookup("void"); + + // IndentingWriter constructor args: + + public static final int INDENT_STEP = 4; + public static final int TAB_SIZE = Integer.MAX_VALUE; // No tabs. + + // Type status codes: + + public static final int STATUS_PENDING = 0; + public static final int STATUS_VALID = 1; + public static final int STATUS_INVALID = 2; + + // Java Names: + + public static final String NAME_SEPARATOR = "."; + public static final String SERIAL_VERSION_UID = "serialVersionUID"; + + // IDL Names: + + public static final String[] IDL_KEYWORDS = { + "abstract", + "any", + "attribute", + "boolean", + "case", + "char", + "const", + "context", + "custom", + "default", + "double", + "enum", + "exception", + "factory", + "FALSE", + "fixed", + "float", + "in", + "inout", + "interface", + "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", + }; + + + public static final String EXCEPTION_SUFFIX = "Exception"; + public static final String ERROR_SUFFIX = "Error"; + public static final String EX_SUFFIX = "Ex"; + + public static final String IDL_REPOSITORY_ID_PREFIX = "IDL:"; + public static final String IDL_REPOSITORY_ID_VERSION = ":1.0"; + + public static final String[] IDL_CORBA_MODULE = {"CORBA"}; + public static final String[] IDL_SEQUENCE_MODULE = {"org","omg","boxedRMI"}; + public static final String[] IDL_BOXEDIDL_MODULE = {"org","omg","boxedIDL"}; + + public static final String IDL_CLASS = "ClassDesc"; + public static final String[] IDL_CLASS_MODULE = {"javax","rmi","CORBA"}; + + public static final String IDL_IDLENTITY = "IDLEntity"; + public static final String IDL_SERIALIZABLE = "Serializable"; + public static final String IDL_EXTERNALIZABLE = "Externalizable"; + public static final String[] IDL_JAVA_IO_MODULE = {"java","io"}; + public static final String[] IDL_ORG_OMG_CORBA_MODULE = {"org","omg","CORBA"}; + public static final String[] IDL_ORG_OMG_CORBA_PORTABLE_MODULE = {"org","omg","CORBA","portable"}; + + public static final String IDL_JAVA_LANG_OBJECT = "_Object"; + public static final String[] IDL_JAVA_LANG_MODULE = {"java","lang"}; + + public static final String IDL_JAVA_RMI_REMOTE = "Remote"; + public static final String[] IDL_JAVA_RMI_MODULE = {"java","rmi"}; + + public static final String IDL_SEQUENCE = "seq"; + + public static final String IDL_CONSTRUCTOR = "create"; + + public static final String IDL_NAME_SEPARATOR = "::"; + public static final String IDL_BOOLEAN = "boolean"; + public static final String IDL_BYTE = "octet"; + public static final String IDL_CHAR = "wchar"; + public static final String IDL_SHORT = "short"; + public static final String IDL_INT = "long"; + public static final String IDL_LONG = "long long"; + public static final String IDL_FLOAT = "float"; + public static final String IDL_DOUBLE = "double"; + public static final String IDL_VOID = "void"; + + public static final String IDL_STRING = "WStringValue"; + public static final String IDL_CONSTANT_STRING = "wstring"; + public static final String IDL_CORBA_OBJECT = "Object"; + public static final String IDL_ANY = "any"; + + // File names: + + public static final String SOURCE_FILE_EXTENSION = ".java"; + public static final String IDL_FILE_EXTENSION = ".idl"; + + // Type Codes: + + public static final int TYPE_VOID = 0x00000001; // In PrimitiveType + public static final int TYPE_BOOLEAN = 0x00000002; // In PrimitiveType + public static final int TYPE_BYTE = 0x00000004; // In PrimitiveType + public static final int TYPE_CHAR = 0x00000008; // In PrimitiveType + public static final int TYPE_SHORT = 0x00000010; // In PrimitiveType + public static final int TYPE_INT = 0x00000020; // In PrimitiveType + public static final int TYPE_LONG = 0x00000040; // In PrimitiveType + public static final int TYPE_FLOAT = 0x00000080; // In PrimitiveType + public static final int TYPE_DOUBLE = 0x00000100; // In PrimitiveType + + public static final int TYPE_STRING = 0x00000200; // In SpecialClassType (String) + public static final int TYPE_ANY = 0x00000400; // In SpecialInterfaceType (Serializable,Externalizable) + public static final int TYPE_CORBA_OBJECT = 0x00000800; // In SpecialInterfaceType (CORBA.Object,Remote) + + public static final int TYPE_REMOTE = 0x00001000; // In RemoteType + public static final int TYPE_ABSTRACT = 0x00002000; // In AbstractType + public static final int TYPE_NC_INTERFACE = 0x00004000; // In NCInterfaceType + + public static final int TYPE_VALUE = 0x00008000; // In ValueType + public static final int TYPE_IMPLEMENTATION = 0x00010000; // In ImplementationType + public static final int TYPE_NC_CLASS = 0x00020000; // In NCClassType + + public static final int TYPE_ARRAY = 0x00040000; // In ArrayType + public static final int TYPE_JAVA_RMI_REMOTE = 0x00080000; // In SpecialInterfaceType + + // Type code masks: + + public static final int TYPE_NONE = 0x00000000; + public static final int TYPE_ALL = 0xFFFFFFFF; + public static final int TYPE_MASK = 0x00FFFFFF; + public static final int TM_MASK = 0xFF000000; + + // Type code modifiers: + + public static final int TM_PRIMITIVE = 0x01000000; + public static final int TM_COMPOUND = 0x02000000; + public static final int TM_CLASS = 0x04000000; + public static final int TM_INTERFACE = 0x08000000; + public static final int TM_SPECIAL_CLASS = 0x10000000; + public static final int TM_SPECIAL_INTERFACE= 0x20000000; + public static final int TM_NON_CONFORMING = 0x40000000; + public static final int TM_INNER = 0x80000000; + + // Attribute kinds... + + public static final int ATTRIBUTE_NONE = 0; // Not an attribute. + public static final int ATTRIBUTE_IS = 1; // read-only, had "is" prefix. + public static final int ATTRIBUTE_GET = 2; // read-only, had "get" prefix. + public static final int ATTRIBUTE_IS_RW = 3; // read-write, had "is" prefix. + public static final int ATTRIBUTE_GET_RW = 4; // read-write, had "get" prefix. + public static final int ATTRIBUTE_SET = 5; // had "set" prefix. + + public static final String[] ATTRIBUTE_WIRE_PREFIX = { + "", + "_get_", + "_get_", + "_get_", + "_get_", + "_set_", + }; +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/ContextElement.java b/src/share/classes/sun/rmi/rmic/iiop/ContextElement.java new file mode 100644 index 000000000..85de40ccb --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ContextElement.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +/** + * ContextElement provides a common interface for elements of a ContextStack. + * @author Bryan Atsatt + */ +public interface ContextElement { + public String getElementName(); +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/ContextStack.java b/src/share/classes/sun/rmi/rmic/iiop/ContextStack.java new file mode 100644 index 000000000..a6e0d99ba --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ContextStack.java @@ -0,0 +1,425 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.tools.java.CompilerError; + +/** + * ContextStack provides a mechanism to record parsing state. + * @author Bryan Atsatt + */ +public class ContextStack { + + // Context codes. + + public static final int TOP = 1; + + public static final int METHOD = 2; + public static final int METHOD_RETURN = 3; + public static final int METHOD_ARGUMENT = 4; + public static final int METHOD_EXCEPTION = 5; + + public static final int MEMBER = 6; + public static final int MEMBER_CONSTANT = 7; + public static final int MEMBER_STATIC = 8; + public static final int MEMBER_TRANSIENT = 9; + + public static final int IMPLEMENTS = 10; + public static final int EXTENDS = 11; + + // String versions of context codes. + + private static final String[] CODE_NAMES = { + "UNKNOWN ", + "Top level type ", + "Method ", + "Return parameter ", + "Parameter ", + "Exception ", + "Member ", + "Constant member ", + "Static member ", + "Transient member ", + "Implements ", + "Extends ", + }; + // Member data. + + private int currentIndex = -1; + private int maxIndex = 100; + private TypeContext[] stack = new TypeContext[maxIndex]; + private int newCode = TOP; + private BatchEnvironment env = null; + private boolean trace = false; + private TypeContext tempContext = new TypeContext(); + + private static final String TRACE_INDENT = " "; + + /** + * Constructor. + */ + public ContextStack (BatchEnvironment env) { + this.env = env; + env.contextStack = this; + } + + /** + * Return true if env.nerrors > 0. + */ + public boolean anyErrors () { + return env.nerrors > 0; + } + + /** + * Enable/disable tracing. + */ + public void setTrace(boolean trace) { + this.trace = trace; + } + + /** + * Check trace flag. + */ + public boolean isTraceOn() { + return trace; + } + + /** + * Get the environment. + */ + public BatchEnvironment getEnv() { + return env; + } + + /** + * Set the new context. + */ + public void setNewContextCode(int code) { + newCode = code; + } + + /** + * Get the current context code. + */ + public int getCurrentContextCode() { + return newCode; + } + + + /** + * If tracing on, write the current call stack (not the context stack) to + * System.out. + */ + final void traceCallStack () { + if (trace) dumpCallStack(); + } + + public final static void dumpCallStack() { + new Error().printStackTrace(System.out); + } + + /** + * Print a line indented by stack depth. + */ + final private void tracePrint (String text, boolean line) { + int length = text.length() + (currentIndex * TRACE_INDENT.length()); + StringBuffer buffer = new StringBuffer(length); + for (int i = 0; i < currentIndex; i++) { + buffer.append(TRACE_INDENT); + } + buffer.append(text); + if (line) { + buffer.append("\n"); + } + System.out.print(buffer.toString()); + } + + /** + * If tracing on, print a line. + */ + final void trace (String text) { + if (trace) { + tracePrint(text,false); + } + } + + /** + * If tracing on, print a line followed by a '\n'. + */ + final void traceln (String text) { + if (trace) { + tracePrint(text,true); + } + } + + /** + * If tracing on, print a pre-mapped ContextElement. + */ + final void traceExistingType (Type type) { + if (trace) { + tempContext.set(newCode,type); + traceln(toResultString(tempContext,true,true)); + } + } + + /** + * Push a new element on the stack. + * @return the new element. + */ + public TypeContext push (ContextElement element) { + + currentIndex++; + + // Grow array if need to... + + if (currentIndex == maxIndex) { + int newMax = maxIndex * 2; + TypeContext[] newStack = new TypeContext[newMax]; + System.arraycopy(stack,0,newStack,0,maxIndex); + maxIndex = newMax; + stack = newStack; + } + + // Make sure we have a context object to use at this position... + + TypeContext it = stack[currentIndex]; + + if (it == null) { + it = new TypeContext(); + stack[currentIndex] = it; + } + + // Set the context object... + + it.set(newCode,element); + + // Trace... + + traceln(toTrialString(it)); + + // Return... + + return it; + } + + /** + * Pop an element from the stack. + * @return the new current element or null if top. + */ + public TypeContext pop (boolean wasValid) { + + if (currentIndex < 0) { + throw new CompilerError("Nothing on stack!"); + } + + newCode = stack[currentIndex].getCode(); + traceln(toResultString(stack[currentIndex],wasValid,false)); + + Type last = stack[currentIndex].getCandidateType(); + if (last != null) { + + // Set status... + + if (wasValid) { + last.setStatus(Constants.STATUS_VALID); + } else { + last.setStatus(Constants.STATUS_INVALID); + } + } + + currentIndex--; + + if (currentIndex < 0) { + + // Done parsing, so update the invalid types + // if this type was valid... + + if (wasValid) { + Type.updateAllInvalidTypes(this); + } + return null; + } else { + return stack[currentIndex]; + } + } + + /** + * Get the current size. + */ + public int size () { + return currentIndex + 1; + } + + /** + * Get a specific context. + */ + public TypeContext getContext (int index) { + + if (currentIndex < index) { + throw new Error("Index out of range"); + } + return stack[index]; + } + + /** + * Get the current top context. + */ + public TypeContext getContext () { + + if (currentIndex < 0) { + throw new Error("Nothing on stack!"); + } + return stack[currentIndex]; + } + + /** + * Is parent context a value type? + */ + public boolean isParentAValue () { + + if (currentIndex > 0) { + return stack[currentIndex - 1].isValue(); + } else { + return false; + } + } + + /** + * Get parent context. Null if none. + */ + public TypeContext getParentContext () { + + if (currentIndex > 0) { + return stack[currentIndex - 1]; + } else { + return null; + } + } + + /** + * Get a string for the context name... + */ + public String getContextCodeString () { + + if (currentIndex >= 0) { + return CODE_NAMES[newCode]; + } else { + return CODE_NAMES[0]; + } + } + + /** + * Get a string for the given context code... + */ + public static String getContextCodeString (int contextCode) { + return CODE_NAMES[contextCode]; + } + + private String toTrialString(TypeContext it) { + int code = it.getCode(); + if (code != METHOD && code != MEMBER) { + return it.toString() + " (trying " + it.getTypeDescription() + ")"; + } else { + return it.toString(); + } + } + + private String toResultString (TypeContext it, boolean result, boolean preExisting) { + int code = it.getCode(); + if (code != METHOD && code != MEMBER) { + if (result) { + String str = it.toString() + " --> " + it.getTypeDescription(); + if (preExisting) { + return str + " [Previously mapped]"; + } else { + return str; + } + } + } else { + if (result) { + return it.toString() + " --> [Mapped]"; + } + } + return it.toString() + " [Did not map]"; + } + + public void clear () { + for (int i = 0; i < stack.length; i++) { + if (stack[i] != null) stack[i].destroy(); + } + } +} + + +class TypeContext { + + public void set(int code, ContextElement element) { + this.code = code; + this.element = element; + if (element instanceof ValueType) { + isValue = true; + } else { + isValue = false; + } + } + + public int getCode() { + return code; + } + + public String getName() { + return element.getElementName(); + } + + public Type getCandidateType() { + if (element instanceof Type) { + return (Type) element; + } else { + return null; + } +} + +public String getTypeDescription() { + if (element instanceof Type) { + return ((Type) element).getTypeDescription(); + } else { + return "[unknown type]"; + } +} + +public String toString () { + if (element != null) { + return ContextStack.getContextCodeString(code) + element.getElementName(); + } else { + return ContextStack.getContextCodeString(code) + "null"; + } +} + +public boolean isValue () { + return isValue; +} + + public boolean isConstant () { + return code == ContextStack.MEMBER_CONSTANT; + } + + public void destroy() { + if (element instanceof Type) { + ((Type)element).destroy(); + } + element = null; + } + + private int code = 0; + private ContextElement element = null; + private boolean isValue = false; +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/DirectoryLoader.java b/src/share/classes/sun/rmi/rmic/iiop/DirectoryLoader.java new file mode 100644 index 000000000..8921f247e --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/DirectoryLoader.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Hashtable; +import java.io.File; +import java.io.FileInputStream; + +/** + * DirectoryLoader is a simple ClassLoader which loads from a specified + * file system directory. + * @author Bryan Atsatt + * @version 1.0 + */ + +public class DirectoryLoader extends ClassLoader { + + private Hashtable cache; + private File root; + + /** + * Constructor. + */ + public DirectoryLoader (File rootDir) { + cache = new Hashtable(); + if (rootDir == null || !rootDir.isDirectory()) { + throw new IllegalArgumentException(); + } + root = rootDir; + } + + private DirectoryLoader () {} + + /** + * Convenience version of loadClass which sets 'resolve' == true. + */ + public Class loadClass(String className) throws ClassNotFoundException { + return loadClass(className, true); + } + + /** + * This is the required version of loadClass which is called + * both from loadClass above and from the internal function + * FindClassFromClass. + */ + public synchronized Class loadClass(String className, boolean resolve) + throws ClassNotFoundException { + Class result; + byte classData[]; + + // Do we already have it in the cache? + + result = (Class) cache.get(className); + + if (result == null) { + + // Nope, can we get if from the system class loader? + + try { + + result = super.findSystemClass(className); + + } catch (ClassNotFoundException e) { + + // No, so try loading it... + + classData = getClassFileData(className); + + if (classData == null) { + throw new ClassNotFoundException(); + } + + // Parse the class file data... + + result = defineClass(classData, 0, classData.length); + + if (result == null) { + throw new ClassFormatError(); + } + + // Resolve it... + + if (resolve) resolveClass(result); + + // Add to cache... + + cache.put(className, result); + } + } + + return result; + } + + /** + * Reurn a byte array containing the contents of the class file. Returns null + * if an exception occurs. + */ + private byte[] getClassFileData (String className) { + + byte result[] = null; + FileInputStream stream = null; + + // Get the file... + + File classFile = new File(root,className.replace('.',File.separatorChar) + ".class"); + + // Now get the bits... + + try { + stream = new FileInputStream(classFile); + result = new byte[stream.available()]; + stream.read(result); + } catch(ThreadDeath death) { + throw death; + } catch (Throwable e) { + } + + finally { + if (stream != null) { + try { + stream.close(); + } catch(ThreadDeath death) { + throw death; + } catch (Throwable e) { + } + } + } + + return result; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/Generator.java b/src/share/classes/sun/rmi/rmic/iiop/Generator.java new file mode 100644 index 000000000..0c6dac229 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/Generator.java @@ -0,0 +1,416 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.IOException; +import sun.tools.java.Identifier; +import sun.tools.java.ClassPath; +import sun.tools.java.ClassFile; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.rmi.rmic.IndentingWriter; +import sun.rmi.rmic.Main; +import sun.rmi.rmic.iiop.Util; +import java.util.HashSet; + +/** + * Generator provides a small framework from which IIOP-specific + * generators can inherit. Common logic is implemented here which uses + * both abstract methods as well as concrete methods which subclasses may + * want to override. The following methods must be present in any subclass: + *

                + *      Default constructor
                + *              CompoundType getTopType(BatchEnvironment env, ClassDefinition cdef); 
                + *      int parseArgs(String argv[], int currentIndex);
                + *      boolean requireNewInstance();
                + *              OutputType[] getOutputTypesFor(CompoundType topType,
                + *                                     HashSet alreadyChecked);
                + *              String getFileNameExtensionFor(OutputType outputType);
                + *              void writeOutputFor (   OutputType outputType,
                + *                              HashSet alreadyChecked,
                + *                                                              IndentingWriter writer) throws IOException;
                + * 
                + * @version 1.0, 2/24/98 + * @author Bryan Atsatt + */ +public abstract class Generator implements sun.rmi.rmic.Generator, + sun.rmi.rmic.iiop.Constants { + + protected boolean alwaysGenerate = false; + protected BatchEnvironment env = null; + protected ContextStack contextStack = null; + private boolean trace = false; + protected boolean idl = false; + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param error Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + if (argv[i].equalsIgnoreCase("-always") || + argv[i].equalsIgnoreCase("-alwaysGenerate")) { + alwaysGenerate = true; + argv[i] = null; + } else if (argv[i].equalsIgnoreCase("-xtrace")) { + trace = true; + argv[i] = null; + } + } + } + return true; + } + + /** + * Return true if non-conforming types should be parsed. + * @param stack The context stack. + */ + protected abstract boolean parseNonConforming(ContextStack stack); + + /** + * Create and return a top-level type. + * @param cdef The top-level class definition. + * @param stack The context stack. + * @return The compound type or null if is non-conforming. + */ + protected abstract CompoundType getTopType(ClassDefinition cdef, ContextStack stack); + + /** + * Return an array containing all the file names and types that need to be + * generated for the given top-level type. The file names must NOT have an + * extension (e.g. ".java"). + * @param topType The type returned by getTopType(). + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + */ + protected abstract OutputType[] getOutputTypesFor(CompoundType topType, + HashSet alreadyChecked); + + /** + * Return the file name extension for the given file name (e.g. ".java"). + * All files generated with the ".java" extension will be compiled. To + * change this behavior for ".java" files, override the compileJavaSourceFile + * method to return false. + * @param outputType One of the items returned by getOutputTypesFor(...) + */ + protected abstract String getFileNameExtensionFor(OutputType outputType); + + /** + * Write the output for the given OutputFileName into the output stream. + * @param name One of the items returned by getOutputTypesFor(...) + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + * @param writer The output stream. + */ + protected abstract void writeOutputFor(OutputType outputType, + HashSet alreadyChecked, + IndentingWriter writer) throws IOException; + + /** + * Return true if a new instance should be created for each + * class on the command line. Subclasses which return true + * should override newInstance() to return an appropriately + * constructed instance. + */ + protected abstract boolean requireNewInstance(); + + /** + * Return true if the specified file needs generation. + */ + public boolean requiresGeneration (File target, Type theType) { + + boolean result = alwaysGenerate; + + if (!result) { + + // Get a ClassFile instance for base source or class + // file. We use ClassFile so that if the base is in + // a zip file, we can still get at it's mod time... + + ClassFile baseFile; + ClassPath path = env.getClassPath(); + String className = theType.getQualifiedName().replace('.',File.separatorChar); + + // First try the source file... + + baseFile = path.getFile(className + ".source"); + + if (baseFile == null) { + + // Then try class file... + + baseFile = path.getFile(className + ".class"); + } + + // Do we have a baseFile? + + if (baseFile != null) { + + // Yes, grab baseFile's mod time... + + long baseFileMod = baseFile.lastModified(); + + // Get a File instance for the target. If it is a source + // file, create a class file instead since the source file + // will frequently be deleted... + + String targetName = IDLNames.replace(target.getName(),".java",".class"); + String parentPath = target.getParent(); + File targetFile = new File(parentPath,targetName); + + // Does the target file exist? + + if (targetFile.exists()) { + + // Yes, so grab it's mod time... + + long targetFileMod = targetFile.lastModified(); + + // Set result... + + result = targetFileMod < baseFileMod; + + } else { + + // No, so we must generate... + + result = true; + } + } else { + + // No, so we must generate... + + result = true; + } + } + + return result; + } + + /** + * Create and return a new instance of self. Subclasses + * which need to do something other than default construction + * must override this method. + */ + protected Generator newInstance() { + Generator result = null; + try { + result = (Generator) getClass().newInstance(); + } + catch (Exception e){} // Should ALWAYS work! + + return result; + } + + /** + * Default constructor for subclasses to use. + */ + protected Generator() { + } + + /** + * Generate output. Any source files created which need compilation should + * be added to the compiler environment using the addGeneratedFile(File) + * method. + * + * @param env The compiler environment + * @param cdef The definition for the implementation class or interface from + * which to generate output + * @param destDir The directory for the root of the package hierarchy + * for generated files. May be null. + */ + public void generate(sun.rmi.rmic.BatchEnvironment env, ClassDefinition cdef, File destDir) { + + this.env = (BatchEnvironment) env; + contextStack = new ContextStack(this.env); + contextStack.setTrace(trace); + + // Make sure the environment knows whether or not to parse + // non-conforming types. This will clear out any previously + // parsed types if necessary... + + this.env.setParseNonConforming(parseNonConforming(contextStack)); + + // Get our top level type... + + CompoundType topType = getTopType(cdef,contextStack); + if (topType != null) { + + Generator generator = this; + + // Do we need to make a new instance? + + if (requireNewInstance()) { + + // Yes, so make one. 'this' instance is the one instantiated by Main + // and which knows any needed command line args... + + generator = newInstance(); + } + + // Now generate all output files... + + generator.generateOutputFiles(topType, this.env, destDir); + } + } + + /** + * Create and return a new instance of self. Subclasses + * which need to do something other than default construction + * must override this method. + */ + protected void generateOutputFiles (CompoundType topType, + BatchEnvironment env, + File destDir) { + + // Grab the 'alreadyChecked' HashSet from the environment... + + HashSet alreadyChecked = env.alreadyChecked; + + // Ask subclass for a list of output types... + + OutputType[] types = getOutputTypesFor(topType,alreadyChecked); + + // Process each file... + + for (int i = 0; i < types.length; i++) { + OutputType current = types[i]; + String className = current.getName(); + File file = getFileFor(current,destDir); + boolean sourceFile = false; + + // Do we need to generate this file? + + if (requiresGeneration(file,current.getType())) { + + // Yes. If java source file, add to environment so will be compiled... + + if (file.getName().endsWith(".java")) { + sourceFile = compileJavaSourceFile(current); + + // Are we supposeded to compile this one? + + if (sourceFile) { + env.addGeneratedFile(file); + } + } + + // Now create an output stream and ask subclass to fill it up... + + try { + IndentingWriter out = new IndentingWriter( + new OutputStreamWriter(new FileOutputStream(file)),INDENT_STEP,TAB_SIZE); + + long startTime = 0; + if (env.verbose()) { + startTime = System.currentTimeMillis(); + } + + writeOutputFor(types[i],alreadyChecked,out); + out.close(); + + if (env.verbose()) { + long duration = System.currentTimeMillis() - startTime; + env.output(Main.getText("rmic.generated", file.getPath(), Long.toString(duration))); + } + if (sourceFile) { + env.parseFile(new ClassFile(file)); + } + } catch (IOException e) { + env.error(0, "cant.write", file.toString()); + return; + } + } else { + + // No, say so if we need to... + + if (env.verbose()) { + env.output(Main.getText("rmic.previously.generated", file.getPath())); + } + } + } + } + + /** + * Return the File object that should be used as the output file + * for the given OutputType. + * @param outputType The type to create a file for. + * @param destinationDir The directory to use as the root of the + * package heirarchy. May be null, in which case the current + * classpath is searched to find the directory in which to create + * the output file. If that search fails (most likely because the + * package directory lives in a zip or jar file rather than the + * file system), the current user directory is used. + */ + protected File getFileFor(OutputType outputType, File destinationDir) { + // Calling this method does some crucial initialization + // in a subclass implementation. Don't skip it. + Identifier id = getOutputId(outputType); + File packageDir = null; + if(idl){ + packageDir = Util.getOutputDirectoryForIDL(id,destinationDir,env); + } else { + packageDir = Util.getOutputDirectoryForStub(id,destinationDir,env); + } + String classFileName = outputType.getName() + getFileNameExtensionFor(outputType); + return new File(packageDir, classFileName); + } + + /** + * Return an identifier to use for output. + * @param outputType the type for which output is to be generated. + * @return the new identifier. This implementation returns the input parameter. + */ + protected Identifier getOutputId (OutputType outputType) { + return outputType.getType().getIdentifier(); + } + + /** + * Return true if the given file should be compiled. + * @param outputType One of the items returned by getOutputTypesFor(...) for + * which getFileNameExtensionFor(OutputType) returned ".java". + */ + protected boolean compileJavaSourceFile (OutputType outputType) { + return true; + } + + //_____________________________________________________________________ + // OutputType is a simple wrapper for a name and a Type + //_____________________________________________________________________ + + public class OutputType { + private String name; + private Type type; + + public OutputType (String name, Type type) { + this.name = name; + this.type = type; + } + + public String getName() { + return name; + } + + public Type getType() { + return type; + } + } +} + diff --git a/src/share/classes/sun/rmi/rmic/iiop/IDLGenerator.java b/src/share/classes/sun/rmi/rmic/iiop/IDLGenerator.java new file mode 100644 index 000000000..3571080b9 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/IDLGenerator.java @@ -0,0 +1,2065 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.File; +import java.io.IOException; +import java.text.DateFormat; +import java.util.Date; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Locale; +import java.util.StringTokenizer; +import java.util.Vector; +import sun.tools.java.Identifier; +import sun.tools.java.ClassDefinition; +import sun.tools.java.CompilerError; +import sun.rmi.rmic.IndentingWriter; +import java.util.HashSet; +import sun.rmi.rmic.Main; + +/** + * An IDL generator for rmic. + * + * @version 1.0, 2/23/98 + * @author Steve Newberry, Bryan Atsatt + */ +public class IDLGenerator extends sun.rmi.rmic.iiop.Generator { + + private boolean valueMethods = true; + private boolean factory = true; //init==!factory + private Hashtable ifHash = new Hashtable(); //IDL file Hashtable + private Hashtable imHash = new Hashtable(); //IDL module Hashtable + + private boolean isThrown = true; //flag for writeInclude + private boolean isException = true; //flag for writeBanner, writeIfndef + private boolean isForward = true; //flag for writeIfndef + private boolean forValuetype = true; //flag for writeInherits + + /** + * Default constructor for Main to use. + */ + public IDLGenerator() { + } + + + /** + * Return true if a new instance should be created for each + * class on the command line. Subclasses which return true + * should override newInstance() to return an appropriately + * constructed instance. + */ + protected boolean requireNewInstance() { + return false; + } + + /** + * Return true if non-conforming types should be parsed. + * @param stack The context stack. + */ + protected boolean parseNonConforming(ContextStack stack) { + return valueMethods; + } + + /** + * Create and return a top-level type. + * @param env The compiler environment. + * @param cdef The top-level class definition. + * @return An RemoteType or null if is non-conforming. + */ + protected sun.rmi.rmic.iiop.CompoundType getTopType(ClassDefinition cdef, + ContextStack stack) { + return CompoundType.forCompound(cdef,stack); + } + + + /** + * Return an Identifier which contains the fully-qualified IDL filename + * for the given OutputType. + * The OutputType contains a filename string (not directory) and Type. + * @param ot the OutputType for which directory nesting is to be defined. + * @return the new identifier. + */ + protected Identifier getOutputId ( + OutputType ot ) { + Identifier id = super.getOutputId( ot ); + + Type t = ot.getType(); + String fName = ot.getName(); + + if ( id == idJavaLangClass ) //java.lang.Class and array of + if ( t.isArray() ) + return Identifier.lookup( + "org.omg.boxedRMI.javax.rmi.CORBA." + fName ); + else return idClassDesc; + + if ( id == idJavaLangString && //array of java.lang.String + t.isArray() ) + return Identifier.lookup( "org.omg.boxedRMI.CORBA." + fName ); + + if ( "org.omg.CORBA.Object".equals( t.getQualifiedName() ) && + t.isArray() ) //array of org.omg.CORBA.Object + return Identifier.lookup( "org.omg.boxedRMI." + fName ); + + if ( t.isArray()) { //array + ArrayType at = (ArrayType)t; + Type et = at.getElementType(); + if ( et.isCompound() ) { + CompoundType ct = (CompoundType)et; + String qName = ct.getQualifiedName(); + if ( ct.isIDLEntity() ) + return Identifier.lookup( getQualifiedName( at ) ); + } + return Identifier.lookup( idBoxedRMI,id ); + } + + if ( t.isCompound() ) { //boxed IDLEntity + CompoundType ct = (CompoundType)t; + String qName = ct.getQualifiedName(); + if ( ct.isBoxed() ) + return Identifier.lookup( getQualifiedName( ct ) ); + } + + return id; + } + + + + /** + * Return the file name extension for the given file name (e.g. ".java"). + * All files generated with the ".java" extension will be compiled. To + * change this behavior for ".java" files, override the compileJavaSourceFile + * method to return false. + * @param outputType One of the items returned by getOutputTypesFor(...) + */ + protected String getFileNameExtensionFor(OutputType outputType) { + return IDL_FILE_EXTENSION; + } + + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param error Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + boolean result = super.parseArgs(argv,main); + String idlFrom; + String idlTo; + if (result) { + nextArg: + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + if (argv[i].equalsIgnoreCase("-idl")) { + idl = true; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-valueMethods" ) ) { + valueMethods = true; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-noValueMethods" ) ) { + valueMethods = false; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-init" ) ) { + factory = false; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-factory" ) ) { + factory = true; + argv[i] = null; + } + else if ( argv[i].equalsIgnoreCase( "-idlfile" ) ) { + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlFrom = argv[i]; + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlTo = argv[i]; + argv[i] = null; + ifHash.put( idlFrom,idlTo ); + continue nextArg; + } + } + main.error("rmic.option.requires.argument", "-idlfile"); + result = false; + } + else if ( argv[i].equalsIgnoreCase( "-idlmodule" ) ) { + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlFrom = argv[i]; + argv[i] = null; + if ( ++i < argv.length && argv[i] != null && !argv[i].startsWith("-") ) { + idlTo = argv[i]; + argv[i] = null; + imHash.put( idlFrom,idlTo ); + continue nextArg; + } + } + main.error("rmic.option.requires.argument", "-idlmodule"); + result = false; + } + + + } + } + } + return result; + } + + + + /** + * Return an array of OutputTypes for the IDL files that need to be + * generated for the given top-level type. + * OutputTypes contain filename string (not directory) and Type. + * @param topType The type returned by getTopType(). + * @param alreadyChecked A set of Types which have already been checked. + * @return Array of OutputTypes to generate + */ + protected OutputType[] getOutputTypesFor( + CompoundType topType, + HashSet alreadyChecked ) { + Vector refVec = getAllReferencesFor( topType ); + Vector outVec = new Vector(); + for ( int i1 = 0; i1 < refVec.size(); i1++ ) { //forall references + Type t = (Type)refVec.elementAt( i1 ); + if ( t.isArray() ) { + ArrayType at = (ArrayType)t; + int dim = at.getArrayDimension(); + Type et = at.getElementType(); + String fName = unEsc( et.getIDLName() ).replace( ' ','_' ); + for ( int i2 = 0; i2 < dim; i2++ ) { //foreach dimension + String fileName = "seq" + ( i2 + 1 ) + "_" + fName; + outVec.addElement( new OutputType( fileName,at ) ); + } + } + else if ( t.isCompound() ) { + String fName = unEsc( t.getIDLName() ); + outVec.addElement( new OutputType( fName.replace( ' ','_' ),t ) ); + if ( t.isClass() ) { + ClassType ct = (ClassType)t; + if ( ct.isException() ) { //exception file + fName = unEsc( ct.getIDLExceptionName() ); + outVec.addElement( new OutputType( fName.replace( ' ','_' ),t ) ); + } + } + } + } + OutputType[] outArr = new OutputType[outVec.size()]; + outVec.copyInto( outArr ); + return outArr; + } + + /** + * Get all referenced types of a given tyoe for which an IDL file needs + * to be generated. + * @param ct The given type. + * @return Vector of Types for which IDL must be generated. + */ + protected Vector getAllReferencesFor( + CompoundType ct ) { + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + int refSize; + refHash.put( ct.getQualifiedName(),ct ); //put the given type + accumulateReferences( refHash,spcHash,arrHash ); + do { + refSize = refHash.size(); + accumulateReferences( refHash,spcHash,arrHash ); + } + while ( refSize < refHash.size() ); //till hashtable stays same size + + Vector outVec = new Vector(); + Enumeration e = refHash.elements(); //ordinary references + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + outVec.addElement( t ); + } + e = spcHash.elements(); //special references + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + outVec.addElement( t ); + } + e = arrHash.elements(); //array references + nextSequence: + while ( e.hasMoreElements() ) { + ArrayType at = (ArrayType)e.nextElement(); + int dim = at.getArrayDimension(); + Type et = at.getElementType(); + Enumeration e2 = arrHash.elements(); + while ( e2.hasMoreElements() ) { //eliminate duplicates + ArrayType at2 = (ArrayType)e2.nextElement(); + if ( et == at2.getElementType() && //same element type & + dim < at2.getArrayDimension() ) //smaller dimension? + continue nextSequence; //ignore this one + } + outVec.addElement( at ); + } + return outVec; + } + + + /** + * Accumulate and filter all those types that are referenced by the given + * referenced types. + * Keep only those for which IDL is to be generated. + * @param refHash Hashtable containing the given types + * @param spcHash Hashtable containing referenced specials (IDL typedefs) + * @param arrHash Hashtable containing referenced arrays (dimensioned) + */ + protected void accumulateReferences( + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash ) { + Enumeration e = refHash.elements(); + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + Vector datVec = getData( t ); //collect and sort data + Vector mthVec = getMethods( t ); //collect and filter methods + getInterfaces( t,refHash ); //collect interfaces + getInheritance( t,refHash ); //add inheritance + getMethodReferences( mthVec,refHash,spcHash,arrHash,refHash ); + getMemberReferences( datVec,refHash,spcHash,arrHash ); + } + e = arrHash.elements(); //add array element references + while ( e.hasMoreElements() ) { + ArrayType at = (ArrayType)e.nextElement(); + Type et = at.getElementType(); + addReference( et,refHash,spcHash,arrHash ); + } + e = refHash.elements(); + while ( e.hasMoreElements() ) { + CompoundType t = (CompoundType)e.nextElement(); + if ( !isIDLGeneratedFor( t ) ) //remove if no IDL generation + refHash.remove( t.getQualifiedName() ); + } + } + + + + /** + * Determine if IDL should be generated for a referenced type. + * Do not generate IDL for a CORBA Object reference. It gets mapped + * to the original IDL or to Object (if exactly org.omg.CORBA.Object) + * Generate (boxed) IDL for an IDL Entity unless it is an IDL user + * exception, a ValueBase, an AbstractBase (or a CORBA Object). + * Do not generate IDL for Implementation classes..unless they inherit + * from multiple distinct remote interfaces + * @param t The type to check. + * @return true or false + */ + protected boolean isIDLGeneratedFor( + CompoundType t ) { + if ( t.isCORBAObject() ) return false; + if ( t.isIDLEntity() ) + if ( t.isBoxed() ) return true; + else if ( "org.omg.CORBA.portable.IDLEntity" + .equals( t.getQualifiedName() ) ) return true; + else if ( t.isCORBAUserException() ) return true; + else return false; + Hashtable inhHash = new Hashtable(); + getInterfaces( t,inhHash ); + if ( t.getTypeCode() == TYPE_IMPLEMENTATION ) + if ( inhHash.size() < 2 ) return false; //no multiple inheritance + else return true; + return true; //generate IDL for this type + } + + + /** + * Write the output for the given OutputFileName into the output stream. + * (The IDL mapping for java.lang.Class is generated from + * javax.rmi.CORBA.ClassDesc in the tools workspace) + * @param OutputType ot One of the items returned by getOutputTypesFor(...) + * @param alreadyChecked A set of Types which have already been checked. + * Intended to be passed to Type.collectMatching(filter,alreadyChecked). + * @param p The output stream. + */ + protected void writeOutputFor( + OutputType ot, + HashSet alreadyChecked, + IndentingWriter p ) + throws IOException { + Type t = ot.getType(); + if ( t.isArray() ) { //specialcase: sequence + writeSequence( ot,p ); + return; + } + if ( isSpecialReference( t ) ) { //specialcase: IDL typecode + writeSpecial( t,p ); + return; + } + if ( t.isCompound() ) { //specialcase: boxed IDL + CompoundType ct = (CompoundType)t; + if ( ct.isIDLEntity() && ct.isBoxed() ) { + writeBoxedIDL( ct,p ); + return; + } + } + if ( t.isClass() ) { //specialcase: exception + ClassType ct = (ClassType)t; + if ( ct.isException() ) { + String eName = unEsc( ct.getIDLExceptionName() ); + String fName = ot.getName(); + if ( fName.equals( eName.replace( ' ','_' ) ) ) { + writeException( ct,p ); + return; + } + } + } + switch ( t.getTypeCode() ) { //general case + case TYPE_IMPLEMENTATION: + writeImplementation( (ImplementationType)t,p ); + break; + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: + writeNCType( (CompoundType)t,p ); + break; + case TYPE_ABSTRACT: //AbstractType is a RemoteType + case TYPE_REMOTE: + writeRemote( (RemoteType)t,p ); + break; + case TYPE_VALUE: + writeValue( (ValueType)t,p ); + break; + default: + throw new CompilerError( + "IDLGenerator got unexpected type code: " + + t.getTypeCode()); + } + } + + + /** + * Write an IDL interface definition for a Java implementation class + * @param t The current ImplementationType + * @param p The output stream. + */ + protected void writeImplementation( + ImplementationType t, + IndentingWriter p ) + throws IOException { + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + + writeBanner( t,0,!isException,p ); + writeInheritedIncludes( inhHash,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeIncOrb( p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.p( "interface " + t.getIDLName() ); + writeInherits( inhHash,!forValuetype,p ); + + p.pln( " {" ); + p.pln( "};" ); + + p.pO();p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write an IDL valuetype definition for + * 1) a nonconforming Java class + * 2) a nonconforming Java interface (that is not an AbstractType) + * @param t The current NC Type (NCClassType or NCInterfaceType) + * @param p The output stream. + */ + protected void writeNCType( + CompoundType t, + IndentingWriter p ) + throws IOException { + Vector conVec = getConstants( t ); //collect constants + Vector mthVec = getMethods( t ); //collect methods + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + Hashtable excHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + getInheritance( t,inhHash ); //add inheritance + getMethodReferences( mthVec,refHash,spcHash,arrHash,excHash ); + + writeProlog( t,refHash,spcHash,arrHash,excHash,inhHash,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.p( "abstract valuetype " + t.getIDLName() ); + writeInherits( inhHash,!forValuetype,p ); + + p.pln( " {" ); + if ( conVec.size() + mthVec.size() > 0 ) { //any content? + p.pln();p.pI(); + for ( int i1 = 0; i1 < conVec.size(); i1++ ) //write constants + writeConstant( (CompoundType.Member)conVec.elementAt( i1 ),p ); + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) //write methods + writeMethod( (CompoundType.Method)mthVec.elementAt( i1 ),p ); + p.pO();p.pln(); + } + p.pln( "};" ); + + p.pO();p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write an IDL interface definition for either: + * 1) a conforming Java remote interface (RemoteType)..or + * 2) a non-conforming Java interface whose methods all throw + * java.rmi.RemoteException (AbstractType) + * @param t The current RemoteType + * @param p The output stream. + */ + protected void writeRemote( + RemoteType t, + IndentingWriter p ) + throws IOException { + Vector conVec = getConstants( t ); //collect constants + Vector mthVec = getMethods( t ); //collect methods + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + Hashtable excHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + getMethodReferences( mthVec,refHash,spcHash,arrHash,excHash ); + + writeProlog( t,refHash,spcHash,arrHash,excHash,inhHash,p ); + writeModule1( t,p ); + p.pln();p.pI(); + if ( t.getTypeCode() == TYPE_ABSTRACT ) p.p( "abstract " ); + p.p( "interface " + t.getIDLName() ); + writeInherits( inhHash,!forValuetype,p ); + + p.pln( " {" ); + if ( conVec.size() + mthVec.size() > 0 ) { //any constants or methods? + p.pln();p.pI(); + for ( int i1 = 0; i1 < conVec.size(); i1++ ) //constants + writeConstant( (CompoundType.Member)conVec.elementAt( i1 ),p ); + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) //methods, attributes + writeMethod( (CompoundType.Method)mthVec.elementAt( i1 ),p ); + p.pO();p.pln(); + } + p.pln( "};" ); + + p.pO();p.pln(); + writeRepositoryID ( t,p ); + p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write an IDL valuetype definition for a conforming Java class. + * Methods and constructors are optional..controlled by -valueMethods flag + * @param t The current ValueType + * @param p The output stream. + */ + protected void writeValue( + ValueType t, + IndentingWriter p ) + throws IOException { + Vector datVec = getData( t ); //collect and sort data + Vector conVec = getConstants( t ); //collect constants + Vector mthVec = getMethods( t ); //collect and filter methods + Hashtable inhHash = new Hashtable(); + Hashtable refHash = new Hashtable(); + Hashtable spcHash = new Hashtable(); + Hashtable arrHash = new Hashtable(); + Hashtable excHash = new Hashtable(); + getInterfaces( t,inhHash ); //collect interfaces + getInheritance( t,inhHash ); //add inheritance + getMethodReferences( mthVec,refHash,spcHash,arrHash,excHash ); + getMemberReferences( datVec,refHash,spcHash,arrHash ); + + writeProlog( t,refHash,spcHash,arrHash,excHash,inhHash,p ); + writeModule1( t,p ); + p.pln();p.pI(); + if ( t.isCustom() ) p.p( "custom " ); + p.p( "valuetype " + t.getIDLName() ); + writeInherits( inhHash,forValuetype,p ); + + p.pln( " {" ); + if ( conVec.size() + datVec.size() + mthVec.size() > 0 ) { //any content? + p.pln();p.pI(); + for ( int i1 = 0; i1 < conVec.size(); i1++ ) //write constants + writeConstant( (CompoundType.Member)conVec.elementAt( i1 ),p ); + for ( int i1 = 0; i1 < datVec.size(); i1++ ) { + CompoundType.Member mem = (CompoundType.Member)datVec.elementAt( i1 ); + if ( mem.getType().isPrimitive() ) + writeData( mem,p ); //write primitive data + } + for ( int i1 = 0; i1 < datVec.size(); i1++ ) { + CompoundType.Member mem = (CompoundType.Member)datVec.elementAt( i1 ); + if ( !mem.getType().isPrimitive() ) + writeData( mem,p ); //write non-primitive data + } + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) //write methods + writeMethod( (CompoundType.Method)mthVec.elementAt( i1 ),p ); + p.pO();p.pln(); + } + p.pln( "};" ); + + p.pO();p.pln(); + writeRepositoryID ( t,p ); + p.pln(); + writeModule2( t,p ); + writeEpilog( t,refHash,p ); + } + + + /** + * Write IDL prolog for a CompoundType. + * @param t The CompoundType. + * @param refHash Hashtable loaded with type references. + * @param spcHash Hashtable loaded with special type references. + * @param arrHash Hashtable loaded with array references. + * @param excHash Hashtable loaded with exceptions thrown. + * @param inhHash Hashtable loaded with inherited types. + * @param p The output stream. + */ + protected void writeProlog( + CompoundType t, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash, + Hashtable excHash, + Hashtable inhHash, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeForwardReferences( refHash,p ); + writeIncludes( excHash,isThrown,p ); //#includes for exceptions thrown + writeInheritedIncludes( inhHash,p ); + writeIncludes( spcHash,!isThrown,p ); //#includes for special types + writeBoxedRMIIncludes( arrHash,p ); + writeIDLEntityIncludes( refHash,p ); + writeIncOrb( p ); + writeIfndef( t,0,!isException,!isForward,p ); + } + + + /** + * Write IDL epilog for a CompoundType. + * @param t The CompoundType. + * @param refHash Hashtable loaded with type references. + * @param p The output stream. + */ + protected void writeEpilog( + CompoundType t, + Hashtable refHash, + IndentingWriter p ) + throws IOException { + writeIncludes( refHash,!isThrown,p ); //#includes for forward dcl types + writeEndif( p ); + } + + + + /** + * Write special typedef + * @param t A special Type. + * @param p The output stream. + */ + protected void writeSpecial( + Type t, + IndentingWriter p ) + throws IOException { + String spcName = t.getQualifiedName(); + if ( "java.io.Serializable".equals( spcName ) ) + writeJavaIoSerializable( t,p ); + else if ( "java.io.Externalizable".equals( spcName ) ) + writeJavaIoExternalizable( t,p ); + else if ( "java.lang.Object".equals( spcName) ) + writeJavaLangObject( t,p ); + else if ( "java.rmi.Remote".equals( spcName) ) + writeJavaRmiRemote( t,p ); + else if ( "org.omg.CORBA.portable.IDLEntity".equals( spcName) ) + writeIDLEntity( t,p ); + } + + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.io.Serializable. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaIoSerializable( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any Serializable;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.io.Externalizable. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaIoExternalizable( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any Externalizable;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.lang.Object. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaLangObject( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any _Object;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write a hard-coded IDL typedef definition for the special case + * java.rmi.Remote. + * @param t The current Type + * @param p The output stream. + */ + protected void writeJavaRmiRemote( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef Object Remote;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + + /** + * Write a hard-coded IDL typedef definition for the special case + * org.omg.CORBA.portable.IDLEntity + * @param t The current Type + * @param p The output stream. + */ + protected void writeIDLEntity( + Type t, + IndentingWriter p ) + throws IOException { + writeBanner( t,0,!isException,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + p.pln( "typedef any IDLEntity;" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Filter and collect non-duplicate inherited interfaces for a type + * @param ct The current CompoundType + * @param inhHash Hashtable containing the inherited interfaces + */ + protected void getInterfaces( + CompoundType ct, + Hashtable inhHash ) { + InterfaceType[] infs = ct.getInterfaces(); + nextInterface: + for ( int i1 = 0; i1 < infs.length; i1++ ) { //forall inherited interfaces + String inhName = infs[i1].getQualifiedName(); + switch ( ct.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_VALUE: //filter for classes + if ( "java.io.Externalizable".equals( inhName ) || + "java.io.Serializable".equals( inhName ) || + "org.omg.CORBA.portable.IDLEntity".equals( inhName ) ) + continue nextInterface; + break; + default: //filter for all others + if ( "java.rmi.Remote".equals( inhName ) ) + continue nextInterface; + break; + } + inhHash.put( inhName,infs[i1] ); //add this one + } + } + + + /** + * Filter and add base class inheritance for a class type + * @param ct The current CompoundType + * @param inhHash Hashtable containing inherited types + */ + protected void getInheritance( + CompoundType ct, + Hashtable inhHash ) { + ClassType par = ct.getSuperclass(); //get parent + if ( par == null ) return; + String parName = par.getQualifiedName(); + switch ( ct.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_VALUE: + if ( "java.lang.Object".equals( parName ) ) //this is implicit + return; + break; + default: return; //ignore other types + } + inhHash.put( parName,par ); //add valid base class + } + + + /** + * Collect and filter type and array references from methods + * @param mthVec Given Vector of methods + * @param refHash Hashtable for type references + * @param spcHash Hashtable for special type references + * @param arrHash Hashtable for array references + * @param excHash Hashtable for exceptions thrown + */ + protected void getMethodReferences( + Vector mthVec, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash, + Hashtable excHash ) { + for ( int i1 = 0; i1 < mthVec.size(); i1++ ) { //forall methods + CompoundType.Method mth = (CompoundType.Method)mthVec.elementAt( i1 ); + Type[] args = mth.getArguments(); + Type ret = mth.getReturnType(); + getExceptions( mth,excHash ); //collect exceptions thrown + for ( int i2 = 0; i2 < args.length; i2++ ) //forall arguments + addReference( args[i2],refHash,spcHash,arrHash ); + addReference( ret,refHash,spcHash,arrHash ); + } + } + + + /** + * Collect and filter type and array references from data members + * @param datVec Given Vector of data members + * @param refHash Hashtable for type references + * @param spcHash Hashtable for special type references + * @param arrHash Hashtable for array references + */ + protected void getMemberReferences( + Vector datVec, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash ) { + for ( int i1 = 0; i1 < datVec.size(); i1++ ) { //forall datamembers + CompoundType.Member mem = (CompoundType.Member)datVec.elementAt( i1 ); + Type dat = mem.getType(); + addReference( dat,refHash,spcHash,arrHash ); + } + } + + + /** + * Add reference for given type avoiding duplication. + * Sort into specials, arrays and regular references. + * Filter out types which are not required. + * @param t Given Type + * @param refHash Hashtable for type references + * @param spcHash Hashtable for special type references + * @param arrHash Hashtable for array references + */ + protected void addReference( + Type ref, + Hashtable refHash, + Hashtable spcHash, + Hashtable arrHash ) { + String rName = ref.getQualifiedName(); + switch ( ref.getTypeCode() ) { + case TYPE_ABSTRACT: + case TYPE_REMOTE: + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: + case TYPE_VALUE: + refHash.put( rName,ref ); + return; + case TYPE_CORBA_OBJECT: + if ( "org.omg.CORBA.Object".equals( rName ) ) return; //don't want + refHash.put( rName,ref ); + return; + case TYPE_ARRAY: //array? + arrHash.put( rName + ref.getArrayDimension(),ref ); + return; + default: + if ( isSpecialReference( ref ) ) //special IDL typedef? + spcHash.put( rName,ref ); + } + } + + + + /** + * Determine whether given Type is a special reference. + * Special cases are: java.io.Serializable, java.io.Externalizable, + * java.lang.Object, java.rmi.Remote and org.omg.CORBA.portable.IDLEntity + * They are special because they have a hard-coded typedef defined in the + * spec. + * @param ref A referenced Type + * @return boolean indicating whether it's a special reference + */ + protected boolean isSpecialReference( + Type ref ) { + String rName = ref.getQualifiedName(); + if ( "java.io.Serializable".equals( rName ) ) return true; + if ( "java.io.Externalizable".equals( rName ) ) return true; + if ( "java.lang.Object".equals( rName) ) return true; + if ( "java.rmi.Remote".equals( rName) ) return true; + if ( "org.omg.CORBA.portable.IDLEntity".equals( rName) ) return true; + return false; + } + + + /** + * Collect and filter thrown exceptions for a given pre-filtered method. + * Keep only 'checked' exception classes minus java.rmi.RemoteException + * and its subclasses + * @param method The current method + * @param excHash Hashtable containing non-duplicate thrown exceptions + */ + protected void getExceptions( + CompoundType.Method mth, + Hashtable excHash ) { + ClassType[] excs = mth.getExceptions(); + for ( int i1 = 0; i1 < excs.length; i1++ ) { //forall exceptions + ClassType exc = excs[i1]; + if ( exc.isCheckedException() && + !exc.isRemoteExceptionOrSubclass() ) { + excHash.put( exc.getQualifiedName(),exc ); + } + } + } + + + /** + * Collect and filter methods for a type. + * Remove any private or inherited methods. + * @param ct The current CompoundType + * @return Vector containing the methods + */ + protected Vector getMethods( + CompoundType ct ) { + Vector vec = new Vector(); + int ctType = ct.getTypeCode(); + switch ( ctType ) { + case TYPE_ABSTRACT: + case TYPE_REMOTE: break; + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: + case TYPE_VALUE: if ( valueMethods ) break; + default: return vec; + } + Identifier ctId = ct.getIdentifier(); + CompoundType.Method[] mths = ct.getMethods(); + nextMethod: + for ( int i1 = 0; i1 < mths.length; i1++ ) { //forall methods + if ( mths[i1].isPrivate() || //private method? + mths[i1].isInherited() ) //inherited method? + continue nextMethod; //yes..ignore it + if ( ctType == TYPE_VALUE ) { + String mthName = mths[i1].getName(); + if ( "readObject" .equals( mthName ) || + "writeObject" .equals( mthName ) || + "readExternal".equals( mthName ) || + "writeExternal".equals( mthName ) ) + continue nextMethod; //ignore this one + } + if ( ( ctType == TYPE_NC_CLASS || + ctType == TYPE_NC_INTERFACE ) && + mths[i1].isConstructor() ) //init not valid for abstract valuetype + continue nextMethod; //ignore this one + vec.addElement( mths[i1] ); //add this one + } + return vec; + } + + + /** + * Collect constants for a type. + * A valid constant is a "public final static" field with a compile-time + * constant value for a primitive type or String + * @param ct The current CompoundType + * @return Vector containing the constants + */ + protected Vector getConstants( + CompoundType ct ) { + Vector vec = new Vector(); + CompoundType.Member[] mems = ct.getMembers(); + for ( int i1 = 0; i1 < mems.length; i1++ ) { //forall members + Type memType = mems[i1].getType(); + String memValue = mems[i1].getValue(); + if ( mems[i1].isPublic() && + mems[i1].isFinal() && + mems[i1].isStatic() && + ( memType.isPrimitive() || "String".equals( memType.getName() ) ) && + memValue != null ) + vec.addElement( mems[i1] ); //add this one + } + return vec; + } + + + /** + * Collect and sort data fields for a ValueType. + * Sort in Java (not IDL) Unicode name string lexicographic increasing + * order. + * Non-static, non-transient fields are mapped. + * If the type is a custom valuetype, only public fields are mapped. + * @param ct The current CompoundType + * @return Vector containing the data fields + */ + protected Vector getData( + CompoundType t ) { + Vector vec = new Vector(); + if ( t.getTypeCode() != TYPE_VALUE ) return vec; + ValueType vt = (ValueType)t; + CompoundType.Member[] mems = vt.getMembers(); + boolean notCust = !vt.isCustom(); + for ( int i1 = 0; i1 < mems.length; i1++ ) { //forall members + if ( !mems[i1].isStatic() && + !mems[i1].isTransient() && + ( mems[i1].isPublic() || notCust ) ) { + int i2; + String memName = mems[i1].getName(); + for ( i2 = 0; i2 < vec.size(); i2++ ) { //insert in java lex order + CompoundType.Member aMem = (CompoundType.Member)vec.elementAt( i2 ); + if ( memName.compareTo( aMem.getName() ) < 0 ) break; + } + vec.insertElementAt( mems[i1],i2 ); //insert this one + } + } + return vec; + } + + + /** + * Write forward references for referenced interfaces and valuetypes + * ...but not if the reference is to a boxed IDLEntity, + * @param refHash Hashtable loaded with referenced types + * @param p The output stream. + */ + protected void writeForwardReferences( + Hashtable refHash, + IndentingWriter p ) + throws IOException { + Enumeration refEnum = refHash.elements(); + nextReference: + while ( refEnum.hasMoreElements() ) { + Type t = (Type)refEnum.nextElement(); + if ( t.isCompound() ) { + CompoundType ct = (CompoundType)t; + if ( ct.isIDLEntity() ) + continue nextReference; //ignore IDLEntity reference + } + writeForwardReference( t,p ); + } + } + + + /** + * Write forward reference for given type + * @param t Given type + * @param p The output stream. + */ + protected void writeForwardReference( + Type t, + IndentingWriter p ) + throws IOException { + String qName = t.getQualifiedName(); + if ( "java.lang.String".equals( qName ) ) ; + else if ( "org.omg.CORBA.Object".equals( qName ) ) return ; //no fwd dcl + + writeIfndef( t,0,!isException,isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + switch ( t.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: p.p( "abstract valuetype " ); break; + case TYPE_ABSTRACT: p.p( "abstract interface " ); break; + case TYPE_VALUE: p.p( "valuetype " ); break; + case TYPE_REMOTE: + case TYPE_CORBA_OBJECT: p.p( "interface " ); break; + default: ; //all other types were filtered + } + p.pln( t.getIDLName() + ";" ); + p.pO();p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write forward reference for boxed valuetype for single dimension of IDL + * sequence. + * If the dimension is <1 and the element is a CompoundType, write a + * forward declare for the element + * @param at ArrayType for forward declare + * @param dim The dimension to write + * @param p The output stream. + */ + protected void writeForwardReference( + ArrayType at, + int dim, + IndentingWriter p) + throws IOException { + Type et = at.getElementType(); + if ( dim < 1 ) { + if ( et.isCompound() ) { + CompoundType ct = (CompoundType)et; + writeForwardReference( et,p); + } + return; + } + String fName = unEsc( et.getIDLName() ).replace( ' ','_' ); + + writeIfndef( at,dim,!isException,isForward,p ); + writeModule1( at,p ); + p.pln();p.pI(); + switch ( et.getTypeCode() ) { + case TYPE_NC_CLASS: + case TYPE_NC_INTERFACE: p.p( "abstract valuetype " ); break; + case TYPE_ABSTRACT: p.p( "abstract interface " ); break; + case TYPE_VALUE: p.p( "valuetype " ); break; + case TYPE_REMOTE: + case TYPE_CORBA_OBJECT: p.p( "interface " ); break; + default: ; //all other types were filtered + } + p.pln( "seq" + dim + "_" + fName + ";" ); + p.pO();p.pln(); + writeModule2( at,p ); + writeEndif( p ); + } + + + /** + * Write #includes for boxed IDLEntity references. + * @param refHash Hashtable loaded with referenced types + * @param p The output stream. + */ + protected void writeIDLEntityIncludes( + Hashtable refHash, + IndentingWriter p ) + throws IOException { + Enumeration refEnum = refHash.elements(); + while ( refEnum.hasMoreElements() ) { + Type t = (Type)refEnum.nextElement(); + if ( t.isCompound() ) { + CompoundType ct = (CompoundType)t; + if ( ct.isIDLEntity() ) { //select IDLEntities + writeInclude( ct,0,!isThrown,p ); + refHash.remove( ct.getQualifiedName() ); //avoid another #include + } + } + } + } + + + /** + * Write #includes + * @param incHash Hashtable loaded with Types to include + * @param isThrown true if Types are thrown exceptions + * @param p The output stream. + */ + protected void writeIncludes( + Hashtable incHash, + boolean isThrown, + IndentingWriter p ) + throws IOException { + Enumeration incEnum = incHash.elements(); + while ( incEnum.hasMoreElements() ) { + CompoundType t = (CompoundType)incEnum.nextElement(); + writeInclude( t,0,isThrown,p ); + } + } + + + /** + * Write includes for boxedRMI valuetypes for IDL sequences. + * Write only the maximum dimension found for an ArrayType. + * @param arrHash Hashtable loaded with array types + * @param p The output stream. + */ + protected void writeBoxedRMIIncludes( + Hashtable arrHash, + IndentingWriter p) + throws IOException { + Enumeration e1 = arrHash.elements(); + nextSequence: + while ( e1.hasMoreElements() ) { + ArrayType at = (ArrayType)e1.nextElement(); + int dim = at.getArrayDimension(); + Type et = at.getElementType(); + + Enumeration e2 = arrHash.elements(); + while ( e2.hasMoreElements() ) { //eliminate duplicates + ArrayType at2 = (ArrayType)e2.nextElement(); + if ( et == at2.getElementType() && //same element type & + dim < at2.getArrayDimension() ) //smaller dimension? + continue nextSequence; //ignore this one + } + writeInclude( at,dim,!isThrown,p ); + } + } + + + /** + * Write #includes + * @param incHash Hashtable loaded with Types to include + * @param p The output stream. + */ + protected void writeInheritedIncludes( + Hashtable inhHash, + IndentingWriter p ) + throws IOException { + Enumeration inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { + CompoundType t = (CompoundType)inhEnum.nextElement(); + writeInclude( t,0,!isThrown,p ); + } + } + + + /** + * Write a #include. + * @param t Type to include + * @param dim The dimension to write if t is an array. + * @param isThrown boolean indicating if include is for thrown exception. + * @param p The output stream. + */ + protected void writeInclude( + Type t, + int dim, + boolean isThrown, + IndentingWriter p) + throws IOException { + CompoundType ct; + String tName; + String[] modNames; + if ( t.isCompound() ) { + ct = (CompoundType)t; + String qName = ct.getQualifiedName(); + if ( "java.lang.String".equals( qName ) ) { + writeIncOrb( p ); //#include orb.idl for String + return; + } + if ( "org.omg.CORBA.Object".equals( qName ) ) + return; //Object treated like primitive + modNames = getIDLModuleNames( ct ); //module name array + tName = unEsc( ct.getIDLName() ); //file name default + + if ( ct.isException() ) + if ( ct.isIDLEntityException() ) + if ( ct.isCORBAUserException() ) + if ( isThrown ) tName = unEsc( ct.getIDLExceptionName() ); + else ; + else tName = ct.getName(); //use original IDL name + else if ( isThrown ) + tName = unEsc( ct.getIDLExceptionName() ); + } + else if ( t.isArray() ) { + Type et = t.getElementType(); //file name for sequence + if ( dim > 0 ) { + modNames = getIDLModuleNames( t ); //module name array + tName = "seq" + dim + "_" + unEsc( et.getIDLName().replace( ' ','_' ) ); + } + else{ //#include element + if ( !et.isCompound() ) return; //no include needed for primitive + ct = (CompoundType) et; + modNames = getIDLModuleNames( ct ); //no boxedRMI for element + tName = unEsc( ct.getIDLName() ); + writeInclude( ct,modNames,tName,p ); + return; + } + } + else return; //no include needed for primitive + writeInclude( t,modNames,tName,p ); + } + + + /** + * Write a #include doing user specified -idlFile translation (if any) for + * IDLEntities. + * @param t Type to include. + * @param modNames Preprocessed module names (default). + * @param tName Preprocessed Type name (default). + * @param p The output stream. + */ + protected void writeInclude( + Type t, + String[] modNames, + String tName, + IndentingWriter p) + throws IOException { + if ( t.isCompound() ) { + CompoundType it = (CompoundType)t; + + if ( ifHash.size() > 0 && //any -idlFile translation to apply + it.isIDLEntity() ) { //..for this IDLEntity? + String qName = t.getQualifiedName(); //fully qualified orig Java name + + Enumeration k = ifHash.keys(); + while ( k.hasMoreElements() ) { //loop thro user-defined -idlFiles + String from = (String)k.nextElement(); + if ( qName.startsWith( from ) ) { //found a match? + String to = (String)ifHash.get( from ); + p.pln( "#include \"" + to + "\"" ); //user-specified idl filename + return; //don't look for any more + } + } + } + } + else if ( t.isArray() ) ; //no -idlFile translation needed for array + else return; //no #include needed for primitive + + p.p( "#include \"" ); //no -idlFile translation required + for ( int i1 = 0; i1 < modNames.length; i1++ ) p.p( modNames[i1] + "/" ); + p.p( tName + ".idl\"" ); + p.pln(); + } + + + /** + * Return the fully qualified Java Name for a Type. + * IDLEntity preprocessing done by getIDLModuleNames(t) + * @param t Given Type + * @return Array containing the original module nesting. + */ + protected String getQualifiedName( + Type t ) { + String[] modNames = getIDLModuleNames( t ); + int len = modNames.length; + StringBuffer buf = new StringBuffer(); + for ( int i1 = 0; i1 < len; i1++ ) + buf.append( modNames[i1] + "." ); + buf.append( t.getIDLName() ); + return buf.toString(); + } + + + /** + * Return the global fully qualified IDL Name for a Type. + * IDLEntity preprocessing done by getIDLModuleNames(t) + * @param t Given Type + * @return Array containing the original module nesting. + */ + protected String getQualifiedIDLName(Type t) { + if ( t.isPrimitive() ) + return t.getIDLName(); + if ( !t.isArray() && + "org.omg.CORBA.Object".equals( t.getQualifiedName() ) ) + return t.getIDLName(); + + String[] modNames = getIDLModuleNames( t ); + int len = modNames.length; + if (len > 0) { + StringBuffer buf = new StringBuffer(); + for ( int i1 = 0; i1 < len; i1++ ) + buf.append( IDL_NAME_SEPARATOR + modNames[i1] ); + buf.append( IDL_NAME_SEPARATOR + t.getIDLName() ); + return buf.toString(); + } else { + return t.getIDLName(); + } + } + + + /** + * Return the IDL module nesting of the given Type. + * For IDLEntity CompoundTypes (or their arrays) apply any user specified + * -idlModule translation or, if none applicable, strip any package + * prefix. + * Add boxedIDL or boxedRMI modules if required. + * @param t Given Type + * @return Array containing the original module nesting. + */ + protected String[] getIDLModuleNames(Type t) { + String[] modNames = t.getIDLModuleNames(); //default module name array + CompoundType ct; + if ( t.isCompound() ) { + ct = (CompoundType)t; + if ( !ct.isIDLEntity ) return modNames; //normal (non-IDLEntity) case + if ( "org.omg.CORBA.portable.IDLEntity" + .equals( t.getQualifiedName() ) ) + return modNames; + } + else if ( t.isArray() ) { + Type et = t.getElementType(); + if ( et.isCompound() ) { + ct = (CompoundType)et; + if ( !ct.isIDLEntity ) return modNames; //normal (non-IDLEntity) case + if ( "org.omg.CORBA.portable.IDLEntity" + .equals( t.getQualifiedName() ) ) + return modNames; + } + else return modNames; + } + else return modNames; //no preprocessing needed for primitives + + //it's an IDLEntity or an array of... + Vector mVec = new Vector(); + if ( !translateJavaPackage( ct,mVec ) ) //apply -idlModule translation + stripJavaPackage( ct,mVec ); //..or strip prefixes (not both) + + if ( ct.isBoxed() ) { //add boxedIDL if required + mVec.insertElementAt( "org",0 ); + mVec.insertElementAt( "omg",1 ); + mVec.insertElementAt( "boxedIDL",2 ); + } + if ( t.isArray() ) { //add boxedRMI if required + mVec.insertElementAt( "org",0 ); + mVec.insertElementAt( "omg",1 ); + mVec.insertElementAt( "boxedRMI",2 ); + } + String[] outArr = new String[mVec.size()]; + mVec.copyInto( outArr ); + return outArr; + } + + + /** + * Apply user specified -idlModule translation to package names of given + * IDLEntity ct. Example: + * -idlModule foo.bar real::mod::nesting + * @param ct CompoundType containing given IDLEntity. + * @param vec Returned Vector of translated IDL module names. + * @return boolean true if any translation was done. + */ + protected boolean translateJavaPackage( + CompoundType ct, + Vector vec ) { + vec.removeAllElements(); + boolean ret = false; + String fc = null; + if ( ! ct.isIDLEntity() ) return ret; + + String pName = ct.getPackageName(); //start from Java package names + if ( pName == null ) return ret; + StringTokenizer pt = new StringTokenizer( pName,"." ); + while ( pt.hasMoreTokens() ) vec.addElement( pt.nextToken() ); + + if ( imHash.size() > 0 ) { //any -idlModule translation to apply? + Enumeration k = imHash.keys(); + + nextModule: + while ( k.hasMoreElements() ) { //loop thro user-defined -idlModules + String from = (String)k.nextElement(); //from String.. + StringTokenizer ft = new StringTokenizer( from,"." ); + int vecLen = vec.size(); + int ifr; + for ( ifr = 0; ifr < vecLen && ft.hasMoreTokens(); ifr++ ) + if ( ! vec.elementAt(ifr).equals( ft.nextToken() ) ) + continue nextModule; //..no match + + if ( ft.hasMoreTokens() ) { //matched so far.. + fc = ft.nextToken(); //a 'from' token remains + if ( ! ct.getName().equals( fc ) || //matches class name? + ft.hasMoreTokens() ) + continue nextModule; //..no match + } + + ret = true; //found a match + for ( int i4 = 0; i4 < ifr; i4++ ) + vec.removeElementAt( 0 ); //remove 'from' package + + String to = (String)imHash.get( from ); //..to String + StringTokenizer tt = new StringTokenizer( to,IDL_NAME_SEPARATOR ); + + int itoco = tt.countTokens(); + int ito = 0; + if ( fc != null ) itoco--; //user may have given IDL type + for ( ito = 0; ito < itoco; ito++ ) + vec.insertElementAt( tt.nextToken(),ito ); //insert 'to' modules + if ( fc != null ) { + String tc = tt.nextToken(); + if ( ! ct.getName().equals( tc ) ) //not the IDL type, so.. + vec.insertElementAt( tc,ito ); //insert final 'to' module + } + } + } + return ret; + } + + + /** + * Strip Java #pragma prefix and/or -pkgPrefix prefix package names from + * given IDLEntity ct. + * Strip any package prefix which may have been added by comparing with + * repository id. For example in Java package fake.omega: + * repid = IDL:phoney.pfix/omega/Juliet:1.0 gives { "omega" } + * @param ct CompoundType containing given IDLEntity. + * @param vec Returned Vector of stripped IDL module names. + */ + protected void stripJavaPackage( + CompoundType ct, + Vector vec ) { + vec.removeAllElements(); + if ( ! ct.isIDLEntity() ) return; + + String repID = ct.getRepositoryID().substring( 4 ); + StringTokenizer rept = new StringTokenizer( repID,"/" ); + if ( rept.countTokens() < 2 ) return; + + while ( rept.hasMoreTokens() ) + vec.addElement( rept.nextToken() ); + vec.removeElementAt( vec.size() - 1 ); + + String pName = ct.getPackageName(); //start from Java package names + if ( pName == null ) return; + Vector pVec = new Vector(); + StringTokenizer pt = new StringTokenizer( pName,"." ); + while ( pt.hasMoreTokens() ) pVec.addElement( pt.nextToken() ); + + int i1 = vec.size() - 1; + int i2 = pVec.size() - 1; + while ( i1 >= 0 && i2 >= 0 ) { //go R->L till mismatch + String rep = (String)( vec.elementAt( i1 ) ); + String pkg = (String)( pVec.elementAt( i2 ) ); + if ( ! pkg.equals( rep ) ) break; + i1--; i2--; + } + for ( int i3 = 0; i3 <= i1; i3++ ) + vec.removeElementAt( 0 ); //strip prefix + } + + + + /** + * Write boxedRMI valuetype for a single dimension of an IDL sequence + * indicated by the given OutputType. + * The filename for the OutputType is of the form "seqn_elemName" where n + * is the dimension required. + * @param ot Given OutputType. + * @param p The output stream. + */ + protected void writeSequence( + OutputType ot, + IndentingWriter p) + throws IOException { + ArrayType at = (ArrayType)ot.getType(); + Type et = at.getElementType(); + String fName = ot.getName(); + int dim = Integer.parseInt( fName.substring( 3,fName.indexOf( "_" ) ) ); + String idlName = unEsc( et.getIDLName() ).replace( ' ','_' ); + String qIdlName = getQualifiedIDLName( et ); + String qName = et.getQualifiedName(); + + String repID = at.getRepositoryID(); + int rix1 = repID.indexOf( '[' ); //edit repository id + int rix2 = repID.lastIndexOf( '[' ) + 1; + StringBuffer rid = new StringBuffer( + repID.substring( 0,rix1 ) + + repID.substring( rix2 ) ); + for ( int i1 = 0; i1 < dim; i1++ ) rid.insert( rix1,'[' ); + + String vtName = "seq" + dim + "_" + idlName; + boolean isFromIDL = false; + if ( et.isCompound() ) { + CompoundType ct = (CompoundType)et; + isFromIDL = ct.isIDLEntity() || ct.isCORBAObject(); + } + boolean isForwardInclude = + et.isCompound() && + !isSpecialReference( et ) && + dim == 1 && + !isFromIDL && + !"org.omg.CORBA.Object".equals(qName) && + !"java.lang.String".equals(qName); + + writeBanner( at,dim,!isException,p ); + if ( dim == 1 && "java.lang.String".equals(qName) ) //special case + writeIncOrb( p ); + if ( dim == 1 && "org.omg.CORBA.Object".equals(qName) ) ; + else if ( isSpecialReference( et ) || dim > 1 || isFromIDL ) + writeInclude( at,dim-1,!isThrown,p ); //"trivial" include + writeIfndef( at,dim,!isException,!isForward,p ); + if ( isForwardInclude ) + writeForwardReference( at,dim-1,p ); //forward declare + writeModule1( at,p ); + p.pln();p.pI(); + p.p( "valuetype " + vtName ); + p.p( " sequence<" ); + if ( dim == 1 ) p.p( qIdlName ); + else { + p.p( "seq" + ( dim - 1 ) + "_" ); + p.p( idlName ); + } + p.pln( ">;" ); + p.pO();p.pln(); + p.pln( "#pragma ID " + vtName + " \"" + rid + "\"" ); + p.pln(); + writeModule2( at,p ); + if ( isForwardInclude ) + writeInclude( at,dim-1,!isThrown,p ); //#include for forward declare + writeEndif( p ); + } + + + /** + * Write valuetype for a boxed IDLEntity. + * @param t Given CompoundType representing the IDLEntity. + * @param p The output stream. + */ + protected void writeBoxedIDL( + CompoundType t, + IndentingWriter p) + throws IOException { + String[] boxNames = getIDLModuleNames( t ); + int len = boxNames.length; + String[] modNames = new String[len - 3]; //remove box modules + for ( int i1 = 0; i1 < len - 3; i1++ ) modNames[i1] = boxNames[i1 + 3]; + String tName = unEsc( t.getIDLName() ); + + writeBanner( t,0,!isException,p ); + writeInclude( t,modNames,tName,p ); + writeIfndef( t,0,!isException,!isForward,p ); + writeModule1( t,p ); + p.pln();p.pI(); + + p.p( "valuetype " + tName + " " ); + for ( int i1 = 0; i1 < modNames.length; i1++ ) + p.p( IDL_NAME_SEPARATOR + modNames[i1] ); + p.pln( IDL_NAME_SEPARATOR + tName + ";" ); + + p.pO();p.pln(); + writeRepositoryID( t,p ); + p.pln(); + writeModule2( t,p ); + writeEndif( p ); + } + + + /** + * Write an exception. + * @param t Given ClassType representing the exception. + * @param p The output stream. + */ + protected void writeException( + ClassType t, + IndentingWriter p) + throws IOException { + writeBanner( t,0,isException,p ); + writeIfndef( t,0,isException,!isForward,p ); + writeForwardReference( t,p ); + writeModule1( t,p ); + p.pln();p.pI(); + + p.pln( "exception " + t.getIDLExceptionName() + " {" ); + p.pln();p.pI(); + p.pln( t.getIDLName() + " value;" ); + p.pO();p.pln(); + p.pln( "};" ); + + p.pO();p.pln(); + writeModule2( t,p ); + writeInclude( t,0,!isThrown,p ); //include valuetype idl file + writeEndif( p ); + } + + + /** + * Write #pragma to identify the repository ID of the given type + * @param t The given Type. + * @param p The output stream. + */ + protected void writeRepositoryID( + Type t, + IndentingWriter p ) + throws IOException { + String repid = t.getRepositoryID(); + if ( t.isCompound() ) { + CompoundType ct = (CompoundType)t; + if ( ct.isBoxed() ) + repid = ct.getBoxedRepositoryID(); + } + + p.pln( "#pragma ID " + t.getIDLName() + " \"" + + repid + "\"" ); + } + + /** + * Write inheritance for an IDL interface or valuetype. Any class + * inheritance precedes any interface inheritance. + * For a valutype any inheritance from abstract interfaces then + * follows the "supports" keyword. + * @param inhHash Hashtable loaded with inherited Types + * @param forValuetype true if writing inheritance for a valuetype + * @param p The output stream. + */ + protected void writeInherits( + Hashtable inhHash, + boolean forValuetype, + IndentingWriter p ) + throws IOException { + int itot = inhHash.size(); + int iinh = 0; + int isup = 0; + if ( itot < 1 ) return; //any inheritance to write? + Enumeration inhEnum = inhHash.elements(); + CompoundType ct; + if ( forValuetype ) + while ( inhEnum.hasMoreElements() ) { + ct = (CompoundType)inhEnum.nextElement(); + if ( ct.getTypeCode() == TYPE_ABSTRACT ) isup++; + } + iinh = itot - isup; + + if ( iinh > 0 ) { + p.p( ": " ); + inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { //write any class inheritance + ct = (CompoundType)inhEnum.nextElement(); + if ( ct.isClass() ) { + p.p( getQualifiedIDLName( ct ) ); + if ( iinh > 1 ) p.p( ", " ); //delimit them with commas + else if ( itot > 1 ) p.p( " " ); + break; //only one parent + } + } + int i = 0; + inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { //write any interface inheritance + ct = (CompoundType)inhEnum.nextElement(); + if ( !ct.isClass() && + !( ct.getTypeCode() == TYPE_ABSTRACT ) ) { + if ( i++ > 0 ) p.p( ", " ); //delimit with commas + p.p( getQualifiedIDLName( ct ) ); + } + } + } + if ( isup > 0 ) { //write abstract interface inheritance + p.p( " supports " ); + int i = 0; + inhEnum = inhHash.elements(); + while ( inhEnum.hasMoreElements() ) { + ct = (CompoundType)inhEnum.nextElement(); + if ( ct.getTypeCode() == TYPE_ABSTRACT ) { + if ( i++ > 0 ) p.p( ", " ); //delimit with commas + p.p( getQualifiedIDLName( ct ) ); + } + } + } + } + + + /** + * Write an IDL constant + * @param constant The current CompoundType.Member constant + * @param p The output stream. + */ + protected void writeConstant( + CompoundType.Member constant, + IndentingWriter p ) + throws IOException { + Type t = constant.getType(); + p.p( "const " ); + p.p( getQualifiedIDLName( t ) ); + p.p( " " + constant.getIDLName() + " = " + constant.getValue() ); + p.pln( ";" ); + } + + + + /** + * Write an IDL data member + * @param data The current CompoundType.Member data member + * @param p The output stream. + */ + protected void writeData( + CompoundType.Member data, + IndentingWriter p ) + throws IOException { + if ( data.isInnerClassDeclaration() ) return; //ignore + Type t = data.getType(); + if ( data.isPublic() ) + p.p( "public " ); + else p.p( "private " ); + p.pln( getQualifiedIDLName( t ) + " " + + data.getIDLName() + ";" ); + } + + + + /** + * Write an IDL Attribute + * @param attr The current CompoundType.Method attribute + * @param p The output stream. + */ + protected void writeAttribute( + CompoundType.Method attr, + IndentingWriter p ) + throws IOException { + if ( attr.getAttributeKind() == ATTRIBUTE_SET ) return; //use getters only + Type t = attr.getReturnType(); + if ( !attr.isReadWriteAttribute() ) p.p( "readonly " ); + p.p( "attribute " + getQualifiedIDLName( t ) + " " ); + p.pln( attr.getAttributeName() + ";" ); + } + + + + /** + * Write an IDL method + * @param method The current CompoundType.Method + * @param p The output stream. + */ + protected void writeMethod( + CompoundType.Method method, + IndentingWriter p ) + throws IOException { + if ( method.isAttribute() ) { + writeAttribute( method,p ); + return; + } + Type[] pts = method.getArguments(); + String[] paramNames = method.getArgumentNames(); + Type rt = method.getReturnType(); + Hashtable excHash = new Hashtable(); + getExceptions( method,excHash ); + + if ( method.isConstructor() ) + if ( factory ) p.p( "factory " + method.getIDLName() + "(" ); + else p.p( "init(" ); //IDL initializer + else { + p.p( getQualifiedIDLName( rt ) ); + p.p( " " + method.getIDLName() + "(" ); + } + p.pI(); + + for ( int i=0; i < pts.length; i++ ) { + if ( i > 0 ) p.pln( "," ); //delimit with comma and newline + else p.pln(); + p.p( "in " ); + p.p( getQualifiedIDLName( pts[i] ) ); + p.p( " " + paramNames[i] ); + } + p.pO(); + p.p( " )" ); + + if ( excHash.size() > 0 ) { //any exceptions to write? + p.pln( " raises (" ); + p.pI(); + int i = 0; + Enumeration excEnum = excHash.elements(); + while ( excEnum.hasMoreElements() ) { + ValueType exc = (ValueType)excEnum.nextElement(); + if ( i > 0 ) p.pln( "," ); //delimit them with commas + if ( exc.isIDLEntityException() ) + if ( exc.isCORBAUserException() ) + p.p( "::org::omg::CORBA::UserEx" ); + else { + String[] modNames = getIDLModuleNames( exc ); + for ( int i2 = 0; i2 < modNames.length; i2++ ) + p.p( IDL_NAME_SEPARATOR + modNames[i2] ); + p.p( IDL_NAME_SEPARATOR + exc.getName() ); + } + else p.p( exc.getQualifiedIDLExceptionName( true ) ); + i++; + } + p.pO(); + p.p( " )" ); + } + + p.pln( ";" ); + } + + + /** + * Remove escape character ("_"), if any, from given String + * @param name Given String + * @return String with any escape character removed + */ + protected String unEsc( + String name ) { + if ( name.startsWith( "_" ) ) return name.substring( 1 ); + else return name; + } + + + /** + * Write IDL banner into the output stream for a given Type + * @param t The given Type. + * @param dim The dimension required if t is an ArrayType. + * @param isException true if writing an exception. + * @param p The output stream. + */ + protected void writeBanner( + Type t, + int dim, + boolean isException, + IndentingWriter p ) + throws IOException { + String[] modNames = getIDLModuleNames( t ); //module name array + String fName = unEsc( t.getIDLName() ); //file name default + if ( isException && t.isClass() ) { + ClassType ct = (ClassType)t; //file name for Exception + fName = unEsc( ct.getIDLExceptionName() ); + } + if ( dim > 0 && t.isArray() ) { + Type et = t.getElementType(); //file name for sequence + fName = "seq" + dim + "_" + unEsc( et.getIDLName().replace( ' ','_' ) ); + } + + p.pln( "/**" ); + p.p( " * " ); + for ( int i1 = 0; i1 < modNames.length; i1++ ) + p.p( modNames[i1] + "/" ); + p.pln( fName + ".idl" ); + p.pln( " * Generated by rmic -idl. Do not edit" ); + String d = DateFormat.getDateTimeInstance( + DateFormat.FULL,DateFormat.FULL,Locale.getDefault() ) + .format( new Date() ); + String ocStr = "o'clock"; + int ocx = d.indexOf( ocStr ); //remove unwanted o'clock, if any + p.p ( " * " ); + if ( ocx > -1 ) + p.pln( d.substring( 0,ocx ) + d.substring( ocx + ocStr.length() ) ); + else p.pln( d ); + p.pln( " */" ); + p.pln(); + } + + + /** + * Write #include for orb.idl + * @param p The output stream. + */ + protected void writeIncOrb( + IndentingWriter p ) + throws IOException { + p.pln( "#include \"orb.idl\"" ); + } + + + /** + * Write #ifndef guard into the output stream for a given Type + * @param t The given Type. + * @param dim The dimension required if t is an ArrayType. + * @param isException true if writing an exception. + * @param isForward. No #define needed if it's a forward declare + * @param p The output stream. + */ + protected void writeIfndef( + Type t, + int dim, + boolean isException, + boolean isForward, + IndentingWriter p ) + throws IOException { + String[] modNames = getIDLModuleNames( t ); //module name array + String fName = unEsc( t.getIDLName() ); //file name default + if ( isException && t.isClass() ) { + ClassType ct = (ClassType)t; //file name for Exception + fName = unEsc( ct.getIDLExceptionName() ); + } + if ( dim > 0 && t.isArray() ) { + Type et = t.getElementType(); //file name for sequence + fName = "seq" + dim + "_" + unEsc( et.getIDLName().replace( ' ','_' ) ); + } + p.pln(); + p.p( "#ifndef __" ); + for ( int i = 0; i < modNames.length; i++ ) p.p( modNames[i] + "_" ); + p.pln( fName + "__" ); + if ( !isForward ) { + p.p( "#define __" ); + for ( int i = 0; i < modNames.length; i++ ) p.p( modNames[i] + "_" ); + p.pln( fName + "__" ); + p.pln(); + } + } + + + /** + * Write #endif bracket into the output stream + * @param p The output stream. + */ + protected void writeEndif( + IndentingWriter p ) + throws IOException { + p.pln("#endif"); + p.pln(); + } + + /** + * Write Module start bracketing for the given type into the output stream + * @param t The given Type + * @param p The output stream. + */ + protected void writeModule1( + Type t, + IndentingWriter p ) + throws IOException { + + String[] modNames = getIDLModuleNames( t ); + p.pln(); + for ( int i = 0; i < modNames.length; i++ ) + p.pln( "module " + modNames[i] + " {" ); + } + + /** + * Write Module end bracketing for the given type into the output stream + * @param t The given Type + * @param p The output stream. + */ + protected void writeModule2( + Type t, + IndentingWriter p ) + throws IOException { + String[] modNames = getIDLModuleNames( t ); + for ( int i=0; i < modNames.length; i++ ) p.pln( "};" ); + p.pln(); + } + +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/IDLNames.java b/src/share/classes/sun/rmi/rmic/iiop/IDLNames.java new file mode 100644 index 000000000..ace1d743c --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/IDLNames.java @@ -0,0 +1,1180 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Hashtable; +import java.util.Locale; +import sun.tools.java.Identifier; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassNotFound; +import com.sun.corba.ee.impl.util.RepositoryId; + +/** + * IDLNames provides static utility methods to perform the IDL + * name mappings specified in Chapter 5 of the Java Language + * to IDL specification. + * + * @version 1.0, 3/19/98 + * @author Bryan Atsatt + */ +public class IDLNames implements sun.rmi.rmic.iiop.Constants { + + /** + * Used to convert ascii to hex. + */ + public static final byte ASCII_HEX[] = { + (byte)'0', + (byte)'1', + (byte)'2', + (byte)'3', + (byte)'4', + (byte)'5', + (byte)'6', + (byte)'7', + (byte)'8', + (byte)'9', + (byte)'A', + (byte)'B', + (byte)'C', + (byte)'D', + (byte)'E', + (byte)'F', + }; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Convert a name. The nameContext argument MUST be pre-filled with + * all names from the appropriate context (e.g. all the method names + * in a given class). The names must not have had any IDL conversions + * applied. + *

                + * Section 28.3.2.2 + * Section 28.3.2.3 + * Section 28.3.2.4 + * Section 28.3.2.7 (member and method names only) + */ + public static String getMemberOrMethodName (NameContext nameContext, + String name, + BatchEnvironment env) { + + // Check namesCache... + + String result = (String) env.namesCache.get(name); + + if (result == null) { + + // 28.3.2.7 Case sensitive member names. + + // Note: This must be done before any of + // the other conversions! + + result = nameContext.get(name); + + // 28.3.2.3 Leading underscores... + + result = convertLeadingUnderscores(result); + + // 28.3.2.2 IDL keywords (NOTE: must be done + // after leading underscore conversion because + // the mangling for IDL keywords creates a + // leading underscore!)... + + result = convertIDLKeywords(result); + + // 28.3.2.4 Illegal IDL identifier characters... + + result = convertToISOLatin1(result); + + // Add to namesCache... + + env.namesCache.put(name,result); + } + + return result; + } + + /** + * Convert names with illegal IDL identifier characters. + *

                + * Section 28.3.2.4 + */ + public static String convertToISOLatin1 (String name) { + + // First, replace any escape sequences... + + String result = replace(name,"x\\u","U"); + result = replace(result,"x\\U","U"); + + // Now see if we have any remaining illegal characters (see + // RepositoryId.IDL_IDENTIFIER_CHARS array)... + + int length = result.length(); + StringBuffer buffer = null; + + for (int i = 0; i < length; i++) { + + char c = result.charAt(i); + + if (c > 255 || RepositoryId.IDL_IDENTIFIER_CHARS[c] == 0) { + + // We gotta convert. Have we already started? + + if (buffer == null) { + + // No, so get set up... + + buffer = new StringBuffer(result.substring(0,i)); + } + + // Convert the character into the IDL escape syntax... + + buffer.append("U"); + buffer.append((char)ASCII_HEX[(c & 0xF000) >>> 12]); + buffer.append((char)ASCII_HEX[(c & 0x0F00) >>> 8]); + buffer.append((char)ASCII_HEX[(c & 0x00F0) >>> 4]); + buffer.append((char)ASCII_HEX[(c & 0x000F)]); + + } else { + if (buffer != null) { + buffer.append(c); + } + } + } + + if (buffer != null) { + result = buffer.toString(); + } + + return result; + } + + /** + * Convert names which collide with IDL keywords. + *

                + * Section 28.3.2.5 + */ + public static String convertIDLKeywords (String name) { + + for (int i = 0; i < IDL_KEYWORDS.length; i++) { + if (name.equalsIgnoreCase(IDL_KEYWORDS[i])) { + return "_" + name; + } + } + + return name; + } + + /** + * Convert names which have leading underscores + *

                + * Section 28.3.2.3 + */ + public static String convertLeadingUnderscores (String name) { + + if (name.startsWith("_")) { + return "J" + name; + } + + return name; + } + + /** + * Convert a type name. + *

                + * Section 28.3.2.5 + * Section 28.3.2.7 (class or interface names only) + * Throws exception if fails 28.3.2.7. + */ + public static String getClassOrInterfaceName (Identifier id, + BatchEnvironment env) throws Exception { + + // Get the type and package name... + + String typeName = id.getName().toString(); + String packageName = null; + + if (id.isQualified()) { + packageName = id.getQualifier().toString(); + } + + // Check namesCache... + + String result = (String) env.namesCache.get(typeName); + + if (result == null) { + + // 28.3.2.5 Inner classes... + + result = replace(typeName,". ","__"); + + // 28.3.2.4 Illegal identifier characters... + + result = convertToISOLatin1(result); + + // 28.3.2.7 Case sensitive class or interface names... + + NameContext context = NameContext.forName(packageName,false,env); + context.assertPut(result); + + // Run it through the name checks... + + result = getTypeOrModuleName(result); + + // Add it to the namesCache... + + env.namesCache.put(typeName,result); + } + + return result; + } + + /** + * Convert an Exception name. + *

                + * Section 28.3.7.2 (see ValueType) + */ + public static String getExceptionName (String idlName) { + + String result = idlName; +// d.11315 Incorrectly mangled exception names + if (idlName.endsWith(EXCEPTION_SUFFIX)) { + + // Remove "Exception" and append "Ex". Strip leading underscore + // in case the idlName is exactly "_Exception"... + + result = stripLeadingUnderscore(idlName.substring(0,idlName.lastIndexOf(EXCEPTION_SUFFIX)) + EX_SUFFIX); + } else { + result = idlName + EX_SUFFIX; + } + + return result; + } + + /** + * Convert a qualified Identifier into an array of IDL names. + *

                + * Section 28.3.2.1 (see CompoundType) + * Throws exception if fails 28.3.2.7. + */ + public static String[] getModuleNames (Identifier theID, + boolean boxIt, + BatchEnvironment env) throws Exception { + + String[] result = null; + + if (theID.isQualified()) { + + // Extract the qualifier... + + Identifier id = theID.getQualifier(); + + // 28.3.2.7 Case sensitive module names. + + env.modulesContext.assertPut(id.toString()); + + // Count them... + + int count = 1; + Identifier current = id; + while (current.isQualified()) { + current = current.getQualifier(); + count++; + } + + result = new String[count]; + int index = count-1; + current = id; + + // Now walk them and fill our array (backwards)... + + for (int i = 0; i < count; i++) { + + String item = current.getName().toString(); + + // Check namesCache... + + String cachedItem = (String) env.namesCache.get(item); + + if (cachedItem == null) { + + // 28.3.2.4 Illegal identifier characters... + + cachedItem = convertToISOLatin1(item); + + // Run it through the name checks... + + cachedItem = getTypeOrModuleName(cachedItem); + + // Add it to the namesCache... + + env.namesCache.put(item,cachedItem); + } + + result[index--] = cachedItem; + current = current.getQualifier(); + } + } + + + // If it is supposed to be "boxed", prepend + // IDL_BOXEDIDL_MODULE... + + if (boxIt) { + if (result == null) { + result = IDL_BOXEDIDL_MODULE; + } else { + String[] boxed = new String[result.length+IDL_BOXEDIDL_MODULE.length]; + System.arraycopy(IDL_BOXEDIDL_MODULE,0,boxed,0,IDL_BOXEDIDL_MODULE.length); + System.arraycopy(result,0,boxed,IDL_BOXEDIDL_MODULE.length,result.length); + result = boxed; + } + } + + return result; + } + + /** + * Get an array name with the specified dimensions. + *

                + * Section 28.3.6 (see ArrayType) + */ + public static String getArrayName (Type theType, int arrayDimension) { + + StringBuffer idlName = new StringBuffer(64); + + // Prefix with seq_... + + idlName.append(IDL_SEQUENCE); + idlName.append(Integer.toString(arrayDimension)); + idlName.append("_"); + + // Add the type name. We need to map any spaces in the + // name to "_"... + + idlName.append(replace(stripLeadingUnderscore(theType.getIDLName())," ","_")); + + // And we're done... + + return idlName.toString(); + } + + /** + * Get an array module names. + */ + public static String[] getArrayModuleNames (Type theType) { + + String[] moduleName; + String[] typeModule = theType.getIDLModuleNames(); + int typeModuleLength = typeModule.length; + + // Does the type have a module? + + if (typeModuleLength == 0) { + + // Nope, so just use the sequence module... + + moduleName = IDL_SEQUENCE_MODULE; + } else { + + // Yes, so gotta concatenate... + + moduleName = new String[typeModuleLength + IDL_SEQUENCE_MODULE.length]; + System.arraycopy(IDL_SEQUENCE_MODULE,0,moduleName,0,IDL_SEQUENCE_MODULE.length); + System.arraycopy(typeModule,0,moduleName,IDL_SEQUENCE_MODULE.length,typeModuleLength); + } + + return moduleName; + } + + private static int getInitialAttributeKind (CompoundType.Method method, + BatchEnvironment env) throws ClassNotFound { + + int result = ATTRIBUTE_NONE; + + // First make sure it is not a constructor... + + if (!method.isConstructor()) { + + // Now check exceptions. It may not throw any checked + // exception other than RemoteException or one of its + // subclasses... + + boolean validExceptions = true; + ClassType[] exceptions = method.getExceptions(); + + if (exceptions.length > 0) { + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i].isCheckedException() && + !exceptions[i].isRemoteExceptionOrSubclass()) { + validExceptions = false; + break; + } + } + } else { + + // If this is a ValueType, it is ok to not have any exceptions, + // otherwise this method does not qualify... + + validExceptions = method.getEnclosing().isType(TYPE_VALUE); + } + + if (validExceptions) { + String name = method.getName(); + int nameLength = name.length(); + int argCount = method.getArguments().length; + Type returnType = method.getReturnType(); + boolean voidReturn = returnType.isType(TYPE_VOID); + boolean booleanReturn = returnType.isType(TYPE_BOOLEAN); + + // It's a getter if name starts with "get" and it has no arguments + // and a return type that is not void... + + if (name.startsWith("get") && nameLength > 3 && argCount == 0 && !voidReturn) { + result = ATTRIBUTE_GET; + } else { + + // It's a getter if name starts with "is" and it has no arguments + // and a boolean return type... + + if (name.startsWith("is") && nameLength > 2 && argCount == 0 && booleanReturn) { + result = ATTRIBUTE_IS; + } else { + + // It's a setter if name starts with "set" and it has 1 argument + // and a void return type... + + if (name.startsWith("set") && nameLength > 3 && argCount == 1 && voidReturn) { + result = ATTRIBUTE_SET; + } + } + } + } + } + + return result; + } + + private static void setAttributeKinds (CompoundType.Method[] methods, + int[] kinds, + String[] names) { + + int count = methods.length; + + // Strip the prefixes off of the attribute names... + + for (int i = 0; i < count; i++) { + switch (kinds[i]) { + case ATTRIBUTE_GET: names[i] = names[i].substring(3); break; + case ATTRIBUTE_IS: names[i] = names[i].substring(2); break; + case ATTRIBUTE_SET: names[i] = names[i].substring(3); break; + } + } + + // Now, we need to look at all the IS attributes to see + // if there is a corresponding getter or setter which has + // a different return type. If so, mark it as not an + // attribute. Do this before checking for invalid setters... + + for (int i = 0; i < count; i++) { + if (kinds[i] == ATTRIBUTE_IS) { + for (int j = 0; j < count; j++) { + if (j != i && + (kinds[j] == ATTRIBUTE_GET || kinds[j] == ATTRIBUTE_SET) && + names[i].equals(names[j])) { + + // We have matching getter or setter. Do the types match? + + Type isType = methods[i].getReturnType(); + Type targetType; + + if (kinds[j] == ATTRIBUTE_GET) { + targetType = methods[j].getReturnType(); + } else { + targetType = methods[j].getArguments()[0]; + } + + if (!isType.equals(targetType)) { + + // No, so forget this guy as an attribute... + + kinds[i] = ATTRIBUTE_NONE; + names[i] = methods[i].getName(); + break; + } + } + } + } + } + + // Now, we need to look at all the setters to see if there + // is a corresponding getter. If not, it is not a setter. + // If there is, change the getter type to _RW and set the + // pair index... + + for (int i = 0; i < count; i++) { + if (kinds[i] == ATTRIBUTE_SET) { + int getterIndex = -1; + int isGetterIndex = -1; + // First look for is-getters, then for getters. + // This is preferred for boolean attributes. + for (int j = 0; j < count; j++) { + if (j != i && names[i].equals(names[j])) { + // Yep, is the return type of the getter the same + // as the argument type of the setter? + + Type getterReturn = methods[j].getReturnType(); + Type setterArg = methods[i].getArguments()[0]; + + if (getterReturn.equals(setterArg)) { + if (kinds[j] == ATTRIBUTE_IS) { + isGetterIndex = j; + // continue looking for another getter + } else if (kinds[j] == ATTRIBUTE_GET) { + getterIndex = j; + // continue looking for an is-getter + } + } + } + } + + if (getterIndex > -1) { + if (isGetterIndex > -1) { + // We have both, a boolean is-getter and a boolean getter. + // Use the is-getter and drop the getter. + + // We have a matching getter. Change it to a read-write type... + kinds[isGetterIndex] = ATTRIBUTE_IS_RW; + + // Now set the pair index for both the getter and the setter... + methods[isGetterIndex].setAttributePairIndex(i); + methods[i].setAttributePairIndex(isGetterIndex); + + // We found a better matching is-getter. + // Forget this other getter as an attribute. + kinds[getterIndex] = ATTRIBUTE_NONE; + names[getterIndex] = methods[getterIndex].getName(); + } else { + // We only have one getter. + + // We have a matching getter. Change it to a read-write type... + kinds[getterIndex] = ATTRIBUTE_GET_RW; + + // Now set the pair index for both the getter and the setter... + methods[getterIndex].setAttributePairIndex(i); + methods[i].setAttributePairIndex(getterIndex); + } + } else { + if (isGetterIndex > -1) { + // We only have one is-getter. + + // We have a matching getter. Change it to a read-write type... + kinds[isGetterIndex] = ATTRIBUTE_IS_RW; + + // Now set the pair index for both the getter and the setter... + methods[isGetterIndex].setAttributePairIndex(i); + methods[i].setAttributePairIndex(isGetterIndex); + } else { + // We did not find a matching getter. + // Forget this setter as an attribute. + kinds[i] = ATTRIBUTE_NONE; + names[i] = methods[i].getName(); + } + } + } + } + + // Finally, do the case conversion and set the + // attribute kinds for each method... + + for (int i = 0; i < count; i++) { + + if (kinds[i] != ATTRIBUTE_NONE) { + + String name = names[i]; + + // Is the first character upper case? + + if (Character.isUpperCase(name.charAt(0))) { + + // Yes, is the second? + + if (name.length() == 1 || Character.isLowerCase(name.charAt(1))) { + + // No, so convert the first character to lower case... + + StringBuffer buffer = new StringBuffer(name); + buffer.setCharAt(0,Character.toLowerCase(name.charAt(0))); + names[i] = buffer.toString(); + } + } + } + + methods[i].setAttributeKind(kinds[i]); + } + } + + /** + * Set all the method names in a given class. + *

                + * Section 28.3.2.7 (see CompoundType) + * Section 28.3.2.7 + * Section 28.3.4.3 (RemoteType/AbstractType only). + */ + public static void setMethodNames (CompoundType container, + CompoundType.Method[] allMethods, + BatchEnvironment env) + throws Exception { + + // This method implements the following name mangling sequence: + // + // 1. If methods belong to a Remote interface, identify + // those which qualify as an attribute under 28.3.4.3. + // Those that do are referred to as 'attributes' below; + // those that do not are referred to as 'methods'. + // + // 2. Apply the 28.3.4.3 manglings, except "__", to all + // attribute names. + // + // 3. Apply all 28.3 manglings, except 28.3.2.7, to all names. + // + // 4. Apply 28.3.2.7 manglings to all method names. + // + // 5. Compare each attribute name to each method name. For + // any which compare equal, append "__" to the attribute + // name. + // + // 6. Compare each name (attribute and method) to all others. + // If any compare equal, throw an Exception with the + // conflicting name as the message. + + int count = allMethods.length; + + if (count == 0) return; + + // Make an array of all the method names... + + String[] names = new String[count]; + for (int i = 0; i < count; i++) { + names[i] = allMethods[i].getName(); + } + + // Are we dealing with a RemoteType, AbstractType, or ValueType? + + CompoundType enclosing = allMethods[0].getEnclosing(); + if (enclosing.isType(TYPE_REMOTE) || + enclosing.isType(TYPE_ABSTRACT) || + enclosing.isType(TYPE_VALUE)) { + + // Yes, so we must do the 28.3.4.3 attribute mapping. First, get + // the initial attribute kind of each method... + + int[] kinds = new int[count]; + + for (int i = 0; i < count; i++) { + kinds[i] = getInitialAttributeKind(allMethods[i],env); + } + + // Now set the attribute kind for each method and do the + // 28.3.4.3 name mangling... + + setAttributeKinds(allMethods,kinds,names); + } + + // Make and populate a new context from our names array... + + NameContext context = new NameContext(true); + + for (int i = 0; i < count; i++) { + context.put(names[i]); + } + + // Apply the appropriate 28.3 manglings to all the names... + + boolean haveConstructor = false; + for (int i = 0; i < count; i++) { + if (!allMethods[i].isConstructor()) { + names[i] = getMemberOrMethodName(context,names[i],env); + } else { + names[i] = IDL_CONSTRUCTOR; + haveConstructor = true; + } + } + + // Now do the 28.3.2.7 mangling for method name collisions... + // Do this in two passes so that we don't change one during + // the detection of collisions and then miss a real one... + + boolean overloaded[] = new boolean[count]; + for (int i = 0; i < count; i++) { + overloaded[i] = (!allMethods[i].isAttribute() && + !allMethods[i].isConstructor() && + doesMethodCollide(names[i],allMethods[i],allMethods,names,true)); + } + convertOverloadedMethods(allMethods,names,overloaded); + + // Now do the same mangling for constructor name collisions... + + for (int i = 0; i < count; i++) { + overloaded[i] = (!allMethods[i].isAttribute() && + allMethods[i].isConstructor() && + doesConstructorCollide(names[i],allMethods[i],allMethods,names,true)); + } + convertOverloadedMethods(allMethods,names,overloaded); + + // Now do the 28.3.4.3 mangling for attribute name collisions... + + for (int i = 0; i < count; i++) { + + CompoundType.Method method = allMethods[i]; + + // If this is an attribute name, does it collide with a method? + + if (method.isAttribute() && + doesMethodCollide(names[i],method,allMethods,names,true)) { + + // Yes, so add double underscore... + + names[i] += "__"; + } + } + + // Do the same mangling for any constructors which collide with + // methods... + + if (haveConstructor) { + for (int i = 0; i < count; i++) { + CompoundType.Method method = allMethods[i]; + + // Is this a constructor which collides with a method? + + if (method.isConstructor() && + doesConstructorCollide(names[i],method,allMethods,names,false)) { + + // Yes, so add double underscore... + + names[i] += "__"; + } + } + } + + // Now see if we have a collision with the container name (28.3.2.9). + + String containerName = container.getIDLName(); + for (int i = 0; i < count; i++) { + if (names[i].equalsIgnoreCase(containerName)) { + // Do not add underscore to attributes. + // Otherwise getFoo will turn into _get_foo_. + if (! allMethods[i].isAttribute()) { + names[i] += "_"; + } + } + } + + // Now see if we have any collisions (28.3.2.9). If we do, + // it's an error. Note: a get/set pair does not collide. + + for (int i = 0; i < count; i++) { + + // Does it collide with any other name? + + if (doesMethodCollide(names[i],allMethods[i],allMethods,names,false)) { + + // Yes, so bail... + + throw new Exception(allMethods[i].toString()); + } + } + + // Ok. We have unique names. Create the appropriate 'wire' name + // for each and set as the 'idl' name. If it is an attribute, also + // set the attribute name... + + for (int i = 0; i < count; i++) { + + CompoundType.Method method = allMethods[i]; + String wireName = names[i]; + + if (method.isAttribute()) { + wireName = ATTRIBUTE_WIRE_PREFIX[method.getAttributeKind()] + + stripLeadingUnderscore(wireName); + String attributeName = names[i]; + method.setAttributeName(attributeName); + } + method.setIDLName(wireName); + } + } + + private static String stripLeadingUnderscore (String name) { + if (name != null && name.length() > 1 + && name.charAt(0) == '_') + { + return name.substring(1); + } + return name; + } + + + private static String stripTrailingUnderscore (String name) { + if (name != null && name.length() > 1 && + name.charAt(name.length() - 1) == '_') + { + return name.substring(0, name.length() - 1); + } + return name; + } + + + private static void convertOverloadedMethods(CompoundType.Method[] allMethods, + String[] names, + boolean[] overloaded) { + + for (int i = 0; i < names.length; i++) { + + // Do we need to mangle it? + + if (overloaded[i]) { + + // Yes, so add arguments... + + CompoundType.Method method = allMethods[i]; + Type[] args = method.getArguments(); + + for (int k = 0; k < args.length; k++) { + + // Add the separator... + + names[i] += "__"; + + // Get the fully qualified IDL name, without the "::" + // prefix... + + String argIDLName = args[k].getQualifiedIDLName(false); + + // Replace any occurances of "::_" with "_" to + // undo any IDL keyword mangling and do next step + // at the same time... + + argIDLName = replace(argIDLName,"::_","_"); + + // Replace any occurances of "::" with "_"... + + argIDLName = replace(argIDLName,"::","_"); + + // Replace any occurances of " " with "_"... + + argIDLName = replace(argIDLName," ","_"); + + // Add the argument type name... + + names[i] += argIDLName; + } + + if (args.length == 0) { + names[i] += "__"; + } + + // Remove any IDL keyword mangling... + + names[i] = stripLeadingUnderscore(names[i]); + } + } + } + + private static boolean doesMethodCollide (String name, + CompoundType.Method method, + CompoundType.Method[] allMethods, + String[] allNames, + boolean ignoreAttributes) { + + // Scan all methods looking for a match... + + for (int i = 0; i < allMethods.length; i++) { + + CompoundType.Method target = allMethods[i]; + + if (method != target && // Not same instance + !target.isConstructor() && // Not a constructor + (!ignoreAttributes || !target.isAttribute()) && // Correct kind + name.equals(allNames[i])) { // Same names + + // Are we looking at a get/set pair? + + int kind1 = method.getAttributeKind(); + int kind2 = target.getAttributeKind(); + + if ((kind1 != ATTRIBUTE_NONE && kind2 != ATTRIBUTE_NONE) && + ((kind1 == ATTRIBUTE_SET && kind2 != ATTRIBUTE_SET) || + (kind1 != ATTRIBUTE_SET && kind2 == ATTRIBUTE_SET) || + // one is a is-getter/setter pair and the other is just a getter + (kind1 == ATTRIBUTE_IS_RW && kind2 == ATTRIBUTE_GET) || + (kind1 == ATTRIBUTE_GET && kind2 == ATTRIBUTE_IS_RW))) { + + // Yes, so ignore it... + + } else { + + // No, so we have a collision... + + return true; + } + } + } + + return false; + } + + private static boolean doesConstructorCollide (String name, + CompoundType.Method method, + CompoundType.Method[] allMethods, + String[] allNames, + boolean compareConstructors) { + + // Scan all methods looking for a match... + + for (int i = 0; i < allMethods.length; i++) { + + CompoundType.Method target = allMethods[i]; + + if (method != target && // Not same instance + (target.isConstructor() == compareConstructors) && // Correct kind + name.equals(allNames[i])) { // Same names + + // We have a collision... + + return true; + } + } + + return false; + } + + + /** + * Set all the member names in a given class. + *

                + * Section 28.3.2.7 (see CompoundType) + * Section 28.3.2.7 + */ + public static void setMemberNames (CompoundType container, + CompoundType.Member[] allMembers, + CompoundType.Method[] allMethods, + BatchEnvironment env) + throws Exception { + + // Make and populate a new context... + + NameContext context = new NameContext(true); + + for (int i = 0; i < allMembers.length; i++) { + context.put(allMembers[i].getName()); + } + + // Now set all the idl names... + + for (int i = 0; i < allMembers.length; i++) { + + CompoundType.Member member = allMembers[i]; + String idlName = getMemberOrMethodName(context,member.getName(),env); + member.setIDLName(idlName); + } + + // First see if we have a collision with the container name (28.3.2.9). + + String containerName = container.getIDLName(); + for (int i = 0; i < allMembers.length; i++) { + String name = allMembers[i].getIDLName(); + if (name.equalsIgnoreCase(containerName)) { + // REVISIT - How is this different than line 788 + allMembers[i].setIDLName(name+"_"); + } + } + + // Check for collisions between member names... + + for (int i = 0; i < allMembers.length; i++) { + String name = allMembers[i].getIDLName(); + for (int j = 0; j < allMembers.length; j++) { + if (i != j && allMembers[j].getIDLName().equals(name)) { + + // Collision... + + throw new Exception(name); + } + } + } + + // Now check for collisions between member names and + // method names... + + boolean changed; + do { + changed = false; + for (int i = 0; i < allMembers.length; i++) { + String name = allMembers[i].getIDLName(); + for (int j = 0; j < allMethods.length; j++) { + if (allMethods[j].getIDLName().equals(name)) { + + // Collision, so append "_" to member name... + + allMembers[i].setIDLName(name+"_"); + changed = true; + break; + } + } + } + } while (changed); + } + + /** + * Get the name for the specified type code. + *

                + * Section 28.3..3 (see PrimitiveType) + * Section 28.3.5.10 (see SpecialClassType) + * Section 28.3.4.1 (see SpecialInterfaceType) + * Section 28.3.10.1 (see SpecialInterfaceType) + * Section 28.3.10.2 (see SpecialClassType) + */ + public static String getTypeName(int typeCode, boolean isConstant) { + + String idlName = null; + + switch (typeCode) { + case TYPE_VOID: idlName = IDL_VOID; break; + case TYPE_BOOLEAN: idlName = IDL_BOOLEAN; break; + case TYPE_BYTE: idlName = IDL_BYTE; break; + case TYPE_CHAR: idlName = IDL_CHAR; break; + case TYPE_SHORT: idlName = IDL_SHORT; break; + case TYPE_INT: idlName = IDL_INT; break; + case TYPE_LONG: idlName = IDL_LONG; break; + case TYPE_FLOAT: idlName = IDL_FLOAT; break; + case TYPE_DOUBLE: idlName = IDL_DOUBLE; break; + case TYPE_ANY: idlName = IDL_ANY; break; + case TYPE_CORBA_OBJECT: idlName = IDL_CORBA_OBJECT; break; + case TYPE_STRING: + { + if (isConstant) { + idlName = IDL_CONSTANT_STRING; + } else { + idlName = IDL_STRING; + } + + break; + } + } + + return idlName; + } + + /** + * Create a qualified name. + */ + public static String getQualifiedName (String[] idlModuleNames, String idlName) { + String result = null; + if (idlModuleNames != null && idlModuleNames.length > 0) { + for (int i = 0; i < idlModuleNames.length;i++) { + if (i == 0) { + result = idlModuleNames[0]; + } else { + result += IDL_NAME_SEPARATOR; + result += idlModuleNames[i]; + } + } + result += IDL_NAME_SEPARATOR; + result += idlName; + } else { + result = idlName; + } + return result; + } + + /** + * Replace substrings + * @param source The source string. + * @param match The string to search for within the source string. + * @param replace The replacement for any matching components. + * @return + */ + public static String replace (String source, String match, String replace) { + + int index = source.indexOf(match,0); + + if (index >=0) { + + // We have at least one match, so gotta do the + // work... + + StringBuffer result = new StringBuffer(source.length() + 16); + int matchLength = match.length(); + int startIndex = 0; + + while (index >= 0) { + result.append(source.substring(startIndex,index)); + result.append(replace); + startIndex = index + matchLength; + index = source.indexOf(match,startIndex); + } + + // Grab the last piece, if any... + + if (startIndex < source.length()) { + result.append(source.substring(startIndex)); + } + + return result.toString(); + + } else { + + // No matches, just return the source... + + return source; + } + } + + /** + * Get an IDL style repository id for + */ + public static String getIDLRepositoryID (String idlName) { + return IDL_REPOSITORY_ID_PREFIX + + replace(idlName,"::", "/") + + IDL_REPOSITORY_ID_VERSION; + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + + /** + * Convert a type or module name. + *

                + * Section 28.3.2.2 + * Section 28.3.2.3 + */ + private static String getTypeOrModuleName (String name) { + + // 28.3.2.3 Leading underscores... + + String result = convertLeadingUnderscores(name); + + // 28.3.2.2 IDL keywords (NOTE: must be done + // after leading underscore conversion because + // the mangling for IDL keywords creates a + // leading underscore!)... + + return convertIDLKeywords(result); + } +} + diff --git a/src/share/classes/sun/rmi/rmic/iiop/ImplementationType.java b/src/share/classes/sun/rmi/rmic/iiop/ImplementationType.java new file mode 100644 index 000000000..9e3046406 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ImplementationType.java @@ -0,0 +1,272 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; +import sun.tools.java.MemberDefinition; + +/** + * ImplementationType represents any non-special class which implements + * one or more interfaces which inherit from java.rmi.Remote. + *

                + * The static forImplementation(...) method must be used to obtain an instance, + * and will return null if the ClassDefinition is non-conforming. + * + * @version 1.0, 2/25/98 + * @author Bryan Atsatt + */ +public class ImplementationType extends ClassType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an ImplementationType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static ImplementationType forImplementation(ClassDefinition classDef, + ContextStack stack, + boolean quiet) { + if (stack.anyErrors()) return null; + + boolean doPop = false; + ImplementationType result = null; + + try { + // Do we already have it? + + sun.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof ImplementationType)) return null; // False hit. + + // Yep, so return it... + + return (ImplementationType) existing; + + } + + // Could this be an implementation? + + if (couldBeImplementation(quiet,stack,classDef)) { + + // Yes, so check it... + + ImplementationType it = new ImplementationType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(stack,quiet)) { + stack.pop(true); + result = it; + } else { + removeType(theType,stack); + stack.pop(false); + } + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + } + + return result; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Implementation"; + } + + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Create a ImplementationType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private ImplementationType(ContextStack stack, ClassDefinition classDef) { + super(TYPE_IMPLEMENTATION | TM_CLASS | TM_COMPOUND,classDef,stack); // Use special constructor. + } + + + private static boolean couldBeImplementation(boolean quiet, ContextStack stack, + ClassDefinition classDef) { + boolean result = false; + BatchEnvironment env = stack.getEnv(); + + try { + if (!classDef.isClass()) { + failedConstraint(17,quiet,stack,classDef.getName()); + } else { + result = env.defRemote.implementedBy(env, classDef.getClassDeclaration()); + if (!result) failedConstraint(8,quiet,stack,classDef.getName()); + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } + + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack, boolean quiet) { + + boolean result = false; + ClassDefinition theClass = getClassDefinition(); + + if (initParents(stack)) { + + // Make up our collections... + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + + // Check interfaces... + + try { + if (addRemoteInterfaces(directInterfaces,true,stack) != null) { + + boolean haveRemote = false; + + // Get methods from all interfaces... + + for (int i = 0; i < directInterfaces.size(); i++) { + InterfaceType theInt = (InterfaceType) directInterfaces.elementAt(i); + if (theInt.isType(TYPE_REMOTE) || + theInt.isType(TYPE_JAVA_RMI_REMOTE)) { + haveRemote = true; + } + + copyRemoteMethods(theInt,directMethods); + } + + // Make sure we have at least one remote interface... + + if (!haveRemote) { + failedConstraint(8,quiet,stack,getQualifiedName()); + return false; + } + + // Now check the methods to ensure we have the + // correct throws clauses... + + if (checkMethods(theClass,directMethods,stack,quiet)) { + + // We're ok, so pass 'em up... + + result = initialize(directInterfaces,directMethods,null,stack,quiet); + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } + + return result; + } + + private static void copyRemoteMethods(InterfaceType type, Vector list) { + + if (type.isType(TYPE_REMOTE)) { + + // Copy all the unique methods from type... + + Method[] allMethods = type.getMethods(); + + for (int i = 0; i < allMethods.length; i++) { + Method theMethod = allMethods[i]; + + if (!list.contains(theMethod)) { + list.addElement(theMethod); + } + } + + // Now recurse thru all inherited interfaces... + + InterfaceType[] allInterfaces = type.getInterfaces(); + + for (int i = 0; i < allInterfaces.length; i++) { + copyRemoteMethods(allInterfaces[i],list); + } + } + } + + // Walk all methods of the class, and for each that is already in + // the list, call setImplExceptions()... + + private boolean checkMethods(ClassDefinition theClass, Vector list, + ContextStack stack, boolean quiet) { + + // Convert vector to array... + + Method[] methods = new Method[list.size()]; + list.copyInto(methods); + + for (MemberDefinition member = theClass.getFirstMember(); + member != null; + member = member.getNextMember()) { + + if (member.isMethod() && !member.isConstructor() + && !member.isInitializer()) { + + // It's a method... + + if (!updateExceptions(member,methods,stack,quiet)) { + return false; + } + } + } + return true; + } + + private boolean updateExceptions (MemberDefinition implMethod, Method[] list, + ContextStack stack, boolean quiet) { + int length = list.length; + String implMethodSig = implMethod.toString(); + + for (int i = 0; i < length; i++) { + Method existingMethod = list[i]; + MemberDefinition existing = existingMethod.getMemberDefinition(); + + // Do we have a matching method? + + if (implMethodSig.equals(existing.toString())) { + + // Yes, so create exception list... + + try { + ValueType[] implExcept = getMethodExceptions(implMethod,quiet,stack); + existingMethod.setImplExceptions(implExcept); + } catch (Exception e) { + return false; + } + } + } + return true; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/InterfaceType.java b/src/share/classes/sun/rmi/rmic/iiop/InterfaceType.java new file mode 100644 index 000000000..b049786ac --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/InterfaceType.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.IOException; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassDefinition; +import sun.rmi.rmic.IndentingWriter; + +/** + * InterfaceType is an abstract base representing any non-special + * interface type. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public abstract class InterfaceType extends CompoundType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Print this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + if (isInner()) { + writer.p("// " + getTypeDescription() + " (INNER)"); + } else { + writer.p("// " + getTypeDescription() + ""); + } + writer.pln(" (" + getRepositoryID() + ")\n"); + printPackageOpen(writer,useIDLNames); + + if (!useIDLNames) { + writer.p("public "); + } + + writer.p("interface " + getTypeName(false,useIDLNames,false)); + printImplements(writer,"",useQualifiedNames,useIDLNames,globalIDLNames); + writer.plnI(" {"); + printMembers(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + printMethods(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + + if (useIDLNames) { + writer.pOln("};"); + } else { + writer.pOln("}"); + } + printPackageClose(writer,useIDLNames); + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create a InterfaceType instance for the given class. NOTE: This constructor + * is ONLY for SpecialInterfaceType. + */ + protected InterfaceType(ContextStack stack, int typeCode, ClassDefinition classDef) { + super(stack,typeCode,classDef); // Call special parent constructor. + + if ((typeCode & TM_INTERFACE) == 0 || ! classDef.isInterface()) { + throw new CompilerError("Not an interface"); + } + } + + /** + * Create a InterfaceType instance for the given class. The resulting + * object is not yet completely initialized. Subclasses must call + * initialize(directInterfaces,directInterfaces,directConstants); + */ + protected InterfaceType(ContextStack stack, + ClassDefinition classDef, + int typeCode) { + super(stack,classDef,typeCode); + + if ((typeCode & TM_INTERFACE) == 0 || ! classDef.isInterface()) { + throw new CompilerError("Not an interface"); + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/NCClassType.java b/src/share/classes/sun/rmi/rmic/iiop/NCClassType.java new file mode 100644 index 000000000..4a60377c2 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/NCClassType.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; + +/** + * NCClassType represents any non-special class which does not + * extends one or more interfaces which inherit from java.rmi.Remote. + *

                + * The static forImplementation(...) method must be used to obtain an instance, + * and will return null if the ClassDefinition is non-conforming. + * + * @version 1.0, 2/25/98 + * @author Bryan Atsatt + */ +public class NCClassType extends ClassType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an NCClassType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static NCClassType forNCClass(ClassDefinition classDef, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + boolean doPop = false; + try { + // Do we already have it? + + sun.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof NCClassType)) return null; // False hit. + + // Yep, so return it... + + return (NCClassType) existing; + + } + + NCClassType it = new NCClassType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(stack)) { + stack.pop(true); + return it; + } else { + removeType(theType,stack); + stack.pop(false); + return null; + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return addExceptionDescription("Non-conforming class"); + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a NCClassType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private NCClassType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_NC_CLASS | TM_CLASS | TM_COMPOUND); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack) { + if (!initParents(stack)) { + return false; + } + + if (stack.getEnv().getParseNonConforming()) { + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directMembers = new Vector(); + + try { + + // Get methods... + + if (addAllMethods(getClassDefinition(),directMethods,false,false,stack) != null) { + + // Update parent class methods... + + if (updateParentClassMethods(getClassDefinition(),directMethods,false,stack) != null) { + + // Get conforming constants... + + if (addConformingConstants(directMembers,false,stack)) { + + // We're ok, so pass 'em up... + + if (!initialize(directInterfaces,directMethods,directMembers,stack,false)) { + return false; + } + } + } + } + return true; + + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + return false; + } else { + return initialize(null,null,null,stack,false); + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/NCInterfaceType.java b/src/share/classes/sun/rmi/rmic/iiop/NCInterfaceType.java new file mode 100644 index 000000000..93d28da51 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/NCInterfaceType.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; + +/** + * NCInterfaceType represents any non-special, non-conforming interface. + *

                + * The static forNCInterface(...) method must be used to obtain an instance. + * @version 1.0, 2/25/98 + * @author Bryan Atsatt + */ +public class NCInterfaceType extends InterfaceType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an NCInterfaceType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static NCInterfaceType forNCInterface( ClassDefinition classDef, + ContextStack stack) { + if (stack.anyErrors()) return null; + + boolean doPop = false; + try { + // Do we already have it? + + sun.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof NCInterfaceType)) return null; // False hit. + + // Yep, so return it... + + return (NCInterfaceType) existing; + } + + NCInterfaceType it = new NCInterfaceType(stack, classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(stack)) { + stack.pop(true); + return it; + } else { + removeType(theType,stack); + stack.pop(false); + return null; + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Non-conforming interface"; + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a NCInterfaceType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private NCInterfaceType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_NC_INTERFACE | TM_INTERFACE | TM_COMPOUND); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack) { + + if (stack.getEnv().getParseNonConforming()) { + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directMembers = new Vector(); + + try { + + // need to include parent interfaces in IDL generation... + addNonRemoteInterfaces( directInterfaces,stack ); + + // Get methods... + + if (addAllMethods(getClassDefinition(),directMethods,false,false,stack) != null) { + + // Get conforming constants... + + if (addConformingConstants(directMembers,false,stack)) { + + // We're ok, so pass 'em up... + + if (!initialize(directInterfaces,directMethods,directMembers,stack,false)) { + return false; + } + } + } + return true; + + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + return false; + } else { + return initialize(null,null,null,stack,false); + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/NameContext.java b/src/share/classes/sun/rmi/rmic/iiop/NameContext.java new file mode 100644 index 000000000..a5ae632c2 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/NameContext.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Hashtable; + +/** + * A NameContext enables detection of strings which differ only + * in case. + * + * @version 1.0, 3/19/98 + * @author Bryan Atsatt + */ +class NameContext { + + private Hashtable table; + private boolean allowCollisions; + + /** + * Get a context for the given name. Name may be null, in + * which case this method will return the default context. + */ + public static synchronized NameContext forName (String name, + boolean allowCollisions, + BatchEnvironment env) { + + NameContext result = null; + + // Do we need to use the default context? + + if (name == null) { + + // Yes. + + name = "null"; + } + + // Have we initialized our hashtable? + + if (env.nameContexts == null) { + + // Nope, so do it... + + env.nameContexts = new Hashtable(); + + } else { + + // Yes, see if we already have the requested + // context... + + result = (NameContext) env.nameContexts.get(name); + } + + // Do we have the requested context? + + if (result == null) { + + // Nope, so create and add it... + + result = new NameContext(allowCollisions); + + env.nameContexts.put(name,result); + } + + return result; + } + + /** + * Construct a context. + * @param allowCollisions true if case-sensitive name collisions + * are allowed, false if not. + */ + public NameContext (boolean allowCollisions) { + this.allowCollisions = allowCollisions; + table = new Hashtable(); + } + + /** + * Add a name to this context. If constructed with allowCollisions + * false and a collision occurs, this method will throw an exception + * in which the message contains the string: "name" and "collision". + */ + public void assertPut (String name) throws Exception { + + String message = add(name); + + if (message != null) { + throw new Exception(message); + } + } + + /** + * Add a name to this context.. + */ + public void put (String name) { + + if (allowCollisions == false) { + throw new Error("Must use assertPut(name)"); + } + + add(name); + } + + /** + * Add a name to this context. If constructed with allowCollisions + * false and a collision occurs, this method will return a message + * string, otherwise returns null. + */ + private String add (String name) { + + // First, create a key by converting name to lowercase... + + String key = name.toLowerCase(); + + // Does this key exist in the context? + + Name value = (Name) table.get(key); + + if (value != null) { + + // Yes, so they match if we ignore case. Do they match if + // we don't ignore case? + + if (!name.equals(value.name)) { + + // No, so this is a case-sensitive match. Are we + // supposed to allow this? + + if (allowCollisions) { + + // Yes, make sure it knows that it collides... + + value.collisions = true; + + } else { + + // No, so return a message string... + + return new String("\"" + name + "\" and \"" + value.name + "\""); + } + } + } else { + + // No, so add it... + + table.put(key,new Name(name,false)); + } + + return null; + } + + /** + * Get a name from the context. If it has collisions, the name + * will be converted as specified in section 5.2.7. + */ + public String get (String name) { + + Name it = (Name) table.get(name.toLowerCase()); + String result = name; + + // Do we need to mangle it? + + if (it.collisions) { + + // Yep, so do it... + + int length = name.length(); + boolean allLower = true; + + for (int i = 0; i < length; i++) { + + if (Character.isUpperCase(name.charAt(i))) { + result += "_"; + result += i; + allLower = false; + } + } + + if (allLower) { + result += "_"; + } + } + + return result; + } + + /** + * Remove all entries. + */ + public void clear () { + table.clear(); + } + + public class Name { + public String name; + public boolean collisions; + + public Name (String name, boolean collisions) { + this.name = name; + this.collisions = collisions; + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/PrimitiveType.java b/src/share/classes/sun/rmi/rmic/iiop/PrimitiveType.java new file mode 100644 index 000000000..5e3dd7693 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/PrimitiveType.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.tools.java.CompilerError; +import sun.tools.java.Identifier; +import sun.tools.java.ClassDefinition; + +/** + * PrimitiveType wraps primitive types and void. + *

                + * The static forPrimitive(...) method must be used to obtain an instance, and + * will return null if the type is non-conforming. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public class PrimitiveType extends Type { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create a PrimitiveType object for the given type. + * + * If the type is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static PrimitiveType forPrimitive(sun.tools.java.Type type, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + // Do we already have it? + + Type existing = getType(type,stack); + + if (existing != null) { + + if (!(existing instanceof PrimitiveType)) return null; // False hit. + + // Yep, so return it... + + return (PrimitiveType) existing; + } + + int typeCode; + + switch (type.getTypeCode()) { + case TC_VOID: typeCode = TYPE_VOID; break; + case TC_BOOLEAN: typeCode = TYPE_BOOLEAN; break; + case TC_BYTE: typeCode = TYPE_BYTE; break; + case TC_CHAR: typeCode = TYPE_CHAR; break; + case TC_SHORT: typeCode = TYPE_SHORT; break; + case TC_INT: typeCode = TYPE_INT; break; + case TC_LONG: typeCode = TYPE_LONG; break; + case TC_FLOAT: typeCode = TYPE_FLOAT; break; + case TC_DOUBLE: typeCode = TYPE_DOUBLE; break; + default: return null; + } + + PrimitiveType it = new PrimitiveType(stack,typeCode); + + // Add it... + + putType(type,it,stack); + + // Do the stack thing in case tracing on... + + stack.push(it); + stack.pop(true); + + return it; + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public String getSignature() { + switch (getTypeCode()) { + case TYPE_VOID: return SIG_VOID; + case TYPE_BOOLEAN: return SIG_BOOLEAN; + case TYPE_BYTE: return SIG_BYTE; + case TYPE_CHAR: return SIG_CHAR; + case TYPE_SHORT: return SIG_SHORT; + case TYPE_INT: return SIG_INT; + case TYPE_LONG: return SIG_LONG; + case TYPE_FLOAT: return SIG_FLOAT; + case TYPE_DOUBLE: return SIG_DOUBLE; + default: return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Primitive"; + } + + /** + * IDL_Naming + * Return the fully qualified IDL name for this type (e.g. com.acme.Dynamite would + * return "com::acme::Dynamite"). + * @param global If true, prepends "::". + */ + public String getQualifiedIDLName(boolean global) { + return super.getQualifiedIDLName(false); + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /* + * Load a Class instance. Return null if fail. + */ + protected Class loadClass() { + switch (getTypeCode()) { + case TYPE_VOID: return Null.class; + case TYPE_BOOLEAN: return boolean.class; + case TYPE_BYTE: return byte.class; + case TYPE_CHAR: return char.class; + case TYPE_SHORT: return short.class; + case TYPE_INT: return int.class; + case TYPE_LONG: return long.class; + case TYPE_FLOAT: return float.class; + case TYPE_DOUBLE: return double.class; + default: throw new CompilerError("Not a primitive type"); + } + } + + /** + * IDL_Naming + * Create an PrimitiveType instance for the given class. + */ + private PrimitiveType(ContextStack stack, int typeCode) { + super(stack,typeCode | TM_PRIMITIVE); + + // Validate type and set names... + + String idlName = IDLNames.getTypeName(typeCode,false); + Identifier id = null; + + switch (typeCode) { + case TYPE_VOID: id = idVoid; break; + case TYPE_BOOLEAN: id = idBoolean; break; + case TYPE_BYTE: id = idByte; break; + case TYPE_CHAR: id = idChar; break; + case TYPE_SHORT: id = idShort; break; + case TYPE_INT: id = idInt; break; + case TYPE_LONG: id = idLong; break; + case TYPE_FLOAT: id = idFloat; break; + case TYPE_DOUBLE: id = idDouble; break; + default: throw new CompilerError("Not a primitive type"); + } + + setNames(id,null,idlName); + setRepositoryID(); + } +} + +class Null {} diff --git a/src/share/classes/sun/rmi/rmic/iiop/PrintGenerator.java b/src/share/classes/sun/rmi/rmic/iiop/PrintGenerator.java new file mode 100644 index 000000000..f612af7e2 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/PrintGenerator.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStreamWriter; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassDefinition; +import sun.rmi.rmic.IndentingWriter; +import sun.rmi.rmic.Main; + +/** + * An IDL generator for rmic. + * + * @version 1.0, 3/9/98 + * @author Bryan Atsatt + */ +public class PrintGenerator implements sun.rmi.rmic.Generator, + sun.rmi.rmic.iiop.Constants { + + private static final int JAVA = 0; + private static final int IDL = 1; + private static final int BOTH = 2; + + private int whatToPrint; // Initialized in parseArgs. + private boolean global = false; + private boolean qualified = false; + private boolean trace = false; + private boolean valueMethods = false; + + private IndentingWriter out; + + /** + * Default constructor for Main to use. + */ + public PrintGenerator() { + OutputStreamWriter writer = new OutputStreamWriter(System.out); + out = new IndentingWriter (writer); + } + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * @param error Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + String arg = argv[i].toLowerCase(); + if (arg.equals("-xprint")) { + whatToPrint = JAVA; + argv[i] = null; + if (i+1 < argv.length) { + if (argv[i+1].equalsIgnoreCase("idl")) { + argv[++i] = null; + whatToPrint = IDL; + } else if (argv[i+1].equalsIgnoreCase("both")) { + argv[++i] = null; + whatToPrint = BOTH; + } + } + } else if (arg.equals("-xglobal")) { + global = true; + argv[i] = null; + } else if (arg.equals("-xqualified")) { + qualified = true; + argv[i] = null; + } else if (arg.equals("-xtrace")) { + trace = true; + argv[i] = null; + } else if (arg.equals("-xvaluemethods")) { + valueMethods = true; + argv[i] = null; + } + } + } + return true; + } + + /** + * Generate output. Any source files created which need compilation should + * be added to the compiler environment using the addGeneratedFile(File) + * method. + * + * @param env The compiler environment + * @param cdef The definition for the implementation class or interface from + * which to generate output + * @param destDir The directory for the root of the package hierarchy + * for generated files. May be null. + */ + public void generate(sun.rmi.rmic.BatchEnvironment env, ClassDefinition cdef, File destDir) { + + BatchEnvironment ourEnv = (BatchEnvironment) env; + ContextStack stack = new ContextStack(ourEnv); + stack.setTrace(trace); + + if (valueMethods) { + ourEnv.setParseNonConforming(true); + } + + // Get our top level type... + + CompoundType topType = CompoundType.forCompound(cdef,stack); + + if (topType != null) { + + try { + + // Collect up all the compound types... + + Type[] theTypes = topType.collectMatching(TM_COMPOUND); + + for (int i = 0; i < theTypes.length; i++) { + + out.pln("\n-----------------------------------------------------------\n"); + + Type theType = theTypes[i]; + + switch (whatToPrint) { + case JAVA: theType.println(out,qualified,false,false); + break; + + case IDL: theType.println(out,qualified,true,global); + break; + + case BOTH: theType.println(out,qualified,false,false); + theType.println(out,qualified,true,global); + break; + + default: throw new CompilerError("Unknown type!"); + } + } + + out.flush(); + + } catch (IOException e) { + throw new CompilerError("PrintGenerator caught " + e); + } + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/RemoteType.java b/src/share/classes/sun/rmi/rmic/iiop/RemoteType.java new file mode 100644 index 000000000..2b6fa353c --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/RemoteType.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.CompilerError; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassNotFound; + +/** + * RemoteType represents any non-special interface which inherits + * from java.rmi.Remote. + *

                + * The static forRemote(...) method must be used to obtain an instance, and will + * return null if the ClassDefinition is non-conforming. + * @version 1.0, 2/25/98 + * @author Bryan Atsatt + */ +public class RemoteType extends InterfaceType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an RemoteType for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static RemoteType forRemote(ClassDefinition classDef, + ContextStack stack, + boolean quiet) { + + if (stack.anyErrors()) return null; + + boolean doPop = false; + RemoteType result = null; + + try { + // Do we already have it? + + sun.tools.java.Type theType = classDef.getType(); + Type existing = getType(theType,stack); + + if (existing != null) { + + if (!(existing instanceof RemoteType)) return null; // False hit. + + // Yep, so return it... + + return (RemoteType) existing; + } + + // Could this be a remote type? + + if (couldBeRemote(quiet,stack,classDef)) { + + // Yes, so check it... + + RemoteType it = new RemoteType(stack,classDef); + putType(theType,it,stack); + stack.push(it); + doPop = true; + + if (it.initialize(quiet,stack)) { + stack.pop(true); + result = it; + } else { + removeType(theType,stack); + stack.pop(false); + } + } + } catch (CompilerError e) { + if (doPop) stack.pop(false); + } + + return result; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Remote interface"; + } + + //_____________________________________________________________________ + // Internal/Subclass Interfaces + //_____________________________________________________________________ + + /** + * Create a RemoteType instance for the given class. The resulting + * object is not yet completely initialized. + */ + protected RemoteType(ContextStack stack, ClassDefinition classDef) { + super(stack,classDef,TYPE_REMOTE | TM_INTERFACE | TM_COMPOUND); + } + + /** + * Create a RemoteType instance for the given class. The resulting + * object is not yet completely initialized. + */ + protected RemoteType(ContextStack stack, ClassDefinition classDef, int typeCode) { + super(stack,classDef,typeCode); + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + + private static boolean couldBeRemote (boolean quiet, ContextStack stack, + ClassDefinition classDef) { + + boolean result = false; + BatchEnvironment env = stack.getEnv(); + + try { + if (!classDef.isInterface()) { + failedConstraint(16,quiet,stack,classDef.getName()); + } else { + result = env.defRemote.implementedBy(env,classDef.getClassDeclaration()); + if (!result) failedConstraint(1,quiet,stack,classDef.getName()); + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } + + + /** + * Initialize this instance. + */ + private boolean initialize (boolean quiet,ContextStack stack) { + + boolean result = false; + + // Go check it out and gather up the info we need... + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directConstants = new Vector(); + + if (isConformingRemoteInterface(directInterfaces, + directMethods, + directConstants, + quiet, + stack)){ + + // We're ok, so pass 'em up... + + result = initialize(directInterfaces,directMethods,directConstants,stack,quiet); + } + + return result; + } + + /** + * Check to ensure that the interface and all it's methods and arguments + * conforms to the RMI/IDL java subset for remote interfaces as defined + * by the "Java to IDL Mapping" specification, section 4. + * @param directInterfaces All directly implmented interfaces will be + * added to this list. + * @param directMethods All directly implemented methods (other than + * constructors and initializers) will be added to this list. + * @param directConstants All constants defined by theInterface will be + * added to this list. + * @param quiet True if should not report constraint failures. + * @return true if constraints satisfied, false otherwise. + */ + private boolean isConformingRemoteInterface ( Vector directInterfaces, + Vector directMethods, + Vector directConstants, + boolean quiet, + ContextStack stack) { + + ClassDefinition theInterface = getClassDefinition(); + + try { + + // Get all remote interfaces... + + if (addRemoteInterfaces(directInterfaces,false,stack) == null ) { + return false; + } + + // Make sure all constants are conforming... + + if (!addAllMembers(directConstants,true,quiet,stack)) { + return false; + } + + // Now, collect up all methods... + + if (addAllMethods(theInterface,directMethods,true,quiet,stack) == null) { + // Failed a constraint check... + return false; + } + + // Now walk 'em, ensuring each is a valid remote method... + + boolean methodsConform = true; + for (int i = 0; i < directMethods.size(); i++) { + if (! isConformingRemoteMethod((Method) directMethods.elementAt(i),quiet)) { + methodsConform = false; + } + } + if (!methodsConform) { + return false; + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + return false; + } + + return true; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/SpecialClassType.java b/src/share/classes/sun/rmi/rmic/iiop/SpecialClassType.java new file mode 100644 index 000000000..2599cee5f --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/SpecialClassType.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.tools.java.ClassNotFound; +import sun.tools.java.CompilerError; +import sun.tools.java.Identifier; +import sun.tools.java.ClassDefinition; + +/** + * SpecialClassType represents any one of the following types: + *

                + *    java.lang.Object
                + *    java.lang.String
                + * 
                + * all of which are treated as special cases. + *

                + * The static forSpecial(...) method must be used to obtain an instance, and + * will return null if the type is non-conforming. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public class SpecialClassType extends ClassType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create a SpecialClassType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static SpecialClassType forSpecial (ClassDefinition theClass, + ContextStack stack) { + if (stack.anyErrors()) return null; + + sun.tools.java.Type type = theClass.getType(); + + // Do we already have it? + + String typeKey = type.toString() + stack.getContextCodeString(); + + Type existing = getType(typeKey,stack); + + if (existing != null) { + + if (!(existing instanceof SpecialClassType)) return null; // False hit. + + // Yep, so return it... + + return (SpecialClassType) existing; + } + + // Is it a special type? + + int typeCode = getTypeCode(type,theClass,stack); + + if (typeCode != TYPE_NONE) { + + // Yes... + + SpecialClassType result = new SpecialClassType(stack,typeCode,theClass); + putType(typeKey,result,stack); + stack.push(result); + stack.pop(true); + return result; + + } else { + + return null; + } + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Special class"; + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create an SpecialClassType instance for the given class. + */ + private SpecialClassType(ContextStack stack, int typeCode, + ClassDefinition theClass) { + super(stack,typeCode | TM_SPECIAL_CLASS | TM_CLASS | TM_COMPOUND, theClass); + Identifier id = theClass.getName(); + String idlName = null; + String[] idlModuleName = null; + boolean constant = stack.size() > 0 && stack.getContext().isConstant(); + + // Set names... + + switch (typeCode) { + case TYPE_STRING: { + idlName = IDLNames.getTypeName(typeCode,constant); + if (!constant) { + idlModuleName = IDL_CORBA_MODULE; + } + break; + } + + case TYPE_ANY: { + idlName = IDL_JAVA_LANG_OBJECT; + idlModuleName = IDL_JAVA_LANG_MODULE; + break; + } + } + + setNames(id,idlModuleName,idlName); + + // Init parents... + + if (!initParents(stack)) { + + // Should not be possible! + + throw new CompilerError("SpecialClassType found invalid parent."); + } + + // Initialize CompoundType... + + initialize(null,null,null,stack,false); + } + + private static int getTypeCode(sun.tools.java.Type type, ClassDefinition theClass, ContextStack stack) { + if (type.isType(TC_CLASS)) { + Identifier id = type.getClassName(); + if (id == idJavaLangString) return TYPE_STRING; + if (id == idJavaLangObject) return TYPE_ANY; + } + return TYPE_NONE; + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/SpecialInterfaceType.java b/src/share/classes/sun/rmi/rmic/iiop/SpecialInterfaceType.java new file mode 100644 index 000000000..a2b1e1951 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/SpecialInterfaceType.java @@ -0,0 +1,213 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import sun.tools.java.ClassNotFound; +import sun.tools.java.CompilerError; +import sun.tools.java.Identifier; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.ClassDefinition; + +/** + * SpecialInterfaceType represents any one of the following types: + *

                + *    java.rmi.Remote
                + *    java.io.Serializable
                + *    java.io.Externalizable
                + *    org.omg.CORBA.Object
                + *    org.omg.CORBA.portable.IDLEntity
                + * 
                + * all of which are treated as special cases. For all but CORBA.Object, + * the type must match exactly. For CORBA.Object, the type must either be + * CORBA.Object or inherit from it. + *

                + * The static forSpecial(...) method must be used to obtain an instance, and + * will return null if the type is non-conforming. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public class SpecialInterfaceType extends InterfaceType { + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create a SpecialInterfaceType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static SpecialInterfaceType forSpecial ( ClassDefinition theClass, + ContextStack stack) { + + if (stack.anyErrors()) return null; + + // Do we already have it? + + sun.tools.java.Type type = theClass.getType(); + Type existing = getType(type,stack); + + if (existing != null) { + + if (!(existing instanceof SpecialInterfaceType)) return null; // False hit. + + // Yep, so return it... + + return (SpecialInterfaceType) existing; + } + + // Is it special? + + if (isSpecial(type,theClass,stack)) { + + // Yes... + + SpecialInterfaceType result = new SpecialInterfaceType(stack,0,theClass); + putType(type,result,stack); + stack.push(result); + + if (result.initialize(type,stack)) { + stack.pop(true); + return result; + } else { + removeType(type,stack); + stack.pop(false); + return null; + } + } + return null; + } + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + return "Special interface"; + } + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create an SpecialInterfaceType instance for the given class. + */ + private SpecialInterfaceType(ContextStack stack, int typeCode, + ClassDefinition theClass) { + super(stack,typeCode | TM_SPECIAL_INTERFACE | TM_INTERFACE | TM_COMPOUND, theClass); + setNames(theClass.getName(),null,null); // Fixed in initialize. + } + + private static boolean isSpecial(sun.tools.java.Type type, + ClassDefinition theClass, + ContextStack stack) { + if (type.isType(TC_CLASS)) { + Identifier id = type.getClassName(); + + if (id.equals(idRemote)) return true; + if (id == idJavaIoSerializable) return true; + if (id == idJavaIoExternalizable) return true; + if (id == idCorbaObject) return true; + if (id == idIDLEntity) return true; + BatchEnvironment env = stack.getEnv(); + try { + if (env.defCorbaObject.implementedBy(env,theClass.getClassDeclaration())) return true; + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + } + return false; + } + + private boolean initialize(sun.tools.java.Type type, ContextStack stack) { + + int typeCode = TYPE_NONE; + Identifier id = null; + String idlName = null; + String[] idlModuleName = null; + boolean constant = stack.size() > 0 && stack.getContext().isConstant(); + + if (type.isType(TC_CLASS)) { + id = type.getClassName(); + + if (id.equals(idRemote)) { + typeCode = TYPE_JAVA_RMI_REMOTE; + idlName = IDL_JAVA_RMI_REMOTE; + idlModuleName = IDL_JAVA_RMI_MODULE; + } else if (id == idJavaIoSerializable) { + typeCode = TYPE_ANY; + idlName = IDL_SERIALIZABLE; + idlModuleName = IDL_JAVA_IO_MODULE; + } else if (id == idJavaIoExternalizable) { + typeCode = TYPE_ANY; + idlName = IDL_EXTERNALIZABLE; + idlModuleName = IDL_JAVA_IO_MODULE; + } else if (id == idIDLEntity) { + typeCode = TYPE_ANY; + idlName = IDL_IDLENTITY; + idlModuleName = IDL_ORG_OMG_CORBA_PORTABLE_MODULE; + } else { + + typeCode = TYPE_CORBA_OBJECT; + + // Is it exactly org.omg.CORBA.Object? + + if (id == idCorbaObject) { + + // Yes, so special case... + + idlName = IDLNames.getTypeName(typeCode,constant); + idlModuleName = null; + + } else { + + // No, so get the correct names... + + try { + + // These can fail if we get case-sensitive name matches... + + idlName = IDLNames.getClassOrInterfaceName(id,env); + idlModuleName = IDLNames.getModuleNames(id,isBoxed(),env); + + } catch (Exception e) { + failedConstraint(7,false,stack,id.toString(),e.getMessage()); + throw new CompilerError(""); + } + } + } + } + + if (typeCode == TYPE_NONE) { + return false; + } + + // Reset type code... + + setTypeCode(typeCode | TM_SPECIAL_INTERFACE | TM_INTERFACE | TM_COMPOUND); + + // Set names + + if (idlName == null) { + throw new CompilerError("Not a special type"); + } + + setNames(id,idlModuleName,idlName); + + // Initialize CompoundType... + + return initialize(null,null,null,stack,false); + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/StaticStringsHash.java b/src/share/classes/sun/rmi/rmic/iiop/StaticStringsHash.java new file mode 100644 index 000000000..757b3f9e0 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/StaticStringsHash.java @@ -0,0 +1,353 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +/** + * StaticStringsHash takes an array of constant strings and + * uses several different hash methods to try to find the + * 'best' one for that set. The set of methods is currently + * fixed, but with a little work could be made extensible thru + * subclassing. + *

                + * The current set of methods is: + *

                  + *
                1. length() - works well when all strings are different length.
                2. + *
                3. charAt(n) - works well when one offset into all strings is different.
                4. + *
                5. hashCode() - works well with larger arrays.
                6. + *
                + * After constructing an instance over the set of strings, the + * getKey(String) method can be used to use the selected hash + * method to produce a key. The method string will contain + * "length()", "charAt(n)", or "hashCode()", and is intended for use by + * code generators. + *

                + * The keys array will contain the full set of unique keys. + *

                + * The buckets array will contain a set of arrays, one for + * each key in the keys, where buckets[x][y] + * is an index into the strings array. + * @version 1.0, 4/17/99 + * @author Bryan Atsatt + */ +public class StaticStringsHash { + + /** The set of strings upon which the hash info is created */ + public String[] strings = null; + + /** Unique hash keys */ + public int[] keys = null; + + /** Buckets for each key, where buckets[x][y] is an index + * into the strings[] array. */ + public int[][] buckets = null; + + /** The method to invoke on String to produce the hash key */ + public String method = null; + + /** Get a key for the given string using the + * selected hash method. + * @param str the string to return a key for. + * @return the key. + */ + public int getKey(String str) { + switch (keyKind) { + case LENGTH: return str.length(); + case CHAR_AT: return str.charAt(charAt); + case HASH_CODE: return str.hashCode(); + } + throw new Error("Bad keyKind"); + } + + /** Constructor + * @param strings the set of strings upon which to + * find an optimal hash method. Must not contain + * duplicates. + */ + public StaticStringsHash(String[] strings) { + this.strings = strings; + length = strings.length; + tempKeys = new int[length]; + bucketSizes = new int[length]; + setMinStringLength(); + + // Decide on the best algorithm based on + // which one has the smallest maximum + // bucket depth. First, try length()... + + int currentMaxDepth = getKeys(LENGTH); + int useCharAt = -1; + boolean useHashCode = false; + + if (currentMaxDepth > 1) { + + // At least one bucket had more than one + // entry, so try charAt(i). If there + // are a lot of strings in the array, + // and minStringLength is large, limit + // the search to a smaller number of + // characters to avoid spending a lot + // of time here that is most likely to + // be pointless... + + int minLength = minStringLength; + if (length > CHAR_AT_MAX_LINES && + length * minLength > CHAR_AT_MAX_CHARS) { + minLength = length/CHAR_AT_MAX_CHARS; + } + + charAt = 0; + for (int i = 0; i < minLength; i++) { + int charAtDepth = getKeys(CHAR_AT); + if (charAtDepth < currentMaxDepth) { + currentMaxDepth = charAtDepth; + useCharAt = i; + if (currentMaxDepth == 1) { + break; + } + } + charAt++; + } + charAt = useCharAt; + + + if (currentMaxDepth > 1) { + + // At least one bucket had more than one + // entry, try hashCode(). + // + // Since the cost of computing a full hashCode + // (for the runtime target string) is much higher + // than the previous methods, use it only if it is + // substantially better. The definition of 'substantial' + // here is not very well founded, and could be improved + // with some further analysis ;^) + + int hashCodeDepth = getKeys(HASH_CODE); + if (hashCodeDepth < currentMaxDepth-3) { + + // Using the full hashCode results in at least + // 3 fewer entries in the worst bucket, so will + // therefore avoid at least 3 calls to equals() + // in the worst case. + // + // Note that using a number smaller than 3 could + // result in using a hashCode when there are only + // 2 strings in the array, and that would surely + // be a poor performance choice. + + useHashCode = true; + } + } + + // Reset keys if needed... + + if (!useHashCode) { + if (useCharAt >= 0) { + + // Use the charAt(i) method... + + getKeys(CHAR_AT); + + } else { + + // Use length method... + + getKeys(LENGTH); + } + } + } + + // Now allocate and fill our real hashKeys array... + + keys = new int[bucketCount]; + System.arraycopy(tempKeys,0,keys,0,bucketCount); + + // Sort keys and bucketSizes arrays... + + boolean didSwap; + do { + didSwap = false; + for (int i = 0; i < bucketCount - 1; i++) { + if (keys[i] > keys[i+1]) { + int temp = keys[i]; + keys[i] = keys[i+1]; + keys[i+1] = temp; + temp = bucketSizes[i]; + bucketSizes[i] = bucketSizes[i+1]; + bucketSizes[i+1] = temp; + didSwap = true; + } + } + } + while (didSwap == true); + + // Allocate our buckets array. Fill the string + // index slot with an unused key so we can + // determine which are free... + + int unused = findUnusedKey(); + buckets = new int[bucketCount][]; + for (int i = 0; i < bucketCount; i++) { + buckets[i] = new int[bucketSizes[i]]; + for (int j = 0; j < bucketSizes[i]; j++) { + buckets[i][j] = unused; + } + } + + // And fill it in... + + for(int i = 0; i < strings.length; i++) { + int key = getKey(strings[i]); + for (int j = 0; j < bucketCount; j++) { + if (keys[j] == key) { + int k = 0; + while (buckets[j][k] != unused) { + k++; + } + buckets[j][k] = i; + break; + } + } + } + } + + /** Print an optimized 'contains' method for the + * argument strings + */ + public static void main (String[] args) { + StaticStringsHash hash = new StaticStringsHash(args); + System.out.println(); + System.out.println(" public boolean contains(String key) {"); + System.out.println(" switch (key."+hash.method+") {"); + for (int i = 0; i < hash.buckets.length; i++) { + System.out.println(" case "+hash.keys[i]+": "); + for (int j = 0; j < hash.buckets[i].length; j++) { + if (j > 0) { + System.out.print(" } else "); + } else { + System.out.print(" "); + } + System.out.println("if (key.equals(\""+ hash.strings[hash.buckets[i][j]] +"\")) {"); + System.out.println(" return true;"); + } + System.out.println(" }"); + } + System.out.println(" }"); + System.out.println(" return false;"); + System.out.println(" }"); + } + + private int length; + private int[] tempKeys; + private int[] bucketSizes; + private int bucketCount; + private int maxDepth; + private int minStringLength = Integer.MAX_VALUE; + private int keyKind; + private int charAt; + + private static final int LENGTH = 0; + private static final int CHAR_AT = 1; + private static final int HASH_CODE = 2; + + /* Determines the maximum number of charAt(i) + * tests that will be done. The search is + * limited because if the number of characters + * is large enough, the likelyhood of finding + * a good hash key based on this method is + * low. The CHAR_AT_MAX_CHARS limit only + * applies f there are more strings than + * CHAR_AT_MAX_LINES. + */ + private static final int CHAR_AT_MAX_LINES = 50; + private static final int CHAR_AT_MAX_CHARS = 1000; + + private void resetKeys(int keyKind) { + this.keyKind = keyKind; + switch (keyKind) { + case LENGTH: method = "length()"; break; + case CHAR_AT: method = "charAt("+charAt+")"; break; + case HASH_CODE: method = "hashCode()"; break; + } + maxDepth = 1; + bucketCount = 0; + for (int i = 0; i < length; i++) { + tempKeys[i] = 0; + bucketSizes[i] = 0; + } + } + + private void setMinStringLength() { + for (int i = 0; i < length; i++) { + if (strings[i].length() < minStringLength) { + minStringLength = strings[i].length(); + } + } + } + + private int findUnusedKey() { + int unused = 0; + int keysLength = keys.length; + + // Note that we just assume that resource + // exhaustion will occur rather than an + // infinite loop here if the set of keys + // is very large. + + while (true) { + boolean match = false; + for (int i = 0; i < keysLength; i++) { + if (keys[i] == unused) { + match = true; + break; + } + } + if (match) { + unused--; + } else { + break; + } + } + return unused; + } + + private int getKeys(int methodKind) { + resetKeys(methodKind); + for(int i = 0; i < strings.length; i++) { + addKey(getKey(strings[i])); + } + return maxDepth; + } + + private void addKey(int key) { + + // Have we seen this one before? + + boolean addIt = true; + for (int j = 0; j < bucketCount; j++) { + if (tempKeys[j] == key) { + addIt = false; + bucketSizes[j]++; + if (bucketSizes[j] > maxDepth) { + maxDepth = bucketSizes[j]; + } + break; + } + } + + if (addIt) { + tempKeys[bucketCount] = key; + bucketSizes[bucketCount] = 1; + bucketCount++; + } + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java b/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java new file mode 100644 index 000000000..ae7c44234 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/StubGenerator.java @@ -0,0 +1,2275 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.File; +import java.io.IOException; +import java.util.Vector; +import java.util.Hashtable; +import java.util.Enumeration; +import sun.tools.java.Identifier; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.CompilerError; +import sun.rmi.rmic.IndentingWriter; +import java.util.HashSet; +import java.util.Arrays; +import com.sun.corba.ee.impl.util.Utility; +import com.sun.corba.ee.impl.util.PackagePrefixChecker; +import sun.rmi.rmic.Main; + +/** + * An IIOP stub/tie generator for rmic. + * + * @version 1.0, 2/23/98 + * @author Bryan Atsatt + * @author Anil Vijendran + * @version 2.0 fall 99 + * @author M. Mortazavi + */ + +public class StubGenerator extends sun.rmi.rmic.iiop.Generator { + + private static final String DEFAULT_STUB_CLASS = "javax.rmi.CORBA.Stub"; + private static final String DEFAULT_TIE_CLASS = "org.omg.CORBA_2_3.portable.ObjectImpl"; + private static final String DEFAULT_POA_TIE_CLASS = "org.omg.PortableServer.Servant"; + + protected boolean reverseIDs = false; + protected boolean localStubs = true; + protected boolean standardPackage = false; + protected boolean useHash = true; + protected String stubBaseClass = DEFAULT_STUB_CLASS; + protected String tieBaseClass = DEFAULT_TIE_CLASS; + protected HashSet namesInUse = new HashSet(); + protected Hashtable classesInUse = new Hashtable(); + protected Hashtable imports = new Hashtable(); + protected int importCount = 0; + protected String currentPackage = null; + protected String currentClass = null; + protected boolean castArray = false; + protected Hashtable transactionalObjects = new Hashtable() ; + protected boolean POATie = false ; + + /** + * Default constructor for Main to use. + */ + public StubGenerator() { + } + + /** + * Overridden in order to set the standardPackage flag. + */ + public void generate( + sun.rmi.rmic.BatchEnvironment env, + ClassDefinition cdef, File destDir) { + ((sun.rmi.rmic.iiop.BatchEnvironment)env). + setStandardPackage(standardPackage); + super.generate(env, cdef, destDir); + } + /** + * Return true if a new instance should be created for each + * class on the command line. Subclasses which return true + * should override newInstance() to return an appropriately + * constructed instance. + */ + protected boolean requireNewInstance() { + return false; + } + + /** + * Return true if non-conforming types should be parsed. + * @param stack The context stack. + */ + protected boolean parseNonConforming(ContextStack stack) { + + // We let the environment setting decide so that + // another generator (e.g. IDLGenerator) can change + // it and we will just go with the flow... + + return stack.getEnv().getParseNonConforming(); + } + + /** + * Create and return a top-level type. + * @param cdef The top-level class definition. + * @param stack The context stack. + * @return The compound type or null if is non-conforming. + */ + protected CompoundType getTopType(ClassDefinition cdef, ContextStack stack) { + + CompoundType result = null; + + // Do we have an interface? + + if (cdef.isInterface()) { + + // Yes, so first try Abstract... + + result = AbstractType.forAbstract(cdef,stack,true); + + if (result == null) { + + // Then try Remote... + + result = RemoteType.forRemote(cdef,stack,false); + } + } else { + + // Not an interface, so try Implementation... + + result = ImplementationType.forImplementation(cdef,stack,false); + } + + return result; + } + + /** + * Examine and consume command line arguments. + * @param argv The command line arguments. Ignore null + * and unknown arguments. Set each consumed argument to null. + * @param error Report any errors using the main.error() methods. + * @return true if no errors, false otherwise. + */ + public boolean parseArgs(String argv[], Main main) { + Object marker = new Object() ; + + // Reset any cached options... + + reverseIDs = false; + localStubs = true; + useHash = true; + stubBaseClass = DEFAULT_STUB_CLASS; + // tieBaseClass = DEFAULT_TIE_CLASS; + transactionalObjects = new Hashtable() ; + + // Parse options... + + boolean result = super.parseArgs(argv,main); + if (result) { + for (int i = 0; i < argv.length; i++) { + if (argv[i] != null) { + String arg = argv[i].toLowerCase(); + if (arg.equals("-iiop")) { + argv[i] = null; + } else if (arg.equals("-xreverseids")) { + reverseIDs = true; + argv[i] = null; + } else if (arg.equals("-nolocalstubs")) { + localStubs = false; + argv[i] = null; + } else if (arg.equals("-xnohash")) { + useHash = false; + argv[i] = null; + } else if (argv[i].equals("-standardPackage")) { + standardPackage = true; + argv[i] = null; + } else if (arg.equals("-xstubbase")) { + argv[i] = null; + if (++i < argv.length && argv[i] != null && !argv[i].startsWith("-")) { + stubBaseClass = argv[i]; + argv[i] = null; + } else { + main.error("rmic.option.requires.argument", "-Xstubbase"); + result = false; + } + } else if (arg.equals("-xtiebase")) { + argv[i] = null; + if (++i < argv.length && argv[i] != null && !argv[i].startsWith("-")) { + tieBaseClass = argv[i]; + argv[i] = null; + } else { + main.error("rmic.option.requires.argument", "-Xtiebase"); + result = false; + } + } else if (arg.equals("-transactional" )) { + // Scan for the next non-flag argument. + // Assume that it is a class name and add it + // to the list of transactional classes. + for ( int ctr=i+1; ctr 0) { + for(int i = 0; i < remoteInterfaces.length; i++) { + if (i > 0) { + p.pln(","); + } + String objName = testUtil(getName(remoteInterfaces[i]), theType); + p.p(objName); + } + } + + // Add java.rmi.Remote if this type does not implement it. + // This allows stubs for Abstract interfaces to be treated + // uniformly... + + if (!implementsRemote(theType)) { + p.pln(","); + p.p(getName("java.rmi.Remote")); + } + + p.plnI(" {"); + p.pln(); + + // Write the ids... + + writeIds( p, theType, false ); + p.pln(); + + // Write the _ids() method... + + p.plnI("public String[] _ids() { "); + p.pln("return _type_ids;"); + p.pOln("}"); + + // Get all the methods and write each stub method... + + CompoundType.Method[] remoteMethods = theType.getMethods(); + int methodCount = remoteMethods.length; + if (methodCount > 0) { + boolean writeHeader = true; + for(int i = 0; i < methodCount; i++) { + if (!remoteMethods[i].isConstructor()) { + if (writeHeader) { + writeHeader = false; + } + p.pln(); + writeStubMethod(p, remoteMethods[i], theType); + } + } + } + + // Write the cast array hack... + + writeCastArray(p); + + p.pOln("}"); // end stub class + } + + void addClassInUse(String qualifiedName) { + String unqualifiedName = qualifiedName; + String packageName = null; + int index = qualifiedName.lastIndexOf('.'); + if (index > 0) { + unqualifiedName = qualifiedName.substring(index+1); + packageName = qualifiedName.substring(0,index); + } + addClassInUse(unqualifiedName,qualifiedName,packageName); + } + + void addClassInUse(Type type) { + if (!type.isPrimitive()) { + Identifier id = type.getIdentifier(); + String name = IDLNames.replace(id.getName().toString(),". ","."); + String packageName = type.getPackageName(); + String qualifiedName; + if (packageName != null) { + qualifiedName = packageName+"."+name; + } else { + qualifiedName = name; + } + addClassInUse(name,qualifiedName,packageName); + } + } + + void addClassInUse(Type[] types) { + for (int i = 0; i < types.length; i++) { + addClassInUse(types[i]); + } + } + + void addStubInUse(Type type) { + if (type.getIdentifier() != idCorbaObject && + type.isType(TYPE_CORBA_OBJECT)) { + String stubName = getStubNameFor(type,false); + String packageName = type.getPackageName(); + String fullName; + if (packageName == null) { + fullName = stubName; + } else { + fullName = packageName + "." + stubName; + } + addClassInUse(stubName,fullName,packageName); + } + if (type.isType(TYPE_REMOTE) || + type.isType(TYPE_JAVA_RMI_REMOTE)) { + addClassInUse("javax.rmi.PortableRemoteObject"); + } + } + + String getStubNameFor(Type type, boolean qualified) { + String stubName; + String className; + if (qualified) { + className = type.getQualifiedName(); + } else { + className = type.getName(); + } + if (((CompoundType)type).isCORBAObject()) { + stubName = Utility.idlStubName(className); + } else { + stubName = Utility.stubNameForCompiler(className); + } + return stubName; + } + + void addStubInUse(Type[] types) { + for (int i = 0; i < types.length; i++) { + addStubInUse(types[i]); + } + } + + private static final String NO_IMPORT = new String(); + + void addClassInUse(String unqualifiedName, String qualifiedName, String packageName) { + + // Have we already got an entry for this qualifiedName? + + String currentName = (String)classesInUse.get(qualifiedName); + + if (currentName == null) { + + // No, never seen it before. Grab any existing import + // name and then decide what to do... + + String importName = (String) imports.get(unqualifiedName); + String nameToUse = null; + + if (packageName == null) { + + // Default package, so doesn't matter which name to use... + + nameToUse = unqualifiedName; + + } else if (packageName.equals("java.lang")) { + + // java.lang.*, so use unqualified name... + + nameToUse = unqualifiedName; + + // unless you want to be able to import things from the right place :--) + + if(nameToUse.endsWith("_Stub")) nameToUse = Util.packagePrefix()+qualifiedName; + + } else if (currentPackage != null && packageName.equals(currentPackage)) { + + // Class in currentPackage, so use unqualified name... + + nameToUse = unqualifiedName; + + // Do we already have a previous import under this + // unqualified name? + + if (importName != null) { + + // Yes, so we use qualifiedName... + + nameToUse = qualifiedName; + + } + + } else if (importName != null) { + + // It is in some package for which we normally + // would import, but we have a previous import + // under this unqualified name. We must use + // the qualified name... + + nameToUse = qualifiedName; + + /* + // Is the currentPackage the default package? + + if (currentPackage == null) { + + // Yes, so undo the import so that all + // uses for this name will be qualified... + + String old = (String)imports.remove(unqualifiedName); + classesInUse.put(old,old); + importCount--; + + // Note that this name is in use but should + // not be imported... + + imports.put(nameToUse,NO_IMPORT); + } + */ + } else if (qualifiedName.equals("org.omg.CORBA.Object")) { + + // Always qualify this quy to avoid confusion... + + nameToUse = qualifiedName; + + } else { + + // Default to using unqualified name, and add + // this guy to the imports... + + // Check for nested class in which case we use + // the fully qualified name instead of imports + if (unqualifiedName.indexOf('.') != -1) { + nameToUse = qualifiedName; + } else { + nameToUse = unqualifiedName; + imports.put(unqualifiedName,qualifiedName); + importCount++; + } + } + + // Now add the name... + + classesInUse.put(qualifiedName,nameToUse); + } + } + + String getName(Type type) { + if (type.isPrimitive()) { + return type.getName() + type.getArrayBrackets(); + } + Identifier id = type.getIdentifier(); + String name = IDLNames.replace(id.toString(),". ","."); + return getName(name) + type.getArrayBrackets(); + } + + // Added for Bug 4818753 + String getExceptionName(Type type) { + Identifier id = type.getIdentifier(); + return IDLNames.replace(id.toString(),". ","."); + } + + String getName(String qualifiedName) { + return (String)classesInUse.get(qualifiedName); + } + + String getName(Identifier id) { + return getName(id.toString()); + } + + String getStubName(Type type) { + String stubName = getStubNameFor(type,true); + return getName(stubName); + } + + void setStandardClassesInUse(CompoundType type, + boolean stub) throws IOException { + + // Reset our state... + + currentPackage = type.getPackageName(); + imports.clear(); + classesInUse.clear(); + namesInUse.clear(); + importCount = 0; + castArray = false; + + // Add the top-level type... + + addClassInUse(type); + + // START OF IASRI 6307510 + if (!type.isPrimitive()) + { + if (currentPackage == null) + imports.put(type.getName().toString(),type.getName().toString()); + else + imports.put(type.getName().toString(),currentPackage+"."+type.getName().toString()); + importCount++; + } + // END OF IASRI 6307510 + + // Set current class name... + + if (stub) { + currentClass = Utility.stubNameForCompiler(type.getName()); + } else { + currentClass = Utility.tieNameForCompiler(type.getName()); + } + + // Add current class... + + if (currentPackage == null) { + addClassInUse(currentClass,currentClass,currentPackage); + } else { + addClassInUse(currentClass,(currentPackage+"."+currentClass),currentPackage); + } + + // Add standard classes... + + addClassInUse("javax.rmi.CORBA.Util"); + addClassInUse(idRemote.toString()); + addClassInUse(idRemoteException.toString()); + addClassInUse(idOutputStream.toString()); + addClassInUse(idInputStream.toString()); + addClassInUse(idSystemException.toString()); + addClassInUse(idJavaIoSerializable.toString()); + addClassInUse(idCorbaORB.toString()); + addClassInUse(idReplyHandler.toString()); + + // Add stub/tie specific imports... + + if (stub) { + addClassInUse(stubBaseClass); + addClassInUse("java.rmi.UnexpectedException"); + addClassInUse(idRemarshalException.toString()); + addClassInUse(idApplicationException.toString()); + if (localStubs) { + addClassInUse("org.omg.CORBA.portable.ServantObject"); + } + } else { + addClassInUse(type); + addClassInUse(tieBaseClass); + addClassInUse(idTieInterface.toString()); + addClassInUse(idBadMethodException.toString()); + addClassInUse(idPortableUnknownException.toString()); + addClassInUse(idJavaLangThrowable.toString()); + } + } + + void addClassesInUse(CompoundType type, RemoteType[] interfaces) { + + // Walk all methods and add types in use... + + CompoundType.Method[] methods = type.getMethods(); + for (int i = 0; i < methods.length; i++) { + addClassInUse(methods[i].getReturnType()); + addStubInUse(methods[i].getReturnType()); + addClassInUse(methods[i].getArguments()); + addStubInUse(methods[i].getArguments()); + addClassInUse(methods[i].getExceptions()); + // bug 4473859: Also include narrower subtypes for use + addClassInUse(methods[i].getImplExceptions()); + } + + // If this is a stub, add all interfaces... + + if (interfaces != null) { + addClassInUse(interfaces); + } + } + + void writePackageAndImports(IndentingWriter p) throws IOException { + + // Write package declaration... + + if (currentPackage != null) { + p.pln("package " + + Util.correctPackageName( + currentPackage, false, standardPackage) + + ";"); + p.pln(); + } + + // Get imports into an array and sort them... + + String[] names = new String[importCount]; + int index = 0; + for (Enumeration e = imports.elements() ; e.hasMoreElements() ;) { + String it = (String) e.nextElement(); + if (it != NO_IMPORT) { + names[index++] = it; + } + } + + Arrays.sort(names,new StringComparator()); + + // Now dump them out... + + for (int i = 0; i < importCount; i++) { + if( + Util.isOffendingPackage(names[i]) + && names[i].endsWith("_Stub") + && String.valueOf(names[i].charAt(names[i].lastIndexOf(".")+1)).equals("_") + ){ + p.pln("import " + PackagePrefixChecker.packagePrefix()+names[i]+";"); + } else{ + p.pln("import " + names[i] + ";"); + } + } + p.pln(); + + // Include offending packages . . . + if ( currentPackage!=null && Util.isOffendingPackage(currentPackage) ){ + p.pln("import " + currentPackage +".* ;"); + } + p.pln(); + + } + + boolean implementsRemote(CompoundType theType) { + boolean result = theType.isType(TYPE_REMOTE) && !theType.isType(TYPE_ABSTRACT); + + // If theType is not remote, look at all the interfaces + // until we find one that is... + + if (!result) { + InterfaceType[] interfaces = theType.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + result = implementsRemote(interfaces[i]); + if (result) { + break; + } + } + } + + return result; + } + + void writeStubMethod ( IndentingWriter p, + CompoundType.Method method, + CompoundType theType) throws IOException { + + // Wtite the method declaration and opening brace... + + String methodName = method.getName(); + String methodIDLName = method.getIDLName(); + + Type paramTypes[] = method.getArguments(); + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getStubExceptions(method,false); + + addNamesInUse(method); + addNameInUse("_type_ids"); + + String objName = testUtil(getName(returnType), returnType); + p.p("public " + objName + " " + methodName + "("); + for(int i = 0; i < paramTypes.length; i++) { + if (i > 0) + p.p(", "); + p.p(getName(paramTypes[i]) + " " + paramNames[i]); + } + + p.p(")"); + if (exceptions.length > 0) { + p.p(" throws "); + for(int i = 0; i < exceptions.length; i++) { + if (i > 0) { + p.p(", "); + } + // Added for Bug 4818753 + p.p(getExceptionName(exceptions[i])); + } + } + + p.plnI(" {"); + + // Now create the method body... + + if (localStubs) { + writeLocalStubMethodBody(p,method,theType); + } else { + writeNonLocalStubMethodBody(p,method,theType); + } + + // Close out the method... + + p.pOln("}"); + } + + + void writeLocalStubMethodBody (IndentingWriter p, + CompoundType.Method method, + CompoundType theType) throws IOException { + + String objName; + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getStubExceptions(method,false); + String methodName = method.getName(); + String methodIDLName = method.getIDLName(); + + p.plnI("if (!Util.isLocal(this)) {"); + writeNonLocalStubMethodBody(p,method,theType); + p.pOlnI("} else {"); + String so = getVariableName("so"); + + p.pln("ServantObject "+so+" = _servant_preinvoke(\""+methodIDLName+"\","+getName(theType)+".class);"); + p.plnI("if ("+so+" == null) {"); + if (!returnType.isType(TYPE_VOID)) { + p.p("return "); + } + p.p(methodName+"("); + for (int i = 0; i < paramNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(paramNames[i]); + } + p.pln(");"); + if (returnType.isType(TYPE_VOID)) { + p.pln( "return ;" ) ; + } + + p.pOln("}"); + p.plnI("try {"); + + // Generate code to copy required arguments, and + // get back the names by which all arguments are known... + + String[] argNames = writeCopyArguments(method,p); + + // Now write the method... + + boolean copyReturn = mustCopy(returnType); + String resultName = null; + if (!returnType.isType(TYPE_VOID)) { + if (copyReturn) { + resultName = getVariableName("result"); + objName = testUtil(getName(returnType), returnType); + p.p(objName+" "+resultName + " = "); + } else { + p.p("return "); + } + } + objName = testUtil(getName(theType), theType); + p.p("(("+objName+")"+so+".servant)."+methodName+"("); + + for (int i = 0; i < argNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(argNames[i]); + } + + if (copyReturn) { + p.pln(");"); + objName = testUtil(getName(returnType), returnType); + p.pln("return ("+objName+")Util.copyObject("+resultName+",_orb());"); + } else { + p.pln(");"); + } + + String e1 = getVariableName("ex"); + String e2 = getVariableName("exCopy"); + p.pOlnI("} catch (Throwable "+e1+") {"); + + p.pln("Throwable "+e2+" = (Throwable)Util.copyObject("+e1+",_orb());"); + for(int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getIdentifier() != idRemoteException && + exceptions[i].isType(TYPE_VALUE)) { + // Added for Bug 4818753 + p.plnI("if ("+e2+" instanceof "+getExceptionName(exceptions[i])+") {"); + p.pln("throw ("+getExceptionName(exceptions[i])+")"+e2+";"); + p.pOln("}"); + } + } + + p.pln("throw Util.wrapException("+e2+");"); + p.pOlnI("} finally {"); + p.pln("_servant_postinvoke("+so+");"); + p.pOln("}"); + p.pOln("}"); + } + + + void writeNonLocalStubMethodBody ( IndentingWriter p, + CompoundType.Method method, + CompoundType theType) throws IOException { + + String methodName = method.getName(); + String methodIDLName = method.getIDLName(); + + Type paramTypes[] = method.getArguments(); + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getStubExceptions(method,true); + + String in = getVariableName("in"); + String out = getVariableName("out"); + String ex = getVariableName("ex"); + + // Decide if we need to use the new streams for + // any of the read calls... + + boolean needNewReadStreamClass = false; + for (int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getIdentifier() != idRemoteException && + exceptions[i].isType(TYPE_VALUE) && + needNewReadStreamClass(exceptions[i])) { + needNewReadStreamClass = true; + break; + } + } + if (!needNewReadStreamClass) { + for (int i = 0; i < paramTypes.length; i++) { + if (needNewReadStreamClass(paramTypes[i])) { + needNewReadStreamClass = true; + break; + } + } + } + if (!needNewReadStreamClass) { + needNewReadStreamClass = needNewReadStreamClass(returnType); + } + + // Decide if we need to use the new streams for + // any of the write calls... + + boolean needNewWriteStreamClass = false; + for (int i = 0; i < paramTypes.length; i++) { + if (needNewWriteStreamClass(paramTypes[i])) { + needNewWriteStreamClass = true; + break; + } + } + + // Now write the method, inserting casts where needed... + + p.plnI("try {"); + if (needNewReadStreamClass) { + p.pln(idExtInputStream + " "+in+" = null;"); + } else { + p.pln(idInputStream + " "+in+" = null;"); + } + p.plnI("try {"); + + String argStream = "null"; + + if (needNewWriteStreamClass) { + p.plnI(idExtOutputStream + " "+out+" = "); + p.pln("(" + idExtOutputStream + ")"); + p.pln("_request(\"" + methodIDLName + "\", true);"); + p.pO(); + } else { + p.pln("OutputStream "+out+" = _request(\"" + methodIDLName + "\", true);"); + } + + if (paramTypes.length > 0) { + writeMarshalArguments(p, out, paramTypes, paramNames); + p.pln(); + } + argStream = out; + + if (returnType.isType(TYPE_VOID)) { + p.pln("_invoke(" + argStream + ");" ); + } else { + if (needNewReadStreamClass) { + p.plnI(in+" = (" + idExtInputStream + ")_invoke(" + argStream + ");"); + p.pO(); + } else { + p.pln(in+" = _invoke(" + argStream + ");"); + } + p.p("return "); + writeUnmarshalArgument(p, in, returnType, null); + p.pln(); + } + + // Handle ApplicationException... + + p.pOlnI("} catch ("+getName(idApplicationException)+" "+ex+") {"); + if (needNewReadStreamClass) { + p.pln(in + " = (" + idExtInputStream + ") "+ex+".getInputStream();"); + } else { + p.pln(in + " = "+ex+".getInputStream();"); + } + + boolean idRead = false; + boolean idAllocated = false; + for(int i = 0; i < exceptions.length; i++) { + if (exceptions[i].getIdentifier() != idRemoteException) { + + // Is this our special-case IDLEntity exception? + + if (exceptions[i].isIDLEntityException() && !exceptions[i].isCORBAUserException()) { + + // Yes. + + if (!idAllocated && !idRead) { + p.pln("String $_id = "+ex+".getId();"); + idAllocated = true; + } + + String helperName = IDLNames.replace(exceptions[i].getQualifiedIDLName(false),"::","."); + helperName += "Helper"; + p.plnI("if ($_id.equals("+helperName+".id())) {"); + p.pln("throw "+helperName+".read("+in+");"); + + } else { + + // No. + + if (!idAllocated && !idRead) { + p.pln("String $_id = "+in+".read_string();"); + idAllocated = true; + idRead = true; + } else if (idAllocated && !idRead) { + p.pln("$_id = "+in+".read_string();"); + idRead = true; + } + p.plnI("if ($_id.equals(\""+getExceptionRepositoryID(exceptions[i])+"\")) {"); + // Added for Bug 4818753 + p.pln("throw ("+getExceptionName(exceptions[i])+") "+in+".read_value(" + getExceptionName(exceptions[i]) + ".class);"); + } + p.pOln("}"); + } + } + if (!idAllocated && !idRead) { + p.pln("String $_id = "+in+".read_string();"); + idAllocated = true; + idRead = true; + } else if (idAllocated && !idRead) { + p.pln("$_id = "+in+".read_string();"); + idRead = true; + } + p.pln("throw new UnexpectedException($_id);"); + + // Handle RemarshalException... + + p.pOlnI("} catch ("+getName(idRemarshalException)+" "+ex+") {"); + if (!returnType.isType(TYPE_VOID)) { + p.p("return "); + } + p.p(methodName + "("); + for(int i = 0; i < paramTypes.length; i++) { + if (i > 0) { + p.p(","); + } + p.p(paramNames[i]); + } + p.pln(");"); + + // Ensure that we release the reply... + + p.pOlnI("} finally {"); + p.pln("_releaseReply("+in+");"); + + p.pOln("}"); + + // Handle SystemException... + + p.pOlnI("} catch (SystemException "+ex+") {"); + p.pln("throw Util.mapSystemException("+ex+");"); + p.pOln("}"); + + // returnResult(p,returnType); + } + + void allocateResult (IndentingWriter p, + Type returnType) throws IOException { + if (!returnType.isType(TYPE_VOID)) { + String objName = testUtil(getName(returnType), returnType); + p.p(objName + " result = "); + } + } + + int getTypeCode(Type type) { + + int typeCode = type.getTypeCode(); + + // Handle late-breaking special case for + // abstract IDL entities... + + if ((type instanceof CompoundType) && + ((CompoundType)type).isAbstractBase()) { + typeCode = TYPE_ABSTRACT; + } + + return typeCode; + } + + + /** + * Write a snippet of Java code to marshal a value named "name" of + * type "type" to the java.io.ObjectOutput stream named "stream". + */ + void writeMarshalArgument(IndentingWriter p, + String streamName, + Type type, String name) throws IOException { + + int typeCode = getTypeCode(type); + + switch (typeCode) { + case TYPE_BOOLEAN: + p.p(streamName + ".write_boolean(" + name + ");"); + break; + case TYPE_BYTE: + p.p(streamName + ".write_octet(" + name + ");"); + break; + case TYPE_CHAR: + p.p(streamName + ".write_wchar(" + name + ");"); + break; + case TYPE_SHORT: + p.p(streamName + ".write_short(" + name + ");"); + break; + case TYPE_INT: + p.p(streamName + ".write_long(" + name + ");"); + break; + case TYPE_LONG: + p.p(streamName + ".write_longlong(" + name + ");"); + break; + case TYPE_FLOAT: + p.p(streamName + ".write_float(" + name + ");"); + break; + case TYPE_DOUBLE: + p.p(streamName + ".write_double(" + name + ");"); + break; + case TYPE_STRING: + p.p(streamName + ".write_value(" + name + "," + getName(type) + ".class);"); + break; + case TYPE_ANY: + p.p("Util.writeAny("+ streamName + "," + name + ");"); + break; + case TYPE_CORBA_OBJECT: + p.p(streamName + ".write_Object(" + name + ");"); + break; + case TYPE_REMOTE: + p.p("Util.writeRemoteObject("+ streamName + "," + name + ");"); + break; + case TYPE_ABSTRACT: + p.p("Util.writeAbstractObject("+ streamName + "," + name + ");"); + break; + case TYPE_NC_INTERFACE: + p.p(streamName + ".write_value((Serializable)" + name + "," + getName(type) + ".class);"); + break; + case TYPE_VALUE: + p.p(streamName + ".write_value(" + name + "," + getName(type) + ".class);"); + break; + case TYPE_IMPLEMENTATION: + p.p(streamName + ".write_value((Serializable)" + name + "," + getName(type) + ".class);"); + break; + case TYPE_NC_CLASS: + p.p(streamName + ".write_value((Serializable)" + name + "," + getName(type) + ".class);"); + break; + case TYPE_ARRAY: + castArray = true; + p.p(streamName + ".write_value(cast_array(" + name + ")," + getName(type) + ".class);"); + break; + case TYPE_JAVA_RMI_REMOTE: + p.p("Util.writeRemoteObject("+ streamName + "," + name + ");"); + break; + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Write a snippet of Java code to unmarshal a value of type "type" + * from the java.io.ObjectInput stream named "stream" into a variable + * named "name" (if "name" is null, the value in unmarshalled and + * discarded). + */ + void writeUnmarshalArgument(IndentingWriter p, + String streamName, + Type type, + String name) throws IOException { + + int typeCode = getTypeCode(type); + + if (name != null) { + p.p(name + " = "); + } + + switch (typeCode) { + case TYPE_BOOLEAN: + p.p(streamName + ".read_boolean();"); + break; + case TYPE_BYTE: + p.p(streamName + ".read_octet();"); + break; + case TYPE_CHAR: + p.p(streamName + ".read_wchar();"); + break; + case TYPE_SHORT: + p.p(streamName + ".read_short();"); + break; + case TYPE_INT: + p.p(streamName + ".read_long();"); + break; + case TYPE_LONG: + p.p(streamName + ".read_longlong();"); + break; + case TYPE_FLOAT: + p.p(streamName + ".read_float();"); + break; + case TYPE_DOUBLE: + p.p(streamName + ".read_double();"); + break; + case TYPE_STRING: + p.p("(String) " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_ANY: + if (type.getIdentifier() != idJavaLangObject) { + p.p("(" + getName(type) + ") "); + } + p.p("Util.readAny(" + streamName + ");"); + break; + case TYPE_CORBA_OBJECT: + if (type.getIdentifier() == idCorbaObject) { + p.p("(" + getName(type) + ") " + streamName + ".read_Object();"); + } else { + p.p("(" + getName(type) + ") " + streamName + ".read_Object(" + getStubName(type) + ".class);"); + } + break; + case TYPE_REMOTE: + String objName = testUtil(getName(type), type); + p.p("(" + objName + ") " + + "PortableRemoteObject.narrow(" + streamName + ".read_Object(), " + objName + ".class);"); + break; + case TYPE_ABSTRACT: + p.p("(" + getName(type) + ") " + streamName + ".read_abstract_interface();"); + break; + case TYPE_NC_INTERFACE: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_VALUE: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_IMPLEMENTATION: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_NC_CLASS: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_ARRAY: + p.p("(" + getName(type) + ") " + streamName + ".read_value(" + getName(type) + ".class);"); + break; + case TYPE_JAVA_RMI_REMOTE: + p.p("(" + getName(type) + ") " + + "PortableRemoteObject.narrow(" + streamName + ".read_Object(), " + getName(type) + ".class);"); + // p.p("(" + getName(type) + ") " + streamName + ".read_Object(" + getStubName(type) + ".class);"); + break; + default: + throw new Error("unexpected type code: " + typeCode); + } + } + + /** + * Get a list of all the RepositoryIDs for interfaces + * implemented directly or indirectly by theType. In the + * case of an ImplementationType which implements 2 or + * more remote interfaces, this list will begin with the + * Identifier for the implementation (see section 5.9 in + * the Java -> IDL mapping). Ensures that the most derived + * type is first in the list because the IOR is generated + * using that entry in the _ids array. + */ + String[] getAllRemoteRepIDs (CompoundType theType) { + + String[] result; + + // Collect up all the (inherited) remote interfaces + // (ignores all the 'special' interfaces: Remote, + // Serializable, Externalizable)... + + Type[] types = collectAllRemoteInterfaces(theType); + + int length = types.length; + boolean haveImpl = theType instanceof ImplementationType; + InterfaceType[] interfaces = theType.getInterfaces(); + int remoteCount = countRemote(interfaces,false); + int offset = 0; + + // Do we have an implementation type that implements + // more than one remote interface? + + if (haveImpl && remoteCount > 1) { + + // Yes, so we need to insert it at the beginning... + + result = new String[length + 1]; + result[0] = getRepositoryID(theType); + offset = 1; + + } else { + + // No. + + result = new String[length]; + + // Here we need to ensure that the most derived + // interface ends up being first in the list. If + // there is only one, we're done. + + if (length > 1) { + + // First, decide what the most derived type is... + + String mostDerived = null; + + if (haveImpl) { + + // If we get here, we know that there is only one + // direct remote interface, so just find it... + + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i].isType(TYPE_REMOTE)) { + mostDerived = interfaces[i].getRepositoryID(); + break; + } + } + } else { + + // If we get here we know that theType is a RemoteType + // so just use its id... + + mostDerived = theType.getRepositoryID(); + } + + // Now search types list and make sure mostDerived is + // at index zero... + + for (int i = 0; i < length; i++) { + if (types[i].getRepositoryID() == mostDerived) { + + // Found it. Swap it if we need to... + + if (i > 0) { + Type temp = types[0]; + types[0] = types[i]; + types[i] = temp; + } + + break; + } + } + } + } + + // Now copy contents of the types array... + + for (int i = 0; i < types.length; i++) { + result[offset++] = getRepositoryID(types[i]); + } + + // If we're supposed to, reverse the array. This + // is only done when the -testReverseIDs flag is + // passed, and that should ONLY be done for test + // cases. This is an undocumented feature. + + if (reverseIDs) { + int start = 0; + int end = result.length -1; + while (start < end) { + String temp = result[start]; + result[start++] = result[end]; + result[end--] = temp; + } + } + + return result; + } + + /** + * Collect all the inherited remote interfaces. + */ + Type[] collectAllRemoteInterfaces (CompoundType theType) { + Vector list = new Vector(); + + // Collect up all the Remote interfaces, and get an instance + // for java.rmi.Remote... + + addRemoteInterfaces(list,theType); + + // Create and return our results... + + Type[] result = new Type[list.size()]; + list.copyInto(result); + + return result; + } + + /** + * Add all the inherited remote interfaces to list. + */ + void addRemoteInterfaces(Vector list, CompoundType theType) { + + if (theType != null) { + if (theType.isInterface() && !list.contains(theType)) { + list.addElement(theType); + } + + InterfaceType[] interfaces = theType.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + + if (interfaces[i].isType(TYPE_REMOTE)) { + addRemoteInterfaces(list,interfaces[i]); + } + } + + addRemoteInterfaces(list,theType.getSuperclass()); + } + } + + /** + * Get a list of all the remote interfaces which this stub + * should declare. + */ + RemoteType[] getDirectRemoteInterfaces (CompoundType theType) { + + RemoteType[] result; + InterfaceType[] interfaces = theType.getInterfaces(); + + // First, get a list of all the interfaces... + + InterfaceType[] list; + + // Because we can be passed either an ImplementationType + // (which has interfaces) or a RemoteType (which is an + // interface and may have interfaces) we must handle each + // separately... + + // Do we have an implementation type? + + if (theType instanceof ImplementationType) { + + // Yes, so list is exactly what this type + // implements and is correct already. + + list = interfaces; + + } else { + + // No, so list is just theType... + + list = new InterfaceType[1]; + list[0] = (InterfaceType) theType; + } + + // Ok, now count up the remote interfaces, allocate + // our result and fill it in... + + int remoteCount = countRemote(list,false); + + if (remoteCount == 0) { + throw new CompilerError("iiop.StubGenerator: No remote interfaces!"); + } + + result = new RemoteType[remoteCount]; + int offset = 0; + for (int i = 0; i < list.length; i++) { + if (list[i].isType(TYPE_REMOTE)) { + result[offset++] = (RemoteType)list[i]; + } + } + + return result; + } + + int countRemote (Type[] list, boolean includeAbstract) { + int remoteCount = 0; + for (int i = 0; i < list.length; i++) { + if (list[i].isType(TYPE_REMOTE) && + (includeAbstract || !list[i].isType(TYPE_ABSTRACT))) { + remoteCount++; + } + } + + return remoteCount; + } + + void writeCastArray(IndentingWriter p) throws IOException { + if (castArray) { + p.pln(); + p.pln("// This method is required as a work-around for"); + p.pln("// a bug in the JDK 1.1.6 verifier."); + p.pln(); + p.plnI("private "+getName(idJavaIoSerializable)+" cast_array(Object obj) {"); + p.pln("return ("+getName(idJavaIoSerializable)+")obj;"); + p.pOln("}"); + } + } + void writeIds(IndentingWriter p, CompoundType theType, boolean isTie + ) throws IOException { + p.plnI("private static final String[] _type_ids = {"); + + String[] ids = getAllRemoteRepIDs(theType); + + if (ids.length >0 ) { + for(int i = 0; i < ids.length; i++) { + if (i > 0) + p.pln(", "); + p.p("\"" + ids[i] + "\""); + } + } else { + // Must be an implementation which only implements Remote... + p.pln("\"\""); + } + String qname = theType.getQualifiedName() ; + boolean isTransactional = isTie && transactionalObjects.containsKey( qname ) ; + // Add TransactionalObject if needed. + if (isTransactional) { + // Have already written an id. + p.pln( ", " ) ; + p.pln( "\"IDL:omg.org/CosTransactions/TransactionalObject:1.0\"" ) ; + } else if (ids.length > 0) { + p.pln(); + } + p.pOln("};"); + } + + + /** + * Write the Tie for the remote class to a stream. + */ + protected void writeTie(OutputType outputType, + IndentingWriter p) throws IOException + { + CompoundType theType = (CompoundType) outputType.getType(); + RemoteType[] remoteInterfaces = null; + + // Write comment... + p.pln("// Tie class generated by rmic, do not edit."); + p.pln("// Contents subject to change without notice."); + p.pln(); + + // Set our standard classes... + setStandardClassesInUse(theType,false); + + // Add classes for this type... + addClassesInUse(theType,remoteInterfaces); + + // START OF IASRI 6307510 + imports.remove(theType.getName().toString()); + importCount--; + // END OF IASRI 6307510 + + // Write package and import statements... + writePackageAndImports(p); + + // Declare the tie class. + p.p("public class " + currentClass + " extends " + + getName(tieBaseClass) + " implements Tie"); + + // Add java.rmi.Remote if this type does not implement it. + // This allows stubs for Abstract interfaces to be treated + // uniformly... + if (!implementsRemote(theType)) { + p.pln(","); + p.p(getName("java.rmi.Remote")); + } + + p.plnI(" {"); + + // Write data members... + p.pln(); + p.pln("private " + getName(theType) + " target = null;"); + p.pln(); + + // Write the ids... + writeIds( p, theType, true ) ; + + // Write setTarget method... + p.pln(); + p.plnI("public void setTarget(Remote target) {"); + p.pln("this.target = (" + getName(theType) + ") target;"); + p.pOln("}"); + + // Write getTarget method... + p.pln(); + p.plnI("public Remote getTarget() {"); + p.pln("return target;"); + p.pOln("}"); + + // Write thisObject method... + p.pln(); + write_tie_thisObject_method(p,idCorbaObject); + + // Write deactivate method... + p.pln(); + write_tie_deactivate_method(p); + + // Write get orb method... + p.pln(); + p.plnI("public ORB orb() {"); + p.pln("return _orb();"); + p.pOln("}"); + + // Write set orb method... + p.pln(); + write_tie_orb_method(p); + + // Write the _ids() method... + p.pln(); + write_tie__ids_method(p); + + // Get all the methods... + CompoundType.Method[] remoteMethods = theType.getMethods(); + + // Register all the argument names used, plus our + // data member names... + + addNamesInUse(remoteMethods); + addNameInUse("target"); + addNameInUse("_type_ids"); + + // Write the _invoke method... + p.pln(); + + String in = getVariableName("in"); + String _in = getVariableName("_in"); + String ex = getVariableName("ex"); + String method = getVariableName("method"); + String reply = getVariableName("reply"); + + p.plnI("public OutputStream _invoke(String "+method+", InputStream "+_in+", " + + "ResponseHandler "+reply+") throws SystemException {"); + + if (remoteMethods.length > 0) { + p.plnI("try {"); + p.plnI(idExtInputStream + " "+in+" = "); + p.pln("(" + idExtInputStream + ") "+_in+";"); + p.pO(); + + // See if we should use a hash table style + // comparison... + + StaticStringsHash hash = getStringsHash(remoteMethods); + + if (hash != null) { + p.plnI("switch ("+method+"."+hash.method+") {"); + for (int i = 0; i < hash.buckets.length; i++) { + p.plnI("case "+hash.keys[i]+": "); + for (int j = 0; j < hash.buckets[i].length; j++) { + CompoundType.Method current = remoteMethods[hash.buckets[i][j]]; + if (j > 0) { + p.pO("} else "); + } + p.plnI("if ("+method+".equals(\""+ current.getIDLName() +"\")) {"); + writeTieMethod(p, theType,current); + } + p.pOln("}"); + p.pO(); + } + } else { + for(int i = 0; i < remoteMethods.length; i++) { + CompoundType.Method current = remoteMethods[i]; + if (i > 0) { + p.pO("} else "); + } + + p.plnI("if ("+method+".equals(\""+ current.getIDLName() +"\")) {"); + writeTieMethod(p, theType, current); + } + } + + if (hash != null) { + p.pI(); + // p.plnI("default:"); + } else { + // p.pOlnI("} else {"); + } + // p.pln("throw new "+getName(idBadMethodException)+"();"); + + if (hash != null) { + p.pO(); + } + p.pOln("}"); + p.pln("throw new "+getName(idBadMethodException)+"();"); + + p.pOlnI("} catch ("+getName(idSystemException)+" "+ex+") {"); + p.pln("throw "+ex+";"); + + p.pOlnI("} catch ("+getName(idJavaLangThrowable)+" "+ex+") {"); + p.pln("throw new " + getName(idPortableUnknownException) + "("+ex+");"); + p.pOln("}"); + } else { + // No methods... + + p.pln("throw new " + getName(idBadMethodException) + "();"); + } + + p.pOln("}"); // end invoke + + // Write the cast array hack... + + writeCastArray(p); + + // End tie class... + p.pOln("}"); + } + public void catchWrongPolicy(IndentingWriter p) throws IOException { + p.pln(""); + } + public void catchServantNotActive(IndentingWriter p) throws IOException { + p.pln(""); + } + public void catchObjectNotActive(IndentingWriter p) throws IOException { + p.pln(""); + } + + public void write_tie_thisObject_method(IndentingWriter p, + Identifier idCorbaObject) + throws IOException + { + if(POATie){ + p.plnI("public " + idCorbaObject + " thisObject() {"); + /* + p.pln("org.omg.CORBA.Object objref = null;"); + p.pln("try{"); + p.pln("objref = _poa().servant_to_reference(this);"); + p.pln("}catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){"); + catchWrongPolicy(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){"); + catchServantNotActive(p); + p.pln("}"); + p.pln("return objref;"); + */ + p.pln("return _this_object();"); + p.pOln("}"); + } else { + p.plnI("public " + idCorbaObject + " thisObject() {"); + p.pln("return this;"); + p.pOln("}"); + } + } + + public void write_tie_deactivate_method(IndentingWriter p) + throws IOException + { + if(POATie){ + p.plnI("public void deactivate() {"); + p.pln("try{"); + p.pln("_poa().deactivate_object(_poa().servant_to_id(this));"); + p.pln("}catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){"); + catchWrongPolicy(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ObjectNotActive exception){"); + catchObjectNotActive(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){"); + catchServantNotActive(p); + p.pln("}"); + p.pOln("}"); + } else { + p.plnI("public void deactivate() {"); + p.pln("_orb().disconnect(this);"); + p.pln("_set_delegate(null);"); + p.pln("target = null;"); + p.pOln("}"); + } + } + + public void write_tie_orb_method(IndentingWriter p) + throws IOException + { + if(POATie){ + p.plnI("public void orb(ORB orb) {"); + /* + p.pln("try{"); + p.pln("orb.connect(_poa().servant_to_reference(this));"); + p.pln("}catch (org.omg.PortableServer.POAPackage.WrongPolicy exception){"); + catchWrongPolicy(p); + p.pln("}catch (org.omg.PortableServer.POAPackage.ServantNotActive exception){"); + catchServantNotActive(p); + p.pln("}"); + */ + p.pln("try {"); + p.pln(" ((org.omg.CORBA_2_3.ORB)orb).set_delegate(this);"); + p.pln("}"); + p.pln("catch(ClassCastException e) {"); + p.pln(" throw new org.omg.CORBA.BAD_PARAM"); + p.pln(" (\"POA Servant requires an instance of org.omg.CORBA_2_3.ORB\");"); + p.pln("}"); + p.pOln("}"); + } else { + p.plnI("public void orb(ORB orb) {"); + p.pln("orb.connect(this);"); + p.pOln("}"); + } + } + + public void write_tie__ids_method(IndentingWriter p) + throws IOException + { + if(POATie){ + p.plnI("public String[] _all_interfaces(org.omg.PortableServer.POA poa, byte[] objectId){"); + p.pln("return _type_ids;"); + p.pOln("}"); + } else { + p.plnI("public String[] _ids() { "); + p.pln("return _type_ids;"); + p.pOln("}"); + } + } + + + StaticStringsHash getStringsHash (CompoundType.Method[] methods) { + if (useHash && methods.length > 1) { + String[] methodNames = new String[methods.length]; + for (int i = 0; i < methodNames.length; i++) { + methodNames[i] = methods[i].getIDLName(); + } + return new StaticStringsHash(methodNames); + } + return null; + } + + static boolean needNewReadStreamClass(Type type) { + if (type.isType(TYPE_ABSTRACT)) { + return true; + } + // Handle late-breaking special case for + // abstract IDL entities... + if ((type instanceof CompoundType) && + ((CompoundType)type).isAbstractBase()) { + return true; + } + return needNewWriteStreamClass(type); + } + + static boolean needNewWriteStreamClass(Type type) { + switch (type.getTypeCode()) { + case TYPE_VOID: + case TYPE_BOOLEAN: + case TYPE_BYTE: + case TYPE_CHAR: + case TYPE_SHORT: + case TYPE_INT: + case TYPE_LONG: + case TYPE_FLOAT: + case TYPE_DOUBLE: return false; + + case TYPE_STRING: return true; + case TYPE_ANY: return false; + case TYPE_CORBA_OBJECT: return false; + case TYPE_REMOTE: return false; + case TYPE_ABSTRACT: return false; + case TYPE_NC_INTERFACE: return true; + case TYPE_VALUE: return true; + case TYPE_IMPLEMENTATION: return true; + case TYPE_NC_CLASS: return true; + case TYPE_ARRAY: return true; + case TYPE_JAVA_RMI_REMOTE: return false; + + default: throw new Error("unexpected type code: " + type.getTypeCode()); + } + } + + /* + * Decide which arguments need to be copied and write + * the copy code. Returns an array of argument names to + * use to refer to either the copy or the original. + */ + String[] writeCopyArguments(CompoundType.Method method, + IndentingWriter p) throws IOException { + + Type[] args = method.getArguments(); + String[] origNames = method.getArgumentNames(); + + // Copy the current parameter names to a result array... + + String[] result = new String[origNames.length]; + for (int i = 0; i < result.length; i++) { + result[i] = origNames[i]; + } + + // Decide which arguments must be copied, if any. If + // any of the arguments are types for which a 'real' copy + // will be done, rather than just an autoConnect, set + // realCopy = true. Note that abstract types may only + // need autoConnect, but we cannot know that at compile + // time... + + boolean realCopy = false; + boolean[] copyArg = new boolean[args.length]; + int copyCount = 0; + int firstCopiedArg = 0; // Only used in single copy case. It is only the first arg that + // needs copying IF copyCount == 1. + + for (int i = 0; i < args.length; i++) { + if (mustCopy(args[i])) { + copyArg[i] = true; + copyCount++; + firstCopiedArg = i; + if (args[i].getTypeCode() != TYPE_REMOTE && + args[i].getTypeCode() != TYPE_IMPLEMENTATION) { + realCopy = true; + } + } else { + copyArg[i] = false; + } + } + + // Do we have any types which must be copied? + if (copyCount > 0) { + // Yes. Are we only doing the copy to ensure + // that autoConnect occurs? + if (realCopy) { + // Nope. We need to go back thru the list and + // mark any strings so that they will be copied + // to preserve any shared references... + for (int i = 0; i < args.length; i++) { + if (args[i].getTypeCode() == TYPE_STRING) { + copyArg[i] = true; + copyCount++; + } + } + } + + // We're ready to generate code. Do we have more than + // one to copy? + if (copyCount > 1) { + // Generate a call to copyObjects... + String arrayName = getVariableName("copies"); + p.p("Object[] " + arrayName + " = Util.copyObjects(new Object[]{"); + boolean first = true; + for (int i = 0; i < args.length; i++) { + if (copyArg[i]) { + if (!first) { + p.p(","); + } + first = false; + p.p(origNames[i]); + } + } + p.pln("},_orb());"); + + // For each of the types which was copied, create + // a local temporary for it, updating the result + // array with the new local parameter name... + int copyIndex = 0 ; + for (int i = 0; i < args.length; i++) { + if (copyArg[i]) { + result[i] = getVariableName(result[i]+"Copy"); + p.pln( getName(args[i]) + " " + result[i] + " = (" + getName(args[i]) + ") " + + arrayName + "[" + copyIndex++ +"];"); + } + } + } else { + // Generate a call to copyObject, updating the result + // with the new local parameter name... + result[firstCopiedArg] = getVariableName(result[firstCopiedArg]+"Copy"); + p.pln( getName(args[firstCopiedArg]) + " " + result[firstCopiedArg] + " = (" + + getName(args[firstCopiedArg]) + ") Util.copyObject(" + + origNames[firstCopiedArg] + ",_orb());"); + } + } + + return result; + } + + static final String SINGLE_SLASH = "\\"; + static final String DOUBLE_SLASH = SINGLE_SLASH + SINGLE_SLASH; + + String getRepositoryID(Type type) { + return IDLNames.replace(type.getRepositoryID(), SINGLE_SLASH, DOUBLE_SLASH); + } + + String getExceptionRepositoryID(Type type) { + ClassType theType = (ClassType) type; + return IDLNames.getIDLRepositoryID(theType.getQualifiedIDLExceptionName(false)); + } + + String getVariableName(String proposed) { + while (namesInUse.contains(proposed)) { + proposed = "$" + proposed; + } + + return proposed; + } + + void addNamesInUse(CompoundType.Method[] methods) { + for (int i = 0; i < methods.length; i++) { + addNamesInUse(methods[i]); + } + } + + void addNamesInUse(CompoundType.Method method) { + String paramNames[] = method.getArgumentNames(); + for (int i = 0; i < paramNames.length; i++) { + addNameInUse(paramNames[i]); + } + } + + void addNameInUse(String name) { + namesInUse.add(name); + } + + static boolean mustCopy(Type type) { + switch (type.getTypeCode()) { + case TYPE_VOID: + case TYPE_BOOLEAN: + case TYPE_BYTE: + case TYPE_CHAR: + case TYPE_SHORT: + case TYPE_INT: + case TYPE_LONG: + case TYPE_FLOAT: + case TYPE_DOUBLE: + case TYPE_STRING: return false; + + case TYPE_ANY: return true; + + case TYPE_CORBA_OBJECT: return false; + + case TYPE_REMOTE: + case TYPE_ABSTRACT: + case TYPE_NC_INTERFACE: + case TYPE_VALUE: + case TYPE_IMPLEMENTATION: + case TYPE_NC_CLASS: + case TYPE_ARRAY: + case TYPE_JAVA_RMI_REMOTE: return true; + + default: throw new Error("unexpected type code: " + type.getTypeCode()); + } + } + + ValueType[] getStubExceptions (CompoundType.Method method, boolean sort) { + + ValueType[] list = method.getFilteredStubExceptions(method.getExceptions()); + + // Sort the list so that all org.omg.CORBA.UserException + // subtypes are at the beginning of the list. This ensures + // that the stub will not call read_string() before calling + // XXHelper.read(). + + if (sort) { + Arrays.sort(list,new UserExceptionComparator()); + } + + return list; + } + + ValueType[] getTieExceptions (CompoundType.Method method) { + return method.getUniqueCatchList(method.getImplExceptions()); + } + + void writeTieMethod(IndentingWriter p, CompoundType type, + CompoundType.Method method) throws IOException { + String methodName = method.getName(); + Type paramTypes[] = method.getArguments(); + String paramNames[] = method.getArgumentNames(); + Type returnType = method.getReturnType(); + ValueType[] exceptions = getTieExceptions(method); + String in = getVariableName("in"); + String ex = getVariableName("ex"); + String out = getVariableName("out"); + String reply = getVariableName("reply"); + + for (int i = 0; i < paramTypes.length; i++) { + p.p(getName(paramTypes[i])+" "+paramNames[i]+" = "); + writeUnmarshalArgument(p, in, paramTypes[i], null); + p.pln(); + } + + boolean handleExceptions = exceptions != null; + boolean doReturn = !returnType.isType(TYPE_VOID); + + if (handleExceptions && doReturn) { + String objName = testUtil(getName(returnType), returnType); + p.pln(objName+" result;"); + } + + if (handleExceptions) + p.plnI("try {"); + + if (doReturn) { + if (handleExceptions) { + p.p("result = "); + } else { + p.p(getName(returnType)+" result = "); + } + } + + p.p("target."+methodName+"("); + for(int i = 0; i < paramNames.length; i++) { + if (i > 0) + p.p(", "); + p.p(paramNames[i]); + } + p.pln(");"); + + if (handleExceptions) { + for(int i = 0; i < exceptions.length; i++) { + p.pOlnI("} catch ("+getName(exceptions[i])+" "+ex+") {"); + + // Is this our IDLEntity Exception special case? + + if (exceptions[i].isIDLEntityException() && !exceptions[i].isCORBAUserException()) { + + // Yes... + + String helperName = IDLNames.replace(exceptions[i].getQualifiedIDLName(false),"::","."); + helperName += "Helper"; + p.pln(idOutputStream+" "+out +" = "+reply+".createExceptionReply();"); + p.pln(helperName+".write("+out+","+ex+");"); + + } else { + + // No... + + p.pln("String id = \"" + getExceptionRepositoryID(exceptions[i]) + "\";"); + p.plnI(idExtOutputStream + " "+out+" = "); + p.pln("(" + idExtOutputStream + ") "+reply+".createExceptionReply();"); + p.pOln(out+".write_string(id);"); + p.pln(out+".write_value("+ex+"," + getName(exceptions[i]) + ".class);"); + } + + p.pln("return "+out+";"); + } + p.pOln("}"); + } + + if (needNewWriteStreamClass(returnType)) { + p.plnI(idExtOutputStream + " "+out+" = "); + p.pln("(" + idExtOutputStream + ") "+reply+".createReply();"); + p.pO(); + } else { + p.pln("OutputStream "+out+" = "+reply+".createReply();"); + } + + if (doReturn) { + writeMarshalArgument(p, out, returnType, "result"); + p.pln(); + } + + p.pln("return "+out+";"); + } + + + /** + * Write Java statements to marshal a series of values in order as + * named in the "names" array, with types as specified in the "types" + * array", to the java.io.ObjectOutput stream named "stream". + */ + void writeMarshalArguments(IndentingWriter p, + String streamName, + Type[] types, String[] names) + throws IOException + { + if (types.length != names.length) { + throw new Error("paramter type and name arrays different sizes"); + } + + for (int i = 0; i < types.length; i++) { + writeMarshalArgument(p, streamName, types[i], names[i]); + if (i != types.length -1) { + p.pln(); + } + } + } + + /** + * Added for IASRI 4987274. Remote classes named "Util" were + * getting confused with javax.rmi.CORBA.Util and the + * unqualifiedName "Util". + */ + String testUtil(String objectName, Type ttype) { + if (objectName.equals("Util")) { + String correctedName = (String)ttype.getPackageName() + "." + objectName; + return correctedName; + } else { + return objectName; + } + } +} + +class StringComparator implements java.util.Comparator { + public int compare(Object o1, Object o2) { + String s1 = (String)o1; + String s2 = (String)o2; + return s1.compareTo(s2); + } +} + + +class UserExceptionComparator implements java.util.Comparator { + public int compare(Object o1, Object o2) { + ValueType v1 = (ValueType)o1; + ValueType v2 = (ValueType)o2; + int result = 0; + if (isUserException(v1)) { + if (!isUserException(v2)) { + result = -1; + } + } else if (isUserException(v2)) { + if (!isUserException(v1)) { + result = 1; + } + } + return result; + } + + final boolean isUserException(ValueType it) { + return it.isIDLEntityException() && !it.isCORBAUserException(); + } +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/Type.java b/src/share/classes/sun/rmi/rmic/iiop/Type.java new file mode 100644 index 000000000..1e946d15c --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/Type.java @@ -0,0 +1,989 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import java.util.Hashtable; +import java.util.Enumeration; +import java.io.IOException; +import sun.tools.java.ClassDefinition; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.Identifier; +import sun.tools.java.ClassNotFound; +import sun.tools.java.CompilerError; +import sun.rmi.rmic.IndentingWriter; +import java.util.HashSet; +import com.sun.corba.ee.impl.util.RepositoryId; +import sun.rmi.rmic.Names; + +/** + * Type is an abstract base class for a family of types which provide + * conformance checking and name mapping as defined in the "Java to IDL + * Mapping" OMG specification. The family is composed of the following + * fixed set of types: + *

                + *
                + *                                              +- RemoteType <-- AbstractType
                + *                                              | 
                + *                           +- InterfaceType <-+- SpecialInterfaceType                   
                + *         +- PrimitiveType  |                  | 
                + *         |                 |                  +- NCInterfaceType
                + *  Type <-+- CompoundType <-|                  
                + *         |                 |                  +- ValueType
                + *         +- ArrayType      |                  |       
                + *                           +- ClassType <-----+- ImplementationType 
                + *                                              |
                + *                                              +- SpecialClassType
                + *                                              |
                + *                                              +- NCClassType
                + *                                              
                + * 
                + * PrimitiveType represents a primitive or a void type. + *

                + * CompoundType is an abstract base representing any non-special class + * or interface type. + *

                + * InterfaceType is an abstract base representing any non-special + * interface type. + *

                + * RemoteType represents any non-special interface which inherits + * from java.rmi.Remote. + *

                + * AbstractType represents any non-special interface which does not + * inherit from java.rmi.Remote, for which all methods throw RemoteException. + *

                + * SpecialInterfaceType represents any one of the following types: + *

                + *    java.rmi.Remote
                + *    java.io.Serializable
                + *    java.io.Externalizable
                + * 
                + * all of which are treated as special cases. + *

                + * NCInterfaceType represents any non-special, non-conforming interface. + *

                + * ClassType is an abstract base representing any non-special class + * type. + *

                + * ValueType represents any non-special class which does inherit from + * java.io.Serializable and does not inherit from java.rmi.Remote. + *

                + * ImplementationType represents any non-special class which implements + * one or more interfaces which inherit from java.rmi.Remote. + *

                + * SpecialClassType represents any one of the following types: + *

                + *    java.lang.Object
                + *    java.lang.String
                + *    org.omg.CORBA.Object
                + * 
                + * all of which are treated as special cases. For all but CORBA.Object, + * the type must match exactly. For CORBA.Object, the type must either be + * CORBA.Object or inherit from it. + *

                + * NCClassType represents any non-special, non-conforming class. + *

                + * ArrayType is a wrapper for any of the other types. The getElementType() + * method can be used to get the array element type. The getArrayDimension() + * method can be used to get the array dimension. + *

                + * NOTE:<\strong> None of these types is multi-thread-safe<\i> + * @version 1.0, 2/25/98 + * @author Bryan Atsatt + */ +public abstract class Type implements sun.rmi.rmic.iiop.Constants, ContextElement, Cloneable { + + private int typeCode; + private int fullTypeCode; + private Identifier id; + + private String name; + private String packageName; + private String qualifiedName; + + private String idlName; + private String[] idlModuleNames; + private String qualifiedIDLName; + + private String repositoryID; + private Class ourClass; + + private int status = STATUS_PENDING; + + protected BatchEnvironment env; // Easy access for subclasses. + protected ContextStack stack; // Easy access for subclasses. + + protected boolean destroyed = false; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Return the unqualified name for this type (e.g. com.acme.Dynamite would + * return "Dynamite"). + */ + public String getName() { + return name; + } + + /** + * Return the package of this type (e.g. com.acme.Dynamite would + * return "com.acme"). Will return null if default package or + * if this type is a primitive. + */ + public String getPackageName() { + return packageName; + } + + /** + * Return the fully qualified name of this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite") + */ + public String getQualifiedName() { + return qualifiedName; + } + + /** + * Return signature for this type (e.g. com.acme.Dynamite + * would return "com.acme.Dynamite", byte = "B") + */ + public abstract String getSignature(); + + /** + * IDL_Naming + * Return the unqualified IDL name of this type (e.g. com.acme.Dynamite would + * return "Dynamite"). + */ + public String getIDLName() { + return idlName; + } + + /** + * IDL_Naming + * Return the IDL module name for this type (e.g. com.acme.Dynamite would return + * a three element array of {"com","acme"). May be a zero length array if + * there is no module name. + */ + public String[] getIDLModuleNames() { + return idlModuleNames; + } + + /** + * IDL_Naming + * Return the fully qualified IDL name for this type (e.g. com.acme.Dynamite would + * return "com::acme::Dynamite"). + * @param global If true, prepends "::". + */ + public String getQualifiedIDLName(boolean global) { + if (global && getIDLModuleNames().length > 0) { + return IDL_NAME_SEPARATOR + qualifiedIDLName; + } else { + return qualifiedIDLName; + } + } + + /** + * Return the identifier for this type. May be qualified. + */ + public Identifier getIdentifier() { + return id; + } + + /** + * Return the repository ID for this type. + */ + public String getRepositoryID() { + return repositoryID; + } + + /** + * Return the repository ID for this "boxed" type. + */ + public String getBoxedRepositoryID() { + return RepositoryId.createForJavaType(ourClass); + } + + /** + * Return the Class for this type. + */ + public Class getClassInstance() { + if (ourClass == null) { + initClass(); + } + return ourClass; + } + + /** + * Return the status of this type. + */ + public int getStatus() { + return status; + } + + /** + * Set the status of this type. + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * Return the compiler environment for this type. + */ + public BatchEnvironment getEnv() { + return env; + } + + /** + * Get type code, without modifiers. Type codes are defined in sun.rmi.rmic.iiop.Constants. + */ + public int getTypeCode() { + return typeCode; + } + + /** + * Get type code, with modifiers. Type codes are defined in sun.rmi.rmic.iiop.Constants. + */ + public int getFullTypeCode() { + return fullTypeCode; + } + + /** + * Get type code modifiers. Type codes are defined in sun.rmi.rmic.iiop.Constants. + */ + public int getTypeCodeModifiers() { + return fullTypeCode & TM_MASK; + } + + /** + * Check for a certain type. Type codes are defined in sun.rmi.rmic.iiop.Constants. + * Returns true if all of the bits in typeCodeMask are present in the full type code + * of this object. + */ + public boolean isType(int typeCodeMask) { + return (fullTypeCode & typeCodeMask) == typeCodeMask; + } + + /** + * Like isType(), but returns true if any of the bits in typeCodeMask are + * present in the full type code of this object. + */ + public boolean typeMatches(int typeCodeMask) { + return (fullTypeCode & typeCodeMask) > 0; + } + + + /** + * Return the fullTypeCode. If an array, returns the + * type code from the element type. + */ + public int getRootTypeCode() { + if (isArray()) { + return getElementType().getFullTypeCode(); + } else { + return fullTypeCode; + } + } + + /** + * Return true if this type is-a InterfaceType. + */ + public boolean isInterface() { + return (fullTypeCode & TM_INTERFACE) == TM_INTERFACE; + } + + /** + * Return true if this type is-a ClassType. + */ + public boolean isClass() { + return (fullTypeCode & TM_CLASS) == TM_CLASS; + } + + /** + * Return true if this type is-a inner class or interface. + */ + public boolean isInner() { + return (fullTypeCode & TM_INNER) == TM_INNER; + } + + + /** + * Return true if this type is-a SpecialInterfaceType. + */ + public boolean isSpecialInterface() { + return (fullTypeCode & TM_SPECIAL_INTERFACE) == TM_SPECIAL_INTERFACE; + } + + /** + * Return true if this type is-a SpecialClassType. + */ + public boolean isSpecialClass() { + return (fullTypeCode & TM_SPECIAL_CLASS) == TM_SPECIAL_CLASS; + } + + /** + * Return true if this type is-a CompoundType. + */ + public boolean isCompound() { + return (fullTypeCode & TM_COMPOUND) == TM_COMPOUND; + } + + /** + * Return true if this type is-a PrimitiveType. + */ + public boolean isPrimitive() { + return (fullTypeCode & TM_PRIMITIVE) == TM_PRIMITIVE; + } + + /** + * Return true if this type is-a ArrayType. + */ + public boolean isArray() { + return (fullTypeCode & TYPE_ARRAY) == TYPE_ARRAY; + } + + /** + * Return true if this type is a conforming type. + */ + public boolean isConforming() { + return (fullTypeCode & TM_NON_CONFORMING) == TM_NON_CONFORMING; + } + + /** + * Return a string representation of this type. + */ + public String toString () { + return getQualifiedName(); + } + + /** + * Get element type. Returns null if not an array. + */ + public Type getElementType () { + return null; + } + + /** + * Get array dimension. Returns zero if not an array. + */ + public int getArrayDimension () { + return 0; + } + + /** + * Get brackets string. Returns "" if not an array. + */ + public String getArrayBrackets () { + return ""; + } + + /** + * Equality check based on the string representation. + */ + public boolean equals(Object obj) { + + String us = toString(); + String them = ((Type)obj).toString(); + return us.equals(them); + } + + /** + * Collect all the matching types referenced directly or indirectly + * by this type, including itself. + * @param typeCodeFilter The typeCode to use as a filter. + */ + public Type[] collectMatching (int typeCodeFilter) { + return collectMatching(typeCodeFilter,new HashSet(env.allTypes.size())); + } + + /** + * Collect all the matching types referenced directly or indirectly + * by this type, including itself. + * @param typeCodeFilter The typeCode to use as a filter. + * @param alreadyChecked Contains types which have previously been checked + * and will be ignored. Updated during collection. + */ + public Type[] collectMatching (int typeCodeFilter, HashSet alreadyChecked) { + Vector matching = new Vector(); + + // Fill up the list... + + addTypes(typeCodeFilter,alreadyChecked,matching); + + // Copy vector contents to array and return it... + + Type[] result = new Type[matching.size()]; + matching.copyInto(result); + + return result; + } + + /** + * Return a string describing this type. + */ + public abstract String getTypeDescription (); + + /** + * Return the name of this type. For arrays, will include "[]" if useIDLNames == false. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public String getTypeName ( boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) { + if (useIDLNames) { + if (useQualifiedNames) { + return getQualifiedIDLName(globalIDLNames); + } else { + return getIDLName(); + } + } else { + if (useQualifiedNames) { + return getQualifiedName(); + } else { + return getName(); + } + } + } + + /** + * Print all types referenced directly or indirectly by this type which + * match the filter. + * @param writer The stream to print to. + * @param typeCodeFilter The type codes to print. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + int typeCodeFilter, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + Type[] theTypes = collectMatching(typeCodeFilter); + print(writer,theTypes,useQualifiedNames,useIDLNames,globalIDLNames); + } + + /** + * Print an array of types. + * @param writer The stream to print to. + * @param theTypes The types to print. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public static void print ( IndentingWriter writer, + Type[] theTypes, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + for (int i = 0; i < theTypes.length; i++) { + theTypes[i].println(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + } + + + /** + * Print this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void print ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + printTypeName(writer,useQualifiedNames,useIDLNames,globalIDLNames); + } + + /** + * Print this type, followed by a newline. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void println ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + print(writer,useQualifiedNames,useIDLNames,globalIDLNames); + writer.pln(); + } + + + + /** + * Print the name of this type. + * @param writer The stream to print to. + * @param useQualifiedNames If true, print qualified names; otherwise, print unqualified names. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + * @param globalIDLNames If true and useIDLNames true, prepends "::". + */ + public void printTypeName ( IndentingWriter writer, + boolean useQualifiedNames, + boolean useIDLNames, + boolean globalIDLNames) throws IOException { + + writer.p(getTypeName(useQualifiedNames,useIDLNames,globalIDLNames)); + } + + /** + * Return context element name. + */ + public String getElementName() { + return getQualifiedName(); + } + + //_____________________________________________________________________ + // Subclass Interfaces + //_____________________________________________________________________ + + /** + * Print the "opening" of the package or module of this type. + * @param writer The stream to print to. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + */ + protected void printPackageOpen ( IndentingWriter writer, + boolean useIDLNames) throws IOException { + + if (useIDLNames) { + String[] moduleNames = getIDLModuleNames(); + for (int i = 0; i < moduleNames.length; i++ ) { + writer.plnI("module " + moduleNames[i] + " {"); + } + } else { + String packageName = getPackageName(); + if (packageName != null) { + writer.pln("package " + packageName + ";"); + } + } + } + + /** + * Get a type out of the table. + */ + protected static Type getType (sun.tools.java.Type key, ContextStack stack) { + return getType(key.toString(),stack); + } + + /** + * Get a type out of the table. + */ + protected static Type getType (String key, ContextStack stack) { + Type result = (Type) stack.getEnv().allTypes.get(key); + + if (result != null) { + stack.traceExistingType(result); + } + + return result; + } + + /** + * Remove a type from the table. + */ + protected static void removeType (String key, ContextStack stack) { + Type value = (Type) stack.getEnv().allTypes.remove(key); + stack.getEnv().invalidTypes.put(value,key); + } + + /** + * Remove a type from the table. + */ + protected static void removeType (sun.tools.java.Type key, ContextStack stack) { + String theKey = key.toString(); + Type old = (Type) stack.getEnv().allTypes.remove(theKey); + putInvalidType(old,theKey,stack); + } + + /** + * Put a type into the table. + */ + protected static void putType (sun.tools.java.Type key, Type value, ContextStack stack) { + stack.getEnv().allTypes.put(key.toString(),value); + } + + /** + * Put a type into the table. + */ + protected static void putType (String key, Type value, ContextStack stack) { + stack.getEnv().allTypes.put(key,value); + } + + /** + * Put an invalid type into the. + */ + protected static void putInvalidType (Type key, String value, ContextStack stack) { + stack.getEnv().invalidTypes.put(key,value); + } + + + /** + * Remove all invalid types... + */ + public void removeInvalidTypes () { + if (env.invalidTypes.size() > 0) { + env.invalidTypes.clear(); + } + } + + /** + * Walk all types and tell them to update invalid types... + */ + protected static void updateAllInvalidTypes (ContextStack stack) { + BatchEnvironment env = stack.getEnv(); + if (env.invalidTypes.size() > 0) { + + // Walk all types and swap invalid... + + for (Enumeration e = env.allTypes.elements() ; e.hasMoreElements() ;) { + Type it = (Type) e.nextElement(); + it.swapInvalidTypes(); + } + + // Delete all invalidTypes... + + env.invalidTypes.clear(); + } + } + + /** + * Return count of previously parsed types. + */ + protected int countTypes () { + return env.allTypes.size(); + } + + /** + * Reset types removes all previously parsed types. + */ + void resetTypes () { + env.reset(); + } + + /** + * Release all resources. + */ + protected void destroy () { + if (!destroyed) { + id = null; + name = null; + packageName = null; + qualifiedName = null; + idlName = null; + idlModuleNames = null; + qualifiedIDLName = null; + repositoryID = null; + ourClass = null; + env = null; + stack = null; + destroyed = true; + } + } + + /** + * Convert all invalid types to valid ones. + */ + protected void swapInvalidTypes () { + } + + /** + * Convert an invalid type to a valid one. + */ + protected Type getValidType (Type invalidType) { + if (invalidType.getStatus() == STATUS_VALID) { + return invalidType; + } + + String key = (String)env.invalidTypes.get(invalidType); + Type result = null; + if (key != null) { + result = (Type) env.allTypes.get(key); + } + + if (result == null) { + throw new Error("Failed to find valid type to swap for " + invalidType + " mis-identified as " + invalidType.getTypeDescription()); + } + //System.out.println("Swapped " + result + " from " + invalidType.getTypeDescription() + // + " to " + result.getTypeDescription()); + //ContextStack.dumpCallStack(); + return result; + } + + /** + * Print the "closing" of the package or module of this type. + * @param writer The stream to print to. + * @param useIDLNames If true, print IDL names; otherwise, print java names. + */ + protected void printPackageClose ( IndentingWriter writer, + boolean useIDLNames) throws IOException { + if (useIDLNames) { + String[] moduleNames = getIDLModuleNames(); + for (int i = 0; i < moduleNames.length; i++ ) { + writer.pOln("};"); + } + } + } + + /** + * Create a Type instance for the given type. Requires that + * setName(Identifier) be called afterward. + */ + protected Type(ContextStack stack, int fullTypeCode) { + this.env = stack.getEnv(); + this.stack = stack; + this.fullTypeCode = fullTypeCode; + typeCode = fullTypeCode & TYPE_MASK; + } + + /** + * Set type codes. May only be called during initialization. + */ + protected void setTypeCode(int fullTypeCode) { + this.fullTypeCode = fullTypeCode; + typeCode = fullTypeCode & TYPE_MASK; + } + + /** + * Set name and package. May only be called during initialization. + */ + protected void setNames(Identifier id, String[] idlModuleNames, String idlName) { + + this.id = id; + name = Names.mangleClass(id).getName().toString(); + packageName = null; + + if (id.isQualified()) { + packageName = id.getQualifier().toString(); + qualifiedName = packageName + NAME_SEPARATOR + name; + } else { + qualifiedName = name; + } + + setIDLNames(idlModuleNames,idlName); + } + + + /** + * Set IDL name. May only be called during initialization. + */ + protected void setIDLNames(String[] idlModuleNames, String idlName) { + this.idlName = idlName; + + if (idlModuleNames != null) { + this.idlModuleNames = idlModuleNames; + } else { + this.idlModuleNames = new String[0]; + } + qualifiedIDLName = IDLNames.getQualifiedName(idlModuleNames,idlName); + } + + /** + * Report a ClassNotFoundException thru the compiler environment. + */ + protected static void classNotFound(ContextStack stack, + ClassNotFound e) { + classNotFound(false,stack,e); + } + + /** + * Report a ClassNotFoundException thru the compiler environment. + */ + protected static void classNotFound(boolean quiet, + ContextStack stack, + ClassNotFound e) { + if (!quiet) stack.getEnv().error(0, "rmic.class.not.found", e.name); + stack.traceCallStack(); + } + + /** + * Report a constraint failure thru the compiler environment. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param arg0 An object to substitute for {0} in the message. + * @param arg1 An object to substitute for {1} in the message. + * @param arg2 An object to substitute for {2} in the message. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack, + Object arg0, Object arg1, Object arg2) { + String message = "rmic.iiop.constraint." + constraintNum; + + if (!quiet) { + stack.getEnv().error(0,message, + (arg0 != null ? arg0.toString() : null), + (arg1 != null ? arg1.toString() : null), + (arg2 != null ? arg2.toString() : null)); + } else { + String error = stack.getEnv().errorString(message,arg0,arg1,arg2); + stack.traceln(error); + } + + return false; + } + + /** + * Report a constraint failure thru the compiler environment. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param arg0 An object to substitute for {0} in the message. + * @param arg1 An object to substitute for {1} in the message. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack, + Object arg0, Object arg1) { + return failedConstraint(constraintNum,quiet,stack,arg0,arg1,null); + } + + + /** + * Report a constraint failure thru the compiler environment. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param arg0 An object to substitute for {0} in the message. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack, + Object arg0) { + return failedConstraint(constraintNum,quiet,stack,arg0,null,null); + } + + /** + * Report a constraint failure thru the compiler environment. + * @param quiet True if should not cause failure or message. + * @param stack The context stack. + * @param constraintNum Used to generate a key of the form + "rmic.iiop.constraint.N", which must identify a message + in the "rmic.properties" file. + * @return false. + */ + protected static boolean failedConstraint(int constraintNum, + boolean quiet, + ContextStack stack) { + return failedConstraint(constraintNum,quiet,stack,null,null,null); + } + + /** + * Cloning is supported by returning a shallow copy of this object. + */ + protected Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error("clone failed"); + } + } + + /* + * Add matching types to list. Return true if this type has not + * been previously checked, false otherwise. + */ + protected boolean addTypes (int typeCodeFilter, + HashSet checked, + Vector matching) { + + boolean result; + + // Have we already checked this type? + + if (checked.contains(this)) { + + // Yes, so return false. + + result = false; + + } else { + + // Nope, so add it... + + checked.add(this); + + // Do we match the filter? + + if (typeMatches(typeCodeFilter)) { + + // Yep. so add it and set result to true... + + matching.addElement(this); + } + + // Return true. + + result = true; + } + + return result; + } + + /* + * Load a Class instance. Return null if fail. + */ + protected abstract Class loadClass(); + + private boolean initClass() { + if (ourClass == null) { + ourClass = loadClass(); + if (ourClass == null) { + failedConstraint(27,false,stack,getQualifiedName()); + return false; + } + } + return true; + } + + /* + * Set the clz and repositoryID fields. Reports error + * and returns false if fails, returns true if succeeds. + */ + protected boolean setRepositoryID() { + + // First, load the class... + + if (!initClass()) { + return false; + } + + // Now make the repositoryID and return success... + + repositoryID = RepositoryId.createForAnyType(ourClass); + return true; + } + + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + private Type () {} // Disallowed. +} diff --git a/src/share/classes/sun/rmi/rmic/iiop/Util.java b/src/share/classes/sun/rmi/rmic/iiop/Util.java new file mode 100644 index 000000000..25a336ed3 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/Util.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.io.File; +import sun.tools.java.Identifier; + +import com.sun.corba.ee.impl.util.PackagePrefixChecker; + +/** + * Util provides static utility methods used by other rmic classes. + * @author Bryan Atsatt + */ + +public final class Util implements sun.rmi.rmic.Constants { + + + public static String packagePrefix(){ return PackagePrefixChecker.packagePrefix();} + + + /** + * Return the directory that should be used for output for a given + * class. + * @param theClass The fully qualified name of the class. + * @param rootDir The directory to use as the root of the + * package heirarchy. May be null, in which case the current + * working directory is used as the root. + */ + private static File getOutputDirectoryFor(Identifier theClass, + File rootDir, + BatchEnvironment env, + boolean idl ) { + File outputDir = null; + String className = theClass.getFlatName().toString().replace('.', SIGC_INNERCLASS); + String qualifiedClassName = className; + String packagePath = null; + String packageName = theClass.getQualifier().toString(); + //Shift package names for stubs generated for interfaces. + /*if(type.isInterface())*/ + packageName = + correctPackageName(packageName, idl, env.getStandardPackage()); + //Done. + if (packageName.length() > 0) { + qualifiedClassName = packageName + "." + className; + packagePath = packageName.replace('.', File.separatorChar); + } + + // Do we have a root directory? + + if (rootDir != null) { + + // Yes, do we have a package name? + + if (packagePath != null) { + + // Yes, so use it as the root. Open the directory... + + outputDir = new File(rootDir, packagePath); + + // Make sure the directory exists... + + ensureDirectory(outputDir,env); + + } else { + + // Default package, so use root as output dir... + + outputDir = rootDir; + } + } else { + + // No root directory. Get the current working directory... + + String workingDirPath = System.getProperty("user.dir"); + File workingDir = new File(workingDirPath); + + // Do we have a package name? + + if (packagePath == null) { + + // No, so use working directory... + + outputDir = workingDir; + + } else { + + // Yes, so use working directory as the root... + + outputDir = new File(workingDir, packagePath); + + // Make sure the directory exists... + + ensureDirectory(outputDir,env); + } + } + + // Finally, return the directory... + + return outputDir; + } + + public static File getOutputDirectoryForIDL(Identifier theClass, + File rootDir, + BatchEnvironment env) { + return getOutputDirectoryFor(theClass, rootDir, env, true); + } + + public static File getOutputDirectoryForStub(Identifier theClass, + File rootDir, + BatchEnvironment env) { + return getOutputDirectoryFor(theClass, rootDir, env, false); + } + + private static void ensureDirectory (File dir, BatchEnvironment env) { + if (!dir.exists()) { + dir.mkdirs(); + if (!dir.exists()) { + env.error(0,"rmic.cannot.create.dir",dir.getAbsolutePath()); + throw new InternalError(); + } + } + } + + public static String correctPackageName( + String p, boolean idl, boolean standardPackage){ + if (idl){ + return p; + } else { + if (standardPackage) { + return p; + } else { + return PackagePrefixChecker.correctPackageName(p); + } + } + } + + public static boolean isOffendingPackage(String p){ + return PackagePrefixChecker.isOffendingPackage(p); + } + + public static boolean hasOffendingPrefix(String p){ + return PackagePrefixChecker.hasOffendingPrefix(p); + } + +} + + + diff --git a/src/share/classes/sun/rmi/rmic/iiop/ValueType.java b/src/share/classes/sun/rmi/rmic/iiop/ValueType.java new file mode 100644 index 000000000..0d256d13f --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/iiop/ValueType.java @@ -0,0 +1,469 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package sun.rmi.rmic.iiop; + +import java.util.Vector; +import sun.tools.java.ClassNotFound; +import sun.tools.java.ClassDeclaration; +import sun.tools.java.ClassDefinition; +import sun.tools.java.MemberDefinition; +import java.util.Hashtable; +import java.io.ObjectStreamClass; +import java.io.ObjectStreamField; + + +/** + * ValueType represents any non-special class which does inherit from + * java.io.Serializable and does not inherit from java.rmi.Remote. + *

                + * The static forValue(...) method must be used to obtain an instance, and + * will return null if the ClassDefinition is non-conforming. + * + * @version 1.0, 2/27/98 + * @author Bryan Atsatt + */ +public class ValueType extends ClassType { + + private boolean isCustom; + + //_____________________________________________________________________ + // Public Interfaces + //_____________________________________________________________________ + + /** + * Create an ValueType object for the given class. + * + * If the class is not a properly formed or if some other error occurs, the + * return value will be null, and errors will have been reported to the + * supplied BatchEnvironment. + */ + public static ValueType forValue(ClassDefinition classDef, + ContextStack stack, + boolean quiet) { + + if (stack.anyErrors()) return null; + + // Do we already have it? + + sun.tools.java.Type theType = classDef.getType(); + String typeKey = theType.toString(); + Type existing = getType(typeKey,stack); + + if (existing != null) { + + if (!(existing instanceof ValueType)) return null; // False hit. + + // Yep, so return it... + + return (ValueType) existing; + } + + // Is this java.lang.Class? + + boolean javaLangClass = false; + + if (classDef.getClassDeclaration().getName() == idJavaLangClass) { + + // Yes, so replace classDef with one for + // javax.rmi.CORBA.ClassDesc... + + javaLangClass = true; + BatchEnvironment env = stack.getEnv(); + ClassDeclaration decl = env.getClassDeclaration(idClassDesc); + ClassDefinition def = null; + + try { + def = decl.getClassDefinition(env); + } catch (ClassNotFound ex) { + classNotFound(stack,ex); + return null; + } + + classDef = def; + } + + // Could this be a value? + + if (couldBeValue(stack,classDef)) { + + // Yes, so check it... + + ValueType it = new ValueType(classDef,stack,javaLangClass); + putType(typeKey,it,stack); + stack.push(it); + + if (it.initialize(stack,quiet)) { + stack.pop(true); + return it; + } else { + removeType(typeKey,stack); + stack.pop(false); + return null; + } + } else { + return null; + } + } + + + /** + * Return a string describing this type. + */ + public String getTypeDescription () { + String result = addExceptionDescription("Value"); + if (isCustom) { + result = "Custom " + result; + } + if (isIDLEntity) { + result = result + " [IDLEntity]"; + } + return result; + } + + /** + * Return true if this type is a "custom" type (i.e. + * it implements java.io.Externalizable or has a + * method with the following signature: + * + * private void writeObject(java.io.ObjectOutputStream out); + * + */ + public boolean isCustom () { + return isCustom; + } + + + //_____________________________________________________________________ + // Subclass/Internal Interfaces + //_____________________________________________________________________ + + /** + * Create a ValueType instance for the given class. The resulting + * object is not yet completely initialized. + */ + private ValueType(ClassDefinition classDef, + ContextStack stack, + boolean isMappedJavaLangClass) { + super(stack,classDef,TYPE_VALUE | TM_CLASS | TM_COMPOUND); + isCustom = false; + + // If this is the mapped version of java.lang.Class, + // set the non-IDL names back to java.lang.Class... + + if (isMappedJavaLangClass) { + setNames(idJavaLangClass,IDL_CLASS_MODULE,IDL_CLASS); + } + } + + //_____________________________________________________________________ + // Internal Interfaces + //_____________________________________________________________________ + + /** + * Initialize this instance. + */ + + private static boolean couldBeValue(ContextStack stack, ClassDefinition classDef) { + + boolean result = false; + ClassDeclaration classDecl = classDef.getClassDeclaration(); + BatchEnvironment env = stack.getEnv(); + + try { + // Make sure it's not remote... + + if (env.defRemote.implementedBy(env, classDecl)) { + failedConstraint(10,false,stack,classDef.getName()); + } else { + + // Make sure it's Serializable... + + if (!env.defSerializable.implementedBy(env, classDecl)) { + failedConstraint(11,false,stack,classDef.getName()); + } else { + result = true; + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return result; + } + + /** + * Initialize this instance. + */ + private boolean initialize (ContextStack stack, boolean quiet) { + + ClassDefinition ourDef = getClassDefinition(); + ClassDeclaration ourDecl = getClassDeclaration(); + + try { + + // Make sure our parentage is ok... + + if (!initParents(stack)) { + failedConstraint(12,quiet,stack,getQualifiedName()); + return false; + } + + + // We're ok, so make up our collections... + + Vector directInterfaces = new Vector(); + Vector directMethods = new Vector(); + Vector directMembers = new Vector(); + + // Get interfaces... + + if (addNonRemoteInterfaces(directInterfaces,stack) != null) { + + // Get methods... + + if (addAllMethods(ourDef,directMethods,false,false,stack) != null) { + + // Update parent class methods + if (updateParentClassMethods(ourDef,directMethods,false,stack) != null) { + + // Get constants and members... + + if (addAllMembers(directMembers,false,false,stack)) { + + // We're ok, so pass 'em up... + + if (!initialize(directInterfaces,directMethods,directMembers,stack,quiet)) { + return false; + } + + // Is this class Externalizable? + + boolean externalizable = false; + if (!env.defExternalizable.implementedBy(env, ourDecl)) { + + // No, so check to see if we have a serialPersistentField + // that will modify the members. + + if (!checkPersistentFields(getClassInstance(),quiet)) { + return false; + } + } else { + + // Yes. + + externalizable = true; + } + + // Should this class be considered "custom"? It is if + // it is Externalizable OR if it has a method with the + // following signature: + // + // private void writeObject(java.io.ObjectOutputStream out); + // + + if (externalizable) { + isCustom = true; + } else { + for (MemberDefinition member = ourDef.getFirstMember(); + member != null; + member = member.getNextMember()) { + + if (member.isMethod() && + !member.isInitializer() && + member.isPrivate() && + member.getName().toString().equals("writeObject")) { + + // Check return type, arguments and exceptions... + + sun.tools.java.Type methodType = member.getType(); + sun.tools.java.Type rtnType = methodType.getReturnType(); + + if (rtnType == sun.tools.java.Type.tVoid) { + + // Return type is correct. How about arguments? + + sun.tools.java.Type[] args = methodType.getArgumentTypes(); + if (args.length == 1 && + args[0].getTypeSignature().equals("Ljava/io/ObjectOutputStream;")) { + + // Arguments are correct, so it is a custom + // value type... + + isCustom = true; + } + } + } + } + } + } + + return true; + } + } + } + } catch (ClassNotFound e) { + classNotFound(stack,e); + } + + return false; + } + + + private boolean checkPersistentFields (Class clz, boolean quiet) { + + // Do we have a writeObject method? + + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals("writeObject") && + methods[i].getArguments().length == 1) { + + Type returnType = methods[i].getReturnType(); + Type arg = methods[i].getArguments()[0]; + String id = arg.getQualifiedName(); + + if (returnType.isType(TYPE_VOID) && + id.equals("java.io.ObjectOutputStream")) { + + // Got one, so there's nothing to do... + + return true; + } + } + } + + // Do we have a valid serialPersistentField array? + + MemberDefinition spfDef = null; + + for (int i = 0; i < members.length; i++) { + if (members[i].getName().equals("serialPersistentFields")) { + + Member member = members[i]; + Type type = member.getType(); + Type elementType = type.getElementType(); + + // We have a member with the correct name. Make sure + // we have the correct signature... + + if (elementType != null && + elementType.getQualifiedName().equals( + "java.io.ObjectStreamField") + ) { + + if (member.isStatic() && + member.isFinal() && + member.isPrivate()) { + + // We have the correct signature + + spfDef = member.getMemberDefinition(); + + } else { + + // Bad signature... + + failedConstraint(4,quiet,stack,getQualifiedName()); + return false; + } + } + } + } + + // If we do not have a serialPersistentField, + // there's nothing to do, so return with no error... + + if (spfDef == null) { + return true; + } + + // Ok, now we must examine the contents of the array - + // then validate them... + + Hashtable fields = getPersistentFields(clz); + boolean result = true; + + for (int i = 0; i < members.length; i++) { + String fieldName = members[i].getName(); + String fieldType = members[i].getType().getSignature(); + + // Is this field present in the array? + + String type = (String) fields.get(fieldName); + + if (type == null) { + + // No, so mark it transient... + + members[i].setTransient(); + + } else { + + // Yes, does the type match? + + if (type.equals(fieldType)) { + + // Yes, so remove it from the fields table... + + fields.remove(fieldName); + + } else { + + // No, so error... + + result = false; + failedConstraint(2,quiet,stack,fieldName,getQualifiedName()); + } + } + } + + // Ok, we've checked all of our fields. Are there any left in the "array"? + // If so, it's an error... + + if (result && fields.size() > 0) { + + result = false; + failedConstraint(9,quiet,stack,getQualifiedName()); + } + + // Return result... + + return result; + } + + /** + * Get the names and types of all the persistent fields of a Class. + */ + private Hashtable getPersistentFields (Class clz) { + Hashtable result = new Hashtable(); + ObjectStreamClass osc = ObjectStreamClass.lookup(clz); + if (osc != null) { + ObjectStreamField[] fields = osc.getFields(); + for (int i = 0; i < fields.length; i++) { + String typeSig; + String typePrefix = String.valueOf(fields[i].getTypeCode()); + if (fields[i].isPrimitive()) { + typeSig = typePrefix; + } else { + if (fields[i].getTypeCode() == '[') { + typePrefix = ""; + } + typeSig = typePrefix + fields[i].getType().getName().replace('.','/'); + if (typeSig.endsWith(";")) { + typeSig = typeSig.substring(0,typeSig.length()-1); + } + } + result.put(fields[i].getName(),typeSig); + } + } + return result; + } +} diff --git a/src/share/classes/sun/rmi/rmic/resources/rmic.properties b/src/share/classes/sun/rmi/rmic/resources/rmic.properties new file mode 100644 index 000000000..1a35b63b3 --- /dev/null +++ b/src/share/classes/sun/rmi/rmic/resources/rmic.properties @@ -0,0 +1,198 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1998 IBM Corp. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# To add a generator sun.rmi.rmic.Foo which is invoked via the -foo option: +# +# 1. Add "foo" to generator.args list. +# 2. Add line: generator.class.foo=sun.rmi.rmic.Foo +# 3. Update rmic.usage string to include new arguments. + +# For each available generator, list the command line argument used +# to invoke it. The value can be a single item or a comma separated +# list. + +generator.args=v1.1,vcompat,v1.2,iiop,idl,xprint + +# For each generator, specify the class to invoke, using the following +# syntax: +# +# generator.class.{arg}=fullClassName +# +# The 'default' entry is required and will be used if none of the args +# specified in generator.args is passed. Note that {arg} is compared +# using String.equalsIgnoreCase(). + +generator.class.default=sun.rmi.rmic.RMIGenerator + +generator.class.v1.1=sun.rmi.rmic.RMIGenerator +generator.class.vcompat=sun.rmi.rmic.RMIGenerator +generator.class.v1.2=sun.rmi.rmic.RMIGenerator +generator.class.iiop=sun.rmi.rmic.iiop.StubGenerator +generator.class.idl=sun.rmi.rmic.iiop.IDLGenerator +generator.class.xprint=sun.rmi.rmic.iiop.PrintGenerator + +# If a generator needs a BatchEnvironment other than +# sun.rmi.rmic.BatchEnvironment, specify it as follows: +# +# generator.env.{arg}=fullClassName + +generator.env.iiop=sun.rmi.rmic.iiop.BatchEnvironment +generator.env.idl=sun.rmi.rmic.iiop.BatchEnvironment +generator.env.xprint=sun.rmi.rmic.iiop.BatchEnvironment + +rmic.usage=Usage: {0} \ +\n\ +\nwhere includes:\ +\n -keep Do not delete intermediate generated source files\ +\n -keepgenerated (same as "-keep")\ +\n -v1.1 Create stubs/skeletons for 1.1 stub protocol version\ +\n -vcompat (default) Create stubs/skeletons compatible with both\ +\n 1.1 and 1.2 stub protocol versions\ +\n -v1.2 Create stubs for 1.2 stub protocol version only\ +\n -iiop Create stubs for IIOP. When present, also includes:\ +\n\ +\n -always Create stubs even when they appear current\ +\n -alwaysgenerate (same as "-always")\ +\n -nolocalstubs Do not create stubs optimized for same process\ +\n\ +\n -idl Create IDL. When present, also includes:\ +\n\ +\n -noValueMethods Do not generate methods for valuetypes \ +\n -always Create IDL even when it appears current\ +\n -alwaysgenerate (same as "-always")\ +\n\ +\n -g Generate debugging info\ +\n -depend Recompile out-of-date files recursively\ +\n -nowarn Generate no warnings\ +\n -nowrite Do not write compiled classes to the file system\ +\n -verbose Output messages about what the compiler is doing\ +\n -classpath Specify where to find input class files\ +\n -bootclasspath Override location of bootstrap class files\ +\n -extdirs Override location of installed extensions\ +\n -d Specify where to place generated class files\ +\n -J Pass argument to the java interpreter +\n\ + +# +# Generic Messages +# + +rmic.cant.read=Can''t read: {0} +rmic.option.unsupported=The {0} option is no longer supported. +rmic.option.already.seen=The {0} option may be specified no more than once. +rmic.option.requires.argument=The {0} option requires an argument. +rmic.no.such.directory=The {0} directory does not exist. +rmic.no.such.option={0} is an invalid option or argument. +rmic.wrote=[wrote {0}] +rmic.errors={0} errors +rmic.1error=1 error +rmic.warnings={0} warnings +rmic.1warning=1 warning +rmic.done_in=[done in {0} ms] +rmic.no.memory=\ + The compiler has run out of memory. Consider using the "-J-mx" command line option to increase the maximum heap size. +rmic.stack.overflow=\ + The compiler has run out of stack space. Consider using the "-J-oss" command line option to increase the memory allocated for the Java stack. +rmic.class.not.found=\ + Class {0} not found. +rmic.missing.property=Missing property generator.class.{0} +rmic.cannot.instantiate=Cannot instantiate class {0} +rmic.cannot.use.both=Cannot use both {0} and {1} +rmic.resource.not.found={0} not found. +rmic.no.output.dir=\ + Cannot find suitable output directory for {0}. Use the -d option to specify a root directory. +rmic.cannot.create.dir=\ + Cannot create output directory {0}. + +# +# JRMP Messages +# + +rmic.cant.make.stubs.for.interface=\ + {0} is an interface; stubs are needed only for remote object classes. +rmic.must.implement.remote=\ + Class {0} does not implement an interface that extends java.rmi.Remote; only remote objects need stubs and skeletons. +rmic.must.implement.remote.directly=\ + Stubs are only needed for classes that directly implement an interface that extends java.rmi.Remote; class {0} does not directly implement a remote interface. +rmic.must.throw.remoteexception=\ + {0} is not a valid remote interface: method {1} must throw java.rmi.RemoteException. +rmic.must.only.throw.exception=\ + Method {0} is not a valid remote method implementation because it throws {1}; implementations of remote methods may only throw java.lang.Exception or its subclasses. +warn.rmic.tie.found=\ + An IIOP "tie" exists for class {0}:\ + \n {1}\ + \nIf you use PortableRemoteObject.exportObject, you should remove this file; otherwise, your server object will be exported to IIOP rather than to JRMP. + +# +# RMI-IIOP Messages +# + +rmic.generated=[generated {0} in {1} ms] +rmic.previously.generated=[previously generated file {0} is current] +warn.rmic.member.not.mapped=\ + Data member {0} of class {1} was not mapped to IDL. + +rmic.iiop.constraint.1=\ + {0} is not a valid interface: does not inherit from java.rmi.Remote. +rmic.iiop.constraint.2=\ + serialPersistentFields array of class {0} is invalid: references non-existent members. +rmic.iiop.constraint.3=\ + {0} is not a valid remote interface: {1} is not a valid primitive or String constant. +rmic.iiop.constraint.4=\ + {0} is not a valid value: serialPersistentFields must be private static final. +rmic.iiop.constraint.5=\ + {0} is not a valid remote interface: method {1} must throw RemoteException or a superclass of RemoteException. +rmic.iiop.constraint.6=\ + {0} is not a valid remote interface: inherited interfaces {1} both declare method {2}. +rmic.iiop.constraint.7=\ + {0} is not a valid type: {1} differ only in case. +rmic.iiop.constraint.8=\ + {0} is not a valid remote implementation: has no remote interfaces. +rmic.iiop.constraint.9=\ + serialPersistentFields array member {0} of class {1} is invalid: type does not match declared member. +rmic.iiop.constraint.10=\ + {0} is not a valid value: implements java.rmi.Remote. +rmic.iiop.constraint.11=\ + {0} is not a valid value: does not implement java.io.Serializable. +rmic.iiop.constraint.12=\ + {0} is not a valid value: invalid parent. +rmic.iiop.constraint.13=\ + {0} is not a valid interface: the idl name for method {1} conflicts with another method. +rmic.iiop.constraint.14=\ + {0} is not a valid abstract interface: not an interface. +rmic.iiop.constraint.15=\ + {0} is not a valid abstract interface: implements java.rmi.Remote. +rmic.iiop.constraint.16=\ + {0} is not a valid remote interface: not an interface. +rmic.iiop.constraint.17=\ + {0} is not a valid remote implementation: not a class. +rmic.iiop.constraint.18=\ + {0} is not a valid interface: method {1} may not pass an exception which implements org.omg.CORBA.portable.IDLEntity. +rmic.iiop.constraint.19=\ + {0} is not a valid interface: the idl name for constant {1} conflicts with another constant. +rmic.iiop.constraint.20=\ + {0} is not a valid class: the idl name for member {1} conflicts with another member. +rmic.iiop.constraint.21=\ + {0} is a remote implementation class and cannot be used as a method argument or return type in {1}. +rmic.iiop.constraint.22=\ + Internal failure: (Method) exception {0} not a class type. +rmic.iiop.constraint.23=\ + Internal failure: (Method) caught null pointer exception for {0}. +rmic.iiop.constraint.24=\ + Class {0} contains an invalid return type. +rmic.iiop.constraint.25=\ + Class {0} contains an invalid argument type in method {1}. +rmic.iiop.constraint.26=\ + Could not compile {0}. +rmic.iiop.constraint.27=\ + Could not load class {0}. +rmic.iiop.constraint.28=\ + {0} is a remote implementation class and cannot be used as a data member in {1}. diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt new file mode 100644 index 000000000..1d278593f --- /dev/null +++ b/src/site/apt/index.apt @@ -0,0 +1,24 @@ +GlassFish-Corba + + This project contains the source code, documentation, and tests for the CORBA ORB that is used in the GlassFish application server project. The GlassFish ORB complies with the CORBA 2.3.1 specification, and with the CORBA 3.0 specifications for the Interoperable Name Service and Portable Interceptors. It includes both IDL and RMI-IIOP support. The GlassFish ORB has an open, extensible architecture that supports flexible configuration and extension through an open SPI. This ORB is written completely in Java. +Special Features of the GlassFish ORB + + This ORB has a number of special features specifically for GlassFish: + + * An optimized, streaming transport for GIOP 1.2 that uses NIO select for scalability. + + * An implementation of RMI-IIOP that uses runtime bytecode generation to avoid the need for the rmic compiler for either stubs or skeletons. + + * An optimized fast object copier to speed up co-located RMI-IIOP calls that require pass-by-value semantics for argument passing. + + * Highly optimized colocated RMI-IIOP calls that short circuit most of the ORB object adapter and transport code for speed. + + * The ORB architecture is based in part on the PEPt work by Harold Carr (a former member of the ORB team), that provides clean separation between protocol, encoding, presentation, and transport without impacting performance. + + * The ORB includes a code generation library (codegen) that supports runtime generation of classes from a high-level java-like API. This is currently used to generate the classes needed to support the remote view for EJB 3. + + * Support is included for dynamic failover and load balancing of IIOP requests. + + + +===================== diff --git a/test/.cvsignore b/test/.cvsignore new file mode 100644 index 000000000..378eac25d --- /dev/null +++ b/test/.cvsignore @@ -0,0 +1 @@ +build diff --git a/test/disabled/performance/eesample/SampleData.java b/test/disabled/performance/eesample/SampleData.java new file mode 100644 index 000000000..b4b30f9df --- /dev/null +++ b/test/disabled/performance/eesample/SampleData.java @@ -0,0 +1,367 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * SampleData.java + * + * Created on July 28, 2006, 10:06 AM + * + * To change this template, choose Tools | Template Manager + * and open the template in the editor. + */ + +package performance.eesample; + +import java.io.Serializable ; +import java.util.List ; +import java.util.ArrayList ; + +/** + * + * @author ken + */ +public class SampleData { + public static class Data implements Serializable { + int id ; + String name ; + String cnpj ; + String obs ; + } + + public List parse( String[][] data ) { + List result = new ArrayList( data.length ) ; + for (String[] rec : data) { + Data drec = new Data() ; + drec.id = Integer.valueOf( rec[0] ) ; + drec.name = rec[1] ; + drec.cnpj = rec[2] ; + drec.obs = rec[3] ; + result.add( drec ) ; + } + return result ; + } + + // Does not propertly account for headers! + public int estimateSize( List arg ) { + int result = 4 ; + for (Data data : arg) { + int size = 0 ; + size += 4 ; + size += 4 ; + size += data.name.length() + 1 ; + size += data.cnpj.length() + 1 ; + size += data.obs.length() + 1 ; + result += size ; + } + return result ; + } + + public static final String[][] bankData = { + {"1","Banco do Brasil S.A.","",""}, + {"2","Banco Central do Brasil","",""}, + {"3","Banco da Amaz\u00C3\u00B4nia S.A.","",""}, + {"4","Banco do Nordeste do Brasil S.A."," . . / - ",""}, + {"5","Banco Nacional da Habita\u00C3\u00C7\u00C3\u00A3o"," . . / - ",""}, + {"6","Banco Nacional de Cr\u00C3\u00A9dito Cooperativo S.A."," . . / - ",""}, + {"8","Banco Meridional S.A."," . . / - ",""}, + {"10","Montenegro Business Corporation","01.212.121/0001-13",""}, + {"20","Banco do Estado de Alagoas S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"21","Banestes S.A. Banco do Estado do Espirito Santo","",""}, + {"24","Banco do Estado de Pernambuco S.A.","",""}, + {"26","Banco do Estado do Acre S.A.","",""}, + {"27","Banco do Estado de Santa Catarina S.A.","",""}, + {"28","Banco Baneb S.A.","",""}, + {"29","Banco Banerj S.A.","",""}, + {"30","Paraiban - Banco do Estado da Para\u00C3\u00ADba S.A.","",""}, + {"31","Banco do Estado de Goi\u00C3\u00A1s S.A.","",""}, + {"32","Banco do Estado de Mato Grosso S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"33","Banco do Estado de S\u00C3\u00A3o Paulo S.A. - Banespa","",""}, + {"34","Banco do Estado do Amazonas S.A.","",""}, + {"35","Banco do Estado do Ceara S.A.","",""}, + {"36","Banco do Estado do Maranh\u00C3\u00A3o S.A.","",""}, + {"37","Banco do Estado do Par\u00C3\u00A1 S.A.","",""}, + {"38","Banco do Estado do Paran\u00C3\u00A1 S.A.","",""}, + {"39","Banco do Estado do Piau\u00C3\u00AD S.A.","",""}, + {"40","Banco Cargill S.A.","",""}, + {"41","Banco do Estado do Rio Grande do Sul S.A.","",""}, + {"42","Banco J. Safra S.A.","",""}, + {"43","Banco do Estado do Rio Grande do Norte S.A.","",""}, + {"47","Banco do Estado de Sergipe S.A.","",""}, + {"48","Banco Bemge S.A.","",""}, + {"50","Banco de Des. do Est. do Rio de Janeiro S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"52","Banco de Des. do Est. do Maranh\u00C3\u00A3o S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"53","Banco de Desenvolvimento do Ceara S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"54","Banco de Desenvolvimento do Est. de S\u00C3\u00A3o Paulo S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"55","Banco de Desenvolvimento do Rio Grande do Norte S.A.","",""}, + {"56","Banco de Desenvolvimento do Estado do Rio Grande do Sul S.A.","",""}, + {"59","Banco do Estado de Rond\u00C3\u00B4nia S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"70","BRB - Banco de Bras\u00C3\u00ADlia S.A.","",""}, + {"71","Banco do Estado do Rio de Janeiro S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"104","Caixa Econ\u00C3\u00B4mica Federal","",""}, + {"106","Banco Itabanco S.A.","",""}, + {"107","Banco BBM S.A.","",""}, + {"109","Banco Credibanco S.A.","",""}, + {"116","Banco BNL do Brasil S.A.","",""}, + {"148","Multi Banco S.A.","",""}, + {"150","Caixa Econ\u00C3\u00B4mica do Estado de Minas Gerais","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"151","Nossa Caixa - Nosso Banco S.A.","",""}, + {"152","Caixa Econ\u00C3\u00B4mica do Estado de Goi\u00C3\u00A1s","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"153","Caixa Econ\u00C3\u00B4mica Estadual do Rio Grande do Sul","",""}, + {"154","Caixa Econ\u00C3\u00B4mica do Estado de Santa Catarina S.A.","",""}, + {"164","Banco Credit Commercial de France S.A.","",""}, + {"165","Banco Norchem S.A.","",""}, + {"166","Banco Inter-Atl\u00C3\u00A2ntico S.A.","",""}, + {"168","Banco CCF Brasil S.A.","",""}, + {"171","BFI - Banco de Financiamento Internacional S.A.","","Em fal\u00C3\u00AAncia"}, + {"175","Continental Banco S.A.","",""}, + {"184","Banco BBA-Creditanstalt S.A.","",""}, + {"199","Banco Financial Portugu\u00C3\u00AAs","",""}, + {"200","Banco Ficrisa Axelrud S.A.","",""}, + {"201","Banco Axial S.A.","",""}, + {"203","Banco Sibisa S.A. com. inv. cred. cons. cred. imob.","","Em fal\u00C3\u00AAncia"}, + {"204","Banco Inter American Express S.A.","",""}, + {"205","Banco Sul Am\u00C3\u00A9rica S.A.","",""}, + {"206","Banco Martinelli S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"207","Banco Garavelo S.A.","","Em fal\u00C3\u00AAncia"}, + {"208","Banco Pactual S.A.","",""}, + {"209","Agrobanco - Banco Comercial S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"210","Dresdner Bank Lateinamerika Aktiengesellschaft","",""}, + {"211","Banco Sistema S.A.","",""}, + {"212","Banco Matone S.A.","",""}, + {"213","Banco Arbi S.A.","",""}, + {"214","Banco Dibens S.A.","",""}, + {"215","Banco Am\u00C3\u00A9rica do Sul S.A.","",""}, + {"216","Banco Regional Malcon S.A. - Comerc. e de Cred. ao Consumidor","",""}, + {"217","Banco John Deere S.A.","",""}, + {"218","BBS Banco Bonsucesso S.A.","",""}, + {"219","Banco Zogbi S.A.","",""}, + {"220","Banco Crefisul S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"221","Banco Fleming Graphus S.A.","",""}, + {"222","Banco AGF Braseg S.A.","",""}, + {"223","Banco Interunion S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"224","Banco Fibra S.A.","",""}, + {"225","Banco Brascan S.A.","",""}, + {"226","Banco Auxiliar S.A.","",""}, + {"227","Banco Rosa S.A.","","Em fal\u00C3\u00AAncia"}, + {"228","Banco Icatu S.A.","",""}, + {"229","Banco Cruzeiro do Sul S.A.","",""}, + {"230","Banco Bandeirantes S.A.","",""}, + {"231","Banco Boavista Interatl\u00C3\u00A2ntico S.A.","",""}, + {"232","Banco Interpart S.A.","",""}, + {"233","Banco GE Capital S.A.","",""}, + {"234","Banco Lavra S.A.","",""}, + {"235","Banco Liberal S.A.","",""}, + {"236","Banco Cambial S.A.","",""}, + {"237","Banco Bradesco S.A.","",""}, + {"240","Banco de Credito Real de Minas Gerais S.A.","",""}, + {"241","Banco Cl\u00C3\u00A1ssico S.A.","",""}, + {"242","Banco Euroinvest S.A. - Eurobanco","",""}, + {"243","Banco Multi Stock S.A.","",""}, + {"244","Banco Cidade S.A.","",""}, + {"245","Banco Empresarial S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"246","Banco ABC Brasil S.A.","",""}, + {"247","Banco Warburg Dillon Read S.A.","",""}, + {"249","Banco Investcred S.A.","",""}, + {"250","Banco Schahin S.A.","",""}, + {"251","Banco S\u00C3\u00A3o Jorge S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"252","Banco Fininvest S.A.","",""}, + {"254","Paran\u00C3\u00A1 Banco S.A.","",""}, + {"255","Milbanco S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"256","Banco Gulfinvest S.A.","",""}, + {"258","Banco Induscred S.A.","",""}, + {"261","Banco Varig S.A.","",""}, + {"262","Banco Boreal S.A.","",""}, + {"263","Banco Cacique S.A.","",""}, + {"265","Banco Fator S.A.","",""}, + {"266","Banco C\u00C3\u00A9dula S.A.","",""}, + {"267","Banco BBM - Comercial, Cred. Imob. e Cred. Fin. Inv. S.A.","",""}, + {"275","Banco ABN Amro S.A.","",""}, + {"277","Planibanc Distribuidora de T\u00C3\u00ADtulos Valores Mobili\u00C3\u00A1rios S.A.","",""}, + {"282","Banco Brasileiro Comercial S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"284","Banco das Na\u00C3\u00C7\u00C3\u00B5es S.A.","",""}, + {"291","Banco de Cr\u00C3\u00A9dito Nacional S.A.","",""}, + {"294","BCR Banco de Cr\u00C3\u00A9dito Real S.A.","",""}, + {"295","Banco Crediplan S.A.","",""}, + {"298","Banco Alfa S.A.","",""}, + {"300","Banco de La Nacion Argentina","",""}, + {"302","Banco do Progresso S.A.","","Em fal\u00C3\u00AAncia"}, + {"303","Banco HNF S.A.","",""}, + {"304","Banco Pontual S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"308","Banco Comercial Bancesa S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"314","Banco do Comercio e Industria de S\u00C3\u00A3o Paulo S.A.","",""}, + {"317","Banco do Com\u00C3\u00A9rcio S.A.","",""}, + {"318","Banco BMG S.A.","",""}, + {"320","Banco Industrial e Comercial S.A.","",""}, + {"334","Banco Econ\u00C3\u00B4mico S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"337","Banco Savena S.A.","",""}, + {"338","Banco F. Barretto S.A.","",""}, + {"341","Banco Ita\u00C3\u00BA S.A.","",""}, + {"344","Banco Mercantil S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"345","Banco Financial S.A.","",""}, + {"347","Banco Sudameris Brasil S.A.","",""}, + {"351","Banco Bozano, Simonsen S.A.","",""}, + {"353","Banco Santander Brasil S.A.","",""}, + {"356","Banco Real Abn Amho S.A.","",""}, + {"361","Banco Industrial de Pernambuco S.A.","",""}, + {"366","Banco Sogeral S.A.","",""}, + {"369","Banco Digibanco S.A.","",""}, + {"370","Banco Europeu para a Am\u00C3\u00A9rica Latina (BEAL), S.A.","",""}, + {"372","Banco Itamarati S.A.","",""}, + {"375","Banco Fen\u00C3\u00ADcia S.A.","",""}, + {"376","Banco Chase Manhattan S.A.","",""}, + {"388","Banco BMD S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"389","Banco Mercantil do Brasil S.A.","",""}, + {"392","Banco Mercantil - Finasa S.A. - S\u00C3\u00A3o Paulo","",""}, + {"394","Banco BMC S.A.","",""}, + {"399","HSBC Bank Brasil S.A.","","Banco m\u00C3\u00BAltiplo"}, + {"405","Banco Mineiro S.A.","",""}, + {"409","Unibanco - Uni\u00C3\u00A3o de Bancos Brasileiros S.A.","",""}, + {"412","Banco Capital S.A.","",""}, + {"415","Banco Nacional S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"417","Banco Sul Brasileiro S.A.","",""}, + {"420","Banco Banorte S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"422","Banco Safra S.A.","",""}, + {"424","Banco Santander Noroeste S.A.","",""}, + {"432","Banco Pinto de Magalh\u00C3\u00A3es S.A.","",""}, + {"434","Banfort - Banco Fortaleza S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"441","Banco Real de S\u00C3\u00A3o Paulo S.A.","",""}, + {"446","Banco Regional S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"453","Banco Rural S.A.","",""}, + {"456","Banco de Tokyo-Mitsubishi Brasil S.A.","",""}, + {"464","Banco Sumitomo Brasileiro S.A.","",""}, + {"466","Banco de Tokyo S.A.","",""}, + {"472","Lloyds TSB Bank PLC","",""}, + {"474","Banco de Cr\u00C3\u00A9dito Comercial S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"477","Citibank N.A.","",""}, + {"479","Bankboston Banco M\u00C3\u00BAltiplo S.A.","",""}, + {"480","Banco Wachovia S.A.","",""}, + {"483","Banco Agrimisa S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"485","Banco de Roraima S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o"}, + {"486","Banco de Desenvolvimento do Paran\u00C3\u00A1 S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"487","Deutsche Bank S.A. Banco Alem\u00C3\u00A3o","",""}, + {"488","Morgan Guaranty Trust Company of New York","",""}, + {"489","Banco Franc\u00C3\u00AAs Uruguay S.A.","",""}, + {"490","Banco Resid\u00C3\u00AAncia S.A.","",""}, + {"491","Banco Maisonnave S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"492","Ing Bank N.V.","",""}, + {"493","Banco Union, C.A.","",""}, + {"494","Banco de La Republica Oriental Del Uruguay","",""}, + {"495","Banco de La Provincia de Buenos Aires","",""}, + {"496","Argentaria, Caja Postal y Banco Hipotecario S.A.","",""}, + {"497","Banco Hispano Americano S.A.","",""}, + {"498","Centro Hispano Banco","",""}, + {"499","Banco Iochpe S.A.","",""}, + {"500","Banco Habitasul S.A.","",""}, + {"501","Banco Brasileiro-Iraquiano S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"502","Banco Santander de Neg\u00C3\u00B3cios S.A.","",""}, + {"503","Banco BRJ S.A.","",""}, + {"504","Banco Multiplic S.A.","",""}, + {"505","Banco Credit Suisse First Boston Garantia S.A.","",""}, + {"600","Banco Luso Brasileiro S.A.","",""}, + {"601","BFC Banco S.A.","",""}, + {"602","Banco Patente S.A.","",""}, + {"603","Banco H\u00C3\u00A9rcules S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"604","Banco Industrial do Brasil S.A.","",""}, + {"605","BPA Banco P\u00C3\u00A3o de A\u00C3\u00C7\u00C3\u00BAcar S.A.","",""}, + {"607","Banco Santos Neves S.A.","",""}, + {"608","Banco Open S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"609","Banco Adolpho Oliveira & Associados S.A.","","Em fal\u00C3\u00AAncia"}, + {"610","Banco VR S.A.","",""}, + {"611","Banco Paulista S.A.","",""}, + {"612","Banco Guanabara S.A.","",""}, + {"613","Banco Pecunia S.A.","",""}, + {"616","Banco Interpacifico S.A.","",""}, + {"618","Banco Tendencia S.A.","",""}, + {"621","Banco Aplicap S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"622","Banco Dracma S.A.","",""}, + {"623","Banco Panamericano S.A.","",""}, + {"624","Banco General Motors S.A.","",""}, + {"625","Banco Arauc\u00C3\u00A1ria S.A.","",""}, + {"626","Banco Ficsa S.A.","",""}, + {"627","Banco Destak S.A.","",""}, + {"629","Banco Bancorp S.A.","","Em fal\u00C3\u00AAncia"}, + {"630","Banco Intercap S.A.","",""}, + {"631","Banco Columbia S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"633","Banco Rendimento S.A.","",""}, + {"634","Banco Tri\u00C3\u00A2ngulo S.A.","",""}, + {"635","Banco do Estado do Amap\u00C3\u00A1 S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"637","Banco Sofisa S.A.","",""}, + {"638","Banco Prosper S.A.","",""}, + {"639","Big S.A. - Banco Irm\u00C3\u00A3os Guimar\u00C3\u00A3es","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"641","Banco Bilbao Vizcaya Brasil S.A.","",""}, + {"642","Brasbanco S.A. Banco Comercial","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"643","Banco Pine S.A.","",""}, + {"645","Banco do Estado de Roraima S.A.","",""}, + {"647","Banco Marka S.A.","",""}, + {"648","Banco Atlantis S.A.","",""}, + {"649","Banco Dimensao S.A.","",""}, + {"650","Banco Pebb S.A.","",""}, + {"652","Banco Frances e Brasileiro S.A.","",""}, + {"653","Banco Indusval S.A.","",""}, + {"654","Banco A.J. Renner S.A."," . . / - ",""}, + {"655","Banco Votorantim S.A.","",""}, + {"656","Banco Matrix S.A.","",""}, + {"657","Banco Tecnicorp S.A.","",""}, + {"658","Banco Porto Real S.A.","",""}, + {"702","Banco Santos S.A.","",""}, + {"705","Banco Investcorp S.A.","",""}, + {"707","Banco Daycoval S.A.","",""}, + {"711","Banco Vetor S.A.","",""}, + {"713","Banco Cindam S.A.","",""}, + {"715","Banco Vega S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"719","Banco Banif Primus S.A.","",""}, + {"720","Banco Maxinvest S.A.","",""}, + {"721","Banco Credibel S.A.","",""}, + {"722","Banco Interior de S\u00C3\u00A3o Paulo S.A.","",""}, + {"724","Banco Porto Seguro S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"725","Banco Finansinos S.A.","",""}, + {"726","Banco Universal S.A.","",""}, + {"727","Banco Comercial de S\u00C3\u00A3o Paulo S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o ordin\u00C3\u00A1ria"}, + {"728","Banco Fital S.A.","",""}, + {"729","Banco Fonte Cindam S.A.","",""}, + {"730","Banco Comercial Paraguayo S.A.","",""}, + {"731","Banco GNPP S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"732","Banco Minas S.A.","",""}, + {"734","Banco Gerdau S.A.","",""}, + {"735","Banco Pottencial S.A.","",""}, + {"736","Banco United S.A.","",""}, + {"737","Banco Theca S.A.","",""}, + {"738","Banco Morada S.A.","",""}, + {"739","Banco BGN S.A.","",""}, + {"740","Banco Barclays e Galicia S.A.","",""}, + {"741","Banco Ribeir\u00C3\u00A3o Preto S.A.","",""}, + {"742","Banco Equatorial S.A.","",""}, + {"743","Banco Emblema S.A.","",""}, + {"744","Bankboston, N.A.","",""}, + {"745","Banco Citibank S.A.","",""}, + {"746","Banco Modal S.A.","",""}, + {"747","Banco Rabobank International Brasil S.A.","",""}, + {"748","Banco Cooperativo Sicredi S.A. - Bansicredi","",""}, + {"749","BR Banco Mercantil S.A.","",""}, + {"750","Banco Republic National Bank of New York (Brasil), S.A.","",""}, + {"751","Dresdner Bank Brasil S.A. Banco M\u00C3\u00BAltiplo","",""}, + {"752","Banco Banque Nationale de Paris Brasil S.A.","",""}, + {"753","Banco Comercial Uruguai S.A.","",""}, + {"754","Banco Bamerindus do Brasil S.A.","","Liquida\u00C3\u00C7\u00C3\u00A3o extrajudicial"}, + {"755","Banco Merrill Lynch S.A.","",""}, + {"756","Banco Cooperativo do Brasil S.A.","",""}, + {"757","Banco Keb do Brasil S.A.","",""}, + {"1002","Teste automatizado - 1186813426861361525","12.345.678/0001-12","Observa\u00C3\u00C7\u00C3\u00A3o de exemplo para teste automatizado."}, + {"1003","Teste automatizado - 8958728301296053374","12.345.678/0001-12","Observa\u00C3\u00C7\u00C3\u00A3o de exemplo para teste automatizado."}, + {"1066","Osaman Banking","78.174.299/0001-98","Teste"} + } ; + + public static void main( String[] args ) { + SampleData ee = new SampleData() ; + List myData = ee.parse( bankData ) ; + int size = ee.estimateSize( myData ) ; + System.out.println( "Data set size = " + size ) ; + } +} diff --git a/test/disabled/performance/eesample/StandardTest.java b/test/disabled/performance/eesample/StandardTest.java new file mode 100644 index 000000000..e78b5f09a --- /dev/null +++ b/test/disabled/performance/eesample/StandardTest.java @@ -0,0 +1,1416 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample; + +import java.lang.reflect.Field ; +import java.lang.reflect.Method ; + +import java.lang.annotation.ElementType ; +import java.lang.annotation.RetentionPolicy ; +import java.lang.annotation.Target ; +import java.lang.annotation.Retention ; + +import java.util.Arrays ; +import java.util.List ; +import java.util.ArrayList ; +import java.util.Map ; +import java.util.Set ; +import java.util.HashMap ; +import java.util.Properties ; + +import java.rmi.RemoteException ; +import java.rmi.Remote ; + +import javax.rmi.CORBA.Tie ; +import javax.rmi.CORBA.Stub ; + +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.DatatypeConstants; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.BAD_OPERATION ; +import org.omg.CORBA.LocalObject ; + +import org.omg.CosNaming.NamingContext ; +import org.omg.CosNaming.NamingContextHelper ; +import org.omg.CosNaming.NamingContextExt ; +import org.omg.CosNaming.NamingContextExtHelper ; +import org.omg.CosNaming.NameComponent ; +import org.omg.CosNaming.NamingContextPackage.CannotProceed ; +import org.omg.CosNaming.NamingContextPackage.InvalidName ; +import org.omg.CosNaming.NamingContextPackage.AlreadyBound ; +import org.omg.CosNaming.NamingContextPackage.NotFound ; + +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantLocator ; + +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; + +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager ; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService ; + +import com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject ; +import com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl ; +import com.sun.corba.ee.impl.javax.rmi.CORBA.Util ; + +import com.sun.corba.ee.spi.extension.ServantCachingPolicy ; + +import performance.eesample.wspex.Address ; +import performance.eesample.wspex.ArrayOfLineItem ; +import performance.eesample.wspex.Customer ; +import performance.eesample.wspex.EchoOrderRequest ; +import performance.eesample.wspex.EchoOrderResponse ; +import performance.eesample.wspex.Item ; +import performance.eesample.wspex.ItemArrayType; +import performance.eesample.wspex.LineItem ; +import performance.eesample.wspex.Location ; +import performance.eesample.wspex.Order ; +import performance.eesample.wspex.Struct ; +import performance.eesample.wspex.Synthetic ; +import performance.eesample.wspex.components.OrderBL; + +import com.sun.japex.JapexDriverBase ; +import com.sun.japex.TestCase ; +import org.glassfish.pfl.basic.tools.argparser.ArgParser; +import org.glassfish.pfl.basic.tools.argparser.DefaultValue; +import org.glassfish.pfl.dynamic.codegen.spi.GenericClass; +import org.glassfish.pfl.dynamic.codegen.spi.Type; +import org.glassfish.pfl.test.TestBase; + +/** Standard top-level ORB test. Does the following: + *

                  + *
                1. Tests CDR stream marshaling (for a copy) for a trivial call (long as arg) and + * for more complex data (ArrayList of simple instances) + *
                2. Tests inter ORB call with trivial data (long arg and result) and returning + * complex data (same ArrayList). The ORB instances are in the same VM, so loopback + * TCP is used. + *
                + * These tests are designed to be easily profiled. + * + * I am modifying this test to use Japex, and to include the wspex test cases so that + * we can more easily compare CORBA vs. SOAP/TCP. This should work as follows: + * + * interface SingleTest { + * void prepare( int size ) ; + * void run() ; + * } + * + * Make StandardTest extend JapexDriver + * Implement the driver methods as follows: + * initializeDriver + * set up ORB + * init stub + * prepare + * Gather parameters from the TestCase: + * - Test name + * - Test size + * Initialize an instance of SingleTest with the size required for the test + * warmup + * Just calls run + * run + * calls SingleTest.run + * terminateDriver + * shutdown the ORB + * + * @author Ken Cavanaugh + */ +public class StandardTest extends JapexDriverBase { + private static Field proDelegate ; + private static Field stubDelegateClass ; + private static Field utilDelegate ; + private static Field singletonORB ; + private static boolean corbaReinit = false ; + + private static final boolean useSingleClassLoader = true ; + + static { + if (!useSingleClassLoader) { + Type.clearCaches() ; + try { + proDelegate = javax.rmi.PortableRemoteObject.class.getDeclaredField( + "proDelegate" ) ; + stubDelegateClass = Stub.class.getDeclaredField( + "stubDelegateClass" ) ; + utilDelegate = javax.rmi.CORBA.Util.class.getDeclaredField( + "utilDelegate" ) ; + singletonORB = org.omg.CORBA.ORB.class.getDeclaredField( + "singleton" ) ; + + proDelegate.setAccessible( true ) ; + stubDelegateClass.setAccessible( true ) ; + utilDelegate.setAccessible( true ) ; + singletonORB.setAccessible( true ) ; + } catch (Exception exc) { + System.out.println( "Error in initializer: " + exc ) ; + } + } + } + + // This ugly little hack is here so that the CORBA delegates set in one + // Japex run (to objects in that run's JapexClassLoader) are not reused + // in a subsequent run, which causes severe problems with objects + // not having the correct type (because the class names are the same, + // but the ClassLoaders are different). This works by re-initializaing delegates + // at the beginning of each run. + private synchronized static void reinitCorbaDelegateHack() { + if (!corbaReinit) { + try { + stubDelegateClass.set( null, StubDelegateImpl.class ) ; + proDelegate.set( null, new PortableRemoteObject() ) ; + utilDelegate.set( null, new Util() ) ; + + synchronized( org.omg.CORBA.ORB.class ) { + singletonORB.set( null, null ) ; + } + } catch (Exception exc) { + System.out.println( "Error in corbaDelegateHack: " + exc ) ; + } + } + + corbaReinit = true ; + } + + // This is static because it is shared between the command-line instantiation + // of StandardTest, and the instance created by Japex, when run in Japex mode. + private static ArgParser ap = new ArgParser( + ArgumentData.class ) ; + + // set up default parameters + private static TestBase testBase ; + private static ArgumentData argData = ap.parse( new String[]{}, + ArgumentData.class ) ; + private static int numInstances = 0 ; + + static { + // The following must be set as system properties + System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass", + "com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject" ) ; + System.setProperty( "javax.rmi.CORBA.StubClass", + "com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl" ) ; + System.setProperty( "javax.rmi.CORBA.UtilClass", + "com.sun.corba.ee.impl.javax.rmi.CORBA.Util" ) ; + System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, + "true" ) ; + } + + private int instance = numInstances++ ; + + // Client state + private ORB clientORB = null ; + private NamingContextExt clientNamingRoot = null ; + + // Server state + private ORB serverORB = null ; + private NamingContextExt serverNamingRoot = null ; + + // Client and server state are both active in LOCAL mode. + + public StandardTest() { + // nothing to do here + } + + private static String getTransportDescription() { + return (argData.blocking() ? "Blocking transport(" : "Default transport(") + + argData.fragmentSize() + ")" ; + } + + private synchronized void log( String msg ) { + System.out.println( "(" + instance + ") " + msg ) ; + } + + private static void decodeAddress(Address address) { + decodeString(address.getAddress1()); + decodeString(address.getAddress2()); + decodeString(address.getCity()); + decodeString(address.getFirstName()); + decodeString(address.getLastName()); + decodeString(address.getState()); + decodeString(address.getZip()); + } + + private static void decodeArray(ItemArrayType echoArray) { + List items = echoArray.getItems(); + for (Item item : items) { + decodeItem(item); + } + } + + private static void decodeCustomer(Customer customer) { + decodeAddress(customer.getBillingAddress()); + decodeString(customer.getContactFirstName()); + decodeString(customer.getContactLastName()); + decodeString(customer.getContactPhone()); + decodeString(customer.getCreditCardExpirationDate()); + decodeString(customer.getCreditCardNumber()); + int id = customer.getCustomerId(); + XMLGregorianCalendar calendar = customer.getLastActivityDate(); + decodeAddress(customer.getShippingAddress()); + } + + private static void decodeItem(Item item) { + XMLGregorianCalendar calendar = item.getCreationdate(); + decodeString(item.getDescription()); + decodeString(item.getId()); + int inv = item.getInventory(); + float price = item.getPrice(); + decodeLocation(item.getLocation()); + } + + private static void decodeLineItem(LineItem lineItem) { + int itemId = lineItem.getItemId(); + int orderId = lineItem.getOrderId(); + int q = lineItem.getOrderQuantity(); + decodeString(lineItem.getProductDescription()); + int productId = lineItem.getProductId(); + float price = lineItem.getUnitPrice(); + } + + private static void decodeLineItems(ArrayOfLineItem lineItems) { + List lineitems = lineItems.getLineItem(); + for (LineItem lineItem : lineitems) { + decodeLineItem(lineItem); + } + } + + private static void decodeLocation(Location location) { + decodeString(location.getAddress()); + decodeString(location.getDescription()); + decodeString(location.getId()); + } + + private static void decodeOrder(Order echoOrder) { + decodeCustomer(echoOrder.getCustomer()); + decodeLineItems(echoOrder.getLineItems()); + XMLGregorianCalendar calendar = echoOrder.getOrderDate(); + int id = echoOrder.getOrderId(); + int status = echoOrder.getOrderStatus(); + float amount = echoOrder.getOrderTotalAmount(); + } + + private static void decodeString(String echoString) { + int length = echoString.length(); + } + + private static void decodeStruct(Struct echoStruct) { + float f = echoStruct.getVarFloat(); + int i = echoStruct.getVarInt(); + decodeString(echoStruct.getVarString()); + } + + private static void decodeSynthetic(Synthetic echoSynthetic) { + byte[] b = echoSynthetic.getBytes(); + decodeStruct(echoSynthetic.getS()); + decodeString(echoSynthetic.getStr()); + } + + private synchronized void fatal( String msg, Throwable thr ) { + thr.printStackTrace() ; + log( msg ) ; + System.exit( 1 ) ; + } + + public interface SingleTest { + String description() ; + + /** Initialize data needed for this test + * + * @param size Size of the test + */ + void prepare( int size ) ; + + /** Run the test + * + * @throws Exception + */ + void run() throws Exception ; + } + + public abstract static class SingleTestBase implements SingleTest { + protected int size = 0 ; + protected final Test testRef ; + + public SingleTestBase( Test testRef ) { + this.testRef = testRef ; + } + + public String description() { + String className = this.getClass().getName() ; + final int lastDot = className.lastIndexOf( '.' ) ; + if (lastDot >= 0) { + className = className.substring(lastDot + 1); + } + + if (size == 0) { + return className + " " + getTransportDescription(); + } else { + return className + size + " " + getTransportDescription(); + } + } + + // Default implementation of prepare. + public void prepare( int size ) { + } + + // All subclasses must define run. + } + + public static class EchoTest extends SingleTestBase { + private int value = 0 ; + + public EchoTest( Test testRef ) { + super( testRef ) ; + } + + public void run() throws Exception { + value += testRef.echo( value + 1 ) ; + } + } + + public static class GetDataTest extends SingleTestBase { + public GetDataTest( Test testRef ) { + super( testRef ) ; + } + + public void run() throws Exception { + testRef.getData(); + } + } + + public static class GetDataArrayTest extends SingleTestBase { + public GetDataArrayTest( Test testRef ) { + super( testRef ) ; + } + + public void run() throws Exception { + testRef.getDataArray(); + } + } + + public static class GetTestRefsTest extends SingleTestBase { + public GetTestRefsTest( Test testRef ) { + super( testRef ) ; + } + + public void run() throws Exception { + testRef.getTestRefs() ; + } + } + + public static class EchoStringTest extends SingleTestBase { + public EchoStringTest( Test testRef ) { + super( testRef ) ; + } + + public void run() throws Exception { + String str = testRef.echoString("Hello World"); + int i = str.length(); + } + } + + public static class EchoVoidTest extends SingleTestBase { + public EchoVoidTest( Test testRef ) { + super( testRef ) ; + } + + public void run() throws Exception { + testRef.echoVoid() ; + } + } + + public static class EchoStructTest extends SingleTestBase { + private Struct struct ; + + public EchoStructTest( Test testRef ) { + super( testRef ) ; + } + + @Override + public void prepare( int size ) { + struct = new Struct(); + struct.setVarInt(5); + struct.setVarFloat(2.5f); + struct.setVarString("Hello There!"); + } + + public void run() throws Exception { + decodeStruct( testRef.echoStruct(struct ) ) ; + } + } + + public static class EchoSyntheticTest extends SingleTestBase { + private Synthetic synthetic ; + + public EchoSyntheticTest( Test testRef ) { + super( testRef ) ; + } + + @Override + public void prepare( int size ) { + this.size = size ; + Struct struct = new Struct(); + struct.setVarInt(5); + struct.setVarFloat(2.5f); + struct.setVarString("Hello There!"); + byte[] bytes = new byte[size]; + synthetic = new Synthetic(); + synthetic.setStr("Hello World"); + synthetic.setS(struct); + synthetic.setBytes(bytes); + } + + public void run() throws Exception { + decodeSynthetic(testRef.echoSynthetic(synthetic)); + } + } + + public static class EchoArrayTest extends SingleTestBase { + private ItemArrayType items ; + + public EchoArrayTest( Test testRef ) { + super( testRef ) ; + } + + @Override + public void prepare( int size ) { + this.size = size ; + + final Item[] itemlist = new Item[size]; + items = new ItemArrayType(); + + for (int i = 0; i < size; i++) { + itemlist[i] = new Item(); + itemlist[i].setId(java.lang.Integer.toString(i)); + itemlist[i].setDescription("Item Description"); + itemlist[i].setPrice(100.00f); + itemlist[i].setInventory(i*100); + + Location loc = new Location(); + loc.setId("CA95050"); + loc.setDescription("Santa Clara, California"); + loc.setAddress("1000, network circle"); + itemlist[i].setLocation(loc); + + try { + DatatypeFactory df = DatatypeFactory.newInstance(); + XMLGregorianCalendar cal = df.newXMLGregorianCalendar(); + cal.setYear(2005); + cal.setMonth(DatatypeConstants.MARCH); + cal.setDay(29); + cal.setTime(11,11,11); + itemlist[i].setCreationdate(cal); + } catch (Exception e) { + throw new RuntimeException(e); + } + + items.getItems().add(itemlist[i]); + } + } + + public void run() throws Exception { + decodeArray(testRef.echoArray(items)); + } + } + + public static class GetOrderTest extends SingleTestBase { + private int orderId ; + private int customerId ; + + public GetOrderTest( Test testRef ) { + super( testRef ) ; + } + + @Override + public void prepare( int size ) { + orderId = 999 ; + customerId = 109292 ; + } + + public void run() throws Exception { + Order or = testRef.getOrder(++orderId, customerId); + if (or.getOrderId() != orderId) { + throw new IllegalStateException("Not equal!"); + } + decodeOrder(or); + // do nothing with the order + } + } + + public static class EchoOrderTest extends SingleTestBase { + private int orderId ; + private int customerId ; + private int mySize ; + private Order order ; + + public EchoOrderTest( Test testRef ) { + super( testRef ) ; + } + + @Override + public void prepare( int size ) { + orderId = 999 ; + customerId = 109292 ; + + this.mySize = size ; + + int id = 1; + + // create the order object + Address ship = new Address(); + ship.setFirstName("Ship FirstName "+ id); + ship.setLastName("Ship LastName " + id); + ship.setAddress1( "Ship StreetAddres " + id); + ship.setAddress2("Street Address Line 2 " + id); + ship.setCity( "City " + id); + ship.setState( "State " + id); + ship.setZip( "12345"); + Address bill = new Address(); + bill.setFirstName("Bill FirstName "+ id); + bill.setLastName("Bill LastName " + id); + bill.setAddress1( "Bill StreetAddres " + id); + bill.setAddress2("Street Address Line 2 " + id); + bill.setCity( "City " + id); + bill.setState( "State " + id); + bill.setZip( "12345"); + Customer customer = new Customer(); + customer.setCustomerId(customerId) ; + customer.setContactFirstName("FirstName " + id); + customer.setContactLastName( "LastName " + id); + customer.setContactPhone(Integer.toString(id)); + DatatypeFactory df ; + try { + df = DatatypeFactory.newInstance(); + } catch (javax.xml.datatype.DatatypeConfigurationException ex){ + throw new RuntimeException(ex); + } + + XMLGregorianCalendar date = df.newXMLGregorianCalendar(); + date.setYear(2005); + date.setMonth(DatatypeConstants.MARCH); + date.setDay(29); + date.setTime(11,11,11); + + customer.setLastActivityDate(date) ; + customer.setCreditCardNumber(""+id); + customer.setCreditCardExpirationDate( ""+id) ; + customer.setBillingAddress(bill) ; + customer.setShippingAddress(ship) ; + + ArrayOfLineItem linearray = new ArrayOfLineItem(); + List lines = linearray.getLineItem(); + + for (int i = 0; i < size; i++){ + LineItem line = new LineItem(); + line.setOrderId(orderId); + line.setItemId(i+1); + line.setProductId(i); + line.setProductDescription("Test Product " +i); + line.setOrderQuantity(1); + line.setUnitPrice((float) 1.00); + lines.add(line); + } + + order = new Order(); + order.setOrderId(orderId); + order.setOrderStatus(1); + order.setOrderDate(date); + order.setOrderTotalAmount((float) 50); + order.setCustomer(customer); + order.setLineItems(linearray); + } + + public void run() throws Exception { + final EchoOrderRequest request= new EchoOrderRequest(); + request.setEchoOrderRequest(order); + decodeOrder(testRef.echoOrder(request).getEchoOrderResponse()); + } + } + + /* + public static class IntCopyTest implements SingleTest { + private int value = 0 ; + + public String description() { + return "IntCopy" ; + } + + public void prepare( int size ) { + // nop + } + + public void run() throws Exception { + value += (Integer)copy( value + 1 ) ; + } + } + + public static class DataCopyTest implements SingleTest { + private final List value ; + + public DataCopyTest() { + final SampleData sd = new SampleData() ; + value = sd.parse( SampleData.bankData ) ; + } + + public String description() { + return "IntCopy" ; + } + + public void prepare( int size ) { + // nop + } + + public void run() throws Exception { + Object data = copy( value ) ; + } + } + */ + + @Target( ElementType.METHOD ) + @Retention( RetentionPolicy.RUNTIME ) + public @interface TestClass { + Class value() ; + } + + public interface Test extends Remote { + @TestClass( EchoTest.class ) + public int echo( int value ) throws RemoteException ; + + @TestClass( GetDataTest.class ) + public List getData() throws RemoteException ; + + @TestClass( GetDataArrayTest.class ) + public SampleData.Data[] getDataArray() throws RemoteException ; + + @TestClass( GetTestRefsTest.class ) + public List getTestRefs() throws RemoteException ; + + public void done() throws RemoteException ; + + // The following methods are taken from the wspex test. + @TestClass( EchoVoidTest.class ) + void echoVoid() throws RemoteException ; + + @TestClass( EchoStringTest.class ) + String echoString(String value) throws RemoteException ; + + @TestClass( EchoStructTest.class ) + Struct echoStruct(Struct parameters) throws RemoteException ; + + @TestClass( EchoSyntheticTest.class ) + Synthetic echoSynthetic(Synthetic s) throws RemoteException ; + + @TestClass( EchoArrayTest.class ) + ItemArrayType echoArray(ItemArrayType items) throws RemoteException ; + + @TestClass( GetOrderTest.class ) + Order getOrder(int orderId, int customerId) throws RemoteException ; + + @TestClass( EchoOrderTest.class ) + EchoOrderResponse echoOrder(EchoOrderRequest or) throws RemoteException ; + } + + /** Class that scans an interface looking for @TestClass annotationed methods. + * It provides APIs for getting the list of annotated methods, + * and mapping a method name to an instance of SingleTest. + */ + private class TestMapper { + private Map> mmap ; + + public TestMapper( Class cls ) { + if (!cls.isInterface()) { + throw new IllegalArgumentException("TestMapper requires an interface, not a class"); + } + + mmap = new HashMap>() ; + + for (Method m : cls.getDeclaredMethods()) { + TestClass tc = m.getAnnotation( TestClass.class ) ; + if (tc != null) { + Class tclass = tc.value() ; + mmap.put( m.getName(), tclass ) ; + } + } + } + + Set getValidNames() { + return mmap.keySet() ; + } + + SingleTest getSingleTest( String name, Object... args ) { + Class cls = mmap.get( name ) ; + if (cls == null) { + return null ; + } + + GenericClass gclass = + new GenericClass( SingleTest.class, cls ) ; + return gclass.create( args ) ; + } + } + + public static class TestImpl extends PortableRemoteObject implements Test { + SampleData sd = new SampleData() ; + List data = sd.parse( SampleData.bankData ) ; + SampleData.Data[] dataArray = null ; + List testRefList = null ; + + public TestImpl() throws RemoteException { + super() ; + dataArray = new SampleData.Data[data.size()] ; + int ctr=0 ; + for (SampleData.Data d : data) { + dataArray[ctr++] = d; + } + } + + public int echo( int value ) throws RemoteException { + return value ; + } + + public List getData() throws RemoteException { + return data ; + } + + public SampleData.Data[] getDataArray() throws RemoteException { + return dataArray ; + } + + public List getTestRefs() throws RemoteException { + return testRefList ; + } + + public void echoVoid() { + } + + public String echoString(String value) { + return value; + } + + public Struct echoStruct(Struct parameters) { + return parameters; + } + + public Synthetic echoSynthetic(Synthetic s) { + return s; + } + + public ItemArrayType echoArray(ItemArrayType items) { + return items; + } + + public Order getOrder(int orderId, int customerId) { + OrderBL bl = new OrderBL(); + return bl.GetOrder(orderId, customerId); + } + + public EchoOrderResponse echoOrder(EchoOrderRequest or){ + Order order = or.getEchoOrderRequest(); + EchoOrderResponse res = new EchoOrderResponse(); + res.setEchoOrderResponse(order); + return res; + } + + public void done() throws RemoteException { + System.exit(0) ; + } + + public void setRef( Test test ) { + testRefList = new ArrayList() ; + for (int ctr=0; ctr nocacheFactoryPolicies = null ; + ReferenceFactory nocacheFactory = rfm.create( nocacheFactoryName, + repositoryId, nocacheFactoryPolicies, locator ) ; + + List cacheFactoryPolicies = Arrays.asList( + (Policy)ServantCachingPolicy.getPolicy() ) ; + ReferenceFactory cacheFactory = rfm.create( cacheFactoryName, + repositoryId, cacheFactoryPolicies, locator ) ; + + // Use a ReferenceFactory to create objref and register it with naming + for ( Object[] data : objrefData) { + String sname = String.class.cast( data[0] ) ; + boolean useCaching = Boolean.class.cast( data[1] ) ; + ReferenceFactory factory = useCaching ? cacheFactory : nocacheFactory ; + byte[] oid = new byte[] { (byte)0, (byte)1, (byte)2 } ; + org.omg.CORBA.Object objref = factory.createReference( oid ) ; + Test ref = Test.class.cast( javax.rmi.PortableRemoteObject.narrow( objref, + Test.class )) ; + locator.setRef( ref ) ; + try { + bindName( serverNamingRoot, sname, objref ) ; + } catch (Exception exc) { + fatal( "Error in initializeServer: " + exc, exc ) ; + } + } + } + + public void serverWait() { + serverORB.run() ; + } + + private void cleanUpServer() { + log( "Shutting down serverORB" ) ; + serverORB.shutdown( true ) ; + log( "Destroying serverORB" ) ; + serverORB.destroy() ; + } + + private Test getTestRef( String name ) { + try { + org.omg.CORBA.Object obj = clientNamingRoot.resolve_str( name ) ; + Test ref = (Test)javax.rmi.PortableRemoteObject.narrow( obj, Test.class ) ; + return ref ; + } catch (Exception exc) { + fatal( "Could not get object reference: " + exc, exc ) ; + } + return null ; // not reachable + } + + // Code for command-line testing + // + // + private void performSingleTest( SingleTest test ) { + try { + final int warmup = argData.warmup() ; + for (int ctr = 0; ctr < warmup; ctr ++ ) { + test.run() ; + } + + final long time = System.nanoTime() ; + + final int count = argData.count() ; + for (int ctr = 0; ctr < count; ctr++) { + test.run(); + } + + final double elapsed = System.nanoTime() - time ; + + log( test.description() + " : " + (elapsed/count)/1000 + + " microseconds" ) ; + } catch (Exception rex) { + fatal( test.description() + ": error in test: ", rex ) ; + rex.printStackTrace() ; + } + } + + /* + public void testNullStreamCopy() { + SingleTest st = new IntCopyTest() ; + performSingleTest( st ) ; + } + + public void testDataStreamCopy() { + SingleTest st = new DataCopyTest() ; + performSingleTest( st ) ; + } + */ + + @org.glassfish.pfl.test.TestCase( "null" ) + public void testNullCall() { + for ( Object[] data : objrefData) { + String oname = (String)data[0] ; + Test test = getTestRef( oname ) ; + SingleTest st = new EchoTest( test ) ; + performSingleTest( st ) ; + } + } + + @org.glassfish.pfl.test.TestCase( "data" ) + public void testDataCall() { + for ( Object[] data : objrefData) { + String oname = (String)data[0] ; + Test test = getTestRef( oname ) ; + SingleTest st = new GetDataTest( test ) ; + performSingleTest( st ) ; + } + } + + @org.glassfish.pfl.test.TestCase( "data-array" ) + public void testDataArrayCall() { + for ( Object[] data : objrefData) { + String oname = (String)data[0] ; + Test test = getTestRef( oname ) ; + SingleTest st = new GetDataArrayTest( test ) ; + performSingleTest( st ) ; + } + } + + @org.glassfish.pfl.test.TestCase( "get-test-refs" ) + public void testGetTestRefsCall() { + for ( Object[] data : objrefData) { + String oname = (String)data[0] ; + Test test = getTestRef( oname ) ; + SingleTest st = new GetTestRefsTest( test ) ; + performSingleTest( st ) ; + } + } + + public void standaloneRun() { + switch (argData.mode()) { + case CLIENT : + runClient() ; + // st.stopServer() ; + System.exit(0) ; + break ; + case SERVER : + initializeServer() ; + serverWait() ; + break ; + case LOCAL : + // Colocated test: + initializeServer() ; + runClient() ; + cleanUpServer() ; + System.exit(0) ; + break ; + } + } + + public class ClientThread extends Thread { + @Override + public void run() { + try { + initializeClientORB() ; + testBase.run() ; + cleanUpClient() ; + log( "Test Complete." ) ; + } catch (Throwable thr) { + fatal( "Test FAILED: Caught throwable " + thr, thr ) ; + } + } + } + + public void runClient() { + final List clients = new ArrayList() ; + for (int ctr=0; ctr + *
              25. -mode [local client server]: Run as a client only on the given host name. + * which must be a name of the host running the program. + * + * @param args args for command + */ + public static void main( String[] args ) { + // override default argData + StandardTest st = new StandardTest() ; + testBase = new TestBase(args, ArgumentData.class, st ) ; + argData = testBase.getArguments( ArgumentData.class ) ; + + if (argData.mode() == TestMode.SERVER) { + if (argData.useJapex()) { + throw new IllegalArgumentException( + "This test does not run with Japex in server mode!" ) ; + } + } + + System.out.println( "Running StandardTest with arguments" ) ; + System.out.println( argData ) ; + System.out.println( "-----------------------------------------------" ) ; + + if (argData.useJapex()) { + System.out.println( "Running with japex" ) ; + String[] jargs = { "test.xml" } ; + + // This will re-use the static argData when it creates a new StandardTest + // as a Japex driver. + com.sun.japex.Japex.main( jargs ) ; + } else { + System.out.println( "Running standalone" ) ; + st.standaloneRun() ; + } + } +} diff --git a/test/disabled/performance/eesample/echoArray.xml b/test/disabled/performance/eesample/echoArray.xml new file mode 100644 index 000000000..84591a1a0 --- /dev/null +++ b/test/disabled/performance/eesample/echoArray.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/disabled/performance/eesample/echoArrayFragmentSize.xml b/test/disabled/performance/eesample/echoArrayFragmentSize.xml new file mode 100644 index 000000000..89cf18b5e --- /dev/null +++ b/test/disabled/performance/eesample/echoArrayFragmentSize.xml @@ -0,0 +1,234 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/disabled/performance/eesample/results_with_fragment_size.txt b/test/disabled/performance/eesample/results_with_fragment_size.txt new file mode 100644 index 000000000..55cd1cb35 --- /dev/null +++ b/test/disabled/performance/eesample/results_with_fragment_size.txt @@ -0,0 +1,186 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Test run on host gemini (dual CPU SunBlade 2500, Solaris 10, 2 GB RAM) +JDK 6 (b87 RC 1) -server + +-Dorg.omg.CORBA.ORBClass=com.sun.corba.ee.impl.orb.ORBImpl -Dorg.omg.CORBA.ORBSingletonClass=com.sun.corba.ee.impl.orb.ORBSingleton -Djavax.rmi.CORBA.PortableRemoteObjectClass=com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject -Djavax.rmi.CORBA.StubClass=com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl -Djavax.rmi.CORBA.UtilClass=com.sun.corba.ee.impl.javax.rmi.CORBA.Util -Xms400m -Xmx600m -server -ea -verbose:gc -verbose:class -classpath .:/volumes/ws/oss-work/build/classes:/volumes/ws/oss-work/test/build/classes:/volumes/ws/oss-work/optional/build/classes:/volumes/ws/oss-work/optional/test/build/classes:/volumes/ws/oss-work/lib/ejb-2_1-api.jar:/volumes/ws/oss-work/lib/testng.jar:/volumes/ws/oss-work/lib/junit.jar:/volumes/ws/oss-work/lib/antlr.jar:/volumes/ws/oss-work/lib/stringtemplate.jar:/volumes/IDE/optimizeit/OptimizeitSuite/lib/optit.jar -Xbootclasspath/p:/volumes/ws/oss-work/build/classes:/volumes/ws/oss-work/test/build/classes:/volumes/ws/oss-work/optional/build/classes:/volumes/ws/oss-work/optional/test/build/classes performance.eesample.StandardTest +Int copy elapsed time: 219.39408319999998 microseconds +[TotalGC 0.225281 secs] +Data copy elapsed time: 14862.646686 microseconds +[TotalGC 0.600715 secs] +[TotalGC 0.0020102 secs] +[TotalGC 0.068441 secs] +Echo Test Default Transport on objref testref/cache : 821.4987326 microseconds +[TotalGC 0.0142518 secs] +Echo Test Default Transport on objref testref/nocache : 436.91754960000003 microseconds +[TotalGC 0.0404662 secs] +[TotalGC 0.0094307 secs] +GetData Test Default Transport on objref testref/cache : 21021.572296799997 microseconds +[TotalGC 1.79827 secs] +GetData Test Default Transport on objref testref/nocache : 20960.8428966 microseconds +[TotalGC 1.84664 secs] +[TotalGC 0.0015715 secs] +GetDataArray Test Default Transport on objref testref/cache : 12989.5854542 microseconds +[TotalGC 1.20065 secs] +GetDataArray Test Default Transport on objref testref/nocache : 12997.6811874 microseconds +[TotalGC 1.22869 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 101.809833 microseconds +[TotalGC 0.0065689 secs] +Data copy elapsed time: 15597.3039518 microseconds +[TotalGC 1.42784 secs] +Echo Test Default transport(2048) on objref testref/cache : 531.761283 microseconds +[TotalGC 0.0451639 secs] +Echo Test Default transport(2048) on objref testref/nocache : 429.3830662 microseconds +[TotalGC 0.0306764 secs] +GetData Test Default transport(2048) on objref testref/cache : 22887.249961399997 microseconds +[TotalGC 2.04926 secs] +GetData Test Default transport(2048) on objref testref/nocache : 22977.3592614 microseconds +[TotalGC 1.88395 secs] +GetDataArray Test Default transport(2048) on objref testref/cache : 15160.3574856 microseconds +[TotalGC 1.35414 secs] +GetDataArray Test Default transport(2048) on objref testref/nocache : 15191.7683688 microseconds +[TotalGC 1.33456 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 94.8997168 microseconds +[TotalGC 0.002221 secs] +Data copy elapsed time: 15520.910185 microseconds +[TotalGC 1.15748 secs] +Echo Test Default transport(3072) on objref testref/cache : 422.466483 microseconds +[TotalGC 0.0480068 secs] +Echo Test Default transport(3072) on objref testref/nocache : 429.9586494 microseconds +[TotalGC 0.0305862 secs] +GetData Test Default transport(3072) on objref testref/cache : 25999.005475 microseconds +[TotalGC 2.27856 secs] +GetData Test Default transport(3072) on objref testref/nocache : 25987.5119084 microseconds +[TotalGC 2.21255 secs] +GetDataArray Test Default transport(3072) on objref testref/cache : 18510.2882324 microseconds +[TotalGC 1.76318 secs] +GetDataArray Test Default transport(3072) on objref testref/nocache : 18511.1967326 microseconds +[TotalGC 1.68951 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 95.47168339999999 microseconds +[TotalGC 0.0042034 secs] +Data copy elapsed time: 15510.2841186 microseconds +[TotalGC 1.01441 secs] +Echo Test Default transport(4096) on objref testref/cache : 441.2467496 microseconds +[TotalGC 0.0344736 secs] +Echo Test Default transport(4096) on objref testref/nocache : 397.9776662 microseconds +[TotalGC 0.0376028 secs] +GetData Test Default transport(4096) on objref testref/cache : 29486.7608884 microseconds +[TotalGC 2.69182 secs] +GetData Test Default transport(4096) on objref testref/nocache : 29394.479638599998 microseconds +[TotalGC 2.55701 secs] +GetDataArray Test Default transport(4096) on objref testref/cache : 21824.5985792 microseconds +[TotalGC 1.84105 secs] +GetDataArray Test Default transport(4096) on objref testref/nocache : 21843.740245999998 microseconds +[TotalGC 1.91242 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 110.1054666 microseconds +[TotalGC 0.0024977 secs] +Data copy elapsed time: 15502.5843518 microseconds +[TotalGC 0.996387 secs] +Echo Test Blocking transport on objref testref/cache : 377.7880164 microseconds +[TotalGC 0.0392961 secs] +Echo Test Blocking transport on objref testref/nocache : 335.515783 microseconds +[TotalGC 0.0225093 secs] +GetData Test Blocking transport on objref testref/cache : 18220.433182599998 microseconds +[TotalGC 1.36718 secs] +GetData Test Blocking transport on objref testref/nocache : 18142.737065999998 microseconds +[TotalGC 1.4887 secs] +GetDataArray Test Blocking transport on objref testref/cache : 10652.1514066 microseconds +[TotalGC 0.963383 secs] +GetDataArray Test Blocking transport on objref testref/nocache : 10680.3795898 microseconds +[TotalGC 0.924922 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 95.7356666 microseconds +[TotalGC 0.0168946 secs] +Data copy elapsed time: 15550.845852 microseconds +[TotalGC 1.09894 secs] +Echo Test Blocking transport(2048) on objref testref/cache : 312.750983 microseconds +[TotalGC 0.0456871 secs] +Echo Test Blocking transport(2048) on objref testref/nocache : 324.89993300000003 microseconds +[TotalGC 0.0167966 secs] +GetData Test Blocking transport(2048) on objref testref/cache : 21249.264996399997 microseconds +[TotalGC 1.83731 secs] +GetData Test Blocking transport(2048) on objref testref/nocache : 21280.7404296 microseconds +[TotalGC 1.94708 secs] +GetDataArray Test Blocking transport(2048) on objref testref/cache : 13955.33562 microseconds +[TotalGC 1.413 secs] +GetDataArray Test Blocking transport(2048) on objref testref/nocache : 13923.23407 microseconds +[TotalGC 1.23519 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 94.2626666 microseconds +[TotalGC 0.0042321 secs] +Data copy elapsed time: 15547.7990852 microseconds +[TotalGC 1.11962 secs] +Echo Test Blocking transport(3072) on objref testref/cache : 315.58251640000003 microseconds +[TotalGC 0.0367393 secs] +Echo Test Blocking transport(3072) on objref testref/nocache : 315.4486662 microseconds +[TotalGC 0.0256397 secs] +GetData Test Blocking transport(3072) on objref testref/cache : 24738.4447432 microseconds +[TotalGC 2.17788 secs] +GetData Test Blocking transport(3072) on objref testref/nocache : 24834.7994928 microseconds +[TotalGC 2.19321 secs] +GetDataArray Test Blocking transport(3072) on objref testref/cache : 17640.2472332 microseconds +[TotalGC 1.70161 secs] +GetDataArray Test Blocking transport(3072) on objref testref/nocache : 17584.1825166 microseconds +[TotalGC 1.60563 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. +Int copy elapsed time: 104.4890166 microseconds +[TotalGC 0.0115538 secs] +Data copy elapsed time: 15524.128068600001 microseconds +[TotalGC 1.09751 secs] +Echo Test Blocking transport(4096) on objref testref/cache : 344.0298998 microseconds +[TotalGC 0.0255125 secs] +Echo Test Blocking transport(4096) on objref testref/nocache : 339.3911998 microseconds +[TotalGC 0.029843 secs] +GetData Test Blocking transport(4096) on objref testref/cache : 28500.3408228 microseconds +[TotalGC 2.64356 secs] +GetData Test Blocking transport(4096) on objref testref/nocache : 28525.6265896 microseconds +[TotalGC 2.66815 secs] +GetDataArray Test Blocking transport(4096) on objref testref/cache : 21122.5719298 microseconds +[TotalGC 2.02667 secs] +GetDataArray Test Blocking transport(4096) on objref testref/nocache : 21141.0109798 microseconds +[TotalGC 2.03743 secs] +Shutting down clientORB +Destroying clientORB +Shutting down serverORB +Destroying serverORB +Test Complete. diff --git a/test/disabled/performance/eesample/test.xml b/test/disabled/performance/eesample/test.xml new file mode 100644 index 000000000..38977c843 --- /dev/null +++ b/test/disabled/performance/eesample/test.xml @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/disabled/performance/eesample/wspex/Address.java b/test/disabled/performance/eesample/wspex/Address.java new file mode 100644 index 000000000..47d4c90e6 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Address.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class Address implements Serializable { + + protected String firstName; + protected String lastName; + protected String address1; + protected String address2; + protected String city; + protected String state; + protected String zip; + + /** + * Gets the value of the firstName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getFirstName() { + return firstName; + } + + /** + * Sets the value of the firstName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setFirstName(String value) { + this.firstName = value; + } + + /** + * Gets the value of the lastName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLastName() { + return lastName; + } + + /** + * Sets the value of the lastName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLastName(String value) { + this.lastName = value; + } + + /** + * Gets the value of the address1 property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAddress1() { + return address1; + } + + /** + * Sets the value of the address1 property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAddress1(String value) { + this.address1 = value; + } + + /** + * Gets the value of the address2 property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAddress2() { + return address2; + } + + /** + * Sets the value of the address2 property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAddress2(String value) { + this.address2 = value; + } + + /** + * Gets the value of the city property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCity() { + return city; + } + + /** + * Sets the value of the city property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCity(String value) { + this.city = value; + } + + /** + * Gets the value of the state property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getState() { + return state; + } + + /** + * Sets the value of the state property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setState(String value) { + this.state = value; + } + + /** + * Gets the value of the zip property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getZip() { + return zip; + } + + /** + * Sets the value of the zip property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setZip(String value) { + this.zip = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/ArrayOfLineItem.java b/test/disabled/performance/eesample/wspex/ArrayOfLineItem.java new file mode 100644 index 000000000..4d797af75 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/ArrayOfLineItem.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class ArrayOfLineItem implements Serializable { + + protected List lineItem; + + /** + * Gets the value of the lineItem property. + * + *

                + * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the lineItem property. + * + *

                + * For example, to add a new item, do as follows: + *

                +     *    getLineItem().add(newItem);
                +     * 
                + * + * + *

                + * Objects of the following type(s) are allowed in the list + * {@link LineItem } + * + * + */ + public List getLineItem() { + if (lineItem == null) { + lineItem = new ArrayList(); + } + return this.lineItem; + } + +} diff --git a/test/disabled/performance/eesample/wspex/Customer.java b/test/disabled/performance/eesample/wspex/Customer.java new file mode 100644 index 000000000..e3f3dbf06 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Customer.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; +import javax.xml.datatype.XMLGregorianCalendar; + +public class Customer implements Serializable { + + protected int customerId; + protected String contactFirstName; + protected String contactLastName; + protected String contactPhone; + protected XMLGregorianCalendar lastActivityDate; + protected String creditCardNumber; + protected String creditCardExpirationDate; + protected Address billingAddress; + protected Address shippingAddress; + + /** + * Gets the value of the customerId property. + * + */ + public int getCustomerId() { + return customerId; + } + + /** + * Sets the value of the customerId property. + * + */ + public void setCustomerId(int value) { + this.customerId = value; + } + + /** + * Gets the value of the contactFirstName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getContactFirstName() { + return contactFirstName; + } + + /** + * Sets the value of the contactFirstName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setContactFirstName(String value) { + this.contactFirstName = value; + } + + /** + * Gets the value of the contactLastName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getContactLastName() { + return contactLastName; + } + + /** + * Sets the value of the contactLastName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setContactLastName(String value) { + this.contactLastName = value; + } + + /** + * Gets the value of the contactPhone property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getContactPhone() { + return contactPhone; + } + + /** + * Sets the value of the contactPhone property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setContactPhone(String value) { + this.contactPhone = value; + } + + /** + * Gets the value of the lastActivityDate property. + * + * @return + * possible object is + * {@link XMLGregorianCalendar } + * + */ + public XMLGregorianCalendar getLastActivityDate() { + return lastActivityDate; + } + + /** + * Sets the value of the lastActivityDate property. + * + * @param value + * allowed object is + * {@link XMLGregorianCalendar } + * + */ + public void setLastActivityDate(XMLGregorianCalendar value) { + this.lastActivityDate = value; + } + + /** + * Gets the value of the creditCardNumber property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCreditCardNumber() { + return creditCardNumber; + } + + /** + * Sets the value of the creditCardNumber property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCreditCardNumber(String value) { + this.creditCardNumber = value; + } + + /** + * Gets the value of the creditCardExpirationDate property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCreditCardExpirationDate() { + return creditCardExpirationDate; + } + + /** + * Sets the value of the creditCardExpirationDate property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCreditCardExpirationDate(String value) { + this.creditCardExpirationDate = value; + } + + /** + * Gets the value of the billingAddress property. + * + * @return + * possible object is + * {@link Address } + * + */ + public Address getBillingAddress() { + return billingAddress; + } + + /** + * Sets the value of the billingAddress property. + * + * @param value + * allowed object is + * {@link Address } + * + */ + public void setBillingAddress(Address value) { + this.billingAddress = value; + } + + /** + * Gets the value of the shippingAddress property. + * + * @return + * possible object is + * {@link Address } + * + */ + public Address getShippingAddress() { + return shippingAddress; + } + + /** + * Sets the value of the shippingAddress property. + * + * @param value + * allowed object is + * {@link Address } + * + */ + public void setShippingAddress(Address value) { + this.shippingAddress = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/EchoOrderRequest.java b/test/disabled/performance/eesample/wspex/EchoOrderRequest.java new file mode 100644 index 000000000..aa1c8a7bd --- /dev/null +++ b/test/disabled/performance/eesample/wspex/EchoOrderRequest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class EchoOrderRequest implements Serializable { + + protected Order echoOrderRequest; + + /** + * Gets the value of the echoOrderRequest property. + * + * @return + * possible object is + * {@link Order } + * + */ + public Order getEchoOrderRequest() { + return echoOrderRequest; + } + + /** + * Sets the value of the echoOrderRequest property. + * + * @param value + * allowed object is + * {@link Order } + * + */ + public void setEchoOrderRequest(Order value) { + this.echoOrderRequest = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/EchoOrderResponse.java b/test/disabled/performance/eesample/wspex/EchoOrderResponse.java new file mode 100644 index 000000000..cbaf5a42f --- /dev/null +++ b/test/disabled/performance/eesample/wspex/EchoOrderResponse.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class EchoOrderResponse implements Serializable { + + protected Order echoOrderResponse; + + /** + * Gets the value of the echoOrderResponse property. + * + * @return + * possible object is + * {@link Order } + * + */ + public Order getEchoOrderResponse() { + return echoOrderResponse; + } + + /** + * Sets the value of the echoOrderResponse property. + * + * @param value + * allowed object is + * {@link Order } + * + */ + public void setEchoOrderResponse(Order value) { + this.echoOrderResponse = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/Item.java b/test/disabled/performance/eesample/wspex/Item.java new file mode 100644 index 000000000..4e13c26b8 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Item.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; +import javax.xml.datatype.XMLGregorianCalendar; + +public class Item implements Serializable { + + protected String id; + protected String description; + protected float price; + protected int inventory; + protected Location location; + protected XMLGregorianCalendar creationdate; + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the description property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDescription() { + return description; + } + + /** + * Sets the value of the description property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDescription(String value) { + this.description = value; + } + + /** + * Gets the value of the price property. + * + */ + public float getPrice() { + return price; + } + + /** + * Sets the value of the price property. + * + */ + public void setPrice(float value) { + this.price = value; + } + + /** + * Gets the value of the inventory property. + * + */ + public int getInventory() { + return inventory; + } + + /** + * Sets the value of the inventory property. + * + */ + public void setInventory(int value) { + this.inventory = value; + } + + /** + * Gets the value of the location property. + * + * @return + * possible object is + * {@link Location } + * + */ + public Location getLocation() { + return location; + } + + /** + * Sets the value of the location property. + * + * @param value + * allowed object is + * {@link Location } + * + */ + public void setLocation(Location value) { + this.location = value; + } + + /** + * Gets the value of the creationdate property. + * + * @return + * possible object is + * {@link XMLGregorianCalendar } + * + */ + public XMLGregorianCalendar getCreationdate() { + return creationdate; + } + + /** + * Sets the value of the creationdate property. + * + * @param value + * allowed object is + * {@link XMLGregorianCalendar } + * + */ + public void setCreationdate(XMLGregorianCalendar value) { + this.creationdate = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/ItemArrayType.java b/test/disabled/performance/eesample/wspex/ItemArrayType.java new file mode 100644 index 000000000..46aab772e --- /dev/null +++ b/test/disabled/performance/eesample/wspex/ItemArrayType.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class ItemArrayType implements Serializable { + + protected List items; + + /** + * Gets the value of the items property. + * + *

                + * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the items property. + * + *

                + * For example, to add a new item, do as follows: + *

                +     *    getItems().add(newItem);
                +     * 
                + * + * + *

                + * Objects of the following type(s) are allowed in the list + * {@link Item } + * + * + */ + public List getItems() { + if (items == null) { + items = new ArrayList(); + } + return this.items; + } + +} diff --git a/test/disabled/performance/eesample/wspex/LineItem.java b/test/disabled/performance/eesample/wspex/LineItem.java new file mode 100644 index 000000000..5f2cf0551 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/LineItem.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class LineItem implements Serializable { + + protected int orderId; + protected int itemId; + protected int productId; + protected String productDescription; + protected int orderQuantity; + protected float unitPrice; + + /** + * Gets the value of the orderId property. + * + */ + public int getOrderId() { + return orderId; + } + + /** + * Sets the value of the orderId property. + * + */ + public void setOrderId(int value) { + this.orderId = value; + } + + /** + * Gets the value of the itemId property. + * + */ + public int getItemId() { + return itemId; + } + + /** + * Sets the value of the itemId property. + * + */ + public void setItemId(int value) { + this.itemId = value; + } + + /** + * Gets the value of the productId property. + * + */ + public int getProductId() { + return productId; + } + + /** + * Sets the value of the productId property. + * + */ + public void setProductId(int value) { + this.productId = value; + } + + /** + * Gets the value of the productDescription property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProductDescription() { + return productDescription; + } + + /** + * Sets the value of the productDescription property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProductDescription(String value) { + this.productDescription = value; + } + + /** + * Gets the value of the orderQuantity property. + * + */ + public int getOrderQuantity() { + return orderQuantity; + } + + /** + * Sets the value of the orderQuantity property. + * + */ + public void setOrderQuantity(int value) { + this.orderQuantity = value; + } + + /** + * Gets the value of the unitPrice property. + * + */ + public float getUnitPrice() { + return unitPrice; + } + + /** + * Sets the value of the unitPrice property. + * + */ + public void setUnitPrice(float value) { + this.unitPrice = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/Location.java b/test/disabled/performance/eesample/wspex/Location.java new file mode 100644 index 000000000..b08a200a6 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Location.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class Location implements Serializable { + + protected String id; + protected String description; + protected String address; + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the description property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDescription() { + return description; + } + + /** + * Sets the value of the description property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDescription(String value) { + this.description = value; + } + + /** + * Gets the value of the address property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAddress() { + return address; + } + + /** + * Sets the value of the address property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAddress(String value) { + this.address = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/Order.java b/test/disabled/performance/eesample/wspex/Order.java new file mode 100644 index 000000000..ec2cb4809 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Order.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; +import javax.xml.datatype.XMLGregorianCalendar; + +public class Order implements Serializable { + + protected int orderId; + protected int orderStatus; + protected XMLGregorianCalendar orderDate; + protected float orderTotalAmount; + protected Customer customer; + protected ArrayOfLineItem lineItems; + + /** + * Gets the value of the orderId property. + * + */ + public int getOrderId() { + return orderId; + } + + /** + * Sets the value of the orderId property. + * + */ + public void setOrderId(int value) { + this.orderId = value; + } + + /** + * Gets the value of the orderStatus property. + * + */ + public int getOrderStatus() { + return orderStatus; + } + + /** + * Sets the value of the orderStatus property. + * + */ + public void setOrderStatus(int value) { + this.orderStatus = value; + } + + /** + * Gets the value of the orderDate property. + * + * @return + * possible object is + * {@link XMLGregorianCalendar } + * + */ + public XMLGregorianCalendar getOrderDate() { + return orderDate; + } + + /** + * Sets the value of the orderDate property. + * + * @param value + * allowed object is + * {@link XMLGregorianCalendar } + * + */ + public void setOrderDate(XMLGregorianCalendar value) { + this.orderDate = value; + } + + /** + * Gets the value of the orderTotalAmount property. + * + */ + public float getOrderTotalAmount() { + return orderTotalAmount; + } + + /** + * Sets the value of the orderTotalAmount property. + * + */ + public void setOrderTotalAmount(float value) { + this.orderTotalAmount = value; + } + + /** + * Gets the value of the customer property. + * + * @return + * possible object is + * {@link Customer } + * + */ + public Customer getCustomer() { + return customer; + } + + /** + * Sets the value of the customer property. + * + * @param value + * allowed object is + * {@link Customer } + * + */ + public void setCustomer(Customer value) { + this.customer = value; + } + + /** + * Gets the value of the lineItems property. + * + * @return + * possible object is + * {@link ArrayOfLineItem } + * + */ + public ArrayOfLineItem getLineItems() { + return lineItems; + } + + /** + * Sets the value of the lineItems property. + * + * @param value + * allowed object is + * {@link ArrayOfLineItem } + * + */ + public void setLineItems(ArrayOfLineItem value) { + this.lineItems = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/Struct.java b/test/disabled/performance/eesample/wspex/Struct.java new file mode 100644 index 000000000..72db83d96 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Struct.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class Struct implements Serializable { + + protected int varInt; + protected float varFloat; + protected String varString; + + /** + * Gets the value of the varInt property. + * + */ + public int getVarInt() { + return varInt; + } + + /** + * Sets the value of the varInt property. + * + */ + public void setVarInt(int value) { + this.varInt = value; + } + + /** + * Gets the value of the varFloat property. + * + */ + public float getVarFloat() { + return varFloat; + } + + /** + * Sets the value of the varFloat property. + * + */ + public void setVarFloat(float value) { + this.varFloat = value; + } + + /** + * Gets the value of the varString property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVarString() { + return varString; + } + + /** + * Sets the value of the varString property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVarString(String value) { + this.varString = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/Synthetic.java b/test/disabled/performance/eesample/wspex/Synthetic.java new file mode 100644 index 000000000..2dad12eb6 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/Synthetic.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex ; + +import java.io.Serializable; + +public class Synthetic implements Serializable { + + protected String str; + protected Struct s; + protected byte[] bytes; + + /** + * Gets the value of the str property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getStr() { + return str; + } + + /** + * Sets the value of the str property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setStr(String value) { + this.str = value; + } + + /** + * Gets the value of the s property. + * + * @return + * possible object is + * {@link Struct } + * + */ + public Struct getS() { + return s; + } + + /** + * Sets the value of the s property. + * + * @param value + * allowed object is + * {@link Struct } + * + */ + public void setS(Struct value) { + this.s = value; + } + + /** + * Gets the value of the bytes property. + * + * @return + * possible object is + * byte[] + */ + public byte[] getBytes() { + return bytes; + } + + /** + * Sets the value of the bytes property. + * + * @param value + * allowed object is + * byte[] + */ + public void setBytes(byte[] value) { + this.bytes = value; + } + +} diff --git a/test/disabled/performance/eesample/wspex/components/OrderBL.java b/test/disabled/performance/eesample/wspex/components/OrderBL.java new file mode 100644 index 000000000..5c30b4fc4 --- /dev/null +++ b/test/disabled/performance/eesample/wspex/components/OrderBL.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.eesample.wspex.components; + +import performance.eesample.wspex.*; + +import java.util.*; +import javax.xml.datatype.DatatypeConstants; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; + +public class OrderBL { + + static DatatypeFactory df; + + public OrderBL() { + } + + public Order GetOrder(int orderId, int customerId) { + int id = 1; + + Address ship = new Address(); + ship.setFirstName("Ship FirstName "+ id); + ship.setLastName("Ship LastName " + id); + ship.setAddress1( "Ship StreetAddres " + id); + ship.setAddress2("Street Address Line 2 " + id); + ship.setCity( "City " + id); + ship.setState( "State " + id); + ship.setZip( "12345"); + + Address bill = new Address(); + bill.setFirstName("Bill FirstName "+ id); + bill.setLastName("Bill LastName " + id); + bill.setAddress1( "Bill StreetAddres " + id); + bill.setAddress2("Street Address Line 2 " + id); + bill.setCity( "City " + id); + bill.setState( "State " + id); + bill.setZip( "12345"); + + Customer customer = new Customer(); + customer.setCustomerId(customerId) ; + customer.setContactFirstName("FirstName " + id); + customer.setContactLastName( "LastName " + id); + customer.setContactPhone(Integer.toString(id)); + + try { + if( df == null ) + df = DatatypeFactory.newInstance(); + } + catch(javax.xml.datatype.DatatypeConfigurationException ex) { + } + + XMLGregorianCalendar date = df.newXMLGregorianCalendar(); + date.setYear(2005); + date.setMonth(DatatypeConstants.MARCH); + date.setDay(29); + date.setTime(11,11,11); + + customer.setLastActivityDate(date) ; + customer.setCreditCardNumber(""+id); + customer.setCreditCardExpirationDate( ""+id) ; + customer.setBillingAddress(bill) ; + customer.setShippingAddress(ship) ; + + int numberLineItems = 50; + ArrayOfLineItem linearray = new ArrayOfLineItem(); + List lines = linearray.getLineItem(); + + for(int i = 0; i < numberLineItems; i++) { + LineItem line = new LineItem(); + line.setOrderId(orderId); + line.setItemId(i+1); + line.setProductId(i); + line.setProductDescription("Test Product " +i); + line.setOrderQuantity(1); + line.setUnitPrice((float) 1.00); + + lines.add(line); + } + + Order order = new Order(); + order.setOrderId(orderId); + order.setOrderStatus( 1); + order.setOrderDate(date); + order.setOrderTotalAmount((float) 50); + order.setCustomer(customer); + order.setLineItems(linearray); + return order; + } +} + diff --git a/test/disabled/performance/simpleperf/counterClient.java b/test/disabled/performance/simpleperf/counterClient.java new file mode 100644 index 000000000..563413ca8 --- /dev/null +++ b/test/disabled/performance/simpleperf/counterClient.java @@ -0,0 +1,396 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf; + +import java.io.PrintStream ; +import javax.rmi.PortableRemoteObject ; +import java.rmi.RemoteException ; +import java.util.Hashtable ; +import java.util.Map ; +import java.util.Properties ; + +import org.omg.CORBA.Policy ; +import org.omg.PortableServer.LifespanPolicyValue ; +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.POAPackage.AdapterAlreadyExists ; +import org.omg.PortableServer.POAPackage.InvalidPolicy ; +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.RequestProcessingPolicyValue ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantLocator ; +import org.omg.PortableServer.ServantRetentionPolicyValue ; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; + +import com.sun.corba.ee.spi.extension.ServantCachingPolicy ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; + +import com.sun.corba.ee.spi.copyobject.CopierManager ; +import com.sun.corba.ee.spi.copyobject.CopyobjectDefaults ; + +import com.sun.corba.ee.impl.orbutil.newtimer.generated.TimingPoints ; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import corba.framework.InternalProcess ; +import org.glassfish.pfl.dynamic.copyobject.spi.ObjectCopierFactory; +import org.glassfish.pfl.tf.timer.spi.Statistics; +import org.glassfish.pfl.tf.timer.spi.StatsEventHandler; +import org.glassfish.pfl.tf.timer.spi.Timer; +import org.glassfish.pfl.tf.timer.spi.TimerEventController; +import org.glassfish.pfl.tf.timer.spi.TimerEventHandler; +import org.glassfish.pfl.tf.timer.spi.TimerFactory; +import org.glassfish.pfl.tf.timer.spi.TimerManager; + +public class counterClient implements InternalProcess +{ + private static final boolean DEBUG = false ; + + private POA createPOA( ORB org, POA rootPOA ) throws AdapterAlreadyExists, InvalidPolicy, + WrongPolicy, RemoteException + { + Policy[] tpolicy = new Policy[3]; + tpolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + tpolicy[2] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN) ; + + POA tpoa = rootPOA.create_POA("POA", rootPOA.the_POAManager(), tpolicy); + counterImpl impl = new counterImpl(); + Servant servant = (Servant)(javax.rmi.CORBA.Util.getTie( impl ) ) ; + CounterServantLocator csl = new CounterServantLocator(servant); + tpoa.set_servant_manager(csl); + + return tpoa ; + } + + private POA createSCPOA( ORB org, POA rootPOA, int sctype ) throws AdapterAlreadyExists, InvalidPolicy, + WrongPolicy, RemoteException + { + Policy[] tpolicy = new Policy[4]; + tpolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + tpolicy[2] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN) ; + + switch (sctype) { + case ServantCachingPolicy.FULL_SEMANTICS : + tpolicy[3] = ServantCachingPolicy.getFullPolicy() ; + break ; + case ServantCachingPolicy.INFO_ONLY_SEMANTICS : + tpolicy[3] = ServantCachingPolicy.getInfoOnlyPolicy() ; + break ; + case ServantCachingPolicy.MINIMAL_SEMANTICS : + tpolicy[3] = ServantCachingPolicy.getMinimalPolicy() ; + break ; + } + + POA tpoa = rootPOA.create_POA( "SCPOA" + sctype, rootPOA.the_POAManager(), tpolicy); + counterImpl impl = new counterImpl(); + Servant servant = (Servant)(javax.rmi.CORBA.Util.getTie( impl ) ) ; + CounterServantLocator csl = new CounterServantLocator(servant); + tpoa.set_servant_manager(csl); + + return tpoa ; + } + + private counterIF createCounter(ORB orb, POA tpoa) + { + // create an objref using POA + byte[] id = "abcdef".getBytes(); + String intf = "" ; // new _counterImpl_Tie()._all_interfaces(tpoa,id)[0]; + + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, intf); + + counterIF counterRef + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + return counterRef ; + } + + private counterIF lookupDifferentORBCounter( ORB orb, ORB orb2, POA tpoa ) + { + counterIF result = createCounter( orb, tpoa ) ; + + String str = orb.object_to_string( (org.omg.CORBA.Object)result ) ; + org.omg.CORBA.Object obj = orb2.string_to_object( str ) ; + + return (counterIF)PortableRemoteObject.narrow( obj, counterIF.class ) ; + } + + private counterIF lookupCounter( ORB orb, POA tpoa ) + { + counterIF result = createCounter( orb, tpoa ) ; + + org.omg.CORBA.Object obj ; + + /* + try { + NamingContextExt nc = NamingContextExtHelper.narrow( + orb.resolve_initial_references( "NameService" ) ) ; + + NameComponent[] name = nc.to_name( "FooObject" ) ; + nc.rebind( name, (org.omg.CORBA.Object)result ) ; + obj = nc.resolve( name ) ; + } catch (Exception exc) { + System.out.println( exc ) ; + exc.printStackTrace() ; + return null ; + } + */ + + String str = orb.object_to_string( (org.omg.CORBA.Object)result ) ; + obj = orb.string_to_object( str ) ; + + return (counterIF)PortableRemoteObject.narrow( obj, counterIF.class ) ; + } + + private static final int WARMUP = 10000 ; + private static final int COUNT = 2000 ; + + private void warmup( counterIF counterRef ) + throws RemoteException { + + long value = 0 ; + + for (int i = 0; i < WARMUP; i++) { + value += counterRef.increment(1); + } + } + + private void performTest(PrintStream out, counterIF counterRef, + String testType ) throws RemoteException + { + long value = 0 ; + long time = System.nanoTime() ; + + for (int i = 0; i < COUNT; i++) { + value += counterRef.increment(1); + } + + double elapsed = System.nanoTime() - time ; + + out.println( "Test " + testType + " : " + (elapsed/COUNT)/1000 ) ; + } + + private ORB initORB( String id, String[] args, Properties environment ) + { + // create and initialize the ORB + environment.setProperty( ORBConstants.TIMING_POINTS_ENABLED, + "true" ) ; + environment.setProperty( ORBConstants.ALLOW_LOCAL_OPTIMIZATION, + "true" ) ; + if (DEBUG) { + environment.setProperty( "com.sun.corba.ee.ORBDebug", + "subcontract" ) ; + } + environment.setProperty( ORBConstants.ORB_ID_PROPERTY, id ) ; + ORB orb = (ORB)org.omg.CORBA.ORB.init(args, environment); + + // Use the optimized reflective object copier for this test + ObjectCopierFactory ocf = CopyobjectDefaults.makeReflectObjectCopierFactory( orb ) ; + CopierManager cm = orb.getCopierManager() ; + int defaultId = cm.getDefaultId() ; + cm.registerObjectCopierFactory( ocf, defaultId ) ; + + System.out.println( "Using optimized reflective copier" ) ; + + return orb ; + } + + private class DataBlock { + TimerEventController controller ; + Timer top ; + TimingPoints tp ; + StatsEventHandler seh ; + } + + private DataBlock startTiming( ORB orb ) { + DataBlock db = new DataBlock() ; + TimerManager tm = orb.makeTimerManager( + TimingPoints.class ) ; + db.tp = tm.points() ; + TimerFactory tf = tm.factory() ; + db.controller = tm.controller() ; + db.top = tf.makeTimer( "top", "Total time spent for making " + + COUNT + " non-colocated invocations in the same VM" ) ; + db.seh = tf.makeMultiThreadedStatsEventHandler( orb.getORBData().getORBId() ) ; + db.controller.register( db.seh ) ; + + if (DEBUG) { + TimerEventHandler tracingHandler = + tf.makeTracingEventHandler( "DEBUG" ) ; + db.controller.register( tracingHandler ) ; + } + + db.top.enable() ; + + // Enabled everything in the invocation path. + db.tp.DynamicType().enable() ; + db.tp.Transport().enable() ; + db.tp.Giop().enable() ; + db.tp.TraceServiceContext().enable() ; + db.tp.Cdr().enable() ; + + db.seh.clear() ; + + db.controller.enter( db.top ) ; + return db ; + } + + private void stopTiming( DataBlock db ) { + db.controller.exit( db.top ) ; + + db.top.disable() ; + db.tp.Cdr().disable() ; + db.tp.DynamicType().disable() ; + + // Dump out timing results. + Map result = db.seh.stats() ; + // TimerUtils.writeHtmlTable( result, db.seh.name() + "TimingData.html", + // "Timing Data for making " + COUNT + // + " non-colocated calls in the same VM (" + // + db.seh.name() + ")" ) ; + } + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + environment.list(out); + + try { + ORB orb = initORB( "MainORB", args, environment ) ; + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + POA poa = createPOA(orb, rootPOA); + POA scpoa = createSCPOA(orb, rootPOA, ServantCachingPolicy.FULL_SEMANTICS ); + POA iiscpoa = createSCPOA(orb, rootPOA, ServantCachingPolicy.INFO_ONLY_SEMANTICS ); + POA minscpoa = createSCPOA(orb, rootPOA, ServantCachingPolicy.MINIMAL_SEMANTICS ); + + out.println( "Times per invocation in microseconds:" ) ; + out.println( + "-------------------------------------------------------------" ) ; + counterIF counterRef1 = createCounter( orb, poa ) ; + warmup( counterRef1 ) ; + performTest(out, counterRef1, "local POA" ); + testIsLocal( counterRef1, true ) ; + + counterIF counterRef2 = createCounter( orb, scpoa ) ; + + warmup( counterRef2 ) ; + performTest(out, counterRef2, "local POA (full servant caching)" ); + testIsLocal( counterRef2, true ) ; + + counterIF counterRef3 = lookupCounter( orb, scpoa ) ; + warmup( counterRef3 ) ; + performTest(out, counterRef3, "local POA (full servant caching) after resolve" ) ; + testIsLocal( counterRef3, true ) ; + + counterIF counterRef4 = createCounter( orb, iiscpoa ) ; + warmup( counterRef4 ) ; + performTest(out, counterRef4, "local POA (info only servant caching)" ); + testIsLocal( counterRef4, true ) ; + + counterIF counterRef5 = lookupCounter( orb, iiscpoa ) ; + warmup( counterRef5 ) ; + performTest(out, counterRef5, "local POA (info only servant caching) after resolve" ); + testIsLocal( counterRef5, true ) ; + + counterIF counterRef6 = createCounter( orb, minscpoa ) ; + warmup( counterRef6 ) ; + performTest(out, counterRef6, "local POA (minimal servant caching)" ); + testIsLocal( counterRef6, true ) ; + + counterIF counterRef7 = lookupCounter( orb, minscpoa ) ; + warmup( counterRef7 ) ; + performTest(out, counterRef7, "local POA (minimal servant caching) after resolve" ); + testIsLocal( counterRef7, true ) ; + + // Note that orb2 is the client ORB + ORB orb2 = initORB( "SecondORB", args, environment); + counterIF counterRef8 = lookupDifferentORBCounter( orb, orb2, scpoa ) ; + + warmup( counterRef8 ) ; + DataBlock db2 = startTiming( orb2 ) ; + try { + performTest(out, counterRef8, + "local POA (full servant caching) after resolve in different ORB" ) ; + } finally { + // stopTiming( db ) ; + stopTiming( db2 ) ; + } + + testIsLocal( counterRef8, false ) ; + } catch (Exception e) { + e.printStackTrace(err); + throw e; + } + } + + private void testIsLocal( counterIF counter, boolean expectedResult ) throws Exception + { + if (StubAdapter.isLocal( counter ) != expectedResult) { + String msg ; + if (expectedResult) { + msg = "Error: expected local object, but is_local returned false"; + } else { + msg = "Error: expected remote object, but is_local returned true"; + } + throw new Exception( msg ) ; + } + } + + public static void main(String args[]) + { + try { + (new counterClient()).run(System.getProperties(), + args, + System.out, + System.err, + null); + + } catch (Exception e) { + System.err.println("ERROR : " + e) ; + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +class CounterServantLocator extends org.omg.CORBA.LocalObject implements ServantLocator +{ + Servant servant; + + CounterServantLocator(Servant servant) + { + this.servant = servant; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + return servant ; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + return; + } +} diff --git a/test/src/share/classes/alpha/bravo/A.idlref b/test/src/share/classes/alpha/bravo/A.idlref new file mode 100644 index 000000000..df2050846 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/A.idlref @@ -0,0 +1,22 @@ +/** + * alpha/bravo/A.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 12:33:02 GMT+00:00 + */ + +#ifndef __alpha_bravo_A__ +#define __alpha_bravo_A__ + +#include "orb.idl" + +module alpha { +module bravo { + + interface A { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/A.java b/test/src/share/classes/alpha/bravo/A.java new file mode 100644 index 000000000..64637a053 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/A.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public interface A extends java.rmi.Remote {} diff --git a/test/src/share/classes/alpha/bravo/AB.idlref b/test/src/share/classes/alpha/bravo/AB.idlref new file mode 100644 index 000000000..5171ab522 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/AB.idlref @@ -0,0 +1,26 @@ +/** + * alpha/bravo/AB.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 12:33:02 GMT+00:00 + */ + +#ifndef __alpha_bravo_AB__ +#define __alpha_bravo_AB__ + +#include "orb.idl" + +#include "alpha/bravo/DuckBill.idl" +#include "alpha/bravo/B.idl" +#include "alpha/bravo/A.idl" + +module alpha { +module bravo { + + interface AB: ::alpha::bravo::DuckBill, ::alpha::bravo::B, ::alpha::bravo::A { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/AB.java b/test/src/share/classes/alpha/bravo/AB.java new file mode 100644 index 000000000..c2d04f084 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/AB.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public abstract class AB extends javax.rmi.PortableRemoteObject + implements A, B, DuckBill { + public AB() throws java.rmi.RemoteException {} + +} diff --git a/test/src/share/classes/alpha/bravo/B.idlref b/test/src/share/classes/alpha/bravo/B.idlref new file mode 100644 index 000000000..af50b618d --- /dev/null +++ b/test/src/share/classes/alpha/bravo/B.idlref @@ -0,0 +1,22 @@ +/** + * alpha/bravo/B.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 12:33:02 GMT+00:00 + */ + +#ifndef __alpha_bravo_B__ +#define __alpha_bravo_B__ + +#include "orb.idl" + +module alpha { +module bravo { + + interface B { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/B.java b/test/src/share/classes/alpha/bravo/B.java new file mode 100644 index 000000000..375197064 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/B.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public interface B extends java.rmi.Remote {} diff --git a/test/src/share/classes/alpha/bravo/Bear.idlref b/test/src/share/classes/alpha/bravo/Bear.idlref new file mode 100644 index 000000000..bf81297b3 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Bear.idlref @@ -0,0 +1,29 @@ +/** + * alpha/bravo/Bear.idl + * Generated by rmic -idl. Do not edit + * 26 November 1998 11:05:54 GMT+00:00 + */ + +#ifndef __alpha_bravo_Bear__ +#define __alpha_bravo_Bear__ + +#include "orb.idl" +#include "java/lang/Ex.idl" + +module alpha { +module bravo { + + abstract interface Bear { + + long getSize( ); + void eat( ) raises ( + ::java::lang::Ex ); + void drink( ); + + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Bear.java b/test/src/share/classes/alpha/bravo/Bear.java new file mode 100644 index 000000000..f884b800a --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Bear.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public interface Bear { + public int getSize() throws java.rmi.RemoteException; + void eat() throws Exception; + void drink() throws java.rmi.RemoteException, + java.rmi.NoSuchObjectException; +} diff --git a/test/src/share/classes/alpha/bravo/Charlie.idlref b/test/src/share/classes/alpha/bravo/Charlie.idlref new file mode 100644 index 000000000..076fb6857 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Charlie.idlref @@ -0,0 +1,81 @@ +/** + * alpha/bravo/Charlie.idl + * Generated by rmic -idl. Do not edit + * 05 May 1999 16:10:32 GMT+00:00 + */ + +#include "java/io/Serializable.idl" +#include "org/omg/boxedRMI/omega/seq2_Hotel.idl" +#include "org/omg/boxedRMI/java/io/seq2_Serializable.idl" +#include "org/omg/boxedRMI/org/omg/boxedIDL/fake/omega/seq1_Kilo.idl" +#include "org/omg/boxedRMI/seq2_long_long.idl" +#include "org/omg/boxedRMI/omega/seq2_India.idl" +#include "org/omg/boxedRMI/omega/seq1_Juliet.idl" +#include "org/omg/boxedRMI/org/omg/CORBA/portable/seq1_IDLEntity.idl" +#include "org/omg/boxedRMI/javax/rmi/CORBA/seq1_ClassDesc.idl" +#include "org/omg/boxedRMI/seq1_Object.idl" +#include "org/omg/boxedRMI/java/io/seq1_Externalizable.idl" +#include "org/omg/boxedRMI/CORBA/seq2_WStringValue.idl" +#include "org/omg/boxedRMI/java/lang/seq1_Object.idl" +#include "org/omg/boxedRMI/org/omg/boxedIDL/omega/seq2_Foxtrot.idl" +#include "org/omg/boxedRMI/java/lang/seq1_Exception.idl" +#include "org/omg/boxedRMI/omega/seq2_Golf.idl" +#include "org/omg/boxedRMI/omega/seq3_Dolphin.idl" +#include "org/omg/boxedRMI/seq2_boolean.idl" +#include "org/omg/boxedRMI/omega/seq2_A.idl" +#include "org/omg/boxedRMI/java/rmi/seq1_Remote.idl" +#include "omega/Juliet.idl" +#include "org/omg/boxedIDL/fake/omega/Kilo.idl" +#include "orb.idl" + +#ifndef __alpha_bravo_Charlie__ +#define __alpha_bravo_Charlie__ + + +module alpha { +module bravo { + + valuetype Charlie { + + public ::org::omg::boxedRMI::org::omg::boxedIDL::fake::omega::seq1_Kilo Kiloz; + public ::omega::Juliet aJuliet; + public ::org::omg::boxedIDL::fake::omega::Kilo aKilo; + public ::java::io::Serializable aSerializable; + public ::CORBA::WStringValue aString; + public ::org::omg::boxedRMI::omega::seq2_A azz; + public ::org::omg::boxedRMI::seq2_boolean boolzz; + public ::org::omg::boxedRMI::javax::rmi::CORBA::seq1_ClassDesc classz; + public ::org::omg::boxedRMI::seq1_Object cobjectz; + public ::org::omg::boxedRMI::java::lang::seq1_Exception exc; + public ::org::omg::boxedRMI::java::io::seq1_Externalizable externalizablez; + public ::org::omg::boxedRMI::omega::seq1_Dolphin finz; + public ::org::omg::boxedRMI::omega::seq2_Dolphin finzz; + public ::org::omg::boxedRMI::omega::seq3_Dolphin finzzz; + public ::org::omg::boxedRMI::org::omg::boxedIDL::omega::seq1_Foxtrot foxtrotz; + public ::org::omg::boxedRMI::org::omg::boxedIDL::omega::seq2_Foxtrot foxtrotzz; + public ::org::omg::boxedRMI::omega::seq1_Golf golfz; + public ::org::omg::boxedRMI::omega::seq2_Golf golfzz; + public ::org::omg::boxedRMI::omega::seq1_Hotel hotelz; + public ::org::omg::boxedRMI::omega::seq2_Hotel hotelzz; + public ::org::omg::boxedRMI::org::omg::CORBA::portable::seq1_IDLEntity idlentityz; + public ::org::omg::boxedRMI::omega::seq1_India indiaz; + public ::org::omg::boxedRMI::omega::seq2_India indiazz; + public ::org::omg::boxedRMI::java::lang::seq1_Object jobjectz; + public ::org::omg::boxedRMI::omega::seq1_Juliet julietz; + public ::org::omg::boxedRMI::seq1_long_long longz; + public ::org::omg::boxedRMI::seq2_long_long longzz; + public ::org::omg::boxedRMI::java::rmi::seq1_Remote remotez; + public ::org::omg::boxedRMI::java::io::seq1_Serializable serializablez; + public ::org::omg::boxedRMI::java::io::seq2_Serializable serializablezz; + public ::org::omg::boxedRMI::CORBA::seq1_WStringValue stringz; + public ::org::omg::boxedRMI::CORBA::seq2_WStringValue stringzz; + + }; + +#pragma ID Charlie "RMI:alpha.bravo.Charlie:895BDFE4B1E0A1EE:B4B3ECF4694A7100" + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Charlie.java b/test/src/share/classes/alpha/bravo/Charlie.java new file mode 100644 index 000000000..8eb792559 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Charlie.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Charlie implements java.io.Serializable { + + public omega.Dolphin finzz[][]; + public boolean boolzz[][]; + public java.lang.Exception exc[]; + public long longz[]; + public omega.A azz[][]; + public omega.Dolphin finz[]; + public java.lang.String aString; + public java.io.Serializable aSerializable; + public omega.Dolphin finzzz[][][]; + public long longzz[][]; + + public java.lang.Object jobjectz[]; + public java.lang.String stringz[]; + public java.lang.Class classz[]; + public java.io.Serializable serializablez[]; + public java.io.Serializable serializablezz[][]; + public java.lang.String stringzz[][]; + public java.io.Externalizable externalizablez[]; + public java.rmi.Remote remotez[]; + public org.omg.CORBA.Object cobjectz[]; + public org.omg.CORBA.portable.IDLEntity idlentityz[]; + + public omega.Foxtrot foxtrotz[]; + public omega.Golf golfz[]; + public omega.Hotel hotelz[]; + public omega.India indiaz[]; + public omega.Foxtrot foxtrotzz[][]; + public omega.Golf golfzz[][]; + public omega.Hotel hotelzz[][]; + public omega.India indiazz[][]; + + public fake.omega.Juliet aJuliet; + public fake.omega.Juliet julietz[]; + public fake.omega.Kilo aKilo; + public fake.omega.Kilo Kiloz[]; + +} diff --git a/test/src/share/classes/alpha/bravo/DuckBill.idlref b/test/src/share/classes/alpha/bravo/DuckBill.idlref new file mode 100644 index 000000000..dc3fef955 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/DuckBill.idlref @@ -0,0 +1,56 @@ +/** + * alpha/bravo/DuckBill.idl + * Generated by rmic -idl. Do not edit + * 26 April 1999 09:38:12 GMT+00:00 + */ + + +#ifndef __alpha_bravo_B__ + +module alpha { +module bravo { + + interface B; + +}; +}; + +#endif + +#include "org/omg/boxedRMI/seq1_long.idl" +#include "orb.idl" + +#ifndef __alpha_bravo_DuckBill__ +#define __alpha_bravo_DuckBill__ + + +module alpha { +module bravo { + + interface DuckBill { + + void hello__( ); + void hello__long__alpha_bravo_B__long( + in long arg0, + in ::alpha::bravo::B arg1, + in long arg2 ); + void hello__org_omg_boxedRMI_seq1_long( + in ::org::omg::boxedRMI::seq1_long arg0 ); + void hello__long( + in long arg0 ); + void hello__long_long( + in long long arg0 ); + void jack_( ); + void Jack_0( ); + void jAcK_1_3( ); + + }; + +#pragma ID DuckBill "RMI:alpha.bravo.DuckBill:0000000000000000" + +}; +}; + +#include "alpha/bravo/B.idl" +#endif + diff --git a/test/src/share/classes/alpha/bravo/DuckBill.java b/test/src/share/classes/alpha/bravo/DuckBill.java new file mode 100644 index 000000000..64155e43a --- /dev/null +++ b/test/src/share/classes/alpha/bravo/DuckBill.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public interface DuckBill extends java.rmi.Remote { + + public void hello() throws java.rmi.RemoteException; + public void hello( int x,B y,int z ) throws java.rmi.RemoteException; + public void hello( int z[] ) throws java.rmi.RemoteException; + public void hello( int z ) throws java.rmi.RemoteException; + public void hello( long z ) throws java.rmi.RemoteException; + + public void jack() throws java.rmi.RemoteException; + public void Jack() throws java.rmi.RemoteException; + public void jAcK() throws java.rmi.RemoteException; + +} diff --git a/test/src/share/classes/alpha/bravo/Hedgehog.idlref b/test/src/share/classes/alpha/bravo/Hedgehog.idlref new file mode 100644 index 000000000..19f9cb01a --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Hedgehog.idlref @@ -0,0 +1,64 @@ +/** + * alpha/bravo/Hedgehog.idl + * Generated by rmic -idl. Do not edit + * 26 April 1999 10:45:28 GMT+00:00 + */ + + +#ifndef __alpha_bravo_Kangaroo__ + +module alpha { +module bravo { + + valuetype Kangaroo; + +}; +}; + +#endif + + +#ifndef __alpha_bravo_Wallaby__ + +module alpha { +module bravo { + + abstract valuetype Wallaby; + +}; +}; + +#endif + +#include "alpha/bravo/Porcupine.idl" +#include "alpha/bravo/Warthog.idl" +#include "orb.idl" + +#ifndef __alpha_bravo_Hedgehog__ +#define __alpha_bravo_Hedgehog__ + + +module alpha { +module bravo { + + valuetype Hedgehog: ::alpha::bravo::Warthog, ::alpha::bravo::Porcupine { + + const short MAX_WARTS = 12; + private boolean foobah; + private long height; + private long length; + public long size; + public ::alpha::bravo::Kangaroo roo; + public ::alpha::bravo::Wallaby wally; + + }; + +#pragma ID Hedgehog "RMI:alpha.bravo.Hedgehog:292712065C451C6B:7E170A93C04E3962" + +}; +}; + +#include "alpha/bravo/Kangaroo.idl" +#include "alpha/bravo/Wallaby.idl" +#endif + diff --git a/test/src/share/classes/alpha/bravo/Hedgehog.java b/test/src/share/classes/alpha/bravo/Hedgehog.java new file mode 100644 index 000000000..83a3c4952 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Hedgehog.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Hedgehog extends Warthog + implements java.io.Serializable, Porcupine { + public final static short MAX_WARTS = 12; + private int length; + protected boolean foobah; + public Wallaby wally; + public Hedgehog(String name) {} + int height; + public int size; + public Hedgehog(int length) {} + public Kangaroo roo; + public int getLength() { int i = 0; return i; } + public int getSize() { int i = 1; return i; } //from Porcupine + + public transient int trans; +} + diff --git a/test/src/share/classes/alpha/bravo/Kangaroo.idlref b/test/src/share/classes/alpha/bravo/Kangaroo.idlref new file mode 100644 index 000000000..19c1cc8f1 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Kangaroo.idlref @@ -0,0 +1,44 @@ +/** + * alpha/bravo/Kangaroo.idl + * Generated by rmic -idl. Do not edit + * 26 April 1999 12:39:10 GMT+00:00 + */ + + +#ifndef __java_util_Hashtable__ + +module java { +module util { + + valuetype Hashtable; + +}; +}; + +#endif + +#include "java/lang/Cloneable.idl" +#include "alpha/bravo/Wallaby.idl" +#include "orb.idl" + +#ifndef __alpha_bravo_Kangaroo__ +#define __alpha_bravo_Kangaroo__ + + +module alpha { +module bravo { + + custom valuetype Kangaroo: ::alpha::bravo::Wallaby supports ::java::lang::Cloneable { + + public ::java::util::Hashtable aHashtable; + + }; + +#pragma ID Kangaroo "RMI:alpha.bravo.Kangaroo:C5A1BE050F6C3A11:C4ADEC553D368E1B" + +}; +}; + +#include "java/util/Hashtable.idl" +#endif + diff --git a/test/src/share/classes/alpha/bravo/Kangaroo.java b/test/src/share/classes/alpha/bravo/Kangaroo.java new file mode 100644 index 000000000..3f3ba908b --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Kangaroo.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Kangaroo extends Wallaby + implements java.io.Serializable, + java.lang.Cloneable { + private int length; + public java.util.Hashtable aHashtable; + public Kangaroo( int length ) { } + private void writeObject( java.io.ObjectOutputStream s ) { } + public int getLength() { int i = 0; return i; } +} diff --git a/test/src/share/classes/alpha/bravo/Mammal.idlref b/test/src/share/classes/alpha/bravo/Mammal.idlref new file mode 100644 index 000000000..d72dcf82f --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Mammal.idlref @@ -0,0 +1,23 @@ +/** + * alpha/bravo/Mammal.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 12:24:12 GMT+00:00 + */ + +#ifndef __alpha_bravo_Mammal__ +#define __alpha_bravo_Mammal__ + +#include "orb.idl" + + +module alpha { +module bravo { + + abstract valuetype Mammal { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Mammal.java b/test/src/share/classes/alpha/bravo/Mammal.java new file mode 100644 index 000000000..26c08c2dd --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Mammal.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public interface Mammal { + + public int getSize( long arg ); + int a = 2; + public final static int b = 3; + +} diff --git a/test/src/share/classes/alpha/bravo/Multi.java b/test/src/share/classes/alpha/bravo/Multi.java new file mode 100644 index 000000000..00d60fdbf --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Multi.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Multi extends javax.rmi.PortableRemoteObject + implements A, B, DuckBill { + public Multi() throws java.rmi.RemoteException {} + public void hello() throws java.rmi.RemoteException {} + public void hello( int x,B y,int z ) throws java.rmi.RemoteException {} + public void hello( int z[] ) throws java.rmi.RemoteException {} + public void hello( int z ) throws java.rmi.RemoteException {} + public void hello( long z ) throws java.rmi.RemoteException {} + + public void jack() throws java.rmi.RemoteException {} + public void Jack() throws java.rmi.RemoteException {} + public void jAcK() throws java.rmi.RemoteException {} + +} diff --git a/test/src/share/classes/alpha/bravo/Platypus.idlref b/test/src/share/classes/alpha/bravo/Platypus.idlref new file mode 100644 index 000000000..4b46ef7ed --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Platypus.idlref @@ -0,0 +1,104 @@ +/** + * alpha/bravo/Platypus.idl + * Generated by rmic -idl. Do not edit + * 26 April 1999 10:02:54 GMT+00:00 + */ + + +#ifndef __alpha_bravo_Platypus__Marsupial__ + +module alpha { +module bravo { + + abstract valuetype Platypus__Marsupial; + +}; +}; + +#endif + + +#ifndef __java_util_Hashtable__ + +module java { +module util { + + valuetype Hashtable; + +}; +}; + +#endif + + +#ifndef __javax_rmi_CORBA_ClassDesc__ + +module javax { +module rmi { +module CORBA { + + valuetype ClassDesc; + +}; +}; +}; + +#endif + + +#ifndef __alpha_bravo_Platypus__MU0024em__ + +module alpha { +module bravo { + + valuetype Platypus__MU0024em; + +}; +}; + +#endif + +#include "java/io/Externalizable.idl" +#include "java/lang/Object.idl" +#include "java/io/Serializable.idl" +#include "java/rmi/Remote.idl" +#include "orb.idl" + +#ifndef __alpha_bravo_Platypus__ +#define __alpha_bravo_Platypus__ + + +module alpha { +module bravo { + + valuetype Platypus { + + public long JAck_0_1; + public long J_ack; + public long Jack_0; + public long J_fred; + public long aU0024b; + public long jack_; + public long _typedef; + public long xU03BCy; + public ::javax::rmi::CORBA::ClassDesc aClass; + public ::java::util::Hashtable aHashtable; + public ::java::rmi::Remote aRemote; + public ::java::io::Serializable aSerializable; + public ::CORBA::WStringValue aString; + public ::java::io::Externalizable anExternalizable; + public ::java::lang::_Object anObject; + + }; + +#pragma ID Platypus "RMI:alpha.bravo.Platypus:60682B43557822B6:F34474B50B9B2726" + +}; +}; + +#include "alpha/bravo/Platypus__Marsupial.idl" +#include "java/util/Hashtable.idl" +#include "javax/rmi/CORBA/ClassDesc.idl" +#include "alpha/bravo/Platypus__MU0024em.idl" +#endif + diff --git a/test/src/share/classes/alpha/bravo/Platypus.java b/test/src/share/classes/alpha/bravo/Platypus.java new file mode 100644 index 000000000..feb4b4d22 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Platypus.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Platypus implements java.io.Serializable { + + private static final long serialVersionUID = -917480103144118490L; + + public int typedef; + public int _fred; + public int a$b; //$ is \U0024 + public int x\u03bCy; // \u03bc is Greek mu + + public java.lang.Object anObject; + public java.lang.Class aClass; + public java.lang.String aString; + public java.io.Serializable aSerializable; + public java.io.Externalizable anExternalizable; + public java.rmi.Remote aRemote; + public java.util.Hashtable aHashtable; + + class Marsupial /* implements java.io.Serializable */ { + public int pouch; + } + + class M$em implements java.io.Serializable { + public int p$rice; + } + + public int jack; + public int Jack; + public int JAck; + public int J_ack; + +} diff --git a/test/src/share/classes/alpha/bravo/Platypus__Marsupial.idlref b/test/src/share/classes/alpha/bravo/Platypus__Marsupial.idlref new file mode 100644 index 000000000..2587edf74 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Platypus__Marsupial.idlref @@ -0,0 +1,23 @@ +/** + * alpha/bravo/Platypus__Marsupial.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 10:26:43 GMT+00:00 + */ + +#ifndef __alpha_bravo_Platypus__Marsupial__ +#define __alpha_bravo_Platypus__Marsupial__ + +#include "orb.idl" + + +module alpha { +module bravo { + + valuetype Platypus__Marsupial { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/PolarBear.idlref b/test/src/share/classes/alpha/bravo/PolarBear.idlref new file mode 100644 index 000000000..07b62c2cb --- /dev/null +++ b/test/src/share/classes/alpha/bravo/PolarBear.idlref @@ -0,0 +1,22 @@ +/** + * alpha/bravo/PolarBear.idl + * Generated by rmic -idl. Do not edit + * 19 March 1999 15:14:35 GMT+00:00 + */ + +#ifndef __alpha_bravo_PolarBear__ +#define __alpha_bravo_PolarBear__ + +#include "orb.idl" + +module alpha { +module bravo { + + abstract valuetype PolarBear { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/PolarBear.java b/test/src/share/classes/alpha/bravo/PolarBear.java new file mode 100644 index 000000000..53240bc14 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/PolarBear.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class PolarBear /*extends Warthog*/ { + + private int length; + public int weight; + + private PolarBear() {} + public PolarBear( int arg ) {} + public PolarBear(int length, int weight) {} + public int getSize() { return 0; } + private void test( int arg ) {} + public void test( long arg ) {} + public int getWeight() { return 0; } + + int a = 2; + public final static int b = 3; + +} diff --git a/test/src/share/classes/alpha/bravo/Porcupine.idlref b/test/src/share/classes/alpha/bravo/Porcupine.idlref new file mode 100644 index 000000000..db40e6ab7 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Porcupine.idlref @@ -0,0 +1,23 @@ +/** + * alpha/bravo/Porcupine.idl + * Generated by rmic -idl. Do not edit + * 20 November 1998 11:28:28 GMT+00:00 + */ + +#ifndef __alpha_bravo_Porcupine__ +#define __alpha_bravo_Porcupine__ + +#include "orb.idl" + + +module alpha { +module bravo { + + abstract valuetype Porcupine { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Porcupine.java b/test/src/share/classes/alpha/bravo/Porcupine.java new file mode 100644 index 000000000..0f5783d93 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Porcupine.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public interface Porcupine { + + public int getSize(); + +} diff --git a/test/src/share/classes/alpha/bravo/Wallaby.idlref b/test/src/share/classes/alpha/bravo/Wallaby.idlref new file mode 100644 index 000000000..8079798cc --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Wallaby.idlref @@ -0,0 +1,23 @@ +/** + * alpha/bravo/Wallaby.idl + * Generated by rmic -idl. Do not edit + * 20 November 1998 11:28:28 GMT+00:00 + */ + +#ifndef __alpha_bravo_Wallaby__ +#define __alpha_bravo_Wallaby__ + +#include "orb.idl" + + +module alpha { +module bravo { + + valuetype Wallaby { + }; + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Wallaby.java b/test/src/share/classes/alpha/bravo/Wallaby.java new file mode 100644 index 000000000..426489bce --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Wallaby.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Wallaby {} + diff --git a/test/src/share/classes/alpha/bravo/Warthog.idlref b/test/src/share/classes/alpha/bravo/Warthog.idlref new file mode 100644 index 000000000..2e67407d3 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Warthog.idlref @@ -0,0 +1,27 @@ +/** + * alpha/bravo/Warthog.idl + * Generated by rmic -idl. Do not edit + * 20 November 1998 11:28:28 GMT+00:00 + */ + +#ifndef __alpha_bravo_Warthog__ +#define __alpha_bravo_Warthog__ + +#include "orb.idl" + +module alpha { +module bravo { + + valuetype Warthog { + + private long shoeSize; + + }; + +#pragma ID Warthog "RMI:alpha/bravo/Warthog:2A79FA460407EC1C" + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Warthog.java b/test/src/share/classes/alpha/bravo/Warthog.java new file mode 100644 index 000000000..b0168fff2 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Warthog.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package alpha.bravo; + +public class Warthog implements java.io.Serializable { + int shoeSize; + + void eat( int arg ) throws java.rmi.RemoteException {} + void drink( int arg ) throws java.lang.RuntimeException {} + void slurp( int arg ) throws java.lang.ArithmeticException {} + + int getFoo() throws java.rmi.RemoteException { return 1; } + void setFoo( int arg ) throws java.rmi.RemoteException {} + + private void test() throws java.rmi.RemoteException {} + public void test( int x ) throws java.rmi.RemoteException {} + +} + diff --git a/test/src/share/classes/alpha/bravo/Wombat.idlref b/test/src/share/classes/alpha/bravo/Wombat.idlref new file mode 100644 index 000000000..bcdb7bb08 --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Wombat.idlref @@ -0,0 +1,42 @@ +/** + * alpha/bravo/Wombat.idl + * Generated by rmic -idl. Do not edit + * 26 April 1999 10:07:42 GMT+00:00 + */ + +#include "omega/MammalOverloadEx.idl" +#include "omega/Wallaby.idl" + +#include "java/rmi/Remote.idl" +#include "orb.idl" + +#ifndef __alpha_bravo_Wombat__ +#define __alpha_bravo_Wombat__ + + +module alpha { +module bravo { + + interface Wombat: ::omega::Wallaby { + + const ::CORBA::WStringValue BLEAT_CONSTANT = "bleat"; + const long BLINT_CONSTANT = 1; + void chirp( + in long arg0 ); + void buzz( ) raises ( + ::omega::MammalOverloadEx ); + void passRemote__( ); + ::java::rmi::Remote passRemote__java_rmi_Remote( + in ::java::rmi::Remote arg0 ); + readonly attribute long chirp__; + readonly attribute boolean BLINT_CONSTANT; + + }; + +#pragma ID Wombat "RMI:alpha.bravo.Wombat:0000000000000000" + +}; +}; + +#endif + diff --git a/test/src/share/classes/alpha/bravo/Wombat.java b/test/src/share/classes/alpha/bravo/Wombat.java new file mode 100644 index 000000000..10939f8fe --- /dev/null +++ b/test/src/share/classes/alpha/bravo/Wombat.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*--Notes. See section 5.4----------------------------------------------------- + 5.4.1 passRemote uses java.rmi.Remote as a parameter and return value + 5.4.2 Wombat extends omega.Wallaby which is itself a Remote interface + 5.4.3.1 foo is an int read-write property + 5.4.3.2 URL is a String read-only property + 5.4.3.3 boo is a boolean read-write property + 5.4.3.4 attribute name pre-mangling. See 5.4.3.1-3 + ambiguous attribute name chirp, BLINT_CONSTANT; + 5.4.4 methods chirp and buzz + 5.4.5 constants BLEAT_CONSTANT, BLINT_CONSTANT + ----------------------------------------------------------------------------*/ + +package alpha.bravo; + +public interface Wombat extends java.rmi.Remote, + omega.Wallaby { + String BLEAT_CONSTANT = "bleat"; + int BLINT_CONSTANT = 1; + void chirp(int x) throws java.rmi.RemoteException; + void buzz() throws java.rmi.RemoteException, + omega.MammalOverload; + int getFoo() throws java.rmi.RemoteException; + void setFoo(int x) throws java.rmi.RemoteException; + String getURL() throws java.rmi.RemoteException; + boolean isBoo() throws java.rmi.RemoteException; + void setBoo(boolean b) throws java.rmi.RemoteException; + void passRemote() throws java.rmi.RemoteException; + java.rmi.Remote + passRemote( java.rmi.Remote r ) + throws java.rmi.RemoteException; + int getChirp() throws java.rmi.RemoteException; + boolean isBLINT_CONSTANT() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/corba/CORBATests.tdesc b/test/src/share/classes/corba/CORBATests.tdesc new file mode 100644 index 000000000..e09130752 --- /dev/null +++ b/test/src/share/classes/corba/CORBATests.tdesc @@ -0,0 +1,91 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +// Batch tests +// Run 'java test.Test' for syntax +// +// These are the CORBA Technologies tests found under +// test/src/share/classes/corba +// +// POAAndEquals and PCOSNamingTest seem to conflict when run +// in the test process. As a safety measure, any test which +// clients or servers within the test process will be run +// with the -separateprocess flag. + +-test corba.simpledynamic.NewAcceptor +-test corba.copyobjectpolicy.CopyObjectPolicyTest +-test corba.connectioncache.ConnectionCacheTest +// MixedOrbTest passes when run outside of the framework, +// but fails in the framework. It is commented out +// until that problem is fixed. +// -test corba.mixedorb.MixedOrbTest +-test corba.resolve_deadlock.ResolveDeadlockTest +-test corba.lb.LBTest -ifpresent + +// I don't think this is needed, and it takes 4.5 minutes to run, so comment it out for now +// -test corba.retryplugin.RetryPluginTest -ifpresent + +-test corba.giopgen.GIOPGenTest +-test corba.rfm.TestRFM +// now run directly from ant junit task: -test corba.messagetrace.MessageTraceTest +// now run directly from ant junit task: -test corba.misc.MiscTest +// now run directly from ant junit task: -test corba.dynamicrmiiiop.DynamicRmiIIOPTest +-test corba.requestpartitioning.RequestPartitioningTest +-test corba.rogueclient.RogueClientTest +-test corba.folb.FolbTest -ifpresent +-test corba.folb_8_1.FolbTest +-test corba.fwddecl.ForwardDeclTest +-test corba.security.PermissionTest +-test corba.unarrow.UncheckedNarrowTest +-test corba.legacyorbclasses.LegacyORBClassesTest +-test corba.legacybootstrapserver.LegacyBootstrapServerTest +-test corba.stubserialization.StubSerializationTest +-test corba.adapteractivator.AdapterActivator +-test corba.exceptiondetailsc.ExceptionDetailSCTest +-test corba.preinvokepostinvoke.PreInvokePostInvokeTest +-test corba.poacallback.POACallbackTest +-test corba.islocal.IsLocalTest +-test corba.strm2.Strm2Test +-test corba.orbconfig.NewORBTests +-test corba.orbconfigappserv.ORBConfigAppServTest +-test corba.iorintsockfact.IorIntSockFactTest +-test corba.connectintercept_1_4.ConnectIntercept_1_4Test +-test corba.connections.ConnectionsTest +-test corba.cdrext.CDRExtTest +-test corba.serialization.zerolengthstring.ZeroLengthStringTest +-test corba.purgecalls.PurgecallsTest +-test corba.codeset.CodeSetTest +-test corba.codebase.CodeBaseTest +-test corba.hcks.HcksTest +-test corba.ior.IORTests +-test corba.ortremote.ORTRemoteTest +-test corba.poamanager.POAManagerTest +-test corba.example.Example +-test corba.oneway.OneWayTest +-test corba.poatest.OneWayTest +-test corba.rmipoacounter.RMIPOACounterTest -separateprocess +-test corba.poapolicies.POAPoliciesTest +-test corba.poaandequals.POAAndEquals -separateprocess +-test corba.multiorb.MultiORBTest +-test corba.serialization.good.GoodRepIdTest +-test corba.cdrstreams.CDRTests +-test corba.giopheaderpadding.GIOPHeaderPaddingTest +-test corba.systemexceptions.SystemExceptionsTest +-test corba.rmic.RmicTest +-test corba.repid.RepIdTest +-test corba.invocation.InvocationTest +-test corba.custom.CustomTest +-test corba.evolve.EvolveTest + +// Leave these last four at the end. +// They go through long combinations of fragments sizes or GIOP combinations. +-test corba.cmvt.CMVTTest +-test corba.fragment2.FragmentTest +-test corba.fragment.FragmentTest +-test corba.msgtypes.MsgTypesTest diff --git a/test/src/share/classes/corba/CopyObjectTests.tdesc b/test/src/share/classes/corba/CopyObjectTests.tdesc new file mode 100644 index 000000000..5e7cd0a58 --- /dev/null +++ b/test/src/share/classes/corba/CopyObjectTests.tdesc @@ -0,0 +1,17 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +// Batch tests +// Run 'java test.Test' for syntax +// +// These are the CORBA Technologies copyObject tests found under +// test/src/share/classes/corba + +-test corba.copyobjectpolicy.CopyObjectPolicyTest +-test corba.copyobject.CopyObjectTest diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/AcceptorAndContactInfoTest.java b/test/src/share/classes/corba/acceptorandcontactinfo/AcceptorAndContactInfoTest.java new file mode 100644 index 000000000..d62a404fc --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/AcceptorAndContactInfoTest.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:31:43 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:54:44 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +public class AcceptorAndContactInfoTest + extends + CORBATest +{ + public static final String thisPackage = + AcceptorAndContactInfoTest.class.getPackage().getName(); + + protected void doTest() + throws + Throwable + { + Controller orbd = createORBD(); + orbd.start(); + + doTestType("Server", "Server", + "Client", "Client"); + + Controller colocatedClientServer = + createClient(thisPackage + ".ColocatedClientServer", + "colocatedClientServer"); + colocatedClientServer.start(); + colocatedClientServer.waitFor(); + colocatedClientServer.stop(); + + orbd.stop(); + } + + protected void doTestType(String serverMainClass, String serverTestName, + String clientMainClass, String clientTestName) + throws + Throwable + { + Controller server = createServer(thisPackage + "." + serverMainClass, + serverTestName); + server.start(); + + Controller client = createClient(thisPackage + "." + clientMainClass, + clientTestName); + client.start(); + client.waitFor(); + client.stop(); + + server.stop(); + } +} + +// End of file. + diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/Client.java b/test/src/share/classes/corba/acceptorandcontactinfo/Client.java new file mode 100644 index 000000000..b96583388 --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/Client.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:54:21 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 10:06:37 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import javax.naming.InitialContext; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; + +import corba.framework.Controller; +import corba.hcks.C; +import corba.hcks.U; + +import com.sun.corba.ee.impl.legacy.connection.LegacyServerSocketManagerImpl; + +public class Client +{ + public static final String baseMsg = Client.class.getName(); + public static final String main = baseMsg + ".main"; + + public static ORB orb; + public static InitialContext initialContext; + + public static rmiiI rmiiIPOA; + public static String rmiiIPOAArg = Server.rmiiIPOA; + + public static void main(String[] av) + { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + rmiiIPOA = (rmiiI) + U.lookupAndNarrow(C.rmiiSL, rmiiI.class, initialContext); + + + U.sop("CLIENT: " + rmiiIPOA.m(rmiiIPOAArg)); + + orb.shutdown(true); + + } catch (Exception e) { + U.sopUnexpectedException(main + " : ", e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } +} + +// End of file. + diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/ColocatedClientServer.java b/test/src/share/classes/corba/acceptorandcontactinfo/ColocatedClientServer.java new file mode 100644 index 000000000..bd0dd4a9f --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/ColocatedClientServer.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 17 (Thu) 17:05:00 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 10:57:47 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import java.util.Properties; +import javax.naming.InitialContext; +import org.omg.CORBA.ORB; +import corba.hcks.C; +import corba.hcks.U; + +public class ColocatedClientServer +{ + public static final String baseMsg = ColocatedClientServer.class.getName(); + public static final String main = baseMsg + ".main"; + + // REVISIT: FRAMEWORK DEVELOPMENT + // REMOVE THIS LATER. + // Necessary so calls not going through locals do not hang + // until I implement the reader thread/work split. + public static int fragmentSize = -1; + //public static int fragmentSize = C.DEFAULT_FRAGMENT_SIZE; + + public static ORB orb; + public static InitialContext initialContext; + public static boolean isColocated = false; + public static java.lang.Object signal = new java.lang.Object(); + + public static void main (String[] av) + { + isColocated = true; // Used by Client and Server. + + try { + // Share an ORB between a client and server. + // So ClientDelegate.isLocal currently succeeds. + + Properties props = new Properties(); + props.setProperty("com.sun.corba.ee.ORBAllowLocalOptimization", + "true"); + orb = ORB.init(av, props); + U.sop(main + " : creating ORB."); + Server.orb = (com.sun.corba.ee.spi.orb.ORB) orb; + Client.orb = orb; + + // Share a naming context between client and server + // so StubAdapter.isLocal is true. + + // Use the same ORB which has interceptor properties set. + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + Server.initialContext = initialContext; + Client.initialContext = initialContext; + + ServerThread ServerThread = new ServerThread(av); + ServerThread.start(); + synchronized (signal) { + try { + signal.wait(); + } catch (InterruptedException e) { + ; + } + } + Client.main(av); + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + } +} + +class ServerThread extends Thread +{ + String[] args; + ServerThread (String[] args) + { + this.args = args; + } + public void run () + { + Server.main(args); + } +} + +// End of file. diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/ServantLocator.java b/test/src/share/classes/corba/acceptorandcontactinfo/ServantLocator.java new file mode 100644 index 000000000..cc271debd --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/ServantLocator.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 07 (Tue) 16:29:22 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 11:13:27 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.OBJECT_NOT_EXIST; +import org.omg.PortableServer.ForwardRequest; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; + +import corba.hcks.U; + +public class ServantLocator + extends + org.omg.CORBA.LocalObject + implements + org.omg.PortableServer.ServantLocator + +{ + public static final String baseMsg = ServantLocator.class.getName(); + + public ServantLocator() + { + } + + public Servant preinvoke(byte[] oid, POA poa, String operation, + CookieHolder cookieHolder) + throws + ForwardRequest + { + String soid = new String(oid); + U.sop(baseMsg + ".preinvoke " + soid); + Servant servant = null; + try { + servant = + (Servant)javax.rmi.CORBA.Util.getTie(new rmiiIServantPOA()); + } catch (Exception e) { + U.sopUnexpectedException(baseMsg, e); + } + return servant; + } + + public void postinvoke(byte[] oid, POA poa, String operation, + java.lang.Object cookie, Servant servant) + { + } +} + +// End of file. diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/Server.java b/test/src/share/classes/corba/acceptorandcontactinfo/Server.java new file mode 100644 index 000000000..ffcb49f7e --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/Server.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:28:12 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 11:12:48 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import javax.naming.InitialContext; + +import org.omg.CORBA.Policy; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +import corba.framework.Controller; +import corba.framework.Options; +import corba.hcks.C; +import corba.hcks.U; + +import com.sun.corba.ee.spi.transport.TransportManager; +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.impl.legacy.connection.LegacyServerSocketManagerImpl; + +public class Server +{ + public static final String baseMsg = Server.class.getName(); + public static final String main = baseMsg + ".main"; + public static final String thisPackage = + Server.class.getPackage().getName(); + + public static final String rmiiIServantPOA_Tie = + thisPackage + "._rmiiIServantPOA_Tie"; + + public static final String rmiiIPOA = "rmiiIPOA"; + public static final String SLPOA = "SLPOA"; + + public static ORB orb; + public static InitialContext initialContext; + public static TransportManager transportManager; + public static POA rootPOA; + public static POA slPOA; + + public static void main(String[] av) + { + try { + U.sop(main + " starting"); + + if (! ColocatedClientServer.isColocated) { + U.sop(main + " : creating ORB."); + orb = (ORB) ORB.init(av, null); + U.sop(main + " : creating InitialContext."); + initialContext = C.createInitialContext(orb); + } + + rootPOA = U.getRootPOA(orb); + rootPOA.the_POAManager().activate(); + + Policy[] policies = U.createUseServantManagerPolicies( + rootPOA, ServantRetentionPolicyValue.NON_RETAIN); + + slPOA = U.createPOAWithServantManager( + rootPOA, SLPOA, policies, new ServantLocator()); + + + U.createRMIPOABind( + C.rmiiSL, rmiiIServantPOA_Tie, slPOA, orb, initialContext); + + U.sop(main + " ready"); + U.sop(Options.defServerHandshake); + System.out.flush(); + + synchronized (ColocatedClientServer.signal) { + ColocatedClientServer.signal.notifyAll(); + } + + orb.run(); + + } catch (Exception e) { + U.sopUnexpectedException(main, e); + System.exit(1); + } + U.sop(main + " ending successfully"); + System.exit(Controller.SUCCESS); + } +} + +// End of file. + diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/rmiiI.java b/test/src/share/classes/corba/acceptorandcontactinfo/rmiiI.java new file mode 100644 index 000000000..7372e9340 --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/rmiiI.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 10 (Thu) 11:30:38 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:55:19 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface rmiiI + extends + Remote +{ + String m(String x) + throws + RemoteException; +} + +// End of file. + diff --git a/test/src/share/classes/corba/acceptorandcontactinfo/rmiiIServantPOA.java b/test/src/share/classes/corba/acceptorandcontactinfo/rmiiIServantPOA.java new file mode 100644 index 000000000..58d02dcca --- /dev/null +++ b/test/src/share/classes/corba/acceptorandcontactinfo/rmiiIServantPOA.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2000 Nov 11 (Sat) 10:45:48 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:56:52 by Harold Carr. +// + +package corba.acceptorandcontactinfo; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; +import corba.hcks.U; + +public class rmiiIServantPOA + extends + PortableRemoteObject + implements + rmiiI +{ + public static final String baseMsg = rmiiIServantPOA.class.getName(); + + public rmiiIServantPOA () + throws + RemoteException + { + // DO NOT CALL SUPER - that would connect the object. + } + + public String m(String x) + { + String result = x + " (echo from " + baseMsg + ")"; + U.sop(result); + return result; + } +} + +// End of file. diff --git a/test/src/share/classes/corba/cdrext/AbsTester.java b/test/src/share/classes/corba/cdrext/AbsTester.java new file mode 100644 index 000000000..941d84dcd --- /dev/null +++ b/test/src/share/classes/corba/cdrext/AbsTester.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.rmi.*; + +public interface AbsTester +{ + public void ping() throws RemoteException; +} + diff --git a/test/src/share/classes/corba/cdrext/CDRExtTest.java b/test/src/share/classes/corba/cdrext/CDRExtTest.java new file mode 100644 index 000000000..a9bbd3de4 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/CDRExtTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class CDRExtTest extends CORBATest { + + protected void doTest() throws Throwable + { + // 2048 since the client assumes 2048 bytes will be enough + // ahead of any structure to push it totally across a + // fragment boundary + Properties clientProps = Options.getClientProperties(); + clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "2048"); + + Controller orbd = createORBD(); + Controller server = createServer("corba.cdrext.Server"); + Controller client = createClient("corba.cdrext.Client"); + + orbd.start(); + server.start(); + client.start(); + + client.waitFor(360000); + + client.stop(); + server.stop(); + orbd.stop(); + } +} + diff --git a/test/src/share/classes/corba/cdrext/CheckedException.java b/test/src/share/classes/corba/cdrext/CheckedException.java new file mode 100644 index 000000000..1cb252d6a --- /dev/null +++ b/test/src/share/classes/corba/cdrext/CheckedException.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +public class CheckedException extends Exception { + public CheckedException(String msg) { + super(msg); + } +} diff --git a/test/src/share/classes/corba/cdrext/Client.java b/test/src/share/classes/corba/cdrext/Client.java new file mode 100644 index 000000000..7c2f0a5cd --- /dev/null +++ b/test/src/share/classes/corba/cdrext/Client.java @@ -0,0 +1,490 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.rmi.*; +import javax.rmi.PortableRemoteObject; +import javax.naming.*; +import java.io.*; +import java.util.*; +import javax.rmi.CORBA.*; + +import org.testng.annotations.Test ; +import org.testng.annotations.BeforeSuite ; +import org.testng.Assert ; + +import corba.framework.TestngRunner ; + +public class Client { + // Important: put the initialContext here so that is does NOT get GCed and finalized + // while the test is running! + private InitialContext rootContext ; + private Tester tester ; + + /* Using a byte array in front and behind the main + * payload parameter, this should allow us to break + * the MarshalTester's data across just about all + * possible fragment points. This exercises code for + * handling primitives, etc, across fragment + * boundaries. A CustomMarshalTester can be used to + * add the further complicating factor of chunking. + * + * Note that this probably doesn't do much with indirections + * across boundaries, or indirections interacting with + * chunks. + */ + private void testFragmentation(Tester tester, + MarshalTester payload) throws Exception { + + System.out.println("Testing fragmentation with a " + payload.getClass().getName() + + "..."); + + for (int i = 0; i < 2048; i++) { + byte[] predata = new byte[i]; + byte[] postdata = new byte[i]; + + for (int y = 0; y < i; y++) { + predata[y] = postdata[y] = (byte)(y % 128); + } + + MarshalTester result = tester.verify(predata, payload, postdata); + + if (!payload.equals(result)) + throw new Exception("Payloads not equal at predata size " + + predata.length); + } + + System.out.println("PASSED"); + } + + @Test + public void testFragmentationMarshalTester() throws Exception { + MarshalTester mt = new MarshalTester(); + mt.init(tester); + testFragmentation(tester, mt); + } + + @Test + public void testFragmentationCustomMarshalTester() throws Exception { + CustomMarshalTester cmt = new CustomMarshalTester(); + cmt.init(tester); + Hashtable extra = new Hashtable(); + extra.put("pkg1", tester); + extra.put("pkg2", tester); + cmt.add(extra); + cmt.add(tester); + testFragmentation(tester, cmt); + } + + /** + * Verify that checked exceptions work. + */ + @Test + public void testCheckedException() throws Exception { + try { + System.out.println("Testing CheckedException..."); + + tester.throwCheckedException(); + + throw new Exception("Failed - No exception"); + + } catch (CheckedException re) { + System.out.println("PASSED"); + } catch (Throwable t) { + throw new Exception("FAILED -- received: " + t.getClass().getName()); + } + } + + /** + * Very that Remote exceptions work. We had a compatibility + * problem between 1.3.x and 1.4.0 with Remote and unchecked + * exceptions. Unfortunately, unless used in multi-JVM + * scenarios, this test still can't catch it. + */ + @Test + public void testRemoteException() throws Exception { + try { + System.out.println("Testing RemoteException..."); + + tester.throwRemoteException(); + + throw new Exception("Failed - No exception"); + + } catch (RemoteException re) { + System.out.println("PASSED"); + } catch (Throwable t) { + throw new Exception("FAILED -- received: " + t.getClass().getName()); + } + } + + @Test + public void testRuntimeException() throws Exception { + try { + System.out.println("Testing RuntimeException..."); + + tester.throwRuntimeException(); + + throw new Exception("Failed - No exception"); + + } catch (UncheckedException ex) { + System.out.println("PASSED"); + } catch (Throwable t) { + throw new Exception("FAILED -- received: " + t.getClass().getName()); + } + } + + /** + * Even though AbsTester isn't Remote or Serializable, + * this should work since the Server's getAbsTester + * method returns a Tester (subinterface of AbsTester). + */ + @Test + public void testAbstractInterface() + throws RemoteException, DataCorruptedException + { + System.out.println("Testing abstract interface..."); + + AbsTester absTester = tester.getAbsTester(); + + if (!(absTester instanceof Tester)) + throw new DataCorruptedException("Not a Tester"); + + // Methods in the abstract interface which + // are declared to throw RemoteException + // should also work. + absTester.ping(); + + System.out.println("PASSED"); + } + + /** + * This will result in an Any on the wire and + * a wchar type code at some point. We don't actually + * use our type codes to unmarshal, so this won't + * be a real test unless in an interop scenario. + */ + @Test + public void testIncorrectCharTC() + throws DataCorruptedException, RemoteException { + + System.out.println("Testing for incorrect char TC..."); + + Character ch1 = new Character('\u6D77'); + if (!ch1.equals(tester.verify(ch1))) + throw new DataCorruptedException("Error on character 1"); + + System.out.println("PASSED"); + } + + /** + * Simply passes an object which uses PutField/GetField. + */ + @Test + public void testPutFieldsGetFields() + throws DataCorruptedException, RemoteException { + + System.out.println("Testing PutFields/GetFields..."); + + TestObject to = new TestObject(); + + if (!to.equals(tester.verify(to))) + throw new DataCorruptedException("TestObjects not equal"); + + System.out.println("PASSED"); + } + + /** + * Makes sure that superclass data is unmarshaled properly. + */ + @Test + public void testSuperClasses() + throws DataCorruptedException, RemoteException { + + System.out.println("Testing superclass constructor call with RMI-IIOP..."); + + SubClass sc = new SubClass(); + + System.out.println("Sending: " + sc); + + SubClass result = (SubClass)tester.verify(sc); + + System.out.println("Received: " + result); + + if (!sc.equals(result)) + throw new DataCorruptedException("Bad result!"); + + System.out.println("PASSED"); + } + + /** + * Makes sure that a class containing a static nested + * inner class is marshaled properly. + * + * NOTE: this class CANNOT be marshalled properly, + * because the nest inner class is not in a static context, + * which means that it does not have a no-args constructor, + * even if no constructor is declared. This means that + * the nested inner class is not properly externalizable, + * and this test is invalid. Note that it used to work + * with the previous native implementation. + */ + public void testStaticNestedInner() + throws DataCorruptedException, RemoteException { + + TestClass data = new TestClass(); + + System.out.println("Testing static nested inner class..."); + + java.lang.Object result = tester.verify(data); + + if (result == null) + throw new DataCorruptedException("Failed -- result was null"); + + if (!data.equals(result)) + throw new DataCorruptedException("Failed: " + result); + + System.out.println("PASSED"); + } + + /** + * Makes sure that recursive references in custom marshaled + * values works. This was more important as an interop + * test in the Connectathon. + */ + @Test + public void testRecursiveReferences() + throws DataCorruptedException, RemoteException { + + System.out.println("Testing recursive references..."); + + // Vector is not custom marshaled before JDK 1.4 + Vector nonCustom = new Vector(); + nonCustom.add(nonCustom); + Vector vectorResult = (Vector)tester.verify(nonCustom); + if (vectorResult == null) + throw new DataCorruptedException("Result Vector was null"); + if (vectorResult.size() != nonCustom.size()) + throw new DataCorruptedException("Result Vector's size is " + + vectorResult.size()); + if (vectorResult.elementAt(0) != vectorResult) + throw new DataCorruptedException("Vector graph not preserved"); + + Hashtable custom = new Hashtable(); + String customKey = "Test"; + custom.put(customKey, custom); + Hashtable hashResult = (Hashtable)tester.verify((Map)custom); + if (hashResult == null) + throw new DataCorruptedException("Result Hashtable was null"); + if (hashResult.size() != custom.size()) + throw new DataCorruptedException("Result Hashtable size is " + + hashResult.size()); + Object hashObj = hashResult.get(customKey); + + // Should preserve self reference + if (hashObj != hashResult) + throw new DataCorruptedException("Hashtable graph not preserved"); + + Hashtable table2 = new Hashtable(); + table2.put("three", table2); + + Hashtable table2Result = (Hashtable)tester.verify(table2); + if (table2Result == null || + table2Result.size() != table2.size() || + table2Result.get("three") != table2Result) { + throw new DataCorruptedException("Bad resulting Hashtable"); + } + + System.out.println("PASSED"); + } + + /** + * If we start to actually use our TypeCodes to marshal/unmarshal + * the Anys (produced when RMI-IIOP sends something as a + * java.lang.Object, Serializable, or Externalizable), this + * will test all the basic type codes. + */ + @Test + public void testTypeCodeCompatibility() + throws DataCorruptedException, RemoteException + { + System.out.println("Testing TypeCode compatibility..."); + + MarshalTester mt = new MarshalTester(); + mt.init(tester); + + MarshalTester result = (MarshalTester)tester.verify((java.lang.Object)mt); + + if (!mt.equals(result)) + throw new DataCorruptedException("MarshalTesters not equal!"); + + System.out.println("PASSED"); + } + + /** + * Occassionally people have filed bugs saying that SQL Date + * is broken in RMI-IIOP, but the problem usually clears up. + */ + @Test + public void testSQLDate() + throws DataCorruptedException, RemoteException + { + System.out.println("Testing SQL Date..."); + + for (int i = 0; i < 100; i++) { + java.sql.Date d = new java.sql.Date((new java.util.Date()).getTime()); + java.sql.Date res = tester.verify(d); + if (!d.equals(res)) + throw new DataCorruptedException("Test 1 failed"); + } + + System.out.println("PASSED"); + } + + /** + * Occassionally people have filed bugs saying that Properties + * is broken in RMI-IIOP, but the problem usually clears up. + */ + @Test + public void testProperties() + throws RemoteException, + DataCorruptedException + { + System.out.println("Testing Properties objects..."); + + Properties props = System.getProperties(); + + if (!props.equals(tester.verify(props))) + throw new DataCorruptedException("Test 1 failed"); + if (!props.equals(tester.verify((Object)props))) + throw new DataCorruptedException("Test 2 failed"); + + Properties defaults = new Properties(); + defaults.setProperty("Test1", "Test2"); + defaults.setProperty("Test3", "Test4"); + Properties props2 = new Properties(defaults); + props2.setProperty("Test5", "Test6"); + + if (!props2.equals(tester.verify(props2))) + throw new DataCorruptedException("Test 3 failed"); + if (!props2.equals(tester.verify((Object)props2))) + throw new DataCorruptedException("Test 4 failed"); + + System.out.println("PASSED"); + } + + /** + * Indirections to Remotes in custom marshaled valuetypes + * (like ArrayList) used to break often, but we seem to + * have it fixed, now. + */ + @Test + public void testArrayList() + throws RemoteException, + DataCorruptedException + { + System.out.println("Testing ArrayList of Remotes..."); + + ArrayList list = new ArrayList(255); + + for (int i = 0; i < 255; i++) + list.add(tester); + + List result = tester.verify(list); + + if (result == null) + throw new DataCorruptedException("Result is null!"); + + if (result.size() != list.size()) + throw new DataCorruptedException("Sizes not equal!"); + + for (int i = 0; i < list.size(); i++) { + if (!list.get(i).equals(result.get(i))) + throw new DataCorruptedException("Item not equal: " + i); + } + + System.out.println("PASSED"); + } + + /** + * Calendar does some interesting RMI-IIOP tricks in + * its readObject/writeObject. When talking to an + * older 1.3.x Calendar, it will read more data than + * was sent. *** This is broken in RMI-IIOP. However, + * that will only occur when 1.4.x is talking to 1.3.x, + * which we currently can't test within the framework. + */ + @Test + public void testCalendar() + throws RemoteException, DataCorruptedException + { + System.out.println("Testing Calendar..."); + + Calendar c1 = Calendar.getInstance(); + + Calendar c2 = (Calendar)tester.verify(c1); + + if (!c1.equals(c2)) + throw new DataCorruptedException("Calendars not equal"); + + System.out.println("PASSED"); + } + + /** + * Makes sure that the protected superclass writeReplace/ + * readResolve methods are called. + */ + @Test + public void testWriteReplaceReadResolve() + throws DataCorruptedException, RemoteException { + + System.out.println("Testing writeReplace/readResolve..."); + + Status.reset(); + + ReplaceSubClass rsc = new ReplaceSubClass(); + + System.out.println("Sending: " + rsc); + + ReplaceSubClass result = (ReplaceSubClass)tester.verify(rsc); + + System.out.println("Received: " + result); + + if (!rsc.equals(result)) + throw new DataCorruptedException("Bad result!"); + + if (!Status.writeReplaceCalled() || + !Status.readResolveCalled()) + throw new DataCorruptedException("Didn't call writeReplace and readResolve"); + + System.out.println("PASSED"); + } + + @BeforeSuite + public void setup() throws Exception { + System.out.println("Finding tester..."); + rootContext = new InitialContext(); + + System.out.println("Looking up tester..."); + java.lang.Object tst = rootContext.lookup("Tester"); + + System.out.println("Narrowing..."); + tester = (Tester)PortableRemoteObject.narrow(tst, + Tester.class); + } + + public static void main(String args[]) { + TestngRunner runner = new TestngRunner() ; + runner.registerClass( Client.class ) ; + runner.run() ; + runner.systemExit() ; + } +} + diff --git a/test/src/share/classes/corba/cdrext/CustomMarshalTester.java b/test/src/share/classes/corba/cdrext/CustomMarshalTester.java new file mode 100644 index 000000000..455b411aa --- /dev/null +++ b/test/src/share/classes/corba/cdrext/CustomMarshalTester.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; +import java.util.*; + +public class CustomMarshalTester extends MarshalTester implements Serializable +{ + private transient List items; + + public CustomMarshalTester() { + items = new LinkedList(); + } + + public void add(Object obj) { + items.add(obj); + } + + public Iterator iterator() { + return items.iterator(); + } + + public boolean equals(Object obj) { + try { + return super.equals(obj) + && items.equals(((CustomMarshalTester)obj).items); + } catch (ClassCastException cce) { + cce.printStackTrace(); + return false; + } + } + + public int size() { + return items.size(); + } + + private void writeObject(ObjectOutputStream s) throws IOException { + + s.defaultWriteObject(); + + s.writeInt(size()); + + Iterator iter = iterator(); + + while (iter.hasNext()) + s.writeObject(iter.next()); + } + + private void readObject(java.io.ObjectInputStream s) + throws IOException, ClassNotFoundException { + + if (items != null) + throw new IOException("Default constructor was invoked [1]!"); + + s.defaultReadObject(); + + if (items != null) + throw new IOException("Default constructor was invoked [2]!"); + + int numItems = s.readInt(); + + items = new LinkedList(); + + for (int i = 0; i < numItems; i++) + items.add(s.readObject()); + } +} + diff --git a/test/src/share/classes/corba/cdrext/DataCorruptedException.java b/test/src/share/classes/corba/cdrext/DataCorruptedException.java new file mode 100644 index 000000000..45c0303f2 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/DataCorruptedException.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +public class DataCorruptedException extends Exception { + public DataCorruptedException(String msg) { + super(msg); + } +} diff --git a/test/src/share/classes/corba/cdrext/MarshalChecker.java b/test/src/share/classes/corba/cdrext/MarshalChecker.java new file mode 100644 index 000000000..30a527383 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/MarshalChecker.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; +import java.util.*; + diff --git a/test/src/share/classes/corba/cdrext/MarshalTester.java b/test/src/share/classes/corba/cdrext/MarshalTester.java new file mode 100644 index 000000000..541c666b1 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/MarshalTester.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.rmi.Remote; +import java.io.*; +import java.util.*; + +/** + * Class with all basic fields plus a recursive, Object, + * and Serializable field. Missing Externalizable field. + * This is useful for testing CORBA type code compatibility + * for when a parameter or return value is Object, + * Serializable, or Externalizable. + * + * Note that we don't actually use the TypeCode for + * our unmarshaling. It might be used by another Java ORB, + * but it would definitely be necessary for a non-Java + * ORB if sent a MarshalTester in an Any. + */ +public class MarshalTester implements Serializable { + public byte byteField; + public boolean booleanField; + public short shortField; + public int intField; + public long longField; + public float floatField; + public double doubleField; + + public char charField; + public String stringField; + + public byte[] byteArrayField; + public boolean[] booleanArrayField; + public short[] shortArrayField; + public int[] intArrayField; + public long[] longArrayField; + public float[] floatArrayField; + public double[] doubleArrayField; + + public char[] charArrayField; + public String[] stringArrayField; + + public MarshalTester recursiveField; + + public Object objectField; + public Serializable serializableField; + public Externalizable externalizableField; + + public Remote remoteField; + + public boolean equals(Object obj) { + MarshalTester other = (MarshalTester)obj; + + return byteField == other.byteField && + booleanField == other.booleanField && + shortField == other.shortField && + intField == other.intField && + longField == other.longField && + floatField == other.floatField && + doubleField == other.doubleField && + charField == other.charField && + stringField.equals(other.stringField) && + Arrays.equals(byteArrayField, other.byteArrayField) && + Arrays.equals(booleanArrayField, other.booleanArrayField) && + Arrays.equals(shortArrayField, other.shortArrayField) && + Arrays.equals(intArrayField, other.intArrayField) && + Arrays.equals(longArrayField, other.longArrayField) && + Arrays.equals(floatArrayField, other.floatArrayField) && + Arrays.equals(doubleArrayField, other.doubleArrayField) && + Arrays.equals(charArrayField, other.charArrayField) && + Arrays.equals(stringArrayField, other.stringArrayField) && + other.recursiveField == other && + objectField.equals(other.objectField) && + serializableField.equals(other.serializableField) && + externalizableField.equals(other.externalizableField) && + remoteField.equals(other.remoteField); + } + + /** + * Separate initialization from constructor so we know the + * marshaling code isn't cheating by invoking default + * constructor. + */ + public void init(Remote remoteField) { + byteField = (byte)83; + booleanField = true; + shortField = (short)5912; + intField = 9035; + longField = (long)949241; + floatField = (float)35.2; + doubleField = (double)3590.421; + + charField = '\u6D77'; + stringField = "\u6D77\u6D77\u6D77"; + + byteArrayField = new byte[] { (byte)241, + (byte)59, + (byte)59, + (byte)0, + (byte)53 }; + + booleanArrayField = new boolean[] { false, true }; + + shortArrayField = new short[] { (short)943, + (short)0, + (short)3512, + (short)35 }; + + intArrayField = new int[] { 35123, 943, -203012, 0, 2312 }; + + longArrayField = new long[] { (long)2412, + (long)-203, + (long)0, + (long)241 }; + + floatArrayField = new float[] { (float)32.3, + (float)912.231, + (float)0.0, + (float)234.11 }; + + doubleArrayField = new double[] { (double)3412.21, + (double)243.22, + (double)0.0, + (double)23.1 }; + + charArrayField = new char[] { 'A', '\u6D77', 'x' }; + + stringArrayField = new String[] { "This is a test", + stringField, + "This is another test" }; + + recursiveField = this; + + objectField = new Integer(52); + serializableField = new Integer(59); + + this.remoteField = remoteField; + + externalizableField + = new TestExternalizable(90283091824L, + "I like \u65E5\u672C", + 59021, + '\u7A7A'); + } + + public MarshalTester() {} +} diff --git a/test/src/share/classes/corba/cdrext/ReplaceSubClass.java b/test/src/share/classes/corba/cdrext/ReplaceSubClass.java new file mode 100644 index 000000000..5f5832c1d --- /dev/null +++ b/test/src/share/classes/corba/cdrext/ReplaceSubClass.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; + +public class ReplaceSubClass extends ReplaceSuperClass +{ + private long longValue; + + public ReplaceSubClass() { + longValue = 92431; + } + + public boolean equals(Object obj) { + if (!(obj instanceof ReplaceSubClass)) + return false; + else { + return super.equals(obj) + && longValue == ((ReplaceSubClass)obj).longValue; + } + } + + public String toString() { + StringBuffer sbuf = new StringBuffer(); + sbuf.append("ReplaceSubClass [longValue="); + sbuf.append(longValue); + sbuf.append(", "); + sbuf.append(super.toString()); + sbuf.append(']'); + return sbuf.toString(); + } +} diff --git a/test/src/share/classes/corba/cdrext/ReplaceSuperClass.java b/test/src/share/classes/corba/cdrext/ReplaceSuperClass.java new file mode 100644 index 000000000..f60219b0a --- /dev/null +++ b/test/src/share/classes/corba/cdrext/ReplaceSuperClass.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; + +public class ReplaceSuperClass implements Serializable +{ + private String strValue; + private int intValue; + + public ReplaceSuperClass() { + strValue = "Test"; + intValue = 3241; + } + + public String toString() { + + StringBuffer sbuf = new StringBuffer(); + sbuf.append("ReplaceSuperClass [strValue="); + sbuf.append(strValue); + sbuf.append(", intValue="); + sbuf.append(intValue); + sbuf.append(']'); + return sbuf.toString(); + } + + public boolean equals(Object obj) { + if (!(obj instanceof ReplaceSuperClass)) + return false; + else { + return intValue == ((ReplaceSuperClass)obj).intValue + && strValue.equals(((ReplaceSuperClass)obj).strValue); + } + } + + protected Object writeReplace() { + System.out.println("---- writeReplace ----"); + + Status.inWriteReplace(); + + return this; + } + + protected Object readResolve() { + System.out.println("--- readResolve ---"); + + Status.inReadResolve(); + + return this; + } +} diff --git a/test/src/share/classes/corba/cdrext/Server.java b/test/src/share/classes/corba/cdrext/Server.java new file mode 100644 index 000000000..202f8de40 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/Server.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import org.omg.CORBA.*; +import org.omg.CORBA.portable.*; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.PortableServer.*; + +import java.rmi.*; +import javax.rmi.PortableRemoteObject; +import javax.naming.*; +import java.io.*; +import java.util.*; + +public class Server extends PortableRemoteObject implements Tester +{ + public Server() throws java.rmi.RemoteException {} + + public MarshalTester verify(byte[] predata, + MarshalTester input, + byte[] postdata) + throws DataCorruptedException + { + if (predata == null) { + System.out.println("predata is null"); + throw new DataCorruptedException("predata is null"); + } + if (postdata == null) { + System.out.println("postdata is null"); + throw new DataCorruptedException("postdata is null"); + } + if (!Arrays.equals(predata, postdata)) { + System.out.println("byte arrays not equal"); + throw new DataCorruptedException("Byte arrays not equal"); + } + + return input; + } + + public java.lang.Object verify(java.lang.Object obj) { + return obj; + } + + public Map verify(Map map) { + return map; + } + + public List verify(List list) { + return list; + } + + public java.sql.Date verify(java.sql.Date date) { + return date; + } + + public Properties verify(Properties props) { + return props; + } + + public Hashtable verify(Hashtable table) { + return table; + } + + public void throwCheckedException() throws CheckedException { + throw new CheckedException("CheckedException"); + } + + public void throwRuntimeException() { + throw new UncheckedException("Runtime Exception"); + } + + public void throwRemoteException() throws RemoteException { + throw new RemoteException("This is a remote exception"); + } + + public AbsTester getAbsTester() { + return this; + } + + public void ping() {} + + public static void main(String[] args) { + try { + + ORB orb = ORB.init(args, System.getProperties()); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + Server impl = new Server(); + javax.rmi.CORBA.Tie tie = javax.rmi.CORBA.Util.getTie( impl ) ; + + byte[] id = rootPOA.activate_object( + (org.omg.PortableServer.Servant)tie ) ; + org.omg.CORBA.Object obj = rootPOA.id_to_reference( id ) ; + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("Tester", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + + // Emit the handshake the test framework expects + // (can be changed in Options by the running test) + System.out.println ("Server is ready."); + + // Wait for clients + orb.run(); + +// Context rootContext = new InitialContext(); +// Server p = new Server(); +// rootContext.rebind("Tester", p); +// System.out.println("Server is ready."); + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); + } + } + +} + diff --git a/test/src/share/classes/corba/cdrext/Status.java b/test/src/share/classes/corba/cdrext/Status.java new file mode 100644 index 000000000..e6a4d7e47 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/Status.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +public class Status +{ + public static boolean writeReplaceCalled() { + return writeReplaceCalled; + } + + public static boolean readResolveCalled() { + return readResolveCalled; + } + + public static void reset() { + writeReplaceCalled = false; + readResolveCalled = false; + } + + public static void inWriteReplace() { + writeReplaceCalled = true; + } + + public static void inReadResolve() { + readResolveCalled = true; + } + + private static boolean writeReplaceCalled; + private static boolean readResolveCalled; +} diff --git a/test/src/share/classes/corba/cdrext/SubClass.java b/test/src/share/classes/corba/cdrext/SubClass.java new file mode 100644 index 000000000..667fb6110 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/SubClass.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; + +public class SubClass extends SuperClass implements Serializable +{ + private long longValue; + + public SubClass() { + longValue = 92431; + } + + public boolean equals(Object obj) { + if (!(obj instanceof SubClass)) + return false; + else { + return super.equals(obj) + && longValue == ((SubClass)obj).longValue; + } + } + + public String toString() { + StringBuffer sbuf = new StringBuffer(); + sbuf.append("SubClass [longValue="); + sbuf.append(longValue); + sbuf.append(", "); + sbuf.append(super.toString()); + sbuf.append(']'); + return sbuf.toString(); + } +} diff --git a/test/src/share/classes/corba/cdrext/SuperClass.java b/test/src/share/classes/corba/cdrext/SuperClass.java new file mode 100644 index 000000000..822b13074 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/SuperClass.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +public class SuperClass +{ + private String strValue; + private int intValue; + + public SuperClass() { + strValue = "Test"; + intValue = 3241; + } + + public String toString() { + + StringBuffer sbuf = new StringBuffer(); + sbuf.append("SuperClass [strValue="); + sbuf.append(strValue); + sbuf.append(", intValue="); + sbuf.append(intValue); + sbuf.append(']'); + return sbuf.toString(); + } + + public boolean equals(Object obj) { + if (!(obj instanceof SuperClass)) + return false; + else { + return intValue == ((SuperClass)obj).intValue + && strValue.equals(((SuperClass)obj).strValue); + } + } +} diff --git a/test/src/share/classes/corba/cdrext/TestClass.java b/test/src/share/classes/corba/cdrext/TestClass.java new file mode 100644 index 000000000..c56820194 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/TestClass.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; + +public class TestClass implements Serializable +{ + private NestedInnerClass instance; + + public TestClass() { + instance = new NestedInnerClass(); + } + + public boolean equals(Object obj) { + if (obj == null) + return false; + + try { + return instance.equals(((TestClass)obj).instance); + } catch (ClassCastException cce) { + return false; + } + } + + private static class NestedInnerClass implements Externalizable { + + private NestedInnerClass() { + data = 12344512L; + } + + private long data; + + public void readExternal(ObjectInput decoder) + throws IOException, ClassNotFoundException { + + data = decoder.readLong(); + } + + public void writeExternal(ObjectOutput encoder) + throws IOException { + + encoder.writeLong(data); + } + + public boolean equals(Object obj) { + if (obj == null) + return false; + + try { + return data == ((NestedInnerClass)obj).data; + } catch (ClassCastException cce) { + return false; + } + } + } +} + + diff --git a/test/src/share/classes/corba/cdrext/TestExternalizable.java b/test/src/share/classes/corba/cdrext/TestExternalizable.java new file mode 100644 index 000000000..0a4585470 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/TestExternalizable.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.io.*; + +public class TestExternalizable implements Externalizable +{ + private long data1; + private String data2; + private int data3; + private char data4; + + public TestExternalizable() {} + + public TestExternalizable(long data1, + String data2, + int data3, + char data4) { + this.data1 = data1; + this.data2 = data2; + this.data3 = data3; + this.data4 = data4; + } + + public boolean equals(Object obj) { + try { + if (obj == null) + return false; + + TestExternalizable other + = (TestExternalizable)obj; + + return (data1 == other.data1 && + (data2 == null || + data2.equals(other.data2)) && + data3 == other.data3 && + data4 == other.data4); + } catch (ClassCastException cce) { + return false; + } + } + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeLong(data1); + + // Check to make sure these are working + // the same + out.writeObject(data2); + out.writeUTF(data2); + + out.writeInt(data3); + + out.writeChar(data4); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException { + + data1 = in.readLong(); + + String data2_obj = (String)in.readObject(); + String data2_utf = in.readUTF(); + + if (data2_obj == null && data2_obj != data2_utf) + throw new IOException("data2_obj null mismatch"); + else + if (data2_obj != null && !data2_obj.equals(data2_utf)) + throw new IOException("data2_obj data2_utf mismatch"); + + data2 = data2_obj; + + data3 = in.readInt(); + + data4 = in.readChar(); + } +} diff --git a/test/src/share/classes/corba/cdrext/TestObject.java b/test/src/share/classes/corba/cdrext/TestObject.java new file mode 100644 index 000000000..7f339da5e --- /dev/null +++ b/test/src/share/classes/corba/cdrext/TestObject.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.util.*; +import java.io.*; + +/** + * Uses PutField/GetField + */ +public class TestObject implements Serializable +{ + private Map internalRep; + + static final long serialVersionUID = 6143829429461952693L; + + static final String STRING_NAME = "stringData"; + static final String BYTE_ARRAY_NAME = "byteArray"; + static final String LONG_NAME = "longData"; + static final String CHAR_NAME = "charData"; + static final String NEW_FIELD_NAME = "cello"; + static final Class NEW_FIELD_CLASS = Integer.class; + + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField(STRING_NAME, String.class), + new ObjectStreamField(BYTE_ARRAY_NAME, byte[].class), + new ObjectStreamField(LONG_NAME, Long.TYPE), + new ObjectStreamField(CHAR_NAME, Character.TYPE), + new ObjectStreamField(NEW_FIELD_NAME, NEW_FIELD_CLASS) + }; + + public TestObject() { + internalRep = new HashMap(); + + internalRep.put(STRING_NAME, "Wookwookwook"); + + byte[] data = new byte[24]; + for (int i = 0; i < data.length; i++) + data[i] = (byte)i; + internalRep.put(BYTE_ARRAY_NAME, data); + + internalRep.put(LONG_NAME, new Long(43)); + + internalRep.put(NEW_FIELD_NAME, new Integer(4523)); + + internalRep.put(CHAR_NAME, new Character('\u6D77')); + } + + public TestObject(String str, + byte[] data, + long lg, + char ch, + Integer newField) { + + this(); + + internalRep.put(STRING_NAME, new String(str)); + + byte[] newArray = new byte[data.length]; + System.arraycopy(data, 0, newArray, 0, data.length); + + internalRep.put(BYTE_ARRAY_NAME, newArray); + internalRep.put(LONG_NAME, new Long(lg)); + internalRep.put(CHAR_NAME, new Character(ch)); + internalRep.put(NEW_FIELD_NAME, newField); + } + + public boolean equals(Object obj) { + try { + TestObject to = (TestObject)obj; + + if (!internalRep.get(STRING_NAME).equals(to.internalRep.get(STRING_NAME))) + return false; + + if (!internalRep.get(LONG_NAME).equals(to.internalRep.get(LONG_NAME))) + return false; + + if (!internalRep.get(CHAR_NAME).equals(to.internalRep.get(CHAR_NAME))) + return false; + + byte[] thisArray = (byte[])internalRep.get(BYTE_ARRAY_NAME); + byte[] otherArray = (byte[])to.internalRep.get(BYTE_ARRAY_NAME); + + return Arrays.equals(thisArray, otherArray); + + } catch (ClassCastException cce) { + return false; + } + } + + private void readObject(java.io.ObjectInputStream s) + throws java.io.IOException, ClassNotFoundException { + + ObjectInputStream.GetField fields = s.readFields(); + + System.out.println("Got: " + fields.getClass().getName()); + + String strData = (String)fields.get(STRING_NAME, null); + byte[] byteData = (byte[])fields.get(BYTE_ARRAY_NAME, null); + long lgData = (long)fields.get(LONG_NAME, (long)0); + char chData = (char)fields.get(CHAR_NAME, (char)'0'); + Integer newField = (Integer)fields.get(NEW_FIELD_NAME, + new Integer(0)); + + if (chData == '0') + System.out.println("chData defaulted"); + else + System.out.println("chData not defaulted -- " + (int)chData); + + if (strData == null) + System.out.println("String data defaulted"); + + if (newField.equals(new Integer(0))) { + System.out.println("The new field was defaulted"); + } + + internalRep = new HashMap(); + + internalRep.put(STRING_NAME, strData); + internalRep.put(BYTE_ARRAY_NAME, byteData); + internalRep.put(LONG_NAME, new Long(lgData)); + internalRep.put(CHAR_NAME, new Character(chData)); + internalRep.put(NEW_FIELD_NAME, newField); + } + + private void writeObject(ObjectOutputStream s) throws IOException { + + System.out.println("In writeObject"); + + ObjectOutputStream.PutField fields = s.putFields(); + + System.out.println("Got: " + fields.getClass().getName()); + + if (internalRep.get(STRING_NAME) == null) + System.out.println("--- String is null"); + if (internalRep.get(BYTE_ARRAY_NAME) == null) + System.out.println("--- byte array is null"); + if (internalRep.get(LONG_NAME) == null) + System.out.println("--- Long is null"); + if (internalRep.get(CHAR_NAME) == null) + System.out.println("--- Char is null"); + if (internalRep.get(NEW_FIELD_NAME) == null) + System.out.println("--- " + NEW_FIELD_NAME + " is null"); + + fields.put(NEW_FIELD_NAME, internalRep.get(NEW_FIELD_NAME)); + fields.put(STRING_NAME, internalRep.get(STRING_NAME)); + fields.put(BYTE_ARRAY_NAME, internalRep.get(BYTE_ARRAY_NAME)); + fields.put(LONG_NAME, ((Long)internalRep.get(LONG_NAME)).longValue()); + fields.put(CHAR_NAME, ((Character)internalRep.get(CHAR_NAME)).charValue()); + + s.writeFields(); + } +} diff --git a/test/src/share/classes/corba/cdrext/Tester.java b/test/src/share/classes/corba/cdrext/Tester.java new file mode 100644 index 000000000..f24a4a255 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/Tester.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +import java.rmi.*; +import java.io.*; +import java.util.*; +import java.sql.Date; + +public interface Tester extends Remote, AbsTester { + + Object verify(Object obj) throws RemoteException; + + Map verify(Map map) throws RemoteException; + + List verify(List list) throws RemoteException; + + Date verify(Date date) throws RemoteException; + + Properties verify(Properties props) throws RemoteException; + + MarshalTester verify(byte[] predata, MarshalTester input, byte[] postdata) + throws RemoteException, DataCorruptedException; + + Hashtable verify(Hashtable table) throws RemoteException; + + void throwRuntimeException() throws RemoteException; + + void throwRemoteException() throws RemoteException; + + void throwCheckedException() + throws CheckedException, RemoteException; + + AbsTester getAbsTester() throws RemoteException; +} diff --git a/test/src/share/classes/corba/cdrext/UncheckedException.java b/test/src/share/classes/corba/cdrext/UncheckedException.java new file mode 100644 index 000000000..41e2b1ea5 --- /dev/null +++ b/test/src/share/classes/corba/cdrext/UncheckedException.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrext; + +public class UncheckedException extends RuntimeException { + public UncheckedException(String msg) { + super(msg); + } +} diff --git a/test/src/share/classes/corba/cdrstreams/CDRTests.java b/test/src/share/classes/corba/cdrstreams/CDRTests.java new file mode 100644 index 000000000..0e1cbf2b8 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/CDRTests.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.orb.ORB; + +public class CDRTests extends CORBATest +{ + protected void doTest() throws Throwable { + + if (test.Test.useJavaSerialization()) { + return; + } + + Controller orbd = createORBD(); + Controller server = createServer("corba.cdrstreams.Server"); + Controller client = createClient("corba.cdrstreams.Client"); + + orbd.start(); + server.start(); + client.start(); + + client.waitFor(180000); + + client.stop(); + server.stop(); + orbd.stop(); + } +} + diff --git a/test/src/share/classes/corba/cdrstreams/Client.java b/test/src/share/classes/corba/cdrstreams/Client.java new file mode 100644 index 000000000..ee0f57b49 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/Client.java @@ -0,0 +1,394 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import javax.rmi.PortableRemoteObject; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.* ; +import java.rmi.RemoteException; +import java.io.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +import org.testng.annotations.Test ; +import org.testng.annotations.BeforeSuite ; + +import corba.framework.TestngRunner ; + +public class Client +{ + GraphProcessor processor ; + + @Test + public void testIndirection1() throws RemoteException, InvalidGraphException + { + System.out.println("---- testIndirection1 ----"); + + Node start = new Node("start", new Vector()); + + // Add a bunch of self links + start.links.add(start); + start.links.add(start); + start.links.add(start); + start.links.add(start); + start.links.add(start); + + // If indirection isn't used, this will result in an infinite loop + // and a stack overflow error + processor.process(start); + } + + private void testObjectArray( java.lang.Object array[]) throws RemoteException, Exception + { + for (int i = 0; i < array.length; i++) { + if (!array[i].equals(processor.verifyTransmission(array[i]))) + throw new Exception("Object of type " + array[i].getClass().getName() + + "at index " + i + " failed verifyTransmission"); + } + } + + @Test + public void testComplexHashtableTest() throws RemoteException, Exception + { + System.out.println("---- complex Hashtable Test ----"); + + Node a = createNode(1024, 'A'); + Node b = createNode(577, 'B'); + Node c = createNode(222, 'C'); + Node d = createNode(799, 'D'); + Node e = createNode(1024, 'E'); + + a.links.add(b); + b.links.add(c); + c.links.add(d); + d.links.add(e); + e.links.add(a); + c.links.add(c); + b.links.add(d); + a.links.add(e); + + String aStr = "A"; + String bStr = "B"; + String cStr = "C"; + String dStr = "D"; + String eStr = "E"; + + Hashtable complex = new Hashtable(); + + complex.put(aStr, a); + complex.put(bStr, b); + complex.put(cStr, c); + complex.put(dStr, d); + complex.put(eStr, e); + + Hashtable result = (Hashtable)processor.verifyTransmission(complex); + + if (result.size() != complex.size()) + throw new Exception("Result has fewer items: " + result.size()); + + Node resA = (Node)result.get(aStr); + Node resB = (Node)result.get(bStr); + Node resC = (Node)result.get(cStr); + Node resD = (Node)result.get(dStr); + Node resE = (Node)result.get(eStr); + + if (!a.equals(resA)) + throw new Exception("result a != a"); + if (!b.equals(resB)) + throw new Exception("result b != b"); + if (!c.equals(resC)) + throw new Exception("result c != c"); + if (!d.equals(resD)) + throw new Exception("result d != d"); + if (!e.equals(resE)) + throw new Exception("result e != e"); + + System.out.println("PASSED"); + } + + public void simpleHashtableTest() + throws RemoteException, Exception + { + System.out.println("---- simple Hashtable Test ----"); + + Hashtable simple = new Hashtable(); + + byte strBytes1[] = new byte[1024]; + byte strBytes2[] = new byte[1024]; + + for (int i = 0; i < 1024; i++) { + strBytes1[i] = (byte)'A'; + strBytes2[i] = (byte)'B'; + } + + String one = new String(strBytes1); + String two = new String(strBytes2); + java.lang.Object oneKey = new Integer(1); + java.lang.Object twoKey = new Integer(2); + + simple.put(oneKey, one); + simple.put(twoKey, two); + + Hashtable result = (Hashtable)processor.verifyTransmission(simple); + + String oneTest = (String)result.get(oneKey); + if (oneTest == null) + throw new Exception("String one not in result Hashtable"); + if (!one.equals(oneTest)) + throw new Exception("String one doesn't equal result string one"); + + String twoTest = (String)result.get(twoKey); + if (twoTest == null) + throw new Exception("String two not in result Hashtable"); + if (!two.equals(twoTest)) + throw new Exception("String two doesn't equal result string two"); + + System.out.println("PASSED"); + } + + @Test + public void testCustomMarshalers() throws RemoteException, Exception + { + System.out.println("---- testCustomMarshalers ----"); + + // First test a value with a good custom marshaler (one that + // correctly reads everything off the stream it should) + + System.out.println("Testing good custom marshalers..."); + + java.lang.Object good[] = new java.lang.Object[100]; + for (int i = 0; i < good.length; i++) + good[i] = new CustomMarshaled(i, i + 100, true); + testObjectArray(good); + + System.out.println("Testing buggy ones that leave bytes when reading..."); + + // Our code should skip over anything incorrectly left on the wire by + // the custom marshaler + java.lang.Object buggy[] = new java.lang.Object[100]; + for (int i = 0; i < buggy.length; i++) { + if (i % 7 == 0) + buggy[i] = new CustomMarshaled(i, i + 100, false); + else + buggy[i] = new CustomMarshaled(i, i + 100, true); + } + + testObjectArray(buggy); + + System.out.println("Testing a buggy one that tries to read too much..."); + + try { + // This should throw a MARSHAL exception (changed to IOException) + processor.verifyTransmission(new OverReader()); + + throw new Exception("Didn't throw an error for an overread"); + + } catch (java.io.IOException e) { + System.out.println("Successful"); + } + } + + private static class OverReader implements java.io.Serializable + { + private void writeObject(java.io.ObjectOutputStream out) + throws java.io.IOException + { + out.defaultWriteObject(); + } + + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, ClassNotFoundException + { + in.defaultReadObject(); + + // Try to read too much + in.readDouble(); + } + } + + @Test + public void testLargeArray() + throws RemoteException, Exception + { + System.out.println("---- testLargeArray ----"); + + long bigArray[] = new long[32000]; + + for (int i = 0; i < bigArray.length; i++) + bigArray[i] = i; + + java.lang.Object resultObj = processor.verifyTransmission(bigArray); + + long testArray[] = (long[])resultObj; + + for (int i = 0; i < bigArray.length; i++) + if (bigArray[i] != testArray[i]) + throw new Exception("Array differed at index " + i + + " with values " + bigArray[i] + + " != " + testArray[i]); + + System.out.println("PASSED"); + } + + public Node createNode(int valueSize, char filler) + { + char valueBuf[] = new char[valueSize]; + + for (int i = 0; i < valueSize; i++) + valueBuf[i] = filler; + + return new Node(new String(valueBuf), new Vector()); + } + + @Test + public void testIndirectionAndOffset() + throws RemoteException, InvalidGraphException, Exception + { + System.out.println("---- testIndirectionAndOffset ----"); + + Node start = createNode(500, 'A'); + + // Add some self links + start.links.add(start); + start.links.add(start); + + Node second = createNode(500, 'B'); + + // Add a two way link to the second node + second.links.add(start); + start.links.add(second); + + processor.process(start); + + // Now try something much harder + + Node a1 = createNode(500, '1'); + Node a2 = createNode(500, '2'); + Node a3 = createNode(256, '3'); + Node a4 = createNode(1024, '4'); + Node a5 = createNode(10000, '5'); + + a1.links.add(a2); + a2.links.add(a3); + a3.links.add(a4); + a4.links.add(a5); + a5.links.add(a1); + a3.links.add(a1); + a4.links.add(a2); + a1.links.add(a4); + + Node start2 = a1; + Node result2 = (Node)processor.verifyTransmission(start2); + + if (!start2.equals(result2)) + throw new Exception("start2 did not equal result2"); + + Node xa2 = (Node)result2.links.get(0); + Node xa3 = (Node)xa2.links.get(0); + Node xa4 = (Node)xa3.links.get(0); + Node xa5 = (Node)xa4.links.get(0); + + if (!a2.equals(xa2)) + throw new Exception("a2 did not equal xa2"); + if (!a3.equals(xa3)) + throw new Exception("a3 did not equal xa3"); + if (!a4.equals(xa4)) + throw new Exception("a4 did not equal xa4"); + if (!a5.equals(xa5)) + throw new Exception("a5 did not equal xa5"); + + System.out.println("Success!"); + } + + @Test + public void testUserException() throws RemoteException, Exception + { + System.out.println("---- testExceptionsAndReset ----"); + + // User exceptions use mark/reset to peek the exception ID + + Node start = new Node(new String("Invalid Node"), null); + + try { + processor.process(start); + + throw new Exception("Didn't get InvalidGraphException!"); + + } catch (InvalidGraphException ex) { + System.out.println("Successfully caught exception: " + + ex); + } + + System.out.println("PASSED"); + } + + + @Test + public void testMarkReset() throws RemoteException, Exception + { + System.out.println("---- Testing mark and reset ----"); + + Properties props = System.getProperties(); + + // Anything much larger makes this test prohibitively slow + props.put(ORBConstants.GIOP_FRAGMENT_SIZE, "64"); + + ORB orb = ORB.init(args, System.getProperties()); + + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + NameComponent nc = new NameComponent("GraphProcessor", ""); + NameComponent path[] = {nc}; + + org.omg.CORBA.Object obj = ncRef.resolve(path); + + processor = + (GraphProcessor) PortableRemoteObject.narrow(obj, + GraphProcessor.class); + + MarkResetTester tester = new MarkResetTester(64); + + if (!processor.receiveObject(tester)) + throw new Exception("Server received a null object!"); + + System.out.println("PASSED"); + } + + private static String[] args ; + + @BeforeSuite + public void setup() throws Exception { + ORB orb = ORB.init(args, System.getProperties()); + + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + NameComponent nc = new NameComponent("GraphProcessor", ""); + NameComponent path[] = {nc}; + + org.omg.CORBA.Object obj = ncRef.resolve(path); + + processor = (GraphProcessor) PortableRemoteObject.narrow(obj, + GraphProcessor.class); + } + + public static void main(String args[]) + { + Client.args = args ; + TestngRunner runner = new TestngRunner() ; + runner.registerClass( Client.class ) ; + runner.run() ; + runner.systemExit() ; + } +} diff --git a/test/src/share/classes/corba/cdrstreams/CustomMarshaled.java b/test/src/share/classes/corba/cdrstreams/CustomMarshaled.java new file mode 100644 index 000000000..beb763047 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/CustomMarshaled.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import java.io.*; + +public class CustomMarshaled implements Serializable +{ + int value1; + long value2; + + boolean good; + + public CustomMarshaled(int value1, long value2, boolean good) + { + this.value1 = value1; + this.value2 = value2; + this.good = good; + } + + public boolean equals(Object obj) + { + CustomMarshaled gcm = (CustomMarshaled)obj; + + return (value1 == gcm.value1 && value2 == gcm.value2); + } + + private void writeObject(java.io.ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + byte[] buffer = new byte[1024]; + for (int i = 0; i < buffer.length; i++) + buffer[i] = (byte)(i % 255); + + out.write(buffer); + + out.writeObject("CustomMarshaled 1.0"); + + } + + private void readObject(java.io.ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + if (good) { + byte[] buffer = new byte[1024]; + in.readFully(buffer); + + for (int i = 0; i < buffer.length; i++) + if (buffer[i] != (byte)(i % 255)) + throw new IOException("Data buffer corrupted"); + + if (!((String)(in.readObject())).equals("CustomMarshaled 1.0")) + throw new IOException("Strings didn't match properly"); + } + + // If it's a bad (has a bug) custom marshaler, it leaves the + // string on the wire + } +} diff --git a/test/src/share/classes/corba/cdrstreams/GraphProcessor.java b/test/src/share/classes/corba/cdrstreams/GraphProcessor.java new file mode 100644 index 000000000..f5339b052 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/GraphProcessor.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface GraphProcessor extends java.rmi.Remote +{ + public void process(Node graphStart) + throws RemoteException, InvalidGraphException; + + public Object verifyTransmission(Object input) + throws RemoteException; + + public boolean receiveObject(Object input) + throws RemoteException; +} diff --git a/test/src/share/classes/corba/cdrstreams/GraphProcessorImpl.java b/test/src/share/classes/corba/cdrstreams/GraphProcessorImpl.java new file mode 100644 index 000000000..4379a8422 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/GraphProcessorImpl.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import java.rmi.RemoteException ; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.ORB ; +import java.io.File ; +import java.io.RandomAccessFile ; +import org.omg.PortableServer.POA ; +import java.util.*; + +public class GraphProcessorImpl extends PortableRemoteObject implements GraphProcessor +{ + public GraphProcessorImpl() throws RemoteException + { + super(); + } + + public void process(Node graphStart) throws InvalidGraphException + { + Vector links = graphStart.links; + + if (links == null) + throw new InvalidGraphException("Links vector cannot be null"); + + System.out.println("Received: " + graphStart.value); + + System.out.println("Value size: " + graphStart.value.length()); + System.out.println("Number of links: " + links.size()); + + Enumeration enumeration = links.elements(); + + int i = 0; + while (enumeration.hasMoreElements()) { + Node node = (Node)enumeration.nextElement(); + System.out.println("Link " + (i++) + ": " + + (node == graphStart ? "good" : "bad")); + + } + } + + public Object verifyTransmission(Object input) + { + return input; + } + + public boolean receiveObject(Object input) + { + return input != null; + } +} diff --git a/test/src/share/classes/corba/cdrstreams/InvalidGraphException.java b/test/src/share/classes/corba/cdrstreams/InvalidGraphException.java new file mode 100644 index 000000000..7570e0dfb --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/InvalidGraphException.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +public class InvalidGraphException extends java.lang.Exception +{ + public InvalidGraphException() {} + public InvalidGraphException(String msg) { + super(msg); + } +} diff --git a/test/src/share/classes/corba/cdrstreams/MarkResetTester.java b/test/src/share/classes/corba/cdrstreams/MarkResetTester.java new file mode 100644 index 000000000..fc94ee050 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/MarkResetTester.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import java.io.*; + +public class MarkResetTester implements Serializable +{ + int fragmentSize; + private static final long TESTVALUE = 275125891; + private static final int FRAGMENT_SIZE_MULTIPLIER = 3; + + public MarkResetTester(int fragmentSize) { + this.fragmentSize = fragmentSize; + } + + private void writeObject(java.io.ObjectOutputStream out) + throws IOException + { + out.defaultWriteObject(); + + // Write how many longs are going to be sent + int numLongs = (int)(FRAGMENT_SIZE_MULTIPLIER + * Math.floor(fragmentSize / 8.0)); + out.writeInt(numLongs); + + System.out.println("Writing " + numLongs + " longs"); + + for (int i = 0; i < numLongs; i++) + out.writeLong((long)i); + + // Do the same thing but with Longs + out.writeInt(numLongs); + + System.out.println("Writing " + numLongs + " Longs"); + + // Intermix indirected and new instances with the same value + Long indirectedLong = new Long(TESTVALUE); + for (int i = 0; i < numLongs; i++) { + if (i % 3 == 0) + out.writeObject(indirectedLong); + else + out.writeObject(new Long(TESTVALUE)); + } + + // Try arrays to test special chunking code + int arraySize = (int)(Math.ceil(fragmentSize / 2.0)); + int numArrays = 7; + + System.out.println("Writing " + numArrays + " arrays of " + + arraySize + " ints"); + + out.writeInt(numArrays); + out.writeInt(arraySize); + + int indirectedArray[] = new int[arraySize]; + for (int i = 0; i < indirectedArray.length; i++) + indirectedArray[i] = i + 111; + + for (int i = 0; i < numArrays; i++) { + if (i % 4 == 0) + out.writeObject(indirectedArray); + else { + int newArray[] = new int[arraySize]; + System.arraycopy(indirectedArray, 0, newArray, 0, arraySize); + out.writeObject(newArray); + } + } + + System.out.println("Finished writing"); + } + + private void readObject(java.io.ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + + // Read how many longs are going to follow + int numLongs = in.readInt(); + + System.out.println("Reading " + numLongs + " longs"); + + if (numLongs != (int)(FRAGMENT_SIZE_MULTIPLIER + * Math.floor(fragmentSize / 8.0))) + throw new IOException("Incorrect number of longs: " + numLongs + + " expected " + (FRAGMENT_SIZE_MULTIPLIER + * Math.floor(fragmentSize / 8.0))); + + System.out.println("Testing all possible mark/resets"); + for (int markedLong = 0; markedLong < numLongs; markedLong++) { + + for (int longsToRead = 1; longsToRead <= numLongs - markedLong; longsToRead++) { + + long expectedValue = markedLong; + in.mark(0); + + System.out.println("Mark set for long " + markedLong + + " reading " + longsToRead + " longs"); + + for (int i = 0; i < longsToRead; i++) { + + long value = in.readLong(); + if (value != expectedValue) { + throw new IOException("Expected " + expectedValue + " but read " + + value + " at markedLong=" + markedLong + + " longsToRead=" + longsToRead + + " i=" + i); + } + + expectedValue++; + + } + + in.reset(); + } + + in.readLong(); + } + + int numLongObjs = in.readInt(); + System.out.println("Reading " + numLongObjs + " Longs"); + Long expectedLong = new Long(TESTVALUE); + + if (in.markSupported()) { + // The assumption is that while we use mark/reset internally, + // we don't guarantee it for user level custom marshaling code. + // This is because they could make the following assumption + // (probably indirectly in a graph) + // + // in.mark(100); + // Object obj1a = in.readObject(); + // in.reset(); + // Object obj1b = in.readObject(); + // + // assert obj1a == obj1b + // + // If the stream says markSupported is true, then it should + // allow the above assertion, so test it here: + System.out.println("markSupported true"); + + in.mark(100); + Object obj1a = in.readObject(); + in.reset(); + in.mark(100); + Object obj1b = in.readObject(); + in.reset(); + if (obj1a != obj1b) + throw new IOException("markSupported returned true, but violated contract"); + } + + System.out.println("Testing Longs..."); + + for (int markedLong = 0; markedLong < numLongs; markedLong++) { + for (int longsToRead = 1; longsToRead <= numLongs - markedLong; longsToRead++) { + in.mark(0); + System.out.println("Mark set for Long " + markedLong + + " reading " + longsToRead + " Longs"); + + for (int i = 0; i < longsToRead; i++) { + + Object objectRead = in.readObject(); + + if (!expectedLong.equals(objectRead)) { + throw new IOException("Object " + objectRead + " doesn't match expected " + + expectedLong + " at markedLong=" + markedLong + + " longsToRead=" + longsToRead + + " i=" + i); + } + } + + in.reset(); + } + + in.readObject(); + } + + System.out.println("Now reading arrays of ints"); + int numArrays = in.readInt(); + int arraySize = in.readInt(); + + System.out.println("Array size: " + arraySize); + System.out.println("Number of arrays: " + numArrays); + + int expectedArray[] = new int[arraySize]; + for (int i = 0; i < expectedArray.length; i++) + expectedArray[i] = i + 111; + + for (int markedArray = 0; markedArray < numArrays; markedArray++) { + for (int arraysToRead = 1; arraysToRead <= numArrays - markedArray; arraysToRead++) { + in.mark(0); + + System.out.println("Mark set for array " + markedArray + + " reading " + arraysToRead + " arrays"); + + for (int i = 0; i < arraysToRead; i++) { + Object objectRead = in.readObject(); + + try { + int arrayRead[] = (int[])objectRead; + + for (int x = 0; x < arraySize; x++) { + if (arrayRead[x] != expectedArray[x]) { + throw new IOException("Expected and read arrays differ at index " + + x + ": " + arrayRead[x] + " != " + + expectedArray[x]); + } + } + } catch (ClassCastException cce) { + throw new IOException("Received non-array: " + objectRead.getClass().getName()); + } + } + + in.reset(); + } + + in.readObject(); + } + + System.out.println("Finished reading"); + } +} diff --git a/test/src/share/classes/corba/cdrstreams/Node.java b/test/src/share/classes/corba/cdrstreams/Node.java new file mode 100644 index 000000000..69c6c2da9 --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/Node.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import java.io.Serializable; +import java.util.Vector; + +public class Node implements Serializable +{ + public String value; + public Vector links; + + public Node() + { + value = ""; + links = new Vector(); + } + + public Node(String value, Vector links) + { + this.value = value; + this.links = links; + } + + private boolean valueCompare(Node node1, Node node2) + { + return node1.value.equals(node2.value); + } + + // Light equals method + public boolean equals(Object obj) + { + if (obj == null) + return false; + + if (!(obj instanceof Node)) + return false; + + Node rt = (Node)obj; + + if (!valueCompare(this, rt)) + return false; + + if (this.links.size() != rt.links.size()) + return false; + + for (int i = 0; i < links.size(); i++) { + Node linkl = (Node)this.links.get(i); + Node linkr = (Node)rt.links.get(i); + + if (!valueCompare(linkl, linkr)) + return false; + if (linkl.links.size() != linkr.links.size()) + return false; + } + + return true; + } +} + diff --git a/test/src/share/classes/corba/cdrstreams/Server.java b/test/src/share/classes/corba/cdrstreams/Server.java new file mode 100644 index 000000000..9269e774a --- /dev/null +++ b/test/src/share/classes/corba/cdrstreams/Server.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cdrstreams; + +import org.omg.CORBA.portable.*; +import javax.rmi.PortableRemoteObject; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; +import java.util.Properties; +import org.omg.PortableServer.*; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +public class Server +{ + public static void main(String args[]) + { + try { + Properties props = new Properties( System.getProperties() ) ; + props.setProperty( ORBConstants.DEBUG_PROPERTY, + "subcontract,giop,transport" ) ; + ORB orb = ORB.init(args, props ); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + GraphProcessorImpl impl = new GraphProcessorImpl(); + javax.rmi.CORBA.Tie tie = javax.rmi.CORBA.Util.getTie( impl ) ; + + byte[] id = rootPOA.activate_object( + (org.omg.PortableServer.Servant)tie ) ; + org.omg.CORBA.Object obj = rootPOA.id_to_reference( id ) ; + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("GraphProcessor", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + + // Emit the handshake the test framework expects + // (can be changed in Options by the running test) + System.out.println ("Server is ready."); + + // Wait for clients + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + + // Make sure to exit with a value greater than 0 on + // error. + System.exit(1); + } + } +} diff --git a/test/src/share/classes/corba/cmvt/CMVTTest.java b/test/src/share/classes/corba/cmvt/CMVTTest.java new file mode 100644 index 000000000..bb0939d30 --- /dev/null +++ b/test/src/share/classes/corba/cmvt/CMVTTest.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cmvt; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class CMVTTest extends CORBATest { + static final int GROW = 0; + static final int STREAM = 2; + static String[] GIOP_version = { "1.0", "1.1", "1.2" }; + static String[] GIOP_strategy = { "GROW", "STRM" }; + + private void printBeginTest(int clientVersion, + int clientStrategy, + int serverVersion, + int serverStrategy) + { + StringBuffer output = new StringBuffer(80); + + // Pleasing aesthetics + output.append(" "); + + output.append(GIOP_version[clientVersion]); + output.append(" "); + output.append(GIOP_strategy[clientStrategy]); + output.append(" client <> "); + output.append(GIOP_version[serverVersion]); + output.append(" "); + output.append(GIOP_strategy[serverStrategy]); + output.append(" server: "); + + System.out.print(output.toString()); + } + + private void printEndTest(String result) + { + System.out.println(result); + } + + private void setClient(int version, int strategy){ + Properties clientProps = Options.getClientProperties(); + + int fragmentSize = 1024; + clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize); + + clientProps.put(ORBConstants.GIOP_VERSION, GIOP_version[version]); + clientProps.put(ORBConstants.GIOP_11_BUFFMGR, "" + GIOP_strategy[strategy]); + clientProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + GIOP_strategy[strategy]); + } + + private void setServer(int version, int strategy){ + Properties serverProps = Options.getServerProperties(); + + serverProps.put(ORBConstants.GIOP_VERSION, GIOP_version[version]); + serverProps.put(ORBConstants.GIOP_11_BUFFMGR, "" + GIOP_strategy[strategy]); + serverProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + GIOP_strategy[strategy]); + } + + private void runTest( String name ) throws Throwable{ + Controller server = createServer("corba.cmvt.Server", name); + Controller client = createClient("corba.cmvt.Client", name); + + server.start(); + client.start(); + + client.waitFor(60000); + + if (client.exitValue() != Controller.SUCCESS) { + printEndTest("FAILED, Client exit value = " + client.exitValue()); + } else if (server.finished()) { + printEndTest("FAILED, Server crashed"); + } else { + printEndTest("PASSED"); + } + + client.stop(); + server.stop(); + } + + protected void doTest() throws Throwable + { + int errors = 0; + + // Pleasing aesthetics + System.out.println(); + + //1.0 + grow + setClient(0,0); + setServer(0,0); + printBeginTest(0,0,0,0); + runTest( "1_0_grow" ); + + //1.2 + grow + setClient(2,0); + setServer(2,0); + printBeginTest(2,0,2,0); + runTest( "1_2_grow" ); + + //1.2 + stream + setClient(2,1); + setServer(2,1); + printBeginTest(2,1,2,1); + runTest( "1_2_stream" ); + + System.out.print(" Test result : " ); + + if (errors > 0) + throw new Exception("Errors detected"); + + } +} + diff --git a/test/src/share/classes/corba/cmvt/Client.java b/test/src/share/classes/corba/cmvt/Client.java new file mode 100644 index 000000000..a3e559c15 --- /dev/null +++ b/test/src/share/classes/corba/cmvt/Client.java @@ -0,0 +1,187 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.cmvt; + +import javax.rmi.PortableRemoteObject; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.* ; +import java.rmi.RemoteException; +import java.io.*; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +public class Client +{ + + + public static org.omg.CORBA.Object readObjref(String file, org.omg.CORBA.ORB orb) { + String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file; + try { + java.io.DataInputStream in = + new java.io.DataInputStream(new FileInputStream(fil)); + String ior = in.readLine(); + System.out.println("IOR: "+ior); + return orb.string_to_object(ior); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + return null; + } + + public static CustomMarshalledValueType constructCustomMarshalledValueType(int len, String r){ + CustomMarshalledValueType cmvt = null; + try{ + cmvt = new CustomMarshalledValueType(len, (byte)r.charAt(0)); + } catch (Exception e){ + e.printStackTrace(); + System.exit(1); + } + return cmvt; + } + + public static java.util.Vector constructVector(int len, String r){ + java.util.Vector ht = new java.util.Vector(); + for(int i=0; i clazz, int which) { } + public void checkSecurityAccess(String provider) { } + + public void checkPermission(Permission perm) { + } + + public void checkPermission(Permission perm, Object context) { + } +} diff --git a/test/src/share/classes/corba/codebase/Server.java b/test/src/share/classes/corba/codebase/Server.java new file mode 100644 index 000000000..b909b4f6f --- /dev/null +++ b/test/src/share/classes/corba/codebase/Server.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codebase; + +import java.rmi.*; +import javax.rmi.PortableRemoteObject; +import javax.naming.*; + +import java.io.*; + +public class Server extends PortableRemoteObject implements Tester +{ + public Server() throws java.rmi.RemoteException { + } + + public void printMessage(String message) + { + System.out.println(message); + } + + public Object requestValue() + throws ClassNotFoundException, InstantiationException, IllegalAccessException + { + Class valueClass = Class.forName("TestValue"); + return valueClass.newInstance(); + } + + public String processValue(Object value) + { + Class valueClass = value.getClass(); + + System.out.println("Received instance of: " + valueClass.getName()); + + return valueClass.getName(); + } + + // This is just helpful for debugging to see whether or not the + // server has access to these files. + public static void tryLoadingClasses() + { + System.out.println("java.rmi.server.codebase = " + + System.getProperty("java.rmi.server.codebase")); + + try { + System.out.println("Trying to load the stub class"); + Class stub = Class.forName("corba.codebase._Tester_Stub"); + System.out.println("Server has access to the stub"); + } catch (ClassNotFoundException cnfe) { + System.out.println("Server doesn't have access to the stub"); + } + + try { + System.out.println("Trying to load the tie class"); + Class tie = Class.forName("corba.codebase._Server_Tie"); + System.out.println("Server has access to the tie"); + } catch (ClassNotFoundException cnfe) { + System.out.println("Server doesn't have access to the tie"); + } + + try { + System.out.println("Trying to load the TestValue class"); + Class testValue = Class.forName("TestValue"); + System.out.println("Server has access to the TestValue class"); + } catch (ClassNotFoundException cnfe) { + System.out.println("Server doesn't have access to TestValue"); + } + } + + private static InitialContext rootContext ; + + public static void main(String[] args) { + try { + System.setSecurityManager(new NoSecurityManager()); + + Server.tryLoadingClasses(); + + rootContext = new InitialContext(); + Server p = new Server(); + + rootContext.rebind("Tester", p); + System.out.println("Server is ready."); + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); + } + } +} + diff --git a/test/src/share/classes/corba/codebase/TestValue.java b/test/src/share/classes/corba/codebase/TestValue.java new file mode 100644 index 000000000..68f6a68e6 --- /dev/null +++ b/test/src/share/classes/corba/codebase/TestValue.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Simple value +import java.io.Serializable; + +public class TestValue implements Serializable +{} diff --git a/test/src/share/classes/corba/codebase/Tester.java b/test/src/share/classes/corba/codebase/Tester.java new file mode 100644 index 000000000..508fc94ed --- /dev/null +++ b/test/src/share/classes/corba/codebase/Tester.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codebase; + +public interface Tester extends java.rmi.Remote { + + void printMessage(String message) throws java.rmi.RemoteException; + + Object requestValue() + throws java.rmi.RemoteException, + ClassNotFoundException, + InstantiationException, + IllegalAccessException; + + String processValue(Object value) throws java.rmi.RemoteException; + + String SERVER_DOWNLOADING_FLAG = "SERVER_DOWNLOADING"; +} diff --git a/test/src/share/classes/corba/codebase/WebServer.java b/test/src/share/classes/corba/codebase/WebServer.java new file mode 100644 index 000000000..0c95ac571 --- /dev/null +++ b/test/src/share/classes/corba/codebase/WebServer.java @@ -0,0 +1,555 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.codebase; + +import java.io.*; +import java.net.*; +import java.util.*; + +public class WebServer extends Thread implements HttpConstants { + + PrintStream log = null; + Vector threads = new Vector(); + File root = null; + int timeout = 5000; + int workers = 5; + int port = 31397; + boolean run; + Properties aliases = null; + boolean started = false; + ServerSocket ss = null; + + public static void main(String[] a) throws Exception { + int port = 31397; + String rootPath = System.getProperty("user.dir"); + int threads = 5; + boolean error = false; + Properties aliases = new Properties(); + + for (int i = 0; i < a.length; i++) { + String arg = a[i]; + if (arg.equals("-port")) { + port = Integer.parseInt(a[i+1]); + i++; + } else if (arg.equals("-docroot")) { + rootPath = a[i+1]; + i++; + } else if (arg.equals("-threads")) { + threads = Integer.parseInt(a[i+1]); + i++; + } else if (arg.equals("-alias")) { + String alias = a[i+1]; + int index = alias.indexOf('='); + if (index >=0) { + String key = alias.substring(0,index); + String value = alias.substring(index+1); + aliases.put(key,value); + } else { + System.out.println(alias + " is an invalid alias. Use x=y form."); + error = true; + } + i++; + } else { + error = true; + } + } + + File root = new File(rootPath); + if (!root.exists()) { + System.out.println("docroot '" + rootPath + "' does not exist."); + error = true; + } + + if (!error) { + System.out.println("WebServer(port=" + port + ", " + + "root=" + root + ", " + + "threads=" + threads + ", " + + "aliases=" + aliases + ")"); + WebServer server = new WebServer(port,root,threads,aliases,null); + server.start(); + System.out.println("Ready."); + } else { + System.out.println("Usage: test.WebServer [-port n][-docroot docRootPath][-threads n][-alias x=y]"); + } + } + + public WebServer (int port, File root, int threads) throws Exception { + this(port,root,threads,null,null); + } + + public WebServer (int port, File root, int threads, + Properties aliases, PrintStream log) throws Exception { + this.root = root; + this.port = port; + this.workers = threads; + this.log = log; + run = true; + this.aliases = aliases; + if (this.log == null) { + this.log = new PrintStream(new FileOutputStream(new File(root,"WebServer.log"))); + } + if (aliases != null) { + if (aliases.size() > 0) { + this.log.println("aliases: " + aliases); + } else { + this.log.println("aliases: "); + } + } + } + + /* print to the log file */ + protected void log(String s) { + if (log != null) { + synchronized (log) { + log.println(s); + log.flush(); + } + } + } + + public boolean waitTillReady() { + if (!Thread.currentThread().isAlive()) { + return false; // Died. + } + synchronized(this) { + while (!started) { + try { + wait(); + } catch (InterruptedException e) {} + } + } + return true; + } + + public void quit() { + try { + ss.close(); + } catch (Exception e){} + + run = false; + } + + public void run () { + + try { + /* start worker threads */ + for (int i = 0; i < workers; ++i) { + Worker w = new Worker(this); + (new Thread(w, "worker #"+i)).start(); + threads.addElement(w); + } + + ss = new ServerSocket(port); + + synchronized(this) { + started = true; + notifyAll(); + } + + while (run) { + try { + Socket s = ss.accept(); + Worker w = null; + synchronized (threads) { + if (threads.isEmpty()) { + Worker ws = new Worker(this); + ws.setSocket(s); + (new Thread(ws, "additional worker")).start(); + } else { + w = (Worker) threads.elementAt(0); + threads.removeElementAt(0); + w.setSocket(s); + } + } + } catch (IOException e) {} + } + + + + } catch (Exception e) { + log.println("WebServer died. Caught " + e); + } + } +} + + +class Worker implements HttpConstants, Runnable { + final static int BUF_SIZE = 2048; + + static final byte[] EOL = {(byte)'\r', (byte)'\n' }; + + /* buffer to use for requests */ + byte[] buf; + /* Socket to client we're handling */ + private Socket s; + private WebServer server; + + Worker(WebServer server) { + this.server = server; + buf = new byte[BUF_SIZE]; + s = null; + } + + synchronized void setSocket(Socket s) { + this.s = s; + notify(); + } + + public synchronized void run() { + while(server.run) { + if (s == null) { + /* nothing to do */ + try { + wait(); + } catch (InterruptedException e) { + /* should not happen */ + continue; + } + } + try { + handleClient(); + } catch (Exception e) { + e.printStackTrace(); + } + /* go back in wait queue if there's fewer + * than numHandler connections. + */ + s = null; + Vector pool = server.threads; + synchronized (pool) { + if (pool.size() >= server.workers) { + /* too many threads, exit this one */ + return; + } else { + pool.addElement(this); + } + } + } + } + + void handleClient() throws IOException { + + System.out.println("Handling client"); + + InputStream is = new BufferedInputStream(s.getInputStream()); + PrintStream ps = new PrintStream(s.getOutputStream()); + /* we will only block in read for this many milliseconds + * before we fail with java.io.InterruptedIOException, + * at which point we will abandon the connection. + */ + s.setSoTimeout(server.timeout); + s.setTcpNoDelay(true); + /* zero out the buffer from last time */ + for (int i = 0; i < BUF_SIZE; i++) { + buf[i] = 0; + } + try { + /* We only support HTTP GET/HEAD, and don't + * support any fancy HTTP options, + * so we're only interested really in + * the first line. + */ + int nread = 0, r = 0; + + outerloop: + while (nread < BUF_SIZE) { + r = is.read(buf, nread, BUF_SIZE - nread); + if (r == -1) { + /* EOF */ + return; + } + int i = nread; + nread += r; + for (; i < nread; i++) { + if (buf[i] == (byte)'\n' || buf[i] == (byte)'\r') { + /* read one line */ + break outerloop; + } + } + } + + System.out.println("Full buffer:"); + System.out.println(new String(buf, "US-ASCII")); + + /* are we doing a GET or just a HEAD */ + boolean doingGet; + /* beginning of file name */ + int index; + if (buf[0] == (byte)'G' && + buf[1] == (byte)'E' && + buf[2] == (byte)'T' && + buf[3] == (byte)' ') { + doingGet = true; + index = 4; + } else if (buf[0] == (byte)'H' && + buf[1] == (byte)'E' && + buf[2] == (byte)'A' && + buf[3] == (byte)'D' && + buf[4] == (byte)' ') { + doingGet = false; + index = 5; + } else { + /* we don't support this method */ + ps.print("HTTP/1.0 " + HTTP_BAD_METHOD + + " unsupported method type: "); + ps.write(buf, 0, 5); + ps.write(EOL); + ps.flush(); + s.close(); + return; + } + + int i = 0; + /* find the file name, from: + * GET /foo/bar.html HTTP/1.0 + * extract "/foo/bar.html" + */ + for (i = index; i < nread; i++) { + if (buf[i] == (byte)' ') { + break; + } + } + + String fname = new String(buf,index,i-index,"US-ASCII"); +/* Deprecate constructor + String fname = new String(buf, 0, index,i-index); + */ + fname = checkAliases(fname).replace('/', File.separatorChar); + if (fname.startsWith(File.separator)) { + fname = fname.substring(1); + } + + System.out.println("Looking in root: " + server.root); + System.out.println("For file: " + fname); + + File targ = new File(server.root, fname); + if (targ.isDirectory()) { + File ind = new File(targ, "index.html"); + if (ind.exists()) { + targ = ind; + } + } + + boolean OK = printHeaders(targ, ps); + if (doingGet) { + if (OK) { + server.log("GET "+targ+". OK"); + sendFile(targ, ps); + } else { + server.log("GET "+targ+". NOT FOUND"); + send404(targ, ps); + } + } else { + server.log("HEAD "+targ+" OK"); + } + } finally { + ps.flush(); + ps.close(); + s.close(); + } + } + + String checkAliases (String name) { + String result = name; + if (server.aliases != null) { + String temp = (String) server.aliases.get(name); + if (temp != null) { + result = temp; + } + } + server.log.println("checkAliases: " + name + " --> " + result); + return result; + } + + boolean printHeaders(File targ, PrintStream ps) throws IOException { + boolean ret = false; + int rCode = 0; + if (!targ.exists()) { + rCode = HTTP_NOT_FOUND; + ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found"); + ps.write(EOL); + ret = false; + } else { + rCode = HTTP_OK; + ps.print("HTTP/1.0 " + HTTP_OK+" OK"); + ps.write(EOL); + ret = true; + } + server.log("From " +s.getInetAddress().getHostAddress()+": GET " + + targ.getAbsolutePath()+"-->"+rCode); + ps.print("Server: Simple java"); + ps.write(EOL); + ps.print("Date: " + (new Date())); + ps.write(EOL); + if (ret) { + if (!targ.isDirectory()) { + ps.print("Content-length: "+targ.length()); + ps.write(EOL); + ps.print("Last Modified: " + (new + Date(targ.lastModified()))); + ps.write(EOL); + String name = targ.getName(); + int ind = name.lastIndexOf('.'); + String ct = null; + if (ind > 0) { + ct = (String) map.get(name.substring(ind)); + } + if (ct == null) { + ct = "unknown/unknown"; + } + ps.print("Content-type: " + ct); + ps.write(EOL); + } else { + ps.print("Content-type: text/html"); + ps.write(EOL); + } + ps.write(EOL); // Bryan + } + return ret; + } + +void send404(File targ, PrintStream ps) throws IOException { + ps.write(EOL); + ps.write(EOL); + ps.println("Not Found\n\n"+ + "The requested resource was not found.\n"); +} + +void sendFile(File targ, PrintStream ps) throws IOException { + InputStream is = null; + if (targ.isDirectory()) { + listDirectory(targ, ps); + return; + } else { + server.log.print("sendFile: " + targ.getAbsolutePath() + ", length = " + targ.length()); + is = new FileInputStream(targ.getAbsolutePath()); + } + int sent = 0; + try { + int n; + while ((n = is.read(buf)) > 0) { + ps.write(buf, 0, n); + sent += n; + } + server.log.println(", sent = " + sent); + + System.out.println("Sent file: " + targ.getAbsolutePath()); + + } catch (Exception e) { + server.log.println(", CAUGHT = " + e); + } finally { + // ps.flush(); + is.close(); + } +} + +/* mapping of file extensions to content-types */ +static java.util.Hashtable map = new java.util.Hashtable(); + +static { + fillMap(); +} +static void setSuffix(String k, String v) { + map.put(k, v); +} + +static void fillMap() { + setSuffix("", "content/unknown"); + setSuffix(".uu", "application/octet-stream"); + setSuffix(".exe", "application/octet-stream"); + setSuffix(".ps", "application/postscript"); + setSuffix(".zip", "application/zip"); + setSuffix(".sh", "application/x-shar"); + setSuffix(".tar", "application/x-tar"); + setSuffix(".snd", "audio/basic"); + setSuffix(".au", "audio/basic"); + setSuffix(".wav", "audio/x-wav"); + setSuffix(".gif", "image/gif"); + setSuffix(".jpg", "image/jpeg"); + setSuffix(".jpeg", "image/jpeg"); + setSuffix(".htm", "text/html"); + setSuffix(".html", "text/html"); + setSuffix(".text", "text/plain"); + setSuffix(".c", "text/plain"); + setSuffix(".cc", "text/plain"); + setSuffix(".c++", "text/plain"); + setSuffix(".h", "text/plain"); + setSuffix(".pl", "text/plain"); + setSuffix(".txt", "text/plain"); + setSuffix(".java", "text/plain"); + setSuffix(".class", "application/java"); + setSuffix(".clz", "application/java"); +} + + void listDirectory(File dir, PrintStream ps) throws IOException { + ps.println("Directory listing

                \n"); + ps.println("Parent Directory
                \n"); + String[] list = dir.list(); + for (int i = 0; list != null && i < list.length; i++) { + File f = new File(dir, list[i]); + if (f.isDirectory()) { + ps.println(""+list[i]+"/
                "); + } else { + ps.println(""+list[i]+"



                " + (new Date()) + ""); + } + +} + +interface HttpConstants { + /** 2XX: generally "OK" */ + public static final int HTTP_OK = 200; + public static final int HTTP_CREATED = 201; + public static final int HTTP_ACCEPTED = 202; + public static final int HTTP_NOT_AUTHORITATIVE = 203; + public static final int HTTP_NO_CONTENT = 204; + public static final int HTTP_RESET = 205; + public static final int HTTP_PARTIAL = 206; + + /** 3XX: relocation/redirect */ + public static final int HTTP_MULT_CHOICE = 300; + public static final int HTTP_MOVED_PERM = 301; + public static final int HTTP_MOVED_TEMP = 302; + public static final int HTTP_SEE_OTHER = 303; + public static final int HTTP_NOT_MODIFIED = 304; + public static final int HTTP_USE_PROXY = 305; + + /** 4XX: client error */ + public static final int HTTP_BAD_REQUEST = 400; + public static final int HTTP_UNAUTHORIZED = 401; + public static final int HTTP_PAYMENT_REQUIRED = 402; + public static final int HTTP_FORBIDDEN = 403; + public static final int HTTP_NOT_FOUND = 404; + public static final int HTTP_BAD_METHOD = 405; + public static final int HTTP_NOT_ACCEPTABLE = 406; + public static final int HTTP_PROXY_AUTH = 407; + public static final int HTTP_CLIENT_TIMEOUT = 408; + public static final int HTTP_CONFLICT = 409; + public static final int HTTP_GONE = 410; + public static final int HTTP_LENGTH_REQUIRED = 411; + public static final int HTTP_PRECON_FAILED = 412; + public static final int HTTP_ENTITY_TOO_LARGE = 413; + public static final int HTTP_REQ_TOO_LONG = 414; + public static final int HTTP_UNSUPPORTED_TYPE = 415; + + /** 5XX: server error */ + public static final int HTTP_SERVER_ERROR = 500; + public static final int HTTP_INTERNAL_ERROR = 501; + public static final int HTTP_BAD_GATEWAY = 502; + public static final int HTTP_UNAVAILABLE = 503; + public static final int HTTP_GATEWAY_TIMEOUT = 504; + public static final int HTTP_VERSION = 505; +} + + + diff --git a/test/src/share/classes/corba/connectioncache/Client.java b/test/src/share/classes/corba/connectioncache/Client.java new file mode 100644 index 000000000..52cf547b5 --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/Client.java @@ -0,0 +1,627 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache ; + +import java.util.Collection ; +import java.util.List ; +import java.util.ArrayList ; +import java.util.Set ; +import java.util.HashSet ; + +import java.util.logging.Logger ; +import java.util.logging.Handler ; +import java.util.logging.Level ; +import java.util.logging.StreamHandler ; +import java.util.logging.Formatter ; +import java.util.logging.LogRecord ; + +import java.io.IOException ; + +import org.testng.Assert ; +import org.testng.annotations.Test ; + +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueue ; +import com.sun.corba.ee.spi.transport.concurrent.ConcurrentQueueFactory ; + +import com.sun.corba.ee.spi.transport.connection.ConnectionFinder ; +import com.sun.corba.ee.spi.transport.connection.ConnectionCache ; +import com.sun.corba.ee.spi.transport.connection.ContactInfo ; +import com.sun.corba.ee.spi.transport.connection.InboundConnectionCache ; +import com.sun.corba.ee.spi.transport.connection.OutboundConnectionCache ; +import com.sun.corba.ee.spi.transport.connection.ConnectionCacheFactory ; + +import corba.framework.TestngRunner ; + +public class Client { + // Ignore all of the LogRecord information except the message. + public static class ReallySimpleFormatter extends Formatter { + public synchronized String format( LogRecord record ) { + return record.getMessage() + "\n" ; + } + } + + // Similar to ConsoleHandler, but outputs to System.out + // instead of System.err, which works better with the + // CORBA test framework. + public static class SystemOutputHandler extends StreamHandler { + public SystemOutputHandler() { + try { + setLevel(Level.FINER); + setFilter(null); + setFormatter(new ReallySimpleFormatter()); + setEncoding(null); + setOutputStream(System.out); + } catch (Exception exc) { + System.out.println( "Caught unexpected exception " + exc ) ; + } + } + + @Override + public void publish(LogRecord record) { + super.publish(record); + flush(); + } + + @Override + public void close() { + flush(); + } + } + + private static final boolean DEBUG = false ; + + private static final Logger logger = Logger.getLogger( "test.corba" ) ; + private static final Handler handler = new SystemOutputHandler() ; + + static { + if (DEBUG) { + logger.setLevel( Level.FINER ) ; + logger.addHandler( handler ) ; + } + } + + private static final int NUMBER_TO_RECLAIM = 1 ; + private static final int MAX_PARALLEL_CONNECTIONS = 4 ; + private static final int HIGH_WATER_MARK = 20 ; // must be a multiple of + // MAX_PARALLEL_CONNECTIONS + // for outboundCacheTest4. + private static final int TTL = 2*60*1000 ; // 2 minute TTL (time to live) + // for reclaimable connections + + private static final OutboundConnectionCache obcache = + ConnectionCacheFactory. + makeBlockingOutboundConnectionCache( + "BlockingOutboundCache", HIGH_WATER_MARK, NUMBER_TO_RECLAIM, + MAX_PARALLEL_CONNECTIONS, TTL ) ; + + private static final InboundConnectionCache ibcache = + ConnectionCacheFactory. + makeBlockingInboundConnectionCache( + "BlockingInboundCache", HIGH_WATER_MARK, NUMBER_TO_RECLAIM, TTL ) ; + + private void testBanner( String msg ) { + if (DEBUG) { + System.out.println( + "=======================================" + + "==============================" ) ; + + System.out.println( msg ) ; + + System.out.println( + "=======================================" + + "==============================" ) ; + } + } + + // Test ConcurrentQueue + @Test() + public void nonBlockingConcurrentQueueTest() { + testBanner( "nonBlockingConccurentQueueTest" ) ; + ConcurrentQueue testQ = + ConcurrentQueueFactory.makeConcurrentQueue( TTL ) ; + testConcurrentQueue( testQ ) ; + } + + private ConcurrentQueue.Handle addData( + ConcurrentQueue arg, + int[] data, int valueForHandleToReturn ) { + + ConcurrentQueue.Handle savedHandle = null ; + + for (int val : data) { + ConcurrentQueue.Handle handle = arg.offer( val ) ; + if (val == valueForHandleToReturn) { + savedHandle = handle ; + } + } + + return savedHandle ; + } + + private void destructiveValidation( ConcurrentQueue queue, + int[] master ) { + + Assert.assertEquals( queue.size(), master.length ) ; + for (int val : master) { + int qval = queue.poll().value() ; + Assert.assertEquals( val, qval ) ; + } + } + + private void testConcurrentQueue( ConcurrentQueue arg ) { + final int[] data = { 23, 43, 51, 3, 7, 9, 22, 33 } ; + final int valueToDelete = 51 ; + final int[] dataAfterDelete = { 23, 43, 3, 7, 9, 22, 33 } ; + + addData( arg, data, valueToDelete ) ; + + destructiveValidation( arg, data ) ; + + final ConcurrentQueue.Handle delHandle = + addData( arg, data, valueToDelete ) ; + + delHandle.remove() ; + + destructiveValidation( arg, dataAfterDelete ) ; + } + + private void checkStat( long actual, long expected, String type ) { + Assert.assertEquals( actual, expected, type ) ; + } + + private void checkStats( ConnectionCache cc, int idle, int reclaimable, + int busy, int total ) { + + checkStat( cc.numberOfIdleConnections(), idle, + "Idle connections" ) ; + checkStat( cc.numberOfReclaimableConnections(), reclaimable, + "Reclaimable connections" ) ; + checkStat( cc.numberOfBusyConnections(), busy, + "Busy connections" ) ; + checkStat( cc.numberOfConnections(), total, + "Total connections" ) ; + } + + // Each of the simple tests expects that all connections in the cache have + // been closed, which may not be the case if a test fails. So we impose + // an order on the tests to make sure that we stop if a test leaves things + // in a bad state. + // + // Inbound and Outbound can be tested independently. + + // Do a single get/release/responseReceived cycle + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest"}) + public void outboundTest1() throws IOException { + testBanner( "outboundTest1: single cycle" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "FirstContact" ) ; + ConnectionImpl c1 = obcache.get( cinfo ) ; + checkStats( obcache, 0, 0, 1, 1 ) ; + + obcache.release( c1, 1 ) ; + checkStats( obcache, 1, 0, 0, 1 ) ; + + obcache.responseReceived( c1 ) ; + checkStats( obcache, 1, 1, 0, 1 ) ; + + obcache.close( c1 ) ; + checkStats( obcache, 0, 0, 0, 0 ) ; + } + + // Do two interleaved get/release/responseReceived cycles + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest", "outboundTest1"}) + public void outboundTest2() throws IOException { + testBanner( "outboundTest2: 2 cycles interleaved" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "FirstContact" ) ; + ConnectionImpl c1 = obcache.get( cinfo ) ; + checkStats( obcache, 0, 0, 1, 1 ) ; + + ConnectionImpl c2 = obcache.get( cinfo ) ; + checkStats( obcache, 0, 0, 2, 2 ) ; + + Assert.assertNotSame( c1, c2) ; + + obcache.release( c1, 1 ) ; + checkStats( obcache, 1, 0, 1, 2 ) ; + + obcache.release( c2, 1 ) ; + checkStats( obcache, 2, 0, 0, 2 ) ; + + obcache.responseReceived( c1 ) ; + checkStats( obcache, 2, 1, 0, 2 ) ; + + obcache.responseReceived( c2 ) ; + checkStats( obcache, 2, 2, 0, 2 ) ; + + obcache.close( c2 ) ; + checkStats( obcache, 1, 1, 0, 1 ) ; + + obcache.close( c1 ) ; + checkStats( obcache, 0, 0, 0, 0 ) ; + } + + // Do enough gets to start using busy connections. + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest", "outboundTest2"}) + public void outboundTest3() throws IOException { + testBanner( "outboundTest3: cycle to busy connections" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "FirstContact" ) ; + Set conns = new HashSet() ; + for (int ctr=0; ctr cinfos = new ArrayList() ; + for (int ctr=0; ctr> csa = + new ArrayList>() ; + for (int ctr=0; ctr set = new HashSet() ; + csa.add( set ) ; + for (int num=0; num conns : csa ) { + for (ConnectionImpl conn : conns) { + obcache.close( conn ) ; + } + } + checkStats( obcache, 0, 0, 0, 0 ) ; + } + + // Test a ContactInfoImpl that throws an IOException + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest", "outboundTest4"}, + expectedExceptions={IOException.class}) + public void outboundTest5() throws IOException { + testBanner( "outboundTest5: test connection open error" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "ExceptionTest" ) ; + cinfo.setUnreachable( true ) ; + try { + obcache.get( cinfo ) ; // should throw an IOException + } finally { + checkStats( obcache, 0, 0, 0, 0 ) ; + cinfo.setUnreachable( false ) ; + } + } + + private static V getSecondOrFirst( Collection coll ) { + V first = null ; + V second = null ; + int count = 0 ; + for (V v : coll) { + if (count == 0) { + first = v ; + } else if (count == 1) { + return v ; + } else { + break ; + } + count++ ; + } + return first ; + } + + // Several tests for ConnectionFinders + private static ConnectionFinder cf1 = + new ConnectionFinder() { + public ConnectionImpl find( + ContactInfo cinfo, + Collection idleConnections, + Collection busyConnections + ) throws IOException { + + return getSecondOrFirst( idleConnections ) ; + } + } ; + + private static ConnectionFinder cf2 = + new ConnectionFinder() { + public ConnectionImpl find( + ContactInfo cinfo, + Collection idleConnections, + Collection busyConnections + ) throws IOException { + + return getSecondOrFirst( busyConnections ) ; + } + } ; + + private static ConnectionFinder cf3 = + new ConnectionFinder() { + public ConnectionImpl find( + ContactInfo cinfo, + Collection idleConnections, + Collection busyConnections + ) throws IOException { + + return cinfo.createConnection() ; + } + } ; + + private static ConnectionFinder cf4 = + new ConnectionFinder() { + public ConnectionImpl find( + ContactInfo cinfo, + Collection idleConnections, + Collection busyConnections + ) throws IOException { + + return null ; + } + } ; + + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest", "outboundTest4"}) + private void outboundTest6() throws IOException { + testBanner( "outboundTest6: test ConnectionFinder non-error case" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "CFTest" ) ; + + // Set up 2 idle and 2 busy connections on cinfo + ConnectionImpl idle1 = obcache.get( cinfo ) ; + ConnectionImpl idle2 = obcache.get( cinfo ) ; + ConnectionImpl busy1 = obcache.get( cinfo ) ; + ConnectionImpl busy2 = obcache.get( cinfo ) ; + obcache.release( idle1, 0 ) ; + obcache.release( idle2, 0 ) ; + checkStats( obcache, 2, 2, 2, 4 ) ; + + // Test cf1 + ConnectionImpl test = obcache.get( cinfo, cf1 ) ; + Assert.assertEquals( test, idle2 ) ; + checkStats( obcache, 1, 1, 3, 4 ) ; + obcache.release( test, 0 ) ; + checkStats( obcache, 2, 2, 2, 4 ) ; + + // Test cf2 + test = obcache.get( cinfo, cf2 ) ; + Assert.assertEquals( test, busy2 ) ; + checkStats( obcache, 2, 2, 2, 4 ) ; + obcache.release( test, 0 ) ; + checkStats( obcache, 2, 2, 2, 4 ) ; + obcache.release( busy2, 0 ) ; + checkStats( obcache, 3, 3, 1, 4 ) ; + + // Test cf3 + test = obcache.get( cinfo, cf3 ) ; + checkStats( obcache, 3, 3, 2, 5 ) ; + obcache.release( test, 0 ) ; + checkStats( obcache, 4, 4, 1, 5 ) ; + obcache.close( test ) ; + checkStats( obcache, 3, 3, 1, 4 ) ; + + // Test cf4 + test = obcache.get( cinfo, cf4 ) ; + checkStats( obcache, 2, 2, 2, 4 ) ; + obcache.release( test, 0 ) ; + checkStats( obcache, 3, 3, 1, 4 ) ; + + obcache.close( idle1 ) ; + obcache.close( idle2 ) ; + obcache.close( busy1 ) ; + obcache.close( busy2 ) ; + checkStats( obcache, 0, 0, 0, 0 ) ; + } + + @Test( expectedExceptions = { IOException.class } ) + private void outboundTest7() throws IOException { + testBanner( "outboundTest7: test ConnectionFinder error case" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "CFTest" ) ; + cinfo.setUnreachable( true ) ; + try { + ConnectionImpl test = obcache.get( cinfo, cf3 ) ; + } finally { + checkStats( obcache, 0, 0, 0, 0 ) ; + } + } + + // Test inboundConnectionCache + // + // Do a single requestReceived/requestProcessed/responseSent cycle + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest"}) + public void inboundTest1() throws IOException { + testBanner( "inboundTest1: single cycle" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "FirstContact" ) ; + ConnectionImpl c1 = cinfo.createConnection() ; + ibcache.requestReceived( c1 ) ; + checkStats( ibcache, 0, 0, 1, 1 ) ; + + ibcache.requestProcessed( c1, 1 ) ; + checkStats( ibcache, 1, 0, 0, 1 ) ; + + ibcache.responseSent( c1 ) ; + checkStats( ibcache, 1, 1, 0, 1 ) ; + + ibcache.close( c1 ) ; + checkStats( ibcache, 0, 0, 0, 0 ) ; + } + + // Do two interleaved requestReceived/requestProcessed/responseSent cycles + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest", "inboundTest1"}) + public void inboundTest2() throws IOException { + testBanner( "inboundTest2: 2 cycles interleaved" ) ; + ContactInfoImpl cinfo = ContactInfoImpl.get( "FirstContact" ) ; + ConnectionImpl c1 = cinfo.createConnection() ; + ibcache.requestReceived( c1 ) ; + checkStats( ibcache, 0, 0, 1, 1 ) ; + + ConnectionImpl c2 = cinfo.createConnection() ; + ibcache.requestReceived( c2 ) ; + checkStats( ibcache, 0, 0, 2, 2 ) ; + + Assert.assertNotSame( c1, c2) ; + + ibcache.requestProcessed( c1, 1 ) ; + checkStats( ibcache, 1, 0, 1, 2 ) ; + + ibcache.requestProcessed( c2, 1 ) ; + checkStats( ibcache, 2, 0, 0, 2 ) ; + + ibcache.responseSent( c1 ) ; + checkStats( ibcache, 2, 1, 0, 2 ) ; + + ibcache.responseSent( c2 ) ; + checkStats( ibcache, 2, 2, 0, 2 ) ; + + ibcache.close( c2 ) ; + checkStats( ibcache, 1, 1, 0, 1 ) ; + + ibcache.close( c1 ) ; + checkStats( ibcache, 0, 0, 0, 0 ) ; + } + + // Do enough gets on enough ContactInfos to start reclaiming + @Test(dependsOnMethods={"nonBlockingConcurrentQueueTest", "inboundTest2"}) + public void inboundTest3() throws IOException { + testBanner( "inboundTest3: test reclamation" ) ; + final int numContactInfo = HIGH_WATER_MARK/MAX_PARALLEL_CONNECTIONS; + final List cinfos = new ArrayList() ; + for (int ctr=0; ctr> csa = + new ArrayList>() ; + for (int ctr=0; ctr set = new HashSet() ; + csa.add( set ) ; + for (int num=0; num conns : csa ) { + for (ConnectionImpl conn : conns) { + ibcache.close( conn ) ; + } + } + checkStats( ibcache, 0, 0, 0, 0 ) ; + } + + public static void main( String[] args ) { + TestngRunner runner = new TestngRunner() ; + runner.registerClass( Client.class ) ; + runner.run() ; + runner.systemExit() ; + } +} diff --git a/test/src/share/classes/corba/connectioncache/ConnectionCacheStressTest.java b/test/src/share/classes/corba/connectioncache/ConnectionCacheStressTest.java new file mode 100644 index 000000000..435bc38a1 --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/ConnectionCacheStressTest.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache; + +import corba.framework.*; + +public class ConnectionCacheStressTest extends CORBATest +{ + @Override + protected void doTest() throws Throwable + { + Controller client = createClient( "corba.connectioncache.StressClient", + "stressClient" ) ; + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + } +} + diff --git a/test/src/share/classes/corba/connectioncache/ConnectionCacheTest.java b/test/src/share/classes/corba/connectioncache/ConnectionCacheTest.java new file mode 100644 index 000000000..35f74572b --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/ConnectionCacheTest.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache; + +import corba.framework.*; + +public class ConnectionCacheTest extends CORBATest +{ + @Override + protected void doTest() throws Throwable + { + Controller client = createClient( "corba.connectioncache.Client" ) ; + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + } +} + diff --git a/test/src/share/classes/corba/connectioncache/ConnectionImpl.java b/test/src/share/classes/corba/connectioncache/ConnectionImpl.java new file mode 100644 index 000000000..5d541eda0 --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/ConnectionImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache ; + +// A simple implementation of Connection for testing. No + +import com.sun.corba.ee.spi.transport.connection.Connection; +import java.util.concurrent.atomic.AtomicBoolean; + +// synchronization is required to use this class. +public class ConnectionImpl implements Connection { + private String name ; + private long id ; + private ContactInfoImpl cinfo ; + private AtomicBoolean isClosed ; + + public ConnectionImpl( String name, long id, ContactInfoImpl cinfo ) { + this.name = name ; + this.id = id ; + this.cinfo = cinfo ; + this.isClosed = new AtomicBoolean() ; + } + + public ContactInfoImpl getContactInfo() { + return cinfo ; + } + + // Simulate access (read/write) to a connection to make sure + // we do not access a closed connection. + public void access() { + if (isClosed.get()) + throw new RuntimeException( "Illegal access: connection " + + name + " is closed." ) ; + } + + public void close() { + boolean wasClosed = isClosed.getAndSet( true ) ; + if (wasClosed) + throw new RuntimeException( + "Attempting to close connection " ) ; + } + + @Override + public String toString() { + return "ConnectionImpl[" + name + ":" + id + "]" ; + } +} + diff --git a/test/src/share/classes/corba/connectioncache/ContactInfoImpl.java b/test/src/share/classes/corba/connectioncache/ContactInfoImpl.java new file mode 100644 index 000000000..975c4e503 --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/ContactInfoImpl.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache ; + +import com.sun.corba.ee.spi.transport.connection.ContactInfo; +import java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +public class ContactInfoImpl implements ContactInfo { + private String address ; + + private static AtomicLong nextId = + new AtomicLong() ; + private static AtomicBoolean simulateAddressUnreachable = + new AtomicBoolean() ; + + private static ConcurrentMap cinfoMap = + new ConcurrentHashMap() ; + + private RandomDelay rdel ; + + private ContactInfoImpl( String address, int minDelay, int maxDelay ) { + this.address = address ; + rdel = new RandomDelay( minDelay, maxDelay ) ; + } + + public static ContactInfoImpl get( String address ) { + return get( address, 0, 0 ) ; + } + + public static ContactInfoImpl get( String address, int minDelay, int maxDelay ) { + ContactInfoImpl result = new ContactInfoImpl( address, minDelay, maxDelay ) ; + ContactInfoImpl entry = cinfoMap.putIfAbsent( address, result ) ; + if (entry == null) + return result ; + else + return entry ; + } + + public void remove( String address ) { + cinfoMap.remove( address ) ; + } + + public void setUnreachable( boolean arg ) { + simulateAddressUnreachable.set( arg ) ; + } + + public ConnectionImpl createConnection() throws IOException { + if (simulateAddressUnreachable.get()) { + throw new IOException( "Address " + address + + " is currently unreachable" ) ; + } else { + long id = nextId.getAndIncrement() ; + ConnectionImpl result = new ConnectionImpl( address, id, this ) ; + return result ; + } + } + + @Override + public String toString() { + return "ContactInfoImpl[" + address + "]" ; + } +} + diff --git a/test/src/share/classes/corba/connectioncache/RandomDelay.java b/test/src/share/classes/corba/connectioncache/RandomDelay.java new file mode 100644 index 000000000..650ae13fe --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/RandomDelay.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache ; + +import java.util.Random; + +public class RandomDelay{ + Random random = new Random() ; + + private final int minDelay ; + private final int maxDelay ; + + public RandomDelay( int minDelay, int maxDelay ) { + if (minDelay < 0) + throw new RuntimeException( "minDelay must be >= 0") ; + if (maxDelay < minDelay) + throw new RuntimeException( "maxDelay must be >= minDelay" ) ; + + this.minDelay = minDelay ; + this.maxDelay = maxDelay ; + } + + void randomWait() { + int delay = minDelay ; + if (maxDelay > minDelay) { + delay = minDelay + random.nextInt( maxDelay-minDelay ) ; + } + + if (delay > 0) { + try { + wait(delay); + } catch (InterruptedException ex) { + // ignore this + } + } + } +} diff --git a/test/src/share/classes/corba/connectioncache/StressClient.java b/test/src/share/classes/corba/connectioncache/StressClient.java new file mode 100644 index 000000000..cdae76b91 --- /dev/null +++ b/test/src/share/classes/corba/connectioncache/StressClient.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.connectioncache ; + +import java.util.List ; +import java.util.ArrayList ; + +import java.util.logging.Logger ; +import java.util.logging.Handler ; +import java.util.logging.Level ; +import java.util.logging.StreamHandler ; +import java.util.logging.Formatter ; +import java.util.logging.LogRecord ; + +import java.io.IOException ; + +import org.testng.Assert ; +import org.testng.annotations.Test ; + +import com.sun.corba.ee.spi.transport.connection.ConnectionCache ; +import com.sun.corba.ee.spi.transport.connection.ContactInfo ; +import com.sun.corba.ee.spi.transport.connection.InboundConnectionCache ; +import com.sun.corba.ee.spi.transport.connection.OutboundConnectionCache ; +import com.sun.corba.ee.spi.transport.connection.ConnectionCacheFactory ; + +import corba.framework.TestngRunner ; +import java.util.Random; + +public class StressClient { + // Ignore all of the LogRecord information except the message. + public static class ReallySimpleFormatter extends Formatter { + public synchronized String format( LogRecord record ) { + return record.getMessage() + "\n" ; + } + } + + // Similar to ConsoleHandler, but outputs to System.out + // instead of System.err, which works better with the + // CORBA test framework. + public static class SystemOutputHandler extends StreamHandler { + public SystemOutputHandler() { + try { + setLevel(Level.FINER); + setFilter(null); + setFormatter(new ReallySimpleFormatter()); + setEncoding(null); + setOutputStream(System.out); + } catch (Exception exc) { + System.out.println( "Caught unexpected exception " + exc ) ; + } + } + + @Override + public void publish(LogRecord record) { + super.publish(record); + flush(); + } + + @Override + public void close() { + flush(); + } + } + + private static final boolean DEBUG = false ; + + private static final Logger logger = Logger.getLogger( "test.corba" ) ; + private static final Handler handler = new SystemOutputHandler() ; + + static { + if (DEBUG) { + logger.setLevel( Level.FINER ) ; + logger.addHandler( handler ) ; + } + } + + private void testBanner( String msg ) { + if (DEBUG) { + System.out.println( + "=======================================" + + "==============================" ) ; + + System.out.println( msg ) ; + + System.out.println( + "=======================================" + + "==============================" ) ; + } + } + + private void checkStat( long actual, long expected, String type ) { + Assert.assertEquals( actual, expected, type ) ; + } + + private void checkStats( ConnectionCache cc, int idle, + int reclaimable, int busy, int total ) { + + checkStat( cc.numberOfIdleConnections(), idle, + "Idle connections" ) ; + checkStat( cc.numberOfReclaimableConnections(), reclaimable, + "Reclaimable connections" ) ; + checkStat( cc.numberOfBusyConnections(), busy, + "Busy connections" ) ; + checkStat( cc.numberOfConnections(), total, + "Total connections" ) ; + } + + private static final int NUM_ITERATIONS = 2000 ; + + private static final int NUM_CONTACT_INFO = 8 ; + private static final int NUM_THREADS = 40 ; + private static final int MAX_CREATE_CONNECTION_DELAY = 19 ; + private static final int MIN_CREATE_CONNECTION_DELAY = 1 ; + private static final int MAX_OPERATION_DELAY = 11 ; + private static final int MIN_OPERATION_DELAY = 1 ; + + private static final int NUMBER_TO_RECLAIM = 1 ; + private static final int MAX_PARALLEL_CONNECTIONS = 4 ; + private static final int HIGH_WATER_MARK = 15 ; + private static final int TTL = 2*60*1000 ; // 2 minute TTL (time to live) + // for reclaimable connections + + private final OutboundConnectionCache obcache ; + private final InboundConnectionCache ibcache ; + private final List cinfos ; + private final RandomDelay operationDelay ; + + private final List threads ; + + public class ClientThread extends Thread { + private final Random rand = new Random() ; + + @Override + public void run() { + /* + * - randomly picks one of several ContactInfos + * - calls get to get a connection (the createConnections takes some random amount of time) + * - waits + * - accesses the connection + * - waits + * - calls release to release the connection expecting 1 response + * - waits + * - accesses the connection + * - calls responseReceived + */ + for (int ctr=0; ctr cinfo = cinfos.get( cindex ) ; + + ConnectionImpl conn = obcache.get(cinfo) ; + + operationDelay.randomWait(); + conn.access() ; + operationDelay.randomWait(); + obcache.release( conn, 1 ) ; + operationDelay.randomWait(); + conn.access() ; + operationDelay.randomWait(); + obcache.responseReceived(conn); + } catch (IOException exc) { + Assert.fail( "Error in thread", exc ) ; + } + } + } + } + + public StressClient() { + obcache = ConnectionCacheFactory. + makeBlockingOutboundConnectionCache( + "BlockingOutboundCache", HIGH_WATER_MARK, NUMBER_TO_RECLAIM, + MAX_PARALLEL_CONNECTIONS, TTL ) ; + + ibcache = ConnectionCacheFactory. + makeBlockingInboundConnectionCache( + "BlockingInboundCache", HIGH_WATER_MARK, NUMBER_TO_RECLAIM, TTL ) ; + + cinfos = new ArrayList() ; + for (int ctr = 0; ctr < NUM_CONTACT_INFO; ctr++ ) { + cinfos.add( ContactInfoImpl.get( "ContactInfo:"+ctr, + MIN_CREATE_CONNECTION_DELAY, MAX_CREATE_CONNECTION_DELAY ) ) ; + } + + operationDelay = new RandomDelay( + MIN_OPERATION_DELAY, MAX_OPERATION_DELAY ) ; + + threads = new ArrayList() ; + } + + @Test + void stressOutboundCache() { + for (int ctr=0; ctr 0 && args[0].equals("-debug") ) + debug = true; + + if (debug) { + System.out.println("ENTER: Server"); + System.out.flush(); + } + + // create and initialize the ORB + Properties p = new Properties(); + p.put("org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + p.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "9999"); + ORB orb = (ORB) ORB.init(args, p); + + if (debug) { + System.out.println("Server: ORB initialized"); + System.out.flush(); + } + + // get rootPOA, set the AdapterActivator, and activate RootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_activator(new MyAdapterActivator(orb)); + rootPOA.the_POAManager().activate(); + + if (debug) { + System.out.println("Server: RootPOA activator set"); + System.out.flush(); + } + + POA poa = createPersistentPOA(orb, rootPOA); + createEcho1(orb, poa); + poa = createNonRetainPOA(orb, rootPOA); + createEcho2(orb, poa); + if (debug) { + System.out.println("Server: refs created"); + System.out.flush(); + } + + // wait for invocations from clients + System.out.println("Server is ready."); + System.out.flush(); + + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + System.exit(1); + } finally { + if (debug) { + System.out.println("EXIT: Server"); + System.out.flush(); + } + } + } + + static POA createPersistentPOA(ORB orb, POA rootPOA) + throws Exception + { + // create a persistent POA + Policy[] tpolicy = new Policy[2]; + tpolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + POA tpoa = rootPOA.create_POA("PersistentPOA", null, tpolicy); + + // register the ServantActivator with the POA, then activate POA + EchoServantActivator csa = new EchoServantActivator(orb); + tpoa.set_servant_manager(csa); + tpoa.the_POAManager().activate(); + return tpoa; + } + + static Tie makeEchoServant( ORB orb ) + { + EchoImpl impl = null ; + + try { + impl = new EchoImpl(orb, Server.debug); + } catch (RemoteException exc) { + // ignore + } + + Tie tie = ORB.getPresentationManager().getTie() ; + tie.setTarget( impl ) ; + + return tie ; + } + + static void createEcho1(ORB orb, POA tpoa) + throws Exception + { + // create an objref using persistent POA + byte[] id = Echo1Id.getBytes(); + String intf = makeEchoServant(orb)._all_interfaces(tpoa,id)[0] ; + + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, intf); + + Class intfr = Class.forName("corba.driinvocation.Echo"); + + Echo echoRef + = (Echo)PortableRemoteObject.narrow(obj, Echo.class ); + + // put objref in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Echo1", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + + // invoke on the local objref to test local invocations + if ( Server.debug ) + System.out.println("\nTesting local invocation: Client thread is " + +Thread.currentThread()); + int value = echoRef.double(1); + if ( Server.debug ) + System.out.println(value); + } + + static POA createNonRetainPOA(ORB orb, POA rootPOA) + throws Exception + { + // create another persistent, non-retaining POA + Policy[] tpolicy = new Policy[3]; + tpolicy[0] = rootPOA.create_lifespan_policy( + LifespanPolicyValue.PERSISTENT); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + tpolicy[2] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN); + POA tpoa = rootPOA.create_POA("NonRetainPOA", null, tpolicy); + + // register the ServantLocator with the POA, then activate POA + EchoServantLocator csl = new EchoServantLocator(orb); + tpoa.set_servant_manager(csl); + tpoa.the_POAManager().activate(); + return tpoa; + } + + static void createEcho2(ORB orb, POA tpoa) + throws Exception + { + // create a servant and get an objref using persistent POA + byte[] id = Echo2Id.getBytes(); + String intf = makeEchoServant(orb)._all_interfaces(tpoa,id)[0] ; + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, intf ) ; + Echo echoRef = (Echo)PortableRemoteObject.narrow(obj, Echo.class ); + + // put objref in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Echo2", ""); + NameComponent path[] = {nc}; + ncRef.rebind(path, echoRef); + } +} + + +class MyAdapterActivator extends LocalObject implements AdapterActivator +{ + private ORB orb; + + MyAdapterActivator(ORB orb) + { + this.orb = orb; + } + + public boolean unknown_adapter(POA parent, String name) + { + if ( Server.debug ) + System.out.println("\nIn MyAdapterActivator.unknown_adapter, parent = " + + parent.the_name()+" child = "+name); + + try { + if ( name.equals("PersistentPOA") ) + Server.createPersistentPOA(orb, parent); + else if ( name.equals("NonRetainPOA") ) + Server.createNonRetainPOA(orb, parent); + else + return false; + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } + + return true; + } +} + + +class EchoServantActivator extends org.omg.CORBA.LocalObject implements ServantActivator +{ + ORB orb; + + EchoServantActivator(ORB orb) + { + this.orb = orb; + } + + public Servant incarnate(byte[] oid, POA adapter) + throws org.omg.PortableServer.ForwardRequest + { + Servant servant = Server.makeEchoServant( orb ) ; + + if ( Server.debug ) + System.out.println("\nIn EchoServantActivator.incarnate, oid = " + +oid + +" poa = "+adapter.the_name() + +" servant = "+servant); + return servant; + } + + public void etherealize(byte[] oid, POA adapter, Servant servant, + boolean cleanup_in_progress, boolean remaining_activations) + { + if ( Server.debug ) + System.out.println("\nIn EchoServantActivator.etherealize, oid = " + +oid + +" poa = "+adapter.the_name() + +" servant = "+servant + +" cleanup_in_progress = "+cleanup_in_progress + +" remaining_activations = "+remaining_activations); + return; + } +} + +class EchoServantLocator extends org.omg.CORBA.LocalObject implements ServantLocator +{ + ORB orb; + + EchoServantLocator(ORB orb) + { + this.orb = orb; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + String sid = new String(oid); + String newidStr = "somethingdifferent"; + + // Tests location forwards + if ( sid.equals(Server.Echo2Id) ) { + // construct a new objref to forward to. + byte[] id = newidStr.getBytes(); + org.omg.CORBA.Object obj = null; + try { + String intf = makeEchoServant(orb)._all_interfaces(tpoa,id)[0] ; + obj = adapter.create_reference_with_id(id, intf ) ; + } catch ( Exception ex ) {} + Echo echoRef = (Echo)PortableRemoteObject.narrow(obj, Echo.class ); + + System.out.println("\nEchoServantLocator.preinvoke forwarding ! " + +"old oid ="+new String(oid) + +"new id ="+new String(id)); + + ForwardRequest fr = new ForwardRequest(obj); + throw fr; + } + + String oidStr = new String(oid); + if ( !newidStr.equals(oidStr) ) + System.err.println("\tERROR !!!: preinvoke got wrong id:"+oidStr); + + MyCookie cookie = new MyCookie(); + Servant servant = Server.makeEchoServant( orb ) ; + + if ( Server.debug ) + System.out.println("\nIn EchoServantLocator.preinvoke, oid = " + +oidStr + +" poa = "+adapter.the_name() + +" operation = " +operation + +" cookie = "+cookie+" servant = "+servant); + + the_cookie.value = cookie; + return servant; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + if ( Server.debug ) + System.out.println("\nIn EchoServantLocator.postinvoke, oid = " + +new String(oid) + +" poa = "+adapter.the_name() + +" operation = " +operation + +" cookie = "+cookie+" servant = "+servant); + return; + } +} + +class MyCookie +{} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/Client.java b/test/src/share/classes/corba/dynamicrmiiiop/Client.java new file mode 100644 index 000000000..9e7b9ba33 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/Client.java @@ -0,0 +1,1535 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop ; + +import java.rmi.Remote ; + +import java.io.Serializable ; +import java.io.Externalizable ; + +import javax.rmi.CORBA.Tie ; + +import org.omg.CORBA.SystemException ; +import org.omg.CORBA.portable.ApplicationException ; +import org.omg.CORBA.portable.ResponseHandler ; +import org.omg.CORBA.portable.UnknownException ; +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import java.util.Set ; +import java.util.HashSet ; +import java.util.Properties ; + +import java.lang.reflect.Method; +import java.lang.reflect.InvocationTargetException ; + +import junit.framework.TestCase ; +import junit.framework.Test ; +import junit.framework.TestResult ; +import junit.framework.TestSuite ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import com.sun.corba.ee.spi.presentation.rmi.DynamicMethodMarshaller ; +import com.sun.corba.ee.spi.presentation.rmi.IDLNameTranslator ; +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.presentation.rmi.IDLType ; + +import corba.dynamicrmiiiop.testclasses.A ; +import corba.dynamicrmiiiop.testclasses.B ; +import corba.dynamicrmiiiop.testclasses.C ; +import corba.dynamicrmiiiop.testclasses.D ; +import corba.dynamicrmiiiop.testclasses.E ; +import corba.dynamicrmiiiop.testclasses.F ; +import corba.dynamicrmiiiop.testclasses.G ; +import corba.dynamicrmiiiop.testclasses.H ; +import corba.dynamicrmiiiop.testclasses.C1 ; +import corba.dynamicrmiiiop.testclasses.C2 ; +import corba.dynamicrmiiiop.testclasses.C3 ; +import corba.dynamicrmiiiop.testclasses.C4 ; +import corba.dynamicrmiiiop.testclasses.C5 ; +import corba.dynamicrmiiiop.testclasses.C6 ; + +import corba.dynamicrmiiiop.testclasses.TieTest ; +import corba.dynamicrmiiiop.testclasses.TieTestImpl ; +import corba.dynamicrmiiiop.testclasses.DMMImplTestClasses ; + +import com.sun.corba.ee.impl.presentation.rmi.ExceptionHandlerImpl ; + +// Included to directly test makeReaderWriter, which is not +// needed in the PresentationManager API. +import com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl ; + +import com.sun.corba.ee.impl.util.RepositoryId ; +import org.glassfish.pfl.basic.graph.Graph; +import org.glassfish.pfl.basic.graph.GraphImpl; +import org.glassfish.pfl.basic.graph.Node; +import org.glassfish.pfl.dynamic.copyobject.spi.LibraryClassLoader; +import org.glassfish.pfl.test.TestCaseTools; + +public class Client extends TestCase +{ + private static final boolean DEBUG = false ; + // private static final int REP_COUNT = 1000 ; + // private List timedTests ; + + public static void main( String[] args ) + { + Client root = new Client() ; + TestResult result = junit.textui.TestRunner.run(root.suite()) ; + + // reportTiming( System.out, root.timedTests ) ; + + if (result.errorCount() + result.failureCount() > 0) { + System.out.println( "Error: failures or errrors in JUnit test" ) ; + System.exit( 1 ) ; + } else + System.exit( 0 ) ; + } + + public Client() + { + super() ; + // timedTests = new ArrayList() ; + } + + public Client( String name ) + { + super( name ) ; + // timedTests = null ; + } + + public static Test suite() + { + System.out.println( + "==============================================================\n" + + "Testing Dynamic RMI-IIOP\n" + + "==============================================================\n" + ) ; + + TestSuite ts = (TestSuite)TestCaseTools.makeTestSuite( Client.class ) ; + + // Add the Codegen ProxyCreator test suite if it is available. + // It is part of the optional ORB build. + String testName = "corba.dynamicrmiiiop.TestCodegenProxyCreator" ; + try { + Class cls = LibraryClassLoader.loadClass( testName ) ; + ts.addTest( (TestSuite)TestCaseTools.makeTestSuite( cls ) ) ; + } catch (ClassNotFoundException exc) { + // Test not available: no op + System.out.println( testName + " test is not available." ) ; + } + + return ts ; + } + + // This is provided to prevent JUnit from complaining that Client + // does not contain tests. + public void testDummy() + { + assertTrue( true ) ; + } + + public void testExceptionNameMangling() + { + Class testClass = + corba.dynamicrmiiiop.testclasses.exception.TestException.class ; + String expectedId = "IDL:corba/dynamicrmiiiop/testclasses/_exception/TestEx:1.0" ; + + ExceptionHandlerImpl eh = new ExceptionHandlerImpl( + new Class[0] ) ; + ExceptionHandlerImpl.ExceptionRW erw = + eh.getRMIExceptionRW( testClass ) ; + assertEquals( expectedId, erw.getId() ) ; + } + + public static boolean equalOrNull( Object obj1, Object obj2 ) + { + if (obj1 == null) + return obj2 == null ; + else + return obj1.equals( obj2 ) ; + } + + public static void sameException( Object obj1, Object obj2 ) + { + if ((obj1 == null) || (obj2 == null)) { + if (obj1 == obj2) + return ; + else + fail( "Objects not the same: obj1 = " + obj1 + + " obj2 = " + obj2 ) ; + } + + if (!obj1.getClass().equals( obj2.getClass() )) { + fail( "Objects have different classes: obj1 = " + obj1 + + " obj2 = " + obj2 ) ; + + return ; + } + + if (!(obj1 instanceof Throwable) || !(obj2 instanceof Throwable)) { + fail( "Objects are not both throwable: obj1 = " + obj1 + + " obj2 = " + obj2 ) ; + + return ; + } + + Throwable thr1 = (Throwable)obj1 ; + Throwable thr2 = (Throwable)obj2 ; + + /* Don't care about matching messages: that's up to the logex code. + boolean sameMessage = equalOrNull( thr1.getMessage(), thr2.getMessage() ) ; + if (!sameMessage) { + fail( "thr1 and thr2 do not have the same message: thr1 message = " + + thr1.getMessage() + " thr2 message = " + thr2.getMessage() ) ; + } + */ + + sameException( thr1.getCause(), thr2.getCause() ) ; + + if (thr1 instanceof UnknownException) { + UnknownException unk1 = (UnknownException)thr1 ; + UnknownException unk2 = (UnknownException)thr2 ; + + sameException( unk1.originalEx, unk2.originalEx ) ; + } + + if (thr1 instanceof SystemException) { + SystemException sys1 = (SystemException)thr1 ; + SystemException sys2 = (SystemException)thr2 ; + + if (sys1.minor != sys2.minor) + fail( "sys1 and sys2 do not have the same minor code: sys1 mc = " + + sys1.minor + " sys2 mc = " + sys2.minor ) ; + + int cs1 = sys1.completed.value() ; + int cs2 = sys2.completed.value() ; + + if (cs1 != cs2) + fail( "sys1 and sys2 do not have the same completion status: cs1 = " + + cs1 + " cs2 = " + cs2 ) ; + } + } + + public static class ORBInitTestSuite extends TestCase + { + /** A simple class that allows checking of the result of a + * computation both in the current thread and in a new thread. + */ + public static abstract class ThreadableTest implements Runnable + { + private Object expected ; + private Object actual ; + private String name ; + + public ThreadableTest( String name, Object expected ) + { + this.name = name ; + this.expected = expected ; + } + + abstract public void run() ; + + protected void setActual( Object actual ) + { + this.actual = actual ; + } + + private void result() + { + assertSame( name, expected, actual ) ; + } + + public void testSameThread() + { + actual = null ; + run() ; + result() ; + } + + public void testDifferentThread() + { + actual = null ; + Thread thr = new Thread( this ) ; + thr.start() ; + + boolean done = false ; + while (!done) { + try { + thr.join() ; + done = true ; + } catch (InterruptedException exc) { + // NO-OP: just retry the join call + } + } + + result() ; + } + } + + public static class TestStubFactoryFactoryType extends ThreadableTest + { + public TestStubFactoryFactoryType( boolean expected ) + { + super( "StubFactoryFactory", Boolean.valueOf( + expected ) ) ; + } + + public void run() + { + setActual( Boolean.valueOf( + ORB.getStubFactoryFactory(). + createsDynamicStubs() ) ) ; + } + } + + public ORBInitTestSuite() + { + super() ; + } + + public ORBInitTestSuite( String name ) + { + super( name ) ; + } + + /* Tests: + * create ORB with dynamic stubs, verify get dynamic stubs from + * chooser. + * init ORBSingleton, verify no affect on chooser. + * chooser. + */ + + ORB makeORB( boolean useDynamic ) + { + Properties props = new Properties() ; + String[] args = null ; + props.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, + Boolean.toString( useDynamic ) ) ; + return (ORB)ORB.init( args, props ) ; + } + + public void testNull() + { + // no-op to keep junit happy + } + +/* Unfortunately these test do not work, because we cannot control + the ORB type exactly here, and setting the global presentation manager + can only happen once. We'll omit these for now. + + public void testDynamicORB() + { + ORB orb = makeORB( true ) ; + ThreadableTest tt2 = new TestStubFactoryFactoryType( + true ) ; + tt2.testSameThread() ; + tt2.testDifferentThread() ; + } + + public void testSingletonORB() + { + ORB orb = makeORB( true ) ; + ORB sorb = (ORB)ORB.init() ; + ThreadableTest tt2 = new TestStubFactoryFactoryType( + true ) ; + tt2.testSameThread() ; + tt2.testDifferentThread() ; + } +*/ + } + + public static class GraphTestSuite extends TestCase + { + public class NodeTestImpl implements Node + { + private String name ; + private Set children ; + + public NodeTestImpl( String name ) + { + this.name = name ; + children = new HashSet() ; + } + + public void addChild( NodeTestImpl node ) + { + children.add( node ) ; + } + + @Override + public String toString() + { + return "NodeTestImpl[" + name + "]" ; + } + + @Override + public boolean equals( Object obj ) + { + if (this == obj) + return true ; + + if (!(obj instanceof NodeTestImpl)) + return false ; + + NodeTestImpl other = (NodeTestImpl)obj ; + + return name.equals( other.name ) ; + } + + @Override + public int hashCode() + { + return name.hashCode() ; + } + + public Set getChildren() + { + return children ; + } + } + + public GraphTestSuite() + { + super() ; + } + + public GraphTestSuite( String name ) + { + super( name ) ; + } + + public void testAdd1() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + Set expected = new HashSet() ; + expected.add( a ) ; + + Graph g = new GraphImpl() ; + g.add( a ) ; + assertTrue( g.equals( expected ) ) ; + } + + public void testAdd2() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + NodeTestImpl b = new NodeTestImpl( "B" ) ; + Set expected = new HashSet() ; + expected.add( a ) ; + expected.add( b ) ; + + Graph g = new GraphImpl() ; + g.add( a ) ; + g.add( b ) ; + assertTrue( g.equals( expected ) ) ; + } + + public void testAddSame() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + NodeTestImpl b = new NodeTestImpl( "B" ) ; + Set expected = new HashSet() ; + expected.add( a ) ; + expected.add( b ) ; + + Graph g = new GraphImpl() ; + g.add( a ) ; + g.add( b ) ; + g.add( a ) ; + assertTrue( g.equals( expected ) ) ; + } + + public void testNullGraph() + { + Graph g = new GraphImpl() ; + Set roots = g.getRoots() ; + assertTrue( roots.isEmpty()) ; + } + + public void testSingeltonGraph() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + Set expected = new HashSet() ; + expected.add( a ) ; + + Graph g = new GraphImpl() ; + g.add( a ) ; + Set roots = g.getRoots() ; + assertTrue( expected.equals( roots ) ) ; + } + + public void testLinearGraph() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + NodeTestImpl b = new NodeTestImpl( "B" ) ; + a.addChild( b ) ; + Set expected = new HashSet() ; + expected.add( a ) ; + + Graph g = new GraphImpl() ; + g.add( b ) ; + g.add( a ) ; + Set roots = g.getRoots() ; + assertTrue( expected.equals( roots ) ) ; + } + + public void testDisconnectedLinearGraph() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + NodeTestImpl b = new NodeTestImpl( "B" ) ; + a.addChild( b ) ; + + NodeTestImpl c = new NodeTestImpl( "C" ) ; + NodeTestImpl d = new NodeTestImpl( "D" ) ; + NodeTestImpl e = new NodeTestImpl( "E" ) ; + c.addChild( d ) ; + d.addChild( e ) ; + + Set expected = new HashSet() ; + expected.add( a ) ; + expected.add( c ) ; + + Graph g = new GraphImpl() ; + g.add( a ) ; + g.add( b ) ; + g.add( c ) ; + g.add( d ) ; + g.add( e ) ; + + Set roots = g.getRoots() ; + assertTrue( expected.equals( roots ) ) ; + } + + public void testComplexGraph() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + NodeTestImpl b = new NodeTestImpl( "B" ) ; + NodeTestImpl c = new NodeTestImpl( "C" ) ; + NodeTestImpl d = new NodeTestImpl( "D" ) ; + NodeTestImpl e = new NodeTestImpl( "E" ) ; + NodeTestImpl f = new NodeTestImpl( "F" ) ; + NodeTestImpl g = new NodeTestImpl( "G" ) ; + NodeTestImpl h = new NodeTestImpl( "H" ) ; + + a.addChild( b ) ; + c.addChild( d ) ; + d.addChild( e ) ; + f.addChild( d ) ; + f.addChild( e ) ; + g.addChild( h ) ; + h.addChild( e ) ; + b.addChild( h ) ; + h.addChild( f ) ; + + Set expected = new HashSet() ; + expected.add( a ) ; + expected.add( c ) ; + expected.add( g ) ; + + Graph graph = new GraphImpl() ; + graph.add( a ) ; + graph.add( b ) ; + graph.add( c ) ; + graph.add( d ) ; + graph.add( e ) ; + graph.add( f ) ; + graph.add( g ) ; + graph.add( h ) ; + + Set roots = graph.getRoots() ; + assertTrue( expected.equals( roots ) ) ; + } + + public void testDynamicAdd() + { + NodeTestImpl a = new NodeTestImpl( "A" ) ; + NodeTestImpl b = new NodeTestImpl( "B" ) ; + NodeTestImpl c = new NodeTestImpl( "C" ) ; + NodeTestImpl d = new NodeTestImpl( "D" ) ; + NodeTestImpl e = new NodeTestImpl( "E" ) ; + NodeTestImpl f = new NodeTestImpl( "F" ) ; + NodeTestImpl g = new NodeTestImpl( "G" ) ; + NodeTestImpl h = new NodeTestImpl( "H" ) ; + + a.addChild( b ) ; + c.addChild( d ) ; + d.addChild( e ) ; + f.addChild( d ) ; + f.addChild( e ) ; + g.addChild( h ) ; + h.addChild( e ) ; + b.addChild( h ) ; + h.addChild( f ) ; + + Set expected = new HashSet() ; + expected.add( a ) ; + expected.add( c ) ; + expected.add( g ) ; + + Graph graph = new GraphImpl() ; + graph.add( a ) ; + graph.add( f ) ; + graph.add( g ) ; + graph.add( c ) ; + + Set roots = graph.getRoots() ; + assertTrue( expected.equals( roots ) ) ; + } + } + + public static class TypeIdTestSuite extends TestCase + { + // Assume interfaces A to G defined as follows: + // A extends B, C + // B extends D + // C extends D + // D extends Remote + // E extends F + // F extends G + // G extends Remote + // H extends G, B + + // C1 extends Object, implements D + // C2 extends Object, implements B + // C3 extends Object, implements A, B + // C4 extends C3, implements A + // C5 extends C4, implements E + // C6 extends C5, implements H + + public void testSingleInterface() + { + doTest( D.class, D.class, new Class[0] ) ; + } + + public void testLinearInterface() + { + doTest( B.class, B.class, new Class[] { D.class } ) ; + } + + public void testDiamondInterface() + { + doTest( A.class, A.class, new Class[] { B.class, C.class, + D.class } ) ; + } + + public void testClassSingleInterface() + { + doTest( C1.class, D.class, new Class[0] ) ; + } + + public void testClassLinearInterface() + { + doTest( C2.class, B.class, new Class[] { D.class } ) ; + } + + public void testClassDiamondInterface() + { + doTest( C3.class, A.class, new Class[] { B.class, C.class, + D.class } ) ; + } + + public void testClassInheritance() + { + doTest( C4.class, A.class, new Class[] { B.class, C.class, + D.class } ) ; + } + + public void testClassMultipleInterface() + { + doTest( C5.class, C5.class, new Class[] { A.class, B.class, + C.class, D.class, E.class, F.class, G.class} ) ; + } + + public void testClassComplexInterface() + { + doTest( C6.class, C6.class, new Class[] { A.class, B.class, + C.class, D.class, E.class, F.class, G.class, H.class } ) ; + } + + private ORB orb = null ; + private PresentationManager pm = null ; + + private void init() + { + Properties props = new Properties() ; + props.setProperty( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + String[] args = null ; + orb = (ORB)org.omg.CORBA.ORB.init( args, props ) ; + pm = ORB.getPresentationManager() ; + } + + public TypeIdTestSuite() + { + super() ; + init() ; + } + + public TypeIdTestSuite( String name ) + { + super( name ) ; + init() ; + } + + private Set makeSet( String[] strings, int startIndex ) + { + Set result = new HashSet() ; + for (int ctr=startIndex; ctr + *
              26. Create a class with a method Object invoke( int methodNumber, Object[] args ). + * The invoke method simply forwards the invocation to the corresponding method. + *
              27. Create a suitable remote interface for testing. + *
              28. Implement the remote interface with an implementation that provides for testing + * correct behavior. + *
              29. Be able to run the tests on 2 implementations of the interface. + *
              30. Create the second implementation of the interface by constructing a proxy + * that delegates to the first implementation. + *
              31. Test that the proxy extends the correct base class + *
              32. Test that the proxy implements the expected interface + * + * We need to test the following kinds of calls: + *
                  + *
                1. Method that echos single arg of primitive type to result (8 tests) + *
                2. Method that takes one int, returns void, asserts expected value received + *
                3. Method that takes one int, return void, throws checked exception for certain value + *
                4. Method that returns one int, no args, certain result expected + *
                5. Method that takes no args, returns no results, causes checked side effect + *
                6. Method that takes no args, return no results, always throws checked exception + *
                7. Method that takes two ints, returns int, computes the sum + *
                8. Method that takes two Strings, returns string, computes concat + *
                9. Method that takes int, String, returns string, computes concat + *
                10. Method that takes String, int, returns string, computes concat + *
                11. Method that takes String, int, String, returns string, computes concat + *
                12. Method that takes int, String, int, return string, computes concat + *
                    + */ +public class TestCodegenProxyCreator extends TestCase { + private static final boolean DEBUG = false ; + + public static class TestException extends Exception { + } + + public static interface TestInterface { + boolean echo( boolean arg ) ; + char echo( char arg ) ; + byte echo( byte arg ) ; + short echo( short arg ) ; + int echo( int arg ) ; + long echo( long arg ) ; + float echo( float arg ) ; + double echo( double arg ) ; + Object echo( Object arg ) ; + Integer echo( Integer arg ) ; + void throwIf42( int arg ) throws TestException ; + int return42() ; + void alwaysThrow() throws TestException ; + void sideEffect() ; + boolean sideEffectCalled() ; + int sum( int arg1, int arg2 ) ; + String concat( String arg1, String arg2 ) ; + String concat( int arg1, String arg2 ) ; + String concat( String arg1, int arg2 ) ; + String concat( String arg1, int arg2, String arg3 ) ; + String concat( int arg1, String arg2, int arg3 ) ; + } + + public static class TestInterfaceImpl implements TestInterface { + private boolean sideEffectCalledFlag = false ; + + public boolean sideEffectCalled() + { + return sideEffectCalledFlag ; + } + + public boolean echo( boolean arg ) + { + return arg ; + } + + public char echo( char arg ) + { + return arg ; + } + + public byte echo( byte arg ) + { + return arg ; + } + + public short echo( short arg ) + { + return arg ; + } + + public int echo( int arg ) + { + return arg ; + } + + public long echo( long arg ) + { + return arg ; + } + + public float echo( float arg ) + { + return arg ; + } + + public double echo( double arg ) + { + return arg ; + } + + public Object echo( Object arg ) + { + return arg ; + } + + public Integer echo( Integer arg ) + { + return arg ; + } + + public void throwIf42( int arg ) throws TestException + { + if (arg == 42) + throw new TestException() ; + } + + public int return42() + { + return 42 ; + } + + public void alwaysThrow() throws TestException + { + throw new TestException() ; + } + + public void sideEffect() + { + sideEffectCalledFlag = true ; + } + + public int sum( int arg1, int arg2 ) + { + return arg1 + arg2 ; + } + + public String concat( String arg1, String arg2 ) + { + return arg1 + arg2 ; + } + + public String concat( int arg1, String arg2 ) + { + return arg1 + arg2 ; + } + + public String concat( String arg1, int arg2 ) + { + return arg1 + arg2 ; + } + + public String concat( String arg1, int arg2, String arg3 ) + { + return arg1 + arg2 + arg3 ; + } + + public String concat( int arg1, String arg2, int arg3 ) + { + return arg1 + arg2 + arg3 ; + } + } + + public static abstract class TestInterfaceImplTester extends TestCase { + + public abstract TestInterface getTestInterface() ; + + public TestInterfaceImplTester() + { + super() ; + } + + public TestInterfaceImplTester( String name ) + { + super( name ) ; + } + + public void testBooleanEcho() + { + assertTrue( getTestInterface().echo( true ) ) ; + } + + public void testCharEcho() + { + assertEquals( getTestInterface().echo( 'A' ), 'A' ) ; + } + + public void testByteEcho() + { + assertEquals( getTestInterface().echo( (byte)23 ), (byte)23 ) ; + } + + public void testShortEcho() + { + assertEquals( getTestInterface().echo( (short)23 ), (short)23 ) ; + } + + public void testIntEcho() + { + assertEquals( getTestInterface().echo( 3214 ), 3214 ) ; + } + + public void testLongEcho() + { + assertEquals( getTestInterface().echo( 12345678901234L ), + 12345678901234L ) ; + } + + public void testFloatEcho() + { + assertEquals( getTestInterface().echo( 1.23f ), 1.23f, .00001f ) ; + } + + public void testDoubleEcho() + { + assertEquals( getTestInterface().echo( 1.23 ), 1.23, .00001 ) ; + } + + public void testObjectEcho() + { + Object obj = new Object() ; + assertEquals( getTestInterface().echo( obj ), obj ) ; + } + + public void testIntegerEcho() + { + Integer num = new Integer( 43 ) ; + assertEquals( getTestInterface().echo( num ), num ) ; + } + + public void testThrowIf42Throw() + { + try { + getTestInterface().throwIf42( 42 ) ; + fail( "Call completed without exception" ) ; + } catch (TestException exc) { + // This is the expected result + } catch (Throwable thr) { + fail( "Unexpected exception " + thr ) ; + } + } + + public void testThrowIf42NoThrow() + { + try { + getTestInterface().throwIf42( 24 ) ; + } catch (Throwable thr) { + fail( "Unexpected exception " + thr ) ; + } + } + + public void testReturn42() + { + assertEquals( getTestInterface().return42(), 42 ) ; + } + + public void testAlwaysThrow() + { + try { + getTestInterface().alwaysThrow() ; + fail( "Call completed without exception" ) ; + } catch (TestException exc) { + // This is the expected result + } catch (Throwable thr) { + fail( "Unexpected exception " + thr ) ; + } + } + + public void testSideEffect() + { + getTestInterface().sideEffect() ; + assertTrue( getTestInterface().sideEffectCalled() ) ; + } + + public void testSum() + { + assertEquals( getTestInterface().sum( 237, 479 ), 237+479 ) ; + } + + public void testConcatSS() + { + assertEquals( getTestInterface().concat( "Another ", "Test" ), + "Another Test" ) ; + } + + public void testConcatIS() + { + assertEquals( getTestInterface().concat( 1, "Test" ), "1Test" ) ; + } + + public void testConcatSI() + { + assertEquals( getTestInterface().concat( "Test", 1 ), "Test1" ) ; + } + + public void testConcatSIS() + { + assertEquals( getTestInterface().concat( "Test", 1, " Another" ), + "Test1 Another" ) ; + } + + public void testConcatISI() + { + assertEquals( getTestInterface().concat( 1, "Test", 2 ), + "1Test2" ) ; + } + } + + public static class SimpleTestSuite extends TestInterfaceImplTester { + private TestInterface object ; + + public SimpleTestSuite( String name ) + { + super( name ) ; + object = new TestInterfaceImpl() ; + } + public SimpleTestSuite() + { + super() ; + object = new TestInterfaceImpl() ; + } + + public TestInterface getTestInterface() + { + return object ; + } + } + + public static class ProxyTestSuite extends TestInterfaceImplTester { + private static Class proxyClass = null ; + private static Method[] methods = null ; + private TestInterface object ; + + public static class TestBase { + Method[] methods = null ; + TestInterface ti = null ; + + public Object selfAsBaseClass() { + return this ; + } + + public void initialize( Method[] methods, TestInterface ti ) + { + this.methods = methods ; + this.ti = ti ; + } + + public Object invoke( int methodNumber, + Object[] args ) throws Throwable + { + try { + return methods[methodNumber].invoke( ti, args ) ; + } catch (InvocationTargetException ite) { + throw ite.getCause() ; + } + } + } + + public ProxyTestSuite( String name ) + { + super( name ) ; + init() ; + } + + public ProxyTestSuite() + { + super() ; + init() ; + } + + private void init() + { + TestInterface ti = new TestInterfaceImpl() ; + + // Make sure we only try to create the proxy class once! + if (proxyClass == null) { + // Set up proxy for ti: this is really the main part of the test + Class baseClass = TestBase.class ; + Class interfaceClass = TestInterface.class ; + Class[] interfaces = new Class[] { interfaceClass } ; + methods = interfaceClass.getDeclaredMethods() ; + + ProtectionDomain pd = this.getClass().getProtectionDomain() ; + ClassLoader loader = this.getClass().getClassLoader() ; + + CodegenProxyCreator pc = + new CodegenProxyCreator( + "corba.dynamicrmiiiop.TestInterfaceProxy", + baseClass, interfaces, methods ) ; + + proxyClass = pc.create( pd, loader, DEBUG, System.out ) ; + } + + try { + TestBase base = (TestBase)proxyClass.newInstance() ; + base.initialize( methods, ti ) ; + object = (TestInterface)base ; + } catch (Exception exc) { + exc.printStackTrace() ; + fail( "Could not create proxy" ) ; + } + } + + public TestInterface getTestInterface() + { + return object ; + } + } + + public void testDummy() + { + // Dummy test to avoid Junit complaints. + } + + public static Test suite() + { + return new TestSuite( TestCodegenProxyCreator.class ) ; + } +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/TestTransport.java b/test/src/share/classes/corba/dynamicrmiiiop/TestTransport.java new file mode 100644 index 000000000..774c16f1b --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/TestTransport.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop ; + +import org.omg.CORBA.portable.ApplicationException ; +import org.omg.CORBA_2_3.portable.InputStream ; +import org.omg.CORBA_2_3.portable.OutputStream ; + +import com.sun.corba.ee.impl.encoding.CDROutputObject ; +import com.sun.corba.ee.impl.encoding.EncapsInputStream ; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; +import com.sun.corba.ee.impl.encoding.CDRInputObject ; + + +import com.sun.corba.ee.spi.orb.ORB ; + +public class TestTransport { + private ORB orb ; + + public TestTransport( ORB orb ) + { + this.orb = orb ; + } + + private static final int REQUEST_HEADER = 24 ; + private static final int NORMAL_REPLY_HEADER = 30 ; + private static final int EXCEPTION_REPLY_HEADER = 36 ; + + public InputStream getInputStream( OutputStream os ) + { + CDROutputObject cos = (CDROutputObject)os ; + byte[] data = cos.toByteArray() ; + return new EncapsInputStream( orb, data, data.length ) ; + } + + public OutputStream makeRequest( String mname ) + { + OutputStream result = new EncapsOutputStream( orb ) ; + result.write_long( REQUEST_HEADER ) ; + result.write_string( mname ) ; + return result ; + } + + public OutputStream makeNormalReply() + { + OutputStream result = new EncapsOutputStream( orb ) ; + result.write_long( NORMAL_REPLY_HEADER ) ; + return result ; + } + + public OutputStream makeExceptionReply() + { + OutputStream result = new EncapsOutputStream( orb ) ; + result.write_long( EXCEPTION_REPLY_HEADER ) ; + return result ; + } + + public String readRequestHeader( InputStream is ) + { + int header = is.read_long() ; + if (header != REQUEST_HEADER) + throw new RuntimeException( + "InputStream does not begin with REQUEST_HEADER" ) ; + return is.read_string() ; + } + + // Throw ApplicationException. Note that this + // must leave the stream ready to read the repo id + // string, so we need to use mark/reset here. + // This code is taken from CorbaClientRequestDispatcher. + private String peekUserExceptionId(CDRInputObject inputObject) + { + // REVISIT - need interface for mark/reset + inputObject.mark(Integer.MAX_VALUE); + String result = inputObject.read_string(); + inputObject.reset(); + return result; + } + + public void readReplyHeader( InputStream is ) + throws ApplicationException + { + int header = is.read_long() ; + if (header == NORMAL_REPLY_HEADER) { + // NO-OP + } else if (header == EXCEPTION_REPLY_HEADER) { + String id = peekUserExceptionId( (CDRInputObject)is ) ; + throw new ApplicationException( id, is ) ; + } else { + // error + throw new RuntimeException( "Bad reply header in test" ) ; + } + } +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/A.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/A.java new file mode 100644 index 000000000..f863c61c5 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/A.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public interface A extends B, C +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/B.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/B.java new file mode 100644 index 000000000..7831645a8 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/B.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public interface B extends D +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C.java new file mode 100644 index 000000000..32b2f7fe0 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public interface C extends D +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C1.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C1.java new file mode 100644 index 000000000..56dda1e5a --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C1.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public class C1 implements D +{ +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C2.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C2.java new file mode 100644 index 000000000..cfeb3b7cf --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C2.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.util.HashMap ; + +public class C2 extends HashMap implements B +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C3.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C3.java new file mode 100644 index 000000000..4a93fe539 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C3.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.util.HashMap ; + +public class C3 extends HashMap implements A, B +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C4.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C4.java new file mode 100644 index 000000000..f576c45fa --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C4.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public class C4 extends C3 implements A +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C5.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C5.java new file mode 100644 index 000000000..ad87c05a5 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C5.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public class C5 extends C4 implements E +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C6.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C6.java new file mode 100644 index 000000000..ccc2cf18b --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/C6.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public class C6 extends C5 implements H +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/D.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/D.java new file mode 100644 index 000000000..62b00d08e --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/D.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.rmi.Remote ; + +public interface D extends Remote +{ +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/DMMImplTestClasses.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/DMMImplTestClasses.java new file mode 100644 index 000000000..535c114ca --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/DMMImplTestClasses.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface DMMImplTestClasses +{ + public interface AllRemote + { + AllRemote make( AllRemote arg ) throws RemoteException ; + + AllRemote make( String arg ) throws RemoteException ; + } + + public interface SomeRemote + { + SomeRemote make( SomeRemote arg ) throws RemoteException ; + + SomeRemote make( String arg ) ; + } + + public interface NoRemote + { + NoRemote make( NoRemote arg ) ; + } + + public interface NoMethods + { + } + + public interface IDLSimpleInterface extends org.omg.CORBA.portable.IDLEntity + { + void noop (); + } + + public interface IDLValue extends org.omg.CORBA.portable.ValueBase + { + public abstract void foo (); + + public abstract int bar (); + + } + + public final class IDLStruct implements org.omg.CORBA.portable.IDLEntity + { + public int arg1 = (int)0; + public int arg2 = (int)0; + + public IDLStruct () + { + } + + public IDLStruct (int _arg1, int _arg2) + { + arg1 = _arg1; + arg2 = _arg2; + } + } + + public interface IDLInterface extends org.omg.CORBA.Object, + org.omg.CORBA.portable.IDLEntity + { + String name (); + void name (String newName); + } +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/DefaultInterface.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/DefaultInterface.java new file mode 100644 index 000000000..9b04ede0e --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/DefaultInterface.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses; + +public interface DefaultInterface extends java.rmi.Remote { + + void foo() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/E.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/E.java new file mode 100644 index 000000000..d316e588b --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/E.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public interface E extends F +{ +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/F.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/F.java new file mode 100644 index 000000000..c16c6b505 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/F.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public interface F extends G +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/G.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/G.java new file mode 100644 index 000000000..9a0d24dbc --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/G.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.rmi.Remote ; + +public interface G extends Remote +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/H.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/H.java new file mode 100644 index 000000000..78e0cc016 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/H.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public interface H extends G, B +{ +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/MyApplicationException.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/MyApplicationException.java new file mode 100644 index 000000000..89598dbc2 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/MyApplicationException.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public class MyApplicationException extends MyApplicationExceptionBase +{ + public MyApplicationException( String msg ) + { + super( msg ) ; + } +} + diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/MyApplicationExceptionBase.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/MyApplicationExceptionBase.java new file mode 100644 index 000000000..96b7a6f03 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/MyApplicationExceptionBase.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +public class MyApplicationExceptionBase extends Exception +{ + public MyApplicationExceptionBase( String msg ) + { + super( msg ) ; + } + + public boolean equals( Object obj ) + { + if (this == obj) + return true ; + + if (!obj.getClass().equals(getClass())) + return false ; + + MyApplicationExceptionBase other = (MyApplicationExceptionBase)obj ; + + if (getMessage() == null) + return other.getMessage() == null ; + + return getMessage().equals( other.getMessage() ) ; + } +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/TieTest.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/TieTest.java new file mode 100644 index 000000000..f3905947c --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/TieTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; +import java.util.Map ; + +public interface TieTest extends Remote +{ + void hasAByteArray( byte[] arg ) throws RemoteException ; + + int throwsException( int arg ) throws Exception, RemoteException ; + + int throwsDeclaredException( int arg ) throws MyApplicationExceptionBase, + RemoteException ; + + int throwsSystemException( int arg ) throws RemoteException ; + + int throwsJavaException( int arg ) throws RemoteException ; + + String m0() throws RemoteException ; + + String m1( String another ) throws RemoteException ; + + String m2( Map map, String key ) throws RemoteException ; + + void vm0() throws RemoteException ; + + void vm1( String another ) throws RemoteException ; + + void vm2( Map map, String key ) throws RemoteException ; +} diff --git a/test/src/share/classes/corba/dynamicrmiiiop/testclasses/TieTestImpl.java b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/TieTestImpl.java new file mode 100644 index 000000000..15eab3a91 --- /dev/null +++ b/test/src/share/classes/corba/dynamicrmiiiop/testclasses/TieTestImpl.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.dynamicrmiiiop.testclasses ; + +import java.rmi.RemoteException ; + +import java.util.Map ; +import java.util.HashMap ; + +import javax.rmi.CORBA.Util ; + +import org.omg.CORBA.BAD_PARAM ; +import org.omg.CORBA.BAD_OPERATION ; +import org.omg.CORBA.CompletionStatus ; +import org.omg.CORBA.SystemException ; + +import org.omg.CORBA.portable.UnknownException ; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; +import org.glassfish.pfl.test.ObjectUtility; + +public class TieTestImpl implements TieTest +{ + private static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + private static Object wrapException( Throwable thr ) + { + try { + return Util.wrapException( thr ) ; + } catch (RuntimeException exc) { + // The return type of wrapException is RemoteException, + // but the stupid spec (see section 1.4.8.1) requires + // that a RuntimeException simply result in the same + // RuntimeException, which is not a subtype of RemoteException. + // Therefore the result is thrown in this case. + // That works OK in stubs, but throwing an exception in a + // static initializer blows up the class loading, which we + // cannot tolerate here in this test. + return exc ; + } + } + + // Data format: ( name, tieOnly?, tieResult, stubResult, args, argTypes ) * + // The Tie result is the result used here, while the stub result is often + // wrapped for exception handling. + private static Object[][] data = { + // name, not used, + // tieResult, + // stubResult, + // args, + // types + { "hasAByteArray", Boolean.FALSE, + null, + null, + new Object[] { new byte[]{ 0, 1, 2, 3 } }, + new Class[] { byte[].class } }, + { "foo_bar_baz", Boolean.TRUE, + new BAD_OPERATION( + wrapper.METHOD_NOT_FOUND_IN_TIE, + CompletionStatus.COMPLETED_NO ), + null, + new Object[] { new Integer(37) }, + new Class[] { int.class } }, + { "throwsDeclaredException", Boolean.FALSE, + new MyApplicationException("Foo"), + new MyApplicationException("Foo"), + new Object[] { new Integer(36) }, + new Class[] { int.class } }, + { "throwsException", Boolean.FALSE, + new Exception("Foo"), + new Exception("Foo"), + new Object[] { new Integer(38) }, + new Class[] { int.class } }, + { "throwsSystemException", Boolean.FALSE, + new BAD_PARAM(), + Util.mapSystemException( new BAD_PARAM() ), + new Object[] { new Integer(35) }, + new Class[] { int.class } }, + { "throwsJavaException", Boolean.FALSE, + new UnknownException( new IllegalStateException() ), + wrapException( new IllegalStateException() ), + new Object[] { new Integer(31) }, + new Class[] { int.class } }, + { "m0", Boolean.FALSE, + "m0 result", + "m0 result", + null, + new Class[0] }, + { "m1", Boolean.FALSE, + "m1 result", + "m1 result", + new Object[] { "m1 arg" }, + new Class[] { String.class } }, + { "m2", Boolean.FALSE, + "m2 result", + "m2 result", + new Object[] { new HashMap(), "m2 arg" }, + new Class[] { Map.class, String.class } }, + { "vm0", Boolean.FALSE, + null, + null, + null, + new Class[0] }, + { "vm1", Boolean.FALSE, + null, + null, + new Object[] { "vm1 arg" }, + new Class[0] }, + { "vm2", Boolean.FALSE, + null, + null, + new Object[] { null, "vm2 arg" }, + new Class[0] } } ; + + private static Map mnameToExpectedTieResult = new HashMap() ; + private static Map mnameToExpectedStubResult = new HashMap() ; + private static Map mnameToExpectedArguments = new HashMap() ; + private static Map mnameToArgumentTypes = new HashMap() ; + private static String lastError ; + + static { + for (int ctr=0; ctr clusterInstanceInfo) + { + if (debug) { dprint(".insert: " + iorInfo); } + return null; + } + + public List extract(IOR ior) + { + if (debug) { dprint(".extract"); } + return null; + } + + //////////////////////////////////////////////////// + // + // ORBConfigurator + // + + public void configure(DataCollector collector, ORB orb) + { + if (debug) { dprint(".configure->:"); } + + this.orb = orb; + try { + orb.register_initial_reference( + ORBConstants.CSI_V2_SSL_TAGGED_COMPONENT_HANDLER, + this); + } catch (InvalidName e) { + dprint(".configure: !!!!! FAILURE"); + e.printStackTrace(System.out); + System.exit(1); + } + + if (debug) { dprint(".configure<-:"); } + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + private static void dprint(String msg) + { + ORBUtility.dprint("CSIv2SSLTaggedComponentHandlerImpl", msg); + } + +} + +// End of file. + + diff --git a/test/src/share/classes/corba/folb/Client.java b/test/src/share/classes/corba/folb/Client.java new file mode 100644 index 000000000..ce3185b85 --- /dev/null +++ b/test/src/share/classes/corba/folb/Client.java @@ -0,0 +1,202 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 08 (Wed) 19:24:39 by Harold Carr. +// Last Modified : 2005 Sep 30 (Fri) 15:35:57 by Harold Carr. +// + +package corba.folb; + +import org.testng.Assert ; +import org.testng.annotations.Test ; +import org.testng.annotations.BeforeSuite ; + +/** + * @author Harold Carr + */ +public class Client extends ClientBase { + + // public CSIv2SSLTaggedComponentHandler csiv2SSLTaggedComponentHandler; + + public Client() { + } + + @BeforeSuite + public void clientSetup() { + setup( getDefaultProperties() ) ; + } + + @Test + public void testBootstrap() { + dprint("--------------------------------------------------"); + dprint("testBootstrap (missing label, therefore IORUpdate)"); + dprint("--------------------------------------------------"); + + makeCall(testRfmWithAddressesWithoutLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL, + "BOOTSTRAP1 Test (missing label, therefore IORUpdate)", + corba.folb_8_1.Common.W, + NO_MEMBERSHIP_LABEL, RECEIVE_IOR_UPDATE); + makeCall(testRfmWithAddressesWithoutLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL, + "BOOTSTRAP2 Test (missing label, therefore IORUpdate)", + corba.folb_8_1.Common.W, + NO_MEMBERSHIP_LABEL, RECEIVE_IOR_UPDATE); + } + + @Test( dependsOnMethods={ "testBootstrap" } ) + public void testNormalOperation() { + dprint("--------------------------------------------------"); + dprint("testNormalOperation (send label, no IORUpdate)"); + dprint("--------------------------------------------------"); + + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Normal operation1 (send label, no IORUpdate)", + corba.folb_8_1.Common.W, + SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Normal operation2 (send label, no IORUpdate)", + corba.folb_8_1.Common.W, + SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + } + + @Test( dependsOnMethods={ "testNormalOperation" } ) + public void testIORUpdate() { + try { + dprint("--------------------------------------------------"); + dprint("testIORUpdate only (send label, receive IORUpdate)"); + dprint("setup: remove instance"); + dprint("--------------------------------------------------"); + doRemoveInstance(gisPoaWithAddressesWithLabels, corba.folb_8_1.Common.Z); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "IORUpdate only1 (send label, receive IORUpdate)", + corba.folb_8_1.Common.W, SEND_MEMBERSHIP_LABEL, + RECEIVE_IOR_UPDATE); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "IORUpdate only2 (send label, no IORUpdate)", + corba.folb_8_1.Common.W, SEND_MEMBERSHIP_LABEL, + NO_IOR_UPDATE); + + doAddInstance(gisPoaWithAddressesWithLabels, corba.folb_8_1.Common.Z); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "IORUpdate only3 (send label, receive IORUpdate)", + corba.folb_8_1.Common.W, SEND_MEMBERSHIP_LABEL, + RECEIVE_IOR_UPDATE); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "IORUpdate only4 (send label, no IORUpdate)", + corba.folb_8_1.Common.W, SEND_MEMBERSHIP_LABEL, + NO_IOR_UPDATE); + } catch (Exception ex) { + Assert.fail( "Caught exception in testIORUpdate", ex ) ; + } + } + + @Test( dependsOnMethods={ "testIORUpdate" } ) + public void testFailoverWithoutUpdate() { + try { + dprint("--------------------------------------------------"); + dprint("testFailoverWithoutUpdate (send label, no IORUpdate)"); + dprint("Setup: remove W listener"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections(corba.folb_8_1.Common.W); + Thread.sleep(2000); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Failover without update (send label, no IORUpdate)", + corba.folb_8_1.Common.X, SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + + dprint("--------------------------------------------------"); + dprint("Check stuck to new instance (send label, no IORUpdate)"); + dprint("--------------------------------------------------"); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Check stuck to new instance (send label, no IORUpdate)", + corba.folb_8_1.Common.X, SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + } catch (Exception ex) { + Assert.fail( "Caught exception in testFailoverWithoutUpdate", ex ) ; + } + } + + @Test( dependsOnMethods={ "testFailoverWithoutUpdate" } ) + public void testFailoverWithUpdate() { + try { + dprint("--------------------------------------------------"); + dprint("testFailoverWithUpdate (send label, IORUpdate)"); + dprint("Setup: remove instances W, X"); + dprint("Setup: remove X listener"); + dprint("--------------------------------------------------"); + doRemoveInstance(gisPoaWithAddressesWithLabels, corba.folb_8_1.Common.W); + doRemoveInstance(gisPoaWithAddressesWithLabels, corba.folb_8_1.Common.X); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections(corba.folb_8_1.Common.X); + Thread.sleep(2000); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Failover with update (send label, IORUpdate)", + corba.folb_8_1.Common.Y, SEND_MEMBERSHIP_LABEL, + RECEIVE_IOR_UPDATE); + + dprint("--------------------------------------------------"); + dprint("Check stuck to new instance (send label, no IORUpdate)"); + dprint("--------------------------------------------------"); + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Check stuck to new instance (send label, no IORUpdate)", + corba.folb_8_1.Common.Y, SEND_MEMBERSHIP_LABEL, + NO_IOR_UPDATE); + } catch (Exception ex) { + Assert.fail("Caught exception in testFailoverWithUpdate", ex); + } + } + + private void doAddInstance( + GroupInfoServiceTest gist, + String arg ) throws Exception { + + dprint( "Adding instance " + arg ) ; + gist.addInstance(arg); + + // Add a delay here to avoid race condition in test: + // We add instance asynchronously, and a call that + // completes after the start of RFM restartFactories + // does NOT get updated in order to avoid a serious + // deadlock problem. + + Thread.sleep( 2*1000 ) ; + } + + private void doRemoveInstance( + GroupInfoServiceTest gist, + String arg ) throws Exception { + + dprint( "Removing instance " + arg ) ; + gist.removeInstance(arg); + + // Add a delay here to avoid race condition in test: + // We remove instance asynchronously, and a call that + // completes after the start of RFM restartFactories + // does NOT get updated in order to avoid a serious + // deadlock problem. + + Thread.sleep( 2*1000 ) ; + } + + public static void main(String[] av) { + doMain( Client.class ) ; + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/ClientBase.java b/test/src/share/classes/corba/folb/ClientBase.java new file mode 100644 index 000000000..c7b1b6b7d --- /dev/null +++ b/test/src/share/classes/corba/folb/ClientBase.java @@ -0,0 +1,331 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 08 (Wed) 19:24:39 by Harold Carr. +// Last Modified : 2005 Sep 30 (Fri) 15:35:57 by Harold Carr. +// + +package corba.folb; + +import java.util.Hashtable; +import java.util.Properties; +import javax.naming.InitialContext; + +import com.sun.corba.ee.spi.folb.GroupInfoService; +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.spi.logging.ORBUtilSystemException ; + +import com.sun.corba.ee.impl.folb.ClientGroupManager; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +import corba.folb_8_1.SocketFactoryImpl; +import corba.framework.TestngRunner; +import corba.hcks.U; + +import org.testng.Assert ; + +import org.omg.CORBA.SystemException ; + +/** + * @author Harold Carr + */ +public abstract class ClientBase { + protected static final ORBUtilSystemException wrapper = + ORBUtilSystemException.self ; + + public static final boolean SEND_MEMBERSHIP_LABEL = true; + public static final boolean NO_MEMBERSHIP_LABEL = ! SEND_MEMBERSHIP_LABEL; + public static final boolean RECEIVE_IOR_UPDATE = true; + public static final boolean NO_IOR_UPDATE = ! RECEIVE_IOR_UPDATE; + + protected ORB orb = null ; + protected GroupInfoService gis = null ; + protected InitialContext initialContext = null ; + protected GroupInfoServiceTest gisPoaWithAddressesWithLabels = null ; + protected GroupInfoServiceTest gisPoaWithoutAddressesWithoutLabel = null ; + protected EchoTest testRfmWithAddressesWithLabel = null ; + protected EchoTest testRfmWithAddressesWithoutLabel = null ; + + protected Properties getDefaultProperties() { + Properties props = new Properties(); + props.setProperty(ORBConstants.DEBUG_PROPERTY, + //"giop,transport,subcontract,poa" + "transport,folb,protocol" ); + + props.setProperty(ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + SocketFactoryImpl.class.getName()); + + // Register a client interceptor to see what connection + // is being used for test (using a proprietary extension). + props.setProperty(ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + corba.folb_8_1.Client.class.getName(), + "dummy"); + + props.setProperty(ORBConstants.USER_CONFIGURATOR_PREFIX + + ClientGroupManager.class.getName(), + "dummy"); + + props.setProperty(ORBConstants.USER_CONFIGURATOR_PREFIX + + CSIv2SSLTaggedComponentHandlerImpl.class.getName(), + "dummy"); + + props.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ; + + return props ; + } + + protected void setup(Properties props) { + try { + dprint("--------------------------------------------------"); + dprint("BEGIN SETUP"); + dprint("--------------------------------------------------"); + + dprint("--------------------------------------------------"); + dprint("ORB.init"); + dprint("--------------------------------------------------"); + orb = (ORB) ORB.init((String[])null, props); + + dprint("--------------------------------------------------"); + dprint("Lookup GIS and addObserver for IORUpdates"); + dprint("--------------------------------------------------"); + gis = (GroupInfoService) orb.resolve_initial_references( + ORBConstants.FOLB_CLIENT_GROUP_INFO_SERVICE); + gis.addObserver(new GroupInfoServiceObserver() { + public void membershipChange() { + dprint(".membershipChange->:"); + dprint(".membershipChange: " + + gis.getClusterInstanceInfo((String[])null)); + dprint(".membershipChange<-:"); + } + } ); + + dprint("--------------------------------------------------"); + dprint("new InitialContext"); + dprint("--------------------------------------------------"); + Hashtable env = new Hashtable(); + env.put("java.naming.corba.orb", orb); + initialContext = new InitialContext(env); + + dprint("--------------------------------------------------"); + dprint("lookup and narrow: " + + Common.GIS_POA_WITH_ADDRESSES_WITH_LABEL); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels = (GroupInfoServiceTest) + U.lookupAndNarrow(Common.GIS_POA_WITH_ADDRESSES_WITH_LABEL, + GroupInfoServiceTest.class, + initialContext); + + dprint("--------------------------------------------------"); + dprint("lookup and narrow: " + + Common.GIS_POA_WITHOUT_ADDRESSES_WITHOUT_LABEL); + dprint("--------------------------------------------------"); + gisPoaWithoutAddressesWithoutLabel = (GroupInfoServiceTest) + U.lookupAndNarrow(Common.GIS_POA_WITHOUT_ADDRESSES_WITHOUT_LABEL, + GroupInfoServiceTest.class, + initialContext); + + dprint("--------------------------------------------------"); + dprint("Lookup and narrow: " + + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL); + dprint("--------------------------------------------------"); + testRfmWithAddressesWithLabel = (EchoTest) + U.lookupAndNarrow(Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + EchoTest.class, + initialContext); + + + dprint("--------------------------------------------------"); + dprint("Lookup and narrow: " + + Common.TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL); + dprint("--------------------------------------------------"); + testRfmWithAddressesWithoutLabel = (EchoTest) + U.lookupAndNarrow(Common.TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL, + EchoTest.class, + initialContext); + + + dprint("--------------------------------------------------"); + dprint("remove IIOP_CLEAR_TEXT listener"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections( + com.sun.corba.ee.spi.transport.SocketInfo.IIOP_CLEAR_TEXT); + Thread.sleep(2000); + + dprint("--------------------------------------------------"); + dprint("END SETUP"); + dprint("--------------------------------------------------"); + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + protected void circularSetup() throws Exception { + dprint("--------------------------------------------------"); + dprint("BEGIN CIRCULAR SETUP"); + dprint("--------------------------------------------------"); + + dprint("--------------------------------------------------"); + dprint("Remove W acceptor/connections"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections( + corba.folb_8_1.Common.W); + + dprint("--------------------------------------------------"); + dprint("Remove X acceptor/connections"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections( + corba.folb_8_1.Common.X); + + dprint("--------------------------------------------------"); + dprint("Remove Y acceptor/connections"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections( + corba.folb_8_1.Common.Y); + Thread.sleep(2000); + + dprint("--------------------------------------------------"); + dprint("Failover without update (send label, no IORUpdate)"); + dprint("--------------------------------------------------"); + + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Failover without update (send label, no IORUpdate)", + corba.folb_8_1.Common.Z, + SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + + dprint("--------------------------------------------------"); + dprint("Restart X Acceptor"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.addAcceptor( + corba.folb_8_1.Common.X); + Thread.sleep(2000); + + dprint("--------------------------------------------------"); + dprint("Remove Z Acceptor"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections( + corba.folb_8_1.Common.Z); + Thread.sleep(2000); + + dprint("--------------------------------------------------"); + dprint("END CIRCULAR SETUP"); + dprint("--------------------------------------------------"); + } + + protected void makeCall(EchoTest ref, String refName, String arg, + String socketType, boolean sendMembershipLabel, + boolean receiveIORUpdate) { + + try { + String msg = null ; + + dprint("--------------------------------------------------"); + dprint(refName + ".echo"); + dprint("--------------------------------------------------"); + + String result = ref.echo(arg); + + dprint("--------------------------------------------------"); + dprint(refName + ".echo result: " + result); + if (socketType.equals(corba.folb_8_1.Client.lastSocketTypeUsed)) { + dprint(" Correct socket type: " + socketType); + } else { + dprint( "ERROR: incorrect socket type: expected: " + socketType + + " got: " + corba.folb_8_1.Client.lastSocketTypeUsed ) ; + Assert.fail( "incorrect socket type: expected: " + socketType + + " got: " + corba.folb_8_1.Client.lastSocketTypeUsed ) ; + } + + if (sendMembershipLabel == ClientGroupManager.sentMemberShipLabel) { + dprint(" Correctly handled membership label: " + + sentOrNotSent(sendMembershipLabel)); + } else { + dprint( "ERROR: incorrectly handled membership label:" + + " expected: " + sentOrNotSent(sendMembershipLabel) + + " got: " + sentOrNotSent(ClientGroupManager.sentMemberShipLabel) ) ; + Assert.fail( "incorrectly handled membership label:" + + " expected: " + sentOrNotSent(sendMembershipLabel) + + " got: " + sentOrNotSent(ClientGroupManager.sentMemberShipLabel) ) ; + } + + if (receiveIORUpdate == ClientGroupManager.receivedIORUpdate) { + dprint(" Correctly handled IOR update: " + + receivedOrNotReceived(receiveIORUpdate)); + } else { + dprint( "ERROR: incorrectly handled IOR update:" + + " expected: " + receivedOrNotReceived(receiveIORUpdate) + + " got: " + receivedOrNotReceived(ClientGroupManager.receivedIORUpdate)); + Assert.fail( "incorrectly handled IOR update:" + + " expected: " + receivedOrNotReceived(receiveIORUpdate) + + " got: " + receivedOrNotReceived(ClientGroupManager.receivedIORUpdate)); + } + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + private String sentOrNotSent(boolean x) { + return x ? "sent" : "not sent"; + } + + private String receivedOrNotReceived(boolean x) { + return x ? "received" : "not received"; + } + + protected void checkMarshalException(String msg, Exception got, + SystemException expected) { + + Throwable thr = got ; + while (thr != null) { + if (thr.getClass().equals(expected.getClass())) { + break ; + } + + thr = thr.getCause() ; + } + + SystemException sysex = null; + if (thr != null) { + sysex = (SystemException)thr ; + } + + if ((sysex != null) && (sysex.minor == expected.minor) + && (sysex.completed == expected.completed)) { + dprint("--------------------------------------------------"); + dprint(msg + ": SUCCEEDED"); + dprint("--------------------------------------------------"); + } else { + got.printStackTrace(System.out); + dprint( msg + "ERROR: Expected MarshalException " + expected + + " Got : " + got + + " detail: " + got.getCause() ) ; + Assert.fail( msg + " FAILED: Expected MarshalException " + expected + + " Got : " + got + + " detail: " + got.getCause() ) ; + } + } + + protected void dprint(String msg) { + ORBUtility.dprint(this, msg); + } + + protected static void doMain( Class cls ) { + TestngRunner runner = new TestngRunner() ; + runner.registerClass( cls ) ; + runner.run() ; + runner.systemExit() ; + } +} diff --git a/test/src/share/classes/corba/folb/ClientCircular.java b/test/src/share/classes/corba/folb/ClientCircular.java new file mode 100644 index 000000000..e2aaed264 --- /dev/null +++ b/test/src/share/classes/corba/folb/ClientCircular.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Sep 23 (Fri) 15:17:47 by Harold Carr. +// Last Modified : 2005 Oct 03 (Mon) 10:28:47 by Harold Carr. +// + +package corba.folb; + +import java.util.Properties; + +import org.omg.CORBA.SystemException; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import org.testng.annotations.BeforeSuite ; +import org.testng.annotations.Test ; + +import org.testng.Assert ; + +/** + * @author Harold Carr + */ +public class ClientCircular extends ClientBase { + + @BeforeSuite + public void clientSetup() throws Exception { + Properties props = getDefaultProperties() ; + + // Set retry timeout to 5 seconds. + props.setProperty(ORBConstants.TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY, + "250:5000:100"); + // props.setProperty(ORBConstants.DEBUG_PROPERTY, + // "transport,subcontract"); + + setup( props ) ; + circularSetup() ; + } + + @Test + public void test() throws Exception { + dprint("--------------------------------------------------"); + dprint("Circular failover without update (send label, no IORUpdate)"); + dprint("--------------------------------------------------"); + + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Circular failover without update (send label, no IORUpdate)", + corba.folb_8_1.Common.X, + SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + + dprint("--------------------------------------------------"); + dprint("Remove last Acceptor"); + dprint("--------------------------------------------------"); + gisPoaWithAddressesWithLabels.removeAcceptorAndConnections( + corba.folb_8_1.Common.X); + Thread.sleep(5000); + + dprint("--------------------------------------------------"); + dprint("Circular timeout reached."); + dprint("--------------------------------------------------"); + try { + makeCall(testRfmWithAddressesWithLabel, + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL, + "Circular timeout reached.", + "DUMMY", + SEND_MEMBERSHIP_LABEL, NO_IOR_UPDATE); + + Assert.fail( "Circular timeout failed: call incorrectly succeeded" ) ; + } catch (Exception e) { + SystemException cf = wrapper.connectFailure( new RuntimeException(), + "dummy", "dummy", "dummy"); + checkMarshalException("Circular timeout", e, cf); + } + } + + public static void main(String[] av) { + doMain( ClientCircular.class ) ; + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/ClientMulti.java b/test/src/share/classes/corba/folb/ClientMulti.java new file mode 100644 index 000000000..390347fbe --- /dev/null +++ b/test/src/share/classes/corba/folb/ClientMulti.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Sep 21 (Wed) 09:14:00 by Harold Carr. +// Last Modified : 2005 Sep 30 (Fri) 16:27:36 by Harold Carr. +// + +package corba.folb; + +import java.util.Hashtable; +import java.util.Properties; +import javax.naming.InitialContext; + +import org.omg.CORBA.ORB; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +import corba.framework.Controller; +import corba.hcks.U; + +import org.testng.annotations.BeforeSuite ; +import org.testng.annotations.Test ; + +import org.testng.Assert ; + +/** + * @author Harold Carr + */ +public class ClientMulti extends ClientBase { + + @BeforeSuite + public void clientSetup() { + setup( getDefaultProperties() ) ; + } + + @Test + public void test() throws Exception + { + CallThread a = + new CallThread(1000, testRfmWithAddressesWithLabel); + CallThread b = + new CallThread(1000, testRfmWithAddressesWithLabel); + CallThread c = + new CallThread(1000, testRfmWithAddressesWithLabel); + a.start(); + b.start(); + c.start(); + + do { + gisPoaWithAddressesWithLabels.removeInstance( + corba.folb_8_1.Common.Z); + Thread.sleep(1000); + gisPoaWithAddressesWithLabels.addInstance( + corba.folb_8_1.Common.Z); + Thread.sleep(1000); + } while (!a.done || !b.done || !c.done); + + Assert.assertTrue( (a.failures + b.failures + c.failures) == 0 ) ; + } + + public static void main(String[] av) { + doMain( ClientCircular.class ) ; + } +} + +class CallThread extends Thread +{ + int iterations; + int failures; + EchoTest ref; + boolean done; + + CallThread(int iterations, EchoTest ref) + { + this.failures = 0 ; + this.iterations = iterations; + this.ref = ref; + done = false; + } + + public void run() + { + for (int i = 0; i < iterations; ++i) { + try { + ref.echo("FOO"); + } catch (java.rmi.RemoteException e) { + failures++ ; + System.out.println("CallThread.run FAILURE !!!!!"); + e.printStackTrace(System.out); + } + } + done = true; + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/ClientWaitTimeout.java b/test/src/share/classes/corba/folb/ClientWaitTimeout.java new file mode 100644 index 000000000..61bfee0fd --- /dev/null +++ b/test/src/share/classes/corba/folb/ClientWaitTimeout.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Sep 23 (Fri) 15:17:47 by Harold Carr. +// Last Modified : 2005 Oct 03 (Mon) 10:28:16 by Harold Carr. +// + +package corba.folb; + +import java.util.Hashtable; +import java.util.Properties; +import javax.naming.InitialContext; + +import org.omg.CORBA.COMM_FAILURE; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.SystemException; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +import corba.framework.Controller; +import corba.hcks.U; + +import org.testng.annotations.BeforeSuite ; +import org.testng.annotations.Test ; + +import org.testng.Assert ; + +/** + * @author Harold Carr + */ +public class ClientWaitTimeout extends ClientBase { + + @BeforeSuite + public void clientSetup() throws Exception { + Properties props = getDefaultProperties(); + + // Set retry timeout to 5 seconds. + props.setProperty(ORBConstants.WAIT_FOR_RESPONSE_TIMEOUT, "5000"); + props.setProperty(ORBConstants.DEBUG_PROPERTY, + "transport,subcontract"); + + setup(props); + circularSetup(); + } + + @Test + public void test() throws Exception { + dprint("--------------------------------------------------"); + dprint("neverReturns - so should timeout in wait"); + dprint("--------------------------------------------------"); + + try { + testRfmWithAddressesWithLabel.neverReturns(); + Assert.fail( "should not return, but did return" ) ; + } catch (java.rmi.MarshalException e) { + SystemException cf = + wrapper.communicationsTimeoutWaitingForResponse( -1); + checkMarshalException("neverReturns", e, cf); + } + } + + public static void main(String[] av) { + doMain( ClientWaitTimeout.class ) ; + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/Common.java b/test/src/share/classes/corba/folb/Common.java new file mode 100644 index 000000000..521780514 --- /dev/null +++ b/test/src/share/classes/corba/folb/Common.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 7 (Tue) 09:24:39 by Harold Carr. +// Last Modified : 2005 Jul 28 (Thu) 18:10:31 by Harold Carr. +// + +package corba.folb; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.*; + +/** + * @author Harold Carr + */ +public abstract class Common +{ + // + // Object Adapter names. + // + + public static final String RFM_WITH_ADDRESSES_WITH_LABEL = + "TEST_RFM_WITH_ADDRESSES_WITH_LABEL"; + + public static final String RFM_WITH_ADDRESSES_WITHOUT_LABEL = + "#INTERNAL#RFM_WITH_ADDRESSES_WITHOUT_LABEL#INTERNAL#"; + + public static final String POA_WITH_ADDRESSES_WITH_LABEL = + "#INTERNAL#POA_WITH_ADDRESSES_WITH_LABEL#INTERNAL#"; + + // + // Names for bound references. + // + + public static final String TEST_RFM_WITH_ADDRESSES_WITH_LABEL = + "TEST_RFM_WITH_ADDRESSES_WITH_LABEL"; + + public static final String TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL = + "TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL"; + + public static final String GIS_POA_WITHOUT_ADDRESSES_WITHOUT_LABEL = + "GIS_POA_WITHOUT_ADDRESSES_WITHOUT_LABEL"; + + public static final String GIS_POA_WITH_ADDRESSES_WITH_LABEL = + "GIS_POA_WITH_ADDRESSES_WITH_LABEL"; +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/EchoTest.java b/test/src/share/classes/corba/folb/EchoTest.java new file mode 100644 index 000000000..bfe3b04cb --- /dev/null +++ b/test/src/share/classes/corba/folb/EchoTest.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 09 (Thu) 14:44:09 by Harold Carr. +// Last Modified : 2005 Sep 29 (Thu) 22:15:12 by Harold Carr. +// + +package corba.folb; + +import java.util.List; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * @author Harold Carr + */ +public interface EchoTest extends Remote { + public String echo(String x) + throws RemoteException; + + public void neverReturns() + throws RemoteException; +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/EchoTestServant.java b/test/src/share/classes/corba/folb/EchoTestServant.java new file mode 100644 index 000000000..7c0866e56 --- /dev/null +++ b/test/src/share/classes/corba/folb/EchoTestServant.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 09 (Thu) 14:44:09 by Harold Carr. +// Last Modified : 2005 Sep 29 (Thu) 23:00:33 by Harold Carr. +// + +package corba.folb; + +import java.util.List; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +public class EchoTestServant + extends PortableRemoteObject + implements EchoTest +{ + public static final String baseMsg = EchoTestServant.class.getName(); + + private ORB orb; + + public EchoTestServant(ORB orb) + throws RemoteException + { + this.orb = orb; + } + + public String echo(String x) + throws RemoteException + { + String result = "TestServant echoes: " + x; + dprint(".echo: " + result); + return result; + } + + public void neverReturns() + throws RemoteException + { + try { + dprint(".neverReturns"); + Object o = new Object(); + try { + synchronized (o) { + o.wait(); + } + } catch (InterruptedException e) { + ; + } + } catch (Exception e) { + dprint(".neverReturns: !!! Unexpected Exception"); + e.printStackTrace(System.out); + } + } + + private void dprint(String msg) + { + ORBUtility.dprint("Server", msg); + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/FolbTest.java b/test/src/share/classes/corba/folb/FolbTest.java new file mode 100644 index 000000000..92bbed033 --- /dev/null +++ b/test/src/share/classes/corba/folb/FolbTest.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 10 (Fri) 10:04:09 by Harold Carr. +// Last Modified : 2005 Sep 30 (Fri) 15:38:24 by Harold Carr. +// + +package corba.folb; + +import java.util.Properties; + +import corba.framework.CORBATest; +import corba.framework.Controller; +import corba.framework.Options; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +/** + * @author Harold Carr + */ +public class FolbTest + extends + CORBATest +{ + protected void doTest() + throws Exception + { + String thisPackage = FolbTest.class.getPackage().getName(); + + Controller orbd = createORBD(); + Controller server; + Controller client; + + orbd.start(); + + // + // Main test + // + + server = createServer(thisPackage+"."+"Server", "Server"); + client = createClient(thisPackage+"."+"Client", "Client"); + + server.start(); + client.start(); + + client.waitFor(180000); + + client.stop(); + server.stop(); + + /** TODO: Issue # GLASSFISH_CORBA-7. Fix and Uncomment following failing tests. + // + // ClientMulti test + // + + server = createServer(thisPackage+"."+"Server", "ServerMulti"); + client = createClient(thisPackage+"."+"ClientMulti", "ClientMulti"); + server.start(); + client.start(); + + client.waitFor(300000); // 5 minutes + + client.stop(); + server.stop(); + + // + // ClientCircular test + // + + server = createServer(thisPackage+"."+"Server", "ServerCircular"); + client = createClient(thisPackage+"."+"ClientCircular", "ClientCircular"); + server.start(); + client.start(); + + client.waitFor(180000); + + client.stop(); + server.stop(); + + // + // ClientWaitTimeout test + // + + server = createServer(thisPackage+"."+"Server", "ServerWaitTimeout"); + client = createClient(thisPackage+"."+"ClientWaitTimeout", "ClientWaitTimeout"); + server.start(); + client.start(); + + client.waitFor(120000); + * + * End Issue # GLASSFISH_CORBA-7. + **/ + client.stop(); + server.stop(); + + // + // Cleanup + // + + orbd.stop(); + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/GroupInfoServiceImpl.java b/test/src/share/classes/corba/folb/GroupInfoServiceImpl.java new file mode 100644 index 000000000..cf07147d3 --- /dev/null +++ b/test/src/share/classes/corba/folb/GroupInfoServiceImpl.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 13 (Mon) 11:04:09 by Harold Carr. +// Last Modified : 2005 Sep 26 (Mon) 22:39:12 by Harold Carr. +// + +package corba.folb; + +import java.net.InetAddress ; +import java.net.UnknownHostException; +import java.util.LinkedList; +import java.util.List; + +import com.sun.corba.ee.spi.folb.ClusterInstanceInfo; +import com.sun.corba.ee.spi.folb.GroupInfoService; +import com.sun.corba.ee.impl.folb.GroupInfoServiceBase; +import com.sun.corba.ee.spi.folb.GroupInfoServiceObserver; +import com.sun.corba.ee.spi.folb.SocketInfo; + +import com.sun.corba.ee.impl.misc.ORBUtility; +import java.util.ArrayList; + +/** + * @author Harold Carr + */ +public class GroupInfoServiceImpl + extends org.omg.CORBA.LocalObject + implements GroupInfoService +{ + private List currentInstances; + private GIS gis; + private boolean debug = true; // REVISIT - get from ORB + + private class GIS extends GroupInfoServiceBase + { + public List internalClusterInstanceInfo( + List endpoints ) { + throw new RuntimeException( "Should not be called" ) ; + } + + @Override + public List getClusterInstanceInfo( + String[] adapterName, List endpoints ) + { + return getClusterInstanceInfo( adapterName ) ; + } + + @Override + public List getClusterInstanceInfo( + String[] adapterName) + { + String adapter_name = ORBUtility.formatStringArray(adapterName); + + try { + if (debug) dprint(".getMemberAddresses->: " + adapter_name); + if (debug) dprint(".getMemberAddresses: " + adapter_name + + ": current members: " + currentInstances); + + List info = + new LinkedList(); + ClusterInstanceInfo instanceInfo; + + + String hostName = ""; + try { + hostName = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + dprint(".getMemberAddresses: " + adapter_name + + ": exception: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + + for (int i=0; i socketInfos = new ArrayList() ; + socketInfos.add( siBad ) ; + socketInfos.add( si ) ; + instanceInfo = + new ClusterInstanceInfo("instance-" + i, i + 1, + socketInfos); + info.add(instanceInfo); + + // + // REVISIT: this is not used in testing - remove + // + // Only add one good address in test ReferenceFactory. + // + + if (isNoLabelName(adapterName)) { + if (debug) dprint(".getMemberAddresses: " + adapter_name + + ": no label ReferenceFactory - only added one good address"); + break; + } + } + + return info; + + } catch (RuntimeException e) { + dprint(".getMemberAddresses: " + adapter_name + + ": exception: " + e); + e.printStackTrace(System.out); + System.exit(1); + throw e; + } finally { + if (debug) dprint(".getMemberAddresses<-: " + adapter_name); + } + } + + @Override + public boolean shouldAddAddressesToNonReferenceFactory( + String[] adapterName) + { + return Common.POA_WITH_ADDRESSES_WITH_LABEL.equals( + adapterName[adapterName.length-1]); + } + + @Override + public boolean shouldAddMembershipLabel (String[] adapterName) + { + return ! isNoLabelName(adapterName); + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + private boolean isNoLabelName(String[] adapterName) + { + return Common.RFM_WITH_ADDRESSES_WITHOUT_LABEL.equals( + adapterName[adapterName.length-1]); + } + } + + public GroupInfoServiceImpl() + { + gis = new GIS(); + currentInstances = new LinkedList(); + for (int i = 0; i < corba.folb_8_1.Common.socketTypes.length; ++i){ + currentInstances.add(corba.folb_8_1.Common.socketTypes[i]); + } + } + + //////////////////////////////////////////////////// + // + // GroupInfoService + // + + public boolean addObserver(GroupInfoServiceObserver x) + { + return gis.addObserver(x); + } + + public void notifyObservers() + { + gis.notifyObservers(); + } + + @Override + public List getClusterInstanceInfo( + String[] adapterName, List endpoints ) + { + return gis.getClusterInstanceInfo(adapterName,endpoints); + } + + public List getClusterInstanceInfo( + String[] adapterName) + { + return gis.getClusterInstanceInfo(adapterName); + } + + public boolean shouldAddAddressesToNonReferenceFactory( + String[] adapterName) + { + return gis.shouldAddAddressesToNonReferenceFactory(adapterName); + } + + public boolean shouldAddMembershipLabel (String[] adapterName) + { + return gis.shouldAddMembershipLabel(adapterName); + } + + //////////////////////////////////////////////////// + // + // Implementation used by GroupInfoServiceTestServant + // + + public boolean add(String x) + { + if (debug) dprint(".add->: " + x); + if (debug) dprint(".add: current members before: " + currentInstances); + boolean result = currentInstances.add(x); + if (debug) dprint(".add: current members after : " + currentInstances); + notifyObservers(); + if (debug) dprint(".add<-: " + x + " " + result); + return result; + } + + + public boolean remove(String x) + { + if (debug) dprint(".remove->: " + x); + if (debug) dprint(".remove: current members before: " + currentInstances); + boolean result = currentInstances.remove(x); + if (debug) dprint(".remove: current members after : " + currentInstances); + notifyObservers(); + if (debug) dprint(".remove<-: " + x + " " + result); + return result; + } + + private static void dprint(String msg) + { + ORBUtility.dprint("GroupInfoServiceImpl", msg); + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/GroupInfoServiceTest.java b/test/src/share/classes/corba/folb/GroupInfoServiceTest.java new file mode 100644 index 000000000..8d518d766 --- /dev/null +++ b/test/src/share/classes/corba/folb/GroupInfoServiceTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 13 (Mon) 11:04:09 by Harold Carr. +// Last Modified : 2005 Sep 23 (Fri) 12:11:36 by Harold Carr. +// + +package corba.folb; + +import java.util.List; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +/** + * @author Harold Carr + */ +public interface GroupInfoServiceTest + extends Remote +{ + public boolean addInstance(String x) + throws RemoteException; + + public boolean removeInstance(String x) + throws RemoteException; + + public boolean addAcceptor(String x) + throws RemoteException; + + public boolean removeAcceptorAndConnections(String x) + throws RemoteException; + + public void doThreadDump() + throws RemoteException; +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/GroupInfoServiceTestServant.java b/test/src/share/classes/corba/folb/GroupInfoServiceTestServant.java new file mode 100644 index 000000000..fd1d5b303 --- /dev/null +++ b/test/src/share/classes/corba/folb/GroupInfoServiceTestServant.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 13 (Mon) 11:04:09 by Harold Carr. +// Last Modified : 2005 Sep 23 (Fri) 13:17:38 by Harold Carr. +// + +package corba.folb; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.misc.ORBUtility; + +import corba.hcks.U; + +/** + * @author Harold Carr + */ +public class GroupInfoServiceTestServant + extends PortableRemoteObject + implements GroupInfoServiceTest +{ + private ORB orb; + private GroupInfoServiceImpl gis; + + public GroupInfoServiceTestServant(ORB orb, GroupInfoServiceImpl gis) + throws RemoteException + { + this.orb = orb; + this.gis = gis; + } + + public boolean addInstance(final String x) + throws RemoteException + { + dprint(".add->: " + x); + // Must be done on a different thread so requests can drain. + new Thread() { + public void run() + { + gis.add(x); + } + }.start(); + dprint(".add<-: " + x); + return true; + } + + public boolean removeInstance(final String x) + throws RemoteException + { + dprint(".remove->: " + x); + // Must be done on a different thread so requests can drain. + new Thread() { + public void run() + { + gis.remove(x); + } + }.start(); + dprint(".remove<-: " + x); + return true; + } + + public boolean addAcceptor(String x) + throws RemoteException + { + dprint(".add->: " + x); + boolean result = + U.registerAcceptor( + x, + ((Integer)corba.folb_8_1.Common.socketTypeToPort.get(x)).intValue(), + orb); + dprint(".add<-: " + x + " " + result); + return result; + } + + public boolean removeAcceptorAndConnections(String x) + throws RemoteException + { + dprint(".remove->: " + x); + boolean result = U.unregisterAcceptorAndCloseConnections(x, orb); + dprint(".remove<-: " + x + " " + result); + return result; + } + + public void doThreadDump() + throws RemoteException + { + try { + dprint(".doThreadDump->:\n"); + StringBuffer buf = new StringBuffer(); + for (Map.Entry entry : + Thread.getAllStackTraces().entrySet()) + { + buf.append("\n"); + buf.append(entry.getKey().toString() + "\n"); + for (StackTraceElement element : entry.getValue()) { + buf.append(element.toString() + "\n"); + } + } + dprint(".doThreadDump: " + buf); + } finally { + dprint(".doThreadDump<-:"); + } + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + private static void dprint(String msg) + { + ORBUtility.dprint("GroupInfoServiceTestServant", msg); + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/README-AS.txt b/test/src/share/classes/corba/folb/README-AS.txt new file mode 100644 index 000000000..dd8d111f2 --- /dev/null +++ b/test/src/share/classes/corba/folb/README-AS.txt @@ -0,0 +1,50 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +This file shows how IIOP FOLB is configured in AS. +It is slightly complicated by the late requirement of support for +static clusters (ala 8.1 EE) is GMS is disabled. + +------------------------------------------------------------------------------ +DYNAMIC and STATIC: + + IIOPSSLSocketFactory (via ORBData) + ReferenceFactoryManager (via RIR) + CSIv2SSLTaggedComponentHandler (via RIR) + ClientGroupManager (via ORBConfigurator) + ClientRequestInterceptor, (via ORBInitializer) + IIOPPrimaryToContactInfo, (via ORBData) + IORToSocketInfo (via ORBData) + (uses CSIv2SSLTaggedComponentHandler.extract) + Offers FOLB_CLIENT_GROUP_INFO_SERVICE (via RIR) + S1ASSerialContextFactory (via Property) + Registers with FOLB_CLIENT_GROUP_INFO_SERVICE (via RIR) + +------------------------------------------------------------------------------ +DYNAMIC: + + com.sun.enterprise.ee.ejb.iiop.IiopFolbGmsClient (via RIR) + Registers with GMS + Offers FOLB_SERVER_GROUP_INFO_SERVICE (via RIR) + ServerGroupManager (via ORBConfigurator) + IORInterceptor (via ORBInitializer) + (uses CSIv2SSLTaggedComponentHandler.insert) + ServerRequestInterceptor (via ORBInitializer) + Registers with FOLB_SERVER_GROUP_INFO_SERVICE (via RIR) + TxSecIORInterceptor - disable adding CSIv2 addresses. + (via ORBInitializer) + +------------------------------------------------------------------------------ +STATIC: + + FailoverIORInterceptor (via Property)-adds failover addresses (from ADMIN). + TxSecIORInterceptor (via ORBInitializer) - adds CSIv2 addresses. + +;;; End of file. diff --git a/test/src/share/classes/corba/folb/README.txt b/test/src/share/classes/corba/folb/README.txt new file mode 100644 index 000000000..305419735 --- /dev/null +++ b/test/src/share/classes/corba/folb/README.txt @@ -0,0 +1,132 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +------------------------------------------------------------------------------ +General Interaction: + +client server + + + +A general call to see IORUpdates and failover: + + (RFM with and without components) +--- echo --+ +-------------------------------------------+ +---> Test + | | | | + | | | | + v | | v + ClientGroupManager | ServerRequestInt + IORToSocketInfo | send_reply + (get addresses from IOR) | check mem label + IIOPrimaryToContactInfo | maybe IORUpdate + (.hasNext/.next - FailoverCache) | | + ClientRequestInterceptor | | + (send membership label | | + and handle IORUpdate) + ServerGroupManager + + | ^ | + | | | + register notify getInfo + | | | + | | | + | | | + | | | +Adding and removing "instances" to test IORUpdates: v | v + +--- add/remove ------> GISTest/(POA) --- add/remove --> GISImpl + + + +Adding and removing acceptors/connections to cause failover: + +--- add/remove ------> Test/(POA) + +------------------------------------------------------------------------------ +Tests: + +Bootstrap: + Missing membership label + Therefore IORUpdate + +Normal operation: + Send label + No IORUpdate + +IORUpdate only: + Setup: kill "instance" + Execute: + Invoke + IORUpdate + +Failover without update: + Setup: kill listener/connections. + Execute: + Invoke + Cannot connect to address + Therefore try next address + No IORUpdate since GIS not aware of "failure" + +Failover with update: + Setup: kill "instance" + Then setup/execute above: Failover with update. + IORUpdate + +Independent POAs: + Ensure no address tag or membership labels added to POAs. + Ensure no restarted by RFM. + +"Circular" failover success: + Setup: kill listener/connections and invoke to get in middle of list. + kill listener/connections in remainder of list. + restart listener/connections before middle of list. + Execute: + Invoke + Ensure .hasNext/.next "mod" to beginning of list + on a single request + +"Circular" failover fail: + Same as above but do not restart. + Ensure failure returned to client when get back to + middle starting point in list. + +------------------------------------------------------------------------------ +Server-side configuration: + +Server.setProperties: + Sets persistent server port. + Sets user-defined listen ports. W, X, Y, Z. + Registers ORBConfigurator for the ServerGroupManager. + addORBInitializer + add_ior_interceptor + add_server_request_interceptor + Registers ORBConfigurator for test. + register_initial_reference of fake GIS for test. + register_initial_reference of real ReferenceFactoryManager + +Server.main: + ORB.init executes configurators. + + Create a ReferenceFactory for the test. + Create (using above RF) and bind reference for the test. + + Create a "special" ReferenceFactory that does not add components. + Create (using special RF) and bind a reference for the test. + + Create and bind an object managed by an independent POA. + (This object also controls fake GIS.) + +ServerGroupManager.initialize + updateMembershipLabel - first time. + Get RFM and GIS from initial references + Register with GIS for change notifications. + + +// End of file. diff --git a/test/src/share/classes/corba/folb/Server.java b/test/src/share/classes/corba/folb/Server.java new file mode 100644 index 000000000..54a28c38c --- /dev/null +++ b/test/src/share/classes/corba/folb/Server.java @@ -0,0 +1,360 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2005 Jun 09 (Thu) 14:44:09 by Harold Carr. +// Last Modified : 2005 Sep 23 (Fri) 15:03:10 by Harold Carr. +// + +package corba.folb; + +import java.rmi.RemoteException; +import java.util.Properties; + +import org.omg.CORBA.LocalObject ; +import org.omg.CORBA.ORBPackage.InvalidName; + +import org.omg.PortableServer.ForwardRequest ; +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantLocator ; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; + +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager; +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory; +import com.sun.corba.ee.spi.orb.ORBConfigurator ; +import com.sun.corba.ee.spi.orb.DataCollector ; +import com.sun.corba.ee.spi.orb.ORB; + +import com.sun.corba.ee.impl.folb.ServerGroupManager; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.impl.misc.ORBUtility; + +import corba.framework.Options; +import corba.hcks.U; + +/** + * @author Harold Carr + */ +public class Server + implements + ORBConfigurator +{ + static { + // This is needed to guarantee that this test will ALWAYS use dynamic + // RMI-IIOP. Currently the default is dynamic when renamed to "ee", + // but static in the default "se" packaging, and this test will + // fail without dynamic RMI-IIOP. + System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ; + } + + private static final String baseMsg = Server.class.getName(); + + public static void setProperties(Properties props) + { + // + // Debugging flags. + // + + props.setProperty(ORBConstants.DEBUG_PROPERTY, + //"giop,transport,subcontract,poa" + "transport" + ); + + + // + // Must set server id and persistent port for + // persistent POAs (e.g., ReferenceFactory) + // + + // 300 is arbitrary; + props.setProperty(ORBConstants.ORB_SERVER_ID_PROPERTY, "300"); + // 4567 is arbitrary; + props.setProperty(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + new Integer(4567).toString()); + + // + // Tell the ORB to listen on user-define ports + // + + String listenPorts = corba.folb_8_1.Server.formatListenPorts(); + props.setProperty(ORBConstants.LISTEN_SOCKET_PROPERTY, listenPorts); + U.sop("Listen ports: " + listenPorts); + + + // + // Register the socket factory that knows how to create + // Sockets of types used by test. + // + + props.setProperty(ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + corba.folb_8_1.SocketFactoryImpl.class.getName()); + + + // + // This registers the IIOPGroupAgent into the system + // which then registers itself as an ORBInitializer + // to then register itself as IOR and ServerRequest Interceptors. + // + + props.setProperty(ORBConstants.USER_CONFIGURATOR_PREFIX + + ServerGroupManager.class.getName(), + "dummy"); + + // + // This configurator registers the "fake" GIS + // + + props.setProperty(ORBConstants.USER_CONFIGURATOR_PREFIX + + Server.class.getName(), + "dummy"); + + + // + // Make ReferenceFactoryManager available + // + + props.setProperty(ORBConstants.RFM_PROPERTY,"dummy"); + + + // + // This configurator registers the CSIv2SSLTaggedComponentHandler + // + + props.setProperty(ORBConstants.USER_CONFIGURATOR_PREFIX + + CSIv2SSLTaggedComponentHandlerImpl.class.getName(), + "dummy"); + } + + public static void main(String[] av) + { + try { + + Properties props = new Properties(); + setProperties(props); + + dprint("--------------------------------------------------"); + dprint("ORB.init"); + dprint("--------------------------------------------------"); + ORB orb = (ORB) ORB.init(av, props); + + + dprint("--------------------------------------------------"); + dprint("resolve ReferenceFactoryManager"); + dprint("--------------------------------------------------"); + ReferenceFactoryManager rfm = (ReferenceFactoryManager) + orb.resolve_initial_references( + ORBConstants.REFERENCE_FACTORY_MANAGER); + + dprint("--------------------------------------------------"); + dprint("activate ReferenceFactoryManager"); + dprint("--------------------------------------------------"); + rfm.activate(); + + // + // repo id, object id and locator managed by ReferenceFactory. + // + + Servant s = (Servant) javax.rmi.CORBA.Util.getTie(new EchoTestServant(orb)); + String repositoryId = s._all_interfaces(null, null)[0]; + // objectId is used to make a reference but it is + // never used in the dispatch. + byte[] objectId = "DUMMY".getBytes(); + ServantLocator servantLocator = new TestServantLocator(orb); + + // + // The ReferenceFactory and Object reference for the test. + // + + ReferenceFactory rf; + org.omg.CORBA.Object ref; + + dprint("--------------------------------------------------"); + dprint("create ReferenceFactory: " + Common.RFM_WITH_ADDRESSES_WITH_LABEL); + dprint("--------------------------------------------------"); + rf = rfm.create(Common.RFM_WITH_ADDRESSES_WITH_LABEL, + repositoryId, null, servantLocator); + + dprint("--------------------------------------------------"); + dprint("createReference: " + rf); + dprint("--------------------------------------------------"); + ref = rf.createReference(objectId); + + dprint("--------------------------------------------------"); + dprint("bind reference: " + + Common.TEST_RFM_WITH_ADDRESSES_WITH_LABEL); + dprint("--------------------------------------------------"); + U.rebind(Common.RFM_WITH_ADDRESSES_WITH_LABEL, ref, orb); + + // + // A ReferenceFactory with a name that causes + // establish_components to not add label. + // This is so we can create a reference missing the + // membership label. When we see the call come in with the + // missing label we send an IOR UPDATE. + // + + dprint("--------------------------------------------------"); + dprint("create ReferenceFactory: " + + Common.RFM_WITH_ADDRESSES_WITHOUT_LABEL); + dprint("--------------------------------------------------"); + rf = rfm.create(Common.RFM_WITH_ADDRESSES_WITHOUT_LABEL, + repositoryId, null, servantLocator); + + dprint("--------------------------------------------------"); + dprint("createReference: " + rf); + dprint("--------------------------------------------------"); + ref = rf.createReference(objectId); + + dprint("--------------------------------------------------"); + dprint("bind reference: " + + Common.TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL); + U.rebind(Common.TEST_RFM_WITH_ADDRESSES_WITHOUT_LABEL, ref, orb); + dprint("--------------------------------------------------"); + + // + // An object managed by an independent POA. + // This object is also used to control GIS. + // + + GroupInfoServiceImpl gis = (GroupInfoServiceImpl) + orb.resolve_initial_references( + ORBConstants.FOLB_SERVER_GROUP_INFO_SERVICE); + + dprint("--------------------------------------------------"); + dprint("getRootPOA"); + dprint("--------------------------------------------------"); + POA rootPOA = U.getRootPOA(orb); + rootPOA.the_POAManager().activate(); + + Servant servant = (Servant) + javax.rmi.CORBA.Util.getTie( + new GroupInfoServiceTestServant(orb, gis)); + + dprint("--------------------------------------------------"); + dprint("createWithServantAndBind: " + + Common.GIS_POA_WITHOUT_ADDRESSES_WITHOUT_LABEL); + dprint("--------------------------------------------------"); + U.createWithServantAndBind(Common.GIS_POA_WITHOUT_ADDRESSES_WITHOUT_LABEL, + servant, rootPOA, orb); + + + dprint("--------------------------------------------------"); + dprint("createPOA: " + + Common.GIS_POA_WITH_ADDRESSES_WITH_LABEL); + dprint("--------------------------------------------------"); + + POA poaWithTags = + rootPOA.create_POA(Common.POA_WITH_ADDRESSES_WITH_LABEL, + null, null); + poaWithTags.the_POAManager().activate(); + + + dprint("--------------------------------------------------"); + dprint("createWithServantAndBind: " + + Common.GIS_POA_WITH_ADDRESSES_WITH_LABEL); + dprint("--------------------------------------------------"); + U.createWithServantAndBind(Common.GIS_POA_WITH_ADDRESSES_WITH_LABEL, + servant, poaWithTags, orb); + + // + // Server ready. + // + + dprint("--------------------------------------------------"); + System.out.println(Options.defServerHandshake); + dprint("--------------------------------------------------"); + + orb.run(); + + // REVISIT - move ServerGroupManager configurator here from test. + + } catch (Exception e) { + e.printStackTrace(System.out); + } + } + + //////////////////////////////////////////////////// + // + // ORBConfigurator + // + + public void configure(DataCollector collector, ORB orb) + { + dprint(".configure->:"); + + try { + + // + // Make Test GroupInfoService available + // + + orb.register_initial_reference( + ORBConstants.FOLB_SERVER_GROUP_INFO_SERVICE, + new GroupInfoServiceImpl()); + + } catch (InvalidName e) { + // REVISIT + e.printStackTrace(System.out); + } + dprint(".configure<-:"); + } + + //////////////////////////////////////////////////// + // + // Servantlocator + // + + private static class TestServantLocator + extends LocalObject + implements ServantLocator + { + ORB orb; + + public TestServantLocator(ORB orb) + { + this.orb = orb; + } + + public synchronized void deactivate() + { + } + + public synchronized Servant preinvoke( + byte[] oid, POA adapter, String operation, CookieHolder the_cookie) + throws ForwardRequest + { + try { + return (Servant) javax.rmi.CORBA.Util.getTie(new EchoTestServant(orb)); + } catch (RemoteException e) { + e.printStackTrace(System.out); + } + return null; + } + + public void postinvoke( + byte[] oid, POA adapter, String operation, Object the_cookie, + Servant the_servant) + { + } + } + + //////////////////////////////////////////////////// + // + // Implementation + // + + private static void dprint(String msg) + { + ORBUtility.dprint("Server", msg); + } +} + +// End of file. diff --git a/test/src/share/classes/corba/folb/TODO.txt b/test/src/share/classes/corba/folb/TODO.txt new file mode 100644 index 000000000..19f8f4e7a --- /dev/null +++ b/test/src/share/classes/corba/folb/TODO.txt @@ -0,0 +1,20 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Test: + +Add TAG COMPONENT: primary name + +make a missing label request +make a circular failover request +make a planned shutdown request +make a crash request + + diff --git a/test/src/share/classes/corba/fragment/BadArrayException.java b/test/src/share/classes/corba/fragment/BadArrayException.java new file mode 100644 index 000000000..4bd98927e --- /dev/null +++ b/test/src/share/classes/corba/fragment/BadArrayException.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment; + +public class BadArrayException extends java.lang.Exception +{ + public BadArrayException() {} + public BadArrayException(String msg) { + super(msg); + } +} diff --git a/test/src/share/classes/corba/fragment/Client.java b/test/src/share/classes/corba/fragment/Client.java new file mode 100644 index 000000000..a7d1e35cf --- /dev/null +++ b/test/src/share/classes/corba/fragment/Client.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment; + +import javax.rmi.PortableRemoteObject; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.* ; +import java.rmi.RemoteException; +import java.io.*; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +public class Client +{ + // size must be divisible by four + public static void testByteArray(FragmentTester tester, int size) + throws RemoteException, BadArrayException + { + System.out.println("Sending array of length " + size); + + byte array[] = new byte[size]; + + int i = 0; + + do { + + for (byte x = 0; x < 4; x++) { + System.out.print("" + x + " "); + array[i++] = x; + } + // System.out.println(); + + } while (i < size); + + byte result[] = tester.verifyTransmission(array); + + if (result == null) + throw new BadArrayException("result was null!"); + + if (array.length != result.length) + throw new BadArrayException("result length incorrect: " + result.length); + + for (i = 0; i < array.length; i++) + if (array[i] != result[i]) + throw new BadArrayException("result mismatch at index: " + i); + + System.out.println("testByteArray completed normally"); + } + + public static org.omg.CORBA.Object readObjref(String file, org.omg.CORBA.ORB orb) { + String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file; + try { + java.io.DataInputStream in = + new java.io.DataInputStream(new FileInputStream(fil)); + String ior = in.readLine(); + System.out.println("IOR: "+ior); + return orb.string_to_object(ior); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + return null; + } + + public static void main(String args[]) + { + try{ + + ORB orb = ORB.init(args, System.getProperties()); + + com.sun.corba.ee.spi.orb.ORB ourORB + = (com.sun.corba.ee.spi.orb.ORB)orb; + + System.out.println("==== Client GIOP version " + + ourORB.getORBData().getGIOPVersion() + + " with strategy " + + ourORB.getORBData().getGIOPBuffMgrStrategy( + ourORB.getORBData().getGIOPVersion()) + + "===="); + + /* + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + NameComponent nc = new NameComponent("FragmentTester", ""); + NameComponent path[] = {nc}; + + org.omg.CORBA.Object obj = ncRef.resolve(path); + */ + + org.omg.CORBA.Object obj = readObjref("IOR", orb); + + FragmentTester tester = + (FragmentTester) PortableRemoteObject.narrow(obj, + FragmentTester.class); + + // Do the crazy work here + + int arrayLen = Integer.parseInt(System.getProperty("array.length")); + + testByteArray(tester, arrayLen); + + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } +} diff --git a/test/src/share/classes/corba/fragment/FragmentTest.java b/test/src/share/classes/corba/fragment/FragmentTest.java new file mode 100644 index 000000000..dd8ee6b31 --- /dev/null +++ b/test/src/share/classes/corba/fragment/FragmentTest.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class FragmentTest extends CORBATest { + static final int GROW = 0; + static final int COLLECT = 1; + static final int STREAM = 2; + static String[] GIOP_version = { "1.0", "1.1", "1.2" }; + static String[] GIOP_strategy = { "GROW", "CLCT", "STRM" }; + + private void printBeginTest(int clientVersion, + int clientStrategy, + int serverVersion, + int serverStrategy) + { + StringBuffer output = new StringBuffer(80); + + // Pleasing aesthetics + output.append(" "); + + output.append(GIOP_version[clientVersion]); + output.append(" "); + output.append(GIOP_strategy[clientStrategy]); + output.append(" client <> "); + output.append(GIOP_version[serverVersion]); + output.append(" "); + output.append(GIOP_strategy[serverStrategy]); + output.append(" server: "); + + System.out.print(output.toString()); + } + + private String testName(int clientVersion, int clientStrategy, int + serverVersion, int serverStrategy) { + + StringBuffer output = new StringBuffer(80); + + output.append(GIOP_version[clientVersion]); + output.append("_"); + output.append(GIOP_strategy[clientStrategy]); + output.append("_client_to_"); + output.append(GIOP_version[serverVersion]); + output.append("_"); + output.append(GIOP_strategy[serverStrategy]); + output.append("_server"); + + return output.toString() ; + } + + private void printEndTest(String result) + { + System.out.println(result); + } + + protected void doTest() throws Throwable + { + int errors = 0; + int fragmentSize = 1024; + + // Pleasing aesthetics + System.out.println(); + + for (int client_strategy = GROW, i = 0; i < GIOP_version.length; i++) { + + Properties clientProps = Options.getClientProperties(); + + clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize); + clientProps.put("array.length", "" + (fragmentSize * 2)); + clientProps.put(ORBConstants.GIOP_VERSION, GIOP_version[i]); + clientProps.put(ORBConstants.GIOP_11_BUFFMGR, "" + client_strategy); + clientProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + client_strategy); + + for (int server_strategy = GROW, j = 0; j < GIOP_version.length; j++) { + + errors = runTest(errors, client_strategy, i, server_strategy, j); + + if (GIOP_version[j].equals("1.1") && server_strategy == GROW) { + server_strategy = STREAM; j--; + } else if (GIOP_version[j].equals("1.2") && server_strategy == STREAM) { + server_strategy = GROW; j--; + } + } + + if (GIOP_version[i].equals("1.1") && client_strategy == GROW) { + client_strategy = COLLECT; i--; + } else if (GIOP_version[i].equals("1.2") && client_strategy == COLLECT) { + client_strategy = STREAM; i--; + } else if (GIOP_version[i].equals("1.2") && client_strategy == STREAM) { + client_strategy = GROW; i--; + } + } + + System.out.print(" Test result : " ); + + if (errors > 0) + throw new Exception("Errors detected"); + } + + private int runTest(int errors, int client_strategy, int client_version, int server_strategy, int server_version) throws Exception { + // skip non-longer support COLLECT strategy tests + if (client_strategy == COLLECT || server_strategy == COLLECT) return errors; + + printBeginTest(client_version, client_strategy, server_version, server_strategy); + String name = testName(client_version, client_strategy, server_version, server_strategy); + + Properties serverProps = Options.getServerProperties(); + serverProps.put(ORBConstants.GIOP_VERSION, GIOP_version[client_version]); + serverProps.put(ORBConstants.GIOP_11_BUFFMGR, "" + server_strategy); + serverProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + server_strategy); + + Controller server = createServer("corba.fragment.Server", name ); + Controller client = createClient("corba.fragment.Client", name ); + + server.start(); + client.start(); + + client.waitFor(60000); + + if (client.exitValue() != Controller.SUCCESS) { + errors++; + printEndTest("FAILED, Client exit value = " + client.exitValue()); + } else + if (server.finished()) { + errors++; + printEndTest("FAILED, Server crashed"); + } else { + printEndTest("PASSED"); + } + + client.stop(); + server.stop(); + return errors; + } +} + diff --git a/test/src/share/classes/corba/fragment/FragmentTester.java b/test/src/share/classes/corba/fragment/FragmentTester.java new file mode 100644 index 000000000..2e68738e1 --- /dev/null +++ b/test/src/share/classes/corba/fragment/FragmentTester.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface FragmentTester extends java.rmi.Remote +{ + public byte[] verifyTransmission(byte array[]) + throws RemoteException, BadArrayException; +} diff --git a/test/src/share/classes/corba/fragment/FragmentTesterImpl.java b/test/src/share/classes/corba/fragment/FragmentTesterImpl.java new file mode 100644 index 000000000..b69e6fe3c --- /dev/null +++ b/test/src/share/classes/corba/fragment/FragmentTesterImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment; + +import java.rmi.RemoteException ; +import javax.rmi.PortableRemoteObject; + +public class FragmentTesterImpl extends PortableRemoteObject implements FragmentTester +{ + public FragmentTesterImpl() throws RemoteException + { + super(); + } + + public byte[] verifyTransmission(byte array[]) throws BadArrayException + { + if (array == null) + throw new BadArrayException("Array is null"); + + if (array.length % 4 != 0) + throw new BadArrayException("Invalid array length: " + array.length); + + System.out.println("Array length = " + array.length); + + int i = 0; + + do { + + System.out.println("" + i + ": "); + + for (int check = 0; check < 4; check++) { + + System.out.print("" + array[i] + " "); + + if (array[i++] != check) { + throw new BadArrayException("Bad array at index " + i + + " value: " + array[i]); + } + } + + System.out.println(); + + + } while (i < array.length); + + return array; + } +} diff --git a/test/src/share/classes/corba/fragment/Server.java b/test/src/share/classes/corba/fragment/Server.java new file mode 100644 index 000000000..f5b5fd522 --- /dev/null +++ b/test/src/share/classes/corba/fragment/Server.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment; + +import org.omg.CORBA.portable.*; +import javax.rmi.PortableRemoteObject; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; +import java.util.Properties; +import org.omg.PortableServer.*; +import java.io.*; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + +public class Server +{ + public static void writeObjref(org.omg.CORBA.Object ref, String file, org.omg.CORBA.ORB orb) { + String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file; + try { + java.io.DataOutputStream out = new + java.io.DataOutputStream(new FileOutputStream(fil)); + out.writeBytes(orb.object_to_string(ref)); + } catch (java.io.IOException e) { + System.err.println("Unable to open file "+fil); + System.exit(1); + } + } + + public static void main(String args[]) + { + try { + + ORB orb = ORB.init(args, System.getProperties()); + + com.sun.corba.ee.spi.orb.ORB ourORB + = (com.sun.corba.ee.spi.orb.ORB)orb; + + System.out.println("==== Server GIOP version " + + ourORB.getORBData().getGIOPVersion() + + " with strategy " + + ourORB.getORBData().getGIOPBuffMgrStrategy( + ourORB.getORBData().getGIOPVersion()) + + "===="); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + FragmentTesterImpl impl = new FragmentTesterImpl(); + javax.rmi.CORBA.Tie tie = javax.rmi.CORBA.Util.getTie( impl ) ; + + byte[] id = rootPOA.activate_object( + (org.omg.PortableServer.Servant)tie ) ; + org.omg.CORBA.Object obj = rootPOA.id_to_reference( id ) ; + + /* + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("FragmentTester", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + */ + + writeObjref(obj, "IOR", orb); + + // Emit the handshake the test framework expects + // (can be changed in Options by the running test) + System.out.println ("Server is ready."); + + // Wait for clients + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + + // Make sure to exit with a value greater than 0 on + // error. + System.exit(1); + } + } +} diff --git a/test/src/share/classes/corba/fragment2/BadArrayException.java b/test/src/share/classes/corba/fragment2/BadArrayException.java new file mode 100644 index 000000000..bad4f3b7c --- /dev/null +++ b/test/src/share/classes/corba/fragment2/BadArrayException.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment2; + +public class BadArrayException extends java.lang.Exception +{ + public BadArrayException() {} + public BadArrayException(String msg) { + super(msg); + } +} diff --git a/test/src/share/classes/corba/fragment2/Client.java b/test/src/share/classes/corba/fragment2/Client.java new file mode 100644 index 000000000..086474286 --- /dev/null +++ b/test/src/share/classes/corba/fragment2/Client.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.fragment2; + +import javax.rmi.PortableRemoteObject; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.* ; +import java.rmi.RemoteException; +import java.io.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +class Tester extends Thread{ + FragmentTester tester; + int size; + static int totalThread = 0; + int threadID; + + public Tester(FragmentTester f, int s){ + tester = f; + size = s; + threadID = totalThread; + totalThread++; + } + + public void run() + { + System.out.println("Sending array of length " + size); + + byte array[] = new byte[size]; + + int i = 0; + + do { + + for (byte x = 0; x < 4; x++) { + System.out.print("" + x + " "); + array[i++] = x; + } + // System.out.println(); + + } while (i < size); + + try{ + tester.verifyTransmission(array); + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + + System.out.println("testByteArray "+"ID:"+threadID+" completed normally"); + } +} + + +class TestCatagory{ + public String giopVersion; + public int fragmentSize; + public int arrayLength; + public int threadNumber; +} + + +public class Client +{ + + + static TestCatagory testCatagory[]; + static int catagoryNumber; + + public static void setTest(){ + int data[] = { 2,1024,1024,5, + 2,2048,2048,5, + 2,2048,4096,5, + 1,1024,1024,5 + }; + + catagoryNumber = data.length / 4; + testCatagory = new TestCatagory[catagoryNumber]; + for(int i=0;i( "foo", "bar" ) ; + Object d2 = new SPair( "baz", new ThrowsSysEx() ) ; + Foo f1 = new Foo( "d1", d1, "d2", d2 ) ; + SPair result = new SPair( "f1", f1 ) ; + return result ; + } + + public Object testSimpleExceptionContext() throws RemoteException { + Object d1 = new SPair( "foo", "bar" ) ; + Object d2 = new SPair( "baz", new ThrowsSimpleSysEx() ) ; + Foo f1 = new Foo( "d1", d1, "d2", d2 ) ; + SPair result = new SPair( "f1", f1 ) ; + return result ; + } +} + +// End of file. diff --git a/test/src/share/classes/corba/ior/Client.java b/test/src/share/classes/corba/ior/Client.java new file mode 100644 index 000000000..769cc932d --- /dev/null +++ b/test/src/share/classes/corba/ior/Client.java @@ -0,0 +1,2168 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.ior; + +import java.io.PrintStream ; + +import java.util.Properties ; +import java.util.NoSuchElementException ; +import java.util.List ; +import java.util.LinkedList ; +import java.util.Iterator ; +import java.util.StringTokenizer ; +import java.util.ArrayList ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.IdAssignmentPolicyValue ; + +import org.omg.CORBA.Policy ; +import org.omg.CORBA.BAD_PARAM ; +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.OctetSeqHolder ; + +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +import org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS ; +import org.omg.IOP.TAG_CODE_SETS ; +import org.omg.IOP.TAG_JAVA_CODEBASE ; +import org.omg.IOP.TAG_ORB_TYPE ; +import org.omg.IOP.TAG_INTERNET_IOP ; + + +import com.sun.corba.ee.spi.ior.Identifiable ; +import com.sun.corba.ee.spi.ior.IdentifiableFactory ; +import com.sun.corba.ee.spi.ior.IdentifiableFactoryFinder ; +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate ; +import com.sun.corba.ee.spi.ior.TaggedComponent ; +import com.sun.corba.ee.spi.ior.TaggedComponentFactoryFinder ; +import com.sun.corba.ee.spi.ior.ObjectId ; +import com.sun.corba.ee.spi.ior.ObjectKey ; +import com.sun.corba.ee.spi.ior.IOR ; +import com.sun.corba.ee.spi.ior.IORFactory ; +import com.sun.corba.ee.spi.ior.ObjectAdapterId ; +import com.sun.corba.ee.spi.ior.IdentifiableContainerBase ; +import com.sun.corba.ee.spi.ior.IORTemplate ; +import com.sun.corba.ee.spi.ior.IORTemplateList ; +import com.sun.corba.ee.spi.ior.IORFactories ; +import com.sun.corba.ee.spi.ior.TaggedProfileTemplate ; + +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories ; +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate ; +import com.sun.corba.ee.spi.ior.iiop.IIOPProfile ; +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ; + +import com.sun.corba.ee.spi.activation.POANameHelper ; + +import com.sun.corba.ee.spi.extension.ZeroPortPolicy ; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.orb.ORBVersion ; +import com.sun.corba.ee.spi.orb.ORBVersionFactory ; + +import com.sun.corba.ee.spi.ior.iiop.AlternateIIOPAddressComponent ; +import com.sun.corba.ee.spi.ior.iiop.CodeSetsComponent ; +import com.sun.corba.ee.spi.ior.iiop.ORBTypeComponent ; +import com.sun.corba.ee.spi.ior.iiop.JavaCodebaseComponent ; + +import com.sun.corba.ee.impl.ior.GenericTaggedProfile ; +import com.sun.corba.ee.impl.ior.GenericTaggedComponent ; +import com.sun.corba.ee.impl.ior.FreezableList ; +import com.sun.corba.ee.impl.ior.OldJIDLObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.OldPOAObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.JIDLObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.POAObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.WireObjectKeyTemplate ; +import com.sun.corba.ee.impl.ior.EncapsulationUtility ; +import com.sun.corba.ee.impl.ior.TaggedComponentFactoryFinderImpl ; +import com.sun.corba.ee.impl.ior.TaggedProfileFactoryFinderImpl ; +import com.sun.corba.ee.impl.ior.ObjectAdapterIdArray ; +import com.sun.corba.ee.impl.ior.ObjectAdapterIdNumber ; +import com.sun.corba.ee.impl.ior.ObjectReferenceTemplateImpl ; +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl ; + +import com.sun.corba.ee.impl.encoding.CDRInputObject ; +import com.sun.corba.ee.impl.encoding.CDROutputObject; +import com.sun.corba.ee.impl.encoding.EncapsInputStream ; +import com.sun.corba.ee.impl.encoding.EncapsOutputStream ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import org.testng.annotations.Test ; +import org.testng.Assert ; + +import corba.framework.TestngRunner ; + +public class Client +{ + private PrintStream out = System.out ; + private PrintStream err = System.err ; + private ORB orb ; + + public static void main(String args[]) + { + System.out.println( "Starting IOR test" ) ; + TestngRunner runner = new TestngRunner() ; + runner.registerClass( Client.class ) ; + runner.run() ; + runner.systemExit() ; + } + + public Client() { + String[] args = null ; + Properties props = new Properties( System.getProperties() ) ; + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + + this.orb = (ORB)ORB.init( args, props ) ; + } + +// ************************************************* +// *************** Utilities ******************* +// ************************************************* + + private void error( String msg ) + { + Assert.fail( msg ) ; + } + + private void info( String msg ) + { + out.println( msg ) ; + } + + private boolean equal( byte[] arr1, byte[] arr2 ) + { + if ((arr1 == null) || (arr2 == null)) + return arr1==arr2 ; + + int len = arr1.length ; + if (len != arr2.length) + return false ; + + for (int ctr = 0; ctr= result.length) + error( "Too many IdentifiableImpls returned by iterator" + + index) ; + + if (!result[ctr].equals( obj )) + error( "Wrong IdentifiableImpl " + result[ctr] + + " in iterator" + index ) ; + ctr++ ; + } + + if (ctr != result.length) + error( "Too few identifiableImpls returned by iterator" + + index + " (ctr=" + ctr + " length=" + result.length + + ")" ) ; + } + + @Test + public void testResolve() + { + try { + org.omg.CORBA.Object obj = orb.resolve_initial_references( + "RootPOA" ) ; + POA root = (POA)obj ; + } catch (Exception exc) { + error( "\tFailure to resolve root POA" ) ; + } + } + + @Test + public void testCorbalocIOR() { + + out.println( "Testing Corbaloc URL" ) ; + + IIOPAddress addr; + AlternateIIOPAddressComponent iiopAddressComponent; + String key = "NameService"; + byte[] fullKey = key.getBytes(); + + ObjectKey okey = orb.getObjectKeyFactory().create( fullKey ) ; + ObjectKeyTemplate oktemp = okey.getTemplate() ; + IORTemplate iortemp = IORFactories.makeIORTemplate(oktemp); + + // Make sure the standard stuff works first + // + org.omg.CORBA.Object ref = orb.string_to_object( + "corbaloc:iiop:1.2@pico:4444/NameService"); + IOR ior1 = orb.getIOR(ref,false); + + addr = IIOPFactories.makeIIOPAddress( "pico", 4444); + IIOPProfileTemplate profileTemplate_1_2 = + IIOPFactories.makeIIOPProfileTemplate(orb, GIOPVersion.V1_2, addr); + + iortemp.add(profileTemplate_1_2); + + IOR ior2 = iortemp.makeIOR( orb, "", okey.getId() ) ; + + out.println("IOR1 = " + ior1.stringify()); + out.println("IOR2 = " + ior2.stringify()); + + if (!ior1.equals(ior2)) + error( "The 2 IORs are different for standard IOR" ) ; + + // Now verify that the more convoluted/complex stuff works + + okey = orb.getObjectKeyFactory().create( fullKey ) ; + oktemp = okey.getTemplate() ; + iortemp = IORFactories.makeIORTemplate(oktemp); + + /* + // This does not work since CorbalocURL.java validates the + // GIOP version so GIOP version 2.9 throw exception + org.omg.CORBA.Object ref = orb.string_to_object( + "corbaloc:iiop:1.2@pico:4444,:1.1@femto:5555,:1.0@tera:6666,:2.9@mega:7777,:1.0@tera:6667,:1.2@pico:4445,:1.1@femto:5556,:1.2@pico:4446/NameService"); + IOR ior1 = IORFactories.getIOR(ref); + */ + + ref = orb.string_to_object( + "corbaloc:iiop:1.2@pico:4444,:1.1@femto:5555,:1.0@tera:6666,:1.0@tera:6667,:1.2@pico:4445,:1.1@femto:5556,:1.2@pico:4446/NameService"); + ior1 = orb.getIOR(ref,false); + + addr = IIOPFactories.makeIIOPAddress( "pico", 4444); + profileTemplate_1_2 = + IIOPFactories.makeIIOPProfileTemplate(orb, GIOPVersion.V1_2, addr); + addr = IIOPFactories.makeIIOPAddress( "pico", 4445); + iiopAddressComponent = IIOPFactories.makeAlternateIIOPAddressComponent(addr); + profileTemplate_1_2.add(iiopAddressComponent); + addr = IIOPFactories.makeIIOPAddress( "pico", 4446); + iiopAddressComponent = IIOPFactories.makeAlternateIIOPAddressComponent(addr); + profileTemplate_1_2.add(iiopAddressComponent); + + /* + addr = IIOPFactories.makeIIOPAddress( "mega", 7777); + IIOPProfileTemplate profileTemplate_2_9 = + IIOPFactories.makeIIOPProfileTemplate(orb, new GIOPVersion(2,9), addr); + */ + + addr = IIOPFactories.makeIIOPAddress( "femto", 5555); + IIOPProfileTemplate profileTemplate_1_1 = + IIOPFactories.makeIIOPProfileTemplate(orb, GIOPVersion.V1_1, addr); + addr = IIOPFactories.makeIIOPAddress( "femto", 5556); + iiopAddressComponent = IIOPFactories.makeAlternateIIOPAddressComponent(addr); + profileTemplate_1_1.add(iiopAddressComponent); + + List profileList_1_0 = new ArrayList(); + addr = IIOPFactories.makeIIOPAddress( "tera", 6666); + IIOPProfileTemplate profileTemplate_1_0 = + IIOPFactories.makeIIOPProfileTemplate(orb, GIOPVersion.V1_0, addr); + profileList_1_0.add(profileTemplate_1_0); + addr = IIOPFactories.makeIIOPAddress( "tera", 6667); + profileTemplate_1_0 = + IIOPFactories.makeIIOPProfileTemplate(orb, GIOPVersion.V1_0, addr); + profileList_1_0.add(profileTemplate_1_0); + + iortemp.add(profileTemplate_1_2); + // iortemp.add(profileTemplate_2_9); + iortemp.add(profileTemplate_1_1); + iortemp.addAll(profileList_1_0); + + ior2 = iortemp.makeIOR( orb, "", okey.getId() ) ; + + out.println("IOR1 = " + ior1.stringify()); + out.println("IOR2 = " + ior2.stringify()); + + if (!ior1.equals(ior2)) + error( "The 2 IORs are different for the complex case" ) ; + } + + @Test + public void testZeroPortPolicy() + { + out.println( "Testing ZeroPortPolicy" ) ; + + POA rootpoa = null ; + + try { + rootpoa = (POA)orb.resolve_initial_references( "RootPOA" ) ; + } catch (org.omg.CORBA.ORBPackage.InvalidName inv) { + error( "ZeroPortPolicy test failed with exception " + inv ) ; + } + + Policy[] policies = { + rootpoa.create_id_assignment_policy( IdAssignmentPolicyValue.SYSTEM_ID ), + ZeroPortPolicy.getPolicy() } ; + + POA testpoa = null ; + + try { + testpoa = rootpoa.create_POA( "TestPOA", null, policies ) ; + } catch (org.omg.PortableServer.POAPackage.AdapterAlreadyExists ex) { + error( "ZeroPortPolicy test failed with exception " + ex ) ; + } catch (org.omg.PortableServer.POAPackage.InvalidPolicy ip) { + error( "ZeroPortPolicy test failed with exception " + ip ) ; + } + + org.omg.CORBA.Object obj = null ; + + try { + obj = testpoa.create_reference( "IDL:omg.org/CORBA/Object:1.0" ) ; + } catch (org.omg.PortableServer.POAPackage.WrongPolicy wp ) { + error( "ZeroPortPolicy test failed with exception " + wp ) ; + } + + IOR ior = orb.getIOR( obj, false ) ; + + // Check that all IIOPProfileTemplate instances have their primary port set to 0 + Iterator iter = ior.iteratorById( TAG_INTERNET_IOP.value ) ; + while (iter.hasNext()) { + IIOPProfile prof = (IIOPProfile)iter.next() ; + IIOPProfileTemplate temp = (IIOPProfileTemplate)prof.getTaggedProfileTemplate() ; + if (temp.getPrimaryAddress().getPort() != 0) + error( "\tZeroPortPolicy test failed" ) ; + } + } + + @Test + public void testORBVersion() + { + out.println( "Testing ORBVersion" ) ; + if (ORBVersionFactory.getFOREIGN().getORBType() != ORBVersion.FOREIGN) + error( "\tBad encoding for FOREIGN version" ) ; + if (ORBVersionFactory.getOLD().getORBType() != ORBVersion.OLD) + error( "\tBad encoding for OLD version" ) ; + if (ORBVersionFactory.getNEW().getORBType() != ORBVersion.NEW) + error( "\tBad encoding for NEW version" ) ; + if (ORBVersionFactory.getNEWER().getORBType() != ORBVersion.NEWER) + error( "\tBad encoding for NEWER version" ) ; + if (ORBVersionFactory.getPEORB().getORBType() != ORBVersion.PEORB) + error( "\tBad encoding for NEWER version" ) ; + + if (ORBVersionFactory.getFOREIGN().equals( ORBVersionFactory.getOLD() )) + error( "\tFOREIGN == OLD!" ) ; + + if (ORBVersionFactory.getOLD().equals( ORBVersionFactory.getNEW() )) + error( "\tOLD == NEW!" ) ; + + if (ORBVersionFactory.getNEW().equals( ORBVersionFactory.getNEWER() )) + error( "\tNEW == NEWER!" ) ; + + if (!ORBVersionFactory.getNEW().equals( ORBVersionFactory.getNEW() )) + error( "\tNEW != NEW!" ) ; + } + + @Test + public void testORBVersionFactory() + { + out.println( "Testing ORBVersionFactory" ) ; + byte[] test = { 0x00 } ; + int pos = test.length - 1 ; + + test[pos] = ORBVersion.NEWER ; + InputStream is = new EncapsInputStream( orb, test, test.length ) ; + ORBVersion version = ORBVersionFactory.create( is ) ; + if (!version.equals( ORBVersionFactory.getNEWER() )) + error( "\tcreate bad version from array1" ) ; + + test[pos] = ORBVersion.NEWER + 50 ; + is = new EncapsInputStream( orb, test, test.length ) ; + version = ORBVersionFactory.create( is ) ; + if (version.getORBType() != ORBVersion.NEWER + 50) + error( "\tcreate bad version from array2" ) ; + + test[pos] = -1 ; + is = new EncapsInputStream( orb, test, test.length ) ; + version = ORBVersionFactory.create( is ) ; + if (version.getORBType() != -1) + error( "\tcreate bad version from array3" ) ; + + OutputStream os = newOutputStream() ; + os.write_octet( ORBVersion.PEORB ) ; + is = makeInputStream( os ) ; + version = ORBVersionFactory.create( is ) ; + if (!version.equals( ORBVersionFactory.getPEORB() )) + error( "\tcreate bad version from input stream" ) ; + + if (!ORBVersionFactory.getORBVersion().equals( ORBVersionFactory.getPEORB() )) + error( "\tDefault ORB version is not NEWER" ) ; + } + + @Test + public void testIdentifiableContainerBase1() + { + out.println( "Testing IdentifiableContainerBase" ) ; + + IdentifiableImpl[] obj = { + new IdentifiableImpl( 0, 27 ) , + new IdentifiableImpl( 1, 28 ) , + new IdentifiableImpl( 0, 29 ) , + new IdentifiableImpl( 0, 30 ) , + new IdentifiableImpl( 2, 31 ) , + new IdentifiableImpl( 0, 32 ) , + new IdentifiableImpl( 2, 33 ) + } ; + + IdentifiableContainerBase icb = new IdentifiableContainerBase() ; + for (int ctr=0; ctr= comps.length) + error( "Iterator return too many component for IdentifiableContainerBase" ) ; + + if (!comps[ctr].equals( obj )) + error( "Incorrect component read back for ctr = " + ctr ) ; + + ctr++ ; + } + + if (ctr != comps.length) + error( "Iterator returned too few components for IdentifiableContainerBase" ) ; + } + + @Test + public void testGenericTaggedComponent() + { + out.println( "Testing GenericTaggedComponent" ) ; + + // Some random data + int id = 424 ; + byte[] data = { 0x12, 0x23, 0x31, 0x33, 0x7A, 0x27, 0x6B, 0x36, 0x7A } ; + GenericTaggedComponent enc = new GenericTaggedComponent( id, data ) ; + + if (id != enc.getId()) + error( "bad id" ) ; + + if (!equal( data, enc.getData() )) + error( "bad data" ) ; + + // Write out and read back + OutputStream os = newOutputStream() ; + enc.write( os ) ; + InputStream is = makeInputStream( os ) ; + + GenericTaggedComponent newEnc = new GenericTaggedComponent( id, is ) ; + + if (!equal( data, newEnc.getData() )) + error( "bad data read back" ) ; + } + + @Test + public void testIIOPAddress() + { + out.println( "Testing IIOPAddress" ) ; + + // Construct and verify + String host = "foo" ; + int port = 1234 ; + IIOPAddress addr = IIOPFactories.makeIIOPAddress( host, port ) ; + + if (!host.equals(addr.getHost())) + error( "incorrect host" ) ; + + if (port != addr.getPort()) + error( "incorrect port" ) ; + + // test equals + Object obj = new Object() ; + if (addr.equals( obj )) + error( "IIOPAddress equal to object" ) ; + + IIOPAddress addr2 = IIOPFactories.makeIIOPAddress( host, port ) ; + if (!addr.equals( addr2 )) + error( "IIOPAddress equals check failed" ) ; + + // Test for range checking on constructor + boolean exceptionOK = false ; + try { + IIOPFactories.makeIIOPAddress( "FOO", -2 ) ; + } catch (BAD_PARAM exc) { + exceptionOK = true ; + } catch (Throwable thr) { + error( "Unexpected exception thrown on out-of-range port for IIOPAddress (1)" ) ; + } + if (!exceptionOK) + error( "No exception thrown on out-of-range port for IIOPAddress (1)" ) ; + + exceptionOK = false ; + try { + IIOPFactories.makeIIOPAddress( "FOO", 65536 ) ; + } catch (BAD_PARAM exc) { + exceptionOK = true ; + } catch (Throwable thr) { + error( "Unexpected exception thrown on out-of-range port for IIOPAddress (2)" ) ; + } + if (!exceptionOK) + error( "No exception thrown on out-of-range port for IIOPAddress (2)" ) ; + + exceptionOK = false ; + try { + IIOPFactories.makeIIOPAddress( "FOO", 130232 ) ; + } catch (BAD_PARAM exc ) { + exceptionOK = true ; + } catch (Throwable thr) { + error( "Unexpected exception thrown on out-of-range port for IIOPAddress (3)" ) ; + } + if (!exceptionOK) + error( "No exception thrown on out-of-range port for IIOPAddress (3)" ) ; + + // read/write test, with port <32768 and >= 32768 + IIOPAddress[] addrs = { + IIOPFactories.makeIIOPAddress( "FOO.SUN.COM", 23 ) , + IIOPFactories.makeIIOPAddress( "FOO.SUN.COM", 32768 ) , + IIOPFactories.makeIIOPAddress( "FOO.SUN.COM", 40151 ) , + IIOPFactories.makeIIOPAddress( "FOO.SUN.COM", 65535 ) + } ; + + OutputStream os = newOutputStream() ; + + for (int ctr=0; ctr iter = testProf.getTaggedProfileTemplate().iterator() ; + + if (!iter.hasNext()) + error( "No components in testProf" ) ; + + tc1 = iter.next() ; + + if (iter.hasNext()) { + tc2 = iter.next() ; + + if (iter.hasNext()) + error( "too many components in testProf" ) ; + + // Don't depend on iteration order + if (tc1 instanceof ORBTypeComponent) { + if (!tc1.equals( comp )) + error( "ORBTypeComponent in testProf does not match original" ) ; + if (!(tc2 instanceof JavaCodebaseComponent)) + error( "Other component is not JavaCodebaseComponent" ) ; + } else { + if (!tc2.equals( comp )) + error( "ORBTypeComponent in testProf does not match original" ) ; + if (!(tc1 instanceof JavaCodebaseComponent)) + error( "Other component is not JavaCodebaseComponent" ) ; + } + } else { + if (!comp.equals( comp )) + error( "ORBTypeComponent in testProf does not match original" ) ; + } + } catch (Throwable thr) { + error( "unexpected exception in examining testProf" ) ; + } + + // test that 1.0 IIOPProfileTemplates do not support addition of components + IIOPProfileTemplate ptemp2 = IIOPFactories.makeIIOPProfileTemplate( orb, + GIOPVersion.V1_0, primary ) ; + + boolean expectedException = false ; + try { + ptemp2.add( comp ) ; + } catch (UnsupportedOperationException uoe) { + expectedException = true ; + } catch (Throwable thr) { + error( "Component add to 1.0 IIOPProfileTemplate threw unexpected exception" ) ; + } + + if (!expectedException) + error( "Component add to 1.0 IIOPProfileTemplate succeeded incorrectly" ) ; + } + + public POAObjectKeyTemplate makePOAObjectKeyTemplate( ObjectAdapterId poaid ) + { + int scid = ORBConstants.FIRST_POA_SCID ; + String orbid = "AVeryLongORBIdName" ; + int serverid = -123 ; + + POAObjectKeyTemplate temp = new POAObjectKeyTemplate( orb, scid, + serverid, orbid, poaid ) ; + + return temp ; + } + + public IIOPProfileTemplate makeIIOPProfileTemplate( int port ) + { + String host = "FOO" ; + IIOPAddress primary = IIOPFactories.makeIIOPAddress( host, port ) ; + + IIOPProfileTemplate ptemp = IIOPFactories.makeIIOPProfileTemplate( orb, + GIOPVersion.V1_2, primary ) ; + + return ptemp ; + } + + @Test + public void testIOR() + { + out.println( "Testing IOR" ) ; + + // Test IOR() + IOR ior1 = IORFactories.makeIOR( orb ) ; + if (!"".equals( ior1.getTypeId() )) + error( "IOR() should have null typeid" ) ; + + Iterator iter = ior1.iterator() ; + if (iter.hasNext()) + error( "IOR() should not have any profiles" ) ; + + // Test IOR(String, IIOPPRofileTemplate, ObjectId ) + String[] ss = { "foo", "bar" } ; + ObjectAdapterId poaid = new ObjectAdapterIdArray( ss ) ; + POAObjectKeyTemplate poktemp1 = makePOAObjectKeyTemplate( poaid ) ; + IIOPProfileTemplate ptemp1 = makeIIOPProfileTemplate( 45671 ) ; + String URL = "htp://foo.sun.com:9999" ; + JavaCodebaseComponent jcomp = + IIOPFactories.makeJavaCodebaseComponent( URL ) ; + ORBTypeComponent comp1 = IIOPFactories.makeORBTypeComponent( + 0x34567ABF ) ; + IIOPAddress addr = IIOPFactories.makeIIOPAddress( "FOO", 32451 ) ; + AlternateIIOPAddressComponent comp2 = + IIOPFactories.makeAlternateIIOPAddressComponent( addr ) ; + + ptemp1.add( comp1) ; + ptemp1.add( comp2 ) ; + ptemp1.add( jcomp ) ; + + IORTemplate iortemp = IORFactories.makeIORTemplate( poktemp1 ) ; + iortemp.add( ptemp1 ) ; + + byte[] id = { 0x00, 0x00, 0x33, 0x44, 0x21, 0x23, 0x00 } ; + ObjectId oid = IORFactories.makeObjectId( id ) ; + + String typeid = "foo:bar" ; + IOR ior3 = iortemp.makeIOR( orb, typeid, oid ) ; + + if (!ior3.getTypeId().equals( typeid )) + error( "IOR(ORB,String,IORTemplate,ObjectId) has bad typeid" ) ; + + IIOPProfile iprof1 = (IIOPProfile)(ptemp1.create( poktemp1, oid )) ; + + iter = ior3.iterator() ; + if (!iter.hasNext()) + error( "ior3 has no profiles" ) ; + + Object obj = iter.next() ; + + if (!iprof1.equals( obj )) + error( "ior3 has wrong profile" ) ; + + if (iter.hasNext()) + error( "ior3 has too many profiles" ) ; + + // Create another IIOPProfile + String[] ss2 = { "bar" } ; + ObjectAdapterId poaid2 = new ObjectAdapterIdArray( ss2 ) ; + POAObjectKeyTemplate poktemp2 = makePOAObjectKeyTemplate( poaid2 ) ; + IIOPProfileTemplate ptemp2 = makeIIOPProfileTemplate( 36123 ) ; + ptemp2.add( jcomp ) ; + ptemp2.add( comp2 ) ; + + IIOPProfile iprof2 = (IIOPProfile)(ptemp2.create( poktemp2, oid )) ; + + // Create a GenericTaggedProfile to use as a profile + int gid = 234 ; + byte[] data = { 2, 14, 56, 37, 31, 42, 1, 9, 116, 57 } ; + GenericTaggedProfile gprof = new GenericTaggedProfile( orb, gid, data ) ; + + // Create ior containing iprof1, iprof2, gprof + IOR ior4 = IORFactories.makeIOR( orb, typeid ) ; + ior4.add( iprof1 ) ; + ior4.add( iprof2 ) ; + ior4.add( gprof ) ; + ior4.makeImmutable() ; + + OutputStream os = newOutputStream() ; + + ior4.write( os ) ; + + InputStream is = makeInputStream( os ) ; + + IOR ior5 = IORFactories.makeIOR( orb, is ) ; + + if (!ior4.equals( ior5 )) + error( "Read and written IORs are different" ) ; + + // Test makeImmutable + ior4.makeImmutable() ; + iter = ior4.iterator() ; + boolean correct = false ; + + try { + iter.next() ; + iter.remove() ; + } catch (UnsupportedOperationException uoe) { + correct = true ; + } catch (Throwable t) { + error( "Bad exception on iterator.remove() for frozen list" ) ; + } + + if (!correct) + error( "iterator.remove succeeded on frozen list" ) ; + + IIOPProfile prof3 = (IIOPProfile)(iter.next()) ; + Iterator iter2 = prof3.getTaggedProfileTemplate().iterator() ; + + correct = false ; + + try { + iter2.next() ; + iter2.remove() ; + } catch (UnsupportedOperationException uoe) { + correct = true ; + } catch (Throwable t) { + error( "Bad exception on iterator.remove() for frozen list" ) ; + } + + if (!correct) + error( "iterator.remove succeeded on frozen list" ) ; + } + + private IORTemplate makeIORTemplate( String[] oaid, int[] ports, + boolean addComponent ) + { + POAObjectKeyTemplate poktemp = + makePOAObjectKeyTemplate( new ObjectAdapterIdArray( oaid ) ) ; + + IORTemplate iort = IORFactories.makeIORTemplate( poktemp ) ; + + for (int ctr=0; ctr" ) ; + System.out.println( "\t-pool
                    " ) ; + } + + System.exit(1) ; + } + + private static List parseInetSocketAddresses( List data ) { + List result = new ArrayList() ; + Iterator iter = data.iterator() ; + while (iter.hasNext()) { + String str = (String)iter.next() ; + int lindex = str.lastIndexOf( ':' ) ; + String head ; + String tail ; + + if (lindex < 0) { + head = "localhost" ; + tail = str ; + } else { + head = str.substring( 0, lindex ) ; + tail = str.substring( lindex+1 ) ; + } + + int port = Integer.valueOf( tail ).intValue() ; + InetSocketAddress isa = new InetSocketAddress( head, port ) ; + result.add( isa ) ; + } + + return result ; + } + + /** All addresses are given in host:port form. + * If host is omitted, we assume localhost for the host. + * Arguments are: + *
                    +     * -listen 
                    +     * -pool , ...
                    +     */
                    +    public static void main( String[] args ) {
                    +      try {
                    +        ArgParser ap = new ArgParser( args ) ; 
                    +        while (!ap.done()) {
                    +          String command = ap.getCommand() ;
                    +          if (command.equals( "-listen" )) {
                    +            String data = ap.getData() ;
                    +            myPort = Integer.valueOf( data ).intValue() ;
                    +          } else if (command.equals( "-pool" )) {
                    +            List data = ap.getDataList() ;
                    +            pool = parseInetSocketAddresses( data ) ;
                    +          } else if (command.equals( "-ORBInitialPort" )) {
                    +            String data = ap.getData() ;
                    +          }
                    +          //this else block is causing it to exit since it is finding args other than -listen and -pool. 
                    +          //-ORBInitialPort is also getting passed
                    +          //else {
                    +          //usageAndExit(null) ;
                    +          //}
                    +        }
                    +      } catch (Exception exc) {
                    +        usageAndExit(exc ) ;
                    +      }
                    +      run() ;
                    +      
                    +    }
                    +
                    +    private static String makeAndSetName( String name, InetAddress addr, int port, 
                    +        int count ) {
                    +
                    +        String result = name + "(" + count + "):" + addr + ":" + port ;
                    +        Thread.currentThread().setName( result ) ;
                    +        return result ;
                    +    }
                    +
                    +    private static void makeCleaner( final InetAddress addr,
                    +        final int port, final int count, final Thread t1, final Thread t2, 
                    +        final Socket ss, final Socket cs ) {
                    +
                    +        new Thread() {
                    +            public void run() {
                    +                String myName = makeAndSetName( "Cleaner", addr, port, count ) ;
                    +                try {
                    +                    System.out.println( myName + " waiting for " + t1 ) ;
                    +                    t1.join() ;
                    +                    System.out.println( myName + " waiting for " + t2 ) ;
                    +                    t2.join() ;
                    +                    ss.close() ;
                    +                    cs.close() ;
                    +                } catch (Exception exc) {
                    +                    // ignore this: we are just cleaning up here!
                    +                    System.out.println( myName + " caught exception " + exc ) ;
                    +                    exc.printStackTrace() ;
                    +                }
                    +
                    +                System.out.println( myName + " is exiting" ) ;
                    +            }
                    +        }.start() ;
                    +    }
                    +
                    +    private static class DataCopier extends Thread {
                    +        private byte[] buffer = new byte[4096] ;
                    +        private String name ;
                    +        private Socket inputSocket ;
                    +        private InputStream is ;
                    +        private OutputStream os ;
                    +        private DataCopier peer ;
                    +        private volatile boolean running = true ;
                    +
                    +        public DataCopier( String name, Socket inputSocket, OutputStream os ) {
                    +            this.name = name ;
                    +            this.inputSocket = inputSocket ;
                    +            try {
                    +                this.is = inputSocket.getInputStream() ;
                    +            } catch (Exception exc) {
                    +                throw new RuntimeException( exc ) ;
                    +            }
                    +            this.os = os ;
                    +        }
                    +
                    +        public void run() {
                    +            try {
                    +                this.setName( name ) ;
                    +                while (running) {
                    +                    int size = is.read( buffer ) ;
                    +                    dprint( name + ": read " + size + " bytes" ) ;
                    +                    if (size < 0)
                    +                        break ;
                    +                    os.write( buffer, 0, size ) ;
                    +                    dprint( name + ": wrote " + size + " bytes" ) ;
                    +                }
                    +            } catch (IOException exc) {
                    +                System.out.println( name + " terminated with exception " + exc ) ;
                    +                exc.printStackTrace() ;
                    +            }
                    +
                    +            close() ;
                    +            System.out.println( name + " is exiting" ) ;
                    +        }
                    +
                    +        // stop this thread by closing the inputSocket, which should
                    +        // terminate the loop.  Then close the peer copier if.
                    +        // This method does nothing after running == false, since otherwise
                    +        // the two peers would cause infinite recursion.
                    +        public synchronized void close() {
                    +            dprint( name + ": close called, running = " + running ) ;
                    +            if (running) {
                    +                running = false ; 
                    +                try {
                    +                    inputSocket.close() ;
                    +                } catch (Exception exc) {
                    +                    // NO-OP
                    +                    dprint( name + ": exception on DataCopier.close: " + exc ) ;
                    +                }
                    +
                    +                peer.close() ;
                    +            } 
                    +        }
                    +
                    +        public void setPeer( DataCopier peer ) {
                    +            this.peer = peer ;
                    +        }
                    +    }
                    +
                    +    private static DataCopier makeDataCopier( final String name, 
                    +        final InetAddress addr, final int port, final int count,
                    +        final Socket s, final OutputStream os ) {
                    +        
                    +        String myName = makeAndSetName( name, addr, port, count ) ;
                    +        DataCopier result = new DataCopier( myName, s, os ) ;
                    +
                    +        return result ;
                    +    }
                    +
                    +    private static boolean createSocketCopier( Socket socket, int count ) {
                    +        int retryCount = 0 ;
                    +        while (retryCount++ < pool.size()) {
                    +            // Grab the next pool address
                    +            poolIndex++ ;
                    +            if (poolIndex == pool.size())
                    +                poolIndex = 0 ;
                    +
                    +            dprint( "Creating new Socket copier(" + count + ") for socket " + socket ) ;
                    +            // Open a new connection to the pool address
                    +            InetSocketAddress isa = (InetSocketAddress)pool.get(poolIndex) ;
                    +            InetAddress addr = isa.getAddress() ;
                    +            int port = isa.getPort() ;
                    +            
                    +            Socket client = null ;
                    +
                    +            try {
                    +                client = new Socket( addr, port ) ;
                    +                
                    +                // Create two data copiers:
                    +                DataCopier t1 = makeDataCopier( "S->C", addr, port, count, socket,
                    +                    client.getOutputStream() ) ;
                    +                DataCopier t2 = makeDataCopier( "C->S", addr, port, count, client,
                    +                    socket.getOutputStream() ) ;
                    +
                    +                // set each copier as a peer of the other
                    +                t1.setPeer( t2 ) ;
                    +                t2.setPeer( t1 ) ;
                    +
                    +                // Now start the data copying
                    +                t1.start() ;
                    +                t2.start() ;
                    +
                    +                // Cleaner is no longer used
                    +                // makeCleaner( addr, port, count, t1, t2, socket, client ) ;
                    +                return true ;
                    +            } catch (IOException exc) {
                    +                System.out.println( "Exception while creating socket to port " + port + ": " + exc ) ;
                    +                exc.printStackTrace() ;
                    +                // run around the retry loop
                    +            }
                    +        }
                    +
                    +        // It was not possible to find a valid instance in the pool.
                    +        return false ;
                    +    }
                    +
                    +    private static int acceptCount = 0 ;
                    +
                    +    private static void run() {  
                    +        try {
                    +            ServerSocket ss = new ServerSocket( myPort ) ;
                    +            System.out.println("Server is ready." ) ;
                    +            System.out.println("Server listening at port " + myPort);
                    +            while (true) {
                    +                try {
                    +                    Socket socket = ss.accept() ;
                    +                    if (!createSocketCopier( socket, acceptCount++ ))
                    +                        // It is very important to close the socket if we cannot
                    +                        // find a valid pool address, as otherwise the client will hang!
                    +                        socket.close() ;
                    +                } catch (Exception exc) {
                    +                    System.out.println( "Exception in accept loop: " + exc ) ;
                    +                    exc.printStackTrace() ;
                    +                }
                    +            }
                    +        } catch (IOException exc) {
                    +            usageAndExit( exc ) ;
                    +        } 
                    +    }
                    +}
                    +    
                    diff --git a/test/src/share/classes/corba/lb/LBTest.java b/test/src/share/classes/corba/lb/LBTest.java
                    new file mode 100644
                    index 000000000..478adb4d4
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lb/LBTest.java
                    @@ -0,0 +1,112 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.lb ;
                    +
                    +import java.util.Properties ;
                    +
                    +import corba.framework.CORBATest ;
                    +import corba.framework.Options ;
                    +import corba.framework.Controller ;
                    +
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +import com.sun.corba.ee.impl.plugin.hwlb.VirtualAddressAgentImpl ;
                    +import com.sun.corba.ee.impl.plugin.hwlb.NoConnectionCacheImpl ;
                    +
                    +public class LBTest
                    +    extends
                    +        CORBATest
                    +{
                    +    private static final String LB_HOST = "localhost" ;
                    +    private static final int LB_PORT = 57340 ;
                    +    private static final int S1_PORT = 57351 ;
                    +    private static final int S2_PORT = 57352 ;
                    +
                    +    private static final int SHARED_SERVER_ID = 2727 ;
                    +
                    +    protected void doTest()
                    +        throws Exception
                    +    {
                    +        String thisPackage = this.getClass().getPackage().getName() ;
                    +        String pluginPackage = "com.sun.corba.ee.impl.plugin.hwlb" ;
                    +
                    +        // Set up shared client and server properties.  This causes the client
                    +        // ORBs to be initialized without connection caching, and the server
                    +        // ORBs to use ORT to set the server port to Sx_PORT, while creating
                    +        // IORs that contains the LB_PORT.
                    +        Properties serverProps = Options.getServerProperties() ; 
                    +        serverProps.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, 
                    +            Integer.toString(SHARED_SERVER_ID)) ;
                    +        serverProps.setProperty( ORBConstants.USER_CONFIGURATOR_PREFIX 
                    +            + pluginPackage + "." + "VirtualAddressAgentImpl",
                    +            "dummy" ) ;
                    +        serverProps.setProperty( VirtualAddressAgentImpl.VAA_HOST_PROPERTY, 
                    +            LB_HOST ) ;
                    +        serverProps.setProperty( VirtualAddressAgentImpl.VAA_PORT_PROPERTY, 
                    +            Integer.toString(LB_PORT) ) ;
                    +
                    +        Properties clientProps = Options.getClientProperties() ; 
                    +        clientProps.setProperty( ORBConstants.USER_CONFIGURATOR_PREFIX 
                    +                + pluginPackage + "." + "NoConnectionCacheImpl",
                    +                "dummy" ) ;
                    +        
                    +        Controller orbd = createORBD();
                    +        orbd.start();
                    +
                    +        Controller lb;
                    +        Controller server1;
                    +        Controller server2;
                    +        Controller client;
                    +
                    +        String lbArgs = "-listen " + LB_PORT + " -pool " + S1_PORT + " " + S2_PORT ;
                    +        Options.addServerArgs( lbArgs ) ;
                    +
                    +        lb = createServer(thisPackage+"."+"LB", "LB" ) ;
                    +
                    +        serverProps.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, 
                    +            Integer.toString(S1_PORT)) ;
                    +        server1 = createServer(thisPackage+"."+"Server", "Server1.1");
                    +
                    +        serverProps.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, 
                    +            Integer.toString(S2_PORT)) ;
                    +        server2 = createServer(thisPackage+"."+"Server", "Server2");
                    +        
                    +        client = createClient(thisPackage+"."+"Client", "Client");
                    +
                    +        lb.start() ;
                    +        Thread.sleep( 1000 ) ;
                    +
                    +        server1.start();
                    +        server2.start();
                    +
                    +        Thread.sleep( 1000 ) ;
                    +
                    +        client.start();
                    +
                    +        // Wait for client to get started before stopping server1.
                    +        Thread.sleep( 4000 ) ;
                    +        server1.stop();
                    +
                    +        Thread.sleep( 1000 ) ;
                    +        serverProps.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, 
                    +            Integer.toString(S1_PORT)) ;
                    +        server1 = createServer(thisPackage+"."+"Server", "Server1.2");
                    +        server1.start() ;
                    +
                    +        client.waitFor(1000 * 60 * 2);
                    +
                    +        client.stop();
                    +        lb.stop() ;
                    +        server1.stop();
                    +        server2.stop();
                    +        orbd.stop();
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/lb/Server.java b/test/src/share/classes/corba/lb/Server.java
                    new file mode 100644
                    index 000000000..c2b1fe93b
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lb/Server.java
                    @@ -0,0 +1,158 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:54:09 by Harold Carr.
                    +// Last Modified : 2005 Oct 06 (Thu) 11:32:08 by Harold Carr.
                    +//
                    +
                    +package corba.lb;
                    +
                    +import java.util.Properties;
                    +import java.util.Hashtable;
                    +
                    +import javax.naming.InitialContext ;
                    +
                    +import javax.rmi.PortableRemoteObject ;
                    +
                    +import org.omg.CORBA.ORB;
                    +import org.omg.CORBA.Policy ;
                    +
                    +import org.omg.PortableServer.POA;
                    +import org.omg.PortableServer.Servant;
                    +import org.omg.PortableServer.LifespanPolicyValue;
                    +import org.omg.PortableServer.IdUniquenessPolicyValue;
                    +import org.omg.PortableServer.IdAssignmentPolicyValue;
                    +import org.omg.PortableServer.ImplicitActivationPolicyValue;
                    +import org.omg.PortableServer.ServantRetentionPolicyValue;
                    +import org.omg.PortableServer.RequestProcessingPolicyValue;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public class Server
                    +{
                    +    static {
                    +        // This is needed to guarantee that this test will ALWAYS use dynamic
                    +        // RMI-IIOP.  Currently the default is dynamic when renamed to "ee",
                    +        // but static in the default "se" packaging, and this test will
                    +        // fail without dynamic RMI-IIOP.
                    +        System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ;
                    +    }
                    +
                    +    private static final String baseMsg = Server.class.getName();
                    +    private static final String RootPOA = "RootPOA";
                    +    private static final long SERVER_RUN_LENGTH = 1000 * 60; // 1 minute
                    +
                    +    public static void main(String[] av)
                    +    {
                    +        try {
                    +            Properties props = new Properties();
                    +            // props.setProperty("com.sun.corba.ee.ORBDebug","subcontract,transport");
                    +
                    +            ORB orb = ORB.init(av, props);
                    +
                    +            POA rootPOA = (POA) orb.resolve_initial_references("RootPOA");
                    +            Policy[] policies = new Policy[] {
                    +                rootPOA.create_lifespan_policy( 
                    +                    LifespanPolicyValue.PERSISTENT ),
                    +                rootPOA.create_id_uniqueness_policy( 
                    +                    IdUniquenessPolicyValue.UNIQUE_ID ),
                    +                rootPOA.create_id_assignment_policy( 
                    +                    IdAssignmentPolicyValue.USER_ID ),
                    +                rootPOA.create_implicit_activation_policy( 
                    +                    ImplicitActivationPolicyValue.NO_IMPLICIT_ACTIVATION ),
                    +                rootPOA.create_servant_retention_policy(
                    +                    ServantRetentionPolicyValue.RETAIN ),
                    +                rootPOA.create_request_processing_policy(
                    +                    RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY )
                    +            } ;
                    +
                    +            POA testPOA = rootPOA.create_POA( "testPOA", rootPOA.the_POAManager(), 
                    +                policies ) ;
                    +
                    +            Servant servant = (Servant)
                    +                javax.rmi.CORBA.Util.getTie(new TestServant());
                    +
                    +            // Print this out just before activate the POAManager, because
                    +            // activating the POAManager causes request to be handled.
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Server is ready.");
                    +            System.out.println("--------------------------------------------");
                    +
                    +            createWithServantAndBind(Common.ReferenceName, servant, 
                    +                                     testPOA, orb);
                    +            // This should come AFTER we have set up the servant, otherwise a
                    +            // request could be processed before the server is ready.
                    +            rootPOA.the_POAManager().activate();
                    +
                    +            // testLocalCalls( orb ) ;
                    +
                    +            orb.run() ;
                    +        } catch (Exception e) {
                    +            e.printStackTrace(System.out);
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("!!!! Server exiting INCORRECTLY...");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(1);
                    +        }
                    +    }
                    +
                    +    private static void testLocalCalls( ORB orb ) {
                    +        System.out.println("--------------------------------------------");
                    +        System.out.println("Beginning local invocation test...");
                    +        System.out.println("--------------------------------------------");
                    +
                    +        try {
                    +            Hashtable env = new Hashtable();
                    +            env.put("java.naming.corba.orb", orb);
                    +
                    +            InitialContext initialContext = new InitialContext(env);
                    +            Test test = (Test)PortableRemoteObject.narrow(
                    +                initialContext.lookup(Common.ReferenceName), Test.class );
                    +
                    +            System.out.println( "test.is_local() = " +
                    +                ((org.omg.CORBA.portable.ObjectImpl)test)._is_local() ) ;
                    +            
                    +            for (int ctr=0; ctr<10; ctr++) {
                    +                System.out.println( "Local invocation with argument " + ctr ) ;
                    +                int result = test.echo( ctr ) ;
                    +                if (result != ctr)
                    +                    throw new Exception( "Result does not match argument" ) ;
                    +            }
                    +        } catch (Exception exc) {
                    +            throw new RuntimeException( exc ) ;
                    +        }
                    +
                    +        System.out.println("--------------------------------------------");
                    +        System.out.println("Local invocation test complete");
                    +        System.out.println("--------------------------------------------");
                    +    }
                    +
                    +    public static org.omg.CORBA.Object 
                    +        createWithServantAndBind (String  name,
                    +                                  Servant servant,
                    +                                  POA     poa,
                    +                                  ORB     orb)
                    +        throws
                    +            Exception
                    +    {
                    +        byte[] id = name.getBytes();
                    +        poa.activate_object_with_id(id, servant);
                    +        org.omg.CORBA.Object ref = poa.id_to_reference(id);
                    +        Common.rebind(name, ref, orb);
                    +        return ref;
                    +    }
                    +
                    +} 
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/lb/Test.java b/test/src/share/classes/corba/lb/Test.java
                    new file mode 100644
                    index 000000000..669393850
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lb/Test.java
                    @@ -0,0 +1,33 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:49:03 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:08:09 by Harold Carr.
                    +//
                    +
                    +package corba.lb;
                    +
                    +import java.rmi.Remote;
                    +import java.rmi.RemoteException;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public interface Test
                    +    extends Remote
                    +{
                    +    public int echo(int x)
                    +        throws RemoteException;
                    +}
                    +
                    +// End of file.
                    +
                    +
                    diff --git a/test/src/share/classes/corba/lb/TestServant.java b/test/src/share/classes/corba/lb/TestServant.java
                    new file mode 100644
                    index 000000000..16c084294
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lb/TestServant.java
                    @@ -0,0 +1,40 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:50:17 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:17:44 by Harold Carr.
                    +//
                    +
                    +package corba.lb;
                    +
                    +import java.rmi.RemoteException;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +public class TestServant
                    +    extends PortableRemoteObject
                    +    implements Test
                    +{
                    +    public static final String baseMsg = TestServant.class.getName();
                    +
                    +    public TestServant()
                    +        throws RemoteException
                    +    {
                    +    }
                    +
                    +    public int echo(int x)
                    +        throws RemoteException
                    +    {
                    +        System.out.println(baseMsg + ".echo: " + x);
                    +        return x;
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/lbq/ClientControl.java b/test/src/share/classes/corba/lbq/ClientControl.java
                    new file mode 100644
                    index 000000000..9b4cc1833
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/ClientControl.java
                    @@ -0,0 +1,25 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.lbq ;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +/** Interface for remote object used to control the Client behavior.
                    + */
                    +public interface ClientControl extends Remote {
                    +    /** Tell the Client to send the given number of requests.
                    +     * The client sends the requests as fast as possible after
                    +     * this method returns.
                    +     */
                    +    void startSendingRequests( int numRequests ) throws RemoteException ;
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/lbq/CommandQueue.java b/test/src/share/classes/corba/lbq/CommandQueue.java
                    new file mode 100644
                    index 000000000..d9c8751b4
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/CommandQueue.java
                    @@ -0,0 +1,155 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.lbq ;
                    +
                    +import org.glassfish.pfl.basic.func.UnaryFunction;
                    +
                    +public class CommandQueue {
                    +    private Command end ; // always points to sink
                    +    private Command head ; // points to last command before sink
                    +    private Command tail ; // points to first command to evaluate
                    +
                    +    public interface Event { } 
                    +
                    +    public interface Command extends UnaryFunction { 
                    +        void setNext( Command next ) ;
                    +    }
                    +  
                    +    public static abstract class CommandBase implements Command {
                    +        protected Command next = null ;
                    +
                    +        public void setNext( Command next ) {
                    +            this.next = next ;
                    +        }
                    +
                    +        public Command evaluate( Event ev ) {
                    +            action( ev ) ;
                    +            return next ;
                    +        }
                    +
                    +        protected void action( Event ev ) {
                    +        }
                    +    }
                    +
                    +    private static class Sink extends CommandBase {
                    +        public Sink() {
                    +            setNext( this ) ;
                    +        }
                    +    }
                    +
                    +    public class Delay extends CommandBase {
                    +        private int count ;
                    +
                    +        /** Do nothing the first numEvents calls.
                    +         */
                    +        public Delay( int numEvents ) {
                    +            this.count = numEvents ;
                    +        }
                    +
                    +        public Command evaluate( Event ev ) {
                    +            count-- ;
                    +            if (count == 0)
                    +                return next ;
                    +            return this ;
                    +        }
                    +    }
                    +
                    +    public CommandQueue() {
                    +        end = new Sink() ;
                    +        tail = end ;
                    +        head = end ;
                    +    }
                    +
                    +    private void doAdd( Command cmd ) {
                    +        if (tail == end) {
                    +            head = cmd ;
                    +        } else {
                    +            tail.setNext( cmd ) ;
                    +        }
                    +
                    +        tail = cmd ;
                    +        cmd.setNext( end ) ;
                    +    }
                    +
                    +    /** Add this command to the queue.  This command must be
                    +     * triggered (by event()) count times before it calls cmd.
                    +     * If count == 0, the first event() will execute cmd.
                    +     */
                    +    public void add( int count, Command cmd ) {
                    +        if (count > 0)
                    +            doAdd( new Delay( count ) ) ;
                    +        doAdd( cmd ) ;
                    +    }
                    +
                    +    public void event( Event ev ) {
                    +        head = head.evaluate( ev ) ;
                    +        if (head == end)
                    +            tail = end ;
                    +    }
                    +
                    +    private static void p( String msg ) {
                    +        System.out.println( msg ) ;
                    +    }
                    +
                    +    private static class Display extends CommandBase {
                    +        String msg ;
                    +
                    +        public Display( String msg ) {
                    +            this.msg = msg ;
                    +        }
                    +
                    +        public void action( Event ev ) {
                    +            p( msg ) ;
                    +        }
                    +    }
                    +
                    +    public static void main( String[] args ) {
                    +        p( "Testing CommandQueue" ) ;
                    +        CommandQueue cq = new CommandQueue() ;
                    +        Event ev = new Event() {} ;
                    +        cq.event( ev ) ; // should do nothing
                    +        cq.event( ev ) ; // should do nothing
                    +
                    +        Command d1 = new Display( "Display 1" ) ;       
                    +        Command d2 = new Display( "Display 2" ) ;       
                    +        Command d3 = new Display( "Display 3" ) ;       
                    +        Command d4 = new Display( "Display 4" ) ;       
                    +
                    +        cq.add( 0, d1 ) ;
                    +        cq.add( 5, d2 ) ;
                    +        cq.add( 8, d3 ) ;
                    +        cq.add( 3, d4 ) ;
                    +
                    +        for (int ctr=0; ctr<25; ctr++) {
                    +            p( "Event " + ctr ) ;
                    +            cq.event( ev ) ;
                    +        }
                    +
                    +        p( "Add to queue while running" ) ;
                    +
                    +        cq.add( 0, d1 ) ;
                    +        cq.add( 5, d2 ) ;
                    +        cq.add( 8, d3 ) ;
                    +
                    +        for (int ctr=0; ctr<11; ctr++) {
                    +            p( "Event " + ctr ) ;
                    +            cq.event( ev ) ;
                    +        }
                    +
                    +        cq.add( 3, d4 ) ;
                    +
                    +        for (int ctr=11; ctr<25; ctr++) {
                    +            p( "Event " + ctr ) ;
                    +            cq.event( ev ) ;
                    +        }
                    +
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/lbq/Common.java b/test/src/share/classes/corba/lbq/Common.java
                    new file mode 100644
                    index 000000000..a4e1e3cb1
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/Common.java
                    @@ -0,0 +1,204 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 14:11:24 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:07:07 by Harold Carr.
                    +//
                    +
                    +package corba.lbq;
                    +
                    +import java.util.Vector;
                    +import java.util.List;
                    +import java.util.ArrayList;
                    +import java.util.StringTokenizer;
                    +import java.util.Properties ;
                    +
                    +import java.rmi.Remote ;
                    +
                    +import java.lang.reflect.Field ;
                    +
                    +import java.security.AccessController ;
                    +import java.security.PrivilegedAction ;
                    +
                    +import javax.rmi.PortableRemoteObject ;
                    +
                    +import org.omg.CosNaming.*;
                    +import org.omg.CosNaming.NamingContextPackage.*;
                    +
                    +import org.omg.PortableServer.POA ;
                    +import org.omg.PortableServer.Servant ;
                    +
                    +import org.omg.PortableInterceptor.ORBInitializer ;
                    +
                    +import com.sun.corba.ee.spi.orb.ORB ;
                    +import com.sun.corba.ee.spi.orb.ORBData ;
                    +
                    +import com.sun.corba.ee.impl.orb.ORBDataParserImpl ;
                    +import com.sun.corba.ee.impl.orb.ORBImpl ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +public class Common
                    +{
                    +    public static final String ReferenceName = "Test";
                    +    private static final String NameService = "NameService";
                    +
                    +    public static org.omg.CORBA.Object resolve(String name, ORB orb)
                    +        throws 
                    +            Exception
                    +    {
                    +        return getNameService(orb).resolve(makeNameComponent(name));
                    +    }
                    +
                    +    public static org.omg.CORBA.Object rebind(String name,
                    +                                              org.omg.CORBA.Object ref,
                    +                                              ORB orb)
                    +        throws 
                    +            Exception
                    +    {
                    +        NamingContext nc = getNameService(orb);
                    +        nc.rebind(makeNameComponent(name), ref);
                    +        return ref;
                    +    }
                    +  
                    +    public static NameComponent[] makeNameComponent(String name)
                    +    {
                    +        Vector result = new Vector();
                    +        StringTokenizer tokens = new StringTokenizer(name, "/");
                    +        while (tokens.hasMoreTokens()) {
                    +            result.addElement(tokens.nextToken());
                    +        }
                    +        NameComponent path[] = new NameComponent[result.size()];
                    +        for (int i = 0; i < result.size(); ++i) {
                    +            path[i] = new NameComponent((String)result.elementAt(i), "");
                    +        }
                    +        return path;
                    +    }
                    +
                    +    public static NamingContext getNameService(ORB orb) throws Exception
                    +    {
                    +        return NamingContextHelper.narrow(
                    +            orb.resolve_initial_references(NameService));
                    +    }
                    +
                    +    public static void addORBInitializer( ORB orb, ORBInitializer init ) {
                    +
                    +        final ORBData odata = orb.getORBData() ;
                    +
                    +        // Add init to the end of a copy of the ORBInitializers
                    +        // from the ORBData.
                    +        final ORBInitializer[] oldOrbInits = odata.getORBInitializers() ;
                    +        final int newIndex = oldOrbInits.length ;
                    +        final ORBInitializer[] newOrbInits = new ORBInitializer[newIndex+1] ;
                    +        for (int ctr=0; ctr T getObject( ORB orb, String name, Class type ) {
                    +        try {
                    +            org.omg.CORBA.Object obj = resolve( name, orb ) ;
                    +            return type.cast( PortableRemoteObject.narrow( obj, type ) ) ;
                    +        } catch (Exception exc) {
                    +            throw new RuntimeException( exc ) ;
                    +        }
                    +    }
                    +
                    +    /** Return all objrefs of type T in the naming context identified by name.
                    +     * Limited to at most 1000 objrefs (to avoid writing more complex code).
                    +     */
                    +    public static  List getObjects( ORB orb, String name, Class type ) {
                    +        try {
                    +            org.omg.CORBA.Object obj = resolve( name, orb ) ;
                    +            NamingContext nc = NamingContextHelper.narrow( obj ) ;
                    +            BindingListHolder blh = new BindingListHolder() ;
                    +            BindingIteratorHolder bih = new BindingIteratorHolder() ;
                    +            nc.list( 1000, blh, bih ) ;
                    +            List result = new ArrayList() ;
                    +            for (Binding bind : blh.value) {
                    +                try {
                    +                    if (bind.binding_type.value() == BindingType._nobject) {
                    +                        org.omg.CORBA.Object elem = nc.resolve( bind.binding_name ) ;
                    +                        result.add( type.cast( PortableRemoteObject.narrow( elem,
                    +                            type ) ));
                    +                    }
                    +                } catch (Exception exc) {
                    +                    // elem was not an object of type type: ignore it.
                    +                }
                    +            }
                    +
                    +            return result ;
                    +        } catch (Exception exc) {
                    +            throw new RuntimeException( exc ) ;
                    +        }
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/lbq/LBControl.java b/test/src/share/classes/corba/lbq/LBControl.java
                    new file mode 100644
                    index 000000000..74621d50f
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/LBControl.java
                    @@ -0,0 +1,30 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.lbq ;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +/** Interface for a remote object used to control the software
                    + * load balancer.
                    + */
                    +public interface LBControl extends Remote {
                    +    /** After accepting numConnections, add port to the pool.
                    +     * Each call to add or remove is added to a queue of commands.
                    +     */
                    +    void add( int numConnections, int port ) throws RemoteException ;
                    +
                    +    /** After accepting numConnections, remove port from the pool.
                    +     * Each call to add or remove is added to a queue of commands.
                    +     */
                    +    void remove( int numConnections, int port ) throws RemoteException ;
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/lbq/Server.java b/test/src/share/classes/corba/lbq/Server.java
                    new file mode 100644
                    index 000000000..8a83973e0
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/Server.java
                    @@ -0,0 +1,114 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:54:09 by Harold Carr.
                    +// Last Modified : 2005 Oct 06 (Thu) 11:32:08 by Harold Carr.
                    +//
                    +
                    +package corba.lbq;
                    +
                    +import java.util.Properties;
                    +
                    +import org.omg.CORBA.Policy ;
                    +
                    +import org.omg.PortableServer.POA;
                    +import org.omg.PortableServer.Servant;
                    +import org.omg.PortableServer.LifespanPolicyValue;
                    +import org.omg.PortableServer.IdUniquenessPolicyValue;
                    +import org.omg.PortableServer.IdAssignmentPolicyValue;
                    +import org.omg.PortableServer.ImplicitActivationPolicyValue;
                    +import org.omg.PortableServer.ServantRetentionPolicyValue;
                    +import org.omg.PortableServer.RequestProcessingPolicyValue;
                    +
                    +import com.sun.corba.ee.spi.orb.ORB ;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public class Server
                    +{
                    +    private static final String baseMsg = Server.class.getName();
                    +    private static final String RootPOA = "RootPOA";
                    +    private static final long SERVER_RUN_LENGTH = 1000 * 60; // 1 minute
                    +
                    +    public static void main(String[] av)
                    +    {
                    +        try {
                    +            Properties props = new Properties();
                    +            // props.setProperty("com.sun.CORBA.ORBDebug","transport");
                    +
                    +            ORB orb = (ORB)org.omg.CORBA.ORB.init(av, props);
                    +
                    +            POA rootPOA = (POA) orb.resolve_initial_references("RootPOA");
                    +            Policy[] policies = new Policy[] {
                    +                rootPOA.create_lifespan_policy( 
                    +                    LifespanPolicyValue.PERSISTENT ),
                    +                rootPOA.create_id_uniqueness_policy( 
                    +                    IdUniquenessPolicyValue.UNIQUE_ID ),
                    +                rootPOA.create_id_assignment_policy( 
                    +                    IdAssignmentPolicyValue.USER_ID ),
                    +                rootPOA.create_implicit_activation_policy( 
                    +                    ImplicitActivationPolicyValue.NO_IMPLICIT_ACTIVATION ),
                    +                rootPOA.create_servant_retention_policy(
                    +                    ServantRetentionPolicyValue.RETAIN ),
                    +                rootPOA.create_request_processing_policy(
                    +                    RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY )
                    +            } ;
                    +
                    +            POA testPOA = rootPOA.create_POA( "testPOA", rootPOA.the_POAManager(), 
                    +                policies ) ;
                    +
                    +            rootPOA.the_POAManager().activate();
                    +
                    +            Servant servant = (Servant)
                    +                javax.rmi.CORBA.Util.getTie(new TestServant());
                    +
                    +            createWithServantAndBind(Common.ReferenceName, servant, 
                    +                                     testPOA, orb);
                    +
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Server is ready.");
                    +            System.out.println("--------------------------------------------");
                    +
                    +            Thread.sleep(SERVER_RUN_LENGTH);
                    +
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Server exiting correctly...");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(0);
                    +
                    +        } catch (Exception e) {
                    +            e.printStackTrace(System.out);
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("!!!! Server exiting INCORRECTLY...");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(1);
                    +        }
                    +    }
                    +
                    +    public static org.omg.CORBA.Object 
                    +        createWithServantAndBind (String  name,
                    +                                  Servant servant,
                    +                                  POA     poa,
                    +                                  ORB     orb)
                    +        throws
                    +            Exception
                    +    {
                    +        byte[] id = name.getBytes();
                    +        poa.activate_object_with_id(id, servant);
                    +        org.omg.CORBA.Object ref = poa.id_to_reference(id);
                    +        Common.rebind(name, ref, orb);
                    +        return ref;
                    +    }
                    +
                    +} 
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/lbq/ServerControl.java b/test/src/share/classes/corba/lbq/ServerControl.java
                    new file mode 100644
                    index 000000000..dccb03414
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/ServerControl.java
                    @@ -0,0 +1,40 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.lbq ;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +/** Interface for a remote object used to control a server. 
                    + */
                    +public interface ServerControl extends Remote {
                    +    /** Query the server to discover its port for use in LB
                    +     */
                    +    int getPort() throws RemoteException ;
                    +
                    +    /** Register the reporter with this server.  It is invoked
                    +     * every time the server handles a request.
                    +     */
                    +    void registerReportCallback( ServerReporter reporter ) throws RemoteException ;
                    +
                    +    /** Causes the server to start rejecting requests after numRequests have 
                    +     * been handled.
                    +     * setRejecting and clearRejecting can be queued.
                    +     */
                    +    void setRejecting( int numRequests ) throws RemoteException ;
                    +
                    +    /** Causes the server to stop rejecting requests after numRequests
                    +     * have been rejected.
                    +     * setRejecting and clearRejecting can be queued.
                    +     */
                    +    void clearRejecting(int numRequests ) throws RemoteException ;
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/lbq/ServerReporter.java b/test/src/share/classes/corba/lbq/ServerReporter.java
                    new file mode 100644
                    index 000000000..c70279ccc
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/ServerReporter.java
                    @@ -0,0 +1,25 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.lbq ;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +/** One of these is implemented by Orchestrator for each server instance and
                    + * registered with the server.
                    + */
                    +public interface ServerReporter extends Remote {
                    +    /** Report that the server is about to responds to a request
                    +     * with the given requestNumber as its argument.
                    +     */
                    +    void requestReceived( int requestNumber ) throws RemoteException ;
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/lbq/Test.java b/test/src/share/classes/corba/lbq/Test.java
                    new file mode 100644
                    index 000000000..353b87dfa
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/Test.java
                    @@ -0,0 +1,33 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:49:03 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:08:09 by Harold Carr.
                    +//
                    +
                    +package corba.lbq;
                    +
                    +import java.rmi.Remote;
                    +import java.rmi.RemoteException;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public interface Test
                    +    extends Remote
                    +{
                    +    public int echo(int x)
                    +        throws RemoteException;
                    +}
                    +
                    +// End of file.
                    +
                    +
                    diff --git a/test/src/share/classes/corba/lbq/TestServant.java b/test/src/share/classes/corba/lbq/TestServant.java
                    new file mode 100644
                    index 000000000..46714edf3
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/TestServant.java
                    @@ -0,0 +1,40 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:50:17 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:17:44 by Harold Carr.
                    +//
                    +
                    +package corba.lbq;
                    +
                    +import java.rmi.RemoteException;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +public class TestServant
                    +    extends PortableRemoteObject
                    +    implements Test
                    +{
                    +    public static final String baseMsg = TestServant.class.getName();
                    +
                    +    public TestServant()
                    +        throws RemoteException
                    +    {
                    +    }
                    +
                    +    public int echo(int x)
                    +        throws RemoteException
                    +    {
                    +        System.out.println(baseMsg + ".echo: " + x);
                    +        return x;
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/lbq/notes.txt b/test/src/share/classes/corba/lbq/notes.txt
                    new file mode 100644
                    index 000000000..2ddb26cd6
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/lbq/notes.txt
                    @@ -0,0 +1,151 @@
                    +#
                    +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    +#
                    +# This program and the accompanying materials are made available under the
                    +# terms of the Eclipse Distribution License v. 1.0, which is available at
                    +# http://www.eclipse.org/org/documents/edl-v10.php.
                    +#
                    +# SPDX-License-Identifier: BSD-3-Clause
                    +#
                    +
                    +Combined FOLB quiesce test with simulated HW loadbalancer
                    +
                    +Idea:
                    +
                    +Start up the following controllers:
                    +
                    +ORBD
                    +LB
                    +Server1
                    +Server2
                    +Server3
                    +Client
                    +Orchestrator
                    +
                    +The Client and Server controllers are very simple standard
                    +dynamic RMI-IIOP programs, using persistent POAs, that
                    +simply send requests and handle them, except that
                    +the servers each implement an object that controls whether
                    +they are rejecting requests or not.  The client implements
                    +an interface that tells it how many requests to send.
                    +
                    +Client has a combined plugin that includes:
                    +(from LB) NoConnectionCacheImpl
                    +(from retryplugin) RetryClientRequestInterceptor
                    +
                    +Server has a combined plugin that includes:
                    +(from LN) VirtualAddressAgentImpl
                    +(from retryplugin) RetryServerRequestInterceptor
                    +
                    +LB is basically the lb test LB class, but it also has an
                    +ORB and implements a control object.
                    +
                    +ORBD is only used for naming, as usual.
                    +
                    +The Orchestrator controls the test.  It uses naming to
                    +find everything else, then runs the test.
                    +
                    +Interfaces:
                    +
                    +// One of these is implemented in LB.  LB is started only with listener:
                    +// all ports are added.
                    +interface LBControl extends Remote {
                    +    // After receiving numConnections, add port to the pool.
                    +    // Each call to add or remove is added to a queue of commands.
                    +    void add( int numConnections, int port ) throws RemoteException ;
                    +
                    +    // After receiving numConnections, remove port from the pool.
                    +    // Each call to add or remove is added to a queue of commands.
                    +    void remove( int numConnections, int port ) throws RemoteException ;
                    +}
                    +
                    +// One of these is implemented by each server.
                    +interface ServerControl extends Remote {
                    +    // Query the server to discover its port for use in LB
                    +    int getPort() throws RemoteException ;
                    +
                    +    // Register the reporter with this server.  It is invoked
                    +    // every time the server handles a request.
                    +    void registerReportCallback( ServerReporter reporter ) throws RemoteException ;
                    +
                    +    // Causes the server to start rejecting requests after numRequests have 
                    +    // been handled.
                    +    // setRejecting and clearRejecting can be queued.
                    +    void setRejecting( int numRequests ) throws RemoteException ;
                    +
                    +    // Causes the server to stop rejecting requests after numRequests
                    +    // have been rejected.
                    +    // setRejecting and clearRejecting can be queued.
                    +    void clearRejecting(int numRequests ) throws RemoteException ;
                    +}
                    +
                    +// Implemented in Client
                    +interface ClientControl extends Remote {
                    +    void startSendingRequests( int numRequests ) throws RemoteException ;
                    +}
                    +
                    +// One of these is implemented by Orchestrator for each server instance and
                    +// registered with the server.
                    +interface ServerReporter extends Remote {
                    +    void requestReceived( int requestNumber ) throws RemoteException ;
                    +}
                    +
                    +Namespace:
                    +root
                    +    control (namespace)
                    +        LBControl
                    +        Client
                    +        servers (namespace)
                    +            // contains one objref for ServerControl for each server
                    +
                    +Note that all of these control objects are implemented with a separate
                    +ORB that does not use any of the various plugins that are being tested
                    +here.  I'll probably create a simple utility class for setting this up.
                    +
                    +Orchestrator operation:
                    +
                    +(Basic LB test)
                    +1. Orch queries name server to get all ServerControl objects 
                    +2. Orch creates a ServerReporter for each ServerControl and 
                    +   registers it
                    +3. Add each server to LBControl
                    +4. Tell Client to send 3*N requests
                    +5. Each server sends a message to orch when it handles a request
                    +6. Check that N messages were received from each server
                    +
                    +(Quiesce test)
                    +7. Orch tells Server2 to reject requests after handling N requests
                    +8. Orch tells Server2 to handle requests after rejecting M requests
                    +9. Orch tells LB to remove Server2 after 3*N+2*M connections
                    +10. Orch tells LB to add Server2 after 3*N+2*M+2*P connections
                    +11. Orch tells client to send 3*N+2*M+2*P+3*Q requests
                    +(Operation should be as follows:
                    +first 3*N requests: normal LB over 3 servers
                    +next 2*M requests: only server1 and server3 handle requests; server2
                    +    continuously rejects requests.  I think this will result in the
                    +    following behavior:
                    +        client invokes, LB to S1: handled
                    +        client invokes, LB to S2: forwarded back to self, so:
                    +            client invokes, LB to S3: handled
                    +        client invokes, LB to S1: handled
                    +    since each forwarded request should result in a new connection
                    +next 2*P requests: LB only sends requests to server1 and server3
                    +next 2*Q requests: LB to all servers again
                    +
                    +12. Orch should see: 
                    +    Server1 N+M+P+Q requests
                    +    Server2 N+Q requests
                    +    Server3 N+M+P+Q requests
                    +
                    +Do we need other tests?
                    +
                    +How do we manage control plane objects?
                    +
                    +Need a getControlPlaneORB() method that
                    +    guarantees no interference in creating transient objects.
                    +    
                    +Info to create:
                    +    orb
                    +    servant
                    +    remote interface type
                    +    namespace name
                    diff --git a/test/src/share/classes/corba/legacyorbclasses/Client.java b/test/src/share/classes/corba/legacyorbclasses/Client.java
                    new file mode 100644
                    index 000000000..d04abc7fc
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/legacyorbclasses/Client.java
                    @@ -0,0 +1,151 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2003 Dec 11 (Thu) 11:03:27 by Harold Carr.
                    +// Last Modified : 2003 Dec 19 (Fri) 10:36:14 by Harold Carr.
                    +//
                    +
                    +package corba.legacyorbclasses;
                    +
                    +import java.util.Properties;
                    +import corba.framework.Controller;
                    +import org.omg.CORBA.ORB;
                    +import org.omg.CosNaming.*;
                    +import org.omg.CosNaming.NamingContextPackage.*;
                    +import com.sun.corba.ee.spi.misc.ORBConstants;
                    +
                    +public class Client 
                    +{
                    +    public static final String baseMsg = Client.class.getName();
                    +    public static final String main = baseMsg + ".main";
                    +
                    +    public static final String ORBClassKey = 
                    +        "org.omg.CORBA.ORBClass";
                    +    public static final String ORBSingletonClassKey =
                    +        "org.omg.CORBA.ORBSingletonClass";
                    +
                    +    public static void main(String av[])
                    +    {
                    +        try {
                    +            // ORBSingletons
                    +            // Note: this negative test must come first, since you
                    +            // can only create one singleton in a JVM.
                    +            createORB(false, false,  "x", null);
                    +            createORB(true,  false,
                    +                      "com.sun.corba.ee.internal.corba.ORBSingleton",
                    +                      com.sun.corba.ee.internal.corba.ORBSingleton.class);
                    +
                    +            // FULL ORBs
                    +            createORB(false, true,  "x", null);         
                    +            createORB(true,  true,  
                    +                      "com.sun.corba.ee.impl.orb.ORBImpl",
                    +                      com.sun.corba.ee.impl.orb.ORBImpl.class);
                    +            createORB(true,  true,
                    +                      "com.sun.corba.ee.internal.Interceptors.PIORB",
                    +                      com.sun.corba.ee.internal.Interceptors.PIORB.class);
                    +            createORB(true,  true,  
                    +                      "com.sun.corba.ee.internal.POA.POAORB",
                    +                      com.sun.corba.ee.internal.POA.POAORB.class);
                    +            createORB(true,  true,  
                    +                      "com.sun.corba.ee.internal.iiop.ORB",
                    +                      com.sun.corba.ee.internal.iiop.ORB.class);
                    +
                    +            System.out.println("Test PASSED.");
                    +
                    +        } catch (Throwable t) {
                    +            System.out.println(main + ": unexpected exception: " + t);
                    +            System.out.println("Test FAILED.");
                    +            System.exit(1);
                    +        }
                    +        System.exit(Controller.SUCCESS);
                    +    }
                    +
                    +    private static void createORB(boolean shouldExist, 
                    +                                  boolean isFullORB,
                    +                                  String className,
                    +                                  Class clazz)
                    +        throws
                    +            Exception
                    +    {
                    +        ORB orb = null;
                    +        creating(className);
                    +        try {
                    +            if (isFullORB) {
                    +                System.getProperties()
                    +                    .setProperty(ORBClassKey, className);
                    +                // NOTE: without setting this explicitly it is getting
                    +                // the default and failing.  Not sure why this is needed
                    +                // in this test but not in others.
                    +                System.getProperties()
                    +                    .setProperty(ORBConstants.INITIAL_PORT_PROPERTY, "1049");
                    +                orb = ORB.init((String[])null, System.getProperties());
                    +            } else {
                    +                System.getProperties()
                    +                    .setProperty(ORBSingletonClassKey,className);
                    +                orb = ORB.init();
                    +            }
                    +
                    +            created(orb);
                    +            checkShouldNotExist(shouldExist, className);
                    +            checkType(clazz, orb);
                    +
                    +            // Do something to make sure the ORB works.
                    +
                    +            if (isFullORB) {
                    +                NamingContext nameService =
                    +                    NamingContextHelper.narrow(
                    +                        orb.resolve_initial_references("NameService"));
                    +                NameComponent nc = new NameComponent("FOO", "");
                    +                NameComponent path[] = { nc };
                    +                nameService.rebind(path, nameService);
                    +            } else {
                    +                orb.create_any();
                    +            }
                    +        } catch (Exception e) {
                    +            if (shouldExist) {
                    +                throw e;
                    +            }
                    +        }
                    +    }
                    +
                    +    public static void creating(String className)
                    +    {
                    +        System.out.println(baseMsg + ".createORB: creating: " + className);
                    +    }
                    +
                    +    public static void created(ORB orb)
                    +    {
                    +        System.out.println(baseMsg + ".createORB: created: " + orb);
                    +    }
                    +
                    +    public static void checkShouldNotExist(boolean shouldExist,
                    +                                           String className)
                    +        throws
                    +            Exception
                    +    {
                    +        if (! shouldExist) {
                    +            throw new Exception("should not exist: " + className);
                    +        }
                    +    }
                    +
                    +    public static void checkType(Class clazz, ORB orb)
                    +        throws
                    +            Exception
                    +    {
                    +        // If we get here we created an ORB as expected.
                    +        // Be sure it is the one we wanted to create.
                    +        if (! clazz.isInstance(orb)) {
                    +            throw new Exception("Expected: " + clazz + " got: " + orb);
                    +        }
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/legacyorbclasses/LegacyORBClassesTest.java b/test/src/share/classes/corba/legacyorbclasses/LegacyORBClassesTest.java
                    new file mode 100644
                    index 000000000..6dbd75dd1
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/legacyorbclasses/LegacyORBClassesTest.java
                    @@ -0,0 +1,44 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2003 Dec 11 (Thu) 10:59:34 by Harold Carr.
                    +// Last Modified : 2003 Dec 15 (Mon) 20:31:54 by Harold Carr.
                    +//
                    +
                    +package corba.legacyorbclasses;
                    +
                    +import corba.framework.Controller;
                    +import corba.framework.CORBATest;
                    +
                    +public class LegacyORBClassesTest
                    +    extends
                    +        CORBATest
                    +{
                    +    public static final String thisPackage =
                    +        LegacyORBClassesTest.class.getPackage().getName();
                    +
                    +    protected void doTest() throws Throwable {
                    +        Controller orbd   = createORBD();
                    +        orbd.start();
                    +
                    +        Controller client = createClient(thisPackage + ".Client");
                    +
                    +        client.start();
                    +        client.waitFor(120000);
                    +        client.stop();
                    +
                    +        orbd.stop();
                    +    }
                    +}
                    +
                    +// End of file.
                    +
                    +
                    diff --git a/test/src/share/classes/corba/messagetrace/Client.java b/test/src/share/classes/corba/messagetrace/Client.java
                    new file mode 100644
                    index 000000000..8a08bff4e
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/messagetrace/Client.java
                    @@ -0,0 +1,713 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.messagetrace  ;
                    +
                    +import java.util.Properties ;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +import javax.rmi.PortableRemoteObject ;
                    +import javax.rmi.CORBA.Util ;
                    +import javax.rmi.CORBA.Tie ;
                    +
                    +import java.nio.ByteBuffer ;
                    +
                    +import corba.util.TransportManagerUtil;
                    +import org.omg.CORBA.TypeCode ;
                    +import org.omg.CORBA.ValueMember ;
                    +import org.omg.CORBA.PUBLIC_MEMBER ;
                    +import org.omg.CORBA.PRIVATE_MEMBER ;
                    +
                    +// I have removed some weblogic test code for bug 5034649.
                    +// We need to check to see if we can include this, because
                    +// the test case relies on code supplied by BEA.
                    +// import weblogic.management.WebLogicObjectName ;
                    +// import weblogic.management.internal.WebLogicAttribute ;
                    +
                    +import javax.management.ObjectName ;
                    +import javax.management.Attribute ;
                    +
                    +import junit.framework.TestCase ;
                    +import junit.framework.Test ;
                    +import junit.framework.TestResult ;
                    +import junit.framework.TestSuite ;
                    +import junit.extensions.TestSetup ;
                    +
                    +import com.sun.corba.ee.spi.orb.ORB ;
                    +
                    +import com.sun.corba.ee.spi.transport.TransportManager ;
                    +import com.sun.corba.ee.spi.transport.MessageTraceManager ;
                    +import com.sun.corba.ee.spi.transport.MessageData ;
                    +
                    +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion ;
                    +
                    +import com.sun.corba.ee.impl.misc.ORBUtility ;
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +import com.sun.corba.ee.impl.protocol.giopmsgheaders.Message ;
                    +
                    +import com.sun.corba.ee.impl.encoding.CDRInputObject ;
                    +import org.glassfish.pfl.test.TestCaseTools;
                    +
                    +public class Client extends TestCase
                    +{
                    +    static ORB clientORB ;
                    +    static ORB serverORB ;
                    +    static TestInterface tester ;
                    +
                    +    static boolean debug ;
                    +
                    +    /** Remote interface used for testing
                    +     */
                    +    public interface TestInterface extends Remote
                    +    {
                    +        TypeCode testit( byte[] pad, TypeCode tc ) throws RemoteException ;
                    +
                    +        Object echo( byte[] pad, Object obj ) throws RemoteException ;
                    +
                    +        int twoArrays( byte[] one, byte[] two ) throws RemoteException ;
                    +
                    +        void setAttribute( ObjectName on, Attribute at ) throws RemoteException ;
                    +    }
                    +
                    +    /** Trivial implementation of the testing interface
                    +     */
                    +    public static class TestInterfaceImpl extends PortableRemoteObject 
                    +        implements TestInterface
                    +    {
                    +        public TestInterfaceImpl() throws RemoteException
                    +        {
                    +            super() ;
                    +        }
                    +
                    +        public TypeCode testit( byte[] pad, TypeCode tc ) throws RemoteException
                    +        {
                    +            return tc ;
                    +        }
                    +
                    +        public Object echo( byte[] pad, Object obj ) throws RemoteException
                    +        {
                    +            return obj ;
                    +        }
                    +
                    +        public int twoArrays( byte[] one, byte[] two ) throws RemoteException 
                    +        {
                    +            return one.length + two.length ;
                    +        }
                    +
                    +        public void setAttribute( ObjectName on, Attribute at ) throws RemoteException 
                    +        {
                    +        }
                    +    }
                    +    
                    +    // An extension of the TestSetup test decorator (that is,
                    +    // interceptor) that is used to initialize ORBs before the
                    +    // tests start, and clean the ORBs up after the test completes.
                    +    // Also sets up the tester remote object.
                    +    private static class ORBManager extends TestSetup
                    +    {
                    +        public ORBManager( Test test ) 
                    +        {
                    +            super( test ) ;
                    +        }
                    +
                    +        public void setUp()
                    +        {
                    +            // Use dynamic RMI-IIOP so we don't need a separate rmic run
                    +            System.setProperty( "com.sun.corba.ee.ORBUseDynamicStub", 
                    +                "true" ) ;
                    +            System.setProperty( "javax.rmi.CORBA.UtilClass",
                    +                "com.sun.corba.ee.impl.javax.rmi.CORBA.Util" ) ;
                    +            System.setProperty( "javax.rmi.CORBA.StubClass",
                    +                "com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl" ) ;
                    +            System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass",
                    +                "com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject" ) ;
                    +            System.setProperty( "org.omg.CORBA.ORBSingletonClass",
                    +                "com.sun.corba.ee.impl.orb.ORBSingleton" ) ;
                    +
                    +            TestInterfaceImpl servant = null ;
                    +
                    +            // Create an unconnected stub, and a corresponding Tie.
                    +            try {
                    +                servant = new TestInterfaceImpl() ;
                    +            } catch (RemoteException rex) {
                    +                rex.printStackTrace() ;
                    +                fail( "Unexpected remote exception " + rex ) ;
                    +            }
                    +
                    +            Tie tie = Util.getTie( servant ) ;
                    +            
                    +            // Set up client and server ORBs.
                    +            Properties props = new Properties() ;
                    +            props.setProperty( "org.omg.CORBA.ORBClass",
                    +                "com.sun.corba.ee.impl.orb.ORBImpl" ) ;
                    +            props.setProperty( "com.sun.corba.ee.transport.ORBDisableDirectByteBufferUse",
                    +                "true" ) ;
                    +            props.setProperty( "com.sun.corba.ee.transport.ORBAcceptorSocketType",
                    +                "Socket" ) ;
                    +            props.setProperty( "com.sun.corba.ee.transport.ORBConnectionSocketType",
                    +                "Socket" ) ;
                    +            serverORB = (ORB)ORB.init( new String[0], props ) ;
                    +            // props.setProperty( "com.sun.corba.ee.ORBDebug",
                    +                // "giop" ) ;
                    +            clientORB = (ORB)ORB.init( new String[0], props ) ;
                    +
                    +            // Connect the tie to the serverORB, which also connects the stub.
                    +            tie.orb( serverORB ) ;
                    +
                    +            TestInterface serverRef = null ;
                    +
                    +            try {
                    +                serverRef = (TestInterface)PortableRemoteObject.toStub( 
                    +                    servant ) ;
                    +            } catch (Exception exc) {
                    +                exc.printStackTrace() ;
                    +                fail( "Unexpected exception in toStub: " + exc ) ;
                    +            }
                    +
                    +            // Get a reference in the client ORB.  This will insure that
                    +            // we actually marshal the data.
                    +            String str = serverORB.object_to_string( 
                    +                (org.omg.CORBA.Object)serverRef ) ;
                    +            org.omg.CORBA.Object clientObj = clientORB.string_to_object( str ) ;
                    +            tester = (TestInterface)PortableRemoteObject.narrow(
                    +                clientObj, TestInterface.class ) ;
                    +        }
                    +
                    +        public void tearDown()
                    +        {
                    +            if (debug)
                    +                System.out.println( "Destroying ORBs" ) ;
                    +
                    +            clientORB.destroy() ;
                    +            serverORB.destroy() ;
                    +        }
                    +    }
                    +
                    +    private static final boolean DEBUG = false ;
                    +    // private static final int REP_COUNT = 1000 ;
                    +    // private List timedTests ;
                    +
                    +    private ValueMember makeValueMember( String name, TypeCode type, 
                    +        boolean isPublic ) 
                    +    {
                    +        return new ValueMember( name, "", "", "", type, null, 
                    +            isPublic ? PUBLIC_MEMBER.value : PRIVATE_MEMBER.value) ; 
                    +    }
                    +
                    +    /**
                    +    private TypeCode makeValueTypeCode( ORB orb )
                    +    {
                    +        String repoID = 
                    +            "RMI:weblogic.management.WebLogicObjectName:6488C1A74F9FA9EA:66076A3E2CDE" ;
                    +
                    +        String name = "weblogic.management.WebLogicObjectName" ;
                    +
                    +        TypeCode recursiveTypeCode  = orb.create_recursive_tc( repoID ) ;
                    +        TypeCode nullTypeCode       = orb.get_primitive_tc( TCKind.tk_null ) ;  
                    +        TypeCode booleanTypeCode    = orb.get_primitive_tc( TCKind.tk_boolean ) ;
                    +        TypeCode longTypeCode       = orb.get_primitive_tc( TCKind.tk_long ) ;
                    +
                    +        ValueMember[] members = new ValueMember[] {
                    +            makeValueMember( "hashCode",  longTypeCode,      false ),
                    +            makeValueMember( "isAdmin",   booleanTypeCode,   false ),
                    +            makeValueMember( "isConfig",  booleanTypeCode,   false ),
                    +            makeValueMember( "isRuntime", booleanTypeCode,   false ),
                    +            makeValueMember( "parent",    recursiveTypeCode, false ) 
                    +        } ;
                    +
                    +        TypeCode result = orb.create_value_tc(
                    +            repoID, name, VM_NONE.value, nullTypeCode, members ) ;
                    +
                    +        return result ;
                    +    }
                    +    **/
                    +
                    +    private byte[] makeBytes( int size )
                    +    {
                    +        byte[] result = new byte[size] ;
                    +        for (int ctr=0; ctr0) && args[0].equals( "-debug" ) ;
                    +
                    +        Client root = new Client() ;
                    +        TestResult result = junit.textui.TestRunner.run(root.suite()) ;
                    +
                    +        // reportTiming( System.out, root.timedTests ) ;
                    +
                    +        if (result.errorCount() + result.failureCount() > 0) {
                    +            System.out.println( "Error: failures or errrors in JUnit test" ) ;
                    +            System.exit( 1 ) ;
                    +        } else
                    +            System.exit( 0 ) ;
                    +    }
                    +
                    +    public Client()
                    +    {
                    +        super() ;
                    +        // timedTests = new ArrayList() ;
                    +    }
                    +
                    +    public Client( String name )
                    +    {
                    +        super( name ) ;
                    +        // timedTests = null ;
                    +    }
                    +
                    +
                    +    public static Test suite()
                    +    {
                    +        System.out.println( 
                    +            "==============================================================\n" +
                    +            "Testing Message Trace Manager\n" +
                    +            "==============================================================\n" 
                    +        ) ;
                    +
                    +        // TestSuite created only to include the ORBManager setup wrapper,
                    +        // which wraps the real TestSuite made from this class.
                    +        // This causes the ORBs for this test to be created before all
                    +        // tests run, and destroyed after all tests are completed.  
                    +        TestSuite main = new TestSuite( "main" ) ;
                    +        TestSuite ts = TestCaseTools.makeTestSuite( Client.class ) ;
                    +        main.addTest( new ORBManager( ts ) ) ;
                    +        return main ;
                    +    }
                    +
                    +    /* Simple-minded, inefficient algorithm for locating the first occurence
                    +     * of pattern (if any) in the buffer after the offset.
                    +     * Returns index >= offset, or -1 if no match is found.
                    +     */
                    +    private int findPattern( byte[] buffer, int offset, byte[] pattern )
                    +    {
                    +        int ctr=offset;
                    +        while (ctr= 0 ) ;
                    +            if (debug)
                    +                System.out.println( "firstIndex = " + firstIndex ) ;
                    +
                    +            // Search for 0xffffffffffff (the start of the indirection) after
                    +            // the typecode.
                    +            byte[] secondp = new byte[] { (byte)0xff, (byte)0xff, (byte)0xff, 
                    +                (byte)0xff, (byte)0xff, (byte)0xff } ;
                    +            int secondIndex = findPattern( buffer, firstIndex, secondp ) ;
                    +            assertTrue( "Could not find start of indirection", secondIndex >= 0 ) ;
                    +            if (debug)
                    +                System.out.println( "secondIndex = " + secondIndex ) ;
                    +
                    +            // Make sure that the offset is the difference
                    +            // between the index of the first pattern and the start
                    +            // of the offset in the second pattern.
                    +            int offset = getInt( buffer, secondIndex + 4 ) ;
                    +            if (debug)
                    +                System.out.println( "offset = " + offset ) ;
                    +
                    +            assertEquals( "Incorrect offset", firstIndex, secondIndex + 4 + offset ) ;
                    +        } catch (Exception exc) {
                    +            fail( "WebLogic test failed: " + exc ) ;
                    +            exc.printStackTrace() ;
                    +        }
                    +    }
                    +
                    +    private void paddedEchoTest( String testMsg,
                    +        Object data, int startSize, int endSize )
                    +    {
                    +        if (debug)
                    +            System.out.println( testMsg ) ;
                    +
                    +        for (int ctr=startSize; ctr<=endSize; ctr++) {
                    +            byte[] pad = makeBytes( ctr ) ;
                    +            Object result = null ;
                    +            
                    +            try {
                    +                result = tester.echo( pad, data ) ;
                    +            } catch (Exception exc) {
                    +                fail( "\tTest failed: " + exc + "with pad size = " + ctr ) ;
                    +                exc.printStackTrace() ;
                    +            }
                    +        }
                    +    }
                    +
                    +    public void testTypeCode()
                    +    {
                    +        TypeCode valueTypeCode = makeValueTypeCode( clientORB ) ;
                    +
                    +        paddedEchoTest( "Testing TypeCode", valueTypeCode, 700, 800 ) ;
                    +
                    +        // Now invoke testit with a variable size pad, to try and force
                    +        // alignment problems in the TypeCode indirection.
                    +        // With a GIOP fragment size of 1024, this test fails at
                    +        // pad sizes 749-752 + n*1024.  It fails because the typecode
                    +        // is marshalled inside a boxed value type using a chunked
                    +        // representation, and certain offsets force the last chunk in the
                    +        // fragment to end with the typecode, forcing a new chunk
                    +        // header between the typecode kind and the typecode body,
                    +        // which is an encapsulation.  This in turn causes the indirection
                    +        // value to be computed incorrectly, because the TypeCodeOutputStream
                    +        // cannot account for the extra length caused by the chunk header.
                    +        // This may be a bit difficult to fix.
                    +        //
                    +        // For now, we will just run this test for 747 and 748, since
                    +        // I don't have time to fix the other typecode problem.
                    +        final int lowerBound = 747 ;
                    +        final int upperBound = 749 ;    // set this to a larger value to
                    +                                        // reproduce bug. 
                    +        for (int ctr=lowerBound; ctr0) && args[0].equals( "-debug" ) ;
                    +
                    +        Client root = new Client() ;
                    +        TestResult result = junit.textui.TestRunner.run(Client.suite()) ;
                    +
                    +        if (result.errorCount() + result.failureCount() > 0) {
                    +            System.out.println( "Error: failures or errrors in JUnit test" ) ;
                    +            System.exit( 1 ) ;
                    +        } else {
                    +            System.exit(0);
                    +        }
                    +    }
                    +
                    +    public Client()
                    +    {
                    +        super() ;
                    +    }
                    +
                    +    public Client( String name )
                    +    {
                    +        super( name ) ;
                    +    }
                    +
                    +    public static Test suite()
                    +    {
                    +        System.out.println( 
                    +            "==============================================================\n" +
                    +            "Miscellaneous CORBA Tests\n" +
                    +            "==============================================================\n" 
                    +        ) ;
                    +
                    +        // TestSuite created only to include the ORBManager setup wrapper,
                    +        // which wraps the real TestSuite made from this class.
                    +        // This causes the ORBs for this test to be created before all
                    +        // tests run, and destroyed after all tests are completed.  
                    +        TestSuite main = new TestSuite( "main" ) ;
                    +        TestSuite ts = TestCaseTools.makeTestSuite( Client.class ) ;
                    +        main.addTest( new ORBManager( ts ) ) ;
                    +        return main ;
                    +    }
                    +
                    +    /** Test for bug 4919770: multiple ORBs share the same root MonitoredObject.
                    +      *
                    +    public void testMonitoringRootName()
                    +    {
                    +        for (int ctr=0; ctr Byte.MAX_VALUE) {
                    +            counter = 1;
                    +        }
                    +        return result ;
                    +    }
                    +
                    +    private static final Random gen = new Random() ;
                    +
                    +    private static final int BUF_SIZE = 160 ;
                    +    private static final int REP_COUNT = 10 ;
                    +    private static final int NUM_THREADS = 5 ;
                    +
                    +    private ByteBuffer getBuffer( int val, int len ) 
                    +    {
                    +        byte[] buff = new byte[len] ;
                    +        for (int ctr=0; ctr,Color> pair = 
                    +        new SPair,Color>(
                    +            new SPair( Color.RED, Color.BLUE ), Color.RED ) ;
                    +    
                    +    private ORB makeORBForEnumTest( boolean useEnumDesc ) {
                    +        String[] args = new String[0] ;
                    +        Properties props = new Properties() ;
                    +        props.setProperty( ORBConstants.USE_ENUM_DESC, 
                    +            Boolean.toString( useEnumDesc ) ) ;
                    +        ORB orb = ORB.class.cast( ORB.init( args, props ) ) ;
                    +        return orb ;
                    +    }
                    +
                    +    public void testEnumMarshalingUseEnumDesc() {
                    +        ORB orb = makeORBForEnumTest( true ) ;
                    +        enumMarshalingTest( orb ) ;
                    +    }
                    +
                    +    private static final List> ioannos = 
                    +        new ArrayList>() ;
                    +
                    +    static {
                    +        ioannos.add( CdrRead.class ) ;
                    +        ioannos.add( CdrWrite.class ) ;
                    +        ioannos.add( PrimitiveRead.class ) ;
                    +        ioannos.add( PrimitiveWrite.class ) ;
                    +        ioannos.add( ValueHandlerRead.class ) ;
                    +        ioannos.add( ValueHandlerWrite.class ) ;
                    +    }
                    +
                    +    private void traceOn() {
                    +        MethodMonitorFactory mmf = MethodMonitorFactoryDefaults.dprint() ;
                    +        for (Class cls : ioannos) {
                    +            MethodMonitorRegistry.register( cls, mmf ) ;
                    +        }
                    +    }
                    +
                    +    private void traceOff() {
                    +        for (Class cls : ioannos) {
                    +            MethodMonitorRegistry.register( cls, null ) ;
                    +        }
                    +    }
                    +
                    +    public void testEnumMarshaling() {
                    +        ORB orb = makeORBForEnumTest( false ) ;
                    +        // traceOn() ;
                    +        try {
                    +            enumMarshalingTest( orb ) ;
                    +        } finally {
                    +            // traceOff() ;
                    +        }
                    +    }
                    +
                    +    private static final boolean SIMPLE = false ;
                    +
                    +    public void enumMarshalingTest( ORB orb ) {
                    +        try {
                    +            OutputStream os = OutputStream.class.cast( orb.create_output_stream() ) ;
                    +
                    +
                    +            if (SIMPLE) {
                    +                os.write_value( Color.BLUE ) ;
                    +            } else {
                    +                os.write_value( pair ) ;
                    +                os.write_value( colors ) ;
                    +                os.write_value( Color.BLUE ) ;
                    +                os.write_value( Coin.NICKEL ) ;
                    +                os.write_value( colors ) ;
                    +                os.write_value( TestEnum.HELLO ) ;
                    +            }
                    +
                    +            InputStream is = InputStream.class.cast( os.create_input_stream() ) ;
                    +
                    +            if (SIMPLE) {
                    +                System.out.println( "Testing BLUE" ) ;
                    +                Color shouldBeBlue = Color.class.cast( is.read_value() ) ;
                    +                assertSame( "Result of read_value is not the expected value",
                    +                    shouldBeBlue, Color.BLUE ) ;
                    +            } else {
                    +                System.out.println( "Testing pair" ) ;
                    +                SPair,Color> shouldBePair = 
                    +                    (SPair,Color>)(is.read_value()) ;
                    +
                    +                assertSame( "pair.first().first()", shouldBePair.first().first(),
                    +                    pair.first().first() ) ;
                    +
                    +                assertSame( "pair.first().second()", shouldBePair.first().second(),
                    +                    pair.first().second() ) ;
                    +
                    +                assertSame( "pair.second()", shouldBePair.second(),
                    +                    pair.second() ) ;
                    +
                    +                System.out.println( "Testing colors" ) ;
                    +                Color[] shouldBeColors = (Color[])is.read_value() ;
                    +                for (int ctr=0; ctr0 and r>1 (by configuration).
                    +    // Let S(a,n)= Sum(k-0,k=n) a*r^k (the standard geometric progression.
                    +    // The we know (by the usual multiply Sn by r argument) that S(n)=a * (r^(n+1)-1)/(r-1).
                    +    // But more importantly here the geometric series satifies the equation
                    +    // S(a,n+1) = r*S(a,n) + a.  So, if we know that S(n) tm = orb.makeTimerManager(
                    +            TimingPoints.class ) ;
                    +        final TimingPoints tp = tm.points() ;
                    +        final Timer nextTime = tp.ContactInfoListIteratorImpl__next() ;
                    +
                    +        // per-event data (all events)
                    +        boolean firstEvent = true ;
                    +        long startTime = 0 ;
                    +
                    +        // per-next event data (only nextTime events)
                    +        boolean firstNextEvent = true ;
                    +        long currentWait = initialTimeout ; // each wait after first must be in [c,1.1*c]
                    +        long currentTime = 0 ; // duration of current nextTime event in milliseconds
                    +
                    +        for (TimerEvent te : leh) {
                    +            if (firstEvent) {
                    +                startTime = te.time() ;
                    +                firstEvent = false ;
                    +            }
                    +
                    +            if (te.timer() == nextTime) {
                    +                if (te.type() == TimerEvent.TimerEventType.ENTER) {
                    +                    currentTime = te.time() ;
                    +                } else { // EXIT
                    +                    final long duration = (te.time()-currentTime)/1000000 ;
                    +
                    +                    if (firstNextEvent) {
                    +                        assertTrue( duration <= 1 ) ; // assume first wait is <= 1 msec.
                    +
                    +                        firstNextEvent = false ;
                    +                    } else {
                    +                        assertTrue( "Expected duration " + duration 
                    +                            + " to be at least " + currentWait, duration >= currentWait ) ;
                    +
                    +                        final long upperBound = (currentWait * 150)/100 ;
                    +                        assertTrue( "Expected duration " + duration 
                    +                            + " to be less than " + upperBound, duration < upperBound ) ;
                    +
                    +                        currentWait = (backoff * currentWait)/100 ;
                    +                    }
                    +                }
                    +            }
                    +
                    +            currentTime = te.time() ; // keep track of last time for overall duration
                    +        }
                    +
                    +        // Check that overall duration is within range.
                    +        final long totalTime = (currentTime - startTime)/1000000 ;
                    +
                    +        assertTrue( totalTime > maxWait ) ;
                    +        assertTrue( totalTime < ((backoff*maxWait)/100 + initialTimeout) ) ;
                    +    } */
                    +
                    +    // Create a corbaloc URL that points to nowhere, then attempt to 
                    +    // narrow and invoke on it.  This will fail, but we are interested
                    +    // in studying the ORB retry behavior.
                    +    /*
                    +    public void testConnectionFailure( boolean useSticky ) {
                    +        final String url = "corbaloc:iiop:1.2@ThisHostDoesNotExist:5555/NameService" ;
                    +
                    +        final Properties props = new Properties() ;
                    +        props.setProperty( "org.omg.CORBA.ORBClass",
                    +            "com.sun.corba.ee.impl.orb.ORBImpl" ) ;
                    +
                    +        if (useSticky) {
                    +            props.setProperty( 
                    +                ORBConstants.IIOP_PRIMARY_TO_CONTACT_INFO_CLASS_PROPERTY,
                    +                IIOPPrimaryToContactInfoImpl.class.getName() ) ;
                    +        }
                    +
                    +        final int expectedInitialTimeout = 50 ;
                    +        final int expectedMaxWait = 2000 ;
                    +        final int expectedBackoff = 100 ;
                    +        final String timeoutString = expectedInitialTimeout + ":" 
                    +            + expectedMaxWait + ":" + expectedBackoff ;
                    +
                    +        props.setProperty( ORBConstants.TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY, 
                    +            timeoutString ) ;
                    +        props.setProperty( ORBConstants.TIMING_POINTS_ENABLED, "true" ) ;
                    +        final ORB orb = (ORB)ORB.init( new String[0], props ) ;
                    +
                    +        final TcpTimeouts timeouts = orb.getORBData().getTransportTcpConnectTimeouts() ;
                    +        assertEquals( timeouts.get_initial_time_to_wait(), expectedInitialTimeout ) ;
                    +        assertEquals( timeouts.get_max_time_to_wait(),     expectedMaxWait ) ;
                    +        assertEquals( timeouts.get_backoff_factor(),       expectedBackoff + 100 ) ;
                    +        
                    +        TimerManager tm = orb.makeTimerManager(
                    +            TimingPoints.class ) ;
                    +        LogEventHandler leh = tm.factory().makeLogEventHandler( "ContactInfoListIterator" ) ;
                    +        tm.controller().register( leh ) ;
                    +        TimingPoints tp = tm.points() ;
                    +        TimerGroup cili = tm.factory().makeTimerGroup( "cili", 
                    +            "TimerGroup for ContactInfoListIteratorImpl" ) ;
                    +        cili.add( tp.ContactInfoListIteratorImpl__hasNext() ) ;
                    +        cili.add( tp.ContactInfoListIteratorImpl__next() ) ;
                    +        cili.add( tp.ContactInfoListIteratorImpl__reportException() ) ;
                    +        cili.add( tp.ContactInfoListIteratorImpl__reportAddrDispositionRetry() ) ;
                    +        cili.add( tp.ContactInfoListIteratorImpl__reportRedirect() ) ;
                    +        cili.add( tp.ContactInfoListIteratorImpl__reportSuccess() ) ;
                    +
                    +        try {
                    +            cili.enable() ;
                    +            org.omg.CORBA.Object obj = orb.string_to_object( url ) ;
                    +            NamingContextExt nc = NamingContextExtHelper.narrow( obj ) ;
                    +            nc.resolve_str( "this/does/not/exist" ) ;
                    +            cili.disable() ;
                    +
                    +        } catch (Exception exc) {
                    +            if (debug) {
                    +                System.out.println( "Received exception: " ) ;
                    +                exc.printStackTrace() ;
                    +            }
                    +        } finally {
                    +            if (debug) {
                    +                leh.display( System.out, "Connection timer log contents" ) ;
                    +                validateLogEvents( orb, leh, expectedInitialTimeout, expectedMaxWait,
                    +                    expectedBackoff+100 ) ;
                    +                orb.destroy() ;
                    +            }
                    +        }
                    +    }
                    +
                    +
                    +    public void DONTRUNtestConnectionFailureWithStickyManager() {
                    +        testConnectionFailure( true ) ;
                    +    }
                    +
                    +    public void DONTRUNtestConnectionFailureWithoutStickyManager() {
                    +        testConnectionFailure( false ) ;
                    +    }
                    +    */
                    +
                    +    private static void displayTimerFactories() {
                    +        System.out.println( "Current TimerFactory instances:" ) ;
                    +        for (TimerFactory tf : TimerFactoryBuilder.contents()) {
                    +            System.out.println( "\t" + tf ) ;
                    +        }
                    +    }
                    +
                    +    private static TimerFactory findTimerFactoryForORB( String orbId ) {
                    +        for (TimerFactory tf : TimerFactoryBuilder.contents()) {
                    +            if (tf.name().contains( orbId )) {
                    +                return tf;
                    +            }
                    +        }
                    +
                    +        return null ;
                    +    }
                    +
                    +
                    +    /* TODO rewrite this test so it doesn't need the enhance functionality. - REG
                    +    public void testORBInit() {
                    +        final String orbId = "OrbOne" ;
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "org.omg.CORBA.ORBClass",
                    +            "com.sun.corba.ee.impl.orb.ORBImpl" ) ;
                    +        props.setProperty( "org.omg.CORBA.ORBId", orbId ) ;
                    +        ORB lorb = null ;
                    +        
                    +        for (int ctr=0; ctr<2; ctr++) {
                    +            lorb = (ORB)ORB.init( new String[0], props ) ;
                    +            // If we don't create a TimerManager, there won't be a 
                    +            // TimerFactory.
                    +            TimerManager tm =
                    +                lorb.makeTimerManager( TimingPoints.class ) ;
                    +
                    +            // displayTimerFactories() ;
                    +            assertTrue( findTimerFactoryForORB(orbId) != null ) ;
                    +
                    +            lorb.destroy() ;
                    +            // displayTimerFactories() ;
                    +            tm.destroy() ; // ORB.destroy won't clean this up!
                    +            assertTrue( findTimerFactoryForORB(orbId) == null ) ;
                    +        }
                    +    }   */
                    +
                    +    private void print2( String actual, String expected ) {
                    +        assertEquals( actual, expected ) ;
                    +        // System.out.println( "actual=" + actual + ",expected=" + expected ) ;
                    +    }
                    +
                    +    public void testOperationTracer() {
                    +        System.out.println( "Testing OperationTracer" ) ;
                    +        long time = System.currentTimeMillis() ;
                    +        OperationTracer.enable() ;
                    +        OperationTracer.finish() ;
                    +        print2( OperationTracer.getAsString(), "" ) ;
                    +        OperationTracer.begin( "Initial" ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:" ) ;
                    +        OperationTracer.startReadValue( "Foo" ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Foo" ) ;
                    +        OperationTracer.readingField( "a" ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Foo.a" ) ;
                    +        OperationTracer.readingField( "b" ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Foo.b" ) ;
                    +        OperationTracer.endReadValue() ;
                    +        print2( OperationTracer.getAsString(), "Initial:" ) ;
                    +        OperationTracer.startReadArray( "Bar", 27 ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Bar<27>" ) ;
                    +        OperationTracer.readingIndex( 0 ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Bar<27>[0]" ) ;
                    +        OperationTracer.readingIndex( 1 ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Bar<27>[1]" ) ;
                    +        OperationTracer.startReadValue( "Baz" ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Bar<27>[1],Baz" ) ;
                    +        OperationTracer.readingField( "x1" ) ;
                    +        print2( OperationTracer.getAsString(), "Initial:Bar<27>[1],Baz.x1" ) ;
                    +        OperationTracer.endReadValue() ;
                    +        print2( OperationTracer.getAsString(), "Initial:Bar<27>[1]" ) ;
                    +        OperationTracer.endReadArray() ;
                    +        print2( OperationTracer.getAsString(), "Initial:" ) ;
                    +        OperationTracer.finish() ;
                    +        print2( OperationTracer.getAsString(), "" ) ;
                    +        double elapsed = (time - System.currentTimeMillis())/1000 ;
                    +        System.out.println( 
                    +            "OperationTracer test complete in " + elapsed + " milliseconds" ) ;
                    +    }
                    +
                    +    public void test5161() {
                    +        System.out.println( "Running test for issue 5161" ) ;
                    +        BuckPasserAL bpal = new BuckPasserAL() ;
                    +        bpal.add( new Buck( "The Buck" ) ) ;
                    +        BuckPasserV bpv = new BuckPasserV() ;
                    +        bpv.add( new Buck( "The Buck" ) ) ;
                    +
                    +        OutputStream out = (OutputStream)orb.create_output_stream();
                    +
                    +        out.write_value(bpal) ;
                    +        out.write_value(bpv) ;
                    +
                    +        InputStream in = (InputStream)out.create_input_stream();
                    +
                    +        BuckPasserAL bpal2 = (BuckPasserAL)in.read_value() ;
                    +        BuckPasserV bpv2 = (BuckPasserV)in.read_value() ;
                    +
                    +        assertTrue( bpal2.equals( bpal ) ) ;
                    +        assertTrue( bpv2.equals( bpv ) ) ;
                    +    }
                    +
                    +    public void testClassMarshaling() {
                    +        System.out.println( "Running test for serialization of primitive classes" ) ;
                    +
                    +        Object[] arr = {
                    +            boolean.class,
                    +            byte.class,
                    +            Byte.class,
                    +            short.class,
                    +            int.class,
                    +            float.class,
                    +            long.class,
                    +            double.class,
                    +            char.class,
                    +            this.getClass() 
                    +        } ;
                    +
                    +        OutputStream out = (OutputStream)orb.create_output_stream();
                    +        out.write_value( arr ) ;
                    +        InputStream in = (InputStream)out.create_input_stream() ;
                    +        Object[] result = (Object[])in.read_value() ;
                    +
                    +        int errorCount = 0 ;
                    +        for (int ctr=0; ctr 0) {
                    +            fail( "Class marshaling test failed with " + errorCount + " errors" ) ;
                    +        }
                    +    }
                    +
                    +    public static abstract class WebContent implements Serializable {
                    +        long id = 42 ;
                    +
                    +        java.util.Set extractFieldSet = null ;
                    +        java.util.Set linkSet = null ;
                    +        Object stats = null ;
                    +        java.lang.Long wcmsNodeId = Long.valueOf(716368 ) ;
                    +        java.lang.String wcmsPath = "/tag/destination/US/CA/075/san-francisco.xml" ;
                    +
                    +        private final void writeObject(java.io.ObjectOutputStream os ) throws IOException {
                    +            os.defaultWriteObject() ;
                    +        }
                    +    }
                    +
                    +    public static class Trip extends WebContent {
                    +        int clientId = 2 ;
                    +        long id = 23900 ;
                    +        boolean isActive = false ;
                    +        int lengthDays = 12 ;
                    +        int version = 232 ;
                    +        char visibilityCode = 'A' ;
                    +
                    +        Date createData = new Date() ;
                    +        String description = "a description of the trip" ;
                    +        Destination dest = new Destination() ;
                    +        String destinationText = "some airport and hotel" ;
                    +        String name = "John Doe" ;
                    +        Object member = null ;
                    +        Object stats = null ;
                    +        Date startDate = new Date() ;
                    +        Date updatedDate = new Date() ;
                    +        Object updatedBy = null ;
                    +
                    +        private final void writeObject( ObjectOutputStream os ) throws IOException {
                    +           os.defaultWriteObject() ;
                    +        }
                    +    }
                    +    
                    +    public static class Destination implements Serializable {
                    +        int typeCode = 4 ;
                    +        Object airport = null ;
                    +        String featuresCode = "a Feature" ;
                    +        String fullName = "Full name" ;
                    +        Point geoPoint = new Point() ;
                    +        String name = "name" ;
                    +
                    +        private final void writeObject( ObjectOutputStream os ) throws IOException {
                    +            os.defaultWriteObject() ;
                    +        }
                    +    }
                    +
                    +    public static class Geometry implements Serializable {
                    +        int dimension = 2 ;
                    +        boolean haveMeasure = true ;
                    +        int srid ;
                    +        int type = 1 ;
                    +    }
                    +
                    +    public static class Point extends Geometry {
                    +        double m = 1.0 ;
                    +        double x = -23.343 ;
                    +        double y = 102.2325446 ;
                    +        double z = 100.23 ;
                    +    }
                    +
                    +    public void testTrip() {
                    +        try {
                    +            System.out.println( "test case testTrip" ) ;          
                    +            Trip trip = new Trip() ;
                    +
                    +            OutputStream os = (OutputStream)orb.create_output_stream() ;
                    +            os.write_value( trip ) ;
                    +            InputStream is = (InputStream)os.create_input_stream() ;
                    +            Trip newTrip = (Trip)is.read_value() ;
                    +            //Assert.assertEquals( lid, newLid ) ;
                    +        } catch (Exception exc) {
                    +            exc.printStackTrace() ;
                    +            fail( exc.toString() ) ;
                    +        }
                    +    }
                    +
                    +    public void testCorbaname() {
                    +        try {
                    +            String[] args = new String[0] ;
                    +            Properties props = new Properties() ;
                    +            orb = ORB.class.cast( ORB.init( args, props ) ) ;
                    +
                    +            final String test = 
                    +                "corbaname:iiop:1.2@192.168.178.1:3700#ejb/XXServiceBean" ;
                    +
                    +            // orb.string_to_object( test ) ;
                    +
                    +            final String test2 = 
                    +                "corbaname:iiop:evolve300.evolve.local:3920#java:global/ferris-bank-business-services/account/AccountServiceBean__3_x_Internal_RemoteBusinessHome__" ;
                    +
                    +            orb.string_to_object( test2 ) ;
                    +        } finally {
                    +            if (orb != null)
                    +                orb.destroy() ;
                    +        }
                    +    }
                    +
                    +    private interface ETest extends Remote {
                    +        int echo( int arg ) throws RemoteException ;
                    +    }
                    +    
                    +    private static class ETestImpl extends PortableRemoteObject implements ETest {
                    +        ETestImpl() throws RemoteException {
                    +            super() ;
                    +        }
                    +
                    +        public int echo( int arg ) { return arg ; }
                    +    }
                    +
                    +    private static class TestServantLocator extends LocalObject
                    +        implements ServantLocator {
                    +
                    +        private final ORB orb ;
                    +        private final Servant servant ;
                    +
                    +        public TestServantLocator( ORB orb ) {
                    +            this.orb = orb ;
                    +            ETestImpl impl = null ;
                    +            try {
                    +                impl = new ETestImpl() ;
                    +            } catch (Exception exc) {
                    +                // do nothing
                    +            }
                    +            Tie tie = orb.getPresentationManager().getTie() ;
                    +            tie.setTarget( impl ) ;
                    +            servant = Servant.class.cast( tie ) ;
                    +        }
                    +
                    +        public synchronized Servant preinvoke( byte[] oid, POA adapter,
                    +            String operation, CookieHolder the_cookie ) throws ForwardRequest {
                    +            return servant ;
                    +        }
                    +
                    +        public void postinvoke( byte[] oid, POA adapter,
                    +            String operation, Object the_cookie, Servant the_servant ) {
                    +        }
                    +    }
                    +
                    +    public void testTypeCode() {
                    +        System.out.println( "Test case testTypeCode" ) ;
                    +        try {
                    +            final String[] args = new String[0] ;
                    +            final Properties props = new Properties() ;
                    +            props.setProperty( ORBConstants.RFM_PROPERTY, "1" ) ;
                    +            props.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ;
                    +            props.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY,
                    +                "300" ) ;
                    +            props.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY,
                    +                "3755" ) ;
                    +            orb = ORB.class.cast( ORB.init( args, props ) ) ;
                    +
                    +            // Just get some object referece for testing
                    +            final ServantLocator locator = new TestServantLocator( orb ) ;
                    +
                    +            ReferenceFactoryManager rfm = null ;
                    +
                    +            try {
                    +                rfm = ReferenceFactoryManager.class.cast(
                    +                    orb.resolve_initial_references( "ReferenceFactoryManager" )) ;
                    +                } catch (Exception exc) {
                    +                    // do nthing
                    +                }
                    +            rfm.activate() ;
                    +
                    +            final PresentationManager pm = 
                    +                com.sun.corba.ee.spi.orb.ORB.getPresentationManager() ;
                    +            String repositoryId ;
                    +
                    +            try {
                    +                repositoryId = pm.getRepositoryId( new ETestImpl() ) ;
                    +            } catch (Exception exc) {
                    +                throw new RuntimeException( exc ) ;
                    +            }
                    +        
                    +            final List policies = new ArrayList() ;
                    +            final ReferenceFactory rf = rfm.create( "factory", repositoryId, 
                    +                policies, locator ) ;
                    +
                    +            // arbitrary
                    +            final byte[] oid = new byte[] { 0, 3, 5, 7 } ;
                    +
                    +            final org.omg.CORBA.Object ref = rf.createReference( oid ) ;
                    +
                    +            final Any any = orb.create_any() ;
                    +            final ForwardRequest fr = new ForwardRequest(ref) ;
                    +
                    +            // The whole point of this test
                    +            ForwardRequestHelper.insert(any, fr) ;
                    +        } finally {
                    +            if (orb != null) {
                    +                orb.destroy() ;
                    +            }
                    +        }
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/misc/MiscTest.java b/test/src/share/classes/corba/misc/MiscTest.java
                    new file mode 100644
                    index 000000000..cebc3e82c
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/misc/MiscTest.java
                    @@ -0,0 +1,30 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.misc;
                    +
                    +import test.Test;
                    +import corba.framework.*;
                    +import java.util.*;
                    +
                    +public class MiscTest extends CORBATest
                    +{
                    +    protected void doTest() throws Throwable
                    +    {
                    +        Controller client = createClient( "corba.misc.Client" ) ;
                    +
                    +        client.start();
                    +
                    +        client.waitFor(120000);
                    +
                    +        client.stop();
                    +    }
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/mixedorb/Client.java b/test/src/share/classes/corba/mixedorb/Client.java
                    new file mode 100644
                    index 000000000..4df2cd1ff
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/mixedorb/Client.java
                    @@ -0,0 +1,227 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.mixedorb;
                    +
                    +import java.util.Properties ;
                    +import java.util.Hashtable ;
                    +
                    +import java.rmi.RemoteException ;
                    +
                    +import javax.rmi.CORBA.Util ;
                    +import javax.rmi.CORBA.Tie ;
                    +
                    +import javax.naming.InitialContext ;
                    +
                    +import com.sun.corba.ee.spi.JndiConstants;
                    +import org.omg.CORBA.ORB ;
                    +
                    +import org.testng.TestNG ;
                    +import org.testng.Assert ;
                    +import org.testng.annotations.Test ;
                    +import org.testng.annotations.Configuration ;
                    +import org.testng.annotations.ExpectedExceptions ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService ;
                    +
                    +import static corba.framework.PRO.* ;
                    +
                    +public class Client {
                    +    private ORB clientORB ;
                    +    private ORB serverORB ;
                    +
                    +    private static final String TEST_REF_NAME = "testref" ;
                    +    private static final String SERVER_NAME = "fromServer" ;
                    +    private static final String CLIENT_NAME = "fromClient" ;
                    +    private static final String PORT_NUM = "3874" ;
                    +
                    +    // Make sure this is unaffected by the rename.
                    +    // The whole point of this test is to work with both the
                    +    // se and ee ORBs.
                    +    private String SE_BASE = "com.sun.corba." + "se." ;
                    +
                    +    // This will be renamed, if we are renaming.
                    +    private String RENAMED_BASE = "com.sun.corba.ee." ;
                    +
                    +    private void setSystemProperties( String base ) {
                    +        // Set the RMI-IIOP delegates and the singleton according to base.      
                    +        System.setProperty( "javax.rmi.CORBA.UtilClass",
                    +            base + "impl.javax.rmi.CORBA.Util" ) ;
                    +        System.setProperty( "javax.rmi.CORBA.StubClass",
                    +            base + "impl.javax.rmi.CORBA.StubDelegateImpl" ) ;
                    +        System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass",
                    +            base + "impl.javax.rmi.PortableRemoteObject" ) ;
                    +
                    +        // We will only use dynamic RMI-IIOP for this test.
                    +        // And only for the EE ORB: the SE ORB uses a slightly different
                    +        // property name.
                    +        System.out.println( "Setting property " + ORBConstants.USE_DYNAMIC_STUB_PROPERTY 
                    +            + " to true" ) ;
                    +        System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ;
                    +
                    +        // Use the J2SE ic provider
                    +        System.setProperty( "java.naming.factory.initial", 
                    +            JndiConstants.COSNAMING_CONTEXT_FACTORY ) ;
                    +    }
                    +
                    +    // We need to set up the client and server ORBs, and start a transient
                    +    // name server that runs on the server ORB, with the client ORB referring
                    +    // to the server ORB's name service.
                    +    private ORB makeORB( String base, boolean isServer) {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "org.omg.CORBA.ORBClass", base + "impl.orb.ORBImpl" ) ;
                    +        props.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, "localhost" ) ;
                    +        props.setProperty( ORBConstants.INITIAL_PORT_PROPERTY, PORT_NUM ) ;
                    +        props.setProperty( ORBConstants.ALLOW_LOCAL_OPTIMIZATION, "true" ) ;
                    +
                    +        if (isServer) {
                    +            props.setProperty( ORBConstants.ORB_ID_PROPERTY, "serverORB" ) ;
                    +            props.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, PORT_NUM ) ;
                    +            props.setProperty( ORBConstants.SERVER_HOST_PROPERTY, "localhost" ) ;
                    +            props.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, "300" ) ;
                    +        } else {
                    +            props.setProperty( ORBConstants.ORB_ID_PROPERTY, "clientORB" ) ;
                    +        }
                    +
                    +        ORB orb = ORB.init( new String[0], props ) ;
                    +
                    +        if (isServer) {
                    +            new TransientNameService( 
                    +                com.sun.corba.ee.spi.orb.ORB.class.cast(orb) ) ;
                    +        }
                    +
                    +        return orb ;
                    +    }
                    +
                    +    private Echo makeServant( String name ) {
                    +        try {
                    +            return new EchoImpl( name ) ;
                    +        } catch (RemoteException rex) {
                    +            Assert.fail( "Unexpected remote exception " + rex ) ;
                    +            return null ; // never reached
                    +        }
                    +    }
                    +
                    +    private void doServer( ORB orb ) {
                    +        try {
                    +            Hashtable env = new Hashtable() ;
                    +            env.put( "java.naming.corba.orb", orb ) ;
                    +            InitialContext ic = new InitialContext( env ) ;
                    +
                    +            Echo servant = makeServant( SERVER_NAME ) ;
                    +            Tie tie = Util.getTie( servant ) ;
                    +            tie.orb( orb ) ;
                    +
                    +            Echo ref = toStub( servant, Echo.class ) ;
                    +            ic.bind( TEST_REF_NAME, ref ) ;
                    +        } catch (Exception exc) {
                    +            System.out.println( "Caught exception " + exc ) ;
                    +            exc.printStackTrace() ;
                    +            System.exit( 1 ) ;
                    +        }
                    +    }
                    +
                    +    private void doClient( ORB orb ) {
                    +        try {
                    +            Hashtable env = new Hashtable() ;
                    +            env.put( "java.naming.corba.orb", orb ) ;
                    +            InitialContext ic = new InitialContext( env ) ;
                    +
                    +            Echo servant = makeServant( CLIENT_NAME ) ;
                    +            Tie tie = Util.getTie( servant ) ;
                    +            tie.orb( orb ) ;
                    +
                    +            Echo ref = toStub( servant, Echo.class ) ;
                    +
                    +            Echo sref = narrow( ic.lookup( TEST_REF_NAME ), Echo.class ) ;
                    +            Assert.assertEquals( sref.name(), SERVER_NAME ) ;
                    +
                    +            Echo rref = sref.say( ref ) ;
                    +            Assert.assertEquals( rref.name(), CLIENT_NAME ) ;
                    +
                    +            Echo r2ref = rref.say( sref ) ;
                    +            Assert.assertEquals( r2ref.name(), SERVER_NAME ) ;
                    +
                    +            Echo ref2 = ref.say( ref ) ;
                    +            Assert.assertEquals( ref2.name(), ref.name() ) ;
                    +        } catch (Exception exc) {
                    +            System.out.println( "Caught exception " + exc ) ;
                    +            exc.printStackTrace() ;
                    +            System.exit( 1 ) ;
                    +        }
                    +    }
                    +
                    +    @Configuration( beforeTest = true ) 
                    +    public void setUp() {
                    +        setSystemProperties( RENAMED_BASE ) ;
                    +        serverORB = makeORB( RENAMED_BASE, true ) ;
                    +        // This should be SE_BASE 
                    +        clientORB = makeORB( SE_BASE, false ) ;
                    +
                    +        try {
                    +            serverORB.resolve_initial_references( "NameService" ) ;
                    +
                    +            // Make sure that the FVD codebase IOR is not shared between
                    +            // multiple ORBs in the value handler, because that causes
                    +            // errors in the JDK ORB.
                    +            com.sun.corba.ee.spi.orb.ORB orb = (com.sun.corba.ee.spi.orb.ORB)serverORB ;
                    +            orb.getFVDCodeBaseIOR() ;
                    +
                    +            clientORB.resolve_initial_references( "NameService" ) ;
                    +        } catch (Exception exc) {
                    +            throw new RuntimeException( exc ) ;
                    +        }
                    +    }
                    +
                    +    @Test()
                    +    public void run() {
                    +        doServer( serverORB ) ;
                    +        doClient( clientORB ) ;
                    +    }
                    +
                    +    @Configuration( afterTest = true )
                    +    public void tearDown() {
                    +        // The Client ORB does not correctly clean up its
                    +        // exported targets: it tries to go to the SE
                    +        // RMI-IIOP implementation, which is not even
                    +        // instantiated here.  So clean up manually.
                    +        //
                    +        // Fixing this requires changes in the ORB:
                    +        // basically it should be the TOA's job to keep
                    +        // track of connected objrefs and clean up the
                    +        // information in RMI-IIOP.  This would affect
                    +        // both the se and ee ORBs, and require a patch
                    +        // to JSE 5.
                    +        clientORB.shutdown( true ) ;
                    +        com.sun.corba.ee.impl.javax.rmi.CORBA.Util.getInstance().
                    +            unregisterTargetsForORB( clientORB ) ;
                    +        clientORB.destroy() ;
                    +
                    +        // The Server ORB does clean up correctly.
                    +        serverORB.destroy() ;
                    +    }
                    +
                    +    public static void main( String[] args ) {
                    +        TestNG tng = new TestNG() ;
                    +
                    +        Class[] tngClasses = new Class[] {
                    +            Client.class 
                    +        } ;
                    +
                    +        tng.setTestClasses( tngClasses ) ;
                    +
                    +        tng.run() ;
                    +
                    +        // Make sure we report success/failure to the wrapper.
                    +        System.exit( tng.hasFailure() ? 1 : 0 ) ;
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/mixedorb/Echo.java b/test/src/share/classes/corba/mixedorb/Echo.java
                    new file mode 100644
                    index 000000000..441b44bbf
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/mixedorb/Echo.java
                    @@ -0,0 +1,22 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.mixedorb;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +public interface Echo extends Remote {
                    +    Echo say( Echo obj ) throws RemoteException ;
                    +
                    +    String name() throws RemoteException ;
                    +}
                    +
                    +
                    diff --git a/test/src/share/classes/corba/mixedorb/EchoImpl.java b/test/src/share/classes/corba/mixedorb/EchoImpl.java
                    new file mode 100644
                    index 000000000..0ee4a4ed7
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/mixedorb/EchoImpl.java
                    @@ -0,0 +1,33 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.mixedorb;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +import javax.rmi.PortableRemoteObject ;
                    +
                    +public class EchoImpl extends PortableRemoteObject implements Echo {
                    +    private String name ;
                    +
                    +    public EchoImpl( String name ) throws RemoteException {
                    +        this.name = name ;
                    +    }
                    +
                    +    public Echo say( Echo echo ) {
                    +        return echo ;
                    +    }
                    +
                    +    public String name() {
                    +        return name ;
                    +    }
                    +}
                    +
                    +
                    diff --git a/test/src/share/classes/corba/mixedorb/MixedOrbTest.java b/test/src/share/classes/corba/mixedorb/MixedOrbTest.java
                    new file mode 100644
                    index 000000000..bf90c024c
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/mixedorb/MixedOrbTest.java
                    @@ -0,0 +1,45 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.mixedorb;
                    +
                    +import test.Test;
                    +import corba.framework.*;
                    +import java.util.*;
                    +
                    +public class MixedOrbTest extends CORBATest
                    +{
                    +    private static final String[] javaFiles = { "Client.java", "Echo.java",
                    +        "EchoImpl.java" }  ;
                    +
                    +    private static final String[] rmicClasses = { "corba.mixedorb.EchoImpl" } ;
                    +
                    +    protected void doTest() throws Throwable
                    +    {
                    +        Options.setRMICClasses(rmicClasses) ;
                    +        Options.addRMICArgs( "-iiop -keep -g -poa" ) ;
                    +        Options.setJavaFiles( javaFiles ) ;
                    +
                    +        compileRMICFiles();
                    +        compileJavaFiles();
                    +
                    +        Controller client = createClient( "corba.mixedorb.Client" ) ;
                    +
                    +        client.start();
                    +
                    +        // Wait for the client to finish for up to 2 minutes, then
                    +        // throw an exception.
                    +        client.waitFor(120000);
                    +
                    +        // Make sure all the processes are shut down.
                    +        client.stop();
                    +    }
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/mixedorb/Notes.txt b/test/src/share/classes/corba/mixedorb/Notes.txt
                    new file mode 100644
                    index 000000000..360cbcb38
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/mixedorb/Notes.txt
                    @@ -0,0 +1,62 @@
                    +#
                    +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    +#
                    +# This program and the accompanying materials are made available under the
                    +# terms of the Eclipse Distribution License v. 1.0, which is available at
                    +# http://www.eclipse.org/org/documents/edl-v10.php.
                    +#
                    +# SPDX-License-Identifier: BSD-3-Clause
                    +#
                    +
                    +Notes on a mixed ORB test
                    +
                    +se ORB = ORB in JDK (5 or later)
                    +ee ORB = ORB in app server (rip-int-generic)
                    +
                    +goal: test use of se ORB with ee RMI-IIOP delegates.
                    +
                    +approach:
                    +
                    +    - Use JNDI for all name server access
                    +    - Create client and server ORBs
                    +        client: ee RMI-IIOP delegates se ORB impl (from JDK)
                    +        server: ee RMI-IIOP delegates and ORB impl (from workspace)
                    +    - Use explicit ORBs passed to 2 JNDI InitialContext instances
                    +    - data
                    +        ORB[] orbs ; // 0 is se, 1 is ee
                    +        InitialContext[] ics ; // ics[i] uses orb[i]
                    +            
                    +    public interface Echo extends Remote {
                    +        Echo echo( Echo obj ) throw RemoteException ;
                    +    }
                    +
                    +    public class EchoImpl extends PortableRemoteObject implements Echo {
                    +        public Echo echo( Echo echo ) {
                    +            return echo ;
                    +        }
                    +    }
                    +
                    +    public class  NarrowHelper {
                    +        private NarrowHelper() {}
                    +
                    +        public static T narrow( Remote obj, Class cls ) {
                    +            return cls.cast( PortableRemoteObject.narrow(
                    +                obj, cls ) ) ;
                    +        }
                    +    }
                    +
                    +    import static NarrowHelper.narrow ;
                    +
                    +    - test
                    +        - client
                    +            Echo myEcho = new EchoImpl() ;
                    +            // put client's ORB in env
                    +            InitialContext ic = new InitialContext( env ) ;
                    +            Echo ec = narrow( ic.lookup( "name" ), Echo.class ) ; 
                    +            Echo result = ec.echo( myEcho ) ;
                    +            result.echo( ec ) ;
                    +
                    +        - server
                    +            - creates JNDI init context bound to server ORB
                    +            - creates an instance of echo
                    +            - registers it with JNDI 
                    diff --git a/test/src/share/classes/corba/msgtypes/BadArrayException.java b/test/src/share/classes/corba/msgtypes/BadArrayException.java
                    new file mode 100644
                    index 000000000..14781a940
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/msgtypes/BadArrayException.java
                    @@ -0,0 +1,19 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.msgtypes;
                    +
                    +public class BadArrayException extends java.lang.Exception
                    +{
                    +    public BadArrayException() {}
                    +    public BadArrayException(String msg) {
                    +        super(msg);
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/msgtypes/Client.java b/test/src/share/classes/corba/msgtypes/Client.java
                    new file mode 100644
                    index 000000000..9bab2d207
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/msgtypes/Client.java
                    @@ -0,0 +1,772 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.msgtypes;
                    +
                    +import java.rmi.RemoteException;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +import org.omg.CORBA.INTERNAL ;
                    +import org.omg.CORBA.LocalObject ;
                    +
                    +import com.sun.corba.ee.spi.transport.ConnectionCache;
                    +
                    +import com.sun.corba.ee.spi.ior.IOR;
                    +import com.sun.corba.ee.spi.ior.IORFactories;
                    +import com.sun.corba.ee.spi.ior.ObjectKey;
                    +import com.sun.corba.ee.spi.ior.ObjectKeyTemplate;
                    +import com.sun.corba.ee.spi.ior.IORTemplate;
                    +import com.sun.corba.ee.spi.ior.ObjectAdapterId;
                    +import com.sun.corba.ee.spi.ior.iiop.GIOPVersion;
                    +import com.sun.corba.ee.spi.ior.iiop.IIOPAddress;
                    +import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate;
                    +import com.sun.corba.ee.spi.ior.iiop.IIOPFactories;
                    +import com.sun.corba.ee.spi.orb.ORB;
                    +import com.sun.corba.ee.spi.protocol.MessageMediator;
                    +import com.sun.corba.ee.spi.protocol.ClientDelegate;
                    +import com.sun.corba.ee.spi.transport.Connection;
                    +import com.sun.corba.ee.spi.transport.ContactInfo ;
                    +import com.sun.corba.ee.spi.transport.ContactInfoList ;
                    +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ;
                    +import com.sun.corba.ee.spi.servicecontext.ServiceContextDefaults ;
                    +
                    +import com.sun.corba.ee.impl.encoding.CDROutputObject;
                    +import com.sun.corba.ee.impl.ior.ObjectKeyFactoryImpl;
                    +import com.sun.corba.ee.impl.ior.ObjectKeyImpl;
                    +import com.sun.corba.ee.impl.ior.POAObjectKeyTemplate;
                    +import com.sun.corba.ee.impl.ior.OldPOAObjectKeyTemplate;
                    +import com.sun.corba.ee.impl.misc.ORBUtility;
                    +import com.sun.corba.ee.spi.misc.ORBConstants;
                    +import com.sun.corba.ee.impl.protocol.ClientDelegateImpl;
                    +import com.sun.corba.ee.impl.protocol.giopmsgheaders.*;
                    +import com.sun.corba.ee.impl.transport.ContactInfoListImpl;
                    +import java.io.FileInputStream;
                    +import java.io.IOException;
                    +import java.util.Iterator;
                    +import java.util.Properties;
                    +import org.omg.PortableInterceptor.ClientRequestInfo;
                    +import org.omg.PortableInterceptor.ClientRequestInterceptor;
                    +import org.omg.PortableInterceptor.ForwardRequest;
                    +import org.omg.PortableInterceptor.ORBInitInfo;
                    +import org.omg.PortableInterceptor.ORBInitializer;
                    +
                    +
                    +public class Client extends LocalObject 
                    +    implements ORBInitializer, ClientRequestInterceptor 
                    +{
                    +    // These constants are defined here only for this test.
                    +    // The new ObjectKeyTemplate code no longer uses offsets.
                    +    static final int MAGIC_OFFSET = 0 ;
                    +    static final int SCID_OFFSET = 4 ;
                    +    static final int REQUEST_ID = 5;
                    +    
                    +    public static void main(String args[])
                    +    {
                    +        try{
                    +            Properties props = new Properties(System.getProperties());
                    +            /*
                    +            props.setProperty("com.sun.corba.ee.ORBDebug",
                    +                              "giop,transport,subcontract,poa");
                    +            */
                    +            org.omg.CORBA.ORB orb = ORB.init(args, props);
                    +
                    +            com.sun.corba.ee.spi.orb.ORB ourORB
                    +                = (com.sun.corba.ee.spi.orb.ORB) orb;
                    +
                    +            System.out.println("==== Client GIOP version "
                    +                               + ourORB.getORBData().getGIOPVersion()
                    +                               + " with strategy "
                    +                               + ourORB.getORBData().getGIOPBuffMgrStrategy(
                    +                                            ourORB.getORBData().getGIOPVersion())
                    +                               + "====");
                    +
                    +            if (args[0].equals("LocateMsg")) {
                    +                runLocateMsgType(ourORB);
                    +            } else if (args[0].equals("EarlyReply")) {
                    +                runEarlyReply(ourORB);
                    +            } else if (args[0].equals("SimpleCancelRequest")) {
                    +                runSimpleCancelRequest(ourORB);
                    +            } else if (args[0].equals("AbortiveCancelRequest1")) {
                    +                runAbortiveCancelRequest1(ourORB);
                    +            } else if (args[0].equals("AbortiveCancelRequest2")) {
                    +                runAbortiveCancelRequest2(ourORB);
                    +            } else if (args[0].equals("TargetAddrDisposition")) {
                    +                runTargetAddressDisposition(ourORB);                
                    +            } else if (args[0].equals("CloseConnection")) {
                    +                runCloseConnection(ourORB);
                    +            } else if (args[0].equals("MessageError")) {
                    +                runMessageError(ourORB);
                    +            } else if (args[0].equals("GIOPInterop")) {
                    +                runGIOPInterop(ourORB);
                    +            } else if (args[0].equals("FragmentedReply")) {
                    +                runFragmentedReply(ourORB);
                    +            } else if (args[0].equals("HeaderPaddingTest")) {
                    +                runHeaderPaddingTest(ourORB);                
                    +            } else {
                    +                System.out.println("Invalid option");
                    +            }
                    +
                    +        } catch (Exception e) {
                    +            System.out.println("ERROR : " + e) ;
                    +            e.printStackTrace(System.out);
                    +            System.exit (1);
                    +        }
                    +    }
                    +
                    +    static void runLocateMsgType(ORB orb) 
                    +    {
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        byte[] objectKey = getObjectKey(orb, ior);
                    +        modifyObjectKey(objectKey);
                    +        LocateRequestMessage msg = getLocateRequestMessage(orb, ior);
                    +        MessageMediator messageMediator =
                    +            beginRequest(orb, fragTestStub, msg);
                    +        org.omg.CORBA.portable.OutputStream os = 
                    +            (org.omg.CORBA.portable.OutputStream)
                    +            messageMediator.getOutputObject();
                    +        msg.write(os);
                    +        messageMediator.finishSendingRequest();
                    +        messageMediator.waitForResponse();
                    +        switch(messageMediator.getLocateReplyHeader().getReplyStatus()) {
                    +        case LocateReplyMessage.UNKNOWN_OBJECT :
                    +            System.out.println("Target object is unknown");
                    +            break;
                    +        case LocateReplyMessage.OBJECT_FORWARD :
                    +        case LocateReplyMessage.OBJECT_FORWARD_PERM :
                    +            System.out.println("Location forward received");
                    +            break;
                    +        case LocateReplyMessage.OBJECT_HERE :
                    +            System.out.println("Target object is available");
                    +            break;
                    +        default:
                    +            System.out.println("Locate reply status is invalid");
                    +            break;
                    +        }
                    +    }
                    +         
                    +    static void runEarlyReply(ORB orb)
                    +        throws RemoteException, BadArrayException 
                    +    {
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        byte[] objKey = getObjectKey(orb, ior);
                    +        modifyObjectKey(objKey);
                    +
                    +        // construct a new IOR
                    +        String typeId = ior.getTypeId();
                    +
                    +        IIOPProfileTemplate iptemp = 
                    +            (IIOPProfileTemplate)ior.getProfile().getTaggedProfileTemplate() ;
                    +        IIOPAddress addr = iptemp.getPrimaryAddress();
                    +
                    +        ObjectKey objectKey = orb.getObjectKeyFactory().create(objKey);
                    +        GIOPVersion gversion = iptemp.getGIOPVersion() ;
                    +
                    +        IIOPProfileTemplate iproftemp = 
                    +            IIOPFactories.makeIIOPProfileTemplate(orb, gversion, addr);
                    +        IORTemplate iortemp = IORFactories.makeIORTemplate(objectKey.getTemplate()) ;
                    +        iortemp.add( iproftemp ) ;
                    +
                    +        IOR newIor = iortemp.makeIOR(orb, typeId, objectKey.getId() ) ;
                    +        
                    +        // IOR -> CorbaContactInfoList ->ClientDelegateImpl, then set
                    +        // new Delegate in the stub.
                    +        ContactInfoList ccil =
                    +            new ContactInfoListImpl(orb, newIor);
                    +        ClientDelegate cdel = new ClientDelegateImpl( orb, ccil ) ;
                    +        StubAdapter.setDelegate( fragTestStub, cdel ) ;
                    +
                    +        // invoke on target
                    +        try {
                    +            String fragSizeStr =
                    +                System.getProperty(ORBConstants.GIOP_FRAGMENT_SIZE);
                    +            int fragmentSize = Integer.decode(fragSizeStr).intValue();
                    +            testByteArray((FragmentTester) fragTestStub,
                    +                          fragmentSize * 1000 * 3);
                    +        } catch (org.omg.CORBA.INV_OBJREF e) {
                    +            System.out.println("Early reply test over");
                    +            // do nothing. This is expected.
                    +        } catch (java.rmi.NoSuchObjectException e) {
                    +            System.out.println("Early reply test over");
                    +            // do nothing. This is expected.
                    +        }
                    +    }
                    +
                    +    static void runSimpleCancelRequest(ORB orb) 
                    +    {
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        LocateRequestMessage msg = getLocateRequestMessage(orb, ior);
                    +        MessageMediator messageMediator =
                    +            beginRequest(orb, fragTestStub, msg);
                    +        GIOPVersion requestVersion =
                    +            GIOPVersion.chooseRequestVersion(orb, ior);
                    +        try {
                    +            ((Connection) messageMediator.getConnection())
                    +                .sendCancelRequest(requestVersion, REQUEST_ID);
                    +        } catch (IOException e) {}
                    +        System.out.println("SimpleCancelRequestMsg sent successfully");
                    +    }
                    +
                    +    static void runAbortiveCancelRequest1(ORB orb) 
                    +    {
                    +
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        byte[] objectKey = getObjectKey(orb, ior);
                    +        modifyObjectKey(objectKey);
                    +
                    +        LocateRequestMessage msg = getLocateRequestMessage(orb, ior);
                    +        MessageMediator messageMediator =
                    +            beginRequest(orb, fragTestStub, msg);
                    +
                    +        CDROutputObject os = (CDROutputObject)
                    +            messageMediator.getOutputObject();
                    +        // create GIOP header and write to output buffer
                    +        os.write_long(Message.GIOPBigMagic);
                    +        GIOPVersion requestVersion =
                    +            GIOPVersion.chooseRequestVersion(orb, ior);
                    +        requestVersion.write((org.omg.CORBA.portable.OutputStream)os);
                    +        os.write_octet(Message.FLAG_NO_FRAG_BIG_ENDIAN);
                    +        os.write_octet(Message.GIOPLocateRequest);
                    +        os.write_ulong(0);
                    +
                    +        // write the requestId to the output buffer
                    +        os.write_ulong (REQUEST_ID);
                    +
                    +        // send first fragment. This will cause the server to start the
                    +        // worker thread and the worker thread will block to read stream.
                    +        os.sendFirstFragment();
                    +
                    +        // send cancel request
                    +        try {
                    +            ((Connection) messageMediator.getConnection())
                    +                .sendCancelRequest(requestVersion, REQUEST_ID);
                    +        } catch (IOException e) {}
                    +        System.out.println("AbortiveCancelRequestMsg sent successfully");
                    +    }
                    +
                    +    static void runAbortiveCancelRequest2(ORB orb)
                    +    {
                    +
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        GIOPVersion requestVersion =
                    +            GIOPVersion.chooseRequestVersion(orb, ior);
                    +        byte encodingVersion =
                    +            ORBUtility.chooseEncodingVersion(orb, ior, requestVersion);
                    +        RequestMessage msg =
                    +            MessageBase.createRequest(
                    +                orb, requestVersion, encodingVersion,
                    +                REQUEST_ID, true, ior, 
                    +                KeyAddr.value, "verifyTransmission", 
                    +                ServiceContextDefaults.makeServiceContexts( orb ), null);
                    +        MessageMediator messageMediator =
                    +            beginRequest(orb, fragTestStub, msg);
                    +        CDROutputObject os = (CDROutputObject)
                    +            messageMediator.getOutputObject();
                    +
                    +        msg.write(os);
                    +
                    +        // send first fragment which has the request header.
                    +        // This will cause the server to start the
                    +        // worker thread and the worker thread will block to read stream for
                    +        // umarshalling method input parameters.
                    +        os.sendFirstFragment();
                    +
                    +        // send cancel request
                    +        try {
                    +            ((Connection) messageMediator.getConnection())
                    +                .sendCancelRequest(requestVersion, REQUEST_ID);
                    +        } catch (IOException e) {}
                    +
                    +        try {
                    +            // This sleep is necessary since the above fragment tranmission does
                    +            // not block. The sleep ensure that the outcome verification happens
                    +            // after the request cancellation takes place.
                    +            Thread.sleep(10000);
                    +        } catch (Exception e) {}
                    +
                    +        try {
                    +            FragmentTester fragTester = (FragmentTester) fragTestStub;
                    +            boolean outcome = fragTester.verifyOutcome();
                    +            System.out.println("AbortiveCancelRequestMsg2 finished is : " +
                    +                outcome);
                    +            if (outcome == false) {
                    +                throw new RuntimeException("Test failed");
                    +            }
                    +        } catch (java.rmi.RemoteException e) {
                    +            throw new RuntimeException(e.toString());
                    +        }
                    +    }
                    +
                    +    static void runTargetAddressDisposition(ORB orb) 
                    +    {
                    +
                    +        FragmentTester frag = (FragmentTester) getStub(orb);
                    +
                    +        try {
                    +            testByteArray(frag, 4);
                    +            boolean outcome = frag.verifyOutcome();
                    +            System.out.println("ClientInvCount : " + interceptorInvocationCount);
                    +            System.out.println("TargetAddrDisp outcome is : " + outcome);
                    +            if (interceptorInvocationCount != 4 || outcome == false) {
                    +                throw new RuntimeException("Test failed");
                    +            }
                    +            interceptorInvocationCount = 0;
                    +        } catch (java.rmi.RemoteException e) {
                    +            throw new RuntimeException(e.toString());
                    +        } catch (BadArrayException e) {
                    +            throw new RuntimeException(e.toString());               
                    +        }
                    +    }
                    +
                    +    static void runCloseConnection(ORB orb) 
                    +    {
                    +
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        LocateRequestMessage msg = getLocateRequestMessage(orb, ior);
                    +        MessageMediator messageMediator =
                    +            beginRequest(orb, fragTestStub, msg);
                    +        GIOPVersion requestVersion =
                    +            GIOPVersion.chooseRequestVersion(orb, ior);
                    +        try {
                    +            ((Connection) messageMediator.getConnection())
                    +                .sendCloseConnection(requestVersion);
                    +        } catch (IOException e) {}
                    +        System.out.println("CloseConnectionMsg sent successfully");
                    +    }
                    +
                    +    /**
                    +     * This test checks if lazy body padding works properly. GIOP spec requires
                    +     * that for versions >= 1.2, body must be aligned on a 8-octet boundary, but
                    +     * if a body is absent in an request/reply then the header must not be
                    +     * padded. Our ORB uses a lazy body padding technique, that inserts the
                    +     * padding in order to align the body, only if the body is present.
                    +     * 
                    +     * @param orb ORB
                    +     */
                    +    static void runHeaderPaddingTest(ORB orb) {
                    +        int align = ORBConstants.GIOP_12_MSG_BODY_ALIGNMENT; // 8 bytes length
                    +        int charLength = 1;
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);      
                    +        CDROutputObject os = (CDROutputObject) StubAdapter.request(fragTestStub, "fooA", false); // CASE 1
                    +        int beforePaddingIndex = os.getBufferPosition();
                    +        os.write_char('a'); // forces padding if not already naturally aligned
                    +        int afterPaddingIndex = os.getBufferPosition();
                    +        int paddingLength = afterPaddingIndex-beforePaddingIndex-charLength;
                    +        if ((paddingLength < 0) || (paddingLength > align)) {
                    +            throw new RuntimeException("marshalling error"); // cannot happen
                    +        }
                    +        if ((paddingLength > 0) && (paddingLength < align)) {
                    +            System.out.println("HeaderPaddingTest(1) completed successfully");
                    +            return; // padding was inserted. No natural alignment.
                    +        }
                    +        
                    +        // The only possibility now if for padding to be zero, because the
                    +        // body in the previous case was likely naturally aligned. 
                    +        // So, now force non-alignment, in order to
                    +        // check to see if padding is inserted. This is done by calling the
                    +        // the method 'fooAA', which has an additional character in its name,
                    +        // that will force non-alignment.
                    +        os = (CDROutputObject)
                    +            StubAdapter.request(fragTestStub, "fooAA", false); // CASE 2
                    +        beforePaddingIndex = os.getBufferPosition();
                    +        os.write_char('a'); // forces padding if not already naturally aligned
                    +        afterPaddingIndex = os.getBufferPosition();
                    +        paddingLength = afterPaddingIndex-beforePaddingIndex-charLength;
                    +        if ((paddingLength < 0) || (paddingLength > align)) {
                    +            throw new RuntimeException("marshalling error"); // cannot happen
                    +        }
                    +        if ((paddingLength > 0) && (paddingLength < align)) {
                    +            // padding was inserted. No natural alignment.
                    +            // Previous case was a case of natural alignment.
                    +            System.out.println("HeaderPaddingTest(2) completed successfully");
                    +            return; 
                    +        } else { // paddingLength == 0
                    +            // Cannot happen. In order for this (padding == 0) to occur in both
                    +            // cases, the header must have been forcibly padded always, 
                    +            // which is incorrect. This indicates lazy body padding is not
                    +            // working properly.
                    +            throw new RuntimeException("Header padding error");
                    +        }        
                    +    }
                    +
                    +    static void runMessageError(ORB orb)
                    +    {
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        LocateRequestMessage msg = getLocateRequestMessage(orb, ior);
                    +        MessageMediator messageMediator =
                    +            beginRequest(orb, fragTestStub, msg);
                    +        GIOPVersion requestVersion =
                    +            GIOPVersion.chooseRequestVersion(orb, ior);
                    +        try {
                    +            ((Connection) messageMediator.getConnection())
                    +                .sendMessageError(requestVersion);
                    +        } catch (IOException e) {}
                    +        System.out.println("MessageError sent successfully");
                    +    }
                    +
                    +    public static void runGIOPInterop(ORB orb) 
                    +    {
                    +        org.omg.CORBA.Object fragTestStub = getStub(orb);
                    +        IOR ior = orb.getIOR( fragTestStub, false ) ;
                    +        ObjectKey objectKey = getObjectKeyObject(orb, ior);
                    +        objectKey = modifyObjectKeySCID(objectKey,
                    +                                        ORBConstants.PERSISTENT_SCID, orb);
                    +
                    +        // Modify to use old magic.
                    +        for (int magic = ObjectKeyFactoryImpl.MAGIC_BASE;
                    +             magic <= ObjectKeyFactoryImpl.MAX_MAGIC; magic++) {
                    +
                    +            System.out.println("magic: " + magic);
                    +            objectKey = modifyObjectKeyMagic(objectKey, magic, orb);
                    +            //ORBUtility.intToBytes(magic, objectKey, MAGIC_OFFSET);
                    +
                    +            // construct a new IOR
                    +            String typeId = ior.getTypeId();
                    +            IIOPProfileTemplate iptemp = 
                    +                (IIOPProfileTemplate)ior.getProfile().getTaggedProfileTemplate() ;
                    +            IIOPAddress addr = iptemp.getPrimaryAddress() ;
                    +
                    +            ObjectKey objKey = orb.getObjectKeyFactory().
                    +                                      create(objectKey.getBytes(orb));
                    +
                    +            IIOPProfileTemplate iproftemp =
                    +                IIOPFactories.makeIIOPProfileTemplate(orb, GIOPVersion.V1_1, addr);
                    +            IORTemplate iortemp = IORFactories.makeIORTemplate(objKey.getTemplate()) ;
                    +            iortemp.add( iproftemp ) ;
                    +
                    +            IOR newIor = iortemp.makeIOR(orb, typeId, objKey.getId() ) ;
                    +
                    +            // create locate request message
                    +            GIOPVersion requestVersion =
                    +                GIOPVersion.chooseRequestVersion(orb, newIor);
                    +            byte encodingVersion = 
                    +                ORBUtility.chooseEncodingVersion(orb, newIor,
                    +                                                 requestVersion);
                    +            System.out.println("GIOP[major, minor]: " + requestVersion.getMajor() +
                    +                               ", " + requestVersion.getMinor());
                    +            LocateRequestMessage msg =
                    +                MessageBase.createLocateRequest(
                    +                    orb, requestVersion, encodingVersion,
                    +                    REQUEST_ID, objectKey.getBytes(orb));
                    +
                    +
                    +            int strategy = requestVersion.lessThan(GIOPVersion.V1_2) ? 0 : 1;
                    +            MessageMediator messageMediator =
                    +                beginRequest(orb, fragTestStub, msg, strategy);
                    +
                    +            org.omg.CORBA.portable.OutputStream os = 
                    +                (org.omg.CORBA.portable.OutputStream)
                    +                messageMediator.getOutputObject();
                    +            msg.write(os);
                    +            messageMediator.finishSendingRequest();
                    +            messageMediator.waitForResponse();
                    +
                    +            switch(messageMediator.getLocateReplyHeader().getReplyStatus()) {
                    +            case LocateReplyMessage.UNKNOWN_OBJECT :
                    +                System.out.println("Target object is unknown");
                    +                break;
                    +            case LocateReplyMessage.OBJECT_FORWARD :
                    +            case LocateReplyMessage.OBJECT_FORWARD_PERM :
                    +                System.out.println("Location forward received");
                    +                break;
                    +            case LocateReplyMessage.OBJECT_HERE :
                    +                System.out.println("Target object is available");
                    +                break;
                    +            default:
                    +                System.out.println("Locate reply status is invalid");
                    +                break;
                    +            }
                    +        }
                    +    }
                    +    
                    +    public static void runFragmentedReply(ORB orb) 
                    +    {
                    +        FragmentTester fragTestRef = (FragmentTester) getStub(orb);
                    +
                    +        try {
                    +            fragTestRef.testFragmentedReply(false);
                    +        } catch (Throwable t) {
                    +            RuntimeException err = new RuntimeException( 
                    +                "Excepion in fragmented reply test" );   
                    +            err.initCause( t ) ;
                    +            throw err ;
                    +        }
                    +    }    
                    +
                    +    ////////////////////////////////////////////////////
                    +    //
                    +    // Utilities
                    +    //
                    +
                    +    static org.omg.CORBA.Object getStub(ORB orb)
                    +    {
                    +        org.omg.CORBA.Object obj = readObjref("IOR", orb);
                    +        return (org.omg.CORBA.Object)PortableRemoteObject.narrow(obj, 
                    +            FragmentTester.class);
                    +    }
                    +
                    +    static byte[] getObjectKey(ORB orb, IOR ior)
                    +    {
                    +        return ior.getProfile().getObjectKey().getBytes(orb);
                    +    }
                    +
                    +    static ObjectKey getObjectKeyObject(ORB orb, IOR ior)
                    +    {
                    +        return ior.getProfile().getObjectKey();
                    +    }
                    +
                    +    static ObjectKey modifyObjectKeySCID(ObjectKey objectKey,
                    +                                         int scid, ORB orb) {
                    +        ObjectKeyTemplate okTemp = objectKey.getTemplate();
                    +        int serverId = okTemp.getServerId();
                    +        String orbId = okTemp.getORBId();
                    +        ObjectAdapterId objectAdapterId = okTemp.getObjectAdapterId();
                    +        ObjectKeyTemplate newOkTemp = 
                    +            new POAObjectKeyTemplate(orb, scid, serverId, orbId, 
                    +                                     objectAdapterId);
                    +        return new ObjectKeyImpl(newOkTemp, objectKey.getId());
                    +    }
                    +
                    +    static ObjectKey modifyObjectKeyMagic(ObjectKey objectKey,
                    +                                          int magic, ORB orb) {
                    +        ObjectKeyTemplate okTemp = objectKey.getTemplate();
                    +        int serverId = okTemp.getServerId();
                    +        int scid = okTemp.getSubcontractId();
                    +        String orbId = okTemp.getORBId();
                    +        ObjectAdapterId objectAdapterId = okTemp.getObjectAdapterId();
                    +        ObjectKeyTemplate newOkTemp;
                    +        if (magic >= ObjectKeyFactoryImpl.JAVAMAGIC_NEWER) {
                    +            newOkTemp = new POAObjectKeyTemplate(orb, scid, serverId, orbId, 
                    +                                                 objectAdapterId);
                    +        } else {
                    +            newOkTemp = new OldPOAObjectKeyTemplate(orb, magic, scid,
                    +                                                    serverId,
                    +                                                    1, // orbId
                    +                                                    1); // poaId
                    +        }
                    +        return new ObjectKeyImpl(newOkTemp, objectKey.getId());
                    +    }
                    +
                    +    static void modifyObjectKey(byte[] objectKey)
                    +    {
                    +        // modify the object key so as to force BadServerIdHandler
                    +        // to be invoked, instead of the usual upcall dispatch
                    +        System.out.println("-> objectkey.length : " + objectKey.length);
                    +        ORBUtility.intToBytes(ORBConstants.PERSISTENT_SCID, objectKey,
                    +                              SCID_OFFSET);
                    +    }
                    +
                    +    static MessageMediator beginRequest(ORB orb,
                    +        org.omg.CORBA.Object stub, Message msg)
                    +    {
                    +        return beginRequest(orb, stub, msg, -1);
                    +    }
                    +
                    +    static MessageMediator beginRequest(ORB orb,
                    +        org.omg.CORBA.Object stub, Message msg, int strategy)
                    +    {
                    +        ClientDelegate delegate = (ClientDelegate)
                    +            StubAdapter.getDelegate(stub) ;
                    +        Iterator iterator = delegate.getContactInfoList().iterator();
                    +        ContactInfo contactInfo;
                    +        if (iterator.hasNext()) {
                    +            contactInfo = (ContactInfo) iterator.next();
                    +        } else {
                    +            throw new RuntimeException("no next");
                    +        }
                    +        Connection connection = (Connection)
                    +            contactInfo.createConnection();
                    +        connection.setConnectionCache(new DummyConnectionCache());
                    +        orb.getTransportManager().getSelector(0)
                    +            .registerForEvent(connection.getEventHandler());
                    +        connection.setState("ESTABLISHED");
                    +        MessageMediator messageMediator = (MessageMediator)
                    +            contactInfo.createMessageMediator(
                    +                orb, contactInfo, connection, "locate message", false);
                    +        CDROutputObject outputObject = null;
                    +        if (strategy == -1) {
                    +            outputObject =
                    +                new CDROutputObject(orb, messageMediator, msg,
                    +                                    messageMediator.getStreamFormatVersion());
                    +        } else {
                    +            outputObject =
                    +                new CDROutputObject(orb, messageMediator, msg,
                    +                                    messageMediator.getStreamFormatVersion(),
                    +                                    strategy);
                    +        }
                    +        messageMediator.setOutputObject(outputObject);
                    +        connection.registerWaiter(messageMediator);
                    +        return messageMediator;
                    +    }
                    +
                    +    // All this, just to get a connection.
                    +    static LocateRequestMessage getLocateRequestMessage(ORB orb, IOR ior)
                    +    {
                    +        byte[] objectKey = getObjectKey(orb, ior);
                    +        GIOPVersion gv = GIOPVersion.chooseRequestVersion(orb, ior);
                    +        byte encodingVersion = ORBUtility.chooseEncodingVersion(orb, ior, gv);
                    +        LocateRequestMessage msg = 
                    +            MessageBase.createLocateRequest(
                    +                orb, gv, encodingVersion, REQUEST_ID, objectKey);
                    +        return msg;
                    +    }
                    +
                    +    // size must be divisible by four
                    +    public static void testByteArray(FragmentTester tester, int size)
                    +        throws RemoteException, BadArrayException
                    +    {
                    +        System.out.println("Sending array of length " + size);
                    +
                    +        byte array[] = new byte[size];
                    +
                    +        int i = 0;
                    +
                    +        do {
                    +
                    +            for (byte x = 0; x < 4; x++) {
                    +                //System.out.print("" + x + " ");
                    +                array[i++] = x;
                    +            }
                    +            // System.out.println();
                    +
                    +        } while (i < size);
                    +
                    +        byte result[] = tester.verifyTransmission(array);
                    +
                    +        if (result == null)
                    +            throw new BadArrayException("result was null!");
                    +
                    +        if (array.length != result.length)
                    +            throw new BadArrayException("result length incorrect: " + result.length);
                    +
                    +        for (i = 0; i < array.length; i++)
                    +            if (array[i] != result[i])
                    +                throw new BadArrayException("result mismatch at index: " + i);
                    +
                    +        System.out.println("testByteArray completed normally");
                    +    }
                    +
                    +    public static org.omg.CORBA.Object readObjref(String file, org.omg.CORBA.ORB orb) 
                    +    {
                    +        String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file;
                    +        try {
                    +            java.io.DataInputStream in =
                    +                new java.io.DataInputStream(new FileInputStream(fil));
                    +            String ior = in.readLine();
                    +            System.out.println("IOR: "+ior);
                    +            return orb.string_to_object(ior);
                    +        } catch (java.io.IOException e) {
                    +            System.err.println("Unable to open file "+fil);
                    +            System.exit(1);
                    +        }
                    +        return null;
                    +    }
                    +
                    +    ////////////////////////////////////////////////////
                    +    //    
                    +    // ORBInitializer interface implementation.
                    +    //
                    +
                    +    public void pre_init(ORBInitInfo info) 
                    +    {
                    +    }
                    +
                    +    public void post_init(ORBInitInfo info) 
                    +    {
                    +        // register the interceptors.
                    +        try {
                    +            info.add_client_request_interceptor(this);
                    +        } catch (org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName e) {
                    +            throw new INTERNAL();
                    +        }
                    +        System.out.println("ORBInitializer.post_init completed");
                    +    }
                    +
                    +    ////////////////////////////////////////////////////
                    +    //
                    +    // implementation of the Interceptor interface.
                    +    //
                    +
                    +    public String name() 
                    +    {
                    +        return "ClientInterceptor";
                    +    }
                    +
                    +    public void destroy() 
                    +    {
                    +    }
                    +
                    +    ////////////////////////////////////////////////////
                    +    //    
                    +    // implementation of the ClientInterceptor interface.
                    +    //
                    +
                    +    private static int interceptorInvocationCount = 0;
                    +
                    +    public void send_request(ClientRequestInfo ri) throws ForwardRequest 
                    +    {
                    +        if (interceptorInvocationCount == 0 ||
                    +                interceptorInvocationCount == 2) {
                    +            interceptorInvocationCount++;
                    +        }   
                    +        System.out.println("send_request called : " + ri.operation());        
                    +    }
                    +
                    +    public void send_poll(ClientRequestInfo ri) 
                    +    {
                    +        System.out.println("send_poll called : " + ri.operation());
                    +    }
                    +
                    +    public void receive_reply(ClientRequestInfo ri) 
                    +    {
                    +        if (interceptorInvocationCount == 3) {
                    +            interceptorInvocationCount++;        
                    +        }        
                    +        System.out.println("receive_reply called : " + ri.operation());
                    +    }
                    +
                    +    public void receive_exception(ClientRequestInfo ri) throws ForwardRequest 
                    +    {
                    +        System.out.println("receive_exception called : " + ri.operation());
                    +    }
                    +
                    +    public void receive_other(ClientRequestInfo ri) throws ForwardRequest 
                    +    {
                    +        if (interceptorInvocationCount == 1) {
                    +            interceptorInvocationCount++;        
                    +        }
                    +        System.out.println("receive_other called : " + ri.operation());
                    +    }
                    +}
                    +
                    +class DummyConnectionCache
                    +    implements ConnectionCache
                    +{
                    +    public String getCacheType() { return null; }
                    +    public void stampTime(Connection connection) {}
                    +    public long numberOfConnections() { return 0; }
                    +    public long numberOfIdleConnections() { return 0; }
                    +    public long numberOfBusyConnections() { return 0; }
                    +    public boolean reclaim() { return true; }
                    +    public void close() {}
                    +
                    +    public String getMonitoringName() {
                    +        throw new UnsupportedOperationException("Not supported yet.");
                    +    }
                    +}
                    +
                    +// End of file.
                    +
                    diff --git a/test/src/share/classes/corba/msgtypes/FragmentTester.java b/test/src/share/classes/corba/msgtypes/FragmentTester.java
                    new file mode 100644
                    index 000000000..db3e41395
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/msgtypes/FragmentTester.java
                    @@ -0,0 +1,29 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.msgtypes;
                    +
                    +import java.rmi.RemoteException ;
                    +
                    +public interface FragmentTester extends java.rmi.Remote
                    +{
                    +    public byte[] verifyTransmission(byte array[])
                    +        throws RemoteException, BadArrayException;
                    +    public boolean verifyOutcome() throws RemoteException;
                    +    public java.lang.Object testFragmentedReply(boolean isSerializable) 
                    +        throws RemoteException;
                    +
                    +    // used for header padding test only. The following two method names differ
                    +    // just by one character. This ensures that the request header for atleast
                    +    // one of these methods would not be naturally aligned on an 8-octet
                    +    // boundary.
                    +    public void fooA(char ch) throws RemoteException;
                    +    public void fooB(char ch) throws RemoteException;
                    +}
                    diff --git a/test/src/share/classes/corba/msgtypes/FragmentTesterImpl.java b/test/src/share/classes/corba/msgtypes/FragmentTesterImpl.java
                    new file mode 100644
                    index 000000000..4ace46467
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/msgtypes/FragmentTesterImpl.java
                    @@ -0,0 +1,80 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.msgtypes;
                    +
                    +import java.rmi.RemoteException ;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +public class FragmentTesterImpl extends PortableRemoteObject implements FragmentTester
                    +{
                    +    Server.InterceptorImpl interceptor = null;
                    +
                    +    public FragmentTesterImpl(Server.InterceptorImpl interceptor) throws RemoteException
                    +    {
                    +        super();
                    +        this.interceptor = interceptor;
                    +    }
                    +
                    +    public byte[] verifyTransmission(byte array[]) throws BadArrayException
                    +    {
                    +        if (array == null)
                    +            throw new BadArrayException("Array is null");
                    +
                    +        if (array.length % 4 != 0)
                    +            throw new BadArrayException("Invalid array length: " + array.length);
                    +
                    +        System.out.println("Array length = " + array.length);
                    +
                    +        int i = 0;
                    +
                    +        do {
                    +
                    +            System.out.println("" + i + ": ");
                    +
                    +            for (int check = 0; check < 4; check++) {
                    +
                    +                System.out.print("" + array[i] + " ");
                    +
                    +                if (array[i++] != check) {
                    +                    throw new BadArrayException("Bad array at index " + i
                    +                                                + " value: " + array[i]);
                    +                }
                    +            }
                    +
                    +            System.out.println();
                    +
                    +
                    +        } while (i < array.length);
                    +
                    +        return array;
                    +    }
                    +
                    +    public boolean verifyOutcome() {
                    +        return this.interceptor.isBalanced();
                    +    }
                    +
                    +    public java.lang.Object testFragmentedReply(boolean isSerializable) 
                    +            throws RemoteException {
                    +
                    +        if (isSerializable) {
                    +            return new java.lang.Object();
                    +        }
                    +            
                    +        return new java.io.Serializable() {};             
                    +    }
                    +    
                    +    // used for header padding test only. The following two method names differ
                    +    // just by one character. This ensures that the request header for atleast
                    +    // one of these methods would not be naturally aligned on an 8-octet
                    +    // boundary.
                    +    public void fooA(char ch) {}
                    +    public void fooB(char ch) {}
                    +}
                    diff --git a/test/src/share/classes/corba/msgtypes/MsgTypesTest.java b/test/src/share/classes/corba/msgtypes/MsgTypesTest.java
                    new file mode 100644
                    index 000000000..c7d72ebfb
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/msgtypes/MsgTypesTest.java
                    @@ -0,0 +1,547 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.msgtypes;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants;
                    +import corba.framework.CORBATest;
                    +import corba.framework.Controller;
                    +import corba.framework.Options;
                    +import java.util.Properties;
                    +
                    +public class MsgTypesTest extends CORBATest {
                    +    static final int GROW = 0;
                    +    static final int COLLECT = 1;
                    +    static final int STREAM = 2;
                    +    static String[] GIOP_version = { "1.0", "1.1", "1.2" };
                    +    static String[] GIOP_strategy = { "GROW", "CLCT", "STRM" };
                    +
                    +    private int errors = 0; // keeps the error count
                    +
                    +    private void printBeginTest(int clientVersion,
                    +                                int clientStrategy,
                    +                                int serverVersion,
                    +                                int serverStrategy)
                    +    {
                    +        StringBuffer output = new StringBuffer(80);
                    +
                    +        // Pleasing aesthetics
                    +        output.append("      ");
                    +
                    +        output.append(GIOP_version[clientVersion]);
                    +        output.append(" ");
                    +        output.append(GIOP_strategy[clientStrategy]);
                    +        output.append(" client <> ");
                    +        output.append(GIOP_version[serverVersion]);
                    +        output.append(" ");
                    +        output.append(GIOP_strategy[serverStrategy]);
                    +        output.append(" server: ");
                    +
                    +        System.out.print(output.toString());
                    +    }
                    +
                    +    private String testName( boolean isServer,
                    +        int clientVersion, int clientStrategy, int serverVersion, int serverStrategy)
                    +    {
                    +        StringBuffer output = new StringBuffer(80);
                    +
                    +        output.append(GIOP_version[clientVersion]);
                    +        output.append("_");
                    +        output.append(GIOP_strategy[clientStrategy]);
                    +        output.append("_to_");
                    +        output.append(GIOP_version[serverVersion]);
                    +        output.append("_");
                    +        output.append(GIOP_strategy[serverStrategy]);
                    +        if (isServer) {
                    +            output.append( "_server" ) ;
                    +        } else {
                    +            output.append( "_client" ) ;
                    +        }
                    +
                    +        return output.toString() ;
                    +    }
                    +
                    +    private void printEndTest(String result)
                    +    {
                    +        System.out.println(result);
                    +    }
                    +
                    +    private void printFinishedTest(String result) {
                    +        StringBuffer output = new StringBuffer(80);
                    +        output.append("      ");
                    +        output.append(result);
                    +
                    +        System.out.println(output.toString());
                    +    }
                    +
                    +    protected void doTest() throws Throwable
                    +    {
                    +        // Pleasing aesthetics
                    +        System.out.println();
                    +
                    +        runLocateMsgType();
                    +        runEarlyReply();
                    +
                    +        runSimpleCancelRequest();
                    +        runAbortiveCancelRequest1();
                    +        runAbortiveCancelRequest2();
                    +
                    +        runMessageError();
                    +        runCloseConnection();
                    +        runGIOPInterop();
                    +        runTargetAddressDisp();
                    +
                    +        // This has been commented out for a long time, and
                    +        // it currently fails with a buffer underflow error.
                    +        // runFragmentedReply();
                    +
                    +        runHeaderPaddingTest();
                    +        
                    +        System.out.print("      Test result : " );
                    +
                    +        if (errors > 0)
                    +            throw new Exception("Errors detected");
                    +    }
                    +
                    +    public void runLocateMsgType() throws Throwable {
                    +
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("LocateMsg");
                    +        int fragmentSize = 32;
                    +
                    +        for (int client_strategy = GROW, i = 0; i < GIOP_version.length; i++) {
                    +
                    +            Properties clientProps = Options.getClientProperties();
                    +
                    +            clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +            clientProps.put(ORBConstants.GIOP_VERSION, GIOP_version[i]);
                    +            clientProps.put(ORBConstants.GIOP_11_BUFFMGR, "" + client_strategy);
                    +            clientProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + client_strategy);
                    +            // clientProps.put(ORBConstants.DEBUG_PROPERTY, "transport,subcontract" ) ;
                    +
                    +            for (int server_strategy = GROW, j = 0; j < GIOP_version.length; j++) {
                    +
                    +                runTest(client_strategy, i, server_strategy, j);
                    +
                    +                if (GIOP_version[j].equals("1.1") && server_strategy == GROW) {
                    +                    server_strategy = STREAM; j--;
                    +                } else if (GIOP_version[j].equals("1.2") && server_strategy == STREAM) {
                    +                    server_strategy = GROW; j--;
                    +                }
                    +            }
                    +
                    +            if (GIOP_version[i].equals("1.1") && client_strategy == GROW) {
                    +                client_strategy = COLLECT; i--;
                    +            } else if (GIOP_version[i].equals("1.2") && client_strategy == COLLECT) {
                    +                client_strategy = STREAM; i--;
                    +            } else if (GIOP_version[i].equals("1.2") && client_strategy == STREAM) {
                    +                client_strategy = GROW; i--;
                    +            }
                    +        }
                    +    }
                    +
                    +    private void runTest(int client_strategy, int client_version, int server_strategy, int server_version) throws Exception {
                    +        // skip non-longer support COLLECT strategy tests
                    +        if (client_strategy == COLLECT || server_strategy == COLLECT) return;
                    +
                    +        printBeginTest(client_version, client_strategy, server_version, server_strategy);
                    +
                    +        Properties serverProps = Options.getServerProperties();
                    +        serverProps.put(ORBConstants.GIOP_VERSION, GIOP_version[client_version]);
                    +        serverProps.put(ORBConstants.GIOP_11_BUFFMGR, "" + server_strategy);
                    +        serverProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + server_strategy);
                    +        // serverProps.put(ORBConstants.DEBUG_PROPERTY, "transport,subcontract" ) ;
                    +
                    +        Controller server = createServer("corba.msgtypes.Server",
                    +            testName( true, client_version, client_strategy, server_version, server_strategy));
                    +        Controller client = createClient("corba.msgtypes.Client",
                    +            testName( false, client_version, client_strategy, server_version, server_strategy));
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printEndTest("LocateMsgTest FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printEndTest("LocateMsgTest FAILED, Server crashed");
                    +            } else {
                    +                printEndTest("LocateMsgTest PASSED");
                    +            }
                    +        }
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runEarlyReply() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("EarlyReply");
                    +
                    +        int fragmentSize = 1024;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runEarlyReply" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runEarlyReply" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("EarlyReplyTest FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("EarlyReplyTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("EarlyReplyTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runSimpleCancelRequest() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("SimpleCancelRequest");
                    +
                    +        int fragmentSize = 32;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runSimpleCancelRequest" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runSimpleCancelRequest" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("SimpleCancelRqstTest FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("SimpleCancelRqstTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("SimpleCancelRqstTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runAbortiveCancelRequest1() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("AbortiveCancelRequest1");
                    +
                    +        int fragmentSize = 1024;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runAbortiveCancelRequest1" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runAbortiveCancelRequest1" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("AbortiveCancelRqTest1 FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("AbortiveCancelRqTest1 FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("AbortiveCancelRqTest1 PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runAbortiveCancelRequest2() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("AbortiveCancelRequest2");
                    +
                    +        int fragmentSize = 1024;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Properties serverProps = Options.getServerProperties();
                    +        serverProps.put("org.omg.CORBA.ORBClass",
                    +                        "com.sun.corba.ee.impl.orb.ORBImpl");
                    +        serverProps.put("org.omg.PortableInterceptor.ORBInitializerClass." +
                    +                  "corba.msgtypes.Server", "true");
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runAbortiveCancelRequest2" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runAbortiveCancelRequest2" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("AbortiveCancelRqTest2 FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("AbortiveCancelRqTest2 FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("AbortiveCancelRqTest2 PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runTargetAddressDisp() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("TargetAddrDisposition");
                    +
                    +        int fragmentSize = 1024;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +        clientProps.put(ORBConstants.GIOP_TARGET_ADDRESSING,
                    +                  "" + ORBConstants.ADDR_DISP_IOR);
                    +        clientProps.put("org.omg.CORBA.ORBClass",
                    +                        "com.sun.corba.ee.impl.orb.ORBImpl");
                    +        clientProps.put("org.omg.PortableInterceptor.ORBInitializerClass." +
                    +                  "corba.msgtypes.Client", "true");
                    +                  
                    +        Properties serverProps = Options.getServerProperties();
                    +        serverProps.put("org.omg.CORBA.ORBClass",
                    +                        "com.sun.corba.ee.impl.orb.ORBImpl");
                    +        serverProps.put("org.omg.PortableInterceptor.ORBInitializerClass." +
                    +                  "corba.msgtypes.Server", "true");
                    +        serverProps.put(ORBConstants.GIOP_TARGET_ADDRESSING,
                    +                  "" + ORBConstants.ADDR_DISP_OBJKEY);              
                    +        Controller server = createServer("corba.msgtypes.Server", "runTargetAddressDisp" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runTargetAddressDisp" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("TargetAddrDisposition FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("TargetAddrDisposition FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("TargetAddrDisposition PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runCloseConnection() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("CloseConnection");
                    +
                    +        int fragmentSize = 32;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runCloseConnection" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runCloseConnection" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("CloseConnectionTest FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("CloseConnectionTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("CloseConnectionTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runMessageError() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("MessageError");
                    +
                    +        int fragmentSize = 32;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runMessageError" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runMessageError" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("MessageErrorTest FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("MessageErrorTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("MessageErrorTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +
                    +    public void runGIOPInterop() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("GIOPInterop");
                    +
                    +        int fragmentSize = 32;
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runGIOPInterop" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runGIOPInterop" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("GIOPInteropTest FAILED, Client exit value = " +
                    +                         client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("GIOPInteropTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("GIOPInteropTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +    
                    +    public void runFragmentedReply() throws Throwable {
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("FragmentedReply");
                    +
                    +        int fragmentSize = 32;
                    +        Properties serverProps = Options.getServerProperties();
                    +        serverProps.put(ORBConstants.GIOP_FRAGMENT_SIZE, "" + fragmentSize);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runFragmentedReply" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runFragmentedReply" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("FragmentedReplyTest FAILED, Client exit value = "
                    +                         + client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("FragmentedReplyTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("FragmentedReplyTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }
                    +   
                    +    private static final boolean NO_HEADER_PADDING_TEST = true ;
                    +
                    +    // This test always passes, EXCEPT when run in the full test suite on hudson.
                    +    // I am disabling the tests due to inability to reproduce the failure in a
                    +    // debuggable context.
                    +    public void runHeaderPaddingTest() throws Throwable {
                    +        if (NO_HEADER_PADDING_TEST) {
                    +            return ;
                    +        }
                    +
                    +        Options.getClientArgs().clear();
                    +        Options.addClientArg("HeaderPaddingTest");
                    +
                    +        Properties clientProps = Options.getClientProperties();
                    +        clientProps.put(ORBConstants.GIOP_VERSION, GIOP_version[2]);
                    +        clientProps.put(ORBConstants.GIOP_12_BUFFMGR, "" + GROW);
                    +
                    +        Controller server = createServer("corba.msgtypes.Server", "runHeaderPaddingTest" );
                    +        Controller client = createClient("corba.msgtypes.Client", "runHeaderPaddingTest" );
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(60000);
                    +
                    +        if (client.exitValue() != Controller.SUCCESS) {
                    +            errors++;
                    +            printFinishedTest("HeaderPaddingTest FAILED, Client exit value = "
                    +                         + client.exitValue());
                    +        } else {
                    +            if (server.finished()) {
                    +                errors++;
                    +                printFinishedTest("HeaderPaddingTest FAILED, Server crashed");
                    +            } else {
                    +                printFinishedTest("HeaderPaddingTest PASSED");
                    +            }
                    +        }
                    +
                    +        client.stop();
                    +        server.stop();
                    +    }  
                    +    
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/msgtypes/Server.java b/test/src/share/classes/corba/msgtypes/Server.java
                    new file mode 100644
                    index 000000000..e94012438
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/msgtypes/Server.java
                    @@ -0,0 +1,201 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.msgtypes;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants;
                    +import com.sun.corba.ee.spi.protocol.ForwardException;
                    +import com.sun.corba.ee.impl.oa.poa.BadServerIdHandler;
                    +import com.sun.corba.ee.impl.ior.IORImpl;
                    +import com.sun.corba.ee.spi.ior.IOR;
                    +import com.sun.corba.ee.spi.ior.ObjectKey;
                    +import java.io.FileOutputStream;
                    +
                    +import java.util.Properties;
                    +import org.omg.CORBA.INTERNAL;
                    +import org.omg.CORBA.LocalObject;
                    +import org.omg.CORBA.ORB;
                    +import org.omg.PortableInterceptor.ForwardRequest;
                    +import org.omg.PortableInterceptor.ORBInitInfo;
                    +import org.omg.PortableInterceptor.ORBInitializer;
                    +import org.omg.PortableInterceptor.ServerRequestInfo;
                    +import org.omg.PortableInterceptor.ServerRequestInterceptor;
                    +import org.omg.PortableServer.POA;
                    +
                    +public class Server extends LocalObject implements ORBInitializer {
                    +
                    +    private static InterceptorImpl interceptor = new InterceptorImpl();
                    +
                    +    // ORBInitializer interface implementation.
                    +
                    +    public void pre_init(ORBInitInfo info) {}
                    +
                    +    public void post_init(ORBInitInfo info) {
                    +        // register the interceptors.
                    +        try {
                    +            info.add_server_request_interceptor(Server.interceptor);
                    +        } catch (org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName e) {
                    +            throw new INTERNAL();
                    +        }
                    +        System.out.println("ORBInitializer.post_init completed");
                    +    }
                    +
                    +    // nested class definitions
                    +
                    +    private static class ServerRequestHandler implements BadServerIdHandler {
                    +
                    +        private org.omg.CORBA.ORB orb = null;
                    +        private String iorString = null;
                    +
                    +        ServerRequestHandler(org.omg.CORBA.ORB orb, String iorString) {
                    +            this.orb = orb;
                    +            this.iorString = iorString;
                    +        }
                    +
                    +        /**
                    +         * This implements the BadServerIdHandler interface. This will be called
                    +         * by the ORB if the process is setup to be a ORBD or when the ORB gets
                    +         * a locate request.
                    +         */
                    +        public void handle(ObjectKey objectKey) {
                    +
                    +            System.out.println("ServerRequestHandler received a request");
                    +
                    +            // create an IOR to return back
                    +            IOR ior = new IORImpl((com.sun.corba.ee.spi.orb.ORB) orb);
                    +            throw new ForwardException(
                    +                (com.sun.corba.ee.spi.orb.ORB)orb, ior);
                    +        }
                    +    }
                    +
                    +    static class InterceptorImpl extends org.omg.CORBA.LocalObject
                    +            implements ServerRequestInterceptor {
                    +        private static String name = "ServerInterceptor";
                    +        private boolean balanced = true;
                    +
                    +        public InterceptorImpl() {}
                    +
                    +            // implementation of the Interceptor interface.
                    +
                    +        public String name() {
                    +            return InterceptorImpl.name;
                    +        }
                    +
                    +        public void destroy() {}
                    +
                    +            // implementation of the ServerInterceptor interface.
                    +
                    +        public void receive_request_service_contexts(ServerRequestInfo ri)
                    +               throws ForwardRequest {
                    +            if (ri.operation().equals("verifyTransmission")) {
                    +                this.balanced = false;
                    +            }
                    +            System.out.println("receive_request_service_contexts called : " + ri.operation());
                    +        }
                    +
                    +        public void receive_request(ServerRequestInfo ri)
                    +                throws ForwardRequest {
                    +            if (ri.operation().equals("verifyTransmission")) {
                    +                this.balanced = false;
                    +            }
                    +            System.out.println("receive_request called : " + ri.operation());
                    +        }
                    +
                    +        public void send_reply(ServerRequestInfo ri) {
                    +            if (ri.operation().equals("verifyTransmission")) {
                    +                this.balanced = true;
                    +            }
                    +            System.out.println("send_reply called : " + ri.operation());
                    +        }
                    +
                    +        public void send_exception(ServerRequestInfo ri) throws ForwardRequest {
                    +            if (ri.operation().equals("verifyTransmission")) {
                    +                this.balanced = true;
                    +            }
                    +            System.out.println("send_exception called : " + ri.operation());
                    +        }
                    +
                    +        public void send_other(ServerRequestInfo ri) throws ForwardRequest {
                    +            if (ri.operation().equals("verifyTransmission")) {
                    +                this.balanced = true;
                    +            }
                    +            System.out.println("send_other called : " + ri.operation());
                    +        }
                    +
                    +        public boolean isBalanced() {
                    +            return this.balanced;
                    +        }
                    +    }
                    +
                    +    // static methods
                    +
                    +    public static void writeObjref(org.omg.CORBA.Object ref, String file, org.omg.CORBA.ORB orb) {
                    +        String fil = System.getProperty("output.dir")+System.getProperty("file.separator")+file;
                    +        try {
                    +            java.io.DataOutputStream out = new
                    +                java.io.DataOutputStream(new FileOutputStream(fil));
                    +            out.writeBytes(orb.object_to_string(ref));
                    +        } catch (java.io.IOException e) {
                    +            System.err.println("Unable to open file "+fil);
                    +            System.exit(1);
                    +        }
                    +    }
                    +
                    +    public static void main(String args[]) {
                    +        try {
                    +            Properties props = new Properties( System.getProperties() ) ;
                    +            String className = ServerRequestHandler.class.getName() ;
                    +            props.setProperty( 
                    +                ORBConstants.BAD_SERVER_ID_HANDLER_CLASS_PROPERTY,
                    +                className ) ;
                    +            
                    +            ORB orb = ORB.init(args, System.getProperties());
                    +
                    +            com.sun.corba.ee.spi.orb.ORB ourORB
                    +                = (com.sun.corba.ee.spi.orb.ORB)orb;
                    +
                    +            System.out.println("==== Server GIOP version "
                    +                               + ourORB.getORBData().getGIOPVersion()
                    +                               + " with strategy "
                    +                               + ourORB.getORBData().getGIOPBuffMgrStrategy(
                    +                                   ourORB.getORBData().getGIOPVersion())
                    +                               + "====");
                    +
                    +            // Get rootPOA
                    +            POA rootPOA = (POA)orb.resolve_initial_references("RootPOA");
                    +            rootPOA.the_POAManager().activate();
                    +
                    +            FragmentTesterImpl impl = new FragmentTesterImpl(Server.interceptor);
                    +            javax.rmi.CORBA.Tie tie = javax.rmi.CORBA.Util.getTie( impl ) ;
                    +
                    +            byte[] id = rootPOA.activate_object(
                    +                (org.omg.PortableServer.Servant)tie ) ;
                    +                                                 
                    +            org.omg.CORBA.Object obj = rootPOA.id_to_reference( id ) ;
                    +
                    +            writeObjref(obj, "IOR", orb);
                    +
                    +            // Emit the handshake the test framework expects
                    +            // (can be changed in Options by the running test)
                    +            System.out.println ("Server is ready.");
                    +
                    +            // Wait for clients
                    +            orb.run();
                    +
                    +        } catch (Exception e) {
                    +            System.err.println("ERROR: " + e);
                    +            e.printStackTrace(System.out);
                    +
                    +            // Make sure to exit with a value greater than 0 on
                    +            // error.
                    +            System.exit(1);
                    +        }
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/nortel/Client.java b/test/src/share/classes/corba/nortel/Client.java
                    new file mode 100644
                    index 000000000..1470b40be
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/nortel/Client.java
                    @@ -0,0 +1,293 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.nortel;
                    +
                    +import java.util.Properties ;
                    +import java.util.Hashtable ;
                    +import java.util.Collection ;
                    +import java.util.ArrayList ;
                    +
                    +import java.rmi.RemoteException ;
                    +
                    +import javax.rmi.CORBA.Util ;
                    +import javax.rmi.CORBA.Tie ;
                    +
                    +import javax.naming.InitialContext ;
                    +
                    +import com.sun.corba.ee.spi.JndiConstants;
                    +import org.omg.CORBA.ORB ;
                    +
                    +import org.testng.TestNG ;
                    +import org.testng.Assert ;
                    +import org.testng.annotations.Test ;
                    +import org.testng.annotations.Configuration ;
                    +import org.testng.annotations.ExpectedExceptions ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService ;
                    +
                    +import static corba.framework.PRO.* ;
                    +
                    +public class Client {
                    +    private ORB clientORB ;
                    +    private ORB serverORB ;
                    +
                    +    private static final String TEST_REF_NAME = "testref" ;
                    +    private static final String SERVER_NAME = "fromServer" ;
                    +    private static final String CLIENT_NAME = "fromClient" ;
                    +    private static final String PORT_NUM = "3874" ;
                    +
                    +    private String BASE = "com.sun.corba.ee." ;
                    +
                    +    private void setSystemProperties() {
                    +        System.setProperty( "javax.rmi.CORBA.UtilClass",
                    +            BASE + "impl.javax.rmi.CORBA.Util" ) ;
                    +        System.setProperty( "javax.rmi.CORBA.StubClass",
                    +            BASE + "impl.javax.rmi.CORBA.StubDelegateImpl" ) ;
                    +        System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass",
                    +            BASE + "impl.javax.rmi.PortableRemoteObject" ) ;
                    +
                    +        // We will only use dynamic RMI-IIOP for this test.
                    +        dprint( "Setting property " + ORBConstants.USE_DYNAMIC_STUB_PROPERTY 
                    +            + " to true" ) ;
                    +        System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ;
                    +
                    +        // Use the J2SE ic provider
                    +        System.setProperty( "java.naming.factory.initial", 
                    +            JndiConstants.COSNAMING_CONTEXT_FACTORY ) ;
                    +    }
                    +
                    +    // We need to set up the client and server ORBs, and start a transient
                    +    // name server that runs on the server ORB, with the client ORB referring
                    +    // to the server ORB's name service.
                    +    private ORB makeORB( boolean isServer) {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "org.omg.CORBA.ORBClass", BASE + "impl.orb.ORBImpl" ) ;
                    +        props.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, "localhost" ) ;
                    +        props.setProperty( ORBConstants.INITIAL_PORT_PROPERTY, PORT_NUM ) ;
                    +        props.setProperty( ORBConstants.ALLOW_LOCAL_OPTIMIZATION, "true" ) ;
                    +
                    +        if (isServer) {
                    +            props.setProperty( ORBConstants.ORB_ID_PROPERTY, "serverORB" ) ;
                    +            props.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, PORT_NUM ) ;
                    +            props.setProperty( ORBConstants.SERVER_HOST_PROPERTY, "localhost" ) ;
                    +            props.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, "300" ) ;
                    +        } else {
                    +            props.setProperty( ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, 
                    +                NortelSocketFactory.class.getName() ) ;
                    +            props.setProperty( ORBConstants.ORB_ID_PROPERTY, "clientORB" ) ;
                    +        }
                    +
                    +        ORB orb = ORB.init( new String[0], props ) ;
                    +
                    +        if (isServer) {
                    +            new TransientNameService( 
                    +                com.sun.corba.ee.spi.orb.ORB.class.cast(orb) ) ;
                    +        }
                    +
                    +        return orb ;
                    +    }
                    +
                    +    private Echo makeServant( String name ) {
                    +        try {
                    +            return new EchoImpl( name ) ;
                    +        } catch (RemoteException rex) {
                    +            Assert.fail( "Unexpected remote exception " + rex ) ;
                    +            return null ; // never reached
                    +        }
                    +    }
                    +
                    +    private void doServer( ORB orb ) {
                    +        try {
                    +            Hashtable env = new Hashtable() ;
                    +            env.put( "java.naming.corba.orb", orb ) ;
                    +            InitialContext ic = new InitialContext( env ) ;
                    +
                    +            Echo servant = makeServant( SERVER_NAME ) ;
                    +            Tie tie = Util.getTie( servant ) ;
                    +            tie.orb( orb ) ;
                    +
                    +            Echo ref = toStub( servant, Echo.class ) ;
                    +            ic.bind( TEST_REF_NAME, ref ) ;
                    +        } catch (Exception exc) {
                    +            dprint( "Caught exception " + exc ) ;
                    +            exc.printStackTrace() ;
                    +            System.exit( 1 ) ;
                    +        }
                    +    }
                    +
                    +    private static void dprint( String msg ) {
                    +        System.out.println( msg ) ;
                    +    }
                    +
                    +    private static final int COUNT_TO_BREAK_CONNECTION = 15 ;
                    +    private static final int NUMBER_ITERATIONS = 30 ;
                    +
                    +    private void doClient( ORB orb ) {
                    +        try {
                    +            Hashtable env = new Hashtable() ;
                    +            env.put( "java.naming.corba.orb", orb ) ;
                    +            InitialContext ic = new InitialContext( env ) ;
                    +
                    +            Echo servant = makeServant( CLIENT_NAME ) ;
                    +            Tie tie = Util.getTie( servant ) ;
                    +            tie.orb( orb ) ;
                    +
                    +            dprint( "Creating first echoref" ) ;
                    +            Echo ref = toStub( servant, Echo.class ) ;
                    +
                    +            dprint( "Looking up second echoref" ) ;
                    +            Echo sref = narrow( ic.lookup( TEST_REF_NAME ), Echo.class ) ;
                    +            Assert.assertEquals( sref.name(), SERVER_NAME ) ;
                    +
                    +            dprint( "Echoing first echoref" ) ;
                    +            Echo rref = sref.say( ref ) ;
                    +            Assert.assertEquals( rref.name(), CLIENT_NAME ) ;
                    +
                    +            dprint( "Echoing second echoref" ) ;
                    +            Echo r2ref = rref.say( sref ) ;
                    +            Assert.assertEquals( r2ref.name(), SERVER_NAME ) ;
                    +
                    +            dprint( "Echoing third echoref" ) ;
                    +            Echo ref2 = ref.say( ref ) ;
                    +            Assert.assertEquals( ref2.name(), ref.name() ) ;
                    +
                    +            doLoop( r2ref, false ) ;
                    +            doLoop( r2ref, true ) ;
                    +        } catch (Exception exc) {
                    +            dprint( "Caught exception " + exc ) ;
                    +            exc.printStackTrace() ;
                    +            System.exit( 1 ) ;
                    +        }
                    +    }
                    +
                    +    private void doLoop( Echo ref, boolean useNio ) {
                    +        // NortelSocketFactory.disconnectSocket() ;
                    +        NortelSocketFactory.useNio = useNio ;
                    +
                    +        int numExceptions = 0 ;
                    +        for (int ctr=0; ctr closure1 = new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return Boolean.valueOf( ObjectUtility.equals( y1, y1 ) ) ;
                    +            }
                    +        } ;
                    +
                    +        session.testForPass( "Testing structural equals: 1", closure1,
                    +            Boolean.TRUE ) ;
                    +
                    +        NullaryFunction closure2 = new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return Boolean.valueOf( ObjectUtility.equals( y1, y2 ) ) ;
                    +            }
                    +        } ;
                    +
                    +        session.testForPass( "Testing structural equals: 2", closure2,
                    +            Boolean.TRUE ) ;
                    +
                    +        NullaryFunction closure3 = new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return Boolean.valueOf( ObjectUtility.equals( y1, y3 ) ) ;
                    +            }
                    +        } ;
                    +
                    +        session.testForPass( "Testing structural equals: 3", closure3,
                    +            Boolean.FALSE ) ;
                    +
                    +        NullaryFunction closure4 = new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return Boolean.valueOf( ObjectUtility.equals( y3, y4 ) ) ;
                    +            }
                    +        } ;
                    +
                    +        session.testForPass( "Testing structural equals: 4", closure4,
                    +            Boolean.FALSE ) ;
                    +
                    +        session.end() ;
                    +    }
                    +
                    +    private NullaryFunction makeActionEvaluator( final Operation action,
                    +        final Object data )
                    +    {
                    +        return new NullaryFunction() {
                    +            public Object evaluate() {
                    +                action.operate( data )  ;
                    +                return true ;
                    +            }
                    +        } ;
                    +    }
                    +
                    +    private void expectError( final Object data, final Operation action,
                    +        Class expectedError )
                    +    {
                    +        String msg = action + "(" + 
                    +            ObjectUtility.make( true, true ).objectToString(data) +
                    +            ") should throw " + expectedError ;
                    +
                    +        session.testForException( msg, makeActionEvaluator( action, data ), 
                    +            expectedError )  ;
                    +    }
                    +
                    +    private void expectResult( final Object data, final Operation action, 
                    +        final Object expectedResult ) 
                    +    {
                    +        String msg = action + "(" + 
                    +            ObjectUtility.make( true, true ).objectToString(data) + ") == " + 
                    +            ObjectUtility.make( true, true ).objectToString(expectedResult) + "?" ;
                    +
                    +        session.testForPass( msg, makeActionEvaluator( action, data ), 
                    +            expectedResult) ;
                    +    }
                    +
                    +    private void testOperations() 
                    +    {
                    +        session.start( "Operations" ) ;
                    +
                    +        // test indexAction
                    +        Operation indexAction = OperationFactory.indexAction( 3 ) ;
                    +
                    +        Integer[] data1 = { Integer.valueOf(0), Integer.valueOf(1) } ;
                    +        expectError( data1, indexAction, 
                    +            java.lang.IndexOutOfBoundsException.class ) ;
                    +
                    +        Integer[] data2 = { Integer.valueOf(0), Integer.valueOf(1), 
                    +                            Integer.valueOf(2), Integer.valueOf(3) } ;
                    +        expectResult( data2, indexAction, Integer.valueOf(3) ) ;
                    +
                    +        // test booleanAction
                    +        Operation booleanAction = OperationFactory.booleanAction() ;
                    +        expectResult( "TRUE", booleanAction, Boolean.valueOf( true ) ) ;
                    +        expectResult( "false", booleanAction, Boolean.valueOf( false ) ) ;
                    +        expectResult( "XXffOP2", booleanAction, Boolean.valueOf( false ) ) ;
                    +
                    +        // test integerAction
                    +        Operation integerAction = OperationFactory.integerAction() ;
                    +        expectResult( "123", integerAction, Integer.valueOf( 123 ) ) ;
                    +        expectError( "123ACE", integerAction, 
                    +            java.lang.NumberFormatException.class ) ;
                    +
                    +        // test stringAction
                    +        Operation stringAction = OperationFactory.stringAction() ;
                    +        expectResult( "This_is_a_string", stringAction, "This_is_a_string" ) ;
                    +
                    +        // test classAction
                    +        Operation classAction = OperationFactory.classAction( ORB.defaultClassNameResolver() ) ;
                    +        expectResult( "com.sun.corba.ee.spi.orb.ORB", classAction,
                    +            com.sun.corba.ee.spi.orb.ORB.class ) ;
                    +
                    +        // test setFlagAction
                    +        Operation setFlagAction = OperationFactory.setFlagAction() ;
                    +        expectResult( "", setFlagAction, Boolean.valueOf( true ) ) ;
                    +
                    +        // test URLAction
                    +        Operation URLAction = OperationFactory.URLAction() ;
                    +        URL testURL = null ;
                    +        try {
                    +            testURL = new URL( "http://www.sun.com" ) ;
                    +        } catch (java.net.MalformedURLException exc) {}
                    +
                    +        expectResult( "http://www.sun.com", URLAction, testURL ) ;
                    +        // For some reason, all strings seem to work: explore later.
                    +        // expectError( "zqxyr://somerandomstuff", URLAction,
                    +            // java.net.MalformedURLException.class ) ;
                    +
                    +        // test integerRangeAction
                    +        Operation integerRangeAction = OperationFactory.integerRangeAction(
                    +            12, 24 ) ;
                    +        expectResult( "13", integerRangeAction, Integer.valueOf( 13 ) ) ;
                    +        expectError( "123ACE", integerRangeAction, 
                    +            java.lang.NumberFormatException.class ) ;
                    +        expectError( "2", integerRangeAction, 
                    +            org.omg.CORBA.BAD_OPERATION.class ) ;
                    +
                    +        // test listAction
                    +        Operation listAction = OperationFactory.listAction( ",", 
                    +            integerAction ) ;
                    +        String arg = "12,23,34,56,129" ;
                    +        Object[] expectedResult = { Integer.valueOf( 12 ), Integer.valueOf( 23 ),
                    +            Integer.valueOf( 34 ), Integer.valueOf( 56 ), Integer.valueOf( 129 ) } ;
                    +
                    +        expectResult( arg, listAction, expectedResult ) ;
                    +
                    +        // test sequenceAction
                    +        Operation[] actions = { integerAction, integerAction, stringAction, 
                    +            booleanAction } ;
                    +        Operation sequenceAction = OperationFactory.sequenceAction( ",",
                    +            actions ) ;
                    +
                    +        String arg2 = "12,23,this_thing,true" ;
                    +        Object[] expectedResult2 = { Integer.valueOf( 12 ), Integer.valueOf( 23 ),
                    +            "this_thing", Boolean.valueOf( true ) } ;
                    +
                    +        expectResult( arg2, sequenceAction, expectedResult2 ) ;
                    +
                    +        // test compose
                    +        Operation composition = OperationFactory.compose( listAction, 
                    +            indexAction ) ;
                    +        expectResult( arg, composition, Integer.valueOf( 56 ) ) ;
                    +
                    +        // test mapAction
                    +        Operation map = OperationFactory.mapAction( integerAction ) ;
                    +        String[] strings = { "12", "23", "473", "2" } ;
                    +        Object[] result = { Integer.valueOf( 12 ), Integer.valueOf( 23 ), Integer.valueOf( 473 ),
                    +            Integer.valueOf( 2 ) } ;
                    +        expectResult( strings, map, result ) ;
                    +
                    +        session.end() ;
                    +    }
                    +
                    +    private PropertyParser makeParser()
                    +    {
                    +        PropertyParser parser = new PropertyParser() ;
                    +        parser.add( "foo.arg", OperationFactory.integerAction(), "arg" ) ;
                    +        parser.add( "foo.flag", OperationFactory.booleanAction(), "flag" ) ;
                    +        parser.add( "foo.str", OperationFactory.stringAction(), "str" ) ;
                    +        
                    +        parser.addPrefix( "foo.prefix", OperationFactory.identityAction(), 
                    +            "prefix", Object.class ) ;
                    +
                    +        // Action to parser , list into Object[][]
                    +        Operation[] inner = { OperationFactory.stringAction(), 
                    +            OperationFactory.integerAction() } ;
                    +        Operation innerList = OperationFactory.sequenceAction( ":", inner ) ;
                    +        Operation outerList = OperationFactory.listAction( ",", innerList ) ;
                    +        parser.add( "foo.list", outerList, "list" ) ;
                    +        return parser ;
                    +    }
                    +
                    +    private Properties makeTestProperties() 
                    +    {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "foo.arg", "273" ) ;
                    +        props.setProperty( "foo.flag", "true" ) ;
                    +        props.setProperty( "foo.str", "AValue" ) ;
                    +        props.setProperty( "foo.prefix.part1", "first" ) ;
                    +        props.setProperty( "foo.prefix.part2", "second" ) ;
                    +        props.setProperty( "foo.prefix.part3", "third" ) ;
                    +        props.setProperty( "foo.list", "red:0,blue:1,green:2" ) ;
                    +        return props ;
                    +    }
                    +
                    +    private Map makeResult()
                    +    {
                    +        Map map = new HashMap() ;
                    +        map.put( "arg", Integer.valueOf( 273 ) ) ;
                    +        map.put( "flag", Boolean.valueOf( true ) ) ;
                    +        map.put( "str", "AValue" ) ;
                    +
                    +        // This is the order the result comes in: the order is not
                    +        // guaranteed in this case.
                    +        Pair[] list = { 
                    +            new Pair( "part3", "third" ), 
                    +            new Pair( "part2", "second" ), 
                    +            new Pair( "part1", "first" ) 
                    +        };
                    +
                    +        map.put( "prefix", list ) ; 
                    +
                    +        Object[][] data = { 
                    +            { "red", Integer.valueOf( 0 ) },
                    +            { "blue", Integer.valueOf( 1 ) },
                    +            { "green", Integer.valueOf( 2 ) },
                    +        } ;
                    +
                    +        map.put( "list", data ) ;
                    +        return map ;
                    +    }
                    +
                    +    private void testParser() 
                    +    {
                    +        session.start( "Parser" ) ;
                    +        
                    +        final PropertyParser parser = makeParser() ;
                    +        final Properties props = makeTestProperties() ;
                    +        NullaryFunction closure  =
                    +            new NullaryFunction() {
                    +            public Map evaluate() {
                    +                return parser.parse( props )  ; 
                    +            }
                    +        } ;
                    +
                    +        Map expectedResult = makeResult() ;
                    +
                    +        session.testForPass( "parser", closure, expectedResult ) ;
                    +
                    +        session.end() ;
                    +    }
                    +
                    +
                    +    // test design:
                    +    // Properties we will use:              Type:
                    +    //      INITIAL_HOST_PROPERTY           string
                    +    //      SERVER_HOST_PROPERTY            string
                    +    //      ORB_INIT_REF_PROPERTY           (string,string)[] (prefix)
                    +    //      foo.arg1                        integer
                    +    //      foo.prefix                      (string,Foo)[]  (prefix)
                    +    //      ORG_OMG_CORBA_PREFIX.poa.maxhold        integer
                    +    //      SUN_PREFIX.poa.foo              Foo
                    +    //      SUN_LC_PREFIX.pool.size         integer
                    +    //      SUN_LC_VERSION_PREFIX.bar.foo   Foo
                    +    // also need to write orb.properties files (and also preserve any
                    +    // installed orb.properties files)
                    +
                    +    private static class Foo{
                    +        private String data ;
                    +
                    +        public Foo( String str )
                    +        {
                    +            data = str ;
                    +        }
                    +
                    +        public boolean equals( Object obj ) 
                    +        {
                    +            if (this == obj)
                    +                return true ;
                    +
                    +            if (!(obj instanceof Foo))
                    +                return false ;
                    +
                    +            Foo other = (Foo)obj ;
                    +
                    +            return other.data.equals( data ) ;
                    +        }
                    +
                    +        public int hashCode()
                    +        {
                    +            return data.hashCode() ;
                    +        }
                    +
                    +        public String toString()
                    +        {
                    +            return data ;
                    +        }
                    +
                    +        private static Operation getOperation()
                    +        {
                    +            return new Operation() {
                    +                public Object operate( Object arg ) {
                    +                    return new Foo( (String)arg ) ;
                    +                }
                    +            } ;
                    +        }
                    +    }
                    +
                    +    private PropertyParser makeDCParser()
                    +    {
                    +        PropertyParser parser = new PropertyParser() ;
                    +        parser.add( ORBConstants.INITIAL_HOST_PROPERTY, 
                    +            OperationFactory.stringAction(), "initialHost" ) ;
                    +        parser.add( ORBConstants.SERVER_HOST_PROPERTY,
                    +            OperationFactory.stringAction(), "serverHost" ) ;
                    +        parser.add( ORBConstants.ORB_INIT_REF_PROPERTY,
                    +            OperationFactory.identityAction(), "initRefs" ) ;
                    +        parser.add( "foo.ORBarg1", Foo.getOperation(), "fooArg1" ) ;
                    +
                    +        Operation[] ops = { OperationFactory.stringAction(), Foo.getOperation() } ;
                    +        Operation prefixOp = OperationFactory.mapSequenceAction( ops ) ;
                    +        parser.addPrefix( "foo.prefix", prefixOp, "fooPrefix", Object.class ) ;
                    +        parser.add( ORBConstants.CORBA_PREFIX + "poa.ORBmaxhold", 
                    +            OperationFactory.integerAction(), "poaMaxHold" ) ;
                    +        parser.addPrefix( ORBConstants.CORBA_PREFIX + "ORBmodule", 
                    +            OperationFactory.stringAction(), "module", String.class ) ;
                    +        parser.add( ORBConstants.SUN_PREFIX + "poa.ORBfoo", Foo.getOperation(),
                    +            "poaFoo" ) ;
                    +        parser.add( ORBConstants.SUN_PREFIX + "pool.ORBsize",
                    +            OperationFactory.integerAction(), "poolSize" ) ;
                    +        parser.add( ORBConstants.SUN_PREFIX + "bar.foo",
                    +            Foo.getOperation(), "barFoo" ) ;
                    +        return parser ;
                    +    }
                    +
                    +    private String[] makeDCArgs()
                    +    {
                    +        // Note that the -ORBModule flag should be ignored, as this is not
                    +        // supported for prefixes.
                    +        String[] result = { "-ORBmaxHold", "27",
                    +            "-ORBInitRef", "FooService=corbaloc::host.org/FooService", 
                    +            "-ORBInitRef", "BarService=corbaloc::host.org/BarService",
                    +            "-ORBmodule.doorTransport", "doorTransportImpl" } ;
                    +        return result ;
                    +    }
                    +
                    +    private static class TestAppletStub implements AppletStub {
                    +        private Properties parameters ;
                    +        private URL codeBase ;
                    +        private URL documentBase ;
                    +
                    +        TestAppletStub(  Properties parameters, URL codeBase, 
                    +            URL documentBase ) 
                    +        {
                    +            this.parameters = parameters ;
                    +            this.codeBase = codeBase ;
                    +            this.documentBase = documentBase ;
                    +        }
                    +
                    +        public void appletResize( int width, int height )
                    +        {
                    +        }
                    +
                    +        public AppletContext getAppletContext() 
                    +        {
                    +            return null ;
                    +        }
                    +
                    +        public URL getCodeBase()
                    +        {
                    +            return codeBase ;
                    +        }
                    +
                    +        public URL getDocumentBase()
                    +        {
                    +            return documentBase ;
                    +        }
                    +
                    +        public String getParameter( String name )
                    +        {
                    +            return parameters.getProperty( name ) ;
                    +        }
                    +
                    +        public boolean isActive()
                    +        {
                    +            return false ;
                    +        }
                    +    }   
                    +
                    +    // This applet needs to support getDocumentBase, getParameter, and getCodeBase
                    +    private Applet makeDCApplet( Properties parameters, URL codeBase, 
                    +        URL documentBase )
                    +    {
                    +        AppletStub stub = new TestAppletStub( parameters, codeBase, documentBase ) ;
                    +        Applet result = new Applet() ;
                    +        result.setStub( stub ) ;
                    +        return result ;
                    +    }
                    +
                    +    private Properties makeDCProperties()
                    +    {
                    +        Properties result = new Properties() ;
                    +        result.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, "thisHost" ) ;
                    +        result.setProperty( ORBConstants.SERVER_HOST_PROPERTY, "thatHost" ) ;
                    +        result.setProperty( ORBConstants.ORB_INIT_REF_PROPERTY, 
                    +            "NameService=corbaloc::host.org/NameService" ) ;
                    +        result.setProperty( "foo.ORBarg1", "MyFoo" ) ;
                    +        result.setProperty( "foo.prefix.stuff1", "AnotherFoo" ) ;
                    +        result.setProperty( "foo.prefix.somestuff", "More Foo" ) ;
                    +        result.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.iiopTransport", 
                    +            "iiopTransportImpl" ) ;
                    +        result.setProperty( ORBConstants.CORBA_PREFIX + "poa.ORBmaxhold", "351" ) ;
                    +        result.setProperty( ORBConstants.SUN_PREFIX + "poa.ORBfoo", "ALittleFoo" ) ;
                    +        result.setProperty( ORBConstants.SUN_PREFIX + "pool.ORBsize", "25000" ) ;
                    +        result.setProperty( ORBConstants.SUN_PREFIX + "bar.foo", "YetAnotherFoo" ) ;
                    +        return result ;
                    +    }
                    +
                    +    private Properties makeDCAppletProperties()
                    +    {
                    +        Properties result = new Properties() ;
                    +        result.setProperty( ORBConstants.ORB_INIT_REF_PROPERTY, 
                    +            "TraderService=corbaloc::host.org/TraderService" ) ;
                    +        result.setProperty( "foo.prefix.stuff2", "2AnotherFoo" ) ;
                    +        result.setProperty( ORBConstants.SUN_PREFIX + "pool.ORBsize", "4000" ) ;
                    +        return result ;
                    +    }
                    +
                    +    private OutputStream makeFileOutputStream( String fileName ) 
                    +    {
                    +        try {
                    +            File file = new File( fileName ) ;
                    +            FileOutputStream out = new FileOutputStream( file ) ;
                    +            return out ;
                    +        } catch (Exception exc) {
                    +            System.out.println( 
                    +                "Unexpected exception in makeFileOutputStream for " 
                    +                + fileName + ": " + exc ) ;
                    +            return null ;
                    +        }
                    +    }
                    +
                    +    private void setDCSystemProperties()
                    +    {
                    +        System.setProperty( "foo.prefix.still.more.stuff", "Too much Foo" ) ;
                    +        System.setProperty( ORBConstants.SUN_PREFIX + "pool.ORBsize", "24000" ) ;
                    +        System.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.soapTransport", 
                    +            "soapTransportImpl" ) ;
                    +    }
                    +        
                    +    private void setDCUserORBFile()
                    +    {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "foo.prefix.somestuff", "Too much Foo" ) ;
                    +        props.setProperty( ORBConstants.SUN_PREFIX + "poa.ORBfoo", "tinyFoo" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.localTransport", 
                    +            "localTransportImpl" ) ;
                    +        OutputStream os = makeFileOutputStream( System.getProperty( "user.home" ) + 
                    +            File.separator + "orb.properties" ) ;
                    +        try {
                    +            props.store( os, "New ORB test properties" ) ;
                    +        } catch (java.io.IOException exc) {
                    +            throw new Error( "Unexpected exception", exc ) ;
                    +        }
                    +    }
                    +
                    +    private void setDCSystemORBFile()
                    +    {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "foo.prefix.somestuff", "Even More Foo" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "poa.ORBmaxhold", "35144" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.localTransport", 
                    +            "localTransportStdImpl" ) ;
                    +        OutputStream os = makeFileOutputStream( System.getProperty( "java.home" ) + 
                    +            File.separator + "lib" + File.separator + "orb.properties" ) ;
                    +        if (os != null) {
                    +            try {
                    +                props.store( os, "New ORB test properties" ) ;
                    +            } catch (java.io.IOException exc) {
                    +                throw new Error( "Unexpected exception", exc ) ;
                    +            }
                    +        } else {
                    +            noJavaHomeAvailable = true ;
                    +        }
                    +    }
                    +
                    +    // Common DataCollector tests:
                    +    // getProperties raises IllegalStateException before setParser call
                    +    // setParser may be called more than once
                    +    // getProperties returns correct properties after setParser call
                    +    // Testing properties in result:
                    +    //      INITIAL_HOST_PROPERTY and INITIAL_SERVER_PROPERTY defaults
                    +    //      -ORB arguments are converted to matching properties
                    +    //      URL properties for applets are made absolute
                    +    //      ORB_INIT_REF_PROPERTY correctly converted to properties
                    +    //      Only corba properties come from system properties
                    +    // Correct overriding:
                    +    //      applet case:
                    +    //          props then applet
                    +    //      normal case:
                    +    //          system, props, /orb.properties,
                    +    //              /orb.properties, finally args
                    +    // Verify that intersection of parser prop names are present in
                    +    //      result iff they are available in data.
                    +
                    +    private void testDataCollectorState( String name, PropertyParser parser,
                    +        final DataCollector dc, boolean expectedAppletResult, 
                    +        Properties expectedProperties )
                    +    {
                    +        NullaryFunction isAppletNullaryFunction =
                    +            new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return Boolean.valueOf( dc.isApplet() ) ;
                    +            }
                    +        } ;
                    +
                    +        session.testForPass( name + "isApplet", isAppletNullaryFunction,
                    +            Boolean.valueOf( expectedAppletResult ) ) ;
                    +
                    +        NullaryFunction getPropertiesNullaryFunction =
                    +            new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return dc.getProperties() ;
                    +            }
                    +        } ;
                    +
                    +        session.testForException( name + "getProperties before setParser", 
                    +            getPropertiesNullaryFunction, IllegalStateException.class ) ;
                    +
                    +        dc.setParser( parser ) ;
                    +
                    +        session.testForPass( name + "getProperties after setParser", 
                    +            getPropertiesNullaryFunction, expectedProperties ) ;
                    +    }
                    +
                    +    private void setupDCEnvironment()
                    +    {
                    +        setDCSystemProperties() ;
                    +        setDCUserORBFile() ;
                    +        setDCSystemORBFile() ;
                    +    }
                    +
                    +    private void testNormalDataCollector() 
                    +    {
                    +        session.start( "Normal DataCollector" ) ;
                    +
                    +        String[] args = null ;
                    +        DataCollector dc1 = DataCollectorFactory.create( args, null,
                    +            "MyHost" ) ;
                    +        PropertyParser parser = new PropertyParser() ;
                    +        Properties props = new Properties() ;
                    +        props.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, "MyHost" ) ;
                    +        testDataCollectorState( "1: no data, verify results: ", parser,
                    +            dc1, false, props ) ;
                    +
                    +        args = makeDCArgs() ;
                    +        PropertyParser parser2 = makeDCParser() ;
                    +        Properties parameters = makeDCProperties() ;
                    +        DataCollector dc2 = DataCollectorFactory.create( args, parameters, "MyHost" ) ;
                    +        props = makeDCNormalResult() ;
                    +        testDataCollectorState( "2: no data, verify results: ", parser2,
                    +            dc2, false, props ) ;
                    +
                    +        session.end() ;
                    +    }
                    +
                    +// Expected results (in override order: later overrides earlier):
                    +// From setDCSystemProperties: (not in applet mode)
                    +//      "foo.prefix.still.more.stuff", "Too much Foo" (not allowed, since this is a std prefix!)
                    +//      ORBConstants.SUN_LC_PREFIX + "pool.ORBsize", "24000" 
                    +// From system file:
                    +//      "foo.prefix.somestuff", "Even More Foo" 
                    +//      ORBConstants.ORG_OMG_CORBA_PREFIX + "poa.ORBmaxhold", "35144" 
                    +// From user home dir file:
                    +//      "foo.prefix.somestuff", "Too much Foo" 
                    +//      ORBConstants.SUN_PREFIX + "poa.ORBfoo", "tinyFoo" 
                    +// From makeDCProperties():
                    +//      ORBConstants.INITIAL_HOST_PROPERTY, "thisHost" 
                    +//      ORBConstants.SERVER_HOST_PROPERTY, "thatHost" 
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY, "NameService=corbaloc::host.org/NameService" 
                    +//      "foo.ORBarg1", "MyFoo" 
                    +//      "foo.prefix.stuff1", "AnotherFoo" 
                    +//      "foo.prefix.somestuff", "More Foo" 
                    +//      ORBConstants.ORG_OMG_CORBA_PREFIX + "poa.ORBmaxhold", "351" 
                    +//      ORBConstants.SUN_PREFIX + "poa.ORBfoo", "ALittleFoo" 
                    +//      ORBConstants.SUN_LC_PREFIX + "pool.ORBsize", "25000" 
                    +//      ORBConstants.SUN_LC_VERSION_PREFIX + "bar.foo", "YetAnotherFoo" 
                    +// From makeDCApplet( makeDCAppletProperties(), new URL( "http://www.bar.com" ),
                    +//      new URL( "http://www.foo.com" ) ):
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY, "TraderService=corbaloc::host.org/TraderService" 
                    +//      "foo.prefix.stuff2", "2AnotherFoo" 
                    +//      ORBConstants.SUN_LC_PREFIX + "pool.ORBsize", "4000" ;
                    +// From args (normal case only):
                    +//      ORBConstants.ORG_OMG_CORBA_PREFIX + "poa.ORBmaxhold", "27"
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.FooService, "corbaloc::host.org/FooService" 
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.BarService, "corbaloc::host.org/BarService" 
                    +// 
                    +// Expected result from the above (applet case):
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.TraderService, "corbaloc::host.org/TraderService" 
                    +//      "foo.prefix.stuff2", "2AnotherFoo" 
                    +//      ORBConstants.SUN_LC_PREFIX + "pool.ORBsize", "4000" 
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.NameService, "corbaloc::host.org/NameService" 
                    +//      "foo.ORBarg1", "MyFoo" 
                    +//      "foo.prefix.stuff1", "AnotherFoo" 
                    +//      "foo.prefix.somestuff", "More Foo" 
                    +//      ORBConstants.ORG_OMG_CORBA_PREFIX + "poa.ORBmaxhold", "351" 
                    +//      ORBConstants.SUN_PREFIX + "poa.ORBfoo", "ALittleFoo" 
                    +//      ORBConstants.SUN_LC_VERSION_PREFIX + "bar.foo", "YetAnotherFoo" 
                    +//      ORBConstants.INITIAL_HOST_PROPERTY, "thisHost" 
                    +//      ORBConstants.SERVER_HOST_PROPERTY, "thatHost" 
                    +//
                    +// Expected result from the above (normal case):
                    +//      ORBConstants.ORG_OMG_CORBA_PREFIX + "poa.ORBmaxhold", "27"
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.FooService, "corbaloc::host.org/FooService" 
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.BarService, "corbaloc::host.org/BarService" 
                    +//      ORBConstants.SUN_LC_PREFIX + "pool.ORBsize", "25000" 
                    +//      ORBConstants.ORB_INIT_REF_PROPERTY.NameService, "corbaloc::host.org/NameService" 
                    +//      "foo.ORBarg1", "MyFoo" 
                    +//      "foo.prefix.stuff1", "AnotherFoo" 
                    +//      "foo.prefix.somestuff", "More Foo" 
                    +//      ORBConstants.ORG_OMG_CORBA_PREFIX + "poa.ORBmaxhold", "351" 
                    +//      ORBConstants.SUN_PREFIX + "poa.ORBfoo", "ALittleFoo" 
                    +//      ORBConstants.SUN_LC_VERSION_PREFIX + "bar.foo", "YetAnotherFoo" 
                    +//      ORBConstants.INITIAL_HOST_PROPERTY, "thisHost" 
                    +//      ORBConstants.SERVER_HOST_PROPERTY, "thatHost" 
                    +
                    +    private Properties makeDCAppletResult()
                    +    {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( "org.omg.CORBA.ORBInitRef.TraderService", 
                    +            "corbaloc::host.org/TraderService" ) ;
                    +        props.setProperty( ORBConstants.SUN_PREFIX + "pool.ORBsize", "4000" ) ;
                    +        props.setProperty( "org.omg.CORBA.ORBInitRef.NameService", "corbaloc::host.org/NameService" ) ;
                    +        props.setProperty( "foo.ORBarg1", "MyFoo" ) ;
                    +        props.setProperty( "foo.prefix.stuff1", "AnotherFoo" ) ;
                    +        props.setProperty( "foo.prefix.somestuff", "More Foo" ) ;
                    +        props.setProperty( "org.omg.CORBA.poa.ORBmaxhold", "351" ) ;
                    +        props.setProperty( ORBConstants.SUN_PREFIX + "poa.ORBfoo", "ALittleFoo" ) ;
                    +        props.setProperty( "com.sun.corba.ee.bar.foo", "YetAnotherFoo" ) ;
                    +        props.setProperty( "org.omg.CORBA.ORBInitialHost", "thisHost" ) ;
                    +        props.setProperty( "com.sun.corba.ee.ORBServerHost", "thatHost" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.iiopTransport", 
                    +            "iiopTransportImpl" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.localTransport", 
                    +            "localTransportImpl" ) ;
                    +        return props ;
                    +    }
                    +
                    +    private Properties makeDCNormalResult()
                    +    {
                    +        Properties props = new Properties() ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "poa.ORBmaxhold", "27" ) ;
                    +        props.setProperty( ORBConstants.ORB_INIT_REF_PROPERTY + ".FooService", 
                    +            "corbaloc::host.org/FooService" ) ;
                    +        props.setProperty( ORBConstants.ORB_INIT_REF_PROPERTY + ".BarService", 
                    +            "corbaloc::host.org/BarService" ) ;
                    +        props.setProperty( "com.sun.corba.ee.pool.ORBsize", "25000" ) ;
                    +        props.setProperty( "org.omg.CORBA.ORBInitRef.NameService", "corbaloc::host.org/NameService" ) ;
                    +        props.setProperty( "foo.ORBarg1", "MyFoo" ) ;
                    +        props.setProperty( "foo.prefix.stuff1", "AnotherFoo" ) ;
                    +        props.setProperty( "foo.prefix.somestuff", "More Foo" ) ;
                    +        props.setProperty( "org.omg.CORBA.poa.ORBmaxhold", "351" ) ;
                    +        props.setProperty( "com.sun.corba.ee.poa.ORBfoo", "ALittleFoo" ) ;
                    +        props.setProperty( "com.sun.corba.ee.bar.foo", "YetAnotherFoo" ) ;
                    +        props.setProperty( "org.omg.CORBA.ORBInitialHost", "thisHost" ) ;
                    +        props.setProperty( "com.sun.corba.ee.ORBServerHost", "thatHost" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.iiopTransport", 
                    +            "iiopTransportImpl" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.soapTransport", 
                    +            "soapTransportImpl" ) ;
                    +        props.setProperty( ORBConstants.CORBA_PREFIX + "ORBmodule.localTransport", 
                    +            "localTransportImpl" ) ;
                    +        return props ;
                    +    }
                    +
                    +    private void testAppletDataCollector() 
                    +    {
                    +        session.start( "Applet DataCollector" ) ;
                    +
                    +        Properties appProps = new Properties() ;
                    +        URL codeBase ;
                    +        URL documentBase ;
                    +        try {
                    +            codeBase = new URL( "http://www.bar.com" ) ;
                    +            documentBase = new URL( "http://www.foo.com" ) ;
                    +        } catch (MalformedURLException exc) {
                    +            throw new Error( "Unexpected Exception", exc ) ;
                    +        }
                    +
                    +        Applet app = makeDCApplet( appProps, codeBase, documentBase ) ; 
                    +
                    +        DataCollector dc1 = DataCollectorFactory.create( app, null,
                    +            "MyHost" ) ;
                    +        PropertyParser parser = new PropertyParser() ;
                    +        Properties props = new Properties() ;
                    +        props.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, "www.bar.com" ) ;
                    +        testDataCollectorState( "1: no data, verify results: ", parser,
                    +            dc1, true, props ) ;
                    +
                    +        appProps = makeDCAppletProperties() ;
                    +        app = makeDCApplet( appProps, codeBase, documentBase ) ;
                    +        PropertyParser parser2 = makeDCParser() ;
                    +        Properties parameters = makeDCProperties() ;
                    +        DataCollector dc2 = DataCollectorFactory.create( app, parameters, "MyHost" ) ;
                    +        props = makeDCAppletResult() ;
                    +        testDataCollectorState( "2: no data, verify results: ", parser2,
                    +            dc2, true, props ) ;
                    +
                    +        session.end() ;
                    +    }
                    +
                    +    private Set makeSetFromArray( Object array )
                    +    {
                    +        Set result = new HashSet() ;
                    +        if (array != null) {
                    +            if (!array.getClass().isArray())
                    +                throw new Error( "makeSetFromArray called with non-array argument" ) ;
                    +
                    +            int size = Array.getLength( array ) ;
                    +            for (int ctr=0; ctr closure = new NullaryFunction() {
                    +            public Object evaluate() {
                    +                return Boolean.valueOf( MyConfigurator.wasCalled ) ;
                    +            }
                    +        } ;
                    +
                    +        session.testForPass( "UserConfigurator", closure, Boolean.TRUE ) ;
                    +
                    +        session.end() ;
                    +    }
                    +
                    +    private void testORBServerHostAndListenOnAllInterfaces()
                    +    {
                    +        // three things to test here:
                    +        // 1. ORBServerHost default value and 'listen on all interfaces' default
                    +        //    Expected result is the IP address of the machine where the test is
                    +        //    being run and listen on all interfaces to be true.
                    +        // 2. ORBServer host set in a property and 'listen on all interfaces'
                    +        //    Expected result is host as set in property and listen on all
                    +        //    interfaces set to false.
                    +        // 3. Verify DataCollector calls parser's complete() method only one
                    +        //    time.
                    +
                    +        System.out.println("\tTest ORBServerHost and Listen on all interfaces");
                    +
                    +        // Case 1
                    +        ORB orb = (ORB)ORB.init();
                    +        String[] args = null ;
                    +        DataCollector dc = DataCollectorFactory.create(args, null, "MyHost");
                    +        ORBDataParserImpl od1 = new ORBDataParserImpl(orb, dc);
                    +        String expected_ip;
                    +        try
                    +        {
                    +            expected_ip =  InetAddress.getLocalHost().getHostAddress();
                    +        }
                    +        catch (UnknownHostException uhe)
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " default ORBServerHost test, failed to get IP address: " +
                    +                         uhe.toString();
                    +            throw new Error(msg);
                    +        }
                    +
                    +        if (!expected_ip.equals(od1.getORBServerHost()))
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " default ORBServerHost test, getORBServerHost() != " + 
                    +                         expected_ip;
                    +            throw new Error(msg);
                    +        }
                    +        if (!od1.getListenOnAllInterfaces())
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " default getListenOnAllInterfaces test";
                    +            throw new Error(msg);
                    +        }
                    +
                    +        // Case 2
                    +
                    +        // if ORBServerHost is set to "0.0.0.0", then listen on all interfaces
                    +        // should be true
                    +        Properties props = new Properties();
                    +        String allHosts = "0.0.0.0";
                    +        props.setProperty(ORBConstants.SERVER_HOST_PROPERTY, allHosts);
                    +        dc = DataCollectorFactory.create(args, props, "MyHost");
                    +        od1 = new ORBDataParserImpl(orb, dc);
                    +        if (!expected_ip.equals(od1.getORBServerHost()))
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " ORBServerHost property = " + allHosts + 
                    +                         " test, getORBServerHost() != " + expected_ip;
                    +            throw new Error(msg);
                    +        }
                    +        if (!od1.getListenOnAllInterfaces())
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " ORBServerHost property = " + allHosts +
                    +                         " test, listenOnAllInterfaces should be true";
                    +            throw new Error(msg);
                    +        }
                    +
                    +        // if ORBServerHost is set to a specific host, then listen on all
                    +        // interfaces should be false
                    +        props = new Properties();
                    +        String expectedHost = "thatHost";
                    +        props.setProperty(ORBConstants.SERVER_HOST_PROPERTY, expectedHost);
                    +        dc = DataCollectorFactory.create(args, props, "MyHost");
                    +        od1 = new ORBDataParserImpl(orb, dc);
                    +        if (!expectedHost.equals(od1.getORBServerHost()))
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " ORBServerHost property = " + expectedHost + 
                    +                         " test, getORBServerHost() != " + expectedHost +
                    +                         " getORBServerHost = " + od1.getORBServerHost();
                    +            throw new Error(msg);
                    +        }
                    +        if (od1.getListenOnAllInterfaces())
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " ORBServerHost property = " + expectedHost +
                    +                         " test, listenOnAllInterfaces should be false";
                    +            throw new Error(msg);
                    +        }
                    +
                    +        // case 3
                    +        // Verify DataCollector calls parser's complete() only once.
                    +        SimpleParser simpleParser = new SimpleParser(dc);
                    +        try
                    +        {
                    +            simpleParser = new SimpleParser(dc);
                    +        }
                    +        catch (IllegalStateException ise)
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                          ise.toString();
                    +            throw new Error(msg);
                    +        }
                    +
                    +        if (!simpleParser.errorIfCalledTooManyTimes())
                    +        {
                    +            String msg = "testORBServerHostAndListenOnAllInterfaces FAILED" +
                    +                         " SimpleParser.complete() called too many times";
                    +            throw new Error(msg);
                    +        }
                    +
                    +        System.out.println("\t\tPASSED");
                    +     }
                    +
                    +    // A simple parser that ensures the parser framework will
                    +    // call the overriden complete() method at most one time.
                    +    private static class SimpleParser extends ParserImplBase
                    +    {
                    +        private int numberOfCompleteMethodInvokes;
                    +        private DataCollector itsDataCollector;
                    +
                    +        public SimpleParser(DataCollector dataCollector)
                    +        {
                    +            numberOfCompleteMethodInvokes = 0;
                    +            // this will force a call to this.complete()
                    +            init(dataCollector);
                    +        }
                    +
                    +        public PropertyParser makeParser()
                    +        {
                    +            PropertyParser parser = new PropertyParser() ;
                    +            return parser ;
                    +        }
                    +
                    +        public void complete()
                    +        {
                    +            if (++numberOfCompleteMethodInvokes > 1)
                    +            {
                    +                throw new IllegalStateException("complete() called too many times" +
                    +                                                 numberOfCompleteMethodInvokes);
                    +            }
                    +        }
                    +
                    +        public boolean errorIfCalledTooManyTimes()
                    +        {
                    +            boolean result = false;
                    +            try
                    +            {
                    +                this.complete();
                    +            }
                    +            catch (IllegalStateException ise)
                    +            {
                    +                System.out.println("\t\tIllegalStateException thrown as expected...");
                    +                result = true;
                    +            }
                    +            return result;
                    +        }
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/orbconfig/MyConfigurator.java b/test/src/share/classes/corba/orbconfig/MyConfigurator.java
                    new file mode 100644
                    index 000000000..ac8bed7e2
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/orbconfig/MyConfigurator.java
                    @@ -0,0 +1,25 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.orbconfig ;
                    +
                    +import com.sun.corba.ee.spi.orb.DataCollector ;
                    +import com.sun.corba.ee.spi.orb.ORBConfigurator ;
                    +import com.sun.corba.ee.spi.orb.ORB ;
                    +
                    +public class MyConfigurator implements ORBConfigurator
                    +{
                    +    public static boolean wasCalled = false ;
                    +
                    +    public void configure( DataCollector dc, ORB orb ) 
                    +    {
                    +        wasCalled = true ;
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/orbconfig/NewORBTests.java b/test/src/share/classes/corba/orbconfig/NewORBTests.java
                    new file mode 100644
                    index 000000000..96f1f6903
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/orbconfig/NewORBTests.java
                    @@ -0,0 +1,37 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.orbconfig;
                    +
                    +import test.Test;
                    +import corba.framework.*;
                    +
                    +
                    +public class NewORBTests extends CORBATest
                    +{
                    +    protected void doTest() throws Throwable
                    +    {
                    +        // Create client controller using the given
                    +        // class.  You can also specify names for these (for instance,
                    +        // you may want to distinguish between many clients) by using
                    +        // the equivalent methods that take two Strings.
                    +        Controller client = createClient("corba.orbconfig.Client");
                    +
                    +        client.start();
                    +
                    +        // Wait for the client to finish for up to 2 minutes, then
                    +        // throw an exception.
                    +        client.waitFor(120000);
                    +
                    +        // Make sure all the processes are shut down.
                    +        client.stop();
                    +    }
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/orbconfig/TestSession.java b/test/src/share/classes/corba/orbconfig/TestSession.java
                    new file mode 100644
                    index 000000000..f5158e1a3
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/orbconfig/TestSession.java
                    @@ -0,0 +1,143 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.orbconfig;
                    +
                    +import java.io.PrintStream ;
                    +
                    +import java.util.ArrayList ;
                    +import java.util.List ;
                    +import org.glassfish.pfl.basic.func.NullaryFunction;
                    +import org.glassfish.pfl.test.JUnitReportHelper;
                    +import org.glassfish.pfl.test.ObjectUtility;
                    +
                    +/** TestSession manages running of tests and checking results within
                    +* a test session.  If the session fails any test, the whole session 
                    +* fails with an Error, which can be used to trigger failure in the
                    +* CORBA test framework.  This allows complete testing on a major subsystem
                    +* to report a series of failures, while better containing failures by
                    +* not testing related subsystems.
                    +*/
                    +public class TestSession 
                    +{
                    +    private JUnitReportHelper helper ;
                    +    private PrintStream out ;
                    +    private boolean errorFlag ;
                    +    private String sessionName ;
                    +    private List failures ;
                    +
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +// Public interface
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +
                    +    public TestSession( PrintStream out, JUnitReportHelper helper )
                    +    {
                    +        this.out = System.out ;
                    +        this.helper = helper ;
                    +    }
                    +
                    +    /** Print a message indicating the start of the session.
                    +    * Also clears the error flag.
                    +    */
                    +    public void start( String sessionName ) 
                    +    {
                    +        this.sessionName = sessionName ;
                    +        this.errorFlag = false ;
                    +        out.println( "Test Session " + sessionName ) ;
                    +        helper.start( sessionName ) ;
                    +        failures = new ArrayList() ;
                    +    }
                    +
                    +    /** Check for errors at the end of the session.
                    +    */
                    +    public void end()
                    +    {
                    +        if (errorFlag) {
                    +            StringBuilder sb = new StringBuilder() ;
                    +            sb.append( "Test failed with errors:\n" ) ;
                    +            for (String thr : failures) {
                    +                sb.append( "    " ) ;
                    +                sb.append( thr ) ;
                    +                sb.append( "\n" ) ;
                    +            }
                    +            String msg = sb.toString() ;
                    +            helper.fail( msg ) ;
                    +            throw new Error( msg ) ;
                    +        } else {
                    +            helper.pass() ;
                    +        }
                    +    }
                    +
                    +    public void testForPass( String name, NullaryFunction closure,
                    +        Object expectedResult )
                    +    {
                    +        try {
                    +            testStart( name ) ;
                    +            Object result = closure.evaluate() ;
                    +
                    +            if (ObjectUtility.equals( result, expectedResult))
                    +                testPass() ;
                    +            else {
                    +                testFail( "Unexpected result returned" ) ;
                    +                out.println( "\t\t\tExpected Result=" +
                    +                    ObjectUtility.defaultObjectToString( expectedResult ) ) ;
                    +                out.println( "\t\t\tActual   Result=" +
                    +                    ObjectUtility.defaultObjectToString( result ) ) ;
                    +            }
                    +        } catch (Throwable thr) {
                    +            testFail( "Unexpected exception " + thr ) ;
                    +            thr.printStackTrace() ;
                    +        }
                    +    }
                    +    
                    +    public void testForException( String name, NullaryFunction closure,
                    +        Class expectedExceptionClass )
                    +    {
                    +        try {
                    +            testStart( name ) ;
                    +            closure.evaluate();
                    +            testFail( "NullaryFunction did not throw expected exception" ) ;
                    +        } catch (Throwable thr) {
                    +            if (expectedExceptionClass.isAssignableFrom( thr.getClass() ))
                    +                testPass( "with exception " + thr ) ;
                    +            else
                    +                testFail( "Unexpected exception" + thr ) ;
                    +        }
                    +    }
                    +
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +// Internal implementation
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +
                    +    private void testStart( String name )
                    +    {
                    +        out.println( "\tTest " + name + "..." ) ;
                    +    }
                    +
                    +    private void testFail( String msg )
                    +    {
                    +        failures.add( msg ) ;
                    +        out.println( "\t\tFAILED: " + msg ) ;
                    +        errorFlag = true ;
                    +    }
                    +
                    +    private void testPass() 
                    +    {
                    +        testPass( null ) ;
                    +    }
                    +
                    +    private void testPass( String msg )
                    +    {
                    +        out.print( "\t\tPASSED" ) ;
                    +        if ((msg != null) && (msg != ""))
                    +            out.print( ": " + msg ) ;
                    +        out.println() ;
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/orbconfigappserv/ORBConfigAppServTest.java b/test/src/share/classes/corba/orbconfigappserv/ORBConfigAppServTest.java
                    new file mode 100644
                    index 000000000..cff7062e3
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/orbconfigappserv/ORBConfigAppServTest.java
                    @@ -0,0 +1,38 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2003 Apr 15 (Tue) 17:31:08 by Harold Carr.
                    +// Last Modified : 2003 Apr 17 (Thu) 21:13:48 by Harold Carr.
                    +//
                    +
                    +package corba.orbconfigappserv;
                    +
                    +import test.Test;
                    +import corba.framework.*;
                    +
                    +public class ORBConfigAppServTest extends CORBATest
                    +{
                    +    public static final String thisPackage =
                    +        ORBConfigAppServTest.class.getPackage().getName();
                    +
                    +    protected void doTest() throws Throwable
                    +    {
                    +        Controller client =
                    +            createClient(thisPackage + ".ORBManager", "ORBManager");
                    +        client.start();
                    +        client.waitFor(120000);
                    +        client.stop();
                    +    }
                    +}
                    +
                    +// End of file.
                    +
                    +
                    diff --git a/test/src/share/classes/corba/orbconfigappserv/ORBInitializerImpl.java b/test/src/share/classes/corba/orbconfigappserv/ORBInitializerImpl.java
                    new file mode 100644
                    index 000000000..dd9ea5e8a
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/orbconfigappserv/ORBInitializerImpl.java
                    @@ -0,0 +1,40 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2003 Apr 15 (Tue) 16:28:44 by Harold Carr.
                    +// Last Modified : 2003 Apr 15 (Tue) 16:31:40 by Harold Carr.
                    +//
                    +
                    +package corba.orbconfigappserv;
                    +
                    +import org.omg.PortableInterceptor.ORBInitInfo;
                    +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;
                    +import org.omg.PortableInterceptor.Current;
                    +import org.omg.PortableInterceptor.CurrentHelper;
                    +
                    +public class ORBInitializerImpl
                    +    extends
                    +        org.omg.CORBA.LocalObject
                    +    implements
                    +        org.omg.PortableInterceptor.ORBInitializer
                    +{
                    +    public void pre_init(ORBInitInfo info)
                    +    {
                    +        System.out.println("ORBInitializerImpl.pre_init");
                    +    }
                    +
                    +    public void post_init(ORBInitInfo info)
                    +    {
                    +        System.out.println("ORBInitializerImpl.post_init");
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/orbconfigappserv/ORBManager.java b/test/src/share/classes/corba/orbconfigappserv/ORBManager.java
                    new file mode 100644
                    index 000000000..c3cdbc05d
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/orbconfigappserv/ORBManager.java
                    @@ -0,0 +1,289 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2003 Apr 15 (Tue) 15:11:52 by Harold Carr.
                    +// Last Modified : 2003 Apr 15 (Tue) 17:22:07 by Harold Carr.
                    +//
                    +
                    +package corba.orbconfigappserv;
                    +
                    +import org.omg.CORBA.ORB;
                    +
                    +import java.util.*;
                    +import java.io.*;
                    +
                    +import javax.rmi.CORBA.Tie;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +import javax.naming.InitialContext;
                    +import javax.naming.Context;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants;
                    +
                    +
                    +public class ORBManager 
                    +{
                    +    private static final String poaOrbClass = 
                    +        "com.sun.corba.ee.impl.orb.ORBImpl";
                    +    private static final String poaOrbSingletonClass =
                    +        "com.sun.corba.ee.impl.orb.ORBSingleton";
                    +    private static final String peorbConfigClass = 
                    +        "corba.orbconfigappserv.UserORBConfiguratorImpl";
                    +
                    +    public static final String OMG_ORB_CLASS_PROPERTY =
                    +            "org.omg.CORBA.ORBClass";
                    +    public static final String OMG_ORB_SINGLETON_CLASS_PROPERTY =
                    +            "org.omg.CORBA.ORBSingletonClass";
                    +    public static final String SUN_PEORB_CONFIGURATOR_CLASS_PROPERTY =
                    +            "com.sun.corba.ee.ORBUserConfigurators";
                    +    public static final String ORB_UTIL_CLASS_PROPERTY =
                    +            "javax.rmi.CORBA.UtilClass";
                    +    public static final String JNDI_PROVIDER_URL_PROPERTY = 
                    +            "java.naming.provider.url";
                    +    public static final String JNDI_CORBA_ORB_PROPERTY = 
                    +            "java.naming.corba.orb";
                    +       
                    +    public static final String OMG_ORB_INIT_HOST_PROPERTY = 
                    +            "org.omg.CORBA.ORBInitialHost";
                    +    public static final String OMG_ORB_INIT_PORT_PROPERTY = 
                    +            "org.omg.CORBA.ORBInitialPort";
                    +    public static final String SUN_ORB_SERVER_HOST_PROPERTY =
                    +            "com.sun.corba.ee.ORBServerHost";
                    +    public static final String SUN_ORB_SERVER_PORT_PROPERTY =
                    +            "com.sun.corba.ee.ORBServerPort";
                    +
                    +    public static final String RMIIIOP_STUB_DELEGATE_CLASS_PROPERTY =
                    +            "javax.rmi.CORBA.StubClass";
                    +    public static final String RMIIIOP_PRO_DELEGATE_CLASS_PROPERTY =
                    +            "javax.rmi.CORBA.PortableRemoteObjectClass";
                    +    
                    +    public static final String SUN_ORB_SOCKET_FACTORY_CLASS_PROPERTY =
                    +            "com.sun.corba.ee.connection.ORBSocketFactoryClass";
                    +    
                    +    private static final String J2EE_INITIALIZER = 
                    +            "corba.orbconfigappserv.ORBInitializerImpl";
                    +    private static final String PI_ORB_INITIALIZER_CLASS_PREFIX =
                    +            "org.omg.PortableInterceptor.ORBInitializerClass.";
                    +
                    +    public static final String ORB_LISTEN_SOCKET_PROPERTY =
                    +            "com.sun.corba.ee.connection.ORBListenSocket";
                    +    private static final String IIOP_CLEAR_TEXT_CONNECTION =
                    +            "IIOP_CLEAR_TEXT";
                    +
                    +    private static final String DEFAULT_ORB_INIT_HOST = "Testing";
                    +    private static final String DEFAULT_ORB_INIT_PORT = "4500";
                    +
                    +    private static org.omg.CORBA.ORB orb = null;  // the singleton ORB
                    +    private static int orbInitialPort = -1;
                    +
                    +    public static void main(String[] av)
                    +    {
                    +        testInit("First init:", av, null);
                    +
                    +        Properties props = new Properties();
                    +        props.put(UserORBConfiguratorImpl.propertyName,
                    +                  "corba.orbconfigappserver.ORBManager");
                    +        testInit("Second init:", av, props);
                    +
                    +        System.out.println();
                    +        System.out.println("DONE");
                    +    }
                    +
                    +    public static void testInit(String msg, String[] av, Properties props)
                    +    {
                    +        System.out.println();
                    +        System.out.println(msg);
                    +        System.out.println();
                    +        init(av, null);
                    +        System.out.println(
                    +         ((com.sun.corba.ee.spi.orb.ORB)orb).getORBData().getORBInitialHost());
                    +    }
                    +
                    +    /**
                    +     * Initializes the single ORB in this process. 
                    +     * This must be called before calling other methods within this class.
                    +     */
                    +    public static synchronized void init(String[] args, Properties props)  {
                    +        /*
                    +        if (orb != null) // There should be only ONE ORB.
                    +            return;
                    +        */
                    +
                    +        orb = createORB(args, props);
                    +    }
                    +
                    +    public static org.omg.CORBA.ORB getORB() {
                    +        if ( orb == null ) 
                    +            init(null, null);
                    +        return orb;
                    +    }
                    +
                    +    /**
                    +     * This is called by the PEORBConfigurator only to get past 
                    +     * JTS initialization. No one else should have to call this
                    +     */
                    +    public static synchronized void setORB(org.omg.CORBA.ORB theORB) {
                    +        if ( orb == null ) 
                    +            orb = theORB;
                    +    }
                    +
                    +
                    +    public static int getORBInitialPort() {
                    +        if ( orbInitialPort == -1 )
                    +            checkORBInitialPort(new Properties());
                    +        return orbInitialPort;
                    +    }
                    +
                    +    private static synchronized ORB createORB(String[] args, Properties props) 
                    +    {
                    +        ORB neworb = null;
                    +        Properties orbInitProperties = new Properties();
                    +          
                    +        System.setProperty(OMG_ORB_CLASS_PROPERTY, poaOrbClass);
                    +        System.setProperty(OMG_ORB_SINGLETON_CLASS_PROPERTY,
                    +                           poaOrbSingletonClass);
                    +        System.setProperty(SUN_PEORB_CONFIGURATOR_CLASS_PROPERTY 
                    +                           + "." + peorbConfigClass,"");
                    +    
                    +        System.setProperty(SUN_ORB_SOCKET_FACTORY_CLASS_PROPERTY,
                    +                           "corba.orbconfigappserv.SocketFactoryImpl");
                    +
                    +        if (System.getProperty(ORB_UTIL_CLASS_PROPERTY) == null) {
                    +            System.setProperty(ORB_UTIL_CLASS_PROPERTY,
                    +                          "com.sun.corba.ee.impl.javax.rmi.CORBA.Util");
                    +        }
                    +
                    +        try {
                    +            if (props != null) {
                    +                orbInitProperties.putAll(props);
                    +            }
                    +
                    +            orbInitProperties.put(
                    +                PI_ORB_INITIALIZER_CLASS_PREFIX + J2EE_INITIALIZER, "");
                    +
                    +            orbInitProperties.put("com.sun.corba.ee.ORBAllowLocalOptimization", 
                    +                                  "true" ) ;
                    +
                    +            orbInitProperties.put(OMG_ORB_CLASS_PROPERTY, poaOrbClass);
                    +            orbInitProperties.put(OMG_ORB_SINGLETON_CLASS_PROPERTY, 
                    +                                  poaOrbSingletonClass);
                    +            
                    +            String initialPort = checkORBInitialPort(orbInitProperties);
                    +            String orbInitialHost = checkORBInitialHost(orbInitProperties);
                    +            // Add -ORBInitRef for INS to work
                    +            args = addORBInitRef(args, orbInitialHost, initialPort); 
                    +            // START OF IASRI 4627397, 4658320, 4669565, 4676091, 4738349
                    +            checkAdditionalORBListeners(orbInitProperties);
                    +
                    +            
                    +            neworb = ORB.init(args, orbInitProperties);
                    +        }
                    +        catch ( Exception ex ) {
                    +            System.out.println(ex);
                    +        }
                    +
                    +        return neworb;
                    +    }
                    +    
                    +    private static String checkORBInitialHost(Properties props) 
                    +    {
                    +        // Host setting in system properties always takes precedence.
                    +        String orbInitialHost = System.getProperty(OMG_ORB_INIT_HOST_PROPERTY);
                    +        if ( orbInitialHost == null )
                    +            orbInitialHost = props.getProperty(OMG_ORB_INIT_HOST_PROPERTY);
                    +        System.out.println("Found orb initial host: " + orbInitialHost);
                    +        orbInitialHost = DEFAULT_ORB_INIT_HOST;
                    +        System.setProperty(OMG_ORB_INIT_HOST_PROPERTY, orbInitialHost);
                    +        System.out.println("Overwriting orb initial host to " + orbInitialHost);
                    +        return orbInitialHost;
                    +    }
                    +
                    +    private static String checkORBInitialPort(Properties props) 
                    +    {
                    +        // Port setting in system properties always takes precedence.
                    +        String initialPort = System.getProperty(OMG_ORB_INIT_PORT_PROPERTY);
                    +        if ( initialPort == null )
                    +            initialPort = props.getProperty(OMG_ORB_INIT_PORT_PROPERTY);
                    +        if( initialPort == null )
                    +            initialPort = DEFAULT_ORB_INIT_PORT;
                    +        System.setProperty(OMG_ORB_INIT_PORT_PROPERTY, initialPort);
                    +        orbInitialPort = new Integer(initialPort).intValue();
                    +        System.out.println("Setting orb initial port to " + initialPort);
                    +        return initialPort;
                    +    }
                    +
                    +    private static void checkAdditionalORBListeners(Properties props) {
                    +        StringBuffer listenSockets = new StringBuffer("");
                    +        listenSockets.append(
                    +            (listenSockets.length()>0 ? "," : "")
                    +            + "FOO" + ":" + 2000
                    +            );
                    +        // Both ways work.
                    +        //props.setProperty(ORB_LISTEN_SOCKET_PROPERTY, listenSockets.toString());
                    +        System.setProperty(ORB_LISTEN_SOCKET_PROPERTY, listenSockets.toString());
                    +    }
                    +
                    +    private static String[] addORBInitRef(String[] args, String orbInitialHost, 
                    +                           String initialPort)
                    +    {
                    +        // Add -ORBInitRef NameService=....
                    +        // This ensures that INS will be used to talk with the NameService.
                    +        String[] newArgs;
                    +        int i=0;
                    +        if ( args == null ) {
                    +            newArgs = new String[2];
                    +        }
                    +        else {
                    +            newArgs = new String[args.length + 2];
                    +            for ( ; i() {
                    +                public Object evaluate() {
                    +                    try {
                    +                        return testRef.getORF() ;
                    +                    } catch (Throwable thr) {
                    +                        RuntimeException err = new RuntimeException(
                    +                            "Unexpected exception in getORF()" ) ;
                    +                        err.initCause( thr ) ;
                    +                        throw err ;
                    +                    }
                    +                }
                    +            },
                    +            orf ) ;
                    +        
                    +        session.testForPass( "ObjectReferenceTemplate",
                    +            new NullaryFunction() {
                    +                public Object evaluate() {
                    +                    try {
                    +                        return testRef.getORT() ;
                    +                    } catch (Throwable thr) {
                    +                        RuntimeException err = new RuntimeException(
                    +                            "Unexpected exception in getORT()" ) ;
                    +                        err.initCause( thr ) ;
                    +                        throw err ;
                    +                    }
                    +                }
                    +            },
                    +            ort ) ;
                    +
                    +        clientORB.destroy() ;
                    +        serverORB.destroy() ;
                    +        session.end() ;
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/ortremote/TestSession.java b/test/src/share/classes/corba/ortremote/TestSession.java
                    new file mode 100644
                    index 000000000..7271a7025
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/ortremote/TestSession.java
                    @@ -0,0 +1,135 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.ortremote ;
                    +
                    +import java.io.PrintStream ;
                    +import org.glassfish.pfl.basic.func.NullaryFunction;
                    +import org.glassfish.pfl.test.JUnitReportHelper;
                    +import org.glassfish.pfl.test.ObjectUtility;
                    +
                    +/** TestSession manages running of tests and checking results within
                    +* a test session.  If the session fails any test, the whole session 
                    +* fails with an Error, which can be used to trigger failure in the
                    +* CORBA test framework.  This allows complete testing on a major subsystem
                    +* to report a series of failures, while better containing failures by
                    +* not testing related subsystems.
                    +*/
                    +public class TestSession 
                    +{
                    +    private PrintStream out ;
                    +    private boolean errorFlag ;
                    +    private String sessionName ;
                    +    private JUnitReportHelper helper ;
                    +
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +// Public interface
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +
                    +    public TestSession( PrintStream out, Class cls )
                    +    {
                    +        this.out = System.out ;
                    +        helper = new JUnitReportHelper( cls.getName() ) ;
                    +    }
                    +
                    +    /** Print a message indicating the start of the session.
                    +    * Also clears the error flag.
                    +    */
                    +    public void start( String sessionName ) 
                    +    {
                    +        this.sessionName = sessionName ;
                    +        this.errorFlag = false ;
                    +        out.println( "Test Session " + sessionName ) ;
                    +    }
                    +
                    +    /** Check for errors at the end of the session.
                    +    */
                    +    public void end()
                    +    {
                    +        helper.done() ;
                    +        if (errorFlag)
                    +            throw new Error( "Test session " + sessionName + " failed" ) ;
                    +    }
                    +
                    +    public void testForPass( String name, NullaryFunction closure, Object expectedResult )
                    +    {
                    +        try {
                    +            testStart( name ) ;
                    +            Object result = closure.evaluate() ;
                    +
                    +            if (ObjectUtility.equals( result, expectedResult))
                    +                testPass() ;
                    +            else {
                    +                testFail( "Unexpected result returned" ) ;
                    +                out.println( "\t\t\tExpected Result=" +
                    +                    ObjectUtility.defaultObjectToString( expectedResult ) ) ;
                    +                out.println( "\t\t\tActual   Result=" +
                    +                    ObjectUtility.defaultObjectToString( result ) ) ;
                    +            }
                    +        } catch (Throwable thr) {
                    +            testFail( "Unexpected exception " + thr ) ;
                    +            thr.printStackTrace() ;
                    +        }
                    +    }
                    +    
                    +    public void testForException( String name, NullaryFunction closure,
                    +        Class expectedExceptionClass )
                    +    {
                    +        try {
                    +            testStart( name ) ;
                    +            closure.evaluate();
                    +            testFail( "Closure did not throw expected exception" ) ;
                    +        } catch (Throwable thr) {
                    +            if (expectedExceptionClass.isAssignableFrom( thr.getClass() ))
                    +                testPass( "with exception " + thr ) ;
                    +            else
                    +                testFail( "Unexpected exception" + thr ) ;
                    +        }
                    +    }
                    +
                    +    public void testAbort( String msg, Throwable thr )
                    +    {
                    +        out.println( "\t" + msg + ": Test aborted due to unexpected exception " + thr ) ;
                    +        thr.printStackTrace() ;
                    +        helper.done() ;
                    +        System.exit( 1 ) ;
                    +    }
                    +
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +// Internal implementation
                    +/////////////////////////////////////////////////////////////////////////////////////
                    +
                    +    private void testStart( String name )
                    +    {
                    +        out.println( "\tTest " + name + "..." ) ;
                    +        helper.start( name ) ;
                    +    }
                    +
                    +    private void testFail( String msg )
                    +    {
                    +        out.println( "\t\tFAILED: " + msg ) ;
                    +        errorFlag = true ;
                    +        helper.fail( msg ) ;
                    +    }
                    +
                    +    private void testPass() 
                    +    {
                    +        testPass( null ) ;
                    +    }
                    +
                    +    private void testPass( String msg )
                    +    {
                    +        out.print( "\t\tPASSED" ) ;
                    +        if ((msg != null) && (msg != ""))
                    +            out.print( ": " + msg ) ;
                    +        out.println() ;
                    +        helper.pass() ;
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/preinvokepostinvoke/Server.java b/test/src/share/classes/corba/preinvokepostinvoke/Server.java
                    new file mode 100644
                    index 000000000..259f4ff8b
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/preinvokepostinvoke/Server.java
                    @@ -0,0 +1,118 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.preinvokepostinvoke;
                    +
                    +import org.omg.CORBA.Policy;
                    +import org.omg.CORBA.ORB;
                    +import org.omg.PortableServer.POA;
                    +import org.omg.PortableServer.RequestProcessingPolicyValue;
                    +import org.omg.PortableServer.Servant;
                    +import org.omg.PortableServer.ServantManager;
                    +import org.omg.PortableServer.ServantRetentionPolicyValue;
                    +import org.omg.PortableServer.ServantLocator;
                    +import javax.rmi.PortableRemoteObject ;
                    +import com.sun.corba.ee.spi.extension.ServantCachingPolicy;
                    +
                    +public class Server {
                    +
                    +     private static ORB orb;
                    +     private static  org.omg.CosNaming.NamingContextExt nctx; 
                    +     private static  POA poaWithServantCachingPolicy; 
                    +
                    +
                    +     public static void main( String[] args ) {
                    +        System.out.println( " Starting Server.... " );
                    +        System.out.flush( );
                    +     
                    +        try {
                    +            orb = ORB.init( args, null );
                    +
                    +            org.omg.CORBA.Object obj = 
                    +                orb.resolve_initial_references( "NameService");
                    +            nctx = org.omg.CosNaming.NamingContextExtHelper.narrow( obj );
                    +
                    +            POA rPOA = (POA)orb.resolve_initial_references( "RootPOA" );
                    +            rPOA.the_POAManager().activate( );
                    +
                    +            Policy[] policies = new Policy[3];
                    +            policies[0] = rPOA.create_servant_retention_policy(
                    +                ServantRetentionPolicyValue.NON_RETAIN);
                    +            policies[1] = rPOA.create_request_processing_policy(
                    +                          RequestProcessingPolicyValue.USE_SERVANT_MANAGER);
                    +            policies[2] = ServantCachingPolicy.getFullPolicy( );
                    +
                    +            MyServantLocator sl = new MyServantLocator( orb );
                    +
                    +            poaWithServantCachingPolicy = rPOA.create_POA( "poa", null, 
                    +                policies );
                    +            poaWithServantCachingPolicy.set_servant_manager( sl );
                    +            poaWithServantCachingPolicy.the_POAManager().activate();
                    +
                    +
                    +            _Interface_Stub s = new _Interface_Stub( );
                    +            bindInstance( (s._ids())[0], "Instance1" );
                    +            System.out.println( "Created and Bound instance1" );
                    +            System.out.flush( );
                    +
                    +            bindInstance( (s._ids())[0], "Instance2" );
                    +            System.out.println( "Created and Bound instance2" );
                    +            System.out.flush( );
                    +
                    +            TestAssert.startTest( );
                    +            resolveReferenceAndInvoke( orb  );
                    +            TestAssert.isTheCallBalanced( 2 );
                    +
                    +            // Emit the handshake the test framework expects
                    +            // (can be changed in Options by the running test)
                    +            System.out.println ("Server is ready.");
                    +            System.out.flush( );
                    +        } catch( Exception e ) {
                    +            e.printStackTrace( );
                    +        }
                    +    }
                    +
                    +    private static void bindInstance( String repId, String bindingName )
                    +    {
                    +        try {
                    +            org.omg.CORBA.Object obj = 
                    +                poaWithServantCachingPolicy.create_reference_with_id(
                    +                    bindingName.getBytes( ), repId );
                    +            org.omg.CosNaming.NameComponent[] nc = nctx.to_name( bindingName );
                    +            nctx.rebind( nc, obj );
                    +        } catch( Exception e ) {
                    +            e.printStackTrace( );
                    +        }
                    +    }
                    +
                    +    private static void resolveReferenceAndInvoke(ORB orb) {
                    +        try {
                    +             org.omg.CORBA.Object obj;
                    +
                    +             obj = nctx.resolve_str( "Instance1" );
                    +             Interface i1 = 
                    +                 (Interface) PortableRemoteObject.narrow(obj,Interface.class );
                    +             i1.o1( "Invoking from Client..." );
                    +        }catch( Exception e ) {
                    +            e.printStackTrace( );
                    +            System.exit( 1 );
                    +        }
                    +    }
                    +}
                    +
                    +        
                    +        
                    +
                    +
                    +       
                    +    
                    +
                    +
                    +
                    diff --git a/test/src/share/classes/corba/prlb/Notes.txt b/test/src/share/classes/corba/prlb/Notes.txt
                    new file mode 100644
                    index 000000000..611bf5e76
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/prlb/Notes.txt
                    @@ -0,0 +1,43 @@
                    +#
                    +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    +#
                    +# This program and the accompanying materials are made available under the
                    +# terms of the Eclipse Distribution License v. 1.0, which is available at
                    +# http://www.eclipse.org/org/documents/edl-v10.php.
                    +#
                    +# SPDX-License-Identifier: BSD-3-Clause
                    +#
                    +
                    +Testing load balancing
                    +    Test:
                    +        Multiple client invoking against multiple servers, each gives
                    +            equal distribution with PRLB
                    +        server fails, clients continue with equal distr.
                    +        server added, client continue with equal distr.
                    +
                    +interface
                    +
                    +public interface PRLBTest extends Remote {
                    +    int myId() ;
                    +
                    +    void invoke( int clientId ) ;
                    +
                    +    Map getAndClearCounts() ;
                    +
                    +    shutdown() ;
                    +}
                    +
                    +2 clients, 3-5 servers
                    +
                    +Each client, server has a unique id of the form (instance num, incarnation num)
                    +
                    +Each client:
                    +    invokes a simple ping() method repeatedly (possibly with a wait time?)
                    +    may be configured to make:w
                    +    some number of invocations, then cause server to shutdown
                    +    configured with an identity
                    +
                    +Each server:
                    +    configured with identity
                    +    controlled by clients
                    +    each uses identical code to configure remote object
                    diff --git a/test/src/share/classes/corba/resolve_deadlock/ResolveDeadlock.java b/test/src/share/classes/corba/resolve_deadlock/ResolveDeadlock.java
                    new file mode 100644
                    index 000000000..aa1af1feb
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/resolve_deadlock/ResolveDeadlock.java
                    @@ -0,0 +1,86 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.resolve_deadlock;
                    +
                    +import java.util.Properties ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService;
                    +
                    +import org.omg.CORBA.ORB ;
                    +
                    +
                    +
                    +public class ResolveDeadlock {   
                    +
                    +    private static final String PORT_NUM = "3074" ;
                    +    private static ORB serverORB ;
                    +
                    +    private static void initializeORBs( String[] args ) {
                    +        // The following must be set as system properties 
                    +        System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass",
                    +            "com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject" ) ;
                    +        System.setProperty( "javax.rmi.CORBA.StubClass",
                    +            "com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl" ) ;
                    +        System.setProperty( "javax.rmi.CORBA.UtilClass",
                    +            "com.sun.corba.ee.impl.javax.rmi.CORBA.Util" ) ;
                    +
                    +        // initializer server ORB.
                    +
                    +        Properties serverProps = new Properties() ;
                    +        serverProps.setProperty( "org.omg.CORBA.ORBSingletonClass",
                    +            "com.sun.corba.ee.impl.orb.ORBSingleton" ) ;
                    +        serverProps.setProperty( "org.omg.CORBA.ORBClass",
                    +            "com.sun.corba.ee.impl.orb.ORBImpl" ) ;
                    +        serverProps.setProperty( ORBConstants.INITIAL_HOST_PROPERTY,
                    +            "localhost" ) ;
                    +        serverProps.setProperty( ORBConstants.INITIAL_PORT_PROPERTY,
                    +            PORT_NUM ) ;
                    +        serverProps.setProperty( ORBConstants.ALLOW_LOCAL_OPTIMIZATION,
                    +            "true" ) ;  
                    +        serverProps.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY,
                    +            PORT_NUM ) ;
                    +        serverProps.setProperty( ORBConstants.SERVER_HOST_PROPERTY,
                    +            "localhost" ) ;
                    +        serverProps.setProperty( ORBConstants.ORB_ID_PROPERTY,
                    +            "serverORB" ) ;
                    +        serverProps.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY,
                    +            "300" ) ;
                    +
                    +        // Ignore the args! Don't want to pick up setting of ORBInitialPort from args!
                    +        String[] noArgs = null ;
                    +        serverORB = ORB.init( noArgs, serverProps ) ;
                    +        new TransientNameService( 
                    +            com.sun.corba.ee.spi.orb.ORB.class.cast(serverORB) ) ;
                    +
                    +        // Activate the transport
                    +        try {
                    +            serverORB.resolve_initial_references( "RootPOA" ) ;
                    +        } catch (Exception exc) {
                    +            throw new RuntimeException( exc ) ;
                    +        }
                    +    }
                    +
                    +    public static void main( String[] args ) {
                    +        initializeORBs( args ) ;
                    +        try {
                    +            //lookup a non-existing name "Foo"
                    +            org.omg.CORBA.Object objRef = serverORB.resolve_initial_references( "Foo" );
                    +            System.out.println( "Unexpectedly found the name Foo! ");
                    +            System.exit(1);         
                    +        } catch (Exception exc) {           
                    +            System.out.println( "Expected exception in getting initial references: " + exc);
                    +            exc.printStackTrace() ;
                    +            System.exit(0) ;
                    +        }
                    +    }
                    +}
                    diff --git a/test/src/share/classes/corba/resolve_deadlock/ResolveDeadlockTest.java b/test/src/share/classes/corba/resolve_deadlock/ResolveDeadlockTest.java
                    new file mode 100644
                    index 000000000..b8127ff5c
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/resolve_deadlock/ResolveDeadlockTest.java
                    @@ -0,0 +1,41 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.resolve_deadlock;
                    +
                    +import test.Test;
                    +import corba.framework.*;
                    +import java.util.*;
                    +
                    +public class ResolveDeadlockTest extends CORBATest
                    +{
                    +    private static String[] javaFiles = { "ResolveDeadlock.java" };
                    +
                    +    // This is the main method defining the test.  All tests
                    +    // should have this.
                    +    protected void doTest() throws Throwable
                    +    {
                    +        Options.setJavaFiles( javaFiles ) ;
                    +
                    +        compileJavaFiles();
                    +
                    +        Controller client = createClient( "corba.resolve_deadlock.ResolveDeadlock" ) ;
                    +
                    +        client.start();
                    +
                    +        // Wait for the client to finish for up to 1 minute, then
                    +        // throw an exception.
                    +        client.waitFor(120000);
                    +
                    +        // Make sure all the processes are shut down.
                    +        client.stop();
                    +    }
                    +}
                    +
                    diff --git a/test/src/share/classes/corba/retryplugin/Client.java b/test/src/share/classes/corba/retryplugin/Client.java
                    new file mode 100644
                    index 000000000..398fa0f28
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/Client.java
                    @@ -0,0 +1,129 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 14:43:22 by Harold Carr.
                    +// Last Modified : 2005 Oct 06 (Thu) 11:59:21 by Harold Carr.
                    +//
                    +
                    +package corba.retryplugin;
                    +
                    +import java.util.Hashtable;
                    +import java.util.Properties;
                    +import javax.naming.InitialContext;
                    +import javax.naming.NamingException;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +import org.omg.CORBA.COMM_FAILURE;
                    +import org.omg.CORBA.ORB;
                    +
                    +import com.sun.corba.ee.impl.plugin.hwlb.RetryClientRequestInterceptor ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public class Client
                    +{
                    +    static {
                    +        // This is needed to guarantee that this test will ALWAYS use dynamic
                    +        // RMI-IIOP.  Currently the default is dynamic when renamed to "ee",
                    +        // but static in the default "se" packaging, and this test will
                    +        // fail without dynamic RMI-IIOP.
                    +        System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ;
                    +    }
                    +
                    +    private static final long CLIENT_RUN_LENGTH = 1000 * 30; // 30 seconds
                    +
                    +    public static void main(String[] av)
                    +    {
                    +        try {
                    +            Properties props = new Properties();
                    +
                    +            props.setProperty(
                    +                "org.omg.PortableInterceptor.ORBInitializerClass."
                    +                + RetryClientRequestInterceptor.class.getName(),
                    +                "dummy");
                    +
                    +            ORB orb = ORB.init((String[])null, props);
                    +            Hashtable env = new Hashtable();
                    +            env.put("java.naming.corba.orb", orb);
                    +            InitialContext initialContext = new InitialContext(env);
                    +
                    +            Test ref  = (Test)
                    +                lookupAndNarrow(Common.ReferenceName, Test.class, 
                    +                                initialContext);
                    +
                    +            long startTime = System.currentTimeMillis();
                    +            int i = 0;
                    +            while (System.currentTimeMillis() - startTime < CLIENT_RUN_LENGTH){
                    +                int result = ref.echo(i);
                    +                if (result != i) {
                    +                    throw new Exception("incorrect echo");
                    +                }
                    +                i++;
                    +                System.out.println("correct echo response: " + result);
                    +            }
                    +            System.out.println("Loop completed.");
                    +            System.out.println();
                    +            System.out.println("Sleeping for 1 minute before timeout test");
                    +            Thread.sleep(1000 * 60);
                    +
                    +            try {
                    +                System.out.println("This echo should timeout");
                    +                RetryClientRequestInterceptor
                    +                    .setTransientRetryTimeout(1000 * 5);
                    +                ref.echo(-1);
                    +                throw new Exception("timeout echo should not succeed");
                    +            } catch (Exception e) {
                    +                // See note in README.txt for the type of this exception.
                    +                System.out.println("******: " + e);
                    +            }
                    +
                    +            System.out.println("Sleeping for 30 seconds before shutdown test");
                    +            Thread.sleep(1000 * 30);
                    +
                    +            try {
                    +                System.out.println("This echo should fail since server done.");
                    +                ref.echo(-1);
                    +                throw new Exception("shutdown echo should not succeed");
                    +            } catch (java.rmi.MarshalException e) {
                    +                if (! e.detail.getClass().isInstance(new COMM_FAILURE())) {
                    +                    throw new Exception("!!! Did not receive correct failure");
                    +                }
                    +            }
                    +
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Client SUCCESS");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(0);
                    +
                    +        } catch (Exception e) {
                    +            e.printStackTrace(System.out);
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Client FAILURE");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(1);
                    +        }
                    +    }
                    +
                    +    public static Object lookupAndNarrow(String name, 
                    +                                         Class clazz,
                    +                                         InitialContext initialContext)
                    +        throws
                    +            NamingException
                    +    {
                    +        return PortableRemoteObject.narrow(initialContext.lookup(name), clazz);
                    +    }
                    +}
                    +
                    +// End of file.
                    +
                    diff --git a/test/src/share/classes/corba/retryplugin/Common.java b/test/src/share/classes/corba/retryplugin/Common.java
                    new file mode 100644
                    index 000000000..25d52d7ca
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/Common.java
                    @@ -0,0 +1,70 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 14:11:24 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:07:07 by Harold Carr.
                    +//
                    +
                    +package corba.retryplugin;
                    +
                    +import java.util.Vector;
                    +import java.util.StringTokenizer;
                    +
                    +import org.omg.CORBA.ORB;
                    +import org.omg.CosNaming.*;
                    +import org.omg.CosNaming.NamingContextPackage.*;
                    +
                    +public class Common
                    +{
                    +    public static final String ReferenceName = "Test";
                    +    private static final String NameService = "NameService";
                    +
                    +    public static org.omg.CORBA.Object resolve(String name, ORB orb)
                    +        throws 
                    +            Exception
                    +    {
                    +        return getNameService(orb).resolve(makeNameComponent(name));
                    +    }
                    +
                    +    public static org.omg.CORBA.Object rebind(String name,
                    +                                              org.omg.CORBA.Object ref,
                    +                                              ORB orb)
                    +        throws 
                    +            Exception
                    +    {
                    +        getNameService(orb).rebind(makeNameComponent(name), ref);
                    +        return ref;
                    +    }
                    +
                    +    public static NameComponent[] makeNameComponent(String name)
                    +    {
                    +        Vector result = new Vector();
                    +        StringTokenizer tokens = new StringTokenizer(name, "/");
                    +        while (tokens.hasMoreTokens()) {
                    +            result.addElement(tokens.nextToken());
                    +        }
                    +        NameComponent path[] = new NameComponent[result.size()];
                    +        for (int i = 0; i < result.size(); ++i) {
                    +            path[i] = new NameComponent((String)result.elementAt(i), "");
                    +        }
                    +        return path;
                    +    }
                    +
                    +    public static NamingContext getNameService(ORB orb)
                    +        throws
                    +            Exception
                    +    {
                    +        return NamingContextHelper.narrow(
                    +            orb.resolve_initial_references(NameService));
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/retryplugin/README.txt b/test/src/share/classes/corba/retryplugin/README.txt
                    new file mode 100644
                    index 000000000..9fed7e451
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/README.txt
                    @@ -0,0 +1,63 @@
                    +#
                    +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    +#
                    +# This program and the accompanying materials are made available under the
                    +# terms of the Eclipse Distribution License v. 1.0, which is available at
                    +# http://www.eclipse.org/org/documents/edl-v10.php.
                    +#
                    +# SPDX-License-Identifier: BSD-3-Clause
                    +#
                    +
                    +This test shows how to stop an ORB from receiving further requests by
                    +throwing TRANSIENT to the client.
                    +
                    +REVISIT:  This test should be refactored to use callbacks from the
                    +server to the client to indicate test phase changes (i.e., rejecting
                    +on/off; always rejecting/retry timeout; shutdown) rather than Thread.sleep.
                    +
                    +------------------------------------------------------------------------------
                    +        ***** IMPORTANT NOTICE *****
                    +
                    +Should only use RetryClientRequestInterceptor if the client *ONLY* talks
                    +to stateless beans.
                    +
                    +If client even talks to one single stateful bean then it should *NOT*
                    +install the RetryClientRequestInterceptor.  Instead the client should
                    +be changed to catch TRANSIENT and retry.
                    +
                    +------------------------------------------------------------------------------
                    +
                    +Operation:
                    +
                    +The client will keep retrying the requests that get TRANSIENT until
                    +success or until the server is shutdown.
                    +
                    +If the server is shutdown the client will try another server address,
                    +if the reference has multiple addresses.  If there is only one address
                    +then a MarshalException/COMM_FAILURE is thrown to the client
                    +application.
                    +
                    +Configuration:
                    +
                    +The server-side installs the RetryServerRequestInterceptor.
                    +Call RetryServerRequestInterceptor.setRejectingRequests(true)
                    +to stop receiving accepting further requests.  After an appropriate
                    +period of time shutdown the server.
                    +
                    +The client-side install the RetryClientRequestInterceptor.
                    +No changes are necessary in client code.
                    +
                    +Note:
                    +
                    +If the timeout is reached then the TRANSIENT exception is thrown to the client.
                    +However, a bug in the ORB may mask that exception and return an
                    +exception indicating the client info stack is null.  That exception
                    +can be ignored and treated as TRANSIENT timing out.
                    +
                    +Note:
                    +
                    +If testing this in an ORB after Oct 4, 2005, the
                    +RetryClientRequestInterceptor will not even see the TRANSIENT since
                    +that is handled by the ContactInfoListIterator.
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/retryplugin/RetryPluginTest.java b/test/src/share/classes/corba/retryplugin/RetryPluginTest.java
                    new file mode 100644
                    index 000000000..9b2797fc2
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/RetryPluginTest.java
                    @@ -0,0 +1,58 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 17:33:44 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 20:01:57 by Harold Carr.
                    +//
                    +
                    +package corba.retryplugin;
                    +
                    +import java.util.Properties;
                    +
                    +import corba.framework.CORBATest;
                    +import corba.framework.Controller;
                    +import corba.framework.Options;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public class RetryPluginTest
                    +    extends
                    +        CORBATest
                    +{
                    +    protected void doTest()
                    +        throws Exception
                    +    {
                    +        String thisPackage = RetryPluginTest.class.getPackage().getName();
                    +
                    +        Controller orbd = createORBD();
                    +        Controller server;
                    +        Controller client;
                    +
                    +        orbd.start();
                    +
                    +        server = createServer(thisPackage+"."+"Server", "Server");
                    +        client = createClient(thisPackage+"."+"Client", "Client");
                    +
                    +        server.start();
                    +        client.start();
                    +
                    +        client.waitFor(1000 * 60 * 5);
                    +
                    +        client.stop();
                    +        server.stop();
                    +        orbd.stop();
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/retryplugin/Server.java b/test/src/share/classes/corba/retryplugin/Server.java
                    new file mode 100644
                    index 000000000..1e7c54d3d
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/Server.java
                    @@ -0,0 +1,113 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:54:09 by Harold Carr.
                    +// Last Modified : 2005 Oct 06 (Thu) 11:32:08 by Harold Carr.
                    +//
                    +
                    +package corba.retryplugin;
                    +
                    +import java.util.Properties;
                    +
                    +import org.omg.CORBA.ORB;
                    +import org.omg.PortableServer.POA;
                    +import org.omg.PortableServer.Servant;
                    +
                    +import com.sun.corba.ee.impl.plugin.hwlb.RetryServerRequestInterceptor ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public class Server
                    +{
                    +    static {
                    +        // This is needed to guarantee that this test will ALWAYS use dynamic
                    +        // RMI-IIOP.  Currently the default is dynamic when renamed to "ee",
                    +        // but static in the default "se" packaging, and this test will
                    +        // fail without dynamic RMI-IIOP.
                    +        System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ;
                    +    }
                    +
                    +    private static final String baseMsg = Server.class.getName();
                    +    private static final String RootPOA = "RootPOA";
                    +    private static final long SERVER_RUN_LENGTH = 1000 * 60; // 1 minute
                    +
                    +    public static void main(String[] av)
                    +    {
                    +        try {
                    +
                    +            Properties props = new Properties();
                    +
                    +            props.setProperty(
                    +                "org.omg.PortableInterceptor.ORBInitializerClass."
                    +                + RetryServerRequestInterceptor.class.getName(),
                    +                "dummy");
                    +
                    +            ORB orb = ORB.init(av, props);
                    +
                    +            POA rootPOA = (POA) orb.resolve_initial_references("RootPOA");
                    +            rootPOA.the_POAManager().activate();
                    +
                    +            Servant servant = (Servant)
                    +                javax.rmi.CORBA.Util.getTie(new TestServant());
                    +
                    +            createWithServantAndBind(Common.ReferenceName, servant, 
                    +                                     rootPOA, orb);
                    +
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Server is ready.");
                    +            System.out.println("--------------------------------------------");
                    +
                    +            long startTime = System.currentTimeMillis();
                    +            while (System.currentTimeMillis() - startTime < SERVER_RUN_LENGTH){
                    +                RetryServerRequestInterceptor.setRejectingRequests(true);
                    +                Thread.sleep(1000 * 10);
                    +                RetryServerRequestInterceptor.setRejectingRequests(false);
                    +                Thread.sleep(1000 * 10);
                    +            }
                    +
                    +            RetryServerRequestInterceptor.setRejectingRequests(true);
                    +            Thread.sleep(SERVER_RUN_LENGTH);
                    +
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("Server exiting correctly...");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(0);
                    +
                    +        } catch (Exception e) {
                    +            e.printStackTrace(System.out);
                    +            System.out.println("--------------------------------------------");
                    +            System.out.println("!!!! Server exiting INCORRECTLY...");
                    +            System.out.println("--------------------------------------------");
                    +            System.exit(1);
                    +        }
                    +    }
                    +
                    +    public static org.omg.CORBA.Object 
                    +        createWithServantAndBind (String  name,
                    +                                  Servant servant,
                    +                                  POA     poa,
                    +                                  ORB     orb)
                    +        throws
                    +            Exception
                    +    {
                    +        byte[] id = name.getBytes();
                    +        poa.activate_object_with_id(id, servant);
                    +        org.omg.CORBA.Object ref = poa.id_to_reference(id);
                    +        Common.rebind(name, ref, orb);
                    +        return ref;
                    +    }
                    +
                    +} 
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/retryplugin/Test.java b/test/src/share/classes/corba/retryplugin/Test.java
                    new file mode 100644
                    index 000000000..1ab6e6aca
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/Test.java
                    @@ -0,0 +1,33 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:49:03 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:08:09 by Harold Carr.
                    +//
                    +
                    +package corba.retryplugin;
                    +
                    +import java.rmi.Remote;
                    +import java.rmi.RemoteException;
                    +
                    +/**
                    + * @author Harold Carr
                    + */
                    +public interface Test
                    +    extends Remote
                    +{
                    +    public int echo(int x)
                    +        throws RemoteException;
                    +}
                    +
                    +// End of file.
                    +
                    +
                    diff --git a/test/src/share/classes/corba/retryplugin/TestServant.java b/test/src/share/classes/corba/retryplugin/TestServant.java
                    new file mode 100644
                    index 000000000..6ebaf32f5
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/retryplugin/TestServant.java
                    @@ -0,0 +1,40 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +//
                    +// Created       : 2005 Oct 05 (Wed) 13:50:17 by Harold Carr.
                    +// Last Modified : 2005 Oct 05 (Wed) 15:17:44 by Harold Carr.
                    +//
                    +
                    +package corba.retryplugin;
                    +
                    +import java.rmi.RemoteException;
                    +import javax.rmi.PortableRemoteObject;
                    +
                    +public class TestServant
                    +    extends PortableRemoteObject
                    +    implements Test
                    +{
                    +    public static final String baseMsg = TestServant.class.getName();
                    +
                    +    public TestServant()
                    +        throws RemoteException
                    +    {
                    +    }
                    +
                    +    public int echo(int x)
                    +        throws RemoteException
                    +    {
                    +        System.out.println(baseMsg + ".echo: " + x);
                    +        return x;
                    +    }
                    +}
                    +
                    +// End of file.
                    diff --git a/test/src/share/classes/corba/rfm/TestClient.java b/test/src/share/classes/corba/rfm/TestClient.java
                    new file mode 100644
                    index 000000000..ec0e06ceb
                    --- /dev/null
                    +++ b/test/src/share/classes/corba/rfm/TestClient.java
                    @@ -0,0 +1,645 @@
                    +/*
                    + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
                    + *
                    + * This program and the accompanying materials are made available under the
                    + * terms of the Eclipse Distribution License v. 1.0, which is available at
                    + * http://www.eclipse.org/org/documents/edl-v10.php.
                    + *
                    + * SPDX-License-Identifier: BSD-3-Clause
                    + */
                    +
                    +package corba.rfm ;
                    +
                    +import java.rmi.Remote ;
                    +import java.rmi.RemoteException ;
                    +
                    +import java.util.Arrays ;
                    +import java.util.List ;
                    +import java.util.ArrayList ;
                    +import java.util.Map ;
                    +import java.util.HashMap ;
                    +import java.util.Properties ;
                    +
                    +import javax.rmi.PortableRemoteObject ;
                    +
                    +import javax.rmi.CORBA.Tie ;
                    +
                    +import org.omg.CORBA.ORB ;
                    +import org.omg.CORBA.Policy ;
                    +import org.omg.CORBA.BAD_OPERATION ;
                    +import org.omg.CORBA.LocalObject ;
                    +
                    +import org.omg.CosNaming.NamingContext ;
                    +import org.omg.CosNaming.NamingContextHelper ;
                    +import org.omg.CosNaming.NamingContextExt ;
                    +import org.omg.CosNaming.NamingContextExtHelper ;
                    +import org.omg.CosNaming.NameComponent ;
                    +import org.omg.CosNaming.NamingContextPackage.CannotProceed ;
                    +import org.omg.CosNaming.NamingContextPackage.InvalidName ;
                    +import org.omg.CosNaming.NamingContextPackage.AlreadyBound ;
                    +import org.omg.CosNaming.NamingContextPackage.NotFound ;
                    +
                    +import org.omg.PortableServer.ForwardRequest ;
                    +import org.omg.PortableServer.POA ;
                    +import org.omg.PortableServer.Servant ;
                    +import org.omg.PortableServer.ServantLocator ;
                    +
                    +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ;
                    +
                    +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactory ;
                    +import com.sun.corba.ee.spi.oa.rfm.ReferenceFactoryManager ;
                    +
                    +import com.sun.corba.ee.spi.extension.ServantCachingPolicy ;
                    +
                    +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ;
                    +
                    +import com.sun.corba.ee.spi.misc.ORBConstants ;
                    +
                    +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService ;
                    +import org.glassfish.pfl.basic.contain.Pair;
                    +
                    +/** This is a test for the ReferenceFactoryManager.
                    + * The basic idea is to start up a number of client threads,
                    + * both remote and co-located, that delay for various
                    + * times, and have these tests invoke several objects.
                    + * Then we reconfigure the POAs using ReferenceFactoryManager.restart,
                    + * and make sure that all threads continue to work correctly,
                    + * and that invocations complete before reconfiguration.
                    + * 

                    + * Structure of this test: + * + * Two ORB instances: + * - Server ORB, which has persistent server ID and port set, + * the user configurator for the ReferenceFactoryManager, + * initial host set to localhost, and initial port set to + * the persistent server port. This ORB is also set up for + * fully optimized colocated RMI-IIOP calls. + * - Client ORB, which has initial host set to localhost, and + * initial port set to the same value as the Server ORB's + * persistent server port. + * + * A simple remote interface that supports echo and delay operations. + * Delay takes a parameter that tells the server how long to wait + * until responding. + * + * A client thread that simply: + * while (running) + * delay( config time ) + * invoke either echo or delay + * log completion + * + * The objref that the client thread uses may be resolved in + * either the client or server ORBs. This allows testing both + * the remote and the various colocated call paths. + * This is essential because the code is different in these cases. + * + * The test needs two ReferenceFactories configured as follows: + * - With full servant caching enabled (test FullServantCacheLocalCRDImpl restart) + * - Without any servant caching (test POAlocalCRDImpl restart) + * We create 3 objrefs for each type of caching with different delay + * length (0, 5, 21 msec) + * These are named cache/0 cache/5 cache/21 nocache/0 nocache/5 and + * nocache/21 + * + * + * The ServantLocator does a couple of things: + * - Delays for a configurable time before returning a fixed servant + * - checks its state to make sure that it is supposed to be in use. + * + * There is also a controller that starts and coordinates all testing + * activity. + * The controller basically starts up a number of different types of + * client threads, then starts another thread that delays, then + * does a restart in the ReferenceFactoryManager. The restart will + * introduce a new ServantLocator in all ReferenceFactory instances, + * and set the state of the old ServantLocator to log errors if + * any further invocations are received in the old ServantLocator. + * Several restart cycles will be performed. + * + * In addition, we need to test nested calls; that is, calls to co-located + * objrefs on the server side. This also include creating new objrefs + * through the RFM. + */ +public class TestClient { + static { + // This is needed to guarantee that this test will ALWAYS use dynamic + // RMI-IIOP. Currently the default is dynamic when renamed to "ee", + // but static in the default "se" packaging, and this test will + // fail without dynamic RMI-IIOP. + System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ; + } + + public static synchronized void log( String msg ) { + System.out.println( msg ) ; + } + + public static synchronized void fatal( String msg, Throwable thr ) { + thr.printStackTrace() ; + log( msg ) ; + System.exit( 1 ) ; + } + + public static void sleep( int delay ) { + try { + Thread.sleep( delay ) ; + } catch (InterruptedException exc) { + // Don't care if my sleep is interrupted. + } + } + + private interface Test extends Remote { + public void createAnObject( int threadId ) throws RemoteException ; + + public int echo( Test remoteSelf, int threadId, int value ) throws RemoteException ; + + public int delay( Test remoteSelf, int threadId, int value, int delay ) throws RemoteException ; + } + + private static class TestImpl extends PortableRemoteObject implements Test { + public TestImpl() throws RemoteException { + super() ; + } + + private void log( int threadId, String msg ) { + StringBuilder sbuff = new StringBuilder() ; + sbuff.append( "[" ) + .append( threadId ) + .append( "] " ) + .append( msg ) ; + System.out.println( sbuff.toString() ) ; + } + + public void createAnObject( int threadId ) throws RemoteException { + byte[] key = { (byte)1, (byte)2, (byte)3 } ; + + log( threadId, "Creating a reference with cacheFactory" ) ; + cacheFactory.createReference( key ) ; + } + + public int echo( Test remoteSelf, int threadId, int value ) throws RemoteException { + remoteSelf.createAnObject( threadId ) ; + + log( threadId, "Echo returns" + value ) ; + return value ; + } + + public int delay( Test remoteSelf, int threadId, int value, int delay ) throws RemoteException { + log( threadId, "Delay sleeps for " + delay + " milliseconds" ) ; + remoteSelf.createAnObject( threadId ) ; + + sleep( delay ) ; + + log( threadId, "Delay returns " + value ) ; + return value ; + } + } + + static Object runningLock = new Object() ; + static boolean running = true ; + + private static class Client extends Thread { + private int threadId ; + private int delay ; + private Test testref ; + private int value ; + private boolean useEcho ; + private int callDelay ; + + public String toString() { + return "Client[" + threadId + "]" ; + } + + // Create a Client thread that invokes the Test remoteSelf, echo method + public Client( int threadId, int delay, Test testref ) { + this.threadId = threadId ; + this.delay = delay ; + this.testref = testref ; + this.value = 0 ; + this.useEcho = true ; + this.callDelay = 0 ; + clients.add( this ) ; + } + + // Create a Client thread that invokes the delay method + public Client( int threadId, int delay, Test testref, int callDelay ) { + this.threadId = threadId ; + this.delay = delay ; + this.testref = testref ; + this.value = 0 ; + this.useEcho = false ; + this.callDelay = callDelay ; + clients.add( this ) ; + } + + private void logStart( ) { + StringBuilder sbuff = new StringBuilder() ; + sbuff.append( "[" ) + .append( threadId ) + .append( ":" ) + .append( value ) + .append( "] " ) + .append( "Call to " ) + .append( useEcho ? "echo" : "delay" ) + .append( " started" ) ; + log( sbuff.toString() ) ; + } + + private void logComplete( int result ) { + StringBuilder sbuff = new StringBuilder() ; + sbuff.append( "[" ) + .append( threadId ) + .append( ":" ) + .append( value ) + .append( "] " ) + .append( "Call to " ) + .append( useEcho ? "echo" : "delay" ) + .append( " completed with result " ) + .append( result ) ; + log( sbuff.toString() ) ; + } + + public void halt() { + synchronized( runningLock ) { + running = false ; + } + + this.interrupt() ; + } + + public void run() { + Thread.currentThread().setName( "Client_" + threadId ) ; + log( "Thread " + threadId + " started" ) ; + + while (true) { + synchronized( runningLock ) { + if (!running) + break ; + } + + try { + log( "Thread " + threadId + " sleeping" ) ; + sleep( delay ) ; + int result ; + logStart( ) ; + if (useEcho) + result = testref.echo( testref, threadId, value ) ; + else + result = testref.delay( testref, threadId, value, callDelay ) ; + logComplete( result ) ; + if (result != value) + throw new Exception( "value and result do not match" ) ; + value++ ; + } catch (InterruptedException exc) { + log( "Thread " + threadId + " interrupted" ) ; + } catch (Exception exc) { + fatal( "Exception in client: " + exc, exc ) ; + } finally { + value++ ; + } + } + + log( "Thread " + threadId + " terminated" ) ; + } + } + + private static List clients = new ArrayList() ; + + private static final String PORT_NUM = "3074" ; + private static ORB clientORB ; + private static ORB serverORB ; + private static ReferenceFactoryManager rfm ; + private static NamingContextExt clientNamingRoot ; + private static NamingContextExt serverNamingRoot ; + + private static String nocacheFactoryName = "nocache" ; + private static List nocacheFactoryPolicies ; + private static ReferenceFactory nocacheFactory ; + + private static String cacheFactoryName = "cache" ; + private static List cacheFactoryPolicies ; + private static ReferenceFactory cacheFactory ; + + private static TestServantLocator locator ; + + private static void cleanUp() { + for (Client cl : clients) + cl.halt() ; + + for (Client cl : clients) { + try { + cl.join( 500 ) ; + } catch (InterruptedException exc) { + log( "Caught interrupted excption while joining thread " + cl ) ; + } + } + + log( "Shutting down clientORB" ) ; + clientORB.shutdown( true ) ; + log( "Destroying clientORB" ) ; + clientORB.destroy() ; + + log( "Shutting down serverORB" ) ; + serverORB.shutdown( true ) ; + log( "Destroying serverORB" ) ; + serverORB.destroy() ; + } + + private static void initializeORBs( String[] args ) { + // The following must be set as system properties + System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass", + "com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject" ) ; + System.setProperty( "javax.rmi.CORBA.StubClass", + "com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl" ) ; + System.setProperty( "javax.rmi.CORBA.UtilClass", + "com.sun.corba.ee.impl.javax.rmi.CORBA.Util" ) ; + System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, + "true" ) ; + + // initializer client and server ORBs. + // Initialize server using RFM and register objrefs in naming + Properties baseProps = new Properties() ; + baseProps.setProperty( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton" ) ; + baseProps.setProperty( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + baseProps.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, + "localhost" ) ; + baseProps.setProperty( ORBConstants.INITIAL_PORT_PROPERTY, + PORT_NUM ) ; + baseProps.setProperty( ORBConstants.ALLOW_LOCAL_OPTIMIZATION, + "true" ) ; + // For debugging only + baseProps.setProperty( ORBConstants.DEBUG_PROPERTY, + "poa" ) ; + + Properties clientProps = new Properties( baseProps ) ; + clientProps.setProperty( ORBConstants.ORB_ID_PROPERTY, + "clientORB" ) ; + + Properties serverProps = new Properties( baseProps ) ; + serverProps.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + PORT_NUM ) ; + serverProps.setProperty( ORBConstants.SERVER_HOST_PROPERTY, + "localhost" ) ; + serverProps.setProperty( ORBConstants.ORB_ID_PROPERTY, + "serverORB" ) ; + serverProps.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, + "300" ) ; + serverProps.setProperty( ORBConstants.RFM_PROPERTY, + "1" ) ; + + // Ignore the args passed in, since they contain a test framework + // determined value of -ORBInitialPort + String[] myArgs = {} ; + + serverORB = ORB.init( myArgs, serverProps ) ; + new TransientNameService( + com.sun.corba.ee.spi.orb.ORB.class.cast(serverORB) ) ; + + clientORB = ORB.init( myArgs, clientProps ) ; + } + + private static class TestServantLocator extends LocalObject + implements ServantLocator { + private boolean isActive ; + private Servant servant ; + + public TestServantLocator( ORB orb, ReferenceFactoryManager rfm ) { + isActive = true ; + + TestImpl impl = null ; + try { + impl = new TestImpl() ; + } catch (Exception exc) { + fatal( "Exception in creating servant: " + exc, exc ) ; + } + + Tie tie = com.sun.corba.ee.spi.orb.ORB.class.cast( orb ) + .getPresentationManager().getTie() ; + tie.setTarget( impl ) ; + servant = Servant.class.cast( tie ) ; + } + + public synchronized void deactivate() { + isActive = false ; + } + + public synchronized Servant preinvoke( byte[] oid, POA adapter, + String operation, CookieHolder the_cookie + ) throws ForwardRequest { + if (!isActive) + throw new BAD_OPERATION( "Attempt to use deactivated ServantLocator" ) ; + + int delay = oid[0] ; + + log( "ServantLocator.preinvoke for " + operation + " with delay " + delay ) ; + + if (delay > 0) + sleep( delay ) ; + log( "ServantLocator.preinvoke for " + operation + " returning servant" ) ; + + return servant ; + } + + public void postinvoke( byte[] oid, POA adapter, + String operation, Object the_cookie, Servant the_servant ) { + log( "ServantLocator.postinvoke for " + operation + " called" ) ; + } + } + + // Info for creating objrefs: + // refname, delay, cacheflag + private static Object[][] objrefData = { + { "cache/0", 0, true }, + { "cache/5", 5, true }, + { "cache/23", 23, true }, + { "nocache/0", 0, false }, + { "nocache/5", 5, false }, + { "nocache/23", 23, false }} ; + + private static void initializeServer() { + // Get the RFM and naming service + try { + rfm = ReferenceFactoryManager.class.cast( + serverORB.resolve_initial_references( "ReferenceFactoryManager" )) ; + rfm.activate() ; + serverNamingRoot = NamingContextExtHelper.narrow( + serverORB.resolve_initial_references( "NameService" )) ; + clientNamingRoot = NamingContextExtHelper.narrow( + clientORB.resolve_initial_references( "NameService" )) ; + } catch (Exception exc) { + fatal( "Exception in getting initial references: " + exc, exc ) ; + } + + // Create required ReferenceFactory instances + locator = new TestServantLocator( serverORB, rfm ) ; + + PresentationManager pm = + com.sun.corba.ee.spi.orb.ORB.getPresentationManager() ; + String repositoryId ; + + try { + repositoryId = pm.getRepositoryId( new TestImpl() ) ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + + nocacheFactoryPolicies = null ; + nocacheFactory = rfm.create( nocacheFactoryName, + repositoryId, nocacheFactoryPolicies, locator ) ; + + cacheFactoryPolicies = Arrays.asList( + (Policy)ServantCachingPolicy.getPolicy() ) ; + cacheFactory = rfm.create( cacheFactoryName, + repositoryId, cacheFactoryPolicies, locator ) ; + + // Use RMs to create objrefs and register them with naming + for ( Object[] data : objrefData) { + String sname = String.class.cast( data[0] ) ; + int delay = Integer.class.cast( data[1] ) ; + boolean useCaching = Boolean.class.cast( data[2] ) ; + ReferenceFactory factory = useCaching ? cacheFactory : nocacheFactory ; + byte[] oid = new byte[] { (byte)delay } ; + org.omg.CORBA.Object objref = factory.createReference( oid ) ; + try { + bindName( serverNamingRoot, sname, objref ) ; + } catch (Exception exc) { + fatal( "Error in initializeServer: " + exc, exc ) ; + } + } + } + + private static void bindName( NamingContext ctx, String sname, + org.omg.CORBA.Object objref ) + throws NotFound, CannotProceed, AlreadyBound, InvalidName + { + NameComponent[] name = serverNamingRoot.to_name( sname ) ; + NamingContext current = ctx ; + for (int ctr=0; ctr>> map = new + HashMap>>() ; + map.put( nocacheFactoryName, new Pair( locator, nocacheFactoryPolicies ) ) ; + map.put( cacheFactoryName, new Pair( locator, cacheFactoryPolicies ) ) ; + rfm.restartFactories( map ) ; + } + + public static void main( String[] args ) { + try { + initializeORBs( args ) ; + initializeServer() ; + initializeClients() ; + + // + // At this point all clients are running and sending + // requests. Now the test begins. + + for (int ctr=0; ctr<3; ctr++) { + sleep( RUN_TIME ) ; + log( "RFM>>>Suspend" ) ; + rfm.suspend() ; + log( "RFM>>>Reconfigure" ) ; + reconfigure() ; + log( "RFM>>>Resume" ) ; + rfm.resume() ; + } + + synchronized (runningLock) { + running = false ; + } + + cleanUp() ; + log( "Test Complete" ) ; + System.exit(0) ; + } catch (Throwable thr) { + fatal( "Test FAILED: Caught throwable " + thr, thr ) ; + } + } +} diff --git a/test/src/share/classes/corba/rfm/TestRFM.java b/test/src/share/classes/corba/rfm/TestRFM.java new file mode 100644 index 000000000..2a6a700a8 --- /dev/null +++ b/test/src/share/classes/corba/rfm/TestRFM.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rfm; + +import test.Test; +import corba.framework.*; +import java.util.*; + +public class TestRFM extends CORBATest +{ + protected void doTest() throws Throwable + { + // Controller orbd = createORBD() ; + // orbd.start() ; + + Controller client = createClient("corba.rfm.TestClient"); + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + // orbd.stop() ; + } +} + diff --git a/test/src/share/classes/corba/rmic/A.java b/test/src/share/classes/corba/rmic/A.java new file mode 100644 index 000000000..813f9af25 --- /dev/null +++ b/test/src/share/classes/corba/rmic/A.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmic; + +public interface A extends java.rmi.Remote { + public void f() throws Throwable; +} diff --git a/test/src/share/classes/corba/rmic/B.java b/test/src/share/classes/corba/rmic/B.java new file mode 100644 index 000000000..699910dab --- /dev/null +++ b/test/src/share/classes/corba/rmic/B.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmic; + +public interface B extends A, java.rmi.Remote { + public void f() throws Exception; +} diff --git a/test/src/share/classes/corba/rmic/C.java b/test/src/share/classes/corba/rmic/C.java new file mode 100644 index 000000000..d0c267033 --- /dev/null +++ b/test/src/share/classes/corba/rmic/C.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmic; + +public interface C extends B, java.rmi.Remote { + public void f() throws ClassNotFoundException, java.rmi.RemoteException; +} diff --git a/test/src/share/classes/corba/rmic/CImpl.java b/test/src/share/classes/corba/rmic/CImpl.java new file mode 100644 index 000000000..322ebbca8 --- /dev/null +++ b/test/src/share/classes/corba/rmic/CImpl.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmic; + +public class CImpl implements C { + public void f() throws ClassNotFoundException, java.rmi.RemoteException { + throw new ClassNotFoundException(" Yahoooo"); + } +} diff --git a/test/src/share/classes/corba/rmic/RmicTest.java b/test/src/share/classes/corba/rmic/RmicTest.java new file mode 100644 index 000000000..84bbbb667 --- /dev/null +++ b/test/src/share/classes/corba/rmic/RmicTest.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// Created : 2003 Apr 09 (Wed) 16:31:43 by Harold Carr. +// Last Modified : 2004 Jan 31 (Sat) 09:54:44 by Harold Carr. +// + +package corba.rmic; + +import corba.framework.Controller; +import corba.framework.CORBATest; + +import corba.framework.*; + +public class RmicTest extends CORBATest { + + public static String[] rmicClasses = { "corba.rmic.CImpl" }; + + protected void doTest() throws Throwable { + Options.addRMICArgs("-g -iiop -poa -always -keep"); + Options.setRMICClasses(rmicClasses); + compileRMICFiles(); + } +} + +// End of file. + diff --git a/test/src/share/classes/corba/rmipoacounter/counterServer.java b/test/src/share/classes/corba/rmipoacounter/counterServer.java new file mode 100644 index 000000000..afa4da122 --- /dev/null +++ b/test/src/share/classes/corba/rmipoacounter/counterServer.java @@ -0,0 +1,375 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.rmipoacounter; + +import javax.rmi.PortableRemoteObject ; +import java.io.DataOutputStream ; +import java.rmi.RemoteException ; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Properties; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.PortableServer.AdapterActivator; +import org.omg.PortableServer.ForwardRequest; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.RequestProcessingPolicyValue; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.ServantActivator; +import org.omg.PortableServer.ServantLocator; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +public class counterServer { + public static boolean debug = true; + public static String Counter1Id = "abcdef"; + public static String Counter2Id = "qwerty"; + + // Temporary hack to get this test to work and keep the output + // directory clean + private static final String outputDirOffset + = "/corba/rmipoacounter/".replace('/', File.separatorChar); + + public static void main(String args[]) + { + try{ + // set debug flag + if ( args.length > 0 && args[0].equals("-debug") ) + debug = true; + + if (debug) { + System.out.println("ENTER: counterServer"); + System.out.flush(); + } + + // create and initialize the ORB + Properties p = new Properties(); + p.put("org.omg.CORBA.ORBClass", + System.getProperty("org.omg.CORBA.ORBClass")); + p.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "9999"); + ORB orb = ORB.init(args, p); + + if (debug) { + System.out.println("counterServer: ORB initialized"); + System.out.flush(); + } + + // get rootPOA, set the AdapterActivator, and activate RootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_activator(new MyAdapterActivator(orb)); + rootPOA.the_POAManager().activate(); + + if (debug) { + System.out.println("counterServer: RootPOA activator set"); + System.out.flush(); + } + + if ( isFirstTime() ) { + if (debug) { + System.out.println("counterServer: Is first time"); + System.out.flush(); + } + POA poa = createPersistentPOA(orb, rootPOA); + createCounter1(orb, poa); + poa = createNonRetainPOA(orb, rootPOA); + createCounter2(orb, poa); + if (debug) { + System.out.println("counterServer: refs created"); + System.out.flush(); + } + } + + // wait for invocations from clients + System.out.println("Server is ready."); + System.out.flush(); + + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + System.exit(1); + } finally { + if (debug) { + System.out.println("EXIT: counterServer"); + System.out.flush(); + } + } + } + + + private static boolean isFirstTime() + throws Exception + { + // Check if the counterValue file is there + String name = System.getProperty("output.dir") + + outputDirOffset + + "counterValue"; + File file = new File(name); + return ( !file.exists() ); + } + + static POA createPersistentPOA(ORB orb, POA rootPOA) + throws Exception + { + // create a persistent POA + Policy[] tpolicy = new Policy[2]; + tpolicy[0] = rootPOA.create_lifespan_policy( + LifespanPolicyValue.PERSISTENT); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + POA tpoa = rootPOA.create_POA("PersistentPOA", null, tpolicy); + + // register the ServantActivator with the POA, then activate POA + CounterServantActivator csa = new CounterServantActivator(orb); + tpoa.set_servant_manager(csa); + tpoa.the_POAManager().activate(); + return tpoa; + } + + static Servant makeCounterServant( ORB orb ) + { + counterImpl impl = null ; + + try { + impl = new counterImpl(orb, counterServer.debug); + } catch (RemoteException exc) { + // ignore + } + + Servant servant = (Servant)(javax.rmi.CORBA.Util.getTie( impl ) ) ; + + return servant ; + } + + static void createCounter1(ORB orb, POA tpoa) + throws Exception + { + // create an objref using persistent POA + byte[] id = Counter1Id.getBytes(); + String intf = new _counterImpl_Tie()._all_interfaces(tpoa,id)[0]; + + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, + intf); + + Class intfr = Class.forName("corba.rmipoacounter.counterIF"); + + counterIF counterRef + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + // put objref in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Counter1", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + + // invoke on the local objref to test local invocations + if ( counterServer.debug ) + System.out.println("\nTesting local invocation: Client thread is "+Thread.currentThread()); + long value = counterRef.increment(1); + if ( counterServer.debug ) + System.out.println(value); + } + + static POA createNonRetainPOA(ORB orb, POA rootPOA) + throws Exception + { + // create another persistent, non-retaining POA + Policy[] tpolicy = new Policy[3]; + tpolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT); + tpolicy[1] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + tpolicy[2] = rootPOA.create_servant_retention_policy( + ServantRetentionPolicyValue.NON_RETAIN); + POA tpoa = rootPOA.create_POA("NonRetainPOA", null, tpolicy); + + // register the ServantLocator with the POA, then activate POA + CounterServantLocator csl = new CounterServantLocator(orb); + tpoa.set_servant_manager(csl); + tpoa.the_POAManager().activate(); + return tpoa; + } + + static void createCounter2(ORB orb, POA tpoa) + throws Exception + { + // create a servant and get an objref using persistent POA + byte[] id = Counter2Id.getBytes(); + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, + new _counterImpl_Tie()._all_interfaces(tpoa,id)[0]); + counterIF counterRef = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + /********8 + // put objref in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Counter2", ""); + NameComponent path[] = {nc}; + ncRef.rebind(path, counterRef); + **********/ + OutputStream f = new FileOutputStream( + System.getProperty("output.dir") + + outputDirOffset + + "counterior2") ; + DataOutputStream out = new DataOutputStream(f) ; + String ior = orb.object_to_string(obj) ; + out.writeBytes(ior) ; + out.close(); + + } +} + + +class MyAdapterActivator extends org.omg.CORBA.LocalObject implements AdapterActivator +{ + private ORB orb; + + MyAdapterActivator(ORB orb) + { + this.orb = orb; + } + + public boolean unknown_adapter(POA parent, String name) + { + if ( counterServer.debug ) + System.out.println("\nIn MyAdapterActivator.unknown_adapter, parent = "+parent.the_name()+" child = "+name); + try { + if ( name.equals("PersistentPOA") ) + counterServer.createPersistentPOA(orb, parent); + else if ( name.equals("NonRetainPOA") ) + counterServer.createNonRetainPOA(orb, parent); + else + return false; + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } + + return true; + } +} + + + +class CounterServantActivator extends org.omg.CORBA.LocalObject implements ServantActivator +{ + ORB orb; + + CounterServantActivator(ORB orb) + { + this.orb = orb; + } + + public Servant incarnate(byte[] oid, POA adapter) + throws org.omg.PortableServer.ForwardRequest + { + Servant servant = counterServer.makeCounterServant( orb ) ; + + if ( counterServer.debug ) + System.out.println("\nIn CounterServantActivator.incarnate, oid = " + +oid + +" poa = "+adapter.the_name() + +" servant = "+servant); + return servant; + } + + public void etherealize(byte[] oid, POA adapter, Servant servant, + boolean cleanup_in_progress, boolean remaining_activations) + { + if ( counterServer.debug ) + System.out.println("\nIn CounterServantActivator.etherealize, oid = " + +oid + +" poa = "+adapter.the_name() + +" servant = "+servant + +" cleanup_in_progress = "+cleanup_in_progress + +" remaining_activations = "+remaining_activations); + return; + } +} + +class CounterServantLocator extends org.omg.CORBA.LocalObject implements ServantLocator +{ + ORB orb; + + CounterServantLocator(ORB orb) + { + this.orb = orb; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + String sid = new String(oid); + String newidStr = "somethingdifferent"; + + // Tests location forwards + if ( sid.equals(counterServer.Counter2Id) ) { + // construct a new objref to forward to. + byte[] id = newidStr.getBytes(); + org.omg.CORBA.Object obj = null; + try { + obj = adapter.create_reference_with_id(id, + new _counterImpl_Tie()._all_interfaces(adapter,oid)[0]); + } catch ( Exception ex ) {} + counterIF counterRef = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + System.out.println("\nCounterServantLocator.preinvoke forwarding ! " + +"old oid ="+new String(oid) + +"new id ="+new String(id)); + + ForwardRequest fr = new ForwardRequest(obj); + throw fr; + } + + String oidStr = new String(oid); + if ( !newidStr.equals(oidStr) ) + System.err.println("\tERROR !!!: preinvoke got wrong id:"+oidStr); + + MyCookie cookie = new MyCookie(); + Servant servant = counterServer.makeCounterServant( orb ) ; + + if ( counterServer.debug ) + System.out.println("\nIn CounterServantLocator.preinvoke, oid = " + +oidStr + +" poa = "+adapter.the_name() + +" operation = " +operation + +" cookie = "+cookie+" servant = "+servant); + + the_cookie.value = cookie; + return servant; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + if ( counterServer.debug ) + System.out.println("\nIn CounterServantLocator.postinvoke, oid = " + +new String(oid) + +" poa = "+adapter.the_name() + +" operation = " +operation + +" cookie = "+cookie+" servant = "+servant); + return; + } +} + +class MyCookie +{} diff --git a/test/src/share/classes/corba/security/Client.java b/test/src/share/classes/corba/security/Client.java new file mode 100644 index 000000000..133467a34 --- /dev/null +++ b/test/src/share/classes/corba/security/Client.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.security; + +import java.security.ProtectionDomain ; +import java.security.Permission ; +import java.security.PermissionCollection ; +import java.security.Principal ; +import java.security.CodeSource ; +import java.security.cert.Certificate ; +import java.security.Policy ; + +import java.util.Properties ; +import java.util.Enumeration ; + +import java.io.PrintStream ; +import java.net.URL ; + +public class Client +{ + private PrintStream out ; + private PrintStream err ; + // private ORB orb ; + + public static void main(String args[]) + { + System.out.println( "Starting Permission test" ) ; + try{ + Properties props = new Properties( System.getProperties() ) ; + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + new Client( props, args, System.out, System.err ) ; + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } + + public Client( Properties props, String args[], PrintStream out, + PrintStream err ) + { + //this.orb = (ORB)ORB.init( args, props ) ; + this.out = System.out ; + this.err = System.err ; + + runTests() ; + } + +// ************************************************* +// *************** Utilities ******************* +// ************************************************* + + private void error( String msg ) + { + RuntimeException exc = new RuntimeException( msg ) ; + throw exc ; + } + + private void info( String msg ) + { + out.println( msg ) ; + } + + +// ************************************************* +// *************** TESTS *********************** +// ************************************************* + private void dumpPermissions( PermissionCollection pc ) + { + Enumeration perms = pc.elements() ; + while (perms.hasMoreElements()) { + Permission current = (Permission)perms.nextElement() ; + info( "\t\t" + current ) ; + } + } + + private void dumpProtectionDomain( String msg, ProtectionDomain pd ) + { + CodeSource cs = pd.getCodeSource() ; + Policy policy = Policy.getPolicy() ; + PermissionCollection pc = policy.getPermissions( pd ) ; + + info( msg ) ; + info( "\tCodeSource: " + cs ) ; + info( "\tPermissions:" ) ; + dumpPermissions( pc ) ; + } + + private void dumpProtectionDomainForClass( Class cls ) + { + dumpProtectionDomain( "ProtectionDomain for " + cls, + cls.getProtectionDomain() ) ; + } + + + private void dumpProtectionDomainForPath( String path ) + { + URL url = null ; + + try { + url = new URL( "file:" + path + "/-" ) ; + } catch (Exception exc) { + exc.printStackTrace( ) ; + System.exit(1) ; + } + + CodeSource cs = new CodeSource( url, (Certificate[])null ) ; + Policy policy = Policy.getPolicy() ; + PermissionCollection pc = policy.getPermissions( cs ) ; + info( "Permissions for code loaded from path " + path ) ; + info( "URL: " + url ) ; + info( "\tPermissionCollection:" ) ; + dumpPermissions( pc ) ; + info( "" ) ; + } + + private Class getClass( String name ) + { + try { + return Class.forName( name ) ; + } catch (Exception exc) { + return null ; + } + } + + private void dumpProperty( String name ) + { + info( "Property " + name + " has value " + + System.getProperty( name ) ) ; + } + + private void runTests() + { + info( "System.getSecurityManager() = " + System.getSecurityManager() ) ; + dumpProperty( "com.sun.corba.ee.POA.ORBServerId" ) ; + dumpProperty( "com.sun.corba.ee.ORBBase" ) ; + dumpProperty( "java.security.policy" ) ; + dumpProperty( "java.security.debug" ) ; + dumpProperty( "java.security.manager" ) ; + info( "" ) ; + + dumpProtectionDomainForPath( + System.getProperty( "com.sun.corba.ee.ORBBase" ) + "/build" ) ; + dumpProtectionDomainForPath( + System.getProperty( "com.sun.corba.ee.ORBBase" ) + "/optional/build" ) ; + dumpProtectionDomainForPath( + System.getProperty( "com.sun.corba.ee.ORBBase" ) + "/test/build" ) ; + + dumpProtectionDomainForClass( + com.sun.corba.ee.spi.orb.ORB.class ) ; + dumpProtectionDomainForClass( + com.sun.corba.ee.impl.orb.ORBImpl.class ) ; + dumpProtectionDomainForClass( + org.omg.CORBA.ORB.class ) ; + dumpProtectionDomainForClass( + corba.security.Client.class ) ; + + Class cls = getClass( + "com.sun.corba.ee.spi.copyobject.OptimizedCopyobjectDefaults" ) ; + if (cls != null) + dumpProtectionDomainForClass( cls ) ; + + cls = getClass( + "com.sun.corba.ee.impl.copyobject.newreflect.ClassCopier" ) ; + if (cls != null) + dumpProtectionDomainForClass( cls ) ; + } +} diff --git a/test/src/share/classes/corba/security/PermissionTest.java b/test/src/share/classes/corba/security/PermissionTest.java new file mode 100644 index 000000000..45be68f09 --- /dev/null +++ b/test/src/share/classes/corba/security/PermissionTest.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.security; + +import test.Test; +import corba.framework.*; +import java.util.*; + +public class PermissionTest extends CORBATest +{ + protected void doTest() throws Throwable + { + Controller client = createClient("corba.security.Client"); + + client.start(); + + client.waitFor(120000); + + client.stop(); + } +} + diff --git a/test/src/share/classes/corba/serialization/good/GoodRepIdTest.java b/test/src/share/classes/corba/serialization/good/GoodRepIdTest.java new file mode 100644 index 000000000..8186b7352 --- /dev/null +++ b/test/src/share/classes/corba/serialization/good/GoodRepIdTest.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.good; + +import corba.framework.*; +import java.util.*; + +public class GoodRepIdTest extends CORBATest +{ + protected void doTest() throws Throwable + { + Controller server = createServer("corba.serialization.good.ShowRepid"); + + server.start(); + + server.stop(); + } +} diff --git a/test/src/share/classes/corba/serialization/good/ShowRepid.java b/test/src/share/classes/corba/serialization/good/ShowRepid.java new file mode 100644 index 000000000..4cf7eb5ba --- /dev/null +++ b/test/src/share/classes/corba/serialization/good/ShowRepid.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* This will print the CORBA RepositoryId for a specified Java class. + * + * If the rules laid down in the CORBA spec (section 10.6.2) and the + * CORBA Java-to-IDL spec (section 1.3.5.6) are followed, I believe + * the following results should be obtained: + * + * + * java ShowRepid java.lang.Class + * class java.lang.Class = RMI:javax.rmi.CORBA.ClassDesc:2BABDA04587ADCCC:CFBF02CF5294176B + * + * java ShowRepid java.util.GregorianCalendar + * class java.util.GregorianCalendar = RMI:java.util.GregorianCalendar:450042FBA7A923B1:8F3DD7D6E5B0D0C1 + * + * java ShowRepid java.io.ObjectStreamClass + * class java.io.ObjectStreamClass = RMI:java.io.ObjectStreamClass:071DA8BE7F971128:AB0E6F1AEEFE7B88 + * + * java ShowRepid ShowRepid + * class ShowRepid = RMI:ShowRepid:AC117E28FE36587A:0000000000001234 + */ +package corba.serialization.good; + +import java.io.*; +import com.sun.corba.ee.impl.util.RepositoryId; + +public class ShowRepid implements Serializable { + static final long serialVersionUID = 0x1234; + + private void writeObject(ObjectOutputStream s) throws IOException { + } + + private static int runTest() { + int rc = 0; + + String r1 = "RMI:javax.rmi.CORBA.ClassDesc:2BABDA04587ADCCC:CFBF02CF5294176B"; + String r2 = "RMI:java.util.GregorianCalendar:450042FBA7A923B1:8F3DD7D6E5B0D0C1"; + String r3 = "RMI:java.io.ObjectStreamClass:071DA8BE7F971128:AB0E6F1AEEFE7B88"; + String r4 = "RMI:corba.serialization.good.ShowRepid:AC117E28FE36587A:0000000000001234"; + String r5 = "RMI:java.util.Hashtable:86573568A211C011:13BB0F25214AE4B8"; + + String s1 = RepositoryId.createForAnyType(java.lang.Class.class); + String s2 = RepositoryId.createForAnyType(java.util.GregorianCalendar.class); + String s3 = RepositoryId.createForAnyType(java.io.ObjectStreamClass.class); + String s4 = RepositoryId.createForAnyType(ShowRepid.class); + String s5 = RepositoryId.createForAnyType(java.util.Hashtable.class); + + if (!s1.equals(r1)) { + System.out.println("mismatch " + s1); + ++rc; + } + if (!s2.equals(r2)) { + System.out.println("mismatch " + s2); + ++rc; + } + if (!s3.equals(r3)) { + System.out.println("mismatch " + s3); + ++rc; + } + if (!s4.equals(r4)) { + System.out.println("mismatch " + s4); + ++rc; + } + if (!s5.equals(r5)) { + System.out.println("mismatch " + s5); + ++rc; + } + + + return rc; + } + + public static void main(String[] args) { + System.out.println("Server is ready."); + if (args.length == 0) { + if (runTest() == 0) + System.out.println("Test PASSED"); + else { + System.out.println("Test FAILED"); + System.exit(1) ; + } + } else { + try { + Class clz = Class.forName(args[0]); + System.out.print(clz + " = "); + System.out.println(RepositoryId.createForAnyType(clz)); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/test/src/share/classes/corba/serialization/proxy/Client.java b/test/src/share/classes/corba/serialization/proxy/Client.java new file mode 100644 index 000000000..803dcd864 --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/Client.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import java.rmi.*; +import javax.rmi.PortableRemoteObject; +import javax.naming.*; + +import java.io.*; + +public class Client +{ + public static void main(String args[]) + { + FrobnicatorProvider test = null; + try { + System.setSecurityManager(new NoSecurityManager()); + Context initialNamingContext = new InitialContext(); + Object myLook = initialNamingContext.lookup("DynamicProxyBug1368"); + + //System.out.println("Lookup = " + initialNamingContext ); + //System.out.println("LookObjType = " + myLook.getClass().getName() ); + + //Obtain a stub for the remote object. + test = (FrobnicatorProvider)PortableRemoteObject.narrow( + myLook , + FrobnicatorProvider.class); + Frobnicator frobnicator = test.getFrobnicator(); + //toString operation will cause proxy invocation + //System.out.println("My frob= " + frobnicator); + //System.out.println("remoting.."); + frobnicator.frobnicate(); + } catch (Throwable t) { + t.printStackTrace(); + System.out.println("Error: DynamicProxyBug1368 Failed"); + System.exit(1); + } + } +} diff --git a/test/src/share/classes/corba/serialization/proxy/Frobnicator.java b/test/src/share/classes/corba/serialization/proxy/Frobnicator.java new file mode 100644 index 000000000..efb14a5ab --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/Frobnicator.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +public interface Frobnicator { + + public void frobnicate(); + +} diff --git a/test/src/share/classes/corba/serialization/proxy/FrobnicatorProvider.java b/test/src/share/classes/corba/serialization/proxy/FrobnicatorProvider.java new file mode 100644 index 000000000..157b156ef --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/FrobnicatorProvider.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import java.rmi.*; + +public interface FrobnicatorProvider extends java.rmi.Remote { + + public Frobnicator getFrobnicator() throws RemoteException ; + +} diff --git a/test/src/share/classes/corba/serialization/proxy/FrobnicatorProviderBean.java b/test/src/share/classes/corba/serialization/proxy/FrobnicatorProviderBean.java new file mode 100644 index 000000000..c57175886 --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/FrobnicatorProviderBean.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; +import java.lang.reflect.*; + +public class FrobnicatorProviderBean extends PortableRemoteObject implements + FrobnicatorProvider +{ + public FrobnicatorProviderBean() throws RemoteException { + super(); + } + + // remote method + public Frobnicator getFrobnicator() throws RemoteException { + return (Frobnicator) + Proxy.newProxyInstance( + Frobnicator.class.getClassLoader(), + new Class[] { Frobnicator.class }, + new Handler() + ); + } +} diff --git a/test/src/share/classes/corba/serialization/proxy/Handler.java b/test/src/share/classes/corba/serialization/proxy/Handler.java new file mode 100644 index 000000000..38625cf23 --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/Handler.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import java.io.Serializable; + +import java.lang.reflect.*; + +public final class Handler implements InvocationHandler, Serializable { + + public Handler() { + super(); + } + + public final Object invoke(final Object proxy, + final Method method, + final Object[] args) throws Throwable { + //System.out.println("From DynamicProxy InvokeHandler .."); + //Doesn't matter what you return here + return null; + } + +} + diff --git a/test/src/share/classes/corba/serialization/proxy/NoSecurityManager.java b/test/src/share/classes/corba/serialization/proxy/NoSecurityManager.java new file mode 100644 index 000000000..f15c60662 --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/NoSecurityManager.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import java.io.FileDescriptor; +import java.util.Hashtable; +import java.net.InetAddress; +import java.lang.reflect.Member; +import java.security.*; + +/** + * Allows everything. The No Security Security Manager. + */ +public class NoSecurityManager extends java.rmi.RMISecurityManager { + + public void checkCreateClassLoader() { } + public void checkAccess(Thread g) { } + public void checkAccess(ThreadGroup g) { } + public void checkExit(int status) { } + public void checkExec(String cmd) { } + public void checkLink(String lib) { } + public void checkRead(FileDescriptor fd) { } + public void checkRead(String file) { } + public void checkRead(String file, Object context) { } + public void checkWrite(FileDescriptor fd) { } + public void checkWrite(String file) { } + public void checkDelete(String file) { } + public void checkConnect(String host, int port) { } + public void checkConnect(String host, int port, Object context) { } + public void checkListen(int port) { } + public void checkAccept(String host, int port) { } + public void checkMulticast(InetAddress maddr) { } + public void checkMulticast(InetAddress maddr, byte ttl) { } + public void checkPropertiesAccess() { } + public void checkPropertyAccess(String key) { } + public void checkPropertyAccess(String key, String def) { } + public boolean checkTopLevelWindow(Object window) { return true; } + public void checkPrintJobAccess() { } + public void checkSystemClipboardAccess() { } + public void checkAwtEventQueueAccess() { } + public void checkPackageAccess(String pkg) { } + public void checkPackageDefinition(String pkg) { } + public void checkSetFactory() { } + public void checkMemberAccess(Class clazz, int which) { } + public void checkSecurityAccess(String provider) { } + + public void checkPermission(Permission perm) { + } + + public void checkPermission(Permission perm, Object context) { + } +} diff --git a/test/src/share/classes/corba/serialization/proxy/ProxySerializationTest.java b/test/src/share/classes/corba/serialization/proxy/ProxySerializationTest.java new file mode 100644 index 000000000..bdc87a061 --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/ProxySerializationTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import test.Test; +import corba.framework.*; +import java.util.Properties; + +public class ProxySerializationTest extends CORBATest { + protected void doTest() throws Throwable + { + //DEBUG: release commnet here + //test.Test.debug=true; + Options.addServerArg("-debug"); + Controller orbd = createORBD(); + + Properties serverProps = Options.getServerProperties(); + orbd.start(); + + Controller server = createServer("corba.serialization.proxy.Server"); + Controller client = createClient("corba.serialization.proxy.Client"); + + server.start(); + client.start(); + + client.waitFor(120000); + + client.stop(); + server.stop(); + + orbd.stop(); + } +} diff --git a/test/src/share/classes/corba/serialization/proxy/Server.java b/test/src/share/classes/corba/serialization/proxy/Server.java new file mode 100644 index 000000000..f7df1dd63 --- /dev/null +++ b/test/src/share/classes/corba/serialization/proxy/Server.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.proxy; + +import java.rmi.*; +import javax.rmi.PortableRemoteObject; +import javax.naming.*; + +public class Server { + + public static void main(final String[] args) throws Exception { + FrobnicatorProvider obj; + try { + System.setSecurityManager(new NoSecurityManager()); + obj = new FrobnicatorProviderBean(); + Context initialNamingContext = new InitialContext(); + initialNamingContext.rebind("DynamicProxyBug1368", obj); + // below print line is important, else the testframe does not work + System.out.println("Server is ready."); + System.out.flush(); + java.lang.Object sync = new java.lang.Object(); + synchronized (sync) { sync.wait(); } + } catch (final Exception ex) { + ex.printStackTrace(); + System.exit(1); + } + } +} + diff --git a/test/src/share/classes/corba/serialization/zerolengthstring/ClassWithZeroLengthStrings.java b/test/src/share/classes/corba/serialization/zerolengthstring/ClassWithZeroLengthStrings.java new file mode 100644 index 000000000..d73f1b5fc --- /dev/null +++ b/test/src/share/classes/corba/serialization/zerolengthstring/ClassWithZeroLengthStrings.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** + * ClassWithZeroLengthStrings contains 5 fields of which 4 fields are zero + * length Strings. field2 and field3 are same instance (so there is an + * indirection while reading field4) and field4 and field5 are same instance( + * so there is an indirection while reading field5). The main idea behind this + * object is to check whether the aliasing is maintaned when we do a + * Util.copyObject( ) by checking for validateObject( ). + */ +package corba.serialization.zerolengthstring; + +import java.io.*; + +public class ClassWithZeroLengthStrings implements Serializable { + private int field1; + private transient String field2; + private transient String field3; + private transient String field4; + private transient String field5; + + public ClassWithZeroLengthStrings( ) { + field1 = 1; + field2 = new String(""); + field3 = field2; + field4 = new String(""); + field5 = field4; + } + + /** + * We do write out all the transient String fields using the writeObject. + */ + private void writeObject(ObjectOutputStream out) throws IOException + { + out.defaultWriteObject(); + out.writeObject( field2 ); + out.writeObject( field3 ); + out.writeObject( field4 ); + out.writeObject( field5 ); + } + + + /** + * We do read all the transient String fields using the readObject. + */ + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + field2 = (String) in.readObject( ); + field3 = (String) in.readObject( ); + field4 = (String) in.readObject( ); + field5 = (String) in.readObject( ); + } + + + /** + * Important method to check whether the structure of the object is + * maintained correctly after Util.copyObject( ) + */ + public boolean validateObject( ) { + if( field1 != 1 ) { + System.err.println( "field1 != 1" ); + return false; + } + + // Structurally fields 2,3,4 and 5 are all Zero Length Strings + String zeroLengthString = new String(""); + if( !field2.equals( zeroLengthString ) + || !field3.equals( zeroLengthString ) + || !field4.equals( zeroLengthString ) + || !field5.equals( zeroLengthString ) ) + { + System.err.println( "if( !field2.equals( zeroLengthString)" + + "|| !field3.equals( zeroLengthString )" + + "|| !field4.equals( zeroLengthString ) "+ + "|| !field5.equals( zeroLengthString ) returned true" ); + return false; + } + + // We want to make sure field2 and field3 are same instance as well + // as field4 and field5 + if( field2 != field3 ) { + System.err.println( "field2 != field3 returned true " ); + return false; + } + if( field4 != field5 ) { + System.err.println( "field4 != field5 returned true " ); + return false; + } + if( field3 == field4 ) { + System.err.println( "field3 == field4 returned true " ); + return false; + } + return true; + } +} + + diff --git a/test/src/share/classes/corba/serialization/zerolengthstring/MainTest.java b/test/src/share/classes/corba/serialization/zerolengthstring/MainTest.java new file mode 100644 index 000000000..8bce636ce --- /dev/null +++ b/test/src/share/classes/corba/serialization/zerolengthstring/MainTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/** + * A Simple test to check copy created from Util.copyObject() preserves the + * object structure correctly. This test was added to test the bug fix for + * a P2 Bug (4728756), Util.copyObjects () use to fail when there were 2 fields + * with different Zero length string instances and 2 other fields aliasing + * to those two Strings. + */ +package corba.serialization.zerolengthstring; + +import java.util.Properties; +import org.omg.CORBA.ORB; +import javax.rmi.CORBA.Util; + +public class MainTest { + + private static boolean runTest( String[] args ) { + try { + ORB orb = ORB.init( args, null ); + ClassWithZeroLengthStrings object = + new ClassWithZeroLengthStrings(); + ClassWithZeroLengthStrings copiedObject = + (ClassWithZeroLengthStrings) Util.copyObject( object, orb ); + // After copying the object successfully, check to see if + // the structure is the same as expected. + return copiedObject.validateObject( ); + } catch ( Exception e ) { + System.err.println( "Exception " + e + " caught in runTest() " ); + e.printStackTrace( ); + return false; + } + } + + public static void main(String[] args) { + System.out.println("Server is ready."); + if ( runTest( args ) ) + System.out.println("Test PASSED"); + else { + System.out.println("Test FAILED"); + System.exit(1) ; + } + } +} diff --git a/test/src/share/classes/corba/serialization/zerolengthstring/ZeroLengthStringTest.java b/test/src/share/classes/corba/serialization/zerolengthstring/ZeroLengthStringTest.java new file mode 100644 index 000000000..cfd295b39 --- /dev/null +++ b/test/src/share/classes/corba/serialization/zerolengthstring/ZeroLengthStringTest.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.serialization.zerolengthstring; + +import corba.framework.*; + +public class ZeroLengthStringTest extends CORBATest +{ + protected void doTest() throws Throwable + { + Controller server = createServer( + "corba.serialization.zerolengthstring.MainTest"); + + server.start(); + + server.stop(); + } +} diff --git a/test/src/share/classes/corba/shutdown/Client.sjava b/test/src/share/classes/corba/shutdown/Client.sjava new file mode 100644 index 000000000..4c7856e74 --- /dev/null +++ b/test/src/share/classes/corba/shutdown/Client.sjava @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.shutdown; + +import HelloApp.*; +import com.sun.corba.ee.impl.orbutil.ORBConstants; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.Properties ; + +public class Client implements Runnable +{ + static final int NTHREADS = 100; + static final int NITNS = 10; + static hello helloRef; + + static final java.lang.Object lock = new java.lang.Object (); + static boolean errorOccured = false; + + public void signalError () + { + synchronized (Client.lock) { + errorOccured = true; + } + } + + public static void main(String args[]) + { + try{ + Properties props = new Properties(System.getProperties()); +// Examples of how to set ORB debug properties and default fragment size +// props.put(ORBConstants.DEBUG_PROPERTY, "transport,giop"); +// props.put(ORBConstants.GIOP_FRAGMENT_SIZE, "32"); + // create and initialize the ORB + ORB orb = ORB.init(args, props); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent("Hello", ""); + NameComponent path[] = {nc}; + helloRef = helloHelper.narrow(ncRef.resolve(path)); + + System.out.println ("Starting client threads..."); + + Thread[] threads = new Thread[NTHREADS]; + for ( int i=0; i( "foo", "bar" ) ; + Object d2 = new Pair( "baz", new ThrowsSysEx() ) ; + Foo f1 = new Foo( "d1", d1, "d2", d2 ) ; + Pair result = new Pair( "f1", f1 ) ; + return result ; + } + + public int[] echo( int[] arg ) { + return arg ; + } + + public Object echo( Object arg ) { + return arg ; + } + + public BuckPasserAL echo( BuckPasserAL arg ) { + return arg ; + } + + public BuckPasserV echo( BuckPasserV arg ) { + return arg ; + } + + public BuckPasserVectorOriginal echo( BuckPasserVectorOriginal arg ) throws RemoteException { + return arg ; + } +} diff --git a/test/src/share/classes/corba/simpledynamic/Framework.java b/test/src/share/classes/corba/simpledynamic/Framework.java new file mode 100644 index 000000000..afe806996 --- /dev/null +++ b/test/src/share/classes/corba/simpledynamic/Framework.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.simpledynamic; + +import java.util.Properties ; +import java.util.Hashtable ; + +import java.rmi.Remote ; + +import javax.rmi.CORBA.Util ; +import javax.rmi.CORBA.Tie ; + +import javax.naming.InitialContext ; +import javax.naming.NamingException ; + +import com.sun.corba.ee.spi.JndiConstants; +import org.testng.TestNG ; +import org.testng.annotations.Configuration ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService ; + +import static corba.framework.PRO.* ; + +public abstract class Framework { + private ORB clientORB ; + private ORB serverORB ; + private InitialContext clientIC ; + private InitialContext serverIC ; + + protected static final String PORT_NUM = "46132" ; + + private String BASE = "com.sun.corba.ee." ; + + private void setSystemProperties() { + System.setProperty( "javax.rmi.CORBA.UtilClass", + BASE + "impl.javax.rmi.CORBA.Util" ) ; + System.setProperty( "javax.rmi.CORBA.StubClass", + BASE + "impl.javax.rmi.CORBA.StubDelegateImpl" ) ; + System.setProperty( "javax.rmi.CORBA.PortableRemoteObjectClass", + BASE + "impl.javax.rmi.PortableRemoteObject" ) ; + + // We will only use dynamic RMI-IIOP for this test. + System.out.println( "Setting property " + ORBConstants.USE_DYNAMIC_STUB_PROPERTY + + " to true" ) ; + System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, "true" ) ; + + // Use the J2SE ic provider + System.setProperty( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY ) ; + } + + // We need to set up the client and server ORBs, and start a transient + // name server that runs on the server ORB, with the client ORB referring + // to the server ORB's name service. + protected ORB makeORB( boolean isServer, Properties extra ) { + Properties props = new Properties( extra ) ; + props.setProperty( "org.omg.CORBA.ORBClass", BASE + "impl.orb.ORBImpl" ) ; + props.setProperty( ORBConstants.INITIAL_HOST_PROPERTY, "localhost" ) ; + props.setProperty( ORBConstants.INITIAL_PORT_PROPERTY, PORT_NUM ) ; + props.setProperty( ORBConstants.ALLOW_LOCAL_OPTIMIZATION, "true" ) ; + + if (isServer) { + props.setProperty( ORBConstants.ORB_ID_PROPERTY, "serverORB" ) ; + props.setProperty( ORBConstants.SERVER_HOST_PROPERTY, "localhost" ) ; + props.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, "300" ) ; + setServerPort( props ) ; + } else { + props.setProperty( ORBConstants.ORB_ID_PROPERTY, "clientORB" ) ; + } + + ORB orb = (ORB)ORB.init( new String[0], props ) ; + + updateORB( orb, isServer ) ; + + if (isServer) { + new TransientNameService( + com.sun.corba.ee.spi.orb.ORB.class.cast(orb) ) ; + } + + return orb ; + } + + // This is the default setup for the server ORB's listening port. + // This can be overridden if necessary. + protected void setServerPort( Properties props ) { + props.setProperty( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, PORT_NUM ) ; + } + + // Can be overridden if necessary to allow the ORB to be further + // configured before it is used. + protected void updateORB( ORB orb, boolean isServer ) { + } + + private InitialContext makeIC( ORB orb ) throws NamingException { + Hashtable env = new Hashtable() ; + env.put( "java.naming.corba.orb", orb ) ; + InitialContext ic = new InitialContext( env ) ; + return ic ; + } + + protected ORB getClientORB() { + return clientORB ; + } + + protected ORB getServerORB() { + return serverORB ; + } + + protected InitialContext getClientIC() { + return clientIC ; + } + + protected InitialContext getServerIC() { + return serverIC ; + } + + protected Properties extraServerProperties() { + return new Properties() ; + } + + protected Properties extraClientProperties() { + return new Properties() ; + } + + /** Connect a servant of type cls to the orb. + */ + protected void connectServant( T servant, ORB orb ) { + + try { + Tie tie = Util.getTie( servant ) ; + tie.orb( getServerORB() ) ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + /** Connect a servant to the server ORB, and register it with the + * server InitialContext under name. + */ + protected void bindServant( T servant, Class cls, + String name ) { + + connectServant( servant, getServerORB() ) ; + + try { + T stub = toStub( servant, cls ) ; + getServerIC().bind( name, stub ) ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + protected T findStub( Class cls, String name ) { + try { + return narrow( getClientIC().lookup( name ), cls ) ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + @Configuration( beforeTest = true ) + public void setUp() { + setSystemProperties() ; + serverORB = makeORB( true, extraServerProperties() ) ; + clientORB = makeORB( false, extraClientProperties() ) ; + + try { + serverORB.resolve_initial_references( "NameService" ) ; + + // Make sure that the FVD codebase IOR is not shared between + // multiple ORBs in the value handler, because that causes + // errors in the JDK ORB. + // com.sun.corba.ee.spi.orb.ORB orb = (com.sun.corba.ee.spi.orb.ORB)serverORB ; + // orb.getFVDCodeBaseIOR() ; + + clientORB.resolve_initial_references( "NameService" ) ; + + serverIC = makeIC( serverORB ) ; + clientIC = makeIC( clientORB ) ; + } catch (Exception exc) { + throw new RuntimeException( exc ) ; + } + } + + @Configuration( afterTest = true ) + public void tearDown() { + // The Client ORB does not correctly clean up its + // exported targets: it tries to go to the SE + // RMI-IIOP implementation, which is not even + // instantiated here. So clean up manually. + // + // Fixing this requires changes in the ORB: + // basically it should be the TOA's job to keep + // track of connected objrefs and clean up the + // information in RMI-IIOP. This would affect + // both the se and ee ORBs, and require a patch + // to JSE 5. + clientORB.shutdown( true ) ; + // com.sun.corba.ee.impl.javax.rmi.CORBA.Util.getInstance(). + // unregisterTargetsForORB( clientORB ) ; + clientORB.destroy() ; + + // The Server ORB does clean up correctly. + serverORB.destroy() ; + } + + public static void run( String outputDirectory, Class[] tngClasses ) { + TestNG tng = new TestNG() ; + tng.setOutputDirectory( outputDirectory ) ; + tng.setTestClasses( tngClasses ) ; + tng.run() ; + + // Make sure we report success/failure to the wrapper. + System.exit( tng.hasFailure() ? 1 : 0 ) ; + } +} diff --git a/test/src/share/classes/corba/simpledynamic/FrameworkClient.java b/test/src/share/classes/corba/simpledynamic/FrameworkClient.java new file mode 100644 index 000000000..1091f82b6 --- /dev/null +++ b/test/src/share/classes/corba/simpledynamic/FrameworkClient.java @@ -0,0 +1,466 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.simpledynamic; + +import org.glassfish.pfl.basic.func.NullaryFunction; +//import com.sun.corba.ee.impl.orbutil.newtimer.generated.TimingPoints; +import org.glassfish.pfl.tf.timer.spi.TimerManager; +import org.glassfish.pfl.tf.timer.spi.TimerGroup; +import org.glassfish.pfl.tf.timer.spi.LogEventHandler; +import java.io.IOException ; +import java.io.ObjectInputStream ; +import java.io.ObjectOutputStream ; +import java.io.Serializable ; + +import java.rmi.MarshalException ; + +import java.util.Properties ; + +import java.rmi.RemoteException ; + + + +import org.testng.Assert ; +import org.testng.annotations.Test ; +import org.testng.annotations.BeforeGroups ; + +import corba.nortel.NortelSocketFactory ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; + +import com.sun.corba.ee.spi.orb.ORB ; + +import corba.misc.Buck ; + +import static corba.framework.PRO.* ; + +public class FrameworkClient extends Framework { + private static final boolean RUN_FRAGMENT_TEST = false ; + + private static final String SERVER_NAME = "fromServer" ; + private static final String CLIENT_NAME = "fromClient" ; + private static final String TEST_REF_NAME = "testref" ; + + private static final String TESTREF_GROUP = "testref_group" ; + private static final String GROUP_5161 = "5161_group" ; + + private Echo makeServant( String name ) { + try { + return new EchoImpl( name ) ; + } catch (RemoteException rex) { + Assert.fail( "Unexpected remote exception " + rex ) ; + return null ; // never reached + } + } + + private void msg( String msg ) { + System.out.println( "+++FrameworkClient: " + msg ) ; + } + + @BeforeGroups( { TESTREF_GROUP } ) + public void initTestRef() { + bindServant( makeServant( SERVER_NAME ), Echo.class, TEST_REF_NAME ) ; + } + + @Test( groups = { TESTREF_GROUP } ) + public void firstTest() { + try { + InterceptorTester.theTester.clear() ; + Echo servant = makeServant( CLIENT_NAME ) ; + connectServant( servant, getClientORB() ) ; + + System.out.println( "Creating first echoref" ) ; + Echo ref = toStub( servant, Echo.class ) ; + + System.out.println( "Hello?" ) ; + System.out.println( "Looking up second echoref" ) ; + Echo sref = findStub( Echo.class, TEST_REF_NAME ) ; + Assert.assertEquals( sref.name(), SERVER_NAME ) ; + + if (RUN_FRAGMENT_TEST) { + System.out.println( "Running test for bug 6578707" ) ; + testFragmentation( sref ) ; + } + + System.out.println( "Echoing first echoref" ) ; + Echo rref = sref.say( ref ) ; + Assert.assertEquals( rref.name(), CLIENT_NAME ) ; + + System.out.println( "Echoing second echoref" ) ; + Echo r2ref = rref.say( sref ) ; + Assert.assertEquals( r2ref.name(), SERVER_NAME ) ; + + System.out.println( "Echoing third echoref" ) ; + Echo ref2 = ref.say( ref ) ; + Assert.assertEquals( ref2.name(), ref.name() ) ; + } catch (Exception exc) { + System.out.println( "Caught exception " + exc ) ; + exc.printStackTrace() ; + } + } + + @Override + protected Properties extraServerProperties() { + Properties result = new Properties() ; + result.setProperty( ORBConstants.TIMING_POINTS_ENABLED, "true" ) ; + + result.setProperty( ORBConstants.DEBUG_PROPERTY, "valueHandler,streamFormatVersion,cdr" ) ; + + return result ; + } + + @Override + protected Properties extraClientProperties() { + Properties result = new Properties() ; + + result.setProperty( ORBConstants.TIMING_POINTS_ENABLED, "true" ) ; + + result.setProperty( ORBConstants.DEBUG_PROPERTY, "valueHandler,streamFormatVersion,cdr" ) ; + + // register nortel socket factory + result.setProperty( ORBConstants.SOCKET_FACTORY_CLASS_PROPERTY, + NortelSocketFactory.class.getName() ) ; + + // register ORBInitializer + result.setProperty( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + InterceptorTester.class.getName(), "true" ) ; + + // result.setProperty( ORBConstants.DEBUG_PROPERTY, + // "transport" ) ; + + result.setProperty( ORBConstants.TRANSPORT_TCP_CONNECT_TIMEOUTS_PROPERTY, + "100:2000:100" ) ; + + return result ; + } + + private static class Fragment implements java.io.Serializable { + String str; + + Fragment(int size) { + str=""; + for(int i=0;i clientTM = + clientORB.makeTimerManager( TimingPoints.class) ; + clientLEH = clientTM.factory().makeLogEventHandler( "Client_CDR_LEH" ) ; + clientTM.controller().register( clientLEH ) ; + clientCDR = clientTM.points().Cdr() ; + + final TimerManager serverTM = + serverORB.makeTimerManager( TimingPoints.class ) ; + serverLEH = serverTM.factory().makeLogEventHandler( "Server_CDR_LEH" ) ; + serverTM.controller().register( serverLEH ) ; + serverCDR = serverTM.points().Cdr() ; + } + + public void enable() { + clientCDR.enable() ; + serverCDR.enable() ; + } + + public void disable() { + clientCDR.disable() ; + serverCDR.disable() ; + } + + public void display( String msg ) { + System.out.println( "Displaying CDR events for: " + msg ) ; + clientLEH.display( System.out, "Client-side events" ) ; + serverLEH.display( System.out, "Server-side events" ) ; + } + + public void clear() { + clientLEH.clear() ; + serverLEH.clear() ; + } + } +*/ + + private static final boolean DEBUG_5161 = false ; + + private Echo clientRef5161 = null ; + //private CDRTimerContext timerContext = null ; + + private void doOperation( String msg, NullaryFunction func ) { + System.out.println( msg ) ; + try { +/* + if (DEBUG_5161) { + timerContext.enable() ; + } +*/ + + func.evaluate() ; + // } catch (Exception exc) { + // System.out.println( msg + ": caught exception " + exc ) ; + // exc.printStackTrace() ; + // Assert.fail( "Failed with exception " + exc ) ; + } finally { +/* + if (DEBUG_5161) { + timerContext.disable() ; + timerContext.display( msg ) ; + timerContext.clear() ; + } +*/ + } + } +/* + + @BeforeGroups( { GROUP_5161 } ) + public void init5161() { + // Make sure that echo is implemented in server, but the reference + // is bound in client for the test: we want this to test marshaling, + // not local optimization copying. + final Echo servant = makeServant( "echotest" ) ; + bindServant( servant, Echo.class, "BuckPasser" ) ; + clientRef5161 = findStub( Echo.class, "BuckPasser" ) ; + + if (DEBUG_5161) + // Prepare timing for client and server ORBs + timerContext = new CDRTimerContext( getClientORB(), getServerORB() ) ; + } + + // btrace hooks + private void stop() {} + private void start() {} + + @Test( groups = { GROUP_5161 } ) + public void test5161VectorOriginal() { + doOperation( "Testing VectorOriginal", new NullaryFunction() { + public Object evaluate() { + try { + BuckPasserVectorOriginal bpvo = new BuckPasserVectorOriginal() ; + bpvo.add( new Buck( "The Buck" ) ) ; + start() ; + BuckPasserVectorOriginal bpvo2 = null ; + try { + bpvo2 = clientRef5161.echo( bpvo ) ; + } finally { + stop() ; + } + Assert.assertTrue( bpvo2.equals( bpvo ) ) ; + return null ; + } catch (RemoteException exc) { + throw new RuntimeException( exc ) ; + } + } + } ) ; + } +*/ + + // @Test( groups = { GROUP_5161 } ) + public void test5161() throws RemoteException { + // System.out.println( "Running test for issue 5161" ) ; + + /* This does not reproduce the problem + final BuckPasserAL bpal = new BuckPasserAL() ; + bpal.add( new Buck( "The Buck" ) ) ; + + final BuckPasserV bpv = new BuckPasserV() ; + bpv.add( new Buck( "The Buck" ) ) ; + + OutputStream out = (OutputStream)orb.create_output_stream(); + + out.write_value(bpal) ; + out.write_value(bpv) ; + + InputStream in = (InputStream)out.create_input_stream(); + + BuckPasserAL bpal2 = (BuckPasserAL)in.read_value() ; + BuckPasserV bpv2 = (BuckPasserV)in.read_value() ; + */ + + /** This case passes, so comment out for now + doOperation( "Testing ArrayList", new NullaryFunction() { + public Object evaluate() { + try { + BuckPasserAL bpal2 = clientRef5161.echo( bpal ) ; + Assert.assertTrue( bpal2.equals( bpal ) ) ; + return null ; + } catch (RemoteException exc) { + throw new RuntimeException( exc ) ; + } + } + } ) ; + */ + } + + public static void main( String[] args ) { + Class[] classes = { FrameworkClient.class } ; + Framework.run( "gen/corba/simpledynamic/test-output", classes ) ; + } +} diff --git a/test/src/share/classes/corba/simpledynamic/InterceptorTester.java b/test/src/share/classes/corba/simpledynamic/InterceptorTester.java new file mode 100644 index 000000000..889eada88 --- /dev/null +++ b/test/src/share/classes/corba/simpledynamic/InterceptorTester.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.simpledynamic; + +import org.omg.PortableInterceptor.ORBInitializer ; +import org.omg.PortableInterceptor.ClientRequestInterceptor ; +import org.omg.PortableInterceptor.ClientRequestInfo ; +import org.omg.PortableInterceptor.ORBInitInfo ; +import org.omg.PortableInterceptor.ForwardRequest ; + +import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName ; + +import org.omg.CORBA.LocalObject ; +import org.omg.CORBA.SystemException ; +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.COMM_FAILURE ; +import org.omg.CORBA.ORB ; +import org.omg.CORBA.Any ; + +import com.sun.corba.ee.impl.misc.ORBUtility ; + +public class InterceptorTester extends LocalObject implements + ORBInitializer, ClientRequestInterceptor { + + public static InterceptorTester theTester = null ; + public static boolean verbose = false ; + + private int errors = 0 ; + private boolean exceptionExpected = false ; + + public InterceptorTester() { + theTester = this ; + } + + public void clear() { + errors = 0 ; + exceptionExpected = false ; + } + + public int getErrors() { + return errors ; + } + + public void setExceptionExpected() { + exceptionExpected = true ; + } + + private void msg( String msg ) { + if (verbose) { + System.out.println( "+++InterceptorTester: " + msg ) ; + } + } + + private void error( String msg ) { + msg( "ERROR: " + msg ) ; + errors++ ; + } + + public void pre_init( ORBInitInfo info ) { + } + + public void post_init( ORBInitInfo info ) { + try { + info.add_client_request_interceptor( this ) ; + } catch (DuplicateName exc) { + INTERNAL internal = new INTERNAL() ; + internal.initCause( exc ) ; + throw internal ; + } + } + + public String name() { + return "ClientInterceptor" ; + } + + public void destroy() { + } + + public void send_request( ClientRequestInfo ri ) throws ForwardRequest { + msg( "send_request called" ) ; + } + + public void send_poll( ClientRequestInfo ri ) { + error( "send_poll should not be called" ) ; + } + + public void receive_reply( ClientRequestInfo ri ) { + if (exceptionExpected) { + error( "normal completion when exception expected!" ) ; + } else { + msg( "normal completion" ) ; + } + } + + public void receive_exception( ClientRequestInfo ri ) throws ForwardRequest { + if (!exceptionExpected) { + error( "exception when normal completion expected!" ) ; + } else { + msg( "expected exception" ) ; + } + + Any exception = ri.received_exception() ; + SystemException sysex = ORBUtility.extractSystemException( exception ) ; + + if (!(sysex instanceof COMM_FAILURE)) { + error( "Expected COMM_FAILURE, got " + sysex ) ; + } else { + msg( "expected COMM_FAILURE" ) ; + } + + sysex.printStackTrace() ; + } + + public void receive_other( ClientRequestInfo ri ) throws ForwardRequest { + error( "receive_other should not be called" ) ; + } +} diff --git a/test/src/share/classes/corba/simpledynamic/NewAcceptor.java b/test/src/share/classes/corba/simpledynamic/NewAcceptor.java new file mode 100644 index 000000000..7c9f0cc3f --- /dev/null +++ b/test/src/share/classes/corba/simpledynamic/NewAcceptor.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.simpledynamic; + +import corba.framework.*; + +public class NewAcceptor extends CORBATest +{ + @Override + protected void doTest() throws Throwable + { + Controller client = createClient( "corba.simpledynamic.NewAcceptorClient" ) ; + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + } +} diff --git a/test/src/share/classes/corba/simpledynamic/NewAcceptorClient.java b/test/src/share/classes/corba/simpledynamic/NewAcceptorClient.java new file mode 100644 index 000000000..fa4ef808a --- /dev/null +++ b/test/src/share/classes/corba/simpledynamic/NewAcceptorClient.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package corba.simpledynamic; + +import java.net.Socket; +import java.util.Properties; +import java.rmi.RemoteException ; + +import com.sun.corba.ee.spi.orb.ORB; +import com.sun.corba.ee.spi.misc.ORBConstants; +import com.sun.corba.ee.spi.transport.Acceptor; +import com.sun.corba.ee.spi.transport.TransportDefault; +import org.glassfish.pfl.basic.func.UnaryVoidFunction; + +import org.testng.Assert ; +import org.testng.annotations.Test ; + +public class NewAcceptorClient extends Framework { + private static final int SERVER_PORT = Integer.parseInt( PORT_NUM ) ; + + // Make sure that the ORB does not create any default acceptors. + @Override + protected void setServerPort( Properties props ) { + super.setServerPort( props ) ; + props.setProperty( ORBConstants.NO_DEFAULT_ACCEPTORS, "true" ) ; + props.setProperty( ORBConstants.ORB_SERVER_ID_PROPERTY, "1" ) ; + } + + // Can be overridden if necessary to allow the ORB to be further + // configured before it is used. + @Override + protected void updateORB( ORB orb, boolean isServer ) { + final Acceptor listener = TransportDefault.makeLazyCorbaAcceptor(orb, + SERVER_PORT, "localhost", "IIOP_CLEAR_TEXT" ) ; + + UnaryVoidFunction func = new UnaryVoidFunction() { + public void evaluate( Socket sock ) { + msg( "Processing message on socket " + sock ) ; + listener.processSocket( sock ) ; + } + } ; + + final Acceptor processor = TransportDefault.makeAcceptOnlyCorbaAcceptor( + orb, SERVER_PORT, "localhost", "IIOP_CLEAR_TEXT", func ) ; + + orb.getTransportManager().registerAcceptor( listener ) ; + orb.getTransportManager().registerAcceptor( processor ) ; + // Called for side-effect of initializing IORTemplate and transport + orb.getFVDCodeBaseIOR() ; + } + + private Echo makeServant( String name ) { + try { + return new EchoImpl( name ) ; + } catch (RemoteException rex) { + Assert.fail( "Unexpected remote exception " + rex ) ; + return null ; // never reached + } + } + + private void msg( String msg ) { + System.out.println( "NewAcceptorClient: " + msg ) ; + } + + private static final int ITERATIONS = 10 ; + + @Test + public void testNewAcceptor() throws RemoteException { + final Echo servant = makeServant( "acceptorTest" ) ; + bindServant( servant, Echo.class, "AcceptorTest" ) ; + Echo clientRef = findStub( Echo.class, "AcceptorTest" ) ; + + String data = "This is my test string" ; + + for (int ctr=0; ctr +// + +// Fixed 4670827: INS does not recognize IPV6 URLs +// Warning: This test can only be run on Jano. The address is hard coded, will +// be made general test when time permits. This is only for SQE to test. +// -test hopper.h4670827.INSTest + +// Fixed 4486041: ORB.init() could provide better failure diagnostics +-test hopper.h4486041.ORBInitErrorTest + +// Fixed 4549085: ORB locked into Latin-1 char set for request messages +-test hopper.h4549085.LockedCodeSetTest +// Fixed 4515953: RMIC doesn't compile Interfaces whose method has IDLEntity as +// return values or parameters +// Commented out temporarily. For now, run the stand alone test case attached +// in the bug traq +//-test hopper.h4515953.RMICIDLEntityTest +// Not required to be run as part of Hopper, it is a fix for the package rename. +//-test hopper.h4645953.ValidateIdlModules + +// Fixed 4647746: POA does not work when ORB.init is called for an Applet +-test hopper.h4647746.POAAppletTest + +// Fixed 4655388: POA.the_children() method throws ClassCastException +-test hopper.h4655388.POAHierarchyTest + +// Fixed 4620926: ServantActivator.incarnate() being invoked more than once +-test hopper.h4620926.ConcurrentServantActivatorTest + +// Fixed 4661596: Bad TypeCode from org.omg.CORBA.WStringValueHelper +-test hopper.h4661596.WStringValueHelperTest + +// End of file. diff --git a/test/src/share/classes/hopper/h4486041/Client.java b/test/src/share/classes/hopper/h4486041/Client.java new file mode 100644 index 000000000..6455e042c --- /dev/null +++ b/test/src/share/classes/hopper/h4486041/Client.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4486041; + +import org.omg.CORBA.ORB; +import java.util.Properties; + +public class Client +{ + public static final String ORBClassKey = + "org.omg.CORBA.ORBClass"; + + public static final String ORBSingletonClassKey = + "org.omg.CORBA.ORBSingletonClass"; + + public static int numberOfErrors = 0; + + public static void main(String[] av) + { + try { + + Properties properties = new Properties(); + + // -------------------------------------- + + properties.put(ORBClassKey, "NotFound"); + expectException("NotFound", av, properties, + ClassNotFoundException.class, false, false); + + // -------------------------------------- + + properties.put(ORBClassKey, "hopper.h4486041.TestORB"); + expectNormal("TestORB Good", av, properties, false); + + // -------------------------------------- + + properties.put(TestORB.ThrowError, "dummy"); + expectException("TestORB ORBInitException", av, properties, + ORBInitException.class, true, false); + + // -------------------------------------- + + System.getProperties().put(ORBSingletonClassKey, + "hopper.h4486041.TestORB"); + expectNormal("TestORB Singleton Good", null, null, true); + + // -------------------------------------- + + /* NOTE: + * set_parameters is not called for singletons so + * this test will not work. + System.getProperties().put(TestORB.ThrowError, "dummy"); + expectException("TestORB Singleton ORBInitException", null, null, + ORBInitException.class, true, true); + */ + + // -------------------------------------- + + if (numberOfErrors > 0) { + throw new Throwable("Test found errors."); + } + + } catch (Throwable t) { + t.printStackTrace(System.out); + System.exit(1); + } + } + + // + // isSetParameters: if the exception happens during set_parameters + // then the exception is not in INITIALIZE from create_impl. + // It is directly from set_parameters. + // + public static void expectException(String message, + String[] av, + Properties properties, + Class expectedException, + boolean isSetParameters, + boolean isSingleton) + { + System.out.println(); + System.out.println("------------------------------------------------"); + System.out.println("Begin expectException: " + message); + try { + if (isSingleton) { + ORB orb = ORB.init(); + } else { + ORB orb = ORB.init(av, properties); + } + System.out.println("\tERROR: Should not see this."); + System.out.println("\t\tExpected exception: " + expectedException); + numberOfErrors++; + } catch (Throwable t) { + Throwable cause; + if (isSetParameters) { + cause = t; + } else { + cause = t.getCause(); + } + System.out.println("\tExpected cause: " + expectedException); + System.out.println("\tCause: " + cause); + if (cause == null || + (! cause.getClass().equals(expectedException))) + { + numberOfErrors++; + System.out.println("\tERROR: Wrong cause."); + } else { + System.out.println("\tOK"); + } + + } + System.out.println("End expectException: " + message); + System.out.println("------------------------------------------------"); + } + + public static void expectNormal(String message, + String[] av, + Properties properties, + boolean isSingleton) + { + System.out.println(); + System.out.println("------------------------------------------------"); + System.out.println("Begin expectNormal: " + message); + try { + if (isSingleton) { + ORB orb = ORB.init(); + } else { + ORB orb = ORB.init(av, properties); + } + System.out.println("\tOK"); + } catch (Throwable t) { + numberOfErrors++; + System.out.println("\tERROR: Should not see this"); + System.out.println("\t\tUnexpected exception: "+ t); + } + System.out.println("End expectNormal: " + message); + System.out.println("------------------------------------------------"); + } +} + +// End of file. diff --git a/test/src/share/classes/hopper/h4486041/ORBInitErrorTest.java b/test/src/share/classes/hopper/h4486041/ORBInitErrorTest.java new file mode 100644 index 000000000..82e2b0fc6 --- /dev/null +++ b/test/src/share/classes/hopper/h4486041/ORBInitErrorTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4486041; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.CORBA.*; + +public class ORBInitErrorTest + extends + CORBATest +{ + protected void doTest() + throws + Throwable + { + // The test does not use the ORBD. However, when I did not + // create and start it then the generated output test directory + // was not created so the client failed when the framework was + // creating its output files. + Controller orbd = createORBD(); + orbd.start(); + + + Controller client = createClient("hopper.h4486041.Client"); + client.start(); + client.waitFor(120000); + client.stop(); + orbd.stop(); + } +} + +// End of file. + + diff --git a/test/src/share/classes/hopper/h4486041/ORBInitException.java b/test/src/share/classes/hopper/h4486041/ORBInitException.java new file mode 100644 index 000000000..11b99324f --- /dev/null +++ b/test/src/share/classes/hopper/h4486041/ORBInitException.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4486041; + +public class ORBInitException + extends + RuntimeException +{ + public ORBInitException(String reason) + { + super(reason); + } +} + +// End of file. diff --git a/test/src/share/classes/hopper/h4486041/TestORB.java b/test/src/share/classes/hopper/h4486041/TestORB.java new file mode 100644 index 000000000..f3d4b1199 --- /dev/null +++ b/test/src/share/classes/hopper/h4486041/TestORB.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4486041; + +import org.omg.CORBA.*; +import org.omg.CORBA.portable.*; +import org.omg.CORBA.ORBPackage.InvalidName; +import java.util.Properties; +import java.applet.Applet; + +public class TestORB + extends + ORB +{ + public static final String ThrowError = "ThrowError"; + + protected void set_parameters(String[] args, Properties props) + { + System.out.println("\tTestORB.set_parameters - Enter"); + if (props.get(ThrowError) != null) { + System.out.println("\tTestORB.set_parameters - Exception Exit"); + throw new ORBInitException("You asked for it."); + } + System.out.println("\tTestORB.set_parameters - Normal Exit"); + } + protected void set_parameters(Applet app, Properties props) + { + } + public String[] list_initial_services() + { + return null; + } + public org.omg.CORBA.Object resolve_initial_references(String object_name) + throws InvalidName + { + return null; + } + public String object_to_string(org.omg.CORBA.Object obj) + { + return null; + } + public org.omg.CORBA.Object string_to_object(String str) + { + return null; + } + public NVList create_list(int count) + { + return null; + } + public NamedValue create_named_value(String s, Any any, int flags) + { + return null; + } + public ExceptionList create_exception_list() + { + return null; + } + public ContextList create_context_list() + { + return null; + } + public Context get_default_context() + { + return null; + } + public Environment create_environment() + { + return null; + } + public org.omg.CORBA.portable.OutputStream create_output_stream() + { + return null; + } + public void send_multiple_requests_oneway(Request[] req) + { + } + public void send_multiple_requests_deferred(Request[] req) + { + } + public boolean poll_next_response() + { + return false; + } + public Request get_next_response() throws WrongTransaction + { + return null; + } + public TypeCode get_primitive_tc(TCKind tcKind) + { + return null; + } + public TypeCode create_struct_tc(String id, String name, + StructMember[] members) + { + return null; + } + public TypeCode create_union_tc(String id, String name, + TypeCode discriminator_type, + UnionMember[] members) + { + return null; + } + public TypeCode create_enum_tc(String id, String name, String[] members) + { + return null; + } + public TypeCode create_alias_tc(String id, String name, + TypeCode original_type) + { + return null; + } + public TypeCode create_exception_tc(String id, String name, + StructMember[] members) + { + return null; + } + public TypeCode create_interface_tc(String id, String name) + { + return null; + } + public TypeCode create_string_tc(int bound) + { + return null; + } + public TypeCode create_wstring_tc(int bound) + { + return null; + } + public TypeCode create_sequence_tc(int bound, TypeCode element_type) + { + return null; + } + public TypeCode create_recursive_sequence_tc(int bound, int offset) + { + return null; + } + public TypeCode create_array_tc(int length, TypeCode element_type) + { + return null; + } + public Any create_any() + { + return null; + } +} + +// End of file. + diff --git a/test/src/share/classes/hopper/h4515953/Processor.java b/test/src/share/classes/hopper/h4515953/Processor.java new file mode 100644 index 000000000..422ed05c6 --- /dev/null +++ b/test/src/share/classes/hopper/h4515953/Processor.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4515953; + +import java.rmi.*; +import org.omg.CORBA.portable.IDLEntity; + +public interface Processor extends Remote { + + // Fails since the import statement specifies + // the original portable InputStream + public IDLEntity testIDLEntity(IDLEntity input) throws RemoteException; + + // Works since a local 2.3 InputStream is defined + public TestInterface testInterface(TestInterface input) throws RemoteException; +} diff --git a/test/src/share/classes/hopper/h4515953/ProcessorImpl.java b/test/src/share/classes/hopper/h4515953/ProcessorImpl.java new file mode 100644 index 000000000..08c985912 --- /dev/null +++ b/test/src/share/classes/hopper/h4515953/ProcessorImpl.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4515953; + +import java.rmi.*; +import javax.rmi.PortableRemoteObject; +import org.omg.CORBA.portable.IDLEntity; + +public class ProcessorImpl extends PortableRemoteObject implements Processor { + + public ProcessorImpl() throws RemoteException {} + + // Fails since the import statement specifies + // the original portable InputStream + public IDLEntity testIDLEntity(IDLEntity input) { return input; } + + // Works since a local 2.3 InputStream is defined + public TestInterface testInterface(TestInterface input) { return input; } +} diff --git a/test/src/share/classes/hopper/h4515953/RMICIDLEntityTest.java b/test/src/share/classes/hopper/h4515953/RMICIDLEntityTest.java new file mode 100644 index 000000000..58969ff80 --- /dev/null +++ b/test/src/share/classes/hopper/h4515953/RMICIDLEntityTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4515953; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.CORBA.*; + +/** + * A very simple test to make sure that RMIC compilation works for Interfaces + * which has methods with IDLEntity as parameters or return values. + */ +public class RMICIDLEntityTest extends CORBATest +{ + public static final String[] javaFiles = { "Processor.java", + "ProcessorImpl.java" }; + + public static final String[] rmiClasses = { "hopper/h4515953/Processor.class" }; + + + protected void doTest() throws Throwable + { + Options.setJavaFiles(javaFiles); + compileJavaFiles(); + + Options.setRMICClasses( rmiClasses ); + compileRMICFiles(); + + } +} + diff --git a/test/src/share/classes/hopper/h4515953/TestInterface.java b/test/src/share/classes/hopper/h4515953/TestInterface.java new file mode 100644 index 000000000..dcf1e0626 --- /dev/null +++ b/test/src/share/classes/hopper/h4515953/TestInterface.java @@ -0,0 +1,13 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4515953; + +public interface TestInterface extends java.io.Serializable {} diff --git a/test/src/share/classes/hopper/h4549085/Client.java b/test/src/share/classes/hopper/h4549085/Client.java new file mode 100644 index 000000000..be3070076 --- /dev/null +++ b/test/src/share/classes/hopper/h4549085/Client.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4549085; + +import org.omg.PortableServer.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.*; + +public class Client +{ + public static void testMultibyteString(Tester tester) + throws Exception + { + System.out.println("Testing multibyte string..."); + + String multibyte = "\u3044Test of multibyte \u3044 string.\u3044"; + + String result = tester.process(multibyte); + + if (!multibyte.equals(result)) + throw new Exception("Not equal: " + result); + + System.out.println("PASSED"); + } + + public static void main(String args[]) + { + try { + ORB orb = ORB.init(args, System.getProperties()); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference in Naming + NameComponent nc = new NameComponent("Tester", ""); + NameComponent path[] = {nc}; + Tester tester = TesterHelper.narrow(ncRef.resolve(path)); + + Client.testMultibyteString(tester); + + orb.shutdown(true); + + } catch (Throwable t) { + t.printStackTrace(); + System.exit (1); + } + } +} diff --git a/test/src/share/classes/hopper/h4549085/LockedCodeSetTest.java b/test/src/share/classes/hopper/h4549085/LockedCodeSetTest.java new file mode 100644 index 000000000..7519a3938 --- /dev/null +++ b/test/src/share/classes/hopper/h4549085/LockedCodeSetTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4549085; + +import test.Test; +import corba.framework.*; +import java.util.*; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.CORBA.*; + +/** + * Simple tests in GIOP 1.1 and 1.2 of chars and wstrings. + */ +public class LockedCodeSetTest extends CORBATest +{ + public static final String[] idlFiles = { "Tester.idl" }; + + public static final String[] javaFiles = { "Server.java", + "Client.java" }; + + + protected void doTest() throws Throwable + { + Options.addIDLCompilerArgs("-fall"); + Options.setIDLFiles(idlFiles); + Options.setJavaFiles(javaFiles); + compileIDLFiles(); + compileJavaFiles(); + + Controller orbd = createORBD(); + + // Make the server only advertise UTF-8 for char, forcing the + // client to select it. The server will still use ISO8859-1 to + // unmarshal the operation name, but should be able to handle + // multibyte chars after the service context is unmarshaled. + Properties serverProps = Options.getServerProperties(); + + serverProps.setProperty(ORBConstants.CHAR_CODESETS, + "83951617,83951617"); + + Controller server = createServer("hopper.h4549085.Server"); + Controller client = createClient("hopper.h4549085.Client"); + + orbd.start(); + server.start(); + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + client.stop(); + server.stop(); + orbd.stop(); + } +} + diff --git a/test/src/share/classes/hopper/h4549085/Server.java b/test/src/share/classes/hopper/h4549085/Server.java new file mode 100644 index 000000000..694e09768 --- /dev/null +++ b/test/src/share/classes/hopper/h4549085/Server.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4549085; + +import org.omg.PortableServer.*; +import org.omg.CORBA.*; +import org.omg.CosNaming.*; + +public class Server extends TesterPOA +{ + public String process(String input) { + return input; + } + + public static void main(String args[]) { + try { + ORB orb = ORB.init(args, System.getProperties()); + + // Get rootPOA + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + // create servant and register it with the ORB + Server server = new Server(); + + byte[] id = rootPOA.activate_object(server); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc = new NameComponent("Tester", ""); + NameComponent path[] = {nc}; + + org.omg.CORBA.Object ref = rootPOA.id_to_reference(id); + + ncRef.rebind(path, ref); + + // Emit the handshake the test framework expects + // (can be changed in Options by the running test) + System.out.println ("Server is ready."); + + // Wait for clients + orb.run(); + + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); + } + } +} + diff --git a/test/src/share/classes/hopper/h4549085/Tester.idl b/test/src/share/classes/hopper/h4549085/Tester.idl new file mode 100644 index 000000000..9826d89ac --- /dev/null +++ b/test/src/share/classes/hopper/h4549085/Tester.idl @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module hopper { + module h4549085 { + interface Tester { + string process(in string input); + }; + }; +}; + + + diff --git a/test/src/share/classes/hopper/h4620926/Client.java b/test/src/share/classes/hopper/h4620926/Client.java new file mode 100644 index 000000000..624b92323 --- /dev/null +++ b/test/src/share/classes/hopper/h4620926/Client.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4620926; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import java.util.*; +import test.*; + +public class Client extends Thread { + private static int numErrors = 0; + + private static synchronized void errorOccurred( int clientNo, + Exception exc) + { + numErrors++ ; + System.out.println( + "\nError in ClientNo " + clientNo + ": " + exc ); + + System.err.println( + "\nError in ClientNo " + clientNo + ": " + exc ); + + exc.printStackTrace(); + } + + private static int counter = 0; + private int clientNo = 0; + Hello ref = null; + + public Client(ORB orb) throws Exception { + counter++; + clientNo = counter; + System.out.println("Creating client - " + clientNo); + NamingContext namingContext = NamingContextHelper.narrow( + orb.resolve_initial_references("NameService")); + NameComponent[] name = { new NameComponent("Hello", "") }; + ref = HelloHelper.narrow(namingContext.resolve(name)); + } + + public void run() { + for (int i = 0; i < 3; i++) { + try { + System.out.println("Client - " + clientNo + " : " + + ref.sayHello()); + Thread.sleep(2000); + } catch (Exception e) { + errorOccurred(clientNo, e) ; + System.exit( 1 ); + } + } + System.out.println( "TEST PASSED" ); + System.out.flush( ); + } + + public static void main(String[] args) { + Client[] c = null; + int noOfThreads = 5; + + // try { + // noOfThreads = Integer.parseInt(args[0]); + // } catch (NumberFormatException e) { } + + try { + c = new Client[noOfThreads]; + for (int i = 0; i < noOfThreads; i++) { + ORB orb = ORB.init(args, null); + c[i] = new Client(orb); + } + + for (int i = 0; i < noOfThreads; i++) { + c[i].start(); + } + + for (int i = 0; i < noOfThreads; i++) { + c[i].join(); + } + } catch (Exception e) { + errorOccurred( -1, e ); + } + + System.exit( numErrors>0 ? 1 : 0 ) ; + } +} diff --git a/test/src/share/classes/hopper/h4620926/ConcurrentServantActivatorTest.java b/test/src/share/classes/hopper/h4620926/ConcurrentServantActivatorTest.java new file mode 100644 index 000000000..6637e8ac2 --- /dev/null +++ b/test/src/share/classes/hopper/h4620926/ConcurrentServantActivatorTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4620926; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + */ +public class ConcurrentServantActivatorTest extends CORBATest +{ + public static String[] idlFiles = { "Hello.idl" } ; + + // Define the .java files that need to be compiled. Any + // java files generated by compiling IDL will automatically be + // compiled with these. + public static String[] javaFiles = { "Client.java", "Server.java" }; + + // This is the main method defining the test. All tests + // should have this. + protected void doTest() throws Throwable + { + Options.addIDLCompilerArgs( "-fall" ) ; + Options.setIDLFiles( idlFiles ) ; + Options.setJavaFiles(javaFiles); + + // Run the compilers. + compileIDLFiles() ; + compileJavaFiles(); + + Controller orbd = createORBD() ; + orbd.start() ; + + Controller server = createServer( "hopper.h4620926.Server" ) ; + server.start() ; + + Controller client = createClient("hopper.h4620926.Client"); + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + server.stop() ; + orbd.stop() ; + } +} + diff --git a/test/src/share/classes/hopper/h4620926/Hello.idl b/test/src/share/classes/hopper/h4620926/Hello.idl new file mode 100644 index 000000000..e1fbad4a1 --- /dev/null +++ b/test/src/share/classes/hopper/h4620926/Hello.idl @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module test { +interface Hello { + string sayHello(); +}; +}; + diff --git a/test/src/share/classes/hopper/h4620926/Server.java b/test/src/share/classes/hopper/h4620926/Server.java new file mode 100644 index 000000000..7ad39ec68 --- /dev/null +++ b/test/src/share/classes/hopper/h4620926/Server.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4620926; + +import org.omg.CORBA.*; +import org.omg.PortableServer.*; +import org.omg.CosNaming.*; +import test.*; +import java.util.Properties ; + +class HelloServant extends HelloPOA { + public String sayHello() { + return "Hello"; + } +} + +public class Server { + + public static int delay = 100; + + public static void main(String[] args) { + + try { + + // try { + // delay = Integer.parseInt(args[0]); + // } catch (Exception e) { } + + Properties props = new Properties() ; + props.setProperty( "com.sun.corba.ee.ORBDebug", "poa" ) ; + ORB orb = ORB.init(args, props); + + POA rootPOA = POAHelper.narrow( + orb.resolve_initial_references("RootPOA")); + Policy[] policy = new Policy[2]; + policy[0] = rootPOA.create_request_processing_policy( + RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + policy[1] = rootPOA.create_id_assignment_policy( + IdAssignmentPolicyValue.USER_ID); + + POA childPOA = rootPOA.create_POA("Child", null, policy); + childPOA.set_servant_manager(new MyServantActivator()); + System.out.println("Set servant manager"); + + String str = "ABCRef"; + org.omg.CORBA.Object obj = childPOA.create_reference_with_id( + str.getBytes(), "IDL:test/Hello:1.0"); + childPOA.the_POAManager().activate(); + + Hello ref = HelloHelper.narrow(obj); + NamingContext namingContext = NamingContextHelper.narrow( + orb.resolve_initial_references("NameService")); + NameComponent[] name = { new NameComponent("Hello", "") }; + + namingContext.rebind(name, ref); + System.out.println("Servant registered"); + + System.out.println("Server is ready."); + + orb.run(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} + +class MyServantActivator extends LocalObject implements ServantActivator { + + public Servant incarnate(byte[] oid, POA adapter) { + + System.out.println("Incarnating Object - " + new String(oid) + + " in POA - " + adapter.the_name()); + try { + System.out.println("Sleeping for " + Server.delay + "msecs"); + Thread.sleep(Server.delay); + } catch (Exception e) { } + return new HelloServant(); + } + + public void etherealize(byte[] oid, POA adapter, Servant servant, + boolean cleanUpInProgress, + boolean remaingActivations) { + System.out.println("Etherealizing Object "); + } +} diff --git a/test/src/share/classes/hopper/h4645953/ValidateIdlModules.java b/test/src/share/classes/hopper/h4645953/ValidateIdlModules.java new file mode 100644 index 000000000..b7ef4c21f --- /dev/null +++ b/test/src/share/classes/hopper/h4645953/ValidateIdlModules.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4645953; + +import test.Test; +import corba.framework.*; + +/** + * A test to check that the IDL with module names starting with 'service' is + * compiled correctly. + */ + +public class ValidateIdlModules extends CORBATest +{ + public static final String[] idlFiles = { "service.idl" }; + + public static final String[] javaFiles = { "pi/serviceexample/*.java" }; + + protected void doTest() throws Throwable + { + Options.addIDLCompilerArgs("-fall" ); + Options.setIDLFiles( idlFiles ); + Options.setJavaFiles( javaFiles ); + + compileIDLFiles( ); + compileJavaFiles( ); + } +} diff --git a/test/src/share/classes/hopper/h4645953/service.idl b/test/src/share/classes/hopper/h4645953/service.idl new file mode 100644 index 000000000..daadde946 --- /dev/null +++ b/test/src/share/classes/hopper/h4645953/service.idl @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module pi { + module serviceexample { + interface test { + void aMethod( ); + }; + }; +}; diff --git a/test/src/share/classes/hopper/h4647746/Client.java b/test/src/share/classes/hopper/h4647746/Client.java new file mode 100644 index 000000000..185ddd61b --- /dev/null +++ b/test/src/share/classes/hopper/h4647746/Client.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4647746; + +import java.io.PrintStream ; + +import java.util.Properties ; +import java.util.LinkedList ; +import java.util.Iterator ; +import java.util.StringTokenizer ; +import java.util.Arrays ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.RequestProcessingPolicyValue ; + +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.InvalidPolicy ; +import org.omg.PortableServer.POAPackage.AdapterAlreadyExists ; + +import org.omg.PortableServer.portable.Delegate ; + +import org.omg.CORBA.portable.ObjectImpl ; + +import org.omg.CORBA.ORB ; +import org.omg.CORBA.Policy ; +import org.omg.CORBA.BAD_PARAM ; +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.OctetSeqHolder ; + +import org.omg.CORBA.ORBPackage.InvalidName ; + +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +public class Client +{ + private PrintStream out ; + private PrintStream err ; + private ORB orb ; + + public static void main(String args[]) + { + System.out.println( "Starting POA Applet initialization test" ) ; + try{ + Properties props = System.getProperties() ; + new Client( props, args, System.out, System.err ) ; + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } + + public Client( Properties props, String args[], PrintStream out, + PrintStream err ) + { + this.orb = ORB.init( args, props ) ; + this.out = System.out ; + this.err = System.err ; + + runTests() ; + } + +// ************************************************* +// *************** Utilities ******************* +// ************************************************* + + private void error( String msg ) + { + throw new RuntimeException( msg ) ; + } + + private void info( String msg ) + { + out.println( msg ) ; + } + + // ************************************************* +// *************** TESTS *********************** +// ************************************************* + + private void runTests() + { + java.applet.Applet applet = new java.applet.Applet() ; + java.applet.AppletStub dummy = new java.applet.AppletStub() { + public void appletResize( int width, int height ) + { + } + + public java.applet.AppletContext getAppletContext() + { + return null ; + } + + public java.net.URL getCodeBase() + { + return null ; + } + + public java.net.URL getDocumentBase() + { + return null ; + } + + public String getParameter( String name ) + { + return null ; + } + + public boolean isActive() + { + return false ; + } + } ; + applet.setStub( dummy ) ; + + ORB orb = ORB.init( applet, null ) ; + POA rpoa = null ; + try { + rpoa = (POA)(orb.resolve_initial_references( "RootPOA" )) ; + } catch (InvalidName err) { + error( err.toString() ) ; + } + + Policy[] policies = { rpoa.create_request_processing_policy( + RequestProcessingPolicyValue.USE_DEFAULT_SERVANT ) } ; + + POA cpoa = null ; + + try { + cpoa = rpoa.create_POA( "Child", rpoa.the_POAManager(), + policies ) ; + } catch (InvalidPolicy err) { + error( err.toString() ) ; + } catch (AdapterAlreadyExists err) { + error( err.toString() ) ; + } + + Servant servant = new Servant() { + public String[] _all_interfaces( POA poa, byte[] objectId ) + { + return null ; + } + } ; + + // This should set the delegate on servant + try { + cpoa.set_servant( servant ) ; + } catch (WrongPolicy err) { + error( err.toString() ) ; + } + + // Without the fix for bug 4647746, this fails because + // the delegate was not initialized in ORB.init in Applet + // mode. + Delegate delegate = servant._get_delegate() ; + } +} diff --git a/test/src/share/classes/hopper/h4647746/POAAppletTest.java b/test/src/share/classes/hopper/h4647746/POAAppletTest.java new file mode 100644 index 000000000..332058336 --- /dev/null +++ b/test/src/share/classes/hopper/h4647746/POAAppletTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4647746; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + */ +public class POAAppletTest extends CORBATest +{ + // Define the .java files that need to be compiled. Any + // java files generated by compiling IDL will automatically be + // compiled with these. + public static String[] javaFiles = { "Client.java" }; + + // This is the main method defining the test. All tests + // should have this. + protected void doTest() throws Throwable + { + // Tell the test about the IDL and Java files defined above. + Options.setJavaFiles(javaFiles); + + // Run the compilers. + compileJavaFiles(); + + // Create client controller using the given + // class. You can also specify names for these (for instance, + // you may want to distinguish between many clients) by using + // the equivalent methods that take two Strings. + Controller client = createClient("hopper.h4647746.Client"); + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + } +} + diff --git a/test/src/share/classes/hopper/h4655388/Client.java b/test/src/share/classes/hopper/h4655388/Client.java new file mode 100644 index 000000000..7d6b9c0f4 --- /dev/null +++ b/test/src/share/classes/hopper/h4655388/Client.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4655388; + +import java.io.PrintStream ; + +import java.util.Properties ; +import java.util.LinkedList ; +import java.util.Iterator ; +import java.util.StringTokenizer ; +import java.util.Arrays ; + +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.RequestProcessingPolicyValue ; + +import org.omg.PortableServer.POAPackage.WrongPolicy ; +import org.omg.PortableServer.POAPackage.InvalidPolicy ; +import org.omg.PortableServer.POAPackage.AdapterAlreadyExists ; + +import org.omg.PortableServer.portable.Delegate ; + +import org.omg.CORBA.portable.ObjectImpl ; + +import org.omg.CORBA.ORB ; +import org.omg.CORBA.Policy ; +import org.omg.CORBA.BAD_PARAM ; +import org.omg.CORBA.INTERNAL ; +import org.omg.CORBA.OctetSeqHolder ; + +import org.omg.CORBA.ORBPackage.InvalidName ; + +import org.omg.CORBA_2_3.portable.OutputStream ; +import org.omg.CORBA_2_3.portable.InputStream ; + +public class Client +{ + private PrintStream out ; + private PrintStream err ; + private ORB orb ; + + public static void main(String args[]) + { + System.out.println( "Starting POA hierarchy test" ) ; + try{ + Properties props = System.getProperties() ; + new Client( props, args, System.out, System.err ) ; + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit (1); + } + } + + public Client( Properties props, String args[], PrintStream out, + PrintStream err ) + { + this.orb = ORB.init( args, props ) ; + this.out = System.out ; + this.err = System.err ; + + runTests() ; + } + +// ************************************************* +// *************** Utilities ******************* +// ************************************************* + + private void error( String msg ) + { + throw new RuntimeException( msg ) ; + } + + private void info( String msg ) + { + out.println( msg ) ; + } + + // ************************************************* +// *************** TESTS *********************** +// ************************************************* + + private void runTests() + { + String[] args = null ; + ORB orb = ORB.init( args, null ) ; + POA rpoa = null ; + try { + rpoa = (POA)(orb.resolve_initial_references( "RootPOA" )) ; + } catch (InvalidName err) { + error( err.toString() ) ; + } + + Policy[] policies = { rpoa.create_request_processing_policy( + RequestProcessingPolicyValue.USE_DEFAULT_SERVANT ) } ; + + POA cpoa = null ; + + try { + cpoa = rpoa.create_POA( "Child1", rpoa.the_POAManager(), + policies ) ; + } catch (InvalidPolicy err) { + error( err.toString() ) ; + } catch (AdapterAlreadyExists err) { + error( err.toString() ) ; + } + + try { + cpoa = rpoa.create_POA( "Child2", rpoa.the_POAManager(), + policies ) ; + } catch (InvalidPolicy err) { + error( err.toString() ) ; + } catch (AdapterAlreadyExists err) { + error( err.toString() ) ; + } + + // Without the fix for bug 4655388, this call fails with a + // ClassCastException. + POA[] children = rpoa.the_children() ; + + if (children.length != 2) + error( "Should have exactly 2 children" ) ; + + if (!children[0].the_name().equals( "Child1" )) + if (!children[0].the_name().equals( "Child2" )) + error( "children[0] is incorrect" ) ; + + if (!children[1].the_name().equals( "Child1" )) + if (!children[1].the_name().equals( "Child2" )) + error( "children[1] is incorrect" ) ; + + if (children[0].the_name().equals( children[1].the_name() )) + error( "Both children have the same name" ) ; + } +} diff --git a/test/src/share/classes/hopper/h4655388/POAHierarchyTest.java b/test/src/share/classes/hopper/h4655388/POAHierarchyTest.java new file mode 100644 index 000000000..3fcbb47a9 --- /dev/null +++ b/test/src/share/classes/hopper/h4655388/POAHierarchyTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4655388; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + */ +public class POAHierarchyTest extends CORBATest +{ + // Define the .java files that need to be compiled. Any + // java files generated by compiling IDL will automatically be + // compiled with these. + public static String[] javaFiles = { "Client.java" }; + + // This is the main method defining the test. All tests + // should have this. + protected void doTest() throws Throwable + { + // Tell the test about the IDL and Java files defined above. + Options.setJavaFiles(javaFiles); + + // Run the compilers. + compileJavaFiles(); + + // Create client controller using the given + // class. You can also specify names for these (for instance, + // you may want to distinguish between many clients) by using + // the equivalent methods that take two Strings. + Controller client = createClient("hopper.h4655388.Client"); + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + } +} + diff --git a/test/src/share/classes/hopper/h4661596/WStringValueHelperTest.java b/test/src/share/classes/hopper/h4661596/WStringValueHelperTest.java new file mode 100644 index 000000000..7bcd5d218 --- /dev/null +++ b/test/src/share/classes/hopper/h4661596/WStringValueHelperTest.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4661596; + +import corba.framework.CORBATest; +import java.util.*; +import org.omg.CORBA.TCKind; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.WStringValueHelper; + +/** + * Checks to make sure WStringValueHelper.type() returns + * a TypeCode reflecting a boxed wstring. + * + * Since we can't get the WStringValueHelper from rip-int + * without Xbootclasspath, this will only run on 1.4.1 or + * greater workspaces. + */ +public class WStringValueHelperTest extends CORBATest +{ + public static final String INDENT = " "; + + // The actual test: + + public void checkWStringValueHelper() throws Exception { + System.out.print(INDENT + + " Checking WStringValueHelper from JDK..."); + + TypeCode tc = WStringValueHelper.type(); + + while (tc.kind().equals(TCKind.tk_alias)) + tc = tc.content_type(); + + if (!tc.kind().equals(TCKind.tk_value_box) || + !tc.content_type().kind().equals(TCKind.tk_wstring)) { + Exception exc = new Exception("Bad TypeCode from WStringValueHelper: " + + " kind: " + + tc.content_type().kind().value()); + throw exc ; + } + + System.out.println("PASSED"); + } + + + // This has nothing to do with the logic of the + // test. It is only to allow us to only run this on + // hopper or greater JDKs. + public boolean jdkIsHopperOrGreater() throws Exception { + + // Should probably use Merlin's new perl-like + // feature. + + try { + + String version + = System.getProperty("java.version"); + + System.out.println(INDENT + + " JDK version: " + version); + + StringTokenizer stok + = new StringTokenizer(version, ". -_b", false); + + int major = Integer.parseInt(stok.nextToken()); + if (major > 1) + return true; + + if (!stok.hasMoreTokens()) + return false; + + int dot1 = Integer.parseInt(stok.nextToken()); + if (dot1 > 4) + return true; + + if (!stok.hasMoreTokens()) + return false; + + int dot2 = Integer.parseInt(stok.nextToken()); + if (dot2 == 0) + return false; + + return true; + + } catch (NoSuchElementException nsee) { + throw new Exception("Error determining version: " + + nsee); + } catch (NumberFormatException nfe) { + throw new Exception("Error determining version: " + + nfe); + } + } + + protected void doTest() throws Throwable { + System.out.println(); + + System.out.println(INDENT + + "Verifying JDK is Hopper or greater..."); + try { + if (!jdkIsHopperOrGreater()) { + System.out.println(INDENT + + "* WARNING: " + + " This test can only be run on Hopper or greater JDKs. Skipping test."); + return; + } + + } catch (Exception ex) { + System.out.println(INDENT + + "* Error determing JDK version. Can only run on Hopper or greater JDKs. Skipping test. Error was: " + ex); + return; + } + + checkWStringValueHelper(); + } +} diff --git a/test/src/share/classes/hopper/h4670827/Client.java b/test/src/share/classes/hopper/h4670827/Client.java new file mode 100644 index 000000000..992b7535b --- /dev/null +++ b/test/src/share/classes/hopper/h4670827/Client.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4670827; + +import org.glassfish.pfl.test.JUnitReportHelper; +import org.omg.CORBA.ORB; + +public class Client implements Runnable { + private JUnitReportHelper helper ; + private boolean failed = false ; + + public static void main(String args[]) { + new Client().run(); + } + + private ORB orb; + + public void run() { + helper = new JUnitReportHelper( Client.class.getName() ) ; + orb = ORB.init( (String[]) null, null ); + + for (Object[] arr : TestConstants.data) { + String name = (String)arr[0] ; + String url = (String)arr[1] ; + boolean shouldSucceed = (Boolean)arr[2] ; + helper.start( name ) ; + try { + if (testURL( url, shouldSucceed )) { + System.out.println( "Passed test " + name ) ; + helper.pass() ; + } else { + System.out.println( "Test " + name + " failed" ) ; + helper.fail( "failed" ) ; + failed = true ; + } + } catch (Exception exc) { + helper.fail( exc ) ; + failed = true ; + } + } + + System.out.println("Thread "+ Thread.currentThread()+" done."); + if (failed) + System.exit(1) ; + } + + private boolean testURL ( String url, boolean shouldPass ) { + if (shouldPass) { + org.omg.CORBA.Object obj = orb.string_to_object( url ); + if( obj == null ) { + System.err.println( url + " lookup failed.." ); + return false; + } + Hello helloRef = HelloHelper.narrow( obj ); + String returnString = helloRef.sayHello( ); + if( !returnString.equals( TestConstants.returnString ) ) { + System.err.println( " hello.sayHello() did not return.." + + TestConstants.returnString ); + System.err.flush( ); + return false; + } + } else { + try { + org.omg.CORBA.Object obj = orb.string_to_object( url ); + Hello helloRef = HelloHelper.narrow( obj ); + String returnString = helloRef.sayHello( ); + // Shouldn't be here + return false; + } catch( Exception e ) { + System.out.println( "Caught Exception " + e + " as expected " ); + } + } + + // If we are here then we passed the test + return true; + } +} diff --git a/test/src/share/classes/hopper/h4670827/HelloImpl.java b/test/src/share/classes/hopper/h4670827/HelloImpl.java new file mode 100644 index 000000000..3477e914f --- /dev/null +++ b/test/src/share/classes/hopper/h4670827/HelloImpl.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4670827; + +public class HelloImpl extends _HelloImplBase { + + public String sayHello( ) { + System.out.println( "Hello Called...." ); + return TestConstants.returnString; + } +} + diff --git a/test/src/share/classes/hopper/h4670827/INSServer.java b/test/src/share/classes/hopper/h4670827/INSServer.java new file mode 100644 index 000000000..184671ec7 --- /dev/null +++ b/test/src/share/classes/hopper/h4670827/INSServer.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4670827; + +import java.io.*; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; +import org.omg.CORBA.*; +import java.util.Properties; +import java.util.Hashtable; +import corba.framework.*; +import com.sun.corba.ee.spi.misc.ORBConstants; + +public class INSServer implements InternalProcess +{ + + public static void main(String args[]) { + try { + (new INSServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + try { + + //We need to set ORBInitialPort = PersistentServerPort to start this + //process as a Bootstrap server which can listen to INS Requests on + //an assigned port. + args = new String[2]; + args[0] = "-ORBInitialPort"; + args[1] = TestConstants.ORBInitialPort; + environment.put( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + TestConstants.ORBInitialPort ); + + + ORB orb = ORB.init(args, environment); + + HelloImpl helloRef = new HelloImpl( ); + orb.connect( helloRef ); + ((com.sun.corba.ee.spi.orb.ORB)orb).register_initial_reference( + TestConstants.INSServiceName, helloRef ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + orb.run( ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } +} + + + + + + diff --git a/test/src/share/classes/hopper/h4670827/INSTest.java b/test/src/share/classes/hopper/h4670827/INSTest.java new file mode 100644 index 000000000..21da89cde --- /dev/null +++ b/test/src/share/classes/hopper/h4670827/INSTest.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4670827; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + * This is a test for INS. + */ +public class INSTest extends CORBATest +{ + public static String[] idlFiles = { "hello.idl" }; + + // Define the .java files that need to be compiled. Any + // java files generated by compiling IDL will automatically be + // compiled with these. + public static String[] javaFiles = {"Client.java", + "HelloImpl.java", + "INSServer.java"}; + + // This is the main method defining the test. All tests + // should have this. + protected void doTest() throws Throwable + { + Options.addIDLCompilerArgs( "-fall -oldImplBase" ); + Options.setJavaFiles(javaFiles); + Options.setIDLFiles(idlFiles); + + compileIDLFiles(); + + compileJavaFiles(); + + Controller client = createClient("hopper.h4670827.Client"); + + Object serverExtras[] = new Object[3]; + + Hashtable serverExtra = Options.getServerExtra(); + serverExtra.put("client", client); + + Controller server + = createServer("hopper.h4670827.INSServer"); + + + // Server starts the client and does a waitFor + server.start(); + + Thread.sleep(10000); + + client.start(); + + Thread.sleep(10000); + + // Make sure all the processes are shut down. + server.stop(); + client.stop(); + } +} + diff --git a/test/src/share/classes/hopper/h4670827/TestConstants.java b/test/src/share/classes/hopper/h4670827/TestConstants.java new file mode 100644 index 000000000..70171af28 --- /dev/null +++ b/test/src/share/classes/hopper/h4670827/TestConstants.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package hopper.h4670827; + +public class TestConstants { + public static final String ORBInitialPort = "2089"; + + public static final String INSServiceName = "HelloService"; + + // Flavor 1: iiop version and port specified + public static final String corbalocURL1 = + "corbaloc:iiop:1.2@[::FFFF:10.5.32.14]:" + + ORBInitialPort + "/" + INSServiceName; + + // Flavor 2: iiop version not specified and port specified + public static final String corbalocURL2 = + "corbaloc:iiop:[::FFFF:10.5.32.14]:" + + ORBInitialPort + "/" + INSServiceName; + + // Flavor 3: iiop version specified and port not specified + public static final String corbalocURL3 = + "corbaloc:iiop:1.2@[::FFFF:10.5.32.14]:" + + ORBInitialPort + "/" + INSServiceName; + + // Flavor 4: iiop version not specified and port not specified + public static final String corbalocURL4 = + "corbaloc:iiop:[::FFFF:10.5.32.14]:" + + ORBInitialPort + "/" + INSServiceName; + + // Flavor 5: negative test no colon + public static final String corbalocURL5 = + "corbaloc:iiop:[::FFFF:10.5.32.14]" + + ORBInitialPort + "/" + INSServiceName; + + // Flavor 6: negative test no bracket and no colon + public static final String corbalocURL6 = + "corbaloc:iiop:[::FFFF:10.5.32.14" + + ORBInitialPort + "/" + INSServiceName; + public static final String returnString = "HELLO"; + + public static Object[][] data = new Object[][] { + { "testIIOPVersionAndPort", corbalocURL1, true }, + { "testIIOPNoVersionAndPort", corbalocURL2, true }, + { "testIIOPVersionAndNoPort", corbalocURL3, true }, + { "testIIOPNoVersionAndNoPort", corbalocURL4, true }, + { "testNoColon", corbalocURL5, false }, + { "testNoColonNoBracket", corbalocURL6, false }, + } ; +} diff --git a/test/src/share/classes/hopper/h4670827/hello.idl b/test/src/share/classes/hopper/h4670827/hello.idl new file mode 100644 index 000000000..fd3c08440 --- /dev/null +++ b/test/src/share/classes/hopper/h4670827/hello.idl @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module hopper { + module h4670827 { + interface Hello + { + string sayHello(); + }; + }; +}; diff --git a/test/src/share/classes/ibmspace/client/ActionSource.java b/test/src/share/classes/ibmspace/client/ActionSource.java new file mode 100644 index 000000000..986bcd7a6 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/ActionSource.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.client; + +import java.util.*; +import java.awt.event.*; + + +public class ActionSource +{ + protected Vector fActionListeners; + + public ActionSource() + { + fActionListeners = new Vector (); + } + + public void addActionListener (ActionListener listener) + { + if (!fActionListeners.contains (listener)) + fActionListeners.addElement (listener); + } + + public void removeActionListener (ActionListener listener) + { + fActionListeners.removeElement (listener); + } + + public void notifyListeners (Object source, String command) + { + ActionEvent event = new ActionEvent (source, ActionEvent.ACTION_PERFORMED, command); + + for (int i=0; i 0 ) { + fUX = fDX/fLen; + fUY = fDY/fLen; + } else { + fUX = 0; + fUY = 0; + } + + // Compute shortened to and from points + + int tx = fTail.x + (int)(fUX*fTailPadding); + int ty = fTail.y + (int)(fUY*fTailPadding); + int hx = fHead.x - (int)(fUX*fHeadPadding); + int hy = fHead.y - (int)(fUY*fHeadPadding); + fFrom = new Point (tx,ty); + fTo = new Point (hx,hy); + + // Compute arrow tip points + + int bx = fTo.x - (int)(fUX*fHeadLength); + int by = fTo.y - (int)(fUY*fHeadLength); + fTipX[0] = fTo.x; + fTipY[0] = fTo.y; + fTipX[1] = bx - (int)(fUY*fHeadSeparation); + fTipY[1] = by + (int)(fUX*fHeadSeparation); + fTipX[2] = bx; + fTipY[2] = by; + fTipX[3] = bx + (int)(fUY*fHeadSeparation); + fTipY[3] = by - (int)(fUX*fHeadSeparation); + + fLabelLoc = new Point ((fFrom.x+fTo.x)/2, (fFrom.y+fTo.y)/2); + + fCacheBlown = false; + } + } + + + + +} diff --git a/test/src/share/classes/ibmspace/client/BarControl.java b/test/src/share/classes/ibmspace/client/BarControl.java new file mode 100644 index 000000000..c64b4c601 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/BarControl.java @@ -0,0 +1,251 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Implements an unlabeled bar control that can be positioned +// either vertically or horizontally. Use LabeledBarControl +// to get this with a label. + + +package ibmspace.client; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; + +public class BarControl extends JComponent implements MouseMotionListener +{ + static final byte VERTICAL = 0; + static final byte HORIZONTAL = 1; + + // + // Data + // + + private double fPercentage; // between 0.0 and 1.0 + private Color fColor, fLightColor, fDarkColor; + private byte fOrientation; + private Dimension fSize = new Dimension (); + + private ActionSource fActionSource; + + + // + // Constructors + // + + public BarControl() + { + addMouseMotionListener (this); + fColor = Color.red; + fPercentage = 0.0; + fOrientation = HORIZONTAL; + fSize = super.getSize (); + fActionSource = new ActionSource (); + } + + public BarControl (byte orientation) + { + addMouseMotionListener (this); + fColor = Color.red; + fPercentage = 0.0; + fOrientation = orientation; + fSize = super.getSize (); + fActionSource = new ActionSource (); + } + + public BarControl(Color c) + { + addMouseMotionListener (this); + fColor = c; + fPercentage = 0.0; + fOrientation = HORIZONTAL; + fSize = super.getSize (); + fActionSource = new ActionSource (); + } + + public BarControl(Color c, byte orientation) + { + addMouseMotionListener (this); + fColor = c; + fPercentage = 0.0; + fOrientation = orientation; + fSize = super.getSize (); + fActionSource = new ActionSource (); + } + + public void addActionListener (ActionListener listener) + { + fActionSource.addActionListener (listener); + } + + public void removeActionListener (ActionListener listener) + { + fActionSource.removeActionListener (listener); + } + + + // + // Setters + // + + public void setColor (Color c) + { + fColor = c; + + int r = c.getRed (); + int g = c.getGreen (); + int b = c.getBlue (); + + fLightColor = new Color ((r+255)/2,(g+255)/2,(b+255)/2); + fDarkColor = new Color (r/2,g/2,b/2); + repaint (); + } + + public void setPercentage (double p) + { + fPercentage = p; + fActionSource.notifyListeners (this, "Percentage Changed"); + repaint (); + } + + // + // Getters + // + + public Color getColor () + { + return fColor; + } + + public double getPercentage () + { + return fPercentage; + } + + + // + // Painting + // + + public void paint (Graphics g) + { + update (g); + } + + + public double f (double value) + { + return Math.sqrt(value); + } + + public void update (Graphics g) + { + Insets insets = getInsets (); + Dimension size = getSize (); + int x = insets.left; + int y = insets.top; + int width = size.width - insets.left - insets.right; + int height = size.height - insets.top - insets.bottom; + + Rectangle bounds; + + + switch ( fOrientation ) + { + case HORIZONTAL: + width = (int)(width*f(fPercentage)); + break; + case VERTICAL: + int newHeight = (int)(height*f(fPercentage)); + y = height - newHeight; + height = newHeight; + break; + default: + return; + } + + int xi = x + 1; + int yi = y + 1; + int xe = x + width; + int ye = y + height; + int xei = xe - 1; + int yei = ye - 1; + + // Bar Fill + + g.setColor (fColor); + g.fillRect (x,y,width,height); + + // Bar Outline + + g.setColor (fLightColor); + g.drawLine (x,y,xe,y); + g.drawLine (x,yi,xei,yi); + g.drawLine (x,y,x,ye); + g.drawLine (xi,y,xi,yei); + + g.setColor (fDarkColor); + g.drawLine (xe,ye,x,ye); + g.drawLine (xe,ye,xe,y); + g.drawLine (xei,yei,xi,yei); + g.drawLine (xei,yei,xei,yi); + + } + + // + // Input Handling + // + + public void mouseDragged (MouseEvent e) + { + fPercentage = computePercentage (e.getPoint()); + fActionSource.notifyListeners (this, "Percentage Changed"); + fActionSource.notifyListeners (this, "User Changed"); + repaint(); + } + + public void mouseMoved (MouseEvent e) + { + } + + public double computePercentage (Point p) + { + Insets insets = getInsets (); + double percentage = 0.0; + + if ( fOrientation == HORIZONTAL ) { + int x = insets.left; + int width = getSize().width - insets.left - insets.right; + width = Math.max(width,0); + if ( p.x > x ) + percentage = Math.min((double)p.x - x, width)/width; + else + percentage = 0.0; + } + + if ( fOrientation == VERTICAL ) { + int y = insets.top; + int height = getSize().height - insets.top - insets.bottom; + height = Math.max(height,0); + if ( p.y < (y+height) ) + percentage = Math.min((double)y + height - p.y, height)/height; + else + percentage = 0.0; + } + + return Math.pow(percentage,2); + } + + + + +} diff --git a/test/src/share/classes/ibmspace/client/BarGroup.java b/test/src/share/classes/ibmspace/client/BarGroup.java new file mode 100644 index 000000000..fb0aa439e --- /dev/null +++ b/test/src/share/classes/ibmspace/client/BarGroup.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// A container for LabeledBarControls. This was done very quick +// and dirty, but would be a useful class if done more generally +// ... maybe later. Anyway, this class holds a set of bars and +// arranges them vertically or horizontally, depending on the +// orientations of the bars (which need to all be the same, this +// error is not handled so be careful!). It then also handles +// some group activity semantics kinda' like a radio group would +// have. This allows me to resize other bars in the group when +// on is resized by the user. + + +package ibmspace.client; + +import java.util.*; +import javax.swing.*; +import java.awt.event.*; +import java.awt.*; + +public class BarGroup extends JPanel implements ActionListener +{ + private Vector fBars; + private Vector fColors; + + public BarGroup() + { + fBars = new Vector (); + fColors = new Vector (); + } + + public void addBar (LabeledBarControl bar) + { + super.add (bar, null); + fBars.addElement (bar); + fColors.addElement (bar.getBarColor()); + bar.addActionListener (this); + adjustBarColor (bar.getBarControl()); + } + + public void removeAll () + { + super.removeAll (); + fBars.removeAllElements (); + fColors.removeAllElements (); + } + + public LabeledBarControl[] getBars () + { + LabeledBarControl[] bars = new LabeledBarControl [fBars.size()]; + for (int i=0; i 0.001 ) + barsToChange++; + + totalPercentage += bc.getPercentage (); + } + + // Level total percentage to 1.0 + + double perBarExcessPercentage = (totalPercentage - 1.0) / barsToChange; + + for (int i=0; i 0.001) { + bc.setPercentage (p-perBarExcessPercentage); + } + + } + + } + + + private Color getBarBaseColor (BarControl bar) + { + for (int i=0; i + // -Djava.naming.provider.url=iiop:// + + try + { + if ( System.getSecurityManager() == null ) { + System.setSecurityManager (new RMISecurityManager()); + } + + Hashtable env = new Hashtable (); + + context = new InitialContext (env); + Object o = context.lookup ("SpaceConquest"); + server = (SpaceConquest)PortableRemoteObject.narrow (o,SpaceConquest.class); + System.out.println ("Connected to server."); + } + catch (Exception e) + { + System.out.println ("Problem looking up server!"); + System.out.println ("exception: " + e.getMessage ()); + e.printStackTrace (); + } + + return server; + } + + public void joinGame () + { + System.out.println ("Joining game..."); + fGameView = null; + + try + { + fGameView = fSpaceConquest.joinGame (fName); + if ( fGameView != null ) fGameView.test (); + updatePlanetMap (); + } + catch (RemoteException e) + { + System.out.println ("Problem joining game!"); + fGameView = null; + } + + if ( fGameView == null ) { + System.out.println ("Problem joining game: null GameView returned!"); + } + } + + public void updatePlanetMap () + { + if ( fSpaceConquest == null || fGameView == null ) return; + + int i = 0; + int numPlanets = 0; + + try + { + if ( fNumberOfPlanets == 0 ) { + System.out.println ("Initializing planet map."); + + fPlanets = fSpaceConquest.getGalaxyMap (); + + + /* + int length = fSpaceConquest.getNumberOfPlanets (); + fPlanets = new Planet [length]; + for ( int p=0; p shipTech.getRange() ) return true; + if ( current.getSpeed() > shipTech.getSpeed() ) return true; + if ( current.getWeapons() > shipTech.getWeapons() ) return true; + if ( current.getShields() > shipTech.getShields() ) return true; + if ( current.getMini() > shipTech.getMini() ) return true; + return false; + } + + + public void buildFleet (ShipDesign design, int number, ID station) + { + try + { + fGameView.buildFleet (design, number, station); + } + catch (RemoteException e) + { + System.out.println ("Problem building ships!"); + } + } + + public void scrapFleet (ID fleetID) + { + try + { + fGameView.scrapFleet (fleetID); + } + catch (RemoteException e) + { + System.out.println ("Problem scrapping fleet!"); + } + } + + public ID[] getFleetsAt (ID planetID) + { + try + { + return fGameView.getFleetsAt (planetID); + } + catch (RemoteException e) + { + System.out.println ("Problem getting list of fleets at planet!"); + return null; + } + } + + public void sendFleet (ID fleetID, ID destinationID) + { + try + { + fGameView.sendFleet (fleetID, destinationID); + } + catch (RemoteException e) + { + System.out.println ("Problem getting list of fleets at planet!"); + } + } + + + public Fleet getFleet (ID fleetID) + { + try + { + return fGameView.getFleet (fleetID); + } + catch (RemoteException e) + { + System.out.println ("Problem getting fleet summary!"); + return null; + } + } + + + public void updateJourneys () + { + try + { + if ( fJournies == null ) System.out.println ("fJournies is null"); + if ( fGameView == null ) System.out.println ("fGameView is null"); + fJournies.removeAllElements (); + ID[] journies = fGameView.getAllJournies (); + if ( journies != null ) { + for (int i=0; i 0 ) { + message = ""; + } + } + } + + if ( message.equals("") ) { + if ( cost > shipSavings || metal > shipMetal ) { + message = "You do not have enough money or metal!"; + } + } + + if ( !message.equals("") ) { + JOptionPane.showMessageDialog (fFrame, message, "IBM Space Conquest", + JOptionPane.OK_OPTION); + return; + } + + message = "Cost = " + cost + ", Metal = " + metal + "."; + int build = JOptionPane.showConfirmDialog (fFrame, message, "IBM Space Conquest", + JOptionPane.YES_NO_OPTION); + if ( build == JOptionPane.YES_OPTION) { + fGame.buildFleet (design, 1, fSelection); + } + updateShipListView (); + updateResourcesView (); + } + } + + class AbandonPlanet implements java.awt.event.ActionListener + { + AbandonPlanet () + { + } + + public void actionPerformed (ActionEvent e) + { + fGame.abandonPlanet (fSelection); + updateMainBudgetUI (); + } + } + + class Surrender implements java.awt.event.ActionListener + { + Surrender () + { + } + + public void actionPerformed (ActionEvent e) + { + fGame.surrender (); + fGame.updateJourneys (); + updateMainBudgetUI (); + updateShipListView (); + updateResourcesView (); + fGalaxyUI.refreshCache (); + fGalaxyUI.repaint(); + } + } + + class ScrapFleet implements java.awt.event.ActionListener + { + ScrapFleet () + { + } + + public void actionPerformed (ActionEvent e) + { + fGame.scrapFleet (getSelectedFleet()); + updateShipListView (); + updateResourcesView (); + } + } + + +} diff --git a/test/src/share/classes/ibmspace/client/JourneyArrow.java b/test/src/share/classes/ibmspace/client/JourneyArrow.java new file mode 100644 index 000000000..4dac6f0e8 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/JourneyArrow.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Arrow represents an arrow to be drawn between two points. It +// also has some behavior specific to this game. Namely, (1) you +// can shorten the head or tail so that the the end points can be +// the centers of planet gifs while the arrows are drawn between +// the planet perimeters, and (2) you can also shorten the tail to +// show progress of a journey (the tail shortens until the fleet +// reaches the destination planet. Even with these, this is probably +// a generally useful class fo UI work. The arrow head drawing code +// is not but it's fast. + +package ibmspace.client; + +import java.awt.*; + +public class JourneyArrow extends Arrow +{ + private int fAvailableRange = 0; + private Color fAcceptedColor = Color.cyan; + private Color fRejectedColor = Color.red; + private boolean fShowDistance = false; + private int fDistance; + private String fDistanceString; + + public JourneyArrow () + { + } + + public void setAvailableRange (int range) + { + fAvailableRange = range; + } + + public void setAcceptedColor (Color color) + { + fAcceptedColor = color; + } + + public void setRejectedColor (Color color) + { + fRejectedColor = color; + } + + public void setShowDistance (boolean show) + { + fShowDistance = show; + } + + public int getDistance () + { + if ( fCacheBlown ) { + fDistance = (int)(getLength() / 50 + 0.5); + } + + return fDistance; + } + + public void draw (Graphics g) + { + int distance = getDistance (); + + if ( fShowDistance ) { + fDistanceString = String.valueOf (distance); + setLabel (fDistanceString); + } else { + setLabel (null); + } + + if ( distance <= fAvailableRange ) { + g.setColor (fAcceptedColor); + } else { + g.setColor (fRejectedColor); + } + + super.draw (g); + } + + + + +} diff --git a/test/src/share/classes/ibmspace/client/LabeledBarControl.java b/test/src/share/classes/ibmspace/client/LabeledBarControl.java new file mode 100644 index 000000000..d6d315d3c --- /dev/null +++ b/test/src/share/classes/ibmspace/client/LabeledBarControl.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// A container for BarControls that adds labels. + +package ibmspace.client; + +import java.awt.*; +import java.util.*; +import java.text.*; +import javax.swing.*; +import javax.swing.border.*; +import java.awt.event.*; + + +public class LabeledBarControl extends JPanel +{ + private JLabel fLabel; + private BarControl fBar; + + public LabeledBarControl(String text) + { + BorderLayout layout = new BorderLayout (5,5); + + fLabel = new JLabel (text); + fLabel.setPreferredSize (new Dimension(80,20)); + fLabel.setMinimumSize (new Dimension(80,20)); + fLabel.setMaximumSize (new Dimension(80,20)); + + fBar = new BarControl (Color.blue); + fBar.setBorder (new EmptyBorder (3,2,3,2)); + + setPreferredSize (new Dimension(50,20)); + setMinimumSize (new Dimension(500,20)); + setMaximumSize (new Dimension(1000,20)); + + setLayout (layout); + add (fLabel, "West"); + add (fBar, "Center"); + } + + public LabeledBarControl(String text, byte orientation) + { + BorderLayout layout = new BorderLayout (5,5); + + fLabel = new JLabel (text); + //fLabel.setBorder (new EtchedBorder()); + + fBar = new BarControl (Color.blue, orientation); + + setLayout (layout); + + add (fBar, "Center"); + + switch ( orientation ) + { + case BarControl.HORIZONTAL: + fLabel.setPreferredSize (new Dimension(80,20)); + fLabel.setMinimumSize (new Dimension(80,20)); + fBar.setBorder (new EmptyBorder (3,2,3,2)); + add (fLabel, "West"); + break; + case BarControl.VERTICAL: + fLabel.setFont (new Font ("SansSerif", Font.PLAIN, 10)); + fLabel.setPreferredSize (new Dimension(40,20)); + fLabel.setMinimumSize (new Dimension(40,20)); + fLabel.setMaximumSize (new Dimension(40,20)); + fBar.setBorder (new EmptyBorder (2,12,2,12)); + fLabel.setHorizontalAlignment (JLabel.CENTER); + fBar.setSize (new Dimension(20,80)); + fBar.setMaximumSize (new Dimension(20,100)); + fBar.setMinimumSize (new Dimension(20,50)); + fBar.setPreferredSize (new Dimension(20,80)); + add (fLabel, "South"); + break; + default: + break; + } + + } + + public void addActionListener (ActionListener listener) + { + fBar.addActionListener (listener); + } + + public void removeActionListener (ActionListener listener) + { + fBar.removeActionListener (listener); + } + + public void setLabelText (String labelText) + { + fLabel.setText (labelText); + } + + public String getLabelText () + { + return fLabel.getText (); + } + + public void setBarColor (Color color) + { + fBar.setColor (color); + } + + public Color getBarColor () + { + return fBar.getColor (); + } + + public BarControl getBarControl () + { + return fBar; + } + + + public void setPercentage (double percentage) + { + fBar.setPercentage (percentage); + } + + public double getPercentage () + { + return fBar.getPercentage (); + } + +} diff --git a/test/src/share/classes/ibmspace/client/PercentLayout.java b/test/src/share/classes/ibmspace/client/PercentLayout.java new file mode 100644 index 000000000..cb116c5b2 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/PercentLayout.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// A layout manager that lays out components in either a vertical +// or horizontal arrangement giving each component a percentage +// of the arrangement. I did this quickly at the end and it can +// certainly be improved. For one, it doesn't check to ensure that +// the percentages total 100! It's still pretty useful. + +package ibmspace.client; + +import java.lang.*; +import java.awt.*; +import java.util.*; + + +public class PercentLayout implements LayoutManager2 +{ + static int VERT = 0; + static int HORZ = 1; + + private int fAlign; + + private Vector fComponents = null; + + public PercentLayout (int align) + { + fAlign = align; + fComponents = new Vector (); + } + + public void addLayoutComponent (Component c, Object constraints) + { + fComponents.addElement (new ComponentInfo(c,(Float)constraints)); + } + + public void addLayoutComponent(String name, Component c) + { + // Not supported + } + + public void removeLayoutComponent (Component c) + { + for (int i=0; i center.x ) { + if ( p.y < center.y ) { + // first quadrant 0 - 98 + + double o = (double)(center.y - p.y); + double a = (double)(p.x - center.x); + double h = Math.sqrt(o*o + a*a); + double sine = o/h; + + return (0.25 - (Math.asin(sine) * 0.5) / Math.PI); + + } else { + // second quadrant 90 - 179 + + double o = (double)(p.y - center.y); + double a = (double)(p.x - center.x); + double h = Math.sqrt(o*o + a*a); + double sine = o/h; + + return ((Math.asin(sine) * 0.5) / Math.PI) + 0.25; + } + } else { + if ( p.y > center.y ) { + // third quadrant 180 - 269 + + double o = (double)(p.y - center.y); + double a = (double)(center.x - p.x); + double h = Math.sqrt(o*o + a*a); + double sine = o/h; + + return (0.25 - (Math.asin(sine) * 0.5) / Math.PI) + 0.50; + } else { + // fourth quadrant 270 - 359 + + double o = (double)(center.y - p.y); + double a = (double)(center.x - p.x); + double h = Math.sqrt(o*o + a*a); + double sine = o/h; + + return ((Math.asin(sine) * 0.5) / Math.PI) + 0.75; + } + } + } + + +} diff --git a/test/src/share/classes/ibmspace/client/PlanetStatsView.java b/test/src/share/classes/ibmspace/client/PlanetStatsView.java new file mode 100644 index 000000000..d6f9a4a82 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/PlanetStatsView.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Displays planet statistics. This is a useful example of text +// scaling, which should be a whole lot easier in 1.2 with +// tranformations, but this is written to work on 1.1.6 or later. + +package ibmspace.client; + +import java.awt.*; +import javax.swing.*; +import ibmspace.common.Planet; +import ibmspace.common.PlanetView; + +public class PlanetStatsView extends JComponent +{ + private String fName = "Unknown"; + private String fIncome = "Unknown"; + private String fPopulation = "Unknown"; + private String fTemperature = "Unknown"; + private String fGravity = "Unknown"; + private String fMetal = "Unknown"; + + public PlanetStatsView () + { + } + + public void presentPlanet (PlanetView planet) + { + + // More info if we have it + + if ( planet != null ) { + fName = planet.getName (); + if ( planet.isOwned() ) { + fIncome = String.valueOf (planet.getIncome()); + fPopulation = String.valueOf (planet.getPopulation()); + fTemperature = String.valueOf (planet.getTemp()); + fGravity = String.valueOf (planet.getGravity()); + fMetal = String.valueOf (planet.getMetal()); + } + } + + repaint (); + } + + public void paint (Graphics g) + { + update (g); + } + + public void update (Graphics g) + { + Rectangle bounds = getBounds (); + + //bounds.grow (-horzInset,-vertInset); + int bx = bounds.x; + int by = bounds.y; + int bw = bounds.width; + int bh = bounds.height; + + // + // Determine and Set Optimal Font Point Size + // + + int maxHeight = bh / 8; + int maxWidth = bw / 2; + int pointSize = 1; + + for ( int pt = 1; pt < 72; pt ++ ) { + Font f = new Font ("SansSerif",Font.PLAIN,pt); + g.setFont (f); + FontMetrics fm = g.getFontMetrics (); + int height = fm.getHeight () + fm.getLeading (); + int width = fm.stringWidth (" Income: "); + + if ( height > maxHeight || width > maxWidth ) + break; + + pointSize = pt; + } + + + // + // Align Text Fields + // + + int x, y; + FontMetrics fm = g.getFontMetrics (); + g.setColor (Color.black); + + x = maxWidth - fm.stringWidth ("Income:"); + y = 3 * maxHeight; + g.drawString ("Income:", x, y); + x = maxWidth + 5; + g.drawString (fIncome, x, y); + + x = maxWidth - fm.stringWidth ("Pop:"); + y += maxHeight; + g.drawString ("Pop:", x, y); + x = maxWidth + 5; + g.drawString (fPopulation, x, y); + + x = maxWidth - fm.stringWidth ("Temp:"); + y += maxHeight; + g.drawString ("Temp:", x, y); + x = maxWidth + 5; + g.drawString (fTemperature, x, y); + + x = maxWidth - fm.stringWidth ("Gravity:"); + y += maxHeight; + g.drawString ("Gravity:", x, y); + x = maxWidth + 5; + g.drawString (fGravity, x, y); + + x = maxWidth - fm.stringWidth ("Metal:"); + y += maxHeight; + g.drawString ("Metal:", x, y); + x = maxWidth + 5; + g.drawString (fMetal, x, y); + + int planetWidth = fm.stringWidth (fName); + x = (bw - planetWidth)/2; + y = (int)(1.5 * maxHeight); + g.setFont (new Font ("SansSerif",Font.BOLD,pointSize+1)); + g.drawString (fName, x, y); + + } + +} diff --git a/test/src/share/classes/ibmspace/client/PlanetViewUI.java b/test/src/share/classes/ibmspace/client/PlanetViewUI.java new file mode 100644 index 000000000..327d58cf9 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/PlanetViewUI.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// PlanetView is really a wrapper for planet gifs that is used +// by GalaxyView. + + +package ibmspace.client; + +import java.awt.*; +import ibmspace.common.Planet; +import ibmspace.common.PlanetView; + +public class PlanetViewUI +{ + private static Image fgUnknownPlanetImage = null; + private static Image fgGoodPlanetImage = null; + private static Image fgBadPlanetImage = null; + private static Image fgSelectionImage = null; + + private PlanetView fPlanetView; + private Image fIcon; + private Image fSelection; + + private boolean fHasSatelites = false; + + + + public static void setUnknownPlanetImage (Image image) + { + fgUnknownPlanetImage = image; + } + + public static void setGoodPlanetImage (Image image) + { + fgGoodPlanetImage = image; + } + + public static void setBadPlanetImage (Image image) + { + fgBadPlanetImage = image; + } + + public static void setSelectionImage (Image image) + { + fgSelectionImage = image; + } + + public PlanetViewUI (PlanetView planet) + { + fPlanetView = planet; + Button c = new Button (); + fHasSatelites = planet.hasSatelites (); + double suitability = planet.getSuitability (); + + //System.out.println ("Suitability: " + suitability); + + if ( suitability == -1 ) { + fIcon = fgUnknownPlanetImage; + } else if ( suitability > 0.5 ) { + fIcon = fgGoodPlanetImage; + } else { + fIcon = fgBadPlanetImage; + } + + fSelection = fgSelectionImage; + } + + public String getName () + { + return fPlanetView.getName (); + } + + public Rectangle getBounds () + { + Point location = fPlanetView.getCoordinates(); + return new Rectangle (location.x-19, location.y-19, 38, 38); + } + + public void draw (Graphics g, boolean drawPlanet, boolean drawName, boolean drawSelection) + { + Point location = fPlanetView.getCoordinates (); + + if ( drawPlanet ) { + if ( drawSelection ) { + g.drawImage (fSelection, location.x-30, location.y-30, 60, 60, null); + } + g.drawImage (fIcon, location.x-19, location.y-19, 38, 38, null); + + if ( fHasSatelites ) { + g.setColor (Color.white); + g.drawOval (location.x-22, location.y-21, 43, 43); + } + } + + if ( drawName ) { + g.setColor (Color.white); + g.setFont (new Font ("SansSerif",Font.PLAIN,10)); + FontMetrics fm = g.getFontMetrics (); + int width = fm.stringWidth (getName()); + int height = fm.getHeight () + fm.getLeading (); + int x = location.x - (width/2); + int y = location.y + 20 + height; + g.drawString (getName(), x, y); + } + + } + +} diff --git a/test/src/share/classes/ibmspace/client/ResourceLevelsPanel.java b/test/src/share/classes/ibmspace/client/ResourceLevelsPanel.java new file mode 100644 index 000000000..e2086af34 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/ResourceLevelsPanel.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// Like PlanetStatsView, this view displays text and scales it +// to fit the given space. + +package ibmspace.client; + +import java.awt.*; +import javax.swing.*; + +public class ResourceLevelsPanel extends JComponent +{ + private String fSavings = ""; + private String fMetal = ""; + private String fIncome = ""; + private String fIIOP = ""; + + public ResourceLevelsPanel () + { + } + + public String valueOf (long value) + { + String units = ""; + + if ( value > 1000000 ) { + value = value / 1000; + if ( value > 1000000 ) { + value = value / 1000; + units = "M"; + } else { + units = "K"; + } + } + return String.valueOf(value) + units; + } + + + public void setShipSavings (long savings) + { + fSavings = valueOf(savings); + } + + public void setShipMetal (long metal) + { + fMetal = valueOf(metal); + } + + public void setIncome (long income) + { + fIncome = valueOf(income); + } + + public void setIIOPCalls (long calls) + { + fIIOP = valueOf(calls); + } + + + public void paint (Graphics g) + { + update (g); + } + + public void update (Graphics g) + { + Rectangle bounds = getBounds (); + + int bx = bounds.x; + int by = bounds.y; + int bw = bounds.width; + int bh = bounds.height; + + // + // Determine and Set Optimal Font Point Size + // + + int maxHeight = bh / 3; + int maxWidth = bw / 2; + int pointSize = 1; + int padding = 0; + + for ( int pt = 1; pt < 72; pt ++ ) { + Font f = new Font ("SansSerif",Font.PLAIN,pt); + g.setFont (f); + FontMetrics fm = g.getFontMetrics (); + int height = fm.getHeight () + fm.getLeading (); + int width = fm.stringWidth ("Savings: " + fSavings); + width = Math.max(width,fm.stringWidth ("Metal: " + fMetal)); + width = Math.max(width,fm.stringWidth ("Income: " + fIncome)); + width = Math.max(width,fm.stringWidth ("IIOP: " + fIIOP)); + + if ( height > maxHeight || width > maxWidth ) + break; + + padding = (maxWidth - width) / 4; + pointSize = pt; + } + + // + // Align Text Fields + // + + int x, y; + FontMetrics fm = g.getFontMetrics (); + g.setColor (Color.black); + + int indent = fm.stringWidth ("Savings: "); + + x = padding; + y = (int)(1.5 * (double)maxHeight); + g.drawString ("Savings: ", x, y); + x += indent; + g.drawString (fSavings, x, y); + + x = maxWidth + padding; + g.drawString ("Income: ", x, y); + x += indent; + g.drawString (fIncome, x, y); + + x = padding; + y += maxHeight; + g.drawString ("Metal: ", x, y); + x += indent; + g.drawString (fMetal, x, y); + + x = maxWidth + padding; + g.setColor (Color.red); + g.drawString ("IIOP: ", x, y); + x += indent; + g.drawString (fIIOP, x, y); + + } + + + +} diff --git a/test/src/share/classes/ibmspace/client/ShipListPanel.java b/test/src/share/classes/ibmspace/client/ShipListPanel.java new file mode 100644 index 000000000..bb40b37a6 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/ShipListPanel.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.client; + +import java.util.Vector; +import java.lang.reflect.Array; +import javax.swing.*; +import javax.swing.event.*; +import ibmspace.common.*; + +public class ShipListPanel extends JScrollPane +{ + private JList fList = null; + private Vector fFleets = null; + private Vector fLabels = null; + + public ShipListPanel() + { + fList = new JList(); + fList.setSelectionMode (0); + fFleets = new Vector (); + fLabels = new Vector (); + getViewport().setView (fList); + } + + private void updateList () + { + String[] label = new String [fLabels.size()]; + for (int i=0; i maxHeight || width > maxWidth ) + break; + + padding = (maxWidth - width) / 2; + pointSize = pt; + } + + + + // + // Align Text Fields + // + + int x, y; + FontMetrics fm = g.getFontMetrics (); + g.setColor (Color.black); + + x = padding; + y = 2 * maxHeight; + g.drawString (fRange, x, y); + y += maxHeight; + g.drawString (fSpeed, x, y); + y += maxHeight; + g.drawString (fWeapons, x, y); + y += maxHeight; + g.drawString (fShields, x, y); + y += maxHeight; + g.drawString (fMini, x, y); + } + +} diff --git a/test/src/share/classes/ibmspace/client/TurnTaker.java b/test/src/share/classes/ibmspace/client/TurnTaker.java new file mode 100644 index 000000000..12bb1f4a4 --- /dev/null +++ b/test/src/share/classes/ibmspace/client/TurnTaker.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// This class puts turn taking into a thread so that the UI remains +// responsive. You take a turn by pressing the "Take Turn" button. +// The button then becomes "Waiting for other players" and may stay +// that way for a while, until all other players have pushed their +// buttons. During this time, your turn call is blocked in the server. +// But because I didn't like being stuck during this time, I made it +// possible to do anything but take another turn while waiting for +// other players. So you can start working on your other turn while +// waiting for other players to finish this turn. In reality, though, +// some of the things you do will affect the current turn that is blocked +// and waiting for other players. This obviously needs more work, but +// it's a start! + +package ibmspace.client; + +public class TurnTaker extends Thread +{ + private GameUI fUI; + + public TurnTaker (GameUI ui) + { + fUI = ui; + } + + public void run () + { + fUI.beginTurn (); + fUI.endTurn (); + } + +} diff --git a/test/src/share/classes/ibmspace/client/good.gif b/test/src/share/classes/ibmspace/client/good.gif new file mode 100644 index 000000000..ee69cdf5d Binary files /dev/null and b/test/src/share/classes/ibmspace/client/good.gif differ diff --git a/test/src/share/classes/ibmspace/client/logo.gif b/test/src/share/classes/ibmspace/client/logo.gif new file mode 100644 index 000000000..e3d181e0e Binary files /dev/null and b/test/src/share/classes/ibmspace/client/logo.gif differ diff --git a/test/src/share/classes/ibmspace/client/selection.gif b/test/src/share/classes/ibmspace/client/selection.gif new file mode 100644 index 000000000..754de1bc2 Binary files /dev/null and b/test/src/share/classes/ibmspace/client/selection.gif differ diff --git a/test/src/share/classes/ibmspace/client/ugly.gif b/test/src/share/classes/ibmspace/client/ugly.gif new file mode 100644 index 000000000..83fdd4508 Binary files /dev/null and b/test/src/share/classes/ibmspace/client/ugly.gif differ diff --git a/test/src/share/classes/ibmspace/client/unknown.gif b/test/src/share/classes/ibmspace/client/unknown.gif new file mode 100644 index 000000000..9322231f0 Binary files /dev/null and b/test/src/share/classes/ibmspace/client/unknown.gif differ diff --git a/test/src/share/classes/ibmspace/common/BudgetSummary.java b/test/src/share/classes/ibmspace/common/BudgetSummary.java new file mode 100644 index 000000000..01442f56f --- /dev/null +++ b/test/src/share/classes/ibmspace/common/BudgetSummary.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.common; + +import java.lang.reflect.Array; + + +public class BudgetSummary implements java.io.Serializable +{ + private String[] fNames; + private double[] fPercentages; + + + public BudgetSummary (int numItems, String[] names, double[] percentages) + { + fNames = names; + fPercentages = percentages; + } + + public String[] getNames () + { + return fNames; + } + + public double getPercentage (String name) + { + for (int i=0; i getResistanceOfGroup(defender) ) { + fWinner = getOwnerOfGroup (offender); + fLoser = getOwnerOfGroup (defender); + eliminateGroup (defender); + } else if ( getStrengthOfGroup (defender) > getResistanceOfGroup (offender) ) { + fWinner = getOwnerOfGroup (defender); + fLoser = getOwnerOfGroup (offender); + eliminateGroup (offender); + } else { + System.out.println ("random call"); + int coin = (int)(Math.random() * 1.0); + if ( coin == 0 ) { + fWinner = getOwnerOfGroup (defender); + fLoser = getOwnerOfGroup (offender); + eliminateGroup (offender); + } else { + fWinner = getOwnerOfGroup (offender); + fLoser = getOwnerOfGroup (defender); + eliminateGroup (defender); + } + } + } + + public int getNumberOfGroups () + { + return fGroups.size (); + } + + public int getStrengthOfGroup (int index) + { + int strength = 0; + Vector group = getGroup (index); + for (int i=0; i dollars ) { + investmentDollars = dollars; + } + investment.invest (investmentDollars); + dollars -= investmentDollars; + } + } + + public int totalAllocations () + { + int total = 0; + + for (int i=0; i 0 ) { + change = -1; + } else { + change = 1; + } + + int i = 0; + while ( difference != 0 ) { + BudgetItem item = (BudgetItem)fBudgetItems.elementAt(i); + item.setPercentage (item.getPercentage()+change); + difference += change; + + i++; + if ( i == numberOfBudgetItems() ) i = 0; + } + } + + } + + public void addBudgetItem (BudgetItem item) + { + fBudgetItems.addElement (item); + } + + public void removeBudgetItem (BudgetItem item) + { + fBudgetItems.removeElement (item); + } + + public BudgetItem findBudgetItem (Investment investment) + { + for (int i=0; i=0; i-- ) { + JourneyImpl journey = (JourneyImpl)fJournies.elementAt (i); + journey.moveFleet (); + if ( journey.isComplete() ) { + FleetImpl fleet = journey.getFleet (); + Planet planet = journey.getDestination (); + Player player = fleet.getOwner (); + String m = "Your fleet of " + fleet.toString() + " arrived at " + + planet.getName(); + player.addMessage (m); + fJournies.removeElement (journey); + } + } + } + + private synchronized void fuelFleets () + { + Vector planets = fGalaxy.getPlanets (); + for (int i=0; i=0; i--) { + Player player = (Player)fPlayers.elementAt (i); + if ( getIncomeFor (player) == 0 ) { + System.out.println ("Eliminates player " + player.getName()); + player.addMessage ("You have been eliminated from the game."); + fPlayers.removeElement (player); + fNumberOfPlayers--; + for (int j=0; j= 0; i--) { + Settlement s = (Settlement)fSettlements.elementAt (i); + if ( s != null & s.getOwner() == player ) { + fSettlements.removeElement (s); + } + } + + for (int i=fFleets.size()-1; i>=0; i--) { + FleetImpl f = (FleetImpl)fFleets.elementAt (i); + if ( f != null && f.getOwner() == player ) { + scrapFleet (f); + fFleets.removeElement (f); + } + } + + String name = player.getName (); + fPlayers.removeElement (player); + fNumberOfPlayers--; + + for (int i=0; i 0 ) { + ids = new ID [journies.size()]; + for (int i=0; i= cost ) { + savings.withdraw (cost); + fDesigns.addElement (design); + return design; + } else { + return null; + } + } + + public ID /*fleet*/ + buildFleet (ShipDesign design, int num, ID stationID) throws RemoteException + { + System.out.println ("buildFleet - " + num + " " + design.getName()); + + fGame.logCall (); + PlanetImpl station = fGame.getPlanet (stationID); + + if ( design != null && station != null && station.getOwner() == fPlayer ) { + + long cost = design.getCostPerShip() * num; + long metal = design.getMetalPerShip() * num; + + ShipSavings savings = fPlayer.getShipSavings (); + long shipMetal = fPlayer.getShipMetal (); + + if ( savings.getSavings() >= cost && shipMetal >= metal ) { + savings.withdraw (cost); + fPlayer.removeShipMetal (metal); + FleetImpl fleet = new FleetImpl (design, num, fPlayer); + fGame.addFleet (fleet, station); + return fleet.getID(); + } + + } + + return null; + } + + public void scrapFleet (ID fleetID) throws RemoteException + { + System.out.println ("scrapFleet"); + fGame.logCall (); + FleetImpl fleet = fGame.getFleet (fleetID); + if ( fleet != null && fleet.getOwner() == fPlayer ) { + fGame.scrapFleet (fleet); + } + } + + public ID /* journey */ + sendFleet (ID fleetID, ID toPlanetID) throws RemoteException + { + System.out.println ("sendFleet"); + fGame.logCall (); + fGame.cancelJourneyFor (fleetID); + FleetImpl fleet = fGame.getFleet (fleetID); + PlanetImpl toPlanet = fGame.getPlanet (toPlanetID); + + if ( fleet != null && fleet.getStation() != null && + fleet.getOwner() == fPlayer && toPlanet != null ) { + JourneyImpl journey = fGame.sendFleet (fleet, toPlanet); + return journey.getID (); + } else { + return null; + } + } + + public Fleet getFleet (ID fleetID) throws RemoteException + { + System.out.println ("getFleet"); + fGame.logCall (); + return fGame.getFleet (fleetID); + } + + public ID[] getFleetsAt (ID planetID) throws RemoteException + { + System.out.println ("getFleetsAt"); + fGame.logCall (); + PlanetImpl planet = fGame.getPlanet (planetID); + if ( planet != null && planet.getOwner() == fPlayer ) { + FleetImpl[] fleets = planet.getFleets (); + int size = Array.getLength (fleets); + ID[] ids = new ID [size]; + for (int i=0; i= fTotalDistance ) { + fIsComplete = true; + fDestination.acceptOrbit (fFleet); + fFleet.setJourney (null); + } + } + +} diff --git a/test/src/share/classes/ibmspace/server/Mining.java b/test/src/share/classes/ibmspace/server/Mining.java new file mode 100644 index 000000000..a61951aeb --- /dev/null +++ b/test/src/share/classes/ibmspace/server/Mining.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + + +public class Mining implements Investment, java.io.Serializable +{ + public static double MINING_COST = 0.1; + + private Player fPlayer; + private PlanetImpl fPlanet; + + public Mining (PlanetImpl planet, Player player) + { + fPlayer = player; + fPlanet = planet; + } + + public String getName () + { + return "Mining"; + } + + public void invest (long dollars) + { + long metal = 0; + + if ( dollars > 0 ) { + long total = fPlanet.getMetal (); + if ( total > 0 ) { + double d = dollars; + double efficiency = total / 10000.0; + metal = (long)(d / MINING_COST * efficiency); + + if ( metal > total ) { + metal = total; + } + + fPlanet.removeMetal (metal); + fPlayer.addShipMetal (metal); + } + } + } + +} diff --git a/test/src/share/classes/ibmspace/server/PlanetImpl.java b/test/src/share/classes/ibmspace/server/PlanetImpl.java new file mode 100644 index 000000000..2e2aaed8b --- /dev/null +++ b/test/src/share/classes/ibmspace/server/PlanetImpl.java @@ -0,0 +1,367 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + +import java.awt.Point; +import java.util.Vector; +import ibmspace.common.ID; +import ibmspace.common.Planet; +import ibmspace.common.Fleet; +import java.lang.reflect.Array; + +public class PlanetImpl implements Planet, java.io.Serializable +{ + // + // Some static helpers for computing random + // temperature, gravity and metal... + // + + private static double MIN_TEMP = -200; + private static double MAX_TEMP = +200; + private static double MIN_GRAV = 0.5; + private static double MAX_GRAV = 3.0; + private static long MAX_METAL = 40000; + + public static double RandomTemp () + { + return Math.random() * (MAX_TEMP-MIN_TEMP) + MIN_TEMP; + } + + public static double RandomGravity () + { + return Math.random() * (MAX_GRAV-MIN_GRAV) + MIN_GRAV; + } + + public static long RandomMetal () + { + return (long)(Math.random() * MAX_METAL); + } + + + // + // Private Data Members + // + + private ID fID; + private String fName; + private Point fCoordinates; + private double fGravity; + private double fTemp; + private long fMetal; + private Player fOwner; + private Settlement fSettlement; + private Vector fFleetsInOrbit; + private Vector fFleetsOnSurface; + + // + // Helper + // + + + public static int pixelsForDistance (int distance) + { + return 50 * distance; + } + + // + // Constructor + // + + public PlanetImpl (String name, double temp, double gravity, long metal) + { + fID = new ID (); + fName = name; + fCoordinates = new Point (0,0); + fTemp = temp; + fGravity = gravity; + fMetal = metal; + fOwner = null; + fSettlement = null; + fFleetsOnSurface = new Vector (); + fFleetsInOrbit = new Vector (); + } + + + // + // Planet Interface Methods + // + + public Vector getFleetList () + { + return fFleetsOnSurface; + } + + + public ID getID () + { + return fID; + } + + public String getName () + { + return fName; + } + + public Point getCoordinates () + { + return fCoordinates; + } + + public boolean hasSatelites () + { + for (int i=0; i 0 ) { + orbitStationedFleets (); + Battle battle = new Battle (); + battle.addFleets (fFleetsInOrbit); + while ( battle.getNumberOfGroups() > 1 ) { + int offender = (int)(Math.random() * 1.0); + int defender = (offender == 0)? 1 : 0; + battle.runBattleSimulation (offender, defender); + Player winner = battle.getWinner (); + Player loser = battle.getLoser (); + winner.addMessage ("You won a battle against " + loser.getName() + " at " + getName()); + loser.addMessage ("You lost a battle against " + winner.getName() + " at " + getName()); + } + + Player newOwner = battle.getOwnerOfGroup (0); + + long scrapMetal = battle.getScrapMetal (); + if ( scrapMetal > 0 ) { + addMetal (scrapMetal); + newOwner.addMessage (scrapMetal + " tons of metal fell on " + getName() + " from the battle."); + } + + if ( newOwner != fOwner ) { + if ( fOwner != null && fSettlement != null ) { + newOwner.addMessage ("You have destroyed " + fOwner.getName() + "'s colony at " + getName()); + fOwner.addMessage ("You colony at " + getName() + " has been destroyed by " + newOwner.getName()); + Budget budget = fOwner.getBudget (); + BudgetItem item = budget.findBudgetItem (getName()); + budget.removeBudgetItem (item); + } + fSettlement = null; + fOwner = newOwner; + } + + fFleetsInOrbit = battle.getGroup (0); + acceptFleets (); + } + } + +} + + + diff --git a/test/src/share/classes/ibmspace/server/PlanetNames.java b/test/src/share/classes/ibmspace/server/PlanetNames.java new file mode 100644 index 000000000..29fe8e7b2 --- /dev/null +++ b/test/src/share/classes/ibmspace/server/PlanetNames.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + +import java.util.Vector; + +public class PlanetNames implements java.io.Serializable +{ + private Vector fNames; + + public PlanetNames () + { + fNames = new Vector (); + fNames.addElement (new String ("Deneb")); + fNames.addElement (new String ("Proxima")); + fNames.addElement (new String ("Enif")); + fNames.addElement (new String ("Altair")); + fNames.addElement (new String ("Ursa")); + fNames.addElement (new String ("Sauron")); + fNames.addElement (new String ("Sol")); + fNames.addElement (new String ("Propus")); + fNames.addElement (new String ("Hobbes")); + fNames.addElement (new String ("Spica")); + fNames.addElement (new String ("Yavin")); + fNames.addElement (new String ("Virgo")); + fNames.addElement (new String ("Tiber")); + fNames.addElement (new String ("Quark")); + fNames.addElement (new String ("Coxa")); + fNames.addElement (new String ("Libra")); + fNames.addElement (new String ("Atlas")); + fNames.addElement (new String ("Alkaid")); + fNames.addElement (new String ("Antares")); + fNames.addElement (new String ("Rigel")); + fNames.addElement (new String ("Murzim")); + fNames.addElement (new String ("Barsoon")); + fNames.addElement (new String ("Atria")); + fNames.addElement (new String ("Thune")); + fNames.addElement (new String ("Regor")); + fNames.addElement (new String ("Remulak")); + fNames.addElement (new String ("Sooltar")); + fNames.addElement (new String ("Klah")); + fNames.addElement (new String ("Dabih")); + fNames.addElement (new String ("Basil")); + fNames.addElement (new String ("Hope")); + fNames.addElement (new String ("Torino")); + fNames.addElement (new String ("Scorpio")); + fNames.addElement (new String ("Procyon")); + fNames.addElement (new String ("Beid")); + fNames.addElement (new String ("Denali")); + fNames.addElement (new String ("Ain")); + } + + public String getName () + { + int index = (int)(Math.random() * (fNames.size()-1)); + String name = (String)fNames.elementAt (index); + fNames.removeElementAt (index); + return name; + } + +} diff --git a/test/src/share/classes/ibmspace/server/PlanetViewImpl.java b/test/src/share/classes/ibmspace/server/PlanetViewImpl.java new file mode 100644 index 000000000..f548ae881 --- /dev/null +++ b/test/src/share/classes/ibmspace/server/PlanetViewImpl.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + +import java.awt.Point; +import ibmspace.common.ID; +import ibmspace.common.PlanetView; + + + +public class PlanetViewImpl implements PlanetView, java.io.Serializable +{ + private Player fPlayer; + private PlanetImpl fPlanet; + + + public PlanetViewImpl (Player player, PlanetImpl planet) + { + fPlayer = player; + fPlanet = planet; + } + + // + // Planet Interface Methods + // + + public ID getID () + { + return fPlanet.getID (); + } + + public String getName () + { + return fPlanet.getName (); + } + + public Point getCoordinates () + { + return fPlanet.getCoordinates (); + } + + public boolean hasSatelites () + { + return fPlanet.hasSatelites (); + } + + + // + // PlanetView Methods + // + + public boolean isOwned () + { + return ( fPlayer == fPlanet.getOwner() ); + } + + public long getMetal () + { + return fPlanet.getMetal (); + } + + public long getPopulation () + { + if ( isOwned() ) { + Settlement settlement = fPlanet.getSettlement (); + if ( settlement != null ) { + return settlement.getPopulation().size (); + } else { + return 0; + } + } else { + return -1; + } + } + + public long getIncome () + { + if ( isOwned() ) { + Settlement settlement = fPlanet.getSettlement (); + if ( settlement != null ) { + return settlement.getIncome (); + } else { + return 0; + } + } else { + return -1; + } + } + + public double getTemp () + { + if ( isOwned() ) { + return fPlayer.getRelativeTempFor (fPlanet.getTemp()); + } else { + return -1; + } + } + + public double getGravity () + { + if ( isOwned() ) { + return fPlayer.getRelativeGravityFor (fPlanet.getGravity()); + } else { + return -1; + } + } + + public double getSuitability () + { + if ( isOwned() ) { + return fPlanet.getSuitabilityFor (fPlayer); + } else { + return -1; + } + } + +} + diff --git a/test/src/share/classes/ibmspace/server/Player.java b/test/src/share/classes/ibmspace/server/Player.java new file mode 100644 index 000000000..eecc41992 --- /dev/null +++ b/test/src/share/classes/ibmspace/server/Player.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + +import ibmspace.common.*; +import java.util.Vector; +import ibmspace.common.Identifiable; +import ibmspace.common.ID; + + +public class Player implements Identifiable, java.io.Serializable +{ + private ID fID; + private String fName; + private double fIdealTemp; + private double fIdealGravity; + private PlanetImpl fHome = null; + + private ShipSavings fSavings = null; + private ResearchLab fResearchLab = null; + private Budget fBudget = null; + private long fShipMetal; + + private Vector fMessages; + + public Player(String name, double idealTemp, double idealGravity) + { + fName = name; + fIdealTemp = idealTemp; + fIdealGravity = idealGravity; + fHome = null; + + fSavings = new ShipSavings (40000); + fShipMetal = 40000; + + fResearchLab = new ResearchLab (new TechProfile(6,2,2,2,1)); + fBudget = new Budget ("Main Budget"); + fBudget.addBudgetItem (new BudgetItem (fSavings,50)); + fBudget.addBudgetItem (new BudgetItem (fResearchLab,50)); + + fMessages = new Vector (); + } + + public void rememberPlanetOwner (Planet planet, String owner) + { + } + + public ID getID () + { + return fID; + } + + public String getName () + { + return fName; + } + + public void setHome (PlanetImpl home) + { + fHome = home; + } + + public PlanetImpl getHome () + { + return fHome; + } + + public Budget getBudget () + { + return fBudget; + } + + public Budget getTechBudget () + { + return fResearchLab.getTechnologyBudget (); + } + + public Budget getPlanetBudget (PlanetImpl planet) + { + BudgetItem item = fBudget.findBudgetItem (planet.getName()); + if ( item != null ) { + return (Budget)item.getInvestment (); + } else { + return null; + } + } + + public ShipSavings getShipSavings () + { + return fSavings; + } + + public long getShipMetal () + { + return fShipMetal; + } + + public ResearchLab getResearchLab () + { + return fResearchLab; + } + + public void setShipMetal (int metal) + { + fShipMetal = metal; + } + + public void addShipMetal (long metal) + { + fShipMetal += metal; + } + + public void removeShipMetal (long metal) + { + fShipMetal -= metal; + } + + public double getIdealTemp () + { + return fIdealTemp; + } + + public double getIdealGravity () + { + return fIdealGravity; + } + + public double getRelativeTempFor (double temp) + { + return temp/fIdealTemp * 72.0; + } + + public double getRelativeGravityFor (double gravity) + { + return gravity/fIdealGravity; + } + + + public void clearMessages () + { + fMessages.removeAllElements (); + } + + public void addMessage (String message) + { + fMessages.addElement (message); + } + + public Vector getMessages () + { + Vector m = fMessages; + fMessages = new Vector (); + return m; + } + + +} diff --git a/test/src/share/classes/ibmspace/server/Population.java b/test/src/share/classes/ibmspace/server/Population.java new file mode 100644 index 000000000..69d6fa3aa --- /dev/null +++ b/test/src/share/classes/ibmspace/server/Population.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + + +public class Population implements java.io.Serializable +{ + private PlanetImpl fPlanet; + private long fChildren; + private long fAdults; + private long fSeniors; + private long fWillDie; + + public Population (PlanetImpl planet, long initialSize) + { + fPlanet = planet; + + if ( initialSize <= 40 ) { + fChildren = 0; + fAdults = initialSize; + fSeniors = 0; + fWillDie = 0; + } else { + fChildren = initialSize / 4; + fAdults = initialSize / 4; + fSeniors = initialSize / 4; + fWillDie = initialSize - (fChildren + fAdults + fSeniors); + } + } + + public long size () + { + return (fChildren + fAdults + fSeniors + fWillDie); + } + + public long getIdealIncome () + { + return (long)((fAdults+fSeniors)/8); + } + + + public void grow (double suitability) + { + long s = size (); + double offspring = Math.min(Math.max(1.0+(double)(50000*suitability /size()),1.01),1.6); + + fChildren = (long)(fAdults * offspring); + fSeniors = (long)(fAdults * suitability); + fAdults = (long)(fChildren * suitability); + fWillDie = (long)(fSeniors * suitability); + + if ( size() < 10 ) { + fChildren = 0; + fAdults = 10; + fSeniors = 0; + fWillDie = 0; + } + } + +} diff --git a/test/src/share/classes/ibmspace/server/ResearchLab.java b/test/src/share/classes/ibmspace/server/ResearchLab.java new file mode 100644 index 000000000..bff6a708d --- /dev/null +++ b/test/src/share/classes/ibmspace/server/ResearchLab.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + +import ibmspace.common.TechProfile; + + +public class ResearchLab implements Investment, java.io.Serializable +{ + private Budget fTechBudget; + private Technology fRange; + private Technology fSpeed; + private Technology fWeapons; + private Technology fShields; + private Technology fMini; + + public ResearchLab (TechProfile profile) + { + fRange = new Technology ("Range", profile.getRange()); + fSpeed = new Technology ("Speed", profile.getSpeed()); + fWeapons = new Technology ("Weapons", profile.getWeapons()); + fShields = new Technology ("Shields", profile.getShields()); + fMini = new Technology ("Mini", profile.getMini()); + + fTechBudget = new Budget ("Technology"); + fTechBudget.addBudgetItem (new BudgetItem(fRange, 20)); + fTechBudget.addBudgetItem (new BudgetItem(fSpeed, 20)); + fTechBudget.addBudgetItem (new BudgetItem(fWeapons, 20)); + fTechBudget.addBudgetItem (new BudgetItem(fShields, 20)); + fTechBudget.addBudgetItem (new BudgetItem(fMini, 20)); + } + + public String getName () + { + return "Technology"; + } + + public void invest (long investment) + { + fTechBudget.invest (investment); + } + + public TechProfile getTechProfile () + { + int range = fRange.getLevel (); + int speed = fSpeed.getLevel (); + int weapons = fWeapons.getLevel (); + int shields = fShields.getLevel (); + int mini = fMini.getLevel (); + return new TechProfile (range, speed, weapons, shields, mini); + } + + public Budget getTechnologyBudget () + { + return fTechBudget; + } + +} diff --git a/test/src/share/classes/ibmspace/server/Settlement.java b/test/src/share/classes/ibmspace/server/Settlement.java new file mode 100644 index 000000000..0d48269ec --- /dev/null +++ b/test/src/share/classes/ibmspace/server/Settlement.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + +// +// A settlement represents the settlement of a planet by a player. +// Each player maitains a list of its current settlements and can +// use these to control and access the planet while settled. +// + + +public class Settlement implements java.io.Serializable +{ + private Player fPlayer = null; + private PlanetImpl fPlanet = null; + + private Budget fBudget = null; + private Terraforming fTerraforming = null; + private Mining fMining = null; + private Population fPopulation = null; + + public Settlement (Player player, PlanetImpl planet, long initialSize) + { + fPlayer = player; + fPlanet = planet; + + if ( fPlanet == null ) { + System.out.println ("fPlanet is null"); + throw new Error ("Settlement.Settlement () - fPlanet is null"); + } + + double temp = fPlayer.getIdealTemp (); + + fTerraforming = new Terraforming (fPlanet, temp); + fMining = new Mining (fPlanet, fPlayer); + fBudget = new Budget (fPlanet.getName()); + fBudget.addBudgetItem (new BudgetItem (fTerraforming, 50)); + fBudget.addBudgetItem (new BudgetItem (fMining, 50)); + + fPopulation = new Population (fPlanet, initialSize); + } + + public Player getOwner () + { + return fPlayer; + } + + public Budget getBudget () + { + return fBudget; + } + + public Population getPopulation () + { + return fPopulation; + } + + public long getIncome () + { + if ( fPopulation == null ) System.out.println ("fPopulation is null!!"); + if ( fPlanet == null ) System.out.println ("fPlanet is null!!"); + if ( fPlayer == null ) System.out.println ("fPlayer is null!!"); + + return (long)(fPopulation.getIdealIncome() * fPlanet.getSuitabilityFor(fPlayer)); + } + + public void growPopulation () + { + fPopulation.grow (fPlanet.getSuitabilityFor(fPlayer)); + } + +} diff --git a/test/src/share/classes/ibmspace/server/ShipSavings.java b/test/src/share/classes/ibmspace/server/ShipSavings.java new file mode 100644 index 000000000..557135f2b --- /dev/null +++ b/test/src/share/classes/ibmspace/server/ShipSavings.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + + +public class ShipSavings implements Investment, java.io.Serializable +{ + private long fSavings; + private double fInterestRate; + + public ShipSavings (long initial) + { + fSavings = initial; + fInterestRate = 0.07; + } + + public ShipSavings () + { + fSavings = 0; + fInterestRate = 0.07; + } + + public String getName () + { + return "Ship Savings"; + } + + public void setInterestRate (double rate) + { + fInterestRate = rate; + } + + public double getInterestRate () + { + return fInterestRate; + } + + public long computeInterest () + { + return (long)(fSavings * fInterestRate); + } + + public void invest (long investment) + { + fSavings += computeInterest (); + fSavings += investment; + } + + public long getSavings () + { + return fSavings; + } + + public void withdraw (long amount) + { + fSavings -= amount; + } + + + +} diff --git a/test/src/share/classes/ibmspace/server/SpaceConquestServer.java b/test/src/share/classes/ibmspace/server/SpaceConquestServer.java new file mode 100644 index 000000000..bdd5a90ef --- /dev/null +++ b/test/src/share/classes/ibmspace/server/SpaceConquestServer.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// This server is bound with the name server and is the first stop +// for all clients joining the game. Each client uses this server +// to (1) get the basic map of the galaxy sans specific details they +// learn about planets later during play, and (2) get a player- +// specific game view server to represent a player-specific view of +// the game. This models the fact that each player only sees the +// parts of the galaxy they experience through play. So, for example, +// a player only sees the current temperature, etc, of a planer when +// he/she has ships stationed there or has a colony there. + +package ibmspace.server; + +import ibmspace.common.GameView; +import ibmspace.common.Planet; +import ibmspace.common.SpaceConquest; + +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; +import java.lang.reflect.Array; +import java.rmi.RMISecurityManager; +import java.rmi.RemoteException; +import java.util.Vector; + +public class SpaceConquestServer extends PortableRemoteObject implements SpaceConquest +{ + private Game fGame; + private int fRequiredPlayers = 0; + private int fNumberOfPlayers = 0; + private Vector fViews; + + public SpaceConquestServer (int numPlayers) throws RemoteException + { + fGame = new Game (numPlayers); + fViews = new Vector (); + fRequiredPlayers = numPlayers; + } + + public SpaceConquestServer () throws RemoteException + { + fGame = new Game (1); + fViews = new Vector (); + fRequiredPlayers = 1; + } + + private synchronized void waitForAllPlayers () + { + try + { + if ( fNumberOfPlayers < fRequiredPlayers ) { + wait (); + } else { + notifyAll (); + } + } + catch (InterruptedException e) + { + } + } + + public synchronized GameView joinGame (String playerName) throws RemoteException + { + if ( fGame.isGameStarted() ) { + // Probably should throw an exception here + // This is to prevent players from joining after the required + // number of players have joined and the game has started. + System.out.println (playerName + " tried to join started game"); + return null; + } + + fGame.logCall (); + double idealTemp = PlanetImpl.RandomTemp (); + double idealGravity = PlanetImpl.RandomGravity (); + Player player = new Player (playerName, idealTemp, idealGravity); + fGame.addPlayer (player); + fNumberOfPlayers++; + + GameView view; + + if ( fRequiredPlayers == 1 ) { + view = new GameViewImpl (fGame, player); + } else { + view = new GameViewServer (fGame, player); + } + + fViews.addElement (view); + waitForAllPlayers (); + return view; + } + + public void quitGame (GameView gameView) throws RemoteException + { + gameView.quit (); + fNumberOfPlayers--; + if ( fNumberOfPlayers == 0 ) PortableRemoteObject.unexportObject (this); + } + + public synchronized Planet[] getGalaxyMap () throws RemoteException + { + Planet[] planets = fGame.createGalaxyMap (); + return planets; + } + + public synchronized int getNumberOfPlanets () throws RemoteException + { + Planet[] planets = getGalaxyMap (); + return Array.getLength (planets); + } + + public synchronized Planet getPlanet (int index) throws RemoteException + { + Planet[] planets = getGalaxyMap (); + return planets[index]; + } + + private static InitialContext context ; + + public static void main (String[] args) + { + int numPlayers = 1; + + if ( Array.getLength (args) != 0 ) { + numPlayers = (Integer.valueOf (args[0])).intValue(); + } + + try + { + if ( System.getSecurityManager() == null ) { + System.setSecurityManager (new RMISecurityManager()); + } + + SpaceConquestServer obj = new SpaceConquestServer (numPlayers); + + // Pass system properties with -D option of java command, e.g. + // -Djava.naming.factory.initial=< name of factory to use> + + context = new InitialContext (); + context.rebind ("SpaceConquest", obj); + System.out.println ("SpaceConquest server bound in registry"); + } + catch (Exception e) + { + System.out.println ("SpaceConquest Server Exception: " + e.getMessage()); + e.printStackTrace (); + } + } + + +} diff --git a/test/src/share/classes/ibmspace/server/Technology.java b/test/src/share/classes/ibmspace/server/Technology.java new file mode 100644 index 000000000..a9a7a67fc --- /dev/null +++ b/test/src/share/classes/ibmspace/server/Technology.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + + +public class Technology implements Investment, java.io.Serializable +{ + private String fName; + private int fLevel; + private long fInvestment; + private long fRequiredInvestment; + + static private int UNIT_INVESTMENT = 1000; + + public Technology (String name, int initialLevel) + { + fName = name; + fLevel = initialLevel; + fInvestment = 0; + fRequiredInvestment = (fLevel+1) * UNIT_INVESTMENT; + } + + public String getName () + { + return fName; + } + + public void invest (long investment) + { + // formula: 1. each level requires level* UNIT_INVESTMENT to reach + // 2. investments are dampened by a random percentage + + fInvestment += investment * Math.random () * 1.25; + if ( fInvestment >= fRequiredInvestment ) { + fLevel ++; + fInvestment -= fRequiredInvestment; + fRequiredInvestment = (fLevel+1) * UNIT_INVESTMENT; + } + + } + + public int getLevel () + { + return fLevel; + } + +} diff --git a/test/src/share/classes/ibmspace/server/Terraforming.java b/test/src/share/classes/ibmspace/server/Terraforming.java new file mode 100644 index 000000000..d55e21ca0 --- /dev/null +++ b/test/src/share/classes/ibmspace/server/Terraforming.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.server; + + +public class Terraforming implements Investment, java.io.Serializable +{ + // Cost in dollars to move temp 10% towards ideal + public static double TERRAFORMING_COST = 1000.0; + + PlanetImpl fPlanet; + double fIdealTemp; + + public Terraforming (PlanetImpl planet, double idealTemp) + { + fPlanet = planet; + fIdealTemp = idealTemp; + } + + public String getName () + { + return "Terraforming"; + } + + public void invest (long dollars) + { + if ( dollars > 0 ) { + double d = dollars; + double temp = fPlanet.getTemp (); + int diff = (int)(temp - fIdealTemp); + int absdiff = Math.abs (diff); + //int sign = diff/absdiff; + + if ( absdiff == 0 ) { + fPlanet.setTemp (fIdealTemp); + } else { + double efficiency = 1.0/absdiff; + double percentChange = d/1000.0 * 0.1 * efficiency; + + if ( percentChange > 1 ) { + percentChange = 1; + } + + double newTemp = temp*(1-percentChange) + fIdealTemp*percentChange; + fPlanet.setTemp (newTemp); + } + } + } + +} diff --git a/test/src/share/classes/ibmspace/spacetest/SpaceTest.java b/test/src/share/classes/ibmspace/spacetest/SpaceTest.java new file mode 100644 index 000000000..0463c5a09 --- /dev/null +++ b/test/src/share/classes/ibmspace/spacetest/SpaceTest.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package ibmspace.spacetest; + +import ibmspace.common.BudgetSummary; +import ibmspace.common.GameView; +import ibmspace.common.Planet; +import ibmspace.common.PlanetView; +import ibmspace.common.SpaceConquest; +import java.rmi.Remote; +import test.ServantContext; +import test.RemoteTest; +import javax.rmi.PortableRemoteObject; + +import java.lang.reflect.Array; +import org.glassfish.pfl.test.JUnitReportHelper; + +public class SpaceTest extends RemoteTest { + + private static final String servantClass = "ibmspace.server.SpaceConquestServer"; + private static final String[] compileEm = + { + "ibmspace.server.SpaceConquestServer", + "ibmspace.server.GameViewServer" + }; + + private static final int TIMING_ITERATIONS = 100; + + /** + * Return an array of fully qualified remote servant class + * names for which ties/skels need to be generated. Return + * empty array if none. + */ + + protected String[] getRemoteServantClasses () { + return compileEm; + } + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + if (iiop) { + String[] ourArgs = {"-always", "-keep"}; + return super.getAdditionalRMICArgs(ourArgs); + } else { + return super.getAdditionalRMICArgs(currentArgs); + } + } + + /** + * Perform the test. + * @param context The context returned by getServantContext(). + */ + + public void doTest (ServantContext context) throws Throwable { + JUnitReportHelper helper = new JUnitReportHelper( + this.getClass().getName() + + ( iiop ? "_iiop" : "_jrmp" ) ) ; + + helper.start( "spaceTest" ) ; + + try { + // First ensure that the caches are cleared out so + // that we can switch between IIOP and JRMP... + + //Utility.clearCaches(); + + Remote remote = context.startServant(servantClass,"SpaceConquest",true,iiop); + + if (remote == null) { + throw new Exception ("startServant() failed"); + } + + // Try narrow... + + SpaceConquest game = (SpaceConquest)PortableRemoteObject.narrow(remote,SpaceConquest.class); + + if (game == null) { + throw new Exception ("narrow() failed for remote"); + } + + GameView gameView = game.joinGame ("Test"); + + Planet[] planets = game.getGalaxyMap (); + + int numPlanets = Array.getLength (planets); + PlanetView[] planetViews = new PlanetView [numPlanets]; + BudgetSummary[] planetBudgets = new BudgetSummary [numPlanets]; + + for (int i=0; i 0 && className.charAt(last+1) == 'L') { + helper.pass() ; + return null; + } + } + + String msg = "Got null codebase from JDKBridge.getCodebase("+result+")"; + helper.fail( msg ) ; + throw new Error(msg) ; + } + + if (!codebase.equals(remoteCodebase)) { + String msg = "getCodebase('"+result+"') returned '"+codebase+"' != expected '"+remoteCodebase+"'"; + helper.fail( msg ) ; + throw new Error(msg) ; + } + } + + helper.pass() ; + return result; + } + + private WebServer webServer = null; + private String remoteCodebase = null; + + public void setup () { + try { + + // Make sure WE know the codebase... + + remoteCodebase = System.getProperty("java.rmi.server.codebase"); + if (remoteCodebase == null) { + throw new Error("No codebase set"); + } + + // Pull the port # out of the codebase... + + int port = 9090; // Default; + + int host = remoteCodebase.indexOf("//"); + if (host > 0) { + host += 2; + int colon = remoteCodebase.indexOf(":",host); + if (colon > 0) { + int length = remoteCodebase.length(); + int slash = remoteCodebase.indexOf('/',colon); + if (slash > 0) { + length = slash; + } + String portStr = remoteCodebase.substring(colon+1,length); + port = Integer.parseInt(portStr); + } + } + + // Make sure that JDKBridge does not know the codebase... + + JDKBridge.setLocalCodebase(null); + if (JDKBridge.getLocalCodebase() != null) { + throw new Error("Could not clear local codebase."); + } + + // Start the webserver pointing at the correct doc root... + + String rootPath = System.getProperty("http.server.root.directory"); + if (rootPath == null) { + throw new Error("http.server.root.directory not set"); + } + File rootDir = new File(rootPath); + webServer = new WebServer(port,rootDir,1); + webServer.start(); + if (!webServer.waitTillReady()){ + throw new Error("WebServer died"); + } + + } catch (Exception e) { + throw new Error ("setup() failed, caught "+e); + } + } + + public void run() { + try { + doTests(); + } finally { + if (webServer != null) { + webServer.quit(); + } + } + } + + public class InnerA {} + public interface InnerB {} +} diff --git a/test/src/share/classes/javax/rmi/Dog.java b/test/src/share/classes/javax/rmi/Dog.java new file mode 100644 index 000000000..168a327c9 --- /dev/null +++ b/test/src/share/classes/javax/rmi/Dog.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + + +import java.rmi.RemoteException; + +public interface Dog +{ + String bark () throws RemoteException; + void die () throws RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/DogImpl.java b/test/src/share/classes/javax/rmi/DogImpl.java new file mode 100644 index 000000000..9731caf00 --- /dev/null +++ b/test/src/share/classes/javax/rmi/DogImpl.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.lang.String; +import java.rmi.RemoteException; + + +public class DogImpl implements Dog, java.io.Serializable +{ + private String fBark = "Rrruf!"; + + public DogImpl (String bark) + { + fBark = bark; + } + + public String bark () throws RemoteException + { + return fBark; + } + + public void die () throws RemoteException + { + } +} diff --git a/test/src/share/classes/javax/rmi/DogServer.java b/test/src/share/classes/javax/rmi/DogServer.java new file mode 100644 index 000000000..e0fd73b6d --- /dev/null +++ b/test/src/share/classes/javax/rmi/DogServer.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.lang.String; +import java.rmi.RemoteException; +import javax.rmi.PortableRemoteObject; + +public class DogServer extends DogImpl implements RemoteDog +{ + public DogServer(String bark) throws RemoteException + { + super (bark); + PortableRemoteObject.exportObject (this); + } + + public void die () throws RemoteException + { + super.die (); + PortableRemoteObject.unexportObject (this); + } + +} diff --git a/test/src/share/classes/javax/rmi/HashCode.java b/test/src/share/classes/javax/rmi/HashCode.java new file mode 100644 index 000000000..052024152 --- /dev/null +++ b/test/src/share/classes/javax/rmi/HashCode.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; +public interface HashCode extends java.rmi.Remote { +} + diff --git a/test/src/share/classes/javax/rmi/HashCodeA.java b/test/src/share/classes/javax/rmi/HashCodeA.java new file mode 100644 index 000000000..c7e8c6f71 --- /dev/null +++ b/test/src/share/classes/javax/rmi/HashCodeA.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; +public interface HashCodeA extends java.rmi.Remote { +} + diff --git a/test/src/share/classes/javax/rmi/HashCodeAImpl.java b/test/src/share/classes/javax/rmi/HashCodeAImpl.java new file mode 100644 index 000000000..06ca5bf78 --- /dev/null +++ b/test/src/share/classes/javax/rmi/HashCodeAImpl.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; +public class HashCodeAImpl extends PortableRemoteObject implements HashCodeA { + public HashCodeAImpl() throws java.rmi.RemoteException {} +} + diff --git a/test/src/share/classes/javax/rmi/HashCodeImpl.java b/test/src/share/classes/javax/rmi/HashCodeImpl.java new file mode 100644 index 000000000..0a3a18547 --- /dev/null +++ b/test/src/share/classes/javax/rmi/HashCodeImpl.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; +public class HashCodeImpl extends PortableRemoteObject implements HashCode { + public HashCodeImpl() throws java.rmi.RemoteException {} +} diff --git a/test/src/share/classes/javax/rmi/PROHello.java b/test/src/share/classes/javax/rmi/PROHello.java new file mode 100644 index 000000000..92b7cefb1 --- /dev/null +++ b/test/src/share/classes/javax/rmi/PROHello.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface PROHello extends Remote { + public static final String HELLO = "Hi!"; + public String sayHello () throws RemoteException; + public Dog getDogValue () throws RemoteException; + public Dog getDogServer () throws RemoteException; + public void unexport () throws RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/PROImpl.java b/test/src/share/classes/javax/rmi/PROImpl.java new file mode 100644 index 000000000..7de57722b --- /dev/null +++ b/test/src/share/classes/javax/rmi/PROImpl.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import com.sun.corba.ee.spi.JndiConstants; + +import javax.naming.InitialContext; +import java.rmi.RemoteException; + +public class PROImpl extends PortableRemoteObject implements PROHello { + + public PROImpl () throws RemoteException { + super(); + } + + public String sayHello () throws RemoteException { + return HELLO; + } + + public Dog getDogValue () throws RemoteException { + return new DogImpl ("Bow wow!"); + } + + public Dog getDogServer () throws RemoteException { + return new DogServer ("Yip Yip Yip!"); + } + + public void unexport () throws RemoteException { + PortableRemoteObject.unexportObject(this); + } + + private static InitialContext context ; + + public static void main (String[] args) { + + // args[0] == 'iiop' || 'jrmp' + // args[1] == publishName + + try { + + if (args[0].equalsIgnoreCase("iiop")) { + System.getProperties().put("java.naming.factory.initial", JndiConstants.COSNAMING_CONTEXT_FACTORY); + } else if (args[0].equalsIgnoreCase("jrmp")) { + System.getProperties().put("java.naming.factory.initial", JndiConstants.REGISTRY_CONTEXT_FACTORY); + } + + context = new InitialContext (); + context.rebind (args[1], new PROImpl()); + + } catch (Exception e) { + System.out.println ("Caught: " + e.getMessage()); + } + } +} diff --git a/test/src/share/classes/javax/rmi/PROImpl2.java b/test/src/share/classes/javax/rmi/PROImpl2.java new file mode 100644 index 000000000..693450ba5 --- /dev/null +++ b/test/src/share/classes/javax/rmi/PROImpl2.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public class PROImpl2 implements PROHello { + + public PROImpl2 () throws RemoteException { + super(); + } + + public String sayHello () throws RemoteException { + return HELLO; + } + + public Dog getDogValue () throws RemoteException { + return new DogImpl ("Bow wow!"); + } + + public Dog getDogServer () throws RemoteException { + return new DogServer ("Yip Yip Yip!"); + } + + public void unexport () throws RemoteException { + PortableRemoteObject.unexportObject(this); + } +} diff --git a/test/src/share/classes/javax/rmi/PROTest.java b/test/src/share/classes/javax/rmi/PROTest.java new file mode 100644 index 000000000..7e4122d15 --- /dev/null +++ b/test/src/share/classes/javax/rmi/PROTest.java @@ -0,0 +1,701 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.NoSuchObjectException; +import java.rmi.server.ExportException; +import test.ServantContext; +import test.RemoteTest; +import com.sun.corba.ee.impl.util.Utility; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import java.io.ObjectOutputStream; +import java.io.ObjectInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ByteArrayInputStream; +import javax.rmi.CORBA.Util; +import javax.rmi.CORBA.Tie; +import javax.naming.Context; +import com.sun.org.omg.SendingContext.CodeBase; +import alpha.bravo.Multi; + +import com.sun.corba.ee.spi.presentation.rmi.StubAdapter ; +import com.sun.corba.ee.spi.presentation.rmi.PresentationManager ; +import org.glassfish.pfl.test.JUnitReportHelper; + +/* + * @test + */ +public class PROTest extends RemoteTest { + + private static final String servantName = "PROServer"; + private static final String servantClass = "javax.rmi.PROImpl"; + private static final String[] compileEm = { + "javax.rmi.PROImpl", + "javax.rmi.PROImpl2", + "javax.rmi.DogServer", + "javax.rmi.ServantInner", + "javax.rmi.ServantOuter.Inner", + "rmic.OnlyRemoteServant", + "javax.rmi.HashCodeImpl", + "javax.rmi.HashCodeAImpl", + "alpha.bravo.Multi", + }; + + private static final int TIMING_ITERATIONS = 100; + + /** + * Return an array of fully qualified remote servant class + * names for which ties/skels need to be generated. Return + * empty array if none. + */ + protected String[] getRemoteServantClasses () { + return compileEm; + } + + /** + * Append additional (i.e. after -iiop and before classes) rmic arguments + * to 'currentArgs'. This implementation will set the output directory if + * the OUTPUT_DIRECTORY flag was passed on the command line. + */ + protected String[] getAdditionalRMICArgs (String[] currentArgs) { + if (iiop) { + String[] ourArgs = {"-always", "-keep"}; + return super.getAdditionalRMICArgs(ourArgs); + } else { + return super.getAdditionalRMICArgs(currentArgs); + } + } + + private final JUnitReportHelper helper ; + private boolean first = true ; + + public PROTest() { + helper = new JUnitReportHelper( this.getClass().getName() + + ( iiop ? "_iiop" : "_jrmp" ) ) ; + } + + private void newTest( String name ) { + if (first) + first = false ; + else + helper.pass() ; + + helper.start( name ) ; + } + + /** + * Perform the test. + * @param context The context returned by getServantContext(). + */ + public void doTest (ServantContext context) throws Throwable { + try { + dprint( "test starts" ) ; + boolean usesDynamicStubs = + com.sun.corba.ee.spi.orb.ORB.getPresentationManager(). + useDynamicStubs() ; + + // Certain tests that depend on the absence of iiop stubs and ties + // cannot function correctly with dynamic RMI-IIOP, since + // dynamic RMI-IIOP can always create any needed stub or tie. + // We assume that JRMP is only usable when we are not using + // dynamic RMI-IIOP. Since we test the JRMP case in static mode + // anyway, we'll just return here in the dynamic case for JRMP. + if (usesDynamicStubs && !iiop) + return ; + + // First ensure that the caches are cleared out so + // that we can switch between IIOP and JRMP... + + Utility.clearCaches(); + + // Check toStub(). First try an unconnected servant... + + PROImpl localImpl = new PROImpl(); + Remote stub = PortableRemoteObject.toStub(localImpl); + boolean fail = false; + + newTest( "test_1" ) ; + ORB defaultORB = context.getORB(); + + if (iiop) { + Tie tie = Util.getTie(localImpl); + tie.orb(defaultORB); + } + + stub = PortableRemoteObject.toStub(localImpl); + if (stub == null) { + throw new Exception ("toStub() on connected servant failed."); + } + + // Make sure second export fails... + newTest( "test_2" ) ; + boolean exportFail = false; + try { + PortableRemoteObject.exportObject(localImpl); + } catch (ExportException e) { + exportFail = true; + } + + if (!exportFail) { + throw new Exception ("exportObject twice did not fail"); + } + + // Try narrow on local stub... + newTest( "test_3" ) ; + PROHello stubref = (PROHello) PortableRemoteObject.narrow(stub,PROHello.class); + + if (stubref == null) { + throw new Exception ("narrow() failed for stub"); + } + + newTest( "test_4" ) ; + Remote remote = context.startServant(servantClass,servantName,true,iiop); + + if (remote == null) { + throw new Exception ("startServant() failed"); + } + + + newTest( "test_5" ) ; + PROHello objref = (PROHello) PortableRemoteObject.narrow(remote,PROHello.class); + if (objref == null) { + throw new Exception ("narrow() failed for remote"); + } + + newTest( "test_6" ) ; + if (!objref.sayHello().equals(PROHello.HELLO)) { + throw new Exception("sayHello() failed"); + } + + newTest( "test_7" ) ; + String bark; + Dog dogValue = objref.getDogValue (); + if ( dogValue == null ) { + throw new Exception ("sayHello() dogValue is null"); + } + bark = dogValue.bark (); + + newTest( "test_8" ) ; + Dog dogServer = objref.getDogServer (); + if ( dogValue == null ) { + throw new Exception ("sayHello() dogServer is null"); + } + bark = dogServer.bark (); + + newTest( "test_9" ) ; + boolean unexportFail = false; + try { + PortableRemoteObject.unexportObject(objref); + } catch (NoSuchObjectException e) { + unexportFail = true; + } + + if (!unexportFail) { + throw new Exception("unexport of stub succeeded!"); + } + + // Now get a round-trip timing... + newTest( "test_10" ) ; + + if (verbose) { + int count = TIMING_ITERATIONS; + long startTime = System.currentTimeMillis(); + while (count-- > 0) { + String hello = objref.sayHello(); + } + long roundTrip = (System.currentTimeMillis() - startTime) / TIMING_ITERATIONS; + System.out.print("Round-trip time for sayHello() = " + + roundTrip + " ms average over " + TIMING_ITERATIONS + " iterations."); + } + + newTest( "test_11" ) ; + // Now check stub streaming and connect(stub,stub)... + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream os = new ObjectOutputStream(bos); + os.writeObject(objref); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + ObjectInputStream is = new ObjectInputStream(bis); + PROHello newRef = (PROHello) is.readObject(); + + if (newRef == null) { + throw new Exception("Stub streaming failed."); + } + + newTest( "test_12" ) ; + fail = false; + try { + newRef.sayHello(); + } catch (RemoteException e) { + if (e.getMessage().startsWith("CORBA BAD_OPERATION 0")) { + fail = true; + } + } + if (iiop && !fail) { + throw new Exception("sayHello on unconnected stub succeeded."); + } + + newTest( "test_13" ) ; + // Now connect it up (stub,stub) and make sure we can call + // methods on it... + + PortableRemoteObject.connect(newRef,objref); + if (!newRef.sayHello().equals(PROHello.HELLO)) { + throw new Exception("connect(stub,stub) failed"); + } + + // Now make sure that they are equal... + + if (newRef.hashCode() != objref.hashCode()) { + throw new Exception("newRef.hashCode() != objref.hashCode()"); + } + + if (!newRef.equals(objref)) { + throw new Exception("newRef != objref"); + } + + newTest( "test_14" ) ; + // Try connect(impl,impl)... + + PROImpl localImpl2 = new PROImpl(); + PortableRemoteObject.connect(localImpl2,localImpl); + try { + PortableRemoteObject.toStub(localImpl2); + } catch (NoSuchObjectException e) { + throw new Exception ("connect(impl,impl) failed"); + } + + // Try connect(stub,impl)... + + newTest( "test_15" ) ; + ObjectInputStream is2 = new ObjectInputStream(new ByteArrayInputStream( + bos.toByteArray())); + PROHello newRef2 = (PROHello) is2.readObject(); + PortableRemoteObject.connect(newRef2,localImpl2); + if (!newRef.sayHello().equals(PROHello.HELLO)) { + throw new Exception("connect(stub,impl) failed"); + } + + newTest( "test_16" ) ; + // Try connect(impl,stub)... + + PROImpl localImpl3 = new PROImpl(); + PortableRemoteObject.connect(localImpl3,objref); + try { + PortableRemoteObject.toStub(localImpl3); + } catch (NoSuchObjectException e) { + throw new Exception ("connect(impl,stub) failed"); + } + + newTest( "test_17" ) ; + // Make sure that trying to connect an already connected object + // succeeds when the ORBs are the same... + + PortableRemoteObject.connect(objref,localImpl3); + PortableRemoteObject.connect(localImpl3,objref); + + newTest( "test_18" ) ; + // Make sure that trying to connect an already connected object fails + // when the ORBs are different... + + PROImpl newLocalImpl = new PROImpl(); + if (iiop) { + ORB newORB = ORB.init(new String[]{},null); + Tie newTie = Util.getTie(newLocalImpl); + newTie.orb(newORB); + } + PROHello newObjRef = (PROHello) PortableRemoteObject.toStub(newLocalImpl); + + boolean callFailed = false; + try { + PortableRemoteObject.connect(objref,newLocalImpl); + } catch (RemoteException e) { + callFailed = true; + } + if (!callFailed) { + if (iiop) { + throw new Exception ("Second connect(stub,impl) succeeded"); + } else { + // System.out.println("REMINDER: document connect and JRMP!"); + } + } + + callFailed = false; + try { + PortableRemoteObject.connect(localImpl3,newObjRef); + } catch (RemoteException e) { + callFailed = true; + } + if (!callFailed) { + if (iiop) { + throw new Exception ("Second connect(impl,stub) succeeded"); + } else { + // System.out.println("REMINDER: document connect and JRMP!"); + } + } + + if (iiop) { + newTest( "test_19" ) ; + // Now export an implementation, get a stub for it, make sure they + // are both unconnected, then connect the stub and make sure they + // are *both* connected... + + PROImpl theImpl = new PROImpl(); + Tie theTie = Util.getTie(theImpl); + org.omg.CORBA.Object theStub = + (org.omg.CORBA.Object)PortableRemoteObject.toStub(theImpl); + callFailed = false; + try { + theTie.orb(); + } catch (SystemException e) { + callFailed = true; + } + if (!callFailed) { + throw new Exception ("theTie already connected"); + } + callFailed = false; + try { + StubAdapter.getDelegate( theStub ); + } catch (SystemException e) { + callFailed = true; + } + if (!callFailed) { + throw new Exception ("theStub already connected"); + } + + StubAdapter.connect( theStub, defaultORB ); // Connect both! + if (theTie.orb() != defaultORB) { + throw new Exception("theTie.orb() != defaultORB"); + } + if (StubAdapter.getDelegate( theStub ).orb(theStub) != defaultORB) { + throw new Exception("theStub.orb() != defaultORB"); + } + + if (Utility.getAndForgetTie(theStub) != null) { + throw new Exception("Utility.getAndForgetTie(theStub) != null"); + } + } + + // Now repeat the same test, only this time use JNDI to do the + // connect on the stub, to insure that our updated CNCtx code + // with "auto-connect" works correctly... + + Context nameContext = context.getNameContext(); + + if (iiop) { + newTest( "test_20" ) ; + PROImpl theImpl = new PROImpl(); + Tie theTie = Util.getTie(theImpl); + org.omg.CORBA.Object theStub = + (org.omg.CORBA.Object)PortableRemoteObject.toStub(theImpl); + callFailed = false; + try { + theTie.orb(); + } catch (SystemException e) { + callFailed = true; + } + if (!callFailed) { + throw new Exception ("(nameContext) theTie already connected"); + } + callFailed = false; + try { + StubAdapter.getDelegate( theStub ); + } catch (SystemException e) { + callFailed = true; + } + if (!callFailed) { + throw new Exception ("(nameContext) theStub already connected"); + } + + nameContext.rebind("PROTest auto-connect",theStub); // Connect both! + + if (theTie.orb() != defaultORB) { + throw new Exception("(nameContext) theTie.orb() != defaultORB"); + } + if (StubAdapter.getDelegate( theStub ).orb(theStub) != defaultORB) { + throw new Exception("(nameContext) theStub.orb() != defaultORB"); + } + + if (Utility.getAndForgetTie(theStub) != null) { + throw new Exception("(nameContext) Utility.getAndForgetTie(theStub) != null"); + } + } + + // Now unexport remote object and make sure we can no longer invoke it... + newTest( "test_21" ) ; + + objref.unexport(); + callFailed = false; + try { + objref.sayHello(); + } catch (RemoteException e) { + callFailed = true; + } + + if (!callFailed) { + if (iiop) { + throw new Exception("unexportObject() failed"); + } else { + // System.out.print("Warning: PortableRemoteObject.unexportObject() NOP on pre 1.2 JRMP!"); + } + } + + // Now unexport our local instance... + newTest( "test_22" ) ; + + PortableRemoteObject.unexportObject(localImpl); + + // Make sure we cannot unexport an object which was never exported... + newTest( "test_23" ) ; + + fail = false; + try { + PortableRemoteObject.unexportObject(new PROImpl2() ); + } catch (NoSuchObjectException e) { + fail = true; + } + + if (!fail) { + if (iiop) { + throw new Exception ("unexportObject() on unconnected servant succeeded."); + } else { + // System.out.print("Warning: unexportObject() on unconnected servant succeeded on JRMP!"); + } + } + + newTest( "test_24" ) ; + // Now make sure that trying to publish an unexported impl + // fails... + + callFailed = false; + try { + nameContext.rebind("foo",new PROImpl2()); + } catch (javax.naming.NamingException e) { + Throwable cause = e.getRootCause(); + if (cause != null) { + if (cause instanceof java.rmi.NoSuchObjectException) { + callFailed = true; + } else { + callFailed = true; + if (iiop) { + System.out.print("Warning: Publish unexported impl root cause: " + cause.getClass().getName()); + } + } + } + } catch (Exception e) { + callFailed = true; + System.out.print("Warning: Publish unexported impl caught: " + e); + } + + if (!callFailed) { + if (iiop) { + throw new Exception("Publish unexported impl succeeded!"); + } else { + // System.out.print("Warning: Publish unexported impl succeeded on 1.1.6/JRMP!"); + } + } + + // Now make sure that we cannot call toStub with our unexported object... + newTest( "test_25" ) ; + + callFailed = false; + try { + PortableRemoteObject.toStub(localImpl); + } catch (NoSuchObjectException e) { + callFailed = true; + } + + if (!callFailed) { + if (iiop) { + throw new Exception("toStub on unexported impl succeeded!"); + } else { + // System.out.print("Warning: toStub on unexported impl succeeded on JRMP!"); + } + } + + newTest( "test_26" ) ; + // Now fire up our servant which implements an inner interface and + // make sure we can talk to it... + + Remote inner = context.startServant("javax.rmi.ServantInner","inner",false,iiop); + SInner innerRef = (SInner) + PortableRemoteObject.narrow(inner,SInner.class); + if (!innerRef.echo(innerRef).equals(innerRef)) { + throw new Exception("innerRef.echo(innerRef) != innerRef"); + } + + if (iiop) { // _REVISIT_ This does not work on JRMP - why not? + newTest( "test_27" ) ; + // Now fire up our servant which implements an outer interface and + // make sure we can talk to it... + + Remote outer = context.startServant("javax.rmi.ServantOuter$Inner","outer",false,iiop); + ServantOuter outerRef = (ServantOuter) + PortableRemoteObject.narrow(outer,ServantOuter.class); + if (!outerRef.echo(outerRef).equals(outerRef)) { + throw new Exception("innerRef.echo(outerRef) != outerRef"); + } + } + + newTest( "test_28" ) ; + // Make sure we can pass an IDL reference across our RMI stub... + CodeBase cb = innerRef.getCodeBase(); + if (cb == null) { + throw new Exception("innerRef.getCodeBase() == null"); + } + + newTest( "test_29" ) ; + // Make sure we can pass a servant which only implements Remote... + Remote r = innerRef.getOnlyRemote(); + if (r == null) { + throw new Exception("innerRef.getOnlyRemote() == null"); + } + + newTest( "test_30" ) ; + // Make sure we can get a stub for a servant which only implements + // Remote... + Remote onlyRemoteStub = PortableRemoteObject.toStub( + new rmic.OnlyRemoteServant()); + if (onlyRemoteStub == null) { + throw new Exception("onlyRemoteStub == null"); + } + + newTest( "test_31" ) ; + // Hashcode regression test. Ensure that stubs for two distincts types + // have different hashCodes. This code is (effectively) a copy of the + // Sun East HashCodeTests.HashCode0002() method. + + // This is really a bogus test, as it can always fail the hashcode + // comparison, but not be equal... + + nameContext.rebind("HashCode",new HashCodeImpl()); + nameContext.rebind("HashCodeA",new HashCodeAImpl()); + Object hashCodeObject = nameContext.lookup("HashCode"); + Object hashCodeAObject = nameContext.lookup("HashCodeA"); + HashCode hashCodeStub = + (HashCode)PortableRemoteObject.narrow(hashCodeObject,HashCode.class); + HashCodeA hashCodeAStub = + (HashCodeA)PortableRemoteObject.narrow(hashCodeAObject,HashCodeA.class); + int hashCode = hashCodeStub.hashCode(); + int hashCodeA = hashCodeAStub.hashCode(); + + if (hashCode == hashCodeA) { + System.out.println("hashCode == hashCodeA ("+hashCode+")"); + if (hashCodeStub.equals(hashCodeAStub)) { + throw new Exception("hashCodeStub.equals(hashCodeAStub)"); + } + } + + // RegisterTarget regression test. The Stub was being cached for + // the tie, and it's delegate was not cleared. The stub is now + // removed from the cache by the Util.unexportObject() method. + if (iiop) { + newTest( "test_32" ) ; + // Create/get tie for impl... + + PROImpl obj = new PROImpl(); + Tie tie = Util.getTie(obj); + + nameContext.rebind("RegisterTarget", obj); + PortableRemoteObject.unexportObject(obj); + Util.registerTarget(tie, obj); + nameContext.rebind("RegisterTarget", obj); + + // Lookup it up and make sure it is alive... + Object registerObject = nameContext.lookup("RegisterTarget"); + PROHello registerRef = (PROHello)PortableRemoteObject.narrow(registerObject, PROHello.class); + if (!registerRef.sayHello().equals(PROHello.HELLO)) { + throw new Exception("RegisterTarget failed"); + } + } + + // Ensure that Utility.loadStub() manages cache correctly... + if (iiop) { + newTest( "test_33" ) ; + // Get a connected tie... + Multi servant = new Multi(); + Tie tie = Util.getTie(servant); + tie.orb(defaultORB); + String interfaceName; + String stubRepoId; + + // Load A... + Utility.clearCaches(); + interfaceName = "alpha.bravo.A"; + stubRepoId = "RMI:alpha.bravo.A:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, false ) ; + + // Load B... + Utility.clearCaches(); + interfaceName = "alpha.bravo.B"; + stubRepoId = "RMI:alpha.bravo.B:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, false ) ; + + // Load DuckBill... + Utility.clearCaches(); + interfaceName = "alpha.bravo.DuckBill"; + stubRepoId = "RMI:alpha.bravo.DuckBill:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, false ) ; + + // Reload A with onlyMostDerived, and ensure that we get Multi + interfaceName = "alpha.bravo.A"; + stubRepoId = "RMI:alpha.bravo.Multi:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, true ) ; + + // Reload A , and ensure that we still get Multi + interfaceName = "alpha.bravo.A"; + stubRepoId = "RMI:alpha.bravo.Multi:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, false ) ; + + // Load A... + Utility.clearCaches(); + interfaceName = "alpha.bravo.A"; + stubRepoId = "RMI:alpha.bravo.A:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, false ) ; + + // Reload A with onlyMostDerived, and ensure that we get Multi + interfaceName = "alpha.bravo.A"; + stubRepoId = "RMI:alpha.bravo.Multi:0000000000000000" ; + testLoadStub( servant, tie, interfaceName, stubRepoId, true ) ; + } + + if (!first) + helper.pass() ; + } catch (Throwable thr) { + helper.fail( thr ) ; + } finally { + helper.done() ; + } + } + + private void testLoadStub( Multi servant, Tie tie, + String interfaceName, String repoId, boolean flag ) throws Exception + { + PresentationManager.StubFactoryFactory sff = + com.sun.corba.ee.spi.orb.ORB.getStubFactoryFactory() ; + PresentationManager.StubFactory stubFactory = + sff.createStubFactory( interfaceName, false, null, null, null ) ; + Remote stub = Utility.loadStub( tie, stubFactory, + null, flag ) ; + String actualRepoId = StubAdapter.getTypeIds( stub )[0] ; + + if (!actualRepoId.equals( repoId )) { + throw new Exception( "Utility.loadStub: expected " + repoId + + " got " + actualRepoId ) ; + } + } + +} diff --git a/test/src/share/classes/javax/rmi/PortableREmoteOBject.java b/test/src/share/classes/javax/rmi/PortableREmoteOBject.java new file mode 100644 index 000000000..4ecb54557 --- /dev/null +++ b/test/src/share/classes/javax/rmi/PortableREmoteOBject.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; +public class PortableREmoteOBject { +} diff --git a/test/src/share/classes/javax/rmi/RemoteDog.java b/test/src/share/classes/javax/rmi/RemoteDog.java new file mode 100644 index 000000000..c7ef18921 --- /dev/null +++ b/test/src/share/classes/javax/rmi/RemoteDog.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +public interface RemoteDog extends Dog, java.rmi.Remote +{ + // No new methods. Just mixes these two interfaces + // into a new interface that RMIC will need +} diff --git a/test/src/share/classes/javax/rmi/SInner.java b/test/src/share/classes/javax/rmi/SInner.java new file mode 100644 index 000000000..fe2dc9be9 --- /dev/null +++ b/test/src/share/classes/javax/rmi/SInner.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; +// import com.sun.corba.ee.impl.io.FVDCodeBaseImpl; +import javax.rmi.CORBA.*; +import com.sun.org.omg.SendingContext.CodeBase; +import rmic.OnlyRemoteServant; + +public interface SInner extends Remote { + public SInner echo (SInner in) throws RemoteException; + public CodeBase getCodeBase () throws RemoteException; + public Remote getOnlyRemote () throws RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/ServantInner.java b/test/src/share/classes/javax/rmi/ServantInner.java new file mode 100644 index 000000000..79ad51848 --- /dev/null +++ b/test/src/share/classes/javax/rmi/ServantInner.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; +// import com.sun.corba.ee.impl.io.FVDCodeBaseImpl; +import javax.rmi.CORBA.*; +import com.sun.org.omg.SendingContext.CodeBase; +import rmic.OnlyRemoteServant; + +public class ServantInner implements SInner { + public ServantInner () throws RemoteException { + } + + public SInner echo (SInner in) throws RemoteException { + return in; + } + + public CodeBase getCodeBase() throws RemoteException { + javax.rmi.CORBA.ValueHandler vh = Util.createValueHandler(); + return (CodeBase) vh.getRunTimeCodeBase(); + } + + public Remote getOnlyRemote() throws RemoteException { + return new OnlyRemoteServant(); + } + +} diff --git a/test/src/share/classes/javax/rmi/ServantOuter.java b/test/src/share/classes/javax/rmi/ServantOuter.java new file mode 100644 index 000000000..e4e8dcbd8 --- /dev/null +++ b/test/src/share/classes/javax/rmi/ServantOuter.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface ServantOuter extends Remote { + public ServantOuter echo (ServantOuter in) throws RemoteException; + + public class Inner implements ServantOuter { + public Inner () throws RemoteException {} + public ServantOuter echo (ServantOuter in) throws RemoteException {return in;} + } +} diff --git a/test/src/share/classes/javax/rmi/fvd/Log.java b/test/src/share/classes/javax/rmi/fvd/Log.java new file mode 100644 index 000000000..b22899fff --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/Log.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +public interface Log + extends java.rmi.Remote { + + public void log(String who, String what) throws java.rmi.RemoteException; + +} diff --git a/test/src/share/classes/javax/rmi/fvd/LogImpl.java b/test/src/share/classes/javax/rmi/fvd/LogImpl.java new file mode 100644 index 000000000..026669b94 --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/LogImpl.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import java.util.Hashtable; +import java.util.Properties; + +public class LogImpl implements Log/*, java.awt.event.ActionListener*/ { + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + private static Log logServer = null; + /* + Frame f = null; + TextArea ta = null; + + public void actionPerformed(ActionEvent e){ + try{ + logMssg("LogImpl","Shutting down"); + TheTest.shutdown(); + logMssg("LogImpl","Shutdown completed"); + System.exit(1); + } + catch(Throwable t){ + logMssg("LogImpl",t.getMessage()); + + } + + } + private void setup(){ + + f = new Frame("Log Window"); + Button b = new Button("Shutdown test"); + f.setLayout(new BorderLayout()); + f.add("South", b); + b.addActionListener(this); + ta = new TextArea(); + f.add("Center", ta); + f.show(); + f.reshape(100,20,350,350); + + } + */ + public void log(String who, String what) throws java.rmi.RemoteException { + /* + if (f == null) + setup(); + String text = ta.getText(); + text = text + "\n" + who + ":"+what; + ta.setText(text); + */ + } + + public static void logMssg(String who, String what){ + try{ + if (logServer == null) + connect(); + logServer.log(who,what); + } + catch(Throwable t){} + } + + public static void open(){ + try{ + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // create an RMI Servant. The Servant will actually + // handle the users request. + + LogImpl servant = new LogImpl(); + + // Let use PortableRemoteObject to export our servant. + // This same method works for JRMP and IIOP. + + PortableRemoteObject.exportObject(servant); + + // Once the Object is exported we are going to link it to + // our ORB. To do this we need to get the Tie associated + // with our Servant. PortableRemoteObject.export(...) + // create a Tie for us. All we have to do is to retrieve the + // Tie from javax.rmi.CORBA.Util.getTie(...); + + Tie servantsTie = javax.rmi.CORBA.Util.getTie(servant); + + // Now lets set the orb in the Tie object. The Sun/IBM + // ORB will perform a orb.connect. So at this point the + // Tie is connected to the ORB and ready for work. + servantsTie.orb(orb); + + + // We are using JNDI/CosNaming to export our object so we + // need to get the root naming context. We use the properties + // set above to initialize JNDI. + + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + + Context ic = new InitialContext(env); + + // Now lets Export our object by publishing the object + // with JNDI + ic.rebind("LogServer", servantsTie); + java.lang.Object objref = ic.lookup("LogServer"); + + // This test is designed to verify PortableRemoteObject.narrow + + logServer= (Log) + PortableRemoteObject.narrow(objref,Log.class); + } + catch(Throwable t){} + } + + private static void connect(){ + try{ + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // We are going to use JNDI/CosNaming so lets go ahead and + // create our root naming context. NOTE: We setup CosNaming + // as our naming plug-in for JNDI by setting properties above. + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + Context ic = new InitialContext(env); + + // Let the test begin... + // Resolve the Object Reference using JNDI/CosNaming + java.lang.Object objref = ic.lookup("LogServer"); + + // This test is designed to verify PortableRemoteObject.narrow + + logServer= (Log) + PortableRemoteObject.narrow(objref,Log.class); + + // com.sun.corba.ee.impl.io.ValueUtility.logEnabled = true; + } + catch(Throwable t){} + } +} diff --git a/test/src/share/classes/javax/rmi/fvd/ParentClass.java b/test/src/share/classes/javax/rmi/fvd/ParentClass.java new file mode 100644 index 000000000..896091628 --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/ParentClass.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +import java.util.Random; + +public abstract class ParentClass implements java.io.Serializable { + + public long getTotal(){ + return 0; + } + + public long getOriginalTotal(){ + return 0; + } +} diff --git a/test/src/share/classes/javax/rmi/fvd/SecurityManager.java b/test/src/share/classes/javax/rmi/fvd/SecurityManager.java new file mode 100644 index 000000000..d69fc1d2e --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/SecurityManager.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +import java.io.FileDescriptor; +import java.util.Hashtable; +import java.net.InetAddress; +import java.lang.reflect.Member; +//import java.security.*; + +public class SecurityManager extends java.rmi.RMISecurityManager { + + // public void checkPermission(Permission perm) { + // } + + public void checkCreateClassLoader() { } + public void checkAccess(Thread g) { } + public void checkAccess(ThreadGroup g) { } + public void checkExit(int status) { } + public void checkExec(String cmd) { } + public void checkLink(String lib) { } + public void checkRead(FileDescriptor fd) { } + public void checkRead(String file) { } + public void checkRead(String file, Object context) { } + public void checkWrite(FileDescriptor fd) { } + public void checkWrite(String file) { } + public void checkDelete(String file) { } + public void checkConnect(String host, int port) { } + public void checkConnect(String host, int port, Object context) { } + public void checkListen(int port) { } + public void checkAccept(String host, int port) { } + public void checkMulticast(InetAddress maddr) { } + public void checkMulticast(InetAddress maddr, byte ttl) { } + public void checkPropertiesAccess() { } + public void checkPropertyAccess(String key) { } + public void checkPropertyAccess(String key, String def) { } + public boolean checkTopLevelWindow(Object window) { return true; } + public void checkPrintJobAccess() { } + public void checkSystemClipboardAccess() { } + public void checkAwtEventQueueAccess() { } + public void checkPackageAccess(String pkg) { } + public void checkPackageDefinition(String pkg) { } + public void checkSetFactory() { } + public void checkMemberAccess(Class clazz, int which) { } + public void checkSecurityAccess(String provider) { } +} diff --git a/test/src/share/classes/javax/rmi/fvd/Servant.java b/test/src/share/classes/javax/rmi/fvd/Servant.java new file mode 100644 index 000000000..9a4b430a0 --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/Servant.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +public interface Servant + extends java.rmi.Remote { + + public String ping(String s) throws java.rmi.RemoteException; + + public long send(ParentClass value) throws java.rmi.RemoteException; + + public ParentClass receiveMismatch(ParentClass value) throws java.rmi.RemoteException; + + public ParentClass receiveABC(ParentClass value) throws java.rmi.RemoteException; + + public ParentClass receiveAE(ParentClass value) throws java.rmi.RemoteException; + +} diff --git a/test/src/share/classes/javax/rmi/fvd/ServantImpl.java b/test/src/share/classes/javax/rmi/fvd/ServantImpl.java new file mode 100644 index 000000000..caa19fe58 --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/ServantImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +public class ServantImpl implements Servant { + + public String ping(String s) throws java.rmi.RemoteException { + return "ServantImpl:"+s; + } + + + public long send(ParentClass value) throws java.rmi.RemoteException { + return value.getTotal(); + } + + public ParentClass receiveMismatch(ParentClass value) + throws java.rmi.RemoteException { + try{ + return (ParentClass)Class.forName("javax.rmi.download.values.ClientA").newInstance(); + } + catch(Throwable t){ + return null; + } + } + + public ParentClass receiveABC(ParentClass value) + throws java.rmi.RemoteException { + try{ + return (ParentClass)Class.forName("javax.rmi.download.values.ClassC").newInstance(); + } + catch(Throwable t){ + return null; + } + } + + public ParentClass receiveAE(ParentClass value) + throws java.rmi.RemoteException { + try{ + return (ParentClass)Class.forName("javax.rmi.download.values.ClassE").newInstance(); + } + catch(Throwable t){ + return null; + } + } + + +} diff --git a/test/src/share/classes/javax/rmi/fvd/TheClient.java b/test/src/share/classes/javax/rmi/fvd/TheClient.java new file mode 100644 index 000000000..1064c9d1f --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/TheClient.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import java.util.Properties; +import java.io.*; +import javax.rmi.PortableRemoteObject; +import javax.naming.InitialContext; +import javax.naming.Context; +import java.util.Hashtable; + +public class TheClient { + + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + private static void passed(){ + System.out.println(test.Util.HANDSHAKE); + System.out.flush(); + } + + private static void failed(Throwable t){ + StringWriter strWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(strWriter); + t.printStackTrace(printWriter); + System.out.println("FVD test FAILED:\n"+strWriter.toString()+"\n <<< END STACK TRACE >>>"); + System.out.flush(); + System.exit(1); + } + + public static void main(String[] args) { + try { + + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // We are going to use JNDI/CosNaming so lets go ahead and + // create our root naming context. NOTE: We setup CosNaming + // as our naming plug-in for JNDI by setting properties above. + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + Context ic = new InitialContext(env); + + // Let the test begin... + // Resolve the Object Reference using JNDI/CosNaming + java.lang.Object objref = ic.lookup("TheFVDTestServer"); + + // This test is designed to verify PortableRemoteObject.narrow + + try{ + Servant narrowTo = null; + if ( (narrowTo = (Servant) + PortableRemoteObject.narrow(objref,Servant.class)) != null ) { + + // Verify connection + String str = "hello"; + String res = narrowTo.ping(str); + if (!res.equals(new String("ServantImpl:"+str))) + throw new Error("Connection bad!"); + + // Send a mismatched class + // i.e. a matching class hierarchy with differing fields + ParentClass mismatch = + (ParentClass)Class.forName("javax.rmi.download.values.ClientA").newInstance(); + if (mismatch == null) + throw new Error("Could not create javax.rmi.download.values.ClientA"); + + if (narrowTo.send(mismatch) != mismatch.getOriginalTotal()) + throw new Error("Mismatched class not sent correctly!"); + + // Send a differing hierarchy + // - Sender (TheClient) has shallow hierarchy C->A whereas + // receiver (TheServer) has deeper hierarchy C->B->A. + ParentClass shallowHierarchy = + (ParentClass)Class.forName("javax.rmi.download.values.ClassC").newInstance(); + + if (shallowHierarchy == null) + throw new Error("Could not create javax.rmi.download.values.ClassA"); + + if (narrowTo.send(shallowHierarchy) != shallowHierarchy.getOriginalTotal()) + throw new Error("shallowHierarchy class not sent correctly!"); + + // Send a differing hierarchy + // - Sender (TheClient) has deeper hierarchy E->D->A whereas + // receiver (TheServer) has shallow hierarchy E->A. + ParentClass deeperHierarchy = + (ParentClass)Class.forName("javax.rmi.download.values.ClassE").newInstance(); + + if (deeperHierarchy == null) + throw new Error("Could not create javax.rmi.download.values.ClassE"); + + if (narrowTo.send(deeperHierarchy) != 19) // ! 26 + throw new Error("deeperHierarchy class not sent correctly!"); + + // Send a value with a member who's type (class) does + // not exist on the receiver's side (i.e. not codebase + // to download it from either). + ParentClass missingClassContainer = + (ParentClass)Class.forName("javax.rmi.download.values.MissingContainer").newInstance(); + + if (missingClassContainer == null) + throw new Error("Could not create javax.rmi.download.values.MissingContainer"); + + if (narrowTo.send(missingClassContainer) != 5) + throw new Error("missingClassContainer class not sent correctly"); + + passed(); + + + } + else throw new Error("Failed to find narrowTo"); + + + } catch (Throwable ex) { + failed(ex); + + } + } catch (Exception ex) { + failed(ex); + + } + } +} + diff --git a/test/src/share/classes/javax/rmi/fvd/TheServer.java b/test/src/share/classes/javax/rmi/fvd/TheServer.java new file mode 100644 index 000000000..96162b0c2 --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/TheServer.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import java.util.Properties; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import javax.naming.InitialContext; +import javax.naming.Context; +import java.util.Hashtable; + +public class TheServer { + + // This test runs the NameServer on port 1050. + + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + public static void main(String[] args) { + try { + + // The RMIClassLoader requires a security manager to be set + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + //System.setSecurityManager(new java.rmi.RMISecurityManager()); + + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put("org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // create an RMI Servant. The Servant will actually + // handle the users request. + + ServantImpl servant = new ServantImpl(); + + // Let use PortableRemoteObject to export our servant. + // This same method works for JRMP and IIOP. + + PortableRemoteObject.exportObject(servant); + + // Once the Object is exported we are going to link it to + // our ORB. To do this we need to get the Tie associated + // with our Servant. PortableRemoteObject.export(...) + // create a Tie for us. All we have to do is to retrieve the + // Tie from javax.rmi.CORBA.Util.getTie(...); + + Tie servantsTie = javax.rmi.CORBA.Util.getTie(servant); + + // Now lets set the orb in the Tie object. The Sun/IBM + // ORB will perform a orb.connect. So at this point the + // Tie is connected to the ORB and ready for work. + servantsTie.orb(orb); + + + // We are using JNDI/CosNaming to export our object so we + // need to get the root naming context. We use the properties + // set above to initialize JNDI. + + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + + Context ic = new InitialContext(env); + + // Now lets Export our object by publishing the object + // with JNDI + ic.rebind("TheFVDTestServer", servant); + + // Self-Test + // resolve the Object Reference using JNDI + Servant iServant = (Servant) + PortableRemoteObject.narrow(ic.lookup("TheFVDTestServer"), + Servant.class); + + System.out.println(test.Util.HANDSHAKE); + System.out.flush(); + + // wait for object invocation + Object sync = new Object(); + synchronized (sync) { sync.wait(); } + + } catch (Exception ex) { + + ex.printStackTrace(System.out); + System.out.println(); + System.out.flush(); + } + } +} diff --git a/test/src/share/classes/javax/rmi/fvd/TheTest.java b/test/src/share/classes/javax/rmi/fvd/TheTest.java new file mode 100644 index 000000000..8aa7ff9ed --- /dev/null +++ b/test/src/share/classes/javax/rmi/fvd/TheTest.java @@ -0,0 +1,202 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.fvd; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import java.io.IOException; +import java.util.Properties; +import javax.naming.InitialContext; +import javax.naming.Context; +import test.Util; +import java.util.Hashtable; +import java.util.Vector; +import org.glassfish.pfl.test.JUnitReportHelper; + +public class TheTest extends test.Test { + // This test runs the NameServer on port 1050. + + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + static Process nameServer = null; + static Process server = null; + static Process client = null; + + public void setup() { + try { + nameServer = Util.startNameServer("1050",true); + } catch (IOException e) { + System.out.println("Failed to start the name server: " + e); + } + try { + // Now we need to start our test server. The test server will register with the NameServer. + compileClasses(); + } catch(Throwable t) { + System.out.println("Compiling classes failed : "+t.toString()); + } + } + + public void run() { + String testName = TheTest.class.getName(); + JUnitReportHelper helper = new JUnitReportHelper( testName ) ; + helper.start( "test1" ) ; + boolean testPassed = true; + + try { + // The RMIClassLoader requires a security manager to be set + //System.setSecurityManager(new javax.rmi.download.SecurityManager()); + //System.setSecurityManager(new java.rmi.RMISecurityManager()); + + // First Compile the classes to generate the Stub and Tie + // files that are needed. NOTE: This requires the latest + // RMIC compiler that supports IIOP. + + // Create user.dir property (this is how the server knows + // where the test value is but we (this client) does not). + Vector properties = new Vector(); + String testPolicy = System.getProperty("java.security.policy"); + if (testPolicy!=null) + properties.addElement("-Djava.security.policy="+testPolicy); + + + // Start it + String valueClasses = getClassesDirectory("values"); + server = Util.startServer("javax.rmi.fvd.TheServer", + properties, valueClasses); + + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // We are going to use JNDI/CosNaming so lets go ahead and + // create our root naming context. NOTE: We setup CosNaming + // as our naming plug-in for JNDI by setting properties above. + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + Context ic = new InitialContext(env); + + // Let the test begin... + // Resolve the Object Reference using JNDI/CosNaming + java.lang.Object objref = ic.lookup("TheFVDTestServer"); + + // This test is designed to verify PortableRemoteObject.narrow + + try{ + // Now try from separate client that has no codebase of its own + + Vector properties2 = new Vector(); + properties.addElement("-Djava.security.policy="+testPolicy); + + // Start it + client = Util.startServer("javax.rmi.fvd.TheClient", + properties, getClassesDirectory("values2")); + + helper.pass() ; + } catch (Throwable ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + helper.fail( ex ) ; + } + } catch (Exception ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + helper.fail( ex ) ; + } finally { + helper.done() ; + // Kill the client + if (client != null) { + client.destroy(); + } + + // Make sure we kill the test server... + + if (server != null) { + server.destroy(); + } + + // Make sure we kill the NameServer... + + if (nameServer != null) { + nameServer.destroy(); + } + + } + + if ( testPassed == true ) { + status = null; + } else { + status = new Error("FullValueDescription Test Failed"); + } + } + + public static void shutdown(){ + if (client != null) { + client.destroy(); + client = null; + } + + if (server != null) { + server.destroy(); + server = null; + } + + if (nameServer != null) { + nameServer.destroy(); + nameServer = null; + } + } + + // Compiling ComboInterface causes the compiler to compile + // all the other classes that need to be compiled. + private void compileClasses () throws Exception { + String arg = "-iiop"; + String[] additionalArgs = null; + String[] classes = {"javax.rmi.fvd.ServantImpl", "javax.rmi.fvd.LogImpl"}; + + // Create the additional args array... + + String outputDirectory = null; + int length = 3; + Hashtable flags = getArgs(); + if (flags.containsKey(test.Test.OUTPUT_DIRECTORY)) { + outputDirectory = (String)flags.get(test.Test.OUTPUT_DIRECTORY); + length += 2; + } + additionalArgs = new String[length]; + int offset = 0; + + if (outputDirectory != null) { + additionalArgs[offset++] = "-d"; + additionalArgs[offset++] = outputDirectory; + } + additionalArgs[offset++] = "-Xreverseids"; + additionalArgs[offset++] = "-alwaysgenerate"; + additionalArgs[offset++] = "-keepgenerated"; + + // Run rmic... + + Util.rmic(arg,additionalArgs,classes,false); + } +} diff --git a/test/src/share/classes/javax/rmi/test1/ComboInterface.java b/test/src/share/classes/javax/rmi/test1/ComboInterface.java new file mode 100644 index 000000000..faa9425f3 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/ComboInterface.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public interface ComboInterface + extends java.rmi.Remote, RemoteInterface3, SingleRemoteInterface { + +} diff --git a/test/src/share/classes/javax/rmi/test1/ComboInterfaceImpl.java b/test/src/share/classes/javax/rmi/test1/ComboInterfaceImpl.java new file mode 100644 index 000000000..5994ff552 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/ComboInterfaceImpl.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public class ComboInterfaceImpl implements ComboInterface { + + public String EchoRemoteInterface1() throws java.rmi.RemoteException { + return "EchoRemoteInterface1"; + } + public String EchoRemoteInterface2() throws java.rmi.RemoteException{ + return "EchoRemoteInterface2"; + } + public String EchoRemoteInterface3() throws java.rmi.RemoteException{ + return "EchoRemoteInterface3"; + } + public String EchoSingleRemoteInterface() throws java.rmi.RemoteException{ + return "EchoSingleRemoteInterface"; + } +} diff --git a/test/src/share/classes/javax/rmi/test1/RemoteInterface1.java b/test/src/share/classes/javax/rmi/test1/RemoteInterface1.java new file mode 100644 index 000000000..1903fa07f --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/RemoteInterface1.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public interface RemoteInterface1 extends java.rmi.Remote { + public String EchoRemoteInterface1() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/test1/RemoteInterface1Impl.java b/test/src/share/classes/javax/rmi/test1/RemoteInterface1Impl.java new file mode 100644 index 000000000..5e09cffbc --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/RemoteInterface1Impl.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public class RemoteInterface1Impl implements RemoteInterface1 { + + public String EchoRemoteInterface1() throws java.rmi.RemoteException { + return "EchoRemoteInterface1"; + } +} diff --git a/test/src/share/classes/javax/rmi/test1/RemoteInterface2.java b/test/src/share/classes/javax/rmi/test1/RemoteInterface2.java new file mode 100644 index 000000000..e29f6339c --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/RemoteInterface2.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public interface RemoteInterface2 + extends java.rmi.Remote, RemoteInterface1 { + public String EchoRemoteInterface2() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/test1/RemoteInterface2Impl.java b/test/src/share/classes/javax/rmi/test1/RemoteInterface2Impl.java new file mode 100644 index 000000000..2b396acc2 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/RemoteInterface2Impl.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public class RemoteInterface2Impl implements RemoteInterface2 { + + public String EchoRemoteInterface1() throws java.rmi.RemoteException { + return "EchoRemoteInterface1"; + } + + public String EchoRemoteInterface2() throws java.rmi.RemoteException { + return "EchoRemoteInterface2"; + } +} diff --git a/test/src/share/classes/javax/rmi/test1/RemoteInterface3.java b/test/src/share/classes/javax/rmi/test1/RemoteInterface3.java new file mode 100644 index 000000000..0f07f7f20 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/RemoteInterface3.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public interface RemoteInterface3 + extends java.rmi.Remote, RemoteInterface2 { + public String EchoRemoteInterface3() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/test1/RemoteInterface3Impl.java b/test/src/share/classes/javax/rmi/test1/RemoteInterface3Impl.java new file mode 100644 index 000000000..171b2f067 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/RemoteInterface3Impl.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public class RemoteInterface3Impl implements RemoteInterface3 { + + public String EchoRemoteInterface1() throws java.rmi.RemoteException { + return "EchoRemoteInterface1"; + } + + public String EchoRemoteInterface2() throws java.rmi.RemoteException { + return "EchoRemoteInterface2"; + } + + public String EchoRemoteInterface3() throws java.rmi.RemoteException { + return "EchoRemoteInterface3"; + } +} diff --git a/test/src/share/classes/javax/rmi/test1/SingleRemoteInterface.java b/test/src/share/classes/javax/rmi/test1/SingleRemoteInterface.java new file mode 100644 index 000000000..fab2f2f37 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/SingleRemoteInterface.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public interface SingleRemoteInterface + extends java.rmi.Remote { + public String EchoSingleRemoteInterface() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/javax/rmi/test1/SingleRemoteInterfaceImpl.java b/test/src/share/classes/javax/rmi/test1/SingleRemoteInterfaceImpl.java new file mode 100644 index 000000000..15a622b85 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/SingleRemoteInterfaceImpl.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +public class SingleRemoteInterfaceImpl implements SingleRemoteInterface { + + public String EchoSingleRemoteInterface() throws java.rmi.RemoteException { + return "EchoSingleRemoteInterface"; + } +} diff --git a/test/src/share/classes/javax/rmi/test1/TheServer.java b/test/src/share/classes/javax/rmi/test1/TheServer.java new file mode 100644 index 000000000..d81b81f6f --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/TheServer.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import java.util.Properties; +import javax.rmi.CORBA.Tie; +import javax.rmi.PortableRemoteObject; +import javax.naming.InitialContext; +import javax.naming.Context; +import java.util.Hashtable; + +public class TheServer { + + // This test runs the NameServer on port 1050. + + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + public static void main(String[] args) { + try { + System.setSecurityManager(new javax.rmi.download.SecurityManager()); + + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put("org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // create an RMI Servant. The Servant will actually + // handle the users request. + + ComboInterfaceImpl servant = new ComboInterfaceImpl(); + + // Let use PortableRemoteObject to export our servant. + // This same method works for JRMP and IIOP. + + PortableRemoteObject.exportObject(servant); + + // Once the Object is exported we are going to link it to + // our ORB. To do this we need to get the Tie associated + // with our Servant. PortableRemoteObject.export(...) + // create a Tie for us. All we have to do is to retrieve the + // Tie from javax.rmi.CORBA.Util.getTie(...); + + Tie servantsTie = javax.rmi.CORBA.Util.getTie(servant); + + // Now lets set the orb in the Tie object. The Sun/IBM + // ORB will perform a orb.connect. So at this point the + // Tie is connected to the ORB and ready for work. + servantsTie.orb(orb); + + + // We are using JNDI/CosNaming to export our object so we + // need to get the root naming context. We use the properties + // set above to initialize JNDI. + + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + + Context ic = new InitialContext(env); + + // Now lets Export our object by publishing the object + // with JNDI + ic.rebind("TheTestServer", servant); + + // Self-Test + // resolve the Object Reference using JNDI + ComboInterface combo = (ComboInterface) + PortableRemoteObject.narrow(ic.lookup("TheTestServer"), + ComboInterface.class); + + // If the self test works then we will give the "Handshake" to + // the client. This means we are open for business. + + if (combo.EchoSingleRemoteInterface().equals("EchoSingleRemoteInterface")) { + System.out.println(test.Util.HANDSHAKE); + } else { + System.out.println("Self test FAILED."); + } + + System.out.flush(); + + // wait for object invocation + Object sync = new Object(); + synchronized (sync) { sync.wait(); } + + } catch (Exception ex) { + + ex.printStackTrace(System.out); + System.out.println(); + System.out.flush(); + } + } +} diff --git a/test/src/share/classes/javax/rmi/test1/TheTest.java b/test/src/share/classes/javax/rmi/test1/TheTest.java new file mode 100644 index 000000000..9d0b14496 --- /dev/null +++ b/test/src/share/classes/javax/rmi/test1/TheTest.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.test1; + +import com.sun.corba.ee.spi.JndiConstants; +import org.omg.CORBA.ORB; + +import java.util.Properties; +import javax.rmi.PortableRemoteObject; +import javax.naming.InitialContext; +import javax.naming.Context; +import test.Util; +import java.util.Hashtable; +import org.glassfish.pfl.test.JUnitReportHelper; + +public class TheTest extends test.Test { + // This test runs the NameServer on port 1050. + private static String[] myArgs = new String[]{"-ORBInitialPort" , "1050" }; + + public void run() { + JUnitReportHelper helper = new JUnitReportHelper( + this.getClass().getName() ) ; + + String testName = new TheTest().getClass().getName(); + Process nameServer = null; + Process server = null; + boolean testPassed = true; + + try { + // First Compile the classes to generate the Stub and Tie + // files that are needed. + if (!getArgs().containsKey("-normic")) { + compileClasses(); + } + + // Now we need to start the NameServer and + // our test server. The test server will register + // with the NameServer. + + nameServer = Util.startNameServer("1050",true); + server = Util.startServer("javax.rmi.test1.TheServer"); + + // Lets setup some properties that we are using + // for this test and then create the ORB Object... + + Properties props = System.getProperties(); + + props.put( "java.naming.factory.initial", + JndiConstants.COSNAMING_CONTEXT_FACTORY); + + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl"); + + props.put( "org.omg.CORBA.ORBSingletonClass", + "com.sun.corba.ee.impl.orb.ORBSingleton"); + + ORB orb = ORB.init(myArgs, props); + + // We are going to use JNDI/CosNaming so lets go ahead and + // create our root naming context. NOTE: We setup CosNaming + // as our naming plug-in for JNDI by setting properties above. + Hashtable env = new Hashtable(); + env.put( "java.naming.corba.orb", orb); + + Context ic = new InitialContext(env); + + // Let the test begin... + helper.start( "test1" ) ; + // Resolve the Object Reference using JNDI/CosNaming + java.lang.Object objref = ic.lookup("TheTestServer"); + + // This test is designed to verify PortableRemoteObject.narrow + + try { + RemoteInterface1 narrowTo = null; + if ( (narrowTo = (RemoteInterface1) + PortableRemoteObject.narrow(objref,RemoteInterface1.class)) != null ) { + if (!narrowTo.EchoRemoteInterface1().equals("EchoRemoteInterface1")) { + throw new Exception("javax.rmi.test1.TheTest: EchoRemoteInterface1() narrow failed"); + } + } + } catch (Throwable ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + } + + + try { + RemoteInterface2 narrowTo = null; + if ( (narrowTo = (RemoteInterface2) + PortableRemoteObject.narrow(objref,RemoteInterface2.class)) != null ) { + if (!narrowTo.EchoRemoteInterface2().equals("EchoRemoteInterface2")) { + throw new Exception("javax.rmi.test1.TheTest: EchoRemoteInterface2() narrow failed"); + } + } + } catch (Throwable ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + } + + try { + RemoteInterface3 narrowTo = null; + if ( (narrowTo = (RemoteInterface3) + PortableRemoteObject.narrow(objref,RemoteInterface3.class)) != null ) { + if (!narrowTo.EchoRemoteInterface3().equals("EchoRemoteInterface3")) { + throw new Exception("javax.rmi.test1.TheTest: EchoRemoteInterface3() narrow failed"); + } + } + } catch (Throwable ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + } + + try { + SingleRemoteInterface narrowTo = null; + if ( (narrowTo = (SingleRemoteInterface) + PortableRemoteObject.narrow(objref,SingleRemoteInterface.class)) != null ) { + if (!narrowTo.EchoSingleRemoteInterface().equals("EchoSingleRemoteInterface")) { + throw new Exception("javax.rmi.test1.TheTest: SingleRemoteInterface() narrow failed"); + } + } + } catch (Throwable ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + } + + } catch (Exception ex) { + System.out.println(testName + " FAILED."); + ex.printStackTrace(); + testPassed = false; + } finally { + if (server != null) { + server.destroy(); + } + + if (nameServer != null) { + nameServer.destroy(); + } + } + + if ( testPassed == true ) { + helper.pass() ; + status = null; + } else { + helper.fail( "test failed" ) ; + status = new Error("PortableRemoteObject.narrow Test Failed"); + } + + helper.done() ; + } + + // Compiling ComboInterface cause the compiler to compile + // all the other classes that need to be compiled. + + private void compileClasses () throws Exception + { + String arg = "-iiop"; + String[] additionalArgs = null; + String[] classes = {"javax.rmi.test1.ComboInterfaceImpl"}; + + // Create the additional args array... + + String outputDirectory = null; + int length = 3; + Hashtable flags = getArgs(); + if (flags.containsKey(test.Test.OUTPUT_DIRECTORY)) { + outputDirectory = (String)flags.get(test.Test.OUTPUT_DIRECTORY); + length += 2; + } + additionalArgs = new String[length]; + int offset = 0; + + if (outputDirectory != null) { + additionalArgs[offset++] = "-d"; + additionalArgs[offset++] = outputDirectory; + } + additionalArgs[offset++] = "-Xreverseids"; + additionalArgs[offset++] = "-alwaysgenerate"; + additionalArgs[offset++] = "-keepgenerated"; + + // Run rmic... + + Util.rmic(arg,additionalArgs,classes,false); + } +} diff --git a/test/src/share/classes/mantis/MantisTests.tdesc b/test/src/share/classes/mantis/MantisTests.tdesc new file mode 100644 index 000000000..4c051e171 --- /dev/null +++ b/test/src/share/classes/mantis/MantisTests.tdesc @@ -0,0 +1,24 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +// +// These are for verifying bugs fixed in Mantis. +// +// Format: +// +// -test +// + +// Fixed 4764130: ClientDelegate.addServiceContexts() records connections prematurely +-test mantis.m4764130.SendingContextTest + +// The following tests are not run if JSG is ON. This is done programmatically. +// mantis.m4764130.SendingContextTest + +// End of file. diff --git a/test/src/share/classes/naming/NamingTests.tdesc b/test/src/share/classes/naming/NamingTests.tdesc new file mode 100644 index 000000000..0dd92908f --- /dev/null +++ b/test/src/share/classes/naming/NamingTests.tdesc @@ -0,0 +1,38 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +// Batch tests +// Run 'java test.Test' for syntax +// +// These are the CosNaming Technologies tests found under +// test/src/share/classes/cosnaming +// + +-test naming.instest.INSTest +-test naming.rinameservice.RINameServiceTest +-test naming.cosnaming.Test + +// PCOSNamingTest is a bit tricky to debug. It runs as follows: +// 1. The test driver starts ORBD and the server, and creates the controller +// for the client. The controllers for the client and ORBD are passed to +// the server as arguments. +// 2. The server runs as an InternalProcess, but the -separateprocess flag +// causes it to be execed in a different process. There is currently no +// debugging support for -separateprocess. +// 3. The server starts and stops ORBD 3 times, and then at the end it starts +// the client. +// +// To debug this test: +// 1. Remove the -separateprocess flag. +// 2. setenv DEBUGGER 1. This allows attaching a debugger to the test driver, +// which also runs the server directly. +// 3. -rdebug can be used as usual for client and ORBD as needed. Note that +// the persistent name service is part of ORBD. + +-test naming.pcosnaming.PCOSNamingTest -separateprocess diff --git a/test/src/share/classes/naming/cosnaming/Test.java b/test/src/share/classes/naming/cosnaming/Test.java new file mode 100644 index 000000000..0d0d3418e --- /dev/null +++ b/test/src/share/classes/naming/cosnaming/Test.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.cosnaming; + +import corba.framework.*; + +public class Test extends CORBATest +{ + protected void doTest () throws Throwable + { + // Turn on debugging flags + // Options.addORBDArgs( "-ORBDebug transport,subcontract,giop,orbd" ) ; + // Options.addClientArgs( "-ORBDebug transport,subcontract,giop" ) ; + + Controller orbd = createORBD(); + + orbd.start(); + + Controller client = createClient("naming.cosnaming.naming_client"); + + client.start(); + + client.waitFor(60000); + + client.stop(); + + orbd.stop(); + } +} diff --git a/test/src/share/classes/naming/cosnaming/naming_client.java b/test/src/share/classes/naming/cosnaming/naming_client.java new file mode 100644 index 000000000..67f43fdef --- /dev/null +++ b/test/src/share/classes/naming/cosnaming/naming_client.java @@ -0,0 +1,568 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// +// naming_client.java - test for name service +// +// +package naming.cosnaming; + +import java.lang.Thread; + +import java.io.OutputStream; +import java.io.DataOutputStream; +import java.io.FileOutputStream; +import java.util.Properties; +import java.util.Random; + +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.CosNaming.NamingContextPackage.*; + + +public class naming_client +{ + public static void main(String args[]) + { + try { + int numberOfClients = 1; + int numberOfObjects = 5; + int totalErrors = 0; + + String nsIOR = null; + String nsKey = "NameService"; + + NamingContext initial = null; + + // Get an orb object + java.util.Properties props = System.getProperties(); + + // Parse arguments + for (int i=0;i 0) { + // Specified IOR + message("trying to destringify and narrow from " + nsIOR); + org.omg.CORBA.Object obj = orb.string_to_object(nsIOR); + try { + initial = NamingContextHelper.narrow(obj); + } catch (org.omg.CORBA.BAD_PARAM e) { + error_message("Could not destringify initial IOR and narrow to CosNaming::NamingContext!"); + totalErrors++; + throw e; + } + } else if (nsKey != null && nsKey.length() > 0) { + // Specified key + message("trying to resolve " + nsKey); + org.omg.CORBA.Object obj = null; + try { + obj = orb.resolve_initial_references(nsKey); + } catch (org.omg.CORBA.ORBPackage.InvalidName e) { + error_message("Could not resolve_initial_references on " + nsKey + + ": got InvalidName exception"); + e.printStackTrace(); + throw e; + } + message("narrowing " + nsKey); + try { + initial = NamingContextHelper.narrow(obj); + } catch (org.omg.CORBA.BAD_PARAM e) { + error_message("Could not narrow to CosNaming::NamingContext from key " + nsKey + "!"); + totalErrors++; + throw e; + } + } else { + error_message("Cannot obtain initial naming context, no IOR or key available!"); + totalErrors++; + initial = null; + throw new Exception("Cannot obtain initial naming context, no IOR or key available!"); + } + + message("got initial naming context: " + initial); + + // Start clients + if (numberOfClients < 2) { + message("running single client synchronously with " + numberOfObjects + " objects"); + // create test + NamingTester test = new NamingTester(orb,0,numberOfObjects,initial); + // run it + test.run(); + // collect errors + totalErrors += test.getErrors(); + } else { + // Create a number of threads + message("creating " + numberOfClients + " individual test-threads with " + numberOfObjects + "objects"); + Thread[] test_threads = new Thread[numberOfClients]; + NamingTester[] tests = new NamingTester[numberOfClients]; + for (int i=0;i " + nc); + } catch (org.omg.CORBA.SystemException ex) { + errors++; + error_message("cannot narrow resolved playground to a naming context!"); + } + } + } + + // Bind again + try { + theRoot.bind_context(playgroundName,playground); + errors++; + error_message("bind_context() second time should throw alreadybound exception but doesn't!"); + } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound ex) { + message("bind_context() second time throws exception, which is fine."); + } + + // Rebind + try { + theRoot.rebind_context(playgroundName,playground); + message("rebind_context() second time works."); + } catch (org.omg.CosNaming.NamingContextPackage.NotFound ex) { + errors++; + error_message("rebind_context() second time throws exception, but it shouldn't!"); + } + + // Now we are ready to create objects + { + // Create a holder for the object references + org.omg.CORBA.Object[] objects = new org.omg.CORBA.Object[numberOfObjects]; + // Create an array of names, i.e. 2D array of namecomponents + NameComponent[][] names = new NameComponent[numberOfObjects][1]; + + message("creating names and object references for " + numberOfObjects + + " objects"); + + // Fill out objectrefs and their names + for (int i=0;i 0) { + for (int i=0;i0) + s = s + ","; + s = s + "[" + name[i].id + "," + name[i].kind + "]"; + } + } + s = s + "}"; + return s; + } + + public int getErrors() { + return errors; + } + + public void message(String msg) { + System.out.println("NamingTester[" + Thread.currentThread().getName() + "]: " + msg); + } + public void error_message(String msg) { + System.err.println("NamingTester[" + Thread.currentThread().getName() + "]: Error: " + msg); + errors++; + } +} diff --git a/test/src/share/classes/naming/instest/Client.java b/test/src/share/classes/naming/instest/Client.java new file mode 100644 index 000000000..de744be0d --- /dev/null +++ b/test/src/share/classes/naming/instest/Client.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.instest; + +import java.util.Properties; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; + +public class Client implements Runnable { + + private String[] args; + + public Client(String[] args) { + this.args = args; + } + + public void signalError () { + System.exit(1); + } + + + public static void main(String args[]) { + new Client(args).run(); + } + + public void run() + { + try { + Properties props = new Properties() ; + //props.setProperty( "com.sun.corba.ee.ORBDebug", + //"subcontract,transport,naming,serviceContext,transientObjectManager" ) ; + ORB orb = ORB.init( args, props ); + + String corbalocURL + = System.getProperty(TestConstants.URL_PROPERTY); + + Object obj + = orb.string_to_object(corbalocURL); + + if( obj == null ) { + System.err.println( "string_to_object(" + + corbalocURL + ") failed.." ); + System.err.flush(); + signalError (); + } + Hello helloRef = HelloHelper.narrow( obj ); + String returnString = helloRef.sayHello( ); + if( !returnString.equals( TestConstants.returnString ) ) { + System.err.println( " hello.sayHello() did not return.." + + TestConstants.returnString ); + System.err.flush( ); + signalError( ); + } + System.out.println( "INS Test Passed.." ); + } catch (Exception e ) { + e.printStackTrace( System.err ); + signalError( ); + } + System.out.println("Thread "+ Thread.currentThread()+" done."); + } +} + + + diff --git a/test/src/share/classes/naming/instest/HelloImpl.java b/test/src/share/classes/naming/instest/HelloImpl.java new file mode 100644 index 000000000..9b6eb6980 --- /dev/null +++ b/test/src/share/classes/naming/instest/HelloImpl.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.instest; + +public class HelloImpl extends _HelloImplBase { + + public String sayHello( ) { + System.out.println( "Hello Called...." ); + return TestConstants.returnString; + } +} + diff --git a/test/src/share/classes/naming/instest/INSServer.java b/test/src/share/classes/naming/instest/INSServer.java new file mode 100644 index 000000000..ec5bb4f45 --- /dev/null +++ b/test/src/share/classes/naming/instest/INSServer.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.instest; + +import java.util.Properties; +import java.util.Hashtable; +import com.sun.corba.ee.spi.misc.ORBConstants; +import java.io.PrintStream; +import org.omg.CORBA.ORB; + +public class INSServer +{ + + public static void main(String args[]) { + try { + (new INSServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + try { + + System.out.println("ORB class: " + + environment.getProperty("org.omg.CORBA.ORBClass")); + + // environment.setProperty( "com.sun.corba.ee.ORBDebug", + // "subcontract,transport,naming,serviceContext,transientObjectManager" ) ; + ORB orb = ORB.init(args, environment); + + HelloImpl helloRef = new HelloImpl( ); + orb.connect( helloRef ); + ((com.sun.corba.ee.spi.orb.ORB)orb).register_initial_reference( + TestConstants.INSServiceName, helloRef ); + + //handshake: + out.println("Server is ready."); + out.flush(); + + orb.run( ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } +} + + + + + + diff --git a/test/src/share/classes/naming/instest/INSTest.java b/test/src/share/classes/naming/instest/INSTest.java new file mode 100644 index 000000000..d69832d53 --- /dev/null +++ b/test/src/share/classes/naming/instest/INSTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.instest; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import corba.framework.CORBATest; +import corba.framework.Controller; +import corba.framework.Options; +import java.util.Properties; + +/** + * This is a test for INS. + */ +public class INSTest extends CORBATest +{ + public static String[] idlFiles = { "hello.idl" }; + + // Define the .java files that need to be compiled. Any + // java files generated by compiling IDL will automatically be + // compiled with these. + public static String[] javaFiles = {"Client.java", + "HelloImpl.java", + "INSServer.java"}; + + // This is the main method defining the test. All tests + // should have this. + + protected void doTest() throws Throwable + { + Options.addIDLCompilerArgs( "-fall -oldImplBase" ); + Options.setJavaFiles(javaFiles); + Options.setIDLFiles(idlFiles); + + compileIDLFiles(); + + compileJavaFiles(); + + Properties serverProps = Options.getServerProperties(); + serverProps.setProperty(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + TestConstants.PERSISTENT_PORT); + + Controller server + = createServer("naming.instest.INSServer"); + + server.start(); + + Properties clientProps = Options.getClientProperties(); + clientProps.setProperty(TestConstants.URL_PROPERTY, + "corbaloc:iiop:1.2@localhost:" + + TestConstants.PERSISTENT_PORT + + '/' + + TestConstants.INSServiceName); + + Controller client = createClient("naming.instest.Client"); + + client.start(); + + client.waitFor(60000); + + // Make sure all the processes are shut down. + client.stop(); + server.stop(); + } +} + diff --git a/test/src/share/classes/naming/instest/TestConstants.java b/test/src/share/classes/naming/instest/TestConstants.java new file mode 100644 index 000000000..8ed1b4a1a --- /dev/null +++ b/test/src/share/classes/naming/instest/TestConstants.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.instest; + +public class TestConstants { + + public static final String URL_PROPERTY = "naming.instest.urlProperty"; + + public static final String INSServiceName = "HelloService"; + + public static final String PERSISTENT_PORT = "2050"; + + public static final String returnString = "HELLO"; +} diff --git a/test/src/share/classes/naming/instest/hello.idl b/test/src/share/classes/naming/instest/hello.idl new file mode 100644 index 000000000..3b79f1246 --- /dev/null +++ b/test/src/share/classes/naming/instest/hello.idl @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module naming { + module instest { + interface Hello + { + string sayHello(); + }; + }; +}; diff --git a/test/src/share/classes/naming/pcosnaming/PCOSNamingTest.java b/test/src/share/classes/naming/pcosnaming/PCOSNamingTest.java new file mode 100644 index 000000000..8bd4542d1 --- /dev/null +++ b/test/src/share/classes/naming/pcosnaming/PCOSNamingTest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.pcosnaming; + +import test.Test; +import corba.framework.*; +import java.util.*; + +public class PCOSNamingTest extends CORBATest +{ + public static String[] idlFiles = { "hello.idl" }; + + public static String[] javaFiles = { "helloClient.java", + "helloServer.java" }; + + protected Controller newServerController() + { + return new InternalExec(); + } + + // Unusual test in which killing ORBD is necessary, and this must be + // controlled by the server (to test persistent references). + // + // To do this, the server is executed in the main test thread, not in a + // separate process. It is passed the Controller objects for ORBD and + // the client, so it can start them and stop them at the appropriate + // times. + protected void doTest() throws Throwable + { + Options.addIDLCompilerArg("-fall"); + Options.addIDLCompilerArg("-oldImplBase"); + Options.setIDLFiles(idlFiles); + Options.setJavaFiles(javaFiles); + + compileIDLFiles(); + compileJavaFiles(); + + Controller orbd = createORBD(); + Controller client + = createClient("naming.pcosnaming.helloClient"); + + Object serverExtras[] = new Object[3]; + + Hashtable serverExtra = Options.getServerExtra(); + serverExtra.put("orbd", orbd); + serverExtra.put("client", client); + + Controller server + = createServer("naming.pcosnaming.helloServer"); + + orbd.start(); + + // This seems to be necessary on NT or else we try to restart + // too soon, and a ghost process from the first ORBD process + // is left beind to cause trouble. + Thread.sleep(10000); + + // Server starts the client and does a waitFor + server.start(); + + // These shouldn't do anything in the current implementation + server.waitFor(); + client.stop(); + server.stop(); + + orbd.stop(); + } +} + diff --git a/test/src/share/classes/naming/pcosnaming/hello.idl b/test/src/share/classes/naming/pcosnaming/hello.idl new file mode 100644 index 000000000..0290224a5 --- /dev/null +++ b/test/src/share/classes/naming/pcosnaming/hello.idl @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module HelloApp +{ + interface hello + { + void sayHello(); + }; +}; + diff --git a/test/src/share/classes/naming/pcosnaming/helloClient.java b/test/src/share/classes/naming/pcosnaming/helloClient.java new file mode 100644 index 000000000..8bcbb78b2 --- /dev/null +++ b/test/src/share/classes/naming/pcosnaming/helloClient.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.pcosnaming; + +import HelloApp.*; +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import java.util.Properties ; + +public class helloClient +{ + public static void main(String args[]) + { + try { + // create and initialize the ORB + ORB orb = ORB.init(args, System.getProperties()); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + + // resolve the Object Reference (Simple Case -One Level ) + NameComponent nc1 = new NameComponent("HelloObj1", ""); + NameComponent path1[] = {nc1}; + hello helloRef = helloHelper.narrow(ncRef.resolve(path1)); + helloRef.sayHello(); + + // resolve the Object Reference (Little Complex Case -Two Level ) + NameComponent nc2 = new NameComponent("HelloContext1", ""); + + NameComponent temppath[] = {nc2}; + NamingContext temp = (NamingContext) ncRef.resolve( temppath ); + System.out.println( "NC Resolve worked" ); + System.out.flush( ); + + NameComponent nc3 = new NameComponent("HelloObj2", ""); + + NameComponent temppath1[] = {nc3}; + helloRef = helloHelper.narrow(temp.resolve(temppath1)); + System.out.println( "First Resolve Worked" ); + System.out.flush( ); + helloRef.sayHello( ); +/* + + NameComponent path2[] = {nc2, nc3}; + helloRef = helloHelper.narrow(ncRef.resolve(path2)); + System.out.println( "helloRef is resolved" ); + System.out.flush( ); + helloRef.sayHello(); + + // resolve the Object Reference (Little Complex Case -Three Level ) + NameComponent nc4 = new NameComponent("HelloContext2", ""); + NameComponent nc5 = new NameComponent("HelloObj3", ""); + NameComponent path3[] = { nc2, nc4, nc5}; + helloRef = helloHelper.narrow(ncRef.resolve(path3)); + helloRef.sayHello(); + +*/ + //orb.shutdown(true); + + } catch (Exception e) { + System.out.println("ERROR : " + e) ; + e.printStackTrace(System.out); + System.exit(1); + } + } +} diff --git a/test/src/share/classes/naming/pcosnaming/helloServer.java b/test/src/share/classes/naming/pcosnaming/helloServer.java new file mode 100644 index 000000000..52c35902b --- /dev/null +++ b/test/src/share/classes/naming/pcosnaming/helloServer.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.pcosnaming; + +import HelloApp._helloImplBase ; +import corba.framework.Controller; +import corba.framework.InternalProcess; +import java.io.PrintStream; + +import java.util.Properties; +import java.util.Hashtable; +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +class helloServant extends _helloImplBase +{ + public void sayHello() + { + helloServer.output.println("Servant: In helloServant.sayHello()"); + } + + public void shutdown() { + throw new UnsupportedOperationException("Not supported yet."); + } +} + +public class helloServer implements InternalProcess +{ + public NamingContext ncRef; + public helloServant helloRef; + public static PrintStream output; + public static PrintStream errors; + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + Controller orbd = (Controller)extra.get("orbd"); + Controller client = (Controller)extra.get("client"); + + helloServer.output = out; + helloServer.errors = err; + + ORB orb = ORB.init(args, environment); + + // create servant and register it with the ORB + helloRef = new helloServant(); + orb.connect(helloRef); + + // get the root naming context + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + ncRef = NamingContextHelper.narrow(objRef); + + // bind the Object Reference in Naming + NameComponent nc1 = new NameComponent("HelloObj1", ""); + NameComponent path1[] = {nc1}; + ncRef.rebind(path1, helloRef); + + output.println("Killing and restarting ORBD..."); + + orbd.stop(); + orbd.start(); + output.println("ORBD restarted"); + + // Give a little more time + Thread.sleep(1000); + + NamingContext ncRef1 = ncRef.new_context(); + output.println( "Persistent Reference was valid"); + + NameComponent nc2 = new NameComponent("HelloContext1", ""); + NameComponent path2[] = {nc2}; + ncRef.rebind_context( path2, ncRef1 ); + + output.println("Killing and restarting ORBD..."); + orbd.stop(); + orbd.start(); + output.println("ORBD restarted"); + + Thread.sleep(1000); + + NamingContext ncRef2 = ncRef.new_context( ); + NameComponent nc3 = new NameComponent("HelloContext2", ""); + NameComponent path3[] = {nc3}; + ncRef1.rebind_context( path3, ncRef2 ); + output.println(" Persistent Reference of NCREF1 was valid....... " ); + + NameComponent nc4 = new NameComponent( "HelloObj2", ""); + NameComponent path4[] = {nc4}; + ncRef1.rebind( path4, helloRef ); + + output.println("Killing and restarting ORBD..."); + orbd.stop(); + orbd.start(); + output.println("ORBD restarted"); + + Thread.sleep(1000); + + NameComponent nc5 = new NameComponent( "HelloObj3",""); + NameComponent path5[] = {nc5}; + ncRef2.rebind( path5, helloRef ); + + output.println( " Persistent Reference of NCREF2 was valid....... " ); + + output.println("Starting client..."); + + // Not very intuitive, but start the client in a separate process. + client.start(); + client.waitFor(); + + output.println("Client finished, exiting..."); + + output.flush(); + + // orb.shutdown(true); + } +} diff --git a/test/src/share/classes/naming/rinameservice/NameServer.java b/test/src/share/classes/naming/rinameservice/NameServer.java new file mode 100644 index 000000000..40bba780c --- /dev/null +++ b/test/src/share/classes/naming/rinameservice/NameServer.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.rinameservice; + +import com.sun.corba.ee.impl.naming.cosnaming.TransientNameService; +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.CORBA.ORB; +import corba.framework.*; +import java.util.*; +import java.io.*; + +/** + * This is a simple test to demonstrate the NameService that we ship with RI + * works. It + * 1. Instantiates ORB by passing Persistent Port property so that there is + * is a listener on port 1050 + * 2. Instantiates TransientNameService by passing the ORB + */ +public class NameServer implements InternalProcess +{ + + public static void main( String args[] ) { + try { + (new NameServer()).run( System.getProperties(), + args, System.out, System.err, null ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + try { + Properties orbProperties = new Properties( ); + orbProperties.put( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, + TestConstants.RI_NAMESERVICE_PORT ); + orbProperties.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ); + orbProperties.setProperty( ORBConstants.DEBUG_PROPERTY, "subcontract,giop,transport" ) ; + ORB orb = ORB.init( args, orbProperties ); + TransientNameService standaloneNameService = + new TransientNameService( + (com.sun.corba.ee.spi.orb.ORB)orb ); + System.out.println( "Server is ready." ) ; + orb.run( ); + } catch( Exception e ) { + System.err.println( "Exception In NameServer " + e ); + e.printStackTrace( ); + System.exit( 1 ); + } + } +} diff --git a/test/src/share/classes/naming/rinameservice/NameServiceClient.java b/test/src/share/classes/naming/rinameservice/NameServiceClient.java new file mode 100644 index 000000000..aed9b1a4e --- /dev/null +++ b/test/src/share/classes/naming/rinameservice/NameServiceClient.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.rinameservice; + +import org.omg.CosNaming.*; +import org.omg.CORBA.*; +import corba.framework.*; +import java.util.*; +import java.io.*; +import com.sun.corba.ee.spi.misc.ORBConstants ; + +/** + * NameServiceClient just tests that StandAlone Name Service that we + * ship with RI. The test makes sure that + * 1. Root NamingContext can be resolved using the -ORBInitRef property + * 2. Basic operations of Bind and Resolve works fine + */ +public class NameServiceClient implements InternalProcess { + public static void main( String args[] ) { + try { + (new NameServiceClient()).run( System.getProperties(), + args, System.out, System.err, null ); + } catch( Exception e ) { + e.printStackTrace( System.err ); + System.exit( 1 ); + } + } + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + try { + System.out.println( "Start of NameService test" ) ; + + String orbArguments[] = new String[2]; + orbArguments[0] = "-ORBInitRef"; + orbArguments[1] = "NameService=corbaloc:iiop:1.2@localhost:" + + TestConstants.RI_NAMESERVICE_PORT + "/NameService"; + Properties props = new Properties() ; + props.setProperty( ORBConstants.DEBUG_PROPERTY, "subcontract,giop,transport" ) ; + ORB orb = ORB.init( orbArguments, props ); + System.out.println( "Created ORB" ) ; + + org.omg.CORBA.Object object = orb.resolve_initial_references( + "NameService" ); + System.out.println( "Resolved NameService" ) ; + + org.omg.CosNaming.NamingContextExt namingContext = + org.omg.CosNaming.NamingContextExtHelper.narrow( object ); + System.out.println( "Narrowed NameService" ) ; + + NameComponent[] name = new NameComponent[1]; + name[0] = new NameComponent(); + name[0].id = "Test"; + name[0].kind = ""; + namingContext.bind( name, object ); + System.out.println( "Bound object in NameService" ) ; + + object = namingContext.resolve_str( "Test" ); + if( object == null ) { + System.err.println( "NamingContext resolve failed..." ); + System.exit( 1 ); + } + System.out.println( "Successfully resolved Standalone Name Server" + + " Using INS" ); + } catch ( Exception e ) { + System.out.println( "Caught exception " + e ) ; + e.printStackTrace(); + System.exit( 1 ); + } + } +} + + diff --git a/test/src/share/classes/naming/rinameservice/RINameServiceTest.java b/test/src/share/classes/naming/rinameservice/RINameServiceTest.java new file mode 100644 index 000000000..bc0420bcf --- /dev/null +++ b/test/src/share/classes/naming/rinameservice/RINameServiceTest.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.rinameservice; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + * RINameServiceTest compiles couple of JavaFiles (StandAlone NameServer and + * Simple Client to test INS functionality ) and starts RINameServer + * and a simple client to test that StandAlone NameServer works. + */ +public class RINameServiceTest extends CORBATest +{ + public static String[] javaFiles = {"NameServer.java", + "NameServiceClient.java"}; + + protected void doTest() throws Throwable + { + Options.setJavaFiles(javaFiles); + + compileJavaFiles( ); + + Controller client = createClient( + "naming.rinameservice.NameServiceClient" ); + Controller server = createServer( + "naming.rinameservice.NameServer" ); + + server.start(); + Thread.sleep( 10000 ); + client.start(); + Thread.sleep( 10000 ); + + server.stop(); + client.stop(); + } +} + + + + diff --git a/test/src/share/classes/naming/rinameservice/TestConstants.java b/test/src/share/classes/naming/rinameservice/TestConstants.java new file mode 100644 index 000000000..53445f36f --- /dev/null +++ b/test/src/share/classes/naming/rinameservice/TestConstants.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package naming.rinameservice; + +public class TestConstants { + public static final String RI_NAMESERVICE_PORT = "1050"; +} diff --git a/test/src/share/classes/omega/A.java b/test/src/share/classes/omega/A.java new file mode 100644 index 000000000..27c23260a --- /dev/null +++ b/test/src/share/classes/omega/A.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public interface A extends java.rmi.Remote { + void a() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/omega/AB.java b/test/src/share/classes/omega/AB.java new file mode 100644 index 000000000..59b84dd05 --- /dev/null +++ b/test/src/share/classes/omega/AB.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public class AB implements A, B { + + public void a() {} + public void b() {} + + // public void a() throws java.rmi.RemoteException {} + // public void b() throws java.rmi.RemoteException {} + + public static void main(String argv[]) { + System.out.println("hi"); + AB it = new AB(); + it.a(); + } +} diff --git a/test/src/share/classes/omega/B.java b/test/src/share/classes/omega/B.java new file mode 100644 index 000000000..e8adeeac3 --- /dev/null +++ b/test/src/share/classes/omega/B.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public interface B extends java.rmi.Remote { + void b() throws java.rmi.RemoteException; +} diff --git a/test/src/share/classes/omega/Bert.idlref b/test/src/share/classes/omega/Bert.idlref new file mode 100644 index 000000000..ff20dfe37 --- /dev/null +++ b/test/src/share/classes/omega/Bert.idlref @@ -0,0 +1,53 @@ +/** + * omega/Bert.idl + * Generated by rmic -idl. Do not edit + * 05 May 1999 15:50:27 GMT+00:00 + */ + + +#ifndef __omega_Bert__Fred__ + +module omega { + + abstract valuetype Bert__Fred; + +}; + +#endif + +#include "org/omg/CORBA/portable/IDLEntity.idl" +#include "omega/India.idl" +#include "omega/Hotel.idl" +#include "omega/Juliet.idl" +#include "omega/Golf.idl" +#include "org/omg/boxedIDL/omega/Foxtrot.idl" +#include "org/omg/boxedIDL/fake/omega/Kilo.idl" +#include "orb.idl" + +#ifndef __omega_Bert__ +#define __omega_Bert__ + + +module omega { + + valuetype Bert { + + private Object aCorbaObject; + private ::org::omg::boxedIDL::omega::Foxtrot aFoxtrot; + private ::omega::Bert__Fred aFred; + private ::omega::Golf aGolf; + private ::omega::Hotel aHotel; + private ::omega::Juliet aJuliet; + private ::org::omg::boxedIDL::fake::omega::Kilo aKilo; + private ::org::omg::CORBA::portable::IDLEntity anIDLEntity; + private ::omega::India anIndia; + + }; + +#pragma ID Bert "RMI:omega.Bert:FA5E0952EA06B261:BD82BBB67D9289F6" + +}; + +#include "omega/Bert__Fred.idl" +#endif + diff --git a/test/src/share/classes/omega/Bert.java b/test/src/share/classes/omega/Bert.java new file mode 100644 index 000000000..2fe6457b6 --- /dev/null +++ b/test/src/share/classes/omega/Bert.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// 5.2.5 + +package omega; + +public class Bert implements java.io.Serializable { + + class Fred {} + Foxtrot aFoxtrot; + Fred aFred; + + private Bert( int arg ) {} + private void aMethod( int arg ) {} + + org.omg.CORBA.Object aCorbaObject; + Golf aGolf; + org.omg.CORBA.portable.IDLEntity anIDLEntity; + Hotel aHotel; + India anIndia; + fake.omega.Juliet aJuliet; + fake.omega.Kilo aKilo; + +} diff --git a/test/src/share/classes/omega/Bert__Fred.idlref b/test/src/share/classes/omega/Bert__Fred.idlref new file mode 100644 index 000000000..7621a90bf --- /dev/null +++ b/test/src/share/classes/omega/Bert__Fred.idlref @@ -0,0 +1,21 @@ +/** + * omega/Bert__Fred.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 09:19:25 GMT+00:00 + */ + +#ifndef __omega_Bert__Fred__ +#define __omega_Bert__Fred__ + +#include "orb.idl" + + +module omega { + + valuetype Bert__Fred { + }; + +}; + +#endif + diff --git a/test/src/share/classes/omega/Climax.java b/test/src/share/classes/omega/Climax.java new file mode 100644 index 000000000..44457702c --- /dev/null +++ b/test/src/share/classes/omega/Climax.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* omega/Climax.java +* Generated by the IBM IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/Lima.idl +* 06 May 1999 17:02:50 o'clock GMT+00:00 +*/ + +public final class Climax extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity +{ + public int quickstep = (int)0; + + public Climax () + { + } // ctor + + public Climax (int _quickstep) + { + quickstep = _quickstep; + } // ctor + +} // class Climax diff --git a/test/src/share/classes/omega/Constants.java b/test/src/share/classes/omega/Constants.java new file mode 100644 index 000000000..a044e90bb --- /dev/null +++ b/test/src/share/classes/omega/Constants.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +import java.rmi.Remote; +import java.rmi.RemoteException; + +public interface Constants extends Remote { + + public final static byte BYTE = 1; + public final static short SHORT = 2; + public final static int INT = 3; + public final static long LONG = 4; + public final static char CHAR = 5; + public final static float FLOAT = 6; + public final static double DOUBLE = 7; + public final static String STRING = "abc"; + + public final static byte BYTE2 = 10; + public final static short SHORT2 = 20; + public final static int INT2 = 30; + public final static long LONG2 = 40L; + public final static char CHAR2 = 50; + public final static float FLOAT2 = 60F; + public final static double DOUBLE2 = 70D; + public final static String STRING2 = "def"; + +} diff --git a/test/src/share/classes/omega/Dolphin.idlref b/test/src/share/classes/omega/Dolphin.idlref new file mode 100644 index 000000000..951cea510 --- /dev/null +++ b/test/src/share/classes/omega/Dolphin.idlref @@ -0,0 +1,22 @@ +/** + * omega/Dolphin.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 11:34:55 GMT+00:00 + */ + +#ifndef __omega_Dolphin__ +#define __omega_Dolphin__ + +#include "orb.idl" + +module omega { + + valuetype Dolphin { + }; + +#pragma ID Dolphin "RMI:omega/Dolphin:9F4FEDF346664E1D" + +}; + +#endif + diff --git a/test/src/share/classes/omega/Dolphin.java b/test/src/share/classes/omega/Dolphin.java new file mode 100644 index 000000000..0ec70c0be --- /dev/null +++ b/test/src/share/classes/omega/Dolphin.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public class Dolphin implements java.io.Serializable{} diff --git a/test/src/share/classes/omega/Dromedary.java b/test/src/share/classes/omega/Dromedary.java new file mode 100644 index 000000000..a7dd61f82 --- /dev/null +++ b/test/src/share/classes/omega/Dromedary.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*----------------------------------------------------------------------------- + - name collision...two foo__longs would be generated +-----------------------------------------------------------------------------*/ + +package omega; + +public interface Dromedary extends java.rmi.Remote { + + void foo() throws java.rmi.RemoteException; + void foo( int i ) throws java.rmi.RemoteException; + void foo__long() throws java.rmi.RemoteException; + +} diff --git a/test/src/share/classes/omega/Foxtrot.java b/test/src/share/classes/omega/Foxtrot.java new file mode 100644 index 000000000..6ed1155a2 --- /dev/null +++ b/test/src/share/classes/omega/Foxtrot.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* genJava/omega/Foxtrot.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/Foxtrot.idl +* 22 April 1999 21:50:01 o'clock GMT+00:00 +*/ + +public final class Foxtrot implements org.omg.CORBA.portable.IDLEntity +{ + public int tango = (int)0; + public int uniform = (int)0; + public int quickstep = (int)0; + + public Foxtrot () + { + } // ctor + + public Foxtrot (int _tango, int _uniform, int _quickstep) + { + tango = _tango; + uniform = _uniform; + quickstep = _quickstep; + } // ctor + +} // class Foxtrot diff --git a/test/src/share/classes/omega/FruitbatEx.idlref b/test/src/share/classes/omega/FruitbatEx.idlref new file mode 100644 index 000000000..6307bff8c --- /dev/null +++ b/test/src/share/classes/omega/FruitbatEx.idlref @@ -0,0 +1,36 @@ +/** + * omega/FruitbatEx.idl + * Generated by rmic -idl. Do not edit + * Thursday, 19 November 1998 14:29:38 GMT + */ + +#ifndef __omega_FruitbatException__ +#define __omega_FruitbatException__ + +#include "orb.idl" +#include "omega/MammalEx.idl" + +module omega { + + valuetype FruitbatException: ::omega::MammalException { + + private long count; + init( + in ::CORBA::WStringValue arg0, + in long arg1 ); + long getCount( ); + + }; + + exception FruitbatEx { + + FruitbatException value; + + }; + +#pragma ID FruitbatException "RMI:omega/FruitbatException:74915202E7A81E44" + +}; + +#endif + diff --git a/test/src/share/classes/omega/FruitbatException.java b/test/src/share/classes/omega/FruitbatException.java new file mode 100644 index 000000000..da4c391de --- /dev/null +++ b/test/src/share/classes/omega/FruitbatException.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public class FruitbatException extends MammalException { + + public FruitbatException( String message, int count ) {} + public int getCount() { return 0; } + private int count; + +} diff --git a/test/src/share/classes/omega/Golf.java b/test/src/share/classes/omega/Golf.java new file mode 100644 index 000000000..b0e479528 --- /dev/null +++ b/test/src/share/classes/omega/Golf.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* genJava/omega/Golf.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/Golf.idl +* 22 April 1999 21:50:06 o'clock GMT+00:00 +*/ + +public interface Golf extends GolfOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ + public static final int uniform = (int)(2); +} // interface Golf diff --git a/test/src/share/classes/omega/GolfOperations.java b/test/src/share/classes/omega/GolfOperations.java new file mode 100644 index 000000000..034e043e6 --- /dev/null +++ b/test/src/share/classes/omega/GolfOperations.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* genJava/omega/GolfOperations.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/Golf.idl +* 22 April 1999 21:50:06 o'clock GMT+00:00 +*/ + +public interface GolfOperations +{ + int count (); + void bar (); +} // interface GolfOperations diff --git a/test/src/share/classes/omega/Hotel.java b/test/src/share/classes/omega/Hotel.java new file mode 100644 index 000000000..10ae856f6 --- /dev/null +++ b/test/src/share/classes/omega/Hotel.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* genJava/omega/Hotel.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/Hotel.idl +* 22 April 1999 22:03:20 o'clock GMT+00:00 +*/ + +public class Hotel implements org.omg.CORBA.portable.ValueBase +{ + public int tango = (int)0; + public int quickstep = (int)0; + + public Hotel () + { + } + + public String[] _truncatable_ids() { + return omega.HotelHelper.get_instance().get_truncatable_base_ids(); + } + + public void dolength (int length) + { + } + +} // class Hotel diff --git a/test/src/share/classes/omega/HotelHelper.java b/test/src/share/classes/omega/HotelHelper.java new file mode 100644 index 000000000..36cc5f25e --- /dev/null +++ b/test/src/share/classes/omega/HotelHelper.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* genJava/omega/HotelHelper.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/Hotel.idl +* 22 April 1999 22:03:19 o'clock GMT+00:00 +*/ + +public final class HotelHelper implements com.sun.org.omg.CORBA.portable.ValueHelper +{ + private static String _id = "IDL:omega/Hotel:1.0"; + + private static HotelHelper helper = new HotelHelper (); + + private static String[] _truncatable_ids = { + _id }; + + public HotelHelper() + { + } + + public static void insert (org.omg.CORBA.Any a, omega.Hotel that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static omega.Hotel extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + + // ValueMember instance for tango + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[0] = new org.omg.CORBA.ValueMember ("tango", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PUBLIC_MEMBER.value); + + // ValueMember instance for quickstep + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[1] = new org.omg.CORBA.ValueMember ("quickstep", + "", + _id, + "", + _tcOf_members0, + null, + org.omg.CORBA.PUBLIC_MEMBER.value); + + __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "Hotel", org.omg.CORBA.VM_NONE.value, null, _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static omega.Hotel read (org.omg.CORBA.portable.InputStream istream) + { + return (omega.Hotel) ((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (get_instance()); + } + + public java.io.Serializable read_value (org.omg.CORBA.portable.InputStream istream) + { + omega.Hotel value = new omega.Hotel (); + value.tango = istream.read_long (); + value.quickstep = istream.read_long (); + return value; + } + + public static void read (org.omg.CORBA.portable.InputStream istream, omega.Hotel value) + { + value.tango = istream.read_long (); + value.quickstep = istream.read_long (); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, omega.Hotel value) + { + ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, get_instance()); + } + + public void write_value (org.omg.CORBA.portable.OutputStream ostream, java.io.Serializable obj) + { + omega.Hotel value = (omega.Hotel) obj; + ostream.write_long (value.tango); + ostream.write_long (value.quickstep); + } + + public String get_id () + { + return _id; + } + + public org.omg.CORBA.TypeCode get_type () + { + return type (); + } + + public static com.sun.org.omg.CORBA.portable.ValueHelper get_instance () + { + return helper; + } + + public Class get_class () + { + return omega.Hotel.class; + } + + public String[] get_truncatable_base_ids () + { + return _truncatable_ids; + } + +} diff --git a/test/src/share/classes/omega/India.java b/test/src/share/classes/omega/India.java new file mode 100644 index 000000000..d7950dde9 --- /dev/null +++ b/test/src/share/classes/omega/India.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + + +/** +* genJava/omega/India.java +* Generated by the IDL-to-Java compiler (portable), version "3.0" +* from d:/java/java/idl/omega/India.idl +* 22 April 1999 21:50:17 o'clock GMT+00:00 +*/ + +public interface India extends org.omg.CORBA.portable.IDLEntity +{ + int count (); + void bar (); +} // interface India diff --git a/test/src/share/classes/omega/MammalEx.idlref b/test/src/share/classes/omega/MammalEx.idlref new file mode 100644 index 000000000..8114f96c2 --- /dev/null +++ b/test/src/share/classes/omega/MammalEx.idlref @@ -0,0 +1,10 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + diff --git a/test/src/share/classes/omega/MammalException.java b/test/src/share/classes/omega/MammalException.java new file mode 100644 index 000000000..232cbc87c --- /dev/null +++ b/test/src/share/classes/omega/MammalException.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public class MammalException extends java.lang.Exception{} + diff --git a/test/src/share/classes/omega/MammalOverload.idlref b/test/src/share/classes/omega/MammalOverload.idlref new file mode 100644 index 000000000..ff4dd0336 --- /dev/null +++ b/test/src/share/classes/omega/MammalOverload.idlref @@ -0,0 +1,25 @@ +// IDL generated by rmic, do not edit. + +#include "orb.idl" + +#ifndef __omega_MammalOverload__ +#define __omega_MammalOverload__ +#include "java/lang/Exception.idl" + +module omega{ + + value MammalOverload: ::java::lang::Exception { + }; + + exception MammalOverloadEx { + + MammalOverload value; + + }; + +#pragma ID MammalOverload "H:/omega/MammalOverload:F2FFB96AFA008BF6" + +}; + +#endif + diff --git a/test/src/share/classes/omega/MammalOverload.java b/test/src/share/classes/omega/MammalOverload.java new file mode 100644 index 000000000..0ddbeaf35 --- /dev/null +++ b/test/src/share/classes/omega/MammalOverload.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public class MammalOverload + extends java.lang.Exception{} diff --git a/test/src/share/classes/omega/MammalOverloadEx.idlref b/test/src/share/classes/omega/MammalOverloadEx.idlref new file mode 100644 index 000000000..7ae6f3091 --- /dev/null +++ b/test/src/share/classes/omega/MammalOverloadEx.idlref @@ -0,0 +1,29 @@ +/** + * omega/MammalOverloadEx.idl + * Generated by rmic -idl. Do not edit + * 19 November 1998 10:49:30 GMT+00:00 + */ + +#ifndef __omega_MammalOverload__ +#define __omega_MammalOverload__ + +#include "orb.idl" +#include "java/lang/Ex.idl" + +module omega { + + valuetype MammalOverload: ::java::lang::Exception { + }; + + exception MammalOverloadEx { + + MammalOverload value; + + }; + +#pragma ID MammalOverload "RMI:omega/MammalOverload:F2FFB96AFA008BF6" + +}; + +#endif + diff --git a/test/src/share/classes/omega/NCRemoteException.java b/test/src/share/classes/omega/NCRemoteException.java new file mode 100644 index 000000000..8a8e75589 --- /dev/null +++ b/test/src/share/classes/omega/NCRemoteException.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; +public class NCRemoteException extends java.rmi.RemoteException { + public static final char J_bar = 1; + + public String getHelp() {return "HELP!";} + + char J_foo; + char _foo; +} diff --git a/test/src/share/classes/omega/RedHerring.java b/test/src/share/classes/omega/RedHerring.java new file mode 100644 index 000000000..d37f053c5 --- /dev/null +++ b/test/src/share/classes/omega/RedHerring.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public class RedHerring implements java.io.Serializable {} + + diff --git a/test/src/share/classes/omega/Thrower.idlref b/test/src/share/classes/omega/Thrower.idlref new file mode 100644 index 000000000..93d7912f2 --- /dev/null +++ b/test/src/share/classes/omega/Thrower.idlref @@ -0,0 +1,36 @@ +/** + * omega/Thrower.idl + * Generated by rmic -idl. Do not edit + * 25 March 1999 15:13:26 GMT+00:00 + */ + +#ifndef __omega_Thrower__ +#define __omega_Thrower__ + +#include "orb.idl" + +module omega { + + valuetype FruitbatException; + +}; + +#include "omega/FruitbatEx.idl" + +module omega { + + interface Thrower { + + void doThrowFruitbat( ) raises ( + ::omega::FruitbatEx ); + readonly attribute ::omega::FruitbatException lastException; + + }; + +#pragma ID Thrower "RMI:omega.Thrower:0000000000000000" + +}; + +#include "omega/FruitbatEx.idl" +#endif + diff --git a/test/src/share/classes/omega/Thrower.java b/test/src/share/classes/omega/Thrower.java new file mode 100644 index 000000000..395b8868d --- /dev/null +++ b/test/src/share/classes/omega/Thrower.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package omega; + +public interface Thrower extends java.rmi.Remote { + + void doThrowFruitbat() throws FruitbatException, java.rmi.RemoteException; + FruitbatException getLastException() throws java.rmi.RemoteException; + + void doThrowClimax() throws Climax, java.rmi.RemoteException; + + void doThrowUser() throws org.omg.CORBA.UserException, java.rmi.RemoteException; + + //Climax getaClimax() throws java.rmi.RemoteException; + //void hurl() throws NCRemoteException, java.rmi.RemoteException; + //NCRemoteException getHurled() throws java.rmi.RemoteException; + +} diff --git a/test/src/share/classes/omega/Wallaby.idlref b/test/src/share/classes/omega/Wallaby.idlref new file mode 100644 index 000000000..56c43d24e --- /dev/null +++ b/test/src/share/classes/omega/Wallaby.idlref @@ -0,0 +1,34 @@ +/** + * omega/Wallaby.idl + * Generated by rmic -idl. Do not edit + * 26 November 1998 11:16:33 GMT+00:00 + */ + +#ifndef __omega_Wallaby__ +#define __omega_Wallaby__ + +#include "orb.idl" +#include "java/lang/Ex.idl" + +module omega { + + interface Wallaby { + + const long bar = 2; + void bar( ); + void eat( ) raises ( + ::java::lang::Ex ); + void drink( ); + long getFoo( ) raises ( + ::java::lang::Ex ); + void setFoo( + in long arg0 ); + readonly attribute ::CORBA::WStringValue URL; + attribute boolean boo; + + }; + +}; + +#endif + diff --git a/test/src/share/classes/omega/Wallaby.java b/test/src/share/classes/omega/Wallaby.java new file mode 100644 index 000000000..8f864275a --- /dev/null +++ b/test/src/share/classes/omega/Wallaby.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*----------------------------------------------------------------------------- + - bar() collides with constant + - eat(), getFoo() throw superclass of RemoteException + - drink() throws RemoteException and one of its subclasses +-----------------------------------------------------------------------------*/ + +package omega; + +public interface Wallaby extends java.rmi.Remote { + + int bar = 2; + void bar() throws java.rmi.RemoteException, + java.lang.RuntimeException; + void eat() throws Exception; + void drink() throws java.rmi.RemoteException, + java.rmi.NoSuchObjectException; + + int getFoo() throws Exception; + void setFoo(int x) throws java.rmi.RemoteException, + java.rmi.NoSuchObjectException; + String getURL() throws java.rmi.RemoteException, + java.lang.RuntimeException; + boolean isBoo() throws java.rmi.RemoteException; + void setBoo(boolean b) throws java.rmi.RemoteException; + +} diff --git a/test/src/share/classes/performance/Tests.tdesc b/test/src/share/classes/performance/Tests.tdesc new file mode 100644 index 000000000..be5a7b529 --- /dev/null +++ b/test/src/share/classes/performance/Tests.tdesc @@ -0,0 +1,11 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +-test performance.simpleperf.SimplePerfTest +-test performance.simpleperf2.SimplePerfTest diff --git a/test/src/share/classes/performance/simpleperf/SimplePerfTest.java b/test/src/share/classes/performance/simpleperf/SimplePerfTest.java new file mode 100644 index 000000000..878dfae2a --- /dev/null +++ b/test/src/share/classes/performance/simpleperf/SimplePerfTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf; + +import com.sun.corba.ee.spi.misc.ORBConstants; + +import corba.framework.CORBATest; +import corba.framework.Controller; +import corba.framework.InternalExec; +import corba.framework.Options; + +public class SimplePerfTest extends CORBATest +{ + protected Controller newClientController() + { + return new InternalExec(); + } + + protected void doTest() throws Throwable + { + Options.setOutputDirectory((String)getArgs().get(test.Test.OUTPUT_DIRECTORY)); + Options.addServerArg("-debug"); + + Controller orbd = createORBD(); + Controller client = createClient("performance.simpleperf.counterClient"); + + orbd.start(); + + client.start(); + + client.waitFor(); + + client.stop(); + orbd.stop(); + } +} + diff --git a/test/src/share/classes/performance/simpleperf/counterIF.java b/test/src/share/classes/performance/simpleperf/counterIF.java new file mode 100644 index 000000000..faca109d7 --- /dev/null +++ b/test/src/share/classes/performance/simpleperf/counterIF.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface counterIF extends java.rmi.Remote { + public long increment( long invalue ) throws java.rmi.RemoteException ; +} diff --git a/test/src/share/classes/performance/simpleperf/counterImpl.java b/test/src/share/classes/performance/simpleperf/counterImpl.java new file mode 100644 index 000000000..a741b3bf8 --- /dev/null +++ b/test/src/share/classes/performance/simpleperf/counterImpl.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf; + +import java.rmi.RemoteException ; +import javax.rmi.PortableRemoteObject ; +import org.omg.CORBA.ORB ; +import java.io.File ; +import java.io.RandomAccessFile ; +import org.omg.PortableServer.POA ; + +public class counterImpl extends PortableRemoteObject implements counterIF +{ + private int value ; + + public counterImpl() throws RemoteException + { + value = 0 ; + } + + public synchronized long increment(long invalue) throws RemoteException + { + value += invalue; + + return value; + } +} + diff --git a/test/src/share/classes/performance/simpleperf/counterServer.java b/test/src/share/classes/performance/simpleperf/counterServer.java new file mode 100644 index 000000000..d25cb1883 --- /dev/null +++ b/test/src/share/classes/performance/simpleperf/counterServer.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf; + +import javax.rmi.PortableRemoteObject ; +import java.util.Properties ; + +import org.omg.CORBA.ORB ; +import org.omg.CORBA.Policy ; +import org.omg.CosNaming.NameComponent ; +import org.omg.CosNaming.NamingContext ; +import org.omg.CosNaming.NamingContextHelper ; +import org.omg.PortableServer.LifespanPolicyValue ; +import org.omg.PortableServer.POA ; +import org.omg.PortableServer.RequestProcessingPolicyValue ; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantLocator ; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; +import org.omg.PortableServer.ServantRetentionPolicyValue ; + +import com.sun.corba.ee.spi.misc.ORBConstants ; +import corba.framework.ThreadProcess ; + +public class counterServer extends ThreadProcess { + + public void run() + { + try{ + // create and initialize the ORB + Properties p = new Properties(); + p.put("org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + p.put( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, "9999"); + p.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "9999"); + String[] args = null ; + ORB orb = ORB.init(args, p); + + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + POA poa = createPOA(orb, rootPOA); + createCounter1(orb, poa); + + // wait for invocations from clients + System.out.println("Server is ready."); + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + } + + private POA createPOA(ORB orb, POA rootPOA) + throws Exception + { + // create a persistent POA + Policy[] tpolicy = new Policy[3]; + tpolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT); + tpolicy[1] = rootPOA.create_request_processing_policy(RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + tpolicy[2] = rootPOA.create_servant_retention_policy(ServantRetentionPolicyValue.NON_RETAIN) ; + POA tpoa = rootPOA.create_POA("PersistentPOA", null, tpolicy); + + counterImpl impl = new counterImpl(); + Servant servant = (Servant)(javax.rmi.CORBA.Util.getTie( impl ) ) ; + CSLocator csl = new CSLocator(servant); + tpoa.set_servant_manager(csl); + tpoa.the_POAManager().activate(); + return tpoa; + } + + private void createCounter1(ORB orb, POA tpoa) + throws Exception + { + // create an objref using POA + byte[] id = "abcdef".getBytes(); + String intf = "" ; // new _counterImpl_Tie()._all_interfaces(tpoa,id)[0]; + + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, intf); + + counterIF counterRef + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + // put objref in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Counter1", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + } +} + +class CSLocator extends org.omg.CORBA.LocalObject implements ServantLocator +{ + Servant servant; + + CSLocator(Servant servant) + { + this.servant = servant; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + return servant ; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + return; + } +} diff --git a/test/src/share/classes/performance/simpleperf2/SimplePerfTest.java b/test/src/share/classes/performance/simpleperf2/SimplePerfTest.java new file mode 100644 index 000000000..247a2e999 --- /dev/null +++ b/test/src/share/classes/performance/simpleperf2/SimplePerfTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf2; + +import test.Test; +import corba.framework.*; +import java.util.*; + +public class SimplePerfTest extends CORBATest +{ + protected Controller newClientController() + { + return new InternalExec(); + } + + protected void doTest() throws Throwable + { + Options.setOutputDirectory((String)getArgs().get(test.Test.OUTPUT_DIRECTORY)); + Options.addServerArg("-debug"); + + // Controller orbd = createORBD(); + Controller client = createClient("performance.simpleperf2.counterClient"); + + // orbd.start(); + + client.start(); + + client.waitFor(); + + client.stop(); + // orbd.stop(); + } +} + diff --git a/test/src/share/classes/performance/simpleperf2/counterClient.java b/test/src/share/classes/performance/simpleperf2/counterClient.java new file mode 100644 index 000000000..88da1afcd --- /dev/null +++ b/test/src/share/classes/performance/simpleperf2/counterClient.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf2; + +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.Properties; + +import javax.rmi.PortableRemoteObject ; +import java.rmi.RemoteException ; + +import org.omg.CORBA.ORB; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.Servant ; +import org.omg.PortableServer.ServantLocator; +import org.omg.PortableServer.ServantLocatorPackage.CookieHolder ; + +import corba.framework.InternalProcess; + +public class counterClient implements InternalProcess +{ + private counterIF createLocalObject( ORB orb ) + throws java.rmi.RemoteException + { + counterImpl cimpl = new counterImpl() ; + + return cimpl ; + } + + private counterIF createRemoteObject( ORB orb ) + throws java.rmi.RemoteException + { + counterImpl obj = new counterImpl() ; + + counterIF counterRef + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + return counterRef ; + } + + private counterIF createRemoteObjectMarshal( ORB orb ) + throws java.rmi.RemoteException, java.rmi.NoSuchObjectException + { + counterImpl obj = new counterImpl() ; + + counterIF counterRef + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + java.rmi.Remote stub = PortableRemoteObject.toStub( counterRef ) ; + + String str = orb.object_to_string( (org.omg.CORBA.Object)stub ) ; + org.omg.CORBA.Object obj2 = orb.string_to_object( str ) ; + + return (counterIF)(PortableRemoteObject.narrow( obj2, + counterIF.class )) ; + } + + private static final int COUNT = 10000 ; + + private void performTest(PrintStream out, counterIF counterRef, + String testType ) throws RemoteException + { + long time = System.currentTimeMillis() ; + long value = 0 ; + + for (int i = 0; i < COUNT; i++) { + value += counterRef.increment(1); + } + + double elapsed = System.currentTimeMillis() - time ; + + out.println( "Test " + testType + ": Elapsed time per invocation = " + + elapsed/COUNT + " milliseconds" ) ; + } + + public void run(Properties environment, + String args[], + PrintStream out, + PrintStream err, + Hashtable extra) throws Exception + { + environment.list(out); + + try { + // create and initialize the ORB + ORB orb = ORB.init(args, environment); + + counterIF counterRef1 = createLocalObject( orb ) ; + performTest(out, counterRef1, "local object" ); + + counterIF counterRef2 = createRemoteObject( orb ) ; + performTest(out, counterRef2, "local RMI-IIOP" ); +/* There are problems here that need further investigation + counterIF counterRef3 = createRemoteObjectMarshal( orb ) ; + performTest(out, counterRef3, "local RMI-IIOP (marshalled)" ); +*/ + } catch (Exception e) { + e.printStackTrace(err); + throw e; + } + } + + public static void main(String args[]) + { + try { + (new counterClient()).run(System.getProperties(), + args, + System.out, + System.err, + null); + + } catch (Exception e) { + System.err.println("ERROR : " + e) ; + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +class CounterServantLocator extends org.omg.CORBA.LocalObject implements ServantLocator +{ + Servant servant; + + CounterServantLocator(Servant servant) + { + this.servant = servant; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + return servant ; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + return; + } +} diff --git a/test/src/share/classes/performance/simpleperf2/counterIF.java b/test/src/share/classes/performance/simpleperf2/counterIF.java new file mode 100644 index 000000000..211ffdeb8 --- /dev/null +++ b/test/src/share/classes/performance/simpleperf2/counterIF.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf2; + +import java.rmi.Remote ; +import java.rmi.RemoteException ; + +public interface counterIF extends java.rmi.Remote { + public long increment( long invalue ) throws java.rmi.RemoteException ; +} diff --git a/test/src/share/classes/performance/simpleperf2/counterImpl.java b/test/src/share/classes/performance/simpleperf2/counterImpl.java new file mode 100644 index 000000000..b5978d97c --- /dev/null +++ b/test/src/share/classes/performance/simpleperf2/counterImpl.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf2; + +import java.rmi.RemoteException ; +import javax.rmi.PortableRemoteObject ; +import org.omg.CORBA.ORB ; +import java.io.File ; +import java.io.RandomAccessFile ; +import org.omg.PortableServer.POA ; + +public class counterImpl extends PortableRemoteObject implements counterIF +{ + private int value ; + + public counterImpl() throws RemoteException + { + value = 0 ; + } + + public synchronized long increment(long invalue) throws RemoteException + { + value += invalue; + + return value; + } +} + diff --git a/test/src/share/classes/performance/simpleperf2/counterServer.java b/test/src/share/classes/performance/simpleperf2/counterServer.java new file mode 100644 index 000000000..26f1a2d96 --- /dev/null +++ b/test/src/share/classes/performance/simpleperf2/counterServer.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package performance.simpleperf2; + +import javax.rmi.PortableRemoteObject ; +import java.io.*; +import java.io.DataOutputStream ; +import java.util.*; +import java.rmi.RemoteException ; +import org.omg.CORBA.*; +import org.omg.CosNaming.*; +import org.omg.PortableServer.*; +import org.omg.PortableServer.ServantLocatorPackage.*; +import com.sun.corba.ee.spi.misc.ORBConstants ; +import corba.framework.ThreadProcess ; + +public class counterServer extends ThreadProcess { + + public void run() + { + try{ + // create and initialize the ORB + Properties p = new Properties(); + p.put("org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + p.put( ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, "9999"); + p.put( ORBConstants.ORB_SERVER_ID_PROPERTY, "9999"); + String[] args = null ; + ORB orb = ORB.init(args, p); + + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + POA poa = createPOA(orb, rootPOA); + createCounter1(orb, poa); + + // wait for invocations from clients + System.out.println("Server is ready."); + orb.run(); + + } catch (Exception e) { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + System.exit(1); + } + } + + private POA createPOA(ORB orb, POA rootPOA) + throws Exception + { + // create a persistent POA + Policy[] tpolicy = new Policy[3]; + tpolicy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT); + tpolicy[1] = rootPOA.create_request_processing_policy(RequestProcessingPolicyValue.USE_SERVANT_MANAGER); + tpolicy[2] = rootPOA.create_servant_retention_policy(ServantRetentionPolicyValue.NON_RETAIN) ; + POA tpoa = rootPOA.create_POA("PersistentPOA", null, tpolicy); + + counterImpl impl = new counterImpl(); + Servant servant = (Servant)(javax.rmi.CORBA.Util.getTie( impl ) ) ; + CSLocator csl = new CSLocator(servant); + tpoa.set_servant_manager(csl); + tpoa.the_POAManager().activate(); + return tpoa; + } + + private void createCounter1(ORB orb, POA tpoa) + throws Exception + { + // create an objref using POA + byte[] id = "abcdef".getBytes(); + String intf = "" ; // new _counterImpl_Tie()._all_interfaces(tpoa,id)[0]; + + org.omg.CORBA.Object obj = tpoa.create_reference_with_id(id, intf); + + counterIF counterRef + = (counterIF)PortableRemoteObject.narrow(obj, counterIF.class ); + + // put objref in NameService + org.omg.CORBA.Object objRef = + orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent("Counter1", ""); + NameComponent path[] = {nc}; + + ncRef.rebind(path, obj); + } +} + +class CSLocator extends org.omg.CORBA.LocalObject implements ServantLocator +{ + Servant servant; + + CSLocator(Servant servant) + { + this.servant = servant; + } + + public Servant preinvoke(byte[] oid, POA adapter, String operation, + CookieHolder the_cookie) + throws org.omg.PortableServer.ForwardRequest + { + return servant ; + } + + public void postinvoke(byte[] oid, POA adapter, String operation, + java.lang.Object cookie, Servant servant) + { + return; + } +} diff --git a/test/src/share/classes/pi/PITests.tdesc b/test/src/share/classes/pi/PITests.tdesc new file mode 100644 index 000000000..90f4b5be3 --- /dev/null +++ b/test/src/share/classes/pi/PITests.tdesc @@ -0,0 +1,30 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +// Batch tests +// Run 'java test.Test' for syntax +// +// These are the PI Technologies tests found under +// test/src/share/classes/pi +// + +// This is an important test, but it does not +// currently run: it seems to be missing the ArbitraryObjectServiceImpl class. +// -test pi.serviceexample.ServiceExampleTest + +-test pi.ort.ORTTest +-test pi.iorinterceptor.IORInterceptorTest +-test pi.codec.CodecTest +-test pi.orbinit.ORBInitTest + +-test pi.clientinterceptor.ClientInterceptorTest +-test pi.clientrequestinfo.ClientRequestInfoTest +-test pi.serverinterceptor.ServerInterceptorTest +-test pi.serverrequestinfo.ServerRequestInfoTest +-test pi.policyfactory.PolicyFactoryTest diff --git a/test/src/share/classes/pi/assertions.html b/test/src/share/classes/pi/assertions.html new file mode 100644 index 000000000..f5dfa5490 --- /dev/null +++ b/test/src/share/classes/pi/assertions.html @@ -0,0 +1,840 @@ + + + + + + + + Assertions Covered by PI Tests + + + +

                    +Assertions Covered by PI Tests

                    +This document enumerates the assertions covered by each PI test. The PI +tests can be found in the test/src/share/classes/pi/ directory. +

                    + +
                    Test: pi.codec

                    +Tests Codec and CodecFactory as covered in orbos/99-12-02, Chapter 10. +

                    +Assertions covered:

                    +CodecFactory: +
                      +
                    • +The CodecFactory is obtained through a call to ORB::resolve_initial_references( +"CodecFactory" )
                    • + +
                    • +A Codec is obtained from the Codec Factory
                    • + +
                    • +Formats ENCODING_CDR_ENCAPS, versions 1.0, 1.1, 1.2 supported.
                    • + +
                    • +codec_encoding raises UnknownEncoding if this factory cannot create a Codec +of the given encoding.
                    • + +
                    • +Method coverage: CodecFactory::create_codec
                    • +
                    +Codec: +
                      +
                    • +FormatMismatch raised if decode or decode_value called when data in the +provided octet sequence cannot be decoded into an any.
                    • + +
                    • +Method coverage: Codec::encode, decode, encode_value, decode_value for +all available codecs.
                    • +
                    + +

                    +Assertions not covered in this test:

                    +Codec: +
                      +
                    • +InvalidTypeForEncoding raised by encode or encode_value when the type is +invalid for the encoding. Reason: Currently no way to detect this in CDROutputStream.
                    • + +
                    • +TypeMismatch raised by decode_value when the given TypeCode does not match +the octet sequence. Reason: Currently no way to detect this in CDRInputStream. +FormatMismatch raised instead.
                    • +
                    + +

                    + +
                    Test: pi.orbinit

                    +Tests Registering Interceptors, as covered in orbos/99-12-02, Chapter 9. +

                    +Assertions covered:

                    +ORBInitializer: +
                      +
                    • +Correct ORBInitializers found and instantiated given system properties.
                    • + +
                    • +When an ORB is initializing, it shall call each registered ORBInitializer, +passing it an ORBInitInfo object.
                    • +
                    +ORBInitInfo: +
                      +
                    • +Interceptors cannot be registered on an ORB after it has been returned +by a call to ORB_init - This is implicit in the current way interceptors +are registered in Java.
                    • + +
                    • +All calls to ORBInitInfo::resolve_initial_references must be made in post_init, +not pre_init.
                    • + +
                    • +resolve_initial_references raises InvalidName at appropriate times
                    • + +
                    • +arguments, orb_id, and codec_factory contain valid values
                    • + +
                    • +add_*_interceptor raises DuplicateName at appropriate times
                    • + +
                    • +Function coverage: resolve_initial_references, add_*_interceptor
                    • + +
                    • +If a service keeps a reference to its ORBInitInfo object and tries to use +it after ORB_init returns, the object no longer exists and an OBJECT_NOT_EXIST +exception shall be raised.
                    • +
                    + +

                    +Assertions not covered in this test:

                    +ORBInitializer: +
                      +
                    • +Request Interceptors are registered on a per-ORB basis. Timestaking to +test, and it fairly evident from clear-box testing.
                    • +
                    +ORBInitInfo: +
                      +
                    • +All calls to ORBInitInfo::register_initial_reference must be made in pre_init, +not post_init. This is implemented, but will not be uncommented until completion +of PI implementation.
                    • + +
                    • +register_initial_reference raises InvalidName at appropriate times - To +be tested at completion of PI implementation.
                    • + +
                    • +Any number of anonymous Interceptors may be registered with the ORB.
                    • + +
                    • +Registration of multiple anonymous interceptors do not raise DuplicateName
                    • + +
                    • +Function coverage: register_initial_reference - To be tested at completion +of PI implementation.
                    • + +
                    • +Function coverage: allocate_slot_id - To be tested in PICurrent test.
                    • + +
                    • +Function coverage: register_policy_factory - To be tested in PolicyFactory +test.
                    • + +
                    • +register_policy_factory raises BAD_INV_ORDER with minor code of TBD_BIO+2 +if PolicyFactory already exists for the given policy type.
                    • +
                    + +

                    + +
                    Test: pi.iorinterceptor

                    +Tests IORInterceptor and IORInfo, as covered in orbos/99-12-02, Chapter +7. +

                    +Assertions covered:

                    +IORInterceptor: +
                      +
                    • +A server side ORB calls the establish_components operation on all registered +IORInterceptor instances when it is assembling the list of components that +will be included in the profile or profiles of an object reference.
                    • + +
                    • +The ORB shall ignore any exceptions thrown by an implementation of IORInterceptor.
                    • + +
                    • +POAManager state changes are notified to a CORBA 3.* compliant IORInterceptor
                    • + +
                    • +POA Destroyed notifications are sent to CORBA 3.* compliant IORInterceptor
                    • +
                    +IORInfo: +
                      +
                    • +add_ior_component and add_ior_component_to_profile adds a tagged component +to the set which will be included when constructing IORs. add_ior_component +will cause a tagged component to be added to all profiles. add_ior_component_to_profile +causes a tagged component to be added to only the profile with the specified +id. Note that, in our ORB this all reduces to the same thing since we +only ever have an IIOP profile.
                    • + +
                    • +any number of components may exist with the same component ID.
                    • + +
                    • +add_ior_component: If the given profile ID does not define a known profile +or it is impossible to add components to that profile, BAD_PARAM is raised +with a minor code of TBD_BP + 3.
                    • +
                    + +

                    +Assertions not covered in this test:

                    +IORInterceptor: +
                      +
                    • +
                    • +
                    +IORInfo: +
                      +
                    • +get_effective_policy - To be tested when implemented.
                    • +
                    + +
                      +

                    + +

                    + +

                    +Test: pi.ort

                    +Tests ORT state changes. +

                    +Assertions covered:

                    +IORInterceptor: +
                      +
                    • +POAManager state changes are notified to a CORBA 3.* compliant IORInterceptor
                    • + +
                    • +POA Destroyed notifications are sent to CORBA 3.* compliant IORInterceptor
                    • +
                    + +
                        +
                      +
                    + +

                    +Test: pi.picurrent

                    +Tests Portable Interceptor Current, as covered in orbos/99-12-02, Chapter +6. +

                    +Assertions covered:

                    +current: +
                      +
                    • +Tests resolve_initial_references( "PICurrent" ).
                    • + +
                    • +Test PIORB.allocateSlotId( ).
                    • + +
                    • +Tests PICurrent.get_slot() and set_slot().
                    • + +
                    • +Tests PICurrent by creating another thread.
                    • + +
                    • + Tests internal working of PIORB.pushPICurrent() and popPICurrent().
                    • +
                    + +

                    +Assertions not covered in this test:

                    +current: +
                      +
                    • +Testing the PICurrent feature from the Interception points.
                    • +
                    + +

                    + +
                    Test: pi.clientinterceptor

                    +Tests ClientRequestInterceptor, as covered in orbos/99-12-02, Chapter 5.2. +

                    +Assertions covered:

                    +ClientRequestInterceptor: +
                      +
                    • +send_request (5.2.1.1.)
                    • + +
                        +
                      • +invoked before request is sent to server
                      • + +
                      • +SYSTEM_EXCEPTION raised implies no other interceptors' send_request operations +are called.  Those Interceptors on the Flow stack are popped and their +receive_exception interception points are called.
                      • + +
                      • +ForwardRequest raised implies no other Interceptors' send_request operations +are called.  Those interceptors on the flow stack are popped and their +receive_other interception points are called.
                      • +
                      + +
                    • +receive_reply (5.2.1.3.)
                    • + +
                        +
                      • +invoked after it is returned from the server and before control is returned +to the client.
                      • + +
                      • +SYSTEM_EXCEPTION raised implies no other Interceptors' receive_reply operations +are called.  The remaining interceptors in the flow stack shall have +their receive_exception interception point called.
                      • +
                      + +
                    • +receive_exception (5.2.1.4.)
                    • + +
                        +
                      • +invoked when an exception occurs.
                      • + +
                      • +ForwardRequest implies no other interceptors' receive_exception operations +are called.  The remaining Interceptors in the flow stack are popped +and have their receive_other interception point called.
                      • +
                      + +
                    • +receive_other (5.2.1.5.)
                    • + +
                        +
                      • +invoked when a request results in something other than a normal reply or +an exception.
                      • + +
                      • +SYSTEM_EXCEPTION raised implies no other Interceptors' receive_other operations +are called.  The remaining interceptrs in the flow stack are popped +and have their receive_exception interception point called.
                      • +
                      + +
                    • +The interceptor list is traversed in order on the sending interception +points and in reverse order on the receiving interception points. (5.2.2.)
                    • + +
                    • +Client-side Flow Rules:
                    • + +
                        +
                      • +One and only one of send_request or send_poll is called on any given request/reply +sequence. (5.2.2.1.)
                      • + +
                      • +One and only one of receive_reply, receive_exception, or receive_other +is called on any given request/reply sequence (5.2.2.1.)
                      • + +
                      • +If and only if send_request or send_poll runs to completion is an ending +interception point called.
                      • +
                      + +
                    • +Interceptors are called on all ORB mediated invocations (5.1.1.) - Will +be tested once implemented.
                    • + +
                    • +Works in POA Remote case (client and server in different processes, POA +is used).
                    • + +
                    • +Works in POA Local case (client and server in same process, same orb, POA +is used).
                    • + +
                    • +Works in RMI/IIOP case (client and server in different processes, RMI/IIOP +is used).
                    • +
                    + +

                    +Assertions not covered in this test:

                    +ClientRequestInterceptor: +
                      +
                    • +send_poll (5.2.1.2.) - This feature is not available in our ORB.  +This will be tested once messaging is implemented in our ORB.
                    • + +
                    • +COMM_FAILURE or similar exception may result in a retry of the request.  +While this retry is a new request with respect to interceptors, there is +one point of correlation between the original request and the retry:  +because control has not returned to the client, the PortableInterceptor::Current +for both the original request and the retrying request is the same. (5.2.1.4.) +- Difficult to simulate these conditions in a test.
                    • + +
                    • +Same as above for ForwardRequest (5.2.1.5.) - Will be tested once implemented.
                    • + +
                    • +If, during request processing, a request is canceled because of an ORB +shutdown, receive_exception is called with the system exception BAD_INV_ORDER +with a minor code of 4 (ORB has shutdown). - Will be tested once implemented.
                    • + +
                    • +If a request is canceled for any other reason (e.g., a GIOP cancel message +is sent by the ORB), receive_exception is called with the system exception +TRANSIENT with a minor code of TBD_T (5.2.2.2.). - Will be tested once +implemented.
                    • + +
                    • +One a oneway call, receive_reply is called before control is returned to +the client (5.2.2.2.) - Spec requires clarification.
                    • + +
                    • +Asynchronous requests handling (5.2.2.2.) - Not implemented in our ORB.
                    • + +
                    • +A request Interceptor may make object invocations itself before allowing +the current request to execute. (5.1.1.) - Will be tested in PICurrent
                    • +
                    + +

                    + +
                    Test:pi.clientrequestinfo

                    +Tests ClientRequestInfo, as covered in orbos/99-12-02, Chapter 5.4.1. and +5.4.2.  Also tests RequestInfo in the context of a client request. +

                    +Assertions covered:

                    +RequestInfo: +
                      +
                    • +Each interception point is given an object through which the Interceptor +can access request information. (5.4.)
                    • + +
                    • +request_id (5.4.1.1.):
                    • + +
                        +
                      • +same for request as for reply
                      • + +
                      • +unique for each currently active request/reply sequence.
                      • +
                      + +
                    • +operation (5.4.1.2.) - Name of the operation being invoked.
                    • + +
                    • +response_expected (5.4.1.8.) - false for oneway, true for all else.
                    • + +
                    • +sync_scope (5.4.1.9.) - Our ORB always returns Messaging::SYNC_WITH_TRANSPORT
                    • + +
                    • +reply_status (5.4.1.10.) - For clients:
                    • + +
                        +
                      • +within receive_reply this value is successful
                      • + +
                      • +within receive_exception this value is SYSTEM_EXCEPTION or USER_EXCEPTION.
                      • + +
                      • +within receive_other, this value is SUCCESSFUL, LOCATION_FORWARD, LOCATION_FORWARD_PERMANENT, +or TRANSPORT_RETRY.
                      • +
                      + +
                    • +forward_reference (5.4.1.11)
                    • + +
                        +
                      • +if reply_status is LOCATION_FORWARD or LOCATION_FORWARD_PERMANENT, contains +object to which the request will be forwarded.
                      • + +
                      • +if reply_status is anything else, BAD_INV_ORDER is thrown with a minor +code of TBD_BIO.
                      • +
                      + +
                    • +get_request_service_context (5.4.1.13):
                    • + +
                        +
                      • +returns a *copy* of the service context with the given id.
                      • + +
                      • +If the request's service context does not contain an entry for that ID, +BAD_PARAM with a minor code of TBD_BP is raised.
                      • +
                      +
                    +ClientRequestInfo: +
                      +
                    • +ClientRequestInfo validity table is implemented (5.4.2.), table 5-1.
                    • + +
                    • +effective_target (5.4.2.2.)
                    • + +
                        +
                      • +The actual object on which the operation will be invoked.
                      • + +
                      • +LOCATION_FORWARD: Contains forwarded IOR on all subsequent requests.
                      • + +
                      • +LOCATION_FORWARD_PERMANENT: Contains forwarded IOR on all subsequent requests.
                      • +
                      + +
                    • +effective_profile (5.4.2.3)
                    • + +
                        +
                      • +the profile that will be used to send the request.
                      • + +
                      • +If a location forward has occurred for this operation's object and that +object's profile changed accordingly, then this profile will be that located +profile.
                      • +
                      + +
                    • +received_exception (5.4.2.4)
                    • + +
                        +
                      • +returns an any which contains the exception to be returned to the client.
                      • + +
                      • +works with SystemException
                      • + +
                      • +works with UserException
                      • +
                      + +
                    • +received_exception_id (5.2.4.5) - repository ID of the exception to be +returned to the client.
                    • + +
                    • +add_request_service_context (5.4.2.9)
                    • + +
                        +
                      • +Allows interceptors to add service contexts to request.
                      • + +
                      • +If replace is false and service context already exists with the given ID, +BAD_INV_ORDER( TBD_BIO + 1 ).
                      • + +
                      • +If replace is true and service context already exists with the given ID, +it is replaced.
                      • +
                      +
                    + +

                    +Assertions not covered in this test:

                    +RequestInfo: +
                      +
                    • +arguments (5.4.1.3.) - Will be tested once DII is implemented.
                    • + +
                    • +exceptions (5.4.1.4.) - Will be tested once DII is implemented.
                    • + +
                    • +contexts (5.4.1.5.) - Will be tested once DII is implemented.
                    • + +
                    • +operation_context (5.4.1.6.) - Will be tested once DII is implemented.
                    • + +
                    • +result (5.4.1.7.) - Will be tested once DII is implemented.
                    • + +
                    • +get_slot (5.4.1.12) - Will be tested once PICurrent is integrated with +client request interceptors.
                    • + +
                    • +get_reply_service_context (5.4.1.14) - Will be tested once ServerRequestInfo +is implemented.
                    • + +
                        +
                      • +returns a *copy* of the service context with the given id that is +associated with the reply.
                      • + +
                      • +If the request's service context does not contain an entry for that ID, +BAD_PARAM with a minor code of TBD_BP is raised.
                      • +
                      + +
                    • +target (5.4.2.1.) - Will be tested once new IOR code is put back.
                    • + +
                        +
                      • +The object which the client called to perform the operation.
                      • + +
                      • +LOCATION_FORWARD: Contains original IOR on all subsequent requests.
                      • + +
                      • +LOCATION_FORWARD_PERMANENT: Contains forwarded IOR on all subsequent requests.
                      • +
                      + +
                    • +get_effective_component (5.4.2.6) - Will be tested once IORInterceptor +and new IOR code is put back.
                    • + +
                        +
                      • +Returns TaggedComponent with the given ID from the profile selected for +this request.
                      • + +
                      • +If no component exists for the given component ID, BADPARAM( TBD_BP + 2 +)
                      • +
                      + +
                    • +get_effective_components (5.4.2.7) - Will be tested once IORInterceptor +and new IOR code is put back.
                    • + +
                        +
                      • +Returns TaggedComponent[] with the given ID from the profile selected for +this request.
                      • + +
                      • +If no component exists for the given component ID, BAD_PARAM( TBD_BP + +2 )
                      • +
                      + +
                    • +get_request_policy (5.4.2.8) - Throws NO_IMPLEMENT in our ORB.
                    • + +
                        +
                      • +Returns the policy in effect for this operation.
                      • + +
                      • +If policy type is invalid, INV_POLICY( TBD_IP )
                      • +
                      + +
                    • +In recevied_exception(), if user exception cannot be inserted into an any, +then returns any with UNKNOWN( TBD_U ). - Difficult to test.
                    • +
                    + +

                    + +
                    Test: pi.serverinterceptor

                    +Tests ServerRequestInterceptor, as covered in orbos/99-12-02, Chapter 5.3. +

                    +Assertions covered:

                    +ServerRequestInterceptor: +
                      +
                    • +receive_request_service_contexts (5.3.1.1)
                    • + +
                        +
                      • +invoked before the servant manager is called.
                      • + +
                      • +SYSTEM_EXCEPTION raised implies no other Interceptors' receive_request_service_contexts +operations are called.  Those interceptors on the flow stack are popped +and their send_exception interception points are called.
                      • + +
                      • +ForwardRequest raised implies no other Interceptors' receive_Request_service_contexts +operations are called.  Those Interceptors on the flow stack are popped +and their send_other interception points are called.
                      • +
                      + +
                    • +receive_request (5.3.1.2)
                    • + +
                        +
                      • +In the DSI model, the ORB shall guarantee that receive_request is called +once, either through arguments or through set_exception.
                      • + +
                      • +In the DSI model, if receive_request is called through set_exception, requesting +the arguments will result in NO_RESOURCES being raised with a minor code +of TBD_NR.
                      • + +
                      • +SYSTEM_EXCEPTION raised implies no other Interceptors' receive_request +operations are called.  Those Interceptors on the FlowStack are popped +and their send_exception interception points are called.
                      • + +
                      • +ForwardRequest raised implies no other Interceptors' receive_request operations +are called.  Those Interceptors on the Flow Stack are popped and their +send_other interception points are called.
                      • +
                      + +
                    • +send_reply (5.3.1.3)
                    • + +
                        +
                      • +Allows the Interceptor to modify the reply service context after the target +operation has been invoked and before the reply is returned to the client.
                      • + +
                      • +SYSTEM_EXCEPTION implies no other Interceptors' send_reply operations are +called.  The remaining Interceptors in the Flow Stack shall have their +send_exception interception point called.
                      • +
                      + +
                    • +send_exception (5.3.1.4)
                    • + +
                        +
                      • +Called when an exception occurs.
                      • + +
                      • +Allows Interceptor to modify the reply service context before the exception +is raised to the client.
                      • + +
                      • +SYSTEM_EXCEPTION changes the exception which successsive Interceptors popped +from the Flow Stack receive on their calls to send_exception.
                      • + +
                      • +The exception raised to the client will be the last exception raised by +an Intercepto, or the original exception of no Interceptor changes the +exception.
                      • + +
                      • +ForwardRequest implies no other Interceptors' send_exception operations +are called.  The remaining Interceptors in the Flow Stack shall have +their send_other interception points called.
                      • +
                      + +
                    • +send_other (5.3.1.5)
                    • + +
                        +
                      • +invoked when a request results in something other than a normal reply or +an exception.
                      • + +
                      • +SYSTEM_EXCEPTION implies no other Interceptors' send_other operations are +called.  The remaining Interceptors in the Flow Stack shall have their +send_exception interception points called.
                      • + +
                      • +ForwardRequest implies successive Interceptors' send_other operations are +called with the new information provided by the ForwardRequest exception.
                      • +
                      + +
                    • +The Interceptor list is traversed in order on the receiving interception +points and in reverse order on the sending interception points (5.3.2)
                    • + +
                    • +receive_request is called after receive_request_service_contexts and before +an ending interception point (5.3.2.1)
                    • + +
                    • +On an exception, receive_request may not be called (5.3.2.1)
                    • + +
                    • +If and only if receive_request_service_contexts runs to completion is an +ending interception point called (5.3.2.1)
                    • + +
                    • +On oneway requests, there is no reply sent to the client, however, the +target is called and the server can construct an empty reply.  This +reply is tracked and send_reply or send_exception is called (5.3.2.2)
                    • +
                    + +

                    +Assertions not covered in this test:

                    +ServerRequestInterceptor: +
                      +
                    • +Interceptors are called on all ORB mediated invocations (5.1.1.) - Will +be tested once implemented.
                    • + +
                    • +If, during request processing, a request is canceled because of an ORB +shutdown, receive_exception is called with the system exception BAD_INV_ORDER +with a minor code of 4 (ORB has shutdown) (5.3.2.2) - Will be tested once +implemented.
                    • + +
                    • +If a request is canceled for any other reason (e.g., a GIOP cancel message +has been received), send_exception is called with the system exception +TRANSIENT with a minor code of TBD_T (5.3.2.2.). - Will be tested once +implemented.
                    • + +
                    • +See 5.3.2.2. regarding GIOP CloseConnection messages - May be difficult +to test.
                    • + +
                    • +Asynchronous request, from the server's point of view, are just normal +synchronous requests.  Normal interception point flows are followed. +(5.3.2.2) - Our ORB does not support asynchronous requests.
                    • +
                    + +

                    + +
                    To Test (_REVISIT_):

                    +This section exists to ensure we eventually get to the following tests, +which were not convenient to implement at discovery time: +

                    ClientRequestInfo +

                      +
                    • +The interceptor cannot modify any "in" arguments (5.1.1.).
                    • + +
                    • +The interceptor cannot modify "out" arguments or the return value (5.1.1.).
                    • + +
                    • +If SYSTEM_EXCEPTION is raised in receive_exception, this has the effect +of changing the exception which successive interceptors popped from the +flow stack receive on their calls to receive_exception.  The exception +raised to the client will be the last exception raised by an Interceptor, +or the original exception if no Interceptor changes the exception (5.2.1.4.)
                    • + +
                    • +If ForwardRequest is raised in receive_other, successive Interceeptors' +receive_other operations are called with the new information provided by +the ForwardRequest exception (5.2.1.5.)
                    • +
                    + +
                      + + diff --git a/test/src/share/classes/pi/policyfactory/Client.java b/test/src/share/classes/pi/policyfactory/Client.java new file mode 100644 index 000000000..0895649bb --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/Client.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import com.sun.corba.ee.spi.misc.ORBConstants; +import org.omg.CORBA.ORB; +import org.omg.CORBA.BAD_POLICY; +import org.omg.CORBA.Any; +import java.util.Properties; +import org.glassfish.pfl.test.JUnitReportHelper; + +public class Client implements Runnable +{ + + static final java.lang.Object lock = new java.lang.Object (); + static boolean errorOccured = false; + + static ORB orb; + + private static boolean SUCCESS = true; + + private static boolean FAILURE = false; + + private String msg = null ; + + public void signalError () { + synchronized (Client.lock) { + errorOccured = true; + System.exit(1); + } + } + + public static void main(String args[]) { + new Client().run(); + } + + public void run() + { + JUnitReportHelper helper = new JUnitReportHelper( this.getClass().getName() ) ; + try { + // create and initialize the ORB + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", + "com.sun.corba.ee.impl.orb.ORBImpl" ); + props.put( ORBConstants.PI_ORB_INITIALIZER_CLASS_PREFIX + + "pi.policyfactory.TestORBInitializer", "" ); + orb = ORB.init( (String[]) null, props ); + + boolean testStatus = SUCCESS; + // Test ClientRequestInfo.arguments() method. + helper.start( "positiveTest" ) ; + testStatus = positiveTest(); + if( testStatus == SUCCESS ) { + System.out.println( "PolicyFactory positive tests Success" ); + System.out.flush(); + helper.pass() ; + } else { + System.err.println( "PolicyFactory positive tests Failure" ); + System.err.flush(); + signalError (); + helper.fail( msg ) ; + } + + helper.start( "negativeTest" ) ; + testStatus = negativeTest(); + if( testStatus == SUCCESS ) { + System.out.println( "PolicyFactory negative tests Success" ); + System.out.flush(); + helper.pass() ; + } else { + System.err.println( "PolicyFactory negative tests Failure" ); + System.err.flush(); + signalError (); + helper.fail( msg ) ; + } + } catch( Exception e ) { + System.err.println( "PolicyFactory test Failed with exception" + e); + System.err.flush(); + signalError (); + } finally { + helper.done() ; + } + } + + /** This method tests + * 1. To see whether the Policy created with type 100 is created from + * PolicyFactoryHundred. This check is made by testing + * whether policy.policy_type method returns 100. + * 2. To see whether the Policy created with type 10000 is created from + * PolicyFactoryThousandPlus. This check is made by testing + * whether policy.policy_type method returns 10000. + */ + private boolean positiveTest( ) { + org.omg.CORBA.Policy policy = null; + Any any = orb.create_any() ; + try { + policy = orb.create_policy( 100, any ); + } + catch( Exception e) { + msg = "PolicyFactoryTest.positiveTest failed with " + " an Exception " + e ; + System.err.println( msg ) ; + System.err.flush( ); + e.printStackTrace(); + return FAILURE; + } + if( policy == null ) { + msg = "PolicyFactoryTest.positiveTest failed because"+ + " policy is not created as expected " ; + System.err.println( msg ) ; + System.err.flush( ); + return FAILURE; + } + if( policy.policy_type() != 100 ) { + msg = "PolicyFactoryTest.positiveTest failed because"+ + " policy.policy_type() != 100 " ; + System.err.println( msg ) ; + System.err.flush( ); + return FAILURE; + } + try { + policy = orb.create_policy( 10000, any ); + } catch( Exception e ) { + msg = "PolicyFactoryTest.positiveTest failed with " + + " an Exception " + e ; + System.err.println( msg ) ; + System.err.flush( ); + e.printStackTrace(); + return FAILURE; + } + if( policy == null ) { + msg = "PolicyFactoryTest.positiveTest failed because"+ + " policy is not created as expected " ; + System.err.println( msg ) ; + System.err.flush( ); + return FAILURE; + } + if( policy.policy_type() != 10000 ) { + msg = "PolicyFactoryTest.positiveTest failed because"+ + " policy.policy_type() != 10000 " ; + System.err.println( msg ) ; + System.err.flush( ); + return FAILURE; + } + return SUCCESS; + } + + /** This method tests to see whether the Policy could be created with + * type 100000 for which there is no PolicyFactory registered. + * Before invoking this methos the ORBInitializer (TestORBInitializer) + * registers 3 policy factories with types 100, 1000 and 1000000. If the + * call to create policy with type 100000 does not raise policy error + * then it's an error. + */ + private boolean negativeTest( ) { + try { + Any any = orb.create_any() ; + org.omg.CORBA.Policy policy = orb.create_policy( 100000, any ); + } + catch( org.omg.CORBA.PolicyError e ) { + msg = "Caught org.omg.CORBA.PolicyError in " + + "PolicyFactory.negativeTest() as expected..." ; + System.out.println( msg ) ; + System.out.flush( ); + if( e.reason != BAD_POLICY.value ) { + return FAILURE; + } + return SUCCESS; + } + return FAILURE; + } + +} diff --git a/test/src/share/classes/pi/policyfactory/PolicyFactoryHundred.java b/test/src/share/classes/pi/policyfactory/PolicyFactoryHundred.java new file mode 100644 index 000000000..f613dcc44 --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/PolicyFactoryHundred.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** This is the Policy Factory to create PolicyHundred object. + */ +public class PolicyFactoryHundred extends LocalObject + implements org.omg.PortableInterceptor.PolicyFactory +{ + public Policy create_policy( int type, Any val ) { + System.out.println( "PolicyFactoryHundred.create_policy called..." ); + System.out.flush(); + return new PolicyHundred(); + } +} + diff --git a/test/src/share/classes/pi/policyfactory/PolicyFactoryTest.java b/test/src/share/classes/pi/policyfactory/PolicyFactoryTest.java new file mode 100644 index 000000000..f7454890a --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/PolicyFactoryTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import test.Test; +import corba.framework.*; +import java.util.*; + +/** + * This is a test for module dynamic, which is part of Portable Interceptors/ + */ +public class PolicyFactoryTest extends CORBATest +{ + + // Define the .java files that need to be compiled. Any + // java files generated by compiling IDL will automatically be + // compiled with these. + public static String[] javaFiles = {"Client.java", + "TestORBInitializer.java" }; + + + // This is the main method defining the test. All tests + // should have this. + protected void doTest() throws Throwable + { + Options.setJavaFiles(javaFiles); + + compileJavaFiles(); + + Controller client = createClient("pi.policyfactory.Client"); + + + client.start(); + + // Wait for the client to finish for up to 2 minutes, then + // throw an exception. + client.waitFor(120000); + + // Make sure all the processes are shut down. + client.stop(); + + } +} + diff --git a/test/src/share/classes/pi/policyfactory/PolicyFactoryThousandPlus.java b/test/src/share/classes/pi/policyfactory/PolicyFactoryThousandPlus.java new file mode 100644 index 000000000..a325f1242 --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/PolicyFactoryThousandPlus.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** This the PolicyFactory to create PolicyThousandPlus policy object. + */ +public class PolicyFactoryThousandPlus extends LocalObject + implements org.omg.PortableInterceptor.PolicyFactory +{ + public Policy create_policy( int type, Any val ) { + System.out.println( "PolicyFactoryOne.create_policy called..." ); + System.out.flush(); + if( type == 1000 ) { + return new PolicyThousand(); + } else if( type == 10000 ) { + return new PolicyTenThousand(); + } + return null; + } +} + diff --git a/test/src/share/classes/pi/policyfactory/PolicyHundred.java b/test/src/share/classes/pi/policyfactory/PolicyHundred.java new file mode 100644 index 000000000..3c77ec4e6 --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/PolicyHundred.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** This Policy object's type is 100. + */ +public class PolicyHundred extends LocalObject + implements Policy +{ + public int policy_type( ) { + return 100; + } + + + public org.omg.CORBA.Policy copy( ) { + return this; + } + + public void destroy ( ) { + // Do Nothing + } +} + diff --git a/test/src/share/classes/pi/policyfactory/PolicyTenThousand.java b/test/src/share/classes/pi/policyfactory/PolicyTenThousand.java new file mode 100644 index 000000000..c4d4c2ca1 --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/PolicyTenThousand.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** This Policy object's type is 10000. + */ +public class PolicyTenThousand extends LocalObject + implements Policy +{ + public int policy_type( ) { + return 10000; + } + + + public org.omg.CORBA.Policy copy( ) { + return this; + } + + public void destroy ( ) { + // Do Nothing + } +} + diff --git a/test/src/share/classes/pi/policyfactory/PolicyThousand.java b/test/src/share/classes/pi/policyfactory/PolicyThousand.java new file mode 100644 index 000000000..6e46f3317 --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/PolicyThousand.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +/** This Policy object's type is 1000. + */ +public class PolicyThousand extends LocalObject + implements Policy +{ + public int policy_type( ) { + return 1000; + } + + public org.omg.CORBA.Policy copy( ) { + return this; + } + + public void destroy ( ) { + // Do Nothing + } +} + diff --git a/test/src/share/classes/pi/policyfactory/TestORBInitializer.java b/test/src/share/classes/pi/policyfactory/TestORBInitializer.java new file mode 100644 index 000000000..fef32adca --- /dev/null +++ b/test/src/share/classes/pi/policyfactory/TestORBInitializer.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package pi.policyfactory; + +import org.omg.PortableInterceptor.*; +import org.omg.PortableInterceptor.PolicyFactory; +import org.omg.PortableInterceptor.ORBInitInfoPackage.*; + +import java.util.*; +import java.io.*; +import org.omg.CORBA.*; + +public class TestORBInitializer extends LocalObject + implements ORBInitializer +{ + public void pre_init (org.omg.PortableInterceptor.ORBInitInfo info) { + System.out.println( "TestORBInitializer.pre_init() called..." ); + System.out.flush( ); + } + + /** pre_init registers 2 PolicyFactories with types 100, 1000 and 10000 + * These types will be used in Positive tests to see the validity of + * ORB.create_policy() API. + */ + public void post_init (org.omg.PortableInterceptor.ORBInitInfo info) { + PolicyFactory policyFactory1000Plus = new PolicyFactoryThousandPlus( ); + PolicyFactory policyFactory100 = new PolicyFactoryHundred( ); + // Same PolicyFactory for types 1000 and 10000. create_policy() method + // takes care of instantiating the right policy based on policy type. + info.register_policy_factory( 1000, policyFactory1000Plus ); + info.register_policy_factory( 10000, policyFactory1000Plus ); + info.register_policy_factory( 100, policyFactory100 ); + System.out.println( "TestORBInitializer.post_init() called..." ); + System.out.flush( ); + } +} + diff --git a/test/src/share/classes/rmic/IDLReferenceTest.classlist b/test/src/share/classes/rmic/IDLReferenceTest.classlist new file mode 100644 index 000000000..c0e7f1f34 --- /dev/null +++ b/test/src/share/classes/rmic/IDLReferenceTest.classlist @@ -0,0 +1,29 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# List of classes for which IDLReferenceTest will generate idl and +# compare it (ignoring whitespace) to a reference file. +# +# For each class listed, the reference file must exist and end +# with the ".idlref" extension. + +omega.Bert +alpha.bravo.DuckBill +alpha.bravo.Platypus +alpha.bravo.Wombat +alpha.bravo.Hedgehog +alpha.bravo.Kangaroo +alpha.bravo.Charlie +# omega.FruitbatException +# omega.Thrower +alpha.bravo.Mammal +alpha.bravo.PolarBear +# alpha.bravo.AB +# fred.Test diff --git a/test/src/share/classes/rmic/StubReferenceTest.classlist b/test/src/share/classes/rmic/StubReferenceTest.classlist new file mode 100644 index 000000000..3810a21d0 --- /dev/null +++ b/test/src/share/classes/rmic/StubReferenceTest.classlist @@ -0,0 +1,37 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# List of classes for which StubReferenceTest will generate stubs/ties +# and compare them (ignoring whitespace) to a reference file. +# +# Entries are in the following form: +# +# = [,]...[,] +# +# For each output class listed, a reference file +# must exist which ends with the ".javaref" extension. +# +# To assert that an inputclass should FAIL to compile, use +# the following format: +# +# = ERROR [,]...[] +# +# where is a string that must be found in the +# error output. + +rmic.NoMethodsImpl = rmic._NoMethods_Stub, rmic._NoMethodsImpl_Tie +rmic.DerivedImpl = rmic._DerivedImpl_Tie, rmic._BaseImpl_Tie, rmic._Base_Stub + +rmic.Diamond = ERROR, interface rmic.Diamond is not a valid remote interface: inherited interfaces rmic.Base and rmic.Right both declare method void method +rmic.DiamondServer = ERROR, interface rmic.Diamond is not a valid remote interface: inherited interfaces rmic.Base and rmic.Right both declare method void method + +rmic.SimpleServant = rmic._SimpleServant_Tie + +rmic.ThrowCORBAUserExServant = rmic._ThrowCORBAUserException_Stub, rmic._ThrowCORBAUserExServant_Tie diff --git a/test/src/share/classes/rmic/_BaseImpl_Tie.javaref b/test/src/share/classes/rmic/_BaseImpl_Tie.javaref new file mode 100644 index 000000000..d97c6edbb --- /dev/null +++ b/test/src/share/classes/rmic/_BaseImpl_Tie.javaref @@ -0,0 +1,83 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + +public class _BaseImpl_Tie extends ObjectImpl implements Tie { + + private BaseImpl target = null; + + private static final String[] _type_ids = { + "RMI:rmic.Base:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (BaseImpl) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + if (method.equals("method")) { + try { + target.method(); + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/test/src/share/classes/rmic/_Base_Stub.javaref b/test/src/share/classes/rmic/_Base_Stub.javaref new file mode 100644 index 000000000..4abd3b45e --- /dev/null +++ b/test/src/share/classes/rmic/_Base_Stub.javaref @@ -0,0 +1,72 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + +public class _Base_Stub extends Stub implements Base { + + private static final String[] _type_ids = { + "RMI:rmic.Base:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public void method() throws java.rmi.RemoteException, rmic.TestException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("method", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + method(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("method",Base.class); + if (so == null) { + method(); + return ; + } + try { + ((Base)so.servant).method(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } +} diff --git a/test/src/share/classes/rmic/_DerivedImpl_Tie.javaref b/test/src/share/classes/rmic/_DerivedImpl_Tie.javaref new file mode 100644 index 000000000..6c38ca38a --- /dev/null +++ b/test/src/share/classes/rmic/_DerivedImpl_Tie.javaref @@ -0,0 +1,83 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + +public class _DerivedImpl_Tie extends ObjectImpl implements Tie { + + private DerivedImpl target = null; + + private static final String[] _type_ids = { + "RMI:rmic.Base:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (DerivedImpl) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + if (method.equals("method")) { + try { + target.method(); + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/test/src/share/classes/rmic/_NoMethodsImpl_Tie.javaref b/test/src/share/classes/rmic/_NoMethodsImpl_Tie.javaref new file mode 100644 index 000000000..838bfc6a2 --- /dev/null +++ b/test/src/share/classes/rmic/_NoMethodsImpl_Tie.javaref @@ -0,0 +1,61 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + +public class _NoMethodsImpl_Tie extends ObjectImpl implements Tie { + + private NoMethodsImpl target = null; + + private static final String[] _type_ids = { + "RMI:rmic.NoMethods:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (NoMethodsImpl) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + throw new BAD_OPERATION(); + } +} diff --git a/test/src/share/classes/rmic/_NoMethods_Stub.javaref b/test/src/share/classes/rmic/_NoMethods_Stub.javaref new file mode 100644 index 000000000..b9f2da707 --- /dev/null +++ b/test/src/share/classes/rmic/_NoMethods_Stub.javaref @@ -0,0 +1,30 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + +public class _NoMethods_Stub extends Stub implements NoMethods { + + private static final String[] _type_ids = { + "RMI:rmic.NoMethods:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } +} diff --git a/test/src/share/classes/rmic/_SimpleServant_Tie.javaref b/test/src/share/classes/rmic/_SimpleServant_Tie.javaref new file mode 100644 index 000000000..4ae49b99d --- /dev/null +++ b/test/src/share/classes/rmic/_SimpleServant_Tie.javaref @@ -0,0 +1,83 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + +public class _SimpleServant_Tie extends ObjectImpl implements Tie { + + private SimpleServant target = null; + + private static final String[] _type_ids = { + "RMI:rmic.Simple:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (SimpleServant) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.charAt(6)) { + case 49: + if (method.equals("method1")) { + target.method1(); + OutputStream out = reply.createReply(); + return out; + } + case 50: + if (method.equals("method2")) { + target.method2(); + OutputStream out = reply.createReply(); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/test/src/share/classes/rmic/_ThrowCORBAUserExServant_Tie.javaref b/test/src/share/classes/rmic/_ThrowCORBAUserExServant_Tie.javaref new file mode 100644 index 000000000..55bce3e69 --- /dev/null +++ b/test/src/share/classes/rmic/_ThrowCORBAUserExServant_Tie.javaref @@ -0,0 +1,266 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.UserException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + +public class _ThrowCORBAUserExServant_Tie extends ObjectImpl implements Tie { + + private ThrowCORBAUserExServant target = null; + + private static final String[] _type_ids = { + "RMI:rmic.ThrowCORBAUserException:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (ThrowCORBAUserExServant) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.charAt(0)) { + case 97: + if (method.equals("a")) { + target.a(); + OutputStream out = reply.createReply(); + return out; + } + case 98: + if (method.equals("b")) { + try { + target.b(); + } catch (CORBAUserException ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserExceptionHelper.write(out,ex); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 99: + if (method.equals("c")) { + try { + target.c(); + } catch (CORBAUserException ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserExceptionHelper.write(out,ex); + return out; + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 100: + if (method.equals("d")) { + try { + target.d(); + } catch (UserException ex) { + String id = "IDL:org/omg/CORBA/UserEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,UserException.class); + return out; + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 101: + if (method.equals("e")) { + try { + target.e(); + } catch (UserException ex) { + String id = "IDL:org/omg/CORBA/UserEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,UserException.class); + return out; + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 102: + if (method.equals("f")) { + try { + target.f(); + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } catch (UserException ex) { + String id = "IDL:org/omg/CORBA/UserEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,UserException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 103: + if (method.equals("g")) { + try { + target.g(); + } catch (UserException ex) { + String id = "IDL:org/omg/CORBA/UserEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,UserException.class); + return out; + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 104: + if (method.equals("h")) { + try { + target.h(); + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } catch (CORBAUserException ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserExceptionHelper.write(out,ex); + return out; + } catch (CORBAUserException2 ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserException2Helper.write(out,ex); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 105: + if (method.equals("i")) { + try { + target.i(); + } catch (CORBAUserException ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserExceptionHelper.write(out,ex); + return out; + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } catch (CORBAUserException2 ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserException2Helper.write(out,ex); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + case 106: + if (method.equals("j")) { + try { + target.j(); + } catch (CORBAUserException ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserExceptionHelper.write(out,ex); + return out; + } catch (CORBAUserException2 ex) { + org.omg.CORBA.portable.OutputStream out = reply.createExceptionReply(); + rmic.CORBAUserException2Helper.write(out,ex); + return out; + } catch (TestException ex) { + String id = "IDL:rmic/TestEx:1.0"; + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createExceptionReply(); + out.write_string(id); + out.write_value(ex,TestException.class); + return out; + } + OutputStream out = reply.createReply(); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/test/src/share/classes/rmic/_ThrowCORBAUserException_Stub.javaref b/test/src/share/classes/rmic/_ThrowCORBAUserException_Stub.javaref new file mode 100644 index 000000000..ca2b7e764 --- /dev/null +++ b/test/src/share/classes/rmic/_ThrowCORBAUserException_Stub.javaref @@ -0,0 +1,563 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +package rmic; + +import java.io.Serializable; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.UserException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _ThrowCORBAUserException_Stub extends Stub implements ThrowCORBAUserException { + + private static final String[] _type_ids = { + "RMI:rmic.ThrowCORBAUserException:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public void a() throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA.portable.InputStream in = null; + try { + OutputStream out = _request("a", true); + _invoke(out); + } catch (ApplicationException ex) { + in = ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + a(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("a",ThrowCORBAUserException.class); + if (so == null) { + a(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).a(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void b() throws java.rmi.RemoteException, rmic.CORBAUserException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("b", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + b(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("b",ThrowCORBAUserException.class); + if (so == null) { + b(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).b(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void c() throws java.rmi.RemoteException, rmic.CORBAUserException, rmic.TestException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("c", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + c(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("c",ThrowCORBAUserException.class); + if (so == null) { + c(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).c(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void d() throws java.rmi.RemoteException, rmic.CORBAUserException, org.omg.CORBA.UserException, rmic.TestException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("d", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:org/omg/CORBA/UserEx:1.0")) { + throw (org.omg.CORBA.UserException) in.read_value(org.omg.CORBA.UserException.class); + } + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + d(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("d",ThrowCORBAUserException.class); + if (so == null) { + d(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).d(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof org.omg.CORBA.UserException) { + throw (org.omg.CORBA.UserException)exCopy; + } + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void e() throws java.rmi.RemoteException, rmic.CORBAUserException, rmic.CORBAUserException2, org.omg.CORBA.UserException, rmic.TestException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("e", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + if ($_id.equals(rmic.CORBAUserException2Helper.id())) { + throw rmic.CORBAUserException2Helper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:org/omg/CORBA/UserEx:1.0")) { + throw (org.omg.CORBA.UserException) in.read_value(org.omg.CORBA.UserException.class); + } + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + e(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("e",ThrowCORBAUserException.class); + if (so == null) { + e(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).e(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException2) { + throw (rmic.CORBAUserException2)exCopy; + } + if (exCopy instanceof org.omg.CORBA.UserException) { + throw (org.omg.CORBA.UserException)exCopy; + } + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void f() throws java.rmi.RemoteException, rmic.TestException, rmic.CORBAUserException, rmic.CORBAUserException2, org.omg.CORBA.UserException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("f", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + if ($_id.equals(rmic.CORBAUserException2Helper.id())) { + throw rmic.CORBAUserException2Helper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + if ($_id.equals("IDL:org/omg/CORBA/UserEx:1.0")) { + throw (org.omg.CORBA.UserException) in.read_value(org.omg.CORBA.UserException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + f(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("f",ThrowCORBAUserException.class); + if (so == null) { + f(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).f(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException2) { + throw (rmic.CORBAUserException2)exCopy; + } + if (exCopy instanceof org.omg.CORBA.UserException) { + throw (org.omg.CORBA.UserException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void g() throws java.rmi.RemoteException, org.omg.CORBA.UserException, rmic.CORBAUserException, rmic.TestException, rmic.CORBAUserException2 { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("g", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + if ($_id.equals(rmic.CORBAUserException2Helper.id())) { + throw rmic.CORBAUserException2Helper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:org/omg/CORBA/UserEx:1.0")) { + throw (org.omg.CORBA.UserException) in.read_value(org.omg.CORBA.UserException.class); + } + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + g(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("g",ThrowCORBAUserException.class); + if (so == null) { + g(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).g(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof org.omg.CORBA.UserException) { + throw (org.omg.CORBA.UserException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException2) { + throw (rmic.CORBAUserException2)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void h() throws java.rmi.RemoteException, rmic.TestException, rmic.CORBAUserException, rmic.CORBAUserException2 { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("h", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + if ($_id.equals(rmic.CORBAUserException2Helper.id())) { + throw rmic.CORBAUserException2Helper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + h(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("h",ThrowCORBAUserException.class); + if (so == null) { + h(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).h(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException2) { + throw (rmic.CORBAUserException2)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void i() throws java.rmi.RemoteException, rmic.CORBAUserException, rmic.TestException, rmic.CORBAUserException2 { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("i", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + if ($_id.equals(rmic.CORBAUserException2Helper.id())) { + throw rmic.CORBAUserException2Helper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + i(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("i",ThrowCORBAUserException.class); + if (so == null) { + i(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).i(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException2) { + throw (rmic.CORBAUserException2)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public void j() throws java.rmi.RemoteException, rmic.CORBAUserException, rmic.CORBAUserException2, rmic.TestException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + OutputStream out = _request("j", true); + _invoke(out); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = ex.getId(); + if ($_id.equals(rmic.CORBAUserExceptionHelper.id())) { + throw rmic.CORBAUserExceptionHelper.read(in); + } + if ($_id.equals(rmic.CORBAUserException2Helper.id())) { + throw rmic.CORBAUserException2Helper.read(in); + } + $_id = in.read_string(); + if ($_id.equals("IDL:rmic/TestEx:1.0")) { + throw (rmic.TestException) in.read_value(rmic.TestException.class); + } + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + j(); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("j",ThrowCORBAUserException.class); + if (so == null) { + j(); + return ; + } + try { + ((ThrowCORBAUserException)so.servant).j(); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + if (exCopy instanceof rmic.CORBAUserException) { + throw (rmic.CORBAUserException)exCopy; + } + if (exCopy instanceof rmic.CORBAUserException2) { + throw (rmic.CORBAUserException2)exCopy; + } + if (exCopy instanceof rmic.TestException) { + throw (rmic.TestException)exCopy; + } + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } +} diff --git a/test/src/share/classes/test.policy b/test/src/share/classes/test.policy new file mode 100644 index 000000000..d2d20ac8e --- /dev/null +++ b/test/src/share/classes/test.policy @@ -0,0 +1,34 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +grant { + permission java.io.SerializablePermission "enableSubstitution"; + permission java.io.SerializablePermission "enableSubclassImplementation"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.corba" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.misc" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.registry"; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.RuntimePermission "reflectionFactoryAccess"; + permission java.lang.RuntimePermission "getClassLoader"; + permission java.lang.RuntimePermission "setContextClassLoader"; + permission java.lang.RuntimePermission "getProtectionDomain" ; + permission java.lang.RuntimePermission "shutdownHooks" ; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.net.SocketPermission "*:*", "listen, connect, accept, resolve"; + permission java.util.logging.LoggingPermission "control"; + permission java.util.PropertyPermission "*", "read, write" ; + permission org.glassfish.pfl.basic.reflection.BridgePermission "getBridge"; + permission com.sun.corba.ee.spi.orbutil.proxy.DynamicAccessPermission "access"; + permission java.lang.management.ManagementPermission "monitor"; + permission javax.management.MBeanServerPermission "createMBeanServer"; + permission javax.management.MBeanPermission "*", "*" ; + permission javax.management.MBeanTrustPermission "*" ; +}; + diff --git a/test/src/share/classes/test.policy.secure b/test/src/share/classes/test.policy.secure new file mode 100644 index 000000000..562073808 --- /dev/null +++ b/test/src/share/classes/test.policy.secure @@ -0,0 +1,81 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +grant CodeBase "file:${com.sun.corba.ee.ORBBase}/build/-" { + permission java.io.SerializablePermission "enableSubstitution"; + permission java.io.SerializablePermission "enableSubclassImplementation"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.corba" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.misc" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.registry"; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.RuntimePermission "reflectionFactoryAccess"; + permission java.lang.RuntimePermission "getClassLoader"; + permission java.lang.RuntimePermission "setContextClassLoader"; + permission java.lang.RuntimePermission "getProtectionDomain"; + permission java.lang.RuntimePermission "shutdownHooks" ; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.net.SocketPermission "*:*", "listen, connect, accept, resolve"; + permission java.util.logging.LoggingPermission "control"; + permission java.util.PropertyPermission "*", "read, write" ; + permission org.glassfish.pfl.basic.reflection.BridgePermission "getBridge"; + permission com.sun.corba.ee.spi.orbutil.proxy.DynamicAccessPermission "access"; + permission java.lang.management.ManagementPermission "monitor"; + permission javax.management.MBeanServerPermission "createMBeanServer"; + permission javax.management.MBeanPermission "*", "*" ; + permission javax.management.MBeanTrustPermission "*" ; +}; + +// The permissions here must be identical to the permissions specified above, +// as the base ORB and the optional classes will have different CodeSources. +// The policy file syntax does not permit multiple codeBases on a grant entry. + +grant CodeBase "file:${com.sun.corba.ee.ORBBase}/orblib/build/-" { + permission java.io.SerializablePermission "enableSubstitution"; + permission java.io.SerializablePermission "enableSubclassImplementation"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.corba" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.misc" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect" ; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.RuntimePermission "reflectionFactoryAccess"; + permission java.lang.RuntimePermission "getClassLoader"; + permission java.lang.RuntimePermission "setContextClassLoader"; + permission java.lang.RuntimePermission "getProtectionDomain"; + permission java.lang.RuntimePermission "shutdownHooks" ; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.net.SocketPermission "*:*", "listen, connect, accept, resolve"; + permission java.util.logging.LoggingPermission "control"; + permission java.util.PropertyPermission "*", "read, write" ; + permission org.glassfish.pfl.basic.reflection.BridgePermission "getBridge"; + permission com.sun.corba.ee.spi.orbutil.proxy.DynamicAccessPermission "access"; + permission java.lang.management.ManagementPermission "monitor"; +}; + +// These permissions are granted to all tests +grant { + // Unfortunately needed because of calls to System.getProperties() + permission java.util.PropertyPermission "*", "read, write" ; + // Needed to exec the java VM + permission java.io.FilePermission "${java.home}/../-", "read,execute" ; + // Tests need full access to the build (two up from test/make) + permission java.io.FilePermission "../../-", "read,write,execute" ; + + // The following are needed for the corba.security test + permission java.security.SecurityPermission "getPolicy" ; + permission java.lang.RuntimePermission "getProtectionDomain" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.rmic"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.rmi.rmic.iiop"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.io" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.tools.asm" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.tools.tree" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.tools.util" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.tools.java" ; + permission java.lang.RuntimePermission "accessClassInPackage.sun.tools.javac"; + permission java.lang.RuntimePermission "shutdownHooks" ; +} ; diff --git a/test/src/share/classes/test/AllTests.tdesc b/test/src/share/classes/test/AllTests.tdesc new file mode 100644 index 000000000..9de3475f9 --- /dev/null +++ b/test/src/share/classes/test/AllTests.tdesc @@ -0,0 +1,37 @@ +// +// Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +// +// This program and the accompanying materials are made available under the +// terms of the Eclipse Distribution License v. 1.0, which is available at +// http://www.eclipse.org/org/documents/edl-v10.php. +// +// SPDX-License-Identifier: BSD-3-Clause + +// Batch tests +// Run 'java test.Test' for syntax. + +-test javax.rmi.CORBA.serialization.SerializationTest +-test test12.SerializationTest -vm 1.2 + +// This has to be run in a separate process because it +// clobbers environment variables like java.rmi.server.codebase +-test javax.rmi.ClassLoadTest -separateprocess +// this no longer tests anything, but manages to fail anyway!! (REG) -test rmic.ParseTest + +// Test FullValueDescription +// DO NOT MOVE THIS TEST TO RUN AFTER rmic.HelloTest, It hangs at times on +// Windows. +-test javax.rmi.fvd.TheTest -separateprocess + +-test rmic.HelloTest +-test rmic.HelloTest -localservants -normic +-test rmic.InnerTest +-test rmic.StaticStringsHashTest +-test rmic.StubReferenceTest +-test javax.rmi.download.TheTest +-test javax.rmi.test1.TheTest +-test rmic.LocalStubTest +-test javax.rmi.PROTest +-test javax.rmi.PROTest -jrmp -separateprocess +-test ibmspace.spacetest.SpaceTest -separateprocess +-test ibmspace.spacetest.SpaceTest -jrmp -separateprocess diff --git a/test/src/share/classes/test12/ARectangle.java b/test/src/share/classes/test12/ARectangle.java new file mode 100644 index 000000000..7088183f1 --- /dev/null +++ b/test/src/share/classes/test12/ARectangle.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test12; + +import java.io.*; +import java.awt.*; + +/** + * NOTE : This code was taken from Sun's persistent fields example @ + * http://java.sun.com/products/jdk/1.2/docs/guide/serialization/examples/altimpl/EvolvedClass.java + */ + +/** + * The evolved Rectangle Class. Interally consists of two fields of type + * Point but externally is still 4 integers (so that it is compatible + * with the original rectangle class) + * + * In order to make this possible, we need to use the Serializable + * Field API so that we can define serializable fields that are + * not part of the implementation class. + */ +class ARectangle implements java.io.Serializable { + + // new rectangle representation + + /** + * First of two points forming diagonal of rectangle. + * + * Note that this field is not a default serializable field + * due to the use of serialPersistentFields member within this class. + */ + Point point1; + + + /** + * Second of two points forming diagonal of rectangle. + * + * Note that this field is not a default serializable field + * due to the use of serialPersistentFields member within this class. + */ + Point point2; + + /* + * mandatory SUID field for an evolved Serializable class. + * serialVersionUID is gotten by doing the serialver command + * on the original class: + * serialver ARectangle (the original rectangle) + */ + static final long serialVersionUID = 9030593813711490592L; + + + /** + * The special member, serialPeristentFields, explicitly declares + * Serializable fields for this class. This allows for fields other + * than the fields in the class to be persistent. Since we want to + * save the state of the two Points point1 and point2, we declare + * the 4 ints as the serial persistent fields + * + * @serialField x1 Integer + * X-coordinate of point 1 of diagonal points of rectangle. + * @serialField y1 Integer + * Y-coordinate of point 1 of diagonal points of rectangle. + * @serialField x2 Integer + * X-coordinate of point 2 of diagonal points of rectangle. + * @serialField y2 Integer + * Y-coordinate of point 2 of diagonal points of rectangle. + */ + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("x1", Integer.TYPE), + new ObjectStreamField("y1", Integer.TYPE), + new ObjectStreamField("x2", Integer.TYPE), + new ObjectStreamField("y2", Integer.TYPE) + }; + + ARectangle(int x1, int y1, int x2, int y2) { + point1 = new Point(x1, y1); + point2 = new Point(x2, y2); + } + + /** + * writeObject - Writes out the serializable fields + * (the 4 integers, x1, y1, x2, y2) using the + * Serializable Field API. (the methods putFields and + * writeFields of the ObjectOutputStream Class and the method put + * of the ObjectOutputStream.PutField inner class) + * + * @serialData Only the serializable fields of the class are written. + * No optional data written. + */ + private void writeObject(ObjectOutputStream s) + throws IOException { + + // set the values of the Serializable fields + ObjectOutputStream.PutField fields = s.putFields(); + fields.put("x1", point1.x); + fields.put("y1", point1.y); + fields.put("x2", point2.x); + fields.put("y2", point2.y); + + // save them + s.writeFields(); + } + + /** + * readsObject - Reads in the serializable fields + * (the 4 integers, x1, y1, x2, y2) using the + * Serializable Field API. (the methods getFields and + * readFields of the ObjectInputStream Class and the method get + * of the ObjectOutputStream.GetField inner class) + * + * @serialData No optional data is read. + */ + private void readObject(ObjectInputStream s) + throws IOException { + + // prepare to read the alternate persistent fields + ObjectInputStream.GetField fields = null; + try { + fields = s.readFields(); + + } catch (Exception ClassNotFoundException) { + throw new IOException(); + } + + // read the alternate persistent fields + int x1 = (int)fields.get("x1", 0); + int y1 = (int)fields.get("y1", 0); + int x2 = (int)fields.get("x2", 0); + int y2 = (int)fields.get("y2", 0); + + // save them back as Points. + point1 = new Point(x1, y1); + point2 = new Point(x2, y2); + } + + public boolean equals(Object o){ + if (!(o instanceof ARectangle)) + return false; + + ARectangle other = (ARectangle)o; + + return ((point1.x == other.point1.x) && + (point1.y == other.point1.y) && + (point2.x == other.point2.x) && + (point2.y == other.point2.y)); + } + + public String toString() { + return("point1.x: " + point1.x + "\npoint1.y: " + point1.y + "\npoint2.x: " + point2.x + "\npoint2.y: " + point2.y); + } +} diff --git a/test/src/share/classes/test12/SerialPersistent.java b/test/src/share/classes/test12/SerialPersistent.java new file mode 100644 index 000000000..6030b71aa --- /dev/null +++ b/test/src/share/classes/test12/SerialPersistent.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test12; +import java.io.ObjectStreamField; + +public class SerialPersistent implements java.io.Serializable { + + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("member1",Object.class), + new ObjectStreamField("member2",java.util.Hashtable.class), + new ObjectStreamField("member3",byte.class), + new ObjectStreamField("member4",char.class), + new ObjectStreamField("member5",short.class), + new ObjectStreamField("member6",int.class), + new ObjectStreamField("member7",long[][][].class), + // new ObjectStreamField("member8",float.class), + new ObjectStreamField("member9",double.class), + new ObjectStreamField("member10",boolean[].class), + }; + + java.lang.Object member1; + java.util.Hashtable member2; + byte member3; + char member4; + short member5; + int member6; + long[][][] member7; + float member8; + double member9; + boolean[] member10; +} diff --git a/test/src/share/classes/test12/SerializationTest.java b/test/src/share/classes/test12/SerializationTest.java new file mode 100644 index 000000000..5b6be7355 --- /dev/null +++ b/test/src/share/classes/test12/SerializationTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package test12; + +import java.util.Properties ; +import org.glassfish.pfl.test.JUnitReportHelper; + +public class SerializationTest extends test.Test { + public void run() { + JUnitReportHelper helper = new JUnitReportHelper( SerializationTest.class.getName() ) ; + + try { + helper.start( "test1" ) ; + Properties props = new Properties() ; + props.put( "org.omg.CORBA.ORBClass", "com.sun.corba.ee.impl.orb.ORBImpl" ) ; + org.omg.CORBA.ORB orb = + org.omg.CORBA.ORB.init(getArgsAsArgs(),props); + org.omg.CORBA_2_3.portable.OutputStream sos = + (org.omg.CORBA_2_3.portable.OutputStream)orb.create_output_stream(); + + + ARectangle rect = new ARectangle(1,3,5,7); + sos.write_value(rect); + + /***************************************************************/ + /*********************** READ DATA BACK IN *********************/ + /***************************************************************/ + + org.omg.CORBA_2_3.portable.InputStream sis = + (org.omg.CORBA_2_3.portable.InputStream)sos.create_input_stream(); + + ARectangle _rect = (ARectangle)sis.read_value(); + if (!rect.equals(_rect)) + throw new Error("ARectangle test failed!"); + + helper.pass() ; + } catch(Throwable e) { + helper.fail( e ) ; + status = new Error(e.getMessage()); + e.printStackTrace(); + } finally { + helper.done() ; + } + } +} diff --git a/test/src/share/classes/test_cases.txt b/test/src/share/classes/test_cases.txt new file mode 100644 index 000000000..dfd778a12 --- /dev/null +++ b/test/src/share/classes/test_cases.txt @@ -0,0 +1,156 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Note: this is very out of date: update after junit conversion! + +corba test suite: test case structure total test case framework notes +--------------------------------------------------------------------------------------------------------------- +./corba/cdrext 30 test cases 30 +./corba/cdrstreams 7 TC 7 +./corba/cmvt 3 TC 3 +./corba/monitoring 6 TC 6 +./corba/codebase 6 TC 6 +./corba/codeset 12 TC, 2 variations 24 +./corba/connectintercept_1_4 3 TC 3 +./corba/custom 3 TC 16 variations 48 +./corba/evolve 2 TC 2 +./corba/example 1 TC 1 +./corba/fragment 1 TC, 30 variations 30 +./corba/fragment2 1 TC, 4 variations 4 +./corba/genericRPCMSGFramework 6 TC 6 +./corba/hcks 60 TC, 4 variations 240 +./corba/ior 159 TC 159 +./corba/iorintsockfact 1 TC 1 +./corba/msgtypes 9 TC, 30 variations on 1 38 +./corba/multiorb 1 TC 1 +./corba/oneway 1 TC 1 +./corba/poaandequals 1 TC 1 +./corba/poamanager 10 TC 10 +./corba/poapolicies 4 TC 4 +./corba/poatest 1 TC 1 +./corba/purgecalls 1 TC 1 +./corba/rmipoacounter 1 TC 1 +./corba/serialization/bad 5 TC 5 +./corba/serialization/good 5 TC 5 +./corba/serialization/zerolengthstring 1 TC 1 +./corba/strm2 5 TC 5 +./corba/transportonly 1 TC 1 +./corba/pept 1 TC 1 +./corba/ortremote 2 TC 2 +./corba/islocal 1 TC, 2 variations 2 +./corba/orbconfig 31 TC 31 +./corba/orbconfigappserv 1 TC 1 +./corba/poacallback 1 TC 1 +./corba/preinvokepostinvoke 1 TC 1 +./corba/copyobject 127 TC, 5 variations 635 junit +./corba/copyobjectpolicy 2 TC 2 +./corba/exceptiondetailsc 1 TC 1 +./corba/adapteractivator 1 TC 1 statusU +-------------------------------------------------------------------------------- + 1323 +-------------------------------------------------------------------------------- + +IBM test suite: +-------------------------------------------------------------------------------- +./anytest 16 test cases 16 +./create 1 TC 1 +./dictionary 1 TC 1 +./ibmspace/spacetest/SpaceTest 1 TC, JRMP and IIOP 2 +./javax/rmi/PROTest 48 TC, JRMP and IIOP 96 +./javax/rmi/fvd/TheTest 1 TC 1 +./javax/rmi/download/TheTest 1 TC 1 +./javax/rmi/ClassLoadTest 21 TC 21 +./javax/rmi/CORBA/serialization/SerializationTest 56 TC 56 +./javax/rmi/test1/TheTest 4 TC 4 +./rmic/HelloTest 45 TC, localservants +/- 90 +./rmic/InnerTest 25 TC 25 +./rmic/StaticStringsHashTest 8 TC 8 +./rmic/StubReferenceTest 8 TC 8 +./rmic/LocalStubTest 35 TC 35 +./rmic/ParseTest 32 TC 32 +./test12/SerializationTest 1 TC 1 +-------------------------------------------------------------------------------- + 398 +-------------------------------------------------------------------------------- + + +Hopper test suite: +-------------------------------------------------------------------------------- +./hopper/h4486041 1 TC 1 +./hopper/h4515953 1 TC 1 +./hopper/h4549085 1 TC 1 +./hopper/h4620926 1 TC 1 +./hopper/h4645953 1 TC 1 +./hopper/h4647746 1 TC 1 +./hopper/h4655388 1 TC 1 +./hopper/h4661596 1 TC 1 +./hopper/h4670827 1 TC 1 +-------------------------------------------------------------------------------- + 9 +-------------------------------------------------------------------------------- + + +Mantis test suite: +-------------------------------------------------------------------------------- +./mantis/m4764130 1 TC 1 +-------------------------------------------------------------------------------- + 1 +-------------------------------------------------------------------------------- + + +Naming test suite: +-------------------------------------------------------------------------------- +./naming/instest 2 TC 2 +./naming/cosnaming 5 TC 5 +./naming/pcosnaming 3 TC 3 +./naming/rinameservice 3 TC 3 +-------------------------------------------------------------------------------- + 13 +-------------------------------------------------------------------------------- + +Performance test suite: +-------------------------------------------------------------------------------- +./performance/simpleperf 5 TC 5 +./performance/simpleperf2 2 TC 2 +-------------------------------------------------------------------------------- + 7 +-------------------------------------------------------------------------------- + +PI test suite: +-------------------------------------------------------------------------------- +./pi/codec 15 TC 15 +./pi/orbinit 1 TC 1 +./pi/ort 4 TC 4 +./pi/clientinterceptor 11 TC, 8 variations 88 +./pi/clientrequestinfo 8 TC, 8 variations 64 +./pi/iorinterceptor 1 TC (incomplete) 1 +./pi/picurrent 7 TC 7 +./pi/policyfactory 3 TC 3 +./pi/serverinterceptor 11 TC, 8 variations 88 +./pi/serverrequestinfo 7 TC, 8 variations 56 +./pi/serviceexample 2 TC 2 +-------------------------------------------------------------------------------- + 329 +-------------------------------------------------------------------------------- + + + +Totals: Test Suites Test Cases +-------------------------------------------------------------------------------- +CORBA 41 1323 +IBM 17 398 +Hopper 9 9 +Mantis 1 1 +Naming 4 13 +Performance 2 7 +PI 11 329 +-------------------------------------------------------------------------------- + 85 2077 + diff --git a/test/src/share/classes/values1/javax/rmi/download/values/ClassA.java b/test/src/share/classes/values1/javax/rmi/download/values/ClassA.java new file mode 100644 index 000000000..ee5dbf0aa --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/ClassA.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassA extends javax.rmi.fvd.ParentClass { + + private static final long serialVersionUID = 123456789L; + + private int a; + + public ClassA(){ + a = 3; + } + + public long getTotal(){ + return super.getTotal() + a; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 3; + } +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/ClassB.java b/test/src/share/classes/values1/javax/rmi/download/values/ClassB.java new file mode 100644 index 000000000..ee163782b --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/ClassB.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassB extends ClassA{ + + private static final long serialVersionUID = 123556789L; + + private int a2; + + public ClassB(){ + a2 = 73; + } + + public long getTotal(){ + return super.getTotal() + a2; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 73; + } +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/ClassC.java b/test/src/share/classes/values1/javax/rmi/download/values/ClassC.java new file mode 100644 index 000000000..7cdc24ad3 --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/ClassC.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassC extends ClassB { + private static final long serialVersionUID = 123156789L; + private int e, f; + + public ClassC(){ + e = 56; + f = 1; + } + + public long getTotal(){ + return super.getTotal() + e + f; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 56 + 1; + } +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/ClassE.java b/test/src/share/classes/values1/javax/rmi/download/values/ClassE.java new file mode 100644 index 000000000..fbb58d3f2 --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/ClassE.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassE extends ClassA{ + private static final long serialVersionUID = 222456789L; + private int f, g, h; + + public ClassE(){ + f = 6; + g = 8; + h = 2; + } + + public long getTotal(){ + return super.getTotal() + f + g + h; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 6 + 8 + 2; + } +} // 19 diff --git a/test/src/share/classes/values1/javax/rmi/download/values/ClientA.java b/test/src/share/classes/values1/javax/rmi/download/values/ClientA.java new file mode 100644 index 000000000..a0b7518ab --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/ClientA.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClientA extends javax.rmi.fvd.ParentClass{ + private static final long serialVersionUID = 113456789L; + + private int c, d, e; + + public ClientA(){ + c = 456; + d = 31; + e = 3109; + } + + public long getTotal(){ + return super.getTotal() + c + d + e; + } + + public long getOriginalTotal(){ + return 456 + 31 + 3109; + } +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/DownloadA.java b/test/src/share/classes/values1/javax/rmi/download/values/DownloadA.java new file mode 100644 index 000000000..c6fa71e67 --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/DownloadA.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; +public class DownloadA implements java.io.Serializable { + public class Inner {} +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/DownloadB.java b/test/src/share/classes/values1/javax/rmi/download/values/DownloadB.java new file mode 100644 index 000000000..76994d472 --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/DownloadB.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; +//import com.sun.corba.ee.impl.util.JDKClassLoader; + +public class DownloadB implements java.io.Serializable { + public class Inner {} + public class Nested {} + + public String toString() { + String exMsg = ""; + + // First, make sure that using Class.forName() fails to load + // our nested class... + + try { + Class.forName("javax.rmi.download.values.DownloadB$Nested"); + + // Succeeded, but should not have... + + return "DownloadB.toString(): loaded Nested when calling Class.forName()!"; + } catch (Exception e) {} + + // Now make sure that using JDKClassLoader.loadClass() succeeds to + // load our nested class... + + try { + //JDKClassLoader.loadClass(null,"javax.rmi.download.values.DownloadB$Nested",true); + + // Success... + + return "Loaded DownloadB.Nested"; + + } catch (Exception e) { + exMsg = e.toString(); + } + + // Failed to load... + + return "DownLoadB.toString() failed to load DownloadB.Nested. Caught: "+exMsg; + } +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/MissingContainer.java b/test/src/share/classes/values1/javax/rmi/download/values/MissingContainer.java new file mode 100644 index 000000000..c9ccf7ecd --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/MissingContainer.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class MissingContainer extends javax.rmi.fvd.ParentClass { + private static final long serialVersionUID = 123456789L; + + private int a; + + public MissingContainer(){ + a = 5; + } + + public long getTotal(){ + return super.getTotal() + a; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 5; + } +} diff --git a/test/src/share/classes/values1/javax/rmi/download/values/TheValueImpl.java b/test/src/share/classes/values1/javax/rmi/download/values/TheValueImpl.java new file mode 100644 index 000000000..b4ad9dbec --- /dev/null +++ b/test/src/share/classes/values1/javax/rmi/download/values/TheValueImpl.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +import javax.rmi.download.TheValue; + +public class TheValueImpl implements TheValue, java.io.Serializable { + public String message = "Hello, world!"; + + public TheValueImpl(){} + + public String sayHello(){ + return message; + } +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/ClassA.java b/test/src/share/classes/values2/javax/rmi/download/values/ClassA.java new file mode 100644 index 000000000..3f2e73ff2 --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/ClassA.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassA extends javax.rmi.fvd.ParentClass { + private static final long serialVersionUID = 123456789L; + + private int a; + + public ClassA(){ + a = 3; + } + + public long getTotal(){ + return super.getTotal() + a; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 3; + } +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/ClassC.java b/test/src/share/classes/values2/javax/rmi/download/values/ClassC.java new file mode 100644 index 000000000..54be225e0 --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/ClassC.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassC extends ClassA { + private static final long serialVersionUID = 123156789L; + private int e, f; + + public ClassC(){ + e = 56; + f = 1; + } + + public long getTotal(){ + return super.getTotal() + e + f; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 56 + 1; + } +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/ClassD.java b/test/src/share/classes/values2/javax/rmi/download/values/ClassD.java new file mode 100644 index 000000000..7e97562c4 --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/ClassD.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassD extends ClassA{ + private static final long serialVersionUID = 128456789L; + + private int a; + + public ClassD(){ + a = 7; + } + + public long getTotal(){ + return super.getTotal() + a; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 7; + } +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/ClassE.java b/test/src/share/classes/values2/javax/rmi/download/values/ClassE.java new file mode 100644 index 000000000..d1540098d --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/ClassE.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClassE extends ClassD{ + private static final long serialVersionUID = 222456789L; + private int f, g, h; + + public ClassE(){ + f = 6; + g = 8; + h = 2; + } + + public long getTotal(){ + return super.getTotal() + f + g + h; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 6 + 8 + 2; + } +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/ClientA.java b/test/src/share/classes/values2/javax/rmi/download/values/ClientA.java new file mode 100644 index 000000000..b9e0f35c8 --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/ClientA.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class ClientA extends javax.rmi.fvd.ParentClass{ + private static final long serialVersionUID = 113456789L; + + private int c, d; + + public ClientA(){ + c = 456; + d = 31; + } + + public long getTotal(){ + return super.getTotal() + c + d; + } + + public long getOriginalTotal(){ + return 456 + 31; + } +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/MissingClass.java b/test/src/share/classes/values2/javax/rmi/download/values/MissingClass.java new file mode 100644 index 000000000..a70af8534 --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/MissingClass.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class MissingClass implements java.io.Serializable { + + private int a; + + public MissingClass(){ + a = 3; + } + +} diff --git a/test/src/share/classes/values2/javax/rmi/download/values/MissingContainer.java b/test/src/share/classes/values2/javax/rmi/download/values/MissingContainer.java new file mode 100644 index 000000000..ff3588307 --- /dev/null +++ b/test/src/share/classes/values2/javax/rmi/download/values/MissingContainer.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998-1999 IBM Corp. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package javax.rmi.download.values; + +public class MissingContainer extends javax.rmi.fvd.ParentClass { + private static final long serialVersionUID = 123456789L; + + private int a; + private MissingClass bclass = new MissingClass(); + + public MissingContainer(){ + a = 5; + } + + public long getTotal(){ + return super.getTotal() + a; + } + + public long getOriginalTotal(){ + return super.getOriginalTotal() + 5; + } +} diff --git a/tools/classcmp/ClassComparer.java b/tools/classcmp/ClassComparer.java new file mode 100644 index 000000000..4aac4f14d --- /dev/null +++ b/tools/classcmp/ClassComparer.java @@ -0,0 +1,687 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +import sun.tools.java.*; +import sun.io.*; +import java.lang.reflect.*; +import java.util.*; +import java.io.*; + +/** + * Given two classpaths and a list of common classes, this + * will show differences between the same class in the + * different classpaths. + * + * Differences are for public or protected members only. + * + * Requires tools.jar, but has no dependency on rip-int. + * + * Should take into account: + * Methods + * Name + * Return value + * Parameter types + * Modifier differences of {public, protected, static} + * + * Fields + * Name + * Type + * All Modifier differences + * + * Classes + * Name + * Superclass name + * Implemented interfaces + * Defined classes + * Fields + * Methods + * + * This is a dirty tool, not a work of high performance art (though + * it's pretty fast in practice). + * + * WARNING: Possibility of infinite loop when each class has a field + * of the other. + */ + +public class ClassComparer +{ + private static final String LINE_SEPARATOR; + static { + LINE_SEPARATOR = System.getProperty("line.separator"); + } + + /** + * Used for Methods, Fields, and Classes. + */ + private interface CCComparable { + + /** + * Is this equivalent to the given value? This is a + * weaker comparison than equals, used to match up + * what should be equal members. For instance, a static + * field foo in Class c and a non-static field foo in + * Class c' are equivalent but not equal. + */ + public boolean isEquivalent(Object obj); + + /** + * Strong comparison -- should be identical in all + * elements used in our test. + */ + public boolean equals(Object obj); + + /** + * Even though HashSet doesn't use this for its + * equals comparison, best to provide it. + */ + public int hashCode(); + } + + /** + * Wrapper for a java.reflect.Field, hiding differences + * in ClassLoader. + */ + private static class CCField implements CCComparable { + + public Field field; + + public CCField(Field field) { + this.field = field; + } + + /** + * Checks for + * + * 1. Equivalency + * 2. Modifiers + * 3. Type + */ + public boolean equals(Object obj) { + + if (obj == null) + return false; + + if (this == obj) + return true; + + CCField other = (CCField)obj; + + return (isEquivalent(other) && + field.getModifiers() == other.field.getModifiers() && + field.getType().getName().equals(other.field.getType().getName())); + } + + /** + * Checks for + * + * 1. Name + */ + public boolean isEquivalent(Object obj) { + + CCField other = (CCField)obj; + + if (other == null) + return false; + + return field.getName().equals(other.field.getName()); + } + + public int hashCode() { + return field.getName().hashCode(); + } + + public String toString() { + return field.toString(); + } + } + + /** + * Wrapper for a java.reflect.Method, hiding differences + * in ClassLoader. + */ + private static class CCMethod implements CCComparable { + + public Method method; + + private static final int MODIFIER_MASK = (Modifier.PUBLIC & + Modifier.PROTECTED & + Modifier.STATIC); + + public CCMethod(Method method) { + this.method = method; + } + + /** + * Checks for + * + * 1. Name + * 2. Parameter types (in certain order) + */ + public boolean isEquivalent(Object obj) { + CCMethod other = (CCMethod)obj; + + if (other == null) + return false; + + return (method.getName().equals(other.method.getName()) && + classNamesCheck(method.getParameterTypes(), + other.method.getParameterTypes())); + } + + /** + * Checks for + * + * 1. Equivalency + * 2. Return type class names + * 3. Exception types (in certain order) + * 4. Differences in modifiers {public, protected, static} + */ + public boolean equals(Object obj) { + + CCMethod other = (CCMethod)obj; + + if (other == null) + return false; + + if (this == obj) + return true; + + return (isEquivalent(other) && + method.getReturnType().getName().equals(other.method.getReturnType().getName()) && + classNamesCheck(method.getExceptionTypes(), + other.method.getExceptionTypes()) && + getRealModifiers() == other.getRealModifiers()); + } + + public int hashCode() { + return method.getName().hashCode(); + } + + public String toString() { + return method.toString(); + } + + private int getRealModifiers() { + return method.getModifiers() & MODIFIER_MASK; + } + + /** + * Makes sure arrays are of equal length, and all class names + * are the same. Will return false for any order mismatch. + */ + private boolean classNamesCheck(Class[] classes1, Class[] classes2) { + if (classes1.length != classes2.length) + return false; + + for (int i = 0; i < classes1.length; i++) + if (!classes1[i].getName().equals(classes2[i].getName())) + return false; + + return true; + } + } + + /** + * Wrapper for a java.lang.Class, hiding differences + * in ClassLoader. + */ + private static class CCClass implements CCComparable { + public String desc; + public Class cl; + public Set methods; + public Set fields; + public Set classes; + public Set interfaceNames; + + public CCClass(String desc, Class cl) { + this.desc = desc; + this.cl = cl; + this.methods = getMethods(cl); + this.fields = getFields(cl); + this.classes = getCCClasses(desc, cl.getDeclaredClasses()); + this.interfaceNames = getInterfaceNames(cl); + } + + public String toString() { + return cl.getName(); + } + + /** + * Checks for + * + * 1. Name + */ + public boolean isEquivalent(Object obj) { + CCClass other = (CCClass)obj; + + if (other == null) + return false; + + return cl.getName().equals(other.cl.getName()); + } + + /** + * Checks for + * + * 1. Equivalency + * 2. Superclass name + * 3. Full non-ordered set comparison of Methods (CCMethod equals) + * 4. Full non-ordered set comparison of Fields (CCField equals) + * 5. Full non-ordered set comparison of Classes (CCClass equals) + * 6. Full non-ordered set comparison of interface class names + */ + public boolean equals(Object obj) { + CCClass other = (CCClass)obj; + + if (other == null) + return false; + + if (this == other) + return true; + + return (isEquivalent(other) && + methods.equals(other.methods) && + fields.equals(other.fields) && + classes.equals(other.classes) && + ((cl.getSuperclass() == null && + other.cl.getSuperclass() == null) || + (cl.getSuperclass() != null && + other.cl.getSuperclass() != null && + cl.getSuperclass().getName().equals(other.cl.getSuperclass().getName()))) && + interfaceNames.equals(other.interfaceNames)); + } + + // Necessary for use in HashSet + public int hashCode() { + return cl.getName().hashCode(); + } + + /** + * Filter declared methods to get public and private method + * Set of CCMethods. + */ + private Set getMethods(Class cl) { + Method[] declMethods = cl.getDeclaredMethods(); + + Set result = new HashSet(declMethods.length); + for (int i = 0; i < declMethods.length; i++) { + if (!Modifier.isPublic(declMethods[i].getModifiers()) && + !Modifier.isProtected(declMethods[i].getModifiers())) + continue; + + result.add(new CCMethod(declMethods[i])); + } + + return result; + } + + private Set getFields(Class cl) { + Field[] declFields = cl.getDeclaredFields(); + + Set result = new HashSet(declFields.length); + for (int i = 0; i < declFields.length; i++) { + if (!Modifier.isPublic(declFields[i].getModifiers()) && + !Modifier.isProtected(declFields[i].getModifiers())) + continue; + + result.add(new CCField(declFields[i])); + } + + return result; + } + + private Set getCCClasses(String newDesc, Class[] input) { + Set result = new HashSet(input.length); + + for (int i = 0; i < input.length; i++) { + if (!Modifier.isPublic(input[i].getModifiers()) && + !Modifier.isProtected(input[i].getModifiers())) + continue; + + result.add(new CCClass(newDesc, input[i])); + } + + return result; + } + + private Set getInterfaceNames(Class cl) { + Class[] interfaces = cl.getInterfaces(); + + Set result = new HashSet(interfaces.length); + + for (int i = 0; i < interfaces.length; i++) + result.add(interfaces[i].getName()); + + return result; + } + + /** + * Deep comparison resulting in formatted string. Probably + * should have formatting knowledge separated out of CCClass. + */ + public String compare(CCClass other) { + StringBuffer sbuf = new StringBuffer(); + + CCClass.compareCCComparables(this, + methods, + other, + other.methods, + sbuf); + + CCClass.compareCCComparables(this, + fields, + other, + other.fields, + sbuf); + + CCClass.compareCCComparables(this, + classes, + other, + other.classes, + sbuf); + + compareInterfaces(other, sbuf); + + if (sbuf.length() > 0) + return sbuf.toString(); + else + return null; + } + + /** + * Returns the set that is A - B (giving you all + * elements in A not in B). + */ + private static Set setDifference(Set a, Set b) { + + HashSet result = new HashSet(a); + + result.removeAll(b); + + return result; + } + + /** + * Provides human friendly differences in interfaces. + */ + private void compareInterfaces(CCClass other, StringBuffer sbuf) { + + Set notInSet1 = CCClass.setDifference(other.interfaceNames, + this.interfaceNames); + + Set notInSet2 = CCClass.setDifference(this.interfaceNames, + other.interfaceNames); + + reportLackingInterfaces(this.desc, notInSet1, sbuf); + reportLackingInterfaces(other.desc, notInSet2, sbuf); + } + + private void reportLackingInterfaces(String desc, Set set, StringBuffer sbuf) { + if (set.size() > 0) { + sbuf.append(desc); + sbuf.append(" does not implement "); + + Iterator names = set.iterator(); + + while (names.hasNext()) { + sbuf.append(names.next()); + sbuf.append(' '); + } + + sbuf.append(LINE_SEPARATOR); + } + } + + /** + * Used to diff Sets of CCMethods, CCFields, and CCClasses. + */ + public static void compareCCComparables(CCClass c1, + Set ccSet1, + CCClass c2, + Set ccSet2, + StringBuffer sbuf) { + + // Tries to find an equivalent in ccSet2 for each + // element in ccSet1 + Iterator set1Iter = ccSet1.iterator(); + + while (set1Iter.hasNext()) { + + CCComparable c1Value = (CCComparable)set1Iter.next(); + + CCComparable c2Equiv = ClassComparer.findEquivalent(c1Value, ccSet2); + + // If there was no equivalent, note that c1 has this + // element but c2 does not. + if (c2Equiv == null) { + sbuf.append(c1.desc); + sbuf.append(": "); + sbuf.append(c1Value.toString()); + sbuf.append(LINE_SEPARATOR); + } else + if (!c1Value.equals(c2Equiv)) { + + // If there was an equivalent, but it isn't equal to + // the one in c1, note the difference. + + sbuf.append(LINE_SEPARATOR); + sbuf.append(c1.desc); + sbuf.append(": "); + sbuf.append(c1Value.toString()); + + sbuf.append(LINE_SEPARATOR); + sbuf.append(c2.desc); + sbuf.append(": "); + sbuf.append(c2Equiv.toString()); + sbuf.append(LINE_SEPARATOR); + sbuf.append(LINE_SEPARATOR); + } + } + + // Now look through c2 to see if there are things it has + // that c1 does not. + Iterator set2Iter = ccSet2.iterator(); + + while (set2Iter.hasNext()) { + + CCComparable c2Value = (CCComparable)set2Iter.next(); + + CCComparable c1Equiv = ClassComparer.findEquivalent(c2Value, + ccSet1); + + // Found something that c1 doesn't have. + if (c1Equiv == null) { + sbuf.append(c2.desc); + sbuf.append(": "); + sbuf.append(c2Value.toString()); + sbuf.append(LINE_SEPARATOR); + } + } + } + } + + public static void compare(CCClass cl1, CCClass cl2) { + String diffs = cl1.compare(cl2); + if (diffs != null) { + putHeader(cl1.cl.getName()); + System.out.println(diffs); + } + } + + public static void putHeader(String className) { + System.out.println("-------------------------------------------"); + System.out.println(className); + System.out.println(); + } + + public static void compareClasses(String classpath1, + String classpath2, + String[] classes) + throws ClassNotFoundException { + + PrivateLoader cl1 = new PrivateLoader(classpath1); + PrivateLoader cl2 = new PrivateLoader(classpath2); + + for (int i = 0; i < classes.length; i++) { + + CCClass c1 = new CCClass("cp1", cl1.loadClass(classes[i])); + CCClass c2 = new CCClass("cp2", cl2.loadClass(classes[i])); + + compare(c1, c2); + } + } + + /** + * Used to find an equivalent to value in the given Set. + * Returns null on failure. + */ + public static CCComparable findEquivalent(CCComparable value, + Set set) { + Iterator iter = set.iterator(); + + while (iter.hasNext()) { + CCComparable testValue = (CCComparable)iter.next(); + + if (value.isEquivalent(testValue)) + return value; + } + + return null; + } + + /** + * Arguments: + * + * 1. Class Path 1 + * 2. Class Path 2 + * 3. List of fully qualified class names to compare that are + * common to both. + * + */ + public static void main(String[] args) { + try { + if (args.length < 3) { + System.out.println("ClassComparer class1...classN"); + System.exit(1); + } + + String[] classes = new String[args.length - 2]; + System.arraycopy(args, 2, classes, 0, classes.length); + + compareClasses(args[0], args[1], classes); + + } catch (Throwable t) { + t.printStackTrace(); + } + } + + private static class PrivateLoader extends ClassLoader + { + private ClassPath classPath; + + public PrivateLoader(ClassPath classPath) { + this.classPath = classPath; + } + + public PrivateLoader(String classPathString) { + this.classPath = new ClassPath(classPathString); + } + + // Called by the super class + protected Class findClass(String name) throws ClassNotFoundException + { + byte[] b = loadClassData(name); + return defineClass(name, b, 0, b.length); + } + + protected synchronized Class loadClass(String name, boolean resolve) + throws ClassNotFoundException + { + // First, check if the class has already been loaded + Class c = findLoadedClass(name); + if (c == null) { + + if (name.startsWith("java.")) { + c = Thread.currentThread().getContextClassLoader().loadClass(name); + } else { + c = findClass(name); + } + } + + if (resolve) + resolveClass(c); + + return c; + } + + /** + * Load the class with the given fully qualified name from the ClassPath. + */ + private byte[] loadClassData(String className) + throws ClassNotFoundException + { + // Build the file name and subdirectory from the + // class name + String filename = className.replace('.', File.separatorChar) + + ".class"; + + // Have ClassPath find the file for us, and wrap it in a + // ClassFile. Note: This is where it looks inside jar files that + // are specified in the path. + ClassFile classFile = classPath.getFile(filename); + + if (classFile != null) { + + // Provide the most specific reason for failure in addition + // to ClassNotFound + Exception reportedError = null; + byte data[] = null; + + try { + // ClassFile is beautiful because it shields us from + // knowing if it's a separate file or an entry in a + // jar file. + DataInputStream input + = new DataInputStream(classFile.getInputStream()); + + // Can't rely on input available() since it will be + // something unusual if it's a jar file! May need + // to worry about a possible problem if someone + // makes a jar file entry with a size greater than + // max int. + data = new byte[(int)classFile.length()]; + + try { + input.readFully(data); + } catch (IOException ex) { + // Something actually went wrong reading the file. This + // is a real error so save it to report it. + data = null; + reportedError = ex; + } finally { + try { input.close(); } catch (IOException ex) {} + } + } catch (IOException ex) { + // Couldn't get the input stream for the file. This is + // probably also a real error. + reportedError = ex; + } + + if (data == null) + throw new ClassNotFoundException(className, reportedError); + + return data; + } + + // Couldn't find the file in the class path. + throw new ClassNotFoundException(className + " in " + classPath); + } + } +} diff --git a/tools/classcmp/Makefile b/tools/classcmp/Makefile new file mode 100644 index 000000000..377e74a95 --- /dev/null +++ b/tools/classcmp/Makefile @@ -0,0 +1,23 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +JAVA_HOME=$(ALT_BOOTDIR) +JAVA=$(JAVA_HOME)/bin/java +JAVAC=$(JAVA_HOME)/bin/javac +CLASSPATH="$(JAVA_HOME)/lib/tools.jar:." + +build: + $(JAVAC) -classpath $(CLASSPATH) ClassComparer.java + $(JAVAC) -d tst1 tst1/TestClass.java + $(JAVAC) -d tst2 tst2/TestClass.java + +run: + $(JAVA) -classpath $(CLASSPATH) ClassComparer tst1 tst2 TestClass + diff --git a/tools/classcmp/tst1/TestClass.java b/tools/classcmp/tst1/TestClass.java new file mode 100644 index 000000000..eeded36ea --- /dev/null +++ b/tools/classcmp/tst1/TestClass.java @@ -0,0 +1,17 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +public class TestClass +{ + public String methodA() { return null; } + + public int methodX() { return 27; } +} + diff --git a/tools/classcmp/tst2/TestClass.java b/tools/classcmp/tst2/TestClass.java new file mode 100644 index 000000000..fc3ebad0b --- /dev/null +++ b/tools/classcmp/tst2/TestClass.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +public class TestClass implements java.io.Serializable +{ + public String methodA() { return null; } +} + diff --git a/tools/ior/CONV_FRAME.idl b/tools/ior/CONV_FRAME.idl new file mode 100644 index 000000000..880a96dd5 --- /dev/null +++ b/tools/ior/CONV_FRAME.idl @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +module CONV_FRAME { // IDL + typedef unsigned long CodeSetId; + struct CodeSetComponent { + CodeSetId native_code_set; + sequence conversion_code_sets; + }; + struct CodeSetComponentInfo { + CodeSetComponent ForCharData; + CodeSetComponent ForWcharData; + }; +}; diff --git a/tools/ior/CodeBaseHandler.java b/tools/ior/CodeBaseHandler.java new file mode 100644 index 000000000..b4ff1c582 --- /dev/null +++ b/tools/ior/CodeBaseHandler.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +import org.omg.IOP.Codec; +import org.omg.CORBA.Any; +import org.omg.CORBA.TypeCode; + +/** + * I can't find a Helper for the Java Codebase + * tagged component. + */ +public class CodeBaseHandler implements EncapsHandler +{ + public void display(byte[] data, + TextOutputHandler out, + Utility util) + throws DecodingException { + + try { + + out.output("type: Java Codebase Component"); + + Codec codec = util.getCDREncapsCodec(Utility.GIOP_1_0); + + TypeCode strType = util.getORB().create_string_tc(0); + + Any any = codec.decode_value(data, strType); + + out.output("codebase: " + any.extract_string()); + + } catch (Exception ex) { + throw new DecodingException(ex.getMessage()); + } + } +} + diff --git a/tools/ior/DecodingException.java b/tools/ior/DecodingException.java new file mode 100644 index 000000000..be2c3202a --- /dev/null +++ b/tools/ior/DecodingException.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +/** + * Thrown by EncapsHandlers to indicate a failure during + * their display call. + */ +public class DecodingException extends Exception +{ + public DecodingException(String msg) { + super(msg); + } +} diff --git a/tools/ior/EncapsHandler.java b/tools/ior/EncapsHandler.java new file mode 100644 index 000000000..34959ff10 --- /dev/null +++ b/tools/ior/EncapsHandler.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +/** + * If you don't have a Helper class for a certain + * tagged component or tagged profile, you can implement + * this interface to display it's data properly. + * + * Otherwise, it will merely be printed as hex. + * + * See CodeBaseHandler for an example. + * + * See the two configuration files and TaggedMapFileReader + * for how to associate your handler with a certain tag. + */ +public interface EncapsHandler +{ + /** + * Decode and display the given data (which represents + * a tagged profile or tagged component). + */ + public void display(byte[] data, + TextOutputHandler out, + Utility util) throws DecodingException; +} diff --git a/tools/ior/IIOP.idl b/tools/ior/IIOP.idl new file mode 100644 index 000000000..71ebfa6dc --- /dev/null +++ b/tools/ior/IIOP.idl @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _IIOP_IDL_ +#define _IIOP_IDL_ + +#include "IOP.idl" + +#pragma prefix "omg.org" + +#ifndef CORBA3 +#define local +#endif + +module IIOP { // IDL extended for version 1.1 and 1.2 + struct Version { + octet major; + octet minor; + }; + struct ProfileBody_1_0 {// renamed from ProfileBody + Version iiop_version; + string host; + unsigned short port; + sequence object_key; + }; + struct ProfileBody_1_1 {// also used for 1.2 + Version iiop_version; + string host; + unsigned short port; + sequence object_key; + // Added in 1.1 unchanged for 1.2 + sequence components; + }; + struct ListenPoint { + string host; + unsigned short port; + }; + typedef sequence ListenPointList; + struct BiDirIIOPServiceContext {// BI_DIR_IIOP Service Context + ListenPointList listen_points; + }; +}; diff --git a/tools/ior/IIOPProfileHandler.java b/tools/ior/IIOPProfileHandler.java new file mode 100644 index 000000000..63daee300 --- /dev/null +++ b/tools/ior/IIOPProfileHandler.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +import java.io.IOException; +import org.omg.CORBA.portable.*; +import org.omg.IOP.*; +import org.omg.IIOP.*; +import org.omg.CORBA.Any; + +/** + * Handles the IIOP Profile. Correctly recognizes 1.0 and 1.1 + * versions, delegating to the appropriate ProfileBody helper. + * + * This is necessary since we have to decide what to do + * depending on the Version at the beginning. + */ +public class IIOPProfileHandler implements EncapsHandler +{ + public void display(byte[] data, + TextOutputHandler out, + Utility util) + throws DecodingException { + + try { + + // Assumes that all IIOPProfiles contain only GIOP 1.0 + // primitives. + Codec codec = util.getCDREncapsCodec(Utility.GIOP_1_0); + + // Check the version of the profile + Any versionAny = codec.decode_value(data, + VersionHelper.type()); + + Version version = VersionHelper.extract(versionAny); + + // This assumes that the profile will change + // after GIOP 1.2. Currently this is handled + // since the caller dumps the data when getting + // a DecodingException. + if (version.major != 1 || version.minor > 2) + throw new DecodingException("Unknown IIOP Profile version: " + + version.major + + '.' + + version.minor); + + if (version.minor == 0) { + Any bodyAny = codec.decode_value(data, + ProfileBody_1_0Helper.type()); + java.lang.Object body + = ProfileBody_1_0Helper.extract(bodyAny); + + util.recursiveDisplay("ProfileBody_1_0", body, out); + + } else { + // GIOP 1.1 and 1.2 use the same + // profile body + Any bodyAny = codec.decode_value(data, + ProfileBody_1_1Helper.type()); + + java.lang.Object body + = ProfileBody_1_1Helper.extract(bodyAny); + + util.recursiveDisplay("ProfileBody_1_1", body, out); + } + } catch (Exception ex) { + throw new DecodingException(ex.getMessage()); + } + } +} diff --git a/tools/ior/IOP.idl b/tools/ior/IOP.idl new file mode 100644 index 000000000..46bd4719b --- /dev/null +++ b/tools/ior/IOP.idl @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _IOP_IDL_ +#define _IOP_IDL_ + +#pragma prefix "omg.org" + +#ifndef CORBA3 +#define local +#endif + +module IOP { // IDL + // Standard Protocol Profile tag values + typedef unsigned long ProfileId; + struct TaggedProfile { + ProfileId tag; + sequence profile_data; + }; + // an Interoperable Object Reference is a sequence of + // object-specific protocol profiles, plus a type ID. + struct IOR { + string type_id; + sequence profiles; + }; + // Standard way of representing multicomponent profiles. + // This would be encapsulated in a TaggedProfile. + typedef unsigned long ComponentId; + struct TaggedComponent { + ComponentId tag; + sequence component_data; + }; + typedef sequence TaggedComponentSeq; + + const ProfileId TAG_INTERNET_IOP = 0; + const ProfileId TAG_MULTIPLE_COMPONENTS = 1; + const ProfileId TAG_SCCP_IOP = 2; + typedef sequence MultipleComponentProfile; + + const ComponentId TAG_ORB_TYPE = 0; + const ComponentId TAG_CODE_SETS = 1; + const ComponentId TAG_POLICIES = 2; + const ComponentId TAG_ALTERNATE_IIOP_ADDRESS = 3; + const ComponentId TAG_ASSOCIATION_OPTIONS = 13; + const ComponentId TAG_SEC_NAME = 14; + const ComponentId TAG_SPKM_1_SEC_MECH = 15; + const ComponentId TAG_SPKM_2_SEC_MECH = 16; + const ComponentId TAG_KerberosV5_SEC_MECH = 17; + const ComponentId TAG_CSI_ECMA_Secret_SEC_MECH = 18; + const ComponentId TAG_CSI_ECMA_Hybrid_SEC_MECH = 19; + const ComponentId TAG_SSL_SEC_TRANS = 20; + const ComponentId TAG_CSI_ECMA_Public_SEC_MECH = 21; + const ComponentId TAG_GENERIC_SEC_MECH = 22; + const ComponentId TAG_FIREWALL_TRANS = 23; + const ComponentId TAG_SCCP_CONTACT_INFO = 24; + const ComponentId TAG_JAVA_CODEBASE = 25; + const ComponentId TAG_TRANSACTION_POLICY = 26; + const ComponentId TAG_MESSAGE_ROUTERS = 30; + const ComponentId TAG_OTS_POLICY = 31; + const ComponentId TAG_INV_POLICY = 32; + const ComponentId TAG_INET_SEC_TRANS = 123; + + typedef unsigned long ServiceId; + struct ServiceContext { + ServiceId context_id; + sequence context_data; + }; + typedef sequence ServiceContextList; +}; diff --git a/tools/ior/IORDecoder.java b/tools/ior/IORDecoder.java new file mode 100644 index 000000000..e04347faa --- /dev/null +++ b/tools/ior/IORDecoder.java @@ -0,0 +1,406 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +import java.io.*; +import java.lang.reflect.*; +import java.util.*; +import org.omg.CORBA.*; +import org.omg.CORBA.portable.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecPackage.*; +import org.omg.IOP.CodecFactoryPackage.*; +import org.omg.IIOP.Version; + +/** + * Utility for dumping IOR information. Uses two files which + * map numbers (tags) to EncapsHandlers or Helpers for + * profiles and components. + */ +public class IORDecoder implements Utility +{ + public static final String DEFAULT_TAG_PROFILE_FILE = "tagprofs.txt"; + public static final String DEFAULT_TAG_COMP_FILE = "tagcomps.txt"; + + private ORB orb; + private Map tagProfileMap; + private Map tagCompMap; + private TextOutputHandler out; + private Utility util; + private CodecFactory codecFactory; + + /** + * Uses default names for the tagged profile and component + * map files, and a default TextOutputHandler. + */ + public IORDecoder(ORB orb) throws InitializationException { + this(orb, + DEFAULT_TAG_PROFILE_FILE, + DEFAULT_TAG_COMP_FILE, + new TextOutputHandler()); + } + + /** + * Resolves a CodecFactory and processes the tagged component and + * tagged profile handler files. + */ + public IORDecoder(ORB orb, + String taggedProfileMapFile, + String taggedComponentMapFile, + TextOutputHandler textOutputHandler) + throws InitializationException { + + try { + + this.orb = orb; + out = textOutputHandler; + util = this; + + org.omg.CORBA.Object objRef + = orb.resolve_initial_references("CodecFactory"); + + if (objRef == null) + throw new InitializationException("Can't find CodecFactory"); + + codecFactory = CodecFactoryHelper.narrow(objRef); + + // Read the mapping files for tagged components + // and tagged profiles + initializeHandlers(taggedProfileMapFile, + taggedComponentMapFile); + + } catch (org.omg.CORBA.ORBPackage.InvalidName in) { + throw new InitializationException("Can't find CodecFactory: " + + in.getMessage()); + } catch (IOException ioe) { + throw new InitializationException("Error reading handler file: " + + ioe); + } catch (Exception ex) { + ex.printStackTrace(); + throw new InitializationException(ex.getMessage()); + } + } + + /** + * Main entry point for printing IORs after initialization. + */ + public void display(String iorString) throws DecodingException { + + out.output("Number of known TaggedProfiles: " + + tagProfileMap.size()); + + out.output("Number of known TaggedComponents: " + + tagCompMap.size()); + + byte[] iorBytes = stringifiedIORToBytes(iorString); + + try { + + Codec codec = util.getCDREncapsCodec(Utility.GIOP_1_0); + + Any any = codec.decode_value(iorBytes, IORHelper.type()); + org.omg.IOP.IOR ior = IORHelper.extract(any); + + util.recursiveDisplay("IOR", ior, out); + + } catch (Exception ex) { + out.output("Error decoding IOR: " + ex.getMessage()); + dumpData(iorBytes, out); + } + } + + public static void main(String[] args) + { + try { + + if (args.length != 1) { + System.out.println("IORDecoder "); + return; + } + + ORB orb = ORB.init(args, System.getProperties()); + + IORDecoder printIOR = new IORDecoder(orb); + + printIOR.display(args[0]); + + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); + } + } + + /** + * Read the two tag map files. + */ + private void initializeHandlers(String tagProfileMapFile, + String tagCompMapFile) + throws IOException { + + tagProfileMap = new HashMap(); + tagCompMap = new HashMap(); + + TaggedMapFileReader mapUtil = new TaggedMapFileReader(); + + mapUtil.readMapFile(tagProfileMapFile, + tagProfileMap, + util); + + mapUtil.readMapFile(tagCompMapFile, + tagCompMap, + util); + } + + + /** + * Copied from com.sun.corba.ee.impl.corba.IOR + */ + private static final String STRINGIFY_PREFIX = "IOR:" ; + private static final int PREFIX_LENGTH = STRINGIFY_PREFIX.length() ; + private static final int NIBBLES_PER_BYTE = 2 ; + private static final int UN_SHIFT = 4 ; // "UPPER NIBBLE" shift factor for << + private byte[] stringifiedIORToBytes(String ior) { + if ((ior.length() & 1) == 1) + throw new IllegalArgumentException("Stringified IOR has odd length"); + + byte[] buf = new byte[(ior.length() - PREFIX_LENGTH) / NIBBLES_PER_BYTE]; + + for (int i=PREFIX_LENGTH, j=0; i < ior.length(); i +=NIBBLES_PER_BYTE, j++) { + buf[j] = (byte)((hexOf(ior.charAt(i)) << UN_SHIFT) & 0xF0); + buf[j] |= (byte)(hexOf(ior.charAt(i+1)) & 0x0F); + } + + return buf; + } + + /** + * Pretty prints the buffer as hex with ASCII + * interpretation on the side. + */ + public void printBuffer(byte[] buffer, + TextOutputHandler out) { + + StringBuffer msg = new StringBuffer(); + char[] charBuf = new char[16]; + + for (int i = 0; i < buffer.length; i += 16) { + + int j = 0; + + msg.setLength(0); + + // For every 16 bytes, there is one line + // of output. First, the hex output of + // the 16 bytes with each byte separated + // by a space. + while (j < 16 && j + i < buffer.length) { + int k = buffer[i + j]; + if (k < 0) + k = 256 + k; + String hex = Integer.toHexString(k); + if (hex.length() == 1) + hex = "0" + hex; + + msg.append(hex); + msg.append(' '); + + j++; + } + + // Add any extra spaces to align the + // text column in case we didn't end + // at 16 + while (j < 16) { + msg.append(" "); + j++; + } + + // Now output the ASCII equivalents. Non-ASCII + // characters are shown as periods. + int x = 0; + + while (x < 16 && x + i < buffer.length) { + if (Character.isLetterOrDigit((char)buffer[i + x])) + charBuf[x] = (char)buffer[i + x]; + else + charBuf[x] = '.'; + x++; + } + + msg.append(charBuf, 0, x); + + out.output(msg.toString()); + } + } + + /** + * Copied from com.sun.corba.ee.impl.util.Utility. + */ + public static int hexOf(char x) + { + int val; + + val = x - '0'; + if (val >=0 && val <= 9) + return val; + + val = (x - 'a') + 10; + if (val >= 10 && val <= 15) + return val; + + val = (x - 'A') + 10; + if (val >= 10 && val <= 15) + return val; + + throw new IllegalArgumentException("Bad hex digit: " + x); + } + + /** + * Recursively display the fields of the given object. + * Cases: + * Core Java classes Call toString + * TaggedComponent Look up handler in map + * TaggedProfile Look up handler in map + * Arrays Recursively display elements + * Other Recursively display fields + */ + public void recursiveDisplay(String name, + java.lang.Object object, + TextOutputHandler out) { + try { + + Class cl = object.getClass(); + + // Print any core JDK classes rather than + // diving inside them. This handles the + // java.lang primitive wrappers well. + if (cl.getName().startsWith("java")) + out.output(name + ": " + object); + else + if (cl.isArray()) + displayArray(name, object, cl.getComponentType(), out); + else + if (cl.equals(TaggedComponent.class)) { + // TaggedComponents are special cases. We have a Map + // from the tag to a EncapsHandler. + TaggedComponent tc = (TaggedComponent)object; + + displayTaggedEntry(name, tc.tag, tc.component_data, tagCompMap, out); + } else + if (cl.equals(TaggedProfile.class)) { + // We also have a Map from the tag to an EncapsHandler + // for TaggedProfiles + TaggedProfile tp = (TaggedProfile)object; + + displayTaggedEntry(name, tp.tag, tp.profile_data, tagProfileMap, out); + } else { + out.output(name + ':'); + out.increaseIndentLevel(); + + Field[] fields = cl.getDeclaredFields(); + + for (int i = 0; i < fields.length; i++) { + recursiveDisplay(fields[i].getName(), + fields[i].get(object), + out); + } + + out.decreaseIndentLevel(); + } + } catch (Throwable t) { + t.printStackTrace(); + } + } + + /** + * Used for TaggedProfiles and TaggedComponents + */ + private void displayTaggedEntry(String name, + int tag, + byte[] data, + Map tagToHandlerMap, + TextOutputHandler out) { + EncapsHandler handler + = (EncapsHandler)tagToHandlerMap.get(new Integer(tag)); + + out.output(name); + out.increaseIndentLevel(); + out.output("tag: " + tag); + + if (handler == null) { + // We don't know anything about this this, + // so dump its data as hex. + dumpData(data, out); + + } else { + try { + // Let the handler display the data + handler.display(data, out, this); + } catch (Exception ex) { + out.output("Error while decoding: " + ex.getMessage()); + dumpData(data, out); + } + } + + out.decreaseIndentLevel(); + } + + private void dumpData(byte[] data, TextOutputHandler out) { + out.output("data:"); + out.increaseIndentLevel(); + printBuffer(data, out); + out.decreaseIndentLevel(); + } + + private void displayArray(String name, + java.lang.Object object, + Class componentType, + TextOutputHandler out) { + + if (componentType.equals(Byte.TYPE)) { + // Show byte arrays as pretty hex dumps + out.output(name + ':'); + out.increaseIndentLevel(); + printBuffer((byte[])object, out); + out.decreaseIndentLevel(); + } else { + // Make an effort to look like we know + // what we're dealing with + out.output(name + " array [length " + Array.getLength(object) + ']'); + out.increaseIndentLevel(); + + for (int i = 0; i < Array.getLength(object); i++) { + String itemName = name + '[' + i + ']'; + recursiveDisplay(itemName, + Array.get(object, i), + out); + } + + out.decreaseIndentLevel(); + } + } + + public org.omg.CORBA.ORB getORB() { + return orb; + } + + public CodecFactory getCodecFactory() { + return codecFactory; + } + + public Codec getCDREncapsCodec(Version giopVersion) + throws UnknownEncoding { + + return codecFactory.create_codec(new Encoding(ENCODING_CDR_ENCAPS.value, + giopVersion.major, + giopVersion.minor)); + } +} diff --git a/tools/ior/InitializationException.java b/tools/ior/InitializationException.java new file mode 100644 index 000000000..7a058ccd4 --- /dev/null +++ b/tools/ior/InitializationException.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +/** + * Exception indicating an error occured during + * initialization of an IORDecoder. + */ +public class InitializationException extends Exception { + public InitializationException(String msg) { + super(msg); + } +} diff --git a/tools/ior/Makefile b/tools/ior/Makefile new file mode 100644 index 000000000..d4a2e9125 --- /dev/null +++ b/tools/ior/Makefile @@ -0,0 +1,31 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +include Rules.jmk + +all: build test1 + +build: idl src + +idl: + $(IDLJ) -td $(TOOLS_OUTPUTDIR) -fall -pkgPrefix IIOP org.omg -pkgPrefix IOP org.omg IIOP.idl + $(IDLJ) -td $(TOOLS_OUTPUTDIR) -fall -pkgPrefix IIOP org.omg -pkgPrefix IOP org.omg IOP.idl + $(IDLJ) -td $(TOOLS_OUTPUTDIR) -fall -pkgPrefix CONV_FRAME org.omg CONV_FRAME.idl + $(JAVAC) -classpath $(CLASSPATH) -d $(TOOLS_OUTPUTDIR) $(TOOLS_OUTPUTDIR)/org/omg/IOP/*.java $(TOOLS_OUTPUTDIR)/org/omg/IIOP/*.java + $(JAVAC) -classpath $(CLASSPATH) -d $(TOOLS_OUTPUTDIR) $(TOOLS_OUTPUTDIR)/org/omg/CONV_FRAME/*.java + +src: + $(JAVAC) -d $(TOOLS_OUTPUTDIR) -classpath $(CLASSPATH) IORDecoder.java TextOutputHandler.java IIOPProfileHandler.java Utility.java EncapsHandler.java TagHelperHandler.java CodeBaseHandler.java DecodingException.java InitializationException.java TaggedMapFileReader.java + +test1: + $(JAVA) $(ORB_PROPS) -classpath $(CLASSPATH) tools.ior.IORDecoder IOR:0000000000000026524d493a5044617461312e4461746131486f6d653a3030303030303030303030303030303000000000000001000000000000018c000102000000000f3133302e3231342e36302e3133320000041a00000000003eafabcb0000000022000000640000000100000000000000010000000e50657273697374656e74504f410000000000000d0000415514cc000000000001ff0300000000000500000001000000200000000000010001000000020501000100010020000101090000000100010100000000210000006800000000000000010040000000000024000000100000000000000424000000660000000000400040000000080606678102010101000000170401000806066781020101010000000764656661756c74000400000000000000000000010000000806066781020101010000001900000070000000000000006866696c653a2f453a2f6a3273646b6565312e332f7265706f7369746f72792f616a6f7368696e742f6170706c69636174696f6e732f41707031436c69656e742e6a617220687474703a2f2f616a6f7368696e743a393139312f41707031436c69656e742e6a6172000000001f0000000400000003000000200000000400000001 + +clean: + $(RM) -r $(TOOLS_OUTPUTDIR) diff --git a/tools/ior/README.txt b/tools/ior/README.txt new file mode 100644 index 000000000..314b6fa11 --- /dev/null +++ b/tools/ior/README.txt @@ -0,0 +1,150 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Requirements +------------ + +This requires an ORB that supports the CodecFactory +through resolve_initial_references. Also, if you want +to see CSIv2 related information, adjust the two +tag files appropriately. Currently, they look for +com.sun.corba.ee.org.omg.CSIIOP files (renamed to +ee). + +Of course, you'll want to use the generated IDL files +that correspond to the same classes that were used to +create the IOR. + +Overview +-------- + +This is a simple utility which uses standard APIs to +print the contents of a stringified IOR. It uses +reflection and a mapping of tag to instance of +EncapsHandler to recursively decode. + +If a Helper class is available for a certain tagged +component or profile, one can easily associate the +tag with the Helper's type by adding a line in the +appropriate text file. + +There are two files, one that maps tags to profiles, +and one that maps tags to components. + +If you want to add more semantic interpretation, +create your own EncapsHandler and associate it +with a certain tag in one of the files. + +Building +-------- + +Make sure your rip-int workspace is built, as the makefiles +rely on its classes. Simply run + +gnumake build + +from this directory. + +Generated code and classes are places in a build subdirectory +under this directory. + +Possibilities +------------- + +One could have another map from + +[containing class name][field name] + +to EncapsHandler. That way, someone could provide +an EncapsHandler which could break apart a Sun +object key to give more specific details about what +it contains. + +Sample +------ + +IOR:0000000000000026524d493a5044617461312e4461746131486f6d653a3030303030303030303030303030303000000000000001000000000000018c000102000000000f3133302e3231342e36302e3133320000041a00000000003eafabcb0000000022000000640000000100000000000000010000000e50657273697374656e74504f410000000000000d0000415514cc000000000001ff0300000000000500000001000000200000000000010001000000020501000100010020000101090000000100010100000000210000006800000000000000010040000000000024000000100000000000000424000000660000000000400040000000080606678102010101000000170401000806066781020101010000000764656661756c74000400000000000000000000010000000806066781020101010000001900000070000000000000006866696c653a2f453a2f6a3273646b6565312e332f7265706f7369746f72792f616a6f7368696e742f6170706c69636174696f6e732f41707031436c69656e742e6a617220687474703a2f2f616a6f7368696e743a393139312f41707031436c69656e742e6a6172000000001f0000000400000003000000200000000400000001 + +Output: + +Number of known TaggedProfiles: 2 +Number of known TaggedComponents: 5 +IOR: + type_id: RMI:PData1.Data1Home:0000000000000000 + profiles array [length 1] + profiles[0] + tag: 0 + ProfileBody_1_1: + iiop_version: + major: 1 + minor: 2 + host: 130.214.60.132 + port: 1050 + object_key: + af ab cb 00 00 00 00 22 00 00 00 64 00 00 00 01 ???........d.... + 00 00 00 00 00 00 00 01 00 00 00 0e 50 65 72 73 ............Pers + 69 73 74 65 6e 74 50 4f 41 00 00 00 00 00 00 0d istentPOA....... + 00 00 41 55 14 cc 00 00 00 00 00 01 ff 03 ..AU.?........ + components array [length 5] + components[0] + tag: 1 + type: IDL:CONV_FRAME/CodeSetComponentInfo:1.0 + data: + ForCharData: + native_code_set: 65537 + conversion_code_sets array [length 2] + conversion_code_sets[0]: 83951617 + conversion_code_sets[1]: 65568 + ForWcharData: + native_code_set: 65801 + conversion_code_sets array [length 1] + conversion_code_sets[0]: 65792 + components[1] + tag: 33 + type: IDL:omg.org/CSIIOP/CompoundSecMechList:1.0 + data: + stateful: false + mechanism_list array [length 1] + mechanism_list[0]: + target_requires: 64 + transport_mech + tag: 36 + type: IDL:omg.org/CSIIOP/TLS_SEC_TRANS:1.0 + data: + target_supports: 0 + target_requires: 0 + port: 1060 + as_context_mech: + target_supports: 64 + target_requires: 64 + client_authentication_mech: + 06 06 67 81 02 01 01 01 ..g?.... + target_name: + 04 01 00 08 06 06 67 81 02 01 01 01 00 00 00 07 ......g?........ + 64 65 66 61 75 6c 74 default + sas_context_mech: + target_supports: 1024 + target_requires: 0 + privilege_authorities array [length 0] + supported_naming_mechanisms array [length 1] + supported_naming_mechanisms[0]: + 06 06 67 81 02 01 01 01 ..g?.... + components[2] + tag: 25 + type: Java Codebase Component + codebase: file:/E:/j2sdkee1.3/repository/ajoshint/applications/App1Client.jar http://ajoshint:9191/App1Client.jar + components[3] + tag: 31 + data: + 00 00 00 03 .... + components[4] + tag: 32 + data: + 00 00 00 01 .... diff --git a/tools/ior/Rules.jmk b/tools/ior/Rules.jmk new file mode 100644 index 000000000..9ba215bd3 --- /dev/null +++ b/tools/ior/Rules.jmk @@ -0,0 +1,28 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +BUILDDIR=../../make +include $(BUILDDIR)/Platform.gmk +include $(BUILDDIR)/common/Defs.gmk + +TOOLS_OUTPUTDIR=./build + +IDLJ_CLASS=Compile + +ORB_CLASS=com.sun.corba.ee.impl.orb.ORBImpl +ORBSINGLETON_CLASS=com.sun.corba.ee.impl.orb.ORBSingleton + +ORB_PROPS=-Dorg.omg.CORBA.ORBClass=$(ORB_CLASS) -Dorg.omg.CORBA.ORBSingletonClass=$(ORBSINGLETON_CLASS) + +RIP_INT_HOME=../../build + +CLASSPATH=.:$(RIP_INT_HOME)/classes:$(TOOLS_OUTPUTDIR) + +IDLJ=$(JAVA) -classpath $(CLASSPATH) $(IDLJ_CLASS) diff --git a/tools/ior/TagHelperHandler.java b/tools/ior/TagHelperHandler.java new file mode 100644 index 000000000..5a08e0457 --- /dev/null +++ b/tools/ior/TagHelperHandler.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +import java.lang.reflect.*; +import org.omg.CORBA.TypeCode; +import org.omg.CORBA.Any; +import org.omg.IOP.Codec; + +/** + * If you have a Helper class which will read the type of + * thing you want to map from a tag, you don't have to + * write an EncapsHandler, just specify the helper + * in the appropriate setup file. + */ +public class TagHelperHandler implements EncapsHandler +{ + private TypeCode typeCode; + private Method extractMethod; + private Codec codec; + + private static final Class[] EXTRACT_ARG_TYPES + = new Class[] { org.omg.CORBA.Any.class }; + + // Surely these are already defined somewhere + private static final Class[] NO_ARG_TYPES = new Class[] {}; + private static final Object[] NO_ARGS = new Object[] {}; + + public TagHelperHandler(String helperClassName, Codec codec) + throws ClassNotFoundException, + IllegalAccessException, + IllegalArgumentException, + InvocationTargetException, + NoSuchMethodException, + SecurityException { + + // This codec was indicated in the setup file, or + // defaulted to the GIOP 1.0 CDR Encapsulation Codec. + this.codec = codec; + + // Find the indicated helper class so we can get the + // desired type's TypeCode as well as the helper's + // extract method. + Class helper = Class.forName(helperClassName); + + typeCode + = (TypeCode)helper.getDeclaredMethod("type", + NO_ARG_TYPES).invoke(null, + NO_ARGS); + + extractMethod + = helper.getDeclaredMethod("extract", EXTRACT_ARG_TYPES); + } + + public void display(byte[] data, + TextOutputHandler out, + Utility util) + throws DecodingException { + + try { + + out.output("type: " + typeCode.id()); + + // Decode using the TypeCode from the helper. + Any any = codec.decode_value(data, typeCode); + + // Have the helper extract the desired type from + // the any. + java.lang.Object value = extractMethod.invoke(null, + new Object[] { any }); + + // Recursively display the type via reflection. + util.recursiveDisplay("data", value, out); + + } catch (Exception ex) { + throw new DecodingException(ex.getMessage()); + } + } +} diff --git a/tools/ior/TaggedMapFileReader.java b/tools/ior/TaggedMapFileReader.java new file mode 100644 index 000000000..795cc817c --- /dev/null +++ b/tools/ior/TaggedMapFileReader.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +import java.io.*; +import java.util.*; +import java.lang.reflect.*; +import org.omg.IOP.*; +import org.omg.IOP.CodecFactoryPackage.*; + +/** + * A tagged map file is currently defined as follows: + * + * Space delimited entries, one per line, in the following + * format: + * + * [] + * + * is either the name of an EncapsHandler, + * or the name of an IDL Helper class. If you have a Helper + * for a certain tagged component or profile, you don't need + * to write your own EncapsHandler. + * + * If the class is a Helper, you can optionally specify + * what encoding to use. If you provide your own handler, + * you are responsible for using the CodecFactory to + * create the correct codec. + * + * If is unspecified, it defaults to the GIOP 1.0 + * CDR encapsulation encoding. Otherwise, use this format: + * + * ENCODING_CDR_ENCAPS + * or + * + * + * Where is the number to be used in an + * org.omg.IOP.Encoding. + * + * Any lines starting with double slashes are ignored. + */ +public class TaggedMapFileReader +{ + private static final Encoding DEFAULT_ENCODING + = new Encoding(ENCODING_CDR_ENCAPS.value, (byte)1, (byte)0); + + /** + * See above for how to optionally specify an encoding + * for use with helper classes. + */ + private Encoding parseEncodingForHelper(StringTokenizer strTok) { + + Encoding encoding = DEFAULT_ENCODING; + + if (strTok.hasMoreTokens()) { + + String encodingStr = strTok.nextToken(); + String majorStr = strTok.nextToken(); + String minorStr = strTok.nextToken(); + + short encodingNum; + + if (encodingStr.equals("ENCODING_CDR_ENCAPS")) + encodingNum = ENCODING_CDR_ENCAPS.value; + else + encodingNum = Short.parseShort(encodingStr); + + encoding = new Encoding(encodingNum, + Byte.parseByte(majorStr), + Byte.parseByte(minorStr)); + } + + return encoding; + } + + /** + * Create a TagHelperHandler which will delegate to the + * given helper class, and unmarshal with a Codec of + * the specified encoding. + */ + private EncapsHandler createTagHelperHandler(String helperClassName, + Encoding encoding, + Utility util) + throws ClassNotFoundException, + IllegalAccessException, + IllegalArgumentException, + InvocationTargetException, + NoSuchMethodException, + UnknownEncoding, + SecurityException { + + Codec codec = util.getCodecFactory().create_codec(encoding); + + return new TagHelperHandler(helperClassName, codec); + } + + /** + * Parse a line of text, create the appropriate + * EncapsHandler, and add it to the Map. + */ + private void parseLine(String fullLine, + Map map, + Utility util) { + + StringTokenizer strTok + = new StringTokenizer(fullLine); + + String number = strTok.nextToken(); + + // Allow comment lines + if (number.startsWith("//")) + return; + + Integer tag = Integer.valueOf(number); + + String className = strTok.nextToken(); + + try { + + EncapsHandler handler; + + if (className.endsWith("Helper")) { + handler + = createTagHelperHandler(className, + parseEncodingForHelper(strTok), + util); + } else { + handler = (EncapsHandler)Class.forName(className).newInstance(); + } + + map.put(tag, handler); + + } catch (Exception ex) { + System.out.println("Error parsing line: " + fullLine); + ex.printStackTrace(); + } + } + + /** + * Read the given file, creating EncapsHandlers for each + * valid line of input. + */ + public void readMapFile(String fileName, Map map, Utility util) + throws IOException { + + FileInputStream fis = null; + try { + fis = new FileInputStream(fileName); + + BufferedReader reader + = new BufferedReader(new InputStreamReader(fis)); + + do { + + String input = reader.readLine(); + if (input == null) + break; + + // Skip blank lines + if (input.length() == 0) + continue; + + parseLine(input, map, util); + + } while (true); + + } catch (FileNotFoundException fnfe) { + // Silent, non-fatal + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException ioe) {} + } + } + } +} + diff --git a/tools/ior/TextOutputHandler.java b/tools/ior/TextOutputHandler.java new file mode 100644 index 000000000..f8f7fe789 --- /dev/null +++ b/tools/ior/TextOutputHandler.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +/** + * Manages text output with an indentation level. + * + * Default uses two spaces per indentation and System.out + * for displaying. + */ +import java.io.PrintWriter; + +public class TextOutputHandler +{ + private StringBuffer indentLevel; + private String indentation; + private PrintWriter writer; + + public TextOutputHandler() { + this(" ", new PrintWriter(System.out, true)); + } + + public TextOutputHandler(String indentation) { + this(" ", new PrintWriter(System.out, true)); + } + + public TextOutputHandler(String indentation, + PrintWriter writer) { + this.indentation = indentation; + this.writer = writer; + + indentLevel = new StringBuffer(); + } + + public void output(String msg) { + writer.print(indentLevel); + writer.println(msg); + } + + public void increaseIndentLevel() { + indentLevel.append(indentation); + } + + public void decreaseIndentLevel() { + indentLevel.setLength(indentLevel.length() - indentation.length()); + } +} diff --git a/tools/ior/Utility.java b/tools/ior/Utility.java new file mode 100644 index 000000000..4b77dc1e1 --- /dev/null +++ b/tools/ior/Utility.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +package tools.ior; + +import java.util.Map; +import java.io.Serializable; +import org.omg.CORBA.Any; +import org.omg.IOP.*; +import org.omg.IOP.CodecFactoryPackage.*; +import org.omg.IIOP.Version; + +/** + * Interface to provide helpful methods to + * EncapsHandler implementations. + */ +public interface Utility +{ + /** + * Constants for Codec selection. See getCDREncapsCodec. + */ + public Version GIOP_1_0 = new Version((byte)1, (byte)0); + public Version GIOP_1_1 = new Version((byte)1, (byte)1); + public Version GIOP_1_2 = new Version((byte)1, (byte)2); + + /** + * If writing one's own EncapsHandler, use Codecs to + * interpret the given byte array. + */ + public CodecFactory getCodecFactory(); + + public Codec getCDREncapsCodec(Version giopVersion) + throws UnknownEncoding; + + /** + * Get the ORB instance. Useful for generating TypeCodes. + */ + org.omg.CORBA.ORB getORB(); + + /** + * Pretty print the given byte buffer as hex with + * ASCII interpretation on the side. + */ + public void printBuffer(byte[] buffer, TextOutputHandler out); + + /** + * Recursively display the fields of the given Object. + * + * Breaks apart array types. All core Java classes (classes + * with names beginning with "java") are directly printed + * with toString. + */ + public void recursiveDisplay(String name, Object object, TextOutputHandler out); +} diff --git a/tools/ior/tagcomps.txt b/tools/ior/tagcomps.txt new file mode 100644 index 000000000..8f57a2482 --- /dev/null +++ b/tools/ior/tagcomps.txt @@ -0,0 +1,18 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +// Contains a map of tagged component number to +// an EncapsHandler or Helper + +1 org.omg.CONV_FRAME.CodeSetComponentInfoHelper +25 tools.ior.CodeBaseHandler +33 com.sun.corba.ee.org.omg.CSIIOP.CompoundSecMechListHelper +35 com.sun.corba.ee.org.omg.CSIIOP.SECIOP_SEC_TRANSHelper +36 com.sun.corba.ee.org.omg.CSIIOP.TLS_SEC_TRANSHelper diff --git a/tools/ior/tagprofs.txt b/tools/ior/tagprofs.txt new file mode 100644 index 000000000..040e3bb48 --- /dev/null +++ b/tools/ior/tagprofs.txt @@ -0,0 +1,15 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +// Contains a map of tagged profile number to +// an EncapsHandler or Helper. + +0 tools.ior.IIOPProfileHandler +1 org.omg.IOP.MultipleComponentProfileHelper diff --git a/tools/pp/msg_parser.txt b/tools/pp/msg_parser.txt new file mode 100644 index 000000000..fcc39ce30 --- /dev/null +++ b/tools/pp/msg_parser.txt @@ -0,0 +1,219 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Types: + +( type_seq ) + +Primitives (Java primitives use java type codes) + +boolean Z + read_boolean + +byte B + read_octet + +char C + read_wchar + +short S + read_short + +int I + read_long + +long J + read_longlong + +float F + read_float + +double D + read_double + +String Q + read_Value(String.class) + +Objref R + read ior only: + IORFactories.makeIOR( InputStream ) + +Typecode T + read_TypeCode + +Any A + look at Util.readAny + just do read_any result is either objref or value + +(ignore Principal, fixed, and context) +Abstract Interface + first read boolean, then either objref or value: handle this in the type string + +array of type @type + read length + read type for length + +object { type* } + read header (save info) + read chunk header if necessary + NOTE: we do not attempt to determine the type in order to + read as the ORB must. Instead we just read according to + the description. + +Indirection + we want to correlate with previously read data + Maintain cache as usual + Store each possibly referenced item in the cache using get_offset to + obtain the correct offset from the stream (see CorbaTransportManager.getMessageData( byte[][] )) + do NOT use CDR stream cache, as we do not want to depend on that much of the implementation. + Add get_offset to CDRInputStream and make it public (or this won't work) + +Is this sufficient to drive a simple CLI message parser? + +BCI@Q{BC{QQ}} + +and similar strings + +Note: display complex types using the ObjectUtility toString methods + +Tool design + +Input: + - A file containing buffers in ORBUtility.getBuffer format that also + meet the requirements of CorbaTransportManager.getMessageData + (that is, request/reply + fragments if more than one packet) + + - a type description + +Output: + - results of parsing the message(s) + +Operation: + - need to determine how message demarcation works + - extend getBuffer to return byte[][] + - get MessageData for byte[][] data + - display headers + - parse data according to type, displaying results + +Value type + tag is 0x7FFFFF00 + bit 0: 1 iff codebase URL is present + bits 1 and 2: + 0: no type info + 2: single repoid + 6: list of repoid + bit 3: 1 if chunked encoding + +value -> value_tag [ codebase_URL ] [ type_info ] state + | value_ref + +value_ref -> indirection_tag indirection + | null_tag + +value_tag -> {long in range 0x7FFFFF00 to 0x7FFFFFFF} + +type_info -> rep_ids + | repository_id + +state -> octects + | value_data* [ end_tag ] + +value_data -> value_chunk + | value + +rep_ids -> long repository_id+ + | indirection_tag indirection + +repository_id -> string + | indirection_tag indirection + +value_chunk -> chunk_size_tag octets + +null_tag -> (long)0 + +indirection_tag -> (long)0xFFFFFFFF + +codebase_URL -> string + | indirection_tag indirection + +chunk_size_tag -> {long in range 1 to 0x7FFFFFEFF} + +end_tag -> {long in range 1-2^31 to -1} + +indirection -> {long in range 1-2^31 to -1} + +80000001 first end chunk +... +FFFFFFFF last end chunk/indirection +00000000 null +00000001 first chunk length +... +7FFFFEFF last chunk length +7FFFFF00 first value header +... +7FFFFFFF last value header + +Is there an ambiguity here for an end tag of -1? +This could either be an end tag, or it could be the start +of an indirection for a value type. But note that, if +it is an end tag, it is the end of the outermost value +type. + +Representations + +All values are represented by a common interface: + +interface Datum { + void display( PrintStream ps, int startIndent, int indentIncrement ) ; + + Object value() ; + + // Type of this datum as given in the input description + String type() ; +} + +interface ValueDatum extends Datum { + String codebaseURL() ; + + String[] repositoryIds() ; + + boolean isChunked() ; + + List contents() ; +} + +interface ArrayDatum extends Datum { + Datum[] data() ; +} + +Basic implementation is interpreter with stack of type strings. +Most actions are obvious from the table above, but values are +complicated: + +"{": start of new value type + - handle ind??rection if present in input stream + - enter new ValueDatum into table for indirections + - read value header, code base URL, and repo IDs + - read chunk length if present + - push ValueDatum onto interpreter stack + +"}": end of value type + - if chunked, skip to end of chunk + - if chunked, read end tag + - pop value datum from stack and put into container + +This points out that we need an outermost container, which is pushed +onto the interpreter stack first. When the stack is empty, we +are/must be done. + +Possible extension: + - add dictionary to args that maps repo ID to parser types + - we could support multiple dictionaries to include JDK built ins and + user extensions diff --git a/www/TestCases.sxc b/www/TestCases.sxc new file mode 100644 index 000000000..4237af52f Binary files /dev/null and b/www/TestCases.sxc differ diff --git a/www/architecture.html b/www/architecture.html new file mode 100644 index 000000000..5575e74bb --- /dev/null +++ b/www/architecture.html @@ -0,0 +1,92 @@ + + + + + + + CORBA Technologies + + +

                    Architecture

                    +

                    The following documents give a high-level discussion of some aspects of + the ORB architecture:

                    +
                      +
                    • + PEPt architecture. + This is the request handling architecture for the ORB.
                    • +
                    • Server Activation Framework document.This discusses + the current ORBD design and some ideas for a portable implementation using the + Object Reference Template that would replace the current ORBD. This document is + only available in PDF, due to HTML conversion problems in FrameMaker 7.
                    • +
                    • ORBD Architecture. This is an early document on some aspects of fault tolerance and load + balancing
                    • +
                    • Failover and load balancing (IIOP FOLB) is an important ORB feature that is part of GlassFish. A number + of documents are available describing FOLB: +
                        +
                      • A paper (pdf) Harold and I wrote describing the design of the IIOP FOLB mechanisms.
                      • +
                      • The functional specification (pdf) + (odt) + Harold wrote for FOLB in SJSAS 9.1 EE. Most of the + material is still relevant to GlassFish Server Open Source Edition 3.1
                      • +
                      • The one pager for IIOP FOLB as it will be delivered in GlassFish Server + Open Source Edition 3.1
                      • + +
                      +

                      Here are some more detailed descriptions of parts of the ORB design: +

                      +
                        +
                      • Presentation +
                      • +
                      • Encoding. + This area is not well documented at present. Everett Anderson (no longer involved + with this project) wrote some useful documentation back in 2002: + + Some parts of these presentations are a bit outdated, but the technical content is still + correct and useful. +
                      • +
                      • Protocol +

                        There's not a lot written for this layer either. There is a lot of code in the ORB + that represents the GIOP protocol messages, but that is pretty simple. The transport-protocol + dispatch does need to be documented somewhere.

                        +

                      • +
                      • Transport
                      • +
                      • Utility (or things that do not fit elsewhere) +
                      • +
                      +

                      The ORB also has an extensive internal SPI that is used by the GlassFIsh project. + Javadocs for the ORB SPI are available + here. + diff --git a/www/contents.html b/www/contents.html new file mode 100644 index 000000000..c1726bc07 --- /dev/null +++ b/www/contents.html @@ -0,0 +1,49 @@ + + + + + + + + + Contents + + + + + + + +

                      GlassFish-CORBA Documentation

                      + + + +
                        + +
                      • ORB Notes (pdf). This document is + intended to cover nearly all details about the ORB architecture. It is currently incomplete, + but gives a good overview of the workspace contents and the design of the ORB class.
                      • + +
                      • Architecture.
                      • + +
                      • Procedures.
                      • + +
                      • OMG Specifications + (note that the same specifications apply for J2SE 5 or later and GlassFish-CORBA)
                      • +
                      • JavaDocs are available for the proprietary ORB SPI and ORB library used in GlassFish.
                      • + + +
                      + + + diff --git a/www/corba-gf-tips.html b/www/corba-gf-tips.html new file mode 100644 index 000000000..544ec1a1a --- /dev/null +++ b/www/corba-gf-tips.html @@ -0,0 +1,515 @@ + + + + + +CORBA GFv3 Tips + + +

                      CORBA GFv3 Tips

                      + + +

                      Mercurial Tips

                      +
                        +
                      • hg tags +
                          +
                        • To find all of the versions of the workspace. Typical output: +
                        • +
                        +
                      • +
                      +
                         tip                              380:372bc5d51565
                      +        VERSION-3.0.0-b031               373:f1c1059c8b4a
                      +        VERSION-3.0.0-b030               362:a10fc0e267fd
                      +        VERSION-3.0.0-b029               355:df0edb5a3970
                      +        VERSION-3.0.0-b028               350:26fbe9d004c7
                      +        VERSION-3.0.0-b027               342:028d4f3a17c9
                      +        VERSION-3.0.0-b025               333:426100ef9203
                      +        VERSION-3.0.0-b024               332:308727367961
                      +        VERSION-3.0.0-b022               328:ff250a049d08
                      +        VERSION-3.0.0-b021               321:16ddfd3dd5d2
                      +        FULL_MERGE                       308:f0172d8ae1e7
                      +        JMXA_PRE_AMX                     289:573ca9377d2c
                      +        UNMARSHAL_TRACE_SUPPORT          254:5044ac6b313f
                      +        VERSION-3.0.0-b020               221:3f5a486dc336
                      +        3.0-Preview                      221:3f5a486dc336
                      +        VERSION-3.0.0-b019               215:47c4ca6db041
                      +        VERSION-3.0.0-b018               208:6fec296e9757
                      +        VERSION-3.0.0-b017               205:0bba456ed22b
                      +        VERSION-3.0.0-b016               203:97952529a3be
                      +        VERSION-3.0.0-b015               201:a8d038435d88
                      +        VERSION-3.0.0-b014               198:d68593365948
                      +        VERSION-3.0.0-b013               193:0843e9da0dfc
                      +        VERSION-3.0.0-b012               190:f20d0bca25df
                      +        VERSION-3.0.0-b011               188:912a8226bc64
                      +        VERSION-3.0.0-b010               186:25991c263318
                      +        VERSION-3.0.0-b009               184:9afe139d453d
                      +        VERSION-3.0.0-b008               176:e699e4cde78d
                      +        VERSION-3.0.0-b005               174:002fb86d838f
                      +        SJSAS91_FCS_BRANCH                 0:0fc818f2f9e5
                      +
                      +
                      +
                        +
                      • hg tag VERSION-3.0.0-bXXX +
                        • To add a new tag.
                        +
                      • hg tag --remove VERSION-3.0.0-bXXX +
                        • To remove a tag (if you add it to the wrong changeset; typical this is done if you forget something)
                        +
                      • hg log -r 380:VERSION-3.0.0-b021 (or 380:373) +
                        • To see (say) all changes since b032 was released.
                        +
                      • hg clone -r VERSION-3.0.0-b021 (or just 373) +
                        • To get a copy of a particular release.
                        +
                      • hg status +
                          +
                        • will tell you what has changed.  It displays +<mode> <pathname>, where pathname is always relative to the +start of the workspace. Some typical modes: +
                            +
                          • M: modified
                          • +
                          • A: added
                          • +
                          • R: removed
                          • +
                          • ?: new file not currently part of workspace
                          • +
                          • !: file was removed that is in workspace
                          • +
                          +
                        • +
                      • +
                      • hg addremove +
                        • To get rid of ? and ! files
                        • +
                        • NOTE: I've seen addremove fail to find files, so keep an eye on it.
                      • +
                      • .hgignore +
                        • file at the top of the workspace. This +gives the many patterns that are ignored (generated files, temp files, +etc) in the build.
                      • +
                      • .hg +
                        • directory at the top of the workspace.  Do not +touch anything in it except the hgrc file, which typically just +contains the parent (if any) from which the workspace was cloned.
                      • +
                      • We do not use branches in the CORBA workspace.  If a command says +something about multiple heads, don't force it with -f.  Instead, +multiple heads is a sign that a merge is needed.
                      • +
                      • You will probably want to have a ~/.hgrc file.  Ken's looks like +this:
                      • +
                      + +
                      [ui]
                      +merge = jfilemerge
                      +verbose = true
                      +username = Ken Cavanaugh <Ken.Cavanaugh@sun.com>
                      +editor = vim
                      +
                      +[merge-tools]
                      +meld.args = $output $base $other
                      +jfilemerge.args = -a $base $local $other $output
                      +
                      +[web]
                      +allow_push = *
                      +allowpull = true
                      +push_ssl = false
                      +
                      +[extensions]
                      +hgk =
                      +hgext.hgk =
                      +
                      +The username seems to be mostly useless.  However, the merge stuff is +really important.  jfilemerge is the same as the old TeamWare merge +tool, which still works better than most programs that came after it +(this is a pure java version).  It's available somewhere on SWAN, but I +can't get to that copy at the moment, so I've attached my mercurial +workspace (which is a NB project) of the jfilemerge tool. +
                      + +
                        +
                      • hg annotate +
                        • useful for finding out which version of a file +first introduced a particular line in a source file (similar to other +version control systems).
                      • +
                      • hg cat +
                        • looks useful for fetching a particular version of a file +(I haven't used this).
                      • +
                      • NOTE: commit (updating your workspace) and push (publishing your changes) are separate operations.  This sometimes confuses people used to svn and the like.
                      • +
                      • hg diff +
                        • for seeing what's changed (you can give +it 0-2 -r options to select versions).
                      • +
                      • hg heads +
                        • shows what's going on if you have multiple heads +(not really useful otherwise)
                      • +
                      • hg merge +
                          +
                        • how you merge changes when needed. Normally you need +this only when you do an hg pull that results in conflicts.
                        • +
                        • It's probably best to do hg commit before hg pull and then merge afterwards.
                      • +
                      • hg rename +
                        • used to move things around (otherwise I think +hg may not link the revisions for the old and new files)
                      • +
                      • hg view +
                          +
                        • shows overall structure of the changesets.  +Jean-Christophe Collet's jHg is probably more useful (attached).
                        • +
                        • Most useful way for me to use jHg: cd <ws> (with +uncommitted changes), then jHg -w `pwd` to have an easy way to browse +changes to create the commit comment.
                      • +
                      + + + +

                      GFv3 workspace and build

                      +The GFv3 wiki starts at + + http://wiki.glassfish.java.net/Wiki.jsp?page=PlanForGlassFishV3. +Some of it is actually useful.
                      +
                      +The GFv3 workspace is at + + https://svn.dev.java.net/svn/glassfish-svn/trunk/v3.
                      + +See the following for build information: + + + +The QL tests are in the GFv3 workspace.  The appserv tests are in a +slightly different place:
                      +
                      +https://svn.dev.java.net/svn/glassfish-svn/trunk/appserv-tests
                      +
                      +We only care about the devtests/ejb directory in appserv-tests.
                      +
                      +Quick summary: + +To see what corba version is in use, look in the top level file: +
                         v3/pom.xml
                      +for the element
                      +
                         <glassfish-corba.version>3.0.0-b032<glassfish-corba.version>
                      +
                      +You can edit this if needed to update the ORB release, then rebuild.
                      +
                      + +Question: I know you can incrementally rebuild a module simply +by running mvn -U install in the module's top
                      +level directory, but how to you regenerate glassfish.zip and web.zip?
                      +
                      +Useful locations (and some key files: note that source is always under +src/main/java in maven):
                      +
                        +
                      • orb (much of this code is very similar to v2)
                        +
                      • +
                          +
                        • orb-connector: the non-corba-bundle dependent code that helps +with ORB init
                        • +
                            +
                          • org.glassfish.enterprise.iiop.api:
                          • +
                              +
                            • GlassFishORBFactory
                            • +
                            • GlassFishORBHelper
                              +
                            • +
                            +
                          +
                        • orb-iiop: the corba-bundle dependent ORB init related code +(depends on orb-connector)
                        • +
                            +
                          • org.glassfish.enterpeise.iiop.impl:
                          • +
                              +
                            • GlassFishORBFactoryImpl
                            • +
                            • GlassFIshORBManager
                            • +
                            • PEORBConfigurator
                              +
                            • +
                            +
                          +
                        • orb-enabler: used to set default ORB-related system properties
                        • +
                        • Note that I currently have enabled the ClientGroupManager to +enabled the use of CSIv2SSLTaggedComponentHandler (see issue 8861), but +none of the other enterprise features are enabled yet.
                          +
                        • +
                        +
                      • transactions/jts
                      • +
                          +
                        • com.sun.jts.CosTransactions
                        • +
                            +
                          • DefaultTransactionService is where the narrow happens that +causes all of the initialization problems.
                            +
                          • +
                          +
                        +
                      • ejb
                      • +
                          +
                        • I haven't had too much need to crawl around here so far.
                          +
                        • +
                        +
                      • common
                      • +
                          +
                        • amx lives under here
                        • +
                        +
                      + + +

                      Maven repositories

                      + +We deal with two repositories: + +Both have the same structure.  Corba modules are +under com/sun/corba.  The following are the CORBA modules we currently +use:
                      +
                        +
                      • glassfish-corba-asm
                      • +
                      • glassfish-corba-codegen
                      • +
                      • glassfish-corba-csiv2-idl
                      • +
                      • glassfish-corba-newtimer
                        +
                      • +
                      • glassfish-corba-omgapi
                      • +
                      • glassfish-corba-orb
                      • +
                      • glassfish-corba-orbgeneric
                      • +
                      +We may combine or rename some of these.  The structure of all of these +is the same: the next level of subdirectory gives the version,
                      +as in for example +http://download.java.net/maven/2/com/sun/corba/glassfish-corba-orb/3.0.0-b031:
                      +
                      [   ]  glassfish-corba-orb-3.0.0-b031.jar                               19-Oct-2009 14:49     1M    
                      +[   ]  glassfish-corba-orb-3.0.0-b031.jar.md5                           19-Oct-2009 14:49     1K    
                      +[   ]  glassfish-corba-orb-3.0.0-b031.jar.sha1                          19-Oct-2009 14:49     1K    
                      +[   ]  glassfish-corba-orb-3.0.0-b031.pom                               19-Oct-2009 14:49     4K    
                      +[   ]  glassfish-corba-orb-3.0.0-b031.pom.md5                           19-Oct-2009 14:49     1K    
                      +[   ]  glassfish-corba-orb-3.0.0-b031.pom.sha1                          19-Oct-2009 14:49     1K 
                      +
                      +
                      +Every artifact in maven (like the jar file) comes with a pom file that +describes it.
                      + + +

                      CORBA workspace and build

                      + +The GFv3 CORBA workspace is at +
                      + + https://kenai.com/hg/gf-corba-v3-mirror~staging.
                      + +Build instructions (assuming WS is where your workspace lives):
                      +
                        +
                      • cd WS/make
                      • +
                      • ant clean orb-library rename
                      • +
                      • cd WS/build/rename/ee/make
                      • +
                      • ant clean build +
                        • builds all of the ORB
                      • +
                      • ant build-tests +
                        • builds all of the ORB tests
                      • +
                      • ant make-bundles +
                        • generates the bundles that we install in maven (or sometimes + directly in the modules directory)
                      • +
                      • ant release +
                          +
                        • release to the download.java.net maven repository
                        • +
                        • Note: this is REALLY slow.  It upload about 8 MB of artifacts +to a slow server (takes 4-8 minutes), which then takes at least 30 +minutes to copy files to the real repository.  Only do this when +releasing an ORB.
                        • +
                      • +
                      • ant release-local +
                        • Related to the ~/.m2 maven repository.  This is really fast, and is fine for developing on your machine
                      • +
                      + +Documentation +
                        +
                      • www/index.html
                      • +
                      • For more details, see +
                          +
                        • www/design/orb_notes.html (which is mostly up to date for the GFv3 workspace structure and build)
                        • +
                        • Note that PEPt has been removed (to avoid problems with inhertance and generics in the framework).
                      • +
                      + +You can browse the b020 version of the ORB at +http://kencavanaugh.com/CORBA/www/sources/orb-sources.html.
                      +Unfortunately I have not had time to keep that up to date.
                      + + +

                      Hudson

                      + +I highly recommend setting up your own Hudson server. The +config.xml that I use for the corba-master job is +attached (it pulls from a local repository, and that is specific to my +setup).  This allows you to simply commit, and not +even think about running the tests (Hudson does that for you). I think +you can use this as follows: + +
                      +
                        +
                      • Get the latest hudson, and run it: java -jar hudson.war
                      • +
                      • You may want to put this in a startup item to automatically start up. +something like: +
                        • nohup java -jar ~/hc/java/hudson/hudson-1-330.war --httpPort=9090 --httpsPort=9091 > ~/.hudson/logfile 2>&1
                      • +
                      • create a job for the CORBA workspace (call it corba-master + for example)
                      • +
                      • In ~/.hudson/jobs/corba-master, there should be a + config.xml. Replace it with the attached version.
                      • +
                      +This should get you close.
                      + + +

                      Testing

                      +The testing and release procedure for the ORB is as follows:
                      +
                        +
                      • First, get all of the ORB unit tests to pass (see the Hudson job, +or look at the ORB notes document which describes the various ant +targets and the runtest script)
                      • +
                      • Then we need to get the app server tests to pass:
                      • +
                          +
                        • glassfish distribution QL
                        • +
                        • web distribution QL
                        • +
                        • EJB dev tests
                        • +
                        +
                      • Then update the ORB version by running the update-build target +against the renamed ORB
                      • +
                      • Then hg tag  VERSION-3.0.0-bXXX, and push the resulting changeset +to the staging repository.
                      • +
                      • Then finally run the release target
                      • +
                      +I'd like to have all of this automated for testing.  Darani has a lot +of this automated on the SWAN
                      +hudson (hudson.sfbay), but I don't have it nicely packaged for off-SWAN +use.
                      +
                      +I have a bunch of scripts for testing. They assume that there is a +BUILD area for the workspace, and
                      +a RUN area for the installed GFv3.
                      +
                        +
                      • installgfv3: copy glassfish.zip to RUN (for glassfish QL)
                      • +
                          +
                        • must have done mvn -U install first
                          +
                        • +
                        +
                      • installgfv3w: copy web.zip to RUN (for web QL)
                      • +
                          +
                        • must have done mvn -U install first.
                          +
                        • +
                        +
                      • installgmbal: copies my current gmbal to whatever is installed at +RUN
                      • +
                      • installorb: copies my current ORB to RUN
                      • +
                      • startql: start the app server and derby database
                      • +
                      • stopql: stop all server and derby
                        +
                      • +
                          +
                        • Check for ASMain with jps after stopql: sometimes it fails to +stop the app server
                        • +
                        +
                      • qlonly: runs the glassfish QL.  This versions starts the app +server
                      • +
                      • qlonlyw: runs the web QL.  Also starts the app server
                      • +
                      • rql: run a single QL directory
                        +
                      • +
                      • runejb: run all of the EJB devtests
                      • +
                      • runql: basically installgfv3 and qlonly
                      • +
                      • rerunql: same as qlonly
                      • +
                      +These are all in the temp.tgz attachment.
                      + + +

                      The GFv3 installation structure

                      +Unzipping glassfish.zip creates the following structure:
                      +
                        +
                      • glassfishv3
                      • +
                          +
                        • bin
                        • +
                        • javadb
                        • +
                        • third-party-license-readme.txt
                        • +
                        • glassfish (the useful part for us)
                        • +
                            +
                          • bin
                          • +
                              +
                            • asadmin lives here
                            • +
                                +
                              • most important for us: asadmin start-domain --debug +allows the debugger to be attached to port 9009 (as specified in +domain.xml)
                                +
                              • +
                              +
                            +
                          • config
                          • +
                          • databases
                          • +
                          • docs
                          • +
                          • domains
                          • +
                              +
                            • domain1 (only care about logs and config)
                              +
                            • +
                                +
                              • logs
                              • +
                                  +
                                • server.log for all logger output (including CORBA trace +info)
                                  +
                                • +
                                +
                              • config
                              • +
                                  +
                                • domain.xml
                                  +
                                • +
                                    +
                                  • use -D to set ORB properties under the +<jvm-options> elements
                                    +
                                  • +
                                  +
                                • logging.properties (I think you can turn on loggers +here)
                                  +
                                • +
                                +
                              +
                            +
                          • legal
                          • +
                          • lib
                          • +
                          • modules (where we install ORB bundles if necessary)
                            +
                          • +
                          • osgi
                            +
                          • +
                          +
                        • mq
                          +
                        • +
                        +
                      + + +

                      Bug tracking

                      +Here is a query for CORBA in +IssueTracker. We don't use bugster much (except for CTS issues).
                      +
                      +

                      +This should get you started.  We should probably put this up as a web +page somewhere.
                      +
                      +I don't think I've quite covered testing adequately, but we can cover +more tomorrow.
                      +
                      +
                      +Ken.
                      + diff --git a/www/design/6763340_diffs.txt b/www/design/6763340_diffs.txt new file mode 100644 index 000000000..07ed9a2e0 --- /dev/null +++ b/www/design/6763340_diffs.txt @@ -0,0 +1,5811 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Here are the differences that should fix 6763340. I'll also include the full modified +ORB sources from JDK 1.6.0_14. I also added code to CorbaClientRequestDispatcherImpl.beginRequest +to limit the maximum recursion, but I have not yet applied that change to the GFv3 ORB. + +Also, all of the System.out.println code that we have added needs to be stripped out of the code. +I have added a lot of ORB debug code in the GFv3 version, but I have not attempted to +do that for the JDK version. + +Fixes for 6763340: + All changes are flagged with a comment containing the bug id: + +spi/protocol/PIHandler.java: + Add after invokeClientPIEndingPoint: + + /** + * Called when a retry is needed after initiateClientPIRequest but + * before invokeClientPIRequest. In this case, we need to properly + * balance initiateClientPIRequest/cleanupClientPIRequest calls, + * but WITHOUT extraneous calls to invokeClientPIEndingPoint + * (see bug 6763340). + * + * @param replyStatus One of the constants in iiop.messages.ReplyMessage + * indicating which reply status to set. + * @param exception The exception before ending interception points have + * been invoked, or null if no exception at the moment. + * @return The exception to be thrown, after having gone through + * all ending points, or null if there is no exception to be + * thrown. Note that this exception can be either the same or + * different from the exception set using setClientPIException. + * There are four possible return types: null (no exception), + * SystemException, UserException, or RemarshalException. + */ + Exception makeCompletedClientRequest( + int replyStatus, Exception exception ) ; + +impl/orb/ORBImpl.java: + Modify releaseOrDecrementInvocationInfo(): + + public void releaseOrDecrementInvocationInfo() + { + int entryCount = -1; + ClientInvocationInfo clientInvocationInfo = null; + try { + if (subcontractDebugFlag) { + dprint(".releaseOrDecrementInvocationInfo->:"); + } + StackImpl invocationInfoStack = + (StackImpl)clientInvocationInfoStack.get(); + if (!invocationInfoStack.empty()) { + clientInvocationInfo = + (ClientInvocationInfo)invocationInfoStack.peek(); + } else { + throw wrapper.invocationInfoStackEmpty() ; + } + clientInvocationInfo.decrementEntryCount(); + entryCount = clientInvocationInfo.getEntryCount(); + if (clientInvocationInfo.getEntryCount() == 0 + // 6763340: don't pop if this is a retry! + && !clientInvocationInfo.isRetryInvocation()) { + + invocationInfoStack.pop(); + if (subcontractDebugFlag) { + dprint(".releaseOrDecrementInvocationInfo: pop"); + } + } + } finally { + if (subcontractDebugFlag) { + dprint(".releaseOrDecrementInvocationInfo<-: entry count: " + + entryCount + + " " + clientInvocationInfo); + } + } + } + +impl/protocol/CorbaClientRequestDispatcherImpl: + Modify beginRequest (this is just the catch (RemarshalException) clause. This is the + only recursive call in the GFv3 ORB, but the same fix is needed before the other + recursive call to beginRequest in the JDK ORB): + + } catch( RemarshalException e ) { + if (orb.subcontractDebugFlag) { + dputil.info( "Remarshal" ) ; + } + + // NOTE: We get here because an interceptor raised ForwardRequest + // and updated the IOR/Iterator. Since we have a fresh iterator + // hasNext should succeed. + + // REVISIT: We should feed ALL interceptor exceptions to + // iterator.reportException so it can determine if it wants + // to retry. Right now, SystemExceptions will flow to the + // client code. + + // REVISIT: + // This assumes that interceptors update + // ContactInfoList outside of subcontract. + // Want to move that update to here. + if (getContactInfoListIterator(orb).hasNext()) { + contactInfo = (ContactInfo)getContactInfoListIterator(orb).next(); + if (orb.subcontractDebugFlag) { + dputil.info( "RemarshalException: hasNext true", + "contact info", contactInfo ) ; + } + + // Fix for 6763340: Complete the first attempt before starting another. + orb.getPIHandler().makeCompletedClientRequest( + ReplyMessage.LOCATION_FORWARD, null ) ; + orb.getPIHandler().cleanupClientPIRequest() ; + + return beginRequest(self, opName, isOneWay, contactInfo); + } else { + if (orb.subcontractDebugFlag) { + dputil.info( "RemarshalException: hasNext false" ) ; + } + ORBUtilSystemException wrapper = + orb.getLogWrapperTable().get_RPC_PROTOCOL_ORBUtil() ; + throw wrapper.remarshalWithNowhereToGo(); + } + } + +impl/interceptors/RequestInfoImpl.java: + Modify reset method: + + void reset() { + + // Please keep these in the same order as declared above. + + flowStackIndex = 0; + startingPointCall = 0; + intermediatePointCall = 0; + endingPointCall = 0; + // 6763340 + setReplyStatus( UNINITIALIZED ) ; + currentExecutionPoint = EXECUTION_POINT_STARTING; + alreadyExecuted = false; + connection = null; + serviceContexts = null; + forwardRequest = null; + forwardRequestIOR = null; + exception = null; + + // We don't need to reset the Slots because they are + // already in the clean state after recieve_ interceptor + // are called. + } + +impl/interceptors/PIHandlerImpl.java: + Replace invokeClientPIEndingPoint as follows: + + // Needed when an error forces a retry AFTER initiateClientPIRequest + // but BEFORE invokeClientPIStartingPoint. + public Exception makeCompletedClientRequest( int replyStatus, + Exception exception ) { + + // 6763340 + return handleClientPIEndingPoint( replyStatus, exception, false ) ; + } + + public Exception invokeClientPIEndingPoint( int replyStatus, + Exception exception ) { + + // 6763340 + return handleClientPIEndingPoint( replyStatus, exception, true ) ; + } + + public Exception handleClientPIEndingPoint( + int replyStatus, Exception exception, boolean invokeEndingPoint ) { + + if (orb.interceptorDebugFlag) { + dputil.enter( "handleClientPIEndingPoint", + "replyStatus", getReplyStatus(replyStatus), + "exception", exception, + "invokeEndingPoint", invokeEndingPoint ) ; + } + + try { + if( !hasClientInterceptors ) return exception; + if( !isClientPIEnabledForThisThread() ) return exception; + + // Translate ReplyMessage.replyStatus into PI replyStatus: + // Note: this is also an assertion to make sure a valid replyStatus + // is passed in (IndexOutOfBoundsException will be thrown otherwise) + short piReplyStatus = REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; + + // Invoke the ending interception points and record exception + // and reply status info in the info object: + ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); + info.setReplyStatus( piReplyStatus ); + info.setException( exception ); + + if (invokeEndingPoint) { + // 6763340 + interceptorInvoker.invokeClientInterceptorEndingPoint( info ); + piReplyStatus = info.getReplyStatus(); + } + + // Check reply status: + if( (piReplyStatus == LOCATION_FORWARD.value) || + (piReplyStatus == TRANSPORT_RETRY.value) ) { + // If this is a forward or a retry, reset and reuse + // info object: + info.reset(); + + // fix for 6763340: + if (invokeEndingPoint) { + info.setRetryRequest( RetryType.AFTER_RESPONSE ) ; + } else { + info.setRetryRequest( RetryType.BEFORE_RESPONSE ) ; + } + + // ... and return a RemarshalException so the orb internals know + exception = new RemarshalException(); + } else if( (piReplyStatus == SYSTEM_EXCEPTION.value) || + (piReplyStatus == USER_EXCEPTION.value) ) { + + exception = info.getException(); + } + + return exception; + } finally { + if (orb.interceptorDebugFlag) { + dputil.exit() ; + } + } + } + +Replace initiateClientPIRequest as follows: + + public void initiateClientPIRequest( boolean diiRequest ) { + if (orb.interceptorDebugFlag) { + dputil.enter( "initiateClientPIRequest" ) ; + } + + try { + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + // Get the most recent info object from the thread local + // ClientRequestInfoImpl stack: + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + ClientRequestInfoImpl info = null; + + if (!infoStack.empty() ) { + info = infoStack.peek(); + } + + if (!diiRequest && (info != null) && info.isDIIInitiate() ) { + // In RequestImpl.doInvocation we already called + // initiateClientPIRequest( true ), so ignore this initiate. + if (orb.interceptorDebugFlag) { + dputil.info( "second call for a DII request" ) ; + } + info.setDIIInitiate( false ); + } else { + // If there is no info object or if we are not retrying a request, + // push a new ClientRequestInfoImpl on the stack: + if (orb.interceptorDebugFlag) { + dputil.info( "normal call" ) ; + } + + // 6763340: don't push unless this is not a retry + if( (info == null) || !info.getRetryRequest().isRetry() ) { + info = new ClientRequestInfoImpl( orb ); + infoStack.push( info ); + if (orb.interceptorDebugFlag) { + dputil.info( "client infoStack was pushed" ) ; + } + // Note: the entry count is automatically initialized to 0. + } + + // Reset the retry request flag so that recursive calls will + // push a new info object, and bump up entry count so we know + // when to pop this info object: + info.setRetryRequest( RetryType.NONE ); + info.incrementEntryCount(); + + // KMC 6763340: I don't know why this wasn't set earlier, + // but we do not want a retry to pick up the previous + // reply status, so clear it here. Most likely a new + // info was pushed before, so that this was not a problem. + info.setReplyStatus( RequestInfoImpl.UNINITIALIZED ) ; + + // If this is a DII request, make sure we ignore the next initiate. + if( diiRequest ) { + info.setDIIInitiate( true ); + } + } + } finally { + if (orb.interceptorDebugFlag) { + dputil.exit() ; + } + } + } + +Replace cleanupClientPIRequest as follows: + + public void cleanupClientPIRequest() { + if (orb.interceptorDebugFlag) { + dputil.enter( "cleanupClientPIRequest" ) ; + } + + try { + if( !hasClientInterceptors ) return; + if( !isClientPIEnabledForThisThread() ) return; + + ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); + RetryType rt = info.getRetryRequest() ; + + // fix for 6763340 + if (!rt.equals( RetryType.BEFORE_RESPONSE )) { + // If the replyStatus has not yet been set, this is an indication + // that the ORB threw an exception before we had a chance to + // invoke the client interceptor ending points. + // + // _REVISIT_ We cannot handle any exceptions or ForwardRequests + // flagged by the ending points here because there is no way + // to gracefully handle this in any of the calling code. + // This is a rare corner case, so we will ignore this for now. + short replyStatus = info.getReplyStatus(); + if (replyStatus == info.UNINITIALIZED ) { + invokeClientPIEndingPoint( ReplyMessage.SYSTEM_EXCEPTION, + wrapper.unknownRequestInvoke( + CompletionStatus.COMPLETED_MAYBE ) ) ; + } + } + + // Decrement entry count, and if it is zero, pop it from the stack. + info.decrementEntryCount(); + + // fix for 6763340, and probably other cases (non-recursive retry) + if (info.getEntryCount() == 0 && !info.getRetryRequest().isRetry()) { + RequestInfoStack infoStack = + threadLocalClientRequestInfoStack.get(); + infoStack.pop(); + if (orb.interceptorDebugFlag) { + dputil.info( "client infoStack was popped" ) ; + } + } + } finally { + if (orb.interceptorDebugFlag) { + dputil.exit() ; + } + } + } + +impl/interceptors/ClientRequestInfoImpl: + +Add import for com.sun.corba.ee.spi.protocol.RetryType + +Change reset() as follows: + + void reset() { + if (myORB.interceptorDebugFlag) { + dputil.enter( "reset" ) ; + } + + try { + super.reset(); + + // Please keep these in the same order that they're declared above. + + // 6763340 + retryRequest = RetryType.NONE; + + // Do not reset entryCount because we need to know when to pop this + // from the stack. + + request = null; + diiInitiate = false; + messageMediator = null; + + // Clear cached attributes: + cachedTargetObject = null; + cachedEffectiveTargetObject = null; + cachedArguments = null; + cachedExceptions = null; + cachedContexts = null; + cachedOperationContext = null; + cachedReceivedExceptionId = null; + cachedResult = null; + cachedReceivedException = null; + cachedEffectiveProfile = null; + cachedRequestServiceContexts = null; + cachedReplyServiceContexts = null; + cachedEffectiveComponents = null; + + piCurrentPushed = false; + + startingPointCall = CALL_SEND_REQUEST; + endingPointCall = CALL_RECEIVE_REPLY; + + } finally { + if (myORB.interceptorDebugFlag) { + dputil.exit() ; + } + } + } + +Change set/getRetryRequest as follows: + + /** + * Set or reset the retry request flag. + */ + void setRetryRequest( RetryType retryRequest ) { + // 6763340 + this.retryRequest = retryRequest; + } + + /** + * Retrieve the current retry request status. + */ + RetryType getRetryRequest() { + // 6763340 + return this.retryRequest; + } + +Add new enum type to com/sun/corba/ee/spi/protocol/RetryType.java (new class) (with appropriate header): + +package com.sun.corba.ee.spi.protocol ; + +// Introduce more information about WHY we are re-trying a request +// so we can properly handle the two cases: +// - BEFORE_RESPONSE means that the retry is caused by +// something that happened BEFORE the message was sent: either +// an exception from the SocketFactory, or one from the +// Client side send_request interceptor point. +// - AFTER_RESPONSE means that the retry is a result either of the +// request sent to the server (from the response), or from the +// Client side receive_xxx interceptor point. +public enum RetryType { + NONE( false ), + BEFORE_RESPONSE( true ), + AFTER_RESPONSE( true ) ; + + private final boolean isRetry ; + + RetryType( boolean isRetry ) { + this.isRetry = isRetry ; + } + + public boolean isRetry() { + return this.isRetry ; + } +} ; + + +================================================ + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/encoding/CDROutputStream_1_0.java +--- a/src/share/classes/com/sun/corba/ee/impl/encoding/CDROutputStream_1_0.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/encoding/CDROutputStream_1_0.java Mon Jul 06 12:05:55 2009 -0700 +@@ -209,18 +209,8 @@ + + private final void createRepositoryIdHandlers() + { +- if (orb != null) { +- // Get the appropriate versions based on the ORB version. The +- // ORB versioning info is only in the core ORB. +- repIdUtil +- = RepositoryIdFactory.getRepIdUtility(orb); +- repIdStrs +- = RepositoryIdFactory.getRepIdStringsFactory(orb); +- } else { +- // Get the latest versions +- repIdUtil = RepositoryIdFactory.getRepIdUtility(); +- repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); +- } ++ repIdUtil = RepositoryIdFactory.getRepIdUtility(); ++ repIdStrs = RepositoryIdFactory.getRepIdStringsFactory(); + } + + public BufferManagerWrite getBufferManager() +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/interceptors/ClientRequestInfoImpl.java +--- a/src/share/classes/com/sun/corba/ee/impl/interceptors/ClientRequestInfoImpl.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/interceptors/ClientRequestInfoImpl.java Mon Jul 06 12:05:55 2009 -0700 +@@ -41,36 +41,22 @@ + + import org.omg.CORBA.Any; + import org.omg.CORBA.BAD_INV_ORDER; +-import org.omg.CORBA.BAD_PARAM; +-import org.omg.CORBA.CompletionStatus; + import org.omg.CORBA.Context; + import org.omg.CORBA.ContextList; + import org.omg.CORBA.CTX_RESTRICT_SCOPE; + import org.omg.CORBA.ExceptionList; +-import org.omg.CORBA.LocalObject; + import org.omg.CORBA.NamedValue; +-import org.omg.CORBA.NO_IMPLEMENT; +-import org.omg.CORBA.NO_RESOURCES; + import org.omg.CORBA.NVList; + import org.omg.CORBA.Object; +-import org.omg.CORBA.ParameterMode; + import org.omg.CORBA.Policy; + import org.omg.CORBA.SystemException; + import org.omg.CORBA.TypeCode; +-import org.omg.CORBA.INTERNAL; +-import org.omg.CORBA.UserException; + import org.omg.CORBA.portable.ApplicationException; +-import org.omg.CORBA.portable.InputStream; + import com.sun.corba.ee.spi.servicecontext.ServiceContexts; +-import com.sun.corba.ee.spi.servicecontext.UnknownServiceContext; + + import org.omg.IOP.ServiceContext; +-import org.omg.IOP.ServiceContextHelper; + import org.omg.IOP.TaggedProfile; +-import org.omg.IOP.TaggedProfileHelper; + import org.omg.IOP.TaggedComponent; +-import org.omg.IOP.TaggedComponentHelper; +-import org.omg.IOP.TAG_INTERNET_IOP; + import org.omg.Dynamic.Parameter; + import org.omg.PortableInterceptor.ClientRequestInfo; + import org.omg.PortableInterceptor.LOCATION_FORWARD; +@@ -83,18 +69,15 @@ + + import com.sun.corba.ee.spi.ior.IOR; + import com.sun.corba.ee.spi.ior.iiop.IIOPProfileTemplate; +-import com.sun.corba.ee.spi.ior.iiop.GIOPVersion; + import com.sun.corba.ee.spi.orb.ORB; + import com.sun.corba.ee.spi.protocol.CorbaMessageMediator; ++import com.sun.corba.ee.spi.protocol.RetryType; + import com.sun.corba.ee.spi.transport.CorbaContactInfo; + import com.sun.corba.ee.spi.transport.CorbaContactInfoList; + import com.sun.corba.ee.spi.transport.CorbaContactInfoListIterator; + +-import com.sun.corba.ee.impl.encoding.CDROutputStream; +-import com.sun.corba.ee.impl.encoding.CDRInputStream_1_0; + import com.sun.corba.ee.impl.orbutil.ORBUtility; + import com.sun.corba.ee.impl.protocol.CorbaInvocationInfo; +-import com.sun.corba.ee.impl.util.RepositoryId; + + /** + * Implementation of the ClientRequestInfo interface as specified in +@@ -122,7 +105,7 @@ + + // The current retry request status. True if this request is being + // retried and this info object is to be reused, or false otherwise. +- private boolean retryRequest; ++ private RetryType retryRequest; + + // The number of times this info object has been (re)used. This is + // incremented every time a request is retried, and decremented every +@@ -168,40 +151,51 @@ + * Reset the info object so that it can be reused for a retry, + * for example. + */ ++ @Override + void reset() { +- super.reset(); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "reset" ) ; ++ } + +- // Please keep these in the same order that they're declared above. +- +- retryRequest = false; ++ try { ++ super.reset(); + +- // Do not reset entryCount because we need to know when to pop this +- // from the stack. ++ // Please keep these in the same order that they're declared above. ++ ++ retryRequest = RetryType.NONE; + +- request = null; +- diiInitiate = false; +- messageMediator = null; ++ // Do not reset entryCount because we need to know when to pop this ++ // from the stack. + +- // Clear cached attributes: +- cachedTargetObject = null; +- cachedEffectiveTargetObject = null; +- cachedArguments = null; +- cachedExceptions = null; +- cachedContexts = null; +- cachedOperationContext = null; +- cachedReceivedExceptionId = null; +- cachedResult = null; +- cachedReceivedException = null; +- cachedEffectiveProfile = null; +- cachedRequestServiceContexts = null; +- cachedReplyServiceContexts = null; +- cachedEffectiveComponents = null; ++ request = null; ++ diiInitiate = false; ++ messageMediator = null; + +- piCurrentPushed = false; ++ // Clear cached attributes: ++ cachedTargetObject = null; ++ cachedEffectiveTargetObject = null; ++ cachedArguments = null; ++ cachedExceptions = null; ++ cachedContexts = null; ++ cachedOperationContext = null; ++ cachedReceivedExceptionId = null; ++ cachedResult = null; ++ cachedReceivedException = null; ++ cachedEffectiveProfile = null; ++ cachedRequestServiceContexts = null; ++ cachedReplyServiceContexts = null; ++ cachedEffectiveComponents = null; + +- startingPointCall = CALL_SEND_REQUEST; +- endingPointCall = CALL_RECEIVE_REPLY; ++ piCurrentPushed = false; + ++ startingPointCall = CALL_SEND_REQUEST; ++ endingPointCall = CALL_RECEIVE_REPLY; ++ ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -286,15 +280,25 @@ + * The object which the client called to perform the operation. + */ + public org.omg.CORBA.Object target (){ +- // access is currently valid for all states: +- //checkAccess( MID_TARGET ); +- if (cachedTargetObject == null) { +- CorbaContactInfo corbaContactInfo = (CorbaContactInfo) +- messageMediator.getContactInfo(); +- cachedTargetObject = +- iorToObject(corbaContactInfo.getTargetIOR()); +- } +- return cachedTargetObject; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "target" ) ; ++ } ++ ++ try { ++ // access is currently valid for all states: ++ //checkAccess( MID_TARGET ); ++ if (cachedTargetObject == null) { ++ CorbaContactInfo corbaContactInfo = (CorbaContactInfo) ++ messageMediator.getContactInfo(); ++ cachedTargetObject = ++ iorToObject(corbaContactInfo.getTargetIOR()); ++ } ++ return cachedTargetObject; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -304,21 +308,31 @@ + * remain unchanged. + */ + public org.omg.CORBA.Object effective_target() { +- // access is currently valid for all states: +- //checkAccess( MID_EFFECTIVE_TARGET ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "effective_target" ) ; ++ } + +- // Note: This is not necessarily the same as locatedIOR. +- // Reason: See the way we handle COMM_FAILURES in +- // ClientRequestDispatcher.createRequest, v1.32 ++ try { ++ // access is currently valid for all states: ++ //checkAccess( MID_EFFECTIVE_TARGET ); + +- if (cachedEffectiveTargetObject == null) { +- CorbaContactInfo corbaContactInfo = (CorbaContactInfo) +- messageMediator.getContactInfo(); +- // REVISIT - get through chain like getLocatedIOR helper below. +- cachedEffectiveTargetObject = +- iorToObject(corbaContactInfo.getEffectiveTargetIOR()); +- } +- return cachedEffectiveTargetObject; ++ // Note: This is not necessarily the same as locatedIOR. ++ // Reason: See the way we handle COMM_FAILURES in ++ // ClientRequestDispatcher.createRequest, v1.32 ++ ++ if (cachedEffectiveTargetObject == null) { ++ CorbaContactInfo corbaContactInfo = (CorbaContactInfo) ++ messageMediator.getContactInfo(); ++ // REVISIT - get through chain like getLocatedIOR helper below. ++ cachedEffectiveTargetObject = ++ iorToObject(corbaContactInfo.getEffectiveTargetIOR()); ++ } ++ return cachedEffectiveTargetObject; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -328,68 +342,98 @@ + * profile. + */ + public TaggedProfile effective_profile (){ +- // access is currently valid for all states: +- //checkAccess( MID_EFFECTIVE_PROFILE ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "effective_profile" ) ; ++ } + +- if( cachedEffectiveProfile == null ) { +- CorbaContactInfo corbaContactInfo = (CorbaContactInfo) +- messageMediator.getContactInfo(); +- cachedEffectiveProfile = +- corbaContactInfo.getEffectiveProfile().getIOPProfile(); +- } ++ try { ++ // access is currently valid for all states: ++ //checkAccess( MID_EFFECTIVE_PROFILE ); + +- // Good citizen: In the interest of efficiency, we assume interceptors +- // will not modify the returned TaggedProfile in any way so we need +- // not make a deep copy of it. ++ if( cachedEffectiveProfile == null ) { ++ CorbaContactInfo corbaContactInfo = (CorbaContactInfo) ++ messageMediator.getContactInfo(); ++ cachedEffectiveProfile = ++ corbaContactInfo.getEffectiveProfile().getIOPProfile(); ++ } + +- return cachedEffectiveProfile; ++ // Good citizen: In the interest of efficiency, we assume interceptors ++ // will not modify the returned TaggedProfile in any way so we need ++ // not make a deep copy of it. ++ ++ return cachedEffectiveProfile; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * Contains the exception to be returned to the client. + */ + public Any received_exception (){ +- checkAccess( MID_RECEIVED_EXCEPTION ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "received_exception" ) ; ++ } + +- if( cachedReceivedException == null ) { +- cachedReceivedException = exceptionToAny( exception ); +- } ++ try { ++ checkAccess( MID_RECEIVED_EXCEPTION ); + +- // Good citizen: In the interest of efficiency, we assume interceptors +- // will not modify the returned Any in any way so we need +- // not make a deep copy of it. ++ if( cachedReceivedException == null ) { ++ cachedReceivedException = exceptionToAny( exception ); ++ } + +- return cachedReceivedException; ++ // Good citizen: In the interest of efficiency, we assume interceptors ++ // will not modify the returned Any in any way so we need ++ // not make a deep copy of it. ++ ++ return cachedReceivedException; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * The CORBA::RepositoryId of the exception to be returned to the client. + */ + public String received_exception_id (){ +- checkAccess( MID_RECEIVED_EXCEPTION_ID ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "received_exception_id" ) ; ++ } + +- if( cachedReceivedExceptionId == null ) { +- String result = null; +- +- if( exception == null ) { +- // Note: exception should never be null here since we will +- // throw a BAD_INV_ORDER if this is not called from +- // receive_exception. +- throw wrapper.exceptionWasNull() ; +- } else if( exception instanceof SystemException ) { +- String name = exception.getClass().getName(); +- result = ORBUtility.repositoryIdOf(name); +- } else if( exception instanceof ApplicationException ) { +- result = ((ApplicationException)exception).getId(); +- } ++ try { ++ checkAccess( MID_RECEIVED_EXCEPTION_ID ); + +- // _REVISIT_ We need to be able to handle a UserException in the +- // DII case. How do we extract the ID from a UserException? +- +- cachedReceivedExceptionId = result; +- } ++ if( cachedReceivedExceptionId == null ) { ++ String result = null; ++ ++ if( exception == null ) { ++ // Note: exception should never be null here since we will ++ // throw a BAD_INV_ORDER if this is not called from ++ // receive_exception. ++ throw wrapper.exceptionWasNull() ; ++ } else if( exception instanceof SystemException ) { ++ String name = exception.getClass().getName(); ++ result = ORBUtility.repositoryIdOf(name); ++ } else if( exception instanceof ApplicationException ) { ++ result = ((ApplicationException)exception).getId(); ++ } + +- return cachedReceivedExceptionId; ++ // _REVISIT_ We need to be able to handle a UserException in the ++ // DII case. How do we extract the ID from a UserException? ++ ++ cachedReceivedExceptionId = result; ++ } ++ ++ return cachedReceivedExceptionId; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -399,9 +443,19 @@ + * returns (get_effective_component should be called instead). + */ + public TaggedComponent get_effective_component (int id){ +- checkAccess( MID_GET_EFFECTIVE_COMPONENT ); +- +- return get_effective_components( id )[0]; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "get_effective_component" ) ; ++ } ++ ++ try { ++ checkAccess( MID_GET_EFFECTIVE_COMPONENT ); ++ ++ return get_effective_components( id )[0]; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -409,54 +463,74 @@ + * selected for this request. + */ + public TaggedComponent[] get_effective_components (int id){ +- checkAccess( MID_GET_EFFECTIVE_COMPONENTS ); +- TaggedComponent[] result = null; +- boolean justCreatedCache = false; +- +- if( cachedEffectiveComponents == null ) { +- cachedEffectiveComponents = new HashMap(); +- justCreatedCache = true; +- } else { +- // Look in cache: +- result = cachedEffectiveComponents.get( id ); +- } +- +- // null could mean we cached null or not in cache. +- if( (result == null) && +- (justCreatedCache || +- !cachedEffectiveComponents.containsKey( id ) ) ) +- { +- // Not in cache. Get it from the profile: +- CorbaContactInfo corbaContactInfo = (CorbaContactInfo) +- messageMediator.getContactInfo(); +- IIOPProfileTemplate ptemp = +- (IIOPProfileTemplate)corbaContactInfo.getEffectiveProfile(). +- getTaggedProfileTemplate(); +- result = ptemp.getIOPComponents(myORB, id); +- cachedEffectiveComponents.put( id, result ); +- } +- +- // As per ptc/00-08-06, section 21.3.13.6., If not found, raise +- // BAD_PARAM with minor code INVALID_COMPONENT_ID. +- if( (result == null) || (result.length == 0) ) { +- throw stdWrapper.invalidComponentId( id ) ; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "get_effective_components" ) ; + } + +- // Good citizen: In the interest of efficiency, we will assume +- // interceptors will not modify the returned TaggedCompoent[], or +- // the TaggedComponents inside of it. Otherwise, we would need to +- // clone the array and make a deep copy of its contents. +- +- return result; ++ try { ++ checkAccess( MID_GET_EFFECTIVE_COMPONENTS ); ++ TaggedComponent[] result = null; ++ boolean justCreatedCache = false; ++ ++ if( cachedEffectiveComponents == null ) { ++ cachedEffectiveComponents = new HashMap(); ++ justCreatedCache = true; ++ } else { ++ // Look in cache: ++ result = cachedEffectiveComponents.get( id ); ++ } ++ ++ // null could mean we cached null or not in cache. ++ if( (result == null) && ++ (justCreatedCache || ++ !cachedEffectiveComponents.containsKey( id ) ) ) ++ { ++ // Not in cache. Get it from the profile: ++ CorbaContactInfo corbaContactInfo = (CorbaContactInfo) ++ messageMediator.getContactInfo(); ++ IIOPProfileTemplate ptemp = ++ (IIOPProfileTemplate)corbaContactInfo.getEffectiveProfile(). ++ getTaggedProfileTemplate(); ++ result = ptemp.getIOPComponents(myORB, id); ++ cachedEffectiveComponents.put( id, result ); ++ } ++ ++ // As per ptc/00-08-06, section 21.3.13.6., If not found, raise ++ // BAD_PARAM with minor code INVALID_COMPONENT_ID. ++ if( (result == null) || (result.length == 0) ) { ++ throw stdWrapper.invalidComponentId( id ) ; ++ } ++ ++ // Good citizen: In the interest of efficiency, we will assume ++ // interceptors will not modify the returned TaggedCompoent[], or ++ // the TaggedComponents inside of it. Otherwise, we would need to ++ // clone the array and make a deep copy of its contents. ++ ++ return result; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * Returns the given policy in effect for this operation. + */ + public Policy get_request_policy (int type){ +- checkAccess( MID_GET_REQUEST_POLICY ); +- // _REVISIT_ Our ORB is not policy-based at this time. +- throw wrapper.piOrbNotPolicyBased() ; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "get_request_policy" ) ; ++ } ++ ++ try { ++ checkAccess( MID_GET_REQUEST_POLICY ); ++ // _REVISIT_ Our ORB is not policy-based at this time. ++ throw wrapper.piOrbNotPolicyBased() ; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -468,16 +542,26 @@ + public void add_request_service_context (ServiceContext service_context, + boolean replace) + { +- checkAccess( MID_ADD_REQUEST_SERVICE_CONTEXT ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "add_request_service_context" ) ; ++ } + +- if( cachedRequestServiceContexts == null ) { +- cachedRequestServiceContexts = +- new HashMap(); +- } ++ try { ++ checkAccess( MID_ADD_REQUEST_SERVICE_CONTEXT ); + +- addServiceContext( cachedRequestServiceContexts, +- messageMediator.getRequestServiceContexts(), +- service_context, replace ); ++ if( cachedRequestServiceContexts == null ) { ++ cachedRequestServiceContexts = ++ new HashMap(); ++ } ++ ++ addServiceContext( cachedRequestServiceContexts, ++ messageMediator.getRequestServiceContexts(), ++ service_context, replace ); ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + // NOTE: When adding a method, be sure to: +@@ -517,6 +601,7 @@ + return messageMediator.getOperationName(); + } + ++ @Override + public String toString() { + return "ClientRequestInfoImpl[operation=" + + operation() + "]" ; +@@ -526,175 +611,225 @@ + * See RequestInfoImpl for javadoc. + */ + public Parameter[] arguments (){ +- checkAccess( MID_ARGUMENTS ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "arguments" ) ; ++ } + +- if( cachedArguments == null ) { +- if( request == null ) { +- throw stdWrapper.piOperationNotSupported1() ; +- } ++ try { ++ checkAccess( MID_ARGUMENTS ); + +- // If it is DII request then get the arguments from the DII req +- // and convert that into parameters. +- cachedArguments = nvListToParameterArray( request.arguments() ); +- } ++ if( cachedArguments == null ) { ++ if( request == null ) { ++ throw stdWrapper.piOperationNotSupported1() ; ++ } + +- // Good citizen: In the interest of efficiency, we assume +- // interceptors will be "good citizens" in that they will not +- // modify the contents of the Parameter[] array. We also assume +- // they will not change the values of the containing Anys. ++ // If it is DII request then get the arguments from the DII req ++ // and convert that into parameters. ++ cachedArguments = nvListToParameterArray( request.arguments() ); ++ } + +- return cachedArguments; ++ // Good citizen: In the interest of efficiency, we assume ++ // interceptors will be "good citizens" in that they will not ++ // modify the contents of the Parameter[] array. We also assume ++ // they will not change the values of the containing Anys. ++ ++ return cachedArguments; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * See RequestInfoImpl for javadoc. + */ + public TypeCode[] exceptions (){ +- checkAccess( MID_EXCEPTIONS ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "exceptions" ) ; ++ } + +- if( cachedExceptions == null ) { +- if( request == null ) { +- throw stdWrapper.piOperationNotSupported2() ; +- } ++ try { ++ checkAccess( MID_EXCEPTIONS ); + +- // Get the list of exceptions from DII request data, If there are +- // no exceptions raised then this method will return null. +- ExceptionList excList = request.exceptions( ); +- int count = excList.count(); +- TypeCode[] excTCList = new TypeCode[count]; +- try { +- for( int i = 0; i < count; i++ ) { +- excTCList[i] = excList.item( i ); +- } +- } catch( Exception e ) { +- throw wrapper.exceptionInExceptions( e ) ; +- } ++ if( cachedExceptions == null ) { ++ if( request == null ) { ++ throw stdWrapper.piOperationNotSupported2() ; ++ } + +- cachedExceptions = excTCList; +- } ++ // Get the list of exceptions from DII request data, If there are ++ // no exceptions raised then this method will return null. ++ ExceptionList excList = request.exceptions( ); ++ int count = excList.count(); ++ TypeCode[] excTCList = new TypeCode[count]; ++ try { ++ for( int i = 0; i < count; i++ ) { ++ excTCList[i] = excList.item( i ); ++ } ++ } catch( Exception e ) { ++ throw wrapper.exceptionInExceptions( e ) ; ++ } + +- // Good citizen: In the interest of efficiency, we assume +- // interceptors will be "good citizens" in that they will not +- // modify the contents of the TypeCode[] array. We also assume +- // they will not change the values of the containing TypeCodes. ++ cachedExceptions = excTCList; ++ } + +- return cachedExceptions; ++ // Good citizen: In the interest of efficiency, we assume ++ // interceptors will be "good citizens" in that they will not ++ // modify the contents of the TypeCode[] array. We also assume ++ // they will not change the values of the containing TypeCodes. ++ ++ return cachedExceptions; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * See RequestInfoImpl for javadoc. + */ + public String[] contexts (){ +- checkAccess( MID_CONTEXTS ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "contexts" ) ; ++ } + +- if( cachedContexts == null ) { +- if( request == null ) { +- throw stdWrapper.piOperationNotSupported3() ; +- } ++ try { ++ checkAccess( MID_CONTEXTS ); + +- // Get the list of contexts from DII request data, If there are +- // no contexts then this method will return null. +- ContextList ctxList = request.contexts( ); +- int count = ctxList.count(); +- String[] ctxListToReturn = new String[count]; +- try { +- for( int i = 0; i < count; i++ ) { +- ctxListToReturn[i] = ctxList.item( i ); +- } +- } catch( Exception e ) { +- throw wrapper.exceptionInContexts( e ) ; +- } ++ if( cachedContexts == null ) { ++ if( request == null ) { ++ throw stdWrapper.piOperationNotSupported3() ; ++ } + +- cachedContexts = ctxListToReturn; +- } ++ // Get the list of contexts from DII request data, If there are ++ // no contexts then this method will return null. ++ ContextList ctxList = request.contexts( ); ++ int count = ctxList.count(); ++ String[] ctxListToReturn = new String[count]; ++ try { ++ for( int i = 0; i < count; i++ ) { ++ ctxListToReturn[i] = ctxList.item( i ); ++ } ++ } catch( Exception e ) { ++ throw wrapper.exceptionInContexts( e ) ; ++ } + +- // Good citizen: In the interest of efficiency, we assume +- // interceptors will be "good citizens" in that they will not +- // modify the contents of the String[] array. ++ cachedContexts = ctxListToReturn; ++ } + +- return cachedContexts; ++ // Good citizen: In the interest of efficiency, we assume ++ // interceptors will be "good citizens" in that they will not ++ // modify the contents of the String[] array. ++ ++ return cachedContexts; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * See RequestInfoImpl for javadoc. + */ + public String[] operation_context (){ +- checkAccess( MID_OPERATION_CONTEXT ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "operation_context" ) ; ++ } + +- if( cachedOperationContext == null ) { +- if( request == null ) { +- throw stdWrapper.piOperationNotSupported4() ; +- } ++ try { ++ checkAccess( MID_OPERATION_CONTEXT ); + +- // Get the list of contexts from DII request data, If there are +- // no contexts then this method will return null. +- Context ctx = request.ctx( ); +- // _REVISIT_ The API for get_values is not compliant with the spec, +- // Revisit this code once it's fixed. +- // _REVISIT_ Our ORB doesn't support Operation Context, This code +- // will not be excerscised until it's supported. +- // The first parameter in get_values is the start_scope which +- // if blank makes it as a global scope. +- // The second parameter is op_flags which is set to RESTRICT_SCOPE +- // As there is only one defined in the spec. +- // The Third param is the pattern which is '*' requiring it to +- // get all the contexts. +- NVList nvList = ctx.get_values( "", CTX_RESTRICT_SCOPE.value,"*" ); +- String[] context = new String[(nvList.count() * 2) ]; +- if( ( nvList != null ) &&( nvList.count() != 0 ) ) { +- // The String[] array will contain Name and Value for each +- // context and hence double the size in the array. +- int index = 0; +- for( int i = 0; i < nvList.count(); i++ ) { +- NamedValue nv; +- try { +- nv = nvList.item( i ); +- } +- catch (Exception e ) { +- return (String[]) null; +- } +- context[index] = nv.name(); +- index++; +- context[index] = nv.value().extract_string(); +- index++; +- } +- } ++ if( cachedOperationContext == null ) { ++ if( request == null ) { ++ throw stdWrapper.piOperationNotSupported4() ; ++ } + +- cachedOperationContext = context; +- } ++ // Get the list of contexts from DII request data, If there are ++ // no contexts then this method will return null. ++ Context ctx = request.ctx( ); ++ // _REVISIT_ The API for get_values is not compliant with the spec, ++ // Revisit this code once it's fixed. ++ // _REVISIT_ Our ORB doesn't support Operation Context, This code ++ // will not be excerscised until it's supported. ++ // The first parameter in get_values is the start_scope which ++ // if blank makes it as a global scope. ++ // The second parameter is op_flags which is set to RESTRICT_SCOPE ++ // As there is only one defined in the spec. ++ // The Third param is the pattern which is '*' requiring it to ++ // get all the contexts. ++ NVList nvList = ctx.get_values( "", CTX_RESTRICT_SCOPE.value,"*" ); ++ String[] context = new String[(nvList.count() * 2) ]; ++ if( ( nvList != null ) &&( nvList.count() != 0 ) ) { ++ // The String[] array will contain Name and Value for each ++ // context and hence double the size in the array. ++ int index = 0; ++ for( int i = 0; i < nvList.count(); i++ ) { ++ NamedValue nv; ++ try { ++ nv = nvList.item( i ); ++ } ++ catch (Exception e ) { ++ return (String[]) null; ++ } ++ context[index] = nv.name(); ++ index++; ++ context[index] = nv.value().extract_string(); ++ index++; ++ } ++ } + +- // Good citizen: In the interest of efficiency, we assume +- // interceptors will be "good citizens" in that they will not +- // modify the contents of the String[] array. ++ cachedOperationContext = context; ++ } + +- return cachedOperationContext; ++ // Good citizen: In the interest of efficiency, we assume ++ // interceptors will be "good citizens" in that they will not ++ // modify the contents of the String[] array. ++ ++ return cachedOperationContext; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * See RequestInfoImpl for javadoc. + */ + public Any result (){ +- checkAccess( MID_RESULT ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "result" ) ; ++ } + +- if( cachedResult == null ) { +- if( request == null ) { +- throw stdWrapper.piOperationNotSupported5() ; +- } +- // Get the result from the DII request data. +- NamedValue nvResult = request.result( ); ++ try { ++ checkAccess( MID_RESULT ); + +- if( nvResult == null ) { +- throw wrapper.piDiiResultIsNull() ; +- } ++ if( cachedResult == null ) { ++ if( request == null ) { ++ throw stdWrapper.piOperationNotSupported5() ; ++ } ++ // Get the result from the DII request data. ++ NamedValue nvResult = request.result( ); + +- cachedResult = nvResult.value(); +- } ++ if( nvResult == null ) { ++ throw wrapper.piDiiResultIsNull() ; ++ } + +- // Good citizen: In the interest of efficiency, we assume that +- // interceptors will not modify the contents of the result Any. +- // Otherwise, we would need to create a deep copy of the Any. ++ cachedResult = nvResult.value(); ++ } + +- return cachedResult; ++ // Good citizen: In the interest of efficiency, we assume that ++ // interceptors will not modify the contents of the result Any. ++ // Otherwise, we would need to create a deep copy of the Any. ++ ++ return cachedResult; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -710,60 +845,99 @@ + * See RequestInfoImpl for javadoc. + */ + public Object forward_reference (){ +- checkAccess( MID_FORWARD_REFERENCE ); +- // Check to make sure we are in LOCATION_FORWARD +- // state as per ptc/00-08-06, table 21-1 +- // footnote 2. +- if( replyStatus != LOCATION_FORWARD.value ) { +- throw stdWrapper.invalidPiCall1() ; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "forward_reference" ) ; + } + +- // Do not cache this value since if an interceptor raises +- // forward request then the next interceptor in the +- // list should see the new value. +- IOR ior = getLocatedIOR(); +- return iorToObject(ior); ++ try { ++ checkAccess( MID_FORWARD_REFERENCE ); ++ // Check to make sure we are in LOCATION_FORWARD ++ // state as per ptc/00-08-06, table 21-1 ++ // footnote 2. ++ if( replyStatus != LOCATION_FORWARD.value ) { ++ throw stdWrapper.invalidPiCall1() ; ++ } ++ ++ // Do not cache this value since if an interceptor raises ++ // forward request then the next interceptor in the ++ // list should see the new value. ++ IOR ior = getLocatedIOR(); ++ return iorToObject(ior); ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- private IOR getLocatedIOR() +- { +- IOR ior; +- CorbaContactInfoList contactInfoList = (CorbaContactInfoList) +- messageMediator.getContactInfo().getContactInfoList(); +- ior = contactInfoList.getEffectiveTargetIOR(); +- return ior; ++ private IOR getLocatedIOR() { ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "getLocatedIOR" ) ; ++ } ++ ++ try { ++ IOR ior; ++ CorbaContactInfoList contactInfoList = (CorbaContactInfoList) ++ messageMediator.getContactInfo().getContactInfoList(); ++ ior = contactInfoList.getEffectiveTargetIOR(); ++ return ior; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + // Used to be protected. public for IIOPFailoverManagerImpl. +- public void setLocatedIOR(IOR ior) +- { +- ORB orb = (ORB) messageMediator.getBroker(); ++ public void setLocatedIOR(IOR ior) { + +- CorbaContactInfoListIterator iterator = (CorbaContactInfoListIterator) +- ((CorbaInvocationInfo)orb.getInvocationInfo()) +- .getContactInfoListIterator(); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "setLocatedIOR" ) ; ++ } + +- // REVISIT - this most likely causes reportRedirect to happen twice. +- // Once here and once inside the request dispatcher. +- iterator.reportRedirect( +- (CorbaContactInfo)messageMediator.getContactInfo(), +- ior); ++ try { ++ ORB orb = (ORB) messageMediator.getBroker(); ++ ++ CorbaContactInfoListIterator iterator = (CorbaContactInfoListIterator) ++ ((CorbaInvocationInfo)orb.getInvocationInfo()) ++ .getContactInfoListIterator(); ++ ++ // REVISIT - this most likely causes reportRedirect to happen twice. ++ // Once here and once inside the request dispatcher. ++ iterator.reportRedirect( ++ (CorbaContactInfo)messageMediator.getContactInfo(), ++ ior); ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * See RequestInfoImpl for javadoc. + */ + public org.omg.IOP.ServiceContext get_request_service_context( int id ) { +- checkAccess( MID_GET_REQUEST_SERVICE_CONTEXT ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "get_request_service_context" ) ; ++ } + +- if( cachedRequestServiceContexts == null ) { +- cachedRequestServiceContexts = +- new HashMap(); +- } ++ try { ++ checkAccess( MID_GET_REQUEST_SERVICE_CONTEXT ); + +- return getServiceContext(cachedRequestServiceContexts, +- messageMediator.getRequestServiceContexts(), +- id); ++ if( cachedRequestServiceContexts == null ) { ++ cachedRequestServiceContexts = ++ new HashMap(); ++ } ++ ++ return getServiceContext(cachedRequestServiceContexts, ++ messageMediator.getRequestServiceContexts(), ++ id); ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -771,35 +945,45 @@ + * TBD_BP is raised. + */ + public org.omg.IOP.ServiceContext get_reply_service_context( int id ) { +- checkAccess( MID_GET_REPLY_SERVICE_CONTEXT ); ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "get_reply_service_context" ) ; ++ } + +- if( cachedReplyServiceContexts == null ) { +- cachedReplyServiceContexts = +- new HashMap(); +- } ++ try { ++ checkAccess( MID_GET_REPLY_SERVICE_CONTEXT ); + +- // In the event this is called from a oneway, we will have no +- // response object. +- // +- // In the event this is called after a IIOPConnection.purgeCalls, +- // we will have a response object, but that object will +- // not contain a header (which would hold the service context +- // container). See bug 4624102. +- // ++ if( cachedReplyServiceContexts == null ) { ++ cachedReplyServiceContexts = ++ new HashMap(); ++ } + +- // REVISIT: getReplyHeader should not be visible here. +- if (messageMediator.getReplyHeader() != null) { +- ServiceContexts serviceContexts = +- messageMediator.getReplyServiceContexts(); +- if (serviceContexts != null) { +- return getServiceContext(cachedReplyServiceContexts, +- serviceContexts, id); +- } +- } +- // See purge calls test. The waiter is woken up by the +- // call to purge calls - but there is no reply containing +- // service contexts. +- throw stdWrapper.invalidServiceContextId() ; ++ // In the event this is called from a oneway, we will have no ++ // response object. ++ // ++ // In the event this is called after a IIOPConnection.purgeCalls, ++ // we will have a response object, but that object will ++ // not contain a header (which would hold the service context ++ // container). See bug 4624102. ++ // ++ ++ // REVISIT: getReplyHeader should not be visible here. ++ if (messageMediator.getReplyHeader() != null) { ++ ServiceContexts sctxs = ++ messageMediator.getReplyServiceContexts(); ++ if (sctxs != null) { ++ return getServiceContext(cachedReplyServiceContexts, ++ sctxs, id); ++ } ++ } ++ // See purge calls test. The waiter is woken up by the ++ // call to purge calls - but there is no reply containing ++ // service contexts. ++ throw stdWrapper.invalidServiceContextId() ; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + // +@@ -807,6 +991,7 @@ + // Override RequestInfoImpl connection to work in framework. + // + ++ @Override + public com.sun.corba.ee.spi.legacy.connection.Connection connection() + { + return (com.sun.corba.ee.spi.legacy.connection.Connection) +@@ -830,14 +1015,14 @@ + /** + * Set or reset the retry request flag. + */ +- void setRetryRequest( boolean retryRequest ) { ++ void setRetryRequest( RetryType retryRequest ) { + this.retryRequest = retryRequest; + } + + /** + * Retrieve the current retry request status. + */ +- boolean getRetryRequest() { ++ RetryType getRetryRequest() { + return this.retryRequest; + } + +@@ -845,42 +1030,109 @@ + * Increases the entry count by 1. + */ + void incrementEntryCount() { +- this.entryCount++; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "incrementEntryCount" ) ; ++ } ++ ++ try { ++ this.entryCount++; ++ if (myORB.interceptorDebugFlag) { ++ dputil.info( "entryCount", this.entryCount ) ; ++ } ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * Decreases the entry count by 1. + */ + void decrementEntryCount() { +- this.entryCount--; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "decrementEntryCount" ) ; ++ } ++ ++ try { ++ this.entryCount--; ++ if (myORB.interceptorDebugFlag) { ++ dputil.info( "entryCount", this.entryCount ) ; ++ } ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * Retrieve the current entry count + */ + int getEntryCount() { +- return this.entryCount; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "getEntryCount" ) ; ++ } ++ ++ int result = 0 ; ++ try { ++ result = this.entryCount; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit( result ) ; ++ } ++ } ++ return result ; + } + + /** + * Overridden from RequestInfoImpl. Calls the super class, then + * sets the ending point call depending on the reply status. + */ ++ @Override + protected void setReplyStatus( short replyStatus ) { +- super.setReplyStatus( replyStatus ); +- switch( replyStatus ) { +- case SUCCESSFUL.value: +- endingPointCall = CALL_RECEIVE_REPLY; +- break; +- case SYSTEM_EXCEPTION.value: +- case USER_EXCEPTION.value: +- endingPointCall = CALL_RECEIVE_EXCEPTION; +- break; +- case LOCATION_FORWARD.value: +- case TRANSPORT_RETRY.value: +- endingPointCall = CALL_RECEIVE_OTHER; +- break; ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "setReplyStatus", ++ PIHandlerImpl.getReplyStatus(replyStatus) ) ; + } ++ try { ++ super.setReplyStatus( replyStatus ); ++ switch( replyStatus ) { ++ case SUCCESSFUL.value: ++ endingPointCall = CALL_RECEIVE_REPLY; ++ break; ++ case SYSTEM_EXCEPTION.value: ++ case USER_EXCEPTION.value: ++ endingPointCall = CALL_RECEIVE_EXCEPTION; ++ break; ++ case LOCATION_FORWARD.value: ++ case TRANSPORT_RETRY.value: ++ endingPointCall = CALL_RECEIVE_OTHER; ++ break; ++ } ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } ++ } ++ ++ @Override ++ protected short getReplyStatus() { ++ if (myORB.interceptorDebugFlag) { ++ dputil.enter( "getReplyStatus" ) ; ++ } ++ ++ short result = 0 ; ++ try { ++ result = super.getReplyStatus() ; ++ } finally { ++ if (myORB.interceptorDebugFlag) { ++ dputil.exit( PIHandlerImpl.getReplyStatus( result ) ) ; ++ } ++ } ++ ++ return result ; + } + + /** +@@ -923,6 +1175,7 @@ + /** + * Overridden from RequestInfoImpl. + */ ++ @Override + protected void setException( Exception exception ) { + super.setException( exception ); + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/interceptors/InterceptorInvoker.java +--- a/src/share/classes/com/sun/corba/ee/impl/interceptors/InterceptorInvoker.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/interceptors/InterceptorInvoker.java Mon Jul 06 12:05:55 2009 -0700 +@@ -35,28 +35,20 @@ + */ + package com.sun.corba.ee.impl.interceptors; + +-import org.omg.CORBA.CompletionStatus; +-import org.omg.CORBA.INTERNAL; + import org.omg.CORBA.SystemException; +-import org.omg.CORBA.portable.Delegate; + import org.omg.PortableInterceptor.LOCATION_FORWARD; +-import org.omg.PortableInterceptor.SUCCESSFUL; + import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; +-import org.omg.PortableInterceptor.TRANSPORT_RETRY; +-import org.omg.PortableInterceptor.USER_EXCEPTION; +-import org.omg.PortableInterceptor.ClientRequestInfo; + import org.omg.PortableInterceptor.ClientRequestInterceptor; + import org.omg.PortableInterceptor.ForwardRequest; + import org.omg.PortableInterceptor.IORInterceptor; + import org.omg.PortableInterceptor.IORInterceptor_3_0; +-import org.omg.PortableInterceptor.ServerRequestInfo; + import org.omg.PortableInterceptor.ServerRequestInterceptor; + import org.omg.PortableInterceptor.ObjectReferenceTemplate; + + import com.sun.corba.ee.spi.ior.IOR; + import com.sun.corba.ee.spi.oa.ObjectAdapter; + import com.sun.corba.ee.spi.orb.ORB; +-import com.sun.corba.ee.impl.orbutil.ORBUtility; ++import com.sun.corba.ee.impl.orbutil.DprintUtil; + + /** + * Handles invocation of interceptors. Has specific knowledge of how to +@@ -69,7 +61,8 @@ + + // The ORB + private ORB orb; +- ++ private DprintUtil dputil = new DprintUtil( this ) ; ++ + // The list of interceptors to be invoked + private InterceptorList interceptorList; + +@@ -99,10 +92,6 @@ + this.current = piCurrent; + } + +- private void dprint( String msg ) { +- ORBUtility.dprint( this, msg ) ; +- } +- + /** + * Enables or disables the interceptor invoker + */ +@@ -121,100 +110,128 @@ + * @param oa The Object Adapter associated with the IOR interceptor. + */ + void objectAdapterCreated( ObjectAdapter oa ) { +- // If invocation is not yet enabled, don't do anything. +- if( enabled ) { +- // Create IORInfo object to pass to IORInterceptors: +- IORInfoImpl info = new IORInfoImpl( oa ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "objectAdapterCreated" ) ; ++ } + +- // Call each IORInterceptor: +- IORInterceptor[] iorInterceptors = +- (IORInterceptor[])interceptorList.getInterceptors( +- InterceptorList.INTERCEPTOR_TYPE_IOR ); +- int size = iorInterceptors.length; ++ try { ++ // If invocation is not yet enabled, don't do anything. ++ if( enabled ) { ++ // Create IORInfo object to pass to IORInterceptors: ++ IORInfoImpl info = new IORInfoImpl( oa ); + +- // Implementation note: +- // This loop counts backwards for greater efficiency. +- // Benchmarks have shown that counting down is more efficient +- // than counting up in Java for loops, as a compare to zero is +- // faster than a subtract and compare to zero. In this case, +- // it doesn't really matter much, but it's simply a force of habit. ++ // Call each IORInterceptor: ++ IORInterceptor[] iorInterceptors = ++ (IORInterceptor[])interceptorList.getInterceptors( ++ InterceptorList.INTERCEPTOR_TYPE_IOR ); ++ int size = iorInterceptors.length; + +- for( int i = (size - 1); i >= 0; i-- ) { +- IORInterceptor interceptor = iorInterceptors[i]; +- try { +- interceptor.establish_components( info ); +- } +- catch( Exception e ) { +- // as per PI spec (orbos/99-12-02 sec 7.2.1), if +- // establish_components throws an exception, ignore it. +- } +- } ++ // Implementation note: ++ // This loop counts backwards for greater efficiency. ++ // Benchmarks have shown that counting down is more efficient ++ // than counting up in Java for loops, as a compare to zero is ++ // faster than a subtract and compare to zero. In this case, ++ // it doesn't really matter much, but it's simply a force of habit. + +- // Change the state so that only template operations are valid +- info.makeStateEstablished() ; ++ for( int i = (size - 1); i >= 0; i-- ) { ++ IORInterceptor interceptor = iorInterceptors[i]; ++ try { ++ interceptor.establish_components( info ); ++ } ++ catch( Exception e ) { ++ // as per PI spec (orbos/99-12-02 sec 7.2.1), if ++ // establish_components throws an exception, ignore it. ++ } ++ } + +- for( int i = (size - 1); i >= 0; i-- ) { +- IORInterceptor interceptor = iorInterceptors[i]; +- if (interceptor instanceof IORInterceptor_3_0) { +- IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; +- // Note that exceptions here are NOT ignored, as per the +- // ORT spec (orbos/01-01-04) +- interceptor30.components_established( info ); +- } +- } ++ // Change the state so that only template operations are valid ++ info.makeStateEstablished() ; + +- // Change the state so that no operations are valid, +- // in case a reference to info escapes this scope. +- // This also completes the actions associated with the +- // template interceptors on this POA. +- info.makeStateDone() ; +- } ++ for( int i = (size - 1); i >= 0; i-- ) { ++ IORInterceptor interceptor = iorInterceptors[i]; ++ if (interceptor instanceof IORInterceptor_3_0) { ++ IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; ++ // Note that exceptions here are NOT ignored, as per the ++ // ORT spec (orbos/01-01-04) ++ interceptor30.components_established( info ); ++ } ++ } ++ ++ // Change the state so that no operations are valid, ++ // in case a reference to info escapes this scope. ++ // This also completes the actions associated with the ++ // template interceptors on this POA. ++ info.makeStateDone() ; ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- void adapterManagerStateChanged( int managerId, short newState ) +- { +- if (enabled) { +- IORInterceptor[] interceptors = +- (IORInterceptor[])interceptorList.getInterceptors( +- InterceptorList.INTERCEPTOR_TYPE_IOR ); +- int size = interceptors.length; ++ void adapterManagerStateChanged( int managerId, short newState ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "adapterManagedStateChanged" ) ; ++ } + +- for( int i = (size - 1); i >= 0; i-- ) { +- try { +- IORInterceptor interceptor = interceptors[i]; +- if (interceptor instanceof IORInterceptor_3_0) { +- IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; +- interceptor30.adapter_manager_state_changed( managerId, +- newState ); +- } +- } catch (Exception exc) { +- // No-op: ignore exception in this case +- } +- } +- } ++ try { ++ if (enabled) { ++ IORInterceptor[] interceptors = ++ (IORInterceptor[])interceptorList.getInterceptors( ++ InterceptorList.INTERCEPTOR_TYPE_IOR ); ++ int size = interceptors.length; ++ ++ for( int i = (size - 1); i >= 0; i-- ) { ++ try { ++ IORInterceptor interceptor = interceptors[i]; ++ if (interceptor instanceof IORInterceptor_3_0) { ++ IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; ++ interceptor30.adapter_manager_state_changed( managerId, ++ newState ); ++ } ++ } catch (Exception exc) { ++ // No-op: ignore exception in this case ++ } ++ } ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + void adapterStateChanged( ObjectReferenceTemplate[] templates, +- short newState ) +- { +- if (enabled) { +- IORInterceptor[] interceptors = +- (IORInterceptor[])interceptorList.getInterceptors( +- InterceptorList.INTERCEPTOR_TYPE_IOR ); +- int size = interceptors.length; ++ short newState ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "adapterStateChanged" ) ; ++ } + +- for( int i = (size - 1); i >= 0; i-- ) { +- try { +- IORInterceptor interceptor = interceptors[i]; +- if (interceptor instanceof IORInterceptor_3_0) { +- IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; +- interceptor30.adapter_state_changed( templates, newState ); +- } +- } catch (Exception exc) { +- // No-op: ignore exception in this case +- } +- } +- } ++ try { ++ if (enabled) { ++ IORInterceptor[] interceptors = ++ (IORInterceptor[])interceptorList.getInterceptors( ++ InterceptorList.INTERCEPTOR_TYPE_IOR ); ++ int size = interceptors.length; ++ ++ for( int i = (size - 1); i >= 0; i-- ) { ++ try { ++ IORInterceptor interceptor = interceptors[i]; ++ if (interceptor instanceof IORInterceptor_3_0) { ++ IORInterceptor_3_0 interceptor30 = (IORInterceptor_3_0)interceptor ; ++ interceptor30.adapter_state_changed( templates, newState ); ++ } ++ } catch (Exception exc) { ++ // No-op: ignore exception in this case ++ } ++ } ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -227,123 +244,123 @@ + * of info.getStartingPointCall() + */ + void invokeClientInterceptorStartingPoint( ClientRequestInfoImpl info ) { +- // If invocation is not yet enabled, don't do anything. +- if( enabled ) { +- if (orb.interceptorDebugFlag) { +- dprint( "->invokeClientInterceptorStartingPoint " + info ) ; +- } ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeClientInterceptorStartingPoint", ++ "info", info ) ; ++ } + +- try { +- // Make a a fresh slot table available to TSC in case +- // interceptors need to make out calls. +- // Client's TSC is now RSC via RequestInfo. +- current.pushSlotTable( ); +- info.setPICurrentPushed( true ); +- info.setCurrentExecutionPoint( info.EXECUTION_POINT_STARTING ); +- +- // Get all ClientRequestInterceptors: +- ClientRequestInterceptor[] clientInterceptors = +- (ClientRequestInterceptor[])interceptorList. +- getInterceptors( InterceptorList.INTERCEPTOR_TYPE_CLIENT ); +- int size = clientInterceptors.length; ++ try { ++ // If invocation is not yet enabled, don't do anything. ++ if( enabled ) { ++ try { ++ // Make a a fresh slot table available to TSC in case ++ // interceptors need to make out calls. ++ // Client's TSC is now RSC via RequestInfo. ++ current.pushSlotTable( ); ++ info.setPICurrentPushed( true ); ++ info.setCurrentExecutionPoint( info.EXECUTION_POINT_STARTING ); ++ ++ // Get all ClientRequestInterceptors: ++ ClientRequestInterceptor[] clientInterceptors = ++ (ClientRequestInterceptor[])interceptorList. ++ getInterceptors( InterceptorList.INTERCEPTOR_TYPE_CLIENT ); ++ int size = clientInterceptors.length; + +- // We will assume that all interceptors returned successfully, +- // and adjust the flowStackIndex to the appropriate value if +- // we later discover otherwise. +- int flowStackIndex = size; +- boolean continueProcessing = true; +- +- // Determine whether we are calling send_request or send_poll: +- // (This is currently commented out because our ORB does not +- // yet support the Messaging specification, so send_poll will +- // never occur. Once we have implemented messaging, this may +- // be uncommented.) +- // int startingPointCall = info.getStartingPointCall(); +- for( int i = 0; continueProcessing && (i < size); i++ ) { +- ClientRequestInterceptor cri = clientInterceptors[i] ; ++ // We will assume that all interceptors returned successfully, ++ // and adjust the flowStackIndex to the appropriate value if ++ // we later discover otherwise. ++ int flowStackIndex = size; ++ boolean continueProcessing = true; ++ ++ // Determine whether we are calling send_request or send_poll: ++ // (This is currently commented out because our ORB does not ++ // yet support the Messaging specification, so send_poll will ++ // never occur. Once we have implemented messaging, this may ++ // be uncommented.) ++ // int startingPointCall = info.getStartingPointCall(); ++ for( int i = 0; continueProcessing && (i < size); i++ ) { ++ ClientRequestInterceptor cri = clientInterceptors[i] ; + +- try { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeClientInterceptorStartingPoint: " + +- cri.name() + ".send_request" ) ; +- } ++ try { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "calling send request on", cri.name() ) ; ++ } + +- cri.send_request( info ); +- +- // Again, it is not necessary for a switch here, since +- // there is only one starting point call type (see +- // above comment). +- +- //switch( startingPointCall ) { +- //case ClientRequestInfoImpl.CALL_SEND_REQUEST: +- //clientInterceptors[i].send_request( info ); +- //break; +- //case ClientRequestInfoImpl.CALL_SEND_POLL: +- //clientInterceptors[i].send_poll( info ); +- //break; +- //} ++ cri.send_request( info ); ++ ++ // Again, it is not necessary for a switch here, since ++ // there is only one starting point call type (see ++ // above comment). ++ ++ //switch( startingPointCall ) { ++ //case ClientRequestInfoImpl.CALL_SEND_REQUEST: ++ //clientInterceptors[i].send_request( info ); ++ //break; ++ //case ClientRequestInfoImpl.CALL_SEND_POLL: ++ //clientInterceptors[i].send_poll( info ); ++ //break; ++ //} + +- } catch( ForwardRequest e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeClientInterceptorStartingPoint " +- + "ForwardRequest from " + cri.name() ) ; +- } ++ } catch( ForwardRequest e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught forward request from", cri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.2.1.), if +- // interception point throws a ForwardRequest, +- // no other Interceptors' send_request operations are +- // called. +- flowStackIndex = i; +- info.setForwardRequest( e ); +- info.setEndingPointCall( +- ClientRequestInfoImpl.CALL_RECEIVE_OTHER ); +- info.setReplyStatus( LOCATION_FORWARD.value ); +- +- updateClientRequestDispatcherForward( info ); +- +- // For some reason, using break here causes the VM on +- // NT to lose track of the value of flowStackIndex +- // after exiting the for loop. I changed this to +- // check a boolean value instead and it seems to work +- // fine. +- continueProcessing = false; +- } catch( SystemException e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeClientInterceptorStartingPoint " +- + "SystemException " + e + " from " +- + cri.name() ) ; +- } ++ // as per PI spec (orbos/99-12-02 sec 5.2.1.), if ++ // interception point throws a ForwardRequest, ++ // no other Interceptors' send_request operations are ++ // called. ++ flowStackIndex = i; ++ info.setForwardRequest( e ); ++ info.setEndingPointCall( ++ ClientRequestInfoImpl.CALL_RECEIVE_OTHER ); ++ info.setReplyStatus( LOCATION_FORWARD.value ); ++ ++ updateClientRequestDispatcherForward( info ); ++ ++ // For some reason, using break here causes the VM on ++ // NT to lose track of the value of flowStackIndex ++ // after exiting the for loop. I changed this to ++ // check a boolean value instead and it seems to work ++ // fine. ++ continueProcessing = false; ++ } catch( SystemException e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught SystemException" + e + "from" ++ + cri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.2.1.), if +- // interception point throws a SystemException, +- // no other Interceptors' send_request operations are +- // called. +- flowStackIndex = i; +- info.setEndingPointCall( +- ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION ); +- info.setReplyStatus( SYSTEM_EXCEPTION.value ); +- info.setException( e ); ++ // as per PI spec (orbos/99-12-02 sec 5.2.1.), if ++ // interception point throws a SystemException, ++ // no other Interceptors' send_request operations are ++ // called. ++ flowStackIndex = i; ++ info.setEndingPointCall( ++ ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION ); ++ info.setReplyStatus( SYSTEM_EXCEPTION.value ); ++ info.setException( e ); + +- // For some reason, using break here causes the VM on +- // NT to lose track of the value of flowStackIndex +- // after exiting the for loop. I changed this to +- // check a boolean value instead and it seems to +- // work fine. +- continueProcessing = false; +- } +- } +- +- // Remember where we left off in the flow stack: +- info.setFlowStackIndex( flowStackIndex ); +- } finally { +- if (orb.interceptorDebugFlag) { +- dprint( "<-invokeClientInterceptorStartingPoint " + info ) ; +- } +- +- // Make the SlotTable fresh for the next interception point. +- current.resetSlotTable( ); +- } +- } // end enabled check ++ // For some reason, using break here causes the VM on ++ // NT to lose track of the value of flowStackIndex ++ // after exiting the for loop. I changed this to ++ // check a boolean value instead and it seems to ++ // work fine. ++ continueProcessing = false; ++ } ++ } ++ ++ // Remember where we left off in the flow stack: ++ info.setFlowStackIndex( flowStackIndex ); ++ } finally { ++ // Make the SlotTable fresh for the next interception point. ++ current.resetSlotTable( ); ++ } ++ } // end enabled check ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + private String getClientEndMethodName( int endingPointCall ) { +@@ -363,110 +380,110 @@ + * depending on the value of info.getEndingPointCall() + */ + void invokeClientInterceptorEndingPoint( ClientRequestInfoImpl info ) { +- // If invocation is not yet enabled, don't do anything. +- if( enabled ) { +- try { +- if (orb.interceptorDebugFlag) { +- dprint( "->invokeClientInterceptorEndingPoint " + info ) ; +- } +- +- // NOTE: It is assumed someplace else prepared a +- // fresh TSC slot table. ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeClientInterceptorEndingPoint" ) ; ++ } + +- info.setCurrentExecutionPoint( info.EXECUTION_POINT_ENDING ); +- +- // Get all ClientRequestInterceptors: +- ClientRequestInterceptor[] clientInterceptors = +- (ClientRequestInterceptor[])interceptorList. +- getInterceptors( InterceptorList.INTERCEPTOR_TYPE_CLIENT ); +- int flowStackIndex = info.getFlowStackIndex(); +- +- // Determine whether we are calling receive_reply, +- // receive_exception, or receive_other: +- int endingPointCall = info.getEndingPointCall(); ++ try { ++ // If invocation is not yet enabled, don't do anything. ++ if( enabled ) { ++ try { ++ // NOTE: It is assumed someplace else prepared a ++ // fresh TSC slot table. + +- // If we would be calling RECEIVE_REPLY, but this is a +- // one-way call, override this and call receive_other: +- if( ( endingPointCall == +- ClientRequestInfoImpl.CALL_RECEIVE_REPLY ) && +- info.getIsOneWay() ) +- { +- endingPointCall = ClientRequestInfoImpl.CALL_RECEIVE_OTHER; +- info.setEndingPointCall( endingPointCall ); +- } +- +- // Only step through the interceptors whose starting points +- // have successfully returned. +- // Unlike the previous loop, this one counts backwards for a +- // reason - we must execute these in the reverse order of the +- // starting points. +- for( int i = (flowStackIndex - 1); i >= 0; i-- ) { +- ClientRequestInterceptor cri = clientInterceptors[i] ; ++ info.setCurrentExecutionPoint( info.EXECUTION_POINT_ENDING ); ++ ++ // Get all ClientRequestInterceptors: ++ ClientRequestInterceptor[] clientInterceptors = ++ (ClientRequestInterceptor[])interceptorList. ++ getInterceptors( InterceptorList.INTERCEPTOR_TYPE_CLIENT ); ++ int flowStackIndex = info.getFlowStackIndex(); ++ ++ // Determine whether we are calling receive_reply, ++ // receive_exception, or receive_other: ++ int endingPointCall = info.getEndingPointCall(); + +- try { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeClientInterceptorEndingPoint: " +- + "Interceptor " + cri.name() + "." +- + getClientEndMethodName( endingPointCall ) ) ; +- } +- +- switch( endingPointCall ) { +- case ClientRequestInfoImpl.CALL_RECEIVE_REPLY: +- cri.receive_reply( info ); +- break; +- case ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION: +- cri.receive_exception( info ); +- break; +- case ClientRequestInfoImpl.CALL_RECEIVE_OTHER: +- cri.receive_other( info ); +- break; +- } +- } catch( ForwardRequest e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeClientInterceptorEndingPoint " +- + "ForwardRequest from " + cri.name() ) ; +- } ++ // If we would be calling RECEIVE_REPLY, but this is a ++ // one-way call, override this and call receive_other: ++ if( ( endingPointCall == ++ ClientRequestInfoImpl.CALL_RECEIVE_REPLY ) && ++ info.getIsOneWay() ) ++ { ++ endingPointCall = ClientRequestInfoImpl.CALL_RECEIVE_OTHER; ++ info.setEndingPointCall( endingPointCall ); ++ } ++ ++ // Only step through the interceptors whose starting points ++ // have successfully returned. ++ // Unlike the previous loop, this one counts backwards for a ++ // reason - we must execute these in the reverse order of the ++ // starting points. ++ for( int i = (flowStackIndex - 1); i >= 0; i-- ) { ++ ClientRequestInterceptor cri = clientInterceptors[i] ; + +- // as per PI spec (orbos/99-12-02 sec 5.2.1.), if +- // interception point throws a ForwardException, +- // ending point call changes to receive_other. +- endingPointCall = +- ClientRequestInfoImpl.CALL_RECEIVE_OTHER; +- info.setEndingPointCall( endingPointCall ); +- info.setReplyStatus( LOCATION_FORWARD.value ); +- info.setForwardRequest( e ); +- updateClientRequestDispatcherForward( info ); +- } catch( SystemException e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeClientInterceptorEndingPoint " +- + "SystemException " + e + " from " +- + cri.name() ) ; +- } ++ try { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "Interceptor" + cri.name() + "method" ++ + getClientEndMethodName( endingPointCall ) ) ; ++ } ++ ++ switch( endingPointCall ) { ++ case ClientRequestInfoImpl.CALL_RECEIVE_REPLY: ++ cri.receive_reply( info ); ++ break; ++ case ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION: ++ cri.receive_exception( info ); ++ break; ++ case ClientRequestInfoImpl.CALL_RECEIVE_OTHER: ++ cri.receive_other( info ); ++ break; ++ } ++ } catch( ForwardRequest e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught ForwardRequest from " ++ + cri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.2.1.), if +- // interception point throws a SystemException, +- // ending point call changes to receive_exception. +- endingPointCall = +- ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION; +- info.setEndingPointCall( endingPointCall ); +- info.setReplyStatus( SYSTEM_EXCEPTION.value ); +- info.setException( e ); +- } +- } +- } finally { +- if (orb.interceptorDebugFlag) { +- dprint( "<-invokeClientInterceptorEndingPoint " + info ) ; +- } ++ // as per PI spec (orbos/99-12-02 sec 5.2.1.), if ++ // interception point throws a ForwardException, ++ // ending point call changes to receive_other. ++ endingPointCall = ++ ClientRequestInfoImpl.CALL_RECEIVE_OTHER; ++ info.setEndingPointCall( endingPointCall ); ++ info.setReplyStatus( LOCATION_FORWARD.value ); ++ info.setForwardRequest( e ); ++ updateClientRequestDispatcherForward( info ); ++ } catch( SystemException e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught SystemException" + e ++ + "from" + cri.name() ) ; ++ } + +- // See doc for setPICurrentPushed as to why this is necessary. +- // Check info for null in case errors happen before initiate. +- if (info != null && info.isPICurrentPushed()) { +- current.popSlotTable( ); +- // After the pop, original client's TSC slot table +- // remains avaiable via PICurrent. +- } +- } +- } // end enabled check ++ // as per PI spec (orbos/99-12-02 sec 5.2.1.), if ++ // interception point throws a SystemException, ++ // ending point call changes to receive_exception. ++ endingPointCall = ++ ClientRequestInfoImpl.CALL_RECEIVE_EXCEPTION; ++ info.setEndingPointCall( endingPointCall ); ++ info.setReplyStatus( SYSTEM_EXCEPTION.value ); ++ info.setException( e ); ++ } ++ } ++ } finally { ++ // See doc for setPICurrentPushed as to why this is necessary. ++ // Check info for null in case errors happen before initiate. ++ if (info != null && info.isPICurrentPushed()) { ++ current.popSlotTable( ); ++ // After the pop, original client's TSC slot table ++ // remains avaiable via PICurrent. ++ } ++ } ++ } // end enabled check ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -478,113 +495,113 @@ + * Invokes receive_request_service_context interception points. + */ + void invokeServerInterceptorStartingPoint( ServerRequestInfoImpl info ) { +- // If invocation is not yet enabled, don't do anything. +- if( enabled ) { +- try { +- if (orb.interceptorDebugFlag) { +- dprint( "->invokeServerInterceptorStartingPoint " + info ) ; +- } ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokerServerInterceptorStartingPoint", ++ "info", info ) ; ++ } + +- // Make a fresh slot table for RSC. +- current.pushSlotTable(); +- info.setSlotTable(current.getSlotTable()); ++ try { ++ // If invocation is not yet enabled, don't do anything. ++ if( enabled ) { ++ try { ++ // Make a fresh slot table for RSC. ++ current.pushSlotTable(); ++ info.setSlotTable(current.getSlotTable()); + +- // Make a fresh slot table for TSC in case +- // interceptors need to make out calls. +- current.pushSlotTable( ); ++ // Make a fresh slot table for TSC in case ++ // interceptors need to make out calls. ++ current.pushSlotTable( ); + +- info.setCurrentExecutionPoint( info.EXECUTION_POINT_STARTING ); +- +- // Get all ServerRequestInterceptors: +- ServerRequestInterceptor[] serverInterceptors = +- (ServerRequestInterceptor[])interceptorList. +- getInterceptors( InterceptorList.INTERCEPTOR_TYPE_SERVER ); +- int size = serverInterceptors.length; ++ info.setCurrentExecutionPoint( info.EXECUTION_POINT_STARTING ); ++ ++ // Get all ServerRequestInterceptors: ++ ServerRequestInterceptor[] serverInterceptors = ++ (ServerRequestInterceptor[])interceptorList. ++ getInterceptors( InterceptorList.INTERCEPTOR_TYPE_SERVER ); ++ int size = serverInterceptors.length; + +- // We will assume that all interceptors returned successfully, +- // and adjust the flowStackIndex to the appropriate value if +- // we later discover otherwise. +- int flowStackIndex = size; +- boolean continueProcessing = true; +- +- // Currently, there is only one server-side starting point +- // interceptor called receive_request_service_contexts. +- for( int i = 0; continueProcessing && (i < size); i++ ) { +- ServerRequestInterceptor sri = serverInterceptors[i] ; +- try { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorStartingPoint: " +- + "Interceptor " + sri.name() +- + ".receive_request_service_contexts" ) ; +- } +- +- sri.receive_request_service_contexts( info ); +- } catch( ForwardRequest e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorStartingPoint " +- + "ForwardException from " +- + sri.name() ) ; +- } ++ // We will assume that all interceptors returned successfully, ++ // and adjust the flowStackIndex to the appropriate value if ++ // we later discover otherwise. ++ int flowStackIndex = size; ++ boolean continueProcessing = true; ++ ++ // Currently, there is only one server-side starting point ++ // interceptor called receive_request_service_contexts. ++ for( int i = 0; continueProcessing && (i < size); i++ ) { ++ ServerRequestInterceptor sri = serverInterceptors[i] ; ++ try { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "Interceptor " + sri.name() ++ + "receive_request_service_contexts" ) ; ++ } ++ ++ sri.receive_request_service_contexts( info ); ++ } catch( ForwardRequest e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught ForwardException from " ++ + sri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.3.1.), if +- // interception point throws a ForwardRequest, +- // no other Interceptors' starting points are +- // called and send_other is called. +- flowStackIndex = i; +- info.setForwardRequest( e ); +- info.setIntermediatePointCall( +- ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ); +- info.setEndingPointCall( +- ServerRequestInfoImpl.CALL_SEND_OTHER ); +- info.setReplyStatus( LOCATION_FORWARD.value ); ++ // as per PI spec (orbos/99-12-02 sec 5.3.1.), if ++ // interception point throws a ForwardRequest, ++ // no other Interceptors' starting points are ++ // called and send_other is called. ++ flowStackIndex = i; ++ info.setForwardRequest( e ); ++ info.setIntermediatePointCall( ++ ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ); ++ info.setEndingPointCall( ++ ServerRequestInfoImpl.CALL_SEND_OTHER ); ++ info.setReplyStatus( LOCATION_FORWARD.value ); + +- // For some reason, using break here causes the VM on +- // NT to lose track of the value of flowStackIndex +- // after exiting the for loop. I changed this to +- // check a boolean value instead and it seems to work +- // fine. +- continueProcessing = false; +- } catch( SystemException e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorStartingPoint " +- + "SystemException " + e + " from " +- + sri.name() ) ; +- } ++ // For some reason, using break here causes the VM on ++ // NT to lose track of the value of flowStackIndex ++ // after exiting the for loop. I changed this to ++ // check a boolean value instead and it seems to work ++ // fine. ++ continueProcessing = false; ++ } catch( SystemException e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught SystemException " + e ++ + "from" + sri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.3.1.), if +- // interception point throws a SystemException, +- // no other Interceptors' starting points are +- // called. +- flowStackIndex = i; +- info.setException( e ); +- info.setIntermediatePointCall( +- ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ); +- info.setEndingPointCall( +- ServerRequestInfoImpl.CALL_SEND_EXCEPTION ); +- info.setReplyStatus( SYSTEM_EXCEPTION.value ); ++ // as per PI spec (orbos/99-12-02 sec 5.3.1.), if ++ // interception point throws a SystemException, ++ // no other Interceptors' starting points are ++ // called. ++ flowStackIndex = i; ++ info.setException( e ); ++ info.setIntermediatePointCall( ++ ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ); ++ info.setEndingPointCall( ++ ServerRequestInfoImpl.CALL_SEND_EXCEPTION ); ++ info.setReplyStatus( SYSTEM_EXCEPTION.value ); + +- // For some reason, using break here causes the VM on +- // NT to lose track of the value of flowStackIndex +- // after exiting the for loop. I changed this to +- // check a boolean value instead and it seems to +- // work fine. +- continueProcessing = false; +- } +- +- } +- +- // Remember where we left off in the flow stack: +- info.setFlowStackIndex( flowStackIndex ); +- } finally { +- if (orb.interceptorDebugFlag) { +- dprint( "<-invokeServerInterceptorStartingPoint " + info ) ; +- } +- // The remaining points, ServantManager and Servant +- // all run in the same logical thread. +- current.popSlotTable( ); +- // Now TSC and RSC are equivalent. +- } +- } // end enabled check ++ // For some reason, using break here causes the VM on ++ // NT to lose track of the value of flowStackIndex ++ // after exiting the for loop. I changed this to ++ // check a boolean value instead and it seems to ++ // work fine. ++ continueProcessing = false; ++ } ++ } ++ ++ // Remember where we left off in the flow stack: ++ info.setFlowStackIndex( flowStackIndex ); ++ } finally { ++ // The remaining points, ServantManager and Servant ++ // all run in the same logical thread. ++ current.popSlotTable( ); ++ // Now TSC and RSC are equivalent. ++ } ++ } // end enabled check ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -593,77 +610,78 @@ + void invokeServerInterceptorIntermediatePoint( + ServerRequestInfoImpl info ) + { +- int intermediatePointCall = info.getIntermediatePointCall(); +- // If invocation is not yet enabled, don't do anything. +- if( enabled && ( intermediatePointCall != +- ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ) ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeServerInterceptorIntermediatePoint", ++ "info", info ) ; ++ } + +- if (orb.interceptorDebugFlag) { +- dprint( "->invokeServerInterceptorIntermediatePoint " + info ) ; +- } +- // NOTE: do not touch the slotStack. The RSC and TSC are +- // equivalent at this point. ++ try { ++ int intermediatePointCall = info.getIntermediatePointCall(); ++ // If invocation is not yet enabled, don't do anything. ++ if( enabled && ( intermediatePointCall != ++ ServerRequestInfoImpl.CALL_INTERMEDIATE_NONE ) ) { + +- info.setCurrentExecutionPoint( info.EXECUTION_POINT_INTERMEDIATE ); +- +- // Get all ServerRequestInterceptors: +- ServerRequestInterceptor[] serverInterceptors = +- (ServerRequestInterceptor[]) +- interceptorList.getInterceptors( +- InterceptorList.INTERCEPTOR_TYPE_SERVER ); +- int size = serverInterceptors.length; ++ // NOTE: do not touch the slotStack. The RSC and TSC are ++ // equivalent at this point. + +- // Currently, there is only one server-side intermediate point +- // interceptor called receive_request. +- for( int i = 0; i < size; i++ ) { +- ServerRequestInterceptor sri = serverInterceptors[i] ; +- try { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorIntermediatePoint: " +- + "Interceptor " + sri.name() +- + ".receive_request" ) ; +- } +- +- sri.receive_request( info ); +- } catch( ForwardRequest e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorIntermediatePoint " +- + "ForwardException from " +- + sri.name() ) ; +- } ++ info.setCurrentExecutionPoint( info.EXECUTION_POINT_INTERMEDIATE ); ++ ++ // Get all ServerRequestInterceptors: ++ ServerRequestInterceptor[] serverInterceptors = ++ (ServerRequestInterceptor[]) ++ interceptorList.getInterceptors( ++ InterceptorList.INTERCEPTOR_TYPE_SERVER ); ++ int size = serverInterceptors.length; + +- // as per PI spec (orbos/99-12-02 sec 5.3.1.), if +- // interception point throws a ForwardRequest, +- // no other Interceptors' intermediate points are +- // called and send_other is called. +- info.setForwardRequest( e ); +- info.setEndingPointCall( +- ServerRequestInfoImpl.CALL_SEND_OTHER ); +- info.setReplyStatus( LOCATION_FORWARD.value ); +- break; +- } catch( SystemException e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorIntermediatePoint " +- + "SystemException " + e + " from " +- + sri.name() ) ; +- } ++ // Currently, there is only one server-side intermediate point ++ // interceptor called receive_request. ++ for( int i = 0; i < size; i++ ) { ++ ServerRequestInterceptor sri = serverInterceptors[i] ; ++ try { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "Interceptor " + sri.name() ++ + "receive_request" ) ; ++ } ++ ++ sri.receive_request( info ); ++ } catch( ForwardRequest e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught ForwardException from " ++ + sri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.3.1.), if +- // interception point throws a SystemException, +- // no other Interceptors' starting points are +- // called. +- info.setException( e ); +- info.setEndingPointCall( +- ServerRequestInfoImpl.CALL_SEND_EXCEPTION ); +- info.setReplyStatus( SYSTEM_EXCEPTION.value ); +- break; ++ // as per PI spec (orbos/99-12-02 sec 5.3.1.), if ++ // interception point throws a ForwardRequest, ++ // no other Interceptors' intermediate points are ++ // called and send_other is called. ++ info.setForwardRequest( e ); ++ info.setEndingPointCall( ++ ServerRequestInfoImpl.CALL_SEND_OTHER ); ++ info.setReplyStatus( LOCATION_FORWARD.value ); ++ break; ++ } catch( SystemException e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught SystemException " + e ++ + "from" + sri.name() ) ; ++ } ++ ++ // as per PI spec (orbos/99-12-02 sec 5.3.1.), if ++ // interception point throws a SystemException, ++ // no other Interceptors' starting points are ++ // called. ++ info.setException( e ); ++ info.setEndingPointCall( ++ ServerRequestInfoImpl.CALL_SEND_EXCEPTION ); ++ info.setReplyStatus( SYSTEM_EXCEPTION.value ); ++ break; ++ } + } ++ } // end enabled check ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; + } +- +- if (orb.interceptorDebugFlag) { +- dprint( "<-invokeServerInterceptorIntermediatePoint " + info ) ; +- } +- } // end enabled check ++ } + } + + private String getServerEndMethodName( int endingPointCall ) { +@@ -683,102 +701,102 @@ + * depending on the value of info.getEndingPointCall() + */ + void invokeServerInterceptorEndingPoint( ServerRequestInfoImpl info ) { +- // If invocation is not yet enabled, don't do anything. +- if( enabled ) { +- try { +- if (orb.interceptorDebugFlag) { +- dprint( "->invokeServerInterceptorEndingPoint " + info ) ; +- } +- +- // NOTE: do not touch the slotStack. The RSC and TSC are +- // equivalent at this point. ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeServerInterceptorEndingPoint", "info", info ) ; ++ } + +- // REVISIT: This is moved out to PIHandlerImpl until dispatch +- // path is rearchitected. It must be there so that +- // it always gets executed so if an interceptor raises +- // an exception any service contexts added in earlier points +- // this point get put in the exception reply (via the SC Q). +- //info.setCurrentExecutionPoint( info.EXECUTION_POINT_ENDING ); +- +- // Get all ServerRequestInterceptors: +- ServerRequestInterceptor[] serverInterceptors = +- (ServerRequestInterceptor[])interceptorList. +- getInterceptors( InterceptorList.INTERCEPTOR_TYPE_SERVER ); +- int flowStackIndex = info.getFlowStackIndex(); +- +- // Determine whether we are calling +- // send_exception, or send_other: +- int endingPointCall = info.getEndingPointCall(); +- +- // Only step through the interceptors whose starting points +- // have successfully returned. +- for( int i = (flowStackIndex - 1); i >= 0; i-- ) { +- ServerRequestInterceptor sri = serverInterceptors[i] ; ++ try { ++ // If invocation is not yet enabled, don't do anything. ++ if( enabled ) { ++ try { ++ // NOTE: do not touch the slotStack. The RSC and TSC are ++ // equivalent at this point. + +- try { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorEndingPoint: " +- + "Interceptor " + sri.name() + "." +- + getServerEndMethodName( endingPointCall ) ) ; +- } +- +- +- switch( endingPointCall ) { +- case ServerRequestInfoImpl.CALL_SEND_REPLY: +- sri.send_reply( info ); +- break; +- case ServerRequestInfoImpl.CALL_SEND_EXCEPTION: +- sri.send_exception( info ); +- break; +- case ServerRequestInfoImpl.CALL_SEND_OTHER: +- sri.send_other( info ); +- break; +- } +- } catch( ForwardRequest e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorEndingPoint " +- + "ForwardRequest from " + sri.name() ) ; +- } ++ // REVISIT: This is moved out to PIHandlerImpl until dispatch ++ // path is rearchitected. It must be there so that ++ // it always gets executed so if an interceptor raises ++ // an exception any service contexts added in earlier points ++ // this point get put in the exception reply (via the SC Q). ++ //info.setCurrentExecutionPoint( info.EXECUTION_POINT_ENDING ); ++ ++ // Get all ServerRequestInterceptors: ++ ServerRequestInterceptor[] serverInterceptors = ++ (ServerRequestInterceptor[])interceptorList. ++ getInterceptors( InterceptorList.INTERCEPTOR_TYPE_SERVER ); ++ int flowStackIndex = info.getFlowStackIndex(); ++ ++ // Determine whether we are calling ++ // send_exception, or send_other: ++ int endingPointCall = info.getEndingPointCall(); ++ ++ // Only step through the interceptors whose starting points ++ // have successfully returned. ++ for( int i = (flowStackIndex - 1); i >= 0; i-- ) { ++ ServerRequestInterceptor sri = serverInterceptors[i] ; + +- // as per PI spec (orbos/99-12-02 sec 5.3.1.), if +- // interception point throws a ForwardException, +- // ending point call changes to receive_other. +- endingPointCall = +- ServerRequestInfoImpl.CALL_SEND_OTHER; +- info.setEndingPointCall( endingPointCall ); +- info.setForwardRequest( e ); +- info.setReplyStatus( LOCATION_FORWARD.value ); +- info.setForwardRequestRaisedInEnding(); +- } catch( SystemException e ) { +- if (orb.interceptorDebugFlag) { +- dprint( ".invokeServerInterceptorEndingPoint " +- + "SystemException " + e + " from " +- + sri.name() ) ; +- } ++ try { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "Interceptor " + sri.name() ++ + "method" + getServerEndMethodName( endingPointCall ) ) ; ++ } ++ ++ ++ switch( endingPointCall ) { ++ case ServerRequestInfoImpl.CALL_SEND_REPLY: ++ sri.send_reply( info ); ++ break; ++ case ServerRequestInfoImpl.CALL_SEND_EXCEPTION: ++ sri.send_exception( info ); ++ break; ++ case ServerRequestInfoImpl.CALL_SEND_OTHER: ++ sri.send_other( info ); ++ break; ++ } ++ } catch( ForwardRequest e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught ForwardRequest from " ++ + sri.name() ) ; ++ } + +- // as per PI spec (orbos/99-12-02 sec 5.3.1.), if +- // interception point throws a SystemException, +- // ending point call changes to send_exception. +- endingPointCall = +- ServerRequestInfoImpl.CALL_SEND_EXCEPTION; +- info.setEndingPointCall( endingPointCall ); +- info.setException( e ); +- info.setReplyStatus( SYSTEM_EXCEPTION.value ); +- } +- } +- +- // Remember that all interceptors' starting and ending points +- // have already been executed so we need not do anything. +- info.setAlreadyExecuted( true ); +- } finally { +- if (orb.interceptorDebugFlag) { +- dprint( "<-invokeServerInterceptorEndingPoint " + info ) ; +- } +- +- // Get rid of the Server side RSC. +- current.popSlotTable(); +- } +- } // end enabled check ++ // as per PI spec (orbos/99-12-02 sec 5.3.1.), if ++ // interception point throws a ForwardException, ++ // ending point call changes to receive_other. ++ endingPointCall = ++ ServerRequestInfoImpl.CALL_SEND_OTHER; ++ info.setEndingPointCall( endingPointCall ); ++ info.setForwardRequest( e ); ++ info.setReplyStatus( LOCATION_FORWARD.value ); ++ info.setForwardRequestRaisedInEnding(); ++ } catch( SystemException e ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "caught SystemException " + e ++ + "from" + sri.name() ) ; ++ } ++ ++ // as per PI spec (orbos/99-12-02 sec 5.3.1.), if ++ // interception point throws a SystemException, ++ // ending point call changes to send_exception. ++ endingPointCall = ++ ServerRequestInfoImpl.CALL_SEND_EXCEPTION; ++ info.setEndingPointCall( endingPointCall ); ++ info.setException( e ); ++ info.setReplyStatus( SYSTEM_EXCEPTION.value ); ++ } ++ } ++ ++ // Remember that all interceptors' starting and ending points ++ // have already been executed so we need not do anything. ++ info.setAlreadyExecuted( true ); ++ } finally { ++ // Get rid of the Server side RSC. ++ current.popSlotTable(); ++ } ++ } // end enabled check ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -793,18 +811,28 @@ + private void updateClientRequestDispatcherForward( + ClientRequestInfoImpl info ) + { +- ForwardRequest forwardRequest = info.getForwardRequestException(); +- +- // ForwardRequest may be null if the forwarded IOR is set internal +- // to the ClientRequestDispatcher rather than explicitly through Portable +- // Interceptors. In this case, we need not update the client +- // delegate ForwardRequest object. +- if( forwardRequest != null ) { +- org.omg.CORBA.Object object = forwardRequest.forward; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "updateClientRequestDispatcherForward" ) ; ++ } + +- // Convert the forward object into an IOR: +- IOR ior = orb.getIOR( object, false ) ; +- info.setLocatedIOR( ior ); ++ try { ++ ForwardRequest forwardRequest = info.getForwardRequestException(); ++ ++ // ForwardRequest may be null if the forwarded IOR is set internal ++ // to the ClientRequestDispatcher rather than explicitly through Portable ++ // Interceptors. In this case, we need not update the client ++ // delegate ForwardRequest object. ++ if( forwardRequest != null ) { ++ org.omg.CORBA.Object object = forwardRequest.forward; ++ ++ // Convert the forward object into an IOR: ++ IOR ior = orb.getIOR( object, false ) ; ++ info.setLocatedIOR( ior ); ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } + } + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/interceptors/PIHandlerImpl.java +--- a/src/share/classes/com/sun/corba/ee/impl/interceptors/PIHandlerImpl.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/interceptors/PIHandlerImpl.java Mon Jul 06 12:05:55 2009 -0700 +@@ -36,33 +36,24 @@ + package com.sun.corba.ee.impl.interceptors; + + import java.util.*; +-import java.io.IOException; + + import org.omg.CORBA.Any; + import org.omg.CORBA.BAD_PARAM; + import org.omg.CORBA.BAD_POLICY; +-import org.omg.CORBA.BAD_INV_ORDER; +-import org.omg.CORBA.COMM_FAILURE; + import org.omg.CORBA.CompletionStatus; +-import org.omg.CORBA.INTERNAL; + import org.omg.CORBA.NVList; +-import org.omg.CORBA.OBJECT_NOT_EXIST; +-import org.omg.CORBA.ORBPackage.InvalidName; + import org.omg.CORBA.SystemException; + import org.omg.CORBA.UserException; +-import org.omg.CORBA.UNKNOWN; + + import org.omg.CORBA.portable.ApplicationException; + import org.omg.CORBA.portable.RemarshalException; + + import org.omg.IOP.CodecFactory; + +-import org.omg.PortableInterceptor.ForwardRequest; + import org.omg.PortableInterceptor.Current; + import org.omg.PortableInterceptor.Interceptor; + import org.omg.PortableInterceptor.LOCATION_FORWARD; + import org.omg.PortableInterceptor.ORBInitializer; +-import org.omg.PortableInterceptor.ORBInitInfo; + import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName; + import org.omg.PortableInterceptor.SUCCESSFUL; + import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; +@@ -71,7 +62,6 @@ + import org.omg.PortableInterceptor.PolicyFactory; + import org.omg.PortableInterceptor.ObjectReferenceTemplate ; + +-import com.sun.corba.ee.pept.encoding.OutputObject; + + import com.sun.corba.ee.spi.ior.IOR; + import com.sun.corba.ee.spi.ior.ObjectKeyTemplate; +@@ -81,14 +71,16 @@ + import com.sun.corba.ee.spi.protocol.CorbaMessageMediator; + import com.sun.corba.ee.spi.protocol.ForwardException; + import com.sun.corba.ee.spi.protocol.PIHandler; +-import com.sun.corba.ee.spi.orbutil.misc.StackImpl; ++import com.sun.corba.ee.spi.protocol.RetryType ; + + import com.sun.corba.ee.impl.logging.InterceptorsSystemException; + import com.sun.corba.ee.impl.logging.ORBUtilSystemException; + import com.sun.corba.ee.impl.logging.OMGSystemException; + import com.sun.corba.ee.impl.corba.RequestImpl; ++ + import com.sun.corba.ee.spi.orbutil.ORBConstants; +-import com.sun.corba.ee.impl.orbutil.ORBUtility; ++ ++import com.sun.corba.ee.impl.orbutil.DprintUtil; + import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; + + /** +@@ -96,31 +88,9 @@ + */ + public class PIHandlerImpl implements PIHandler + { +- // REVISIT - delete these after framework merging. +- boolean printPushPopEnabled = false; +- int pushLevel = 0; +- private void printPush() +- { +- if (! printPushPopEnabled) return; +- printSpaces(pushLevel); +- pushLevel++; +- System.out.println("PUSH"); +- } +- private void printPop() +- { +- if (! printPushPopEnabled) return; +- pushLevel--; +- printSpaces(pushLevel); +- System.out.println("POP"); +- } +- private void printSpaces(int n) +- { +- for (int i = 0; i < n; i++) { +- System.out.print(" "); +- } +- } ++ private ORB orb ; ++ private DprintUtil dputil = new DprintUtil( this ) ; + +- private ORB orb ; + InterceptorsSystemException wrapper ; + ORBUtilSystemException orbutilWrapper ; + OMGSystemException omgWrapper ; +@@ -168,12 +138,24 @@ + LOCATION_FORWARD.value, // = ReplyMessage.LOCATION_FORWARD_PERM + TRANSPORT_RETRY.value // = ReplyMessage.NEEDS_ADDRESSING_MODE + }; +- ++ ++ static String getReplyStatus( int piReplyStatus ) { ++ switch (piReplyStatus) { ++ case SUCCESSFUL.value: return "SUCCESSFUL" ; ++ case USER_EXCEPTION.value: return "USER_EXCEPTION" ; ++ case SYSTEM_EXCEPTION.value: return "SYSTEM_EXCEPTION" ; ++ case LOCATION_FORWARD.value: return "LOCATION_FORWARD" ; ++ case TRANSPORT_RETRY.value: return "TRANSPORT_RETRY" ; ++ default: return "UNINITIALIZED" ; ++ } ++ } ++ + // ThreadLocal containing a stack to store client request info objects + // and a disable count. + private ThreadLocal> + threadLocalClientRequestInfoStack = + new ThreadLocal>() { ++ @Override + protected RequestInfoStack initialValue() { + return new RequestInfoStack(); + } +@@ -183,24 +165,37 @@ + private ThreadLocal> + threadLocalServerRequestInfoStack = + new ThreadLocal>() { ++ @Override + protected RequestInfoStack initialValue() { + return new RequestInfoStack(); + } + }; + + public void close() { +- orb = null ; +- wrapper = null ; +- orbutilWrapper = null ; +- omgWrapper = null ; +- codecFactory = null ; +- arguments = null ; +- interceptorList = null ; +- interceptorInvoker = null ; +- current = null ; +- policyFactoryTable = null ; +- threadLocalClientRequestInfoStack = null ; +- threadLocalServerRequestInfoStack = null ; ++ // be careful: close nulls the orb reference ++ boolean debug = orb.interceptorDebugFlag ; ++ if (debug) { ++ dputil.enter( "close" ) ; ++ } ++ ++ try { ++ orb = null ; ++ wrapper = null ; ++ orbutilWrapper = null ; ++ omgWrapper = null ; ++ codecFactory = null ; ++ arguments = null ; ++ interceptorList = null ; ++ interceptorInvoker = null ; ++ current = null ; ++ policyFactoryTable = null ; ++ threadLocalClientRequestInfoStack = null ; ++ threadLocalServerRequestInfoStack = null ; ++ } finally { ++ if (debug) { ++ dputil.exit() ; ++ } ++ } + } + // Class to contain all ThreadLocal data for ClientRequestInfo + // maintenance. +@@ -215,78 +210,98 @@ + } + + public PIHandlerImpl( ORB orb, String[] args ) { +- this.orb = orb ; +- wrapper = orb.getLogWrapperTable().get_RPC_PROTOCOL_Interceptors() ; +- orbutilWrapper = orb.getLogWrapperTable().get_RPC_PROTOCOL_ORBUtil() ; +- omgWrapper = orb.getLogWrapperTable().get_RPC_PROTOCOL_OMG() ; +- arguments = args ; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "(ORB,String[])" ) ; ++ } + +- // Create codec factory: +- codecFactory = new CodecFactoryImpl( orb ); ++ try { ++ this.orb = orb ; ++ wrapper = orb.getLogWrapperTable().get_RPC_PROTOCOL_Interceptors() ; ++ orbutilWrapper = orb.getLogWrapperTable().get_RPC_PROTOCOL_ORBUtil() ; ++ omgWrapper = orb.getLogWrapperTable().get_RPC_PROTOCOL_OMG() ; ++ arguments = args ; + +- // Create new interceptor list: +- interceptorList = new InterceptorList( wrapper ); ++ // Create codec factory: ++ codecFactory = new CodecFactoryImpl( orb ); + +- // Create a new PICurrent. +- current = new PICurrent( orb ); ++ // Create new interceptor list: ++ interceptorList = new InterceptorList( wrapper ); + +- // Create new interceptor invoker, initially disabled: +- interceptorInvoker = new InterceptorInvoker( orb, interceptorList, +- current ); ++ // Create a new PICurrent. ++ current = new PICurrent( orb ); + +- // Register the PI current and Codec factory objects +- orb.getLocalResolver().register( ORBConstants.PI_CURRENT_NAME, +- ClosureFactory.makeConstant( current ) ) ; +- orb.getLocalResolver().register( ORBConstants.CODEC_FACTORY_NAME, +- ClosureFactory.makeConstant( codecFactory ) ) ; ++ // Create new interceptor invoker, initially disabled: ++ interceptorInvoker = new InterceptorInvoker( orb, interceptorList, ++ current ); ++ ++ // Register the PI current and Codec factory objects ++ orb.getLocalResolver().register( ORBConstants.PI_CURRENT_NAME, ++ ClosureFactory.makeConstant( current ) ) ; ++ orb.getLocalResolver().register( ORBConstants.CODEC_FACTORY_NAME, ++ ClosureFactory.makeConstant( codecFactory ) ) ; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void initialize() { +- // If we have any orb initializers, make use of them: +- if( orb.getORBData().getORBInitializers() != null ) { +- // Create the ORBInitInfo object to pass to ORB intializers: +- ORBInitInfoImpl orbInitInfo = createORBInitInfo(); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "initialize" ) ; ++ } + +- // Make sure get_slot and set_slot are not called from within +- // ORB initializers: +- current.setORBInitializing( true ); ++ try { ++ // If we have any orb initializers, make use of them: ++ if( orb.getORBData().getORBInitializers() != null ) { ++ // Create the ORBInitInfo object to pass to ORB intializers: ++ ORBInitInfoImpl orbInitInfo = createORBInitInfo(); + +- // Call pre_init on all ORB initializers: +- preInitORBInitializers( orbInitInfo ); ++ // Make sure get_slot and set_slot are not called from within ++ // ORB initializers: ++ current.setORBInitializing( true ); + +- // Call post_init on all ORB initializers: +- postInitORBInitializers( orbInitInfo ); ++ // Call pre_init on all ORB initializers: ++ preInitORBInitializers( orbInitInfo ); + +- // Proprietary: sort interceptors: +- interceptorList.sortInterceptors(); ++ // Call post_init on all ORB initializers: ++ postInitORBInitializers( orbInitInfo ); + +- // Re-enable get_slot and set_slot to be called from within +- // ORB initializers: +- current.setORBInitializing( false ); ++ // Proprietary: sort interceptors: ++ interceptorList.sortInterceptors(); + +- // Ensure nobody makes any more calls on this object. +- orbInitInfo.setStage( ORBInitInfoImpl.STAGE_CLOSED ); ++ // Re-enable get_slot and set_slot to be called from within ++ // ORB initializers: ++ current.setORBInitializing( false ); + +- // Set cached flags indicating whether we have interceptors +- // registered of a given type. +- hasIORInterceptors = interceptorList.hasInterceptorsOfType( +- InterceptorList.INTERCEPTOR_TYPE_IOR ); +- // XXX This must always be true, so that using the new generic +- // RPC framework can pass info between the PI stack and the +- // framework invocation stack. Temporary until Harold fixes +- // this. Note that this must never be true until after the +- // ORBInitializer instances complete executing. +- //hasClientInterceptors = interceptorList.hasInterceptorsOfType( +- //InterceptorList.INTERCEPTOR_TYPE_CLIENT ); +- hasClientInterceptors = true; +- hasServerInterceptors = interceptorList.hasInterceptorsOfType( +- InterceptorList.INTERCEPTOR_TYPE_SERVER ); ++ // Ensure nobody makes any more calls on this object. ++ orbInitInfo.setStage( ORBInitInfoImpl.STAGE_CLOSED ); + +- // Enable interceptor invoker (not necessary if no interceptors +- // are registered). This should be the last stage of ORB +- // initialization. +- interceptorInvoker.setEnabled( true ); +- } ++ // Set cached flags indicating whether we have interceptors ++ // registered of a given type. ++ hasIORInterceptors = interceptorList.hasInterceptorsOfType( ++ InterceptorList.INTERCEPTOR_TYPE_IOR ); ++ // XXX This must always be true, so that using the new generic ++ // RPC framework can pass info between the PI stack and the ++ // framework invocation stack. Temporary until Harold fixes ++ // this. Note that this must never be true until after the ++ // ORBInitializer instances complete executing. ++ //hasClientInterceptors = interceptorList.hasInterceptorsOfType( ++ //InterceptorList.INTERCEPTOR_TYPE_CLIENT ); ++ hasClientInterceptors = true; ++ hasServerInterceptors = interceptorList.hasInterceptorsOfType( ++ InterceptorList.INTERCEPTOR_TYPE_SERVER ); ++ ++ // Enable interceptor invoker (not necessary if no interceptors ++ // are registered). This should be the last stage of ORB ++ // initialization. ++ interceptorInvoker.setEnabled( true ); ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -299,33 +314,70 @@ + * part of the PIHandler interface, since ORBImpl implements the ORB interface. + */ + public void destroyInterceptors() { +- interceptorList.destroyAll(); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "destroyInterceptors" ) ; ++ } ++ ++ try { ++ interceptorList.destroyAll(); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- public void objectAdapterCreated( ObjectAdapter oa ) +- { +- if (!hasIORInterceptors) +- return ; ++ public void objectAdapterCreated( ObjectAdapter oa ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "objectAdapterCreated" ) ; ++ } + +- interceptorInvoker.objectAdapterCreated( oa ) ; ++ try { ++ if (!hasIORInterceptors) ++ return ; ++ ++ interceptorInvoker.objectAdapterCreated( oa ) ; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void adapterManagerStateChanged( int managerId, +- short newState ) +- { +- if (!hasIORInterceptors) +- return ; ++ short newState ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "adapterManagerStateChanged" ) ; ++ } + +- interceptorInvoker.adapterManagerStateChanged( managerId, newState ) ; ++ try { ++ if (!hasIORInterceptors) ++ return ; ++ ++ interceptorInvoker.adapterManagerStateChanged( managerId, newState ) ; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void adapterStateChanged( ObjectReferenceTemplate[] +- templates, short newState ) +- { +- if (!hasIORInterceptors) +- return ; ++ templates, short newState ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "adapterStateChanged" ) ; ++ } + +- interceptorInvoker.adapterStateChanged( templates, newState ) ; ++ try { ++ if (!hasIORInterceptors) ++ return ; ++ ++ interceptorInvoker.adapterStateChanged( templates, newState ) ; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -334,189 +386,316 @@ + *****************/ + + public void disableInterceptorsThisThread() { +- if( !hasClientInterceptors ) return; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "disableInterceptorsThisThread" ) ; ++ } + +- RequestInfoStack infoStack = +- threadLocalClientRequestInfoStack.get(); +- infoStack.disableCount++; ++ try { ++ if( !hasClientInterceptors ) return; ++ ++ RequestInfoStack infoStack = ++ threadLocalClientRequestInfoStack.get(); ++ infoStack.disableCount++; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void enableInterceptorsThisThread() { +- if( !hasClientInterceptors ) return; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "enableInterceptorsThisThread" ) ; ++ } + +- RequestInfoStack infoStack = +- threadLocalClientRequestInfoStack.get(); +- infoStack.disableCount--; ++ try { ++ if( !hasClientInterceptors ) return; ++ ++ RequestInfoStack infoStack = ++ threadLocalClientRequestInfoStack.get(); ++ infoStack.disableCount--; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void invokeClientPIStartingPoint() +- throws RemarshalException +- { +- if( !hasClientInterceptors ) return; +- if( !isClientPIEnabledForThisThread() ) return; ++ throws RemarshalException { + +- // Invoke the starting interception points and record exception +- // and reply status info in the info object: +- ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); +- interceptorInvoker.invokeClientInterceptorStartingPoint( info ); +- +- // Check reply status. If we will not have another chance later +- // to invoke the client ending points, do it now. +- short replyStatus = info.getReplyStatus(); +- if( (replyStatus == SYSTEM_EXCEPTION.value) || +- (replyStatus == LOCATION_FORWARD.value) ) +- { +- // Note: Transport retry cannot happen here since this happens +- // before the request hits the wire. ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeClientPIStartingPoint" ) ; ++ } + +- Exception exception = invokeClientPIEndingPoint( +- convertPIReplyStatusToReplyMessage( replyStatus ), +- info.getException() ); +- if( exception == null ) { +- // Do not throw anything. Otherwise, it must be a +- // SystemException, UserException or RemarshalException. +- } if( exception instanceof SystemException ) { +- throw (SystemException)exception; +- } else if( exception instanceof RemarshalException ) { +- throw (RemarshalException)exception; +- } else if( (exception instanceof UserException) || +- (exception instanceof ApplicationException) ) { +- // It should not be possible for an interceptor to throw +- // a UserException. By asserting instead of throwing the +- // UserException, we need not declare anything but +- // RemarshalException in the throws clause. +- throw wrapper.exceptionInvalid() ; ++ try { ++ if( !hasClientInterceptors ) return; ++ if( !isClientPIEnabledForThisThread() ) return; ++ ++ // Invoke the starting interception points and record exception ++ // and reply status info in the info object: ++ ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); ++ interceptorInvoker.invokeClientInterceptorStartingPoint( info ); ++ ++ // Check reply status. If we will not have another chance later ++ // to invoke the client ending points, do it now. ++ short replyStatus = info.getReplyStatus(); ++ if( (replyStatus == SYSTEM_EXCEPTION.value) || ++ (replyStatus == LOCATION_FORWARD.value) ) { ++ // Note: Transport retry cannot happen here since this happens ++ // before the request hits the wire. ++ ++ Exception exception = invokeClientPIEndingPoint( ++ convertPIReplyStatusToReplyMessage( replyStatus ), ++ info.getException() ); ++ if( exception == null ) { ++ // Do not throw anything. Otherwise, it must be a ++ // SystemException, UserException or RemarshalException. ++ } if( exception instanceof SystemException ) { ++ throw (SystemException)exception; ++ } else if( exception instanceof RemarshalException ) { ++ throw (RemarshalException)exception; ++ } else if( (exception instanceof UserException) || ++ (exception instanceof ApplicationException) ) { ++ // It should not be possible for an interceptor to throw ++ // a UserException. By asserting instead of throwing the ++ // UserException, we need not declare anything but ++ // RemarshalException in the throws clause. ++ throw wrapper.exceptionInvalid() ; ++ } ++ } else if( replyStatus != ClientRequestInfoImpl.UNINITIALIZED ) { ++ throw wrapper.replyStatusNotInit() ; ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; + } + } +- else if( replyStatus != ClientRequestInfoImpl.UNINITIALIZED ) { +- throw wrapper.replyStatusNotInit() ; +- } + } +- +- public Exception invokeClientPIEndingPoint( +- int replyStatus, Exception exception ) +- { +- if( !hasClientInterceptors ) return exception; +- if( !isClientPIEnabledForThisThread() ) return exception; + +- // Translate ReplyMessage.replyStatus into PI replyStatus: +- // Note: this is also an assertion to make sure a valid replyStatus +- // is passed in (IndexOutOfBoundsException will be thrown otherwise) +- short piReplyStatus = REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; +- +- // Invoke the ending interception points and record exception +- // and reply status info in the info object: +- ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); +- info.setReplyStatus( piReplyStatus ); +- info.setException( exception ); +- interceptorInvoker.invokeClientInterceptorEndingPoint( info ); +- piReplyStatus = info.getReplyStatus(); ++ // Needed when an error forces a retry AFTER initiateClientPIRequest ++ // but BEFORE invokeClientPIStartingPoint. ++ public Exception makeCompletedClientRequest( int replyStatus, ++ Exception exception ) { + +- // Check reply status: +- if( (piReplyStatus == LOCATION_FORWARD.value) || +- (piReplyStatus == TRANSPORT_RETRY.value) ) +- { +- // If this is a forward or a retry, reset and reuse +- // info object: +- info.reset(); +- info.setRetryRequest( true ); ++ return handleClientPIEndingPoint( replyStatus, exception, false ) ; ++ } + +- // ... and return a RemarshalException so the orb internals know +- exception = new RemarshalException(); ++ public Exception invokeClientPIEndingPoint( int replyStatus, ++ Exception exception ) { ++ ++ return handleClientPIEndingPoint( replyStatus, exception, true ) ; ++ } ++ ++ public Exception handleClientPIEndingPoint( ++ int replyStatus, Exception exception, boolean invokeEndingPoint ) { ++ ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "handleClientPIEndingPoint", ++ "replyStatus", getReplyStatus(replyStatus), ++ "exception", exception, ++ "invokeEndingPoint", invokeEndingPoint ) ; + } +- else if( (piReplyStatus == SYSTEM_EXCEPTION.value) || +- (piReplyStatus == USER_EXCEPTION.value) ) +- { +- exception = info.getException(); ++ ++ try { ++ if( !hasClientInterceptors ) return exception; ++ if( !isClientPIEnabledForThisThread() ) return exception; ++ ++ // Translate ReplyMessage.replyStatus into PI replyStatus: ++ // Note: this is also an assertion to make sure a valid replyStatus ++ // is passed in (IndexOutOfBoundsException will be thrown otherwise) ++ short piReplyStatus = REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; ++ ++ // Invoke the ending interception points and record exception ++ // and reply status info in the info object: ++ ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); ++ info.setReplyStatus( piReplyStatus ); ++ info.setException( exception ); ++ ++ if (invokeEndingPoint) { ++ interceptorInvoker.invokeClientInterceptorEndingPoint( info ); ++ piReplyStatus = info.getReplyStatus(); ++ } ++ ++ // Check reply status: ++ if( (piReplyStatus == LOCATION_FORWARD.value) || ++ (piReplyStatus == TRANSPORT_RETRY.value) ) { ++ // If this is a forward or a retry, reset and reuse ++ // info object: ++ info.reset(); ++ ++ // fix for 6763340: ++ if (invokeEndingPoint) { ++ info.setRetryRequest( RetryType.AFTER_RESPONSE ) ; ++ } else { ++ info.setRetryRequest( RetryType.BEFORE_RESPONSE ) ; ++ } ++ ++ // ... and return a RemarshalException so the orb internals know ++ exception = new RemarshalException(); ++ } else if( (piReplyStatus == SYSTEM_EXCEPTION.value) || ++ (piReplyStatus == USER_EXCEPTION.value) ) { ++ ++ exception = info.getException(); ++ } ++ ++ return exception; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } +- +- return exception; + } +- ++ + public void initiateClientPIRequest( boolean diiRequest ) { +- if( !hasClientInterceptors ) return; +- if( !isClientPIEnabledForThisThread() ) return; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "initiateClientPIRequest" ) ; ++ } + +- // Get the most recent info object from the thread local +- // ClientRequestInfoImpl stack: +- RequestInfoStack infoStack = +- threadLocalClientRequestInfoStack.get(); +- ClientRequestInfoImpl info = null; +- if( !infoStack.empty() ) +- info = infoStack.peek(); ++ try { ++ if( !hasClientInterceptors ) return; ++ if( !isClientPIEnabledForThisThread() ) return; + +- if( !diiRequest && (info != null) && info.isDIIInitiate() ) { +- // In RequestImpl.doInvocation we already called +- // initiateClientPIRequest( true ), so ignore this initiate. +- info.setDIIInitiate( false ); +- } +- else { +- // If there is no info object or if we are not retrying a request, +- // push a new ClientRequestInfoImpl on the stack: +- if( (info == null) || !info.getRetryRequest() ) { +- info = new ClientRequestInfoImpl( orb ); +- infoStack.push( info ); +- printPush(); +- // Note: the entry count is automatically initialized to 0. +- } +- +- // Reset the retry request flag so that recursive calls will +- // push a new info object, and bump up entry count so we know +- // when to pop this info object: +- info.setRetryRequest( false ); +- info.incrementEntryCount(); ++ // Get the most recent info object from the thread local ++ // ClientRequestInfoImpl stack: ++ RequestInfoStack infoStack = ++ threadLocalClientRequestInfoStack.get(); ++ ClientRequestInfoImpl info = null; + +- // If this is a DII request, make sure we ignore the next initiate. +- if( diiRequest ) { +- info.setDIIInitiate( true ); +- } +- } ++ if (!infoStack.empty() ) { ++ info = infoStack.peek(); ++ } ++ ++ if (!diiRequest && (info != null) && info.isDIIInitiate() ) { ++ // In RequestImpl.doInvocation we already called ++ // initiateClientPIRequest( true ), so ignore this initiate. ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "second call for a DII request" ) ; ++ } ++ info.setDIIInitiate( false ); ++ } else { ++ // If there is no info object or if we are not retrying a request, ++ // push a new ClientRequestInfoImpl on the stack: ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "normal call" ) ; ++ } ++ ++ // 6763340: don't push unless this is not a retry ++ if( (info == null) || !info.getRetryRequest().isRetry() ) { ++ info = new ClientRequestInfoImpl( orb ); ++ infoStack.push( info ); ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "client infoStack was pushed" ) ; ++ } ++ // Note: the entry count is automatically initialized to 0. ++ } ++ ++ // Reset the retry request flag so that recursive calls will ++ // push a new info object, and bump up entry count so we know ++ // when to pop this info object: ++ info.setRetryRequest( RetryType.NONE ); ++ info.incrementEntryCount(); ++ ++ // KMC 6763340: I don't know why this wasn't set earlier, ++ // but we do not want a retry to pick up the previous ++ // reply status, so clear it here. Most likely a new ++ // info was pushed before, so that this was not a problem. ++ info.setReplyStatus( RequestInfoImpl.UNINITIALIZED ) ; ++ ++ // If this is a DII request, make sure we ignore the next initiate. ++ if( diiRequest ) { ++ info.setDIIInitiate( true ); ++ } ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void cleanupClientPIRequest() { +- if( !hasClientInterceptors ) return; +- if( !isClientPIEnabledForThisThread() ) return; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "cleanupClientPIRequest" ) ; ++ } + +- ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); +- +- // If the replyStatus has not yet been set, this is an indication +- // that the ORB threw an exception before we had a chance to +- // invoke the client interceptor ending points. +- // +- // _REVISIT_ We cannot handle any exceptions or ForwardRequests +- // flagged by the ending points here because there is no way +- // to gracefully handle this in any of the calling code. +- // This is a rare corner case, so we will ignore this for now. +- short replyStatus = info.getReplyStatus(); +- if( replyStatus == info.UNINITIALIZED ) { +- invokeClientPIEndingPoint( ReplyMessage.SYSTEM_EXCEPTION, +- wrapper.unknownRequestInvoke( +- CompletionStatus.COMPLETED_MAYBE ) ) ; +- } +- +- // Decrement entry count, and if it is zero, pop it from the stack. +- info.decrementEntryCount(); +- if( info.getEntryCount() == 0 ) { +- RequestInfoStack infoStack = +- threadLocalClientRequestInfoStack.get(); +- infoStack.pop(); +- printPop(); ++ try { ++ if( !hasClientInterceptors ) return; ++ if( !isClientPIEnabledForThisThread() ) return; ++ ++ ClientRequestInfoImpl info = peekClientRequestInfoImplStack(); ++ RetryType rt = info.getRetryRequest() ; ++ ++ // fix for 6763340 ++ if (!rt.equals( RetryType.BEFORE_RESPONSE )) { ++ // If the replyStatus has not yet been set, this is an indication ++ // that the ORB threw an exception before we had a chance to ++ // invoke the client interceptor ending points. ++ // ++ // _REVISIT_ We cannot handle any exceptions or ForwardRequests ++ // flagged by the ending points here because there is no way ++ // to gracefully handle this in any of the calling code. ++ // This is a rare corner case, so we will ignore this for now. ++ short replyStatus = info.getReplyStatus(); ++ if (replyStatus == info.UNINITIALIZED ) { ++ invokeClientPIEndingPoint( ReplyMessage.SYSTEM_EXCEPTION, ++ wrapper.unknownRequestInvoke( ++ CompletionStatus.COMPLETED_MAYBE ) ) ; ++ } ++ } ++ ++ // Decrement entry count, and if it is zero, pop it from the stack. ++ info.decrementEntryCount(); ++ ++ // fix for 6763340, and probably other cases (non-recursive retry) ++ if (info.getEntryCount() == 0 && !info.getRetryRequest().isRetry()) { ++ RequestInfoStack infoStack = ++ threadLocalClientRequestInfoStack.get(); ++ infoStack.pop(); ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "client infoStack was popped" ) ; ++ } ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } + } + + public void setClientPIInfo(CorbaMessageMediator messageMediator) + { +- if( !hasClientInterceptors ) return; +- if( !isClientPIEnabledForThisThread() ) return; +- +- peekClientRequestInfoImplStack().setInfo(messageMediator); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "setClientPIInfo" ) ; ++ } ++ ++ try { ++ if( !hasClientInterceptors ) return; ++ if( !isClientPIEnabledForThisThread() ) return; ++ ++ peekClientRequestInfoImplStack().setInfo(messageMediator); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void setClientPIInfo( RequestImpl requestImpl ) { +- if( !hasClientInterceptors ) return; +- if( !isClientPIEnabledForThisThread() ) return; +- +- peekClientRequestInfoImplStack().setDIIRequest( requestImpl ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "setClientPIInfo" ) ; ++ } ++ ++ try { ++ if( !hasClientInterceptors ) return; ++ if( !isClientPIEnabledForThisThread() ) return; ++ ++ peekClientRequestInfoImplStack().setDIIRequest( requestImpl ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -524,176 +703,281 @@ + * Server PI hooks + *****************/ + +- public void invokeServerPIStartingPoint() +- { +- if( !hasServerInterceptors ) return; ++ public void invokeServerPIStartingPoint() { + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- interceptorInvoker.invokeServerInterceptorStartingPoint( info ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeServerPIStartingPoint" ) ; ++ } + +- // Handle SystemException or ForwardRequest: +- serverPIHandleExceptions( info ); ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ interceptorInvoker.invokeServerInterceptorStartingPoint( info ); ++ ++ // Handle SystemException or ForwardRequest: ++ serverPIHandleExceptions( info ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- public void invokeServerPIIntermediatePoint() +- { +- if( !hasServerInterceptors ) return; ++ public void invokeServerPIIntermediatePoint() { + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- interceptorInvoker.invokeServerInterceptorIntermediatePoint( info ); +- +- // Clear servant from info object so that the user has control over +- // its lifetime: +- info.releaseServant(); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokeServerPIIntermediatePoint" ) ; ++ } + +- // Handle SystemException or ForwardRequest: +- serverPIHandleExceptions( info ); ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ interceptorInvoker.invokeServerInterceptorIntermediatePoint( info ); ++ ++ // Clear servant from info object so that the user has control over ++ // its lifetime: ++ info.releaseServant(); ++ ++ // Handle SystemException or ForwardRequest: ++ serverPIHandleExceptions( info ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- public void invokeServerPIEndingPoint( ReplyMessage replyMessage ) +- { +- if( !hasServerInterceptors ) return; +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ public void invokeServerPIEndingPoint( ReplyMessage replyMessage ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "invokerServerPIEndingPoint" ) ; ++ } + +- // REVISIT: This needs to be done "early" for the following workaround. +- info.setReplyMessage( replyMessage ); ++ try { + +- // REVISIT: This was done inside of invokeServerInterceptorEndingPoint +- // but needs to be here for now. See comment in that method for why. +- info.setCurrentExecutionPoint( info.EXECUTION_POINT_ENDING ); ++ if( !hasServerInterceptors ) return; ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); + +- // It is possible we might have entered this method more than +- // once (e.g. if an ending point threw a SystemException, then +- // a new ServerResponseImpl is created). +- if( !info.getAlreadyExecuted() ) { +- int replyStatus = replyMessage.getReplyStatus(); ++ // REVISIT: This needs to be done "early" for the following workaround. ++ info.setReplyMessage( replyMessage ); + +- // Translate ReplyMessage.replyStatus into PI replyStatus: +- // Note: this is also an assertion to make sure a valid +- // replyStatus is passed in (IndexOutOfBoundsException will be +- // thrown otherwise) +- short piReplyStatus = +- REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; ++ // REVISIT: This was done inside of invokeServerInterceptorEndingPoint ++ // but needs to be here for now. See comment in that method for why. ++ info.setCurrentExecutionPoint( info.EXECUTION_POINT_ENDING ); + +- // Make forwarded IOR available to interceptors, if applicable: +- if( ( piReplyStatus == LOCATION_FORWARD.value ) || +- ( piReplyStatus == TRANSPORT_RETRY.value ) ) +- { +- info.setForwardRequest( replyMessage.getIOR() ); +- } ++ // It is possible we might have entered this method more than ++ // once (e.g. if an ending point threw a SystemException, then ++ // a new ServerResponseImpl is created). ++ if( !info.getAlreadyExecuted() ) { ++ int replyStatus = replyMessage.getReplyStatus(); + +- // REVISIT: Do early above for now. +- // Make reply message available to interceptors: +- //info.setReplyMessage( replyMessage ); ++ // Translate ReplyMessage.replyStatus into PI replyStatus: ++ // Note: this is also an assertion to make sure a valid ++ // replyStatus is passed in (IndexOutOfBoundsException will be ++ // thrown otherwise) ++ short piReplyStatus = ++ REPLY_MESSAGE_TO_PI_REPLY_STATUS[replyStatus]; + +- // Remember exception so we can tell if an interceptor changed it. +- Exception prevException = info.getException(); ++ // Make forwarded IOR available to interceptors, if applicable: ++ if( ( piReplyStatus == LOCATION_FORWARD.value ) || ++ ( piReplyStatus == TRANSPORT_RETRY.value ) ) ++ { ++ info.setForwardRequest( replyMessage.getIOR() ); ++ } + +- // _REVISIT_ We do not have access to the User Exception at +- // this point, so treat it as an UNKNOWN for now. +- // Note that if this is a DSI call, we do have the user exception. +- if( !info.isDynamic() && +- (piReplyStatus == USER_EXCEPTION.value) ) +- { +- info.setException( omgWrapper.unknownUserException( +- CompletionStatus.COMPLETED_MAYBE ) ) ; +- } +- +- // Invoke the ending interception points: +- info.setReplyStatus( piReplyStatus ); +- interceptorInvoker.invokeServerInterceptorEndingPoint( info ); +- short newPIReplyStatus = info.getReplyStatus(); +- Exception newException = info.getException(); +- +- // Check reply status. If an interceptor threw a SystemException +- // and it is different than the one that we came in with, +- // rethrow it so the proper response can be constructed: +- if( ( newPIReplyStatus == SYSTEM_EXCEPTION.value ) && +- ( newException != prevException ) ) +- { +- throw (SystemException)newException; ++ // REVISIT: Do early above for now. ++ // Make reply message available to interceptors: ++ //info.setReplyMessage( replyMessage ); ++ ++ // Remember exception so we can tell if an interceptor changed it. ++ Exception prevException = info.getException(); ++ ++ // _REVISIT_ We do not have access to the User Exception at ++ // this point, so treat it as an UNKNOWN for now. ++ // Note that if this is a DSI call, we do have the user exception. ++ if( !info.isDynamic() && ++ (piReplyStatus == USER_EXCEPTION.value) ) ++ { ++ info.setException( omgWrapper.unknownUserException( ++ CompletionStatus.COMPLETED_MAYBE ) ) ; ++ } ++ ++ // Invoke the ending interception points: ++ info.setReplyStatus( piReplyStatus ); ++ interceptorInvoker.invokeServerInterceptorEndingPoint( info ); ++ short newPIReplyStatus = info.getReplyStatus(); ++ Exception newException = info.getException(); ++ ++ // Check reply status. If an interceptor threw a SystemException ++ // and it is different than the one that we came in with, ++ // rethrow it so the proper response can be constructed: ++ if( ( newPIReplyStatus == SYSTEM_EXCEPTION.value ) && ++ ( newException != prevException ) ) ++ { ++ throw (SystemException)newException; ++ } ++ ++ // If we are to forward the location: ++ if( newPIReplyStatus == LOCATION_FORWARD.value ) { ++ if( piReplyStatus != LOCATION_FORWARD.value ) { ++ // Treat a ForwardRequest as a ForwardException. ++ IOR ior = info.getForwardRequestIOR(); ++ throw new ForwardException( orb, ior ) ; ++ } ++ else if( info.isForwardRequestRaisedInEnding() ) { ++ // Treat a ForwardRequest by changing the IOR. ++ replyMessage.setIOR( info.getForwardRequestIOR() ); ++ } ++ } + } +- +- // If we are to forward the location: +- if( newPIReplyStatus == LOCATION_FORWARD.value ) { +- if( piReplyStatus != LOCATION_FORWARD.value ) { +- // Treat a ForwardRequest as a ForwardException. +- IOR ior = info.getForwardRequestIOR(); +- throw new ForwardException( orb, ior ) ; +- } +- else if( info.isForwardRequestRaisedInEnding() ) { +- // Treat a ForwardRequest by changing the IOR. +- replyMessage.setIOR( info.getForwardRequestIOR() ); +- } +- } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } + } + + public void setServerPIInfo( Exception exception ) { +- if( !hasServerInterceptors ) return; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "setServerPIInfo" ) ; ++ } + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- info.setException( exception ); ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ info.setException( exception ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- public void setServerPIInfo( NVList arguments ) +- { +- if( !hasServerInterceptors ) return; ++ public void setServerPIInfo( NVList arguments ) { + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- info.setDSIArguments( arguments ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "setServerPIInfo" ) ; ++ } ++ ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ info.setDSIArguments( arguments ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- public void setServerPIExceptionInfo( Any exception ) +- { +- if( !hasServerInterceptors ) return; ++ public void setServerPIExceptionInfo( Any exception ) { + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- info.setDSIException( exception ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "SetServerPIExceptionInfo" ) ; ++ } ++ ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ info.setDSIException( exception ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + +- public void setServerPIInfo( Any result ) +- { +- if( !hasServerInterceptors ) return; ++ public void setServerPIInfo( Any result ) { + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- info.setDSIResult( result ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "setServerPIInfo" ) ; ++ } ++ ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ info.setDSIResult( result ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void initializeServerPIInfo( CorbaMessageMediator request, +- ObjectAdapter oa, byte[] objectId, ObjectKeyTemplate oktemp ) +- { +- if( !hasServerInterceptors ) return; ++ ObjectAdapter oa, byte[] objectId, ObjectKeyTemplate oktemp ) { + +- RequestInfoStack infoStack = +- threadLocalServerRequestInfoStack.get(); +- ServerRequestInfoImpl info = new ServerRequestInfoImpl( orb ); +- infoStack.push( info ); +- printPush(); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "initializeServerPIInfo" ) ; ++ } + +- // Notify request object that once response is constructed, make +- // sure we execute ending points. +- request.setExecutePIInResponseConstructor( true ); ++ try { + +- info.setInfo( request, oa, objectId, oktemp ); ++ if( !hasServerInterceptors ) return; ++ ++ RequestInfoStack infoStack = ++ threadLocalServerRequestInfoStack.get(); ++ ServerRequestInfoImpl info = new ServerRequestInfoImpl( orb ); ++ infoStack.push( info ); ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "server infoStack was pushed" ) ; ++ } ++ ++ // Notify request object that once response is constructed, make ++ // sure we execute ending points. ++ request.setExecutePIInResponseConstructor( true ); ++ ++ info.setInfo( request, oa, objectId, oktemp ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void setServerPIInfo( java.lang.Object servant, +- String targetMostDerivedInterface ) +- { +- if( !hasServerInterceptors ) return; ++ String targetMostDerivedInterface ) { + +- ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); +- info.setInfo( servant, targetMostDerivedInterface ); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "setServerPIInfo" ) ; ++ } ++ ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ ServerRequestInfoImpl info = peekServerRequestInfoImplStack(); ++ info.setInfo( servant, targetMostDerivedInterface ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public void cleanupServerPIRequest() { +- if( !hasServerInterceptors ) return; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "cleanupServerPIRequest" ) ; ++ } + +- RequestInfoStack infoStack = +- threadLocalServerRequestInfoStack.get(); +- infoStack.pop(); +- printPop(); ++ try { ++ if( !hasServerInterceptors ) return; ++ ++ RequestInfoStack infoStack = ++ threadLocalServerRequestInfoStack.get(); ++ infoStack.pop(); ++ if (orb.interceptorDebugFlag) { ++ dputil.info( "server infoStack was popped" ) ; ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /* +@@ -708,20 +992,29 @@ + *

                      + * This method will NOT work for ending points. + */ +- private void serverPIHandleExceptions( ServerRequestInfoImpl info ) +- { +- int endingPointCall = info.getEndingPointCall(); +- if(endingPointCall == ServerRequestInfoImpl.CALL_SEND_EXCEPTION) { +- // If a system exception was thrown, throw it to caller: +- throw (SystemException)info.getException(); ++ private void serverPIHandleExceptions( ServerRequestInfoImpl info ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "serverPIHandleExceptions" ) ; + } +- else if( (endingPointCall == ServerRequestInfoImpl.CALL_SEND_OTHER) && +- (info.getForwardRequestException() != null) ) +- { +- // If an interceptor throws a forward request, convert it +- // into a ForwardException for easier handling: +- IOR ior = info.getForwardRequestIOR(); +- throw new ForwardException( orb, ior ); ++ ++ try { ++ int endingPointCall = info.getEndingPointCall(); ++ if(endingPointCall == ServerRequestInfoImpl.CALL_SEND_EXCEPTION) { ++ // If a system exception was thrown, throw it to caller: ++ throw (SystemException)info.getException(); ++ } ++ else if( (endingPointCall == ServerRequestInfoImpl.CALL_SEND_OTHER) && ++ (info.getForwardRequestException() != null) ) ++ { ++ // If an interceptor throws a forward request, convert it ++ // into a ForwardException for easier handling: ++ IOR ior = info.getForwardRequestIOR(); ++ throw new ForwardException( orb, ior ); ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } + } + +@@ -733,14 +1026,24 @@ + * conditions. + */ + private int convertPIReplyStatusToReplyMessage( short replyStatus ) { +- int result = 0; +- for( int i = 0; i < REPLY_MESSAGE_TO_PI_REPLY_STATUS.length; i++ ) { +- if( REPLY_MESSAGE_TO_PI_REPLY_STATUS[i] == replyStatus ) { +- result = i; +- break; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "convertPIReplyStatusToReplyMessage" ) ; ++ } ++ ++ try { ++ int result = 0; ++ for( int i = 0; i < REPLY_MESSAGE_TO_PI_REPLY_STATUS.length; i++ ) { ++ if( REPLY_MESSAGE_TO_PI_REPLY_STATUS[i] == replyStatus ) { ++ result = i; ++ break; ++ } ++ } ++ return result; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; + } + } +- return result; + } + + /** +@@ -749,16 +1052,26 @@ + * the Info stack is empty. + */ + private ClientRequestInfoImpl peekClientRequestInfoImplStack() { +- RequestInfoStack infoStack = +- threadLocalClientRequestInfoStack.get(); +- ClientRequestInfoImpl info = null; +- if( !infoStack.empty() ) { +- info = infoStack.peek(); +- } else { +- throw wrapper.clientInfoStackNull() ; +- } +- +- return info; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "peekClientRequestInfoImplStack" ) ; ++ } ++ ++ try { ++ RequestInfoStack infoStack = ++ threadLocalClientRequestInfoStack.get(); ++ ClientRequestInfoImpl info = null; ++ if( !infoStack.empty() ) { ++ info = infoStack.peek(); ++ } else { ++ throw wrapper.clientInfoStackNull() ; ++ } ++ ++ return info; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -766,17 +1079,27 @@ + * top of the ThreadLocal stack. Returns null if there are none. + */ + private ServerRequestInfoImpl peekServerRequestInfoImplStack() { +- RequestInfoStack infoStack = +- threadLocalServerRequestInfoStack.get(); +- ServerRequestInfoImpl info = null; +- +- if( !infoStack.empty() ) { +- info = infoStack.peek(); +- } else { +- throw wrapper.serverInfoStackNull() ; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "peekServerRequestInfoImplStack" ) ; + } + +- return info; ++ try { ++ RequestInfoStack infoStack = ++ threadLocalServerRequestInfoStack.get(); ++ ServerRequestInfoImpl info = null; ++ ++ if( !infoStack.empty() ) { ++ info = infoStack.peek(); ++ } else { ++ throw wrapper.serverInfoStackNull() ; ++ } ++ ++ return info; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -784,59 +1107,89 @@ + * for requests on this thread. + */ + private boolean isClientPIEnabledForThisThread() { +- RequestInfoStack infoStack = +- threadLocalClientRequestInfoStack.get(); +- return (infoStack.disableCount == 0); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "isClientPIEnabledForThisThread" ) ; ++ } ++ ++ try { ++ RequestInfoStack infoStack = ++ threadLocalClientRequestInfoStack.get(); ++ return (infoStack.disableCount == 0); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * Call pre_init on all ORB initializers + */ + private void preInitORBInitializers( ORBInitInfoImpl info ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "perInitORBInitializers" ) ; ++ } + +- // Inform ORBInitInfo we are in pre_init stage +- info.setStage( ORBInitInfoImpl.STAGE_PRE_INIT ); ++ try { + +- // Step through each initializer instantiation and call its +- // pre_init. Ignore any exceptions. +- for( int i = 0; i < orb.getORBData().getORBInitializers().length; +- i++ ) { +- ORBInitializer init = orb.getORBData().getORBInitializers()[i]; +- if( init != null ) { +- try { +- init.pre_init( info ); +- } +- catch( Exception e ) { +- // As per orbos/99-12-02, section 9.3.1.2, "If there are +- // any exceptions, the ORB shall ignore them and proceed." +- } +- } +- } ++ // Inform ORBInitInfo we are in pre_init stage ++ info.setStage( ORBInitInfoImpl.STAGE_PRE_INIT ); ++ ++ // Step through each initializer instantiation and call its ++ // pre_init. Ignore any exceptions. ++ for( int i = 0; i < orb.getORBData().getORBInitializers().length; ++ i++ ) { ++ ORBInitializer init = orb.getORBData().getORBInitializers()[i]; ++ if( init != null ) { ++ try { ++ init.pre_init( info ); ++ } ++ catch( Exception e ) { ++ // As per orbos/99-12-02, section 9.3.1.2, "If there are ++ // any exceptions, the ORB shall ignore them and proceed." ++ } ++ } ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** + * Call post_init on all ORB initializers + */ + private void postInitORBInitializers( ORBInitInfoImpl info ) { ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "postInitORBInitializers" ) ; ++ } + +- // Inform ORBInitInfo we are in post_init stage +- info.setStage( ORBInitInfoImpl.STAGE_POST_INIT ); ++ try { + +- // Step through each initializer instantiation and call its post_init. +- // Ignore any exceptions. +- for( int i = 0; i < orb.getORBData().getORBInitializers().length; +- i++ ) { +- ORBInitializer init = orb.getORBData().getORBInitializers()[i]; +- if( init != null ) { +- try { +- init.post_init( info ); +- } +- catch( Exception e ) { +- // As per orbos/99-12-02, section 9.3.1.2, "If there are +- // any exceptions, the ORB shall ignore them and proceed." +- } +- } +- } ++ // Inform ORBInitInfo we are in post_init stage ++ info.setStage( ORBInitInfoImpl.STAGE_POST_INIT ); ++ ++ // Step through each initializer instantiation and call its post_init. ++ // Ignore any exceptions. ++ for( int i = 0; i < orb.getORBData().getORBInitializers().length; ++ i++ ) { ++ ORBInitializer init = orb.getORBData().getORBInitializers()[i]; ++ if( init != null ) { ++ try { ++ init.post_init( info ); ++ } ++ catch( Exception e ) { ++ // As per orbos/99-12-02, section 9.3.1.2, "If there are ++ // any exceptions, the ORB shall ignore them and proceed." ++ } ++ } ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -844,18 +1197,28 @@ + * pre_init and post_init methods + */ + private ORBInitInfoImpl createORBInitInfo() { +- ORBInitInfoImpl result = null; +- +- // arguments comes from set_parameters. May be null. ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "createORBInitInfo" ) ; ++ } + +- // _REVISIT_ The spec does not specify which ID this is to be. +- // We currently get this from the corba.ORB, which reads it from +- // the ORB_ID_PROPERTY property. +- String orbId = orb.getORBData().getORBId() ; ++ try { ++ ORBInitInfoImpl result = null; ++ ++ // arguments comes from set_parameters. May be null. + +- result = new ORBInitInfoImpl( orb, arguments, orbId, codecFactory ); ++ // _REVISIT_ The spec does not specify which ID this is to be. ++ // We currently get this from the corba.ORB, which reads it from ++ // the ORB_ID_PROPERTY property. ++ String orbId = orb.getORBData().getORBId() ; + +- return result; ++ result = new ORBInitInfoImpl( orb, arguments, orbId, codecFactory ); ++ ++ return result; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + /** +@@ -871,22 +1234,32 @@ + * name already exists for the given type. + */ + public void register_interceptor( Interceptor interceptor, int type ) +- throws DuplicateName +- { +- // We will assume interceptor is not null, since it is called +- // internally. +- if( (type >= InterceptorList.NUM_INTERCEPTOR_TYPES) || (type < 0) ) { +- throw wrapper.typeOutOfRange( Integer.valueOf( type ) ) ; +- } ++ throws DuplicateName { + +- String interceptorName = interceptor.name(); +- +- if( interceptorName == null ) { +- throw wrapper.nameNull() ; ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "register_interceptor" ) ; + } + +- // Register with interceptor list: +- interceptorList.register_interceptor( interceptor, type ); ++ try { ++ // We will assume interceptor is not null, since it is called ++ // internally. ++ if( (type >= InterceptorList.NUM_INTERCEPTOR_TYPES) || (type < 0) ) { ++ throw wrapper.typeOutOfRange( Integer.valueOf( type ) ) ; ++ } ++ ++ String interceptorName = interceptor.name(); ++ ++ if( interceptorName == null ) { ++ throw wrapper.nameNull() ; ++ } ++ ++ // Register with interceptor list: ++ interceptorList.register_interceptor( interceptor, type ); ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } ++ } + } + + public Current getPICurrent( ) { +@@ -912,27 +1285,37 @@ + * this method to com.sun.corba.ee.spi.orb.ORB. + */ + public org.omg.CORBA.Policy create_policy(int type, org.omg.CORBA.Any val) +- throws org.omg.CORBA.PolicyError +- { +- if( val == null ) { +- nullParam( ); ++ throws org.omg.CORBA.PolicyError { ++ ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "create_policy" ) ; + } + +- if( policyFactoryTable == null ) { +- throw new org.omg.CORBA.PolicyError( +- "There is no PolicyFactory Registered for type " + type, +- BAD_POLICY.value ); ++ try { ++ if( val == null ) { ++ nullParam( ); ++ } ++ ++ if( policyFactoryTable == null ) { ++ throw new org.omg.CORBA.PolicyError( ++ "There is no PolicyFactory Registered for type " + type, ++ BAD_POLICY.value ); ++ } ++ ++ PolicyFactory factory = policyFactoryTable.get( type ); ++ if( factory == null ) { ++ throw new org.omg.CORBA.PolicyError( ++ " Could Not Find PolicyFactory for the Type " + type, ++ BAD_POLICY.value); ++ } ++ ++ org.omg.CORBA.Policy policy = factory.create_policy( type, val ); ++ return policy; ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } +- +- PolicyFactory factory = policyFactoryTable.get( type ); +- if( factory == null ) { +- throw new org.omg.CORBA.PolicyError( +- " Could Not Find PolicyFactory for the Type " + type, +- BAD_POLICY.value); +- } +- +- org.omg.CORBA.Policy policy = factory.create_policy( type, val ); +- return policy; + } + + /** This method registers the Policy Factory in the policyFactoryTable, +@@ -940,15 +1323,25 @@ + * it is used internally by the Interceptors. + */ + public void registerPolicyFactory( int type, PolicyFactory factory ) { +- if( policyFactoryTable == null ) { +- policyFactoryTable = new HashMap(); ++ if (orb.interceptorDebugFlag) { ++ dputil.enter( "registerPolicyFactory" ) ; + } +- Integer key = Integer.valueOf( type ); +- PolicyFactory val = policyFactoryTable.get( key ); +- if (val == null) { +- policyFactoryTable.put( key, factory ); +- } else { +- throw omgWrapper.policyFactoryRegFailed( Integer.valueOf( type ) ) ; ++ ++ try { ++ if( policyFactoryTable == null ) { ++ policyFactoryTable = new HashMap(); ++ } ++ Integer key = Integer.valueOf( type ); ++ PolicyFactory val = policyFactoryTable.get( key ); ++ if (val == null) { ++ policyFactoryTable.put( key, factory ); ++ } else { ++ throw omgWrapper.policyFactoryRegFailed( Integer.valueOf( type ) ) ; ++ } ++ } finally { ++ if (orb.interceptorDebugFlag) { ++ dputil.exit() ; ++ } + } + } + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/interceptors/PINoOpHandlerImpl.java +--- a/src/share/classes/com/sun/corba/ee/impl/interceptors/PINoOpHandlerImpl.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/interceptors/PINoOpHandlerImpl.java Mon Jul 06 12:05:55 2009 -0700 +@@ -120,6 +120,12 @@ + { + return null; + } ++ ++ public Exception makeCompletedClientRequest( ++ int replyStatus, Exception exception ) ++ { ++ return null; ++ } + + public void initiateClientPIRequest( boolean diiRequest ) { + } +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/interceptors/RequestInfoImpl.java +--- a/src/share/classes/com/sun/corba/ee/impl/interceptors/RequestInfoImpl.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/interceptors/RequestInfoImpl.java Mon Jul 06 12:05:55 2009 -0700 +@@ -41,40 +41,26 @@ + import java.lang.reflect.InvocationTargetException ; + + import java.util.Map ; +-import java.util.HashMap ; + + import org.omg.PortableInterceptor.ForwardRequest; + import org.omg.PortableInterceptor.InvalidSlot; + import org.omg.PortableInterceptor.RequestInfo; +-import org.omg.PortableInterceptor.LOCATION_FORWARD; +-import org.omg.IOP.TaggedProfile; +-import org.omg.IOP.TaggedComponent; + import org.omg.IOP.ServiceContextHelper; + import org.omg.Messaging.SYNC_WITH_TRANSPORT; + import org.omg.CORBA.ParameterMode; + + import org.omg.CORBA.Any; + import org.omg.CORBA.BAD_INV_ORDER; +-import org.omg.CORBA.BAD_PARAM; + import org.omg.CORBA.CompletionStatus; +-import org.omg.CORBA.Context; +-import org.omg.CORBA.ContextList; +-import org.omg.CORBA.CTX_RESTRICT_SCOPE; +-import org.omg.CORBA.ExceptionList; +-import org.omg.CORBA.INTERNAL; + import org.omg.CORBA.LocalObject; + import org.omg.CORBA.NamedValue; +-import org.omg.CORBA.NO_IMPLEMENT; +-import org.omg.CORBA.NO_RESOURCES; + import org.omg.CORBA.NVList; + import org.omg.CORBA.Object; +-import org.omg.CORBA.Policy; + import org.omg.CORBA.SystemException; + import org.omg.CORBA.TypeCode; + import org.omg.CORBA.UNKNOWN; + import org.omg.CORBA.UserException; + import org.omg.CORBA.portable.ApplicationException; +-import org.omg.CORBA.portable.Delegate; + import org.omg.CORBA.portable.InputStream; + + import org.omg.Dynamic.Parameter; +@@ -95,10 +81,10 @@ + + import com.sun.corba.ee.spi.orbutil.ORBClassLoader; + +-import com.sun.corba.ee.impl.encoding.CDRInputStream_1_0; + import com.sun.corba.ee.impl.encoding.EncapsOutputStream; + + import com.sun.corba.ee.impl.orbutil.ORBUtility; ++import com.sun.corba.ee.impl.orbutil.DprintUtil; + + import com.sun.corba.ee.impl.util.RepositoryId; + +@@ -121,6 +107,7 @@ + + // The ORB from which to get PICurrent and other info + protected ORB myORB; ++ protected DprintUtil dputil ; + protected InterceptorsSystemException wrapper ; + protected OMGSystemException stdWrapper ; + +@@ -199,7 +186,7 @@ + startingPointCall = 0; + intermediatePointCall = 0; + endingPointCall = 0; +- replyStatus = UNINITIALIZED; ++ setReplyStatus( UNINITIALIZED ) ; + currentExecutionPoint = EXECUTION_POINT_STARTING; + alreadyExecuted = false; + connection = null; +@@ -249,6 +236,7 @@ + super(); + + this.myORB = myORB; ++ dputil = new DprintUtil(this) ; + wrapper = myORB.getLogWrapperTable().get_RPC_PROTOCOL_Interceptors() ; + stdWrapper = myORB.getLogWrapperTable().get_RPC_PROTOCOL_OMG() ; + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/orb/ORBImpl.java +--- a/src/share/classes/com/sun/corba/ee/impl/orb/ORBImpl.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/orb/ORBImpl.java Mon Jul 06 12:05:55 2009 -0700 +@@ -1948,7 +1948,9 @@ + } + clientInvocationInfo.decrementEntryCount(); + entryCount = clientInvocationInfo.getEntryCount(); +- if (clientInvocationInfo.getEntryCount() == 0) { ++ if (clientInvocationInfo.getEntryCount() == 0 ++ && !clientInvocationInfo.isRetryInvocation()) { ++ + invocationInfoStack.pop(); + if (subcontractDebugFlag) { + dprint(".releaseOrDecrementInvocationInfo: pop"); +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/orbutil/ORBUtility.java +--- a/src/share/classes/com/sun/corba/ee/impl/orbutil/ORBUtility.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/orbutil/ORBUtility.java Mon Jul 06 12:05:55 2009 -0700 +@@ -272,8 +272,6 @@ + + private static ValueHandler vhandler = + new ValueHandlerImpl() ; +- private static ValueHandler vhandler_1_3_1 = +- new ValueHandlerImpl_1_3_1() ; + + /** + * Creates the correct ValueHandler for the given ORB, +@@ -282,18 +280,6 @@ + * Util.createValueHandler. + */ + public static ValueHandler createValueHandler(ORB orb) { +- +- if (orb == null) +- return vhandler; +- +- ORBVersion version = orb.getORBVersion(); +- +- if (version == null) +- return vhandler; +- +- if (version.equals(ORBVersionFactory.getNEW())) +- return vhandler_1_3_1; +- + return vhandler; + } + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/orbutil/RepIdDelegator.java +--- a/src/share/classes/com/sun/corba/ee/impl/orbutil/RepIdDelegator.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/orbutil/RepIdDelegator.java Mon Jul 06 12:05:55 2009 -0700 +@@ -36,11 +36,9 @@ + + package com.sun.corba.ee.impl.orbutil; + +-import org.omg.CORBA.ORB; + + import java.io.Serializable; + +-import java.util.Hashtable; + + import java.net.MalformedURLException; + +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/orbutil/RepositoryIdFactory.java +--- a/src/share/classes/com/sun/corba/ee/impl/orbutil/RepositoryIdFactory.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/orbutil/RepositoryIdFactory.java Mon Jul 06 12:05:55 2009 -0700 +@@ -36,14 +36,10 @@ + + package com.sun.corba.ee.impl.orbutil; + +-import com.sun.corba.ee.spi.orb.ORBVersion; + import com.sun.corba.ee.spi.orb.ORB; + + public abstract class RepositoryIdFactory + { +- private static final RepIdDelegator_1_3_1 ladybirdDelegator +- = new RepIdDelegator_1_3_1(); +- + private static final RepIdDelegator currentDelegator + = new RepIdDelegator(); + +@@ -61,19 +57,7 @@ + */ + public static RepositoryIdStrings getRepIdStringsFactory(ORB orb) + { +- if (orb != null) { +- switch (orb.getORBVersion().getORBType()) { +- case ORBVersion.NEWER: +- case ORBVersion.FOREIGN: +- case ORBVersion.JDK1_3_1_01: +- return currentDelegator; +- case ORBVersion.NEW: +- return ladybirdDelegator; +- default: +- return currentDelegator; +- } +- } else +- return currentDelegator; ++ return currentDelegator; + } + + /** +@@ -90,18 +74,6 @@ + */ + public static RepositoryIdUtility getRepIdUtility(ORB orb) + { +- if (orb != null) { +- switch (orb.getORBVersion().getORBType()) { +- case ORBVersion.NEWER: +- case ORBVersion.FOREIGN: +- case ORBVersion.JDK1_3_1_01: +- return currentDelegator; +- case ORBVersion.NEW: +- return ladybirdDelegator; +- default: +- return currentDelegator; +- } +- } else +- return currentDelegator; ++ return currentDelegator; + } + } +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/impl/protocol/CorbaClientRequestDispatcherImpl.java +--- a/src/share/classes/com/sun/corba/ee/impl/protocol/CorbaClientRequestDispatcherImpl.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/impl/protocol/CorbaClientRequestDispatcherImpl.java Mon Jul 06 12:05:55 2009 -0700 +@@ -120,6 +120,8 @@ + import com.sun.corba.ee.spi.orbutil.ORBConstants; + import com.sun.corba.ee.impl.orbutil.newtimer.generated.TimingPoints; + ++import com.sun.corba.ee.impl.orbutil.DprintUtil; ++ + import com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage; + import com.sun.corba.ee.impl.protocol.giopmsgheaders.KeyAddr; + import com.sun.corba.ee.impl.protocol.giopmsgheaders.ProfileAddr; +@@ -137,6 +139,8 @@ + { + // Used for locking + private Object lock = new Object(); ++ private DprintUtil dputil = new DprintUtil( this ) ; ++ + private ORBVersionServiceContext ovsc = + ServiceContextDefaults.makeORBVersionServiceContext(); + +@@ -147,26 +151,21 @@ + public OutputObject beginRequest(Object self, String opName, + boolean isOneWay, ContactInfo contactInfo) { + +- ORB orb = null; +- TimingPoints tp = null ; ++ final CorbaContactInfo corbaContactInfo = (CorbaContactInfo) contactInfo; ++ final ORB orb = (ORB)contactInfo.getBroker(); ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.enter("beginRequest", "op", opName, "isOneWay", isOneWay, ++ "contactInfo", contactInfo ); ++ } ++ ++ final TimingPoints tp = orb.getTimerManager().points() ; + try { +- CorbaContactInfo corbaContactInfo = (CorbaContactInfo) contactInfo; +- orb = (ORB)contactInfo.getBroker(); +- tp = orb.getTimerManager().points() ; + tp.enter_totalRequest() ; + +- if (orb.subcontractDebugFlag) { +- dprint(".beginRequest->: op/" + opName); +- } +- +- // + // Portable Interceptor initialization. +- // + orb.getPIHandler().initiateClientPIRequest( false ); + +- // +- // Connection. +- // + CorbaConnection connection = null; + + // This locking is done so that multiple connections are not created +@@ -174,7 +173,6 @@ + synchronized (lock) { + if (contactInfo.isConnectionBased()) { + try { +- + tp.enter_connectionSetup(); + + if (contactInfo.shouldCacheConnection()) { +@@ -184,22 +182,23 @@ + + if (connection != null) { + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest: op/" + opName +- + ": Using cached connection: " + connection); ++ dputil.info( "Using cached connection", connection); + } + } else { + connection = (CorbaConnection) + contactInfo.createConnection(); + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest: op/" + opName +- + ": Using created connection: " + connection); ++ dputil.info( "Using created connection", connection); + } + + if (connection.shouldRegisterReadEvent()) { +- // REVISIT: cast + orb.getTransportManager().getSelector(0) + .registerForEvent(connection.getEventHandler()); + connection.setState("ESTABLISHED"); ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "connection registered" ) ; ++ } + } + + // Do not do connection reclaim here since the connections +@@ -211,22 +210,24 @@ + .getOutboundConnectionCache(contactInfo); + connectionCache.stampTime(connection); + connectionCache.put(contactInfo, connection); +- // connectionCache.reclaim(); +- } +- } +- } finally { ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "connection cached" ) ; ++ } ++ } ++ } ++ } finally { + tp.exit_connectionSetup(); + } +- } +- } ++ } ++ } + + CorbaMessageMediator messageMediator = + (CorbaMessageMediator)contactInfo.createMessageMediator( + orb, contactInfo, connection, opName, isOneWay); + + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest: " + opAndId(messageMediator) +- + ": created message mediator: " + messageMediator); ++ dputil.info( "created message mediator", messageMediator); + } + + // NOTE: Thread data so we can get the mediator in release reply +@@ -252,10 +253,8 @@ + OutputObject outputObject = contactInfo.createOutputObject(messageMediator); + + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest: " + opAndId(messageMediator) +- + ": created output object: " + outputObject); ++ dputil.info( "created output object", outputObject ); + } +- + + // NOTE: Not necessary for oneways, but useful for debugging. + // This must be done BEFORE message initialization since fragments +@@ -266,6 +265,9 @@ + synchronized (lock) { + if (contactInfo.isConnectionBased()) { + if (contactInfo.shouldCacheConnection()) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "reclaiming connections" ); ++ } + OutboundConnectionCache connectionCache = orb.getTransportManager() + .getOutboundConnectionCache(contactInfo); + connectionCache.reclaim(); +@@ -281,8 +283,7 @@ + orb.getPIHandler().invokeClientPIStartingPoint(); + } catch( RemarshalException e ) { + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest: " + opAndId(messageMediator) +- + ": Remarshal"); ++ dputil.info( "Remarshal" ) ; + } + + // NOTE: We get here because an interceptor raised ForwardRequest +@@ -300,8 +301,21 @@ + // Want to move that update to here. + if (getContactInfoListIterator(orb).hasNext()) { + contactInfo = (ContactInfo)getContactInfoListIterator(orb).next(); ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "RemarshalException: hasNext true", ++ "contact info", contactInfo ) ; ++ } ++ ++ // Fix for 6763340: Complete the first attempt before starting another. ++ orb.getPIHandler().makeCompletedClientRequest( ++ ReplyMessage.LOCATION_FORWARD, null ) ; ++ orb.getPIHandler().cleanupClientPIRequest() ; ++ + return beginRequest(self, opName, isOneWay, contactInfo); + } else { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "RemarshalException: hasNext false" ) ; ++ } + ORBUtilSystemException wrapper = + orb.getLogWrapperTable().get_RPC_PROTOCOL_ORBUtil() ; + throw wrapper.remarshalWithNowhereToGo(); +@@ -310,8 +324,7 @@ + + messageMediator.initializeMessage(); + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest: " + opAndId(messageMediator) +- + ": initialized message"); ++ dputil.info( "initialized message"); + } + + tp.enter_clientEncoding(); +@@ -320,7 +333,7 @@ + + } finally { + if (orb.subcontractDebugFlag) { +- dprint(".beginRequest<-: op/" + opName); ++ dputil.exit() ; + } + } + } +@@ -331,28 +344,22 @@ + ApplicationException, + org.omg.CORBA.portable.RemarshalException + { +- ORB orb = null; +- TimingPoints tp = null; +- CorbaMessageMediator messageMediator = null; ++ CorbaMessageMediator messageMediator = (CorbaMessageMediator) ++ outputObject.getMessageMediator(); ++ ORB orb = (ORB) messageMediator.getBroker(); ++ TimingPoints tp = orb.getTimerManager().points() ; ++ if (orb.subcontractDebugFlag) { ++ dputil.enter( "marshalingComplete", "self", self, ++ opAndId( messageMediator ) ) ; ++ } ++ + try { +- messageMediator = (CorbaMessageMediator) +- outputObject.getMessageMediator(); ++ tp.exit_clientEncoding(); ++ tp.enter_clientTransportAndWait(); + +- orb = (ORB) messageMediator.getBroker(); +- tp = orb.getTimerManager().points() ; +- +- tp.exit_clientEncoding(); +- +- +- if (orb.subcontractDebugFlag) { +- dprint(".marshalingComplete->: " + opAndId(messageMediator)); +- } +- +- tp.enter_clientTransportAndWait(); + InputObject inputObject = null ; + try { +- inputObject = +- marshalingComplete1(orb, messageMediator); ++ inputObject = marshalingComplete1(orb, messageMediator); + } finally { + tp.exit_clientTransportAndWait(); + } +@@ -364,7 +371,7 @@ + tp.enter_clientDecoding() ; + + if (orb.subcontractDebugFlag) { +- dprint(".marshalingComplete<-: " + opAndId(messageMediator)); ++ dputil.exit(); + } + } + } +@@ -375,21 +382,17 @@ + ApplicationException, + org.omg.CORBA.portable.RemarshalException + { ++ if (orb.subcontractDebugFlag) { ++ dputil.enter("marshalingComplete1", opAndId(messageMediator) ) ; ++ } ++ + try { + messageMediator.finishSendingRequest(); + ++ return messageMediator.waitForResponse(); ++ } catch (RuntimeException e) { + if (orb.subcontractDebugFlag) { +- dprint(".marshalingComplete: " + opAndId(messageMediator) +- + ": finished sending request"); +- } +- +- return messageMediator.waitForResponse(); +- +- } catch (RuntimeException e) { +- +- if (orb.subcontractDebugFlag) { +- dprint(".marshalingComplete: " + opAndId(messageMediator) +- + ": exception: " + e.toString()); ++ dputil.info( "exception", e.toString()); + } + + boolean retry = +@@ -404,22 +407,44 @@ + + if (retry) { + if (newException == e) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Retry true; same exception" ) ; ++ } ++ + continueOrThrowSystemOrRemarshal(messageMediator, + new RemarshalException()); + } else { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Retry true; new exception" ) ; ++ } ++ + continueOrThrowSystemOrRemarshal(messageMediator, + newException); + } + } else { + // NOTE: Interceptor ending point will run in releaseReply. +- if (newException instanceof RuntimeException) ++ if (newException instanceof RuntimeException) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Retry false; RuntimeException" ) ; ++ } ++ + throw (RuntimeException)newException ; +- else ++ } else { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Retry false; other exception" ) ; ++ } ++ + // XXX Not sure what to do in this case, or if it is even possible. + throw e ; +- } ++ } ++ } ++ + return null; // for compiler +- } ++ } finally { ++ if (orb.subcontractDebugFlag) { ++ dputil.exit(); ++ } ++ } + } + + protected InputObject processResponse(ORB orb, +@@ -434,8 +459,7 @@ + orb.getLogWrapperTable().get_RPC_PROTOCOL_ORBUtil() ; + + if (orb.subcontractDebugFlag) { +- dprint(".processResponse: " + opAndId(messageMediator) +- + ": response received"); ++ dputil.enter("processResponse", opAndId(messageMediator) ) ; + } + + tp.enter_processResponse() ; +@@ -443,6 +467,9 @@ + // We know for sure now that we've sent a message. + // So OK to not send initial again. + if (messageMediator.getConnection() != null) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Non-null connection" ) ; ++ } + ((CorbaConnection)messageMediator.getConnection()) + .setPostInitialContexts(); + } +@@ -455,11 +482,17 @@ + Exception exception = null; + + if (messageMediator.isOneWay()) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "One way request" ) ; ++ } + getContactInfoListIterator(orb) + .reportSuccess(messageMediator.getContactInfo()); + // Invoke Portable Interceptors with receive_other + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.NO_EXCEPTION, exception ); ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "One way request", "exception", exception ) ; ++ } + continueOrThrowSystemOrRemarshal(messageMediator, exception); + return null; + } +@@ -472,12 +505,9 @@ + ((CDRInputObject)inputObject).performORBVersionSpecificInit(); + + if (messageMediator.isSystemExceptionReply()) { +- + SystemException se = messageMediator.getSystemExceptionReply(); +- + if (orb.subcontractDebugFlag) { +- dprint(".processResponse: " + opAndId(messageMediator) +- + ": received system exception: " + se); ++ dputil.info( "received system exception", se); + } + + boolean doRemarshal = +@@ -485,6 +515,9 @@ + .reportException(messageMediator.getContactInfo(), se); + + if (doRemarshal) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Do remarshal", se); ++ } + + // Invoke Portable Interceptors with receive_exception: + exception = orb.getPIHandler().invokeClientPIEndingPoint( +@@ -493,6 +526,9 @@ + // If PI did not change the exception, throw a + // Remarshal. + if( se == exception ) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Do remarshal: same exception"); ++ } + // exception = null is to maintain symmetry with + // GenericPOAClientSC. + exception = null; +@@ -500,6 +536,9 @@ + new RemarshalException()); + throw wrapper.statementNotReachable1() ; + } else { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "Do remarshal: new exception", exception ); ++ } + // Otherwise, throw the exception PI wants thrown. + continueOrThrowSystemOrRemarshal(messageMediator, + exception); +@@ -508,6 +547,9 @@ + } + + // No retry, so see if was unknown. ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "NO remarshal", se); ++ } + + ServiceContexts contexts = + messageMediator.getReplyServiceContexts(); +@@ -520,9 +562,19 @@ + Throwable unknown = usc.getUE() ; + UnknownException ue = new UnknownException(unknown); + ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "NO remarshal: UserException available", ++ unknown ); ++ } ++ + // Invoke Portable Interceptors with receive_exception: + exception = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.SYSTEM_EXCEPTION, ue ); ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "NO remarshal: UserException available: PI exception ", ++ exception ); ++ } + + continueOrThrowSystemOrRemarshal(messageMediator, exception); + throw wrapper.statementNotReachable3() ; +@@ -531,10 +583,17 @@ + + // It was not a comm failure nor unknown. + // This is the general case. ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "general exception", se); ++ } + + // Invoke Portable Interceptors with receive_exception: +- exception = orb.getPIHandler().invokeClientPIEndingPoint( ++ exception = orb.getPIHandler().invokeClientPIEndingPoint( // ### FIRST CALL + ReplyMessage.SYSTEM_EXCEPTION, se ); ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "general exception: PI exception", exception ); ++ } + + continueOrThrowSystemOrRemarshal(messageMediator, exception); + +@@ -542,16 +601,14 @@ + // we should assert in case exception is null somehow. + throw wrapper.statementNotReachable4() ; + } else if (messageMediator.isUserExceptionReply()) { +- +- if (orb.subcontractDebugFlag) { +- dprint(".processResponse: " + opAndId(messageMediator) +- + ": received user exception"); +- } +- + getContactInfoListIterator(orb) + .reportSuccess(messageMediator.getContactInfo()); + + String exceptionRepoId = peekUserExceptionId(inputObject); ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "received user exception", "exceptionRepoId", exceptionRepoId ); ++ } ++ + Exception newException = null; + + if (messageMediator.isDIIRequest()) { +@@ -560,15 +617,24 @@ + newException = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.USER_EXCEPTION, exception ); + messageMediator.setDIIException(newException); +- ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "received user exception (DII)", "exception", exception, ++ "newException", newException ); ++ } + } else { +- ApplicationException appException = +- new ApplicationException( +- exceptionRepoId, +- (org.omg.CORBA.portable.InputStream)inputObject); ++ ApplicationException appException = new ApplicationException( ++ exceptionRepoId, (org.omg.CORBA.portable.InputStream)inputObject); ++ + exception = appException; ++ + newException = orb.getPIHandler().invokeClientPIEndingPoint( + ReplyMessage.USER_EXCEPTION, appException ); ++ ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "received user exception (not DII)", "exception", exception, ++ "newException", newException ); ++ } + } + + if (newException != exception) { +@@ -583,10 +649,8 @@ + return inputObject; + + } else if (messageMediator.isLocationForwardReply()) { +- + if (orb.subcontractDebugFlag) { +- dprint(".processResponse: " + opAndId(messageMediator) +- + ": received location forward"); ++ dputil.info( "received location forward"); + } + + // NOTE: Expects iterator to update target IOR +@@ -613,10 +677,8 @@ + throw wrapper.statementNotReachable5() ; + + } else if (messageMediator.isDifferentAddrDispositionRequestedReply()){ +- + if (orb.subcontractDebugFlag) { +- dprint(".processResponse: " + opAndId(messageMediator) +- + ": received different addressing dispostion request"); ++ dputil.info( "received different addressing dispostion request"); + } + + // Set the desired target addressing disposition. +@@ -643,10 +705,8 @@ + new RemarshalException()); + throw wrapper.statementNotReachable6() ; + } else /* normal response */ { +- + if (orb.subcontractDebugFlag) { +- dprint(".processResponse: " + opAndId(messageMediator) +- + ": received normal response"); ++ dputil.info( "received normal response"); + } + + getContactInfoListIterator(orb) +@@ -665,6 +725,9 @@ + } + } finally { + tp.exit_processResponse() ; ++ if (orb.subcontractDebugFlag) { ++ dputil.exit() ; ++ } + } + } + +@@ -673,68 +736,64 @@ + // of one of these two types. This is a utility method for + // the above invoke code which must do this numerous times. + // If the exception is null, no exception is thrown. +- // + // Note that this code is duplicated in GenericPOAClientSC.java + protected void continueOrThrowSystemOrRemarshal( + CorbaMessageMediator messageMediator, Exception exception) + throws + SystemException, RemarshalException + { ++ final ORB orb = (ORB) messageMediator.getBroker(); + +- ORB orb = (ORB) messageMediator.getBroker(); ++ if (orb.subcontractDebugFlag) { ++ dputil.enter( "continueOrThrowSystemOrRemarshal", "exception", exception ) ; ++ } + +- if( exception == null ) { ++ try { ++ if ( exception == null ) { ++ // do nothing. ++ } else if( exception instanceof RemarshalException ) { ++ // REVISIT - unify with PI handling ++ orb.getInvocationInfo().setIsRetryInvocation(true); + +- // do nothing. ++ // NOTE - We must unregister the waiter NOW for this request ++ // since the retry will result in a new request id. Therefore ++ // the old request id would be lost and we would have a memory ++ // leak in the responseWaitingRoom. ++ unregisterWaiter(orb); + +- } else if( exception instanceof RemarshalException ) { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "throwing Remarshal" ); ++ } + +- // REVISIT - unify with PI handling +- orb.getInvocationInfo().setIsRetryInvocation(true); ++ throw (RemarshalException)exception; + +- // NOTE - We must unregister the waiter NOW for this request +- // since the retry will result in a new request id. Therefore +- // the old request id would be lost and we would have a memory +- // leak in the responseWaitingRoom. +- unregisterWaiter(orb); ++ } else { ++ if (orb.subcontractDebugFlag) { ++ dputil.info( "throwing exception", exception); ++ } + +- if (orb.subcontractDebugFlag) { +- dprint(".continueOrThrowSystemOrRemarshal: " +- + opAndId(messageMediator) +- + ": throwing Remarshal"); +- } +- +- throw (RemarshalException)exception; +- +- } else { +- +- if (orb.subcontractDebugFlag) { +- dprint(".continueOrThrowSystemOrRemarshal: " +- + opAndId(messageMediator) +- + ": throwing sex:" +- + exception); +- } +- +- throw (SystemException)exception; ++ throw (SystemException)exception; ++ } ++ } finally { ++ if (orb.subcontractDebugFlag) { ++ dputil.exit() ; ++ } + } + } + +- protected CorbaContactInfoListIterator getContactInfoListIterator(ORB orb) +- { ++ protected CorbaContactInfoListIterator getContactInfoListIterator(ORB orb) { + return (CorbaContactInfoListIterator) + ((CorbaInvocationInfo)orb.getInvocationInfo()) + .getContactInfoListIterator(); + } + +- protected void registerWaiter(CorbaMessageMediator messageMediator) +- { ++ protected void registerWaiter(CorbaMessageMediator messageMediator) { + if (messageMediator.getConnection() != null) { + messageMediator.getConnection().registerWaiter(messageMediator); + } + } + +- protected void unregisterWaiter(ORB orb) +- { ++ protected void unregisterWaiter(ORB orb) { + MessageMediator messageMediator = + orb.getInvocationInfo().getMessageMediator(); + if (messageMediator!=null && messageMediator.getConnection() != null) { +@@ -745,8 +804,7 @@ + } + } + +- protected void addServiceContexts(CorbaMessageMediator messageMediator) +- { ++ protected void addServiceContexts(CorbaMessageMediator messageMediator) { + ORB orb = (ORB)messageMediator.getBroker(); + CorbaConnection c = (CorbaConnection) messageMediator.getConnection(); + GIOPVersion giopVersion = messageMediator.getGIOPVersion(); +@@ -887,11 +945,9 @@ + TimingPoints tp = orb.getTimerManager().points() ; + + try { +- + tp.exit_clientDecoding(); +- + if (orb.subcontractDebugFlag) { +- dprint(".endRequest->:"); ++ dputil.enter("endRequest"); + } + + // Note: the inputObject may be null if an error occurs +@@ -900,12 +956,10 @@ + + MessageMediator messageMediator = + orb.getInvocationInfo().getMessageMediator(); +- if (messageMediator != null) +- { ++ if (messageMediator != null) { + ORBUtility.popEncVersionFromThreadLocalState(); + +- if (messageMediator.getConnection() != null) +- { ++ if (messageMediator.getConnection() != null) { + ((CorbaMessageMediator)messageMediator) + .sendCancelRequestIfFinalFragmentNotSent(); + } +@@ -939,26 +993,24 @@ + // exceptions during stream marshaling. More generally, exceptions + // that occur in the ORB after send_request (which includes + // after returning from _request) before _invoke: +- orb.getPIHandler().cleanupClientPIRequest(); ++ orb.getPIHandler().cleanupClientPIRequest(); // ### SECOND CALL + + // REVISIT: Early replies? + } catch (IOException ex) { + // See CDRInput/OutputObject.close() for more info. + // This won't result in a Corba error if an IOException happens. +- if (orb.subcontractDebugFlag) +- { +- dprint(".endRequest: ignoring IOException - " + ex.toString()); ++ if (orb.subcontractDebugFlag) { ++ dputil.info("ignoring IOException", ex ); + } + } finally { + tp.exit_totalRequest() ; + if (orb.subcontractDebugFlag) { +- dprint(".endRequest<-:"); ++ dputil.exit() ; + } + } + } + +- protected void performCodeSetNegotiation(CorbaMessageMediator messageMediator) +- { ++ protected void performCodeSetNegotiation(CorbaMessageMediator messageMediator) { + CorbaConnection conn = (CorbaConnection) messageMediator.getConnection(); + if (conn == null) + return ; +@@ -1003,9 +1055,8 @@ + } + } + +- protected void addCodeSetServiceContext(CorbaConnection conn, +- ServiceContexts ctxs, +- GIOPVersion giopVersion) { ++ protected void addCodeSetServiceContext(CorbaConnection conn, ++ ServiceContexts ctxs, GIOPVersion giopVersion) { + + // REVISIT. OMG issue 3318 concerning sending the code set + // service context more than once was deemed too much for the +@@ -1035,6 +1086,7 @@ + // Get the negotiated code sets (if any) out of the connection + codeSetCtx = conn.getCodeSetContext(); + } ++ + // Either we shouldn't send the code set service context, or + // for some reason, the connection doesn't have its code sets. + // Perhaps the server didn't include them in the IOR. Uses +@@ -1047,8 +1099,7 @@ + ctxs.put(cssc); + } + +- protected String peekUserExceptionId(InputObject inputObject) +- { ++ protected String peekUserExceptionId(InputObject inputObject) { + CDRInputObject cdrInputObject = (CDRInputObject) inputObject; + // REVISIT - need interface for mark/reset + cdrInputObject.mark(Integer.MAX_VALUE); +@@ -1057,13 +1108,7 @@ + return result; + } + +- protected void dprint(String msg) +- { +- ORBUtility.dprint("CorbaClientRequestDispatcherImpl", msg); +- } +- +- protected String opAndId(CorbaMessageMediator mediator) +- { ++ protected String opAndId(CorbaMessageMediator mediator) { + return ORBUtility.operationNameAndRequestId(mediator); + } + } +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/spi/orb/ORB.java +--- a/src/share/classes/com/sun/corba/ee/spi/orb/ORB.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/spi/orb/ORB.java Mon Jul 06 12:05:55 2009 -0700 +@@ -172,7 +172,7 @@ + public boolean streamFormatVersionDebugFlag = false ; + public boolean valueHandlerDebugFlag = false ; + public boolean orbLifecycleDebugFlag = false ; +- ++ + private LogWrapperTable logWrapperTable ; + + private static LogWrapperTable staticLogWrapperTable = +diff -r 4074e79c320a src/share/classes/com/sun/corba/ee/spi/protocol/PIHandler.java +--- a/src/share/classes/com/sun/corba/ee/spi/protocol/PIHandler.java Fri May 15 17:40:34 2009 -0700 ++++ b/src/share/classes/com/sun/corba/ee/spi/protocol/PIHandler.java Mon Jul 06 12:05:55 2009 -0700 +@@ -155,6 +155,27 @@ + int replyStatus, Exception exception ) ; + + /** ++ * Called when a retry is needed after initiateClientPIRequest but ++ * before invokeClientPIRequest. In this case, we need to properly ++ * balance initiateClientPIRequest/cleanupClientPIRequest calls, ++ * but WITHOUT extraneous calls to invokeClientPIEndingPoint ++ * (see bug 6763340). ++ * ++ * @param replyStatus One of the constants in iiop.messages.ReplyMessage ++ * indicating which reply status to set. ++ * @param exception The exception before ending interception points have ++ * been invoked, or null if no exception at the moment. ++ * @return The exception to be thrown, after having gone through ++ * all ending points, or null if there is no exception to be ++ * thrown. Note that this exception can be either the same or ++ * different from the exception set using setClientPIException. ++ * There are four possible return types: null (no exception), ++ * SystemException, UserException, or RemarshalException. ++ */ ++ Exception makeCompletedClientRequest( ++ int replyStatus, Exception exception ) ; ++ ++ /** + * Invoked when a request is about to be created. Must be called before + * any of the setClientPI* methods so that a new info object can be + * prepared for information collection. diff --git a/www/design/FOLB/AS9.0-RMI-IIOP-FOLB-FS.odt b/www/design/FOLB/AS9.0-RMI-IIOP-FOLB-FS.odt new file mode 100644 index 000000000..3f8b55ad7 Binary files /dev/null and b/www/design/FOLB/AS9.0-RMI-IIOP-FOLB-FS.odt differ diff --git a/www/design/FOLB/AS9.0-RMI-IIOP-FOLB-FS.pdf b/www/design/FOLB/AS9.0-RMI-IIOP-FOLB-FS.pdf new file mode 100644 index 000000000..ce3eebd50 Binary files /dev/null and b/www/design/FOLB/AS9.0-RMI-IIOP-FOLB-FS.pdf differ diff --git a/www/design/FOLB/FODynamicCluster.pdf b/www/design/FOLB/FODynamicCluster.pdf new file mode 100644 index 000000000..15dfa084b Binary files /dev/null and b/www/design/FOLB/FODynamicCluster.pdf differ diff --git a/www/design/FOLB/IIOPFOLBOnePager.html b/www/design/FOLB/IIOPFOLBOnePager.html new file mode 100644 index 000000000..aeb615a72 --- /dev/null +++ b/www/design/FOLB/IIOPFOLBOnePager.html @@ -0,0 +1,269 @@ + + + + + + + + + + + + +

                      IIOP Failover and Load Balancing One Pager

                      +
                        +
                      1. +

                        Introduction

                        +
                          +
                        1. +

                          Project/Component Working name: IIOP FOLB

                          +
                        2. +
                        3. +

                          Author: Ken.Cavanaugh@Oracle.Com

                          +
                        4. +
                        5. +

                          Date: 5/24/10

                        6. +
                        7. +

                          Revision: 1.0

                        8. +
                      2. +
                      3. +

                        Project Summary:

                        +
                          +
                        1. +

                          Project Description

                          +

                          The purpose of this project is to bring IIOP FOLB features from + GlassFish v2.1.1 to GlassFish Server Open Source Edition 3.1. In +addition, + there are some bugs that exist in the GF 2.1.1 release in IIOP +FOLB that we + would like to address in GlassFish Server Open Source Edition 3.1. + Fixing these + bugs requires making some architectural changes in the way the +handling of the + CSIv2 (secure IIOP) protocol is divided between the ORB and the + security/ejb.security module in the app server code.

                          +

                          Note that most of this work was previously reviewed in WSARC + case + 2007/141. + The references in 2007/141 are still relevant to this current +work, but + unfortunately the links are currently broken to +www.glassfishwiki.org/gfwiki. + See the references section for +more current + links.

                          +

                          There are some secondary goals for IIOP FOLB, which may not be + addressed in GF 3.1, given the short time schedule.

                          +

                          It would be nice to think about better integration of the + per-request load balancing feature (PRLB) which was done in a GF +2.1.1 patch + for Argela. In particular, the normal InitialContext load +balancing is not + compatible with PRLB, so configuring both behaviors should be +viewed as an + error. Currently configurating PRLB requires adding a special +configuration + flag to the EJB descriptor, and there is no admin support for this + feature.

                          + +

                          Similarly, better integration and administration of IIOP + hardware loadbalancer (HWLB) support would be useful. The HWLB +support was + added in GF 2 for NTT West some time ago. Configuring IIOP HWLB +currently + requires setting some obscure ORB flags. HWLB is also incompatible + at the ORB + level with other forms of load balancing.

                          +

                          Another big development item is getting some system-level + testing of IIOP FOLB written for small clusters. Currently this +happens only in + SQE tests, which have too long a testing cycle to give sufficient +feedback to + development. This is also dependent on getting a framework put +together for + supporting cluster testing.

                        2. +
                        3. +

                          Risks and Assumptions

                          +

                          FOLB system testing is dependent on the availability of a + suitable testing framework.

                          +

                          The CSIv2 code is complex and delicate, and the CSIv2 CTS tests + are difficult to work with.

                          +

                          CORBA customer escalations may impact the FOLB + schedule.

                        4. +
                      4. +
                      5. +

                        Problem Summary:

                        +
                          +
                        1. +

                          Problem Area

                          +

                          Support of high availability and scalability for large systems. + This feature covers only the IIOP protocol.

                        2. +
                        3. +

                          Justification

                          +

                          The primary justification for this work is feature parity with + GF v2.1.1. We would also like to fix the CSIv2/FOLB bug described +in Issue + 2791. However, fixing 2791 is not a release driver.

                        4. +
                      6. +
                      7. +

                        Technical Description

                        +
                          +
                        1. +

                          Details

                          +

                          The technical details are described primarily in the functional + specification. Here I will only describe +the changes + from the original AS 9.0 EE implementation.

                          +

                          Access to the required GMS interfaces will be done using GF 3.1 + facilities instead of using Class.forName().

                          +

                          A number of changes in support of CSIv2 with FOLB may be made. + Ideally, I'd like to at least get the handling of CSIv2 tagged +components moved + into the ORB, but this is considered to be P3 or less for V3.1.

                          +

                          A number of changes will be needed for load balancing in the + naming code, which has changed substantially in GlassFish version +3, and those + changes will be carried forward into GlassFish Server Open Source +Edition + 3.1.

                        2. +
                        3. +

                          Bug/RFE Numbers

                          +

                          Issue + 2791

                          + +

                          This is the bug about CSIv2 and FOLB not working together

                          +

                          Bug 6919275

                          +

                          This is one of several bugs that were related to the isLocal + problem when the clear text IIOP port is set to 0, forcing the use + of CSIv2. A + more robust fix is desired for this problem.

                        4. +
                        5. +

                          In scope

                          +

                          Feature parity for IIOP FOLB with GlassFish v2.1.1

                          +

                          Fix issues discussed above

                        6. +
                        7. +

                          Out of scope

                          +

                          N/A

                        8. +
                        9. +

                          Interfaces

                          +

                          Interfaces are described in the functional spec.

                          +
                        10. +
                        11. +

                          Doc Impact

                          +

                          None.

                        12. +
                        13. +

                          Admin/Config Impact

                          +

                          Probably no impact, unless better support for PRLB and HWLB is + added

                        14. +
                        15. +

                          HA Impact

                          +

                          IIOP FOLB makes use of Shoal/GMS to maintain an up-to-date view + of the cluster membership.

                          +

                          The ORB does not maintain any persistent state, so no other HA + services are required.

                        16. +
                        17. +

                          I18N/L10N Impact

                          +

                          None.

                        18. +
                        19. +

                          Packaging, Delivery, and Upgrade

                          +
                            +
                          1. +

                            Packaging

                            +

                            The packacing is unchanged from GF 3.0. The same ORB bundles + will be delivered to the maven repository from the CORBA + workspace.

                            +
                          2. +
                          3. +

                            Delivery

                            +

                            There is no change in CORBA packaging from the GF v3 + packaging for the GlassFish Server Open Source Edition 3.1

                          4. + +
                          5. +

                            Upgrade and Migration

                            +

                            No migration or upgrade is needed for CORBA.

                          6. +
                        20. +
                        21. +

                          Security Impact

                          +

                          Part of this feature improves CSIv2 by adding CSIv2 capability + to IIOP FOLB, which improves security for IIOP communications in a + clustered + environment.

                        22. +
                        23. +

                          Compatibility Impact

                          +

                          No change is planned in any part of the IIOP protocol, either + standard or as extended for FOLB (meaning new service contexts and + tagged + components) as first introduced in the Sun Java System Application + Server 9.1 + EE release.

                          +

                          No standard CORBA APIs as defined by the OMG will be affected by + this work.

                          +

                          There are no others APIs exposed by the ORB to application + code.

                        24. +
                        25. +

                          Dependencies

                          +

                          No change in ORB dependencies will result from this work.

                          +

                          The ejb and ejb.security modules depend on the ORB and will be + affected by changes for FOLB, particularly in relation to CSIv2.

                          + +

                          Some changes will be needed in the orb-iiop and orb-connector + modules to accommodate the integration of GMS into GlassFish +Server Open Source + Edition 3.1. Note that orb-iiop and/or orb-connector will thus be +dependent on + GMS

                          +

                          The third-party open source dependencies of the ORB are the same + as in GlassFish version 3: ASM at runtime; ant, the ant-maven +plugin, and + Jscheme at build time; and emma, findbugs, junit, and testng at +test time. All + of these dependencies have been previously reviewed and approved +by Sun legal + for GF v3.0.

                        26. +
                        27. +

                          Testing Impact

                          +

                          Some SQE tests exist for IIOP FOLB. One of the PDE tasks for + this feature is to obtain the SQE tests or construct new tests +that can run in + some kind of cluster testing framework. Given that PDE can do +this, there + should be little impact on SQE, other than the usual execution of +existing + tests across the support configuration matrix.

                        28. +
                        29. +

                          Reference + Documents

                          +
                            +
                          1. "IIOP Failover in Dynamic Clusters" by Ken +Cavanaugh and + Harold Carr
                          2. +
                          3. "Functional Specification RMI-IIOP Load Balancing and +Failover + AS 9.0 EE" by Harold Carr
                          4. +
                        30. +
                        31. +

                          Schedule

                          +
                            +
                          1. +

                            Projected Availability

                            +

                            We expect this feature to be available in M3. Detailed + scheduling will be provided.

                          2. +
                        32. +
                      8. +
                      diff --git a/www/design/GIOP_blunders.html b/www/design/GIOP_blunders.html new file mode 100644 index 000000000..68982df85 --- /dev/null +++ b/www/design/GIOP_blunders.html @@ -0,0 +1,113 @@ + + + + + + GIOP Blunders + + +

                      GIOP Blunders

                      +


                      +

                      Last Modified: May 18, 2004

                      +

                      Version: 1.6

                      +
                      <Ken Cavanaugh> +
                      +

                      It's interesting to take a look at the errors (and outright blunders) + that were committed in the design of GIOP. I am just looking at GIOP and some + items directly from CORBA, rather than all of CORBA. Here's my list:

                      +
                        +
                      1. Lack of separate session layer. This needs to top the list, + because this is probably the worst of the blunders. Addressing this problem + would allow us to introduce very powerful session-dependent compression, which + would substantially reduce the size of the messages. It would clean up other + problems as well, such as assigning an FVD to a session.
                      2. +
                      3. Inadequate versioning support. We need to be able to version + the protocol separately from the encoding.
                      4. +
                      5. Use of padding in CDR. The alignment rules force complications + in the code, and don't really buy anything for performance.
                      6. +
                      7. Use of indirection instead of labelling for references to shared + data. Correctly computing the indirections affects the code in many places, + due to the presence of fragmentation and encapsulation. It would be simpler to + just reference the position of the item directly, instead of an indirection to + the item.
                      8. +
                      9. Inadequate semantics for location forward. We tried to fix this + once with the location forward permanent idea, but that broke down into + semantic difficulties. The whole area of what a client should do when a + request completes other than normally is underspecified. +
                      10. +
                      11. Overly complex wide character support. +
                      12. +
                      13. IDL has become too complex yet remains insufficiently + expressive. There are a lot of areas here that can be criticized, because + every mistake in IDL directly translates to a problem in GIOP. Here's my list: +
                          +
                        1. Strings and characters should all be unicode.
                        2. +
                        3. Unions should not exist.
                        4. +
                        5. Structs, Exceptions, and ValueTypes should be unified. +
                        6. +
                        7. Truncatable valuetypes are a mistake and should not exist. +
                        8. +
                        9. XML should be a first-class citizen in IDL.
                        10. +
                        11. Sequence and Array should not both exist.
                        12. +
                      14. +
                      15. Too hard to get GIOP through a firewall. Of course, any number + of ORBs (including some in the past at Sun) have done things like base64 + encoding through HTTP. The problem is that no real standard exists. + The OMG firewall spec efforts aimed at changing firewalls to handle IIOP, + which was not possible. Instead, a standardized means (even if slower) to + encode IIOP in a firewall friendly manner would make more sense. +
                      16. +
                      17. IOR design is more complex than needed. We end up mostly + just needing opaque target object information, plus an open ended and + extensible list of transport end point addresses. A single level list + structure would handle this nicely. +
                      18. +
                      19. Request ID belongs in the GIOP header. This simplifies the + transport dispatch code, because reading a GIOP message requires first + reading the fixed 12 byte header, which given enough information to + read the rest of the message. Since the request ID is needed very + early in the request processing, it would be nicer to simply include + it in the GIOP header (even in those cases where it is not needed). +
                      20. +
                      21. Fix an endianess choice and be done with it. I've actually + changed my mind about this. Even in Java, it turns out that there are + significant marshalling efficiencies that are possible if the byte order + matches the native platform byte order. Receiver makes right is still the + correct choice, and I think GIOP is about right here. +
                      22. +
                      23. Encapsulations require versioning. In fact, multiple parts + of the GIOP protocol require versioning, notably encoding and protocol + (in PEPt terms), which really should be versioned separately. +
                      24. +
                      25. Repository IDs should always be meaningful. This should be + required in all cases, rather than allowing users to specify arbitrary + repository IDs in an IDL definition. +
                      26. +
                      27. Chunking is a bad idea. Instead, introduce enough meta-data so + that it is always possible to unmarshal the data, even if the type is unknown. +
                      28. +
                      29. Encapsulating complex typecodes is not needed. +
                      30. +
                      31. It's almost too easy to pick on, but Bidirectional GIOP is a mess, + and is not getting any better. +
                      32. +
                      33. Clients should be able to determine whether to locate or not. +
                      34. +
                      35. Clients should be able to determine when to cache a location + forward. +
                      36. +
                      37. Client behavior for multiple endpoints and location forward is + underspecified. +
                      38. +
                      + diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/IORProfiles.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/IORProfiles.gif new file mode 100644 index 000000000..b70dc9112 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/IORProfiles.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/IORProfiles.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/IORProfiles.vthought new file mode 100644 index 000000000..de664a1e6 --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/IORProfiles.vthought @@ -0,0 +1,269 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:04 $") + (writeDate "Thu Feb 6, 2003 11:29:59 AM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/IORProfiles.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 216) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 213 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 2) + (layer 1) + (type "Rectangle") + (location 108 153) + (size 90 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard current choice}) + ) + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 308.5 27) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 IOR Profiles}}) + ) + (shape + (id 6) + (layer -1) + (type "Rectangle") + (location 473.625 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc profile n}) + ) + (shape + (id 7) + (layer -1) + (type "Rectangle") + (location 358.875 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ...}) + ) + (shape + (id 9) + (layer -1) + (type "Rectangle") + (location 244.125 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc profile 2}) + ) + (shape + (id 10) + (layer -1) + (type "Rectangle") + (location 129.375 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc profile 1}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 2) + (end 10) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 4) + (layer 3) + (rotation 0) + (locked F) + (contents 5 8) + ) + (group + (id 5) + (layer -1) + (rotation 0) + (locked F) + (contents 6 7) + ) + (group + (id 8) + (layer -1) + (rotation 0) + (locked F) + (contents 9 10) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/ORBD_EE_fsd.sxw b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/ORBD_EE_fsd.sxw new file mode 100644 index 000000000..9c8e9c9cc Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/ORBD_EE_fsd.sxw differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/architecture.sxw b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/architecture.sxw new file mode 100644 index 000000000..cca22d376 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/architecture.sxw differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/dataModel.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/dataModel.gif new file mode 100644 index 000000000..b99aadb35 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/dataModel.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleEE.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleEE.gif new file mode 100644 index 000000000..d98165ed2 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleEE.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleEE.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleEE.vthought new file mode 100644 index 000000000..07790960d --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleEE.vthought @@ -0,0 +1,1102 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:01 $") + (writeDate "Wed Feb 5, 2003 9:15:07 PM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/exampleEE.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 468) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 213 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 459 288) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD Om +\par (locator)}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 396 351) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD O2 +\par (locator)}) + ) + (shape + (id 7) + (layer 6) + (type "Rectangle") + (location 513 76.5) + (size 108 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server Sn}) + ) + (shape + (id 8) + (layer 7) + (type "Rectangle") + (location 495 130.5) + (size 108 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server S2}) + ) + (shape + (id 12) + (layer 11) + (type "Rectangle") + (location 67.5 90) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 6. effective IOR'}) + ) + (shape + (id 14) + (layer -1) + (type "Rectangle") + (location 159.75 63) + (size 67.5 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S1,2,...,n}) + ) + (shape + (id 15) + (layer -1) + (type "Rectangle") + (location 213.75 63) + (size 40.5 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 18) + (layer -1) + (type "Rectangle") + (location 46.125 252) + (size 56.25 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S1,2,...,n}) + ) + (shape + (id 19) + (layer -1) + (type "Rectangle") + (location 91.125 252) + (size 33.75 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 21) + (layer 16) + (type "Rectangle") + (location 324 18) + (size 252 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 First Invocation on a Running Server}}) + ) + (shape + (id 24) + (layer 19) + (type "Rectangle") + (location 67.5 117) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1. effective IOR}) + ) + (shape + (id 26) + (layer 21) + (type "Rectangle") + (location 54 144) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 28) + (layer 23) + (type "Rectangle") + (location 67 381) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard server ORT}) + ) + (shape + (id 31) + (layer -1) + (type "Rectangle") + (location 61.9375 318) + (size 61.875 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S1,2,...,n}) + ) + (shape + (id 32) + (layer -1) + (type "Rectangle") + (location 111.4375 318) + (size 37.125 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 34) + (layer -1) + (type "Rectangle") + (location 156.9375 144) + (size 61.875 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O1,2,...,m}) + ) + (shape + (id 35) + (layer -1) + (type "Rectangle") + (location 206.4375 144) + (size 37.125 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 36) + (layer 27) + (type "Ellipse") + (location 423 279) + (size 18 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 37) + (layer 28) + (type "Rectangle") + (location 297 396) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD O1 +\par (locator)}) + ) + (shape + (id 38) + (layer 29) + (type "Rectangle") + (location 477 193.5) + (size 108 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server S1}) + ) + (shape + (id 39) + (layer 30) + (type "Rectangle") + (location 126 117) + (size 234 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 35) + (end 3) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 34) + (end 4) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (start 15) + (end 7) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 6) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 15) + (end 8) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 9) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 39) + (end 38) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 108) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 7. invoke on S1/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 10) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 15) + (end 38) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 11) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (start 12) + (end 14) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 16) + (layer 13) + (rotation 0) + (textRotation 0) + (locked F) + (start 31) + (end 18) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 90) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 4. create IOR}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 20) + (layer 15) + (rotation 0) + (textRotation 0) + (locked F) + (start 39) + (end 37) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 144) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 2. invoke on O1/x +\par 5 return LF S1,2,...,n/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 22) + (layer 17) + (rotation 0) + (textRotation 0) + (locked F) + (start 34) + (end 37) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 23) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (end 34) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 25) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (end 34) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 27) + (layer 22) + (rotation 0) + (textRotation 0) + (locked F) + (start 28) + (end 31) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 29) + (layer 24) + (rotation 0) + (textRotation 0) + (locked F) + (start 37) + (end 32) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.448) + (textWidth 100) + (textOffset 13) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 3. map request +\par to ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallArrow") + ) +) + +(groups + (group + (id 13) + (layer 12) + (rotation 0) + (locked F) + (contents 14 15) + ) + (group + (id 17) + (layer 14) + (rotation 0) + (locked F) + (contents 18 19) + ) + (group + (id 30) + (layer 25) + (rotation 0) + (locked F) + (contents 31 32) + ) + (group + (id 33) + (layer 26) + (rotation 0) + (locked F) + (contents 34 35) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleFirstInvokeRunning.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleFirstInvokeRunning.gif new file mode 100644 index 000000000..5d340d715 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleFirstInvokeRunning.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleFirstInvokeRunning.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleFirstInvokeRunning.vthought new file mode 100644 index 000000000..036c8a573 --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleFirstInvokeRunning.vthought @@ -0,0 +1,1238 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:03 $") + (writeDate "Wed Feb 5, 2003 2:18:00 PM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/exampleFirstInvokeRunning.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 468) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 239 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 67.5 90) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 6. effective IOR'}) + ) + (shape + (id 6) + (layer -1) + (type "Rectangle") + (location 148.5 63) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 7) + (layer -1) + (type "Rectangle") + (location 184.5 63) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 10) + (layer -1) + (type "Rectangle") + (location 58.5 252) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 11) + (layer -1) + (type "Rectangle") + (location 94.5 252) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 13) + (layer 8) + (type "Rectangle") + (location 324 18) + (size 252 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 First Invocation on a Running Server}}) + ) + (shape + (id 16) + (layer 11) + (type "Rectangle") + (location 67.5 117) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1. effective IOR}) + ) + (shape + (id 18) + (layer 13) + (type "Rectangle") + (location 54 144) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 20) + (layer 15) + (type "Rectangle") + (location 67 381) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard server ORT}) + ) + (shape + (id 23) + (layer -1) + (type "Rectangle") + (location 80.5 318) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 24) + (layer -1) + (type "Rectangle") + (location 116.5 318) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 28) + (layer 21) + (type "Rounded Rectangle") + (location 531 247.5) + (size 54 45) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server +\par object}) + ) + (shape + (id 29) + (layer 22) + (type "Rounded Rectangle") + (location 495 193.5) + (size 54 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORB}) + ) + (shape + (id 30) + (layer 23) + (type "Rounded Rectangle") + (location 553.5 166.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA2}) + ) + (shape + (id 32) + (layer -1) + (type "Rectangle") + (location 148.5 144) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 33) + (layer -1) + (type "Rectangle") + (location 184.5 144) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 36) + (layer 27) + (type "Ellipse") + (location 423 279) + (size 18 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 38) + (layer -1) + (type "Rectangle") + (location 526.5 54) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 39) + (layer -1) + (type "Rectangle") + (location 562.5 54) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 41) + (layer -1) + (type "Rectangle") + (location 526.5 99) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 42) + (layer -1) + (type "Rectangle") + (location 562.5 99) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 43) + (layer 30) + (type "Rounded Rectangle") + (location 463.5 139.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA1}) + ) + (shape + (id 44) + (layer 31) + (type "Rectangle") + (location 288 396) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD O +\par (locator)}) + ) + (shape + (id 45) + (layer 32) + (type "Rectangle") + (location 499.5 166.5) + (size 171 261) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server S}) + ) + (shape + (id 46) + (layer 33) + (type "Rectangle") + (location 112.5 117) + (size 207 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 46) + (end 45) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 108) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 7. invoke on S/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 7) + (end 45) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 6) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 8) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 23) + (end 10) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 90) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 4. create IOR}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 12) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 46) + (end 44) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 108) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 2. invoke on O/x +\par 5 return LF S/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 14) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 32) + (end 44) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 15) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 32) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 17) + (layer 12) + (rotation 0) + (textRotation 0) + (locked F) + (start 18) + (end 32) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 19) + (layer 14) + (rotation 0) + (textRotation 0) + (locked F) + (start 20) + (end 23) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 21) + (layer 16) + (rotation 0) + (textRotation 0) + (locked F) + (start 44) + (end 24) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.448) + (textWidth 100) + (textOffset 13) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 3. map request +\par to ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallArrow") + ) + (connection + (id 25) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (start 29) + (end 30) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 26) + (layer 19) + (rotation 0) + (textRotation 0) + (locked F) + (start 29) + (end 43) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 27) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (start 28) + (end 29) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 34) + (layer 25) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 38) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 35) + (layer 26) + (rotation 0) + (textRotation 0) + (locked F) + (start 43) + (end 41) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 1) + (textWidth 81) + (textOffset -29) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 5) + (layer 4) + (rotation 0) + (locked F) + (contents 6 7) + ) + (group + (id 9) + (layer 6) + (rotation 0) + (locked F) + (contents 10 11) + ) + (group + (id 22) + (layer 17) + (rotation 0) + (locked F) + (contents 23 24) + ) + (group + (id 31) + (layer 24) + (rotation 0) + (locked F) + (contents 32 33) + ) + (group + (id 37) + (layer 28) + (rotation 0) + (locked F) + (contents 38 39) + ) + (group + (id 40) + (layer 29) + (rotation 0) + (locked F) + (contents 41 42) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleRegister.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleRegister.gif new file mode 100644 index 000000000..84fc857ec Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleRegister.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleRegister.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleRegister.vthought new file mode 100644 index 000000000..1b250b69a --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleRegister.vthought @@ -0,0 +1,1218 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:00 $") + (writeDate "Wed Feb 5, 2003 2:44:24 PM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/exampleRegister.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 504) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 201 9) + (size 806 639) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Rectangle") + (location 331 15.5) + (size 252 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 Server Registration and Activation}}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 58.5 72) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard effective IOR}) + ) + (shape + (id 6) + (layer 5) + (type "Rectangle") + (location 54 108) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 7) + (layer 6) + (type "Rectangle") + (location 342 432) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Activator}) + ) + (shape + (id 9) + (layer 8) + (type "Rectangle") + (location 67 381) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard server ORT}) + ) + (shape + (id 12) + (layer -1) + (type "Rectangle") + (location 80.5 318) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 13) + (layer -1) + (type "Rectangle") + (location 116.5 318) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 16) + (layer 13) + (type "Rectangle") + (location 81 243) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc naming}) + ) + (shape + (id 25) + (layer 22) + (type "Rounded Rectangle") + (location 531 247.5) + (size 54 45) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server +\par object}) + ) + (shape + (id 26) + (layer 23) + (type "Rounded Rectangle") + (location 495 193.5) + (size 54 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORB}) + ) + (shape + (id 27) + (layer 24) + (type "Rounded Rectangle") + (location 553.5 166.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA2}) + ) + (shape + (id 29) + (layer -1) + (type "Rectangle") + (location 130.5 99) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 30) + (layer -1) + (type "Rectangle") + (location 166.5 99) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 33) + (layer 28) + (type "Ellipse") + (location 423 279) + (size 18 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 35) + (layer -1) + (type "Rectangle") + (location 526.5 54) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 36) + (layer -1) + (type "Rectangle") + (location 562.5 54) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 38) + (layer -1) + (type "Rectangle") + (location 526.5 99) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 39) + (layer -1) + (type "Rectangle") + (location 562.5 99) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 40) + (layer 31) + (type "Rounded Rectangle") + (location 463.5 139.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA1}) + ) + (shape + (id 41) + (layer 32) + (type "Rectangle") + (location 216 360) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD O}) + ) + (shape + (id 42) + (layer 33) + (type "Rectangle") + (location 499.5 166.5) + (size 171 261) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server S}) + ) + (shape + (id 43) + (layer 34) + (type "Rectangle") + (location 99 94.5) + (size 180 117) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 29) + (end 41) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 29) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (start 6) + (end 29) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 8) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 9) + (end 12) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 10) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 13) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.448) + (textWidth 10) + (textOffset 13) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc }) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallArrow") + ) + (connection + (id 14) + (layer 11) + (rotation 0) + (textRotation 0) + (locked F) + (start 43) + (end 16) + (points + (90 198) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.386) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 7. resolve}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "SmallFlatArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 15) + (layer 12) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 35) + (points + (351 144) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.386) + (textWidth 54) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 6. bind}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "SmallFlatArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 17) + (layer 14) + (rotation 0) + (textRotation 0) + (locked F) + (end 7) + (points + (585 395) + (414 423) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.314) + (textWidth 108) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 1. Administrator +\par registers server}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 18) + (layer 15) + (rotation 0) + (textRotation 0) + (locked F) + (start 7) + (end 42) + (points + (414 369) + (441 324) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.41) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 2. server +\par activation}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 19) + (layer 16) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 40) + (points + (351 198) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.386) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 5. ORT +\par exchange}) + (drawStartArrowhead T) + (drawEndArrowhead T) + (startArrowhead "SmallFlatArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 20) + (layer 17) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (end 41) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.539) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 4. ORB +\par registration}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 21) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 25) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.312) + (textWidth 90) + (textOffset -8) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 3. server object +\par registration}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "SmallFlatArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 22) + (layer 19) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (end 27) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 23) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (end 40) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 24) + (layer 21) + (rotation 0) + (textRotation 0) + (locked F) + (start 25) + (end 26) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 31) + (layer 26) + (rotation 0) + (textRotation 0) + (locked F) + (start 38) + (end 35) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 32) + (layer 27) + (rotation 0) + (textRotation 0) + (locked F) + (start 40) + (end 38) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 1) + (textWidth 68) + (textOffset -28) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 11) + (layer 10) + (rotation 0) + (locked F) + (contents 12 13) + ) + (group + (id 28) + (layer 25) + (rotation 0) + (locked F) + (contents 29 30) + ) + (group + (id 34) + (layer 29) + (rotation 0) + (locked F) + (contents 35 36) + ) + (group + (id 37) + (layer 30) + (rotation 0) + (locked F) + (contents 38 39) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleSecondInvokeRunning.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleSecondInvokeRunning.gif new file mode 100644 index 000000000..3469ab844 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleSecondInvokeRunning.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleSecondInvokeRunning.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleSecondInvokeRunning.vthought new file mode 100644 index 000000000..dde870bb8 --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleSecondInvokeRunning.vthought @@ -0,0 +1,907 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:04 $") + (writeDate "Wed Feb 5, 2003 2:25:44 PM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/exampleSecondInvokeRunning.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 468) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 239 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 67.5 99) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1. effective IOR'}) + ) + (shape + (id 6) + (layer -1) + (type "Rectangle") + (location 148.5 72) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 7) + (layer -1) + (type "Rectangle") + (location 184.5 72) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 8) + (layer 5) + (type "Rectangle") + (location 324 18) + (size 252 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 Second Invocation on a Running Server}}) + ) + (shape + (id 11) + (layer 8) + (type "Rectangle") + (location 54 144) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 15) + (layer 12) + (type "Rounded Rectangle") + (location 531 247.5) + (size 54 45) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server +\par object}) + ) + (shape + (id 16) + (layer 13) + (type "Rounded Rectangle") + (location 495 193.5) + (size 54 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORB}) + ) + (shape + (id 17) + (layer 14) + (type "Rounded Rectangle") + (location 553.5 166.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA2}) + ) + (shape + (id 19) + (layer -1) + (type "Rectangle") + (location 148.5 144) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 20) + (layer -1) + (type "Rectangle") + (location 184.5 144) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 23) + (layer 18) + (type "Ellipse") + (location 423 279) + (size 18 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 25) + (layer -1) + (type "Rectangle") + (location 526.5 54) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 26) + (layer -1) + (type "Rectangle") + (location 562.5 54) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 28) + (layer -1) + (type "Rectangle") + (location 526.5 99) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 29) + (layer -1) + (type "Rectangle") + (location 562.5 99) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 30) + (layer 21) + (type "Rounded Rectangle") + (location 463.5 139.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA1}) + ) + (shape + (id 31) + (layer 22) + (type "Rectangle") + (location 288 396) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD O +\par (locator)}) + ) + (shape + (id 32) + (layer 23) + (type "Rectangle") + (location 499.5 166.5) + (size 171 261) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server S}) + ) + (shape + (id 33) + (layer 24) + (type "Rectangle") + (location 112.5 117) + (size 207 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 33) + (end 32) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 108) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 2. invoke on S/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 7) + (end 32) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 6) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 9) + (layer 6) + (rotation 0) + (textRotation 0) + (locked F) + (start 19) + (end 31) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 10) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 11) + (end 19) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 12) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 17) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 13) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 30) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 14) + (layer 11) + (rotation 0) + (textRotation 0) + (locked F) + (start 15) + (end 16) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 21) + (layer 16) + (rotation 0) + (textRotation 0) + (locked F) + (start 28) + (end 25) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 22) + (layer 17) + (rotation 0) + (textRotation 0) + (locked F) + (start 30) + (end 28) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 1) + (textWidth 81) + (textOffset -29) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 5) + (layer 4) + (rotation 0) + (locked F) + (contents 6 7) + ) + (group + (id 18) + (layer 15) + (rotation 0) + (locked F) + (contents 19 20) + ) + (group + (id 24) + (layer 19) + (rotation 0) + (locked F) + (contents 25 26) + ) + (group + (id 27) + (layer 20) + (rotation 0) + (locked F) + (contents 28 29) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleThirdInvokeNotRunning.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleThirdInvokeNotRunning.gif new file mode 100644 index 000000000..e85b99d9c Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleThirdInvokeNotRunning.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleThirdInvokeNotRunning.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleThirdInvokeNotRunning.vthought new file mode 100644 index 000000000..634e3ad8f --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/exampleThirdInvokeNotRunning.vthought @@ -0,0 +1,1582 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:03 $") + (writeDate "Wed Feb 5, 2003 3:12:36 PM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/exampleThirdInvokeNotRunning.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 540) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 195 17) + (size 806 639) + (zoom 1.2451) + (documentLocation 0 59) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 65.5 96.2964) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 13. effective IOR'}) + ) + (shape + (id 6) + (layer -1) + (type "Rectangle") + (location 137.5 69.2964) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 7) + (layer -1) + (type "Rectangle") + (location 173.5 69.2964) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 10) + (layer -1) + (type "Rectangle") + (location 38.5 258.5) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 11) + (layer -1) + (type "Rectangle") + (location 74.5 258.5) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 16) + (layer 11) + (type "Rectangle") + (location 56.5 126.575) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard 1. effective IOR}) + ) + (shape + (id 18) + (layer -1) + (type "Rectangle") + (location 137.5 99.575) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 19) + (layer -1) + (type "Rectangle") + (location 173.5 99.575) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 20) + (layer 13) + (type "Rectangle") + (location 358 24.5) + (size 252 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 Third Invocation, Server Inactive}}) + ) + (shape + (id 23) + (layer 16) + (type "Rectangle") + (location 54 162) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 24) + (layer 17) + (type "Rectangle") + (location 342 468) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Activator}) + ) + (shape + (id 26) + (layer 19) + (type "Rectangle") + (location 58 417) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard server ORT}) + ) + (shape + (id 29) + (layer -1) + (type "Rectangle") + (location 35.5 327) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S}) + ) + (shape + (id 30) + (layer -1) + (type "Rectangle") + (location 71.5 327) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 32) + (layer 23) + (type "Rectangle") + (location 342 81) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc naming}) + ) + (shape + (id 40) + (layer 31) + (type "Rounded Rectangle") + (location 531 283.5) + (size 54 45) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server +\par object}) + ) + (shape + (id 41) + (layer 32) + (type "Rounded Rectangle") + (location 495 229.5) + (size 54 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORB}) + ) + (shape + (id 42) + (layer 33) + (type "Rounded Rectangle") + (location 553.5 202.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA2}) + ) + (shape + (id 44) + (layer -1) + (type "Rectangle") + (location 139.5 162) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 45) + (layer -1) + (type "Rectangle") + (location 175.5 162) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 48) + (layer 37) + (type "Ellipse") + (location 423 315) + (size 18 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 50) + (layer -1) + (type "Rectangle") + (location 526.5 90) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 51) + (layer -1) + (type "Rectangle") + (location 562.5 90) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc x}) + ) + (shape + (id 53) + (layer -1) + (type "Rectangle") + (location 526.5 135) + (size 45 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 54) + (layer -1) + (type "Rectangle") + (location 562.5 135) + (size 27 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 57205 57205 57205) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 55) + (layer 40) + (type "Rounded Rectangle") + (location 463.5 175.5) + (size 45 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc POA1}) + ) + (shape + (id 56) + (layer 41) + (type "Rectangle") + (location 216 396) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD O}) + ) + (shape + (id 57) + (layer 42) + (type "Rectangle") + (location 499.5 202.5) + (size 171 261) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server S}) + ) + (shape + (id 58) + (layer 43) + (type "Rectangle") + (location 108 126) + (size 198 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 58) + (end 57) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 108) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 14. invoke on S/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 7) + (end 57) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 6) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 8) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 29) + (end 10) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.46) + (textWidth 90) + (textOffset -8) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 11. create IOR}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 12) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 56) + (end 24) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 126) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 4. request activation}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 13) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 58) + (end 56) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.51) + (textWidth 108) + (textOffset 20) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 3. invoke on O/x +\par 12. return LF S/x}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 14) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 19) + (end 57) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.37) + (textWidth 90) + (textOffset -3) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 2. server down}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 15) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 18) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 21) + (layer 14) + (rotation 0) + (textRotation 0) + (locked F) + (start 44) + (end 56) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 22) + (layer 15) + (rotation 0) + (textRotation 0) + (locked F) + (start 23) + (end 44) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 25) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (end 29) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 27) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (start 56) + (end 30) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.603) + (textWidth 100) + (textOffset 7) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 10. map request to ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallArrow") + ) + (connection + (id 31) + (layer 22) + (rotation 0) + (textRotation 0) + (locked F) + (start 32) + (end 50) + (points + (468 45) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.386) + (textWidth 54) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 9. bind}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "SmallFlatArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 33) + (layer 24) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (end 57) + (points + (414 405) + (441 360) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.41) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 5. server +\par activation}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 34) + (layer 25) + (rotation 0) + (textRotation 0) + (locked F) + (start 56) + (end 55) + (points + (351 234) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.386) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 8. ORT +\par exchange}) + (drawStartArrowhead T) + (drawEndArrowhead T) + (startArrowhead "SmallFlatArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 35) + (layer 26) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 56) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.539) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 7. ORB +\par registration}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 36) + (layer 27) + (rotation 0) + (textRotation 0) + (locked F) + (start 56) + (end 40) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.312) + (textWidth 90) + (textOffset -8) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc 6. server object +\par registration}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "SmallFlatArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 37) + (layer 28) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 42) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 38) + (layer 29) + (rotation 0) + (textRotation 0) + (locked F) + (start 41) + (end 55) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 39) + (layer 30) + (rotation 0) + (textRotation 0) + (locked F) + (start 40) + (end 41) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 46) + (layer 35) + (rotation 0) + (textRotation 0) + (locked F) + (start 53) + (end 50) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 47) + (layer 36) + (rotation 0) + (textRotation 0) + (locked F) + (start 55) + (end 53) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 1) + (textWidth 68) + (textOffset -28) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD ORT}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 5) + (layer 4) + (rotation 0) + (locked F) + (contents 6 7) + ) + (group + (id 9) + (layer 6) + (rotation 0) + (locked F) + (contents 10 11) + ) + (group + (id 17) + (layer 12) + (rotation 0) + (locked F) + (contents 18 19) + ) + (group + (id 28) + (layer 21) + (rotation 0) + (locked F) + (contents 29 30) + ) + (group + (id 43) + (layer 34) + (rotation 0) + (locked F) + (contents 44 45) + ) + (group + (id 49) + (layer 38) + (rotation 0) + (locked F) + (contents 50 51) + ) + (group + (id 52) + (layer 39) + (rotation 0) + (locked F) + (contents 53 54) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample.gif new file mode 100644 index 000000000..93f16d742 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample.vthought new file mode 100644 index 000000000..f9a617ddc --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample.vthought @@ -0,0 +1,1218 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:02 $") + (writeDate "Mon Jan 27, 2003 10:11:48 PM PST") + (documentPath "/home/ken/work/orbd/objectModelExample.vthought") +) + +(document + (palette F) + (layout + (page "Letter") + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 269 228) + (size 1158 844) + (zoom 2) + (documentLocation 22 221) + (gridSnap F) + (gridVisibility F) + (gridSpacing 4) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Rectangle") + (location 497.5 385) + (size 171 22) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard ApplicationObjectAdapters}) + ) + (shape + (id 2) + (layer 1) + (type "Rectangle") + (location 269.5 287) + (size 131 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard GroupObjectAdapters}) + ) + (shape + (id 3) + (layer 2) + (type "Ellipse") + (location 390.7647 376.0562) + (size 38.9461 20) + (rotation 31) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 219.5 407) + (size 159 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard GroupApplicationInstances}) + ) + (shape + (id 6) + (layer -1) + (type "Rectangle") + (location 437.5 239) + (size 139 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard ObjectAdapterReplicas}) + ) + (shape + (id 7) + (layer -1) + (type "Ellipse") + (location 421.7868 265.7943) + (size 43.4401 20) + (rotation 314) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 4) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 11) + (layer -1) + (type "Ellipse") + (location 376.5 293.5) + (size 27 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc O}) + ) + (shape + (id 12) + (layer -1) + (type "Ellipse") + (location 398.5 311.5) + (size 27 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc P}) + ) + (shape + (id 13) + (layer -1) + (type "Ellipse") + (location 418.5 331.5) + (size 27 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc P}) + ) + (shape + (id 17) + (layer 8) + (type "Ellipse") + (location 308.6732 395.0299) + (size 29.7142 20) + (rotation 311) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 19) + (layer 10) + (type "Ellipse") + (location 315.1453 305.0335) + (size 21.0485 14.4881) + (rotation 58) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 2 2) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 20) + (layer 11) + (type "Ellipse") + (location 368.5 440.5) + (size 27 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc A}) + ) + (shape + (id 21) + (layer 12) + (type "Ellipse") + (location 366.5 466.5) + (size 27 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc A}) + ) + (shape + (id 23) + (layer -1) + (type "Ellipse") + (location 276.5 454.5) + (size 45 45) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORB}) + ) + (shape + (id 24) + (layer -1) + (type "Ellipse") + (location 276.5 499.5) + (size 45 45) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORB}) + ) + (shape + (id 26) + (layer -1) + (type "Ellipse") + (location 207 480) + (size 36 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S2}) + ) + (shape + (id 27) + (layer -1) + (type "Ellipse") + (location 207 516) + (size 36 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc S1}) + ) + (shape + (id 29) + (layer -1) + (type "Ellipse") + (location 135 485) + (size 58 54) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Node2}) + ) + (shape + (id 30) + (layer -1) + (type "Ellipse") + (location 135 539) + (size 58 54) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Node1}) + ) + (shape + (id 33) + (layer 18) + (type "Ellipse") + (location 245.5 330.5) + (size 27 27) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc R}) + ) + (shape + (id 35) + (layer 20) + (type "Ellipse") + (location 60 384) + (size 54 54) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD}) + ) + (shape + (id 46) + (layer 31) + (type "Ellipse") + (location 59.5 561.5) + (size 63 63) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Cluster}) + ) +) + +(connections + (connection + (id 9) + (layer -1) + (rotation 0) + (textRotation 0) + (locked F) + (start 11) + (end 13) + (points + (382 271) + (400 255) + (420 256) + (436 269) + (437 290) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc }) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 10) + (layer -1) + (rotation 0) + (textRotation 0) + (locked F) + (start 11) + (end 12) + (points + (394 275) + (404 271) + (412 276) + (416 285) + (413 294) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc }) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 14) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 33) + (end 21) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 18) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 33) + (end 20) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 31) + (layer 16) + (rotation 0) + (textRotation 0) + (locked F) + (start 33) + (end 11) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 32) + (layer 17) + (rotation 0) + (textRotation 0) + (locked F) + (start 35) + (end 33) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 34) + (layer 19) + (rotation 0) + (textRotation 0) + (locked F) + (start 46) + (end 35) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 36) + (layer 21) + (rotation 0) + (textRotation 0) + (locked F) + (start 20) + (end 12) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 37) + (layer 22) + (rotation 0) + (textRotation 0) + (locked F) + (start 21) + (end 13) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 38) + (layer 23) + (rotation 0) + (textRotation 0) + (locked F) + (start 23) + (end 20) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 39) + (layer 24) + (rotation 0) + (textRotation 0) + (locked F) + (start 24) + (end 21) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 40) + (layer 25) + (rotation 0) + (textRotation 0) + (locked F) + (start 26) + (end 23) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 41) + (layer 26) + (rotation 0) + (textRotation 0) + (locked F) + (start 27) + (end 24) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 42) + (layer 27) + (rotation 0) + (textRotation 0) + (locked F) + (start 29) + (end 26) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 43) + (layer 28) + (rotation 0) + (textRotation 0) + (locked F) + (start 30) + (end 27) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 44) + (layer 29) + (rotation 0) + (textRotation 0) + (locked F) + (start 46) + (end 29) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 45) + (layer 30) + (rotation 0) + (textRotation 0) + (locked F) + (start 46) + (end 30) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "FlatArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 5) + (layer 4) + (rotation 0) + (locked F) + (contents 6 7 8) + ) + (group + (id 8) + (layer -1) + (rotation 0) + (locked F) + (contents 9 10 11 12 13) + ) + (group + (id 22) + (layer 13) + (rotation 0) + (locked F) + (contents 23 24) + ) + (group + (id 25) + (layer 14) + (rotation 0) + (locked F) + (contents 26 27) + ) + (group + (id 28) + (layer 15) + (rotation 0) + (locked F) + (contents 29 30) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample2.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample2.gif new file mode 100644 index 000000000..ff9e0e14d Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/objectModelExample2.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/orbd.zargo b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/orbd.zargo new file mode 100644 index 000000000..abd1b046e Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/orbd.zargo differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubFields.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubFields.gif new file mode 100644 index 000000000..4eeae07ce Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubFields.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubFields.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubFields.vthought new file mode 100644 index 000000000..4c956508b --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubFields.vthought @@ -0,0 +1,139 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:04 $") + (writeDate "Thu Feb 6, 2003 10:44:08 AM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/stubFields.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 216) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 213 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Rectangle") + (location 234 108) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 2) + (layer 1) + (type "Rectangle") + (location 247.5 54) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard effective IOR}) + ) + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 301.5 90) + (size 225 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections +) + +(groups +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubIORProfiles.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubIORProfiles.gif new file mode 100644 index 000000000..e1ba30014 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubIORProfiles.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubIORProfiles.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubIORProfiles.vthought new file mode 100644 index 000000000..95dcaa7a0 --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubIORProfiles.vthought @@ -0,0 +1,591 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:01 $") + (writeDate "Thu Feb 6, 2003 11:41:11 AM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/stubIORProfiles.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 432) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 213 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 2) + (layer 1) + (type "Rectangle") + (location 56.5 67) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard effective IOR}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 52 220) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 6) + (layer 5) + (type "Rectangle") + (location 315 342) + (size 90 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard current choice}) + ) + (shape + (id 9) + (layer -1) + (type "Rectangle") + (location 536.625 261) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD M profile}) + ) + (shape + (id 10) + (layer -1) + (type "Rectangle") + (location 421.875 261) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ...}) + ) + (shape + (id 12) + (layer -1) + (type "Rectangle") + (location 307.125 261) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD 2 profile}) + ) + (shape + (id 13) + (layer -1) + (type "Rectangle") + (location 192.375 261) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ORBD 1 profile}) + ) + (shape + (id 15) + (layer 8) + (type "Rectangle") + (location 531 171) + (size 90 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard current choice}) + ) + (shape + (id 16) + (layer 9) + (type "Rectangle") + (location 340 36) + (size 198 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}{\f1\fnil helvetica bold;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard {\b\f1 Stub, IORs and Current Profiles}}) + ) + (shape + (id 19) + (layer -1) + (type "Rectangle") + (location 536.625 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server N profile}) + ) + (shape + (id 20) + (layer -1) + (type "Rectangle") + (location 421.875 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc ...}) + ) + (shape + (id 22) + (layer -1) + (type "Rectangle") + (location 307.125 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server 2 profile}) + ) + (shape + (id 23) + (layer -1) + (type "Rectangle") + (location 192.375 99) + (size 114.75 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Server 1 profile}) + ) + (shape + (id 24) + (layer 11) + (type "Rectangle") + (location 313 197.5) + (size 621 369) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub}) + ) +) + +(connections + (connection + (id 1) + (layer 0) + (rotation 0) + (textRotation 0) + (locked F) + (start 2) + (end 23) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 13) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (start 6) + (end 12) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 14) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 15) + (end 19) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups + (group + (id 7) + (layer 6) + (rotation 0) + (locked F) + (contents 8 11) + ) + (group + (id 8) + (layer -1) + (rotation 0) + (locked F) + (contents 9 10) + ) + (group + (id 11) + (layer -1) + (rotation 0) + (locked F) + (contents 12 13) + ) + (group + (id 17) + (layer 10) + (rotation 0) + (locked F) + (contents 18 21) + ) + (group + (id 18) + (layer -1) + (rotation 0) + (locked F) + (contents 19 20) + ) + (group + (id 21) + (layer -1) + (rotation 0) + (locked F) + (contents 22 23) + ) +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubInitial.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubInitial.gif new file mode 100644 index 000000000..4d408eca7 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubInitial.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubInitial.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubInitial.vthought new file mode 100644 index 000000000..bd895d425 --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubInitial.vthought @@ -0,0 +1,227 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:02 $") + (writeDate "Thu Feb 6, 2003 10:40:02 AM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/stubInitial.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 216) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 213 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Rectangle") + (location 369 81) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc IOR 1}) + ) + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 247.5 54) + (size 81 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard effective IOR}) + ) + (shape + (id 5) + (layer 4) + (type "Rectangle") + (location 243 108) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 6) + (layer 5) + (type "Rectangle") + (location 310.5 90) + (size 225 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub (initial configuration)}) + ) +) + +(connections + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 3) + (end 1) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 4) + (layer 3) + (rotation 0) + (textRotation 0) + (locked F) + (start 5) + (end 1) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups +) diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubLocationForward.gif b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubLocationForward.gif new file mode 100644 index 000000000..26dfccbc0 Binary files /dev/null and b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubLocationForward.gif differ diff --git a/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubLocationForward.vthought b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubLocationForward.vthought new file mode 100644 index 000000000..053a32b54 --- /dev/null +++ b/www/design/IIOPGroupAgent/ORTExchangeAgent-2003/stubLocationForward.vthought @@ -0,0 +1,253 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:01 $") + (writeDate "Thu Feb 6, 2003 10:44:33 AM PST") + (documentPath "/export/home/carr/ws/rip-int-generic/notes/orbd/stubLocationForward.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 648 216) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 213 16) + (size 806 657) + (zoom 1.2451) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Rectangle") + (location 360 54) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc IOR 2}) + ) + (shape + (id 3) + (layer 2) + (type "Rectangle") + (location 234 108) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard target IOR}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 360 108) + (size 72 18) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc IOR 1}) + ) + (shape + (id 6) + (layer 5) + (type "Rectangle") + (location 247.5 54) + (size 99 18) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 0) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard effective IOR}) + ) + (shape + (id 7) + (layer 6) + (type "Rectangle") + (location 301.5 90) + (size 225 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed T) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Stub (after LOCATION_FORWARD)}) + ) +) + +(connections + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 3) + (end 4) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) + (connection + (id 5) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (start 6) + (end 1) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "SmallFlatArrow") + ) +) + +(groups +) diff --git a/www/design/OutboundConnectionCacheImpl.png b/www/design/OutboundConnectionCacheImpl.png new file mode 100644 index 000000000..bf0fc25ca Binary files /dev/null and b/www/design/OutboundConnectionCacheImpl.png differ diff --git a/www/design/SAF/SAF_class.mif b/www/design/SAF/SAF_class.mif new file mode 100644 index 000000000..adf7c2eed --- /dev/null +++ b/www/design/SAF/SAF_class.mif @@ -0,0 +1,890 @@ + +# Creator: Visual Thought-1.5 +# For: ken +# Title: SAF_class.vthought +# Creation Date: Fri Sep 15, 2000 5:34:19 PM PDT + # All dimensions are in points + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > +> # end of ColorCatalog +#----- Begin mifref header + + + # ShapeRect L T W H: the position and size of the frame. + # [ integer_point_values ] + # If you uncomment the ShapeRect line below, the anchored frame + # created in the output MIF file will always have the bounds specified. + # This feature allows you to create standard-sized anchored frames. + # Otherwise, the bounding box of the objects in the input MIF file + # will be used as the bounding box of the anchored frame. + # + + # FrameType: whether frame is anchored, and if anchored its position. + # [ Below, Top, Bottom, Inline, Left, Right, Inside, Outside, + # Near, Far, RunIntoParagraph, NotAnchored ] + + + # Float: Whether frame is floating. + # [ Yes, No ] + # Yes floats graphic frame to avoid large white space that results + # when anchored frame and the line containing it are moved to the + # next page. + # + + # NSOffset: Near-side offset. + # [ integer_point_value ] + # + + # BLOffset: Baseline offset. + # [ integer_point_value ] + # + + # AnchorAlign: Aligment of anchored frame. + # [ Left, Center, Right, Inside, Outside ] + # + + # AnchorBeside: Whether the graphic frame is anchored outside of a text + # frame or a column in a text frame. + # [ Column, TextFrame ] + # + + # Cropped: Yes clips sides of graphic frame to fit column. + # [ Yes, No ] + # +#----- End mifref header + # Anchored frame bounding box. + + # End of anchored frame bounding box. + + + + + + + + + +> + + + + + + + + + +> + + + + + + > + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + +> + + + + + + > + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + +> + + + + + + > + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + +> + + + + + + > + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + +> + + + + + + > + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> +# End of MIFFILE +#----- Begin mifref footer +# Brackets closing the AFrame statement started in mifhead.txt. + > +> +# TextFlow definition allow MIF import by reference in FrameMaker 5. + + > + > # end of Para +> # end of TextFlow +#----- End mifref footer diff --git a/www/design/SAF/activation.idl b/www/design/SAF/activation.idl new file mode 100644 index 000000000..168774e0f --- /dev/null +++ b/www/design/SAF/activation.idl @@ -0,0 +1,315 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Distribution License v. 1.0, which is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +// New activation IDL for revised SAF. + +module ActivationIDL { + // Possible values for endpointType argument on Server.getEndpoint() + // If you change the value of this constant then update + // core.EndPoint accordingly. It has a duplicate definition + // to avoid a compilation dependency. + const string IIOP_CLEAR_TEXT = "IIOP_CLEAR_TEXT"; + + // this is a typedef from CORBA 2.3, since we don't have a corba.idl + // it is included here + + typedef string ServerId; + typedef string ORBId; + typedef sequence POAName; + + /** Raised if getEndpoint is called on a server callback object for + * an invalid endpoint type + */ + exception NoSuchEndPoint {} ; + + /** + * Raised if an attempt is made to retrieve ports corresponding to + * non-registered ORB + */ + exception InvalidORBId {} ; + + /** Raised if an operation is attempted against an invalid server ID. + */ + exception ServerNotRegistered { + ServerId serverId ; + }; + + /** Raised if an operation is attempted for a server that is not running, + * and the server is required to be running for the operation. + */ + exception ServerNotActive { + ServerId serverId ; + }; + + /** Raised if an operation is attempted against a server that is in a + * hold down state. A server becomes held down if it fails to activate + * within 10 seconds. + */ + exception ServerHeldDown { + ServerId serverId ; + }; + + /** Raised if an attempt is made to activate a server that is already + * running. + */ + exception ServerAlreadyActive{ + ServerId serverId ; + }; + + /** Raised if an attempt is made to register a serverdef with the + * same applicationName as an existing serverdef. + */ + exception ServerAlreadyRegistered { + ServerId serverId; + }; + + /** Raised if an attempt is made to install a server that is currently + * installed. Note that a newly created server starts out in an uninstalled + * state. + */ + exception ServerAlreadyInstalled { + ServerId serverId; + } ; + + /** Raised if an attempt is made to uninstall a server that is currently + * uninstalled. Note that a newly created server starts out in an + * uninstalled + * state. + */ + exception ServerAlreadyUninstalled { + ServerId serverId; + } ; + + /** Raised if an attempt is made to register an invalid serverdef. + */ + exception BadServerDefinition { + string reason; + }; + + /** Raised if an attempt is made to register endpoints for the + * same ORB again + */ + exception ORBAlreadyRegistered { + ORBid orbId; + }; + + typedef long tcpPort ; + typedef sequence ServerIds; + + // passing a struct containing endpointType and port-#s + struct EndPointInfo { + string endpointType; + tcpPort port; + }; + + typedef sequence EndpointInfoList; + + + struct ORBIds { + ORBid orbId; + long mappedORBId; + }; + + typedef sequence ORBIdList; + + /** Server callback API, passed to Activator in active method. + */ + interface ServerObject { + readonly attribute ServerID server_id ; + + /** Shutdown this server. Returns after orb.shutdown() completes. + */ + void shutdown(); + + /** Install the server. Returns after the install hook completes + * execution in the server. + */ + void install(); + + /** Uninstall the server. Returns after the uninstall hook + * completes execution. + */ + void uninstall(); + }; + + interface ORBObject { + readonly attribute ServerID server_id ; + + readonly attribute ORBID orb_id ; + + void template_required( in POAName poa_name ) ; + }; + + interface Activator { + // A new ORB started server registers itself with the Activator + void register_server(in ServerObject server_obj) + raises (ServerNotRegistered); + + void register_orb( in ServerId serverId, in ORBId orbId, + in EndpointInfoList endPointInfo) + raises ( ServerNotRegistered, NoSuchEndPoint, ORBAlreadyRegistered) ; + + // Register the POA template + void register_poa( in ObjectReferenceTemplate template ) + + // list active servers + ServerIds getActiveServers(); + + // If the server is not running, start it up. + void activate(in ServerId serverId) + raises (ServerAlreadyActive, ServerNotRegistered, ServerHeldDown); + + // If the server is running, shut it down + void shutdown(in ServerId serverId) + raises (ServerNotActive, ServerNotRegistered); + + // Invoke the server install hook. If the server is not + // currently running, this method will activate it. + void install(in ServerId serverId) + raises (ServerNotRegistered, ServerHeldDown, + ServerAlreadyInstalled); + + // list all registered ORBs and their mapping for a server + ORBIdList getORBNames(in ServerId serverId) + raises (ServerNotRegistered); + + // Invoke the server uninstall hook. If the server is not + // currently running, this method will activate it. + // After this hook completes, the server may still be running. + void uninstall(in ServerId serverId) + raises (ServerNotRegistered, ServerHeldDown, + ServerAlreadyUninstalled); + }; + + interface Locator { + // This interface is strictly for the use of ServerTool. The old getEndpoint + // method is no longer needed because the port numbers are embedded in the + // ORBD template. + + + // struct contain ORB and port info + struct ORBPortInfo { + ORBid orbId; + tcpPort port; + }; + + typedef sequence ORBPortInfoList; + + // struct to return the list of endpoints for a server for a specific + // endpoint + struct ServerLocation { + string hostname; + ORBPortInfoList ports; + }; + + // locate server - returns the port with a specific type for all registered + // ORBs of an active server. + // Starts the server if it is not already running. + ServerLocation locateServer( + in ServerId serverId, + in string endPoint) + raises(NoSuchEndPoint, ServerNotRegistered, ServerHeldDown); + + // struct to return the list of endpoints for a server for a specific + // ORB + struct ServerLocationPerORB { + string hostname; + EndpointInfoList ports; + }; + + // locate server - returns all ports registered with a specified ORB for + // an active server + // Starts the server if it is not already running. + ServerLocationPerORB locateServerForORB( + in ServerId serverId, + in ORBid orbId) + raises(InvalidORBId, ServerNotRegistered, ServerHeldDown); + + // Useful from external BadServerIdHandlers which can only + // get the orbid as a number from the object key but need + // to call locateServerForORB with the ORBid. + ORBid ORBNumberToId( + in ServerId serverId, + in long orbId) + raises(InvalidORBId, ServerNotRegistered); + + // Useful from external BadServerIdHandlers which need + // to pick a particular port type. + long getServerPortForType( + in ServerLocationPerORB location, + in string endPointType) + raises(NoSuchEndPoint); + }; + + interface ServerManager : Activator, Locator { }; + + interface Repository { + // server program definition. + struct ServerDef { + string applicationName; // alias used for servers with identical + // serverName values. + string serverName; // Class name of server's main class. + string serverClassPath; // class path used to run the server. + string serverArgs; + string serverVmArgs; + }; + + // register server definition + // This returns the serverId of the server. A newly created server is + // always uninstalled. + long registerServer (in ServerDef serverDef) + raises (ServerAlreadyRegistered, BadServerDefinition); + + // unregister server definition + void unregisterServer (in ServerId serverId) + raises (ServerNotRegistered); + + // get server definition + ServerDef getServer(in ServerId serverId) + raises (ServerNotRegistered); + + // Return whether the server has been installed + boolean isInstalled( in ServerId serverId ) + raises (ServerNotRegistered); + + // Mark the server as being installed. Raises ServerAlreadyInstalled + // if the server is currently marked as installed. + void install( in ServerId serverId ) + raises (ServerNotRegistered, ServerAlreadyInstalled) ; + + // Mark the server as being uninstalled. Raises ServerAlreadyUninstalled + // if the server is currently marked as uninstalled. + void uninstall( in ServerId serverId ) + raises (ServerNotRegistered, ServerAlreadyUninstalled) ; + + // list registered servers + ServerIds listRegisteredServers (); + + typedef sequence StringSeq ; + + // Returns list of ALL applicationNames defined in ServerDefs of registered + // servers. + StringSeq getApplicationNames(); + + // Find the ServerID associated with the given application name. + long getServerID( in string applicationName ) raises (ServerNotRegistered) ; + }; + + interface InitialNameService { + exception NameAlreadyBound {}; + + // bind initial name + void bind ( + in string name, + in Object obj, + in boolean isPersistant) raises (NameAlreadyBound); + }; + +}; diff --git a/www/design/SAF/current.doc b/www/design/SAF/current.doc new file mode 100644 index 000000000..29012c824 Binary files /dev/null and b/www/design/SAF/current.doc differ diff --git a/www/design/SAF/extending.doc b/www/design/SAF/extending.doc new file mode 100644 index 000000000..c4bf3a201 Binary files /dev/null and b/www/design/SAF/extending.doc differ diff --git a/www/design/SAF/imr.doc b/www/design/SAF/imr.doc new file mode 100644 index 000000000..3d5b9a893 Binary files /dev/null and b/www/design/SAF/imr.doc differ diff --git a/www/design/SAF/init_order.txt b/www/design/SAF/init_order.txt new file mode 100644 index 000000000..cff48e978 --- /dev/null +++ b/www/design/SAF/init_order.txt @@ -0,0 +1,69 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +1. Note that only the activator is registered in InitNS. + +2. activator and request interceptor need to reference each other. + +ORBD init: + +ORBDActivator: + constructor( ) + + setRequestInterceptor( request interceptor ) + - holds this for init and getting slot id + + setORB( ORB ) + - needs to get rootPOA before it starts operations + - needs to call setORB on requestInterceptor + +ORBDAdapterActivator: + constructor( ORB, activator, servant locator ) + - needs to get POA policies that are shared with the activator + - needs to assign the servant locator to the new POA + +ORBDRequestInterceptor: + constructor( int slot ) + - needs the slot id + + setORB( ORB ) + - find activator + +ORBDServantLocator: + constructor( ORB, int slot ) + - needs PICurrent + - needs the slot id + +As always, it's good to have ORBs everywhere. + +Model: + +in initializer: + +pre_init: + - allocate slot id + - create activator ( ) + - create request interceptor( activator, slot id ) + - activator . setRequestInterceptor( interceptor ) + - add_client_request( request interceptor ) + - bind activator in initial naming + +post_init: + - not needed here. + +in ORBD init: + +- find activator from init naming +- get slot id from activator +- activator init( ORB ) +- create servant locator ( ORB, slot ) +- create adapter activator( ORB, activator, servant locator ) +- register adapter activator with root POA +- request interceptor init( ORB ) diff --git a/www/design/SAF/interceptor_usage.text b/www/design/SAF/interceptor_usage.text new file mode 100644 index 000000000..c575e73ea --- /dev/null +++ b/www/design/SAF/interceptor_usage.text @@ -0,0 +1,248 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Notation: + +Adapter ID: addition to POA, also in ServerRequestInfo in PI. +meaning is the unique ID of the POA. For persistent POAs, this must +be the same value each time the server is restarted OR the POA is activated. + +Object ID: the value passed to create_reference_with_id or the equivalent +assigned in create_reference. + +Object Key: the object key in an IIOP message + +valuetype ObjectTemplate { + typedef sequence AdapterID ; + typedef sequence ObjectID ; + + AdapterID get_adapter_id() ; + CORBA::Object make_object( in ObjectID id ) ; + + factory init( in CORBA::Object ) ; +} + +local interface IORInfoExt : PortableInterceptor::IORInfo { + ObjectTemplate get_object_template() ; + void set_object_template( in ObjectTemplate otemp ) ; +} + +- ORB must provide an implementation for ObjectTemplateValueFactory and register it. + How does a portable application find it? Perhaps ObjectTemplateDefaultFactory? + If so, what is the constructor? + +interface Activator { + ObjectTemplate register_poa_template( in ObjectTemplate poaTemplate ) ; + ObjectTemplate lookup_poa_template( in AdapterID poaAID ) ; +} + +ORBD Activator: + +package com.sun.corba.ee.internal.PortableActivation ; + +import com.sun.corba.ee.PortableActivation.ObjectTemplate ; +import com.sun.corba.ee.PortableActivation.ObjectTemplateValueFactory ; +import com.sun.corba.ee.PortableActivation.Activator ; +import org.omg.CORBA_2_3.ORB ; +import org.omg.PortableServer.POA ; +import org.omg.CORBA.Policy ; + +class ORBDActivator implements Activator { + Activator( ORB orb ) { + this.orb = orb ; + POA rootPOA = (POA)orb.resolve_initial_references( ORBConstants.ROOT_POA_NAME ) ; + // This is probably not exactly the correct repository ID + otf = (ObjectTemplateFactory)(orb.lookup_value_factory( + "IDL:omg.org/Interceptors/ObjectTemplateFactory:1.0" ) ) ; + orbdTemplates = new HashMap() ; + poaTemplates = new HashMap() ; + } + + private ORB orb ; + + private poa rootPOA ; + + private ObjectTemplateValueFactory otf ; + + // Maps adapter ID for a Server POA to corresponding ORBD POA ObjectTemplate + private HashMap orbdTemplates ; + + // Maps adapter ID for an ORBD POA to corresponding Server POA ObjectTemplate + private HashMap poaTemplates ; + + private POA createPOA( String id ) throws AdapterAlreadyExists + { + Policy[] policies = new Policy[ 6 ] ; + int index = 0 ; + + policies[ index++ ] = rootPOA.create_lifespan_policy( PERSISTENT ) ; + policies[ index++ ] = rootPOA.create_id_uniqueness_policy( UNIQUE_ID ) ; + policies[ index++ ] = rootPOA.create_id_assignment_policy( USER_ID ) ; + policies[ index++ ] = rootPOA.create_servant_retention_policy( NON_REATIN ) ; + policies[ index++ ] = rootPOA.create_request_processing_policy( USE_SERVANT_MANAGER ) ; + policies[ index++ ] = rootPOA.create_implicit_activation_policy( NO_IMPLICIT_ACTIVATION ) ; + + try { + return rootPOA.create_POA( id, rootPOA.the_POAManager, policies ) ; + } catch (InvalidPolicy ip) { + // This should never happen + return null ; + } + } + + public ObjectTemplate register_poa_template( ObjectTemplate poaTemplate ) { + AdapterID poaAID = poaTemplate.get_adapter_id() ; + ObjectTemplate orbdTemplate = (ObjectTemplate)(orbdTemplates.get( poaAID )) ; + + if (orbdTemplate == null) { + POA newPOA = createPOA( poaAID ) ; + org.omg.CORBA.Object obj = newPOA.create_reference( "" ) ; + orbdTemplate = otf.init( obj ) ; + orbdTemplates.put( poaAID, orbdTemplate ) ; + } + + // policies may change: reregister every time + AdapterID orbdAID = orbdTemplate.get_adapter_id() ; + poaTemplates.put( orbdAID, poaTemplate ) ; + + return orbdTemplate ; + } + + public ObjectTemplate lookup_poa_template( AdapterID poaAID ) + { + return (ObjectTemplate)(poaTemplates.get( poaAID ) ) ; + } +} + +///////////////////////// ORBD Locator: + +class ORBDRequestInterceptor implements ServerRequestInterceptor { + private Current pic ; + private Activator activator ; + + ORBDRequestInterceptor( ORB orb ) + { + } + + void receive_request_service_contexts( ServerRequestInfo ri ) throws ForwardRequest + { + } + + void receive_request( ServerRequestInfo sri ) throws ForwardRequest { + byte[] adapterID = sri.adapter_id() ; + ObjectTemplate iort = activator.lookup_poa_template( adapterID ) ; + byte[] objectID = sri.object_id() ; + org.omg.CORBA.Object obj = iort.make_object( objectID ) ; + PortableInterceptor.Current pic = ; + Any any = orb.create_any() ; + any.insert_object( obj ) ; + pic.set_slot( MY_SLOT_ID, any ) ; + } + + void send_reply( ServerRequestInfo ri ) + { + } + + void send_exception( ServerRequestInfo ri ) throws ForwardRequset + { + } + + void send_other( ServerRequestInfo ri ) throws ForwardRequset + { + } +} + + Servant locator: + preinvoke( ) + { + PortableInterceptor.Current pic = ; + Any any = pic.get_slot( MY_SLOT_ID ) ; + org.omg.CORBA.Object obj = any.extract_object() ; + ForwardReqest fr = new ForwardRequest( obj ) ; + throw fr ; + } + + AdapterActivator: + - this is installed in the ORBD root POA + + unknown_adapter( POA parent, String name ) { + POA poa = parent.create_poa( name, parent.the_POAManager, policies ) ; + // Policies should be: + // PERSISTENT, + // UNIQUE_ID, + // USER_ID, + // NO_IMPLICIT_ACTIVATION, + // NON_RETAIN, + // USE_SERVANT_MANAGER, + + poa.set_servant_manager( orbdServantLocator ) ; + return true ; + } + +Server: + // This interceptor must run last OR add another point! + IORInterceptor: // Only do this for persistent POAs (How?) ! + establish_components( IORInfo info ) { + IORInfoExt extInfo = IORInfoExtHelper.narrow( info ) ; + ObjectTemplate otemp = extInfo.get_object_template() ; + Activator act = + // may want sid, orbid too + ObjectTemplate daemonTemplate = act.register_poa_template( otemp ) ; + info.set_object_template( daemonTemplate ) ; + } + +Server startup: + Activator passes appropriate org.omg.PortableInterceptor.ORBInitializer.XXX arguments + to server instance. This registers the IORInterceptor that handles the + persistent POA case. + + Note that the server activation model needs to allow addition of properties for registering + interceptors! + + +The full server activation model (SAM). + +We have: + +- A workgroup consists of one or more hosts (machines) +- A host with 0 or more registered servers +- Each server has 0 or more ORBs +- Each ORB has 0 or more persistent POAs + +(first release might assume only one host per workgroup). + +Our SAM should track: + +- startup and shutdown of servers + +// Note that ORB initializer post_init SHOULD be able to use ORB +- startup and shutdown of ORBs +- creation and destruction of POAs + +Various information may be made available for servers, ORBs, and POAs such as: + +- Start time +- Current state +- Re-creation count +- Number of invocations handled + +(first release probably would not do much here) + +All of this information should be maintained locally with low overhead, rather than +being maintained in a centralized server. + +There must be an Activator server running in a daemon (orbd) on every host that +is supporting persistent objects. + +There must be an Implementation Repository somewhere (may be shared across multiple +machines). The IMR defines the scope of a workgroup. + +There is a locator server that is responsible for forwarding requests to servers. +It uses information from the IMR and the Activator to find the servers. diff --git a/www/design/SAF/introduction.book b/www/design/SAF/introduction.book new file mode 100644 index 000000000..98358ca43 Binary files /dev/null and b/www/design/SAF/introduction.book differ diff --git a/www/design/SAF/introduction.doc b/www/design/SAF/introduction.doc new file mode 100644 index 000000000..3f4005303 Binary files /dev/null and b/www/design/SAF/introduction.doc differ diff --git a/www/design/SAF/introduction.pdf b/www/design/SAF/introduction.pdf new file mode 100644 index 000000000..2a36a1938 Binary files /dev/null and b/www/design/SAF/introduction.pdf differ diff --git a/www/design/SAF/introductionTOC.fm b/www/design/SAF/introductionTOC.fm new file mode 100644 index 000000000..1d878289f Binary files /dev/null and b/www/design/SAF/introductionTOC.fm differ diff --git a/www/design/SAF/old_activation_interaction.vthought b/www/design/SAF/old_activation_interaction.vthought new file mode 100644 index 000000000..7c8c1ba2b --- /dev/null +++ b/www/design/SAF/old_activation_interaction.vthought @@ -0,0 +1,759 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.4") + (buildDate "$Date: 2006/05/12 00:20:14 $") + (writeDate "Wed Mar 1, 2000 2:01:16 PM PST") + (documentPath "/home/kenc/work/design/SAF/old_activation_interaction.vthought") +) + +(document + (palette F) + (layout + (page "Letter") + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 617 161) + (size 711 969) + (zoom 1.158) + (documentLocation 0 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Bus") + (location 405 409.5) + (size 18 279) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 2) + (layer 1) + (type "Rectangle") + (location 405 702) + (size 54 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\ul server}}) + ) + (shape + (id 4) + (layer 3) + (type "Bus") + (location 522 458.1735) + (size 18 367.8979) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 5) + (layer 4) + (type "Rectangle") + (location 522 700.5304) + (size 72 38.9388) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\ul repository}}) + ) + (shape + (id 16) + (layer 15) + (type "Bus") + (location 198 459) + (size 18 378) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 17) + (layer 16) + (type "Bus") + (location 54 459) + (size 18 378) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText F) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + ) + (shape + (id 19) + (layer -1) + (type "Rectangle") + (location 54 701.294) + (size 54 37.4118) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\ul client}}) + ) + (shape + (id 22) + (layer 19) + (type "Rectangle") + (location 198 702) + (size 54 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\ul server manager}}) + ) +) + +(connections + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 2) + (points + (405 243) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 6) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 5) + (points + (522 243) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 7) + (layer 6) + (rotation 0) + (textRotation 0) + (locked F) + (end 1) + (points + (207 432) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.477) + (textWidth 114) + (textOffset 11) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc active(id, callback)}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "ThinFlatArrow") + ) + (connection + (id 8) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (points + (288 558) + (207 558) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.556) + (textWidth 98) + (textOffset 10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc return ServerDef}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "OpenThinArrow") + ) + (connection + (id 9) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 1) + (points + (288 468) + (207 468) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 116) + (textOffset 10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc return ORBD port}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "OpenThinArrow") + ) + (connection + (id 10) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 17) + (points + (126 396) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 98) + (textOffset 10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc location forward}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "OpenThinArrow") + ) + (connection + (id 11) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (start 1) + (points + (180 324) + (63 324) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.738) + (textWidth 80) + (textOffset 10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc reply}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "OpenThinArrow") + ) + (connection + (id 12) + (layer 11) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 1) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.471) + (textWidth 78) + (textOffset 11) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc getEndpoint}) + (drawStartArrowhead T) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "ThinFlatArrow") + ) + (connection + (id 13) + (layer 12) + (rotation 0) + (textRotation 0) + (locked F) + (start 17) + (end 1) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.181) + (textWidth 60) + (textOffset 11) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc invoke}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "ThinFlatArrow") + ) + (connection + (id 14) + (layer 13) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 1) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.289) + (textWidth 78) + (textOffset 11) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc exec server}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "ThinFlatArrow") + ) + (connection + (id 15) + (layer 14) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 4) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.198) + (textWidth 78) + (textOffset 11) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc getServer(id)}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "ThinFlatArrow") + ) + (connection + (id 20) + (layer -1) + (rotation 0) + (textRotation 0) + (locked F) + (start 19) + (points + (54 243) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 21) + (layer 18) + (rotation 0) + (textRotation 0) + (locked F) + (end 16) + (points + (63 630) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.471) + (textWidth 60) + (textOffset 11) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc invoke}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "ThinFlatArrow") + ) + (connection + (id 23) + (layer 20) + (rotation 0) + (textRotation 0) + (locked F) + (start 22) + (points + (198 243) + ) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (dash + (pattern 3 3) + (offset 0) + ) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead F) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) +) + +(groups + (group + (id 18) + (layer 17) + (rotation 0) + (locked F) + (contents 19 20) + ) +) diff --git a/www/design/SAF/old_imr_class.vthought b/www/design/SAF/old_imr_class.vthought new file mode 100644 index 000000000..37eb7d417 --- /dev/null +++ b/www/design/SAF/old_imr_class.vthought @@ -0,0 +1,278 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.4") + (buildDate "$Date: 2006/05/12 00:20:15 $") + (writeDate "Wed Mar 1, 2000 2:02:39 PM PST") + (documentPath "/home/kenc/work/design/SAF/old_imr_class.vthought") +) + +(document + (palette F) + (layout + (page "Letter") + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 275 167) + (size 728 987) + (zoom 1.1875) + (documentLocation 5 0) + (gridSnap T) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 1) + (layer 0) + (type "Rectangle") + (location 148.5 103.5) + (size 243 189) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\b Repository} +\par __________ +\par __________ +\par +\par \pard registerServer( serverDef ) : serverId +\par unregisterServer( serverId ) +\par getServer( serverId ) : ServerDef +\par isInstalled( serverId ) : boolean +\par install( serverId ) +\par uninstall( serverId ) +\par listRegisteredServers : ServerIds +\par getApplicationNames : StringSeq +\par getServerID( applicationName ) : serverId}) + ) + (shape + (id 4) + (layer 3) + (type "Rectangle") + (location 216 252) + (size 108 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\b ServerManager}}) + ) + (shape + (id 5) + (layer 4) + (type "Rectangle") + (location 405 409.5) + (size 324 99) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\b Locator} +\par __________ +\par __________ +\par +\par \pard locateServer( serverId, endpointType ) : ServerLocation +\par getEndpoint( endpointType ) : tcpPort}) + ) + (shape + (id 6) + (layer 5) + (type "Rectangle") + (location 121.5 387) + (size 189 144) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\b Activator} +\par __________ +\par __________ +\par +\par \pard active( serverId, serverObj ) +\par getActiveServers() : ServerIds +\par activate( serverId ) +\par shutdown( serverId ) +\par install( serverId ) +\par uninstall( serverId )}) + ) + (shape + (id 7) + (layer 6) + (type "Rectangle") + (location 418.5 144) + (size 225 108) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "top") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\b Server} +\par __________ +\par __________ +\par \pard shutdown +\par install +\par uninstall +\par getEndpoint( endpointType ) : tcpPort}) + ) +) + +(connections + (connection + (id 2) + (layer 1) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 5) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.45) + (textWidth 72) + (textOffset -10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc name}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "HollowFlatArrow") + ) + (connection + (id 3) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 4) + (end 6) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.45) + (textWidth 72) + (textOffset -10) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc name}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "HollowFlatArrow") + ) +) + +(groups +) diff --git a/www/design/SAF/portable.doc b/www/design/SAF/portable.doc new file mode 100644 index 000000000..68fa250b8 Binary files /dev/null and b/www/design/SAF/portable.doc differ diff --git a/www/design/SAF/server_activation.mif b/www/design/SAF/server_activation.mif new file mode 100644 index 000000000..46896ed72 --- /dev/null +++ b/www/design/SAF/server_activation.mif @@ -0,0 +1,1898 @@ + +# Creator: Visual Thought-1.5 +# For: ken +# Title: server_activation.vthought +# Creation Date: Fri Sep 15, 2000 5:11:10 PM PDT + # All dimensions are in points + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > + + + + + + + + > +> # end of ColorCatalog +#----- Begin mifref header + + + # ShapeRect L T W H: the position and size of the frame. + # [ integer_point_values ] + # If you uncomment the ShapeRect line below, the anchored frame + # created in the output MIF file will always have the bounds specified. + # This feature allows you to create standard-sized anchored frames. + # Otherwise, the bounding box of the objects in the input MIF file + # will be used as the bounding box of the anchored frame. + # + + # FrameType: whether frame is anchored, and if anchored its position. + # [ Below, Top, Bottom, Inline, Left, Right, Inside, Outside, + # Near, Far, RunIntoParagraph, NotAnchored ] + + + # Float: Whether frame is floating. + # [ Yes, No ] + # Yes floats graphic frame to avoid large white space that results + # when anchored frame and the line containing it are moved to the + # next page. + # + + # NSOffset: Near-side offset. + # [ integer_point_value ] + # + + # BLOffset: Baseline offset. + # [ integer_point_value ] + # + + # AnchorAlign: Aligment of anchored frame. + # [ Left, Center, Right, Inside, Outside ] + # + + # AnchorBeside: Whether the graphic frame is anchored outside of a text + # frame or a column in a text frame. + # [ Column, TextFrame ] + # + + # Cropped: Yes clips sides of graphic frame to fit column. + # [ Yes, No ] + # +#----- End mifref header + # Anchored frame bounding box. + + # End of anchored frame bounding box. + + + + + + + + + +> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + > + + + + + + + + + + + + + + + + + + + + + + + +> + + + + + + + + + + + + + +> + + + + + + > + + + + + + + + + + +> + + + + + + + + + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> + + + + + + + + + + + + > + +> +# End of MIFFILE +#----- Begin mifref footer +# Brackets closing the AFrame statement started in mifhead.txt. + > +> +# TextFlow definition allow MIF import by reference in FrameMaker 5. + + > + > # end of Para +> # end of TextFlow +#----- End mifref footer diff --git a/www/design/SAF/server_activation.vthought b/www/design/SAF/server_activation.vthought new file mode 100644 index 000000000..d3c89e2ca --- /dev/null +++ b/www/design/SAF/server_activation.vthought @@ -0,0 +1,633 @@ +; +; Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +; +; This program and the accompanying materials are made available under the +; terms of the Eclipse Distribution License v. 1.0, which is available at +; http://www.eclipse.org/org/documents/edl-v10.php. +; +; SPDX-License-Identifier: BSD-3-Clause + +; Visual Thought 1.0 + +(header + (program "vthought") + (version "1.5") + (buildDate "$Date: 2006/05/12 00:20:16 $") + (writeDate "Fri Sep 15, 2000 5:10:36 PM PDT") + (documentPath "/home/ken/work/design/SAF/server_activation.vthought") +) + +(document + (palette F) + (layout + (page "Custom") + (pageDescription + (orientation "portrait") + (size 504 360) + (dscPageSize "Letter") + (paperTray "lettertray") + (paperSize "letter") + ) + (units "Inches") + (orientation "portrait") + (numberOfPages 1 1) + (scale 100) + (margins 18 18 18 18) + ) +) + +(views + (view + (location 58 99) + (size 986 961) + (zoom 2) + (documentLocation 0 0) + (gridSnap F) + (gridVisibility F) + (gridSpacing 9) + (pageBreaks T) + (toolVisibility T) + (rulerVisibility T) + ) +) + +(shapes + (shape + (id 2) + (layer -1) + (type "Rectangle") + (location 262 200.5) + (size 64 55) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 timeout +\par ------- +\par kill process +\par unblock waiters +\par log error}}) + ) + (shape + (id 3) + (layer -1) + (type "Rectangle") + (location 198.5 199) + (size 69 60) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 server dies +\par --------- +\par cancel timer +\par unblock waiters +\par log error +\par } +\par \pard }) + ) + (shape + (id 5) + (layer -1) + (type "Rectangle") + (location 107 93.5) + (size 64 55) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 timeout +\par ------- +\par kill process +\par unblock waiters +\par log error}}) + ) + (shape + (id 6) + (layer -1) + (type "Rectangle") + (location 43.5 92) + (size 69 60) + (rotation 0) + (locked F) + (style + (filled F) + (fillColor 65535 65535 65535) + (stroked F) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 server dies +\par --------- +\par cancel timer +\par unblock waiters +\par log error +\par } +\par \pard }) + ) + (shape + (id 16) + (layer 11) + (type "Rounded Rectangle") + (location 234 270) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc starting}) + ) + (shape + (id 17) + (layer 12) + (type "Rounded Rectangle") + (location 396 162) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc running}) + ) + (shape + (id 18) + (layer 13) + (type "Rounded Rectangle") + (location 234 54) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc stopping}) + ) + (shape + (id 19) + (layer 14) + (type "Rounded Rectangle") + (location 72 162) + (size 72 36) + (rotation 0) + (locked F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (flipHorizontal F) + (flipVertical F) + (showText T) + (textVerticalAlignment "center") + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc stopped}) + ) +) + +(connections + (connection + (id 7) + (layer 2) + (rotation 0) + (textRotation 0) + (locked F) + (start 17) + (end 17) + (points + (448 167) + (457 176) + (456 187) + (448 194) + (439 194) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.704) + (textWidth 82) + (textOffset -85) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 locate +\par ------ +\par wait for ORB +\par activation}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 8) + (layer 3) + (rotation 0) + (textRotation 0) + (locked F) + (start 18) + (end 18) + (points + (180.4388 50) + (171.4388 41) + (171.4388 32) + (180.4388 23) + (189.4388 23) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.488) + (textWidth 72) + (textOffset 34) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 locate +\par ------ +\par block}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 9) + (layer 4) + (rotation 0) + (textRotation 0) + (locked F) + (start 18) + (end 19) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 10) + (layer 5) + (rotation 0) + (textRotation 0) + (locked F) + (start 17) + (end 18) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.488) + (textWidth 72) + (textOffset -39) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 shutdown +\par -------- +\par start timer}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 11) + (layer 6) + (rotation 0) + (textRotation 0) + (locked F) + (start 17) + (end 19) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.278) + (textWidth 94) + (textOffset -24) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 server dies +\par --------- +\par unblock waiters +\par log error}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 12) + (layer 7) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 17) + (curved F) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.625) + (textWidth 72) + (textOffset -27) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 server registers +\par --------- +\par cancel timer +\par unblock waiters}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 13) + (layer 8) + (rotation 0) + (textRotation 0) + (locked F) + (start 16) + (end 16) + (points + (288 270) + (297 279) + (297 288) + (288 297) + (279 297) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.505) + (textWidth 72) + (textOffset 34) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 locate +\par ------ +\par block}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 14) + (layer 9) + (rotation 0) + (textRotation 0) + (locked F) + (end 19) + (points + (202.5 252) + (189 234) + (162 211) + (129 189) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText F) + (textDistancePercentage 0.5) + (textWidth 72) + (textOffset 0) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc Text}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) + (connection + (id 15) + (layer 10) + (rotation 0) + (textRotation 0) + (locked F) + (start 19) + (end 16) + (points + (78 204) + (94 229) + (124 252) + (158 265) + ) + (curved T) + (style + (filled T) + (fillColor 65535 65535 65535) + (stroked T) + (strokeColor 0 0 0) + (lineWidth 1) + (shadowed F) + (shadowColor 39321 39321 39321) + ) + (showText T) + (textDistancePercentage 0.5) + (textWidth 90) + (textOffset -47) + (rtfText{\rtf1\ansi\deff0 +{\fonttbl{\f0\fnil helvetica medium;}} +{\colortbl\red0\green0\blue0;} +\cf0\plain\pard\qc {\fs16 locate +\par ------ +\par exec process +\par start timer +\par block}}) + (drawStartArrowhead F) + (drawEndArrowhead T) + (startArrowhead "StandardArrow") + (endArrowhead "StandardArrow") + ) +) + +(groups + (group + (id 1) + (layer 0) + (rotation 0) + (locked F) + (contents 2 3) + ) + (group + (id 4) + (layer 1) + (rotation 0) + (locked F) + (contents 5 6) + ) +) diff --git a/www/design/ThreadPool.html b/www/design/ThreadPool.html new file mode 100644 index 000000000..d5dae3c31 --- /dev/null +++ b/www/design/ThreadPool.html @@ -0,0 +1,340 @@ + + + + + + + + + ThreadPool Element in Server.xml + + +

                      ThreadPool Configuration in the Application Server

                      +

                      Introduction

                      Based on discussions and collective agreement, it is + felt that the ThreadPool should really be a separate element in the server.xml + instead of getting bundled in with the ORB element as it exists today in S1AS + 7.0. +

                      This document describes why this is useful to do and how this could be + achieved.

                      +

                      ThreadPool configuration and DTD

                      If ThreadPool was made a + separate element in the server.xml it would allow the user to configure more + than one ThreadPools (if required) and associate these threadpools to other + components of the Application Server (ORB, Connectors etc.). This would + encourage code re-use as well as give the user controls to tune the Application + Server based on the load in the system and in different sub-systems (ORB, + Connectors etc.). Inherent advantages offered by this scheme: +
                        +
                      • One single place for the user to specify different threadpools + configuration params
                      • +
                      • Ability to have multiple threadpools. This will aid in starvation + problems and help improve performace (ECPerf)
                      • +
                      • Ability to dedicate threadpools/work-queues to App. server + components and EJB beans if desired.
                      • +
                      • Allow monitoring and administration on the + threadpool/work-queues
                      • +
                      The DTD given below describes the ThreadPool configuration element. + This element would be at the same level as the other components like + http-service, iiop-service, web-container, ejb-container etc. in the S1AS 8.0 + server.xml DTD (http://iaseng.red.iplanet.com/apollo/config/sun-server_8_0.dtd): +
                        +

                      <!ELEMENT thread-pool-config + (thread-pool+)>

                      +

                      <!--
                           + thread-pool-id                               + This is an id for the work-queue e.g. "thread-pool-1", "thread-pool-2" + etc
                           + min-thread-pool-size                     + Minimum number of threads in the threadpool servicing requests in this + queue.
                                                                               + These are created up front when this threadpool is instantiated +
                           + max-thread-pool-size                    + Maximum number of threads in the threadpool servicing requests in this + queue
                                                                               + This is the upper bound on the no. of threads that exist in the + threadpool.
                           + idle-thread-timeout-in-seconds      idle threads are + removed from pool, after this time
                           + num-work-queues                         + This denotes the total number of work queues that are serviced by this + threadpool.
                                                                                + Default value would be 1
                      -->

                      +

                      <!ELEMENT thread-pool(EMPTY)> +
                      <!ATTLIST thread-pool  + thread-pool-id                          + CDATA     #REQUIRED
                                                             + min-thread-pool-size                 + CDATA     "0"
                                                             + max-thread-pool-size                + CDATA     "200"
                                                             + idle-thread-timeout-in-seconds  CDATA     "120" +
                                                             + num-work-queues                     + CDATA     "1">

                      +

                      <!--  The ORB element would look like + ...

                      +

                              + use-thread-pool-ids                        + This would refer to the thread-pool-id(s) defined in the thread-pool + sub-element of
                                                                                    + thread-pool-config element in server.xml. These would be the threadpool(s) used + by the
                                                                                    + ORB. More than one thread-pool-id(s) could be specified by using commas to + separate
                                                                                    + the names e.g. "orb-thread-pool-1, orb-thread-pool-2"
                      -->

                      +

                      <!ELEMENT orb (property*)>
                      <!ATTLIST orb  + message-fragment-size          + CDATA     "1024"
                                     + use-thread-pool-ids                           + IDREFS         #REQUIRED +
                                     + max-connections                               + CDATA         "1024"
                                     + ....
                                     + ...>

                      +

                      Essentially, thread-pool-config is a server wide element, that consists + of atleast 1 or more thread-pool elements.

                      +

                      A ThreadPoolManagerImpl class could be used as a singleton instance, to + create all the ThreadPools at server startup using the configuration parameters + defined in the threadpool-config element of the server.xml. Any component can + then get the threadpool instance by providing the threadpool-id to this + singleton ThreadPoolManager instance. Using this threadpool instance a work + queue serviced by this threadpool can be obtained. Work can be added to the + queue and it will get processed by the threads of the threadpool.

                      +

                      EJB descriptors (or module descriptors - not sure if there is anything + like this) could use the threadpool-ids defined in the server.xml to denote if + the EJB (module) would want to use a dedicated threadpool. This could be done + to avoid starvation. If nothing is specified or incorrect threadpool-id is + specified in the bean descriptors, then the threadpool associated with the ORB + will be used to service requests from that bean.
                       
                       

                      +

                      ThreadPoolManager SPI

                      This section defines the ThreadPoolManager + SPI. This SPI will be defined in com.sun.corba.ee.spi....(the exact package + name is TBD) +

                      This interface will be implemented by the ThreadPoolManagerImpl class in + App. Server PE 8.0. It will be responsible for returning an instance of the + ThreadPool given a thread-pool-id, from any component that wants to use a + ThreadPool. In addition, ThreadPoolManagerImpl class will be responsible for + creating all the threadpools (and their queues) at server startup time. This is + done using the config bean that reads the thread-pool-config element in + server.xml. ThreadPoolManager instance would be a singleton instance in the + App. Server process.
                       

                      +

                      public interface ThreadPoolManager { +

                      +

                          /**
                          + * This method will return an instance of the threadpool given a + threadpoolId,
                          * that + can be used by any component in the app. server.
                          */
                          public ThreadPool getThreadPool(String + threadpoolId);

                      +

                          /**
                          + * This method will return an instance of the threadpool given a numeric + threadpoolId.
                          * This + method will be used by the ORB to support the functionality of +
                          * dedicated threadpool for EJB + beans
                          */ +
                          public ThreadPool + getThreadPool(int numericIdForThreadpool);

                      +

                          /**
                          + * This method is used to return the numeric id of the threadpool, given a + String
                          * + threadpoolId. This is used by the POA interceptors to add the numeric + threadpool
                          * Id, as + a tagged component in the IOR. This is used to provide the functionality + of
                          * dedicated + threadpool for EJB beans
                          */
                          public int  getNumericId(String + threadpoolId);

                      +

                          /**
                          + * Return a String Id for a numericId of a threadpool managed by the + threadpool
                          * + manager
                          + */
                          public String + getStringId(int numericIdForThreadpool);

                      +

                          /**
                          + * Returns the first instance of ThreadPool in the ThreadPoolManager +
                          */
                          public ThreadPool + getDefaultThreadPool();

                      +

                      }

                      +

                      An implementation of this SPI will also exist in the ORB that ships with + J2SE, so that the ORB code that uses these API does not change for J2SE. +
                       

                      +

                      ThreadPool SPI

                      This section defines the ThreadPool SPI. This SPI + will be defined in com.sun.corba.ee.spi....(the exact package name is TBD) +

                      The ORB already has plans for having an interface like that as part of + the work being done on the design of the ORB transport. I am adding more APIs + to the designed interface for this done by Harold Carr.

                      +

                      public interface ThreadPool {

                      +

                          /**
                          + * This method will return any instance of the WorkQueue. If the + ThreadPool
                          * + instance only services one WorkQueue then that WorkQueue instance + will
                          * be returned. + If there are more than one WorkQueues serviced by this
                          * ThreadPool, then this method would return + a WorkQueue based on the
                          * implementation of the class that + implements this interface. For PE 8.0 we
                          * would return a WorkQueue in a roundrobin + fashion everytime this method
                          * is called. In the future we could allow + pluggability of  Policy objects for this.
                          */
                          public WorkQueue + getAnyWorkQueue();

                      +

                          /**
                          + * This method will return an instance of the of the WorkQueue given a + queueId.
                          * This will + be useful in situations where there are more than one WorkQueues +
                          * managed by the ThreadPool and + the user of the ThreadPool wants to always use
                          * the same WorkQueue for doing the + Work.
                          * If the + number of WorkQueues in the ThreadPool are 10, then queueIds will go +
                          * from 0-9 +
                          */
                          public WorkQueue getWorkQueue(int + queueId);

                      +

                          /**
                          + * This method will return the number of WorkQueues serviced by the + threadpool.
                          + */
                          public int + numberOfWorkQueues();

                      +

                          /**
                          + * This method will return the minimum number of threads maintained by the + threadpool.
                          + */
                          public int + minimumNumberOfThreads();

                      +

                          /**
                          + * This method will return the maximum number of threads in the threadpool at + any
                          * point in time, + for the life of the threadpool
                          */
                          public int + maximumNumberOfThreads();

                      +

                          /**
                          + * This method will return the time in milliseconds when idle threads in the + threadpool are
                          * + removed.
                          + */
                          public long + idleTimeoutForThreads();

                      +

                          /**
                          + * This method will return the current number of threads in the threadpool. This + method
                          * returns a + value which is not synchronized.
                          */
                          public int + currentNumberOfThreads();

                      +

                          /**
                          + * This method will return the number of available threads in the threadpool + which are
                           * + waiting for work. This method returns a value which is not + synchronized.
                          + */
                          public int + numberOfAvailableThreads();

                      +

                          /**
                          + * This method will return the number of busy threads in the + threadpool
                          * This + method returns a value which is not synchronized.
                          + */
                          public int + numberOfBusyThreads();

                      +

                          /**
                          + * This method returns the number of Work items processed by the + threadpool
                          + */
                          public long + currentProcessedCount();

                      +

                          /**
                          + * This method will return the name of the threadpool.
                          */
                          public String getName();

                      +

                      }
                       

                      +

                      WorkQueue SPI

                      This section defines the WorkQueue SPI. This SPI + will be defined in com.sun.corba.ee.spi....(the exact package name is TBD) +

                      The ORB already has plans for having an interface like that as part of + the work being done on the design of the ORB transport by Harold Carr. The + following has been borrowed from that design

                      +

                      public interface WorkQueue {

                      +

                          /**
                          + * This method is used to add work to the WorkQueue
                          */
                          public void addWork(Work + aWorkItem);

                      +

                          /**
                          + * This method will return the name of the WorkQueue.
                          */
                          public String getName();

                      +

                          /**
                          + * Returns the total number of Work items added to the Queue. +
                          */
                          public long + totalWorkItemsAdded();

                      +

                          /**
                          + * Returns the total number of Work items in the Queue to be + processed.
                          + */
                          public int + workItemsInQueue();

                      +

                      }
                       

                      +

                      Work SPI

                      This section defines the Work SPI. This SPI will be + defined in com.sun.corba.ee.spi....(the exact package name is TBD) +

                      The ORB already has plans for having an interface like that as part of + the work being done on the design of the ORB transport by Harold Carr. The + following has been borrowed from that design

                      +

                      public interface Work {

                      +

                          public void + doWork();

                      +

                          public String + getName();

                      +

                      }

                      + diff --git a/www/design/copyobject.htm b/www/design/copyobject.htm new file mode 100644 index 000000000..edfa7db3a --- /dev/null +++ b/www/design/copyobject.htm @@ -0,0 +1,275 @@ + + + + + + + Copyobject Design + + +

                      The Design of the Copyobject Facility

                      +

                      CORBA supports both remote (across a network) and co-located invocation + of object references. Obviously the remote case requires mechanisms such as + connections and marshalling in order to communicate remotely. However, we do + not want to pay this high overhead for communicating with an object reference + when it is co-located with the invoker. For this reason, the RMI-IIOP standard + supports a co-located call optimization at the stub level.

                      +

                      An RMI-IIOP stub consists of two parts:

                      +
                        +
                      • A Java type specific Stub, which has the methods given by the remote + interface.
                      • +
                      • A Java type independent Delegate, which has portable, standard + methods for performing invocations.
                      • +
                      +

                      This co-located call optimization obtains the servant (i.e. the + implementation of the remote interface) from the delegate by the + servant_preinvoke method, and then directly invokes the method on the servant, + completely bypassing all transport mechanisms in the ORB. However, the CORBA + and J2EE specifications require that co-located calls preserve the same + semantics as remote ones, in that all objects must be copied when they are + passed on a co-located call. The reason for this is to avoid interference + between client and server threads in the co-located case that could not occur + in the remote case.

                      +

                      This object copying is commonly performed by using a CDR stream to copy + the objects. This bypasses the transport overhead associated with TCP/IP + connections, but the cost of copying the data is still considerable. Any kind + of marshalling stream must do certain operations, such as linearizing the data, + that are not necessary when an object is simply copied.

                      +

                      Some Benchmark Results

                      +

                      I have a benchmark on object copying that runs as part of the CORBA + units tests. The test copies data created by + NonFinalComplexClass.makeNonFinalComplexGraph() in a loop 2000 times. Here is + the class that is copied:

                      +
                      +private static class NonFinalComplexClass implements java.io.Serializable {
                      +    public boolean publicBoolean = false ;
                      +    protected char protectedChar = 'D' ;
                      +    private byte privateByte = (byte)3 ;
                      +    short shrt = (short)-2345 ;
                      +    public int finalPublicInt = 273415 ;
                      +    protected long finalProtectedLong = 38958284 ;
                      +    private float finalPrivateFloat = (float)3.1415926535 ;
                      +    double finalDouble = 2.718281828 ;
                      +    String str1 ;
                      +    String str2 ;
                      +    private Object finalPrivateObject1 = new HashMap() ;
                      +    private Object finalPrivateObject2 = finalPrivateObject1 ;
                      +    public Object[] references ;
                      +
                      +    public NonFinalComplexClass( String name )
                      +    {
                      +        str1 = name ;
                      +        str2 = str1 ;
                      +    }
                      +
                      +    public static NonFinalComplexClass makeNonFinalComplexClass(String str )
                      +    {
                      +        return new NonFinalComplexClass( str ) ;
                      +    }
                      +
                      +    public static NonFinalComplexClass makeNonFinalComplexClassAliasedArray(String str )
                      +    {
                      +        int num = 5 ;
                      +        NonFinalComplexClass[] classes = new NonFinalComplexClass[ num ] ;
                      +
                      +        for (int ctr = 0; ctr<num; ctr++ ) {
                      +            classes[ctr] = makeNonFinalComplexClass( str + ":member " + ctr ) ;
                      +            if (ctr==0) { // 0th classes references all others
                      +                classes[ctr].references = new NonFinalComplexClass[num] ;
                      +            } else { // others reference only 0th, but allocate
                      +                     // different sizes reference arrays
                      +                classes[ctr].references = new NonFinalComplexClass[ctr] ;
                      +                classes[ctr].references[0] = classes[0] ;
                      +            }
                      +
                      +            // Make 0th class reference the others
                      +            classes[0].references[ctr] = classes[ctr] ;
                      +        }
                      +
                      +        return classes[0] ;
                      +    }
                      +
                      +    public static NonFinalComplexClass makeNonFinalComplexClassGraph()
                      +    {
                      +        int num = 5 ;
                      +        NonFinalComplexClass[] classes = new NonFinalComplexClass[ num ] ;
                      +
                      +        for (int ctr = 0; ctr<num; ctr++ ) {
                      +            classes[ctr] = makeNonFinalComplexClassAliasedArray(
                      +                "group " + ctr ) ;
                      +            if (ctr==0) { // 0th classes references all others
                      +                classes[ctr].references = new NonFinalComplexClass[num] ;
                      +            } else { // others reference only 0th, but allocate
                      +                     // different sizes reference arrays
                      +                classes[ctr].references = new NonFinalComplexClass[ctr] ;
                      +                classes[ctr].references[0] = classes[0] ;
                      +            }
                      +
                      +            // Make 0th class reference the others
                      +            classes[0].references[ctr] = classes[ctr] ;
                      +        }
                      +
                      +        return classes[0] ;
                      +    }
                      +}
                      +
                      +

                      My testbed is configured as follows:

                      +
                        +
                      • JDK 1.5.0_02
                      • +
                      • Red Hat Linux 9
                      • +
                      • Athlon XP 2600+ (2 GHz)
                      • +
                      • 2 GB PC3200 RAM
                      • +
                      +

                      This results in the following copy times for the different copiers that + we currently support:

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      Copier ImplementationObject timeArray timeAliasedArray timeGraph time
                      newreflect121342950923
                      newreflect fallback97363874862
                      old reflect9227311531115
                      ORB Stream72156842673671
                      Java Stgream5166011561189
                      +

                      All times are given in microseconds needs to copy the object. There are + a number of intersting points about the data in this table:

                      +
                        +
                      1. Java serialization is quite fast, and in fact is considerably faster + in J2SE 5 than in previous releases.
                      2. +
                      3. The old reflect copier is nearly identical to the one that we shipped + in AS 7. We don't actually use this version in AS 8.x, but I keep it around in + the benchmarks for comparison purposes.
                      4. +
                      5. The new reflect copier is significantly faster than either + stream-based copier for all but the most trivial of operations. The fact that + the fallback version is faster likely just reflects HotSpot optimization + behavior, as this test never triggers the fallback behavior.
                      6. +
                      7. The Java serialization implementation is now 2-4 times faster than + the ORB serialization (CDR). This means that JSG should be considerably faster + than CDR for marshalling in many cases (and this will be the subject of Ram's + performance work on JSG in the future).
                      8. +
                      +

                      ORB SPI for Object Copying

                      +

                      The ORB currently supports both the optimized reflective copier, and an + object copier that simply passes all objects through by reference without doing + any copies. Either copier can be selected for each EJB deployed in the app + server by means of the CopyObjectPolicy (in spi.extension), which can be + applied to any POA. Since each EJB has its own POA, we can configurate copying + behavior independently for each EJB.

                      +

                      Like most things in the ORB, object copying is configured by registering + a factory against the ORB. The default configuration of the ORB contains only + the standard stream-based copier, but the AS 8.1 initialization includes two + others: the newreflect fallback copier mentioned in the benchmark, and also the + pass-by-reference "copier", which actually does no copies at all. The + configuration in the app server is handled in appserv-core in the + com.sun.enterprise.iiop.PEORBConfigurator.configureCopiers method.

                      +

                      The basic interface for copyObject is simply:

                      +
                      package com.sun.corba.ee.spi.copyobject ;
                      +
                      +/** Provides an interface for a variety of means to copy an arbitrary object.
                      + * Any implementation of this interface must return an exact copy of obj,
                      + * preserving all aliasing across all objects reachable from obj.  
                      + * ReflectiveCopyException must be thrown if the implementation cannot copy
                      + * obj for some reason.  Note thyat a trivial implementation of this 
                      + * interface is possible (always return obj), but this is often not the
                      + * desired implementation.
                      + */
                      +public interface ObjectCopier {
                      +    Object copy( Object obj ) throws ReflectiveCopyException ;
                      +}
                      +

                      This method will copy any object presented to it. Multiple calls to copy + on the same instance of an ObjectCopier implementation will preserve all + aliasing between different objects reachable from objects passed as arguments + to copy.

                      +

                      In addition, there is a simple factory interface:

                      +
                      package com.sun.corba.ee.spi.copyobject ;
                      +
                      +public interface ObjectCopierFactory {
                      +    ObjectCopier make() ;
                      +}
                      +

                      This trivial API is provided so that different ObjectCopier + implementations can be registered with the ORB's CopierManager, which has the + following interface:

                      +
                      +package com.sun.corba.ee.spi.copyobject ;
                      +
                      +/** Manager of ObjectCopier implementations used to support javax.rmi.CORBA.Util.copyObject(s).
                      + * This provides simple methods for registering all supported ObjectCopier factories. 
                      + * A default copier is also supported, for use in contexts where no specific copier id
                      + * is available.
                      + */
                      +public interface CopierManager
                      +{
                      +    /** Set the Id of the copier to use if no other copier has been set.
                      +     */
                      +    void setDefaultId( int id ) ;
                      +
                      +    /** Return the copier for the default copier id.  Throws a BAD_PARAM exception
                      +     * if no default copier id has been set.
                      +     */
                      +    int getDefaultId() ;
                      +
                      +    ObjectCopierFactory getObjectCopierFactory( int id ) ;
                      +
                      +    ObjectCopierFactory getDefaultObjectCopierFactory() ;
                      +
                      +    /** Register an ObjectCopierFactory under a particular id.  This can be retrieved
                      +     * later by getObjectCopierFactory.
                      +     */
                      +    void registerObjectCopierFactory( ObjectCopierFactory factory, int id ) ;
                      +}
                      +
                      +

                      (explain this)

                      +

                      For direct use, an application could directly obtain the needed + ObjectCopierFactory from one of the copy object defaults classes:

                      +

                      Packaging Considerations

                      +

                      +

                      Some Difficulties in copying objects

                      +

                      +

                      The Design of the Reflective Copier

                      +

                      + diff --git a/www/design/corba_testing_extensions.htm b/www/design/corba_testing_extensions.htm new file mode 100644 index 000000000..766f81be8 --- /dev/null +++ b/www/design/corba_testing_extensions.htm @@ -0,0 +1,101 @@ + + + + + + + Extending the CORBA test framework + + +

                      Introduction

                      +

                      The CORBA project's testing requirements have been met by a custom + framework oringinally written by IBM. This was enhanced to include the + capability to run tests that require multiple separate processes by the + addition of the corba.framework.CORBATest class, originally written by Everett + Anderson. I have enhanced the framework in some ways as well, in particular by + making it easy to debug tests. In addition a number of more recent tests have + been written using JUnit, which provides a very effective unit test + framework.

                      +

                      While this framework has worked well for some time, recent developments + suggest the need for further evolution. In no particular order, here are some + recent considerations:

                      +
                        +
                      1. It would be useful to change the port numbers used in the tests so + that more than one developer can share a single fast server machine.
                      2. +
                      3. We should be able to run tests against both the compiled class files + (for quick turnaround) and against the as-delivered jar files (for final + verification).
                      4. +
                      5. A number of recent features are configurable in ways that have global + effects on all tests. This includes JSG, Dynamic RMI-IIOP, and nio select.
                      6. +
                      +

                      This suggests that we need to enhance both the description of our tests, + and the description of the environment used to run the tests. The standard way + to do this nowadays is XML, but I'll probably consider something scheme based + instead, or perhaps Harold's lxml syntax.

                      +

                      Test Environment

                      +

                      There are a large number of parameters that are configured for + tests:

                      +
                        +
                      1. Current working directory is assumed to be <ws>/test/make (ws + may be renamed)
                      2. +
                      3. System properties: +
                          +
                        1. javax.rmi.CORBA.UtilClass = + com.sun.corba.ee.impl.javax.rmi.CORBA.Util
                        2. +
                        3. javax.rmi.CORBA.StubClass = + com.sun.corba.ee.impl.javax.rmi.CORBA.StubDelegateImpl
                        4. +
                        5. javax.rmi.CORBA.PortableRemoteObjectClass = + com.sun.corba.ee.impl.javax.rmi.PortableRemoteObject
                        6. +
                        7. http.server.port = 9090
                        8. +
                        9. java.rmi.server.codebase = http://localhost:9090/
                        10. +
                        11. http.server.root.directory = + ../../values/build/$(ARCH)/classes
                        12. +
                        13. java.security.policy = ../src/share/classes/test.policy
                        14. +
                        15. java.security.debug = debug
                        16. +
                        17. org.omg.CORBA.ORBClass = com.sun.corba.ee.impl.orb.ORBImpl
                        18. +
                        19. org.omg.CORBA.ORBSingletonClass = + com.sun.corba.ee.impl.orb.ORBSingleton
                        20. +
                        21. com.sun.CORBA.POA.ORBServerId = 1
                        22. +
                        23. com.sun.COBRA.ORBBase = $(BASEDIR)
                        24. +
                        25. com.sun.CORBA.ORBArch = $(ARCH)
                        26. +
                        27. com.sun.CORBA.test.sourcepath = $(TESTSOURCEPATH) (this contains + the normal source, the generated source, and the test source, but does not seem + to be used)
                        28. +
                        29. com.sun.CORBA.ORBUseDynamicStubClass = true or not set
                        30. +
                        31. com.sun.CORBA.ORBUseBCELReflectiveCopyObject = true or not + set
                        32. +
                        33. com.sun.CORBA.encoding.ORBEnableJavaSerialization = true or not + set
                        34. +
                        35. We really should just treat this as any property is allowed, but + we need to have some that are easy to set up, and some that are just + defaults.
                        36. +
                      4. +
                      5. JVM version
                      6. +
                      7. JVM type (server or client)
                      8. +
                      +

                      +

                      +

                      +

                      Test Description

                      +

                      Tests have a number of different characteristics that we can + control:

                      +
                        +
                      1. Arguments that can be specified in the test command: +
                          +
                        1. +
                      2. +
                      3. The list of valid controllers for the test. Anything started by a + controller can be debugged in several ways.
                      4. +
                      +

                      + diff --git a/www/design/dynamic_rmi_iiop.htm b/www/design/dynamic_rmi_iiop.htm new file mode 100644 index 000000000..310d04be5 --- /dev/null +++ b/www/design/dynamic_rmi_iiop.htm @@ -0,0 +1,503 @@ + + + + + + + Dynamic RMI-IIOP + + +

                      Dynamic RMI-IIOP

                      +

                      One important new feature in the PEORB in app server 8.1 is the ability + to use RMI-IIOP without any build-time code generation using a tool such as + rmic. The traditional model for remote method invocation is to first compile a + remote interface and its implementation, then use rmic to generate stubs and + skeletons. This requires that rmic analyze a lot of information, either by + using a Java compiler front end, or by using a library that enables the reading + of class files. rmic must then write out a number of Java source files for + stubs and ties to a file system, and then finally invoke the Java compiler to + generate the class files for the stubs and ties, which are then loaded in the + usual manner through a ClassLoader.

                      +

                      This adds up to a lot of overhead, since this process effectively + requires reading and writing a lot of information through the file system. In + fact, we found in the past that rmic was responsible for perhaps 50% of the + total time needed to deploy an EJB. The idea behind dynamic RMI-IIOP is to + generate code for stubs and ties as needed at runtime, completely avoiding the + overhead of file system I/O. The major question is, how expensive is it to use + dynamic RMI-IIOP instead of static stubs and ties?

                      +

                      The PresentationManager

                      +

                      Because Dynamic RMI-IIOP does not rely on generated code for stubs and + ties, much of the class analysis that is done by rmic must instead be done in + the ORB implementation. It turned out to be impossible to re-use any of the + RMIC implementation for this purpose, so we created a new part of the ORB + architecture to handle this. We call this the PresentationManager.

                      +

                      The PresentationManager provides the following interface:

                      +
                      +public interface PresentationManager {
                      +    ClassData getClassData( Class cls ) ;
                      +
                      +    DynamicMethodMarshalled getDynamicMethodMarshalled( Method method ) ;
                      +
                      +    StubFactoryFactory getStubFactoryFactory( boolean isDynamic ) ;
                      +
                      +    void setStubFactoryFactory( boolean isDynamic, StubFactoryFactory sff ) ;
                      +
                      +    Tie getTie() ;
                      +
                      +    boolean useDynamicStubs() ;
                      +} ;
                      +

                      Here is a summary of the various methods on this interface:

                      +
                        +
                      • The ClassData primarily provides access to the IDLNameTranslator, + which translates between the RMI-IIOP method name passed on the GIOP request + and the Java method represented by this name. The ClassData also provides the + repository IDs for the remote interface, and also an InvocationHandlerFactory + that is used in dynamic stubs.
                      • +
                      • The DynamicMethodMarshaller provides a uniform interface for reading + and writing arguments, results, and exceptions for a particular method.
                      • +
                      • The StubFactoryFactory is used whenever the ORB needs to obtain a + StubFactory which can create a Stub. For example, whenever an object reference + is unmarshalled, the ORB will attempt to get a Stub for the object + reference.
                      • +
                      • getTie returns a Dynamic Tie which can be used anywhere an RMI-IIOP + Tie is needed (typically in the POA).
                      • +
                      +

                      The ClassData and DynamicMethodMarshallers are somewhat expensive to + compute, so they are cached in the implementation of the + PresentationManager.

                      +

                      Ties

                      +

                      First, let's look briefly at the problem of dynamic Ties. A tie class + must extend org.omg.PortableServer.Servant (so that the tie can be used in a + POA) and implent javax.rmi.CORBA.Tie, as required by the OMG RMI-IIOP + specification (Ref XXX). The Tie interface is as follows:

                      +
                      +public interface Tie extends org.omg.CORBA.portable.InvokeHandler {
                      +    org.omg.CORBA.Object thisObject() ;
                      +
                      +    void deactuvate() throws java.rmi.NoSuchObjectException ;
                      +
                      +    ORB orb() ;
                      +
                      +    void orb( ORB orb ) ;
                      +
                      +    void setTarget( java.rmi.Remote target ) ;
                      +
                      +    java.rmi.Remote getTarget() ;
                      +}
                      +
                      +public interface InvokeHandler {
                      +    OutputStream _invoke( String method, InputStream input,
                      +        ResponseHandler handler ) ;
                      +}
                      +

                      The key methods here are the setTarget and _invoke methods. The + setTarget method is used to set the actual implementation of a remote object + that is to be used in this Tie. The invoke method is used by the ORB to perform + the actual invocation in the server of the remote operation named by the method + String. This invocation is implemented as follows:

                      +
                        +
                      1. Obtain the actual Java method to be invoked from the method String + (this is actually rather complicated due to the complex name mangling rules + defined by the RMI-IIOP specification).
                      2. +
                      3. Unmarshal the arguments for this operation from the InputStream.
                      4. + +
                      5. Invoke the actual method on the target with the arguments.
                      6. +
                      7. Use the ResponseHandler to create an appropriate type of response for + the request as an OutputStream.
                      8. +
                      9. Write the results of the invocation to the OutputStream, which is the + result of the _invoke call.
                      10. +
                      +

                      In the static case, this is accomplished through generated code. Step 1 + is done with a case statement that effectively maps from the method name in the + _invoke call to the Java method as found in the generated code. Specific + arguments are unmarshalled, and then passed in a call to the _invoke method. + The result is marshalled to the OutputStream using a method appropriate to the + declared type of the result. This means that there is a specific Tie class for + each type of remote object.

                      +

                      The dynamic case handles this somewhat differently. First, there is only + one type of Tie in Dynamic RMI-IIOP, which is the + com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie class. This class can act + as a Tie for any valid remote interface. An instance of the Tie class discovers + what kind of Tie it is by reflectively analyzing the Class of the target in the + setTarget call. The setTarget call uses the PresentationManager to obtain the + ClassData. The _invoke method is then implementated as follows, following the + steps above:

                      +
                        +
                      1. Use the IDLNameTranslator to get the Java Method from the method + passed into the _invoke() call.
                      2. +
                      3. Use the PresentationManager to get the DynamicMethodMarshalled from + the java method. Unmarshal the arguments using the + DynamicMethodMarshaller.
                      4. +
                      5. Invoke the method with the target and the unmarshalled arguments + using Java reflection.
                      6. +
                      7. Use the ResponseHandler to create the result OutputStream.
                      8. +
                      9. Use the DynamicMethodMarshaller to write the results to the result + OutputStream.
                      10. +
                      +

                      Obviously there is some concern here in the performance of Dynamic Ties. + Every step here is slower than the corresponding step in the static case. + However, this does not matter for one simple reason: Ties are only used in the + case of a remote invocation. The cost of a remote invocation is dominated by + two factors: the cost of the data transfer, and (perhaps primarily) the cost of + marshalling the data. Compared to the two factors, the extra overhead of the + ReflectiveTie is negligible.

                      +

                      It is worth noting that the relative costs of remote calls are subject + to change as technology evolves. The transmission cost may diminish to near + zero, as very high speed interfaces (like InfiniBand) with advanced RDMA based + transport hardware. This leaves the cost of the marshalling, which is an + interesting design and reseach challenge at this time. Certainly it might be + necessary to re-visit the cost of the ReflectiveTie implementation if we found + a way to substantially speed up the marshalling.

                      +

                      Stubs

                      +

                      Stubs present a rather more complex problem than the Ties. The ORB must + create a stub in certain cases:

                      +
                        +
                      1. When a remote object is unmarshalled (in CDRInputStream_1_0)
                      2. +
                      3. When a remote object is narrowed
                      4. +
                      5. When PortableRemoteObject.toStub is called
                      6. +
                      +

                      The creation of a stub is handled by the Utility.loadStub method. This + must be able to handle both RMI-IIOP and IDL stubs. Originally, this was almost + the same, as both cases were handled by calling Class.newInstance on the + appropriate Stub class. However, only RMI-IIOP can support dynamic stubs: IDL + requires compiler generated stubs. This is because the IDL stub requires + parsing of the IDL language definition of the interface. This call to + Class.newInstance is using the Class object as a factory for the stub.

                      +

                      This architecture was workable when all stubs were static, but with + dynamic stubs, there may not be a Class available to use as a factory. We also + do not want to create a customer ClassLoader to support stubs, as this would + make ORB integration with the app server more difficult. Consequently I + re-wrote parts of the RMI-IIOP code in terms of a StubFactory. In the static + case, the StubFactory simply calls Class.newInstance to create a stub.

                      +

                      Stubs also have a greater impact on performance than the ties. The stub + is always used on every call for both the remote and co-located cases. The + performance of a trivial co-located call is on the order of 1-5 microseconds + depending on options with static stubs. We do not want this case to become + significantly slower in the dynamic stub case.

                      +

                      I have written two different implementations of dynamic stubs: one that + uses the standard JDK dynamic proxy mechanism, and another using stubs + generated at runtime using the apache BCEL library. These approaches can be + compared in a number of ways:

                      +
                      +
                      RMI-IIOP Specification Compliance.
                      +
                      Unfortunately javax.rmi.CORBA.Stub is a class, not an interface. The + RMI-IIOP specification (ref XXX) also requires that all RMI-IIOP stubs extend + the Stub class. This means that dynamic proxies cannot be used to create a + fully compliant RMI-IIOP stub.
                      +
                      Java standards compliance
                      +
                      Dynamic proxies have been part of the JDK since 1.3 and are well + supported. The BCEL library is not a standard API.
                      +
                      Simplicity
                      +
                      It is easier in terms of the overall stub architecture to use BCEL + rather than dynamic proxies. This is due to the lack of problems relating to + the javax.rmi.CORBA.Stub base class when the BCEL approach is used.
                      +
                      Performance
                      +
                      The BCEL approach is actually faster than the dynamic proxy approach. + This is due to the ability to tune the code generation to the needs of stubs, + rather than requiring that a general framework be used.
                      +
                      +

                      Stub Architecture

                      +

                      The following diagram illustrates the required stub + architecture:

                      +

                      The blue classes are the classes defined in the OMG standards. They + define the methods shared by all remote references. Orange represents those + classes defined as part of Java. The yellow interface represents some remote + interface for which we are examining the different sorts of stubs.

                      +

                      Three sorts of stubs are illustrated here: standard static stubs, as + defined in the RMI-IIOP specification (the purple class), stubs and supporting + classes for the proxy implementation (in green), and the BCEL-based stubs + (shown in red). Each of these cases is described in the following sections.

                      +

                      The basic remote method invocation mechanism shares the same basic + outline in all three cases:

                      +
                        +
                      1. Determine the method name for the remote request.
                      2. +
                      3. Obtain the delegate that represents the remote reference.
                      4. +
                      5. Determine whether the request is local. If not local: +
                          +
                        1. Use the delegate to create a request which is represented as an + OutputStream.
                        2. +
                        3. Marshal the arguments to the OutputStream.
                        4. +
                        5. Tell the delegate to finish the invocation.
                        6. +
                        7. Unmarshal the result
                        8. +
                        9. Inform the delegate that the call has completed + (releaseReply)
                        10. +
                        11. Return the result
                        12. +
                      6. +
                      7. Otherwise, this is a local call: +
                          +
                        1. Use the servant_preinvoke method on the delegate to obtain a + ServantObject.
                        2. +
                        3. Copy the arguments if necessary to preserve the correct RMI-IIOP + semantics.
                        4. +
                        5. Invoke the method on the servant obtained from the + ServantObject.
                        6. +
                        7. Copy the result if necessary.
                        8. +
                        9. Inform the delegate that the call has completed + (servant_postinvoke)
                        10. +
                        11. Return the result
                        12. +
                      8. +
                      +

                      This is the basic outline, ignoring various exception cases. Most + exceptions are simply returned to the caller after being unmarshalled, much as + an ordinary result, but the exceptions are thrown, instead of returned from the + method. One particular exception has special meaning: the RemarshalException. + If a RemarshalException is thrown, the stub code goes all the way back to the + beginning to start the invocation process again. This is necessary in this + model to support the LocationForward mechanism defined in the GIOP + protocol.

                      +

                      Static Stubs

                      +

                      Classes with names like _XXX_Stub are generated by rmic. They extend the + javax.rmi.CORBA.Stub class as required by the RMI-IIOP specification, and + implement the remote interfaces. While these stubs could be generated in many + ways, the stubs generated by rmic -iiop duplicate the complete method + invocation logic in each method.

                      +

                      The general invoke logic is all generated in place for each method. This + is really the optimal way to generate the stubs, as each method can be + customized for the exact types of arguments, result, and exceptions thrown by + the method. However, it is not clear that this is really worthwhile, given the + optimizing capabilities of modern VMs that can use agressive inlining at + runtime.

                      +

                      Dynamic Stubs

                      +

                      The invocation logic for both kinds of dynamic stubs is the same, since + both cases actually use the same InvocationHandler to handle the methods on the + remote interface. This code (found in StubInvocationHandlerImpl) operates as + follows:

                      +
                        +
                      • The method name for the remote request is obtained from the + IDLNameTranslator in a reversal of the mechanism used in Ties.
                      • +
                      • All marshalling, unmarshalling, and copying of arguments and results + is handled by a DynamicMethodMarshaller
                      • +
                      • In the co-located case, the invocation is handled using + reflection.
                      • +
                      +

                      The main differences between the two types of stubs are in how they are + constructed, and how all of the non-remote interface methods are handled.

                      +

                      The performance of the co-located invocation case is crucial for some + applications of the app server. Probably the most important aspect of this cost + is the overhead of copying arguments and results. This is highly optimized in + the app server using a complex reflective copier, but even calling the copier + for simple data types is expensive. This is not a problem in the static stub + case, since the generated code only calls the copier for non-primitive types, + but this is more difficult in the dynamic case. If we look at the arguments in + the dynamic case, all arguments are objects of some type. Primitives are + wrapper in the java.lang wrappers of the appropriate type. However, there is no + way to tell inside the call whether an Integer is really an int (which cannot + be aliased, and so need not be copied), or really an Integer (which must be + copied in order to preserve aliasing). However, the DynamicMethodMarshaller is + constructed with complete type information on the Method, so it can tell + whether or not copying is required. Consequently the StubInvocationHandler + delegates the decision about whether or not to invoke the current copier to the + DynamicMethodMarshaller, which analyzed the Method argument types. If the + arguments are all primitives, the DynamicMethodMarshaller copy method does + nothing, otherwise it calls the copier.

                      +

                      This optimization allows us to measure the actual overhead of the + dynamic invocation, and make a fair comparison in the performance test. The + restuls are that the dynamic case is only about 50% slower than the static + case. This is quite good, as the colocated case is already highly optimized, + and the EJB layer adds sufficient overhead so that this 50% slowdown is not + noticeable. JDK 5.0 will provide even better performance, firstly because it is + already about 3 times faster on the same hardware, and also because the + concurrency utilities should be far faster than the old concurrency library + currently used by the ORB. This change should be significant because the POA + synchonization overhead for enter and exit is quite high.

                      +

                      The end result is that dynamic RMI-IIOP has sufficiently good + performance that we no longer see a need for any use of rmic in the normal use + of the app server. The only remaining case where stubs are needed is when an + EJB is deployed which must be accessible to a client written using another ORB + that does not support dynamic RMI-IIOP (in other words, any ORB other than the + one we ship in the app server).

                      +
                      Dynamic Proxy Stubs
                      +

                      The dynamic proxy case is somewhat more complex due to the need to + duplicate some of the methods defined in ObjectImpl and in Stub in an interface + called DynamicStub so that these standard methods are still available in the + dynamic case. However, this change is visible to client code, since clients may + occasionally obtain a stub and directly handle it as a javax.rmi.CORBA.Stub + class. This also necessarily occurs in the ORB itself. To allow such code to + easily work in the new model, I introduced a new SPI called StubAdapter. This + class has the following static methods:

                      +
                        +
                      • boolean isStubClass( Class )
                      • +
                      • boolean isStub( Object )
                      • +
                      • void setDelegate( Object, Delegate )
                      • +
                      • Delegate getDelegate( Object )
                      • +
                      • org.omg.CORBA.Object activateServant( Servant )
                      • +
                      • org.omg.CORBA.Object activateTie( Tie )
                      • +
                      • ORB getORB( Object )
                      • +
                      • String[] getTypeIds( Object )
                      • +
                      • void connect( Object, ORB )
                      • +
                      • boolean isLocal( Object )
                      • +
                      • OutputStream request( Object, String, boolean )
                      • +
                      +

                      These methods are implemented by checking two cases: either the Object + is a java.rmi.CORBA.Stub, in which the object is cast to Stub, or else the + Object is a DynamicStub, in which case the Object is cast to Stub. This is + rather ugly, and completely non-object oriented, but is directly caused by the + use of a class (instead of an interface) as the standard interface for all + stubs in the RMI-IIOP specification.

                      +

                      A dynamic proxy stub consists of two parts: a dynamic proxy which + implements the remote interface as well as DynamicStub, and an + InvocationHandler. The proxy is created using the standard JDK proxy mechanism. + The invocation handler is a composite InvocationHandler that has two parts: one + part delegates methods to DynamicStubImpl, and the other handles invocations on + the methods of the remote interface as previously described.

                      +
                      BCEL stubs
                      +

                      The BCEL stubs are actually simpler than the Dynamic Proxy version, + except for the actual class generation code. I have taken the approach of + constructing a very light-weight proxy mechanism that is actually mostly + independent of the RMI-IIOP stub requirements. Here the point is that a stub + really is nothing more in essence than a proxy, and all of the other machinery + that is part of the RMI-IIOP invocation process can be placed in a shared + class.

                      +

                      The interface to the proxy generator is as follows:

                      +
                      +public class ProxyCreator extends CodeGeneratorBase implements Constants {
                      +    public ProxyCreator( String className, String superClassName, Class[] interfaces,
                      +        Method[] methods ) ;
                      +}
                      +
                      +public abstract class CodeGeneratorBase  {
                      +    public Class create( ProtectionDomain pd, ClassLoader loader ) ;
                      +}
                      +

                      There are several requirements for using this class:

                      +
                        +
                      1. superClass must have an accessible no-args constructor
                      2. +
                      3. superclass must have an accessible method with the signature +
                        Object invoke( int methodNumber, Object[] args ) ;
                      4. +
                      5. The methods passed into the ProxyCreator constructor must also be + made available throw some mechanism at runtime so that invoke method in the + superClass sees the same methods as were used to construct the proxy.
                      6. +
                      +

                      In my BCEL dynamic stub implementation, the superClass is called + BCELStubBase. This class has the following interface:

                      +
                      +public abstract class BCELStubBase extend javax.rmi.CORBA.Stub {
                      +    public String[] _ids() ;
                      +
                      +    public void initialize( String[] typeIds, InvocationHandler handler, 
                      +        Methods[] methods ) ;
                      +
                      +    protected Object invoke( int methodNumber, Object[] args ) throws Throwable 
                      +    {
                      +        Method method = methods[methodNumber] ;
                      +        return handler.invoke( null, method, args ) ;
                      +    }
                      +}
                      +

                      The _ids() method is required because it is an abstract method in + javax.rmi.CORBA.Stub. It is implemented simply by returning the value of the + typeIds argument that was passed into the initialize method. The initialize + method itself simply stores its arguments in private fields in BCELStubBase. + The implementation of the invoke method is quite simple: it simply obtains the + appropriate java.lang.reflect.Method from the methods passed into the + initialzie method, and then passes this method and the args to the handler that + was passed into the initialize method.

                      +

                      The generated code is also quite simple: for the method at index n of + methods, the generated code simply:

                      +
                        +
                      1. Creates an Object[] args sized to hold the arguments.
                      2. +
                      3. Wraps args of primitive type in the appropriate wrapper (e.g., + java.lang.Integer for an int)
                      4. +
                      5. Copies the argument or argument wrapper into the args array.
                      6. +
                      7. Calls invoke( n, args ) in the superClass.
                      8. +
                      9. Unwraps the result if it is a primitive and then return the + result.
                      10. +
                      +

                      The invocation handler used here is the StubInvocationHandlerImpl + previously described. This is why the BCEL case is actually simple: there is no + need for a complex (and slower) InvocationHandler. Instead, we let the super + classes directly handle all of the non-remote interface methods that are + required for a Stub.

                      +

                      Stub Serialization

                      +

                      All RMI-IIOP stubs must be serializable. The serialized form is + specified by the RMI-IIOP standard, and is simply the IOR written out to a Java + OutputStream in the same way that an IOR is written to a CDR stream. In the + static stub case, we simply rely on the javax.rmi.CORBA.Stub class, which + implements readObject and writeObject methods that operate by delegating to the + StubDelegate. The StubDelegateImpl class then simply reads and writes the IOR + representation used for the Stub.

                      +

                      The dynamic case is more complex, due to the fact that we cannot rely on + the ClassLoader to directly load the correct Stub class. The static case works + here by assuming that the ClassLoader can always get the Stub. In fact, this + even handles downloadable stubs, since the ORB uses the RMIClassLoader to load + stub classes. The two dynamic cases are each somewhat different.

                      +

                      In the dynamic proxy case, DynamicStubImpl implements readObject, + writeObject, and readResolve. The readObject and writeObject methods are the + same as in the StubDelegateImpl code used in the static case. However, dynamic + stubs have additional state as compared to static stubs, due to the need for + information such as the DynamicMethodMarshalled and IDLNameTranslator. + Consequently the DynamicStubImpl code also has a readResolve method. This + method operates as follows:

                      +
                        +
                      1. Get the repository ID from the IOR
                      2. +
                      3. Get the interface class name from the repository ID
                      4. +
                      5. Use the JDKBridge to load the interface class (which must be in the + local VM)
                      6. +
                      7. Use the PresentationManager to get the class data, which contains the + IDLNameTranslator among other things
                      8. +
                      9. Use the class data to create an InvocationHandlerFactoryImpl
                      10. +
                      11. Use the InvocationHandlerFactoryImpl to create the InvocationHandler + that is returned.
                      12. +
                      +

                      When a dynamic proxy stub is serialized, the dynamic proxy itself is + serialized. Dynamic proxies are serialized as a proxy descriptor plus the state + of the proxy, which is just the InvocationHandler. Here the InvocationHandler + is actually a private class called CustomCompositeInvocationHandlerImpl which + is a nested class in the InvocationHandlerFactoryImpl class. + CustomCompositeInvocationHandlerImpl defines a writeReplace method that simply + returns the DynamicStubImpl, which we have already discussed.

                      +

                      Now, when the dynamic proxy stub is deserialized, first a + DynamicStubImpl is constructed, then its readObject method is called, which + restores the IOR. Next the readResolve method is called, which creates the + correct CustomCompositeInvocationHandlerImpl. Finally a proxy class is + constructed which has the CustomCompositeInvocationHandlerImpl as its + InvocationHandler.

                      +

                      The BCEL case is somewhat different, and only partly implemented today + (this is related to a bug that needs to be fixed in the app server). All of the + state for the stub is contained in the BCELStubBase class. Since this class + inherits from javax.rmi.CORBA.Stub, Stub serializes and deserializes the IOR. + BCELStubBase has only transient fields, and the generated stub has no data, so + the only state actually serialized in this case is the IOR. Hoever, as in the + dynamic proxy case, the transient state of BCELStubBase must be restored on + deserialization, and so BCELStubBase defines a readObject method for this + purpose. This readObject method is actually rather similar to the + DynamicStubImpl.readResolve method. However, this readObject just constructs a + StubInvocationHandlerImpl instead of using the + InvocationHandlerFactoryImpl.

                      +

                      The BCEL case also needs to make sure that the BCEL generated class is + available. This can be handled by adding a writeReplace method in the generated + BCEL stub that calls a superClass method that writes a BCELStubBase instead of + the generated BCEL stub class. Correspondingly a readResolve method is needed + in the BCELStubBase that will generate the BCEL stub class, create an instance + of this class, call the initialize method on the new instance, and return the + result.

                      +

                      Configuring the PresentationManager

                      +

                      Most configuration for the ORB is handled in the ORBImpl class when the + ORB is created. However, the PresentationManager cannot be handled this way, + because it is needed in the RMI-IIOP implementation. Much of the RMI-IIOP code + runs when no ORB is available, and so the basic StubFactory mechanisms must be + available even when there is no ORB. Consequently, the PresentationManager is + configured statically in the ORB SPI class. That is, the PresentationManager is + a singleton, and is shared by all ORBs (at least within the same ClassLoader as + usual).

                      +

                      There are two system properties that are used to configure the + PresentationManager in a static initializer in the ORB SPI class:

                      +
                        +
                      • com.sun.CORBA.ORBUseDynamicStub, which is a boolean. This flag + indicates to use dynamic (true) or static (false) stubs for all RMI-IIOP stubs. + IDL stubs are static in either case.
                      • +
                      • com.sun.CORBA.ORBDynamicStubFactoryFactoryClass, which is a String + representing a Class name. This value (if set) indicates that a special + StubFactoryFactory is to be used. If this property is not set to a valid + StubFactoryFactory class, the dynamic proxy version is used. This allows us to + place the entire BCEL-based StubFactoryFactory into the optional part of the + ORB.
                      • +
                      + diff --git a/www/design/dynamic_rmi_iiop_optimization.html b/www/design/dynamic_rmi_iiop_optimization.html new file mode 100644 index 000000000..5065e8207 --- /dev/null +++ b/www/design/dynamic_rmi_iiop_optimization.html @@ -0,0 +1,291 @@ + + + + + + Dynamic RMI-IIOP Optimization + + + + +

                      Dynamic RMI-IIOP Optimization

                      +
                      +

                      Last Modified: May 20, 2004

                      + +

                      Version: 1.1

                      + +
                      <Ken Cavanaugh> +
                      + +

                      Now that we have Dynamic RMI-IIOP (DRI) functioning very well, it is + time to consider optimizations. I use the simpleperf test to measure +the cost of optimized co-located calls, which is the only case where +the impact of DRI is significant. We can measure this with static +stubs, with dynamic stubs and no optimized copyobject, and dynamic +stubs and optimized copyobject. The results are very informative.

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      Test Type Static Stubs Dynamic Stubs
                      +Optimized Copy
                      Dynamic Stubs
                      +Stream Copy
                      BCEL Stubs
                      +Optimized Copy
                      BCEL Stubs
                      +No Copy
                      colocated normal POA 60.3139.8865.7129.170.9
                      full caching 28.2/4.422.3/21.2315.2/285.261/16.561/6.8
                      info only caching 1.9/1.820.9/11.6278/264.818.4/11.16.6/5.0
                      minimal caching .9/.955.8/34.4?318.3/374.7?45.8/33.5?10.8/3.8
                      same machine
                      +different ORB
                      1540.61573.8152715591440
                      + +

                      All times are from my Linux machine libros, which is configured as + follows:

                      + +
                        +
                      • Athlon XP 2600+ CPU
                      • +
                      • 1 GB DDR 400 RAM
                      • +
                      • Red Hat Linux 9
                      • +
                      • JDK 1.4.2_04
                      • + +
                      + +

                      I have also run the same test on the same machine with JDK 1.5.0 +beta 2
                      +

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      Test Type
                      +
                      Static Stubs
                      +
                      Dynamic Stubs
                      +Optimized Copy
                      +
                      Dynamic Stubs
                      +Stream Copy
                      +
                      BCEL Stubs
                      +Optimized Copy
                      +
                      BCEL Stubs
                      +No Copy
                      +
                      colocated normal POA
                      +
                      16.3
                      +

                      +

                      +
                      34.5
                      +
                      22.8
                      +
                      full caching
                      +
                      2.7/1.6
                      +

                      +

                      +
                      12.5/10.5
                      +
                      3.6/2.5
                      +
                      info only caching
                      +
                      1.2/.8
                      +

                      +

                      +
                      8.9/8.7
                      +
                      2/1.4
                      +
                      minimal caching
                      +
                      .6/.4
                      +

                      +

                      +
                      26.3/26
                      +
                      1.3/1
                      +
                      same machine
                      +different ORB
                      +
                      597
                      +

                      +

                      +
                      546
                      +
                      563
                      +
                      +

                      Generally 1.5.0 is fully 3 times faster than 1.4.2_04.  The +ratio is usually preserved, but note that the full servant caching BCEL +number is not improved as much as in the static stub case.
                      +

                      +

                      All times are given in microseconds. When two times are given, the +first is a straight creation, and the second is a creation followed +by a object->string->object conversion, which seems to cause +the test to run faster (I have no idea why). In all cases, the +invocation tests were run 10000 times, and these numbers reflect the +average time per invocation. The test implementation does nothing: it +just receives a single long argument and returns what it received.

                      + +

                      A number of things can be learned from these numbers (which have +been pretty consistent every time I have run them). First, the +"resolve" sometimes makes a large difference, particularly in the +full caching case. This is a puzzle. Another surprise is that the +dynamic stubs/optimized copy/minimal caching case is so slow. There +does appear to be much more variability in the dynamic stub numbers, +which may indicate more GC activity, but I have not as yet explored +this.

                      + +

                      The largest component of the time is now obvious from the 1.5 numbers: +calling copyObjects costs a lot of time, even with the highly optimized +copyObject implementation. In fact, without the copyObject overhead, the +dynamic case takes barely twice as much time as the static. +

                      Taking just the full caching and info only caching, we see that the + difference between dynamic and static ranges from about 6-19 +microseconds per call. This is the cost of using reflection and +packaging all of the arguments in native wrappers and arrays, and +also the cost of copyObject(s) calls. copyObject is particularly +important, since the overhead of not using the optimized copyObject +code is about 250-300 microseconds per call. This seems to be the +cost of creating 2 ORB streams (one for argument copying and one for + copying the result). The tests in the same machine/different ORB case +show no consistent differences, leading me to believe that the stream +creation overhead is similar in both cases, as in both cases we +create an argument and a result stream, and the processing is nearly +the same. This looks like 20% of the cost of a remote invocation +(with a very fast network) is due to stream creation. We could also +run the local/different ORB tests with Java serialization and see + what the difference is, but I have not done this so far.

                      + +

                      There are significant opportunities for optimization in the current + implementation. I will focus on the BCEL proxy implementation, since +that is the one we will ship. It also appears likely that there is +significantly more opportunity there for optimization than in the +proxy-based implementation. We will still preserve the JDK proxy +implementation for the present. It is becoming apparent that my +original idea of using the same InvocationHandler for both JDK and +BCEL proxies may not work, and it definitely not optimal.

                      + +

                      One big optimization is possible in the InvocationHandlerFactory. +This currently constructs an InvocationHandler that dispatches +requests to the remote interfaes, as well as DynamicStub, +org.omg.CORBA.Object, and java.lang.Object. This is necessary because +JDK proxies all extend java.lang.reflect.Proxy, so the base class +cannot do anything useful for the application. However, the BCEL +proxies extend BCELStubBase which extends javax.rmi.CORBA.Stub, and +Stub implements everything needed except for the remote interfaces +themselves. This means that we never need to do an InvocationHandler +lookup in the BCEL proxy case. In fact, the BCEL proxy just goes +directly to the StubInvocationHandler, rather than the more complex + composite invocation handler returned by the +InvocationHandlerFactoryImpl class.

                      + +

                      Another area to look at is the doPrivileged block that calls + setAccessible in the StubInvocationHandlerImpl code. This is happening +on every call. However, there is a simple solution: just check +isAccessible() before doing the setAccessible call. isAccessible +simply returns a boolean in the JDK, so its cost is trivial. This +avoids doing the doPrivilege block on every call.

                      + +

                      I also need to look at the implementation of copyObject(s). +Optimizing this further will be difficult, as the code is already +fairly close to optimal for what it does (without pushing further +into dynamic code generation for class copiers). We can determine +when a copyObjects call is made with nothing but wrapped primitives +and avoid the array copy in that case. We cannot skip copying wrapped +primitives, but the code handles those as immutables anyway.

                      + +

                      A more difficult optimization would be to change the BCEL generated + proxy code so that a different dispatch path was used for local calls, +one that avoided wrapping and allocating an argument array +completely. I'll probably explore this again, but this will not be +possible before the Milestone 4 deadline.

                      + + diff --git a/www/design/everett/casestudies/giop1.txt b/www/design/everett/casestudies/giop1.txt new file mode 100644 index 000000000..72fccb27a --- /dev/null +++ b/www/design/everett/casestudies/giop1.txt @@ -0,0 +1,231 @@ +# +# Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Distribution License v. 1.0, which is available at +# http://www.eclipse.org/org/documents/edl-v10.php. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +Scenario: + +Vendor says + +"We've apparently caught a marshalling bug in +the RI ORB. In the following tests the unmarshalling of +a response message from the RI is performed. This response contains +a java.util.ArrayList of three object references. The attached GIOP +dump shows that the third object reference starts in the wrong +position (4 bytes after the correct position). Due to the enhanced +strictness of the VisiBroker ORB in the maintenance release, it now +encounters an error in attempting to unmarshal the body of the +response message from the RI. We feel that this bug in the RI ORB +needs to be fixed." + +and provides the following annotated 3 fragment GIOP trace: + +1st fragment of the response message: + +47 49 4f 50 01 02 02 01 00 00 03 f4 00 00 00 14 GIOP............ +00 00 00 00 00 00 00 01 4e 45 4f 00 00 00 00 02 ........NEO..... +00 0a 00 00 00 00 00 00 7f ff ff 0a 00 00 00 3a ................ +52 4d 49 3a 6a 61 76 61 2e 75 74 69 6c 2e 41 72 RMI.java.util.Ar +72 61 79 4c 69 73 74 3a 46 36 35 35 31 35 34 46 rayList.F655154F +33 32 38 31 35 33 38 30 3a 37 38 38 31 44 32 31 32815380.7881D21 +44 39 39 43 37 36 31 39 44 00 00 00 00 00 04 9c D99C7619D......? +01 01 00 00 00 00 00 03 00 00 00 0a 01 00 00 00 ................ +beginning of 1st obj ref +00 00 00 56 52 4d 49 3a 63 6f 6d 2e 73 75 6e 2e ...VRMI.com.sun. +63 74 73 2e 74 65 73 74 73 2e 69 6e 74 65 72 6f cts.tests.intero +70 2e 65 6a 62 2e 65 6e 74 69 74 79 2e 62 6d 70 p.ejb.entity.bmp +2e 63 6c 69 65 6e 74 76 69 65 77 74 65 73 74 2e .clientviewtest. +54 65 73 74 42 65 61 6e 3a 30 30 30 30 30 30 30 TestBean.0000000 +30 30 30 30 30 30 30 30 30 00 00 00 00 00 00 01 000000000....... +00 00 00 00 00 00 01 dc 00 01 02 00 00 00 00 0e .......?........ +31 37 32 2e 32 30 2e 38 30 2e 31 34 30 00 a4 2a 172.20.80.140.?. +00 00 00 8e af ab cb 00 00 00 00 22 00 00 00 64 ...????........d +00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 0e ................ +50 65 72 73 69 73 74 65 6e 74 50 4f 41 00 00 00 PersistentPOA... +00 00 00 5d 8c 47 3d d9 00 00 00 00 00 00 00 51 ....?G.........Q +ac ed 00 05 73 72 00 11 6a 61 76 61 2e 6c 61 6e ?...sr..java.lan +67 2e 49 6e 74 65 67 65 72 12 e2 a0 a4 f7 81 87 g.Integer..??.?? +38 02 00 01 49 00 05 76 61 6c 75 65 78 72 00 10 8...I..valuexr.. +6a 61 76 61 2e 6c 61 6e 67 2e 4e 75 6d 62 65 72 java.lang.Number +86 ac 95 1d 0b 94 e0 8b 02 00 00 78 70 00 00 00 ???..?.?...xp... +02 0a 00 00 00 00 00 05 00 00 00 01 00 00 00 20 ................ +00 00 00 00 00 01 00 01 00 00 00 02 05 01 00 01 ................ +00 01 00 20 00 01 01 09 00 00 00 01 00 01 01 00 ................ +00 00 00 21 00 00 00 7c 00 00 00 00 00 00 00 01 ................ +00 00 00 00 00 00 00 24 00 00 00 20 00 00 00 66 ...............f +00 00 00 00 00 00 00 01 00 00 00 0e 31 37 32 2e ............172. +32 30 2e 38 30 2e 31 34 30 00 04 24 00 40 00 00 20.80.140....... +00 00 00 08 06 06 67 81 02 01 01 01 00 00 00 17 ......g?........ +04 01 00 08 06 06 67 81 02 01 01 01 00 00 00 07 ......g?........ +64 65 66 61 75 6c 74 00 04 00 00 00 00 00 00 00 default......... +00 00 00 01 00 00 00 08 06 06 67 81 02 01 01 01 ..........g?.... +00 00 00 0f 00 00 00 19 00 00 00 5e 00 00 00 00 ................ +00 00 00 56 68 74 74 70 3a 2f 2f 64 61 72 6b 6b ...Vhttp...darkk +6e 69 67 68 74 2e 73 6d 2e 69 6e 70 72 69 73 65 night.sm.inprise +2e 63 6f 6d 3a 39 31 39 31 2f 69 6e 74 65 72 6f .com.9191.intero +70 5f 65 6a 62 5f 45 62 6d 70 5f 63 6c 69 65 6e p.ejb.Ebmp.clien +74 76 69 65 77 74 65 73 74 5f 6a 32 65 65 33 43 tviewtest.j2ee3C +6c 69 65 6e 74 2e 6a 61 72 00 00 00 00 00 00 1f lient.jar....... +00 00 00 04 00 00 00 03 00 00 00 20 00 00 00 04 ................ +00 00 00 01 01 00 00 00 00 00 00 56 52 4d 49 3a ...........VRMI. +beginning of 2nd obj ref +63 6f 6d 2e 73 75 6e 2e 63 74 73 2e 74 65 73 74 com.sun.cts.test +73 2e 69 6e 74 65 72 6f 70 2e 65 6a 62 2e 65 6e s.interop.ejb.en +74 69 74 79 2e 62 6d 70 2e 63 6c 69 65 6e 74 76 tity.bmp.clientv +69 65 77 74 65 73 74 2e 54 65 73 74 42 65 61 6e iewtest.TestBean +3a 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 .000000000000000 +30 00 00 00 00 00 00 01 00 00 00 00 00 00 01 dc 0..............? +length of the profile +00 01 02 00 00 00 00 0e 31 37 32 2e 32 30 2e 38 ........172.20.8 +30 2e 31 34 30 00 a4 2a 00 00 00 8e af ab cb 00 0.140.?....????. +00 00 00 22 00 00 00 64 00 00 00 01 00 00 00 00 .......d........ +00 00 00 01 00 00 00 0e 50 65 72 73 69 73 74 65 ........Persiste +6e 74 50 4f 41 00 00 00 00 00 00 5d 8c 47 3d d9 ntPOA.......?G.. +00 00 00 00 00 00 00 51 ac ed 00 05 73 72 00 11 .......Q?...sr.. +6a 61 76 61 2e 6c 61 6e 67 2e 49 6e 74 65 67 65 java.lang.Intege +72 12 e2 a0 a4 f7 81 87 38 02 00 01 49 00 05 76 r..??.??8...I..v +61 6c 75 65 78 72 00 10 6a 61 76 61 2e 6c 61 6e aluexr..java.lan +67 2e 4e 75 6d 62 65 72 86 ac 95 1d 0b 94 e0 8b g.Number???..?.? +02 00 00 78 70 00 00 00 03 0a 00 00 00 00 00 05 ...xp........... +00 00 00 01 00 00 00 20 00 00 00 00 00 01 00 01 ................ +00 00 00 02 05 01 00 01 00 01 00 20 00 01 01 09 ................ + +2nd fragment of response message: + +47 49 4f 50 01 02 00 07 00 00 03 60 00 00 00 14 GIOP............ +00 00 00 01 00 01 01 00 00 00 00 21 00 00 00 7c ................ +00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 24 ................ +00 00 00 20 00 00 00 66 00 00 00 00 00 00 00 01 .......f........ +00 00 00 0e 31 37 32 2e 32 30 2e 38 30 2e 31 34 ....172.20.80.14 +30 00 04 24 00 40 00 00 00 00 00 08 06 06 67 81 0.............g? +02 01 01 01 00 00 00 17 04 01 00 08 06 06 67 81 ..............g? +02 01 01 01 00 00 00 07 64 65 66 61 75 6c 74 00 ........default. +04 00 00 00 00 00 00 00 00 00 00 01 00 00 00 08 ................ +06 06 67 81 02 01 01 01 00 00 00 0f 00 00 00 19 ..g?............ +00 00 00 5e 00 00 00 00 00 00 00 56 68 74 74 70 ...........Vhttp +3a 2f 2f 64 61 72 6b 6b 6e 69 67 68 74 2e 73 6d ...darkknight.sm +2e 69 6e 70 72 69 73 65 2e 63 6f 6d 3a 39 31 39 .inprise.com.919 +31 2f 69 6e 74 65 72 6f 70 5f 65 6a 62 5f 45 62 1.interop.ejb.Eb +6d 70 5f 63 6c 69 65 6e 74 76 69 65 77 74 65 73 mp.clientviewtes +74 5f 6a 32 65 65 33 43 6c 69 65 6e 74 2e 6a 61 t.j2ee3Client.ja +72 00 00 00 00 00 00 1f 00 00 00 04 00 00 00 03 r............... +00 00 00 20 00 00 00 04 00 00 00 01 00 00 02 48 ...............H +end of 2nd obj ref +01 65 72 73 00 00 00 56 52 4d 49 3a 63 6f 6d 2e .ers...VRMI.com. +beginning of 3rd obj ref +73 75 6e 2e 63 74 73 2e 74 65 73 74 73 2e 69 6e sun.cts.tests.in +74 65 72 6f 70 2e 65 6a 62 2e 65 6e 74 69 74 79 terop.ejb.entity +2e 62 6d 70 2e 63 6c 69 65 6e 74 76 69 65 77 74 .bmp.clientviewt +65 73 74 2e 54 65 73 74 42 65 61 6e 3a 30 30 30 est.TestBean.000 +30 30 30 30 30 30 30 30 30 30 30 30 30 00 65 72 0000000000000.er +00 00 00 01 00 00 00 00 00 00 01 dc 00 01 02 00 ...........?.... +00 00 00 0e 31 37 32 2e 32 30 2e 38 30 2e 31 34 ....172.20.80.14 +30 00 a4 2a 00 00 00 8e af ab cb 00 00 00 00 22 0.?....????..... +00 00 00 64 00 00 00 01 00 00 00 00 00 00 00 01 ...d............ +00 00 00 0e 50 65 72 73 69 73 74 65 6e 74 50 4f ....PersistentPO +41 00 00 00 00 00 00 5d 8c 47 3d d9 00 00 00 00 A.......?G...... +00 00 00 51 ac ed 00 05 73 72 00 11 6a 61 76 61 ...Q?...sr..java +2e 6c 61 6e 67 2e 49 6e 74 65 67 65 72 12 e2 a0 .lang.Integer..? +a4 f7 81 87 38 02 00 01 49 00 05 76 61 6c 75 65 ?.??8...I..value +78 72 00 10 6a 61 76 61 2e 6c 61 6e 67 2e 4e 75 xr..java.lang.Nu +6d 62 65 72 86 ac 95 1d 0b 94 e0 8b 02 00 00 78 mber???..?.?...x +70 00 00 00 04 0a 00 00 00 00 00 05 00 00 00 01 p............... +00 00 00 20 00 00 00 00 00 01 00 01 00 00 00 02 ................ +05 01 00 01 00 01 00 20 00 01 01 09 00 00 00 01 ................ +00 01 01 00 00 00 00 21 00 00 00 7c 00 00 00 00 ................ +00 00 00 01 00 00 00 00 00 00 00 24 00 00 00 20 ................ +00 00 00 66 00 00 00 00 00 00 00 01 00 00 00 0e ...f............ +31 37 32 2e 32 30 2e 38 30 2e 31 34 30 00 04 24 172.20.80.140... +00 40 00 00 00 00 00 08 06 06 67 81 02 01 01 01 ..........g?.... +00 00 00 17 04 01 00 08 06 06 67 81 02 01 01 01 ..........g?.... +00 00 00 07 64 65 66 61 75 6c 74 00 04 00 00 00 ....default..... +00 00 00 00 00 00 00 01 00 00 00 08 06 06 67 81 ..............g? +02 01 01 01 00 00 00 0f 00 00 00 19 00 00 00 5e ................ +00 00 00 00 00 00 00 56 68 74 74 70 3a 2f 2f 64 .......Vhttp...d +61 72 6b 6b 6e 69 67 68 74 2e 73 6d 2e 69 6e 70 arkknight.sm.inp +72 69 73 65 2e 63 6f 6d 3a 39 31 39 31 2f 69 6e rise.com.9191.in +74 65 72 6f 70 5f 65 6a 62 5f 45 62 6d 70 5f 63 terop.ejb.Ebmp.c +6c 69 65 6e 74 76 69 65 77 74 65 73 74 5f 6a 32 lientviewtest.j2 +65 65 33 43 6c 69 65 6e 74 2e 6a 61 72 00 00 00 ee3Client.jar... +00 00 00 1f 00 00 00 04 00 00 00 03 00 00 00 20 ................ +00 00 00 04 00 00 00 01 ff ff ff ff ............ + +Real answer: Their ORB isn't handling chunking with fragmentation +properly. Do you see why? Of course not. Start deciphering it +by hand. + +STEP 0: Probably want to print it out and get a pencil... maybe +a few different colored pens. + +STEP 1: Seek to the beginning of the ArrayList. You can see this +by looking for the repository ID or the 7fffffxx valuetag before it. +The xx can tell you if it's chunking or not. We know that +java.util.ArrayList has a writeObject method, so it should be chunked. + +00 0a 00 00 00 00 00 00 7f ff ff 0a 00 00 00 3a ................ +52 4d 49 3a 6a 61 76 61 2e 75 74 69 6c 2e 41 72 RMI.java.util.Ar +72 61 79 4c 69 73 74 3a 46 36 35 35 31 35 34 46 rayList.F655154F +33 32 38 31 35 33 38 30 3a 37 38 38 31 44 32 31 32815380.7881D21 +44 39 39 43 37 36 31 39 44 00 00 00 00 00 04 9c D99C7619D......? +01 01 00 00 00 00 00 03 00 00 00 0a 01 00 00 00 ................ +00 00 00 56 52 4d 49 3a 63 6f 6d 2e 73 75 6e 2e ...VRMI.com.sun. +63 74 73 2e 74 65 73 74 73 2e 69 6e 74 65 72 6f cts.tests.intero +70 2e 65 6a 62 2e 65 6e 74 69 74 79 2e 62 6d 70 p.ejb.entity.bmp +2e 63 6c 69 65 6e 74 76 69 65 77 74 65 73 74 2e .clientviewtest. +54 65 73 74 42 65 61 6e 3a 30 30 30 30 30 30 30 TestBean.0000000 + +STEP 2: Make sure that the repository ID length 0x3a covers +the whole rep ID, including the terminating null. Remember that +repository Ids are written as Latin-1 CORBA strings. See +CORBA chapter 15 for encoding of a CORBA string. + +STEP 3: There is no codebase here, so after the rep Id, we +should have the chunk length. Here, it is 0x49c. Go ahead +and mark where this chunk ends in the stream. 0x49c is +a whopping 1180 bytes later! That's 1180/16 = 73.75 +lines of trace later in the 2nd fragment. + +74 5f 6a 32 65 65 33 43 6c 69 65 6e 74 2e 6a 61 t.j2ee3Client.ja +72 00 00 00 00 00 00 1f 00 00 00 04 00 00 00 03 r............... +00 00 00 20 00 00 00 04 00 00 00 01 00 00 02 48 ...............H + ^ + | + first chunk ends here + + +The next line is where the 3rd object reference begins, as they +note. + + first chunk ends here + | + v +00 00 00 20 00 00 00 04 00 00 00 01 00 00 02 48 ...............H +01 65 72 73 00 00 00 56 52 4d 49 3a 63 6f 6d 2e .ers...VRMI.com. +73 75 6e 2e 63 74 73 2e 74 65 73 74 73 2e 69 6e sun.cts.tests.in + +They contend that this middle line is 4 bytes too late, and +that the 01 should be right after the previous 01. + +SOLVED! +------- + +The writer was chunking and fragmenting. It wrote a chunk length +that stretched into the second fragment. It could do that since +it knew in advance the length of what it was writing and couldn't +split it across chunks. + +When it got to the end of the thing which it couldn't +split into multiple chunks, it would be in a new fragment so +could no longer modify fragment 1's chunk length to include +new data. Thus, it would have to open a new chunk. + +The new chunk had a length of 0x248 bytes and encloses the +3rd object reference, including the boolean abstract interface +marker at the beginning of the 3rd line. The 65 72 73 you +see after the 01 are just garbage alignment bytes. + diff --git a/www/design/everett/serial_pres/pres1/first0.jpg b/www/design/everett/serial_pres/pres1/first0.jpg new file mode 100644 index 000000000..9bce47c69 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/first0.jpg differ diff --git a/www/design/everett/serial_pres/pres1/first1.jpg b/www/design/everett/serial_pres/pres1/first1.jpg new file mode 100644 index 000000000..a25a044d8 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/first1.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img0.html b/www/design/everett/serial_pres/pres1/img0.html new file mode 100644 index 000000000..9eaa29610 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img0.html @@ -0,0 +1,24 @@ + + + + + + + Serialization 1: Overview + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img0.jpg b/www/design/everett/serial_pres/pres1/img0.jpg new file mode 100644 index 000000000..877fe0bd9 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img0.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img1.html b/www/design/everett/serial_pres/pres1/img1.html new file mode 100644 index 000000000..d8975b563 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img1.html @@ -0,0 +1,24 @@ + + + + + + + Indirections + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img1.jpg b/www/design/everett/serial_pres/pres1/img1.jpg new file mode 100644 index 000000000..c29ecd271 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img1.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img2.html b/www/design/everett/serial_pres/pres1/img2.html new file mode 100644 index 000000000..7c87f16d6 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img2.html @@ -0,0 +1,24 @@ + + + + + + + Chunking 1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img2.jpg b/www/design/everett/serial_pres/pres1/img2.jpg new file mode 100644 index 000000000..c296f0ca2 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img2.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img3.html b/www/design/everett/serial_pres/pres1/img3.html new file mode 100644 index 000000000..f55d32dc8 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img3.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype Layout + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img3.jpg b/www/design/everett/serial_pres/pres1/img3.jpg new file mode 100644 index 000000000..915ba736d Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img3.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img4.html b/www/design/everett/serial_pres/pres1/img4.html new file mode 100644 index 000000000..aee6c8615 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img4.html @@ -0,0 +1,24 @@ + + + + + + + Chunking 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img4.jpg b/www/design/everett/serial_pres/pres1/img4.jpg new file mode 100644 index 000000000..d305b3986 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img4.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img5.html b/www/design/everett/serial_pres/pres1/img5.html new file mode 100644 index 000000000..9e339eb68 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img5.html @@ -0,0 +1,24 @@ + + + + + + + Chunking with Fragmentation 1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img5.jpg b/www/design/everett/serial_pres/pres1/img5.jpg new file mode 100644 index 000000000..56fc32a49 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img5.jpg differ diff --git a/www/design/everett/serial_pres/pres1/img6.html b/www/design/everett/serial_pres/pres1/img6.html new file mode 100644 index 000000000..2ceed3b3b --- /dev/null +++ b/www/design/everett/serial_pres/pres1/img6.html @@ -0,0 +1,24 @@ + + + + + + + Chunking with Fragmentation 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/img6.jpg b/www/design/everett/serial_pres/pres1/img6.jpg new file mode 100644 index 000000000..d525e6a5d Binary files /dev/null and b/www/design/everett/serial_pres/pres1/img6.jpg differ diff --git a/www/design/everett/serial_pres/pres1/index.jpg b/www/design/everett/serial_pres/pres1/index.jpg new file mode 100644 index 000000000..9ce70eb72 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/index.jpg differ diff --git a/www/design/everett/serial_pres/pres1/last0.jpg b/www/design/everett/serial_pres/pres1/last0.jpg new file mode 100644 index 000000000..10b7d4523 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/last0.jpg differ diff --git a/www/design/everett/serial_pres/pres1/last1.jpg b/www/design/everett/serial_pres/pres1/last1.jpg new file mode 100644 index 000000000..37bc3cd51 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/last1.jpg differ diff --git a/www/design/everett/serial_pres/pres1/next0.jpg b/www/design/everett/serial_pres/pres1/next0.jpg new file mode 100644 index 000000000..80f7c1ab3 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/next0.jpg differ diff --git a/www/design/everett/serial_pres/pres1/next1.jpg b/www/design/everett/serial_pres/pres1/next1.jpg new file mode 100644 index 000000000..56834248f Binary files /dev/null and b/www/design/everett/serial_pres/pres1/next1.jpg differ diff --git a/www/design/everett/serial_pres/pres1/prev0.jpg b/www/design/everett/serial_pres/pres1/prev0.jpg new file mode 100644 index 000000000..ddcd550d5 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/prev0.jpg differ diff --git a/www/design/everett/serial_pres/pres1/prev1.jpg b/www/design/everett/serial_pres/pres1/prev1.jpg new file mode 100644 index 000000000..e195e5bf4 Binary files /dev/null and b/www/design/everett/serial_pres/pres1/prev1.jpg differ diff --git a/www/design/everett/serial_pres/pres1/serial1pres.html b/www/design/everett/serial_pres/pres1/serial1pres.html new file mode 100644 index 000000000..6b3639190 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/serial1pres.html @@ -0,0 +1,42 @@ + + + + + + + Serialization 1: Overview + + +
                      +

                      Click here to start

                      +
                      +
                      + +
                      +

                      Table of contents

                      + + + + + + +
                      +

                      Author: Everett Anderson

                      +

                      E-mail: dev@glassfish-corba.dev.java.net

                      +

                      Homepage: http://glassfish-corba.dev.java.net/

                      +

                      Further information:
                      +Transformed to HTML by Ken Cavanaugh

                      +

                      Download presentation

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres1/serial1pres.odp b/www/design/everett/serial_pres/pres1/serial1pres.odp new file mode 100644 index 000000000..d57a6875a Binary files /dev/null and b/www/design/everett/serial_pres/pres1/serial1pres.odp differ diff --git a/www/design/everett/serial_pres/pres1/serial1pres.sxi b/www/design/everett/serial_pres/pres1/serial1pres.sxi new file mode 100644 index 000000000..7aa14e71f Binary files /dev/null and b/www/design/everett/serial_pres/pres1/serial1pres.sxi differ diff --git a/www/design/everett/serial_pres/pres1/text.jpg b/www/design/everett/serial_pres/pres1/text.jpg new file mode 100644 index 000000000..eed22dd2f Binary files /dev/null and b/www/design/everett/serial_pres/pres1/text.jpg differ diff --git a/www/design/everett/serial_pres/pres1/text0.html b/www/design/everett/serial_pres/pres1/text0.html new file mode 100644 index 000000000..4d4749407 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text0.html @@ -0,0 +1,26 @@ + + + + + + + Serialization 1: Overview + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Serialization 1: Overview

                      +Chunking, Indirections, and Fragmentation +May 16, 2002 + + diff --git a/www/design/everett/serial_pres/pres1/text1.html b/www/design/everett/serial_pres/pres1/text1.html new file mode 100644 index 000000000..6f7c1e8d4 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text1.html @@ -0,0 +1,24 @@ + + + + + + + Indirections + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Indirections

                      + + diff --git a/www/design/everett/serial_pres/pres1/text2.html b/www/design/everett/serial_pres/pres1/text2.html new file mode 100644 index 000000000..cb0c7fb84 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text2.html @@ -0,0 +1,29 @@ + + + + + + + Chunking 1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking 1

                      +
                      • What is chunking?

                      • +
                        • 15.3.4.6
                        • +
                        • Provides markers for ORB to keep track of custom data (skipping) or handling truncatables.
                        • +
                        • No relation to fragmentation benefits despite wording in spec.
                        • +
                        • Makes things more complicated.
                        • +
                      + diff --git a/www/design/everett/serial_pres/pres1/text3.html b/www/design/everett/serial_pres/pres1/text3.html new file mode 100644 index 000000000..8ed369c49 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text3.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype Layout + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Valuetype Layout 15.3.4.8

                      + + diff --git a/www/design/everett/serial_pres/pres1/text4.html b/www/design/everett/serial_pres/pres1/text4.html new file mode 100644 index 000000000..febd4ab01 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text4.html @@ -0,0 +1,27 @@ + + + + + + + Chunking 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking 2

                      +
                      • Chunk lengths are positive longs. Indirections, valuetags, and chunk lengths have separate ranges/values.

                      • +
                      • Chunk length cannot split primitive CDR types, arrays of primitive CDR types, strings, wstrings, or indirections. CORBA 3.0 ptc-02-02-01 15.3.4.6, interop issue 4326.

                      • +
                      • Chunks do not overlap (and close before nested valuetypes).

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres1/text5.html b/www/design/everett/serial_pres/pres1/text5.html new file mode 100644 index 000000000..18c9634e9 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text5.html @@ -0,0 +1,24 @@ + + + + + + + Chunking with Fragmentation 1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking with Fragmentation 1

                      + + diff --git a/www/design/everett/serial_pres/pres1/text6.html b/www/design/everett/serial_pres/pres1/text6.html new file mode 100644 index 000000000..f28ed80f1 --- /dev/null +++ b/www/design/everett/serial_pres/pres1/text6.html @@ -0,0 +1,24 @@ + + + + + + + Chunking with Fragmentation 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking with Fragmentation 2

                      + + diff --git a/www/design/everett/serial_pres/pres2/first0.jpg b/www/design/everett/serial_pres/pres2/first0.jpg new file mode 100644 index 000000000..9bce47c69 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/first0.jpg differ diff --git a/www/design/everett/serial_pres/pres2/first1.jpg b/www/design/everett/serial_pres/pres2/first1.jpg new file mode 100644 index 000000000..a25a044d8 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/first1.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img0.html b/www/design/everett/serial_pres/pres2/img0.html new file mode 100644 index 000000000..cd19b2b55 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img0.html @@ -0,0 +1,24 @@ + + + + + + + Serialization 2: Valuetype Code + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img0.jpg b/www/design/everett/serial_pres/pres2/img0.jpg new file mode 100644 index 000000000..61dd434ee Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img0.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img1.html b/www/design/everett/serial_pres/pres2/img1.html new file mode 100644 index 000000000..334ec0de2 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img1.html @@ -0,0 +1,24 @@ + + + + + + + Review + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img1.jpg b/www/design/everett/serial_pres/pres2/img1.jpg new file mode 100644 index 000000000..52c244999 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img1.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img10.html b/www/design/everett/serial_pres/pres2/img10.html new file mode 100644 index 000000000..d3f1ed938 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img10.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img10.jpg b/www/design/everett/serial_pres/pres2/img10.jpg new file mode 100644 index 000000000..8e232fcfd Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img10.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img11.html b/www/design/everett/serial_pres/pres2/img11.html new file mode 100644 index 000000000..79e27b7c8 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img11.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img11.jpg b/www/design/everett/serial_pres/pres2/img11.jpg new file mode 100644 index 000000000..4b1c4fafe Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img11.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img12.html b/www/design/everett/serial_pres/pres2/img12.html new file mode 100644 index 000000000..00aaa58b6 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img12.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img12.jpg b/www/design/everett/serial_pres/pres2/img12.jpg new file mode 100644 index 000000000..8df88eb5b Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img12.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img13.html b/www/design/everett/serial_pres/pres2/img13.html new file mode 100644 index 000000000..2b739e7c9 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img13.html @@ -0,0 +1,24 @@ + + + + + + + Example 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img13.jpg b/www/design/everett/serial_pres/pres2/img13.jpg new file mode 100644 index 000000000..33d7f5625 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img13.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img14.html b/www/design/everett/serial_pres/pres2/img14.html new file mode 100644 index 000000000..bd895563d --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img14.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 4 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img14.jpg b/www/design/everett/serial_pres/pres2/img14.jpg new file mode 100644 index 000000000..10023f915 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img14.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img15.html b/www/design/everett/serial_pres/pres2/img15.html new file mode 100644 index 000000000..5df706297 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img15.html @@ -0,0 +1,24 @@ + + + + + + + Example 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img15.jpg b/www/design/everett/serial_pres/pres2/img15.jpg new file mode 100644 index 000000000..d52775a25 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img15.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img2.html b/www/design/everett/serial_pres/pres2/img2.html new file mode 100644 index 000000000..ee3a85b1c --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img2.html @@ -0,0 +1,24 @@ + + + + + + + CDROutputStreams + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img2.jpg b/www/design/everett/serial_pres/pres2/img2.jpg new file mode 100644 index 000000000..d595828f9 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img2.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img3.html b/www/design/everett/serial_pres/pres2/img3.html new file mode 100644 index 000000000..05c78c221 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img3.html @@ -0,0 +1,24 @@ + + + + + + + CDROutputStream_1_0 vars + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img3.jpg b/www/design/everett/serial_pres/pres2/img3.jpg new file mode 100644 index 000000000..73635750a Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img3.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img4.html b/www/design/everett/serial_pres/pres2/img4.html new file mode 100644 index 000000000..bdbe3ad5b --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img4.html @@ -0,0 +1,24 @@ + + + + + + + End tag variables + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img4.jpg b/www/design/everett/serial_pres/pres2/img4.jpg new file mode 100644 index 000000000..a4ed246f3 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img4.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img5.html b/www/design/everett/serial_pres/pres2/img5.html new file mode 100644 index 000000000..236978d54 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img5.html @@ -0,0 +1,24 @@ + + + + + + + Chunking variables (non-frag) + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img5.jpg b/www/design/everett/serial_pres/pres2/img5.jpg new file mode 100644 index 000000000..ed19b3591 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img5.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img6.html b/www/design/everett/serial_pres/pres2/img6.html new file mode 100644 index 000000000..d245ebf8b --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img6.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype code 1 (write_value) + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img6.jpg b/www/design/everett/serial_pres/pres2/img6.jpg new file mode 100644 index 000000000..1b75624e4 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img6.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img7.html b/www/design/everett/serial_pres/pres2/img7.html new file mode 100644 index 000000000..33f063db8 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img7.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype code 2 (block methods) + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img7.jpg b/www/design/everett/serial_pres/pres2/img7.jpg new file mode 100644 index 000000000..c35801201 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img7.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img8.html b/www/design/everett/serial_pres/pres2/img8.html new file mode 100644 index 000000000..2d2cb103e --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img8.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype code 3 (end tag methods) + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img8.jpg b/www/design/everett/serial_pres/pres2/img8.jpg new file mode 100644 index 000000000..41acb2210 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img8.jpg differ diff --git a/www/design/everett/serial_pres/pres2/img9.html b/www/design/everett/serial_pres/pres2/img9.html new file mode 100644 index 000000000..d29a2b591 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/img9.html @@ -0,0 +1,24 @@ + + + + + + + Example 1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/img9.jpg b/www/design/everett/serial_pres/pres2/img9.jpg new file mode 100644 index 000000000..d286e1d7d Binary files /dev/null and b/www/design/everett/serial_pres/pres2/img9.jpg differ diff --git a/www/design/everett/serial_pres/pres2/index.jpg b/www/design/everett/serial_pres/pres2/index.jpg new file mode 100644 index 000000000..9ce70eb72 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/index.jpg differ diff --git a/www/design/everett/serial_pres/pres2/last0.jpg b/www/design/everett/serial_pres/pres2/last0.jpg new file mode 100644 index 000000000..10b7d4523 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/last0.jpg differ diff --git a/www/design/everett/serial_pres/pres2/last1.jpg b/www/design/everett/serial_pres/pres2/last1.jpg new file mode 100644 index 000000000..37bc3cd51 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/last1.jpg differ diff --git a/www/design/everett/serial_pres/pres2/next0.jpg b/www/design/everett/serial_pres/pres2/next0.jpg new file mode 100644 index 000000000..80f7c1ab3 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/next0.jpg differ diff --git a/www/design/everett/serial_pres/pres2/next1.jpg b/www/design/everett/serial_pres/pres2/next1.jpg new file mode 100644 index 000000000..56834248f Binary files /dev/null and b/www/design/everett/serial_pres/pres2/next1.jpg differ diff --git a/www/design/everett/serial_pres/pres2/prev0.jpg b/www/design/everett/serial_pres/pres2/prev0.jpg new file mode 100644 index 000000000..ddcd550d5 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/prev0.jpg differ diff --git a/www/design/everett/serial_pres/pres2/prev1.jpg b/www/design/everett/serial_pres/pres2/prev1.jpg new file mode 100644 index 000000000..e195e5bf4 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/prev1.jpg differ diff --git a/www/design/everett/serial_pres/pres2/serial2pres.html b/www/design/everett/serial_pres/pres2/serial2pres.html new file mode 100644 index 000000000..7cb3291d2 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/serial2pres.html @@ -0,0 +1,51 @@ + + + + + + + Serialization 2: Valuetype Code + + +
                      +

                      Click here to start

                      +
                      +
                      + +
                      +

                      Table of contents

                      + + + + + + + + + + + + + + + +
                      +

                      Author: Everett Anderson

                      +

                      E-mail: dev@glassfish-corba.dev.java.net

                      +

                      Homepage: http://glassfish-corba.dev.java.net/

                      +

                      Further information:
                      +Transformed to HTML by Ken Cavanaugh

                      +

                      Download presentation

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres2/serial2pres.odp b/www/design/everett/serial_pres/pres2/serial2pres.odp new file mode 100644 index 000000000..bf6f76b71 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/serial2pres.odp differ diff --git a/www/design/everett/serial_pres/pres2/serial2pres.sxi b/www/design/everett/serial_pres/pres2/serial2pres.sxi new file mode 100644 index 000000000..1e49ce583 Binary files /dev/null and b/www/design/everett/serial_pres/pres2/serial2pres.sxi differ diff --git a/www/design/everett/serial_pres/pres2/text.jpg b/www/design/everett/serial_pres/pres2/text.jpg new file mode 100644 index 000000000..eed22dd2f Binary files /dev/null and b/www/design/everett/serial_pres/pres2/text.jpg differ diff --git a/www/design/everett/serial_pres/pres2/text0.html b/www/design/everett/serial_pres/pres2/text0.html new file mode 100644 index 000000000..931204da6 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text0.html @@ -0,0 +1,26 @@ + + + + + + + Serialization 2: Valuetype Code + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Serialization 2: Valuetype Code

                      +CDROutputStreams +May 30, 2002 + + diff --git a/www/design/everett/serial_pres/pres2/text1.html b/www/design/everett/serial_pres/pres2/text1.html new file mode 100644 index 000000000..d36c59488 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text1.html @@ -0,0 +1,28 @@ + + + + + + + Review + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Review

                      +
                      • Valuetypes are encoded as a value tag plus optional codebase and repository ID strings

                      • +
                      • Chunks are never nested (so close before any value tag)

                      • +
                      • Chunks cannot split primitives, arrays of primitives, strings, wstrings, or indirections

                      • +
                      • Chunks may span fragments

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres2/text10.html b/www/design/everett/serial_pres/pres2/text10.html new file mode 100644 index 000000000..e09ad4986 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text10.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking & Fragmentation 1

                      + + diff --git a/www/design/everett/serial_pres/pres2/text11.html b/www/design/everett/serial_pres/pres2/text11.html new file mode 100644 index 000000000..be68fe017 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text11.html @@ -0,0 +1,27 @@ + + + + + + + Chunking & Fragmentation 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking and Fragmentation 2

                      +
                      • Before ???special??? writes (arrays of primitives, string/wstring data, indirections), call handleSpecialChunkBegin with the total size in bytes of desired data

                      • +
                      • Afterwards, call handleSpecialChunkEnd

                      • +
                      • Primitives are overridden in 1_2 to call checkPrimitiveAcrossFragmentedChunk after writing, but don't use handleSpecialChunk methods (ABLE TO REUSE?)

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres2/text12.html b/www/design/everett/serial_pres/pres2/text12.html new file mode 100644 index 000000000..5dc0da98f --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text12.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking and Fragmentation 3

                      + + diff --git a/www/design/everett/serial_pres/pres2/text13.html b/www/design/everett/serial_pres/pres2/text13.html new file mode 100644 index 000000000..869b20e63 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text13.html @@ -0,0 +1,24 @@ + + + + + + + Example 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Example 2

                      + + diff --git a/www/design/everett/serial_pres/pres2/text14.html b/www/design/everett/serial_pres/pres2/text14.html new file mode 100644 index 000000000..6a026aef1 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text14.html @@ -0,0 +1,24 @@ + + + + + + + Chunking & Fragmentation 4 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking and Fragmenation 4

                      + + diff --git a/www/design/everett/serial_pres/pres2/text15.html b/www/design/everett/serial_pres/pres2/text15.html new file mode 100644 index 000000000..790249da1 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text15.html @@ -0,0 +1,24 @@ + + + + + + + Example 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Example 3

                      + + diff --git a/www/design/everett/serial_pres/pres2/text2.html b/www/design/everett/serial_pres/pres2/text2.html new file mode 100644 index 000000000..476c701fd --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text2.html @@ -0,0 +1,27 @@ + + + + + + + CDROutputStreams + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      CDROutputStreams

                      +
                      • CDROutputStream_1_0 is original CDROutputStream, containing most valuetype code

                      • +
                      • CDROutputStream_1_1 and 1_2 override certain methods to better handle fragmentation

                      • +
                      • CDROutputStream_1_1 does not handle chunking with fragmentation at all (thus we don't really support this)

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres2/text3.html b/www/design/everett/serial_pres/pres2/text3.html new file mode 100644 index 000000000..b6d6ea3d4 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text3.html @@ -0,0 +1,24 @@ + + + + + + + CDROutputStream_1_0 vars + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      CDROutputStream_1_0 vars

                      + + diff --git a/www/design/everett/serial_pres/pres2/text4.html b/www/design/everett/serial_pres/pres2/text4.html new file mode 100644 index 000000000..559a12e2a --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text4.html @@ -0,0 +1,24 @@ + + + + + + + End tag variables + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      End tag variables

                      + + diff --git a/www/design/everett/serial_pres/pres2/text5.html b/www/design/everett/serial_pres/pres2/text5.html new file mode 100644 index 000000000..5147e5a55 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text5.html @@ -0,0 +1,24 @@ + + + + + + + Chunking variables (non-frag) + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Chunking variables (non-frag)

                      + + diff --git a/www/design/everett/serial_pres/pres2/text6.html b/www/design/everett/serial_pres/pres2/text6.html new file mode 100644 index 000000000..f7cfa4960 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text6.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype code 1 (write_value) + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Valuetype code 1 (write_value)

                      + + diff --git a/www/design/everett/serial_pres/pres2/text7.html b/www/design/everett/serial_pres/pres2/text7.html new file mode 100644 index 000000000..8374f9da0 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text7.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype code 2 (block methods) + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Valuetype code 2 (block methods)

                      + + diff --git a/www/design/everett/serial_pres/pres2/text8.html b/www/design/everett/serial_pres/pres2/text8.html new file mode 100644 index 000000000..4dd71450a --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text8.html @@ -0,0 +1,24 @@ + + + + + + + Valuetype code 3 (end tag methods) + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Valuetype code 3 (end tag methods)

                      + + diff --git a/www/design/everett/serial_pres/pres2/text9.html b/www/design/everett/serial_pres/pres2/text9.html new file mode 100644 index 000000000..8ce76de24 --- /dev/null +++ b/www/design/everett/serial_pres/pres2/text9.html @@ -0,0 +1,24 @@ + + + + + + + Example 1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Example 1

                      + + diff --git a/www/design/everett/serial_pres/pres3/first0.jpg b/www/design/everett/serial_pres/pres3/first0.jpg new file mode 100644 index 000000000..9bce47c69 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/first0.jpg differ diff --git a/www/design/everett/serial_pres/pres3/first1.jpg b/www/design/everett/serial_pres/pres3/first1.jpg new file mode 100644 index 000000000..a25a044d8 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/first1.jpg differ diff --git a/www/design/everett/serial_pres/pres3/img0.html b/www/design/everett/serial_pres/pres3/img0.html new file mode 100644 index 000000000..d1e92b25b --- /dev/null +++ b/www/design/everett/serial_pres/pres3/img0.html @@ -0,0 +1,24 @@ + + + + + + + Serialization 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres3/img0.jpg b/www/design/everett/serial_pres/pres3/img0.jpg new file mode 100644 index 000000000..35bdfbda9 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/img0.jpg differ diff --git a/www/design/everett/serial_pres/pres3/img1.html b/www/design/everett/serial_pres/pres3/img1.html new file mode 100644 index 000000000..b61bb9ebd --- /dev/null +++ b/www/design/everett/serial_pres/pres3/img1.html @@ -0,0 +1,24 @@ + + + + + + + RMI writeObject refresh + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres3/img1.jpg b/www/design/everett/serial_pres/pres3/img1.jpg new file mode 100644 index 000000000..7ab5e4411 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/img1.jpg differ diff --git a/www/design/everett/serial_pres/pres3/img2.html b/www/design/everett/serial_pres/pres3/img2.html new file mode 100644 index 000000000..64c81a628 --- /dev/null +++ b/www/design/everett/serial_pres/pres3/img2.html @@ -0,0 +1,24 @@ + + + + + + + Original Problem + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres3/img2.jpg b/www/design/everett/serial_pres/pres3/img2.jpg new file mode 100644 index 000000000..6cca75651 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/img2.jpg differ diff --git a/www/design/everett/serial_pres/pres3/img3.html b/www/design/everett/serial_pres/pres3/img3.html new file mode 100644 index 000000000..43f1f3202 --- /dev/null +++ b/www/design/everett/serial_pres/pres3/img3.html @@ -0,0 +1,23 @@ + + + + + + Example: Old + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres3/img3.jpg b/www/design/everett/serial_pres/pres3/img3.jpg new file mode 100644 index 000000000..a8abd9d5c Binary files /dev/null and b/www/design/everett/serial_pres/pres3/img3.jpg differ diff --git a/www/design/everett/serial_pres/pres3/img4.html b/www/design/everett/serial_pres/pres3/img4.html new file mode 100644 index 000000000..833d8ba6f --- /dev/null +++ b/www/design/everett/serial_pres/pres3/img4.html @@ -0,0 +1,24 @@ + + + + + + + Example: New + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres3/img4.jpg b/www/design/everett/serial_pres/pres3/img4.jpg new file mode 100644 index 000000000..bbdab26f2 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/img4.jpg differ diff --git a/www/design/everett/serial_pres/pres3/index.jpg b/www/design/everett/serial_pres/pres3/index.jpg new file mode 100644 index 000000000..9ce70eb72 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/index.jpg differ diff --git a/www/design/everett/serial_pres/pres3/last0.jpg b/www/design/everett/serial_pres/pres3/last0.jpg new file mode 100644 index 000000000..10b7d4523 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/last0.jpg differ diff --git a/www/design/everett/serial_pres/pres3/last1.jpg b/www/design/everett/serial_pres/pres3/last1.jpg new file mode 100644 index 000000000..37bc3cd51 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/last1.jpg differ diff --git a/www/design/everett/serial_pres/pres3/next0.jpg b/www/design/everett/serial_pres/pres3/next0.jpg new file mode 100644 index 000000000..80f7c1ab3 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/next0.jpg differ diff --git a/www/design/everett/serial_pres/pres3/next1.jpg b/www/design/everett/serial_pres/pres3/next1.jpg new file mode 100644 index 000000000..56834248f Binary files /dev/null and b/www/design/everett/serial_pres/pres3/next1.jpg differ diff --git a/www/design/everett/serial_pres/pres3/prev0.jpg b/www/design/everett/serial_pres/pres3/prev0.jpg new file mode 100644 index 000000000..ddcd550d5 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/prev0.jpg differ diff --git a/www/design/everett/serial_pres/pres3/prev1.jpg b/www/design/everett/serial_pres/pres3/prev1.jpg new file mode 100644 index 000000000..e195e5bf4 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/prev1.jpg differ diff --git a/www/design/everett/serial_pres/pres3/serial3pres.html b/www/design/everett/serial_pres/pres3/serial3pres.html new file mode 100644 index 000000000..4480e5b55 --- /dev/null +++ b/www/design/everett/serial_pres/pres3/serial3pres.html @@ -0,0 +1,40 @@ + + + + + + + Serialization 3 + + +
                      +

                      Click here to start

                      +
                      +
                      + +
                      +

                      Table of contents

                      + + + + +
                      +

                      Author: Everett Anderson

                      +

                      E-mail: dev@glassfish-corba.dev.java.net

                      +

                      Homepage: http://glassfish-corba.dev.java.net/

                      +

                      Further information:
                      +Transformed to HTML by Ken Cavanaugh

                      +

                      Download presentation

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres3/serial3pres.odp b/www/design/everett/serial_pres/pres3/serial3pres.odp new file mode 100644 index 000000000..d8febac98 Binary files /dev/null and b/www/design/everett/serial_pres/pres3/serial3pres.odp differ diff --git a/www/design/everett/serial_pres/pres3/serial3pres.sxi b/www/design/everett/serial_pres/pres3/serial3pres.sxi new file mode 100644 index 000000000..e16f3569b Binary files /dev/null and b/www/design/everett/serial_pres/pres3/serial3pres.sxi differ diff --git a/www/design/everett/serial_pres/pres3/text.jpg b/www/design/everett/serial_pres/pres3/text.jpg new file mode 100644 index 000000000..eed22dd2f Binary files /dev/null and b/www/design/everett/serial_pres/pres3/text.jpg differ diff --git a/www/design/everett/serial_pres/pres3/text0.html b/www/design/everett/serial_pres/pres3/text0.html new file mode 100644 index 000000000..1bba78dfa --- /dev/null +++ b/www/design/everett/serial_pres/pres3/text0.html @@ -0,0 +1,25 @@ + + + + + + + Serialization 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Serialization 3: RMI-IIOP Stream Format 2 Overview

                      +June 13, 2002 + + diff --git a/www/design/everett/serial_pres/pres3/text1.html b/www/design/everett/serial_pres/pres3/text1.html new file mode 100644 index 000000000..f9e111e20 --- /dev/null +++ b/www/design/everett/serial_pres/pres3/text1.html @@ -0,0 +1,24 @@ + + + + + + + RMI writeObject refresh + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      RMI writeObject refresh

                      + + diff --git a/www/design/everett/serial_pres/pres3/text2.html b/www/design/everett/serial_pres/pres3/text2.html new file mode 100644 index 000000000..6cd3daeff --- /dev/null +++ b/www/design/everett/serial_pres/pres3/text2.html @@ -0,0 +1,26 @@ + + + + + + + Original Problem + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Problem Case & Solution

                      +
                      • In RMI-IIOP, If a superclass evolves to become custom marshaled and writes optional data, but a receiver still has the older version, the receiver won't be able to know how to get past (or even if there is any) optional data.

                      • +
                      • Solution by Simon & Bob Scheifler: Wrap any optional data by a fake valuetype. The unmarshaler will be able to skip to the end of this fake valuetype (skips chunks until end tag).

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres3/text3.html b/www/design/everett/serial_pres/pres3/text3.html new file mode 100644 index 000000000..5b68c222d --- /dev/null +++ b/www/design/everett/serial_pres/pres3/text3.html @@ -0,0 +1,24 @@ + + + + + + + Example: Old + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Example: Old format

                      + + diff --git a/www/design/everett/serial_pres/pres3/text4.html b/www/design/everett/serial_pres/pres3/text4.html new file mode 100644 index 000000000..a96559d89 --- /dev/null +++ b/www/design/everett/serial_pres/pres3/text4.html @@ -0,0 +1,24 @@ + + + + + + + Example: New + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Example: New Format

                      + + diff --git a/www/design/everett/serial_pres/pres4/first0.jpg b/www/design/everett/serial_pres/pres4/first0.jpg new file mode 100644 index 000000000..9bce47c69 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/first0.jpg differ diff --git a/www/design/everett/serial_pres/pres4/first1.jpg b/www/design/everett/serial_pres/pres4/first1.jpg new file mode 100644 index 000000000..a25a044d8 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/first1.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img0.html b/www/design/everett/serial_pres/pres4/img0.html new file mode 100644 index 000000000..2c9afff35 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img0.html @@ -0,0 +1,24 @@ + + + + + + + Presentation 4 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img0.jpg b/www/design/everett/serial_pres/pres4/img0.jpg new file mode 100644 index 000000000..711054356 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img0.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img1.html b/www/design/everett/serial_pres/pres4/img1.html new file mode 100644 index 000000000..136ab6484 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img1.html @@ -0,0 +1,24 @@ + + + + + + + java.io.Serializable + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img1.jpg b/www/design/everett/serial_pres/pres4/img1.jpg new file mode 100644 index 000000000..09b4d1167 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img1.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img2.html b/www/design/everett/serial_pres/pres4/img2.html new file mode 100644 index 000000000..999a7ea33 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img2.html @@ -0,0 +1,24 @@ + + + + + + + Slide 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img2.jpg b/www/design/everett/serial_pres/pres4/img2.jpg new file mode 100644 index 000000000..ded0985be Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img2.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img3.html b/www/design/everett/serial_pres/pres4/img3.html new file mode 100644 index 000000000..f11b80450 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img3.html @@ -0,0 +1,24 @@ + + + + + + + Slide 4 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img3.jpg b/www/design/everett/serial_pres/pres4/img3.jpg new file mode 100644 index 000000000..39de49b3a Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img3.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img4.html b/www/design/everett/serial_pres/pres4/img4.html new file mode 100644 index 000000000..ca8c9661f --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img4.html @@ -0,0 +1,24 @@ + + + + + + + Slide 5 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img4.jpg b/www/design/everett/serial_pres/pres4/img4.jpg new file mode 100644 index 000000000..8817b594d Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img4.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img5.html b/www/design/everett/serial_pres/pres4/img5.html new file mode 100644 index 000000000..86d9c42a9 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img5.html @@ -0,0 +1,24 @@ + + + + + + + Evolution Notes + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img5.jpg b/www/design/everett/serial_pres/pres4/img5.jpg new file mode 100644 index 000000000..4841fac5d Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img5.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img6.html b/www/design/everett/serial_pres/pres4/img6.html new file mode 100644 index 000000000..467bd896b --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img6.html @@ -0,0 +1,24 @@ + + + + + + + Evolution and RMI-IIOP + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img6.jpg b/www/design/everett/serial_pres/pres4/img6.jpg new file mode 100644 index 000000000..37155031f Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img6.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img7.html b/www/design/everett/serial_pres/pres4/img7.html new file mode 100644 index 000000000..154427e8c --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img7.html @@ -0,0 +1,24 @@ + + + + + + + CDROutputStream write_value + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img7.jpg b/www/design/everett/serial_pres/pres4/img7.jpg new file mode 100644 index 000000000..a4414ebb7 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img7.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img8.html b/www/design/everett/serial_pres/pres4/img8.html new file mode 100644 index 000000000..e05e3b30f --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img8.html @@ -0,0 +1,24 @@ + + + + + + + CDRInputStream read_value + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img8.jpg b/www/design/everett/serial_pres/pres4/img8.jpg new file mode 100644 index 000000000..c73af31fd Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img8.jpg differ diff --git a/www/design/everett/serial_pres/pres4/img9.html b/www/design/everett/serial_pres/pres4/img9.html new file mode 100644 index 000000000..35215ee01 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/img9.html @@ -0,0 +1,24 @@ + + + + + + + RMI-IIOP Problem + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/img9.jpg b/www/design/everett/serial_pres/pres4/img9.jpg new file mode 100644 index 000000000..5cbda67e9 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/img9.jpg differ diff --git a/www/design/everett/serial_pres/pres4/index.jpg b/www/design/everett/serial_pres/pres4/index.jpg new file mode 100644 index 000000000..9ce70eb72 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/index.jpg differ diff --git a/www/design/everett/serial_pres/pres4/last0.jpg b/www/design/everett/serial_pres/pres4/last0.jpg new file mode 100644 index 000000000..10b7d4523 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/last0.jpg differ diff --git a/www/design/everett/serial_pres/pres4/last1.jpg b/www/design/everett/serial_pres/pres4/last1.jpg new file mode 100644 index 000000000..37bc3cd51 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/last1.jpg differ diff --git a/www/design/everett/serial_pres/pres4/next0.jpg b/www/design/everett/serial_pres/pres4/next0.jpg new file mode 100644 index 000000000..80f7c1ab3 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/next0.jpg differ diff --git a/www/design/everett/serial_pres/pres4/next1.jpg b/www/design/everett/serial_pres/pres4/next1.jpg new file mode 100644 index 000000000..56834248f Binary files /dev/null and b/www/design/everett/serial_pres/pres4/next1.jpg differ diff --git a/www/design/everett/serial_pres/pres4/prev0.jpg b/www/design/everett/serial_pres/pres4/prev0.jpg new file mode 100644 index 000000000..ddcd550d5 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/prev0.jpg differ diff --git a/www/design/everett/serial_pres/pres4/prev1.jpg b/www/design/everett/serial_pres/pres4/prev1.jpg new file mode 100644 index 000000000..e195e5bf4 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/prev1.jpg differ diff --git a/www/design/everett/serial_pres/pres4/serial4pres.html b/www/design/everett/serial_pres/pres4/serial4pres.html new file mode 100644 index 000000000..0b59f92af --- /dev/null +++ b/www/design/everett/serial_pres/pres4/serial4pres.html @@ -0,0 +1,45 @@ + + + + + + + Presentation 4 + + +
                      +

                      Click here to start

                      +
                      +
                      + +
                      +

                      Table of contents

                      + + + + + + + + + +
                      +

                      Author: Everett Anderson

                      +

                      E-mail: dev@glassfish-corba.dev.java.net

                      +

                      Homepage: http://glassfish-corba.dev.java.net/

                      +

                      Further information:
                      +Transformed to HTML by Ken Cavanaugh

                      +

                      Download presentation

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres4/serial4pres.odp b/www/design/everett/serial_pres/pres4/serial4pres.odp new file mode 100644 index 000000000..00b8e1d64 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/serial4pres.odp differ diff --git a/www/design/everett/serial_pres/pres4/serial4pres.sxi b/www/design/everett/serial_pres/pres4/serial4pres.sxi new file mode 100644 index 000000000..02ac6ac60 Binary files /dev/null and b/www/design/everett/serial_pres/pres4/serial4pres.sxi differ diff --git a/www/design/everett/serial_pres/pres4/text.jpg b/www/design/everett/serial_pres/pres4/text.jpg new file mode 100644 index 000000000..eed22dd2f Binary files /dev/null and b/www/design/everett/serial_pres/pres4/text.jpg differ diff --git a/www/design/everett/serial_pres/pres4/text0.html b/www/design/everett/serial_pres/pres4/text0.html new file mode 100644 index 000000000..ba63bd21d --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text0.html @@ -0,0 +1,28 @@ + + + + + + + Presentation 4 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Serialization 4: Serializable refresh

                      +Review of Java Object Serialization +and +Relationship with RMI-IIOP +June 25, 2002 + + diff --git a/www/design/everett/serial_pres/pres4/text1.html b/www/design/everett/serial_pres/pres4/text1.html new file mode 100644 index 000000000..76597bdae --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text1.html @@ -0,0 +1,31 @@ + + + + + + + java.io.Serializable + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      java.io.Serializable

                      +
                      • Order of serialization: top down

                      • +
                      • writeObject/readObject

                      • +
                      • PutField/GetField

                      • +
                      • writeReplace/readResolve

                      • +
                      • serialVersionUID

                      • +
                      • serialPersistantFields

                      • +
                      • defaultWriteObject/defaultReadObject

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres4/text2.html b/www/design/everett/serial_pres/pres4/text2.html new file mode 100644 index 000000000..db7a338f2 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text2.html @@ -0,0 +1,24 @@ + + + + + + + Slide 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Example 1

                      + + diff --git a/www/design/everett/serial_pres/pres4/text3.html b/www/design/everett/serial_pres/pres4/text3.html new file mode 100644 index 000000000..0aed6a6be --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text3.html @@ -0,0 +1,24 @@ + + + + + + + Slide 4 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      + + diff --git a/www/design/everett/serial_pres/pres4/text4.html b/www/design/everett/serial_pres/pres4/text4.html new file mode 100644 index 000000000..46d06c6c0 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text4.html @@ -0,0 +1,24 @@ + + + + + + + Slide 5 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      + + diff --git a/www/design/everett/serial_pres/pres4/text5.html b/www/design/everett/serial_pres/pres4/text5.html new file mode 100644 index 000000000..f8e69c78b --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text5.html @@ -0,0 +1,31 @@ + + + + + + + Evolution Notes + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Evolution Notes

                      +
                      • Lots of rules for compatible/incompatible changes

                      • +
                      • Arun built a test of all basic changes including writeObject/readObject, but it took weeks to run, so hasn't been run in a year. About 10 classes were taken as a quick look matrix.

                      • +
                      • We haven't tested writeReplace/readResolve very much

                      • +
                      • We haven't tested inner classes and inner class evolution

                      • +
                      • We haven't tested evolving superclasses very much

                      • +
                      • We haven't tested optional data semantics very much

                      • +
                      • http://java.sun.com/j2se/1.4/docs/guide/serialization/index.html

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres4/text6.html b/www/design/everett/serial_pres/pres4/text6.html new file mode 100644 index 000000000..b91e4eb93 --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text6.html @@ -0,0 +1,28 @@ + + + + + + + Evolution and RMI-IIOP + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Evolution & RMI-IIOP

                      +
                      • Java Serialization includes all type information on the wire. RMI-IIOP doesn't, so to handle evolution, must use the callback Codebase object. Some want a new RMI-IIOP stream version in which a TypeCode is sent with the valuetype giving all info.

                      • +
                      • Codebase IOR exchanged via SendingContext Runtime service context.

                      • +
                      • Codebase "meta" method query results in information represented by a FullValueDescriptor including ValueMembers and TypeCodes which are then used to compare the remote and local versions.

                      • +
                      • We have sketchy TypeCode and comparison code

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres4/text7.html b/www/design/everett/serial_pres/pres4/text7.html new file mode 100644 index 000000000..5dc856dde --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text7.html @@ -0,0 +1,24 @@ + + + + + + + CDROutputStream write_value + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      CDROutputStream write_value

                      + + diff --git a/www/design/everett/serial_pres/pres4/text8.html b/www/design/everett/serial_pres/pres4/text8.html new file mode 100644 index 000000000..2de5553fe --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text8.html @@ -0,0 +1,24 @@ + + + + + + + CDRInputStream read_value + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      CDRInputStream read_value

                      + + diff --git a/www/design/everett/serial_pres/pres4/text9.html b/www/design/everett/serial_pres/pres4/text9.html new file mode 100644 index 000000000..661f804bf --- /dev/null +++ b/www/design/everett/serial_pres/pres4/text9.html @@ -0,0 +1,24 @@ + + + + + + + RMI-IIOP Problem + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      RMI-IIOP Problems

                      + + diff --git a/www/design/everett/serial_pres/pres5/first0.jpg b/www/design/everett/serial_pres/pres5/first0.jpg new file mode 100644 index 000000000..9bce47c69 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/first0.jpg differ diff --git a/www/design/everett/serial_pres/pres5/first1.jpg b/www/design/everett/serial_pres/pres5/first1.jpg new file mode 100644 index 000000000..a25a044d8 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/first1.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img0.html b/www/design/everett/serial_pres/pres5/img0.html new file mode 100644 index 000000000..1cd393db2 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img0.html @@ -0,0 +1,24 @@ + + + + + + + Serialization 5 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img0.jpg b/www/design/everett/serial_pres/pres5/img0.jpg new file mode 100644 index 000000000..9ffc995e7 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img0.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img1.html b/www/design/everett/serial_pres/pres5/img1.html new file mode 100644 index 000000000..3ac43a47b --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img1.html @@ -0,0 +1,24 @@ + + + + + + + Motivation + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img1.jpg b/www/design/everett/serial_pres/pres5/img1.jpg new file mode 100644 index 000000000..cbef5354f Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img1.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img10.html b/www/design/everett/serial_pres/pres5/img10.html new file mode 100644 index 000000000..770f16fc5 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img10.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img10.jpg b/www/design/everett/serial_pres/pres5/img10.jpg new file mode 100644 index 000000000..3a35ea93d Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img10.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img11.html b/www/design/everett/serial_pres/pres5/img11.html new file mode 100644 index 000000000..872f99a33 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img11.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img11.jpg b/www/design/everett/serial_pres/pres5/img11.jpg new file mode 100644 index 000000000..0c55ffc61 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img11.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img12.html b/www/design/everett/serial_pres/pres5/img12.html new file mode 100644 index 000000000..5860b21fc --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img12.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img12.jpg b/www/design/everett/serial_pres/pres5/img12.jpg new file mode 100644 index 000000000..ace9d55cd Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img12.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img13.html b/www/design/everett/serial_pres/pres5/img13.html new file mode 100644 index 000000000..c0fd1c471 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img13.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 4 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img13.jpg b/www/design/everett/serial_pres/pres5/img13.jpg new file mode 100644 index 000000000..9f03d5090 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img13.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img14.html b/www/design/everett/serial_pres/pres5/img14.html new file mode 100644 index 000000000..9ac418a1f --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img14.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 5 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img14.jpg b/www/design/everett/serial_pres/pres5/img14.jpg new file mode 100644 index 000000000..3f733b173 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img14.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img15.html b/www/design/everett/serial_pres/pres5/img15.html new file mode 100644 index 000000000..abfa075d1 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img15.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img15.jpg b/www/design/everett/serial_pres/pres5/img15.jpg new file mode 100644 index 000000000..607b7ef6c Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img15.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img16.html b/www/design/everett/serial_pres/pres5/img16.html new file mode 100644 index 000000000..f57b5811a --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img16.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img16.jpg b/www/design/everett/serial_pres/pres5/img16.jpg new file mode 100644 index 000000000..31c23620c Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img16.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img17.html b/www/design/everett/serial_pres/pres5/img17.html new file mode 100644 index 000000000..66ee1f2de --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img17.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img17.jpg b/www/design/everett/serial_pres/pres5/img17.jpg new file mode 100644 index 000000000..9361dd401 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img17.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img18.html b/www/design/everett/serial_pres/pres5/img18.html new file mode 100644 index 000000000..cce2915c8 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img18.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 4 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img18.jpg b/www/design/everett/serial_pres/pres5/img18.jpg new file mode 100644 index 000000000..787487c59 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img18.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img19.html b/www/design/everett/serial_pres/pres5/img19.html new file mode 100644 index 000000000..763c318da --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img19.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 5 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img19.jpg b/www/design/everett/serial_pres/pres5/img19.jpg new file mode 100644 index 000000000..38027b0aa Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img19.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img2.html b/www/design/everett/serial_pres/pres5/img2.html new file mode 100644 index 000000000..9c26af4c2 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img2.html @@ -0,0 +1,24 @@ + + + + + + + Overview + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img2.jpg b/www/design/everett/serial_pres/pres5/img2.jpg new file mode 100644 index 000000000..c287a637a Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img2.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img20.html b/www/design/everett/serial_pres/pres5/img20.html new file mode 100644 index 000000000..3dc915396 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img20.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 6 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img20.jpg b/www/design/everett/serial_pres/pres5/img20.jpg new file mode 100644 index 000000000..50e550677 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img20.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img21.html b/www/design/everett/serial_pres/pres5/img21.html new file mode 100644 index 000000000..84dd3f55d --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img21.html @@ -0,0 +1,24 @@ + + + + + + + How does ORB monitor optional data? + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img21.jpg b/www/design/everett/serial_pres/pres5/img21.jpg new file mode 100644 index 000000000..7b497cd85 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img21.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img22.html b/www/design/everett/serial_pres/pres5/img22.html new file mode 100644 index 000000000..1658e4371 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img22.html @@ -0,0 +1,24 @@ + + + + + + + Issues + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img22.jpg b/www/design/everett/serial_pres/pres5/img22.jpg new file mode 100644 index 000000000..c8f1d106b Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img22.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img3.html b/www/design/everett/serial_pres/pres5/img3.html new file mode 100644 index 000000000..abab9bb61 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img3.html @@ -0,0 +1,24 @@ + + + + + + + Bonus Complexity + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img3.jpg b/www/design/everett/serial_pres/pres5/img3.jpg new file mode 100644 index 000000000..9fdf87402 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img3.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img4.html b/www/design/everett/serial_pres/pres5/img4.html new file mode 100644 index 000000000..0975485e3 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img4.html @@ -0,0 +1,24 @@ + + + + + + + ValueHandlerMultiFormat + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img4.jpg b/www/design/everett/serial_pres/pres5/img4.jpg new file mode 100644 index 000000000..ac1ae40c5 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img4.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img5.html b/www/design/everett/serial_pres/pres5/img5.html new file mode 100644 index 000000000..1dce79942 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img5.html @@ -0,0 +1,24 @@ + + + + + + + ValueHandlerMultiFormat 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img5.jpg b/www/design/everett/serial_pres/pres5/img5.jpg new file mode 100644 index 000000000..0d38543f2 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img5.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img6.html b/www/design/everett/serial_pres/pres5/img6.html new file mode 100644 index 000000000..055bc4b3e --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img6.html @@ -0,0 +1,24 @@ + + + + + + + ValueOutputStream + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img6.jpg b/www/design/everett/serial_pres/pres5/img6.jpg new file mode 100644 index 000000000..82c017900 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img6.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img7.html b/www/design/everett/serial_pres/pres5/img7.html new file mode 100644 index 000000000..325faf152 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img7.html @@ -0,0 +1,24 @@ + + + + + + + ValueInputStream + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img7.jpg b/www/design/everett/serial_pres/pres5/img7.jpg new file mode 100644 index 000000000..47fb48d73 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img7.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img8.html b/www/design/everett/serial_pres/pres5/img8.html new file mode 100644 index 000000000..58441874c --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img8.html @@ -0,0 +1,24 @@ + + + + + + + Output State Diagram + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img8.jpg b/www/design/everett/serial_pres/pres5/img8.jpg new file mode 100644 index 000000000..6a8e455dd Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img8.jpg differ diff --git a/www/design/everett/serial_pres/pres5/img9.html b/www/design/everett/serial_pres/pres5/img9.html new file mode 100644 index 000000000..d29a2168b --- /dev/null +++ b/www/design/everett/serial_pres/pres5/img9.html @@ -0,0 +1,24 @@ + + + + + + + Input State Diagram + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/img9.jpg b/www/design/everett/serial_pres/pres5/img9.jpg new file mode 100644 index 000000000..6d3f15f75 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/img9.jpg differ diff --git a/www/design/everett/serial_pres/pres5/index.jpg b/www/design/everett/serial_pres/pres5/index.jpg new file mode 100644 index 000000000..9ce70eb72 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/index.jpg differ diff --git a/www/design/everett/serial_pres/pres5/last0.jpg b/www/design/everett/serial_pres/pres5/last0.jpg new file mode 100644 index 000000000..10b7d4523 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/last0.jpg differ diff --git a/www/design/everett/serial_pres/pres5/last1.jpg b/www/design/everett/serial_pres/pres5/last1.jpg new file mode 100644 index 000000000..37bc3cd51 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/last1.jpg differ diff --git a/www/design/everett/serial_pres/pres5/next0.jpg b/www/design/everett/serial_pres/pres5/next0.jpg new file mode 100644 index 000000000..80f7c1ab3 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/next0.jpg differ diff --git a/www/design/everett/serial_pres/pres5/next1.jpg b/www/design/everett/serial_pres/pres5/next1.jpg new file mode 100644 index 000000000..56834248f Binary files /dev/null and b/www/design/everett/serial_pres/pres5/next1.jpg differ diff --git a/www/design/everett/serial_pres/pres5/prev0.jpg b/www/design/everett/serial_pres/pres5/prev0.jpg new file mode 100644 index 000000000..ddcd550d5 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/prev0.jpg differ diff --git a/www/design/everett/serial_pres/pres5/prev1.jpg b/www/design/everett/serial_pres/pres5/prev1.jpg new file mode 100644 index 000000000..e195e5bf4 Binary files /dev/null and b/www/design/everett/serial_pres/pres5/prev1.jpg differ diff --git a/www/design/everett/serial_pres/pres5/serial5pres.html b/www/design/everett/serial_pres/pres5/serial5pres.html new file mode 100644 index 000000000..06ecc0c46 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/serial5pres.html @@ -0,0 +1,58 @@ + + + + + + + Serialization 5 + + +
                      +

                      Click here to start

                      +
                      +
                      + +
                      +

                      Table of contents

                      + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      Author: Everett Anderson

                      +

                      E-mail: dev@glassfish-corba.dev.java.net

                      +

                      Homepage: http://glassfish-corba.dev.java.net/

                      +

                      Further information:
                      +Transformed to HTML by Ken Cavanaugh

                      +

                      Download presentation

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres5/serial5pres.odp b/www/design/everett/serial_pres/pres5/serial5pres.odp new file mode 100644 index 000000000..7b169990a Binary files /dev/null and b/www/design/everett/serial_pres/pres5/serial5pres.odp differ diff --git a/www/design/everett/serial_pres/pres5/serial5pres.sxi b/www/design/everett/serial_pres/pres5/serial5pres.sxi new file mode 100644 index 000000000..bf2437deb Binary files /dev/null and b/www/design/everett/serial_pres/pres5/serial5pres.sxi differ diff --git a/www/design/everett/serial_pres/pres5/text.jpg b/www/design/everett/serial_pres/pres5/text.jpg new file mode 100644 index 000000000..eed22dd2f Binary files /dev/null and b/www/design/everett/serial_pres/pres5/text.jpg differ diff --git a/www/design/everett/serial_pres/pres5/text0.html b/www/design/everett/serial_pres/pres5/text0.html new file mode 100644 index 000000000..9f17e43b3 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text0.html @@ -0,0 +1,27 @@ + + + + + + + Serialization 5 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Serialization 5: Stream Format 2

                      +RMI-IIOP Stream Format Version 2 +Writing Data +July 18, 2002 + + diff --git a/www/design/everett/serial_pres/pres5/text1.html b/www/design/everett/serial_pres/pres5/text1.html new file mode 100644 index 000000000..a008dec9e --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text1.html @@ -0,0 +1,24 @@ + + + + + + + Motivation + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Motivation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text10.html b/www/design/everett/serial_pres/pres5/text10.html new file mode 100644 index 000000000..991205403 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text10.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Output Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text11.html b/www/design/everett/serial_pres/pres5/text11.html new file mode 100644 index 000000000..1ec7f87d4 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text11.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Output Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text12.html b/www/design/everett/serial_pres/pres5/text12.html new file mode 100644 index 000000000..719ec5c23 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text12.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Output Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text13.html b/www/design/everett/serial_pres/pres5/text13.html new file mode 100644 index 000000000..516b54543 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text13.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 4 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Output Implementation 4

                      + + diff --git a/www/design/everett/serial_pres/pres5/text14.html b/www/design/everett/serial_pres/pres5/text14.html new file mode 100644 index 000000000..0f5494e42 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text14.html @@ -0,0 +1,24 @@ + + + + + + + Output Implementation 5 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Output Implementation 5

                      + + diff --git a/www/design/everett/serial_pres/pres5/text15.html b/www/design/everett/serial_pres/pres5/text15.html new file mode 100644 index 000000000..e592b61e5 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text15.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text16.html b/www/design/everett/serial_pres/pres5/text16.html new file mode 100644 index 000000000..c2145514d --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text16.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text17.html b/www/design/everett/serial_pres/pres5/text17.html new file mode 100644 index 000000000..c87dca32f --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text17.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text18.html b/www/design/everett/serial_pres/pres5/text18.html new file mode 100644 index 000000000..64a87131d --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text18.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 4 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text19.html b/www/design/everett/serial_pres/pres5/text19.html new file mode 100644 index 000000000..22592a16f --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text19.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 5 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text2.html b/www/design/everett/serial_pres/pres5/text2.html new file mode 100644 index 000000000..67b4a8408 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text2.html @@ -0,0 +1,24 @@ + + + + + + + Overview + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Overview

                      + + diff --git a/www/design/everett/serial_pres/pres5/text20.html b/www/design/everett/serial_pres/pres5/text20.html new file mode 100644 index 000000000..31e19e8ec --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text20.html @@ -0,0 +1,24 @@ + + + + + + + Input Implementation 6 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Implementation

                      + + diff --git a/www/design/everett/serial_pres/pres5/text21.html b/www/design/everett/serial_pres/pres5/text21.html new file mode 100644 index 000000000..4b3f249c4 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text21.html @@ -0,0 +1,27 @@ + + + + + + + How does ORB monitor optional data? + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      How does ORB input stream monitor optional data?

                      +
                      • If the optional data only has a null, the ORB stream (CDRInputStream_1_0) uses a specialNoOptionalDataState boolean to throw the specified MARSHAL exception.

                      • +
                      • If what the ValueHandler wants to read won't fit in the current chunk, we know it can't be compatible since one can't break primitives, arrays of primitives, Strings, etc, across chunks.

                      • +
                      • If we're at the end of a chunk and the next thing is an end tag, we know we must have reached the end of the current valuetype's data, so requesting more would be an error.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres5/text22.html b/www/design/everett/serial_pres/pres5/text22.html new file mode 100644 index 000000000..2e047eac9 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text22.html @@ -0,0 +1,27 @@ + + + + + + + Issues + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Stream Format Version 2 Issues

                      +
                      • This works great for normal data in the stream, but what about encapsulations? Especially Codecs in PI and our service contexts! Currently, my implementation uses stream format version 1 for this kind of thing, but this won't work well if Throwable evolves further (UnknownExceptionInfo service context) or people marshal RMI-IIOP valuetypes with Codecs. (BEA is doing more these days with valuetypes in service contexts.)

                      • +
                      • Anys don't seem to be an issue since they keep valuetypes until the Any is written to a stream, and then just hand the valuetype to the Any.

                      • +
                      • Testing is going to be difficult. The best tests here involve class evolution, both superclasses and most derived classes evolving to add writeObject methods with and without optional data.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres5/text3.html b/www/design/everett/serial_pres/pres5/text3.html new file mode 100644 index 000000000..4411cbd53 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text3.html @@ -0,0 +1,24 @@ + + + + + + + Bonus Complexity + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Bonus Complexity

                      + + diff --git a/www/design/everett/serial_pres/pres5/text4.html b/www/design/everett/serial_pres/pres5/text4.html new file mode 100644 index 000000000..72fe87a61 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text4.html @@ -0,0 +1,24 @@ + + + + + + + ValueHandlerMultiFormat + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      ValueHandlerMultiFormat

                      + + diff --git a/www/design/everett/serial_pres/pres5/text5.html b/www/design/everett/serial_pres/pres5/text5.html new file mode 100644 index 000000000..b37b9fcc6 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text5.html @@ -0,0 +1,24 @@ + + + + + + + ValueHandlerMultiFormat 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      ValueHandlerMultiFormat

                      + + diff --git a/www/design/everett/serial_pres/pres5/text6.html b/www/design/everett/serial_pres/pres5/text6.html new file mode 100644 index 000000000..b3e27570c --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text6.html @@ -0,0 +1,24 @@ + + + + + + + ValueOutputStream + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      ValueOutputStream

                      + + diff --git a/www/design/everett/serial_pres/pres5/text7.html b/www/design/everett/serial_pres/pres5/text7.html new file mode 100644 index 000000000..54248ca4f --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text7.html @@ -0,0 +1,24 @@ + + + + + + + ValueInputStream + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      ValueInputStream

                      + + diff --git a/www/design/everett/serial_pres/pres5/text8.html b/www/design/everett/serial_pres/pres5/text8.html new file mode 100644 index 000000000..94bc18639 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text8.html @@ -0,0 +1,24 @@ + + + + + + + Output State Diagram + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Output State Diagram

                      + + diff --git a/www/design/everett/serial_pres/pres5/text9.html b/www/design/everett/serial_pres/pres5/text9.html new file mode 100644 index 000000000..0ee882864 --- /dev/null +++ b/www/design/everett/serial_pres/pres5/text9.html @@ -0,0 +1,24 @@ + + + + + + + Input State Diagram + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input State Diagram

                      + + diff --git a/www/design/everett/serial_pres/pres6/first0.jpg b/www/design/everett/serial_pres/pres6/first0.jpg new file mode 100644 index 000000000..9bce47c69 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/first0.jpg differ diff --git a/www/design/everett/serial_pres/pres6/first1.jpg b/www/design/everett/serial_pres/pres6/first1.jpg new file mode 100644 index 000000000..a25a044d8 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/first1.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img0.html b/www/design/everett/serial_pres/pres6/img0.html new file mode 100644 index 000000000..e951b92e3 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img0.html @@ -0,0 +1,24 @@ + + + + + + + Serialization 6 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img0.jpg b/www/design/everett/serial_pres/pres6/img0.jpg new file mode 100644 index 000000000..5a1d8b13d Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img0.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img1.html b/www/design/everett/serial_pres/pres6/img1.html new file mode 100644 index 000000000..0d55e9c1a --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img1.html @@ -0,0 +1,24 @@ + + + + + + + Recent fixes + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img1.jpg b/www/design/everett/serial_pres/pres6/img1.jpg new file mode 100644 index 000000000..145a0b4fb Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img1.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img10.html b/www/design/everett/serial_pres/pres6/img10.html new file mode 100644 index 000000000..8583c84d9 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img10.html @@ -0,0 +1,24 @@ + + + + + + + java.io.DataOutput/Input + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img10.jpg b/www/design/everett/serial_pres/pres6/img10.jpg new file mode 100644 index 000000000..3ab381895 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img10.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img11.html b/www/design/everett/serial_pres/pres6/img11.html new file mode 100644 index 000000000..a63901048 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img11.html @@ -0,0 +1,24 @@ + + + + + + + Tools + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img11.jpg b/www/design/everett/serial_pres/pres6/img11.jpg new file mode 100644 index 000000000..ad05c5085 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img11.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img12.html b/www/design/everett/serial_pres/pres6/img12.html new file mode 100644 index 000000000..8ac56a31b --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img12.html @@ -0,0 +1,24 @@ + + + + + + + corbalinux1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img12.jpg b/www/design/everett/serial_pres/pres6/img12.jpg new file mode 100644 index 000000000..df646e972 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img12.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img13.html b/www/design/everett/serial_pres/pres6/img13.html new file mode 100644 index 000000000..af0dc4ac5 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img13.html @@ -0,0 +1,24 @@ + + + + + + + Switching to java.nio + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img13.jpg b/www/design/everett/serial_pres/pres6/img13.jpg new file mode 100644 index 000000000..d15e8e46d Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img13.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img14.html b/www/design/everett/serial_pres/pres6/img14.html new file mode 100644 index 000000000..0161a5923 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img14.html @@ -0,0 +1,24 @@ + + + + + + + Exceptions in the ValueHandler + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img14.jpg b/www/design/everett/serial_pres/pres6/img14.jpg new file mode 100644 index 000000000..d64533b18 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img14.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img15.html b/www/design/everett/serial_pres/pres6/img15.html new file mode 100644 index 000000000..a2979f4e3 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img15.html @@ -0,0 +1,24 @@ + + + + + + + Warning on IIOPInputStream/IIOPOutputStream + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img15.jpg b/www/design/everett/serial_pres/pres6/img15.jpg new file mode 100644 index 000000000..fd0935517 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img15.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img16.html b/www/design/everett/serial_pres/pres6/img16.html new file mode 100644 index 000000000..9d0087378 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img16.html @@ -0,0 +1,24 @@ + + + + + + + JDK 1.3.0 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img16.jpg b/www/design/everett/serial_pres/pres6/img16.jpg new file mode 100644 index 000000000..fc8cf1620 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img16.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img17.html b/www/design/everett/serial_pres/pres6/img17.html new file mode 100644 index 000000000..5ee4be6d7 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img17.html @@ -0,0 +1,24 @@ + + + + + + + Exceptions + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img17.jpg b/www/design/everett/serial_pres/pres6/img17.jpg new file mode 100644 index 000000000..57383f5cf Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img17.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img18.html b/www/design/everett/serial_pres/pres6/img18.html new file mode 100644 index 000000000..1b8267621 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img18.html @@ -0,0 +1,24 @@ + + + + + + + javax.rmi.CORBA.Stub + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img18.jpg b/www/design/everett/serial_pres/pres6/img18.jpg new file mode 100644 index 000000000..7fc36c963 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img18.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img19.html b/www/design/everett/serial_pres/pres6/img19.html new file mode 100644 index 000000000..61329f915 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img19.html @@ -0,0 +1,24 @@ + + + + + + + CDR Stream Rewrite + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img19.jpg b/www/design/everett/serial_pres/pres6/img19.jpg new file mode 100644 index 000000000..b29d0ca02 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img19.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img2.html b/www/design/everett/serial_pres/pres6/img2.html new file mode 100644 index 000000000..3b8dac8a7 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img2.html @@ -0,0 +1,24 @@ + + + + + + + Input Stream Diagram 1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img2.jpg b/www/design/everett/serial_pres/pres6/img2.jpg new file mode 100644 index 000000000..2fa511127 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img2.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img20.html b/www/design/everett/serial_pres/pres6/img20.html new file mode 100644 index 000000000..b9acb81e5 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img20.html @@ -0,0 +1,24 @@ + + + + + + + Simon + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img20.jpg b/www/design/everett/serial_pres/pres6/img20.jpg new file mode 100644 index 000000000..be4d55418 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img20.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img21.html b/www/design/everett/serial_pres/pres6/img21.html new file mode 100644 index 000000000..06d01cece --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img21.html @@ -0,0 +1,24 @@ + + + + + + + corba.strm2 tests + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img21.jpg b/www/design/everett/serial_pres/pres6/img21.jpg new file mode 100644 index 000000000..b49fca28b Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img21.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img22.html b/www/design/everett/serial_pres/pres6/img22.html new file mode 100644 index 000000000..3a87f3ef9 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img22.html @@ -0,0 +1,24 @@ + + + + + + + Class evolution in corba.strm2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img22.jpg b/www/design/everett/serial_pres/pres6/img22.jpg new file mode 100644 index 000000000..5a52424b6 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img22.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img23.html b/www/design/everett/serial_pres/pres6/img23.html new file mode 100644 index 000000000..07e19f4b3 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img23.html @@ -0,0 +1,24 @@ + + + + + + + Why class4 & class5 are incompatible + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img23.jpg b/www/design/everett/serial_pres/pres6/img23.jpg new file mode 100644 index 000000000..0c80a69df Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img23.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img3.html b/www/design/everett/serial_pres/pres6/img3.html new file mode 100644 index 000000000..b2eace985 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img3.html @@ -0,0 +1,24 @@ + + + + + + + Input Stream Diagram 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img3.jpg b/www/design/everett/serial_pres/pres6/img3.jpg new file mode 100644 index 000000000..fa4d443da Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img3.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img4.html b/www/design/everett/serial_pres/pres6/img4.html new file mode 100644 index 000000000..8579f45da --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img4.html @@ -0,0 +1,24 @@ + + + + + + + Code overview 1 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img4.jpg b/www/design/everett/serial_pres/pres6/img4.jpg new file mode 100644 index 000000000..b10ea4ce0 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img4.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img5.html b/www/design/everett/serial_pres/pres6/img5.html new file mode 100644 index 000000000..d06973d09 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img5.html @@ -0,0 +1,24 @@ + + + + + + + Code overview 2 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img5.jpg b/www/design/everett/serial_pres/pres6/img5.jpg new file mode 100644 index 000000000..697eb02d9 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img5.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img6.html b/www/design/everett/serial_pres/pres6/img6.html new file mode 100644 index 000000000..605551641 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img6.html @@ -0,0 +1,24 @@ + + + + + + + Code overview 3 + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img6.jpg b/www/design/everett/serial_pres/pres6/img6.jpg new file mode 100644 index 000000000..ce1c3f0fd Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img6.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img7.html b/www/design/everett/serial_pres/pres6/img7.html new file mode 100644 index 000000000..693341cee --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img7.html @@ -0,0 +1,24 @@ + + + + + + + Rep Id Rewrite + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img7.jpg b/www/design/everett/serial_pres/pres6/img7.jpg new file mode 100644 index 000000000..98d1e33d4 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img7.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img8.html b/www/design/everett/serial_pres/pres6/img8.html new file mode 100644 index 000000000..d2a5a1276 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img8.html @@ -0,0 +1,24 @@ + + + + + + + IO Prototype + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img8.jpg b/www/design/everett/serial_pres/pres6/img8.jpg new file mode 100644 index 000000000..802011210 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img8.jpg differ diff --git a/www/design/everett/serial_pres/pres6/img9.html b/www/design/everett/serial_pres/pres6/img9.html new file mode 100644 index 000000000..b23adc198 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/img9.html @@ -0,0 +1,24 @@ + + + + + + + Uncache Fix + + +
                      +First page Back Continue Last page Overview Text

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/img9.jpg b/www/design/everett/serial_pres/pres6/img9.jpg new file mode 100644 index 000000000..fc7752718 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/img9.jpg differ diff --git a/www/design/everett/serial_pres/pres6/index.jpg b/www/design/everett/serial_pres/pres6/index.jpg new file mode 100644 index 000000000..9ce70eb72 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/index.jpg differ diff --git a/www/design/everett/serial_pres/pres6/last0.jpg b/www/design/everett/serial_pres/pres6/last0.jpg new file mode 100644 index 000000000..10b7d4523 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/last0.jpg differ diff --git a/www/design/everett/serial_pres/pres6/last1.jpg b/www/design/everett/serial_pres/pres6/last1.jpg new file mode 100644 index 000000000..37bc3cd51 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/last1.jpg differ diff --git a/www/design/everett/serial_pres/pres6/next0.jpg b/www/design/everett/serial_pres/pres6/next0.jpg new file mode 100644 index 000000000..80f7c1ab3 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/next0.jpg differ diff --git a/www/design/everett/serial_pres/pres6/next1.jpg b/www/design/everett/serial_pres/pres6/next1.jpg new file mode 100644 index 000000000..56834248f Binary files /dev/null and b/www/design/everett/serial_pres/pres6/next1.jpg differ diff --git a/www/design/everett/serial_pres/pres6/prev0.jpg b/www/design/everett/serial_pres/pres6/prev0.jpg new file mode 100644 index 000000000..ddcd550d5 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/prev0.jpg differ diff --git a/www/design/everett/serial_pres/pres6/prev1.jpg b/www/design/everett/serial_pres/pres6/prev1.jpg new file mode 100644 index 000000000..e195e5bf4 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/prev1.jpg differ diff --git a/www/design/everett/serial_pres/pres6/serial6pres.html b/www/design/everett/serial_pres/pres6/serial6pres.html new file mode 100644 index 000000000..5ec4e7fef --- /dev/null +++ b/www/design/everett/serial_pres/pres6/serial6pres.html @@ -0,0 +1,59 @@ + + + + + + + Serialization 6 + + +
                      +

                      Click here to start

                      +
                      +
                      + +
                      +

                      Table of contents

                      + + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      Author: Everett Anderson

                      +

                      E-mail: dev@glassfish-corba.dev.java.net

                      +

                      Homepage: http://glassfish-corba.dev.java.net/

                      +

                      Further information:
                      +Transformed to HTML by Ken Cavanaugh

                      +

                      Download presentation

                      +
                      + + diff --git a/www/design/everett/serial_pres/pres6/serial6pres.odp b/www/design/everett/serial_pres/pres6/serial6pres.odp new file mode 100644 index 000000000..4119e3bf8 Binary files /dev/null and b/www/design/everett/serial_pres/pres6/serial6pres.odp differ diff --git a/www/design/everett/serial_pres/pres6/serial6pres.sxi b/www/design/everett/serial_pres/pres6/serial6pres.sxi new file mode 100644 index 000000000..ec6419e1b Binary files /dev/null and b/www/design/everett/serial_pres/pres6/serial6pres.sxi differ diff --git a/www/design/everett/serial_pres/pres6/text.jpg b/www/design/everett/serial_pres/pres6/text.jpg new file mode 100644 index 000000000..eed22dd2f Binary files /dev/null and b/www/design/everett/serial_pres/pres6/text.jpg differ diff --git a/www/design/everett/serial_pres/pres6/text0.html b/www/design/everett/serial_pres/pres6/text0.html new file mode 100644 index 000000000..8184487c2 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text0.html @@ -0,0 +1,26 @@ + + + + + + + Serialization 6 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Serialization 6

                      +July 31, 2002 +Remaining Items + + diff --git a/www/design/everett/serial_pres/pres6/text1.html b/www/design/everett/serial_pres/pres6/text1.html new file mode 100644 index 000000000..2c04ed8da --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text1.html @@ -0,0 +1,27 @@ + + + + + + + Recent fixes + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Recent fixes to rip-int

                      +
                      • Forgot case in which sender was not custom marshaled but we have a read object method which might read optional data.

                      • +
                      • Added state to help when a readObject method tries to read optional data again after already failing once.

                      • +
                      • Fixed serialization code's corruption of variables when remote side has a superclass that the local class doesn't.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text10.html b/www/design/everett/serial_pres/pres6/text10.html new file mode 100644 index 000000000..dd0fda54b --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text10.html @@ -0,0 +1,27 @@ + + + + + + + java.io.DataOutput/Input + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      java.io.DataOutput/Input

                      +
                      • Java to IDL has clarified what many of the simple writes defined in java.io.DataOutput and java.io.DataInput do in RMI-IIOP. To maintain backwards compatibility with our older ORBs:

                      • +
                        • Look at orbutil/IIOPInputStream_1_3 and how I preserved readUTF's behavior. Basically, define a small method in the real io/IIOPInputStream to encapsulate what needs to change and override it.
                        • +
                        • Not very pretty ultimately, but currently what we have for this. Note that pure ORB issues leap out here, too.
                        • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text11.html b/www/design/everett/serial_pres/pres6/text11.html new file mode 100644 index 000000000..f6ecbe583 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text11.html @@ -0,0 +1,27 @@ + + + + + + + Tools + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Tools

                      +
                      • Remember that we have two neat tools in our workspace:

                      • +
                        • IOR dumping tool. See /net/anybodys/export2/iortool for a pre-built pre-configured copy. Just modify the Makefile and past in your IOR.
                        • +
                        • Class comparison tool. Can be used to compare our classes against the latest omg.zip file as well as compare our standard classes against a JDK's to make sure we haven't changed any public APIs.
                        • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text12.html b/www/design/everett/serial_pres/pres6/text12.html new file mode 100644 index 000000000..b7804bf10 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text12.html @@ -0,0 +1,29 @@ + + + + + + + corbalinux1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Corbalinux1

                      +
                      • We have a Linux machine!

                      • +
                      • Corbalinux1

                      • +
                      • User name: corba Password: rip-int

                      • +
                      • Sometimes needs rebooting. It lives in the server room across from our SCA 14 breakroom.

                      • +
                      • Should have its automounts working for anybodys. See local disk for JDKs or try /java.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text13.html b/www/design/everett/serial_pres/pres6/text13.html new file mode 100644 index 000000000..988afc2fa --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text13.html @@ -0,0 +1,29 @@ + + + + + + + Switching to java.nio + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Switching to java.nio

                      +
                      • Try this:

                      • +
                        • Make ByteBufferWithInfo closed, providing methods for get/setting bytes and index rather than direct array access.
                        • +
                        • When that works, try switching to java.nio.ByteBuffers. Will need to do some work to see if you want direct/indirect buffers, develop a cache since they're expensive to create, etc.
                        • +
                        • Experiment with replacing our marshaling code with that actually on the nio buffer. Performance gain?
                        • +
                        • Revamp CodeSetConversion to stop taking byte[]'s.
                        • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text14.html b/www/design/everett/serial_pres/pres6/text14.html new file mode 100644 index 000000000..5c719a1e2 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text14.html @@ -0,0 +1,28 @@ + + + + + + + Exceptions in the ValueHandler + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Exceptions in the ValueHandler

                      +
                      • Very hard to debug

                      • +
                      • Since ValueHandler methods don't throw ClassNotFoundException and IOException, we have native code to force these to be thrown even though they're not declared. There are no initCauses going on down there.

                      • +
                      • Logging may help

                      • +
                      • If debugging by hand, make sure to look at all output from your test (both sides) to get clues, not just the side you think is affected

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text15.html b/www/design/everett/serial_pres/pres6/text15.html new file mode 100644 index 000000000..01a0b21cd --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text15.html @@ -0,0 +1,25 @@ + + + + + + + Warning on IIOPInputStream/IIOPOutputStream + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Warning on io/IIOP streams

                      +
                      • Make sure to read/write to the ORB stream directly rather than calling java.io defined methods. If you do, you may trigger reactions from the state machines or corrupt variables unintentionally.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text16.html b/www/design/everett/serial_pres/pres6/text16.html new file mode 100644 index 000000000..c29c72eb7 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text16.html @@ -0,0 +1,27 @@ + + + + + + + JDK 1.3.0 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      JDK 1.3.0

                      +
                      • Currently listed as EOL'd on java.sun.com

                      • +
                      • We are really only able to support compatibility with at least JDK 1.3.1_01 and later. For all RMI-IIOP exceptions to work, make that 1.3.1_05.

                      • +
                      • 1.3.0 always wrote the calledDefaultWriteObject RMI-IIOP custom marshaling indicator as false, so may not interact well with the new stream states that actually consider this. (It was changed to always be true in 1.3.1, the more common case.)

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text17.html b/www/design/everett/serial_pres/pres6/text17.html new file mode 100644 index 000000000..9a1fbc3fd --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text17.html @@ -0,0 +1,24 @@ + + + + + + + Exceptions + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Exceptions Bugs in RMI-IIOP

                      + + diff --git a/www/design/everett/serial_pres/pres6/text18.html b/www/design/everett/serial_pres/pres6/text18.html new file mode 100644 index 000000000..49fa7b302 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text18.html @@ -0,0 +1,26 @@ + + + + + + + javax.rmi.CORBA.Stub + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      javax.rmi.CORBA.Stub Bug

                      +
                      • Hitachi has escalated the javax.rmi.CORBA.Stub cross JDK incompatibility bug. CTE is in the process of fixing it in J2SE 1.4.0_xx. I haven't heard if they're going to let it into Hopper, but I doubt it, so CTE will handle it in a Hopper update release.

                      • +
                      • Someone needs to put this change into rip-int, too. (Adding the serialVersionUID to the class, see the bug report)

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text19.html b/www/design/everett/serial_pres/pres6/text19.html new file mode 100644 index 000000000..8faf056a8 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text19.html @@ -0,0 +1,27 @@ + + + + + + + CDR Stream Rewrite + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      CDR Stream Rewrite

                      +
                      • Move valuetype handling code out as a separate component.

                      • +
                      • Use states to implement chunking so the chunking code isn't active when you're not.

                      • +
                      • Stop using instance variables to maintain state across method calls where possible due to issues with variable corruption during recursion.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text2.html b/www/design/everett/serial_pres/pres6/text2.html new file mode 100644 index 000000000..f7162dcfc --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text2.html @@ -0,0 +1,24 @@ + + + + + + + Input Stream Diagram 1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Stream Diagram 1

                      + + diff --git a/www/design/everett/serial_pres/pres6/text20.html b/www/design/everett/serial_pres/pres6/text20.html new file mode 100644 index 000000000..da065b074 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text20.html @@ -0,0 +1,25 @@ + + + + + + + Simon + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Simon

                      +
                      • Simon suspects that places like io/ValueUtility getSignature should have many more TCKinds listed. This was one of the problems with exception compatibility across JDKs. In my fixes, I added value_box. See the REVISITs. If other TypeCode rewriting is to be done, ask him about what other things should be there.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text21.html b/www/design/everett/serial_pres/pres6/text21.html new file mode 100644 index 000000000..57663ff45 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text21.html @@ -0,0 +1,27 @@ + + + + + + + corba.strm2 tests + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      corba.strm2 tests

                      +
                      • New tests for complex evolutionary cases never tested before. Exercises stream format version 2 and the states especially.

                      • +
                      • Subdirectory class0 through class7. Class5 through class7 aren't active yet since there are still bugs. Class5 through class7 may also be illegal ??? sent mail to Bob Scheifler yesterday to confirm validity. Watch for answer.

                      • +
                      • Compiling could be done in Makefile if someone can figure out how.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text22.html b/www/design/everett/serial_pres/pres6/text22.html new file mode 100644 index 000000000..f1be87287 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text22.html @@ -0,0 +1,24 @@ + + + + + + + Class evolution in corba.strm2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Class evolution in corba.strm2

                      + + diff --git a/www/design/everett/serial_pres/pres6/text23.html b/www/design/everett/serial_pres/pres6/text23.html new file mode 100644 index 000000000..8612eddf0 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text23.html @@ -0,0 +1,27 @@ + + + + + + + Why class4 & class5 are incompatible + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Why class4 and class5 incompat?

                      +
                      • When class5's TestObjectSuper tries to read its extra optional data, it is at a point in the stream in which blockLength is already maxBlockLength and it's right at the beginning of an end tag.

                      • +
                      • Since blockLength is maxBlockLength (what start_block uses to prevent recursive calls from alignAndCheck and checkBlockLength as well as when the next thing is a valuetag or end tag), our code never checks for an end tag in checkBlockLength We ultimately get a MARSHAL exception.

                      • +
                      • Tried many ways around this, but ultimately it was too complicated and didn't work in all cases. These tests will generally show you pretty quickly if your changes help.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text3.html b/www/design/everett/serial_pres/pres6/text3.html new file mode 100644 index 000000000..d3fc7029d --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text3.html @@ -0,0 +1,24 @@ + + + + + + + Input Stream Diagram 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Input Stream Diagram 2

                      + + diff --git a/www/design/everett/serial_pres/pres6/text4.html b/www/design/everett/serial_pres/pres6/text4.html new file mode 100644 index 000000000..2c39a74dc --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text4.html @@ -0,0 +1,24 @@ + + + + + + + Code overview 1 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Code overview

                      + + diff --git a/www/design/everett/serial_pres/pres6/text5.html b/www/design/everett/serial_pres/pres6/text5.html new file mode 100644 index 000000000..639ee1cf4 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text5.html @@ -0,0 +1,24 @@ + + + + + + + Code overview 2 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Code overview 2

                      + + diff --git a/www/design/everett/serial_pres/pres6/text6.html b/www/design/everett/serial_pres/pres6/text6.html new file mode 100644 index 000000000..6bf2d3fc0 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text6.html @@ -0,0 +1,24 @@ + + + + + + + Code overview 3 + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Code overview 3

                      + + diff --git a/www/design/everett/serial_pres/pres6/text7.html b/www/design/everett/serial_pres/pres6/text7.html new file mode 100644 index 000000000..00cd56968 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text7.html @@ -0,0 +1,26 @@ + + + + + + + Rep Id Rewrite + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Repository ID Rewrite

                      +
                      • Switch to a single repository ID cache with a double cache lookup based on ORB version.

                      • +
                      • Get away from static methods.

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text8.html b/www/design/everett/serial_pres/pres6/text8.html new file mode 100644 index 000000000..7018b9dd5 --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text8.html @@ -0,0 +1,27 @@ + + + + + + + IO Prototype + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      IO Prototype

                      +
                      • I once did a prototype of what could happen if the java.io group developed a relatively easy to extend template method system for going through the serialization protocol, separating the writing from the process.

                      • +
                      • This will now live in rip-int temporarily in docs/eea1/ioprototype.

                      • +
                      • While java.io agreed it would be nice, it would hurt their performance and they have no resources (Mike Warres is the only one who could do this work, and he's too busy.)

                      • +
                      + diff --git a/www/design/everett/serial_pres/pres6/text9.html b/www/design/everett/serial_pres/pres6/text9.html new file mode 100644 index 000000000..7a515d56c --- /dev/null +++ b/www/design/everett/serial_pres/pres6/text9.html @@ -0,0 +1,26 @@ + + + + + + + Uncache Fix + + +
                      +First page Back Continue Last page Overview Graphics

                      +

                      Uncache Fix

                      +
                      • Bob Scheiffler filed two very difficult bugs, one which seemed to require the removal of the stub to tie cache in util/Utility. See docs/eea1/uncache for the changes I made to a Merlin workspace on this.

                      • +
                      • It didn't slow down the 1.3 RI on the modified Merlin build during EC Perf.

                      • +
                      + diff --git a/www/design/general_exception.html b/www/design/general_exception.html new file mode 100644 index 000000000..a09e85621 --- /dev/null +++ b/www/design/general_exception.html @@ -0,0 +1,113 @@ + + + + + + + General Exception Handling + + + + +

                      General Exception Handling

                      +
                      + +

                      + Last Modified: May 23, 2004 +

                      +

                      + Version: 1.6

                      + +
                      + <Ken Cavanaugh> +
                      + +

                      + The PEORB already has extensive exception handling code for CORBA system exceptions. + The mechanism starts with a descriptive .mc file, with data stored in S-expressions. + This takes the following form: +

                      +
                      +("packagename" "classname" group
                      +    (
                      +        (EXCEPTIONCLASS
                      +            (EXCEPTION_NAME ID LEVEL "meaning with {n] args")
                      +            ...
                      +        )
                      +        ...
                      +    )
                      +)
                      +
                      +

                      Here the packagename is the Java package in which the classname is generated. +The group is used to group CORBA system exception into different groups. +This is followed by a list of exception classes (given by just the major exception +type in the CORBA system exceptionc case). Each exception class in turn +lists the EXCEPTION_NAME which is used as a constant for the minor code, and +also as exceptionName for the name of the method used to create and log the +exception. The ID is used to create a unique log record ID for this log +record. The meaning string provides a way to parameterize the string that describes +the log entry in the logger. +

                      +

                      +The basic idea here is to generate a Java class for each such file that contains methods +for each EXCEPTION_NAME entry called exceptionName. Each exceptionName method +does two things: first, it logs all details about the exception, then it creates +an instance of the exception and returns it. The caller may then throw the exception, +store for later use, or ignore it as needed. +

                      +

                      We can use almost the same structure to handle arbitrary exceptions. +Here is a slight variation: +

                      +("packagename" "classname" group
                      +    (
                      +        (ExceptionClass
                      +            (exceptionName ID LEVEL "meaning with {n] args")
                      +            ...
                      +        )
                      +        ...
                      +    )
                      +)
                      +
                      +

                      +We should make some simplifying assumptions to handle this case. +

                        +
                      1. group is used directly as the beginning of the log record ID string. +
                      2. ExceptionClass is the fully qualified name of an exception. +
                      3. Only one group per file +
                      4. All entries for a single group must appear in the same file. +
                      +What we will do is generate two methods for every public constructor in the +ExceptionClass. One method has all the arguments passed on the +constructor, the other starts with a chained exception, and then is +followed by the arguments passed in the constructor. +

                      +

                      +We also need to handle message strings that contain + + +Cases: + +FooException( String reason ) + +BarException( int data, Object more ) + +BarException( String reason, int data, Object more ) + +- If first param is a string, it is a reason string +- All additional constructor args are {1}, ... {n} +- If message string contains {m}, m>n, then additional string args are + supplied in the methods +- reason string is set to the formatted message + + + diff --git a/www/design/monitoring.html b/www/design/monitoring.html new file mode 100644 index 000000000..8e822a381 --- /dev/null +++ b/www/design/monitoring.html @@ -0,0 +1,390 @@ + + + + + + + monitoring + + + + + + +

                      ORB Monitoring Extensions for AS 8.2

                      +

                      It has become apparent that some changes are needed in the ORB + monitoring framework for AS 8.2. The current monitoring code in the ORB is + overly long and difficult to construct. We also need to consider upcoming + requirements in AS 8.2 in areas such as dynamic configuration changes and + self-tuning. I would like to build a dynamic MBean directly in the ORB so that + we can more readily experiment with different maangement tools, and also to + fully validate the ORB monitoring framework design.

                      +

                      Note: this is basically obsolete, given the new JMX utilities

                      +

                      Simplifying the Usage of ORB Monitoring

                      +

                      Currently the ORB monitoring code is rather long. For example, here is + the code in CorbaInboundConnectionCacheImpl:

                      +
                          protected void registerWithMonitoring()
                      +    {
                      +        // ORB
                      +        MonitoredObject orbMO = 
                      +            orb.getMonitoringManager().getRootMonitoredObject();
                      +
                      +        // REVISIT - add ORBUtil mkdir -p like operation for this.
                      +
                      +        // CONNECTION
                      +        MonitoredObject connectionMO = 
                      +            orbMO.getChild(MonitoringConstants.CONNECTION_MONITORING_ROOT);
                      +        if (connectionMO == null) {
                      +            connectionMO = 
                      +                MonitoringFactories.getMonitoredObjectFactory()
                      +                    .createMonitoredObject(
                      +                        MonitoringConstants.CONNECTION_MONITORING_ROOT,
                      +                        MonitoringConstants.CONNECTION_MONITORING_ROOT_DESCRIPTION);
                      +            orbMO.addChild(connectionMO);
                      +        }
                      +
                      +        // INBOUND CONNECTION
                      +        MonitoredObject inboundConnectionMO = 
                      +            connectionMO.getChild(
                      +                MonitoringConstants.INBOUND_CONNECTION_MONITORING_ROOT);
                      +        if (inboundConnectionMO == null) {
                      +            inboundConnectionMO =
                      +                MonitoringFactories.getMonitoredObjectFactory()
                      +                    .createMonitoredObject(
                      +                        MonitoringConstants.INBOUND_CONNECTION_MONITORING_ROOT,
                      +                        MonitoringConstants.INBOUND_CONNECTION_MONITORING_ROOT_DESCRIPTION);
                      +            connectionMO.addChild(inboundConnectionMO);
                      +        }
                      +
                      +        // NODE FOR THIS CACHE
                      +        MonitoredObject thisMO = 
                      +            inboundConnectionMO.getChild(getMonitoringName());
                      +        if (thisMO == null) {
                      +            thisMO =
                      +                MonitoringFactories.getMonitoredObjectFactory()
                      +                    .createMonitoredObject(
                      +                        getMonitoringName(),
                      +                        MonitoringConstants.CONNECTION_MONITORING_DESCRIPTION);
                      +            inboundConnectionMO.addChild(thisMO);
                      +        }
                      +
                      +        LongMonitoredAttributeBase attribute;
                      +
                      +        // ATTRIBUTE
                      +        attribute = new 
                      +            LongMonitoredAttributeBase(
                      +                MonitoringConstants.CONNECTION_TOTAL_NUMBER_OF_CONNECTIONS, 
                      +                MonitoringConstants.CONNECTION_TOTAL_NUMBER_OF_CONNECTIONS_DESCRIPTION)
                      +            {
                      +                public Object getValue() {
                      +                    return new Long(CorbaInboundConnectionCacheImpl.this.numberOfConnections());
                      +                }
                      +            };
                      +        thisMO.addAttribute(attribute);
                      +
                      +        // ATTRIBUTE
                      +        attribute = new 
                      +            LongMonitoredAttributeBase(
                      +                MonitoringConstants.CONNECTION_NUMBER_OF_IDLE_CONNECTIONS, 
                      +                MonitoringConstants.CONNECTION_NUMBER_OF_IDLE_CONNECTIONS_DESCRIPTION)
                      +            {
                      +                public Object getValue() {
                      +                    return new Long(CorbaInboundConnectionCacheImpl.this.numberOfIdleConnections());
                      +                }
                      +            };
                      +        thisMO.addAttribute(attribute);
                      +
                      +        // ATTRIBUTE
                      +        attribute = new 
                      +            LongMonitoredAttributeBase(
                      +                MonitoringConstants.CONNECTION_NUMBER_OF_BUSY_CONNECTIONS, 
                      +                MonitoringConstants.CONNECTION_NUMBER_OF_BUSY_CONNECTIONS_DESCRIPTION)
                      +            {
                      +                public Object getValue() {
                      +                    return new Long(CorbaInboundConnectionCacheImpl.this.numberOfBusyConnections());
                      +                }
                      +            };
                      +        thisMO.addAttribute(attribute);
                      +    }
                      +

                      Fully formatted, this is 82 lines of source. Here are some thoughts on + simplifying assumptions:

                      +
                        +
                      1. +

                        (BIG assumption): Use a Dynamic MBean constructed by introspection + on the MonitoredXXX objects reachable from the Root MonitoredObject in the ORB. + This eliminates the need for MonitoringConstants, and consequently simplifies + the declarations.

                        +

                        There is a problem with this: the app + server currently has a surprisingly complicated way of getting from ORB + MonitoredObject (which is dynamic) to a Dynamic MBean by going through a static + Stats layer (ugh). We could simply keep the necessary constants for the AS in + MonitoringConstants, but I would rather get rid of them.

                      2. +
                      3. +

                        Any reasonable name (let's say a Java + identifier) is legal for MonitoredObjects.

                      4. +
                      5. +

                        MonitoredAttribute names must start with + a capital letter and be Java identifiers (SomethingLikeThis).

                      6. +
                      7. +

                        All descriptions for MonitoredObjects and + MonitoredAttributes are stored in a resource file (Can we make this dynamic if + necessary?)

                      8. +
                      9. +

                        The key in the resource file for object + or attribute "XXX" is "XXX.description".

                      10. +
                      11. +

                        The MonitoredAttribute SomethingLikeThis + is implemented by a method named somethingLikeThis. RO means only a getter + (TYPE somethingLikeThis()) while a RW attribute has a setter as well (void + somethingLikeThis(TYPE)).

                      12. +
                      13. +

                        The TYPE of an attribute is determined + from the getter/setter methods.

                      14. +
                      15. +

                        We provide a utility class MUtil in spi.monitoring.

                      16. +
                      +

                      With these assumptions, we could get the example above down to:

                      +
                      protected void registerWithMonitoring()
                      +{
                      +    MonitoredObject thisMO = MUtil.get( orb, "/Connections/Inbound/" + getMonitoringName() ) ;
                      +    thisMO.addAttribute( "NumberOfConnections", this ) ;
                      +    thisMO.addAttribute( "NumberOfIdleConnections", this ) ;
                      +    thisMO.addAttribute( "NumberOfBusyConnections", this ) ;
                      +}
                      +

                      That's it! Just 4 lines of code.

                      +

                      Here the get method get or creates the MonitoredObjects as needed (as + Harold noted, a "mkdir -p" like operation). addAttribute uses all of the + assumptions mentioned above to derive the appropriate information.

                      +

                      MonitoredObjects for JavaBeans

                      +

                      A further extension to this is possible. Consider the case of ORBData. + ORBData has a lot of methods that look like:

                      +
                           (some data type) getXXXX() ;
                      +

                      This is the standard pattern for a JavaBean accessor method for a + property named "XXXX". In addition, we have methods like:

                      +
                          boolean isJavaSerializationEnabled() ;
                      +
                      +    boolean showInfoMessages() ;
                      +

                      A method name that returns a boolean and starts with "is" is a JavaBean + accessor method. Unfortunately ORBData has a lot of boolean methods that do not + start with "is", so we cannot directly use the JavaBean Introspector. However, + the job is simple enough that that is not necessary. Alternatively we could + pull all of the information out of the ParserTable class. In any case, the idea + is to create a MonitoredObject for ORBData that reflects all of the + configuration data for the ORB. We will discuss why this is useful a bit later. +

                      +

                      Some ORB Monitoring Problems

                      +

                      Currently there are two different ways of getting information the root + monitored object: either we call

                      +
                      MonitoringFactories.getMonitoringManagerFactory().createMonitoringManager(
                      +  (root name), description ).getRootMonitoredObject()
                      +

                      or we call

                      +
                      orb.getMonitoringManager().getRootMonitoredObject()
                      +

                      Having two different ways of getting information is a frequent source + of problems. These two mechanisms agree when the (root name) is the same as the + corresponding value in the ORB, but that is currently not the case, due to the + change I made to make sure that the monitoring code does not get overwritten by + multiple ORBs. Hosever, the createMonitoringManager call will create a new + MonitoringManager and root MonitoredObject whenever it is called. Currently I + see two difference MonitoringManager objects in the app server: one with root + named "orb", and one with root named "orb_S1AS-ORB_1", which comes from the app + server's standard ORB id and the change I made in ORB b42 to fix bug 4919770. +

                      +

                      Another problem occurs here because the ThreadPool always uses the first + form to get to the root MonitoredObject, which is indepedent of the ORB. This + means that all ThreadPools, no matter how they are created or where they are + used, will be associated with the root MonitoredObject that corresponds to the + first ORB created with ORB id "". This means that the threadpool monitoring + will work regardless of the ORB id in the current app server. I still cannot + reproduce Sheetal's bug, but it seems unlikely to be a significant problem. +

                      +

                      On the other hand, the connection monitoring goes straight to the ORB to + get the root monitored object. Some suggestions for 8.2:

                      +
                        +
                      1. +

                        There should be only one possible root + MonitoredObject, and a single MonitoringManager. The ORB should create its + monitoring root under this top-level (probably unnamed) root object, using the + current naming convention.

                      2. +
                      3. +

                        The ThreadPool should continue to be ORB + independent, as it can be used anywhere. However, the threadpool really should + not both be independent of the ORB and have its monitoring registered under the + ORB. Instead, we should register the threadpool under its own root, independent + of the ORB.

                      4. +
                      5. +

                        We only need one MonitoringManager, which simply provides access to + / in the monitoring hierarchy.

                      6. +
                      +

                      Current hierarchy (multiple named roots):

                      +
                      orb
                      +        threadpool
                      +        Connections
                      +                Inbound
                      +                Outbound
                      +orb_XXX_1
                      +orb_XXX_2
                      +etc
                      +

                      New hierarchy (this requires app server changes):

                      +
                      (root)
                      +        threadpoolroot
                      +                threadpool_1
                      +                threadpool_2
                      +                (etc. if we create multiple ThreadPoolManagers)
                      +        orbroot
                      +                orb_XXX_1
                      +                        Connections
                      +                                Inbound
                      +                                Outbound
                      +                        (plus more TBD as we work on 8.2 and 9)
                      +                orb_XXX_2
                      +                orb_YYY_1
                      +

                      Note that the old hierarchy is confusing when there are multiple ORBs. + There is no confusion in the new hierarchy. For example,

                      +
                      orb.getMonitoringManager().getRootMonitoredObject() 
                      +

                      should just return the ORB's root, which is:

                      +
                      /orbroot/orb_XXX_n
                      +

                      MonitoringFactories.getRootMonitoredObject should just return / (and + this replaces the current MonitoringManagerFactory.createMonitoringManager + call).

                      +

                      Adding Notifications to ORB Monitoring

                      +

                      Given the possibility of changing MonitoredAttribute values, it becomes + necessary to consider how the ORB can find out about changes. For this, we need + to extend the ORB monitoring framework with events and event listeners.

                      +

                      Model:

                      +
                        +
                      1. +

                        An attribute set method is called.

                      2. +
                      3. +

                        The attribute examines the registered listeners and invokes the + attributeChanged method on each listener, giving the listener the + MonitoredObject, the MonitoredAttribute, and the old and new values of the + attribute.

                      4. +
                      5. +

                        Control returns from the attribute set method.

                      6. +
                      +

                      The other case we need to consider is creating and destroying + MonitoredObjects. Here we want to receive either an ObjectCreated or an + ObjectDestroyed notification on the parent MonitoredObject of the + MonitoredObject that was created or removed. Here the notification just needs + the parent and child MonitoredObjects.

                      +

                      A listener needs to implement the following interfaces as needed:

                      +
                      interface AttributeListener {
                      +    void attributeChanged( MonitoredObject object, MonitoredAttribute attribute, Object oldValue,
                      +        Object newValue ) ;
                      +}
                      +
                      +interface ObjectListener {
                      +    void objectCreated( MonitoredObject parent, MonitoredObject child ) ;
                      +    void objectRemoved( MonitoredObject parent, MonitoredObject child ) ;
                      +} ;
                      +
                      +

                      MonitoredObject needs new methods to handle the registration of + listeners. I think it may also be useful to have a scope associated with the + registration, so that a listener can be registered either for events from one + MonitoredObject, from the immediate descendants of a MonitoredObject, or from + all descendants of a MonitoredObject. Since we are still using J2SE 1.4, we + will map these scope values to integer constants. Then we need to add the + following methods to MonitoredObject:

                      +
                      interface MonitoredObject {
                      +    ...
                      +    void registerAttributeListener( AttributeListener listener, int scope ) ;
                      +
                      +    AttributeListener[]  attributeListeners() ;
                      +
                      +    void removeAttributeListener( AttributeListener listener ) ;
                      +
                      +    void registerObjectListener( ObjectListener listener, int scope ) ;
                      +
                      +    ObjectListener[] objectListeners() ;
                      +
                      +    void removeObjectListener( ObjectListener listener ) ;
                      +}
                      +
                      +
                      +

                      An Architecture for Dynamic Configuration

                      +

                      The basic idea here is simple: provide attribute change notification + events and configurations agends that listen for these events. But how exactly + does this work?

                      +

                      First, I think we do not need the complex model that JavaBeans use, + where some events can be vetoed. We still need to decide what the notification + model should be, what events we support, and how those events get translated + into Mbean notifications.

                      +

                      ORB dynamic MBean Support

                      +

                      The ORB will probably need to be configurable in where it obtains an + MBean server. On J2SE, the ORB should use + java.lang.management.ManagementFactory.getPlatformMBeanServer. What to do in + J2EE is still TBD.

                      +

                      What we need to define here is how to map the ORB + MonitoredObject/MonitoredAttribute framework into MBeans using the JMX + framework. There are some significant differences in approaches taken in the + two framworks. The JMX approach is more complex, with more features including + such items as relations. The ORB Monitoring Framework only supports a single + hierarchy, which is built in to the definition of the MonitoredObject. The + genesis of the ORB framework is for monitoring (mostly) performance-related + attributes of the system, while JMX is intended to be a fully general + management and monitoring framework.

                      +

                      Part of the intent here is to grow the ORB framework to be more general, + so that it can also support ORB management. Primarily this comes about through + the addition of notifications. So far I have seen little need to add actions, + but that is also easily possible.

                      +

                      There are several problems to solve here:

                      +
                        +
                      1. For each MonitoredObject, there is a dynamic MBean whose attributes + correspond to the MonitoredAttributes of the Monitored Object.
                      2. +
                      3. The name of the MBean is derived from the nesting of the + MonitoredObjects starting at the root.
                      4. +
                      5. There is an object in the MBean pacakge that listens for + MonitoredObject events (registered against the root, scoped for all + descendants). This handles events as follows: +
                          +
                        1. For an attributedChanged event, the attribute on the + corresponding MBean is updated.
                        2. +
                        3. For an objectCreated event, an MBean corresponding to the + MonitoredObject is created and registered with the MBean server.
                        4. +
                        5. For an objectDestroyed evend, the MBean corresponding to the + destroyed MonitoredObject is de-registered from the MBean server.
                        6. +
                      6. +
                      +

                      Dynamic Tracing in Java Applications

                      +

                      Solaris 10 has recently introduced the dtrace facility, which provides + extremely useful tools for dignosing and tuning the Solaris OS and C/C++ + applications. What about Java? Here I am not just interested in things like the + Java stack. Instead, I want to consider extremely large and complex apps like + the app server, which has many interacting modules, each of which has its own + unique requirements for monitoring. As monitoring is a big push for AS 8.2 and + 9, it seems that we should seriously consider what we need to do here.

                      +

                      In fact, there is a project to do exactly this: it's called jtrace, which is work being done in Janet + Koenig's group with Sanjay Radia and A. Sundar. More information is available + in jplan, and it is currently + scheduled for Dolphin (J2SE 7). Unfortunately this work is a very long way (3+ + years for J2SE, probably >4 for J2EE) out.

                      +

                      I wonder if we could do something sooner? There are several + possibilities:

                      +
                        +
                      1. Add instrumentation at the ORB SPI level. This is a very specific + case, and somewhat labor-intensive to add. The big question still remains about + what to do for the data collection language: DTrace's D is quite nice and + fairly large.
                      2. +
                      3. Similar to 1, but add the instrumentation at the Container level (in + the component-based development sense; see components for a draft of these ideas).
                      4. +
                      5. Combine several ideas: java.lang.Instrument in J2SE 5.0, byte-code + instrumentation using ASM or BCEL, remote communications (perhaps using + CORBA?), and the current Dtrace to create more-or-less what is needed. The key + piece here is implementing a custom provider for DTrace (for which there is no + information at present).
                      6. +
                      7. It might be nice to be able to use MBeans as well with a tracing tool + of some sort.
                      8. +
                      + diff --git a/www/design/orb_notes.html b/www/design/orb_notes.html new file mode 100644 index 000000000..490d00535 --- /dev/null +++ b/www/design/orb_notes.html @@ -0,0 +1,2080 @@ + + + + + + + + + + + + + + + + + + + + +
                      + + +
                      Abstract: +Comprehensive documentation on the Sun Java ORB. + +

                      Contents

                      + + + +
                      + + +

                      Chapter 1  Starting Points

                      + + + +

                      1.1  Changes for the GlassFish-CORBA project

                      + +This document originally described CORAB development internally in +Sun's TeamWare environment. We have since switched to using Mercurial, +both internally and externally. The glassfish-corba project still +uses CVS, but only to maintain easy access to the documents.
                      +
                      +Some of the policies and procedures described here will be changed +as we continue moving all of our work to the open internet glassfish-corba +project.
                      +
                      + + +

                      1.2  ORB Development procedures

                      + +Over the years, we have established a fairly successful development +methodology for working on the ORB. Any piece of work from a minor +bugfix to a major new subsystem iterates over the same stages one +or more times. I'll discuss this briefly here, but the details will +appear below. +
                      1. +Discuss or document the design. This can take many forms, ranging +from an informal discussion to a written document. Written documents +have in the past been done in many different formats, including email, +text files, FrameMaker documents, StarOffice documents, HTML, XML +and DocBook, and LATEX (about the only thing none of us have used +seems to be Word!). Going forward, all of these are still viable in +different ways, but I'd really like to make sure that we capture all +of the design efforts into our documentation collection. All current +documentation is found in the CORBA workspace in the www directory, +and all future documentation should either be there, or in the actual +source code. +
                      2. Develop the code. This include writing both the code to implement +the change and the code to test it. Bugs need a test that fails before +the change is made, and that passes after the change. All tests must +be incorporated somewhere in the CORBA test suites (see sub:Test-Suites) +so that they can be run automatically. Test execution speed is important, +so make the test as fast as possible. Please follow the principles +discussed in sec:Thoughts-on-Middleware and in sec:ORB-Coding-Practices. +
                      3. Verify that nothing has been broken by the change. This requires running +all of the CORBA test suites, and fixing any problems that show up +(see sub:debugging-tests for help on debugging tests). +
                      4. Prepare a webrev for a code review. The webrev tool is available on +SWAN (Sun's internal network) in /java/devtools/share/bin. Read the +comments in this kshell script for details. (TBD: where is webrev +outside of Sun?). Webrevs have the advantage that they can be archived +standalone, and this is probably a good thing to do. Another viable +option is to use a tool like meld (see meld ) +that can do directory diffs. +
                      5. Have at least 1 (and preferably more) developer from the GlassFish-CORBA +team review the changes. Make any necessary corrections from the review, +and re-review if necessary.
                        +
                        +TBD: Currently we conduct all code reviews in real time, usually via +phone conference (since this has been a distributed team for a long +time). We need to investigate this in the open source world, and find +a more scalable method that works asynchronously. Something like Google's +Mondrian would be a good choice, if it were available.
                      + + +

                      1.3  Workspace Structure and Builds

                      + +The workspace is divided into a number of directories. The current +structure will change somewhat after I finish work on another putback +that restructures the workspace to simplify its organization and remove +obsolete junk.
                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      Directory
                      Purpose
                      build
                      created during build process
                      build/classes
                      compiled classes
                      build/gensrc
                      Java source code generated by build
                      build/lib
                      miscellaneous idl files for the interface repository
                      build/release/libJar files that are the build results: +
                      • +idlj.jar: the IDL compiler +
                      • omgapi.jar: the OMG API classes that are NOT part of JDK 5 or 6 +
                      • orblib.jar: the ORB library files from the orblib directory +
                      • peorb.jar: the main ORB files +
                      build/rename/ee
                      Where the ant rename target puts a copy of the workspace
                      lib
                      various jar files needed to build and test the ORB: +
                      • +emma (for code coverage) +
                      • ejb 2.1 APIs (for a codegen test) +
                      • japex (to compile against for StandardTest) +
                      • jscheme (used for generating log wrappers) +
                      • junit and testng (for testing) +
                      make
                      contains ant build files
                      nbproject
                      contains NetBeans support to treat workspace as a NetBeans project
                      orblib
                      Standalone ORB library source files (delivered to orblib.jar)
                      src
                      main ORB source code (delivered to peorb.jar)
                      test
                      ORB test source (and orblibrary as well at present)
                      tools
                      IOR parser

                      + + +

                      1.3.1  docs

                      + +There are quite a few files here. This will eventually include all +of the useful files from /java/j2ee/CORBA. Most of the doc files in +the current workspace are useless, with one important exception: the +eea1 directory. These are Everett Anderson's notes on the design and +implementation of the GIOP layer, and are still quite useful. This +also documents the RMI-IIOP stream format version 2 implementation.
                      +
                      + + +

                      1.3.2  ORB source

                      + +Generally, most ORB implementation source packages have two parts: +an interface defined in an spi package, and an implementation in an +impl package. We will generally discuss these together.
                      +
                      +The ORB source code is divided into several parts: +
                      +src/solaris
                      Useless and should be removed. +
                      src/share/classes
                      This contains the main part of the source code. +It can be further divided into: +
                      +org
                      OMG standard CORBA APIs +
                      javax
                      OMG standard RMI-IIOP APIs +
                      sun/rmi
                      rmic compiler +
                      sun/corba
                      CORBA Bridge class, which isolates ORB dependencies on +non-public JDK APIs +
                      com/sun/corba/ee
                      Main body of ORB source code (automatically renamed +to ee package for app server build) +
                      +GiopIDL
                      IDL files for GIOP protocol definitions +
                      PortableActivationIDL
                      Old ideas for ORBD rewrite; to be removed +
                      experimental/portableactivation
                      Part of ORBD rewrite; to be removed +
                      impl/spi
                      The main part of the ORB implementation +
                      +activation
                      ORBD +
                      copyobject
                      Object copier code with special hooks for CORBA +
                      corba(impl)
                      Implementation of OMG CORBA APIs (but not org.omg.CORBA.ORB) +
                      dynamicany
                      Dynamic Any support +
                      encoding
                      Input and output streams for CDR and JSG (Java Serialization +for GIOP). PEPt encoding level code. +
                      extension(spi)
                      Some AS-specific CORBA policies used by EJB for creating +POAs. +
                      folb
                      Code for support IIOP failover and load balancing in GlassFish +v2 +
                      interceptors(impl)
                      Portable Interceptor implementation +
                      io(impl)
                      Code to analyze classes and implement streams for GIOP. +This is the valuehandler implementation, which can be used by other +ORBs. +
                      ior
                      How we represent IORs +
                      javax(impl)
                      RMI-IIOP implementation +
                      legacy
                      Some AS-specific extensions to interceptors and some connection +management support +
                      logging
                      Logging infrastructure used by generated log wrappers +
                      monitoring
                      ORB monitoring framework +
                      naming
                      CosNaming service implementations +
                      oa
                      Object Adapters. This includes: +
                      +poa(impl)
                      The Portable Object Adapter implementation +
                      toa(impl)
                      Simple OA used for orb.connect/disconnect (JDK 1.2) and +old RMI-IIOP support +
                      rfm
                      The ReferenceFactoryManager, used to enable suspend/resume of +ORB processing for dynamic reconfiguration. Used to support dynamic +FOLB in AS9. +
                      *.java
                      The OA SPI. +
                      +
                      orb
                      The implementation of the ORB class, and associated configuration +framework. The configuration code should really be moved into a utility +library. +
                      orbutil
                      (impl) Utilities not related to RMI-IIOP. This includes +JDK 1.3.1 backwards compatibility support, the threadpool, and a few +other miscellaneous utilities, and ORBConstants. ORBConstants is very +commonly used in the ORB and App server and should be moved to an +SPI package. +
                      presentation
                      PEPt presentation level code for dynamic RMI-IIOP +
                      plugin(impl only)
                      ORB Hardware loadbalancing support +
                      protocol
                      PEPt protocol level code +
                      resolver
                      Internal classes used to support string to object reference +conversion +
                      servicecontext
                      Internal representation of GIOP ServiceContexts. +
                      transport
                      PEPt transport level code +
                      txpoa
                      TSIdentificationImpl, which is used to connect the ORB and +the transaction service. +
                      util
                      low-level code mostly related to RMI-IIOP. +
                      +
                      internal
                      Old (JDK 1.4 and earlier) ORB and JNI library related classes +that we maintain for backward compatibility. +
                      org/omg
                      Various mostly CSIv2 related protocol definitions (we compile +the CSIv2 IDL in the ORB so that the app server CSIv2 implementation +can use it). +
                      pept
                      The PEPt 1.0 code used in the ORB. +
                      +
                      com/sun/org/omg
                      Some not quite standard OMG classes that were still +in flux in the CORBA 2.4.1 timeframe (these are internal only, so +this doesn't matter much now) +
                      com/sun/tools/corba/se
                      A number of tools: +
                      +idl
                      The idl compiler +
                      jmk
                      The tool used to validate .jmk files against the contents of +the source directories +
                      logutil
                      The source code for the jschemeutil.jar library +
                      timer
                      XML data for generating timing points +
                      +
                      +
                      orblib/src/share/classes/com/sun/corba/ee
                      Classes in the ORB library. +There are no dependencies from any of this code to classes in the +src hierarchy. +
                      +org
                      Contains the ASM code used in the ORB for dynamic class generation. +
                      impl/orbutil and spi/orbutil
                      Contains a number of modules: +
                      +argparser(spi only)
                      A general purpose annotation-driven CLI argument +parser. +
                      closure
                      Simple closure support used in a few placescodegen The runtime +byte code generator library. +
                      codegen
                      A general-purpose runtime code generation library. +
                      concurrent
                      Some concurrent queue implementations needed in the new +connection cache. +
                      copyobject
                      A fast general-purpose object copier. +
                      file(spi only)
                      A collection of text file utilities used for copyright +header processing and workspace renaming. +
                      fsm(spi only)
                      Finite State Machine library used in the POA to support +ActiveObjectMap entry semantics. Should be more widely used in ORB +(e.g. connection management). Supports much of the UML state model +(but not nested states, and not petri-net style operations) +
                      generic(spi_only)
                      Some useful utilities related to Java 5 generic +(generic Pair, various kinds of generic function classes) +
                      graph(impl only)
                      Some simple graph utilities for computing transitive +closure. Should probably be heavily revised. +
                      jmx
                      A new framework for using annotation to generate open MBeans +
                      misc(spi only)
                      odds and ends that don't fit elsewhere +
                      newtimer
                      A general-purpose timer framework used to capture BEGIN/END +pairs of events. +
                      proxy(spi only)
                      Utilities related to simplify construction of InvocationHandlers +for java.lang.reflect.Proxy. +
                      timer(impl only)
                      An old, deprecated timer framework. +
                      transport
                      The new connection cache implementation (not yet integrated +in the ORB). A nearly identical version of this code is in Grizzly, +and the ORB will eventually use the Grizzly copy. +
                      threadpool
                      The ORB threadpool implementation that is shared with +the app server (should revisit this in light of JDK 5 executors). +
                      +
                      +
                      + + +

                      1.3.3  ORB Renaming

                      + +Most of the ORB is packaged under the com.sun.corba.ee package. A +version of the ORB code exists in this package (or in a slightly different +version) in every JDK since 1.2. We also deliver the ORB code to the +Sun application server (now project GlassFish). To avoid possibly +collisions between the classes in the JDK and the classes in GlassFish, +we rename all the files in the ORB to the com.sun.corba.ee package.
                      +
                      +This rename is done automatically using a Java program (com.sun.corba.ee.spi.orbutil.file.WorkspaceRename) +that is part of the ORB library. There is an ant target (rename) for +this as well. All that is needed for the rename is: +
                      1. +cd <workspace>/make +
                      2. ant orb-library (on a new workspace, to build the orblib.jar the first +time) +
                      3. ant rename +
                      +(TBD: make rename do a fast check for the orblib.jar, and build it +if it is not present. Right now, calling ant orb-library takes around +5 seconds, which is too long, since the incremental rename is <1 second). +The ant rename target on a fast local file system should take around +30 seconds or so (much faster than the old scripted version).
                      +
                      +Of course, the rename also interferes with the standard edit-compile-test-debug +cycle. I have a build environment built around vim that gets around +this problem, but it is difficult to impossible to deal with renaming +with any IDE that I know of.
                      +
                      +The rename is no longer necessary for development in GlassFish-CORBA. +Here all that is required is an ant build, from NetBeans, standalone, +or from any other tool a developer might care to use. The only time +a rename is required is when the jar files are created that are delivered +to GlassFish for integration in the app server.
                      +
                      + + +

                      1.3.4  ORB Build Files

                      + +The ORB can only be built with ant. All makefile support has been +removed.
                      +
                      + + +

                      1.3.4.1  Building the ORB

                      + +The ORB can be build either standalone (the mode used to deliver the +ORB into GlassFish), or as part of the JDK. Here we just focus on +the app server specific build. You MUST use JDK 5 or later.
                      +
                      +Assume <ws> is the ORB workspace. The basic build sequence is: +
                      1. +cd <ws>/make +
                      2. ant rename +
                      3. cd <ws>/build/rename/ee/make +
                      4. ant build +
                      5. ant test (or ant emma to run the tests and generate a coverage report) +
                      +Assuming a local file system is used on a fast machine, the rename +should take around 30 seconds, and the build 60 seconds or less. The +test target builds the tests (build-tests) which takes around 60-90 +seconds, and then runs all of the tests, which should take around +40 minutes.
                      +
                      +I generally use a script to automate this. It is also possible to +do a build from NetBeans. It used to be necessary to rename in order +to build and run the tests, but that has been fixed in the GlassFish-CORBA +project.
                      +
                      +Another small note: it is possible to generate JavaDocs for the CORBA +SPI. To do this, simply go to the make directory in the renamed version +of the workspace, and run “ant javadoc”. The resulting JavaDocs +may then be accessed from <ws>/build/rename/ee/build/release/docs/index.html +(exercise for the reader: fix all of the JavaDoc warnings that show +up). It should also be possible to create the SPI javadocs without +renaming, and the NetBean project supports this as well.
                      +
                      +Here is a more detailed description of the ant targets that are useful +to a developer:
                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      Target Name
                      Function
                      build
                      builds the ORB library and main ORB code (but not the tests)
                      build-tests
                      Runs idlj and rmic on test files, and calls compile-tests
                      compile-tests
                      Only compiles the tests (useful if you are changing a test, as build-tests +takes a lot longer to run
                      orb-library
                      Just build the ORB library (needed for rename)
                      update-copyright-headers
                      Update all copyright headers in the workspace to the contents of make/copyright-information/copyright.txt
                      validate-copyright-headers
                      Check that the copyright headers match copyright.txt
                      clean
                      Removes all generated files, renamed workspace, and test results
                      clean-emma
                      Removes emma results
                      clean-tests
                      Removes test results
                      javadoc
                      generate javadocs for ORB SPI (TBD: need to handle ORB library as +well)
                      findbugs
                      generate a findbugs report on the ORB
                      emma
                      Runs clean-emma, emma-instr, test, emma-report
                      emma-instr
                      Instrument all of the class files so that emma can generate a coverage +report
                      emma-report
                      Generate an emma report (found in <ws>/build/coverage/coverage.html)

                      +There are also a number of targets useful for running tests, which +are discussed in 1.4.
                      +
                      + + +

                      1.3.4.2  Structure of the build files

                      + +Let's look at the ant files first. There are several .xml files, all +included in build.xml: +
                      +build.xml
                      the main file +
                      jscheme.xml
                      Ant targets for running jscheme and generating log wrappers +
                      src-idl.xml
                      Ant targets for generating java from idl for the main +ORB code +
                      test-idl.xml
                      Ant targets for generating java from idl for the ORB +tests +
                      test-rmic.sml
                      Ant targets for generating stub and skeletons using +rmic for the ORB tests +
                      test.xml
                      Ant targets for running the ORB tests. +
                      emma.xml
                      Ant targets for emma support +
                      findbugs-filter.xml
                      Used by findbugs to avoid generating bug reports +on either the compilers or third-party code. +
                      +There are a number of other files as well: +
                      +build.properties
                      Included in build.xml, and used to define the build +version and other information for the maven repository importer (TBD: +this needs testing and integration for GlassFish v3) +
                      deleted-files.txt
                      A list of generated files that are deleted in +the build, as they are not wanted in the delivery. +
                      glassfish-corba.pom
                      Part of the maven importer support +
                      runtest
                      A useful script for running tests as described in 1.4. +
                      + + +

                      1.3.5  tests

                      + +The ORB has many tests in several different test suites (docs/TestCases.sxc +gives some details of the contents and the numbers of test cases in +the test suites, from a rough manual count). The test suites are: +
                      +ibm
                      Old RMI-IIOP tests created by IBM. These are the hardest tests +to deal with. +
                      corba
                      The bulk of our developer tests. Covers all areas of the ORB +to some degree. +
                      pi
                      The Portable Interceptor tests. +
                      naming
                      Test for the name services. +
                      mantis
                      Tests specifically for bug fixes made to JDK 1.4.1. +
                      hopper
                      Tests specifically for bug fixes made to JDK 1.4.2. +
                      copyobject
                      Tests for the various object copiers. Can also be used +as a timing test for streams, which will likely be very important +to us. +
                      simpleperf
                      A simple performance test mainly for colocated calls. +
                      + + +

                      1.3.6  libraries

                      + +There are a number of libraries in the lib directory. These are all +used either for building or testing. +
                      +ejb-2_1-api.jar
                      Needed for codegen test +
                      emma.jar
                      Main emma code +
                      emma_ant.jar
                      Emma's ant task +
                      ir.idl
                      Old and obsolete interface repository file (should be deleted) +
                      japex.jar
                      A version of the Japex performance testing framework (used +for compiling StandardTest) +
                      jscheme.jar
                      Scheme interpreter used for generating log wrapper source +files +
                      jschemelogutil.jar
                      Some simple utilities used with JScheme (source +is in the workspace) +
                      junit.jar
                      JUnit, used for some of the ORB tests +
                      maven-repository-importer-1.1.jar
                      Part of the maven support for +GlassFish (which is incomplete) +
                      orb.idl
                      A standard IDL file for some standard definitions (not really +used) +
                      rt.idl
                      IDL for the CodeBase interface (part of the SendingContext +module; used to enable access to another VM's typing information for +RMI-IIOP) +
                      testng.jar
                      TestNG, used in some of the ORB tests +
                      + + +

                      1.4  ORB Developer Tests

                      + + + +

                      1.4.1  Test Suites

                      + +The ORB developer tests are found in the directories test and optional/test. +The makefile for running the tests is in test/make/Makefile, but the +test suites can also be run from make/Makefile.corba. This table gives +a brief overview of the available test suites:
                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      Suite NameTest Fileant target in
                      +GlassFish-CORBA
                      Purpose
                      all-test-allruns all test suites
                      IBMtest/AllTests.desctest-rmi-iiopOld IBM tests
                      corbacorba/CORBATests.tdesctest-corbaMost of the newer tests
                      pipi/PITests.tdesctest-piPortable Interceptors tests
                      copyobjectcorba/CopyObjectTests.tdesctest-copyobjectcopyobject test
                      namingnaming/NamingTests.tdesctest-namingnaming tests
                      hopperhopper/HopperTests.tdesctest-hopperBugfixes for JDK 1.4.1
                      mantismantis/MantisTests.tdesctest-mantisBugfixes for JDK 1.4.2
                      simpleperfperformance/Tests.tdesctest-perfco-located call performance test

                      +All of the tests are run from <ws>/make using the appropriate targets. +The output of the tests (stdout and stderr) are redirected to log +files. These log files are located in <ws>/test/make/gen, under the +package name of the individual tests in the test suite. Most of the +tests of interest are in the corba test suite, so making those pass +first is usually all that is needed (the others tend to pass too, +once the CORBA tests pass). This is not always the case, particularly +if you are working on the RMI-IIOP code (which is tested in the IBM +test suite). These tests are also descibed briefly in <ws>/docs/TestCases.sxc, +which is a spreadsheet that roughly counts the number of test cases +in each test in each test suite.
                      +
                      +Each of the tests in the test suite starts one or more Controllers. +A Controller is simply a class that controls a component of a test. +For example, many of the tests have 3 controllers: a Client, a Server, +and ORBD (which is used mainly for name service, as few tests actually +exercise server activation).
                      +
                      +Adding a new test is simple: just create a new package for testing, +write the test, and add it to the appropriate test file. There is +a document that is somewhat helpful in the workspace at +
                      +test/src/share/classes/corba/framework/package.html +
                      +Especially read the section on the Controller classes, as that is +really the heart of the test framework. However, the document is old, +and somewhat out of date. You should consider the following additions +and changes since the document was written: +
                      • +You can use JUnit for tests. Simple write a JUnit test, and then wrap +it with a simple test class that extends corba.framework.CORBATest. +In fact, ANY program can be included in the CORBA test framework this +way. All that is needed is for the embedded test to indicate success +by returning 0, and failure by return a positive value in a System.exit() +call.
                        +
                        +The following tests currently use JUnit: +
                        • +corba/copyobject (this is the most complex example of what can be +done with JUnit) +
                        • corba/dynamicrmiiiop +
                        • corba/stubserialization +
                        • corba/misc (this is a good test to use a simple example) +
                        • corba/messagetrace +
                        • corba/codegen +
                        +
                      • Similarly, you can also use TestNG for tests. The following tests +use TestNG: +
                        • +corba/timer +
                        • corba/mixedorb +
                        • corba/jmx +
                        • corba/nortel +
                        • corba/simpledynamic +
                        • corba/mixedorb +
                        • corba/connectioncache +
                        +
                      • The ant build needs to be updated if new tests that require IDL or +RMIC are needed. See test-idl.xml and test-rmic.xml to see how this +is handled. +
                      • You can write tests that use RMI-IIOP without needing rmic. To do +this, just use dynamic RMI-IIOP. For an example of how to do this, +look at the corba/rfm test. Basically you just need to use the PresentationManager +API for a couple of things (access to the repository ID and to create +a Tie), and you also need to make sure that dynamic RMI-IIOP is enabled. +A renamed test will automatically run under dynamic RMI-IIOP, but +if the test is NOT renamed (and this will be the case after the migration +to GlassFish, at least for pure ORB development), you need to add +the following static initializer to the test code: +
                      +
                      +static { +
                      +System.setProperty( ORBConstants.USE_DYNAMIC_STUB_PROPERTY, “true” ) ; +
                      +} +
                      +
                      • +Conversion status info is out of date in the corba/framework/package.html +document: ignore this section. +
                      • Debugging is better. The document mentions the RDebugExec controller +(and also ODebugExec, but the omniscient debugger has not been tested +or updated in years. See http://www.lambdacs.com/debugger/debugger.html +for more information). +
                      • Default ORB class has changed. We now use com.sun.corba.ee.impl.orb.ORBImpl. +
                      • There are two security policy files available for running the tests. +The default test.policy file simply sets up the needed permissions +for all of the tests and the ORB. The more fine grained test.policy.secure +file sets up more restrictive permissions for the tests, while giving +more powerful permissions to the ORB code in the build and optional/build +directories. Which policy file is used is set in the test/make/Makefile +in the DEFINES macro.
                        +
                        +Setting the more secure policy file is useful to work on ensuring +that the ORB has doPrivileged blocks around all operations that have +security implications. It is known that the ORB is at least somewhat +deficient in this area, but we have not taken the time to thoroughly +address this issue.
                        +
                        +
                      • There are several environment variables that are useful to set while +running tests (see test/make/Makefile for more details): +
                        +STATIC_STUB
                        when set to 1, forces the use of static RMI-IIOP +
                        DYNAMIC_STUB
                        when set to 1, forces the use of dynamic RMI-IIOP +
                        BCEL_COPYOBJECT
                        when set to 1, uses the BCEL version of the fast +object copier (experimental) +
                        JAVA_SERIALIZATION
                        when set to 0, use CDR instead of JSG (JSG is +experimental, but enabled by default in the workspace only) +
                        DEBUGGER
                        can be set as follows: +
                        +1
                        Set ORBDebugForkedProcess=true (for IBM tests), and run tests +so that a JPDA-compliant debugger can be attached +
                        2
                        Run tests under OptimizeIt +
                        3
                        Run tests withc -Djcov=true for coverage analysis +
                        +
                        +
                      + + +

                      1.4.2  debugging tests

                      + +To debug a test, you need to know the name of the controller(s) to +which you need to attach a debugger. Controllers are normally created +by the methods createORBD, createClient, and createServer. The default +names of the controllers are ORBD, Client, and Server, respectively. +The createClient and createServer methods can also take a second argument +(the first is the class name of the test program) that gives a specific +name for the controller.
                      +
                      +Given the name of the controller(s) to debug, simply add the argument +
                      +-rdebug XXX,YYY +
                      +for controllers XXX and YYY (for example) to the end of the test file +argument that starts the test.
                      +
                      +ORB debug flags can also be passed into a test. To do this, add the +argument +
                      +-orbtrace XXX:f1,f2;YYY:f3 +
                      +where the argument is a semi-colon separated. Each element of this +list starts with a controller name, followed by a comma separated +list of ORB debug flag names (see com.sun.corba.ee.spi.orb.ORB for +the current list).
                      +
                      +It is also possible to change the log levels so that ORB log information +can be displayed on the console (or anywhere else, depending on the +log system configuration). This follows the usual log system mechanisms. +The ORB logger names are discussed in sec:ORB-Logging.
                      +
                      + + +

                      1.4.3  Debugging and Running a single test

                      + +I recently added the capability to run and debug a single test. This +requires the runtest script in the make directory. This is a script +that calls the run-test-target target in the test.xml file. You can +give runtest any arguments that occur in the .tdesc files. To use +runtest, cd to <ws>/make and check that runtest is executable. Here +are a few examples (assuming the current directory is <ws>/make): +
                      1. +To run the codegen test:
                        +./runtest -test corba.codegen.CodegenTest +
                      2. To attach a debugger to the client controller in the codegen test:
                        +./runtest -test corba.codegen.CodegenTest -rdebug client +
                      3. To see the transport debug output on the evol_client controller in +the corba EvolveTest:
                        +./runtest -test corba.evolve.EvolveTest -orbtrace evol_client:transport
                        +(the debug output will be in ../test/make/gen/corba/evolve/evol_client.out.txt) +
                      +All tests are run in the environment of the current ORB workspace. +Either the renamed or the non-renamed version can be used. This is +important because JDK 5 or later contains many of the same classes +in the com.sun.corba packages as the workspace. The ant files set +up the java -Xbootclasspath argument correctly so that the versions +of the com.sun.corba classes in the workspace are used, instead of +those in the JDK.
                      +
                      + + +

                      1.5  ORB SQE Tests

                      + +Sony Manuel maintains a large collection of CORBA SQE tests in /java/idl/ws/rip/RIP_TEST_MASTER. +Read the file DTF_RTM_README.html in this workspace for details +(and contact Sony as well). These test are not currently available +in GlassFish-CORBA.
                      +
                      +We should look at creating a tighter integration between the CORBA +dev tests and the SQE tests at some point. In particular, I'd like +to have the POA and INS tests run automatically as part of the CORBA +dev test cycle.
                      +
                      + + +

                      1.6  Thoughts on Middleware goals

                      + +Middleware is a rather complex kind of software to build well. It +spans many parts of the computer science discipline, including compilers, +operating systems, and network communications. Middleware tends to +be complex, long-lived software, and there are many different ways +to build it. Our goal in developing the ORB has been to develop very +flexible and high-performance middleware while maintaining a clear +(if complex) architecture that can be easily composed, ultimately +out of re-usable modules. One way to look at an ORB is that ORB.init +creates a particular middleware implementation that is specialized +to the needs of an application. For example, the behavior of the default +ORB in the JDK is rather different from that of the ORB in the app +server, even though both share >95% of the same code.
                      +
                      +At least the following dimensions must be considered in order to build +effective middleware: +
                      +Flexibility.
                      Middleware has been changing constantly since Nelson +invented RPC around 1980 or so. Much of Harold's work on PEPt has +been devoted to dealing effectively with this aspect of middleware +construction. The following elements often vary indendently of each +other: +
                      +Presentation.
                      By this we mean the kinds of data types that may be +passed between a client and server (roles here, as any given software +entity often acts in both roles), and the APIs and other structures +used to collect these kinds of data together.
                      +
                      +Examples of data types include the IDL data model from CORBA, the +Java data model from RMI, XML schema, ASN.1, SUN RPC, MIME types, +and many others.
                      +
                      +There are broadly speaking two ways to view the API question: either +the system uses some sort of Proxy to make a remote call “look +like” a call to an abstraction (method call, procedure call, SmallTalk +message send, etc) or the API provides an explicit representation +of a request or message that a program can set up with data and then +send (CORBA dynamic invocation, Message Oriented Middleware, and others).
                      +
                      +
                      Encoding.
                      Given a structure containing the data from the presentation +layer, it needs to be converted from an in memory representation to +some representation suitable for transmitting across some serial medium +like a TCP connection. This is usually referred to as marshalling +and unmarshalling the data, and is often the most expensive operation +that middleware performs. In fact, I believe this is the most significant +challenge for middleware of all types as network hardware increases +in speed. +
                      Protocol.
                      This is related to but distinct from encoding. Here we +are concerned about the kinds of messages that clients and servers +exchange. This is mainly about message framing, headers, various kinds +of meta-data associated with requests, and the distributed state machines +involved in protocol design. +
                      Transport.
                      Ultimately, some mechanism must be used to transmit data +from the client to the server. This can include network protocols, +shared memory mechanisms, Solaris doors, and direct calls within the +same address space that bypass all such mechanisms (in which case +the protocol and encoding are much simplified as well). +
                      +
                      Performance.
                      Everyone always wants middleware to perform as quickly +as possible. This is quite a challenge. First, there are many aspects +to performance, including: +
                      +Latency.
                      How long does it take to send messages of various types? +What about short vs. very long messages? +
                      Throughput.
                      How many request per second can be sent through the +system? This often conflicts with latency. For example, a front end +concentrator can help to pump more data through, at the cost of increased +latency due to an extra hop. +
                      Creating Endpoints.
                      Object-Oriented remoting systems like CORBA +create, marshal, and unmarshal endpoints (IORs in CORBA) constantly, +and the performance of such operations is quite significant. +
                      +Today, our latency is poor (except for co-located RMI-IIOP calls, +which are highly optimized), our throughput is OK (and this is NIO +select related), and the IOR handling is pretty good, although much +more is possible.
                      +
                      +We need to follow a number of strategies for improving performance:
                      + +
                      • +Cache when appropriate. The ORB caches lots of information, especially +related to class-specific information for marshalling and handling +stubs and skeletons. +
                      • Don't do it if you don't need it. For example, interceptors are expensive, +so don't pay overhead for them if none are installed. A bad example +is that the encoding currently computes two indices instead of one, +and checks to see whether to marshal little- or big-endian on every +primitive marshalling operation. These are areas that we should investigate +soon.
                        +
                        +This is particularly important for systems that have extreme flexibility.
                        +
                        +
                      • Precompute where possible (really a form of caching). A good example +of this is the use of IOR templates to make endpoint (IOR) construction +very fast. Creating a POA creates an IOR template, and creating an +IOR from an IOR template is almost a trivial construction. +
                      • Avoid data copying. This is one of the main areas of important for +transport optimization. For example, this is where use of direct ByteBuffers +can help performance (which we do today). +
                      • Consider runtime code generation. We have started to do this already +for dynamic RMI-IIOP. I also have been experimenting with doing this +for fast object copying, and marshalling is another candidate. +
                      • Instrument the code so that performance can be understood. We have +started to add internal instrumentation for this, and I think we will +expand on this approach. Sometime the most appropriate tool is an +external tool like OptimizeIt, but both approaches have their advantages. +Note that applying OptimizeIt to an ORB test is easy: see sub:Test-Suites. +
                      +
                      +Reliability.
                      Middleware is usually used in places that need to run +continuously (like the app server). This again implies a number of +considerations: +
                      +Avoid Memory Leaks.
                      This has been an issue for the ORB mainly +in caching class related data. We have had to make careful use of +soft and weak references in a number of places to handle this. Extreme +care is needed to avoid leaking direct ByteBuffers, which generally +must be pooled to achieve acceptable performance. +
                      Build Clean Code.
                      This is why we have a strong emphasis on programming +to interfaces. Another important aspect of this is only write a piece +of code once, and then reuse it. +
                      Use Test Driven Development.
                      By this I mean that anyone producing +a module of code must also produce a set of unit tests (and other +tests as needed) to validate the correctness of the module. This also +means that as much as possible, bug fixes require a test that fails, +and a fix that makes the test pass, and the test must be incorported +into the automated build. +
                      +
                      + + +

                      1.7  ORB Coding Practices

                      + +
                      • +Use comments wisely. Some guidelines: +
                        • +Don't document the obvious. If the code is clear, it should speak +for itself. If the code is not clear, try to make it clear. If you +can't, then comment about its operation. +
                        • Try to choose meaningful names to reduce the need for comments. +
                        • DO document global issues that span more than one method/class/package. +These are the most important comments to include. +
                        • Always document public methods (there should be NO public data members, +except possibly for some static constants). Follow the standards for +using JavaDoc. +
                        +
                      • Program to interfaces. Most of the ORB is built this way. There are +a number of characteristics of this design: +
                        • +Use of the factory pattern. Factories in the ORB are generally classes +in spi packages which contain only static methods for accessing factories, +or standard instances of particular interfaces. These classes should +end in the name “Default(s)” or “Factory”. +
                        • new is only used to create instances of interfaces inside +the factory classes. This makes it much easier to re-use code, and +to isolate the client from caching vs. creation decisions. +
                        • Initialization drives call flow. That is, in order to understand what +really happens at runtime, you must know how the ORB initialization +set up the concrete instances behind the interfaces. Similarly, in +order to understand the dispatch cycle, you must understand how the +IOR is created and marshalled (especially if we ever do a Solaris +doors transport again). +
                        +
                      • Avoid magic strings and numbers. If you need a constant, put it in +ORBConstants, since it will either need to be configurable or else +referencable in more than one place in most cases. +
                      • Generally use only SPI classes (but note ORBConstants is in impl). +Generally an ORB implementation class is free to use any required +spi class, but should avoid using implementation classes outside of +its own package. +
                      • The ORB object instance is central. It is the repository for all runtime +ORB data. It drives the configuration of the runtime ORB. Everything +that the ORB provides is accessible from the com.sun.corba.ee.spi.orb.ORB +class. +
                        • +Access the ORB either as org.omg.CORBA.ORB or as com.sun.corba.ee.spi.ORB. +There are other ORB classes, but never program to them. +
                        • Use the CORBA ORB for code that may be shared with other ORB implementations. +This is mainly an issue in the RMI-IIOP code and the value handler, +which are used by some third party ORBs. If you need the ORB SPI, +provide code that handles the CORBA ORB case as well. +
                        +
                      • ORB extensions should be created as IDL local interfaces, and made +accessible through a resolve_initial_references call. We have not +followed this principal in the past as much as we should have, and +the result is that there are too many methods in spi.orb.ORB. An alternative +here is to use dependency injection from a component framework, but +that's a separate topic (and paper). +
                      • Read “Effective Java” (if you haven't already). Josh Bloch's +book is full of some very good advice that should almost always be +followed. +
                      • Try to avoid complex constructors, or classes with many constructors. +This makes the code confusing and hard to use. +
                      • Try to complete instance initialization in the constructor. If this +is not possible, check whether the instance is in a good state before +continuing with the body of a method. +
                      • Some ideas on error handling: +
                        • +Design code to fail fast. That is, if there is a problem in the code, +fail sooner, so that the problem is correctly reported, rather than +letting it propagate through the system until it's hard to determine +what happened. Examples of this include use of assert, and +the ORB's use of INTERNAL SystemExceptions to report consistency failures. +
                        • Use exception chaining when reporting errors. The log wrappers make +this easy to do. +
                        • Use system exceptions to report errors. We have a pretty good log +wrapper mechanism that makes this easy to do: always use it. The only +exception here is in ORB independent libraries (like codegen). Here, +just use standard Java exceptions. +
                        • Prefer unchecked exceptions in most cases. This has been a raging +debate for a long time in the Java community. I think checked exceptions +are occasionally useful, but often more trouble than they are worth. +A good rule of thumb is that if the only thing an application is going +to do is pass the exception on to another layer, it should be unchecked. +Writing code that catches a series of checked exceptions and handles +each through a standard reporting mechanism is wasteful and annoying, +and does nothing for the readability of the code. +
                        +
                      • Avoid import xxx.* Careful organization of import lists is a great +aid to figuring out how classes are coupled together. The ORB rules +that should be followed for import lists are: +
                        1. +Arrange packages from the general to the specific. For example, put +java.* first, then org.omg.* first, finally internal com.sun.corba.ee.spi.* +classes. +
                        2. Within a package, arrange classes in alphabetical order. +
                        3. Separate different package imports with a blank line. +
                        4. If you have an IDE that can do this for you, use it. +
                        +
                      • Be very careful with import static xxx.* It is occasionally very +useful (for example, for calling all the static methods like _class, +_method, _if etc. in the codegen library). But using it for all +statics could lead to much confusion. +
                      • Names are very important +
                        • +Interfaces have descriptive noun phrases (e.g. LocalClientRequestDispatcher) +
                        • Implementations of interfaces end in “Impl” (e.g. JIDLLocalCRDImpl) +
                        • Try to avoid abbreviations (but not if the name is too long) +
                        • Limit names to 7 nouns (and I think we break this one once or twice) +
                        • Multiple implementations should look like <InterfaceName><Characteristic>Impl +or <Characteristic><InterfaceName>Impl +
                        • Abtract base classes should look like <InterfaceName>Base +
                        • Factory interfaces usually look like <InterfaceName>Factory +
                        • Follow the standard Java naming conventions (except for IDL generated +methods) +
                        +
                      • Prefer short methods (and let HotSpot do its job). Some of the code +in the ORB (e.g. CDR streams) has badly violated this rule, resulting +in many cut-and-paste sections of nearly identical code. This is a +testing, debugging, and understanding nightmare. +
                      • Pay attention to cohesion and coupling. A class should do one thing +that can be crisply articulated, as should a method. A class should +use a minimum of other classes to get its job done. +
                      • Either prevent inheritance or design for it. Harold and I have often +been in conflict on this one. There is some code in the ORB in which +the data members are private instead of protected. This is occasionally +helpful (for example, in some of the HWLB plugin code), but is an +open door to maintenance headaches. If a field or method is protected, +you are really saying that no invoker can call this, but a subclass +can, and a subclass can override this method. What are the constraints +on subclasses in this case? Such design decisions should be documented +in the code. +
                      • Use shallow inheritance hierarchies. We commonly use the interface/abstract +base class/several concrete classes pattern to facilitate code reuse +across implementation variations. There are a few places (e.g. local +client request dispatchers, some of the POAPolicyMediator code) that +do this for two (perhaps more?) layers, but that should be rare. +
                      • Don't bother making methods final for optimization, as this is not +helpful. Final is semantic: it means that no subclass can override +this method. +
                      • Utility classes (those that only contain static methods) must be final +and have a empty private no-args constructor. This prevents all instantiation +and subclasses of utility classes. +
                      • Consider making most local data final. This is unusual, but actually +quite useful, since most local data is initialized and then referenced +in the method. Parameters should always be final, as assigning to +a parameter is poor style. +
                      • Never use public data members in classes (except for static final). +Be careful with protected and default access for data members. +
                      • Avoid non-constant static data members in classes. Sometimes they +are necessary, in which case concurrency protection is usually required. +
                      • Use JDK 5 (and convert old code to use it). The new language extensions +help to make for more readable code. I have converted some of the +code, but not all. +
                      • Design for testability. Make sure that classes have an interface that +supports testability: if some internal state is established that needs +to be verified, then there must be an interface to access the state. +Leaving code for testing in the product code is acceptable, but make +sure it does not affect any critical performance issues. +
                      • Design for concurrency. +
                        • +Make sure you know whether instances of a class may be used from more +than one thread concurrently. If so, use locking. +
                        • NEVER assume that it is safe to access ANY data without either locking +or declaring it to be volatile. Don't break this rule for stats counters +under the assumption that it will only be off a little (this isn't +true in complex SMP servers with large caches). +
                        • Make use of the Java 5 concurrency utilities. These are very well +designed to solve a number of hard problems. +
                        • If you need to wait on more than one condition, use the java.concurrent.util.locks +package, particularly ReentrantLock and Condition. +
                        • Use a lock hiearchy to avoid deadlocks if multiple locks are required +in a thread of control. +
                        • Be aware of the potential for locking hot spots on Sun's SMP servers +(and especially Niagra these days). This frequently is a single lock +that every request dispatched through the ORB must acquire at some +point. Again, Java 5 has some very useful utilities to help (such +as ConcurrentHashMap). +
                        +
                      • Do NOT put Class instance into Maps as values or keys directly or +indirectly. Pinning a Class object in a Map will prevent the Class +from being garbage collected, which will prevent that Class's ClassLoader, +and all other Classes loaded by the ClassLoader from being garbage +collected. This has led to massive memory leaks in the App Server +on several occasions.
                        +
                        +The solution here is to use WeakHashMap (for Classes in keys) or SoftCache +(for Classes in values) as need. Grep the source code for examples.
                      + + +

                      1.8  Supporting JDK and App Server

                      + +The main body of the ORB code (that is, most of the contents of the +src directory) must be delivered into both the JDK and the app server +without change (other than the automatic rename). This has some interesting +implications: +
                      1. +Use extension, not variation. Never create an app server and a JDK +version of the same class. Instead, refactor the class so that there +is a common base in the core that can be extended, either through +inheritance or composition. +
                      2. Prefer composition to inheritance. +
                      3. Remember that the io, util, and javax code is shared between our ORB +and other (non-Sun) ORBs. This means in particular that other ORBs +may be built using our ValueHandler and RMI-IIOP classes. The main +issue here is that we cannot assume that the ORB class is always com.sun.corba.ee.spi.orb.ORB. +It is OK to create a specialized path for our ORB, but this must always +be done with an instanceof check, and handle the non-Sun +ORB case correctly. +
                      4. All behavior exhibited by the JDK ORB must follow the OMG specifications. +Mostly this is CORBA 2.3.1, but we follow the semantics of later versions +when errors have been corrected. For example, the POA should basically +follow the behavior documented for CORBA 3.0 at this point. Note that +it is fine to create non-standard extensions to CORBA semantics for +the app server: this is exactly what we have done for failover and +load balancing support (among others). +
                      + + +

                      Chapter 2  The ORB Class

                      + +The ORB class is the central control point in the Sun ORB implementation. +Here we will examine its structure, the services it provides, and +how it is initialized and terminated.
                      +
                      + + +

                      2.1  Inheritance Structure

                      + +The ORB class has the longest inheritance chain in the ORB. Constructing +a UML diagram for this is difficult (because of the way this works +in Java Studio Enterprise) and not very illuminating. Instead, I'll +just list the classes and their main function: +
                      +org.omg.CORBA.ORB:
                      This is the main ORB API defined by the OMG. +
                      org.omg.CORBA_2_3.ORB:
                      This adds some methods related to value +types. +
                      com.sun.corba.ee.org.omg.CORBA.ORB:
                      This adds register_initial_reference. +While the method is an OMG standard, the Java mapping that we used +for the ORB API did not include this method, so we put it here. +
                      com.sun.corba.ee.spi.orb.ORB:
                      This adds all of the internal SPI +methods to the ORB. +
                      com.sun.corba.ee.impl.orb.ORBImpl:
                      This is the ORB implementation. +
                      com.sun.corba.ee.internal.iiop.ORB:
                      For backwards compatibility +with JDK 1.4. +
                      com.sun.corba.ee.internal.POAORB:
                      For backwards compatibility with +JDK 1.4. +
                      com.sun.corba.ee.internal.PIORB:
                      For backwards compatibility with +JDK 1.4. +
                      +The first 3 classes together define the standard OMG ORB API. It is +split because it evolved in stages, and we cannot add new methods +to an interface that a third party may implement. Instead, we extend +the API class, allowing older ORB implementations from third parties +to continue to work. The classes in the internal package can be ignored. +They are present so that any old code written with the ORBClass property +set to the class name will continue to work.
                      +
                      + + +

                      2.2  ORB SPI structure

                      + +The key part of the ORB SPI is in the com.sun.corba.ee.spi.orb.ORB +abstract class. This is an abstract class because it must extend the +other ORB abstract API classes defined by the OMG. The ORB class provides +the following operations: +
                      • +A set of debug flags. ORB defines a number of public boolean data +members of the form xxxDebugFlag. These can be set to true using the +ORBConstants.DEBUG_PROPERTY property. Adding new flags is simple: +just follow the existing pattern. These flags are accessible to any +part of the ORB that uses an ORB class instance, which is everything +except RMI-IIOP and some libraries. +
                      • Methods for testing for local host and server id, which is important +for determining when a call is colocated. This mechanism should be +revisited in order to deal with multi-homed hosts and calls between +different ORB instances (which currently are not optimized, even if +the ORB instances are in the same VM). +
                      • Methods for manipulating the OAInvocationInfo stack. This stack contains +information about the current request on the server side. The ORB +has several stacks that serve similar functions, as does the EJB layer +in the app server. This suggests an important optimization: unify +the lifecycle management of the stacks, and use a single unified stack +on each side (client and server) that supports extensible data elements. +
                      • Access to a number of managers, factories, and registries: +
                        • +CorbaTransportManager +
                        • LegacyServerSocketManager +
                        • PresentationManager (this is a static, as it is shared across RMI-IIOP +and all ORB instances). +
                        • PresentationManager.StubFactoryFactory (also static) +
                        • MonitoringManager +
                        • PIHandler, which provides all of the methods needed to support Portable +Interceptors. +
                        • ServiceContextFactoryRegistry +
                        • RequestDispatcherRegistry, which provides many of the key objects +needed for the dispatch cycle. +
                        • ORBData, which contains all of the ORB configuration data. +
                        • ClientDelegateFactory, which converts a CorbaContactInfoList into +a CorbaClientDelegate. +
                        • CorbaContactInfoListFactory, which converts an IOR into a CorbaContactInfoList. +The ClientDelegateFactory and the CorbaContactInfoListFactory are +the two essential objects used to prepare an endpoint (represented +by an object reference, and containing an IOR) into a form suitable +for use in the dispatch cycle. +
                        • Resolvers for resolve_initial_references, list_initial_services, +and register_initial_reference. These are also used for string_to_object. +
                        • Factories and related objects for IOR handling: +
                          • +TaggedComponentFactoryFinder +
                          • IdentifiableFactoryFinder for TaggedProfiles +
                          • IdentifiableFactoryFinder for TaggedProfileTemplates +
                          • ObjectKeyFactory +
                          • WireObjectKeyTemplate +
                          +This allows us to extend the basic IOR framework with tagged component +and profiles as needed, and also allows us to plug in a particular +object key representation. The object key representation is important +for the operation of object adapters.
                          +
                          +
                        • ThreadPoolManager +
                        • CopierManager +
                        • ByteBufferPool +
                        +
                      • Access to the ORB Invocation Interceptor. This is a non-standard interceptor +that intercepts calls before and after the dispatch through the stub +(when dynamic RMI-IIOP is used). This is currently used in the app +server for call flow analysis, and could also be used for ORB timing +points. We may wish to consider providing a more extensible mechanism +here: the current implementation supports only one interceptor. +
                      • Access to primitive type codes and a mapping between repository IDs +and type codes. +
                      • Access to the current ORB version, and a mechanism to set the ORB +version for the current request (to handle interoperability between +different versions of the Sun ORB). +
                      • Access to the IOR for the FVD CodeBase object. +
                      • Mechanisms for dealing with bad server IDs. This is only needed to +support the ORBD. The mechanism is now obsolete, as the object reference +template (ORT) provides a better solution, but our current ORBD has +not been updated to use ORT. +
                      • The notifyORB method, which is used to support the DII get_next_response +mechanism. +
                      • Support for controlling ORB shutdown so that shutdown cannot happen +until all active requests have completed. +
                      • Access to the transient server ID, which is used for IORs for transient +object references. +
                      • Methods used by generated log wrapper classes to create log wrappers, +which are used for reporting errors and managing CORBA system exceptions. +
                      +Clearly there are a lot of methods in the ORB SPI. A better approach +would be to push most of this into the initial references mechanism, +using IDL local objects. This would substantially reduce the size +of the ORB SPI. But I think we are unlikely to do this, as the impact +on the existing code is probably too large.
                      +
                      + + +

                      2.3  ORB Initialization

                      + +The ORB initialization code is fairly complicated, but reasonably +well structured at this point. I'll start with a discussion of the +ORB configuration framework, then describe the ORB initialization +process in moderate detail. I'll also discuss how this is extended +in the app server.
                      +
                      + + +

                      2.3.1  The Configuration Framework

                      + +The orb packages contains a mostly general purpose framework for handling +configuration. This is divided into several parts: +
                      • +The DataCollector, which gathers configuration data from config files, +system properties and other properties objects, and command line arguments +together into a uniform Property object. +
                      • The Operation interface and factory methods for creating Operation +instances. Operation is a simple unary function interface that returns +an object. A wide variety of factory methods are provided in OperationFactory +and OperationFactoryExt, including one that composes Operations to +create a new Operation. This allows expression of fairly complex parsing +methods. Many of the Operation instances just convert a String into +some other type. +
                      • The PropertyParser and related classes that take a number of operations +and combine them into a single parser that can parse all the elements +of a Property instance into a Map<String,Object> from field names +to values. +
                      • Base classes that use a PropertyParser to initialize (possibly private) +fields in a configuration object (typically a JavaBean-like object +with only read accessors). There is also a base class (ParserImplTableBase) +for constructing a PropertyParser from a table that includes default +values and test data. This is used for initializing the ORBData object +that contains all of the ORB configuration data. +
                      +The following sections will look at these parts in more detail.
                      +
                      + + +

                      2.3.1.1  DataCollector

                      + +A DataCollector has a rather simple interface: setParser passes a +PropertyParser instance to the DataCollector, which causes the DataCollector +to gather together all configuration data from the available data +sources into a single instance of Properties. This instance is available +in the getProperties method.
                      +
                      +The available data sources are: +
                      • +System Properties +
                      • Applet Properties +
                      • Contents of configuration files +
                      • Command line arguments +
                      +It is perhaps not immediately obvious why a PropertyParser needs to +be passed to the DataCollector. The reason for this is that it is +not always possible to simply grab every bit of information from the +data sources. But it is possible to get all configuration information +for the known property names. So the DataCollector uses the PropertyParser +to fetch information for all property names of interest.
                      +
                      +Here is a class diagram of the DataCollector classes:
                      +
                      +
                      +
                      +Note that there are 3 different kinds of DataCollector. The Applet +and Normal DataCollectors are used with the corresponding ORB.init +methods. The PropertyOnly DataCollector is only used internally, when +we need to create an internal full ORB instance to support certain +operations on the ORB singleton. The DataCollectorFactory class provides +static methods for creating the different kinds of DataCollectors.
                      +
                      +There are a few issues here that could be revisited: +
                      • +The DataCollector framework has some internal ORB dependencies that +could be removed: +
                        • +It handles some URL property names (for applets) specially. +
                        • There is special handling for -ORBInitRef. +
                        • The DataCollector base goes to a lot of trouble to hide some sensitive +data from arbitrary access by untrusted clients (mainly the local +host name). It may be better to avoid doing this, and instead check +all access to sensitive information through the SecurityManager (if +one is present). +
                        • While the DataCollector interface is independent of the ORB, DataCollectorBase +is not. It would be cleaner to factor the ORB dependencies into another +base class. +
                        +
                      +Fixing these issues would allow reuse of the DataCollector mechanism +outside of the ORB, and provide a somewhat cleaner implementation.
                      +
                      + + +

                      2.3.1.2  Operation

                      + +The operation interface is simply: +
                      +public interface Operation { +
                      +Object operate( Object value ) ; +
                      +} +
                      +The SPI classes OperationFactory and OperationFactoryExt provide a +large number of factory methods for creating instances of the Operation +interface: +
                      • +makeErrorAction( Operation op ), where operate calls op and ignores +any errors it may through +
                      • indexAction( int index ), where operate returns the index element +of its argument, if the argument is an array +
                      • suffixAction, where operate returns the first value in a Pair<String,String> +object +
                      • valueAction, where operate returns the second value in a Pair<String,String> +object +
                      • identityAction, where operate returns its argument +
                      • booleanAction, where operate converts its argument from a String to +a Boolean +
                      • integerAction, where operate converts its argument from a String to +an Integer +
                      • stringAction, where operate checks that its argument is a String, +and returns it if it is +
                      • classAction, where operate converts its argument from a String into +a Class using ORBClassLoader.loadClass +
                      • setFlagAction, where operate returns Boolean.TRUE +
                      • URLAction, where operate converts its argument from a String into +a URL +
                      • integerRangeAction( int min, int max ), where operate converts its +argument from a String to an integer if its argument represents an +integer between min and max, otherwise throws an exception +
                      • listAction( String sep, Operation act ), where operate expects its +argument to be a String of data separated by the sep delimiter, and +uses a StringTokenizer to separate the argument into a sequence of +Strings. operate then applies act to each String in the sequence, +and returns the results in an array. This is used for parsing homogeneous +lists of data. +
                      • sequenceAction( String sep, Operation[] act ), where operate behaves +similarly to listAction, except that successive elements of act are +applied to the sequence of Strings, instead of always using the same +Operation. This is used to process heterogeneous lists of data. +
                      • composeAction( Operation op1, Operation op2 ), where operate first +applies op1 to its argument, then applies op2 to the result. +
                      • mapAction( Operation op ), where operate applies op to each element +of its argument, which must be an array, and returns an array of the +results. +
                      • mapSequenceAction( Operation[] op ), where operate behaves similarly +to mapAction, except that successive elements of op are applied to +the elements of the argument in sequence. +
                      • convertIntegerToShort, where operate converts an Integer to a Short. +
                      • convertAction( Class<?> cls ), where operate constructs an instance +of cls using its argument as an argument to the constructor. Here +it is assumed that cls contains a constructor that takes a single +String as an argument. +
                      +Other Operation implementations can be readily created, but this set +is sufficient to handle all ORB configuration parsing (except for +URL parsing, which is currently handled by some classes in the resolver +package). Extending this framework to handle URL parsing is relatively +straightforward, but requires the ability to handle optional data +and alternate forms that is not currently present (essentially something +like ifAction( predicate, opTrue, opFalse ) would probably take us +in the right direction).
                      +
                      +The other issue with this is that composing all of the actions in +Java is somewhat cumbersome (take a look at ParserTable.makeADOperation +for an example). A customized language (e.g. some Lisp macros) could +make this much simpler. Combining this with annotation and code generation +could reduce the ORB configuration implementation to something like: +
                      +@Configuration
                      +
                      +public interface ORBData { +
                      +@Parse( “<some expression>” )
                      +
                      +public String getORBInitialHost() ;
                      +
                      +... +
                      +} +
                      +Pursuing this degree of automation is probably more than is justified +by the needs of the ORB. +
                      + + +

                      2.3.1.3  PropertyParser

                      + +The DataCollector gives us a way to gather multiple sources of configuration +together into a uniform Properties object, and the Operation framework +gives us a way to parse Strings into data in many different ways. +The PropertyParser ties these two mechanisms together so that we can +parse all of the configuration data in a single operation.
                      +
                      +A PropertyParser is basically a collection of ParserActions. There +are two kinds of ParserActions: +
                      +Normal:
                      Here the property name is found in the Properties object, +and the String associated with the name is transformed into a value. +
                      Prefix:
                      Here the property name is a prefix, and all property names +that start with the prefix are transformed into the value. +
                      +There is a factory class (ParserActionFactory) that is used to create +the two ParserActions.
                      +
                      +A PropertyParser is initialized by call its add and addPrefix methods +to add the ParserActions that are needed in the PropertyParser. These +methods return the PropertyParser so that they can be chained if necessary. +Each of these methods takes the following arguments: +
                      +propName
                      which is the property name to which this action is applied +
                      action
                      which is the Operation performed by this action +
                      fieldName
                      which is the name in the resulting Map in which the result +of the Operation is stored. This is used later (see sub:Base-Classes-for) +for storing the results in a configuration object like ORBData. +
                      +There are two other important methods in the PropertyParser. The parse +method takes a Properties instance and returns a Map from fieldNames +to the parsed values. This is the main parsing method in the framework. +The iterator method returns an Iterator over the ParserActions, which +can be used to find all of the property names in the PropertyParser. +This is used by the DataCollector to determine which properties are +required.
                      +
                      +The following diagram shows the different classes used in the PropertyParser +implementation:
                      +
                      +
                      +
                      + + +

                      2.3.1.4  Base Classes for Parsing Properties

                      + +The top of the configuration framework includes classes that can take +the Map returned from a PropertyParser and use it to update the fields +in a class that is essentially a read-only JavaBean. This is done +in ParserImplBase. A further extension to this class in ParserImplTableBase +allows the use of a table of ParserData to initialize the Parser.
                      +
                      +The ORB configuration data is represented by the ORBData class. It +is implemented by ORBDataParserImpl, which extends ParserImplTableBase +and uses ParserTable (essentially a large ParserData[]) to provide +the initialization data.
                      +
                      +The ParserData contains the following information: +
                      • +The property name. +
                      • The Operation used to parse the information. +
                      • The field name into which the parsed configuration data is placed. +
                      • The default value which is used when the Properties do not contain +the property name +
                      • Test data and test value which are used to test the Operation. This +is done automatically in the corba.orbconfig test (see testORBData()). +
                      +Instances of ParserData are created by the factory methods in ParserDataFactory. +ParserData is implemented by the NormalParserData and PrefixParserData +classes.
                      +
                      + + +

                      2.3.2  Details of ORB.init

                      + +Initializing an ORB from an ORB.init() call (the two versions that +have arguments) requires several steps: +
                      1. +Select the ORB class that needs to be instantiated. +
                      2. Create an instance of the class. +
                      3. Invoke the set_parameters method on the instance. +
                      +These steps are all standard. The more interesting part is what happens +in set_parameters.
                      +
                      +set_parameters proceeds as follows: +
                      1. +Call the preInit method, which sets up most of the configuration independent +parts of the ORB (which is not very much). This includes: +
                        1. +Initializing a PIHandler that does nothing, so that the ORB can perform +requests before PI has been initialized (which happens near the end). +
                        2. Create a ThreadGroup for use by the ORB. This is complicated because +of some Applet considerations: for details, see the code. +
                        3. Set up the transient server ID. This is currently just set to System.currentTimeInMillis. +
                        4. Set up the ORBVersion ThreadLocal. +
                        5. Initialize some locks. +
                        6. Initialize the various registries. +
                        7. Set up invocation info ThreadLocal stacks. +
                        +
                      2. Create a DataCollector that represents the available configuration +data for use in creating this ORB instance. ORB.init( String args, +Properties props ) uses the NormalDataCollector, while ORB.init( Applet +app, Properties props ) uses the AppletDataCollector. +
                      3. Call the postInit method, which handles all configuration-dependent +ORB initialization. This includes: +
                        1. +Setting up the ORBData. This is simple: just construct configData +using ORBDataParserImpl and the DataCollector. +
                        2. Set up the debug flags. +
                        3. Initialize the monitoring manager, the transport manager, and the +legacy server socket manager. +
                        4. Set up another parser (using the Parser framework) to obtain the ORBConfigurator. +Run the ORBConfigurator. +
                        5. Set up the real PIHandler, replacing the no-op version from the beginning +of the initialization sequence. +
                        6. Set up the thread pool manager and the byte buffer pool +
                        +
                      +Most of the detailed ORB initialization happens in the ORB configurator, +which we will examine next.
                      +
                      + + +

                      2.3.2.1  The ORB configurator

                      + +We have two mechanisms for customizing the ORB initialization: the +standard (from PI) ORBInitializer, and the ORBConfigurator. Why two? +There really is only need for one, except for one really irritating +problem: the ORBInitializer does not provide direct access to the +ORB or the ORB configuration data (our DataCollector). We also want +to be able to have ORB extension parse configuration properties that +are not even known in the base ORB configuration (although we don't +currently make use of this). So I chose to create the ORBConfigurator +interface.
                      +
                      +Looking back on this now, there is an alternative that may have been +better: simply extend ORBInitInfo with an internal SPI so that we +could access the ORB directly. The current situation is the result +of a spec compromise: no one could agree on what operations should +be allowed on an ORB instance while it's in the process of initialization, +so a facade object (ORBInitInfo) was specified that sharply restricts +what can be done with the underlying ORB instance. Of course, this +makes it hard to access anyone's ORB extensions from inside an ORBInitializer.
                      +
                      +The current ORBConfigurator we use is replaceable, as is obvious from +the use of the parser to obtain it. For example, we could replace +the current Java-code driven approach with an XML-based approach, +a Lisp-Sexpression approach, something based on the JINI config language +(which is an interpreted simple subset of Java), or some other mechanism. +But this does not seem to be needed today.
                      +
                      +Here is what the ORBConfiguratorImpl configure method does: +
                      1. +Initialize the default object copiers. This is overridden in the app +server init. Object copiers are discussed in more detail in sec:Fast-Object-Copying. +
                      2. Initialize IOR machinery (see sec:IORs for more details). +This involves: +
                        1. +Setting up the tagged profile and tagged profile template factories. +
                        2. Registering the tagged component factories. This could be extended +by the app server init to include CSIv2 related tagged components, +which would remove the need for using the very slow codec APIs. +
                        3. Registering the ValueFactory instances for the ObjectReferenceTemplate +(this is needed so that the ORB knows how to marshal these classes, +since their public interface is an abstract value type). +
                        4. Register the ObjectKeyFactory. +
                        +
                      3. Register the ClientDelegateFactory. +
                      4. Initialize the transport. As noted in the comments, this is complicated +because we support several legacy mechanisms for initialization. The +more preferred mechanism for intializing the transport is simply to +register all required Acceptor instances (but we need a better framework +for creating Acceptors easily, I suspect). But we also have the older +SocketFactory mechanism, as well as a number of even older configuration +parameters. See sec:Transport-Design for a discussion about +the transport design. +
                      5. Initialize naming. This really means setting up the resolvers for +resolve_initial_references and related methods. This provides access +to a name service through either the old bootstrap or the standard +INS mechanisms. Resolvers are discussed in sec:Resolvers. +
                      6. Initializer the service context registry. Just as in the IOR case, +this could be extended by the app server init to include CSIv2 related +service contexts, again avoiding the need for using the codec APIs. +
                      7. Initialize the request dispatcher registry. This is the central mechanism +that ties all of the code together that is needed for invoking and +dispatching in the ORB. This includes: +
                        1. +Registering ClientRequestDispatchers and ServerRequestDispatchers. +
                        2. Registering the special ServerRequestDispatcher used for INS (this +one has no object adapter). +
                        3. Registering the LocalClientRequestDispatchers, which are used for +co-located requests. This includes all of the servant caching optimizations. +One small note on this: we could extend the optimizations significantly +to cache the servant in ALL cases, and then have the POA invalidate +the cache when necessary. Currently we assume that we are caching +only in the ServantLocator case, and we assume that the ServantLocator +always returns the same instance for the same object reference. What +we have now is fully effective for the App Server, so there has been +little incentive to re-visit this issue. +
                        4. register the ServerRequestDispatcher used to handle the bootstrap +mechanism. +
                        5. Register the ObjectAdapterFactories. +
                        +Much of this registration is driven by subcontract IDs. See sec:Subcontract-IDsfor +more details.
                        +
                        +
                      8. Register the initial reference for dynamic any support. +
                      9. Handle the psersistent server initialization. +
                      + + +

                      2.3.3  Initializing the ORB in the App Server

                      + +TBD
                      +
                      +portable interceptors
                      +
                      +PEORBConfigurator
                      +
                      +The ORBManager
                      +
                      + + +

                      2.4  ORB Shutdown

                      + +The primary issue in starting up the ORB is simply to configure all +of the data needed for running the ORB. In contrast, shutdown must +carefully control access to the ORB so that spurious errors do not +occur in requests that are in the middle of being processed.
                      +
                      +Details TBD.
                      +
                      + + +

                      Chapter 3  Dispatch Path Overview

                      + +Here is a simplified sequence diagram describing the overall ORB dispatch +path:
                      +
                      +(discuss this at a high level)
                      +
                      +The next few chapters look at this in more detail through the PEPt +model.
                      +
                      + + +

                      Chapter 4  Presentation

                      + + + +

                      4.1  Stubs and Skeletons

                      + +See mapping specs and dynamic RMI-IIOP document
                      +
                      + + +

                      4.2  Data types

                      + +IDL: basics
                      +
                      +IDL: typecode and any
                      +
                      +Java addtions and value types
                      +
                      + + +

                      Chapter 5  Encoding

                      + +impl.encoding
                      +
                      +impl.io
                      +
                      +impl.util
                      +
                      + + +

                      5.1  Repository IDs

                      + + + +

                      Chapter 6  Protocol

                      + +impl.protocol
                      +
                      +impl.protocol.giopmsgheaders
                      +
                      + + +

                      6.1  Subcontract IDs

                      + + + +

                      6.2  IORs

                      + + + +

                      6.3  Service Contexts

                      + + + +

                      6.4  GIOP Message Representation

                      + + + +

                      Chapter 7  Transport

                      + +The transport is responsible for handling the transfer of data to +and from endpoints. Connection management is also an important part +of the transport, since we most commonly use GIOP as a protocol, and +GIOP is connection based. We also include here the logic that is used +to decide which of several possible endpoints should be used for a +connection.
                      +
                      +The client and the server roles in a CORBA request are distinct, but +both are event driven: messages are normally received by a selector +thread. The client simply needs to get a connection, write the messages +to the connection, and wait for a response. The server is event driven: +it responds to messages received. The server also contains acceptors, +which represent endpoints on which the server listens for new connections,
                      +
                      +connection management
                      +
                      +mapping endpoints to sockets
                      +
                      +message tracing
                      +
                      +acceptors
                      +
                      +listener
                      +
                      +selector
                      +
                      + + +

                      Chapter 8  Other Aspects of the ORB

                      + + + +

                      8.1  Object Adapters

                      + + + +

                      8.2  The RequestDispatcherRegistry

                      + + + +

                      8.3  Encoding Details

                      + + + +

                      8.4  ORB Logging

                      + + + +

                      8.5  ORB Monitoring

                      + + + +

                      8.6  ORB versioning

                      + + + +

                      8.7  ORBD and Server Activation

                      + + + +

                      8.7.1  current model

                      + + + +

                      8.7.2  ideas for using ORT

                      + + + +

                      8.8  Portable Interceptors

                      + + + +

                      8.9  RMI-IIOP Implementation

                      + + + +

                      8.10  Resolvers

                      + + + +

                      8.11  Name Services

                      + + + +

                      8.12  ORB and App Server Integration

                      + + + +

                      Chapter 9  Utilities

                      + + + +

                      9.1  Fast Object Copying

                      + + + +

                      9.2  Dynamic Code Generation

                      + + + +

                      9.3  Useful utilities

                      + + + +

                      9.4  FSM Framework

                      + + + +

                      9.5  Graph Utilities

                      + + + +

                      9.6  JDK 5 Specific Utilities

                      + + + +

                      9.7  Timing Framework

                      + + + +

                      Chapter 10  Living with our legacy

                      + + + +

                      10.1  Testing Principles

                      + + + +

                      10.2  Benchmarking

                      + + + +

                      10.3  FOLB Support

                      + + + +

                      10.4  HWLB Support

                      + + + +

                      Chapter 11  Compilers

                      + + + +

                      11.1  New rmic iiop backend

                      + + + +

                      11.2  idlj

                      + + + +

                      Chapter 12  Future Directions

                      + + + +

                      12.1  Embedded Languages

                      + + + +

                      12.2  Components

                      + + + +

                      12.3  Fast Marshalling

                      + + + +

                      12.4  Security

                      + +include security document here (that I was working on for a while +last summer)
                      +
                      + + +

                      12.5  Better handling of Invocation Info

                      + + + + +
                      This document was translated from LATEX by +HEVEA.
                      + diff --git a/www/design/orb_notes.pdf b/www/design/orb_notes.pdf new file mode 100644 index 000000000..1eacf7b12 Binary files /dev/null and b/www/design/orb_notes.pdf differ diff --git a/www/design/orb_notes001.png b/www/design/orb_notes001.png new file mode 100644 index 000000000..07af1bbfa Binary files /dev/null and b/www/design/orb_notes001.png differ diff --git a/www/design/orb_notes002.png b/www/design/orb_notes002.png new file mode 100644 index 000000000..51d1406f3 Binary files /dev/null and b/www/design/orb_notes002.png differ diff --git a/www/design/orb_notes003.png b/www/design/orb_notes003.png new file mode 100644 index 000000000..1b16bf5b9 Binary files /dev/null and b/www/design/orb_notes003.png differ diff --git a/www/design/orb_notes004.png b/www/design/orb_notes004.png new file mode 100644 index 000000000..3ad29a3e6 Binary files /dev/null and b/www/design/orb_notes004.png differ diff --git a/www/design/orbdArchitecture.html b/www/design/orbdArchitecture.html new file mode 100644 index 000000000..cc7e914ff --- /dev/null +++ b/www/design/orbdArchitecture.html @@ -0,0 +1,2577 @@ + + + + + + + + + + + + + + +

                      +ORBD Architecture for S1AS8/EE

                      +

                      +Draft 0.71

                      +

                      +

                      +

                      +

                      +Ken Cavanaugh

                      +

                      +Harold Carr

                      +
                      +
                      +

                      + Table of Contents

                      +
                      +
                        +
                      1. + Introduction 4

                        +
                      2. + S1AS8/EE ORBD Operation 7

                        +
                      +

                      + 2.1. Main blocks in ORBD model 7

                      +

                      + 2.2. Plugin points for main blocks 7

                      +

                      + 2.3.Use Case: First Invocation, Server Running 7

                      +
                        +
                      1. + ORBD Data Model 10

                        +
                      +

                      + 3.1. Getting ORT Information 11

                      +

                      + 3.2.General ORBD Operation 12

                      +

                      + 3.3. Constructing the Forwarded IOR 13

                      +

                      + 3.4. Contents of IORs 14

                      +

                      + 3.5.Session Beans need Persistent IORs 14

                      +

                      + 3.6. isLocal and Failover 15

                      +
                        +
                      1. + State Maintenance 17

                        +
                      +

                      + 4.1.Starting and Stopping a Node 17

                      +

                      + 4.2.Starting and Stopping a Server Instance 18

                      +

                      + 4.3.Starting and Stopping an Application Instance 18

                      +

                      + 4.4.Starting and Stopping an ORBD 19

                      +
                        +
                      1. + Fault Tolerance 20

                        +
                      +

                      + 5.1.Creation of an Object Adapter 21

                      +

                      + 5.2.Performing an Invocation on x 21

                      +

                      + 5.3.Impact of Orderly Shutdown 22

                      +
                        +
                      1. + Load Balancing 23

                        +
                      2. + Online Upgrades 26

                        +
                      3. + Redundant ORBD 27

                        +
                      +

                      + 8.1.The Redundant Model 27

                      +

                      + 8.2.ORBD startup 28

                      +

                      + 8.3.Redundant ORBD operation 28

                      +

                      + 8.4. Location of ORBD 29

                      +

                      + 8.5. Replication viz-a-viz IOR Size 29

                      +

                      + 8.6. Interoperability with other app servers and clients 30

                      +

                      + 8.7.Allow users to not use ORBD 30

                      +

                      + 8.8. Limitation: cannot add more ORBDs after cluster created 31

                      +

                      + Appendix A. Phased Implementation of S1AS8/EE + ORBD 32

                      +

                      + Appendix B. Template Creation 37

                      +

                      + Appendix C. Future Versions 39

                      +

                      + Appendix D. Rejected Alternatives 45

                      +

                      + Appendix E. Smart Stubs are a Dumb Idea 46

                      +

                      + Appendix F.Constructing IORs from multiple + templates 49

                      +

                      + Appendix G.Epochs for Online Upgrades 50

                      +

                      + Appendix H.Servers Shedding Load and Avoiding Client + Starvation 51

                      +

                      + Appendix I. Other considerations 52

                      +

                      + Appendix J. Data Model Constraints 56

                      +

                      + Appendix K. A Tutorial on J2SE ORBD Operation 57

                      +
                      +

                      Introduction

                      +

                      This document describes infrastructure for +supporting scalability and availability (i.e., load balancing, fault +tolerance and online-upgrades) for IIOP requests in S1AS8/EE. The +general infrastructure is called ORBD (for historical reasons). +However, as we describe the architecture it should become clear that +ORBD is the component in the infrastructure that supports failover +and other components support load-balancing.

                      +



                      +

                      +

                      To understand why an ORBD is useful, suppose an +application is initially deployed on a single server instance, and +then later migrated to a different pair of server instances for +failover. If the original IOR referred directly to the single server +instance it is impossible to make the change transparently. It is +impossible to find all occurrences of the original IOR for arbitrary +CORBA clients. It is also impossible for an application running on +the app server that uses IOR stringification. +

                      +



                      +

                      +

                      Instead, the principal idea is that server IORs +contain ???persistant??? references to ORBDs which then redirect +requests to appropriate servers. In other words, we "nail down" +the address of one part of the system, the ORBD, so that other parts +may have much more dynamic behavior. We then highly optimize the +system based on special domain knowledge (namely DAS and other +information, such as dynamic load information) so that ORBD does not +become a bottleneck).

                      +



                      +

                      +

                      The other principal idea is that once the ORBD has +redirected a request, clients will hold IORs that contain addresses +for replicated servers. The client ORB is then able to choose which +replica to use based on locality and load information.

                      +



                      +

                      +

                      Top-level points:

                      +



                      +

                      +
                        +
                      1. ORBD functionality is lightweight.

                        +
                      2. The use case for ORBD is failover (NOT load + balancing, although ORBD bootstraps the load balancing process by + providing IORs which contain the locations of replicas).

                        +
                      3. CorbaContactInfoList is the load-balancing + point (in the client).

                        +
                      4. An ORBD instance will be colocated with every + server instance (i.e., ORBD does NOT need to be a separate process, + but may be if so desired).

                        +
                      5. ORBD leverages DAS. ORBD caches information + for efficiency.

                        +
                      6. ORBD is NOT responsible for restarting + servers.

                        +
                      7. ORBD maps invocations on location independent + IORs to their CURRENT location. The actual location may change at + any time in any way. ORBD transparently finds the current location + and forwards request appropriately.

                        +
                      8. Load balancing info is piggybacked on server + replies (it may be multicast in future versions).

                        +
                      9. ORBD provides transparent IIOP interop + requirements. +

                        +
                      +



                      +

                      +

                      Why is it better?

                      +



                      +

                      +

                      The ORBD-based ORB/EJB failover design supports +the colocated (web & ejb in the same tier) 90% case while also +providing infrastructure that will allow us to leap-frog the +competition in future

                      +



                      +

                      +
                        +
                      • ORBD supports sophisticated call routing / + load balancing. +

                        +
                      • Ease-of-use: The user will not have to + generate different "smart" stubs for HA..

                        +
                      • No bottle necks, scalable & distributed + design: colocated ORBDs in each serve process.

                        +
                      • ACC and web container use of EJBs is the main + use case for IIOP. The ACC and web container do not have full access + to the DAS information. Use of ORBD provides transparent IIOP + failover in the CORBA layer, rather than imposing DAS access/caching + requirements on the ACC and web containers. +

                        +
                      +



                      +

                      +

                      Why this design is better than S1AS7.0?:

                      +



                      +

                      +

                      ORBD takes the 90% case into some areas that the +non-ORBD approach does not handle (e.g. ACC calling into a replicated +application that is performing an online upgrade).

                      +



                      +

                      +

                      ORBD integration with S1AS8/EE

                      +



                      +

                      +

                      ORBD is integrated with the overall clustering +mechanisms in the application server to handle failover and +load-balancing for IIOP, HTTP, JMS, etc., as a whole. This leverages +the S1AS8/EE mechanisms in the areas of health checks, monitoring +availability of instances and load metrics exchange.

                      +

                      +

                      +



                      +

                      +



                      +

                      +

                      Overview of Document +

                      +



                      +

                      +

                      The remainder of the paper presents a detailed +view of S1AS8/EE ORBD architecture, starting with the data model of +S1AS8/EE from the ORB's point of view. We +then look at how this data model and the ORBD operation presented +earlier operate with respect to state maintenance, +fault tolerance, load balancing, online upgrades and redundant ORBDs. +Appendices give fine-grained details necessary to implement ORBD. +(These appendices are not necessary for a general understanding of +the ORBD.)

                      +



                      +

                      +

                      Background Assumptions

                      +



                      +

                      +

                      This document assumes a basic familiarity with +Interoperable Object References (IOR), the Portable Object Adapter +(POA), Portable Interceptors (PI) and the +Object Reference Template (ORT) as described in the CORBA 3.0 +architecture specification. It also assumes familiarity with the +CORBA mechanisms used to support load-balancing, fault tolerance and +online-upgrades: client-side stub operation, addressing and request +retry mechanisms, ORT exchange and LOCATION_FORWARD . This document +contains a section ???A Tutorial on J2SE ORBD Operation??? which +illustrates these mechanisms with several use cases. We emphasis that +this material is NOT specifying the S1AS8/EE ORBD. It IS a tutorial +and can be safely skipped if one already understands the basic +mechanism.

                      +

                      +S1AS8/EE ORBD Operation

                      +

                      Main blocks in ORBD model

                      +
                        +
                      • Client: the + client makes invocations on RMI-IIOP references. Those invocations + need to continue to work in the presence of failures and + online-upgrades. The invocations should be load-balanced across + server instances.

                        +
                      • Server: the + server is managed by the DAS.

                        +
                      +
                        +
                      • ORBD: enables an IOR to survive a wide + range of faults and administrative changes in application + configuration. +

                        +
                      +

                      Plugin points for main blocks

                      +
                        +
                      • Client: CORBAContactInfoList : + client-side dynamic load-balancing plug-in point. Enables + flexibility in routing policies and the ability for administrators + to use different algorithms or tune parameters for the default ones + we provide. CorbaContactInfoList abstracts IORs. It is responsible + for updating the effective IOR and for selecting an appropriate + address for an invocation.

                        +
                      +
                        +
                      • Server: ServerRequestInterceptor and/or + ServantManager: these points can do load-shedding, add server + load metrics as reply service contexts or multicast load metrics.

                        +
                      +
                        +
                      • ORBD: ServerInstanceMetric: this is + the main point that the ORBD gets information on the state of the + cluster. +

                        +
                      +

                      Use Case: First Invocation, Server Running

                      +

                      This use case makes the following assumptions:

                      +



                      +

                      +
                        +
                      1. N application server replicas have all been + activated and completed their registration and ORT exchange with M + redundant ORBDs.

                        +
                      2. The N application server replicas each + created IOR O1,2,...,M/x and bound that IOR in naming using the same + name.

                        +
                      3. The IOR has been resolved from naming + resulting in a stub with its target IOR and effective IOR fields + both set to O1,2,...,M/x. +

                        +
                      +

                      The following figure shows the basic operation of +the S1AS8/EE ORBD when a client makes an initial invocation on a +stub:

                      +



                      +

                      +




                      +

                      +
                        +
                      1. The client invokes a method + on the stub. The stub uses the effective IOR O1,2,...,M/x to service + the invocation. The client ORB selects a profile from the IOR, say + O1/x.

                        +
                      2. ORBD receives the request.

                        +
                      3. ORBD maps the request to + the appropriate ORT.

                        +
                      4. ORBD creates a new IOR, + S1,2,...,N/x using the object ID x from the request.

                        +
                      5. ORBD returns a + LOCATION_FORWARD response with IOR S1,2,...,N/x.

                        +
                      6. The stub sets its effective + IOR field to S1,2,...,N/x. The client ORB transparently retries the + request using the new IOR. The client ORB selects a profile from the + IOR, say S1/x.

                        +
                      7. The request is sent to + server S1.

                        +
                      +



                      +

                      +

                      If S1 is not available the a different profile +would be chosen from the effective IOR and +the request would be transparently retried, in this example to S2 and +then to S3.

                      +



                      +

                      +

                      If all SN are not available the client ORB would +fall back to the target IOR and select a profile, say O1. If ORBD O1 +is not available then a different profile from target IOR is +selected, possible resulting in requests directed to O2, ..., OM.

                      +

                      ORBD Data Model

                      +

                      ORBD maintains its own information model for two +reasons:

                      +



                      +

                      +

                      1. To cache information locally for performance

                      +

                      2. To provide only the information needed for +ORBD.

                      +



                      +

                      +

                      The only state the ORBD maintains is a map of +server-id/orb-id/poa-id to ORT (there is an ORT for each EJB type).

                      +



                      +

                      +

                      The following diagram gives a sketch of the data +of interest to ORBD. In part the data represents the natural +containment hierarchy from the Cluster down +to a particular object adapter instance. Here we are assuming that +each EJB type has its own object adapter (a POA instance). Also note +that we have introduced an ApplicationInstance +into the model to represent a grouping of related EJB types that form +some sort of application.

                      +



                      +

                      +




                      +

                      +

                      Getting ORT Information

                      +

                      For each replica, ORBD only needs it +ObjectReferenceTemplate (ORT). The DAS has all of the information +globally available that is used to create (at deployment time) beans +(i.e., IORs), which results in the creation of the object reference +template.

                      +



                      +

                      +

                      The ORBD in each app server instance computes ORTs +using the instances DAS cache. Instead of updating multiple ORBD +instances with ORT information, we update DAS, which makes the +information available in all server instances. This does not assume +that DAS is always running. There must have been sometime when DAS +was running so that the system could be installed. DAS will also be +needed whenever major changes in deployment are needed, such as +adding or removing nodes or server instances, or redeploying +applications. +

                      +



                      +

                      +

                      Rejected alternatives:

                      +



                      +

                      +

                      1. Direct exchange between each server instance +and the replicated

                      +

                      ORBD.

                      +



                      +

                      +

                      2. At each bean deployment, register the ORT for +the deployed bean (or

                      +

                      replica) with the DAS. Each server instance +then has access to the

                      +

                      ORT. The ORT is also persistent, and the ORT +for a persistent POA

                      +

                      will be valid between restarts of the POA or +the server instance

                      +

                      that contains the POA.

                      +



                      +

                      +

                      What this second possibility is, is simply +using the DAS to mediate

                      +

                      the template exchange between ORBD and the +server instance. This

                      +

                      avoids direct communication between ORBD and +the server instances. +

                      +

                      General ORBD Operation

                      +

                      The primary function of ORBD is to redirect +incoming requests to an appropriate server instance in a cluster. +ORBD supports this function by maintaining a snapshot (not +necessarily perfect) of the state of the nodes and server instances +in a cluster. State maintenance in a cluster where different +components are starting and stopping is a significant part of the +ORBD architecture and will be discussed in detail in later sections.

                      +

                      In order to understand how ORBD handles an +incoming request, we first need to look at how IORs are created. All +IORs are created from a POA instance using the +create_reference_from_id method, which is supplied type id and object +id arguments. The object id is a unique identifier for the IOR in the +context of this particular POA. In the app server, this is typically +derived from the primary database key for the EJB state.

                      +

                      create_reference_from_id delegates to the +make_object method on the ORT instance associated with the POA. +

                      +

                      The POA is created by the container whenever an +EJB type is deployed in the container. Each POA instance gets part of +its template created from the ORB that created the POA. An ORBD +IORInterceptor is also installed in the +ORB. All of this operates as follows to create the POA:

                      +
                        +
                      1. parent.create_POA( + name, policies) is called on the parent of the POA being created + (which may be the ORB's root POA, which is always present).

                        +
                      2. The new POA constructs its ObjectKeyTemplate + oktemp

                        +
                      3. The new POA calls ORB.createIORTemplate( + oktemp ). The ORB then uses the ObjectKeyTemplate oktemp to create + an IORTemplate, and adds profile templates + for each protocol registered with the ORB to the IORTemplate. The + IORTemplate is returned.

                        +
                      4. The POA creates its ObjectReferenceTemplate + from the IORTemplate returned in step 3.

                        +
                      5. The ORBD IORInterceptor + components_established method is called.

                        +
                      6. The interceptor gets the POA instance's + current ObjectReferenceTemplate (which was just + created in step 4.) and registers this template with ORBD.

                        +
                      7. ORBD creates/finds its own template that + corresponds to the one being registered and returns that template.

                        +
                      8. The interceptor sets the current factory for + the POA instance to the one returned from ORBD.

                        +
                      +

                      At this point, any create_reference call to the +POA results in an IOR that is handled by ORBD.

                      +

                      Incoming requests for ORBD are directed to a +particular ObjectAdapter. Each +ObjectReferenceTemplate (the template field in the ObjectAdapter) is +identified by server ID, orb ID, and object adapter ID. This triple +must be unique throughout the cluster. The basic operation of ORBD in +handling an incoming request can then be summarized as:

                      +
                        +
                      1. Get the (server ID, orb ID, + object adapter ID) from the incoming request.

                        +
                      2. Find the ORBD ObjectAdapter + using (server ID, orb ID, object adapter ID).

                        +
                      3. Get the set of applicable + ObjectAdapter instances by applying the ObjectAdapterReplicas + relation to the ORBD ObjectAdapter for this request.

                        +
                      4. From the templates for this + set of ObjectAdapter instances, construct an IOR.

                        +
                      5. Use the + ServerRequestInterceptor to send the IOR + back to the client as a LOCATION_FORWARD reply, causing the client + to transparently redirect the invocation to the new IOR. (Note, this + redirection only occurs on initial requests or after failures or + redirections from the server.)

                        +
                      +

                      Exactly how the forwarded IOR is constructed is +the subject of the next section.

                      +

                      Constructing the Forwarded IOR

                      +

                      We have defined a ServerInstanceMetric +interface, in the data model, which is intended to represent the +capability of a server instance to handle additional load. We assume +that 0 indicates an unloaded server instance and MAX_INT represents a +server instance that cannot accept additional load (which could be a +server instance that is not running). How this is computed is outside +the scope of the ORBD design. The implementation of +ServerInstanceMetric is pluggable in ORBD.

                      +



                      +

                      +

                      In a highly-available system ORBD will contain a +collection of ORTs corresponding to the +server and application replicas under various loads. Given this +collection, the ORBD makes a choice in constructing the IOR based on +the ServerInstanceMetric. Two possibilities are:

                      +
                        +
                      1. Pick the template whose ObjectAdapter's + ServerInstance has the lowest metric. + Construct the IOR using that template.

                        +
                      2. Sort the list of templates into lowest to + highest order based on the ObjectAdapter's ServerInstanceMetric + values. Construct an IOR using all of these templates in such a way + that a client will try the profiles corresponding to the lower + metric values first.

                        +
                      +



                      +

                      +

                      Other variations are possible too, such as only +using those templates that correspond to +server instances that are actually running at the time the call is +made. In this paper we use option 2, as this is the best option for +spreading the load of handling failures to the clients, rather than +just to the ORBD.

                      +



                      +

                      +

                      The ServerInstanceMetric may be implemented in a +variety of ways. It may cache information inside an object plugged +into ORBD, or it may simply contact an external agent for load +information. Design of the ServerInstanceMetric is outside the scope +of the ORBD architecture. In any case, the ServerInstanceMetric +implementation is plugged into the initialization of ORBD itself.

                      +



                      +

                      +

                      Contents of IORs

                      +

                      Two profiles. One profile contains +TAG_ALTERNATE_IIOP_ADDRESS TAGGED_COMPONENTS with server instance +addresses. The other profile contains TAG_ALTERNATE_IIOP_ADDRESS +TAGGED_COMPONENTS with ORBD addresses. The ORBD profile also +contains a TAGGED_COMPONENT which indicates it is a profile for an +ORBD. That way our CorbaContactInfoList will only use it after +trying all server instance addresses. A foreign client would not +necessarily be smart but it would be operational. +

                      +



                      +

                      +

                      Session Beans need Persistent IORs

                      +

                      The S1AS7 EJB to POA mapping assumes that session +beans are mapped to transient POAs. The template for a transient POA +changes (e.g., time-dependent element) every time the POA is +instantiated, and so it cannot be stored in DAS.

                      +



                      +

                      +

                      To enable fault tolerance, load balancing and +online upgrades for all IORs, the app server should not use transient +POAs. All references should be be created with POAs with a +PERSISTENT policy. In this case the app server would manage +transience itself.

                      +



                      +

                      +

                      Note: by definition, a transient POA can never be +re-started and produce the same object references. It is possible +that we do not want to use transient POAs for stateless session beans +in the presence of replicas, because the lifetime of the replica can +be less than the lifetime of the object reference, and the transient +POA is tied to the lifetime of the replica. ORBD allows us to get +around this problem too, but all ORBD replicas need to be updated +with newly created transient POA templates, which is potentially +expensive if there are a lot a replicas.

                      +

                      isLocal and Failover

                      +

                      Util.isLocal determines the locality of an object +on the host, port, and server ID of the effective target IOR. For +failover we use the ORBD addresses in the IOR, but make a local call +to the local ORBD (when available).

                      +



                      +

                      +

                      Scenario: a client holds an IOR to an EJB which is +colocated in the same JVM. The IOR is saved into some persistent +state (file/DB).

                      +



                      +

                      +

                      Case 1: The target EJB is a Stateless SessionBean +(transient POA). The server crashes, restarts and reads the saved +IOR. The client component invokes the remote IOR (note that it +contains the transient port of the previous incarnation of the +server). A good way to support this is to make all IORs persistent +and manage transience in the app server itself.

                      +



                      +

                      +

                      Case 2: The target EJB is an EntityBean +(persistent POA). The server crashes, and failsover to another JVM +with a different persistent port. The 2nd JVM loads the client +component and EntityBean, The client reads the saved IOR and invokes +on it. The client's effective target IOR still points to the downed +server. It invokes and fails. So it tries other servers or fails +back to the ORBD. If it fails back to the ORBD then the ORBD will +construct a new effecive target IOR which will contain the failed and +restarted/moved server's new address.

                      +



                      +

                      +

                      Note that if isLocal returns true then the +invocation will work because the EntityBean can be activated in the +second server.

                      +



                      +

                      +

                      This assumes that there is a singleton ORB +instance in a JVM, and IORs are "connected" after +deserialization. +

                      +

                      State Maintenance

                      +

                      ORBD needs to be +informed about state changes in nodes, server instances, application +instances, and object adapters. Some of these can be handled within +the ORB framework while others will require access to configuration +information maintained in the cluster and to state changes in +entities such as nodes.

                      +

                      Since JMX is the basic mechanism for management +and monitoring in S1AS, ORBD uses JMX to obtain information about the +state of nodes, server instances, and applications. Some events are +detectable within the ORB framework itself, such as the +ServerInstance starting and terminating cleanly (via Portable +Interceptors and other mechanisms). The ORB provides all necessary +information about the object adapters running inside an ORB instance +(note, we are assuming a single ORB per server instance). +

                      +

                      Grouping of object adapters into applications is +not directly determinable from the ORB itself, as the concept of an +application is at the EJB container level, and at the administration +data level. We could decide to establish a +convention for POA usage such that each application instance has a +separate POA manager. Further details here await the detailed changes +in the EJB container design.

                      +

                      Starting and Stopping a Node

                      +

                      State changes in nodes are tracked by ORBD to +allow for accurate handling of node failure. The +interesting cases include:

                      +
                        +
                      1. A running node fails. In + this case, all server instances, + application instances, and object adapters under the node can be + presumed to fail as well. The ServerInstanceMetric must go to + MAX_INT for server instances contained in the failing node, so that + the failed nodes will not be chosen by a client. ORBD will need to + clean up all data configured associated with the failed node. This + includes:

                        +
                      +
                        +
                      • Changing + the state of all server instances and ORBs + to shut down.

                        +
                      • Destroying + all object adapter instances associated with the node.

                        +
                      +
                        +
                      1. A running node is shutdown. + Here we want a graceful shutdown of all components. ORBD will stop + forwarding requests to any object adapter contained in the node. + Each server instance will need to shutdown its ORB instance, which + will cause any pending requests to be completed, and prevent new + pending requests from starting.

                        +
                      2. A configured node starts. + ORBD observes the startup of the node (via the Server watchdog + object) so that it is prepared for the startup of contained server + instances, application instances, and object adapters. ORBD will not + dispatch traffic to any of the contained components until that + component is up and running. (Note that this may affect the + determination of the server metric, in that a ServerInstance may be + up and running with a low metric before an ApplicationInstance is + fully initialized. In this case it may be necessary to increase the + server metric applied to an object adapter in the + ApplicationInstance until the ApplicationInstance is fully + initialized.)

                        +
                      3. A new node is configured. + This is similar to the previous case. The only difference is that a + new node may be configured while the cluster is fully up and + running, but we do not think matters for ORBD operation.

                        +
                      +



                      +

                      +



                      +

                      +

                      Starting and Stopping a Server Instance

                      +



                      +

                      +
                        +
                      1. A running server instance + fails. ORBD finds out about this by monitoring a server watchdog + object. ORBD marks all application instances as down and destroys + the object adapters. +

                        +
                      2. A running server instance + is shut down. This should basically be the same as case 1.

                        +
                      3. A configured server starts. + ORBD marks the server instance as being up.

                        +
                      4. A new server instance is + configured. Basically the same as 3, except that a new + ServerInstance object must be created.

                        +
                      +

                      +

                      +

                      +

                      Starting and Stopping an Application Instance

                      +



                      +

                      +

                      In this case we do not have a concept of abnormal +shutdown as the server instance should handle any errors that occur +in an application instance.

                      +
                        +
                      1. A running application + instance is shut down. ORBD finds out about this at the beginning of + the shutdown process and stops directing traffic to the instance. + The normal POAManager shutdown happens + afterwards, allowing a clean shutdown.

                        +
                      2. A configured application + instance starts up. The ORB marks the application instance as being + up.

                        +
                      3. A new application instance + is configured. Same as 2, except that a new ApplicationInstance + object is created.

                        +
                      +



                      +

                      +



                      +

                      +

                      Starting and Stopping an ORBD

                      +



                      +

                      +

                      tbd...

                      +

                      Fault Tolerance

                      +

                      Fault tolerant behavior is implicit in what has +already been discussed. To see this, we will consider:

                      +
                        +
                      1. A normal request.

                        +
                      2. A request that fails in + different ways.

                        +
                      +

                      Let's assume that we have ServerInstance S1 and +S2, each containing an ApplicationInstance A, and that each +ApplicationInstance contains a POA P. Then we have POAs S1/A/P and +S2/A/P in the cluster, each of which can handle requests for this +application. Also note that we have ReplicaGroup +R which contains S1/A and S2/A, and ObjectAdapter instance O for R. +The GroupApplicationInstances, +GroupObjectAdapters, ObjectAdapterReplicas, +and ApplicationObjectAdapters relations are +described in the following diagram.

                      +



                      +

                      +




                      +

                      +

                      This diagram includes all elements from the ORBD +data model shown on page 10 (except for the ServerInstanceMetric). +The cluster and ORB nodes are also included here for clarity. Note +that they are otherwise ignored in this example, as there is only +one cluster, and each ServerInstance in S1AS 8 contains only one ORB +instance.

                      +

                      Creation of an Object Adapter

                      +
                        +
                      1. ServerInstance S1 creates + ObjectAdapter S1/A/P

                        +
                      2. ORBD IORInterceptor runs + for S1/A/P

                        +
                      +
                        +
                      1. IORInterceptor + sends ObjectReferenceTemplate for S1/A/P to ORBD.

                        +
                      2. ORBD + notes that the received template is for S1/A, uses the + GroupApplicationInstance relation to + discover that this is part of ReplicaGroup + R, and that its ObjectAdapter O is used for A/P (if this is the + first request, ORBD creates an ObjectAdapter O to use for A/P).

                        +
                      3. ORBD + returns ObjectReferenceTemplate for O to S1.

                        +
                      4. S1/A/P + installs ObjectReferenceTemplate for O as its current factory

                        +
                      +

                      At this point, the object adapter is ready to +create IORs. When it creates an IOR with object ID x, call it IOR/x, +it will use the template for object adapter O in ORBD, causing +invocations on IOR/x to be handled by ORBD.

                      +

                      Performing an Invocation on x

                      +

                      An invocation on x proceeds as follows:

                      +
                        +
                      1. Client invokes an + operations on x.

                        +
                      2. Client ORB sends a request + to x (which points to ORBD).

                        +
                      3. ORBD receives the request + on x.

                        +
                      4. ORBD obtains the object id + xid from the request on x.

                        +
                      5. ORBD obtains the + ObjectAdapter O that corresponds to x.

                        +
                      6. ORBD finds the + ObjectAdapter instances S1/A/P and S2/A/P that are related to O by + the ObjectAdapterReplicas relation.

                        +
                      7. ORBD uses the templates + from S1/A/P and S2/A/P to construct a new template M.

                        +
                      8. ORBD constructs another IOR + IOR/ y by calling M.make_object( xid ).

                        +
                      9. ORBD sends a + LOCATION_FORWARD response to the client containing IOR/y.

                        +
                      10. Client ORB chooses a + profile p from y to use for the next request.

                        +
                      11. Client ORB sends a request + using profile p.

                        +
                      12. The application instance + corresponding to profile p handles the request.

                        +
                      +

                      Failures are handled as follows:

                      +
                        +
                      1. Client ORB receives a + SystemException for the request.

                        +
                      2. If the error cannot be + retried, the error is returned to the client. This happens, for + example, if the completion status is COMPLETED_MAYBE or + COMPLETED_YES, in which case the operation cannot be retried.

                        +
                      3. If the error can be + retried, the client ORB looks for another profile in IOR y.

                        +
                      4. If another profile is + found, use it to retry the invocation. Steps 1-4 can be repeated + until no more profiles are available.

                        +
                      5. After the profiles are + exhausted, fall back to IOR x, which points to ORBD. +

                        +
                      +

                      A limit may be placed on the total number of +requests for an invocation to avoid various scenarios that can result +in never-ending invocations.

                      +

                      Impact of Orderly Shutdown

                      +

                      It should be possible to shutdown a server +instance cleanly, so that no spurious failures are observed in an ORB +client. This is handled by calling ORB.shutdown(true), +which will not return until a clean ORB shutdown has completed. +Before the shutdown call, the ORB accepts all calls (ignoring +POAManagers for now). After shutdown, all +new calls are rejected with a BAD_INV_ORDER error, with completion +status COMPLETED_NO. This tells the client that the operation can be +safely retried. All calls that are currently in process in the ORB +continue and cause the shutdown operation to block until all pending +operations in the ORB have completed. After they all complete, the +ORB will shutdown all object adapters and transports, and finally +return from the shutdown call.

                      +

                      ORBD is informed of the state change in the +ServerInstance as soon as shutdown starts, so that it does not direct +new traffic to the instance that is being shutdown. +

                      +

                      Load Balancing

                      +

                      Load Information

                      +



                      +

                      +

                      We need to design +mechanism to compute and propagate load/availability information such +as:

                      +
                        +
                      • Server instance availability

                        +
                      • Server instance load

                        +
                      • Server instance + EJB type load

                        +
                      +



                      +

                      +

                      That +computation/propagation is NOT a function of the ORBD, but must be in +place.

                      +



                      +

                      +

                      Initially load +information will be piggybacked onto replies in server load service +contexts This updates a client cache of server load information. That +cache is used by CorbaContactInfoList to make subsequent address +choices for invocations.

                      +



                      +

                      +

                      Using Load Information

                      +



                      +

                      +

                      The client-side CorbaContactInfoList is the +primary consumer of load information. It uses load information +contain in server reply service contexts.

                      +



                      +

                      +

                      For clients that are not running our ORB servers +can load-shed by doing a LOCATION_FORWARD back to the ORBD (via +ServerRequestInterceptor or ServantManager). (Servers can also do a +LOCATION_FORWARD when new server instances are added.)

                      +



                      +

                      +

                      ORBD ServerInstanceMetric may also be a consumer, +but that is not required. Again: ORBD does not give the client +information about load, that is not its function. ORBD can make some +use of load information, although this is not necessary. In fact, +ORBD need not be aware of load at all: we make load balancing +decisions in the client.

                      +



                      +

                      +

                      ORBD is primarily the bootstrap point for +load-balancing and the last chance point for failover. It is not the +primary point for load-balancing (although it might use +load-balancing information when constructing a LOCATION_FORWARD IOR).

                      +



                      +

                      +



                      +

                      +

                      Location of load-balancing decisions

                      +



                      +

                      +

                      * In the client (e.g. CORBAContactInfoList). This +is the option we are pursuing.

                      +



                      +

                      +

                      There is only one limitation with this approach: a +cluster can evolve (e.g., add/remove server instances, online +upgrades of instances one-at-a-time) in all ways except that the +number of ORBD instances cannot change. (That limitation could be +overcome by using IP multicast.)

                      +



                      +

                      +

                      Note: ORBD instances can migrate: ORBD IP +addresses are mapped to to different via DHCP or DNS.

                      +



                      +

                      +

                      It is useful to put some adaptive decisions in the +client since it does not consult the ORBD on each invocation. After +failover, the client's adaptive CorbaContactInfoList decides how to +choose another address to service an invocation. The adaptive +mechanism can use load information obtained via server reply load +service contexts, periodic polling, IP multicast (if enabled), etc.

                      +



                      +

                      +

                      ORBD participation in Load-Balancing

                      +



                      +

                      +

                      The main area that needs further discussion is +dynamic handling of changing load and load shedding.

                      +



                      +

                      +

                      This architecture assumes that the +ServerInstanceMetric reflects the dynamically changing load in the +system. The design of the ServerInstanceMetric in ORBD must take into +account considerations of timeliness of information vs. load on the +system to maintain the information. In any case, we will assume that +the metric maintains a reasonably close correspondence to the true +load in the system.

                      +



                      +

                      +

                      Let us assume that the scenarios are as described +in the fault tolerance section, and discuss what happens when a +server instance becomes overloaded:

                      +
                        +
                      1. The server instance detects + an overload situation and (indirectly) informs the Server + InstanceMetric in ORBD by updating the + metric values.

                        +
                      2. An incoming request is + received by the server.

                        +
                      3. A load balancing + ServerRequestInterceptor looks at the server instance load for each + request. When the load is too high, the interceptor starts + forwarding incoming requests back to ORBD.

                        +
                      4. The ORB client that sent + the request transparently sends another request to ORBD.

                        +
                      5. ORBD operates as usual, + using the ServerInstanceMetric which now causes ORBD to use a + different ordering of profiles according to the Server + InstanceMetric.

                        +
                      6. The client + receives a new IOR from ORBD, picks a profile (which should + be for a non-overloaded server instance), and sends the request to + the server.

                        +
                      +

                      The main design challenge here will be to make +sure that load balancing does not exhibit pathological behavior under +heavy load. We do not want excessive numbers of LOCATION_FORWARDs +in an attempt to balance load too dynamically. We also do not want to +lose invocations in endless sequences of forwarding between different +server instances and ORBD.

                      +



                      +

                      +

                      Client participation in Load-balancing

                      +



                      +

                      +

                      Whenever a request is sent, the client ORB can +choose the best profile to use through the CORBAContactInfoList +implementation. This require CorbaContactInfoList to know about the +state of the cluster via load-info piggybacked on server replies or +via multicast server load from servers.

                      +



                      +

                      +

                      Online Upgrades

                      +

                      Online upgrades is are similar to the previous +scenarios for fault tolerance and load balancing. Suppose we wish to +shutdown S1/A and replace it with a new version of the application, +S1/A2. In order for this to work, implementations A and A2 must have +the same object adapters, and those object adapters must have +compatible interfaces (basically this means assignment compatibility +in Java). The upgrade proceeds as follows:

                      +
                        +
                      1. S1/A2 is deployed and made ready to start.

                        +
                      2. An orderly shutdown of S1/A is begun. This is + most easily arranged if A has a single POAManager for all its POA + instances.

                        +
                      3. After the shutdown of S1/A is completed, S1/A + is destroyed.

                        +
                      4. At this point, all new requests are + redirected to S2/A, either by ORBD or by ORB client side retries.

                        +
                      5. S1/A2 is started. It registers its components + with ORBD.

                        +
                      6. Traffic begins being handled by S1/A2. If all + goes well, S2/A can then be upgraded to S2/A2 in a similar fashion.

                        +
                      +

                      It may happen that the online +upgrade fails. In that case, S1/A2 must be ???upgraded??? to S1/A, +which reverts to the original state.

                      +

                      Redundant ORBD

                      +

                      ORBD is redundant to avoid becoming a single point +of failure. Each instance of ORBD runs with each server replica. This +automatically means ORBDs are monitored and restarted as part of the +server instance.

                      +

                      The Redundant Model

                      +

                      Each cluster has some predetermined number of ORBD +instances O1 ... On. Each ORBD instance is assigned a unique host +name, which we will refer to as name1 through namen. +Each ORBD instance also has a fixed port. Call these port1 .. portn. +We will assume that each ORBD has a unique Object Key, probably +???ORBD??? or something similar. Then each ORBD instance registers a +suitable IOR in naming under the name ORBD. A server that needs to +call a method on an ORBD instance can then use INS as follows to get +to ORBD:

                      +
                        +
                      1. Create a URL of the form + ???corbaloc::{host}:{port}/ORBD???

                        +
                      2. Use ORB.string_to_object + to convert the URL into a generic stub containing an IOR for the + ORBD.

                        +
                      3. Narrow the stub to the ORBD type.

                        +
                      +

                      This allows a client of ORBD to construct a stub +for ORBD knowing only the host and port at which ORBD is running. +(This is the mechanism that is also used in order to bootstrap the +naming service.) This avoids dependencies on naming for the basic +ORBD/Server functionality, which avoids any need for a replicated +naming service in the design of ORBD.

                      +

                      The server (i.e. The IORInterceptor code) can then +inform all of the ORBD instances of ORB events of interest to ORBD, +such as the creation of an object adapter. The easiest way to do this +is simply to successively invoke the method on each ORBD instance.

                      +



                      +

                      +

                      One important consideration is what happens in the +IORInterceptor with all of the ORBD templates that are received from +the different ORBD instances. As discussed in Appendix B, all of the +templates are merged together to construct a single template. There +is an issue here about how to handle a failed ORBD that causes a +failure in the template exchange.

                      +

                      ORBD startup

                      +

                      When an ORBD instance starts up, it must +synchronize its internal state with the state of the system. It does +this by consulting the DAS cache in the server instance in which it +is running.

                      +



                      +

                      +

                      Rejected alternative:

                      +



                      +

                      +

                      The ORBD instance uses JMX to discover the basic +configuration of the system. After the ORBD knows the IP address and +port for every ServerInstance, the ORBD instance uses INS to +construct an IOR for an object that must be present in every +ServerInstance. This IOR is then used by ORBD to query each +ServerInstance for ORB, ApplicationInstance, and ObjectAdapter +information.

                      +

                      Redundant ORBD operation

                      +

                      This is the same as in normal case, described in +???General ORBD Operation???. IORs contain a host/port for each ORBD +instance. The client ORB, during method invocation, chooses one +host/port and invokes the method. Since each ORBD replica has the +same state, it does not matter which replica is chosen. If a request +to one replica fails, the client will choose a different request +until the request is handled.

                      +



                      +

                      +

                      Rejected update alternative:

                      +



                      +

                      +

                      The IORInterceptor must register its ORT with each +ORBD instance when the components_established method is called. The +IORInterceptor then gets back several templates, one from each ORBD. +The interceptor then fuses these templates together, as previously +described for ORBD. This fused template then becomes the current +factory for the POA.

                      +

                      Location of ORBD

                      +

                      There is NO separate ORBD process. This eases +process adminsitration. We need an attribute in server.xml to +configure an ORBD when it needs to be exposed to remote clients. +

                      +



                      +

                      +

                      Note: it is possible to run ORBD functionality as +a separate process or in appserver instances.

                      +



                      +

                      +

                      One consideration is reliability. If ORBD is run +in a separate JVM, far fewer classes are loaded, its execution is +more predictable, and there will likely be fewer scenarios that can +result in JVM failure.

                      +



                      +

                      +

                      Another consideration is ease-of-implementation: +ORBD needs a lot of the infrastructure present in the app server +process (e.g., DAS cache, server monitoring, startup). Putting the +ORBD in an app server instance avoids the need to manage separate +ORBD processes.

                      +



                      +

                      +

                      It is not necessary to run ORBD in every app +server instance. Any instance may run ORBD if configured to do so.

                      +



                      +

                      +

                      Another consideration is evolution. How much +change is allowed after the app server cluster is installed. ORBD +allows both the number and location of EJB replicas to change +dynamically. The location of ORBD repliaces can change dynamically +by using DNS names (rather than IP addresses) in ORBD IIOP profiles +that are resolved via DNS. The only thing that cannot easily change +dynamically is the number of ORBD instances which is wired into every +IOR that an app server creates. That limitation can be removed by +using IP multicast to broadcast ORBD locations.

                      +

                      Replication viz-a-viz IOR Size

                      +

                      For redundancy, every IOR must refer to at least +two ORBD instances.

                      +



                      +

                      +

                      If every server instance runs an ORBD for a large +cluster this may lead to large IORs and longer update times for all +of the ORBD replicas.

                      +



                      +

                      +

                      In a homogeneous environment, instead of having a +separate profile for each app server instance, we can have a single +profile containing TAG_ALTERNATE_IIOP_ADDRESS TAGGED_COMPONENTs with +host/port information for each app-server instance. This reduces the +size of IORs. However, their may be issues with online upgrades +having different information. In that case a separate profile for +the upgraded app server. Once all app servers were upgraded the +system could revert to a single profile again. +

                      +

                      Interoperability with other app servers and +clients

                      +

                      Interoperability is achieved by adherence to OMG +standards. If we generate IORs with multiple standard IIOP profiles +or single IIOP profiles containing TAG_ALTERNATE_IIOP_ADDRESS, we are +as compliant as we can be. Exactly how an ORB handles such an IOR is +not specified by the the core CORBA standard. (The CORBA +fault-tolerant specification defines a variant of IOR called an IOGR +that does specify the correct semantics. However, we cannot depend +on that existing in other vendor's products.)

                      +



                      +

                      +

                      ORBD makes the system more interoperable with +other ORBs. ORBD is build on the standard location forward mechanism +that all GIOP implementations must support. We can do some load +balancing and failover for clients that are not running on our ORB, +by having our servers send LOCATION_FORWARDs back to ORBD whenever +they are overloaded. +

                      +



                      +

                      +

                      Note: any client-side LB/FO we do via +CORBAContactInfoList is not standard.

                      +

                      Allow users to not use ORBD

                      +

                      In the case were users are going with a colocated +deployment model it would be useful to not deploy ORBD. ORBD only +needs to be present when for RMI-IIOP ACC clients or when segregated +web tier applications access EJBs on a separate cluster.

                      +



                      +

                      +

                      The colocated only model may benefit from a server +instance ORB using a "local-only "transport option that +initializes a local object that can never be marshaled and ensure +that the colocated request dispatcher optimization is always used.

                      +



                      +

                      +

                      In this case customers should be using local EJBs, +but may not for various reasons (i.e., the ability to change +configuration without recoding). +

                      +

                      Limitation: cannot add more ORBDs after cluster +created

                      +

                      One significant issue in this design is that more +ORBD instances cannot easily be added after a cluster is created. The +existing ORBD instances may be moved to different nodes as desired, +but the number must stay fixed as otherwise persistent ORBD IORs will +not be preserved. +

                      +



                      +

                      +

                      We do not know of an easy solution to this +problem. One solution is to use IP multicast to communicate with ORBD +instances. All that is needed is an IP multicast call to locate ORBD +instances, which can then be handled in the normal multiple profile +IOR manner. It is possible to build such a proprietary IIOP extension +and incorporate this into the PEORB, although it is not a trivial +undertaking. Probably the larger issue is simply whether most +customers would accept the use of IP multicast in an app server, as +this is still not a commonly deployed protocol.

                      +



                      +

                      +
                        +
                      1. + Phased Implementation of S1AS8/EE ORBD

                        +
                      +



                      +

                      +

                      Phase 1 - Simple remote client failover

                      +



                      +

                      +

                      No ORBD.

                      +



                      +

                      +

                      At deployment/redeployment add/remove server time, +DAS pushes config info to all server instances.

                      +



                      +

                      +

                      ORB config:

                      +



                      +

                      +

                      Every server instance has IORInterceptor. When +each server instance creates POAs the IORInterceptor reads the +configuration information and adds a TAG_ALTERNATE_IIOP_ADDRESS +TAGGED_COMPONENT for each server replica.

                      +



                      +

                      +

                      Every server instance, ACC and servlet container +has CorbaContactInfoList. It always tries to use a colocated +invocation if possible. Otherwise it chooses a +TAG_ALTERNATE_IIOP_ADDRESS in list order. It could also round robin +through remote addresses.

                      +



                      +

                      +

                      Enables:

                      +



                      +

                      +

                      Simple remote client failover (and load-balancing +via round-robin).

                      +



                      +

                      +

                      Not supported:

                      +



                      +

                      +

                      Container local failover. If the server instance +does down and comes up the old "colocated" IORs will not be +valid - resulting in remote calls to replicas.

                      +



                      +

                      +

                      Adding/removing server instances.

                      +



                      +

                      +

                      Phase 2 - Ability to add/remove server +instances

                      +



                      +

                      +

                      Assumes phase 1.

                      +



                      +

                      +

                      NO ORBD.

                      +



                      +

                      +

                      DAS pushes changes out.

                      +



                      +

                      +

                      Every server instance IORInterceptor adds an EPOCH +TAGGED_COMPONENT.

                      +



                      +

                      +

                      When a server instance is added or removed from +cluster the all server instances shut down and restart their +POA/POAManagers. This results in a new ORT with the current EPOCH +embedded in references.

                      +



                      +

                      +

                      Every server instance has +ServerRequestInterceptor. During POA shutdown/restart +ServerRequestInterceptor sends TRANSIENT/UPGRADE exception to client. + Client waits and tries again.

                      +



                      +

                      +

                      When an invocation arrives the +ServerRequestInterceptor checks to see if the EPOCH is out-of-date. +The ServerRequestInterceptor creates a new IOR using the ORT (with +current addresses and EPOCH) and does LOCATION_FORWARD. (If the +current and old EPOCHs are not compatible then the +ServerRequestInterceptor would reject the request.)

                      +



                      +

                      +

                      Enables:

                      +



                      +

                      +

                      Phase 1 plus adding/removing server instances.

                      +



                      +

                      +

                      Not supported:

                      +



                      +

                      +

                      Local container failover.

                      +



                      +

                      +

                      Limitation:

                      +



                      +

                      +

                      At least one server instance must not move to +ensure that uses of old references can find a server replica that can +then update to a current reference.

                      +



                      +

                      +

                      Phase 3 - local container failover

                      +



                      +

                      +

                      Assumes phase 2 in place.

                      +



                      +

                      +

                      ServerRequestIntercepor-based ORBD in each server +replica.

                      +



                      +

                      +

                      Every server instance IORInterceptor, after adding +TAG_ALTERNATE_IIOP_ADDRESS for each server replica, exchanges its ORT +with the local ORBD ORT, which is then set on the POA.

                      +



                      +

                      +

                      ORBD IORInterceptor adds ORBD addresses.

                      +



                      +

                      +

                      Client CorbaContactInfoList tries colocated if +possible. Initial request will go to the local ORBD which does a +LOCATION_FORWARD containing effective IOR with server instance +addresses. The initial request and all subsequent requests will go +to the local server instance. If the local server instance fails +(e.g., ACC) CorbaContactInfoList chooses another +TAG_ALTERNATE_IIOP_ADDRESS. If all alternates fail it falls back on +target IOR pointing to ORBDs and the process repeats.

                      +



                      +

                      +

                      Enables:

                      +



                      +

                      +

                      Phase 2 plus local container failover.

                      +



                      +

                      +

                      Phase 4 - Server Load added to replies

                      +



                      +

                      +

                      Assume phase 3.

                      +



                      +

                      +

                      Every server instance ServerRequestInterceptor +adds a server load service context on replies.

                      +



                      +

                      +

                      Client has ClientRequestInterceptor which reads +server load service contexts and gives information to +CorbaContactInfoList.

                      +



                      +

                      +

                      CorbaContactInfoList uses server load to decide +which server replica to use. If the local replica is too loaded +would we do a remote call?

                      +



                      +

                      +

                      Phase 5 - Load Shedding

                      +



                      +

                      +

                      Assume phase 4

                      +



                      +

                      +

                      Every server instance ServerRequestInterceptor +sends a TRANSIENT/OVERLOADED (or it could do LOCATION_FORWARD to +single IOR when server is overloaded).

                      +



                      +

                      +

                      Need a MustService Service Context from client to +avoid starvation.

                      +



                      +

                      +

                      Enables:

                      +



                      +

                      +

                      LOCATION_FORWARD allows foreign ORBS to +participate in load shedding.

                      +



                      +

                      +

                      Other phases

                      +



                      +

                      +

                      Ability to add/remove server instances without +using TRANSIENT/UPGRADE. Either by POAManager/AdapterActivator POA +destroy/create, or ... (TBD by Ken).

                      +

                      +

                      +

                      +

                      +
                        +
                      1. + Template Creation

                        +
                      +

                      The easiest way to explicitly create a template is +simply to use the exact same code that we would use inside ORB.init() +as follows:

                      +



                      +

                      +

                      For each ServerInstance where you need to create +templates:

                      +



                      +

                      +

                      1. ORB orb = ORB.init() (with probably a few +special parameters, such

                      +

                      as a "never start the transport" +option). Also set the server ID

                      +

                      at this stage. No request interceptors should +be registered, as

                      +

                      this ORB will never handle requests. The IOR +interceptor should

                      +

                      implement the correct establish_components +method for adding

                      +

                      TAG_ALTERNATE_IIOP_ADDRESS TAGGED_COMPONENTS, +but should do nothing

                      +

                      on the components_established method. In other +words, just use the

                      +

                      same code in two different IORInterceptor +classes, except that the

                      +

                      derived class adds the components_established +method. Then a

                      +

                      different ORBInitializer class is needed here. +Harold knows all of

                      +

                      these details extremely well.

                      +



                      +

                      +

                      2. Create and register acceptors for transports as +needed, according

                      +

                      to the ServerInstance configuration and the +node. Note that this

                      +

                      is for the node where the ServerInstance runs, +which is usually not

                      +

                      the node where this code is running. They are +registered with

                      +

                      ORB.registerAcceptor(). Also note that this is +being done outside

                      +

                      of the ORB.init call, after casting the +org.omg.CORBA.ORB to

                      +

                      com.sun.corba.ee.spi.orb.ORB.

                      +



                      +

                      +

                      3. For each deployed EJB:

                      +

                      3.1 create the POA with the correct name +and the correct

                      +

                      policies.

                      +

                      3.2 extract the iotemplate from the POA as +follows:

                      +

                      IORTemplate iortemp =

                      +

                      +((ObjectAdapterBase)poa).getIORTemplate()

                      +

                      3.3 store the template somewhere +convenient. Note that we do

                      +

                      not need to make this persistent, since we +can just run

                      +

                      through this initialization at +ServerInstance startup time.

                      +



                      +

                      +

                      4. destroy the ORB, since we will never need it +again

                      +



                      +

                      +

                      Most of the above is already implemented in the +PEORB code base.

                      +

                      We need to add a flag to avoid starting the +transports, and

                      +

                      finish the acceptor implementation.

                      +



                      +

                      +

                      Bottom line: use the same code to construct the +template

                      +

                      and to initialize the POAs at ServerInstance +startup time, avoiding a lot

                      +

                      of duplicate code maintenance headaches.

                      +
                        +
                      1. + Future Versions

                        +
                      +

                      This section collects ideas, features, +optimizations, etc., for future versions of ORBD.

                      +



                      +

                      +



                      +

                      +



                      +

                      +

                      IP Multicast for broadcasting load information.

                      +

                      It is possible to use IP multicast to broadcast +load information within the cluster (it would not reach clients). A +multicast aware CorbaContactInfoList would listen to these broadcasts +and use them to pick addresses for invocations. If S1AS were ever to +use such a mechanism, it would be transparent to ORBD: the multicast +load information would be plugged in using the ServerInstanceMetric +and CorbaContactInfoList interfaces.

                      +



                      +

                      +

                      However, what sort of deployment difficulties +would this create for our customers? For example, if a cluster is +deployed across multiple LANs, the routers must handle IP multicast +traffic. Some customers may not be willing to deploy IP multicast. +

                      +



                      +

                      +

                      Reducing Traffic to ORBD

                      +



                      +

                      +

                      There are a number of ways to reduce the traffic +to ORBD:

                      +



                      +

                      +
                        +
                      1. Only talk to ORBD for the first invocation on + a particular template. Then all other instances of the same + template can be reconstructed from information already present in + the client. This means in effect that a client would only invoke + ORBD once per EJB type. This just requires keeping track of + templates when we unmarshal IORs, and keeping a mapping from ORBD + templates to Server templates in the client (the same map that ORBD + maintains). In this case the client is simply building ORBD->Server + cache. +

                        +
                      2. Create a local-only profile, which allows for + rapid restart w/o talking to ORBD. Such a profile would never be + marshaled, and would be reconstructed whenever an ORB unmarshals one + of its own IORs. To implement this we need to distinguish between + marshaling to another ORB and marshaling to serialize. +

                        +
                      +



                      +

                      +

                      SPECIFYING and IMPLEMENTING LOAD-BALANCING +POLICIES

                      +



                      +

                      +

                      How will client-side routing policy be specified +for an EJB?

                      +



                      +

                      +

                      Would there be an element in the EJB's deployment +descriptor?

                      +



                      +

                      +

                      We need a design for the routing policy +information, especially for how much of this is needed in S1AS8/EE +vs. how much is a good idea for later.

                      +



                      +

                      +

                      Generally all of these things should work the same +way: The deployment descriptor drives what policies are passed when +the POA is created. These policies in turn affect the +TAG_ALTERNATE_IIOP_ADDRESS TAGGED_COMPONENT instances that are added +in the IORInterceptor. The Client side can then look at the +components and decide what to do via CorbaContactInfoList.

                      +



                      +

                      +

                      For S1AS8/EE we are looking at simple +InitialContext load balancing from client and load balancing home +lookups plus a framework that allows future extensions (e.g., +failover, smarter load balancing, online upgrades).

                      +



                      +

                      +

                      The important thing is to have the mechanisms in +place to allow pluggable client-side routing policies. One +possibility: provide the policy class name in the EJB's deployment +descriptor (with some default if not specified), put the classname +into the IOR, then the client while invoking on the IOR knows what +policy to use.

                      +



                      +

                      +

                      This should be simple to do in the PEORB as +follows: +

                      +



                      +

                      +

                      1. Create a CorbaContactInfoListFactory instance +and register it with

                      +

                      the ORB (this is done at ORB.init() time). +This factory implements

                      +

                      the method

                      +



                      +

                      +

                      CorbaContactInfoList create( IOR ior )

                      +

                      {

                      +

                      RoutingPolicyComponent comp = <extract +this from ior: details

                      +

                      TBD>

                      +

                      if (comp = null)

                      +

                      return the default +CorbaContactInfoList

                      +

                      else

                      +

                      get class name from comp

                      +

                      instantiate class, which must +implement

                      +

                      CorbaContactInfoList

                      +

                      return result

                      +

                      }

                      +



                      +

                      +

                      Of course, we could also simply use a routing +policy ID instead,

                      +

                      which keeps the IOR shorter (by perhaps 3-5%). +Which approach we

                      +

                      take makes little difference, since all parts +of the app server

                      +

                      will need to know how to interpret the policy +(assuming that we do

                      +

                      not use dynamic code downloading).

                      +



                      +

                      +

                      2. The most important method that the +CorbaContactInfoList needs to

                      +

                      implement is simply

                      +



                      +

                      +

                      Iterator iterator()

                      +



                      +

                      +

                      which returns an instance of +CorbaContactInfoListIterator. There

                      +

                      are a number of other methods, but we will +probably just create a

                      +

                      base class to handle the normal implementation +of the other

                      +

                      methods.

                      +

                      +

                      +

                      3. CorbaContactInfoListIterator.next() must return +an instance of

                      +

                      CorbaContactInfo. CorbaContactInfo will +contain all of the IOR

                      +

                      addressing information needed for the request. +This is basically:

                      +



                      +

                      +

                      - Host

                      +

                      - Port

                      +

                      - GIOP version (probably always 1.2 for S1AS8)

                      +

                      - Object Key

                      +



                      +

                      +

                      next() returns whatever instance is appropriate +based on the

                      +

                      routing policy.

                      +



                      +

                      +

                      Load-balancing based on EJB characteristics

                      +



                      +

                      +

                      Use IIOP LOCATION_FORWARD that contain forwarded +IORs that focus on EJBs characteristics. For example: routing based +on primary keys, affinity based routing, routing leveraging the +transaction commit options. Routing may also be different for EJBHome +and EJBObject IORs. +

                      +



                      +

                      +

                      Possible policies:

                      +



                      +

                      +

                      1. Hash primary key to replica:

                      +



                      +

                      +

                      Somewhere you need to specify exactly how +this mapping takes

                      +

                      place. Perhaps the hash function is +passed as a value type?

                      +

                      The client side just needs to create the +appropriate

                      +

                      CorbaContactInfoList implementation.

                      +



                      +

                      +

                      2. Based on load:

                      +



                      +

                      +

                      You could use something like +ServerInstanceMetric for this.

                      +

                      Basically there needs to be some sort of +load monitor running

                      +

                      in the client. What about ACC/web +clients? They will not

                      +

                      have access to all of the information.

                      +



                      +

                      +

                      3. Affinity:

                      +



                      +

                      +

                      You place the cookie inside the Object ID, +as that is the only

                      +

                      part of the IOR the application can +modify. This happens

                      +

                      whenever the object reference is created, +assuming your

                      +

                      preference is for requests to be handled +wherever the target

                      +

                      was created.

                      +



                      +

                      +

                      4. Based on method name:

                      +



                      +

                      +

                      You have easy access to the method name in +interceptors or in

                      +

                      the contact info, but not to the +parameters. This sounds like

                      +

                      you want to choose the policy based on the +method type, in

                      +

                      which case the CorbaContactInfoList must +be prepared to handle

                      +

                      any supported policy. If this is a real +requirement, we would

                      +

                      not bind the routing policy to the IOR at

                      +

                      unmarshallinh/creation time: instead, we +would just have a

                      +

                      single CorbaContactInfoListFactory that +would handle all

                      +

                      cases.

                      +



                      +

                      +

                      5. Based on other system information (e.g. +data/time)

                      +



                      +

                      +

                      Presumably this means use different +replicas as different

                      +

                      times of the day? Again, a policy, +perhaps mapping times to

                      +

                      replicas. +

                      +

                      How do clients discover this policy: always from +the IOR, either from

                      +

                      a TAGGED_COMPONENT, or from data stuffed into the +object key.

                      +



                      +

                      +

                      Questions:

                      +



                      +

                      +

                      1. How dynamic is the policy?

                      +



                      +

                      +

                      2. Do we have the same policy for a single IOR, or +do we change it per

                      +

                      request?

                      +



                      +

                      +

                      3. What will we want to do in S1AS8/EE vs. future +releases?

                      +



                      +

                      +

                      4. How extensible does this need to be?

                      +

                      +

                      +
                        +
                      1. + Rejected Alternatives

                        +
                      +

                      Location of load-balancing decisions +

                      +



                      +

                      +
                        +
                      1. In the ORBD only: not dynamic enough.

                        +
                      2. In the client only. With this approach it is + not possible to change the locations or number of replicas of an + EJB. This means that clients would hold onto IORs which would + become out-of-date as the system evolves. +

                        +
                      3. In a router that lives between the client and + server (e.g. an IP level router like in the HTTP case). This is not + an option for now. Note: A router is a bridge. Building an + efficient IIOP bridge entails transport work to avoid the overhead + of remarshaling every request that traverses the bridge. If there + is ever a need for such bridge entity, we should start talking about + it now, as the transport work is not entirely simple.

                        +
                      +

                      +

                      +
                        +
                      1. + Smart Stubs are a Dumb Idea

                        +
                      +



                      +

                      +

                      Smart Stubs are a Dumb Idea

                      +



                      +

                      +

                      1. Smart stubs used for load balancing and fault +tolerance place

                      +

                      type-independent behavior in type-dependent +code. This often

                      +

                      increases the size of the stub code needlessly.

                      +



                      +

                      +

                      2. Smart stubs are hard to manage if a system uses +multiple

                      +

                      implementations of the same type.

                      +



                      +

                      +

                      3. Smart stubs are a static solution. The ORBD +approach allows the

                      +

                      behavior of an invocation to change dynamically +from one invocation

                      +

                      to the next. For example, we could switch +protocols dynamically

                      +

                      (if we decided to implement non-IIOP protocols +for some reason).

                      +



                      +

                      +

                      4. Smart stubs are harder to test, due to the +interaction of code

                      +

                      generation rules for RMI-IIOP with the +requirements of a particular

                      +

                      mechanism in the smart stub (i.e. M X N feature +interaction vs. M +

                      +

                      N). If we decide to do dynamic byte code +generation someday, it

                      +

                      will also be easier to test with standard +stubs.

                      +



                      +

                      +

                      5. Standard stubs are more easily replaced by +dynamic proxies. This

                      +

                      is an area that a lot of people on the ORB and +EJB sides would like

                      +

                      to investigate further time permitting. For +example, this could

                      +

                      make deployment much faster, which could also +be a significant

                      +

                      competitive advantage.

                      +



                      +

                      +

                      6. Dynamic stub loading works better with standard +stubs, as the

                      +

                      standard stubs are not tightly coupled to their +environment.

                      +

                      + +

                      +

                      Possible reasons that smart stubs are used in +other systems:

                      +



                      +

                      +

                      1. They can solve some problems without deep ORB +knowledge. Since we

                      +

                      have the ORB expertise, we can do better. We +also are building the

                      +

                      PEORB so it can work very well in a highly +dynamic environment.

                      +



                      +

                      +

                      2. It may be the best you can do in a non-CORBA +system (meaning non-OO

                      +

                      RPC systems). One of the critical features +that we use is the

                      +

                      representation of an object reference +(basically the IOR). This

                      +

                      representation directly controls advanced +features like load

                      +

                      balancing and fault tolerance, as well as +multiple protocol

                      +

                      support. We can also do compression of IORs by +establishing

                      +

                      transport session state, and many other useful +optimizations. But

                      +

                      without this capability, a smart stub may be +the only options.

                      +



                      +

                      +

                      3. Some type-dependent optimizations may be more +easily performed in a

                      +

                      smart stub. For example, some beans may have +methods that fetch

                      +

                      read-only, or just slowly chaning values. Such +data can be cached

                      +

                      in the stub, either with no update facility, or +with a simple cache

                      +

                      invalidation protocol.

                      +



                      +

                      +

                      However, even this case can be handled pretty +well at the ORB

                      +

                      level. Basically this just requires building a +more advanced

                      +

                      ClientSubcontract that can cache appropriately +based on the

                      +

                      operation name.

                      +



                      +

                      +

                      All of these sort of ideas were expressed a +decade ago in the

                      +

                      Spring project at Sun labs.

                      +

                      +

                      +



                      +

                      +
                        +
                      1. + Constructing + IORs from multiple templates

                        +
                      +

                      How do we construct a forwarded IOR using multiple +templates. While the current ORT standard does not directly address +this point, Ken designed the standard to allow extensibility in this +area. The important point is that the ORT standard defines two types: +the ObjectReferenceFactory and the +ObjectReferenceTemplate, which extends ObjectReferenceFactory. The +ObjectReferenceFactory defines a make_object method, which creates an +IOR, and the ObjectReferenceTemplate adds methods to obtain the +server ID, ORB ID, and ObjectAdapter ID. This information +uniquely identifies the template within the domain of a single +ORBD, and is essential for the matching of templates that ORBD +performs. This separation allows multiple templates to be merged into +a single factory, losing their unique identity, but still supporting +the crucial make_object operation.

                      +

                      The question still remains: how do we merge the +templates? Here we will rely on a proprietary extension to ORT, and +allow access to the underlying IORTemplate +inside the ORT. The IORTemplate explicitly allows access to its +constituent profile templates, so we can extract the profile +templates from all of the ORTs, combine them into a single +IORTemplate, and create a new ObjectReferenceFactory from the +combined IORTemplate.

                      +
                        +
                      1. + Epochs for Online Upgrades

                        +
                      +

                      Policies and therefore templates can change as a +consequence of an upgrade.

                      +

                      IORs containing epochs ensure no stale IORs.

                      +

                      Fixed epoch on ORBD IORs (enabled by policy given +to ORBD).

                      +



                      +

                      +
                        +
                      1. + Servers Shedding Load and Avoiding Client Starvation

                        +
                      +

                      A server could shed load by responding to a +request with a TRANSIENT SystemException with a SUNVMCID minor code +indicating load-shedding.

                      +



                      +

                      +

                      If servers are continuously shedding load it is +possible that a client could continuously cycle through both +effective IOR and target IOR and never get serviced. To avoid this, +the client retry mechanism can determine some point at which it can +refuse to be load-shedded. In this case the client side ORB (via a +ClientRequestInterceptor) would add a +ServiceContext to the request that would +tell the server it cannot load-shed that request.

                      +



                      +

                      +

                      An overloaded server could alternatively respond +with a LOCATION_FORWARD containing an IOR with ORBD addresses back to +the client. +

                      +
                        +
                      1. + Other considerations

                        +
                      +

                      These notes will be merged into appropriate +sections above. They are included here now so as to contribute to the +design process and to keep them from getting lost.

                      +



                      +

                      +

                      ORBD INTEGRATION WITH S1AS8/EE

                      +



                      +

                      +

                      ORBD needs to be integrated with the overall +clustering mechanisms in the appserver. +Failover, load-balancing and online +upgrades need to be considered for HTTP, JMS, IIOP, etc., as a whole +in the areas of health checks, availability monitoring and load +metrics exchange.

                      +



                      +

                      +

                      EJB-AWARE ROUTING POLICIES

                      +



                      +

                      +

                      Routing policies should be cluster and EJB-aware +and pluggable.

                      +

                      The primary target of IIOP requests are EJBs, +the mechanisms should support and leverage EJB-specific features. +Possibilities include: routing based on primary keys, affinity based +routing, and routing leveraging the transaction commit options. +Routing may need to be different for EJBHome +and EJBObject IORs.

                      +



                      +

                      +

                      IIOP/ORBD-S1AS8/EE INTEGRATION - PRIMARY IIOP +PLUGIN POINTS

                      +



                      +

                      +
                        +
                      1. Client: CORBAContactInfoList : this is + responsible for updating the effective IOR and for selecting an + appropriate profile for an invocation. The ORBD gives and initial + effective IOR but need not be consulted again unless the + CORBAContactInfoList runs out of alternatives.

                        +
                      2. Server: ServerRequestInterceptor and/or + ServantManager: these points can add piggy + back load metrics (or routing info as you called it) and do + load-shedding.

                        +
                      3. ORBD: ServerInstanceMetric: this is the main + point the the ORBD integrates with the DAS to get information on the + state of the cluster.

                        +
                      +



                      +

                      +

                      Currently, in this ORBD architecture document, the +only reflection of app server characteristics is the ORBD's +ServerInstanceMetric, which we plan to use to get a simple ordering +of all possible replicas that can be used for a request. As the load +changes dynamically in the system, a custom CORBAContactInfoList +implementation can be used to take that into account, as well as the +affinities mentioned above.

                      +

                      The Client's +CORBAConstantInfoList is designed to be pluggable to control +decisions about which available profile to use for a request, and to +update this choice based on results of previous requests.

                      +



                      +

                      +

                      WHICH PROCESS SHOULD ORBD RUN IN?

                      +



                      +

                      +

                      ORBD may be run as its own process, in an +application server process, or in some other part of the system. It +is clear it must be replicated. If the ORBD were in every +application server instance it would obviate the need to separately +monitor and startup ORBD

                      +

                      instance. But it would also introduce extra load +on the application server and possibly let a failing application +server to interfere with ORBD operation.

                      +

                      Regarding reliability, if ORBD is run in a +separate JVM, far fewer classes are loaded, its execution is more +predictable, and there will likely be fewer scenarios that can result +in JVM failure.

                      +

                      Regarding reuse, ORBD needs a lot of the +infrastructure present in the app server processes.

                      +

                      The ORBD design does not care where ORBD is run. +Running ORBD in the app server process is possible. We could run in +every app server instance or only those instances configured to do +so.

                      +

                      A consideration: how much change do we allow after +the app server cluster is installed. The current ORBD design assumes +that both the number and location of EJB replicas can change +dynamically. The location of ORBD replicas can +be changed dynamically as well, with a little care in how the host +name in the IIOP profile for an ORBD reference is constructed. The +only thing that cannot easily change dynamically is the number of +ORBD instances, which wired into into every IOR +created. Removing that limitation basically requires some use +of IP multicast and custom ORB transports. All of this is

                      +

                      possible in the PEORB framework, but we will not +have time for it in S1AS8/EE.

                      +

                      +

                      +

                      PIGGYBACK INFO IN REPLIES

                      +



                      +

                      +

                      Piggybacking information +in replies could be used to update a local cache of server load +information, for example. This information would be used by +CORBAContactInfoList to help it select appropriate profiles.

                      +

                      Note: Updating actual client effective IORs using +this info is problematic. The ORB creates IORs from templates, so +IORs are immutable. Updating an IOR directly is expensive, since it +requires copying the entire IOR.

                      +

                      It is not necessary to update an a client +effective IOR when a server goes down. The CORBAContactInfoList +notes the down server (to avoid trying it again unless no others are +available) tries a different profile. If all other profiles fail it +would try the downed server profile again. If that also failed it +would then fail over to the ORBD to get a new effective IOR.

                      +



                      +

                      +

                      ORBD'S SEPARATE STATE MODEL

                      +



                      +

                      +

                      ORBD maintains its own information model for two +reasons:

                      +



                      +

                      +
                        +
                      1. To provide only the information needed for + ORBD.

                        +
                      2. To cache information locally for performance

                        +
                      +



                      +

                      +

                      Much of the information will be obtained from the +app server using app server mechanisms. The most important +information that ORBD needs is the ORT for all of the object adapters +(=EJB types now that we will be using the POA-per-EJB-type design). +The ORT piece is purely CORBA, but driven by how the EJB container +code creates POAs. Other information stored by ORBD is cached info +from DAS (e.g., what parts of the system are up or down). +

                      +



                      +

                      +

                      MULTICAST

                      +



                      +

                      +

                      Using IP multicast for load information/node +health status is a useful idea. If the app server uses such a +mechanism, it will be transparent to ORBD. In this case, load +information received via multicast would be plugged in using the +ServerInstanceMetric interface.

                      +



                      +

                      +

                      + +

                      +
                        +
                      1. + Data Model Constraints

                        +
                      +

                      There are two important constraints in the data +model:

                      +
                        +
                      1. +
                      +

                      This constraint basically means that the object +adapters for ORBD and the object adapters in application instances +are never the same.

                      +
                        +
                      1. +
                      +

                      The ObjectAdapterReplicas relation gives the set +of (application) object adapters that correspond to an (ORBD) object +adapter. This key relation defines the set of object adapters that +can be used to handle a request to ORBD. + +

                      +
                        +
                      1. + A Tutorial on J2SE ORBD Operation

                        +
                      +

                      +Use Case: Server Registration and Activation

                      +

                      In J2SE, ORBD is used to enable persistent IORs. +This means that if a client invokes an operation on a persistent IOR +and the server servicing that IOR is not running, then ORBD will +activate the server transparently to the client.

                      +

                      There are two services used to support persistent +IORs in J2SE: location and activation services. The ORBD serves as a +location service that is used by clients to find a server instance +that can satisfy an incoming request. The activation service is used +by the ORBD (location service) to activate a service instance if one +is not running.

                      +

                      The following figure shows the steps involved in +this process.

                      +



                      +

                      +




                      +

                      +



                      +

                      +
                        +
                      1. For any server S that + creates POAs with a PERSISTENT policy, S + must be registered with the Activator.

                        +
                      2. When a persistent server S + registers with the Activator, it activates the server (i.e., starts + the server running in a new JVM).

                        +
                      3. Persistent servers + transparently contain a Server object which is used by the ORBD as a + watchdog. When S starts, its Server object registers with ORBD.

                        +
                      4. For each ORB created in S + that ORB transparently notifies the ORBD of its existence.

                        +
                      5. For each POA with a + PERSISTENT policy, that POA performs an ORT exchange with the ORBD. + Here we see that POA1 now has a copy of the ORB's ORT while the ORBD + has a copy of server S's ORT. This means that any IORs created by + POA1 will contain contact information for the ORBD and that the ORBD + is able to create IORs with contact information for server S. The + gray areas in the templates indicate the object ID which must be + inserted into a template to create an IOR.

                        +
                      6. POA1 creates an IOR + with object ID x and binds that IOR in naming.

                        +
                      7. The Client uses naming to + obtain the IOR. When a IOR is unmarshaled + it results in a Stub being created. The stub internally maintains + two fields containing the resolved IOR: target IOR and effective + IOR. When initially created the stub's two fields point to the same + IOR.

                        +
                      +

                      Before showing how a client makes an invocation on +a stub we need to first show how stubs work.

                      +



                      +

                      +

                      +ORB Client Invocation Operation

                      +



                      +

                      +

                      How an ORB client makes an invocation is a key +part of the architecture.

                      +

                      When an IOR is unmarshaled +it results in a stub. The stub maintains two fields, the target IOR +and the effective IOR. The target is the original IOR that was used +to create the stub. The target IOR is fixed for the lifetime of the +stub. The effective IOR is the IOR that is currently being used for +requests on this stub. The effective IOR can change over the lifetime +of the stub. The following figure shows a stub and its IOR fields:

                      +



                      +

                      +




                      +

                      +

                      When a method call is invoked on a CORBA stub it +results in some form of communication with a server implementation of +the object represented by the stub. We provide the following +definitions to help clarify this interaction:

                      +
                        +
                      • An invocation is a method call on a + CORBA stub (i.e. An RMI-IIOP remote object). An invocation causes + one or more requests.

                        +
                      • A request is a request/response pair + of messages between a client and a server. An invocation usually + causes a single request, but in some circumstances, an invocation + may cause a number of requests.

                        +
                      +

                      When a method on a CORBA stub is invoked there are +several possible results:

                      +
                        +
                      1. A normal result, containing the expected + result type.

                        +
                      2. A SystemException, + indicating a major type and minor code for the error, as well as a + completion status, which indicates whether the server ORB started + dispatching to the object implementation before the error. + SystemExceptions may be retriable in some + cases. For example, a COMM_FAILURE with a completion status of + COMPLETED_NO can be safely retried.

                        +
                      3. A user exception, indicating some sort of + error declared in the interface of the remote type.

                        +
                      4. A LOCATION_FORWARD, which indicates that some + other object implementation, typically on a different server, should + be consulted for this and subsequent invocations.

                        +
                      +



                      +

                      +

                      An invocation, in detail, consists of the +following steps:

                      +
                        +
                      1. Initially the stub's effective IOR is the + same as the target IOR:

                        +
                      +



                      +

                      +




                      +

                      +
                        +
                      1. A CORBA IOR contains one or more profiles, + each of which contains all necessary information for making a + request to a specific server. A profile is chosen from the effective + IOR to use for invocations on this stub.

                        +
                      +



                      +

                      +




                      +

                      +
                        +
                      1. Various updates occur after different + replies:

                        +
                      +
                        +
                      1. A normal result, a user exception, or a + non-retriable SystemException is simply + returned to the client.

                        +
                      2. A LOCATION_FORWARD result updates the stub's + effective IOR to be the IOR contained in the LOCATION_FORWARD + response.

                        +
                      +



                      +

                      +
                      +



                      +

                      +



                      +

                      +

                      A profile is selected +from the new effective IOR for subsequent requests (including a +transparent retry of the current request).

                      +



                      +

                      +
                        +
                      1. A retriable SystemException causes another + profile to be selected from the effective IOR. If no profile is + available in the effective IOR, the effective IOR reverts back to + the target IOR, a profile is chosen, and the request is retried. If + the effective IOR is the same as the target IOR, and no profile + remains, an error is returned to the client.

                        +
                      +

                      Exactly what constitutes a retriable +SystemException is system specific. For example, certain +SystemExceptions (e.g. TRANSIENT) may be +retried against the same profile some limited number of times. (The +retry behavior of an ORB is pluggable +through the ORB SPI.)

                      +

                      Retry behavior is crucial for ORBD in two ways. +First, ORBD functions mainly as a redirector using LOCATION_FORWARD. +Since we do not want to funnel every request in the system through +ORBD, the client caches the effective IOR in order to improve +efficiency. Secondly, if part of the cluster fails or becomes +overloaded, we need a way to tell a client that it should try +something else to satisfy its invocation. This can be accomplished by +trying another profile or falling back to the ORBD to try again at +that level:

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +




                      +

                      +



                      +

                      +

                      +Use Case: First Invocation, Server Running

                      +



                      +

                      +

                      When a client invokes +a method on a newly created stub, both the target and effective IOR +fields contain the same IOR. In the scenario we started in Server +Registration and Activation, the effective IOR contains the object ID +x but addressing information pointing to the ORBD. How the ORBD +redirects this invocation to the appropriate server is shown in the +following figure:

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +



                      +

                      +




                      +

                      +
                        +
                      1. The Client invokes on the + stub (created as the result of resolving an IOR from naming). The + stub uses the effective IOR to service the invocation. Even though + the client ???thinks??? it is invoking an IOR for server S it is + actually invoking an IOR pointing to the ORBD (indicated by O/x) + since that is what is contained in the effective IOR field.

                        +
                      2. ORBD receives the request.

                        +
                      3. ORBD maps the request to + the appropriate server ORT. +

                        +
                      4. ORBD extracts the object ID + x from the request and creates an IOR with object ID x containing + contact information for server S.

                        +
                      5. ORBD returns a + LOCATION_FORWARD response containing IOR S/x to the Client.

                        +
                      6. The stub sets its effective + IOR field to point to IOR S/x returned in the LOCATION_FORWARD + response from the ORBD.

                        +
                      7. The client stub + transparently retries the request with IOR S/x, which is now + directed to server S. All subsequent invocations will use the + effective IOR S/x. They will therefore go directly to server S with + no further ORBD interaction. However, if the server goes down + (gracefully or otherwise) the client stub will transparently fall + back to the target IOR resulting in a request to ORBD (which will + try to activate the server ??? as shown later).

                        +
                      +

                      +Use Case: Second Invocation, Server Running

                      +



                      +

                      +

                      Since the stub caches IOR S/x as the effective IOR +and the stub uses the effective IOR for initially servicing an +invocation, subsequent invocations are go directly to the server:

                      +



                      +

                      +




                      +

                      +
                        +
                      1. The client invokes on the stub. The stub uses + the effective IOR S/x to service the invocation.

                        +
                      2. Server S receives the request which is mapped + via object ID x to the appropriate implementation.

                        +
                      +

                      +Use Case: Third Invocation, Server Inactive

                      +



                      +

                      +

                      In this case, the effective IOR still points to +S/x. However, server S has gone down. The following figure +illustrates the steps taken for this case:

                      +



                      +

                      +




                      +

                      +
                        +
                      1. The client invokes on the stub. The stub + uses the effective IOR S/x to service the invocation.

                        +
                      2. The ORB attempts to make a connection to + server S. When that attempt fails other profiles in the effective + IOR would be tried. In this case we are assuming there is only one + profile.

                        +
                      3. Since the single profile in effective IOR S/x + failed the stub falls back to the original target IOR O/x.

                        +
                      4. ORBD receives the request for server S which + is down (how it knows it is down is not discussed here). It asks the + activator to activate server S.

                        +
                      5. The activator activates server S.

                        +
                      6. Server S's server object registers with ORBD.

                        +
                      7. ORBs created in S + register with ORBD.

                        +
                      8. POAs with PERSISTENT policies perform an ORT + exchange with ORBD.

                        +
                      9. IOR O/x is created inside server S under POA1 + and bound in naming.

                        +
                      10. ORBD, which has discarded previous ORTs + associated with S and refreshed them + during server S's activation, maps the request to the appropriate + ORT.

                        +
                      11. Using object ID x, ORBD creates IOR S/x + using the ORT.

                        +
                      12. ORBD responds to the request with a + LOCATION_FORWARD containing IOR S/x.

                        +
                      13. The stub sets its effective IOR field to + S/x.

                        +
                      14. The client ORB transparently retries the + request using a profile from effective IOR S/x which results in the + request being directed to server S.

                        +
                      +



                      +

                      +

                      CorbaContactInfoList

                      +



                      +

                      +

                      The ORB interface responsible for dealing with +IORs is CorbaContactInfoList. CorbaContactInfoList abstracts IORs. +It is responsible for choosing how to contact a server for an +invocation. Alternate addresses may be represented as multiple +profiles and/or TAG_ALTERNATE_IIOP_ADDRESS TAGGED_COMPONENTs in +profiles (as in CSIv2). CorbaContactInfoList is responsible for +choosing the "best" address. It is also responsible for +choosing the next "best" address should one fail. That +includes failing over to the original address (e.g., the target IOR ??? +which would contain profiles for redundant ORBDs). The client +delegate just keeps asking for the next one on failure. +CorbaContactInfoList does not necessarily just iterate through a +list. It can use routing information to decide what "next" +is. It is also notified of previous client side failures to help its +decision making process. +

                      +



                      +

                      +

                      There are many details left out of these uses +cases, such as timing issues between the activator and the ORBD, the +possibility the when server S is restarted it creates POAs with +different policies, and more detail on multiple profile IORs. We left +those details out in order to give a broad overview of J2SE ORBD +operation.

                      +



                      +

                      +

                      Differences between J2SE and S1AS8/EE ORBD +operation

                      +

                      The main differences between J2SE ORBD operation +and S1AS8/EE ORBD operation are:

                      +



                      +

                      +
                        +
                      1. J2SE applications may create many ORBs in a + server. S1AS8/EE only creates one ORB.

                        +
                      2. In J2SE, server registration, activation and + ORBD location are only involved with a server if at least one POA + created in the server has a PERSISTENT policy. In S1AS8/EE, all POAs + exchange templates with the ORBD since we want to provide failover + for all IORs created in the server.

                        +
                      3. In J2SE, the activator and ORBD (the locator) + are colocated in the same process. In + S1AS8/EE, some other part of S1AS 8 EE is responsible for starting + and stopping server and application instances (note, the starting + and stopping of theses instances are events of interest to the + ORBD).

                        +
                      4. In J2SE, IORs generally contain one profile. + In S1AS8/EE IORs contain multiple profiles (or additional + TAGGED_ALTERNATE_IIOP_ADDRESS components), one for each application + replica.

                        +
                      +



                      +

                      +
                      +
                        +
                        May 15, 2006
                        +
                      +
                      + + diff --git a/www/design/orbdArchitecture.sxw b/www/design/orbdArchitecture.sxw new file mode 100644 index 000000000..cca22d376 Binary files /dev/null and b/www/design/orbdArchitecture.sxw differ diff --git a/www/design/orbdArchitecture_html_14a23ee7.gif b/www/design/orbdArchitecture_html_14a23ee7.gif new file mode 100644 index 000000000..d98165ed2 Binary files /dev/null and b/www/design/orbdArchitecture_html_14a23ee7.gif differ diff --git a/www/design/orbdArchitecture_html_1d6149dc.gif b/www/design/orbdArchitecture_html_1d6149dc.gif new file mode 100644 index 000000000..26dfccbc0 Binary files /dev/null and b/www/design/orbdArchitecture_html_1d6149dc.gif differ diff --git a/www/design/orbdArchitecture_html_20a9079b.gif b/www/design/orbdArchitecture_html_20a9079b.gif new file mode 100644 index 000000000..b99aadb35 Binary files /dev/null and b/www/design/orbdArchitecture_html_20a9079b.gif differ diff --git a/www/design/orbdArchitecture_html_3330d434.gif b/www/design/orbdArchitecture_html_3330d434.gif new file mode 100644 index 000000000..b70dc9112 Binary files /dev/null and b/www/design/orbdArchitecture_html_3330d434.gif differ diff --git a/www/design/orbdArchitecture_html_3472b4d5.gif b/www/design/orbdArchitecture_html_3472b4d5.gif new file mode 100644 index 000000000..eaa4dcd30 Binary files /dev/null and b/www/design/orbdArchitecture_html_3472b4d5.gif differ diff --git a/www/design/orbdArchitecture_html_49d410e2.gif b/www/design/orbdArchitecture_html_49d410e2.gif new file mode 100644 index 000000000..3469ab844 Binary files /dev/null and b/www/design/orbdArchitecture_html_49d410e2.gif differ diff --git a/www/design/orbdArchitecture_html_7394932c.gif b/www/design/orbdArchitecture_html_7394932c.gif new file mode 100644 index 000000000..b2f5a9529 Binary files /dev/null and b/www/design/orbdArchitecture_html_7394932c.gif differ diff --git a/www/design/orbdArchitecture_html_77bcdcbf.gif b/www/design/orbdArchitecture_html_77bcdcbf.gif new file mode 100644 index 000000000..e1ba30014 Binary files /dev/null and b/www/design/orbdArchitecture_html_77bcdcbf.gif differ diff --git a/www/design/orbdArchitecture_html_m2abb7fe1.gif b/www/design/orbdArchitecture_html_m2abb7fe1.gif new file mode 100644 index 000000000..4eeae07ce Binary files /dev/null and b/www/design/orbdArchitecture_html_m2abb7fe1.gif differ diff --git a/www/design/orbdArchitecture_html_m3f9af29d.gif b/www/design/orbdArchitecture_html_m3f9af29d.gif new file mode 100644 index 000000000..5d340d715 Binary files /dev/null and b/www/design/orbdArchitecture_html_m3f9af29d.gif differ diff --git a/www/design/orbdArchitecture_html_m431c1580.gif b/www/design/orbdArchitecture_html_m431c1580.gif new file mode 100644 index 000000000..e85b99d9c Binary files /dev/null and b/www/design/orbdArchitecture_html_m431c1580.gif differ diff --git a/www/design/orbdArchitecture_html_m6a2efbbb.gif b/www/design/orbdArchitecture_html_m6a2efbbb.gif new file mode 100644 index 000000000..4d408eca7 Binary files /dev/null and b/www/design/orbdArchitecture_html_m6a2efbbb.gif differ diff --git a/www/design/orbdArchitecture_html_m6f0b4e4.gif b/www/design/orbdArchitecture_html_m6f0b4e4.gif new file mode 100644 index 000000000..84fc857ec Binary files /dev/null and b/www/design/orbdArchitecture_html_m6f0b4e4.gif differ diff --git a/www/design/orbdArchitecture_html_md67d953.gif b/www/design/orbdArchitecture_html_md67d953.gif new file mode 100644 index 000000000..ff9e0e14d Binary files /dev/null and b/www/design/orbdArchitecture_html_md67d953.gif differ diff --git a/www/design/stubs.gif b/www/design/stubs.gif new file mode 100644 index 000000000..0aaa8cea2 Binary files /dev/null and b/www/design/stubs.gif differ diff --git a/www/design/testing_giop.html b/www/design/testing_giop.html new file mode 100644 index 000000000..e53d9ff29 --- /dev/null +++ b/www/design/testing_giop.html @@ -0,0 +1,216 @@ + + + + + + + + +

                      ORB Support for GIOP Testing

                      +


                      +

                      Last Modified: May 17, 2004

                      +

                      Version: 1.6

                      +
                      <Ken Cavanaugh> +
                      +

                      We often need to examine problems in CORBA that are related to the + details of marshalling messages for CDR encoded GIOP messages. This is + currently a difficult and time-consuming problem due to the lack of tools for + this task. Harsha Godugu is working on a GIOP analyzer to make this process + easier. This note discusses some ORB changes needed to support the GIOP + analyzer, and also to make other debugging tasks easier.

                      +

                      What we need is the following:

                      +
                        +
                      • An API for capturing the messages sent and received by a particular + invocation. This will allow us to gather data for testing the GIOP analyzer . +
                      • +
                      • An API for taking a sequence of messages and converting that sequence + into an input stream. Utilities for converting an array of strings or a text + file in the GIOP dump format will also be useful.
                      • +
                      +

                      Getting an Input Stream from Messages

                      +

                      Probably the simplest possible representation for the data contained in + a sequence of messages is simply byte[][]. Wherever I use this type to + represent a sequence of messages, we will assume that:

                      +
                        +
                      1. The first message in the sequence is either a (GIOP) request or + reply.
                      2. +
                      3. Subsequent messages are all fragment messages.
                      4. +
                      5. Every message except the last has the more fragment bit set.
                      6. +
                      7. All messages in the sequence share the same request ID.
                      8. +
                      +

                      If any of these conditions fail, getMessageData should throw an + appropriate exception. getMessageData is a new method on the ORB SPI defined as + follows:

                      +
                      +    /** Messages must be an array of GIOP messages.  The first message must
                      +     * be a GIOP request or response.  Any subsequent messages must be
                      +     * fragment messages with the same request ID as the first message.
                      +     * This returns a MessageData interface, in which all of the Messages
                      +     * have been unmarshalled, and the result of getStream is a stream
                      +     * that is prepared to unmarshal the request or reply body.
                      +     */
                      +    MessageData getMessageData( byte[][] messages ) ;
                      +
                      +

                      MessageData is an interface defined as follows:

                      +
                      +public interface MessageData {
                      +    /** An array GIOP Messages.  The first message is a request or reply,
                      +     * all subsequent messages are fragments with the same request ID.
                      +     */
                      +    Message[] getMessages() ;
                      +
                      +    /** A fully initialized input stream for the message data, positioned
                      +     * at the first element of the body.
                      +     */
                      +    CDRInputStream getStream() ;
                      +}
                      +
                      +

                      To support this, we need a Connection that is backed by a byte[][] or + equivalent. I am currently testing this, which us called + BufferedConnectionImpl.

                      +

                      Capturing Messages from an Invocation

                      +

                      The idea here is to provide an interface that allows the programmer to + obtain the sequence of messages in the request and reply from a CORBA method + invocation. The model I have designed for this is fairly simple and easy to + use. First, we define a new interface called a MessageTraceManager:

                      +
                      +public interface MessageTraceManager {
                      +    /** Returns true if messages are to be captured on this thread, otherwise
                      +     * false.
                      +     */
                      +    boolean isEnabled() ;
                      +
                      +    /** Called with flag=true to enable capture of messages
                      +     */
                      +    void enable( boolean flag ) ;
                      +
                      +    /** Return an array of messages (represented as byte[]) for the 
                      +     * message(s) sent for the request in the last invocation.  In the
                      +     * event of a location forward, this is the sequence for the last
                      +     * invocation.
                      +     */
                      +    byte[][] getRequestData() ;
                      +
                      +    /** Return an array of messages (represented as byte[]) for the 
                      +     * message(s) received for the last invocation.  In the event of
                      +     * a location forward, this is the sequence received from the last
                      +     * invocation.
                      +     */
                      +    byte[][] getResponseData() ;
                      +}
                      +
                      +

                      This interface allows access to the messages sent and received in the + last request. To obtain an instance of MessageTraceManager, we add the + following API to the ORB SPI:

                      +
                      +    /** Return a MessageTraceManager for the current thread.  Each thread that
                      +     * calls this method gets its own MessageTraceManager.
                      +     */
                      +    MessageTraceManager getMessageTraceManager() 
                      +
                      +

                      This API allows message data to be collected from any synchronous CORBA + invocation. This include RMI-IIOP, IDL, and DII (but not deferred synchronous + invocations). A test could also simulate a stub invocation if desired.

                      +

                      ORB Code Notes

                      +

                      Start with receipt of read event on a connection:

                      +
                        +
                      1. SocketOrChannelAcceptorImpl.createMessageMediator( Broker, + Connection ) +
                          +
                        1. CorbaContactInfoBase.createMessageMediator( Broker, Connection ) + line 130
                        2. +
                        3. MessageBase.readGIOPMessage( orb, connection ) +
                            +
                          1. reads 12 byte GIOP header buf = connection.read( 12, 0, 12 ) + ;
                          2. +
                          3. constructs appropriate Message type
                          4. +
                          5. read size data for message buf = connection.read( buf, 12, + size-12 ) ;
                          6. +
                          7. msg.setByteBuffer( buf ) ;
                          8. +
                        4. +
                        5. byteBuffer = msg.getByteBuffer() ;
                        6. +
                        7. msg.setByteBuffer( null ) ;
                        8. +
                        9. messageMediator = new CorbaMessageMediatorImpl( orb, connection, + msg, byteBuffer )
                        10. +
                      2. +
                      3. After creating the message mediator, we end up going through the + double dispatch and end up in CorbaMessageMediatorImpl.handleInput( + RequestMessage_1_2 ). This calls: +
                          +
                        1. header.unmarshalRequestID
                        2. +
                        3. setInputObject (line 872), which calls + CorbaContactInfoBase.setInputObject(), which creates the CDRInputObject.
                        4. +
                        5. handleRequest(RequestMessage_1_2, CorbaMessageMediator
                        6. +
                        7. beginRequest(messageMediator)
                        8. +
                        9. handleRequestRequest(messageMediator) +
                            +
                          1. This calls unmarshalHeader, then finally does the dispatch. +
                          2. +
                        10. +
                      4. +
                      +

                      Note that we generally always need to call unmarshalRequestID before we + can do much else, since the transport does not know where to put anything + without knowing the request ID (it's obvious from the code that one of GIOP's + minor blunders is not putting the request ID in the GIOP message header, since + it is so frequently needed). Here is a sketch of the code for getMessageData( + byte[][] data ):

                      +
                      +public MessageData getMessageData( byte[][] data )
                      +{
                      +    connection = new BufferedConnectionImpl() ;
                      +    for (int ctr=0; ctr<data.length; ctr++)
                      +        // write data[ctr] to connection
                      +
                      +    final Message[] messages = new Message[data.length] ;
                      +    int requestID = 0 ;
                      +    Message firstMessage = null ;
                      +    Message msg = null ;
                      +    CDRInputObject inobj = null ;
                      +    BufferManagerRead buffman = null ;
                      +
                      +    for (int ctr=0; ctr<data.length; ctr++) {
                      +        msg = MessageBase.readGIOPMessage( orb, connectionCopy ) ;
                      +        messages[ctr] = msg ;
                      +        msg.unmarshalRequestID() ; // Do we always do this?
                      +        // Check that moreFragments == (ctr < data.length)
                      +
                      +        if (ctr==0) {
                      +            // Check that we have a request or reply
                      +            requestID = msg.getRequestID() ;
                      +            firstMessage = msg ;
                      +            requestID = msg.getRequestID() ;
                      +            inobj = new CDRInputObject( orb, connection,
                      +                msg.getByteBuffer(), msg ) ;
                      +            buffman = inobj.getBufferManager() ;
                      +        } else {
                      +            // Check that the request ID is as expected
                      +            buffman.processFragment( msg, msg.getByteBuffer() ) ;
                      +        }
                      +    }
                      +
                      +    // Unmarshal all the data in the first message.  This may 
                      +    // cause other fragments to be read.
                      +    firstMessage.unmarshalHeader( stream ) ;
                      +
                      +    final CDRInputObject resultObj = inobj ;
                      +
                      +    return new MessageData() {
                      +       Message[] getMessages() { return messages ; }
                      +       CDRInputStream getInputStream() { return resultObj ; }
                      +    } ;
                      +}
                      +
                      + + diff --git a/www/design/versioning.html b/www/design/versioning.html new file mode 100644 index 000000000..39c640957 --- /dev/null +++ b/www/design/versioning.html @@ -0,0 +1,673 @@ + + + + + + + + + ORB Versioning + + + + +

                      Versioning

                      +

                      This note discusses the details of how we can introduce a versioning mechanism into the Java ORB for the purpose +of fixing our current interoperability problems. The basic concept is that all ORBs that we have not yet shipped +will include versioning information in every request, response, and IOR. The rest of this note discusses the exact +format of the versioning information and how it can be interpreted to achieve interoperability.

                      +

                      Version Format

                      +

                      I have thought of a number of possibilities for the format of version information:

                      + +
                        +
                      1. single byte (as Ram suggested): I'm not sure we want to make it that limited. +
                      2. 4 bytes: plenty of range, or can do major+minor in the same space. Larger than 1, plus inflexible. +
                      3. string: very flexible encoding, but somewhat longer: typically would add at least 8 bytes, even if short. +
                      4. CDR encapsulation: can put any data type in there, but we would need a version encoding ID, making this too + bulky (this is as big as a tagged component). +
                      5. self-describing sequence of octets. What I mean by this is that bit 7 in each octet is set to 1 if more octets + follow, or 0 if it is the last octet.This is usually as small as case 1, while being completely open ended if we + need to extend it later. Reading this from a CDR stream is simple enough: just keep calling read_byte until a result + >0 is returned. Then the encoding is simply: +
                          +
                        • Last octet: encoding = value +
                        • Not last octet: encoding = value - 128 +
                        +
                      + + +
                      +

                      Note that for a version in the range 0-127, this is exactly the same as option 1. +

                      + +

                      As I stated previously, the reason I am thinking about the format of the version ID is if we need to know something +like JDK version or OS in the version. Perhaps we should allow for this, but it's hard to decide how far to go. +For example, we could represent a version by a string (or an equivalent octet sequence in option 5) in the following +format:

                      +
                         <major ORB version>:<minor ORB version>:<(java.version)>:<(os.name)>:<(os.arch)>:<(os.version>)
                      +

                      where (name) means the result of System.getProperty(name).

                      +

                      Given all of these considerations, I think we should use option 5 for the version ID. All of our ORBs will currently +restrict the version to a single octet in the 0-127 range. The location of this data is discussed in "Object +Key Formats".

                      +

                      We will use exactly the same form for the version in both the object key and in a new service context. The new +service context ID should be allocated in the range 0x4e454f00-0x4e454f0f (see ptc/00-07-06.txt). So, let's just +define another constant TAG_ORB_VERSION = 0x4e454f00 in ORBConstants for this service context tag. This service +context should be present in all GIOP request and reply messages sent by NEW and NEWER ORBs. Its data will consist +solely of a series of octets (no length is needed) encoded as above.

                      +

                      A service context is then encoded using a CDR encapsulation as follows: + + + + + + + + + + + + + + + + + + + + + + +
                      ID (4 bytes)
                      Length (4 bytes)
                      endianness (1 byte)
                      1xxx
                      1xxx
                      ...
                      0xxx
                      +

                      +

                      This is easy to read as follows:

                      + +
                        +
                      1. read the ID +
                      2. read the length +
                      3. read the octet array based on the length +
                      4. create an input stream from the octet array +
                      5. consume the endianness from the new input stream +
                      6. read and accumulate the version until we read a byte > 0 +
                      + +

                      If we attempt to read past the end of the encapsulation, we get a marshaling error.

                      + +

                      For the following discussion, we only need to distinguish the following cases based on the object version:

                      + +

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      ORB Type +

                      +

                      Definition +

                      +

                      Encoding +

                      +

                      Magic +

                      FOREIGNForeign ORB +

                      none +

                      +

                      N/A +

                      OLDOld Sun ORB (JDK 1.2, RMI-IIOP Standard Extension, JDK 1.3, J2EE 1.0, 1.1, 1.2) +

                      1 +

                      +

                      0xAFABCAFE +

                      NEWJDK 1.3.1 ORB +

                      2 +

                      +

                      0xAFABCAFF +

                      NEWERJDK 1.4 or later ORB, including J2EE 1.3 or later. +

                      3 +

                      +

                      0xAFABCB00 +

                      +

                      + +

                      When the version in found in the object key, it defines the version of the ORB that created the IOR. When the +version is found in a service context, it defines the version of the ORB that sent the GIOP request or reply. Note +that the NEW and NEWER ORBs need different MAGIC values, since the object key structure is actually different in +these cases. Also, only NEWER ORBs actually include a version in the object key: the version in the object key +is implicit in the MAGIC value for OLD and NEW ORBs.

                      +

                      Object key formats

                      +

                      The current object key formats are as follows:

                      + +

                      MAGIC = 0xAFABCAFE

                      + +

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      Object Key Type +

                      +

                      Field Name +

                      +

                      Field Type +

                      +

                      JIDL +

                      MAGIClong
                      SCIDlong
                      IDsequence<octet>
                      +

                      POA +

                      MAGIClong
                      SCIDlong
                      SERVERIDlong
                      ORBIDlong
                      POAIDlong
                      IDsequence<octet>
                      +

                      + +

                      Proposed new formats for NEW (JDK 1.3.1) ORB. No versions in the object key because this version has a unique +magic number:

                      + +

                      MAGIC = 0xAFABCAFF

                      + +

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      Object Key Type +

                      +

                      Field Name +

                      +

                      Field Type +

                      +

                      JIDL +

                      MAGIClong
                      SCIDlong
                      IDsequence<octet>
                      +

                      POA +

                      MAGIClong
                      SCIDlong
                      SERVERIDlong
                      ORBIDlong
                      POAIDlong
                      IDsequence<octet>
                      +

                      + +

                      New formats for NEWER (JDK 1.4 and later) ORBs:

                      + +

                      MAGIC = 0xAFABCB00

                      + +

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      Object Key Type +

                      +

                      Field Name +

                      +

                      Field Type +

                      +

                      JIDL +

                      MAGIClong
                      SCIDlong
                      IDsequence<octet>
                      VERSIONn octets
                      +

                      POA +

                      MAGIClong
                      SCIDlong
                      SERVERIDlong
                      ORBIDstring
                      POANAMEsequence<string>
                      IDsequence<octet>
                      VERSIONn octets
                      +

                      + +

                      Note that all of these are marshaled according to CDR rules. Also, note that the previous discussion here about +MAGIC was wrong: we simply MUST change the MAGIC every time any part of the object key structure changes (or else +we need to introduce a new subcontract, but that is actually a larger change, and I do not want to have multiple +versions of the same subcontract that differ only in trivial encoding details.)

                      +

                      Representing the Version

                      +

                      I don't want to expose the exact encoding of versions to all of the code that needs to check the version. Instead, +I would like to define an ORBVersion interface as follows:

                      +
                      public interface ORBVersion {
                      +
                         int FOREIGN = 0 ;
                      +
                         int OLD = 1 ;
                      +
                         int NEW = 2 ;
                      +
                         int NEWER = 3 ;
                      +
                         /** Return the ORB version type.
                      +
                         * Always returns one of the constants defined in this interface
                      +
                         */
                      +
                         int getORBType() ;
                      +
                         /** Write the version to os as a series of properly encoded octets.
                      +
                         void write( OutputStream os ) ;
                      +
                      }
                      +

                      This interface provides all of the version information that we currently need. It can be extended as needed +in the future.

                      +

                      We also need a factory class:

                      +
                      public class ORBVersionFactory {
                      +
                         private ORBVersionFactory() {} 
                      +
                         /** Return the ORB version that this ORB is using.
                      +
                         */
                      +
                         public static ORBVersion getORBVersion() 
                      +
                         { ... }
                      +
                         /** Get the ORB version encoded in the input stream.
                      +
                         */
                      +
                         public static ORBVersion create( InputStream is ) 
                      +
                         { ... }
                      +
                      }
                      +

                      The factory can be efficiently implemented rather easily by pre-allocating 4 instances of an implementation +of ORBVersion. Since the ORBVersion does not need to be mutable, we can just share the pre-allocated instances +as needed. Both of these ORBVersion classes should be identical in Ladybird and Merlin.

                      +

                      The ORB version service context also needs to be supported. To do this, we simply use the ORBVersionFactory +to read the data when the service context is constructed. This simply requires adding a new ORBVersionServiceContext +class to handle the service context.

                      +

                      Getting the ORB version from a GIOP request proceeds something like the following:

                      +
                      if (version service context is present)
                      +
                         get version from service context
                      +
                      else if (request is SUN-1.0 protocol(see interoperability discussion))
                      +
                         version is OLD
                      +
                      else
                      +
                         version is FOREIGN
                      +

                      IOR version implementation

                      +

                      For getting the version from the IOR, we want something like:

                      +

                      ior.getProfile().getVersion()

                      +

                      so that the code using the version is independent of the different representations of IORs in Ladybird and Merlin. +The details of how this is implemented are substantially different in the two code bases.

                      +

                      Implementation in Ladybird

                      +

                      In Ladybird, we will probably implement the versioning by going directly to the object key. We can do this as +follows:

                      + +
                        +
                      1. Get the object key from the IOR profile. +
                      2. Convert the object key byte array into an InputStream. +
                      3. Read off the magic and the scid. +
                      4. Use the scid to determine whether the key is POA or JIDL. +
                      5. read off the rest of the data including the user ID. +
                      6. Hand the object key over to the ORBVersionFactory. +
                      7. return the ORBVersion. +
                      + +

                      I think we will just code this directly in core.Profile in Ladybird and not worry about the fact that too much +of the code knows all about the object key formats. That problem is fixed in Merlin.

                      +

                      Implementation in Merlin/J2EE 1.3

                      +

                      Implementing IOR versioning in Merlin is pretty simple:

                      + +
                      +
                      ObjectKeyTemplate
                      +
                      The basic interface for all object key templates. I will add a ORBVersion getVersion() method on this interface. +
                      ObjectKeyTemplateBase
                      +
                      This abstract class factors out the common parts of the implementation of all object key templates. This is + where getVersion will be implemented. +
                      ObjectKeyFactory
                      +
                      This singleton factory class contains the code that determines what kind of object key template to create based + on the magic and subcontract ids. It needs to be modified to handle two different forms of magic, and also to get + the ORB version if it is present. +
                      + +

                      POAObjectKeyTemplate, JIDLObjectKeyTemplate, and WireObjectKeyTemplate are the three concrete classes that represent +all possible object key templates in our ORB. They should be entirely unaffected by the version related changes.

                      +

                      Interoperability

                      +

                      We need a way to decide upon receiving a GIOP request what kind of ORB sent it. +Since both NEW and NEWER ORBs will always send a Sun protocol version message, those cases are easy. Distinguishing +FOREIGN and OLD is more difficult. The old (and non-standard) GIOP protocol always sent GIOP 1.0 requests with +CodeSet and CodeBase components. Since these two components are not defined for GIOP 1.0, it is unlikely that a +FOREIGN ORB would send such a request. Therefore, we will assume that any such message is from an OLD or NEW ORB, +and NEW can be distinguished based on the version. I will refer to the OLD and NEW ORB protocol as SUN-1.0.

                      +

                      Then we can make everything interoperate across all versions as follows:

                      +

                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      +

                      Invoking ORB +

                      +

                      ORB of IOR +

                      Receiving ORB +

                      Detection Mechanisms +

                      +

                      Protocol +

                      +

                      Serialization +

                      FOREIGNFOREIGNFOREIGN +

                      DON'T' CARE +

                      FOREIGNOLDOLD +

                      DON'T CARE (probably does not interoperate) +

                      FOREIGNNEWNEWServer: GIOP request is not SUN-1.0 +

                      compliant +

                      +

                      compliant +

                      FOREIGNNEWNEWER
                      FOREIGNNEWERNEWER
                      OLDFOREIGNFOREIGN +

                      DON'T CARE (probably does not interoperate) +

                      OLDOLDOLD +

                      currently interoperable +

                      OLDNEWNEWServer: GIOP request is SUN-1.0 +

                      SUN-1.0 +

                      +

                      old +

                      OLDNEWNEWER
                      OLDNEWERNEWER
                      NEWFOREIGNFOREIGNClient: IOR does not contain magic +

                      SUN-1.0 +

                      +

                      compliant +

                      NEWOLDOLDClient: IOR contains old magic +

                      old +

                      NEWNEWNEWClient: IOR contains new magic, NEW version +

                      compliant +

                      NEWNEWNEWERClient: IOR contains new magic, NEW version
                      +
                      + Server: receives target with NEW version
                      NEWNEWERNEWERClient: IOR contains new magic
                      +
                      + Server: receives target with NEWER version
                      NEWERFOREIGNFOREIGNClient: IOR does not contain magic +

                      compliant +

                      +

                      compliant +

                      NEWEROLDOLDClient: IOR contains old magic +

                      SUN-1.0 +

                      +

                      old +

                      NEWERNEWNEWClient: IOR contains new magic, NEW version +

                      SUN-1.0 +

                      +

                      compliant +

                      NEWERNEWNEWERClient: IOR contains new magic, NEW version
                      +
                      + Server: receives target with NEW version
                      +

                      SUN-1.0 +

                      NEWERNEWERNEWERClient: IOR contains new magic, NEWER version
                      +
                      + Server: receives target with NEWER version
                      +

                      compliant +

                      +

                      + +

                      Note that the versioning is complicated by the fact that an ORB supporting a POA may receive requests on persistent +object references that were created by an ORB of an earlier version that supported the POA. We can detect this +by checking the version of the target that was received in the GIOP request, which may be different from the version +of the receiving ORB. We only support backwards compatibility here: it is not always possible to run a persistent +server for an object reference on an ORB whose version is earlier than the version in the object reference. In +particular, a persistent IOR created by a NEWER ORB cannot be served by a NEW ORB. The last two rows in the table +are significant: the protocol accepted by the server is different in these two cases because the client can only +chose the version based on the IOR, not on the actual version of the server. + + + + diff --git a/www/index.html b/www/index.html new file mode 100644 index 000000000..eb12e9ec5 --- /dev/null +++ b/www/index.html @@ -0,0 +1,219 @@ + + + + + + Project Home Page + + + + + + + + +

                      GlassFish-Corba 

                      + + + +

                      This project contains the source code, documentation, and tests for +the CORBA ORB that is used in the GlassFish application server project. + The GlassFish ORB complies with the CORBA 2.3.1 specification, and +with the CORBA 3.0 specifications for the Interoperable Name Service and +Portable Interceptors. It includes both IDL and RMI-IIOP support. The +GlassFish ORB has an open, extensible architecture that supports +flexible configuration and extension through an open SPI. This ORB is +written completely in Java.

                      + + +

                      Special Features of the GlassFish ORB

                      + + +

                      This ORB has a number of special features specifically for GlassFish:

                      + + +
                        + + +
                      1. An optimized, streaming transport for GIOP 1.2 that uses NIO select for scalability.
                      2. + + +
                      3. An implementation of RMI-IIOP that uses runtime bytecode generation to avoid the need for the + rmic compiler for either stubs or skeletons.
                      4. + + +
                      5. An optimized fast object copier to speed up co-located RMI-IIOP calls that require pass-by-value semantics for argument passing.
                      6. + + +
                      7. Highly optimized colocated RMI-IIOP calls that short circuit most of the ORB object adapter and transport code for speed.
                      8. + + +
                      9. The ORB architecture is based in part on the PEPt +work by Harold Carr (a former member of the ORB team), that provides +clean separation between protocol, encoding, presentation, and +transport without impacting performance.
                      10. + + +
                      11. The ORB includes a code generation library (codegen) that +supports runtime generation of classes from a high-level java-like API. +This is currently used to generate the classes needed to support the +remote view for EJB 3.
                      12. + + +
                      13. Support is included for dynamic failover and load balancing of IIOP requests.
                      14. + + +
                      + + +

                      Documentation

                      + + +

                      The ORB documentation is available here (including JavaDocs).

                      + +

                      Getting the source code

                      + +The ORB source code is now managed using Mercurial. +It is hosted at Kenai.com as the GlassFish Version 3 CORBA ORB project. + +

                      There are several source code repositories available at the GlassFish CORBA site on Kenai: +See the sources page for the details. +The repositories are used as follows: +

                        +
                      • GFv3 CORBA Master is the main repository for the GFv3 ORB.
                      • +
                      • GFv3 CORBA Experimental is the repository for GFv3 ORB work that is not ready for integration into the main repository.
                      • +
                      • GFv3 CORBA Staging is the repository used to stage updates to the GFv3 ORB. These changes will be pushed to the master repository after testing using Hudson (which is partially in place, but still needs some work). This repository cannot be viewed; it is for mercurial push operations only.
                      • +
                      • GlassFish v31 ORB contains a copy of the code for the GFv31 ORB (it is not currently the main repository).
                      • +
                      + +

                      The java.net subversion repository contains only the documents in +the www directory, so that the docs can be displayed automatically from +the glassfish-corba project.  This repository also contains the +JavaDocs, which are generated in the build process when synchronizing +the internal and external repositories.

                      + +

                      The intended model for developing GFv3 CORBA is that all changes are pushed first to the staging repository, where they +are tested using Hudson. After the Hudson tests pass, the changes will then be pushed to the master repository, where +they may be checked out and viewed by anyone. However, this is not fully in place yet, and I am still doing direct pushes to +the master repository. +

                      + +

                      Building the Project

                      + + +

                      The simplest thing to do is to use NetBeans:

                      + + +
                        + + +
                      1. Make sure you have NetBeans 6.9.1 or later installed.
                      2. + +
                      3. Select versioning->mercurial->clone other.
                      4. + +
                      5. Type in the URL for the master repository (https://kenai.com/hg/gf-corba-v3-mirror~master).
                      6. + +
                      7. Pick a location to create the local clone.
                      8. + +
                      9. Create a project from the clone (this is also doing the hg clone, which takes a little while).
                      10. + +
                      11. Open the cloned project as the main project.
                      12. + +
                      13. Use NetBeans to build and run tests as desired. Use the +right-click menu on the project to get to the CORBA-specific targets, +such as all of the different test-related targets.
                      14. + + +
                      + +

                      The typical build time should be 30-60 seconds depending on your hardware. The test time is variable, but running all of +the tests should not take more than around 45 minutes.

                      + +

                      More details (and other options) are described here +(pdf) in the ORB documentation.

                      + + +

                      Obtaining ORB builds

                      + +

                      For GlassFish v31, all of the ORB files are contained in the GlassFish appserv-rt.jar +file. You can get this by installing glassfish from the GlassFish downloads. + +

                      The ORB packaging is completely different for GFv3. The ORB is now delivered in several OSGi bundles: +

                        +
                      • glassfish-corba-asm contains the version of ASM that the GFv3 ORB uses. This will eventually migrate to the version used in GFv3 so it can be shared.
                      • +
                      • glassfish-corba-codegen contains the codegen and copyobject libraries, which provide a high-level runtime bytecode generation facility and generic +object copying library (the two have mutual dependencies).
                      • +
                      • glassfish-corba-csiv2-idl contains the idlj-generated Java classes for the CSIv2 IDL definitions.
                      • +
                      • glassfish-corba-dynamicany contains the Dynamic Any code for the ORB (which I'd like to load on demand at some point).
                      • +
                      • glassfish-corba-internal-api contains the ORB FOLB API code. +
                      • glassfish-corba-newtimer contains the ORB timer library.
                      • +
                      • glassfish-corba-omgapi contains the GlassFish-specific versions of a few org.omg.* files.
                      • +
                      • glassfish-corba-orb contains the main part of the ORB code.
                      • +
                      • glassfish-corba-orbgeneric contains the main part of the ORB library (which is independent of the rest of the ORB).
                      • +
                      + +These bundles are available in the Sun Maven 2 repository, with a GroupId of com.sun.corba. The current version is +3.1.0.b027. + +

                      Planned Work

                      + +

                      There are a number of efforts underway right now to improve the ORB following the GF 3.1 release:

                      +
                        +
                      1. Further extend the ORB monitoring Gmbal implementation.
                      2. + +
                      3. Replace most of the ORB transport with Grizzly, +which will include improved CSIv2 (SSL) scalability and improved ORB +connection caching. Most of the Grizzly performance features are +already in the current ORB transport, but moving to a single transport +has many benefits for code quality, integration, and further +optimizations.
                      4. + +
                      5. The encoding performance has been improved for the GlassFish v31 +version of the ORB. This is still in progress, and more details will +appear first in the CORBA blog.
                      6. + +
                      7. Improve the internal code generation library (codegen). Codegen provides a java-level API +for generating classes at runtime. This is used for things like generating the EJB 3 remote view +from a EJB 3 POJO business interface. Planned improvements include: + +
                          +
                        • Extend codegen with more language constructs (e.g. break, continue, switch)
                        • +
                        • Add line number table and local variable table generation for debugging + dynamically generated classes.
                        • +
                        • Complete method overload resolution support.
                        • +
                        • Make the code generator API extensible (e.g. scheme-like macros).
                        • +
                        • Make more extensive use of codegen in the ORB to improve performance.
                        • +
                        • Provide more extensive utilities for generating Proxy-style classes.
                        • +
                        +
                      8. +
                      + +

                      Here are some additional items that we plan to work on (some will only take a few days, +some may take several months):

                      + + +
                        +
                      1. Use TestNG to drive the CORBA test framework, so that we can use TestNG's +parameterization and grouping capabilities to improve our test coverage.
                      2. + +
                      3. Fix redundant IDL and RMIC compilation problems with the tests.
                      4. + +
                      5. Improve the documentation coverage, particularly in the ORB Notes Document.
                      6. + +
                      7. Make more extensive use of the internal ORB timer library to support ORB microbenchmarks as regression tests.
                      8. + + +
                      9. As always, fix bugs.
                      + + + diff --git a/www/procedures.html b/www/procedures.html new file mode 100644 index 000000000..9f8da1465 --- /dev/null +++ b/www/procedures.html @@ -0,0 +1,51 @@ + + + + + + Procedures + + + +

                      Procedures

                      +

                      There is a set procedure that must always be followed for CORBA development. This will evolve +as the GlassFish-CORBA project evolves, so this is simply a first cut at defining the current +development model. Not: this is quite out of date, and needs some updates. +

                      +
                        +
                      1. Discuss the idea for a change to the project on the dev@glassfish-corba.dev.java.net alias. +Make sure to give enough detail that others on the alias can reasonably understand what needs +to be changed, why the change is needed, and roughly what code will be changed.
                      2. +
                      3. Decide what new tests (if any) need to be written for the change. In the case of a +bug, a new test is always required. For a bug, the test must fail without the fix, +and pass with the fix. Any new tests must be integrated into the existing CORBA test framework. +Junit or TestNG can also be used, but they require a simple wrapper to integrate with the +test framework.
                      4. +
                      5. Make the modifications using whatever tools you like. Some of us use emacs or vim, +others use NetBeans, but any choice could be made here.
                      6. +
                      7. Run all of the ORB tests (ant test) and make sure that they all pass. No modifications +will be accepted that cause existing tests to fail.
                      8. +
                      9. Prepare a collection of all differences in modified files. We used to use a Sun +internal tool called webrev that did this for a TeamWare workspace. Now that we are +using CVS, a different tool will be required. As of this writing, I don't have any +specific tool recommendations here, but that will change over time.
                      10. +
                      11. Get the changes reviewed by at least one other team member. We usually prefer to +do this using a telephone call and a shared VNC session, but that may not always be +possible. If necessary, a review could be conducted by email.
                      12. +
                      13. Finally, commit the changes to the CVS repository. This is the usual CVS +repository on java.net at cvs.dev.java.net. Everything in this project is in +the glassfish-corba module.
                      14. + +
                      + + diff --git a/www/schedule.html b/www/schedule.html new file mode 100644 index 000000000..8f34adbc0 --- /dev/null +++ b/www/schedule.html @@ -0,0 +1,85 @@ + + + + + + + CORBA Technologies + + + + + + +

                      CORBA (RMI-IIOP) Schedule

                      +

                      The CORBA schedule is maintained in a pure Java application called +JxProject. JxProject can produce output in a binary form and also in +XML. Harold has written an XSLT script that produces an HTML page +from the JxProject XML file. Ken has written an XQuery program that +was used to re-organize the future items on the schedule according to +release, category, and priority. This version is now the main +schedule. +

                      +

                      To update the schedule: +

                      +
                        +
                      1. Use JxProject to update the + schedule in docs/schedule/schedule.jxp in a CORBA workspace

                        +
                      2. Export the schedule to XML as + schedule.xml +
                      3. Put schedule.jxp and schedule.xml + back to rip-int-generic +
                      4. Run "sh tohtml" in the + docs/schedule directory in rip-int-generic to generate the HTML + version +
                      +

                      The master copy of the schedule is kept in the rip-int-generic +workspace, which is located at +/net/anybodys/export3/ws/rip-int-generic. The schedule is always in +the docs/schedule directory in a CORBA workspace. +

                      +

                      The html version of the schedule can be viewed here +in HTML form. This includes all schedule items for AS 8.2 and 9, and +the Mustang release of J2SE, organized by release, category, and +priority. +

                      +

                      The categories are: +

                      +
                        +
                      • SQ: service quality. This includes + new product features that require ORB support. +
                      • Sec: security. +
                      • MM: Management and Monitoring. +
                      • Maint: maintainability. This + includes features that improve the quality of the ORB in areas such + as test, build, internal code structure, and other non-product + visible items. +
                      • Perf: performance. +
                      +

                      There are 4 priorities with meaning +roughly as follows: +

                      +
                        +
                      • P1: This is required for the + release (release driver in J2SE). +
                      • P2: This is important for the + ORB, but may not make the release if insufficient resources are + available (group driver in J2SE). +
                      • P3: This is nice to have, but may + not make the release (target of opportunity in J2SE). +
                      • P4: An important feature at least for some customers, but we + do not believe that sufficient resources will be available. We will + not even schedule such items. +
                      + +